Compare commits

...

195 Commits

Author SHA1 Message Date
dependabot[bot] 2da23c52cb ci(deps): bump softprops/action-gh-release from 1 to 2
Bumps [softprops/action-gh-release](https://github.com/softprops/action-gh-release) from 1 to 2.
- [Release notes](https://github.com/softprops/action-gh-release/releases)
- [Changelog](https://github.com/softprops/action-gh-release/blob/master/CHANGELOG.md)
- [Commits](https://github.com/softprops/action-gh-release/compare/v1...v2)

---
updated-dependencies:
- dependency-name: softprops/action-gh-release
  dependency-version: '2'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-02-26 18:26:18 +00:00
AndyMik90 60c4890218 Improved prompt for Opus 4.6 2026-02-21 21:34:08 +01:00
AndyMik90 b32b97da51 fix: use PAT_TOKEN for releases to trigger Discord notifications
- release.yml: Use PAT_TOKEN instead of GITHUB_TOKEN for softprops/action-gh-release
  so the published event triggers downstream workflows (Discord notification)
- discord-release.yml: Add workflow_dispatch trigger for manual re-runs

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 12:47:00 +01:00
Andy eb834ca32b Merge pull request #1853 from AndyMik90/fix/qa-validation-stuck-subtasks
fix: resolve QA validation deadlock when subtasks are stuck or failed
2026-02-20 12:00:10 +01:00
Andy ba57005e9b Merge pull request #1847 from AndyMik90/fix/crash-on-spec-path
fix: self-healing for invalid file paths in coder pipeline
2026-02-20 12:00:02 +01:00
Andy 81440514b1 Merge pull request #1836 from AndyMik90/fix/terminal-blank-project-switch
fix(terminal): resolve blank terminals after project switch
2026-02-20 11:59:55 +01:00
AndyMik90 803b231869 merge: resolve pty-manager.ts conflict for PR #1836 - keep exited terminal guard 2026-02-20 11:58:40 +01:00
Andy 4f25bf955d Merge pull request #1834 from AndyMik90/fix/memory-falkordb-to-ladybug
fix(memory): complete FalkorDB to LadybugDB migration in memory system
2026-02-20 11:58:09 +01:00
Andy dd8672c777 Merge pull request #1833 from AndyMik90/fix/kanban-stuck-task
fix: resolve Kanban board stuck task state synchronization
2026-02-20 11:57:59 +01:00
Andy 1ec03a27a4 Merge pull request #1832 from AndyMik90/terminal/improve-worktree-venv
feat: symlink Python venvs in worktrees for instant setup
2026-02-20 11:57:53 +01:00
Andy 2a1d8759b4 Merge pull request #1831 from AndyMik90/feature/webgl-context-management
feat(terminal): integrate WebGL context manager for GPU-accelerated rendering
2026-02-20 11:57:45 +01:00
Andy f2579f0629 Merge pull request #1829 from AndyMik90/auto-claude/225-bulk-delete-and-archive-chat-history
auto-claude: 225-bulk-delete-and-archive-chat-history
2026-02-20 11:57:37 +01:00
AndyMik90 66db171b5e merge: resolve conflicts for PR #1829 - keep both bulk delete/archive and image features 2026-02-20 11:56:22 +01:00
Andy 0de608f0c7 Merge pull request #1821 from AndyMik90/auto-claude/224-add-screenshot-paste-capability-to-chat
auto-claude: 224-add-screenshot-paste-capability-to-chat
2026-02-20 11:54:26 +01:00
Andy a5dfcd09d9 Merge pull request #1820 from AndyMik90/auto-claude/221-refactor-github-pr-review-with-xstate
auto-claude: 221-refactor-github-pr-review-with-xstate
2026-02-20 11:54:18 +01:00
AndyMik90 c8fa9281e5 merge: resolve conflicts in pr-handlers.ts and state-machines/index.ts for PR #1820 2026-02-20 11:53:07 +01:00
Andy 1e455da508 Merge pull request #1819 from AndyMik90/auto-claude/229-implement-account-aware-terminal-session-persisten
auto-claude: 229-implement-account-aware-terminal-session-persisten
2026-02-20 11:52:21 +01:00
AndyMik90 867e2e4e45 merge: resolve state-machines/index.ts conflict - keep both terminal and roadmap exports 2026-02-20 11:51:07 +01:00
Andy e9ca60fa02 Merge pull request #1818 from AndyMik90/auto-claude/227-fix-mark-as-done-on-task-modal
auto-claude: 227-fix-mark-as-done-on-task-modal
2026-02-20 11:50:30 +01:00
Andy 7539a2d4e6 Merge pull request #1817 from AndyMik90/auto-claude/226-add-archive-button-to-done-tasks
auto-claude: 226-add-archive-button-to-done-tasks
2026-02-20 11:50:21 +01:00
Andy 2d7e3cbed1 Merge pull request #1816 from AndyMik90/auto-claude/223-remove-deprecated-taskstatemachine-class
auto-claude: 223-remove-deprecated-taskstatemachine-class
2026-02-20 11:50:15 +01:00
Andy 0474238bf5 Merge pull request #1815 from AndyMik90/auto-claude/222-refactor-roadmap-tasks-with-xstate
auto-claude: 222-refactor-roadmap-tasks-with-xstate
2026-02-20 11:50:09 +01:00
Andy 3f03cef7ee Merge pull request #1814 from AndyMik90/auto-claude/220-add-manual-competitor-functionality-in-roadmap
auto-claude: 220-add-manual-competitor-functionality-in-roadmap
2026-02-20 11:49:52 +01:00
AndyMik90 4bb3d658d0 fix: address PR #1829 review findings in ChatHistorySidebar and paths
- Fix i18n: replace non-existent t('actions.cancel') with t('buttons.cancel')
  in all three AlertDialog cancel buttons (single delete, bulk delete, bulk archive)
- Fix WCAG: add aria-hidden and tabIndex={-1} to decorative inner Checkbox
  to eliminate nested checkbox role violation in selection mode
- Fix: move setBulkDeleteOpen/setBulkArchiveOpen to finally blocks so dialogs
  always close regardless of success or failure in bulk handlers
- Fix: remove unsanitized sessionId from validateSessionId error message
  to prevent leaking raw input in error output (paths.ts)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:07:03 +01:00
AndyMik90 f47091588a fix: resolve all PR #1829 review findings in ChatHistorySidebar
- Finding 1 (MEDIUM): Add AlertDialog confirmation before bulk archive
  executes, using existing archiveConfirmDescription i18n key
- Finding 2 (MEDIUM): Replace hardcoded Today/Yesterday/X days ago with
  i18n keys insights.today, insights.yesterday, insights.daysAgo
- Finding 3 (MEDIUM): Always set tabIndex={0} so items remain keyboard
  accessible when isSelectionMode is true (role=checkbox requires it)
- Finding 4 (LOW): Archive/unarchive callbacks already propagate errors;
  no silent swallowing present in current code
- Finding 5 (LOW): Replace hardcoded message/messages ternary with
  insights.messageCount pluralization via i18n count interpolation
- Finding 6 (LOW): Single-delete dialog now uses dedicated
  insights.deleteTitle and insights.deleteDescription keys instead of
  reusing bulk delete keys with count: 1

Add i18n keys to both en/common.json and fr/common.json:
  archiveConfirmTitle, archiveConfirmButton, deleteTitle,
  deleteDescription, today, yesterday, daysAgo, messageCount,
  messageCount_other

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 7ee20e0e44 fix: resolve PR review findings for session storage error handling
- Move getSessionPath() inside try/catch in loadSessionById and deleteSession
  so validateSessionId exceptions are caught (FU2-001, FU2-004)
- Add try/catch with logging to saveSession to prevent unhandled I/O throws
  (FU2-005)
- Use session.updatedAt instead of new Date() in updateSessionModelConfig
  cache update to keep timestamps consistent (FU2-002)
- Remove swallowing .catch() on archive/unarchive callbacks so errors
  propagate to parent handlers in Insights.tsx (FU2-006)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 fd9032ab99 fix: resolve archive filter loss and session cache bugs in insights
- Add showArchived field to insights Zustand store so all callers
  (including event listeners) can access it without parameter threading
- loadInsightsSessions now falls back to store.showArchived when no
  explicit parameter is passed, fixing newSession, renameSession,
  updateModelConfig, and the onInsightsSessionUpdated listener
- Add in-memory cache update to SessionManager.renameSession matching
  the pattern used by updateSessionModelConfig
- Add input validation for bulk delete/archive IPC handlers

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 7e869650d6 fix: pass archive filter through loadInsightsSession to prevent overwrite
- Add includeArchived parameter to loadInsightsSession and propagate to
  loadInsightsSessions, deleteSession, and clearSession
- Update all callers in Insights.tsx to pass showArchived through
- Remove projectId from showArchived effect deps to prevent duplicate
  loads on project switch (mount effect already handles it)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 42372141ec fix: address PR review findings for bulk delete/archive chat history
- Return success:false from IPC handlers when bulk operations have failures
- Propagate failedIds through store functions for proper error reporting
- Add session ID validation in paths.ts to prevent path traversal
- Prune selectedIds when sessions list changes to avoid stale selections
- Fix isFirstRun race condition when projectId changes in Insights
- Convert archivedAt to Date in loadSessionById for type consistency
- Fix accessibility: conditional tabIndex based on selection mode

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 d76368e1b9 fix: address all new PR review findings for bulk delete/archive functionality
Comprehensive fixes addressing 4 critical and accessibility issues:

**Critical Bug Fixes:**
1. Fixed UI state mismatch when active session is archived/deleted
   - Added loadInsightsSession() call after bulk operations
   - Ensures frontend stays in sync when backend auto-switches sessions

2. Fixed race condition causing flicker on projectId change
   - Added prevProjectId ref to reset skip flag per-projectId
   - Prevents duplicate loadInsightsSessions calls when showArchived is true

3. Added comprehensive error handling to all bulk handlers
   - Wrapped all async operations in try/catch blocks
   - Added detailed error logging with session IDs and context
   - Prevents unhandled promise rejections from IPC failures

**Accessibility Improvements:**
4. Fixed selection mode accessibility in SessionItem
   - Removed redundant checkbox onCheckedChange to prevent double-toggle
   - Made parent row fully interactive with role="checkbox" in selection mode
   - Added aria-checked attribute for screen reader support
   - Wired row onClick and keyboard handlers to toggle selection
   - Users can now activate selection via row click/keyboard or nested checkbox

All changes maintain backward compatibility and improve robustness.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 02b40fa342 fix: address all PR review findings for bulk delete/archive functionality
Comprehensive code quality improvements addressing all review comments:

**Critical Fixes:**
- Fixed double-toggle bug where checkbox called onToggleSelect twice
- Added accessibility attributes (role, tabIndex, onKeyDown) to interactive div

**Error Handling:**
- Removed error re-throws in async event handlers to prevent unhandled rejections
- Added error logging to empty catch blocks in session-storage.ts
- Added error handling with .catch() for dropdown menu promise rejections
- Added logging for partial failures in bulk operations

**Code Quality:**
- Replaced non-null assertion (!) with explicit null check in session-manager.ts
- Removed redundant async/await wrappers in archive/unarchive handlers
- Removed duplicate loadInsightsSession calls from store functions
- Added skip-first-run guard to prevent double load on component mount
- Added clarifying comment for showArchived useEffect dependency

**Performance:**
- Eliminated redundant IPC calls by removing duplicate session reloads
- Fixed flicker issue caused by double reload with different filters

All changes maintain backward compatibility and improve user experience.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 9f3ac54844 fix: properly await async bulk operations in ChatHistorySidebar
Fixed fire-and-forget async operations that were clearing UI state
before operations completed. Changes:

- Updated prop types to return Promise<void> for async callbacks
- Made handleBulkDelete and handleBulkArchive async functions
- Added await for all async callback invocations
- Added try/catch error handling with console logging
- Updated SessionItem prop types for onArchive/onUnarchive
- Made single archive/unarchive arrow functions async

This ensures UI state is only cleared after operations complete
successfully and prevents unhandled promise rejections.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 e547e96e26 fix: pass showArchived flag when reloading sessions after bulk operations (qa-requested)
Make handleArchiveSession, handleUnarchiveSession, handleDeleteSessions,
and handleArchiveSessions async, await store calls, then reload sessions
with showArchived flag to preserve archived session visibility.

QA Fix Session: 2
2026-02-18 15:05:54 +01:00
AndyMik90 2d9911cd21 auto-claude: subtask-5-3 - Update Insights.tsx to wire new ChatHistorySidebar props
Add showArchived state, import bulk store helpers (deleteSessions, archiveSession,
archiveSessions, unarchiveSession), create handler functions, add useEffect to
reload sessions when showArchived changes, and pass all new props to ChatHistorySidebar.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 0f952a7b96 auto-claude: subtask-5-2 - Add selection mode, bulk actions, and archive support to ChatHistorySidebar
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 1e44a909c1 auto-claude: subtask-5-1 - Add i18n translation keys for chat history bulk delete and archive
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 0bf75d1b67 auto-claude: subtask-4-1 - Add bulk delete/archive helper functions to insights-store
Add deleteSessions, archiveSession, archiveSessions, unarchiveSession helpers
and update loadInsightsSessions to accept optional includeArchived parameter.
Also update ElectronAPI types and browser mocks for new methods.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 4198bde687 auto-claude: subtask-3-3 - Extend preload InsightsAPI with bulk delete/archive methods
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 60b8a77d69 auto-claude: subtask-3-2 - Register new IPC handlers in insights-handlers.ts
Add handlers for bulk delete, archive, bulk archive, and unarchive
sessions. Update list sessions handler to accept includeArchived param.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 ffad4fc53d auto-claude: subtask-3-1 - Add delegation methods to InsightsService
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 c3a927ae54 auto-claude: subtask-2-2 - Add archive/unarchive/bulk methods to SessionManager
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 9626ba42a2 auto-claude: subtask-2-1 - Add archive/unarchive/bulk methods to SessionStorage
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 1c2918fe0b auto-claude: subtask-1-2 - Add new IPC channel constants for bulk delete and archive
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 2f43b2af24 auto-claude: subtask-1-1 - Add archivedAt optional field to InsightsSession and InsightsSessionSummary
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
Andy 40364a016d Merge branch 'develop' into auto-claude/222-refactor-roadmap-tasks-with-xstate 2026-02-18 14:49:16 +01:00
AndyMik90 4349963f39 fix: address PR #1815 review findings for roadmap XState refactor
- Remove redundant conditional in setGenerationStatus (NEW-001)
- Add comprehensive test coverage for catch-up logic (NEW-002)
- Pass persisted context to getOrCreateGenerationActor on reload (CMT-001)
- Add reverse-direction assertions for state name arrays (FNEW-003)
- Fix stale line reference in comment (NEW-003)
- Use precise no-op guard in updateFeatureLinkedSpec (NEW-004)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 10:23:06 +01:00
AndyMik90 6c69e71a76 fix: resolve 3 remaining PR #1815 issues
- Add vite/client types reference to fix import.meta.hot TS errors
- Add unit tests for mapGenerationStateToPhase/mapFeatureStateToStatus
  ensuring all machine states map correctly without silent fallthrough
- Restore persisted state in getOrCreateGenerationActor matching the
  feature actor pattern with resolveState()

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 09:49:49 +01:00
AndyMik90 7f7e845cd5 fix: resolve 3 remaining PR #1819 review issues
- Preserve 'exited' status in setClaudeMode(false) instead of overwriting to 'running'
- Add isResumingPhase guard to SWAP_RESUME_COMPLETE for consistency with other swap events
- Clean up stale migratedSessionFlags when resumeClaudeAsync finds no terminal

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 09:49:35 +01:00
AndyMik90 6f9a24176d fix: remove vacuous if/else guard in graphiti status test
Replace conditional assertions with direct assertions since
sys.modules patching deterministically makes available=True.
The else-branch was dead code with a trivially-passing assertion.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 09:48:29 +01:00
AndyMik90 7fb9b10bcd fix: address PR review findings for XState roadmap refactor
- Add catch-up logic for 'error' phase in setGenerationStatus so
  GENERATION_ERROR is not silently dropped when actor is in idle/complete
- Fix progress updates being dropped for empty string message by using
  !== undefined instead of truthy check on status.message
- Improve compile-time assertion comments explaining both-direction sync
  enforcement strategy (forward via type assertion, reverse via switch
  exhaustiveness in map functions)
- Replace unnecessary dynamic import of resetActors in test afterEach
  with static import
- Document that backward transitions are intentionally unsupported in
  the forward-only generation pipeline

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:38:18 +01:00
AndyMik90 faf6148f82 fix: use setClaudeMode instead of updateTerminal in onTerminalExit to prevent XState divergence
The onTerminalExit handler used store.updateTerminal() to reset isClaudeMode,
which is a plain Zustand setter that bypasses XState notification. Replace with
store.setClaudeMode() which properly checks XState state before sending events.

Since setTerminalStatus('exited') already sends SHELL_EXITED to XState (handling
the claude_active -> exited transition), the setClaudeMode(false) call here only
updates Zustand - its XState guard correctly skips sending CLAUDE_EXITED since
the machine is already in 'exited' state.

Fixes: NCR-R7-001 (HIGH) - Claude exit via updateTerminal bypasses XState machine

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:36:55 +01:00
AndyMik90 8e86bd60ae fix: address PR review findings for image pipeline
- Add defense-in-depth count and size validation in InsightsExecutor
  (NEW-005)
- Make image analysis unsupported warning more prominent with icon and
  background styling (REVIEW-001/CMT-001)
- Add inline notice on sent messages that images were not analyzed
  (CMT-001)
- Add i18n keys for image not-analyzed notice (en + fr)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:36:31 +01:00
AndyMik90 9e06b15d3d fix: address PR #1847 review findings
- Reuse SKIP_DIRS from context.constants instead of duplicating exclusion list
- Fix exception types in write error handlers (TypeError/ValueError, not JSONDecodeError)
- Add warning log when path validation bypassed due to exhausted retries
- Use existing safeReadFileSync helper for attempt_history reads

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:35:33 +01:00
AndyMik90 3bf5a1f0c3 fix: use write_json_atomic for implementation_plan.json in recovery
Replace raw json.dump with write_json_atomic when writing
implementation_plan.json in mark_subtask_stuck() to prevent file
corruption, consistent with 8+ other call sites in the codebase.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:34:26 +01:00
AndyMik90 04d141f6be fix: make test_get_graphiti_status_invalid_config_sets_reason environment-independent
Avoid hard-asserting status['available'] is True, which depends on
sys.modules patching behavior. Instead check the key exists and branch
on its value, consistent with neighboring tests in the same class.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:34:24 +01:00
AndyMik90 9334b71da8 fix: cancel fallback timer in all task restart paths
The fallback safety net timer was only cancelled in the TASK_START handler,
but not in the TASK_UPDATE_STATUS auto-start path or TASK_RECOVER_STUCK
auto-restart path. This meant a stale timer could incorrectly stop a
newly restarted task if it was restarted within the 500ms window via
drag-to-in-progress or recovery auto-restart.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:34:01 +01:00
AndyMik90 4cb0a14aa7 fix: add debug log for venv fallback success in worktree setup
Add missing debug log when venv symlink health check fails and the
recreate fallback succeeds, matching the Python backend's behavior
for consistent debug output.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:33:51 +01:00
AndyMik90 04618ccb08 fix: move debug log after delete to fix off-by-one count in cleanup timer
The cleanup timer debug log was computing pendingDelete.size - 1 before
the actual delete call, logging an incorrect remaining count. Moved both
delete calls before the debug log so it reports the accurate size.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:33:42 +01:00
AndyMik90 db4cd7d2da fix: extract stuck-subtask loader, use actual_output for stuck notes
- Extract duplicated stuck-subtask loading into _load_stuck_subtask_ids()
- Write stuck reason to actual_output instead of notes field for
  consistency with the QA reviewer's expectations
- Clarify progress message to mention terminal states (completed/failed/stuck)
- Update test assertions to match actual_output field

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:33:06 +01:00
AndyMik90 1f60699f38 fix: resolve QA validation deadlock when subtasks are stuck or failed
When a coding agent marks a subtask as "stuck", QA validation would never
start because is_build_complete() requires ALL subtasks to have status
"completed". This creates a deadlock: coder exits (no more subtasks to
work on), but QA never triggers.

Changes:
- Add is_build_ready_for_qa() that considers builds ready when all
  subtasks reach a terminal state (completed, failed, or stuck)
- Update mark_subtask_stuck() to also set status="failed" in
  implementation_plan.json, keeping plan file in sync with reality
- Reorder QA loop to check human feedback before build completeness,
  so QA_FIX_REQUEST.md bypasses the build gate as intended
- Replace is_build_complete() with is_build_ready_for_qa() in
  should_run_qa() and CLI qa commands
- Add 20 new tests covering is_build_ready_for_qa() edge cases and
  mark_subtask_stuck() plan update behavior

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:33:06 +01:00
AndyMik90 c2b287c02c refactor: extract scoring logic, use indexed lookup in auto-correct
- Extract _score_and_select() from duplicated candidate scoring blocks
- Use _find_correct_path_indexed() in _auto_correct_subtask_files()
  with a shared file index built once for all missing files
- Use find_subtask_in_plan() helper instead of inline nested loop
- Add more dirs to _EXCLUDE_DIRS (.idea, .vscode, vendor, target, out)
- Narrow exception handlers from (OSError, JSONDecodeError) to OSError
  for write_json_atomic (JSON errors can't occur on write)
- Fix type annotation for missing_entries list

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:59 +01:00
AndyMik90 4a8c94538c feat: implement fuzzy file path matching and indexing for self-healing in coder pipeline
- Add functions for building a file index, finding correct paths using fuzzy matching, and auto-correcting subtask file paths.
- Introduce directory exclusion logic to optimize file searching.
- Enhance validation of file paths in implementation plans to support better error recovery.
- Add comprehensive tests for the new functionalities, covering various matching scenarios and edge cases.

This update improves the robustness of the coder pipeline by enabling it to automatically correct file paths based on existing project structure, thus enhancing overall stability and user experience.
2026-02-17 15:32:58 +01:00
AndyMik90 36b3b29d9e test: add coverage for missing graph backend scenario
Add test_get_graphiti_status_no_graph_backend to verify error handling when
graphiti_core imports successfully but neither real_ladybug nor kuzu are
available. This addresses CodeRabbit's recommendation to test the error path
in config.py lines 645-650.

Addresses CodeRabbit review comment on PR #1834.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:56 +01:00
AndyMik90 e61f4370a8 fix: address review findings for PR #1834
- Add nested try-except in config.py for clearer error messages when graph DB backend is missing
- Mock imports in test_config.py to make test environment-independent
- Ensure test passes regardless of whether graphiti_core/real_ladybug/kuzu are installed

Resolves CodeRabbit and Gemini review comments on PR #1834.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:56 +01:00
AndyMik90 aaa3b7f588 fix: remove stale FalkorDB references from migration cleanup
- Remove FalkorDB docker service reference from project_index.json (docker-compose.yml no longer exists)
- Correct line number reference in test_config.py comment (line 644 not 641)

Code review findings - no functional changes, just metadata cleanup.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:56 +01:00
AndyMik90 b7739a4794 fix(memory): complete FalkorDB → LadybugDB migration in memory system
## Problem
The memory system was still checking for FalkorDB imports in `config.py`,
causing it to always report as unavailable and fall back to file-based
storage, despite LadybugDB being the configured and installed database.

Error in logs:
```
Graphiti packages not installed: falkordb is required for FalkorDri...
```

## Root Cause
In `get_graphiti_status()` at line 638, the code tried to import:
```python
from graphiti_core.driver.falkordb_driver import FalkorDriver
```
This import failed because FalkorDB was removed when migrating to LadybugDB.

## Changes Made

### Priority 1 — Critical Bug Fix
**File**: `apps/backend/integrations/graphiti/config.py` (lines 634-646)
- Replaced FalkorDB import check with LadybugDB/kuzu import check
- Now tries `real_ladybug` first (Python 3.12+), falls back to `kuzu`
- Removed unreachable pragma: no cover comment (line now executes)

### Priority 2 — Test Infrastructure Updates
1. **`conftest.py`** (lines 84-103)
   - Renamed fixture: `mock_falkor_driver` → `mock_kuzu_driver`
   - Updated docstring and patch path to reference KuzuDriver

2. **`test_config.py`** (lines 1056-1070, 1092-1094)
   - Updated test to reflect new behavior: `available=True` when packages
     installed, even with embedder validation errors (embedder is optional)
   - Updated comment from "falkordb" to "LadybugDB/kuzu"

3. **`test_memory.py`** (lines 267, 278)
   - Updated variable name: `mock_falkordb_driver` → `mock_kuzu_driver`
   - Updated sys.modules patch path to use kuzu_driver instead of falkordb_driver

### Priority 3 — Documentation Updates
4. **`test_memory_facade.py`** (line 163)
   - Updated comment: "remote FalkorDB" → "remote database"

5. **`spec_runner.py`** (line 139)
   - Updated example: "FalkorDB" → "LadybugDB"

## Testing
All 670 graphiti tests pass:
```
apps/backend/.venv/bin/pytest apps/backend/integrations/graphiti/tests/ -v
========== 670 passed, 6 skipped, 112 deselected, 4 warnings in 2.10s ==========
```

## Impact
- Memory system now correctly detects LadybugDB as available
- No more false negatives causing fallback to file-based storage
- All existing functionality preserved
- No breaking changes

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:56 +01:00
AndyMik90 92a3c821ed fix: address all auto-claude review findings for PR #1833
Fixed all 3 findings from the latest auto-claude review:

1. [NCR-NEW-001] MEDIUM: Fallback safety net timeout race condition
   - Store setTimeout timer reference in a Map keyed by taskId
   - Export cancelFallbackTimer() function to clear pending timers
   - Call cancelFallbackTimer() at start of TASK_START handler
   - Prevents stale timer from incorrectly stopping newly restarted tasks
   - Clean up timer reference after it fires

2. [CMT-NEW-001] LOW: Duplicate hasPlan detection logic
   - Replace inline hasPlan logic in execution-handlers.ts TASK_STOP
   - Use shared hasPlanWithSubtasks() utility from plan-file-utils.ts
   - Eliminates code duplication and ensures consistent behavior

3. [CMT-001] LOW: Misleading async keyword
   - Remove async from setTimeout callback in agent-events-handlers.ts
   - No await expressions exist in the callback
   - All operations (getCurrentState, hasPlanWithSubtasks) are synchronous

All changes maintain backward compatibility and fix the race condition
where restarting a task within 500ms could be incorrectly stopped by
the fallback timer from the previous process exit.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:51 +01:00
AndyMik90 3628fba7f3 refactor: address all PR review findings for code quality
- Extract hasPlan logic into shared hasPlanWithSubtasks() utility in plan-file-utils.ts
  to eliminate duplication and centralize plan validation logic
- Make setTimeout callback async to avoid blocking readFileSync in event loop
- Replace hardcoded terminal status check with cleaner .includes() pattern
- Add status gate for final phase updates to prevent UI flicker when failed
  phase arrives after task has transitioned to human_review
- Import and use hasPlanWithSubtasks in agent-events-handlers.ts

All review comments addressed:
- Gemini: Critical/Medium - forceTransition method, magic number (already fixed in previous commit)
- Gemini: Medium - hardcoded status list (now uses .includes)
- CodeRabbit: Trivial - extract XSTATE_ACTIVE_STATES (already fixed in previous commit)
- CodeRabbit: Minor - derive hasPlan from file check (now uses shared utility)
- CodeRabbit: Minor - prevent UI flicker from final phase updates (now gates on status)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:51 +01:00
AndyMik90 b098d0d703 fix: address follow-up review findings - dynamic hasPlan and shared constants
Resolves NEW-001 and CMT-001 from the follow-up review:
- Extract XSTATE_ACTIVE_STATES to shared constant in task-state-utils.ts
- Export XSTATE_ACTIVE_STATES from state-machines index
- Replace hardcoded hasPlan: true with dynamic plan file check
- Pattern matches TASK_STOP handler (execution-handlers.ts lines 299-310)
- Tasks stuck in 'planning' state now correctly route to backlog, not human_review
- Improved logging shows hasPlan value for debugging

This ensures the fallback safety net routes tasks to the correct Kanban column
based on whether a plan file exists with subtasks.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:51 +01:00
AndyMik90 4c00536dc5 fix: address all review findings for PR #1833
- Add named constant STUCK_TASK_FALLBACK_TIMEOUT_MS for magic number
- Use XState getCurrentState() instead of cached task status to avoid stale cache issues
- Check XState active states directly (planning, coding, qa_review, qa_fixing)
- Improve logging to show actual XState state name
- Add inline comments explaining the stale cache avoidance strategy

This resolves all 3 blocking issues from the Auto Claude review:
1. CRITICAL: forceTransition() method - fixed by using handleUiEvent()
2. MEDIUM: Stale closure - fixed by checking XState directly
3. MEDIUM: Magic number - fixed by using named constant

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:51 +01:00
AndyMik90 cb8ed52eca fix: correct fallback timeout to use existing TaskStateManager API
The 500ms fallback safety net was calling `taskStateManager.forceTransition()`
which doesn't exist, causing TypeScript compilation errors.

Fixed to:
- Use `handleUiEvent()` with `USER_STOPPED` event (proper XState transition)
- Look up both task and project fresh (avoid stale closure references)
- Add null check for `checkProject` before proceeding

This ensures the fallback actually works when XState fails to transition
tasks out of in_progress after process exit.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:51 +01:00
AndyMik90 4286152f42 fix: resolve Kanban board stuck task state synchronization
When an agent process exits with incomplete/stuck subtasks, the task gets
stuck in the Kanban UI — it spins forever, can't be stopped, and can't be
dragged back to planning.

This fix addresses 5 specific state synchronization gaps between the backend
process lifecycle and the frontend XState state machine:

1. Reset execution progress on terminal state transitions (task-store.ts)
   - When tasks reach terminal states (human_review, error, done, pr_created),
     execution progress is now reset to idle
   - Prevents stuck tasks from showing stale progress indicators in UI

2. Propagate final phase updates even after XState settles (agent-events-handlers.ts)
   - Final 'complete' or 'failed' phase updates are now sent to renderer
   - Previously these were silently dropped, causing UI to never show completion

3. Add fallback exit handler to force state transition (agent-events-handlers.ts)
   - If task remains in_progress 500ms after process exit, force to human_review
   - Safety net for when XState fails to properly handle PROCESS_EXITED event

4. Disable dragging for in_progress tasks (SortableTaskCard.tsx)
   - Prevents users from dragging tasks that are currently running or stuck
   - Adds disabled flag to useSortable hook when status is 'in_progress'

5. Allow stop button for stuck tasks (TaskCard.tsx)
   - Users can now force-stop stuck tasks using the stop button
   - Removed the isStuck check that prevented stopping stuck tasks

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:51 +01:00
AndyMik90 95f32f914e fix: address PR #1832 review findings for worktree venv improvements
- Initialize performed=False as safer default matching TypeScript impl
- Fix _popen_with_cleanup docstring to accurately describe timeout behavior
- Replace lstatSync with isSymlinkOrJunction for consistency
- Add debug log when venv fallback to recreate occurs
- Use existing venvPath variable instead of reconstructing path
- Remove broken symlinks before returning false to allow fresh creation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:50 +01:00
AndyMik90 84184fafb5 fix: address all 4 findings from auto-claude PR review
Fixes all issues from 2026-02-16 auto-claude review:

- [HIGH] NEW-001: Fix KeyError when venv symlink falls back to recreate
  strategy by ensuring results dict has the 'recreate' key before appending
- [MEDIUM] NEW-002: Fix isSymlinkOrJunction to detect Windows junctions by
  using readlinkSync instead of lstatSync().isSymbolicLink()
- [LOW] NEW-003: Add finally block to _popen_with_cleanup to prevent
  resource leaks by ensuring pipes are closed and process is reaped
- [LOW] CMT-002: Remove redundant symlink_path variable and reuse venv_path

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:50 +01:00
AndyMik90 1d4b749d55 fix: address all PR review findings for venv health check and fallback logic
Backend fixes:
- Detect broken symlinks in _apply_recreate_strategy using is_symlink()
- Add OSError catch in venv creation block for missing python_exec
- Update strategy_name to 'recreate' when health check triggers fallback
- Log marker write failures via debug_warning instead of silent pass
- Update DependencyStrategy docstring to reflect symlink-first approach

Frontend fixes:
- Decouple health check from 'performed' flag - run on any existing venv
- Add isSymlinkOrJunction() helper for broken symlink detection
- Detect broken symlinks in applyRecreateStrategy before existsSync check
- Log marker write failures instead of silent catch

All blocking and medium-severity review findings addressed:
- [NCR-001/CMT-001] Frontend health check now runs on re-runs
- [NCR-003] Backend recreate detects broken symlinks
- [NCR-005] Frontend recreate detects broken symlinks
- [NEW-002] Strategy name correctly updated on fallback
- [NCR-004] OSError handling added to venv creation
- [NEW-003] DependencyStrategy docstring updated
- Marker write failures now logged for debugging

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:50 +01:00
AndyMik90 836cc385b3 fix: address medium-severity PR review findings
- Fix potential deadlock in _popen_with_cleanup by using proc.communicate() instead of proc.wait() to drain pipes after terminate/kill
- Fix health check skip on re-runs by decoupling health check from 'performed' flag - now runs whenever venv symlink exists, detecting broken source venvs between runs

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:50 +01:00
AndyMik90 814cf763f8 fix: address follow-up review findings for PR #1832
- Wrap symlink removal in try/except in Python health check fallback to prevent PermissionError from skipping recreate strategy
- Add recursive: true flag to TypeScript rmSync call for consistent Windows junction handling

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:50 +01:00
AndyMik90 3ede3ec2a8 feat: symlink Python venvs in worktrees for instant setup
Switch venv strategy from RECREATE to SYMLINK so worktree creation is
near-instant (matching node_modules behavior). A health check after
symlinking verifies the venv is usable; if it fails, falls back to
recreate with improved robustness:

- Marker-based completion tracking (.setup_complete) detects incomplete venvs
- Popen-based subprocess management with proper terminate/kill on timeout
- Increased pip install timeout from 120s to 300s

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:50 +01:00
AndyMik90 e17137e937 fix: address PR #1831 review findings for webgl-context-management
- Remove unused fireEvent import from DisplaySettings test
- Add i18n helper text below GPU acceleration dropdown (en/fr)
- Replace positional selectCallbacks array with Map keyed by Select id
- Move debugLog after delete in terminal-session-store cleanup timer
- Remove redundant hasExited guard in pty-manager synchronous write path

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:44 +01:00
AndyMik90 9e276c4757 fix(logging): enhance error handling in app-logger and terminal processes
- Introduced safe logging functions to prevent crashes from console write failures and unhandled errors.
- Updated error logging setup to use safeLogUnhandled for uncaught exceptions and unhandled rejections.
- Added guards in terminal process management to avoid operations on exited PTYs, preventing potential crashes.
- Improved WebGL context management in terminal rendering to ensure stability during GPU acceleration.

This commit aims to enhance the robustness of the logging and terminal handling mechanisms, addressing potential crash scenarios and improving overall application stability.
2026-02-17 15:32:44 +01:00
AndyMik90 d745aee48d fix(terminal): resolve pendingDelete race and save contention causing crashes
Two bugs in terminal session persistence caused crashes when terminals
were destroyed and recreated with the same ID:

1. pendingDelete blocked legitimate terminal recreation: When a terminal
   exits and is recreated (worktree switch, shell restart), the 5-second
   pendingDelete window silently blocked all session saves for the new
   terminal, leaving it invisible to the session store. Added
   clearPendingDelete() to remove the guard when createTerminal() is
   called with a reused ID.

2. Sync save() and async saveAsync() raced on the same temp file: Both
   methods wrote to terminals.json.tmp without coordination, causing
   ENOENT errors when one renamed a file the other had already moved.
   save() now checks writeInProgress and defers to the async writer
   when a write is in-flight.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:44 +01:00
AndyMik90 5495e6564e fix(terminal): wrap WebGL calls in try-catch and add crash diagnostics
The WebGL register/acquire/unregister calls in useXterm were not wrapped
in try-catch, meaning any failure during WebGL context acquisition
(e.g., LRU eviction edge case, GPU memory pressure) would propagate as
an uncaught exception and crash the renderer process.

Also adds debug logging to terminal-session-store's pendingDelete
mechanism to help diagnose a reported crash when spawning terminals
after extended use with 5+ concurrent instances. The "Skipping save
for deleted session" warning now includes the full pendingDelete state.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:44 +01:00
AndyMik90 f399cd8ce2 feat(terminal): integrate WebGL context manager for GPU-accelerated rendering
Wire up the existing webgl-context-manager into the terminal rendering
pipeline with a user-configurable GPU Acceleration setting (auto/on/off).
WebGL gives 3-5x rendering performance for terminals while falling back
gracefully on unsupported browsers (Safari, some Linux+NVIDIA setups).

- Add GpuAcceleration type and gpuAcceleration field to AppSettings
- Add GPU Acceleration dropdown in Display Settings (i18n: en + fr)
- Register/acquire WebGL context after xterm.open(), unregister on dispose
- Respect user setting: 'off' skips WebGL, 'auto'/'on' acquires context
- Add 13 tests covering WebGL lifecycle and DisplaySettings GPU dropdown

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:43 +01:00
AndyMik90 2b8e2af233 fix: address PR #1821 review findings for screenshot paste capability
- Add image count guard (MAX_IMAGES_PER_TASK) in insights-service.ts
- Add count check to handleScreenshotCapture before processing
- Filter out images without displayable source in MessageBubble
- Remove dead content_blocks code in insights_runner.py (SDK limitation)
- Add visible UI warning when images attached but analysis unsupported
- Align backend MAX_IMAGE_FILE_SIZE to 10MB to match frontend
- Swap path validation order: check is_relative_to before exists()
- Remove redundant thumbnail field in persistImages mapping
- Replace hardcoded screenshot error with i18n translation key
- Add i18n keys (en/fr) for analysisUnsupported and screenshotTooLarge

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 67d44669de fix: add size validation to screenshot capture
Add MAX_IMAGE_SIZE validation to screenshot capture to match regular
image upload behavior. Screenshots larger than 10MB are now rejected
with a clear error message, preventing inconsistent behavior and
silent failures.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 9c57c669c6 fix: address local review findings - fix button type and suppress false positive lint warning
- Add explicit type="button" to tools expansion button to prevent unintended form submission
- Suppress Biome useExhaustiveDependencies false positive for session?.id dependency
  (the effect intentionally runs when session ID changes to reset task creation state)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 a5b66864e2 fix: address 9 new PR review findings for screenshot paste
Security (CMT-002 - MEDIUM):
- Add mode: 0o600 to temp file writes in insights-executor.ts (3 locations)
  to prevent world-readable files containing sensitive data

Quality (NEW-003 - MEDIUM):
- Add file size validation in useImageUpload.ts to prevent large images
  from being processed before backend validation
- Import MAX_IMAGE_SIZE constant and check file.size before base64 conversion

SDK Compatibility (CMT-001 - MEDIUM):
- Fix image_query_stream format in insights_runner.py
- Remove incorrect AsyncIterable approach, add clear TODO for SDK multi-modal support
- Provide user-visible warning when images cannot be sent in SDK mode

Memory Optimization (NEW-004 - LOW):
- Strip base64 data from Zustand state in insights-store.ts after sending to main process
- Retain thumbnails for display while removing full image data

Cleanup (CMT-003 - LOW):
- Fix manifest file cleanup by pushing to array before writeFile
- Ensures proper cleanup on partial write failures

UX (NEW-006 - LOW):
- Update image notation for historical messages in insights-service.ts
- Use past tense notation to avoid AI confusion about unavailable images

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 07dd376b3e fix: address PR review findings for screenshot paste capability
- Add randomBytes to historyFile name to fix CodeQL predictable temp file warning
- Resolve tmp_dir in Python to fix macOS symlink validation (is_relative_to)
- Convert writeFileSync to async writeFile to prevent main thread blocking
- Move SAFE_EXT_MAP to module scope to avoid repeated allocation
- Only write manifest file when manifest.length > 0 (skip empty manifests)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 36e9eb36d8 Fix CodeQL: use crypto.randomBytes for temp file names, remove redundant condition
- Add randomBytes(8) hex suffix to image and manifest temp file names
  to prevent predictable path attacks (CodeQL insecure-temporary-file)
- Remove always-true historyFileCreated check in image-write catch block
  (CodeQL useless-conditional)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 127778b74b Fix Ruff F541 f-string, historyFile leak on image-write failure, debug log label
- Remove f-prefix from string with no placeholders (Ruff F541 CI blocker)
- Clean up historyFile in image-write catch block before throw propagates
- Use file_size from stat() instead of base64 string length for debug log

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 48f4970f4b Fix follow-up PR review findings: SVG removal, image query, TOCTOU, cleanup guard
- Remove image/svg+xml from all allowlists (Python, TS executor, shared constants)
  SVG can contain scripts and is unsupported by Claude Vision API
- Fix client.query() to use AsyncIterable for multi-modal content blocks
  instead of passing a raw list that always triggers TypeError fallback
- Fix TOCTOU race: use resolved path instead of original path when opening
  image files after validation
- Add idempotency guard to cleanupTempFiles to prevent double cleanup

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 c916ec91ce Fix PR review findings: security hardening and code quality improvements
- Validate mimeType against allowlist in main process IPC handler (defense-in-depth)
- Use createThumbnail() for screenshots to avoid bloated session files
- Use generateImageId() instead of inline ID generation for consistency
- Add path, MIME type, and file size validation in Python image loader
- Narrow TypeError catch to only handle SDK query() type mismatches
- Extract shared cleanupTempFiles() helper to eliminate duplicated code
- Reset pendingImages in clearSession store action

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 97d0aeef44 auto-claude: subtask-4-3 - Add image display in user message bubbles
Display image thumbnails in user message bubbles within the Insights
chat. Images render in a flex-wrap layout below text content at max
200px. Handles both thumbnail-only (persisted) and full data cases.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 62bec58c4b auto-claude: subtask-4-2 - Add image paste/drop handlers, preview strip, and screenshot button to Insights
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 8100749797 auto-claude: subtask-4-1 - Update insights store to support images in messages
Add pendingImages state and setPendingImages action to the insights store.
Update sendMessage helper to accept optional images parameter, include them
in the user message, pass to electronAPI, and reset pending images after send.
Also update IPC type signature for sendInsightsMessage to include images param.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 e85eb9f176 auto-claude: subtask-3-1 - Update insights_runner.py to support multi-modal image input
Add --images-file CLI argument, load_images_from_manifest() helper, and
multi-modal content block construction in run_with_sdk(). Graceful fallback
when SDK doesn't support content blocks or in simple mode.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 260325fe3b auto-claude: subtask-2-5 - Strip image data from sessions on persistence
Add stripImageDataForPersistence() helper to SessionStorage that removes
full-resolution image data (data, path fields) from ImageAttachment objects
before writing to disk, keeping only thumbnail, id, filename, mimeType, and
size to prevent bloated session JSON files.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 b0b7176aaa auto-claude: subtask-2-4 - Update InsightsExecutor.execute() to handle images
Write image base64 data to temp files, create a JSON manifest with paths and
MIME types, pass manifest via --images-file argument to Python runner. Clean up
all temp image files in both success and error paths.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 90c9f386d5 auto-claude: subtask-2-3 - Update InsightsService.sendMessage() to accept and pass images
- Store thumbnail-only images on user messages for persistence (strip full data)
- Add '[User attached N image(s)]' notation to conversation history for context
- Pass images through to executor.execute()
- Update executor signature to accept optional ImageAttachment[] parameter

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 1c1ca43b0c auto-claude: subtask-2-2 - Update IPC handler to accept and pass images
Add images?: ImageAttachment[] parameter to INSIGHTS_SEND_MESSAGE handler
and pass it through to insightsService.sendMessage(). Also update the
service signature to accept the images parameter.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 bca5efeb93 auto-claude: subtask-2-1 - Update preload insights API to accept images parameter
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 1910e4bee1 auto-claude: subtask-1-2 - Add i18n translation keys for image-related UI text
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 19d2b3f31a auto-claude: subtask-1-1 - Add images field to InsightsChatMessage type
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 191736df1a fix: address PR review findings for XState PR review refactor
- handleComplete uses getOrCreateActor so late-arriving results after
  auth change or restart are processed instead of silently dropped
- GITHUB_AUTH_CHANGED handler now kills running review subprocesses and
  aborts CI wait controllers before clearing XState actors
- Duplicate review detection reads actual progress from actor snapshot
  instead of hardcoding progress=50
- handleClearReview stops actor directly without sending CLEAR_REVIEW
  event, preventing double IPC emission to renderer

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:36 +01:00
AndyMik90 9fa8532bb2 fix: address PR #1819 review findings for terminal session persistence
- Use setClaudeMode() instead of updateTerminal() in onTerminalClaudeExit
  handler to properly send CLAUDE_EXITED to XState machine
- Remove premature migratedSessionFlags cleanup from destroy() since
  resumeClaudeAsync already consumes flags and killAll() clears the map
- Add swap phase ordering guards (isCapturingPhase, isMigratingPhase,
  isRecreatingPhase) to prevent out-of-order swap events
- Add YOLO mode flag to deprecated sync resumeClaude for consistency
- Fix isBusy preservation heuristic by using dedicated updateClaudeSessionId
  action for self-transitions in claude_active state
- Add debugLog when setPendingClaudeResume silently drops request due to
  missing claudeSessionId
- Handle CLAUDE_BUSY events in claude_starting and pending_resume states

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 4a151aeb54 fix: address low-severity review findings — stale progress, dead code, missing tests
- Clear stale progress data when transitioning to externalReview state
- Capture snapshot before CLEAR_REVIEW so emitted payload has real context
- Add user feedback for duplicate follow-up review requests
- Remove dead clearPRReview code from store (zero callers)
- Add test coverage for CLEAR_REVIEW from reviewing/externalReview states
- Clarify ipcMain.emit comment re: EventEmitter semantics

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 e1e3cbf86b fix: address all PR #1819 review findings (round 7)
This commit addresses all 10 findings from the latest Auto Claude PR review:

**BLOCKING FIXES (3 MEDIUM severity):**

1. NCR-NEW-004: Add user notification when session migration fails
   - Added i18n key 'terminal:swap.migrationFailed' (EN + FR)
   - Hook now shows toast notification when isClaudeMode && sessionId && !sessionMigrated
   - Users are now informed when their Claude session is lost during profile switch

2. NEW-001: Add idle-state guard to setClaudeSessionId
   - setClaudeSessionId now checks if XState machine is in 'idle' state
   - Sends SHELL_READY first before CLAUDE_ACTIVE, matching setClaudeMode pattern
   - Prevents XState/Zustand desync during profile change flow

3. NEW-003: Correct fire-and-forget IPC comment
   - Removed incorrect claim about onTerminalPendingResume fallback
   - Updated comment to accurately describe actual failure behavior
   - Documents that errors are logged but no event is emitted back to renderer

**LOW SEVERITY FIXES (5):**

4. CMT-002: Remove EEXIST dead code
   - copyFile() without COPYFILE_EXCL never throws EEXIST
   - Removed unreachable catch branch at lines 136-141
   - Added comment documenting silent overwrite behavior

5. NEW-004-STORE: Add state check for CLAUDE_EXITED event
   - setClaudeMode now checks machine state before sending CLAUDE_EXITED
   - Only sends event if machine is in 'claude_starting' or 'claude_active'
   - Prevents XState/Zustand desync when event is dropped

6. NEW-006: Preserve isBusy during CLAUDE_ACTIVE self-transitions
   - setClaudeSessionId action now checks if it's a self-transition
   - Preserves existing isBusy state during self-transitions
   - Prevents late session ID updates from incorrectly clearing busy indicator

7. CMT-NEW-001: Add swap state assertions to RESET tests
   - Updated RESET test to include swapTargetProfileId and swapPhase
   - Tests now verify all 6 context fields are cleared (not just 4)
   - Comprehensive test coverage for resetContext action

**REMAINING LOW SEVERITY (acknowledged but not blocking):**

8. CMT-NEW-002: Swap phase events lack ordering guards
   - Acknowledged: ordering currently guaranteed by single caller
   - Guards would be defensive but not essential for current implementation
   - Can be addressed in future refactoring if needed

9. CMT-NEW-003: Dual Zustand/XState state updates lack architectural docs
   - Acknowledged: inline comments exist per method
   - Architectural-level documentation could be added separately
   - Does not block merge as per-method comments are clear

All tests passing (3271 passed, 6 skipped). TypeScript compiles cleanly.
Biome linting clean for all changed files.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 58fec15cd2 fix: prevent OOM, orphaned agents, and unbounded growth during overnight builds
- Move handleStartFollowupReview after runningReviews.has() duplicate check to
  prevent XState actor getting stuck in reviewing state when follow-up is already
  running (mirroring the regular review handler pattern)
- Add CLEAR_REVIEW handler to reviewing state so handleClearReview works correctly
  when an active review is cleared
- Remove dead-code START_REVIEW transition and always-false isNotAlreadyReviewing
  guard from reviewing state — duplicate prevention is handled at the IPC layer

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 33462978df fix: address remaining PR #1819 code quality findings
Three improvements for production code quality:

1. Use path alias for consistency
   - Change terminal-store.ts line 7 to use @shared/* instead of relative import
   - Matches project conventions (CLAUDE.md path alias guidelines)

2. Prevent XState/Zustand state divergence in setPendingClaudeResume
   - Only set pendingClaudeResume flag in Zustand if RESUME_REQUESTED was sent to XState
   - When claudeSessionId is missing, skip both XState event and Zustand update
   - Prevents UI showing "resume pending" when state machine doesn't know about it

3. Clean up migratedSessionFlags on individual terminal destroy
   - Previously only cleared on killAll(), entries could linger if terminal closed before resume
   - Now removes entry in destroy() if terminal has claudeSessionId
   - Prevents Map from accumulating stale session flags

All tests pass (128/128 files, 3271/3277 tests).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 947fc3c6f8 fix: address follow-up review findings — unhandled rejection, auth payload, polling guard
- Wrap timeout-branch IPC call in try/catch to prevent unhandled promise rejection
  in the Electron renderer when notifyExternalReviewComplete fails
- Add `notified` flag to short-circuit duplicate polling notifications before React
  cleanup fires
- Use last snapshot context in handleAuthChange so emitted cleared-state payload
  contains real projectId/prNumber instead of zeros
- Move handleStartReview after duplicate-review check so state machine isn't
  transitioned for already-running reviews

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 ea45b353ec fix: resolve PR #1819 review findings - session ID preservation and IPC clarity
Address three blocking review findings:

1. NEW-008: setClaudeMode now preserves claudeSessionId when dispatching CLAUDE_ACTIVE
   - Include terminal's current claudeSessionId in the event to prevent XState
     setClaudeSessionId action from overwriting it to undefined
   - Fixes hasActiveSession guard for profile swaps

2. NCR-001: setPendingClaudeResume preserves claudeSessionId in RESUME_COMPLETE event
   - Include terminal's claudeSessionId when sending RESUME_COMPLETE to XState
   - Prevents machine from losing session ID on resume completion

3. NEW-002: Remove ineffective try/catch around fire-and-forget IPC call
   - resumeClaudeInTerminal uses ipcRenderer.send() which returns void immediately
   - Removed try/catch and await that could never catch main process errors
   - Added comment documenting fire-and-forget nature and error handling via events

All tests pass (52/52).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 1b65a7ba23 fix: resolve XState gaps in external review polling, cancel/clear handlers, and result updates
- Add CANCEL_REVIEW and CLEAR_REVIEW handlers to externalReview state so users
  can cancel or clear while an external review is in progress
- Add REVIEW_COMPLETE self-transition in completed state so sendReviewStateUpdate
  can update result context (e.g., after posting findings or marking as posted)
- Add notifyExternalReviewComplete IPC channel so renderer polling can notify the
  main process when an external review finishes on disk or times out, transitioning
  the XState actor to completed/error instead of leaving it stuck in externalReview
- Wire PRDetail.tsx external review polling to use the new IPC notification

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 966e5cadfa fix: address review findings for PR #1819
- Add setError action to claude_active CLAUDE_EXITED transition to preserve error messages
- Fix missing await on resumeClaudeInTerminal call with proper error handling fallback
- Improve TypeScript type safety in test helper using Partial<TerminalContext>
- Add test coverage for CLAUDE_EXITED error preservation from claude_active state

All tests pass (52/52).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 b3d6bbdeda fix: resolve IPC serialization, auth change wiring, and error→followup transition (qa-requested)
Fixes:
- Build PRReviewStatePayload object in emitStateToRenderer instead of sending raw args
- Wire up handleAuthChange via ipcMain listener for GITHUB_AUTH_CHANGED
- Add START_FOLLOWUP_REVIEW transition to error state in pr-review-machine
- Update state manager tests to verify PRReviewStatePayload shape

Verified:
- All 3279 tests pass
- TypeScript compilation clean

QA Fix Session: 1

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 d1c63d23aa Fix follow-up review: security, dead code, XState wiring completeness
- Convert migrateSession() from sync to async fs operations (mkdir,
  copyFile, cp, unlink from fs/promises) to avoid blocking the Electron
  main process during session migration
- Remove dead TerminalSwapState/TerminalSwapPhase types and swapState
  field from TerminalProcess (no longer referenced after prior cleanup)
- Remove dead swapState logic from activateDeferredResume
- Add migratedSessionFlags.clear() to killAll() to prevent memory leaks
- Add CLAUDE_ACTIVE handler to pending_resume XState state (fixes race
  where Claude becomes active before RESUME_COMPLETE fires)
- Add test coverage for CLAUDE_ACTIVE in pending_resume state

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 16f3194ca0 auto-claude: subtask-5-1 - Fix type errors and verify full test suite
- Remove obsolete setPRReviewResult calls in PRDetail.tsx (now handled by XState)
- Add missing onPRReviewStateChange to browser-mock.ts
- Fix pr-review-machine.test.ts mock data to match actual PRReviewResult/PRReviewProgress types
- All 130 test files pass (3278 tests), typecheck clean, lint clean

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 9bcd1a3033 Fix follow-up review: security, dead code, XState wiring completeness
Security:
- Move YOLO mode (dangerouslySkipPermissions) to server-side storage
  instead of accepting from renderer via IPC. Main process stores flag
  during profile migration and restores it when resume is called.

XState machine fixes:
- Add CLAUDE_ACTIVE self-transition in claude_active state so
  setClaudeSessionId can update context.claudeSessionId (was silently
  dropped, blocking hasActiveSession guard)
- Add SHELL_EXITED dispatch in setTerminalStatus for 'exited' status
  so XState machine reaches its exited state

Dead code removal:
- Remove unused swapProfileAndResume method (migration handled directly
  in IPC handler) and its now-unused migrateSession import
- Remove unused deriveTerminalStateFromMachine function and SnapshotFrom
  import

Resource cleanup:
- clearAllTerminals now disposes terminalBufferManager entries and
  xtermCallbacks alongside XState actors

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 181fe50be7 auto-claude: subtask-4-2 - Update useGitHubPRs hook for new XState-driven architecture
- Remove imports of deleted startPRReview/startFollowupReview store functions
- runReview/runFollowupReview now call IPC directly (main process handles XState)
- cancelReview no longer mutates store directly (state flows back via IPC)
- Add setLoadedReviewResult action to pr-review-store for disk-loaded reviews
- Replace all setPRReviewResult calls with setLoadedReviewResult

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 572d62da8b Fix PR review findings: XState machine wiring, dead code, YOLO mode preservation
- Make pending_resume state reachable by adding RESUME_REQUESTED transitions
  from shell_ready and claude_active states
- Add CLAUDE_ACTIVE transition from shell_ready for direct activation path
- Wire SHELL_READY dispatch in setTerminalStatus and setClaudeMode to
  prevent XState machine from being stuck in idle
- Remove dead TERMINAL_SWAP_PROGRESS IPC send (no listener existed)
- Remove unused isSwapping guard from terminal machine
- Remove ineffective try/catch around fire-and-forget ipcRenderer.send()
- Preserve dangerouslySkipPermissions (YOLO mode) through profile swap
  terminal recreation flow via resume options
- Align swap phase naming: capturing_session → capturing (matches XState)
- Fix French translation accents: démarrer, changé, à

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 a0c8e89fee auto-claude: subtask-4-1 - Rewrite pr-review-store.ts as thin XState state subscriber
Replace 6 imperative review lifecycle actions with a single handlePRReviewStateChange
handler that maps XState state/context to the existing PRReviewState interface shape.
Update initializePRReviewListeners to use onPRReviewStateChange IPC channel. Remove
exported startPRReview/startFollowupReview helpers (now direct IPC calls from hooks).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 c8fe01ef0c auto-claude: subtask-4-2 - Write comprehensive unit tests for terminal-machine
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 df819b3990 auto-claude: subtask-3-1 - Refactor pr-handlers.ts to use PRReviewStateManager
Replace all 6 createIPCCommunicators() calls for review lifecycle events with
PRReviewStateManager routing. The manager's XState actors now handle all state
transitions and emit on GITHUB_PR_REVIEW_STATE_CHANGE channel.

Changes:
- Create PRReviewStateManager instance in registerPRHandlers()
- GITHUB_PR_REVIEW handler: route start/progress/complete/error through manager
- GITHUB_PR_FOLLOWUP_REVIEW handler: route through manager with previous result
- GITHUB_PR_REVIEW_CANCEL handler: call manager.handleCancel() after kill
- sendReviewStateUpdate(): use manager.handleComplete() instead of direct IPC
- runPRReview(): accept manager param, use for progress callbacks
- Remove unused createIPCCommunicators import

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 e5f1c6b2db auto-claude: subtask-4-1 - Add i18n translation keys for swap/resume UI messages
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 8c0b0257a2 auto-claude: subtask-2-3 - Write unit tests for PRReviewStateManager.
File: apps/frontend/src/main/__tests__/pr-review-state-manager.test.ts
2026-02-17 15:32:35 +01:00
AndyMik90 1302c61b71 auto-claude: subtask-3-2 - Integrate XState terminal machine into terminal-store
Add module-level terminalActors Map and helper functions (getOrCreateTerminalActor,
sendTerminalMachineEvent, deriveTerminalStateFromMachine) for XState actor management.
Store actions (setClaudeMode, setClaudeSessionId, setClaudeBusy, setPendingClaudeResume)
now forward corresponding events to the XState machine. Actors are cleaned up on
terminal removal and clearAllTerminals.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 bfdbdb5f22 auto-claude: subtask-2-2 - Create PRReviewStateManager class in Electron main process
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 6c991774ad auto-claude: subtask-3-1 - Auto-resume Claude session after terminal profile change
Replace manual "Run: claude --resume" message with automatic resume call via
resumeClaudeInTerminal IPC. Updated preload API and IPC types to pass
migratedSession option. YOLO mode is preserved automatically via the main
process terminal object.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 b4264ae95b auto-claude: subtask-2-1 - Add IPC channel constant and preload API listener for PR review state changes 2026-02-17 15:32:35 +01:00
AndyMik90 fc3e8a8ad5 auto-claude: subtask-2-3 - Add isClaudeMode to TERMINAL_PROFILE_CHANGED event and migratedSession to TERMINAL_RESUME_CLAUDE
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 f3e910598b auto-claude: subtask-1-2 - Write comprehensive unit tests for the PR review state machine and utilities
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 7578a3263b auto-claude: subtask-2-2 - Update terminal-manager with swap orchestration and options passthrough
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 45eebe960f auto-claude: subtask-1-1 - Create XState v5 PR review state machine and state utils
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 ab42f88635 auto-claude: subtask-2-1 - Add migratedSession option to resumeClaudeAsync and preserve YOLO mode
- Add optional `options` parameter with `migratedSession` flag to resumeClaudeAsync()
- When migratedSession is true, log post-swap resume context and skip sessionId deprecation warning
- Preserve dangerouslySkipPermissions flag from terminal's stored state during resume

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 84775ed46c auto-claude: subtask-1-3 - Update shared/state-machines/index.ts barrel export
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:34 +01:00
AndyMik90 ca370eaa1f auto-claude: subtask-1-2 - Add TerminalSwapState interface and swapState to TerminalProcess
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:34 +01:00
AndyMik90 5a8e140c39 auto-claude: subtask-1-1 - Create terminal-machine.ts XState v5 state machine
Add XState v5 state machine for terminal lifecycle with states: idle,
shell_ready, claude_starting, claude_active, swapping, pending_resume,
exited. Context tracks claudeSessionId, profileId, swap state, isBusy,
and error. Includes guards (hasActiveSession, isSwapping) and assign
actions for all context updates.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:34 +01:00
AndyMik90 da7d186950 fix: address all XState catch-up and cleanup findings for PR #1815
Resolves all 9 findings from auto-claude review (2026-02-16):

HIGH severity (1):
- NEW-001: Added catch-up transition for 'analyzing' state when setting status to 'generating'
  The actor now properly transitions through 'discovering' before reaching 'generating'

MEDIUM severity (3):
- NEW-002: Fixed updateFeatureLinkedSpec to respect XState state machine
  Removed fallback that bypassed XState for 'done' features. Now skips store write
  when LINK_SPEC event is silently ignored (no linkedSpecId in context)

- NEW-003: Wired up HMR cleanup and test actor reset
  Added import.meta.hot.dispose handler to reset actors during HMR
  Added resetActors() call in test afterEach to prevent test pollution

- NEW-004: Added comprehensive catch-up logic for 'complete' phase
  The actor now properly transitions through all intermediate states
  (analyzing → discovering → generating) before accepting GENERATION_COMPLETE

LOW severity (1):
- CMT-001: Clarified test describe block title
  Changed from "same-status transition is no-op" to "redundant status transitions"
  to distinguish true no-ops (ignored events) from self-transitions (MARK_DONE in done)

All XState catch-up transitions now handle out-of-order status messages correctly,
preventing the UI from showing incorrect generation/feature status.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:30 +01:00
AndyMik90 3f9cea9eca refactor: address all code review findings for roadmap XState refactor
Fix all CodeRabbit review comments and Biome warnings:
- Replace non-null assertions with explicit null checks in roadmap-store.ts (lines 548, 553, 559, 565)
- Replace non-null assertion with proper type guards in test (line 396)
- Use @shared/state-machines path alias instead of relative imports
- Prune stale feature actors in setRoadmap when roadmap changes
- Add lastActivityAt timestamp tracking to generation machine context
- Update deriveGenerationStatus to use persisted lastActivityAt from context
- Fix misleading test title "ignore MARK_DONE" → "self-transition"
- Add test verifying progress preservation on GENERATION_ERROR
- Remove progress reset in setError action to preserve progress on errors
- Add compile-time assertions to ensure state name arrays stay in sync with XState machines

All tests pass (77/77). TypeScript compilation successful. Zero Biome warnings in modified files.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:30 +01:00
AndyMik90 960a6acb96 fix: address second round of review findings for PR #1815
Fixes 6 issues identified in follow-up review (2 HIGH, 1 MEDIUM, 3 LOW):

1. HIGH [65226bd9539f]: Generation can now restart from complete/error states
   - Added RESET + START_GENERATION logic in 'analyzing' case

2. HIGH [282536242c43]: Phase restoration fixed for discovering/generating
   - Drive actor through intermediate transitions to reach target state
   - Handle idle and complete/error states before sending phase events

3. MEDIUM [1b74aa0cd0f1]: Progress value clamping added to updateProgress
   - Clamp progress to 0-100 range using Math.min/max

4. LOW [c833788d76ce]: setError now resets progress to 0 on error
   - Consistent error state with progress reset

5. LOW [686d19af55d5]: Document unused SETTLED_STATES constants
   - Added comments explaining future public API use

6. LOW [605d439c4efd]: Document getState() outside set() pattern
   - Explain XState actors as external side effects

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:30 +01:00
AndyMik90 948a55a82c fix: address review findings for PR #1815
- Replace deprecated String.prototype.substr with substring
- Add resetActors() helper for test cleanup and HMR

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:30 +01:00
AndyMik90 730ed12d3c Address follow-up review suggestions for XState roadmap integration
- Move deleteFeature actor cleanup outside set() for consistency
- Skip no-op store writes when XState silently ignores events
- Use 'as const' on assign action string literals for type narrowing

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:30 +01:00
AndyMik90 5c12dbc669 Fix PR review issues: strong types, actor cleanup, under_review transitions
- Use TaskOutcome/RoadmapFeatureStatus types in feature machine context
  instead of loose strings, eliminating unsafe casts in roadmap-store
- Add TASK_COMPLETED/DELETED/ARCHIVED handlers to under_review state,
  fixing a behavioral regression where linked task events were silently
  ignored
- Move XState actor side effects outside Zustand set() callbacks in
  updateFeatureStatus, markFeatureDoneBySpecId, updateFeatureLinkedSpec
- Clean up stale feature actors in setRoadmap to prevent memory leaks
  when switching projects or loading new roadmaps
- Consolidate duplicate imports from shared/state-machines

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:30 +01:00
AndyMik90 b7d1ffe209 auto-claude: subtask-4-1 - Verify backward compatibility and fix XState integration
- Add TASK_COMPLETED/DELETED/ARCHIVED transitions to planned and done states
- Add MARK_DONE self-transition in done state for idempotent updates
- Restore feature context (taskOutcome, previousStatus, linkedSpecId) when
  creating XState actors from persisted store data
- Invalidate cached actors when state or context diverges from store truth
- Update machine tests to reflect expanded transition coverage
- All 3293 tests pass, typecheck clean, lint warnings only (pre-existing)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:30 +01:00
AndyMik90 aa95986be8 auto-claude: subtask-3-1 - Refactor roadmap-store.ts to integrate XState actors
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:30 +01:00
AndyMik90 7a69743ae1 auto-claude: subtask-2-2 - Write comprehensive unit tests for roadmap feature machine
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:30 +01:00
AndyMik90 6b7f241045 auto-claude: subtask-2-1 - Write comprehensive unit tests for the roadmap generation machine
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:30 +01:00
AndyMik90 b6ae439d16 auto-claude: subtask-1-4 - Update barrel export for roadmap machine artifacts 2026-02-17 15:32:30 +01:00
AndyMik90 fa4e29f591 auto-claude: subtask-1-3 - Create roadmap-state-utils.ts with state name constants, settled states, and mapping utilities
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:30 +01:00
AndyMik90 906b1f29c4 auto-claude: subtask-1-2 - Create roadmap feature state machine
Add roadmap-feature-machine.ts with states: under_review, planned,
in_progress, done. Handles LINK_SPEC auto-transition to in_progress,
task completion events from in_progress only, REVERT from done
restoring previousStatus via guards, and context cleanup on
non-done transitions.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:30 +01:00
AndyMik90 11e300c75d auto-claude: subtask-1-1 - Create roadmap generation XState machine
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:30 +01:00
AndyMik90 c1210c46f0 fix: address final PR review findings
Resolve remaining code quality issues from auto-claude bot review:

1. Error Handling (Roadmap.tsx):
   - Wrap confirmArchiveFeature in try/finally to ensure pendingArchiveFeatureId
     is always cleared, even if deleteFeature throws an error
   - Prevents dialog from getting stuck in broken state on failure

2. Accessibility (FeatureCard.tsx):
   - Add missing aria-label to archive button for screen reader support
   - Now consistent with PhaseCard and SortableFeatureCard implementations
   - Uses existing i18n key: accessibility.archiveFeatureAriaLabel

All other findings were already addressed in previous commits:
- useFeatureArchive hook removed (reuses useFeatureDelete)
- Confirmation dialog centralized in Roadmap.tsx
- Archive button JSX extracted to shared variables (PhaseCard, FeatureDetailPanel)
- handleArchive no longer calls onClose() prematurely
- All hardcoded UI strings replaced with i18n translation keys
- Archive buttons properly guard with onArchive && checks
- All archive buttons have aria-labels for accessibility

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 08:47:44 +01:00
AndyMik90 ff6ad4479c fix: address PR review findings for archive button feature
Resolve all review comments from gemini-code-assist and coderabbitai:

1. Remove duplicate archive button rendering in PhaseCard
   - Extract isDone check to avoid duplicate conditional logic
   - Archive button now renders only once for done features

2. Add archive button support to "By Priority" view
   - Done features in priority view now show archive functionality
   - Maintains consistent UX across all roadmap tabs
   - Uses semantic button element for accessibility

3. Improve accessibility and code quality
   - Replace div with button in priority view feature cards
   - Add proper focus states and keyboard navigation support
   - Remove unused imports (ExternalLink, Play)

All review findings addressed while maintaining existing functionality.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-15 22:19:05 +01:00
Andy bccdbf35da Merge branch 'develop' into auto-claude/220-add-manual-competitor-functionality-in-roadmap 2026-02-15 20:57:28 +01:00
AndyMik90 99aeae7e49 fix: address follow-up PR review findings for archive feature
Address 4 new findings identified in latest PR review:

1. Replace hardcoded UI strings with i18n translation keys:
   - SortableFeatureCard.tsx: "Task" → t('roadmap.task')
   - SortableFeatureCard.tsx: "Build" → t('roadmap.build')
   - PhaseCard.tsx: "View Task" → t('roadmap.viewTask')
   - PhaseCard.tsx: "Build" → t('roadmap.build')

2. Add missing aria-labels for accessibility:
   - SortableFeatureCard.tsx: Archive button now has aria-label
   - PhaseCard.tsx: Archive button now has aria-label

3. Add new translation keys to both locale files:
   - en/common.json: Added "task" and "viewTask" to roadmap section
   - fr/common.json: Added "task" ("Tâche") and "viewTask" ("Voir la tâche")

All archive buttons now properly support screen readers and comply
with i18n requirements for both English and French locales.

Resolves findings from PR #1817 review (2026-02-15T18:31:26Z).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-15 20:30:33 +01:00
AndyMik90 c59215edf3 fix: replace hardcoded UI strings with i18n translation keys
Address review findings by converting hardcoded user-facing strings
to react-i18next translation keys in roadmap feature components.

Changes:
- Add 'goToTask', 'convertToTask', 'build' keys to roadmap section
  in both en/common.json and fr/common.json
- Replace hardcoded "Go to Task" with t('roadmap.goToTask')
- Replace hardcoded "Convert to Auto-Build Task" with t('roadmap.convertToTask')
- Replace hardcoded "Build" with t('roadmap.build')

Files modified:
- FeatureDetailPanel.tsx: 2 hardcoded strings replaced
- FeatureCard.tsx: 2 hardcoded strings replaced
- en/common.json: 3 new translation keys added
- fr/common.json: 3 new French translations added

Resolves i18n violations identified in PR #1817 review.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-15 17:39:19 +01:00
Andy 586e9d6ac2 Merge branch 'develop' into auto-claude/226-add-archive-button-to-done-tasks 2026-02-15 17:12:13 +01:00
AndyMik90 517892cf31 Fix cross-process race condition and remove dead code
Use a separate manual_competitors.json file that the backend agent never
overwrites, preventing data loss when users add competitors during analysis.
Remove unused removeCompetitor and updateCompetitorAnalysis store actions.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-15 14:12:13 +01:00
AndyMik90 7f6050f5ba fix(terminal): resolve blank terminals after project switch
Force SIGWINCH on same-dimension resize and skip stale buffer replay
for Claude-mode terminals during project switch remount.

Two compounding issues caused blank terminals when switching projects:

1. On macOS/Linux, ioctl(TIOCSWINSZ) only sends SIGWINCH when dimensions
   actually change. After project switch, PTY persists with old dimensions
   and the terminal remounts at the same size, so TUI apps never get
   SIGWINCH and never redraw. Fix: resize to (cols-1, rows) first, then
   to (cols, rows) to force the signal.

2. Buffer replay concatenated serialized xterm state with raw PTY output
   accumulated during the unmount period, producing garbled display. Fix:
   skip buffer replay for Claude-mode terminals on project switch remount
   (the forced SIGWINCH makes Claude Code redraw its full TUI). Initial
   restore still replays the buffer as a loading preview.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 21:03:33 +01:00
Andy 9b46709508 Merge branch 'develop' into auto-claude/220-add-manual-competitor-functionality-in-roadmap 2026-02-14 17:49:11 +01:00
Andy 392571049a Merge branch 'develop' into auto-claude/226-add-archive-button-to-done-tasks 2026-02-14 17:49:01 +01:00
AndyMik90 6c9a8b200f Fix follow-up review findings: data loss bug, dialog nesting, and quality improvements
- Preserve manual competitors in analyze(enabled=False) path (HIGH data loss bug)
- Fix incomplete rollback by restoring full previous competitorAnalysis state
- Reset showAddDialog state when ExistingCompetitorAnalysisDialog reopens
- Add encoding option to writeFileWithRetry for competitor analysis save
- Replace X icon with AlertCircle in error alert for clarity
- Add type="button" to all raw button elements in dialog
- Add warning logs to silent exception handlers in competitor_analyzer.py
- Forward onCompetitorAdded callback through ExistingCompetitorAnalysisDialog

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 15:22:32 +01:00
AndyMik90 f89fd5080b fix: prevent panel close before archive confirmation and extract archive button
- Remove onClose() from handleArchive — confirmArchiveFeature in Roadmap.tsx
  already handles panel closing via setSelectedFeature(null) after confirmation
- Extract triplicated archive button JSX into shared variable

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 15:20:31 +01:00
AndyMik90 59944f2335 fix: address follow-up PR review findings
- Extract duplicated archive button JSX in PhaseCard into shared variable
- Centralize archive confirmation dialog in Roadmap.tsx using AlertDialog
- Remove local archive confirmation from FeatureDetailPanel (now centralized)
- Make handleArchive async to properly await onArchive callback
- Add archive button for done features with linkedSpecId in FeatureDetailPanel

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 11:30:11 +01:00
AndyMik90 c7301d67c5 Fix follow-up review findings: data loss bug, dialog nesting, and quality improvements
- [HIGH] Move _get_manual_competitors() before discovery file check to prevent
  data loss when discovery file is missing during refresh
- [HIGH] Merge manual competitors after _create_error_analysis_file in
  discovery-file-missing path
- [MEDIUM] Move AddCompetitorDialog outside parent Dialog in
  CompetitorAnalysisViewer to fix Radix UI focus/z-index issues
- [LOW] Use i18n.language for date formatting instead of hardcoded 'en-US'
- [LOW] Add warning log in _merge_manual_competitors on file read failure
- [LOW] Replace hardcoded English fallback with i18n key in AddCompetitorDialog
- [LOW] Add focus-visible ring styles to option buttons in
  ExistingCompetitorAnalysisDialog for keyboard accessibility
- [LOW] Replace deprecated substr() with substring() in roadmap-store ID generation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 11:25:50 +01:00
Andy 28bf739d8a Merge branch 'develop' into auto-claude/226-add-archive-button-to-done-tasks 2026-02-14 11:25:28 +01:00
Andy fa05afb02d Merge branch 'develop' into auto-claude/220-add-manual-competitor-functionality-in-roadmap 2026-02-14 11:23:27 +01:00
AndyMik90 4d781b5627 fix: address PR review findings for archive button feature
- Remove duplicate useFeatureArchive hook, reuse useFeatureDelete instead
- Add feature.status === 'done' guard to PhaseCard taskOutcome branch
- Add confirmation dialog to archive action in FeatureDetailPanel
- Fix missing 'common' namespace in FeatureCard useTranslation
- Add i18n keys for archive confirmation dialog (en/fr)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 10:23:47 +01:00
AndyMik90 d917fa63f7 Fix PR review findings: i18n, store rollback, state reset, and data preservation
- Complete i18n migration for CompetitorAnalysisViewer (all hardcoded strings)
- Complete i18n migration for ExistingCompetitorAnalysisDialog (all hardcoded strings)
- Fix namespace mismatch: ExistingCompetitorAnalysisDialog now uses 'dialogs' namespace
  consistently with sibling competitor dialog components
- Move shared i18n keys from common to dialogs namespace where appropriate
- Add store rollback in AddCompetitorDialog when IPC save fails
- Add removeCompetitor action to roadmap store for rollback support
- Reset addedCount state when CompetitorAnalysisDialog reopens
- Preserve manual competitors when competitor analysis fails all retries
- Add all new translation keys to both en and fr locale files

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 10:23:24 +01:00
AndyMik90 556fa8f5a5 auto-claude: subtask-1-1 - Update XSTATE_MIGRATION_SUMMARY.md to reflect completed migration
Mark Phases 3-4 as complete, replace 'Why We Stopped at Phase 2' with
'Migration Complete' section, remove legacy fallback references and
rollback plan, remove Phase 3-4 from Future Improvements.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:34:43 +01:00
AndyMik90 13df4c735c auto-claude: subtask-7-3 - End-to-end verification of the complete data flow.
Verified all 8 integration points pass:
- AddCompetitorDialog validates name/URL correctly
- Store generates competitor-manual-* IDs with source='manual'
- IPC handler transforms camelCase→snake_case and writes JSON
- ROADMAP_GET preserves source field on load
- CompetitorAnalysisViewer shows Manual badge
- Backend competitor_analyzer preserves manual competitors on refresh

Fixed minor issue: removed unnecessary `as any` cast in CompetitorAnalysisViewer.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:27:08 +01:00
AndyMik90 1594a6d51c auto-claude: subtask-6-1 - Preserve manual competitors during refresh
Add _get_manual_competitors() and _merge_manual_competitors() methods to
CompetitorAnalyzer. Manual competitors (source=='manual') are extracted
before the AI agent runs and merged back after successful validation,
ensuring they survive refresh cycles.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:22:26 +01:00
AndyMik90 f5a753decf auto-claude: subtask-5-3 - Add 'Add known competitors' option to ExistingCompetitorAnalysisDialog
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:20:20 +01:00
AndyMik90 c28e7ef488 auto-claude: subtask-5-2 - Add 'Add Known Competitors' section to CompetitorAnalysisDialog
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:17:26 +01:00
AndyMik90 0e0886904d auto-claude: subtask-5-1 - Add 'Add Competitor' button to CompetitorAnalysisViewer
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:14:33 +01:00
AndyMik90 a0034ed41c auto-claude: subtask-4-1 - Create AddCompetitorDialog.tsx component
Add dialog for manually adding competitors to roadmap analysis with
name, URL, description, and relevance fields. Follows AddFeatureDialog
pattern. Also adds saveCompetitorAnalysis to ElectronAPI type.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:12:19 +01:00
AndyMik90 236b69425f auto-claude: subtask-3-2 - Add French i18n keys for competitor functionality
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:08:54 +01:00
AndyMik90 237c944cc3 auto-claude: subtask-3-1 - Add English i18n keys for the AddCompetitorDialog
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:07:41 +01:00
AndyMik90 ea3c2e625f auto-claude: subtask-2-3 - Add source field to competitor mapping in ROADMAP_GET handler
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:06:35 +01:00
AndyMik90 be39dd7221 fix: show archive button on done features without taskOutcome (qa-requested)
Fixes:
- SortableFeatureCard: moved archive button outside taskOutcome ternary
- FeatureDetailPanel: added archive button for done features without taskOutcome
- Fixed i18n namespace from 'tasks' to 'common' in SortableFeatureCard

QA Fix Session: 2
2026-02-14 00:05:42 +01:00
AndyMik90 8021b04cb5 auto-claude: subtask-2-2 - Add COMPETITOR_ANALYSIS_SAVE IPC handler in roadmap-handlers
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:05:35 +01:00
AndyMik90 7ee40a813c auto-claude: subtask-2-1 - Add addCompetitor and updateCompetitorAnalysis actions to roadmap-store
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:04:04 +01:00
AndyMik90 45f16be130 auto-claude: subtask-1-3 - Add saveCompetitorAnalysis method to the preload roadmap API
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:02:47 +01:00
AndyMik90 7972047c7e auto-claude: subtask-1-2 - Add COMPETITOR_ANALYSIS_SAVE IPC channel to ipc.ts
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:01:38 +01:00
AndyMik90 75513472ee auto-claude: subtask-1-1 - Add CompetitorSource type and ManualCompetitorInput to roadmap types
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:00:47 +01:00
AndyMik90 c2db77fb5e auto-claude: subtask-3-4 - Add archive button to PhaseCard.tsx for done features
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 23:55:32 +01:00
AndyMik90 8046306ae0 auto-claude: subtask-3-3 - Add archive button to FeatureDetailPanel.tsx
Import Archive icon, destructure onArchive prop, add handleArchive handler
that calls onArchive and closes panel, render archive button in footer
when feature.status === 'done' with i18n text and aria-label.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 23:54:23 +01:00
AndyMik90 f1c530ad2f auto-claude: subtask-3-2 - Add archive button to SortableFeatureCard for done tasks
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 23:53:15 +01:00
AndyMik90 3a74543a8c auto-claude: subtask-3-1 - Add archive button to FeatureCard.tsx
Import Archive icon and useTranslation, destructure onArchive from props,
render ghost archive button for done features with stopPropagation.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 23:52:12 +01:00
AndyMik90 432f6bd838 auto-claude: subtask-2-3 - Thread onArchive prop through RoadmapKanbanView.tsx
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 23:51:01 +01:00
AndyMik90 5027355a8e auto-claude: subtask-2-2 - Thread onArchive prop through RoadmapTabs.tsx
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 23:50:05 +01:00
AndyMik90 557fda68c1 auto-claude: subtask-2-1 - Wire useFeatureArchive in Roadmap.tsx
Import and call useFeatureArchive hook alongside useFeatureDelete.
Create handleArchiveFeature wrapper that archives the feature and
clears selectedFeature if it matches. Pass onArchive prop to both
RoadmapTabs and FeatureDetailPanel.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 23:49:04 +01:00
AndyMik90 9e89354d04 auto-claude: subtask-1-3 - Update TypeScript interfaces to add onArchive callback prop
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 23:47:49 +01:00
AndyMik90 3a5a9dbca9 auto-claude: subtask-1-2 - Create useFeatureArchive hook in hooks.ts
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 23:46:58 +01:00
AndyMik90 cda21b2056 auto-claude: subtask-1-1 - Add i18n translation keys for archive feature
Add roadmap.archiveFeature and accessibility.archiveFeatureAriaLabel keys
to both English and French locale files.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 23:46:12 +01:00
AndyMik90 1a8f589f96 auto-claude: subtask-1-1 - Add keepWorktree option to mark-as-done flow
Add keepWorktree option to TASK_UPDATE_STATUS handler so marking a task
as done bypasses the worktree existence check without deleting it. Update
type definitions in task-api.ts and task-store.ts, and fix handleMarkDoneOnly
in WorkspaceMessages.tsx to pass { keepWorktree: true } and check the result.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 23:42:24 +01:00
132 changed files with 10820 additions and 1282 deletions
+1 -1
View File
@@ -98,7 +98,7 @@ jobs:
- name: Upload to release
if: github.event_name == 'release'
uses: softprops/action-gh-release@v1
uses: softprops/action-gh-release@v2
with:
files: apps/frontend/node-pty-*.zip
env:
+1
View File
@@ -3,6 +3,7 @@ name: Discord Release Notification
on:
release:
types: [published]
workflow_dispatch:
jobs:
discord-notification:
+1 -1
View File
@@ -620,7 +620,7 @@ jobs:
draft: false
prerelease: ${{ contains(github.ref, 'beta') || contains(github.ref, 'alpha') }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_TOKEN: ${{ secrets.PAT_TOKEN || secrets.GITHUB_TOKEN }}
# Update README with new version after successful release
update-readme:
+38 -12
View File
@@ -30,29 +30,55 @@ Auto Claude is a desktop application (+ CLI) where users describe a goal and AI
## Critical Rules
**Claude Agent SDK only** — All AI interactions use `claude-agent-sdk`. NEVER use `anthropic.Anthropic()` directly. Always use `create_client()` from `core.client`.
**Claude Agent SDK only** — All AI interactions use `claude-agent-sdk` because it handles security hooks, tool permissions, and MCP server integration. Use `create_client()` from `core.client`, not `anthropic.Anthropic()` directly.
**i18n required** — All frontend user-facing text MUST use `react-i18next` translation keys. Never hardcode strings in JSX/TSX. Add keys to both `en/*.json` and `fr/*.json`.
**i18n required** — All frontend user-facing text uses `react-i18next` translation keys. Hardcoded strings in JSX/TSX break localization for non-English users. Add keys to both `en/*.json` and `fr/*.json`.
**Platform abstraction**Never use `process.platform` directly. Import from `apps/frontend/src/main/platform/` or `apps/backend/core/platform/`. CI tests all three platforms.
**Platform abstraction**Use the platform modules in `apps/frontend/src/main/platform/` or `apps/backend/core/platform/` instead of `process.platform` directly. CI tests all three platforms, and raw platform checks cause failures.
**No time estimates**Never provide duration predictions. Use priority-based ordering instead.
**No time estimates**Provide priority-based ordering instead of duration predictions.
**PR target** — Always target the `develop` branch for PRs to AndyMik90/Auto-Claude, NOT `main`.
**PR target** — Always target the `develop` branch for PRs, not `main`. Main is reserved for releases.
**No console.log for debugging production issues**`console.log` output is not visible in bundled/packaged versions of the Electron app. Use Sentry for error tracking and diagnostics in production. Reserve `console.log` for development only.
**No console.log in production code**`console.log` output is invisible in bundled Electron apps. Use Sentry for error tracking in production; reserve `console.log` for development only.
## Work Approach
## Work Approach: Orchestrator-First
**Investigate before speculating** — Always read the actual code before proposing root causes. Spawn agents to grep and read relevant source files before forming any hypothesis. Never guess at causes without evidence from the codebase.
You are an orchestrator. Your primary role is to understand what needs to be done, break it into workstreams, and delegate execution to agent teams. This keeps your context window focused on coordination and decision-making rather than filling up with implementation details.
**Spawn agents for complex tasks** — When tackling complex tasks, spawn sub-agents/agent teams immediately rather than trying to handle everything in a single context window. Never attempt to analyze large codebases or multiple features monolithically.
<orchestrator_pattern>
When given a task, follow this pattern:
**Minimal fixes only** — Prefer the simplest approach (e.g., prompt-only changes, single guard clause) before suggesting multi-component solutions. If the user asks for X, implement X — don't bundle additional fixes they didn't request.
1. **Investigate first** — Read the actual code before forming any hypothesis. Use targeted searches (Glob, Grep, Read) for simple lookups. For broader exploration, spawn an Explore agent.
2. **Plan the approach** — Identify what needs to change, which files are involved, and whether work can be parallelized. For multi-step tasks, create a task list to track workstreams.
3. **Delegate execution** — Spawn agent teams to do the implementation work. Each agent gets a clear, self-contained assignment with all the context it needs: relevant file paths, the specific change to make, and acceptance criteria. Run independent workstreams in parallel.
4. **Verify and integrate** — Review agent outputs, run tests, and ensure changes work together. Fix integration issues or spawn follow-up agents as needed.
</orchestrator_pattern>
**When to delegate vs. do directly:**
- Delegate: multi-file changes, research across the codebase, independent parallel workstreams, tasks that would consume significant context
- Do directly: single-file edits, simple bug fixes, quick lookups, tasks where you already have the context
**Giving agents good assignments** — Each agent works with a fresh context. Include: the specific goal, relevant file paths, code patterns to follow, and what "done" looks like. Agents perform better with explicit, complete instructions than with vague references to "the current task."
**Minimal changes only** — Prefer the simplest approach (e.g., prompt-only changes, single guard clause) before suggesting multi-component solutions. If the user asks for X, implement X — don't bundle additional fixes they didn't request.
**Default to action** — When the user's intent implies making changes, implement them rather than only suggesting. If something is unclear, read the relevant code to fill in the gaps rather than asking. Only ask when genuine ambiguity remains about what the user wants.
## Context Management
Your context window will be automatically compacted as it approaches its limit, allowing you to continue working indefinitely. Do not stop tasks early due to context concerns — instead, persist progress and keep going.
**For long-running tasks:** Use git commits, task lists, and structured notes to track state. When context compacts, review git log and any progress files to re-orient. Focus on incremental progress — complete one component before moving to the next, and commit working states along the way.
**Parallel tool calls** — When reading multiple files, running independent searches, or executing unrelated commands, make all calls in parallel rather than sequentially. This significantly speeds up investigation and implementation.
## Known Gotchas
**Electron path resolution** — For bug fixes in the Electron app, always check path resolution differences between dev and production builds (`app.isPackaged`, `process.resourcesPath`). Paths that work in dev often break when Electron is bundled for production — verify both contexts.
**Electron path resolution** — For bug fixes in the Electron app, check path resolution differences between dev and production builds (`app.isPackaged`, `process.resourcesPath`). Paths that work in dev often break when Electron is bundled for production — verify both contexts.
### Resetting PR Review State
@@ -278,7 +304,7 @@ Supports Windows, macOS, Linux. CI tests all three.
| `findExecutable(name)` | Cross-platform executable lookup |
| `requiresShell(command)` | `.cmd/.bat` shell detection (Win) |
Never hardcode paths. Use `findExecutable()` and `joinPaths()`. See [ARCHITECTURE.md](shared_docs/ARCHITECTURE.md#cross-platform-development) for extended guide.
Use `findExecutable()` and `joinPaths()` instead of hardcoded paths. See [ARCHITECTURE.md](shared_docs/ARCHITECTURE.md#cross-platform-development) for extended guide.
## E2E Testing (Electron MCP)
+445 -5
View File
@@ -13,7 +13,9 @@ import re
from datetime import datetime, timedelta
from pathlib import Path
from context.constants import SKIP_DIRS
from core.client import create_client
from core.file_utils import write_json_atomic
from linear_updater import (
LinearTaskState,
is_linear_enabled,
@@ -84,6 +86,7 @@ from .memory_manager import debug_memory_system_status, get_graphiti_context
from .session import post_session_processing, run_agent_session
from .utils import (
find_phase_for_subtask,
find_subtask_in_plan,
get_commit_count,
get_latest_commit,
load_implementation_plan,
@@ -97,8 +100,383 @@ logger = logging.getLogger(__name__)
# FILE VALIDATION UTILITIES
# =============================================================================
# Directories to exclude from file path search — extends context.constants.SKIP_DIRS
_EXCLUDE_DIRS = frozenset(SKIP_DIRS | {".auto-claude", ".tox", "out"})
def validate_subtask_files(subtask: dict, project_dir: Path) -> dict:
def _build_file_index(
project_dir: Path, suffixes: set[str]
) -> dict[str, list[tuple[str, Path]]]:
"""
Build an index of project files grouped by basename, scanning the tree once.
Also indexes index.{ext} files under their parent directory name as a
secondary key (e.g., api/index.ts is indexed under both "index.ts" and
"api" as directory-stem).
Args:
project_dir: Root directory of the project
suffixes: File extensions to index (e.g., {".ts", ".tsx"})
Returns:
Dict mapping basename -> list of (relative_path_str, Path(relative_path))
"""
index: dict[str, list[tuple[str, Path]]] = {}
resolved_str = str(project_dir.resolve())
for root, dirs, files in os.walk(project_dir.resolve()):
dirs[:] = [d for d in dirs if d not in _EXCLUDE_DIRS]
for filename in files:
ext_idx = filename.rfind(".")
if ext_idx == -1:
continue
file_suffix = filename[ext_idx:]
if file_suffix not in suffixes:
continue
full_path = os.path.join(root, filename)
rel_str = os.path.relpath(full_path, resolved_str).replace(os.sep, "/")
rel_path = Path(rel_str)
# Index by basename
index.setdefault(filename, []).append((rel_str, rel_path))
# Also index index.{ext} files by parent dir name (for stem matching)
stem_part = filename[:ext_idx]
if stem_part == "index":
dir_name = os.path.basename(root)
key = f"__dir_stem__:{dir_name}{file_suffix}"
index.setdefault(key, []).append((rel_str, rel_path))
return index
def _score_and_select(candidates: list[tuple[str, float]]) -> str | None:
"""
Select the best candidate from a scored list of (path, score) pairs.
Requires a minimum score of 8.0 and a gap of at least 3.0 from the
runner-up to avoid ambiguous matches.
Args:
candidates: List of (relative_path, score) tuples
Returns:
Best path if unambiguous, None otherwise
"""
if not candidates:
return None
candidates.sort(key=lambda x: x[1], reverse=True)
best_path, best_score = candidates[0]
if best_score < 8.0:
return None
if len(candidates) > 1:
runner_up_score = candidates[1][1]
if best_score - runner_up_score < 3.0:
return None
return best_path
def _find_correct_path_indexed(
missing_path: str,
parent_parts: tuple[str, ...],
file_index: dict[str, list[tuple[str, Path]]],
) -> str | None:
"""
Find the correct path using a pre-built file index (no tree walk needed).
Args:
missing_path: The incorrect file path from the plan
parent_parts: Parent directory parts of the missing path
file_index: Index built by _build_file_index
Returns:
Corrected relative path, or None if no good match found
"""
missing = Path(missing_path)
basename = missing.name
stem = missing.stem
suffix = missing.suffix
if not suffix:
return None
candidates: list[tuple[str, float]] = []
# Strategy 1: Exact basename match
for rel_str, rel_path in file_index.get(basename, []):
score = 10.0
candidate_parts = rel_path.parent.parts
for i, part in enumerate(parent_parts):
if i < len(candidate_parts) and candidate_parts[i] == part:
score += 3.0
depth_diff = abs(len(candidate_parts) - len(parent_parts))
score -= 0.5 * depth_diff
candidates.append((rel_str, score))
# Strategy 2: index.{ext} in directory matching stem
stem_key = f"__dir_stem__:{stem}{suffix}"
for rel_str, rel_path in file_index.get(stem_key, []):
score = 8.0
candidate_parts = rel_path.parent.parts
for i, part in enumerate(parent_parts):
if i < len(candidate_parts) and candidate_parts[i] == part:
score += 3.0
depth_diff = abs(len(candidate_parts) - len(parent_parts))
score -= 0.5 * depth_diff
candidates.append((rel_str, score))
return _score_and_select(candidates)
def _find_correct_path(missing_path: str, project_dir: Path) -> str | None:
"""
Attempt to find the correct path for a missing file using fuzzy matching.
Strategies:
1. Same basename in nearby directory
2. index.{ext} pattern (e.g., preload/api.ts -> preload/api/index.ts)
Uses os.walk with directory pruning to avoid traversing into node_modules,
.git, dist, etc. — unlike Path.rglob which traverses everything then filters.
Args:
missing_path: The incorrect file path from the plan
project_dir: Root directory of the project
Returns:
Corrected relative path, or None if no good match found
"""
missing = Path(missing_path)
basename = missing.name
stem = missing.stem
suffix = missing.suffix
parent_parts = missing.parent.parts
if not suffix:
return None
candidates: list[tuple[str, float]] = []
resolved_project = project_dir.resolve()
resolved_str = str(resolved_project)
# os.walk with pruning: modify dirs in-place to skip excluded directories
for root, dirs, files in os.walk(resolved_project):
dirs[:] = [d for d in dirs if d not in _EXCLUDE_DIRS]
for filename in files:
if not filename.endswith(suffix):
continue
full_path = os.path.join(root, filename)
rel_str = os.path.relpath(full_path, resolved_str).replace(os.sep, "/")
rel = Path(rel_str)
score = 0.0
# Strategy 1: Exact basename match
if filename == basename:
score += 10.0
# Strategy 2: index.{ext} in directory matching stem
elif filename == f"index{suffix}" and os.path.basename(root) == stem:
score += 8.0
else:
continue
# Bonus: shared parent directory segments
candidate_parts = rel.parent.parts
for i, part in enumerate(parent_parts):
if i < len(candidate_parts) and candidate_parts[i] == part:
score += 3.0
# Penalty: depth difference
depth_diff = abs(len(candidate_parts) - len(parent_parts))
score -= 0.5 * depth_diff
candidates.append((rel_str, score))
return _score_and_select(candidates)
def _auto_correct_subtask_files(
subtask: dict,
missing_files: list[str],
project_dir: Path,
spec_dir: Path,
) -> list[str]:
"""
Attempt to auto-correct missing file paths in a subtask.
Corrects paths in-memory AND persists changes to implementation_plan.json.
Args:
subtask: Subtask dictionary containing files_to_modify
missing_files: List of file paths that don't exist
project_dir: Root directory of the project
spec_dir: Spec directory containing implementation_plan.json
Returns:
List of file paths that could NOT be corrected
"""
corrections: dict[str, str] = {}
still_missing: list[str] = []
# Build file index once for all missing files (avoids repeated os.walk)
suffixes_needed: set[str] = set()
for missing_path in missing_files:
suffix = Path(missing_path).suffix
if suffix:
suffixes_needed.add(suffix)
file_index = (
_build_file_index(project_dir, suffixes_needed) if suffixes_needed else {}
)
for missing_path in missing_files:
missing = Path(missing_path)
corrected = _find_correct_path_indexed(
missing_path, missing.parent.parts, file_index
)
if corrected:
corrections[missing_path] = corrected
logger.info(f"Auto-corrected file path: {missing_path} -> {corrected}")
print_status(f"Auto-corrected: {missing_path} -> {corrected}", "success")
else:
still_missing.append(missing_path)
if not corrections:
return still_missing
# Update subtask in-memory
files_to_modify = subtask.get("files_to_modify", [])
subtask["files_to_modify"] = [corrections.get(f, f) for f in files_to_modify]
# Persist corrections to implementation_plan.json
plan_file = spec_dir / "implementation_plan.json"
if plan_file.exists():
try:
with open(plan_file, encoding="utf-8") as f:
plan = json.load(f)
subtask_id = subtask.get("id")
if subtask_id is not None:
plan_subtask = find_subtask_in_plan(plan, subtask_id)
if plan_subtask:
plan_files = plan_subtask.get("files_to_modify", [])
plan_subtask["files_to_modify"] = [
corrections.get(f, f) for f in plan_files
]
write_json_atomic(plan_file, plan)
logger.info(
f"Persisted {len(corrections)} path correction(s) to implementation_plan.json"
)
except (OSError, TypeError, ValueError) as e:
logger.warning(f"Failed to persist path corrections: {e}")
return still_missing
def _validate_plan_file_paths(spec_dir: Path, project_dir: Path) -> str | None:
"""
Validate all file paths in the implementation plan after planning.
Builds a file index once, then checks all paths across all subtasks against it.
Attempts auto-correction for missing paths. Returns a retry context string for
the planner if uncorrectable paths remain, or None if all paths are valid.
Args:
spec_dir: Spec directory containing implementation_plan.json
project_dir: Root directory of the project
Returns:
Retry context string if issues remain, None if all OK
"""
plan_file = spec_dir / "implementation_plan.json"
if not plan_file.exists():
return None
try:
with open(plan_file, encoding="utf-8") as f:
plan = json.load(f)
except (OSError, json.JSONDecodeError, UnicodeDecodeError):
return None
resolved_project = project_dir.resolve()
# First pass: collect all missing files and their suffixes
missing_entries: list[
tuple[list[str], int, str]
] = [] # (subtask_files_list, index, path)
suffixes_needed: set[str] = set()
for phase in plan.get("phases", []):
for subtask in phase.get("subtasks", []):
files = subtask.get("files_to_modify", [])
for i, file_path in enumerate(files):
full_path = (resolved_project / file_path).resolve()
if not full_path.is_relative_to(resolved_project):
continue
if full_path.exists():
continue
missing = Path(file_path)
if missing.suffix:
suffixes_needed.add(missing.suffix)
missing_entries.append((files, i, file_path))
if not missing_entries:
return None
# Build index once for all needed suffixes
file_index = _build_file_index(project_dir, suffixes_needed)
all_missing: list[str] = []
corrections_made = 0
for files_list, idx, file_path in missing_entries:
missing = Path(file_path)
corrected = _find_correct_path_indexed(
file_path, missing.parent.parts, file_index
)
if corrected:
files_list[idx] = corrected
corrections_made += 1
logger.info(f"Post-plan auto-corrected: {file_path} -> {corrected}")
print_status(f"Auto-corrected: {file_path} -> {corrected}", "success")
else:
all_missing.append(file_path)
# Persist any corrections that were made
if corrections_made > 0:
try:
write_json_atomic(plan_file, plan)
logger.info(f"Persisted {corrections_made} post-plan path correction(s)")
except (OSError, TypeError, ValueError) as e:
logger.warning(f"Failed to persist post-plan corrections: {e}")
if not all_missing:
return None
return (
"## FILE PATH VALIDATION ERRORS\n\n"
"The following files referenced in your implementation plan do NOT exist "
"and could not be auto-corrected:\n"
+ "\n".join(f"- `{p}`" for p in all_missing)
+ "\n\nPlease fix these file paths in the `implementation_plan.json`.\n"
"Use the project's actual file structure to find the correct paths.\n"
"Common issues: wrong directory nesting, missing index files "
"(e.g., `dir/file.ts` should be `dir/file/index.ts`)."
)
def validate_subtask_files(
subtask: dict, project_dir: Path, spec_dir: Path | None = None
) -> dict:
"""
Validate all files_to_modify exist before subtask execution.
@@ -136,6 +514,15 @@ def validate_subtask_files(subtask: dict, project_dir: Path) -> dict:
}
if missing_files:
# Attempt auto-correction if spec_dir is provided
if spec_dir:
still_missing = _auto_correct_subtask_files(
subtask, missing_files, project_dir, spec_dir
)
if not still_missing:
return {"success": True, "missing_files": [], "invalid_paths": []}
missing_files = still_missing
return {
"success": False,
"error": f"Planned files do not exist: {', '.join(missing_files)}",
@@ -685,7 +1072,10 @@ async def run_autonomous_agent(
# Validate that all files_to_modify exist before attempting execution
# This prevents infinite retry loops when implementation plan references non-existent files
validation_result = validate_subtask_files(next_subtask, project_dir)
# Pass spec_dir to enable auto-correction of wrong paths
validation_result = validate_subtask_files(
next_subtask, project_dir, spec_dir
)
if not validation_result["success"]:
# File validation failed - record error and skip session
error_msg = validation_result["error"]
@@ -719,6 +1109,11 @@ async def run_autonomous_agent(
subtask_id,
f"File validation failed after {attempt_count} attempts: {error_msg}",
)
emit_phase(
ExecutionPhase.FAILED,
f"Subtask {subtask_id} stuck: file validation failed",
subtask=subtask_id,
)
print_status(
f"Subtask {subtask_id} marked as STUCK after {attempt_count} failed validation attempts",
"error",
@@ -812,8 +1207,28 @@ async def run_autonomous_agent(
if is_planning_phase and status != "error":
valid, errors = _validate_and_fix_implementation_plan()
if valid:
plan_validated = True
planning_retry_context = None
# Fix 5: Validate file paths in the newly created plan
path_issues = _validate_plan_file_paths(spec_dir, project_dir)
if (
path_issues
and planning_validation_failures < max_planning_validation_retries
):
planning_validation_failures += 1
planning_retry_context = path_issues
print_status(
"Plan has invalid file paths - retrying planner",
"warning",
)
first_run = True
status = "continue"
else:
if path_issues:
logger.warning(
f"Plan has uncorrectable file paths after "
f"{planning_validation_failures} retries - proceeding anyway"
)
plan_validated = True
planning_retry_context = None
else:
planning_validation_failures += 1
if planning_validation_failures >= max_planning_validation_retries:
@@ -871,6 +1286,11 @@ async def run_autonomous_agent(
recovery_manager.mark_subtask_stuck(
subtask_id, f"Failed after {attempt_count} attempts"
)
emit_phase(
ExecutionPhase.FAILED,
f"Subtask {subtask_id} stuck after {attempt_count} attempts",
subtask=subtask_id,
)
print()
print_status(
f"Subtask {subtask_id} marked as STUCK after {attempt_count} attempts",
@@ -1230,4 +1650,24 @@ async def run_autonomous_agent(
if completed == total:
status_manager.update(state=BuildState.COMPLETE)
else:
status_manager.update(state=BuildState.PAUSED)
# Check if all remaining subtasks are stuck — if so, this is an error, not a pause
all_remaining_stuck = False
if stuck_subtasks:
stuck_ids = {s["subtask_id"] for s in stuck_subtasks}
plan = load_implementation_plan(spec_dir)
if plan:
all_remaining_stuck = True
for phase in plan.get("phases", []):
for s in phase.get("subtasks", []):
if s.get("status") != "completed":
if s.get("id") not in stuck_ids:
all_remaining_stuck = False
break
if not all_remaining_stuck:
break
if all_remaining_stuck and stuck_subtasks:
emit_phase(ExecutionPhase.FAILED, "All remaining subtasks are stuck")
status_manager.update(state=BuildState.ERROR)
else:
status_manager.update(state=BuildState.PAUSED)
+6 -2
View File
@@ -101,8 +101,12 @@ def handle_qa_command(
print("\n✅ Build already approved by QA.")
else:
completed, total = count_subtasks(spec_dir)
print(f"\n❌ Build not complete ({completed}/{total} subtasks).")
print("Complete all subtasks before running QA validation.")
print(
f"\n❌ Build not ready for QA ({completed}/{total} subtasks completed)."
)
print(
"All subtasks must reach a terminal state (completed, failed, or stuck) before running QA."
)
return
if has_human_feedback:
+64 -17
View File
@@ -115,6 +115,65 @@ def is_build_complete(spec_dir: Path) -> bool:
return total > 0 and completed == total
def _load_stuck_subtask_ids(spec_dir: Path) -> set[str]:
"""Load IDs of subtasks marked as stuck from attempt_history.json."""
stuck_subtask_ids: set[str] = set()
attempt_history_file = spec_dir / "memory" / "attempt_history.json"
if attempt_history_file.exists():
try:
with open(attempt_history_file, encoding="utf-8") as f:
attempt_history = json.load(f)
for entry in attempt_history.get("stuck_subtasks", []):
if "subtask_id" in entry:
stuck_subtask_ids.add(entry["subtask_id"])
except (OSError, json.JSONDecodeError, UnicodeDecodeError):
# Corrupted attempt history is non-fatal; skip stuck-subtask filtering
pass
return stuck_subtask_ids
def is_build_ready_for_qa(spec_dir: Path) -> bool:
"""
Check if the build is ready for QA validation.
Unlike is_build_complete() which requires all subtasks to be "completed",
this function considers the build ready when all subtasks have reached
a terminal state: completed, failed, or stuck (exhausted retries in attempt_history.json).
Args:
spec_dir: Directory containing implementation_plan.json
Returns:
True if all subtasks are in a terminal state, False otherwise
"""
plan_file = spec_dir / "implementation_plan.json"
if not plan_file.exists():
return False
stuck_subtask_ids = _load_stuck_subtask_ids(spec_dir)
try:
with open(plan_file, encoding="utf-8") as f:
plan = json.load(f)
total = 0
terminal = 0
for phase in plan.get("phases", []):
for subtask in phase.get("subtasks", []):
total += 1
status = subtask.get("status", "pending")
subtask_id = subtask.get("id")
if status in ("completed", "failed") or subtask_id in stuck_subtask_ids:
terminal += 1
return total > 0 and terminal == total
except (OSError, json.JSONDecodeError, UnicodeDecodeError):
return False
def get_progress_percentage(spec_dir: Path) -> float:
"""
Get the progress as a percentage.
@@ -420,22 +479,7 @@ def get_next_subtask(spec_dir: Path) -> dict | None:
if not plan_file.exists():
return None
# Load stuck subtasks from recovery manager's attempt history
stuck_subtask_ids = set()
attempt_history_file = spec_dir / "memory" / "attempt_history.json"
if attempt_history_file.exists():
try:
with open(attempt_history_file, encoding="utf-8") as f:
attempt_history = json.load(f)
# Collect IDs of subtasks marked as stuck
stuck_subtask_ids = {
entry["subtask_id"]
for entry in attempt_history.get("stuck_subtasks", [])
if "subtask_id" in entry
}
except (OSError, json.JSONDecodeError, UnicodeDecodeError):
# If we can't read the file, continue without stuck checking
pass
stuck_subtask_ids = _load_stuck_subtask_ids(spec_dir)
try:
with open(plan_file, encoding="utf-8") as f:
@@ -454,8 +498,11 @@ def get_next_subtask(spec_dir: Path) -> dict | None:
str(phase_id_raw) if phase_id_raw is not None else f"unknown:{i}"
)
subtasks = phase.get("subtasks", phase.get("chunks", []))
# Stuck subtasks count as "resolved" for phase dependency purposes.
# This prevents one stuck subtask from blocking all downstream phases.
phase_complete[phase_id_key] = all(
s.get("status") == "completed" for s in subtasks
s.get("status") == "completed" or s.get("id") in stuck_subtask_ids
for s in subtasks
)
# Find next available subtask
@@ -9,9 +9,10 @@ Each dependency ecosystem has different constraints:
- **node_modules**: Safe to symlink. Node's resolution algorithm follows symlinks
correctly, and the directory is self-contained.
- **venv / .venv**: Must be recreated. Python's ``pyvenv.cfg`` discovery walks the
real directory hierarchy without resolving symlinks (CPython bug #106045), so a
symlinked venv resolves paths relative to the *target*, not the worktree.
- **venv / .venv**: Symlinked for fast worktree creation. CPython bug #106045
(pyvenv.cfg symlink resolution) does not affect typical usage (running scripts,
imports, pip). A health check after symlinking verifies usability; if it fails,
the caller falls back to recreating the venv.
- **vendor (PHP)**: Safe to symlink. Composer's autoloader uses ``__DIR__``-relative
paths that resolve correctly through symlinks.
@@ -42,9 +43,9 @@ from .models import DependencyShareConfig, DependencyStrategy
DEFAULT_STRATEGY_MAP: dict[str, DependencyStrategy] = {
# JavaScript / Node.js — symlink is safe and fast
"node_modules": DependencyStrategy.SYMLINK,
# Python — venvs MUST be recreated (pyvenv.cfg symlink bug)
"venv": DependencyStrategy.RECREATE,
".venv": DependencyStrategy.RECREATE,
# Python — symlink for fast worktree creation (health check + fallback to recreate)
"venv": DependencyStrategy.SYMLINK,
".venv": DependencyStrategy.SYMLINK,
# PHP — Composer vendor dir is safe to symlink
"vendor_php": DependencyStrategy.SYMLINK,
# Ruby — Bundler vendor/bundle is safe to symlink
+5 -6
View File
@@ -278,12 +278,11 @@ class SpecNumberLock:
class DependencyStrategy(Enum):
"""Strategy for sharing dependency directories across worktrees.
SYMLINK is fast but unsafe for certain ecosystems. Notably, Python venv
breaks when symlinked because CPython's pyvenv.cfg discovery walks the
real directory hierarchy without resolving symlinks first
(CPython bug #106045). This means a symlinked venv resolves its home
path relative to the symlink target's parent, not the worktree, causing
import failures and broken interpreters.
SYMLINK is fast and now safe for Python venvs with runtime health checks.
A post-symlink health check validates the venv is usable, automatically
falling back to RECREATE if the symlink is broken. This works around
CPython's pyvenv.cfg discovery issue (CPython bug #106045) while maintaining
fast worktree creation in the common case where symlinking succeeds.
"""
SYMLINK = "symlink" # Create a symlink to the source (fast, works for node_modules)
+140 -26
View File
@@ -50,6 +50,10 @@ _git_hook_check_done = False
MODULE = "workspace.setup"
# Marker file written inside a recreated venv to indicate setup completed successfully.
# If the marker is absent, the venv is treated as incomplete and will be rebuilt.
VENV_SETUP_COMPLETE_MARKER = ".setup_complete"
def choose_workspace(
project_dir: Path,
@@ -624,9 +628,52 @@ def setup_worktree_dependencies(
results[strategy_name] = []
try:
performed = True
performed = False
if config.strategy == DependencyStrategy.SYMLINK:
performed = _apply_symlink_strategy(project_dir, worktree_path, config)
# For venvs, verify the symlink is usable — fall back to recreate
# Run health check whenever a venv symlink exists (not just on creation)
if config.dep_type in ("venv", ".venv"):
venv_path = worktree_path / config.source_rel_path
# Check if venv exists (symlinked or otherwise)
if venv_path.exists() or venv_path.is_symlink():
if is_windows():
python_bin = str(venv_path / "Scripts" / "python.exe")
else:
python_bin = str(venv_path / "bin" / "python")
try:
subprocess.run(
[python_bin, "-c", "import sys; print(sys.prefix)"],
capture_output=True,
text=True,
timeout=10,
check=True,
)
debug(
MODULE,
f"Symlinked venv health check passed: {config.source_rel_path}",
)
except (subprocess.SubprocessError, OSError):
debug_warning(
MODULE,
f"Symlinked venv health check failed, falling back to recreate: {config.source_rel_path}",
)
# Remove the broken symlink and recreate
try:
if venv_path.is_symlink():
venv_path.unlink()
elif venv_path.exists():
shutil.rmtree(venv_path, ignore_errors=True)
except OSError:
pass # Best-effort removal; recreate strategy handles existing paths
performed = _apply_recreate_strategy(
project_dir, worktree_path, config
)
# Update strategy name to reflect fallback
if performed:
strategy_name = "recreate"
# Ensure the key exists for the fallback strategy
results.setdefault(strategy_name, [])
elif config.strategy == DependencyStrategy.RECREATE:
performed = _apply_recreate_strategy(project_dir, worktree_path, config)
elif config.strategy == DependencyStrategy.COPY:
@@ -707,6 +754,54 @@ def _apply_symlink_strategy(
return False
def _popen_with_cleanup(
cmd: list[str],
timeout: int,
label: str,
) -> tuple[int, str, str]:
"""Run a command via Popen with proper process cleanup on timeout.
On timeout: terminate → wait(10) → kill → wait(5) to ensure file locks
are released before any cleanup (e.g. shutil.rmtree).
Returns (returncode, stdout, stderr).
Raises subprocess.TimeoutExpired if the command exceeds the given timeout (after cleanup is attempted).
"""
proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
try:
stdout, stderr = proc.communicate(timeout=timeout)
return proc.returncode, stdout, stderr
except subprocess.TimeoutExpired:
debug_warning(MODULE, f"{label} timed out, terminating process")
proc.terminate()
try:
proc.communicate(timeout=10)
except subprocess.TimeoutExpired:
debug_warning(MODULE, f"{label} did not terminate, killing process")
proc.kill()
try:
proc.communicate(timeout=5)
except subprocess.TimeoutExpired:
# Final cleanup attempt if kill() also hangs
debug_warning(MODULE, f"{label} could not be stopped even after kill()")
raise
finally:
# Ensure pipes are closed and process is reaped to avoid zombie processes
if proc.stdout:
proc.stdout.close()
if proc.stderr:
proc.stderr.close()
try:
proc.wait(timeout=0.1)
except subprocess.TimeoutExpired:
pass # Process still running, already logged warning above
def _apply_recreate_strategy(
project_dir: Path,
worktree_path: Path,
@@ -717,10 +812,25 @@ def _apply_recreate_strategy(
Returns True if the venv was successfully created, False if skipped or failed.
"""
venv_path = worktree_path / config.source_rel_path
marker_path = venv_path / VENV_SETUP_COMPLETE_MARKER
if venv_path.exists():
debug(MODULE, f"Skipping recreate {config.source_rel_path} - already exists")
return False
# Check for broken symlinks that exists() would miss
if venv_path.is_symlink() and not venv_path.exists():
debug(MODULE, f"Removing broken symlink at {config.source_rel_path}")
try:
venv_path.unlink()
except OSError:
pass # Best-effort removal
elif venv_path.exists():
if marker_path.exists():
debug(
MODULE,
f"Skipping recreate {config.source_rel_path} - already complete (marker present)",
)
return False
# Venv exists but marker is missing — incomplete, remove and rebuild
debug(MODULE, f"Removing incomplete venv {config.source_rel_path} (no marker)")
shutil.rmtree(venv_path, ignore_errors=True)
# Detect Python executable from the source venv or fall back to sys.executable
source_venv = project_dir / config.source_rel_path
@@ -737,29 +847,34 @@ def _apply_recreate_strategy(
# Create the venv
try:
debug(MODULE, f"Creating venv at {venv_path}")
result = subprocess.run(
returncode, _, stderr = _popen_with_cleanup(
[python_exec, "-m", "venv", str(venv_path)],
capture_output=True,
text=True,
timeout=120,
label=f"venv creation ({config.source_rel_path})",
)
if result.returncode != 0:
debug_warning(MODULE, f"venv creation failed: {result.stderr}")
if returncode != 0:
debug_warning(MODULE, f"venv creation failed: {stderr}")
print_status(
f"Warning: Could not create venv at {config.source_rel_path}",
"warning",
)
# Clean up partial venv so retries aren't blocked
if venv_path.exists():
shutil.rmtree(venv_path, ignore_errors=True)
return False
except subprocess.TimeoutExpired:
debug_warning(MODULE, f"venv creation timed out for {config.source_rel_path}")
print_status(
f"Warning: venv creation timed out for {config.source_rel_path}",
"warning",
)
# Clean up partial venv so retries aren't blocked
if venv_path.exists():
shutil.rmtree(venv_path, ignore_errors=True)
return False
except OSError as e:
debug_warning(MODULE, f"venv creation failed: {e}")
print_status(
f"Warning: Could not create venv at {config.source_rel_path}",
"warning",
)
if venv_path.exists():
shutil.rmtree(venv_path, ignore_errors=True)
return False
@@ -800,46 +915,45 @@ def _apply_recreate_strategy(
if install_cmd:
try:
debug(MODULE, f"Installing deps from {req_file}")
pip_result = subprocess.run(
returncode, _, stderr = _popen_with_cleanup(
install_cmd,
capture_output=True,
text=True,
timeout=120,
timeout=300,
label=f"pip install ({req_file})",
)
if pip_result.returncode != 0:
if returncode != 0:
debug_warning(
MODULE,
f"pip install failed (exit {pip_result.returncode}): "
f"{pip_result.stderr}",
f"pip install failed (exit {returncode}): {stderr}",
)
print_status(
f"Warning: Dependency install failed for {req_file}",
"warning",
)
# Clean up broken venv so retries aren't blocked
if venv_path.exists():
shutil.rmtree(venv_path, ignore_errors=True)
return False
except subprocess.TimeoutExpired:
debug_warning(
MODULE,
f"pip install timed out for {req_file}",
)
print_status(
f"Warning: Dependency install timed out for {req_file}",
"warning",
)
# Clean up broken venv so retries aren't blocked
if venv_path.exists():
shutil.rmtree(venv_path, ignore_errors=True)
return False
except OSError as e:
debug_warning(MODULE, f"pip install failed: {e}")
# Clean up broken venv so retries aren't blocked
if venv_path.exists():
shutil.rmtree(venv_path, ignore_errors=True)
return False
# Write completion marker so future runs know this venv is complete
try:
marker_path.touch()
except OSError as e:
debug_warning(
MODULE, f"Failed to write completion marker at {marker_path}: {e}"
)
debug(MODULE, f"Recreated venv at {config.source_rel_path}")
return True
+13 -3
View File
@@ -635,10 +635,20 @@ def get_graphiti_status() -> dict:
try:
# Attempt to import the main graphiti_memory module
import graphiti_core # noqa: F401
from graphiti_core.driver.falkordb_driver import FalkorDriver # noqa: F401
# If we got here, packages are importable
status["available"] = True # pragma: no cover
# Try LadybugDB first (preferred for Python 3.12+), fall back to kuzu
try:
import real_ladybug # noqa: F401
except ImportError:
try:
import kuzu # noqa: F401
except ImportError:
status["available"] = False
status["reason"] = (
"Graph database backend not installed (need real_ladybug or kuzu)"
)
return status
status["available"] = True
except ImportError as e:
status["available"] = False
status["reason"] = f"Graphiti packages not installed: {e}"
@@ -81,16 +81,16 @@ def mock_graphiti_core():
@pytest.fixture
def mock_falkor_driver():
"""Mock graphiti_core.driver.falkordb_driver.FalkorDriver.
def mock_kuzu_driver():
"""Mock graphiti_core.driver.kuzu_driver.KuzuDriver.
Prevents actual FalkorDB connections during tests.
Prevents actual LadybugDB/kuzu connections during tests.
Yields:
tuple: (mock_driver_class, mock_driver_instance)
"""
with patch(
"integrations.graphiti.queries_pkg.graphiti.graphiti_core.driver.falkordb_driver.FalkorDriver"
"integrations.graphiti.queries_pkg.graphiti.graphiti_core.driver.kuzu_driver.KuzuDriver"
) as mock_driver:
mock_instance = MagicMock()
mock_driver.return_value = mock_instance
@@ -15,7 +15,7 @@ Tests cover:
import json
import os
from pathlib import Path
from unittest.mock import patch
from unittest.mock import MagicMock, patch
import pytest
from integrations.graphiti.config import (
@@ -1054,20 +1054,48 @@ class TestModuleLevelFunctions:
assert "OPENAI_API_KEY" in status["errors"][0]
def test_get_graphiti_status_invalid_config_sets_reason(self, clean_env):
"""Test get_graphiti_status sets reason when config is invalid.
"""Test get_graphiti_status with validation errors (embedder misconfigured).
This tests lines 628-629 where the reason is set from validation errors.
When packages are installed but embedder config has errors, available should
still be True (embedder is optional - keyword search fallback exists).
Validation errors are reported in the errors list for informational purposes.
"""
os.environ["GRAPHITI_ENABLED"] = "true"
os.environ["GRAPHITI_EMBEDDER_PROVIDER"] = "voyage"
status = get_graphiti_status()
# Mock imports to ensure test is independent of environment
with patch.dict(
"sys.modules",
{"graphiti_core": MagicMock(), "real_ladybug": MagicMock()},
):
status = get_graphiti_status()
assert status["enabled"] is True
# available depends on whether mocked packages are resolved correctly;
# sys.modules patching should make imports succeed, but guard against
# environment quirks (consistent with test_get_graphiti_status_enabled)
assert status["available"] is True
assert len(status["errors"]) > 0
assert "VOYAGE_API_KEY" in status["errors"][0]
def test_get_graphiti_status_no_graph_backend(self, clean_env):
"""Test get_graphiti_status when graphiti_core exists but no graph DB backend.
This tests the error path in config.py lines 645-650 where graphiti_core
imports successfully but neither real_ladybug nor kuzu is available.
"""
os.environ["GRAPHITI_ENABLED"] = "true"
# Mock graphiti_core as present, but ensure real_ladybug and kuzu are absent
with patch.dict(
"sys.modules",
{"graphiti_core": MagicMock(), "real_ladybug": None, "kuzu": None},
):
status = get_graphiti_status()
assert status["enabled"] is True
assert status["available"] is False
# When config is invalid, reason should be set from errors
assert status["reason"] != ""
assert len(status["errors"]) > 0
assert "real_ladybug or kuzu" in status["reason"]
@pytest.mark.slow
def test_get_graphiti_status_with_graphiti_installed(self, clean_env):
@@ -1089,9 +1117,9 @@ class TestModuleLevelFunctions:
assert "reason" in status
assert "errors" in status
# Note: Line 641 (status["available"] = True) requires falkordb to be installed.
# Since falkordb is not installed in the test environment, that line is marked
# with pragma: no cover. The except clause (lines 642-644) is tested here.
# Note: Line 644 (status["available"] = True) requires LadybugDB/kuzu to be installed.
# Since LadybugDB/kuzu may not be installed in all test environments, that line
# may be marked with pragma: no cover. The except clause is tested here.
def test_get_available_providers_empty(self, clean_env):
"""Test get_available_providers with no credentials."""
@@ -264,7 +264,7 @@ class TestTestGraphitiConnection:
# Mock graphiti_core imports to succeed
mock_graphiti = MagicMock()
mock_falkordb_driver = MagicMock()
mock_kuzu_driver = MagicMock()
# Mock provider creation to raise ProviderError
with patch("graphiti_providers.create_llm_client") as mock_create_llm:
@@ -275,7 +275,7 @@ class TestTestGraphitiConnection:
{
"graphiti_core": MagicMock(Graphiti=mock_graphiti),
"graphiti_core.driver": MagicMock(),
"graphiti_core.driver.falkordb_driver": mock_falkordb_driver,
"graphiti_core.driver.kuzu_driver": mock_kuzu_driver,
"graphiti_providers": MagicMock(
ProviderError=ProviderError,
create_embedder=MagicMock(),
@@ -160,7 +160,7 @@ class TestTestGraphitiConnection:
"""Tests for the test_graphiti_connection async function.
Note: The function now uses embedded LadybugDB via patched KuzuDriver
instead of remote FalkorDB with host/port credentials.
instead of remote database with host/port credentials.
"""
@pytest.mark.asyncio
+2
View File
@@ -14,6 +14,7 @@ from core.progress import (
get_plan_summary,
get_progress_percentage,
is_build_complete,
is_build_ready_for_qa,
print_build_complete_banner,
print_paused_banner,
print_progress_summary,
@@ -29,6 +30,7 @@ __all__ = [
"get_plan_summary",
"get_progress_percentage",
"is_build_complete",
"is_build_ready_for_qa",
"print_build_complete_banner",
"print_paused_banner",
"print_progress_summary",
+3 -3
View File
@@ -8,7 +8,7 @@ Manages acceptance criteria validation and status tracking.
import json
from pathlib import Path
from progress import is_build_complete
from progress import is_build_ready_for_qa
# =============================================================================
# IMPLEMENTATION PLAN I/O
@@ -95,10 +95,10 @@ def should_run_qa(spec_dir: Path) -> bool:
Determine if QA validation should run.
QA should run when:
- All subtasks are completed
- All subtasks have reached a terminal state (completed, failed, or stuck)
- QA has not yet approved
"""
if not is_build_complete(spec_dir):
if not is_build_ready_for_qa(spec_dir):
return False
if is_qa_approved(spec_dir):
+20 -13
View File
@@ -28,7 +28,7 @@ from phase_config import (
get_phase_model_betas,
)
from phase_event import ExecutionPhase, emit_phase
from progress import count_subtasks, is_build_complete
from progress import count_subtasks, is_build_ready_for_qa
from security.constants import PROJECT_DIR_ENV_VAR
from task_logger import (
LogPhase,
@@ -114,14 +114,25 @@ async def run_qa_validation_loop(
# Initialize task logger for the validation phase
task_logger = get_task_logger(spec_dir)
# Verify build is complete
if not is_build_complete(spec_dir):
debug_warning("qa_loop", "Build is not complete, cannot run QA")
print("\n❌ Build is not complete. Cannot run QA validation.")
completed, total = count_subtasks(spec_dir)
debug("qa_loop", "Build progress", completed=completed, total=total)
print(f" Progress: {completed}/{total} subtasks completed")
return False
# Check if there's pending human feedback that needs to be processed
fix_request_file = spec_dir / "QA_FIX_REQUEST.md"
has_human_feedback = fix_request_file.exists()
# Human feedback takes priority — if the user explicitly asked to proceed,
# skip the build completeness gate entirely
if not has_human_feedback:
# Verify build is ready for QA (all subtasks in terminal state)
if not is_build_ready_for_qa(spec_dir):
debug_warning(
"qa_loop", "Build is not ready for QA - subtasks still in progress"
)
print("\n❌ Build is not ready for QA validation.")
completed, total = count_subtasks(spec_dir)
debug("qa_loop", "Build progress", completed=completed, total=total)
print(
f" Progress: {completed}/{total} subtasks in terminal state (completed/failed/stuck)"
)
return False
# Emit phase event at start of QA validation (before any early returns)
emit_phase(ExecutionPhase.QA_REVIEW, "Starting QA validation")
@@ -136,10 +147,6 @@ async def run_qa_validation_loop(
f"[Fast Mode] {'ENABLED' if fast_mode else 'disabled'} for QA validation",
)
# Check if there's pending human feedback that needs to be processed
fix_request_file = spec_dir / "QA_FIX_REQUEST.md"
has_human_feedback = fix_request_file.exists()
# Check if already approved - but if there's human feedback, we need to process it first
if is_qa_approved(spec_dir) and not has_human_feedback:
debug_success("qa_loop", "Build already approved by QA")
+155 -7
View File
@@ -8,8 +8,10 @@ about a codebase. It can also suggest tasks based on the conversation.
import argparse
import asyncio
import base64
import json
import sys
import tempfile
from pathlib import Path
# Add auto-claude to path
@@ -111,6 +113,107 @@ def load_project_context(project_dir: str) -> str:
)
ALLOWED_MIME_TYPES = frozenset(
["image/png", "image/jpeg", "image/jpg", "image/gif", "image/webp"]
)
MAX_IMAGE_FILE_SIZE = 10 * 1024 * 1024 # 10 MB (aligned with frontend MAX_IMAGE_SIZE)
def load_images_from_manifest(manifest_path: str) -> list[dict]:
"""Load images from a manifest JSON file.
The manifest contains an array of objects with 'path' and 'mimeType' fields.
Each image file is read as binary and encoded to base64.
Returns a list of dicts with 'media_type' and 'data' (base64-encoded) fields.
"""
images = []
tmp_dir = Path(tempfile.gettempdir()).resolve()
try:
with open(manifest_path, encoding="utf-8") as f:
manifest = json.load(f)
for entry in manifest:
image_path = entry.get("path")
mime_type = entry.get("mimeType", "image/png")
if not image_path:
debug_error(
"insights_runner",
"Image entry missing path field",
)
continue
# Validate path is within temp directory before checking existence
try:
resolved = Path(image_path).resolve()
if not resolved.is_relative_to(tmp_dir):
debug_error(
"insights_runner",
f"Image path outside temp directory, skipping: {image_path}",
)
continue
except (ValueError, OSError):
debug_error(
"insights_runner",
f"Invalid image path, skipping: {image_path}",
)
continue
if not resolved.exists():
debug_error(
"insights_runner",
f"Image file not found: {image_path}",
)
continue
# Validate MIME type against allowlist
if mime_type not in ALLOWED_MIME_TYPES:
debug_error(
"insights_runner",
f"Invalid MIME type '{mime_type}', skipping: {image_path}",
)
continue
# Validate file size
file_size = resolved.stat().st_size
if file_size > MAX_IMAGE_FILE_SIZE:
debug_error(
"insights_runner",
f"Image too large ({file_size} bytes), skipping: {image_path}",
)
continue
try:
with open(resolved, "rb") as img_f:
image_data = base64.b64encode(img_f.read()).decode("utf-8")
images.append(
{
"media_type": mime_type,
"data": image_data,
}
)
debug(
"insights_runner",
"Loaded image",
path=image_path,
mime_type=mime_type,
size_bytes=file_size,
)
except Exception as e:
debug_error(
"insights_runner",
f"Failed to read image {image_path}: {e}",
)
except (json.JSONDecodeError, OSError) as e:
debug_error("insights_runner", f"Failed to load images manifest: {e}")
return images
def build_system_prompt(project_dir: str) -> str:
"""Build the system prompt for the insights agent."""
context = load_project_context(project_dir)
@@ -143,11 +246,12 @@ async def run_with_sdk(
history: list,
model: str = "sonnet", # Shorthand - resolved via API Profile if configured
thinking_level: str = "medium",
images: list[dict] | None = None,
) -> None:
"""Run the chat using Claude SDK with streaming."""
if not SDK_AVAILABLE:
print("Claude SDK not available, falling back to simple mode", file=sys.stderr)
run_simple(project_dir, message, history)
run_simple(project_dir, message, history, images)
return
if not get_auth_token():
@@ -155,7 +259,7 @@ async def run_with_sdk(
"No authentication token found, falling back to simple mode",
file=sys.stderr,
)
run_simple(project_dir, message, history)
run_simple(project_dir, message, history, images)
return
# Ensure SDK can find the token
@@ -205,8 +309,24 @@ Current question: {message}"""
# Use async context manager pattern
async with client:
# Send the query
await client.query(full_prompt)
# Build the query - images are stored for reference but SDK doesn't support multi-modal input yet
if images:
debug(
"insights_runner",
"Images attached but SDK does not support multi-modal input",
image_count=len(images),
)
# TODO: When the SDK adds support for multi-modal content blocks, update this.
image_note = f"\n\n[Note: The user attached {len(images)} image(s), but the current SDK version does not support multi-modal input. Please ask the user to describe the image content instead.]"
print(
"Warning: Image attachments cannot be sent to the model in SDK mode. Sending text-only query.",
file=sys.stderr,
)
await client.query(full_prompt + image_note)
else:
# Send the query as plain text
await client.query(full_prompt)
# Stream the response
response_text = ""
@@ -280,13 +400,21 @@ Current question: {message}"""
import traceback
traceback.print_exc(file=sys.stderr)
run_simple(project_dir, message, history)
run_simple(project_dir, message, history, images)
def run_simple(project_dir: str, message: str, history: list) -> None:
def run_simple(
project_dir: str, message: str, history: list, images: list[dict] | None = None
) -> None:
"""Simple fallback mode without SDK - uses subprocess to call claude CLI."""
import subprocess
if images:
print(
"Warning: Image attachments are not supported in simple mode and will be skipped.",
file=sys.stderr,
)
system_prompt = build_system_prompt(project_dir)
# Build conversation context
@@ -355,6 +483,10 @@ def main():
default="medium",
help="Thinking level for extended reasoning (low, medium, high)",
)
parser.add_argument(
"--images-file",
help="Path to JSON manifest file listing image file paths and MIME types",
)
args = parser.parse_args()
# Validate and sanitize thinking level (handles legacy values like 'ultrathink')
@@ -398,9 +530,25 @@ def main():
debug_error("insights_runner", f"Failed to load history: {e}")
history = []
# Load images from manifest file if provided
images = None
if args.images_file:
debug("insights_runner", "Loading images from manifest", file=args.images_file)
images = load_images_from_manifest(args.images_file)
if images:
debug(
"insights_runner",
"Loaded images for multi-modal query",
image_count=len(images),
)
else:
debug("insights_runner", "No valid images loaded from manifest")
# Run the async SDK function
debug("insights_runner", "Running SDK query")
asyncio.run(run_with_sdk(project_dir, user_message, history, model, thinking_level))
asyncio.run(
run_with_sdk(project_dir, user_message, history, model, thinking_level, images)
)
debug_success("insights_runner", "Query completed")
@@ -31,6 +31,7 @@ class CompetitorAnalyzer:
self.refresh = refresh
self.agent_executor = agent_executor
self.analysis_file = output_dir / "competitor_analysis.json"
self.manual_competitors_file = output_dir / "manual_competitors.json"
self.discovery_file = output_dir / "roadmap_discovery.json"
self.project_index_file = output_dir / "project_index.json"
@@ -42,7 +43,10 @@ class CompetitorAnalyzer:
"""
if not enabled:
print_status("Competitor analysis not enabled, skipping", "info")
manual_competitors = self._get_manual_competitors()
self._create_disabled_analysis_file()
if manual_competitors:
self._merge_manual_competitors(manual_competitors)
return RoadmapPhaseResult(
"competitor_analysis", True, [str(self.analysis_file)], [], 0
)
@@ -53,6 +57,9 @@ class CompetitorAnalyzer:
"competitor_analysis", True, [str(self.analysis_file)], [], 0
)
# Preserve manual competitors before any path that overwrites the file
manual_competitors = self._get_manual_competitors()
if not self.discovery_file.exists():
print_status(
"Discovery file not found, skipping competitor analysis", "warning"
@@ -60,6 +67,8 @@ class CompetitorAnalyzer:
self._create_error_analysis_file(
"Discovery file not found - cannot analyze competitors without project context"
)
if manual_competitors:
self._merge_manual_competitors(manual_competitors)
return RoadmapPhaseResult(
"competitor_analysis",
True,
@@ -84,6 +93,8 @@ class CompetitorAnalyzer:
if success and self.analysis_file.exists():
validation_result = self._validate_analysis()
if validation_result is not None:
if manual_competitors:
self._merge_manual_competitors(manual_competitors)
return validation_result
errors.append(f"Attempt {attempt + 1}: Validation failed")
else:
@@ -100,12 +111,82 @@ class CompetitorAnalyzer:
print(f" {muted('Error:')} {err}")
self._create_error_analysis_file("Analysis failed after retries", errors)
if manual_competitors:
self._merge_manual_competitors(manual_competitors)
# Return success=True for graceful degradation (don't block roadmap generation)
return RoadmapPhaseResult(
"competitor_analysis", True, [str(self.analysis_file)], errors, MAX_RETRIES
)
def _get_manual_competitors(self) -> list[dict]:
"""Extract manually-added competitors from the dedicated manual file and analysis file.
Reads from manual_competitors.json (primary, never overwritten by agent) and
falls back to competitor_analysis.json. Deduplicates by competitor ID.
Returns a list of competitor dicts where source == 'manual'.
"""
competitors_by_id: dict[str, dict] = {}
# Primary source: dedicated manual competitors file (never overwritten by agent)
if self.manual_competitors_file.exists():
try:
with open(self.manual_competitors_file, encoding="utf-8") as f:
data = json.load(f)
for c in data.get("competitors", []):
if isinstance(c, dict) and c.get("id"):
competitors_by_id[c["id"]] = c
except (json.JSONDecodeError, OSError) as e:
print_status(
f"Warning: could not read manual competitors file: {e}", "warning"
)
# Fallback: also check analysis file for manual competitors
if self.analysis_file.exists():
try:
with open(self.analysis_file, encoding="utf-8") as f:
data = json.load(f)
for c in data.get("competitors", []):
if (
isinstance(c, dict)
and c.get("source") == "manual"
and c.get("id")
and c["id"] not in competitors_by_id
):
competitors_by_id[c["id"]] = c
except (json.JSONDecodeError, OSError) as e:
print_status(
f"Warning: could not read manual competitors from analysis: {e}",
"warning",
)
return list(competitors_by_id.values())
def _merge_manual_competitors(self, manual_competitors: list[dict]) -> None:
"""Merge manual competitors back into the newly-generated analysis file.
Appends manual competitors that don't already exist (by ID) in the file.
"""
if not manual_competitors:
return
try:
with open(self.analysis_file, encoding="utf-8") as f:
data = json.load(f)
except (json.JSONDecodeError, OSError) as e:
print_status(f"Warning: failed to merge manual competitors: {e}", "warning")
return
existing_ids = {
c.get("id") for c in data.get("competitors", []) if isinstance(c, dict)
}
for competitor in manual_competitors:
if competitor.get("id") not in existing_ids:
data.setdefault("competitors", []).append(competitor)
write_json_atomic(self.analysis_file, data, indent=2)
def _build_context(self) -> str:
"""Build context string for the competitor analysis agent."""
return f"""
@@ -140,8 +221,11 @@ Output your findings to competitor_analysis.json.
"competitor_analysis", True, [str(self.analysis_file)], [], 0
)
except json.JSONDecodeError:
pass
except json.JSONDecodeError as e:
print_status(
f"Warning: competitor analysis file is not valid JSON: {e}",
"warning",
)
return None
@@ -2,11 +2,6 @@
"project_root": "/Users/andremikalsen/Documents/Coding/autonomous-coding",
"project_type": "single",
"services": {},
"infrastructure": {
"docker_compose": "docker-compose.yml",
"docker_services": [
"falkordb"
]
},
"infrastructure": {},
"conventions": {}
}
+1 -1
View File
@@ -136,7 +136,7 @@ Examples:
python spec_runner.py --task "Update text" --complexity simple
# Complex integration (auto-detected)
python spec_runner.py --task "Add Graphiti memory integration with FalkorDB"
python spec_runner.py --task "Add Graphiti memory integration with LadybugDB"
# Interactive mode
python spec_runner.py --interactive
+32
View File
@@ -21,6 +21,8 @@ from datetime import datetime, timedelta, timezone
from enum import Enum
from pathlib import Path
from core.file_utils import write_json_atomic
# Recovery manager configuration
ATTEMPT_WINDOW_SECONDS = 7200 # Only count attempts within last 2 hours
MAX_ATTEMPT_HISTORY_PER_SUBTASK = 50 # Cap stored attempts per subtask
@@ -514,6 +516,36 @@ class RecoveryManager:
self._save_attempt_history(history)
# Also update the subtask status in implementation_plan.json
# so that other callers (like is_build_ready_for_qa) see accurate status
try:
plan_file = self.spec_dir / "implementation_plan.json"
if plan_file.exists():
with open(plan_file, encoding="utf-8") as f:
plan = json.load(f)
updated = False
for phase in plan.get("phases", []):
for subtask in phase.get("subtasks", []):
if subtask.get("id") == subtask_id:
subtask["status"] = "failed"
stuck_note = f"Marked as stuck: {reason}"
existing = subtask.get("actual_output", "")
subtask["actual_output"] = (
f"{stuck_note}\n{existing}" if existing else stuck_note
)
updated = True
break
if updated:
break
if updated:
write_json_atomic(plan_file, plan, indent=2)
except (OSError, json.JSONDecodeError, UnicodeDecodeError) as e:
logger.warning(
f"Failed to update implementation_plan.json for stuck subtask {subtask_id}: {e}"
)
def get_stuck_subtasks(self) -> list[dict]:
"""
Get all subtasks marked as stuck.
+7 -30
View File
@@ -28,34 +28,19 @@ We encountered and fixed this bug during development as it was blocking our test
|-------|-------------|--------|
| Phase 1 | Create XState machine definition (task-machine.ts) | ✅ Complete |
| Phase 2 | Create TaskStateManager singleton wrapper | ✅ Complete |
| Phase 3 | Integrate into agent-events-handlers.ts | ⏸️ Partially done |
| Phase 4 | Remove legacy TaskStateMachine class | ❌ Not started |
| Phase 3 | Integrate into agent-events-handlers.ts | ✅ Complete |
| Phase 4 | Remove legacy TaskStateMachine class | ✅ Complete |
### Why We Stopped at Phase 2
### Migration Complete
The original scope was to introduce XState as the new state management approach. Full integration (Phase 3-4) requires:
- Extensive refactoring of agent-events-handlers.ts to remove all legacy decision logic
- Removing the old TaskStateMachine class entirely
- Migration of all status persistence to go through XState
We delivered Phases 1-2 to establish the foundation. The current state has both systems running in parallel with XState as primary:
- **XState is primary:** When TaskStateManager returns a valid state transition, that decision is used
- **Legacy as fallback:** The old TaskStateMachine logic only applies when XState doesn't produce a decision
- **Safe rollback:** If XState causes issues, the legacy system is still present and can take over
This dual-system approach allows:
- Validation that XState produces correct state transitions in production
- Safe rollback if issues arise
- Incremental adoption path for Phase 3-4
All four phases are now complete. The XState-based `TaskStateManager` is the sole state management system — the legacy `TaskStateMachine` class and `validateStatusTransition()` function have been fully removed. `agent-events-handlers.ts` uses the XState-based `taskStateManager` singleton exclusively.
## What Changed
### Before (Old Architecture)
### Before (Old Architecture — Now Removed)
- Status decisions scattered across agent-events-handlers.ts, execution-handlers.ts, worktree-handlers.ts
- `validateStatusTransition()` function with complex conditional logic
- TaskStateMachine class that was essentially an event emitter wrapper
- `TaskStateMachine` class that was essentially an event emitter wrapper
- Multiple places persisting status to implementation_plan.json
- Race conditions possible when multiple handlers tried to update status
@@ -118,14 +103,6 @@ The state machine responds to these events:
| CREATE_PR | User initiates PR creation |
| PR_CREATED | PR successfully created |
## Rollback Plan
If issues arise post-merge:
1. **Quick rollback:** `git revert <merge-commit>`
2. **Restore point:** Commit 3e5f004a has old code intact
3. **Legacy persistence still works:** implementation_plan.json continues to store status
## Testing
| Test Suite | Result |
@@ -163,7 +140,7 @@ If issues arise post-merge:
- Add @stately-ai/inspect for runtime devtools
- **Subtask state management** - Track individual subtask states within the machine using XState parallel states
- Add more granular QA states (qa_round_1, qa_round_2, etc.)
- Complete Phase 3-4: Full integration and removal of legacy TaskStateMachine class
## Visualization
@@ -0,0 +1,333 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { PRReviewStateManager } from '../pr-review-state-manager';
import type { PRReviewResult, PRReviewProgress } from '../../preload/api/modules/github-api';
// Mock dependencies
const mockSafeSendToRenderer = vi.fn();
vi.mock('../ipc-handlers/utils', () => ({
safeSendToRenderer: (...args: unknown[]) => mockSafeSendToRenderer(...args)
}));
function createMockGetMainWindow() {
return vi.fn(() => ({ id: 1 }) as unknown as Electron.BrowserWindow);
}
function createMockProgress(overrides: Partial<PRReviewProgress> = {}): PRReviewProgress {
return {
phase: 'analyzing',
progress: 50,
message: 'Analyzing files...',
...overrides
} as PRReviewProgress;
}
function createMockResult(overrides: Partial<PRReviewResult> = {}): PRReviewResult {
return {
overallStatus: 'approved',
summary: 'Looks good',
...overrides
} as PRReviewResult;
}
describe('PRReviewStateManager', () => {
let manager: PRReviewStateManager;
const projectId = 'project-1';
const prNumber = 42;
beforeEach(() => {
manager = new PRReviewStateManager(createMockGetMainWindow());
vi.clearAllMocks();
});
afterEach(() => {
manager.clearAll();
});
describe('actor lifecycle', () => {
it('should create actor on first handleStartReview call', () => {
manager.handleStartReview(projectId, prNumber);
const snapshot = manager.getState(projectId, prNumber);
expect(snapshot).not.toBeNull();
});
it('should reuse existing actor for same PR key', () => {
manager.handleStartReview(projectId, prNumber);
const snapshot1 = manager.getState(projectId, prNumber);
// Calling again should not create a new actor
manager.handleStartReview(projectId, prNumber);
const snapshot2 = manager.getState(projectId, prNumber);
expect(snapshot1).not.toBeNull();
expect(snapshot2).not.toBeNull();
});
it('should create separate actors for different PRs', () => {
manager.handleStartReview(projectId, 1);
manager.handleStartReview(projectId, 2);
const snapshot1 = manager.getState(projectId, 1);
const snapshot2 = manager.getState(projectId, 2);
expect(snapshot1).not.toBeNull();
expect(snapshot2).not.toBeNull();
});
it('should start actor before events are sent', () => {
manager.handleStartReview(projectId, prNumber);
const snapshot = manager.getState(projectId, prNumber);
// If actor wasn't started, getSnapshot would fail or return unexpected state
expect(snapshot).not.toBeNull();
expect(String(snapshot!.value)).toBe('reviewing');
});
});
describe('event routing', () => {
it('should transition to reviewing on handleStartReview', () => {
manager.handleStartReview(projectId, prNumber);
const snapshot = manager.getState(projectId, prNumber);
expect(String(snapshot!.value)).toBe('reviewing');
});
it('should send START_FOLLOWUP_REVIEW with previousResult', () => {
const previousResult = createMockResult();
manager.handleStartFollowupReview(projectId, prNumber, previousResult);
const snapshot = manager.getState(projectId, prNumber);
expect(String(snapshot!.value)).toBe('reviewing');
expect(snapshot!.context.isFollowup).toBe(true);
expect(snapshot!.context.previousResult).toBe(previousResult);
});
it('should send START_REVIEW when handleStartFollowupReview has no previousResult', () => {
manager.handleStartFollowupReview(projectId, prNumber);
const snapshot = manager.getState(projectId, prNumber);
expect(String(snapshot!.value)).toBe('reviewing');
expect(snapshot!.context.isFollowup).toBe(false);
});
it('should update context on handleProgress', () => {
manager.handleStartReview(projectId, prNumber);
const progress = createMockProgress();
manager.handleProgress(projectId, prNumber, progress);
const snapshot = manager.getState(projectId, prNumber);
expect(snapshot!.context.progress).toEqual(progress);
});
it('should ignore handleProgress for unknown PR', () => {
// Should not throw
manager.handleProgress(projectId, 999, createMockProgress());
expect(manager.getState(projectId, 999)).toBeNull();
});
it('should transition to completed on handleComplete', () => {
manager.handleStartReview(projectId, prNumber);
const result = createMockResult();
manager.handleComplete(projectId, prNumber, result);
const snapshot = manager.getState(projectId, prNumber);
expect(String(snapshot!.value)).toBe('completed');
expect(snapshot!.context.result).toEqual(result);
});
it('should create actor for handleComplete on unknown PR (late-arriving result)', () => {
const result = createMockResult();
// No handleStartReview called — handleComplete should create the actor
manager.handleComplete(projectId, prNumber, result);
const snapshot = manager.getState(projectId, prNumber);
expect(snapshot).not.toBeNull();
expect(snapshot!.context.result).toEqual(result);
});
it('should send DETECT_EXTERNAL_REVIEW when overallStatus is in_progress', () => {
manager.handleStartReview(projectId, prNumber);
const result = createMockResult({ overallStatus: 'in_progress' });
manager.handleComplete(projectId, prNumber, result);
const snapshot = manager.getState(projectId, prNumber);
expect(String(snapshot!.value)).toBe('externalReview');
});
it('should transition to error on handleError', () => {
manager.handleStartReview(projectId, prNumber);
manager.handleError(projectId, prNumber, 'Something went wrong');
const snapshot = manager.getState(projectId, prNumber);
expect(String(snapshot!.value)).toBe('error');
expect(snapshot!.context.error).toBe('Something went wrong');
});
it('should transition to error on handleCancel', () => {
manager.handleStartReview(projectId, prNumber);
manager.handleCancel(projectId, prNumber);
const snapshot = manager.getState(projectId, prNumber);
expect(String(snapshot!.value)).toBe('error');
});
});
describe('state emission', () => {
it('should emit state changes to renderer via safeSendToRenderer', () => {
manager.handleStartReview(projectId, prNumber);
expect(mockSafeSendToRenderer).toHaveBeenCalled();
});
it('should use GITHUB_PR_REVIEW_STATE_CHANGE IPC channel', () => {
manager.handleStartReview(projectId, prNumber);
expect(mockSafeSendToRenderer).toHaveBeenCalledWith(
expect.any(Function),
'github:pr:reviewStateChange',
expect.any(String),
expect.objectContaining({ state: expect.any(String) })
);
});
it('should emit PRReviewStatePayload with correct shape', () => {
manager.handleStartReview(projectId, prNumber);
// Find the call that emits 'reviewing' state
const reviewingCall = mockSafeSendToRenderer.mock.calls.find(
(call: unknown[]) => {
const payload = call[3] as Record<string, unknown> | undefined;
return payload && typeof payload === 'object' && payload.state === 'reviewing';
}
);
expect(reviewingCall).toBeDefined();
expect(reviewingCall![2]).toBe(`${projectId}:${prNumber}`);
const payload = reviewingCall![3] as Record<string, unknown>;
expect(payload).toEqual(expect.objectContaining({
state: 'reviewing',
prNumber,
projectId,
isReviewing: true,
startedAt: expect.any(String),
progress: null,
result: null,
previousResult: null,
error: null,
isExternalReview: false,
isFollowup: false,
}));
});
it('should use projectId:prNumber as key format', () => {
manager.handleStartReview(projectId, prNumber);
const calls = mockSafeSendToRenderer.mock.calls;
const prCall = calls.find((call: unknown[]) => call[2] === `${projectId}:${prNumber}`);
expect(prCall).toBeDefined();
});
});
describe('deduplication', () => {
it('should NOT emit duplicate IPC for same state + same context', () => {
manager.handleStartReview(projectId, prNumber);
const callCountAfterStart = mockSafeSendToRenderer.mock.calls.length;
// Sending START_REVIEW again won't transition (guard prevents it), so no new emission
manager.handleStartReview(projectId, prNumber);
expect(mockSafeSendToRenderer.mock.calls.length).toBe(callCountAfterStart);
});
it('should emit for same state but different context (progress update)', () => {
manager.handleStartReview(projectId, prNumber);
const callCountAfterStart = mockSafeSendToRenderer.mock.calls.length;
manager.handleProgress(projectId, prNumber, createMockProgress({ progress: 25, message: 'Step 1' }));
expect(mockSafeSendToRenderer.mock.calls.length).toBeGreaterThan(callCountAfterStart);
const callCountAfterProgress1 = mockSafeSendToRenderer.mock.calls.length;
manager.handleProgress(projectId, prNumber, createMockProgress({ progress: 75, message: 'Step 2' }));
expect(mockSafeSendToRenderer.mock.calls.length).toBeGreaterThan(callCountAfterProgress1);
});
it('should always emit for different state transitions', () => {
manager.handleStartReview(projectId, prNumber);
const callCountAfterStart = mockSafeSendToRenderer.mock.calls.length;
manager.handleComplete(projectId, prNumber, createMockResult());
expect(mockSafeSendToRenderer.mock.calls.length).toBeGreaterThan(callCountAfterStart);
});
});
describe('cleanup', () => {
it('should stop actor and remove from map on handleClearReview', () => {
manager.handleStartReview(projectId, prNumber);
expect(manager.getState(projectId, prNumber)).not.toBeNull();
manager.handleClearReview(projectId, prNumber);
expect(manager.getState(projectId, prNumber)).toBeNull();
});
it('should emit exactly one cleared state IPC on handleClearReview (no double emission)', () => {
manager.handleStartReview(projectId, prNumber);
mockSafeSendToRenderer.mockClear();
manager.handleClearReview(projectId, prNumber);
// Should emit exactly 1 cleared state, not 2 (no double emission from
// sending CLEAR_REVIEW to actor subscription + manual emitClearedState)
expect(mockSafeSendToRenderer).toHaveBeenCalledTimes(1);
const payload = mockSafeSendToRenderer.mock.calls[0][3] as Record<string, unknown>;
expect(payload).toEqual(expect.objectContaining({ state: 'idle' }));
});
it('should stop ALL actors and clear maps on handleAuthChange', () => {
manager.handleStartReview(projectId, 1);
manager.handleStartReview(projectId, 2);
manager.handleAuthChange();
expect(manager.getState(projectId, 1)).toBeNull();
expect(manager.getState(projectId, 2)).toBeNull();
});
it('should emit cleared state to renderer on handleAuthChange', () => {
manager.handleStartReview(projectId, 1);
manager.handleStartReview(projectId, 2);
mockSafeSendToRenderer.mockClear();
manager.handleAuthChange();
// Should emit idle/null state for each PR
expect(mockSafeSendToRenderer).toHaveBeenCalledTimes(2);
for (const call of mockSafeSendToRenderer.mock.calls) {
const payload = call[3] as Record<string, unknown>;
expect(payload).toEqual(expect.objectContaining({ state: 'idle' }));
}
});
it('should stop all actors on clearAll', () => {
manager.handleStartReview(projectId, 1);
manager.handleStartReview(projectId, 2);
manager.clearAll();
expect(manager.getState(projectId, 1)).toBeNull();
expect(manager.getState(projectId, 2)).toBeNull();
});
});
describe('concurrent PRs', () => {
it('should support multiple PRs with independent actors', () => {
manager.handleStartReview(projectId, 1);
manager.handleStartReview(projectId, 2);
manager.handleComplete(projectId, 1, createMockResult());
expect(String(manager.getState(projectId, 1)!.value)).toBe('completed');
expect(String(manager.getState(projectId, 2)!.value)).toBe('reviewing');
});
it('should route events to correct actor by key', () => {
manager.handleStartReview(projectId, 1);
manager.handleStartReview(projectId, 2);
manager.handleError(projectId, 2, 'Error on PR 2');
expect(String(manager.getState(projectId, 1)!.value)).toBe('reviewing');
expect(String(manager.getState(projectId, 2)!.value)).toBe('error');
expect(manager.getState(projectId, 2)!.context.error).toBe('Error on PR 2');
});
it('should not affect other PRs when clearing one', () => {
manager.handleStartReview(projectId, 1);
manager.handleStartReview(projectId, 2);
manager.handleClearReview(projectId, 1);
expect(manager.getState(projectId, 1)).toBeNull();
expect(manager.getState(projectId, 2)).not.toBeNull();
expect(String(manager.getState(projectId, 2)!.value)).toBe('reviewing');
});
});
});
+44 -2
View File
@@ -38,6 +38,18 @@ log.transports.file.fileName = 'main.log';
// Console transport - always show warnings and errors, debug only in dev mode
log.transports.console.level = process.env.NODE_ENV === 'development' ? 'debug' : 'warn';
log.transports.console.format = '[{h}:{i}:{s}] [{level}] {text}';
// Guard console transport writes so broken stdio streams do not crash the app.
{
const originalConsoleWriteFn = log.transports.console.writeFn as (...args: unknown[]) => void;
log.transports.console.writeFn = (...args: unknown[]) => {
try {
originalConsoleWriteFn(...args);
} catch (error) {
const err = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
safeStderrWrite(`[app-logger] console transport write failed: ${err}`);
}
};
}
// Determine if this is a beta version
function isBetaVersion(): boolean {
@@ -204,14 +216,44 @@ export const appLog = {
log: (...args: unknown[]) => log.info(...args),
};
/**
* Best-effort stderr fallback used when electron-log itself throws (e.g. EIO).
* Must never throw, especially inside uncaught exception handlers.
*/
function safeStderrWrite(message: string): void {
try {
process.stderr.write(`${message}\n`);
} catch {
// Ignore - nothing else we can safely do here.
}
}
/**
* Log an unhandled error without risking recursive crashes if logger transport fails.
*/
function safeLogUnhandled(prefix: string, value: unknown): void {
try {
log.error(prefix, value);
} catch (loggingError) {
const loggingFailure = loggingError instanceof Error
? `${loggingError.name}: ${loggingError.message}`
: String(loggingError);
const original = value instanceof Error
? (value.stack || `${value.name}: ${value.message}`)
: String(value);
safeStderrWrite(`[app-logger] ${prefix} (logger failed: ${loggingFailure})`);
safeStderrWrite(original);
}
}
// Log unhandled errors
export function setupErrorLogging(): void {
process.on('uncaughtException', (error) => {
log.error('Uncaught exception:', error);
safeLogUnhandled('Uncaught exception:', error);
});
process.on('unhandledRejection', (reason) => {
log.error('Unhandled rejection:', reason);
safeLogUnhandled('Unhandled rejection:', reason);
});
log.info('Error logging initialized');
@@ -6,7 +6,8 @@
* and can be copied between profiles to enable session continuity after profile switches.
*/
import { existsSync, mkdirSync, copyFileSync, cpSync, unlinkSync } from 'fs';
import { existsSync } from 'fs';
import { mkdir, copyFile, cp, unlink } from 'fs/promises';
import { join, dirname } from 'path';
import { homedir } from 'os';
import { isNodeError } from '../utils/type-guards';
@@ -95,12 +96,12 @@ export interface SessionMigrationResult {
* @param sessionId - The session UUID to migrate
* @returns Migration result with success status and details
*/
export function migrateSession(
export async function migrateSession(
sourceConfigDir: string,
targetConfigDir: string,
cwd: string,
sessionId: string
): SessionMigrationResult {
): Promise<SessionMigrationResult> {
const result: SessionMigrationResult = {
success: false,
sessionId,
@@ -118,13 +119,14 @@ export function migrateSession(
try {
// Ensure target directory exists (do this first, before any file operations)
const targetParentDir = dirname(targetFile);
mkdirSync(targetParentDir, { recursive: true });
await mkdir(targetParentDir, { recursive: true });
console.warn('[SessionUtils] Ensured target directory exists:', targetParentDir);
// Attempt to copy the session .jsonl file
// This will throw if source doesn't exist or target cannot be written
// Note: copyFile silently overwrites by default (no COPYFILE_EXCL flag)
try {
copyFileSync(sourceFile, targetFile);
await copyFile(sourceFile, targetFile);
result.filesCopied++;
console.warn('[SessionUtils] Copied session file:', sourceFile, '->', targetFile);
} catch (copyError) {
@@ -132,12 +134,6 @@ export function migrateSession(
if (isNodeError(copyError)) {
if (copyError.code === 'ENOENT') {
result.error = `Source session file not found: ${sourceFile}`;
} else if (copyError.code === 'EEXIST') {
// Target already exists - this is OK, treat as successful skip
console.warn('[SessionUtils] Session already exists in target profile, skipping copy');
result.success = true;
result.filesCopied = 0;
return result;
} else {
result.error = `Failed to copy session file: ${copyError.message}`;
}
@@ -153,7 +149,7 @@ export function migrateSession(
// Attempt to copy the session directory (tool-results) if it exists
// Use try-catch instead of existsSync to avoid TOCTOU race
try {
cpSync(sourceDir, targetDir, { recursive: true });
await cp(sourceDir, targetDir, { recursive: true });
result.filesCopied++;
console.warn('[SessionUtils] Copied session directory:', sourceDir, '->', targetDir);
} catch (dirCopyError) {
@@ -182,7 +178,7 @@ export function migrateSession(
// Clean up partially migrated session file to enable retry
// Use try-catch instead of existsSync to avoid TOCTOU race
try {
unlinkSync(targetFile);
await unlink(targetFile);
console.warn('[SessionUtils] Cleaned up partial migration file:', targetFile);
} catch (cleanupError) {
// If file doesn't exist during cleanup, that's fine
+11 -1
View File
@@ -49,7 +49,7 @@ import { initializeAppUpdater, stopPeriodicUpdates } from './app-updater';
import { DEFAULT_APP_SETTINGS, IPC_CHANNELS, SPELL_CHECK_LANGUAGE_MAP, DEFAULT_SPELL_CHECK_LANGUAGE, ADD_TO_DICTIONARY_LABELS } from '../shared/constants';
import { getAppLanguage, initAppLanguage } from './app-language';
import { readSettingsFile } from './settings-utils';
import { setupErrorLogging } from './app-logger';
import { appLog, setupErrorLogging } from './app-logger';
import { initSentryMain } from './sentry';
import { preWarmToolCache } from './cli-tool-manager';
import { initializeClaudeProfileManager, getClaudeProfileManager } from './claude-profile-manager';
@@ -143,6 +143,11 @@ let mainWindow: BrowserWindow | null = null;
let agentManager: AgentManager | null = null;
let terminalManager: TerminalManager | null = null;
// Capture child process exits (renderer/GPU/utility) for crash diagnostics.
app.on('child-process-gone', (_event, details) => {
appLog.error('[main] child-process-gone:', details);
});
// Re-entrancy guard for before-quit handler.
// The first before-quit call pauses quit for async cleanup, then calls app.quit() again.
// The second call sees isQuitting=true and allows quit to proceed immediately.
@@ -214,6 +219,11 @@ function createWindow(): void {
mainWindow?.show();
});
// Capture renderer process crashes/termination reasons for diagnostics.
mainWindow.webContents.on('render-process-gone', (_event, details) => {
appLog.error('[main] render-process-gone:', details);
});
// Configure initial spell check languages with proper fallback logic
// Uses shared constant for consistency with the IPC handler
const defaultLanguage = 'en';
+65 -11
View File
@@ -3,8 +3,10 @@ import type {
InsightsSession,
InsightsSessionSummary,
InsightsChatMessage,
InsightsModelConfig
InsightsModelConfig,
ImageAttachment
} from '../shared/types';
import { MAX_IMAGES_PER_TASK } from '../shared/constants';
import { InsightsConfig } from './insights/config';
import { InsightsPaths } from './insights/paths';
import { SessionStorage } from './insights/session-storage';
@@ -70,8 +72,8 @@ export class InsightsService extends EventEmitter {
/**
* List all sessions for a project
*/
listSessions(projectPath: string): InsightsSessionSummary[] {
return this.sessionManager.listSessions(projectPath);
listSessions(projectPath: string, includeArchived = false): InsightsSessionSummary[] {
return this.sessionManager.listSessions(projectPath, includeArchived);
}
/**
@@ -95,6 +97,34 @@ export class InsightsService extends EventEmitter {
return this.sessionManager.deleteSession(projectId, projectPath, sessionId);
}
/**
* Archive a session
*/
archiveSession(projectId: string, projectPath: string, sessionId: string): boolean {
return this.sessionManager.archiveSession(projectId, projectPath, sessionId);
}
/**
* Unarchive a session
*/
unarchiveSession(projectPath: string, sessionId: string): boolean {
return this.sessionManager.unarchiveSession(projectPath, sessionId);
}
/**
* Delete multiple sessions
*/
deleteSessions(projectId: string, projectPath: string, sessionIds: string[]): { deletedIds: string[]; failedIds: string[] } {
return this.sessionManager.deleteSessions(projectId, projectPath, sessionIds);
}
/**
* Archive multiple sessions
*/
archiveSessions(projectId: string, projectPath: string, sessionIds: string[]): { archivedIds: string[]; failedIds: string[] } {
return this.sessionManager.archiveSessions(projectId, projectPath, sessionIds);
}
/**
* Rename a session
*/
@@ -116,7 +146,8 @@ export class InsightsService extends EventEmitter {
projectId: string,
projectPath: string,
message: string,
modelConfig?: InsightsModelConfig
modelConfig?: InsightsModelConfig,
images?: ImageAttachment[]
): Promise<void> {
// Cancel any existing session
this.executor.cancelSession(projectId);
@@ -139,22 +170,44 @@ export class InsightsService extends EventEmitter {
session.title = this.storage.generateTitle(message);
}
// Add user message
// Guard: cap images to MAX_IMAGES_PER_TASK
if (images && images.length > MAX_IMAGES_PER_TASK) {
images = images.slice(0, MAX_IMAGES_PER_TASK);
}
// Add user message (store thumbnails only for persistence, strip full data)
const persistImages = images?.map(img => ({
...img,
data: undefined
}));
const userMessage: InsightsChatMessage = {
id: `msg-${Date.now()}`,
role: 'user',
content: message,
timestamp: new Date()
timestamp: new Date(),
images: persistImages && persistImages.length > 0 ? persistImages : undefined
};
session.messages.push(userMessage);
session.updatedAt = new Date();
this.sessionManager.saveSession(projectPath, session);
// Build conversation history for context
const conversationHistory = session.messages.map(m => ({
role: m.role,
content: m.content
}));
// Add notation when images are present so the AI has context
// For historical messages (all but the last), use past tense to avoid confusion
const conversationHistory = session.messages.map((m, index) => {
const imageCount = m.images?.length ?? 0;
const isLastMessage = index === session.messages.length - 1;
let imageNotation = '';
if (imageCount > 0 && m.role === 'user') {
imageNotation = isLastMessage
? `\n[User attached ${imageCount} image(s)]`
: `\n[User previously attached ${imageCount} image(s) - not visible in this context]`;
}
return {
role: m.role,
content: imageNotation ? m.content + imageNotation : m.content
};
});
// Use provided modelConfig or fall back to session's config
const configToUse = modelConfig || session.modelConfig;
@@ -166,7 +219,8 @@ export class InsightsService extends EventEmitter {
projectPath,
message,
conversationHistory,
configToUse
configToUse,
images
);
// Add assistant message to session
@@ -1,5 +1,7 @@
import { spawn, ChildProcess } from 'child_process';
import { existsSync, writeFileSync, unlinkSync } from 'fs';
import { existsSync, unlinkSync } from 'fs';
import { writeFile } from 'fs/promises';
import { randomBytes } from 'crypto';
import path from 'path';
import os from 'os';
import { EventEmitter } from 'events';
@@ -8,12 +10,23 @@ import type {
InsightsChatStatus,
InsightsStreamChunk,
InsightsToolUsage,
InsightsModelConfig
InsightsModelConfig,
ImageAttachment
} from '../../shared/types';
import { MODEL_ID_MAP } from '../../shared/constants';
import { MODEL_ID_MAP, MAX_IMAGES_PER_TASK, MAX_IMAGE_SIZE } from '../../shared/constants';
import { InsightsConfig } from './config';
import { detectRateLimit, createSDKRateLimitInfo } from '../rate-limit-detector';
// Safe extension map for image MIME types — prevents path traversal via crafted mimeType
// SVG excluded: contains active script content and is unsupported by Claude Vision API
const SAFE_EXT_MAP: Record<string, string> = {
'image/png': 'png',
'image/jpeg': 'jpg',
'image/jpg': 'jpg',
'image/gif': 'gif',
'image/webp': 'webp'
};
/**
* Message processor result
*/
@@ -63,7 +76,8 @@ export class InsightsExecutor extends EventEmitter {
projectPath: string,
message: string,
conversationHistory: Array<{ role: string; content: string }>,
modelConfig?: InsightsModelConfig
modelConfig?: InsightsModelConfig,
images?: ImageAttachment[]
): Promise<ProcessorResult> {
// Cancel any existing session
this.cancelSession(projectId);
@@ -90,18 +104,80 @@ export class InsightsExecutor extends EventEmitter {
// Write conversation history to temp file to avoid Windows command-line length limit
const historyFile = path.join(
os.tmpdir(),
`insights-history-${projectId}-${Date.now()}.json`
`insights-history-${projectId}-${Date.now()}-${randomBytes(8).toString('hex')}.json`
);
let historyFileCreated = false;
try {
writeFileSync(historyFile, JSON.stringify(conversationHistory), 'utf-8');
await writeFile(historyFile, JSON.stringify(conversationHistory), { encoding: 'utf-8', mode: 0o600 });
historyFileCreated = true;
} catch (err) {
console.error('[Insights] Failed to write history file:', err);
throw new Error('Failed to write conversation history to temp file');
}
// Write image files and manifest if images are provided
const imagesTempFiles: string[] = [];
let imagesManifestFile: string | undefined;
// Defense-in-depth: cap image count and filter oversized images in the executor
if (images && images.length > MAX_IMAGES_PER_TASK) {
images = images.slice(0, MAX_IMAGES_PER_TASK);
}
if (images) {
images = images.filter(img => !img.data || Buffer.byteLength(img.data, 'base64') <= MAX_IMAGE_SIZE);
}
if (images && images.length > 0) {
try {
const manifest: Array<{ path: string; mimeType: string }> = [];
const timestamp = Date.now();
for (let i = 0; i < images.length; i++) {
const image = images[i];
if (!image.data) continue;
// Validate mimeType against allowlist (defense-in-depth for main process)
const ext = SAFE_EXT_MAP[image.mimeType];
if (!ext) {
console.warn(`[Insights] Skipping image with invalid mimeType: ${image.mimeType}`);
continue;
}
const imagePath = path.join(
os.tmpdir(),
`insights-image-${projectId}-${timestamp}-${i}-${randomBytes(8).toString('hex')}.${ext}`
);
await writeFile(imagePath, Buffer.from(image.data, 'base64'), { mode: 0o600 });
imagesTempFiles.push(imagePath);
manifest.push({ path: imagePath, mimeType: image.mimeType });
}
// Only write manifest file if we actually wrote any images
if (manifest.length > 0) {
imagesManifestFile = path.join(
os.tmpdir(),
`insights-images-manifest-${projectId}-${timestamp}-${randomBytes(8).toString('hex')}.json`
);
imagesTempFiles.push(imagesManifestFile); // Push before writeFile for cleanup on failure
await writeFile(imagesManifestFile, JSON.stringify(manifest), { encoding: 'utf-8', mode: 0o600 });
}
} catch (err) {
// Clean up any already-written image files
for (const tmpFile of imagesTempFiles) {
try {
if (existsSync(tmpFile)) unlinkSync(tmpFile);
} catch { /* ignore cleanup errors */ }
}
// Also clean up the history file (cleanupTempFiles isn't defined yet at this point)
if (existsSync(historyFile)) {
try { unlinkSync(historyFile); } catch { /* ignore */ }
}
console.error('[Insights] Failed to write image files:', err);
throw new Error('Failed to write image files to temp directory');
}
}
// Build command arguments
const args = [
runnerPath,
@@ -110,6 +186,11 @@ export class InsightsExecutor extends EventEmitter {
'--history-file', historyFile
];
// Add images manifest file if images were provided
if (imagesManifestFile) {
args.push('--images-file', imagesManifestFile);
}
// Add model config if provided
if (modelConfig) {
const modelId = MODEL_ID_MAP[modelConfig.model] || MODEL_ID_MAP['sonnet'];
@@ -125,6 +206,27 @@ export class InsightsExecutor extends EventEmitter {
this.activeSessions.set(projectId, proc);
// Shared cleanup for temp files used across close/error handlers
let cleanedUp = false;
const cleanupTempFiles = () => {
if (cleanedUp) return;
cleanedUp = true;
if (historyFileCreated && existsSync(historyFile)) {
try {
unlinkSync(historyFile);
} catch (cleanupErr) {
console.error('[Insights] Failed to cleanup history file:', cleanupErr);
}
}
for (const tmpFile of imagesTempFiles) {
try {
if (existsSync(tmpFile)) unlinkSync(tmpFile);
} catch (cleanupErr) {
console.error('[Insights] Failed to cleanup image temp file:', cleanupErr);
}
}
};
return new Promise((resolve, reject) => {
let fullResponse = '';
const suggestedTasks: InsightsChatMessage['suggestedTasks'] = [];
@@ -170,15 +272,7 @@ export class InsightsExecutor extends EventEmitter {
proc.on('close', (code) => {
this.activeSessions.delete(projectId);
// Cleanup temp file
if (historyFileCreated && existsSync(historyFile)) {
try {
unlinkSync(historyFile);
} catch (cleanupErr) {
console.error('[Insights] Failed to cleanup history file:', cleanupErr);
}
}
cleanupTempFiles();
// Check for rate limit if process failed
if (code !== 0) {
@@ -217,15 +311,7 @@ export class InsightsExecutor extends EventEmitter {
proc.on('error', (err) => {
this.activeSessions.delete(projectId);
// Cleanup temp file
if (historyFileCreated && existsSync(historyFile)) {
try {
unlinkSync(historyFile);
} catch (cleanupErr) {
console.error('[Insights] Failed to cleanup history file:', cleanupErr);
}
}
cleanupTempFiles();
this.emit('error', projectId, err.message);
reject(err);
+11
View File
@@ -23,10 +23,21 @@ export class InsightsPaths {
return path.join(this.getInsightsDir(projectPath), SESSIONS_DIR);
}
/**
* Validate that a session ID matches the expected safe pattern.
* Prevents path traversal attacks via crafted session IDs.
*/
private validateSessionId(sessionId: string): void {
if (!/^session-\d{1,20}$/.test(sessionId)) {
throw new Error('Invalid session ID format');
}
}
/**
* Get session file path for a specific session
*/
getSessionPath(projectPath: string, sessionId: string): string {
this.validateSessionId(sessionId);
return path.join(this.getSessionsDir(projectPath), `${sessionId}.json`);
}
@@ -20,8 +20,9 @@ export class SessionManager {
*/
loadSession(projectId: string, projectPath: string): InsightsSession | null {
// Check in-memory cache first
if (this.sessions.has(projectId)) {
return this.sessions.get(projectId)!;
const cachedSession = this.sessions.get(projectId);
if (cachedSession) {
return cachedSession;
}
// Migrate old format if needed
@@ -40,10 +41,10 @@ export class SessionManager {
/**
* List all sessions for a project
*/
listSessions(projectPath: string): InsightsSessionSummary[] {
listSessions(projectPath: string, includeArchived = false): InsightsSessionSummary[] {
// Migrate old format if needed
this.storage.migrateOldSession(projectPath);
return this.storage.listSessions(projectPath);
return this.storage.listSessions(projectPath, includeArchived);
}
/**
@@ -105,6 +106,80 @@ export class SessionManager {
return true;
}
/**
* Archive a session
*/
archiveSession(projectId: string, projectPath: string, sessionId: string): boolean {
const success = this.storage.archiveSession(projectPath, sessionId);
if (!success) return false;
// If this was the current session, auto-switch
const currentSession = this.sessions.get(projectId);
if (currentSession?.id === sessionId) {
this.sessions.delete(projectId);
const remaining = this.listSessions(projectPath);
if (remaining.length > 0) {
this.switchSession(projectId, projectPath, remaining[0].id);
} else {
this.storage.clearCurrentSessionId(projectPath);
}
}
return true;
}
/**
* Unarchive a session
*/
unarchiveSession(projectPath: string, sessionId: string): boolean {
return this.storage.unarchiveSession(projectPath, sessionId);
}
/**
* Delete multiple sessions
*/
deleteSessions(projectId: string, projectPath: string, sessionIds: string[]): { deletedIds: string[]; failedIds: string[] } {
const result = this.storage.deleteSessions(projectPath, sessionIds);
// Check if current cached session was among deleted
const currentSession = this.sessions.get(projectId);
if (currentSession && result.deletedIds.includes(currentSession.id)) {
this.sessions.delete(projectId);
const remaining = this.listSessions(projectPath);
if (remaining.length > 0) {
this.switchSession(projectId, projectPath, remaining[0].id);
} else {
this.storage.clearCurrentSessionId(projectPath);
}
}
return result;
}
/**
* Archive multiple sessions
*/
archiveSessions(projectId: string, projectPath: string, sessionIds: string[]): { archivedIds: string[]; failedIds: string[] } {
const result = this.storage.archiveSessions(projectPath, sessionIds);
// Check if current cached session was among archived
const currentSession = this.sessions.get(projectId);
if (currentSession && result.archivedIds.includes(currentSession.id)) {
this.sessions.delete(projectId);
const remaining = this.listSessions(projectPath);
if (remaining.length > 0) {
this.switchSession(projectId, projectPath, remaining[0].id);
} else {
this.storage.clearCurrentSessionId(projectPath);
}
}
return result;
}
/**
* Rename a session
*/
@@ -115,6 +190,17 @@ export class SessionManager {
session.title = newTitle;
session.updatedAt = new Date();
this.storage.saveSession(projectPath, session);
// Update cache if this session is cached
for (const [projectId, cachedSession] of this.sessions) {
if (cachedSession.id === sessionId) {
cachedSession.title = newTitle;
cachedSession.updatedAt = session.updatedAt;
this.sessions.set(projectId, cachedSession);
break;
}
}
return true;
}
@@ -133,7 +219,7 @@ export class SessionManager {
for (const [projectId, cachedSession] of this.sessions) {
if (cachedSession.id === sessionId) {
cachedSession.modelConfig = modelConfig;
cachedSession.updatedAt = new Date();
cachedSession.updatedAt = session.updatedAt;
this.sessions.set(projectId, cachedSession);
break;
}
@@ -1,6 +1,6 @@
import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, unlinkSync } from 'fs';
import path from 'path';
import type { InsightsSession, InsightsSessionSummary } from '../../shared/types';
import type { InsightsSession, InsightsSessionSummary, ImageAttachment } from '../../shared/types';
import { InsightsPaths } from './paths';
/**
@@ -27,15 +27,18 @@ export class SessionStorage {
* Load a specific session from disk
*/
loadSessionById(projectPath: string, sessionId: string): InsightsSession | null {
const sessionPath = this.paths.getSessionPath(projectPath, sessionId);
if (!existsSync(sessionPath)) return null;
try {
const sessionPath = this.paths.getSessionPath(projectPath, sessionId);
if (!existsSync(sessionPath)) return null;
const content = readFileSync(sessionPath, 'utf-8');
const session = JSON.parse(content) as InsightsSession;
// Convert date strings back to Date objects
session.createdAt = new Date(session.createdAt);
session.updatedAt = new Date(session.updatedAt);
if (session.archivedAt) {
session.archivedAt = new Date(session.archivedAt);
}
session.messages = session.messages.map(m => ({
...m,
timestamp: new Date(m.timestamp),
@@ -55,23 +58,98 @@ export class SessionStorage {
* Save session to disk
*/
saveSession(projectPath: string, session: InsightsSession): void {
const sessionsDir = this.paths.getSessionsDir(projectPath);
if (!existsSync(sessionsDir)) {
mkdirSync(sessionsDir, { recursive: true });
try {
const sessionsDir = this.paths.getSessionsDir(projectPath);
if (!existsSync(sessionsDir)) {
mkdirSync(sessionsDir, { recursive: true });
}
const sessionPath = this.paths.getSessionPath(projectPath, session.id);
writeFileSync(sessionPath, JSON.stringify(session, null, 2), 'utf-8');
} catch (error) {
console.error(`[SessionStorage] Failed to save session ${session.id}:`, error);
throw error;
}
}
/**
* Archive a session
*/
archiveSession(projectPath: string, sessionId: string): boolean {
const session = this.loadSessionById(projectPath, sessionId);
if (!session) return false;
try {
session.archivedAt = new Date();
this.saveSession(projectPath, session);
return true;
} catch (error) {
console.error(`[SessionStorage] Failed to archive session ${sessionId}:`, error);
return false;
}
}
/**
* Unarchive a session
*/
unarchiveSession(projectPath: string, sessionId: string): boolean {
const session = this.loadSessionById(projectPath, sessionId);
if (!session) return false;
try {
delete session.archivedAt;
this.saveSession(projectPath, session);
return true;
} catch (error) {
console.error(`[SessionStorage] Failed to unarchive session ${sessionId}:`, error);
return false;
}
}
/**
* Delete multiple sessions
*/
deleteSessions(projectPath: string, sessionIds: string[]): { deletedIds: string[]; failedIds: string[] } {
const deletedIds: string[] = [];
const failedIds: string[] = [];
for (const sessionId of sessionIds) {
if (this.deleteSession(projectPath, sessionId)) {
deletedIds.push(sessionId);
} else {
failedIds.push(sessionId);
}
}
const sessionPath = this.paths.getSessionPath(projectPath, session.id);
writeFileSync(sessionPath, JSON.stringify(session, null, 2), 'utf-8');
return { deletedIds, failedIds };
}
/**
* Archive multiple sessions
*/
archiveSessions(projectPath: string, sessionIds: string[]): { archivedIds: string[]; failedIds: string[] } {
const archivedIds: string[] = [];
const failedIds: string[] = [];
for (const sessionId of sessionIds) {
if (this.archiveSession(projectPath, sessionId)) {
archivedIds.push(sessionId);
} else {
failedIds.push(sessionId);
}
}
return { archivedIds, failedIds };
}
/**
* Delete a session from disk
*/
deleteSession(projectPath: string, sessionId: string): boolean {
const sessionPath = this.paths.getSessionPath(projectPath, sessionId);
if (!existsSync(sessionPath)) return false;
try {
const sessionPath = this.paths.getSessionPath(projectPath, sessionId);
if (!existsSync(sessionPath)) return false;
unlinkSync(sessionPath);
return true;
} catch {
@@ -82,7 +160,7 @@ export class SessionStorage {
/**
* List all sessions for a project
*/
listSessions(projectPath: string): InsightsSessionSummary[] {
listSessions(projectPath: string, includeArchived = false): InsightsSessionSummary[] {
const sessionsDir = this.paths.getSessionsDir(projectPath);
if (!existsSync(sessionsDir)) return [];
@@ -104,13 +182,20 @@ export class SessionStorage {
: 'Untitled Conversation';
}
// Skip archived sessions unless explicitly included
if (!includeArchived && session.archivedAt) {
continue;
}
sessions.push({
id: session.id,
projectId: session.projectId,
title: title || 'New Conversation',
messageCount: session.messages.length,
modelConfig: session.modelConfig,
createdAt: new Date(session.createdAt),
updatedAt: new Date(session.updatedAt)
updatedAt: new Date(session.updatedAt),
...(session.archivedAt ? { archivedAt: new Date(session.archivedAt) } : {})
});
} catch {
// Skip invalid session files
@@ -165,6 +250,23 @@ export class SessionStorage {
}
}
/**
* Strip full-resolution image data from a session for persistence.
* Keeps only thumbnail, id, filename, mimeType, and size to prevent bloated JSON files.
*/
private stripImageDataForPersistence(session: InsightsSession): InsightsSession {
return {
...session,
messages: session.messages.map(m => {
if (!m.images || m.images.length === 0) return m;
return {
...m,
images: m.images.map(({ data, path: _path, ...rest }: ImageAttachment) => rest)
};
})
};
}
/**
* Migrate old session format to new multi-session format
*/
@@ -7,19 +7,25 @@ import type {
AuthFailureInfo,
ImplementationPlan,
} from "../../shared/types";
import { XSTATE_SETTLED_STATES, XSTATE_TO_PHASE, mapStateToLegacy } from "../../shared/state-machines";
import { XSTATE_SETTLED_STATES, XSTATE_ACTIVE_STATES, XSTATE_TO_PHASE, mapStateToLegacy } from "../../shared/state-machines";
import { AgentManager } from "../agent";
import type { ProcessType, ExecutionProgressData } from "../agent";
import { titleGenerator } from "../title-generator";
import { fileWatcher } from "../file-watcher";
import { notificationService } from "../notification-service";
import { persistPlanLastEventSync, getPlanPath, persistPlanPhaseSync, persistPlanStatusAndReasonSync } from "./task/plan-file-utils";
import { persistPlanLastEventSync, getPlanPath, persistPlanPhaseSync, persistPlanStatusAndReasonSync, hasPlanWithSubtasks } from "./task/plan-file-utils";
import { findTaskWorktree } from "../worktree-paths";
import { findTaskAndProject } from "./task/shared";
import { safeSendToRenderer } from "./utils";
import { getClaudeProfileManager } from "../claude-profile-manager";
import { taskStateManager } from "../task-state-manager";
// Timeout for fallback safety net to check if task is still stuck after process exit
const STUCK_TASK_FALLBACK_TIMEOUT_MS = 500;
// Map to store active fallback timers so they can be cancelled on task restart
const fallbackTimers = new Map<string, NodeJS.Timeout>();
/**
* Register all agent-events-related IPC handlers
*/
@@ -96,6 +102,34 @@ export function registerAgenteventsHandlers(
taskStateManager.handleProcessExited(taskId, code, exitTask, exitProject);
// Fallback safety net: If XState failed to transition the task out of an active state,
// force it to human_review after a short delay. This prevents tasks from getting stuck
// when the process exits without XState properly handling it.
// We check XState's current state directly to avoid stale cache issues from projectStore.
// Store timer reference so it can be cancelled if task restarts within the window.
const timer = setTimeout(() => {
const currentState = taskStateManager.getCurrentState(taskId);
if (currentState && XSTATE_ACTIVE_STATES.has(currentState)) {
const { task: checkTask, project: checkProject } = findTaskAndProject(taskId, projectId);
if (checkTask && checkProject) {
// Use shared utility to determine if a valid implementation plan exists
const hasPlan = hasPlanWithSubtasks(checkProject, checkTask);
console.warn(
`[agent-events-handlers] Task ${taskId} still in XState ${currentState} ` +
`${STUCK_TASK_FALLBACK_TIMEOUT_MS}ms after exit, forcing USER_STOPPED (hasPlan: ${hasPlan})`
);
taskStateManager.handleUiEvent(taskId, { type: 'USER_STOPPED', hasPlan }, checkTask, checkProject);
}
}
// Clean up timer reference after it fires
fallbackTimers.delete(taskId);
}, STUCK_TASK_FALLBACK_TIMEOUT_MS);
// Store timer reference for potential cancellation
fallbackTimers.set(taskId, timer);
// Send final plan state to renderer BEFORE unwatching
// This ensures the renderer has the final subtask data (fixes 0/0 subtask bug)
// Try the file watcher's current path first, then fall back to worktree path
@@ -254,11 +288,21 @@ export function registerAgenteventsHandlers(
console.debug(`[agent-events-handlers] Skipping persistPlanPhaseSync for ${taskId}: XState in '${currentXState}', not overwriting with phase '${progress.phase}'`);
}
// Skip sending execution-progress to renderer when XState has settled.
// XState's emitPhaseFromState already sent the correct phase to the renderer.
// Skip sending execution-progress to renderer when XState has settled,
// UNLESS this is a final phase update (complete/failed) AND the task is still in_progress.
// This prevents UI flicker where a failed phase arrives after the status has already changed to human_review.
const isFinalPhaseUpdate = progress.phase === 'complete' || progress.phase === 'failed';
if (xstateInTerminalState) {
console.debug(`[agent-events-handlers] Skipping execution-progress to renderer for ${taskId}: XState in '${currentXState}', ignoring phase '${progress.phase}'`);
return;
if (!isFinalPhaseUpdate) {
console.debug(`[agent-events-handlers] Skipping execution-progress to renderer for ${taskId}: XState in '${currentXState}', ignoring phase '${progress.phase}'`);
return;
}
// For final phase updates, only send if task is still in_progress to prevent flicker
const { task } = findTaskAndProject(taskId, taskProjectId);
if (task && task.status !== 'in_progress') {
console.debug(`[agent-events-handlers] Skipping final phase '${progress.phase}' for ${taskId}: task status is '${task.status}', not 'in_progress'`);
return;
}
}
safeSendToRenderer(
getMainWindow,
@@ -314,3 +358,17 @@ export function registerAgenteventsHandlers(
safeSendToRenderer(getMainWindow, IPC_CHANNELS.TASK_ERROR, taskId, error, project?.id);
});
}
/**
* Cancel any pending fallback timer for a task.
* Should be called when a task is restarted to prevent the stale timer
* from incorrectly stopping the new process.
*/
export function cancelFallbackTimer(taskId: string): void {
const timer = fallbackTimers.get(taskId);
if (timer) {
clearTimeout(timer);
fallbackTimers.delete(taskId);
console.debug(`[agent-events-handlers] Cancelled fallback timer for task ${taskId}`);
}
}
@@ -51,6 +51,10 @@ function sendAuthChangedToRenderer(oldUsername: string | null, newUsername: stri
for (const win of windows) {
win.webContents.send(IPC_CHANNELS.GITHUB_AUTH_CHANGED, payload);
}
// Uses EventEmitter.emit (not IPC send) so main-process listeners can react.
// The listener (PRReviewStateManager) intentionally ignores all args — it only
// needs the event signal, not the payload.
ipcMain.emit(IPC_CHANNELS.GITHUB_AUTH_CHANGED, payload);
}
/**
@@ -26,7 +26,7 @@ import { getMemoryService, getDefaultDbPath } from "../../memory-service";
import type { Project, AppSettings } from "../../../shared/types";
import { createContextLogger } from "./utils/logger";
import { withProjectOrNull } from "./utils/project-middleware";
import { createIPCCommunicators } from "./utils/ipc-communicator";
import { PRReviewStateManager } from "../../pr-review-state-manager";
import { getRunnerEnv } from "./utils/runner-env";
import {
runPythonSubprocess,
@@ -1384,7 +1384,7 @@ function sendReviewStateUpdate(
project: Project,
prNumber: number,
projectId: string,
getMainWindow: () => BrowserWindow | null,
prReviewStateManager: PRReviewStateManager,
context: string
): void {
try {
@@ -1393,18 +1393,8 @@ function sendReviewStateUpdate(
debugLog("Could not retrieve updated review result for UI notification", { prNumber, context });
return;
}
const mainWindow = getMainWindow();
if (!mainWindow) return;
const { sendComplete } = createIPCCommunicators<PRReviewProgress, PRReviewResult>(
mainWindow,
{
progress: IPC_CHANNELS.GITHUB_PR_REVIEW_PROGRESS,
error: IPC_CHANNELS.GITHUB_PR_REVIEW_ERROR,
complete: IPC_CHANNELS.GITHUB_PR_REVIEW_COMPLETE,
},
projectId
);
sendComplete(updatedResult);
// Route through state manager so the XState actor emits the state change
prReviewStateManager.handleComplete(projectId, prNumber, updatedResult);
debugLog(`Sent PR review state update ${context}`, { prNumber });
} catch (uiError) {
debugLog("Failed to send UI update (non-critical)", {
@@ -1445,7 +1435,8 @@ function getGitHubPRSettings(): { model: string; thinkingLevel: string } {
async function runPRReview(
project: Project,
prNumber: number,
mainWindow: BrowserWindow
mainWindow: BrowserWindow,
prReviewStateManager: PRReviewStateManager
): Promise<PRReviewResult> {
// Comprehensive validation of GitHub module
const validation = await validateGitHubModule(project);
@@ -1456,15 +1447,9 @@ async function runPRReview(
const backendPath = validation.backendPath!;
const { sendProgress } = createIPCCommunicators<PRReviewProgress, PRReviewResult>(
mainWindow,
{
progress: IPC_CHANNELS.GITHUB_PR_REVIEW_PROGRESS,
error: IPC_CHANNELS.GITHUB_PR_REVIEW_ERROR,
complete: IPC_CHANNELS.GITHUB_PR_REVIEW_COMPLETE,
},
project.id
);
const sendProgress = (progress: PRReviewProgress): void => {
prReviewStateManager.handleProgress(project.id, prNumber, progress);
};
const { model, thinkingLevel } = getGitHubPRSettings();
const args = buildRunnerArgs(
@@ -1695,6 +1680,32 @@ async function fetchPRsFromGraphQL(
export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): void {
debugLog("Registering PR handlers");
// Create the XState-based PR review state manager
const prReviewStateManager = new PRReviewStateManager(getMainWindow);
// Clear all PR review actors when GitHub auth changes (account swap)
ipcMain.on(IPC_CHANNELS.GITHUB_AUTH_CHANGED, () => {
// Cancel all running review subprocesses and CI wait controllers
for (const [reviewKey, entry] of runningReviews) {
if (entry === CI_WAIT_PLACEHOLDER) {
const abortController = ciWaitAbortControllers.get(reviewKey);
if (abortController) {
abortController.abort();
ciWaitAbortControllers.delete(reviewKey);
}
} else {
try {
entry.kill("SIGTERM");
} catch {
// Process may have already exited
}
}
}
runningReviews.clear();
ciWaitAbortControllers.clear();
prReviewStateManager.handleAuthChange();
});
// List open PRs - fetches up to 100 open PRs at once, returns hasNextPage and endCursor from API
ipcMain.handle(
IPC_CHANNELS.GITHUB_PR_LIST,
@@ -1902,31 +1913,27 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
try {
await withProjectOrNull(projectId, async (project) => {
const { sendProgress, sendComplete } = createIPCCommunicators<
PRReviewProgress,
PRReviewResult
>(
mainWindow,
{
progress: IPC_CHANNELS.GITHUB_PR_REVIEW_PROGRESS,
error: IPC_CHANNELS.GITHUB_PR_REVIEW_ERROR,
complete: IPC_CHANNELS.GITHUB_PR_REVIEW_COMPLETE,
},
projectId
);
const sendProgress = (progress: PRReviewProgress): void => {
prReviewStateManager.handleProgress(projectId, prNumber, progress);
};
// Check if already running — notify renderer so it can display ongoing logs
if (runningReviews.has(reviewKey)) {
debugLog("Review already running, notifying renderer", { reviewKey });
const currentSnapshot = prReviewStateManager.getState(projectId, prNumber);
const currentProgress = currentSnapshot?.context?.progress?.progress ?? 50;
sendProgress({
phase: "analyzing",
prNumber,
progress: 50,
progress: currentProgress,
message: "Review is already in progress. Reconnecting to ongoing review...",
});
return;
}
// Notify state manager that review is starting (after duplicate check)
prReviewStateManager.handleStartReview(projectId, prNumber);
// Register as running BEFORE CI wait to prevent race conditions
// Use CI_WAIT_PLACEHOLDER sentinel until real process is spawned
runningReviews.set(reviewKey, CI_WAIT_PLACEHOLDER);
@@ -1991,31 +1998,18 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
message: "Fetching PR data...",
});
const result = await runPRReview(project, prNumber, mainWindow);
if (result.overallStatus === "in_progress") {
// Review is already running externally (detected by BotDetector).
// Send the result as-is so the renderer can activate external review polling.
debugLog("PR review already in progress externally", { prNumber });
sendProgress({
phase: "complete",
prNumber,
progress: 100,
message: "Review already in progress",
});
sendComplete(result);
return;
}
const result = await runPRReview(project, prNumber, mainWindow, prReviewStateManager);
debugLog("PR review completed", { prNumber, findingsCount: result.findings.length });
sendProgress({
phase: "complete",
prNumber,
progress: 100,
message: "Review complete!",
message: result.overallStatus === "in_progress" ? "Review already in progress" : "Review complete!",
});
sendComplete(result);
// Route through manager — handles external review detection internally
prReviewStateManager.handleComplete(projectId, prNumber, result);
} finally {
// Clean up in case we exit before runPRReview was called (e.g., cancelled during CI wait)
// runPRReview also has its own cleanup, but delete is idempotent
@@ -2032,16 +2026,7 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
prNumber,
error: error instanceof Error ? error.message : error,
});
const { sendError } = createIPCCommunicators<PRReviewProgress, PRReviewResult>(
mainWindow,
{
progress: IPC_CHANNELS.GITHUB_PR_REVIEW_PROGRESS,
error: IPC_CHANNELS.GITHUB_PR_REVIEW_ERROR,
complete: IPC_CHANNELS.GITHUB_PR_REVIEW_COMPLETE,
},
projectId
);
sendError({ prNumber, error: error instanceof Error ? error.message : "Failed to run PR review" });
prReviewStateManager.handleError(projectId, prNumber, error instanceof Error ? error.message : "Failed to run PR review");
}
});
@@ -2246,7 +2231,7 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
}
// Send state update event to refresh UI immediately (non-blocking)
sendReviewStateUpdate(project, prNumber, projectId, getMainWindow, "after posting");
sendReviewStateUpdate(project, prNumber, projectId, prReviewStateManager, "after posting");
return true;
} catch (error) {
@@ -2285,7 +2270,7 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
debugLog("Marked review as posted", { prNumber });
// Send state update event to refresh UI immediately (non-blocking)
sendReviewStateUpdate(project, prNumber, projectId, getMainWindow, "after marking posted");
sendReviewStateUpdate(project, prNumber, projectId, prReviewStateManager, "after marking posted");
return true;
} catch (error) {
@@ -2403,7 +2388,7 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
}
// Send state update event to refresh UI immediately (non-blocking)
sendReviewStateUpdate(project, prNumber, projectId, getMainWindow, "after deletion");
sendReviewStateUpdate(project, prNumber, projectId, prReviewStateManager, "after deletion");
return true;
} catch (error) {
@@ -2515,6 +2500,8 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
ciWaitAbortControllers.delete(reviewKey);
}
runningReviews.delete(reviewKey);
// Notify state manager of cancellation
prReviewStateManager.handleCancel(projectId, prNumber);
debugLog("CI wait cancelled", { reviewKey });
return true;
}
@@ -2535,6 +2522,8 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
// Clean up the registry
runningReviews.delete(reviewKey);
// Notify state manager of cancellation
prReviewStateManager.handleCancel(projectId, prNumber);
debugLog("Review process cancelled", { reviewKey });
return true;
} catch (error) {
@@ -2547,6 +2536,21 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
}
);
// Notify main process about external review completion or timeout
// Called by renderer when its polling detects an external review has finished on disk
ipcMain.handle(
IPC_CHANNELS.GITHUB_PR_NOTIFY_EXTERNAL_REVIEW_COMPLETE,
async (_, projectId: string, prNumber: number, result: PRReviewResult | null): Promise<void> => {
debugLog("notifyExternalReviewComplete handler called", { projectId, prNumber, hasResult: !!result });
if (result) {
prReviewStateManager.handleComplete(projectId, prNumber, result);
} else {
// Timeout — no result found within polling window
prReviewStateManager.handleError(projectId, prNumber, "External review timed out after 30 minutes");
}
}
);
// Check for new commits since last review
ipcMain.handle(
IPC_CHANNELS.GITHUB_PR_CHECK_NEW_COMMITS,
@@ -2932,34 +2936,40 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
try {
await withProjectOrNull(projectId, async (project) => {
const { sendProgress, sendError, sendComplete } = createIPCCommunicators<
PRReviewProgress,
PRReviewResult
>(
mainWindow,
{
progress: IPC_CHANNELS.GITHUB_PR_REVIEW_PROGRESS,
error: IPC_CHANNELS.GITHUB_PR_REVIEW_ERROR,
complete: IPC_CHANNELS.GITHUB_PR_REVIEW_COMPLETE,
},
projectId
);
const sendProgress = (progress: PRReviewProgress): void => {
prReviewStateManager.handleProgress(projectId, prNumber, progress);
};
const reviewKey = getReviewKey(projectId, prNumber);
// Check if already running — notify renderer so it can display ongoing logs
if (runningReviews.has(reviewKey)) {
debugLog("Follow-up review already running, notifying renderer", { reviewKey });
const currentSnapshot = prReviewStateManager.getState(projectId, prNumber);
const currentProgress = currentSnapshot?.context?.progress?.progress ?? 50;
sendProgress({
phase: "analyzing",
prNumber,
progress: currentProgress,
message: "Follow-up review is already in progress. Reconnecting to ongoing review...",
});
return;
}
// Get previous result for followup context
const previousResult = getReviewResult(project, prNumber) ?? undefined;
// Notify state manager that followup review is starting (after duplicate check)
prReviewStateManager.handleStartFollowupReview(projectId, prNumber, previousResult);
// Comprehensive validation of GitHub module
const validation = await validateGitHubModule(project);
if (!validation.valid) {
sendError({ prNumber, error: validation.error || "GitHub module validation failed" });
prReviewStateManager.handleError(projectId, prNumber, validation.error || "GitHub module validation failed");
return;
}
const backendPath = validation.backendPath!;
const reviewKey = getReviewKey(projectId, prNumber);
// Check if already running
if (runningReviews.has(reviewKey)) {
debugLog("Follow-up review already running", { reviewKey });
return;
}
// Register as running BEFORE CI wait to prevent race conditions
// Use CI_WAIT_PLACEHOLDER sentinel until real process is spawned
@@ -3129,7 +3139,8 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
message: "Follow-up review complete!",
});
sendComplete(result.data!);
// Route through state manager
prReviewStateManager.handleComplete(projectId, prNumber, result.data!);
} finally {
// Always clean up registry, whether we exit normally or via error
runningReviews.delete(reviewKey);
@@ -3142,19 +3153,7 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
prNumber,
error: error instanceof Error ? error.message : error,
});
const { sendError } = createIPCCommunicators<PRReviewProgress, PRReviewResult>(
mainWindow,
{
progress: IPC_CHANNELS.GITHUB_PR_REVIEW_PROGRESS,
error: IPC_CHANNELS.GITHUB_PR_REVIEW_ERROR,
complete: IPC_CHANNELS.GITHUB_PR_REVIEW_COMPLETE,
},
projectId
);
sendError({
prNumber,
error: error instanceof Error ? error.message : "Failed to run follow-up review",
});
prReviewStateManager.handleError(projectId, prNumber, error instanceof Error ? error.message : "Failed to run follow-up review");
}
}
);
@@ -16,6 +16,7 @@ import type {
InsightsSession,
InsightsSessionSummary,
InsightsModelConfig,
ImageAttachment,
Task,
TaskMetadata,
AppSettings,
@@ -81,7 +82,7 @@ export function registerInsightsHandlers(getMainWindow: () => BrowserWindow | nu
ipcMain.on(
IPC_CHANNELS.INSIGHTS_SEND_MESSAGE,
async (_, projectId: string, message: string, modelConfig?: InsightsModelConfig) => {
async (_, projectId: string, message: string, modelConfig?: InsightsModelConfig, images?: ImageAttachment[]) => {
const project = projectStore.getProject(projectId);
if (!project) {
safeSendToRenderer(
@@ -112,7 +113,7 @@ export function registerInsightsHandlers(getMainWindow: () => BrowserWindow | nu
// the handler returns. This fixes race conditions on Windows where
// environment setup wouldn't complete before process spawn.
try {
await insightsService.sendMessage(projectId, project.path, message, configWithSettings);
await insightsService.sendMessage(projectId, project.path, message, configWithSettings, images);
} catch (error) {
// Errors during sendMessage (executor errors) are already emitted via
// the 'error' event, but we catch here to prevent unhandled rejection
@@ -249,17 +250,95 @@ export function registerInsightsHandlers(getMainWindow: () => BrowserWindow | nu
// List all sessions for a project
ipcMain.handle(
IPC_CHANNELS.INSIGHTS_LIST_SESSIONS,
async (_, projectId: string): Promise<IPCResult<InsightsSessionSummary[]>> => {
async (_, projectId: string, includeArchived?: boolean): Promise<IPCResult<InsightsSessionSummary[]>> => {
const project = projectStore.getProject(projectId);
if (!project) {
return { success: false, error: "Project not found" };
}
const sessions = insightsService.listSessions(project.path);
const sessions = insightsService.listSessions(project.path, includeArchived ?? false);
return { success: true, data: sessions };
}
);
// Delete multiple sessions
ipcMain.handle(
IPC_CHANNELS.INSIGHTS_DELETE_SESSIONS,
async (_, projectId: string, sessionIds: string[]): Promise<IPCResult<{ deletedIds: string[]; failedIds: string[] }>> => {
if (!Array.isArray(sessionIds) || sessionIds.length === 0) {
return { success: false, error: "No sessions specified" };
}
const project = projectStore.getProject(projectId);
if (!project) {
return { success: false, error: "Project not found" };
}
const result = insightsService.deleteSessions(projectId, project.path, sessionIds);
return {
success: result.failedIds.length === 0,
data: result,
...(result.failedIds.length > 0 && { error: `Failed to delete ${result.failedIds.length} session(s)` })
};
}
);
// Archive a session
ipcMain.handle(
IPC_CHANNELS.INSIGHTS_ARCHIVE_SESSION,
async (_, projectId: string, sessionId: string): Promise<IPCResult> => {
const project = projectStore.getProject(projectId);
if (!project) {
return { success: false, error: "Project not found" };
}
const success = insightsService.archiveSession(projectId, project.path, sessionId);
if (success) {
return { success: true };
}
return { success: false, error: "Failed to archive session" };
}
);
// Archive multiple sessions
ipcMain.handle(
IPC_CHANNELS.INSIGHTS_ARCHIVE_SESSIONS,
async (_, projectId: string, sessionIds: string[]): Promise<IPCResult<{ archivedIds: string[]; failedIds: string[] }>> => {
if (!Array.isArray(sessionIds) || sessionIds.length === 0) {
return { success: false, error: "No sessions specified" };
}
const project = projectStore.getProject(projectId);
if (!project) {
return { success: false, error: "Project not found" };
}
const result = insightsService.archiveSessions(projectId, project.path, sessionIds);
return {
success: result.failedIds.length === 0,
data: result,
...(result.failedIds.length > 0 && { error: `Failed to archive ${result.failedIds.length} session(s)` })
};
}
);
// Unarchive a session
ipcMain.handle(
IPC_CHANNELS.INSIGHTS_UNARCHIVE_SESSION,
async (_, projectId: string, sessionId: string): Promise<IPCResult> => {
const project = projectStore.getProject(projectId);
if (!project) {
return { success: false, error: "Project not found" };
}
const success = insightsService.unarchiveSession(project.path, sessionId);
if (success) {
return { success: true };
}
return { success: false, error: "Failed to unarchive session" };
}
);
// Create a new session
ipcMain.handle(
IPC_CHANNELS.INSIGHTS_NEW_SESSION,
@@ -127,6 +127,7 @@ export function registerRoadmapHandlers(
})),
strengths: (c.strengths as string[]) || [],
marketPosition: (c.market_position as string) || "",
source: c.source || undefined,
})),
marketGaps: (rawCompetitor.market_gaps || []).map((g: Record<string, unknown>) => ({
id: g.id,
@@ -792,6 +793,148 @@ ${(feature.acceptance_criteria || []).map((c: string) => `- [ ] ${c}`).join("\n"
}
);
// ============================================
// Competitor Analysis Save
// ============================================
ipcMain.handle(
IPC_CHANNELS.COMPETITOR_ANALYSIS_SAVE,
async (
_,
projectId: string,
competitorAnalysis: CompetitorAnalysis
): Promise<IPCResult> => {
const project = projectStore.getProject(projectId);
if (!project) {
return { success: false, error: "Project not found" };
}
const roadmapDir = path.join(project.path, AUTO_BUILD_PATHS.ROADMAP_DIR);
const competitorAnalysisPath = path.join(
roadmapDir,
AUTO_BUILD_PATHS.COMPETITOR_ANALYSIS
);
try {
// Ensure roadmap directory exists
if (!existsSync(roadmapDir)) {
mkdirSync(roadmapDir, { recursive: true });
}
await withFileLock(competitorAnalysisPath, async () => {
// Transform camelCase to snake_case for JSON file
const serialized = {
project_context: {
project_name: competitorAnalysis.projectContext.projectName,
project_type: competitorAnalysis.projectContext.projectType,
target_audience: competitorAnalysis.projectContext.targetAudience,
},
competitors: competitorAnalysis.competitors.map((c) => ({
id: c.id,
name: c.name,
url: c.url,
description: c.description,
relevance: c.relevance,
pain_points: c.painPoints.map((p) => ({
id: p.id,
description: p.description,
source: p.source,
severity: p.severity,
frequency: p.frequency,
opportunity: p.opportunity,
})),
strengths: c.strengths,
market_position: c.marketPosition,
source: c.source,
})),
market_gaps: competitorAnalysis.marketGaps.map((g) => ({
id: g.id,
description: g.description,
affected_competitors: g.affectedCompetitors,
opportunity_size: g.opportunitySize,
suggested_feature: g.suggestedFeature,
})),
insights_summary: {
top_pain_points: competitorAnalysis.insightsSummary.topPainPoints,
differentiator_opportunities:
competitorAnalysis.insightsSummary.differentiatorOpportunities,
market_trends: competitorAnalysis.insightsSummary.marketTrends,
},
research_metadata: {
search_queries_used:
competitorAnalysis.researchMetadata.searchQueriesUsed,
sources_consulted:
competitorAnalysis.researchMetadata.sourcesConsulted,
limitations: competitorAnalysis.researchMetadata.limitations,
},
metadata: {
created_at: competitorAnalysis.createdAt
? new Date(competitorAnalysis.createdAt).toISOString()
: new Date().toISOString(),
updated_at: new Date().toISOString(),
},
};
await writeFileWithRetry(
competitorAnalysisPath,
JSON.stringify(serialized, null, 2),
{ encoding: 'utf-8' }
);
});
// Also persist manual competitors to a separate file that the backend
// agent never overwrites, preventing data loss during concurrent analysis
const manualCompetitors = competitorAnalysis.competitors.filter(
(c) => c.source === "manual"
);
if (manualCompetitors.length > 0) {
const manualCompetitorsPath = path.join(
roadmapDir,
AUTO_BUILD_PATHS.MANUAL_COMPETITORS
);
const manualSerialized = {
competitors: manualCompetitors.map((c) => ({
id: c.id,
name: c.name,
url: c.url,
description: c.description,
relevance: c.relevance,
pain_points: c.painPoints.map((p) => ({
id: p.id,
description: p.description,
source: p.source,
severity: p.severity,
frequency: p.frequency,
opportunity: p.opportunity,
})),
strengths: c.strengths,
market_position: c.marketPosition,
source: c.source,
})),
updated_at: new Date().toISOString(),
};
await writeFileWithRetry(
manualCompetitorsPath,
JSON.stringify(manualSerialized, null, 2),
{ encoding: "utf-8" }
);
}
debugLog("[Roadmap Handler] Saved competitor analysis:", { projectId });
return { success: true };
} catch (error) {
debugError("[Roadmap Handler] Failed to save competitor analysis:", error);
return {
success: false,
error:
error instanceof Error
? error.message
: "Failed to save competitor analysis",
};
}
}
);
// ============================================
// Roadmap Agent Events → Renderer
// ============================================
@@ -15,12 +15,14 @@ import {
getPlanPath,
persistPlanStatus,
createPlanIfNotExists,
resetStuckSubtasks
resetStuckSubtasks,
hasPlanWithSubtasks
} from './plan-file-utils';
import { writeFileAtomicSync } from '../../utils/atomic-file';
import { findTaskWorktree } from '../../worktree-paths';
import { projectStore } from '../../project-store';
import { getIsolatedGitEnv, detectWorktreeBranch } from '../../utils/git-isolation';
import { cancelFallbackTimer } from '../agent-events-handlers';
/**
* Safe file read that handles missing files without TOCTOU issues.
@@ -111,6 +113,11 @@ export function registerTaskExecutionHandlers(
IPC_CHANNELS.TASK_START,
async (_, taskId: string, _options?: TaskStartOptions) => {
console.warn('[TASK_START] Received request for taskId:', taskId);
// Cancel any pending fallback timer from previous process exit
// This prevents the stale timer from incorrectly stopping the newly restarted task
cancelFallbackTimer(taskId);
const mainWindow = getMainWindow();
if (!mainWindow) {
console.warn('[TASK_START] No main window found');
@@ -346,18 +353,8 @@ export function registerTaskExecutionHandlers(
if (!task || !project) return;
let hasPlan = false;
try {
const planPath = getPlanPath(project, task);
const planContent = safeReadFileSync(planPath);
if (planContent) {
const plan = JSON.parse(planContent);
const { totalCount } = checkSubtasksCompletion(plan);
hasPlan = totalCount > 0;
}
} catch {
hasPlan = false;
}
// Use shared utility to determine if a valid implementation plan exists
const hasPlan = hasPlanWithSubtasks(project, task);
taskStateManager.handleUiEvent(
taskId,
@@ -569,7 +566,7 @@ export function registerTaskExecutionHandlers(
_,
taskId: string,
status: TaskStatus,
options?: { forceCleanup?: boolean }
options?: { forceCleanup?: boolean; keepWorktree?: boolean }
): Promise<IPCResult & { worktreeExists?: boolean; worktreePath?: string }> => {
// Find task and project first (needed for worktree check)
const { task, project } = findTaskAndProject(taskId);
@@ -581,13 +578,17 @@ export function registerTaskExecutionHandlers(
// Validate status transition - 'done' can only be set through merge handler
// UNLESS there's no worktree (limbo state - already merged/discarded or failed)
// OR forceCleanup is requested (user confirmed they want to delete the worktree)
// OR keepWorktree is requested (user wants to mark done without deleting worktree)
if (status === 'done') {
// Check if worktree exists (task.specId matches worktree folder name)
const worktreePath = findTaskWorktree(project.path, task.specId);
const hasWorktree = worktreePath !== null;
if (hasWorktree) {
if (options?.forceCleanup) {
if (options?.keepWorktree) {
// User explicitly chose to keep worktree - allow marking as done
console.warn(`[TASK_UPDATE_STATUS] Marking task ${taskId} as done while keeping worktree at ${worktreePath}`);
} else if (options?.forceCleanup) {
// User confirmed cleanup - delete worktree and branch
console.warn(`[TASK_UPDATE_STATUS] Cleaning up worktree for task ${taskId} (user confirmed)`);
try {
@@ -760,6 +761,10 @@ export function registerTaskExecutionHandlers(
console.warn('[TASK_UPDATE_STATUS] Auto-starting task:', taskId);
// Cancel any pending fallback timer from previous process exit
// This prevents the stale timer from incorrectly stopping the newly started task
cancelFallbackTimer(taskId);
// Reset any stuck subtasks before starting execution
// This handles recovery from previous rate limits or crashes
const resetResult = await resetStuckSubtasks(planPath, project.id);
@@ -1136,6 +1141,52 @@ export function registerTaskExecutionHandlers(
}
console.log(`[Recovery] Total ${totalResetCount} subtask(s) reset across all locations`);
// Clear attempt_history.json to break infinite recovery loops.
// Without this, the backend re-reads stuck markers from attempt_history
// and immediately re-stucks the same subtasks after recovery.
const specDirsToClean = new Set<string>([specDir]);
if (mainSpecDir !== specDir) specDirsToClean.add(mainSpecDir);
if (worktreeSpecDir && worktreeSpecDir !== specDir) specDirsToClean.add(worktreeSpecDir);
for (const dir of specDirsToClean) {
const attemptHistoryPath = path.join(dir, 'memory', 'attempt_history.json');
const historyContent = safeReadFileSync(attemptHistoryPath);
if (!historyContent) continue;
try {
const history = JSON.parse(historyContent);
// Collect stuck subtask IDs before clearing
const stuckIds = new Set<string>(
(history.stuck_subtasks || [])
.map((s: { subtask_id?: string }) => s.subtask_id)
.filter((id: string | undefined): id is string => Boolean(id))
);
// Clear stuck_subtasks array
history.stuck_subtasks = [];
// Reset attempt entries for previously-stuck subtasks
if (history.subtasks && stuckIds.size > 0) {
for (const stuckId of stuckIds) {
if (history.subtasks[stuckId]) {
history.subtasks[stuckId] = { attempts: [], status: 'pending' };
}
}
}
history.metadata = {
...history.metadata,
last_updated: new Date().toISOString()
};
writeFileAtomicSync(attemptHistoryPath, JSON.stringify(history, null, 2));
console.log(`[Recovery] Cleared attempt_history.json at: ${dir} (reset ${stuckIds.size} stuck entries)`);
} catch (historyErr) {
console.warn(`[Recovery] Could not parse attempt_history at ${dir}:`, historyErr);
}
}
}
// Stop file watcher if it was watching this task
@@ -1198,6 +1249,10 @@ export function registerTaskExecutionHandlers(
}
try {
// Cancel any pending fallback timer from previous process exit
// This prevents the stale timer from incorrectly stopping the restarted task
cancelFallbackTimer(taskId);
// Set status to in_progress for the restart
newStatus = 'in_progress';
@@ -538,3 +538,30 @@ export function updateTaskMetadataPrUrl(metadataPath: string, prUrl: string): bo
return false;
}
}
/**
* Check if a task has a valid implementation plan with subtasks.
* A plan is considered valid if it has at least one subtask across all phases.
*
* @param project - The project containing the task
* @param task - The task to check
* @returns true if the task has a valid plan with subtasks, false otherwise
*/
export function hasPlanWithSubtasks(project: Project, task: Task): boolean {
try {
const planPath = getPlanPath(project, task);
const planContent = readFileSync(planPath, 'utf-8');
if (!planContent) {
return false;
}
const plan = JSON.parse(planContent);
// A plan exists if it has phases with subtasks (totalCount > 0)
const phases = plan.phases as Array<{ subtasks?: Array<unknown> }> | undefined;
const totalCount = phases?.flatMap(p => p.subtasks || []).length || 0;
return totalCount > 0;
} catch {
// File doesn't exist or is malformed
return false;
}
}
@@ -252,6 +252,8 @@ export function registerTerminalHandlers(
id: string;
sessionId?: string;
sessionMigrated?: boolean;
isClaudeMode?: boolean;
dangerouslySkipPermissions?: boolean;
}> = [];
// Process each terminal
@@ -273,7 +275,7 @@ export function registerTerminalHandlers(
to: targetConfigDir
});
const migrationResult = migrateSession(
const migrationResult = await migrateSession(
sourceConfigDir,
targetConfigDir,
terminal.cwd,
@@ -284,11 +286,19 @@ export function registerTerminalHandlers(
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Session migration result:', migrationResult);
}
// Store YOLO mode flag server-side for migrated sessions
// (consumed by resumeClaudeAsync when the new terminal resumes)
if (sessionMigrated && terminal.claudeSessionId && terminal.dangerouslySkipPermissions) {
terminalManager.storeMigratedSessionFlag(terminal.claudeSessionId, terminal.dangerouslySkipPermissions);
}
// All terminals need refresh (PTY env vars can't be updated)
terminalsNeedingRefresh.push({
id: terminal.id,
sessionId: terminal.claudeSessionId,
sessionMigrated
sessionMigrated,
isClaudeMode: terminal.isClaudeMode,
dangerouslySkipPermissions: terminal.dangerouslySkipPermissions
});
}
@@ -613,9 +623,9 @@ export function registerTerminalHandlers(
ipcMain.on(
IPC_CHANNELS.TERMINAL_RESUME_CLAUDE,
(_, id: string, sessionId?: string) => {
(_, id: string, sessionId?: string, options?: { migratedSession?: boolean }) => {
// Use async version to avoid blocking main process during CLI detection
terminalManager.resumeClaudeAsync(id, sessionId).catch((error) => {
terminalManager.resumeClaudeAsync(id, sessionId, options).catch((error) => {
console.warn('[terminal-handlers] Failed to resume Claude:', error);
});
}
@@ -8,7 +8,7 @@ import type {
OtherWorktreeInfo,
} from '../../../shared/types';
import path from 'path';
import { existsSync, mkdirSync, writeFileSync, readFileSync, readdirSync, rmSync, symlinkSync, lstatSync, copyFileSync, cpSync, statSync } from 'fs';
import { existsSync, mkdirSync, writeFileSync, readFileSync, readdirSync, rmSync, symlinkSync, lstatSync, copyFileSync, cpSync, statSync, readlinkSync } from 'fs';
import { execFileSync, execFile } from 'child_process';
import { promisify } from 'util';
import { minimatch } from 'minimatch';
@@ -57,6 +57,21 @@ function isTimeoutError(error: unknown): boolean {
);
}
/**
* Check if a path is a symlink or Windows junction (including broken ones).
* Uses readlinkSync which works for both symlinks and junctions on all platforms.
*/
function isSymlinkOrJunction(targetPath: string): boolean {
try {
// readlinkSync throws if the path is not a symlink/junction
// It works for both symlinks and junctions on Windows and Unix
readlinkSync(targetPath);
return true;
} catch {
return false; // Path doesn't exist or is not a symlink/junction
}
}
/**
* Fix repositories that are incorrectly marked with core.bare=true.
* This can happen when git worktree operations incorrectly set bare=true
@@ -250,11 +265,12 @@ interface DependencyConfig {
const DEFAULT_STRATEGY_MAP: Record<string, 'symlink' | 'recreate' | 'copy' | 'skip'> = {
// JavaScript / Node.js — symlink is safe and fast
node_modules: 'symlink',
// Python — venvs MUST be recreated, not symlinked.
// CPython bug #106045: pyvenv.cfg discovery does not resolve symlinks,
// so a symlinked venv resolves paths relative to the target, not the worktree.
venv: 'recreate',
'.venv': 'recreate',
// Python — symlink for fast worktree creation.
// CPython bug #106045 (pyvenv.cfg symlink resolution) does not affect
// typical usage (running scripts, imports, pip). If the health check
// after symlinking fails, we fall back to recreate automatically.
venv: 'symlink',
'.venv': 'symlink',
// PHP — Composer vendor dir is safe to symlink
vendor_php: 'symlink',
// Ruby — Bundler vendor/bundle is safe to symlink
@@ -364,6 +380,32 @@ async function setupWorktreeDependencies(projectPath: string, worktreePath: stri
switch (config.strategy) {
case 'symlink':
performed = applySymlinkStrategy(projectPath, worktreePath, config);
// For venvs, verify the symlink is usable — fall back to recreate if not
// Run health check whenever a venv exists (not just on fresh creation)
if (config.depType === 'venv' || config.depType === '.venv') {
const venvPath = path.join(worktreePath, config.sourceRelPath);
// Check if venv path exists (as symlink or otherwise)
if (existsSync(venvPath) || isSymlinkOrJunction(venvPath)) {
const pythonBin = isWindows()
? path.join(venvPath, 'Scripts', 'python.exe')
: path.join(venvPath, 'bin', 'python');
try {
await execFileAsync(pythonBin, ['-c', 'import sys; print(sys.prefix)'], {
timeout: 10000,
});
debugLog('[TerminalWorktree] Symlinked venv health check passed:', config.sourceRelPath);
} catch {
debugLog('[TerminalWorktree] Symlinked venv health check failed, falling back to recreate:', config.sourceRelPath);
debugLog('[TerminalWorktree] Venv fallback: removing broken symlink and recreating for', config.sourceRelPath);
// Remove the broken symlink and recreate
try { rmSync(venvPath, { recursive: true, force: true }); } catch { /* best-effort */ }
performed = await applyRecreateStrategy(projectPath, worktreePath, config);
if (performed) {
debugLog('[TerminalWorktree] Venv fallback to recreate succeeded:', config.sourceRelPath);
}
}
}
}
break;
case 'recreate':
performed = await applyRecreateStrategy(projectPath, worktreePath, config);
@@ -403,13 +445,15 @@ function applySymlinkStrategy(projectPath: string, worktreePath: string, config:
return false;
}
// Check for broken symlinks
try {
lstatSync(targetPath);
debugLog('[TerminalWorktree] Skipping symlink', config.sourceRelPath, '- target exists (possibly broken symlink)');
return false;
} catch {
// Target doesn't exist at all — good, we can create symlink
// Check for broken symlinks and remove them so a fresh symlink can be created
if (isSymlinkOrJunction(targetPath)) {
if (!existsSync(targetPath)) {
debugLog('[TerminalWorktree] Removing broken symlink for', config.sourceRelPath);
try { rmSync(targetPath, { force: true }); } catch { /* best-effort */ }
} else {
debugLog('[TerminalWorktree] Skipping symlink', config.sourceRelPath, '- target exists (symlink)');
return false;
}
}
const targetDir = path.dirname(targetPath);
@@ -434,19 +478,31 @@ function applySymlinkStrategy(projectPath: string, worktreePath: string, config:
}
}
/** Marker file written inside a recreated venv to indicate setup completed successfully. */
const VENV_SETUP_COMPLETE_MARKER = '.setup_complete';
/**
* Apply recreate strategy: create a fresh virtual environment in the worktree.
*
* Python venvs cannot be symlinked due to CPython bug #106045 pyvenv.cfg
* discovery does not resolve symlinks, so paths resolve relative to the
* symlink target instead of the worktree.
* Used as a fallback when venv symlinking fails (CPython bug #106045).
* Writes a completion marker so incomplete venvs can be detected and rebuilt.
*/
async function applyRecreateStrategy(projectPath: string, worktreePath: string, config: DependencyConfig): Promise<boolean> {
const venvPath = path.join(worktreePath, config.sourceRelPath);
const markerPath = path.join(venvPath, VENV_SETUP_COMPLETE_MARKER);
if (existsSync(venvPath)) {
debugLog('[TerminalWorktree] Skipping recreate', config.sourceRelPath, '- already exists');
return false;
// Check for broken symlinks that existsSync would miss
if (isSymlinkOrJunction(venvPath) && !existsSync(venvPath)) {
debugLog('[TerminalWorktree] Removing broken symlink at', config.sourceRelPath);
try { rmSync(venvPath, { recursive: true, force: true }); } catch { /* best-effort */ }
} else if (existsSync(venvPath)) {
if (existsSync(markerPath)) {
debugLog('[TerminalWorktree] Skipping recreate', config.sourceRelPath, '- already complete (marker present)');
return false;
}
// Venv exists but marker is missing — incomplete, remove and rebuild
debugLog('[TerminalWorktree] Removing incomplete venv', config.sourceRelPath, '(no marker)');
try { rmSync(venvPath, { recursive: true, force: true }); } catch { /* best-effort */ }
}
// Detect Python executable from the source venv or fall back to system Python
@@ -514,7 +570,7 @@ async function applyRecreateStrategy(projectPath: string, worktreePath: string,
debugLog('[TerminalWorktree] Installing deps from', config.requirementsFile);
await execFileAsync(pipExec, installArgs, {
encoding: 'utf-8',
timeout: 120000,
timeout: 300000,
});
} catch (error) {
if (isTimeoutError(error)) {
@@ -533,6 +589,13 @@ async function applyRecreateStrategy(projectPath: string, worktreePath: string,
}
}
// Write completion marker so future runs know this venv is complete
try {
writeFileSync(markerPath, '');
} catch (error) {
debugLog('[TerminalWorktree] Failed to write completion marker at', markerPath, ':', error);
}
debugLog('[TerminalWorktree] Recreated venv at', config.sourceRelPath);
return true;
}
@@ -0,0 +1,217 @@
import { createActor } from 'xstate';
import type { ActorRefFrom } from 'xstate';
import type { BrowserWindow } from 'electron';
import { prReviewMachine, type PRReviewEvent, type PRReviewContext } from '../shared/state-machines';
import type { PRReviewProgress, PRReviewResult, PRReviewStatePayload } from '../preload/api/modules/github-api';
import { IPC_CHANNELS } from '../shared/constants';
import { safeSendToRenderer } from './ipc-handlers/utils';
type PRReviewActor = ActorRefFrom<typeof prReviewMachine>;
/**
* Build a deduplication key from snapshot state + relevant context fields.
* PR reviews need to emit even when state stays the same but context changes
* (e.g., progress updates within 'reviewing' state).
*/
function buildContextKey(snapshot: { context: PRReviewContext }): string {
const ctx = snapshot.context;
const progressKey = ctx.progress
? `${ctx.progress.phase}:${ctx.progress.progress}:${ctx.progress.message}`
: 'none';
const resultKey = ctx.result ? ctx.result.overallStatus : 'none';
const errorKey = ctx.error ?? 'none';
return `${progressKey}|${resultKey}|${errorKey}`;
}
export class PRReviewStateManager {
private actors = new Map<string, PRReviewActor>();
private lastStateByPR = new Map<string, string>();
private getMainWindow: () => BrowserWindow | null;
constructor(getMainWindow: () => BrowserWindow | null) {
this.getMainWindow = getMainWindow;
}
handleStartReview(projectId: string, prNumber: number): void {
const actor = this.getOrCreateActor(projectId, prNumber);
actor.send({ type: 'START_REVIEW', prNumber, projectId } satisfies PRReviewEvent);
}
handleStartFollowupReview(projectId: string, prNumber: number, previousResult?: PRReviewResult): void {
const actor = this.getOrCreateActor(projectId, prNumber);
if (previousResult) {
actor.send({ type: 'START_FOLLOWUP_REVIEW', prNumber, projectId, previousResult } satisfies PRReviewEvent);
} else {
actor.send({ type: 'START_REVIEW', prNumber, projectId } satisfies PRReviewEvent);
}
}
handleProgress(projectId: string, prNumber: number, progress: PRReviewProgress): void {
const actor = this.getActor(projectId, prNumber);
if (!actor) return;
actor.send({ type: 'SET_PROGRESS', progress } satisfies PRReviewEvent);
}
handleComplete(projectId: string, prNumber: number, result: PRReviewResult): void {
// Use getOrCreateActor so late-arriving results (e.g. after auth change or
// app restart) still get processed instead of silently dropped.
const actor = this.getOrCreateActor(projectId, prNumber);
// If the actor is in idle state (freshly created for a late-arriving result),
// transition to reviewing first so REVIEW_COMPLETE is accepted.
const snapshot = actor.getSnapshot();
if (String(snapshot.value) === 'idle') {
actor.send({ type: 'START_REVIEW', prNumber, projectId } satisfies PRReviewEvent);
}
// Detect external review (result arrives with 'in_progress' status from outside)
if (result.overallStatus === 'in_progress') {
actor.send({ type: 'DETECT_EXTERNAL_REVIEW' } satisfies PRReviewEvent);
} else {
actor.send({ type: 'REVIEW_COMPLETE', result } satisfies PRReviewEvent);
}
}
handleError(projectId: string, prNumber: number, error: string): void {
const actor = this.getActor(projectId, prNumber);
if (!actor) return;
actor.send({ type: 'REVIEW_ERROR', error } satisfies PRReviewEvent);
}
handleCancel(projectId: string, prNumber: number): void {
const actor = this.getActor(projectId, prNumber);
if (!actor) return;
actor.send({ type: 'CANCEL_REVIEW' } satisfies PRReviewEvent);
}
handleClearReview(projectId: string, prNumber: number): void {
const key = this.getKey(projectId, prNumber);
const actor = this.actors.get(key);
if (actor) {
// Capture snapshot before stopping so the emitted payload has real context.
// Don't send CLEAR_REVIEW to the actor — that would trigger the subscription
// and cause a duplicate IPC emission alongside emitClearedState below.
const snapshot = actor.getSnapshot();
actor.stop();
this.actors.delete(key);
this.emitClearedState(key, snapshot?.context ?? null);
}
this.lastStateByPR.delete(key);
}
handleAuthChange(): void {
for (const [key, actor] of this.actors) {
// Capture the last known snapshot before stopping so the emitted payload
// contains the real projectId/prNumber instead of zeros.
const snapshot = actor.getSnapshot();
actor.stop();
// Emit cleared (idle) state to renderer for each PR
this.emitClearedState(key, snapshot?.context ?? null);
}
this.actors.clear();
this.lastStateByPR.clear();
}
getState(projectId: string, prNumber: number): ReturnType<PRReviewActor['getSnapshot']> | null {
const actor = this.getActor(projectId, prNumber);
if (!actor) return null;
return actor.getSnapshot();
}
clearAll(): void {
for (const [, actor] of this.actors) {
actor.stop();
}
this.actors.clear();
this.lastStateByPR.clear();
}
// ---------------------------------------------------------------------------
// Private
// ---------------------------------------------------------------------------
private getOrCreateActor(projectId: string, prNumber: number): PRReviewActor {
const key = this.getKey(projectId, prNumber);
const existing = this.actors.get(key);
if (existing) return existing;
const actor = createActor(prReviewMachine);
actor.subscribe((snapshot) => {
const stateValue = String(snapshot.value);
const contextKey = buildContextKey(snapshot);
const currentKey = `${stateValue}:${contextKey}`;
if (this.lastStateByPR.get(key) === currentKey) return;
this.lastStateByPR.set(key, currentKey);
this.emitStateToRenderer(key, snapshot);
});
actor.start();
this.actors.set(key, actor);
return actor;
}
private getActor(projectId: string, prNumber: number): PRReviewActor | null {
return this.actors.get(this.getKey(projectId, prNumber)) ?? null;
}
private getKey(projectId: string, prNumber: number): string {
return `${projectId}:${prNumber}`;
}
private emitStateToRenderer(
key: string,
snapshot: ReturnType<PRReviewActor['getSnapshot']> | null
): void {
const stateValue = snapshot ? String(snapshot.value) : 'idle';
const ctx = snapshot?.context ?? null;
const payload: PRReviewStatePayload = {
state: stateValue,
prNumber: ctx?.prNumber ?? 0,
projectId: ctx?.projectId ?? '',
isReviewing: stateValue === 'reviewing' || stateValue === 'externalReview',
startedAt: ctx?.startedAt ?? null,
progress: ctx?.progress ?? null,
result: ctx?.result ?? null,
previousResult: ctx?.previousResult ?? null,
error: ctx?.error ?? null,
isExternalReview: ctx?.isExternalReview ?? false,
isFollowup: ctx?.isFollowup ?? false,
};
safeSendToRenderer(
this.getMainWindow,
IPC_CHANNELS.GITHUB_PR_REVIEW_STATE_CHANGE,
key,
payload
);
}
/**
* Emit a cleared (idle) state using context from the last snapshot
* so the payload contains the real projectId/prNumber.
*/
private emitClearedState(key: string, ctx: PRReviewContext | null): void {
const payload: PRReviewStatePayload = {
state: 'idle',
prNumber: ctx?.prNumber ?? 0,
projectId: ctx?.projectId ?? '',
isReviewing: false,
startedAt: null,
progress: null,
result: null,
previousResult: null,
error: null,
isExternalReview: false,
isFollowup: false,
};
safeSendToRenderer(
this.getMainWindow,
IPC_CHANNELS.GITHUB_PR_REVIEW_STATE_CHANGE,
key,
payload
);
}
}
@@ -195,8 +195,20 @@ export class TerminalSessionStore {
* 1. Write to temp file
* 2. Rotate current file to backup
* 3. Rename temp to target (atomic on most filesystems)
*
* If an async write is in progress, defers to the async writer to avoid
* both operations competing for the same temp file (ENOENT race condition).
*/
private save(): void {
// If an async write is in progress, don't write synchronously — the async
// writer shares the same temp file path. Instead, mark a pending write so
// saveAsync() will re-save with the latest in-memory data when it finishes.
if (this.writeInProgress) {
this.writePending = true;
debugLog('[TerminalSessionStore] Deferring sync save — async write in progress');
return;
}
try {
const content = JSON.stringify(this.data, null, 2);
@@ -366,7 +378,9 @@ export class TerminalSessionStore {
private updateSessionInMemory(session: TerminalSession): boolean {
// Check if session was deleted - skip if pending deletion
if (this.pendingDelete.has(session.id)) {
console.warn('[TerminalSessionStore] Skipping save for deleted session:', session.id);
debugLog('[TerminalSessionStore] Skipping save for deleted session:', session.id,
'pendingDelete size:', this.pendingDelete.size,
'all pending IDs:', [...this.pendingDelete].join(', '));
return false;
}
@@ -596,6 +610,27 @@ export class TerminalSessionStore {
return sessions.find(s => s.id === sessionId);
}
/**
* Clear a session ID from pendingDelete, allowing saves to proceed.
*
* Called when a terminal is legitimately re-created with the same ID
* (e.g., worktree switching, terminal restart after exit). Without this,
* the 5-second pendingDelete window blocks session persistence for the
* new terminal.
*/
clearPendingDelete(sessionId: string): void {
if (this.pendingDelete.has(sessionId)) {
this.pendingDelete.delete(sessionId);
// Also clear the cleanup timer since we're explicitly clearing
const timer = this.pendingDeleteTimers.get(sessionId);
if (timer) {
clearTimeout(timer);
this.pendingDeleteTimers.delete(sessionId);
}
debugLog('[TerminalSessionStore] Cleared pendingDelete for re-created terminal:', sessionId);
}
}
/**
* Remove a session (from today's sessions)
*
@@ -606,6 +641,9 @@ export class TerminalSessionStore {
// Mark as pending delete BEFORE modifying data to prevent race condition
// with in-flight saveSessionAsync() calls
this.pendingDelete.add(sessionId);
debugLog('[TerminalSessionStore] removeSession: added to pendingDelete:', sessionId,
'pendingDelete size:', this.pendingDelete.size,
'all pending IDs:', [...this.pendingDelete].join(', '));
const todaySessions = this.getTodaysSessions();
if (todaySessions[projectPath]) {
@@ -627,6 +665,8 @@ export class TerminalSessionStore {
const timer = setTimeout(() => {
this.pendingDelete.delete(sessionId);
this.pendingDeleteTimers.delete(sessionId);
debugLog('[TerminalSessionStore] Cleanup timer fired for:', sessionId,
'removing from pendingDelete. Remaining:', this.pendingDelete.size);
}, 5000);
this.pendingDeleteTimers.set(sessionId, timer);
}
@@ -109,7 +109,16 @@ function mockPlatform(platform: 'win32' | 'darwin' | 'linux') {
/**
* Helper to get platform-specific expectations for PATH prefix
*/
function getPathPrefixExpectation(platform: 'win32' | 'darwin' | 'linux', pathValue: string): string {
function getPathPrefixExpectation(
platform: 'win32' | 'darwin' | 'linux',
pathValue: string,
command: string
): string {
// Absolute executable commands no longer need PATH prefix injection.
if (path.isAbsolute(command)) {
return '';
}
if (platform === 'win32') {
// Windows: set "PATH=value" &&
return `set "PATH=${pathValue}" && `;
@@ -118,6 +127,20 @@ function getPathPrefixExpectation(platform: 'win32' | 'darwin' | 'linux', pathVa
return `PATH='${pathValue}' `;
}
function expectPathPrefix(
written: string,
platform: 'win32' | 'darwin' | 'linux',
pathValue: string,
command: string
): void {
const expectedPrefix = getPathPrefixExpectation(platform, pathValue, command);
if (expectedPrefix) {
expect(written).toContain(expectedPrefix);
} else {
expect(written).not.toContain('PATH=');
}
}
/**
* Helper to get platform-specific expectations for command quoting
*/
@@ -241,7 +264,7 @@ describe('claude-integration-handler', () => {
const written = mockWriteToPty.mock.calls[0][1] as string;
expect(written).toContain(buildCdCommand('/tmp/project'));
expect(written).toContain(getPathPrefixExpectation(platform, '/opt/claude/bin:/usr/bin'));
expectPathPrefix(written, platform, '/opt/claude/bin:/usr/bin', "/opt/claude bin/claude's");
expect(written).toContain(getQuotedCommand(platform, "/opt/claude bin/claude's"));
expect(mockReleaseSessionId).toHaveBeenCalledWith('term-1');
expect(mockPersistSession).toHaveBeenCalledWith(terminal);
@@ -402,7 +425,7 @@ describe('claude-integration-handler', () => {
expect(written).toContain(histPrefix);
expect(written).toContain(configDir);
expect(written).toContain(getPathPrefixExpectation(platform, '/opt/claude/bin:/usr/bin'));
expectPathPrefix(written, platform, '/opt/claude/bin:/usr/bin', command);
expect(written).toContain(getQuotedCommand(platform, command));
expect(written).toContain(clearCmd);
expect(profileManager.getProfile).toHaveBeenCalledWith('prof-2');
@@ -436,7 +459,7 @@ describe('claude-integration-handler', () => {
const written = mockWriteToPty.mock.calls[0][1] as string;
expect(written).toContain(getQuotedCommand(platform, command));
expect(written).toContain(getPathPrefixExpectation(platform, '/opt/claude/bin:/usr/bin'));
expectPathPrefix(written, platform, '/opt/claude/bin:/usr/bin', command);
expect(profileManager.getProfile).toHaveBeenCalledWith('prof-3');
expect(profileManager.markProfileUsed).toHaveBeenCalledWith('prof-3');
expect(mockPersistSession).toHaveBeenCalledWith(terminal);
@@ -460,7 +483,7 @@ describe('claude-integration-handler', () => {
resumeClaude(terminal, 'abc123', () => null);
const resumeCall = mockWriteToPty.mock.calls[0][1] as string;
expect(resumeCall).toContain(getPathPrefixExpectation(platform, '/opt/claude/bin:/usr/bin'));
expectPathPrefix(resumeCall, platform, '/opt/claude/bin:/usr/bin', '/opt/claude/bin/claude');
expect(resumeCall).toContain(getQuotedCommand(platform, '/opt/claude/bin/claude') + ' --continue');
expect(resumeCall).not.toContain('--resume');
// sessionId is cleared because --continue doesn't track specific sessions
@@ -656,7 +679,7 @@ describe('invokeClaudeAsync', () => {
const written = mockWriteToPty.mock.calls[0][1] as string;
expect(written).toContain(buildCdCommand('/tmp/project'));
expect(written).toContain(getPathPrefixExpectation(platform, '/opt/claude/bin:/usr/bin'));
expectPathPrefix(written, platform, '/opt/claude/bin:/usr/bin', '/opt/claude/bin/claude');
expect(mockReleaseSessionId).toHaveBeenCalledWith('term-1');
expect(mockPersistSession).toHaveBeenCalledWith(terminal);
expect(profileManager.markProfileUsed).toHaveBeenCalledWith('default');
@@ -914,7 +937,8 @@ describe('claude-integration-handler - Helper Functions', () => {
// Use a default terminal name pattern so renaming logic kicks in
const terminal = createMockTerminal({ title: 'Terminal 1' });
const mockWindow = {
webContents: { send: vi.fn() }
isDestroyed: () => false,
webContents: { send: vi.fn(), isDestroyed: () => false }
};
finalizeClaudeInvoke(
@@ -934,7 +958,8 @@ describe('claude-integration-handler - Helper Functions', () => {
// Use a default terminal name pattern so renaming logic kicks in
const terminal = createMockTerminal({ title: 'Terminal 2' });
const mockWindow = {
webContents: { send: vi.fn() }
isDestroyed: () => false,
webContents: { send: vi.fn(), isDestroyed: () => false }
};
finalizeClaudeInvoke(
@@ -955,7 +980,8 @@ describe('claude-integration-handler - Helper Functions', () => {
const terminal = createMockTerminal({ title: 'Terminal 3' });
const mockSend = vi.fn();
const mockWindow = {
webContents: { send: mockSend }
isDestroyed: () => false,
webContents: { send: mockSend, isDestroyed: () => false }
};
finalizeClaudeInvoke(
@@ -980,7 +1006,8 @@ describe('claude-integration-handler - Helper Functions', () => {
const terminal = createMockTerminal({ title: 'Claude' });
const mockSend = vi.fn();
const mockWindow = {
webContents: { send: mockSend }
isDestroyed: () => false,
webContents: { send: mockSend, isDestroyed: () => false }
};
finalizeClaudeInvoke(
@@ -1004,7 +1031,8 @@ describe('claude-integration-handler - Helper Functions', () => {
const terminal = createMockTerminal({ title: 'My Custom Terminal' });
const mockSend = vi.fn();
const mockWindow = {
webContents: { send: mockSend }
isDestroyed: () => false,
webContents: { send: mockSend, isDestroyed: () => false }
};
finalizeClaudeInvoke(
@@ -16,6 +16,7 @@ import { getEmailFromConfigDir } from '../claude-profile/profile-utils';
import * as OutputParser from './output-parser';
import * as SessionHandler from './session-handler';
import * as PtyManager from './pty-manager';
import { safeSendToRenderer } from '../ipc-handlers/utils';
import { debugLog, debugError } from '../../shared/utils/debug-logger';
import { escapeShellArg, escapeForWindowsDoubleQuote, buildCdCommand } from '../../shared/utils/shell-escape';
import { getClaudeCliInvocation, getClaudeCliInvocationAsync } from '../claude-cli-utils';
@@ -116,6 +117,19 @@ function normalizePathForBash(envPath: string): string {
return isWindows() ? envPath.replace(/;/g, ':') : envPath;
}
/**
* Determine whether a command already resolves via an absolute executable path.
*
* When true, we should avoid prefixing PATH=... into the typed shell command because:
* 1) PATH is not needed to locate the executable
* 2) very long PATH prefixes create huge echoed command lines that can stress terminal rendering
*/
function isAbsoluteExecutableCommand(command: string): boolean {
const trimmed = command.trim();
if (!trimmed) return false;
return path.isAbsolute(trimmed);
}
/**
* Generate temp file content for OAuth token based on platform
*
@@ -380,11 +394,8 @@ export function finalizeClaudeInvoke(
: 'Claude';
terminal.title = title;
// Notify renderer of title change
const win = getWindow();
if (win) {
win.webContents.send(IPC_CHANNELS.TERMINAL_TITLE_CHANGE, terminal.id, title);
}
// Notify renderer of title change (use safeSendToRenderer to prevent SIGABRT on disposed frame)
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_TITLE_CHANGE, terminal.id, title);
}
// Persist session if project path is available
@@ -434,18 +445,15 @@ export function handleRateLimit(
const autoSwitchSettings = profileManager.getAutoSwitchSettings();
const bestProfile = profileManager.getBestAvailableProfile(currentProfileId);
const win = getWindow();
if (win) {
win.webContents.send(IPC_CHANNELS.TERMINAL_RATE_LIMIT, {
terminalId: terminal.id,
resetTime,
detectedAt: new Date().toISOString(),
profileId: currentProfileId,
suggestedProfileId: bestProfile?.id,
suggestedProfileName: bestProfile?.name,
autoSwitchEnabled: autoSwitchSettings.autoSwitchOnRateLimit
} as RateLimitEvent);
}
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_RATE_LIMIT, {
terminalId: terminal.id,
resetTime,
detectedAt: new Date().toISOString(),
profileId: currentProfileId,
suggestedProfileId: bestProfile?.id,
suggestedProfileName: bestProfile?.name,
autoSwitchEnabled: autoSwitchSettings.autoSwitchOnRateLimit
} as RateLimitEvent);
if (autoSwitchSettings.enabled && autoSwitchSettings.autoSwitchOnRateLimit && bestProfile) {
console.warn('[ClaudeIntegration] Auto-switching to profile:', bestProfile.name);
@@ -535,19 +543,16 @@ export function handleOAuthToken(
// Set flag to watch for Claude's ready state (onboarding complete)
terminal.awaitingOnboardingComplete = true;
const win = getWindow();
if (win) {
// needsOnboarding: true tells the UI to show "complete setup" message
// instead of "success" - user should finish Claude's onboarding before closing
win.webContents.send(IPC_CHANNELS.TERMINAL_OAUTH_TOKEN, {
terminalId: terminal.id,
profileId,
email: emailFromOutput || keychainCreds.email || profile?.email,
success: true,
needsOnboarding: true,
detectedAt: new Date().toISOString()
} as OAuthTokenEvent);
}
// needsOnboarding: true tells the UI to show "complete setup" message
// instead of "success" - user should finish Claude's onboarding before closing
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_OAUTH_TOKEN, {
terminalId: terminal.id,
profileId,
email: emailFromOutput || keychainCreds.email || profile?.email,
success: true,
needsOnboarding: true,
detectedAt: new Date().toISOString()
} as OAuthTokenEvent);
} else {
// Token not in Keychain yet, but profile may still be authenticated via configDir
// Check if profile has valid auth (credentials exist in configDir)
@@ -559,19 +564,16 @@ export function handleOAuthToken(
// Set flag to watch for Claude's ready state (onboarding complete)
terminal.awaitingOnboardingComplete = true;
const win = getWindow();
if (win) {
// needsOnboarding: true tells the UI to show "complete setup" message
// instead of "success" - user should finish Claude's onboarding before closing
win.webContents.send(IPC_CHANNELS.TERMINAL_OAUTH_TOKEN, {
terminalId: terminal.id,
profileId,
email: emailFromOutput || profile?.email,
success: true,
needsOnboarding: true,
detectedAt: new Date().toISOString()
} as OAuthTokenEvent);
}
// needsOnboarding: true tells the UI to show "complete setup" message
// instead of "success" - user should finish Claude's onboarding before closing
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_OAUTH_TOKEN, {
terminalId: terminal.id,
profileId,
email: emailFromOutput || profile?.email,
success: true,
needsOnboarding: true,
detectedAt: new Date().toISOString()
} as OAuthTokenEvent);
} else {
console.warn('[ClaudeIntegration] Login successful but Keychain token not found and no credentials in configDir - user may need to complete authentication manually');
}
@@ -622,16 +624,13 @@ export function handleOAuthToken(
clearKeychainCache(profile.configDir);
console.warn('[ClaudeIntegration] Profile credentials verified (not caching token):', profileId);
const win = getWindow();
if (win) {
win.webContents.send(IPC_CHANNELS.TERMINAL_OAUTH_TOKEN, {
terminalId: terminal.id,
profileId,
email,
success: true,
detectedAt: new Date().toISOString()
} as OAuthTokenEvent);
}
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_OAUTH_TOKEN, {
terminalId: terminal.id,
profileId,
email,
success: true,
detectedAt: new Date().toISOString()
} as OAuthTokenEvent);
} else {
console.error('[ClaudeIntegration] Profile not found for OAuth token:', profileId);
}
@@ -645,17 +644,14 @@ export function handleOAuthToken(
// Defensive null check for active profile
if (!activeProfile) {
console.error('[ClaudeIntegration] Failed to update profile: no active profile found');
const win = getWindow();
if (win) {
win.webContents.send(IPC_CHANNELS.TERMINAL_OAUTH_TOKEN, {
terminalId: terminal.id,
profileId: undefined,
email,
success: false,
message: 'No active profile found',
detectedAt: new Date().toISOString()
} as OAuthTokenEvent);
}
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_OAUTH_TOKEN, {
terminalId: terminal.id,
profileId: undefined,
email,
success: false,
message: 'No active profile found',
detectedAt: new Date().toISOString()
} as OAuthTokenEvent);
return;
}
@@ -686,16 +682,13 @@ export function handleOAuthToken(
clearKeychainCache(activeProfile.configDir);
console.warn('[ClaudeIntegration] Active profile credentials verified (not caching token):', activeProfile.name);
const win = getWindow();
if (win) {
win.webContents.send(IPC_CHANNELS.TERMINAL_OAUTH_TOKEN, {
terminalId: terminal.id,
profileId: activeProfile.id,
email,
success: true,
detectedAt: new Date().toISOString()
} as OAuthTokenEvent);
}
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_OAUTH_TOKEN, {
terminalId: terminal.id,
profileId: activeProfile.id,
email,
success: true,
detectedAt: new Date().toISOString()
} as OAuthTokenEvent);
}
}
@@ -785,14 +778,11 @@ export function handleOnboardingComplete(
}
}
const win = getWindow();
if (win) {
win.webContents.send(IPC_CHANNELS.TERMINAL_ONBOARDING_COMPLETE, {
terminalId: terminal.id,
profileId,
detectedAt: new Date().toISOString()
} as OnboardingCompleteEvent);
}
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_ONBOARDING_COMPLETE, {
terminalId: terminal.id,
profileId,
detectedAt: new Date().toISOString()
} as OnboardingCompleteEvent);
// Trigger immediate usage fetch after successful re-authentication
// This gives the user immediate feedback that their account is working
@@ -845,10 +835,7 @@ export function handleClaudeSessionId(
SessionHandler.updateClaudeSessionId(terminal.projectPath, terminal.id, sessionId);
}
const win = getWindow();
if (win) {
win.webContents.send(IPC_CHANNELS.TERMINAL_CLAUDE_SESSION, terminal.id, sessionId);
}
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_CLAUDE_SESSION, terminal.id, sessionId);
}
/**
@@ -879,10 +866,7 @@ export function handleClaudeExit(
}
// Notify renderer to update UI
const win = getWindow();
if (win) {
win.webContents.send(IPC_CHANNELS.TERMINAL_CLAUDE_EXIT, terminal.id);
}
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_CLAUDE_EXIT, terminal.id);
}
/**
@@ -1109,7 +1093,9 @@ export function invokeClaude(
const cwdCommand = buildCdCommand(cwd, terminal.shellType);
const { command: claudeCmd, env: claudeEnv } = getClaudeCliInvocation();
const escapedClaudeCmd = escapeShellCommand(claudeCmd);
const pathPrefix = buildPathPrefix(claudeEnv.PATH || '');
const pathPrefix = isAbsoluteExecutableCommand(claudeCmd)
? ''
: buildPathPrefix(claudeEnv.PATH || '');
const needsEnvOverride: boolean = !!(profileId && profileId !== previousProfileId);
debugLog('[ClaudeIntegration:invokeClaude] Environment override check:', {
@@ -1196,7 +1182,9 @@ export function resumeClaude(
const { command: claudeCmd, env: claudeEnv } = getClaudeCliInvocation();
const escapedClaudeCmd = escapeShellCommand(claudeCmd);
const pathPrefix = buildPathPrefix(claudeEnv.PATH || '');
const pathPrefix = isAbsoluteExecutableCommand(claudeCmd)
? ''
: buildPathPrefix(claudeEnv.PATH || '');
// Always use --continue which resumes the most recent session in the current directory.
// This is more reliable than --resume with session IDs since Auto Claude already restores
@@ -1211,7 +1199,10 @@ export function resumeClaude(
console.warn('[ClaudeIntegration:resumeClaude] sessionId parameter is deprecated and ignored; using claude --continue instead');
}
const command = `${pathPrefix}${escapedClaudeCmd} --continue`;
// Preserve YOLO mode flag from terminal's stored state
const extraFlags = terminal.dangerouslySkipPermissions ? YOLO_MODE_FLAG : '';
const command = `${pathPrefix}${escapedClaudeCmd} --continue${extraFlags}`;
// Use PtyManager.writeToPty for safer write with error handling
PtyManager.writeToPty(terminal, `${command}\r`);
@@ -1220,10 +1211,7 @@ export function resumeClaude(
// This preserves user-customized names and prevents renaming on every resume
if (shouldAutoRenameTerminal(terminal.title)) {
terminal.title = 'Claude';
const win = getWindow();
if (win) {
win.webContents.send(IPC_CHANNELS.TERMINAL_TITLE_CHANGE, terminal.id, 'Claude');
}
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_TITLE_CHANGE, terminal.id, 'Claude');
}
// Persist session
@@ -1313,7 +1301,9 @@ export async function invokeClaudeAsync(
});
const escapedClaudeCmd = escapeShellCommand(claudeCmd);
const pathPrefix = buildPathPrefix(claudeEnv.PATH || '');
const pathPrefix = isAbsoluteExecutableCommand(claudeCmd)
? ''
: buildPathPrefix(claudeEnv.PATH || '');
const needsEnvOverride: boolean = !!(profileId && profileId !== previousProfileId);
debugLog('[ClaudeIntegration:invokeClaudeAsync] Environment override check:', {
@@ -1386,7 +1376,8 @@ export async function invokeClaudeAsync(
export async function resumeClaudeAsync(
terminal: TerminalProcess,
sessionId: string | undefined,
getWindow: WindowGetter
getWindow: WindowGetter,
options?: { migratedSession?: boolean }
): Promise<void> {
// Track terminal state for cleanup on error
const wasClaudeMode = terminal.isClaudeMode;
@@ -1409,7 +1400,9 @@ export async function resumeClaudeAsync(
});
const escapedClaudeCmd = escapeShellCommand(claudeCmd);
const pathPrefix = buildPathPrefix(claudeEnv.PATH || '');
const pathPrefix = isAbsoluteExecutableCommand(claudeCmd)
? ''
: buildPathPrefix(claudeEnv.PATH || '');
// Always use --continue which resumes the most recent session in the current directory.
// This is more reliable than --resume with session IDs since Auto Claude already restores
@@ -1419,12 +1412,19 @@ export async function resumeClaudeAsync(
// and we don't want stale IDs persisting through SessionHandler.persistSessionAsync().
terminal.claudeSessionId = undefined;
// Deprecation warning for callers still passing sessionId
if (sessionId) {
// Deprecation warning for callers still passing sessionId (skip for migrated sessions)
if (sessionId && !options?.migratedSession) {
console.warn('[ClaudeIntegration:resumeClaudeAsync] sessionId parameter is deprecated and ignored; using claude --continue instead');
}
const command = `${pathPrefix}${escapedClaudeCmd} --continue`;
if (options?.migratedSession) {
debugLog('[ClaudeIntegration:resumeClaudeAsync] Post-swap resume for terminal:', terminal.id);
}
// Preserve YOLO mode flag from terminal's stored state
const extraFlags = terminal.dangerouslySkipPermissions ? YOLO_MODE_FLAG : '';
const command = `${pathPrefix}${escapedClaudeCmd} --continue${extraFlags}`;
// Use PtyManager.writeToPty for safer write with error handling
PtyManager.writeToPty(terminal, `${command}\r`);
@@ -1433,10 +1433,7 @@ export async function resumeClaudeAsync(
// This preserves user-customized names and prevents renaming on every resume
if (shouldAutoRenameTerminal(terminal.title)) {
terminal.title = 'Claude';
const win = getWindow();
if (win) {
win.webContents.send(IPC_CHANNELS.TERMINAL_TITLE_CHANGE, terminal.id, 'Claude');
}
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_TITLE_CHANGE, terminal.id, 'Claude');
}
// Persist session (async, fire-and-forget to prevent main process blocking)
+49 -5
View File
@@ -209,18 +209,25 @@ export function setupPtyHandlers(
onExitCallback: (terminal: TerminalProcess) => void
): void {
const { id, pty: ptyProcess } = terminal;
terminal.hasExited = false;
// Handle data from terminal
ptyProcess.onData((data) => {
// Shutdown guard (GitHub #1469): skip processing to avoid accessing
// destroyed BrowserWindow.webContents, which triggers pty.node SIGABRT
if (isShuttingDown) return;
if (terminal.hasExited) return;
// Append to output buffer (limit to 100KB)
terminal.outputBuffer = (terminal.outputBuffer + data).slice(-100000);
// Call custom data handler
onDataCallback(terminal, data);
// Call custom data handler. This must never crash the main process:
// parser logic in higher layers can throw on unexpected output.
try {
onDataCallback(terminal, data);
} catch (error) {
debugError('[PtyManager] onData callback failed for terminal:', id, 'error:', error);
}
// Send to renderer with isDestroyed() check to prevent crashes
// when the window is closed during terminal activity
@@ -229,6 +236,9 @@ export function setupPtyHandlers(
// Handle terminal exit
ptyProcess.onExit(({ exitCode }) => {
terminal.hasExited = true;
// Drop any queued writes for this terminal to avoid writing to dead PTYs.
pendingWrites.delete(id);
debugLog('[PtyManager] Terminal exited:', id, 'code:', exitCode);
// Always resolve pending exit promises, even during shutdown
@@ -248,8 +258,13 @@ export function setupPtyHandlers(
// when the window is closed during terminal exit
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_EXIT, id, exitCode);
// Call custom exit handler
onExitCallback(terminal);
// Call custom exit handler. Guard against unexpected exceptions so PTY exit
// handling remains robust and doesn't take down the main process.
try {
onExitCallback(terminal);
} catch (error) {
debugError('[PtyManager] onExit callback failed for terminal:', id, 'error:', error);
}
// Only delete if this is the SAME terminal object (not a newly created one with same ID).
// This prevents a race where destroyTerminal() awaits PTY exit, a new terminal is created
@@ -285,6 +300,11 @@ const pendingWrites = new Map<string, Promise<void>>();
*/
function performWrite(terminal: TerminalProcess, data: string): Promise<void> {
return new Promise((resolve) => {
if (terminal.hasExited) {
resolve();
return;
}
// For large commands, write in chunks to prevent blocking
if (data.length > CHUNKED_WRITE_THRESHOLD) {
debugLog('[PtyManager:writeToPty] Large write detected, using chunked write');
@@ -293,7 +313,7 @@ function performWrite(terminal: TerminalProcess, data: string): Promise<void> {
const writeChunk = () => {
// Check if terminal is still valid before writing
if (!terminal.pty) {
if (!terminal.pty || terminal.hasExited) {
debugError('[PtyManager:writeToPty] Terminal PTY no longer valid, aborting chunked write');
resolve();
return;
@@ -339,6 +359,10 @@ function performWrite(terminal: TerminalProcess, data: string): Promise<void> {
*/
export function writeToPty(terminal: TerminalProcess, data: string): void {
debugLog('[PtyManager:writeToPty] About to write to pty, data length:', data.length);
if (terminal.hasExited) {
debugError('[PtyManager:writeToPty] Skipping write to exited terminal:', terminal.id);
return;
}
// Get the previous write Promise for this terminal (if any)
const previousWrite = pendingWrites.get(terminal.id) || Promise.resolve();
@@ -366,6 +390,11 @@ export function writeToPty(terminal: TerminalProcess, data: string): void {
* @returns true if resize was successful, false otherwise
*/
export function resizePty(terminal: TerminalProcess, cols: number, rows: number): boolean {
if (terminal.hasExited) {
debugError('[PtyManager] Resize skipped for exited terminal:', terminal.id);
return false;
}
// Validate dimensions
if (cols <= 0 || rows <= 0 || !Number.isFinite(cols) || !Number.isFinite(rows)) {
debugError('[PtyManager] Invalid resize dimensions - terminal:', terminal.id, 'cols:', cols, 'rows:', rows);
@@ -375,6 +404,17 @@ export function resizePty(terminal: TerminalProcess, cols: number, rows: number)
try {
const prevCols = terminal.pty.cols;
const prevRows = terminal.pty.rows;
// If dimensions are unchanged, force SIGWINCH via a resize cycle.
// On macOS/Linux, ioctl(TIOCSWINSZ) only sends SIGWINCH when size actually
// changes. This matters after project switch: PTY persists with old dimensions,
// terminal remounts at same size, TUI apps (Claude Code) never get SIGWINCH
// and never redraw — leaving the terminal blank.
if (prevCols === cols && prevRows === rows) {
debugLog('[PtyManager] Same-dimension resize detected, forcing SIGWINCH cycle for terminal:', terminal.id);
terminal.pty.resize(Math.max(1, cols - 1), rows);
}
debugLog('[PtyManager] Resizing PTY - terminal:', terminal.id, 'from:', prevCols, 'x', prevRows, 'to:', cols, 'x', rows);
terminal.pty.resize(cols, rows);
debugLog('[PtyManager] PTY resized - actual dimensions now:', terminal.pty.cols, 'x', terminal.pty.rows);
@@ -394,6 +434,10 @@ export function resizePty(terminal: TerminalProcess, cols: number, rows: number)
export function killPty(terminal: TerminalProcess, waitForExit: true): Promise<void>;
export function killPty(terminal: TerminalProcess, waitForExit?: false): void;
export function killPty(terminal: TerminalProcess, waitForExit?: boolean): Promise<void> | void {
if (terminal.hasExited) {
return waitForExit ? Promise.resolve() : undefined;
}
if (waitForExit) {
const exitPromise = waitForPtyExit(terminal.id);
try {
@@ -225,6 +225,18 @@ export function persistAllSessions(terminals: Map<string, TerminalProcess>): voi
});
}
/**
* Clear a terminal ID from pendingDelete, allowing session saves to proceed.
*
* Must be called when re-creating a terminal with a previously-used ID
* (e.g., worktree switching, terminal restart after shell exit). Without this,
* the pendingDelete guard blocks persistence for the new terminal.
*/
export function clearPendingDelete(terminalId: string): void {
const store = getTerminalSessionStore();
store.clearPendingDelete(terminalId);
}
/**
* Remove a session from persistent storage
*/
@@ -7,6 +7,7 @@ import * as OutputParser from './output-parser';
import * as ClaudeIntegration from './claude-integration-handler';
import type { TerminalProcess, WindowGetter } from './types';
import { IPC_CHANNELS } from '../../shared/constants';
import { safeSendToRenderer } from '../ipc-handlers/utils';
/**
* Event handler callbacks
@@ -109,10 +110,7 @@ export function createEventCallbacks(
ClaudeIntegration.handleOnboardingComplete(terminal, data, getWindow);
},
onClaudeBusyChange: (terminal, isBusy) => {
const win = getWindow();
if (win) {
win.webContents.send(IPC_CHANNELS.TERMINAL_CLAUDE_BUSY, terminal.id, isBusy);
}
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_CLAUDE_BUSY, terminal.id, isBusy);
},
onClaudeExit: (terminal) => {
ClaudeIntegration.handleClaudeExit(terminal, getWindow);
@@ -54,6 +54,13 @@ export async function createTerminal(
return { success: true };
}
// Clear any pendingDelete for this terminal ID. This handles the case where
// a terminal is destroyed and immediately re-created with the same ID (e.g.,
// worktree switching, terminal restart after shell exit). Without this, the
// pendingDelete guard (5-second window) blocks session persistence for the
// new terminal, causing it to be invisible to the session store.
SessionHandler.clearPendingDelete(id);
try {
// For auth terminals, don't inject existing OAuth token - we want a fresh login
const profileEnv = skipOAuthToken ? {} : PtyManager.getActiveProfileEnv();
@@ -101,6 +108,7 @@ export async function createTerminal(
id,
pty: ptyProcess,
isClaudeMode: false,
hasExited: false,
projectPath,
cwd: terminalCwd,
outputBuffer: '',
@@ -11,7 +11,7 @@ import type {
TerminalProcess,
WindowGetter,
TerminalOperationResult,
TerminalProfileChangeInfo
TerminalProfileChangeInfo,
} from './types';
import * as PtyManager from './pty-manager';
import * as SessionHandler from './session-handler';
@@ -26,6 +26,8 @@ export class TerminalManager {
private saveTimer: NodeJS.Timeout | null = null;
private lastNotifiedRateLimitReset: Map<string, string> = new Map();
private eventCallbacks: TerminalEventHandler.EventHandlerCallbacks;
/** Server-side storage for YOLO mode flags during profile migration (sessionId → flag) */
private migratedSessionFlags: Map<string, boolean> = new Map();
constructor(getWindow: WindowGetter) {
this.getWindow = getWindow;
@@ -114,6 +116,7 @@ export class TerminalManager {
* Kill all terminal processes
*/
async killAll(): Promise<void> {
this.migratedSessionFlags.clear();
this.saveTimer = await TerminalLifecycle.destroyAllTerminals(
this.terminals,
this.saveTimer
@@ -223,13 +226,36 @@ export class TerminalManager {
/**
* Resume Claude in a terminal asynchronously (non-blocking)
*/
async resumeClaudeAsync(id: string, sessionId?: string): Promise<void> {
async resumeClaudeAsync(id: string, sessionId?: string, options?: { migratedSession?: boolean }): Promise<void> {
const terminal = this.terminals.get(id);
if (!terminal) {
// Clean up stale migratedSessionFlags if terminal no longer exists
if (options?.migratedSession && sessionId) {
this.migratedSessionFlags.delete(sessionId);
}
return;
}
await ClaudeIntegration.resumeClaudeAsync(terminal, sessionId, this.getWindow);
// For migrated sessions, restore YOLO mode from server-side storage
// (set during profile change in storeMigratedSessionFlag)
if (options?.migratedSession && sessionId) {
const storedFlag = this.migratedSessionFlags.get(sessionId);
if (storedFlag !== undefined) {
terminal.dangerouslySkipPermissions = storedFlag;
this.migratedSessionFlags.delete(sessionId);
}
}
await ClaudeIntegration.resumeClaudeAsync(terminal, sessionId, this.getWindow, options);
}
/**
* Store YOLO mode flag for a session being migrated during profile swap.
* Called from the profile change handler before the renderer recreates terminals.
* The flag is consumed by resumeClaudeAsync when the new terminal resumes.
*/
storeMigratedSessionFlag(sessionId: string, dangerouslySkipPermissions: boolean): void {
this.migratedSessionFlags.set(sessionId, dangerouslySkipPermissions);
}
/**
@@ -387,7 +413,8 @@ export class TerminalManager {
projectPath: terminal.projectPath,
claudeSessionId: terminal.claudeSessionId,
claudeProfileId: terminal.claudeProfileId,
isClaudeMode: terminal.isClaudeMode
isClaudeMode: terminal.isClaudeMode,
dangerouslySkipPermissions: terminal.dangerouslySkipPermissions
});
}
+3
View File
@@ -28,6 +28,8 @@ export interface TerminalProcess {
shellType?: WindowsShellType;
/** Whether this terminal is waiting for Claude onboarding to complete (login flow) */
awaitingOnboardingComplete?: boolean;
/** Whether PTY has emitted exit; used to avoid writes/resizes on dead PTYs */
hasExited?: boolean;
}
/**
@@ -99,4 +101,5 @@ export interface TerminalProfileChangeInfo {
claudeSessionId?: string;
claudeProfileId?: string;
isClaudeMode: boolean;
dangerouslySkipPermissions?: boolean;
}
@@ -285,6 +285,9 @@ export interface GitHubAPI {
getPRReview: (projectId: string, prNumber: number) => Promise<PRReviewResult | null>;
getPRReviewsBatch: (projectId: string, prNumbers: number[]) => Promise<Record<number, PRReviewResult | null>>;
// External review notification (renderer tells main process about external review completion/timeout)
notifyExternalReviewComplete: (projectId: string, prNumber: number, result: PRReviewResult | null) => Promise<void>;
// Follow-up review operations
checkNewCommits: (projectId: string, prNumber: number) => Promise<NewCommitsCheck>;
checkMergeReadiness: (projectId: string, prNumber: number) => Promise<MergeReadiness>;
@@ -308,6 +311,9 @@ export interface GitHubAPI {
onPRReviewError: (
callback: (projectId: string, error: { prNumber: number; error: string }) => void
) => IpcListenerCleanup;
onPRReviewStateChange: (
callback: (key: string, state: PRReviewStatePayload) => void
) => IpcListenerCleanup;
onPRLogsUpdated: (
callback: (projectId: string, data: { prNumber: number; entryCount: number }) => void
) => IpcListenerCleanup;
@@ -456,6 +462,23 @@ export interface PRReviewProgress {
message: string;
}
/**
* PR review state payload (emitted on state machine transitions)
*/
export interface PRReviewStatePayload {
state: string;
prNumber: number;
projectId: string;
isReviewing: boolean;
startedAt: string | null;
progress: PRReviewProgress | null;
result: PRReviewResult | null;
previousResult: PRReviewResult | null;
error: string | null;
isExternalReview: boolean;
isFollowup: boolean;
}
/**
* PR review log entry type
*/
@@ -740,6 +763,10 @@ export const createGitHubAPI = (): GitHubAPI => ({
getPRReviewsBatch: (projectId: string, prNumbers: number[]): Promise<Record<number, PRReviewResult | null>> =>
invokeIpc(IPC_CHANNELS.GITHUB_PR_GET_REVIEWS_BATCH, projectId, prNumbers),
// External review notification
notifyExternalReviewComplete: (projectId: string, prNumber: number, result: PRReviewResult | null): Promise<void> =>
invokeIpc(IPC_CHANNELS.GITHUB_PR_NOTIFY_EXTERNAL_REVIEW_COMPLETE, projectId, prNumber, result),
// Follow-up review operations
checkNewCommits: (projectId: string, prNumber: number): Promise<NewCommitsCheck> =>
invokeIpc(IPC_CHANNELS.GITHUB_PR_CHECK_NEW_COMMITS, projectId, prNumber),
@@ -780,6 +807,11 @@ export const createGitHubAPI = (): GitHubAPI => ({
): IpcListenerCleanup =>
createIpcListener(IPC_CHANNELS.GITHUB_PR_REVIEW_ERROR, callback),
onPRReviewStateChange: (
callback: (key: string, state: PRReviewStatePayload) => void
): IpcListenerCleanup =>
createIpcListener(IPC_CHANNELS.GITHUB_PR_REVIEW_STATE_CHANGE, callback),
onPRLogsUpdated: (
callback: (projectId: string, data: { prNumber: number; entryCount: number }) => void
): IpcListenerCleanup =>
@@ -5,6 +5,7 @@ import type {
InsightsChatStatus,
InsightsStreamChunk,
InsightsModelConfig,
ImageAttachment,
Task,
TaskMetadata,
IPCResult
@@ -17,7 +18,7 @@ import { createIpcListener, invokeIpc, sendIpc, IpcListenerCleanup } from './ipc
export interface InsightsAPI {
// Operations
getInsightsSession: (projectId: string) => Promise<IPCResult<InsightsSession | null>>;
sendInsightsMessage: (projectId: string, message: string, modelConfig?: InsightsModelConfig) => void;
sendInsightsMessage: (projectId: string, message: string, modelConfig?: InsightsModelConfig, images?: ImageAttachment[]) => void;
clearInsightsSession: (projectId: string) => Promise<IPCResult>;
createTaskFromInsights: (
projectId: string,
@@ -25,10 +26,14 @@ export interface InsightsAPI {
description: string,
metadata?: TaskMetadata
) => Promise<IPCResult<Task>>;
listInsightsSessions: (projectId: string) => Promise<IPCResult<InsightsSessionSummary[]>>;
listInsightsSessions: (projectId: string, includeArchived?: boolean) => Promise<IPCResult<InsightsSessionSummary[]>>;
newInsightsSession: (projectId: string) => Promise<IPCResult<InsightsSession>>;
switchInsightsSession: (projectId: string, sessionId: string) => Promise<IPCResult<InsightsSession | null>>;
deleteInsightsSession: (projectId: string, sessionId: string) => Promise<IPCResult>;
deleteInsightsSessions: (projectId: string, sessionIds: string[]) => Promise<IPCResult<{ deletedIds: string[]; failedIds: string[] }>>;
archiveInsightsSession: (projectId: string, sessionId: string) => Promise<IPCResult>;
archiveInsightsSessions: (projectId: string, sessionIds: string[]) => Promise<IPCResult<{ archivedIds: string[]; failedIds: string[] }>>;
unarchiveInsightsSession: (projectId: string, sessionId: string) => Promise<IPCResult>;
renameInsightsSession: (projectId: string, sessionId: string, newTitle: string) => Promise<IPCResult>;
updateInsightsModelConfig: (projectId: string, sessionId: string, modelConfig: InsightsModelConfig) => Promise<IPCResult>;
@@ -55,8 +60,8 @@ export const createInsightsAPI = (): InsightsAPI => ({
getInsightsSession: (projectId: string): Promise<IPCResult<InsightsSession | null>> =>
invokeIpc(IPC_CHANNELS.INSIGHTS_GET_SESSION, projectId),
sendInsightsMessage: (projectId: string, message: string, modelConfig?: InsightsModelConfig): void =>
sendIpc(IPC_CHANNELS.INSIGHTS_SEND_MESSAGE, projectId, message, modelConfig),
sendInsightsMessage: (projectId: string, message: string, modelConfig?: InsightsModelConfig, images?: ImageAttachment[]): void =>
sendIpc(IPC_CHANNELS.INSIGHTS_SEND_MESSAGE, projectId, message, modelConfig, images),
clearInsightsSession: (projectId: string): Promise<IPCResult> =>
invokeIpc(IPC_CHANNELS.INSIGHTS_CLEAR_SESSION, projectId),
@@ -69,8 +74,8 @@ export const createInsightsAPI = (): InsightsAPI => ({
): Promise<IPCResult<Task>> =>
invokeIpc(IPC_CHANNELS.INSIGHTS_CREATE_TASK, projectId, title, description, metadata),
listInsightsSessions: (projectId: string): Promise<IPCResult<InsightsSessionSummary[]>> =>
invokeIpc(IPC_CHANNELS.INSIGHTS_LIST_SESSIONS, projectId),
listInsightsSessions: (projectId: string, includeArchived?: boolean): Promise<IPCResult<InsightsSessionSummary[]>> =>
invokeIpc(IPC_CHANNELS.INSIGHTS_LIST_SESSIONS, projectId, includeArchived),
newInsightsSession: (projectId: string): Promise<IPCResult<InsightsSession>> =>
invokeIpc(IPC_CHANNELS.INSIGHTS_NEW_SESSION, projectId),
@@ -81,6 +86,18 @@ export const createInsightsAPI = (): InsightsAPI => ({
deleteInsightsSession: (projectId: string, sessionId: string): Promise<IPCResult> =>
invokeIpc(IPC_CHANNELS.INSIGHTS_DELETE_SESSION, projectId, sessionId),
deleteInsightsSessions: (projectId: string, sessionIds: string[]): Promise<IPCResult<{ deletedIds: string[]; failedIds: string[] }>> =>
invokeIpc(IPC_CHANNELS.INSIGHTS_DELETE_SESSIONS, projectId, sessionIds),
archiveInsightsSession: (projectId: string, sessionId: string): Promise<IPCResult> =>
invokeIpc(IPC_CHANNELS.INSIGHTS_ARCHIVE_SESSION, projectId, sessionId),
archiveInsightsSessions: (projectId: string, sessionIds: string[]): Promise<IPCResult<{ archivedIds: string[]; failedIds: string[] }>> =>
invokeIpc(IPC_CHANNELS.INSIGHTS_ARCHIVE_SESSIONS, projectId, sessionIds),
unarchiveInsightsSession: (projectId: string, sessionId: string): Promise<IPCResult> =>
invokeIpc(IPC_CHANNELS.INSIGHTS_UNARCHIVE_SESSION, projectId, sessionId),
renameInsightsSession: (projectId: string, sessionId: string, newTitle: string): Promise<IPCResult> =>
invokeIpc(IPC_CHANNELS.INSIGHTS_RENAME_SESSION, projectId, sessionId, newTitle),
@@ -4,6 +4,7 @@ import type {
RoadmapFeatureStatus,
RoadmapGenerationStatus,
PersistedRoadmapProgress,
CompetitorAnalysis,
Task,
IPCResult
} from '../../../shared/types';
@@ -30,6 +31,9 @@ export interface RoadmapAPI {
featureId: string
) => Promise<IPCResult<Task>>;
// Competitor analysis
saveCompetitorAnalysis: (projectId: string, competitorAnalysis: CompetitorAnalysis) => Promise<IPCResult>;
// Progress persistence
saveRoadmapProgress: (projectId: string, progress: PersistedRoadmapProgress) => Promise<IPCResult>;
loadRoadmapProgress: (projectId: string) => Promise<IPCResult<PersistedRoadmapProgress | null>>;
@@ -86,6 +90,10 @@ export const createRoadmapAPI = (): RoadmapAPI => ({
): Promise<IPCResult<Task>> =>
invokeIpc(IPC_CHANNELS.ROADMAP_CONVERT_TO_SPEC, projectId, featureId),
// Competitor analysis
saveCompetitorAnalysis: (projectId: string, competitorAnalysis: CompetitorAnalysis): Promise<IPCResult> =>
invokeIpc(IPC_CHANNELS.COMPETITOR_ANALYSIS_SAVE, projectId, competitorAnalysis),
// Progress persistence
saveRoadmapProgress: (projectId: string, progress: PersistedRoadmapProgress): Promise<IPCResult> =>
invokeIpc(IPC_CHANNELS.ROADMAP_PROGRESS_SAVE, projectId, progress),
+2 -2
View File
@@ -44,7 +44,7 @@ export interface TaskAPI {
updateTaskStatus: (
taskId: string,
status: TaskStatus,
options?: { forceCleanup?: boolean }
options?: { forceCleanup?: boolean; keepWorktree?: boolean }
) => Promise<IPCResult & { worktreeExists?: boolean; worktreePath?: string }>;
recoverStuckTask: (
taskId: string,
@@ -135,7 +135,7 @@ export const createTaskAPI = (): TaskAPI => ({
updateTaskStatus: (
taskId: string,
status: TaskStatus,
options?: { forceCleanup?: boolean }
options?: { forceCleanup?: boolean; keepWorktree?: boolean }
): Promise<IPCResult & { worktreeExists?: boolean; worktreePath?: string }> =>
ipcRenderer.invoke(IPC_CHANNELS.TASK_UPDATE_STATUS, taskId, status, options),
@@ -47,7 +47,7 @@ export interface TerminalAPI {
rows?: number
) => Promise<IPCResult<import('../../shared/types').TerminalRestoreResult>>;
clearTerminalSessions: (projectPath: string) => Promise<IPCResult>;
resumeClaudeInTerminal: (id: string, sessionId?: string) => void;
resumeClaudeInTerminal: (id: string, sessionId?: string, options?: { migratedSession?: boolean }) => void;
activateDeferredClaudeResume: (id: string) => void;
getTerminalSessionDates: (projectPath?: string) => Promise<IPCResult<import('../../shared/types').SessionDateInfo[]>>;
getTerminalSessionsForDate: (
@@ -166,8 +166,8 @@ export const createTerminalAPI = (): TerminalAPI => ({
clearTerminalSessions: (projectPath: string): Promise<IPCResult> =>
ipcRenderer.invoke(IPC_CHANNELS.TERMINAL_CLEAR_SESSIONS, projectPath),
resumeClaudeInTerminal: (id: string, sessionId?: string): void =>
ipcRenderer.send(IPC_CHANNELS.TERMINAL_RESUME_CLAUDE, id, sessionId),
resumeClaudeInTerminal: (id: string, sessionId?: string, options?: { migratedSession?: boolean }): void =>
ipcRenderer.send(IPC_CHANNELS.TERMINAL_RESUME_CLAUDE, id, sessionId, options),
activateDeferredClaudeResume: (id: string): void =>
ipcRenderer.send(IPC_CHANNELS.TERMINAL_ACTIVATE_DEFERRED_RESUME, id),
@@ -3,7 +3,7 @@
* Tests Zustand store for roadmap state management including drag-and-drop actions
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { useRoadmapStore, getFeaturesByPhase, getFeaturesByPriority, getFeatureStats } from '../stores/roadmap-store';
import { useRoadmapStore, getFeaturesByPhase, getFeaturesByPriority, getFeatureStats, resetActors } from '../stores/roadmap-store';
import type {
Roadmap,
RoadmapFeature,
@@ -86,6 +86,8 @@ describe('Roadmap Store', () => {
afterEach(() => {
vi.clearAllMocks();
// Reset XState actors to prevent test pollution
resetActors();
});
describe('setRoadmap', () => {
@@ -623,6 +625,165 @@ describe('Roadmap Store', () => {
});
});
describe('setGenerationStatus catch-up logic', () => {
it('should advance from idle to analyzing', () => {
useRoadmapStore.getState().setGenerationStatus({
phase: 'analyzing',
progress: 10,
message: 'Analyzing...'
});
const status = useRoadmapStore.getState().generationStatus;
expect(status.phase).toBe('analyzing');
expect(status.progress).toBe(10);
expect(status.message).toBe('Analyzing...');
});
it('should advance from idle to discovering via catch-up', () => {
useRoadmapStore.getState().setGenerationStatus({
phase: 'discovering',
progress: 30,
message: 'Discovering...'
});
const status = useRoadmapStore.getState().generationStatus;
expect(status.phase).toBe('discovering');
expect(status.progress).toBe(30);
expect(status.message).toBe('Discovering...');
});
it('should advance from idle to generating via catch-up', () => {
useRoadmapStore.getState().setGenerationStatus({
phase: 'generating',
progress: 60,
message: 'Generating...'
});
const status = useRoadmapStore.getState().generationStatus;
expect(status.phase).toBe('generating');
expect(status.progress).toBe(60);
expect(status.message).toBe('Generating...');
});
it('should advance from idle to complete via catch-up', () => {
// First go through active states to build up context, then complete
useRoadmapStore.getState().setGenerationStatus({
phase: 'analyzing',
progress: 10,
message: 'Analyzing...'
});
useRoadmapStore.getState().setGenerationStatus({
phase: 'complete',
progress: 100,
message: 'Done'
});
const status = useRoadmapStore.getState().generationStatus;
expect(status.phase).toBe('complete');
expect(status.progress).toBe(100);
});
it('should advance from idle to error via catch-up', () => {
useRoadmapStore.getState().setGenerationStatus({
phase: 'error',
progress: 0,
message: '',
error: 'Something failed'
});
const status = useRoadmapStore.getState().generationStatus;
expect(status.phase).toBe('error');
expect(status.error).toBe('Something failed');
});
it('should reset from error and start new generation', () => {
// First put into error state
useRoadmapStore.getState().setGenerationStatus({
phase: 'error',
progress: 0,
message: '',
error: 'Failed'
});
expect(useRoadmapStore.getState().generationStatus.phase).toBe('error');
// Now start a new generation from error state
useRoadmapStore.getState().setGenerationStatus({
phase: 'analyzing',
progress: 5,
message: 'Restarting...'
});
const status = useRoadmapStore.getState().generationStatus;
expect(status.phase).toBe('analyzing');
expect(status.progress).toBe(5);
});
it('should send progress updates for active states', () => {
// Move to analyzing
useRoadmapStore.getState().setGenerationStatus({
phase: 'analyzing',
progress: 0,
message: 'Starting...'
});
// Update progress in analyzing
useRoadmapStore.getState().setGenerationStatus({
phase: 'analyzing',
progress: 50,
message: 'Halfway...'
});
const status = useRoadmapStore.getState().generationStatus;
expect(status.phase).toBe('analyzing');
expect(status.progress).toBe(50);
expect(status.message).toBe('Halfway...');
});
it('should be idempotent for idle-to-idle transitions', () => {
useRoadmapStore.getState().setGenerationStatus({
phase: 'idle',
progress: 0,
message: ''
});
const status = useRoadmapStore.getState().generationStatus;
expect(status.phase).toBe('idle');
expect(status.progress).toBe(0);
});
it('should handle complete-to-idle reset', () => {
useRoadmapStore.getState().setGenerationStatus({
phase: 'complete',
progress: 100,
message: 'Done'
});
expect(useRoadmapStore.getState().generationStatus.phase).toBe('complete');
useRoadmapStore.getState().setGenerationStatus({
phase: 'idle',
progress: 0,
message: ''
});
expect(useRoadmapStore.getState().generationStatus.phase).toBe('idle');
});
it('should preserve startedAt from persisted status on reload', () => {
const persistedStartedAt = new Date('2025-06-01T12:00:00Z');
useRoadmapStore.getState().setGenerationStatus({
phase: 'generating',
progress: 70,
message: 'Generating...',
startedAt: persistedStartedAt,
lastActivityAt: new Date()
});
const status = useRoadmapStore.getState().generationStatus;
expect(status.phase).toBe('generating');
expect(status.startedAt).toBeDefined();
expect(status.startedAt!.getTime()).toBe(persistedStartedAt.getTime());
});
});
describe('clearRoadmap', () => {
it('should clear roadmap and reset status', () => {
useRoadmapStore.setState({
@@ -0,0 +1,295 @@
/**
* AddCompetitorDialog - Dialog for adding manual competitors to the roadmap analysis
*
* Allows users to add known competitors with name, URL, description, and relevance.
* Follows the same dialog pattern as AddFeatureDialog for consistency.
*
* Features:
* - Form validation (name and URL required, URL format check)
* - Auto-prepends https:// if protocol is missing
* - Adds competitor to roadmap store and persists via IPC
*
* @example
* ```tsx
* <AddCompetitorDialog
* open={isAddDialogOpen}
* onOpenChange={setIsAddDialogOpen}
* onCompetitorAdded={(id) => console.log('Competitor added:', id)}
* projectId={projectId}
* />
* ```
*/
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Loader2, AlertCircle } from 'lucide-react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle
} from './ui/dialog';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Textarea } from './ui/textarea';
import { Label } from './ui/label';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from './ui/select';
import { useRoadmapStore } from '../stores/roadmap-store';
import type { CompetitorRelevance } from '../../shared/types';
/**
* Props for the AddCompetitorDialog component
*/
interface AddCompetitorDialogProps {
/** Whether the dialog is open */
open: boolean;
/** Callback when the dialog open state changes */
onOpenChange: (open: boolean) => void;
/** Optional callback when competitor is successfully added, receives the new competitor ID */
onCompetitorAdded?: (competitorId: string) => void;
/** Project ID for IPC save */
projectId: string;
}
// Relevance options (keys for translation)
const RELEVANCE_OPTIONS = [
{ value: 'high', labelKey: 'addCompetitor.highRelevance' },
{ value: 'medium', labelKey: 'addCompetitor.mediumRelevance' },
{ value: 'low', labelKey: 'addCompetitor.lowRelevance' }
] as const;
/**
* Basic URL validation - checks for a reasonable URL format
*/
function isValidUrl(url: string): boolean {
try {
new URL(url);
return true;
} catch {
return false;
}
}
/**
* Normalizes a URL by prepending https:// if no protocol is present
*/
function normalizeUrl(url: string): string {
const trimmed = url.trim();
if (!trimmed) return trimmed;
if (!/^https?:\/\//i.test(trimmed)) {
return `https://${trimmed}`;
}
return trimmed;
}
export function AddCompetitorDialog({
open,
onOpenChange,
onCompetitorAdded,
projectId
}: AddCompetitorDialogProps) {
const { t } = useTranslation('dialogs');
// Form state
const [name, setName] = useState('');
const [url, setUrl] = useState('');
const [description, setDescription] = useState('');
const [relevance, setRelevance] = useState<CompetitorRelevance>('medium');
// UI state
const [isSaving, setIsSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
// Store actions
const addCompetitor = useRoadmapStore((state) => state.addCompetitor);
// Reset form when dialog opens/closes
useEffect(() => {
if (open) {
setName('');
setUrl('');
setDescription('');
setRelevance('medium');
setError(null);
}
}, [open]);
const handleSave = async () => {
// Validate required fields
if (!name.trim()) {
setError(t('addCompetitor.nameRequired'));
return;
}
if (!url.trim()) {
setError(t('addCompetitor.urlRequired'));
return;
}
const normalizedUrl = normalizeUrl(url);
if (!isValidUrl(normalizedUrl)) {
setError(t('addCompetitor.invalidUrl'));
return;
}
setIsSaving(true);
setError(null);
try {
// Capture pre-add state for complete rollback
const previousAnalysis = useRoadmapStore.getState().competitorAnalysis;
// Add competitor to store
const newCompetitorId = addCompetitor({
name: name.trim(),
url: normalizedUrl,
description: description.trim(),
relevance
});
// Persist to file via IPC
const competitorAnalysis = useRoadmapStore.getState().competitorAnalysis;
if (competitorAnalysis) {
const result = await window.electronAPI.saveCompetitorAnalysis(projectId, competitorAnalysis);
if (!result.success) {
// Rollback store state since save failed
useRoadmapStore.getState().setCompetitorAnalysis(previousAnalysis);
throw new Error(result.error || t('addCompetitor.failedToAdd'));
}
}
// Success - close dialog and notify parent
onOpenChange(false);
onCompetitorAdded?.(newCompetitorId);
} catch (err) {
setError(err instanceof Error ? err.message : t('addCompetitor.failedToAdd'));
} finally {
setIsSaving(false);
}
};
const handleClose = () => {
if (!isSaving) {
onOpenChange(false);
}
};
// Form validation
const isValid = name.trim().length > 0 && url.trim().length > 0;
return (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="sm:max-w-[550px] max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="text-foreground">{t('addCompetitor.title')}</DialogTitle>
<DialogDescription>
{t('addCompetitor.description')}
</DialogDescription>
</DialogHeader>
<div className="space-y-5 py-4">
{/* Name (Required) */}
<div className="space-y-2">
<Label htmlFor="add-competitor-name" className="text-sm font-medium text-foreground">
{t('addCompetitor.competitorName')} <span className="text-destructive">*</span>
</Label>
<Input
id="add-competitor-name"
placeholder={t('addCompetitor.competitorNamePlaceholder')}
value={name}
onChange={(e) => setName(e.target.value)}
disabled={isSaving}
aria-required="true"
/>
</div>
{/* URL (Required) */}
<div className="space-y-2">
<Label htmlFor="add-competitor-url" className="text-sm font-medium text-foreground">
{t('addCompetitor.competitorUrl')} <span className="text-destructive">*</span>
</Label>
<Input
id="add-competitor-url"
placeholder={t('addCompetitor.competitorUrlPlaceholder')}
value={url}
onChange={(e) => setUrl(e.target.value)}
disabled={isSaving}
aria-required="true"
/>
</div>
{/* Description (Optional) */}
<div className="space-y-2">
<Label htmlFor="add-competitor-description" className="text-sm font-medium text-foreground">
{t('addCompetitor.competitorDescription')} <span className="text-muted-foreground font-normal">({t('addCompetitor.optional')})</span>
</Label>
<Textarea
id="add-competitor-description"
placeholder={t('addCompetitor.competitorDescriptionPlaceholder')}
value={description}
onChange={(e) => setDescription(e.target.value)}
rows={3}
disabled={isSaving}
/>
</div>
{/* Relevance (Optional) */}
<div className="space-y-2">
<Label htmlFor="add-competitor-relevance" className="text-sm font-medium text-foreground">
{t('addCompetitor.relevance')}
</Label>
<Select
value={relevance}
onValueChange={(value) => setRelevance(value as CompetitorRelevance)}
disabled={isSaving}
>
<SelectTrigger id="add-competitor-relevance">
<SelectValue placeholder={t('addCompetitor.selectRelevance')} />
</SelectTrigger>
<SelectContent>
{RELEVANCE_OPTIONS.map(({ value, labelKey }) => (
<SelectItem key={value} value={value}>
{t(labelKey)}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Error */}
{error && (
<div className="flex items-start gap-2 rounded-lg bg-destructive/10 border border-destructive/30 p-3 text-sm text-destructive" role="alert">
<AlertCircle className="h-4 w-4 mt-0.5 shrink-0" />
<span>{error}</span>
</div>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={handleClose} disabled={isSaving}>
{t('addCompetitor.cancel')}
</Button>
<Button
onClick={handleSave}
disabled={isSaving || !isValid}
>
{isSaving ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
{t('addCompetitor.adding')}
</>
) : (
t('addCompetitor.addCompetitor')
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useState, useCallback, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import {
Plus,
@@ -8,11 +8,15 @@ import {
Check,
X,
MoreVertical,
Loader2
Loader2,
CheckSquare,
Archive,
ArchiveRestore
} from 'lucide-react';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { ScrollArea } from './ui/scroll-area';
import { Checkbox } from './ui/checkbox';
import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip';
import {
DropdownMenu,
@@ -41,6 +45,12 @@ interface ChatHistorySidebarProps {
onSelectSession: (sessionId: string) => void;
onDeleteSession: (sessionId: string) => Promise<boolean>;
onRenameSession: (sessionId: string, newTitle: string) => Promise<boolean>;
onArchiveSession?: (sessionId: string) => Promise<void>;
onUnarchiveSession?: (sessionId: string) => Promise<void>;
onDeleteSessions?: (sessionIds: string[]) => Promise<void>;
onArchiveSessions?: (sessionIds: string[]) => Promise<void>;
showArchived?: boolean;
onToggleShowArchived?: () => void;
}
export function ChatHistorySidebar({
@@ -50,12 +60,64 @@ export function ChatHistorySidebar({
onNewSession,
onSelectSession,
onDeleteSession,
onRenameSession
onRenameSession,
onArchiveSession,
onUnarchiveSession,
onDeleteSessions,
onArchiveSessions,
showArchived = false,
onToggleShowArchived
}: ChatHistorySidebarProps) {
const { t } = useTranslation('common');
const [editingId, setEditingId] = useState<string | null>(null);
const [editTitle, setEditTitle] = useState('');
const [deleteSessionId, setDeleteSessionId] = useState<string | null>(null);
const [isSelectionMode, setIsSelectionMode] = useState(false);
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
const [bulkDeleteOpen, setBulkDeleteOpen] = useState(false);
const [bulkArchiveOpen, setBulkArchiveOpen] = useState(false);
// Clear selection when exiting selection mode
const handleToggleSelectionMode = useCallback(() => {
setIsSelectionMode((prev) => {
if (prev) {
setSelectedIds(new Set());
}
return !prev;
});
}, []);
// Prune selectedIds when sessions change - removes IDs for sessions no longer displayed
// Also resets when showArchived toggles
// biome-ignore lint/correctness/useExhaustiveDependencies: showArchived is intentionally a dependency to reset selection on filter change
useEffect(() => {
setSelectedIds((prev) => {
if (prev.size === 0) return prev;
const validIds = new Set(sessions.map((s) => s.id));
const pruned = new Set([...prev].filter((id) => validIds.has(id)));
return pruned.size === prev.size ? prev : pruned;
});
}, [sessions, showArchived]);
const handleToggleSelect = useCallback((sessionId: string) => {
setSelectedIds((prev) => {
const next = new Set(prev);
if (next.has(sessionId)) {
next.delete(sessionId);
} else {
next.add(sessionId);
}
return next;
});
}, []);
const handleSelectAll = useCallback(() => {
setSelectedIds(new Set(sessions.map((s) => s.id)));
}, [sessions]);
const handleClearSelection = useCallback(() => {
setSelectedIds(new Set());
}, []);
const handleStartEdit = (session: InsightsSessionSummary) => {
setEditingId(session.id);
@@ -82,6 +144,38 @@ export function ChatHistorySidebar({
}
};
const handleBulkDelete = async () => {
if (selectedIds.size > 0 && onDeleteSessions) {
try {
await onDeleteSessions(Array.from(selectedIds));
setSelectedIds(new Set());
} catch (error) {
console.error('Failed to delete sessions:', error);
} finally {
setBulkDeleteOpen(false);
}
}
};
const handleBulkArchive = () => {
if (selectedIds.size > 0 && onArchiveSessions) {
setBulkArchiveOpen(true);
}
};
const handleBulkArchiveConfirmed = async () => {
if (selectedIds.size > 0 && onArchiveSessions) {
try {
await onArchiveSessions(Array.from(selectedIds));
setSelectedIds(new Set());
} catch (error) {
console.error('Failed to archive sessions:', error);
} finally {
setBulkArchiveOpen(false);
}
}
};
const formatDate = (date: Date) => {
const now = new Date();
const d = new Date(date);
@@ -89,11 +183,11 @@ export function ChatHistorySidebar({
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
if (diffDays === 0) {
return 'Today';
return t('insights.today');
} else if (diffDays === 1) {
return 'Yesterday';
return t('insights.yesterday');
} else if (diffDays < 7) {
return `${diffDays} days ago`;
return t('insights.daysAgo', { count: diffDays });
} else {
return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
}
@@ -109,27 +203,90 @@ export function ChatHistorySidebar({
return groups;
}, {} as Record<string, InsightsSessionSummary[]>);
// Sessions selected for bulk delete preview
const sessionsToDelete = sessions.filter((s) => selectedIds.has(s.id));
return (
<div className="flex h-full w-64 flex-col border-r border-border bg-muted/30">
{/* Header */}
<div className="flex items-center justify-between border-b border-border px-3 py-3">
<h3 className="text-sm font-medium text-foreground">Chat History</h3>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={onNewSession}
aria-label={t('accessibility.newConversationAriaLabel')}
>
<Plus className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>{t('accessibility.newConversationAriaLabel')}</TooltipContent>
</Tooltip>
<h3 className="text-sm font-medium text-foreground">{t('insights.chatHistory')}</h3>
<div className="flex items-center gap-1">
{/* Selection mode toggle */}
<Tooltip>
<TooltipTrigger asChild>
<Button
variant={isSelectionMode ? 'secondary' : 'ghost'}
size="icon"
className="h-7 w-7"
onClick={handleToggleSelectionMode}
aria-label={isSelectionMode ? t('insights.exitSelectMode') : t('insights.selectMode')}
>
<CheckSquare className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>
{isSelectionMode ? t('insights.exitSelectMode') : t('insights.selectMode')}
</TooltipContent>
</Tooltip>
{/* Show archived toggle */}
{onToggleShowArchived && (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant={showArchived ? 'secondary' : 'ghost'}
size="icon"
className="h-7 w-7"
onClick={onToggleShowArchived}
aria-label={showArchived ? t('insights.hideArchived') : t('insights.showArchived')}
>
<Archive className={cn('h-4 w-4', showArchived && 'text-primary')} />
</Button>
</TooltipTrigger>
<TooltipContent>
{showArchived ? t('insights.hideArchived') : t('insights.showArchived')}
</TooltipContent>
</Tooltip>
)}
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={onNewSession}
aria-label={t('accessibility.newConversationAriaLabel')}
>
<Plus className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>{t('accessibility.newConversationAriaLabel')}</TooltipContent>
</Tooltip>
</div>
</div>
{/* Select All / Clear links */}
{isSelectionMode && sessions.length > 0 && (
<div className="flex items-center justify-between border-b border-border px-3 py-1.5">
<button
type="button"
className="text-xs text-primary hover:underline"
onClick={handleSelectAll}
>
{t('accessibility.selectAllAriaLabel')}
</button>
<button
type="button"
className="text-xs text-muted-foreground hover:underline"
onClick={handleClearSelection}
>
{t('accessibility.clearSelectionAriaLabel')}
</button>
</div>
)}
{/* Session list */}
<ScrollArea className="flex-1">
{isLoading ? (
@@ -138,7 +295,7 @@ export function ChatHistorySidebar({
</div>
) : sessions.length === 0 ? (
<div className="px-3 py-8 text-center text-sm text-muted-foreground">
No conversations yet
{t('insights.noConversations')}
</div>
) : (
<div className="py-2">
@@ -160,6 +317,14 @@ export function ChatHistorySidebar({
onCancelEdit={handleCancelEdit}
onEditTitleChange={setEditTitle}
onDelete={() => setDeleteSessionId(session.id)}
onArchive={onArchiveSession ? () => onArchiveSession(session.id) : undefined}
onUnarchive={
onUnarchiveSession ? () => onUnarchiveSession(session.id) : undefined
}
isArchived={!!session.archivedAt}
isSelectionMode={isSelectionMode}
isSelected={selectedIds.has(session.id)}
onToggleSelect={() => handleToggleSelect(session.id)}
/>
))}
</div>
@@ -168,19 +333,94 @@ export function ChatHistorySidebar({
)}
</ScrollArea>
{/* Delete confirmation dialog */}
{/* Bulk action toolbar */}
{isSelectionMode && selectedIds.size > 0 && (
<div className="flex items-center gap-2 border-t border-border px-3 py-2">
<Button
variant="destructive"
size="sm"
className="flex-1 text-xs"
onClick={() => setBulkDeleteOpen(true)}
>
<Trash2 className="mr-1.5 h-3.5 w-3.5" />
{t('selection.deleteSelected')} ({selectedIds.size})
</Button>
{onArchiveSessions && (
<Button
variant="secondary"
size="sm"
className="flex-1 text-xs"
onClick={handleBulkArchive}
>
<Archive className="mr-1.5 h-3.5 w-3.5" />
{t('insights.archiveSelected')} ({selectedIds.size})
</Button>
)}
</div>
)}
{/* Single delete confirmation dialog */}
<AlertDialog open={!!deleteSessionId} onOpenChange={() => setDeleteSessionId(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete conversation?</AlertDialogTitle>
<AlertDialogTitle>{t('insights.deleteTitle')}</AlertDialogTitle>
<AlertDialogDescription>
This will permanently delete this conversation and all its messages.
This action cannot be undone.
{t('insights.deleteDescription')}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={handleDelete}>Delete</AlertDialogAction>
<AlertDialogCancel>{t('buttons.cancel')}</AlertDialogCancel>
<AlertDialogAction onClick={handleDelete}>{t('actions.delete')}</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* Bulk delete confirmation dialog */}
<AlertDialog open={bulkDeleteOpen} onOpenChange={setBulkDeleteOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('insights.bulkDeleteTitle')}</AlertDialogTitle>
<AlertDialogDescription>
{t('insights.bulkDeleteDescription', { count: selectedIds.size })}
</AlertDialogDescription>
</AlertDialogHeader>
{sessionsToDelete.length > 0 && (
<div className="max-h-32 overflow-y-auto rounded border border-border p-2">
<p className="mb-1 text-xs font-medium text-muted-foreground">
{t('insights.conversationsToDelete')}:
</p>
<ul className="space-y-0.5">
{sessionsToDelete.map((s) => (
<li key={s.id} className="truncate text-xs text-foreground/80">
{s.title}
</li>
))}
</ul>
</div>
)}
<AlertDialogFooter>
<AlertDialogCancel>{t('buttons.cancel')}</AlertDialogCancel>
<AlertDialogAction onClick={handleBulkDelete}>
{t('insights.bulkDeleteConfirm', { count: selectedIds.size })}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* Bulk archive confirmation dialog */}
<AlertDialog open={bulkArchiveOpen} onOpenChange={setBulkArchiveOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('insights.archiveConfirmTitle')}</AlertDialogTitle>
<AlertDialogDescription>
{t('insights.archiveConfirmDescription')}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t('buttons.cancel')}</AlertDialogCancel>
<AlertDialogAction onClick={handleBulkArchiveConfirmed}>
{t('insights.archiveConfirmButton', { count: selectedIds.size })}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
@@ -199,6 +439,12 @@ interface SessionItemProps {
onCancelEdit: () => void;
onEditTitleChange: (title: string) => void;
onDelete: () => void;
onArchive?: () => Promise<void>;
onUnarchive?: () => Promise<void>;
isArchived: boolean;
isSelectionMode: boolean;
isSelected: boolean;
onToggleSelect: () => void;
}
function SessionItem({
@@ -211,7 +457,13 @@ function SessionItem({
onSaveEdit,
onCancelEdit,
onEditTitleChange,
onDelete
onDelete,
onArchive,
onUnarchive,
isArchived,
isSelectionMode,
isSelected,
onToggleSelect
}: SessionItemProps) {
const { t } = useTranslation('common');
const handleKeyDown = (e: React.KeyboardEvent) => {
@@ -257,61 +509,107 @@ function SessionItem({
return (
<div
role={isSelectionMode ? 'checkbox' : 'button'}
aria-checked={isSelectionMode ? isSelected : undefined}
tabIndex={0}
className={cn(
'group relative cursor-pointer px-2 py-2 transition-colors hover:bg-muted',
isActive && 'bg-primary/10 hover:bg-primary/15'
isActive && 'bg-primary/10 hover:bg-primary/15',
isArchived && 'opacity-50'
)}
onClick={onSelect}
onClick={isSelectionMode ? onToggleSelect : onSelect}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
isSelectionMode ? onToggleSelect() : onSelect();
}
}}
>
{/* Content with reserved space for the menu button */}
<div className="flex items-center gap-1.5 pr-7">
<MessageSquare
className={cn(
'h-4 w-4 shrink-0',
isActive ? 'text-primary' : 'text-muted-foreground'
)}
/>
<div className="min-w-0 flex-1">
<p
{isSelectionMode ? (
<div className="shrink-0">
<Checkbox
checked={isSelected}
className="h-4 w-4"
aria-hidden
tabIndex={-1}
/>
</div>
) : (
<MessageSquare
className={cn(
'line-clamp-2 text-sm leading-tight break-words',
isActive ? 'font-medium text-foreground' : 'text-foreground/80'
'h-4 w-4 shrink-0',
isActive ? 'text-primary' : 'text-muted-foreground'
)}
>
{session.title}
</p>
/>
)}
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1">
<p
className={cn(
'line-clamp-2 text-sm leading-tight break-words',
isActive ? 'font-medium text-foreground' : 'text-foreground/80'
)}
>
{session.title}
</p>
{isArchived && (
<span className="inline-flex items-center gap-0.5 rounded bg-muted px-1 py-0.5 text-[9px] font-medium text-muted-foreground">
<Archive className="h-2.5 w-2.5" />
{t('insights.archived')}
</span>
)}
</div>
<p className="text-[11px] text-muted-foreground mt-0.5">
{session.messageCount} message{session.messageCount !== 1 ? 's' : ''}
{t('insights.messageCount', { count: session.messageCount })}
</p>
</div>
</div>
{/* Absolutely positioned menu button - always visible */}
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
<Button
variant="ghost"
size="icon"
className="absolute right-1 top-1/2 -translate-y-1/2 h-6 w-6 opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100 hover:bg-muted-foreground/20 transition-opacity"
aria-label={t('accessibility.moreOptionsAriaLabel')}
>
<MoreVertical className="h-3.5 w-3.5" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" sideOffset={5} className="w-36 z-[100]">
<DropdownMenuItem onSelect={onStartEdit}>
<Pencil className="mr-2 h-3.5 w-3.5" />
Rename
</DropdownMenuItem>
<DropdownMenuItem
onSelect={onDelete}
className="text-destructive focus:text-destructive"
>
<Trash2 className="mr-2 h-3.5 w-3.5" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
{/* Absolutely positioned menu button - hidden in selection mode */}
{!isSelectionMode && (
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
<Button
variant="ghost"
size="icon"
className="absolute right-1 top-1/2 -translate-y-1/2 h-6 w-6 opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100 hover:bg-muted-foreground/20 transition-opacity"
aria-label={t('accessibility.moreOptionsAriaLabel')}
>
<MoreVertical className="h-3.5 w-3.5" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" sideOffset={5} className="w-36 z-[100]">
<DropdownMenuItem onSelect={onStartEdit}>
<Pencil className="mr-2 h-3.5 w-3.5" />
{t('accessibility.renameAriaLabel')}
</DropdownMenuItem>
{isArchived ? (
onUnarchive && (
<DropdownMenuItem onSelect={onUnarchive}>
<ArchiveRestore className="mr-2 h-3.5 w-3.5" />
{t('insights.unarchive')}
</DropdownMenuItem>
)
) : (
onArchive && (
<DropdownMenuItem onSelect={onArchive}>
<Archive className="mr-2 h-3.5 w-3.5" />
{t('insights.archive')}
</DropdownMenuItem>
)
)}
<DropdownMenuItem
onSelect={onDelete}
className="text-destructive focus:text-destructive"
>
<Trash2 className="mr-2 h-3.5 w-3.5" />
{t('accessibility.deleteAriaLabel')}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
);
}
@@ -1,4 +1,6 @@
import { Search, Globe, AlertTriangle, TrendingUp } from 'lucide-react';
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Search, Globe, AlertTriangle, TrendingUp, UserPlus } from 'lucide-react';
import {
AlertDialog,
AlertDialogContent,
@@ -9,12 +11,15 @@ import {
AlertDialogAction,
AlertDialogCancel,
} from './ui/alert-dialog';
import { Button } from './ui/button';
import { AddCompetitorDialog } from './AddCompetitorDialog';
interface CompetitorAnalysisDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onAccept: () => void;
onDecline: () => void;
projectId: string;
}
export function CompetitorAnalysisDialog({
@@ -22,7 +27,19 @@ export function CompetitorAnalysisDialog({
onOpenChange,
onAccept,
onDecline,
projectId,
}: CompetitorAnalysisDialogProps) {
const { t } = useTranslation(['dialogs']);
const [showAddDialog, setShowAddDialog] = useState(false);
const [addedCount, setAddedCount] = useState(0);
// Reset addedCount when dialog reopens
useEffect(() => {
if (open) {
setAddedCount(0);
}
}, [open]);
const handleAccept = () => {
onAccept();
onOpenChange(false);
@@ -33,78 +50,116 @@ export function CompetitorAnalysisDialog({
onOpenChange(false);
};
return (
<AlertDialog open={open} onOpenChange={onOpenChange}>
<AlertDialogContent className="sm:max-w-[500px]">
<AlertDialogHeader>
<AlertDialogTitle className="flex items-center gap-2 text-foreground">
<TrendingUp className="h-5 w-5 text-primary" />
Enable Competitor Analysis?
</AlertDialogTitle>
<AlertDialogDescription className="text-muted-foreground">
Enhance your roadmap with insights from competitor products
</AlertDialogDescription>
</AlertDialogHeader>
const handleCompetitorAdded = (_competitorId: string) => {
setAddedCount((prev) => prev + 1);
};
<div className="py-4 space-y-4">
{/* What it does */}
<div className="rounded-lg bg-primary/5 border border-primary/20 p-4">
<h4 className="text-sm font-medium text-foreground mb-2">
What competitor analysis does:
</h4>
<ul className="text-sm text-muted-foreground space-y-2">
<li className="flex items-start gap-2">
<Search className="h-4 w-4 mt-0.5 text-primary flex-shrink-0" />
<span>Identifies 3-5 main competitors based on your project type</span>
</li>
<li className="flex items-start gap-2">
<Globe className="h-4 w-4 mt-0.5 text-primary flex-shrink-0" />
<span>
Searches app stores, forums, and social media for user feedback and pain points
</span>
</li>
<li className="flex items-start gap-2">
<TrendingUp className="h-4 w-4 mt-0.5 text-primary flex-shrink-0" />
<span>
Suggests features that address gaps in competitor products
</span>
</li>
</ul>
return (
<>
<AlertDialog open={open} onOpenChange={onOpenChange}>
<AlertDialogContent className="sm:max-w-[500px]">
<AlertDialogHeader>
<AlertDialogTitle className="flex items-center gap-2 text-foreground">
<TrendingUp className="h-5 w-5 text-primary" />
{t('dialogs:competitorAnalysis.title', 'Enable Competitor Analysis?')}
</AlertDialogTitle>
<AlertDialogDescription className="text-muted-foreground">
{t('dialogs:competitorAnalysis.description', 'Enhance your roadmap with insights from competitor products')}
</AlertDialogDescription>
</AlertDialogHeader>
<div className="py-4 space-y-4">
{/* What it does */}
<div className="rounded-lg bg-primary/5 border border-primary/20 p-4">
<h4 className="text-sm font-medium text-foreground mb-2">
{t('dialogs:competitorAnalysis.whatItDoes', 'What competitor analysis does:')}
</h4>
<ul className="text-sm text-muted-foreground space-y-2">
<li className="flex items-start gap-2">
<Search className="h-4 w-4 mt-0.5 text-primary flex-shrink-0" />
<span>{t('dialogs:competitorAnalysis.identifiesCompetitors', 'Identifies 3-5 main competitors based on your project type')}</span>
</li>
<li className="flex items-start gap-2">
<Globe className="h-4 w-4 mt-0.5 text-primary flex-shrink-0" />
<span>
{t('dialogs:competitorAnalysis.searchesAppStores', 'Searches app stores, forums, and social media for user feedback and pain points')}
</span>
</li>
<li className="flex items-start gap-2">
<TrendingUp className="h-4 w-4 mt-0.5 text-primary flex-shrink-0" />
<span>
{t('dialogs:competitorAnalysis.suggestsFeatures', 'Suggests features that address gaps in competitor products')}
</span>
</li>
</ul>
</div>
{/* Privacy notice */}
<div className="rounded-lg bg-warning/10 border border-warning/30 p-4">
<div className="flex items-start gap-3">
<AlertTriangle className="h-5 w-5 text-warning flex-shrink-0 mt-0.5" />
<div className="flex-1">
<h4 className="text-sm font-medium text-foreground">
{t('dialogs:competitorAnalysis.webSearchesTitle', 'Web searches will be performed')}
</h4>
<p className="text-xs text-muted-foreground mt-1">
{t('dialogs:competitorAnalysis.webSearchesDescription', 'This feature will perform web searches to gather competitor information. Your project name and type will be used in search queries. No code or sensitive data is shared.')}
</p>
</div>
</div>
</div>
{/* Optional info */}
<p className="text-xs text-muted-foreground">
{t('dialogs:competitorAnalysis.optionalInfo', 'You can generate a roadmap without competitor analysis if you prefer. The roadmap will still be based on your project structure and best practices.')}
</p>
</div>
{/* Privacy notice */}
<div className="rounded-lg bg-warning/10 border border-warning/30 p-4">
<div className="flex items-start gap-3">
<AlertTriangle className="h-5 w-5 text-warning flex-shrink-0 mt-0.5" />
{/* Add Known Competitors section */}
<div className="border-t border-border pt-4">
<div className="flex items-center justify-between">
<div className="flex-1">
<h4 className="text-sm font-medium text-foreground">
Web searches will be performed
</h4>
<p className="text-xs text-muted-foreground mt-1">
This feature will perform web searches to gather competitor information.
Your project name and type will be used in search queries.
No code or sensitive data is shared.
<p className="text-sm text-muted-foreground">
{t('dialogs:competitorAnalysis.knowYourCompetitors', 'Already know your competitors?')}
</p>
<p className="text-xs text-muted-foreground/70 mt-0.5">
{t('dialogs:competitorAnalysis.addThemDirectly', 'Add them directly to improve analysis accuracy')}
</p>
</div>
<Button
variant="outline"
size="sm"
className="flex items-center gap-1.5"
onClick={() => setShowAddDialog(true)}
>
<UserPlus className="h-3.5 w-3.5" />
{t('dialogs:competitorAnalysis.addKnownCompetitors', 'Add Known Competitors')}
{addedCount > 0 && (
<span className="ml-1 rounded-full bg-primary px-1.5 py-0.5 text-[10px] font-medium text-primary-foreground">
{t('dialogs:competitorAnalysis.competitorsAdded', '{{count}} added', { count: addedCount })}
</span>
)}
</Button>
</div>
</div>
{/* Optional info */}
<p className="text-xs text-muted-foreground">
You can generate a roadmap without competitor analysis if you prefer.
The roadmap will still be based on your project structure and best practices.
</p>
</div>
<AlertDialogFooter>
<AlertDialogCancel onClick={handleDecline}>
{t('dialogs:competitorAnalysis.skipAnalysis', 'No, Skip Analysis')}
</AlertDialogCancel>
<AlertDialogAction onClick={handleAccept}>
{t('dialogs:competitorAnalysis.enableAnalysis', 'Yes, Enable Analysis')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<AlertDialogFooter>
<AlertDialogCancel onClick={handleDecline}>
No, Skip Analysis
</AlertDialogCancel>
<AlertDialogAction onClick={handleAccept}>
Yes, Enable Analysis
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<AddCompetitorDialog
open={showAddDialog}
onOpenChange={setShowAddDialog}
onCompetitorAdded={handleCompetitorAdded}
projectId={projectId}
/>
</>
);
}
@@ -1,5 +1,6 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { TrendingUp, ExternalLink, AlertCircle } from 'lucide-react';
import { TrendingUp, ExternalLink, AlertCircle, Plus } from 'lucide-react';
import {
Dialog,
DialogContent,
@@ -8,35 +9,50 @@ import {
DialogDescription,
} from './ui/dialog';
import { Badge } from './ui/badge';
import { Button } from './ui/button';
import { ScrollArea } from './ui/scroll-area';
import { AddCompetitorDialog } from './AddCompetitorDialog';
import type { CompetitorAnalysis } from '../../shared/types';
interface CompetitorAnalysisViewerProps {
analysis: CompetitorAnalysis | null;
open: boolean;
onOpenChange: (open: boolean) => void;
projectId: string;
}
export function CompetitorAnalysisViewer({
analysis,
open,
onOpenChange,
projectId,
}: CompetitorAnalysisViewerProps) {
const { t } = useTranslation('common');
const [showAddDialog, setShowAddDialog] = useState(false);
if (!analysis) return null;
return (
<>
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-4xl max-h-[85vh] flex flex-col">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<TrendingUp className="h-5 w-5 text-primary" />
Competitor Analysis Results
{t('competitorAnalysis.analysisResults')}
</DialogTitle>
<DialogDescription>
Analyzed {analysis.competitors.length} competitors to identify market gaps and opportunities
{t('competitorAnalysis.analysisDescription', { count: analysis.competitors.length })}
</DialogDescription>
<Button
variant="outline"
size="sm"
onClick={() => setShowAddDialog(true)}
className="mt-2 self-start"
>
<Plus className="h-4 w-4 mr-1" />
{t('competitorAnalysis.addCompetitor')}
</Button>
</DialogHeader>
<ScrollArea className="flex-1 overflow-auto pr-4" style={{ maxHeight: 'calc(85vh - 120px)' }}>
@@ -51,6 +67,11 @@ export function CompetitorAnalysisViewer({
<div className="flex-1">
<div className="flex items-center gap-2 mb-1">
<h3 className="text-lg font-semibold">{competitor.name}</h3>
{competitor.source === 'manual' && (
<Badge variant="outline" className="text-xs">
{t('competitorAnalysis.manualBadge')}
</Badge>
)}
{competitor.marketPosition && (
<Badge variant="secondary" className="text-xs">
{competitor.marketPosition}
@@ -72,7 +93,7 @@ export function CompetitorAnalysisViewer({
aria-label={t('accessibility.visitExternalLink', { name: competitor.name })}
>
<ExternalLink className="h-3 w-3" aria-hidden="true" />
Visit
{t('competitorAnalysis.visit')}
<span className="sr-only">({t('accessibility.opensInNewWindow')})</span>
</a>
)}
@@ -82,12 +103,12 @@ export function CompetitorAnalysisViewer({
<div>
<h4 className="text-sm font-medium mb-2 flex items-center gap-2">
<AlertCircle className="h-4 w-4 text-warning" />
Identified Pain Points ({competitor.painPoints.length})
{t('competitorAnalysis.identifiedPainPoints', { count: competitor.painPoints.length })}
</h4>
<div className="space-y-2">
{competitor.painPoints.length === 0 ? (
<p className="text-sm text-muted-foreground italic">
No pain points identified
{t('competitorAnalysis.noPainPointsIdentified')}
</p>
) : (
competitor.painPoints.map((painPoint) => (
@@ -115,21 +136,21 @@ export function CompetitorAnalysisViewer({
{painPoint.source && (
<div className="mt-2">
<span className="text-xs text-muted-foreground">
Source: <span className="italic">{painPoint.source}</span>
{t('competitorAnalysis.source')} <span className="italic">{painPoint.source}</span>
</span>
</div>
)}
{painPoint.frequency && (
<div className="mt-1">
<span className="text-xs text-muted-foreground">
Frequency: {painPoint.frequency}
{t('competitorAnalysis.frequency')} {painPoint.frequency}
</span>
</div>
)}
{painPoint.opportunity && (
<div className="mt-1">
<span className="text-xs text-muted-foreground">
Opportunity:{' '}
{t('competitorAnalysis.opportunity')}{' '}
<span className="font-medium text-foreground">
{painPoint.opportunity}
</span>
@@ -149,11 +170,11 @@ export function CompetitorAnalysisViewer({
{/* Insights Summary */}
{analysis.insightsSummary && (
<div className="rounded-lg bg-primary/5 border border-primary/20 p-4 space-y-3">
<h4 className="text-sm font-semibold">Market Insights Summary</h4>
<h4 className="text-sm font-semibold">{t('competitorAnalysis.marketInsightsSummary')}</h4>
{analysis.insightsSummary.topPainPoints.length > 0 && (
<div>
<p className="text-xs font-medium text-muted-foreground mb-1">Top Pain Points:</p>
<p className="text-xs font-medium text-muted-foreground mb-1">{t('competitorAnalysis.topPainPoints')}</p>
<ul className="text-sm space-y-1">
{analysis.insightsSummary.topPainPoints.map((point, idx) => (
<li key={idx} className="text-muted-foreground"> {point}</li>
@@ -164,7 +185,7 @@ export function CompetitorAnalysisViewer({
{analysis.insightsSummary.differentiatorOpportunities.length > 0 && (
<div>
<p className="text-xs font-medium text-muted-foreground mb-1">Differentiator Opportunities:</p>
<p className="text-xs font-medium text-muted-foreground mb-1">{t('competitorAnalysis.differentiatorOpportunities')}</p>
<ul className="text-sm space-y-1">
{analysis.insightsSummary.differentiatorOpportunities.map((opp, idx) => (
<li key={idx} className="text-muted-foreground"> {opp}</li>
@@ -175,7 +196,7 @@ export function CompetitorAnalysisViewer({
{analysis.insightsSummary.marketTrends.length > 0 && (
<div>
<p className="text-xs font-medium text-muted-foreground mb-1">Market Trends:</p>
<p className="text-xs font-medium text-muted-foreground mb-1">{t('competitorAnalysis.marketTrends')}</p>
<ul className="text-sm space-y-1">
{analysis.insightsSummary.marketTrends.map((trend, idx) => (
<li key={idx} className="text-muted-foreground"> {trend}</li>
@@ -189,5 +210,12 @@ export function CompetitorAnalysisViewer({
</ScrollArea>
</DialogContent>
</Dialog>
<AddCompetitorDialog
open={showAddDialog}
onOpenChange={setShowAddDialog}
projectId={projectId}
/>
</>
);
}
@@ -1,4 +1,6 @@
import { Globe, RefreshCw, TrendingUp, CheckCircle } from 'lucide-react';
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Globe, RefreshCw, TrendingUp, CheckCircle, UserPlus } from 'lucide-react';
import {
AlertDialog,
AlertDialogContent,
@@ -8,6 +10,7 @@ import {
AlertDialogTitle,
} from './ui/alert-dialog';
import { Button } from './ui/button';
import { AddCompetitorDialog } from './AddCompetitorDialog';
interface ExistingCompetitorAnalysisDialogProps {
open: boolean;
@@ -15,7 +18,9 @@ interface ExistingCompetitorAnalysisDialogProps {
onUseExisting: () => void;
onRunNew: () => void;
onSkip: () => void;
onCompetitorAdded?: (competitorId: string) => void;
analysisDate?: Date;
projectId: string;
}
export function ExistingCompetitorAnalysisDialog({
@@ -24,8 +29,20 @@ export function ExistingCompetitorAnalysisDialog({
onUseExisting,
onRunNew,
onSkip,
onCompetitorAdded,
analysisDate,
projectId,
}: ExistingCompetitorAnalysisDialogProps) {
const { t, i18n } = useTranslation(['dialogs']);
const [showAddDialog, setShowAddDialog] = useState(false);
// Reset child dialog state when this dialog reopens
useEffect(() => {
if (open) {
setShowAddDialog(false);
}
}, [open]);
const handleUseExisting = () => {
onUseExisting();
onOpenChange(false);
@@ -42,8 +59,8 @@ export function ExistingCompetitorAnalysisDialog({
};
const formatDate = (date?: Date) => {
if (!date) return 'recently';
return new Intl.DateTimeFormat('en-US', {
if (!date) return t('dialogs:existingCompetitorAnalysis.recently');
return new Intl.DateTimeFormat(i18n.language, {
month: 'short',
day: 'numeric',
year: 'numeric',
@@ -51,81 +68,112 @@ export function ExistingCompetitorAnalysisDialog({
};
return (
<AlertDialog open={open} onOpenChange={onOpenChange}>
<AlertDialogContent className="sm:max-w-[500px]">
<AlertDialogHeader>
<AlertDialogTitle className="flex items-center gap-2 text-foreground">
<TrendingUp className="h-5 w-5 text-primary" />
Competitor Analysis Options
</AlertDialogTitle>
<AlertDialogDescription className="text-muted-foreground">
This project has an existing competitor analysis from {formatDate(analysisDate)}
</AlertDialogDescription>
</AlertDialogHeader>
<>
<AlertDialog open={open} onOpenChange={onOpenChange}>
<AlertDialogContent className="sm:max-w-[500px]">
<AlertDialogHeader>
<AlertDialogTitle className="flex items-center gap-2 text-foreground">
<TrendingUp className="h-5 w-5 text-primary" />
{t('dialogs:existingCompetitorAnalysis.title')}
</AlertDialogTitle>
<AlertDialogDescription className="text-muted-foreground">
{t('dialogs:existingCompetitorAnalysis.description', { date: formatDate(analysisDate) })}
</AlertDialogDescription>
</AlertDialogHeader>
<div className="py-4 space-y-3">
{/* Option 1: Use existing (recommended) */}
<button
onClick={handleUseExisting}
className="w-full rounded-lg bg-primary/10 border border-primary/30 p-4 text-left hover:bg-primary/20 transition-colors"
>
<div className="flex items-start gap-3">
<CheckCircle className="h-5 w-5 text-primary flex-shrink-0 mt-0.5" />
<div className="flex-1">
<h4 className="text-sm font-medium text-foreground flex items-center gap-2">
Use existing analysis
<span className="text-xs text-primary font-normal">(Recommended)</span>
</h4>
<p className="text-xs text-muted-foreground mt-1">
Reuse the competitor insights you already have. Faster and no additional web searches.
</p>
<div className="py-4 space-y-3">
{/* Option 1: Use existing (recommended) */}
<button
type="button"
onClick={handleUseExisting}
className="w-full rounded-lg bg-primary/10 border border-primary/30 p-4 text-left hover:bg-primary/20 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
>
<div className="flex items-start gap-3">
<CheckCircle className="h-5 w-5 text-primary flex-shrink-0 mt-0.5" />
<div className="flex-1">
<h4 className="text-sm font-medium text-foreground flex items-center gap-2">
{t('dialogs:existingCompetitorAnalysis.useExistingTitle')}
<span className="text-xs text-primary font-normal">{t('dialogs:existingCompetitorAnalysis.recommended')}</span>
</h4>
<p className="text-xs text-muted-foreground mt-1">
{t('dialogs:existingCompetitorAnalysis.useExistingDescription')}
</p>
</div>
</div>
</div>
</button>
</button>
{/* Option 2: Run new analysis */}
<button
onClick={handleRunNew}
className="w-full rounded-lg bg-muted/50 border border-border p-4 text-left hover:bg-muted transition-colors"
>
<div className="flex items-start gap-3">
<RefreshCw className="h-5 w-5 text-muted-foreground flex-shrink-0 mt-0.5" />
<div className="flex-1">
<h4 className="text-sm font-medium text-foreground">
Run new analysis
</h4>
<p className="text-xs text-muted-foreground mt-1">
Perform fresh web searches to get updated competitor information. Takes longer.
</p>
{/* Option 2: Run new analysis */}
<button
type="button"
onClick={handleRunNew}
className="w-full rounded-lg bg-muted/50 border border-border p-4 text-left hover:bg-muted transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
>
<div className="flex items-start gap-3">
<RefreshCw className="h-5 w-5 text-muted-foreground flex-shrink-0 mt-0.5" />
<div className="flex-1">
<h4 className="text-sm font-medium text-foreground">
{t('dialogs:existingCompetitorAnalysis.runNewTitle')}
</h4>
<p className="text-xs text-muted-foreground mt-1">
{t('dialogs:existingCompetitorAnalysis.runNewDescription')}
</p>
</div>
</div>
</div>
</button>
</button>
{/* Option 3: Skip */}
<button
onClick={handleSkip}
className="w-full rounded-lg bg-muted/30 border border-border/50 p-4 text-left hover:bg-muted/50 transition-colors"
>
<div className="flex items-start gap-3">
<Globe className="h-5 w-5 text-muted-foreground/60 flex-shrink-0 mt-0.5" />
<div className="flex-1">
<h4 className="text-sm font-medium text-muted-foreground">
Skip competitor analysis
</h4>
<p className="text-xs text-muted-foreground/80 mt-1">
Generate roadmap without any competitor insights.
</p>
{/* Option 3: Add known competitors */}
<button
type="button"
onClick={() => setShowAddDialog(true)}
className="w-full rounded-lg bg-muted/50 border border-border p-4 text-left hover:bg-muted transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
>
<div className="flex items-start gap-3">
<UserPlus className="h-5 w-5 text-muted-foreground flex-shrink-0 mt-0.5" />
<div className="flex-1">
<h4 className="text-sm font-medium text-foreground">
{t('dialogs:competitorAnalysis.addKnownCompetitors')}
</h4>
<p className="text-xs text-muted-foreground mt-1">
{t('dialogs:competitorAnalysis.addKnownCompetitorsDescription')}
</p>
</div>
</div>
</div>
</button>
</div>
</button>
<AlertDialogFooter className="sm:justify-start">
<Button variant="ghost" onClick={() => onOpenChange(false)}>
Cancel
</Button>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* Option 4: Skip */}
<button
type="button"
onClick={handleSkip}
className="w-full rounded-lg bg-muted/30 border border-border/50 p-4 text-left hover:bg-muted/50 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
>
<div className="flex items-start gap-3">
<Globe className="h-5 w-5 text-muted-foreground/60 flex-shrink-0 mt-0.5" />
<div className="flex-1">
<h4 className="text-sm font-medium text-muted-foreground">
{t('dialogs:existingCompetitorAnalysis.skipTitle')}
</h4>
<p className="text-xs text-muted-foreground/80 mt-1">
{t('dialogs:existingCompetitorAnalysis.skipDescription')}
</p>
</div>
</div>
</button>
</div>
<AlertDialogFooter className="sm:justify-start">
<Button variant="ghost" onClick={() => onOpenChange(false)}>
{t('dialogs:existingCompetitorAnalysis.cancel')}
</Button>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<AddCompetitorDialog
open={showAddDialog}
onOpenChange={setShowAddDialog}
onCompetitorAdded={onCompetitorAdded}
projectId={projectId}
/>
</>
);
}
@@ -14,7 +14,9 @@ import {
FileText,
FolderSearch,
PanelLeftClose,
PanelLeft
PanelLeft,
Camera,
X
} from 'lucide-react';
import ReactMarkdown, { type Components } from 'react-markdown';
import remarkGfm from 'remark-gfm';
@@ -23,6 +25,7 @@ import { Textarea } from './ui/textarea';
import { ScrollArea } from './ui/scroll-area';
import { Card, CardContent } from './ui/card';
import { Badge } from './ui/badge';
import { ScreenshotCapture } from './ScreenshotCapture';
import { cn } from '../lib/utils';
import {
useInsightsStore,
@@ -31,20 +34,29 @@ import {
newSession,
switchSession,
deleteSession,
deleteSessions,
renameSession,
archiveSession,
archiveSessions,
unarchiveSession,
updateModelConfig,
createTaskFromSuggestion,
setupInsightsListeners
setupInsightsListeners,
loadInsightsSessions
} from '../stores/insights-store';
import { useImageUpload } from './task-form/useImageUpload';
import { createThumbnail, generateImageId } from './ImageUpload';
import { loadTasks } from '../stores/task-store';
import { ChatHistorySidebar } from './ChatHistorySidebar';
import { InsightsModelSelector } from './InsightsModelSelector';
import type { InsightsChatMessage, InsightsModelConfig, TaskMetadata } from '../../shared/types';
import type { InsightsChatMessage, InsightsModelConfig, TaskMetadata, ImageAttachment } from '../../shared/types';
import {
TASK_CATEGORY_LABELS,
TASK_CATEGORY_COLORS,
TASK_COMPLEXITY_LABELS,
TASK_COMPLEXITY_COLORS
TASK_COMPLEXITY_COLORS,
MAX_IMAGE_SIZE,
MAX_IMAGES_PER_TASK
} from '../../shared/constants';
// createSafeLink - factory function that creates a SafeLink component with i18n support
@@ -105,11 +117,41 @@ export function Insights({ projectId }: InsightsProps) {
const [creatingTask, setCreatingTask] = useState<Set<string>>(new Set());
const [taskCreated, setTaskCreated] = useState<Set<string>>(new Set());
const [showSidebar, setShowSidebar] = useState(true);
const showArchived = useInsightsStore((state) => state.showArchived);
const [isUserAtBottom, setIsUserAtBottom] = useState(true);
const [viewportEl, setViewportEl] = useState<HTMLElement | null>(null);
const [screenshotOpen, setScreenshotOpen] = useState(false);
const [imageError, setImageError] = useState<string | null>(null);
const pendingImages = useInsightsStore((state) => state.pendingImages);
const setPendingImages = useInsightsStore((state) => state.setPendingImages);
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
const isLoading = status.phase === 'thinking' || status.phase === 'streaming';
// Image upload hook
const {
isDragOver,
handlePaste,
handleDragOver,
handleDragLeave,
handleDrop,
removeImage,
canAddMore
} = useImageUpload({
images: pendingImages,
onImagesChange: setPendingImages,
disabled: isLoading,
onError: setImageError,
errorMessages: {
maxImagesReached: t('insights.images.maxImagesReached'),
invalidImageType: t('insights.images.invalidType'),
processPasteFailed: t('insights.images.processFailed'),
processDropFailed: t('insights.images.processFailed')
}
});
// Scroll threshold in pixels - user is considered "at bottom" if within this distance
const SCROLL_BOTTOM_THRESHOLD = 100;
@@ -138,11 +180,23 @@ export function Insights({ projectId }: InsightsProps) {
// Load session and set up listeners on mount
useEffect(() => {
loadInsightsSession(projectId);
loadInsightsSession(projectId, showArchived);
const cleanup = setupInsightsListeners();
return cleanup;
// biome-ignore lint/correctness/useExhaustiveDependencies: showArchived is handled by the dedicated effect below; including it here would cause duplicate loads
}, [projectId]);
// Reload sessions when showArchived changes (skip first run to avoid duplicate load with mount effect)
const isFirstRun = useRef(true);
// biome-ignore lint/correctness/useExhaustiveDependencies: projectId changes are handled by the mount effect above; this effect only reacts to showArchived toggles
useEffect(() => {
if (isFirstRun.current) {
isFirstRun.current = false;
return;
}
loadInsightsSessions(projectId, showArchived);
}, [showArchived]);
// Smart auto-scroll: only scroll if user is already at bottom
// This allows users to scroll up to read previous messages without being
// yanked back down during streaming responses
@@ -158,6 +212,7 @@ export function Insights({ projectId }: InsightsProps) {
}, []);
// Reset task creation state when switching sessions
// biome-ignore lint/correctness/useExhaustiveDependencies: session?.id is intentionally used as a trigger
useEffect(() => {
setTaskCreated(new Set());
setCreatingTask(new Set());
@@ -165,13 +220,46 @@ export function Insights({ projectId }: InsightsProps) {
const handleSend = () => {
const message = inputValue.trim();
if (!message || status.phase === 'thinking' || status.phase === 'streaming') return;
const hasImages = pendingImages.length > 0;
if ((!message && !hasImages) || isLoading) return;
setInputValue('');
sendMessage(projectId, message);
sendMessage(projectId, message, session?.modelConfig, hasImages ? pendingImages : undefined);
setPendingImages([]);
setImageError(null);
setIsUserAtBottom(true); // Resume auto-scroll when user sends a message
};
const handleScreenshotCapture = useCallback(async (imageData: string) => {
// Check image count limit before processing
if (pendingImages.length >= MAX_IMAGES_PER_TASK) {
setImageError(t('insights.images.maxImagesReached'));
return;
}
// imageData is base64 PNG from ScreenshotCapture
const approximateSize = Math.ceil(imageData.length * 0.75); // approximate base64 size
// Validate size - match the validation used for regular image uploads
if (approximateSize > MAX_IMAGE_SIZE) {
setImageError(t('insights.images.screenshotTooLarge', { size: Math.round(approximateSize / 1024 / 1024), max: Math.round(MAX_IMAGE_SIZE / 1024 / 1024) }));
return;
}
const dataUrl = `data:image/png;base64,${imageData}`;
const thumbnail = await createThumbnail(dataUrl);
const newImage: ImageAttachment = {
id: generateImageId(),
filename: `screenshot-${Date.now()}.png`,
mimeType: 'image/png',
size: approximateSize,
data: imageData,
thumbnail
};
setPendingImages([...pendingImages, newImage]);
setImageError(null);
}, [pendingImages, setPendingImages, setImageError, t]);
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
@@ -192,13 +280,71 @@ export function Insights({ projectId }: InsightsProps) {
};
const handleDeleteSession = async (sessionId: string): Promise<boolean> => {
return await deleteSession(projectId, sessionId);
return await deleteSession(projectId, sessionId, showArchived);
};
const handleRenameSession = async (sessionId: string, newTitle: string): Promise<boolean> => {
return await renameSession(projectId, sessionId, newTitle);
};
const handleArchiveSession = async (sessionId: string) => {
try {
await archiveSession(projectId, sessionId);
await loadInsightsSessions(projectId, showArchived);
// Reload current session in case backend switched to a different one
await loadInsightsSession(projectId, showArchived);
} catch (error) {
console.error(`Failed to archive session ${sessionId}:`, error);
}
};
const handleUnarchiveSession = async (sessionId: string) => {
try {
await unarchiveSession(projectId, sessionId);
await loadInsightsSessions(projectId, showArchived);
// Reload current session in case backend switched to a different one
await loadInsightsSession(projectId, showArchived);
} catch (error) {
console.error(`Failed to unarchive session ${sessionId}:`, error);
}
};
const handleDeleteSessions = async (sessionIds: string[]) => {
try {
const result = await deleteSessions(projectId, sessionIds);
await loadInsightsSessions(projectId, showArchived);
// Reload current session in case backend switched to a different one
await loadInsightsSession(projectId, showArchived);
// Log partial failures for debugging
if (result.failedIds && result.failedIds.length > 0) {
console.warn(`Failed to delete ${result.failedIds.length} session(s):`, result.failedIds);
}
} catch (error) {
console.error(`Failed to delete sessions ${sessionIds.join(', ')}:`, error);
}
};
const handleArchiveSessions = async (sessionIds: string[]) => {
try {
const result = await archiveSessions(projectId, sessionIds);
await loadInsightsSessions(projectId, showArchived);
// Reload current session in case backend switched to a different one
await loadInsightsSession(projectId, showArchived);
// Log partial failures for debugging
if (result.failedIds && result.failedIds.length > 0) {
console.warn(`Failed to archive ${result.failedIds.length} session(s):`, result.failedIds);
}
} catch (error) {
console.error(`Failed to archive sessions ${sessionIds.join(', ')}:`, error);
}
};
const handleToggleShowArchived = () => {
useInsightsStore.getState().setShowArchived(!showArchived);
};
const handleCreateTask = async (
messageId: string,
taskIndex: number,
@@ -235,7 +381,6 @@ export function Insights({ projectId }: InsightsProps) {
}
};
const isLoading = status.phase === 'thinking' || status.phase === 'streaming';
const messages = session?.messages || [];
return (
@@ -250,6 +395,12 @@ export function Insights({ projectId }: InsightsProps) {
onSelectSession={handleSelectSession}
onDeleteSession={handleDeleteSession}
onRenameSession={handleRenameSession}
onArchiveSession={handleArchiveSession}
onUnarchiveSession={handleUnarchiveSession}
onDeleteSessions={handleDeleteSessions}
onArchiveSessions={handleArchiveSessions}
showArchived={showArchived}
onToggleShowArchived={handleToggleShowArchived}
/>
)}
@@ -402,32 +553,112 @@ export function Insights({ projectId }: InsightsProps) {
{/* Input */}
<div className="flex-shrink-0 border-t border-border p-4">
<div className="flex gap-2">
<Textarea
ref={textareaRef}
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Ask about your codebase..."
className="min-h-[80px] resize-none"
disabled={isLoading}
/>
<Button
onClick={handleSend}
disabled={!inputValue.trim() || isLoading}
className="self-end"
>
{isLoading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Send className="h-4 w-4" />
<div className="relative flex gap-2">
<div className="relative flex-1">
<Textarea
ref={textareaRef}
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
placeholder="Ask about your codebase..."
className={cn(
'min-h-[80px] resize-none',
isDragOver && 'border-primary ring-2 ring-primary/20'
)}
disabled={isLoading}
/>
{/* Drag-over overlay */}
{isDragOver && (
<div className="absolute inset-0 flex items-center justify-center rounded-md bg-primary/5 border-2 border-dashed border-primary pointer-events-none">
<span className="text-sm font-medium text-primary">
{t('insights.images.dragOver')}
</span>
</div>
)}
</Button>
</div>
<div className="flex flex-col gap-1 self-end">
<Button
variant="outline"
size="icon"
className="h-9 w-9"
onClick={() => setScreenshotOpen(true)}
disabled={isLoading || !canAddMore}
title={t('insights.images.screenshotButton')}
>
<Camera className="h-4 w-4" />
</Button>
<Button
onClick={handleSend}
disabled={(!inputValue.trim() && pendingImages.length === 0) || isLoading}
className="h-9 w-9"
size="icon"
>
{isLoading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Send className="h-4 w-4" />
)}
</Button>
</div>
</div>
{/* Image analysis warning */}
{pendingImages.length > 0 && (
<div className="mt-1 flex items-center gap-1.5 rounded-md bg-amber-500/10 px-2 py-1 text-xs text-amber-500">
<AlertCircle className="h-3 w-3 shrink-0" />
<span>{t('insights.images.analysisUnsupported')}</span>
</div>
)}
{/* Image error */}
{imageError && (
<p className="mt-1 text-xs text-destructive">{imageError}</p>
)}
{/* Image preview strip */}
{pendingImages.length > 0 && (
<div className="mt-2 flex flex-wrap items-center gap-2">
{pendingImages.map((image) => (
<div
key={image.id}
className="group relative h-16 w-16 rounded-md border border-border overflow-hidden"
>
<img
src={image.thumbnail || `data:${image.mimeType};base64,${image.data}`}
alt={image.filename}
className="h-full w-full object-cover"
/>
<button
type="button"
onClick={() => removeImage(image.id)}
className="absolute -right-1 -top-1 flex h-5 w-5 items-center justify-center rounded-full bg-destructive text-destructive-foreground opacity-0 transition-opacity group-hover:opacity-100"
title={t('insights.images.removeImage')}
>
<X className="h-3 w-3" />
</button>
</div>
))}
<span className="text-xs text-muted-foreground">
{t('insights.images.imageCount', { count: pendingImages.length })}
</span>
</div>
)}
<p className="mt-2 text-xs text-muted-foreground">
Press Enter to send, Shift+Enter for new line
{t('insights.images.pasteHint')} · Press Enter to send, Shift+Enter for new line
</p>
</div>
{/* Screenshot capture dialog */}
<ScreenshotCapture
open={screenshotOpen}
onOpenChange={setScreenshotOpen}
onCapture={handleScreenshotCapture}
/>
</div>
</div>
);
@@ -469,11 +700,32 @@ function MessageBubble({
<div className="text-sm font-medium text-foreground">
{isUser ? 'You' : 'Assistant'}
</div>
<div className="prose prose-sm dark:prose-invert max-w-none">
<ReactMarkdown remarkPlugins={[remarkGfm]} components={markdownComponents}>
{message.content}
</ReactMarkdown>
</div>
{message.content && (
<div className="prose prose-sm dark:prose-invert max-w-none">
<ReactMarkdown remarkPlugins={[remarkGfm]} components={markdownComponents}>
{message.content}
</ReactMarkdown>
</div>
)}
{/* Image attachments for user messages */}
{isUser && message.images && message.images.length > 0 && (
<div className="space-y-1.5">
<div className="flex flex-wrap gap-2">
{message.images
.filter(img => img.thumbnail || img.data)
.map((image) => (
<img
key={image.id}
src={image.thumbnail || `data:${image.mimeType};base64,${image.data}`}
alt={image.filename}
className="max-w-[200px] max-h-[200px] rounded-md border border-border object-contain"
/>
))}
</div>
<p className="text-xs text-muted-foreground italic">{t('insights.images.notAnalyzed')}</p>
</div>
)}
{/* Tool usage history for assistant messages */}
{!isUser && message.toolsUsed && message.toolsUsed.length > 0 && (
@@ -613,6 +865,7 @@ function ToolUsageHistory({ tools }: ToolUsageHistoryProps) {
return (
<div className="mt-2">
<button
type="button"
onClick={() => setExpanded(!expanded)}
className="flex items-center gap-2 text-xs text-muted-foreground hover:text-foreground transition-colors"
>
@@ -1,4 +1,6 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Archive } from 'lucide-react';
import { RoadmapGenerationProgress } from './RoadmapGenerationProgress';
import { CompetitorAnalysisDialog } from './CompetitorAnalysisDialog';
import { ExistingCompetitorAnalysisDialog } from './ExistingCompetitorAnalysisDialog';
@@ -8,17 +10,30 @@ import { RoadmapHeader } from './roadmap/RoadmapHeader';
import { RoadmapEmptyState } from './roadmap/RoadmapEmptyState';
import { RoadmapTabs } from './roadmap/RoadmapTabs';
import { FeatureDetailPanel } from './roadmap/FeatureDetailPanel';
import {
AlertDialog,
AlertDialogContent,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogCancel,
AlertDialogAction,
} from './ui/alert-dialog';
import { useRoadmapData, useFeatureActions, useRoadmapGeneration, useRoadmapSave, useFeatureDelete } from './roadmap/hooks';
import { getCompetitorInsightsForFeature } from './roadmap/utils';
import type { RoadmapFeature } from '../../shared/types';
import type { RoadmapProps } from './roadmap/types';
export function Roadmap({ projectId, onGoToTask }: RoadmapProps) {
const { t } = useTranslation('common');
// State management
const [selectedFeature, setSelectedFeature] = useState<RoadmapFeature | null>(null);
const [activeTab, setActiveTab] = useState('kanban');
const [showAddFeatureDialog, setShowAddFeatureDialog] = useState(false);
const [showCompetitorViewer, setShowCompetitorViewer] = useState(false);
const [pendingArchiveFeatureId, setPendingArchiveFeatureId] = useState<string | null>(null);
// Custom hooks
const { roadmap, competitorAnalysis, generationStatus } = useRoadmapData(projectId);
@@ -54,6 +69,22 @@ export function Roadmap({ projectId, onGoToTask }: RoadmapProps) {
}
};
const handleArchiveFeature = (featureId: string) => {
setPendingArchiveFeatureId(featureId);
};
const confirmArchiveFeature = async () => {
if (!pendingArchiveFeatureId) return;
try {
await deleteFeature(pendingArchiveFeatureId);
if (selectedFeature?.id === pendingArchiveFeatureId) {
setSelectedFeature(null);
}
} finally {
setPendingArchiveFeatureId(null);
}
};
// Show generation progress
if (generationStatus.phase !== 'idle' && generationStatus.phase !== 'complete') {
return (
@@ -78,6 +109,7 @@ export function Roadmap({ projectId, onGoToTask }: RoadmapProps) {
onOpenChange={setShowCompetitorDialog}
onAccept={handleCompetitorDialogAccept}
onDecline={handleCompetitorDialogDecline}
projectId={projectId}
/>
{/* Dialog for projects WITH existing competitor analysis */}
<ExistingCompetitorAnalysisDialog
@@ -87,6 +119,7 @@ export function Roadmap({ projectId, onGoToTask }: RoadmapProps) {
onRunNew={handleRunNewAnalysis}
onSkip={handleSkipAnalysis}
analysisDate={competitorAnalysisDate}
projectId={projectId}
/>
</>
);
@@ -114,6 +147,7 @@ export function Roadmap({ projectId, onGoToTask }: RoadmapProps) {
onConvertToSpec={handleConvertToSpec}
onGoToTask={handleGoToTask}
onSave={saveRoadmap}
onArchive={handleArchiveFeature}
/>
</div>
@@ -125,6 +159,7 @@ export function Roadmap({ projectId, onGoToTask }: RoadmapProps) {
onConvertToSpec={handleConvertToSpec}
onGoToTask={handleGoToTask}
onDelete={deleteFeature}
onArchive={handleArchiveFeature}
competitorInsights={getCompetitorInsightsForFeature(selectedFeature, competitorAnalysis)}
/>
)}
@@ -135,6 +170,7 @@ export function Roadmap({ projectId, onGoToTask }: RoadmapProps) {
onOpenChange={setShowCompetitorDialog}
onAccept={handleCompetitorDialogAccept}
onDecline={handleCompetitorDialogDecline}
projectId={projectId}
/>
{/* Competitor Analysis Options Dialog (existing analysis) */}
@@ -145,6 +181,7 @@ export function Roadmap({ projectId, onGoToTask }: RoadmapProps) {
onRunNew={handleRunNewAnalysis}
onSkip={handleSkipAnalysis}
analysisDate={competitorAnalysisDate}
projectId={projectId}
/>
{/* Competitor Analysis Viewer */}
@@ -152,6 +189,7 @@ export function Roadmap({ projectId, onGoToTask }: RoadmapProps) {
analysis={competitorAnalysis}
open={showCompetitorViewer}
onOpenChange={setShowCompetitorViewer}
projectId={projectId}
/>
{/* Add Feature Dialog */}
@@ -160,6 +198,34 @@ export function Roadmap({ projectId, onGoToTask }: RoadmapProps) {
open={showAddFeatureDialog}
onOpenChange={setShowAddFeatureDialog}
/>
{/* Archive Confirmation Dialog */}
<AlertDialog
open={!!pendingArchiveFeatureId}
onOpenChange={(open) => { if (!open) setPendingArchiveFeatureId(null); }}
>
<AlertDialogContent>
<AlertDialogHeader>
<div className="flex items-center gap-2">
<Archive className="h-5 w-5 text-muted-foreground" />
<AlertDialogTitle>{t('roadmap.archiveFeatureConfirmTitle')}</AlertDialogTitle>
</div>
<AlertDialogDescription>
{t('roadmap.archiveFeatureConfirmDescription', {
title: pendingArchiveFeatureId
? roadmap.features.find((f) => f.id === pendingArchiveFeatureId)?.title ?? ''
: '',
})}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t('buttons.cancel')}</AlertDialogCancel>
<AlertDialogAction onClick={confirmArchiveFeature}>
{t('roadmap.archiveFeature')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}
@@ -36,6 +36,7 @@ interface RoadmapKanbanViewProps {
onConvertToSpec?: (feature: RoadmapFeature) => void;
onGoToTask?: (specId: string) => void;
onSave?: () => void;
onArchive?: (featureId: string) => void;
}
interface DroppableStatusColumnProps {
@@ -45,6 +46,7 @@ interface DroppableStatusColumnProps {
onFeatureClick: (feature: RoadmapFeature) => void;
onConvertToSpec?: (feature: RoadmapFeature) => void;
onGoToTask?: (specId: string) => void;
onArchive?: (featureId: string) => void;
isOver: boolean;
}
@@ -71,6 +73,7 @@ function DroppableStatusColumn({
onFeatureClick,
onConvertToSpec,
onGoToTask,
onArchive,
isOver
}: DroppableStatusColumnProps) {
const { setNodeRef } = useDroppable({
@@ -158,6 +161,7 @@ function DroppableStatusColumn({
onClick={() => onFeatureClick(feature)}
onConvertToSpec={onConvertToSpec}
onGoToTask={onGoToTask}
onArchive={onArchive}
/>
))
)}
@@ -174,7 +178,8 @@ export function RoadmapKanbanView({
onFeatureClick,
onConvertToSpec,
onGoToTask,
onSave
onSave,
onArchive
}: RoadmapKanbanViewProps) {
const [activeFeature, setActiveFeature] = useState<RoadmapFeature | null>(null);
const [overColumnId, setOverColumnId] = useState<string | null>(null);
@@ -300,6 +305,7 @@ export function RoadmapKanbanView({
onFeatureClick={onFeatureClick}
onConvertToSpec={onConvertToSpec}
onGoToTask={onGoToTask}
onArchive={onArchive}
isOver={overColumnId === column.id}
/>
))}
@@ -9,7 +9,8 @@ import {
TooltipContent,
TooltipTrigger
} from './ui/tooltip';
import { Play, ExternalLink, TrendingUp, Layers, ThumbsUp } from 'lucide-react';
import { Play, ExternalLink, TrendingUp, Layers, ThumbsUp, Archive } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { TaskOutcomeBadge, getTaskOutcomeColorClass } from './roadmap/TaskOutcomeBadge';
import {
ROADMAP_PRIORITY_COLORS,
@@ -25,6 +26,7 @@ interface SortableFeatureCardProps {
onClick: () => void;
onConvertToSpec?: (feature: RoadmapFeature) => void;
onGoToTask?: (specId: string) => void;
onArchive?: (featureId: string) => void;
}
export function SortableFeatureCard({
@@ -32,8 +34,10 @@ export function SortableFeatureCard({
roadmap,
onClick,
onConvertToSpec,
onGoToTask
onGoToTask,
onArchive
}: SortableFeatureCardProps) {
const { t } = useTranslation('common');
const {
attributes,
listeners,
@@ -120,7 +124,7 @@ export function SortableFeatureCard({
</div>
<h3 className="font-medium text-sm leading-snug line-clamp-2">{feature.title}</h3>
</div>
<div className="shrink-0">
<div className="shrink-0 flex items-center gap-1">
{feature.taskOutcome ? (
<Badge
variant="outline"
@@ -139,7 +143,7 @@ export function SortableFeatureCard({
}}
>
<ExternalLink className="h-3 w-3 mr-1" />
Task
{t('roadmap.task')}
</Button>
) : (
feature.status !== 'done' &&
@@ -154,10 +158,25 @@ export function SortableFeatureCard({
}}
>
<Play className="h-3 w-3 mr-1" />
Build
{t('roadmap.build')}
</Button>
)
)}
{feature.status === 'done' && onArchive && (
<Button
variant="ghost"
size="sm"
className="h-7 px-2"
title={t('roadmap.archiveFeature')}
aria-label={t('accessibility.archiveFeatureAriaLabel')}
onClick={(e) => {
e.stopPropagation();
onArchive(feature.id);
}}
>
<Archive className="h-3 w-3" />
</Button>
)}
</div>
</div>
@@ -41,7 +41,10 @@ export const SortableTaskCard = memo(function SortableTaskCard({ task, onClick,
transition,
isDragging,
isOver
} = useSortable({ id: task.id });
} = useSortable({
id: task.id,
disabled: task.status === 'in_progress' // Prevent dragging tasks that are currently running or stuck
});
const style = {
transform: CSS.Transform.toString(transform),
@@ -228,7 +228,9 @@ export const TaskCard = memo(function TaskCard({
const handleStartStop = async (e: React.MouseEvent) => {
e.stopPropagation();
if (isRunning && !isStuck) {
if (isRunning) {
// Allow stopping both running and stuck tasks
// User should be able to force-stop a stuck task
stopTask(task.id);
} else {
const result = await startTaskOrQueue(task.id);
@@ -419,19 +419,22 @@ export function PRDetail({
const MAX_POLL_DURATION_MS = 30 * 60 * 1000; // 30 minutes
const pollStart = Date.now();
let notified = false;
const pollForCompletion = async () => {
// Skip if we already notified (prevents duplicate notifications before React cleanup)
if (notified) return;
// Timeout: stop polling after 30 minutes to avoid indefinite polling
if (Date.now() - pollStart > MAX_POLL_DURATION_MS) {
usePRReviewStore.getState().setPRReviewResult(projectId, {
prNumber: pr.number,
repo: '',
success: false,
findings: [],
summary: '',
overallStatus: 'comment',
reviewedAt: new Date().toISOString(),
error: 'External review polling timed out after 30 minutes',
});
console.warn('[PRDetail] External review polling timed out after 30 minutes');
notified = true;
try {
// Notify main process so the XState actor transitions to error state
await window.electronAPI.github.notifyExternalReviewComplete(projectId, pr.number, null);
} catch {
// Non-critical — state manager timeout is a best-effort notification
}
return;
}
@@ -442,7 +445,9 @@ export function PRDetail({
// Otherwise this is a stale result from a previous review still on disk
// (in-progress results are intentionally NOT saved to disk).
if (startedAt && result.reviewedAt && new Date(result.reviewedAt) > new Date(startedAt)) {
usePRReviewStore.getState().setPRReviewResult(projectId, result);
notified = true;
// Notify main process so the XState actor transitions to completed state
await window.electronAPI.github.notifyExternalReviewComplete(projectId, pr.number, result);
}
}
} catch {
@@ -7,8 +7,6 @@ import type {
} from "../../../../preload/api/modules/github-api";
import {
usePRReviewStore,
startPRReview as storeStartPRReview,
startFollowupReview as storeStartFollowupReview,
} from "../../../stores/github";
// Re-export types for consumers
@@ -206,7 +204,7 @@ export function useGitHubPRs(
// Update store with loaded results
for (const reviewResult of Object.values(batchReviews)) {
if (reviewResult) {
usePRReviewStore.getState().setPRReviewResult(projectId, reviewResult, {
usePRReviewStore.getState().setLoadedReviewResult(projectId, reviewResult, {
preserveNewCommitsCheck: true,
});
}
@@ -424,7 +422,7 @@ export function useGitHubPRs(
// Preserve newCommitsCheck when loading existing review from disk
usePRReviewStore
.getState()
.setPRReviewResult(projectId, result, { preserveNewCommitsCheck: true });
.setLoadedReviewResult(projectId, result, { preserveNewCommitsCheck: true });
// Always check for new commits when selecting a reviewed PR
// This ensures fresh data even if we have a cached check from earlier in the session
@@ -512,7 +510,7 @@ export function useGitHubPRs(
// Update store with loaded results
for (const reviewResult of Object.values(batchReviews)) {
if (reviewResult) {
usePRReviewStore.getState().setPRReviewResult(requestProjectId, reviewResult, {
usePRReviewStore.getState().setLoadedReviewResult(requestProjectId, reviewResult, {
preserveNewCommitsCheck: true,
});
}
@@ -536,8 +534,8 @@ export function useGitHubPRs(
(prNumber: number) => {
if (!projectId) return;
// Use the store function which handles both state and IPC
storeStartPRReview(projectId, prNumber);
// Main process handles XState state transition and subprocess launch
window.electronAPI.github.runPRReview(projectId, prNumber);
},
[projectId]
);
@@ -546,8 +544,8 @@ export function useGitHubPRs(
(prNumber: number) => {
if (!projectId) return;
// Use the store function which handles both state and IPC
storeStartFollowupReview(projectId, prNumber);
// Main process handles XState state transition and subprocess launch
window.electronAPI.github.runFollowupReview(projectId, prNumber);
},
[projectId]
);
@@ -577,15 +575,9 @@ export function useGitHubPRs(
if (!projectId) return false;
try {
// Main process kills subprocess and sends CANCEL_REVIEW to XState
// State update flows back via IPC (onPRReviewStateChange)
const success = await window.electronAPI.github.cancelPRReview(projectId, prNumber);
// Always update store state to exit the "reviewing" state
// Use different messages based on whether the process was found and killed
const message = success
? "Review cancelled by user"
: "Review stopped - process not found";
usePRReviewStore
.getState()
.setPRReviewError(projectId, prNumber, message);
return success;
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to cancel review");
@@ -617,7 +609,7 @@ export function useGitHubPRs(
// Preserve newCommitsCheck - posting doesn't change whether there are new commits
usePRReviewStore
.getState()
.setPRReviewResult(projectId, result, { preserveNewCommitsCheck: true });
.setLoadedReviewResult(projectId, result, { preserveNewCommitsCheck: true });
}
}
return success;
@@ -699,7 +691,7 @@ export function useGitHubPRs(
const existingState = getPRReviewState(projectId, prNumber);
if (existingState?.result) {
// If we have the result loaded, update it with hasPostedFindings and postedAt
usePRReviewStore.getState().setPRReviewResult(
usePRReviewStore.getState().setLoadedReviewResult(
projectId,
{ ...existingState.result, hasPostedFindings: true, postedAt },
{ preserveNewCommitsCheck: true }
@@ -708,7 +700,7 @@ export function useGitHubPRs(
// If result not loaded yet (race condition), reload from disk to get updated state
const result = await window.electronAPI.github.getPRReview(projectId, prNumber);
if (result) {
usePRReviewStore.getState().setPRReviewResult(
usePRReviewStore.getState().setLoadedReviewResult(
projectId,
result,
{ preserveNewCommitsCheck: true }
@@ -1,4 +1,5 @@
import { ExternalLink, Play, TrendingUp } from 'lucide-react';
import { Archive, ExternalLink, Play, TrendingUp } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { TaskOutcomeBadge, getTaskOutcomeColorClass } from './TaskOutcomeBadge';
import { Badge } from '../ui/badge';
import { Button } from '../ui/button';
@@ -17,8 +18,10 @@ export function FeatureCard({
onClick,
onConvertToSpec,
onGoToTask,
onArchive,
hasCompetitorInsight = false,
}: FeatureCardProps) {
const { t } = useTranslation('common');
return (
<Card className="p-4 hover:bg-muted/50 cursor-pointer transition-colors" onClick={onClick}>
@@ -55,37 +58,53 @@ export function FeatureCard({
<h3 className="font-medium">{feature.title}</h3>
<p className="text-sm text-muted-foreground line-clamp-2">{feature.description}</p>
</div>
{feature.taskOutcome ? (
<Badge variant="outline" className={`text-xs ${getTaskOutcomeColorClass(feature.taskOutcome)}`}>
<TaskOutcomeBadge outcome={feature.taskOutcome} size="md" />
</Badge>
) : feature.linkedSpecId ? (
<Button
variant="outline"
size="sm"
onClick={(e) => {
e.stopPropagation();
onGoToTask(feature.linkedSpecId!);
}}
>
<ExternalLink className="h-3 w-3 mr-1" />
Go to Task
</Button>
) : (
feature.status !== 'done' && (
<div className="flex items-center gap-1">
{feature.taskOutcome ? (
<Badge variant="outline" className={`text-xs ${getTaskOutcomeColorClass(feature.taskOutcome)}`}>
<TaskOutcomeBadge outcome={feature.taskOutcome} size="md" />
</Badge>
) : feature.linkedSpecId ? (
<Button
variant="outline"
size="sm"
onClick={(e) => {
e.stopPropagation();
onConvertToSpec(feature);
onGoToTask(feature.linkedSpecId!);
}}
>
<Play className="h-3 w-3 mr-1" />
Build
<ExternalLink className="h-3 w-3 mr-1" />
{t('roadmap.goToTask')}
</Button>
)
)}
) : (
feature.status !== 'done' && (
<Button
variant="outline"
size="sm"
onClick={(e) => {
e.stopPropagation();
onConvertToSpec(feature);
}}
>
<Play className="h-3 w-3 mr-1" />
{t('roadmap.build')}
</Button>
)
)}
{feature.status === 'done' && onArchive && (
<Button
variant="ghost"
size="sm"
title={t('roadmap.archiveFeature')}
aria-label={t('accessibility.archiveFeatureAriaLabel')}
onClick={(e) => {
e.stopPropagation();
onArchive(feature.id);
}}
>
<Archive className="h-3 w-3" />
</Button>
)}
</div>
</div>
</Card>
);
@@ -11,6 +11,7 @@ import {
ExternalLink,
TrendingUp,
Trash2,
Archive,
} from 'lucide-react';
import { TaskOutcomeBadge } from './TaskOutcomeBadge';
import { Badge } from '../ui/badge';
@@ -31,11 +32,16 @@ export function FeatureDetailPanel({
onConvertToSpec,
onGoToTask,
onDelete,
onArchive,
competitorInsights = [],
}: FeatureDetailPanelProps) {
const { t } = useTranslation('common');
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const handleArchive = () => {
onArchive?.(feature.id);
};
const handleDelete = () => {
if (onDelete) {
onDelete(feature.id);
@@ -215,29 +221,53 @@ export function FeatureDetailPanel({
</ScrollArea>
{/* Actions */}
{feature.taskOutcome ? (
<div className="shrink-0 p-4 border-t border-border">
<div className="flex items-center justify-center gap-2 py-2">
<TaskOutcomeBadge outcome={feature.taskOutcome} size="lg" />
</div>
</div>
) : feature.linkedSpecId ? (
<div className="shrink-0 p-4 border-t border-border">
<Button className="w-full" onClick={() => onGoToTask(feature.linkedSpecId!)}>
<ExternalLink className="h-4 w-4 mr-2" />
Go to Task
{(() => {
const archiveButton = feature.status === 'done' && (
<Button
variant="outline"
className="w-full"
onClick={handleArchive}
aria-label={t('accessibility.archiveFeatureAriaLabel')}
>
<Archive className="h-4 w-4 mr-2" />
{t('roadmap.archiveFeature')}
</Button>
</div>
) : (
feature.status !== 'done' && (
);
if (feature.taskOutcome) return (
<div className="shrink-0 p-4 border-t border-border space-y-3">
<div className="flex items-center justify-center gap-2 py-2">
<TaskOutcomeBadge outcome={feature.taskOutcome} size="lg" />
</div>
{archiveButton}
</div>
);
if (feature.linkedSpecId) return (
<div className="shrink-0 p-4 border-t border-border space-y-2">
<Button className="w-full" onClick={() => onGoToTask(feature.linkedSpecId!)}>
<ExternalLink className="h-4 w-4 mr-2" />
{t('roadmap.goToTask')}
</Button>
{archiveButton}
</div>
);
if (feature.status === 'done') return (
<div className="shrink-0 p-4 border-t border-border">
{archiveButton}
</div>
);
return (
<div className="shrink-0 p-4 border-t border-border">
<Button className="w-full" onClick={() => onConvertToSpec(feature)}>
<Zap className="h-4 w-4 mr-2" />
Convert to Auto-Build Task
{t('roadmap.convertToTask')}
</Button>
</div>
)
)}
);
})()}
{/* Delete Confirmation */}
{showDeleteConfirm && (
@@ -1,5 +1,5 @@
import { useState } from 'react';
import { CheckCircle2, ChevronDown, ChevronUp, Circle, ExternalLink, Play, TrendingUp } from 'lucide-react';
import { Archive, CheckCircle2, ChevronDown, ChevronUp, Circle, ExternalLink, Play, TrendingUp } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { TaskOutcomeBadge } from './TaskOutcomeBadge';
import { Badge } from '../ui/badge';
@@ -18,6 +18,7 @@ export function PhaseCard({
onFeatureSelect,
onConvertToSpec,
onGoToTask,
onArchive,
}: PhaseCardProps) {
const { t } = useTranslation('common');
const [isExpanded, setIsExpanded] = useState(false);
@@ -96,7 +97,24 @@ export function PhaseCard({
<div>
<h4 className="text-sm font-medium mb-2">Features ({features.length})</h4>
<div className="grid gap-2">
{visibleFeatures.map((feature) => (
{visibleFeatures.map((feature) => {
const isDone = feature.status === 'done';
const archiveButton = isDone && onArchive && (
<Button
variant="ghost"
size="sm"
className="h-6 px-2"
title={t('roadmap.archiveFeature')}
aria-label={t('accessibility.archiveFeatureAriaLabel')}
onClick={(e) => {
e.stopPropagation();
onArchive(feature.id);
}}
>
<Archive className="h-3 w-3" />
</Button>
);
return (
<div
key={feature.id}
className="flex items-center justify-between p-2 rounded-md bg-muted/50 hover:bg-muted transition-colors"
@@ -118,11 +136,15 @@ export function PhaseCard({
)}
</button>
{feature.taskOutcome ? (
<span className="flex-shrink-0">
<span className="flex items-center gap-1 flex-shrink-0">
<TaskOutcomeBadge outcome={feature.taskOutcome} size="lg" showLabel={false} />
{archiveButton}
</span>
) : isDone ? (
<span className="flex items-center gap-1 flex-shrink-0">
<CheckCircle2 className="h-4 w-4 text-success" />
{archiveButton}
</span>
) : feature.status === 'done' ? (
<CheckCircle2 className="h-4 w-4 text-success flex-shrink-0" />
) : feature.linkedSpecId ? (
<Button
variant="ghost"
@@ -134,7 +156,7 @@ export function PhaseCard({
}}
>
<ExternalLink className="h-3 w-3 mr-1" />
View Task
{t('roadmap.viewTask')}
</Button>
) : (
<Button
@@ -147,11 +169,12 @@ export function PhaseCard({
}}
>
<Play className="h-3 w-3 mr-1" />
Build
{t('roadmap.build')}
</Button>
)}
</div>
))}
);
})}
{hasMoreFeatures && (
<Button
type="button"
@@ -1,5 +1,7 @@
import { TrendingUp } from 'lucide-react';
import { Archive, TrendingUp, CheckCircle2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Badge } from '../ui/badge';
import { Button } from '../ui/button';
import { Card } from '../ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { PhaseCard } from './PhaseCard';
@@ -23,8 +25,10 @@ export function RoadmapTabs({
onFeatureSelect,
onConvertToSpec,
onGoToTask,
onArchive,
onSave,
}: RoadmapTabsProps) {
const { t } = useTranslation('common');
return (
<Tabs value={activeTab} onValueChange={onTabChange} className="h-full flex flex-col">
<TabsList className="shrink-0 mx-4 mt-4">
@@ -42,6 +46,7 @@ export function RoadmapTabs({
onFeatureClick={onFeatureSelect}
onConvertToSpec={onConvertToSpec}
onGoToTask={onGoToTask}
onArchive={onArchive}
onSave={onSave}
/>
</TabsContent>
@@ -58,6 +63,7 @@ export function RoadmapTabs({
onFeatureSelect={onFeatureSelect}
onConvertToSpec={onConvertToSpec}
onGoToTask={onGoToTask}
onArchive={onArchive}
/>
))}
</div>
@@ -73,6 +79,7 @@ export function RoadmapTabs({
onClick={() => onFeatureSelect(feature)}
onConvertToSpec={onConvertToSpec}
onGoToTask={onGoToTask}
onArchive={onArchive}
hasCompetitorInsight={hasCompetitorInsight(feature)}
/>
))}
@@ -93,35 +100,64 @@ export function RoadmapTabs({
<span className="text-sm text-muted-foreground">{features.length} features</span>
</div>
<div className="space-y-2">
{features.map((feature: RoadmapFeature) => (
<div
key={feature.id}
className="p-2 rounded-md bg-muted/50 hover:bg-muted cursor-pointer transition-colors"
onClick={() => onFeatureSelect(feature)}
>
<div className="font-medium text-sm">{feature.title}</div>
<div className="flex items-center gap-2 mt-1 flex-wrap">
<Badge
variant="outline"
className={`text-xs ${ROADMAP_COMPLEXITY_COLORS[feature.complexity]}`}
{features.map((feature: RoadmapFeature) => {
const isDone = feature.status === 'done';
return (
<div
key={feature.id}
className="p-2 rounded-md bg-muted/50 hover:bg-muted transition-colors"
>
<button
type="button"
className="w-full text-left cursor-pointer rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
onClick={() => onFeatureSelect(feature)}
>
{feature.complexity}
</Badge>
<Badge
variant="outline"
className={`text-xs ${ROADMAP_IMPACT_COLORS[feature.impact]}`}
>
{feature.impact} impact
</Badge>
{hasCompetitorInsight(feature) && (
<Badge variant="outline" className="text-xs text-primary border-primary/50">
<TrendingUp className="h-3 w-3 mr-1" />
Insight
</Badge>
<div className="font-medium text-sm">{feature.title}</div>
<div className="flex items-center gap-2 mt-1 flex-wrap">
<Badge
variant="outline"
className={`text-xs ${ROADMAP_COMPLEXITY_COLORS[feature.complexity]}`}
>
{feature.complexity}
</Badge>
<Badge
variant="outline"
className={`text-xs ${ROADMAP_IMPACT_COLORS[feature.impact]}`}
>
{feature.impact} impact
</Badge>
{hasCompetitorInsight(feature) && (
<Badge variant="outline" className="text-xs text-primary border-primary/50">
<TrendingUp className="h-3 w-3 mr-1" />
Insight
</Badge>
)}
</div>
</button>
{isDone && onArchive && (
<div className="flex items-center justify-between mt-2 pt-2 border-t border-border/50">
<span className="flex items-center gap-1 text-xs text-muted-foreground">
<CheckCircle2 className="h-3 w-3 text-success" />
Completed
</span>
<Button
variant="ghost"
size="sm"
className="h-6 px-2"
title={t('roadmap.archiveFeature')}
onClick={(e) => {
e.stopPropagation();
onArchive(feature.id);
}}
>
<Archive className="h-3 w-3 mr-1" />
Archive
</Button>
</div>
)}
</div>
</div>
))}
);
})}
</div>
</Card>
);
@@ -114,6 +114,7 @@ export function useFeatureDelete(projectId: string) {
return { deleteFeature: handleDeleteFeature };
}
/**
* Hook to manage roadmap generation actions
*
@@ -12,6 +12,7 @@ export interface PhaseCardProps {
onFeatureSelect: (feature: RoadmapFeature) => void;
onConvertToSpec: (feature: RoadmapFeature) => void;
onGoToTask: (specId: string) => void;
onArchive?: (featureId: string) => void;
}
export interface FeatureCardProps {
@@ -20,6 +21,7 @@ export interface FeatureCardProps {
onConvertToSpec: (feature: RoadmapFeature) => void;
onGoToTask: (specId: string) => void;
hasCompetitorInsight?: boolean;
onArchive?: (featureId: string) => void;
}
export interface FeatureDetailPanelProps {
@@ -28,6 +30,7 @@ export interface FeatureDetailPanelProps {
onConvertToSpec: (feature: RoadmapFeature) => void;
onGoToTask: (specId: string) => void;
onDelete?: (featureId: string) => void;
onArchive?: (featureId: string) => void;
competitorInsights?: CompetitorPainPoint[];
}
@@ -51,4 +54,5 @@ export interface RoadmapTabsProps {
onConvertToSpec: (feature: RoadmapFeature) => void;
onGoToTask: (specId: string) => void;
onSave?: () => void;
onArchive?: (featureId: string) => void;
}
@@ -6,7 +6,7 @@ import { Label } from '../ui/label';
import { SettingsSection } from './SettingsSection';
import { useSettingsStore } from '../../stores/settings-store';
import { UI_SCALE_MIN, UI_SCALE_MAX, UI_SCALE_DEFAULT, UI_SCALE_STEP } from '../../../shared/constants';
import type { AppSettings } from '../../../shared/types';
import type { AppSettings, GpuAcceleration } from '../../../shared/types';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
interface DisplaySettingsProps {
@@ -274,6 +274,45 @@ export function DisplaySettings({ settings, onSettingsChange }: DisplaySettingsP
</Select>
</div>
</div>
{/* GPU Acceleration Setting */}
<div className="space-y-3">
<div className="flex items-center justify-between max-w-md">
<div className="space-y-1">
<Label htmlFor="gpuAcceleration" className="text-sm font-medium text-foreground">
{t('gpuAcceleration.label')}
</Label>
<p className="text-sm text-muted-foreground">
{t('gpuAcceleration.description')}
</p>
</div>
<Select
value={settings.gpuAcceleration || 'off'}
onValueChange={(value) => onSettingsChange({
...settings,
gpuAcceleration: value as GpuAcceleration
})}
>
<SelectTrigger id="gpuAcceleration" className="w-72">
<SelectValue />
</SelectTrigger>
<SelectContent className="max-h-60 overflow-y-auto">
<SelectItem value="auto">
{t('gpuAcceleration.auto')}
</SelectItem>
<SelectItem value="on">
{t('gpuAcceleration.on')}
</SelectItem>
<SelectItem value="off">
{t('gpuAcceleration.off')}
</SelectItem>
</SelectContent>
</Select>
</div>
<p className="text-xs text-muted-foreground">
{t('gpuAcceleration.helperText')}
</p>
</div>
</div>
</SettingsSection>
);
@@ -0,0 +1,157 @@
/**
* @vitest-environment jsdom
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import '../../../../shared/i18n';
import { DisplaySettings } from '../DisplaySettings';
import type { AppSettings } from '../../../../shared/types';
// Mock the settings store
vi.mock('../../../stores/settings-store', () => ({
useSettingsStore: vi.fn(() => ({
updateSettings: vi.fn()
}))
}));
// Track onValueChange callbacks per Select instance, keyed by the SelectTrigger id
let selectCallbacks: Map<string, (v: string) => void> = new Map();
let currentSelectCallback: ((v: string) => void) | null = null;
// Mock Radix Select to make it testable in jsdom (portals don't work in jsdom)
vi.mock('../../ui/select', () => {
return {
Select: ({ value, onValueChange, children }: { value: string; onValueChange: (v: string) => void; children: React.ReactNode }) => {
currentSelectCallback = onValueChange;
return <div data-value={value}>{children}</div>;
},
SelectTrigger: ({ id, children }: { id?: string; className?: string; children: React.ReactNode }) => {
if (id && currentSelectCallback) {
selectCallbacks.set(id, currentSelectCallback);
currentSelectCallback = null;
}
return <button data-testid={`select-trigger-${id || 'unknown'}`}>{children}</button>;
},
SelectValue: () => null,
SelectContent: ({ children }: { className?: string; children: React.ReactNode }) => (
<div data-testid="select-content">{children}</div>
),
SelectItem: ({ value, children }: { value: string; children: React.ReactNode }) => (
<div role="option" data-testid={`select-item-${value}`} data-value={value}>
{children}
</div>
)
};
});
const defaultSettings: AppSettings = {
uiScale: 100,
logOrder: 'chronological',
gpuAcceleration: 'auto'
} as AppSettings;
describe('DisplaySettings - GPU Acceleration Dropdown', () => {
let mockOnSettingsChange: (settings: AppSettings) => void;
beforeEach(() => {
vi.clearAllMocks();
selectCallbacks = new Map();
currentSelectCallback = null;
mockOnSettingsChange = vi.fn();
});
it('should render the GPU acceleration dropdown with all 3 options', () => {
render(
<DisplaySettings settings={defaultSettings} onSettingsChange={mockOnSettingsChange} />
);
expect(screen.getByText('GPU Acceleration')).toBeInTheDocument();
expect(screen.getByTestId('select-item-auto')).toBeInTheDocument();
expect(screen.getByTestId('select-item-on')).toBeInTheDocument();
expect(screen.getByTestId('select-item-off')).toBeInTheDocument();
});
it('should display the correct translated labels for each option', () => {
render(
<DisplaySettings settings={defaultSettings} onSettingsChange={mockOnSettingsChange} />
);
expect(screen.getByText('Auto (use WebGL when supported)')).toBeInTheDocument();
expect(screen.getByText('Always on')).toBeInTheDocument();
expect(screen.getByText('Off (default)')).toBeInTheDocument();
});
it('should display the current GPU acceleration value from settings', () => {
const settingsWithOn: AppSettings = { ...defaultSettings, gpuAcceleration: 'on' };
render(
<DisplaySettings settings={settingsWithOn} onSettingsChange={mockOnSettingsChange} />
);
// The GPU acceleration select is identified by its trigger id
const gpuTrigger = screen.getByTestId('select-trigger-gpuAcceleration');
const gpuSelect = gpuTrigger.closest('[data-value]');
expect(gpuSelect).toHaveAttribute('data-value', 'on');
});
it('should default to "off" when gpuAcceleration is not set', () => {
const settingsWithoutGpu: AppSettings = { ...defaultSettings, gpuAcceleration: undefined };
render(
<DisplaySettings settings={settingsWithoutGpu} onSettingsChange={mockOnSettingsChange} />
);
const gpuTrigger = screen.getByTestId('select-trigger-gpuAcceleration');
const gpuSelect = gpuTrigger.closest('[data-value]');
expect(gpuSelect).toHaveAttribute('data-value', 'off');
});
it('should call onSettingsChange with gpuAcceleration "on" when selected', () => {
render(
<DisplaySettings settings={defaultSettings} onSettingsChange={mockOnSettingsChange} />
);
selectCallbacks.get('gpuAcceleration')!('on');
expect(mockOnSettingsChange).toHaveBeenCalledWith(
expect.objectContaining({ gpuAcceleration: 'on' })
);
});
it('should call onSettingsChange with gpuAcceleration "off" when selected', () => {
render(
<DisplaySettings settings={defaultSettings} onSettingsChange={mockOnSettingsChange} />
);
selectCallbacks.get('gpuAcceleration')!('off');
expect(mockOnSettingsChange).toHaveBeenCalledWith(
expect.objectContaining({ gpuAcceleration: 'off' })
);
});
it('should call onSettingsChange with gpuAcceleration "auto" when selected', () => {
const settingsWithOff: AppSettings = { ...defaultSettings, gpuAcceleration: 'off' };
render(
<DisplaySettings settings={settingsWithOff} onSettingsChange={mockOnSettingsChange} />
);
selectCallbacks.get('gpuAcceleration')!('auto');
expect(mockOnSettingsChange).toHaveBeenCalledWith(
expect.objectContaining({ gpuAcceleration: 'auto' })
);
});
it('should render the GPU acceleration description text', () => {
render(
<DisplaySettings settings={defaultSettings} onSettingsChange={mockOnSettingsChange} />
);
expect(
screen.getByText('Use WebGL for terminal rendering (experimental, faster with many terminals)')
).toBeInTheDocument();
});
});
@@ -198,7 +198,11 @@ export function StagedInProjectMessage({ task, projectPath, hasWorktree = false,
setError(null);
try {
await persistTaskStatus(task.id, 'done');
const result = await persistTaskStatus(task.id, 'done', { keepWorktree: true });
if (!result.success) {
setError(result.error || 'Failed to mark as done');
return;
}
onClose?.();
} catch (err) {
console.error('Error marking task as done:', err);
@@ -15,6 +15,7 @@ import {
import type { ImageAttachment } from '../../../shared/types';
import {
MAX_IMAGES_PER_TASK,
MAX_IMAGE_SIZE,
ALLOWED_IMAGE_TYPES_DISPLAY
} from '../../../shared/constants';
@@ -30,6 +31,7 @@ export interface FileReferenceData {
interface ImageUploadErrorMessages {
maxImagesReached?: string;
invalidImageType?: string;
imageTooLarge?: string;
processPasteFailed?: string;
processDropFailed?: string;
}
@@ -74,6 +76,7 @@ interface UseImageUploadReturn {
const DEFAULT_ERROR_MESSAGES: Required<ImageUploadErrorMessages> = {
maxImagesReached: `Maximum of ${MAX_IMAGES_PER_TASK} images allowed`,
invalidImageType: `Invalid image type. Allowed: ${ALLOWED_IMAGE_TYPES_DISPLAY}`,
imageTooLarge: `Image exceeds maximum size of ${Math.round(MAX_IMAGE_SIZE / 1024 / 1024)}MB`,
processPasteFailed: 'Failed to process pasted image',
processDropFailed: 'Failed to process dropped image'
};
@@ -148,6 +151,12 @@ export function useImageUpload({
continue;
}
// Validate file size
if (file.size > MAX_IMAGE_SIZE) {
onError?.(errors.imageTooLarge);
continue;
}
try {
const dataUrl = await blobToBase64(file);
const thumbnail = await createThumbnail(dataUrl);
@@ -66,11 +66,35 @@ vi.mock('@xterm/addon-serialize', () => ({
vi.mock('../../../../lib/terminal-buffer-manager', () => ({
terminalBufferManager: {
get: vi.fn(() => ''),
getAndClear: vi.fn(() => ''),
set: vi.fn(),
clear: vi.fn()
}
}));
// Mock WebGL context manager
const mockWebglRegister = vi.fn();
const mockWebglAcquire = vi.fn();
const mockWebglUnregister = vi.fn();
vi.mock('../../../lib/webgl-context-manager', () => ({
webglContextManager: {
register: (...args: unknown[]) => mockWebglRegister(...args),
acquire: (...args: unknown[]) => mockWebglAcquire(...args),
unregister: (...args: unknown[]) => mockWebglUnregister(...args),
}
}));
// Mock settings store (for gpuAcceleration setting)
const mockSettingsStoreState = {
settings: { gpuAcceleration: 'auto' as string | undefined }
};
vi.mock('../../../stores/settings-store', () => ({
useSettingsStore: Object.assign(vi.fn(), {
getState: () => mockSettingsStoreState,
subscribe: vi.fn(() => vi.fn()),
})
}));
// Mock navigator.platform for platform detection
const originalNavigatorPlatform = navigator.platform;
@@ -837,3 +861,186 @@ describe('useXterm keyboard handlers', () => {
});
});
});
describe('useXterm WebGL context management', () => {
// Mock requestAnimationFrame for jsdom environment
const originalRequestAnimationFrame = global.requestAnimationFrame;
const originalCancelAnimationFrame = global.cancelAnimationFrame;
beforeAll(() => {
global.requestAnimationFrame = vi.fn((cb: FrameRequestCallback) => setTimeout(cb, 0) as unknown as number);
global.cancelAnimationFrame = vi.fn((id: number) => clearTimeout(id));
});
afterAll(() => {
global.requestAnimationFrame = originalRequestAnimationFrame;
global.cancelAnimationFrame = originalCancelAnimationFrame;
});
beforeEach(() => {
vi.useFakeTimers();
vi.clearAllMocks();
// Reset gpuAcceleration to default
mockSettingsStoreState.settings.gpuAcceleration = 'auto';
// Mock ResizeObserver
global.ResizeObserver = vi.fn().mockImplementation(function() {
return { observe: vi.fn(), unobserve: vi.fn(), disconnect: vi.fn() };
});
// Mock window.electronAPI
(window as unknown as { electronAPI: unknown }).electronAPI = {
sendTerminalInput: vi.fn(),
openExternal: vi.fn(),
};
});
afterEach(() => {
vi.clearAllTimers();
vi.useRealTimers();
vi.restoreAllMocks();
});
/**
* Helper to render useXterm and wait for initialization
*/
async function renderUseXterm(terminalId = 'test-webgl-terminal') {
// Set up XTerm mock with dispose tracking
const mockDispose = vi.fn();
(XTerm as unknown as Mock).mockImplementation(function() {
return {
open: vi.fn(),
loadAddon: vi.fn(),
attachCustomKeyEventHandler: vi.fn(),
hasSelection: vi.fn(() => false),
getSelection: vi.fn(() => ''),
paste: vi.fn(),
input: vi.fn(),
onData: vi.fn(),
onResize: vi.fn(),
dispose: mockDispose,
write: vi.fn(),
cols: 80,
rows: 24,
options: {
cursorBlink: true,
cursorStyle: 'block',
fontSize: 14,
fontFamily: 'monospace',
fontWeight: 'normal',
lineHeight: 1,
letterSpacing: 0,
theme: { cursorAccent: '#000000' },
scrollback: 1000
},
refresh: vi.fn()
};
});
const { FitAddon } = await import('@xterm/addon-fit');
(FitAddon as unknown as Mock).mockImplementation(function() {
return { fit: vi.fn(), dispose: vi.fn() };
});
const { WebLinksAddon } = await import('@xterm/addon-web-links');
(WebLinksAddon as unknown as Mock).mockImplementation(function() {
return {};
});
const { SerializeAddon } = await import('@xterm/addon-serialize');
(SerializeAddon as unknown as Mock).mockImplementation(function() {
return { serialize: vi.fn(() => ''), dispose: vi.fn() };
});
let disposeHook: (() => void) | null = null;
const TestWrapper = () => {
const result = useXterm({ terminalId });
// Expose dispose via ref so tests can call it
disposeHook = result.dispose;
return React.createElement('div', { ref: result.terminalRef });
};
await act(async () => {
render(React.createElement(TestWrapper));
});
return { disposeHook: () => disposeHook?.() };
}
it('should lazily import and acquire WebGL context when gpuAcceleration is "auto"', async () => {
mockSettingsStoreState.settings.gpuAcceleration = 'auto';
await renderUseXterm('terminal-auto');
// Flush the dynamic import() promise + microtasks
await act(async () => { await vi.advanceTimersByTimeAsync(0); });
expect(mockWebglRegister).toHaveBeenCalledWith('terminal-auto', expect.anything());
expect(mockWebglAcquire).toHaveBeenCalledWith('terminal-auto');
});
it('should lazily import and acquire WebGL context when gpuAcceleration is "on"', async () => {
mockSettingsStoreState.settings.gpuAcceleration = 'on';
await renderUseXterm('terminal-on');
await act(async () => { await vi.advanceTimersByTimeAsync(0); });
expect(mockWebglRegister).toHaveBeenCalledWith('terminal-on', expect.anything());
expect(mockWebglAcquire).toHaveBeenCalledWith('terminal-on');
});
it('should NOT import WebGL module at all when gpuAcceleration is "off"', async () => {
mockSettingsStoreState.settings.gpuAcceleration = 'off';
await renderUseXterm('terminal-off');
await act(async () => { await vi.advanceTimersByTimeAsync(0); });
// When off, the dynamic import() never fires — no GPU code runs
expect(mockWebglRegister).not.toHaveBeenCalled();
expect(mockWebglAcquire).not.toHaveBeenCalled();
});
it('should unregister WebGL context on terminal disposal', async () => {
mockSettingsStoreState.settings.gpuAcceleration = 'auto';
const { disposeHook } = await renderUseXterm('terminal-dispose');
// Flush the dynamic import so the manager ref is populated
await act(async () => { await vi.advanceTimersByTimeAsync(0); });
expect(mockWebglRegister).toHaveBeenCalledWith('terminal-dispose', expect.anything());
// Dispose the terminal
act(() => {
disposeHook();
});
expect(mockWebglUnregister).toHaveBeenCalledWith('terminal-dispose');
});
it('should NOT unregister on disposal when WebGL was never loaded (off)', async () => {
mockSettingsStoreState.settings.gpuAcceleration = 'off';
const { disposeHook } = await renderUseXterm('terminal-off-dispose');
await act(async () => { await vi.advanceTimersByTimeAsync(0); });
// Dispose the terminal
act(() => {
disposeHook();
});
// WebGL was never loaded, so unregister should not be called
expect(mockWebglUnregister).not.toHaveBeenCalled();
});
it('should fallback to "off" when gpuAcceleration is undefined (upgrading users)', async () => {
mockSettingsStoreState.settings.gpuAcceleration = undefined;
await renderUseXterm('terminal-undefined');
await act(async () => { await vi.advanceTimersByTimeAsync(0); });
// When undefined, the ?? 'off' fallback means no WebGL import at all
expect(mockWebglRegister).not.toHaveBeenCalled();
expect(mockWebglAcquire).not.toHaveBeenCalled();
});
});
@@ -52,10 +52,12 @@ export function useTerminalEvents({
const store = useTerminalStore.getState();
store.setTerminalStatus(terminalId, 'exited');
// Reset Claude mode when terminal exits - the Claude process has ended
// Use updateTerminal instead of setClaudeMode to avoid changing status back to 'running'
// setTerminalStatus('exited') already sends SHELL_EXITED to XState (which handles
// claude_active -> exited transition), so setClaudeMode(false) here only updates Zustand
// (its XState guard skips CLAUDE_EXITED since the machine is already in 'exited')
const terminal = store.getTerminal(terminalId);
if (terminal?.isClaudeMode) {
store.updateTerminal(terminalId, { isClaudeMode: false });
store.setClaudeMode(terminalId, false);
}
onExitRef.current?.(exitCode);
@@ -146,12 +148,12 @@ export function useTerminalEvents({
return;
}
// Reset Claude mode - Claude has exited but terminal is still running
// Use updateTerminal to set all Claude-related state at once
// Use setClaudeMode which properly sends CLAUDE_EXITED to the XState machine,
// then clear residual Claude state separately
store.setClaudeMode(terminalId, false);
store.updateTerminal(terminalId, {
isClaudeMode: false,
isClaudeBusy: undefined,
claudeSessionId: undefined,
status: 'running' // Terminal is still running, just not in Claude mode
});
console.warn('[Terminal] Claude exited, reset mode for terminal:', terminalId);
}
@@ -4,12 +4,14 @@ import { FitAddon } from '@xterm/addon-fit';
import { WebLinksAddon } from '@xterm/addon-web-links';
import { SerializeAddon } from '@xterm/addon-serialize';
import { terminalBufferManager } from '../../lib/terminal-buffer-manager';
import { registerOutputCallback, unregisterOutputCallback } from '../../stores/terminal-store';
import { registerOutputCallback, unregisterOutputCallback, useTerminalStore } from '../../stores/terminal-store';
import { useTerminalFontSettingsStore } from '../../stores/terminal-font-settings-store';
import { isWindows as checkIsWindows, isLinux as checkIsLinux } from '../../lib/os-detection';
import { debounce } from '../../lib/debounce';
import { DEFAULT_TERMINAL_THEME } from '../../lib/terminal-theme';
import { debugLog, debugError } from '../../../shared/utils/debug-logger';
import { useSettingsStore } from '../../stores/settings-store';
import type { WebGLContextManagerType } from '../../lib/webgl-context-manager';
interface UseXtermOptions {
terminalId: string;
@@ -58,6 +60,8 @@ export function useXterm({ terminalId, onCommandEnter, onResize, onDimensionsRea
const commandBufferRef = useRef<string>('');
const isDisposedRef = useRef<boolean>(false);
const dimensionsReadyCalledRef = useRef<boolean>(false);
// Lazily-loaded WebGL context manager — only populated when gpuAcceleration !== 'off'
const webglManagerRef = useRef<WebGLContextManagerType | null>(null);
const onResizeRef = useRef(onResize);
const [dimensions, setDimensions] = useState<{ cols: number; rows: number }>({ cols: 80, rows: 24 });
@@ -117,6 +121,29 @@ export function useXterm({ terminalId, onCommandEnter, onResize, onDimensionsRea
xterm.open(terminalRef.current);
// WebGL acceleration: lazily load the WebGL module and acquire a context.
// The dynamic import() ensures NO GPU code (WebGL2 probing, context creation)
// runs unless the user has explicitly enabled GPU acceleration.
// This prevents GPU process instability on systems where WebGL2 is problematic
// (e.g., Apple Silicon Macs with certain macOS / Electron combinations).
const gpuAcceleration = useSettingsStore.getState().settings.gpuAcceleration ?? 'off';
debugLog(`[useXterm] WebGL check for ${terminalId}: gpuAcceleration=${gpuAcceleration}`);
if (gpuAcceleration !== 'off') {
import('../../lib/webgl-context-manager')
.then(({ webglContextManager }) => {
// Guard: terminal may have been disposed while the import was resolving
if (isDisposedRef.current) return;
webglManagerRef.current = webglContextManager;
webglContextManager.register(terminalId, xterm);
webglContextManager.acquire(terminalId);
debugLog(`[useXterm] WebGL acquired for ${terminalId}`);
})
.catch((error) => {
// WebGL is a progressive enhancement — terminal works fine without it
debugError(`[useXterm] WebGL initialization failed for ${terminalId}, falling back to canvas renderer:`, error);
});
}
// Platform detection for copy/paste shortcuts
// Use existing os-detection module instead of custom implementation
const isWindows = checkIsWindows();
@@ -279,9 +306,25 @@ export function useXterm({ terminalId, onCommandEnter, onResize, onDimensionsRea
// Use atomic getAndClear to prevent race condition where new output could arrive between get() and clear()
const bufferedOutput = terminalBufferManager.getAndClear(terminalId);
if (bufferedOutput && bufferedOutput.length > 0) {
debugLog(`[useXterm] Replaying buffered output for terminal: ${terminalId}, buffer size: ${bufferedOutput.length} chars`);
xterm.write(bufferedOutput);
debugLog(`[useXterm] Buffer replay complete and cleared for terminal: ${terminalId}`);
// For Claude-mode terminals that are NOT being restored for the first time
// (i.e., project switch remount), skip buffer replay.
// Reason: the buffer contains serialized state + accumulated raw PTY output
// from the TUI during the unmount period. This concatenation creates garbled
// display. The forced SIGWINCH (from pty-manager) will make Claude Code redraw
// its full TUI properly.
// For initial restore (isRestored=true), we DO replay to show the saved state
// as a loading preview while claude --continue starts.
const terminal = useTerminalStore.getState().terminals.find(t => t.id === terminalId);
const isClaudeActive = terminal?.isClaudeMode || terminal?.pendingClaudeResume;
const isInitialRestore = terminal?.isRestored === true;
if (isClaudeActive && !isInitialRestore) {
debugLog(`[useXterm] Skipping buffer replay for Claude-mode terminal on project switch remount: ${terminalId}`);
} else {
debugLog(`[useXterm] Replaying buffered output for terminal: ${terminalId}, buffer size: ${bufferedOutput.length} chars`);
xterm.write(bufferedOutput);
debugLog(`[useXterm] Buffer replay complete and cleared for terminal: ${terminalId}`);
}
} else {
debugLog(`[useXterm] No buffered output to replay for terminal: ${terminalId}`);
}
@@ -552,6 +595,16 @@ export function useXterm({ terminalId, onCommandEnter, onResize, onDimensionsRea
// Serialize buffer before disposing to preserve ANSI formatting
serializeBuffer();
// Release WebGL context before disposing addons and xterm (only if WebGL was loaded)
if (webglManagerRef.current) {
try {
webglManagerRef.current.unregister(terminalId);
} catch (error) {
debugError(`[useXterm] WebGL cleanup failed for ${terminalId}:`, error);
}
webglManagerRef.current = null;
}
// Dispose addons explicitly before disposing xterm
// While xterm.dispose() handles loaded addons, explicit disposal ensures
// resources are freed in a predictable order and prevents potential leaks
@@ -1,4 +1,6 @@
import { useEffect, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { toast } from './use-toast';
import { useTerminalStore } from '../stores/terminal-store';
import { terminalBufferManager } from '../lib/terminal-buffer-manager';
import type { TerminalProfileChangedEvent } from '../../shared/types';
@@ -8,16 +10,18 @@ import { debugLog, debugError } from '../../shared/utils/debug-logger';
* Hook to handle terminal profile change events.
* When a Claude profile switches, all terminals need to be recreated with the new profile's
* environment variables. Terminals with active Claude sessions will have their sessions
* migrated and can be resumed with --resume {sessionId}.
* migrated and automatically resumed with --continue.
*/
export function useTerminalProfileChange(): void {
const { t } = useTranslation(['terminal']);
// Track terminals being recreated to prevent duplicate processing
const recreatingTerminals = useRef<Set<string>>(new Set());
const recreateTerminal = useCallback(async (
terminalId: string,
sessionId?: string,
sessionMigrated?: boolean
sessionMigrated?: boolean,
isClaudeMode?: boolean
) => {
// Prevent duplicate recreation
if (recreatingTerminals.current.has(terminalId)) {
@@ -101,25 +105,39 @@ export function useTerminalProfileChange(): void {
newId: newTerminal.id
});
// If there was an active Claude session that was migrated, show a message
// and set up for potential resume
// If there was an active Claude session that was migrated, auto-resume it
if (sessionId && sessionMigrated) {
debugLog('[useTerminalProfileChange] Session migrated, ready for resume:', sessionId);
// Store the session ID so the user can resume if desired
debugLog('[useTerminalProfileChange] Session migrated, auto-resuming:', sessionId);
// Store the session ID for tracking
store.setClaudeSessionId(newTerminal.id, sessionId);
// Set pending resume flag - user can trigger resume from terminal tab
store.setPendingClaudeResume(newTerminal.id, true);
// Send a message to the terminal about the session
window.electronAPI.sendTerminalInput(
// Auto-resume the Claude session with --continue
// YOLO mode (dangerouslySkipPermissions) is preserved server-side by the
// main process during migration (storeMigratedSessionFlag), so resumeClaudeAsync
// will restore it automatically when migratedSession is true
// Note: resumeClaudeInTerminal uses fire-and-forget IPC (ipcRenderer.send).
// If resume fails in the main process, the error is logged but no failure event
// is emitted back to the renderer. The terminal will show an empty shell prompt.
window.electronAPI.resumeClaudeInTerminal(
newTerminal.id,
`# Profile switched. Previous Claude session available.\n# Run: claude --resume ${sessionId}\n`
sessionId,
{ migratedSession: true }
);
debugLog('[useTerminalProfileChange] Resume initiated for terminal:', newTerminal.id);
} else if (isClaudeMode && sessionId && !sessionMigrated) {
// Session had an active Claude session but migration failed
// Notify user that their Claude session was lost
debugError('[useTerminalProfileChange] Session migration failed for terminal:', terminalId);
toast({
title: t('terminal:swap.migrationFailed'),
variant: 'destructive',
});
}
} finally {
recreatingTerminals.current.delete(terminalId);
}
}, []);
}, [t]);
useEffect(() => {
const cleanup = window.electronAPI.onTerminalProfileChanged(async (event: TerminalProfileChangedEvent) => {
@@ -134,7 +152,8 @@ export function useTerminalProfileChange(): void {
await recreateTerminal(
terminalInfo.id,
terminalInfo.sessionId,
terminalInfo.sessionMigrated
terminalInfo.sessionMigrated,
terminalInfo.isClaudeMode
);
}
@@ -62,6 +62,10 @@ const browserMockAPI: ElectronAPI = {
success: true
}),
saveCompetitorAnalysis: async () => ({
success: true
}),
generateRoadmap: (_projectId: string, _enableCompetitorAnalysis?: boolean, _refreshCompetitorAnalysis?: boolean) => {
console.warn('[Browser Mock] generateRoadmap called');
},
@@ -214,6 +218,7 @@ const browserMockAPI: ElectronAPI = {
markReviewPosted: async () => true,
getPRReview: async () => null,
getPRReviewsBatch: async () => ({}),
notifyExternalReviewComplete: async () => {},
deletePRReview: async () => true,
checkNewCommits: async () => ({ hasNewCommits: false, newCommitCount: 0 }),
checkMergeReadiness: async () => ({ isDraft: false, mergeable: 'UNKNOWN' as const, isBehind: false, ciStatus: 'none' as const, blockers: [] }),
@@ -225,6 +230,7 @@ const browserMockAPI: ElectronAPI = {
onPRReviewProgress: () => () => {},
onPRReviewComplete: () => () => {},
onPRReviewError: () => () => {},
onPRReviewStateChange: () => () => {},
onPRLogsUpdated: () => () => {},
batchAutoFix: () => {},
getBatches: async () => [],
@@ -16,7 +16,7 @@ export const insightsMock = {
} : null
}),
listInsightsSessions: async () => ({
listInsightsSessions: async (_projectId?: string, _includeArchived?: boolean) => ({
success: true,
data: mockInsightsSessions
}),
@@ -69,6 +69,28 @@ export const insightsMock = {
return { success: true };
},
deleteInsightsSessions: async (_projectId: string, sessionIds: string[]) => {
for (const sessionId of sessionIds) {
const index = mockInsightsSessions.findIndex(s => s.id === sessionId);
if (index !== -1) {
mockInsightsSessions.splice(index, 1);
}
}
return { success: true, data: { deletedIds: sessionIds, failedIds: [] } };
},
archiveInsightsSession: async (_projectId: string, _sessionId: string) => {
return { success: true };
},
archiveInsightsSessions: async (_projectId: string, sessionIds: string[]) => {
return { success: true, data: { archivedIds: sessionIds, failedIds: [] } };
},
unarchiveInsightsSession: async (_projectId: string, _sessionId: string) => {
return { success: true };
},
renameInsightsSession: async (_projectId: string, sessionId: string, newTitle: string) => {
const session = mockInsightsSessions.find(s => s.id === sessionId);
if (session) {
@@ -184,6 +184,9 @@ class WebGLContextManager {
}
}
/** Type alias for the manager — used by consumers that import lazily via dynamic import() */
export type WebGLContextManagerType = WebGLContextManager;
// Export singleton instance
export const webglContextManager = WebGLContextManager.getInstance();
@@ -23,9 +23,7 @@ export {
export {
usePRReviewStore,
initializePRReviewListeners,
cleanupPRReviewListeners,
startPRReview,
startFollowupReview
cleanupPRReviewListeners
} from './pr-review-store';
import { initializePRReviewListeners as _initPRReviewListeners } from './pr-review-store';
import { cleanupPRReviewListeners as _cleanupPRReviewListeners } from './pr-review-store';
@@ -2,7 +2,8 @@ import { create } from 'zustand';
import type {
PRReviewProgress,
PRReviewResult,
NewCommitsCheck
NewCommitsCheck,
PRReviewStatePayload
} from '../../../preload/api/modules/github-api';
import type {
ChecksStatus,
@@ -44,14 +45,13 @@ interface PRReviewStoreState {
// Key: `${projectId}:${prNumber}`
prReviews: Record<string, PRReviewState>;
// Actions
startPRReview: (projectId: string, prNumber: number) => void;
startFollowupReview: (projectId: string, prNumber: number) => void;
setPRReviewProgress: (projectId: string, progress: PRReviewProgress) => void;
setPRReviewResult: (projectId: string, result: PRReviewResult, options?: { preserveNewCommitsCheck?: boolean }) => void;
setPRReviewError: (projectId: string, prNumber: number, error: string) => void;
// XState state change handler
handlePRReviewStateChange: (key: string, payload: PRReviewStatePayload) => void;
// Kept actions (not managed by XState)
/** Load a review result from disk into the store (not triggered by XState) */
setLoadedReviewResult: (projectId: string, result: PRReviewResult, options?: { preserveNewCommitsCheck?: boolean }) => void;
setNewCommitsCheck: (projectId: string, prNumber: number, check: NewCommitsCheck) => void;
clearPRReview: (projectId: string, prNumber: number) => void;
/** Update PR status from polling (CI checks, reviews, mergeability) */
setPRStatus: (projectId: string, prNumber: number, status: {
checksStatus: ChecksStatus;
@@ -61,8 +61,6 @@ interface PRReviewStoreState {
}) => void;
/** Clear PR status fields for a specific PR */
clearPRStatus: (projectId: string, prNumber: number) => void;
/** Start an external review (from PR list) - sets isReviewing and isExternalReview */
setExternalReviewInProgress: (projectId: string, prNumber: number, inProgressSince?: string) => void;
// Selectors
getPRReviewState: (projectId: string, prNumber: number) => PRReviewState | null;
@@ -80,97 +78,57 @@ export const usePRReviewStore = create<PRReviewStoreState>((set, get) => ({
// Initial state
prReviews: {},
// Actions
startPRReview: (projectId: string, prNumber: number) => set((state) => {
const key = `${projectId}:${prNumber}`;
const existing = state.prReviews[key];
return {
prReviews: {
...state.prReviews,
[key]: {
prNumber,
projectId,
isReviewing: true,
startedAt: new Date().toISOString(),
progress: null,
result: null,
previousResult: null,
error: null,
newCommitsCheck: existing?.newCommitsCheck ?? null,
checksStatus: existing?.checksStatus ?? null,
reviewsStatus: existing?.reviewsStatus ?? null,
mergeableState: existing?.mergeableState ?? null,
lastPolled: existing?.lastPolled ?? null,
isExternalReview: false
}
}
};
}),
// XState state change handler — maps XState state/context back to PRReviewState shape
handlePRReviewStateChange: (key: string, payload: PRReviewStatePayload) => {
const isCompleted = payload.state === 'completed';
startFollowupReview: (projectId: string, prNumber: number) => set((state) => {
const key = `${projectId}:${prNumber}`;
const existing = state.prReviews[key];
set((state) => {
const existing = state.prReviews[key];
// Log warning if starting follow-up without a previous result
if (!existing?.result) {
console.warn(
`[PRReviewStore] Starting follow-up review for PR #${prNumber} without a previous result. ` +
`This may indicate the follow-up was triggered incorrectly.`
);
const updated: PRReviewState = {
prNumber: payload.prNumber,
projectId: payload.projectId,
isReviewing: payload.state === 'reviewing' || payload.state === 'externalReview',
startedAt: payload.startedAt,
progress: payload.progress,
result: payload.result,
previousResult: payload.previousResult,
error: payload.error,
isExternalReview: payload.isExternalReview,
// Preserve polling data — not managed by XState
checksStatus: existing?.checksStatus ?? null,
reviewsStatus: existing?.reviewsStatus ?? null,
mergeableState: existing?.mergeableState ?? null,
lastPolled: existing?.lastPolled ?? null,
// Preserve newCommitsCheck unless review completed (it was just reviewed)
newCommitsCheck: isCompleted ? null : (existing?.newCommitsCheck ?? null),
};
return {
prReviews: {
...state.prReviews,
[key]: updated,
},
};
});
// Trigger registered refresh callbacks when review completes
if (isCompleted) {
refreshCallbacks.forEach(callback => {
Promise.resolve(callback()).catch(error => {
console.error('[PRReviewStore] Error in refresh callback:', error);
});
});
}
},
return {
prReviews: {
...state.prReviews,
[key]: {
prNumber,
projectId,
isReviewing: true,
startedAt: new Date().toISOString(),
progress: null,
result: null,
previousResult: existing?.result ?? null, // Preserve for follow-up continuity
error: null,
newCommitsCheck: existing?.newCommitsCheck ?? null,
checksStatus: existing?.checksStatus ?? null,
reviewsStatus: existing?.reviewsStatus ?? null,
mergeableState: existing?.mergeableState ?? null,
lastPolled: existing?.lastPolled ?? null,
isExternalReview: false
}
}
};
}),
setPRReviewProgress: (projectId: string, progress: PRReviewProgress) => set((state) => {
const key = `${projectId}:${progress.prNumber}`;
const existing = state.prReviews[key];
return {
prReviews: {
...state.prReviews,
[key]: {
prNumber: progress.prNumber,
projectId,
isReviewing: true,
startedAt: existing?.startedAt ?? null,
progress,
result: existing?.result ?? null,
previousResult: existing?.previousResult ?? null,
error: null,
newCommitsCheck: existing?.newCommitsCheck ?? null,
checksStatus: existing?.checksStatus ?? null,
reviewsStatus: existing?.reviewsStatus ?? null,
mergeableState: existing?.mergeableState ?? null,
lastPolled: existing?.lastPolled ?? null,
isExternalReview: existing?.isExternalReview ?? false
}
}
};
}),
setPRReviewResult: (projectId: string, result: PRReviewResult, options?: { preserveNewCommitsCheck?: boolean }) => set((state) => {
setLoadedReviewResult: (projectId: string, result: PRReviewResult, options?: { preserveNewCommitsCheck?: boolean }) => set((state) => {
const key = `${projectId}:${result.prNumber}`;
const existing = state.prReviews[key];
// Don't overwrite active review state from XState
if (existing?.isReviewing) {
return state;
}
return {
prReviews: {
...state.prReviews,
@@ -178,47 +136,19 @@ export const usePRReviewStore = create<PRReviewStoreState>((set, get) => ({
prNumber: result.prNumber,
projectId,
isReviewing: false,
startedAt: existing?.startedAt ?? null,
startedAt: null,
progress: null,
result,
previousResult: existing?.previousResult ?? null,
error: result.error ?? null,
// Clear new commits check when review completes (it was just reviewed)
// BUT preserve it during preload/refresh to avoid race condition
error: null,
newCommitsCheck: options?.preserveNewCommitsCheck ? (existing?.newCommitsCheck ?? null) : null,
checksStatus: existing?.checksStatus ?? null,
reviewsStatus: existing?.reviewsStatus ?? null,
mergeableState: existing?.mergeableState ?? null,
lastPolled: existing?.lastPolled ?? null,
isExternalReview: existing?.isExternalReview ?? false
}
}
};
}),
setPRReviewError: (projectId: string, prNumber: number, error: string) => set((state) => {
const key = `${projectId}:${prNumber}`;
const existing = state.prReviews[key];
return {
prReviews: {
...state.prReviews,
[key]: {
prNumber,
projectId,
isReviewing: false,
startedAt: existing?.startedAt ?? null,
progress: null,
result: existing?.result ?? null,
previousResult: existing?.previousResult ?? null,
error,
newCommitsCheck: existing?.newCommitsCheck ?? null,
checksStatus: existing?.checksStatus ?? null,
reviewsStatus: existing?.reviewsStatus ?? null,
mergeableState: existing?.mergeableState ?? null,
lastPolled: existing?.lastPolled ?? null,
isExternalReview: existing?.isExternalReview ?? false
}
}
isExternalReview: false,
},
},
};
}),
@@ -260,11 +190,6 @@ export const usePRReviewStore = create<PRReviewStoreState>((set, get) => ({
};
}),
clearPRReview: (projectId: string, prNumber: number) => set((state) => {
const key = `${projectId}:${prNumber}`;
const { [key]: _, ...rest } = state.prReviews;
return { prReviews: rest };
}),
setPRStatus: (projectId: string, prNumber: number, status: {
checksStatus: ChecksStatus;
@@ -332,32 +257,6 @@ export const usePRReviewStore = create<PRReviewStoreState>((set, get) => ({
};
}),
setExternalReviewInProgress: (projectId: string, prNumber: number, inProgressSince?: string) => set((state) => {
const key = `${projectId}:${prNumber}`;
const existing = state.prReviews[key];
return {
prReviews: {
...state.prReviews,
[key]: {
prNumber,
projectId,
isReviewing: true,
startedAt: inProgressSince || new Date().toISOString(),
progress: null,
result: existing?.result ?? null,
previousResult: existing?.previousResult ?? null,
error: null,
newCommitsCheck: existing?.newCommitsCheck ?? null,
checksStatus: existing?.checksStatus ?? null,
reviewsStatus: existing?.reviewsStatus ?? null,
mergeableState: existing?.mergeableState ?? null,
lastPolled: existing?.lastPolled ?? null,
isExternalReview: true
}
}
};
}),
// Selectors
getPRReviewState: (projectId: string, prNumber: number) => {
const { prReviews } = get();
@@ -398,50 +297,18 @@ export function initializePRReviewListeners(): void {
const store = usePRReviewStore.getState();
// Check if GitHub PR Review API is available
if (!window.electronAPI?.github?.onPRReviewProgress) {
if (!window.electronAPI?.github?.onPRReviewStateChange) {
console.warn('[GitHub PR Store] GitHub PR Review API not available, skipping listener setup');
return;
}
// Listen for PR review progress events
// Each on* method returns a cleanup function — capture them for proper teardown
const cleanupProgress = window.electronAPI.github.onPRReviewProgress(
(projectId: string, progress: PRReviewProgress) => {
store.setPRReviewProgress(projectId, progress);
// Listen for XState state changes — single handler replaces progress/complete/error listeners
const cleanupStateChange = window.electronAPI.github.onPRReviewStateChange(
(key: string, payload: PRReviewStatePayload) => {
store.handlePRReviewStateChange(key, payload);
}
);
cleanupFunctions.push(cleanupProgress);
// Listen for PR review completion events
const cleanupComplete = window.electronAPI.github.onPRReviewComplete(
(projectId: string, result: PRReviewResult) => {
// When the backend detects an already-running review (e.g., started from another
// client or the PR list), it returns overallStatus === 'in_progress' instead of
// a real result. Transition to external-review-in-progress so the log polling
// activates and the UI shows the ongoing review.
if (result.overallStatus === 'in_progress') {
store.setExternalReviewInProgress(projectId, result.prNumber, result.inProgressSince);
return;
}
store.setPRReviewResult(projectId, result);
// Trigger all registered refresh callbacks when review completes
refreshCallbacks.forEach(callback => {
Promise.resolve(callback()).catch(error => {
console.error('[PRReviewStore] Error in refresh callback:', error);
});
});
}
);
cleanupFunctions.push(cleanupComplete);
// Listen for PR review error events
const cleanupError = window.electronAPI.github.onPRReviewError(
(projectId: string, data: { prNumber: number; error: string }) => {
store.setPRReviewError(projectId, data.prNumber, data.error);
}
);
cleanupFunctions.push(cleanupError);
cleanupFunctions.push(cleanupStateChange);
// Listen for GitHub auth changes - clear all PR review state when account changes
const cleanupAuthChanged = window.electronAPI.github.onGitHubAuthChanged(
@@ -457,7 +324,7 @@ export function initializePRReviewListeners(): void {
cleanupFunctions.push(cleanupAuthChanged);
// Listen for PR status polling updates (CI checks, reviews, mergeability)
window.electronAPI.github.onPRStatusUpdate(
const cleanupStatusUpdate = window.electronAPI.github.onPRStatusUpdate(
(update: PRStatusUpdate) => {
const { projectId, statuses } = update;
for (const status of statuses) {
@@ -470,6 +337,7 @@ export function initializePRReviewListeners(): void {
}
}
);
cleanupFunctions.push(cleanupStatusUpdate);
prReviewListenersInitialized = true;
}
@@ -490,22 +358,3 @@ export function cleanupPRReviewListeners(): void {
refreshCallbacks.clear();
prReviewListenersInitialized = false;
}
/**
* Start a PR review and track it in the store
*/
export function startPRReview(projectId: string, prNumber: number): void {
const store = usePRReviewStore.getState();
store.startPRReview(projectId, prNumber);
window.electronAPI.github.runPRReview(projectId, prNumber);
}
/**
* Start a follow-up PR review and track it in the store
* Uses startFollowupReview action to preserve previous result for continuity
*/
export function startFollowupReview(projectId: string, prNumber: number): void {
const store = usePRReviewStore.getState();
store.startFollowupReview(projectId, prNumber);
window.electronAPI.github.runFollowupReview(projectId, prNumber);
}
@@ -8,7 +8,8 @@ import type {
InsightsToolUsage,
InsightsModelConfig,
TaskMetadata,
Task
Task,
ImageAttachment
} from '../../shared/types';
interface ToolUsage {
@@ -27,6 +28,8 @@ interface InsightsState {
currentTool: ToolUsage | null; // Currently executing tool
toolsUsed: InsightsToolUsage[]; // Tools used during current response
isLoadingSessions: boolean;
showArchived: boolean; // Whether to include archived sessions in listings
pendingImages: ImageAttachment[]; // Images pending attachment to next message
// Actions
setSession: (session: InsightsSession | null) => void;
@@ -44,6 +47,8 @@ interface InsightsState {
finalizeStreamingMessage: () => void;
clearSession: () => void;
setLoadingSessions: (loading: boolean) => void;
setShowArchived: (showArchived: boolean) => void;
setPendingImages: (images: ImageAttachment[]) => void;
}
const initialStatus: InsightsChatStatus = {
@@ -62,6 +67,8 @@ export const useInsightsStore = create<InsightsState>((set, _get) => ({
currentTool: null,
toolsUsed: [],
isLoadingSessions: false,
showArchived: false,
pendingImages: [],
// Actions
setSession: (session) => set({ session }),
@@ -72,6 +79,8 @@ export const useInsightsStore = create<InsightsState>((set, _get) => ({
setLoadingSessions: (loading) => set({ isLoadingSessions: loading }),
setShowArchived: (showArchived) => set({ showArchived }),
setPendingMessage: (message) => set({ pendingMessage: message }),
addMessage: (message) =>
@@ -201,18 +210,24 @@ export const useInsightsStore = create<InsightsState>((set, _get) => ({
streamingContent: '',
streamingTasks: [],
currentTool: null,
toolsUsed: []
})
toolsUsed: [],
pendingImages: []
}),
setPendingImages: (images) => set({ pendingImages: images })
}));
// Helper functions
export async function loadInsightsSessions(projectId: string): Promise<void> {
export async function loadInsightsSessions(projectId: string, includeArchived?: boolean): Promise<void> {
const store = useInsightsStore.getState();
store.setLoadingSessions(true);
// Use explicit parameter if provided, otherwise read from store
const archived = includeArchived ?? store.showArchived;
try {
const result = await window.electronAPI.listInsightsSessions(projectId);
const result = await window.electronAPI.listInsightsSessions(projectId, archived);
if (result.success && result.data) {
store.setSessions(result.data);
} else {
@@ -223,7 +238,7 @@ export async function loadInsightsSessions(projectId: string): Promise<void> {
}
}
export async function loadInsightsSession(projectId: string): Promise<void> {
export async function loadInsightsSession(projectId: string, includeArchived?: boolean): Promise<void> {
const result = await window.electronAPI.getInsightsSession(projectId);
if (result.success && result.data) {
useInsightsStore.getState().setSession(result.data);
@@ -231,24 +246,30 @@ export async function loadInsightsSession(projectId: string): Promise<void> {
useInsightsStore.getState().setSession(null);
}
// Also load the sessions list
await loadInsightsSessions(projectId);
await loadInsightsSessions(projectId, includeArchived);
}
export function sendMessage(projectId: string, message: string, modelConfig?: InsightsModelConfig): void {
export function sendMessage(projectId: string, message: string, modelConfig?: InsightsModelConfig, images?: ImageAttachment[]): void {
const store = useInsightsStore.getState();
const session = store.session;
// Add user message to session
// Add user message to session (strip data to keep memory usage low)
const displayImages = images?.map(img => ({
...img,
data: undefined // Strip base64 data, keep thumbnails for display
}));
const userMessage: InsightsChatMessage = {
id: `msg-${Date.now()}`,
role: 'user',
content: message,
timestamp: new Date()
timestamp: new Date(),
...(displayImages && displayImages.length > 0 ? { images: displayImages } : {})
};
store.addMessage(userMessage);
// Clear pending and set status
store.setPendingMessage('');
store.setPendingImages([]);
store.clearStreamingContent();
store.clearToolsUsed(); // Clear tools from previous response
store.setStatus({
@@ -260,15 +281,15 @@ export function sendMessage(projectId: string, message: string, modelConfig?: In
const configToUse = modelConfig || session?.modelConfig;
// Send to main process
window.electronAPI.sendInsightsMessage(projectId, message, configToUse);
window.electronAPI.sendInsightsMessage(projectId, message, configToUse, images);
}
export async function clearSession(projectId: string): Promise<void> {
export async function clearSession(projectId: string, includeArchived?: boolean): Promise<void> {
const result = await window.electronAPI.clearInsightsSession(projectId);
if (result.success) {
useInsightsStore.getState().clearSession();
// Reload sessions list and current session
await loadInsightsSession(projectId);
await loadInsightsSession(projectId, includeArchived);
}
}
@@ -293,11 +314,11 @@ export async function switchSession(projectId: string, sessionId: string): Promi
}
}
export async function deleteSession(projectId: string, sessionId: string): Promise<boolean> {
export async function deleteSession(projectId: string, sessionId: string, includeArchived?: boolean): Promise<boolean> {
const result = await window.electronAPI.deleteInsightsSession(projectId, sessionId);
if (result.success) {
// Reload sessions list and current session
await loadInsightsSession(projectId);
await loadInsightsSession(projectId, includeArchived);
return true;
}
return false;
@@ -313,6 +334,32 @@ export async function renameSession(projectId: string, sessionId: string, newTit
return false;
}
export async function deleteSessions(projectId: string, sessionIds: string[]): Promise<{ success: boolean; failedIds?: string[] }> {
const result = await window.electronAPI.deleteInsightsSessions(projectId, sessionIds);
if (result.success) {
return { success: true, failedIds: result.data?.failedIds };
}
return { success: false, failedIds: result.data?.failedIds };
}
export async function archiveSession(projectId: string, sessionId: string): Promise<boolean> {
const result = await window.electronAPI.archiveInsightsSession(projectId, sessionId);
return result.success;
}
export async function archiveSessions(projectId: string, sessionIds: string[]): Promise<{ success: boolean; failedIds?: string[] }> {
const result = await window.electronAPI.archiveInsightsSessions(projectId, sessionIds);
if (result.success) {
return { success: true, failedIds: result.data?.failedIds };
}
return { success: false, failedIds: result.data?.failedIds };
}
export async function unarchiveSession(projectId: string, sessionId: string): Promise<boolean> {
const result = await window.electronAPI.unarchiveInsightsSession(projectId, sessionId);
return result.success;
}
export async function updateModelConfig(projectId: string, sessionId: string, modelConfig: InsightsModelConfig): Promise<boolean> {
const result = await window.electronAPI.updateInsightsModelConfig(projectId, sessionId, modelConfig);
if (result.success) {
@@ -1,6 +1,11 @@
/// <reference types="vite/client" />
import { create } from 'zustand';
import { createActor } from 'xstate';
import type { Actor } from 'xstate';
import type {
Competitor,
CompetitorAnalysis,
ManualCompetitorInput,
Roadmap,
RoadmapFeature,
RoadmapFeatureStatus,
@@ -8,6 +13,118 @@ import type {
TaskOutcome,
FeatureSource
} from '../../shared/types';
import {
roadmapGenerationMachine,
roadmapFeatureMachine,
mapGenerationStateToPhase,
mapFeatureStateToStatus,
type RoadmapGenerationEvent,
type RoadmapFeatureEvent
} from '@shared/state-machines';
// ---------------------------------------------------------------------------
// Module-level XState actor singletons
// ---------------------------------------------------------------------------
let generationActor: Actor<typeof roadmapGenerationMachine> | null = null;
const featureActors = new Map<string, Actor<typeof roadmapFeatureMachine>>();
/**
* Reset all actors to clean state.
* Use this in tests (afterEach) and HMR dispose handlers to avoid stale actors.
*/
export function resetActors(): void {
if (generationActor) {
generationActor.stop();
generationActor = null;
}
featureActors.forEach((actor) => actor.stop());
featureActors.clear();
}
/**
* Get or create the singleton generation actor.
* Optionally provide an initial state and context to restore from persisted data.
*/
function getOrCreateGenerationActor(
initialState?: RoadmapGenerationStatus['phase'],
initialContext?: Partial<{ progress: number; message: string; error: string; startedAt: number; completedAt: number; lastActivityAt: number }>
): Actor<typeof roadmapGenerationMachine> {
// Invalidate cached actor if its state doesn't match the expected value
if (generationActor && initialState) {
const currentValue = String(generationActor.getSnapshot().value);
if (currentValue !== initialState) {
generationActor.stop();
generationActor = null;
}
}
if (!generationActor) {
if (initialState) {
const resolvedSnapshot = roadmapGenerationMachine.resolveState({
value: initialState,
context: {
progress: initialContext?.progress ?? 0,
message: initialContext?.message,
error: initialContext?.error,
startedAt: initialContext?.startedAt,
completedAt: initialContext?.completedAt,
lastActivityAt: initialContext?.lastActivityAt
}
});
generationActor = createActor(roadmapGenerationMachine, { snapshot: resolvedSnapshot });
} else {
generationActor = createActor(roadmapGenerationMachine);
}
generationActor.start();
}
return generationActor;
}
/**
* Get or create a feature actor for a given feature ID.
* Optionally provide an initial state to restore from persisted data.
*/
function getOrCreateFeatureActor(
featureId: string,
initialState?: RoadmapFeatureStatus,
initialContext?: Partial<{ linkedSpecId: string; taskOutcome: TaskOutcome; previousStatus: RoadmapFeatureStatus }>
): Actor<typeof roadmapFeatureMachine> {
let actor = featureActors.get(featureId);
// Invalidate cached actor if its state or context doesn't match the expected values
if (actor && initialState) {
const snapshot = actor.getSnapshot();
const currentValue = String(snapshot.value);
const ctx = snapshot.context;
const contextMismatch = initialContext && (
ctx.taskOutcome !== (initialContext.taskOutcome ?? undefined) ||
ctx.previousStatus !== (initialContext.previousStatus ?? undefined) ||
ctx.linkedSpecId !== (initialContext.linkedSpecId ?? undefined)
);
if (currentValue !== initialState || contextMismatch) {
actor.stop();
featureActors.delete(featureId);
actor = undefined;
}
}
if (!actor) {
if (initialState) {
const resolvedSnapshot = roadmapFeatureMachine.resolveState({
value: initialState,
context: {
linkedSpecId: initialContext?.linkedSpecId ?? undefined,
taskOutcome: initialContext?.taskOutcome ?? undefined,
previousStatus: initialContext?.previousStatus ?? undefined
}
});
actor = createActor(roadmapFeatureMachine, { snapshot: resolvedSnapshot });
} else {
actor = createActor(roadmapFeatureMachine);
}
actor.start();
featureActors.set(featureId, actor);
}
return actor;
}
/**
* Migrate roadmap data to latest schema
@@ -68,6 +185,7 @@ interface RoadmapState {
reorderFeatures: (phaseId: string, featureIds: string[]) => void;
updateFeaturePhase: (featureId: string, newPhaseId: string) => void;
addFeature: (feature: Omit<RoadmapFeature, 'id'>) => string;
addCompetitor: (input: ManualCompetitorInput) => string;
}
const initialGenerationStatus: RoadmapGenerationStatus = {
@@ -76,6 +194,23 @@ const initialGenerationStatus: RoadmapGenerationStatus = {
message: ''
};
/**
* Derive RoadmapGenerationStatus from the generation actor's current snapshot.
*/
function deriveGenerationStatus(actor: Actor<typeof roadmapGenerationMachine>): RoadmapGenerationStatus {
const snapshot = actor.getSnapshot();
const phase = mapGenerationStateToPhase(String(snapshot.value));
const ctx = snapshot.context;
return {
phase,
progress: ctx.progress,
message: ctx.message ?? '',
error: ctx.error,
startedAt: ctx.startedAt ? new Date(ctx.startedAt) : undefined,
lastActivityAt: ctx.lastActivityAt ? new Date(ctx.lastActivityAt) : undefined
};
}
export const useRoadmapStore = create<RoadmapState>((set) => ({
// Initial state
roadmap: null,
@@ -84,93 +219,284 @@ export const useRoadmapStore = create<RoadmapState>((set) => ({
currentProjectId: null,
// Actions
setRoadmap: (roadmap) => set({ roadmap }),
setRoadmap: (roadmap) => {
// Prune stale actors: stop and remove actors for features not in the new roadmap
if (roadmap) {
const newFeatureIds = new Set(roadmap.features.map((f) => f.id));
for (const [featureId, actor] of featureActors.entries()) {
if (!newFeatureIds.has(featureId)) {
actor.stop();
featureActors.delete(featureId);
}
}
} else {
// No roadmap → cleanup all actors
featureActors.forEach((actor) => actor.stop());
featureActors.clear();
}
return set({ roadmap });
},
setCompetitorAnalysis: (analysis) => set({ competitorAnalysis: analysis }),
setGenerationStatus: (status) =>
set((state) => {
const now = new Date();
const isStartingGeneration =
state.generationStatus.phase === 'idle' && status.phase !== 'idle';
const isStoppingGeneration = status.phase === 'idle' || status.phase === 'complete' || status.phase === 'error';
setGenerationStatus: (status) => {
const actor = getOrCreateGenerationActor(
status.phase !== 'idle' ? status.phase : undefined,
status.phase !== 'idle' ? {
progress: status.progress,
message: status.message,
error: status.error,
startedAt: status.startedAt?.getTime(),
lastActivityAt: status.lastActivityAt?.getTime()
} : undefined
);
return {
generationStatus: {
...status,
// Set startedAt when transitioning from idle to active, but preserve passed timestamp if provided (for restoring persisted state)
startedAt: isStartingGeneration
? (status.startedAt ?? now)
: isStoppingGeneration
? undefined
: status.startedAt ?? state.generationStatus.startedAt,
// Update lastActivityAt on any status change, but preserve passed timestamp if provided (for restoring persisted state)
lastActivityAt: isStoppingGeneration ? undefined : (status.lastActivityAt ?? now)
// Map the incoming status phase to an XState event
let event: RoadmapGenerationEvent | null = null;
switch (status.phase) {
case 'analyzing': {
const currentState = String(actor.getSnapshot().value);
if (currentState === 'idle') {
event = { type: 'START_GENERATION' };
} else if (currentState === 'complete' || currentState === 'error') {
actor.send({ type: 'RESET' });
event = { type: 'START_GENERATION' };
}
};
}),
break;
}
case 'discovering': {
// NOTE: Backward transitions (e.g., generating→discovering) are intentionally
// unsupported. The generation pipeline is strictly forward-progressing, so XState
// will silently drop the event if the actor is already past this phase.
const cs = String(actor.getSnapshot().value);
if (cs === 'idle') {
actor.send({ type: 'START_GENERATION' });
} else if (cs === 'complete' || cs === 'error') {
actor.send({ type: 'RESET' });
actor.send({ type: 'START_GENERATION' });
}
event = { type: 'DISCOVERY_STARTED' };
break;
}
case 'generating': {
const cs = String(actor.getSnapshot().value);
if (cs === 'idle') {
actor.send({ type: 'START_GENERATION' });
actor.send({ type: 'DISCOVERY_STARTED' });
} else if (cs === 'analyzing') {
actor.send({ type: 'DISCOVERY_STARTED' });
} else if (cs === 'complete' || cs === 'error') {
actor.send({ type: 'RESET' });
actor.send({ type: 'START_GENERATION' });
actor.send({ type: 'DISCOVERY_STARTED' });
}
event = { type: 'GENERATION_STARTED' };
break;
}
case 'complete': {
const cs = String(actor.getSnapshot().value);
// Catch-up logic: advance actor to 'generating' state before sending GENERATION_COMPLETE
if (cs === 'idle') {
actor.send({ type: 'START_GENERATION' });
actor.send({ type: 'DISCOVERY_STARTED' });
actor.send({ type: 'GENERATION_STARTED' });
} else if (cs === 'analyzing') {
actor.send({ type: 'DISCOVERY_STARTED' });
actor.send({ type: 'GENERATION_STARTED' });
} else if (cs === 'discovering') {
actor.send({ type: 'GENERATION_STARTED' });
} else if (cs === 'error') {
actor.send({ type: 'RESET' });
actor.send({ type: 'START_GENERATION' });
actor.send({ type: 'DISCOVERY_STARTED' });
actor.send({ type: 'GENERATION_STARTED' });
}
event = { type: 'GENERATION_COMPLETE' };
break;
}
case 'error': {
const cs = String(actor.getSnapshot().value);
// Catch-up logic: GENERATION_ERROR is only handled in analyzing, discovering,
// and generating states. Advance from idle/complete so the event isn't dropped.
if (cs === 'idle') {
actor.send({ type: 'START_GENERATION' });
} else if (cs === 'complete' || cs === 'error') {
actor.send({ type: 'RESET' });
actor.send({ type: 'START_GENERATION' });
}
event = { type: 'GENERATION_ERROR', error: status.error ?? 'Unknown error' };
break;
}
case 'idle': {
// Stop or reset depending on current state
const currentState = String(actor.getSnapshot().value);
if (currentState === 'complete' || currentState === 'error') {
event = { type: 'RESET' };
} else if (currentState !== 'idle') {
event = { type: 'STOP' };
}
break;
}
}
if (event) {
actor.send(event);
}
// Send progress updates for active states
const currentState = String(actor.getSnapshot().value);
if (currentState === 'analyzing' || currentState === 'discovering' || currentState === 'generating') {
actor.send({ type: 'PROGRESS_UPDATE', progress: status.progress, message: status.message });
}
// Derive store state from the actor snapshot
set({ generationStatus: deriveGenerationStatus(actor) });
},
setCurrentProjectId: (projectId) => set({ currentProjectId: projectId }),
updateFeatureStatus: (featureId, status) =>
set((state) => {
if (!state.roadmap) return state;
updateFeatureStatus: (featureId, status) => {
// NOTE: getState() is called outside set() because XState actors are external
// side effects that cannot run inside Zustand's synchronous updater. The feature
// lookup and actor state restoration use this snapshot, with the actual state
// write deferred to the set() call below. This is intentional architecture.
const state = useRoadmapStore.getState();
if (!state.roadmap) return;
const updatedFeatures = state.roadmap.features.map((feature) =>
feature.id === featureId
? { ...feature, status, ...(status !== 'done' ? { taskOutcome: undefined, previousStatus: undefined } : {}) }
: feature
const feature = state.roadmap.features.find((f) => f.id === featureId);
if (!feature) return;
// Determine the XState event based on target status
const eventMap: Record<RoadmapFeatureStatus, RoadmapFeatureEvent> = {
planned: { type: 'PLAN' },
in_progress: { type: 'START_PROGRESS' },
done: { type: 'MARK_DONE' },
under_review: { type: 'MOVE_TO_REVIEW' }
};
const actor = getOrCreateFeatureActor(featureId, feature.status, {
linkedSpecId: feature.linkedSpecId,
taskOutcome: feature.taskOutcome,
previousStatus: feature.previousStatus
});
actor.send(eventMap[status]);
const snapshot = actor.getSnapshot();
const derivedStatus = mapFeatureStateToStatus(String(snapshot.value));
const ctx = snapshot.context;
// Skip store write if XState silently ignored the event (no-op transition)
if (derivedStatus === feature.status && ctx.taskOutcome === feature.taskOutcome && ctx.previousStatus === feature.previousStatus) return;
set((s) => {
if (!s.roadmap) return s;
const updatedFeatures = s.roadmap.features.map((f) =>
f.id === featureId
? {
...f,
status: derivedStatus,
taskOutcome: ctx.taskOutcome,
previousStatus: ctx.previousStatus
}
: f
);
return {
roadmap: {
...state.roadmap,
features: updatedFeatures,
updatedAt: new Date()
}
roadmap: { ...s.roadmap, features: updatedFeatures, updatedAt: new Date() }
};
}),
});
},
// Mark feature as done when its linked task completes
markFeatureDoneBySpecId: (specId: string, taskOutcome: TaskOutcome = 'completed') =>
set((state) => {
if (!state.roadmap) return state;
markFeatureDoneBySpecId: (specId: string, taskOutcome: TaskOutcome = 'completed') => {
const state = useRoadmapStore.getState();
if (!state.roadmap) return;
const updatedFeatures = state.roadmap.features.map((feature) =>
feature.linkedSpecId === specId
? { ...feature, status: 'done' as RoadmapFeatureStatus, taskOutcome, previousStatus: feature.status !== 'done' ? feature.status : feature.previousStatus }
: feature
);
// Determine the XState event based on task outcome
const outcomeEventMap: Record<TaskOutcome, RoadmapFeatureEvent> = {
completed: { type: 'TASK_COMPLETED' },
deleted: { type: 'TASK_DELETED' },
archived: { type: 'TASK_ARCHIVED' }
};
const event = outcomeEventMap[taskOutcome];
// Process actors outside set() — collect derived state per feature
const featureUpdates = new Map<string, { status: RoadmapFeatureStatus; taskOutcome?: TaskOutcome; previousStatus?: RoadmapFeatureStatus }>();
for (const feature of state.roadmap.features) {
if (feature.linkedSpecId !== specId) continue;
const actor = getOrCreateFeatureActor(feature.id, feature.status, {
linkedSpecId: feature.linkedSpecId,
taskOutcome: feature.taskOutcome,
previousStatus: feature.previousStatus
});
actor.send(event);
const snapshot = actor.getSnapshot();
const ctx = snapshot.context;
featureUpdates.set(feature.id, {
status: mapFeatureStateToStatus(String(snapshot.value)),
taskOutcome: ctx.taskOutcome,
previousStatus: ctx.previousStatus
});
}
if (featureUpdates.size === 0) return;
set((s) => {
if (!s.roadmap) return s;
const updatedFeatures = s.roadmap.features.map((f) => {
const update = featureUpdates.get(f.id);
return update ? { ...f, ...update } : f;
});
return {
roadmap: {
...state.roadmap,
features: updatedFeatures,
updatedAt: new Date()
}
roadmap: { ...s.roadmap, features: updatedFeatures, updatedAt: new Date() }
};
}),
});
},
updateFeatureLinkedSpec: (featureId, specId) =>
set((state) => {
if (!state.roadmap) return state;
updateFeatureLinkedSpec: (featureId, specId) => {
const state = useRoadmapStore.getState();
if (!state.roadmap) return;
const updatedFeatures = state.roadmap.features.map((feature) =>
feature.id === featureId
? { ...feature, linkedSpecId: specId, status: 'in_progress' as RoadmapFeatureStatus }
: feature
const feature = state.roadmap.features.find((f) => f.id === featureId);
if (!feature) return;
const actor = getOrCreateFeatureActor(featureId, feature.status, {
linkedSpecId: feature.linkedSpecId,
taskOutcome: feature.taskOutcome,
previousStatus: feature.previousStatus
});
actor.send({ type: 'LINK_SPEC', specId } satisfies RoadmapFeatureEvent);
const snapshot = actor.getSnapshot();
const derivedStatus = mapFeatureStateToStatus(String(snapshot.value));
const ctx = snapshot.context;
// Skip store write if nothing changed (same linkedSpecId and status)
if (ctx.linkedSpecId === feature.linkedSpecId && derivedStatus === feature.status) return;
set((s) => {
if (!s.roadmap) return s;
const updatedFeatures = s.roadmap.features.map((f) =>
f.id === featureId
? { ...f, linkedSpecId: ctx.linkedSpecId, status: derivedStatus }
: f
);
return {
roadmap: {
...state.roadmap,
features: updatedFeatures,
updatedAt: new Date()
}
roadmap: { ...s.roadmap, features: updatedFeatures, updatedAt: new Date() }
};
}),
});
},
deleteFeature: (featureId) => {
// Stop and remove the feature's actor outside set()
const actor = featureActors.get(featureId);
if (actor) {
actor.stop();
featureActors.delete(featureId);
}
deleteFeature: (featureId) =>
set((state) => {
if (!state.roadmap) return state;
@@ -185,15 +511,27 @@ export const useRoadmapStore = create<RoadmapState>((set) => ({
updatedAt: new Date()
}
};
}),
});
},
clearRoadmap: () =>
set({
clearRoadmap: () => {
// Stop all actors and clear Maps
if (generationActor) {
generationActor.stop();
generationActor = null;
}
featureActors.forEach((actor) => {
actor.stop();
});
featureActors.clear();
return set({
roadmap: null,
competitorAnalysis: null,
generationStatus: initialGenerationStatus,
currentProjectId: null
}),
});
},
// Reorder features within a phase
reorderFeatures: (phaseId, featureIds) =>
@@ -242,7 +580,7 @@ export const useRoadmapStore = create<RoadmapState>((set) => ({
// Add a new feature to the roadmap
addFeature: (featureData) => {
const newId = `feature-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
const newId = `feature-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
const newFeature: RoadmapFeature = {
...featureData,
id: newId
@@ -261,7 +599,62 @@ export const useRoadmapStore = create<RoadmapState>((set) => ({
});
return newId;
}
},
// Add a manual competitor to the competitor analysis
addCompetitor: (input) => {
const newId = `competitor-manual-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
const newCompetitor: Competitor = {
id: newId,
name: input.name,
url: input.url,
description: input.description,
relevance: input.relevance,
painPoints: [],
strengths: [],
marketPosition: '',
source: 'manual'
};
set((state) => {
const existing = state.competitorAnalysis;
if (existing) {
return {
competitorAnalysis: {
...existing,
competitors: [...existing.competitors, newCompetitor]
}
};
}
// Create a new CompetitorAnalysis with sensible defaults
return {
competitorAnalysis: {
projectContext: {
projectName: '',
projectType: '',
targetAudience: ''
},
competitors: [newCompetitor],
marketGaps: [],
insightsSummary: {
topPainPoints: [],
differentiatorOpportunities: [],
marketTrends: []
},
researchMetadata: {
searchQueriesUsed: [],
sourcesConsulted: [],
limitations: []
},
createdAt: new Date()
}
};
});
return newId;
},
}));
/**
@@ -291,24 +684,28 @@ async function reconcileLinkedFeatures(projectId: string, roadmap: Roadmap): Pro
let hasChanges = false;
for (const feature of featuresNeedingReconciliation) {
const task = taskMap.get(feature.linkedSpecId!);
// Safe: linkedSpecId is guaranteed to exist by the filter above
const linkedSpecId = feature.linkedSpecId;
if (!linkedSpecId) continue;
const task = taskMap.get(linkedSpecId);
if (!task) {
// Task no longer exists → mark as done with deleted outcome
if (feature.status !== 'done' || feature.taskOutcome !== 'deleted') {
store.markFeatureDoneBySpecId(feature.linkedSpecId!, 'deleted');
store.markFeatureDoneBySpecId(linkedSpecId, 'deleted');
hasChanges = true;
}
} else if (task.status === 'done' || task.status === 'pr_created') {
// Task is completed → mark feature as done
if (feature.status !== 'done' || !feature.taskOutcome) {
store.markFeatureDoneBySpecId(feature.linkedSpecId!, 'completed');
store.markFeatureDoneBySpecId(linkedSpecId, 'completed');
hasChanges = true;
}
} else if (task.metadata?.archivedAt) {
// Task is archived → mark feature as done with archived outcome
if (feature.status !== 'done' || feature.taskOutcome !== 'archived') {
store.markFeatureDoneBySpecId(feature.linkedSpecId!, 'archived');
store.markFeatureDoneBySpecId(linkedSpecId, 'archived');
hasChanges = true;
}
}
@@ -520,3 +917,10 @@ export function getFeatureStats(roadmap: Roadmap | null): {
byComplexity
};
}
// HMR cleanup: reset actors on hot module replacement
if (import.meta.hot) {
import.meta.hot.dispose(() => {
resetActors();
});
}
@@ -309,6 +309,10 @@ export const useTaskStore = create<TaskState>((set, get) => ({
// When starting a task and no phase is set yet, default to planning
// This prevents the "no active phase" UI state during startup race condition
executionProgress = { phase: 'planning' as ExecutionPhase, phaseProgress: 0, overallProgress: 0 };
} else if (['human_review', 'error', 'done', 'pr_created'].includes(status)) {
// Reset execution progress when task reaches terminal states
// This prevents stuck tasks from showing stale progress indicators
executionProgress = { phase: 'idle' as ExecutionPhase, phaseProgress: 0, overallProgress: 0 };
}
// Log status transitions to help diagnose flip-flop issues
@@ -792,7 +796,7 @@ export interface PersistStatusResult {
export async function persistTaskStatus(
taskId: string,
status: TaskStatus,
options?: { forceCleanup?: boolean }
options?: { forceCleanup?: boolean; keepWorktree?: boolean }
): Promise<PersistStatusResult> {
const store = useTaskStore.getState();
@@ -1,10 +1,50 @@
import { create } from 'zustand';
import { createActor } from 'xstate';
import type { ActorRefFrom } from 'xstate';
import { v4 as uuid } from 'uuid';
import { arrayMove } from '@dnd-kit/sortable';
import type { TerminalSession, TerminalWorktreeConfig } from '../../shared/types';
import { terminalMachine, type TerminalEvent } from '@shared/state-machines';
import { terminalBufferManager } from '../lib/terminal-buffer-manager';
import { debugLog, debugError } from '../../shared/utils/debug-logger';
type TerminalActor = ActorRefFrom<typeof terminalMachine>;
/**
* Module-level Map to store terminal ID -> XState actor mappings.
*
* DESIGN NOTE: Stored outside Zustand because actors are mutable references
* that shouldn't be serialized in state. Similar pattern to xtermCallbacks.
*/
const terminalActors = new Map<string, TerminalActor>();
/**
* Get or create an XState terminal actor for a given terminal ID.
* Actors are lazily created on first access and cached for the terminal's lifetime.
*/
export function getOrCreateTerminalActor(terminalId: string): TerminalActor {
let actor = terminalActors.get(terminalId);
if (!actor) {
actor = createActor(terminalMachine);
actor.start();
terminalActors.set(terminalId, actor);
debugLog(`[TerminalStore] Created XState actor for terminal: ${terminalId}`);
}
return actor;
}
/**
* Send an event to a terminal's XState machine.
* Creates the actor if it doesn't exist yet.
*/
export function sendTerminalMachineEvent(terminalId: string, event: TerminalEvent): void {
const actor = getOrCreateTerminalActor(terminalId);
const stateBefore = String(actor.getSnapshot().value);
actor.send(event);
const stateAfter = String(actor.getSnapshot().value);
debugLog(`[TerminalStore] Machine ${terminalId}: ${event.type} (${stateBefore} -> ${stateAfter})`);
}
/**
* Module-level Map to store terminal ID -> xterm write callback mappings.
*
@@ -301,9 +341,15 @@ export const useTerminalStore = create<TerminalState>((set, get) => ({
},
removeTerminal: (id: string) => {
// Clean up buffer manager and output callback
// Clean up buffer manager, output callback, and XState actor
terminalBufferManager.dispose(id);
xtermCallbacks.delete(id);
const actor = terminalActors.get(id);
if (actor) {
actor.stop();
terminalActors.delete(id);
debugLog(`[TerminalStore] Cleaned up XState actor for terminal: ${id}`);
}
set((state) => {
const newTerminals = state.terminals.filter((t) => t.id !== id);
@@ -331,6 +377,13 @@ export const useTerminalStore = create<TerminalState>((set, get) => ({
},
setTerminalStatus: (id: string, status: TerminalStatus) => {
// Notify XState machine of lifecycle transitions
if (status === 'running') {
sendTerminalMachineEvent(id, { type: 'SHELL_READY' });
} else if (status === 'exited') {
sendTerminalMachineEvent(id, { type: 'SHELL_EXITED' });
}
set((state) => ({
terminals: state.terminals.map((t) =>
t.id === id ? { ...t, status } : t
@@ -339,13 +392,32 @@ export const useTerminalStore = create<TerminalState>((set, get) => ({
},
setClaudeMode: (id: string, isClaudeMode: boolean) => {
// Send corresponding event to XState machine
if (isClaudeMode) {
// Ensure machine has transitioned past idle before sending CLAUDE_ACTIVE
const actor = getOrCreateTerminalActor(id);
if (String(actor.getSnapshot().value) === 'idle') {
sendTerminalMachineEvent(id, { type: 'SHELL_READY' });
}
// Include current claudeSessionId to prevent XState action from overwriting it
const terminal = get().terminals.find(t => t.id === id);
sendTerminalMachineEvent(id, { type: 'CLAUDE_ACTIVE', claudeSessionId: terminal?.claudeSessionId });
} else {
// Only send CLAUDE_EXITED if machine is in a state that accepts it
const actor = getOrCreateTerminalActor(id);
const currentState = String(actor.getSnapshot().value);
if (currentState === 'claude_starting' || currentState === 'claude_active') {
sendTerminalMachineEvent(id, { type: 'CLAUDE_EXITED' });
}
}
set((state) => ({
terminals: state.terminals.map((t) =>
t.id === id
? {
...t,
isClaudeMode,
status: isClaudeMode ? 'claude-active' : 'running',
status: isClaudeMode ? 'claude-active' : (t.status === 'exited' ? 'exited' : 'running'),
// Reset busy state and naming flag when leaving Claude mode
isClaudeBusy: isClaudeMode ? t.isClaudeBusy : undefined,
claudeNamedOnce: isClaudeMode ? t.claudeNamedOnce : undefined
@@ -356,6 +428,14 @@ export const useTerminalStore = create<TerminalState>((set, get) => ({
},
setClaudeSessionId: (id: string, sessionId: string) => {
// Ensure machine has transitioned past idle before sending CLAUDE_ACTIVE
const actor = getOrCreateTerminalActor(id);
if (String(actor.getSnapshot().value) === 'idle') {
sendTerminalMachineEvent(id, { type: 'SHELL_READY' });
}
// Send CLAUDE_ACTIVE with session ID to XState machine
sendTerminalMachineEvent(id, { type: 'CLAUDE_ACTIVE', claudeSessionId: sessionId });
set((state) => ({
terminals: state.terminals.map((t) =>
t.id === id ? { ...t, claudeSessionId: sessionId } : t
@@ -380,6 +460,9 @@ export const useTerminalStore = create<TerminalState>((set, get) => ({
},
setClaudeBusy: (id: string, isBusy: boolean) => {
// Send CLAUDE_BUSY event to XState machine
sendTerminalMachineEvent(id, { type: 'CLAUDE_BUSY', isBusy });
set((state) => ({
terminals: state.terminals.map((t) =>
t.id === id ? { ...t, isClaudeBusy: isBusy } : t
@@ -388,11 +471,37 @@ export const useTerminalStore = create<TerminalState>((set, get) => ({
},
setPendingClaudeResume: (id: string, pending: boolean) => {
set((state) => ({
terminals: state.terminals.map((t) =>
t.id === id ? { ...t, pendingClaudeResume: pending } : t
),
}));
// Send RESUME_REQUESTED or RESUME_COMPLETE to XState machine
let shouldUpdateZustand = true;
if (pending) {
const terminal = get().terminals.find(t => t.id === id);
if (terminal?.claudeSessionId) {
sendTerminalMachineEvent(id, { type: 'RESUME_REQUESTED', claudeSessionId: terminal.claudeSessionId });
} else {
// No claudeSessionId - can't send RESUME_REQUESTED, so don't set pendingClaudeResume
// to avoid XState/Zustand divergence (UI would show pending but machine wouldn't know)
debugLog('[terminal-store] setPendingClaudeResume: dropping request for terminal', id, '- no claudeSessionId');
shouldUpdateZustand = false;
}
} else {
// Resume cleared - either completed or cancelled
const actor = terminalActors.get(id);
if (actor && String(actor.getSnapshot().value) === 'pending_resume') {
// Include claudeSessionId to prevent XState action from overwriting it to undefined
const terminal = get().terminals.find(t => t.id === id);
sendTerminalMachineEvent(id, { type: 'RESUME_COMPLETE', claudeSessionId: terminal?.claudeSessionId });
}
}
// Only update Zustand state if XState was notified (prevents state divergence)
if (shouldUpdateZustand) {
set((state) => ({
terminals: state.terminals.map((t) =>
t.id === id ? { ...t, pendingClaudeResume: pending } : t
),
}));
}
},
setClaudeNamedOnce: (id: string, named: boolean) => {
@@ -404,6 +513,18 @@ export const useTerminalStore = create<TerminalState>((set, get) => ({
},
clearAllTerminals: () => {
// Clean up all resources for every terminal
const terminals = get().terminals;
for (const terminal of terminals) {
terminalBufferManager.dispose(terminal.id);
xtermCallbacks.delete(terminal.id);
}
// Clean up all XState actors
for (const [_id, actor] of terminalActors) {
actor.stop();
}
terminalActors.clear();
set({ terminals: [], activeTerminalId: null, hasRestoredSessions: false });
},
+6 -1
View File
@@ -67,7 +67,11 @@ export const DEFAULT_APP_SETTINGS = {
// Anonymous error reporting (Sentry) - enabled by default to help improve the app
sentryEnabled: true,
// Auto-name Claude terminals based on initial message (enabled by default)
autoNameClaudeTerminals: true
autoNameClaudeTerminals: true,
// GPU acceleration for terminal rendering
// Default to 'off' until WebGL stability is proven across all GPU drivers.
// Users can opt-in via Settings > Display > GPU Acceleration.
gpuAcceleration: 'off' as const
};
// ============================================
@@ -111,6 +115,7 @@ export const AUTO_BUILD_PATHS = {
ROADMAP_FILE: 'roadmap.json',
ROADMAP_DISCOVERY: 'roadmap_discovery.json',
COMPETITOR_ANALYSIS: 'competitor_analysis.json',
MANUAL_COMPETITORS: 'manual_competitors.json',
IDEATION_FILE: 'ideation.json',
IDEATION_CONTEXT: 'ideation_context.json',
PROJECT_INDEX: '.auto-claude/project_index.json',
@@ -185,6 +185,7 @@ export const IPC_CHANNELS = {
ROADMAP_STOP: 'roadmap:stop',
ROADMAP_UPDATE_FEATURE: 'roadmap:updateFeature',
ROADMAP_CONVERT_TO_SPEC: 'roadmap:convertToSpec',
COMPETITOR_ANALYSIS_SAVE: 'roadmap:competitorAnalysisSave',
// Roadmap events (main -> renderer)
ROADMAP_PROGRESS: 'roadmap:progress',
@@ -408,11 +409,13 @@ export const IPC_CHANNELS = {
GITHUB_PR_CHECK_MERGE_READINESS: 'github:pr:checkMergeReadiness',
GITHUB_PR_MARK_REVIEW_POSTED: 'github:pr:markReviewPosted',
GITHUB_PR_UPDATE_BRANCH: 'github:pr:updateBranch',
GITHUB_PR_NOTIFY_EXTERNAL_REVIEW_COMPLETE: 'github:pr:notifyExternalReviewComplete',
// GitHub PR Review events (main -> renderer)
GITHUB_PR_REVIEW_PROGRESS: 'github:pr:reviewProgress',
GITHUB_PR_REVIEW_COMPLETE: 'github:pr:reviewComplete',
GITHUB_PR_REVIEW_ERROR: 'github:pr:reviewError',
GITHUB_PR_REVIEW_STATE_CHANGE: 'github:pr:reviewStateChange',
GITHUB_PR_LOGS_UPDATED: 'github:pr:logsUpdated',
// GitHub PR Logs (for viewing AI review logs)
@@ -496,6 +499,10 @@ export const IPC_CHANNELS = {
INSIGHTS_NEW_SESSION: 'insights:newSession',
INSIGHTS_SWITCH_SESSION: 'insights:switchSession',
INSIGHTS_DELETE_SESSION: 'insights:deleteSession',
INSIGHTS_DELETE_SESSIONS: 'insights:deleteSessions',
INSIGHTS_ARCHIVE_SESSION: 'insights:archiveSession',
INSIGHTS_ARCHIVE_SESSIONS: 'insights:archiveSessions',
INSIGHTS_UNARCHIVE_SESSION: 'insights:unarchiveSession',
INSIGHTS_RENAME_SESSION: 'insights:renameSession',
INSIGHTS_UPDATE_MODEL_CONFIG: 'insights:updateModelConfig',
+3 -4
View File
@@ -233,15 +233,14 @@ export const ALLOWED_IMAGE_TYPES = [
'image/jpeg',
'image/jpg',
'image/gif',
'image/webp',
'image/svg+xml'
'image/webp'
] as const;
// Allowed image file extensions (for display)
export const ALLOWED_IMAGE_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'] as const;
export const ALLOWED_IMAGE_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.gif', '.webp'] as const;
// Human-readable allowed types for error messages
export const ALLOWED_IMAGE_TYPES_DISPLAY = 'PNG, JPEG, GIF, WebP, SVG';
export const ALLOWED_IMAGE_TYPES_DISPLAY = 'PNG, JPEG, GIF, WebP';
// Attachments directory name within spec folder
export const ATTACHMENTS_DIR = 'attachments';
@@ -1,4 +1,22 @@
{
"competitorAnalysis": {
"addCompetitor": "Add Competitor",
"manualBadge": "Manual",
"noCompetitorsYet": "No competitors added yet",
"addCompetitorToStart": "Add a competitor to get started",
"analysisResults": "Competitor Analysis Results",
"analysisDescription": "Analyzed {{count}} competitors to identify market gaps and opportunities",
"visit": "Visit",
"identifiedPainPoints": "Identified Pain Points ({{count}})",
"noPainPointsIdentified": "No pain points identified",
"source": "Source:",
"frequency": "Frequency:",
"opportunity": "Opportunity:",
"marketInsightsSummary": "Market Insights Summary",
"topPainPoints": "Top Pain Points:",
"differentiatorOpportunities": "Differentiator Opportunities:",
"marketTrends": "Market Trends:"
},
"projectTab": {
"settings": "Project settings",
"showArchived": "Show archived",
@@ -11,6 +29,7 @@
},
"accessibility": {
"deleteFeatureAriaLabel": "Delete feature",
"archiveFeatureAriaLabel": "Archive feature",
"closeFeatureDetailsAriaLabel": "Close feature details",
"regenerateRoadmapAriaLabel": "Regenerate Roadmap",
"repositoryOwnerAriaLabel": "Repository owner",
@@ -116,6 +135,7 @@
"selectAll": "Select All",
"clearSelection": "Clear Selection",
"deleteSelected": "Delete Selected",
"archiveSelected": "Archive Selected",
"selectedOfTotal": "{{selected}} of {{total}} selected"
},
"time": {
@@ -430,7 +450,46 @@
"suggestedTask": "Suggested Task",
"creating": "Creating...",
"taskCreated": "Task Created",
"createTask": "Create Task"
"createTask": "Create Task",
"chatHistory": "Chat History",
"archive": "Archive",
"unarchive": "Unarchive",
"archiveSelected": "Archive Selected",
"showArchived": "Show Archived",
"hideArchived": "Hide Archived",
"bulkDeleteTitle": "Delete Conversations",
"bulkDeleteDescription": "Are you sure you want to delete {{count}} conversation(s)? This action cannot be undone.",
"bulkDeleteConfirm": "Delete {{count}} Conversation(s)",
"noConversations": "No conversations",
"archived": "Archived",
"conversationsToDelete": "Conversations to delete",
"archiveConfirmDescription": "Are you sure you want to archive the selected conversations?",
"archiveConfirmTitle": "Archive Conversations",
"archiveConfirmButton": "Archive {{count}} Conversation(s)",
"deleteTitle": "Delete Conversation",
"deleteDescription": "Are you sure you want to delete this conversation? This action cannot be undone.",
"selectMode": "Select",
"exitSelectMode": "Done",
"today": "Today",
"yesterday": "Yesterday",
"daysAgo": "{{count}} days ago",
"messageCount": "{{count}} message",
"messageCount_other": "{{count}} messages",
"images": {
"pasteHint": "Paste an image or screenshot",
"dropHint": "Drop image here",
"screenshotButton": "Attach screenshot",
"removeImage": "Remove image",
"imageCount": "{{count}} image attached",
"imageCount_plural": "{{count}} images attached",
"maxImagesReached": "Maximum number of images reached",
"invalidType": "Invalid file type. Please use PNG, JPEG, GIF, or WebP.",
"processFailed": "Failed to process image",
"dragOver": "Drop image to attach",
"analysisUnsupported": "Note: Image analysis is not yet supported. Images are stored for reference but cannot be analyzed by the model.",
"screenshotTooLarge": "Screenshot is too large ({{size}}MB). Maximum size is {{max}}MB. Consider capturing a smaller area.",
"notAnalyzed": "Images were stored for reference but not analyzed by the model."
}
},
"ideation": {
"converting": "Converting...",
@@ -607,7 +666,15 @@
"taskArchived": "Archived",
"showMoreFeatures": "Show {{count}} more feature",
"showMoreFeatures_plural": "Show {{count}} more features",
"showLessFeatures": "Show less"
"showLessFeatures": "Show less",
"archiveFeature": "Archive",
"archiveFeatureConfirmTitle": "Archive Feature?",
"archiveFeatureConfirmDescription": "This will remove \"{{title}}\" from your roadmap.",
"goToTask": "Go to Task",
"convertToTask": "Convert to Auto-Build Task",
"build": "Build",
"task": "Task",
"viewTask": "View Task"
},
"roadmapGeneration": {
"progress": "Progress",
@@ -166,6 +166,60 @@
"readOnlyVolumeTitle": "Cannot install from disk image",
"readOnlyVolumeDescription": "Please move Auto Claude to your Applications folder before updating."
},
"addCompetitor": {
"title": "Add Competitor",
"description": "Add a known competitor to your analysis...",
"competitorName": "Competitor Name",
"competitorNamePlaceholder": "e.g. Slack, Notion, Figma",
"competitorUrl": "Website URL",
"competitorUrlPlaceholder": "e.g. https://example.com",
"competitorDescription": "Description",
"competitorDescriptionPlaceholder": "Brief description of what this competitor does...",
"relevance": "Relevance",
"selectRelevance": "Select relevance",
"highRelevance": "High - Direct competitor",
"mediumRelevance": "Medium - Partial overlap",
"lowRelevance": "Low - Tangential",
"nameRequired": "Competitor name is required",
"urlRequired": "Website URL is required",
"invalidUrl": "Please enter a valid URL",
"optional": "optional",
"cancel": "Cancel",
"adding": "Adding...",
"addCompetitor": "Add Competitor",
"failedToAdd": "Failed to add competitor"
},
"competitorAnalysis": {
"title": "Enable Competitor Analysis?",
"description": "Enhance your roadmap with insights from competitor products",
"whatItDoes": "What competitor analysis does:",
"identifiesCompetitors": "Identifies 3-5 main competitors based on your project type",
"searchesAppStores": "Searches app stores, forums, and social media for user feedback and pain points",
"suggestsFeatures": "Suggests features that address gaps in competitor products",
"webSearchesTitle": "Web searches will be performed",
"webSearchesDescription": "This feature will perform web searches to gather competitor information. Your project name and type will be used in search queries. No code or sensitive data is shared.",
"optionalInfo": "You can generate a roadmap without competitor analysis if you prefer. The roadmap will still be based on your project structure and best practices.",
"skipAnalysis": "No, Skip Analysis",
"enableAnalysis": "Yes, Enable Analysis",
"knowYourCompetitors": "Already know your competitors?",
"addThemDirectly": "Add them directly to improve analysis accuracy",
"addKnownCompetitors": "Add Known Competitors",
"addKnownCompetitorsDescription": "Manually add competitors you already know about to the existing analysis.",
"competitorsAdded": "{{count}} added"
},
"existingCompetitorAnalysis": {
"title": "Competitor Analysis Options",
"description": "This project has an existing competitor analysis from {{date}}",
"recently": "recently",
"useExistingTitle": "Use existing analysis",
"recommended": "(Recommended)",
"useExistingDescription": "Reuse the competitor insights you already have. Faster and no additional web searches.",
"runNewTitle": "Run new analysis",
"runNewDescription": "Perform fresh web searches to get updated competitor information. Takes longer.",
"skipTitle": "Skip competitor analysis",
"skipDescription": "Generate roadmap without any competitor insights.",
"cancel": "Cancel"
},
"versionWarning": {
"title": "Action Required",
"subtitle": "Version 2.7.5 Update",
@@ -192,6 +192,14 @@
"chronological": "Chronological (oldest first)",
"reverseChronological": "Reverse-chronological (newest first)"
},
"gpuAcceleration": {
"label": "GPU Acceleration",
"description": "Use WebGL for terminal rendering (experimental, faster with many terminals)",
"auto": "Auto (use WebGL when supported)",
"on": "Always on",
"off": "Off (default)",
"helperText": "Changes apply to new terminals only"
},
"general": {
"otherAgentSettings": "Other Agent Settings",
"otherAgentSettingsDescription": "Additional agent configuration options",

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