Dev Server Dock For WorktreeCards: Process Management

by Alex Johnson 54 views

Developing AI agents across multiple Git worktrees can be a complex task, often requiring developers to juggle numerous development servers. This article explores how adding a dev server dock to Canopy, a tool designed to manage worktrees, can significantly improve developer workflow. By integrating process management directly into the WorktreeCards, Canopy evolves from a simple file browser into a comprehensive runtime environment manager. This enhancement allows developers to start, monitor, and stop development servers with a single keystroke, streamlining their workflow and reducing cognitive overhead.

The Challenge: Managing Multiple Dev Servers

When working on AI agents across various worktrees, developers frequently encounter the challenge of managing multiple development servers. The current process involves several manual steps, which can be both time-consuming and error-prone. These steps typically include:

  • Manually switching between terminals for each worktree.
  • Running commands like npm run dev or similar in each worktree.
  • Tracking which servers are running on which ports.
  • Manually stopping servers when switching contexts.

This manual process not only creates friction but also increases cognitive load. Developers may forget which servers are running in background worktrees, leading to port conflicts and other issues. The lack of a visual indicator for active servers in each worktree further complicates the management process. Addressing these challenges is crucial for enhancing developer productivity and reducing the risk of errors.

User impact is significant when these manual processes are streamlined. Developers waste less time managing dev servers across worktrees, reducing the chances of forgotten servers running in the background and the risk of port conflicts from orphaned processes. Furthermore, a visual indicator of which worktrees have active servers provides immediate clarity and control. By integrating dev server management into Canopy, developers can focus more on coding and less on administrative tasks.

The Solution: One-Keystroke Dev Server Management

To address these challenges, the proposed solution is to integrate one-keystroke dev server management directly into Canopy's WorktreeCards. This enhancement aims to transform Canopy from a file browser into a runtime environment manager, providing developers with a seamless experience for managing their development servers. The primary goal is to enable developers to start and stop servers without leaving the Canopy dashboard, while also providing a clear visual indication of which worktrees have running servers. This integration will significantly reduce the friction associated with managing multiple dev servers and improve overall workflow efficiency.

The user story driving this enhancement is clear: As a developer working with AI agents across multiple Git worktrees, the desire is to have one-keystroke dev server management integrated into Canopy's WorktreeCards. This would allow for starting and stopping servers without leaving the dashboard and always knowing which worktrees have running servers. By fulfilling this user story, Canopy can provide a more intuitive and efficient development experience.

Current Architecture and Proposed Enhancements

Canopy's current architecture includes several key components that will facilitate the integration of dev server management. These components include:

  • WorktreeCard Component: Renders individual worktree cards, providing a visual representation of each worktree. (src/components/WorktreeCard.tsx)
  • WorktreeService: Manages worktree monitors, ensuring that Canopy is aware of the status of each worktree. (src/services/monitor/WorktreeService.ts)
  • Event Bus: A typed event system for decoupled communication between different parts of the application. (src/services/events.ts)
  • Type System: Centralized type definitions that ensure consistency and prevent errors across the application. (src/types/index.ts)

To enhance Canopy with dev server management, several new components and modifications to existing ones are proposed. These include the creation of a DevServerManager service, a useDevServer hook, and a ServerDock component. Additionally, modifications to the WorktreeCard component, type system, and event bus will be necessary to support the new functionality.

Before implementing the Server Dock, it's important to address a related UI issue: the inconsistent border styles in WorktreeCards. Currently, focused cards use double borders, while unfocused cards use round borders. To maintain a consistent and clean user interface, it is recommended to standardize all cards to use round borders. The traffic light indicator and branch name highlighting already provide sufficient focus indication, making the double border style unnecessary.

Deliverables: Key Code Changes

The implementation of dev server management in Canopy will involve the creation of new files and the modification of existing ones. Here is a detailed overview of the key code changes:

