feat: session refactor (#30)
This commit is contained in:
@@ -0,0 +1,249 @@
|
||||
# Agent Orchestration + Session UI Data Flow
|
||||
|
||||
This document describes how a task session is created, how agentctl/agent lifecycle events flow through the backend, and how the session details page consumes those events.
|
||||
|
||||
## Overview (Actors)
|
||||
|
||||
- **Client UI**: Next.js app with session details page and panels (chat, terminal, git, files).
|
||||
- **Backend**: Orchestrator + WebSocket gateway + task/session store.
|
||||
- **agentctl**: Sidecar HTTP/WS server inside agent container (or standalone process) that manages the agent subprocess and exposes ACP + workspace streams.
|
||||
- **Agent**: ACP-speaking process (JSON-RPC over stdin/stdout) that performs work.
|
||||
|
||||
## Orchestration Flow (Task Session Creation)
|
||||
|
||||
```
|
||||
Client UI
|
||||
| HTTP: POST /api/v1/tasks { start_agent: true, agent_profile_id }
|
||||
v
|
||||
Backend Task Service
|
||||
| create task + first session
|
||||
| start agentctl orchestration
|
||||
| create task_session (STARTING)
|
||||
| launch agentctl (container or standalone)
|
||||
| wait for /health
|
||||
| POST /api/v1/start
|
||||
| POST /api/v1/acp/call initialize
|
||||
| POST /api/v1/acp/call session/new
|
||||
| POST /api/v1/acp/call session/prompt
|
||||
v
|
||||
agentctl
|
||||
| spawns agent process
|
||||
| streams ACP updates + workspace streams
|
||||
v
|
||||
Agent
|
||||
| ACP notifications (session/update)
|
||||
v
|
||||
agentctl -> Backend
|
||||
| ACP update stream -> backend
|
||||
| backend updates task_session state + messages
|
||||
| backend publishes WS notifications
|
||||
v
|
||||
Client UI
|
||||
| session.subscribe
|
||||
| receive session-scoped events
|
||||
```
|
||||
|
||||
## Backend Event Routing (Session Scoped)
|
||||
|
||||
Events are now routed primarily by **session_id**. The WS gateway maintains **session subscriber lists**. It broadcasts session events only to clients subscribed to that session.
|
||||
|
||||
```
|
||||
agentctl WS /api/v1/acp/stream
|
||||
-> backend ACP handler
|
||||
-> task_session state update
|
||||
-> message persisted
|
||||
-> WS broadcast: session.channel
|
||||
|
||||
agentctl WS /api/v1/workspace/git-status/stream
|
||||
-> backend git-status handler
|
||||
-> attach to session
|
||||
-> WS broadcast: session.channel
|
||||
|
||||
agentctl WS /api/v1/output/stream
|
||||
-> backend shell handler
|
||||
-> session resolve (session_id -> task_id)
|
||||
-> WS broadcast: session.channel
|
||||
```
|
||||
|
||||
Session notifications:
|
||||
- `session.agentctl_starting`
|
||||
- `session.agentctl_ready`
|
||||
- `session.agentctl_error`
|
||||
- `session.state_changed`
|
||||
- `session.message.added`, `session.message.updated`
|
||||
- `session.shell.output`, `session.shell.status`
|
||||
- `session.git.status`
|
||||
- `session.workspace.file.changes`
|
||||
|
||||
## Frontend Session Page Flow (SSR + WS)
|
||||
|
||||
```
|
||||
Server (SSR)
|
||||
- fetch session by id
|
||||
- fetch parent task + workspace context
|
||||
- hydrate store (tasks, sessions, repos, agent profiles)
|
||||
|
||||
Client (Hydrated)
|
||||
- read sessionId from URL (/s/:sessionId)
|
||||
- set activeSessionId in store
|
||||
- subscribe to session events
|
||||
- child components read from store + hooks
|
||||
```
|
||||
|
||||
### Component Subscriptions
|
||||
|
||||
Each component subscribes to the data it needs via hooks. The **WS client deduplicates subscriptions** so multiple components can safely request the same channel.
|
||||
|
||||
```
|
||||
TaskSessionPage (/s/:sessionId)
|
||||
-> useSession(sessionId)
|
||||
-> subscribe: session.{sessionId}
|
||||
|
||||
TaskChatPanel
|
||||
-> useSessionMessages(sessionId)
|
||||
-> subscribe: session.{sessionId}
|
||||
|
||||
ShellTerminal
|
||||
-> useSessionAgentctl(sessionId)
|
||||
-> subscribe: session.{sessionId}
|
||||
-> useShellOutput(sessionId)
|
||||
-> subscribe: session.{sessionId}
|
||||
|
||||
TaskChangesPanel (Git)
|
||||
-> useSessionGitStatus(sessionId)
|
||||
-> subscribe: session.{sessionId}
|
||||
|
||||
TaskFilesPanel
|
||||
-> useSessionAgentctl(sessionId)
|
||||
-> wait for readiness
|
||||
-> useSessionWorktrees(sessionId)
|
||||
-> subscribe: session.{sessionId}
|
||||
```
|
||||
|
||||
## Event + State Flow Diagram
|
||||
|
||||
```
|
||||
Agent
|
||||
| ACP session/update
|
||||
v
|
||||
agentctl
|
||||
| WS /api/v1/acp/stream
|
||||
v
|
||||
Backend ACP handler
|
||||
| update session state/messages
|
||||
| emit session WS events
|
||||
v
|
||||
WS Gateway (session subscribers)
|
||||
| broadcast to session.{sessionId}
|
||||
v
|
||||
WebSocket Client (browser)
|
||||
| dedupe subscription
|
||||
| route to store slice
|
||||
v
|
||||
Zustand Store
|
||||
| sessions, messages, shell, git, worktrees
|
||||
v
|
||||
Session UI Panels
|
||||
| hook selectors
|
||||
| render
|
||||
```
|
||||
|
||||
## Concrete Example: New Session -> Message Appears In Chat
|
||||
|
||||
Scenario: user starts a task session and the agent replies with a completion message that appears in the chat panel.
|
||||
|
||||
### Sequence (Calls + Events)
|
||||
|
||||
1) Client -> Backend (HTTP request)
|
||||
```
|
||||
POST /api/v1/tasks
|
||||
body:
|
||||
title: "Example task"
|
||||
workspace_id: "workspace-1"
|
||||
repository_id: "repo-9"
|
||||
agent_profile_id: "profile-abc"
|
||||
start_agent: true
|
||||
```
|
||||
|
||||
2) Backend (internal)
|
||||
- creates task
|
||||
- creates first task session
|
||||
- starts agentctl orchestration for the new session
|
||||
- returns session_id in the HTTP response
|
||||
|
||||
3) Backend -> agentctl (HTTP)
|
||||
- `POST /api/v1/start`
|
||||
- `POST /api/v1/acp/call` initialize
|
||||
- `POST /api/v1/acp/call` session/new
|
||||
- `POST /api/v1/acp/call` session/prompt
|
||||
|
||||
4) Backend -> Client (WS notification)
|
||||
```
|
||||
action: session.agentctl_starting
|
||||
payload:
|
||||
task_id: "task-123"
|
||||
session_id: "session-789"
|
||||
```
|
||||
|
||||
5) Client subscribes to session
|
||||
```
|
||||
action: session.subscribe
|
||||
payload:
|
||||
session_id: "session-789"
|
||||
```
|
||||
|
||||
6) agentctl -> Backend (ACP notification)
|
||||
```
|
||||
jsonrpc: "2.0"
|
||||
method: "session/update"
|
||||
params:
|
||||
type: "content"
|
||||
data:
|
||||
text: "Working on your request..."
|
||||
session_id: "session-789"
|
||||
```
|
||||
|
||||
7) Backend -> Client (WS notification)
|
||||
```
|
||||
action: session.message.added
|
||||
payload:
|
||||
session_id: "session-789"
|
||||
message:
|
||||
id: "msg-1"
|
||||
author_type: "agent"
|
||||
content: "Working on your request..."
|
||||
```
|
||||
|
||||
8) Client store update (message handler)
|
||||
```
|
||||
messages.bySession["session-789"] += message
|
||||
```
|
||||
|
||||
9) Chat panel render
|
||||
```
|
||||
TaskChatPanel -> useSessionMessages("session-789") -> messages list -> render
|
||||
```
|
||||
|
||||
### Full Event List (Typical Session Start)
|
||||
|
||||
- HTTP request: `POST /api/v1/tasks` with `start_agent: true`
|
||||
- WS notification: `session.agentctl_starting`
|
||||
- WS request: `session.subscribe`
|
||||
- WS notification: `session.agentctl_ready`
|
||||
- ACP notifications from agent:
|
||||
- `session/update` (content/toolCall/complete/error)
|
||||
- WS notifications:
|
||||
- `session.message.added`
|
||||
- `session.message.updated`
|
||||
- `session.state_changed`
|
||||
- `session.shell.status` / `session.shell.output` (if shell active)
|
||||
- `session.git.status` (if git watcher active)
|
||||
- `session.workspace.file.changes` (if watcher active)
|
||||
|
||||
## Notes / Guardrails
|
||||
|
||||
- Session is the source of truth; task id is derived from session when needed.
|
||||
- No fallback to “active task” or “first message” for session ownership.
|
||||
- Agentctl readiness is explicit; panels that require a live agent should wait for `agentctl_ready`.
|
||||
- Store slices are keyed by session id (messages, shell output, git status, worktrees).
|
||||
- WS subscriptions are **session-scoped** and **deduplicated** at the client level.
|
||||
@@ -0,0 +1,104 @@
|
||||
# Agent Permission Requests
|
||||
|
||||
This document describes how permission requests flow between the agent, backend, and frontend.
|
||||
|
||||
## Overview
|
||||
Some agents (e.g., Auggie) require user approval for sensitive tool actions (run command, write file, etc.). The agentctl sidecar streams permission requests to the backend, which then broadcasts them to the UI. The user responds via the UI, and the backend forwards the response back to agentctl.
|
||||
|
||||
## High-Level Flow
|
||||
```
|
||||
Agent (ACP/CLI)
|
||||
|
|
||||
| permission_request (tool call needs approval)
|
||||
v
|
||||
agentctl (permission stream)
|
||||
|
|
||||
| WS /api/v1/acp/permissions/stream
|
||||
v
|
||||
Backend (lifecycle manager)
|
||||
|
|
||||
| events.ACPMessage (type=permission_request)
|
||||
v
|
||||
Backend (WS gateway)
|
||||
|
|
||||
| session.permission.requested (WS notification)
|
||||
v
|
||||
Frontend (CommandApprovalDialog / tool-call UI)
|
||||
|
|
||||
| permission.respond (WS request)
|
||||
v
|
||||
Backend (orchestrator)
|
||||
|
|
||||
| RespondToPermissionBySessionID
|
||||
v
|
||||
agentctl (POST /api/v1/acp/permissions/respond)
|
||||
|
|
||||
v
|
||||
Agent continues (approved/rejected)
|
||||
```
|
||||
|
||||
## Backend Components
|
||||
- **agentctl permission stream**
|
||||
- agentctl exposes `GET /api/v1/acp/permissions/stream`.
|
||||
- Streams `PermissionNotification` from the agent process.
|
||||
- **lifecycle StreamManager**
|
||||
- Connects to the permission stream.
|
||||
- Publishes `events.ACPMessage` with `type=permission_request`.
|
||||
- **orchestrator watcher**
|
||||
- Parses ACP messages and forwards permission requests to WS clients.
|
||||
- **gateway websocket**
|
||||
- Broadcasts `session.permission.requested` to session subscribers.
|
||||
- **orchestrator handlers**
|
||||
- Handles `permission.respond` and forwards to agentctl.
|
||||
|
||||
## Frontend Components
|
||||
- **CommandApprovalDialog**
|
||||
- Shows permission requests not tied to a visible tool call.
|
||||
- **ToolCallMessage inline actions**
|
||||
- Shows approve/reject inline for tool call messages.
|
||||
- **WebSocket client**
|
||||
- Subscribes to `session.permission.requested`.
|
||||
- Sends `permission.respond` with `{ session_id, pending_id, option_id, cancelled }`.
|
||||
|
||||
## Message Shapes
|
||||
|
||||
### Permission Requested (WS notification)
|
||||
```json
|
||||
{
|
||||
"type": "notification",
|
||||
"action": "session.permission.requested",
|
||||
"payload": {
|
||||
"pending_id": "perm-123",
|
||||
"session_id": "session-abc",
|
||||
"task_id": "task-xyz",
|
||||
"tool_call_id": "tool-456",
|
||||
"title": "Command Execution Approval",
|
||||
"options": [
|
||||
{ "option_id": "allow_once", "name": "Allow once", "kind": "allow_once" },
|
||||
{ "option_id": "reject_once", "name": "Reject", "kind": "reject_once" }
|
||||
],
|
||||
"action_type": "command",
|
||||
"action_details": { "command": "rm -rf .", "cwd": "/workspace" },
|
||||
"created_at": "2026-01-18T00:00:00Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Permission Respond (WS request)
|
||||
```json
|
||||
{
|
||||
"type": "request",
|
||||
"action": "permission.respond",
|
||||
"payload": {
|
||||
"session_id": "session-abc",
|
||||
"pending_id": "perm-123",
|
||||
"option_id": "allow_once",
|
||||
"cancelled": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Notes
|
||||
- Permissions are scoped to a **session**, not a task.
|
||||
- If the session has no active UI, the pending permission is still stored on the backend and sent when the client subscribes.
|
||||
- The agent can define different tools that require permission via its registry config.
|
||||
@@ -0,0 +1,127 @@
|
||||
# Agentctl session lifecycle (Kandev)
|
||||
|
||||
This document explains how **agentctl** fits into the Kandev execution flow, what “ready” means, and which parts of the system depend on agentctl being up.
|
||||
|
||||
## What agentctl is
|
||||
|
||||
`agentctl` is a sidecar process that runs inside each agent container (or standalone runtime). It provides:
|
||||
|
||||
- **HTTP API** for lifecycle operations (`/health`, `/api/v1/start`, `/api/v1/stop`, etc.)
|
||||
- **ACP bridge** (stdin/stdout JSON‑RPC) to the agent process (Auggie/Codex/etc.)
|
||||
- **WebSockets** for streaming ACP updates and agent output
|
||||
- **Shell access** to the workspace (terminal output + input)
|
||||
|
||||
It is the backend’s *control plane* for an agent execution.
|
||||
|
||||
## High‑level flow (runtime‑agnostic)
|
||||
|
||||
```
|
||||
User action (start task)
|
||||
|
|
||||
v
|
||||
Kandev orchestrator
|
||||
|
|
||||
| 1) Create task session in DB
|
||||
| 2) Launch agent runtime (Docker or standalone)
|
||||
v
|
||||
agentctl process starts
|
||||
|
|
||||
| 3) HTTP server comes up (health + control APIs)
|
||||
v
|
||||
Backend waits for agentctl readiness
|
||||
|
|
||||
| 4) agentctl ready => shell/workspace access available
|
||||
v
|
||||
ACP session initialization
|
||||
|
|
||||
| 5) initialize -> session/new or session/load
|
||||
| 6) prompt is sent
|
||||
v
|
||||
Agent runs, ACP updates stream
|
||||
|
|
||||
| 7) session/update notifications => WS to client
|
||||
v
|
||||
Task session state transitions
|
||||
```
|
||||
|
||||
## “Ready” concepts (important distinction)
|
||||
|
||||
There are **two different “ready” moments**:
|
||||
|
||||
1) **agentctl ready**
|
||||
- Meaning: agentctl HTTP server is healthy and can accept requests.
|
||||
- Practical impact: shell/workspace endpoints become usable.
|
||||
- Source: `lifecycle.Manager.waitForAgentctlReady`.
|
||||
- Today: only logged; **not emitted as a WS event**.
|
||||
|
||||
2) **agent ready** (prompt completed)
|
||||
- Meaning: agent finished the current prompt and is idle/ready for follow‑up.
|
||||
- Source: `events.AgentReady` (after prompt completion).
|
||||
- Today: internal event for orchestrator state transitions.
|
||||
|
||||
The frontend should not rely on “agent ready” when it needs shell access; shell access depends on agentctl readiness instead.
|
||||
|
||||
## Current backend signals
|
||||
|
||||
- **agentctl readiness**
|
||||
- `agentctl is ready` (agentctl client log)
|
||||
- `agentctl ready - shell/workspace access available` (lifecycle manager log)
|
||||
|
||||
- **agent ready** (post‑prompt)
|
||||
- `events.AgentReady` internal event (used by orchestrator state transitions)
|
||||
|
||||
There is **no WS event** that tells the client “agentctl is ready.”
|
||||
|
||||
## Where shell streaming depends on agentctl
|
||||
|
||||
- Client calls `shell.subscribe` (WS request)
|
||||
- Backend checks:
|
||||
- agent execution exists for the task
|
||||
- agentctl is connected
|
||||
- Backend starts a streaming loop that relays agentctl shell output as `shell.output` WS notifications
|
||||
|
||||
If agentctl isn’t ready yet, `shell.subscribe` fails and the frontend currently retries.
|
||||
|
||||
## Suggested improvement (optional)
|
||||
|
||||
Introduce a WS notification like:
|
||||
|
||||
```
|
||||
{ "action": "task.session.agentctl_ready", "payload": { "task_id": "...", "task_session_id": "..." } }
|
||||
```
|
||||
|
||||
So the client can subscribe once and only request shell after it receives readiness.
|
||||
|
||||
## End‑to‑end diagram (detailed)
|
||||
|
||||
```
|
||||
Client Backend (Kandev) agentctl Agent
|
||||
| | | |
|
||||
| orchestrator.start | | |
|
||||
|------------------------------->| | |
|
||||
| | create task session | |
|
||||
| | launch runtime | |
|
||||
| |---------------------------->| process starts |
|
||||
| | | HTTP server up |
|
||||
| | waitForAgentctlReady | |
|
||||
| |---------------------------->| /health |
|
||||
| |<----------------------------| 200 OK |
|
||||
| | (agentctl ready) | |
|
||||
| | ACP initialize | |
|
||||
| |---------------------------->| initialize |
|
||||
| | ACP session/new | |
|
||||
| |---------------------------->| session/new |
|
||||
| | ACP prompt | |
|
||||
| |---------------------------->| session/prompt |
|
||||
| | |--------------------->|
|
||||
| | | agent runs |
|
||||
| | WS stream | |
|
||||
|<-------------------------------| (session/update notifications) |
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
- `apps/backend/internal/agent/lifecycle/manager.go` (waitForAgentctlReady)
|
||||
- `apps/backend/internal/agentctl/client/client.go` (WaitForReady)
|
||||
- `apps/backend/internal/agent/handlers/shell_handlers.go` (shell.subscribe)
|
||||
- `apps/backend/internal/events/types.go` (`AgentReady`)
|
||||
@@ -0,0 +1,124 @@
|
||||
# Relationship Events LLD
|
||||
|
||||
This document defines backend-driven state propagation and how WS notifications mirror those changes to the UI. Clients do **not** emit these events.
|
||||
|
||||
## Core Rules
|
||||
|
||||
1) **Session state changes drive task state changes**.
|
||||
2) **Agentctl lifecycle changes drive session state changes**, which then drive task state changes.
|
||||
3) **Task state changes may move columns**, but only between **In Progress** and **Review** for now.
|
||||
|
||||
All state propagation happens **server-side** on internal events. WebSocket events are outbound mirrors for UI synchronization.
|
||||
|
||||
---
|
||||
|
||||
## 1) Session State -> Task State
|
||||
|
||||
**Trigger (backend only)**
|
||||
- `events.TaskSessionStateChanged` (internal event bus)
|
||||
|
||||
**Flow**
|
||||
1. Resolve `task_id` from `session_id`.
|
||||
2. Map `TaskSessionState -> TaskState` (table below).
|
||||
3. If task state changes, call `taskSvc.UpdateTaskState(taskID, newState)`.
|
||||
4. Emit `events.TaskStateChanged` and WS `task.state_changed`.
|
||||
5. Emit WS `session.state_changed` for clients.
|
||||
|
||||
**Mapping Table**
|
||||
|
||||
| TaskSessionState | TaskState | Board Column |
|
||||
|-------------------|---------------|-----------------------|
|
||||
| CREATED | SCHEDULING | In Progress (if any) |
|
||||
| STARTING | SCHEDULING | In Progress (if any) |
|
||||
| RUNNING | IN_PROGRESS | In Progress |
|
||||
| WAITING_FOR_INPUT | REVIEW | Review |
|
||||
| COMPLETED | REVIEW | Review |
|
||||
| ERROR | ERROR | (no auto-move) |
|
||||
| CANCELLED | CANCELLED | (no auto-move) |
|
||||
|
||||
Notes:
|
||||
- `WAITING_FOR_INPUT -> REVIEW` and `COMPLETED -> REVIEW` are the default paths. If a board has no Review column, keep task in its current column.
|
||||
- If the mapped task state equals current task state, do nothing.
|
||||
|
||||
---
|
||||
|
||||
## 2) Agentctl State -> Session State -> Task State
|
||||
|
||||
**Triggers (backend only)**
|
||||
- `events.AgentctlStarting`
|
||||
- `events.AgentctlReady`
|
||||
- `events.AgentctlError`
|
||||
|
||||
**Agentctl -> Session Mapping**
|
||||
|
||||
| Agentctl Event | Session State |
|
||||
|--------------------------|---------------|
|
||||
| AgentctlStarting | STARTING |
|
||||
| AgentctlReady | RUNNING |
|
||||
| AgentctlError | FAILED |
|
||||
|
||||
**Flow**
|
||||
1. On Agentctl event, update session state in DB.
|
||||
2. Emit `events.TaskSessionStateChanged` (which triggers session->task mapping).
|
||||
3. Emit WS `session.agentctl_*` and `session.state_changed`.
|
||||
|
||||
---
|
||||
|
||||
## 3) Task State -> Column Move
|
||||
|
||||
**Trigger (backend only)**
|
||||
- `events.TaskStateChanged`
|
||||
|
||||
**Policy (for now)**
|
||||
- Only move tasks **between In Progress and Review**.
|
||||
- Do not auto-move for other states.
|
||||
|
||||
**Flow**
|
||||
1. When task state changes:
|
||||
- If new state is `IN_PROGRESS`, move to column mapped to In Progress (if exists).
|
||||
- If new state is `REVIEW`, move to column mapped to Review (if exists).
|
||||
2. If column lookup fails or column already matches, do nothing.
|
||||
3. Emit `events.TaskUpdated` and WS `task.updated` with new `column_id`.
|
||||
|
||||
---
|
||||
|
||||
## WebSocket Notifications (Outbound Only)
|
||||
|
||||
- `session.state_changed`
|
||||
- `session.agentctl_starting`
|
||||
- `session.agentctl_ready`
|
||||
- `session.agentctl_error`
|
||||
- `task.state_changed`
|
||||
- `task.updated`
|
||||
|
||||
Clients should treat these as **read-only state mirrors**.
|
||||
|
||||
---
|
||||
|
||||
## E2E Flow (Client-Initiated)
|
||||
|
||||
| Edge Trigger (Client) | Backend Action | Internal Event(s) | WS Notification(s) |
|
||||
|----------------------------------------------|---------------------------------------------------|--------------------------------------|-------------------------------------------------|
|
||||
| `POST /api/v1/tasks` (start_agent: true) | Create task + create session + start agentctl | task.created, task_session.created | task.created, session.agentctl_starting |
|
||||
| `POST /api/v1/tasks` (start_agent: false) | Create task + create session (idle) | task.created, task_session.created | task.created |
|
||||
| `message.add` (session message) | Persist message + prompt agent via ACP | message.added | session.message.added |
|
||||
| `task.state` (manual update) | Update task state | task.state_changed | task.state_changed, task.updated (column move) |
|
||||
| `task.session.resume` | Resume session + start agentctl | task_session.state_changed | session.agentctl_starting, session.state_changed |
|
||||
|
||||
Notes:
|
||||
- Column move only occurs for `IN_PROGRESS` / `REVIEW` transitions.
|
||||
|
||||
---
|
||||
|
||||
## E2E Flow (Agent / agentctl-Initiated)
|
||||
|
||||
| Edge Trigger (Agent/agentctl) | Backend Action | Internal Event(s) | WS Notification(s) |
|
||||
|----------------------------------------------|---------------------------------------------------|--------------------------------------|-------------------------------------------------|
|
||||
| Agentctl starting | Update session state → STARTING | task_session.state_changed | session.agentctl_starting, session.state_changed |
|
||||
| Agentctl ready | Update session state → RUNNING | task_session.state_changed | session.agentctl_ready, session.state_changed |
|
||||
| Agentctl error | Update session state → ERROR | task_session.state_changed | session.agentctl_error, session.state_changed |
|
||||
| ACP content/progress | Create/append message chunks | message.added / message.updated | session.message.added / session.message.updated |
|
||||
| ACP input_required | Create message (requests_input=true) | message.added | session.message.added + session.waiting_for_input |
|
||||
| Git status stream update | Update session git status | git.status.updated | session.git.status |
|
||||
| Workspace file change stream | Update session file activity | workspace.file.changed | session.workspace.file.changes |
|
||||
| Shell output stream | Append shell output | shell.output | session.shell.output |
|
||||
@@ -0,0 +1,174 @@
|
||||
# Task Session Page Data Flow (SSR + WS + Store)
|
||||
|
||||
This document maps the current data flow for `/task/:id/:sessionId` and highlights which components/hooks depend on which data. It also calls out places where hooks could be made more granular or shared.
|
||||
|
||||
## SSR Entry Point
|
||||
|
||||
Route: `apps/web/app/task/[id]/[sessionId]/page.tsx`
|
||||
|
||||
Server fetches:
|
||||
- `fetchTask(taskId)`
|
||||
- `fetchBoardSnapshot(task.board_id)`
|
||||
- `listAgents()`
|
||||
- `listRepositories(task.workspace_id)`
|
||||
- `listTaskSessions(task.id)` for each task in board
|
||||
- `listTaskSessionMessages(sessionId)` (best-effort)
|
||||
|
||||
Hydration:
|
||||
- `snapshotToState(snapshot)` → kanban columns + tasks
|
||||
- `taskToState(task, sessionId, messages?)` → `tasks.activeTaskId`, `tasks.activeSessionId`, `messages.bySession[sessionId]`
|
||||
- Repositories + agent profiles are merged into store
|
||||
- Render `<StateHydrator initialState={...} />` and `<TaskPageClient ... />`
|
||||
|
||||
## Client Composition
|
||||
|
||||
```
|
||||
TaskSessionPage (SSR)
|
||||
└─ TaskPageClient
|
||||
├─ TaskTopBar
|
||||
└─ TaskLayout
|
||||
├─ TaskSessionSidebar (left)
|
||||
├─ TaskCenterPanel (chat/changes/notes)
|
||||
└─ TaskRightPanel (files + terminal)
|
||||
```
|
||||
|
||||
## Active Selection (Store)
|
||||
|
||||
Store slice: `tasks.activeTaskId`, `tasks.activeSessionId`
|
||||
- Set on initial mount by `TaskPageClient` from URL + SSR task.
|
||||
- Updated when selecting a task/session in sidebar.
|
||||
|
||||
## WebSocket Data Flow
|
||||
|
||||
WebSocket client:
|
||||
- `apps/web/lib/ws/client.ts` with deduplicated subscriptions.
|
||||
- Components call `client.subscribe(taskId)`; dedup ensures single WS subscription.
|
||||
- On reconnect, re-subscribes to active task channels.
|
||||
|
||||
Handlers (global router):
|
||||
- `message.added` / `message.updated` → `messages.bySession[sessionId]`
|
||||
- `task_session.state_changed` → `taskSessionStatesByTaskId` + `taskSessions.items`
|
||||
- `git.status` → `gitStatus` (keyed by task)
|
||||
- `shell.output` → `shell.outputs[taskId]`
|
||||
|
||||
## Component Data Dependencies
|
||||
|
||||
### TaskPageClient (`apps/web/app/task/[id]/page-client.tsx`)
|
||||
- Props: `task`, `sessionId`, `initialSessionsByTask`, `initialRepositories`, `initialAgentProfiles`
|
||||
- Store:
|
||||
- `tasks.activeTaskId`, `tasks.activeSessionId` via `setActiveSession`
|
||||
- `kanban.tasks`, `kanban.columns`, `workspaces.items`
|
||||
- `agentProfiles.items`
|
||||
- Hooks:
|
||||
- `useSessionResumption(task?.id, sessionId)`
|
||||
- `useTaskAgent(task)` (agent state, task.execution polling)
|
||||
- `useRepositories(workspaceId)` (fallback to SSR data)
|
||||
- WS:
|
||||
- Subscribes to all tasks in board (deduped)
|
||||
- Listens for `task_session.state_changed` to refresh `sessionsByTask`
|
||||
- Responsibilities:
|
||||
- URL sync via `history.replaceState`
|
||||
- Task selection triggers `fetchTask` + `listTaskSessions`
|
||||
|
||||
### TaskSessionSidebar (`apps/web/components/task/task-session-sidebar.tsx`)
|
||||
- Store:
|
||||
- `tasks.activeTaskId`
|
||||
- `tasks.activeSessionId`
|
||||
- Props:
|
||||
- tasks + columns + sessionsByTask from `TaskPageClient`
|
||||
- Uses:
|
||||
- `TaskSessionSwitcher` (sessions list)
|
||||
- `TaskSwitcher` (tasks list)
|
||||
- Calls back to parent for selection and session list reload.
|
||||
|
||||
### TaskCenterPanel (`apps/web/components/task/task-center-panel.tsx`)
|
||||
- Props: `taskId`, `onSendMessage`, `selectedDiffPath`, `openFileRequest`
|
||||
- Includes:
|
||||
- `TaskChatPanel`
|
||||
- `TaskChangesPanel`
|
||||
- `FileViewerContent`
|
||||
|
||||
### TaskChatPanel (`apps/web/components/task/task-chat-panel.tsx`)
|
||||
- Store:
|
||||
- `tasks.activeSessionId` (fallback unless `sessionId` prop passed)
|
||||
- Hooks:
|
||||
- `useTaskSession(sessionId)` → taskId + session details
|
||||
- `useTaskMessages(taskId, sessionId)` → messages + meta
|
||||
- `useLazyLoadMessages(sessionId)` → pagination
|
||||
- Data:
|
||||
- Renders from `messages.bySession[sessionId]`
|
||||
|
||||
### TaskRightPanel (`apps/web/components/task/task-right-panel.tsx`)
|
||||
- Store:
|
||||
- `tasks.activeSessionId`
|
||||
- Uses:
|
||||
- `ShellTerminal taskId + activeSessionId`
|
||||
|
||||
### ShellTerminal (`apps/web/components/task/shell-terminal.tsx`)
|
||||
- Store:
|
||||
- `shell.outputs[taskId]`
|
||||
- `taskSessions.items[sessionId]?.state` or `taskSessionStatesByTaskId[taskId]`
|
||||
- WS:
|
||||
- Subscribes to shell only when session is RUNNING or WAITING_FOR_INPUT.
|
||||
|
||||
### TaskFilesPanel / TaskChangesPanel
|
||||
- Store:
|
||||
- `gitStatus` keyed by active task
|
||||
- No direct WS subscriptions.
|
||||
|
||||
## ASCII Diagram (Current)
|
||||
|
||||
```
|
||||
SSR
|
||||
┌──────────────────────────────────────────────────────────────┐
|
||||
│ /task/:id/:sessionId │
|
||||
│ fetchTask + snapshot + agents + repos + sessions + messages │
|
||||
│ StateHydrator -> store (activeTaskId + activeSessionId) │
|
||||
└──────────────────────────────────────────────────────────────┘
|
||||
|
||||
Client
|
||||
┌─────────────────────────────── TaskPageClient ──────────────────────────────┐
|
||||
│ setActiveSession(taskId, sessionId) │
|
||||
│ subscribe(board tasks) + listen task_session.state_changed │
|
||||
│ │
|
||||
│ ┌─ TaskSessionSidebar (sessions + tasks) │
|
||||
│ ├─ TaskCenterPanel │
|
||||
│ │ └─ TaskChatPanel │
|
||||
│ │ ├─ useTaskSession(sessionId) │
|
||||
│ │ ├─ useTaskMessages(taskId, sessionId) │
|
||||
│ │ └─ useLazyLoadMessages(sessionId) │
|
||||
│ └─ TaskRightPanel │
|
||||
│ └─ ShellTerminal (shell.output + session state) │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
|
||||
WS
|
||||
task.subscribe -> deduped in client
|
||||
message.added/updated -> messages.bySession
|
||||
task_session.state_changed -> taskSessions + taskSessionStatesByTaskId
|
||||
git.status -> gitStatus (task)
|
||||
shell.output -> shell.outputs[task]
|
||||
```
|
||||
|
||||
## Hooks Review (Granularity + Reuse)
|
||||
|
||||
Current hooks:
|
||||
- `useTaskMessages(taskId, sessionId)`
|
||||
- Fetches + sets loading meta + subscribes to task updates.
|
||||
- Could be split into:
|
||||
- `useSessionMessages(sessionId)` (only fetch + store)
|
||||
- `useTaskSubscription(taskId)` (subscription only)
|
||||
- `useLazyLoadMessages(sessionId)` uses store meta; OK as a focused pagination hook.
|
||||
- `useTaskSession(sessionId)` derives taskId from messages if session not in store.
|
||||
- Can be simplified once session list is guaranteed in store.
|
||||
- `useTaskAgent(task)` + `useSessionResumption(taskId, sessionId)`
|
||||
- Both access execution state. Consider a combined `useTaskExecution(taskId, sessionId)` hook.
|
||||
- `useRepositories(workspaceId)` currently handles fetch + loading; OK but could be generalized (e.g. `useListResource`).
|
||||
|
||||
Suggested split for sharing:
|
||||
- `useTaskSubscription(taskId)` → handles `client.subscribe(taskId)` only.
|
||||
- `useSessionMessages(sessionId)` → fetch + store; no taskId.
|
||||
- `useActiveSession()` selector → centralizes active session usage.
|
||||
- `useTaskGitStatus(taskId)` → pure selector + optional subscribe.
|
||||
- `useShellOutput(taskId)` → pure selector + optional subscribe.
|
||||
|
||||
This would allow panels to mix and match only what they need without pulling in extra behavior.
|
||||
@@ -0,0 +1,243 @@
|
||||
# Session Resumption LLD
|
||||
|
||||
## Goals
|
||||
- Support multiple active sessions per task.
|
||||
- Resume sessions after backend restart without relying on user navigation.
|
||||
- Distinguish resumable vs non-resumable agents (no `resume_token`).
|
||||
- Keep session state consistent across backend, agentctl, and UI.
|
||||
- Support local and remote executors.
|
||||
|
||||
## Key Assumptions
|
||||
- A session is the unit of execution; each session has at most one active agent execution.
|
||||
- Task can have multiple sessions concurrently (active or historical).
|
||||
- Agents that support session resumption provide a `resume_token` in session metadata.
|
||||
- Agents that do not support resumption cannot resume after restart.
|
||||
- Remote executors keep running across backend restarts; the backend must reconnect.
|
||||
|
||||
## Data Model (existing + additions)
|
||||
- `task_sessions`
|
||||
- `id`, `task_id`, `state`, `agent_profile_id`, `agent_execution_id`, `metadata` (includes `resume_token`)
|
||||
- `worktree_id`, `worktree_path`, `worktree_branch`
|
||||
- `executor_id` (local/remote)
|
||||
- `executors_running` (persistent table)
|
||||
- `id` (executor instance id), `session_id`, `task_id`, `runtime`
|
||||
- `agentctl_url`, `agentctl_port`, `container_id` (docker), `pid` (local)
|
||||
- `status`: `starting | ready | error | stopped`
|
||||
- `supports_session_resume`, `supports_workspace_only`
|
||||
- `resume_token`
|
||||
- `workspace_path`, `worktree_id`, `worktree_path`, `worktree_branch`
|
||||
- `last_seen_at`, `error_message`
|
||||
- `executors_cache` (in-memory only)
|
||||
- `execution_id`, `session_id`, `runtime`, `status`, `agentctl_url/port`, `workspace_path`
|
||||
|
||||
Note: agentctl state is derived from `executors_running.status` and health checks.
|
||||
|
||||
## Agent Capability
|
||||
- Add `supports_session_resume` boolean to agent registry or agent profile.
|
||||
- When `false`, mark session as non-resumable on backend restart.
|
||||
- UI should show: “This agent cannot resume previous sessions. Create a new session.”
|
||||
|
||||
## Executor Types
|
||||
- **Local Docker**: containers survive backend restart; recover via Docker APIs.
|
||||
- **Local Standalone**: agentctl processes are local and typically *do not* survive restart.
|
||||
- **Remote Executor**: agentctl runs remotely; survives backend restart; backend must reconnect.
|
||||
|
||||
## Startup Flow (Backend)
|
||||
Goal: recover agentctl instances from `executors_running` on backend start, not when a user opens a session.
|
||||
|
||||
1) **Load executors**
|
||||
- Query `executors_running` where `status` in (`starting`, `ready`).
|
||||
|
||||
2) **Reject non-resumable executors**
|
||||
- If `supports_session_resume=false`, mark related sessions `ERROR` and set `error_message=not_resumable`.
|
||||
|
||||
3) **Resume executors by runtime**
|
||||
- **Local Docker**:
|
||||
- Verify Docker daemon running.
|
||||
- Locate containers by `executors_running.container_id` or session label.
|
||||
- If container missing: mark executor `error`, mark sessions `ERROR`.
|
||||
- If container running: healthcheck agentctl.
|
||||
- **Local Standalone**:
|
||||
- Verify worktree path exists.
|
||||
- If missing: mark executor `error`, mark sessions `ERROR`.
|
||||
- Start agentctl process and healthcheck.
|
||||
- **Remote Executor**:
|
||||
- Call `Health()` on `agentctl_url`.
|
||||
- If unreachable: mark executor `error`, mark sessions `ERROR`.
|
||||
|
||||
4) **Sync executor cache**
|
||||
- Register running executions in `executors_cache` keyed by `session_id`.
|
||||
- Update `executors_running.last_seen_at`.
|
||||
|
||||
5) **Enable workspace access**
|
||||
- If agentctl is healthy, set `executors_running.status=ready`.
|
||||
- Shell/fs/git are enabled regardless of agent resume.
|
||||
|
||||
6) **Resume agent session**
|
||||
- If `supports_session_resume=true` and `resume_token` present, resume agent.
|
||||
- On success: set `session.state = WAITING_FOR_INPUT`.
|
||||
- On failure: set `session.state = ERROR`, update `error_message`.
|
||||
|
||||
7) **Publish updates**
|
||||
- Emit session agentctl events to UI.
|
||||
|
||||
## Executor Resumption Capability
|
||||
Executors should report whether agent session resume is supported by the runtime + agent, so the backend can decouple executor lifecycle from agent lifecycle.
|
||||
|
||||
### Agentctl Capability Probe
|
||||
After agentctl is reachable, call a capability endpoint (new or existing) to determine:
|
||||
- `supports_session_resume`: whether the agent can resume with the session resumption token.
|
||||
- `supports_workspace_only`: whether workspace-only mode is available (for git/fs/shell without agent).
|
||||
|
||||
Note: `requires_new_session` is redundant with `supports_session_resume=false`. If we keep it, it must be a derived/alias field, not an independent signal.
|
||||
|
||||
This allows:\n
|
||||
- Executor resume (agentctl + workspace streams) even if agent resume is not possible.
|
||||
- The UI to enable shell/git/files regardless of agent resumption outcome.
|
||||
|
||||
## Session Resumption Flow (Backend)
|
||||
Triggered when user explicitly requests resume.
|
||||
|
||||
1) Validate session:
|
||||
- Session exists and belongs to task.
|
||||
- Agent profile supports resume and session has `resume_token`.
|
||||
- Worktree exists if required.
|
||||
|
||||
2) Create agentctl instance (local only):
|
||||
- Call `LaunchAgent` with `session_id`, `worktree_path`, `worktree_branch`.
|
||||
- Persist `executors_running.status=starting`.
|
||||
|
||||
3) Start agent process and resume:
|
||||
- Resume agent session with `resume_token`.
|
||||
- On success:
|
||||
- `session.state = WAITING_FOR_INPUT`
|
||||
- `executors_running.status = ready`
|
||||
- `task.state = REVIEW`
|
||||
- On failure:
|
||||
- `session.state = ERROR`
|
||||
- `executors_running.status = error`
|
||||
- Persist `error_message`.
|
||||
|
||||
## Session Status API
|
||||
### `task.session.status`
|
||||
Return session-specific status (no task-level fallback):
|
||||
- `session_id`, `task_id`, `state`, `agent_profile_id`
|
||||
- `executor_status`, `agent_execution_id`, `runtime`
|
||||
- `is_agent_running` (based on execution for that session)
|
||||
- `is_resumable` (resume supported + `resume_token` present)
|
||||
- `needs_resume` (no running execution + resumable)
|
||||
- `resume_reason` (e.g., `agent_not_running`, `not_resumable`, `missing_resume_token`)
|
||||
- `worktree_path`, `worktree_branch`
|
||||
|
||||
## WebSocket Events
|
||||
Session-scoped events:
|
||||
- `session.agentctl_starting`
|
||||
- `session.agentctl_ready`
|
||||
- `session.agentctl_error`
|
||||
- `session.state_changed`
|
||||
- `session.message.added`, `session.message.updated`
|
||||
|
||||
Payloads must include `session_id` and `task_id`.
|
||||
|
||||
## Frontend Flow
|
||||
1) **SSR page** loads session + task + messages and hydrates store.
|
||||
2) **useSessionResumption**
|
||||
- Calls `task.session.status`.
|
||||
- If `needs_resume && is_resumable`: show “Resume session” CTA or auto-resume (configurable).
|
||||
- If `!is_resumable`: show “Create new session” CTA.
|
||||
3) **UI states**
|
||||
- `executor_status=starting`: show spinner and disable shell/file panels.
|
||||
- `executor_status=ready`: allow shell/file access.
|
||||
- `executor_status=error`: show error badge and retry/resume action.
|
||||
|
||||
## Multi-Session per Task Considerations
|
||||
- Executor and lifecycle manager must key executions by `session_id` (done).
|
||||
- `task.session.status` must only check `execution.SessionID == sessionID`.
|
||||
- WebSocket subscriptions should be per-session to avoid cross-session updates.
|
||||
|
||||
## Non-Resumable Agents
|
||||
- Add `supports_session_resume=false` in agent registry/profile.
|
||||
- Backend returns `is_resumable=false` in status.
|
||||
- UI displays a banner: “This agent doesn’t support resuming. Start a new session.”
|
||||
|
||||
## Open Decisions
|
||||
- Whether to keep `executors_running` lean or store full runtime metadata.
|
||||
- Auto-resume on backend startup vs on-demand (current request: startup).
|
||||
- Whether to auto-resume all resumable sessions or only those in RUNNING/WAITING_FOR_INPUT.
|
||||
- Remote executor reconnect timeout/backoff policy.
|
||||
|
||||
## Resumption Flow Diagrams
|
||||
|
||||
### Local Docker Executor (agentctl container survives)
|
||||
```
|
||||
Backend Restart
|
||||
|
|
||||
|-- load executors_running (starting/ready)
|
||||
|-- docker: RecoverInstances()
|
||||
| -> map container to executors_running.id or session_id label
|
||||
|-- agentctl Health()
|
||||
|-- agentctl Capabilities? (supports_session_resume)
|
||||
|-- register AgentExecution(session_id, runtime=local_docker)
|
||||
|-- executors_running.status = ready (workspace-only enabled)
|
||||
|
|
||||
|-- if supports_session_resume & resume_token present:
|
||||
| ResumeSession
|
||||
| session.state = WAITING_FOR_INPUT
|
||||
| else:
|
||||
| session.state = ERROR (not_resumable)
|
||||
|
|
||||
'-- WS events to UI:
|
||||
session.agentctl_ready / session.state_changed
|
||||
```
|
||||
|
||||
### Local Standalone Executor (agentctl does NOT survive)
|
||||
```
|
||||
Backend Restart
|
||||
|
|
||||
|-- load executors_running (starting/ready)
|
||||
|-- no local instances to recover
|
||||
|-- LaunchAgent from executors_running (workspace-only)
|
||||
|-- executors_running.status = starting
|
||||
|-- agentctl Health()
|
||||
|-- agentctl Capabilities? (supports_session_resume)
|
||||
|-- executors_running.status = ready (workspace-only enabled)
|
||||
|
|
||||
|-- if supports_session_resume & resume_token present:
|
||||
| ResumeSession
|
||||
| session.state = WAITING_FOR_INPUT
|
||||
| else:
|
||||
| session.state = ERROR (not_resumable)
|
||||
|
|
||||
'-- WS events to UI:
|
||||
session.agentctl_starting / ready / error
|
||||
```
|
||||
|
||||
### Remote Executor (agentctl survives remotely)
|
||||
```
|
||||
Backend Restart
|
||||
|
|
||||
|-- load executors_running: agentctl_url, id
|
||||
|-- connect to agentctl Health()
|
||||
|-- agentctl Capabilities? (supports_session_resume)
|
||||
|-- register AgentExecution(session_id, runtime=remote)
|
||||
|-- executors_running.status = ready (workspace-only enabled)
|
||||
|
|
||||
|-- if supports_session_resume & resume_token present:
|
||||
| ResumeSession
|
||||
| session.state = WAITING_FOR_INPUT
|
||||
| else:
|
||||
| session.state = ERROR (not_resumable)
|
||||
|
|
||||
'-- WS events to UI:
|
||||
session.agentctl_ready / session.state_changed
|
||||
```
|
||||
|
||||
## Executor vs Agent Resumption
|
||||
Separating executor resume from agent resume allows:
|
||||
- Shell/git/files to function as soon as agentctl is reachable.
|
||||
- Agent resume to fail gracefully without losing workspace access.
|
||||
|
||||
Example UI behavior:
|
||||
1) `session.agentctl_ready` -> enable shell/git/files panels.
|
||||
2) If `supports_session_resume=false` -> show “Create new session to continue messaging.”
|
||||
3) If resume fails -> show error but keep workspace panels active.
|
||||
Reference in New Issue
Block a user