Files
Docwell/Server/internal/ai/ai_test.go
T
tajniak81andClaude Opus 5.5 cad42fbe89
CI / desktop (ubuntu-latest) (push) Successful in 2h34m54s
CI / mobile (push) Failing after 4m52s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
CI / docker (push) Successful in 53m34s
Docs / build (push) Canceled after 0s
Docs / deploy (push) Canceled after 0s
CI / go (Media) (push) Successful in 13m0s
CI / go (Server) (push) Successful in 24m4s
CI / go (Web-App) (push) Successful in 12m35s
CI / frontend (push) Failing after 11m51s
Prepare the 0.3.0 release
CHANGELOG.md gets the 0.3.0 notes: everything since 0.2.0 by area, and
the steps for upgrading a 0.2.0 install (new compose files with a stock
PocketBase on 8070, pb_data at /pb/pb_data, the media service, and the
SMTP password to enter once more). The release workflow now uses the
tag's CHANGELOG section as the Gitea release text. A v0.2.0 compose stack
with data was upgraded in place to this commit and kept its data.

Also fixes what CI would have failed on:
- Server lint (golangci-lint v2.14): errors.Is/As for sentinel errors,
  the bbolt/errors package instead of the deprecated bolt error, one
  needless conversion, and commented nolints for gosec false positives.
- SPDX headers on Database/export-schema.sh and Server/entrypoint.sh.
- Prettier on two files; the generated pbschema/schema.json is ignored.
- The editor-bridge dist page rebuilt to match the phone app's copy.

PLAN.md and the upgrade guide point to the release notes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 10:21:57 +01:00

358 lines
13 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-License-Identifier: AGPL-3.0-or-later
package ai
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"docwell/server/internal/access"
"github.com/go-pdf/fpdf"
)
func TestSealerRoundTrip(t *testing.T) {
s := newSealer("secret")
sealed := s.seal("sk-test")
if sealed == "sk-test" || !strings.HasPrefix(sealed, "v1:") {
t.Fatalf("not sealed: %q", sealed)
}
if got, err := s.open(sealed); err != nil || got != "sk-test" {
t.Fatalf("open = %q, %v", got, err)
}
if _, err := newSealer("other").open(sealed); err == nil {
t.Fatal("another secret opened the key")
}
if s.seal("") != "" {
t.Fatal("an empty key should stay empty")
}
}
func TestChunkDoc(t *testing.T) {
long := strings.Repeat("word ", 400)
doc := `{"type":"doc","content":[
{"type":"paragraph","attrs":{"blockId":"intro1"},"content":[{"type":"text","text":"Intro text."}]},
{"type":"heading","attrs":{"level":2,"blockId":"setup1"},"content":[{"type":"text","text":"Setup"}]},
{"type":"bulletList","content":[
{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"one"}]}]},
{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"two"}]}]}]},
{"type":"paragraph","content":[{"type":"text","text":"` + long + `"}]}
]}`
pieces := chunkDoc("Guide", json.RawMessage(doc))
if len(pieces) < 3 {
t.Fatalf("want at least 3 pieces, got %d: %+v", len(pieces), pieces)
}
if pieces[0].Block != "intro1" || pieces[0].Text != "Intro text." {
t.Errorf("first piece = %+v", pieces[0])
}
if pieces[1].Block != "setup1" || !strings.Contains(pieces[1].Text, "one\ntwo") {
t.Errorf("heading piece = %+v", pieces[1])
}
if !strings.HasPrefix(pieces[1].Embed, "Guide › Setup") {
t.Errorf("embed text lacks its context: %q", pieces[1].Embed[:30])
}
for _, p := range pieces {
if len([]rune(p.Text)) > chunkSize*3/2 {
t.Errorf("piece too long: %d", len([]rune(p.Text)))
}
}
}
func TestStoreSearch(t *testing.T) {
st, err := OpenStore(t.TempDir())
if err != nil {
t.Fatal(err)
}
defer st.Close()
vec := func(x, y float32) []float32 { return normalize([]float32{x, y}) }
if err := st.Put("ws1", "page/a", "h1", []Chunk{
{Page: "a", Space: "s1", Title: "A", Text: "east", Vector: vec(1, 0)},
{Page: "a", Space: "s1", Title: "A", Text: "north", Vector: vec(0, 1)},
}); err != nil {
t.Fatal(err)
}
if err := st.Put("ws1", "page/b", "h2", []Chunk{{Page: "b", Space: "s2", Title: "B", Text: "north-east", Vector: vec(1, 1)}}); err != nil {
t.Fatal(err)
}
hits, err := st.Search("ws1", vec(0, 1), 2, nil)
if err != nil || len(hits) != 2 {
t.Fatalf("hits = %v, %v", hits, err)
}
if hits[0].Text != "north" || hits[1].Text != "north-east" || hits[0].Source != "page/a" {
t.Errorf("order = %q, %q (%s)", hits[0].Text, hits[1].Text, hits[0].Source)
}
only, _ := st.Search("ws1", vec(0, 1), 5, func(c Chunk) bool { return c.Space == "s2" })
if len(only) != 1 || only[0].Page != "b" {
t.Errorf("filter = %+v", only)
}
if h, _ := st.Hash("ws1", "page/a"); h != "h1" {
t.Errorf("hash = %q", h)
}
// Replacing a source drops its old chunks.
_ = st.Put("ws1", "page/a", "h3", []Chunk{{Page: "a", Space: "s1", Text: "only", Vector: vec(1, 0)}})
pages, _, chunks, _ := st.Counts("ws1")
if pages != 2 || chunks != 2 {
t.Errorf("counts = %d pages, %d chunks", pages, chunks)
}
_ = st.Drop("ws1", "page/b")
if src, _ := st.Sources("ws1"); len(src) != 1 {
t.Errorf("sources = %v", src)
}
_ = st.DropWorkspace("ws1")
if m, _ := st.Meta("ws1"); m.Model != "" {
t.Error("meta survived dropping the workspace")
}
}
func TestReadSSE(t *testing.T) {
var got []string
err := readSSE(strings.NewReader("event: x\ndata: one\n\ndata: two\ndata: more\n\n: comment\n\ndata: [DONE]\n\ndata: after\n\n"), func(d string) error {
if d == "[DONE]" {
return io.EOF
}
got = append(got, d)
return nil
})
if err != nil || len(got) != 2 || got[1] != "two\nmore" {
t.Fatalf("got %q, %v", got, err)
}
}
func TestOpenAIDriver(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer k" {
w.WriteHeader(401)
_, _ = io.WriteString(w, `{"error":{"message":"bad key"}}`)
return
}
switch r.URL.Path {
case "/v1/chat/completions":
w.Header().Set("Content-Type", "text/event-stream")
for _, d := range []string{"Hel", "lo"} {
fmt.Fprintf(w, "data: {\"choices\":[{\"delta\":{\"content\":%q}}]}\n\n", d)
}
_, _ = io.WriteString(w, "data: {\"choices\":[],\"usage\":{\"prompt_tokens\":7,\"completion_tokens\":2}}\n\ndata: [DONE]\n\n")
case "/v1/embeddings":
_, _ = io.WriteString(w, `{"data":[{"index":1,"embedding":[0,1]},{"index":0,"embedding":[1,0]}],"usage":{"prompt_tokens":3}}`)
}
}))
defer srv.Close()
p, _ := NewProvider(KindOpenAI, srv.URL+"/v1/", "k", srv.Client())
var out strings.Builder
u, err := p.Chat(context.Background(), ChatRequest{Model: "m", Messages: []Message{{"user", "hi"}}}, func(d string) { out.WriteString(d) })
if err != nil || out.String() != "Hello" || u.InputTokens != 7 || u.OutputTokens != 2 {
t.Fatalf("chat = %q %+v %v", out.String(), u, err)
}
vecs, _, err := p.Embed(context.Background(), "e", []string{"a", "b"})
if err != nil || vecs[0][0] != 1 || vecs[1][1] != 1 {
t.Fatalf("embed = %v %v", vecs, err)
}
bad, _ := NewProvider(KindOpenAI, srv.URL+"/v1", "wrong", srv.Client())
_, err = bad.Chat(context.Background(), ChatRequest{Model: "m"}, func(string) {})
var pe *ProviderError
if !asProviderError(err, &pe) || pe.Status != 401 || pe.Message != "bad key" {
t.Fatalf("error = %v", err)
}
}
func asProviderError(err error, out **ProviderError) bool {
return errors.As(err, out)
}
func TestOllamaDriver(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/chat":
_, _ = io.WriteString(w, `{"message":{"content":"Hi"},"done":false}`+"\n"+`{"message":{"content":" there"},"done":false}`+"\n"+`{"done":true,"prompt_eval_count":5,"eval_count":2}`+"\n")
case "/api/embed":
_, _ = io.WriteString(w, `{"embeddings":[[0.5,0.5]]}`)
}
}))
defer srv.Close()
p, _ := NewProvider(KindOllama, srv.URL, "", srv.Client())
var out strings.Builder
u, err := p.Chat(context.Background(), ChatRequest{Model: "llama"}, func(d string) { out.WriteString(d) })
if err != nil || out.String() != "Hi there" || u.OutputTokens != 2 {
t.Fatalf("chat = %q %+v %v", out.String(), u, err)
}
if v, _, err := p.Embed(context.Background(), "e", []string{"x"}); err != nil || len(v[0]) != 2 {
t.Fatalf("embed = %v %v", v, err)
}
}
func TestRankPieces(t *testing.T) {
pieces := []piece{{Text: "cats and dogs"}, {Text: "invoice approval steps"}, {Text: "lunch"}, {Text: "approval of an invoice by finance"}}
got := rankPieces(pieces, "How does invoice approval work?", 2)
if len(got) != 2 || got[0].Text != "invoice approval steps" || got[1].Text != "approval of an invoice by finance" {
t.Fatalf("got %+v", got)
}
}
func TestMCPProtocol(t *testing.T) {
s := &Service{log: slog.New(slog.NewTextHandler(io.Discard, nil))}
c := access.Caller{ID: "u1"}
call := func(write bool, body string) map[string]any {
t.Helper()
raw, err := s.MCP(context.Background(), c, write, []byte(body), nil)
if err != nil {
t.Fatal(err)
}
if raw == nil {
return nil
}
var out map[string]any
if err := json.Unmarshal(raw, &out); err != nil {
t.Fatalf("%s: %v", raw, err)
}
return out
}
init := call(false, `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}`)
res := init["result"].(map[string]any)
if res["protocolVersion"] != "2025-06-18" {
t.Errorf("version = %v", res["protocolVersion"])
}
if call(false, `{"jsonrpc":"2.0","method":"notifications/initialized"}`) != nil {
t.Error("a notification got an answer")
}
names := func(write bool) []string {
r := call(write, `{"jsonrpc":"2.0","id":2,"method":"tools/list"}`)["result"].(map[string]any)
var out []string
for _, tool := range r["tools"].([]any) {
out = append(out, tool.(map[string]any)["name"].(string))
}
return out
}
if read := strings.Join(names(false), ","); strings.Contains(read, "update_page") || !strings.Contains(read, "read_page") {
t.Errorf("read tools = %s", read)
}
if write := strings.Join(names(true), ","); !strings.Contains(write, "create_page") {
t.Errorf("write tools = %s", write)
}
denied := call(false, `{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"update_page","arguments":{}}}`)
if denied["error"] == nil {
t.Error("a read token could call a write tool")
}
missing := call(false, `{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"read_page","arguments":{}}}`)
if r := missing["result"].(map[string]any); r["isError"] != true {
t.Errorf("missing argument = %v", r)
}
if call(false, `{"jsonrpc":"2.0","id":5,"method":"nope"}`)["error"] == nil {
t.Error("unknown method answered")
}
}
func TestPDFText(t *testing.T) {
doc := fpdf.New("P", "mm", "A4", "")
doc.AddPage()
doc.SetFont("Helvetica", "", 12)
doc.Cell(40, 10, "Expense policy page one")
doc.AddPage()
doc.Cell(40, 10, "Receipts are due within 30 days")
var buf bytes.Buffer
if err := doc.Output(&buf); err != nil {
t.Fatal(err)
}
text, err := extractText("policy.pdf", buf.Bytes())
if err != nil {
t.Fatal(err)
}
if !strings.Contains(text, "Expense policy page one") || !strings.Contains(text, "Receipts are due") {
t.Fatalf("text = %q", text)
}
if _, err := extractText("broken.pdf", []byte("%PDF-1.4 not really")); err == nil {
t.Fatal("a broken PDF was read")
}
}
func TestTranscribeDriver(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/audio/transcriptions" {
w.WriteHeader(404)
return
}
if err := r.ParseMultipartForm(1 << 20); err != nil {
t.Error(err)
}
f, h, err := r.FormFile("file")
if err != nil {
t.Fatal(err)
}
data, _ := io.ReadAll(f)
fmt.Fprintf(w, `{"text":"model %s heard %d bytes of %s"}`, r.FormValue("model"), len(data), h.Filename)
}))
defer srv.Close()
p, _ := NewProvider(KindOpenAI, srv.URL+"/v1", "", srv.Client())
text, err := p.Transcribe(context.Background(), "whisper-1", "call.m4a", []byte("abcd"))
if err != nil || text != "model whisper-1 heard 4 bytes of call.m4a" {
t.Fatalf("text = %q, %v", text, err)
}
o, _ := NewProvider(KindOllama, srv.URL, "", srv.Client())
if _, err := o.Transcribe(context.Background(), "m", "a.mp3", nil); !errors.Is(err, ErrNoTranscription) {
t.Fatalf("ollama = %v", err)
}
}
func TestIsMedia(t *testing.T) {
for _, c := range []struct {
mime, name string
want bool
}{
{"audio/mpeg", "a", true}, {"video/mp4", "v", true}, {"", "Meeting.M4A", true},
{"application/octet-stream", "rec.webm", true}, {"application/pdf", "x.pdf", false},
} {
if IsMedia(c.mime, c.name) != c.want {
t.Errorf("IsMedia(%q, %q) != %v", c.mime, c.name, c.want)
}
}
}
func TestScannedPDFIsDetected(t *testing.T) {
doc := fpdf.New("P", "mm", "A4", "")
doc.AddPage()
doc.Rect(20, 20, 50, 50, "F") // a drawing, no text
var buf bytes.Buffer
if err := doc.Output(&buf); err != nil {
t.Fatal(err)
}
if _, err := extractText("scan.pdf", buf.Bytes()); !errors.Is(err, errNoPDFText) {
t.Fatalf("err = %v", err)
}
}
func TestPDFGoesWithTheQuestion(t *testing.T) {
var got map[string]any
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = json.NewDecoder(r.Body).Decode(&got)
w.Header().Set("Content-Type", "text/event-stream")
_, _ = io.WriteString(w, "data: {\"choices\":[{\"delta\":{\"content\":\"# Page 1\"}}]}\n\ndata: [DONE]\n\n")
}))
defer srv.Close()
p, _ := NewProvider(KindOpenAI, srv.URL, "", srv.Client())
var out strings.Builder
_, err := p.Chat(context.Background(), ChatRequest{
Model: "m", PDF: []byte("%PDF-1.4"), Messages: []Message{{"user", "Write it out."}},
}, func(d string) { out.WriteString(d) })
if err != nil || out.String() != "# Page 1" {
t.Fatalf("%q %v", out.String(), err)
}
msgs := got["messages"].([]any)
parts := msgs[len(msgs)-1].(map[string]any)["content"].([]any)
file := parts[0].(map[string]any)["file"].(map[string]any)
if !strings.HasPrefix(file["file_data"].(string), "data:application/pdf;base64,JVBERi0xLjQ") || parts[1].(map[string]any)["text"] != "Write it out." {
t.Fatalf("parts = %v", parts)
}
o, _ := NewProvider(KindOllama, srv.URL, "", srv.Client())
if _, err := o.Chat(context.Background(), ChatRequest{PDF: []byte("x")}, func(string) {}); !errors.Is(err, ErrNoDocuments) {
t.Fatalf("ollama = %v", err)
}
}