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: add Feeds digest + MeatSpace streak dashboard widgets (#2034)

Adam Eivy5b10b4dba9ff
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7f39a644f3..2c326cf69a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -28,6 +28,10 @@
- **The Story Builder index now uses the full desktop width instead of a single narrow column.** The create form and the "Continue a story" session list previously stacked in one `max-w-3xl` column, leaving most of a 1280px+ screen empty. Above the `lg` breakpoint they now sit side by side — form left, in-progress sessions in a fixed-width sidebar on the right — mirroring the POST launcher's two-column layout (#1986), so your existing stories are visible without scrolling. Below `lg` the columns stack exactly as before, so mobile is unchanged (#2030).
+## Dashboard
+
+- **Two new dashboard widgets surface previously invisible data: a Feeds unread digest and a health-logging streak.** The Feeds Digest widget shows your total unread RSS/Atom count plus the top unread feeds by count and deep-links to Brain → Feeds — it consumes the existing `getFeedStats` wrapper (now the endpoint's first real caller) so unread counts aren't recomputed. The Health Logging Streak widget mirrors the Activity Streak / Daily POST pattern: current + best cross-domain logging streak, a 7-day sparkline, and this-week counts per domain (alcohol, nicotine, workouts, body, blood pressure) via a new `GET /api/meatspace/logging-stats` aggregate, deep-linking to MeatSpace. Both are gated hidden on fresh installs with no feeds/logs and render at mobile widths (#2034).
+
## Loading states
- **The DataDog, Jira, and GitHub integration pages now show a layout-shaped skeleton on first paint instead of a centered "Loading…" line.** Each page previously rendered a bare full-screen text message sized with `h-screen`, which mis-sized under mobile browser chrome and jumped when the real content arrived. They now share a `PageSkeleton` that reserves the header + card-grid dimensions (matching the loaded layout, using the `port-*` design tokens like the dashboard's `WidgetSkeleton`), so there's no post-load layout jump and no full-height wrapper fighting Layout's scroll (#2029).
diff --git a/client/src/components/dashboard/builtins/FeedsWidget.jsx b/client/src/components/dashboard/builtins/FeedsWidget.jsx
new file mode 100644
index 0000000000..19c1810b7f
--- /dev/null
+++ b/client/src/components/dashboard/builtins/FeedsWidget.jsx
@@ -0,0 +1,58 @@
+import { Link } from 'react-router-dom';
+import { Rss, ArrowRight } from 'lucide-react';
+
+// Glanceable RSS/Atom unread digest. Reads the shared `feeds` slice of
+// dashboardState (populated from the existing getFeedStats wrapper — the
+// server owns unread computation, so this never re-derives it) and deep-links
+// into Brain → Feeds. Gated off until the user has subscribed to a feed.
+export default function FeedsWidget({ dashboardState }) {
+ const feeds = dashboardState?.feeds;
+ if (!feeds) return null;
+
+ const unread = feeds.unreadItems ?? 0;
+ const topUnread = Array.isArray(feeds.topUnread) ? feeds.topUnread : [];
+
+ return (
+ <Link
+ to="/brain/feeds"
+ className="bg-port-card border border-port-border rounded-xl p-4 h-full block hover:border-gray-600 transition-colors"
+ >
+ <div className="flex items-center gap-2 mb-3">
+ <Rss size={16} className="text-gray-500" />
+ <h3 className="text-sm font-semibold text-white">Feeds</h3>
+ <span className="ml-auto flex items-center gap-1 text-xs text-port-accent">
+ Open <ArrowRight size={12} />
+ </span>
+ </div>
+
+ <div className="flex items-center gap-3 mb-3">
+ <div className="text-2xl" aria-hidden="true">{unread > 0 ? '📬' : '📭'}</div>
+ <div>
+ <div className="text-xl font-bold text-white">
+ {unread} unread
+ </div>
+ <div className="text-xs text-gray-500">
+ {feeds.totalFeeds ?? 0} feed{(feeds.totalFeeds ?? 0) !== 1 ? 's' : ''} subscribed
+ </div>
+ </div>
+ </div>
+
+ {topUnread.length > 0 ? (
+ <ul className="space-y-1">
+ {topUnread.map((f) => (
+ <li key={f.id} className="flex items-center gap-2 text-xs">
+ <span className="flex-1 truncate text-gray-300" title={f.title}>
+ {f.title || 'Untitled feed'}
+ </span>
+ <span className="shrink-0 px-1.5 py-0.5 rounded-full bg-port-accent/20 text-port-accent font-semibold">
+ {f.unread}
+ </span>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <div className="text-xs text-gray-500">All caught up 🎉</div>
+ )}
+ </Link>
+ );
+}
diff --git a/client/src/components/dashboard/builtins/FeedsWidget.test.jsx b/client/src/components/dashboard/builtins/FeedsWidget.test.jsx
new file mode 100644
index 0000000000..beef90ed08
--- /dev/null
+++ b/client/src/components/dashboard/builtins/FeedsWidget.test.jsx
@@ -0,0 +1,52 @@
+import { describe, it, expect } from 'vitest';
+import { render, screen } from '@testing-library/react';
+import { MemoryRouter } from 'react-router-dom';
+import FeedsWidget from './FeedsWidget';
+
+const renderWidget = (feeds) =>
+ render(
+ <MemoryRouter>
+ <FeedsWidget dashboardState={{ feeds }} />
+ </MemoryRouter>
+ );
+
+describe('FeedsWidget', () => {
+ it('renders nothing when stats are absent (fetch failed / no data)', () => {
+ const { container } = renderWidget(null);
+ expect(container.firstChild).toBeNull();
+ });
+
+ it('shows the unread count and deep-links to Brain → Feeds', () => {
+ renderWidget({ totalFeeds: 3, totalItems: 20, unreadItems: 7, topUnread: [] });
+ expect(screen.getByText('7 unread')).toBeTruthy();
+ expect(screen.getByText('3 feeds subscribed')).toBeTruthy();
+ expect(screen.getByRole('link').getAttribute('href')).toBe('/brain/feeds');
+ });
+
+ it('lists top unread feed names with per-feed counts', () => {
+ renderWidget({
+ totalFeeds: 2,
+ totalItems: 10,
+ unreadItems: 8,
+ topUnread: [
+ { id: 'a', title: 'Hacker News', unread: 5 },
+ { id: 'b', title: 'Lobsters', unread: 3 },
+ ],
+ });
+ expect(screen.getByText('Hacker News')).toBeTruthy();
+ expect(screen.getByText('Lobsters')).toBeTruthy();
+ expect(screen.getByText('5')).toBeTruthy();
+ expect(screen.getByText('3')).toBeTruthy();
+ });
+
+ it('shows a caught-up state when nothing is unread', () => {
+ renderWidget({ totalFeeds: 2, totalItems: 4, unreadItems: 0, topUnread: [] });
+ expect(screen.getByText('0 unread')).toBeTruthy();
+ expect(screen.getByText('All caught up 🎉')).toBeTruthy();
+ });
+
+ it('singularizes the feed label for a single subscription', () => {
+ renderWidget({ totalFeeds: 1, totalItems: 2, unreadItems: 2, topUnread: [{ id: 'a', title: 'Solo', unread: 2 }] });
+ expect(screen.getByText('1 feed subscribed')).toBeTruthy();
+ });
+});
diff --git a/client/src/components/dashboard/builtins/MeatSpaceStreakWidget.jsx b/client/src/components/dashboard/builtins/MeatSpaceStreakWidget.jsx
new file mode 100644
index 0000000000..69a0ef25c3
--- /dev/null
+++ b/client/src/components/dashboard/builtins/MeatSpaceStreakWidget.jsx
@@ -0,0 +1,81 @@
+import { Link } from 'react-router-dom';
+import { HeartPulse, ArrowRight } from 'lucide-react';
+
+// Health-logging habit loop. Reads the `meatspaceLogging` slice of
+// dashboardState (cross-domain streak + this-week counts computed server-side)
+// and deep-links into MeatSpace. Mirrors ActivityStreakWidget/DailyPostWidget's
+// streak framing. Gated off until at least one health log exists.
+export default function MeatSpaceStreakWidget({ dashboardState }) {
+ const stats = dashboardState?.meatspaceLogging;
+ if (!stats) return null;
+
+ const streak = stats.currentStreak ?? 0;
+ const longest = stats.longestStreak ?? 0;
+ const streakGlyph = streak >= 7 ? '🔥' : streak >= 3 ? '⚡' : '✨';
+ const activeDomains = (stats.domains || []).filter((d) => d.thisWeek > 0);
+
+ return (
+ <Link
+ to="/meatspace/overview"
+ className="bg-port-card border border-port-border rounded-xl p-4 h-full block hover:border-gray-600 transition-colors"
+ >
+ <div className="flex items-center gap-2 mb-3">
+ <HeartPulse size={16} className="text-gray-500" />
+ <h3 className="text-sm font-semibold text-white">Health Logging</h3>
+ <span className="ml-auto flex items-center gap-1 text-xs text-port-accent">
+ Open <ArrowRight size={12} />
+ </span>
+ </div>
+
+ <div className="flex items-center gap-3">
+ <div className="text-2xl" aria-hidden="true">{streakGlyph}</div>
+ <div>
+ <div className="text-xl font-bold text-white">
+ {streak} day{streak !== 1 ? 's' : ''}
+ </div>
+ <div className="text-xs text-gray-500">
+ {streak > 0 ? 'Logging streak' : 'No streak — log something today'}
+ </div>
+ </div>
+ {longest > streak && (
+ <div className="ml-auto text-right">
+ <div className="text-sm font-semibold text-port-accent">{longest} days</div>
+ <div className="text-xs text-gray-500">Best</div>
+ </div>
+ )}
+ {streak > 0 && streak === longest && (
+ <div className="ml-auto px-2 py-1 bg-port-success/20 text-port-success text-xs rounded-full">
+ Personal best!
+ </div>
+ )}
+ </div>
+
+ {/* 7-day sparkline: intensity by number of domains logged that day. */}
+ <div className="flex gap-1 mt-3">
+ {(stats.last7Days || []).map((day) => (
+ <div
+ key={day.date}
+ className={`flex-1 h-2 rounded-full ${day.logged ? 'bg-port-success' : 'bg-port-border'}`}
+ title={`${day.label}: ${day.domains} domain${day.domains !== 1 ? 's' : ''} logged`}
+ />
+ ))}
+ </div>
+
+ <div className="mt-3 text-xs text-gray-400">
+ {activeDomains.length > 0 ? (
+ <span>
+ This week:{' '}
+ {activeDomains.map((d, i) => (
+ <span key={d.key}>
+ {i > 0 && ', '}
+ <span className="text-gray-300">{d.label}</span> {d.thisWeek}
+ </span>
+ ))}
+ </span>
+ ) : (
+ <span>No logs this week yet</span>
+ )}
+ </div>
+ </Link>
+ );
+}
diff --git a/client/src/components/dashboard/builtins/MeatSpaceStreakWidget.test.jsx b/client/src/components/dashboard/builtins/MeatSpaceStreakWidget.test.jsx
new file mode 100644
index 0000000000..bf1567fe63
--- /dev/null
+++ b/client/src/components/dashboard/builtins/MeatSpaceStreakWidget.test.jsx
@@ -0,0 +1,63 @@
+import { describe, it, expect } from 'vitest';
+import { render, screen } from '@testing-library/react';
+import { MemoryRouter } from 'react-router-dom';
+import MeatSpaceStreakWidget from './MeatSpaceStreakWidget';
+
+const renderWidget = (meatspaceLogging) =>
+ render(
+ <MemoryRouter>
+ <MeatSpaceStreakWidget dashboardState={{ meatspaceLogging }} />
+ </MemoryRouter>
+ );
+
+const baseStats = {
+ currentStreak: 4,
+ longestStreak: 9,
+ weekTotal: 5,
+ totalLogged: 30,
+ domains: [
+ { key: 'alcohol', label: 'Alcohol', total: 10, thisWeek: 2 },
+ { key: 'nicotine', label: 'Nicotine', total: 5, thisWeek: 0 },
+ { key: 'workouts', label: 'Workouts', total: 15, thisWeek: 3 },
+ ],
+ last7Days: Array.from({ length: 7 }, (_, i) => ({
+ date: `2026-06-2${i}`,
+ label: 'Mon',
+ domains: i % 2,
+ logged: i % 2 === 1,
+ })),
+};
+
+describe('MeatSpaceStreakWidget', () => {
+ it('renders nothing when stats are absent', () => {
+ const { container } = renderWidget(null);
+ expect(container.firstChild).toBeNull();
+ });
+
+ it('shows the current streak and deep-links to MeatSpace', () => {
+ renderWidget(baseStats);
+ expect(screen.getByText('4 days')).toBeTruthy();
+ expect(screen.getByText('Logging streak')).toBeTruthy();
+ expect(screen.getByRole('link').getAttribute('href')).toBe('/meatspace/overview');
+ });
+
+ it('lists only domains with logs this week', () => {
+ renderWidget(baseStats);
+ expect(screen.getByText('Alcohol')).toBeTruthy();
+ expect(screen.getByText('Workouts')).toBeTruthy();
+ // Nicotine has 0 this week and should be omitted.
+ expect(screen.queryByText('Nicotine')).toBeNull();
+ });
+
+ it('shows the best streak when the current run is not the record', () => {
+ renderWidget(baseStats);
+ expect(screen.getByText('9 days')).toBeTruthy();
+ expect(screen.getByText('Best')).toBeTruthy();
+ });
+
+ it('prompts to start when there is no active streak', () => {
+ renderWidget({ ...baseStats, currentStreak: 0, domains: [], last7Days: [] });
+ expect(screen.getByText('No streak — log something today')).toBeTruthy();
+ expect(screen.getByText('No logs this week yet')).toBeTruthy();
+ });
+});
diff --git a/client/src/components/dashboard/widgetRegistry.jsx b/client/src/components/dashboard/widgetRegistry.jsx
index 0e738aeeb3..0a3a4a2ebe 100644
--- a/client/src/components/dashboard/widgetRegistry.jsx
+++ b/client/src/components/dashboard/widgetRegistry.jsx
@@ -24,6 +24,8 @@ const AppsGridWidget = lazyWithReload(() => import('./builtins/AppsGridWi
const QuickStatsWidget = lazyWithReload(() => import('./builtins/QuickStatsWidget'));
const ActivityStreakWidget = lazyWithReload(() => import('./builtins/ActivityStreakWidget'));
const HourlyActivityWidget = lazyWithReload(() => import('./builtins/HourlyActivityWidget'));
+const FeedsWidget = lazyWithReload(() => import('./builtins/FeedsWidget'));
+const MeatSpaceStreakWidget = lazyWithReload(() => import('./builtins/MeatSpaceStreakWidget'));
// Each entry: { id, label, Component, width, defaultH?, gate?, module? }.
// `gate(state) => bool` skips the widget when it has nothing useful to show.
@@ -62,6 +64,8 @@ export const WIDGETS = [
{ id: 'decision-log', label: 'Decision Log', Component: DecisionLogWidget, width: 'quarter', defaultH: 4 },
{ id: 'activity-streak', label: 'Activity Streak', Component: ActivityStreakWidget, width: 'third', defaultH: 3, gate: (s) => s.usage?.currentStreak > 0 || s.usage?.longestStreak > 0, module: { id: '06', status: 'STREAK', glyph: 'spark' } },
{ id: 'hourly-activity', label: 'Activity by Hour', Component: HourlyActivityWidget, width: 'full', defaultH: 4, gate: (s) => !!s.usage?.hourlyActivity && s.usage.hourlyActivity.some((v) => v > 0) },
+ { id: 'feeds', label: 'Feeds Digest', Component: FeedsWidget, width: 'quarter', defaultH: 4, gate: (s) => (s.feeds?.totalFeeds ?? 0) > 0 },
+ { id: 'meatspace-streak', label: 'Health Logging Streak', Component: MeatSpaceStreakWidget, width: 'third', defaultH: 4, gate: (s) => (s.meatspaceLogging?.totalLogged ?? 0) > 0 },
];
export const WIDGETS_BY_ID = Object.fromEntries(WIDGETS.map((w) => [w.id, w]));
diff --git a/client/src/pages/Dashboard.jsx b/client/src/pages/Dashboard.jsx
index d837622935..bdbcfc0657 100644
--- a/client/src/pages/Dashboard.jsx
+++ b/client/src/pages/Dashboard.jsx
@@ -20,6 +20,8 @@ export default function Dashboard() {
const [health, setHealth] = useState(null);
const [usage, setUsage] = useState(null);
const [tribeCare, setTribeCare] = useState(null);
+ const [feeds, setFeeds] = useState(null);
+ const [meatspaceLogging, setMeatspaceLogging] = useState(null);
const [loading, setLoading] = useState(true);
const [dataError, setDataError] = useState(null);
const [layoutsError, setLayoutsError] = useState(null);
@@ -59,16 +61,20 @@ export default function Dashboard() {
const fetchData = useCallback(async () => {
setDataError(null);
- const [appsData, healthData, usageData, tribeCareData] = await Promise.all([
+ const [appsData, healthData, usageData, tribeCareData, feedsData, meatspaceLoggingData] = await Promise.all([
api.getApps().catch((err) => { setDataError(err.message); return []; }),
api.checkHealth().catch(() => null),
api.getUsage().catch(() => null),
api.getTribeCareSummary({ silent: true }).catch(() => null),
+ api.getFeedStats({ silent: true }).catch(() => null),
+ api.getMeatspaceLoggingStats({ silent: true }).catch(() => null),
]);
setApps(appsData);
setHealth(healthData);
setUsage(usageData);
setTribeCare(tribeCareData);
+ setFeeds(feedsData);
+ setMeatspaceLogging(meatspaceLoggingData);
setLoading(false);
}, []);
@@ -165,8 +171,8 @@ export default function Dashboard() {
}), [activeApps]);
const dashboardState = useMemo(
- () => ({ apps, sortedApps, activeApps, appStats, health, usage, tribeCare, refetch: fetchData }),
- [apps, sortedApps, activeApps, appStats, health, usage, tribeCare, fetchData]
+ () => ({ apps, sortedApps, activeApps, appStats, health, usage, tribeCare, feeds, meatspaceLogging, refetch: fetchData }),
+ [apps, sortedApps, activeApps, appStats, health, usage, tribeCare, feeds, meatspaceLogging, fetchData]
);
// Falls back to a local minimal layout only AFTER the initial fetch has
diff --git a/client/src/services/apiMeatspace.js b/client/src/services/apiMeatspace.js
index 089e74eb1e..22e52e4820 100644
--- a/client/src/services/apiMeatspace.js
+++ b/client/src/services/apiMeatspace.js
@@ -67,6 +67,7 @@ export const setMeatspaceBirthDate = (birthDate) => request('/meatspace/birth-da
body: JSON.stringify({ birthDate })
});
export const getDeathClock = () => request('/meatspace/death-clock');
+export const getMeatspaceLoggingStats = (options = {}) => request('/meatspace/logging-stats', options);
export const getLEV = () => request('/meatspace/lev');
export const getAlcoholSummary = () => request('/meatspace/alcohol');
export const getDailyAlcohol = (from, to) => {
diff --git a/client/src/services/apiMessages.js b/client/src/services/apiMessages.js
index 0062fd2efe..87c23caf0e 100644
--- a/client/src/services/apiMessages.js
+++ b/client/src/services/apiMessages.js
@@ -48,7 +48,7 @@ export const enableGmailApi = () => request('/messages/gmail/enable-api', { meth
// Feeds - RSS/Atom Feed Ingestion
export const getFeeds = () => request('/feeds');
-export const getFeedStats = () => request('/feeds/stats');
+export const getFeedStats = (options = {}) => request('/feeds/stats', options);
export const getFeedItems = ({ feedId, unreadOnly } = {}) => {
const params = new URLSearchParams();
if (feedId) params.set('feedId', feedId);
diff --git a/server/routes/meatspaceCoreRoutes.js b/server/routes/meatspaceCoreRoutes.js
index 1d1e34b8bc..6b9e7fa52b 100644
--- a/server/routes/meatspaceCoreRoutes.js
+++ b/server/routes/meatspaceCoreRoutes.js
@@ -10,6 +10,7 @@ import { validateRequest } from '../lib/validation.js';
import { configUpdateSchema, lifestyleUpdateSchema } from '../lib/meatspaceValidation.js';
import { birthDateInputSchema } from '../lib/identityValidation.js';
import * as meatspaceService from '../services/meatspace.js';
+import { getLoggingStats } from '../services/meatspaceLoggingStats.js';
const router = Router();
@@ -26,6 +27,15 @@ router.get('/', asyncHandler(async (req, res) => {
res.json(overview);
}));
+/**
+ * GET /api/meatspace/logging-stats
+ * Cross-domain health-logging streak + this-week counts for the dashboard widget.
+ */
+router.get('/logging-stats', asyncHandler(async (req, res) => {
+ const stats = await getLoggingStats();
+ res.json(stats);
+}));
+
// =============================================================================
// CONFIG
// =============================================================================
diff --git a/server/services/feeds.js b/server/services/feeds.js
index 4482898635..11b9932c6f 100644
--- a/server/services/feeds.js
+++ b/server/services/feeds.js
@@ -376,10 +376,22 @@ export async function markAllRead(feedId) {
export async function getFeedStats() {
const data = await store.load();
+ // Single-pass per-feed unread tally (O(I)) — mirrors getFeeds()'s approach so
+ // the widget can surface top unread feed names without a second computation.
+ const unreadCounts = new Map();
+ for (const item of data.items) {
+ if (!item.read) unreadCounts.set(item.feedId, (unreadCounts.get(item.feedId) || 0) + 1);
+ }
+ const topUnread = data.feeds
+ .map(feed => ({ id: feed.id, title: feed.title, unread: unreadCounts.get(feed.id) || 0 }))
+ .filter(f => f.unread > 0)
+ .sort((a, b) => b.unread - a.unread)
+ .slice(0, 5);
return {
totalFeeds: data.feeds.length,
totalItems: data.items.length,
- unreadItems: data.items.filter(i => !i.read).length
+ unreadItems: data.items.filter(i => !i.read).length,
+ topUnread
};
}
diff --git a/server/services/feeds.test.js b/server/services/feeds.test.js
index 78edd6d545..c1d9f3ab15 100644
--- a/server/services/feeds.test.js
+++ b/server/services/feeds.test.js
@@ -101,7 +101,7 @@ const FETCH_ERROR = 'Could not fetch feed — check the URL';
describe('getFeeds / getFeedStats — empty state', () => {
it('returns empty arrays before any subscriptions', async () => {
expect(await feeds.getFeeds()).toEqual([]);
- expect(await feeds.getFeedStats()).toEqual({ totalFeeds: 0, totalItems: 0, unreadItems: 0 });
+ expect(await feeds.getFeedStats()).toEqual({ totalFeeds: 0, totalItems: 0, unreadItems: 0, topUnread: [] });
});
});
@@ -449,7 +449,27 @@ describe('getFeeds — unread counts', () => {
describe('getFeedStats', () => {
it('aggregates totals across feeds', async () => {
- await seedTwoFeeds();
- expect(await feeds.getFeedStats()).toEqual({ totalFeeds: 2, totalItems: 4, unreadItems: 4 });
+ const { feedA, feedB } = await seedTwoFeeds();
+ const stats = await feeds.getFeedStats();
+ expect(stats.totalFeeds).toBe(2);
+ expect(stats.totalItems).toBe(4);
+ expect(stats.unreadItems).toBe(4);
+ // Every feed with unread items is surfaced, sorted by unread count desc.
+ expect(stats.topUnread).toHaveLength(2);
+ expect(stats.topUnread.map(f => f.id).sort()).toEqual([feedA.id, feedB.id].sort());
+ expect(stats.topUnread.every(f => f.unread === 2)).toBe(true);
+ });
+
+ it('excludes fully-read feeds and ranks by unread count', async () => {
+ const { feedA } = await seedTwoFeeds();
+ // Mark every item in feedA read so it drops out of topUnread entirely.
+ for (const item of await feeds.getItems({ feedId: feedA.id })) {
+ await feeds.markItemRead(item.id);
+ }
+ const stats = await feeds.getFeedStats();
+ expect(stats.unreadItems).toBe(2);
+ expect(stats.topUnread).toHaveLength(1);
+ expect(stats.topUnread[0].id).not.toBe(feedA.id);
+ expect(stats.topUnread[0].unread).toBe(2);
});
});
diff --git a/server/services/meatspaceLoggingStats.js b/server/services/meatspaceLoggingStats.js
new file mode 100644
index 0000000000..1a003ce58a
--- /dev/null
+++ b/server/services/meatspaceLoggingStats.js
@@ -0,0 +1,131 @@
+/**
+ * MeatSpace Logging Stats
+ *
+ * Aggregates the daily-dated health logs (alcohol, nicotine, workouts, body,
+ * blood pressure) into a single glanceable summary for the dashboard streak
+ * widget: a cross-domain logging streak, per-domain this-week counts, and a
+ * 7-day sparkline. Pure read — composes the existing per-domain getters rather
+ * than reaching into their storage files, so MortalLoom-backed installs are
+ * covered for free.
+ */
+
+import { getDateString } from '../lib/fileUtils.js';
+import { getDailyAlcohol } from './meatspaceAlcohol.js';
+import { getDailyNicotine } from './meatspaceNicotine.js';
+import { getWorkouts, getBodyHistory, getBloodPressureHistory } from './meatspaceHealth.js';
+
+// Each domain contributes an array of `{ date: 'YYYY-MM-DD', ... }` records.
+// `label` is the human-facing name shown per-domain in the widget.
+const DOMAINS = [
+ { key: 'alcohol', label: 'Alcohol', load: () => getDailyAlcohol() },
+ { key: 'nicotine', label: 'Nicotine', load: () => getDailyNicotine() },
+ { key: 'workouts', label: 'Workouts', load: () => getWorkouts() },
+ { key: 'body', label: 'Body', load: () => getBodyHistory() },
+ { key: 'bloodPressure', label: 'Blood Pressure', load: () => getBloodPressureHistory() },
+];
+
+// Consecutive days (ending today, or yesterday if today is empty) that have at
+// least one log in any domain. Mirrors usage.js's calculateStreak so the two
+// dashboard streaks read the same way.
+function calculateStreak(loggedDates) {
+ let streak = 0;
+ const checkDate = new Date();
+ // Normalize to midnight so day arithmetic is stable across DST.
+ checkDate.setHours(0, 0, 0, 0);
+ while (true) {
+ const dateStr = getDateString(checkDate);
+ if (loggedDates.has(dateStr)) {
+ streak++;
+ checkDate.setDate(checkDate.getDate() - 1);
+ } else if (streak === 0) {
+ // Grace: a gap today doesn't break a streak that ran through yesterday.
+ checkDate.setDate(checkDate.getDate() - 1);
+ if (!loggedDates.has(getDateString(checkDate))) break;
+ } else {
+ break;
+ }
+ }
+ return streak;
+}
+
+// Longest run of consecutive logged days anywhere in history.
+function calculateLongestStreak(loggedDates) {
+ const dates = [...loggedDates].sort();
+ let longest = 0;
+ let run = 0;
+ let prev = null;
+ for (const dateStr of dates) {
+ if (prev) {
+ const diffDays = Math.round(
+ (new Date(dateStr) - new Date(prev)) / (1000 * 60 * 60 * 24)
+ );
+ run = diffDays === 1 ? run + 1 : 1;
+ } else {
+ run = 1;
+ }
+ longest = Math.max(longest, run);
+ prev = dateStr;
+ }
+ return longest;
+}
+
+export async function getLoggingStats() {
+ const perDomain = await Promise.all(
+ DOMAINS.map(async (d) => ({ ...d, entries: (await d.load().catch(() => [])) || [] }))
+ );
+
+ const today = new Date();
+ today.setHours(0, 0, 0, 0);
+ const weekAgo = new Date(today);
+ weekAgo.setDate(weekAgo.getDate() - 6); // inclusive 7-day window (today + 6 prior)
+ const weekAgoStr = getDateString(weekAgo);
+ const todayStr = getDateString(today);
+
+ // Union of every logged date across domains → drives the streak + sparkline.
+ const loggedDates = new Set();
+ const domains = [];
+ let totalLogged = 0;
+
+ for (const d of perDomain) {
+ let thisWeek = 0;
+ for (const entry of d.entries) {
+ if (!entry?.date) continue;
+ loggedDates.add(entry.date);
+ totalLogged++;
+ if (entry.date >= weekAgoStr && entry.date <= todayStr) thisWeek++;
+ }
+ domains.push({ key: d.key, label: d.label, total: d.entries.length, thisWeek });
+ }
+
+ // 7-day sparkline: count of distinct domains logged each day (0..DOMAINS.length).
+ const perDayDomainCount = new Map();
+ for (const d of perDomain) {
+ const daysSeen = new Set();
+ for (const entry of d.entries) {
+ if (entry?.date && entry.date >= weekAgoStr && entry.date <= todayStr) daysSeen.add(entry.date);
+ }
+ for (const date of daysSeen) perDayDomainCount.set(date, (perDayDomainCount.get(date) || 0) + 1);
+ }
+
+ const last7Days = [];
+ for (let i = 6; i >= 0; i--) {
+ const date = new Date(today);
+ date.setDate(date.getDate() - i);
+ const dateStr = getDateString(date);
+ last7Days.push({
+ date: dateStr,
+ label: date.toLocaleDateString('en-US', { weekday: 'short' }),
+ domains: perDayDomainCount.get(dateStr) || 0,
+ logged: loggedDates.has(dateStr),
+ });
+ }
+
+ return {
+ currentStreak: calculateStreak(loggedDates),
+ longestStreak: calculateLongestStreak(loggedDates),
+ weekTotal: domains.reduce((sum, d) => sum + d.thisWeek, 0),
+ totalLogged,
+ domains,
+ last7Days,
+ };
+}
diff --git a/server/services/meatspaceLoggingStats.test.js b/server/services/meatspaceLoggingStats.test.js
new file mode 100644
index 0000000000..b3558820a8
--- /dev/null
+++ b/server/services/meatspaceLoggingStats.test.js
@@ -0,0 +1,107 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Mock the per-domain getters so we can drive getLoggingStats with fixed data.
+const mockAlcohol = vi.fn();
+const mockNicotine = vi.fn();
+const mockWorkouts = vi.fn();
+const mockBody = vi.fn();
+const mockBloodPressure = vi.fn();
+
+vi.mock('./meatspaceAlcohol.js', () => ({ getDailyAlcohol: () => mockAlcohol() }));
+vi.mock('./meatspaceNicotine.js', () => ({ getDailyNicotine: () => mockNicotine() }));
+vi.mock('./meatspaceHealth.js', () => ({
+ getWorkouts: () => mockWorkouts(),
+ getBodyHistory: () => mockBody(),
+ getBloodPressureHistory: () => mockBloodPressure(),
+}));
+
+const { getLoggingStats } = await import('./meatspaceLoggingStats.js');
+
+// Local YYYY-MM-DD for `offset` days ago (mirrors getDateString's local basis).
+function daysAgo(offset) {
+ const d = new Date();
+ d.setDate(d.getDate() - offset);
+ const y = d.getFullYear();
+ const m = String(d.getMonth() + 1).padStart(2, '0');
+ const day = String(d.getDate()).padStart(2, '0');
+ return `${y}-${m}-${day}`;
+}
+
+beforeEach(() => {
+ mockAlcohol.mockResolvedValue([]);
+ mockNicotine.mockResolvedValue([]);
+ mockWorkouts.mockResolvedValue([]);
+ mockBody.mockResolvedValue([]);
+ mockBloodPressure.mockResolvedValue([]);
+});
+
+describe('getLoggingStats', () => {
+ it('returns a zeroed summary when nothing has been logged', async () => {
+ const stats = await getLoggingStats();
+ expect(stats.currentStreak).toBe(0);
+ expect(stats.longestStreak).toBe(0);
+ expect(stats.totalLogged).toBe(0);
+ expect(stats.weekTotal).toBe(0);
+ expect(stats.last7Days).toHaveLength(7);
+ expect(stats.last7Days.every((d) => d.logged === false && d.domains === 0)).toBe(true);
+ expect(stats.domains.map((d) => d.key)).toEqual([
+ 'alcohol', 'nicotine', 'workouts', 'body', 'bloodPressure',
+ ]);
+ });
+
+ it('counts a current streak of consecutive logged days ending today', async () => {
+ mockWorkouts.mockResolvedValue([
+ { date: daysAgo(0) }, { date: daysAgo(1) }, { date: daysAgo(2) },
+ ]);
+ const stats = await getLoggingStats();
+ expect(stats.currentStreak).toBe(3);
+ expect(stats.longestStreak).toBe(3);
+ expect(stats.totalLogged).toBe(3);
+ });
+
+ it('applies the yesterday grace when today has no log', async () => {
+ mockNicotine.mockResolvedValue([{ date: daysAgo(1) }, { date: daysAgo(2) }]);
+ const stats = await getLoggingStats();
+ // Today empty but yesterday+ logged → streak still counts.
+ expect(stats.currentStreak).toBe(2);
+ });
+
+ it('breaks the streak on a gap and reports longest historical run', async () => {
+ mockAlcohol.mockResolvedValue([
+ { date: daysAgo(0) },
+ // gap at daysAgo(1)
+ { date: daysAgo(2) }, { date: daysAgo(3) }, { date: daysAgo(4) },
+ ]);
+ const stats = await getLoggingStats();
+ expect(stats.currentStreak).toBe(1);
+ expect(stats.longestStreak).toBe(3);
+ });
+
+ it('aggregates per-domain this-week counts and de-dupes streak days across domains', async () => {
+ // Alcohol + nicotine both logged today → one streak day, two domain counts.
+ mockAlcohol.mockResolvedValue([{ date: daysAgo(0) }, { date: daysAgo(10) }]);
+ mockNicotine.mockResolvedValue([{ date: daysAgo(0) }]);
+ const stats = await getLoggingStats();
+
+ const alcohol = stats.domains.find((d) => d.key === 'alcohol');
+ const nicotine = stats.domains.find((d) => d.key === 'nicotine');
+ expect(alcohol.total).toBe(2);
+ expect(alcohol.thisWeek).toBe(1); // the 10-day-old entry is outside the window
+ expect(nicotine.thisWeek).toBe(1);
+ expect(stats.weekTotal).toBe(2);
+
+ // Today's sparkline cell reflects both domains, but the streak counts one day.
+ const today = stats.last7Days.at(-1);
+ expect(today.logged).toBe(true);
+ expect(today.domains).toBe(2);
+ expect(stats.currentStreak).toBe(1);
+ });
+
+ it('survives a domain getter that rejects', async () => {
+ mockBody.mockRejectedValue(new Error('disk gone'));
+ mockWorkouts.mockResolvedValue([{ date: daysAgo(0) }]);
+ const stats = await getLoggingStats();
+ expect(stats.currentStreak).toBe(1);
+ expect(stats.domains.find((d) => d.key === 'body').total).toBe(0);
+ });
+});