Apps
Apps are the core building blocks of the Fiberwise AI platform. They are sophisticated web applications that seamlessly integrate frontend components, dynamic data models, AI agents, and custom functions to deliver intelligent, interactive user experiences.
What are Fiberwise Apps?
Fiberwise apps are **JavaScript bundle applications** consisting of Web Components, manifest-defined data models, and optional agents/functions. Each app is defined by an app_manifest.yaml
file that declaratively configures the app's structure, data models, agents, and UI routes. Apps are loaded dynamically by the platform and run as integrated components within the Fiberwise ecosystem.
Core Capabilities of Fiberwise Apps:
- Manifest-Driven Architecture: Single YAML file defines app metadata, data models, agents, and routes
- Dynamic Data Models: Manifest-defined database schemas with automatic CRUD APIs via fiber.data
- Web Components: ES6+ modules using Shadow DOM with separate .html, .css, .js files
- Agent Integration: Optional Python agents defined in manifest for AI functionality
- SDK Integration: Built-in FiberWise SDK access via FIBER instance
- Route-Based Navigation: Manifest-defined routes mapping paths to components
- Local Development: Direct file editing with optional build tools
App Architecture & Structure
Every Fiberwise app follows a standardized directory structure that supports modern development practices:
my-fiberwise-app/
โโโ app_manifest.yaml # App definition and configuration
โโโ index.js # Main entry point with initialize() and render() functions
โโโ [main-component].js # Primary UI component (Web Component class)
โโโ [main-component].html # Component template (imported as ?raw)
โโโ [main-component].css # Component styles (imported as ?inline)
โโโ [other-components].js # Additional components
โโโ agents/ # Python agents (optional)
โ โโโ my-agent.py
โโโ functions/ # Python functions (optional)
โ โโโ my-function.py
โโโ package.json # Build dependencies (optional - for build tools)
โโโ vite.config.js # Build configuration (optional)
โโโ node_modules/ # NPM dependencies (if using build tools)
โโโ dist/ # Build output (if using build tools)
Key Architecture Principles
- Manifest-Driven: All app configuration defined in app_manifest.yaml
- Web Components: Custom elements with Shadow DOM encapsulation
- File-Based Structure: Separate .html, .css, .js files imported as modules
- Platform Integration: Standard initialize(appBridge, manifest) and render(mountPoint) functions
- SDK Access: Built-in FIBER SDK instance for platform APIs
- Optional Build Tools: Can use Vite for development, but not required
App Manifest Structure
The app_manifest.yaml
defines your app's configuration, data models, agents, and UI routes in a simple, declarative format:
# Real Fiberwise App Manifest Example
app:
name: Activation Chat
app_slug: activation-chat
version: 0.0.29
description: A chat application that uses agent activations and dynamic data as the message store
entryPoint: index.js
icon: fas fa-comments
category: simple
publisher: FiberWise
# Dynamic Data Models - Auto-generated database tables
models:
- name: Chat
model_slug: chats
description: Chat session container with metadata
fields:
- name: Chat ID
field_column: chat_id
type: uuid
required: true
is_primary_key: true
description: Primary key used in agent context
- name: Title
field_column: title
type: string
required: true
default: "New Chat"
- name: Settings
field_column: settings
type: json
default: {}
description: Chat-specific configuration
- name: Created At
field_column: created_at
type: timestamp
default: CURRENT_TIMESTAMP
is_system_field: true
- name: Message
model_slug: messages
fields:
- name: Message ID
field_column: message_id
type: uuid
is_primary_key: true
- name: Chat Reference
field_column: chat_id
type: uuid
required: true
relatedModelSlug: chats
- name: Content
field_column: content
type: text
required: true
- name: Role
field_column: role
type: string
required: true
default: "user"
# App Routes and Navigation
routes:
- path: /
component: chat-app
title: Chat Interface
icon: fas fa-comments
- path: /settings
component: chat-settings
title: Settings
icon: fas fa-cog
isOverlay: true
# AI Agents integrated with the app
agents:
- name: chatAgent
description: Advanced conversational AI with context awareness
agent_type_id: llm
version: 2.0.0
input_schema:
type: object
properties:
prompt:
type: string
description: User message
context:
type: object
description: Chat context and history
output_schema:
type: object
properties:
content:
type: string
metadata:
type: object
# Custom Functions for data processing
functions:
- name: messageProcessor
description: Process and analyze chat messages
version: 1.0.0
input_schema:
type: object
properties:
message:
type: string
chat_id:
type: string
output_schema:
type: object
properties:
processed_message:
type: string
sentiment:
type: string
implementation: |-
async def run(input_data):
message = input_data.get('message', '')
# Process message logic here
return {
'processed_message': message.strip(),
'sentiment': 'neutral'
}
is_async: true
# Automated data processing pipelines (optional)
pipelines:
- id: message_processing_pipeline
name: Chat Message Processing
description: Parallel processing pipeline for messages
trigger:
type: data_event
config:
model: messages
event: create
nodes:
- id: process_message
type: function_executor
config:
function_id: messageProcessor
- id: sentiment_analysis
type: agent_executor
config:
agent_id: sentimentAgent
- id: notification_handler
type: function_executor
config:
function_id: notificationHandler
edges:
- source: process_message
target: sentiment_analysis
- source: sentiment_analysis
target: notification_handler
โ Complete UnifiedManifest API Reference
UnifiedManifest Advantages
- Single Source of Truth: All app components defined in one file
- Version Validation: Semantic versioning enforced across all components
- Relationship Modeling: Clear relationships between data models
- Component Orchestration: Pipelines for automated data processing and event handling
- Development Efficiency: Reduced configuration overhead
Data Models
Fiberwise apps use structured data models with automatic user isolation, system fields, and database integration. Models are defined in your app manifest and provide secure, type-safe data storage.
๐ Complete Data Models Guide
For comprehensive information about data models, field types, user isolation, and advanced features, see the dedicated Data Models documentation.
Quick Example
models:
- name: Task
model_slug: tasks
user_isolation: enforced # โ
Automatic user data protection
fields:
- name: Task ID
field_column: task_id
type: GENERATED_UUID
required: true
is_primary_key: true
- name: Title
field_column: title
type: string
required: true
# System fields automatically added
- name: User ID
field_column: user_id
type: integer
default: CURRENT_USER
is_system_field: true
SDK Integration
// Simple data operations with automatic user isolation
import { FIBER } from './index.js';
// Create records - user_id automatically assigned
const task = await FIBER.data.create_item('tasks', {
title: 'Complete project documentation',
priority: 2
// user_id, created_at automatically populated
});
// Query user's data - automatically filtered by user_id
const myTasks = await FIBER.data.list_items('tasks', {
page: 1,
limit: 20
// No need to filter by user - automatic isolation
});
Key Features
- Automatic User Isolation:
user_isolation: enforced
provides database-level protection - Rich Field Types:
GENERATED_UUID
,string
,integer
,json
, and more - System Fields: Automatic
user_id
,created_at
,updated_at
management - Database Integration: Auto-generated schemas and REST APIs
- Type Safety: Validation, constraints, and relationship support
Learn More About Data Models
For detailed information about field types, validation, relationships, user isolation, and advanced features, visit the complete Data Models Guide.
Security Implementation Status
โ Currently Available: Enforced User Isolation
- โ
User Tracking:
user_id
field automatically populated - โ
System Fields:
is_system_field("user_id")
implementation complete - โ Database Isolation: All queries automatically filtered by user_id
- โ user_isolation: enforced - Complete security regardless of app code
- โ Auto-Assignment: user_id automatically assigned to all new records
โ Implemented: Database-Level User Isolation
- โ Database-level Filtering: Automatic row filtering by user_id
- โ user_isolation: enforced - Complete security regardless of app code
- โ Zero-Trust Security: Impossible for apps to access other users' data
- โ CURRENT_USER Resolution: Automatic user context in queries
- โ Complete Protection: Even malicious apps cannot bypass user isolation
๐ Active Security Guarantee
user_isolation: enforced
is now fully implemented and provides complete, unbreakable user data isolation:
- โ Database-enforced: All queries automatically include user_id filtering
- โ Application-independent: Security enforced even if app code is malicious
- โ Query-agnostic: All database operations automatically filtered by user context
- โ Zero configuration: Developers get security by default
โ Automatic Security Features
- Single user_id Field: Simplified to one system field for user ownership
- Automatic Filtering: No need to manually filter by user - handled automatically
- System Field Protection: user_id field automatically protected from modification
- Zero-Touch Security: User isolation works without any developer intervention
โ Automatic User Attribution
The user_id
system field is fully implemented and working. The platform automatically:
- Populates user_id: Automatically sets user_id on all new records
- Filters queries: All database operations are automatically filtered by user_id
- Protects field: user_id field cannot be modified by users
- Enforces isolation: Users can only access their own data
User-Scoped App Patterns
// Current Implementation: Application-level user filtering
// Example 1: Creating data - user attribution is automatic
const createUserChat = async (chatData) => {
// The user_id field is automatically set by the platform
const chat = await FIBER.data.create_item('chats', {
title: 'AI Strategy Discussion',
settings: { temperature: 0.7 }
// Note: created_by is automatically populated with current user ID
});
return chat;
// Returns: {
// item_id: "uuid-generated",
// data: { title: "AI Strategy Discussion", settings: {...} },
// created_by: 123, // โ Automatically set to current user
// created_at: "2025-08-14T10:30:00Z"
// }
};
// Example 2: Querying user's own data (current implementation)
const getUserChats = async () => {
// Current approach: Application must implement user filtering
// The platform tracks created_by but doesn't automatically filter
// Option A: Client-side filtering (if supported by SDK)
return await FIBER.data.list_items('chats', {
filters: {
// This would need to be implemented in the SDK to filter by created_by
},
sort: [{ field: 'created_at', order: 'desc' }]
});
// Option B: Server-side API endpoint with user context
// The dynamic_app_routes.py currently doesn't filter by created_by automatically
// but has access to current_user for implementing this filtering
};
// Example 3: Current security responsibility (developer must ensure)
const secureGetUserChats = async () => {
// Currently, security is the app developer's responsibility
// The created_by field exists but automatic filtering is not yet implemented
try {
const chats = await FIBER.data.list_items('chats');
// Without proper filtering, this could return all chats
// Developers must implement user-based filtering
return chats;
} catch (error) {
console.error('Error fetching chats:', error);
return [];
}
};
// Example 4: Planned future implementation with CURRENT_USER
const futureSecurePatterns = async () => {
// These patterns will work when RLS and CURRENT_USER resolution are implemented
// Future: Automatic user filtering regardless of query
const autoFilteredChats = await FIBER.data.list_items('chats', {
// Even without explicit filtering, RLS will restrict to current user
});
// Future: Explicit CURRENT_USER filter for clarity
const explicitUserChats = await FIBER.data.list_items('chats', {
filters: {
user_id: 'CURRENT_USER' // Platform will resolve to current user ID
}
});
return { autoFilteredChats, explicitUserChats };
};
๐ Current Implementation: Manifest Example
Here's how to configure user data tracking in your app manifest with the current implementation:
# Current manifest with user tracking support
app:
name: Chat Application
app_slug: chat-app
version: 1.0.0
# Data models with user attribution
models:
- name: Chat
model_slug: chats
description: User chat sessions with automatic user tracking
fields:
- name: Chat ID
field_column: chat_id
type: uuid
is_primary_key: true
- name: Title
field_column: title
type: string
required: true
default: "New Chat"
# Platform automatically handles created_by field
# Note: created_by is added to app_model_items table automatically
- name: Created At
field_column: created_at
type: timestamp
default: CURRENT_TIMESTAMP
is_system_field: true
description: "System-managed timestamp"
- name: Message
model_slug: messages
fields:
- name: Message ID
field_column: message_id
type: uuid
is_primary_key: true
- name: Chat Reference
field_column: chat_id
type: uuid
required: true
relatedModelSlug: chats
- name: Content
field_column: content
type: text
required: true
- name: Role
field_column: role
type: string
required: true
default: "user"
# Note: created_by tracking is handled automatically by the platform
# You don't need to define it in your manifest
Current Implementation Notes
- Automatic User Tracking:
user_id
field is automatically added to all tables - System Fields: Fields marked with
is_system_field: true
are tracked as system-managed - Database Schema: All app data goes into
app_model_items
with JSONBdata
field - User Context: Current user ID is available in API endpoints via
get_current_user
dependency - Security Note: Apps must implement user filtering logic in their queries
- Future Enhancement: CURRENT_USER resolution and automatic RLS are planned features
Database Schema Overview
-- Current platform database structure
CREATE TABLE app_model_items (
item_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
app_id UUID NOT NULL REFERENCES apps(app_id) ON DELETE CASCADE,
model_id UUID NOT NULL REFERENCES models(model_id) ON DELETE CASCADE,
created_by integer REFERENCES users(id), -- Automatic user tracking
data JSONB NOT NULL, -- Your app's field data
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- Essential indexes for performance
CREATE INDEX idx_app_model_items_model ON app_model_items (app_id, model_id);
CREATE INDEX idx_app_model_items_owner ON app_model_items (created_by);
CREATE INDEX idx_app_model_items_data_gin ON app_model_items USING GIN (data jsonb_path_ops);
Current vs. Planned Security Features
โ Currently Available
- User Tracking:
user_id
field automatically populated - System Fields:
is_system_field("user_id")
function implemented - User Context: Current user available in API endpoints
- Field Validation: Basic type checking and constraints
๐ง Planned Enhancements
- CURRENT_USER Resolution: Automatic user ID substitution in queries
- Row-Level Security: Database-enforced user data isolation
- user_isolation Settings: Declarative security modes in manifest
- Automatic Filtering: Platform-enforced user context in queries
Performance & Optimization
- Automatic Indexing: Primary keys, foreign keys, user_id fields, and frequently queried fields
- RLS Performance: Row-Level Security policies are optimized with proper indexing
- Query Optimization: Intelligent query planning and caching with user context
- Connection Pooling: Efficient database connection management
- Data Validation: Client and server-side validation for data integrity
- Security Overhead: Minimal performance impact from automatic security enforcement
๐ Planned Feature: Pipelines & Workflows
Fiberwise is developing powerful automation capabilities through pipelines (internal processing chains) and workflows (external orchestration systems). These will provide declarative ways to automate complex data processing and business logic.
Planned Automation Capabilities
๐ Pipeline Processing
Internally triggered chains of functions and agents for data processing and transformation.
๐ Data Automation
Automatically process data changes through customizable processing chains.
โก Internal Triggers
Respond to data model changes, agent completions, and system events automatically.
๐ Workflow Orchestration
External triggers for complex business processes with human-in-the-loop capabilities.
Example Pipeline Configuration
This shows the planned pipeline syntax that will be available in future releases:
# Future pipeline configuration in app_manifest.yaml
pipelines:
- id: message_processor
name: Smart Message Processing
description: Parallel processing of incoming messages with AI analysis
# Automatic triggers
trigger:
type: data_event
config:
model: messages
event: create
# Processing nodes (run in parallel where possible)
nodes:
- id: extract_metadata
type: function_executor
config:
function_id: messageMetaExtractor
input_mapping:
message: "$trigger.data.content"
- id: sentiment_analysis
type: agent_executor
config:
agent_id: sentimentAgent
input_mapping:
text: "$trigger.data.content"
- id: spam_detection
type: function_executor
config:
function_id: spamDetector
input_mapping:
content: "$trigger.data.content"
metadata: "$nodes.extract_metadata.output"
- id: priority_routing
type: conditional_router
condition: "$nodes.sentiment_analysis.output.urgency > 0.7"
config:
high_priority_handler: alertHandler
normal_handler: standardProcessor
- id: notification_dispatcher
type: function_executor
config:
function_id: notificationHandler
input_mapping:
priority: "$nodes.priority_routing.output.priority"
analysis: "$nodes.sentiment_analysis.output"
# Define execution flow
edges:
- source: extract_metadata
target: spam_detection
- source: sentiment_analysis
target: priority_routing
- source: priority_routing
target: notification_dispatcher
๐ง Planned Features: Advanced Orchestration
The Fiberwise platform is evolving to include more sophisticated orchestration capabilities.
๐ Workflows (Planned)
Higher-level orchestration that can include pipeline execution as individual workflow steps.
- External Triggers: Manual initiation, webhooks, scheduled events
- Pipeline Integration: Execute entire pipelines as single workflow nodes
- Human-in-Loop: Approval steps, manual data entry, decision points
- Business Processes: Multi-stage operations with conditional branching
Future Workflow Example:
workflows:
- id: content_approval_workflow
trigger:
type: external # Manual or webhook trigger
steps:
- id: content_processing
type: pipeline_execution
config:
pipeline_id: content_analysis_pipeline
- id: human_review
type: approval_step
config:
reviewers: ["[email protected]"]
- id: publish_content
type: function_execution
config:
function_id: contentPublisher
โก Enhanced Pipelines
Internal processing chains triggered by data events and system changes.
- Internal Triggers: Data model changes, agent completions, system events
- Node Dependencies: Controlled execution flow based on data availability
- Agent Integration: Seamless AI processing within automated workflows
- Data Transformation: Real-time data processing and routing
Current Implementation Status
Currently, automation is handled through:
- โ Functions: Reusable processing units
- โ Agents: AI-powered processing with activations
- โ System Fields: Automatic data population (CURRENT_USER, CURRENT_TIMESTAMP)
- โ SDK Integration: Real-time data synchronization and event handling
Pipelines and workflows are being developed to provide visual, declarative orchestration of these existing capabilities.
Modern Web Components & SDK Integration
Fiberwise apps use cutting-edge Web Components architecture with deep integration to the Fiberwise JavaScript SDK. Components are built using ES6+ modules, Shadow DOM encapsulation, and the standard Web Components API.
Component Architecture
// chat-app.js - Modern Web Component with Fiberwise SDK integration
import htmlTemplate from './chat-app.html?raw'; // Vite raw import
import cssStyles from './chat-app.css?inline'; // Vite inline import
import { FIBER } from './index.js'; // Fiberwise SDK instance
export class ChatApp extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
// Component state
this.currentChatId = null;
this.isLoading = false;
this.realtimeConnected = false;
}
async connectedCallback() {
// Initialize component when added to DOM
console.log('[ChatApp] Component mounted');
// Connect to real-time service
await this.connectRealtime();
// Load initial data
await this.loadInitialData();
// Render the component
this.render();
// Setup event listeners
this.setupEventHandlers();
}
async connectRealtime() {
try {
await FIBER.realtime.connect();
this.realtimeConnected = true;
// Listen for agent activation updates
FIBER.realtime.on('message', (message) => {
if (message.type === 'activation_completed') {
this.handleActivationUpdate(message);
}
});
console.log('[ChatApp] Real-time connection established');
} catch (error) {
console.error('[ChatApp] Real-time connection failed:', error);
this.realtimeConnected = false;
}
}
async sendMessage(content) {
if (!content.trim()) return;
try {
// Create chat if needed
if (!this.currentChatId) {
const chat = await FIBER.data.create_item('chats', {
title: content.substring(0, 30) + '...'
});
this.currentChatId = chat.item_id;
}
// Activate AI agent with context
const activation = await FIBER.agents.activate(
'chatAgent',
{
prompt: content,
history: await this.getChatHistory()
},
{
chat_id: this.currentChatId,
user_preferences: this.getUserPreferences()
},
{
provider_id: this.selectedProviderId,
temperature: 0.7,
max_tokens: 2048
}
);
console.log('[ChatApp] Agent activation:', activation.activation_id);
// Update UI immediately (real-time will handle completion)
this.showPendingMessage(content, activation.activation_id);
} catch (error) {
console.error('[ChatApp] Send message failed:', error);
this.showError('Failed to send message');
}
}
handleActivationUpdate(message) {
// Handle real-time agent completion
if (message.context?.chat_id === this.currentChatId) {
const activationId = message.activation_id;
// Update UI with agent response
this.updateActivationStatus(activationId, message.status);
if (message.status === 'completed') {
this.displayAgentResponse(message);
}
}
}
render() {
// Use Shadow DOM for encapsulation
this.shadowRoot.innerHTML = `
${htmlTemplate}
`;
// Bind dynamic content
this.bindEventHandlers();
this.updateConnectionStatus();
}
setupEventHandlers() {
// Component-to-component communication
this.addEventListener('message-sent', (e) => {
this.sendMessage(e.detail.content);
});
this.addEventListener('chat-selected', (e) => {
this.switchChat(e.detail.chatId);
});
}
disconnectedCallback() {
// Cleanup when component is removed
if (this.realtimeConnected) {
FIBER.realtime.disconnect();
}
}
}
// Register the custom element
customElements.define('chat-app', ChatApp);
SDK Instance Creation
The app entry point creates a shared SDK instance for all components:
// index.js - App entry point with SDK initialization
import fiber from 'fiberwise';
// Create shared FIBER SDK instance
export const FIBER = fiber.createInstance({
baseUrl: window.location.origin + "/api/v1"
});
// Required platform integration functions
export async function initialize(appBridge, manifest) {
console.log('[MyApp] Initializing with platform...');
// Initialize SDK with platform bridge
FIBER.initialize(appBridge, manifest);
// Perform any app-specific initialization
await setupAppConfiguration();
return true; // CRITICAL: Must return true
}
export function render(mountPoint) {
console.log('[MyApp] Rendering to mount point');
// Create and mount the main component
const appElement = document.createElement('chat-app');
mountPoint.appendChild(appElement);
}
// Import main component (must be at end)
import './chat-app.js';
Advanced Component Patterns
Inter-Component Communication
// Custom events for component coordination
class ChatInput extends HTMLElement {
sendMessage() {
const message = this.shadowRoot.querySelector('input').value;
// Emit custom event to parent
this.dispatchEvent(new CustomEvent('message-sent', {
detail: { content: message, timestamp: Date.now() },
bubbles: true
}));
}
}
class ChatList extends HTMLElement {
selectChat(chatId) {
// Update selection and notify parent
this.selectedChatId = chatId;
this.dispatchEvent(new CustomEvent('chat-selected', {
detail: { chatId },
bubbles: true
}));
}
}
State Management
// Centralized state management
class AppState {
constructor() {
this.state = {
currentChat: null,
messages: [],
agents: [],
providers: []
};
this.subscribers = new Set();
}
update(partialState) {
this.state = { ...this.state, ...partialState };
this.notify();
}
subscribe(callback) {
this.subscribers.add(callback);
return () => this.subscribers.delete(callback);
}
notify() {
this.subscribers.forEach(callback => callback(this.state));
}
}
Real-time Communication & Streaming
Fiberwise apps leverage advanced WebSocket infrastructure for instant bidirectional communication, agent activation streaming, and live data synchronization. This enables responsive, modern user experiences without polling or page refreshes.
WebSocket Connection & Event Handling
// Advanced real-time integration
import { FIBER } from './index.js';
class RealtimeEnabledApp extends HTMLElement {
constructor() {
super();
this.connectionStatus = 'disconnected';
this.reconnectAttempts = 0;
this.maxReconnectAttempts = 5;
}
async connectedCallback() {
await this.establishRealtimeConnection();
this.setupMessageHandlers();
}
async establishRealtimeConnection() {
try {
// Connect to Fiberwise real-time service
await FIBER.realtime.connect();
this.connectionStatus = 'connected';
console.log('โ
WebSocket connected');
this.updateConnectionIndicator(true);
// Reset reconnect counter on successful connection
this.reconnectAttempts = 0;
} catch (error) {
console.error('โ WebSocket connection failed:', error);
this.connectionStatus = 'failed';
this.updateConnectionIndicator(false);
// Implement reconnection logic
this.scheduleReconnect();
}
}
setupMessageHandlers() {
// Agent activation completion events
FIBER.realtime.on('message', (message) => {
switch (message.type) {
case 'activation_completed':
this.handleActivationCompleted(message);
break;
case 'activation_failed':
this.handleActivationFailed(message);
break;
case 'activation_streaming':
this.handleActivationStreaming(message);
break;
case 'data_update':
this.handleDataUpdate(message);
break;
default:
console.log('Unknown message type:', message.type);
}
});
// Connection state management
FIBER.realtime.on('connected', () => {
console.log('๐ Real-time service connected');
this.connectionStatus = 'connected';
this.updateConnectionIndicator(true);
});
FIBER.realtime.on('disconnected', () => {
console.log('๐ Real-time service disconnected');
this.connectionStatus = 'disconnected';
this.updateConnectionIndicator(false);
this.scheduleReconnect();
});
// Error handling
FIBER.realtime.on('error', (error) => {
console.error('๐จ Real-time error:', error);
this.showConnectionError(error);
});
}
// Handle agent activation completion with context filtering
handleActivationCompleted(message) {
console.log('๐ Activation completed:', message.activation_id);
// Filter messages by context (e.g., chat_id, user_id)
if (this.shouldProcessMessage(message)) {
// Update UI with agent response
this.displayActivationResult(message);
// Remove loading indicators
this.hideLoadingIndicator(message.activation_id);
// Scroll to new content
this.scrollToLatestMessage();
// Show success notification
this.showSuccessNotification('Response received');
}
}
// Handle streaming activation responses (chunk by chunk)
handleActivationStreaming(message) {
if (this.shouldProcessMessage(message)) {
// Append streaming content to UI
this.appendStreamingContent(
message.activation_id,
message.content_chunk,
message.is_final
);
// Auto-scroll during streaming
if (this.autoScrollEnabled) {
this.scrollToLatestMessage();
}
}
}
// Context-aware message filtering
shouldProcessMessage(message) {
// Only process messages relevant to current context
const context = message.context || {};
return (
context.chat_id === this.currentChatId ||
context.user_id === this.currentUserId ||
context.app_id === this.appId
);
}
// Advanced activation with streaming support
async activateAgentWithStreaming(agentId, inputData, context = {}, metadata = {}) {
try {
// Show immediate loading state
const loadingId = this.showLoadingIndicator('Processing...');
// Configure streaming activation
const streamConfig = {
enableStreaming: true,
chunkSize: 64, // Characters per chunk
streamDelay: 50 // Milliseconds between chunks
};
// Activate agent with enhanced context
const activation = await FIBER.agents.activate(
agentId,
inputData,
{
...context,
chat_id: this.currentChatId,
streaming: true
},
{
...metadata,
...streamConfig
}
);
// Track activation for real-time updates
this.trackActivation(activation.activation_id, loadingId);
console.log('๐ Streaming activation started:', activation.activation_id);
return activation;
} catch (error) {
console.error('๐ฅ Activation failed:', error);
this.showError('Failed to process request');
throw error;
}
}
// Fallback polling for unreliable connections
async enablePollingFallback() {
if (this.connectionStatus !== 'connected') {
console.log('๐ Enabling polling fallback');
this.pollingInterval = setInterval(async () => {
try {
const pendingActivations = await FIBER.activations.list({
status: 'pending',
context: { chat_id: this.currentChatId },
limit: 10
});
this.processPendingActivations(pendingActivations);
} catch (error) {
console.error('Polling failed:', error);
}
}, 2000); // Poll every 2 seconds
}
}
scheduleReconnect() {
if (this.reconnectAttempts < this.maxReconnectAttempts) {
this.reconnectAttempts++;
const delay = Math.pow(2, this.reconnectAttempts) * 1000; // Exponential backoff
console.log(`๐ Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts})`);
setTimeout(() => {
this.establishRealtimeConnection();
}, delay);
} else {
console.log('๐ซ Max reconnection attempts reached, enabling polling fallback');
this.enablePollingFallback();
}
}
disconnectedCallback() {
// Clean up connections and timers
if (this.connectionStatus === 'connected') {
FIBER.realtime.disconnect();
}
if (this.pollingInterval) {
clearInterval(this.pollingInterval);
}
}
}
Advanced Streaming Patterns
Progressive Message Display
// Progressive streaming display
appendStreamingContent(activationId, chunk, isFinal = false) {
const messageElement = this.getMessageElement(activationId);
if (!messageElement) {
// Create new message container for streaming
this.createStreamingMessage(activationId);
}
const contentElement = messageElement.querySelector('.message-content');
// Append chunk with smooth animation
contentElement.textContent += chunk;
// Add typing indicator effect
if (!isFinal) {
this.showTypingCursor(contentElement);
} else {
this.hideTypingCursor(contentElement);
this.markMessageComplete(activationId);
}
// Trigger auto-scroll with smooth animation
this.smoothScrollToBottom();
}
Multi-Agent Coordination
// Coordinate multiple agents in real-time
async handleMultiAgentWorkflow(userInput) {
// Stage 1: Analyze intent
const intentAnalysis = await FIBER.agents.activate('intentAnalyzer', {
input: userInput
});
// Stage 2: Route to specialized agents based on intent
const specialists = this.getSpecialistAgents(intentAnalysis.intent);
// Stage 3: Parallel processing with real-time updates
const promises = specialists.map(async (agentId) => {
return FIBER.agents.activate(agentId, {
input: userInput,
context: intentAnalysis.context
});
});
// Track all activations
const activations = await Promise.all(promises);
// Real-time handler will update UI as each agent completes
activations.forEach(activation => {
this.trackActivation(activation.activation_id, agentId);
});
}
Performance Optimization
- Connection Pooling: Shared WebSocket connections across components
- Message Batching: Combine multiple updates to reduce UI thrashing
- Context Filtering: Only process relevant messages for current app state
- Graceful Degradation: Automatic fallback to polling when WebSocket fails
- Memory Management: Cleanup event listeners and connections on component unmount
App Categories & Use Cases
The Fiberwise platform supports diverse application categories, each optimized for specific use cases and interaction patterns:
๐ฌ Communication & Chat
AI-powered chat applications with real-time messaging, multi-agent conversations, and persistent chat history.
- Real-time WebSocket messaging
- LLM provider integration
- Context-aware conversations
- Multi-chat session management
๐ Productivity & Workflow
Task automation, project management, and workflow optimization applications with AI assistance.
- Dynamic data models for tasks/projects
- Pipeline orchestration
- Agent-powered automation
- Dashboard and analytics
๐จ Creative & Content
Content generation, creative assistance, and media processing applications.
- Content generation pipelines
- Multi-modal AI integration
- Version control and iterations
- Collaborative editing
๐ง Developer Tools
Development utilities, testing frameworks, and platform management interfaces.
- Function testing and debugging
- Agent development tools
- API testing and monitoring
- System diagnostics
๐ Analytics & Intelligence
Data analysis, business intelligence, and AI-driven insights applications.
- Data pipeline integration
- Real-time analytics
- AI-powered insights
- Interactive dashboards
๐ฏ Demo & Education
Learning applications, platform demonstrations, and educational tools.
- Simple, focused functionality
- Clear user interactions
- Educational content
- Progressive complexity
Enterprise Application Patterns
๐ข Multi-Tenant SaaS Applications
Build applications that serve multiple organizations with isolated data and customizable workflows.
- Tenant-specific data models
- Role-based access control
- Customizable agent configurations
- Usage tracking and billing integration
๐ Integration & API Applications
Create applications that connect Fiberwise with external systems and services.
- OAuth and API key management
- Webhook handling and processing
- Data synchronization pipelines
- External service authentication
โก Real-time Collaborative Applications
Build applications that enable real-time collaboration between users and AI agents.
- Shared document editing
- Live presence indicators
- Conflict resolution
- Real-time notifications
Development & Deployment Lifecycle
Fiberwise apps follow a comprehensive development lifecycle with modern tooling, automated processes, and seamless deployment:
Development Setup
Initialize project structure with modern tooling
- Create
app_manifest.yaml
with UnifiedManifest structure - Setup
package.json
with Fiberwise SDK dependency - Configure
vite.config.js
with watch mode and hot reload - Implement main
index.js
with SDK initialization
fiber app init my-app --template=chat
Development & Testing
Iterative development with live reload and debugging
- Start development server with
fiber app dev --watch
- Real-time building to
app_bundles
directory - Live testing in Fiberwise platform at
localhost:5555
- WebSocket debugging and agent testing
fiber app dev --watch --verbose
Installation & Database Setup
Automated deployment with schema generation
- Install app via CLI or web interface
- Automatic database table creation from models
- API endpoint generation for all data models
- Agent and function registration
fiber app install . --verbose
Production Runtime
Full platform integration with monitoring
- Component loading and initialization
- Real-time WebSocket connections
- Agent activations and data synchronization
- Performance monitoring and logging
# App runs at: http://localhost:5555/apps/my-app
Updates & Maintenance
Version management with migration support
- Version bumping with semantic versioning
- Database schema migrations
- Component hot-swapping
- Rollback capabilities
fiber app update . --version=2.1.0 --migrate
Development Commands & Workflow
Development Commands
# Start development server with hot reload
fiber app dev --watch --verbose
# Build for production
npm run build
# Install dependencies
npm install
# Run tests (if configured)
npm test
Deployment Commands
# Install new app
fiber app install . --verbose
# Update existing app
fiber app update . --verbose
# Force update (ignore version check)
fiber app update . --force
# Version management
fiber app version --increment patch
Continuous Development Best Practices
๐ Hot Reload Development
Use fiber app dev --watch
for immediate feedback during development. Changes are automatically built and deployed to the development environment.
๐ Real-time Debugging
Monitor WebSocket connections, agent activations, and data model operations using browser dev tools and verbose logging.
๐งช Integration Testing
Test apps in the full Fiberwise environment with real databases, agents, and WebSocket connections before production deployment.
๐ฆ Version Control
Use semantic versioning for all components (app, agents, functions) with proper migration strategies for data model changes.
Development Best Practices
๐๏ธ Architecture Design
Build scalable, maintainable applications
- Use the UnifiedManifest structure for comprehensive app definition
- Design normalized data models with clear relationships
- Implement proper separation of concerns between components
- Plan for user data isolation from the start
โก Performance Optimization
Ensure responsive, efficient applications
- Use WebSocket connections for real-time updates
- Implement proper loading states and error handling
- Optimize bundle sizes with tree shaking and code splitting
- Cache frequently accessed data appropriately
๐ Security & Data Protection
Implement robust security measures
- Validate all user inputs on both client and server
- Use encrypted fields for sensitive data
- Implement proper access control and permissions
- Follow OWASP guidelines for web application security
๐ฑ User Experience Design
Create intuitive, accessible interfaces
- Design responsive layouts for desktop and mobile
- Provide clear feedback for all user actions
- Implement progressive loading for large datasets
- Follow accessibility standards (WCAG 2.1)
๐งช Testing & Quality Assurance
Ensure reliability through comprehensive testing
- Test components in isolation and integration
- Validate data model constraints and relationships
- Test real-time features under various network conditions
- Implement automated testing in CI/CD pipelines
๐ Documentation & Maintenance
Maintain clear, up-to-date documentation
- Document app purpose, setup, and usage clearly
- Maintain version changelogs and migration guides
- Include inline code comments for complex logic
- Create user guides and troubleshooting documentation
Code Quality Guidelines
JavaScript/Web Components
// โ
Good: Clear component structure with error handling
class MyComponent extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.state = {
loading: false,
error: null,
data: null
};
}
async connectedCallback() {
try {
await this.initialize();
} catch (error) {
console.error('[MyComponent] Initialization failed:', error);
this.handleError(error);
}
}
async initialize() {
this.setState({ loading: true });
// Connect to real-time service with error handling
try {
await FIBER.realtime.connect();
this.setupEventHandlers();
} catch (error) {
console.warn('Real-time connection failed, using polling fallback');
this.enablePollingFallback();
}
await this.loadInitialData();
this.setState({ loading: false });
this.render();
}
setState(newState) {
this.state = { ...this.state, ...newState };
this.render();
}
disconnectedCallback() {
// Clean up resources
this.cleanup();
}
}
Data Model Design
# โ
Good: Well-structured data model with relationships
models:
- name: Project
model_slug: projects
description: Main project container
fields:
- name: Project ID
field_column: project_id
type: uuid
is_primary_key: true
description: Unique project identifier
- name: Name
field_column: name
type: string
required: true
max_length: 255
description: Human-readable project name
- name: Settings
field_column: settings
type: json
default: {}
description: Project-specific configuration
- name: Owner
field_column: owner_id
type: uuid
required: true
relatedModelSlug: users
description: Project owner reference
- name: Created At
field_column: created_at
type: timestamp
default: CURRENT_TIMESTAMP
is_system_field: true
Error Handling Patterns
// Comprehensive error handling for app operations
class ErrorHandler {
static async handleAgentActivation(activationPromise) {
try {
const result = await activationPromise;
return { success: true, data: result };
} catch (error) {
console.error('Agent activation failed:', error);
if (error.status === 429) {
return {
success: false,
error: 'Rate limit exceeded. Please try again later.',
retryAfter: error.retryAfter
};
} else if (error.status === 401) {
return {
success: false,
error: 'Authentication failed. Please check your credentials.',
shouldReauth: true
};
} else {
return {
success: false,
error: 'An unexpected error occurred. Please try again.',
details: error.message
};
}
}
}
static async handleDataOperation(operation) {
try {
const result = await operation();
return { success: true, data: result };
} catch (error) {
console.error('Data operation failed:', error);
// Handle specific database errors
if (error.code === 'UNIQUE_VIOLATION') {
return {
success: false,
error: 'A record with this information already exists.'
};
} else if (error.code === 'FOREIGN_KEY_VIOLATION') {
return {
success: false,
error: 'Referenced record does not exist.'
};
} else {
return {
success: false,
error: 'Database operation failed. Please try again.'
};
}
}
}
}
Getting Started & Next Steps
Quick Start Commands
# Initialize a new Fiberwise app
fiber app init my-awesome-app --template=chat
# Start development with hot reload
cd my-awesome-app
fiber app dev --watch --verbose
# Install and test your app
fiber app install . --verbose
# Access your app at:
# http://localhost:5555/apps/my-awesome-app
Community & Resources
๐ GitHub Repository
Browse the complete Fiberwise codebase, including example apps and SDK implementations
View on GitHub๐ฌ Discord Community
Join our developer community for support, discussions, and collaboration
Join Discord๐ Developer Blog
Latest updates, tutorials, and insights from the Fiberwise development team
Read Blog