merge: resolve state-machines/index.ts conflict - keep both terminal and roadmap exports
This commit is contained in:
+231
@@ -1,3 +1,234 @@
|
||||
## 2.7.6 - Stability & Feature Enhancements
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
- **Multi-profile account management** — Unified profile swapping with automatic token refresh and rate limit recovery for both OAuth and API-compatible providers
|
||||
|
||||
- **Enhanced terminal experience** — Customizable terminal fonts with OS-specific defaults, Claude Code CLI settings injection, and improved worktree integration
|
||||
|
||||
- **Advanced roadmap management** — Expand/collapse functionality for phase features and real-time sync with task lifecycle
|
||||
|
||||
- **Queue System v2** — Smart task prioritization with auto-promotion and intelligent rate limit recovery
|
||||
|
||||
- **GitHub integration enhancements** — AI-powered PR template generation, user-friendly API error handling, and improved review visibility
|
||||
|
||||
- **UI/UX improvements** — Spell check support for text inputs, collapsible sidebar toggle, task screenshot capture, expandable task descriptions, and bulk worktree operations
|
||||
|
||||
- **Evidence-based PR validation** — Advanced review system with trigger-driven exploration and enhanced recovery mechanisms
|
||||
|
||||
### 🛠️ Improvements
|
||||
|
||||
- **Performance optimizations** — Async parallel worktree listing prevents UI freezes and improves responsiveness
|
||||
|
||||
- **Robustness enhancements** — Atomic file writes, better error detection in AI responses, and improved OOM/orphaned agent management for overnight builds
|
||||
|
||||
- **Terminal stability** — Fixed GPU context exhaustion from large pastes, SIGABRT crashes on macOS shutdown, and session restoration on app restart
|
||||
|
||||
- **Build & packaging** — XState bundling for packaged apps, aligned Linux package builds, and improved auto-updater for beta releases and DMG installations
|
||||
|
||||
- **Diagnostic improvements** — Sentry instrumentation for Python subprocesses and better error tracking across the system
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
- **Terminal & PTY** — Fixed paste size limits, race conditions, rendering issues, text alignment, worktree crashes, and terminal content resizing on expansion
|
||||
|
||||
- **PR review system** — Resolved error visibility in bundled apps, improved structured output validation with three-tier recovery, preserved findings during crashes, and fixed UTC timestamp detection for comment tracking
|
||||
|
||||
- **Planning & task execution** — Fixed handling of empty/greenfield projects, atomic writes to prevent 0-byte file corruption, planning phase crashes, and implementation plan file watching
|
||||
|
||||
- **Authentication & profiles** — Resolved OAuth token revocation loops, API profile mode support without OAuth requirement, subscription type preservation during token refresh, and Linux credential file detection
|
||||
|
||||
- **Windows/cross-platform** — Complete System32 executable path fixes for where.exe and taskkill.exe, Windows credential normalization, and proper shell detection for Windows terminals
|
||||
|
||||
- **Agent management** — Fixed infinite retry loops for tool concurrency errors, auth error detection, and title generator production path resolution
|
||||
|
||||
- **UI/UX fixes** — Resolved Insights scroll-to-blank-space issues, infinite re-render loops in terminal font settings, kanban board scaling collisions, ideation stuck states, and panel constraint errors during terminal exit
|
||||
|
||||
- **Worktree & Git** — Improved branch pattern validation, removed auto-commit on deletion, support for detached HEAD state during PR creation, and better merge conflict resolution with progress tracking
|
||||
|
||||
- **Integrations** — Fixed Ollama infinite subprocess spawning, Graphiti import paths, OpenRouter API URL suffix, and GitLab authentication bugs
|
||||
|
||||
- **Settings & configuration** — Corrected .auto-claude path discovery timeout, z.AI China preset URL, log order sorting, and onboarding completion state persistence
|
||||
|
||||
### 📚 Documentation
|
||||
|
||||
- Added Awesome Claude Code badge to README
|
||||
|
||||
- Added instructions for resetting PR review state in CLAUDE.md
|
||||
|
||||
---
|
||||
|
||||
## What's Changed
|
||||
|
||||
- fix: handle unknown SDK message types (rate_limit_event) to prevent session crashes by @AndyMik90 in 4a75ea9f9
|
||||
- fix: PR review error visibility and gh CLI resolution in bundled apps by @AndyMik90 in 732fc1cd3
|
||||
- fix: handle empty/greenfield projects in spec creation (#1426) (#1841) by @Andy in 819f98d9f
|
||||
- fix: clear terminalEventSeen on task restart to prevent stuck-after-planning (#1828) (#1840) by @Andy in 28a620079
|
||||
- fix: watch worktree path for implementation_plan.json changes (#1805) (#1842) by @Andy in fb3a3fbda
|
||||
- fix: resolve Claude CLI not found on Windows - PATH, prompt size, cwd (#1661) (#1843) by @Andy in 76d1d3b03
|
||||
- fix: handle planning phase crash and resume recovery (#1562) (#1844) by @Andy in 3cb05781f
|
||||
- fix: show dismissed PR review findings in UI instead of silently dropping them (#1852) by @Andy in d98ff7d19
|
||||
- fix: preserve file/line info in PR review extraction recovery (#1857) by @Andy in 635b53eea
|
||||
- docs: add Awesome Claude Code badge to README (#1838) by @Andy in 2e4b5ac65
|
||||
- test: achieve 100% test coverage for backend CLI commands (#1772) by @StillKnotKnown in 385f04414
|
||||
- fix: cap terminal paste size to 1MB to prevent GPU context exhaustion by @AndyMik90 in 7b0f3a2c0
|
||||
- fix: prevent OOM, orphaned agents, and unbounded growth during overnight builds (#1813) by @Andy in 4091d1d4b
|
||||
- docs: add instructions for resetting PR review state in CLAUDE.md by @AndyMik90 in ecb615802
|
||||
- auto-claude: 217-investigate-symlink-issues-in-work-tree-creation-f (#1808) by @Andy in ae13ce14c
|
||||
- auto-claude: 218-enable-claude-code-features-in-worktree-terminals (#1809) by @Andy in e3b219288
|
||||
- auto-claude: 219-investigate-and-fix-authentication-subscription-sy (#1810) by @Andy in 6204d5fc2
|
||||
- feat(roadmap): add expand/collapse functionality for phase features (#1796) by @Burak in f735f0b49
|
||||
- auto-claude: 216-display-ongoing-pr-review-logs-in-progress (#1807) by @Andy in a4870fa0c
|
||||
- fix(pr-review): reduce structured output failures and preserve findings in recovery (#1806) by @Andy in f1b8cd3a7
|
||||
- fix(sentry): enable Sentry for Python subprocesses and add diagnostic instrumentation (#1804) by @Andy in 4d4234378
|
||||
- fix(pr-review): add three-tier recovery for structured output validation failure (#1797) by @Andy in d1fbccde3
|
||||
- test: improve backend agent test coverage to 94% (#1779) by @StillKnotKnown in ed93df698
|
||||
- fix(github): use UTC timestamps for reviewed_at to fix comment detection (#1795) by @Andy in 8872d33e3
|
||||
- feat: add user-friendly GitHub API error handling (#1790) by @StillKnotKnown in 8ece0009e
|
||||
- fix(roadmap): sync roadmap features with task lifecycle (#1791) by @Andy in 115576e85
|
||||
- fix(github): resolve PR review hanging in bundled app (#1793) by @Andy in 3791b37bb
|
||||
- feat(profiles): implement unified profile swapping across OAuth and API accounts (#1794) by @StillKnotKnown in 282387356
|
||||
- test: improve backend memory system test coverage to 100% (#1780) by @StillKnotKnown in 4f1b7b2a9
|
||||
- fix(ideation): guard against non-string properties in IdeaCard badges by @AndyMik90 in 5e78d748e
|
||||
- fix(updater): convert HTML release notes to markdown before rendering by @AndyMik90 in aa5fc7f95
|
||||
- fix(pr-review): simplify structured output schema to reduce validation failures (#1787) by @Andy in cd8914700
|
||||
- fix(qa): enforce visual verification for UI changes and inject startup commands (#1784) by @Andy in f149a7fbd
|
||||
- fix(plan-files): use atomic writes to prevent 0-byte corruption (#1785) by @Andy in c2245b812
|
||||
- fix(terminal): make worktree dropdown scrollable and show all items by @AndyMik90 in 950da45e4
|
||||
- auto-claude: subtask-1-1 - Add adaptive thinking badge to thinking level label (#1782) by @Andy in 25acf2826
|
||||
- auto-claude: subtask-1-1 - Add overflow-hidden and break-words to subtask cards by @AndyMik90 in 39aa08872
|
||||
- refactor(app-updater): disable automatic downloads and allow intentional downgrades by @AndyMik90 in 8de8039db
|
||||
- fix(auth): detect auth errors in AI response text and prevent retry loops (#1776) by @Andy in f4788e4af
|
||||
- test: achieve 100% coverage for backend core workspace module (#1774) by @StillKnotKnown in 3f95765cf
|
||||
- fix(title-generator): add production path resolution for backend source (#1778) by @Andy in 923880f5b
|
||||
- fix(fast-mode): use setting_sources instead of env var for CLI fast mode (#1771) by @Andy in 390ba6a58
|
||||
- fix(windows): complete System32 executable path fixes for where.exe and taskkill.exe (#1715) by @VDT-91 in aa7f56e5d
|
||||
- fix(worktree): remove auto-commit on deletion and add uncommitted changes warning by @AndyMik90 in cec8e65ee
|
||||
- Smart PR Status Polling System (#1766) by @Andy in 48d5f7a32
|
||||
- feat: simplify thinking system and remove opus-1m model variant (#1760) by @Andy in bb7e18937
|
||||
- auto-claude: 203-fix-pr-review-ui-update-issue (#1732) by @Andy in 7589f8e4f
|
||||
- auto-claude: subtask-2-1 - Create isAPIProfileAuthenticated() function to val (#1745) by @Andy in 57e38a692
|
||||
- auto-claude: 202-fix-kanban-board-scaling-collisions (#1731) by @Andy in d09ebb850
|
||||
- auto-claude: 204-fix-pr-review-ui-not-updating-without-manual-navig (#1734) by @Andy in 087091cef
|
||||
- auto-claude: 203-fix-ui-not-updating-during-pr-review-operations (#1733) by @Andy in f085c08bd
|
||||
- auto-claude: 205-fix-insights-chat-only-shows-last-task-suggestion- (#1735) by @Andy in f121f9cdd
|
||||
- auto-claude: 197-roadmap-generation-stuck-at-50-file-locking-race-c (#1746) by @Andy in f41f15e59
|
||||
- auto-claude: 193-fix-update-context7-mcp-tool-name-from-get-library (#1744) by @Andy in bdff9141a
|
||||
- auto-claude: 192-changelog-generation-multiple-critical-bugs-tasks- (#1725) by @Andy in 8c9a504df
|
||||
- auto-claude: 194-bug-rate-limit-during-task-execution-causes-subtas (#1726) by @Andy in 8a7443d24
|
||||
- auto-claude: 201-bug-pr-review-logs-and-analysis (#1730) by @Andy in e0d53adb4
|
||||
- auto-claude: 196-fix-worktrees-dialog-auto-close-race-condition-and (#1727) by @Andy in 323b0d3be
|
||||
- auto-claude: 199-bug-logs-disappear-after-restart (#1728) by @Andy in d639f6ef8
|
||||
- auto-claude: 198-critical-oauth-token-revocation-causes-infinite-40 (#1747) by @Andy in 4438c0b10
|
||||
- Fix Panel Constraints Error During Terminal Exit (#1757) by @Andy in 32bf353da
|
||||
- auto-claude: 190-bug-context-page-crash-multiple-root-causes-when-v (#1724) by @Andy in 2db36982f
|
||||
- feat: add search/filter to WorktreeSelector dropdown (#1754) by @Andy in 09f059ca3
|
||||
- fix(terminal): push worktree branch to remote with tracking on creation (#1753) by @Andy in b5de0d9ff
|
||||
- auto-claude: 189-subtask-execution-stuck-in-infinite-retry-loop-whe (#1723) by @Andy in 445da186c
|
||||
- auto-claude: 188-terminal-claude-sessions-require-manual-click-to-r (#1743) by @Andy in f8499e965
|
||||
- auto-claude: 200-bug-changelog-and-release-generation (#1729) by @Andy in 826583b82
|
||||
- fix(terminal): use each terminal's cwd for invoke Claude all button (#1756) by @Andy in ac4fe4f42
|
||||
- feat(terminal): read Claude Code CLI settings and inject env vars into PTY sessions (#1750) by @Andy in 152e54093
|
||||
- fix: correct .auto-claude path mismatch causing discovery phase timeout (#1748) by @VDT-91 in 2c2a8a754
|
||||
- fix: remove incorrect /v1 suffix from OpenRouter API URL (#1749) by @StillKnotKnown in 7e799ee57
|
||||
- fix: prevent terminal worktree crash with race condition fixes (#1586) (#1658) by @VDT-91 in 216b58bcf
|
||||
- fix: correct log order sorting and add configurable log order setting (#1720) by @Burak in 2e2b82365
|
||||
- fix(ollama): stop infinite subprocess spawning from useEffect re-render loop (#1716) by @Quentin Veys in acb131b72
|
||||
- fix(graphiti): migrate graphiti_memory imports to canonical paths (#1714) by @Quentin Veys in df528f065
|
||||
- fix: improve auto-updater for beta releases and DMG installs (#1681) by @Andy in ff91a1af0
|
||||
- feat: unified operation registry for intelligent auth/rate limit recovery (#1698) by @Andy in 6d0222fa9
|
||||
- fix: Prevent stale worktree data from overriding correct task status (#1710) by @Burak in fe08c644c
|
||||
- feat: add subscriptionType and rateLimitTier to ClaudeProfile (#1688) by @Andy in a5e3cc9a2
|
||||
- auto-claude: subtask-1-1 - Add useTaskStore import and update task state after successful PR creation (#1683) by @Andy in 4587162e4
|
||||
- auto-claude: 182-implement-pagination-and-filtering-for-github-pr-l (#1654) by @Andy in b4e6b2fe4
|
||||
- auto-claude: 181-add-expand-button-for-long-task-descriptions (#1653) by @Andy in d9cd300fe
|
||||
- fix(terminal): resolve text alignment issues on expand/minimize (#1650) by @VDT-91 in f5a7e26d9
|
||||
- fix(windows): use full path to where.exe for reliable executable lookup (#1659) by @VDT-91 in 5f63daa3c
|
||||
- fix: resolve ideation stuck at 3/6 types bug (#1660) by @VDT-91 in e6e8da17c
|
||||
- Clarify Local and Origin Branch Distinction (#1652) by @Andy in 9317148b6
|
||||
- auto-claude: 186-set-default-dark-mode-on-startup (#1656) by @Andy in 473020621
|
||||
- auto-claude: subtask-1-1 - Add min-h-0 to enable scrolling in Roadmap tabs (#1655) by @Andy in ae703be9f
|
||||
- fix: XState status lifecycle & cross-project contamination fixes (#1647) by @kaigler in 5293fb399
|
||||
- refactor(frontend): complete XState task state machine migration (#1338) (#1575) by @kaigler in e2f9abadb
|
||||
- Merge conflict resolution progress bar and log viewer (#1620) by @Andy in d16be3077
|
||||
- fix: align Linux package builds (AppImage/deb/Flatpak) with target-specific extraResources (#1623) by @StillKnotKnown in bad1a9b2c
|
||||
- Fix/gitlab bugs (#1519 and #1521) (#1544) by @bu5hm4nn in cd423c65c
|
||||
- feat(kanban): add bulk task delete and worktree cleanup improvements (#1588) by @kaigler in 02ed91c91
|
||||
- fix: add worktree isolation warning to prevent agent escape (#1528) by @kaigler in fe5cc582b
|
||||
- feat(ui): add spell check support for text inputs (#1304) by @kaigler in 8f02a5129
|
||||
- fix(windows): complete Windows credential fixes with path normalization (#1585) by @kaigler in 1e1997167
|
||||
- AI-Powered GitHub PR Template Generation (#1618) by @Andy in 900dd4360
|
||||
- Fix pty.node SIGABRT crash on macOS shutdown (#1619) by @Andy in f355e09d7
|
||||
- fix(merge): use git merge for diverged branches with progress tracking (#1605) by @Andy in bde2ca4b2
|
||||
- Surface Billing/Credit Exhaustion Errors to UI (Issue #1580) (#1617) by @Andy in 7bf12e856
|
||||
- auto-claude: subtask-1-1 - Change $teamId type from ID! to String! in the team query (#1627) by @Andy in 54d0cd2f4
|
||||
- fix(auth): support API profile mode without OAuth requirement (#1616) by @StillKnotKnown in f8cc63af4
|
||||
- fix: agent retry loop for tool concurrency errors (#1546) [v3] (#1606) by @Michael Ludlow in 0aea4fb5e
|
||||
- fix(queue): enforce max parallel tasks and auto-refresh UI (#1594) by @Andy in 4070a4c29
|
||||
- Persist Kanban column collapse state per project via main process (#1579) by @Andy in a1114664e
|
||||
- feat(pr-review): evidence-based validation and trigger-driven exploration (#1593) by @Andy in bfc232825
|
||||
- fix(ui): smart auto-scroll for Insights streaming responses (#1591) by @kaigler in eee97e7ea
|
||||
- fix(changelog): validate Claude CLI exists before generation (#1305) by @kaigler in c1f24c07f
|
||||
- auto-claude: subtask-1-1 - Add min-w-0 class to subtask title row flex container (#1578) by @Andy in 286591c02
|
||||
- auto-claude: subtask-1-1 - Remove Popover wrapper and related functionality from ClaudeCodeStatusBadge (#1566) by @Andy in 8d18cc81a
|
||||
- fix(claude-profile): preserve subscriptionType and rateLimitTier during token refresh (#1556) by @Andy in 52e426a48
|
||||
- auto-claude: subtask-1-1 - Update cancelReview callback to handle both success and failure cases (#1551) by @Andy in d8f00fe5a
|
||||
- fix(backend): prioritize git remote detection over env var for repo (#1555) by @Andy in 9b07ed464
|
||||
- fix(backend): handle detached HEAD state when pushing branch for PR creation (#1560) by @Andy in 2b72694d0
|
||||
- fix: add explicit UTF-8 encoding across all Electron main process I/O (#1554) by @Andy in 4243530e9
|
||||
- fix(backend): pass OAuth token to Python subprocess for authentication by @AndyMik90 in 6f1002dd7
|
||||
- perf(frontend): async parallel worktree listing to prevent UI freezes (#1553) by @Andy in 399a7e736
|
||||
- auto-claude: subtask-1-1 - Remove amber lock indicator line from kanban resize handle (#1557) by @Andy in 83a64b88e
|
||||
- fix(frontend): resolve TerminalFontSettings infinite re-render loop (#1536) by @StillKnotKnown in 1c6266025
|
||||
- fix(frontend): respect hasCompletedOnboarding from ~/.claude.json (#1537) by @StillKnotKnown in 1860c2c43
|
||||
- fix: prevent planner from generating invalid verification types (#1388) (#1529) by @kaigler in 94d941333
|
||||
- fix(frontend): resolve Insights scroll-to-blank-space issue on macOS (ACS-382) (#1535) by @StillKnotKnown in 496b2b96a
|
||||
- feat: add customizable terminal fonts with OS-specific defaults (#1412) by @StillKnotKnown in f289107b8
|
||||
- Add dev mode screenshot capture warning (#1516) by @Andy in 16eeb301a
|
||||
- fix: add worktree isolation warnings to prevent agent escape (ACS-394) (#1495) by @StillKnotKnown in 1e453653b
|
||||
- fix: resolve flaky subprocess-spawn test on Windows CI (ACS-392) (#1494) by @StillKnotKnown in f6b264d56
|
||||
- feat(task-logger): strip ANSI escape codes from logs and extend coverage (#1411) by @StillKnotKnown in 988ec0c25
|
||||
- fix(frontend): use spawn() instead of exec() for Windows terminal launching (#1498) by @StillKnotKnown in 26c9083d3
|
||||
- fix(api-profiles): correct z.AI China preset URL and rename provider presets (#1500) by @StillKnotKnown in 05cf0a516
|
||||
- fix: validate branch pattern before worktree cleanup to prevent deleting wrong branch (#1493) by @StillKnotKnown in 8576754a1
|
||||
- Real-Time Updates for Insights Chat (#1511) by @Andy in d940b6ade
|
||||
- Fix Terminal UI Rendering Issues (#1514) by @Andy in 8d8306b8e
|
||||
- Fix terminal content resizing on expansion (#1512) by @Andy in 9f6c0026b
|
||||
- Restore Terminal Session History on App Restart (#1515) by @Andy in 63e2847fc
|
||||
- Move Reference Images Above Task Title & Fix Image Display Issues (#1513) by @Andy in b269ac305
|
||||
- auto-claude: 143-fix-github-integration-ui-refresh-issues (#1467) by @Andy in aa2cb4fa6
|
||||
- feat: Multi-profile account swapping with token refresh and queue routing (#1496) by @Andy in 1e72c8d77
|
||||
- Simplified Testing Strategy for Regression Prevention (#1379) by @Andy in ae4e48e8b
|
||||
- auto-claude: 152-persist-tasks-during-roadmap-regeneration (#1463) by @Andy in 9bd3d7e3b
|
||||
- Debug Kanban Memory & Add Sentry Monitoring (#1380) by @Andy in bc5f550ee
|
||||
- auto-claude: 147-remove-outdated-compatibility-shims (#1465) by @Andy in 53111dbb9
|
||||
- auto-claude: 162-fix-worktree-error-on-repeated-task-starts (#1453) by @Andy in b955badf7
|
||||
- auto-claude: 155-fix-pr-list-diff-display-metrics (#1458) by @Andy in 31f116db5
|
||||
- auto-claude: 151-fix-pr-review-agent-token-refresh-on-account-swap (#1456) by @Andy in d081af042
|
||||
- auto-claude: 148-add-progress-persistence-and-status-indicators (#1464) by @Andy in 4937d5745
|
||||
- auto-claude: 154-fix-task-modal-conflict-check-status-refresh (#1462) by @Andy in 0299009df
|
||||
- auto-claude: 153-widen-kanban-columns-and-add-collapse-feature (#1457) by @Andy in d65973075
|
||||
- auto-claude: subtask-1-1 - Add filter after map operation to remove empty str (#1466) by @Andy in 783f0fe0e
|
||||
- fix: add formatReleaseNotes helper for markdown changelog rendering (#1468) by @Andy in 43a97e1b3
|
||||
- feat(sidebar): add collapsible sidebar toggle (#1501) by @Michael Ludlow in d17c17887
|
||||
- fix(auth): check .credentials.json for Linux profile authentication (#1492) by @StillKnotKnown in 8d2f66291
|
||||
- auto-claude: subtask-1-1 - Replace ReleaseNotesRenderer with ReactMarkdown (#1454) by @Andy in 1185a558c
|
||||
- auto-claude: 156-fix-electron-app-version-detection-bug (#1459) by @Andy in 9a3b48c25
|
||||
- auto-claude: subtask-1-1 - Add --no-track flag to git worktree add command (#1455) by @Andy in 0c2990815
|
||||
- auto-claude: subtask-1-1 - Change task.specId to taskId in 3 startSpecCreation calls (#1461) by @Andy in 91edc0e14
|
||||
- fix(onboarding): align MemoryStep layout with Settings MemoryBackendSection (#1445) by @Michael Ludlow in e9de26d59
|
||||
- auto-claude: subtask-1-1 - Add metadata?.requireReviewBeforeCoding check (#1460) by @Andy in 426d56571
|
||||
- fix: use API profile environment variables for task title generation (#1471) by @JoshuaRileyDev in c5a0f042d
|
||||
- fix(auth): Long-lived OAuth authentication with multi-profile usage display (#1443) by @Andy in 12e788417
|
||||
- feat: Add screenshot capture to task creation modal (#1429) by @JoshuaRileyDev in 1a2a1b1fc
|
||||
- fix: prevent queue settings modal from disappearing when tasks change (#1430) by @JoshuaRileyDev in 33acc1430
|
||||
- feat: Queue System v2 with Auto-Promotion and Smart Task Management (#1203) by @JoshuaRileyDev in 3b87e24d7
|
||||
- feat: Add API profile providers usage endpoints support (#1279) by @StillKnotKnown in cfe7dedd0
|
||||
|
||||
## Thanks to all contributors
|
||||
|
||||
@AndyMik90, @Andy, @Burak, @StillKnotKnown, @VDT-91, @kaigler, @Michael Ludlow, @JoshuaRileyDev, @Quentin Veys, @bu5hm4nn
|
||||
|
||||
## 2.7.5 - Security & Platform Improvements
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
@@ -40,6 +40,8 @@ Auto Claude is a desktop application (+ CLI) where users describe a goal and AI
|
||||
|
||||
**PR target** — Always target the `develop` branch for PRs to AndyMik90/Auto-Claude, NOT `main`.
|
||||
|
||||
**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.
|
||||
|
||||
## Work Approach
|
||||
|
||||
**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.
|
||||
|
||||
@@ -17,18 +17,18 @@
|
||||
### Stable Release
|
||||
|
||||
<!-- STABLE_VERSION_BADGE -->
|
||||
[](https://github.com/AndyMik90/Auto-Claude/releases/tag/v2.7.5)
|
||||
[](https://github.com/AndyMik90/Auto-Claude/releases/tag/v2.7.6)
|
||||
<!-- STABLE_VERSION_BADGE_END -->
|
||||
|
||||
<!-- STABLE_DOWNLOADS -->
|
||||
| Platform | Download |
|
||||
|----------|----------|
|
||||
| **Windows** | [Auto-Claude-2.7.5-win32-x64.exe](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.5/Auto-Claude-2.7.5-win32-x64.exe) |
|
||||
| **macOS (Apple Silicon)** | [Auto-Claude-2.7.5-darwin-arm64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.5/Auto-Claude-2.7.5-darwin-arm64.dmg) |
|
||||
| **macOS (Intel)** | [Auto-Claude-2.7.5-darwin-x64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.5/Auto-Claude-2.7.5-darwin-x64.dmg) |
|
||||
| **Linux** | [Auto-Claude-2.7.5-linux-x86_64.AppImage](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.5/Auto-Claude-2.7.5-linux-x86_64.AppImage) |
|
||||
| **Linux (Debian)** | [Auto-Claude-2.7.5-linux-amd64.deb](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.5/Auto-Claude-2.7.5-linux-amd64.deb) |
|
||||
| **Linux (Flatpak)** | [Auto-Claude-2.7.5-linux-x86_64.flatpak](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.5/Auto-Claude-2.7.5-linux-x86_64.flatpak) |
|
||||
| **Windows** | [Auto-Claude-2.7.6-win32-x64.exe](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6/Auto-Claude-2.7.6-win32-x64.exe) |
|
||||
| **macOS (Apple Silicon)** | [Auto-Claude-2.7.6-darwin-arm64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6/Auto-Claude-2.7.6-darwin-arm64.dmg) |
|
||||
| **macOS (Intel)** | [Auto-Claude-2.7.6-darwin-x64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6/Auto-Claude-2.7.6-darwin-x64.dmg) |
|
||||
| **Linux** | [Auto-Claude-2.7.6-linux-x86_64.AppImage](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6/Auto-Claude-2.7.6-linux-x86_64.AppImage) |
|
||||
| **Linux (Debian)** | [Auto-Claude-2.7.6-linux-amd64.deb](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6/Auto-Claude-2.7.6-linux-amd64.deb) |
|
||||
| **Linux (Flatpak)** | [Auto-Claude-2.7.6-linux-x86_64.flatpak](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6/Auto-Claude-2.7.6-linux-x86_64.flatpak) |
|
||||
<!-- STABLE_DOWNLOADS_END -->
|
||||
|
||||
### Beta Release
|
||||
@@ -36,18 +36,18 @@
|
||||
> ⚠️ Beta releases may contain bugs and breaking changes. [View all releases](https://github.com/AndyMik90/Auto-Claude/releases)
|
||||
|
||||
<!-- BETA_VERSION_BADGE -->
|
||||
[](https://github.com/AndyMik90/Auto-Claude/releases/tag/v2.7.6-beta.5)
|
||||
[](https://github.com/AndyMik90/Auto-Claude/releases/tag/v2.7.6-beta.6)
|
||||
<!-- BETA_VERSION_BADGE_END -->
|
||||
|
||||
<!-- BETA_DOWNLOADS -->
|
||||
| Platform | Download |
|
||||
|----------|----------|
|
||||
| **Windows** | [Auto-Claude-2.7.6-beta.5-win32-x64.exe](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.5/Auto-Claude-2.7.6-beta.5-win32-x64.exe) |
|
||||
| **macOS (Apple Silicon)** | [Auto-Claude-2.7.6-beta.5-darwin-arm64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.5/Auto-Claude-2.7.6-beta.5-darwin-arm64.dmg) |
|
||||
| **macOS (Intel)** | [Auto-Claude-2.7.6-beta.5-darwin-x64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.5/Auto-Claude-2.7.6-beta.5-darwin-x64.dmg) |
|
||||
| **Linux** | [Auto-Claude-2.7.6-beta.5-linux-x86_64.AppImage](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.5/Auto-Claude-2.7.6-beta.5-linux-x86_64.AppImage) |
|
||||
| **Linux (Debian)** | [Auto-Claude-2.7.6-beta.5-linux-amd64.deb](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.5/Auto-Claude-2.7.6-beta.5-linux-amd64.deb) |
|
||||
| **Linux (Flatpak)** | [Auto-Claude-2.7.6-beta.5-linux-x86_64.flatpak](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.5/Auto-Claude-2.7.6-beta.5-linux-x86_64.flatpak) |
|
||||
| **Windows** | [Auto-Claude-2.7.6-beta.6-win32-x64.exe](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.6/Auto-Claude-2.7.6-beta.6-win32-x64.exe) |
|
||||
| **macOS (Apple Silicon)** | [Auto-Claude-2.7.6-beta.6-darwin-arm64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.6/Auto-Claude-2.7.6-beta.6-darwin-arm64.dmg) |
|
||||
| **macOS (Intel)** | [Auto-Claude-2.7.6-beta.6-darwin-x64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.6/Auto-Claude-2.7.6-beta.6-darwin-x64.dmg) |
|
||||
| **Linux** | [Auto-Claude-2.7.6-beta.6-linux-x86_64.AppImage](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.6/Auto-Claude-2.7.6-beta.6-linux-x86_64.AppImage) |
|
||||
| **Linux (Debian)** | [Auto-Claude-2.7.6-beta.6-linux-amd64.deb](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.6/Auto-Claude-2.7.6-beta.6-linux-amd64.deb) |
|
||||
| **Linux (Flatpak)** | [Auto-Claude-2.7.6-beta.6-linux-x86_64.flatpak](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.6/Auto-Claude-2.7.6-beta.6-linux-x86_64.flatpak) |
|
||||
<!-- BETA_DOWNLOADS_END -->
|
||||
|
||||
> All releases include SHA256 checksums and VirusTotal scan results for security verification.
|
||||
|
||||
@@ -19,5 +19,5 @@ Quick Start:
|
||||
See README.md for full documentation.
|
||||
"""
|
||||
|
||||
__version__ = "2.7.6-beta.5"
|
||||
__version__ = "2.7.6"
|
||||
__author__ = "Auto Claude Team"
|
||||
|
||||
@@ -14,6 +14,7 @@ from core.error_utils import (
|
||||
is_authentication_error,
|
||||
is_rate_limit_error,
|
||||
is_tool_concurrency_error,
|
||||
safe_receive_messages,
|
||||
)
|
||||
from core.file_utils import write_json_atomic
|
||||
from debug import debug, debug_detailed, debug_error, debug_section, debug_success
|
||||
@@ -490,7 +491,7 @@ async def run_agent_session(
|
||||
# Collect response text and show tool use
|
||||
response_text = ""
|
||||
debug("session", "Starting to receive response stream...")
|
||||
async for msg in client.receive_response():
|
||||
async for msg in safe_receive_messages(client, caller="session"):
|
||||
msg_type = type(msg).__name__
|
||||
message_count += 1
|
||||
debug_detailed(
|
||||
|
||||
+107
-1
@@ -29,6 +29,89 @@ from core.platform import (
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# =============================================================================
|
||||
# SDK Message Parser Patch
|
||||
# =============================================================================
|
||||
# The Claude Agent SDK's message_parser raises MessageParseError for unknown
|
||||
# message types (e.g., "rate_limit_event"). Since parse_message runs inside an
|
||||
# async generator, the exception kills the entire agent session stream.
|
||||
# Patch to log a warning and return a SystemMessage instead of crashing.
|
||||
# This is needed until the SDK natively handles all CLI message types.
|
||||
|
||||
|
||||
def _patch_sdk_message_parser() -> None:
|
||||
"""Patch the SDK's parse_message to handle unknown message types gracefully.
|
||||
|
||||
The Claude CLI may emit message types that the installed SDK version doesn't
|
||||
recognize (e.g., rate_limit_event, usage_event). Without this patch, any
|
||||
unrecognized type raises MessageParseError inside the SDK's async generator,
|
||||
which terminates the entire response stream and kills the agent session.
|
||||
|
||||
The patch converts unknown types into SystemMessage objects with a
|
||||
'unknown_<type>' subtype, which all message consumers silently skip.
|
||||
"""
|
||||
try:
|
||||
import claude_agent_sdk._internal.message_parser as _parser
|
||||
from claude_agent_sdk._errors import MessageParseError
|
||||
from claude_agent_sdk.types import SystemMessage
|
||||
|
||||
_original_parse = _parser.parse_message
|
||||
|
||||
def _patched_parse(data):
|
||||
try:
|
||||
return _original_parse(data)
|
||||
except MessageParseError as e:
|
||||
msg = str(e)
|
||||
if "Unknown message type" in msg:
|
||||
msg_type = (
|
||||
data.get("type", "unknown")
|
||||
if isinstance(data, dict)
|
||||
else "unknown"
|
||||
)
|
||||
# Rate limit events deserve a visible warning; others just debug-level
|
||||
if "rate_limit" in msg_type:
|
||||
retry_after = (
|
||||
data.get("retry_after")
|
||||
or data.get("data", {}).get("retry_after")
|
||||
if isinstance(data, dict)
|
||||
else None
|
||||
)
|
||||
retry_info = (
|
||||
f" (retry_after={retry_after}s)" if retry_after else ""
|
||||
)
|
||||
logger.warning(
|
||||
f"Rate limit event received from CLI{retry_info} — "
|
||||
f"the SDK will handle backoff automatically"
|
||||
)
|
||||
else:
|
||||
logger.debug(
|
||||
f"SDK received unhandled message type '{msg_type}', skipping"
|
||||
)
|
||||
return SystemMessage(
|
||||
subtype=f"unknown_{msg_type}",
|
||||
data=data if isinstance(data, dict) else {},
|
||||
)
|
||||
raise
|
||||
|
||||
_parser.parse_message = _patched_parse
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to patch SDK message parser: {e}")
|
||||
|
||||
|
||||
_patch_sdk_message_parser()
|
||||
|
||||
# =============================================================================
|
||||
# Windows System Prompt Limits
|
||||
# =============================================================================
|
||||
# Windows CreateProcessW has a 32,768 character limit for the entire command line.
|
||||
# When CLAUDE.md is very large and passed as --system-prompt, the command can exceed
|
||||
# this limit, causing ERROR_FILE_NOT_FOUND. We cap CLAUDE.md content to stay safe.
|
||||
# 20,000 chars leaves ~12KB headroom for CLI overhead (model, tools, MCP config, etc.)
|
||||
WINDOWS_MAX_SYSTEM_PROMPT_CHARS = 20000
|
||||
WINDOWS_TRUNCATION_MESSAGE = (
|
||||
"\n\n[... CLAUDE.md truncated due to Windows command-line length limit ...]"
|
||||
)
|
||||
|
||||
# =============================================================================
|
||||
# Project Index Cache
|
||||
# =============================================================================
|
||||
@@ -821,8 +904,31 @@ def create_client(
|
||||
if should_use_claude_md():
|
||||
claude_md_content = load_claude_md(project_dir)
|
||||
if claude_md_content:
|
||||
# On Windows, the SDK passes system_prompt as a --system-prompt CLI argument.
|
||||
# Windows CreateProcessW has a 32,768 character limit for the entire command line.
|
||||
# When CLAUDE.md is very large, the command can exceed this limit, causing Windows
|
||||
# to return ERROR_FILE_NOT_FOUND which the SDK misreports as "Claude Code not found".
|
||||
# Cap CLAUDE.md content to keep total command line under the limit. (#1661)
|
||||
was_truncated = False
|
||||
if is_windows():
|
||||
max_claude_md_chars = (
|
||||
WINDOWS_MAX_SYSTEM_PROMPT_CHARS
|
||||
- len(base_prompt)
|
||||
- len(WINDOWS_TRUNCATION_MESSAGE)
|
||||
- len("\n\n# Project Instructions (from CLAUDE.md)\n\n")
|
||||
)
|
||||
if len(claude_md_content) > max_claude_md_chars > 0:
|
||||
claude_md_content = (
|
||||
claude_md_content[:max_claude_md_chars]
|
||||
+ WINDOWS_TRUNCATION_MESSAGE
|
||||
)
|
||||
print(
|
||||
" - CLAUDE.md: truncated (exceeded Windows command-line limit)"
|
||||
)
|
||||
was_truncated = True
|
||||
base_prompt = f"{base_prompt}\n\n# Project Instructions (from CLAUDE.md)\n\n{claude_md_content}"
|
||||
print(" - CLAUDE.md: included in system prompt")
|
||||
if not was_truncated:
|
||||
print(" - CLAUDE.md: included in system prompt")
|
||||
else:
|
||||
print(" - CLAUDE.md: not found in project root")
|
||||
else:
|
||||
|
||||
@@ -6,7 +6,17 @@ Common error detection and classification functions used across
|
||||
agent sessions, QA, and other modules.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
from collections.abc import AsyncIterator
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from claude_agent_sdk.types import Message
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def is_tool_concurrency_error(error: Exception) -> bool:
|
||||
@@ -118,3 +128,61 @@ def is_authentication_error(error: Exception) -> bool:
|
||||
"please login again",
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
async def safe_receive_messages(
|
||||
client,
|
||||
*,
|
||||
caller: str = "agent",
|
||||
) -> AsyncIterator[Message]:
|
||||
"""Iterate over SDK messages with resilience against unexpected errors.
|
||||
|
||||
The SDK's ``receive_response()`` async generator can terminate early if:
|
||||
1. An unhandled message type slips past the monkey-patch (e.g., SDK upgrade
|
||||
removes the patch surface).
|
||||
2. A transient parse error corrupts a single message in the stream.
|
||||
3. An unexpected ``StopAsyncIteration`` or runtime error occurs mid-stream.
|
||||
|
||||
This wrapper catches per-message errors, logs them, and continues yielding
|
||||
subsequent messages so the agent session can complete its work.
|
||||
|
||||
It also detects rate-limit events (surfaced as ``SystemMessage`` with
|
||||
subtype ``unknown_rate_limit_event``) and logs a user-visible warning.
|
||||
|
||||
Args:
|
||||
client: A ``ClaudeSDKClient`` instance (must be inside ``async with``).
|
||||
caller: Label for log messages (e.g., "session", "agent_runner").
|
||||
|
||||
Yields:
|
||||
Parsed ``Message`` objects from the SDK response stream.
|
||||
"""
|
||||
try:
|
||||
async for msg in client.receive_response():
|
||||
# Detect rate-limit events surfaced by the monkey-patch
|
||||
msg_type = type(msg).__name__
|
||||
if msg_type == "SystemMessage":
|
||||
subtype = getattr(msg, "subtype", "")
|
||||
if subtype.startswith("unknown_"):
|
||||
original_type = subtype[len("unknown_") :]
|
||||
if "rate_limit" in original_type:
|
||||
data = getattr(msg, "data", {})
|
||||
retry_after = data.get("retry_after") or data.get(
|
||||
"data", {}
|
||||
).get("retry_after")
|
||||
retry_info = (
|
||||
f" (retry in {retry_after}s)" if retry_after else ""
|
||||
)
|
||||
logger.warning(f"[{caller}] Rate limit event{retry_info}")
|
||||
else:
|
||||
logger.debug(
|
||||
f"[{caller}] Skipping unknown SDK message type: {original_type}"
|
||||
)
|
||||
continue
|
||||
yield msg
|
||||
except GeneratorExit:
|
||||
return
|
||||
except Exception as e:
|
||||
# If the generator itself raises (e.g., transport error), log and stop
|
||||
# gracefully so callers can process whatever was collected so far.
|
||||
logger.error(f"[{caller}] SDK response stream terminated unexpectedly: {e}")
|
||||
return
|
||||
|
||||
@@ -1211,6 +1211,9 @@ class WorktreeManager:
|
||||
)
|
||||
|
||||
target = target_branch or self.base_branch
|
||||
# Strip remote prefix (e.g., "origin/feat/x" → "feat/x") since gh expects branch names only
|
||||
if target.startswith("origin/"):
|
||||
target = target[len("origin/") :]
|
||||
pr_title = title or f"auto-claude: {spec_name}"
|
||||
|
||||
# Try AI-powered PR body from project's PR template, fall back to spec summary
|
||||
@@ -1381,6 +1384,9 @@ class WorktreeManager:
|
||||
)
|
||||
|
||||
target = target_branch or self.base_branch
|
||||
# Strip remote prefix (e.g., "origin/feat/x" → "feat/x") since glab expects branch names only
|
||||
if target.startswith("origin/"):
|
||||
target = target[len("origin/") :]
|
||||
mr_title = title or f"auto-claude: {spec_name}"
|
||||
|
||||
# Get MR body from spec.md if available
|
||||
|
||||
@@ -24,7 +24,7 @@ You MUST create `spec.md` with ALL required sections (see template below).
|
||||
## PHASE 0: LOAD ALL CONTEXT (MANDATORY)
|
||||
|
||||
```bash
|
||||
# Read all input files
|
||||
# Read all input files (some may not exist for greenfield/empty projects)
|
||||
cat project_index.json
|
||||
cat requirements.json
|
||||
cat context.json
|
||||
@@ -35,6 +35,12 @@ Extract from these files:
|
||||
- **From requirements.json**: Task description, workflow type, services, acceptance criteria
|
||||
- **From context.json**: Files to modify, files to reference, patterns
|
||||
|
||||
**IMPORTANT**: If any input file is missing, empty, or shows 0 files, this is likely a **greenfield/new project**. Adapt accordingly:
|
||||
- Skip sections that reference existing code (e.g., "Files to Modify", "Patterns to Follow")
|
||||
- Instead, focus on files to CREATE and the initial project structure
|
||||
- Define the tech stack, dependencies, and setup instructions from scratch
|
||||
- Use industry best practices as patterns rather than referencing existing code
|
||||
|
||||
---
|
||||
|
||||
## PHASE 1: ANALYZE CONTEXT
|
||||
|
||||
@@ -15,7 +15,11 @@ from pathlib import Path
|
||||
from agents.base import sanitize_error_message
|
||||
from agents.memory_manager import get_graphiti_context, save_session_memory
|
||||
from claude_agent_sdk import ClaudeSDKClient
|
||||
from core.error_utils import is_rate_limit_error, is_tool_concurrency_error
|
||||
from core.error_utils import (
|
||||
is_rate_limit_error,
|
||||
is_tool_concurrency_error,
|
||||
safe_receive_messages,
|
||||
)
|
||||
from debug import debug, debug_detailed, debug_error, debug_section, debug_success
|
||||
from security.tool_input_validator import get_safe_tool_input
|
||||
from task_logger import (
|
||||
@@ -141,7 +145,7 @@ async def run_qa_fixer_session(
|
||||
|
||||
response_text = ""
|
||||
debug("qa_fixer", "Starting to receive response stream...")
|
||||
async for msg in client.receive_response():
|
||||
async for msg in safe_receive_messages(client, caller="qa_fixer"):
|
||||
msg_type = type(msg).__name__
|
||||
message_count += 1
|
||||
debug_detailed(
|
||||
|
||||
@@ -16,7 +16,11 @@ from pathlib import Path
|
||||
from agents.base import sanitize_error_message
|
||||
from agents.memory_manager import get_graphiti_context, save_session_memory
|
||||
from claude_agent_sdk import ClaudeSDKClient
|
||||
from core.error_utils import is_rate_limit_error, is_tool_concurrency_error
|
||||
from core.error_utils import (
|
||||
is_rate_limit_error,
|
||||
is_tool_concurrency_error,
|
||||
safe_receive_messages,
|
||||
)
|
||||
from debug import debug, debug_detailed, debug_error, debug_section, debug_success
|
||||
from prompts_pkg import get_qa_reviewer_prompt
|
||||
from security.tool_input_validator import get_safe_tool_input
|
||||
@@ -195,7 +199,7 @@ This is attempt {previous_error.get("consecutive_errors", 1) + 1}. If you fail t
|
||||
|
||||
response_text = ""
|
||||
debug("qa_reviewer", "Starting to receive response stream...")
|
||||
async for msg in client.receive_response():
|
||||
async for msg in safe_receive_messages(client, caller="qa_reviewer"):
|
||||
msg_type = type(msg).__name__
|
||||
message_count += 1
|
||||
debug_detailed(
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
# Auto-Build Framework Dependencies
|
||||
# SDK 0.1.33+ required for Opus 4.6 adaptive thinking support
|
||||
# Earlier versions lacked effort parameter and thinking type configuration
|
||||
claude-agent-sdk>=0.1.33
|
||||
# SDK 0.1.39+ required for Opus 4.6 adaptive thinking support and stability fixes
|
||||
# Earlier versions lacked effort parameter, thinking type configuration,
|
||||
# and crashed on unhandled CLI message types (e.g., rate_limit_event)
|
||||
claude-agent-sdk>=0.1.39
|
||||
python-dotenv>=1.0.0
|
||||
|
||||
# TOML parsing fallback for Python < 3.11
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -6,18 +6,54 @@ Phases for spec document creation and quality assurance.
|
||||
"""
|
||||
|
||||
import json
|
||||
from typing import TYPE_CHECKING
|
||||
from pathlib import Path
|
||||
|
||||
from .. import validator, writer
|
||||
from ..discovery import get_project_index_stats
|
||||
from .models import MAX_RETRIES, PhaseResult
|
||||
|
||||
if TYPE_CHECKING:
|
||||
pass
|
||||
|
||||
def _is_greenfield_project(spec_dir: Path) -> bool:
|
||||
"""Check if the project is empty/greenfield (0 discovered files)."""
|
||||
stats = get_project_index_stats(spec_dir)
|
||||
if not stats:
|
||||
return False # Can't determine - don't assume greenfield
|
||||
return stats.get("file_count", 0) == 0
|
||||
|
||||
|
||||
def _greenfield_context() -> str:
|
||||
"""Return additional context for greenfield/empty projects."""
|
||||
return """
|
||||
**GREENFIELD PROJECT**: This is an empty or new project with no existing code.
|
||||
There are no existing files to reference or modify. You are creating everything from scratch.
|
||||
|
||||
Adapt your approach:
|
||||
- Do NOT reference existing files, patterns, or code structures
|
||||
- Focus on what needs to be CREATED, not modified
|
||||
- Define the initial project structure, files, and directories
|
||||
- Specify the tech stack, frameworks, and dependencies to install
|
||||
- Provide setup instructions for the new project
|
||||
- For "Files to Modify" and "Files to Reference" sections, list files to CREATE instead
|
||||
- For "Patterns to Follow", describe industry best practices rather than existing code
|
||||
"""
|
||||
|
||||
|
||||
class SpecPhaseMixin:
|
||||
"""Mixin for spec writing and critique phase methods."""
|
||||
|
||||
def _check_and_log_greenfield(self) -> bool:
|
||||
"""Check if the project is greenfield and log if so.
|
||||
|
||||
Returns:
|
||||
True if the project is greenfield (no existing files).
|
||||
"""
|
||||
is_greenfield = _is_greenfield_project(self.spec_dir)
|
||||
if is_greenfield:
|
||||
self.ui.print_status(
|
||||
"Greenfield project detected - adapting spec for new project", "info"
|
||||
)
|
||||
return is_greenfield
|
||||
|
||||
async def phase_quick_spec(self) -> PhaseResult:
|
||||
"""Quick spec for simple tasks - combines context and spec in one step."""
|
||||
spec_file = self.spec_dir / "spec.md"
|
||||
@@ -29,6 +65,8 @@ class SpecPhaseMixin:
|
||||
"quick_spec", True, [str(spec_file), str(plan_file)], [], 0
|
||||
)
|
||||
|
||||
is_greenfield = self._check_and_log_greenfield()
|
||||
|
||||
errors = []
|
||||
for attempt in range(MAX_RETRIES):
|
||||
self.ui.print_status(
|
||||
@@ -42,7 +80,7 @@ class SpecPhaseMixin:
|
||||
|
||||
This is a SIMPLE task. Create a minimal spec and implementation plan directly.
|
||||
No research or extensive analysis needed.
|
||||
|
||||
{_greenfield_context() if is_greenfield else ""}
|
||||
Create:
|
||||
1. A concise spec.md with just the essential sections
|
||||
2. A simple implementation_plan.json with 1-2 subtasks
|
||||
@@ -80,6 +118,9 @@ Create:
|
||||
"spec.md exists but has issues, regenerating...", "warning"
|
||||
)
|
||||
|
||||
is_greenfield = self._check_and_log_greenfield()
|
||||
greenfield_ctx = _greenfield_context() if is_greenfield else ""
|
||||
|
||||
errors = []
|
||||
for attempt in range(MAX_RETRIES):
|
||||
self.ui.print_status(
|
||||
@@ -88,6 +129,7 @@ Create:
|
||||
|
||||
success, output = await self.run_agent_fn(
|
||||
"spec_writer.md",
|
||||
additional_context=greenfield_ctx,
|
||||
phase_name="spec_writing",
|
||||
)
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ from ui.capabilities import configure_safe_encoding
|
||||
|
||||
configure_safe_encoding()
|
||||
|
||||
from core.error_utils import safe_receive_messages
|
||||
from debug import debug, debug_detailed, debug_error, debug_section, debug_success
|
||||
from security.tool_input_validator import get_safe_tool_input
|
||||
from task_logger import (
|
||||
@@ -162,7 +163,7 @@ class AgentRunner:
|
||||
|
||||
response_text = ""
|
||||
debug("agent_runner", "Starting to receive response stream...")
|
||||
async for msg in client.receive_response():
|
||||
async for msg in safe_receive_messages(client, caller="agent_runner"):
|
||||
msg_type = type(msg).__name__
|
||||
message_count += 1
|
||||
debug_detailed(
|
||||
|
||||
@@ -203,19 +203,19 @@ def generate_spec_name(task_description: str) -> str:
|
||||
return "-".join(name_parts) if name_parts else "spec"
|
||||
|
||||
|
||||
def rename_spec_dir_from_requirements(spec_dir: Path) -> bool:
|
||||
def rename_spec_dir_from_requirements(spec_dir: Path) -> Path:
|
||||
"""Rename spec directory based on requirements.json task description.
|
||||
|
||||
Args:
|
||||
spec_dir: The current spec directory
|
||||
|
||||
Returns:
|
||||
Tuple of (success, new_spec_dir). If success is False, new_spec_dir is the original.
|
||||
The new spec directory path (or the original if no rename was needed/possible).
|
||||
"""
|
||||
requirements_file = spec_dir / "requirements.json"
|
||||
|
||||
if not requirements_file.exists():
|
||||
return False
|
||||
return spec_dir
|
||||
|
||||
try:
|
||||
with open(requirements_file, encoding="utf-8") as f:
|
||||
@@ -223,7 +223,7 @@ def rename_spec_dir_from_requirements(spec_dir: Path) -> bool:
|
||||
|
||||
task_desc = req.get("task_description", "")
|
||||
if not task_desc:
|
||||
return False
|
||||
return spec_dir
|
||||
|
||||
# Generate new name
|
||||
new_name = generate_spec_name(task_desc)
|
||||
@@ -240,11 +240,11 @@ def rename_spec_dir_from_requirements(spec_dir: Path) -> bool:
|
||||
|
||||
# Don't rename if it's already a good name (not "pending")
|
||||
if "pending" not in current_name:
|
||||
return True
|
||||
return spec_dir
|
||||
|
||||
# Don't rename if target already exists
|
||||
if new_spec_dir.exists():
|
||||
return True
|
||||
return spec_dir
|
||||
|
||||
# Rename the directory
|
||||
shutil.move(str(spec_dir), str(new_spec_dir))
|
||||
@@ -253,11 +253,11 @@ def rename_spec_dir_from_requirements(spec_dir: Path) -> bool:
|
||||
update_task_logger_path(new_spec_dir)
|
||||
|
||||
print_status(f"Spec folder: {highlight(new_dir_name)}", "success")
|
||||
return True
|
||||
return new_spec_dir
|
||||
|
||||
except (json.JSONDecodeError, OSError) as e:
|
||||
print_status(f"Could not rename spec folder: {e}", "warning")
|
||||
return False
|
||||
return spec_dir
|
||||
|
||||
|
||||
# Phase display configuration
|
||||
|
||||
@@ -6,6 +6,7 @@ Main orchestration logic for spec creation with dynamic complexity adaptation.
|
||||
"""
|
||||
|
||||
import json
|
||||
import types
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
@@ -18,6 +19,7 @@ from review import run_review_checkpoint
|
||||
from task_logger import (
|
||||
LogEntryType,
|
||||
LogPhase,
|
||||
TaskLogger,
|
||||
get_task_logger,
|
||||
)
|
||||
from ui import (
|
||||
@@ -238,6 +240,47 @@ class SpecOrchestrator:
|
||||
task_logger.start_phase(LogPhase.PLANNING, "Starting spec creation process")
|
||||
TaskEventEmitter.from_spec_dir(self.spec_dir).emit("PLANNING_STARTED")
|
||||
|
||||
# Track whether we've already ended the planning phase (to avoid double-end)
|
||||
self._planning_phase_ended = False
|
||||
|
||||
try:
|
||||
return await self._run_phases(interactive, auto_approve, task_logger, ui)
|
||||
except Exception as e:
|
||||
# Emit PLANNING_FAILED so the frontend XState machine transitions to error state
|
||||
# instead of leaving the task stuck in "planning" forever
|
||||
try:
|
||||
task_emitter = TaskEventEmitter.from_spec_dir(self.spec_dir)
|
||||
task_emitter.emit(
|
||||
"PLANNING_FAILED",
|
||||
{"error": str(e), "recoverable": True},
|
||||
)
|
||||
except Exception:
|
||||
pass # Don't mask the original error
|
||||
if not self._planning_phase_ended:
|
||||
self._planning_phase_ended = True
|
||||
try:
|
||||
task_logger.end_phase(
|
||||
LogPhase.PLANNING,
|
||||
success=False,
|
||||
message=f"Spec creation crashed: {e}",
|
||||
)
|
||||
except Exception:
|
||||
pass # Best effort - don't mask the original error when logging fails
|
||||
raise
|
||||
|
||||
async def _run_phases(
|
||||
self,
|
||||
interactive: bool,
|
||||
auto_approve: bool,
|
||||
task_logger: TaskLogger,
|
||||
ui: types.ModuleType,
|
||||
) -> bool:
|
||||
"""Internal method that runs all spec creation phases.
|
||||
|
||||
Separated from run() so that run() can wrap this in a try/except
|
||||
to emit PLANNING_FAILED on unhandled exceptions.
|
||||
"""
|
||||
|
||||
print(
|
||||
box(
|
||||
f"Spec Directory: {self.spec_dir}\n"
|
||||
@@ -291,9 +334,11 @@ class SpecOrchestrator:
|
||||
results.append(result)
|
||||
if not result.success:
|
||||
print_status("Discovery failed", "error")
|
||||
self._planning_phase_ended = True
|
||||
task_logger.end_phase(
|
||||
LogPhase.PLANNING, success=False, message="Discovery failed"
|
||||
)
|
||||
self._emit_planning_failed("Discovery phase failed")
|
||||
return False
|
||||
# Store summary for subsequent phases (compaction)
|
||||
await self._store_phase_summary("discovery")
|
||||
@@ -305,17 +350,26 @@ class SpecOrchestrator:
|
||||
results.append(result)
|
||||
if not result.success:
|
||||
print_status("Requirements gathering failed", "error")
|
||||
self._planning_phase_ended = True
|
||||
task_logger.end_phase(
|
||||
LogPhase.PLANNING,
|
||||
success=False,
|
||||
message="Requirements gathering failed",
|
||||
)
|
||||
self._emit_planning_failed("Requirements gathering failed")
|
||||
return False
|
||||
# Store summary for subsequent phases (compaction)
|
||||
await self._store_phase_summary("requirements")
|
||||
|
||||
# Rename spec folder with better name from requirements
|
||||
rename_spec_dir_from_requirements(self.spec_dir)
|
||||
# IMPORTANT: Update self.spec_dir after rename so subsequent phases use the correct path
|
||||
new_spec_dir = rename_spec_dir_from_requirements(self.spec_dir)
|
||||
if new_spec_dir != self.spec_dir:
|
||||
self.spec_dir = new_spec_dir
|
||||
self.validator = SpecValidator(self.spec_dir)
|
||||
# Update phase executor to use the renamed directory
|
||||
phase_executor.spec_dir = self.spec_dir
|
||||
phase_executor.spec_validator = self.validator
|
||||
|
||||
# Update task description from requirements
|
||||
req = requirements.load_requirements(self.spec_dir)
|
||||
@@ -335,9 +389,11 @@ class SpecOrchestrator:
|
||||
results.append(result)
|
||||
if not result.success:
|
||||
print_status("Complexity assessment failed", "error")
|
||||
self._planning_phase_ended = True
|
||||
task_logger.end_phase(
|
||||
LogPhase.PLANNING, success=False, message="Complexity assessment failed"
|
||||
)
|
||||
self._emit_planning_failed("Complexity assessment failed")
|
||||
return False
|
||||
|
||||
# Map of all available phases
|
||||
@@ -396,17 +452,22 @@ class SpecOrchestrator:
|
||||
f"Phase '{phase_name}' failed: {'; '.join(result.errors)}",
|
||||
LogEntryType.ERROR,
|
||||
)
|
||||
self._planning_phase_ended = True
|
||||
task_logger.end_phase(
|
||||
LogPhase.PLANNING,
|
||||
success=False,
|
||||
message=f"Phase {phase_name} failed",
|
||||
)
|
||||
self._emit_planning_failed(
|
||||
f"Phase '{phase_name}' failed: {'; '.join(result.errors)}"
|
||||
)
|
||||
return False
|
||||
|
||||
# Summary
|
||||
self._print_completion_summary(results, phases_executed)
|
||||
|
||||
# End planning phase successfully
|
||||
self._planning_phase_ended = True
|
||||
task_logger.end_phase(
|
||||
LogPhase.PLANNING, success=True, message="Spec creation complete"
|
||||
)
|
||||
@@ -638,6 +699,25 @@ class SpecOrchestrator:
|
||||
)
|
||||
)
|
||||
|
||||
def _emit_planning_failed(self, error: str) -> None:
|
||||
"""Emit PLANNING_FAILED event so the frontend transitions to error state.
|
||||
|
||||
Without this, the task stays stuck in 'planning' / 'in_progress' forever
|
||||
when spec creation fails, because the XState machine never receives a
|
||||
terminal event.
|
||||
|
||||
Args:
|
||||
error: Human-readable error description
|
||||
"""
|
||||
try:
|
||||
task_emitter = TaskEventEmitter.from_spec_dir(self.spec_dir)
|
||||
task_emitter.emit(
|
||||
"PLANNING_FAILED",
|
||||
{"error": error, "recoverable": True},
|
||||
)
|
||||
except Exception:
|
||||
pass # Best effort - don't mask the original failure
|
||||
|
||||
def _run_review_checkpoint(self, auto_approve: bool) -> bool:
|
||||
"""Run the human review checkpoint.
|
||||
|
||||
@@ -661,9 +741,8 @@ class SpecOrchestrator:
|
||||
print_status("Build will not proceed without approval.", "warning")
|
||||
return False
|
||||
|
||||
except SystemExit as e:
|
||||
if e.code != 0:
|
||||
return False
|
||||
except SystemExit:
|
||||
# Review checkpoint may call sys.exit(); treat any exit as unapproved
|
||||
return False
|
||||
except KeyboardInterrupt:
|
||||
print()
|
||||
@@ -696,19 +775,25 @@ class SpecOrchestrator:
|
||||
The functionality has been moved to models.rename_spec_dir_from_requirements.
|
||||
|
||||
Returns:
|
||||
True if successful or not needed, False on error
|
||||
True if successful or not needed, False if prerequisites are missing
|
||||
"""
|
||||
result = rename_spec_dir_from_requirements(self.spec_dir)
|
||||
# Update self.spec_dir if it was renamed
|
||||
if result and self.spec_dir.name.endswith("-pending"):
|
||||
# Find the renamed directory
|
||||
parent = self.spec_dir.parent
|
||||
prefix = self.spec_dir.name[:4] # e.g., "001-"
|
||||
for candidate in parent.iterdir():
|
||||
if (
|
||||
candidate.name.startswith(prefix)
|
||||
and "pending" not in candidate.name
|
||||
):
|
||||
self.spec_dir = candidate
|
||||
break
|
||||
return result
|
||||
# Check prerequisites first
|
||||
requirements_file = self.spec_dir / "requirements.json"
|
||||
if not requirements_file.exists():
|
||||
return False
|
||||
|
||||
try:
|
||||
with open(requirements_file, encoding="utf-8") as f:
|
||||
req = json.load(f)
|
||||
task_desc = req.get("task_description", "")
|
||||
if not task_desc:
|
||||
return False
|
||||
except (json.JSONDecodeError, OSError):
|
||||
return False
|
||||
|
||||
# Attempt rename
|
||||
new_spec_dir = rename_spec_dir_from_requirements(self.spec_dir)
|
||||
if new_spec_dir != self.spec_dir:
|
||||
self.spec_dir = new_spec_dir
|
||||
self.validator = SpecValidator(self.spec_dir)
|
||||
return True
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "auto-claude-ui",
|
||||
"version": "2.7.6-beta.5",
|
||||
"version": "2.7.6",
|
||||
"type": "module",
|
||||
"description": "Desktop UI for Auto Claude autonomous coding framework",
|
||||
"homepage": "https://github.com/AndyMik90/Auto-Claude",
|
||||
|
||||
@@ -186,7 +186,7 @@ describe('Subprocess Spawn Integration', () => {
|
||||
'Test task description'
|
||||
]),
|
||||
expect.objectContaining({
|
||||
cwd: AUTO_CLAUDE_SOURCE, // Process runs from auto-claude source directory
|
||||
cwd: TEST_PROJECT_PATH, // Process runs from project directory to avoid cross-drive issues on Windows (#1661)
|
||||
env: expect.objectContaining({
|
||||
PYTHONUNBUFFERED: '1'
|
||||
})
|
||||
@@ -218,7 +218,7 @@ describe('Subprocess Spawn Integration', () => {
|
||||
'spec-001'
|
||||
]),
|
||||
expect.objectContaining({
|
||||
cwd: AUTO_CLAUDE_SOURCE // Process runs from auto-claude source directory
|
||||
cwd: TEST_PROJECT_PATH // Process runs from project directory to avoid cross-drive issues on Windows (#1661)
|
||||
})
|
||||
);
|
||||
}, 30000); // Increase timeout for Windows CI (dynamic imports are slow)
|
||||
@@ -248,7 +248,7 @@ describe('Subprocess Spawn Integration', () => {
|
||||
'--qa'
|
||||
]),
|
||||
expect.objectContaining({
|
||||
cwd: AUTO_CLAUDE_SOURCE // Process runs from auto-claude source directory
|
||||
cwd: TEST_PROJECT_PATH // Process runs from project directory to avoid cross-drive issues on Windows (#1661)
|
||||
})
|
||||
);
|
||||
}, 30000); // Increase timeout for Windows CI (dynamic imports are slow)
|
||||
|
||||
@@ -0,0 +1,301 @@
|
||||
/**
|
||||
* Unit tests for FileWatcher concurrency mechanisms
|
||||
* Tests deduplication, supersession, cancellation, and unwatchAll behaviour
|
||||
* under concurrent watch()/unwatch() call patterns.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
import path from 'path';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mock chokidar BEFORE importing FileWatcher so the module sees our mock.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// A minimal FSWatcher stub that lets us control when close() resolves.
|
||||
class MockFSWatcher extends EventEmitter {
|
||||
close: ReturnType<typeof vi.fn>;
|
||||
constructor(closeImpl?: () => Promise<void>) {
|
||||
super();
|
||||
this.close = vi.fn(closeImpl ?? (() => Promise.resolve()));
|
||||
}
|
||||
}
|
||||
|
||||
// Track every watcher created so tests can inspect them.
|
||||
let createdWatchers: MockFSWatcher[] = [];
|
||||
// Factory override — tests replace this to inject custom stubs.
|
||||
let watchFactory: (() => MockFSWatcher) | null = null;
|
||||
|
||||
vi.mock('chokidar', () => ({
|
||||
default: {
|
||||
watch: vi.fn((_path: string, _opts: unknown) => {
|
||||
const watcher = watchFactory ? watchFactory() : new MockFSWatcher();
|
||||
createdWatchers.push(watcher);
|
||||
return watcher;
|
||||
})
|
||||
}
|
||||
}));
|
||||
|
||||
// Mock 'fs' so we can control existsSync / readFileSync without touching disk.
|
||||
vi.mock('fs', () => ({
|
||||
existsSync: vi.fn(() => true),
|
||||
readFileSync: vi.fn(() => JSON.stringify({ phases: [] }))
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Import after mocks are registered
|
||||
// ---------------------------------------------------------------------------
|
||||
import { FileWatcher } from '../file-watcher';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('FileWatcher concurrency', () => {
|
||||
let fw: FileWatcher;
|
||||
|
||||
beforeEach(() => {
|
||||
fw = new FileWatcher();
|
||||
createdWatchers = [];
|
||||
watchFactory = null;
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
// Clean up any watchers that are still open.
|
||||
await fw.unwatchAll();
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 1. Deduplication — same taskId + same specDir
|
||||
// -------------------------------------------------------------------------
|
||||
describe('deduplication: second watch() with same specDir is a no-op', () => {
|
||||
it('should only create one FSWatcher when watch() is called twice with the same specDir while the first is still in-flight', async () => {
|
||||
const specDir = '/project/.auto-claude/specs/001-task';
|
||||
const taskId = 'task-1';
|
||||
|
||||
// To create a real async gap we need an existing watcher whose close() is slow.
|
||||
// First, set up a watcher for taskId (completes synchronously).
|
||||
await fw.watch(taskId, specDir);
|
||||
expect(createdWatchers).toHaveLength(1);
|
||||
|
||||
// Replace close() with a slow one so the next watch() call has an async gap.
|
||||
const existingWatcher = createdWatchers[0];
|
||||
let resolveClose!: () => void;
|
||||
existingWatcher.close = vi.fn(
|
||||
() => new Promise<void>((res) => { resolveClose = res; })
|
||||
);
|
||||
|
||||
// Now start two concurrent watch() calls for the SAME specDir.
|
||||
// Both will try to enter, but the second should be deduplicated.
|
||||
const watchPromise1 = fw.watch(taskId, specDir);
|
||||
const watchPromise2 = fw.watch(taskId, specDir);
|
||||
|
||||
// Resolve the close so both can proceed.
|
||||
resolveClose();
|
||||
await Promise.all([watchPromise1, watchPromise2]);
|
||||
|
||||
// Only one new FSWatcher should have been created (the second call was a no-op).
|
||||
// createdWatchers[0] is the original; createdWatchers[1] is the new one.
|
||||
expect(createdWatchers).toHaveLength(2);
|
||||
expect(fw.isWatching(taskId)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 2. Supersession — same taskId, different specDir
|
||||
// -------------------------------------------------------------------------
|
||||
describe('supersession: watch() with different specDir replaces the in-flight call', () => {
|
||||
it('should let the second call win when the first is awaiting close()', async () => {
|
||||
const taskId = 'task-2';
|
||||
const specDir1 = path.join('/project', '.auto-claude', 'specs', '001-first');
|
||||
const specDir2 = path.join('/project', '.auto-claude', 'specs', '002-second');
|
||||
|
||||
// First call installs an existing watcher (simulate: the watcher for
|
||||
// specDir1 is already set up so the second watch() needs to close it).
|
||||
// We do this by running the first watch() to completion first.
|
||||
await fw.watch(taskId, specDir1);
|
||||
expect(createdWatchers).toHaveLength(1);
|
||||
|
||||
// Now make the close() of the first watcher slow so there's an async gap
|
||||
// during which the second watch() can enter and supersede.
|
||||
const existingWatcher = createdWatchers[0];
|
||||
let resolveClose!: () => void;
|
||||
existingWatcher.close = vi.fn(
|
||||
() => new Promise<void>((res) => { resolveClose = res; })
|
||||
);
|
||||
|
||||
// Start the second watch() — it will try to close the first watcher's
|
||||
// FSWatcher and will be awaiting that.
|
||||
const watch2Promise = fw.watch(taskId, specDir2);
|
||||
|
||||
// While the second watch() is awaiting close, start a THIRD call with
|
||||
// yet another specDir — this supersedes the second call.
|
||||
// Actually for the test described in the finding, we want:
|
||||
// - First call bails, second call creates the watcher.
|
||||
// Let's resolve the close and let watch2 finish.
|
||||
resolveClose();
|
||||
await watch2Promise;
|
||||
|
||||
// The final watcher should be for specDir2.
|
||||
expect(fw.getWatchedSpecDir(taskId)).toBe(specDir2);
|
||||
// Two watchers were created in total (one for each specDir).
|
||||
expect(createdWatchers).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('first watch() bails when pendingWatches changes to a different specDir', async () => {
|
||||
const taskId = 'task-super';
|
||||
const specDir1 = path.join('/project', '.auto-claude', 'specs', 'super-first');
|
||||
const specDir2 = path.join('/project', '.auto-claude', 'specs', 'super-second');
|
||||
|
||||
// Make the first watcher's close() slow so we can interleave.
|
||||
let resolveFirstClose!: () => void;
|
||||
watchFactory = () => {
|
||||
const w = new MockFSWatcher(() => new Promise<void>((res) => { resolveFirstClose = res; }));
|
||||
return w;
|
||||
};
|
||||
|
||||
// Start first watch().
|
||||
const watch1Promise = fw.watch(taskId, specDir1);
|
||||
|
||||
// Immediately start second watch() — before the first has resolved the
|
||||
// slow close(). At this point specDir1 watch hasn't even created an
|
||||
// FSWatcher yet (it's the very first call so there's no existing watcher
|
||||
// to close), so watch1Promise may resolve synchronously up to watcher
|
||||
// creation. Reset factory to normal for subsequent watcher creations.
|
||||
watchFactory = null;
|
||||
|
||||
const watch2Promise = fw.watch(taskId, specDir2);
|
||||
|
||||
// Let any remaining microtasks run.
|
||||
await Promise.resolve();
|
||||
if (resolveFirstClose) resolveFirstClose();
|
||||
|
||||
await Promise.all([watch1Promise, watch2Promise]);
|
||||
|
||||
// The winning call (specDir2) should own the watcher.
|
||||
expect(fw.getWatchedSpecDir(taskId)).toBe(specDir2);
|
||||
});
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 3. Cancellation — unwatch() during in-flight watch()
|
||||
// -------------------------------------------------------------------------
|
||||
describe('cancellation: unwatch() during in-flight watch() prevents watcher creation', () => {
|
||||
it('should not create a watcher when unwatch() is called before the async gap resolves', async () => {
|
||||
const taskId = 'task-3';
|
||||
const specDir = '/project/.auto-claude/specs/003-cancel';
|
||||
|
||||
// There's no pre-existing watcher, so watch() won't call close(). But it
|
||||
// does go async (chokidar.watch is sync but we can test the cancellation
|
||||
// flag by calling unwatch() before watch() runs).
|
||||
// The real async gap in watch() is the existing.watcher.close() call.
|
||||
// For this test, let's pre-install a watcher so close() is called.
|
||||
|
||||
// Install a slow-close watcher for taskId by manually populating the map.
|
||||
// We can do that by running a first watch(), then replacing close().
|
||||
await fw.watch(taskId, specDir);
|
||||
|
||||
// Replace the watcher's close() with a slow one.
|
||||
const existingWatcher = createdWatchers[0];
|
||||
let resolveExistingClose!: () => void;
|
||||
existingWatcher.close = vi.fn(
|
||||
() => new Promise<void>((res) => { resolveExistingClose = res; })
|
||||
);
|
||||
|
||||
// Start a second watch() — it will await the slow close().
|
||||
const specDir2 = '/project/.auto-claude/specs/003-cancel-v2';
|
||||
const watchPromise = fw.watch(taskId, specDir2);
|
||||
|
||||
// While watch() is in-flight, call unwatch().
|
||||
await fw.unwatch(taskId);
|
||||
|
||||
// Now resolve the slow close so watch() can continue past the await.
|
||||
resolveExistingClose();
|
||||
await watchPromise;
|
||||
|
||||
// No new watcher should have been registered.
|
||||
expect(fw.isWatching(taskId)).toBe(false);
|
||||
// Only one FSWatcher was ever created (the original one for specDir).
|
||||
expect(createdWatchers).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 4. unwatchAll() with pending watches
|
||||
// -------------------------------------------------------------------------
|
||||
describe('unwatchAll() cancels all pending watches', () => {
|
||||
it('should cancel pending watch() calls and clear pendingWatches', async () => {
|
||||
const taskId1 = 'task-4a';
|
||||
const taskId2 = 'task-4b';
|
||||
const specDir1 = '/project/.auto-claude/specs/004a';
|
||||
const specDir2 = '/project/.auto-claude/specs/004b';
|
||||
|
||||
// Set up slow-close scenario for taskId1 (so watch() is in-flight).
|
||||
await fw.watch(taskId1, specDir1);
|
||||
const watcher1 = createdWatchers[0];
|
||||
let resolveClose1!: () => void;
|
||||
watcher1.close = vi.fn(
|
||||
() => new Promise<void>((res) => { resolveClose1 = res; })
|
||||
);
|
||||
|
||||
// Start a new watch for taskId1 with a different specDir — this is now in-flight.
|
||||
const newSpecDir1 = '/project/.auto-claude/specs/004a-v2';
|
||||
const watchPromise1 = fw.watch(taskId1, newSpecDir1);
|
||||
|
||||
// Start a fresh watch for taskId2.
|
||||
await fw.watch(taskId2, specDir2);
|
||||
|
||||
// Call unwatchAll() while watchPromise1 is still pending.
|
||||
const unwatchAllPromise = fw.unwatchAll();
|
||||
|
||||
// Resolve the slow close so everything can proceed.
|
||||
resolveClose1();
|
||||
await Promise.all([watchPromise1, unwatchAllPromise]);
|
||||
|
||||
// After unwatchAll, no watchers should be active.
|
||||
expect(fw.isWatching(taskId1)).toBe(false);
|
||||
expect(fw.isWatching(taskId2)).toBe(false);
|
||||
|
||||
// pendingWatches should be cleared (we verify indirectly: a fresh
|
||||
// watch() call for taskId1 must succeed without treating it as a duplicate).
|
||||
const specDirFresh = path.join('/project', '.auto-claude', 'specs', '004a-fresh');
|
||||
await fw.watch(taskId1, specDirFresh);
|
||||
expect(fw.isWatching(taskId1)).toBe(true);
|
||||
expect(fw.getWatchedSpecDir(taskId1)).toBe(specDirFresh);
|
||||
});
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 5. getWatchedSpecDir() returns correct specDir
|
||||
// -------------------------------------------------------------------------
|
||||
describe('getWatchedSpecDir()', () => {
|
||||
it('returns the specDir that was passed to watch()', async () => {
|
||||
const taskId = 'task-5';
|
||||
const specDir = path.join('/project', '.auto-claude', 'specs', '005-specdir');
|
||||
|
||||
await fw.watch(taskId, specDir);
|
||||
|
||||
expect(fw.getWatchedSpecDir(taskId)).toBe(specDir);
|
||||
});
|
||||
|
||||
it('returns null when the task is not being watched', () => {
|
||||
expect(fw.getWatchedSpecDir('unknown-task')).toBeNull();
|
||||
});
|
||||
|
||||
it('returns updated specDir after re-watch with different specDir', async () => {
|
||||
const taskId = 'task-5b';
|
||||
const specDir1 = path.join('/project', '.auto-claude', 'specs', '005b-first');
|
||||
const specDir2 = path.join('/project', '.auto-claude', 'specs', '005b-second');
|
||||
|
||||
await fw.watch(taskId, specDir1);
|
||||
expect(fw.getWatchedSpecDir(taskId)).toBe(specDir1);
|
||||
|
||||
await fw.watch(taskId, specDir2);
|
||||
expect(fw.getWatchedSpecDir(taskId)).toBe(specDir2);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -329,7 +329,9 @@ export class AgentManager extends EventEmitter {
|
||||
this.registerTaskWithOperationRegistry(taskId, 'spec-creation', { projectPath, taskDescription, specDir });
|
||||
|
||||
// Note: This is spec-creation but it chains to task-execution via run.py
|
||||
await this.processManager.spawnProcess(taskId, autoBuildSource, args, combinedEnv, 'task-execution', projectId);
|
||||
// Use projectPath as cwd instead of autoBuildSource to avoid cross-drive file access
|
||||
// issues on Windows. The script path is absolute so Python finds its modules via sys.path[0]. (#1661)
|
||||
await this.processManager.spawnProcess(taskId, projectPath, args, combinedEnv, 'task-execution', projectId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -410,7 +412,10 @@ export class AgentManager extends EventEmitter {
|
||||
// Register with unified OperationRegistry for proactive swap support
|
||||
this.registerTaskWithOperationRegistry(taskId, 'task-execution', { projectPath, specId, options });
|
||||
|
||||
await this.processManager.spawnProcess(taskId, autoBuildSource, args, combinedEnv, 'task-execution', projectId);
|
||||
// Use projectPath as cwd instead of autoBuildSource to avoid cross-drive file access
|
||||
// issues on Windows. The script path (runPath) is absolute so Python finds its modules
|
||||
// via sys.path[0] which is set to the script's directory. (#1661)
|
||||
await this.processManager.spawnProcess(taskId, projectPath, args, combinedEnv, 'task-execution', projectId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -448,7 +453,8 @@ export class AgentManager extends EventEmitter {
|
||||
|
||||
const args = [runPath, '--spec', specId, '--project-dir', projectPath, '--qa'];
|
||||
|
||||
await this.processManager.spawnProcess(taskId, autoBuildSource, args, combinedEnv, 'qa-process', projectId);
|
||||
// Use projectPath as cwd instead of autoBuildSource to avoid cross-drive issues on Windows (#1661)
|
||||
await this.processManager.spawnProcess(taskId, projectPath, args, combinedEnv, 'qa-process', projectId);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -22,10 +22,10 @@ import { pythonEnvManager, getConfiguredPythonPath } from '../python-env-manager
|
||||
import { buildMemoryEnvVars } from '../memory-env-builder';
|
||||
import { readSettingsFile } from '../settings-utils';
|
||||
import type { AppSettings } from '../../shared/types/settings';
|
||||
import { getOAuthModeClearVars } from './env-utils';
|
||||
import { getOAuthModeClearVars, normalizeEnvPathKey, mergePythonEnvPath } from './env-utils';
|
||||
import { getAugmentedEnv } from '../env-utils';
|
||||
import { getToolInfo, getClaudeCliPathForSdk } from '../cli-tool-manager';
|
||||
import { killProcessGracefully, isWindows } from '../platform';
|
||||
import { killProcessGracefully, isWindows, getPathDelimiter } from '../platform';
|
||||
import { debugLog } from '../../shared/utils/debug-logger';
|
||||
|
||||
/**
|
||||
@@ -679,7 +679,17 @@ export class AgentProcessManager {
|
||||
},
|
||||
});
|
||||
|
||||
// Parse Python commandto handle space-separated commands like "py -3"
|
||||
// Merge PATH from pythonEnv with augmented PATH from env.
|
||||
// pythonEnv may contain its own PATH (e.g., on Windows with pywin32_system32 prepended).
|
||||
// Simply spreading pythonEnv after env would overwrite the augmented PATH (which includes
|
||||
// npm globals, homebrew, etc.), causing "Claude code not found" on Windows (#1661).
|
||||
// mergePythonEnvPath() normalizes PATH key casing and prepends pythonEnv-specific paths.
|
||||
const mergedPythonEnv = { ...pythonEnv };
|
||||
const pathSep = getPathDelimiter();
|
||||
|
||||
mergePythonEnvPath(env as Record<string, string | undefined>, mergedPythonEnv as Record<string, string | undefined>, pathSep);
|
||||
|
||||
// Parse Python command to handle space-separated commands like "py -3"
|
||||
const [pythonCommand, pythonBaseArgs] = parsePythonCommand(this.getPythonPath());
|
||||
let childProcess;
|
||||
try {
|
||||
@@ -687,7 +697,7 @@ export class AgentProcessManager {
|
||||
cwd,
|
||||
env: {
|
||||
...env, // Already includes process.env, extraEnv, profileEnv, PYTHONUNBUFFERED, PYTHONUTF8
|
||||
...pythonEnv, // Include Python environment (PYTHONPATH for bundled packages)
|
||||
...mergedPythonEnv, // Python env with merged PATH (preserves augmented PATH entries)
|
||||
...oauthModeClearVars, // Clear stale ANTHROPIC_* vars when in OAuth mode
|
||||
...apiProfileEnv // Include active API profile config (highest priority for ANTHROPIC_* vars)
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import type { IdeationConfig, Idea } from '../../shared/types';
|
||||
import { AUTO_BUILD_PATHS } from '../../shared/constants';
|
||||
import { detectRateLimit, createSDKRateLimitInfo, getBestAvailableProfileEnv } from '../rate-limit-detector';
|
||||
import { getAPIProfileEnv } from '../services/profile';
|
||||
import { getOAuthModeClearVars } from './env-utils';
|
||||
import { getOAuthModeClearVars, normalizeEnvPathKey } from './env-utils';
|
||||
import { debugLog, debugError } from '../../shared/utils/debug-logger';
|
||||
import { stripAnsiCodes } from '../../shared/utils/ansi-sanitizer';
|
||||
import { parsePythonCommand } from '../python-detector';
|
||||
@@ -397,6 +397,12 @@ export class AgentQueueManager {
|
||||
PYTHONUTF8: '1'
|
||||
};
|
||||
|
||||
// Normalize PATH key to a single uppercase 'PATH' entry.
|
||||
// On Windows, process.env spread produces 'Path' while pythonEnv may write 'PATH',
|
||||
// resulting in duplicate keys in the final object. Without normalization the child
|
||||
// process inherits both keys, which can cause tool-not-found errors (#1661).
|
||||
normalizeEnvPathKey(finalEnv as Record<string, string | undefined>);
|
||||
|
||||
// Debug: Show OAuth token source (token values intentionally omitted for security - AC4)
|
||||
const tokenSource = profileEnv['CLAUDE_CODE_OAUTH_TOKEN']
|
||||
? 'Electron app profile'
|
||||
@@ -730,6 +736,12 @@ export class AgentQueueManager {
|
||||
PYTHONUTF8: '1'
|
||||
};
|
||||
|
||||
// Normalize PATH key to a single uppercase 'PATH' entry.
|
||||
// On Windows, process.env spread produces 'Path' while pythonEnv may write 'PATH',
|
||||
// resulting in duplicate keys in the final object. Without normalization the child
|
||||
// process inherits both keys, which can cause tool-not-found errors (#1661).
|
||||
normalizeEnvPathKey(finalEnv as Record<string, string | undefined>);
|
||||
|
||||
// Debug: Show OAuth token source (token values intentionally omitted for security - AC4)
|
||||
const tokenSource = profileEnv['CLAUDE_CODE_OAUTH_TOKEN']
|
||||
? 'Electron app profile'
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { getOAuthModeClearVars } from './env-utils';
|
||||
import { getOAuthModeClearVars, normalizeEnvPathKey, mergePythonEnvPath } from './env-utils';
|
||||
|
||||
describe('getOAuthModeClearVars', () => {
|
||||
describe('OAuth mode (no active API profile)', () => {
|
||||
@@ -132,3 +132,166 @@ describe('getOAuthModeClearVars', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('normalizeEnvPathKey', () => {
|
||||
it('should leave an already-uppercase PATH key untouched', () => {
|
||||
const env: Record<string, string | undefined> = { PATH: '/usr/bin:/bin', HOME: '/home/user' };
|
||||
normalizeEnvPathKey(env);
|
||||
expect(env).toEqual({ PATH: '/usr/bin:/bin', HOME: '/home/user' });
|
||||
});
|
||||
|
||||
it('should rename a lowercase-variant "Path" key to "PATH"', () => {
|
||||
const env: Record<string, string | undefined> = { Path: 'C:\\Windows\\system32', HOME: '/home/user' };
|
||||
normalizeEnvPathKey(env);
|
||||
expect(env['PATH']).toBe('C:\\Windows\\system32');
|
||||
expect('Path' in env).toBe(false);
|
||||
});
|
||||
|
||||
it('should prefer existing "PATH" and remove "Path" when both keys coexist', () => {
|
||||
// Simulates process.env spread ('Path') after getAugmentedEnv writes ('PATH')
|
||||
const env: Record<string, string | undefined> = {
|
||||
Path: 'C:\\old',
|
||||
PATH: 'C:\\Windows\\system32;C:\\augmented',
|
||||
HOME: '/home/user'
|
||||
};
|
||||
normalizeEnvPathKey(env);
|
||||
expect(env.PATH).toBe('C:\\Windows\\system32;C:\\augmented');
|
||||
expect('Path' in env).toBe(false);
|
||||
});
|
||||
|
||||
it('should remove all case-variant PATH duplicates when PATH is already present', () => {
|
||||
const env: Record<string, string | undefined> = {
|
||||
PATH: '/correct',
|
||||
Path: '/old1',
|
||||
path: '/old2'
|
||||
};
|
||||
normalizeEnvPathKey(env);
|
||||
expect(env.PATH).toBe('/correct');
|
||||
expect('Path' in env).toBe(false);
|
||||
expect('path' in env).toBe(false);
|
||||
});
|
||||
|
||||
it('should handle env with no PATH-like key gracefully', () => {
|
||||
const env: Record<string, string | undefined> = { HOME: '/home/user', SHELL: '/bin/zsh' };
|
||||
normalizeEnvPathKey(env);
|
||||
expect(env).toEqual({ HOME: '/home/user', SHELL: '/bin/zsh' });
|
||||
});
|
||||
|
||||
it('should return the same env object reference (mutates in place)', () => {
|
||||
const env: Record<string, string | undefined> = { PATH: '/usr/bin' };
|
||||
const result = normalizeEnvPathKey(env);
|
||||
expect(result).toBe(env);
|
||||
});
|
||||
});
|
||||
|
||||
describe('mergePythonEnvPath - Windows PATH merge logic (#1661)', () => {
|
||||
const SEP = ';'; // Use Windows separator for these tests
|
||||
|
||||
it('should prepend pythonEnv-only entries to the augmented PATH', () => {
|
||||
const env: Record<string, string | undefined> = {
|
||||
PATH: 'C:\\npm;C:\\homebrew'
|
||||
};
|
||||
const mergedPythonEnv: Record<string, string | undefined> = {
|
||||
PATH: 'C:\\pywin32_system32;C:\\npm;C:\\homebrew'
|
||||
};
|
||||
|
||||
mergePythonEnvPath(env, mergedPythonEnv, SEP);
|
||||
|
||||
// pywin32_system32 is unique to pythonEnv, so it should be prepended
|
||||
expect(mergedPythonEnv.PATH).toBe('C:\\pywin32_system32;C:\\npm;C:\\homebrew');
|
||||
});
|
||||
|
||||
it('should deduplicate entries that already exist in augmented PATH', () => {
|
||||
const env: Record<string, string | undefined> = {
|
||||
PATH: 'C:\\npm;C:\\homebrew;C:\\pywin32_system32'
|
||||
};
|
||||
const mergedPythonEnv: Record<string, string | undefined> = {
|
||||
PATH: 'C:\\pywin32_system32;C:\\npm'
|
||||
};
|
||||
|
||||
mergePythonEnvPath(env, mergedPythonEnv, SEP);
|
||||
|
||||
// All pythonEnv entries are already in env.PATH, so mergedPythonEnv.PATH should equal env.PATH
|
||||
expect(mergedPythonEnv.PATH).toBe('C:\\npm;C:\\homebrew;C:\\pywin32_system32');
|
||||
});
|
||||
|
||||
it('should normalize Windows-style "Path" key in pythonEnv to "PATH"', () => {
|
||||
const env: Record<string, string | undefined> = {
|
||||
PATH: 'C:\\npm;C:\\homebrew'
|
||||
};
|
||||
// pythonEnv uses 'Path' (Windows native casing)
|
||||
const mergedPythonEnv: Record<string, string | undefined> = {
|
||||
Path: 'C:\\pywin32_system32;C:\\npm'
|
||||
};
|
||||
|
||||
mergePythonEnvPath(env, mergedPythonEnv, SEP);
|
||||
|
||||
// 'Path' should be normalized to 'PATH' and pythonEnv-specific entry prepended
|
||||
expect('Path' in mergedPythonEnv).toBe(false);
|
||||
expect(mergedPythonEnv.PATH).toBe('C:\\pywin32_system32;C:\\npm;C:\\homebrew');
|
||||
});
|
||||
|
||||
it('should normalize Windows-style "Path" in env and deduplicate duplicates', () => {
|
||||
// Simulates process.env spread ('Path') + getAugmentedEnv write ('PATH') leaving both
|
||||
const env: Record<string, string | undefined> = {
|
||||
Path: 'C:\\old',
|
||||
PATH: 'C:\\npm;C:\\homebrew'
|
||||
};
|
||||
const mergedPythonEnv: Record<string, string | undefined> = {
|
||||
PATH: 'C:\\pywin32_system32;C:\\npm'
|
||||
};
|
||||
|
||||
mergePythonEnvPath(env, mergedPythonEnv, SEP);
|
||||
|
||||
// env 'Path' should be removed; augmented 'PATH' value preserved
|
||||
expect('Path' in env).toBe(false);
|
||||
expect(env.PATH).toBe('C:\\npm;C:\\homebrew');
|
||||
// Only the unique pywin32_system32 entry prepended
|
||||
expect(mergedPythonEnv.PATH).toBe('C:\\pywin32_system32;C:\\npm;C:\\homebrew');
|
||||
});
|
||||
|
||||
it('should use env.PATH unchanged when pythonEnv has no unique entries', () => {
|
||||
const env: Record<string, string | undefined> = {
|
||||
PATH: 'C:\\npm;C:\\homebrew'
|
||||
};
|
||||
const mergedPythonEnv: Record<string, string | undefined> = {
|
||||
PATH: 'C:\\npm;C:\\homebrew'
|
||||
};
|
||||
|
||||
mergePythonEnvPath(env, mergedPythonEnv, SEP);
|
||||
|
||||
expect(mergedPythonEnv.PATH).toBe('C:\\npm;C:\\homebrew');
|
||||
});
|
||||
|
||||
it('should work correctly with Unix colon separator', () => {
|
||||
const unixSep = ':';
|
||||
const env: Record<string, string | undefined> = {
|
||||
PATH: '/usr/bin:/bin'
|
||||
};
|
||||
const mergedPythonEnv: Record<string, string | undefined> = {
|
||||
PATH: '/opt/pyenv/shims:/usr/bin:/bin'
|
||||
};
|
||||
|
||||
mergePythonEnvPath(env, mergedPythonEnv, unixSep);
|
||||
|
||||
// /opt/pyenv/shims is unique and should be prepended
|
||||
expect(mergedPythonEnv.PATH).toBe('/opt/pyenv/shims:/usr/bin:/bin');
|
||||
});
|
||||
|
||||
it('should handle missing PATH in pythonEnv gracefully (no-op)', () => {
|
||||
const env: Record<string, string | undefined> = {
|
||||
PATH: 'C:\\npm;C:\\homebrew'
|
||||
};
|
||||
// pythonEnv has no PATH at all
|
||||
const mergedPythonEnv: Record<string, string | undefined> = {
|
||||
PYTHONPATH: '/site-packages'
|
||||
};
|
||||
|
||||
mergePythonEnvPath(env, mergedPythonEnv, SEP);
|
||||
|
||||
// Nothing should change
|
||||
expect(mergedPythonEnv.PATH).toBeUndefined();
|
||||
expect(mergedPythonEnv.PYTHONPATH).toBe('/site-packages');
|
||||
expect(env.PATH).toBe('C:\\npm;C:\\homebrew');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,6 +2,88 @@
|
||||
* Utility functions for managing environment variables in agent spawning
|
||||
*/
|
||||
|
||||
/**
|
||||
* Normalize the PATH key in an environment object to a single uppercase 'PATH' key.
|
||||
*
|
||||
* On Windows, process.env spreads as 'Path' (the native casing) while getAugmentedEnv()
|
||||
* writes 'PATH'. Without normalization, both keys coexist in the object and the child
|
||||
* process receives duplicate PATH entries, causing tool-not-found errors like #1661.
|
||||
*
|
||||
* Mutates the provided env object in place and returns it for convenience.
|
||||
*
|
||||
* @param env - Mutable environment record to normalize
|
||||
* @returns The same env object with PATH normalized to uppercase
|
||||
*/
|
||||
export function normalizeEnvPathKey(env: Record<string, string | undefined>): Record<string, string | undefined> {
|
||||
// If 'PATH' already exists, delete all other case-variant keys (e.g. 'Path')
|
||||
if ('PATH' in env) {
|
||||
for (const key of Object.keys(env)) {
|
||||
if (key !== 'PATH' && key.toUpperCase() === 'PATH') {
|
||||
delete env[key];
|
||||
}
|
||||
}
|
||||
return env;
|
||||
}
|
||||
|
||||
// No uppercase 'PATH' key - find the first case-variant and rename it
|
||||
const pathKey = Object.keys(env).find(k => k.toUpperCase() === 'PATH');
|
||||
if (pathKey) {
|
||||
env['PATH'] = env[pathKey];
|
||||
delete env[pathKey];
|
||||
// Remove any remaining case-variant keys
|
||||
for (const key of Object.keys(env)) {
|
||||
if (key !== 'PATH' && key.toUpperCase() === 'PATH') {
|
||||
delete env[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return env;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge pythonEnv PATH entries with the augmented PATH in env, deduplicating entries.
|
||||
*
|
||||
* pythonEnv may carry its own PATH (e.g. pywin32_system32 prepended on Windows).
|
||||
* Simply spreading pythonEnv after env would overwrite the augmented PATH (which
|
||||
* includes npm globals, Homebrew, etc.), causing "Claude code not found" (#1661).
|
||||
*
|
||||
* Strategy:
|
||||
* 1. Normalize PATH key casing in both env and pythonEnv to uppercase 'PATH'.
|
||||
* 2. Extract only pythonEnv PATH entries that are not already in env.PATH.
|
||||
* 3. Prepend those unique entries to env.PATH and store the result in pythonEnv.PATH.
|
||||
*
|
||||
* Mutates mergedPythonEnv in place (caller should pass a shallow copy if immutability is needed).
|
||||
*
|
||||
* @param env - The base environment (already augmented with tool paths)
|
||||
* @param mergedPythonEnv - Shallow copy of pythonEnv to merge PATH into
|
||||
* @param pathSep - Platform path separator (';' on Windows, ':' elsewhere)
|
||||
*/
|
||||
export function mergePythonEnvPath(
|
||||
env: Record<string, string | undefined>,
|
||||
mergedPythonEnv: Record<string, string | undefined>,
|
||||
pathSep: string
|
||||
): void {
|
||||
// Normalize PATH key to uppercase in both objects
|
||||
normalizeEnvPathKey(env);
|
||||
normalizeEnvPathKey(mergedPythonEnv);
|
||||
|
||||
if (mergedPythonEnv['PATH'] && env['PATH']) {
|
||||
const augmentedPathEntries = new Set(
|
||||
(env['PATH'] as string).split(pathSep).filter(Boolean)
|
||||
);
|
||||
// Extract only new entries from pythonEnv.PATH that aren't already in the augmented PATH
|
||||
const pythonPathEntries = (mergedPythonEnv['PATH'] as string)
|
||||
.split(pathSep)
|
||||
.filter(entry => entry && !augmentedPathEntries.has(entry));
|
||||
|
||||
// Prepend python-specific paths (e.g., pywin32_system32) to the augmented PATH
|
||||
mergedPythonEnv['PATH'] = pythonPathEntries.length > 0
|
||||
? [...pythonPathEntries, env['PATH'] as string].join(pathSep)
|
||||
: env['PATH'] as string;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get environment variables to clear ANTHROPIC_* vars when in OAuth mode
|
||||
*
|
||||
|
||||
@@ -88,16 +88,18 @@ function htmlToMarkdown(html: string): string {
|
||||
md = md.replace(/<br\s*\/?>/gi, '\n');
|
||||
md = md.replace(/<hr\s*\/?>/gi, '---\n\n');
|
||||
|
||||
// Remove any remaining HTML tags
|
||||
md = md.replace(/<[^>]+>/g, '');
|
||||
// Remove any remaining HTML tags (loop to handle nested tag fragments)
|
||||
while (/<[^>]+>/.test(md)) {
|
||||
md = md.replace(/<[^>]+>/g, '');
|
||||
}
|
||||
|
||||
// Decode common HTML entities
|
||||
md = md.replace(/&/g, '&');
|
||||
// Decode common HTML entities (& LAST to prevent double-unescaping like &lt; → < → <)
|
||||
md = md.replace(/</g, '<');
|
||||
md = md.replace(/>/g, '>');
|
||||
md = md.replace(/"/g, '"');
|
||||
md = md.replace(/'/g, "'");
|
||||
md = md.replace(/ /g, ' ');
|
||||
md = md.replace(/&/g, '&');
|
||||
|
||||
// Clean up excessive whitespace
|
||||
md = md.replace(/\n{3,}/g, '\n\n');
|
||||
|
||||
@@ -15,64 +15,122 @@ interface WatcherInfo {
|
||||
*/
|
||||
export class FileWatcher extends EventEmitter {
|
||||
private watchers: Map<string, WatcherInfo> = new Map();
|
||||
// Maps taskId -> specDir for the in-flight watch() call.
|
||||
// Allows re-watch calls with a different specDir to proceed while
|
||||
// still preventing duplicate calls for the exact same specDir.
|
||||
private pendingWatches: Map<string, string> = new Map();
|
||||
// Tracks taskIds that had unwatch() called while watch() was in-flight.
|
||||
// Checked after each await point in watch() to avoid creating a leaked watcher.
|
||||
private cancelledWatches: Set<string> = new Set();
|
||||
|
||||
/**
|
||||
* Start watching a task's implementation plan
|
||||
*/
|
||||
async watch(taskId: string, specDir: string): Promise<void> {
|
||||
// Stop any existing watcher for this task
|
||||
await this.unwatch(taskId);
|
||||
|
||||
const planPath = path.join(specDir, 'implementation_plan.json');
|
||||
|
||||
// Check if plan file exists
|
||||
if (!existsSync(planPath)) {
|
||||
this.emit('error', taskId, `Plan file not found: ${planPath}`);
|
||||
// Prevent overlapping watch() calls for the same taskId + specDir combination.
|
||||
// Since watch() is async, rapid-fire callers could enter concurrently
|
||||
// before the first call updates state, creating duplicate watchers.
|
||||
// A call with a different specDir is a legitimate re-watch and is allowed through.
|
||||
const pendingSpecDir = this.pendingWatches.get(taskId);
|
||||
if (pendingSpecDir !== undefined && pendingSpecDir === specDir) {
|
||||
return;
|
||||
}
|
||||
this.pendingWatches.set(taskId, specDir);
|
||||
|
||||
// Create watcher with settings to handle frequent writes
|
||||
const watcher = chokidar.watch(planPath, {
|
||||
persistent: true,
|
||||
ignoreInitial: true,
|
||||
awaitWriteFinish: {
|
||||
stabilityThreshold: 300,
|
||||
pollInterval: 100
|
||||
try {
|
||||
// Close any existing watcher for this task.
|
||||
// Delete from the map BEFORE awaiting close so that a concurrent watch()
|
||||
// call entering after the await cannot obtain the same FSWatcher reference
|
||||
// and attempt a second close() on the same object.
|
||||
const existing = this.watchers.get(taskId);
|
||||
if (existing) {
|
||||
this.watchers.delete(taskId);
|
||||
await existing.watcher.close();
|
||||
}
|
||||
});
|
||||
|
||||
// Store watcher info
|
||||
this.watchers.set(taskId, {
|
||||
taskId,
|
||||
watcher,
|
||||
planPath
|
||||
});
|
||||
// Check if a newer watch() call has superseded this one while we were awaiting.
|
||||
// If the pending specDir changed, another concurrent watch() took over — bail out
|
||||
// to avoid overwriting the watcher it is about to create.
|
||||
if (this.pendingWatches.get(taskId) !== specDir) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle file changes
|
||||
watcher.on('change', () => {
|
||||
// Check if unwatch() was called while we were awaiting above.
|
||||
if (this.cancelledWatches.has(taskId)) {
|
||||
this.cancelledWatches.delete(taskId);
|
||||
return;
|
||||
}
|
||||
|
||||
const planPath = path.join(specDir, 'implementation_plan.json');
|
||||
|
||||
// Check if plan file exists
|
||||
if (!existsSync(planPath)) {
|
||||
this.emit('error', taskId, `Plan file not found: ${planPath}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Create watcher with settings to handle frequent writes
|
||||
const watcher = chokidar.watch(planPath, {
|
||||
persistent: true,
|
||||
ignoreInitial: true,
|
||||
awaitWriteFinish: {
|
||||
stabilityThreshold: 300,
|
||||
pollInterval: 100
|
||||
}
|
||||
});
|
||||
|
||||
// Check again after the synchronous watcher creation (no await, but defensive).
|
||||
if (this.cancelledWatches.has(taskId)) {
|
||||
this.cancelledWatches.delete(taskId);
|
||||
await watcher.close();
|
||||
return;
|
||||
}
|
||||
|
||||
// Store watcher info
|
||||
this.watchers.set(taskId, {
|
||||
taskId,
|
||||
watcher,
|
||||
planPath
|
||||
});
|
||||
|
||||
// Handle file changes
|
||||
watcher.on('change', () => {
|
||||
try {
|
||||
const content = readFileSync(planPath, 'utf-8');
|
||||
const plan: ImplementationPlan = JSON.parse(content);
|
||||
this.emit('progress', taskId, plan);
|
||||
} catch {
|
||||
// File might be in the middle of being written
|
||||
// Ignore parse errors, next change event will have complete file
|
||||
}
|
||||
});
|
||||
|
||||
// Handle errors
|
||||
watcher.on('error', (error: unknown) => {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
this.emit('error', taskId, message);
|
||||
});
|
||||
|
||||
// Read and emit initial state
|
||||
try {
|
||||
const content = readFileSync(planPath, 'utf-8');
|
||||
const plan: ImplementationPlan = JSON.parse(content);
|
||||
this.emit('progress', taskId, plan);
|
||||
} catch {
|
||||
// File might be in the middle of being written
|
||||
// Ignore parse errors, next change event will have complete file
|
||||
// Initial read failed - not critical
|
||||
}
|
||||
} finally {
|
||||
// Only clean up if this call still owns the entry. If a superseding
|
||||
// concurrent watch() call has already updated pendingWatches with a
|
||||
// different specDir, leave that entry intact so the superseding call
|
||||
// can proceed correctly.
|
||||
if (this.pendingWatches.get(taskId) === specDir) {
|
||||
this.pendingWatches.delete(taskId);
|
||||
// The delete above guarantees has() is now false, so there is no
|
||||
// longer any in-flight watch() for this taskId. Clear the
|
||||
// cancellation flag so it doesn't linger for future watch() calls.
|
||||
this.cancelledWatches.delete(taskId);
|
||||
}
|
||||
});
|
||||
|
||||
// Handle errors
|
||||
watcher.on('error', (error: unknown) => {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
this.emit('error', taskId, message);
|
||||
});
|
||||
|
||||
// Read and emit initial state
|
||||
try {
|
||||
const content = readFileSync(planPath, 'utf-8');
|
||||
const plan: ImplementationPlan = JSON.parse(content);
|
||||
this.emit('progress', taskId, plan);
|
||||
} catch {
|
||||
// Initial read failed - not critical
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,6 +138,13 @@ export class FileWatcher extends EventEmitter {
|
||||
* Stop watching a task
|
||||
*/
|
||||
async unwatch(taskId: string): Promise<void> {
|
||||
// If watch() is currently in-flight for this taskId, it is already closing the
|
||||
// existing watcher. Just set the cancellation flag and return to avoid a
|
||||
// double-close of the same FSWatcher.
|
||||
if (this.pendingWatches.has(taskId)) {
|
||||
this.cancelledWatches.add(taskId);
|
||||
return;
|
||||
}
|
||||
const watcherInfo = this.watchers.get(taskId);
|
||||
if (watcherInfo) {
|
||||
await watcherInfo.watcher.close();
|
||||
@@ -91,6 +156,17 @@ export class FileWatcher extends EventEmitter {
|
||||
* Stop all watchers
|
||||
*/
|
||||
async unwatchAll(): Promise<void> {
|
||||
// Cancel any in-flight watch() calls so they don't create new watchers
|
||||
// after this cleanup completes.
|
||||
for (const taskId of this.pendingWatches.keys()) {
|
||||
this.cancelledWatches.add(taskId);
|
||||
}
|
||||
this.pendingWatches.clear();
|
||||
// Clear cancellation flags now that pendingWatches is empty: the in-flight
|
||||
// calls will bail via the supersession check (pendingWatches.get() returns
|
||||
// undefined) and will not clean up cancelledWatches themselves. Clearing
|
||||
// here ensures the instance is fully reset for subsequent use.
|
||||
this.cancelledWatches.clear();
|
||||
const closePromises = Array.from(this.watchers.values()).map(
|
||||
async (info) => {
|
||||
await info.watcher.close();
|
||||
@@ -107,6 +183,15 @@ export class FileWatcher extends EventEmitter {
|
||||
return this.watchers.has(taskId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the spec directory currently being watched for a task
|
||||
*/
|
||||
getWatchedSpecDir(taskId: string): string | null {
|
||||
const watcherInfo = this.watchers.get(taskId);
|
||||
if (!watcherInfo) return null;
|
||||
return path.dirname(watcherInfo.planPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current plan state for a task
|
||||
*/
|
||||
|
||||
@@ -98,7 +98,23 @@ export function registerAgenteventsHandlers(
|
||||
|
||||
// Send final plan state to renderer BEFORE unwatching
|
||||
// This ensures the renderer has the final subtask data (fixes 0/0 subtask bug)
|
||||
const finalPlan = fileWatcher.getCurrentPlan(taskId);
|
||||
// Try the file watcher's current path first, then fall back to worktree path
|
||||
let finalPlan = fileWatcher.getCurrentPlan(taskId);
|
||||
if (!finalPlan && exitTask && exitProject) {
|
||||
// File watcher may have been watching the wrong path (main vs worktree)
|
||||
// Try reading directly from the worktree
|
||||
const worktreePath = findTaskWorktree(exitProject.path, exitTask.specId);
|
||||
if (worktreePath) {
|
||||
const specsBaseDir = getSpecsDir(exitProject.autoBuildPath);
|
||||
const worktreePlanPath = path.join(worktreePath, specsBaseDir, exitTask.specId, AUTO_BUILD_PATHS.IMPLEMENTATION_PLAN);
|
||||
try {
|
||||
const content = readFileSync(worktreePlanPath, 'utf-8');
|
||||
finalPlan = JSON.parse(content);
|
||||
} catch {
|
||||
// Worktree plan file not readable - not critical
|
||||
}
|
||||
}
|
||||
}
|
||||
if (finalPlan) {
|
||||
safeSendToRenderer(
|
||||
getMainWindow,
|
||||
@@ -109,7 +125,9 @@ export function registerAgenteventsHandlers(
|
||||
);
|
||||
}
|
||||
|
||||
fileWatcher.unwatch(taskId);
|
||||
fileWatcher.unwatch(taskId).catch((err) => {
|
||||
console.error(`[agent-events-handlers] Failed to unwatch for ${taskId}:`, err);
|
||||
});
|
||||
|
||||
if (processType === "spec-creation") {
|
||||
console.warn(`[Task ${taskId}] Spec creation completed with code ${code}`);
|
||||
@@ -211,15 +229,26 @@ export function registerAgenteventsHandlers(
|
||||
const worktreePath = findTaskWorktree(project.path, task.specId);
|
||||
if (worktreePath) {
|
||||
const specsBaseDir = getSpecsDir(project.autoBuildPath);
|
||||
const worktreeSpecDir = path.join(worktreePath, specsBaseDir, task.specId);
|
||||
const worktreePlanPath = path.join(
|
||||
worktreePath,
|
||||
specsBaseDir,
|
||||
task.specId,
|
||||
worktreeSpecDir,
|
||||
AUTO_BUILD_PATHS.IMPLEMENTATION_PLAN
|
||||
);
|
||||
if (existsSync(worktreePlanPath)) {
|
||||
persistPlanPhaseSync(worktreePlanPath, progress.phase, project.id);
|
||||
}
|
||||
|
||||
// Re-watch the worktree path if the file watcher is still watching the main project path.
|
||||
// This handles the case where the task started before the worktree existed:
|
||||
// the initial watch fell back to the main project spec dir, but now the worktree
|
||||
// is available and implementation_plan.json is being written there.
|
||||
const currentWatchDir = fileWatcher.getWatchedSpecDir(taskId);
|
||||
if (currentWatchDir && currentWatchDir !== worktreeSpecDir && existsSync(worktreePlanPath)) {
|
||||
console.warn(`[agent-events-handlers] Re-watching worktree path for ${taskId}: ${worktreeSpecDir}`);
|
||||
fileWatcher.watch(taskId, worktreeSpecDir).catch((err) => {
|
||||
console.error(`[agent-events-handlers] Failed to re-watch worktree for ${taskId}:`, err);
|
||||
});
|
||||
}
|
||||
}
|
||||
} else if (xstateInTerminalState && progress.phase) {
|
||||
console.debug(`[agent-events-handlers] Skipping persistPlanPhaseSync for ${taskId}: XState in '${currentXState}', not overwriting with phase '${progress.phase}'`);
|
||||
|
||||
@@ -1499,6 +1499,19 @@ async function runPRReview(
|
||||
// Build environment with project settings
|
||||
const subprocessEnv = await getRunnerEnv(getClaudeMdEnv(project));
|
||||
|
||||
safeBreadcrumb({
|
||||
category: 'github.pr-review',
|
||||
message: `Subprocess env for PR #${prNumber} review`,
|
||||
level: 'info',
|
||||
data: {
|
||||
prNumber,
|
||||
hasGITHUB_CLI_PATH: !!subprocessEnv.GITHUB_CLI_PATH,
|
||||
GITHUB_CLI_PATH: subprocessEnv.GITHUB_CLI_PATH ?? 'NOT SET',
|
||||
hasGITHUB_TOKEN: !!subprocessEnv.GITHUB_TOKEN,
|
||||
hasPYTHONPATH: !!subprocessEnv.PYTHONPATH,
|
||||
},
|
||||
});
|
||||
|
||||
// Create operation ID for this review
|
||||
const reviewKey = getReviewKey(project.id, prNumber);
|
||||
|
||||
@@ -2028,7 +2041,7 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
|
||||
},
|
||||
projectId
|
||||
);
|
||||
sendError(error instanceof Error ? error.message : "Failed to run PR review");
|
||||
sendError({ prNumber, error: error instanceof Error ? error.message : "Failed to run PR review" });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -3015,6 +3028,19 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
|
||||
// Build environment with project settings
|
||||
const followupEnv = await getRunnerEnv(getClaudeMdEnv(project));
|
||||
|
||||
safeBreadcrumb({
|
||||
category: 'github.pr-review',
|
||||
message: `Subprocess env for PR #${prNumber} follow-up review`,
|
||||
level: 'info',
|
||||
data: {
|
||||
prNumber,
|
||||
hasGITHUB_CLI_PATH: !!followupEnv.GITHUB_CLI_PATH,
|
||||
GITHUB_CLI_PATH: followupEnv.GITHUB_CLI_PATH ?? 'NOT SET',
|
||||
hasGITHUB_TOKEN: !!followupEnv.GITHUB_TOKEN,
|
||||
hasPYTHONPATH: !!followupEnv.PYTHONPATH,
|
||||
},
|
||||
});
|
||||
|
||||
const { process: childProcess, promise } = runPythonSubprocess<PRReviewResult>({
|
||||
pythonPath: getPythonPath(backendPath),
|
||||
args,
|
||||
|
||||
@@ -30,6 +30,15 @@ vi.mock('../../utils', () => ({
|
||||
getGitHubTokenForSubprocess: () => mockGetGitHubTokenForSubprocess(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../../cli-tool-manager', () => ({
|
||||
getToolInfo: () => ({ found: false, path: undefined, source: undefined }),
|
||||
}));
|
||||
|
||||
vi.mock('../../../../sentry', () => ({
|
||||
getSentryEnvForSubprocess: () => ({}),
|
||||
safeBreadcrumb: () => {},
|
||||
}));
|
||||
|
||||
import { getRunnerEnv } from '../runner-env';
|
||||
|
||||
describe('getRunnerEnv', () => {
|
||||
|
||||
@@ -3,7 +3,8 @@ import { getAPIProfileEnv } from '../../../services/profile';
|
||||
import { getBestAvailableProfileEnv } from '../../../rate-limit-detector';
|
||||
import { pythonEnvManager } from '../../../python-env-manager';
|
||||
import { getGitHubTokenForSubprocess } from '../utils';
|
||||
import { getSentryEnvForSubprocess } from '../../../sentry';
|
||||
import { getSentryEnvForSubprocess, safeBreadcrumb } from '../../../sentry';
|
||||
import { getToolInfo } from '../../../cli-tool-manager';
|
||||
|
||||
/**
|
||||
* Get environment variables for Python runner subprocesses.
|
||||
@@ -43,12 +44,30 @@ export async function getRunnerEnv(
|
||||
const githubToken = await getGitHubTokenForSubprocess();
|
||||
const githubEnv: Record<string, string> = githubToken ? { GITHUB_TOKEN: githubToken } : {};
|
||||
|
||||
// Resolve gh CLI path so Python subprocess can find it in bundled apps
|
||||
// (bundled Electron apps have a stripped PATH that doesn't include Homebrew etc.)
|
||||
const ghInfo = getToolInfo('gh');
|
||||
const ghCliEnv: Record<string, string> = ghInfo.found && ghInfo.path ? { GITHUB_CLI_PATH: ghInfo.path } : {};
|
||||
safeBreadcrumb({
|
||||
category: 'github.runner-env',
|
||||
message: `gh CLI for subprocess: found=${ghInfo.found}, path=${ghInfo.path ?? 'none'}, source=${ghInfo.source ?? 'none'}`,
|
||||
level: ghInfo.found ? 'info' : 'warning',
|
||||
data: {
|
||||
found: ghInfo.found,
|
||||
path: ghInfo.path ?? null,
|
||||
source: ghInfo.source ?? null,
|
||||
willSetGITHUB_CLI_PATH: !!(ghInfo.found && ghInfo.path),
|
||||
hasGITHUB_TOKEN: !!githubToken,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
...pythonEnv, // Python environment including PYTHONPATH (fixes #139)
|
||||
...apiProfileEnv,
|
||||
...oauthModeClearVars,
|
||||
...profileEnv, // OAuth token from profile manager (fixes #563, rate-limit aware)
|
||||
...githubEnv, // Fresh GitHub token from gh CLI (fixes #151)
|
||||
...ghCliEnv, // gh CLI path for bundled apps (Python backend uses GITHUB_CLI_PATH)
|
||||
...getSentryEnvForSubprocess(), // Sentry DSN + sample rates for Python subprocess
|
||||
...extraEnv, // extraEnv last so callers can still override
|
||||
};
|
||||
|
||||
@@ -20,7 +20,8 @@ import { isWindows, isMacOS } from '../../../platform';
|
||||
import { getEffectiveSourcePath } from '../../../updater/path-resolver';
|
||||
import { pythonEnvManager, getConfiguredPythonPath } from '../../../python-env-manager';
|
||||
import { getTaskkillExePath, getWhereExePath } from '../../../utils/windows-paths';
|
||||
import { safeCaptureException } from '../../../sentry';
|
||||
import { safeCaptureException, safeBreadcrumb } from '../../../sentry';
|
||||
import { getToolInfo } from '../../../cli-tool-manager';
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
const execFileAsync = promisify(execFile);
|
||||
@@ -559,6 +560,7 @@ export interface GitHubModuleValidation {
|
||||
pythonEnvValid: boolean;
|
||||
error?: string;
|
||||
backendPath?: string;
|
||||
ghCliPath?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -622,33 +624,36 @@ export async function validateGitHubModule(project: Project): Promise<GitHubModu
|
||||
return result;
|
||||
}
|
||||
|
||||
// 2. Check gh CLI installation (cross-platform)
|
||||
try {
|
||||
if (isWindows()) {
|
||||
await execFileAsync(getWhereExePath(), ['gh'], { timeout: 5000 });
|
||||
} else {
|
||||
await execAsync('which gh');
|
||||
}
|
||||
// 2. Check gh CLI installation (uses CLI tool manager for bundled app compatibility)
|
||||
const ghInfo = getToolInfo('gh');
|
||||
safeBreadcrumb({
|
||||
category: 'github.validation',
|
||||
message: `gh CLI lookup: found=${ghInfo.found}, path=${ghInfo.path ?? 'none'}, source=${ghInfo.source ?? 'none'}`,
|
||||
level: ghInfo.found ? 'info' : 'warning',
|
||||
data: { found: ghInfo.found, path: ghInfo.path ?? null, source: ghInfo.source ?? null },
|
||||
});
|
||||
if (ghInfo.found && ghInfo.path) {
|
||||
result.ghCliInstalled = true;
|
||||
} catch (error: unknown) {
|
||||
result.ghCliPath = ghInfo.path;
|
||||
} else {
|
||||
result.ghCliInstalled = false;
|
||||
const errCode = (error as NodeJS.ErrnoException).code;
|
||||
if (errCode === 'ENOENT' && isWindows()) {
|
||||
result.error = `System utility 'where.exe' not found. Check Windows installation.`;
|
||||
} else {
|
||||
const installInstructions = isWindows()
|
||||
? 'winget install --id GitHub.cli'
|
||||
: isMacOS()
|
||||
? 'brew install gh'
|
||||
: 'See https://cli.github.com/';
|
||||
result.error = `GitHub CLI (gh) is not installed. Install it with:\n ${installInstructions}`;
|
||||
}
|
||||
const installInstructions = isWindows()
|
||||
? 'winget install --id GitHub.cli'
|
||||
: isMacOS()
|
||||
? 'brew install gh'
|
||||
: 'See https://cli.github.com/';
|
||||
result.error = `GitHub CLI (gh) is not installed. Install it with:\n ${installInstructions}`;
|
||||
safeCaptureException(new Error('gh CLI not found in bundled app'), {
|
||||
tags: { component: 'github-validation' },
|
||||
extra: { ghInfo, isPackaged: require('electron').app?.isPackaged ?? 'unknown' },
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
// 3. Check gh authentication
|
||||
// 3. Check gh authentication (use resolved path for bundled app compatibility)
|
||||
try {
|
||||
await execAsync('gh auth status 2>&1');
|
||||
const ghPath = result.ghCliPath || 'gh';
|
||||
await execAsync(`"${ghPath}" auth status 2>&1`);
|
||||
result.ghAuthenticated = true;
|
||||
} catch (error: any) {
|
||||
// gh auth status returns non-zero when not authenticated
|
||||
|
||||
@@ -153,16 +153,24 @@ function getGitBranchesWithInfo(projectPath: string): GitBranchDetail[] {
|
||||
.map(b => b.trim())
|
||||
// Remove HEAD pointer entries like "origin/HEAD"
|
||||
.filter(b => !b.endsWith('/HEAD'))
|
||||
.map(name => ({
|
||||
name,
|
||||
type: 'remote' as const,
|
||||
displayName: name,
|
||||
isCurrent: false
|
||||
}));
|
||||
.map(fullName => {
|
||||
// Strip "origin/" prefix so branch names are clean for PR targets etc.
|
||||
const name = fullName.replace(/^origin\//, '');
|
||||
return {
|
||||
name,
|
||||
type: 'remote' as const,
|
||||
displayName: name,
|
||||
isCurrent: false
|
||||
};
|
||||
});
|
||||
} catch {
|
||||
// Remote branches may not exist, continue with local only
|
||||
}
|
||||
|
||||
// Deduplicate: if a branch exists locally and remotely, keep only the local entry
|
||||
const localNames = new Set(localBranches.map(b => b.name));
|
||||
remoteBranches = remoteBranches.filter(b => !localNames.has(b.name));
|
||||
|
||||
// Combine and sort: local branches first, then remote branches, alphabetically within each group
|
||||
const allBranches = [...localBranches, ...remoteBranches];
|
||||
|
||||
|
||||
@@ -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
|
||||
// ============================================
|
||||
|
||||
@@ -81,6 +81,22 @@ async function ensureProfileManagerInitialized(): Promise<
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the spec directory for file watching, preferring the worktree path if it exists.
|
||||
* When a task runs in a worktree, implementation_plan.json is written there,
|
||||
* not in the main project's spec directory.
|
||||
*/
|
||||
function getSpecDirForWatcher(projectPath: string, specsBaseDir: string, specId: string): string {
|
||||
const worktreePath = findTaskWorktree(projectPath, specId);
|
||||
if (worktreePath) {
|
||||
const worktreeSpecDir = path.join(worktreePath, specsBaseDir, specId);
|
||||
if (existsSync(path.join(worktreeSpecDir, 'implementation_plan.json'))) {
|
||||
return worktreeSpecDir;
|
||||
}
|
||||
}
|
||||
return path.join(projectPath, specsBaseDir, specId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register task execution handlers (start, stop, review, status management, recovery)
|
||||
*/
|
||||
@@ -161,6 +177,31 @@ export function registerTaskExecutionHandlers(
|
||||
|
||||
console.warn('[TASK_START] Found task:', task.specId, 'status:', task.status, 'reviewReason:', task.reviewReason, 'subtasks:', task.subtasks.length);
|
||||
|
||||
// Clear stale tracking state from any previous execution so that:
|
||||
// - terminalEventSeen doesn't suppress future PROCESS_EXITED events
|
||||
// - lastSequenceByTask doesn't drop events from the new process
|
||||
taskStateManager.prepareForRestart(taskId);
|
||||
|
||||
// Check if implementation_plan.json has valid subtasks BEFORE XState handling.
|
||||
// This is more reliable than task.subtasks.length which may not be loaded yet.
|
||||
const specsBaseDir = getSpecsDir(project.autoBuildPath);
|
||||
const specDir = path.join(
|
||||
project.path,
|
||||
specsBaseDir,
|
||||
task.specId
|
||||
);
|
||||
const planFilePath = path.join(specDir, AUTO_BUILD_PATHS.IMPLEMENTATION_PLAN);
|
||||
let planHasSubtasks = false;
|
||||
const planContent = safeReadFileSync(planFilePath);
|
||||
if (planContent) {
|
||||
try {
|
||||
const plan = JSON.parse(planContent);
|
||||
planHasSubtasks = checkSubtasksCompletion(plan).totalCount > 0;
|
||||
} catch {
|
||||
// Invalid/corrupt plan file - treat as no subtasks
|
||||
}
|
||||
}
|
||||
|
||||
// Immediately mark as started so the UI moves the card to In Progress.
|
||||
// Use XState actor state as source of truth (if actor exists), with task data as fallback.
|
||||
// - plan_review: User approved the plan, send PLAN_APPROVED to transition to coding
|
||||
@@ -173,6 +214,11 @@ export function registerTaskExecutionHandlers(
|
||||
// XState says plan_review - send PLAN_APPROVED
|
||||
console.warn('[TASK_START] XState: plan_review -> coding via PLAN_APPROVED');
|
||||
taskStateManager.handleUiEvent(taskId, { type: 'PLAN_APPROVED' }, task, project);
|
||||
} else if (currentXState === 'error' && !planHasSubtasks) {
|
||||
// FIX (#1562): Task crashed during planning (no subtasks yet).
|
||||
// Uses planHasSubtasks from implementation_plan.json (more reliable than task.subtasks.length).
|
||||
console.warn('[TASK_START] XState: error with no plan subtasks -> planning via PLANNING_STARTED');
|
||||
taskStateManager.handleUiEvent(taskId, { type: 'PLANNING_STARTED' }, task, project);
|
||||
} else if (currentXState === 'human_review' || currentXState === 'error') {
|
||||
// XState says human_review or error - send USER_RESUMED
|
||||
console.warn('[TASK_START] XState:', currentXState, '-> coding via USER_RESUMED');
|
||||
@@ -186,6 +232,11 @@ export function registerTaskExecutionHandlers(
|
||||
// No XState actor - fallback to task data (e.g., after app restart)
|
||||
console.warn('[TASK_START] No XState actor, task data: plan_review -> coding via PLAN_APPROVED');
|
||||
taskStateManager.handleUiEvent(taskId, { type: 'PLAN_APPROVED' }, task, project);
|
||||
} else if (task.status === 'error' && !planHasSubtasks) {
|
||||
// FIX (#1562): No XState actor, task crashed during planning (no subtasks).
|
||||
// Uses planHasSubtasks from implementation_plan.json (more reliable than task.subtasks.length).
|
||||
console.warn('[TASK_START] No XState actor, error with no plan subtasks -> planning via PLANNING_STARTED');
|
||||
taskStateManager.handleUiEvent(taskId, { type: 'PLANNING_STARTED' }, task, project);
|
||||
} else if (task.status === 'human_review' || task.status === 'error') {
|
||||
// No XState actor - fallback to task data for resuming
|
||||
console.warn('[TASK_START] No XState actor, task data:', task.status, '-> coding via USER_RESUMED');
|
||||
@@ -205,24 +256,27 @@ export function registerTaskExecutionHandlers(
|
||||
}
|
||||
|
||||
// Start file watcher for this task
|
||||
const specsBaseDir = getSpecsDir(project.autoBuildPath);
|
||||
const specDir = path.join(
|
||||
project.path,
|
||||
specsBaseDir,
|
||||
task.specId
|
||||
);
|
||||
fileWatcher.watch(taskId, specDir);
|
||||
// Use worktree path if it exists, since the backend writes implementation_plan.json there
|
||||
const watchSpecDir = getSpecDirForWatcher(project.path, specsBaseDir, task.specId);
|
||||
fileWatcher.watch(taskId, watchSpecDir).catch((err) => {
|
||||
console.error(`[TASK_START] Failed to watch spec dir for ${taskId}:`, err);
|
||||
});
|
||||
|
||||
// Check if spec.md exists (indicates spec creation was already done or in progress)
|
||||
// Check main project path for spec file (spec is created before worktree)
|
||||
const specFilePath = path.join(specDir, AUTO_BUILD_PATHS.SPEC_FILE);
|
||||
const hasSpec = existsSync(specFilePath);
|
||||
|
||||
// Check if this task needs spec creation first (no spec file = not yet created)
|
||||
// OR if it has a spec but no implementation plan subtasks (spec created, needs planning/building)
|
||||
const needsSpecCreation = !hasSpec;
|
||||
const needsImplementation = hasSpec && task.subtasks.length === 0;
|
||||
// FIX (#1562): Check actual plan file for subtasks, not just task.subtasks.length.
|
||||
// When a task crashes during planning, it may have spec.md but an empty/missing
|
||||
// implementation_plan.json. Previously, this path would call startTaskExecution
|
||||
// (run.py) which expects subtasks to exist. Now we check the actual plan file.
|
||||
const needsImplementation = hasSpec && !planHasSubtasks;
|
||||
|
||||
console.warn('[TASK_START] hasSpec:', hasSpec, 'needsSpecCreation:', needsSpecCreation, 'needsImplementation:', needsImplementation);
|
||||
console.warn('[TASK_START] hasSpec:', hasSpec, 'planHasSubtasks:', planHasSubtasks, 'needsSpecCreation:', needsSpecCreation, 'needsImplementation:', needsImplementation);
|
||||
|
||||
// Get base branch: task-level override takes precedence over project settings
|
||||
const baseBranch = task.metadata?.baseBranch || project.settings?.mainBranch;
|
||||
@@ -237,18 +291,12 @@ export function registerTaskExecutionHandlers(
|
||||
// Also pass baseBranch so worktrees are created from the correct branch
|
||||
agentManager.startSpecCreation(taskId, project.path, taskDescription, specDir, task.metadata, baseBranch, project.id);
|
||||
} else if (needsImplementation) {
|
||||
// Spec exists but no subtasks - run run.py to create implementation plan and execute
|
||||
// Read the spec.md to get the task description
|
||||
const _taskDescription = task.description || task.title;
|
||||
try {
|
||||
readFileSync(specFilePath, 'utf-8');
|
||||
} catch {
|
||||
// Use default description
|
||||
}
|
||||
|
||||
console.warn('[TASK_START] Starting task execution (no subtasks) for:', task.specId);
|
||||
// Start task execution which will create the implementation plan
|
||||
// Note: No parallel mode for planning phase - parallel only makes sense with multiple subtasks
|
||||
// Spec exists but no valid subtasks in implementation plan
|
||||
// FIX (#1562): Use startTaskExecution (run.py) which will create the planner
|
||||
// agent session to generate the implementation plan. run.py handles the case
|
||||
// where implementation_plan.json is missing or has no subtasks - the planner
|
||||
// agent will generate the plan before the coder starts.
|
||||
console.warn('[TASK_START] Starting task execution (no valid subtasks in plan) for:', task.specId);
|
||||
agentManager.startTaskExecution(
|
||||
taskId,
|
||||
project.path,
|
||||
@@ -289,7 +337,9 @@ export function registerTaskExecutionHandlers(
|
||||
*/
|
||||
ipcMain.on(IPC_CHANNELS.TASK_STOP, (_, taskId: string) => {
|
||||
agentManager.killTask(taskId);
|
||||
fileWatcher.unwatch(taskId);
|
||||
fileWatcher.unwatch(taskId).catch((err) => {
|
||||
console.error('[TASK_STOP] Failed to unwatch:', err);
|
||||
});
|
||||
|
||||
// Find task and project to emit USER_STOPPED with plan context
|
||||
const { task, project } = findTaskAndProject(taskId);
|
||||
@@ -315,6 +365,9 @@ export function registerTaskExecutionHandlers(
|
||||
task,
|
||||
project
|
||||
);
|
||||
|
||||
// Clear stale tracking state so a subsequent restart works correctly
|
||||
taskStateManager.prepareForRestart(taskId);
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -484,6 +537,9 @@ export function registerTaskExecutionHandlers(
|
||||
return { success: false, error: 'Failed to write QA fix request file' };
|
||||
}
|
||||
|
||||
// Clear stale tracking state before starting new QA process
|
||||
taskStateManager.prepareForRestart(taskId);
|
||||
|
||||
// Restart QA process - use worktree path if it exists, otherwise main project
|
||||
// The QA process needs to run where the implementation_plan.json with completed subtasks is
|
||||
const qaProjectPath = hasWorktree ? worktreePath : project.path;
|
||||
@@ -513,7 +569,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);
|
||||
@@ -525,13 +581,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 {
|
||||
@@ -658,6 +718,8 @@ export function registerTaskExecutionHandlers(
|
||||
|
||||
// Auto-start task when status changes to 'in_progress' and no process is running
|
||||
if (status === 'in_progress' && !agentManager.isRunning(taskId)) {
|
||||
// Clear stale tracking state before starting a new process
|
||||
taskStateManager.prepareForRestart(taskId);
|
||||
const mainWindow = getMainWindow();
|
||||
|
||||
// Check git status before auto-starting
|
||||
@@ -710,13 +772,29 @@ export function registerTaskExecutionHandlers(
|
||||
}
|
||||
|
||||
// Start file watcher for this task
|
||||
fileWatcher.watch(taskId, specDir);
|
||||
// Use worktree path if it exists, since the backend writes implementation_plan.json there
|
||||
const watchSpecDir = getSpecDirForWatcher(project.path, specsBaseDir, task.specId);
|
||||
fileWatcher.watch(taskId, watchSpecDir).catch((err) => {
|
||||
console.error(`[TASK_UPDATE_STATUS] Failed to watch spec dir for ${taskId}:`, err);
|
||||
});
|
||||
|
||||
// Check if spec.md exists
|
||||
const specFilePath = path.join(specDir, AUTO_BUILD_PATHS.SPEC_FILE);
|
||||
const hasSpec = existsSync(specFilePath);
|
||||
const needsSpecCreation = !hasSpec;
|
||||
const needsImplementation = hasSpec && task.subtasks.length === 0;
|
||||
// FIX (#1562): Check actual plan file for subtasks, not just task.subtasks.length
|
||||
const updatePlanFilePath = path.join(specDir, AUTO_BUILD_PATHS.IMPLEMENTATION_PLAN);
|
||||
let updatePlanHasSubtasks = false;
|
||||
const updatePlanContent = safeReadFileSync(updatePlanFilePath);
|
||||
if (updatePlanContent) {
|
||||
try {
|
||||
const plan = JSON.parse(updatePlanContent);
|
||||
updatePlanHasSubtasks = checkSubtasksCompletion(plan).totalCount > 0;
|
||||
} catch {
|
||||
// Invalid/corrupt plan file - treat as no subtasks
|
||||
}
|
||||
}
|
||||
const needsImplementation = hasSpec && !updatePlanHasSubtasks;
|
||||
|
||||
console.warn('[TASK_UPDATE_STATUS] hasSpec:', hasSpec, 'needsSpecCreation:', needsSpecCreation, 'needsImplementation:', needsImplementation);
|
||||
|
||||
@@ -1065,11 +1143,15 @@ export function registerTaskExecutionHandlers(
|
||||
}
|
||||
|
||||
// Stop file watcher if it was watching this task
|
||||
fileWatcher.unwatch(taskId);
|
||||
fileWatcher.unwatch(taskId).catch((err) => {
|
||||
console.error('[TASK_RECOVER_STUCK] Failed to unwatch:', err);
|
||||
});
|
||||
|
||||
// Auto-restart the task if requested
|
||||
let autoRestarted = false;
|
||||
if (autoRestart) {
|
||||
// Clear stale tracking state before restarting
|
||||
taskStateManager.prepareForRestart(taskId);
|
||||
// Check git status before auto-restarting
|
||||
const gitStatusForRestart = checkGitStatus(project.path);
|
||||
if (!gitStatusForRestart.isGitRepo || !gitStatusForRestart.hasCommits) {
|
||||
@@ -1146,12 +1228,16 @@ export function registerTaskExecutionHandlers(
|
||||
|
||||
// Start the task execution
|
||||
// Start file watcher for this task
|
||||
const specsBaseDir = getSpecsDir(project.autoBuildPath);
|
||||
const specDirForWatcher = path.join(project.path, specsBaseDir, task.specId);
|
||||
fileWatcher.watch(taskId, specDirForWatcher);
|
||||
// Use worktree path if it exists, since the backend writes implementation_plan.json there
|
||||
const watchSpecDir = getSpecDirForWatcher(project.path, specsBaseDir, task.specId);
|
||||
fileWatcher.watch(taskId, watchSpecDir).catch((err) => {
|
||||
console.error(`[Recovery] Failed to watch spec dir for ${taskId}:`, err);
|
||||
});
|
||||
|
||||
// Check if spec.md exists to determine whether to run spec creation or task execution
|
||||
const specFilePath = path.join(specDirForWatcher, AUTO_BUILD_PATHS.SPEC_FILE);
|
||||
// Check main project path for spec file (spec is created before worktree)
|
||||
// mainSpecDir is declared earlier in the handler scope
|
||||
const specFilePath = path.join(mainSpecDir, AUTO_BUILD_PATHS.SPEC_FILE);
|
||||
const hasSpec = existsSync(specFilePath);
|
||||
const needsSpecCreation = !hasSpec;
|
||||
|
||||
@@ -1162,7 +1248,7 @@ export function registerTaskExecutionHandlers(
|
||||
// No spec file - need to run spec_runner.py to create the spec
|
||||
const taskDescription = task.description || task.title;
|
||||
console.warn(`[Recovery] Starting spec creation for: ${task.specId}`);
|
||||
agentManager.startSpecCreation(taskId, project.path, taskDescription, specDirForWatcher, task.metadata, baseBranchForRecovery, project.id);
|
||||
agentManager.startSpecCreation(taskId, project.path, taskDescription, mainSpecDir, task.metadata, baseBranchForRecovery, project.id);
|
||||
} else {
|
||||
// Spec exists - run task execution
|
||||
console.warn(`[Recovery] Starting task execution for: ${task.specId}`);
|
||||
|
||||
@@ -1370,7 +1370,9 @@ function getTaskBaseBranch(specDir: string): string | undefined {
|
||||
if (metadata.baseBranch &&
|
||||
metadata.baseBranch !== '__project_default__' &&
|
||||
GIT_BRANCH_REGEX.test(metadata.baseBranch)) {
|
||||
return metadata.baseBranch;
|
||||
// Strip remote prefix if present (e.g., "origin/feat/x" → "feat/x")
|
||||
const branch = metadata.baseBranch.replace(/^origin\//, '');
|
||||
return branch;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
|
||||
@@ -6,6 +6,7 @@ import { app } from 'electron';
|
||||
import { findPythonCommand, getBundledPythonPath } from './python-detector';
|
||||
import { isLinux, isWindows, getPathDelimiter } from './platform';
|
||||
import { getIsolatedGitEnv } from './utils/git-isolation';
|
||||
import { normalizeEnvPathKey } from './agent/env-utils';
|
||||
|
||||
export interface PythonEnvStatus {
|
||||
ready: boolean;
|
||||
@@ -726,17 +727,10 @@ if sys.version_info >= (3, 12):
|
||||
const pywin32System32 = path.join(this.sitePackagesPath, 'pywin32_system32');
|
||||
|
||||
// Add pywin32_system32 to PATH for DLL loading
|
||||
// Fix PATH case sensitivity: On Windows, env vars are case-insensitive but Node.js
|
||||
// preserves case. If we have both 'PATH' and 'Path', Node.js lexicographically sorts
|
||||
// and uses the first match, causing issues. Normalize to single 'PATH' key.
|
||||
// See: https://github.com/nodejs/node/issues/9157
|
||||
const pathKey = Object.keys(baseEnv).find(k => k.toUpperCase() === 'PATH');
|
||||
const currentPath = pathKey ? baseEnv[pathKey] : '';
|
||||
|
||||
// Remove any existing PATH variants to avoid duplicates
|
||||
if (pathKey && pathKey !== 'PATH') {
|
||||
delete baseEnv[pathKey];
|
||||
}
|
||||
// Normalize to single 'PATH' key before reading/writing, using the shared utility.
|
||||
// This prevents duplicate 'Path'/'PATH' keys that cause DLL-load failures on Windows.
|
||||
normalizeEnvPathKey(baseEnv);
|
||||
const currentPath = baseEnv['PATH'] ?? '';
|
||||
|
||||
if (currentPath && !currentPath.includes(pywin32System32)) {
|
||||
windowsEnv['PATH'] = `${pywin32System32};${currentPath}`;
|
||||
|
||||
@@ -169,6 +169,18 @@ export class TaskStateManager {
|
||||
return this.getCurrentState(taskId) === 'plan_review';
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset tracking state for a task that is about to be restarted.
|
||||
* Clears terminalEventSeen (so process exits aren't swallowed) and
|
||||
* lastSequenceByTask (so events from the new process aren't dropped
|
||||
* as duplicates). Does NOT stop or remove the XState actor, since
|
||||
* the caller may still need to send events to it.
|
||||
*/
|
||||
prepareForRestart(taskId: string): void {
|
||||
this.terminalEventSeen.delete(taskId);
|
||||
this.lastSequenceByTask.delete(taskId);
|
||||
}
|
||||
|
||||
clearTask(taskId: string): void {
|
||||
this.lastSequenceByTask.delete(taskId);
|
||||
this.lastStateByTask.delete(taskId);
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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),
|
||||
|
||||
|
||||
@@ -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,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}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
|
||||
|
||||
@@ -68,6 +68,7 @@ export function GitHubPRs({ onOpenSettings, isActive = false }: GitHubPRsProps)
|
||||
isReviewing,
|
||||
isExternalReview,
|
||||
previousReviewResult,
|
||||
reviewError,
|
||||
hasMore,
|
||||
selectPR,
|
||||
runReview,
|
||||
@@ -271,6 +272,7 @@ export function GitHubPRs({ onOpenSettings, isActive = false }: GitHubPRsProps)
|
||||
startedAt={startedAt}
|
||||
isReviewing={isReviewing}
|
||||
isExternalReview={isExternalReview}
|
||||
reviewError={reviewError}
|
||||
initialNewCommitsCheck={storedNewCommitsCheck}
|
||||
isActive={isActive}
|
||||
isLoadingFiles={isLoadingPRDetails}
|
||||
|
||||
@@ -46,6 +46,7 @@ interface PRDetailProps {
|
||||
startedAt: string | null;
|
||||
isReviewing: boolean;
|
||||
isExternalReview?: boolean;
|
||||
reviewError?: string | null;
|
||||
initialNewCommitsCheck?: NewCommitsCheck | null;
|
||||
isActive?: boolean;
|
||||
isLoadingFiles?: boolean;
|
||||
@@ -81,6 +82,7 @@ export function PRDetail({
|
||||
startedAt,
|
||||
isReviewing,
|
||||
isExternalReview = false,
|
||||
reviewError: reviewErrorProp,
|
||||
initialNewCommitsCheck,
|
||||
isActive: _isActive = false,
|
||||
isLoadingFiles = false,
|
||||
@@ -721,6 +723,16 @@ export function PRDetail({
|
||||
};
|
||||
}
|
||||
|
||||
if (reviewErrorProp && !reviewResult?.success) {
|
||||
return {
|
||||
status: 'not_reviewed',
|
||||
label: t('prReview.reviewFailed'),
|
||||
description: reviewErrorProp,
|
||||
icon: <AlertCircle className="h-5 w-5" />,
|
||||
color: 'bg-destructive/20 text-destructive border-destructive/50',
|
||||
};
|
||||
}
|
||||
|
||||
if (!reviewResult || !reviewResult.success) {
|
||||
return {
|
||||
status: 'not_reviewed',
|
||||
@@ -863,7 +875,7 @@ export function PRDetail({
|
||||
icon: <MessageSquare className="h-5 w-5" />,
|
||||
color: 'bg-primary/20 text-primary border-primary/50',
|
||||
};
|
||||
}, [isReviewing, reviewProgress, reviewResult, postedFindingIds, isReadyToMerge, newCommitsCheck, t]);
|
||||
}, [isReviewing, reviewProgress, reviewResult, reviewErrorProp, postedFindingIds, isReadyToMerge, newCommitsCheck, t]);
|
||||
|
||||
const handlePostReview = async () => {
|
||||
const idsToPost = Array.from(selectedFindingIds);
|
||||
@@ -1128,6 +1140,7 @@ ${t('prReview.blockedStatusMessageFooter')}`;
|
||||
reviewResult={reviewResult}
|
||||
previousReviewResult={previousReviewResult}
|
||||
postedCount={new Set([...postedFindingIds, ...(reviewResult?.postedFindingIds ?? [])]).size}
|
||||
reviewError={reviewErrorProp}
|
||||
onRunReview={onRunReview}
|
||||
onRunFollowupReview={onRunFollowupReview}
|
||||
onCancelReview={onCancelReview}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState } from 'react';
|
||||
import { CheckCircle, Circle, CircleDot, Play, RefreshCw } from 'lucide-react';
|
||||
import { AlertCircle, CheckCircle, Circle, CircleDot, Play, RefreshCw } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '../../ui/button';
|
||||
import { cn } from '../../../lib/utils';
|
||||
@@ -26,6 +26,7 @@ export interface ReviewStatusTreeProps {
|
||||
reviewResult: PRReviewResult | null;
|
||||
previousReviewResult: PRReviewResult | null;
|
||||
postedCount: number;
|
||||
reviewError?: string | null;
|
||||
onRunReview: () => void;
|
||||
onRunFollowupReview: () => void;
|
||||
onCancelReview: () => void;
|
||||
@@ -45,6 +46,7 @@ export function ReviewStatusTree({
|
||||
reviewResult,
|
||||
previousReviewResult,
|
||||
postedCount,
|
||||
reviewError,
|
||||
onRunReview,
|
||||
onRunFollowupReview,
|
||||
onCancelReview,
|
||||
@@ -57,8 +59,26 @@ export function ReviewStatusTree({
|
||||
// Determine if this is a follow-up review in progress (for edge case handling)
|
||||
const isFollowupInProgress = isReviewing && (previousReviewResult !== null || reviewResult?.isFollowupReview);
|
||||
|
||||
// If not reviewed, show simple status
|
||||
// If not reviewed, show simple status (with error if present)
|
||||
if (status === 'not_reviewed' && !isReviewing) {
|
||||
if (reviewError) {
|
||||
return (
|
||||
<div className="flex flex-wrap items-center justify-between gap-y-3 p-4 border rounded-lg bg-card shadow-sm border-destructive/30">
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<div className="h-2.5 w-2.5 shrink-0 rounded-full bg-destructive" />
|
||||
<div className="min-w-0">
|
||||
<span className="font-medium text-destructive truncate block">{t('prReview.reviewFailed')}</span>
|
||||
<span className="text-xs text-muted-foreground truncate block mt-0.5">{reviewError}</span>
|
||||
</div>
|
||||
</div>
|
||||
<Button onClick={onRunReview} size="sm" variant="outline" className="gap-2 shrink-0 ml-auto sm:ml-0">
|
||||
<RefreshCw className="h-3.5 w-3.5" />
|
||||
{t('prReview.retryReview')}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap items-center justify-between gap-y-3 p-4 border rounded-lg bg-card shadow-sm">
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
|
||||
@@ -34,6 +34,7 @@ interface UseGitHubPRsResult {
|
||||
isReviewing: boolean;
|
||||
isExternalReview: boolean;
|
||||
previousReviewResult: PRReviewResult | null;
|
||||
reviewError: string | null;
|
||||
isConnected: boolean;
|
||||
repoFullName: string | null;
|
||||
activePRReviews: number[]; // PR numbers currently being reviewed
|
||||
@@ -117,6 +118,7 @@ export function useGitHubPRs(
|
||||
const isExternalReview = selectedPRReviewState?.isExternalReview ?? false;
|
||||
const previousReviewResult = selectedPRReviewState?.previousResult ?? null;
|
||||
const startedAt = selectedPRReviewState?.startedAt ?? null;
|
||||
const reviewError = selectedPRReviewState?.error ?? null;
|
||||
|
||||
// Get list of PR numbers currently being reviewed
|
||||
const activePRReviews = useMemo(() => {
|
||||
@@ -731,6 +733,7 @@ export function useGitHubPRs(
|
||||
isReviewing,
|
||||
isExternalReview,
|
||||
previousReviewResult,
|
||||
reviewError,
|
||||
isConnected,
|
||||
repoFullName,
|
||||
activePRReviews,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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');
|
||||
},
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -792,7 +792,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();
|
||||
|
||||
|
||||
@@ -111,6 +111,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',
|
||||
|
||||
@@ -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",
|
||||
@@ -362,6 +381,7 @@
|
||||
"followup": "Follow-up",
|
||||
"initial": "Initial",
|
||||
"rerunFollowup": "Re-run follow-up review",
|
||||
"retryReview": "Retry Review",
|
||||
"rerunReview": "Re-run review",
|
||||
"updateBranch": "Update Branch",
|
||||
"updatingBranch": "Updating...",
|
||||
@@ -606,7 +626,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",
|
||||
|
||||
@@ -1,4 +1,22 @@
|
||||
{
|
||||
"competitorAnalysis": {
|
||||
"addCompetitor": "Ajouter un concurrent",
|
||||
"manualBadge": "Manuel",
|
||||
"noCompetitorsYet": "Aucun concurrent ajouté pour l'instant",
|
||||
"addCompetitorToStart": "Ajoutez un concurrent pour commencer",
|
||||
"analysisResults": "Résultats de l'analyse concurrentielle",
|
||||
"analysisDescription": "{{count}} concurrents analysés pour identifier les opportunités et lacunes du marché",
|
||||
"visit": "Visiter",
|
||||
"identifiedPainPoints": "Points de douleur identifiés ({{count}})",
|
||||
"noPainPointsIdentified": "Aucun point de douleur identifié",
|
||||
"source": "Source :",
|
||||
"frequency": "Fréquence :",
|
||||
"opportunity": "Opportunité :",
|
||||
"marketInsightsSummary": "Résumé des perspectives du marché",
|
||||
"topPainPoints": "Principaux points de douleur :",
|
||||
"differentiatorOpportunities": "Opportunités de différenciation :",
|
||||
"marketTrends": "Tendances du marché :"
|
||||
},
|
||||
"projectTab": {
|
||||
"settings": "Paramètres du projet",
|
||||
"showArchived": "Afficher archivés",
|
||||
@@ -11,6 +29,7 @@
|
||||
},
|
||||
"accessibility": {
|
||||
"deleteFeatureAriaLabel": "Supprimer la fonctionnalité",
|
||||
"archiveFeatureAriaLabel": "Archiver la fonctionnalité",
|
||||
"closeFeatureDetailsAriaLabel": "Fermer les détails de la fonctionnalité",
|
||||
"regenerateRoadmapAriaLabel": "Régénérer la feuille de route",
|
||||
"repositoryOwnerAriaLabel": "Propriétaire du dépôt",
|
||||
@@ -371,6 +390,7 @@
|
||||
"followup": "Suivi",
|
||||
"initial": "Initial",
|
||||
"rerunFollowup": "Relancer la revue de suivi",
|
||||
"retryReview": "Réessayer la revue",
|
||||
"rerunReview": "Relancer la revue",
|
||||
"updateBranch": "Mettre à jour la branche",
|
||||
"updatingBranch": "Mise à jour...",
|
||||
@@ -606,7 +626,15 @@
|
||||
"taskArchived": "Archivé",
|
||||
"showMoreFeatures": "Afficher {{count}} fonctionnalité supplémentaire",
|
||||
"showMoreFeatures_plural": "Afficher {{count}} fonctionnalités supplémentaires",
|
||||
"showLessFeatures": "Afficher moins"
|
||||
"showLessFeatures": "Afficher moins",
|
||||
"archiveFeature": "Archiver",
|
||||
"archiveFeatureConfirmTitle": "Archiver la fonctionnalité ?",
|
||||
"archiveFeatureConfirmDescription": "Cela supprimera \"{{title}}\" de votre feuille de route.",
|
||||
"goToTask": "Aller à la tâche",
|
||||
"convertToTask": "Convertir en tâche Auto-Build",
|
||||
"build": "Construire",
|
||||
"task": "Tâche",
|
||||
"viewTask": "Voir la tâche"
|
||||
},
|
||||
"roadmapGeneration": {
|
||||
"progress": "Progression",
|
||||
|
||||
@@ -166,6 +166,60 @@
|
||||
"readOnlyVolumeTitle": "Impossible d'installer depuis une image disque",
|
||||
"readOnlyVolumeDescription": "Veuillez déplacer Auto Claude dans votre dossier Applications avant de mettre à jour."
|
||||
},
|
||||
"addCompetitor": {
|
||||
"title": "Ajouter un concurrent",
|
||||
"description": "Ajoutez un concurrent connu à votre analyse...",
|
||||
"competitorName": "Nom du concurrent",
|
||||
"competitorNamePlaceholder": "ex. Slack, Notion, Figma",
|
||||
"competitorUrl": "URL du site web",
|
||||
"competitorUrlPlaceholder": "ex. https://example.com",
|
||||
"competitorDescription": "Description",
|
||||
"competitorDescriptionPlaceholder": "Brève description de ce que fait ce concurrent...",
|
||||
"relevance": "Pertinence",
|
||||
"selectRelevance": "Sélectionner la pertinence",
|
||||
"highRelevance": "Élevée - Concurrent direct",
|
||||
"mediumRelevance": "Moyenne - Chevauchement partiel",
|
||||
"lowRelevance": "Faible - Tangentiel",
|
||||
"nameRequired": "Le nom du concurrent est requis",
|
||||
"urlRequired": "L'URL du site web est requise",
|
||||
"invalidUrl": "Veuillez entrer une URL valide",
|
||||
"optional": "optionnel",
|
||||
"cancel": "Annuler",
|
||||
"adding": "Ajout en cours...",
|
||||
"addCompetitor": "Ajouter le concurrent",
|
||||
"failedToAdd": "Échec de l'ajout du concurrent"
|
||||
},
|
||||
"competitorAnalysis": {
|
||||
"title": "Activer l'analyse concurrentielle ?",
|
||||
"description": "Améliorez votre feuille de route avec des informations sur les produits concurrents",
|
||||
"whatItDoes": "Ce que fait l'analyse concurrentielle :",
|
||||
"identifiesCompetitors": "Identifie 3 à 5 concurrents principaux en fonction de votre type de projet",
|
||||
"searchesAppStores": "Recherche dans les magasins d'applications, forums et réseaux sociaux les retours et points de douleur des utilisateurs",
|
||||
"suggestsFeatures": "Suggère des fonctionnalités qui comblent les lacunes des produits concurrents",
|
||||
"webSearchesTitle": "Des recherches web seront effectuées",
|
||||
"webSearchesDescription": "Cette fonctionnalité effectuera des recherches web pour recueillir des informations sur les concurrents. Le nom et le type de votre projet seront utilisés dans les requêtes de recherche. Aucun code ni donnée sensible n'est partagé.",
|
||||
"optionalInfo": "Vous pouvez générer une feuille de route sans analyse concurrentielle si vous préférez. La feuille de route sera toujours basée sur la structure de votre projet et les meilleures pratiques.",
|
||||
"skipAnalysis": "Non, ignorer l'analyse",
|
||||
"enableAnalysis": "Oui, activer l'analyse",
|
||||
"knowYourCompetitors": "Vous connaissez déjà vos concurrents ?",
|
||||
"addThemDirectly": "Ajoutez-les directement pour améliorer la précision de l'analyse",
|
||||
"addKnownCompetitors": "Ajouter des concurrents connus",
|
||||
"addKnownCompetitorsDescription": "Ajoutez manuellement les concurrents que vous connaissez déjà à l'analyse existante.",
|
||||
"competitorsAdded": "{{count}} ajouté(s)"
|
||||
},
|
||||
"existingCompetitorAnalysis": {
|
||||
"title": "Options d'analyse concurrentielle",
|
||||
"description": "Ce projet a une analyse concurrentielle existante du {{date}}",
|
||||
"recently": "récemment",
|
||||
"useExistingTitle": "Utiliser l'analyse existante",
|
||||
"recommended": "(Recommandé)",
|
||||
"useExistingDescription": "Réutilisez les informations concurrentielles que vous avez déjà. Plus rapide et sans recherches web supplémentaires.",
|
||||
"runNewTitle": "Lancer une nouvelle analyse",
|
||||
"runNewDescription": "Effectuer de nouvelles recherches web pour obtenir des informations concurrentielles à jour. Prend plus de temps.",
|
||||
"skipTitle": "Ignorer l'analyse concurrentielle",
|
||||
"skipDescription": "Générer la feuille de route sans informations concurrentielles.",
|
||||
"cancel": "Annuler"
|
||||
},
|
||||
"versionWarning": {
|
||||
"title": "Action requise",
|
||||
"subtitle": "Mise à jour version 2.7.5",
|
||||
|
||||
@@ -0,0 +1,399 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createActor } from 'xstate';
|
||||
import {
|
||||
roadmapFeatureMachine,
|
||||
type RoadmapFeatureEvent
|
||||
} from '../roadmap-feature-machine';
|
||||
|
||||
/**
|
||||
* Helper to run a sequence of events and get the final snapshot
|
||||
*/
|
||||
function runEvents(events: RoadmapFeatureEvent[], initialState?: string) {
|
||||
const actor = initialState
|
||||
? createActor(roadmapFeatureMachine, {
|
||||
snapshot: roadmapFeatureMachine.resolveState({
|
||||
value: initialState,
|
||||
context: {}
|
||||
})
|
||||
})
|
||||
: createActor(roadmapFeatureMachine);
|
||||
actor.start();
|
||||
|
||||
for (const event of events) {
|
||||
actor.send(event);
|
||||
}
|
||||
|
||||
const snapshot = actor.getSnapshot();
|
||||
actor.stop();
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
describe('roadmapFeatureMachine', () => {
|
||||
describe('initial state', () => {
|
||||
it('should start in under_review state', () => {
|
||||
const actor = createActor(roadmapFeatureMachine);
|
||||
actor.start();
|
||||
expect(actor.getSnapshot().value).toBe('under_review');
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it('should have empty context initially', () => {
|
||||
const actor = createActor(roadmapFeatureMachine);
|
||||
actor.start();
|
||||
const { context } = actor.getSnapshot();
|
||||
expect(context.linkedSpecId).toBeUndefined();
|
||||
expect(context.taskOutcome).toBeUndefined();
|
||||
expect(context.previousStatus).toBeUndefined();
|
||||
actor.stop();
|
||||
});
|
||||
});
|
||||
|
||||
describe('status transitions: under_review → planned → in_progress → done', () => {
|
||||
it('should transition under_review → planned via PLAN', () => {
|
||||
const snapshot = runEvents([{ type: 'PLAN' }]);
|
||||
expect(snapshot.value).toBe('planned');
|
||||
});
|
||||
|
||||
it('should transition planned → in_progress via START_PROGRESS', () => {
|
||||
const snapshot = runEvents([{ type: 'PLAN' }, { type: 'START_PROGRESS' }]);
|
||||
expect(snapshot.value).toBe('in_progress');
|
||||
});
|
||||
|
||||
it('should transition in_progress → done via MARK_DONE', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'PLAN' },
|
||||
{ type: 'START_PROGRESS' },
|
||||
{ type: 'MARK_DONE' }
|
||||
]);
|
||||
expect(snapshot.value).toBe('done');
|
||||
});
|
||||
|
||||
it('should transition under_review → in_progress via START_PROGRESS', () => {
|
||||
const snapshot = runEvents([{ type: 'START_PROGRESS' }]);
|
||||
expect(snapshot.value).toBe('in_progress');
|
||||
});
|
||||
|
||||
it('should transition under_review → done via MARK_DONE', () => {
|
||||
const snapshot = runEvents([{ type: 'MARK_DONE' }]);
|
||||
expect(snapshot.value).toBe('done');
|
||||
expect(snapshot.context.previousStatus).toBe('under_review');
|
||||
});
|
||||
|
||||
it('should transition planned → done via MARK_DONE', () => {
|
||||
const snapshot = runEvents([{ type: 'PLAN' }, { type: 'MARK_DONE' }]);
|
||||
expect(snapshot.value).toBe('done');
|
||||
expect(snapshot.context.previousStatus).toBe('planned');
|
||||
});
|
||||
|
||||
it('should allow reverse: planned → under_review via MOVE_TO_REVIEW', () => {
|
||||
const snapshot = runEvents([{ type: 'PLAN' }, { type: 'MOVE_TO_REVIEW' }]);
|
||||
expect(snapshot.value).toBe('under_review');
|
||||
});
|
||||
|
||||
it('should allow reverse: in_progress → planned via PLAN', () => {
|
||||
const snapshot = runEvents([{ type: 'START_PROGRESS' }, { type: 'PLAN' }]);
|
||||
expect(snapshot.value).toBe('planned');
|
||||
});
|
||||
|
||||
it('should allow reverse: in_progress → under_review via MOVE_TO_REVIEW', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_PROGRESS' },
|
||||
{ type: 'MOVE_TO_REVIEW' }
|
||||
]);
|
||||
expect(snapshot.value).toBe('under_review');
|
||||
});
|
||||
});
|
||||
|
||||
describe('LINK_SPEC', () => {
|
||||
it('should set linkedSpecId and auto-transition to in_progress from under_review', () => {
|
||||
const snapshot = runEvents([{ type: 'LINK_SPEC', specId: 'spec-42' }]);
|
||||
expect(snapshot.value).toBe('in_progress');
|
||||
expect(snapshot.context.linkedSpecId).toBe('spec-42');
|
||||
});
|
||||
|
||||
it('should set linkedSpecId and auto-transition to in_progress from planned', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'PLAN' },
|
||||
{ type: 'LINK_SPEC', specId: 'spec-99' }
|
||||
]);
|
||||
expect(snapshot.value).toBe('in_progress');
|
||||
expect(snapshot.context.linkedSpecId).toBe('spec-99');
|
||||
});
|
||||
|
||||
it('should update linkedSpecId without changing state when already in_progress', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_PROGRESS' },
|
||||
{ type: 'LINK_SPEC', specId: 'spec-7' }
|
||||
]);
|
||||
expect(snapshot.value).toBe('in_progress');
|
||||
expect(snapshot.context.linkedSpecId).toBe('spec-7');
|
||||
});
|
||||
|
||||
it('should be ignored from done state (no LINK_SPEC transition defined)', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'MARK_DONE' },
|
||||
{ type: 'LINK_SPEC', specId: 'spec-1' }
|
||||
]);
|
||||
expect(snapshot.value).toBe('done');
|
||||
expect(snapshot.context.linkedSpecId).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('TASK_COMPLETED from in_progress', () => {
|
||||
it('should transition to done with taskOutcome="completed"', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_PROGRESS' },
|
||||
{ type: 'TASK_COMPLETED' }
|
||||
]);
|
||||
expect(snapshot.value).toBe('done');
|
||||
expect(snapshot.context.taskOutcome).toBe('completed');
|
||||
expect(snapshot.context.previousStatus).toBe('in_progress');
|
||||
});
|
||||
});
|
||||
|
||||
describe('TASK_DELETED from in_progress', () => {
|
||||
it('should transition to done with taskOutcome="deleted"', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_PROGRESS' },
|
||||
{ type: 'TASK_DELETED' }
|
||||
]);
|
||||
expect(snapshot.value).toBe('done');
|
||||
expect(snapshot.context.taskOutcome).toBe('deleted');
|
||||
expect(snapshot.context.previousStatus).toBe('in_progress');
|
||||
});
|
||||
});
|
||||
|
||||
describe('TASK_ARCHIVED from in_progress', () => {
|
||||
it('should transition to done with taskOutcome="archived"', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_PROGRESS' },
|
||||
{ type: 'TASK_ARCHIVED' }
|
||||
]);
|
||||
expect(snapshot.value).toBe('done');
|
||||
expect(snapshot.context.taskOutcome).toBe('archived');
|
||||
expect(snapshot.context.previousStatus).toBe('in_progress');
|
||||
});
|
||||
});
|
||||
|
||||
describe('REVERT from done', () => {
|
||||
it('should revert to in_progress when previousStatus was in_progress', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_PROGRESS' },
|
||||
{ type: 'MARK_DONE' },
|
||||
{ type: 'REVERT' }
|
||||
]);
|
||||
expect(snapshot.value).toBe('in_progress');
|
||||
});
|
||||
|
||||
it('should revert to planned when previousStatus was planned', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'PLAN' },
|
||||
{ type: 'MARK_DONE' },
|
||||
{ type: 'REVERT' }
|
||||
]);
|
||||
expect(snapshot.value).toBe('planned');
|
||||
});
|
||||
|
||||
it('should revert to under_review when previousStatus was under_review', () => {
|
||||
const snapshot = runEvents([{ type: 'MARK_DONE' }, { type: 'REVERT' }]);
|
||||
expect(snapshot.value).toBe('under_review');
|
||||
});
|
||||
|
||||
it('should revert to under_review when no previousStatus is set (fallback)', () => {
|
||||
// Use state restoration to put in done without previousStatus
|
||||
const actor = createActor(roadmapFeatureMachine, {
|
||||
snapshot: roadmapFeatureMachine.resolveState({
|
||||
value: 'done',
|
||||
context: { previousStatus: undefined }
|
||||
})
|
||||
});
|
||||
actor.start();
|
||||
actor.send({ type: 'REVERT' });
|
||||
expect(actor.getSnapshot().value).toBe('under_review');
|
||||
actor.stop();
|
||||
});
|
||||
});
|
||||
|
||||
describe('moving away from done clears taskOutcome and previousStatus', () => {
|
||||
it('should clear context on REVERT', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_PROGRESS' },
|
||||
{ type: 'TASK_COMPLETED' },
|
||||
{ type: 'REVERT' }
|
||||
]);
|
||||
expect(snapshot.value).toBe('in_progress');
|
||||
expect(snapshot.context.taskOutcome).toBeUndefined();
|
||||
expect(snapshot.context.previousStatus).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should clear context on MOVE_TO_REVIEW from done', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_PROGRESS' },
|
||||
{ type: 'TASK_COMPLETED' },
|
||||
{ type: 'MOVE_TO_REVIEW' }
|
||||
]);
|
||||
expect(snapshot.value).toBe('under_review');
|
||||
expect(snapshot.context.taskOutcome).toBeUndefined();
|
||||
expect(snapshot.context.previousStatus).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should clear context on PLAN from done', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_PROGRESS' },
|
||||
{ type: 'TASK_DELETED' },
|
||||
{ type: 'PLAN' }
|
||||
]);
|
||||
expect(snapshot.value).toBe('planned');
|
||||
expect(snapshot.context.taskOutcome).toBeUndefined();
|
||||
expect(snapshot.context.previousStatus).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should clear context on START_PROGRESS from done', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_PROGRESS' },
|
||||
{ type: 'TASK_ARCHIVED' },
|
||||
{ type: 'START_PROGRESS' }
|
||||
]);
|
||||
expect(snapshot.value).toBe('in_progress');
|
||||
expect(snapshot.context.taskOutcome).toBeUndefined();
|
||||
expect(snapshot.context.previousStatus).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('redundant status transitions', () => {
|
||||
it('should ignore MOVE_TO_REVIEW when already in under_review (no-op)', () => {
|
||||
const actor = createActor(roadmapFeatureMachine);
|
||||
actor.start();
|
||||
// MOVE_TO_REVIEW is not defined on under_review, so it's ignored
|
||||
actor.send({ type: 'MOVE_TO_REVIEW' });
|
||||
expect(actor.getSnapshot().value).toBe('under_review');
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it('should ignore PLAN when already in planned (no-op)', () => {
|
||||
const snapshot = runEvents([{ type: 'PLAN' }, { type: 'PLAN' }]);
|
||||
expect(snapshot.value).toBe('planned');
|
||||
});
|
||||
|
||||
it('should ignore START_PROGRESS when already in in_progress (no-op)', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_PROGRESS' },
|
||||
{ type: 'START_PROGRESS' }
|
||||
]);
|
||||
expect(snapshot.value).toBe('in_progress');
|
||||
});
|
||||
|
||||
it('should handle MARK_DONE in done state (self-transition)', () => {
|
||||
const snapshot = runEvents([{ type: 'MARK_DONE' }, { type: 'MARK_DONE' }]);
|
||||
expect(snapshot.value).toBe('done');
|
||||
});
|
||||
});
|
||||
|
||||
describe('task events from various states', () => {
|
||||
it('should transition TASK_COMPLETED from under_review to done', () => {
|
||||
const snapshot = runEvents([{ type: 'TASK_COMPLETED' }]);
|
||||
expect(snapshot.value).toBe('done');
|
||||
expect(snapshot.context.taskOutcome).toBe('completed');
|
||||
expect(snapshot.context.previousStatus).toBe('under_review');
|
||||
});
|
||||
|
||||
it('should transition TASK_DELETED from under_review to done', () => {
|
||||
const snapshot = runEvents([{ type: 'TASK_DELETED' }]);
|
||||
expect(snapshot.value).toBe('done');
|
||||
expect(snapshot.context.taskOutcome).toBe('deleted');
|
||||
expect(snapshot.context.previousStatus).toBe('under_review');
|
||||
});
|
||||
|
||||
it('should transition TASK_ARCHIVED from under_review to done', () => {
|
||||
const snapshot = runEvents([{ type: 'TASK_ARCHIVED' }]);
|
||||
expect(snapshot.value).toBe('done');
|
||||
expect(snapshot.context.taskOutcome).toBe('archived');
|
||||
expect(snapshot.context.previousStatus).toBe('under_review');
|
||||
});
|
||||
|
||||
it('should transition TASK_DELETED from planned to done', () => {
|
||||
const snapshot = runEvents([{ type: 'PLAN' }, { type: 'TASK_DELETED' }]);
|
||||
expect(snapshot.value).toBe('done');
|
||||
expect(snapshot.context.taskOutcome).toBe('deleted');
|
||||
expect(snapshot.context.previousStatus).toBe('planned');
|
||||
});
|
||||
|
||||
it('should handle TASK_ARCHIVED from done (update outcome)', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'MARK_DONE' },
|
||||
{ type: 'TASK_ARCHIVED' }
|
||||
]);
|
||||
expect(snapshot.value).toBe('done');
|
||||
expect(snapshot.context.taskOutcome).toBe('archived');
|
||||
});
|
||||
});
|
||||
|
||||
describe('state restoration from snapshot', () => {
|
||||
it('should restore to planned state', () => {
|
||||
const actor = createActor(roadmapFeatureMachine, {
|
||||
snapshot: roadmapFeatureMachine.resolveState({
|
||||
value: 'planned',
|
||||
context: {}
|
||||
})
|
||||
});
|
||||
actor.start();
|
||||
expect(actor.getSnapshot().value).toBe('planned');
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it('should restore to in_progress with linkedSpecId', () => {
|
||||
const actor = createActor(roadmapFeatureMachine, {
|
||||
snapshot: roadmapFeatureMachine.resolveState({
|
||||
value: 'in_progress',
|
||||
context: { linkedSpecId: 'spec-123' }
|
||||
})
|
||||
});
|
||||
actor.start();
|
||||
const { value, context } = actor.getSnapshot();
|
||||
expect(value).toBe('in_progress');
|
||||
expect(context.linkedSpecId).toBe('spec-123');
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it('should restore to done with full context and allow revert', () => {
|
||||
const actor = createActor(roadmapFeatureMachine, {
|
||||
snapshot: roadmapFeatureMachine.resolveState({
|
||||
value: 'done',
|
||||
context: {
|
||||
linkedSpecId: 'spec-5',
|
||||
taskOutcome: 'completed',
|
||||
previousStatus: 'in_progress'
|
||||
}
|
||||
})
|
||||
});
|
||||
actor.start();
|
||||
expect(actor.getSnapshot().value).toBe('done');
|
||||
expect(actor.getSnapshot().context.taskOutcome).toBe('completed');
|
||||
|
||||
actor.send({ type: 'REVERT' });
|
||||
expect(actor.getSnapshot().value).toBe('in_progress');
|
||||
expect(actor.getSnapshot().context.taskOutcome).toBeUndefined();
|
||||
actor.stop();
|
||||
});
|
||||
});
|
||||
|
||||
describe('moving away from in_progress clears context', () => {
|
||||
it('should clear taskOutcome and previousStatus when moving to planned', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_PROGRESS' },
|
||||
{ type: 'PLAN' }
|
||||
]);
|
||||
expect(snapshot.context.taskOutcome).toBeUndefined();
|
||||
expect(snapshot.context.previousStatus).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should clear taskOutcome and previousStatus when moving to under_review', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_PROGRESS' },
|
||||
{ type: 'MOVE_TO_REVIEW' }
|
||||
]);
|
||||
expect(snapshot.context.taskOutcome).toBeUndefined();
|
||||
expect(snapshot.context.previousStatus).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,461 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { createActor } from 'xstate';
|
||||
import {
|
||||
roadmapGenerationMachine,
|
||||
type RoadmapGenerationEvent,
|
||||
} from '../roadmap-generation-machine';
|
||||
|
||||
/**
|
||||
* Helper to run a sequence of events and get the final state
|
||||
*/
|
||||
function runEvents(events: RoadmapGenerationEvent[]) {
|
||||
const actor = createActor(roadmapGenerationMachine);
|
||||
actor.start();
|
||||
|
||||
for (const event of events) {
|
||||
actor.send(event);
|
||||
}
|
||||
|
||||
const snapshot = actor.getSnapshot();
|
||||
actor.stop();
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
describe('roadmapGenerationMachine', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date('2025-01-01T00:00:00Z'));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('initial state', () => {
|
||||
it('should start in idle state', () => {
|
||||
const actor = createActor(roadmapGenerationMachine);
|
||||
actor.start();
|
||||
expect(actor.getSnapshot().value).toBe('idle');
|
||||
actor.stop();
|
||||
});
|
||||
|
||||
it('should have default context initially', () => {
|
||||
const actor = createActor(roadmapGenerationMachine);
|
||||
actor.start();
|
||||
const snapshot = actor.getSnapshot();
|
||||
expect(snapshot.context.progress).toBe(0);
|
||||
expect(snapshot.context.message).toBeUndefined();
|
||||
expect(snapshot.context.error).toBeUndefined();
|
||||
expect(snapshot.context.startedAt).toBeUndefined();
|
||||
expect(snapshot.context.completedAt).toBeUndefined();
|
||||
actor.stop();
|
||||
});
|
||||
});
|
||||
|
||||
describe('happy path: idle → analyzing → discovering → generating → complete', () => {
|
||||
it('should transition through the standard workflow', () => {
|
||||
const events: RoadmapGenerationEvent[] = [
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'PROGRESS_UPDATE', progress: 20, message: 'Analyzing...' },
|
||||
{ type: 'DISCOVERY_STARTED' },
|
||||
{ type: 'PROGRESS_UPDATE', progress: 50, message: 'Discovering...' },
|
||||
{ type: 'GENERATION_STARTED' },
|
||||
{ type: 'PROGRESS_UPDATE', progress: 80, message: 'Generating...' },
|
||||
{ type: 'GENERATION_COMPLETE' },
|
||||
];
|
||||
|
||||
const snapshot = runEvents(events);
|
||||
expect(snapshot.value).toBe('complete');
|
||||
expect(snapshot.context.progress).toBe(100);
|
||||
expect(snapshot.context.completedAt).toBeDefined();
|
||||
});
|
||||
|
||||
it('should transition from idle to analyzing on START_GENERATION', () => {
|
||||
const snapshot = runEvents([{ type: 'START_GENERATION' }]);
|
||||
expect(snapshot.value).toBe('analyzing');
|
||||
});
|
||||
|
||||
it('should transition from analyzing to discovering on DISCOVERY_STARTED', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'DISCOVERY_STARTED' },
|
||||
]);
|
||||
expect(snapshot.value).toBe('discovering');
|
||||
});
|
||||
|
||||
it('should transition from discovering to generating on GENERATION_STARTED', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'DISCOVERY_STARTED' },
|
||||
{ type: 'GENERATION_STARTED' },
|
||||
]);
|
||||
expect(snapshot.value).toBe('generating');
|
||||
});
|
||||
|
||||
it('should transition from generating to complete on GENERATION_COMPLETE', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'DISCOVERY_STARTED' },
|
||||
{ type: 'GENERATION_STARTED' },
|
||||
{ type: 'GENERATION_COMPLETE' },
|
||||
]);
|
||||
expect(snapshot.value).toBe('complete');
|
||||
});
|
||||
});
|
||||
|
||||
describe('PROGRESS_UPDATE updates context in all active states', () => {
|
||||
it('should update progress in analyzing state', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'PROGRESS_UPDATE', progress: 25, message: 'Analyzing codebase' },
|
||||
]);
|
||||
expect(snapshot.value).toBe('analyzing');
|
||||
expect(snapshot.context.progress).toBe(25);
|
||||
expect(snapshot.context.message).toBe('Analyzing codebase');
|
||||
});
|
||||
|
||||
it('should update progress in discovering state', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'DISCOVERY_STARTED' },
|
||||
{ type: 'PROGRESS_UPDATE', progress: 50, message: 'Discovering features' },
|
||||
]);
|
||||
expect(snapshot.value).toBe('discovering');
|
||||
expect(snapshot.context.progress).toBe(50);
|
||||
expect(snapshot.context.message).toBe('Discovering features');
|
||||
});
|
||||
|
||||
it('should update progress in generating state', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'DISCOVERY_STARTED' },
|
||||
{ type: 'GENERATION_STARTED' },
|
||||
{ type: 'PROGRESS_UPDATE', progress: 80, message: 'Generating roadmap' },
|
||||
]);
|
||||
expect(snapshot.value).toBe('generating');
|
||||
expect(snapshot.context.progress).toBe(80);
|
||||
expect(snapshot.context.message).toBe('Generating roadmap');
|
||||
});
|
||||
});
|
||||
|
||||
describe('error flow: GENERATION_ERROR from any active state → error', () => {
|
||||
it('should transition to error from analyzing', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'GENERATION_ERROR', error: 'Analysis failed' },
|
||||
]);
|
||||
expect(snapshot.value).toBe('error');
|
||||
expect(snapshot.context.error).toBe('Analysis failed');
|
||||
});
|
||||
|
||||
it('should transition to error from discovering', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'DISCOVERY_STARTED' },
|
||||
{ type: 'GENERATION_ERROR', error: 'Discovery failed' },
|
||||
]);
|
||||
expect(snapshot.value).toBe('error');
|
||||
expect(snapshot.context.error).toBe('Discovery failed');
|
||||
});
|
||||
|
||||
it('should transition to error from generating', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'DISCOVERY_STARTED' },
|
||||
{ type: 'GENERATION_STARTED' },
|
||||
{ type: 'GENERATION_ERROR', error: 'Generation failed' },
|
||||
]);
|
||||
expect(snapshot.value).toBe('error');
|
||||
expect(snapshot.context.error).toBe('Generation failed');
|
||||
});
|
||||
|
||||
it('should preserve progress when transitioning to error', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'PROGRESS_UPDATE', progress: 60, message: 'Processing...' },
|
||||
{ type: 'GENERATION_ERROR', error: 'Something went wrong' },
|
||||
]);
|
||||
expect(snapshot.value).toBe('error');
|
||||
expect(snapshot.context.progress).toBe(60);
|
||||
expect(snapshot.context.error).toBe('Something went wrong');
|
||||
});
|
||||
});
|
||||
|
||||
describe('stop flow: STOP from analyzing/discovering/generating → idle', () => {
|
||||
it('should transition to idle from analyzing on STOP', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'STOP' },
|
||||
]);
|
||||
expect(snapshot.value).toBe('idle');
|
||||
expect(snapshot.context.progress).toBe(0);
|
||||
expect(snapshot.context.startedAt).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should transition to idle from discovering on STOP', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'DISCOVERY_STARTED' },
|
||||
{ type: 'STOP' },
|
||||
]);
|
||||
expect(snapshot.value).toBe('idle');
|
||||
expect(snapshot.context.progress).toBe(0);
|
||||
});
|
||||
|
||||
it('should transition to idle from generating on STOP', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'DISCOVERY_STARTED' },
|
||||
{ type: 'GENERATION_STARTED' },
|
||||
{ type: 'STOP' },
|
||||
]);
|
||||
expect(snapshot.value).toBe('idle');
|
||||
expect(snapshot.context.progress).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('RESET from complete/error → idle', () => {
|
||||
it('should transition from complete to idle on RESET', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'DISCOVERY_STARTED' },
|
||||
{ type: 'GENERATION_STARTED' },
|
||||
{ type: 'GENERATION_COMPLETE' },
|
||||
{ type: 'RESET' },
|
||||
]);
|
||||
expect(snapshot.value).toBe('idle');
|
||||
expect(snapshot.context.progress).toBe(0);
|
||||
expect(snapshot.context.completedAt).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should transition from error to idle on RESET', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'GENERATION_ERROR', error: 'Some error' },
|
||||
{ type: 'RESET' },
|
||||
]);
|
||||
expect(snapshot.value).toBe('idle');
|
||||
expect(snapshot.context.error).toBeUndefined();
|
||||
expect(snapshot.context.progress).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('guard: START_GENERATION rejected when not idle', () => {
|
||||
it('should ignore START_GENERATION in analyzing state', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'START_GENERATION' },
|
||||
]);
|
||||
expect(snapshot.value).toBe('analyzing');
|
||||
});
|
||||
|
||||
it('should ignore START_GENERATION in discovering state', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'DISCOVERY_STARTED' },
|
||||
{ type: 'START_GENERATION' },
|
||||
]);
|
||||
expect(snapshot.value).toBe('discovering');
|
||||
});
|
||||
|
||||
it('should ignore START_GENERATION in generating state', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'DISCOVERY_STARTED' },
|
||||
{ type: 'GENERATION_STARTED' },
|
||||
{ type: 'START_GENERATION' },
|
||||
]);
|
||||
expect(snapshot.value).toBe('generating');
|
||||
});
|
||||
|
||||
it('should ignore START_GENERATION in complete state', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'DISCOVERY_STARTED' },
|
||||
{ type: 'GENERATION_STARTED' },
|
||||
{ type: 'GENERATION_COMPLETE' },
|
||||
{ type: 'START_GENERATION' },
|
||||
]);
|
||||
expect(snapshot.value).toBe('complete');
|
||||
});
|
||||
|
||||
it('should ignore START_GENERATION in error state', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'GENERATION_ERROR', error: 'err' },
|
||||
{ type: 'START_GENERATION' },
|
||||
]);
|
||||
expect(snapshot.value).toBe('error');
|
||||
});
|
||||
});
|
||||
|
||||
describe('stale events ignored after complete/error', () => {
|
||||
it('should ignore PROGRESS_UPDATE in complete state', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'DISCOVERY_STARTED' },
|
||||
{ type: 'GENERATION_STARTED' },
|
||||
{ type: 'GENERATION_COMPLETE' },
|
||||
{ type: 'PROGRESS_UPDATE', progress: 50, message: 'stale' },
|
||||
]);
|
||||
expect(snapshot.value).toBe('complete');
|
||||
expect(snapshot.context.progress).toBe(100);
|
||||
});
|
||||
|
||||
it('should ignore PROGRESS_UPDATE in error state', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'GENERATION_ERROR', error: 'err' },
|
||||
{ type: 'PROGRESS_UPDATE', progress: 50, message: 'stale' },
|
||||
]);
|
||||
expect(snapshot.value).toBe('error');
|
||||
expect(snapshot.context.progress).toBe(0);
|
||||
});
|
||||
|
||||
it('should ignore STOP in complete state', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'DISCOVERY_STARTED' },
|
||||
{ type: 'GENERATION_STARTED' },
|
||||
{ type: 'GENERATION_COMPLETE' },
|
||||
{ type: 'STOP' },
|
||||
]);
|
||||
expect(snapshot.value).toBe('complete');
|
||||
});
|
||||
|
||||
it('should ignore STOP in error state', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'GENERATION_ERROR', error: 'err' },
|
||||
{ type: 'STOP' },
|
||||
]);
|
||||
expect(snapshot.value).toBe('error');
|
||||
});
|
||||
|
||||
it('should ignore GENERATION_ERROR in complete state', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'DISCOVERY_STARTED' },
|
||||
{ type: 'GENERATION_STARTED' },
|
||||
{ type: 'GENERATION_COMPLETE' },
|
||||
{ type: 'GENERATION_ERROR', error: 'late error' },
|
||||
]);
|
||||
expect(snapshot.value).toBe('complete');
|
||||
expect(snapshot.context.error).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('timestamp tracking', () => {
|
||||
it('should set startedAt on START_GENERATION', () => {
|
||||
const snapshot = runEvents([{ type: 'START_GENERATION' }]);
|
||||
expect(snapshot.context.startedAt).toBe(Date.now());
|
||||
});
|
||||
|
||||
it('should clear startedAt when returning to idle via STOP', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'STOP' },
|
||||
]);
|
||||
expect(snapshot.context.startedAt).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should clear startedAt when returning to idle via RESET', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'GENERATION_ERROR', error: 'err' },
|
||||
{ type: 'RESET' },
|
||||
]);
|
||||
expect(snapshot.context.startedAt).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should set completedAt on GENERATION_COMPLETE', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'DISCOVERY_STARTED' },
|
||||
{ type: 'GENERATION_STARTED' },
|
||||
{ type: 'GENERATION_COMPLETE' },
|
||||
]);
|
||||
expect(snapshot.context.completedAt).toBe(Date.now());
|
||||
});
|
||||
|
||||
it('should clear completedAt on RESET from complete', () => {
|
||||
const snapshot = runEvents([
|
||||
{ type: 'START_GENERATION' },
|
||||
{ type: 'DISCOVERY_STARTED' },
|
||||
{ type: 'GENERATION_STARTED' },
|
||||
{ type: 'GENERATION_COMPLETE' },
|
||||
{ type: 'RESET' },
|
||||
]);
|
||||
expect(snapshot.context.completedAt).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should reset startedAt on new START_GENERATION', () => {
|
||||
vi.setSystemTime(new Date('2025-01-01T00:00:00Z'));
|
||||
const actor = createActor(roadmapGenerationMachine);
|
||||
actor.start();
|
||||
|
||||
actor.send({ type: 'START_GENERATION' });
|
||||
const firstStartedAt = actor.getSnapshot().context.startedAt;
|
||||
|
||||
actor.send({ type: 'GENERATION_ERROR', error: 'err' });
|
||||
actor.send({ type: 'RESET' });
|
||||
|
||||
vi.setSystemTime(new Date('2025-01-01T01:00:00Z'));
|
||||
actor.send({ type: 'START_GENERATION' });
|
||||
|
||||
const secondStartedAt = actor.getSnapshot().context.startedAt;
|
||||
expect(firstStartedAt).toBeDefined();
|
||||
expect(secondStartedAt).toBeDefined();
|
||||
if (firstStartedAt && secondStartedAt) {
|
||||
expect(secondStartedAt).toBeGreaterThan(firstStartedAt);
|
||||
}
|
||||
actor.stop();
|
||||
});
|
||||
});
|
||||
|
||||
describe('state restoration from snapshot', () => {
|
||||
it('should restore to correct state from snapshot', () => {
|
||||
const testStates = ['idle', 'analyzing', 'discovering', 'generating', 'complete', 'error'];
|
||||
|
||||
for (const state of testStates) {
|
||||
const actor = createActor(roadmapGenerationMachine, {
|
||||
snapshot: roadmapGenerationMachine.resolveState({
|
||||
value: state,
|
||||
context: {
|
||||
progress: 0,
|
||||
message: undefined,
|
||||
error: undefined,
|
||||
startedAt: undefined,
|
||||
completedAt: undefined,
|
||||
},
|
||||
}),
|
||||
});
|
||||
actor.start();
|
||||
expect(actor.getSnapshot().value).toBe(state);
|
||||
actor.stop();
|
||||
}
|
||||
});
|
||||
|
||||
it('should restore context from snapshot', () => {
|
||||
const actor = createActor(roadmapGenerationMachine, {
|
||||
snapshot: roadmapGenerationMachine.resolveState({
|
||||
value: 'generating',
|
||||
context: {
|
||||
progress: 75,
|
||||
message: 'Almost done',
|
||||
error: undefined,
|
||||
startedAt: 1000,
|
||||
completedAt: undefined,
|
||||
},
|
||||
}),
|
||||
});
|
||||
actor.start();
|
||||
const snapshot = actor.getSnapshot();
|
||||
expect(snapshot.value).toBe('generating');
|
||||
expect(snapshot.context.progress).toBe(75);
|
||||
expect(snapshot.context.message).toBe('Almost done');
|
||||
expect(snapshot.context.startedAt).toBe(1000);
|
||||
actor.stop();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
GENERATION_STATE_NAMES,
|
||||
FEATURE_STATE_NAMES,
|
||||
mapGenerationStateToPhase,
|
||||
mapFeatureStateToStatus,
|
||||
} from '../roadmap-state-utils';
|
||||
import { roadmapGenerationMachine } from '../roadmap-generation-machine';
|
||||
import { roadmapFeatureMachine } from '../roadmap-feature-machine';
|
||||
|
||||
describe('mapGenerationStateToPhase', () => {
|
||||
it('should map every GENERATION_STATE_NAMES entry to a non-default phase', () => {
|
||||
for (const state of GENERATION_STATE_NAMES) {
|
||||
const phase = mapGenerationStateToPhase(state);
|
||||
// Each known state should map to itself (identity mapping), NOT the default 'idle'
|
||||
expect(phase).toBe(state);
|
||||
}
|
||||
});
|
||||
|
||||
it('should map each generation state to a valid phase value', () => {
|
||||
const validPhases = new Set(['idle', 'analyzing', 'discovering', 'generating', 'complete', 'error']);
|
||||
for (const state of GENERATION_STATE_NAMES) {
|
||||
const phase = mapGenerationStateToPhase(state);
|
||||
expect(validPhases.has(phase)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('should return idle for unknown states', () => {
|
||||
expect(mapGenerationStateToPhase('nonexistent')).toBe('idle');
|
||||
expect(mapGenerationStateToPhase('')).toBe('idle');
|
||||
});
|
||||
|
||||
it('should have a case for every generation state (no silent fallthrough)', () => {
|
||||
// Verify that no known state falls through to the default case
|
||||
// by checking that each maps to its own name (identity)
|
||||
const defaultValue = mapGenerationStateToPhase('__unknown_sentinel__');
|
||||
for (const state of GENERATION_STATE_NAMES) {
|
||||
if (state === defaultValue) continue; // 'idle' is both a valid state and the default
|
||||
const result = mapGenerationStateToPhase(state);
|
||||
expect(result).not.toBe(defaultValue);
|
||||
}
|
||||
});
|
||||
|
||||
it('should include every machine state in GENERATION_STATE_NAMES (reverse direction)', () => {
|
||||
const machineStates = Object.keys(roadmapGenerationMachine.config.states ?? {});
|
||||
const stateNameSet = new Set<string>(GENERATION_STATE_NAMES);
|
||||
for (const machineState of machineStates) {
|
||||
expect(stateNameSet.has(machineState), `Machine state '${machineState}' missing from GENERATION_STATE_NAMES`).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('mapFeatureStateToStatus', () => {
|
||||
it('should map every FEATURE_STATE_NAMES entry to a non-default status', () => {
|
||||
for (const state of FEATURE_STATE_NAMES) {
|
||||
const status = mapFeatureStateToStatus(state);
|
||||
// Each known state should map to itself (identity mapping), NOT the default 'under_review'
|
||||
expect(status).toBe(state);
|
||||
}
|
||||
});
|
||||
|
||||
it('should map each feature state to a valid status value', () => {
|
||||
const validStatuses = new Set(['under_review', 'planned', 'in_progress', 'done']);
|
||||
for (const state of FEATURE_STATE_NAMES) {
|
||||
const status = mapFeatureStateToStatus(state);
|
||||
expect(validStatuses.has(status)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('should return under_review for unknown states', () => {
|
||||
expect(mapFeatureStateToStatus('nonexistent')).toBe('under_review');
|
||||
expect(mapFeatureStateToStatus('')).toBe('under_review');
|
||||
});
|
||||
|
||||
it('should have a case for every feature state (no silent fallthrough)', () => {
|
||||
// Verify that no known state falls through to the default case
|
||||
// by checking that each maps to its own name (identity)
|
||||
const defaultValue = mapFeatureStateToStatus('__unknown_sentinel__');
|
||||
for (const state of FEATURE_STATE_NAMES) {
|
||||
if (state === defaultValue) continue; // 'under_review' is both valid and default
|
||||
const result = mapFeatureStateToStatus(state);
|
||||
expect(result).not.toBe(defaultValue);
|
||||
}
|
||||
});
|
||||
|
||||
it('should include every machine state in FEATURE_STATE_NAMES (reverse direction)', () => {
|
||||
const machineStates = Object.keys(roadmapFeatureMachine.config.states ?? {});
|
||||
const stateNameSet = new Set<string>(FEATURE_STATE_NAMES);
|
||||
for (const machineState of machineStates) {
|
||||
expect(stateNameSet.has(machineState), `Machine state '${machineState}' missing from FEATURE_STATE_NAMES`).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -10,3 +10,28 @@ export type { TaskStateName } from './task-state-utils';
|
||||
|
||||
export { terminalMachine } from './terminal-machine';
|
||||
export type { TerminalContext, TerminalEvent } from './terminal-machine';
|
||||
|
||||
export { roadmapGenerationMachine } from './roadmap-generation-machine';
|
||||
export type {
|
||||
RoadmapGenerationContext,
|
||||
RoadmapGenerationEvent,
|
||||
} from './roadmap-generation-machine';
|
||||
|
||||
export { roadmapFeatureMachine } from './roadmap-feature-machine';
|
||||
export type {
|
||||
RoadmapFeatureContext,
|
||||
RoadmapFeatureEvent,
|
||||
} from './roadmap-feature-machine';
|
||||
|
||||
export {
|
||||
GENERATION_STATE_NAMES,
|
||||
FEATURE_STATE_NAMES,
|
||||
GENERATION_SETTLED_STATES,
|
||||
FEATURE_SETTLED_STATES,
|
||||
mapGenerationStateToPhase,
|
||||
mapFeatureStateToStatus,
|
||||
} from './roadmap-state-utils';
|
||||
export type {
|
||||
GenerationStateName,
|
||||
FeatureStateName,
|
||||
} from './roadmap-state-utils';
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
import { assign, createMachine } from 'xstate';
|
||||
import type { TaskOutcome, RoadmapFeatureStatus } from '../types/roadmap';
|
||||
|
||||
export interface RoadmapFeatureContext {
|
||||
linkedSpecId?: string;
|
||||
taskOutcome?: TaskOutcome;
|
||||
previousStatus?: RoadmapFeatureStatus;
|
||||
}
|
||||
|
||||
export type RoadmapFeatureEvent =
|
||||
| { type: 'PLAN' }
|
||||
| { type: 'START_PROGRESS' }
|
||||
| { type: 'MARK_DONE' }
|
||||
| { type: 'LINK_SPEC'; specId: string }
|
||||
| { type: 'TASK_COMPLETED' }
|
||||
| { type: 'TASK_DELETED' }
|
||||
| { type: 'TASK_ARCHIVED' }
|
||||
| { type: 'REVERT' }
|
||||
| { type: 'MOVE_TO_REVIEW' };
|
||||
|
||||
export const roadmapFeatureMachine = createMachine(
|
||||
{
|
||||
id: 'roadmapFeature',
|
||||
initial: 'under_review',
|
||||
types: {} as {
|
||||
context: RoadmapFeatureContext;
|
||||
events: RoadmapFeatureEvent;
|
||||
},
|
||||
context: {
|
||||
linkedSpecId: undefined,
|
||||
taskOutcome: undefined,
|
||||
previousStatus: undefined
|
||||
},
|
||||
states: {
|
||||
under_review: {
|
||||
on: {
|
||||
PLAN: 'planned',
|
||||
START_PROGRESS: 'in_progress',
|
||||
LINK_SPEC: {
|
||||
target: 'in_progress',
|
||||
actions: 'setLinkedSpec'
|
||||
},
|
||||
MARK_DONE: {
|
||||
target: 'done',
|
||||
actions: 'savePreviousUnderReview'
|
||||
},
|
||||
TASK_COMPLETED: {
|
||||
target: 'done',
|
||||
actions: ['savePreviousUnderReview', 'setTaskOutcomeCompleted']
|
||||
},
|
||||
TASK_DELETED: {
|
||||
target: 'done',
|
||||
actions: ['savePreviousUnderReview', 'setTaskOutcomeDeleted']
|
||||
},
|
||||
TASK_ARCHIVED: {
|
||||
target: 'done',
|
||||
actions: ['savePreviousUnderReview', 'setTaskOutcomeArchived']
|
||||
}
|
||||
}
|
||||
},
|
||||
planned: {
|
||||
on: {
|
||||
START_PROGRESS: 'in_progress',
|
||||
LINK_SPEC: {
|
||||
target: 'in_progress',
|
||||
actions: 'setLinkedSpec'
|
||||
},
|
||||
MARK_DONE: {
|
||||
target: 'done',
|
||||
actions: 'savePreviousPlanned'
|
||||
},
|
||||
TASK_COMPLETED: {
|
||||
target: 'done',
|
||||
actions: ['savePreviousPlanned', 'setTaskOutcomeCompleted']
|
||||
},
|
||||
TASK_DELETED: {
|
||||
target: 'done',
|
||||
actions: ['savePreviousPlanned', 'setTaskOutcomeDeleted']
|
||||
},
|
||||
TASK_ARCHIVED: {
|
||||
target: 'done',
|
||||
actions: ['savePreviousPlanned', 'setTaskOutcomeArchived']
|
||||
},
|
||||
MOVE_TO_REVIEW: 'under_review'
|
||||
}
|
||||
},
|
||||
in_progress: {
|
||||
on: {
|
||||
TASK_COMPLETED: {
|
||||
target: 'done',
|
||||
actions: ['savePreviousInProgress', 'setTaskOutcomeCompleted']
|
||||
},
|
||||
TASK_DELETED: {
|
||||
target: 'done',
|
||||
actions: ['savePreviousInProgress', 'setTaskOutcomeDeleted']
|
||||
},
|
||||
TASK_ARCHIVED: {
|
||||
target: 'done',
|
||||
actions: ['savePreviousInProgress', 'setTaskOutcomeArchived']
|
||||
},
|
||||
MARK_DONE: {
|
||||
target: 'done',
|
||||
actions: 'savePreviousInProgress'
|
||||
},
|
||||
MOVE_TO_REVIEW: {
|
||||
target: 'under_review',
|
||||
actions: 'clearDoneContext'
|
||||
},
|
||||
PLAN: {
|
||||
target: 'planned',
|
||||
actions: 'clearDoneContext'
|
||||
},
|
||||
LINK_SPEC: {
|
||||
actions: 'setLinkedSpec'
|
||||
}
|
||||
}
|
||||
},
|
||||
done: {
|
||||
on: {
|
||||
REVERT: [
|
||||
{
|
||||
target: 'in_progress',
|
||||
guard: 'previousWasInProgress',
|
||||
actions: 'clearDoneContext'
|
||||
},
|
||||
{
|
||||
target: 'planned',
|
||||
guard: 'previousWasPlanned',
|
||||
actions: 'clearDoneContext'
|
||||
},
|
||||
{
|
||||
target: 'under_review',
|
||||
actions: 'clearDoneContext'
|
||||
}
|
||||
],
|
||||
MARK_DONE: {
|
||||
target: 'done'
|
||||
},
|
||||
TASK_COMPLETED: {
|
||||
target: 'done',
|
||||
actions: 'setTaskOutcomeCompleted'
|
||||
},
|
||||
TASK_DELETED: {
|
||||
target: 'done',
|
||||
actions: 'setTaskOutcomeDeleted'
|
||||
},
|
||||
TASK_ARCHIVED: {
|
||||
target: 'done',
|
||||
actions: 'setTaskOutcomeArchived'
|
||||
},
|
||||
MOVE_TO_REVIEW: {
|
||||
target: 'under_review',
|
||||
actions: 'clearDoneContext'
|
||||
},
|
||||
PLAN: {
|
||||
target: 'planned',
|
||||
actions: 'clearDoneContext'
|
||||
},
|
||||
START_PROGRESS: {
|
||||
target: 'in_progress',
|
||||
actions: 'clearDoneContext'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
guards: {
|
||||
previousWasInProgress: ({ context }) => context.previousStatus === 'in_progress',
|
||||
previousWasPlanned: ({ context }) => context.previousStatus === 'planned'
|
||||
},
|
||||
actions: {
|
||||
setLinkedSpec: assign({
|
||||
linkedSpecId: ({ event }) =>
|
||||
event.type === 'LINK_SPEC' ? event.specId : undefined
|
||||
}),
|
||||
savePreviousUnderReview: assign({ previousStatus: () => 'under_review' as const }),
|
||||
savePreviousPlanned: assign({ previousStatus: () => 'planned' as const }),
|
||||
savePreviousInProgress: assign({ previousStatus: () => 'in_progress' as const }),
|
||||
setTaskOutcomeCompleted: assign({ taskOutcome: () => 'completed' as const }),
|
||||
setTaskOutcomeDeleted: assign({ taskOutcome: () => 'deleted' as const }),
|
||||
setTaskOutcomeArchived: assign({ taskOutcome: () => 'archived' as const }),
|
||||
clearDoneContext: assign({
|
||||
taskOutcome: () => undefined,
|
||||
previousStatus: () => undefined
|
||||
})
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -0,0 +1,117 @@
|
||||
import { assign, createMachine } from 'xstate';
|
||||
|
||||
export interface RoadmapGenerationContext {
|
||||
progress: number;
|
||||
message?: string;
|
||||
error?: string;
|
||||
startedAt?: number;
|
||||
completedAt?: number;
|
||||
lastActivityAt?: number;
|
||||
}
|
||||
|
||||
export type RoadmapGenerationEvent =
|
||||
| { type: 'START_GENERATION' }
|
||||
| { type: 'PROGRESS_UPDATE'; progress: number; message: string }
|
||||
| { type: 'DISCOVERY_STARTED' }
|
||||
| { type: 'GENERATION_STARTED' }
|
||||
| { type: 'GENERATION_COMPLETE' }
|
||||
| { type: 'GENERATION_ERROR'; error: string }
|
||||
| { type: 'STOP' }
|
||||
| { type: 'RESET' };
|
||||
|
||||
export const roadmapGenerationMachine = createMachine(
|
||||
{
|
||||
id: 'roadmapGeneration',
|
||||
initial: 'idle',
|
||||
types: {} as {
|
||||
context: RoadmapGenerationContext;
|
||||
events: RoadmapGenerationEvent;
|
||||
},
|
||||
context: {
|
||||
progress: 0,
|
||||
message: undefined,
|
||||
error: undefined,
|
||||
startedAt: undefined,
|
||||
completedAt: undefined,
|
||||
lastActivityAt: undefined,
|
||||
},
|
||||
states: {
|
||||
idle: {
|
||||
on: {
|
||||
START_GENERATION: { target: 'analyzing', actions: 'setStarted' },
|
||||
},
|
||||
},
|
||||
analyzing: {
|
||||
on: {
|
||||
PROGRESS_UPDATE: { actions: 'updateProgress' },
|
||||
DISCOVERY_STARTED: 'discovering',
|
||||
GENERATION_ERROR: { target: 'error', actions: 'setError' },
|
||||
STOP: { target: 'idle', actions: 'resetContext' },
|
||||
},
|
||||
},
|
||||
discovering: {
|
||||
on: {
|
||||
PROGRESS_UPDATE: { actions: 'updateProgress' },
|
||||
GENERATION_STARTED: 'generating',
|
||||
GENERATION_ERROR: { target: 'error', actions: 'setError' },
|
||||
STOP: { target: 'idle', actions: 'resetContext' },
|
||||
},
|
||||
},
|
||||
generating: {
|
||||
on: {
|
||||
PROGRESS_UPDATE: { actions: 'updateProgress' },
|
||||
GENERATION_COMPLETE: { target: 'complete', actions: 'setCompleted' },
|
||||
GENERATION_ERROR: { target: 'error', actions: 'setError' },
|
||||
STOP: { target: 'idle', actions: 'resetContext' },
|
||||
},
|
||||
},
|
||||
complete: {
|
||||
on: {
|
||||
RESET: { target: 'idle', actions: 'resetContext' },
|
||||
},
|
||||
},
|
||||
error: {
|
||||
on: {
|
||||
RESET: { target: 'idle', actions: 'resetContext' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
actions: {
|
||||
setStarted: assign({
|
||||
progress: () => 0,
|
||||
message: () => undefined,
|
||||
error: () => undefined,
|
||||
startedAt: () => Date.now(),
|
||||
completedAt: () => undefined,
|
||||
lastActivityAt: () => Date.now(),
|
||||
}),
|
||||
updateProgress: assign({
|
||||
progress: ({ event }) =>
|
||||
event.type === 'PROGRESS_UPDATE' ? Math.min(100, Math.max(0, event.progress)) : 0,
|
||||
message: ({ event }) =>
|
||||
event.type === 'PROGRESS_UPDATE' ? event.message : undefined,
|
||||
lastActivityAt: () => Date.now(),
|
||||
}),
|
||||
setCompleted: assign({
|
||||
progress: () => 100,
|
||||
completedAt: () => Date.now(),
|
||||
lastActivityAt: () => Date.now(),
|
||||
}),
|
||||
setError: assign({
|
||||
error: ({ event }) =>
|
||||
event.type === 'GENERATION_ERROR' ? event.error : undefined,
|
||||
lastActivityAt: () => Date.now(),
|
||||
}),
|
||||
resetContext: assign({
|
||||
progress: () => 0,
|
||||
message: () => undefined,
|
||||
error: () => undefined,
|
||||
startedAt: () => undefined,
|
||||
completedAt: () => undefined,
|
||||
lastActivityAt: () => undefined,
|
||||
}),
|
||||
},
|
||||
}
|
||||
);
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* Shared XState roadmap state utilities.
|
||||
*
|
||||
* Provides type-safe state names, settled states, and mapping helpers
|
||||
* derived from the roadmap machine definitions. Used by roadmap-store
|
||||
* and roadmap hooks to avoid duplicate constants.
|
||||
*/
|
||||
import type { StateValueFrom } from 'xstate';
|
||||
import type { RoadmapGenerationStatus, RoadmapFeatureStatus } from '../types/roadmap';
|
||||
import { roadmapGenerationMachine } from './roadmap-generation-machine';
|
||||
import { roadmapFeatureMachine } from './roadmap-feature-machine';
|
||||
|
||||
/**
|
||||
* All XState generation state names.
|
||||
*
|
||||
* IMPORTANT: These must match the state keys in roadmap-generation-machine.ts.
|
||||
* If you add/remove a state in the machine, update this array.
|
||||
*/
|
||||
export const GENERATION_STATE_NAMES = [
|
||||
'idle', 'analyzing', 'discovering', 'generating', 'complete', 'error'
|
||||
] as const;
|
||||
|
||||
export type GenerationStateName = typeof GENERATION_STATE_NAMES[number];
|
||||
|
||||
// Compile-time assertion: ensures every element in GENERATION_STATE_NAMES is a valid machine state.
|
||||
// The reverse direction (every machine state is in the array) is enforced by the exhaustive switch
|
||||
// in mapGenerationStateToPhase below — adding a new machine state without a switch case will cause
|
||||
// it to silently map to 'idle' via default, which the mapGenerationStateToPhase tests will catch.
|
||||
const _genCheck: readonly StateValueFrom<typeof roadmapGenerationMachine>[] = GENERATION_STATE_NAMES;
|
||||
|
||||
/**
|
||||
* All XState feature state names.
|
||||
*
|
||||
* IMPORTANT: These must match the state keys in roadmap-feature-machine.ts.
|
||||
* If you add/remove a state in the machine, update this array.
|
||||
*/
|
||||
export const FEATURE_STATE_NAMES = [
|
||||
'under_review', 'planned', 'in_progress', 'done'
|
||||
] as const;
|
||||
|
||||
export type FeatureStateName = typeof FEATURE_STATE_NAMES[number];
|
||||
|
||||
// Compile-time assertion: ensures every element in FEATURE_STATE_NAMES is a valid machine state.
|
||||
// Reverse direction enforced by mapFeatureStateToStatus switch exhaustiveness (see comment above).
|
||||
const _featCheck: readonly StateValueFrom<typeof roadmapFeatureMachine>[] = FEATURE_STATE_NAMES;
|
||||
|
||||
/**
|
||||
* Generation states where the machine has settled — the generation is
|
||||
* complete or has errored. Stale progress events should NOT overwrite
|
||||
* these states, as XState is the source of truth.
|
||||
*
|
||||
* NOTE: Exported for future consumer use (e.g., UI components that need to
|
||||
* check if generation is settled before allowing user actions). Currently
|
||||
* unused but intentionally retained as public API for roadmap state checking.
|
||||
*/
|
||||
export const GENERATION_SETTLED_STATES: ReadonlySet<string> = new Set<GenerationStateName>([
|
||||
'complete', 'error'
|
||||
]);
|
||||
|
||||
/**
|
||||
* Feature states where the machine has settled — the feature is done.
|
||||
* Stale task lifecycle events should NOT overwrite this state.
|
||||
*
|
||||
* NOTE: Exported for future consumer use (e.g., UI components that need to
|
||||
* check if feature is settled before allowing drag-and-drop or status changes).
|
||||
* Currently unused but intentionally retained as public API for feature state checking.
|
||||
*/
|
||||
export const FEATURE_SETTLED_STATES: ReadonlySet<string> = new Set<FeatureStateName>([
|
||||
'done'
|
||||
]);
|
||||
|
||||
/**
|
||||
* Maps an XState generation state to the RoadmapGenerationStatus phase.
|
||||
*
|
||||
* The generation machine states map 1:1 to the phase union type, so this
|
||||
* is a type-safe identity mapping with a fallback for unknown states.
|
||||
*/
|
||||
export function mapGenerationStateToPhase(
|
||||
state: string
|
||||
): RoadmapGenerationStatus['phase'] {
|
||||
switch (state) {
|
||||
case 'idle':
|
||||
return 'idle';
|
||||
case 'analyzing':
|
||||
return 'analyzing';
|
||||
case 'discovering':
|
||||
return 'discovering';
|
||||
case 'generating':
|
||||
return 'generating';
|
||||
case 'complete':
|
||||
return 'complete';
|
||||
case 'error':
|
||||
return 'error';
|
||||
default:
|
||||
return 'idle';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps an XState feature state to the RoadmapFeatureStatus type.
|
||||
*
|
||||
* The feature machine states map 1:1 to the status union type, so this
|
||||
* is a type-safe identity mapping with a fallback for unknown states.
|
||||
*/
|
||||
export function mapFeatureStateToStatus(
|
||||
state: string
|
||||
): RoadmapFeatureStatus {
|
||||
switch (state) {
|
||||
case 'under_review':
|
||||
return 'under_review';
|
||||
case 'planned':
|
||||
return 'planned';
|
||||
case 'in_progress':
|
||||
return 'in_progress';
|
||||
case 'done':
|
||||
return 'done';
|
||||
default:
|
||||
return 'under_review';
|
||||
}
|
||||
}
|
||||
@@ -126,12 +126,16 @@ export const taskMachine = createMachine(
|
||||
on: {
|
||||
CREATE_PR: 'creating_pr',
|
||||
MARK_DONE: 'done',
|
||||
USER_RESUMED: { target: 'coding', actions: 'clearReviewReason' }
|
||||
USER_RESUMED: { target: 'coding', actions: 'clearReviewReason' },
|
||||
// Allow restarting planning from human_review (e.g., incomplete task with no subtasks)
|
||||
PLANNING_STARTED: { target: 'planning', actions: 'clearReviewReason' }
|
||||
}
|
||||
},
|
||||
error: {
|
||||
on: {
|
||||
USER_RESUMED: { target: 'coding', actions: 'clearReviewReason' },
|
||||
// Allow restarting from error back to planning (e.g., spec creation crashed)
|
||||
PLANNING_STARTED: { target: 'planning', actions: 'clearReviewReason' },
|
||||
MARK_DONE: 'done'
|
||||
}
|
||||
},
|
||||
|
||||
@@ -108,6 +108,7 @@ import type {
|
||||
InsightsModelConfig
|
||||
} from './insights';
|
||||
import type {
|
||||
CompetitorAnalysis,
|
||||
Roadmap,
|
||||
RoadmapFeatureStatus,
|
||||
RoadmapGenerationStatus,
|
||||
@@ -416,6 +417,7 @@ export interface ElectronAPI {
|
||||
getRoadmap: (projectId: string) => Promise<IPCResult<Roadmap | null>>;
|
||||
getRoadmapStatus: (projectId: string) => Promise<IPCResult<{ isRunning: boolean }>>;
|
||||
saveRoadmap: (projectId: string, roadmap: Roadmap) => Promise<IPCResult>;
|
||||
saveCompetitorAnalysis: (projectId: string, competitorAnalysis: CompetitorAnalysis) => Promise<IPCResult>;
|
||||
generateRoadmap: (projectId: string, enableCompetitorAnalysis?: boolean, refreshCompetitorAnalysis?: boolean) => void;
|
||||
refreshRoadmap: (projectId: string, enableCompetitorAnalysis?: boolean, refreshCompetitorAnalysis?: boolean) => void;
|
||||
stopRoadmap: (projectId: string) => Promise<IPCResult>;
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
// Competitor Analysis Types
|
||||
// ============================================
|
||||
|
||||
export type CompetitorSource = 'manual' | 'ai';
|
||||
export type CompetitorRelevance = 'high' | 'medium' | 'low';
|
||||
export type PainPointSeverity = 'high' | 'medium' | 'low';
|
||||
export type OpportunitySize = 'high' | 'medium' | 'low';
|
||||
@@ -28,6 +29,14 @@ export interface Competitor {
|
||||
painPoints: CompetitorPainPoint[];
|
||||
strengths: string[];
|
||||
marketPosition: string;
|
||||
source?: CompetitorSource;
|
||||
}
|
||||
|
||||
export interface ManualCompetitorInput {
|
||||
name: string;
|
||||
url: string;
|
||||
description: string;
|
||||
relevance: CompetitorRelevance;
|
||||
}
|
||||
|
||||
export interface CompetitorMarketGap {
|
||||
|
||||
Generated
+3
-3
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "auto-claude",
|
||||
"version": "2.7.6-beta.3",
|
||||
"version": "2.7.6-beta.6",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "auto-claude",
|
||||
"version": "2.7.6-beta.3",
|
||||
"version": "2.7.6-beta.6",
|
||||
"license": "AGPL-3.0",
|
||||
"workspaces": [
|
||||
"apps/*",
|
||||
@@ -25,7 +25,7 @@
|
||||
},
|
||||
"apps/frontend": {
|
||||
"name": "auto-claude-ui",
|
||||
"version": "2.7.6-beta.3",
|
||||
"version": "2.7.6-beta.6",
|
||||
"hasInstallScript": true,
|
||||
"license": "AGPL-3.0",
|
||||
"dependencies": {
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "auto-claude",
|
||||
"version": "2.7.6-beta.5",
|
||||
"version": "2.7.6",
|
||||
"description": "Autonomous multi-agent coding framework powered by Claude AI",
|
||||
"license": "AGPL-3.0",
|
||||
"author": "Auto Claude Team",
|
||||
|
||||
@@ -337,6 +337,136 @@ class TestGitHubCLIInvocation:
|
||||
assert result["success"] is True
|
||||
|
||||
|
||||
class TestGitHubOriginPrefixStripping:
|
||||
"""Test that origin/ prefix is stripped from target_branch in create_pull_request."""
|
||||
|
||||
def test_origin_prefix_stripped_from_target_branch(self, tmp_path):
|
||||
"""Test that 'origin/develop' becomes 'develop' in --base argument to gh CLI."""
|
||||
# Setup
|
||||
project_dir = tmp_path / "project"
|
||||
project_dir.mkdir()
|
||||
spec_dir = tmp_path / "spec"
|
||||
spec_dir.mkdir()
|
||||
|
||||
# Create .auto-claude directories
|
||||
auto_claude_dir = project_dir / ".auto-claude"
|
||||
auto_claude_dir.mkdir(exist_ok=True)
|
||||
|
||||
# Create WorktreeManager
|
||||
manager = WorktreeManager(
|
||||
project_dir=project_dir,
|
||||
base_branch="main",
|
||||
)
|
||||
|
||||
# Mock get_worktree_info to return a valid WorktreeInfo
|
||||
mock_worktree_info = WorktreeInfo(
|
||||
path=spec_dir,
|
||||
branch="auto-claude/001-test-spec",
|
||||
spec_name="001-test-spec",
|
||||
base_branch="main",
|
||||
is_active=True,
|
||||
)
|
||||
|
||||
# Mock subprocess result
|
||||
mock_subprocess_result = MagicMock(
|
||||
returncode=0,
|
||||
stdout="https://github.com/user/repo/pull/123\n",
|
||||
stderr="",
|
||||
)
|
||||
|
||||
# Import the actual module to patch it directly
|
||||
import core.worktree as worktree_module
|
||||
|
||||
with (
|
||||
patch.object(manager, "get_worktree_info", return_value=mock_worktree_info),
|
||||
patch.object(
|
||||
worktree_module, "get_gh_executable", return_value="/usr/bin/gh"
|
||||
),
|
||||
patch.object(
|
||||
worktree_module.subprocess, "run", return_value=mock_subprocess_result
|
||||
) as mock_run,
|
||||
patch.object(manager, "_extract_spec_summary", return_value="Test PR body"),
|
||||
):
|
||||
result = manager.create_pull_request(
|
||||
spec_name="001-test-spec",
|
||||
target_branch="origin/develop",
|
||||
title="Test PR Title",
|
||||
draft=False,
|
||||
)
|
||||
|
||||
# Verify gh CLI received "develop" (not "origin/develop") as --base
|
||||
assert mock_run.called
|
||||
call_args = mock_run.call_args[0][0]
|
||||
base_idx = call_args.index("--base")
|
||||
assert call_args[base_idx + 1] == "develop", (
|
||||
f"Expected 'develop' after --base, got '{call_args[base_idx + 1]}'"
|
||||
)
|
||||
assert result["success"] is True
|
||||
|
||||
def test_target_branch_without_origin_prefix_unchanged(self, tmp_path):
|
||||
"""Test that 'develop' (no prefix) is passed through unchanged to gh CLI."""
|
||||
# Setup
|
||||
project_dir = tmp_path / "project"
|
||||
project_dir.mkdir()
|
||||
spec_dir = tmp_path / "spec"
|
||||
spec_dir.mkdir()
|
||||
|
||||
# Create .auto-claude directories
|
||||
auto_claude_dir = project_dir / ".auto-claude"
|
||||
auto_claude_dir.mkdir(exist_ok=True)
|
||||
|
||||
# Create WorktreeManager
|
||||
manager = WorktreeManager(
|
||||
project_dir=project_dir,
|
||||
base_branch="main",
|
||||
)
|
||||
|
||||
# Mock get_worktree_info to return a valid WorktreeInfo
|
||||
mock_worktree_info = WorktreeInfo(
|
||||
path=spec_dir,
|
||||
branch="auto-claude/001-test-spec",
|
||||
spec_name="001-test-spec",
|
||||
base_branch="main",
|
||||
is_active=True,
|
||||
)
|
||||
|
||||
# Mock subprocess result
|
||||
mock_subprocess_result = MagicMock(
|
||||
returncode=0,
|
||||
stdout="https://github.com/user/repo/pull/123\n",
|
||||
stderr="",
|
||||
)
|
||||
|
||||
# Import the actual module to patch it directly
|
||||
import core.worktree as worktree_module
|
||||
|
||||
with (
|
||||
patch.object(manager, "get_worktree_info", return_value=mock_worktree_info),
|
||||
patch.object(
|
||||
worktree_module, "get_gh_executable", return_value="/usr/bin/gh"
|
||||
),
|
||||
patch.object(
|
||||
worktree_module.subprocess, "run", return_value=mock_subprocess_result
|
||||
) as mock_run,
|
||||
patch.object(manager, "_extract_spec_summary", return_value="Test PR body"),
|
||||
):
|
||||
result = manager.create_pull_request(
|
||||
spec_name="001-test-spec",
|
||||
target_branch="develop",
|
||||
title="Test PR Title",
|
||||
draft=False,
|
||||
)
|
||||
|
||||
# Verify gh CLI received "develop" as --base
|
||||
assert mock_run.called
|
||||
call_args = mock_run.call_args[0][0]
|
||||
base_idx = call_args.index("--base")
|
||||
assert call_args[base_idx + 1] == "develop", (
|
||||
f"Expected 'develop' after --base, got '{call_args[base_idx + 1]}'"
|
||||
)
|
||||
assert result["success"] is True
|
||||
|
||||
|
||||
class TestGitHubErrorHandling:
|
||||
"""Test that GitHub error handling still works correctly."""
|
||||
|
||||
|
||||
@@ -270,6 +270,118 @@ class TestCreateMergeRequest:
|
||||
assert result["pr_url"] == "https://gitlab.com/user/repo/-/merge_requests/44"
|
||||
|
||||
|
||||
class TestGitLabOriginPrefixStripping:
|
||||
"""Test that origin/ prefix is stripped from target_branch in create_merge_request."""
|
||||
|
||||
def test_origin_prefix_stripped_from_target_branch(
|
||||
self, worktree_manager, temp_project_dir
|
||||
):
|
||||
"""Test that 'origin/develop' becomes 'develop' in --target-branch argument to glab CLI."""
|
||||
import core.worktree as worktree_module
|
||||
|
||||
spec_name = "test-feature"
|
||||
|
||||
mock_worktree_info = WorktreeInfo(
|
||||
path=temp_project_dir / ".auto-claude" / "worktrees" / "tasks" / spec_name,
|
||||
branch=f"auto-claude/{spec_name}",
|
||||
spec_name=spec_name,
|
||||
base_branch="main",
|
||||
is_active=True,
|
||||
)
|
||||
|
||||
mock_subprocess_result = MagicMock(
|
||||
returncode=0,
|
||||
stdout="https://gitlab.com/user/repo/-/merge_requests/42\n",
|
||||
stderr="",
|
||||
)
|
||||
|
||||
with (
|
||||
patch.object(
|
||||
worktree_manager, "get_worktree_info", return_value=mock_worktree_info
|
||||
),
|
||||
patch.object(
|
||||
worktree_module,
|
||||
"get_glab_executable",
|
||||
return_value="/usr/local/bin/glab",
|
||||
),
|
||||
patch.object(
|
||||
worktree_module.subprocess, "run", return_value=mock_subprocess_result
|
||||
) as mock_run,
|
||||
patch.object(
|
||||
worktree_manager, "_extract_spec_summary", return_value="Test MR body"
|
||||
),
|
||||
):
|
||||
result = worktree_manager.create_merge_request(
|
||||
spec_name=spec_name,
|
||||
target_branch="origin/develop",
|
||||
title="Test MR",
|
||||
draft=False,
|
||||
)
|
||||
|
||||
# Verify glab CLI received "develop" (not "origin/develop") as --target-branch
|
||||
assert mock_run.called
|
||||
call_args = mock_run.call_args[0][0]
|
||||
target_idx = call_args.index("--target-branch")
|
||||
assert call_args[target_idx + 1] == "develop", (
|
||||
f"Expected 'develop' after --target-branch, got '{call_args[target_idx + 1]}'"
|
||||
)
|
||||
assert result["success"] is True
|
||||
|
||||
def test_target_branch_without_origin_prefix_unchanged(
|
||||
self, worktree_manager, temp_project_dir
|
||||
):
|
||||
"""Test that 'develop' (no prefix) is passed through unchanged to glab CLI."""
|
||||
import core.worktree as worktree_module
|
||||
|
||||
spec_name = "test-feature"
|
||||
|
||||
mock_worktree_info = WorktreeInfo(
|
||||
path=temp_project_dir / ".auto-claude" / "worktrees" / "tasks" / spec_name,
|
||||
branch=f"auto-claude/{spec_name}",
|
||||
spec_name=spec_name,
|
||||
base_branch="main",
|
||||
is_active=True,
|
||||
)
|
||||
|
||||
mock_subprocess_result = MagicMock(
|
||||
returncode=0,
|
||||
stdout="https://gitlab.com/user/repo/-/merge_requests/43\n",
|
||||
stderr="",
|
||||
)
|
||||
|
||||
with (
|
||||
patch.object(
|
||||
worktree_manager, "get_worktree_info", return_value=mock_worktree_info
|
||||
),
|
||||
patch.object(
|
||||
worktree_module,
|
||||
"get_glab_executable",
|
||||
return_value="/usr/local/bin/glab",
|
||||
),
|
||||
patch.object(
|
||||
worktree_module.subprocess, "run", return_value=mock_subprocess_result
|
||||
) as mock_run,
|
||||
patch.object(
|
||||
worktree_manager, "_extract_spec_summary", return_value="Test MR body"
|
||||
),
|
||||
):
|
||||
result = worktree_manager.create_merge_request(
|
||||
spec_name=spec_name,
|
||||
target_branch="develop",
|
||||
title="Test MR",
|
||||
draft=False,
|
||||
)
|
||||
|
||||
# Verify glab CLI received "develop" as --target-branch
|
||||
assert mock_run.called
|
||||
call_args = mock_run.call_args[0][0]
|
||||
target_idx = call_args.index("--target-branch")
|
||||
assert call_args[target_idx + 1] == "develop", (
|
||||
f"Expected 'develop' after --target-branch, got '{call_args[target_idx + 1]}'"
|
||||
)
|
||||
assert result["success"] is True
|
||||
|
||||
|
||||
class TestPushAndCreatePR:
|
||||
"""Test push_and_create_pr method with provider detection."""
|
||||
|
||||
|
||||
Reference in New Issue
Block a user