diff --git a/go/adk/pkg/a2a/converter.go b/go/adk/pkg/a2a/converter.go
index 5f77e74d28..48a82162c4 100644
--- a/go/adk/pkg/a2a/converter.go
+++ b/go/adk/pkg/a2a/converter.go
@@ -47,7 +47,7 @@ func a2aPartConverter(_ context.Context, _ a2atype.Event, part *a2atype.Part) (*
}
// keepFileName copies a non-image file's name into PartMetadata, which survives ADK blanking DisplayName.
-// Vertex rejects PartMetadata; this is safe only because the file wrapper replaces these parts.
+// Vertex rejects PartMetadata, but Gemini never gets these parts: the file wrapper turns them into text.
func keepFileName(p *genai.Part) {
if p == nil || p.InlineData == nil || p.InlineData.DisplayName == "" || strings.HasPrefix(p.InlineData.MIMEType, "image/") {
return
diff --git a/go/adk/pkg/fileextract/llm.go b/go/adk/pkg/fileextract/llm.go
index 03a8215ebc..954f1b5901 100644
--- a/go/adk/pkg/fileextract/llm.go
+++ b/go/adk/pkg/fileextract/llm.go
@@ -11,8 +11,8 @@ import (
"google.golang.org/genai"
)
-// WithFileText wraps an LLM so every provider receives non-image file blobs as
-// extracted text; images pass through for the adapter to handle.
+// WithFileText wraps an LLM so user files that the provider cannot read reach it as text.
+// Images, and parts the adapter sends itself (see FileSender), are not changed.
func WithFileText(llm model.LLM) model.LLM {
if g, ok := llm.(googleLLM); ok {
return googleFileTextLLM{fileTextLLM{llm}, g}
@@ -31,7 +31,34 @@ type googleFileTextLLM struct {
}
func (m fileTextLLM) GenerateContent(ctx context.Context, req *model.LLMRequest, stream bool) iter.Seq2[*model.LLMResponse, error] {
- return m.LLM.GenerateContent(ctx, filesToText(req), stream)
+ return m.LLM.GenerateContent(ctx, filesToText(req, m.LLM), stream)
+}
+
+// FileSender is a model whose adapter sends some user file parts to its provider
+// as they are: a document as bytes, or a link the provider fetches itself.
+type FileSender interface{ ProviderAccepts(p *genai.Part) bool }
+
+// providerAccepts reports whether llm's provider takes p as it is, through llm's adapter.
+func providerAccepts(llm model.LLM, p *genai.Part) bool {
+ if s, ok := llm.(FileSender); ok {
+ return s.ProviderAccepts(p)
+ }
+ // Gemini takes a link as genai FileData, as it is.
+ _, google := llm.(googleLLM)
+ return google && p.FileData != nil
+}
+
+// newestUserTurn is the index of the last user content, or -1. Only a file there
+// may fail the request: one in replayed history would fail every later turn.
+// ADK sends tool results as user content, so those are not a user turn.
+func newestUserTurn(contents []*genai.Content) int {
+ for i, c := range slices.Backward(contents) {
+ if c != nil && strings.TrimSpace(c.Role) == genai.RoleUser &&
+ !slices.ContainsFunc(c.Parts, func(p *genai.Part) bool { return p != nil && p.FunctionResponse != nil }) {
+ return i
+ }
+ }
+ return -1
}
// FilenameMetadataKey is the PartMetadata key the A2A converter stores a file's name under.
@@ -54,41 +81,62 @@ func isDataPart(b *genai.Blob) bool {
bytes.HasPrefix(data, []byte("")) && bytes.HasSuffix(data, []byte(""))
}
-// filesToText returns req with user file blobs replaced by text, copying only the
-// contents and parts it changes so the caller's session history is untouched.
-func filesToText(req *model.LLMRequest) *model.LLMRequest {
+// filesToText returns req with the files in each user turn changed to a form the
+// provider reads (see turnFilesToText). It never changes req, which holds the
+// session history, and returns req itself when there is nothing to change.
+func filesToText(req *model.LLMRequest, llm model.LLM) *model.LLMRequest {
if req == nil {
return req
}
- var contents []*genai.Content
+ out := *req
+ out.Contents = slices.Clone(req.Contents)
+ newest := newestUserTurn(req.Contents)
for i, c := range req.Contents {
if c == nil || c.Role != genai.RoleUser {
continue
}
- var parts []*genai.Part
- for j, p := range c.Parts {
- if p == nil || p.InlineData == nil || strings.HasPrefix(p.InlineData.MIMEType, "image/") || isDataPart(p.InlineData) {
- continue
- }
- if parts == nil {
- parts = slices.Clone(c.Parts)
- }
- parts[j] = genai.NewPartFromText(inlineFileToText(p.InlineData, partFileName(p)))
- }
- if parts == nil {
- continue
- }
- if contents == nil {
- contents = slices.Clone(req.Contents)
+ if parts := turnFilesToText(c.Parts, llm, i == newest); !slices.Equal(parts, c.Parts) {
+ turn := *c
+ turn.Parts = parts
+ out.Contents[i] = &turn
}
- changed := *c
- changed.Parts = parts
- contents[i] = &changed
}
- if contents == nil {
+ if slices.Equal(out.Contents, req.Contents) {
return req
}
- out := *req
- out.Contents = contents
return &out
}
+
+// turnFilesToText returns a new list of the parts of one user turn, with each file
+// that the provider cannot read changed to text. A link stays a link only in the
+// newest user turn: the provider fetches it on each request, so a link that breaks
+// in an older turn would fail every later turn.
+func turnFilesToText(parts []*genai.Part, llm model.LLM, newest bool) []*genai.Part {
+ var out []*genai.Part
+ for _, p := range parts {
+ switch {
+ case p == nil || providerAccepts(llm, p) && (newest || p.FileData == nil):
+ // The model's adapter sends it as it is.
+ out = append(out, p)
+ case p.FileData != nil:
+ // A link: the bare URL, so the agent's fetch tool can read it, or nothing when
+ // the text already has the URL. Not "File: name (url)": with that, models
+ // invented the file's contents.
+ if !hasText(parts, p.FileData.FileURI) {
+ out = append(out, genai.NewPartFromText(p.FileData.FileURI))
+ }
+ case p.InlineData != nil && !strings.HasPrefix(p.InlineData.MIMEType, "image/") && !isDataPart(p.InlineData):
+ // A document as bytes: its text, or a note that it could not be read.
+ out = append(out, genai.NewPartFromText(inlineFileToText(p.InlineData, partFileName(p))))
+ default:
+ // Text, images, A2A data parts and tool calls.
+ out = append(out, p)
+ }
+ }
+ return out
+}
+
+// hasText reports whether a text part in parts contains s.
+func hasText(parts []*genai.Part, s string) bool {
+ return slices.ContainsFunc(parts, func(p *genai.Part) bool { return p != nil && strings.Contains(p.Text, s) })
+}
diff --git a/go/adk/pkg/fileextract/llm_test.go b/go/adk/pkg/fileextract/llm_test.go
index 158fb20c2c..41d1302e51 100644
--- a/go/adk/pkg/fileextract/llm_test.go
+++ b/go/adk/pkg/fileextract/llm_test.go
@@ -3,6 +3,7 @@ package fileextract
import (
"context"
"iter"
+ "slices"
"strings"
"testing"
@@ -96,6 +97,109 @@ func TestWithFileText_LeavesDataPartsNextToFiles(t *testing.T) {
}
}
+// pdfSendingLLM sends pdf bytes and links itself, like the OpenAI Responses adapter.
+type pdfSendingLLM struct{ recordingLLM }
+
+func (*pdfSendingLLM) ProviderAccepts(p *genai.Part) bool {
+ return p.FileData != nil || p.InlineData != nil && p.InlineData.MIMEType == "application/pdf"
+}
+
+func TestWithFileText_LeavesFilesTheModelSends(t *testing.T) {
+ pdf := &genai.Part{InlineData: &genai.Blob{Data: []byte("%PDF"), MIMEType: "application/pdf", DisplayName: "report.pdf"}}
+ link := &genai.Part{FileData: &genai.FileData{FileURI: "https://files.example.com/report.pdf"}}
+ req := &model.LLMRequest{Contents: []*genai.Content{{Role: genai.RoleUser, Parts: []*genai.Part{pdf, link}}}}
+
+ sender := &pdfSendingLLM{}
+ for range WithFileText(sender).GenerateContent(t.Context(), req, false) {
+ }
+ if sender.got != req {
+ t.Errorf("request with files the model sends was changed: %+v", sender.got.Contents[0].Parts)
+ }
+
+ other := &recordingLLM{}
+ pdfOnly := &model.LLMRequest{Contents: []*genai.Content{{Role: genai.RoleUser, Parts: []*genai.Part{pdf}}}}
+ for range WithFileText(other).GenerateContent(t.Context(), pdfOnly, false) {
+ }
+ if got := other.got.Contents[0].Parts[0].Text; !strings.Contains(got, "could not be read") {
+ t.Errorf("pdf for a model that cannot send it = %q, want the could-not-be-read note", got)
+ }
+}
+
+func TestWithFileText_LinkStaysAfterToolCall(t *testing.T) {
+ link := &genai.Part{FileData: &genai.FileData{FileURI: "https://files.example.com/report.pdf"}}
+ req := &model.LLMRequest{Contents: []*genai.Content{
+ {Role: genai.RoleUser, Parts: []*genai.Part{genai.NewPartFromText("read this"), link}},
+ {Role: genai.RoleModel, Parts: []*genai.Part{genai.NewPartFromFunctionCall("fetch", nil)}},
+ {Role: genai.RoleUser, Parts: []*genai.Part{genai.NewPartFromFunctionResponse("fetch", nil)}},
+ }}
+ sender := &pdfSendingLLM{}
+ for range WithFileText(sender).GenerateContent(t.Context(), req, false) {
+ }
+ if sender.got != req {
+ t.Errorf("a tool result made the link turn an older turn: %+v", sender.got.Contents[0].Parts)
+ }
+}
+
+func TestWithFileText_Links(t *testing.T) {
+ const url = "https://files.example.com/report.pdf"
+ link := &genai.Part{FileData: &genai.FileData{FileURI: url}}
+ user := func(parts ...*genai.Part) *genai.Content { return &genai.Content{Role: genai.RoleUser, Parts: parts} }
+ texts := func(c *genai.Content) (out []string) {
+ for _, p := range c.Parts {
+ if p.FileData != nil {
+ p = genai.NewPartFromText("")
+ }
+ out = append(out, p.Text)
+ }
+ return out
+ }
+
+ sender, google, other := &pdfSendingLLM{}, &googleRecordingLLM{}, &recordingLLM{}
+ for _, m := range []struct {
+ name string
+ llm model.LLM
+ rec *recordingLLM
+ sendsLink bool
+ }{
+ {"model that sends links (OpenAI Responses)", sender, &sender.recordingLLM, true},
+ {"Gemini", google, &google.recordingLLM, true},
+ {"model that cannot send links", other, other, false},
+ } {
+ for name, tc := range map[string]struct {
+ turn *genai.Content
+ want []string
+ }{
+ "link becomes its URL": {user(genai.NewPartFromText("read this"), link), []string{"read this", url}},
+ "link already in the text is dropped": {user(genai.NewPartFromText("read "+url), link), []string{"read " + url}},
+ } {
+ t.Run(m.name+"/"+name, func(t *testing.T) {
+ // The same turn as replayed history and as the newest turn.
+ req := &model.LLMRequest{Contents: []*genai.Content{
+ tc.turn,
+ {Role: genai.RoleModel, Parts: []*genai.Part{genai.NewPartFromText("ok")}},
+ tc.turn,
+ }}
+ for range WithFileText(m.llm).GenerateContent(t.Context(), req, false) {
+ }
+ wantNewest := tc.want
+ if m.sendsLink {
+ wantNewest = texts(tc.turn) // the newest turn keeps its link
+ }
+ got := m.rec.got.Contents
+ if older := texts(got[0]); !slices.Equal(older, tc.want) {
+ t.Errorf("older turn = %q, want %q", older, tc.want)
+ }
+ if newest := texts(got[2]); !slices.Equal(newest, wantNewest) {
+ t.Errorf("newest turn = %q, want %q", newest, wantNewest)
+ }
+ if len(tc.turn.Parts) != 2 || tc.turn.Parts[1] != link {
+ t.Error("the session's own content was changed")
+ }
+ })
+ }
+ }
+}
+
func TestWithFileText_NameFromPartMetadata(t *testing.T) {
file := &genai.Part{
InlineData: &genai.Blob{Data: []byte("remember the milk"), MIMEType: "application/octet-stream"},
diff --git a/go/adk/pkg/models/openai_adk.go b/go/adk/pkg/models/openai_adk.go
index 0ca31749a1..fd92f2b122 100644
--- a/go/adk/pkg/models/openai_adk.go
+++ b/go/adk/pkg/models/openai_adk.go
@@ -268,7 +268,7 @@ func genaiContentsToOpenAIMessages(contents []*genai.Content, config *genai.Gene
functionCalls = append(functionCalls, part.FunctionCall)
} else if part.InlineData != nil && strings.HasPrefix(part.InlineData.MIMEType, "image/") {
imageParts = append(imageParts, openai.ChatCompletionContentPartImageImageURLParam{
- URL: fmt.Sprintf("data:%s;base64,%s", part.InlineData.MIMEType, base64.StdEncoding.EncodeToString(part.InlineData.Data)),
+ URL: dataURL(part.InlineData.MIMEType, part.InlineData.Data),
})
}
}
@@ -546,3 +546,8 @@ func chatCompletionToLLMResponse(completion *openai.ChatCompletion) *model.LLMRe
Content: &genai.Content{Role: string(genai.RoleModel), Parts: parts},
}
}
+
+// dataURL is data as a base64 data: URL of the given media type.
+func dataURL(mimeType string, data []byte) string {
+ return fmt.Sprintf("data:%s;base64,%s", mimeType, base64.StdEncoding.EncodeToString(data))
+}
diff --git a/go/adk/pkg/models/openai_responses.go b/go/adk/pkg/models/openai_responses.go
index bd6c4925b7..cc8859ed73 100644
--- a/go/adk/pkg/models/openai_responses.go
+++ b/go/adk/pkg/models/openai_responses.go
@@ -2,12 +2,13 @@
package models
import (
+ "cmp"
"context"
- "encoding/base64"
"encoding/json"
"fmt"
"maps"
- "slices"
+ "mime"
+ "net/http"
"strings"
"github.com/openai/openai-go/v3/packages/param"
@@ -15,6 +16,8 @@ import (
"github.com/openai/openai-go/v3/shared"
"google.golang.org/adk/v2/model"
"google.golang.org/genai"
+
+ "github.com/kagent-dev/kagent/go/adk/pkg/fileextract"
)
func generateContentResponses(
@@ -102,9 +105,11 @@ func genaiContentsToResponsesInput(contents []*genai.Content, config *genai.Gene
}
}
- newestUser := newestUserTurn(contents)
+ // The size of this file and every newer one: while it is over the cap, the file
+ // becomes a note, so the newest files are the ones sent.
+ fileBytes := requestFileBytes(contents)
var input responses.ResponseInputParam
- for i, content := range contents {
+ for _, content := range contents {
if content == nil || strings.TrimSpace(content.Role) == openAIRoleSystem {
continue
}
@@ -126,27 +131,32 @@ func genaiContentsToResponsesInput(contents []*genai.Content, config *genai.Gene
functionCalls = append(functionCalls, part.FunctionCall)
} else if part.InlineData != nil && strings.HasPrefix(part.InlineData.MIMEType, "image/") {
hasFile = true
- contentParts = append(contentParts, responsesInputImage(fmt.Sprintf(
- "data:%s;base64,%s",
- part.InlineData.MIMEType,
- base64.StdEncoding.EncodeToString(part.InlineData.Data),
- )))
+ contentParts = append(contentParts, responsesInputImage(dataURL(part.InlineData.MIMEType, part.InlineData.Data)))
+ } else if fileType := responsesFileType(part); fileType != "" && role == genai.RoleUser && fileBytes > maxRequestFileBytes {
+ fileBytes -= len(part.InlineData.Data)
+ note := overFileCapNote(part.InlineData.DisplayName)
+ textParts = append(textParts, note)
+ contentParts = append(contentParts, responses.ResponseInputContentParamOfInputText(note))
+ } else if fileType != "" && role == genai.RoleUser {
+ hasFile = true
+ contentParts = append(contentParts, fileNameParts(part.InlineData.DisplayName)...)
+ file := responses.ResponseInputFileParam{
+ FileData: param.NewOpt(dataURL(fileType, part.InlineData.Data)),
+ Filename: param.NewOpt(cmp.Or(part.InlineData.DisplayName, "file")),
+ }
+ contentParts = append(contentParts, responses.ResponseInputContentUnionParam{OfInputFile: &file})
} else if part.FileData != nil && role == genai.RoleUser {
- // The provider fetches the link itself, on this turn and on every replayed one.
+ // The provider fetches the link itself. fileextract makes links in older turns text.
switch {
- case !isHTTPLink(part.FileData.FileURI) && i == newestUser:
- return nil, "", unsupportedLinkError(part.FileData)
case !isHTTPLink(part.FileData.FileURI):
- note := unsupportedLinkNote(part.FileData)
- textParts = append(textParts, note)
- contentParts = append(contentParts, responses.ResponseInputContentParamOfInputText(note))
+ return nil, "", unsupportedLinkError(part.FileData)
case strings.HasPrefix(part.FileData.MIMEType, "image/"):
hasFile = true
- contentParts = append(contentParts, linkNameParts(part.FileData)...)
+ contentParts = append(contentParts, fileNameParts(part.FileData.DisplayName)...)
contentParts = append(contentParts, responsesInputImage(part.FileData.FileURI))
default:
hasFile = true
- contentParts = append(contentParts, linkNameParts(part.FileData)...)
+ contentParts = append(contentParts, fileNameParts(part.FileData.DisplayName)...)
file := responses.ResponseInputFileParam{FileURL: param.NewOpt(part.FileData.FileURI)}
contentParts = append(contentParts, responses.ResponseInputContentUnionParam{OfInputFile: &file})
}
@@ -196,13 +206,14 @@ func genaiContentsToResponsesInput(contents []*genai.Content, config *genai.Gene
return input, instructions, nil
}
-// linkNameParts names a link in a text part before it: neither input_file nor
-// input_image takes a name next to a URL (Azure rejects filename beside file_url).
-func linkNameParts(f *genai.FileData) responses.ResponseInputMessageContentListParam {
- if f.DisplayName == "" {
+// fileNameParts names a file in a text part before it: the model does not see
+// input_file's filename, and neither input_file nor input_image takes a name next
+// to a URL (Azure rejects filename beside file_url).
+func fileNameParts(name string) responses.ResponseInputMessageContentListParam {
+ if name == "" {
return nil
}
- return responses.ResponseInputMessageContentListParam{responses.ResponseInputContentParamOfInputText("File: " + f.DisplayName)}
+ return responses.ResponseInputMessageContentListParam{responses.ResponseInputContentParamOfInputText("File: " + name)}
}
// responsesInputImage builds an input_image part from a data or https URL.
@@ -217,15 +228,28 @@ func isHTTPLink(uri string) bool {
return strings.HasPrefix(lower, "https://") || strings.HasPrefix(lower, "http://")
}
-// newestUserTurn is the index of the last user content, or -1. Only a bad link
-// there fails the request; in replayed history it becomes a note.
-func newestUserTurn(contents []*genai.Content) int {
- for i, c := range slices.Backward(contents) {
+// maxRequestFileBytes caps the bytes of the files in one request: OpenAI takes at
+// most 50 MB of files in total per request.
+// https://developers.openai.com/api/docs/guides/file-inputs#usage-considerations
+const maxRequestFileBytes = 50_000_000 // decimal MB: under the limit if OpenAI means MiB too
+
+// requestFileBytes is the size of the user files that input_file gets as bytes.
+func requestFileBytes(contents []*genai.Content) (n int) {
+ for _, c := range contents {
if c != nil && strings.TrimSpace(c.Role) == genai.RoleUser {
- return i
+ for _, p := range c.Parts {
+ if p != nil && responsesFileType(p) != "" {
+ n += len(p.InlineData.Data)
+ }
+ }
}
}
- return -1
+ return n
+}
+
+func overFileCapNote(name string) string {
+ return fmt.Sprintf("[File %q was not sent: the files in this chat are over the %d MB limit for one request.]",
+ cmp.Or(name, "file"), maxRequestFileBytes/1_000_000)
}
func unsupportedLinkError(f *genai.FileData) error {
@@ -235,15 +259,6 @@ func unsupportedLinkError(f *genai.FileData) error {
return fmt.Errorf("cannot send link %q with media type %q: %s", f.FileURI, f.MIMEType, linkRule)
}
-// unsupportedLinkNote keeps the URL, so a model with a fetch tool can still use it.
-func unsupportedLinkNote(f *genai.FileData) string {
- link := f.FileURI
- if f.DisplayName != "" {
- link = fmt.Sprintf("%s (%s)", f.DisplayName, f.FileURI)
- }
- return fmt.Sprintf("[Link %q was not sent: %s.]", link, linkRule)
-}
-
func genaiToolsToResponsesTools(tools []*genai.Tool) []responses.ToolUnionParam {
var out []responses.ToolUnionParam
for _, t := range tools {
@@ -436,3 +451,35 @@ func responsesStatusToFinishReason(status responses.ResponseStatus) genai.Finish
return genai.FinishReasonStop
}
}
+
+// responsesFileTypes are the document types that input_file reads from bytes
+// (pdf and Office; text types stay with fileextract as plain text), each with the
+// type http.DetectContentType gives its bytes: an Office file is a zip archive.
+var responsesFileTypes = map[string]string{
+ "application/pdf": "application/pdf",
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "application/zip",
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "application/zip",
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation": "application/zip",
+}
+
+// responsesFileType is the media type of p's bytes, without parameters, when
+// input_file reads them, else "". The bytes must match the type, as the provider
+// rejects a file that does not; fileextract gives that file the could-not-be-read note.
+func responsesFileType(p *genai.Part) string {
+ if p.InlineData == nil {
+ return ""
+ }
+ mediaType, _, _ := mime.ParseMediaType(p.InlineData.MIMEType)
+ if sniffed, ok := responsesFileTypes[mediaType]; ok && http.DetectContentType(p.InlineData.Data) == sniffed {
+ return mediaType
+ }
+ return ""
+}
+
+var _ fileextract.FileSender = (*OpenAIModel)(nil)
+
+// ProviderAccepts implements fileextract.FileSender: the Responses API takes links,
+// and pdf and Office files as bytes. Chat Completions takes neither.
+func (m *OpenAIModel) ProviderAccepts(p *genai.Part) bool {
+ return m.apiFormat() == OpenAIAPIFormatResponses && (p.FileData != nil || responsesFileType(p) != "")
+}
diff --git a/go/adk/pkg/models/openai_responses_test.go b/go/adk/pkg/models/openai_responses_test.go
index 9821b1ce13..3adba26b22 100644
--- a/go/adk/pkg/models/openai_responses_test.go
+++ b/go/adk/pkg/models/openai_responses_test.go
@@ -7,6 +7,7 @@ import (
"log/slog"
"net/http"
"net/http/httptest"
+ "slices"
"strings"
"testing"
@@ -311,6 +312,128 @@ func TestGenaiContentsToResponsesInput_Image(t *testing.T) {
}
}
+func TestGenaiContentsToResponsesInput_DocumentBytes(t *testing.T) {
+ input, _, err := genaiContentsToResponsesInput([]*genai.Content{{
+ Role: "user",
+ Parts: []*genai.Part{
+ {Text: "summarize"},
+ {InlineData: &genai.Blob{MIMEType: "Application/PDF; name=report.pdf", Data: []byte("%PDF-"), DisplayName: "report.pdf"}},
+ },
+ }}, nil)
+ require.NoError(t, err)
+ b, err := json.Marshal(input[0].OfMessage)
+ require.NoError(t, err)
+ require.JSONEq(t, `{"role":"user","content":[
+ {"type":"input_text","text":"summarize"},
+ {"type":"input_text","text":"File: report.pdf"},
+ {"type":"input_file","file_data":"data:application/pdf;base64,JVBERi0=","filename":"report.pdf"}
+ ]}`, string(b))
+}
+
+func TestOpenAIModelProviderAccepts(t *testing.T) {
+ pdf := &genai.Part{InlineData: &genai.Blob{MIMEType: "application/pdf", Data: []byte("%PDF-1.7")}}
+ pdfWithParams := &genai.Part{InlineData: &genai.Blob{MIMEType: "Application/PDF; name=a.pdf", Data: []byte("%PDF-1.7")}}
+ textAsPDF := &genai.Part{InlineData: &genai.Blob{MIMEType: "application/pdf", Data: []byte("hello, not a pdf")}}
+ const docxType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
+ docx := &genai.Part{InlineData: &genai.Blob{MIMEType: docxType, Data: []byte("PK\x03\x04rest of a zip")}}
+ textAsDocx := &genai.Part{InlineData: &genai.Blob{MIMEType: docxType, Data: []byte("hello, not a docx")}}
+ pdfAsDocx := &genai.Part{InlineData: &genai.Blob{MIMEType: docxType, Data: []byte("%PDF-1.7")}}
+ csv := &genai.Part{InlineData: &genai.Blob{MIMEType: "text/csv"}}
+ link := &genai.Part{FileData: &genai.FileData{FileURI: "https://files.example.com/report.pdf"}}
+ text := genai.NewPartFromText("hi")
+
+ responsesModel := &OpenAIModel{Config: &OpenAIConfig{APIFormat: OpenAIAPIFormatResponses}}
+ chatModel := &OpenAIModel{Config: &OpenAIConfig{}}
+ for _, tc := range []struct {
+ name string
+ m *OpenAIModel
+ part *genai.Part
+ want bool
+ }{
+ {"responses pdf bytes", responsesModel, pdf, true},
+ {"responses pdf bytes with params", responsesModel, pdfWithParams, true},
+ {"responses text labelled pdf", responsesModel, textAsPDF, false},
+ {"responses docx bytes", responsesModel, docx, true},
+ {"responses text labelled docx", responsesModel, textAsDocx, false},
+ {"responses pdf labelled docx", responsesModel, pdfAsDocx, false},
+ {"responses link", responsesModel, link, true},
+ {"responses csv stays text", responsesModel, csv, false},
+ {"responses text part", responsesModel, text, false},
+ {"chat completions pdf bytes", chatModel, pdf, false},
+ {"chat completions link", chatModel, link, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ require.Equal(t, tc.want, tc.m.ProviderAccepts(tc.part))
+ })
+ }
+}
+
+func TestGenaiContentsToResponsesInput_FileCap(t *testing.T) {
+ const mb = 1_000_000
+ pdfBytes := make([]byte, 51*mb)
+ copy(pdfBytes, "%PDF-")
+ type file struct {
+ name string
+ size int
+ }
+ user := func(files ...file) *genai.Content {
+ c := &genai.Content{Role: genai.RoleUser, Parts: []*genai.Part{genai.NewPartFromText("read")}}
+ for _, f := range files {
+ c.Parts = append(c.Parts, &genai.Part{InlineData: &genai.Blob{MIMEType: "application/pdf", Data: pdfBytes[:f.size], DisplayName: f.name}})
+ }
+ return c
+ }
+ reply := &genai.Content{Role: genai.RoleModel, Parts: []*genai.Part{genai.NewPartFromText("ok")}}
+
+ for _, tc := range []struct {
+ name string
+ contents []*genai.Content
+ wantSent, wantNote []string
+ }{
+ {"all fit", []*genai.Content{user(file{"a.pdf", 10 * mb}), reply, user(file{"b.pdf", 10 * mb})}, []string{"a.pdf", "b.pdf"}, nil},
+ {"exactly the cap fits", []*genai.Content{user(file{"a.pdf", 25 * mb}), reply, user(file{"b.pdf", 25 * mb})}, []string{"a.pdf", "b.pdf"}, nil},
+ {"older file over the cap becomes a note", []*genai.Content{user(file{"a.pdf", 30 * mb}), reply, user(file{"b.pdf", 30 * mb})}, []string{"b.pdf"}, []string{"a.pdf"}},
+ {
+ "newest first: files older than the first that does not fit are notes too",
+ []*genai.Content{user(file{"small.pdf", 1 * mb}), reply, user(file{"a.pdf", 30 * mb}), reply, user(file{"b.pdf", 30 * mb})},
+ []string{"b.pdf"}, []string{"a.pdf", "small.pdf"},
+ },
+ {"later file in a turn is newer", []*genai.Content{user(file{"a.pdf", 30 * mb}, file{"b.pdf", 30 * mb})}, []string{"b.pdf"}, []string{"a.pdf"}},
+ {"newest file over the cap alone", []*genai.Content{user(file{"big.pdf", 51 * mb})}, nil, []string{"big.pdf"}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ input, _, err := genaiContentsToResponsesInput(tc.contents, nil)
+ require.NoError(t, err)
+ var sent, notes []string
+ for _, item := range input {
+ if item.OfMessage == nil {
+ continue
+ }
+ // A message with no file left is one text string.
+ texts := strings.Split(item.OfMessage.Content.OfString.Value, "\n")
+ for _, c := range item.OfMessage.Content.OfInputItemContentList {
+ if c.OfInputFile != nil {
+ sent = append(sent, c.OfInputFile.Filename.Value)
+ } else if c.OfInputText != nil {
+ texts = append(texts, c.OfInputText.Text)
+ }
+ }
+ for _, text := range texts {
+ if strings.HasPrefix(text, "[File ") {
+ require.Contains(t, text, "was not sent: the files in this chat are over the 50 MB limit")
+ notes = append(notes, text)
+ }
+ }
+ }
+ require.ElementsMatch(t, tc.wantSent, sent)
+ require.Len(t, notes, len(tc.wantNote))
+ for _, name := range tc.wantNote {
+ require.True(t, slices.ContainsFunc(notes, func(n string) bool { return strings.Contains(n, `"`+name+`"`) }), "no note for %s in %q", name, notes)
+ }
+ })
+ }
+}
+
func TestResponsesUsageToGenai(t *testing.T) {
t.Run("nil when no tokens", func(t *testing.T) {
if got := responsesUsageToGenai(responses.ResponseUsage{}); got != nil {
@@ -417,18 +540,6 @@ func TestGenaiContentsToResponsesInput_Links(t *testing.T) {
}, nil)
require.ErrorContains(t, err, `cannot send link "gs://bucket/report.pdf"`)
})
-
- t.Run("non-http link in an older turn becomes a note", func(t *testing.T) {
- input, _, err := genaiContentsToResponsesInput([]*genai.Content{
- user(genai.NewPartFromText("read this"), link("gs://bucket/report.pdf", "application/pdf", "report.pdf")),
- {Role: "model", Parts: []*genai.Part{genai.NewPartFromText("I cannot")}},
- user(genai.NewPartFromText("hello again")),
- }, nil)
- require.NoError(t, err)
- require.Len(t, input, 3)
- require.Contains(t, userContent(t, input[0]), `[Link \"report.pdf (gs://bucket/report.pdf)\" was not sent`)
- require.JSONEq(t, `{"role":"user","content":"hello again"}`, userContent(t, input[2]))
- })
}
func TestNewAzureOpenAIModel_ResponsesPath(t *testing.T) {
diff --git a/ui/package.json b/ui/package.json
index ca22ff4f17..94df8531f3 100644
--- a/ui/package.json
+++ b/ui/package.json
@@ -37,7 +37,10 @@
"react-router-dom": "^7.18.4",
"remark-breaks": "^4.0.0",
"remark-gfm": "^4.0.1",
- "swr": "^2.5.1"
+ "remark-parse": "^11.0.0",
+ "swr": "^2.5.1",
+ "unified": "^11.0.0",
+ "unist-util-visit": "^5.0.0"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
diff --git a/ui/src/api/chat/a2aGrpcChatClient.test.ts b/ui/src/api/chat/a2aGrpcChatClient.test.ts
index ee163f406c..f3787ce1d9 100644
--- a/ui/src/api/chat/a2aGrpcChatClient.test.ts
+++ b/ui/src/api/chat/a2aGrpcChatClient.test.ts
@@ -25,6 +25,7 @@ import {
} from "@/generated/a2a_pb";
import { setApiTransport } from "../transport";
import { A2AGrpcChatClient } from "./a2aGrpcChatClient";
+import { LinkFile } from "./attachments";
import { A2A_METADATA } from "./a2aMetadata";
import type { ChatEvent, ChatMessage } from "./types";
@@ -1505,6 +1506,52 @@ describe("A2AGrpcChatClient files", () => {
expect(new TextDecoder().decode(part?.content.value as Uint8Array)).toBe("# hi");
});
+ it("sends a link from the text as a url part after the text, with no bytes", async () => {
+ let captured: SendMessageRequest | undefined;
+ serve(({ service }) => {
+ service(A2AService, {
+ // eslint-disable-next-line require-yield
+ sendStreamingMessage: async function* (request) {
+ captured = request;
+ },
+ });
+ });
+ const link = "https://files.example/a/report.pdf?sig=abc";
+ for await (const event of new A2AGrpcChatClient().send({
+ conversation: CONVERSATION,
+ text: `summarize ${link}`,
+ files: [new LinkFile(link)],
+ })) {
+ void event;
+ }
+ const [text, part] = captured?.message?.parts ?? [];
+ expect(text?.content).toEqual({ case: "text", value: `summarize ${link}` });
+ expect(part?.content).toEqual({ case: "url", value: link });
+ expect(part?.filename).toBe("report.pdf");
+ expect(part?.mediaType).toBe("application/pdf");
+ });
+
+ it("keeps the chip of an agent-sent link that its text also names", async () => {
+ const link = "https://files.example/out/report.pdf";
+ const events = await turn([
+ statusFrame({
+ state: TaskState.WORKING,
+ message: {
+ messageId: "m-agent-link",
+ role: Role.AGENT,
+ parts: [
+ { content: { case: "text" as const, value: `Your report is ready: ${link}` } },
+ { content: { case: "url" as const, value: link }, filename: "report.pdf", mediaType: "application/pdf" },
+ ],
+ },
+ }),
+ ]);
+ expect(transcript(events)[0]?.parts).toEqual([
+ { kind: "text", text: `Your report is ready: ${link}` },
+ { kind: "file", name: "report.pdf", mediaType: "application/pdf", url: link },
+ ]);
+ });
+
it("renders a file the agent sent rather than dropping it", async () => {
const events = await turn([
statusFrame({
@@ -1533,6 +1580,23 @@ describe("A2AGrpcChatClient files", () => {
]);
});
+ it("shows no chip for a link whose URL is in the message text", async () => {
+ const link = "https://files.example/a.pdf";
+ const events = await turn([
+ statusFrame({
+ message: {
+ messageId: "m-text-link",
+ role: Role.USER,
+ parts: [
+ { content: { case: "text" as const, value: `summarize ${link}` } },
+ { content: { case: "url" as const, value: link }, filename: "a.pdf", mediaType: "application/pdf" },
+ ],
+ },
+ }),
+ ]);
+ expect(transcript(events)[0]?.parts).toEqual([{ kind: "text", text: `summarize ${link}` }]);
+ });
+
it("names a linked file by its path and drops non-http links", async () => {
const events = await turn([
statusFrame({
diff --git a/ui/src/api/chat/a2aGrpcChatClient.ts b/ui/src/api/chat/a2aGrpcChatClient.ts
index d4f239af32..f2d3339d59 100644
--- a/ui/src/api/chat/a2aGrpcChatClient.ts
+++ b/ui/src/api/chat/a2aGrpcChatClient.ts
@@ -68,7 +68,7 @@ import {
readToolApprovalResponse,
type PendingRequest,
} from "./hitl";
-import { mediaTypeOf } from "./attachments";
+import { fileNameFromUrl, isHttpUrl, LinkFile, mediaTypeOf } from "./attachments";
import { agentInstanceShareToken } from "../shareToken";
import { interleaveTaskMessages } from "./transcriptOrder";
import { serviceClient } from "../transport";
@@ -216,24 +216,6 @@ function toPart(part: A2APart): ChatPart | undefined {
return undefined;
}
-function isHttpUrl(url: string): boolean {
- try {
- const { protocol } = new URL(url);
- return protocol === "http:" || protocol === "https:";
- } catch {
- return false;
- }
-}
-
-// Last path segment, so a query string or fragment never becomes the name.
-function fileNameFromUrl(url: string): string {
- try {
- return decodeURIComponent(new URL(url).pathname.split("/").pop() ?? "") || "file";
- } catch {
- return "file";
- }
-}
-
/**
* What a data part represents.
*
@@ -259,7 +241,7 @@ function dataKindOf(
return "unknown";
}
-function toParts(parts: readonly A2APart[] | undefined): ChatPart[] {
+function toParts(parts: readonly A2APart[] | undefined, role?: Role): ChatPart[] {
const result: ChatPart[] = [];
for (const source of parts ?? []) {
const part = toPart(source);
@@ -272,7 +254,12 @@ function toParts(parts: readonly A2APart[] | undefined): ChatPart[] {
}
result.push(part);
}
- return result;
+ // A link the user sent beside its own URL in the text (see LinkFile) gets no chip.
+ if (role !== Role.USER) return result;
+ return result.filter(
+ (part) =>
+ !(part.kind === "file" && part.url && result.some((t) => t.kind === "text" && t.text.includes(part.url!))),
+ );
}
type ControlFlowResult = "confirmation_required" | "rejected";
@@ -456,7 +443,10 @@ export class A2AGrpcChatClient implements ChatClient {
const client = serviceClient(A2AService);
const fileParts = await Promise.all(
(input.files ?? []).map(async (file) => ({
- content: { case: "raw" as const, value: new Uint8Array(await file.arrayBuffer()) },
+ content:
+ file instanceof LinkFile
+ ? { case: "url" as const, value: file.url }
+ : { case: "raw" as const, value: new Uint8Array(await file.arrayBuffer()) },
filename: file.name,
mediaType: mediaTypeOf(file),
})),
@@ -550,7 +540,7 @@ export class A2AGrpcChatClient implements ChatClient {
};
const status = event.status;
const message = status?.message;
- const parts = visibleParts(toParts(message?.parts), { hideRejected: true });
+ const parts = visibleParts(toParts(message?.parts, message?.role), { hideRejected: true });
const state = turnState(status?.state);
/*
* The question, when this is the frame that parked the turn.
@@ -699,7 +689,7 @@ export class A2AGrpcChatClient implements ChatClient {
if (payload.case === "message") {
const message = payload.value as A2AMessage;
- const parts = visibleParts(toParts(message.parts), { hideRejected: true });
+ const parts = visibleParts(toParts(message.parts, message.role), { hideRejected: true });
if (parts.length === 0) continue;
const id = message.messageId || nextId("message");
if (delivered.has(id)) continue;
@@ -812,7 +802,7 @@ export function messagesFromTask(task: A2ATask): ChatMessage[] {
},
},
]
- : toParts(message.parts);
+ : toParts(message.parts, message.role);
if (decisions) pendingApproval = undefined;
if (answer) pendingQuestions.delete(answer.requestId);
if (parts.length === 0) return;
diff --git a/ui/src/api/chat/attachments.test.ts b/ui/src/api/chat/attachments.test.ts
index 4dd2e4e2de..71ec98a7be 100644
--- a/ui/src/api/chat/attachments.test.ts
+++ b/ui/src/api/chat/attachments.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { MAX_TOTAL_BYTES, isAllowedFile, mediaTypeOf, stageFiles } from "./attachments";
+import { MAX_TOTAL_BYTES, isAllowedFile, mediaTypeOf, stageFiles, textLinks } from "./attachments";
const sized = (name: string, type: string, size: number) =>
({ name, type, size }) as File;
@@ -18,6 +18,55 @@ describe("mediaTypeOf", () => {
});
});
+describe("textLinks", () => {
+ it.each([
+ ["summarize https://example.com/a/report.pdf?sig=abc", ["https://example.com/a/report.pdf?sig=abc"]],
+ ["see (https://example.com/a.docx).", ["https://example.com/a.docx"]],
+ ["https://example.com/a.pdf and https://example.com/a.pdf", ["https://example.com/a.pdf"]],
+ ["what is https://github.com/kagent-dev/kagent", []],
+ ["https://example.com/index.html", []],
+ ["ftp://example.com/a.pdf example.com/a.pdf", []],
+ ["read [the report](https://example.com/a.pdf) now", ["https://example.com/a.pdf"]],
+ ["read now", ["https://example.com/a.pdf"]],
+ ["https://example.com/a.pdf?v=(2)", ["https://example.com/a.pdf?v=(2)"]],
+ ["(see https://example.com/a.pdf?v=(2)).", ["https://example.com/a.pdf?v=(2)"]],
+ ["run `curl https://example.com/a.pdf` here", []],
+ // GFM links www. as http://www., which is not in the text as written.
+ ["www.example.com/a.pdf", []],
+ ["", []],
+ // Private hosts: the provider cannot fetch them.
+ ...[
+ "http://localhost:8080/a.pdf",
+ "http://LOCALHOST./a.pdf",
+ "http://fileserver/a.pdf",
+ "http://127.0.0.1/a.pdf",
+ "http://2130706433/a.pdf",
+ "http://10.0.0.1/a.pdf",
+ "",
+ "http://0.0.0.0:8000/a.pdf",
+ "http://printer.local/a.pdf",
+ "http://files.corp.internal/a.pdf",
+ "http://files.default.svc/a.pdf",
+ "http://files.default.svc.cluster.local/a.pdf",
+ "http://fileserver.lan/a.pdf",
+ "http://nas.home.arpa/a.pdf",
+ "http://box.localdomain/a.pdf",
+ ].map((url): [string, string[]] => [url, []]),
+ // Public hosts that look close to private ones.
+ ...[
+ "https://lan.example.com/a.pdf",
+ "https://local.example.com/a.pdf",
+ "https://example.svc.com/a.pdf",
+ ].map((url): [string, string[]] => [url, [url]]),
+ // Any IP address stays text, public ones too. An IPv6 host has no dot.
+ ...["http://11.0.0.1/a.pdf", "http://172.32.0.1/a.pdf", ""].map(
+ (url): [string, string[]] => [url, []],
+ ),
+ ])("%j is %j", (text, expected) => {
+ expect(textLinks(text)).toEqual(expected);
+ });
+});
+
describe("isAllowedFile", () => {
it.each([
["photo.png", "image/png", true],
@@ -26,8 +75,8 @@ describe("isAllowedFile", () => {
["scan.tiff", "image/tiff", false],
["logo.svg", "image/svg+xml", false],
["page.htm", "", true],
- ["report.pdf", "application/pdf", false],
- ["deck.pptx", "", false],
+ ["report.pdf", "application/pdf", true],
+ ["deck.pptx", "", true],
["setup.exe", "application/x-msdownload", false],
["archive.zip", "", false],
])("%s (%j) → %s", (name, type, expected) => {
diff --git a/ui/src/api/chat/attachments.ts b/ui/src/api/chat/attachments.ts
index 0858324d71..97b42b230e 100644
--- a/ui/src/api/chat/attachments.ts
+++ b/ui/src/api/chat/attachments.ts
@@ -1,3 +1,8 @@
+import remarkGfm from "remark-gfm";
+import remarkParse from "remark-parse";
+import { unified } from "unified";
+import { visit } from "unist-util-visit";
+
// One cap for the whole message: the gateway's gRPC limit is 16 MiB, framing included.
export const MAX_TOTAL_BYTES = 10 * 1024 * 1024;
@@ -18,6 +23,10 @@ const TYPE_BY_EXTENSION: Record = {
jpeg: "image/jpeg",
gif: "image/gif",
webp: "image/webp",
+ pdf: "application/pdf",
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
};
const ALLOWED_TYPES = new Set([
@@ -51,6 +60,62 @@ export function isAllowedFile(file: Pick): boolean {
return ALLOWED_TYPES.has(mediaTypeOf(file));
}
+/**
+ * A link in the message text, sent beside the text as an A2A url part with no bytes and
+ * no chip. A model that reads links fetches it; for any other model the runtime drops the
+ * part, and the URL in the text stays for the agent's fetch tool.
+ */
+export class LinkFile extends File {
+ constructor(readonly url: string) {
+ super([], fileNameFromUrl(url));
+ }
+}
+
+// The model reads the text as markdown, so links are found the same way: bare URLs,
+// and [markdown](links), but none inside code.
+const markdown = unified().use(remarkParse).use(remarkGfm);
+
+/**
+ * The links in `text` to send as url parts: http(s) URLs to a file of a known type,
+ * as written in the text, so the runtime finds them there. A web page stays text only:
+ * no provider is known to read one as a file. A link to a private host stays text too:
+ * the provider fetches the link itself and cannot reach it.
+ */
+export function textLinks(text: string): string[] {
+ const links = new Set();
+ visit(markdown.parse(text), "link", ({ url }) => {
+ const type = TYPE_BY_EXTENSION[extensionOf(fileNameFromUrl(url))];
+ if (text.includes(url) && isHttpUrl(url) && !isPrivateHost(url) && type && type !== "text/html") {
+ links.add(url);
+ }
+ });
+ return [...links];
+}
+
+export function isHttpUrl(url: string): boolean {
+ try {
+ const { protocol } = new URL(url);
+ return protocol === "http:" || protocol === "https:";
+ } catch {
+ return false;
+ }
+}
+
+// An IP, dotless or LAN host the provider likely cannot fetch.
+function isPrivateHost(url: string): boolean {
+ const host = new URL(url).hostname.toLowerCase().replace(/\.$/, "");
+ return /^[\d.]+$/.test(host) || !host.includes(".") || /\.(local|localdomain|internal|svc|lan|home\.arpa)$/.test(host);
+}
+
+// Last path segment, so a query string or fragment never becomes the name.
+export function fileNameFromUrl(url: string): string {
+ try {
+ return decodeURIComponent(new URL(url).pathname.split("/").pop() ?? "") || "file";
+ } catch {
+ return "file";
+ }
+}
+
export function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${Number((bytes / 1024).toFixed(1))} KB`;
diff --git a/ui/src/api/chat/mockChatClient.ts b/ui/src/api/chat/mockChatClient.ts
index 2cdd97942d..bf9f3b2d43 100644
--- a/ui/src/api/chat/mockChatClient.ts
+++ b/ui/src/api/chat/mockChatClient.ts
@@ -27,7 +27,7 @@ import type {
ChatPart,
SendMessageInput,
} from "./types";
-import { mediaTypeOf } from "./attachments";
+import { LinkFile, mediaTypeOf } from "./attachments";
const TIMING = {
ok: { step: 300, word: 45 },
@@ -134,7 +134,8 @@ export class MockChatClient implements ChatClient {
async *send(input: SendMessageInput): AsyncIterable {
activity.started += 1;
try {
- yield* this.stream(input);
+ // A link's URL is already in the text; like the real client, it gets no chip.
+ yield* this.stream({ ...input, files: input.files?.filter((file) => !(file instanceof LinkFile)) });
} finally {
activity.finished += 1;
}
diff --git a/ui/src/api/hooks/useChat.transcript.test.ts b/ui/src/api/hooks/useChat.transcript.test.ts
index 2074bf8c2b..4a97d029b2 100644
--- a/ui/src/api/hooks/useChat.transcript.test.ts
+++ b/ui/src/api/hooks/useChat.transcript.test.ts
@@ -8,6 +8,7 @@ import type {
ChatMessage,
SendMessageInput,
} from "../chat/types";
+import { LinkFile } from "../chat/attachments";
import { useChat } from "./useChat";
/**
@@ -90,6 +91,24 @@ describe("useChat and the reader's own message", () => {
expect(textOf(mine[0])).toBe(QUESTION);
});
+ it("shows a chip for an attached file but not for a link from the text", async () => {
+ const seen: SendMessageInput[] = [];
+ setChatClientFactory(() => client({ seen }));
+ const { result } = renderHook(() => useChat(CONVERSATION));
+ await waitFor(() => expect(result.current.isLoadingHistory).toBe(false));
+
+ const link = new LinkFile("https://files.example/a.pdf");
+ const attached = new File(["# hi"], "notes.md", { type: "text/markdown" });
+ await act(async () => {
+ await result.current.send(`read ${link.url}`, [attached, link]);
+ });
+
+ const mine = result.current.messages.filter((message) => message.role === "user");
+ expect(mine[0].parts.filter((part) => part.kind === "file").map((part) => part.name)).toEqual(["notes.md"]);
+ // The link still goes to the agent.
+ expect(seen[0].files).toEqual([attached, link]);
+ });
+
it("sends it under the id it filed it under, which is what lets an echo replace it", async () => {
const seen: SendMessageInput[] = [];
setChatClientFactory(() => client({ seen, reply: () => [] }));
diff --git a/ui/src/api/hooks/useChat.ts b/ui/src/api/hooks/useChat.ts
index ecb65c0ae3..92a06127b5 100644
--- a/ui/src/api/hooks/useChat.ts
+++ b/ui/src/api/hooks/useChat.ts
@@ -43,7 +43,7 @@ import { getChatClient } from "../chat";
import { runtimeConfig } from "../runtimeConfig";
import { randomId } from "../randomId";
import { conversationKey } from "../chat/types";
-import { mediaTypeOf } from "../chat/attachments";
+import { LinkFile, mediaTypeOf } from "../chat/attachments";
import {
IDLE_TURN,
isActive,
@@ -319,7 +319,8 @@ export function useChat(
// were a new chat message.
parts: displayParts ?? [
...(text ? [{ kind: "text" as const, text }] : []),
- ...(files ?? []).map(
+ // A link's URL is already in the text; it gets no chip.
+ ...(files ?? []).filter((file) => !(file instanceof LinkFile)).map(
(file): ChatPart => ({
kind: "file",
name: file.name,
diff --git a/ui/src/components/chat/ChatComposer.test.tsx b/ui/src/components/chat/ChatComposer.test.tsx
new file mode 100644
index 0000000000..b44d399d84
--- /dev/null
+++ b/ui/src/components/chat/ChatComposer.test.tsx
@@ -0,0 +1,38 @@
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { ThemeProvider } from "@emotion/react";
+import { describe, expect, it, vi } from "vitest";
+import { LinkFile } from "@/api/chat/attachments";
+import { themeFor } from "@/theme/theme";
+import { ChatComposer } from "./ChatComposer";
+
+const TEXT = "read https://files.example/a.pdf and https://example.com/docs";
+
+/** What the composer hands to `send` when the reader types TEXT and presses Enter. */
+async function sent(canAttach: boolean | undefined) {
+ const send = vi.fn<(text: string, files: File[]) => Promise>(async () => {});
+ render(
+
+
+ ,
+ );
+ const input = screen.getByTestId("chat-input");
+ fireEvent.change(input, { target: { value: TEXT } });
+ fireEvent.keyDown(input, { key: "Enter", code: "Enter", keyCode: 13 });
+ await waitFor(() => expect(send).toHaveBeenCalledOnce());
+ return send.mock.calls[0];
+}
+
+describe("ChatComposer and links in the text", () => {
+ it("sends a link to a known file type as a LinkFile, and leaves a page link as text", async () => {
+ const [text, files] = await sent(true);
+ expect(text).toBe(TEXT);
+ expect(files).toHaveLength(1);
+ expect(files[0]).toBeInstanceOf(LinkFile);
+ expect((files[0] as LinkFile).url).toBe("https://files.example/a.pdf");
+ });
+
+ it.each([false, undefined])("sends no link when the agent takes no files (canAttach %s)", async (canAttach) => {
+ const [, files] = await sent(canAttach);
+ expect(files).toEqual([]);
+ });
+});
diff --git a/ui/src/components/chat/ChatComposer.tsx b/ui/src/components/chat/ChatComposer.tsx
index 26b5240c50..65e92e6603 100644
--- a/ui/src/components/chat/ChatComposer.tsx
+++ b/ui/src/components/chat/ChatComposer.tsx
@@ -4,7 +4,7 @@ import type { TextAreaRef } from "antd/es/input/TextArea";
import { useTheme } from "@emotion/react";
import { Paperclip, Save, Send, Square } from "lucide-react";
import type { ChatController } from "@/api";
-import { ACCEPTED_FILES, mediaTypeOf, stageFiles } from "@/api/chat/attachments";
+import { ACCEPTED_FILES, LinkFile, mediaTypeOf, stageFiles, textLinks } from "@/api/chat/attachments";
import { randomId } from "@/api/randomId";
import { AttachmentChip } from "./AttachmentChip";
import { WindowFileDrop } from "./WindowFileDrop";
@@ -144,7 +144,7 @@ export function ChatComposer({
// immediately, rather than holding text that has already been sent.
setDraft("");
setStaged({ files: [] });
- await send(text, files);
+ await send(text, canAttach ? [...files, ...textLinks(text).map((url) => new LinkFile(url))] : files);
}
return (
diff --git a/ui/yarn.lock b/ui/yarn.lock
index 50849d076b..5d240b98cb 100644
--- a/ui/yarn.lock
+++ b/ui/yarn.lock
@@ -4520,9 +4520,12 @@ __metadata:
react-router-dom: "npm:^7.18.4"
remark-breaks: "npm:^4.0.0"
remark-gfm: "npm:^4.0.1"
+ remark-parse: "npm:^11.0.0"
swr: "npm:^2.5.1"
typescript: "npm:^6.0.3"
typescript-eslint: "npm:^8.71.1"
+ unified: "npm:^11.0.0"
+ unist-util-visit: "npm:^5.0.0"
vite: "npm:^8.3.4"
vitest: "npm:^4.1.11"
languageName: unknown