Skip to content

feat: Agent self-execute — background task execution during chat (SELF-EXEC-001) #264

Closed

Description

@vybe

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

  1. User sends message → POST /api/agents/{name}/chat
  2. Chat endpoint acquires execution queue (max 1 at a time per agent)
  3. Blocks until agent responds
  4. Returns response to user

How parallel task works today

  1. MCP chat_with_agent(agent_name, message, parallel=true) → POST /api/agents/{name}/task
  2. No queue — uses slot-based capacity (default 3 parallel)
  3. Can be async (fire-and-forget with async=true)
  4. Tracked in task_executions table, 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-calls
  • TaskExecutionService already tracks parallel task executions with activities
  • Activity panel (UnifiedActivityPanel.vue) already shows running activities

What's missing

  1. 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
  2. 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
  3. Result injection: Optionally, the self-task result should appear as a system message in the chat, so the user sees the outcome
  4. 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 chat

1.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_TASK

Self-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:

  1. Check if chat_session_id matches the currently viewed session
  2. If yes, append a special "background task result" message to the chat
  3. 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:

  1. Sets X-Self-Task: true header
  2. Passes inject_result preference
  3. Logs as self-task instead of collaboration

No new MCP tools needed — chat_with_agent already handles this path.

Implementation Order

  1. Backend activity type + detection — Add SELF_TASK enum, detect self-calls in /task endpoint
  2. Backend execution tracking — Store chat_session_id link, inject_result flag in execution record
  3. MCP tool parameter — Add inject_result param, self-call detection headers
  4. WebSocket events — Emit self_task activity events with chat context
  5. Frontend activity panel — Render self-task entries distinctly in UnifiedActivityPanel
  6. Frontend chat injection — Handle result injection into chat messages
  7. 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

  1. added
    priority-p1
    type-feature
    status-in-progress
    on Apr 4, 2026
  2. removed
    status-in-progress
    on Apr 17, 2026
  3. added
    complexity-medium
    on Jun 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    complexity-mediumpriority-p1type-feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions