Beyond Claude Vibe Coding - Zellij terminal pane sub-agent spawning

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:

  • Ctrl-p d - Split pane down
  • Ctrl-p r - Split pane right
  • Ctrl-p x - Close current pane
  • Ctrl-p h/j/k/l - Navigate between panes

The Zellij + Claude Code Advantage:

When you combine Zellij with Claude Code, you create a powerful development environment where:

  1. Visual Task Separation: Each sub-agent task runs in its own visible pane, making it easy to monitor multiple concurrent operations
  2. Persistent Monitoring: Unlike background processes that disappear into the void, Zellij panes remain visible with live output
  3. Organized Workspace: Tasks stack vertically in dedicated columns, creating a clean separation between your main Claude session and delegated work
  4. Auto-Cleanup: Panes close automatically when tasks complete, preventing workspace bloat
  5. Column-Based Layout: The system intelligently manages pane positioning—creating new columns when needed or stacking in existing rightmost columns
  6. Result Persistence: All task outputs are saved to timestamped markdown files in ~/var/ for later reference

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:

  • Single column layout: When Claude is the only pane, create a new column to the right
  • Multiple column layout: When columns already exist, navigate to the rightmost column and stack new tasks there

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:

  • The --close-on-exit flag for automatic cleanup
  • The --name parameter for identifying panes
  • The --direction right for positioning
  • A simple bash one-liner that creates output and exits

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:

  • Timestamp: 20251026-110000
  • Hash: a1b2c3d4 (from md5 of task description)
  • Result file: ~/var/task-20251026-110000-a1b2c3d4.md

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:

  1. Reads system CPU statistics using appropriate tools
  2. Analyzes trends over the requested time period
  3. Generates visualizations or summaries
  4. Formats results as structured markdown
  5. Writes the complete report to the result file

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:

  1. Pane opens showing task progress
  2. Sub-agent searches all source files
  3. Parses TODO comments, extracts context
  4. Categorizes by priority (HIGH/MEDIUM/LOW) and module
  5. Generates organized markdown report
  6. Pane closes after 3 seconds

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:

  • Monitors pane shows "Running npm audit..."
  • Sub-agent runs security checks
  • Analyzes licenses against project policy
  • Generates compliance report
  • Results saved to timestamped file

Example 3: Performance Benchmarking

Command:

/zellij-agent Run performance benchmarks on the API endpoints and compare with last week's baseline
        

Multi-step process:

  • Sub-agent loads benchmark suite
  • Executes tests against endpoints
  • Retrieves historical data
  • Generates comparison charts
  • Creates detailed performance report

Example 4: Documentation Generation

Command:

/zellij-agent Generate API documentation from TypeScript interfaces in src/types/
        

Automated workflow:

  • Scans TypeScript files
  • Extracts interface definitions
  • Generates markdown documentation
  • Includes usage examples
  • Outputs to structured document

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

  1. Descriptive Task Names: Use clear, specific task descriptions for better result file organization
  2. Check Result Files: Review ~/var/ regularly for completed task outputs
  3. Clean Up: Periodically archive or delete old result files
  4. Workspace Organization: Close completed Zellij panes to maintain clean workspace
  5. Timeout Awareness: Tasks timeout after 5 minutes; for longer operations, consider breaking into subtasks

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:

  • Visualizes AI work through dedicated monitoring panes
  • Organizes concurrent tasks with intelligent pane positioning
  • Persists results in structured, searchable markdown files
  • Auto-cleans workspaces to prevent clutter
  • Scales to multiple tasks running simultaneously

This is just one example of what's possible. The same principles can be extended to:

  • Integration with other terminal multiplexers (tmux, screen)
  • Connection to external services via MCP servers
  • Workflow automation through hooks
  • Custom agent types with specialized capabilities
  • Integration with CI/CD pipelines

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?

  1. Install Zellij: curl -L https://github.com/zellij-org/zellij/releases/latest/download/zellij-x86_64-unknown-linux-musl.tar.gz | tar xz
  2. Clone the dotfiles: git clone https://github.com/jreuben11/dotfiles
  3. Symlink commands: ln -s ~/dotfiles/claude/.claude/commands ~/.claude/commands
  4. Restart Claude Code
  5. Try: /zellij-agent Count files in current directory

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

Like
Reply

To view or add a comment, sign in

More articles by Joshua Reuben

Others also viewed

Explore content categories