Skip to content

Tauri command layer: wire frontend to agent backend services #1008

Closed

Description

@malibio

Overview

Create all Tauri command functions that bridge the Svelte frontend to the Rust agent backend services. This is the glue layer that connects the UI components (#1003) to the local agent (#1006, #1007), model manager (#1000), ACP client (#1004), and context assembly (#1005).

Also handles service initialization in Tauri managed state and event emission for all agent-related channels.

Acceptance Criteria

  • All local agent commands registered and callable from frontend
  • All model management commands registered and callable
  • All ACP commands registered and callable
  • Event emission works for all event channels (streaming, tools, status, download, ACP)
  • LocalAgentService and AcpClientService registered as independent Tauri managed state (OUTSIDE AppServices)
  • Services survive database hot-swap (verified by test)
  • Agent services obtain NodeService/NodeEmbeddingService per-operation from AppServices
  • GPU lifecycle integration: chat model unloaded during release_gpu_resources()
  • Error mapping: Rust errors converted to frontend-friendly strings
  • Commands handle concurrent calls safely
  • Frontend mock backends replaced with real Tauri invoke calls
  • Integration test: invoke command, verify event emission
  • Code passes bun run quality:fix

Technical Specifications

New Modules

  • packages/desktop-app/src-tauri/src/commands/local_agent.rs
  • packages/desktop-app/src-tauri/src/commands/acp.rs

Local Agent Commands

#[command] async fn local_agent_status() -> Result<LocalAgentStatus, String>
#[command] async fn local_agent_new_session(model_id: String) -> Result<String, String>  // returns session_id
#[command] async fn local_agent_send(session_id: String, message: String) -> Result<StopReason, String>
#[command] async fn local_agent_cancel(session_id: String) -> Result<(), String>
#[command] async fn local_agent_end_session(session_id: String) -> Result<(), String>
#[command] async fn local_agent_get_sessions() -> Result<Vec<AgentSession>, String>

Model Management Commands

#[command] async fn model_list() -> Result<Vec<(ModelInfo, ModelStatus)>, String>
#[command] async fn model_recommended() -> Result<ModelInfo, String>  // RAM-based recommendation
#[command] async fn model_download(model_id: String) -> Result<(), String>
#[command] async fn model_cancel_download(model_id: String) -> Result<(), String>
#[command] async fn model_delete(model_id: String) -> Result<(), String>
#[command] async fn model_load(model_id: String) -> Result<(), String>
#[command] async fn model_unload() -> Result<(), String>

ACP Commands

#[command] async fn acp_list_agents() -> Result<Vec<AcpAgentInfo>, String>
#[command] async fn acp_start_session(agent_id: String, context_node_ids: Vec<String>) -> Result<String, String>
#[command] async fn acp_send_message(session_id: String, message: String) -> Result<(), String>
#[command] async fn acp_end_session(session_id: String) -> Result<(), String>
#[command] async fn acp_refresh_agents() -> Result<Vec<AcpAgentInfo>, String>

Event Emission

  • Forward streaming chunks -> local-agent://chunk
  • Forward tool calls -> local-agent://tool
  • Forward status changes -> local-agent://status
  • Forward errors -> local-agent://error
  • Forward download progress -> model://download-progress
  • Forward ACP session state -> acp://session-state
  • Forward ACP agent messages -> acp://agent-message

Service Initialization (in lib.rs)

// Agent services are OUTSIDE AppServices — survive database hot-swaps
app.manage(LocalAgentService::new(models_dir));
app.manage(AcpClientService::new());

// Initialize model manager on startup (scan for existing models)
// Start agent registry background health checks

Key pattern: Agent services obtain NodeService and NodeEmbeddingService references on each operation via AppServices accessor methods — they never store these long-term.

GPU Lifecycle Integration

  • Chat model must be unloaded during release_gpu_resources()
  • Follow same drain-then-release ordering as embedding processor shutdown
  • Re-load chat model after database switch completes (if model was previously loaded)

Reference Files

  • packages/desktop-app/src-tauri/src/commands/ — existing command patterns
  • packages/desktop-app/src-tauri/src/lib.rs — app initialization and service registration
  • packages/desktop-app/src-tauri/src/app_services.rs — AppServices pattern and hot-swap lifecycle
  • packages/desktop-app/src-tauri/src/mcp_integration.rs — similar independent service pattern

Dependencies

Related Issues

Activity

  1. malibio commented on Apr 3, 2026

    @malibio
    CollaboratorAuthor

    Implementation Guide

    Start Here

    1. Read packages/desktop-app/src-tauri/src/commands/embeddings.rs — the most complete command example:

      • Line 60: #[tauri::command] attribute on async function
      • Takes State<'_, AppServices> + typed params
      • Returns Result<T, CommandError>
      • Uses services.embedding_state().await? for service access
    2. Read packages/desktop-app/src-tauri/src/commands/nodes.rs — node CRUD pattern:

      • CreateNodeInput struct (line 22) — input types for frontend serialization
      • CommandError (line 42) — machine-readable codes + user message
      • From<NodeServiceError> impl (line 53) — maps business errors to command errors
    3. Read packages/desktop-app/src-tauri/src/lib.rs lines 380-429 — tauri::generate_handler![] macro where all commands are registered. Your new commands go here.

    Command Registration

    All existing command files are in packages/desktop-app/src-tauri/src/commands/:

    • db.rs, nodes.rs, embeddings.rs, collections.rs, schemas.rs, settings.rs, diagnostics.rs, import.rs, models.rs
    • mod.rs — module declarations (add your new modules here)

    You'll create two new files:

    • commands/local_agent.rs — local agent commands
    • commands/acp.rs — ACP agent commands

    Service Initialization Sequence

    In lib.rs setup, services initialize in this order:

    1. ShutdownToken registered as managed state (line 237)
    2. AppServices registered as managed state (line 329)
    3. Frontend calls initialize_database command → creates ServiceBundle → populates AppServices
    4. Background tasks spawned after database init: MCP server, event forwarder, playbook engine

    Your agent services initialize in step 2 (before database):

    // lib.rs setup — agent services are independent of database
    let models_dir = app.path().app_data_dir()?.join("models");
    app.manage(LocalAgentService::new(models_dir));
    app.manage(AcpClientService::new());

    They obtain NodeService per-operation from AppServices (which may not be initialized yet — commands must handle the NOT_INITIALIZED error gracefully).

    Event Forwarding Pattern

    For streaming events from Rust to frontend, follow the pattern in initialize_domain_event_forwarder() (lib.rs line 48):

    // In your command handler, get the app handle:
    async fn local_agent_send(
        app: tauri::AppHandle,
        services: State<'_, AppServices>,
        agent: State<'_, LocalAgentService>,
        session_id: String,
        message: String,
    ) -> Result<StopReason, CommandError> {
        let node_service = services.node_service().await?;
        
        agent.send_message(session_id, message, &node_service, |chunk| {
            app.emit("local-agent://chunk", &chunk)?;
            Ok(())
        }).await.map_err(CommandError::from)
    }

    GPU Lifecycle Integration

    During AppServices::switch_database() (app_services.rs line 174), the chat model must be unloaded. The drain protocol:

    1. Cancel session token → stops background tasks
    2. Shut down embedding processor
    3. Release GPU resources
    4. Replace services

    Your LocalAgentService should listen for the shutdown signal and unload the chat model. The model reloads on the next agent operation after the new database is initialized.

  2. malibio commented on Apr 4, 2026

    @malibio
    CollaboratorAuthor

    Baseline: 124 test files passed, 3850 tests passed (worktree agent-a2329807)

  3. self-assigned this
    on Apr 4, 2026
  4. added a commit that references this issue on Apr 4, 2026
    8a319ab
  5. added a commit that references this issue on Jun 22, 2026
    7b9aa49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions