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([issue-827]): add MeatSpace clinician-export view for blood + lifestyle

[._.]/ Adam Eivy3d727db68467
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index ab73fd05d6..e30bc9eb93 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -258,6 +258,7 @@ const navItems = [
{ to: '/meatspace/alcohol', label: 'Alcohol', icon: Activity },
{ to: '/meatspace/blood', label: 'Blood', icon: HeartPulse },
{ to: '/meatspace/body', label: 'Body', icon: Scale },
+ { to: '/meatspace/export', label: 'Export', icon: FileText },
{ to: '/meatspace/genome', label: 'Genome', icon: Dna },
{ to: '/meatspace/health', label: 'Body Health', icon: Heart },
{ to: '/meatspace/lifestyle', label: 'Lifestyle', icon: ClipboardList },
@@ -843,7 +844,7 @@ export default function Layout() {
{/* Sidebar */}
<aside
className={`
- fixed inset-y-0 left-0 z-50 h-screen
+ fixed inset-y-0 left-0 z-50 h-screen print:hidden
flex flex-col bg-port-card border-r border-port-border
transition-all duration-300 ease-in-out
${mobileOpen ? 'translate-x-0' : '-translate-x-full lg:translate-x-0'}
@@ -1007,7 +1008,7 @@ export default function Layout() {
{/* Main area */}
<div className={`flex-1 flex flex-col min-w-0 max-w-full transition-all duration-300 ${collapsed ? 'lg:ml-16' : 'lg:ml-56'}`}>
{/* Mobile header */}
- <header className="lg:hidden flex items-center justify-between px-2 py-1.5 border-b border-port-border bg-port-card">
+ <header className="lg:hidden flex items-center justify-between px-2 py-1.5 border-b border-port-border bg-port-card print:hidden">
<button
onClick={() => setMobileOpen(true)}
className="inline-flex items-center justify-center min-w-[40px] min-h-[40px] -ml-1 rounded-lg text-gray-400 hover:text-white"
diff --git a/client/src/components/meatspace/constants.js b/client/src/components/meatspace/constants.js
index 2810dfccd8..df0f692848 100644
--- a/client/src/components/meatspace/constants.js
+++ b/client/src/components/meatspace/constants.js
@@ -9,6 +9,7 @@ import {
Scale,
Settings,
Stethoscope,
+ FileText,
} from 'lucide-react';
export const TABS = [
@@ -17,6 +18,7 @@ export const TABS = [
{ id: 'alcohol', label: 'Alcohol', icon: Beer },
{ id: 'blood', label: 'Blood', icon: HeartPulse },
{ id: 'body', label: 'Body', icon: Scale },
+ { id: 'export', label: 'Export', icon: FileText },
{ id: 'genome', label: 'Genome', icon: Dna },
{ id: 'health', label: 'Health', icon: Stethoscope },
{ id: 'settings', label: 'Settings', icon: Settings },
diff --git a/client/src/components/meatspace/tabs/ExportTab.jsx b/client/src/components/meatspace/tabs/ExportTab.jsx
new file mode 100644
index 0000000000..c554ac0924
--- /dev/null
+++ b/client/src/components/meatspace/tabs/ExportTab.jsx
@@ -0,0 +1,177 @@
+import { useState, useEffect, useCallback } from 'react';
+import { Printer, ClipboardCopy, FileText } from 'lucide-react';
+
+import * as api from '../../../services/api';
+import { copyToClipboard } from '../../../lib/clipboard';
+import { buildClinicianReport, reportToMarkdown, formatRange } from '../../../lib/clinicianReport';
+import { STATUS_COLORS } from '../constants';
+import BrailleSpinner from '../../BrailleSpinner';
+
+const STATUS_LABELS = { normal: 'Normal', low: 'Low', high: 'High', unknown: '—' };
+
+export default function ExportTab() {
+ const [report, setReport] = useState(null);
+ const [loading, setLoading] = useState(true);
+
+ const fetchData = useCallback(async () => {
+ const [blood, config] = await Promise.all([
+ api.getBloodTests().catch(() => ({ tests: [] })),
+ api.getMeatspaceConfig().catch(() => null),
+ ]);
+ setReport(buildClinicianReport({ tests: blood?.tests || [], config }));
+ setLoading(false);
+ }, []);
+
+ useEffect(() => {
+ fetchData();
+ }, [fetchData]);
+
+ const handleCopy = async () => {
+ await copyToClipboard(reportToMarkdown(report), 'Clinician summary copied as markdown');
+ };
+
+ const handlePrint = () => {
+ window.print();
+ };
+
+ if (loading) {
+ return (
+ <div className="flex justify-center py-12">
+ <BrailleSpinner text="Building clinician summary" />
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-6">
+ {/* Action bar — hidden when printing */}
+ <div className="print:hidden flex flex-wrap items-center justify-between gap-3">
+ <div className="flex items-center gap-2">
+ <FileText size={18} className="text-port-accent" />
+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">
+ Clinician Summary
+ </h3>
+ </div>
+ <div className="flex gap-2">
+ <button
+ type="button"
+ onClick={handleCopy}
+ className="flex items-center gap-1.5 px-3 py-1.5 text-sm border border-port-border text-gray-300 rounded-lg hover:border-gray-500 hover:text-white"
+ >
+ <ClipboardCopy size={14} />
+ Copy markdown
+ </button>
+ <button
+ type="button"
+ onClick={handlePrint}
+ className="flex items-center gap-1.5 px-3 py-1.5 text-sm bg-port-accent text-white rounded-lg hover:bg-port-accent/80"
+ >
+ <Printer size={14} />
+ Print / Save PDF
+ </button>
+ </div>
+ </div>
+
+ <p className="print:hidden text-xs text-gray-600">
+ A one-page summary of your blood panels and lifestyle data to hand to a clinician.
+ Use Print to save as PDF, or copy as markdown to paste into a message or note.
+ </p>
+
+ {/* Printable report */}
+ <article className="bg-port-card border border-port-border rounded-xl p-6 space-y-8 print:bg-white print:text-black print:border-0 print:p-0">
+ <header className="space-y-1">
+ <h2 className="text-xl font-bold text-white print:text-black">
+ Clinician Summary — Blood &amp; Lifestyle
+ </h2>
+ <p className="text-xs text-gray-500 print:text-gray-700">
+ Generated {report.generatedAt.toLocaleString()}
+ </p>
+ <p className="text-xs text-gray-600 print:text-gray-700 italic">
+ Self-tracked data exported from PortOS. Reference ranges are general adult ranges
+ and not a diagnosis.
+ </p>
+ </header>
+
+ {/* Lifestyle */}
+ <section>
+ <SectionTitle>Lifestyle</SectionTitle>
+ <table className="w-full text-sm border-collapse">
+ <tbody>
+ {report.lifestyle.map(row => (
+ <tr key={row.label} className="border-b border-port-border print:border-gray-300">
+ <th scope="row" className="text-left font-medium text-gray-400 print:text-gray-700 py-1.5 pr-4 align-top w-40">
+ {row.label}
+ </th>
+ <td className="py-1.5 pr-4 text-gray-200 print:text-black">{row.value}</td>
+ <td className="py-1.5 text-xs text-gray-500 print:text-gray-600">{row.note || ''}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </section>
+
+ {/* Blood panels */}
+ <section className="space-y-6">
+ <SectionTitle>Blood Panels</SectionTitle>
+ {report.bloodTests.length === 0 ? (
+ <p className="text-sm text-gray-500 print:text-gray-700">No blood test data on record.</p>
+ ) : (
+ report.bloodTests.map(test => (
+ <div key={test.date} className="space-y-3 print:break-inside-avoid">
+ <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
+ <h4 className="text-base font-semibold text-gray-200 print:text-black">{test.date}</h4>
+ {test.outOfRange.length > 0 && (
+ <span className="text-xs text-port-error print:text-red-700">
+ {test.outOfRange.length} marker{test.outOfRange.length === 1 ? '' : 's'} out of range
+ </span>
+ )}
+ </div>
+ {test.categories.map(({ category, markers }) => (
+ <div key={category}>
+ <h5 className="text-xs font-medium text-gray-500 print:text-gray-700 uppercase mb-1">
+ {category}
+ </h5>
+ <table className="w-full text-sm border-collapse">
+ <thead>
+ <tr className="text-left text-xs text-gray-600 print:text-gray-700">
+ <th scope="col" className="py-1 pr-4 font-normal">Marker</th>
+ <th scope="col" className="py-1 pr-4 font-normal">Value</th>
+ <th scope="col" className="py-1 pr-4 font-normal">Reference</th>
+ <th scope="col" className="py-1 font-normal">Flag</th>
+ </tr>
+ </thead>
+ <tbody>
+ {markers.map(m => (
+ <tr key={m.key} className="border-t border-port-border print:border-gray-300">
+ <td className="py-1 pr-4 text-gray-300 print:text-black">{m.label}</td>
+ <td className={`py-1 pr-4 font-mono ${m.outOfRange ? STATUS_COLORS[m.status] : 'text-gray-200'} print:text-black`}>
+ {m.value}{m.unit ? ` ${m.unit}` : ''}
+ </td>
+ <td className="py-1 pr-4 text-gray-500 print:text-gray-700 font-mono">
+ {formatRange(m.range) || '—'}
+ </td>
+ <td className={`py-1 ${m.outOfRange ? STATUS_COLORS[m.status] : 'text-gray-600'} print:text-black`}>
+ {m.outOfRange ? STATUS_LABELS[m.status] : ''}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ ))}
+ </div>
+ ))
+ )}
+ </section>
+ </article>
+ </div>
+ );
+}
+
+function SectionTitle({ children }) {
+ return (
+ <h3 className="text-sm font-medium text-gray-400 print:text-black uppercase tracking-wider mb-3 border-b border-port-border print:border-gray-400 pb-1">
+ {children}
+ </h3>
+ );
+}
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 40d4ffd48c..a6d96a5415 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -62,6 +62,7 @@ grep -i "what you want to do" client/src/lib/README.md
|---|---|
| `audioRecorder.js` | `startMemoRecording()` → `{ stop, cancel }` handle whose `stop()` resolves to `{ audioBase64, mimeType, peak, durationMs }` (16 kHz mono WAV, base64). Plus `blobToWav16k`, `encodePcmToWav`, `pickRecordingMimeType`, `arrayBufferToBase64`. Standalone one-shot memo capture for catalog voice ingest — NOT the live voice-agent recorder in `services/voiceClient.js`. |
| `clientErrorReporter.js` | `reportClientError({ type, error?, message?, ... })` — POSTs window.onerror + unhandledrejection events to `/api/client-errors` with throttle + dedup. Wired from `main.jsx`; never call directly from React components. |
+| `clinicianReport.js` | Pure builders for the MeatSpace clinician-export view (`/meatspace/export`). `buildClinicianReport({ tests, config })` → structured report model (blood panels grouped by category with reference ranges + out-of-range flags, plus a lifestyle summary); `reportToMarkdown(report)` → copy-paste markdown. Reuses the Blood tab's `REFERENCE_RANGES` / `getBloodValueStatus` so printed flags match the UI. Also exports `buildBloodTestModel`, `buildLifestyleModel`, `getCategoryForKey`, `formatRange`. |
| `clipboard.js` | `copyToClipboard`, `writeClipboardSilently`, `readClipboard` — safe across insecure-origin contexts. Use these instead of `navigator.clipboard.writeText` inline. |
| `compareHelpers.js` | `equalByKeys(a, b, keys)` / `equalListByKeys(a, b, keys)` — typed key-based equality for `useAutoRefetch`'s `compare`. Keys are property names, dotted paths (`'context.running'`), or `(item) => value` accessors. The typed alternative to `sameJsonShape` when a monotonic timestamp or unrendered field would break stringify-equality dedup. |
| `genUtils.js` | Shared bits between Image Gen and Video Gen pages. |
diff --git a/client/src/lib/clinicianReport.js b/client/src/lib/clinicianReport.js
new file mode 100644
index 0000000000..a4c8e770d7
--- /dev/null
+++ b/client/src/lib/clinicianReport.js
@@ -0,0 +1,205 @@
+/**
+ * clinicianReport.js — pure builders for the MeatSpace clinician-export view.
+ *
+ * Turns raw blood-test history + lifestyle config into a structured,
+ * doctor-friendly report model and a copy-paste markdown rendering. No React,
+ * no I/O — fully unit-testable. Reuses the blood reference ranges and status
+ * classifier that the Blood tab already uses, so the printed flags match the UI.
+ */
+
+import { REFERENCE_RANGES, getBloodValueStatus } from '../components/meatspace/constants.js';
+
+// Blood-marker category grouping — mirrors BloodTestCard's getCategoryForKey so
+// the printed report sections match the on-screen tab grouping.
+const CATEGORY_KEYS = {
+ 'Metabolic Panel': [
+ 'glucose', 'bun', 'creatinine', 'egfr', 'na', 'k', 'ci', 'co2',
+ 'calcium', 'protein', 'albumin', 'globulin', 'a_g_ratio', 'bilirubin',
+ 'bili_direct', 'alk_phos', 'sgot_ast', 'alt', 'hba1c', 'anion_gap', 'apoB'
+ ],
+ Lipids: ['cholesterol', 'hdl', 'ldl', 'triglycerides', 'chol_hdl_ratio', 'non_hdl_col'],
+ CBC: [
+ 'wbc', 'rbc', 'hemoglobin', 'hematocrit', 'platelets',
+ 'mcv', 'mch', 'mchc', 'rdw', 'mpv',
+ 'neutrophils_pct', 'lymphocytes_pct', 'monocytes_pct', 'eosinophils_pct', 'basophils_pct',
+ 'abs_neutrophils', 'abs_lymphocytes', 'abs_monocytes', 'abs_eosinophils', 'abs_basophils'
+ ],
+ Thyroid: ['tsh', 'free_t4', 'free_t3'],
+};
+
+const CATEGORY_ORDER = ['Metabolic Panel', 'Lipids', 'CBC', 'Thyroid', 'Other'];
+
+export function getCategoryForKey(key) {
+ for (const [category, keys] of Object.entries(CATEGORY_KEYS)) {
+ if (keys.includes(key)) return category;
+ }
+ return 'Other';
+}
+
+const STATUS_LABELS = { normal: 'Normal', low: 'Low', high: 'High', unknown: '' };
+
+export function formatRange(range) {
+ if (!range) return '';
+ const unit = range.unit ? ` ${range.unit}` : '';
+ return `${range.min}–${range.max}${unit}`;
+}
+
+/**
+ * Build the structured model for a single blood test record. Returns the date
+ * plus markers grouped by category, each carrying value/range/status/flag.
+ */
+export function buildBloodTestModel(test) {
+ if (!test || typeof test !== 'object') return null;
+ const { date, ...values } = test;
+ const grouped = {};
+ for (const [key, value] of Object.entries(values)) {
+ if (value == null || typeof value !== 'number') continue;
+ const range = REFERENCE_RANGES[key];
+ const status = getBloodValueStatus(value, range);
+ const category = range ? getCategoryForKey(key) : 'Other';
+ if (!grouped[category]) grouped[category] = [];
+ grouped[category].push({
+ key,
+ label: range?.label || key,
+ value,
+ unit: range?.unit || '',
+ range,
+ status,
+ outOfRange: status === 'low' || status === 'high',
+ });
+ }
+ const categories = CATEGORY_ORDER
+ .filter(cat => grouped[cat]?.length)
+ .map(cat => ({ category: cat, markers: grouped[cat] }));
+ const outOfRange = categories.flatMap(c => c.markers).filter(m => m.outOfRange);
+ return { date: date || 'Undated', categories, outOfRange };
+}
+
+const SMOKING_LABELS = { never: 'Never', former: 'Former', current: 'Current' };
+const DIET_LABELS = { excellent: 'Excellent', good: 'Good', fair: 'Fair', poor: 'Poor' };
+const STRESS_LABELS = { low: 'Low', moderate: 'Moderate', high: 'High' };
+
+function bmiCategory(bmi) {
+ if (bmi == null) return '';
+ if (bmi < 18.5) return 'Underweight';
+ if (bmi < 25) return 'Normal';
+ if (bmi < 30) return 'Overweight';
+ return 'Obese';
+}
+
+/**
+ * Build the lifestyle section as a list of `{ label, value, note }` rows.
+ * `LIFESTYLE_ADJUSTMENTS` keys define which factors the clinician summary covers.
+ */
+export function buildLifestyleModel(config) {
+ const lifestyle = config?.lifestyle || {};
+ const sex = config?.sex;
+ const rows = [];
+ rows.push({ label: 'Biological sex', value: sex ? capitalize(sex) : 'Not specified' });
+ rows.push({
+ label: 'Smoking',
+ value: SMOKING_LABELS[lifestyle.smokingStatus] || 'Not specified',
+ });
+ if (lifestyle.alcoholDrinksPerDay != null) {
+ rows.push({ label: 'Alcohol', value: `${lifestyle.alcoholDrinksPerDay} drinks/day (self-reported)` });
+ }
+ rows.push({
+ label: 'Exercise',
+ value: lifestyle.exerciseMinutesPerWeek != null
+ ? `${lifestyle.exerciseMinutesPerWeek} min/week`
+ : 'Not specified',
+ note: 'WHO target: 150+ min/week moderate activity',
+ });
+ rows.push({
+ label: 'Sleep',
+ value: lifestyle.sleepHoursPerNight != null
+ ? `${lifestyle.sleepHoursPerNight} hrs/night`
+ : 'Not specified',
+ note: 'Optimal range: 7–9 hrs',
+ });
+ rows.push({ label: 'Diet quality', value: DIET_LABELS[lifestyle.dietQuality] || 'Not specified' });
+ rows.push({ label: 'Stress level', value: STRESS_LABELS[lifestyle.stressLevel] || 'Not specified' });
+ rows.push({
+ label: 'BMI',
+ value: lifestyle.bmi != null ? `${lifestyle.bmi}` : 'Not specified',
+ note: bmiCategory(lifestyle.bmi) || undefined,
+ });
+ const conditions = Array.isArray(lifestyle.chronicConditions) ? lifestyle.chronicConditions : [];
+ if (conditions.length) {
+ rows.push({ label: 'Chronic conditions', value: conditions.join(', ') });
+ }
+ return rows;
+}
+
+function capitalize(s) {
+ return typeof s === 'string' && s.length ? s[0].toUpperCase() + s.slice(1) : s;
+}
+
+/**
+ * Build the full clinician report model from blood tests + lifestyle config.
+ * `tests` is the raw array from the Blood tab (oldest-first); the report shows
+ * newest-first. `generatedAt` is injected for testability.
+ */
+export function buildClinicianReport({ tests = [], config = null, generatedAt = new Date() } = {}) {
+ const bloodTests = (Array.isArray(tests) ? tests : [])
+ .map(buildBloodTestModel)
+ .filter(Boolean)
+ .reverse();
+ return {
+ generatedAt: generatedAt instanceof Date ? generatedAt : new Date(generatedAt),
+ bloodTests,
+ lifestyle: buildLifestyleModel(config),
+ };
+}
+
+/** Serialize a report model to clipboard-friendly markdown. */
+export function reportToMarkdown(report) {
+ if (!report) return '';
+ const lines = [];
+ lines.push('# Clinician Summary — Blood & Lifestyle');
+ lines.push('');
+ lines.push(`_Generated ${report.generatedAt.toLocaleString()}_`);
+ lines.push('');
+ lines.push('> Self-tracked data exported from PortOS MeatSpace. Reference ranges are general adult ranges and not a diagnosis.');
+ lines.push('');
+
+ lines.push('## Lifestyle');
+ lines.push('');
+ lines.push('| Factor | Value | Note |');
+ lines.push('| --- | --- | --- |');
+ for (const row of report.lifestyle) {
+ lines.push(`| ${row.label} | ${row.value} | ${row.note || ''} |`);
+ }
+ lines.push('');
+
+ lines.push('## Blood Panels');
+ lines.push('');
+ if (!report.bloodTests.length) {
+ lines.push('_No blood test data on record._');
+ lines.push('');
+ }
+ for (const test of report.bloodTests) {
+ lines.push(`### ${test.date}`);
+ lines.push('');
+ if (test.outOfRange.length) {
+ const flags = test.outOfRange
+ .map(m => `${m.label} ${m.value}${m.unit ? ` ${m.unit}` : ''} (${STATUS_LABELS[m.status]})`)
+ .join(', ');
+ lines.push(`**Out of range:** ${flags}`);
+ lines.push('');
+ }
+ for (const { category, markers } of test.categories) {
+ lines.push(`#### ${category}`);
+ lines.push('');
+ lines.push('| Marker | Value | Reference | Flag |');
+ lines.push('| --- | --- | --- | --- |');
+ for (const m of markers) {
+ const value = `${m.value}${m.unit ? ` ${m.unit}` : ''}`;
+ lines.push(`| ${m.label} | ${value} | ${formatRange(m.range)} | ${STATUS_LABELS[m.status]} |`);
+ }
+ lines.push('');
+ }
+ }
+
+ return lines.join('\n').trimEnd() + '\n';
+}
diff --git a/client/src/lib/clinicianReport.test.js b/client/src/lib/clinicianReport.test.js
new file mode 100644
index 0000000000..5a545b8bd6
--- /dev/null
+++ b/client/src/lib/clinicianReport.test.js
@@ -0,0 +1,140 @@
+import { describe, it, expect } from 'vitest';
+import {
+ buildBloodTestModel,
+ buildLifestyleModel,
+ buildClinicianReport,
+ reportToMarkdown,
+ getCategoryForKey,
+ formatRange,
+} from './clinicianReport.js';
+
+describe('getCategoryForKey', () => {
+ it('groups known markers into their panels', () => {
+ expect(getCategoryForKey('glucose')).toBe('Metabolic Panel');
+ expect(getCategoryForKey('ldl')).toBe('Lipids');
+ expect(getCategoryForKey('wbc')).toBe('CBC');
+ expect(getCategoryForKey('tsh')).toBe('Thyroid');
+ });
+
+ it('falls back to Other for unknown markers', () => {
+ expect(getCategoryForKey('mystery_marker')).toBe('Other');
+ });
+});
+
+describe('formatRange', () => {
+ it('formats a range with unit', () => {
+ expect(formatRange({ min: 70, max: 99, unit: 'mg/dL' })).toBe('70–99 mg/dL');
+ });
+ it('omits the unit when blank', () => {
+ expect(formatRange({ min: 1, max: 2.5, unit: '' })).toBe('1–2.5');
+ });
+ it('returns empty string for no range', () => {
+ expect(formatRange(null)).toBe('');
+ });
+});
+
+describe('buildBloodTestModel', () => {
+ it('groups markers, classifies status, and surfaces out-of-range flags', () => {
+ const model = buildBloodTestModel({
+ date: '2025-01-15',
+ glucose: 110, // high (range 70-99)
+ hdl: 55, // normal
+ ldl: 90, // normal
+ notANumber: 'skip me',
+ missing: null,
+ });
+ expect(model.date).toBe('2025-01-15');
+ const metabolic = model.categories.find(c => c.category === 'Metabolic Panel');
+ expect(metabolic.markers.map(m => m.key)).toEqual(['glucose']);
+ expect(metabolic.markers[0].status).toBe('high');
+ expect(metabolic.markers[0].outOfRange).toBe(true);
+ const lipids = model.categories.find(c => c.category === 'Lipids');
+ expect(lipids.markers.every(m => !m.outOfRange)).toBe(true);
+ expect(model.outOfRange.map(m => m.key)).toEqual(['glucose']);
+ });
+
+ it('returns null for non-objects', () => {
+ expect(buildBloodTestModel(null)).toBeNull();
+ expect(buildBloodTestModel(42)).toBeNull();
+ });
+
+ it('labels an undated record', () => {
+ expect(buildBloodTestModel({ glucose: 80 }).date).toBe('Undated');
+ });
+});
+
+describe('buildLifestyleModel', () => {
+ it('renders specified lifestyle factors with labels and notes', () => {
+ const rows = buildLifestyleModel({
+ sex: 'male',
+ lifestyle: {
+ smokingStatus: 'former',
+ exerciseMinutesPerWeek: 200,
+ sleepHoursPerNight: 8,
+ dietQuality: 'good',
+ stressLevel: 'low',
+ bmi: 23.1,
+ chronicConditions: ['hypertension'],
+ },
+ });
+ const byLabel = Object.fromEntries(rows.map(r => [r.label, r]));
+ expect(byLabel['Biological sex'].value).toBe('Male');
+ expect(byLabel.Smoking.value).toBe('Former');
+ expect(byLabel.Exercise.value).toBe('200 min/week');
+ expect(byLabel.BMI.note).toBe('Normal');
+ expect(byLabel['Chronic conditions'].value).toBe('hypertension');
+ });
+
+ it('marks unspecified factors rather than dropping them', () => {
+ const rows = buildLifestyleModel(null);
+ const byLabel = Object.fromEntries(rows.map(r => [r.label, r]));
+ expect(byLabel['Biological sex'].value).toBe('Not specified');
+ expect(byLabel.Smoking.value).toBe('Not specified');
+ expect(byLabel.BMI.value).toBe('Not specified');
+ });
+
+ it('ignores a non-array chronicConditions value', () => {
+ const rows = buildLifestyleModel({ lifestyle: { chronicConditions: 'oops' } });
+ expect(rows.some(r => r.label === 'Chronic conditions')).toBe(false);
+ });
+});
+
+describe('buildClinicianReport + reportToMarkdown', () => {
+ const fixture = {
+ generatedAt: new Date('2025-02-01T12:00:00Z'),
+ tests: [
+ { date: '2024-06-01', glucose: 85 },
+ { date: '2025-01-15', glucose: 110, hdl: 55 },
+ ],
+ config: { sex: 'female', lifestyle: { smokingStatus: 'never', bmi: 21 } },
+ };
+
+ it('orders blood tests newest-first', () => {
+ const report = buildClinicianReport(fixture);
+ expect(report.bloodTests.map(t => t.date)).toEqual(['2025-01-15', '2024-06-01']);
+ });
+
+ it('tolerates a non-array tests value', () => {
+ const report = buildClinicianReport({ tests: 'nope', config: null });
+ expect(report.bloodTests).toEqual([]);
+ });
+
+ it('renders markdown with lifestyle, panels, ranges, and flags', () => {
+ const md = reportToMarkdown(buildClinicianReport(fixture));
+ expect(md).toContain('# Clinician Summary — Blood & Lifestyle');
+ expect(md).toContain('## Lifestyle');
+ expect(md).toContain('| Marker | Value | Reference | Flag |');
+ expect(md).toContain('70–99 mg/dL');
+ expect(md).toContain('**Out of range:** Glucose 110 mg/dL (High)');
+ expect(md.endsWith('\n')).toBe(true);
+ });
+
+ it('notes when no blood data exists', () => {
+ const md = reportToMarkdown(buildClinicianReport({ tests: [], config: null }));
+ expect(md).toContain('_No blood test data on record._');
+ });
+
+ it('returns empty string for a null report', () => {
+ expect(reportToMarkdown(null)).toBe('');
+ });
+});
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 4fe4377325..a1d1e3c743 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -33,6 +33,7 @@ export * from './graphSimulation.js';
// === Generic UI / collection utilities ===
export * from './audioRecorder.js';
export * from './clientErrorReporter.js';
+export * from './clinicianReport.js';
export * from './clipboard.js';
export * from './compareHelpers.js';
export * from './genUtils.js';
diff --git a/client/src/pages/MeatSpace.jsx b/client/src/pages/MeatSpace.jsx
index a028a92b13..ead8e01005 100644
--- a/client/src/pages/MeatSpace.jsx
+++ b/client/src/pages/MeatSpace.jsx
@@ -9,6 +9,7 @@ import AgeTab from '../components/meatspace/tabs/AgeTab';
import AlcoholTab from '../components/meatspace/tabs/AlcoholTab';
import BloodTab from '../components/meatspace/tabs/BloodTab';
import BodyTab from '../components/meatspace/tabs/BodyTab';
+import ExportTab from '../components/meatspace/tabs/ExportTab';
import GenomeTab from '../components/meatspace/tabs/GenomeTab';
import HealthTab from '../components/meatspace/tabs/HealthTab';
import SettingsTab from '../components/meatspace/tabs/SettingsTab';
@@ -36,6 +37,8 @@ export default function MeatSpace() {
return <BloodTab />;
case 'body':
return <BodyTab />;
+ case 'export':
+ return <ExportTab />;
case 'genome':
return <GenomeTab />;
case 'health':
@@ -53,10 +56,12 @@ export default function MeatSpace() {
return (
<div className="flex flex-col h-full">
- <MortalLoomBanner section="Meatspace health data" />
+ <div className="print:hidden">
+ <MortalLoomBanner section="Meatspace health data" />
+ </div>
{/* Header */}
- <div className="shrink-0 px-6 pt-6 pb-4 border-b border-port-border">
+ <div className="shrink-0 px-6 pt-6 pb-4 border-b border-port-border print:hidden">
<div className="flex items-center gap-3 mb-4">
<Skull size={24} className="text-port-error" />
<h1 className="text-2xl font-bold text-white">MeatSpace</h1>
@@ -83,7 +88,7 @@ export default function MeatSpace() {
</div>
{/* Tab content */}
- <div className="flex-1 overflow-auto p-6">
+ <div className="flex-1 overflow-auto p-6 print:overflow-visible print:p-0">
{renderTabContent()}
</div>
</div>
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index eb9a53bee9..64f8187d1f 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -124,6 +124,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.meatspace.nicotine', path: '/meatspace/nicotine', label: 'Nicotine', section: 'MeatSpace', aliases: ['meatspace-nicotine', 'nicotine'] },
{ id: 'nav.meatspace.age', path: '/meatspace/age', label: 'Age', section: 'MeatSpace', aliases: ['meatspace-age'] },
{ id: 'nav.meatspace.blood', path: '/meatspace/blood', label: 'Blood', section: 'MeatSpace', aliases: ['meatspace-blood', 'blood'] },
+ { id: 'nav.meatspace.export', path: '/meatspace/export', label: 'Export', section: 'MeatSpace', aliases: ['meatspace-export', 'clinician-export', 'health-export'], keywords: ['clinician', 'doctor', 'print', 'pdf', 'summary', 'report', 'blood', 'lifestyle'] },
{ id: 'nav.meatspace.genome', path: '/meatspace/genome', label: 'Genome', section: 'MeatSpace', aliases: ['meatspace-genome', 'genome'] },
{ id: 'nav.meatspace.lifestyle', path: '/meatspace/lifestyle', label: 'Lifestyle', section: 'MeatSpace', aliases: ['meatspace-lifestyle', 'lifestyle'] },
{ id: 'nav.meatspace.settings', path: '/meatspace/settings', label: 'Settings', section: 'MeatSpace', aliases: ['meatspace-settings'] },