Added comprehensive test suite documenting and verifying query execution plans
for all SQL queries in StatsDB. The tests analyze index usage, identify slow
queries, and document optimization decisions.
Key additions:
- 30 new tests in "EXPLAIN QUERY PLAN verification for SQL query optimization" section
- Query plan documentation for getQueryEvents, getAggregatedStats, getAutoRunSessions, getAutoRunTasks
- Analysis of INSERT, UPDATE, and DELETE query performance
- Index coverage analysis for all 7 database indexes
- Identified slow queries: byDay (date() overhead), exportToCsv (memory), clearOldData (bulk deletes)
- Verification that NO full table scans occur in production queries
- Optimization recommendations summary with rationale for implemented vs. not implemented
All 371 tests pass.
Add comprehensive test suite "Performance profiling: dashboard load time
with 100k events" with 26 new tests that profile and document the
performance characteristics of the Usage Dashboard loading with ~1 year
of data (approximately 100,000 query events).
Test Coverage:
- Query structure verification (4 SQL queries, indexed columns)
- 100k event simulation with compact result verification
- Memory constraints (result set <50KB, no raw data loading)
- Query timing documentation (55-175ms typical load time)
- Index usage verification (idx_query_start_time, etc.)
- Edge cases (zero duration, max integers, sparse data)
- Parallel execution with getDatabaseSize
- exportCsv vs getAggregatedStats comparison
Key Findings Documented:
- All aggregation queries use start_time index for O(log N) seeks
- Aggregation happens entirely in SQLite, not JavaScript
- Result set is ~10-20KB regardless of input size
- Dashboard load time: 55-175ms typical, 200-300ms worst case
- Added database size indicator next to time range info in footer
- Uses Database icon (lucide-react) with tooltip "Stats database size"
- Formats size with appropriate units (B, KB, MB, GB) using formatDatabaseSize() helper
- Fetches database size alongside stats data using Promise.all() for parallel loading
- Updates in real-time when stats are refreshed
Added 8 new tests verifying:
- Database size display on modal open
- Fetching database size alongside stats data
- Real-time updates on data refresh
- Formatting for bytes, KB, MB, GB
- Icon and tooltip presence
- Null/zero size handling
All 59 tests in UsageDashboardModal.test.tsx pass
Implemented conditional VACUUM for the stats database when it exceeds 100MB:
- Added getDatabaseSize() method to check database file size in bytes
- Added vacuum() method to run SQLite VACUUM command and report bytes freed
- Added vacuumIfNeeded(threshold) method for conditional vacuum based on size
- Initialize() now calls vacuumIfNeeded() after database is ready
- Default threshold is 100MB (104857600 bytes)
- Vacuum failure does not block app startup (graceful error handling)
- Comprehensive logging for vacuum operations
Added 22 comprehensive tests covering:
- getDatabaseSize edge cases
- vacuum() execution and error handling
- vacuumIfNeeded() threshold logic
- Integration with initialize()
- Return type verification
All 287 stats-db tests pass, full test suite (13,208 tests) passes.
Created test suite at src/__tests__/renderer/fonts-and-sizing.test.ts
with 41 tests verifying font and sizing render correctly across platforms:
- Default font stack with cross-platform fallbacks (macOS, Windows, Linux)
- Font size scaling via document root (rem-based sizing)
- Platform-specific font availability documentation
- Font smoothing settings verification
- Common monospace fonts panel configuration tests
- Custom font handling and special character support
- Mobile/web font handling (ui-monospace, px sizing)
- Chart and graph node font sizing ranges
- Accessibility font sizing (WCAG compliance, large text support)
Created test suite at src/__tests__/renderer/hooks/keyboard/useKeyboardShortcutHelpers.test.ts
with 53 tests verifying that keyboard shortcuts work correctly on both macOS (Cmd)
and Windows/Linux (Ctrl).
Tests cover:
- Meta key equivalence (treats Cmd and Ctrl as equivalent)
- Shift/Alt modifier combinations
- Arrow key, Backspace, number key, and slash shortcuts
- Tab shortcut cross-platform support
- Case insensitivity and edge cases
- Complete verification of actual app shortcuts
- Add normalizePath() utility function that converts Windows backslashes to forward slashes
- Apply path normalization to insertQueryEvent, getQueryEvents, insertAutoRunSession, and updateAutoRunSession
- Add 31 comprehensive tests covering path normalization for various scenarios:
- Windows/Unix paths, UNC paths, mixed slashes
- Null/undefined handling, empty strings, special characters
- Unicode characters, long paths, edge cases
- Ensures paths stored in database are platform-independent for cross-platform data portability
Added comprehensive tests documenting how file deletions are handled:
- File watcher captures 'unlink' events and batches within 500ms debounce
- Graph rebuild excludes deleted files (no node created)
- Edges to/from deleted nodes are automatically removed (buildGraphData
only creates edges for files that exist)
- diffNodes identifies removed nodes for exit animation
- Position preservation works for remaining nodes after deletion
- External link nodes removed when all referencing docs deleted
- Multiple simultaneous deletions (folder delete) handled via batching
The file deletion feature was already fully implemented; these tests
document the expected behavior and edge cases for maintainability.
Verified that file renames are handled gracefully by the existing
debouncing architecture. Chokidar emits unlink + add events for
renames (by design), which are batched within the 500ms debounce
window. The graph rebuild correctly removes the old node and adds
the new node with smooth animations.
Added comprehensive documentation explaining the rename handling
flow and 9 new tests covering various rename scenarios including
cross-directory moves, multiple concurrent renames, and case-only
renames on macOS.
- Add three-tier position priority system: saved store > previousNodesRef > fresh layout
- Save positions after initial layout (ensures positions preserved on first file change)
- Preserve positions from previousNodesRef during real-time updates before any user interaction
- Add 11 comprehensive tests documenting position preservation behavior
Add real-time file watching to the Document Graph feature so the
visualization automatically updates when markdown files are added,
modified, or deleted.
Implementation details:
- Created new documentGraph.ts IPC handler using chokidar for
cross-platform file watching
- Added 500ms debounce delay (longer than autorun's 300ms since
graph rebuilds are more expensive)
- Batch file change events to minimize IPC traffic and rebuilds
- Ignore dotfiles, node_modules, dist, build, and .git directories
- Only process .md file changes
- Watcher automatically starts when graph modal opens and stops
when it closes
Files changed:
- src/main/ipc/handlers/documentGraph.ts (new)
- src/main/ipc/handlers/index.ts (register handlers)
- src/main/preload.ts (expose IPC bridge)
- src/renderer/global.d.ts (TypeScript types)
- src/renderer/components/DocumentGraph/DocumentGraphView.tsx
(subscribe to file changes)
- src/__tests__/main/documentGraph-watcher.test.ts (new, 18 tests)
Adds 8 new tests to verify the end-to-end flow of real-time updates when
the Usage Dashboard is open while an AI session is actively recording stats:
- Dashboard updates data when stats:updated is received
- Multiple rapid stats updates are debounced into single fetch
- Stats updates during Auto Run session correctly update dashboard
- "Updated" indicator appears when real-time data arrives
- Dashboard continues working after multiple update cycles
- Closing modal during active session properly unsubscribes
- Reopening modal after close re-establishes subscription
- Tests use fake timers to precisely verify 1-second debounce behavior
All 49 tests in UsageDashboardModal.test.tsx pass.
Adds 16 new tests to verify that concurrent writes don't cause database
locking issues in the stats database:
- WAL mode verification (enabled for concurrent access)
- Rapid sequential writes (10 inserts each to all 3 tables)
- Concurrent writes via Promise.all (cross-table, 20 concurrent, mixed ops)
- Interleaved read/write operations (no blocking)
- High-volume concurrent writes (50 and 100 writes without data loss)
- Unique ID generation under concurrent load
- Database connection stability during intensive operations
better-sqlite3 provides inherent locking safety through synchronous
operations, and WAL mode enables concurrent reads during writes.
- Added "Updated" badge with pulsing dot next to dashboard title when real-time data arrives
- Badge appears for 3 seconds after both automatic real-time updates and manual refresh
- Implemented pulse-fade animation (badge fades out) and pulse-dot animation (dot pulses 3 times)
- Theme-aware: badge uses accent color for text, background, and pulsing dot
- Accessibility: animations disabled for users with prefers-reduced-motion
- Added 6 comprehensive tests verifying indicator behavior, animation styling, and theme integration
- DurationTrendsChart: Added transition animations to SVG line path, area
path, and data points (cx, cy) for smooth position updates when data changes
- SourceDistributionChart: Added transition animations to donut arc paths
for smooth segment resizing during data updates
- AgentComparisonChart: Added transition animations to horizontal bar widths
for smooth width changes when data updates (replaced Tailwind classes with
inline styles for consistent timing)
- ActivityHeatmap: Added transition animations to cell background colors
for smooth intensity changes during data updates
All animations use 0.5s duration with cubic-bezier(0.4, 0, 0.2, 1) easing
for natural, smooth motion. Hover effects use faster 0.15-0.2s transitions.
Added 13 new tests verifying animation CSS is correctly applied:
- 4 tests for DurationTrendsChart smooth animations
- 3 tests for SourceDistributionChart smooth animations
- 3 tests for AgentComparisonChart smooth animations
- 3 tests for ActivityHeatmap smooth animations
Updated existing tests to match new CSS class structure (removed transition-all
duration-300 Tailwind classes in favor of inline transition styles).
Verify that real-time data updates don't cause visual flickering by:
- Ensuring data remains visible during refresh (no loading state flicker)
- Verifying debounce subscription pattern is correctly established
- Confirming refresh button doesn't show loading spinner that hides data
- Testing unsubscription from stats updates when modal closes
- Validating content persists when refresh is triggered after initial load
- Ensuring time range changes trigger new fetches correctly
- Checking debounce batches rapid stats:updated events
All 36 tests in UsageDashboardModal.test.tsx pass.
Verifies the stats:updated event is correctly broadcast after each database
write operation (record-query, start-autorun, end-autorun, record-task) and
NOT broadcast for read-only operations (get-*, export-csv).
Tests include:
- Broadcast verification for all write operations
- Graceful handling when window is null or destroyed
- Correct timing (broadcast after DB write completes)
- Multiple sequential writes broadcast correctly
- Updated scanMarkdownFiles() in graphDataBuilder.ts to throw error when
root directory fails to be read (permission denied, path doesn't exist, etc.)
- Subdirectory failures still continue gracefully with console.warn
- Error message includes original error details for user debugging
- Error is caught and displayed via existing error UI with Retry button
- Added 2 new tests covering root directory failure scenarios
- All 152 DocumentGraph tests pass
- Add ProgressData interface and ProgressCallback type to graphDataBuilder.ts
- buildGraphData now accepts onProgress callback reporting:
- Scanning phase: number of directories scanned
- Parsing phase: current/total files with currentFile name
- Update DocumentGraphView to display progress:
- "Scanning directories... (X scanned)" during scanning
- "Parsing documents... X of Y" with animated progress bar
- Current file shown below progress bar (truncated, hover for full)
- Add 7 tests for progress callback in graphDataBuilder.test.ts
- Add 8 tests for progress UI in DocumentGraphView.test.tsx
- Updated loading spinner to use Loader2 icon (matching codebase patterns)
- Changed spinner color from textDim to accent for better visibility
- Repositioned text below spinner with proper gap spacing
- Added 3 tests documenting loading/empty/error state behavior
- Added useDebouncedCallback from hooks/utils for debounce functionality
- Added GRAPH_REBUILD_DEBOUNCE_DELAY constant (300ms) for consistent timing
- Created debounced loadGraphData for settings-triggered rebuilds
- Initial modal open executes immediately (no delay for first load)
- Settings changes (external links toggle) are debounced to prevent rapid rebuilds
- Refresh button still executes immediately via direct loadGraphData() call
- Added cleanup effect to cancel pending debounced loads on unmount
- Added effect to reset initial mount tracking when modal closes
- Updated component docstring to document the performance optimization
- Added 6 new tests covering debounce behavior (133 DocumentGraph tests pass)
- Remove content field from ParsedFile interface to prevent storing raw file content in memory
- File content is now read, parsed for links/stats, then immediately discarded
- Add documentation comments explaining the lazy load optimization pattern
- Reduces memory footprint when processing large directories with many markdown files
Performance optimization for large directories:
- Added maxNodes and offset options to BuildOptions in graphDataBuilder.ts
- GraphData now returns totalDocuments, loadedDocuments, and hasMore for pagination
- DocumentGraphView loads 50 documents initially with "Load more" button
- Load more increments by 25 documents at a time
- Footer shows "X of Y documents" when not all are loaded
- Edges only created to loaded documents to prevent dangling edges
- Added 6 new tests for max nodes limit functionality (24 total in graphDataBuilder.test.ts)
- Enable onlyRenderVisibleElements prop in ReactFlow component
- Only renders nodes and edges visible in the viewport
- Reduces DOM elements and improves performance for large graphs
- Add 2 tests for performance optimizations
- Create NodeContextMenu component with Open, Copy Path/URL, and Focus actions
- Wire onNodeContextMenu and onPaneClick handlers in DocumentGraphView
- Add handleFocusNode to center view on selected node using setCenter
- Update footer hint to mention right-click functionality
- Add 20 unit tests for NodeContextMenu covering all actions and edge cases
Verified that node drag functionality was already implemented via React Flow's
useNodesState hook and onNodesChange handler. Added 3 new tests documenting the
drag behavior and position persistence integration:
- Tests verify useNodesState provides the expected API structure
- Tests verify position persistence via saveNodePositions/restoreNodePositions
- Tests document the React Flow integration pattern for drag updates
Total test count for DocumentGraph: 92 tests passing
- Add selectedNodeId state to track currently selected node
- Add handleSelectionChange callback using React Flow's onSelectionChange prop
- Update styledEdges to highlight connected edges with accent color
- Connected edges get increased stroke width (2.5px) and higher z-index
- Edges have smooth 0.2s transition animation for stroke and stroke-width
- Update test mock to include OnSelectionChangeFunc export
Implement force-directed and hierarchical layout algorithms for the
Document Graph visualization using d3-force and @dagrejs/dagre.
Features:
- Force-directed layout with configurable forces (charge, link, collision)
- Hierarchical (dagre) layout with TB/LR direction options
- Smooth animated transitions between layouts (20 frames, ease-out cubic)
- In-memory position persistence during session
- Position saving on node drag and layout changes
Files added:
- src/renderer/components/DocumentGraph/layoutAlgorithms.ts
- src/__tests__/renderer/components/DocumentGraph/layoutAlgorithms.test.ts (28 tests)
Integration:
- Updated DocumentGraphView.tsx to use new layout algorithms
- Replaced simple grid layout with proper force/hierarchical layouts
- Added onNodeDragStop handler for position persistence
- Animation cleanup on unmount
Created the main graph container component with:
- React Flow canvas with custom DocumentNode and ExternalLinkNode types
- Controls panel: layout toggle, external links toggle, zoom, fit view
- MiniMap and Background with theme-aware colors
- Modal integration with layer stack (Escape handling)
- Loading, empty, and error states
- Document/external link opening callbacks
Also added DOCUMENT_GRAPH modal priority and integrated into App.tsx.
Create custom React Flow node for displaying external link domains with:
- Domain name display (www. stripped by graphDataBuilder)
- Link count badge (shown when >1 links to same domain)
- Dashed border to distinguish from document nodes
- Globe and external-link icons from lucide-react
- Multi-URL tooltip showing all URLs to that domain
- Compact size (160px max-width) with pill-shaped design
Includes 19 unit tests covering rendering, selection states,
theme integration, and React Flow handle positioning.
- Create custom React Flow node for displaying markdown documents
- Display title, stats (line count, word count, size), and description
- Theme-aware styling with selection and hover states
- Add comprehensive test suite (18 tests)
Implements graphDataBuilder.ts which scans directories for markdown files,
parses their links and stats, and builds React Flow compatible node/edge
structures for the Document Graph visualization.
Key features:
- Recursive directory scanning with sensible exclusions (node_modules, .git, etc.)
- Integration with existing markdownLinkParser and documentStats utilities
- Support for optional external link nodes with domain deduplication
- Type guards for document vs external link node discrimination
- Full test coverage (18 tests)
- Added documentStats.ts with DocumentStats interface and computeDocumentStats()
- Computes line count, word count, file size (formatted), title, and description
- Title extraction: prefers front matter, falls back to H1 heading, then filename
- Description extraction: checks 13 common keys (description, overview, abstract, etc.)
- Includes formatFileSize() helper for human-readable sizes (B, KB, MB, GB, TB)
- Test suite: 45 tests covering all functions and edge cases
Implement markdownLinkParser.ts utility that extracts:
- Wiki-style links ([[filename]] and [[path|display]])
- Standard markdown links ([text](path.md))
- External URLs with domain extraction
- YAML front matter parsing
Regex patterns aligned with existing remarkFileLinks.ts for consistency.
Includes comprehensive test suite with 31 tests covering all link types,
front matter parsing, deduplication, and edge cases.
- Add GitGraph icon button to FileExplorerPanel, positioned left of the eye icon
- Add "Document Graph" tooltip on hover
- Add isGraphViewOpen state in App.tsx for controlling graph modal visibility
- Wire onOpenGraphView callback through RightPanel → FileExplorerPanel
Install reactflow@11.11.4, @dagrejs/dagre@1.1.8, d3-force@3.0.0, and
@types/d3-force@3.0.10 for the upcoming Document Graph visualization
feature in Phase 3 of the Global Stats & Graphing implementation.
- Create EmptyState component with theme-aware styling
- Features BarChart3 icon with decorative SVG bars
- Supports customizable title and message props
- Default message: "No usage data yet. Start using Maestro to see your stats!"
- Update UsageDashboardModal to use new component
- Add comprehensive test suite (16 tests)
- Add dialog:saveFile IPC handler in system.ts for native save dialog
- Expose saveFile API via preload.ts and global.d.ts types
- Update UsageDashboardModal to use save dialog instead of auto-download
- User can now choose file location and name for CSV exports
- Added comprehensive tests for save dialog handler and export flow
- Updated test mocks in setup.ts and UsageDashboardModal.test.tsx
Add comprehensive Auto Run statistics section for the Usage Dashboard modal:
- Total auto run sessions count
- Tasks completed vs attempted with success rate percentage
- Average tasks per session metric
- Average session and task durations
- Mini bar chart showing tasks completed over time (last 14 days)
- Loading, error, and empty state handling
- Real-time updates via stats API subscription
- Theme-aware styling with inline styles
- 29 comprehensive tests covering all functionality
Create SummaryCards component that displays key metrics in card format:
- Total queries (with K/M suffix formatting)
- Total time (Xh Xm format)
- Average duration (Xm Xs format)
- Most active agent (by query count)
- Interactive vs Auto ratio (percentage)
Each card includes:
- Themed icon with accent-tinted background
- Computed/derived values with memoization
- Full theme support (light/dark)
- Accessibility features (title tooltips)
Includes comprehensive test suite with 30 tests covering:
- All metric rendering
- Number and duration formatting
- Agent/ratio calculations
- Theme support
- Edge cases (empty data, large numbers)