New Files to Create

  1. DevServerManager Service (src/services/server/DevServerManager.ts):

    • This service will be responsible for managing the lifecycle of development servers. It will maintain a process registry mapping worktreeId to ChildProcess, allowing for the tracking and control of individual server processes.
    • The service will include URL detection from stdout using regex patterns, enabling Canopy to automatically identify the URL of the running server.
    • Lifecycle management functions such as start, stop, and restart will be implemented to control the server processes.
    • The service will emit events to notify other parts of the application of state changes, such as when a server starts, stops, or encounters an error.
  2. Dev Server Hook (src/hooks/useDevServer.ts):

    • This hook will allow React components to subscribe to DevServerManager events for a specific worktree.
    • It will return an object containing the server's status (status), URL (url), and functions to start (start), stop (stop), and access logs (logs).
    • The hook will provide a simple and consistent interface for interacting with the DevServerManager from React components.
  3. Server Dock Component (src/components/ServerDock.tsx):

    • This component will provide a user interface for displaying the status of the development server.
    • It will include a status indicator (e.g., stopped, starting, running, error) to visually represent the server's state.
    • When the server is running, the component will display the URL, allowing developers to quickly access the application in their browser.
    • The component will include start and stop buttons, enabling developers to control the server with a single click.

Files to Modify

  1. src/components/WorktreeCard.tsx:

    • The conditional borderStyle logic will be removed to standardize all cards to use round borders.
    • The ServerDock component will be added as a conditional section at the bottom of the WorktreeCard, allowing it to be displayed when appropriate.
  2. src/types/index.ts:

    • A DevServerStatus type will be added to represent the possible states of a development server (e.g., 'stopped' | 'starting' | 'running' | 'error').
    • A DevServerState interface will be added to encapsulate the state of a development server, including its status, URL, port, PID, and error message.
    • A devServer config option will be added to the CanopyConfig interface, allowing users to configure the behavior of the dev server management system.
  3. src/services/events.ts:

    • A server:update event type will be added to notify components when the state of a server changes.
    • A server:error event type will be added to notify components when a server encounters an error.
  4. src/hooks/useDashboardNav.ts:

    • A s keyboard shortcut will be added to toggle the dev server for the focused worktree, providing a quick and convenient way to start and stop servers.

Implementation Details

DevServerManager Architecture:

The DevServerManager will maintain a map of worktree IDs to ChildProcess objects, allowing it to track and control individual server processes. It will also maintain a map of worktree IDs to DevServerState objects, providing a centralized store for server state information.

interface DevServerState {
  worktreeId: string;
  status: 'stopped' | 'starting' | 'running' | 'error';
  url?: string;
  port?: number;
  pid?: number;
  errorMessage?: string;
}

class DevServerManager {
  private servers = new Map<string, ChildProcess>();
  private states = new Map<string, DevServerState>();
  
  async start(worktreeId: string, command?: string): Promise<void>;
  async stop(worktreeId: string): Promise<void>;
  getState(worktreeId: string): DevServerState;
}

URL Detection Patterns:

The DevServerManager will use regex patterns to detect the URL of the running server from its stdout. Common patterns include:

  • Local: http://localhost:3000
  • Listening on 0.0.0.0:8080
  • Server running at http://127.0.0.1:5173
  • Started server on http://localhost:4200

Configuration Strategy:

The system will use an auto-detection strategy with config override. It will first check the package.json file for dev or start scripts. Users will be able to override this behavior in the .canopy.json file:

{
  "devServer": {
    "command": "npm run start:frontend",
    "autoStart": false
  }
}

Testing and Documentation

Tests

Comprehensive testing will be conducted to ensure the reliability and stability of the dev server management system. This will include both unit and integration tests.

Unit Tests:

  • DevServerManager process lifecycle
  • URL detection regex patterns
  • State management and event emission
  • Config detection from package.json

Integration Tests:

  • Server start/stop via keyboard shortcut
  • State persistence across card re-renders
  • Graceful shutdown on app exit

Documentation

To ensure that developers can effectively use the new dev server management system, the following documentation updates will be made:

  • Update CLAUDE.md with new service and hook documentation.
  • Add the s keyboard shortcut to the shortcuts section.

Technical Specifications: Footprint, Performance, and Dependencies

Footprint:

  • src/services/server/ - new service directory
  • src/hooks/useDevServer.ts - new hook
  • src/components/ServerDock.tsx - new component
  • Modifications to WorktreeCard, events, types, useDashboardNav

Performance Considerations:

  • Process spawning is async and non-blocking.
  • URL detection streams stdout (no buffering entire output).
  • State updates debounced to prevent render thrashing.
  • Servers persist outside the React render cycle.

Dependencies:

  • Use Node.js built-in child_process.spawn (no new deps needed).
  • Consider the tree-kill package for proper process tree cleanup on Windows.

