Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

fix(agent): host code-exec artifacts instead of leaking base64 into chat (#19853)

euvre45f9aa215aec
diff --git a/internal/agent/component/agent.go b/internal/agent/component/agent.go
index f7e2f6c039..2e650569b5 100644
--- a/internal/agent/component/agent.go
+++ b/internal/agent/component/agent.go
@@ -1138,8 +1138,9 @@ func buildAgentChatModel(ctx context.Context, p AgentParam) (*models.EinoChatMod
// artifactEntry is the shape of a single tool-returned artifact
// surfaced through the Agent's outputs["artifacts"].
type artifactEntry struct {
- Name string `json:"name"`
- URL string `json:"url"`
+ Name string `json:"name"`
+ URL string `json:"url"`
+ MIMEType string `json:"mime_type,omitempty"`
}
// artifactCollectorKey is the context key used to share the
@@ -1283,19 +1284,11 @@ func extractArtifactsFromToolMessage(msg *schema.Message) []artifactEntry {
}
name, _ := m["name"].(string)
url, _ := m["url"].(string)
- if url == "" {
- if content, ok := m["content_b64"].(string); ok && content != "" {
- mime, _ := m["mime_type"].(string)
- if mime == "" {
- mime = "application/octet-stream"
- }
- url = "data:" + mime + ";base64," + content
- }
- }
if name == "" || url == "" {
continue
}
- out = append(out, artifactEntry{Name: name, URL: url})
+ mime, _ := m["mime_type"].(string)
+ out = append(out, artifactEntry{Name: name, URL: url, MIMEType: mime})
}
return out
}
@@ -1334,10 +1327,7 @@ func formatArtifactMarkdown(artifacts []artifactEntry, existingText string) stri
if strings.Contains(existingText, a.URL) {
continue
}
- lower := strings.ToLower(a.URL)
- if strings.HasSuffix(lower, ".png") || strings.HasSuffix(lower, ".jpg") ||
- strings.HasSuffix(lower, ".jpeg") || strings.HasSuffix(lower, ".gif") ||
- strings.HasSuffix(lower, ".webp") {
+ if isImageArtifact(a) {
fmt.Fprintf(&sb, "\n\n![%s](%s)", a.Name, a.URL)
} else {
fmt.Fprintf(&sb, "\n\n[Download %s](%s)", a.Name, a.URL)
@@ -1346,6 +1336,16 @@ func formatArtifactMarkdown(artifacts []artifactEntry, existingText string) stri
return sb.String()
}
+func isImageArtifact(a artifactEntry) bool {
+ if strings.HasPrefix(strings.ToLower(a.MIMEType), "image/") {
+ return true
+ }
+ lower := strings.ToLower(a.URL)
+ return strings.HasSuffix(lower, ".png") || strings.HasSuffix(lower, ".jpg") ||
+ strings.HasSuffix(lower, ".jpeg") || strings.HasSuffix(lower, ".gif") ||
+ strings.HasSuffix(lower, ".webp") || strings.HasSuffix(lower, ".svg")
+}
+
// extractToolCalls converts eino ToolCalls from a message into the
// output map format.
func extractToolCalls(msg *schema.Message) []map[string]any {
diff --git a/internal/agent/component/agent_artifact_test.go b/internal/agent/component/agent_artifact_test.go
index 24e5f750c5..386782727c 100644
--- a/internal/agent/component/agent_artifact_test.go
+++ b/internal/agent/component/agent_artifact_test.go
@@ -139,10 +139,10 @@ func TestAgent_ReActAgent_CollectsArtifactsFromCodeExecTool(t *testing.T) {
}
func TestExtractArtifactsFromToolMessageAcceptsSandboxContent(t *testing.T) {
- msg := &schema.Message{Role: schema.Tool, Content: `{"_ARTIFACTS":[{"name":"chart.png","mime_type":"image/png","content_b64":"aW1hZ2U="}]}`}
+ msg := &schema.Message{Role: schema.Tool, Content: `{"_ARTIFACTS":[{"name":"chart.png","mime_type":"image/png","url":"/api/v1/documents/artifact/abc.png"},{"name":"inline.png","mime_type":"image/png","content_b64":"aW1hZ2U="}]}`}
got := extractArtifactsFromToolMessage(msg)
- if len(got) != 1 || got[0].URL != "data:image/png;base64,aW1hZ2U=" {
- t.Fatalf("got %#v, want sandbox data URL", got)
+ if len(got) != 1 || got[0].URL != "/api/v1/documents/artifact/abc.png" || got[0].MIMEType != "image/png" {
+ t.Fatalf("got %#v, want hosted artifact only", got)
}
}
@@ -154,8 +154,8 @@ func TestArtifactCollectorPreparedByInvokeReceivesRunnerFuture(t *testing.T) {
}
recordArtifactsFromToolMessage(ctx, &schema.Message{Role: schema.Tool, Content: `{"_ARTIFACTS":[{"name":"chart.png","mime_type":"image/png","content_b64":"aW1hZ2U="}]}`})
got := collectArtifactsFromToolCalls(ctx, nil)
- if len(got) != 1 || got[0].URL != "data:image/png;base64,aW1hZ2U=" {
- t.Fatalf("got %#v, want streamed sandbox artifact", got)
+ if len(got) != 0 {
+ t.Fatalf("got %#v, want no artifacts without a hosted URL", got)
}
}
diff --git a/internal/agent/component/artifact_markdown_test.go b/internal/agent/component/artifact_markdown_test.go
index 4e5f88b65b..402166d111 100644
--- a/internal/agent/component/artifact_markdown_test.go
+++ b/internal/agent/component/artifact_markdown_test.go
@@ -55,6 +55,19 @@ func TestFormatArtifactMarkdown_DownloadLink(t *testing.T) {
}
}
+// TestFormatArtifactMarkdown_ImageMIMEType: an image/ MIME type wins
+// over the URL extension, matching the Python collector's routing.
+func TestFormatArtifactMarkdown_ImageMIMEType(t *testing.T) {
+ arts := []artifactEntry{
+ {Name: "chart.bin", URL: "/api/v1/documents/artifact/1ae8d553478544628bb8be267d502371.bin", MIMEType: "image/png"},
+ }
+ got := formatArtifactMarkdown(arts, "answer")
+ want := "\n\n![chart.bin](/api/v1/documents/artifact/1ae8d553478544628bb8be267d502371.bin)"
+ if got != want {
+ t.Errorf("got %q, want %q", got, want)
+ }
+}
+
// TestFormatArtifactMarkdown_DedupesAgainstExistingText: if the URL is
// already in the answer, the artifact link is omitted.
func TestFormatArtifactMarkdown_DedupesAgainstExistingText(t *testing.T) {
diff --git a/internal/agent/tool/code_exec.go b/internal/agent/tool/code_exec.go
index 8c86fc5d07..283f827b4d 100644
--- a/internal/agent/tool/code_exec.go
+++ b/internal/agent/tool/code_exec.go
@@ -18,16 +18,20 @@ package tool
import (
"context"
+ "encoding/base64"
"encoding/json"
"errors"
"fmt"
"os"
+ "path/filepath"
"strings"
"ragflow/internal/common"
+ "ragflow/internal/storage"
"github.com/cloudwego/eino/components/tool"
"github.com/cloudwego/eino/schema"
+ "github.com/google/uuid"
"go.uber.org/zap"
)
@@ -166,7 +170,7 @@ func (c *CodeExecTool) InvokableRun(ctx context.Context, argumentsInJSON string,
// ReAct loop instead of prompting retries against broken infrastructure.
return codeExecStubResult(err.Error()), err
}
- out, mErr := codeExecResultJSON(resp)
+ out, mErr := codeExecResultJSON(ctx, resp)
if mErr != nil {
return codeExecStubResult(mErr.Error()), mErr
}
@@ -182,9 +186,10 @@ func (c *CodeExecTool) InvokableRun(ctx context.Context, argumentsInJSON string,
// us back" field).
// - StructuredResult["actual_type"] → ActualType (Python
// `infer_actual_type` surface for downstream Message component).
-// - Metadata["artifacts"] → Artifacts (the model AND the Message
-// component's `_ARTIFACTS` collector both consume this; we
-// surface it as `_ARTIFACTS` to match the Python envelope).
+// - Metadata["artifacts"] → Artifacts, published to the sandbox
+// artifact bucket and exposed as `_ARTIFACTS` references
+// ({name, url, mime_type, size}); the blob payload stays out of
+// the model-visible envelope.
// - Metadata["attachments"] → Attachments (rendered into
// downstream Markdown by Message via the same path the Agent
// tool artifact Markdown uses).
@@ -193,7 +198,7 @@ func (c *CodeExecTool) InvokableRun(ctx context.Context, argumentsInJSON string,
// other than map[string]any) are silently dropped with a log
// warning. This matches the Python tool's "skip on shape mismatch"
// semantics — better to lose one artifact than to abort the run.
-func codeExecResultJSON(r *SandboxResponse) (string, error) {
+func codeExecResultJSON(ctx context.Context, r *SandboxResponse) (string, error) {
if r == nil {
return codeExecStubResult("empty response"), nil
}
@@ -203,7 +208,7 @@ func codeExecResultJSON(r *SandboxResponse) (string, error) {
Stderr: r.Stderr,
}
if r.Metadata != nil {
- out.Artifacts = extractArtifactList(r.Metadata, "artifacts")
+ out.Artifacts = publishSandboxArtifacts(ctx, extractArtifactList(r.Metadata, "artifacts"))
out.Attachments = extractArtifactList(r.Metadata, "attachments")
}
hasStructuredResult := false
@@ -240,6 +245,91 @@ func codeExecResultJSON(r *SandboxResponse) (string, error) {
return string(b), nil
}
+// publishSandboxArtifacts turns sandbox artifact descriptors into
+// hosted references: each blob is uploaded to the sandbox artifact
+// bucket and the entry keeps only {name, url, mime_type, size}, so
+// raw base64 never enters the model-visible envelope or the final
+// chat message. Entries that cannot be published are dropped — the
+// /api/v1/documents/artifact route only serves uploaded objects.
+func publishSandboxArtifacts(ctx context.Context, artifacts []map[string]any) []map[string]any {
+ if len(artifacts) == 0 {
+ return nil
+ }
+ published := make([]map[string]any, 0, len(artifacts))
+ for _, art := range artifacts {
+ if entry := publishSandboxArtifact(ctx, art); entry != nil {
+ published = append(published, entry)
+ }
+ }
+ if len(published) == 0 {
+ return nil
+ }
+ return published
+}
+
+func publishSandboxArtifact(ctx context.Context, art map[string]any) map[string]any {
+ name, _ := art["name"].(string)
+ if name == "" {
+ return nil
+ }
+ mime, _ := art["mime_type"].(string)
+ if url, _ := art["url"].(string); url != "" {
+ if strings.HasPrefix(strings.ToLower(strings.TrimSpace(url)), "data:") {
+ fmt.Fprintf(os.Stderr, "code_exec: artifact %q carries an inline data: url; dropping\n", name)
+ return nil
+ }
+ return map[string]any{"name": name, "url": url, "mime_type": mime, "size": art["size"]}
+ }
+ contentB64, _ := art["content_b64"].(string)
+ if contentB64 == "" {
+ return nil
+ }
+ storageExt := sandboxArtifactStorageExt(name, mime)
+ if storageExt == "" {
+ fmt.Fprintf(os.Stderr, "code_exec: artifact %q (mime %q) has no servable file type; dropping\n", name, mime)
+ return nil
+ }
+ blob, err := base64.StdEncoding.DecodeString(contentB64)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "code_exec: artifact %q is not valid base64: %v; dropping\n", name, err)
+ return nil
+ }
+ impl := storage.GetStorageFactory().GetStorage()
+ if impl == nil {
+ fmt.Fprintf(os.Stderr, "code_exec: storage not initialized; dropping artifact %q\n", name)
+ return nil
+ }
+ storageName := uuid.NewString() + storageExt
+ if err := impl.Put(ctx, common.SandboxArtifactBucket(), storageName, blob); err != nil {
+ fmt.Fprintf(os.Stderr, "code_exec: upload artifact %q: %v; dropping\n", name, err)
+ return nil
+ }
+ return map[string]any{
+ "name": name,
+ "url": "/api/v1/documents/artifact/" + storageName,
+ "mime_type": mime,
+ "size": art["size"],
+ }
+}
+
+// sandboxArtifactStorageExt picks the extension the artifact route
+// serves: the descriptor's own extension when it is servable, else one
+// derived from the MIME type.
+func sandboxArtifactStorageExt(name, mime string) string {
+ if ext := strings.ToLower(filepath.Ext(name)); ext != "" {
+ if _, ok := common.SandboxArtifactContentTypes[ext]; ok {
+ return ext
+ }
+ }
+ m := strings.ToLower(strings.TrimSpace(mime))
+ for ext, contentType := range common.SandboxArtifactContentTypes {
+ if contentType == m {
+ return ext
+ }
+ }
+ return ""
+}
+
// extractArtifactList pulls a list of dict-shaped entries out of
// Metadata[key]. Items that aren't map[string]any are dropped with
// a stderr log line so the operator can see the data loss without
diff --git a/internal/agent/tool/code_exec_test.go b/internal/agent/tool/code_exec_test.go
index 92aa53596d..3c3d1dee84 100644
--- a/internal/agent/tool/code_exec_test.go
+++ b/internal/agent/tool/code_exec_test.go
@@ -17,11 +17,16 @@
package tool
import (
+ "bytes"
"context"
+ "encoding/base64"
"encoding/json"
"errors"
"strings"
"testing"
+
+ "ragflow/internal/common"
+ "ragflow/internal/storage"
)
func TestCodeExec_StubsErrorWhenClientMissing(t *testing.T) {
@@ -178,10 +183,9 @@ func TestCodeExec_Info(t *testing.T) {
}
// TestCodeExec_ResultExtractsArtifacts pins the artifact
-// collection: SandboxResponse.Metadata["artifacts"] must be
-// surfaced as `_ARTIFACTS` in the tool's JSON envelope so the
-// Message
-// component's artifact Markdown formatter can render them.
+// collection: SandboxResponse.Metadata["artifacts"] entries that
+// already carry a hosted URL surface unchanged as `_ARTIFACTS` in
+// the tool's JSON envelope.
func TestCodeExec_ResultExtractsArtifacts(t *testing.T) {
t.Parallel()
@@ -195,7 +199,7 @@ func TestCodeExec_ResultExtractsArtifacts(t *testing.T) {
},
},
}
- out, err := codeExecResultJSON(resp)
+ out, err := codeExecResultJSON(t.Context(), resp)
if err != nil {
t.Fatalf("codeExecResultJSON: %v", err)
}
@@ -209,6 +213,9 @@ func TestCodeExec_ResultExtractsArtifacts(t *testing.T) {
if got.Artifacts[0]["name"] != "chart.png" {
t.Errorf("Artifacts[0][name] = %v, want chart.png", got.Artifacts[0]["name"])
}
+ if got.Artifacts[0]["url"] != "minio://b/chart.png" {
+ t.Errorf("Artifacts[0][url] = %v, want minio://b/chart.png", got.Artifacts[0]["url"])
+ }
}
// TestCodeExec_ResultExtractsArtifactsFromProviderShape pins the
@@ -250,8 +257,8 @@ func TestCodeExec_ResultExtractsArtifactsFromProviderShape(t *testing.T) {
}
// TestCodeExec_ResultDropsBadArtifactShape ensures the extractor
-// silently drops entries that aren't map[string]any rather than
-// aborting the run.
+// silently drops entries that aren't map[string]any, and entries
+// without a URL or uploadable payload, rather than aborting the run.
func TestCodeExec_ResultDropsBadArtifactShape(t *testing.T) {
t.Parallel()
@@ -260,12 +267,12 @@ func TestCodeExec_ResultDropsBadArtifactShape(t *testing.T) {
Metadata: map[string]any{
"artifacts": []any{
"just a string", // bad shape
- map[string]any{"name": "ok.png"}, // good
+ map[string]any{"name": "ok.png"}, // no url, no content_b64
42, // bad shape
},
},
}
- out, err := codeExecResultJSON(resp)
+ out, err := codeExecResultJSON(t.Context(), resp)
if err != nil {
t.Fatalf("codeExecResultJSON: %v", err)
}
@@ -273,11 +280,171 @@ func TestCodeExec_ResultDropsBadArtifactShape(t *testing.T) {
if jerr := json.Unmarshal([]byte(out), &got); jerr != nil {
t.Fatalf("output not valid JSON: %v", jerr)
}
- if len(got.Artifacts) != 1 {
- t.Errorf("Artifacts len = %d, want 1 (bad shapes dropped)", len(got.Artifacts))
+ if len(got.Artifacts) != 0 {
+ t.Errorf("Artifacts len = %d, want 0 (unpublishable dropped)", len(got.Artifacts))
+ }
+}
+
+// TestCodeExec_UploadsArtifactBlobs pins the base64-leak fix: sandbox
+// artifact payloads must be uploaded to the sandbox artifact bucket
+// and referenced by /api/v1/documents/artifact/<uuid><ext> URLs, with
+// the raw content_b64 kept out of the model-visible envelope.
+func TestCodeExec_UploadsArtifactBlobs(t *testing.T) {
+ factory := storage.GetStorageFactory()
+ prev := factory.GetStorage()
+ mem := storage.NewMemoryStorage()
+ factory.SetStorage(mem)
+ t.Cleanup(func() { factory.SetStorage(prev) })
+
+ png := []byte("fake-png-bytes")
+ encoded := base64.StdEncoding.EncodeToString(png)
+ resp := &SandboxResponse{
+ Returned: "ok",
+ Metadata: map[string]any{
+ "artifacts": []any{
+ map[string]any{
+ "name": "sales_trend.png",
+ "content_b64": encoded,
+ "mime_type": "image/png",
+ "size": float64(len(png)),
+ },
+ map[string]any{
+ "name": "pre-hosted.png",
+ "url": "minio://b/pre-hosted.png",
+ "content_b64": encoded,
+ "mime_type": "image/png",
+ },
+ },
+ },
+ }
+ out, err := codeExecResultJSON(t.Context(), resp)
+ if err != nil {
+ t.Fatalf("codeExecResultJSON: %v", err)
+ }
+ if strings.Contains(out, "content_b64") || strings.Contains(out, encoded) {
+ t.Fatalf("envelope leaks artifact base64: %s", out)
+ }
+ var got codeExecResult
+ if jerr := json.Unmarshal([]byte(out), &got); jerr != nil {
+ t.Fatalf("output not valid JSON: %v (raw=%s)", jerr, out)
+ }
+ if len(got.Artifacts) != 2 {
+ t.Fatalf("Artifacts len = %d, want 2", len(got.Artifacts))
+ }
+ uploaded, _ := got.Artifacts[0]["url"].(string)
+ if !strings.HasPrefix(uploaded, "/api/v1/documents/artifact/") || !strings.HasSuffix(uploaded, ".png") {
+ t.Errorf("Artifacts[0][url] = %q, want hosted artifact URL", uploaded)
+ }
+ if m, _ := got.Artifacts[0]["mime_type"].(string); m != "image/png" {
+ t.Errorf("Artifacts[0][mime_type] = %v, want image/png", got.Artifacts[0]["mime_type"])
+ }
+ if hosted, _ := got.Artifacts[1]["url"].(string); hosted != "minio://b/pre-hosted.png" {
+ t.Errorf("Artifacts[1][url] = %v, want passthrough of existing url", got.Artifacts[1]["url"])
+ }
+
+ objName := strings.TrimPrefix(uploaded, "/api/v1/documents/artifact/")
+ data, gerr := mem.Get(t.Context(), common.SandboxArtifactBucket(), objName)
+ if gerr != nil || !bytes.Equal(data, png) {
+ t.Errorf("stored object %q = (%v, %v), want uploaded blob", objName, data, gerr)
+ }
+}
+
+// TestCodeExec_DropsDataURLArtifacts pins that inline data: urls are
+// dropped instead of passed through as hosted references — a data: url
+// would put its base64 payload back into the model-visible envelope
+// and the rendered chat message.
+func TestCodeExec_DropsDataURLArtifacts(t *testing.T) {
+ t.Parallel()
+
+ resp := &SandboxResponse{
+ Returned: "ok",
+ Metadata: map[string]any{
+ "artifacts": []any{
+ map[string]any{
+ "name": "inline.png",
+ "url": "data:image/png;base64,iVBORw0KGgo=",
+ "mime_type": "image/png",
+ },
+ map[string]any{"name": "hosted.png", "url": "minio://b/hosted.png"},
+ },
+ },
+ }
+ out, err := codeExecResultJSON(t.Context(), resp)
+ if err != nil {
+ t.Fatalf("codeExecResultJSON: %v", err)
+ }
+ if strings.Contains(out, "data:") || strings.Contains(out, "iVBORw0KGgo") {
+ t.Fatalf("envelope leaks inline artifact data: %s", out)
}
- if got.Artifacts[0]["name"] != "ok.png" {
- t.Errorf("Artifacts[0][name] = %v, want ok.png", got.Artifacts[0]["name"])
+ var got codeExecResult
+ if jerr := json.Unmarshal([]byte(out), &got); jerr != nil {
+ t.Fatalf("output is not valid JSON: %v (raw=%s)", jerr, out)
+ }
+ if len(got.Artifacts) != 1 || got.Artifacts[0]["name"] != "hosted.png" {
+ t.Fatalf("Artifacts = %#v, want only the hosted entry", got.Artifacts)
+ }
+}
+
+// TestCodeExec_UploadsArtifactWithDerivedExtension pins that every
+// published URL carries an extension the artifact route serves: names
+// without a servable extension fall back to one derived from the
+// MIME type, and descriptors with neither are dropped.
+func TestCodeExec_UploadsArtifactWithDerivedExtension(t *testing.T) {
+ factory := storage.GetStorageFactory()
+ prev := factory.GetStorage()
+ mem := storage.NewMemoryStorage()
+ factory.SetStorage(mem)
+ t.Cleanup(func() { factory.SetStorage(prev) })
+
+ pdf := []byte("%PDF-fake")
+ encoded := base64.StdEncoding.EncodeToString(pdf)
+ resp := &SandboxResponse{
+ Returned: "ok",
+ Metadata: map[string]any{
+ "artifacts": []any{
+ map[string]any{
+ "name": "report",
+ "content_b64": encoded,
+ "mime_type": "application/pdf",
+ "size": float64(len(pdf)),
+ },
+ map[string]any{
+ "name": "dump.bin",
+ "content_b64": encoded,
+ "mime_type": "text/csv",
+ },
+ map[string]any{
+ "name": "mystery.blob",
+ "content_b64": encoded,
+ },
+ },
+ },
+ }
+ out, err := codeExecResultJSON(t.Context(), resp)
+ if err != nil {
+ t.Fatalf("codeExecResultJSON: %v", err)
+ }
+ var got codeExecResult
+ if jerr := json.Unmarshal([]byte(out), &got); jerr != nil {
+ t.Fatalf("output is not valid JSON: %v (raw=%s)", jerr, out)
+ }
+ if len(got.Artifacts) != 2 {
+ t.Fatalf("Artifacts len = %d, want 2 (unservable descriptor dropped)", len(got.Artifacts))
+ }
+ url0, _ := got.Artifacts[0]["url"].(string)
+ if !strings.HasPrefix(url0, "/api/v1/documents/artifact/") || !strings.HasSuffix(url0, ".pdf") {
+ t.Errorf("Artifacts[0][url] = %q, want hosted URL ending in .pdf", url0)
+ }
+ url1, _ := got.Artifacts[1]["url"].(string)
+ if !strings.HasSuffix(url1, ".csv") {
+ t.Errorf("Artifacts[1][url] = %q, want extension derived from text/csv", url1)
+ }
+ for _, u := range []string{url0, url1} {
+ objName := strings.TrimPrefix(u, "/api/v1/documents/artifact/")
+ data, gerr := mem.Get(t.Context(), common.SandboxArtifactBucket(), objName)
+ if gerr != nil || !bytes.Equal(data, pdf) {
+ t.Errorf("stored object %q = (%v, %v), want uploaded blob", objName, data, gerr)
+ }
}
}
@@ -295,7 +462,7 @@ func TestCodeExec_ResultExtractsAttachments(t *testing.T) {
},
},
}
- out, err := codeExecResultJSON(resp)
+ out, err := codeExecResultJSON(t.Context(), resp)
if err != nil {
t.Fatalf("codeExecResultJSON: %v", err)
}
@@ -322,7 +489,7 @@ func TestCodeExec_ResultSurfacesActualType(t *testing.T) {
},
},
}
- out, err := codeExecResultJSON(resp)
+ out, err := codeExecResultJSON(t.Context(), resp)
if err != nil {
t.Fatalf("codeExecResultJSON: %v", err)
}
@@ -348,7 +515,7 @@ func TestCodeExec_ResultUsesStructuredResultValue(t *testing.T) {
"value": float64(8),
},
}
- out, err := codeExecResultJSON(resp)
+ out, err := codeExecResultJSON(t.Context(), resp)
if err != nil {
t.Fatalf("codeExecResultJSON: %v", err)
}
@@ -373,7 +540,7 @@ func TestCodeExec_ResultFallsBackToStdoutJSON(t *testing.T) {
resp := &SandboxResponse{
Stdout: `{"a":[1,2]}`,
}
- out, err := codeExecResultJSON(resp)
+ out, err := codeExecResultJSON(t.Context(), resp)
if err != nil {
t.Fatalf("codeExecResultJSON: %v", err)
}
diff --git a/internal/common/environments.go b/internal/common/environments.go
index 24387050d5..c3f2a80efa 100644
--- a/internal/common/environments.go
+++ b/internal/common/environments.go
@@ -31,6 +31,31 @@ func GetEnvSmall(key string) string {
return strings.ToLower(GetEnv(key))
}
+// SandboxArtifactBucket is the object-storage bucket that holds
+// code-exec sandbox artifacts, served back through
+// /api/v1/documents/artifact/<name>.
+func SandboxArtifactBucket() string {
+ if bucket := GetEnv(EnvSandboxArtifactBucket); bucket != "" {
+ return bucket
+ }
+ return "sandbox-artifacts"
+}
+
+// SandboxArtifactContentTypes maps the sandbox-artifact file extensions
+// the /api/v1/documents/artifact route serves to response content
+// types. Artifact publication derives storage-name extensions from the
+// same table so every published URL resolves to a servable type.
+var SandboxArtifactContentTypes = map[string]string{
+ ".png": "image/png",
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".svg": "image/svg+xml",
+ ".pdf": "application/pdf",
+ ".csv": "text/csv",
+ ".json": "application/json",
+ ".html": "text/html",
+}
+
func IsLLMDebugEnabled() bool {
enabled, err := strconv.ParseBool(strings.TrimSpace(GetEnv(EnvLLMDebug)))
return err == nil && enabled
diff --git a/internal/service/document/document.go b/internal/service/document/document.go
index e219e93c4e..a416890053 100644
--- a/internal/service/document/document.go
+++ b/internal/service/document/document.go
@@ -185,17 +185,6 @@ var (
ErrPreviewFileEmpty = errors.New("preview file empty")
)
-var artifactContentTypes = map[string]string{
- ".png": "image/png",
- ".jpg": "image/jpeg",
- ".jpeg": "image/jpeg",
- ".svg": "image/svg+xml",
- ".pdf": "application/pdf",
- ".csv": "text/csv",
- ".json": "application/json",
- ".html": "text/html",
-}
-
var artifactForceAttachmentExtensions = map[string]struct{}{
".htm": {},
".html": {},
diff --git a/internal/service/document/document_artifact.go b/internal/service/document/document_artifact.go
index 7b4f030a6c..a9ff1dda2f 100644
--- a/internal/service/document/document_artifact.go
+++ b/internal/service/document/document_artifact.go
@@ -44,7 +44,7 @@ func (s *DocumentService) GetDocumentArtifact(ctx context.Context, filename, use
}
ext := strings.ToLower(filepath.Ext(basename))
- contentType, ok := artifactContentTypes[ext]
+ contentType, ok := common.SandboxArtifactContentTypes[ext]
if !ok {
return nil, ErrArtifactInvalidFileType
}
@@ -60,7 +60,7 @@ func (s *DocumentService) GetDocumentArtifact(ctx context.Context, filename, use
return nil, fmt.Errorf("storage not initialized")
}
- bucket := sandboxArtifactBucket()
+ bucket := common.SandboxArtifactBucket()
if !storageImpl.ObjExist(ctx, bucket, basename) {
return nil, ErrArtifactNotFound
}
@@ -168,13 +168,6 @@ func (s *DocumentService) sandboxArtifactAccessible(ctx context.Context, filenam
return false
}
-func sandboxArtifactBucket() string {
- if bucket := common.GetEnv(common.EnvSandboxArtifactBucket); bucket != "" {
- return bucket
- }
- return "sandbox-artifacts"
-}
-
// sanitizeArtifactFilename scrubs characters that are unsafe inside a storage
// object key for sandbox artifacts. It intentionally only replaces the
// artifact-specific unsafe set (artifactUnsafeFilenameChars) and does NOT strip
diff --git a/internal/service/document/document_test.go b/internal/service/document/document_test.go
index 1db7aec67a..6b2351f305 100644
--- a/internal/service/document/document_test.go
+++ b/internal/service/document/document_test.go
@@ -3596,7 +3596,7 @@ func TestGetDocumentArtifact_AuthGate(t *testing.T) {
mockStorage := useFakeStorage(t)
data := []byte("artifact content")
- if err := mockStorage.Put(ctx, sandboxArtifactBucket(), "result.png", data); err != nil {
+ if err := mockStorage.Put(ctx, common.SandboxArtifactBucket(), "result.png", data); err != nil {
t.Fatalf("seed artifact: %v", err)
}