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

13.7 KB
Raw Blame
import { useCallback, useState, useEffect } from 'react';
import {Download,
  Copy,
  Check,
  FileText,
  Code,
  FileJson,
  Files,
  Eye,
  BookOpen} from 'lucide-react';
import BrailleSpinner from '../../BrailleSpinner';
import * as api from '../../../services/api';
import toast from '../../ui/Toast';
import { copyToClipboard } from '../../../lib/clipboard';
import { downloadBlob } from '../../../lib/downloadBlob';
import { formatCount } from '../../../utils/formatters';
import ListLoadError from '../../ui/ListLoadError';
import useListResource from '../../../hooks/useListResource';

import { DOCUMENT_CATEGORIES } from '../constants';

const fetchDocuments = () => api.getDigitalTwinDocuments({ silent: true });
const fetchFormats = () => api.getDigitalTwinExportFormats({ silent: true });

export default function ExportTab({ onRefresh: _onRefresh }) {
  const documentsResource = useListResource(fetchDocuments);
  const formatsResource = useListResource(fetchFormats);
  const { items: documents, retry: retryDocuments } = documentsResource;
  const { items: formats, retry: retryFormats } = formatsResource;
  const loadError = [documentsResource, formatsResource].find((resource) => resource.state === 'error') || null;
  const loading = !loadError && (documentsResource.state === 'loading' || formatsResource.state === 'loading');
  const retryLoad = useCallback(() => { retryDocuments(); retryFormats(); }, [retryDocuments, retryFormats]);
  const [exporting, setExporting] = useState(false);

  // Export configuration
  const [selectedFormat, setSelectedFormat] = useState('system_prompt');
  const [selectedDocs, setSelectedDocs] = useState([]);
  const [includeDisabled, setIncludeDisabled] = useState(false);

  // Export result
  const [exportResult, setExportResult] = useState(null);
  const [copied, setCopied] = useState(false);

  // Default: select all enabled documents once the library has loaded. An empty
  // selection exports EVERYTHING (see handleExport), so it must never be seeded
  // from a failed read — the whole tab fails into a retry instead.
  useEffect(() => {
    if (documentsResource.state !== 'ready') return;
    setSelectedDocs(documents.filter(d => d.enabled).map(d => d.id));
  }, [documentsResource.state, documents]);

  const toggleDocument = (docId) => {
    setSelectedDocs(prev =>
      prev.includes(docId) ? prev.filter(id => id !== docId) : [...prev, docId]
    );
  };

  const handleExport = async () => {
    setExporting(true);
    try {
      const result = await api.exportSoul(
        selectedFormat,
        selectedDocs.length > 0 ? selectedDocs : null,
        includeDisabled
      );
      setExportResult(result);
    } catch {
      // The request helper already shows the failure toast.
    } finally {
      setExporting(false);
    }
  };

  const handleCopyExport = async () => {
    if (!exportResult) return;

    const content = typeof exportResult.content === 'string'
      ? exportResult.content
      : JSON.stringify(exportResult.content, null, 2);

    const ok = await copyToClipboard(content, 'Copied to clipboard');
    if (ok) {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  const downloadFile = () => {
    if (!exportResult) return;

    const content = typeof exportResult.content === 'string'
      ? exportResult.content
      : JSON.stringify(exportResult.content, null, 2);

    const extension = selectedFormat === 'json' ? 'json' : 'md';
    const filename = selectedFormat === 'legacy_portrait'
      ? `legacy-portrait-${new Date().toISOString().slice(0, 10)}.md`
      : `soul-export.${extension}`;

    downloadBlob(content, filename, 'text/plain');

    toast.success(`Downloaded ${filename}`);
  };

  const getFormatIcon = (formatId) => {
    switch (formatId) {
      case 'system_prompt':
        return FileText;
      case 'agents_md':
      // Pre-#4852 id, still resolvable from a persisted preference.
      case 'claude_md':
        return Code;
      case 'json':
        return FileJson;
      case 'individual':
        return Files;
      case 'legacy_portrait':
        return BookOpen;
      default:
        return FileText;
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <BrailleSpinner text="Loading" />
      </div>
    );
  }

  if (loadError) {
    return <ListLoadError what="export options" error={loadError.error} onRetry={retryLoad} />;
  }

  return (
    <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6">
      {/* Configuration */}
      <div className="space-y-4 sm:space-y-6">
        {/* Format Selection */}
        <div className="bg-port-card rounded-lg border border-port-border p-4">
          <h3 className="font-semibold text-white mb-4">Export Format</h3>
          <div className="space-y-2">
            {formats.map(format => {
              const Icon = getFormatIcon(format.id);
              return (
                <button
                  key={format.id}
                  onClick={() => {
                    setSelectedFormat(format.id);
                    setExportResult(null);
                  }}
                  className={`w-full flex items-start gap-3 p-3 min-h-[60px] rounded-lg border transition-colors text-left ${
                    selectedFormat === format.id
                      ? 'border-port-accent bg-port-accent/10'
                      : 'border-port-border hover:border-gray-500'
                  }`}
                >
                  <Icon className={`w-5 h-5 mt-0.5 shrink-0 ${
                    selectedFormat === format.id ? 'text-port-accent' : 'text-gray-400'
                  }`} />
                  <div className="min-w-0">
                    <div className={`font-medium ${
                      selectedFormat === format.id ? 'text-port-accent' : 'text-white'
                    }`}>
                      {format.label}
                    </div>
                    <div className="text-sm text-gray-400">{format.description}</div>
                  </div>
                </button>
              );
            })}
          </div>
        </div>

        {/* Document Selection */}
        <div className="bg-port-card rounded-lg border border-port-border p-4">
          <div className="flex items-center justify-between mb-4">
            <h3 className="font-semibold text-white">Documents ({selectedDocs.length})</h3>
            <div className="flex gap-3">
              <button
                onClick={() => setSelectedDocs(documents.map(d => d.id))}
                className="text-xs py-1 px-2 min-h-[32px] text-port-accent hover:text-white"
              >
                All
              </button>
              <button
                onClick={() => setSelectedDocs(documents.filter(d => d.enabled).map(d => d.id))}
                className="text-xs py-1 px-2 min-h-[32px] text-gray-500 hover:text-white"
              >
                Enabled
              </button>
              <button
                onClick={() => setSelectedDocs([])}
                className="text-xs py-1 px-2 min-h-[32px] text-gray-500 hover:text-white"
              >
                None
              </button>
            </div>
          </div>

          <div className="space-y-1 max-h-64 overflow-y-auto">
            {documents.map(doc => (
              <label
                key={doc.id}
                className="flex items-center gap-3 p-2 min-h-[44px] rounded hover:bg-port-border cursor-pointer"
              >
                <input
                  type="checkbox"
                  checked={selectedDocs.includes(doc.id)}
                  onChange={() => toggleDocument(doc.id)}
                  className="w-5 h-5 rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"
                />
                <div className="flex-1 min-w-0">
                  <div className={`text-sm truncate ${doc.enabled ? 'text-white' : 'text-gray-500'}`}>
                    {doc.title}
                  </div>
                  <div className="text-xs text-gray-500">
                    {DOCUMENT_CATEGORIES[doc.category]?.label}
                    {!doc.enabled && ' • Disabled'}
                  </div>
                </div>
              </label>
            ))}
          </div>

          <label className="flex items-center gap-3 mt-4 pt-4 border-t border-port-border min-h-[44px]">
            <input
              type="checkbox"
              checked={includeDisabled}
              onChange={(e) => setIncludeDisabled(e.target.checked)}
              className="w-5 h-5 rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"
            />
            <span className="text-sm text-gray-400">Include disabled documents</span>
          </label>
        </div>

        {/* Export Button */}
        <button
          onClick={handleExport}
          disabled={exporting || selectedDocs.length === 0}
          className="w-full flex items-center justify-center gap-2 px-6 py-3 min-h-[48px] bg-port-accent text-white rounded-lg font-medium hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {exporting ? (
            <>
              <BrailleSpinner />
              Exporting...
            </>
          ) : (
            <>
              <Download className="w-5 h-5" />
              Generate Export
            </>
          )}
        </button>
      </div>

      {/* Preview / Result */}
      <div className="bg-port-card rounded-lg border border-port-border overflow-hidden flex flex-col min-h-[300px] lg:min-h-0">
        <div className="p-4 border-b border-port-border flex flex-wrap items-center justify-between gap-2">
          <h3 className="font-semibold text-white flex items-center gap-2">
            <Eye size={18} />
            Preview
          </h3>

          {exportResult && (
            <div className="flex items-center gap-2">
              <span className="text-sm text-gray-500 hidden sm:inline">
                ~{formatCount(exportResult.tokenEstimate)} tokens
              </span>
              <button
                onClick={handleCopyExport}
                className="p-2 min-h-[40px] min-w-[40px] flex items-center justify-center text-gray-400 hover:text-white transition-colors"
                title="Copy to clipboard" aria-label="Copy to clipboard"
              >
                {copied ? <Check size={18} className="text-port-success" /> : <Copy size={18} />}
              </button>
              <button
                onClick={downloadFile}
                className="p-2 min-h-[40px] min-w-[40px] flex items-center justify-center text-gray-400 hover:text-white transition-colors"
                title="Download" aria-label="Download"
              >
                <Download size={18} />
              </button>
            </div>
          )}
        </div>

        <div className="flex-1 overflow-auto p-4">
          {exportResult ? (
            <pre className="text-sm text-gray-300 whitespace-pre-wrap break-all font-mono">
              {typeof exportResult.content === 'string'
                ? exportResult.content
                : JSON.stringify(exportResult.content, null, 2)}
            </pre>
          ) : (
            <div className="flex items-center justify-center h-full text-gray-500">
              <div className="text-center">
                <Download className="w-12 h-12 mx-auto mb-4 opacity-50" />
                <p>Select options and generate export</p>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Usage Instructions */}
      {exportResult && (
        <div className="lg:col-span-2 bg-port-card rounded-lg border border-port-border p-4">
          <h3 className="font-semibold text-white mb-3">How to Use</h3>

          {selectedFormat === 'system_prompt' && (
            <div className="text-sm text-gray-400 space-y-2">
              <p>1. Copy the exported content</p>
              <p>2. Paste into your LLMs system prompt / custom instructions</p>
              <p>3. The LLM will now respond according to your soul document</p>
            </div>
          )}

          {(selectedFormat === 'agents_md' || selectedFormat === 'claude_md') && (
            <div className="text-sm text-gray-400 space-y-2">
              <p>1. Download or copy the export</p>
              <p>2. Add to your project as <code className="bg-port-bg px-1 rounded">AGENTS.md</code>, with a <code className="bg-port-bg px-1 rounded">CLAUDE.md</code> next to it containing just <code className="bg-port-bg px-1 rounded">@AGENTS.md</code></p>
              <p>3. Every agent CLI — Claude Code included — will read and apply these instructions</p>
            </div>
          )}

          {selectedFormat === 'json' && (
            <div className="text-sm text-gray-400 space-y-2">
              <p>1. Download the JSON export</p>
              <p>2. Parse and inject into your API requests</p>
              <p>3. Use the documents array to build system prompts programmatically</p>
            </div>
          )}

          {selectedFormat === 'individual' && (
            <div className="text-sm text-gray-400 space-y-2">
              <p>1. Each document is exported separately</p>
              <p>2. Use individual files for selective context injection</p>
              <p>3. Combine as needed for different use cases</p>
            </div>
          )}

          {selectedFormat === 'legacy_portrait' && (
            <div className="text-sm text-gray-400 space-y-2">
              <p>1. Download the comprehensive identity portrait</p>
              <p>2. Includes identity docs, traits, chronotype, taste, genome, goals, autobiography, and social presence</p>
              <p>3. A durable, human-readable record — archive it, share it, or keep it as a time capsule</p>
            </div>
          )}
        </div>
      )}
    </div>
  );
}