RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
fix(models): support the MinerU 4.1 Tasks API in ParseMinerUV1 (#21995)
CCLUCKYf8254381e22f
diff --git a/internal/entity/models/mineru_v1.go b/internal/entity/models/mineru_v1.goindex ee16ff7c68..2025731276 100644--- a/internal/entity/models/mineru_v1.go+++ b/internal/entity/models/mineru_v1.go@@ -23,11 +23,13 @@ import ("crypto/sha256""encoding/hex""encoding/json"+ "errors""fmt""io""net/http""net/url""path"+ "strconv""strings""sync""time"@@ -46,8 +48,10 @@ var (const DefaultMinerUV1ParseTimeout = 30 * time.Minutetype minerUV1SupportCacheEntry struct {- supported bool- expires time.Time+ supported bool+ supportsTasks bool+ decided bool+ expires time.Time}var minerUV1SupportCache sync.Map@@ -123,8 +127,7 @@ func MinerUV1OCRMode(raw string) string {}}-func minerUV1SupportCacheKey(baseURL, apiKey string) string {- token := minerUBearerFromAPIKey(apiKey)+func minerUV1SupportCacheKey(baseURL, token string) string {sum := sha256.Sum256([]byte(token))return baseURL + "\x00" + hex.EncodeToString(sum[:])}@@ -139,6 +142,20 @@ func minerUProbeGET(ctx context.Context, client *http.Client, rawURL, token strireturn 0, err}+func minerUParseHealthVersion(body []byte) (supportsTasks bool, decided bool) {+ var payload struct {+ Version string `json:"version"`+ }+ if err := json.Unmarshal(body, &payload); err != nil || strings.TrimSpace(payload.Version) == "" {+ return false, false+ }+ major, minor, _, ok := minerUParseSemver(payload.Version)+ if !ok {+ return false, false+ }+ return minerUV1VersionSupportsTasks(major, minor), true+}+// MinerUSupportsV1 reports whether baseURL speaks MinerU 4's /v1 HTTP API.// 404/405 mean a 3.x /file_parse service. 401/403 still count as V1 (the// route exists; credentials may be wrong).@@ -147,16 +164,16 @@ func MinerUSupportsV1(ctx context.Context, baseURL, apiKey string) (bool, error)if baseURL == "" {return false, fmt.Errorf("MinerU base URL is empty")}- cacheKey := minerUV1SupportCacheKey(baseURL, apiKey)+ token := minerUBearerFromAPIKey(apiKey)+ cacheKey := minerUV1SupportCacheKey(baseURL, token)if cached, ok := minerUV1SupportCache.Load(cacheKey); ok {entry := cached.(minerUV1SupportCacheEntry)if time.Now().Before(entry.expires) {return entry.supported, nil}}- token := minerUBearerFromAPIKey(apiKey)- code, err := minerUProbeGET(ctx, minerUHTTPClient(), baseURL+"/v1/health", token)- if err != nil {+ code, body, err := minerUGET(ctx, minerUHTTPClient(), baseURL+"/v1/health", token)+ if err != nil && code == 0 {return false, err}var supported bool@@ -166,9 +183,15 @@ func MinerUSupportsV1(ctx context.Context, baseURL, apiKey string) (bool, error)default:supported = true}+ var supportsTasks, decided bool+ if supported && code >= 200 && code < 300 {+ supportsTasks, decided = minerUParseHealthVersion(body)+ }minerUV1SupportCache.Store(cacheKey, minerUV1SupportCacheEntry{- supported: supported,- expires: time.Now().Add(minerUV1SupportCacheTTL),+ supported: supported,+ supportsTasks: supportsTasks,+ decided: decided,+ expires: time.Now().Add(minerUV1SupportCacheTTL),})return supported, nil}@@ -179,6 +202,17 @@ func applyMinerUAuth(req *http.Request, token string) {}}+// minerUHTTPStatusError carries the HTTP status of a non-2xx MinerU response+// so callers can branch on it (the Tasks dispatch only falls back to the+// legacy cycle on 404). Its text matches the previous plain fmt error.+type minerUHTTPStatusError struct {+ Status int+ Err error+}++func (e *minerUHTTPStatusError) Error() string { return e.Err.Error() }+func (e *minerUHTTPStatusError) Unwrap() error { return e.Err }+func minerUJSON(ctx context.Context, client *http.Client, method, rawURL, token string, body any, dest any) error {var reader io.Readerif body != nil {@@ -206,7 +240,10 @@ func minerUJSON(ctx context.Context, client *http.Client, method, rawURL, tokenreturn fmt.Errorf("read %s %s: %w", method, rawURL, err)}if resp.StatusCode < 200 || resp.StatusCode >= 300 {- return fmt.Errorf("MinerU V1 %s %s: HTTP %d: %s", method, rawURL, resp.StatusCode, string(payload))+ return &minerUHTTPStatusError{+ Status: resp.StatusCode,+ Err: fmt.Errorf("MinerU V1 %s %s: HTTP %d: %s", method, rawURL, resp.StatusCode, string(payload)),+ }}if dest == nil {return nil@@ -274,8 +311,86 @@ func minerUV1Terminal(status string) bool {}}-// ParseMinerUV1 runs the MinerU 4 V1 cycle: create upload → PUT bytes →-// complete → parse job → poll → download zip and/or markdown.+// minerUParseSemver parses strings like "4.0.12", "v4.1.0", "4.0", "4.1.0-alpha".+// Prerelease tags and build metadata are stripped. Returns ok=false on unparseable inputs.+func minerUParseSemver(v string) (major, minor, patch int, ok bool) {+ v = strings.TrimSpace(v)+ v = strings.TrimPrefix(v, "v")+ v = strings.TrimPrefix(v, "V")+ if v == "" {+ return 0, 0, 0, false+ }+ if idx := strings.IndexAny(v, "-+"); idx >= 0 {+ v = v[:idx]+ }+ parts := strings.Split(v, ".")+ if len(parts) == 0 {+ return 0, 0, 0, false+ }+ var err error+ major, err = strconv.Atoi(parts[0])+ if err != nil {+ return 0, 0, 0, false+ }+ if len(parts) > 1 {+ minor, err = strconv.Atoi(parts[1])+ if err != nil {+ return 0, 0, 0, false+ }+ }+ if len(parts) > 2 {+ patch, _ = strconv.Atoi(parts[2])+ }+ return major, minor, patch, true+}++func minerUV1VersionSupportsTasks(major, minor int) bool {+ if major > 4 {+ return true+ }+ if major == 4 {+ return minor >= 1+ }+ return false+}++// minerUV1ServerSupportsTasks probes GET /v1/health to determine whether the server+// speaks the 4.0 legacy upload/job protocol or the 4.1+ Tasks API.+// A recognized version < 4.1 selects the 4.0 cycle; version >= 4.1 selects Tasks.+// If /v1/health is unavailable or omits version, decided is false and the caller+// probes /v1/tasks directly, falling back on 404/400.+// Results are cached in minerUV1SupportCache so repeated calls and callers that+// precede ParseMinerUV1 with MinerUSupportsV1 do not probe /v1/health twice.+func minerUV1ServerSupportsTasks(ctx context.Context, client *http.Client, baseURL, token string) (supportsTasks bool, decided bool) {+ cacheKey := minerUV1SupportCacheKey(baseURL, token)+ if cached, ok := minerUV1SupportCache.Load(cacheKey); ok {+ entry := cached.(minerUV1SupportCacheEntry)+ if time.Now().Before(entry.expires) {+ return entry.supportsTasks, entry.decided+ }+ }+ code, body, err := minerUGET(ctx, client, baseURL+"/v1/health", token)+ if err != nil || code < 200 || code >= 300 {+ return false, false+ }+ supportsTasks, decided = minerUParseHealthVersion(body)+ minerUV1SupportCache.Store(cacheKey, minerUV1SupportCacheEntry{+ supported: true,+ supportsTasks: supportsTasks,+ decided: decided,+ expires: time.Now().Add(minerUV1SupportCacheTTL),+ })+ return supportsTasks, decided+}++// ParseMinerUV1 runs the MinerU 4 V1 parse cycle. When GET /v1/health advertises+// a known server version, versions < 4.1 (such as 4.0.x) run the 4.0 upload →+// complete → parse job → poll cycle directly, avoiding the 4.1 Tasks API where+// 4.0 servers return HTTP 400 (validation error on the 4.1 manifest).+// When /v1/health is absent or omits version, the 4.1 Tasks API runs first,+// falling back to the 4.0 cycle when POST /v1/tasks returns 404 (unavailable)+// or 400 (schema validation error on 4.0 servers). When the version is known+// to be >= 4.1, errors from the Tasks API are returned directly.// ocrMode is the V1 ocr_mode (auto, txt, ocr); use MinerUV1OCRMode to normalize.func ParseMinerUV1(ctx context.Context, baseURL, apiKey, filename string, content []byte, backend, ocrMode string, timeout time.Duration) (*MinerUV1Result, error) {baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/")@@ -296,6 +411,27 @@ func ParseMinerUV1(ctx context.Context, baseURL, apiKey, filename string, contenname := minerUFilename(filename)sum := sha256.Sum256(content)+ supportsTasks, decided := minerUV1ServerSupportsTasks(ctx, client, baseURL, token)+ if decided && !supportsTasks {+ return parseMinerUV1Legacy(ctx, client, token, baseURL, name, content, sum, backend, ocrMode)+ }++ result, err := parseMinerUTasks(ctx, client, token, baseURL, name, content, sum, backend, ocrMode)+ if err == nil {+ return result, nil+ }+ if decided && supportsTasks {+ return nil, err+ }+ if !errors.Is(err, errMinerUTasksUnavailable) {+ return nil, err+ }+ return parseMinerUV1Legacy(ctx, client, token, baseURL, name, content, sum, backend, ocrMode)+}++// parseMinerUV1Legacy runs the MinerU 4.0 cycle: create upload → PUT bytes →+// complete → parse job → poll → download zip and/or markdown.+func parseMinerUV1Legacy(ctx context.Context, client *http.Client, token, baseURL, name string, content []byte, sum [32]byte, backend, ocrMode string) (*MinerUV1Result, error) {var created minerUV1UploadResponseif err := minerUJSON(ctx, client, http.MethodPost, baseURL+"/v1/uploads", token, map[string]any{"filename": name,@@ -319,39 +455,8 @@ func ParseMinerUV1(ctx context.Context, baseURL, apiKey, filename string, contenif created.UploadURL == "" {return nil, fmt.Errorf("MinerU V1 upload missing upload_url")}- uploadURL, err := url.Parse(created.UploadURL)- if err != nil {- return nil, fmt.Errorf("invalid upload_url: %w", err)- }- if !uploadURL.IsAbs() {- base, err := url.Parse(baseURL + "/")- if err != nil {- return nil, fmt.Errorf("invalid MinerU base URL: %w", err)- }- uploadURL = base.ResolveReference(uploadURL)- }- method := strings.ToUpper(strings.TrimSpace(created.UploadMethod))- if method == "" {- method = http.MethodPut- }- req, err := http.NewRequestWithContext(ctx, method, uploadURL.String(), bytes.NewReader(content))- if err != nil {- return nil, fmt.Errorf("create byte upload: %w", err)- }- for k, v := range created.UploadHeaders {- req.Header.Set(k, v)- }- if minerUSameOrigin(baseURL, uploadURL.String()) {- applyMinerUAuth(req, token)- }- resp, err := client.Do(req)- if err != nil {- return nil, fmt.Errorf("byte upload: %w", err)- }- _, _ = io.Copy(io.Discard, resp.Body)- resp.Body.Close()- if resp.StatusCode < 200 || resp.StatusCode >= 300 {- return nil, fmt.Errorf("byte upload: HTTP %d", resp.StatusCode)+ if err := minerUPutUploadBytes(ctx, token, baseURL, created.UploadMethod, created.UploadURL, created.UploadHeaders, content); err != nil {+ return nil, err}var completed minerUV1UploadResponseif err := minerUJSON(ctx, client, http.MethodPost, baseURL+"/v1/uploads/"+created.ID+"/complete", token, nil, &completed); err != nil {@@ -414,7 +519,7 @@ func ParseMinerUV1(ctx context.Context, baseURL, apiKey, filename string, contencontinue}if ref, ok := file.OutputFiles["zip"]; ok && ref.artifactID() != "" && len(result.Zip) == 0 {- body, err := minerUV1DownloadFile(ctx, client, baseURL, token, ref.artifactID())+ body, err := minerUDownloadFile(ctx, baseURL, token, baseURL+"/v1/files/"+ref.artifactID()+"/content")if err != nil {if artifactErr == nil {artifactErr = fmt.Errorf("download zip: %w", err)@@ -424,7 +529,7 @@ func ParseMinerUV1(ctx context.Context, baseURL, apiKey, filename string, conten}}if ref, ok := file.OutputFiles["markdown"]; ok && ref.artifactID() != "" && result.Markdown == "" {- body, err := minerUV1DownloadFile(ctx, client, baseURL, token, ref.artifactID())+ body, err := minerUDownloadFile(ctx, baseURL, token, baseURL+"/v1/files/"+ref.artifactID()+"/content")if err != nil {if artifactErr == nil {artifactErr = fmt.Errorf("download markdown: %w", err)@@ -481,14 +586,75 @@ func minerUV1DownloadHTTPClient(apiOrigin string) *http.Client {}}-func minerUV1DownloadFile(ctx context.Context, client *http.Client, baseURL, token, fileID string) ([]byte, error) {+// minerUPutUploadBytes uploads the raw file bytes to an upload URL with the+// given method (PUT unless the server said otherwise), applying the supplied+// headers and attaching the bearer token only when the URL is same-origin+// with the API base, and stripping the token on any cross-origin redirect so+// signed object-storage links never see the token.+func minerUPutUploadBytes(ctx context.Context, token, baseURL, method, rawURL string, headers map[string]string, content []byte) error {+ uploadURL, err := url.Parse(rawURL)+ if err != nil {+ return fmt.Errorf("invalid upload_url: %w", err)+ }+ if !uploadURL.IsAbs() {+ base, err := url.Parse(baseURL + "/")+ if err != nil {+ return fmt.Errorf("invalid MinerU base URL: %w", err)+ }+ uploadURL = base.ResolveReference(uploadURL)+ }+ if method = strings.ToUpper(strings.TrimSpace(method)); method == "" {+ method = http.MethodPut+ }+ req, err := http.NewRequestWithContext(ctx, method, uploadURL.String(), bytes.NewReader(content))+ if err != nil {+ return fmt.Errorf("create byte upload: %w", err)+ }+ for k, v := range headers {+ req.Header.Set(k, v)+ }+ apiOrigin := strings.TrimRight(strings.TrimSpace(baseURL), "/")+ if minerUSameOrigin(apiOrigin, uploadURL.String()) {+ applyMinerUAuth(req, token)+ }+ resp, err := minerUV1DownloadHTTPClient(apiOrigin).Do(req)+ if err != nil {+ return fmt.Errorf("byte upload: %w", err)+ }+ _, _ = io.Copy(io.Discard, resp.Body)+ resp.Body.Close()+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ return fmt.Errorf("byte upload: HTTP %d", resp.StatusCode)+ }+ return nil+}++// minerUDownloadFile GETs a MinerU artifact URL. Legacy 4.0 output_files ids+// resolve to /v1/files/{id}/content; 4.1 tasks return the result_url directly+// (a Files URL on local services, a signed object-storage link on SaaS). The+// bearer token is attached only to same-origin URLs and stripped again on+// every cross-origin redirect.+func minerUDownloadFile(ctx context.Context, baseURL, token, rawURL string) ([]byte, error) {+ parsedURL, err := url.Parse(rawURL)+ if err != nil {+ return nil, fmt.Errorf("invalid download url: %w", err)+ }+ if !parsedURL.IsAbs() {+ base, err := url.Parse(strings.TrimRight(strings.TrimSpace(baseURL), "/") + "/")+ if err != nil {+ return nil, fmt.Errorf("invalid MinerU base URL: %w", err)+ }+ parsedURL = base.ResolveReference(parsedURL)+ }apiOrigin := strings.TrimRight(strings.TrimSpace(baseURL), "/")dlClient := minerUV1DownloadHTTPClient(apiOrigin)- req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiOrigin+"/v1/files/"+fileID+"/content", nil)+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, parsedURL.String(), nil)if err != nil {return nil, err}- applyMinerUAuth(req, token)+ if minerUSameOrigin(apiOrigin, parsedURL.String()) {+ applyMinerUAuth(req, token)+ }resp, err := dlClient.Do(req)if err != nil {return nil, err@@ -504,6 +670,164 @@ func minerUV1DownloadFile(ctx context.Context, client *http.Client, baseURL, tokreturn body, nil}+// errMinerUTasksUnavailable marks a MinerU server without the 4.1 Tasks API:+// POST /v1/tasks returned 404, so the caller falls back to the 4.0 legacy+// cycle instead of surfacing the routing error.+var errMinerUTasksUnavailable = errors.New("MinerU V1 tasks API unavailable")++// MinerU 4.1 Tasks API payload. Every response is a complete snapshot whose+// absent fields carry no value: an upload slot only exists while the file is+// actually waiting for bytes.+type minerUTaskUpload struct {+ URL string `json:"url"`+ Headers map[string]string `json:"headers"`+ ExpiresAt int64 `json:"expires_at"`+}++type minerUTaskFile struct {+ FileID string `json:"file_id"`+ FileName string `json:"file_name"`+ Status string `json:"status"`+ Upload *minerUTaskUpload `json:"upload"`+ ResultURL string `json:"result_url"`+ Error *minerUV1Error `json:"error"`+}++// minerUTaskResponse decodes both the 202 creation receipt and the GET detail+// snapshot.+type minerUTaskResponse struct {+ TaskID string `json:"task_id"`+ Status string `json:"status"`+ Error *minerUV1Error `json:"error"`+ Files []minerUTaskFile `json:"files"`+}++// parseMinerUTasks runs the MinerU 4.1 Tasks cycle: POST /v1/tasks with a+// JSON manifest → PUT raw bytes to the returned upload URL (no completion+// call) → poll GET /v1/tasks/{id} → download the file's result_url.+// output_formats ["default"] yields one ZIP per input holding markdown.md+// plus the other general results, which minerUMarkdownFromZip unpacks.+// Creation returns errMinerUTasksUnavailable on 404 (absent) or 400 (4.0 servers+// validating against legacy schema) so ParseMinerUV1 can run the legacy 4.0+// cycle when version was not decided by health; every other creation failure+// is a real error (401/503 carry protocol meaning and must not be masked by a+// legacy retry).+func parseMinerUTasks(ctx context.Context, client *http.Client, token, baseURL, name string, content []byte, sum [32]byte, backend, ocrMode string) (*MinerUV1Result, error) {+ var created minerUTaskResponse+ if err := minerUJSON(ctx, client, http.MethodPost, baseURL+"/v1/tasks", token, map[string]any{+ "files": []map[string]any{{+ "file_name": name,+ "bytes": len(content),+ "sha256sum": hex.EncodeToString(sum[:]),+ }},+ "tier": MinerUTierFromBackend(backend),+ "ocr_mode": MinerUV1OCRMode(ocrMode),+ "output_formats": []string{"default"},+ }, &created); err != nil {+ var statusErr *minerUHTTPStatusError+ if errors.As(err, &statusErr) && (statusErr.Status == http.StatusNotFound || statusErr.Status == http.StatusBadRequest) {+ return nil, fmt.Errorf("%w: %w", errMinerUTasksUnavailable, err)+ }+ return nil, fmt.Errorf("create task: %w", err)+ }+ if created.TaskID == "" {+ return nil, fmt.Errorf("MinerU V1 tasks creation missing task_id")+ }+ if len(created.Files) == 0 {+ return nil, fmt.Errorf("MinerU V1 tasks creation missing files")+ }++ // Upload only when a snapshot offers a slot: the receipt can arrive before+ // the upload is prepared, and a waiting file without an upload means poll+ // on. A successful PUT is never repeated.+ uploaded := false+ if upload := created.Files[0].Upload; upload != nil {+ if err := minerUPutUploadBytes(ctx, token, baseURL, http.MethodPut, upload.URL, upload.Headers, content); err != nil {+ return nil, err+ }+ uploaded = true+ }++ task := &created+ pollWait := minerUV1PollInitial+ for !minerUV1Terminal(task.Status) {+ select {+ case <-ctx.Done():+ return nil, ctx.Err()+ case <-time.After(pollWait):+ }+ if pollWait < minerUV1PollMax {+ pollWait *= 2+ if pollWait > minerUV1PollMax {+ pollWait = minerUV1PollMax+ }+ }+ var detail minerUTaskResponse+ if err := minerUJSON(ctx, client, http.MethodGet, baseURL+"/v1/tasks/"+url.PathEscape(created.TaskID), token, nil, &detail); err != nil {+ return nil, fmt.Errorf("poll task: %w", err)+ }+ task = &detail+ if !uploaded && len(task.Files) > 0 && task.Files[0].Upload != nil {+ if err := minerUPutUploadBytes(ctx, token, baseURL, http.MethodPut, task.Files[0].Upload.URL, task.Files[0].Upload.Headers, content); err != nil {+ return nil, err+ }+ uploaded = true+ }+ }+ switch task.Status {+ case "failed", "canceled":+ return nil, minerUTaskStatusError(task.Status, task.Error, task.Files)+ }++ result := &MinerUV1Result{}+ var markdownParts []string+ for _, file := range task.Files {+ if file.Status != "completed" || file.ResultURL == "" {+ continue+ }+ body, err := minerUDownloadFile(ctx, baseURL, token, file.ResultURL)+ if err != nil {+ return nil, fmt.Errorf("download task result: %w", err)+ }+ if len(result.Zip) == 0 {+ result.Zip = body+ }+ if md, err := minerUMarkdownFromZip(body); err == nil && strings.TrimSpace(md) != "" {+ markdownParts = append(markdownParts, md)+ }+ }+ if len(markdownParts) == 1 {+ result.Markdown = markdownParts[0]+ } else if len(markdownParts) > 1 {+ for i := range markdownParts {+ markdownParts[i] = strings.TrimRight(markdownParts[i], "\r\n")+ }+ result.Markdown = strings.Join(markdownParts, "\n\n") + "\n"+ }+ if len(result.Zip) == 0 && strings.TrimSpace(result.Markdown) == "" {+ return nil, minerUTaskStatusError(task.Status, task.Error, task.Files)+ }+ return result, nil+}++// minerUTaskStatusError names a terminal task status and its first error:+// the snapshot-level error wins over per-file errors, matching how the+// response nests them.+func minerUTaskStatusError(status string, taskErr *minerUV1Error, files []minerUTaskFile) error {+ msg := status+ if taskErr != nil && strings.TrimSpace(taskErr.Message) != "" {+ msg = taskErr.Message+ } else {+ for i := range files {+ if files[i].Error != nil && strings.TrimSpace(files[i].Error.Message) != "" {+ msg = files[i].Error.Message+ break+ }+ }+ }+ return fmt.Errorf("MinerU V1 task %s: %s", status, msg)+}+// minerUMarkdownFromZip prefers a .md member, then content_list.json text,// then MinerU 4 structured_content.json block text.func minerUMarkdownFromZip(zipBytes []byte) (string, error) {diff --git a/internal/entity/models/mineru_v1_test.go b/internal/entity/models/mineru_v1_test.goindex be0b294b69..196783282e 100644--- a/internal/entity/models/mineru_v1_test.go+++ b/internal/entity/models/mineru_v1_test.go@@ -8,6 +8,8 @@ import ("archive/zip""bytes""context"+ "crypto/sha256"+ "encoding/hex""encoding/json""io""net/http"@@ -160,9 +162,9 @@ func TestMinerUV1DownloadStripsAuthOnCrossOriginRedirect(t *testing.T) {}))defer api.Close()- body, err := minerUV1DownloadFile(context.Background(), minerUHTTPClient(), api.URL, "secret-token", "out-1")+ body, err := minerUDownloadFile(context.Background(), api.URL, "secret-token", api.URL+"/v1/files/out-1/content")if err != nil {- t.Fatalf("minerUV1DownloadFile: %v", err)+ t.Fatalf("minerUDownloadFile: %v", err)}if body == nil || string(body) != "artifact" {t.Fatalf("body = %q", body)@@ -172,6 +174,41 @@ func TestMinerUV1DownloadStripsAuthOnCrossOriginRedirect(t *testing.T) {}}+func TestMinerUV1UploadStripsAuthOnCrossOriginRedirect(t *testing.T) {+ var sawAuth atomic.Bool+ redirect := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Header.Get("Authorization") != "" {+ sawAuth.Store(true)+ }+ w.WriteHeader(http.StatusOK)+ }))+ defer redirect.Close()++ var apiSawAuth atomic.Bool+ api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Header.Get("Authorization") != "" {+ apiSawAuth.Store(true)+ }+ if r.URL.Path == "/v1/upload-slot" {+ http.Redirect(w, r, redirect.URL, http.StatusTemporaryRedirect)+ return+ }+ http.NotFound(w, r)+ }))+ defer api.Close()++ err := minerUPutUploadBytes(context.Background(), "secret-token", api.URL, http.MethodPut, api.URL+"/v1/upload-slot", nil, []byte("data"))+ if err != nil {+ t.Fatalf("minerUPutUploadBytes: %v", err)+ }+ if !apiSawAuth.Load() {+ t.Fatal("same-origin upload must carry the bearer token initially")+ }+ if sawAuth.Load() {+ t.Fatal("Authorization must not be forwarded to a cross-origin redirect target")+ }+}+func TestParseMinerUV1OutputFilesUseFileID(t *testing.T) {orig := minerUV1PollInitialminerUV1PollInitial = time.Millisecond@@ -394,3 +431,564 @@ func TestMinerUProbeGETKeepsStatusWhenBodyReadFails(t *testing.T) {t.Fatal("probe error = nil, want the transport error when no status was received")}}++func TestParseMinerUV1TasksFlow(t *testing.T) {+ orig := minerUV1PollInitial+ minerUV1PollInitial = time.Millisecond+ t.Cleanup(func() { minerUV1PollInitial = orig })++ var (+ mu sync.Mutex+ created map[string]any+ gotBytes []byte+ uploadHdr string+ uploadAuth bool+ polls int+ )+ zipBuf := minerUTestZip(t, "markdown.md", "# Tasks\n\nFrom 4.1.\n")++ var server *httptest.Server+ server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodPost && r.URL.Path == "/v1/tasks":+ var payload map[string]any+ _ = json.NewDecoder(r.Body).Decode(&payload)+ mu.Lock()+ created = payload+ mu.Unlock()+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusAccepted)+ _, _ = w.Write([]byte(`{"task_id":"task-1","status":"waiting-file","files":[{"file_id":"file-1","file_name":"sample.pdf","status":"waiting-file","upload":{"url":"/v1/tasks/task-1/uploads/file-1","headers":{"X-Up":"1"},"expires_at":1800003600}}]}`))+ case r.Method == http.MethodPut && r.URL.Path == "/v1/tasks/task-1/uploads/file-1":+ mu.Lock()+ uploadHdr = r.Header.Get("X-Up")+ uploadAuth = r.Header.Get("Authorization") != ""+ gotBytes, _ = io.ReadAll(r.Body)+ mu.Unlock()+ w.WriteHeader(http.StatusOK)+ case r.Method == http.MethodGet && r.URL.Path == "/v1/tasks/task-1":+ mu.Lock()+ polls+++ n := polls+ mu.Unlock()+ w.Header().Set("Content-Type", "application/json")+ if n < 2 {+ _, _ = w.Write([]byte(`{"task_id":"task-1","status":"pending","progress":{"completed":0,"failed":0,"total":1},"files":[{"file_id":"file-1","file_name":"sample.pdf","status":"pending"}]}`))+ return+ }+ _, _ = w.Write([]byte(`{"task_id":"task-1","status":"completed","progress":{"completed":1,"failed":0,"total":1},"files":[{"file_id":"file-1","file_name":"sample.pdf","status":"completed","parse":{"tier":"standard","duration_ms":8000},"result_url":"` + server.URL + `/v1/files/file-1/content"}]}`))+ case r.Method == http.MethodGet && r.URL.Path == "/v1/files/file-1/content":+ w.Header().Set("Content-Type", "application/zip")+ _, _ = w.Write(zipBuf)+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()++ result, err := ParseMinerUV1(context.Background(), server.URL, "secret", "sample.pdf", []byte("%PDF-1.4"), "pipeline", "ocr", 5*time.Second)+ if err != nil {+ t.Fatalf("ParseMinerUV1: %v", err)+ }+ if result.Markdown != "# Tasks\n\nFrom 4.1.\n" {+ t.Fatalf("markdown = %q", result.Markdown)+ }+ if len(result.Zip) == 0 {+ t.Fatal("expected zip artifact")+ }+ mu.Lock()+ defer mu.Unlock()+ files, _ := created["files"].([]any)+ if len(files) != 1 {+ t.Fatalf("creation files = %v", created["files"])+ }+ file, _ := files[0].(map[string]any)+ if file["file_name"] != "sample.pdf" {+ t.Fatalf("file_name = %v", file["file_name"])+ }+ if file["bytes"] != float64(8) {+ t.Fatalf("bytes = %v, want 8", file["bytes"])+ }+ // The upload payload is asserted earlier in this test (%PDF-1.4); compare the+ // manifest digest against the exact SHA-256 of that same payload so a wrong+ // digest of the correct length cannot pass.+ wantSum := sha256.Sum256([]byte("%PDF-1.4"))+ if sum, _ := file["sha256sum"].(string); sum != hex.EncodeToString(wantSum[:]) {+ t.Fatalf("sha256sum = %v, want %x", file["sha256sum"], wantSum)+ }+ if file["file_id"] != nil || file["client_file_id"] != nil {+ t.Fatalf("client must not send file_id/client_file_id: %v", file)+ }+ if created["tier"] != "basic" {+ t.Fatalf("tier = %v, want basic (mapped from pipeline)", created["tier"])+ }+ if created["ocr_mode"] != "ocr" {+ t.Fatalf("ocr_mode = %v, want ocr", created["ocr_mode"])+ }+ if formats, _ := created["output_formats"].([]any); len(formats) != 1 || formats[0] != "default" {+ t.Fatalf("output_formats = %v, want [default]", created["output_formats"])+ }+ if !bytes.Equal(gotBytes, []byte("%PDF-1.4")) {+ t.Fatalf("uploaded bytes = %q", gotBytes)+ }+ if uploadHdr != "1" {+ t.Fatalf("upload headers not applied: X-Up = %q", uploadHdr)+ }+ if !uploadAuth {+ t.Fatal("same-origin upload must carry the bearer token")+ }+}++func TestParseMinerUV1TasksUploadSlotArrivesOnPoll(t *testing.T) {+ orig := minerUV1PollInitial+ minerUV1PollInitial = time.Millisecond+ t.Cleanup(func() { minerUV1PollInitial = orig })++ var (+ mu sync.Mutex+ uploaded bool+ polls int+ )+ zipBuf := minerUTestZip(t, "markdown.md", "# Late slot\n")++ var server *httptest.Server+ server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodPost && r.URL.Path == "/v1/tasks":+ w.WriteHeader(http.StatusAccepted)+ _, _ = w.Write([]byte(`{"task_id":"task-2","status":"waiting-file","files":[{"file_id":"file-2","file_name":"sample.pdf","status":"waiting-file"}]}`))+ case r.Method == http.MethodGet && r.URL.Path == "/v1/tasks/task-2":+ mu.Lock()+ polls+++ n := polls+ uploadedAlready := uploaded+ mu.Unlock()+ w.Header().Set("Content-Type", "application/json")+ switch {+ case n == 1:+ _, _ = w.Write([]byte(`{"task_id":"task-2","status":"waiting-file","files":[{"file_id":"file-2","status":"waiting-file","upload":{"url":"/v1/tasks/task-2/uploads/file-2","headers":{},"expires_at":1800003600}}]}`))+ case n == 2 && !uploadedAlready:+ t.Error("upload slot was offered but no PUT arrived before the next poll")+ _, _ = w.Write([]byte(`{"task_id":"task-2","status":"waiting-file","files":[{"file_id":"file-2","status":"waiting-file"}]}`))+ default:+ _, _ = w.Write([]byte(`{"task_id":"task-2","status":"completed","files":[{"file_id":"file-2","status":"completed","result_url":"` + server.URL + `/v1/files/file-2/content"}]}`))+ }+ case r.Method == http.MethodPut && r.URL.Path == "/v1/tasks/task-2/uploads/file-2":+ mu.Lock()+ uploaded = true+ mu.Unlock()+ w.WriteHeader(http.StatusOK)+ case r.Method == http.MethodGet && r.URL.Path == "/v1/files/file-2/content":+ _, _ = w.Write(zipBuf)+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()++ result, err := ParseMinerUV1(context.Background(), server.URL, "secret", "sample.pdf", []byte("%PDF-1.4"), "standard", "auto", 5*time.Second)+ if err != nil {+ t.Fatalf("ParseMinerUV1: %v", err)+ }+ if result.Markdown != "# Late slot\n" {+ t.Fatalf("markdown = %q", result.Markdown)+ }+}++func TestParseMinerUV1TasksFailedFileSurfacesError(t *testing.T) {+ orig := minerUV1PollInitial+ minerUV1PollInitial = time.Millisecond+ t.Cleanup(func() { minerUV1PollInitial = orig })++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodPost && r.URL.Path == "/v1/tasks":+ w.WriteHeader(http.StatusAccepted)+ _, _ = w.Write([]byte(`{"task_id":"task-3","status":"waiting-file","files":[{"file_id":"file-3","status":"waiting-file","upload":{"url":"/v1/tasks/task-3/uploads/file-3","headers":{},"expires_at":1800003600}}]}`))+ case r.Method == http.MethodPut && r.URL.Path == "/v1/tasks/task-3/uploads/file-3":+ w.WriteHeader(http.StatusOK)+ case r.Method == http.MethodGet && r.URL.Path == "/v1/tasks/task-3":+ _, _ = w.Write([]byte(`{"task_id":"task-3","status":"partial","files":[{"file_id":"file-3","status":"failed","error":{"code":"render_failed","message":"page render failed"}}]}`))+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()++ _, err := ParseMinerUV1(context.Background(), server.URL, "secret", "sample.pdf", []byte("%PDF-1.4"), "pipeline", "auto", 5*time.Second)+ if err == nil {+ t.Fatal("expected error for failed task file")+ }+ if !strings.Contains(err.Error(), "partial") || !strings.Contains(err.Error(), "page render failed") {+ t.Fatalf("error = %q, want partial status and file error", err.Error())+ }+}++func TestParseMinerUV1TasksCreationErrorIsNotMaskedByLegacy(t *testing.T) {+ var legacyCalls atomic.Int32+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodPost && r.URL.Path == "/v1/tasks":+ http.Error(w, `{"error":{"code":"invalid_api_key","message":"bad key"}}`, http.StatusUnauthorized)+ case r.Method == http.MethodPost && r.URL.Path == "/v1/uploads":+ legacyCalls.Add(1)+ http.NotFound(w, r)+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()++ _, err := ParseMinerUV1(context.Background(), server.URL, "secret", "sample.pdf", []byte("%PDF-1.4"), "pipeline", "auto", 5*time.Second)+ if err == nil {+ t.Fatal("expected the 401 creation error")+ }+ if !strings.Contains(err.Error(), "401") {+ t.Fatalf("error = %q, want the 401 status", err.Error())+ }+ if legacyCalls.Load() != 0 {+ t.Fatal("legacy cycle must not run for a non-404 creation failure")+ }+}++func TestParseMinerUV1LegacySelectedForVersion40(t *testing.T) {+ orig := minerUV1PollInitial+ minerUV1PollInitial = time.Millisecond+ t.Cleanup(func() { minerUV1PollInitial = orig })++ var (+ mu sync.Mutex+ tasksCalls int+ gotBytes []byte+ gotTier string+ gotOCR string+ polls int+ )+ zipBuf := minerUTestZip(t, "doc.md", "# From 4.0 Legacy\n")++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodGet && r.URL.Path == "/v1/health":+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{"status":"ok","version":"4.0.12"}`))+ case r.Method == http.MethodPost && r.URL.Path == "/v1/tasks":+ mu.Lock()+ tasksCalls+++ mu.Unlock()+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusBadRequest)+ _, _ = w.Write([]byte(`{"detail":[{"loc":["body","files",0,"source"],"msg":"field required","type":"value_error.missing"}]}`))+ case r.Method == http.MethodPost && r.URL.Path == "/v1/uploads":+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"id":"up-40","status":"pending","upload_url":"/v1/uploads/up-40/content","upload_method":"PUT"}`))+ case r.Method == http.MethodPut && r.URL.Path == "/v1/uploads/up-40/content":+ body, _ := io.ReadAll(r.Body)+ mu.Lock()+ gotBytes = body+ mu.Unlock()+ w.WriteHeader(http.StatusOK)+ case r.Method == http.MethodPost && r.URL.Path == "/v1/uploads/up-40/complete":+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"id":"up-40","status":"completed","file":{"id":"file-40"}}`))+ case r.Method == http.MethodPost && r.URL.Path == "/v1/parse/jobs":+ var payload map[string]any+ _ = json.NewDecoder(r.Body).Decode(&payload)+ if tier, ok := payload["tier"].(string); ok {+ mu.Lock()+ gotTier = tier+ mu.Unlock()+ }+ if mode, ok := payload["ocr_mode"].(string); ok {+ mu.Lock()+ gotOCR = mode+ mu.Unlock()+ }+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"job_id":"job-40","status":"queued"}`))+ case r.Method == http.MethodGet && r.URL.Path == "/v1/parse/jobs/job-40":+ mu.Lock()+ polls+++ n := polls+ mu.Unlock()+ w.Header().Set("Content-Type", "application/json")+ if n < 2 {+ _, _ = w.Write([]byte(`{"job_id":"job-40","status":"running"}`))+ return+ }+ _, _ = w.Write([]byte(`{"job_id":"job-40","status":"completed","files":[{"name":"doc.pdf","status":"completed","output_files":{"zip":{"file_id":"out-zip"},"markdown":{"file_id":"out-md"}}}]}`))+ case r.Method == http.MethodGet && r.URL.Path == "/v1/files/out-zip/content":+ w.Header().Set("Content-Type", "application/zip")+ _, _ = w.Write(zipBuf)+ case r.Method == http.MethodGet && r.URL.Path == "/v1/files/out-md/content":+ _, _ = w.Write([]byte("# From 4.0 Legacy\n"))+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()++ result, err := ParseMinerUV1(context.Background(), server.URL, "secret", "sample.pdf", []byte("%PDF-1.4"), "pipeline", "ocr", 5*time.Second)+ if err != nil {+ t.Fatalf("ParseMinerUV1: %v", err)+ }+ if result.Markdown != "# From 4.0 Legacy\n" {+ t.Fatalf("markdown = %q", result.Markdown)+ }+ if len(result.Zip) == 0 {+ t.Fatal("expected zip artifact")+ }+ mu.Lock()+ defer mu.Unlock()+ if tasksCalls != 0 {+ t.Fatalf("expected /v1/tasks not to be called when version is 4.0.12, got %d calls", tasksCalls)+ }+ if !bytes.Equal(gotBytes, []byte("%PDF-1.4")) {+ t.Fatalf("uploaded bytes = %q", gotBytes)+ }+ if gotTier != "basic" {+ t.Fatalf("tier = %q, want basic", gotTier)+ }+ if gotOCR != "ocr" {+ t.Fatalf("ocr_mode = %q, want ocr", gotOCR)+ }+}++func TestParseMinerUV1LegacySelectedWhenTasksReturns400(t *testing.T) {+ orig := minerUV1PollInitial+ minerUV1PollInitial = time.Millisecond+ t.Cleanup(func() { minerUV1PollInitial = orig })++ var (+ mu sync.Mutex+ tasksCalls int+ polls int+ )+ zipBuf := minerUTestZip(t, "doc.md", "# From 4.0 Legacy Via 400 Fallback\n")++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodGet && r.URL.Path == "/v1/health":+ // Health endpoint is present but omits version (decided=false).+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{"status":"ok"}`))+ case r.Method == http.MethodPost && r.URL.Path == "/v1/tasks":+ mu.Lock()+ tasksCalls+++ mu.Unlock()+ // A 4.0 server returns HTTP 400 validation error on the 4.1 manifest.+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusBadRequest)+ _, _ = w.Write([]byte(`{"detail":[{"loc":["body","files",0,"source"],"msg":"field required","type":"value_error.missing"}]}`))+ case r.Method == http.MethodPost && r.URL.Path == "/v1/uploads":+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"id":"up-40","status":"pending","upload_url":"/v1/uploads/up-40/content","upload_method":"PUT"}`))+ case r.Method == http.MethodPut && r.URL.Path == "/v1/uploads/up-40/content":+ w.WriteHeader(http.StatusOK)+ case r.Method == http.MethodPost && r.URL.Path == "/v1/uploads/up-40/complete":+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"id":"up-40","status":"completed","file":{"id":"file-40"}}`))+ case r.Method == http.MethodPost && r.URL.Path == "/v1/parse/jobs":+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"job_id":"job-40","status":"queued"}`))+ case r.Method == http.MethodGet && r.URL.Path == "/v1/parse/jobs/job-40":+ mu.Lock()+ polls+++ n := polls+ mu.Unlock()+ w.Header().Set("Content-Type", "application/json")+ if n < 2 {+ _, _ = w.Write([]byte(`{"job_id":"job-40","status":"running"}`))+ return+ }+ _, _ = w.Write([]byte(`{"job_id":"job-40","status":"completed","files":[{"name":"doc.pdf","status":"completed","output_files":{"zip":{"file_id":"out-zip"},"markdown":{"file_id":"out-md"}}}]}`))+ case r.Method == http.MethodGet && r.URL.Path == "/v1/files/out-zip/content":+ w.Header().Set("Content-Type", "application/zip")+ _, _ = w.Write(zipBuf)+ case r.Method == http.MethodGet && r.URL.Path == "/v1/files/out-md/content":+ _, _ = w.Write([]byte("# From 4.0 Legacy Via 400 Fallback\n"))+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()++ result, err := ParseMinerUV1(context.Background(), server.URL, "secret", "sample.pdf", []byte("%PDF-1.4"), "pipeline", "ocr", 5*time.Second)+ if err != nil {+ t.Fatalf("ParseMinerUV1: %v", err)+ }+ if result.Markdown != "# From 4.0 Legacy Via 400 Fallback\n" {+ t.Fatalf("markdown = %q", result.Markdown)+ }+ mu.Lock()+ defer mu.Unlock()+ if tasksCalls != 1 {+ t.Fatalf("expected /v1/tasks to be called once and return 400, got %d calls", tasksCalls)+ }+}++func TestParseMinerUV1HealthCachedBetweenSupportAndParse(t *testing.T) {+ var healthCalls int+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodGet && r.URL.Path == "/v1/health":+ healthCalls+++ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{"status":"ok","version":"4.0.12"}`))+ case r.Method == http.MethodPost && r.URL.Path == "/v1/uploads":+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"id":"up-1","status":"completed","file":{"id":"file-1"}}`))+ case r.Method == http.MethodPost && r.URL.Path == "/v1/parse/jobs":+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"job_id":"job-1","status":"completed","files":[{"status":"completed","output_files":{"markdown":{"file_id":"md-1"}}}]}`))+ case r.Method == http.MethodGet && r.URL.Path == "/v1/files/md-1/content":+ _, _ = w.Write([]byte("# Cached\n"))+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()++ ctx := context.Background()+ apiKey := "test-cache-key"+ supported, err := MinerUSupportsV1(ctx, server.URL, apiKey)+ if err != nil || !supported {+ t.Fatalf("MinerUSupportsV1: supported=%v, err=%v", supported, err)+ }+ if healthCalls != 1 {+ t.Fatalf("healthCalls after MinerUSupportsV1 = %d, want 1", healthCalls)+ }++ res, err := ParseMinerUV1(ctx, server.URL, apiKey, "test.pdf", []byte("%PDF-1.4"), "pipeline", "auto", 5*time.Second)+ if err != nil {+ t.Fatalf("ParseMinerUV1: %v", err)+ }+ if res.Markdown != "# Cached\n" {+ t.Fatalf("res.Markdown = %q", res.Markdown)+ }+ if healthCalls != 1 {+ t.Fatalf("healthCalls after ParseMinerUV1 = %d, want 1 (should be cached)", healthCalls)+ }+}++func TestParseMinerUTasksMultiFileMarkdownJoined(t *testing.T) {+ orig := minerUV1PollInitial+ minerUV1PollInitial = time.Millisecond+ t.Cleanup(func() { minerUV1PollInitial = orig })++ zip1 := minerUTestZip(t, "part1.md", "# Part 1\n")+ zip2 := minerUTestZip(t, "part2.md", "# Part 2\n")++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodGet && r.URL.Path == "/v1/health":+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{"status":"ok","version":"4.1.0"}`))+ case r.Method == http.MethodPost && r.URL.Path == "/v1/tasks":+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusAccepted)+ _, _ = w.Write([]byte(`{+ "task_id":"task-multi",+ "status":"completed",+ "files":[+ {"file_id":"f1","file_name":"part1.pdf","status":"completed","result_url":"/v1/download/f1.zip"},+ {"file_id":"f2","file_name":"part2.pdf","status":"completed","result_url":"/v1/download/f2.zip"}+ ]+ }`))+ case r.Method == http.MethodGet && r.URL.Path == "/v1/download/f1.zip":+ w.Header().Set("Content-Type", "application/zip")+ _, _ = w.Write(zip1)+ case r.Method == http.MethodGet && r.URL.Path == "/v1/download/f2.zip":+ w.Header().Set("Content-Type", "application/zip")+ _, _ = w.Write(zip2)+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()++ res, err := ParseMinerUV1(context.Background(), server.URL, "secret", "multi.pdf", []byte("%PDF-1.4"), "pipeline", "auto", 5*time.Second)+ if err != nil {+ t.Fatalf("ParseMinerUV1: %v", err)+ }+ expected := "# Part 1\n\n# Part 2\n"+ if res.Markdown != expected {+ t.Fatalf("res.Markdown = %q, want %q", res.Markdown, expected)+ }+ if len(res.Zip) == 0 {+ t.Fatal("expected non-empty zip")+ }+}++func TestMinerUParseSemverAndTasksSupport(t *testing.T) {+ tests := []struct {+ version string+ wantMajor int+ wantMinor int+ wantPatch int+ wantOK bool+ supportsTasks bool+ }{+ {"4.0.12", 4, 0, 12, true, false},+ {"4.0.0", 4, 0, 0, true, false},+ {"4.0", 4, 0, 0, true, false},+ {"v4.0.10", 4, 0, 10, true, false},+ {"4.1.0", 4, 1, 0, true, true},+ {"4.1.2", 4, 1, 2, true, true},+ {"v4.2.0-rc1", 4, 2, 0, true, true},+ {"5.0.0", 5, 0, 0, true, true},+ {"3.0.5", 3, 0, 5, true, false},+ {"invalid", 0, 0, 0, false, false},+ {"", 0, 0, 0, false, false},+ }+ for _, tc := range tests {+ major, minor, patch, ok := minerUParseSemver(tc.version)+ if ok != tc.wantOK {+ t.Errorf("minerUParseSemver(%q) ok = %v, want %v", tc.version, ok, tc.wantOK)+ continue+ }+ if !ok {+ continue+ }+ if major != tc.wantMajor || minor != tc.wantMinor || patch != tc.wantPatch {+ t.Errorf("minerUParseSemver(%q) = (%d, %d, %d), want (%d, %d, %d)", tc.version, major, minor, patch, tc.wantMajor, tc.wantMinor, tc.wantPatch)+ }+ if got := minerUV1VersionSupportsTasks(major, minor); got != tc.supportsTasks {+ t.Errorf("minerUV1VersionSupportsTasks(%d, %d) = %v, want %v", major, minor, got, tc.supportsTasks)+ }+ }+}++func TestParseMinerUV1TasksErrorOnVersion41IsNotMaskedByLegacy(t *testing.T) {+ var legacyCalls atomic.Int32+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodGet && r.URL.Path == "/v1/health":+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{"status":"ok","version":"4.1.0"}`))+ case r.Method == http.MethodPost && r.URL.Path == "/v1/tasks":+ http.Error(w, `{"error":{"code":"invalid_request","message":"bad field"}}`, http.StatusBadRequest)+ case r.Method == http.MethodPost && r.URL.Path == "/v1/uploads":+ legacyCalls.Add(1)+ http.NotFound(w, r)+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()++ _, err := ParseMinerUV1(context.Background(), server.URL, "secret", "sample.pdf", []byte("%PDF-1.4"), "pipeline", "auto", 5*time.Second)+ if err == nil {+ t.Fatal("expected the 400 creation error")+ }+ if !strings.Contains(err.Error(), "400") {+ t.Fatalf("error = %q, want the 400 status", err.Error())+ }+ if legacyCalls.Load() != 0 {+ t.Fatal("legacy cycle must not run for 4.1 server creation failure")+ }+}