Skip to main content

Viewer Architecture

Overview

The Bike4Mind viewer system is a sophisticated content rendering architecture that handles multiple content types including files, AI-generated artifacts, and interactive components. The architecture follows a hierarchical factory pattern with security-first principles and type-safe implementations.

Architecture Diagram

graph TB
subgraph "User Interface Layer"
KV[KnowledgeViewer]
SC[SessionControls]
LM[LayoutManager]
end

subgraph "Artifact Viewers"
RAV[ReactArtifactViewer]
HAV[HtmlArtifactViewer]
SAV[SvgArtifactViewer]
MV[MermaidViewer]
end

subgraph "File Viewers"
PDF[PDFViewer]
DOC[DOCXViewer]
CSV[CSVViewer]
JSON[JSONViewer]
TEXT[TextViewer]
CODE[CodeViewer]
end

subgraph "Preview Components"
RAP[ReactArtifactPreviewCard]
GAP[GenericArtifactPreview]
end

subgraph "Security Layer"
SF[SandboxFrame]
CSP[ContentSecurityPolicy]
VM[ValidationMiddleware]
end

KV --> RAV
KV --> HAV
KV --> SAV
KV --> MV
KV --> PDF
KV --> DOC
KV --> CSV
KV --> JSON
KV --> TEXT
KV --> CODE

RAV --> SF
HAV --> SF
SF --> CSP
KV --> VM

RAP --> RAV
SC --> LM
LM --> KV

Core Components

KnowledgeViewer (Master Coordinator)

Location: packages/client/app/components/Knowledge/KnowledgeViewer.tsx

The central orchestrator that manages all content rendering:

interface KnowledgeItem = 
| IFileKnowledgeItem
| IQuestMasterKnowledgeItem
| ICodeKnowledgeItem
| IMermaidKnowledgeItem
| IReactKnowledgeItem
| IHtmlKnowledgeItem
| ISvgKnowledgeItem;

Key Responsibilities:

  • Content type detection and routing
  • Unified tabbed interface management
  • Layout control integration
  • Copy/download functionality
  • State management via Zustand
  • WebSocket streaming integration

Features:

  • Dynamic content loading with signed URL refresh
  • Responsive layout controls (vertical, horizontal, PiP)
  • Unified copy/download operations
  • Error boundary handling
  • Performance optimized with memoization

ReactArtifactViewer (Sandboxed Execution)

Location: packages/client/app/components/Knowledge/ReactArtifactViewer.tsx

Secure React component execution environment:

Security Features:

  • Sandboxed iframe execution
  • Content Security Policy enforcement
  • Allowed dependencies whitelist
  • Error boundary isolation

Supported Dependencies:

const ALLOWED_DEPENDENCIES = [
'react', 'lucide-react', 'recharts',
'mathjs', 'lodash', 'd3', 'papaparse', 'xlsx'
];

Execution Flow:

  1. Validate artifact content
  2. Generate sandbox HTML with CSP
  3. Transform JSX using Babel
  4. Execute in isolated iframe
  5. Handle runtime errors and messaging

Preview System

ReactArtifactPreviewCard provides compact artifact summaries:

  • Complexity indicators based on line count
  • Dependency visualization
  • Quick actions (copy, save, expand, preview)
  • Integration with session layout system

Data Flow

Content Loading Pipeline

sequenceDiagram
participant UI as User Interface
participant KV as KnowledgeViewer
participant SL as SessionLayout
participant FB as FabFile Backend
participant VR as Viewer Renderer

UI->>KV: Select content item
KV->>SL: Update layout state
KV->>FB: Check signed URL expiry
FB-->>KV: Refresh URL if needed
KV->>VR: Route to appropriate viewer
VR-->>KV: Render content
KV-->>UI: Display rendered content

Artifact Processing

sequenceDiagram
participant AI as AI Response
participant AP as ArtifactParser
participant KV as KnowledgeViewer
participant RAV as ReactArtifactViewer
participant SF as SandboxFrame

AI->>AP: Parse artifact from response
AP->>KV: Create artifact data
KV->>RAV: Route React artifact
RAV->>SF: Generate sandbox HTML
SF-->>RAV: Secure execution environment
RAV-->>KV: Rendered component

Security Architecture

Sandboxing Strategy

Iframe Sandboxing:

  • sandbox="allow-scripts" - Minimal permissions
  • Same-origin policy enforcement
  • CSP header injection
  • Script execution isolation

Content Security Policy:

const cspPolicy = `
default-src 'self' 'unsafe-inline' 'unsafe-eval'
https://unpkg.com https://cdn.tailwindcss.com;
script-src 'self' 'unsafe-inline' 'unsafe-eval'
https://unpkg.com https://cdn.tailwindcss.com;
`;

