File size: 9,020 Bytes
3786a3f
 
f14eb69
3786a3f
 
 
 
 
 
 
 
 
a67b1ec
3786a3f
 
feca495
a67b1ec
3786a3f
 
 
 
 
 
 
 
 
d737dbb
2fb781f
3786a3f
 
a67b1ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3786a3f
 
 
 
 
feca495
a67b1ec
feca495
3786a3f
 
 
 
 
f14eb69
 
 
a67b1ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3786a3f
 
 
a67b1ec
3786a3f
 
 
 
 
f14eb69
 
 
 
 
 
 
 
a67b1ec
 
 
3786a3f
 
 
feca495
a67b1ec
feca495
a67b1ec
feca495
3786a3f
 
 
 
 
 
 
 
d737dbb
2fb781f
3786a3f
 
 
a67b1ec
 
 
 
 
 
f14eb69
a67b1ec
 
3786a3f
f14eb69
 
a67b1ec
 
 
 
 
 
 
 
f14eb69
3786a3f
 
 
f14eb69
a67b1ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f14eb69
a67b1ec
f14eb69
3786a3f
 
 
 
a67b1ec
3786a3f
 
 
 
 
 
a67b1ec
3786a3f
a67b1ec
 
 
 
 
 
 
 
 
 
 
f14eb69
3786a3f
 
 
 
 
a67b1ec
3786a3f
 
 
f14eb69
 
 
 
 
 
 
 
 
3786a3f
 
 
 
2fb781f
3786a3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f14eb69
3786a3f
 
 
 
 
 
d737dbb
3786a3f
 
 
 
a67b1ec
3786a3f
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
'use client';

import { useState, useEffect, useCallback, useRef } from 'react';
import { useGraphData } from '@/hooks/useGraphData';
import { useGraphStore } from '@/store/graph';
import { QueryPanel, QueryMode } from '@/components/query/QueryPanel';
import { AnswerCard } from '@/components/query/AnswerCard';
import { PathView, Hop } from '@/components/query/PathView';
import { SourceToggle } from '@/components/query/SourceToggle';
import { QueryHistory } from '@/components/query/QueryHistory';
import { EntityPanel } from '@/components/entities/EntityPanel';
import { GraphVisualization } from '@/components/graph/GraphVisualization';
import { Upload, Sparkles, PlusCircle } from 'lucide-react';
import Link from 'next/link';
import api from '@/lib/axios';
import { useDocumentsStore } from '@/store/documents';
import { useHistoryStore, HistoryItem } from '@/store/history';

interface QueryResult {
  answer: string;
  confidence?: number;
  method?: string;
  citations?: { doc: string; page?: string }[];
  entities?: string[];
  paths?: string[];
  hops?: Hop[];
  context?: string;
  conclusion?: string;
}

const LAST_SESSION_KEY = 'graphrag-last-session';

function loadLastSession(): { query: string; mode: QueryMode; result: QueryResult | null } | null {
  try {
    const raw = localStorage.getItem(LAST_SESSION_KEY);
    return raw ? JSON.parse(raw) : null;
  } catch {
    return null;
  }
}

function saveLastSession(query: string, mode: QueryMode, result: QueryResult | null) {
  try {
    localStorage.setItem(LAST_SESSION_KEY, JSON.stringify({ query, mode, result }));
  } catch {}
}

function clearLastSession() {
  try {
    localStorage.removeItem(LAST_SESSION_KEY);
  } catch {}
}

