Beyond Claude Vibe Coding - Zellij terminal pane sub-agent spawning
Introduction: Claude Code and the Renaissance of Command-Line Development
Claude Code represents a paradigm shift in how we interact with AI assistants in development workflows. Unlike browser-based chat interfaces that treat AI as a separate tool, Claude Code embeds AI directly into your terminal environment where developers actually work. This integration makes the command line king again—not just for running commands, but as a unified interface for AI-assisted development.
But Claude Code's power extends far beyond simple "vibe coding." The platform provides a rich extensibility ecosystem that transforms it from a chat interface into a programmable development environment. Through agents (autonomous sub-tasks), MCP servers (Model Context Protocol for external integrations), skills (reusable capabilities), custom slash commands (user-defined operations), hooks (event-driven automation), BMAD (Background Multi-Agent Development), and claude-flow (workflow orchestration), developers can create sophisticated automation systems tailored to their exact needs.
The key insight is that Claude Code isn't just an AI that lives in your terminal—it's a platform for building AI-powered development tools that integrate seamlessly with your existing Unix toolchain. This blog post explores one such integration: a custom command system that delegates tasks to sub-agents running in Zellij terminal panes, creating a visual, persistent, and organized workflow for concurrent AI tasks.
Why Zellij? Terminal Multiplexing Meets Modern Development
Zellij is a modern terminal multiplexer (like tmux or screen) that provides a workspace-oriented approach to managing multiple terminal sessions. Unlike traditional multiplexers, Zellij emphasizes discoverability and ease of use with its modal keybindings, floating panes, and intuitive session management.
Quick Zellij Primer:
# Install Zellij
curl -L https://github.com/zellij-org/zellij/releases/latest/download/zellij-x86_64-unknown-linux-musl.tar.gz | tar xz
sudo mv zellij /usr/local/bin/
# Launch a new session
zellij
# Key concepts:
# - Panes: Split your terminal into multiple views
# - Tabs: Organize panes into workspaces
# - Sessions: Named, persistent work environments
# - Layouts: Predefined pane arrangements
Basic pane operations:
The Zellij + Claude Code Advantage:
When you combine Zellij with Claude Code, you create a powerful development environment where:
This integration transforms Claude Code from a single-threaded assistant into a multi-tasking orchestration platform where you can delegate research, code analysis, file processing, and other tasks to autonomous agents while continuing your primary work.
Architecture Overview: The Zellij-Agent System
The system consists of four main components working together to create a seamless agent delegation experience:
1. The Custom Slash Command (zellij-agent.md)
At the heart of the system is the /zellij-agent custom command, stored at ~/.claude/commands/zellij-agent.md. Claude Code automatically discovers commands in this directory and makes them available via slash notation.
The command uses frontmatter metadata to define its interface:
---
description: Delegate a task to a sub-agent with live monitoring in a zellij pane
argument-hint: <task-description>
---
This creates a command that accepts any task description: /zellij-agent Count all TODO comments in the codebase
The Smart Positioning Algorithm:
The command's most sophisticated feature is its intelligent pane positioning logic. It needs to handle two scenarios:
The implementation uses Zellij's layout dump to count columns:
# Count columns by checking layout structure
LAYOUT=$(zellij action dump-layout 2>&1)
COLUMN_COUNT=$(echo "$LAYOUT" | awk '/focus=true hide_floating_panes=true/,/^ \}/' | grep -c 'split_direction="vertical"')
if [ "$COLUMN_COUNT" -eq 0 ]; then
# Single column - create new column to the right
DIRECTION="right"
else
# Multiple columns - navigate to rightmost, then create down
for i in {1..10}; do
zellij action move-focus right 2>/dev/null || break
done
DIRECTION="down"
fi
This ensures that all agent tasks appear in the rightmost column, stacked vertically, creating a clean visual separation from your main work.
Task Environment Preparation:
Each task gets unique identifiers for tracking and organization:
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
TASK_HASH=$(echo "$ARGUMENTS" | md5sum | cut -c1-8)
RESULT_FILE="$HOME/var/task-${TIMESTAMP}-${TASK_HASH}.md"
mkdir -p "$HOME/var"
This creates result files like ~/var/task-20251026-105831-4e0686da.md, making it easy to find task outputs later and preventing filename collisions.
Launching the Monitoring Pane:
The command spawns a Zellij pane running the monitoring script:
zellij action new-pane --close-on-exit --direction "$DIRECTION" \
--name "sub-agent-${TASK_HASH}" \
-- ~/.claude/commands/scripts/spawn-agent-pane.sh "$ARGUMENTS" "$RESULT_FILE"
The --close-on-exit flag ensures the pane automatically closes when the script finishes, keeping your workspace clean.
Sub-Agent Delegation:
After launching the monitoring pane, the command instructs Claude to use its Task tool to spawn an autonomous sub-agent:
Use Task tool with subagent_type="general-purpose" with this prompt:
Task: $ARGUMENTS
Instructions:
1. Execute the task: "$ARGUMENTS"
2. Gather all necessary information using available tools
3. Create a comprehensive markdown report
4. Write the complete results to: $RESULT_FILE
Format the output file with metadata, summary, detailed results, and conclusions.
This creates a complete workflow: the monitoring pane shows progress, the sub-agent does the work, and results are saved to a structured markdown file.
2. The Monitoring Script (spawn-agent-pane.sh)
The spawn-agent-pane.sh script runs inside each Zellij pane and provides live visual feedback during task execution. Located at ~/.claude/commands/scripts/spawn-agent-pane.sh, this script is the user-facing interface for task monitoring.
Trap Handler for Reliability:
The script starts with a critical safety mechanism:
#!/bin/bash
# Ensure cleanup on exit/interrupt
trap "exit 0" TERM INT EXIT
TASK_DESC="$1"
RESULT_FILE="$2"
TIMEOUT_SECONDS=300 # 5 minute maximum
This trap ensures the script always exits cleanly, even if interrupted or killed, preventing hanging processes that caused the input freeze issues during development.
Visual Header Design:
The script creates an attractive ASCII art header for immediate visual recognition:
cat << 'EOF'
╔═══════════════════════════════════════════════════════════╗
║ 🤖 SUB-AGENT TASK EXECUTION ║
╚═══════════════════════════════════════════════════════════╝
EOF
echo ""
echo "📋 Task: $TASK_DESC"
echo "📝 Result: $RESULT_FILE"
echo "⏰ Started: $(date '+%Y-%m-%d %H:%M:%S')"
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "🔄 Sub-agent is working..."
echo " (This pane will remain open until task completes)"
This provides immediate context about what's running in each pane.
Progress Monitoring Loop:
The core of the script is a polling loop that waits for the result file:
WAIT_TIME=0
MAX_WAIT=300 # 5 minutes max
while [ $WAIT_TIME -lt $MAX_WAIT ]; do
if [ -f "$RESULT_FILE" ] && [ -s "$RESULT_FILE" ]; then
# File exists and has content - task complete!
echo "✅ Task completed!"
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "📄 Results saved to:"
echo " $RESULT_FILE"
echo ""
echo "⏱️ Duration: ${WAIT_TIME}s"
echo ""
echo "🎉 Closing pane in 3 seconds..."
sleep 3
exit 0
fi
# Show progress indicator every 5 seconds
if [ $((WAIT_TIME % 5)) -eq 0 ] && [ $WAIT_TIME -gt 0 ]; then
echo "⏳ Still working... (${WAIT_TIME}s elapsed)"
fi
sleep 1
WAIT_TIME=$((WAIT_TIME + 1))
done
This creates the live feedback users see: progress updates every 5 seconds, completion detection, duration tracking, and a 3-second countdown before the pane closes.
Timeout Handling:
If a task exceeds the 5-minute timeout:
echo "⚠️ Timeout reached after ${MAX_WAIT}s"
echo " Check if sub-agent is still running"
echo ""
echo "Closing pane in 5 seconds..."
sleep 5
This prevents indefinitely hanging panes while giving users time to notice there was an issue.
3. The Smart Position Helper (smart-pane-position.sh)
The smart-pane-position.sh script was created during development as a standalone helper for determining optimal pane positioning. While the final implementation inlines this logic in the main command, the script demonstrates the evolution of the positioning algorithm.
Initial Approach (Abandoned):
The first attempt tried to detect existing columns by testing if focus could move right:
CAN_MOVE_RIGHT=false
zellij action move-focus right 2>/dev/null && CAN_MOVE_RIGHT=true
This failed because Zellij's focus commands cycle through panes, making it impossible to distinguish between "moved to a different column" and "cycled back to the same column."
Layout Dump Approach (Final):
The solution was to parse Zellij's layout structure directly:
LAYOUT=$(zellij action dump-layout 2>&1)
COLUMN_COUNT=$(echo "$LAYOUT" | grep -c 'split_direction="vertical"')
However, this counted ALL vertical splits in the entire layout, including templates and inactive tabs. The final refinement filters to only the active tab:
COLUMN_COUNT=$(echo "$LAYOUT" | awk '/focus=true hide_floating_panes=true/,/^ \}/' | grep -c 'split_direction="vertical"')
This accurately counts columns in the current workspace and enables the intelligent positioning behavior.
4. The Legacy Agent Runner (zellij-agent-runner.sh)
The zellij-agent-runner.sh script represents an earlier iteration of the system before the Task tool integration was refined. It's retained for reference and demonstrates an alternative approach to agent delegation.
Task Metadata Generation:
This script shows a different method for creating task identifiers:
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
TASK_ID=$(echo "$1" | md5sum | cut -c1-8)
RESULT_FILE="$HOME/var/task-${TIMESTAMP}-${TASK_ID}.md"
Template-Based Result Files:
Rather than having the sub-agent create the result file, this version pre-creates a template:
cat > "$RESULT_FILE" << EOF
# Sub-Agent Task Results
**Task ID**: ${TASK_ID}
**Timestamp**: ${TIMESTAMP}
**Task Description**: $*
---
## Task Execution
## Agent Output
Task: $*
Status: Ready for agent execution
_Note: This task was delegated via zellij pane. Parent agent should use Task tool to execute._
EOF
This approach was superseded by having the sub-agent create the complete file, but it demonstrates an alternative workflow where the monitoring script prepares the structure and the agent fills in results.
5. The Test Command (test-zellij.md)
The test-zellij.md command serves as both a verification tool and a simple example of Zellij integration without the complexity of agent delegation.
Simple Workflow Validation:
Test the zellij pane workflow by:
1. Opening a new pane on the right side
2. Running a simple bash command that creates a test file in ~/var/
3. Auto-closing the pane after 2 seconds
Execute this command:
```bash
zellij run --direction right --close-on-exit --name "test-pane" \
-- bash -c 'echo "Test completed at $(date)" > ~/var/test-$(date +%s).txt && \
echo "File created: ~/var/test-$(date +%s).txt" && \
sleep 2'
This demonstrates:
Recommended by LinkedIn
It's an excellent starting point for understanding the mechanics before diving into the full agent system.
Workflow Deep Dive: How It All Works Together
When you execute /zellij-agent Analyze CPU usage trends over the last hour, here's the complete sequence of events:
Step 1: Command Parsing (0-1 second)
Claude Code recognizes the /zellij-agent command and loads zellij-agent.md. It extracts the argument: "Analyze CPU usage trends over the last hour"
Step 2: Environment Setup (1-2 seconds)
The command generates unique identifiers:
It ensures ~/var/ exists and is writable.
Step 3: Layout Analysis (2-3 seconds)
The command dumps the Zellij layout and counts columns:
If COLUMN_COUNT == 0:
→ User has single pane (just Claude)
→ Direction = "right" (create new column)
Else:
→ Multiple columns exist
→ Navigate to rightmost column
→ Direction = "down" (stack in that column)
Step 4: Pane Launch (3-4 seconds)
Zellij spawns a new pane running spawn-agent-pane.sh:
┌─────────────┬─────────────────────────────┐
│ │ ╔═════════════════════════╗ │
│ Claude │ ║ 🤖 SUB-AGENT EXECUTION ║ │
│ Main │ ╚═════════════════════════╝ │
│ Session │ │
│ │ 📋 Task: Analyze CPU... │
│ │ 📝 Result: ~/var/task-... │
│ │ ⏰ Started: 11:00:00 │
│ │ │
│ │ 🔄 Sub-agent is working... │
└─────────────┴─────────────────────────────┘
Step 5: Sub-Agent Delegation (4-10 seconds)
Claude spawns a sub-agent using the Task tool. The sub-agent:
Meanwhile, the monitoring pane shows progress updates every 5 seconds.
Step 6: Task Completion (10-60 seconds, varies)
When the sub-agent writes the result file, the monitoring script detects it:
⏳ Still working... (5s elapsed)
⏳ Still working... (10s elapsed)
⏳ Still working... (15s elapsed)
✅ Task completed!
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📄 Results saved to:
~/var/task-20251026-110000-a1b2c3d4.md
⏱️ Duration: 18s
🎉 Closing pane in 3 seconds...
Step 7: Auto-Cleanup (60-63 seconds)
After 3 seconds, the pane closes automatically due to --close-on-exit, leaving your workspace clean.
Step 8: Result Access (any time later)
The task results are permanently saved:
cat ~/var/task-20251026-110000-a1b2c3d4.md
Output:
---
task_id: 20251026-110000-a1b2c3d4
task: Analyze CPU usage trends over the last hour
timestamp: 2025-10-26 11:00:00
status: completed
---
# CPU Usage Trend Analysis
## Summary
Average CPU usage over the last hour: 34.2%
Peak usage: 87% at 10:42:15
Lowest usage: 12% at 10:15:30
## Detailed Analysis
[... comprehensive results ...]
Usage Examples: Practical Applications
Example 1: Code Quality Analysis
Command:
/zellij-agent Find all TODO comments in the codebase and categorize them by priority and module
What happens:
Result file (~/var/task-20251026-112000-xyz789.md):
# TODO Comment Analysis
## Summary
Total TODOs: 47
High Priority: 12
Medium Priority: 23
Low Priority: 12
## By Module
### Authentication Module (High Priority)
- `src/auth/login.ts:42` - TODO: Implement rate limiting
- `src/auth/oauth.ts:156` - TODO: Add token refresh logic
[... detailed categorization ...]
Example 2: Dependency Audit
Command:
/zellij-agent Audit all npm dependencies for security vulnerabilities and license compliance
Workflow:
Example 3: Performance Benchmarking
Command:
/zellij-agent Run performance benchmarks on the API endpoints and compare with last week's baseline
Multi-step process:
Example 4: Documentation Generation
Command:
/zellij-agent Generate API documentation from TypeScript interfaces in src/types/
Automated workflow:
Example 5: Concurrent Tasks
Multiple simultaneous delegations:
/zellij-agent Analyze memory usage patterns
/zellij-agent Count lines of code by language
/zellij-agent Find potential SQL injection vulnerabilities
Result:
┌───────────┬─────────────┐
│ │ Memory │
│ Claude │ Analysis │
│ ├─────────────┤
│ │ LOC Count │
│ ├─────────────┤
│ │ SQL Audit │
└───────────┴─────────────┘
All three tasks run concurrently, each with its own monitoring pane, all stacked in the rightmost column.
Advanced Patterns and Best Practices
Pattern 1: Sequential Task Chains
For complex workflows requiring multiple steps:
/zellij-agent Fetch latest sales data from database and save to CSV
# Wait for completion, then:
/zellij-agent Analyze sales data from ~/var/task-[timestamp].csv and generate trend report
Pattern 2: Parallel Research Tasks
Delegate multiple research tasks simultaneously:
/zellij-agent Research best practices for React Server Components
/zellij-agent Find recent CVEs affecting our tech stack
/zellij-agent Analyze competitor pricing strategies
All run concurrently with separate monitoring panes.
Pattern 3: Long-Running Background Tasks
For tasks that take extended time:
/zellij-agent Download and analyze last month's server logs for error patterns
The monitoring pane stays open, showing progress every 5 seconds, while you continue other work in the main Claude session.
Best Practices
Conclusion: The Future of AI-Assisted Development
The Zellij-agent system demonstrates how Claude Code's extensibility transforms it from a chat interface into a programmable automation platform. By combining custom slash commands, shell scripts, terminal multiplexing, and autonomous agents, we've created a system that:
This is just one example of what's possible. The same principles can be extended to:
The command line isn't just back—with tools like Claude Code and thoughtful integrations like this Zellij system, it's more powerful than ever. The future of development isn't choosing between AI and traditional tools; it's building seamless integrations that make them work together.
Ready to try it yourself?
The complete source code is available at: https://github.com/jreuben11/dotfiles/tree/main/claude/.claude/commands
Happy hacking! 🚀
in the age of Claude, commandline is king - ditch your IDE and brush up on LazyVim - here is a good resource: https://lazyvim-ambitious-devs.phillips.codes/course/ You may also consider Hyprland https://www.youtube.com/watch?v=V7nP-To0630&list=PLZhEtW7iLbnB0Qa0kp9ICLViOp6ty4Rkk&index=2