Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(cos): add daily task trends chart to productivity dashboard

Adam Eivya41879e78cbf
diff --git a/.changelog/v0.12.x.md b/.changelog/v0.12.x.md
index 6b56c3ce50..ea85835799 100644
--- a/.changelog/v0.12.x.md
+++ b/.changelog/v0.12.x.md
@@ -30,13 +30,15 @@ This release adds branch management and automated release workflow capabilities
- **AI Insights**: Generates recommendations like "Peak Performance Hour" and "Most Productive Day" based on historical patterns
- **Milestones**: Tracks achievements like "Completed 100 tasks" or "7-day work streak"
- **Gamification**: Flame icon for active streaks, trophy icons for milestones, encouraging consistent productivity
+- **Daily Task Trends Chart**: Visual bar chart showing daily task completions over the last 30 days with success rate color coding, rolling averages, and trend analysis (volume/success rate trending up/down/stable)
**Server changes**:
-- `server/services/productivity.js` — New service with streak calculation, pattern analysis, and milestone tracking
-- `server/routes/cos.js` — Added `/productivity`, `/productivity/summary`, `/productivity/recalculate` endpoints
+- `server/services/productivity.js` — New service with streak calculation, pattern analysis, milestone tracking, daily history tracking, and trend calculations
+- `server/routes/cos.js` — Added `/productivity`, `/productivity/summary`, `/productivity/recalculate`, `/productivity/trends` endpoints
**Client changes**:
- `client/src/components/cos/tabs/ProductivityTab.jsx` — Full-featured productivity dashboard with collapsible sections
+- `client/src/components/cos/DailyTrendsChart.jsx` — Interactive bar chart component showing 30-day task completion history with tooltips, trend indicators, and success rate legend
- `client/src/components/cos/constants.js` — Added "Streaks" tab with Flame icon
- `client/src/services/api.js` — Added `getCosProductivity`, `getCosProductivitySummary`, `recalculateCosProductivity` functions
diff --git a/client/src/components/cos/DailyTrendsChart.jsx b/client/src/components/cos/DailyTrendsChart.jsx
new file mode 100644
index 0000000000..3451f454c8
--- /dev/null
+++ b/client/src/components/cos/DailyTrendsChart.jsx
@@ -0,0 +1,219 @@
+import { useState, useEffect, useCallback, useMemo } from 'react';
+import { TrendingUp, TrendingDown, Minus, Activity, RefreshCw, ChevronDown, ChevronRight } from 'lucide-react';
+import * as api from '../../services/api';
+
+/**
+ * DailyTrendsChart - Visualizes daily task completion trends
+ * Shows a bar chart of tasks completed per day with success rate overlay
+ */
+export default function DailyTrendsChart({ days = 30, initialExpanded = true }) {
+ const [data, setData] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [expanded, setExpanded] = useState(initialExpanded);
+
+ const loadData = useCallback(async () => {
+ setLoading(true);
+ const result = await api.getCosProductivityTrends(days).catch(() => null);
+ setData(result);
+ setLoading(false);
+ }, [days]);
+
+ useEffect(() => {
+ loadData();
+ }, [loadData]);
+
+ // Find max tasks for scaling
+ const maxTasks = useMemo(() => {
+ if (!data?.data) return 1;
+ return Math.max(...data.data.map(d => d.tasks), 1);
+ }, [data]);
+
+ const getSuccessRateColor = (rate) => {
+ if (rate >= 80) return 'bg-port-success';
+ if (rate >= 60) return 'bg-port-warning';
+ if (rate > 0) return 'bg-port-error';
+ return 'bg-port-border';
+ };
+
+ const getTrendIcon = (trend) => {
+ if (trend === 'increasing' || trend === 'improving') {
+ return <TrendingUp size={14} className="text-port-success" />;
+ }
+ if (trend === 'decreasing' || trend === 'declining') {
+ return <TrendingDown size={14} className="text-port-error" />;
+ }
+ return <Minus size={14} className="text-gray-500" />;
+ };
+
+ const getTrendLabel = (trend) => {
+ if (trend === 'increasing') return 'Volume trending up';
+ if (trend === 'decreasing') return 'Volume trending down';
+ if (trend === 'improving') return 'Success rate improving';
+ if (trend === 'declining') return 'Success rate declining';
+ return 'Stable';
+ };
+
+ if (loading) {
+ return (
+ <div className="bg-port-card border border-port-border rounded-lg p-4">
+ <div className="flex items-center justify-center py-8">
+ <RefreshCw className="w-5 h-5 animate-spin text-port-accent" />
+ </div>
+ </div>
+ );
+ }
+
+ if (!data?.data?.length) {
+ return (
+ <div className="bg-port-card border border-port-border rounded-lg p-4">
+ <div className="flex items-center gap-2 mb-3">
+ <Activity size={16} className="text-port-accent" />
+ <span className="font-medium text-white">Daily Task Trends</span>
+ </div>
+ <p className="text-sm text-gray-500">No task history available. Complete tasks to see trends.</p>
+ </div>
+ );
+ }
+
+ const { summary } = data;
+
+ return (
+ <div className="bg-port-card border border-port-border rounded-lg overflow-hidden">
+ {/* Header */}
+ <button
+ onClick={() => setExpanded(!expanded)}
+ className="w-full flex items-center justify-between p-4 hover:bg-port-bg/50 transition-colors"
+ >
+ <div className="flex items-center gap-2">
+ {expanded ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
+ <Activity size={16} className="text-port-accent" />
+ <span className="font-medium text-white">Daily Task Trends</span>
+ <span className="text-xs text-gray-500">({summary.days} days)</span>
+ </div>
+ <div className="flex items-center gap-3">
+ {/* Trend indicators */}
+ <div className="flex items-center gap-1">
+ {getTrendIcon(summary.volumeTrend)}
+ <span className="text-xs text-gray-400">{getTrendLabel(summary.volumeTrend)}</span>
+ </div>
+ </div>
+ </button>
+
+ {expanded && (
+ <div className="p-4 pt-0">
+ {/* Summary Stats */}
+ <div className="grid grid-cols-4 gap-2 mb-4">
+ <div className="text-center">
+ <div className="text-lg font-bold text-white">{summary.totalTasks}</div>
+ <div className="text-xs text-gray-500">Total Tasks</div>
+ </div>
+ <div className="text-center">
+ <div className="text-lg font-bold text-port-accent">{summary.activeDays}</div>
+ <div className="text-xs text-gray-500">Active Days</div>
+ </div>
+ <div className="text-center">
+ <div className="text-lg font-bold text-cyan-400">{summary.avgTasksPerActiveDay}</div>
+ <div className="text-xs text-gray-500">Avg/Day</div>
+ </div>
+ <div className="text-center">
+ <div className={`text-lg font-bold ${summary.avgSuccessRate >= 70 ? 'text-port-success' : summary.avgSuccessRate >= 50 ? 'text-port-warning' : 'text-port-error'}`}>
+ {summary.avgSuccessRate}%
+ </div>
+ <div className="text-xs text-gray-500">Success</div>
+ </div>
+ </div>
+
+ {/* Bar Chart */}
+ <div className="relative">
+ {/* Y-axis labels */}
+ <div className="absolute left-0 top-0 bottom-6 w-8 flex flex-col justify-between text-xs text-gray-600">
+ <span>{maxTasks}</span>
+ <span>{Math.round(maxTasks / 2)}</span>
+ <span>0</span>
+ </div>
+
+ {/* Chart area */}
+ <div className="ml-10 overflow-x-auto">
+ <div className="flex items-end gap-0.5 h-32" style={{ minWidth: `${data.data.length * 12}px` }}>
+ {data.data.map((day, idx) => {
+ const barHeight = (day.tasks / maxTasks) * 100;
+ const isToday = idx === data.data.length - 1;
+
+ return (
+ <div
+ key={day.date}
+ className="flex-1 flex flex-col items-center group relative"
+ style={{ minWidth: '10px', maxWidth: '24px' }}
+ >
+ {/* Bar */}
+ <div
+ className={`w-full rounded-t transition-all ${day.tasks > 0 ? getSuccessRateColor(day.successRate) : 'bg-port-border/30'} ${isToday ? 'ring-1 ring-port-accent' : ''}`}
+ style={{ height: `${Math.max(barHeight, day.tasks > 0 ? 8 : 2)}%` }}
+ />
+
+ {/* Tooltip */}
+ <div className="absolute bottom-full mb-2 left-1/2 -translate-x-1/2 hidden group-hover:block z-10">
+ <div className="bg-port-bg border border-port-border rounded px-2 py-1 text-xs whitespace-nowrap shadow-lg">
+ <div className="text-white font-medium">{day.date}</div>
+ {day.tasks > 0 ? (
+ <>
+ <div className="text-gray-400">{day.tasks} task{day.tasks !== 1 ? 's' : ''}</div>
+ <div className={day.successRate >= 70 ? 'text-port-success' : day.successRate >= 50 ? 'text-port-warning' : 'text-port-error'}>
+ {day.successes}/{day.tasks} passed ({day.successRate}%)
+ </div>
+ </>
+ ) : (
+ <div className="text-gray-500">No tasks</div>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+
+ {/* X-axis labels - show every 7th day */}
+ <div className="flex gap-0.5 mt-1" style={{ minWidth: `${data.data.length * 12}px` }}>
+ {data.data.map((day, idx) => (
+ <div
+ key={day.date}
+ className="flex-1 text-center"
+ style={{ minWidth: '10px', maxWidth: '24px' }}
+ >
+ {idx % 7 === 0 && (
+ <span className="text-xs text-gray-600">{day.dateShort}</span>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+
+ {/* Legend */}
+ <div className="flex items-center justify-center gap-4 mt-4 text-xs">
+ <div className="flex items-center gap-1">
+ <div className="w-3 h-3 rounded bg-port-success" />
+ <span className="text-gray-500">80%+</span>
+ </div>
+ <div className="flex items-center gap-1">
+ <div className="w-3 h-3 rounded bg-port-warning" />
+ <span className="text-gray-500">60-79%</span>
+ </div>
+ <div className="flex items-center gap-1">
+ <div className="w-3 h-3 rounded bg-port-error" />
+ <span className="text-gray-500">&lt;60%</span>
+ </div>
+ </div>
+
+ {/* Success trend indicator */}
+ {summary.successTrend !== 'stable' && (
+ <div className={`mt-3 p-2 rounded text-xs text-center ${summary.successTrend === 'improving' ? 'bg-port-success/10 text-port-success' : 'bg-port-error/10 text-port-error'}`}>
+ {getTrendIcon(summary.successTrend)}
+ <span className="ml-1">{getTrendLabel(summary.successTrend)}</span>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/cos/index.js b/client/src/components/cos/index.js
index e54910337e..3eec690231 100644
--- a/client/src/components/cos/index.js
+++ b/client/src/components/cos/index.js
@@ -19,6 +19,7 @@ export { default as StatusBubble } from './StatusBubble';
export { default as EventLog } from './EventLog';
export { default as QuickSummary } from './QuickSummary';
export { default as ActionableInsightsBanner } from './ActionableInsightsBanner';
+export { default as DailyTrendsChart } from './DailyTrendsChart';
// Tab Components
export { default as TasksTab } from './tabs/TasksTab';
diff --git a/client/src/components/cos/tabs/ProductivityTab.jsx b/client/src/components/cos/tabs/ProductivityTab.jsx
index 8ed402dda8..0fe377a146 100644
--- a/client/src/components/cos/tabs/ProductivityTab.jsx
+++ b/client/src/components/cos/tabs/ProductivityTab.jsx
@@ -16,6 +16,7 @@ import {
Award
} from 'lucide-react';
import * as api from '../../../services/api';
+import DailyTrendsChart from '../DailyTrendsChart';
const DAY_NAMES = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const FULL_DAY_NAMES = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
@@ -197,6 +198,9 @@ export default function ProductivityTab() {
)}
</div>
+ {/* Daily Task Trends Chart */}
+ <DailyTrendsChart days={30} initialExpanded={true} />
+
{/* AI Insights */}
{data.insights?.length > 0 && (
<div>
diff --git a/client/src/services/api.js b/client/src/services/api.js
index d37a6de857..b3fbe14791 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -536,6 +536,7 @@ export const compareCosWeeks = (week1, week2) => request(`/cos/digest/compare?we
export const getCosProductivity = () => request('/cos/productivity');
export const getCosProductivitySummary = () => request('/cos/productivity/summary');
export const recalculateCosProductivity = () => request('/cos/productivity/recalculate', { method: 'POST' });
+export const getCosProductivityTrends = (days = 30) => request(`/cos/productivity/trends?days=${days}`);
export const getCosQuickSummary = () => request('/cos/quick-summary');
export const getCosRecentTasks = (limit = 10) => request(`/cos/recent-tasks?limit=${limit}`);
export const getCosActionableInsights = () => request('/cos/actionable-insights');
diff --git a/server/routes/cos.js b/server/routes/cos.js
index fa0ced7837..0142aa712e 100644
--- a/server/routes/cos.js
+++ b/server/routes/cos.js
@@ -884,6 +884,13 @@ router.post('/productivity/recalculate', asyncHandler(async (req, res) => {
res.json({ success: true, data });
}));
+// GET /api/cos/productivity/trends - Get daily task completion trends for charting
+router.get('/productivity/trends', asyncHandler(async (req, res) => {
+ const days = parseInt(req.query.days) || 30;
+ const trends = await productivity.getDailyTrends(days);
+ res.json(trends);
+}));
+
// GET /api/cos/actionable-insights - Get prioritized action items requiring user attention
// Surfaces the most important things to address right now across all CoS subsystems
router.get('/actionable-insights', asyncHandler(async (req, res) => {
diff --git a/server/services/productivity.js b/server/services/productivity.js
index 65e1d3d9e3..f3d3b371f4 100644
--- a/server/services/productivity.js
+++ b/server/services/productivity.js
@@ -31,6 +31,9 @@ const DEFAULT_PRODUCTIVITY = {
dailyPatterns: {
// Aggregated by day of week (0-6): { tasks, successes, failures, avgDuration }
},
+ dailyHistory: {
+ // Indexed by YYYY-MM-DD: { tasks, successes, failures, successRate }
+ },
milestones: [
// { type, value, achievedAt, description }
],
@@ -129,6 +132,7 @@ export async function recalculateProductivity() {
// Initialize patterns
const hourlyPatterns = {};
const dailyPatterns = {};
+ const dailyHistory = {};
// Track dates with activity for streak calculation
const activeDates = new Set();
@@ -155,7 +159,7 @@ export async function recalculateProductivity() {
else hourlyPatterns[hour].failures++;
hourlyPatterns[hour].totalDuration += duration;
- // Daily patterns
+ // Daily patterns (by day of week)
if (!dailyPatterns[dayOfWeek]) {
dailyPatterns[dayOfWeek] = { tasks: 0, successes: 0, failures: 0, totalDuration: 0 };
}
@@ -163,6 +167,20 @@ export async function recalculateProductivity() {
if (success) dailyPatterns[dayOfWeek].successes++;
else dailyPatterns[dayOfWeek].failures++;
dailyPatterns[dayOfWeek].totalDuration += duration;
+
+ // Daily history (by date)
+ if (!dailyHistory[dateStr]) {
+ dailyHistory[dateStr] = { tasks: 0, successes: 0, failures: 0 };
+ }
+ dailyHistory[dateStr].tasks++;
+ if (success) dailyHistory[dateStr].successes++;
+ else dailyHistory[dateStr].failures++;
+ }
+
+ // Calculate success rates for daily history
+ for (const date of Object.keys(dailyHistory)) {
+ const h = dailyHistory[date];
+ h.successRate = h.tasks > 0 ? Math.round((h.successes / h.tasks) * 100) : 0;
}
// Calculate average durations
@@ -280,6 +298,7 @@ export async function recalculateProductivity() {
},
hourlyPatterns,
dailyPatterns,
+ dailyHistory,
milestones,
totals: {
totalTasks,
@@ -400,3 +419,84 @@ export async function getProductivitySummary() {
recentMilestone: data.milestones?.[data.milestones.length - 1] || null
};
}
+
+/**
+ * Get daily task trends for visualization
+ * Returns last N days of task completion data with trend analysis
+ */
+export async function getDailyTrends(days = 30) {
+ const data = await loadProductivity();
+ const dailyHistory = data.dailyHistory || {};
+
+ // Generate date range for last N days
+ const today = new Date();
+ const dateRange = [];
+ for (let i = days - 1; i >= 0; i--) {
+ const d = new Date(today);
+ d.setDate(d.getDate() - i);
+ dateRange.push(getDateString(d));
+ }
+
+ // Build trend data for each day
+ const trendData = dateRange.map(date => {
+ const dayData = dailyHistory[date] || { tasks: 0, successes: 0, failures: 0, successRate: 0 };
+ return {
+ date,
+ dateShort: date.slice(5), // MM-DD
+ ...dayData
+ };
+ });
+
+ // Calculate rolling averages and trends
+ const windowSize = 7;
+ const withAverages = trendData.map((day, idx) => {
+ const window = trendData.slice(Math.max(0, idx - windowSize + 1), idx + 1);
+ const avgTasks = window.reduce((sum, d) => sum + d.tasks, 0) / window.length;
+ const avgSuccessRate = window.reduce((sum, d) => sum + d.successRate, 0) / window.length;
+ return {
+ ...day,
+ rollingAvgTasks: Math.round(avgTasks * 10) / 10,
+ rollingAvgSuccessRate: Math.round(avgSuccessRate)
+ };
+ });
+
+ // Calculate overall trend direction
+ const recentDays = withAverages.slice(-7);
+ const olderDays = withAverages.slice(-14, -7);
+
+ const recentTotal = recentDays.reduce((sum, d) => sum + d.tasks, 0);
+ const olderTotal = olderDays.reduce((sum, d) => sum + d.tasks, 0);
+ const recentAvgRate = recentDays.reduce((sum, d) => sum + d.successRate, 0) / (recentDays.length || 1);
+ const olderAvgRate = olderDays.reduce((sum, d) => sum + d.successRate, 0) / (olderDays.length || 1);
+
+ let volumeTrend = 'stable';
+ if (recentTotal > olderTotal * 1.2) volumeTrend = 'increasing';
+ else if (recentTotal < olderTotal * 0.8) volumeTrend = 'decreasing';
+
+ let successTrend = 'stable';
+ if (recentAvgRate > olderAvgRate + 10) successTrend = 'improving';
+ else if (recentAvgRate < olderAvgRate - 10) successTrend = 'declining';
+
+ // Summary stats
+ const activeDaysInRange = trendData.filter(d => d.tasks > 0).length;
+ const totalTasksInRange = trendData.reduce((sum, d) => sum + d.tasks, 0);
+ const avgTasksPerActiveDay = activeDaysInRange > 0
+ ? Math.round(totalTasksInRange / activeDaysInRange * 10) / 10
+ : 0;
+
+ return {
+ data: withAverages,
+ summary: {
+ days,
+ activeDays: activeDaysInRange,
+ totalTasks: totalTasksInRange,
+ avgTasksPerActiveDay,
+ avgSuccessRate: Math.round(
+ trendData.filter(d => d.tasks > 0).reduce((sum, d) => sum + d.successRate, 0) /
+ (activeDaysInRange || 1)
+ ),
+ volumeTrend,
+ successTrend
+ }
+ };
+}