Files
pipelines/internal/server/chat_attachments.go
T
alan f5ccec8e1f chat: deliver attachments and cancel runs immediately
Carry browser files as base64 prompt attachments, write them to private
temporary files and pass file:// references to OpenCode, and map the user
turn's top-level files back into history. Replay a running step on subscribe,
forward only a caller-supplied msg_ id, and persist cancel on the run and live
step before interrupting the runner.
2026-10-20 14:30:53 +01:00

134 lines
3.9 KiB
Go

package server
import (
"encoding/base64"
"fmt"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
const (
// maxChatAttachments bounds one prompt's browser files. OpenCode receives a
// small number of local files; more is not a useful chat message.
maxChatAttachments = 8
// maxChatAttachmentBytes bounds the decoded bytes for one prompt. The browser
// sends base64 over the existing 2 MiB websocket frame, so this keeps the
// encoded body comfortably below that hard limit.
maxChatAttachmentBytes = 1 << 20
)
// prepareChatAttachments writes browser attachment bytes into a private
// temporary directory and returns the file references OpenCode accepts plus the
// display parts the user turn carries. A browser File reference is not readable
// by the agent service, so the bytes must cross the websocket.
func prepareChatAttachments(sessionID string, attachments []protocol.ChatAttachment) ([]opencode.PromptFile, []protocol.ChatPart, error) {
if len(attachments) == 0 {
return nil, nil, nil
}
if len(attachments) > maxChatAttachments {
return nil, nil, fmt.Errorf("at most %d attachments are allowed", maxChatAttachments)
}
dir := filepath.Join(os.TempDir(), "pipelines-chat-attachments", safeChatAttachmentSegment(sessionID))
if err := os.MkdirAll(dir, 0o700); err != nil {
return nil, nil, fmt.Errorf("prepare attachment directory: %w", err)
}
var files []opencode.PromptFile
var parts []protocol.ChatPart
var created []string
cleanup := func() {
for _, path := range created {
_ = os.Remove(path)
}
}
total := 0
for index, attachment := range attachments {
data := strings.TrimSpace(attachment.Data)
if data == "" {
cleanup()
return nil, nil, fmt.Errorf("attachment %q has no data", attachment.Name)
}
decoded, err := base64.StdEncoding.DecodeString(data)
if err != nil {
cleanup()
return nil, nil, fmt.Errorf("attachment %q is not valid base64", attachment.Name)
}
total += len(decoded)
if total > maxChatAttachmentBytes {
cleanup()
return nil, nil, fmt.Errorf("attachments exceed the %s limit", "1 MiB")
}
name := safeChatAttachmentName(attachment.Name)
mime := strings.TrimSpace(attachment.Mime)
if mime == "" {
mime = "application/octet-stream"
}
path := filepath.Join(dir, fmt.Sprintf("%d-%02d-%s", time.Now().UnixNano(), index, name))
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
cleanup()
return nil, nil, fmt.Errorf("write attachment %q: %w", name, err)
}
if _, err := file.Write(decoded); err != nil {
_ = file.Close()
cleanup()
return nil, nil, fmt.Errorf("write attachment %q: %w", name, err)
}
if err := file.Close(); err != nil {
cleanup()
return nil, nil, fmt.Errorf("close attachment %q: %w", name, err)
}
created = append(created, path)
uri := (&url.URL{Scheme: "file", Path: path}).String()
files = append(files, opencode.PromptFile{URI: uri, Name: name})
parts = append(parts, protocol.ChatPart{Type: protocol.ChatPartFile, Name: name, Mime: mime, URI: uri})
}
return files, parts, nil
}
func safeChatAttachmentSegment(value string) string {
value = strings.TrimSpace(value)
value = strings.Map(func(r rune) rune {
switch {
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '_', r == '-':
return r
default:
return '_'
}
}, value)
if value == "" {
return "session"
}
if len(value) > 80 {
value = value[:80]
}
return value
}
func safeChatAttachmentName(value string) string {
name := filepath.Base(strings.TrimSpace(value))
name = strings.Map(func(r rune) rune {
if r == 0 || r == '/' || r == '\\' {
return -1
}
return r
}, name)
name = strings.TrimSpace(name)
if name == "" || name == "." {
name = "attachment"
}
if len(name) > 120 {
ext := filepath.Ext(name)
if len(ext) > 16 {
ext = ""
}
name = name[:120-len(ext)] + ext
}
return name
}