Skip to content

feat: Tauri command layer wiring frontend to agent backend services - #1034

Merged
malibio merged 1 commit into
mainfrom
feature/issue-1008-tauri-commands
Apr 4, 2026
Merged

malibio merged 1 commit into
mainfrom
feature/issue-1008-tauri-commands

Conversation

@malibio

@malibio malibio commented Apr 4, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Creates Tauri command modules: local_agent.rs, chat_models.rs, acp.rs
  • Registers LocalAgentService and AcpClientService as independent managed state
  • Wires frontend stores to real Tauri invocations with mock fallback
  • Updates tauri-commands.ts with all new invoke wrappers
  • All 194 Rust app tests passing, 3850 frontend tests passing

Closes #1008

…loses #1008)

Creates Tauri command modules for local agent, model management, and ACP.
Registers LocalAgentService and AcpClientService as independent managed
state. Wires frontend stores to real Tauri invocations with mock fallback
for development mode. Updates tauri-commands.ts with all new invoke wrappers.

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Apr 4, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review -- PR #1034

Reviewer: Principal Engineer (automated)
Verdict: Approve with improvements -- net positive, no blockers


Overall Assessment

This PR delivers a well-structured Tauri command layer that bridges all 18 specified commands across three modules (local agent, chat models, ACP). The architecture correctly places agent services as independent managed state outside AppServices, the ?Sized bounds enable trait-object usage for dynamic dispatch, and the frontend stores are cleanly wired with mock fallback. The GPU lifecycle integration is properly ordered. This is a clear net improvement and should merge.

The findings below are improvements to address before or shortly after merge -- none are blockers.


Findings

Suggested Improvements

1. [Improvement] RwLock read guard held across .await in all local_agent_* commands

ManagedAgentState::service() returns a tokio::sync::RwLockReadGuard, and every command handler holds it across subsequent .await calls:

// local_agent.rs -- local_agent_send (and all other commands)
let service = state.service().await;   // acquires RwLockReadGuard
service.send_message(...).await        // held across this .await

For local_agent_send specifically, the guard is held for the entire duration of a ReAct agent turn -- potentially seconds to minutes. While tokio::sync::RwLock is designed to be held across .await (unlike std::sync::RwLock), this blocks all write-lock acquisitions for the entire turn duration, meaning the agent service cannot be swapped (e.g., when a new model is loaded) until every in-flight send_message completes.

Since the RwLock inner type is LocalAgentService which itself uses interior mutability (RwLock<HashMap> for sessions), the outer lock serves primarily to enable service replacement. Consider one of:

  • (a) Wrap the inner value in Arc so you can clone() the Arc and drop the guard immediately, or
  • (b) Add a dedicated method that clones the Arc<LocalAgentService> and returns it, so commands never hold the outer guard for long.

This applies to all 6 local_agent_* command handlers.

2. [Improvement] isTauri() duplicated 4 times in this PR

The PR adds a private isTauri() function in each of: tauri-commands.ts, agent-store.svelte.ts, chat-store.svelte.ts, model-store.svelte.ts. The codebase already has 3-4 copies of the same check (isTauriEnvironment() in backend-adapter.ts, collection-service.ts, app-initialization.ts, and isTauri() in external-links.ts).

Extract a single canonical isTauri() into $lib/utils/environment.ts and import it everywhere. DRY principle; one check to maintain when the detection logic evolves.

3. [Improvement] extract_agent_id in acp.rs is fragile

fn extract_agent_id(session_id: &str) -> String {
    let without_prefix = session_id.strip_prefix("acp-").unwrap_or(session_id);
    if let Some(pos) = without_prefix.rfind('-') {
        without_prefix[..pos].to_string()
    } else {
        without_prefix.to_string()
    }
}

This parses the convention acp-{agent_id}-{uuid_prefix} but breaks if agent_id itself contains a hyphen (e.g., my-custom-agent would be parsed as my-custom instead of my-custom-agent). The UUID suffix is more than one hyphen segment, so rfind('-') strips only the last segment, not the full UUID suffix.

Better approach: have start_session return a structured type or store a session_id -> agent_id mapping in the AcpClientService so the command layer doesn't need to reverse-engineer IDs from string conventions.

4. [Improvement] acp_send_message blocks on receive_message synchronously

service.send_message(&agent_id, msg).await?;
match service.receive_message(&agent_id).await { ... }

This means acp_send_message blocks the calling Tauri command until the external agent responds. If the agent is slow or unresponsive, the frontend's invoke() promise hangs with no timeout. Consider:

  • Adding a configurable timeout (e.g., tokio::time::timeout)
  • Or making receive event-driven (spawn a background task that emits events as messages arrive)

5. [Improvement] local_agent_get_sessions has an N+1 query pattern

let session_pairs = service.get_sessions().await;
for (id, _) in &session_pairs {
    if let Some(session) = service.get_session(id).await {
        sessions.push(session);
    }
}

get_sessions() iterates all sessions, then get_session() re-acquires the sessions lock for each ID. Add a get_all_sessions() method on LocalAgentService that returns Vec<AgentSession> in a single lock acquisition.

