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

8.7 KB
Raw Blame
import { useState, useEffect, useMemo, useRef } from 'react';
import { Link, useNavigate, useSearchParams } from 'react-router';
import * as api from '../../../services/api';
import { FolderOpen, RefreshCw, AlertTriangle } from 'lucide-react';
import { timeAgo, formatDateTime } from '../../../utils/formatters';
import { WIKI_CATEGORIES, PageTypeIcon } from '../constants.jsx';
import MarkdownOutput from '../../cos/MarkdownOutput';

const LINT_REPORT_PATH = 'wiki/lint-report.md';

const WIKI_JOB_ID = 'job-wiki-maintenance';

// Reads the maintenance job's real state; 'unavailable' keeps a failed fetch
// from reading as "off". Read-only: never runs the job.
function WikiMaintenanceStatus() {
  const [state, setState] = useState({ status: 'loading', job: null });

  useEffect(() => {
    let cancelled = false;
    api.getCosJobs({ silent: true })
      .then(data => {
        if (cancelled) return;
        const job = (data?.jobs || []).find(j => j.id === WIKI_JOB_ID) || null;
        setState({ status: 'ready', job });
      })
      .catch(() => { if (!cancelled) setState({ status: 'unavailable', job: null }); });
    return () => { cancelled = true; };
  }, []);

  const { status, job } = state;
  if (status === 'loading') return null;
  if (status === 'unavailable') {
    return <p className="text-xs text-gray-600 mt-1">Wiki maintenance job status is unavailable right now.</p>;
  }
  if (job?.enabled) {
    return (
      <p className="text-xs text-gray-600 mt-1">
        Weekly wiki maintenance is on
        {job.nextRunAt ? <> — next run {formatDateTime(job.nextRunAt)}</> : null}.
      </p>
    );
  }
  return (
    <p className="text-xs text-gray-600 mt-1">
      Weekly wiki maintenance is off. Enable or run it in{' '}
      <Link to="/cos/jobs" className="text-port-accent hover:underline">System Tasks</Link>.
    </p>
  );
}

export default function OverviewTab({ vaultId, stats, notes, allNotes, onRefresh }) {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [lintReport, setLintReport] = useState(null);
  const [loadingLint, setLoadingLint] = useState(false);
  const [lintError, setLintError] = useState(false);

  const lintExists = allNotes?.some(n => n.path === LINT_REPORT_PATH);

  const openNote = (notePath) => {
    const next = new URLSearchParams(searchParams);
    next.set('note', notePath);
    navigate({ pathname: '/wiki/browse', search: next.toString() });
  };

  // Each load gets a generation; a response from a superseded load (vault switched, Retry, report removed) is dropped.
  const lintRequestRef = useRef(0);

  useEffect(() => {
    if (lintExists) loadLintReport();
    else {
      lintRequestRef.current++;
      setLoadingLint(false);
      setLintReport(null);
      setLintError(false);
    }
  }, [vaultId, lintExists]);

  // A failed read is kept distinct from "no report yet" so it never reads as an absent report.
  const loadLintReport = () => {
    const requestId = ++lintRequestRef.current;
    const isCurrent = () => requestId === lintRequestRef.current;
    setLoadingLint(true);
    setLintError(false);
    setLintReport(null);
    api.getNote(vaultId, LINT_REPORT_PATH, { silent: true })
      .then(data => {
        if (!isCurrent()) return;
        if (data?.error) throw new Error(data.error);
        setLintReport(data);
      })
      .catch(() => { if (isCurrent()) { setLintReport(null); setLintError(true); } })
      .finally(() => { if (isCurrent()) setLoadingLint(false); });
  };

  const recentPages = useMemo(() =>
    [...notes].sort((a, b) => new Date(b.modifiedAt) - new Date(a.modifiedAt)).slice(0, 10),
    [notes]
  );

  return (
    <div className="space-y-6">
      {/* Stats grid */}
      <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-3">
        <div className="bg-port-card border border-port-border rounded-lg p-4 text-center">
          <FolderOpen className="w-5 h-5 text-gray-400 mx-auto mb-1" />
          <div className="text-2xl font-bold text-white">{stats.rawSources}</div>
          <div className="text-xs text-gray-500">Raw Sources</div>
        </div>
        {WIKI_CATEGORIES.map(cat => (
          <div key={cat.key} className="bg-port-card border border-port-border rounded-lg p-4 text-center">
            <cat.icon className={`w-5 h-5 ${cat.textClass} mx-auto mb-1`} />
            <div className="text-2xl font-bold text-white">{stats[cat.key]}</div>
            <div className="text-xs text-gray-500">{cat.label}</div>
          </div>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Recent activity */}
        <div className="bg-port-card border border-port-border rounded-lg">
          <div className="px-4 py-3 border-b border-port-border flex items-center justify-between">
            <h2 className="text-sm font-medium text-white">Recent Activity</h2>
            <button onClick={onRefresh} aria-label="Refresh" className="text-gray-500 hover:text-white">
              <RefreshCw size={14} />
            </button>
          </div>
          <div className="divide-y divide-port-border/50">
            {recentPages.length === 0 ? (
              <div className="p-4 text-center text-gray-500 text-sm">No wiki pages yet. Add source files to the <code className="text-gray-300">raw/</code> folder in your vault.</div>
            ) : recentPages.map(note => (
              <button
                key={note.path}
                onClick={() => openNote(note.path)}
                className="w-full flex items-center gap-3 px-4 py-2.5 text-left hover:bg-port-bg/50 transition-colors"
              >
                <PageTypeIcon folder={note.folder} />
                <div className="flex-1 min-w-0">
                  <div className="text-sm text-white truncate">{note.name}</div>
                  <div className="text-xs text-gray-500">{note.folder}</div>
                </div>
                <span className="text-xs text-gray-500 shrink-0">{timeAgo(note.modifiedAt)}</span>
              </button>
            ))}
          </div>
        </div>

        {/* Lint report / health */}
        <div className="bg-port-card border border-port-border rounded-lg">
          <div className="px-4 py-3 border-b border-port-border flex items-center justify-between">
            <h3 className="text-sm font-medium text-white">Health Report</h3>
            {lintReport && (
              <div className="flex items-center gap-3">
                <span className="text-xs text-gray-500">Updated {timeAgo(lintReport.modifiedAt)}</span>
                <button onClick={() => openNote(LINT_REPORT_PATH)} className="text-xs text-port-accent hover:underline">Open full report</button>
              </div>
            )}
          </div>
          <div className="p-4">
            {loadingLint ? (
              <div className="flex items-center justify-center h-20">
                <RefreshCw size={16} className="animate-spin text-port-accent" />
              </div>
            ) : lintError ? (
              <div className="text-center py-6">
                <p className="text-sm text-gray-500">Couldn't load the health report</p>
                <button onClick={loadLintReport} className="text-xs text-port-accent hover:underline mt-2">Retry</button>
              </div>
            ) : lintReport ? (
              <div className="text-sm text-gray-300 max-h-64 overflow-auto">
                {lintReport.body?.trim() ? <MarkdownOutput content={lintReport.body} baseLevel={4} /> : <p className="text-gray-500">Report empty</p>}
              </div>
            ) : (
              <div className="text-center py-6">
                <AlertTriangle size={24} className="text-gray-600 mx-auto mb-2" />
                <p className="text-sm text-gray-500">No lint report yet</p>
                <WikiMaintenanceStatus />
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Quick actions */}
      <div className="bg-port-card border border-port-border rounded-lg p-4">
        <h3 className="text-sm font-medium text-white mb-3">How to Use</h3>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm text-gray-400">
          <div>
            <span className="text-port-accent font-medium">Ingest:</span> Drop markdown files into <code className="text-gray-300">raw/</code> in Obsidian, then ask Claude to ingest them
          </div>
          <div>
            <span className="text-port-accent font-medium">Query:</span> Ask questions about the wiki content — answers can be filed back as wiki pages
          </div>
          <div>
            <span className="text-port-accent font-medium">Lint:</span> Ask Claude to health-check the wiki, or let the scheduled job handle it
          </div>
        </div>
      </div>
    </div>
  );
}