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.
* feat: add CI failure detail notifications in lifecycle manager
When CI fails on a PR, the lifecycle manager now fetches individual check
details (names, statuses, URLs) and sends them to the worker session.
This complements the existing static reaction message with actionable
debugging information.
Flow:
- On first transition to ci_failed: static reaction message fires (existing)
- On next poll: detailed CI failure info with check names and URLs dispatched
- Fingerprinting prevents re-sending the same failure set
- New/changed failures trigger fresh detailed notifications
- Tracking metadata cleared when PR is merged/closed or CI passes
Follows the same deduplication pattern as maybeDispatchReviewBacklog().
* fix: send CI details directly to avoid consuming reaction retry budget
The detailed CI failure dispatch now uses sessionManager.send() directly
instead of executeReaction(), so it doesn't increment the ci-failed
reaction tracker. This prevents low retries/escalateAfter settings from
causing premature escalation before the agent receives failure details.
The transition reaction still owns escalation; the detailed dispatch is
purely informational follow-up delivery.
* feat: add merge conflict notifications in lifecycle manager
Adds maybeDispatchMergeConflicts() that detects merge conflicts from
the PR enrichment cache or getMergeability() and notifies the worker
session. Conflicts are dispatched independently of session status since
they can coexist with ci_failed, changes_requested, etc.
- Uses the existing merge-conflicts reaction config
- Dispatches once per conflict occurrence (tracks lastMergeConflictDispatched)
- Clears tracking when conflicts resolve, allowing re-dispatch if they recur
- Sends directly via sessionManager.send() (same pattern as CI details)
* fix: use CICheck type instead of inline type declaration
Replace inline Array<{ name, status, url, conclusion }> with the
existing CICheck type from ./types.js for formatCIFailureMessage and
the checks variable in maybeDispatchCIFailureDetails.
* fix: resolve no-useless-assignment lint error in merge conflict check
Declare hasConflicts without initial value since both branches of the
if/else assign to it before it's read.
* feat: show agent notification state in session page blockers
The blockers section on both SessionDetail (IssuesList) and SessionCard
(alert pills) now shows whether the agent has been notified about each
blocker. Reads lifecycle manager dispatch metadata:
- lastCIFailureDispatchHash for CI failures
- lastMergeConflictDispatched for merge conflicts
- lastPendingReviewDispatchHash for review comments
Displays "agent notified" indicator next to blockers where the lifecycle
manager has already forwarded the issue to the worker session.
* fix: use lifecycle status as fallback for blockers when PR data is stale
The blockers section now uses the lifecycle manager's session status
metadata as a source of truth when PR enrichment data hasn't caught up.
PR enrichment uses a 5-min cache and can timeout or be rate-limited,
causing blockers to show stale/incorrect state.
Changes:
- IssuesList and getAlerts now check metadata["status"] (lifecycle
manager state) alongside PR enrichment data
- CI failing: shown when pr.ciStatus is "failing" OR lifecycle status
is "ci_failed"
- Changes requested: shown when pr.reviewDecision matches OR lifecycle
status is "changes_requested"
- Merge conflicts: shown when pr.mergeability.noConflicts is false OR
lifecycle dispatch metadata indicates conflicts were detected
* fix: fall back to getMergeability when cached hasConflicts is undefined
When PREnrichmentData has hasConflicts as undefined (the field is typed
as boolean | undefined), the previous check treated it as no conflicts.
Now falls through to the getMergeability() call instead.
* test: add coverage for CI/conflict notify action and recovery paths
- Test CI tracking clears when CI recovers to passing
- Test notify action for CI failure details (human notification path)
- Test notify action for merge conflicts (human notification path)
These cover the previously uncovered notify action branches and the
CI recovery cleanup path in the lifecycle manager.
* fix: resolve typecheck error in CI recovery test
writeMetadata requires SessionMetadata type which doesn't include
custom keys like lastCIFailureFingerprint. Rewrote the test to use
setupCheck and let the lifecycle manager set tracking metadata
naturally through the CI failure flow, then verify cleanup on recovery.
* fix: don't use dispatch metadata for conflict detection in UI
lastMergeConflictDispatched lingers after conflicts resolve until the
lifecycle manager's next poll clears it. Using it as a conflict signal
caused stale "merge conflict" alerts. Now only pr.mergeability.noConflicts
drives conflict detection; the metadata is only used for the "agent
notified" badge.
* fix: use Promise.allSettled for dispatch functions to avoid orphaned rejections
Promise.all rejects immediately on first failure, leaving in-flight
promises unmonitored. Promise.allSettled waits for all to complete.