Skip to content

AI Chat node type: schema, behavior, plugin, and viewer #1017

Closed

Description

@malibio

Overview

Implement the ai-chat node type as a first-class knowledge graph node. Conversations (both local agent and ACP) are stored as nodes with messages in nested properties, following the same pattern as playbook rules[]. This enables semantic search across chat history, Stamped ACL permissions, cloud sync, and end-to-end development traceability.

Architecture decisions: ADR-028 (message storage), ADR-029 (behavior-owned embedding)

Full specification: AI Chat Node Architecture (supersedes archived spec)

Acceptance Criteria

  • AiChatNodeBehavior implements NodeBehavior trait
  • Core schema defined in core_schemas.rs with messages[] array property
  • get_embeddable_content() extracts user + assistant text from properties.messages[], skips tool calls
  • get_parent_contribution() returns None
  • aiChatNodePlugin registered in core-plugins.ts with /ai-chat slash command
  • AiChatNodeViewer.svelte renders conversation with streaming support
  • Tool calls render as collapsible cards (tool name, args, result summary, duration)
  • Tool result archival at write time: full results kept in memory during session, only result_summary persisted to DB, full result nulled
  • Write buffering: messages buffered in memory, debounced flush every 5-10s, immediate flush on close/navigate-away/app-exit
  • Soft message cap: UX nudge at ~500 messages suggesting a new conversation (not a hard limit)
  • Node references in assistant messages decorated as clickable NodeReference components
  • referenced_nodes[] tracked per message, mentions relationships created
  • Provenance: nodes created by agent get created_by and source_chat_node properties
  • Side nav AI item creates/opens an ai-chat node
  • First-launch onboarding dialog (ACP provider vs local model download)
  • Unit tests for behavior, schema validation, content extraction, and tool result archival
  • Code passes bun run quality:fix

Technical Specifications

Schema (nested properties pattern — ADR-028)

{
  "node_type": "ai-chat",
  "content": "Chat title",
  "properties": {
    "provider": "native | anthropic | gemini | mistral",
    "model": "ministral-3b-instruct-q4_k_m",
    "status": "active | archived",
    "last_active": "2026-04-03T10:30:00Z",
    "context_tokens": 4200,
    "created_nodes": ["node:abc123"],
    "messages": [
      {
        "role": "user",
        "content": "Implement the webhook handler",
        "referenced_nodes": ["node:spec-789"],
        "timestamp": "2026-04-03T10:28:00Z"
      },
      {
        "role": "tool_call",
        "tool": "search_semantic",
        "args": { "query": "billing webhook" },
        "status": "completed",
        "result_summary": "Found 3 nodes matching 'billing webhook'",
        "result": null,
        "duration_ms": 340,
        "timestamp": "2026-04-03T10:28:01Z"
      },
      {
        "role": "assistant",
        "content": "Based on the spec, here is my approach...",
        "referenced_nodes": ["node:abc123"],
        "timestamp": "2026-04-03T10:28:05Z"
      }
    ]
  }
}

Guardrails (from ADR-028 and architect review)

Tool result archival: Tool call results archived at write time. During active session, full result kept in memory for display. When flushing to DB, result nulled out, result_summary preserved. Full results are reproducible by re-running the tool.

Write buffering: Messages buffered in memory during active conversation. Frontend in-memory state is source of truth. Debounced flush to SurrealDB every 5-10 seconds. Immediate flush on: conversation close, navigate-away, app exit.

Soft message cap: At ~500 messages, gentle UX prompt suggests starting a new conversation. Not a hard limit. If conversation splitting is ever needed, it should be user-initiated (not automatic). Documented as deferred in ADR-028.

NodeBehavior Implementation

pub struct AiChatNodeBehavior;

impl NodeBehavior for AiChatNodeBehavior {
    fn type_name(&self) -> &'static str { "ai-chat" }
    fn can_have_children(&self) -> bool { false }
    fn supports_markdown(&self) -> bool { false }

    fn get_embeddable_content(&self, node: &Node) -> Option<String> {
        // Behaviors operate on flattened API format (see flatten_properties_for_api)
        let messages = node.properties.get("messages")?.as_array()?;
        let text: Vec<&str> = messages.iter()
            .filter_map(|m| match m.get("role")?.as_str()? {
                "user" | "assistant" => m.get("content")?.as_str(),
                _ => None,
            })
            .collect();
        if text.is_empty() { None } else { Some(text.join("\n\n")) }
    }

    fn get_parent_contribution(&self, _node: &Node) -> Option<String> {
        None
    }
}

