How jcode Implements Swarm Coordination for Multiple Agents: Event-Driven Architecture Explained
jcode implements swarm coordination for multiple agents by treating each session as an independent Agent attached to the same repository, automatically broadcasting server-side events that synchronize shared plans and member status across all connected clients.
The 1jehuang/jcode repository provides a terminal-based coding agent that supports collaborative editing through an event-driven swarm coordination system. When multiple users open the same repository simultaneously, jcode automatically detects the overlap and forms a swarm that enables real-time synchronization of plans, alerts, and conflict detection. This article examines the actual source code to explain exactly how jcode implements swarm coordination for multiple agents across its three-layer architecture.
The Three-Layer Architecture of Swarm Coordination
Agent Core: The Pending Alerts Buffer
At the foundation of the system lies the Agent struct defined in src/agent.rs. Each agent maintains a pending_alerts buffer (lines 94-100) that receives notifications generated from swarm events. According to the 1jehuang/jcode source code, when the agent prepares the next provider request via Agent::messages_for_provider, it appends these alerts to the system prompt using current_turn_system_reminder. This injection mechanism ensures the LLM sees the latest swarm plan without requiring separate API calls.
Protocol Layer: Server-Side Event Streaming
The coordination mechanism relies on two primary server-pushed event types dispatched through src/tui/app/remote/server_events.rs. The server emits ServerEvent::SwarmStatus { members } as a heartbeat containing a Vec<SwarmMemberStatus> that lists every participant and their lifecycle state. Additionally, ServerEvent::SwarmPlan transmits a diff of the shared plan, including additions, deletions, and re-orders. The client stores this data in a RemoteSwarmPlanSnapshot managed by src/tui/app/remote/swarm_plan_core.rs, which parses events and synchronizes both the UI and local state.
UI Layer: Visual Feedback and Conflict Detection
The presentation layer aggregates swarm data through SwarmInfo structures defined in src/tui/info_widget.rs. This component collects SwarmMemberStatus entries and the latest RemoteSwarmPlanSnapshot to render a concise status bar showing each member's role, conflict flags, and plan summaries. The background rendering logic in src/tui/info_widget_swarm_background.rs (lines 245-254) refreshes this display whenever new SwarmStatus or SwarmPlan events arrive, providing immediate visual feedback when conflicts emerge.
Step-by-Step Swarm Coordination Flow
-
Session Initialization: When a user executes
jcode start,Agent::newcreates an independent agent instance insrc/agent.rs. -
Automatic Swarm Detection: The backend recognizes existing sessions on the same repository and transmits an initial
SwarmStatusevent containing aVec<SwarmMemberStatus>that enumerates all participants. -
Event Processing: The dispatcher in
src/tui/app/remote/server_events.rsmatches incoming events, updatesApp::tui_state.swarm_info, and instantiatesRemoteSwarmPlanSnapshot::newto maintain local copies of the shared plan. -
Alert Generation: The system pushes textual alerts (e.g., "⚡ Swarm plan updated") into the
Agent.pending_alertsbuffer, ensuring the next LLM turn receives current context. -
LLM Context Injection: During
Agent::messages_for_provider, pending alerts append to the system prompt, allowing the model to generate conflict-aware responses based on the latest swarm state. -
Conflict Resolution: Each
SwarmMemberStatuscarries aconflictflag that the UI highlights; the backend rejects conflicting file writes and broadcasts updatedSwarmPlanevents to resolve discrepancies across the swarm.
Practical Configuration and Usage Examples
Enabling Swarm Mode via Configuration
Configure the swarm-specific model in your ~/.jcode/config.toml:
[agents]
swarm_model = "gpt-4o-mini" # model used for the swarm sub-agent
Starting a Multi-Agent Swarm
Launch two sessions pointing to the same repository to automatically form a swarm:
# Session A
jcode start myproj
# Session B (separate terminal)
jcode start myproj
Both clients receive SwarmStatus events listing both participants and begin exchanging plan updates immediately.
Accessing Swarm Plan Data Programmatically
Inspect pending alerts from within an agent turn:
use jcode::agent::Agent;
// Inside an agent turn
if let Some(plan) = agent.pending_alerts.last() {
println!("Latest swarm plan: {}", plan);
}
Runtime Model Selection
Switch the swarm model without restarting sessions using the TUI picker:
app.open_agent_model_picker(jcode::tui::AgentModelTarget::Swarm);
This updates the configuration and applies the new model to subsequent swarm turns.
Key Source Files for Swarm Coordination
src/agent.rs: CoreAgentstruct withpending_alertsfield and injection logic forAgent::messages_for_provider.src/tui/app/remote/server_events.rs: Event dispatcher handlingServerEvent::SwarmStatusandServerEvent::SwarmPlan.src/tui/app/remote/swarm_plan_core.rs: Helper for storingRemoteSwarmPlanSnapshotand generating user-visible notifications.src/tui/info_widget.rs:SwarmInfodefinition and rendering logic for member status display.src/tui/info_widget_swarm_background.rs: Background widget implementation for swarm status visualization.src/tui/app/remote/key_handling.rs: UI commands for toggling swarm features and updating configuration.src/tui/app/inline_interactive/openers.rs: Picker logic for launching swarm-specific targets from the command palette.
Summary
- jcode treats each session as an independent
Agentattached to a shared repository, automatically forming swarms when multiple sessions connect to the same codebase. - Coordination relies on
ServerEvent::SwarmStatusheartbeats andServerEvent::SwarmPlandiffs transmitted throughsrc/tui/app/remote/server_events.rs. - The
pending_alertsbuffer insrc/agent.rsinjects swarm context into LLM requests viaAgent::messages_for_providerandcurrent_turn_system_reminder. RemoteSwarmPlanSnapshotmaintains local copies of shared plans whileSwarmInforenders real-time status in the terminal UI.- Conflict detection uses boolean flags in
SwarmMemberStatus, with the backend rejecting conflicting writes and broadcasting resolution updates to maintain consistency.
Frequently Asked Questions
How does jcode detect when multiple agents form a swarm?
When a client opens a session with jcode start, the backend checks if other active sessions exist for the same repository. If detected, it automatically creates a swarm and broadcasts a SwarmStatus event containing a Vec<SwarmMemberStatus> to all connected clients, as implemented in the server event handling logic.
What types of events are exchanged between swarm members?
The protocol transmits two primary event types: ServerEvent::SwarmStatus serves as a heartbeat listing all members and their lifecycle states, while ServerEvent::SwarmPlan carries diffs of the shared plan including file additions, deletions, and re-ordering operations.
How does the LLM stay synchronized with the swarm plan?
The Agent struct maintains a pending_alerts buffer that receives notifications from swarm events. When preparing the next provider request in Agent::messages_for_provider, the system appends these alerts to the prompt via current_turn_system_reminder, ensuring the model receives the latest plan context without additional API calls.
How are conflicts handled in a jcode swarm?
Each SwarmMemberStatus includes a conflict flag that the UI highlights in the status bar. When conflicting file writes occur, the backend rejects the operation and broadcasts an updated SwarmPlan event that resolves the conflict, with visual feedback rendered through SwarmInfo in src/tui/info_widget.rs.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →