Skip to content

Harness engineering beginner tutorial, from 0 to 1

8.0 KB
Raw Blame
import { useState, useCallback, useEffect } from 'react';
import { DocumentList } from './components/DocumentList';
import { QuestionPanel } from './components/QuestionPanel';
import { DocumentDetail } from './components/DocumentDetail';
import { ImportPanel } from './components/ImportPanel';
import { StatusBar } from './components/StatusBar';
import { Document, AppStatus, QAResponse } from '../shared/types';

declare global {
  interface Window {
    knowledgeBase: {
      documents: {
        list: () => Promise<Document[]>;
        import: (filePath: string) => Promise<Document>;
        get: (id: string) => Promise<Document | null>;
        getContent: (id: string) => Promise<string | null>;
        delete: (id: string) => Promise<boolean>;
      };
      indexing: {
        start: (documentId?: string) => Promise<AppStatus>;
        status: () => Promise<AppStatus>;
        chunks: (documentId: string) => Promise<Array<{ id: string; content: string; index: number; metadata: Record<string, string> }>>;
      };
      qa: {
        ask: (question: string) => Promise<QAResponse>;
        history: () => Promise<Array<{ question: string; response: QAResponse }>>;
      };
    };
  }
}

export function App() {
  const [documents, setDocuments] = useState<Document[]>([]);
  const [selectedDoc, setSelectedDoc] = useState<Document | null>(null);
  const [appStatus, setAppStatus] = useState<AppStatus>({
    documentsLoaded: 0,
    indexStatus: 'idle',
    lastActivity: '',
    indexedCount: 0,
    totalChunks: 0,
  });
  const [lastResponse, setLastResponse] = useState<QAResponse | null>(null);
  const [showImport, setShowImport] = useState(false);

  // Load documents on mount -- demonstrates basic persistence
  useEffect(() => {
    refreshDocuments();
  }, []);

  const refreshDocuments = useCallback(async () => {
    try {
      const docs = await window.knowledgeBase.documents.list();
      setDocuments(docs);
      const status = await window.knowledgeBase.indexing.status();
      setAppStatus(status);
    } catch (err) {
      console.error('Failed to refresh documents:', err);
    }
  }, []);

  const handleImport = useCallback(async (filePath: string) => {
    try {
      await window.knowledgeBase.documents.import(filePath);
      await refreshDocuments();
      setShowImport(false);
    } catch (err) {
      console.error('Import failed:', err);
    }
  }, [refreshDocuments]);

  const handleSelectDocument = useCallback((doc: Document) => {
    setSelectedDoc(doc);
  }, []);

  const handleAskQuestion = useCallback(async (question: string) => {
    try {
      const response = await window.knowledgeBase.qa.ask(question);
      setLastResponse(response);
    } catch (err) {
      console.error('Q&A failed:', err);
    }
  }, []);

  const handleDeleteDocument = useCallback(async (id: string) => {
    try {
      await window.knowledgeBase.documents.delete(id);
      if (selectedDoc?.id === id) {
        setSelectedDoc(null);
      }
      await refreshDocuments();
    } catch (err) {
      console.error('Delete failed:', err);
    }
  }, [selectedDoc, refreshDocuments]);

  const handleIndexDocument = useCallback(async (documentId: string) => {
    try {
      await window.knowledgeBase.indexing.start(documentId);
      await refreshDocuments();
      // Re-select the document to get updated status
      const updated = await window.knowledgeBase.documents.get(documentId);
      if (updated) {
        setSelectedDoc(updated);
      }
    } catch (err) {
      console.error('Indexing failed:', err);
    }
  }, [refreshDocuments]);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100vh' }}>
      <header style={{
        padding: '12px 20px',
        background: '#16213e',
        borderBottom: '1px solid #0f3460',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
      }}>
        <h1 style={{ fontSize: '18px', fontWeight: 600 }}>Knowledge Base</h1>
        <button
          onClick={refreshDocuments}
          style={{
            padding: '6px 14px',
            background: '#0f3460',
            color: '#e0e0e0',
            border: '1px solid #1a1a4e',
            borderRadius: '4px',
            cursor: 'pointer',
            fontSize: '13px',
          }}
        >
          Refresh
        </button>
      </header>

      <div style={{ display: 'flex', flex: 1, overflow: 'hidden' }}>
        {/* Left panel: Document list */}
        <div style={{
          width: '280px',
          borderRight: '1px solid #0f3460',
          display: 'flex',
          flexDirection: 'column',
          background: '#16213e',
        }}>
          <div style={{
            padding: '10px 16px',
            borderBottom: '1px solid #0f3460',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}>
            <span style={{ fontSize: '13px', fontWeight: 500, color: '#a0a0c0' }}>
              Documents ({documents.length})
            </span>
            <button
              onClick={() => setShowImport(!showImport)}
              style={{
                padding: '4px 10px',
                background: '#533483',
                color: '#fff',
                border: 'none',
                borderRadius: '3px',
                cursor: 'pointer',
                fontSize: '12px',
              }}
            >
              {showImport ? 'Cancel' : '+ Import'}
            </button>
          </div>
          <DocumentList
            documents={documents}
            onSelect={handleSelectDocument}
            selectedId={selectedDoc?.id ?? null}
          />
        </div>

        {/* Right panel: Import, Document detail + Q&A */}
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
          <div style={{ flex: 1, overflow: 'auto', padding: '20px' }}>
            {showImport ? (
              <ImportPanel onImport={handleImport} />
            ) : selectedDoc ? (
              <DocumentDetail
                document={selectedDoc}
                onDelete={handleDeleteDocument}
                onIndex={handleIndexDocument}
              />
            ) : (
              <div style={{ color: '#666', textAlign: 'center', paddingTop: '40px' }}>
                Select a document or ask a question to get started
              </div>
            )}
            {lastResponse && (
              <div style={{
                marginTop: '16px',
                padding: '16px',
                background: '#1a1a3e',
                borderRadius: '6px',
                border: '1px solid #0f3460',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px' }}>
                  <span style={{ fontSize: '14px', fontWeight: 600 }}>Answer</span>
                  <span style={{
                    fontSize: '11px',
                    padding: '2px 8px',
                    borderRadius: '10px',
                    background: lastResponse.confidence >= 0.8 ? '#2d5a2d' : '#5a4a2d',
                    color: lastResponse.confidence >= 0.8 ? '#5cb85c' : '#f0ad4e',
                  }}>
                    Confidence: {Math.round(lastResponse.confidence * 100)}%
                  </span>
                </div>
                <div style={{ fontSize: '14px', lineHeight: 1.6 }}>{lastResponse.answer}</div>
                {lastResponse.citations.length > 0 && (
                  <div style={{ marginTop: '10px', fontSize: '12px', color: '#8888bb' }}>
                    <strong>Citations:</strong>
                    {lastResponse.citations.map((c, i) => (
                      <div key={i} style={{ marginTop: '4px', paddingLeft: '8px', borderLeft: '2px solid #533483' }}>
                        {c.documentTitle} (chunk {c.chunkIndex}): {c.excerpt.substring(0, 100)}...
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )}
          </div>

          <QuestionPanel onAsk={handleAskQuestion} />
        </div>
      </div>

      <StatusBar status={appStatus} />
    </div>
  );
}