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

24.2 KB
Raw Blame
import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { ArrowLeft, Flame, Trophy, Clock, Gauge, TrendingUp, History } from 'lucide-react';
import {
  LineChart, Line, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid
} from 'recharts';
import { useNavigate } from 'react-router';
import { getPostProgress } from '../../../services/api';
import useChartColors from '../../../hooks/useChartColors.js';
import { formatDurationMin } from '../../../utils/formatters';
import { DRILL_LABELS, DRILL_TO_DOMAIN, domainLabel } from './constants';
import { streakGlyph } from '../../../lib/streakGlyph.js';
import PostHistory from './PostHistory';
import TabPills from '../../ui/TabPills';

const RANGES = [
  { label: '7d', days: 7 },
  { label: '30d', days: 30 },
  { label: '90d', days: 90 },
  { label: 'All', days: 0 }
];

// Same domain palette PostHistory uses so the two views read as one system.
const DOMAIN_HEX = {
  math: '#60a5fa',
  memory: '#4ade80',
  wordplay: '#c084fc',
  verbal: '#fbbf24',
  imagination: '#22d3ee',
  cognitive: '#fb7185'
};
const domainHex = (key) => DOMAIN_HEX[key] || '#a3a3a3';

const mean = (list) => (list.length ? list.reduce((a, b) => a + b, 0) / list.length : null);

// Build per-DOMAIN per-day series client-side from the server's per-DRILL
// series (keyed by drill type), mapping each type to its domain via
// DRILL_TO_DOMAIN — the same type→domain resolution PostHistory uses, which is
// finer-grained than the server's coarse module buckets.
function buildDomainSeries(byDrill) {
  const domains = {}; // domainKey -> Map(date -> {scores, accs, resp})
  for (const [type, points] of Object.entries(byDrill || {})) {
    const domain = DRILL_TO_DOMAIN[type] || 'other';
    const dmap = domains[domain] || (domains[domain] = new Map());
    for (const p of points || []) {
      const b = dmap.get(p.date) || { scores: [], accs: [], resp: [] };
      if (typeof p.score === 'number') b.scores.push(p.score);
      if (p.accuracy != null) b.accs.push(p.accuracy);
      if (p.avgResponseMs != null) b.resp.push(p.avgResponseMs);
      dmap.set(p.date, b);
    }
  }
  const out = {};
  for (const [domain, dmap] of Object.entries(domains)) {
    out[domain] = Array.from(dmap.entries())
      .sort(([a], [b]) => a.localeCompare(b))
      .map(([date, b]) => ({
        date,
        score: b.scores.length ? Math.round(mean(b.scores)) : null,
        accuracy: b.accs.length ? mean(b.accs) : null,
        avgResponseMs: b.resp.length ? Math.round(mean(b.resp)) : null,
      }));
  }
  return out;
}

// Routed progress sub-pages (`/post/progress/:subtab`). Exported so the
// nav-manifest contract test (server/lib/navManifest.test.js) can assert each one
// is reachable from ⌘K and voice, mirroring MEMORY_SUBROUTES in PostTab.jsx.
export const PROGRESS_SUBROUTES = [
  { id: 'sessions', label: 'Sessions' },
];

const PROGRESS_TABS = [
  { id: 'trends', label: 'Trends', icon: TrendingUp },
  { id: 'sessions', label: 'Sessions', icon: History },
];