Frontend Components

  • AiChatNodeViewer.svelte — page-level viewer (follows QueryNodeViewer pattern)
  • ChatMessage.svelte — message bubble with streaming support
  • ToolCallDisplay.svelte — collapsible card for tool executions
  • AiOnboardingDialog.svelte — first-launch modal (ACP vs local model)
  • Side nav AI item in sidebar

Reference Files

  • packages/core/src/behaviors/mod.rs — NodeBehavior trait
  • packages/core/src/models/core_schemas.rs — core schema definitions
  • packages/desktop-app/src/lib/plugins/core-plugins.ts — plugin registration
  • packages/desktop-app/src/lib/components/viewers/query-node-viewer.svelte — page-level viewer pattern
  • packages/desktop-app/src/lib/design/icons/registry.ts — ai-chat icon already registered

Dependencies

Related Issues

Activity

  1. malibio commented on Apr 3, 2026

    @malibio
    CollaboratorAuthor

    Scope Boundary: #1017 vs #1003

    #1017 (this issue) owns the chat experience:

    • AiChatNodeViewer.svelte (page-level viewer)
    • ChatMessage.svelte, ChatInput.svelte, ToolCallDisplay.svelte
    • AiOnboardingDialog.svelte (first-launch modal)
    • chatStore.ts (conversation state, write buffering, message cap)
    • Node reference decoration in assistant messages
    • aiChatNodePlugin in core-plugins.ts
    • AiChatNodeBehavior in behaviors/mod.rs
    • Core schema in core_schemas.rs
    • Side nav AI item

    #1003 owns agent/model management:

    • Agent selector, status bar
    • Model manager in Settings, model picker
    • agentStore.ts, modelStore.ts

    The AiChatNodeViewer consumes the agent selector and model picker from #1003.

    Backend Implementation Guide

    NodeBehavior Registration

    Read packages/core/src/behaviors/mod.rs:

    • BehaviorRegistry (around line 1050) — HashMap<String, Box<dyn NodeBehavior>>
    • BehaviorRegistry::new() registers all built-in types
    • Add AiChatNodeBehavior registration alongside others

    Core Schema

    Read packages/core/src/models/core_schemas.rs:

    • get_core_schemas() returns all built-in schemas
    • Follow the pattern of existing schemas (task, date, query) for field definitions
    • Properties: provider, model, status, last_active, context_tokens, created_nodes, messages

    Validation in NodeService

    Read packages/core/src/services/node_service.rs:

    • validate_playbook_rules() (line 1784) — shows how type-specific validation is called on create/update
    • You'll need similar validation for ai-chat properties (valid provider, valid status, message structure)
  2. malibio commented on Apr 3, 2026

    @malibio
    CollaboratorAuthor

    Archived Design System Reference

    There is a comprehensive archived chat UI implementation guide with full Svelte component code, CSS styling, and state management patterns:

    • Chat UI Implementation Guide: nodespace-docs/archived/architecture/ai/chat-ui-implementation-guide.md

      • ChatPanel.svelte — main container with provider selector, chat history, input
      • ChatHistory.svelte — scrollable message list with auto-scroll on new messages
      • AssistantMessage.svelte — with inline node reference parsing and NodePill rendering
      • ToolCallBlock — collapsible tool execution display (pending/success/error states)
      • ChatInput — with @mention autocomplete integration
      • NodePill.svelte — type-aware clickable node badges with loading/error states
      • node-reference-parser.ts — parses nodespace:// links and raw UUIDs from content
      • ChatState interface — conversation entries, streaming state, UI preferences
      • Full CSS with design tokens (--surface-1, --space-4, --text-muted, etc.)
    • Node Reference System in Chat: nodespace-docs/archived/architecture/ai/node-reference-system-in-chat.md

      • Two-way reference flow (user @mentions → agent nodespace:// links)
      • mentions relationship creation
      • NodePill display formats per node type

    Note: These archived docs assume child-node message storage (superseded by ADR-028). The UI component patterns, CSS, and node reference system are still directly applicable — only the data loading needs to change from "fetch child nodes" to "read properties.messages[]".

    Use these as the starting point for AiChatNodeViewer implementation.

  3. malibio commented on Apr 3, 2026

    @malibio
    CollaboratorAuthor

    Baseline: 123 test files, 3816 tests passed. Starting implementation.

  4. self-assigned this
    on Apr 3, 2026
  5. added 2 commits that reference this issue on Apr 3, 2026
    ff8f824
    148e323
  6. added a commit that references this issue on Jun 22, 2026
    f664ef5
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