Commit Graph

116 Commits

Author SHA1 Message Date
suraj-markup 40906331e7 fix(mobile): increase message bar padding above keyboard
Add extra padding (keyboardHeight + 10) so the input comfortably
clears the keyboard suggestions/accessory bar on all devices.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 03:53:39 +05:30
suraj-markup ba2053dd4c fix(mobile): replace KeyboardAvoidingView with Keyboard API listener
KeyboardAvoidingView was causing two issues: scrolling the page to the
top on focus, and not restoring the layout when dismissing the keyboard.

New approach uses Keyboard.addListener to track keyboard height and
applies it as paddingBottom on the message bar directly. This works
reliably on both iOS and Android regardless of softInputMode.

- Removed softwareKeyboardLayoutMode: "pan" from app.json
- Replaced KAV with plain View + dynamic keyboard padding
- Reverted SpawnSession/Settings screens to simple iOS-only KAV

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 03:48:44 +05:30
suraj-markup a685565bbb fix(mobile): increase keyboard offset for Android accessory bar
Bump Android keyboardVerticalOffset from 80 to 140 to account for the
suggestions/clipboard bar that sits above the keyboard on many devices.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 03:45:30 +05:30
suraj-markup fe90d5b4e7 fix(mobile): fix keyboard hiding text input on Android and iOS
- Set android.softwareKeyboardLayoutMode to "pan" in app.json to prevent
  conflict between system adjustResize and KeyboardAvoidingView
- Use behavior="padding" consistently on both platforms
- Add keyboardVerticalOffset on Android to account for nav header
- Applied fix across all screens with keyboard input

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 03:42:44 +05:30
suraj-markup fa5fcc9e91 fix(mobile): ensure message input stays visible above keyboard
- Set KeyboardAvoidingView behavior to "height" on Android (was undefined)
- Add scrollToEnd on TextInput focus so content scrolls up with keyboard
- Add keyboardShouldPersistTaps="handled" for better tap behavior

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 03:39:05 +05:30
suraj-markup 7ed6e0c2c1 fix(mobile): address second round of review comments
- Add required `type: TIME_INTERVAL` to notification trigger for SDK 53
- Remove phantom statuses from SessionStatus/ActivityState not in core
  (removed "running" from SessionStatus; "starting", "thinking", "working"
  from ActivityState)
- Handle unhandled promise rejections from scheduleNotification in
  useSessionNotifications hook with void + .catch()
