Skip to content

Implement Missing Tauri Commands for Schema Operations #388

Closed

Description

@malibio

Implement Missing Tauri Commands for Schema Operations

Problem Statement

Issue #106 (Schema Management System) is incomplete. The implementation has:

  • ✅ Backend SchemaService (Rust) - packages/core/src/services/schema_service.rs
  • ✅ MCP handlers for AI agents - packages/core/src/mcp/handlers/schema.rs
  • ✅ Frontend TypeScript wrapper - packages/desktop-app/src/lib/services/schema-service.ts
  • ❌ Tauri commands - MISSING

The frontend currently calls non-existent mcp_call_tool commands (lines 215-221, 309-327, etc. in schema-service.ts). This creates a major architecture inconsistency: node operations have Tauri commands, but schema operations don't.

This is a breaking bug: When the frontend runs in Tauri mode (not browser), all schema operations fail because the commands don't exist.

Architecture Requirements

1. Two Entry Points, One Backend Pattern

This codebase follows an established pattern (see node operations):

Tauri Commands (desktop app)  ───┐
                                 ├──▶ SchemaService (shared backend)
MCP Handlers (external AI)   ────┘

Both must call the same backend service to avoid duplication and maintain consistency.

Reference Implementation: /packages/desktop-app/src-tauri/src/commands/nodes.rs

  • Tauri commands are thin wrappers around NodeService and NodeOperations
  • MCP handlers in /packages/core/src/mcp/handlers/node.rs call the same services
  • Prevents logic duplication and ensures identical behavior

2. Event Propagation for Live Frontend Updates

CRITICAL: When MCP handlers update schemas (via external AI agents), changes must propagate to the Tauri frontend in real-time via event emissions.

Current Investigation Results:

Event Pattern Exists for Nodes

  • MCP Integration: /packages/desktop-app/src-tauri/src/mcp_integration.rs
    • Method emit_event_for_method emits Tauri events after successful MCP operations
    • Emits: node-created, node-updated, node-deleted
  • Frontend Listener: SharedNodeStore reacts to these events (though it doesn't currently have schema-specific logic)

Event Pattern MISSING for Schemas

  • MCP schema handlers (packages/core/src/mcp/handlers/schema.rs) return success
  • BUT emit_event_for_method in mcp_integration.rs does NOT check for schema methods
  • Result: External AI agent schema updates DO NOT propagate to frontend

Required Fix: Add schema event emissions to MCP integration layer so frontend receives updates.

3. Frontend Schema Representation

Backend: Schemas are stored as Node objects with:

  • node_type = "schema"
  • id = schema_name (e.g., "task")
  • properties field contains serialized SchemaDefinition JSON

Frontend: Uses typed SchemaDefinition interface (/packages/desktop-app/src/lib/types/schema.ts):

interface SchemaDefinition {
  isCore: boolean;
  version: number;
  description: string;
  fields: SchemaField[];
}

Decision: Tauri commands should return SchemaDefinition (not raw Node). The frontend service layer handles serialization/deserialization from Node properties.

Implementation Guide

Phase 1: Create Tauri Commands File

File: /packages/desktop-app/src-tauri/src/commands/schemas.rs

Required Commands (5 total):

1. get_schema_definition

#[tauri::command]
pub async fn get_schema_definition(
    service: State<'_, SchemaService>,
    schema_id: String,
) -> Result<SchemaDefinition, CommandError>
  • Input: schema_id: String
  • Output: SchemaDefinition (serialized)
  • Errors: CommandError if schema not found
  • Backend Call: service.get_schema(&schema_id).await?

2. add_schema_field

#[tauri::command]
pub async fn add_schema_field(
    service: State<'_, SchemaService>,
    schema_id: String,
    field: SchemaField,
) -> Result<SchemaFieldResult, CommandError>

#[derive(Serialize)]
struct SchemaFieldResult {
    schema_id: String,
    new_version: i32,
}
  • Input: schema_id: String, field: SchemaField
  • Output: { schema_id, new_version }
  • Errors: Field already exists, non-user protection level
  • Backend Call: service.add_field(&schema_id, field).await?
  • Event: Should emit schema-updated event

3. remove_schema_field

#[tauri::command]
pub async fn remove_schema_field(
    service: State<'_, SchemaService>,
    schema_id: String,
    field_name: String,
) -> Result<SchemaFieldResult, CommandError>
  • Input: schema_id: String, field_name: String
  • Output: { schema_id, new_version }
  • Errors: Field not found, core field protection
  • Backend Call: service.remove_field(&schema_id, &field_name).await?
  • Event: Should emit schema-updated event

4. extend_schema_enum

#[tauri::command]
pub async fn extend_schema_enum(
    service: State<'_, SchemaService>,
    schema_id: String,
    field_name: String,
    value: String,
) -> Result<SchemaFieldResult, CommandError>
  • Input: schema_id: String, field_name: String, value: String
  • Output: { schema_id, new_version }
  • Errors: Not an enum, not extensible, value exists
  • Backend Call: service.extend_enum_field(&schema_id, &field_name, value).await?
  • Event: Should emit schema-updated event

5. remove_schema_enum_value

#[tauri::command]
pub async fn remove_schema_enum_value(
    service: State<'_, SchemaService>,
    schema_id: String,
    field_name: String,
    value: String,
) -> Result<SchemaFieldResult, CommandError>
  • Input: schema_id: String, field_name: String, value: String
  • Output: { schema_id, new_version }
  • Errors: Core value, value not found
  • Backend Call: service.remove_enum_value(&schema_id, &field_name, &value).await?
  • Event: Should emit schema-updated event

Pattern to Follow: Copy error handling pattern from /packages/desktop-app/src-tauri/src/commands/nodes.rs:

  • Use CommandError for structured errors
  • Implement From<NodeServiceError> conversion
  • Include user-friendly messages and error codes
  • Return early on validation failures

Phase 2: Register Commands in Tauri

File: /packages/desktop-app/src-tauri/src/lib.rs

Add to invoke_handler! macro (around line 142):

.invoke_handler(tauri::generate_handler![
    // ... existing commands ...
    commands::schemas::get_schema_definition,
    commands::schemas::add_schema_field,
    commands::schemas::remove_schema_field,
    commands::schemas::extend_schema_enum,
    commands::schemas::remove_schema_enum_value,
])

Add to commands module export:

// In src-tauri/src/commands/mod.rs
pub mod schemas;

Phase 3: Add Event Emission for MCP Schema Updates

File: /packages/desktop-app/src-tauri/src/mcp_integration.rs

Update emit_event_for_method (line 94) to handle schema methods:

fn emit_event_for_method(app: &AppHandle, method: &str, result: &Value) {
    match method {
        // ... existing node operations ...

        // Schema operations - emit schema-specific events
        "add_schema_field" | "remove_schema_field" | "extend_schema_enum" | "remove_schema_enum_value" => {
            if let Some(schema_id) = result["schema_id"].as_str() {
                let event = SchemaUpdatedEvent {
                    schema_id: schema_id.to_string(),
                    new_version: result["new_version"].as_i64().unwrap_or(0) as i32,
                };
                if let Err(e) = app.emit("schema-updated", &event) {
                    warn!("Failed to emit schema-updated event: {}", e);
                }
            }
        }
        "get_schema_definition" => {
            // No event needed for read operations
        }
        _ => {}
    }
}

Add event payload struct:

#[derive(Debug, Serialize)]
struct SchemaUpdatedEvent {
    schema_id: String,
    new_version: i32,
}

Phase 4: Update Frontend Service

File: /packages/desktop-app/src/lib/services/schema-service.ts

Refactor all methods to call Tauri commands instead of mcp_call_tool:

Before (line 215):

const result = await invoke<{ schema: unknown }>(
  'mcp_call_tool',
  {
    name: 'get_schema_definition',
    arguments: { schema_id: schemaId }
  }
);

After:

const result = await invoke<SchemaDefinition>(
  'get_schema_definition',
  { schemaId } // camelCase for TypeScript
);

Changes Required:

  1. Replace all invoke('mcp_call_tool', ...) with direct command calls
  2. Simplify parameter passing (remove nested arguments object)
  3. Update response parsing (remove result.schema indirection)
  4. Keep browser mode fallback unchanged (uses mock data)

Example Refactor for addField:

async addField(schemaId: string, config: AddFieldConfig): Promise<AddFieldResult> {
  // ... validation ...

  if (!isTauriAvailable) {
    // Browser mode - mock implementation unchanged
  }

  try {
    const result = await invoke<{
      schema_id: string;
      new_version: number;
    }>('add_schema_field', {
      schemaId,
      field: {
        name: config.fieldName,
        fieldType: config.fieldType,
        indexed: config.indexed ?? false,
        required: config.required,
        default: config.default,
        description: config.description,
        itemType: config.itemType,
        enumValues: config.enumValues,
        extensible: config.extensible
      }
    });

    return {
      schemaId: result.schema_id,
      newVersion: result.new_version,
      success: true
    };
  } catch (error) {
    // ... existing error handling ...
  }
}

Phase 5: Add Frontend Event Listener (Optional)

File: /packages/desktop-app/src/lib/services/shared-node-store.ts (or new schema store)

Listen for schema-updated events to invalidate cached schemas:

// In component initialization or service setup
import { listen } from '@tauri-apps/api/event';

listen<{ schema_id: string; new_version: number }>('schema-updated', (event) => {
  console.log(`Schema ${event.payload.schema_id} updated to version ${event.payload.new_version}`);
  // Invalidate cache or refetch schema
  // schemaCache.delete(event.payload.schema_id);
});

Note: This phase is optional since schemas change infrequently. However, it ensures multi-window/multi-viewer consistency if schema editing UI is open in multiple places.

Phase 6: Testing

Unit Tests (Rust)

Add tests in /packages/desktop-app/src-tauri/src/commands/schemas.rs:

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_get_schema_definition() {
        // Create test schema service
        // Call command
        // Assert response structure
    }

    #[tokio::test]
    async fn test_add_field_validation() {
        // Test error cases: duplicate field, core protection
    }
}

Integration Tests (TypeScript)

Update /packages/desktop-app/src/tests/integration/schema-service.test.ts:

describe('SchemaService Tauri Integration', () => {
  it('should fetch schema via Tauri command', async () => {
    const schema = await schemaService.getSchema('task');
    expect(schema.fields).toBeDefined();
  });

  it('should handle non-existent schema', async () => {
    await expect(schemaService.getSchema('nonexistent'))
      .rejects.toThrow();
  });
});

Event Propagation Test

Test MCP → Tauri event flow:

it('should emit schema-updated event when MCP updates schema', async () => {
  const eventPromise = new Promise((resolve) => {
    listen('schema-updated', (event) => resolve(event.payload));
  });

  // Trigger MCP update via external AI agent simulation
  // await mcpClient.addSchemaField('task', ...);

  const event = await eventPromise;
  expect(event.schema_id).toBe('task');
});

Acceptance Criteria

Must Have

  • All 5 Tauri commands implemented in commands/schemas.rs
  • Commands registered in lib.rs invoke handler
  • Commands call SchemaService (shared with MCP handlers)
  • Frontend service refactored to use Tauri commands (not mcp_call_tool)
  • Event emission added for MCP schema updates in mcp_integration.rs
  • Error handling follows node commands pattern (CommandError)
  • All existing unit tests pass
  • New integration tests added for Tauri commands

Should Have

  • Frontend event listener for schema-updated events
  • Event propagation test (MCP → Tauri → Frontend)
  • Browser mode fallback still works (mock data path)

Nice to Have

  • Schema cache invalidation on events
  • Performance metrics for schema operations
  • Error recovery strategies for network failures

Resources

Reference Implementations

  • Node Commands Pattern: /packages/desktop-app/src-tauri/src/commands/nodes.rs
  • MCP Event Emission: /packages/desktop-app/src-tauri/src/mcp_integration.rs (lines 94-202)
  • Command Registration: /packages/desktop-app/src-tauri/src/lib.rs (lines 142-174)

Related Files

  • Backend Service: /packages/core/src/services/schema_service.rs
  • MCP Handlers: /packages/core/src/mcp/handlers/schema.rs
  • Frontend Service: /packages/desktop-app/src/lib/services/schema-service.ts
  • TypeScript Types: /packages/desktop-app/src/lib/types/schema.ts

Architecture Docs

  • Component Architecture: /docs/architecture/components/component-architecture-guide.md
  • Schema Design: /docs/architecture/data/schema-management.md

Labels

  • backend - Rust Tauri commands
  • frontend - TypeScript service refactor
  • architecture - Consistency with established patterns
  • bug - Broken functionality (frontend fails in Tauri mode)
  • good-first-issue - Clear specification with reference implementations

Estimated Complexity

Medium (2-3 days)

  • Phase 1-2: 4-6 hours (command implementation)
  • Phase 3: 2 hours (event emission)
  • Phase 4: 4 hours (frontend refactor)
  • Phase 5-6: 2-4 hours (testing and validation)

Breaking Changes

None - This fixes broken functionality without changing public APIs.

The frontend service already has the correct TypeScript signatures. We're just implementing the missing backend commands that the frontend expects to exist.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions