Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Implementation:0xranx OpenContext emit agent event

From Leeroopedia
Knowledge Sources
Domains Real_Time_Systems, Desktop_App
Last Updated 2026-10-24 12:00 GMT

Overview

Concrete tool for emitting structured agent streaming events from the Rust backend to the React frontend via Tauri's event system.

Description

The emit_agent_event function is the core event emission mechanism for agent streaming. It takes a `tauri::AppHandle`, a request ID, and an `AgentStreamEvent` payload, then emits a Tauri event named `agent-stream-{request_id}`.

The AgentStreamEvent struct is the unified event format for all agent types (Codex, Claude, OpenCode). It uses `skip_serializing_if = "Option::is_none"` on all fields so only non-null fields are included in the event payload, keeping the wire format compact.

The function is called from the background thread that reads the agent process's stdout. Each line of output is parsed as JSON-RPC and mapped to an `AgentStreamEvent` variant.

Helper functions:

  • emit_agent_error: Emits an error event with `done: true` and the error message.
  • emit_agent_status: Emits a status-only event (e.g., "spawning", "connecting").

Usage

  • Agent streaming: Used by all agent exec functions (codex_exec, claude_exec, opencode_run) to stream responses.
  • Frontend subscription: The frontend's `useAgentStreaming` hook listens to these events.
  • Event naming: The `agent-stream-{request_id}` pattern allows concurrent agent sessions.

Code Reference

Source Location

  • Repository: OpenContext
  • File: src-tauri/src/commands/agent.rs

Signature

#[derive(Serialize, Clone, Default)]
pub(crate) struct AgentStreamEvent {
    #[serde(skip_serializing_if = "Option::is_none")]
    content: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    done: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    error: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    status: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    reasoning: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    permission: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    tool: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    models: Option<serde_json::Value>,
}

fn emit_agent_event(app: &tauri::AppHandle, request_id: &str, payload: AgentStreamEvent) {
    let event_name = format!("agent-stream-{}", request_id);
    let _ = app.emit(&event_name, payload);
}

fn emit_agent_error(app: &tauri::AppHandle, request_id: &str, message: String) {
    emit_agent_event(app, request_id, AgentStreamEvent {
        content: None,
        done: Some(true),
        error: Some(message),
        ..Default::default()
    });
}

fn emit_agent_status(app: &tauri::AppHandle, request_id: &str, status: &str) {
    emit_agent_event(app, request_id, AgentStreamEvent {
        status: Some(status.to_string()),
        ..Default::default()
    });
}

Import

// Internal to the agent module — used by codex_exec, claude_exec, opencode_run
use crate::commands::agent::{emit_agent_event, emit_agent_error, emit_agent_status, AgentStreamEvent};

I/O Contract

Inputs

Name Type Required Description
app &tauri::AppHandle Yes Tauri app handle for event emission
request_id &str Yes Request ID (part of event name)
payload AgentStreamEvent Yes Event payload

AgentStreamEvent Fields

Field Type Description
content Option<String> Text content tokens from the agent
done Option<bool> Stream completion signal
error Option<String> Error message
status Option<String> Status update (e.g., "spawning")
reasoning Option<String> Reasoning/thinking tokens
permission Option<Value> Tool call permission request
tool Option<Value> Tool call information
models Option<Value> Available model list

Outputs

Name Type Description
event Tauri Event Emitted as `agent-stream-{request_id}`

Usage Examples

Emit Content Token

emit_agent_event(&app, &request_id, AgentStreamEvent {
    content: Some("Here is the refactored code...".to_string()),
    ..Default::default()
});

Emit Completion

emit_agent_event(&app, &request_id, AgentStreamEvent {
    done: Some(true),
    ..Default::default()
});

Emit Permission Request

emit_agent_event(&app, &request_id, AgentStreamEvent {
    permission: Some(serde_json::json!({
        "callId": "patch_001",
        "type": "apply_patch_approval_request",
        "changes": { /* patch details */ }
    })),
    ..Default::default()
});

Frontend Listener (JavaScript)

import { listen } from '@tauri-apps/api/event';

const unlisten = await listen(`agent-stream-${requestId}`, (event) => {
  const { content, done, error, reasoning, permission, tool } = event.payload;

  if (content) updateMessageContent(content);
  if (reasoning) updateReasoning(reasoning);
  if (done) finalizeMessage();
  if (error) showError(error);
  if (permission) showPermissionDialog(permission);
  if (tool) renderToolCall(tool);
});

Related Pages

Implements Principle

Requires Environment

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment