Files
Docwell/Server/internal/ai/files.go
T
tajniak81andClaude Opus 5.5 1696f2e77e
CI / go (Server) (push) Failing after 22m44s
CI / go (Media) (push) Canceled after 0s
CI / go (Web-App) (push) Canceled after 0s
CI / frontend (push) Failing after 10m17s
CI / desktop (ubuntu-latest) (push) Failing after 1h44m2s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
CI / mobile (push) Failing after 5m11s
CI / docker (push) Successful in 1h29m50s
Docs / build (push) Successful in 14m34s
Docs / deploy (push) Skipped
Search the text of files attached to pages
The search index now reads the files pages link to: PDF text layers,
Word (.docx), HTML and text files such as Markdown or CSV, up to 25 MB,
and their names. Each file is read once, a few seconds after upload,
and its text is kept in the index; each linked file is indexed as its
own document under its page, like database records, so a file taken
off its page, or a trashed page, drops out. Scanned PDFs are not read.

Hits carry a new file field (id and name). The web search palette and
the phone's search show the file with an attachment icon and the page it
is on; /docwell in Slack names the file too.

PDF, Word and HTML reading moved from the AI package into
internal/textract, which AI's extra files now use as well. The index
mapping version is bumped, so existing indexes rebuild on start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 20:50:27 +01:00

176 lines
5.9 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package ai
import (
"context"
"errors"
"fmt"
"path/filepath"
"strings"
"unicode/utf8"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/store/pocketbase"
"docwell/server/internal/textract"
)
// ---- Extra files for retrieval ----------------------------------------------------
//
// Workspace admins can add documents that are not pages (a handbook, a
// spec) to what chat retrieves. Only their text is kept.
// MaxFileBytes caps one uploaded file.
const MaxFileBytes = 10 << 20
const maxFileText = 2_000_000
type fileRecord struct {
ID string `json:"id"`
Workspace string `json:"workspace"`
Name string `json:"name"`
ContentText string `json:"content_text"`
Size float64 `json:"size"`
Updated string `json:"updated"`
Created string `json:"created"`
}
// File is an extra document as admins see it.
type File struct {
ID string `json:"id"`
Name string `json:"name"`
Size int `json:"size"`
Chars int `json:"chars"`
Indexed bool `json:"indexed"`
Created string `json:"created"`
}
// extractText reads the text of a supported file (textract), with the
// messages admins see.
func extractText(name string, data []byte) (string, error) {
text, err := textract.Text(name, data)
switch {
case err == nil:
return text, nil
case errors.Is(err, textract.ErrNoText):
return "", errNoPDFText
case errors.Is(err, textract.ErrNotUTF8):
return "", apperr.Invalid("The file is not UTF-8 text.")
case errors.Is(err, textract.ErrUnsupported):
return "", apperr.Invalid("Add text, Markdown, HTML, Word (.docx) or PDF files.")
}
switch strings.ToLower(filepath.Ext(name)) {
case ".pdf":
return "", apperr.Invalid("The PDF could not be read.")
case ".docx":
return "", apperr.Invalid("The Word document could not be read.")
}
return "", apperr.Invalid("The HTML file could not be read.")
}
// errNoPDFText is a PDF without a text layer (scanned pages).
var errNoPDFText = apperr.Invalid("The PDF has no text layer.")
const ocrSystem = `You turn documents into text for a team wiki. Write out all the text of the document, page by page, as Markdown: keep headings, lists and tables, and describe charts or pictures in one short line in brackets. No preamble and no remarks of your own.`
// readScannedPDF has a document-reading chat model write out a PDF without
// a text layer (scanned pages).
func (s *Service) readScannedPDF(ctx context.Context, c access.Caller, wsID string, data []byte) (string, error) {
_, chain, err := s.ready(ctx, c, wsID)
if err != nil {
return "", apperr.Invalid("The PDF has no text layer, and AI cannot read it here: " + userError(err))
}
var out strings.Builder
_, err = s.chat(ctx, wsID, chain, ChatRequest{
System: ocrSystem, MaxTokens: 32000, PDF: data,
Messages: []Message{{Role: "user", Content: "Write out the text of this document."}},
}, func(d string) { out.WriteString(d) })
if err != nil {
if errors.Is(err, ErrNoDocuments) || errors.Is(err, errNoProfile) {
return "", apperr.Invalid("The PDF has no text layer (scanned pages). To read it, add an Anthropic or OpenAI provider whose model reads PDF files.")
}
return "", apperr.Invalid("The PDF has no text layer, and AI could not read it: " + userError(err))
}
return out.String(), nil
}
func (s *Service) fileView(ws string, r fileRecord) File {
h, _ := s.store.Hash(ws, "file/"+r.ID)
return File{ID: r.ID, Name: r.Name, Size: int(r.Size), Chars: utf8.RuneCountInString(r.ContentText), Indexed: h != "", Created: r.Created}
}
// ListFiles lists a workspace's extra files (workspace admin).
func (s *Service) ListFiles(ctx context.Context, c access.Caller, wsID string) ([]File, error) {
if err := s.canManage(ctx, c, wsID); err != nil {
return nil, err
}
res, err := pocketbase.List[fileRecord](ctx, s.pb, "ai_files", pocketbase.ListOptions{
PerPage: 500, Filter: fmt.Sprintf("workspace = '%s'", wsID), Sort: "name",
})
if err != nil {
return nil, err
}
out := make([]File, 0, len(res.Items))
for _, r := range res.Items {
out = append(out, s.fileView(wsID, r))
}
return out, nil
}
// AddFile stores an extra file's text (workspace admin).
func (s *Service) AddFile(ctx context.Context, c access.Caller, wsID, name string, data []byte) (File, error) {
if err := s.canManage(ctx, c, wsID); err != nil {
return File{}, err
}
name = strings.TrimSpace(filepath.Base(name))
if name == "" || name == "." || len(name) > 200 {
return File{}, apperr.Invalid("The file needs a name of up to 200 characters.")
}
if len(data) > MaxFileBytes {
return File{}, apperr.Invalid("Files can be up to 10 MB.")
}
text, err := extractText(name, data)
if errors.Is(err, errNoPDFText) {
text, err = s.readScannedPDF(ctx, c, wsID, data)
}
if err != nil {
return File{}, err
}
if strings.TrimSpace(text) == "" {
return File{}, apperr.Invalid("The file has no text.")
}
if utf8.RuneCountInString(text) > maxFileText {
text = string([]rune(text)[:maxFileText])
}
rec, err := pocketbase.Create[fileRecord](ctx, s.pb, "ai_files", map[string]any{
"workspace": wsID, "name": name, "content_text": text, "size": len(data), "created_by": c.ID,
})
if err != nil {
return File{}, err
}
s.wake()
return s.fileView(wsID, rec), nil
}
// DeleteFile removes an extra file and its vectors (workspace admin).
func (s *Service) DeleteFile(ctx context.Context, c access.Caller, id string) error {
if !validID(id) {
return apperr.NotFound("file not found")
}
rec, err := pocketbase.Get[fileRecord](ctx, s.pb, "ai_files", id)
if err != nil {
if pocketbase.IsNotFound(err) {
return apperr.NotFound("file not found")
}
return err
}
if err := s.canManage(ctx, c, rec.Workspace); err != nil {
return apperr.NotFound("file not found")
}
if err := s.pb.Delete(ctx, "ai_files", id); err != nil {
return err
}
return s.store.Drop(rec.Workspace, "file/"+id)
}