export function MainQueryView() {
  useGraphData();
  const setHighlighted = useGraphStore((s) => s.setHighlighted);
  const selectEntity = useGraphStore((s) => s.selectEntity);
  const data = useGraphStore((s) => s.data);
  const selectedIds = useDocumentsStore((s) => s.selectedDocumentIds);
  const addHistoryItem = useHistoryStore((s) => s.addItem);

  const [query, setQuery] = useState('');
  const [mode, setMode] = useState<QueryMode>('hybrid');
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<QueryResult | null>(null);

  const scrollRef = useRef<HTMLDivElement>(null);
  const answerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const session = loadLastSession();
    if (session) {
      setQuery(session.query);
      setMode(session.mode);
      setResult(session.result);
      if (session.result?.entities) {
        setHighlighted(session.result.entities, session.result.paths || []);
      }
    }
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    if (query || result) {
      saveLastSession(query, mode, result);
    }
  }, [query, mode, result]);

  useEffect(() => {
    function handleAskEntity(e: Event) {
      const name = (e as CustomEvent).detail;
      if (name) setQuery(name);
    }
    window.addEventListener('graphrag:ask-entity', handleAskEntity);
    return () => window.removeEventListener('graphrag:ask-entity', handleAskEntity);
  }, []);

  const scrollToAnswer = useCallback(() => {
    requestAnimationFrame(() => {
      if (answerRef.current) {
        answerRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }
    });
  }, []);

  const runQuery = useCallback(async (overrideQuery?: string) => {
    const q = overrideQuery ?? query;
    if (!q.trim()) return;
    setLoading(true);
    setResult(null);
    try {
      const { data: res } = await api.post('/query/', {
        query: q,
        mode,
        document_ids: selectedIds.length > 0 ? selectedIds : undefined,
      });
      const mapped: QueryResult = {
        answer: res.answer,
        confidence: res.confidence,
        method: res.strategy || res.method || mode,
        citations: res.sources?.map((s: string) => ({ doc: s })) || res.citations,
        entities: res.highlighted_entities,
        paths: res.paths,
        hops: res.hops,
        context: res.context,
        conclusion: res.conclusion,
      };
      setResult(mapped);
      setHighlighted(mapped.entities || [], mapped.paths || []);

      addHistoryItem({
        id: Date.now().toString(),
        query_text: q,
        retrieval_mode: (res.strategy || mode).toUpperCase(),
        answer_text: res.answer || '',
        answer_preview: (res.answer || '').substring(0, 200),
        response_time: res.response_time ?? 0,
        created_at: new Date().toISOString(),
      });

      scrollToAnswer();
    } catch (err: any) {
      const backendError = err.response?.data?.error;
      let errorMsg = backendError || 'Failed to process query. Please check your API keys and Neo4j connection.';

      if (err.response?.status === 401) {
        errorMsg = 'Your session has expired. Please log in again.';
      }
      setResult({ answer: `**Error:** ${errorMsg}`, method: mode });
      scrollToAnswer();
    } finally {
      setLoading(false);
    }
  }, [query, mode, selectedIds, setHighlighted, addHistoryItem, scrollToAnswer]);

  const handleNewChat = useCallback(() => {
    setQuery('');
    setResult(null);
    setHighlighted([], []);
    selectEntity(null);
    clearLastSession();
  }, [setHighlighted, selectEntity]);

  const handleHistorySelect = useCallback((queryText: string, item?: HistoryItem) => {
    setQuery(queryText);
    if (item?.answer_text) {
      const modeFromItem = (item.retrieval_mode || 'hybrid').toLowerCase() as QueryMode;
      setMode(modeFromItem);
      setResult({
        answer: item.answer_text,
        method: item.retrieval_mode,
        confidence: undefined,
      });
      scrollToAnswer();
    }
  }, [scrollToAnswer]);

  function askEntity(name: string) {
    setQuery(name);
    selectEntity(null);
    setTimeout(() => runQuery(name), 50);
  }

  const empty = data.nodes.length === 0;

  return (
    <div className="flex h-full flex-col lg:flex-row">
      {/* Left Panel: Query + Answer */}
      <div className="flex w-full flex-col border-b border-border lg:w-2/5 lg:border-b-0 lg:border-r">
        {/* New Chat button */}
        <div className="flex items-center justify-end border-b border-border px-4 py-2">
          <button
            onClick={handleNewChat}
            className="flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium text-text-muted hover:bg-bg-surface hover:text-text-primary transition-colors"
          >
            <PlusCircle className="h-3.5 w-3.5" />
            New Chat
          </button>
        </div>

        <div ref={scrollRef} className="flex-1 space-y-4 overflow-y-auto p-4 scrollbar-thin">
          <QueryPanel
            value={query}
            onChange={setQuery}
            mode={mode}
            onModeChange={setMode}
            onSubmit={() => runQuery()}
            loading={loading}
          />

          <div ref={answerRef}>
            <AnswerCard
              answer={result?.answer || ''}
              confidence={result?.confidence}
              method={result?.method}
              citations={result?.citations}
              loading={loading}
            />
          </div>

          {result?.hops && result.hops.length > 0 && (
            <PathView
              hops={result.hops}
              conclusion={result.conclusion}
            />
          )}

          {empty && !loading && (
            <div className="rounded-md border border-dashed border-border bg-bg-surface p-6 text-center">
              <Sparkles className="mx-auto mb-2 h-6 w-6 text-accent-cyan" />
              <p className="text-sm font-medium text-text-primary">Your graph is empty</p>
              <p className="mt-1 text-xs text-text-muted">
                Upload documents to build your knowledge graph.
              </p>
              <Link
                href="/documents"
                className="mt-3 inline-flex items-center gap-1.5 rounded-md bg-accent-violet px-3 py-1.5 text-xs font-medium text-white hover:bg-accent-violet/90"
              >
                <Upload className="h-3.5 w-3.5" /> Upload Document
              </Link>
            </div>
          )}
        </div>

        <QueryHistory onSelect={handleHistorySelect} />

        {result && (
          <SourceToggle
            method={result.method || mode}
            entityCount={result.entities?.length || 0}
            chunkCount={result.citations?.length || 0}
            context={result.context}
          />
        )}
      </div>

      {/* Right Panel: Graph */}
      <div className="relative w-full flex-1">
        {data.nodes.length > 0 ? (
          <GraphVisualization />
        ) : (
          <div className="flex h-full items-center justify-center bg-bg-base text-sm text-text-muted">
            Graph will appear here once documents are processed.
          </div>
        )}
        <EntityPanel onAsk={askEntity} />
      </div>
    </div>
  );
}