Spaces:
Running

File size: 9,462 Bytes
03608f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"use client";

import { BookOpenIcon, FileTextIcon, SearchIcon, ShieldAlertIcon, Trash2Icon, UploadIcon } from "lucide-react";
import { useState, type FormEvent } from "react";
import { toast } from "sonner";

import { EmptyState, ErrorState, PageHeader } from "@/components/shell/page";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Skeleton } from "@/components/ui/skeleton";
import { Textarea } from "@/components/ui/textarea";
import { api, ApiError } from "@/lib/api";
import { useAuth } from "@/lib/auth";
import { formatDateTime } from "@/lib/format";
import { useI18n } from "@/lib/i18n";
import { useApi } from "@/lib/use-api";

import type { KnowledgeDoc, KnowledgeSearch } from "./types";

function toBase64(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(String(reader.result).split(",", 2)[1] ?? "");
    reader.onerror = () => reject(reader.error ?? new Error("read failed"));
    reader.readAsDataURL(file);
  });
}

function UploadForm({ onAdded }: { onAdded: () => void }) {
  const { t } = useI18n();
  const [title, setTitle] = useState("");
  const [file, setFile] = useState<File | null>(null);
  const [text, setText] = useState("");
  const [url, setUrl] = useState("");
  const [busy, setBusy] = useState(false);

  const submit = async (e: FormEvent) => {
    e.preventDefault();
    setBusy(true);
    try {
      let body: Record<string, string>;
      if (file) {
        body = { filename: file.name, content_type: file.type, content_base64: await toBase64(file) };
      } else if (text.trim()) {
        body = { text };
      } else {
        body = { url: url.trim() };
      }
      await api("/knowledge/docs", {
        method: "POST",
        body: { ...body, title: title.trim() || file?.name || undefined },
      });
      toast.success(t("knowledge.added"));
      setTitle("");
      setFile(null);
      setText("");
      setUrl("");
      onAdded();
    } catch (err) {
      toast.error(err instanceof ApiError ? err.detail : t("common.error"));
    } finally {
      setBusy(false);
    }
  };

  const ready = Boolean(file || text.trim() || url.trim());
  return (
    <form onSubmit={submit} className="space-y-3 rounded-lg border bg-card p-4" data-testid="knowledge-upload">

      <div>

        <h2 className="text-sm font-semibold">{t("knowledge.upload")}</h2>

        <p className="text-xs text-muted-foreground">{t("knowledge.uploadHint")}</p>

      </div>

      <div className="grid gap-3 sm:grid-cols-2">

        <div className="space-y-1.5">

          <Label htmlFor="kb-title">{t("knowledge.docTitle")}</Label>

          <Input id="kb-title" value={title} onChange={(e) => setTitle(e.target.value)} maxLength={300} />

        </div>

        <div className="space-y-1.5">

          <Label htmlFor="kb-file">{t("knowledge.file")}</Label>

          <Input

            id="kb-file"

            type="file"

            accept=".pdf,.docx,.md,.markdown,.txt,.html,.htm"

            onChange={(e) => setFile(e.target.files?.[0] ?? null)}

          />

        </div>

      </div>

      <div className="space-y-1.5">

        <Label htmlFor="kb-text">{t("knowledge.pasteText")}</Label>

        <Textarea id="kb-text" rows={4} value={text} onChange={(e) => setText(e.target.value)} disabled={Boolean(file)} />

      </div>

      <div className="space-y-1.5">

        <Label htmlFor="kb-url">{t("knowledge.url")}</Label>

        <Input

          id="kb-url"

          type="url"

          dir="ltr"

          placeholder="https://"

          value={url}

          onChange={(e) => setUrl(e.target.value)}

          disabled={Boolean(file || text.trim())}

        />

      </div>

      <Button type="submit" disabled={!ready || busy} data-testid="knowledge-add">

        <UploadIcon className="size-4" aria-hidden />

        {t("knowledge.add")}

      </Button>

    </form>
  );
}

