* feat: support multiple concurrent orchestrators with isolated worktrees
- Each orchestrator session gets a numbered ID ({prefix}-orchestrator-N)
and an isolated git worktree, replacing the single shared orchestrator
- reserveNextOrchestratorIdentity atomically reserves the next available
number and detects conflicting project prefix configurations early
- isOrchestratorSession / isOrchestratorSessionName accept optional
allSessionPrefixes for cross-project false-positive prevention
- getProjectPause and resolveGlobalPause track the longest active pause
across all concurrent orchestrators instead of returning the first found
- cleanupWorktreeAndMetadata helper used consistently on all failure paths
including post-launch; system prompt file included in cleanup
- pollBacklog, status.ts, ProjectSidebar, sessions page, global-pause,
project-utils, serialize, and sessions API route all pass
allSessionPrefixes to isOrchestratorSession
- Web sessions/[id]/page.tsx fetches project prefix map and passes it
through prefixByProjectRef to avoid stale closure in fetchProjectSessions
* fix: seed sseAttentionLevels from fresh sessions on full refresh
When scheduleRefresh dispatches a reset action, derive sseAttentionLevels
from the freshly fetched sessions using getAttentionLevel. This clears
phantom entries for removed sessions and seeds correct levels for new
sessions, preventing stale favicon color and attention counts until the
next SSE snapshot.
* fix: merge duplicate @/lib/types imports into single import statement
Combining the separate import type and value import from @/lib/types
into one import to satisfy the no-duplicate-imports lint rule.
- Fix bad temp name for non-standard packages: use full packageName
instead of last hyphen-segment to avoid collisions between packages
like "custom-tracker-plugin" and "my-custom-plugin"
- Fix disabled top-level plugin blocking inline loading: when an
existing plugin entry has `enabled: false`, it's now set to `true`
when there's an inline tracker/scm/notifier reference for the same
package/path
- Create validatePluginConfigFields helper to deduplicate the
TrackerConfigSchema, SCMConfigSchema, and NotifierConfigSchema
validation logic (was duplicated thrice)
- Fix multi-project external plugin order-dependency: tracker and SCM
plugins now receive no project-level config at create() time, making
them consistent with built-in plugins. Project-specific config is
passed per-call via ProjectConfig argument, avoiding first-project
wins behavior
- Document post-validation invariant for plugin field: added
documentation clarifying that `plugin` is always populated after
validateConfig() to help downstream consumers understand they can
safely assume non-null after validation
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
extractPluginConfig was being called with mod.manifest.name before the
config was updated from the temp name. When manifest name differs from
temp name (e.g., temp "teams" vs manifest "ms-teams"), extractPluginConfig
found no match and returned undefined, causing the plugin to be registered
without its configuration (webhook URLs, tokens, etc.).
Fix by reordering operations:
1. Validate and update configs with manifest.name FIRST
2. Extract plugin config AFTER (now finds the config by manifest.name)
3. Register plugin with its correct configuration
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
When multiple projects share the same external plugin, a misconfiguration
in one project (wrong expectedPluginName) would prevent the plugin from
being registered at all, silently breaking it for all projects.
Fix by:
1. Register the plugin FIRST, before validating individual project configs
2. Validate each project's config in its own try-catch
3. Log validation errors but continue processing other projects
This ensures:
- Plugin is always registered if it loads successfully
- Projects with correct config get updated
- Projects with bad config get a warning but don't break others
- Misconfigured projects fail at point of use with clearer errors
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
generateTempPluginName was splitting package names on both hyphens and
slashes, which truncated multi-word names like "jira-cloud" to just
"cloud".
Fix by first extracting the package name without scope, then using a
regex to match the common ao-plugin-{slot}-{name} pattern which
preserves the full plugin name including hyphens.
Examples:
- @acme/ao-plugin-tracker-jira-cloud -> jira-cloud (was: cloud)
- ao-plugin-scm-azure-devops -> azure-devops (was: devops)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Strip package and path loading metadata from notifier config passed
to plugin create(). These fields are used for plugin resolution, not
plugin-specific configuration. Prevents filesystem paths from leaking
into plugin config where they could conflict with plugin-specific
fields of the same name.
- Remove collectExternalPluginConfigs from public API exports since it
is only used internally within config.ts during validateConfig.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Fix multiple projects sharing same external plugin: change
findExternalPluginEntry to findAllExternalPluginEntries which returns
all matching entries, allowing all projects to be updated with the
actual manifest.name
- Fix path without slashes misidentified as npm package: use separate
pkg and path parameters in generateTempPluginName instead of combining
them and checking for slashes. Local paths like "my-tracker" (no
slashes) are now correctly returned as-is
- Replace console.warn with process.stderr.write for structured logging
in plugin-registry.ts
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Remove unused collectExternalPluginConfigs import from tests
- Add missing location field to _externalPluginEntries in test
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
1. Only set expectedPluginName when user explicitly specifies `plugin`
- Auto-generated temp names no longer block manifest name inference
- External plugins like @acme/ao-plugin-tracker-jira-cloud with
manifest.name "jira-cloud" will now load correctly
2. Add structured location data to ExternalPluginEntryRef
- New ExternalPluginLocation type with kind/projectId/configType
- Avoids fragile string parsing of source (project/notifier keys
can legally contain dots)
3. Expand home paths (~/) in inline plugin configs
- Apply expandHome() to tracker/scm/notifier path fields
- Consistent behavior with config.plugins path expansion
4. Improve error messages
- Use "package" vs "path" in manifest mismatch errors instead
of always saying "package"
5. Fix tests to use config._externalPluginEntries
- Tests now check entries stored by validateConfig() instead
of calling collectExternalPluginConfigs() again on modified config
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Update all usages of project.tracker.plugin and project.scm.plugin
to use optional chaining since the plugin field is now optional
when package or path fields are specified.
Files updated:
- CLI: doctor.ts, status.ts, verify.ts
- Web: issues/route.ts, verify/route.ts, scm-webhooks.ts,
serialize.ts, services.ts
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add support for specifying external plugins inline in tracker, scm, and
notifier configs using optional `package` or `path` fields.
**Config schema changes:**
- TrackerConfig, SCMConfig, NotifierConfig now accept optional `package`
(npm) or `path` (local) fields alongside the existing `plugin` field
- When only `package`/`path` is specified, plugin name is auto-inferred
- When both `plugin` and `package`/`path` are specified, manifest.name
is validated against the declared plugin name
**Example usage:**
```yaml
projects:
my-app:
tracker:
plugin: jira # optional - validates against manifest.name
package: "@acme/ao-plugin-tracker-jira"
teamId: "TEAM-123"
scm:
path: ./plugins/my-scm # local plugin
notifiers:
teams:
package: "@acme/ao-plugin-notifier-teams"
```
**Implementation details:**
- collectExternalPluginConfigs() extracts external plugin entries from
tracker/scm/notifier configs during config validation
- Auto-generates InstalledPluginConfig entries merged into config.plugins
- Plugin registry validates manifest.name matches expectedPluginName and
updates config with actual manifest.name after loading
- Warns when plugin slot doesn't match configured slot
Closes#736
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* fix(agent-claude-code): return idle state when no JSONL session file exists
Freshly spawned sessions had no Claude Code JSONL file yet (Claude Code
doesn't create it until the first conversation), causing getActivityState
to return null → displayed as 'unknown' in ao status.
When the process is running but no session file exists, return
{ state: 'idle', timestamp: now } so the dashboard shows the correct
state immediately after spawn.
Closes#883
* fix(agent-claude-code): use session.createdAt for idle timestamp when no JSONL file
Using new Date() as the timestamp caused isIdleBeyondThreshold to always
compute ~0ms, preventing stuck detection from ever firing for sessions that
hang before creating a JSONL file. Using session.createdAt correctly
represents when the session began, allowing stuck detection to eventually
trigger.
Replace hardcoded "merged"/"killed" checks in pollAll() with the
canonical TERMINAL_STATUSES set from types.ts. This ensures sessions
in done, terminated, cleanup, or errored states are correctly treated
as inactive for polling, active-count, and all-complete detection.
Closes#752
tsconfig.server.json sets rootDir:"server" so importing from
../src/lib/mux-protocol.ts violated the boundary and broke the CI
typecheck step. Reverted to local type definitions with a comment
linking to the canonical source.
Also adds tests to bring diff coverage above 80%:
- MuxProvider.test.tsx: 30 tests covering lifecycle, message handling,
and all terminal operations (subscribeTerminal, write, open, close,
resize, reconnect, cleanup)
- api-routes.test.ts: GET /api/sessions/patches coverage (success,
field shape, project filter, error path)
- useSessionEvents.test.ts: mux-path tests (muxSessions snapshot
dispatch, membership-change scheduleRefresh, mux-active SSE bypass,
cleanup on unmount)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
After a reconnect MuxProvider re-opens all terminals, but new PTYs spawn
at 80×24 default. DirectTerminal only sent the initial resize on mount.
Add a dedicated effect that fires whenever muxStatus transitions to
"connected": calls fit.fit() to measure the current container then sends
the live cols/rows to the server, keeping the PTY size in sync.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
muxStatus was in the deps array solely for the guard check at the top of
the effect. This caused the entire RAF loop + transitionend + backup timers
to re-run on every mux status transition (e.g. reconnecting→connected),
even when no layout change occurred.
Fix: track muxStatus in a ref (updated on every render) and read the ref
inside the effect, so the guard always sees the current value without
muxStatus being a dependency.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Add reattachAttempts counter to ManagedTerminal and MAX_REATTACH_ATTEMPTS
constant (3). The onExit handler only re-calls open() while the counter is
below the cap, resets it to 0 on a successful attach, and falls through to
notify exit callbacks once the limit is reached — preventing a crash-loop
where a PTY that exits immediately after spawn triggers infinite re-attaches.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
A throwing callback (e.g. ws.send on a closed socket) would abort the
for-of loop, causing remaining subscribers to miss the data chunk and
skipping the ring buffer update — corrupting replay history for future
reconnections. Wrapping each call in try-catch keeps all subscribers
independent and ensures the buffer update always runs.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
In the ws library, "error" is always followed by "close", so the close
handler's cleanup (clearInterval, unsubscribe sessions, unsubscribe all
terminals) was running twice. Reduced the error handler to just the
console.error log and let close handle cleanup exclusively.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Replace the duplicated ClientMessage/ServerMessage/SessionPatch local
type definitions in mux-websocket.ts with a single import type from
src/lib/mux-protocol.ts — eliminates the risk of the two copies drifting
apart as the protocol evolves
- Add ws.readyState === WebSocket.OPEN guard to the ws.send call inside
the terminal-operation catch block, consistent with all other sends in
the file; prevents a throw that would bubble into the outer catch and
replace the real error with a misleading "Invalid message format"
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- SessionBroadcaster.connect(): capture controller in a local variable and
only clear this.abortController in finally if it still equals the local
controller; prevents a concurrent connect() call's controller being
nullified by an older connect()'s finally block
- Heartbeat: send ws.ping() before incrementing missedPongs so all
MAX_MISSED_PONGS pings are actually transmitted before terminating
(previously terminated after MAX_MISSED_PONGS-1 sent pings)
- Remove TerminalManager.close(): never called by the mux handler (which
uses per-subscriber unsubscribe instead) and subtly broken — it killed
the PTY without clearing subscribers, which would have triggered an
immediate re-attach via onExit
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Move buffer send + subscribe inside !subscriptions.has(id) guard so
reconnecting clients don't receive the history replay twice (once on
first open, once after wsRef is reassigned on reconnect)
- Remove `terminals` field from MuxContextValue and useMemo — it was
populated from a write-only ref and never consumed by any component
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- useSessionEvents: mux-active SSE cleanup now also resets
pendingMembershipKeyRef and refreshingRef so the aborted fetch's
.finally() handler cannot reschedule after unmount
- DirectTerminal: add distinct "Disconnected" label and error-coloured
dot for muxStatus "disconnected" (WebSocket constructor failure with
no reconnect), instead of the misleading "Connecting…" shown for
transient states
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The SSE effect had muxSessions (array reference) in its deps, causing
it to re-run on every snapshot and fire cleanup that cleared the
debounce timer the mux effect intentionally preserved.
- Derive muxActive = muxSessions !== undefined and use that in SSE
effect deps — the effect now only re-runs when mux transitions
between present/absent, not on every new array reference
- Add reschedule in scheduleRefresh .finally() abort path: when a
fetch is aborted mid-flight (by a new snapshot) and there is still
a pending membership key, reschedule so the refresh isn't silently
dropped
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- MuxProvider: handle exited and error terminal messages — exited
removes the terminal from openedTerminalsRef (preventing re-open on
reconnect) and writes a red notice into the xterm stream; error is
logged to console
- MuxProvider: remove dead buffersRef/bufferBytesRef — client-side
ring buffer was never read; the server already delivers history on
open
- mux-websocket: use ws.terminate() instead of ws.close() on heartbeat
timeout — an unresponsive peer won't complete the close handshake,
so terminate() immediately destroys the socket and frees resources
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Removing the muxSessions.length === 0 guard so an empty snapshot
triggers the membership-key comparison and scheduleRefresh(), which
fetches the full session list and dispatches a reset. Previously,
[] caused an early return that left removed sessions visible indefinitely.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- MuxProvider: reset isDestroyedRef to false at the start of the
effect so React StrictMode's double-invoke doesn't permanently break
the connection (cleanup sets it true, re-run must reset it)
- DirectTerminal: remove dead status state — it was only set to "error"
in a catch block but never read; displayStatus already derives the
error indicator from the error string directly
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- mux-websocket: wire up the exited ServerMessage — add exitCallbacks
to ManagedTerminal, pass onExit param through subscribe(), and fire
callbacks when PTY exits and re-attach fails so clients get notified
- DirectTerminal: fix displayStatus to show "error" when there is a
local error (e.g. xterm.js load failure) regardless of mux state
- useSessionEvents: SSE effect's mux early-return path now returns a
cleanup function that clears refreshTimerRef and aborts in-flight
requests on unmount, preventing post-unmount dispatch calls
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- DirectTerminal: remove stale muxStatus read from xterm setup effect
(muxStatus was captured at mount, leaving reload button permanently
disabled); reload button now checks muxStatus directly on each render
- TerminalManager: kill PTY and delete map entry when last subscriber
unsubscribes, preventing orphaned node-pty processes when all mux
clients disconnect
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- MuxProvider: assign wsRef.current immediately after construction so
cleanup can close a WebSocket that is still in CONNECTING state;
add isDestroyedRef to prevent the close handler from scheduling
reconnects after the component unmounts
- mux-websocket: client "close" message now only unsubscribes that
client — removed terminalManager.close() which killed the shared PTY
for every other connected client
- useSessionEvents: mux effect cleanup no longer clears the debounce
timer; only aborts in-flight requests, preventing rapid mux snapshots
from starving the membership-change refresh
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Replace Node.js Buffer.byteLength() with TextEncoder in MuxProvider
(browser-safe UTF-8 byte counting for the ring buffer)
- Remove write-only sessionSubscribedRef from MuxProvider
- Remove dead DirectTerminalLocation, DirectTerminalWsUrlOptions,
buildDirectTerminalWsUrl and their tests (superseded by mux)
- Call closeTerminal(sessionId) on DirectTerminal unmount so PTY
processes are released and openedTerminalsRef stays accurate
- Add cleanup return to mux effect in useSessionEvents so pending
refresh timers and abort controllers are cleared on unmount
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Use native WS ping frames for heartbeat so idle browser clients are not
incorrectly disconnected (browser auto-responds to native ping with pong)
- Pass runtime config to buildMuxWsUrl() so dynamic port/proxy path set via
TERMINAL_WS_PATH env var is actually used (was fetched but never consumed)
- Delay initial WS connect until runtime config fetch resolves, preventing
race condition on first load
- shutdown() now terminates all mux clients and closes the WSS, preventing
orphaned PTY processes on restart
- ws 'error' handler now unsubscribes terminal callbacks alongside session
subscription to prevent leaks in edge cases where 'close' does not follow
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Replace three separate real-time channels (per-terminal WS, SSE, HTTP poll)
with a single persistent multiplexed WebSocket at /mux.
Architecture:
- Browser ↔ MuxProvider owns one WS connection per tab (/mux)
- Terminal I/O, resize, open/close all flow over mux channels
- Session status patches delivered via a shared SSE relay:
mux server subscribes once to Next.js /api/events (SSE) and
broadcasts to all connected browser clients — no per-client polling
- Manual WS upgrade routing fixes ws library limitation with multiple
WebSocketServer instances on the same HTTP server
Remove:
- terminal-websocket.ts (legacy ttyd-based per-session server, port 14800)
- Per-terminal WebSocket connections from DirectTerminal
- Per-client 5 s HTTP polling for session patches
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Implements client-side multiplexed WebSocket context:
- Create MuxProvider component with persistent connection management
- Implement exponential backoff reconnection (1s to 30s)
- Add subscribeTerminal/writeTerminal/resizeTerminal/openTerminal methods
- Manage per-terminal ring buffers (50KB max) for background output
- Track session patches from server
- Create useMux() hook for easy access in components
- Mount MuxProvider in app root layout via Providers wrapper
- Support dynamic runtime config from /api/runtime/terminal
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Implements backend multiplexed WebSocket server on /mux endpoint:
- Add mux-protocol.ts with ClientMessage and ServerMessage types
- Create TerminalManager class for managing PTY processes independently
- Implement mux-websocket.ts with attachMuxWebSocket() function
- Wire mux server into existing direct-terminal-ws server
- Support multiple terminals over single persistent WebSocket connection
- Implement 50KB ring buffer for background terminal output
- Add heartbeat and reconnection logic
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: event-driven live tab titles and favicons via SSE
Switch tab titles and favicons from polling to real-time SSE updates:
- Extend useSessionEvents to expose sseAttentionLevels map from SSE
snapshots (server-computed, includes full PR state)
- Refactor DynamicFavicon to use SSE attention levels instead of
recomputing from the full sessions array (which has stale PR data
between refreshes)
- Add useSSESessionActivity hook for session detail page to update
document.title emoji immediately on activity change
- Add live dashboard title showing count of sessions needing attention
- Update PullRequestsPage to use new DynamicFavicon API
Closes#115
* fix: seed initial attention levels to avoid stale favicon/title on first render
Accept initialAttentionLevels parameter in useSessionEvents so callers
can seed the attention map from initialSessions via getAttentionLevel().
This prevents the favicon and dashboard title from briefly showing
"all clear" before the first SSE snapshot arrives.
* fix: add EventSource mock to session page test for SSE hook compatibility
* fix: reset stale activity state when sessionId changes in useSSESessionActivity
Add sessionId to the effect dependency array and reset state to null at
the start of each effect run so callers that reuse the hook with a
different sessionId don't see the previous session's activity.
* fix: reset sseAttentionLevels on initialSessions change to prevent stale data on project switch
The reset action now accepts an optional sseAttentionLevels field. When
initialSessions changes (e.g., project switch via sidebar), the dispatch
passes the current initialAttentionLevels via ref so the favicon and
dashboard title reflect the new project immediately rather than showing
stale attention data until the first SSE snapshot.