- Await scheduleNotification in SettingsScreen test handlers and show
  error alert on failure instead of premature "Sent"

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 03:20:48 +05:30
suraj-markup f3944b5f15 fix(mobile): address PR review comments and lint CI failure
- Exclude packages/mobile/** from root eslint config (mobile uses Expo/CJS toolchain)
- Align TERMINAL_STATUSES and NON_RESTORABLE_STATUSES with packages/core/src/types.ts
- Fix isRestorable() to use isTerminal() check matching core logic
- Change notification trigger from null to { seconds: 1 } for Android background task compat
- Add isPRRateLimited guard to merge button to prevent merge when API rate limited
- Await scheduleNotification in background task to ensure notifications are delivered

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 03:06:33 +05:30
suraj-markup 5a22a85e72 chore(mobile): update app icons and splash screen with Agent Orchestrator branding
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-03 02:38:17 +05:30
suraj-markup 2675c191e2 feat(mobile): add dashboard action parity — merge, CI fix, review comments, spawn
Adds missing action features to match the web dashboard:

- Merge PR button: green button when PR is mergeable, calls /api/prs/:id/merge
- CI checks list: individual checks with status icons and links
- "Ask to fix CI" button: sends "Please fix the failing CI checks" to agent
- Unresolved review comments: per-comment card with author, path, body
- "Ask Agent to Fix" per comment: sends context-specific message with file path
- Alert cards: CI failures, merge conflicts, changes requested warnings
- Spawn Session screen: create new sessions with project ID and optional issue ID
- "+" button on home screen header to spawn sessions
- PR title is now tappable (opens in browser)
- Color-coded CI/review/mergeability status values
- PR blockers list display

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 01:46:35 +05:30
suraj-markup c53099923d feat(mobile): add React Native app for monitoring AO sessions
Adds `packages/mobile` — an Expo SDK 53 React Native app for monitoring
agent sessions from a phone.

Features:
- Home screen: Kanban-style session list sorted by attention level
- Session detail: metadata, PR link, CI status, branch info
- Terminal screen: full xterm.js terminal via WebView (port 14801)
- Settings screen: configurable backend URL (LAN IP or ngrok)
- Push notifications: background polling for attention-level changes

Improvements over PR #235:
- Fixed terminal onmessage handler to filter JSON control messages
  (resize echoes no longer render as garbage text)
- Removed duplicate terminal.html (single source of truth in
  terminal-html.ts)
- Fixed isDone check to include "cleanup" status using isTerminal()

Tech: Expo SDK 53, React Navigation 6, React Native WebView.
Two server connections: REST API (port 3000) + WebSocket terminal (14801).

The mobile package is excluded from the pnpm workspace to avoid
interfering with the monorepo toolchain.

Closes #265

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 01:34:45 +05:30
Karan Vaidya 4cda43795b
fix: handle ad-hoc spawn with free-text issue strings (#155)
* fix: handle "invalid issue format" error for ad-hoc spawn

gh CLI returns "invalid issue format" when the issue argument is free-text
rather than a valid issue number/URL. This error was not matched by
isIssueNotFoundError, causing ad-hoc spawns to fail instead of gracefully
falling through to ad-hoc mode.

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

* fix: sanitize ad-hoc issue text into valid git branch names

When tracker lookup fails (ad-hoc mode), the raw free-text was used
directly as a branch name, causing git to reject it. Now:
- Only use tracker.branchName() when the issue was actually resolved
- Slugify ad-hoc text (lowercase, replace non-alphanumeric with hyphens,
  trim, cap at 60 chars) to produce valid branch names

e.g. "fix the cold start issue" → feat/fix-the-cold-start-issue

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

* fix: preserve casing for branch-safe issue IDs, only slugify free-text

The slug sanitization was lowercasing all issue IDs without a resolved
issue (e.g. INT-9999 → int-9999). Now only applies sanitization when
the issueId contains characters invalid for git branch names.

Adds tests for slug sanitization, casing preservation, truncation,
empty-slug fallback, and isIssueNotFoundError patterns.

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

* test: assert tracker.branchName not called for unresolved issues

Adds assertion to existing test that tracker.branchName is NOT called
when the issue wasn't found. Adds end-to-end test for "invalid issue
format" error flowing through spawn with free-text slugification.

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

* fix: reject '..' in branch-safe check, verify generatePrompt skipped

The isBranchSafe regex allowed '..' which is invalid in git refs.
Also asserts that tracker.generatePrompt is not called when the
issue wasn't resolved, and adds a test for the '..' edge case.

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

* fix: trim dashes after truncation, not before

Bugbot correctly noted that .slice(0, 60) after dash-trim can
reintroduce a trailing dash. Reorder so trim runs after slice.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Prateek <karnalprateek@gmail.com>
2026-02-27 19:10:03 +05:30
prateek e5105133c5
Default dangerouslySkipPermissions to true (#226)
* docs: add demo video and article links to README

Add tweet screenshot for the video demo prominently after the intro,
and link to the full article thread. Replaces the TODO placeholder.

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

* docs: use article screenshot for README article link

Replace text-only article link with clickable screenshot showing
the article title, preview image, and engagement stats.

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

* docs: replace demo video screenshot with higher quality version

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

* Default dangerouslySkipPermissions to true for autonomous agent operation

Spawned agents need to run CLI commands without permission prompts. Changed
the agentConfig.permissions schema default from undefined to "skip" so
--dangerously-skip-permissions is included by default. The orchestrator
session is hardcoded to "skip" regardless of config since it must always
run ao CLI commands autonomously.

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

* Default agentConfig to {} so permissions default propagates

When agentConfig is absent from YAML, .optional() leaves it undefined,
so project.agentConfig?.permissions evaluates to undefined instead of
"skip". Change to .default({}) so Zod always constructs the object and
applies the inner permissions default.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 19:04:50 +05:30
prateek 5540d90290
fix: skip orchestrator sessions during cleanup (#144)
* fix: skip orchestrator sessions during cleanup

The cleanup command could kill the orchestrator's own tmux session
(named {prefix}-orchestrator) because it has no PR or issue, making
it eligible for the "dead runtime" cleanup heuristic.

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

* fix: add role metadata for orchestrator session identification

Store role=orchestrator in metadata during spawnOrchestrator() and
check it in cleanup() for explicit identification. Keeps the name
fallback (endsWith -orchestrator) for pre-existing sessions.

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

* fix: preserve role in restore path, add integration test

- restore() now preserves the role field when recreating metadata
  from archive (previously dropped, breaking role-based detection)
- Add integration test: orchestrator skipped while sibling session
  with same closed issue gets killed (verifies real tracker plugin)
- Verified: both unit and integration tests fail without the guard

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

* fix: persist role field in metadata, isolate role test from name fallback

Bugbot caught two real issues:
- writeMetadata() and readMetadata() never serialized the role field,
  so role=orchestrator was silently dropped on disk
- The role-based test used "app-orchestrator" as session name, so the
  name fallback caught it — role check was never actually exercised

Fix: add role to metadata read/write, rename test session to "app-99"
so only the role metadata path can protect it.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 18:17:03 +05:30
prateek 91dd7cc15f
fix: keep Claude Code interactive after initial prompt (#145)
* fix: keep Claude Code interactive after initial prompt

Claude Code's -p flag runs in one-shot mode (exits after responding),
which prevents follow-up messages via `ao send`. Instead, launch Claude
interactively and deliver the initial prompt post-launch via
runtime.sendMessage().

Adds `promptDelivery` property to the Agent interface so each agent
plugin can declare whether prompts should be inlined in the launch
command or sent after the agent starts.

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

* fix: make post-launch prompt delivery non-fatal and add test coverage

- Move sendMessage call outside the try/catch that destroys the session.
  A prompt delivery failure should not kill a running agent — user can
  retry with `ao send`.
- Add tests: no-prompt + post-launch agent, sendMessage failure resilience,
  5s delay verification, systemPrompt/systemPromptFile alongside omitted -p.

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

* test: add integration test for prompt delivery (proves bug and fix)

Two real-Claude integration tests that contrast:
1. `-p` mode: Claude exits after responding (the bug)
2. Interactive + sendMessage: Claude stays alive, follow-up works (the fix)

Runs in CI with ANTHROPIC_API_KEY. Skips when prerequisites missing.

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

* fix(test): skip interactive test without auth, improve TUI readiness detection

The integration test failed in CI because interactive Claude requires
full login auth (not just ANTHROPIC_API_KEY). Skip the interactive suite
when `claude auth status` reports not logged in.

Also fix local flakiness: replace blind 5s sleep with polling for
Claude's TUI prompt character (❯) before sending the first message,
and increase scrollback capture from 200 to 500 lines.

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

* fix(test): skip interactive test in CI, fix TUI readiness detection

The interactive test ran in CI despite hasInteractiveAuth() — Claude
reports logged in when ANTHROPIC_API_KEY is set, but interactive mode
requires OAuth. Use `!process.env.CI` as the skip condition instead.

Also fix waitForTuiReady false positive: the OAuth screen's
"Paste code here if prompted >" matched the `>` regex. Now checks
the last non-empty line for Claude's specific ❯ prompt character,
and bails early if the OAuth/login screen is detected.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 18:11:06 +05:30
suraj-markup 433189a79b perf(agent-codex): cache findCodexSessionFile to avoid double scan
Add a 30-second TTL cache for session file lookups so that
getActivityState, getSessionInfo, and getRestoreCommand called in the
same refresh cycle reuse the result instead of re-scanning
~/.codex/sessions/ independently.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 16:25:24 +05:30
suraj-markup c307ae30e0 feat(agent-codex): implement mtime-based activity state detection
Use the Codex session file's mtime as a proxy for agent activity.
Codex continuously appends to its rollout JSONL while working, so:
- recently modified file → active
- stale file (past threshold) → idle
- process not running → exited

This replaces the previous null return with real activity detection,
using the same threshold constant (DEFAULT_READY_THRESHOLD_MS = 5min)
as the Claude Code plugin.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 15:58:25 +05:30
suraj-markup b6eb4d8888 fix(agent-codex): catch approval emit throw, remove dead wasClosedBefore guard
- Wrap entire handleApprovalRequest body in try/catch so a throwing
  "approval" listener doesn't cause an unhandled promise rejection
- Remove wasClosedBefore variable that was always false (the closed
  check on entry guarantees it), simplifying the connect catch block

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 13:52:52 +05:30
suraj-markup 9f1614dd0d refactor(agent-codex): extract shared CLI flag helpers
Extract duplicated approval-policy and model/reasoning flag logic from
getLaunchCommand and getRestoreCommand into shared appendApprovalFlags
and appendModelFlags helpers. Single source of truth for flag mapping.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 12:28:50 +05:30
suraj-markup 3f81936467 fix(agent-codex): reject pending requests before emitting error event
Move this.emit("error", err) after the pending-rejection loop in
handleProcessError, matching handleProcessExit's order. Without this,
emit("error") with no listeners throws synchronously, skipping
cleanup of pending requests.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 12:08:00 +05:30
suraj-markup 89d2b5ead3 test(agent-codex): add missing setupMockStream calls to edge-case tests
Three tests relied on the empty default stream coincidentally matching
expected values instead of actually exercising the streaming parser.
Added setupMockStream(content) and stronger assertions to verify the
parser correctly handles missing model, missing token events, and
missing threadId.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 11:51:09 +05:30
suraj-markup da7d3ec80e fix(agent-codex): stream JSONL, shell-escape binary, guard close()
- Replace full-file readFile with streaming createReadStream + readline
  for potentially huge Codex session files (100MB+)
- Shell-escape resolved binary path in launch/restore commands
- Prevent connect() failure from resetting an explicit close() call
- Remove dead helper functions replaced by streamCodexSessionData

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 09:23:15 +05:30
suraj-markup 3f76338bb4 fix(agent-codex): add jsonrpc 2.0 field and fix resume flag ordering
- Add "jsonrpc": "2.0" to all JSON-RPC requests, notifications, and
  approval responses for spec compliance
- Place flags before positional threadId in resume command for CLI
  parser compatibility (codex resume --flags <threadId>)
- Add test assertions for jsonrpc field and flag ordering

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 01:41:47 +05:30
suraj-markup e7033048f2 fix(agent-codex): prevent symlink cycle in recursive session scan
- Use lstat instead of stat in collectJsonlFiles so symlinks to
  directories are never followed (isDirectory returns false for symlinks)
- Add MAX_SESSION_SCAN_DEPTH=4 cap as defense-in-depth
  (Codex uses YYYY/MM/DD structure, max 3 levels)
- Update tests to mock lstat for directory checks separately from stat

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 01:29:41 +05:30
suraj-markup 2dfbf8a778 fix(agent-codex): fix token double-counting and spawn error handling
- Remove additive cached_tokens/reasoning_tokens from cost calculation
  (they are subsets of input_tokens/output_tokens per OpenAI API convention)
- Wrap entire connect() body in try/catch so connecting flag resets if
  spawn() throws synchronously (EMFILE, ENOMEM)
- Add test for spawn-throws-synchronously recovery
- Update cost assertions to reflect correct non-additive token counting

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 01:19:36 +05:30
suraj-markup c0105476da fix(agent-codex): address follow-up review — retry after failed connect, binary guard recovery, lint fixes
- Reset closed flag after failed connect() so client can retry
- Wrap binary resolve guard in try/finally to clear on rejection
- Fix duplicate import and unused variable lint errors in tests
- Add test: client retries connect after transient handshake failure

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 01:00:44 +05:30
suraj-markup 4e7129d50d fix(agent-codex): address review comments — resource cleanup, concurrency, and memory
Fixes 6 issues flagged by Cursor Bugbot on PR #188:

1. sessionFileMatchesCwd reads only first 4 KB via open()+read() instead of
   loading entire rollout file into memory (Medium)
2. Binary resolution race condition: added promise guard to prevent
   concurrent resolveCodexBinary() calls (Low)
3. Concurrent connect() calls: added connecting guard to prevent
   orphaned child processes (High)
4. connect() failure cleanup: wrap initialize() in try/catch that
   calls close() on failure (Medium)
5. readline cleanup on process exit/error: close readline in both
   handleProcessExit and handleProcessError (Medium)
6. stderr pipe drain: call stderr.resume() to prevent child blocking
   when stderr buffer fills (High)

All 177 tests pass, typecheck clean.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 00:38:58 +05:30
suraj-markup 82317cbdeb fix(agent-codex): use correct Codex CLI flags, native resume, and date-sharded sessions
Verified all CLI flags against actual Codex documentation and fixed 6 issues:
- --approval-mode → --ask-for-approval (untrusted/on-request/never)
- --reasoning → -c model_reasoning_effort=high (config override)
- Fake text re-injection → codex resume <threadId> (native subcommand)
- Flat readdir → recursive collectJsonlFiles() for YYYY/MM/DD sharding
- ThreadStartParams values → correct Codex enum values
- Added /opt/homebrew/bin/codex and ~/.cargo/bin/codex fallback paths

Closes #176, #177, #178, #179, #183, #184

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 23:47:28 +05:30
suraj-markup 2e09330980 feat(agent-codex): add token tracking, approval policies, reasoning flag, binary detection, conversation resume, and app-server client
Implements six Codex-specific improvements:
- getSessionInfo() parses JSONL session files for token usage and cost estimation
- Configurable approval/sandbox policies (--approval-mode, --dangerously-bypass-approvals-and-sandbox)
- Auto-detect o-series models for --reasoning flag
- resolveCodexBinary() discovers codex via which + fallback paths
- getRestoreCommand() extracts thread context for conversation resume via re-injection
- CodexAppServerClient JSON-RPC client for Codex app-server mode (thread/turn management, approval handling, model discovery)

Closes #176, #177, #178, #179, #183, #184

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 22:37:13 +05:30
suraj-markup 0a5fea19e3 test(agent-codex): update tests for correct Codex CLI flags
Update test expectations to match the corrected Codex CLI flags:
- --full-auto instead of --dangerously-bypass-approvals-and-sandbox
- -c developer_instructions=... instead of --system-prompt (inline)
- -c model_instructions_file=... instead of --system-prompt $(cat) (file)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 08:56:03 +05:30
suraj-markup 584ca1daa2 fix(agent-codex): use correct Codex CLI flags and remove dead code
- Replace --dangerously-bypass-approvals-and-sandbox with --full-auto
  (keeps workspace sandbox, auto-approves — safer default for automation)
- Replace nonexistent --system-prompt flag with Codex config overrides:
  -c developer_instructions=... for inline prompts
  -c model_instructions_file=... for file-based prompts
- Remove redundant "active" pattern checks that duplicate the default
  return value (addresses BugBot dead-code finding)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 08:25:42 +05:30
suraj-markup 89fc3369d5 fix: add agent field to readMetadata return mapping
readMetadata() was not returning the `agent` field even though
writeMetadata() persisted it. This meant typed consumers got
undefined for session.agent while raw readers worked fine.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 03:54:52 +05:30
suraj-markup 46b0d1a541 fix: persist agent name in metadata so lifecycle resolves correct plugin
When --agent override is used at spawn time, the agent name was not stored
in session metadata. The lifecycle manager and session enrichment always
resolved the agent from project config defaults, causing mismatched process
detection (e.g. looking for "claude" instead of "codex") and incorrect
"killed" status on the first poll cycle.

- Add `agent` field to SessionMetadata type and writeMetadata
- Store `plugins.agent.name` in metadata during spawn
- Pass stored agent name to resolvePlugins in list/get/restore paths
- Read `session.metadata["agent"]` in lifecycle manager's determineStatus
- Add tests for metadata persistence with and without override

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 03:47:43 +05:30
suraj-markup 2bdc6bb59c test: add tests for --agent override and codex plugin registration
- Session manager: agent override uses correct agent, unknown agent throws, default used without override
- CLI spawn: --agent flag passthrough with and without issue ID
- Plugin registry: multiple agent plugins registered via loadBuiltins importFn

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 03:26:54 +05:30
suraj-markup b0965693c2 fix(agent-codex): suppress no-useless-escape lint for bash template literals
The \$ escapes in bash script template literals are intentional to
prevent JS template interpolation. Added eslint-disable/enable block.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 00:32:51 +05:30
suraj-markup 71ee3a2144 feat(cli): add --agent flag to override agent plugin at spawn time
Allows starting sessions with a different agent without changing config:
  ao spawn ao --agent codex
  ao spawn ao --agent codex INT-1234

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 23:23:54 +05:30
suraj-markup e410079026 feat(agent-codex): mature Codex plugin to match Claude Code support
Brings the Codex agent plugin to feature parity with Claude Code by
fixing four key gaps and hardening the shell wrapper infrastructure.

## Changes

**`packages/plugins/agent-codex/src/index.ts`**

- Permission flag: `--approval-mode full-auto` → `--dangerously-bypass-approvals-and-sandbox`
- Terminal-based activity detection with Codex-specific patterns:
  idle (bare prompts), waiting_input (approval prompts), active (spinners, esc to interrupt)
- PATH-based shell wrappers (`~/.ao/bin/gh`, `git`, `ao-metadata-helper.sh`):
  - `gh` wrapper captures `pr/create` and `pr/merge` output to update PR metadata;
    all other commands use `exec` for transparent passthrough (no stderr merging)
  - `git` wrapper captures `checkout -b` / `switch -c` to update branch metadata
  - Metadata helper escapes sed metacharacters (`&`, `|`, `\`) in values
  - Uses `grep -Fxv` (fixed-string) instead of regex for PATH cleaning
  - Validates `AO_DATA_DIR`/`AO_SESSION` paths to prevent arbitrary file overwrites
    (rejects traversal, resolves symlinks, allowlists `~/.ao/` and `/tmp/`)
- `getEnvironment()` prepends `~/.ao/bin` to PATH for wrapper interception
- `setupWorkspaceHooks()` / `postLaunchSetup()` install wrappers atomically
  (temp file + rename) and append AGENTS.md section
- `getActivityState()` returns `{ state: "exited" }` when dead, `null` when running

**`packages/core/src/lifecycle-manager.ts`**

- Branch-based PR fallback: when `metadata.pr` is missing, calls
  `scm.detectPR()` via `gh pr list --head <branch>` to auto-discover PRs
  for agents without hook systems (Codex, Aider, OpenCode)

## Test coverage

- 85 tests in `agent-codex` (up from 27), replicating Claude Code test patterns:
  detectActivity edge cases, isProcessRunning boundaries, setupWorkspaceHooks
  file I/O behavior, shell wrapper content verification, atomic write validation
- 245 tests in core pass
- All 22 packages typecheck clean

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 20:53:33 +05:30
prateek 3c160881e5
chore: remove static CLAUDE.orchestrator.md (#143)
The static file is fully superseded by the auto-generated orchestrator
prompt in packages/core/src/orchestrator-prompt.ts, which gets injected
dynamically via `ao start`. Also clean up stale references in comments
and architecture docs.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 14:29:17 +05:30
prateek 40c1906d41
feat(web): redesign dashboard, session detail, and orchestrator terminal (#125)
* docs: add design research artifacts — briefs, token reference, screenshots

Comprehensive design research package for the ao dashboard, session
detail page, and orchestrator terminal. Produced via competitive analysis
of 14 products (Linear, Vercel, Railway, Fly.io, Inngest, WandB, LangSmith,
Supabase, and more) + Playwright CSS extraction from live sites + full
codebase audit.

Artifacts:
- docs/design/design-brief.md            Main design brief (v2, Playwright-updated)
- docs/design/session-detail-design-brief.md   /sessions/[id] design spec
- docs/design/orchestrator-terminal-design-brief.md  Orchestrator page spec
- docs/design/token-reference.css        Drop-in CSS replacement for globals.css
- docs/design/competitive-analysis-raw.md  Raw research notes, all 14 sites
- docs/design/design-brief-v1.md         Original text-only brief (pre-Playwright)
- docs/design/README.md                  Index + research methods summary
- docs/design/screenshots/linear-homepage.png   Playwright-captured screenshot
- docs/design/screenshots/railway-homepage.png  Playwright-captured screenshot

Key findings:
- Linear CSS token values verified via Playwright (body bg #08090A, accent
  #7070FF, Berkeley Mono monospace, type scale, radius, transitions)
- Recommended palette: #0C0C11 base (blue-cast dark vs current GitHub #0d1117)
- Highest-impact change: load Inter Variable via next/font/google
- Orchestrator terminal needs visual differentiation (violet accent, status strip)
- token-reference.css is ready to drop into packages/web/src/app/globals.css

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

* feat(web): redesign dashboard, session detail, and orchestrator terminal

Implements a cohesive dense dark-mode design system across all three main views.

- New color token palette: #0c0c11 base, #141419 surface, #1c1c25 elevated
- Accent blue #5b7ef8, status semantics (ready/error/attention/working/idle/done)
- Violet accent #a371f7 reserved for orchestrator
- Inter Variable + JetBrains Mono loaded via next/font with CSS variables
- activity-pulse keyframe for live agent dots

- AttentionZone header: dot + label + flex divider + count pill + chevron
- Sessions laid out in responsive 1→2→3 column grid
- Solid green merge button (translateY hover), no confirm() dialog

- Breadcrumb nav: ← Agent Orchestrator / {session-id} [orchestrator badge]
- CSS 8×8px activity dot with pulse animation replaces emoji labels
- Merge-ready state: green-bordered banner with checkmark icon
- Orchestrator sessions show zone counts strip (merge/respond/review counts)

- xterm.js dark theme (#0a0a0f bg, #d4d4d8 fg, full 16-color ANSI palette)
- variant prop: "agent" (blue cursor) vs "orchestrator" (violet cursor)
- Dynamic height prop instead of fixed 600px; fullscreen toggle with SVG icons

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

* refactor(web): strip rainbow stats, clean header, IBM Plex Sans typography

- Replace Inter with IBM Plex Sans (technical tool aesthetic, distinctive numerics)
- Replace 4-color big-number stats bar with a single compact inline status line
  in the header: "35 sessions · 1 working · 9 PRs" — no decorative colors
- Remove the two-tone "Agent (blue) Orchestrator (white)" title — just "Orchestrator"
- Remove ClientTimestamp (useless) — replaced by orchestrator nav link
- Zone headers: colored dot only (semantic), neutral uppercase label, plain count
  — removes the rainbow-colored label text that read as a widget template
- Add subtle radial gradient glow at top of page for depth

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

* feat(web): kanban layout, amber accent, full-width, bigger stats

- Switch accent from blue (#5b7ef8) to amber/gold (#d18616) throughout
- Replace grid layout with horizontal Kanban columns for active zones
  (merge, respond, review, pending, working), Done stays full-width below
- Remove max-w-[1100px] constraint — full viewport width
- Header stats numbers 20px bold (was 12px), orchestrator link is now a
  visible bordered button
- AttentionZone gains variant="column" for Kanban mode (compact header
  with count pill, vertical card stack)
- Update all hardcoded rgba(91,126,248,...) in SessionCard to amber

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

* fix(web): layout, alert sizing, column order, button feel

- Kanban column order: working→pending→review→respond→merge
  (left = in progress, right = ready to ship)
- Columns use flex-1 min-w-[200px] to fill available width
  instead of fixed 260px leaving half the page empty
- Alert badges: inline-flex wrapper prevents stretching to full
  row width when wrapping
- Terminal button: add bg-subtle fill so it reads as a button
- PR number (#91): remove opaque pill background, now plain
  amber text link — clearly a hyperlink
- Merge PR button: pt-0.5 spacer above the action area

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

* fix(web): don't cache rate-limited partial PR data

When GitHub rate limits fire, enrichSessionPR was caching the
bad partial data (0 additions, CI failing) for 60 seconds, causing
the dashboard to show incorrect data for the full TTL window.

- Skip cache write when majority of API calls failed
- Downgrade console.error → console.warn (this is handled/expected)

The next page refresh will retry live API calls, so data recovers
as soon as the rate limit window resets.

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

* feat(web): graceful GitHub API rate limit handling in UI

When the GitHub plugin hits rate limits, the dashboard now:

- Shows a single amber banner: "GitHub API rate limited — PR data
  (CI status, review state, sizes) may be stale. Will retry on
  next refresh."
- Hides CI badge, review decision, and size pill on PR cards
  (they'd show wrong values: +0 -0 XS, CI failing)
- Shows a subtle "⚠ PR data rate limited" note on affected cards
  instead of misleading alert badges
- Skips CI/review/conflict-based attention zone classification
  for rate-limited PRs (prevents sessions moving to Review due
  to phantom "CI failing" from the fallback value)
- Doesn't cache partial rate-limited data so next refresh retries
  live API calls as soon as the rate limit window resets

What still works when rate limited:
- Session ID, title, branch, PR number/link
- Session activity status (working/spawning/etc.)
- Merge button if mergeability was already cached
- Restore/terminate/send actions

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

* feat(web): dashboard redesign — glassmorphism, Kanban, rate-limit handling, perf fix

Design:
- Kanban layout: active zones as flex columns (working→pending→review→respond→merge),
  Done as full-width grid below
- GitHub dark color palette (main's tokens) with glassmorphic card surfaces
  (rgba bg + backdrop-blur) and subtle blue/violet body gradient
- Activity state shown as labeled pill (● active / ● idle etc.) instead of bare dot
- Session card: title on its own row, larger font, inline-flex alert badges (no stretch)
- PR number rendered as plain accent link, not a blue pill badge
- Terminal button has background fill to feel like a button
- Info circle icon replaces alarming warning triangle for rate-limit indicators
- "1 working" → "1 active" in header stats
- PR table constrained to max-w-[900px] and centered
- Orchestrator session no longer uses purple accent

Rate limiting:
- isPRRateLimited() helper; getAttentionLevel() skips PR classification when limited
- Rate-limited banner in Dashboard; suppressed CI/size/review badges in PRStatus
- SessionCard shows subtle "PR data rate limited" indicator; getAlerts() returns []
- serialize.ts: rate-limited enrichment results cached for 5 min (not 60s) to stop
  retrying 168 failing API calls every minute

Performance:
- page.tsx: 4s hard timeout on PR enrichment — serves stale data fast instead of
  blocking SSR for 75s under rate limiting
- cache.ts: TTLCache.set() accepts optional ttl override for per-entry control

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

* fix: suppress stale size/CI/review in PR table when rate limited

PRTableRow now shows "—" for size, CI, and review columns when GitHub
API is rate limited, matching the card view which already hides these.
Prevents misleading "+0 -0 XS" size and "needs review" labels from the
default fallback values.

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

* feat: 3D card effect with depth shadow and top-edge shine

Cards now clearly pop against the dark background:
- Solid gradient bg (rgba(28,36,47) → rgba(18,23,31)) instead of
  near-invisible rgba(22,27,34,0.8) surface
- Layered box-shadow: contact shadow + diffuse depth + inset top highlight
  that simulates light hitting the card's top edge (the "shine")
- Hover: card lifts 2px with deeper shadow
- Merge-ready: green-tinted bg with green ambient glow + stronger lift on hover

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

* fix: restore text legibility inside session cards

The darker solid card gradient made muted/secondary text nearly
invisible — #484f58 (text-muted) had only ~2:1 contrast on the
new card bg. Override the color tokens locally within .session-card
to GitHub's established dark-mode legibility values:

  --color-text-muted:     #484f58 → #656d76  (3.8:1 on card bg)
  --color-text-secondary: #7d8590 → #8b949e  (6.2:1 on card bg)
  --color-text-tertiary:  #484f58 → #656d76

Scoped to .session-card so the rest of the UI is unchanged.

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

* fix: address bugbot comments — fonts, review zone, ActivityDot, orchestrator btn

- layout.tsx: add IBM Plex Sans weight 700 (was missing, font-bold falling
  back to 600)
- DirectTerminal.tsx: use "IBM Plex Mono" instead of unloaded "JetBrains Mono"
- SessionDetail.tsx: add review zone to OrchestratorStatusStrip (was omitted,
  sessions with CI failures were invisible in the strip)
- ActivityDot.tsx: extract shared component, remove duplicate implementations
  in SessionCard.tsx and SessionDetail.tsx
- Dashboard.tsx: redesign orchestrator button with 3D glass style matching
  card aesthetic (blue-tinted bg, depth shadow, hover lift)

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

* fix(web): lint — eqeqeq, duplicate import, unused var

- ActivityDot.tsx: != → !== (eqeqeq rule)
- PRStatus.tsx: merge duplicate @/lib/types imports into one
- SessionCard.tsx: remove unused activityIcon import

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

* feat(web): elevate session detail + orchestrator page design

- Nav: glass backdrop-blur effect with chevron back link
- Header: detail-card 3D treatment with left-border accent keyed to activity color
- Meta chips: bordered pill style with subtle bg instead of flat text
- Status tag: pill badge for status instead of plain text
- PR card: detail-card 3D treatment, border-color reflects PR state
- PR merged badge: purple pill instead of gray text
- Unresolved count: red pill badge in section header
- Blockers section: renamed "Issues" → "Blockers"
- Terminal section: colored bar indicator instead of plain label
- Orchestrator status strip: total agent count + per-zone colored pills
- globals.css: add .nav-glass and .detail-card classes

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

* fix(web): fetchZoneCounts parses body.sessions, delayed 2s to avoid contention

The /api/sessions endpoint returns `{ sessions: [...] }` not a bare array.
fetchZoneCounts was treating the whole response object as an array, so
zone counts were always zero on the orchestrator detail page.

Also delays the initial fetchZoneCounts call by 2s so it doesn't contend
with the session fetch on page load (both hit /api/sessions which is slow
when GitHub enrichment is running).

Also includes: Playwright kill-Chrome-for-Testing tip in CLAUDE.md,
toned-down detail-card shadow in globals.css.

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

* perf+test(web): cache-first PR enrichment, skip exited sessions, fix component tests

Performance improvements:
- enrichSessionPR() now accepts cacheOnly option and returns boolean
- /api/sessions/[id]: serve from cache immediately, only block on first load
- /api/sessions: skip PR enrichment for EXITED sessions (no longer changing)
- cache: increase default TTL from 60s to 5 minutes

Test fixes (match redesigned SessionCard + AttentionZone):
- "restore session" (header) → "restore"; expanded panel still shows "restore session"
- "merge PR #N" → "Merge PR #N" (capital M)
- "CI status unknown" → "CI unknown"
- "ask to fix CI" / "ask to fix CI" → "ask to fix"
- "terminate session" → "terminate"
- Zone labels: RESPOND/WORKING/DONE → Respond/Working/Done (CSS uppercase is visual only)
- "working" zone no longer collapsed by default; collapse tests now use "done" zone

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

* feat(core): ActivityDetection with timestamp propagation

- Add ActivityDetection interface { state, timestamp? } to types.ts
- Agent getActivityState() returns ActivityDetection | null instead of
  ActivityState | null, allowing timestamp from JSONL mtime to propagate
- session-manager updates session.lastActivityAt when detected.timestamp
  is more recent — fixes "active 22h ago" showing stale timestamps
- Update all agent plugins (claude-code, aider, codex, opencode) to
  return ActivityDetection objects

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

* fix(web): dismissible rate limit banner + 60min rate-limit cache TTL

- Add X dismiss button to GitHub API rate limit banner in Dashboard.tsx
  so it can be closed during demos
- Extend rate-limited PR cache TTL from 5min to 60min — GitHub GraphQL
  rate limits reset hourly, no point retrying every 5 minutes

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

* fix(web): address Cursor Bugbot review comments on PR #125

- Dashboard StatusLine: active sessions count now uses var(--color-status-working)
  (blue) instead of neutral text color, matching the design system semantics
- SessionCard: isReadyToMerge now guards against rate-limited state — a card
  with stale cached mergeability data won't show green merge-ready styling
- DirectTerminal: add `variant` to useEffect dependency array (was missing,
  causing stale cursor/selection colors if variant changed after mount)
- agent-aider: include `timestamp: chatMtime` in all ActivityDetection returns,
  matching the pattern used by agent-claude-code (enables accurate lastActivityAt)

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

* fix(ci): resolve lint, typecheck, and test failures

Lint:
- Remove unused parseJsonlFile function (superseded by parseJsonlFileTail)
- Remove dead lastLogModified stat() call in getSessionInfo (field was
  removed from AgentSessionInfo but the filesystem read was left behind)

Typecheck + Tests (ActivityDetection):
- session-manager.test.ts: update mocks to return { state: "active" } /
  { state: "idle" } instead of bare strings — getActivityState() returns
  ActivityDetection | null, not ActivityState | null
- integration tests (aider, claude-code, codex, opencode): update imports
  from ActivityState → ActivityDetection, variable types, comparisons
  (activityState?.state !== "exited"), and assertions (?.state).toBe()

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

* fix: parseJsonlFileTail uses readFile for small files; enrich exited sessions with PRs

- parseJsonlFileTail now calls stat() then readFile() for files smaller than
  maxBytes, falling back to open()/handle.read() only for large files. This
  fixes the test infrastructure (which mocks readFile but not open) and also
  fixes a scope bug where `offset` was declared inside an inner try block but
  referenced outside both try blocks.
- Math.max(0, NaN) returns NaN not 0, so size must default to 0 when stat
  returns a mock without a size field: `const { size = 0 } = await stat(...)`.
- Update activity-detection.test.ts: getActivityState() now returns
  ActivityDetection objects, so tests use (await ...)?.state comparisons.
- Remove stale lastLogModified test (field was removed from AgentSessionInfo).
- Remove EXITED skip guard from api/sessions/route.ts: exited sessions can
  still have open, merge-ready PRs that need enrichment on the dashboard.

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

* fix: comprehensive code review fixes — tests, timestamps, UI correctness

Address gaps identified in code review of the ActivityDetection PR:

Core / Session Manager:
- Add `timestamp` to all `{ state: "exited" }` returns in all 4 agent plugins
  (claude-code, aider, codex, opencode) using consistent `exitedAt = new Date()` pattern
- Add 2 new session-manager tests: timestamp propagation when detection timestamp
  is newer, and no-downgrade when detection timestamp is older
- Fix `parseJsonlFileTail` lint error: remove useless `= 0` initializer (value was
  always overwritten before use; catch block returns early)

Web package — tests:
- Fix 3 `api-routes.test.ts` failures: `sessionsGET()` needs a Request object since
  the route reads `request.url` for `?active=true` query param
- Fix `serialize.test.ts` rate-limit test: spy on `console.warn` (what the code uses)
  not `console.error`
- Add 5 `ActivityDot` component tests covering all activity states, unknown states,
  null activity, and dotOnly mode

Web package — UI correctness:
- Fix `relativeTime()` in SessionDetail to guard against invalid/empty ISO strings
- Fix timer Map leak: add `timersRef.current.clear()` in cleanup effect after forEach
- Add `encodeURIComponent` to sessionId in message fetch URL

Server — race condition fix:
- Guard `activeSessions.delete` in pty.onExit, ws.on("close"), and ws.on("error")
  against stale handlers deleting a newly-registered session with the same ID.
  Fixes flaky integration test where afterEach's pty.kill() fired asynchronously
  after the next test had already set up a new session with the same session ID.

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

* fix(web): narrow PREnrichmentData types to eliminate unsafe casts in serialize

PREnrichmentData.ciStatus and .reviewDecision were typed as string,
requiring unsafe `as` casts when reading from cache into DashboardPR.
Narrow them to the same literal union types used by DashboardPR, making
the casts unnecessary. Also narrow ciChecks[].status to match CoreCICheck.

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-20 18:43:57 +05:30
prateek 0e2ca70b0b
feat: session title fallback chain for PR-less sessions (#105)
* feat: session title fallback chain — PR title → summary → issue title → branch

Sessions without PRs now always show a meaningful title on the dashboard
instead of just the status text. The fallback chain is:

1. PR title (already worked)
2. Agent summary (now fetched from JSONL via getSessionInfo())
3. Issue title (now fetched via tracker.getIssue())
4. Humanized branch name (e.g., "feat/infer-project-id" → "Infer Project ID")

Key changes:
- Enrich agent summaries by calling getSessionInfo() for sessions
  without summaries (local file I/O, not API calls)
- Enrich issue titles via tracker.getIssue() with 5-min TTL cache
- Add humanizeBranch() utility for last-resort branch name display
- Add issueTitle field to DashboardSession type
- Show issue title in expanded detail panel

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

* fix: extract humanizeBranch to separate module to avoid client-side timer leaks

Moves humanizeBranch() from serialize.ts to format.ts — a pure utility
module with no side effects. This prevents the client bundle from pulling
in TTLCache instantiations (which create setInterval timers) when
SessionCard.tsx imports the function.

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

* fix: remove dead re-export of humanizeBranch from serialize.ts

No consumer imports humanizeBranch from serialize — SessionCard imports
directly from format.ts. The re-export was unused surface area.

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

* fix: add missing first-project fallback in summary enrichment block

Matches the pattern used by all other enrichment blocks in page.tsx
(issue labels, issue titles, PR enrichment) which fall back to the
first configured project when projectId and sessionPrefix both miss.

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

* feat: smarter title heuristic — skip prompt excerpts, prefer issue titles

The agent summary fallback from extractSummary() often returns truncated
spawn prompts ("You are working on GitHub issue #42: Add auth...") which
make poor titles. The new heuristic detects these prompt excerpts and
prefers the issue title when available.

Updated fallback chain:
  PR title → quality summary → issue title → any summary → humanized branch → status

Changes:
- Add looksLikePromptExcerpt() to detect spawn prompt patterns
- Add getSessionTitle() to encapsulate the smart fallback logic
- Expand humanizeBranch() with more prefix patterns (release, hotfix, etc.)
- SessionCard now uses getSessionTitle() instead of inline ?? chain
- Add 25 unit tests covering all functions and edge cases
- Fix missing issueTitle field in serialize.test.ts fixture

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

* refactor: extract shared resolveProject() to eliminate duplication

Moves resolveProject() from route.ts into serialize.ts as a shared
export. Both page.tsx and route.ts now use the same function instead
of duplicating the 3-step project resolution logic (projectId →
sessionPrefix → first project fallback) inline.

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

* feat: replace looksLikePromptExcerpt heuristic with summaryIsFallback metadata

Instead of fragile string matching to detect truncated spawn prompts,
the agent plugin now sets summaryIsFallback: true when the summary is
a first-message fallback rather than a real agent-generated summary.

- Add summaryIsFallback to AgentSessionInfo (core/types.ts)
- extractSummary() returns { summary, isFallback } in claude-code plugin
- Add summaryIsFallback to DashboardSession, propagate in serialize.ts
- Replace looksLikePromptExcerpt() with !session.summaryIsFallback
- Fix .js extension in format.ts import (review feedback)
- Add thorough tests for all layers of propagation

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

* test: add resolveProject and enrichSessionIssueTitle coverage

- resolveProject: 5 tests covering direct match, prefix fallback,
  first-project fallback, empty projects, and priority ordering
- enrichSessionIssueTitle: 7 tests covering enrichment, # prefix
  stripping, Linear-style labels, skip conditions, error handling,
  and cross-call caching

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

* refactor: extract shared enrichSessionsMetadata, fix session detail route

- Extract duplicated enrichment orchestration (issue labels, agent
  summaries, issue titles) from page.tsx and route.ts into a single
  enrichSessionsMetadata() function in serialize.ts
- Fix /api/sessions/[id] route: was missing agent summary and issue
  title enrichment, and had hand-rolled project resolution instead of
  using resolveProject() (also missing the first-project fallback)
- Optimize: resolve projects once per session instead of 3x
- Add 8 tests for enrichSessionsMetadata covering full pipeline, skip
  conditions, missing plugins, no-tracker config, multiple sessions,
  and default agent fallback

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

* fix: remove dead getAgent and getTracker exports from services.ts

These helpers became unused when enrichSessionsMetadata was extracted
to serialize.ts with inline registry.get() calls (to avoid coupling
serialize.ts to services.ts and pulling plugin packages into webpack).

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 19:02:02 +05:30
prateek 450507193e
docs: update port references to reflect configurability (#122)
All docs now mention that the dashboard port (default 3000) is
configurable via `port:` in agent-orchestrator.yaml. Fixes incorrect
port 9847 references in SETUP.md, adds multi-project port guidance,
and documents terminal port auto-detection.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 07:37:00 +05:30
prateek 9822aba4e0
fix: auto-detect free port in `ao init` instead of hardcoding 3000 (#120)
When port 3000 is occupied, `ao init` now scans upward (3001, 3002, ...)
until a free port is found. Applies to both interactive and --auto modes.
Uses the existing isPortAvailable() from web-dir.ts (now exported).

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-19 07:27:39 +05:30
prateek 0e533840ba
fix: tab title followups — empty name guard, dedupe truncation (#121)
- Guard against empty project name in getProjectName() and icon.tsx
  (falls back to config key or "A" initial)
- Extract branch truncation into shared `truncate()` helper in
  session detail page
- Addresses bugbot comments from PR #111

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 07:12:32 +05:30
prateek b605ee8ed4
feat: dynamic tab titles and health-aware favicons (#111)
* feat: dynamic browser tab titles and health-aware favicons

Tabs now show contextual titles so multiple dashboard instances are
distinguishable at a glance. Favicons reflect system health (green/
yellow/red) and display the project initial for visual identification.

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

* fix: address review — dedupe project name, handle merge level, add activity emoji

- Extract getProjectName() to shared lib/project-name.ts (used by
  layout, page, icon) — fixes bugbot duplication comment
- computeHealth now treats "merge" attention level as yellow (needs
  human action) instead of silently mapping to green — fixes bugbot
  merge-ignored comment
- Add activity status emoji to session tab titles (🟢💤🚧💀)
  that updates live as session state changes
- Special-case orchestrator sessions: "ao-orchestrator | Orchestrator Terminal"
- Extract activityIcon map to shared lib/activity-icons.ts

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

* fix: use absolute title to avoid layout template duplication

The layout template `%s | project` was wrapping the page title
`project | Agent Orchestrator`, producing `project | Agent Orchestrator | project`.
Use `title.absolute` to opt out of the template on the root page.

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

* fix: use "ao | <project>" format for dashboard title

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

* fix: dedupe config reads with React.cache() on getProjectName

Wraps getProjectName with React.cache() so layout, page, and icon
share a single loadConfig() call per server render pass instead of
reading the YAML file three times.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 04:21:49 +05:30
prateek 520010d5a2
feat: configurable terminal server ports for multi-dashboard support (#113)
* feat: make terminal server ports configurable to fix multi-dashboard EADDRINUSE

When multiple ao dashboards run simultaneously (e.g., ao on port 3000,
integrator on port 3002), both try to start terminal WebSocket servers
on hardcoded ports 3001/3003, causing EADDRINUSE. Add terminalPort and
directTerminalPort to config schema so each instance can use unique ports.

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

* fix: use optional() instead of default() for terminal port schema

Zod .default() always fills in the value, making config.terminalPort
never undefined and the env var fallback in buildDashboardEnv dead code.
Switch to .optional() so the priority chain works correctly:
config value > TERMINAL_PORT env var > hardcoded default.

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

* fix: move terminal server defaults from 3001/3003 to 14800/14801

The 3000-3009 range is the most contested in dev tooling (Next.js
auto-increments, BrowserSync, Grafana, Rails, Express all default to
3000+). Port 14800-14899 has zero IANA registrations, zero known dev
tool conflicts, and is safely below OS ephemeral ranges.

Updated all hardcoded fallbacks, .env.local.example, docker-compose
port mappings, and documentation.

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

* feat: auto-detect available terminal ports for zero-config multi-dashboard

When no terminal ports are configured (no config, no env vars),
buildDashboardEnv now probes for an available port pair starting at
14800. The second `ao start` automatically gets 14802/14803 (or the
next free pair), eliminating EADDRINUSE without any user configuration.

Port detection scans in steps of 2 to keep the pair consecutive.
Explicit config/env values bypass auto-detection entirely.

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

* fix: update onboarding test to use new default terminal port (14801)

The onboarding integration test had port 3003 hardcoded for the
WebSocket health check. Updated to read from DIRECT_TERMINAL_PORT
env var with 14801 as the default, matching the new port defaults.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 04:00:19 +05:30
prateek 1a3cad900f
fix: restore archived sessions that were killed/cleaned up (#110)
* fix: restore archived sessions that were killed/cleaned up

restore() only searched active metadata files, so sessions that had
been killed (and archived to the archive/ subdirectory) could not be
restored. Now restore() falls back to the archive directory, picks the
latest archived version, and recreates the active metadata file before
proceeding.

- Add readArchivedMetadataRaw() to metadata.ts
- Update restore() to search archive as fallback
- Add 4 unit tests for readArchivedMetadataRaw
- Add 2 integration tests for archive restore in session-manager

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

* fix: prevent archive prefix collision for underscore-containing session IDs

readArchivedMetadataRaw used startsWith(sessionId + "_") which would
cause "app" to false-match archive files belonging to "app_v2". Now
verifies the character after the prefix is a digit (start of ISO
timestamp) to disambiguate.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 02:19:44 +05:30
prateek 1e304110f7
fix: destroy old runtime before restore, cleanup clone on failure (#109)
Two bugbot follow-ups from PR #104:

1. Destroy old runtime handle before creating new one in restore().
   When an agent crashes, the tmux session survives. Creating a new
   tmux session with the same name fails. Now we destroy the old
   handle first (best-effort, non-blocking).

2. Wrap git clone in try-catch in workspace-clone restore(). On clone
   failure (network error, disk full), clean up the partial directory
   so future restore attempts aren't blocked.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 01:35:49 +05:30
prateek 65fa811b3b
feat: implement session restore for crashed/exited agents (#104)
* feat: implement session restore for crashed/exited agents

Add true in-place session restore: same session ID, same worktree, same
metadata — optionally resuming the Claude Code conversation via --resume.

Core changes:
- Add TERMINAL_STATUSES, TERMINAL_ACTIVITIES, NON_RESTORABLE_STATUSES sets
  and isTerminalSession/isRestorable helpers to types.ts
- Add SessionNotRestorableError and WorkspaceMissingError error classes
- Add restore() to SessionManager with 9-step flow: find metadata →
  validate restorability → check/recreate workspace → get restore or
  launch command → create runtime → update metadata
- Add restoredAt field to Session and SessionMetadata

Plugin extensions:
- workspace-worktree: exists() + restore() (git worktree prune + re-add)
- workspace-clone: exists() + restore() (git clone + checkout)
- scm-github: branchExists() via git rev-parse
- agent-claude-code: getRestoreCommand() finds latest JSONL session file
  and builds claude --resume command

CLI + Web:
- Add `ao session restore <id>` subcommand
- Web restore API route uses sessionManager.restore() instead of spawn()
- SessionCard uses centralized TERMINAL_STATUSES/TERMINAL_ACTIVITIES
- Web types re-export core constants with sync tests

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

* fix: add "merged" to TERMINAL_STATUSES

The old inline isTerminal check included "merged" but when refactored
to use the TERMINAL_STATUSES set, "merged" was omitted. This caused
merged sessions (whose activity is not "exited") to incorrectly show
the "terminal" link and "terminate session" button.

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

* fix: enrich runtime state before restore check, remove dead branchExists

- Add enrichSessionWithRuntimeState() call before isRestorable() in
  restore() so crashed sessions (status "working", agent exited) are
  correctly detected as terminal and eligible for restore.
- Remove dead branchExists from SCM interface and scm-github plugin
  (defined but never called anywhere in the codebase).

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

* fix: allow restore of crashed working sessions

Remove "working" from NON_RESTORABLE_STATUSES. The isTerminalSession()
gate already prevents restoring truly active sessions (activity is not
"exited"). This fix allows crashed agents (status "working", activity
"exited") to be restored, aligning core behavior with the UI which
already shows the restore button for this case.

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

* fix: distinguish missing branch from missing restore support

Split the compound condition so workspace restore gives an accurate
error message when branch metadata is null ("branch metadata is
missing") vs when the workspace plugin lacks a restore method.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 01:12:57 +05:30
prateek de6653e258
feat: first-class orchestrator session + file-based system prompt (#101)
* feat: first-class orchestrator session + file-based system prompt

Make the orchestrator a first-class managed session that flows through
the same SessionManager pipeline as worker sessions, and fix a blocking
bug where long system prompts get truncated by tmux/zsh.

Changes:
- Add OrchestratorSpawnConfig type and spawnOrchestrator() to
  SessionManager interface
- Implement spawnOrchestrator() in session-manager.ts: proper
  hash-based tmuxName, runtimeHandle, plugin lifecycle — no workspace
  creation (uses project.path directly)
- Refactor `ao start` to use SessionManager.spawnOrchestrator()
  instead of manual tmux calls + metadata writes (~80 lines removed)
- Refactor `ao stop` to use SessionManager.kill() instead of manual
  tmux kill + metadata delete
- Update `ao init` next steps: guide users to `ao start` before
  `ao spawn`
- Add systemPromptFile to AgentLaunchConfig for file-based system
  prompts (avoids tmux truncation of 2000+ char inline prompts)
- Update agent-claude-code, agent-codex, agent-aider plugins to use
  shell command substitution "$(cat '/path')" when systemPromptFile
  is set
- Update runtime-tmux create() to use load-buffer/paste-buffer for
  launch commands >200 chars
- Add 8 tests for spawnOrchestrator
- Fix SessionManager mock in 8 test files (add spawnOrchestrator)

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

* fix: use hash-based tmux name in orchestrator attach hint

The tmux attach hint after `ao start` printed the user-facing session
ID (e.g. app-orchestrator) instead of the hash-based tmux session name
(e.g. a3b4c5d6e7f8-app-orchestrator), causing "session not found"
errors. Now captures the runtimeHandle.id from spawnOrchestrator's
return value for the correct tmux target.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 19:32:35 +05:30
prateek 767558fed6
fix: three spawn regressions from PR #88 session-manager refactor (#100)
1. No-issue spawn: use session/{sessionId} branch instead of defaultBranch
   to avoid git worktree conflicts with the main repo's checked-out branch.

2. Plugin resolution: accept importFn parameter in loadBuiltins/loadFromConfig
   so CLI can pass its own import() context for pnpm strict resolution. Added
   all plugin packages as CLI workspace dependencies.

3. Ad-hoc issue IDs: gracefully handle IssueNotFoundError by continuing
   without tracker context instead of throwing. Non-issue errors (auth,
   network) still fail fast.

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-18 17:53:33 +05:30
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