function SearchPanel() {
  const { t } = useI18n();
  const [q, setQ] = useState("");
  const [result, setResult] = useState<KnowledgeSearch | null>(null);
  const [busy, setBusy] = useState(false);

  const submit = async (e: FormEvent) => {
    e.preventDefault();
    if (q.trim().length < 2) return;
    setBusy(true);
    try {
      setResult(await api<KnowledgeSearch>("/knowledge/search", { query: { q: q.trim(), k: 5 } }));
    } catch (err) {
      toast.error(err instanceof ApiError ? err.detail : t("common.error"));
    } finally {
      setBusy(false);
    }
  };

  return (
    <section className="space-y-3 rounded-lg border bg-card p-4">

      <h2 className="text-sm font-semibold">{t("knowledge.searchTitle")}</h2>

      <form onSubmit={submit} className="flex gap-2">

        <Input

          aria-label={t("common.search")}

          placeholder={t("knowledge.searchPlaceholder")}

          value={q}

          onChange={(e) => setQ(e.target.value)}

          maxLength={500}

        />

        <Button type="submit" variant="outline" disabled={busy} data-testid="knowledge-search">

          <SearchIcon className="size-4" aria-hidden />

          {t("common.search")}

        </Button>

      </form>

      {result && result.hits.length === 0 && (

        <p className="text-sm text-muted-foreground">{t("knowledge.noHits")}</p>

      )}

      {result && result.hits.length > 0 && (

        <ol className="space-y-2" data-testid="knowledge-hits">

          {result.hits.map((h) => (

            <li key={h.chunk_id} className="rounded-md border p-3 text-sm">

              <div className="mb-1 flex flex-wrap items-center gap-2">

                <cite className="font-medium not-italic" data-testid="citation">

                  {h.citation}

                </cite>

                <Badge variant="outline">{t("knowledge.untrusted")}</Badge>

                {h.flags.includes("possible_injection") && (

                  <Badge variant="destructive" title={t("knowledge.flaggedHint")}>

                    <ShieldAlertIcon className="size-3" aria-hidden />

                    {t("knowledge.flagged", { n: 1 })}

                  </Badge>

                )}

                <span className="text-xs text-muted-foreground tabular">

                  {t("knowledge.score", { s: h.score.toFixed(2) })}

                </span>

              </div>

              <p className="whitespace-pre-wrap text-muted-foreground" dir="auto">

                {h.text}

              </p>

            </li>

          ))}

        </ol>

      )}

    </section>
  );
}

export function KnowledgeView() {
  const { t, locale } = useI18n();
  const { hasRole } = useAuth();
  const docs = useApi<KnowledgeDoc[]>("/knowledge/docs");
  const canEdit = hasRole("manager");

  const remove = async (d: KnowledgeDoc) => {
    try {
      await api(`/knowledge/docs/${d.id}`, { method: "DELETE" });
      toast.success(t("knowledge.removed"));
      docs.reload();
    } catch (err) {
      toast.error(err instanceof ApiError ? err.detail : t("common.error"));
    }
  };

  let list;
  if (docs.error && !docs.data) {
    list = <ErrorState error={docs.error} onRetry={docs.reload} />;
  } else if (!docs.data) {
    list = <Skeleton className="h-24 w-full" />;
  } else if (docs.data.length === 0) {
    list = <EmptyState icon={BookOpenIcon} title={t("knowledge.noDocs")} hint={t("knowledge.noDocsHint")} />;
  } else {
    list = (
      <ul className="divide-y rounded-lg border bg-card" data-testid="knowledge-docs">

        {docs.data.map((d) => (

          <li key={d.id} className="flex flex-wrap items-center gap-3 p-3 text-sm">

            <FileTextIcon className="size-4 text-muted-foreground" aria-hidden />

            <div className="min-w-0 flex-1">

              <p className="truncate font-medium">{d.title}</p>

              <p className="text-xs text-muted-foreground">

                {d.source_type.toUpperCase()} 路 {t("knowledge.chunks", { n: d.chunk_count })}

                {d.page_count ? ` 路 ${t("knowledge.pages", { n: d.page_count })}` : ""} 路{" "}

                {formatDateTime(d.created_at, locale)}

              </p>

            </div>

            {d.flagged_chunks > 0 && (

              <Badge variant="destructive" title={t("knowledge.flaggedHint")}>

                <ShieldAlertIcon className="size-3" aria-hidden />

                {t("knowledge.flagged", { n: d.flagged_chunks })}

              </Badge>

            )}

            {canEdit && (

              <Button variant="ghost" size="icon" aria-label={`${t("knowledge.remove")} ${d.title}`} onClick={() => void remove(d)}>

                <Trash2Icon className="size-4" aria-hidden />

              </Button>

            )}

          </li>

        ))}

      </ul>
    );
  }

  return (
    <div className="space-y-5">

      <PageHeader title={t("knowledge.title")} subtitle={t("knowledge.subtitle")} />

      {canEdit && <UploadForm onAdded={docs.reload} />}

      <section className="space-y-2">

        <h2 className="text-sm font-semibold">{t("knowledge.docs")}</h2>

        {list}

      </section>

      <SearchPanel />

    </div>
  );
}