Repository navigation
Description
Summary
Allow an agent to trigger a background task execution on itself while actively chatting with a user. The agent calls itself via the Trinity MCP chat_with_agent tool (which it's already connected to), and Trinity tracks and displays this self-execution in the chat UI's activity panel.
Why: Agents often need to perform work that takes time (research, file processing, code generation) while keeping the chat responsive. Today, the agent blocks the chat while working. With self-execute, the agent can kick off a background task, immediately respond to the user ("I'm working on that in the background"), and the user sees the task progress in the activity panel.
Current Architecture
How chat works today
- User sends message →
POST /api/agents/{name}/chat - Chat endpoint acquires execution queue (max 1 at a time per agent)
- Blocks until agent responds
- Returns response to user
How parallel task works today
- MCP
chat_with_agent(agent_name, message, parallel=true)→POST /api/agents/{name}/task - No queue — uses slot-based capacity (default 3 parallel)
- Can be async (fire-and-forget with
async=true) - Tracked in
task_executionstable, activity timeline
What already works
- Agent has MCP connection to Trinity (
TRINITY_MCP_API_KEY) - Agent can already call
chat_with_agent(agent_name=<self>, parallel=true, async=true)to self-execute checkAgentAccess()already allows self-callsTaskExecutionServicealready tracks parallel task executions with activities- Activity panel (
UnifiedActivityPanel.vue) already shows running activities
What's missing
- Chat-aware self-execution: When an agent self-executes during chat, Trinity needs to know it's a "self-task" triggered from an active chat, not just a generic parallel task
- Chat UI integration: The self-task should appear in the chat activity panel alongside the current chat's tool calls — not just in the general activity timeline
- Result injection: Optionally, the self-task result should appear as a system message in the chat, so the user sees the outcome
- Frontend SSE/WebSocket integration: The chat panel needs to listen for self-task events and display progress
Design
Phase 1: Backend — Self-Execute Tracking
1.1 New activity type: SELF_TASK
In models.py, add:
class ActivityType(str, Enum):
# ... existing ...
SELF_TASK = "self_task" # Agent executing task on itself during chat1.2 Modify /task endpoint to detect self-execution
In routers/chat.py execute_parallel_task():
# Detect self-execution: source agent == target agent
is_self_task = (x_source_agent == name)
if is_self_task:
triggered_by = "self_task"
# Track as SELF_TASK activity instead of AGENT_COLLABORATION
activity_type = ActivityType.SELF_TASKSelf-tasks are still parallel tasks — they use slots, not the chat queue. The only change is the triggered_by label and activity type for the UI to differentiate.
1.3 Enrich execution record with chat context
When the agent calls chat_with_agent on itself, the MCP tool should pass additional context:
// In chat.ts, detect self-call
const isSelfTask = authContext?.scope === "agent" && authContext.agentName === agent_name;
if (isSelfTask) {
headers["X-Self-Task"] = "true";
// Pass originating chat session if available
if (options?.chat_session_id) {
headers["X-Chat-Session-ID"] = options.chat_session_id;
}
}The backend stores chat_session_id in the execution record's details, linking the self-task to the active chat.
1.4 New MCP tool parameter: inject_result
Add optional parameter to chat_with_agent:
inject_result: z.boolean().optional().default(false)
.describe("If true, inject the task result as a system message in the originating chat session")When inject_result=true and the task completes, the backend writes a system/assistant message into the chat session so the user sees it.
Phase 2: Backend — Result Injection
2.1 Task completion callback
In TaskExecutionService, after a self-task completes:
if triggered_by == "self_task" and inject_result:
# Write result as system message into the originating chat session
db.add_chat_message(
session_id=chat_session_id,
agent_name=agent_name,
user_id=source_user_id,
user_email=source_user_email,
role="assistant",
content=f"**Background task completed:**\n\n{result.response}",
timestamp=now_iso(),
cost=result.cost,
context_used=result.context_used,
context_max=result.context_max,
execution_time_ms=duration_ms,
source="self_task"
)2.2 WebSocket event for self-task
New WebSocket event type for chat-specific self-task updates:
{
"type": "agent_activity",
"agent_name": "my-agent",
"activity_type": "self_task",
"activity_state": "started|completed|failed",
"action": "Background task: <message_preview>",
"details": {
"execution_id": "...",
"chat_session_id": "...",
"message_preview": "Research competitor pricing...",
"inject_result": true
}
}On completion:
{
"type": "agent_activity",
"activity_type": "self_task",
"activity_state": "completed",
"details": {
"execution_id": "...",
"chat_session_id": "...",
"cost_usd": 0.05,
"execution_time_ms": 45000,
"response_preview": "Found 3 competitors..."
}
}Phase 3: Frontend — Chat Activity Display
3.1 Activity panel: self-task entries
UnifiedActivityPanel.vue already renders activity timeline entries. Add visual differentiation for self_task type:
- Icon: Different icon (e.g., refresh/loop icon instead of tool icon)
- Label: "Background Task" instead of tool name
- Progress: Pulsing indicator while running
- Duration: Shows elapsed time while running, final time on completion
- Expandable: Click to see full task message and result
3.2 Chat message injection
When the frontend receives a self_task completed WebSocket event with inject_result=true:
- Check if
chat_session_idmatches the currently viewed session - If yes, append a special "background task result" message to the chat
- Style differently from normal assistant messages (e.g., bordered card, "Background Task" header)
// In ChatPanel.vue or agent store
ws.on('agent_activity', (event) => {
if (event.activity_type === 'self_task' &&
event.activity_state === 'completed' &&
event.details?.chat_session_id === currentSessionId.value &&
event.details?.inject_result) {
// Fetch the execution result and add to chat
messages.value.push({
role: 'assistant',
content: event.details.response_preview,
timestamp: event.timestamp,
source: 'self_task'
})
}
})3.3 Chat bubble variant for self-task results
ChatBubble.vue gets a new rendering mode for source === 'self_task':
- Light purple/blue background (distinct from normal assistant white)
- Header: "🔄 Background Task Result"
- Shows cost and duration metadata
- Collapsible if long
Phase 4: MCP Tool Enhancement
4.1 New parameter on chat_with_agent
parameters: z.object({
// ... existing params ...
inject_result: z.boolean().optional().default(false)
.describe(
"When calling yourself (self-task), inject the result as a message in your current chat session. " +
"Only applies to self-calls (agent_name matches calling agent)."
),
})4.2 Self-call detection in MCP tool
The MCP tool detects self-calls and:
- Sets
X-Self-Task: trueheader - Passes
inject_resultpreference - Logs as self-task instead of collaboration
No new MCP tools needed — chat_with_agent already handles this path.
Implementation Order
- Backend activity type + detection — Add
SELF_TASKenum, detect self-calls in/taskendpoint - Backend execution tracking — Store
chat_session_idlink,inject_resultflag in execution record - MCP tool parameter — Add
inject_resultparam, self-call detection headers - WebSocket events — Emit
self_taskactivity events with chat context - Frontend activity panel — Render self-task entries distinctly in UnifiedActivityPanel
- Frontend chat injection — Handle result injection into chat messages
- Frontend chat bubble — New rendering variant for self-task results
Files to Modify
| Layer | File | Change |
|---|---|---|
| Backend | src/backend/models.py |
Add SELF_TASK activity type |
| Backend | src/backend/routers/chat.py |
Detect self-execution in /task, pass chat_session_id |
| Backend | src/backend/services/task_execution_service.py |
Result injection callback for self-tasks |
| Backend | src/backend/services/activity_service.py |
Handle SELF_TASK activity type |
| Backend | src/backend/database.py |
Add source field to chat_messages (for self_task messages) |
| MCP | src/mcp-server/src/tools/chat.ts |
Add inject_result param, self-call detection |
| MCP | src/mcp-server/src/client.ts |
Pass inject_result and X-Self-Task header |
| Frontend | src/frontend/src/components/UnifiedActivityPanel.vue |
Self-task entry rendering |
| Frontend | src/frontend/src/components/ChatPanel.vue |
Listen for self-task completion, inject result |
| Frontend | src/frontend/src/components/chat/ChatBubble.vue |
Self-task result rendering variant |
| Frontend | src/frontend/src/stores/agents.js |
Handle self-task WebSocket events |
Acceptance Criteria
- Agent can call
chat_with_agent(agent_name=<self>, parallel=true, inject_result=true)via MCP - Self-task runs in background while chat remains interactive (user can send new messages)
- Activity panel shows self-task with distinct visual (running spinner, then completion status)
- When
inject_result=true, task result appears as a styled message in the chat - Self-task activity events broadcast via WebSocket with
activity_type: "self_task" - Execution record links to originating chat session
- Works with async mode (
async=true) for fire-and-forget self-tasks - Respects agent capacity limits (uses parallel slots, not chat queue)
Out of Scope
- Cancellation of running self-tasks from the UI (future enhancement)
- Chaining self-tasks (one self-task triggering another — already works via existing MCP)
- Progress streaming from self-task to chat (would require SSE bridge — future)
Activity
feat(chat): agent self-execute with optional result injection (#264)
docs: update orchestration plan — mark #264 as shipped (PR #334)
feat(chat): agent self-execute with optional result injection (#264) (#…
fix(backlog): repair drain spawn — lazy-import target after #95 (#496) (
docs(planning): #408 dissolution gated on #428, not #306 (re-audit) (#…
Release: v0.5.0 (#608)