# Background Tasks Sidebar (Hybrid Mode)

**Status:** Design Complete | **Priority:** High | **Estimated Effort:** 2-3 days

## Problem Statement

The current "orchestrator" approach for background tasks has several issues:

1. **Complex and unreliable** - Uses LLM-based intent classification + fire-and-forget Promises
2. **No persistence** - Tasks lost on gateway restart
3. **No visibility** - Users can't see what's running or completed
4. **Duplicate system** - We already have `sessions_spawn` (subagents) that solves the hard problems

## Solution: Hybrid Sidebar Mode

Repurpose the existing sidebar (currently used for tool output) to show a **tabbed interface**:

- **Tool Output** (existing) - Full output from clicked tool cards
- **Background Tasks** (new) - Live view of subagent tasks with progress/status

## Why This Works

| Feature           | Orchestrator (Current)     | Subagent + Sidebar (Proposed)      |
| ----------------- | -------------------------- | ---------------------------------- |
| Persistence       | ❌ Fire-and-forget Promise | ✅ Session-based with history      |
| Progress tracking | ❌ None                    | ✅ Built into session metadata     |
| UI visibility     | ❌ Invisible               | ✅ Sidebar panel with live updates |
| "Soft insertion"  | ❌ Just sends message      | ✅ Contextual task completion      |
| Complexity        | ❌ High (new subsystem)    | ✅ Low (uses existing infra)       |

## Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                     Chat Interface                          │
├──────────────────────────┬──────────────────────────────────┤
│                          │  📋 Sidebar (Hybrid Mode)        │
│  User: "Analyze the      │  ┌────────────────────────────┐  │
│  codebase structure"     │  │ [Tool Output | Tasks ▼]    │  │
│                          │  ├────────────────────────────┤  │
│  → Spawn subagent        │  │ 🔍 Code Analysis            │  │
│  → Auto-open sidebar     │  │ ⏳ Running · 2m elapsed      │  │
│  → Show in Tasks tab     │  │ [View] [Kill]               │  │
│                          │  │                             │  │
│  (keep chatting...)      │  │ ✅ Documentation Update     │  │
│                          │  │ Complete · 5m ago           │  │
│                          │  │ [View Results]              │  │
│                          │  └────────────────────────────┘  │
└──────────────────────────┴──────────────────────────────────┘
```

## Implementation Plan

### Phase 1: Remove Orchestrator (Gateway)

**Files to modify/delete:**

1. **Delete:** `src/orchestrator/router.ts` and `src/orchestrator/router.test.ts`
   - Remove `IntentRouter` class entirely
   - Delete keyword-based classification logic

2. **Delete:** `src/orchestrator/janitor.ts` (if not used elsewhere)
   - Check if nightly reset/distillation is used by cron

3. **Modify:** `src/auto-reply/reply/dispatch-from-config.ts`
   - Remove `IntentRouter` import
   - Remove orchestrator classification block (~60 lines)
   - Remove `isLongRunning` check and background handoff
   - Keep the normal flow - subagents work via `sessions_spawn`

4. **Modify:** `src/config/types.sophiaclaw.ts`
   - Remove `orchestrator` config section:

   ```typescript
   // DELETE THIS:
   orchestrator?: {
     enabled?: boolean;
     classifierModel?: string;
     conversationalModel?: string;
     longRunningModel?: string;
   };
   ```

5. **Modify:** `src/config/zod-schema.ts` and `src/config/schema.help.ts`
   - Remove orchestrator schema definitions

### Phase 2: Enhance Sidebar (UI)

**New/Modified Files:**

1. **Create:** `ui/src/ui/views/task-panel.ts`
   - New component for task list rendering
   - Shows subagents with status indicators

2. **Modify:** `ui/src/ui/views/chat.ts`
   - Add tab switcher in sidebar header
   - Pass task data to sidebar

3. **Modify:** `ui/src/ui/app.ts`
   - Add state for active sidebar tab (`sidebarTab: 'tool' | 'tasks'`)
   - Add polling for subagent sessions
   - Auto-open sidebar on subagent spawn

4. **Modify:** `ui/src/ui/app-render.ts`
   - Pass task list to chat component

### Data Flow

```typescript
// 1. User spawns subagent (existing flow)
sessions_spawn({ task: "Analyze codebase", mode: "run", label: "Code Analysis" });

// 2. UI detects new subagent (new)
// Poll sessions_list({ kinds: ["subagent"], activeMinutes: 60 })

// 3. Auto-open sidebar to Tasks tab (new)
sidebarTab = "tasks";
sidebarOpen = true;

// 4. Render task list (new component)
// Shows: label, status, elapsed time, actions

// 5. Task completes → show completion state
// User can click "View Results" to open that session
```

## UI Specification

### Task List Item

```
┌─────────────────────────────────────────┐
│ 🔍 Code Analysis                    [×] │  ← Label + close
│ ⏳ Running · 2m 34s                [Kill] │  ← Status + elapsed + action
│ Progress: ▓▓▓▓▓▓▓░░░ 7/10 files         │  ← Optional progress bar
└─────────────────────────────────────────┘
```

**Status icons:**

- `⏳` Running (spinning animation)
- `✅` Complete
- `❌` Failed
- `🕐` Pending

**Actions:**

- **View** - Open subagent session in new tab
- **Kill** - Send terminate signal
- **Dismiss** - Remove from list (keep session)

### Tab Switcher (in sidebar header)

```
┌────────────────────────────────────┐
│ [←] [Tool Output | Tasks (3)]  [×] │
└────────────────────────────────────┘
```

- Click tab to switch view
- Badge shows count of active tasks
- Arrow collapses sidebar

## API Requirements

**Existing - No Changes Needed:**

- `sessions_list` - Already returns subagent sessions
- `sessions_spawn` - Already creates background tasks
- `subagents` tool - Already provides kill/steer

**Optional Enhancement (Future):**

- Add `label` field to `sessions_spawn` for better display names
- Add `progress` field to session metadata for progress bars

## Configuration

**Remove from config:**

```yaml
# DELETE THIS SECTION
orchestrator:
  enabled: true
  classifierModel: kimi-coding/k2p5
  conversationalModel: ...
  longRunningModel: ...
```

**No new config needed** - uses existing subagent system.

## Migration Path

1. **Delete orchestrator code** (Phase 1)
2. **Users already using `sessions_spawn`** - No change needed, just better UI
3. **Users relying on orchestrator** - Will need to explicitly use `sessions_spawn` or `/spawn` command

## Testing Checklist

- [ ] Subagent spawns appear in sidebar automatically
- [ ] Tab switcher works (Tool Output ↔ Tasks)
- [ ] Task status updates live (running → complete)
- [ ] "View" opens subagent session
- [ ] "Kill" terminates subagent
- [ ] Sidebar resizes properly with task list
- [ ] Empty state shows helpful message
- [ ] Mobile/narrow view handles sidebar gracefully

## Future Enhancements

1. **Progress API** - Allow subagents to report % complete
2. **Task Categories** - Group by type (code review, research, etc.)
3. **Notifications** - Toast when task completes while sidebar closed
4. **History** - Completed tasks persist for 24h
5. **Quick Actions** - Spawn common tasks from sidebar

## Related Documentation

- `docs/tools/subagents.md` - How subagents work
- `docs/gateway/background-process.md` - Exec/process backgrounding
- `ui/src/ui/views/sessions.ts` - Session list implementation (reference)
