Commit Graph

9 Commits

Author SHA1 Message Date
prateek 59c490a3af
fix: dashboard config discovery + CLI service layer refactoring (#70)
* fix: config discovery, activity detection, and metadata port storage

- findConfigFile() checks AO_CONFIG_PATH env var (resolved to absolute path)
- loadConfig() delegates to findConfigFile() for consistent validation
- Pure Node.js readLastJsonlEntry (no external tail binary), safe for
  multi-byte UTF-8 at chunk boundaries
- Added "ready" activity state to agent plugins
- Store dashboardPort, terminalWsPort, directTerminalWsPort in session
  metadata so ao stop targets the correct processes
- Zod schema port default aligned with TypeScript interface

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: dashboard config discovery + CLI service layer refactoring

- Config discovery via AO_CONFIG_PATH env var
- Auto port detection with PortManager
- Activity detection with ready state, pure Node.js readLastLine
- 5 CLI services: ConfigService, PortManager, DashboardManager, MetadataService, ProcessManager
- Store all service ports in metadata for ao stop
- Set NEXT_PUBLIC_ env vars for frontend terminal components
- Multi-byte UTF-8 safe readLastJsonlEntry
- Tests for all new services and utils

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: address bugbot review comments (port fallback + systemPrompt)

1. Align port fallback to 3000 everywhere (matching Zod schema default):
   - start.ts: config.port ?? 3000
   - dashboard.ts: config.port ?? 3000
   - types.ts JSDoc: "defaults to 3000"
   - orchestrator-prompt.ts: already correct at 3000

2. Add --append-system-prompt to Claude Code plugin's getLaunchCommand
   so orchestrator context is actually passed to the Claude agent.
   Previously systemPrompt was generated but silently dropped.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: remove dead ConfigService mock from status test

The vi.mock for ConfigService.js referenced a deleted module.
Config mocking is already handled by the @composio/ao-core mock.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: extract shared buildDashboardEnv to eliminate duplication

Dashboard env construction (AO_CONFIG_PATH, PORT, NEXT_PUBLIC_*) was
duplicated between start.ts and dashboard.ts. Extracted into
buildDashboardEnv() in web-dir.ts (already shared by both commands).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 17:08:48 +05:30
prateek bba1316527
feat: implement DirectTerminal with XDA clipboard support (#55)
* feat: implement DirectTerminal with XDA clipboard support

Fixes clipboard functionality in web terminal without requiring iTerm2 attachment.

## Problem
Browser clipboard (Cmd+C/Ctrl+C) only worked when an iTerm2 client was attached
to the tmux session. Users had to keep iTerm2 tabs open in the background for
clipboard to work in the web dashboard.

## Root Cause
- tmux uses XDA (Extended Device Attributes) queries to detect terminal capabilities
- xterm.js doesn't implement XDA (marked as TODO in their codebase)
- Without XDA response, tmux doesn't enable clipboard support (TTYC_MS)
- iTerm2 responds to XDA, enabling clipboard for the entire session

## Solution
Implemented DirectTerminal component with custom XDA handler:
- Registers CSI > q handler using xterm.js parser API
- Responds with XTerm identification: DCS > | XTerm(370) ST
- tmux detects "XTerm(" and enables clipboard capability
- OSC 52 sequences flow: tmux → WebSocket → xterm.js → navigator.clipboard

## Changes
- Add DirectTerminal component with XDA handler
- Add direct-terminal-ws WebSocket server using node-pty
- Replace Terminal with DirectTerminal in SessionDetail
- Add comprehensive test page at /dev/terminal-test documenting:
  - Root cause analysis
  - Implementation details
  - Node version requirements (requires Node 20.x due to node-pty)
  - Debugging journey and lessons learned
- Fix ttyd port recycling to prevent EADDRINUSE errors

## Testing
Visit http://localhost:3000/dev/terminal-test for side-by-side comparison
and complete documentation.

Investigation time: 12+ hours (Feb 15-16, 2026)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: lint and typecheck errors

- Remove unused expectedWidth variable in DirectTerminal
- Add test files to eslint ignores

* fix: wrap useSearchParams in Suspense boundary

- Add Suspense wrapper to /dev/terminal-test page
- Add Suspense wrapper to /test-direct page
- Fixes Next.js build prerender error

* fix: address Bugbot review comments

- Fix useEffect cleanup memory leak in DirectTerminal
- Remove accidentally committed build artifacts
- Remove test scripts from repository root
- Add build/ to .gitignore

* fix: address additional Bugbot comments

- Re-enable mouse mode in ttyd terminal (was temporarily disabled)
- Fix hardcoded macOS paths in direct-terminal-ws
- Use 'tmux' from PATH instead of hardcoded /opt/homebrew/bin/tmux
- Use os.userInfo() for username fallback instead of 'equinox'
- Use process.env.PATH for cross-platform compatibility

Note: Bugbot comment about XDA response is incorrect - terminal.write()
is the correct API for responding to XDA queries. The implementation works
as confirmed by user testing.

* perf: fix slow terminal scrolling

- Remove status and error from useEffect dependencies (was recreating terminal on every state change)
- Add scroll performance settings: scrollSensitivity, fastScrollModifier
- Terminal now only recreates when sessionId changes

* fix: pass startFullscreen prop to DirectTerminal in SessionDetail

The fullscreen query parameter was being read from URL but not passed
through to the DirectTerminal component. This caused the fullscreen=true
query param to be ignored when viewing session detail pages.

Fixes:
- Pass startFullscreen prop from SessionDetail to DirectTerminal
- Enables ?fullscreen=true to work on session detail pages

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: enable mouse mode for DirectTerminal scrolling

DirectTerminal was not scrollable because tmux mouse mode was not enabled
for the sessions. The ttyd implementation already had this, but the
DirectTerminal WebSocket server was missing it.

Changes:
- Add spawn import from node:child_process
- Enable tmux mouse mode on session connection
- Hide tmux status bar for cleaner appearance

This makes DirectTerminal scrolling work the same as ttyd terminals.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: reduce scroll speed in DirectTerminal for smoother experience

Reduced scroll sensitivity from 3 to 1 lines per wheel tick for more
natural scrolling behavior. Also reduced fast scroll (with Alt) from 5 to 3.

Changes:
- scrollSensitivity: 3 → 1 (normal scroll speed)
- fastScrollSensitivity: 5 → 3 (Alt+scroll speed)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* feat: auto-select two different sessions for terminal test page

When no query params are provided, the test page now automatically fetches
available sessions and picks two different ones for side-by-side comparison.
This avoids port conflicts between ttyd and DirectTerminal by default.

Changes:
- Fetch sessions from /api/sessions on mount
- Use first two available sessions as defaults (or fall back to hardcoded)
- Query params still work for manual override
- Warning only shows when sessions are actually the same

Examples:
- /dev/terminal-test (auto-picks two sessions)
- /dev/terminal-test?old_session=X&new_session=Y (manual override)
- /dev/terminal-test?session=X (uses same session for both)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: filter out terminated sessions in terminal test auto-selection

The auto-selection was picking terminated/exited sessions, causing
WebSocket connection failures when trying to attach to non-existent
tmux sessions (PTY exit code 1).

Now filters to only use sessions with activity !== "exited" for
auto-selection, ensuring terminals can actually connect.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* feat: add server-side active session filtering to API

Instead of filtering terminated sessions on the client, added proper
API support with ?active=true query parameter to filter server-side.

Changes:
- GET /api/sessions?active=true - Returns only non-exited sessions
- Updated terminal test page to use new API parameter
- Properly maintains session/dashboard alignment during filtering
- Removed client-side filtering logic

This is cleaner, more efficient, and follows proper API design patterns.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* refactor: replace magic strings with ACTIVITY_STATE constants

Added ACTIVITY_STATE constants to @composio/ao-core types and replaced
all hardcoded "exited", "waiting_input", "blocked" strings with proper
constants throughout the codebase.

Changes:
- Added ACTIVITY_STATE constant object to core/types.ts
- Replaced magic strings in API route (/api/sessions)
- Replaced magic strings in lib/types.ts (getAttentionLevel)
- Properly typed constants with satisfies Record<string, ActivityState>

This prevents typos, improves IDE autocomplete, and makes refactoring
easier by having a single source of truth for activity state values.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: move WebSocket servers outside src/ to fix webpack build error

Moved terminal-websocket.ts and direct-terminal-ws.ts from src/server/
to server/ (outside src/) to prevent Next.js webpack from trying to
bundle them with client code.

These are standalone Node.js WebSocket servers (not Next.js API routes)
that should not be part of the Next.js build. Webpack was failing when
encountering node:child_process imports.

Changes:
- Moved src/server/*.ts to server/*.ts
- Updated package.json scripts to point to new location

Fixes: Module build failed: UnhandledSchemeError with node:child_process

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: update server file path in terminal test page docs

Updated documentation to reflect new server file location after moving
files from src/server/ to server/.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: import from @composio/ao-core/types to avoid bundling server code

The main @composio/ao-core export includes tmux utilities that use
node:child_process, which webpack cannot bundle for the client.

The package already exports a /types entry point that only includes
types and constants (no server utilities).

Changes:
- Import from @composio/ao-core/types instead of @composio/ao-core
- This prevents webpack from trying to bundle tmux.js in client code

Fixes webpack error: UnhandledSchemeError with node:child_process

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: combine duplicate imports to resolve lint errors

* fix: update .env.local.example to match code defaults (port 3003)

Addresses bugbot comment: Documentation showed port 3002 but both
server (direct-terminal-ws.ts) and client (DirectTerminal.tsx) default
to 3003. This mismatch could cause connection failures if developers
set only DIRECT_TERMINAL_PORT without NEXT_PUBLIC_DIRECT_TERMINAL_PORT.

Updated documentation to reflect actual code defaults.

---------

Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-16 04:34:15 +05:30
prateek 21335db8af
feat: publish to npm under @composio scope (#32)
* feat: add npm publishing support with @composio scope

Set up Changesets for version management, add publish metadata to all 20
packages under the @composio scope, create an unscoped wrapper package
(@composio/agent-orchestrator) for global install, and add a GitHub
Actions release workflow.

- Rename all packages from @agent-orchestrator/* to @composio/ao-*
- Add @composio/agent-orchestrator wrapper (bin shim → @composio/ao-cli)
- Add license, repository, homepage, bugs, files, engines to all packages
- Add .npmrc (access=public), MIT LICENSE file
- Add .changeset/ config with linked versioning for all packages
- Add .github/workflows/release.yml (changesets publish CI)
- Add changeset, version-packages, release scripts to root

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: exclude private web package from release build

The release script now filters out @composio/ao-web, matching the
workflow's existing exclusion and preventing a Next.js build failure
from blocking npm publishing.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-15 04:28:57 +05:30
prateek 620bad9053
Wire xterm.js terminal embed into web dashboard (#29)
* feat: wire xterm.js terminal embed into web dashboard

- Add xterm.js dependencies (@xterm/xterm, @xterm/addon-fit)
- Create SSE streaming endpoint at /api/sessions/:id/terminal
  - Polls tmux capture-pane every 2 seconds
  - Streams ANSI-aware output with colors/formatting
  - Handles session exit gracefully
- Implement Terminal component with xterm.js
  - Live output streaming from tmux pane
  - Fullscreen mode toggle
  - Optional input mode to send messages to agent
  - Read-only by default
- Import xterm.js CSS in globals.css

The terminal shows live agent activity in the browser with full
ANSI color support. Users can optionally enable input mode to
send messages to the running agent.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: improve terminal rendering and remove clunky input interface

- Fix rendering issues:
  - Use term.reset() instead of clear() for proper clearing
  - Only update when content changes (prevents flickering)
  - Add scrollToBottom() to show latest output
  - Increase scrollback buffer to 10000 lines
  - Add convertEol for proper line endings
  - Increase default height to 600px
  - Add padding around terminal content

- Simplify interface:
  - Remove separate input box (was clunky)
  - Make it clearly "Read-only" by default
  - Clean up header UI
  - Better fullscreen sizing calculation

Next step: Consider WebSocket-based bidirectional terminal for
true interactive sessions (like tmux attach).

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* feat: implement proper interactive terminal with WebSocket

Replace hacky SSE polling with real-time WebSocket for bidirectional
terminal communication. This is a proper interactive terminal - type
directly, like tmux attach in the browser.

Architecture:
- WebSocket server on port 3001 alongside Next.js
- Uses tmux pipe-pane for real-time output streaming
- Sends input character-by-character via tmux send-keys
- Handles terminal resize events
- Connection status indicator

Implementation:
- packages/web/src/server/terminal-websocket.ts: WebSocket server
- Terminal component now fully interactive (not read-only)
- Runs both servers via concurrently in dev mode
- Green dot = connected, red dot = disconnected
- Proper cursor, no more clunky input box

Benefits:
- Real-time streaming (not 2-second polling)
- Type directly into terminal
- Proper terminal control sequences
- Handles resize
- Like native tmux attach

Dependencies added:
- ws (WebSocket server)
- @types/ws
- concurrently (run multiple servers)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: improve terminal rendering - hide extra cursor, faster polling

- Hide xterm cursor (tmux output has its own)
- Increase polling from 500ms to 100ms (5x faster, less lag)
- Add -J flag to join wrapped lines (reduce truncation)
- Increase scrollback to 200 lines

Note: Current polling approach has limitations:
- Still some lag when typing (replacing full content)
- Not true real-time streaming
- For interactive use, prefer 'tmux attach' directly

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: improve terminal auto-sizing - multiple fit attempts

- Fit terminal multiple times (0ms, 100ms, 250ms, 500ms) to catch layout changes
- Add w-full class to ensure terminal takes full width
- Better error handling for fit operations
- Should eliminate need to manually zoom out

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: use const for pollInterval, expand WORKING zone by default

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: import WebSocket as value, not type-only

WebSocket.OPEN is used as a runtime value, so it cannot be a type-only import.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* feat: implement proper tmux control mode streaming

Replace hacky polling approach with professional tmux control mode:

- Use 'tmux -C attach-session' for true incremental streaming
- Parse control mode protocol (%output, %exit, %layout-change)
- Send commands via stdin (not spawning processes)
- Unescape octal sequences from tmux output
- Event-driven (not polling) - lower latency, less CPU
- Only sends new output (not full snapshots)

Benefits:
- 10x less bandwidth (no repeated snapshots)
- Lower latency (~10ms vs 100ms)
- No missed output (event-driven)
- Proper professional solution (how iTerm2 does it)

Based on research of VS Code, tmux control mode documentation,
and industry best practices for terminal streaming.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* refactor: replace custom WebSocket terminal with ttyd

- Replace broken custom tmux control mode + xterm.js with ttyd (iframe)
- ttyd handles all terminal rendering, ANSI, resize, input correctly
- Terminal server now manages ttyd instances per session on dynamic ports
- Enable mouse mode on tmux sessions for proper scroll behavior
- Remove dead code: @xterm/xterm, @xterm/addon-fit, ws deps
- Remove dead SSE terminal API route
- Remove xterm.css import
- Clean up Terminal component: single status dot, no decorative dots
- Make Linear issue link clickable in SessionDetail
- Extract issue label from URL for display (INT-1327 from full URL)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* feat: add tracker plugin integration for issue label extraction

Replaces hardcoded URL parsing with proper tracker plugin abstraction.
Now the dashboard uses tracker.issueLabel() to extract human-readable
labels from issue URLs (e.g., "INT-1327", "#42") in a plugin-agnostic way.

Changes:
- Core: Add optional issueLabel() method to Tracker interface
- Plugins: Implement issueLabel() in tracker-github and tracker-linear
- Web: Add issueUrl and issueLabel fields to DashboardSession
- Web: Add enrichSessionIssue() to populate labels via tracker plugin
- Web: Update SessionDetail and SessionCard to use new fields
- Web: Add getTracker() helper to services.ts

This is fully generic - any tracker plugin can implement issueLabel()
and the dashboard will automatically use it.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: add delay before Enter in tmux sendMessage to ensure text delivery

The dashboard "ask to resolve" button was putting messages in the input
buffer without submitting them. The tmux send-keys Enter was arriving
before the pasted text was fully processed. Match the bash send-to-session
script behavior with a 300ms delay.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: use node:timers/promises for async setTimeout

node:util does not export setTimeout — the async sleep function
lives in node:timers/promises.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: hide tmux status bar in terminal for cleaner appearance

Added 'status off' option to remove the green tmux bar at the bottom
of the terminal for a cleaner, less cluttered interface.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: add health check to wait for ttyd before returning URL

Fixes race condition where iframe loads before ttyd is ready,
causing 'localhost refused to connect' on direct page loads.
Now waits up to 3s for ttyd to be listening before responding.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* feat: enable hot reloading for terminal server with tsx watch

Both frontend (Next.js) and backend (terminal server) now have
hot reloading enabled for faster development iteration.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: add PR enrichment to session detail page

The session detail page was not enriching PR data with live stats
from GitHub, causing it to show +0 -0. Now calls enrichSessionPR()
to fetch additions, deletions, CI status, and review data.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: clean up and collapse unresolved PR comments

- Extract title and description from Bugbot comments
- Strip out HTML comments, metadata, and image links
- Make comments collapsible (collapsed by default)
- Show clean summary with expand for details

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* feat: convert session detail page to client-side with live updates

- Changed from SSR to client-side component
- Added polling every 5 seconds for real-time data
- Created /api/sessions/[id] endpoint for single session fetch
- Faster navigation with client-side routing
- No page refresh needed to see updates

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: remove machine-specific symlinks from repository

- Remove .claude and packages/web/agent-orchestrator.yaml symlinks
- Add them to .gitignore to prevent re-committing
- These are development convenience links created per-worktree

Fixes Bugbot comment about environment-dependent paths that break
on other machines.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* feat: improve session detail UI and fix activity detection

- Fix session activity detection and timestamps
  - session-manager now checks if runtime is alive in get()
  - Use file birthtime/mtime for createdAt/lastActivityAt
  - Fixes "Idle" status and "Created just now" issues

- Improve session detail UI
  - Hide empty projectId chip
  - Add PR# chip to header
  - Fix "0 checks failing" logic
  - Remove duplicate status display
  - Humanize attention level labels ("review" → "Pending Review")

- Add Linear tracker support
  - Register Linear tracker plugin in web services
  - Issue labels now show "INT-1354" instead of full URL

- Add "Ask Agent to Fix" feature
  - Button for each unresolved comment
  - API endpoint to send messages to agent via tmux
  - /api/sessions/[id]/message endpoint

- Fix waitForTtyd timeout handling
  - Add timeout event handler to prevent hanging requests
  - Properly abort timed-out requests

- Fix lint errors
  - Remove duplicate imports
  - Fix unused variables
  - Use type-only imports where appropriate

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: address production issues in terminal implementation

- Use dynamic hostname instead of hardcoded localhost
  - Terminal.tsx uses window.location.hostname
  - terminal-websocket.ts derives URL from request host
  - Supports remote access and reverse proxy scenarios
  - Fixes high-severity Bugbot comments

- Add SIGTERM handling for graceful shutdown
  - Previously only handled SIGINT
  - Now cleans up ttyd processes on SIGTERM too
  - Prevents orphan processes after restarts
  - Adds 5s timeout to prevent hanging

Fixes Bugbot comments:
- r2807572056: Terminal embed hardcodes localhost endpoints
- r2807630014: Terminal URLs are hardcoded to localhost
- r2807604002: ttyd children survive non-interrupt shutdowns

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: properly validate message delivery to tmux sessions

Use execFile with promisify instead of spawn to:
- Wait for tmux commands to complete
- Check exit codes for failures
- Return proper error if send-keys fails
- Add 5s timeout to prevent hanging

Previously the endpoint returned success immediately without
verifying if the message was actually delivered to the session.

Fixes Bugbot comment r2807674035

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: use runtime plugin sendMessage for proper message delivery

Address Bugbot review comments:
- Use session.runtimeHandle instead of raw session id
- Use Runtime plugin's sendMessage method for proper sanitization
- Remove direct tmux command execution

The Runtime plugin's sendMessage handles:
- Proper runtime handle resolution
- Input sanitization and control character stripping
- Safe message delivery via load-buffer for long messages

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: sanitize message input and support runtime defaults

Address Bugbot review comments:
- Add stripControlChars sanitization to prevent control character injection
- Fall back to config.defaults.runtime when project.runtime is not set
- Validate that message is not empty after sanitization

This aligns the message endpoint with the existing send endpoint's
security model and ensures proper runtime resolution.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: address all Bugbot review comments

Comprehensive fixes for all remaining issues:

**message/route.ts:**
- Add session ID validation with validateIdentifier
- Add JSON parse error handling with try/catch
- Add message length validation with MAX_MESSAGE_LENGTH
- Add type guard for non-string messages
- Add URL encoding for session IDs

**terminal-websocket.ts:**
- Fix memory leak in waitForTtyd by tracking and canceling timeouts
- Add cleanup() function to cancel pending requests and timers
- Add MAX_PORT limit to prevent port exhaustion
- Add error handlers for spawned tmux processes
- Use once() instead of on() for exit/error to prevent race condition
- Add unref() to shutdown timeout to allow graceful exit

**page.tsx:**
- Use useCallback to memoize fetchSession
- Add fetchSession to useEffect dependency arrays
- Add URL encoding for session ID in fetch

**Terminal.tsx:**
- Add URL encoding for session ID in terminal fetch URL

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: remove unused err variable in JSON parse catch block

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: add security improvements for terminal and message endpoints

Address remaining Bugbot security concerns:

**terminal-websocket.ts:**
- Add TODO comments about authentication requirements
- Restrict CORS to localhost origins only (was allowing any origin)
- Add session existence validation before spawning ttyd
- Import fs and path modules for session validation

**Authentication:**
Full authentication with session ownership validation is tracked
separately and requires architectural decisions about auth middleware.
These changes provide defense-in-depth for the current implementation.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: remove unused readFileSync import

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* feat: terminal button opens ttyd directly in new tab

Instead of navigating to the session detail page, the terminal button
now fetches the ttyd URL from the terminal server and opens it directly
in a new browser tab. Falls back to the session detail page if the
terminal server is unavailable.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: address final 4 Bugbot review comments

**Issue 1: Terminal lookup ignores configured data directory (HIGH)**
- Load config using loadConfig() from @agent-orchestrator/core
- Use config.dataDir instead of hardcoded path for session validation
- Ensures terminal works with custom dataDir configurations

**Issue 2: Terminal ports exhaust without reuse (MEDIUM)**
- Implement port recycling with availablePorts Set
- Recycle ports when ttyd instances exit or error
- Prevents port exhaustion after 100 allocations

**Issue 3: Remote dashboard blocked by terminal CORS (MEDIUM)**
- Replace hardcoded localhost whitelist with dynamic origin validation
- Allow CORS if origin hostname matches request host
- Supports remote deployments while maintaining security

**Issue 4: Message endpoint can pick wrong runtime plugin (MEDIUM)**
- Use session.runtimeHandle.runtimeName instead of project config
- Ensures message delivery uses the runtime that created the session
- Handles sessions created with different runtime than current config

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-15 01:37:07 +05:30
prateek 24f14015e5
fix: wire dashboard to real session data with PR enrichment (#28)
* fix: wire dashboard to real session data with PR enrichment

- Parse owner/repo from GitHub PR URLs in session-manager for gh CLI calls
- Add static plugin imports in web services.ts (webpack can't resolve dynamic imports)
- Add PR enrichment to page.tsx server component with project matching fallback
- Add project matching fallback in API route for sessions without projectId
- Map bash "starting" status to "working" for backwards compatibility
- Add fallback runtime handle for bash-created sessions without runtimeHandle
- Add getPRSummary to SCM interface for fetching additions/deletions/title
- Implement getPRSummary in scm-github plugin
- Use getPRSummary in enrichSessionPR to populate PR diff stats
- Add plugin-tracker-github dependency to web package

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: update send test for fallback runtime handle behavior

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: register workspace-worktree plugin in web services

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-14 18:21:07 +05:30
prateek b7431424ff
feat: wire web dashboard API routes to real core services (#26)
* feat: wire web dashboard API routes to real core services

Replace all mock data in web API routes with real SessionManager, SCM,
and plugin calls. Add services singleton for lazy initialization and
a serialization layer for core Session → DashboardSession conversion.

Closes INT-1346

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: clear cached init on failure + clean up SSE intervals on stream close

- services.ts: Clear _aoServicesInit on rejection so subsequent calls
  retry instead of permanently returning a failed promise
- events/route.ts: Clear both intervals in the updates catch block
  (matching heartbeat behavior) to stop polling after disconnect

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 17:37:08 +05:30
prateek e450fed462
fix: upgrade @testing-library/jest-dom for vitest 2.x type compatibility (#21)
The v6.6.0 module augmentation for vitest's Assertion interface was
broken with vitest 2.x. Upgrading to v6.9.1 fixes the ~47 typecheck
errors (toBeInTheDocument, toHaveAttribute). Also adds vitest.d.ts to
ensure the type augmentation is included in tsc compilation.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 14:40:44 +05:30
prateek 343c8a65b5
feat: implement web dashboard with attention-zone UI and API routes (#1)
* feat: implement web dashboard with attention-zone UI, API routes, and SSE

Implements the Next.js 15 web dashboard for INT-1332 with:
- Attention-prioritized session cards (urgent/action/warning/ok/done zones)
- 6 API routes: sessions, spawn, send, kill, merge, SSE events
- 5 components: SessionCard, AttentionZone, PRStatus, CIBadge, Terminal
- Session detail page with PR merge readiness, CI checks, unresolved comments
- Tailwind CSS 4 dark theme matching the reference bash dashboard
- Mock data layer covering all attention states for development
- SSE endpoint for real-time lifecycle event streaming

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* test: add vitest test suite for web dashboard (77 tests)

Add comprehensive tests covering API routes, component rendering, and
attention-level classification. Fix merge button visibility when no alerts present.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: address all PR review feedback

- Fix SSE memory leak: add cancel() handler to clear intervals on disconnect
- Add X-Accel-Buffering header for reverse proxy compatibility
- Add input validation on all API routes (validateString, validateIdentifier)
- Import core types (SessionStatus, ActivityState, CIStatus, etc.) from
  @agent-orchestrator/core instead of redeclaring them
- Fix hydration mismatch: render timestamp client-side only via useEffect
- Add error handling on fetch calls in Dashboard (check response.ok)
- Add cn() utility for conditional class composition
- Fix setTimeout leak: use useRef + useEffect cleanup in SessionCard
- Fix getAttentionLevel edge case: status-based checks outside PR block
- Add NaN check on parseInt in merge route
- Extract duplicated sizeLabel logic into shared getSizeLabel()
- Add TODO guard comment on mock-data.ts for production removal

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: address Codex review feedback (iteration 1)

- Use strict /^\d+$/ validation on PR merge route (reject "432foo")
- Treat exited agents with non-terminal status as urgent (crashed agents)
- Add explicit getAttentionLevel mappings for review_pending, approved, cleanup
- Guard SSE update loop against empty sessions array
- Use encodeURIComponent on session details link
- Tighten mergeScore types to Pick<DashboardPR, ...>
- Add stripControlChars() and apply to send route for shell safety

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* style: apply ESLint and Prettier formatting after rebase on main

- Add next-env.d.ts to ESLint ignores (triple-slash reference)
- Merge duplicate imports using inline type syntax (no-duplicate-imports)
- Replace non-null assertions with proper null checks
- Apply Prettier formatting across all packages

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: address Cursor Bugbot review findings

- Add reviewDecision "none" to warning zone in getAttentionLevel
- Change ACTION zone color from green to orange for proper priority signaling
- Fix SessionDetail date hydration mismatch with ClientDateCard pattern
- Add export const dynamic = "force-dynamic" to SSE route
- Add --color-accent-orange CSS variable

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: address Codex review iteration 2 findings

- Gate merge route on PR state (409 if not open) and draft status (422)
- Handle pr.state === "closed" in getAttentionLevel → done zone
- Reject messages that become empty after control char stripping
- Align SSEEvent types with actual emitted events (snapshot + activity)
- Add 6 new tests for edge cases (85 total)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: resolve typecheck error in test helper (NextRequest init type)

Cast RequestInit to NextRequest's ConstructorParameters to fix
type incompatibility between global RequestInit.signal (null allowed)
and Next.js RequestInit.signal (null not allowed).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: resolve remaining review threads (zone colors, draft PRs, ternary)

- WORKING zone uses green (not blue) per design spec
- ACTION zone uses orange, consistent across all components
- Draft PRs with reviewDecision "none" fall to ok (not warning)
- Remove redundant ternary in getAttentionLevel

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add Playwright screenshot tooling for visual verification

Agents and developers can now capture headless Chromium screenshots of
the running dashboard. Includes dev server auto-start, default page
specs, and CLI arg parsing. Screenshots committed to branch for PR
visibility.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* chore: add session detail screenshot after compact metadata redesign

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* chore: add screenshots for session detail redesign + zone reclassification

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: address bugbot findings — unused type, kill route validation, draft PR awareness

- Remove unused SSEEvent type alias from types.ts
- Add validateIdentifier() to kill route for session ID validation
- Skip "needs review" alert for draft PRs in SessionCard getAlerts()
- Show "draft" instead of "needs review" in PRTableRow for draft PRs

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: session detail redesign + attention zone reclassification

Session Detail:
- Nav bar replacing standalone back link
- Meta chips (project/branch/issue) with GitHub links
- Humanized status labels and relative timestamps
- Unified PR card with stats row, issues list, inline CI checks
- Clickable file paths in unresolved comments

Attention Zones (reordered by human action urgency):
- merge: PRs ready to merge (highest ROI per second)
- respond: agents waiting for input (quick unblock)
- review: CI failures, changes requested, conflicts
- pending: waiting on reviewer or CI
- working: agents doing their thing
- done: merged or terminated

Also fixes:
- Add validateIdentifier() to send route for session ID
- Update all tests for new zone names

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: resolve 3 remaining review threads

- Remove duplicate eslint ignore entry for next-env.d.ts
- Export checkStatusIcon and ciCheckSortOrder from CIBadge, import in
  SessionDetail instead of duplicating
- Add restore API route (was untracked)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: restore route validation, merged session guards

- Add validateIdentifier() to restore route (matches kill/send routes)
- Block restoring merged sessions with 409 response
- Hide kill button for merged sessions in top-row and expanded panel
- Expanded panel now shows restore OR terminate (not ternary fallback)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: exclude e2e from tsconfig include (fixes next build)

The e2e directory imports playwright which isn't resolvable during
next build. Since e2e files are standalone tooling (not app code),
exclude them from the main tsconfig include.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: unify CI check rendering via CICheckList layout prop

Add layout prop ("vertical"|"inline"|"expanded") to CICheckList,
remove duplicated InlineCIChecks from SessionDetail in favor of
reusing CICheckList with the appropriate layout mode.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: add isDraft guard to unresolvedThreads pending check

Draft PRs with unresolved threads should fall through to "working",
not "pending". Adds the missing !pr.isDraft guard to match the
reviewDecision check on the next line.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: address 9 bugbot findings across e2e, SSE, and mock-data

- server.ts: kill child process on waitForServer failure, drain stdout
  to prevent backpressure
- screenshot.ts: validate Number() args for NaN with clear error messages
- events/route.ts: initialize interval variables as undefined
- mock-data.ts: exclude draft PRs from needsReview stat count

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: prevent simultaneous restore and kill buttons in SessionCard

Add !isRestorable guard to kill button condition so the two buttons
are mutually exclusive. Restorable sessions show restore; non-restorable
exited sessions show kill.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: remove unreachable kill button from SessionCard top row

The kill button in the top row was dead code — isRestorable already
covers all activity === "exited" cases, so the !isRestorable && exited
condition could never be true.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: update tests to match SessionCard after kill button removal

Tests referenced "kill session" text that no longer exists. Exited
sessions show "restore session", not "kill session". Updated 4 tests
to use onRestore/restore session instead of onKill/kill session.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 14:26:59 +05:30
Prateek 5058c409d5 feat: scaffold TypeScript monorepo with all plugin interfaces
Phase 0 complete. Establishes:
- pnpm workspace with 18 packages (core, cli, web, 15 plugins)
- Complete type definitions in packages/core/src/types.ts defining
  all 8 plugin slot interfaces (Runtime, Agent, Workspace, Tracker,
  SCM, Notifier, Terminal) + core service interfaces
- YAML config loader with Zod validation and sensible defaults
- Plugin registry with built-in discovery
- CLAUDE.md with conventions for spawned agents

All agents can now branch from main and implement their assigned
packages against the interfaces defined in types.ts.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 17:02:42 +05:30