WeKnora/internal/infrastructure/docparser/image_resolver.go

1091 lines
34 KiB
Go
Raw Normal View History

package docparser
import (
"bytes"
"context"
"encoding/base64"
fix(docparser): resolve remote images referenced by HTML img tags (#2355) Remote http(s) images written as <img src="..."> reached no resolver. Markdown images went through ResolveRemoteImages, HTML data-URIs and HTML relative paths each had their own pass, but nothing claimed the remaining combination, so those images were dropped without a log line and the multimodal stage was skipped for documents that rely on HTML for layout. ResolveRemoteImages now scans HTML img tags with a quoted src as a second pass and rewrites only the src attribute value, leaving the tag intact because the surrounding markup is why these documents use HTML at all. The per-image work (whitelist, SSRF, download, icon filter, upload) moves into one helper so the two syntaxes cannot drift apart on policy. Each pass carries its own image budget; sharing one would let HTML images eat into the number of Markdown images a document already gets resolved. An attribute value is trimmed, HTML-unescaped and its scheme lowercased before use, because HTML permits padding, spells a query separator &amp; and tolerates any scheme case, while every fetcher downstream compares the scheme byte-for-byte. Markdown targets get none of that normalization, so no Markdown reference resolves differently than it does today. A whitelisted host keeps serving the image from where it already lives, and its span is rewritten with the normalized URL rather than the raw attribute text: later stages both locate the image by searching the document for its serving URL and fetch that same string, so the two have to agree. The src attribute must now be preceded by whitespace, so a hyphenated attribute name is no longer mistaken for it. Among HTML tags this cuts two ways: one carrying both a hyphenated *-src and a real src now resolves the real src instead of the placeholder, while one carrying only a hyphenated *-src is no longer resolved at all. Recovering the latter needs an attribute parser rather than a regex, and resolving a lazy-loading placeholder while the real image goes unvisited is the worse of the two failures. Both halves are pinned by tests. Image-derived text also has to survive into the answer, which is why this touches internal/searchutil. The chat enricher and the image_info filters matched Markdown links only, so an HTML-only passage looked image-free: every entry was dropped and the model received bare markup with the caption and OCR text stripped, even though the analysis had run. Both now recognise HTML img tags through one shared regex, so a tag the parser stores can always be matched back. Both syntaxes are located against the original passage and spliced in a single pass; scanning one regex over the other's output let a metadata block that itself quotes an image reference be rescanned and duplicated. The chat variant still enriches only images present in the passage, so orphan entries stay out. Known limits: - An unquoted src and a srcset-only tag are not matched, nor is a tag whose attribute values hold a bare > or a quoted src= of their own. - imgHTMLDataURI still matches src without a boundary, so a data-src holding a base64 placeholder is consumed as if it were the src and the whole tag replaced. Worth the same fix, but it changes what an existing lazy-loading document resolves, so it belongs on its own. - A reference shown as a documentation example is rewritten like any other. Recognising code spans needs a Markdown parser; a hand-rolled scanner risks the far worse failure of treating a document's real screenshots as examples. - Rewriting a whitelisted src writes the unescaped URL back into an HTML attribute, so a query parameter whose name spells an entity renders differently than the author wrote it. Keeping the encoded form would mean unescaping on every matcher instead. - Image text reaches the model only when the whole reference falls inside the retrieved window; an img tag is several times longer than a Markdown link and straddles a chunk boundary more often. - A reference repeated in one document is fetched once per occurrence, which is what gives each chunk its own analysed copy. - Nothing bounds how long one document's fetches may take in total. - Parent-context pruning removes only Markdown images. Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-07-28 13:08:31 +00:00
"errors"
"fmt"
fix(docparser): resolve remote images referenced by HTML img tags (#2355) Remote http(s) images written as <img src="..."> reached no resolver. Markdown images went through ResolveRemoteImages, HTML data-URIs and HTML relative paths each had their own pass, but nothing claimed the remaining combination, so those images were dropped without a log line and the multimodal stage was skipped for documents that rely on HTML for layout. ResolveRemoteImages now scans HTML img tags with a quoted src as a second pass and rewrites only the src attribute value, leaving the tag intact because the surrounding markup is why these documents use HTML at all. The per-image work (whitelist, SSRF, download, icon filter, upload) moves into one helper so the two syntaxes cannot drift apart on policy. Each pass carries its own image budget; sharing one would let HTML images eat into the number of Markdown images a document already gets resolved. An attribute value is trimmed, HTML-unescaped and its scheme lowercased before use, because HTML permits padding, spells a query separator &amp; and tolerates any scheme case, while every fetcher downstream compares the scheme byte-for-byte. Markdown targets get none of that normalization, so no Markdown reference resolves differently than it does today. A whitelisted host keeps serving the image from where it already lives, and its span is rewritten with the normalized URL rather than the raw attribute text: later stages both locate the image by searching the document for its serving URL and fetch that same string, so the two have to agree. The src attribute must now be preceded by whitespace, so a hyphenated attribute name is no longer mistaken for it. Among HTML tags this cuts two ways: one carrying both a hyphenated *-src and a real src now resolves the real src instead of the placeholder, while one carrying only a hyphenated *-src is no longer resolved at all. Recovering the latter needs an attribute parser rather than a regex, and resolving a lazy-loading placeholder while the real image goes unvisited is the worse of the two failures. Both halves are pinned by tests. Image-derived text also has to survive into the answer, which is why this touches internal/searchutil. The chat enricher and the image_info filters matched Markdown links only, so an HTML-only passage looked image-free: every entry was dropped and the model received bare markup with the caption and OCR text stripped, even though the analysis had run. Both now recognise HTML img tags through one shared regex, so a tag the parser stores can always be matched back. Both syntaxes are located against the original passage and spliced in a single pass; scanning one regex over the other's output let a metadata block that itself quotes an image reference be rescanned and duplicated. The chat variant still enriches only images present in the passage, so orphan entries stay out. Known limits: - An unquoted src and a srcset-only tag are not matched, nor is a tag whose attribute values hold a bare > or a quoted src= of their own. - imgHTMLDataURI still matches src without a boundary, so a data-src holding a base64 placeholder is consumed as if it were the src and the whole tag replaced. Worth the same fix, but it changes what an existing lazy-loading document resolves, so it belongs on its own. - A reference shown as a documentation example is rewritten like any other. Recognising code spans needs a Markdown parser; a hand-rolled scanner risks the far worse failure of treating a document's real screenshots as examples. - Rewriting a whitelisted src writes the unescaped URL back into an HTML attribute, so a query parameter whose name spells an entity renders differently than the author wrote it. Keeping the encoded form would mean unescaping on every matcher instead. - Image text reaches the model only when the whole reference falls inside the retrieved window; an img tag is several times longer than a Markdown link and straddles a chunk boundary more often. - A reference repeated in one document is fetched once per occurrence, which is what gives each chunk its own analysed copy. - Nothing bounds how long one document's fetches may take in total. - Parent-context pruning removes only Markdown images. Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-07-28 13:08:31 +00:00
"html"
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"io"
"log"
"mime"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"regexp"
feat(agent): read chat attachments on demand (#4203) * feat(agent): read chat attachments on demand Agent turns pasted query-selected attachment excerpts into the prompt before the model could act. List stored files as a manifest so the agent can page and search them through read_attachment. * fix(agent): preserve attachment access and image reads * fix(agent): bound attachment cleanup and image processing * Remove standalone read_attachment tool * Read attachments and images through read_file Merge read_attachment into read_file (attachment:// paths, numbered document images, staged-copy aliasing, query search), return sandbox images as images, describe images for non-vision models inside the tool call with bounded concurrency and model-chosen detail/focus, render image reads in the UI, and record image metadata in Langfuse. * fix(agent): make attachment pagination complete and bound image reads * refactor(agent): separate attachment reads and cache image observations * fix(attachment): read image batches concurrently and harden description cache - ReadImages authorizes once and describes images in parallel - start VLM deadlines after a slot is held; longer timeout for full reads - detach shared description calls from the first caller's context - skip rewriting unchanged sandbox projections - strip the description cache from temporary document API responses - render upload text before calling the vision model * fix(attachment): number images in document order and polish attachment UI - return resolved images in document order instead of reverse - show attachment file names instead of attachment:// IDs in tool titles - use the shared file icon and a lighter card for chat attachments * fix(ci): renumber attachment migrations and satisfy lint Main already took sqlite 000035 and versioned 000116, so the attachment lookup indexes move to the next free numbers. Also wrap the ReadImages signature and drop an unused test parameter. * fix(ci): expect sqlite migrations to reach version 36
2026-10-13 06:37:17 +00:00
"sort"
"strings"
"time"
fix(docparser): resolve remote images referenced by HTML img tags (#2355) Remote http(s) images written as <img src="..."> reached no resolver. Markdown images went through ResolveRemoteImages, HTML data-URIs and HTML relative paths each had their own pass, but nothing claimed the remaining combination, so those images were dropped without a log line and the multimodal stage was skipped for documents that rely on HTML for layout. ResolveRemoteImages now scans HTML img tags with a quoted src as a second pass and rewrites only the src attribute value, leaving the tag intact because the surrounding markup is why these documents use HTML at all. The per-image work (whitelist, SSRF, download, icon filter, upload) moves into one helper so the two syntaxes cannot drift apart on policy. Each pass carries its own image budget; sharing one would let HTML images eat into the number of Markdown images a document already gets resolved. An attribute value is trimmed, HTML-unescaped and its scheme lowercased before use, because HTML permits padding, spells a query separator &amp; and tolerates any scheme case, while every fetcher downstream compares the scheme byte-for-byte. Markdown targets get none of that normalization, so no Markdown reference resolves differently than it does today. A whitelisted host keeps serving the image from where it already lives, and its span is rewritten with the normalized URL rather than the raw attribute text: later stages both locate the image by searching the document for its serving URL and fetch that same string, so the two have to agree. The src attribute must now be preceded by whitespace, so a hyphenated attribute name is no longer mistaken for it. Among HTML tags this cuts two ways: one carrying both a hyphenated *-src and a real src now resolves the real src instead of the placeholder, while one carrying only a hyphenated *-src is no longer resolved at all. Recovering the latter needs an attribute parser rather than a regex, and resolving a lazy-loading placeholder while the real image goes unvisited is the worse of the two failures. Both halves are pinned by tests. Image-derived text also has to survive into the answer, which is why this touches internal/searchutil. The chat enricher and the image_info filters matched Markdown links only, so an HTML-only passage looked image-free: every entry was dropped and the model received bare markup with the caption and OCR text stripped, even though the analysis had run. Both now recognise HTML img tags through one shared regex, so a tag the parser stores can always be matched back. Both syntaxes are located against the original passage and spliced in a single pass; scanning one regex over the other's output let a metadata block that itself quotes an image reference be rescanned and duplicated. The chat variant still enriches only images present in the passage, so orphan entries stay out. Known limits: - An unquoted src and a srcset-only tag are not matched, nor is a tag whose attribute values hold a bare > or a quoted src= of their own. - imgHTMLDataURI still matches src without a boundary, so a data-src holding a base64 placeholder is consumed as if it were the src and the whole tag replaced. Worth the same fix, but it changes what an existing lazy-loading document resolves, so it belongs on its own. - A reference shown as a documentation example is rewritten like any other. Recognising code spans needs a Markdown parser; a hand-rolled scanner risks the far worse failure of treating a document's real screenshots as examples. - Rewriting a whitelisted src writes the unescaped URL back into an HTML attribute, so a query parameter whose name spells an entity renders differently than the author wrote it. Keeping the encoded form would mean unescaping on every matcher instead. - Image text reaches the model only when the whole reference falls inside the retrieved window; an img tag is several times longer than a Markdown link and straddles a chunk boundary more often. - A reference repeated in one document is fetched once per occurrence, which is what gives each chunk its own analysed copy. - Nothing bounds how long one document's fetches may take in total. - Parent-context pruning removes only Markdown images. Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-07-28 13:08:31 +00:00
"github.com/Tencent/WeKnora/internal/searchutil"
secutils "github.com/Tencent/WeKnora/internal/utils"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/google/uuid"
)
const (
// minImageDimension is the minimum width/height in pixels; images smaller
// than this on either axis are treated as icons and filtered out.
minImageDimension = 64
// minImageBytes is the minimum file size in bytes; very small images are
// almost certainly icons or decorative elements.
minImageBytes = 512 // 512 bytes
)
// isIconImage returns true if the image data looks like a small icon or
// decorative element that should be filtered out. It checks pixel dimensions
// when decodable, and falls back to raw byte size otherwise.
func isIconImage(data []byte) bool {
cfg, _, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil {
// Cannot decode dimensions — fall back to size-only heuristic.
return len(data) < minImageBytes
}
if cfg.Width < minImageDimension && cfg.Height < minImageDimension {
return true
}
return false
}
// StoredImage describes an image that has been saved to storage.
type StoredImage struct {
OriginalRef string // reference in the original markdown
ServingURL string // provider:// URL (e.g. local://images/xxx.png, minio://bucket/key)
MimeType string
feat(chat): open cited documents at the cited passage (#3700) * feat(chat): open cited documents at the cited passage Clicking a citation used to show only the parsed chunk. It now opens the original file in the references panel, jumps to the cited place and highlights it, narrowed to the sentence the citation supports. Parsing records where each chunk sits in the original file (chunks.source_locators): PDF page and paragraph boxes from the docreader, MinerU and PaddleOCR-VL layouts; Word paragraphs, slides, sheet rows and EPUB chapters aligned in Go against any parser engine's Markdown; text offsets for Markdown/TXT; segment times for audio. Pipeline text rewrites are followed with a line-diff remapper. Scanned PDF pages get their OCR text as quotes at search time so a sentence can pick its page. The frontend renders PDFs with pdf.js and every other previewable type with the existing preview, then highlights with the CSS Custom Highlight API in a highlighter yellow that stays visible against the brand green. * fix(docreader): serialize source blocks outside main so tests import it test_docx_tables stubs docreader.parser in sys.modules, so importing docreader.main from a later test failed in the full unittest discover run. The wire conversion now lives in docreader.source_wire, which needs only the proto. * fix(chat): tighten source locators from review - Remap rewritten-line-for-line stretches by line so scanned PDF pages no longer drift onto the wrong page. - Keep the source preview mounted for citations in the file already open. - Wait for in-flight PDF page renders before looking for the text layer. - Count image rune offsets in one pass; stream xlsx rows up to maxUnits. - Start text locators after a UTF-8 BOM, as viewers decode without it. - Only re-query image children for scanned-page results. - Seek audio citations without autoplay and drop stale seek listeners. - Fix the SQLite migration's cross-reference to versioned/000113. * fix(migrations): renumber chunk source locators after main's chunk_images main took versioned 000113 and sqlite 000032 for chunk_images, so the source_locators column moves to versioned 000114 and sqlite 000033.
2026-09-25 05:26:16 +00:00
// SourceLocators place the image in the original file (e.g. the scanned
// page it was rendered from). Filled by ingestion after resolution.
SourceLocators types.SourceLocators
}
// ImageResolver reads images from a DocReader ReadResult (inline bytes only)
// and saves them via FileService, replacing markdown references with unified URLs.
type ImageResolver struct {
// TenantID for storage path namespacing
TenantID uint64
}
// NewImageResolver creates a resolver.
func NewImageResolver() *ImageResolver {
return &ImageResolver{}
}
// ResolveAndStore reads images from the convert result, persists them via fileSvc,
// and replaces markdown references with provider:// URLs.
// It returns the updated markdown and a list of stored images.
func (r *ImageResolver) ResolveAndStore(
ctx context.Context,
result *types.ReadResult,
fileSvc interfaces.FileService,
tenantID uint64,
) (updatedMarkdown string, images []StoredImage, err error) {
markdown := UnwrapLinkedImages(result.MarkdownContent)
md2, imgDataURIs, _ := r.ResolveDataURIImages(ctx, markdown, fileSvc, tenantID)
markdown = md2
images = append(images, imgDataURIs...)
md3, imgHTML, _ := r.ResolveHTMLDataURIImages(ctx, markdown, fileSvc, tenantID)
markdown = md3
images = append(images, imgHTML...)
md4, imgBare, _ := r.ResolveBareBase64Content(ctx, markdown, fileSvc, tenantID)
markdown = md4
images = append(images, imgBare...)
if len(result.ImageRefs) == 0 {
feat(agent): read chat attachments on demand (#4203) * feat(agent): read chat attachments on demand Agent turns pasted query-selected attachment excerpts into the prompt before the model could act. List stored files as a manifest so the agent can page and search them through read_attachment. * fix(agent): preserve attachment access and image reads * fix(agent): bound attachment cleanup and image processing * Remove standalone read_attachment tool * Read attachments and images through read_file Merge read_attachment into read_file (attachment:// paths, numbered document images, staged-copy aliasing, query search), return sandbox images as images, describe images for non-vision models inside the tool call with bounded concurrency and model-chosen detail/focus, render image reads in the UI, and record image metadata in Langfuse. * fix(agent): make attachment pagination complete and bound image reads * refactor(agent): separate attachment reads and cache image observations * fix(attachment): read image batches concurrently and harden description cache - ReadImages authorizes once and describes images in parallel - start VLM deadlines after a slot is held; longer timeout for full reads - detach shared description calls from the first caller's context - skip rewriting unchanged sandbox projections - strip the description cache from temporary document API responses - render upload text before calling the vision model * fix(attachment): number images in document order and polish attachment UI - return resolved images in document order instead of reverse - show attachment file names instead of attachment:// IDs in tool titles - use the shared file icon and a lighter card for chat attachments * fix(ci): renumber attachment migrations and satisfy lint Main already took sqlite 000035 and versioned 000116, so the attachment lookup indexes move to the next free numbers. Also wrap the ReadImages signature and drop an unused test parameter. * fix(ci): expect sqlite migrations to reach version 36
2026-10-13 06:37:17 +00:00
return markdown, sortImagesByPosition(markdown, images), nil
}
// Build a map of original_ref -> image ref for fast lookup
refMap := make(map[string]types.ImageRef)
for _, ref := range result.ImageRefs {
refMap[ref.OriginalRef] = ref
}
savedRefs := make(map[string]StoredImage)
matches := scanMarkdownImageTargets(markdown)
// Process in reverse order to preserve positions when replacing
for i := len(matches) - 1; i >= 0; i-- {
match := matches[i]
rawTarget := markdown[match.TargetStart:match.TargetEnd]
refPath, pathStart, pathEnd, ok := splitMarkdownImageTarget(rawTarget, refMap)
if !ok {
continue
}
// Skip already-resolved URLs (http/https, unified /files/, or provider:// scheme)
if strings.HasPrefix(refPath, "http://") || strings.HasPrefix(refPath, "https://") ||
isProviderScheme(refPath) {
continue
}
// Find inline image bytes from the result
stored, ok := r.saveReferencedImage(ctx, fileSvc, tenantID, refPath, refMap, savedRefs)
if !ok {
continue
}
images = appendStoredImage(images, stored)
// Replace in markdown
absolutePathStart := match.TargetStart + pathStart
absolutePathEnd := match.TargetStart + pathEnd
markdown = markdown[:absolutePathStart] + stored.ServingURL + markdown[absolutePathEnd:]
}
md5, imgRelativeHTML, _ := r.ResolveRelativeHTMLImages(ctx, markdown, fileSvc, tenantID, refMap, savedRefs)
markdown = md5
images = append(images, imgRelativeHTML...)
feat(agent): read chat attachments on demand (#4203) * feat(agent): read chat attachments on demand Agent turns pasted query-selected attachment excerpts into the prompt before the model could act. List stored files as a manifest so the agent can page and search them through read_attachment. * fix(agent): preserve attachment access and image reads * fix(agent): bound attachment cleanup and image processing * Remove standalone read_attachment tool * Read attachments and images through read_file Merge read_attachment into read_file (attachment:// paths, numbered document images, staged-copy aliasing, query search), return sandbox images as images, describe images for non-vision models inside the tool call with bounded concurrency and model-chosen detail/focus, render image reads in the UI, and record image metadata in Langfuse. * fix(agent): make attachment pagination complete and bound image reads * refactor(agent): separate attachment reads and cache image observations * fix(attachment): read image batches concurrently and harden description cache - ReadImages authorizes once and describes images in parallel - start VLM deadlines after a slot is held; longer timeout for full reads - detach shared description calls from the first caller's context - skip rewriting unchanged sandbox projections - strip the description cache from temporary document API responses - render upload text before calling the vision model * fix(attachment): number images in document order and polish attachment UI - return resolved images in document order instead of reverse - show attachment file names instead of attachment:// IDs in tool titles - use the shared file icon and a lighter card for chat attachments * fix(ci): renumber attachment migrations and satisfy lint Main already took sqlite 000035 and versioned 000116, so the attachment lookup indexes move to the next free numbers. Also wrap the ReadImages signature and drop an unused test parameter. * fix(ci): expect sqlite migrations to reach version 36
2026-10-13 06:37:17 +00:00
return markdown, sortImagesByPosition(markdown, images), nil
}
// sortImagesByPosition orders images by where they first appear in markdown,
// since each resolution pass collects its own kind and references are
// rewritten back to front. Callers number images by this order. Images not
// found in markdown keep their relative order at the end.
func sortImagesByPosition(markdown string, images []StoredImage) []StoredImage {
position := func(image StoredImage) int {
if i := strings.Index(markdown, image.ServingURL); image.ServingURL != "" && i >= 0 {
return i
}
return len(markdown)
}
sort.SliceStable(images, func(a, b int) bool {
return position(images[a]) < position(images[b])
})
return images
}
func appendStoredImage(images []StoredImage, stored StoredImage) []StoredImage {
for _, existing := range images {
if existing.OriginalRef == stored.OriginalRef && existing.ServingURL == stored.ServingURL {
return images
}
}
return append(images, stored)
}
func (r *ImageResolver) saveReferencedImage(
ctx context.Context,
fileSvc interfaces.FileService,
tenantID uint64,
refPath string,
refMap map[string]types.ImageRef,
savedRefs map[string]StoredImage,
) (StoredImage, bool) {
if stored, ok := savedRefs[refPath]; ok {
return stored, true
}
ref, found := refMap[refPath]
if !found || len(ref.ImageData) == 0 {
return StoredImage{}, false
}
if !ref.IsOriginal && isIconImage(ref.ImageData) {
return StoredImage{}, false
}
// Reuse a previously saved upload when the same source image (identified by
// ref.Filename) has already been persisted under a different markdown ref
// path (e.g. "images/foo.png" vs "./images/foo.png"). This avoids writing
// the same bytes to object storage multiple times.
if ref.Filename != "" {
if cached, ok := savedRefs["__filename__:"+ref.Filename]; ok {
stored := StoredImage{
OriginalRef: refPath,
ServingURL: cached.ServingURL,
MimeType: cached.MimeType,
}
savedRefs[refPath] = stored
return stored, true
}
}
ext := extFromMime(ref.MimeType)
if ext == "" {
ext = filepath.Ext(ref.Filename)
}
if ext == "" {
ext = ".png"
}
fileName := uuid.New().String() + ext
servingURL, saveErr := fileSvc.SaveBytes(ctx, ref.ImageData, tenantID, fileName, false)
if saveErr != nil {
log.Printf("WARN: failed to save image %s: %v", refPath, saveErr)
return StoredImage{}, false
}
stored := StoredImage{
OriginalRef: refPath,
ServingURL: servingURL,
MimeType: ref.MimeType,
}
savedRefs[refPath] = stored
if ref.Filename != "" {
savedRefs["__filename__:"+ref.Filename] = stored
}
return stored, true
}
func extFromMime(mime string) string {
switch mime {
case "image/png":
return ".png"
case "image/jpeg":
return ".jpg"
case "image/gif":
return ".gif"
case "image/webp":
return ".webp"
case "image/bmp":
return ".bmp"
case "image/svg+xml":
return ".svg"
default:
return ""
}
}
// isProviderScheme checks if the path uses a provider:// scheme (local://, minio://, cos://, tos://).
func isProviderScheme(p string) bool {
2026-05-18 10:54:57 +00:00
for _, prefix := range []string{"local://", "minio://", "cos://", "tos://", "s3://", "obs://"} {
if strings.HasPrefix(p, prefix) {
return true
}
}
return false
}
// isWhitelistedImageHost checks if the image URL's host is in the whitelist.
// Whitelisted hosts are trusted (e.g. internal MinerU service) — images are
// still downloaded for validation and OCR/caption analysis, but not uploaded
// to object storage. The markdown keeps the original URL.
// Configure via IMAGE_HOST_KEEP_URL env var (comma-separated hosts).
func isWhitelistedImageHost(rawURL string) bool {
whitelist := strings.TrimSpace(os.Getenv("IMAGE_HOST_KEEP_URL"))
if whitelist == "" {
return false
}
u, err := url.Parse(rawURL)
if err != nil || u.Host == "" {
return false
}
host := strings.ToLower(u.Host)
hostname := strings.ToLower(u.Hostname())
for _, h := range strings.Split(whitelist, ",") {
h = strings.ToLower(strings.TrimSpace(h))
if h == "" {
continue
}
// Exact host match (includes port) or hostname match (any port)
if host == h || hostname == h {
return true
}
}
return false
}
// ---------------------------------------------------------------------------
// Helper functions for base64 image handling
// ---------------------------------------------------------------------------
// cleanBase64Payload removes whitespace characters from a base64 payload string.
func cleanBase64Payload(payload string) string {
payload = strings.ReplaceAll(payload, "\n", "")
payload = strings.ReplaceAll(payload, "\r", "")
payload = strings.ReplaceAll(payload, "\t", "")
payload = strings.ReplaceAll(payload, " ", "")
return payload
}
// decodeBase64Flexible tries standard, raw, URL-safe, and raw-URL-safe base64 decodings.
func decodeBase64Flexible(payload string) ([]byte, error) {
if data, err := base64.StdEncoding.DecodeString(payload); err == nil {
return data, nil
}
if data, err := base64.RawStdEncoding.DecodeString(payload); err == nil {
return data, nil
}
if data, err := base64.URLEncoding.DecodeString(payload); err == nil {
return data, nil
}
return base64.RawURLEncoding.DecodeString(payload)
}
// sniffImageMime detects the MIME type by examining the magic bytes of image data.
func sniffImageMime(data []byte) string {
if len(data) < 4 {
return ""
}
if data[0] == 0x89 && data[1] == 'P' && data[2] == 'N' && data[3] == 'G' {
return "image/png"
}
if data[0] == 0xFF && data[1] == 0xD8 && data[2] == 0xFF {
return "image/jpeg"
}
if data[0] == 'G' && data[1] == 'I' && data[2] == 'F' {
return "image/gif"
}
if len(data) >= 12 &&
data[0] == 'R' && data[1] == 'I' && data[2] == 'F' && data[3] == 'F' &&
data[8] == 'W' && data[9] == 'E' && data[10] == 'B' && data[11] == 'P' {
return "image/webp"
}
if data[0] == 'B' && data[1] == 'M' {
return "image/bmp"
}
return ""
}
// ---------------------------------------------------------------------------
// HTML <img> tag data URI resolution
// ---------------------------------------------------------------------------
// imgHTMLDataURI matches HTML <img> tags with inline data:image/*;base64,... in the src attribute.
var imgHTMLDataURI = regexp.MustCompile(
`(?i)<img\s[^>]*?src\s*=\s*["'](data:image/[^;]+;base64,[^"']+)["'][^>]*?/?\s*>`,
)
fix(docparser): resolve remote images referenced by HTML img tags (#2355) Remote http(s) images written as <img src="..."> reached no resolver. Markdown images went through ResolveRemoteImages, HTML data-URIs and HTML relative paths each had their own pass, but nothing claimed the remaining combination, so those images were dropped without a log line and the multimodal stage was skipped for documents that rely on HTML for layout. ResolveRemoteImages now scans HTML img tags with a quoted src as a second pass and rewrites only the src attribute value, leaving the tag intact because the surrounding markup is why these documents use HTML at all. The per-image work (whitelist, SSRF, download, icon filter, upload) moves into one helper so the two syntaxes cannot drift apart on policy. Each pass carries its own image budget; sharing one would let HTML images eat into the number of Markdown images a document already gets resolved. An attribute value is trimmed, HTML-unescaped and its scheme lowercased before use, because HTML permits padding, spells a query separator &amp; and tolerates any scheme case, while every fetcher downstream compares the scheme byte-for-byte. Markdown targets get none of that normalization, so no Markdown reference resolves differently than it does today. A whitelisted host keeps serving the image from where it already lives, and its span is rewritten with the normalized URL rather than the raw attribute text: later stages both locate the image by searching the document for its serving URL and fetch that same string, so the two have to agree. The src attribute must now be preceded by whitespace, so a hyphenated attribute name is no longer mistaken for it. Among HTML tags this cuts two ways: one carrying both a hyphenated *-src and a real src now resolves the real src instead of the placeholder, while one carrying only a hyphenated *-src is no longer resolved at all. Recovering the latter needs an attribute parser rather than a regex, and resolving a lazy-loading placeholder while the real image goes unvisited is the worse of the two failures. Both halves are pinned by tests. Image-derived text also has to survive into the answer, which is why this touches internal/searchutil. The chat enricher and the image_info filters matched Markdown links only, so an HTML-only passage looked image-free: every entry was dropped and the model received bare markup with the caption and OCR text stripped, even though the analysis had run. Both now recognise HTML img tags through one shared regex, so a tag the parser stores can always be matched back. Both syntaxes are located against the original passage and spliced in a single pass; scanning one regex over the other's output let a metadata block that itself quotes an image reference be rescanned and duplicated. The chat variant still enriches only images present in the passage, so orphan entries stay out. Known limits: - An unquoted src and a srcset-only tag are not matched, nor is a tag whose attribute values hold a bare > or a quoted src= of their own. - imgHTMLDataURI still matches src without a boundary, so a data-src holding a base64 placeholder is consumed as if it were the src and the whole tag replaced. Worth the same fix, but it changes what an existing lazy-loading document resolves, so it belongs on its own. - A reference shown as a documentation example is rewritten like any other. Recognising code spans needs a Markdown parser; a hand-rolled scanner risks the far worse failure of treating a document's real screenshots as examples. - Rewriting a whitelisted src writes the unescaped URL back into an HTML attribute, so a query parameter whose name spells an entity renders differently than the author wrote it. Keeping the encoded form would mean unescaping on every matcher instead. - Image text reaches the model only when the whole reference falls inside the retrieved window; an img tag is several times longer than a Markdown link and straddles a chunk boundary more often. - A reference repeated in one document is fetched once per occurrence, which is what gives each chunk its own analysed copy. - Nothing bounds how long one document's fetches may take in total. - Parent-context pruning removes only Markdown images. Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-07-28 13:08:31 +00:00
// imgHTMLSrc matches an HTML <img> tag carrying a quoted src attribute. It does
// not care what the src points at — callers select the references they handle by
// inspecting the scheme, which is how the relative and the remote paths divide
// the same tags between them.
//
// Shared with the search layer so that an image stored here can always be
// matched back to the tag it came from. See searchutil.HTMLImageSrcRegex for
// the submatch layout and the known limits.
var imgHTMLSrc = searchutil.HTMLImageSrcRegex
// ResolveHTMLDataURIImages finds <img src="data:image/*;base64,..."> tags in markdown,
// decodes the images, stores them via fileSvc, and replaces each tag with a markdown
// image reference using the storage URL.
func (r *ImageResolver) ResolveHTMLDataURIImages(
ctx context.Context,
markdown string,
fileSvc interfaces.FileService,
tenantID uint64,
) (updatedMarkdown string, images []StoredImage, err error) {
matches := imgHTMLDataURI.FindAllStringSubmatchIndex(markdown, -1)
if len(matches) == 0 {
return markdown, nil, nil
}
processed := 0
for i := len(matches) - 1; i >= 0; i-- {
if processed >= maxRemoteImages {
break
}
m := matches[i]
dataURI := markdown[m[2]:m[3]]
mimeType, payload, ok := parseImageDataURI(dataURI)
if !ok {
continue
}
payload = cleanBase64Payload(payload)
if payload == "" {
continue
}
data, decErr := decodeBase64Flexible(payload)
if decErr != nil {
log.Printf("WARN: HTML img data URI base64 decode failed: %v", decErr)
continue
}
if len(data) > maxRemoteImageSize {
continue
}
if isIconImage(data) {
markdown = markdown[:m[0]] + markdown[m[1]:]
continue
}
ext := extFromMime(mimeType)
if ext == "" {
ext = ".png"
}
fileName := uuid.New().String() + ext
servingURL, saveErr := fileSvc.SaveBytes(ctx, data, tenantID, fileName, false)
if saveErr != nil {
log.Printf("WARN: failed to save HTML img data URI image: %v", saveErr)
continue
}
images = append(images, StoredImage{
OriginalRef: "html-img-data-uri",
ServingURL: servingURL,
MimeType: mimeType,
})
markdown = markdown[:m[0]] + fmt.Sprintf("![image](%s)", servingURL) + markdown[m[1]:]
processed++
}
return markdown, images, nil
}
// ResolveRelativeHTMLImages finds HTML <img> tags whose src points at a
// relative document image reference, stores the corresponding bytes via
// fileSvc, and replaces only the src attribute value with the storage URL.
func (r *ImageResolver) ResolveRelativeHTMLImages(
ctx context.Context,
markdown string,
fileSvc interfaces.FileService,
tenantID uint64,
refMap map[string]types.ImageRef,
savedRefs map[string]StoredImage,
) (updatedMarkdown string, images []StoredImage, err error) {
fix(docparser): resolve remote images referenced by HTML img tags (#2355) Remote http(s) images written as <img src="..."> reached no resolver. Markdown images went through ResolveRemoteImages, HTML data-URIs and HTML relative paths each had their own pass, but nothing claimed the remaining combination, so those images were dropped without a log line and the multimodal stage was skipped for documents that rely on HTML for layout. ResolveRemoteImages now scans HTML img tags with a quoted src as a second pass and rewrites only the src attribute value, leaving the tag intact because the surrounding markup is why these documents use HTML at all. The per-image work (whitelist, SSRF, download, icon filter, upload) moves into one helper so the two syntaxes cannot drift apart on policy. Each pass carries its own image budget; sharing one would let HTML images eat into the number of Markdown images a document already gets resolved. An attribute value is trimmed, HTML-unescaped and its scheme lowercased before use, because HTML permits padding, spells a query separator &amp; and tolerates any scheme case, while every fetcher downstream compares the scheme byte-for-byte. Markdown targets get none of that normalization, so no Markdown reference resolves differently than it does today. A whitelisted host keeps serving the image from where it already lives, and its span is rewritten with the normalized URL rather than the raw attribute text: later stages both locate the image by searching the document for its serving URL and fetch that same string, so the two have to agree. The src attribute must now be preceded by whitespace, so a hyphenated attribute name is no longer mistaken for it. Among HTML tags this cuts two ways: one carrying both a hyphenated *-src and a real src now resolves the real src instead of the placeholder, while one carrying only a hyphenated *-src is no longer resolved at all. Recovering the latter needs an attribute parser rather than a regex, and resolving a lazy-loading placeholder while the real image goes unvisited is the worse of the two failures. Both halves are pinned by tests. Image-derived text also has to survive into the answer, which is why this touches internal/searchutil. The chat enricher and the image_info filters matched Markdown links only, so an HTML-only passage looked image-free: every entry was dropped and the model received bare markup with the caption and OCR text stripped, even though the analysis had run. Both now recognise HTML img tags through one shared regex, so a tag the parser stores can always be matched back. Both syntaxes are located against the original passage and spliced in a single pass; scanning one regex over the other's output let a metadata block that itself quotes an image reference be rescanned and duplicated. The chat variant still enriches only images present in the passage, so orphan entries stay out. Known limits: - An unquoted src and a srcset-only tag are not matched, nor is a tag whose attribute values hold a bare > or a quoted src= of their own. - imgHTMLDataURI still matches src without a boundary, so a data-src holding a base64 placeholder is consumed as if it were the src and the whole tag replaced. Worth the same fix, but it changes what an existing lazy-loading document resolves, so it belongs on its own. - A reference shown as a documentation example is rewritten like any other. Recognising code spans needs a Markdown parser; a hand-rolled scanner risks the far worse failure of treating a document's real screenshots as examples. - Rewriting a whitelisted src writes the unescaped URL back into an HTML attribute, so a query parameter whose name spells an entity renders differently than the author wrote it. Keeping the encoded form would mean unescaping on every matcher instead. - Image text reaches the model only when the whole reference falls inside the retrieved window; an img tag is several times longer than a Markdown link and straddles a chunk boundary more often. - A reference repeated in one document is fetched once per occurrence, which is what gives each chunk its own analysed copy. - Nothing bounds how long one document's fetches may take in total. - Parent-context pruning removes only Markdown images. Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-07-28 13:08:31 +00:00
matches := imgHTMLSrc.FindAllStringSubmatchIndex(markdown, -1)
if len(matches) == 0 {
return markdown, nil, nil
}
for i := len(matches) - 1; i >= 0; i-- {
m := matches[i]
src := strings.TrimSpace(markdown[m[4]:m[5]])
if src == "" || strings.HasPrefix(src, "http://") || strings.HasPrefix(src, "https://") ||
isProviderScheme(src) || strings.HasPrefix(strings.ToLower(src), "data:image/") {
continue
}
stored, ok := r.saveReferencedImage(ctx, fileSvc, tenantID, src, refMap, savedRefs)
if !ok {
continue
}
images = appendStoredImage(images, stored)
markdown = markdown[:m[4]] + stored.ServingURL + markdown[m[5]:]
}
return markdown, images, nil
}
// ---------------------------------------------------------------------------
// Bare base64/data URI resolution (catch-all)
// ---------------------------------------------------------------------------
// bareDataURIPattern matches standalone data:image/*;base64,... strings.
var bareDataURIPattern = regexp.MustCompile(
`(?i)data:image/([^;\s]+);base64,([A-Za-z0-9+/=]{100,})`,
)
// bareBase64CommaPrefixed matches base64,DATA patterns (partial data URIs missing the mime prefix).
var bareBase64CommaPrefixed = regexp.MustCompile(
`base64,([A-Za-z0-9+/=]{200,})`,
)
// ResolveBareBase64Content finds remaining bare data URIs and base64 image content
// in the markdown text, decodes and stores them, and replaces with image references.
// This acts as a catch-all after the standard markdown and HTML resolvers.
func (r *ImageResolver) ResolveBareBase64Content(
ctx context.Context,
markdown string,
fileSvc interfaces.FileService,
tenantID uint64,
) (updatedMarkdown string, images []StoredImage, err error) {
md, imgs1 := r.resolveBareDataURIs(ctx, markdown, fileSvc, tenantID)
markdown = md
images = append(images, imgs1...)
md2, imgs2 := r.resolveBareBase64Prefix(ctx, markdown, fileSvc, tenantID)
markdown = md2
images = append(images, imgs2...)
return markdown, images, nil
}
func (r *ImageResolver) resolveBareDataURIs(
ctx context.Context,
markdown string,
fileSvc interfaces.FileService,
tenantID uint64,
) (string, []StoredImage) {
matches := bareDataURIPattern.FindAllStringSubmatchIndex(markdown, -1)
if len(matches) == 0 {
return markdown, nil
}
var images []StoredImage
processed := 0
for i := len(matches) - 1; i >= 0; i-- {
if processed >= maxRemoteImages {
break
}
m := matches[i]
// Check context: skip HTML src attributes, but handle broken markdown refs
insideWrapper := false
if m[0] > 0 {
prev := markdown[m[0]-1]
if prev == '"' || prev == '\'' {
continue // inside HTML attribute — already handled by ResolveHTMLDataURIImages
}
if prev == '(' {
insideWrapper = true // likely inside a broken ![...](...) ref
}
}
mimeSubtype := strings.ToLower(markdown[m[2]:m[3]])
payload := markdown[m[4]:m[5]]
mimeType := "image/" + mimeSubtype
payload = cleanBase64Payload(payload)
if payload == "" {
continue
}
data, decErr := decodeBase64Flexible(payload)
if decErr != nil {
log.Printf("WARN: bare data URI base64 decode failed: %v", decErr)
continue
}
if len(data) > maxRemoteImageSize {
continue
}
if isIconImage(data) {
markdown = markdown[:m[0]] + markdown[m[1]:]
continue
}
ext := extFromMime(mimeType)
if ext == "" {
ext = ".png"
}
fileName := uuid.New().String() + ext
servingURL, saveErr := fileSvc.SaveBytes(ctx, data, tenantID, fileName, false)
if saveErr != nil {
log.Printf("WARN: failed to save bare data URI image: %v", saveErr)
continue
}
images = append(images, StoredImage{
OriginalRef: "bare-data-uri",
ServingURL: servingURL,
MimeType: mimeType,
})
if insideWrapper {
// Inside a broken markdown ref like ![weird]alt](data:...) — replace data URI only
markdown = markdown[:m[0]] + servingURL + markdown[m[1]:]
} else {
markdown = markdown[:m[0]] + fmt.Sprintf("![image](%s)", servingURL) + markdown[m[1]:]
}
processed++
}
return markdown, images
}
func (r *ImageResolver) resolveBareBase64Prefix(
ctx context.Context,
markdown string,
fileSvc interfaces.FileService,
tenantID uint64,
) (string, []StoredImage) {
matches := bareBase64CommaPrefixed.FindAllStringSubmatchIndex(markdown, -1)
if len(matches) == 0 {
return markdown, nil
}
var images []StoredImage
processed := 0
for i := len(matches) - 1; i >= 0; i-- {
if processed >= maxRemoteImages {
break
}
m := matches[i]
// Skip if preceded by ';' — this is part of a data URI handled above
if m[0] > 0 && markdown[m[0]-1] == ';' {
continue
}
payload := markdown[m[2]:m[3]]
payload = cleanBase64Payload(payload)
if payload == "" {
continue
}
data, decErr := decodeBase64Flexible(payload)
if decErr != nil {
continue
}
if len(data) > maxRemoteImageSize {
continue
}
mimeType := sniffImageMime(data)
if mimeType == "" {
continue
}
if isIconImage(data) {
markdown = markdown[:m[0]] + markdown[m[1]:]
continue
}
ext := extFromMime(mimeType)
if ext == "" {
ext = ".png"
}
fileName := uuid.New().String() + ext
servingURL, saveErr := fileSvc.SaveBytes(ctx, data, tenantID, fileName, false)
if saveErr != nil {
log.Printf("WARN: failed to save bare base64 image: %v", saveErr)
continue
}
images = append(images, StoredImage{
OriginalRef: "bare-base64",
ServingURL: servingURL,
MimeType: mimeType,
})
markdown = markdown[:m[0]] + fmt.Sprintf("![image](%s)", servingURL) + markdown[m[1]:]
processed++
}
return markdown, images
}
// ---------------------------------------------------------------------------
// Remote image resolution (for manual / web-clipped markdown content)
// ---------------------------------------------------------------------------
const (
// maxRemoteImageSize is the maximum allowed size for a single remote image download.
maxRemoteImageSize = 10 * 1024 * 1024 // 10 MB
// maxRemoteImages is the maximum number of remote images to process per document.
maxRemoteImages = 30
// remoteImageFetchTimeout is the per-image HTTP request timeout.
remoteImageFetchTimeout = 15 * time.Second
)
// reLinkedImage matches the nested [![alt](img_url)](link_url) pattern where
// an image is wrapped inside a Markdown link. We unwrap it to just ![alt](img_url)
// so that downstream image-processing regexes only have to handle the flat form.
// The URL groups support one level of balanced parentheses.
var reLinkedImage = regexp.MustCompile(
`\[!\[([^\]]*)\]\(([^()\s]*(?:\([^)]*\)[^()\s]*)*)\)\]` + // [![alt](img_url)]
`\([^()\s]*(?:\([^)]*\)[^()\s]*)*\)`, // (link_url) — captured but discarded
)
// UnwrapLinkedImages replaces all [![alt](img_url)](link_url) occurrences in
// the markdown with just ![alt](img_url), stripping the outer link wrapper.
// This should be called before any image-extraction regex so that only the
// flat ![alt](url) form needs to be handled.
func UnwrapLinkedImages(markdown string) string {
return reLinkedImage.ReplaceAllString(markdown, "![$1]($2)")
}
// imgMarkdownPattern matches Markdown image syntax: ![alt](url).
// The alt-text group uses .*? (non-greedy) to allow literal ] in alt text.
// The URL group supports one level of balanced parentheses so that URLs
// like https://example.com/item_(abc)/123 are captured in full.
var imgMarkdownPattern = regexp.MustCompile(`!\[(.*?)\]\(([^()\s]*(?:\([^)]*\)[^()\s]*)*)\)`)
// imgMarkdownDataURI matches markdown images whose URL is a data:image/*;base64,...
// payload. (?i) applies to the whole parenthesized data URI.
// The alt-text group uses .*? (non-greedy) to allow literal ] inside alt text
// (e.g. file paths like ![C:\img]name.png](data:...)).
var imgMarkdownDataURI = regexp.MustCompile(
`!\[(.*?)\]\((?i:(data:image/[^;]+;base64,\s*[^)]+))\)`,
)
// parseImageDataURI splits a data URI into image MIME type and base64 payload.
func parseImageDataURI(dataURI string) (mimeType string, b64Payload string, ok bool) {
const sep = ";base64,"
idx := strings.Index(strings.ToLower(dataURI), sep)
if idx < 0 {
return "", "", false
}
meta := strings.TrimSpace(dataURI[:idx])
const prefix = "data:image/"
if len(meta) < len(prefix) || !strings.EqualFold(meta[:len(prefix)], prefix) {
return "", "", false
}
sub := strings.TrimSpace(meta[len(prefix):])
mimeType = "image/" + strings.ToLower(sub)
b64Payload = strings.TrimSpace(dataURI[idx+len(sep):])
if b64Payload == "" {
return "", "", false
}
return mimeType, b64Payload, true
}
// ResolveDataURIImages finds embedded data:image/*;base64 images in markdown,
// decodes them, stores via fileSvc, and replaces each reference with the returned
// provider URL (same limits as remote images: count and decoded size).
func (r *ImageResolver) ResolveDataURIImages(
ctx context.Context,
markdown string,
fileSvc interfaces.FileService,
tenantID uint64,
) (updatedMarkdown string, images []StoredImage, err error) {
markdown = UnwrapLinkedImages(markdown)
matches := imgMarkdownDataURI.FindAllStringSubmatchIndex(markdown, -1)
if len(matches) == 0 {
return markdown, nil, nil
}
processed := 0
for i := len(matches) - 1; i >= 0; i-- {
feat(datasource): deep-adapt Feishu/Lark sync with folder mirror, block parsing and embedded objects (#3497) * ci(build): add manual docker build workflow Co-Authored-By: Claude <noreply@anthropic.com> * feat(datasource): deep-adapt Feishu/Lark sync with folder mirror, block parsing and embedded objects - folder mirror: wiki/drive connectors emit path-qualified FileName so knowledge lands in KB folders mirroring the Feishu tree; shortcut subtrees deduped; sanitized directory names; legacy datasources converge via one-shot resync marker (incremental sync upgrades to full once, then clears) - parse mode: replace FEISHU_DOCX_PARSE_MODE env with per-datasource settings.parse_mode (blocks default, export escape hatch); frontend selector + 5 locales; zero-migration read-time fallback - block-level GFM: extend docx block coverage (callout/grid/iframe/ board/mindnote/agenda/synced blocks), rich text elements (links, inline code, KaTeX equations, mentions), real ordered-list numbering, code language mapping, merged-cell fill, truncation note - embedded objects: images (gated off multimodal toggle) and boards (download_as_image, 403-degraded) stored as knowledge with weknora-img://<n> markers resolved in the document-processing pipeline via knowledge FilePath; document attachments whitelisted (pdf/md/xls(x)/csv/doc(x)/ppt(x)) as standalone knowledge in the parent folder with bidirectional parent/child metadata and filename list in the body; videos skipped with placeholder + source link - golden baseline explicitly re-recorded; docs (.env.example, docker-compose, docs/*, website-docs) synced * fix(datasource): address Feishu deep-adaptation smoke-test findings - folder mapping: drop the space/root-folder name prefix — the selected sync root maps to the knowledge-base root, subdirectories stay relative - docx blocks: render view(33) blocks silently as containers (children only), removing the stray '[飞书块: 视图]' placeholder before file lists - sheet inline tables: fetch merge ranges via sheets/v3 sheets/query and fill the top-left value across the merged region (closed-interval interpretation, flagged for real-environment verification) - knowledge list: hide embedded image/board rows (metadata embedded_image=true) from the document list and folder-tree counts; rows remain for VLM indexing and marker resolution; search untouched - frontend: hydrate protected images (resource:// etc.) in the document preview so embedded Feishu images/boards actually render * fix(datasource): resolve embedded image markers at ingest time The weknora-img://<n> markers were only resolved during document processing, so chunks carried real resource:// URLs while the stored markdown file and source_content kept raw markers — file preview showed blank images. Resolve them in ingestItem before CreateKnowledgeFromFile (children are emitted first, so image rows with FilePath already exist); markers with missing children are kept for the ProcessDocument fallback to degrade. Stored file, source_content and chunks now agree. Existing datasources converge on the next full re-sync (update=delete+recreate). * feat(datasource): resolve Feishu mention users to real names at ingest docx mention_user elements only carry an open_id, so they rendered as a generic '@成员'. Resolve the display name via GET /contact/v3/users/:id (user_id_type=open_id) while generating the markdown during FetchDocxWithBlocks — before storage, per user decision; the frontend performs no lookups. A per-sync closure caches positive and negative lookups; permission errors and empty names silently degrade to '@成员' (debug log only, ingest never blocked). Requires one of the contact read scopes (e.g. contact:user.base:readonly) on the Feishu app. * refactor(datasource): polish round — defect fixes and structural cleanup - attachment placeholder patching now targets the unique '- weknora-att://<token>' marker line rendered per attachment instead of matching by display name, so an identical earlier bullet is never replaced by mistake (regression-tested) - markdown link targets with spaces or parens are percent-escaped (iframe / mention_doc / inline links), keeping them parseable - drive folder-tree walking consolidated into core.WalkDriveTree, deleting the 174-line copy in drive/paths.go - parse mode threading made explicit: DocxFetchInput.ParseMode replaces the private client field (connector entry resolves via ParseFeishuConfig and passes it through ops) - maxFeishuDownloadBytes restored to a const; the oversize-degrade test now declares an over-cap Content-Length and downloadRawBytes rejects early on the header * refactor(datasource): align Feishu image handling with the platform image pipeline Replace the image-as-separate-knowledge-row channel with the platform's orthodox flow: the connector downloads image/board bytes at fetch time and embeds them in the parent markdown as base64 data URIs; the document processing image resolver (image_resolver.ResolveAndStore, the same stage used for parsed PDFs/Word) stores them on the tenant file service, swaps in persistent provider:// URLs and produces OCR/caption child chunks when a VLM is configured. Removed with the marker pipeline: - weknora-img:// ingest resolution in ingestItem - the ProcessDocument Step-1.9 marker hook - the document-list/folder-tree filter for embedded_image rows - the feishu-specific runtime parse_mode backfill; legacy data sources are now stamped by migration 000096 (sqlite 000017) which writes the one-shot resync_required marker — the generic full-upgrade + clear consumption stays Attachment (PDF/Word/md) sub-items are unchanged. * style: gofmt test files * fix(datasource): resolve Drive sub-selection kind from the root listing A single-file Drive selection (rootFolderToken:fileToken) was probed with folder APIs before falling back: folder meta returned 91202 and the folder list 1061002 on every sync, logging API errors for a working configuration. listDriveFilesForResource now walks the root subtree first and reads the selected node's kind off the listing: a file filters straight out of the already-fetched results (zero error calls), a sub-folder still gets its dedicated walk, and only a token missing from the listing (partial listing / permission edge) keeps the legacy probe + fallback. Also pins sub-folder selection semantics with a dedicated test. * fix(datasource): address review findings across the Feishu deep-adaptation branch Four parallel reviewer slices audited the branch; this applies the accepted findings. Content fidelity (blocks rendering): - todo blocks parse style.done — completed items render "- [x]" instead of always unchecked - code fences size past the longest backtick run in the content, so a line of ``` inside code can no longer close the fence early - ordered-list "auto" numbering only resets on a sibling of the last item; child blocks rendered flat between items no longer renumber the run Image pipeline: - inline base64 images are capped at the document-processing resolver's 10 MB budget; larger images degrade to a placeholder instead of leaving a permanent raw-base64 blob in stored markdown - image markers carry a per-document nonce so user-typed look-alike text can never be patched in place of a real marker - attachment marker patching anchors on the token's line end, closing the token-prefix collision - SupportedImageExt recovers image/svg+xml (board exports), which the platform resolver already stores natively Sync correctness: - clearResyncMarker re-reads the row before writing: a long upgraded sync no longer risks reverting concurrent user edits with a stale full-row update - wiki EditTime keys on max(obj_edit_time, node_edit_time): pure moves/renames re-file the document on the next incremental sync - file-typed wiki/drive base names are sanitised; a "/" in a title can no longer fake an extra folder level Docs/tests/comments: - datasources docs rewritten to the v3 image contract (no image rows, no image_map, no parse_mode backfill claim) - DataSourceEditorDialog drops settings.parse_mode when backtracking to a non-Feishu connector type - stale comments corrected (types.go parse-mode transport, repository folder-counts, wiki List partial-error branch, test headers); regression tests added for todo done, fence sizing, ordered numbering, svg sniff * fix(datasource): repair markdown conversion defects found in live smoke test Live re-sync of the all-block-type Feishu test document surfaced three converter defects: - Code blocks: the closing fence reused the opening fence string, so a tagged block ended with ```java — CommonMark requires a bare closing fence, and every renderer left the block unterminated. The closing fence is now backticks only. - Feishu heading7-9 emitted 7-9 hash marks; GFM stops at H6, so those lines rendered as literal '#######' text. They now degrade to bold. - The docx API percent-encodes link targets (http%3A%2F%2F...); escapeURL now reverses that encoding before markdown-escaping, so stored links point at real URLs instead of percent-encoded strings. Verified against the live document via a throwaway API probe: the 'i|g|k' table cells questioned during review are the document's own content (the sheets copy says i|j|k; the two docx tables genuinely contain 'g'), not a converter bug. * fix(frontend): render GFM task lists in document preview Task list items (- [x] / - [ ]) rendered as plain bullets: marked emits <input type="checkbox"> for them, but the preview DOMPurify config's ALLOWED_TAGS allowlist has no 'input', so the element was stripped whole. The preview renderer now overrides checkbox to emit a styled task-checkbox span (class/attr both allowlisted) and the preview styles draw the box with a check mark, hiding the list bullet via :has(). Same gap exists in the chat markdown surface; left untouched there. * fix(datasource): crop blank canvas borders from whiteboard exports The board download_as_image API renders the WHOLE board canvas, not the content bounding box — editors routinely leave the canvas far larger than the drawing, so board/mindnote/diagram exports surfaced with large blank areas below the content. The API has no crop parameter, so the connector now trims near-uniform blank borders after download (bottom-right pixel seeds the background color, 14/255 per-channel tolerance absorbs JPEG noise, 8px margin kept). PNG and JPEG are re-encoded; anything undecodable, fully blank, or already tight passes through unchanged, and oversized images (>64MP) skip the scan to bound memory. * fix(datasource): require corner majority before trimming board exports The blank-border trim seeded the background color from the bottom-right pixel alone. A large solid shape reaching that corner would seed the background with its own fill color, and fully-filled rows could then be trimmed as blank — cutting real content. The background color is now the majority of the four corner pixels (>=3 must agree); on a split vote content reaches the corners and the image passes through untrimmed. Content visible against the background is untouched either way: a row or column survives if even one pixel differs from the background by more than the 14/255 JPEG-noise tolerance. * fix(datasource): widen board trim margin and lower JPEG quality to 80 The 8px margin read as a tight crop — a 32px white frame now visually bounds the content region. JPEG re-encode quality drops 90 -> 80 to keep the re-encoded size closer to the original export. * feat(datasource): timeline widget Markdown degradation + table column alignment Two content-fidelity gaps from the live smoke test: - 文档小组件 (add_ons, block_type 40) carry their full data inline in record; there is no server-side render to download. The timeline component (component_type_id blk_6358a421bca0001c...) now degrades to a Markdown list (- **time · title**:text), honoring contentShow and omitting empty segments; unknown component types and malformed records keep the previous placeholder note. - docx text blocks carry style.align (1 left / 2 center / 3 right, absent unless the author set it). Native-table rendering now collects per-column alignment from the first explicit cell and emits GFM colon separators (:---: / ---:). Embedded sheets/bitable keep the plain separator — their value APIs expose no alignment. * feat(datasource): show document titles for 云文档 mention links The docx renderer emitted mention_doc references as [url](url) because the payload carries no title. Feishu doc URLs now emit a [weknora-docname://token](url) placeholder and FetchDocxWithBlocks resolves the titles in one drive metadata batch call (POST /drive/v1/metas/batch_query, docx/doc/sheet/bitable/wiki/...), patching the link text to [文档名](url). Refs whose metadata cannot be fetched — no permission (970003), deleted/mismatched (970005), API absent — degrade to the previous URL-as-text form with a warn log. This is display-only: referenced docs are not pulled as sub-documents (deferred design lives in the task PRD). * docs(datasource): document mention rendering enhancement and drive rename limitation - Add optional mention scopes (contact:user.base:readonly, drive:drive.metadata:readonly, board:whiteboard:node:read) with degrade behavior to the Feishu permission tables - Describe mention_user real-name lookup, mention_doc title backfill and timeline widget placeholders in the blocks rendering flow - Document the Drive known limitation: folder renames / file moves do not bump modified_time, so incremental sync keeps the old KB folder structure until a full sync; Wiki sources are unaffected - Clarify the directory-mapping wording in website-docs to distinguish Wiki (rename-aware) from Drive (rename-blind) sources * docs(datasource): add blocks vs export tradeoff summary to website-docs * docs(datasource): document docx block-type coverage for blocks mode - Add a full block-type support table (block_type 1-52 grouped) to the datasource dev doc: text/heading/list/task/quote structures, code fences with language aliases, containers (callout/quote/grid/view), native tables with merged-cell splitting (top-left value fill) and column alignment, embedded sheet/bitable converted to in-document Markdown tables, image/board inline pipeline, attachment whitelist, iframe links, timeline add-on degradation and the placeholder set - Summarize the same coverage in the drive user guide, the wiki quick-start doc and website-docs; fix the stale claim that board blocks degrade to placeholders (they ride the image pipeline now) * style: resolve diff-scoped lint findings across feishu packages - Wrap over-length signatures and calls (lll, max 120) - Add doc comments to exported Block* payload types (revive) - Rename unused closure parameters to _ (revive) - Check w.Write / resp.Body.Close error returns (errcheck) - Apply De Morgan rewrite in docname token validation (staticcheck) - gofumpt-format touched files golangci-lint run --new-from-rev=main ./... now reports 0 issues. * ci: drop fork-only docker-build workflow The manual docker-build workflow lives on the fork's main and is not part of the upstream contribution; it entered the branch through the fork-main merge. * fix(migrations): renumber feishu resync migrations to avoid version collision with upstream Upstream added 000017_dingtalk_stream_only (sqlite) and 000096_dingtalk_stream_only (versioned) before our merge, colliding with our 000017/000096 feishu resync migrations. golang-migrate rejects duplicate versions. Renumber to the next free slots (sqlite 000027, versioned 000108) and update comments + test constant. * fix(migrations): renumber feishu resync migrations ahead of upstream 000027/000108 Upstream main now also claims sqlite 000027 and versioned 000108 (session_sandbox_config_tenant), colliding with our just-renumbered resync migrations. Move to 000028 / 000109. * fix(feishu): address review — deprecated env fallback and upgrade notes - Keep FEISHU_DOCX_PARSE_MODE as a one-release deprecated fallback when a data source has no per-source parse_mode (deprecation warning logged); annotate it in .env.example / docker-compose.yml instead of removing. - Point stale migration-number comments at the final numbers (versioned 000110 / sqlite 000030) in datasource_service.go and tests. - website-docs: add Feishu upgrade notes (env deprecation, default mode flip to blocks, one-shot full resync with embedding/VLM recompute); refresh 24-feishu-drive.md parse-mode section to the per-source setting and new blocks semantics. * docs(feishu): document necessary and optional connector permissions Restore the permission matrix lost with the docs/ removal: necessary scopes (wiki/drive/export/docx) with missing-permission symptoms and optional enhancement scopes (embedded sheets/bitable, board export, mention user/doc rendering) with their degrade behavior, in 10-datasource.md's Feishu section; make 24-feishu-drive.md list the three necessary drive scopes and link to the full table. * Revert "docs(feishu): document necessary and optional connector permissions" This reverts commit 3be19cb1b656b3596f2cb6afb2cda8c2a1d12be1. * docs(feishu): permission matrix by connector, parse mode and necessity Necessary-scope tables split by connector (feishu/lark wiki vs feishu_drive/lark_drive) with blocks/export applicability columns and missing-permission symptoms; optional enhancement scopes with their degrade behavior; scope names cross-checked against the Feishu open platform API docs (files/folder list, medias download, export tasks, metas batch_query). Full matrix lives in 10-datasource.md; the drive guide mirrors its own table and links back. * test(feishu): adapt mention_user_test to upstream retryTestServer signature * feat(feishu): mirror the sync root (wiki space / drive folder) as a top-level KB folder So a knowledge base linking several feishu sources can tell them apart at a glance: syncing folder 测试1 yields 测试1/... and syncing wiki space 飞书知识库同步测试 yields 飞书知识库同步测试/.... Root-name resolution failure falls back to the previous root-less behaviour without failing the sync; existing sources converge through the one-shot resync marker. * refactor(feishu): cache wiki space folder prefix per run, refresh stale comments Review follow-ups for d012e593f: cache the sanitized space prefix per spaceID for the whole sync run (K selected spaces now cost one ListWikiSpaces paging pass instead of K), fix the misleading warn wording, and realign the WalkDriveTree / driveFolderName doc comments with root-mirror semantics. * docs(feishu): drop stale and duplicated comments from the deep-adaptation - board.go: trimBoardImage no longer claims a bottom-right seed (the code votes the background over the four corners) - shared.go: rewrite the FetchDocxWithBlocks note (images/boards inline via base64 now; removes a stale-marker splice artefact) - markdown.go: drop an internal task-number leftover - datasource_service.go: collapse the ProcessSync/processSyncStreaming notes duplicated verbatim from resyncRequired's doc comment, keep the call-site why (marker cleared only on success) - datasource_resync_test.go: drop the obsolete 'backfill' wording * feat(i18n): 添加解析模式及其提示信息到繁體中文語言包 * fix(frontend): use radius token for task checkbox; fix simplified chars in zh-TW parse mode CI guard fixes: the PR-added task-checkbox style pushed the radius-literal count to 161 (> baseline 160); the new zh-TW keys missed the locale parity audit (user's dc6fdcff9) — also normalise the simplified 文档 leftovers. * fix(feishu): preserve sync scope, nested content, and legacy settings Cover shortcut selection, ancestor path changes, nested containers and table boards with regression tests. Avoid redundant Drive traversal, repair resync migrations for legacy settings, and preserve inherited parse modes. Bound board image dimensions before decoding. * docs(feishu): clarify shortcut scope and incremental path tracking * Fix Feishu sync reconciliation and embedded media regressions * Bound Feishu table rendering by actual cell data --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-16 08:49:44 +00:00
if processed >= types.MaxInlineDocumentImages {
break
}
m := matches[i]
if len(m) < 6 {
continue
}
dataURI := markdown[m[4]:m[5]]
mimeType, payload, ok := parseImageDataURI(dataURI)
if !ok {
continue
}
payload = cleanBase64Payload(payload)
if payload == "" {
continue
}
data, decErr := decodeBase64Flexible(payload)
if decErr != nil {
log.Printf("WARN: data URI base64 decode failed: %v", decErr)
continue
}
if len(data) > maxRemoteImageSize {
log.Printf("WARN: data URI image exceeds size limit (%d bytes)", maxRemoteImageSize)
continue
}
if isIconImage(data) {
markdown = markdown[:m[0]] + markdown[m[1]:]
continue
}
ext := extFromMime(mimeType)
if ext == "" {
ext = ".png"
}
fileName := uuid.New().String() + ext
servingURL, saveErr := fileSvc.SaveBytes(ctx, data, tenantID, fileName, false)
if saveErr != nil {
log.Printf("WARN: failed to save data URI image: %v", saveErr)
continue
}
images = append(images, StoredImage{
OriginalRef: dataURI,
ServingURL: servingURL,
MimeType: mimeType,
})
markdown = markdown[:m[4]] + servingURL + markdown[m[5]:]
processed++
}
return markdown, images, nil
}
fix(docparser): resolve remote images referenced by HTML img tags (#2355) Remote http(s) images written as <img src="..."> reached no resolver. Markdown images went through ResolveRemoteImages, HTML data-URIs and HTML relative paths each had their own pass, but nothing claimed the remaining combination, so those images were dropped without a log line and the multimodal stage was skipped for documents that rely on HTML for layout. ResolveRemoteImages now scans HTML img tags with a quoted src as a second pass and rewrites only the src attribute value, leaving the tag intact because the surrounding markup is why these documents use HTML at all. The per-image work (whitelist, SSRF, download, icon filter, upload) moves into one helper so the two syntaxes cannot drift apart on policy. Each pass carries its own image budget; sharing one would let HTML images eat into the number of Markdown images a document already gets resolved. An attribute value is trimmed, HTML-unescaped and its scheme lowercased before use, because HTML permits padding, spells a query separator &amp; and tolerates any scheme case, while every fetcher downstream compares the scheme byte-for-byte. Markdown targets get none of that normalization, so no Markdown reference resolves differently than it does today. A whitelisted host keeps serving the image from where it already lives, and its span is rewritten with the normalized URL rather than the raw attribute text: later stages both locate the image by searching the document for its serving URL and fetch that same string, so the two have to agree. The src attribute must now be preceded by whitespace, so a hyphenated attribute name is no longer mistaken for it. Among HTML tags this cuts two ways: one carrying both a hyphenated *-src and a real src now resolves the real src instead of the placeholder, while one carrying only a hyphenated *-src is no longer resolved at all. Recovering the latter needs an attribute parser rather than a regex, and resolving a lazy-loading placeholder while the real image goes unvisited is the worse of the two failures. Both halves are pinned by tests. Image-derived text also has to survive into the answer, which is why this touches internal/searchutil. The chat enricher and the image_info filters matched Markdown links only, so an HTML-only passage looked image-free: every entry was dropped and the model received bare markup with the caption and OCR text stripped, even though the analysis had run. Both now recognise HTML img tags through one shared regex, so a tag the parser stores can always be matched back. Both syntaxes are located against the original passage and spliced in a single pass; scanning one regex over the other's output let a metadata block that itself quotes an image reference be rescanned and duplicated. The chat variant still enriches only images present in the passage, so orphan entries stay out. Known limits: - An unquoted src and a srcset-only tag are not matched, nor is a tag whose attribute values hold a bare > or a quoted src= of their own. - imgHTMLDataURI still matches src without a boundary, so a data-src holding a base64 placeholder is consumed as if it were the src and the whole tag replaced. Worth the same fix, but it changes what an existing lazy-loading document resolves, so it belongs on its own. - A reference shown as a documentation example is rewritten like any other. Recognising code spans needs a Markdown parser; a hand-rolled scanner risks the far worse failure of treating a document's real screenshots as examples. - Rewriting a whitelisted src writes the unescaped URL back into an HTML attribute, so a query parameter whose name spells an entity renders differently than the author wrote it. Keeping the encoded form would mean unescaping on every matcher instead. - Image text reaches the model only when the whole reference falls inside the retrieved window; an img tag is several times longer than a Markdown link and straddles a chunk boundary more often. - A reference repeated in one document is fetched once per occurrence, which is what gives each chunk its own analysed copy. - Nothing bounds how long one document's fetches may take in total. - Parent-context pruning removes only Markdown images. Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-07-28 13:08:31 +00:00
// errRemoteImageIsIcon marks the one skip reason worth aggregating: a page can
// carry hundreds of tracking pixels and spacer GIFs, and a line for each would
// drown the reasons an operator actually needs to see.
var errRemoteImageIsIcon = errors.New("filtered out as icon")
// remoteImageResult describes one image that was fetched successfully.
type remoteImageResult struct {
// ServingURL is empty when KeepOriginalURL is set. The caller fills it in
// with the normalized request URL — NOT the raw document bytes. Later stages
// both search the document for this string and fetch it, so a padded or
// entity-encoded value satisfies neither.
ServingURL string
MimeType string
// KeepOriginalURL marks a whitelisted host. Its bytes are downloaded so that
// OCR/caption analysis can run, but it is not uploaded: the image keeps being
// served from its original host, reached through the normalized URL.
KeepOriginalURL bool
}
// fetchAndStoreRemoteImage applies the SSRF policy, downloads the image,
// rejects icons and uploads the bytes to storage.
//
fix(docparser): resolve remote images referenced by HTML img tags (#2355) Remote http(s) images written as <img src="..."> reached no resolver. Markdown images went through ResolveRemoteImages, HTML data-URIs and HTML relative paths each had their own pass, but nothing claimed the remaining combination, so those images were dropped without a log line and the multimodal stage was skipped for documents that rely on HTML for layout. ResolveRemoteImages now scans HTML img tags with a quoted src as a second pass and rewrites only the src attribute value, leaving the tag intact because the surrounding markup is why these documents use HTML at all. The per-image work (whitelist, SSRF, download, icon filter, upload) moves into one helper so the two syntaxes cannot drift apart on policy. Each pass carries its own image budget; sharing one would let HTML images eat into the number of Markdown images a document already gets resolved. An attribute value is trimmed, HTML-unescaped and its scheme lowercased before use, because HTML permits padding, spells a query separator &amp; and tolerates any scheme case, while every fetcher downstream compares the scheme byte-for-byte. Markdown targets get none of that normalization, so no Markdown reference resolves differently than it does today. A whitelisted host keeps serving the image from where it already lives, and its span is rewritten with the normalized URL rather than the raw attribute text: later stages both locate the image by searching the document for its serving URL and fetch that same string, so the two have to agree. The src attribute must now be preceded by whitespace, so a hyphenated attribute name is no longer mistaken for it. Among HTML tags this cuts two ways: one carrying both a hyphenated *-src and a real src now resolves the real src instead of the placeholder, while one carrying only a hyphenated *-src is no longer resolved at all. Recovering the latter needs an attribute parser rather than a regex, and resolving a lazy-loading placeholder while the real image goes unvisited is the worse of the two failures. Both halves are pinned by tests. Image-derived text also has to survive into the answer, which is why this touches internal/searchutil. The chat enricher and the image_info filters matched Markdown links only, so an HTML-only passage looked image-free: every entry was dropped and the model received bare markup with the caption and OCR text stripped, even though the analysis had run. Both now recognise HTML img tags through one shared regex, so a tag the parser stores can always be matched back. Both syntaxes are located against the original passage and spliced in a single pass; scanning one regex over the other's output let a metadata block that itself quotes an image reference be rescanned and duplicated. The chat variant still enriches only images present in the passage, so orphan entries stay out. Known limits: - An unquoted src and a srcset-only tag are not matched, nor is a tag whose attribute values hold a bare > or a quoted src= of their own. - imgHTMLDataURI still matches src without a boundary, so a data-src holding a base64 placeholder is consumed as if it were the src and the whole tag replaced. Worth the same fix, but it changes what an existing lazy-loading document resolves, so it belongs on its own. - A reference shown as a documentation example is rewritten like any other. Recognising code spans needs a Markdown parser; a hand-rolled scanner risks the far worse failure of treating a document's real screenshots as examples. - Rewriting a whitelisted src writes the unescaped URL back into an HTML attribute, so a query parameter whose name spells an entity renders differently than the author wrote it. Keeping the encoded form would mean unescaping on every matcher instead. - Image text reaches the model only when the whole reference falls inside the retrieved window; an img tag is several times longer than a Markdown link and straddles a chunk boundary more often. - A reference repeated in one document is fetched once per occurrence, which is what gives each chunk its own analysed copy. - Nothing bounds how long one document's fetches may take in total. - Parent-context pruning removes only Markdown images. Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-07-28 13:08:31 +00:00
// Both the Markdown and the HTML scan go through here so that the SSRF check,
// the icon filter and the whitelist behaviour cannot drift apart between the
// two syntaxes.
func fetchAndStoreRemoteImage(
ctx context.Context,
client *http.Client,
fileSvc interfaces.FileService,
tenantID uint64,
imgURL string,
) (*remoteImageResult, error) {
whitelisted := isWhitelistedImageHost(imgURL)
if !whitelisted {
if err := secutils.ValidateURLForSSRF(imgURL); err != nil {
return nil, fmt.Errorf("blocked by SSRF policy: %w", err)
}
}
data, mimeType, err := downloadImage(ctx, client, imgURL)
if err != nil {
return nil, fmt.Errorf("download: %w", err)
}
if isIconImage(data) {
return nil, errRemoteImageIsIcon
}
if whitelisted {
return &remoteImageResult{MimeType: mimeType, KeepOriginalURL: true}, nil
}
ext := extFromMime(mimeType)
if ext == "" {
ext = extFromURLPath(imgURL)
}
if ext == "" {
ext = ".png" // safe default
}
servingURL, err := fileSvc.SaveBytes(ctx, data, tenantID, uuid.New().String()+ext, false)
if err != nil {
return nil, fmt.Errorf("save: %w", err)
}
return &remoteImageResult{ServingURL: servingURL, MimeType: mimeType}, nil
}
// isRemoteHTTPURL reports whether raw is an absolute http(s) URL.
//
fix(docparser): resolve remote images referenced by HTML img tags (#2355) Remote http(s) images written as <img src="..."> reached no resolver. Markdown images went through ResolveRemoteImages, HTML data-URIs and HTML relative paths each had their own pass, but nothing claimed the remaining combination, so those images were dropped without a log line and the multimodal stage was skipped for documents that rely on HTML for layout. ResolveRemoteImages now scans HTML img tags with a quoted src as a second pass and rewrites only the src attribute value, leaving the tag intact because the surrounding markup is why these documents use HTML at all. The per-image work (whitelist, SSRF, download, icon filter, upload) moves into one helper so the two syntaxes cannot drift apart on policy. Each pass carries its own image budget; sharing one would let HTML images eat into the number of Markdown images a document already gets resolved. An attribute value is trimmed, HTML-unescaped and its scheme lowercased before use, because HTML permits padding, spells a query separator &amp; and tolerates any scheme case, while every fetcher downstream compares the scheme byte-for-byte. Markdown targets get none of that normalization, so no Markdown reference resolves differently than it does today. A whitelisted host keeps serving the image from where it already lives, and its span is rewritten with the normalized URL rather than the raw attribute text: later stages both locate the image by searching the document for its serving URL and fetch that same string, so the two have to agree. The src attribute must now be preceded by whitespace, so a hyphenated attribute name is no longer mistaken for it. Among HTML tags this cuts two ways: one carrying both a hyphenated *-src and a real src now resolves the real src instead of the placeholder, while one carrying only a hyphenated *-src is no longer resolved at all. Recovering the latter needs an attribute parser rather than a regex, and resolving a lazy-loading placeholder while the real image goes unvisited is the worse of the two failures. Both halves are pinned by tests. Image-derived text also has to survive into the answer, which is why this touches internal/searchutil. The chat enricher and the image_info filters matched Markdown links only, so an HTML-only passage looked image-free: every entry was dropped and the model received bare markup with the caption and OCR text stripped, even though the analysis had run. Both now recognise HTML img tags through one shared regex, so a tag the parser stores can always be matched back. Both syntaxes are located against the original passage and spliced in a single pass; scanning one regex over the other's output let a metadata block that itself quotes an image reference be rescanned and duplicated. The chat variant still enriches only images present in the passage, so orphan entries stay out. Known limits: - An unquoted src and a srcset-only tag are not matched, nor is a tag whose attribute values hold a bare > or a quoted src= of their own. - imgHTMLDataURI still matches src without a boundary, so a data-src holding a base64 placeholder is consumed as if it were the src and the whole tag replaced. Worth the same fix, but it changes what an existing lazy-loading document resolves, so it belongs on its own. - A reference shown as a documentation example is rewritten like any other. Recognising code spans needs a Markdown parser; a hand-rolled scanner risks the far worse failure of treating a document's real screenshots as examples. - Rewriting a whitelisted src writes the unescaped URL back into an HTML attribute, so a query parameter whose name spells an entity renders differently than the author wrote it. Keeping the encoded form would mean unescaping on every matcher instead. - Image text reaches the model only when the whole reference falls inside the retrieved window; an img tag is several times longer than a Markdown link and straddles a chunk boundary more often. - A reference repeated in one document is fetched once per occurrence, which is what gives each chunk its own analysed copy. - Nothing bounds how long one document's fetches may take in total. - Parent-context pruning removes only Markdown images. Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-07-28 13:08:31 +00:00
// The comparison is deliberately byte-exact. Downstream fetchers compare the
// scheme the same way, so anything accepted here has to be spelled the way they
// expect; per-syntax normalization belongs in the SrcOf of the scan that needs
// it, not in this predicate.
func isRemoteHTTPURL(raw string) bool {
return strings.HasPrefix(raw, "http://") || strings.HasPrefix(raw, "https://")
}
// remotePassSpec describes one scan of a document: which references it matches,
// where the URL sits inside a match, and how to turn the raw document bytes into
// the URL to request.
type remotePassSpec struct {
Pattern *regexp.Regexp
URLGroup int
Syntax string
SrcOf func(string) string
}
// remotePassStats accumulates the reasons a scan passed a reference over, so
// that a partially resolved document can be explained afterwards.
type remotePassStats struct {
resolved int
iconSkips int
overBudget int
}
func (s *remotePassStats) report(syntax string) {
if s.iconSkips > 0 {
log.Printf("INFO: skipped %d %s remote image(s) as icons", s.iconSkips, syntax)
}
if s.overBudget > 0 {
log.Printf(
"WARN: remote image limit of %d reached for %s images; %d reference(s) left unresolved",
maxRemoteImages, syntax, s.overBudget,
)
}
}
// resolveRemoteImagePass rewrites every remote http(s) reference matched by
// spec.Pattern, replacing the span of its URL capture group with the URL the
// image will be served from: the storage URL, or the normalized original for a
// whitelisted host. Matches are walked in reverse so the spans still to be
// processed stay valid after each replacement.
func resolveRemoteImagePass(
ctx context.Context,
markdown string,
fix(docparser): resolve remote images referenced by HTML img tags (#2355) Remote http(s) images written as <img src="..."> reached no resolver. Markdown images went through ResolveRemoteImages, HTML data-URIs and HTML relative paths each had their own pass, but nothing claimed the remaining combination, so those images were dropped without a log line and the multimodal stage was skipped for documents that rely on HTML for layout. ResolveRemoteImages now scans HTML img tags with a quoted src as a second pass and rewrites only the src attribute value, leaving the tag intact because the surrounding markup is why these documents use HTML at all. The per-image work (whitelist, SSRF, download, icon filter, upload) moves into one helper so the two syntaxes cannot drift apart on policy. Each pass carries its own image budget; sharing one would let HTML images eat into the number of Markdown images a document already gets resolved. An attribute value is trimmed, HTML-unescaped and its scheme lowercased before use, because HTML permits padding, spells a query separator &amp; and tolerates any scheme case, while every fetcher downstream compares the scheme byte-for-byte. Markdown targets get none of that normalization, so no Markdown reference resolves differently than it does today. A whitelisted host keeps serving the image from where it already lives, and its span is rewritten with the normalized URL rather than the raw attribute text: later stages both locate the image by searching the document for its serving URL and fetch that same string, so the two have to agree. The src attribute must now be preceded by whitespace, so a hyphenated attribute name is no longer mistaken for it. Among HTML tags this cuts two ways: one carrying both a hyphenated *-src and a real src now resolves the real src instead of the placeholder, while one carrying only a hyphenated *-src is no longer resolved at all. Recovering the latter needs an attribute parser rather than a regex, and resolving a lazy-loading placeholder while the real image goes unvisited is the worse of the two failures. Both halves are pinned by tests. Image-derived text also has to survive into the answer, which is why this touches internal/searchutil. The chat enricher and the image_info filters matched Markdown links only, so an HTML-only passage looked image-free: every entry was dropped and the model received bare markup with the caption and OCR text stripped, even though the analysis had run. Both now recognise HTML img tags through one shared regex, so a tag the parser stores can always be matched back. Both syntaxes are located against the original passage and spliced in a single pass; scanning one regex over the other's output let a metadata block that itself quotes an image reference be rescanned and duplicated. The chat variant still enriches only images present in the passage, so orphan entries stay out. Known limits: - An unquoted src and a srcset-only tag are not matched, nor is a tag whose attribute values hold a bare > or a quoted src= of their own. - imgHTMLDataURI still matches src without a boundary, so a data-src holding a base64 placeholder is consumed as if it were the src and the whole tag replaced. Worth the same fix, but it changes what an existing lazy-loading document resolves, so it belongs on its own. - A reference shown as a documentation example is rewritten like any other. Recognising code spans needs a Markdown parser; a hand-rolled scanner risks the far worse failure of treating a document's real screenshots as examples. - Rewriting a whitelisted src writes the unescaped URL back into an HTML attribute, so a query parameter whose name spells an entity renders differently than the author wrote it. Keeping the encoded form would mean unescaping on every matcher instead. - Image text reaches the model only when the whole reference falls inside the retrieved window; an img tag is several times longer than a Markdown link and straddles a chunk boundary more often. - A reference repeated in one document is fetched once per occurrence, which is what gives each chunk its own analysed copy. - Nothing bounds how long one document's fetches may take in total. - Parent-context pruning removes only Markdown images. Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-07-28 13:08:31 +00:00
spec remotePassSpec,
client func() *http.Client,
fileSvc interfaces.FileService,
tenantID uint64,
fix(docparser): resolve remote images referenced by HTML img tags (#2355) Remote http(s) images written as <img src="..."> reached no resolver. Markdown images went through ResolveRemoteImages, HTML data-URIs and HTML relative paths each had their own pass, but nothing claimed the remaining combination, so those images were dropped without a log line and the multimodal stage was skipped for documents that rely on HTML for layout. ResolveRemoteImages now scans HTML img tags with a quoted src as a second pass and rewrites only the src attribute value, leaving the tag intact because the surrounding markup is why these documents use HTML at all. The per-image work (whitelist, SSRF, download, icon filter, upload) moves into one helper so the two syntaxes cannot drift apart on policy. Each pass carries its own image budget; sharing one would let HTML images eat into the number of Markdown images a document already gets resolved. An attribute value is trimmed, HTML-unescaped and its scheme lowercased before use, because HTML permits padding, spells a query separator &amp; and tolerates any scheme case, while every fetcher downstream compares the scheme byte-for-byte. Markdown targets get none of that normalization, so no Markdown reference resolves differently than it does today. A whitelisted host keeps serving the image from where it already lives, and its span is rewritten with the normalized URL rather than the raw attribute text: later stages both locate the image by searching the document for its serving URL and fetch that same string, so the two have to agree. The src attribute must now be preceded by whitespace, so a hyphenated attribute name is no longer mistaken for it. Among HTML tags this cuts two ways: one carrying both a hyphenated *-src and a real src now resolves the real src instead of the placeholder, while one carrying only a hyphenated *-src is no longer resolved at all. Recovering the latter needs an attribute parser rather than a regex, and resolving a lazy-loading placeholder while the real image goes unvisited is the worse of the two failures. Both halves are pinned by tests. Image-derived text also has to survive into the answer, which is why this touches internal/searchutil. The chat enricher and the image_info filters matched Markdown links only, so an HTML-only passage looked image-free: every entry was dropped and the model received bare markup with the caption and OCR text stripped, even though the analysis had run. Both now recognise HTML img tags through one shared regex, so a tag the parser stores can always be matched back. Both syntaxes are located against the original passage and spliced in a single pass; scanning one regex over the other's output let a metadata block that itself quotes an image reference be rescanned and duplicated. The chat variant still enriches only images present in the passage, so orphan entries stay out. Known limits: - An unquoted src and a srcset-only tag are not matched, nor is a tag whose attribute values hold a bare > or a quoted src= of their own. - imgHTMLDataURI still matches src without a boundary, so a data-src holding a base64 placeholder is consumed as if it were the src and the whole tag replaced. Worth the same fix, but it changes what an existing lazy-loading document resolves, so it belongs on its own. - A reference shown as a documentation example is rewritten like any other. Recognising code spans needs a Markdown parser; a hand-rolled scanner risks the far worse failure of treating a document's real screenshots as examples. - Rewriting a whitelisted src writes the unescaped URL back into an HTML attribute, so a query parameter whose name spells an entity renders differently than the author wrote it. Keeping the encoded form would mean unescaping on every matcher instead. - Image text reaches the model only when the whole reference falls inside the retrieved window; an img tag is several times longer than a Markdown link and straddles a chunk boundary more often. - A reference repeated in one document is fetched once per occurrence, which is what gives each chunk its own analysed copy. - Nothing bounds how long one document's fetches may take in total. - Parent-context pruning removes only Markdown images. Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-07-28 13:08:31 +00:00
) (string, []StoredImage) {
matches := spec.Pattern.FindAllStringSubmatchIndex(markdown, -1)
if len(matches) == 0 {
fix(docparser): resolve remote images referenced by HTML img tags (#2355) Remote http(s) images written as <img src="..."> reached no resolver. Markdown images went through ResolveRemoteImages, HTML data-URIs and HTML relative paths each had their own pass, but nothing claimed the remaining combination, so those images were dropped without a log line and the multimodal stage was skipped for documents that rely on HTML for layout. ResolveRemoteImages now scans HTML img tags with a quoted src as a second pass and rewrites only the src attribute value, leaving the tag intact because the surrounding markup is why these documents use HTML at all. The per-image work (whitelist, SSRF, download, icon filter, upload) moves into one helper so the two syntaxes cannot drift apart on policy. Each pass carries its own image budget; sharing one would let HTML images eat into the number of Markdown images a document already gets resolved. An attribute value is trimmed, HTML-unescaped and its scheme lowercased before use, because HTML permits padding, spells a query separator &amp; and tolerates any scheme case, while every fetcher downstream compares the scheme byte-for-byte. Markdown targets get none of that normalization, so no Markdown reference resolves differently than it does today. A whitelisted host keeps serving the image from where it already lives, and its span is rewritten with the normalized URL rather than the raw attribute text: later stages both locate the image by searching the document for its serving URL and fetch that same string, so the two have to agree. The src attribute must now be preceded by whitespace, so a hyphenated attribute name is no longer mistaken for it. Among HTML tags this cuts two ways: one carrying both a hyphenated *-src and a real src now resolves the real src instead of the placeholder, while one carrying only a hyphenated *-src is no longer resolved at all. Recovering the latter needs an attribute parser rather than a regex, and resolving a lazy-loading placeholder while the real image goes unvisited is the worse of the two failures. Both halves are pinned by tests. Image-derived text also has to survive into the answer, which is why this touches internal/searchutil. The chat enricher and the image_info filters matched Markdown links only, so an HTML-only passage looked image-free: every entry was dropped and the model received bare markup with the caption and OCR text stripped, even though the analysis had run. Both now recognise HTML img tags through one shared regex, so a tag the parser stores can always be matched back. Both syntaxes are located against the original passage and spliced in a single pass; scanning one regex over the other's output let a metadata block that itself quotes an image reference be rescanned and duplicated. The chat variant still enriches only images present in the passage, so orphan entries stay out. Known limits: - An unquoted src and a srcset-only tag are not matched, nor is a tag whose attribute values hold a bare > or a quoted src= of their own. - imgHTMLDataURI still matches src without a boundary, so a data-src holding a base64 placeholder is consumed as if it were the src and the whole tag replaced. Worth the same fix, but it changes what an existing lazy-loading document resolves, so it belongs on its own. - A reference shown as a documentation example is rewritten like any other. Recognising code spans needs a Markdown parser; a hand-rolled scanner risks the far worse failure of treating a document's real screenshots as examples. - Rewriting a whitelisted src writes the unescaped URL back into an HTML attribute, so a query parameter whose name spells an entity renders differently than the author wrote it. Keeping the encoded form would mean unescaping on every matcher instead. - Image text reaches the model only when the whole reference falls inside the retrieved window; an img tag is several times longer than a Markdown link and straddles a chunk boundary more often. - A reference repeated in one document is fetched once per occurrence, which is what gives each chunk its own analysed copy. - Nothing bounds how long one document's fetches may take in total. - Parent-context pruning removes only Markdown images. Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-07-28 13:08:31 +00:00
return markdown, nil
}
fix(docparser): resolve remote images referenced by HTML img tags (#2355) Remote http(s) images written as <img src="..."> reached no resolver. Markdown images went through ResolveRemoteImages, HTML data-URIs and HTML relative paths each had their own pass, but nothing claimed the remaining combination, so those images were dropped without a log line and the multimodal stage was skipped for documents that rely on HTML for layout. ResolveRemoteImages now scans HTML img tags with a quoted src as a second pass and rewrites only the src attribute value, leaving the tag intact because the surrounding markup is why these documents use HTML at all. The per-image work (whitelist, SSRF, download, icon filter, upload) moves into one helper so the two syntaxes cannot drift apart on policy. Each pass carries its own image budget; sharing one would let HTML images eat into the number of Markdown images a document already gets resolved. An attribute value is trimmed, HTML-unescaped and its scheme lowercased before use, because HTML permits padding, spells a query separator &amp; and tolerates any scheme case, while every fetcher downstream compares the scheme byte-for-byte. Markdown targets get none of that normalization, so no Markdown reference resolves differently than it does today. A whitelisted host keeps serving the image from where it already lives, and its span is rewritten with the normalized URL rather than the raw attribute text: later stages both locate the image by searching the document for its serving URL and fetch that same string, so the two have to agree. The src attribute must now be preceded by whitespace, so a hyphenated attribute name is no longer mistaken for it. Among HTML tags this cuts two ways: one carrying both a hyphenated *-src and a real src now resolves the real src instead of the placeholder, while one carrying only a hyphenated *-src is no longer resolved at all. Recovering the latter needs an attribute parser rather than a regex, and resolving a lazy-loading placeholder while the real image goes unvisited is the worse of the two failures. Both halves are pinned by tests. Image-derived text also has to survive into the answer, which is why this touches internal/searchutil. The chat enricher and the image_info filters matched Markdown links only, so an HTML-only passage looked image-free: every entry was dropped and the model received bare markup with the caption and OCR text stripped, even though the analysis had run. Both now recognise HTML img tags through one shared regex, so a tag the parser stores can always be matched back. Both syntaxes are located against the original passage and spliced in a single pass; scanning one regex over the other's output let a metadata block that itself quotes an image reference be rescanned and duplicated. The chat variant still enriches only images present in the passage, so orphan entries stay out. Known limits: - An unquoted src and a srcset-only tag are not matched, nor is a tag whose attribute values hold a bare > or a quoted src= of their own. - imgHTMLDataURI still matches src without a boundary, so a data-src holding a base64 placeholder is consumed as if it were the src and the whole tag replaced. Worth the same fix, but it changes what an existing lazy-loading document resolves, so it belongs on its own. - A reference shown as a documentation example is rewritten like any other. Recognising code spans needs a Markdown parser; a hand-rolled scanner risks the far worse failure of treating a document's real screenshots as examples. - Rewriting a whitelisted src writes the unescaped URL back into an HTML attribute, so a query parameter whose name spells an entity renders differently than the author wrote it. Keeping the encoded form would mean unescaping on every matcher instead. - Image text reaches the model only when the whole reference falls inside the retrieved window; an img tag is several times longer than a Markdown link and straddles a chunk boundary more often. - A reference repeated in one document is fetched once per occurrence, which is what gives each chunk its own analysed copy. - Nothing bounds how long one document's fetches may take in total. - Parent-context pruning removes only Markdown images. Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-07-28 13:08:31 +00:00
var (
images []StoredImage
stats remotePassStats
)
for i := len(matches) - 1; i >= 0; i-- {
m := matches[i]
fix(docparser): resolve remote images referenced by HTML img tags (#2355) Remote http(s) images written as <img src="..."> reached no resolver. Markdown images went through ResolveRemoteImages, HTML data-URIs and HTML relative paths each had their own pass, but nothing claimed the remaining combination, so those images were dropped without a log line and the multimodal stage was skipped for documents that rely on HTML for layout. ResolveRemoteImages now scans HTML img tags with a quoted src as a second pass and rewrites only the src attribute value, leaving the tag intact because the surrounding markup is why these documents use HTML at all. The per-image work (whitelist, SSRF, download, icon filter, upload) moves into one helper so the two syntaxes cannot drift apart on policy. Each pass carries its own image budget; sharing one would let HTML images eat into the number of Markdown images a document already gets resolved. An attribute value is trimmed, HTML-unescaped and its scheme lowercased before use, because HTML permits padding, spells a query separator &amp; and tolerates any scheme case, while every fetcher downstream compares the scheme byte-for-byte. Markdown targets get none of that normalization, so no Markdown reference resolves differently than it does today. A whitelisted host keeps serving the image from where it already lives, and its span is rewritten with the normalized URL rather than the raw attribute text: later stages both locate the image by searching the document for its serving URL and fetch that same string, so the two have to agree. The src attribute must now be preceded by whitespace, so a hyphenated attribute name is no longer mistaken for it. Among HTML tags this cuts two ways: one carrying both a hyphenated *-src and a real src now resolves the real src instead of the placeholder, while one carrying only a hyphenated *-src is no longer resolved at all. Recovering the latter needs an attribute parser rather than a regex, and resolving a lazy-loading placeholder while the real image goes unvisited is the worse of the two failures. Both halves are pinned by tests. Image-derived text also has to survive into the answer, which is why this touches internal/searchutil. The chat enricher and the image_info filters matched Markdown links only, so an HTML-only passage looked image-free: every entry was dropped and the model received bare markup with the caption and OCR text stripped, even though the analysis had run. Both now recognise HTML img tags through one shared regex, so a tag the parser stores can always be matched back. Both syntaxes are located against the original passage and spliced in a single pass; scanning one regex over the other's output let a metadata block that itself quotes an image reference be rescanned and duplicated. The chat variant still enriches only images present in the passage, so orphan entries stay out. Known limits: - An unquoted src and a srcset-only tag are not matched, nor is a tag whose attribute values hold a bare > or a quoted src= of their own. - imgHTMLDataURI still matches src without a boundary, so a data-src holding a base64 placeholder is consumed as if it were the src and the whole tag replaced. Worth the same fix, but it changes what an existing lazy-loading document resolves, so it belongs on its own. - A reference shown as a documentation example is rewritten like any other. Recognising code spans needs a Markdown parser; a hand-rolled scanner risks the far worse failure of treating a document's real screenshots as examples. - Rewriting a whitelisted src writes the unescaped URL back into an HTML attribute, so a query parameter whose name spells an entity renders differently than the author wrote it. Keeping the encoded form would mean unescaping on every matcher instead. - Image text reaches the model only when the whole reference falls inside the retrieved window; an img tag is several times longer than a Markdown link and straddles a chunk boundary more often. - A reference repeated in one document is fetched once per occurrence, which is what gives each chunk its own analysed copy. - Nothing bounds how long one document's fetches may take in total. - Parent-context pruning removes only Markdown images. Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-07-28 13:08:31 +00:00
start, end := m[2*spec.URLGroup], m[2*spec.URLGroup+1]
if start < 0 {
continue
}
fix(docparser): resolve remote images referenced by HTML img tags (#2355) Remote http(s) images written as <img src="..."> reached no resolver. Markdown images went through ResolveRemoteImages, HTML data-URIs and HTML relative paths each had their own pass, but nothing claimed the remaining combination, so those images were dropped without a log line and the multimodal stage was skipped for documents that rely on HTML for layout. ResolveRemoteImages now scans HTML img tags with a quoted src as a second pass and rewrites only the src attribute value, leaving the tag intact because the surrounding markup is why these documents use HTML at all. The per-image work (whitelist, SSRF, download, icon filter, upload) moves into one helper so the two syntaxes cannot drift apart on policy. Each pass carries its own image budget; sharing one would let HTML images eat into the number of Markdown images a document already gets resolved. An attribute value is trimmed, HTML-unescaped and its scheme lowercased before use, because HTML permits padding, spells a query separator &amp; and tolerates any scheme case, while every fetcher downstream compares the scheme byte-for-byte. Markdown targets get none of that normalization, so no Markdown reference resolves differently than it does today. A whitelisted host keeps serving the image from where it already lives, and its span is rewritten with the normalized URL rather than the raw attribute text: later stages both locate the image by searching the document for its serving URL and fetch that same string, so the two have to agree. The src attribute must now be preceded by whitespace, so a hyphenated attribute name is no longer mistaken for it. Among HTML tags this cuts two ways: one carrying both a hyphenated *-src and a real src now resolves the real src instead of the placeholder, while one carrying only a hyphenated *-src is no longer resolved at all. Recovering the latter needs an attribute parser rather than a regex, and resolving a lazy-loading placeholder while the real image goes unvisited is the worse of the two failures. Both halves are pinned by tests. Image-derived text also has to survive into the answer, which is why this touches internal/searchutil. The chat enricher and the image_info filters matched Markdown links only, so an HTML-only passage looked image-free: every entry was dropped and the model received bare markup with the caption and OCR text stripped, even though the analysis had run. Both now recognise HTML img tags through one shared regex, so a tag the parser stores can always be matched back. Both syntaxes are located against the original passage and spliced in a single pass; scanning one regex over the other's output let a metadata block that itself quotes an image reference be rescanned and duplicated. The chat variant still enriches only images present in the passage, so orphan entries stay out. Known limits: - An unquoted src and a srcset-only tag are not matched, nor is a tag whose attribute values hold a bare > or a quoted src= of their own. - imgHTMLDataURI still matches src without a boundary, so a data-src holding a base64 placeholder is consumed as if it were the src and the whole tag replaced. Worth the same fix, but it changes what an existing lazy-loading document resolves, so it belongs on its own. - A reference shown as a documentation example is rewritten like any other. Recognising code spans needs a Markdown parser; a hand-rolled scanner risks the far worse failure of treating a document's real screenshots as examples. - Rewriting a whitelisted src writes the unescaped URL back into an HTML attribute, so a query parameter whose name spells an entity renders differently than the author wrote it. Keeping the encoded form would mean unescaping on every matcher instead. - Image text reaches the model only when the whole reference falls inside the retrieved window; an img tag is several times longer than a Markdown link and straddles a chunk boundary more often. - A reference repeated in one document is fetched once per occurrence, which is what gives each chunk its own analysed copy. - Nothing bounds how long one document's fetches may take in total. - Parent-context pruning removes only Markdown images. Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-07-28 13:08:31 +00:00
imgURL := spec.SrcOf(markdown[start:end])
if !isRemoteHTTPURL(imgURL) {
continue
}
fix(docparser): resolve remote images referenced by HTML img tags (#2355) Remote http(s) images written as <img src="..."> reached no resolver. Markdown images went through ResolveRemoteImages, HTML data-URIs and HTML relative paths each had their own pass, but nothing claimed the remaining combination, so those images were dropped without a log line and the multimodal stage was skipped for documents that rely on HTML for layout. ResolveRemoteImages now scans HTML img tags with a quoted src as a second pass and rewrites only the src attribute value, leaving the tag intact because the surrounding markup is why these documents use HTML at all. The per-image work (whitelist, SSRF, download, icon filter, upload) moves into one helper so the two syntaxes cannot drift apart on policy. Each pass carries its own image budget; sharing one would let HTML images eat into the number of Markdown images a document already gets resolved. An attribute value is trimmed, HTML-unescaped and its scheme lowercased before use, because HTML permits padding, spells a query separator &amp; and tolerates any scheme case, while every fetcher downstream compares the scheme byte-for-byte. Markdown targets get none of that normalization, so no Markdown reference resolves differently than it does today. A whitelisted host keeps serving the image from where it already lives, and its span is rewritten with the normalized URL rather than the raw attribute text: later stages both locate the image by searching the document for its serving URL and fetch that same string, so the two have to agree. The src attribute must now be preceded by whitespace, so a hyphenated attribute name is no longer mistaken for it. Among HTML tags this cuts two ways: one carrying both a hyphenated *-src and a real src now resolves the real src instead of the placeholder, while one carrying only a hyphenated *-src is no longer resolved at all. Recovering the latter needs an attribute parser rather than a regex, and resolving a lazy-loading placeholder while the real image goes unvisited is the worse of the two failures. Both halves are pinned by tests. Image-derived text also has to survive into the answer, which is why this touches internal/searchutil. The chat enricher and the image_info filters matched Markdown links only, so an HTML-only passage looked image-free: every entry was dropped and the model received bare markup with the caption and OCR text stripped, even though the analysis had run. Both now recognise HTML img tags through one shared regex, so a tag the parser stores can always be matched back. Both syntaxes are located against the original passage and spliced in a single pass; scanning one regex over the other's output let a metadata block that itself quotes an image reference be rescanned and duplicated. The chat variant still enriches only images present in the passage, so orphan entries stay out. Known limits: - An unquoted src and a srcset-only tag are not matched, nor is a tag whose attribute values hold a bare > or a quoted src= of their own. - imgHTMLDataURI still matches src without a boundary, so a data-src holding a base64 placeholder is consumed as if it were the src and the whole tag replaced. Worth the same fix, but it changes what an existing lazy-loading document resolves, so it belongs on its own. - A reference shown as a documentation example is rewritten like any other. Recognising code spans needs a Markdown parser; a hand-rolled scanner risks the far worse failure of treating a document's real screenshots as examples. - Rewriting a whitelisted src writes the unescaped URL back into an HTML attribute, so a query parameter whose name spells an entity renders differently than the author wrote it. Keeping the encoded form would mean unescaping on every matcher instead. - Image text reaches the model only when the whole reference falls inside the retrieved window; an img tag is several times longer than a Markdown link and straddles a chunk boundary more often. - A reference repeated in one document is fetched once per occurrence, which is what gives each chunk its own analysed copy. - Nothing bounds how long one document's fetches may take in total. - Parent-context pruning removes only Markdown images. Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-07-28 13:08:31 +00:00
if ctx.Err() != nil {
log.Printf("WARN: remote image resolution cancelled: %v", ctx.Err())
break
}
fix(docparser): resolve remote images referenced by HTML img tags (#2355) Remote http(s) images written as <img src="..."> reached no resolver. Markdown images went through ResolveRemoteImages, HTML data-URIs and HTML relative paths each had their own pass, but nothing claimed the remaining combination, so those images were dropped without a log line and the multimodal stage was skipped for documents that rely on HTML for layout. ResolveRemoteImages now scans HTML img tags with a quoted src as a second pass and rewrites only the src attribute value, leaving the tag intact because the surrounding markup is why these documents use HTML at all. The per-image work (whitelist, SSRF, download, icon filter, upload) moves into one helper so the two syntaxes cannot drift apart on policy. Each pass carries its own image budget; sharing one would let HTML images eat into the number of Markdown images a document already gets resolved. An attribute value is trimmed, HTML-unescaped and its scheme lowercased before use, because HTML permits padding, spells a query separator &amp; and tolerates any scheme case, while every fetcher downstream compares the scheme byte-for-byte. Markdown targets get none of that normalization, so no Markdown reference resolves differently than it does today. A whitelisted host keeps serving the image from where it already lives, and its span is rewritten with the normalized URL rather than the raw attribute text: later stages both locate the image by searching the document for its serving URL and fetch that same string, so the two have to agree. The src attribute must now be preceded by whitespace, so a hyphenated attribute name is no longer mistaken for it. Among HTML tags this cuts two ways: one carrying both a hyphenated *-src and a real src now resolves the real src instead of the placeholder, while one carrying only a hyphenated *-src is no longer resolved at all. Recovering the latter needs an attribute parser rather than a regex, and resolving a lazy-loading placeholder while the real image goes unvisited is the worse of the two failures. Both halves are pinned by tests. Image-derived text also has to survive into the answer, which is why this touches internal/searchutil. The chat enricher and the image_info filters matched Markdown links only, so an HTML-only passage looked image-free: every entry was dropped and the model received bare markup with the caption and OCR text stripped, even though the analysis had run. Both now recognise HTML img tags through one shared regex, so a tag the parser stores can always be matched back. Both syntaxes are located against the original passage and spliced in a single pass; scanning one regex over the other's output let a metadata block that itself quotes an image reference be rescanned and duplicated. The chat variant still enriches only images present in the passage, so orphan entries stay out. Known limits: - An unquoted src and a srcset-only tag are not matched, nor is a tag whose attribute values hold a bare > or a quoted src= of their own. - imgHTMLDataURI still matches src without a boundary, so a data-src holding a base64 placeholder is consumed as if it were the src and the whole tag replaced. Worth the same fix, but it changes what an existing lazy-loading document resolves, so it belongs on its own. - A reference shown as a documentation example is rewritten like any other. Recognising code spans needs a Markdown parser; a hand-rolled scanner risks the far worse failure of treating a document's real screenshots as examples. - Rewriting a whitelisted src writes the unescaped URL back into an HTML attribute, so a query parameter whose name spells an entity renders differently than the author wrote it. Keeping the encoded form would mean unescaping on every matcher instead. - Image text reaches the model only when the whole reference falls inside the retrieved window; an img tag is several times longer than a Markdown link and straddles a chunk boundary more often. - A reference repeated in one document is fetched once per occurrence, which is what gives each chunk its own analysed copy. - Nothing bounds how long one document's fetches may take in total. - Parent-context pruning removes only Markdown images. Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-07-28 13:08:31 +00:00
if stats.resolved >= maxRemoteImages {
stats.overBudget++
continue
}
fix(docparser): resolve remote images referenced by HTML img tags (#2355) Remote http(s) images written as <img src="..."> reached no resolver. Markdown images went through ResolveRemoteImages, HTML data-URIs and HTML relative paths each had their own pass, but nothing claimed the remaining combination, so those images were dropped without a log line and the multimodal stage was skipped for documents that rely on HTML for layout. ResolveRemoteImages now scans HTML img tags with a quoted src as a second pass and rewrites only the src attribute value, leaving the tag intact because the surrounding markup is why these documents use HTML at all. The per-image work (whitelist, SSRF, download, icon filter, upload) moves into one helper so the two syntaxes cannot drift apart on policy. Each pass carries its own image budget; sharing one would let HTML images eat into the number of Markdown images a document already gets resolved. An attribute value is trimmed, HTML-unescaped and its scheme lowercased before use, because HTML permits padding, spells a query separator &amp; and tolerates any scheme case, while every fetcher downstream compares the scheme byte-for-byte. Markdown targets get none of that normalization, so no Markdown reference resolves differently than it does today. A whitelisted host keeps serving the image from where it already lives, and its span is rewritten with the normalized URL rather than the raw attribute text: later stages both locate the image by searching the document for its serving URL and fetch that same string, so the two have to agree. The src attribute must now be preceded by whitespace, so a hyphenated attribute name is no longer mistaken for it. Among HTML tags this cuts two ways: one carrying both a hyphenated *-src and a real src now resolves the real src instead of the placeholder, while one carrying only a hyphenated *-src is no longer resolved at all. Recovering the latter needs an attribute parser rather than a regex, and resolving a lazy-loading placeholder while the real image goes unvisited is the worse of the two failures. Both halves are pinned by tests. Image-derived text also has to survive into the answer, which is why this touches internal/searchutil. The chat enricher and the image_info filters matched Markdown links only, so an HTML-only passage looked image-free: every entry was dropped and the model received bare markup with the caption and OCR text stripped, even though the analysis had run. Both now recognise HTML img tags through one shared regex, so a tag the parser stores can always be matched back. Both syntaxes are located against the original passage and spliced in a single pass; scanning one regex over the other's output let a metadata block that itself quotes an image reference be rescanned and duplicated. The chat variant still enriches only images present in the passage, so orphan entries stay out. Known limits: - An unquoted src and a srcset-only tag are not matched, nor is a tag whose attribute values hold a bare > or a quoted src= of their own. - imgHTMLDataURI still matches src without a boundary, so a data-src holding a base64 placeholder is consumed as if it were the src and the whole tag replaced. Worth the same fix, but it changes what an existing lazy-loading document resolves, so it belongs on its own. - A reference shown as a documentation example is rewritten like any other. Recognising code spans needs a Markdown parser; a hand-rolled scanner risks the far worse failure of treating a document's real screenshots as examples. - Rewriting a whitelisted src writes the unescaped URL back into an HTML attribute, so a query parameter whose name spells an entity renders differently than the author wrote it. Keeping the encoded form would mean unescaping on every matcher instead. - Image text reaches the model only when the whole reference falls inside the retrieved window; an img tag is several times longer than a Markdown link and straddles a chunk boundary more often. - A reference repeated in one document is fetched once per occurrence, which is what gives each chunk its own analysed copy. - Nothing bounds how long one document's fetches may take in total. - Parent-context pruning removes only Markdown images. Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-07-28 13:08:31 +00:00
res, err := fetchAndStoreRemoteImage(ctx, client(), fileSvc, tenantID, imgURL)
if err != nil {
if errors.Is(err, errRemoteImageIsIcon) {
stats.iconSkips++
} else {
log.Printf("WARN: skipped %s remote image %s: %v", spec.Syntax, imgURL, err)
}
continue
}
fix(docparser): resolve remote images referenced by HTML img tags (#2355) Remote http(s) images written as <img src="..."> reached no resolver. Markdown images went through ResolveRemoteImages, HTML data-URIs and HTML relative paths each had their own pass, but nothing claimed the remaining combination, so those images were dropped without a log line and the multimodal stage was skipped for documents that rely on HTML for layout. ResolveRemoteImages now scans HTML img tags with a quoted src as a second pass and rewrites only the src attribute value, leaving the tag intact because the surrounding markup is why these documents use HTML at all. The per-image work (whitelist, SSRF, download, icon filter, upload) moves into one helper so the two syntaxes cannot drift apart on policy. Each pass carries its own image budget; sharing one would let HTML images eat into the number of Markdown images a document already gets resolved. An attribute value is trimmed, HTML-unescaped and its scheme lowercased before use, because HTML permits padding, spells a query separator &amp; and tolerates any scheme case, while every fetcher downstream compares the scheme byte-for-byte. Markdown targets get none of that normalization, so no Markdown reference resolves differently than it does today. A whitelisted host keeps serving the image from where it already lives, and its span is rewritten with the normalized URL rather than the raw attribute text: later stages both locate the image by searching the document for its serving URL and fetch that same string, so the two have to agree. The src attribute must now be preceded by whitespace, so a hyphenated attribute name is no longer mistaken for it. Among HTML tags this cuts two ways: one carrying both a hyphenated *-src and a real src now resolves the real src instead of the placeholder, while one carrying only a hyphenated *-src is no longer resolved at all. Recovering the latter needs an attribute parser rather than a regex, and resolving a lazy-loading placeholder while the real image goes unvisited is the worse of the two failures. Both halves are pinned by tests. Image-derived text also has to survive into the answer, which is why this touches internal/searchutil. The chat enricher and the image_info filters matched Markdown links only, so an HTML-only passage looked image-free: every entry was dropped and the model received bare markup with the caption and OCR text stripped, even though the analysis had run. Both now recognise HTML img tags through one shared regex, so a tag the parser stores can always be matched back. Both syntaxes are located against the original passage and spliced in a single pass; scanning one regex over the other's output let a metadata block that itself quotes an image reference be rescanned and duplicated. The chat variant still enriches only images present in the passage, so orphan entries stay out. Known limits: - An unquoted src and a srcset-only tag are not matched, nor is a tag whose attribute values hold a bare > or a quoted src= of their own. - imgHTMLDataURI still matches src without a boundary, so a data-src holding a base64 placeholder is consumed as if it were the src and the whole tag replaced. Worth the same fix, but it changes what an existing lazy-loading document resolves, so it belongs on its own. - A reference shown as a documentation example is rewritten like any other. Recognising code spans needs a Markdown parser; a hand-rolled scanner risks the far worse failure of treating a document's real screenshots as examples. - Rewriting a whitelisted src writes the unescaped URL back into an HTML attribute, so a query parameter whose name spells an entity renders differently than the author wrote it. Keeping the encoded form would mean unescaping on every matcher instead. - Image text reaches the model only when the whole reference falls inside the retrieved window; an img tag is several times longer than a Markdown link and straddles a chunk boundary more often. - A reference repeated in one document is fetched once per occurrence, which is what gives each chunk its own analysed copy. - Nothing bounds how long one document's fetches may take in total. - Parent-context pruning removes only Markdown images. Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-07-28 13:08:31 +00:00
stats.resolved++
fix(docparser): resolve remote images referenced by HTML img tags (#2355) Remote http(s) images written as <img src="..."> reached no resolver. Markdown images went through ResolveRemoteImages, HTML data-URIs and HTML relative paths each had their own pass, but nothing claimed the remaining combination, so those images were dropped without a log line and the multimodal stage was skipped for documents that rely on HTML for layout. ResolveRemoteImages now scans HTML img tags with a quoted src as a second pass and rewrites only the src attribute value, leaving the tag intact because the surrounding markup is why these documents use HTML at all. The per-image work (whitelist, SSRF, download, icon filter, upload) moves into one helper so the two syntaxes cannot drift apart on policy. Each pass carries its own image budget; sharing one would let HTML images eat into the number of Markdown images a document already gets resolved. An attribute value is trimmed, HTML-unescaped and its scheme lowercased before use, because HTML permits padding, spells a query separator &amp; and tolerates any scheme case, while every fetcher downstream compares the scheme byte-for-byte. Markdown targets get none of that normalization, so no Markdown reference resolves differently than it does today. A whitelisted host keeps serving the image from where it already lives, and its span is rewritten with the normalized URL rather than the raw attribute text: later stages both locate the image by searching the document for its serving URL and fetch that same string, so the two have to agree. The src attribute must now be preceded by whitespace, so a hyphenated attribute name is no longer mistaken for it. Among HTML tags this cuts two ways: one carrying both a hyphenated *-src and a real src now resolves the real src instead of the placeholder, while one carrying only a hyphenated *-src is no longer resolved at all. Recovering the latter needs an attribute parser rather than a regex, and resolving a lazy-loading placeholder while the real image goes unvisited is the worse of the two failures. Both halves are pinned by tests. Image-derived text also has to survive into the answer, which is why this touches internal/searchutil. The chat enricher and the image_info filters matched Markdown links only, so an HTML-only passage looked image-free: every entry was dropped and the model received bare markup with the caption and OCR text stripped, even though the analysis had run. Both now recognise HTML img tags through one shared regex, so a tag the parser stores can always be matched back. Both syntaxes are located against the original passage and spliced in a single pass; scanning one regex over the other's output let a metadata block that itself quotes an image reference be rescanned and duplicated. The chat variant still enriches only images present in the passage, so orphan entries stay out. Known limits: - An unquoted src and a srcset-only tag are not matched, nor is a tag whose attribute values hold a bare > or a quoted src= of their own. - imgHTMLDataURI still matches src without a boundary, so a data-src holding a base64 placeholder is consumed as if it were the src and the whole tag replaced. Worth the same fix, but it changes what an existing lazy-loading document resolves, so it belongs on its own. - A reference shown as a documentation example is rewritten like any other. Recognising code spans needs a Markdown parser; a hand-rolled scanner risks the far worse failure of treating a document's real screenshots as examples. - Rewriting a whitelisted src writes the unescaped URL back into an HTML attribute, so a query parameter whose name spells an entity renders differently than the author wrote it. Keeping the encoded form would mean unescaping on every matcher instead. - Image text reaches the model only when the whole reference falls inside the retrieved window; an img tag is several times longer than a Markdown link and straddles a chunk boundary more often. - A reference repeated in one document is fetched once per occurrence, which is what gives each chunk its own analysed copy. - Nothing bounds how long one document's fetches may take in total. - Parent-context pruning removes only Markdown images. Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-07-28 13:08:31 +00:00
// A whitelisted host is served from where it already lives, so the
// document keeps pointing there. The span is still rewritten with the
// normalized URL: later stages both locate the image by searching the
// document for its ServingURL and fetch that same string, so the two have
// to agree, and an entity-encoded or padded attribute value satisfies
// neither.
servingURL := res.ServingURL
if res.KeepOriginalURL {
servingURL = imgURL
}
images = append(images, StoredImage{
OriginalRef: imgURL,
ServingURL: servingURL,
fix(docparser): resolve remote images referenced by HTML img tags (#2355) Remote http(s) images written as <img src="..."> reached no resolver. Markdown images went through ResolveRemoteImages, HTML data-URIs and HTML relative paths each had their own pass, but nothing claimed the remaining combination, so those images were dropped without a log line and the multimodal stage was skipped for documents that rely on HTML for layout. ResolveRemoteImages now scans HTML img tags with a quoted src as a second pass and rewrites only the src attribute value, leaving the tag intact because the surrounding markup is why these documents use HTML at all. The per-image work (whitelist, SSRF, download, icon filter, upload) moves into one helper so the two syntaxes cannot drift apart on policy. Each pass carries its own image budget; sharing one would let HTML images eat into the number of Markdown images a document already gets resolved. An attribute value is trimmed, HTML-unescaped and its scheme lowercased before use, because HTML permits padding, spells a query separator &amp; and tolerates any scheme case, while every fetcher downstream compares the scheme byte-for-byte. Markdown targets get none of that normalization, so no Markdown reference resolves differently than it does today. A whitelisted host keeps serving the image from where it already lives, and its span is rewritten with the normalized URL rather than the raw attribute text: later stages both locate the image by searching the document for its serving URL and fetch that same string, so the two have to agree. The src attribute must now be preceded by whitespace, so a hyphenated attribute name is no longer mistaken for it. Among HTML tags this cuts two ways: one carrying both a hyphenated *-src and a real src now resolves the real src instead of the placeholder, while one carrying only a hyphenated *-src is no longer resolved at all. Recovering the latter needs an attribute parser rather than a regex, and resolving a lazy-loading placeholder while the real image goes unvisited is the worse of the two failures. Both halves are pinned by tests. Image-derived text also has to survive into the answer, which is why this touches internal/searchutil. The chat enricher and the image_info filters matched Markdown links only, so an HTML-only passage looked image-free: every entry was dropped and the model received bare markup with the caption and OCR text stripped, even though the analysis had run. Both now recognise HTML img tags through one shared regex, so a tag the parser stores can always be matched back. Both syntaxes are located against the original passage and spliced in a single pass; scanning one regex over the other's output let a metadata block that itself quotes an image reference be rescanned and duplicated. The chat variant still enriches only images present in the passage, so orphan entries stay out. Known limits: - An unquoted src and a srcset-only tag are not matched, nor is a tag whose attribute values hold a bare > or a quoted src= of their own. - imgHTMLDataURI still matches src without a boundary, so a data-src holding a base64 placeholder is consumed as if it were the src and the whole tag replaced. Worth the same fix, but it changes what an existing lazy-loading document resolves, so it belongs on its own. - A reference shown as a documentation example is rewritten like any other. Recognising code spans needs a Markdown parser; a hand-rolled scanner risks the far worse failure of treating a document's real screenshots as examples. - Rewriting a whitelisted src writes the unescaped URL back into an HTML attribute, so a query parameter whose name spells an entity renders differently than the author wrote it. Keeping the encoded form would mean unescaping on every matcher instead. - Image text reaches the model only when the whole reference falls inside the retrieved window; an img tag is several times longer than a Markdown link and straddles a chunk boundary more often. - A reference repeated in one document is fetched once per occurrence, which is what gives each chunk its own analysed copy. - Nothing bounds how long one document's fetches may take in total. - Parent-context pruning removes only Markdown images. Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-07-28 13:08:31 +00:00
MimeType: res.MimeType,
})
fix(docparser): resolve remote images referenced by HTML img tags (#2355) Remote http(s) images written as <img src="..."> reached no resolver. Markdown images went through ResolveRemoteImages, HTML data-URIs and HTML relative paths each had their own pass, but nothing claimed the remaining combination, so those images were dropped without a log line and the multimodal stage was skipped for documents that rely on HTML for layout. ResolveRemoteImages now scans HTML img tags with a quoted src as a second pass and rewrites only the src attribute value, leaving the tag intact because the surrounding markup is why these documents use HTML at all. The per-image work (whitelist, SSRF, download, icon filter, upload) moves into one helper so the two syntaxes cannot drift apart on policy. Each pass carries its own image budget; sharing one would let HTML images eat into the number of Markdown images a document already gets resolved. An attribute value is trimmed, HTML-unescaped and its scheme lowercased before use, because HTML permits padding, spells a query separator &amp; and tolerates any scheme case, while every fetcher downstream compares the scheme byte-for-byte. Markdown targets get none of that normalization, so no Markdown reference resolves differently than it does today. A whitelisted host keeps serving the image from where it already lives, and its span is rewritten with the normalized URL rather than the raw attribute text: later stages both locate the image by searching the document for its serving URL and fetch that same string, so the two have to agree. The src attribute must now be preceded by whitespace, so a hyphenated attribute name is no longer mistaken for it. Among HTML tags this cuts two ways: one carrying both a hyphenated *-src and a real src now resolves the real src instead of the placeholder, while one carrying only a hyphenated *-src is no longer resolved at all. Recovering the latter needs an attribute parser rather than a regex, and resolving a lazy-loading placeholder while the real image goes unvisited is the worse of the two failures. Both halves are pinned by tests. Image-derived text also has to survive into the answer, which is why this touches internal/searchutil. The chat enricher and the image_info filters matched Markdown links only, so an HTML-only passage looked image-free: every entry was dropped and the model received bare markup with the caption and OCR text stripped, even though the analysis had run. Both now recognise HTML img tags through one shared regex, so a tag the parser stores can always be matched back. Both syntaxes are located against the original passage and spliced in a single pass; scanning one regex over the other's output let a metadata block that itself quotes an image reference be rescanned and duplicated. The chat variant still enriches only images present in the passage, so orphan entries stay out. Known limits: - An unquoted src and a srcset-only tag are not matched, nor is a tag whose attribute values hold a bare > or a quoted src= of their own. - imgHTMLDataURI still matches src without a boundary, so a data-src holding a base64 placeholder is consumed as if it were the src and the whole tag replaced. Worth the same fix, but it changes what an existing lazy-loading document resolves, so it belongs on its own. - A reference shown as a documentation example is rewritten like any other. Recognising code spans needs a Markdown parser; a hand-rolled scanner risks the far worse failure of treating a document's real screenshots as examples. - Rewriting a whitelisted src writes the unescaped URL back into an HTML attribute, so a query parameter whose name spells an entity renders differently than the author wrote it. Keeping the encoded form would mean unescaping on every matcher instead. - Image text reaches the model only when the whole reference falls inside the retrieved window; an img tag is several times longer than a Markdown link and straddles a chunk boundary more often. - A reference repeated in one document is fetched once per occurrence, which is what gives each chunk its own analysed copy. - Nothing bounds how long one document's fetches may take in total. - Parent-context pruning removes only Markdown images. Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-07-28 13:08:31 +00:00
markdown = markdown[:start] + servingURL + markdown[end:]
}
fix(docparser): resolve remote images referenced by HTML img tags (#2355) Remote http(s) images written as <img src="..."> reached no resolver. Markdown images went through ResolveRemoteImages, HTML data-URIs and HTML relative paths each had their own pass, but nothing claimed the remaining combination, so those images were dropped without a log line and the multimodal stage was skipped for documents that rely on HTML for layout. ResolveRemoteImages now scans HTML img tags with a quoted src as a second pass and rewrites only the src attribute value, leaving the tag intact because the surrounding markup is why these documents use HTML at all. The per-image work (whitelist, SSRF, download, icon filter, upload) moves into one helper so the two syntaxes cannot drift apart on policy. Each pass carries its own image budget; sharing one would let HTML images eat into the number of Markdown images a document already gets resolved. An attribute value is trimmed, HTML-unescaped and its scheme lowercased before use, because HTML permits padding, spells a query separator &amp; and tolerates any scheme case, while every fetcher downstream compares the scheme byte-for-byte. Markdown targets get none of that normalization, so no Markdown reference resolves differently than it does today. A whitelisted host keeps serving the image from where it already lives, and its span is rewritten with the normalized URL rather than the raw attribute text: later stages both locate the image by searching the document for its serving URL and fetch that same string, so the two have to agree. The src attribute must now be preceded by whitespace, so a hyphenated attribute name is no longer mistaken for it. Among HTML tags this cuts two ways: one carrying both a hyphenated *-src and a real src now resolves the real src instead of the placeholder, while one carrying only a hyphenated *-src is no longer resolved at all. Recovering the latter needs an attribute parser rather than a regex, and resolving a lazy-loading placeholder while the real image goes unvisited is the worse of the two failures. Both halves are pinned by tests. Image-derived text also has to survive into the answer, which is why this touches internal/searchutil. The chat enricher and the image_info filters matched Markdown links only, so an HTML-only passage looked image-free: every entry was dropped and the model received bare markup with the caption and OCR text stripped, even though the analysis had run. Both now recognise HTML img tags through one shared regex, so a tag the parser stores can always be matched back. Both syntaxes are located against the original passage and spliced in a single pass; scanning one regex over the other's output let a metadata block that itself quotes an image reference be rescanned and duplicated. The chat variant still enriches only images present in the passage, so orphan entries stay out. Known limits: - An unquoted src and a srcset-only tag are not matched, nor is a tag whose attribute values hold a bare > or a quoted src= of their own. - imgHTMLDataURI still matches src without a boundary, so a data-src holding a base64 placeholder is consumed as if it were the src and the whole tag replaced. Worth the same fix, but it changes what an existing lazy-loading document resolves, so it belongs on its own. - A reference shown as a documentation example is rewritten like any other. Recognising code spans needs a Markdown parser; a hand-rolled scanner risks the far worse failure of treating a document's real screenshots as examples. - Rewriting a whitelisted src writes the unescaped URL back into an HTML attribute, so a query parameter whose name spells an entity renders differently than the author wrote it. Keeping the encoded form would mean unescaping on every matcher instead. - Image text reaches the model only when the whole reference falls inside the retrieved window; an img tag is several times longer than a Markdown link and straddles a chunk boundary more often. - A reference repeated in one document is fetched once per occurrence, which is what gives each chunk its own analysed copy. - Nothing bounds how long one document's fetches may take in total. - Parent-context pruning removes only Markdown images. Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-07-28 13:08:31 +00:00
stats.report(spec.Syntax)
return markdown, images
}
// htmlAttrSrc normalizes an HTML src attribute value into the URL to request.
//
// Three things are HTML-specific. An attribute value may be padded, so it is
// trimmed — on both sides of the decode, because an entity can itself expand to
// whitespace. It may carry entities, and `&amp;` is the correct spelling of a
// query separator, so it is unescaped. And the scheme may be written in any
// case, while every fetcher downstream compares it byte-for-byte, so it is
// lowercased.
//
// Markdown targets get none of this: they are handed through unchanged so that
// existing documents resolve exactly the references they resolve today.
func htmlAttrSrc(raw string) string {
src := strings.TrimSpace(html.UnescapeString(strings.TrimSpace(raw)))
if i := strings.Index(src, "://"); i > 0 {
src = strings.ToLower(src[:i]) + src[i:]
}
return src
}
// markdownSrc hands a Markdown image target through untouched. Markdown has no
// attribute quoting or entity encoding to undo, and leaving it alone is what
// keeps existing documents resolving exactly what they resolve today.
func markdownSrc(raw string) string { return raw }
// ResolveRemoteImages downloads remote http(s) images into storage and points
// the document at the stored copies. Both Markdown image syntax and HTML <img>
// tags with a quoted src are covered.
func (r *ImageResolver) ResolveRemoteImages(
ctx context.Context,
markdown string,
fileSvc interfaces.FileService,
tenantID uint64,
) (updatedMarkdown string, images []StoredImage, err error) {
markdown = UnwrapLinkedImages(markdown)
// The client owns a dedicated transport, so it is built only once a scan
// actually has something to fetch.
var httpClient *http.Client
client := func() *http.Client {
if httpClient == nil {
httpClient = secutils.NewSSRFSafeHTTPClient(secutils.SSRFSafeHTTPClientConfig{
Timeout: remoteImageFetchTimeout,
MaxRedirects: 5,
})
}
return httpClient
}
// Two scans, each with its own budget. Sharing one would let HTML images eat
// into the number of Markdown images a document already gets resolved today.
markdown, mdImages := resolveRemoteImagePass(ctx, markdown, remotePassSpec{
Pattern: imgMarkdownPattern,
// Group 2 of imgMarkdownPattern is the target; group 1 is the alt text.
URLGroup: 2,
Syntax: "markdown",
SrcOf: markdownSrc,
}, client, fileSvc, tenantID)
markdown, htmlImages := resolveRemoteImagePass(ctx, markdown, remotePassSpec{
Pattern: imgHTMLSrc,
URLGroup: searchutil.HTMLImageSrcURLGroup,
Syntax: "html",
SrcOf: htmlAttrSrc,
}, client, fileSvc, tenantID)
images = append(images, mdImages...)
images = append(images, htmlImages...)
return markdown, images, nil
}
// downloadImage fetches an image from remoteURL using the provided SSRF-safe
// client. It validates Content-Type and enforces maxRemoteImageSize.
func downloadImage(ctx context.Context, client *http.Client, remoteURL string) (data []byte, mimeType string, err error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, remoteURL, nil)
if err != nil {
return nil, "", fmt.Errorf("create request: %w", err)
}
// Some CDNs require a browser-like User-Agent.
req.Header.Set("User-Agent", "Mozilla/5.0 (compatible; WeKnora/1.0)")
resp, err := client.Do(req)
if err != nil {
return nil, "", fmt.Errorf("HTTP GET: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, "", fmt.Errorf("unexpected status %d", resp.StatusCode)
}
// Determine MIME type from Content-Type header.
ct := resp.Header.Get("Content-Type")
mimeType, _, _ = mime.ParseMediaType(ct)
if mimeType == "" {
mimeType = "application/octet-stream"
}
// Only allow image content types (or octet-stream which we sniff later).
if !strings.HasPrefix(mimeType, "image/") && mimeType != "application/octet-stream" {
return nil, "", fmt.Errorf("non-image content type: %s", mimeType)
}
// Read body with size limit.
limited := io.LimitReader(resp.Body, maxRemoteImageSize+1)
body, err := io.ReadAll(limited)
if err != nil {
return nil, "", fmt.Errorf("read body: %w", err)
}
if len(body) > maxRemoteImageSize {
return nil, "", fmt.Errorf("image exceeds %d bytes limit", maxRemoteImageSize)
}
// If MIME was octet-stream, sniff the real type from body.
if mimeType == "application/octet-stream" {
detected := http.DetectContentType(body)
if strings.HasPrefix(detected, "image/") {
mimeType = detected
} else {
return nil, "", fmt.Errorf("downloaded data is not an image (sniffed: %s)", detected)
}
}
return body, mimeType, nil
}
// extFromURLPath extracts the image file extension from the URL path segment.
func extFromURLPath(rawURL string) string {
p := path.Ext(path.Base(rawURL))
switch strings.ToLower(p) {
case ".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".svg":
return strings.ToLower(p)
default:
return ""
}
}