export default function PostProgress({ subtab, onBack }) {
  const navigate = useNavigate();
  const goToProgress = (id) => navigate(id === 'sessions' ? '/post/progress/sessions' : '/post/progress');
  const chartColors = useChartColors();
  const [progress, setProgress] = useState(null);
  const [range, setRange] = useState(90);
  const [domain, setDomain] = useState('all');
  const [loaded, setLoaded] = useState(false);
  // Guard against out-of-order responses: switching All (a full-history scan)
  // → 7d can let the slower All response land last and overwrite the 7d data
  // while the 7d range stays selected. Only the newest request may set state.
  const reqRef = useRef(0);

  const loadData = useCallback(async () => {
    // The Sessions sub-view renders PostHistory (its own fetch) — no need to
    // pull the progress payload for it.
    if (subtab === 'sessions') return;
    const reqId = ++reqRef.current;
    const p = await getPostProgress(range, { silent: true })
      .catch((err) => { console.warn('⚠️ Failed to load POST progress: ' + err.message); return null; });
    if (reqId !== reqRef.current) return; // a newer request superseded this one
    setProgress(p);
    setLoaded(true);
  }, [range, subtab]);

  useEffect(() => { loadData(); }, [loadData]);

  const domainSeries = useMemo(
    () => buildDomainSeries(progress?.series?.byDrill),
    [progress]
  );
  const domainKeys = useMemo(() => Object.keys(domainSeries).sort(), [domainSeries]);

  // The active series drives all three trend charts: overall per-day buckets, or
  // one domain's per-day series when a domain is selected.
  const activeSeries = useMemo(() => {
    if (domain !== 'all' && domainSeries[domain]) return domainSeries[domain];
    return progress?.series?.byDay || [];
  }, [domain, domainSeries, progress]);

  const scoreData = useMemo(
    () => activeSeries.filter(p => p.score != null).map(p => ({ date: p.date, score: p.score })),
    [activeSeries]
  );
  const accuracyData = useMemo(
    () => activeSeries.filter(p => p.accuracy != null).map(p => ({ date: p.date, accuracy: Math.round(p.accuracy * 100) })),
    [activeSeries]
  );
  const speedData = useMemo(
    () => activeSeries.filter(p => p.avgResponseMs != null).map(p => ({ date: p.date, seconds: +(p.avgResponseMs / 1000).toFixed(2) })),
    [activeSeries]
  );
  const minutesData = useMemo(
    () => (progress?.series?.byDay || []).map(p => ({ date: p.date, minutes: p.minutes })),
    [progress]
  );
  // Protocol-scoped benchmark trend (issue #4442) — only sessions run under
  // the CURRENT fixed protocol/scorer version, separate from the blended
  // "Score Trend" above which includes every scored session. `excludedCount`
  // is surfaced explicitly rather than silently omitted.
  const benchmark = progress?.series?.benchmark || null;
  // `sessions` carries through so a same-day-average point can be labeled
  // honestly — getPostProgress buckets by day, so a day with 2+ compatible
  // runs reports their MEAN, not either individual run's actual score
  // (issue #4442 codex review).
  const benchmarkScoreData = useMemo(
    () => (benchmark?.byDay || []).filter(p => p.score != null).map(p => ({ date: p.date, score: p.score, sessions: p.sessions })),
    [benchmark]
  );

  // Sub-view: the full session-list table (reuses PostHistory), deep-linked at
  // /post/progress/sessions.
  if (subtab === 'sessions') {
    return (
      <div className="space-y-4">
        <ProgressTabs subtab="sessions" onChange={goToProgress} />
        <PostHistory onBack={onBack} />
      </div>
    );
  }

  const streak = progress?.streak || { current: 0, longest: 0 };
  const totals = progress?.totals || { minutesTrained: 0, sessions: 0, practiceEntries: 0 };
  const mastery = progress?.mastery || { multiplication: null, cognitive: {}, memoryItems: [], reviews: null };
  const cognitiveMastery = Object.values(mastery.cognitive || {}).filter(Boolean);
  const dueTotal = (mastery.memoryItems || []).reduce((n, m) => n + (m.dueCount || 0), 0);
  const reviews = mastery.reviews || null;
  const hasAny = totals.sessions > 0 || totals.practiceEntries > 0;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between gap-3 flex-wrap">
        <div className="flex items-center gap-3">
          <button onClick={onBack} className="text-gray-400 hover:text-white transition-colors" aria-label="Back">
            <ArrowLeft size={20} />
          </button>
          <h2 className="text-xl font-bold text-white">Progress</h2>
        </div>
        <div className="flex gap-1">
          {RANGES.map(r => (
            <button
              key={r.label}
              onClick={() => setRange(r.days)}
              className={`px-3 py-1 text-xs rounded-lg transition-colors ${
                range === r.days ? 'bg-port-accent/20 text-port-accent' : 'text-gray-500 hover:text-white'
              }`}
            >
              {r.label}
            </button>
          ))}
        </div>
      </div>

      <ProgressTabs subtab={undefined} onChange={goToProgress} />

      {loaded && !hasAny && (
        <div className="bg-port-card border border-port-border rounded-lg text-center text-gray-500 py-12 text-sm">
          No training activity yet. Complete a POST session or a practice drill to start tracking your progress.
        </div>
      )}

      {hasAny && (
        <>
          {/* Stat cards */}
          <div className="grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-5 gap-3 sm:gap-4">
            <StatCard
              label="Current Streak"
              value={streak.current}
              suffix={streak.current === 1 ? 'day' : 'days'}
              icon={<span aria-hidden="true">{streakGlyph(streak.current)}</span>}
            />
            <StatCard
              label="Longest Streak"
              value={streak.longest}
              suffix={streak.longest === 1 ? 'day' : 'days'}
              icon={<Trophy size={14} className="text-port-accent" />}
            />
            <StatCard
              label="Time in Training"
              value={formatDurationMin(totals.minutesTrained) || '0m'}
              icon={<Clock size={14} className="text-port-success" />}
            />
            <StatCard label="Sessions" value={totals.sessions} />
            <StatCard label="Practice Drills" value={totals.practiceEntries} />
          </div>

          {/* Domain selector */}
          <div className="flex items-center gap-2 flex-wrap">
            <span className="text-xs text-gray-500 flex items-center gap-1"><Gauge size={12} /> Trend focus:</span>
            <button
              onClick={() => setDomain('all')}
              className={`px-3 py-1 text-xs rounded-lg transition-colors ${
                domain === 'all' ? 'bg-port-accent/20 text-port-accent' : 'text-gray-500 hover:text-white'
              }`}
            >
              All domains
            </button>
            {domainKeys.map(key => (
              <button
                key={key}
                onClick={() => setDomain(key)}
                className={`px-3 py-1 text-xs rounded-lg transition-colors flex items-center gap-1.5 ${
                  domain === key ? 'bg-port-accent/20 text-port-accent' : 'text-gray-500 hover:text-white'
                }`}
              >
                <span className="w-2 h-2 rounded-full" style={{ backgroundColor: domainHex(key) }} />
                {domainLabel(key)}
              </button>
            ))}
          </div>

          {/* Trend charts */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6">
            <TrendChart
              title="Score Trend"
              data={scoreData}
              dataKey="score"
              domainRange={[0, 100]}
              stroke={domain === 'all' ? chartColors.accent : domainHex(domain)}
              chartColors={chartColors}
              emptyText="Complete more sessions to chart your score."
            />
            <TrendChart
              title="Accuracy Trend"
              data={accuracyData}
              dataKey="accuracy"
              domainRange={[0, 100]}
              unit="%"
              stroke={chartColors.success}
              chartColors={chartColors}
              emptyText="No accuracy data yet."
            />
            <TrendChart
              title="Response Time (getting faster)"
              data={speedData}
              dataKey="seconds"
              domainRange={[0, 'auto']}
              unit="s"
              stroke={chartColors.warning}
              chartColors={chartColors}
              emptyText="No response-time data yet."
            />
            <TrendChart
              title="Time in Training (min/day)"
              data={minutesData}
              dataKey="minutes"
              domainRange={[0, 'auto']}
              unit="m"
              stroke={chartColors.chart2 || chartColors.success}
              chartColors={chartColors}
              emptyText="No training time logged yet."
            />
          </div>

          {/* Benchmark trend — a narrower, protocol-scoped comparison than the
              blended "Score Trend" above. Only counts sessions run under the
              CURRENT registered protocol/scorer version (issue #4442); a
              retired protocol/scorer version or an ordinary Quick/Test/Train
              session never contributes here, and the excluded count says so
              instead of quietly under-reporting. */}
          {benchmark && (
            <div className="grid grid-cols-1 gap-4 sm:gap-6">
              <div>
                {/* TrendChart's line needs 2+ points to plot — a single
                    compatible run is the common first-use case (issue #4442
                    codex review), so show its score directly instead of
                    falling into the chart's "no runs yet" empty state, which
                    would misreport a real result as none. */}
                {benchmarkScoreData.length === 1 ? (
                  <div className="bg-port-card border border-port-border rounded-lg p-4">
                    <h3 className="text-sm font-medium text-gray-400 mb-3">
                      {`Benchmark Trend — ${benchmark.protocolId} v${benchmark.protocolVersion}`}
                    </h3>
                    <div className="text-sm text-gray-300">
                      {benchmarkScoreData[0].sessions > 1
                        ? <>Day average ({benchmarkScoreData[0].sessions} runs): <span className="font-mono font-bold text-white">{benchmarkScoreData[0].score}</span> on {benchmarkScoreData[0].date}.</>
                        : <>Latest compatible run: <span className="font-mono font-bold text-white">{benchmarkScoreData[0].score}</span> on {benchmarkScoreData[0].date}.</>}
                      {' '}Complete another benchmark to chart a trend.
                    </div>
                  </div>
                ) : (
                  <TrendChart
                    title={`Benchmark Trend — ${benchmark.protocolId} v${benchmark.protocolVersion}`}
                    data={benchmarkScoreData}
                    dataKey="score"
                    domainRange={[0, 100]}
                    stroke={chartColors.accent}
                    chartColors={chartColors}
                    emptyText="No compatible benchmark runs yet — start one from the launcher."
                  />
                )}
                {benchmark.excludedCount > 0 && (
                  <p className="text-xs text-gray-500 mt-2">
                    {benchmark.excludedCount} earlier benchmark {benchmark.excludedCount === 1 ? 'run' : 'runs'} excluded — different protocol/scoring version, not comparable to the current battery.
                  </p>
                )}
              </div>
            </div>
          )}

          {/* Mastery panel */}
          <div className="grid grid-cols-1 xl:grid-cols-2 gap-4 sm:gap-6">
            {mastery.multiplication && (
              <div className="bg-port-card border border-port-border rounded-lg p-4">
                <h3 className="text-sm font-medium text-gray-400 mb-3">Multiplication Ladder</h3>
                <div className="flex items-baseline gap-2">
                  <span className="text-2xl font-mono font-bold text-white">L{mastery.multiplication.level}</span>
                  <span className="text-sm text-gray-400">{mastery.multiplication.description}</span>
                </div>
                <div className="text-xs text-gray-500 mt-1">
                  Earned floor: L{mastery.multiplication.floorLevel}
                </div>
              </div>
            )}

            {cognitiveMastery.length > 0 && (
              <div className="bg-port-card border border-port-border rounded-lg p-4 xl:col-span-2">
                <h3 className="text-sm font-medium text-gray-400 mb-3">Cognitive Ladders</h3>
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
                  {cognitiveMastery.map(info => {
                    const current = (info.levels || []).find(level => level.level === info.level) || {};
                    const targetAccuracy = info.thresholds?.targetAccuracy ?? 0;
                    const minSamples = info.thresholds?.minSamples ?? 0;
                    const action = info.decision?.action || (info.currentMastered ? 'mastered' : 'hold');
                    return (
                      <div key={info.type} className="rounded-lg border border-port-border/60 bg-port-bg/40 p-3">
                        <div className="flex items-center justify-between gap-2">
                          <div>
                            <div className="text-sm text-white">{DRILL_LABELS[info.type] || info.type}</div>
                            <div className="text-xs text-gray-500">Level {info.level + 1} of {info.levels?.length || 0} · {info.label}</div>
                          </div>
                          <span className={`text-[0.65rem] uppercase tracking-wide px-2 py-0.5 rounded-full ${
                            action === 'promote' || action === 'mastered'
                              ? 'bg-port-success/15 text-port-success'
                              : 'bg-port-warning/15 text-port-warning'
                          }`}>
                            {action === 'promote' ? 'promoted' : action}
                          </span>
                        </div>
                        <div className="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-xs text-gray-400">
                          <span>{current.samples || 0}/{minSamples} exact-rung runs</span>
                          <span>{Math.round((current.accuracy || 0) * 100)}% / {Math.round(targetAccuracy * 100)}% accuracy</span>
                          {info.thresholds?.minCompletion != null && (
                            <span>{Math.round((current.completion || 0) * 100)}% avg completion (≥{Math.round(info.thresholds.minCompletion * 100)}% qualifies)</span>
                          )}
                          {current.incompleteSamples > 0 && <span>{current.incompleteSamples} incomplete excluded</span>}
                          {current.targetMs != null && (
                            <span>{current.avgResponseMs > 0 ? `${(current.avgResponseMs / 1000).toFixed(1)}s` : '—'} / ≤{(current.targetMs / 1000).toFixed(1)}s</span>
                          )}
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            )}

            <div className="bg-port-card border border-port-border rounded-lg p-4">
              <div className="flex items-center justify-between mb-3">
                <h3 className="text-sm font-medium text-gray-400">Memory Mastery</h3>
                {dueTotal > 0 && (
                  <span className="px-2 py-0.5 bg-port-warning/20 text-port-warning text-xs rounded-full">
                    {dueTotal} due
                  </span>
                )}
              </div>
              {(mastery.memoryItems || []).length > 0 ? (
                <div className="space-y-2">
                  {mastery.memoryItems.map(item => (
                    <div key={item.id} className="flex items-center gap-3">
                      <span className="text-xs text-gray-400 w-32 shrink-0 truncate" title={item.title}>{item.title}</span>
                      <div className="flex-1 h-2 bg-port-bg rounded-full overflow-hidden">
                        <div
                          className="h-full rounded-full bg-port-success"
                          style={{ width: `${Math.min(100, Math.max(0, item.overallPct))}%` }}
                        />
                      </div>
                      <span className="text-xs font-mono w-10 text-right text-gray-400">{Math.round(item.overallPct)}%</span>
                      {item.dueCount > 0 && <Flame size={12} className="text-port-warning shrink-0" aria-label="Due for review" />}
                    </div>
                  ))}
                </div>
              ) : (
                <div className="text-center text-gray-500 py-6 text-sm">No memory items yet.</div>
              )}
            </div>
          </div>

          {/* Skill retention panel (issue #2096) — mastered skills' re-verification
              state + a 90-day retention %. Only shown once a skill is mastered. */}
          {reviews && reviews.trackedCount > 0 && (
            <div className="bg-port-card border border-port-border rounded-lg p-4">
              <div className="flex items-center justify-between mb-3">
                <h3 className="text-sm font-medium text-gray-400">Skill Retention</h3>
                <div className="flex items-center gap-2">
                  {reviews.retentionPct != null && (
                    <span className="text-xs text-gray-400">
                      90-day retention: <span className="font-mono text-white">{reviews.retentionPct}%</span>
                    </span>
                  )}
                  {reviews.dueCount > 0 && (
                    <span className="px-2 py-0.5 bg-port-warning/20 text-port-warning text-xs rounded-full">
                      {reviews.dueCount} due
                    </span>
                  )}
                </div>
              </div>
              <div className="flex flex-wrap gap-2">
                {(reviews.skills || []).map(s => (
                  <span
                    key={s.skillId}
                    className={`px-2 py-1 rounded-md text-xs border ${RETENTION_STATE_CLASS[s.state] || RETENTION_STATE_CLASS.fresh}`}
                    title={RETENTION_STATE_LABEL[s.state] || s.state}
                  >
                    {s.label}
                    <span className="ml-1 opacity-70">· {RETENTION_STATE_LABEL[s.state] || s.state}</span>
                  </span>
                ))}
              </div>
            </div>
          )}
        </>
      )}
    </div>
  );
}

// Retention-state → badge styling + human label (issue #2096).
const RETENTION_STATE_CLASS = {
  fresh: 'bg-port-success/10 border-port-success/30 text-port-success',
  due: 'bg-port-warning/10 border-port-warning/30 text-port-warning',
  'needs-refresh': 'bg-port-error/10 border-port-error/30 text-port-error',
  permanent: 'bg-emerald-500/10 border-emerald-500/30 text-emerald-300',
};
const RETENTION_STATE_LABEL = {
  fresh: 'fresh',
  due: 'due for review',
  'needs-refresh': 'needs refresh',
  permanent: 'mastered permanently',
};

function ProgressTabs({ subtab, onChange }) {
  return (
    <TabPills
      tabs={PROGRESS_TABS}
      activeTab={subtab === 'sessions' ? 'sessions' : 'trends'}
      onChange={onChange}
      mobileCompact
      ariaLabel="Progress sections"
    />
  );
}

function TrendChart({ title, data, dataKey, domainRange, unit, stroke, chartColors, emptyText }) {
  return (
    <div className="bg-port-card border border-port-border rounded-lg p-4">
      <h3 className="text-sm font-medium text-gray-400 mb-3">{title}</h3>
      {data.length > 1 ? (
        <ResponsiveContainer width="100%" height={200}>
          <LineChart data={data}>
            <CartesianGrid stroke={chartColors.grid} strokeDasharray="3 3" />
            <XAxis dataKey="date" tick={{ fontSize: 11, fill: chartColors.axis }} />
            <YAxis
              domain={domainRange}
              tick={{ fontSize: 11, fill: chartColors.axis }}
              tickFormatter={unit ? (v) => `${v}${unit}` : undefined}
            />
            <Tooltip
              contentStyle={{ backgroundColor: chartColors.tooltipBg, border: `1px solid ${chartColors.tooltipBorder}`, borderRadius: 8 }}
              labelStyle={{ color: chartColors.axis }}
              formatter={(v) => [`${v}${unit || ''}`, title]}
            />
            <Line type="monotone" dataKey={dataKey} stroke={stroke} strokeWidth={2} dot={{ r: 3 }} connectNulls />
          </LineChart>
        </ResponsiveContainer>
      ) : (
        <div className="text-center text-gray-500 py-12 text-sm">{emptyText}</div>
      )}
    </div>
  );
}

function StatCard({ label, value, suffix, valueClass = 'text-white', icon }) {
  return (
    <div className="bg-port-card border border-port-border rounded-lg p-3 text-center">
      <div className={`text-2xl font-mono font-bold flex items-center justify-center gap-1.5 ${valueClass}`}>
        {icon}
        {value}
        {suffix && <span className="text-xs font-normal text-gray-500 self-end mb-1">{suffix}</span>}
      </div>
      <div className="text-xs text-gray-500">{label}</div>
    </div>
  );
}