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:
- Validate artifact content
- Generate sandbox HTML with CSP
- Transform JSX using Babel
- Execute in isolated iframe
- 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:
- Global error listeners in sandbox
- Component-level error boundaries
- Network failure handling
- 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 Type | Viewer Component | Features |
---|---|---|
PDFViewer | PDFTron integration, annotations | |
DOCX | DOCXViewer | Office document rendering |
XLSX | XLSXViewer | Spreadsheet with multiple sheets |
CSV | CSVViewer | Tabular data with sorting |
JSON | JSONViewer | Syntax highlighting, folding |
Images | ImageViewer | Responsive display, zoom |
Code Files | CodeViewer | 20+ language support |
Markdown | MarkdownViewer | MDX support, Mermaid integration |
Extension Guidelines
Adding New Viewers
- Create Viewer Component:
const NewArtifactViewer: React.FC<ArtifactViewerProps<NewArtifact>> = ({
artifact, onError
}) => {
// Implementation
};
- Update Knowledge Item Types:
interface INewKnowledgeItem extends IBaseKnowledgeItem {
type: 'new-type';
content: NewArtifact;
}
- Register in KnowledgeViewer:
case 'new-type':
return <NewArtifactViewer artifact={item.content} />;
- 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