fix(webui,sendfile): close three holes the adversarial review found
Follow-up to 0b2398f, which claimed non-delivery is never silent and that
oversized files fail visibly. Both claims had gaps.
chatStreamSink.Media skipped any attachment with an empty URL, exactly as
liveReply.Media used to. The tool registry is shared between the Telegram
and dashboard chat setups, so send_file is offered on the dashboard too:
the model announced a sent file, the sink dropped the event, and nothing
reached the transcript. The dashboard cannot upload at all, so the fix is
to REPORT the file as undeliverable and name where it is on the host,
rather than to stay quiet. The skip was right while media meant a hosted
URL; it stopped being right when a host path could arrive here.
send_file applied one 50MB ceiling to every type while the sender enforces
10MB for photos, so an 11-50MB image passed the early check, was reported
sent, and was rejected by a layer the model cannot see. The early check is
now per-type and mirrors the sender's limits.
MediaType called every image/* an image, but a photo endpoint rejects
image/svg+xml and image/tiff outright. Photo-safe formats are now an
explicit set, so an svg goes as a document and arrives, which is what the
"unrecognised means document" reasoning intended all along.
Also tests the readability probe's own error path (mode 0000), which was
the one case it exists for and the one case not covered; verified it fails
with the probe removed.
Remaining review findings are filed, not fixed: fallback lines appended
after the live reply finalizes are dropped by a stopped renderer
(archie-core-atv2), confinement is symlink-blind and re-opens after
checking (archie-core-jkmu), and concurrent uploads are uncapped
(archie-core-3svc).
This commit is contained in:
1 parent
bbcbe3153d
commit
12f85a581f
5 files changed
+155
-22
No files matched your search
@@ -33,13 +33,32 @@ import (
|
||||
// ToolName is the registry name of the file-delivery tool.
|
||||
const ToolName = "send_file"
|
||||
|
||||
// MaxUploadBytes bounds what may be handed to a channel for upload. It is
|
||||
// the Telegram Bot API's 50 MB document ceiling, which is the tightest
|
||||
// limit among the channels that can deliver at all; checking it here means
|
||||
// an oversized file fails as a tool error the model can report instead of
|
||||
// as a delivery failure it never sees. The channel enforces its own real
|
||||
// limits regardless -- this is an early, visible check, not the authority.
|
||||
const MaxUploadBytes int64 = 50 * 1024 * 1024
|
||||
// Upload ceilings, in bytes. These are the Telegram Bot API's, the
|
||||
// tightest among the channels that can deliver at all; checking them here
|
||||
// means an oversized file fails as a tool error the model can report
|
||||
// instead of as a delivery failure it never sees. The channel enforces its
|
||||
// own limits regardless -- this is an early, visible check, not the
|
||||
// authority.
|
||||
//
|
||||
// Images have their own, much lower ceiling. Applying MaxUploadBytes to
|
||||
// every type made the early check useless for exactly the type that needed
|
||||
// it: a 20 MB screenshot passed here, was reported to the model as sent,
|
||||
// and was then rejected by a layer the model cannot see.
|
||||
const (
|
||||
MaxUploadBytes int64 = 50 * 1024 * 1024
|
||||
MaxImageUploadBytes int64 = 10 * 1024 * 1024
|
||||
)
|
||||
|
||||
// uploadLimit reports the ceiling for a media kind. It mirrors the
|
||||
// telegram sender's own limits by design: the two must agree, or the early
|
||||
// check either lets through what the send rejects or refuses what it would
|
||||
// have accepted.
|
||||
func uploadLimit(mediaType string) int64 {
|
||||
if mediaType == "image" {
|
||||
return MaxImageUploadBytes
|
||||
}
|
||||
return MaxUploadBytes
|
||||
}
|
||||
|
||||
// Tool builds the registry entry rooted at workspace. Relative paths
|
||||
// resolve against it, and confinement (when enabled) is measured from it,
|
||||
@@ -107,9 +126,10 @@ func prepare(workspace, path, caption string) (tools.MultimodalResult, error) {
|
||||
if !info.Mode().IsRegular() {
|
||||
return tools.MultimodalResult{}, fmt.Errorf("%s: %s: %w", ToolName, resolved, errNotRegularFile)
|
||||
}
|
||||
if info.Size() > MaxUploadBytes {
|
||||
return tools.MultimodalResult{}, fmt.Errorf("%s: %s is %d bytes, over the %d byte upload limit",
|
||||
ToolName, resolved, info.Size(), MaxUploadBytes)
|
||||
mediaType := MediaType(resolved)
|
||||
if limit := uploadLimit(mediaType); info.Size() > limit {
|
||||
return tools.MultimodalResult{}, fmt.Errorf("%s: %s is %d bytes, over the %d byte upload limit for %s",
|
||||
ToolName, resolved, info.Size(), limit, mediaType)
|
||||
}
|
||||
// Opened, not just stat'd: an unreadable file is a failure the model
|
||||
// must see now rather than one the channel discovers after the turn
|
||||
@@ -129,13 +149,25 @@ func prepare(workspace, path, caption string) (tools.MultimodalResult, error) {
|
||||
IsMultimodal: true,
|
||||
Summary: summary,
|
||||
URLs: []tools.MediaRef{{
|
||||
Type: MediaType(resolved),
|
||||
Type: mediaType,
|
||||
Path: resolved,
|
||||
FileName: name,
|
||||
}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// photoFormats are the image types a chat platform will accept through its
|
||||
// photo endpoint. Membership is by exact media type rather than an
|
||||
// "image/" prefix: image/svg+xml and image/tiff are images that a photo
|
||||
// endpoint rejects outright, so treating the whole prefix as photo-safe
|
||||
// turned a deliverable file into a failed send. As documents they arrive.
|
||||
var photoFormats = map[string]bool{
|
||||
"image/jpeg": true,
|
||||
"image/png": true,
|
||||
"image/gif": true,
|
||||
"image/webp": true,
|
||||
}
|
||||
|
||||
// MediaType maps a filename onto the four-value media vocabulary
|
||||
// gateway.MediaAttachment.Type uses.
|
||||
//
|
||||
@@ -143,9 +175,10 @@ func prepare(workspace, path, caption string) (tools.MultimodalResult, error) {
|
||||
// arbitrary bytes: guessing "image" wrongly makes the platform reject the
|
||||
// send, while sending an image as a document still delivers the file.
|
||||
func MediaType(path string) string {
|
||||
mt := mime.TypeByExtension(strings.ToLower(filepath.Ext(path)))
|
||||
mt, _, _ := strings.Cut(mime.TypeByExtension(strings.ToLower(filepath.Ext(path))), ";")
|
||||
mt = strings.TrimSpace(mt)
|
||||
switch {
|
||||
case strings.HasPrefix(mt, "image/"):
|
||||
case photoFormats[mt]:
|
||||
return "image"
|
||||
case strings.HasPrefix(mt, "video/"):
|
||||
return "video"
|
||||
|
||||
@@ -33,6 +33,11 @@ func TestPrepareReturnsLocalPathRef(t *testing.T) {
|
||||
{"markdown is a document", "transcript.md", "document"},
|
||||
{"unknown extension is a document", "dump.bin", "document"},
|
||||
{"png is an image", "shot.png", "image"},
|
||||
{"jpeg is an image", "photo.jpg", "image"},
|
||||
// An svg IS an image, but no photo endpoint accepts one, so
|
||||
// calling it one turns a deliverable file into a failed send.
|
||||
{"svg is a document, not a photo", "diagram.svg", "document"},
|
||||
{"tiff is a document, not a photo", "scan.tiff", "document"},
|
||||
{"mp4 is a video", "clip.mp4", "video"},
|
||||
{"mp3 is audio", "note.mp3", "audio"},
|
||||
}
|
||||
@@ -80,6 +85,14 @@ func TestPrepareFailuresAreErrors(t *testing.T) {
|
||||
ws := t.TempDir()
|
||||
outside := t.TempDir()
|
||||
writeFile(t, outside, "secret.txt", 8)
|
||||
locked := writeFile(t, ws, "locked.txt", 8)
|
||||
if err := os.Chmod(locked, 0o000); err != nil {
|
||||
t.Fatalf("chmod: %v", err)
|
||||
}
|
||||
if os.Geteuid() == 0 {
|
||||
// root ignores the mode bits, so the probe cannot fail this way.
|
||||
t.Skip("running as root: an unreadable file is still readable")
|
||||
}
|
||||
big := writeFile(t, ws, "big.bin", 0)
|
||||
if err := os.Truncate(big, MaxUploadBytes+1); err != nil {
|
||||
t.Fatalf("truncate: %v", err)
|
||||
@@ -94,6 +107,7 @@ func TestPrepareFailuresAreErrors(t *testing.T) {
|
||||
{name: "empty path", path: " ", wantSub: "path is required"},
|
||||
{name: "missing file", path: "nope.txt", wantErr: os.ErrNotExist},
|
||||
{name: "directory", path: ".", wantSub: "not a regular file"},
|
||||
{name: "unreadable file", path: "locked.txt", wantErr: os.ErrPermission},
|
||||
{name: "over the upload limit", path: "big.bin", wantSub: "upload limit"},
|
||||
{
|
||||
name: "outside the workspace",
|
||||
@@ -121,6 +135,32 @@ func TestPrepareFailuresAreErrors(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// An image is capped far lower than everything else by the platform that
|
||||
// delivers it. Checking one 50 MB ceiling for every type told the model an
|
||||
// 11 MB screenshot was sent and left the rejection to a layer it cannot
|
||||
// see -- the early check has to be the check that actually applies.
|
||||
func TestPrepareAppliesTheImageLimit(t *testing.T) {
|
||||
ws := t.TempDir()
|
||||
png := writeFile(t, ws, "shot.png", 0)
|
||||
if err := os.Truncate(png, MaxImageUploadBytes+1); err != nil {
|
||||
t.Fatalf("truncate: %v", err)
|
||||
}
|
||||
if _, err := prepare(ws, "shot.png", ""); err == nil ||
|
||||
!strings.Contains(err.Error(), "upload limit") {
|
||||
t.Fatalf("err = %v, want an over-the-image-limit error", err)
|
||||
}
|
||||
|
||||
// The same size as a document is fine: the limits must stay
|
||||
// per-type rather than collapsing into one conservative number.
|
||||
doc := writeFile(t, ws, "dump.bin", 0)
|
||||
if err := os.Truncate(doc, MaxImageUploadBytes+1); err != nil {
|
||||
t.Fatalf("truncate: %v", err)
|
||||
}
|
||||
if _, err := prepare(ws, "dump.bin", ""); err != nil {
|
||||
t.Fatalf("prepare document of image-limit+1 bytes: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Confinement is a deployment posture: with the jail lifted, a path
|
||||
// outside the workspace must be sendable, exactly as the read tool can
|
||||
// read it.
|
||||
|
||||
@@ -257,16 +257,29 @@ func (s chatStreamSink) ToolCall(event gateway.ToolCallEvent) {
|
||||
// Media has no inline rendering path on the dashboard yet (see
|
||||
// archie-core-1786748942243-6-f109697e), so it degrades to a link in the
|
||||
// delta stream -- the same fallback Telegram's liveReply uses when its own
|
||||
// SendMedia call fails. An attachment with no URL has nothing to link to
|
||||
// and is skipped rather than emitting an empty line.
|
||||
// SendMedia call fails.
|
||||
//
|
||||
// A local file cannot be linked and this channel cannot upload one, so it
|
||||
// is REPORTED as undelivered rather than skipped. Skipping was right while
|
||||
// media meant a hosted URL; once send_file could hand this sink a host
|
||||
// path, silence here meant the model announced a file it had sent and
|
||||
// nothing arrived -- the precise defect send_file was built to end,
|
||||
// reappearing on the channel that cannot deliver.
|
||||
func (s chatStreamSink) Media(event gateway.MediaEvent) {
|
||||
if event.Attachment.URL == "" {
|
||||
return
|
||||
att := event.Attachment
|
||||
switch {
|
||||
case att.URL != "":
|
||||
s.write(chatStreamEvent{Type: "delta", Text: "\n\n📎 " + att.Type + ": " + att.URL})
|
||||
case att.Path != "":
|
||||
name := att.FileName
|
||||
if name == "" {
|
||||
name = att.Path
|
||||
}
|
||||
s.write(chatStreamEvent{
|
||||
Type: "delta",
|
||||
Text: "\n\n📎 could not send " + name + ": this channel cannot deliver a local file. It is on the daemon host at " + att.Path + ".",
|
||||
})
|
||||
}
|
||||
s.write(chatStreamEvent{
|
||||
Type: "delta",
|
||||
Text: "\n\n📎 " + event.Attachment.Type + ": " + event.Attachment.URL,
|
||||
})
|
||||
}
|
||||
|
||||
// chatShowToolCalls reports config.ChatConfig.ShowToolCalls, the one setting
|
||||
|
||||
@@ -835,3 +835,47 @@ func postTo(server *Server, body string) *httptest.ResponseRecorder {
|
||||
server.Handler().ServeHTTP(res, req)
|
||||
return res
|
||||
}
|
||||
|
||||
// The dashboard cannot upload a file at all, so a local attachment must
|
||||
// say so in the transcript. Skipping it silently is the same defect
|
||||
// send_file was built to end: the model reports a file as sent and
|
||||
// nothing arrives, with no signal either way.
|
||||
func TestChatStreamReportsUndeliverableLocalFile(t *testing.T) {
|
||||
stream := func(_ context.Context, _ gateway.Message, turn gateway.TurnStream) (string, error) {
|
||||
turn.Media(gateway.MediaEvent{
|
||||
ToolName: "send_file",
|
||||
Attachment: gateway.MediaAttachment{
|
||||
Type: "document",
|
||||
Path: "/var/log/archie/session.log",
|
||||
FileName: "session.log",
|
||||
},
|
||||
})
|
||||
return "", nil
|
||||
}
|
||||
|
||||
server, sessions := chatTestServer(t)
|
||||
server.Chat.Router.LLMStream = stream
|
||||
saveWebSession(t, sessions, "web-1")
|
||||
|
||||
req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/api/chat/stream",
|
||||
strings.NewReader(`{"channel_id":"browser-web-1","text":"send me the log"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
res := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(res, req)
|
||||
if res.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", res.Code, res.Body)
|
||||
}
|
||||
|
||||
var joined strings.Builder
|
||||
for _, ev := range parseChatSSE(t, res.Body.String()) {
|
||||
if ev.Type == "delta" {
|
||||
joined.WriteString(ev.Text)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(joined.String(), "session.log") {
|
||||
t.Errorf("delta stream = %q, want it to name the undelivered file", joined.String())
|
||||
}
|
||||
if !strings.Contains(joined.String(), "could not") {
|
||||
t.Errorf("delta stream = %q, want it to report non-delivery", joined.String())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user