Dependency Management:

  • Whitelist-based dependency loading
  • CDN-only external resources
  • Version pinning for security
  • No arbitrary module loading

Error Handling

Layered Error Boundaries:

  1. Global error listeners in sandbox
  2. Component-level error boundaries
  3. Network failure handling
  4. Validation error reporting

Performance Optimizations

Dynamic Loading

const ReactArtifactViewer = dynamic(() => import('./ReactArtifactViewer'), {
ssr: false,
loading: () => <CircularProgress />
});

Memoization Strategy

const knowledgeItems = useMemo(() => {
// Expensive computation memoized
return processWorkBenchFiles(workBenchFiles, artifactData);
}, [artifactData, workBenchFiles]);

Signed URL Management

  • Automatic URL refresh before expiry
  • Efficient caching strategy
  • Batch URL refresh operations

Type System

Artifact Type Definitions

// Base artifact interface
interface Artifact {
id: string;
type: ArtifactType;
title: string;
content: string;
metadata?: ArtifactMetadata;
}

// React-specific extensions
interface ReactArtifact extends Artifact {
metadata: {
dependencies: string[];
props?: Record<string, unknown>;
hasDefaultExport: boolean;
};
}

Viewer Props Pattern

interface ArtifactViewerProps<T extends Artifact = Artifact> {
artifact: T;
onClose?: () => void;
onEdit?: (updatedArtifact: T) => void;
className?: string;
}

Integration Points

Session Management

  • Deep integration with SessionsContext
  • WorkBench file synchronization
  • Real-time streaming updates

Layout System

  • useSessionLayout hook integration
  • Multi-layout support (vertical, horizontal, PiP)
  • State persistence across sessions

WebSocket Integration

  • Real-time artifact updates
  • Streaming content support
  • Progress indication during generation

File Support Matrix

File TypeViewer ComponentFeatures
PDFPDFViewerPDFTron integration, annotations
DOCXDOCXViewerOffice document rendering
XLSXXLSXViewerSpreadsheet with multiple sheets
CSVCSVViewerTabular data with sorting
JSONJSONViewerSyntax highlighting, folding
ImagesImageViewerResponsive display, zoom
Code FilesCodeViewer20+ language support
MarkdownMarkdownViewerMDX support, Mermaid integration

Extension Guidelines

Adding New Viewers

  1. Create Viewer Component:
const NewArtifactViewer: React.FC<ArtifactViewerProps<NewArtifact>> = ({ 
artifact, onError
}) => {
// Implementation
};
  1. Update Knowledge Item Types:
interface INewKnowledgeItem extends IBaseKnowledgeItem {
type: 'new-type';
content: NewArtifact;
}
  1. Register in KnowledgeViewer:
case 'new-type':
return <NewArtifactViewer artifact={item.content} />;
  1. Add to Type Unions:
type KnowledgeItem = ... | INewKnowledgeItem;

Security Considerations

  • Always validate artifact content
  • Use sandbox attributes for untrusted content
  • Implement CSP for external resources
  • Error boundary isolation required

Best Practices

Performance

  • Use dynamic imports for heavy components
  • Implement proper memoization
  • Lazy load content when possible
  • Optimize re-render cycles

Security

  • Validate all user content
  • Use sandboxed execution environments
  • Implement proper CSP policies
  • Regular dependency audits

User Experience

  • Consistent loading states
  • Proper error messaging
  • Responsive design patterns
  • Accessible keyboard navigation

Testing Strategy

Unit Testing

  • Component isolation testing
  • Mock external dependencies
  • Error boundary validation
  • Performance benchmarking

Integration Testing

  • End-to-end content flow
  • Security boundary testing
  • Cross-browser compatibility
  • WebSocket integration testing

Troubleshooting Guide

Common Issues

Sandbox Execution Failures:

  • Check CSP policy configuration
  • Verify allowed dependencies
  • Review error console in iframe

Content Loading Issues:

  • Validate signed URL expiry
  • Check network connectivity
  • Review CORS configuration

Performance Problems:

  • Analyze React DevTools profiler
  • Review memoization usage
  • Check for memory leaks

Debug Tools

// Enable debug logging
const DEBUG_VIEWERS = process.env.NODE_ENV === 'development';

if (DEBUG_VIEWERS) {
console.log('Viewer state:', { item, isLoading, error });
}

Future Enhancements

Planned Features

  • Plugin architecture for custom viewers
  • Enhanced collaboration features
  • Improved caching strategies
  • Advanced security sandbox options

Performance Roadmap

  • Virtual scrolling for large content
  • Progressive loading strategies
  • Web Workers for heavy computations
  • Service Worker caching integration