Tasks: Phased Implementation

The implementation of dev server management in Canopy will be carried out in several phases to ensure a smooth and manageable process.

Phase 1: UI Standardization

  • [ ] Remove conditional borderStyle in WorktreeCard.tsx:225 - standardize to round
  • [ ] Verify focus indication still works via branch name highlighting

Phase 2: Type System & Events

  • [ ] Add DevServerStatus and DevServerState types to src/types/index.ts
  • [ ] Add devServer config option to CanopyConfig interface
  • [ ] Add server:update and server:error events to src/services/events.ts

Phase 3: DevServerManager Service

  • [ ] Create src/services/server/index.ts with exports
  • [ ] Implement DevServerManager class with process registry
  • [ ] Add URL detection regex for common dev server outputs
  • [ ] Implement start(), stop(), restart() methods
  • [ ] Add event emission for state changes
  • [ ] Implement graceful shutdown (SIGTERM → SIGKILL fallback)

Phase 4: React Integration

  • [ ] Create src/hooks/useDevServer.ts hook
  • [ ] Create src/components/ServerDock.tsx component
  • [ ] Integrate ServerDock into WorktreeCard (conditional render)
  • [ ] Add s keyboard shortcut to useDashboardNav.ts

Phase 5: Config & Detection

  • [ ] Implement package.json script detection
  • [ ] Add .canopy.json devServer config parsing
  • [ ] Update DEFAULT_CONFIG with devServer defaults

Phase 6: Cleanup & Polish

  • [ ] Add proper process cleanup on app exit
  • [ ] Handle port conflicts gracefully
  • [ ] Add tests for DevServerManager
  • [ ] Update documentation

Acceptance Criteria: Ensuring Success

The following acceptance criteria will be used to determine the success of the dev server management integration:

  • [ ] All WorktreeCards display with consistent round border style
  • [ ] WorktreeCards with detected dev scripts show "Start Dev" option when focused
  • [ ] Pressing s on focused card starts dev server with visual feedback
  • [ ] Running servers display URL in dock section (e.g., 🟢 http://localhost:3000)
  • [ ] Pressing s again stops the running server
  • [ ] Servers persist when switching focus between worktrees
  • [ ] All servers gracefully terminated on Canopy exit
  • [ ] Config override via .canopy.json works correctly
  • [ ] Tests pass for DevServerManager lifecycle

Edge Cases & Risks: Addressing Potential Issues

Edge Cases:

  • Port already in use - show error state with message
  • Dev script missing - don't show the server dock for that worktree
  • Process crashes - detect and show error state
  • Multiple dev scripts (frontend/backend) - MVP uses the first dev script found
  • Worktree removed while the server is running - stop the server and clean up

Risks:

  • Orphaned processes on unexpected exit - mitigate with a SIGTERM handler
  • Windows process tree cleanup differs from Unix - may need the tree-kill package
  • Long-running servers consume resources - consider idle detection in the future

Additional Context: Visual Concept

Visual Concept for Server Dock:

╭─── feature/login • worktrees/login ───────── [ACTIVE] ───╮
│ Summary: 🔧 Implementing OAuth flow                      │
│ ● 5 files • +128 • -34                                   │
│                                                          │
│ [Expand] [CopyTree] [VS Code] [Finder]                   │
├──────────────────────────────────────────────────────────┤
│ 🟢 Running: http://localhost:3000              [s] Stop  │
╰──────────────────────────────────────────────────────────╯

States:

  • No dev script detected: Dock not shown
  • Stopped: ⚫ [s] Start Dev Server
  • Starting: 🟡 Starting...
  • Running: 🟢 http://localhost:3000 [s] Stop
  • Error: 🔴 Error: Port 3000 in use [s] Retry

Conclusion: Enhancing Developer Productivity with Canopy

Integrating a dev server dock into Canopy's WorktreeCards represents a significant enhancement to developer workflow. By streamlining process management and providing a visual interface for server status, Canopy transforms into a more powerful tool for managing AI agent development across multiple Git worktrees. This improvement not only reduces the cognitive overhead associated with manual server management but also allows developers to focus more on coding and less on administrative tasks. The phased implementation plan ensures a smooth rollout of the new features, while comprehensive testing and documentation will guarantee the reliability and usability of the system.

For further reading on process management and development environments, consider exploring resources from trusted websites such as https://developer.mozilla.org/.