6. [Improvement] local_agent_status derives status from last session only

let sessions = service.get_sessions().await;
Ok(sessions.last().map(|(_, s)| s.clone()).unwrap_or(LocalAgentStatus::Idle))

get_sessions() returns a Vec collected from a HashMap iteration, so ordering is non-deterministic. The "last" session is arbitrary, not necessarily the most recent. If the intent is "overall agent status," consider checking if any session is active/generating.

7. [Improvement] Missing context_node_ids parameter on acp_start_session

The issue spec defines:

#[command] async fn acp_start_session(agent_id: String, context_node_ids: Vec<String>) -> Result<String, String>

The implementation omits context_node_ids. If this was a deliberate scope reduction, note it in the PR description. If not, it should be added to satisfy the acceptance criteria.

8. [Improvement] Event listener leak potential in chat-store.svelte.ts

const unlistenChunk = await listen<StreamingChunk>(AGENT_EVENTS.LOCAL_AGENT_CHUNK, ...);
this.eventUnlisteners.push(unlistenChunk);

If sendViaTauri is called multiple times before cleanupEventListeners runs (e.g., rapid sends), listeners accumulate in eventUnlisteners. The finally block cleans up, but if a second send starts before the first completes (despite the isStreaming guard), orphaned listeners could fire for the wrong message. The isStreaming guard should prevent this in practice, but consider clearing listeners at the start of sendViaTauri as well for defensive programming.

Nitpicks

Nit: chat_models.rs -- chat_model_download sets progress callback on every call

manager.set_progress_callback(Box::new(move |evt: DownloadEvent| { ... })).await;

This replaces the global progress callback on every download invocation. If two downloads were somehow triggered concurrently, the second call would overwrite the first's callback. Not a real issue today (single download at a time), but worth a comment noting the assumption.

Nit: NoOpInferenceEngine token_count estimate

The 1-token-per-4-chars heuristic is reasonable for a stub, but consider returning Err(InferenceError::NoModelLoaded) for consistency with generate(), since accurate token counting requires a tokenizer. Currently the agent loop could silently use inaccurate counts for history trimming when no model is loaded.

Nit: Unused import createLogger in tauri-commands.ts

const log = createLogger('TauriCommands');

The log variable is created but never used in the diff. Either add logging for error paths or remove the import.

Nit: Mock fallback on error in agent-store.svelte.ts

if (this.agents.length === 0) {
    this.agents = [...MOCK_AGENTS];
    log.info('Fell back to mock agents after error');
}

Silently falling back to mock data on Tauri errors could mask real issues. Consider at minimum logging the original error at warn level before the fallback so developers can distinguish "no Tauri" from "Tauri call failed."


Command Coverage Audit

All 18 commands from the spec are registered:

  • Local Agent: 6/6 (status, new_session, send, cancel, end_session, get_sessions)
  • Chat Models: 7/7 (list, recommended, download, cancel_download, delete, load, unload)
  • ACP: 5/5 (list_agents, start_session, send_message, end_session, refresh_agents)

Architecture Alignment

  • Independent managed state (outside AppServices): Correct
  • Agent services obtain NodeService per-operation via AppServices: Correct (GraphToolExecutor holds AppServices clone)
  • GPU lifecycle integration: Correct (chat model unloaded before embedding resources, proper thread isolation)
  • Event channels match spec: Correct (all 7 event channels present)
  • Error mapping to CommandError: Correct (consistent *_error() helpers per module)
  • ?Sized bounds for trait-object usage: Correct and well-motivated

Summary

The PR fulfills all 18 command registrations, correctly implements the independent managed state pattern, and cleanly wires frontend stores with Tauri/mock duality. The RwLock guard lifetime (finding #1) and the extract_agent_id fragility (finding #3) are the most impactful items to address. The isTauri() duplication (finding #2) is a codebase-wide issue this PR exacerbates but shouldn't block on.

Recommendation: Approve. Address findings #1 and #3 in a follow-up or in this PR before merge.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review verdict: Approve with improvements (no blockers). All 18 commands registered, independent managed state pattern correct, GPU lifecycle integrated, frontend stores wired with mock fallback. See detailed review comment above for 8 improvement suggestions. Key items to address: (1) RwLock guard held across long .await in local_agent commands, (2) fragile extract_agent_id string parsing, (3) isTauri() duplication.

@malibio
malibio merged commit 4c867db into main Apr 4, 2026
@malibio
malibio deleted the feature/issue-1008-tauri-commands branch April 4, 2026 07:22
malibio added a commit that referenced this pull request Jun 22, 2026
…loses #1008) (#1034)

Creates Tauri command modules for local agent, model management, and ACP.
Registers LocalAgentService and AcpClientService as independent managed
state. Wires frontend stores to real Tauri invocations with mock fallback
for development mode. Updates tauri-commands.ts with all new invoke wrappers.

Co-authored-by: Michael Libio <[email protected]>
Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Tauri command layer: wire frontend to agent backend services

1 participant