oficina / base Public

Equipo client and fake learn files (Task 1)

Human

Prompt

Build Base's half of files in Ask, slice 1, task by task from the approved plan; keep the fake faithful to Equipo's assistant-attachments spec (can_attach, DELETE /api/v1/attachments/{id}, 409 attachments_unavailable, 409 attachment_sent).

From this commit's own message. The prompt ledger has no entries for it — which is what a squashed, rebased or amended commit looks like, and what every commit looks like in a repo without a ledger.

Summary

equipo: Attachment, Message.Attachments, Snapshot.CanAttach, Send with files, Upload (no Idempotency-Key), OpenAttachment (streamed), DeleteAttachment (404 is done), ErrAttachmentsUnavailable; a do helper beside call. equipotest: upload with sniffing and Equipo's limits, per-person read and delete, sends with files, FilesReady, ExpireUploads, hold, busy, slow and hostile switches.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 4775d85de8a0216c1b7f81d07cb6b48b309893c2 parent 6f778dd
9 files changed, +922 −33
  • internal/equipo/chat.go +24 −13
  • internal/equipo/equipo.go +8 −3
  • internal/equipo/equipo_test.go +4 −4
  • internal/equipo/equipotest/chat.go +69 −10
  • internal/equipo/equipotest/fake.go +14 −2
  • internal/equipo/equipotest/files.go +431 −0
  • internal/equipo/files.go +163 −0
  • internal/equipo/files_test.go +208 −0
  • internal/web/ask_relay.go +1 −1
diff --git a/internal/equipo/chat.go b/internal/equipo/chat.go
index 162e727..b387865 100644
--- a/internal/equipo/chat.go
+++ b/internal/equipo/chat.go
@@ -29,12 +29,15 @@ func InFlight(state string) bool {
}
// Message is one line of the conversation; Role is person or assistant.
+// Attachments are the files the person sent with it, in their order
+// (Clean keeps only a usable id).
type Message struct {
- ID string `json:"id"`
- Role string `json:"role"`
- Text string `json:"text"`
- TurnID string `json:"turn_id"`
- CreatedAt time.Time `json:"created_at"`
+ ID string `json:"id"`
+ Role string `json:"role"`
+ Text string `json:"text"`
+ TurnID string `json:"turn_id"`
+ CreatedAt time.Time `json:"created_at"`
+ Attachments []Attachment `json:"attachments,omitempty"`
}
// Turn is the Assistant's answer to the person's messages.
@@ -240,7 +243,8 @@ const assistant = "/api/v1/assistant"
// Snapshot is the part of GET /api/v1/assistant/snapshot Base shows: who
// the bearer speaks for, the conversation's tail, its turns, its cards,
// the event cursor they were read at (so the stream picks up exactly
-// after them), and whether the person has a runner that can answer.
+// after them), whether the person has a runner that can answer, and
+// whether it can take files (CanAttach; an older Equipo never says so).
type Snapshot struct {
Me struct {
Address string `json:"address"`
@@ -250,6 +254,7 @@ type Snapshot struct {
Cards []Card `json:"cards"`
Cursor int64 `json:"cursor"`
Available bool `json:"available"`
+ CanAttach bool `json:"can_attach"`
}
// Sent is POST messages's answer.
@@ -290,14 +295,20 @@ func (c *Client) SetTimeZone(ctx context.Context, token, zone string) error {
return err
}
-// Send sends the person's message: ErrNoRunner or ErrRunnerTooOld when
-// the person has no runner that can answer. key makes a retry safe:
-// Equipo keeps one message per key. It goes as the body's
-// idempotency_key, and as the Idempotency-Key header every mutation
-// carries.
-func (c *Client) Send(ctx context.Context, token, text, key string) (Sent, error) {
+// Send sends the person's message, with the files uploaded for it (their
+// ids, in order; text may be empty when there are any): ErrNoRunner or
+// ErrRunnerTooOld when the person has no runner that can answer, and
+// ErrAttachmentsUnavailable when files came and the runner can't take
+// them. key makes a retry safe: Equipo keeps one message per key (and its
+// files). It goes as the body's idempotency_key, and as the
+// Idempotency-Key header every mutation carries. Without files the body
+// is what it always was.
+func (c *Client) Send(ctx context.Context, token, text, key string, files []string) (Sent, error) {
var out Sent
- in := map[string]string{"text": text, "idempotency_key": key}
+ var in any = map[string]string{"text": text, "idempotency_key": key}
+ if len(files) > 0 {
+ in = map[string]any{"text": text, "idempotency_key": key, "attachments": files}
+ }
_, err := c.call(ctx, http.MethodPost, assistant+"/messages", token, key, nil, in, &out)
return out, err
}
diff --git a/internal/equipo/equipo.go b/internal/equipo/equipo.go
index f79c82b..b800739 100644
--- a/internal/equipo/equipo.go
+++ b/internal/equipo/equipo.go
@@ -25,10 +25,12 @@ import (
"time"
)
-// Error is a non-2xx answer from Equipo: its status and error code.
+// Error is a non-2xx answer from Equipo: its status and error code, and
+// for an upload or a read its Retry-After, if it gave one.
type Error struct {
- Status int
- Code string
+ Status int
+ Code string
+ RetryAfter string
}
func (e *Error) Error() string { return fmt.Sprintf("equipo: %d %s", e.Status, e.Code) }
@@ -90,6 +92,9 @@ type Client struct {
http *http.Client
// StreamHeaderTimeout bounds the wait for the event stream's headers.
StreamHeaderTimeout time.Duration
+ // FileTimeout bounds an upload, and the wait for a file's headers
+ // (60 s when zero).
+ FileTimeout time.Duration
}
// New is a client for the Equipo at origin. It never follows a redirect,
diff --git a/internal/equipo/equipo_test.go b/internal/equipo/equipo_test.go
index d2b2e26..fdb1e82 100644
--- a/internal/equipo/equipo_test.go
+++ b/internal/equipo/equipo_test.go
@@ -92,7 +92,7 @@ func TestSendCarriesBearerAndKey(t *testing.T) {
f := equipotest.New(t)
c := equipo.New(f.URL)
cred := signIn(t, f, c)
- sent, err := c.Send(context.Background(), cred.Token, "What can I do", "k-1")
+ sent, err := c.Send(context.Background(), cred.Token, "What can I do", "k-1", nil)
if err != nil {
t.Fatal(err)
}
@@ -158,7 +158,7 @@ func TestClientUsesAssistantRoutes(t *testing.T) {
if err != nil || len(snap.Cards) != 1 || !snap.Available || snap.Me.Address != "paul@tito.io" {
t.Fatalf("snapshot: %+v %v", snap, err)
}
- sent, err := c.Send(ctx, cred.Token, "What can I do", "k-1")
+ sent, err := c.Send(ctx, cred.Token, "What can I do", "k-1", nil)
if err != nil {
t.Fatal(err)
}
@@ -222,7 +222,7 @@ func TestSendWithoutRunner(t *testing.T) {
c := equipo.New(f.URL)
cred := signIn(t, f, c)
f.NoRunner()
- _, err := c.Send(context.Background(), cred.Token, "What can I do", "k-1")
+ _, err := c.Send(context.Background(), cred.Token, "What can I do", "k-1", nil)
if !errors.Is(err, equipo.ErrNoRunner) || errors.Is(err, equipo.ErrRunnerTooOld) {
t.Fatalf("send: %v, want ErrNoRunner", err)
}
@@ -438,7 +438,7 @@ func TestFakeGlanceIsLiveOnly(t *testing.T) {
cred := signIn(t, f, c)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
- sent, err := c.Send(ctx, cred.Token, "What's on today?", "k-1")
+ sent, err := c.Send(ctx, cred.Token, "What's on today?", "k-1", nil)
if err != nil {
t.Fatal(err)
}
diff --git a/internal/equipo/equipotest/chat.go b/internal/equipo/equipotest/chat.go
index 9ff1a45..1ef54ea 100644
--- a/internal/equipo/equipotest/chat.go
+++ b/internal/equipo/equipotest/chat.go
@@ -29,6 +29,9 @@ type message struct {
TurnID string `json:"turn_id"`
CreatedAt time.Time `json:"created_at"`
Switched *struct{} `json:"switched"`
+ // Attachments are the files sent with a person's message, in order;
+ // omitted when there are none (wire.Message).
+ Attachments []file `json:"attachments,omitempty"`
}
type turn struct {
@@ -366,10 +369,14 @@ func (f *Fake) Turn(id string) string {
}
func (f *Fake) serveChat(w http.ResponseWriter, r *http.Request) {
- if _, ok := f.bearer(r); !ok {
+ d, ok := f.bearer(r)
+ if !ok {
writeError(w, r, 401, "unauthenticated")
return
}
+ if f.serveFiles(w, r, d.id) {
+ return
+ }
// Only the Assistant's routes: a call to the Coordinator's is a 404.
p, ok := strings.CutPrefix(r.URL.Path, assistant)
switch {
@@ -386,7 +393,7 @@ func (f *Fake) serveChat(w http.ResponseWriter, r *http.Request) {
writeJSON(w, 200, map[string]any{"items": f.tail(), "before": ""})
f.cmu.Unlock()
case r.Method == http.MethodPost && p == "/messages":
- f.send(w, r)
+ f.send(w, r, d.id)
case r.Method == http.MethodPost && strings.HasPrefix(p, "/turns/") && strings.HasSuffix(p, "/cancel"):
f.cancel(w, r, strings.TrimSuffix(strings.TrimPrefix(p, "/turns/"), "/cancel"))
case r.Method == http.MethodPost && strings.HasPrefix(p, "/cards/") && strings.HasSuffix(p, "/answer"):
@@ -439,7 +446,7 @@ func (f *Fake) snapshot(w http.ResponseWriter, r *http.Request) {
"me": map[string]any{"id": f.address, "address": f.address, "role": "owner",
"person": map[string]any{"name": "Paul"}, "team_id": f.Instance, "team_name": "Tito"},
"messages": f.tail(), "turns": turns, "cards": cards, "cursor": f.cursor,
- "available": f.runner == "",
+ "available": f.runner == "", "can_attach": f.canAttach(),
})
}
@@ -465,7 +472,17 @@ func (f *Fake) host(w http.ResponseWriter, r *http.Request) {
writeJSON(w, 200, map[string]any{"origin": in.Origin, "revision": len(f.Hosts())})
}
-func (f *Fake) send(w http.ResponseWriter, r *http.Request) {
+// send is POST messages, as Equipo's LaneStore.Send with files (the
+// assistant-attachments spec, A1): text may be empty when files come; at
+// most five, each the person's own and unsent; files need a runner that
+// can take them (409 attachments_unavailable, nothing stored). A replayed
+// key with other text or files is 409 idempotency_conflict.
+func (f *Fake) send(w http.ResponseWriter, r *http.Request, owner string) {
+ f.fmu.Lock()
+ hold, entered := f.sendHold, f.sendEntered
+ f.sendHold, f.sendEntered = nil, nil
+ f.fmu.Unlock()
+ f.waitHeld(hold, entered)
var in struct {
Text string `json:"text"`
IdempotencyKey string `json:"idempotency_key"`
@@ -476,9 +493,9 @@ func (f *Fake) send(w http.ResponseWriter, r *http.Request) {
return
}
in.Text = strings.TrimSpace(in.Text)
- if in.Text == "" || len(in.Text) > 16<<10 || !utf8.ValidString(in.Text) ||
- len(in.IdempotencyKey) < 1 || len(in.IdempotencyKey) > 128 ||
- strings.HasPrefix(in.IdempotencyKey, "reply:") || strings.HasPrefix(in.IdempotencyKey, "card:") {
+ if (in.Text == "" && len(in.Attachments) == 0) || len(in.Text) > 16<<10 || !utf8.ValidString(in.Text) || strings.ContainsRune(in.Text, 0) ||
+ len(in.IdempotencyKey) < 1 || len(in.IdempotencyKey) > 128 || len(in.Attachments) > maxFiles ||
+ strings.HasPrefix(in.IdempotencyKey, "reply:") || strings.HasPrefix(in.IdempotencyKey, "card:") || strings.HasPrefix(in.IdempotencyKey, "handoff:") {
writeError(w, r, 422, "invalid_input")
return
}
@@ -489,16 +506,31 @@ func (f *Fake) send(w http.ResponseWriter, r *http.Request) {
writeError(w, r, 409, code)
return
}
+ if len(in.Attachments) > 0 && !f.canAttach() {
+ f.cmu.Unlock()
+ writeError(w, r, 409, "attachments_unavailable")
+ return
+ }
if id, ok := f.sent[in.IdempotencyKey]; ok {
for _, m := range f.messages {
- if m.ID == id {
+ if m.ID != id {
+ continue
+ }
+ if m.Text != in.Text || !sameFiles(m.Attachments, in.Attachments) {
+ writeError(w, r, 409, "idempotency_conflict")
+ } else {
writeJSON(w, 200, map[string]any{"message": m, "turn": *f.turns[m.TurnID]})
}
}
f.cmu.Unlock()
return
}
- m, t := f.ask(in.Text)
+ if !f.checkFiles(owner, in.Attachments) {
+ f.cmu.Unlock()
+ writeError(w, r, 422, "invalid_input")
+ return
+ }
+ m, t := f.askWith(in.Text, func(id string) []file { return f.linkFiles(in.Attachments, id) })
f.sent[in.IdempotencyKey] = m.ID
f.cmu.Unlock()
f.mu.Lock()
@@ -513,11 +545,38 @@ func (f *Fake) send(w http.ResponseWriter, r *http.Request) {
go f.answerTurn(t.ID, in.Text)
}
+// canAttach is the snapshot's can_attach: a runner that can answer and
+// can take files.
+func (f *Fake) canAttach() bool {
+ f.fmu.Lock()
+ defer f.fmu.Unlock()
+ return f.filesReady && f.runner == ""
+}
+
+func sameFiles(have []file, ids []string) bool {
+ if len(have) != len(ids) {
+ return false
+ }
+ for i := range have {
+ if have[i].ID != ids[i] {
+ return false
+ }
+ }
+ return true
+}
+
// ask records the person's message and a queued turn; the caller holds cmu.
-func (f *Fake) ask(text string) (message, turn) {
+func (f *Fake) ask(text string) (message, turn) { return f.askWith(text, nil) }
+
+// askWith is ask for a message with files: link, when set, links them to
+// the message's id and answers them.
+func (f *Fake) askWith(text string, link func(id string) []file) (message, turn) {
now := time.Now().UTC()
t := &turn{ID: f.next("t"), Revision: 1, State: "queued", Attempt: 1, CreatedAt: now, UpdatedAt: now}
m := message{ID: f.next("m"), Revision: 1, Role: "person", Text: text, TurnID: t.ID, CreatedAt: now}
+ if link != nil {
+ m.Attachments = link(m.ID)
+ }
t.MessageIDs = []string{m.ID}
f.turns[t.ID] = t
f.messages = append(f.messages, m)
diff --git a/internal/equipo/equipotest/fake.go b/internal/equipo/equipotest/fake.go
index 3169cc8..de46c00 100644
--- a/internal/equipo/equipotest/fake.go
+++ b/internal/equipo/equipotest/fake.go
@@ -74,6 +74,7 @@ type Fake struct {
snapHold, snapEntered chan struct{}
chat
nativeState
+ fileState
}
// HoldNextExchange makes the next exchange wait, once it has arrived and
@@ -161,6 +162,7 @@ func New(t testing.TB) *Fake {
Reply: func(string) string { return "Hello. What shall we work on?" }}
f.chat.init()
f.nativeState.init()
+ f.fileState.initFiles()
f.srv = httptest.NewServer(http.HandlerFunc(f.serve))
f.URL = f.srv.URL
t.Cleanup(func() {
@@ -232,10 +234,20 @@ func (f *Fake) Revoked(id string) bool {
}
func (f *Fake) serve(w http.ResponseWriter, r *http.Request) {
- body, _ := io.ReadAll(io.LimitReader(r.Body, 64<<10))
+ // An upload is read whole, as Equipo's ReadUpload does, unless it says
+ // it is over the limit; a call keeps its first 64 KiB.
+ limit := int64(64 << 10)
+ if r.Method == http.MethodPost && r.URL.Path == attachments {
+ limit = maxUpload + 1
+ if r.ContentLength > maxUpload {
+ limit = 0
+ }
+ }
+ body, _ := io.ReadAll(io.LimitReader(r.Body, limit))
r.Body = io.NopCloser(bytes.NewReader(body))
+ kept := body[:min(len(body), 64<<10)]
f.mu.Lock()
- f.calls = append(f.calls, Call{r.Method, r.URL.Path, r.URL.RawQuery, r.Header.Clone(), string(body)})
+ f.calls = append(f.calls, Call{r.Method, r.URL.Path, r.URL.RawQuery, r.Header.Clone(), string(kept)})
f.mu.Unlock()
w.Header().Set("Cache-Control", "no-store")
// Equipo's native sign-in has rules of its own (native.go).
diff --git a/internal/equipo/equipotest/files.go b/internal/equipo/equipotest/files.go
new file mode 100644
index 0000000..8bc6e6c
--- /dev/null
+++ b/internal/equipo/equipotest/files.go
@@ -0,0 +1,431 @@
+package equipotest
+
+import (
+ "bytes"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/hex"
+ "image"
+ _ "image/gif" // DecodeConfig for the image types Equipo sniffs
+ _ "image/jpeg"
+ _ "image/png"
+ "io"
+ "mime"
+ "net/http"
+ "path"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+ "unicode/utf8"
+)
+
+// Equipo's attachments (internal/attach, chat/attachments.go and
+// attachments_http.go, and the delete route of the assistant-attachments
+// spec, A2): POST /api/v1/attachments takes one file (the bytes as the
+// body, its type in Content-Type, its name in Content-Disposition) and
+// answers 201 with its wire.MessageAttachment; GET
+// /api/v1/attachments/{id} and /preview serve the person's own file;
+// DELETE /api/v1/attachments/{id} deletes an unsent one (204), 404 when it
+// isn't the person's or is gone, 409 attachment_sent once it is on a
+// message. A person here is a device: another device's file is 404.
+
+// Equipo's limits (internal/attach).
+const (
+ maxUpload = 10 << 20
+ maxFiles = 5
+ maxUnsent = 20
+ maxSide = 12000
+ maxPixels = 40_000_000
+ attachments = "/api/v1/attachments"
+)
+
+// file is one upload: its wire.MessageAttachment and its bytes.
+type file struct {
+ ID string `json:"id"`
+ Revision int64 `json:"revision"`
+ Kind string `json:"kind"`
+ Name string `json:"name"`
+ MediaType string `json:"media_type"`
+ Size int64 `json:"size"`
+ SHA256 string `json:"sha256"`
+ Width int `json:"width"`
+ Height int `json:"height"`
+ MessageID string `json:"message_id"`
+ CreatedAt time.Time `json:"created_at"`
+ owner string
+ data []byte
+}
+
+// fileState is the fake's files and the switches tests turn.
+type fileState struct {
+ fmu sync.Mutex
+ files map[string]*file
+ // filesReady says the person's runner can take files (can_attach);
+ // false, as for a runner never seen, until FilesReady.
+ filesReady bool
+ // expired makes the next send with files 422, as an upload dropped
+ // after 24 hours does.
+ expired bool
+ // uploadHold and uploadEntered hold the next upload, once its body has
+ // arrived and before it answers; busyNext makes the next upload 503
+ // with Retry-After: 1; uploadDelay slows every upload, so a test sees
+ // how many overlap (uploading, most).
+ uploadHold, uploadEntered chan struct{}
+ busyNext bool
+ uploadDelay time.Duration
+ uploading, most int
+ // hostileType and hostileDisposition, when set, are what every read
+ // answers with instead of Equipo's own; readDelay writes a read in 64
+ // KiB pieces with this pause between; readStatus, when set, is what
+ // every read answers (with an error body).
+ hostileType, hostileDisposition string
+ readDelay time.Duration
+ readStatus int
+ // sendHold and sendEntered hold the next send of a message, once it
+ // has arrived and before it is looked at.
+ sendHold, sendEntered chan struct{}
+}
+
+func (s *fileState) initFiles() { s.files = map[string]*file{} }
+
+// FilesReady says whether the person's runner can take files: the
+// snapshot's can_attach, and whether a send with files passes (else 409
+// attachments_unavailable).
+func (f *Fake) FilesReady(ok bool) { f.fmu.Lock(); f.filesReady = ok; f.fmu.Unlock() }
+
+// ExpireUploads makes the next send with files 422 invalid_input, as when
+// an upload was dropped after 24 hours unsent.
+func (f *Fake) ExpireUploads() { f.fmu.Lock(); f.expired = true; f.fmu.Unlock() }
+
+// HoldNextUpload makes the next upload wait, once its body has arrived and
+// before it answers, until release is called. entered is closed when it
+// arrives.
+func (f *Fake) HoldNextUpload() (entered <-chan struct{}, release func()) {
+ f.fmu.Lock()
+ defer f.fmu.Unlock()
+ f.uploadHold, f.uploadEntered = make(chan struct{}), make(chan struct{})
+ hold := f.uploadHold
+ return f.uploadEntered, sync.OnceFunc(func() { close(hold) })
+}
+
+// HoldNextSend makes the next send of a message wait, once it has arrived
+// and before it is looked at, until release is called. entered is closed
+// when it arrives.
+func (f *Fake) HoldNextSend() (entered <-chan struct{}, release func()) {
+ f.fmu.Lock()
+ defer f.fmu.Unlock()
+ f.sendHold, f.sendEntered = make(chan struct{}), make(chan struct{})
+ hold := f.sendHold
+ return f.sendEntered, sync.OnceFunc(func() { close(hold) })
+}
+
+// BusyNextUpload makes the next upload answer 503 with Retry-After: 1.
+func (f *Fake) BusyNextUpload() { f.fmu.Lock(); f.busyNext = true; f.fmu.Unlock() }
+
+// SlowUploads makes every upload take d before it answers.
+func (f *Fake) SlowUploads(d time.Duration) { f.fmu.Lock(); f.uploadDelay = d; f.fmu.Unlock() }
+
+// UploadsAtOnce is the most uploads the fake has had in flight at once.
+func (f *Fake) UploadsAtOnce() int { f.fmu.Lock(); defer f.fmu.Unlock(); return f.most }
+
+// ServeHostile makes every read answer with Content-Type typ and
+// Content-Disposition disposition, as a broken Equipo might ("" for
+// Equipo's own).
+func (f *Fake) ServeHostile(typ, disposition string) {
+ f.fmu.Lock()
+ f.hostileType, f.hostileDisposition = typ, disposition
+ f.fmu.Unlock()
+}
+
+// ServeSlowly makes every read write its bytes 64 KiB at a time, pausing
+// d between pieces.
+func (f *Fake) ServeSlowly(d time.Duration) { f.fmu.Lock(); f.readDelay = d; f.fmu.Unlock() }
+
+// FailReads makes every read answer status with an error body (0 stops).
+func (f *Fake) FailReads(status int) { f.fmu.Lock(); f.readStatus = status; f.fmu.Unlock() }
+
+// FileErrorBody is in the body of every read FailReads fails, so a test
+// can see that it never comes through.
+const FileErrorBody = "equipo-error-body"
+
+// Upload is the upload with id as the fake keeps it: its bytes, name and
+// type, and the message it went with ("" while unsent). ok is false once
+// it is deleted, or if there never was one.
+func (f *Fake) Upload(id string) (data []byte, name, media, message string, ok bool) {
+ f.fmu.Lock()
+ defer f.fmu.Unlock()
+ u, ok := f.files[id]
+ if !ok {
+ return nil, "", "", "", false
+ }
+ return u.data, u.Name, u.MediaType, u.MessageID, true
+}
+
+// Uploads are the ids of the files the fake holds, sent or not.
+func (f *Fake) Uploads() []string {
+ f.fmu.Lock()
+ defer f.fmu.Unlock()
+ var out []string
+ for id := range f.files {
+ out = append(out, id)
+ }
+ return out
+}
+
+// serveFiles answers the attachment routes for the person behind the
+// bearer (owner); ok is false for any other path.
+func (f *Fake) serveFiles(w http.ResponseWriter, r *http.Request, owner string) bool {
+ p := r.URL.Path
+ switch {
+ case r.Method == http.MethodPost && p == attachments:
+ f.upload(w, r, owner)
+ case !strings.HasPrefix(p, attachments+"/"):
+ return false
+ case r.Method == http.MethodDelete:
+ f.deleteFile(w, r, owner, strings.TrimPrefix(p, attachments+"/"))
+ case r.Method == http.MethodGet || r.Method == http.MethodHead:
+ id, preview := strings.TrimPrefix(p, attachments+"/"), false
+ if rest, ok := strings.CutSuffix(id, "/preview"); ok {
+ id, preview = rest, true
+ }
+ f.readFile(w, r, owner, id, preview)
+ default:
+ writeError(w, r, 404, "not_found")
+ }
+ return true
+}
+
+// upload is POST /api/v1/attachments, as Equipo's chat.ReadUpload and
+// Store.Upload: the type sniffed from the bytes, never the declared one.
+func (f *Fake) upload(w http.ResponseWriter, r *http.Request, owner string) {
+ f.fmu.Lock()
+ f.uploading++
+ f.most = max(f.most, f.uploading)
+ hold, entered, busy, delay := f.uploadHold, f.uploadEntered, f.busyNext, f.uploadDelay
+ f.uploadHold, f.uploadEntered, f.busyNext = nil, nil, false
+ f.fmu.Unlock()
+ defer func() { f.fmu.Lock(); f.uploading--; f.fmu.Unlock() }()
+ f.waitHeld(hold, entered)
+ if delay > 0 {
+ select {
+ case <-time.After(delay):
+ case <-f.closing:
+ }
+ }
+ if busy {
+ w.Header().Set("Retry-After", "1")
+ writeError(w, r, 503, "unavailable")
+ return
+ }
+ data, _ := io.ReadAll(r.Body)
+ if r.ContentLength > maxUpload || len(data) > maxUpload {
+ writeError(w, r, 413, "attachment_too_large")
+ return
+ }
+ name := ""
+ if _, params, err := mime.ParseMediaType(r.Header.Get("Content-Disposition")); err == nil {
+ name = params["filename"]
+ }
+ u, status, code := sniff(name, r.Header.Get("Content-Type"), data)
+ if status != 0 {
+ writeError(w, r, status, code)
+ return
+ }
+ f.fmu.Lock()
+ defer f.fmu.Unlock()
+ unsent := 0
+ for _, x := range f.files {
+ if x.owner == owner && x.MessageID == "" {
+ unsent++
+ }
+ }
+ if unsent >= maxUnsent {
+ writeError(w, r, 409, "attachment_limit")
+ return
+ }
+ sum := sha256.Sum256(data)
+ u.ID, u.Revision, u.owner, u.data = "at_"+strings.ToLower(rand.Text()), 1, owner, data
+ u.Size, u.SHA256, u.CreatedAt = int64(len(data)), hex.EncodeToString(sum[:]), time.Now().UTC()
+ f.files[u.ID] = u
+ writeJSON(w, http.StatusCreated, *u)
+}
+
+// sniff is the file Equipo would keep for data named name: its kind,
+// type, name and size, or the status and code it refuses it with.
+func sniff(name, declared string, data []byte) (*file, int, string) {
+ u := &file{Kind: "file", Name: safeName(name)}
+ declared, _, _ = mime.ParseMediaType(declared)
+ heic := len(data) >= 12 && string(data[4:8]) == "ftyp" && strings.Contains("heic heix mif1 hevc", string(data[8:12]))
+ if declared == "image/heic" || declared == "image/heif" || heic {
+ return nil, 415, "attachment_heic"
+ }
+ if len(data) == 0 {
+ return nil, 415, "attachment_type"
+ }
+ switch ct := http.DetectContentType(data); {
+ case ct == "image/png" || ct == "image/jpeg" || ct == "image/gif" || ct == "image/webp":
+ u.Kind, u.MediaType = "image", ct
+ if cfg, _, err := image.DecodeConfig(bytes.NewReader(data)); err == nil {
+ u.Width, u.Height = cfg.Width, cfg.Height
+ }
+ if u.Width > maxSide || u.Height > maxSide || u.Width*u.Height > maxPixels {
+ return nil, 413, "attachment_pixels"
+ }
+ case ct == "application/pdf":
+ u.MediaType = ct
+ case strings.HasPrefix(ct, "text/") && utf8.Valid(data):
+ switch ext := strings.ToLower(path.Ext(u.Name)); {
+ case declared == "text/markdown" || ext == ".md" || ext == ".markdown":
+ u.MediaType = "text/markdown"
+ case declared == "text/csv" || ext == ".csv":
+ u.MediaType = "text/csv"
+ case declared == "application/json" || ext == ".json":
+ u.MediaType = "application/json"
+ default:
+ u.MediaType = "text/plain"
+ }
+ default:
+ return nil, 415, "attachment_type"
+ }
+ return u, 0, ""
+}
+
+// safeName is a name as Equipo keeps it: its last path part, without
+// control characters, at most 255 bytes, "file" when nothing is left.
+func safeName(name string) string {
+ name = path.Base(strings.ReplaceAll(name, `\`, "/"))
+ name = strings.Map(func(r rune) rune {
+ if r < 0x20 || r == 0x7f {
+ return -1
+ }
+ return r
+ }, strings.ToValidUTF8(name, ""))
+ for len(name) > 255 {
+ _, n := utf8.DecodeLastRuneInString(name)
+ name = name[:len(name)-n]
+ }
+ if name == "" || name == "." || name == "/" {
+ return "file"
+ }
+ return name
+}
+
+// readFile is GET /api/v1/attachments/{id}[/preview], as Equipo's
+// serveFile: the sniffed type (text with its charset), inline for an image
+// and a download for anything else, nosniff and a sandboxing CSP. A
+// preview is an image's own bytes here (Equipo scales it), and 404 for a
+// file.
+func (f *Fake) readFile(w http.ResponseWriter, r *http.Request, owner, id string, preview bool) {
+ f.fmu.Lock()
+ u, ok := f.files[id]
+ status, typ, disposition, delay := f.readStatus, f.hostileType, f.hostileDisposition, f.readDelay
+ f.fmu.Unlock()
+ if status != 0 {
+ writeJSON(w, status, map[string]string{"code": FileErrorBody, "detail": FileErrorBody})
+ return
+ }
+ if !ok || u.owner != owner || preview && u.Kind != "image" {
+ writeError(w, r, 404, "not_found")
+ return
+ }
+ if typ == "" {
+ typ = u.MediaType
+ if strings.HasPrefix(typ, "text/") || typ == "application/json" {
+ typ += "; charset=utf-8"
+ }
+ }
+ if disposition == "" {
+ disposition = "attachment"
+ if u.Kind == "image" {
+ disposition = "inline"
+ }
+ }
+ h := w.Header()
+ h.Set("Content-Type", typ)
+ h.Set("Content-Length", strconv.Itoa(len(u.data)))
+ h.Set("Content-Disposition", mime.FormatMediaType(disposition, map[string]string{"filename": u.Name}))
+ h.Set("X-Content-Type-Options", "nosniff")
+ h.Set("Content-Security-Policy", "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; sandbox")
+ h.Set("Cache-Control", "private, max-age=86400")
+ h.Set("X-Equipo-Only", "yes")
+ w.WriteHeader(http.StatusOK)
+ if r.Method == http.MethodHead {
+ return
+ }
+ rc := http.NewResponseController(w)
+ for rest := u.data; len(rest) > 0; {
+ n := min(len(rest), 64<<10)
+ if _, err := w.Write(rest[:n]); err != nil {
+ return
+ }
+ rest = rest[n:]
+ if delay > 0 {
+ _ = rc.Flush()
+ select {
+ case <-time.After(delay):
+ case <-r.Context().Done():
+ return
+ case <-f.closing:
+ return
+ }
+ }
+ }
+}
+
+// deleteFile is DELETE /api/v1/attachments/{id}.
+func (f *Fake) deleteFile(w http.ResponseWriter, r *http.Request, owner, id string) {
+ f.fmu.Lock()
+ defer f.fmu.Unlock()
+ u, ok := f.files[id]
+ switch {
+ case !ok || u.owner != owner:
+ writeError(w, r, 404, "not_found")
+ case u.MessageID != "":
+ writeError(w, r, 409, "attachment_sent")
+ default:
+ delete(f.files, id)
+ w.WriteHeader(http.StatusNoContent)
+ }
+}
+
+// checkFiles reports whether a send may name ids, as Equipo's checkFiles
+// and linkFiles do: at most five, each the person's own and unsent, none
+// twice, and no upload dropped meanwhile (ExpireUploads).
+func (f *Fake) checkFiles(owner string, ids []string) bool {
+ f.fmu.Lock()
+ defer f.fmu.Unlock()
+ if len(ids) == 0 {
+ return true
+ }
+ if len(ids) > maxFiles {
+ return false
+ }
+ if f.expired {
+ f.expired = false
+ return false
+ }
+ seen := map[string]bool{}
+ for _, id := range ids {
+ u, ok := f.files[id]
+ if !ok || u.owner != owner || u.MessageID != "" || seen[id] {
+ return false
+ }
+ seen[id] = true
+ }
+ return true
+}
+
+// linkFiles links the checked ids to message m, in order, and answers
+// them as the message carries them.
+func (f *Fake) linkFiles(ids []string, m string) []file {
+ f.fmu.Lock()
+ defer f.fmu.Unlock()
+ var out []file
+ for _, id := range ids {
+ u := f.files[id]
+ u.MessageID, u.Revision = m, u.Revision+1
+ out = append(out, *u)
+ }
+ return out
+}
diff --git a/internal/equipo/files.go b/internal/equipo/files.go
new file mode 100644
index 0000000..00a184b
--- /dev/null
+++ b/internal/equipo/files.go
@@ -0,0 +1,163 @@
+package equipo
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "mime"
+ "net/http"
+ "net/url"
+ "time"
+)
+
+// Attachment is one of a message's files, as Equipo's
+// wire.MessageAttachment has it, with only the fields Base passes on: no
+// URL of Equipo's ever reaches a client, which builds Base's own
+// (/ask/attachments/{id}). Kind is image or file; Width and Height are an
+// image's upright size, 0 for a file.
+type Attachment struct {
+ ID string `json:"id"`
+ Kind string `json:"kind"`
+ Name string `json:"name"`
+ MediaType string `json:"media_type"`
+ Size int64 `json:"size"`
+ Width int `json:"width"`
+ Height int `json:"height"`
+}
+
+// The kinds of attachment.
+const (
+ AttachmentImage = "image"
+ AttachmentFile = "file"
+)
+
+// MaxUpload is the most an upload may be: Equipo's attach.MaxBytes,
+// 10 MiB. MaxFiles is the most a message may carry.
+const (
+ MaxUpload = 10 << 20
+ MaxFiles = 5
+)
+
+var (
+ // ErrAttachmentsUnavailable: the person's runner can't take files
+ // (never seen, or older than the protocol that carries them). Nothing
+ // was stored; words alone still send.
+ ErrAttachmentsUnavailable = &Error{Status: 409, Code: "attachments_unavailable"}
+ // ErrNotFound: no such file for the person (another's, or gone).
+ ErrNotFound = &Error{Status: 404}
+)
+
+// fileTimeout is FileTimeout's default.
+const fileTimeout = 60 * time.Second
+
+// do sends one request with a raw body of size bytes (nil for none) and
+// returns the answer unread, for the caller to read and close. A non-2xx
+// answer is an *Error with Equipo's code, its body read (a little) and
+// closed. It gives up when the headers take longer than FileTimeout; the
+// body is bounded by ctx alone.
+func (c *Client) do(ctx context.Context, method, path, token string, header http.Header, body []byte) (*http.Response, error) {
+ ctx, cancel := context.WithCancel(ctx)
+ var in io.Reader
+ if body != nil {
+ in = bytes.NewReader(body)
+ }
+ req, err := http.NewRequestWithContext(ctx, method, c.origin+path, in)
+ if err != nil {
+ cancel()
+ return nil, err
+ }
+ for k, v := range header {
+ req.Header[k] = v
+ }
+ req.Header.Set("Authorization", "Bearer "+token)
+ late := time.AfterFunc(c.fileTimeout(), cancel)
+ res, err := c.http.Do(req)
+ if !late.Stop() && err == nil {
+ res.Body.Close()
+ err = context.DeadlineExceeded
+ }
+ if err != nil {
+ cancel()
+ return nil, err
+ }
+ if res.StatusCode < 200 || res.StatusCode > 299 {
+ var e struct {
+ Code string `json:"code"`
+ }
+ raw, _ := io.ReadAll(io.LimitReader(res.Body, 4<<10))
+ _ = json.Unmarshal(raw, &e)
+ res.Body.Close()
+ cancel()
+ return nil, &Error{Status: res.StatusCode, Code: e.Code, RetryAfter: res.Header.Get("Retry-After")}
+ }
+ res.Body = cancelOnClose{res.Body, cancel}
+ return res, nil
+}
+
+func (c *Client) fileTimeout() time.Duration {
+ if c.FileTimeout > 0 {
+ return c.FileTimeout
+ }
+ return fileTimeout
+}
+
+// Upload sends one file to POST /api/v1/attachments: the bytes as the
+// body (with their length, which Equipo wants), the declared type in
+// Content-Type and the name in Content-Disposition (RFC 2231's filename*
+// for a name beyond ASCII). It carries no Idempotency-Key: Equipo's upload
+// takes none, and a retry is a second upload. Equipo's refusals come back
+// as an *Error with their code: attachment_too_large (413),
+// attachment_type and attachment_heic (415), attachment_pixels (413),
+// attachment_limit (409).
+func (c *Client) Upload(ctx context.Context, token, name, mediaType string, body []byte) (Attachment, error) {
+ if mediaType == "" {
+ mediaType = "application/octet-stream"
+ }
+ disposition := mime.FormatMediaType("attachment", map[string]string{"filename": name})
+ if disposition == "" {
+ disposition = "attachment"
+ }
+ h := http.Header{"Content-Type": {mediaType}, "Content-Disposition": {disposition}, "Accept": {"application/json"}}
+ ctx, cancel := context.WithTimeout(ctx, c.fileTimeout())
+ defer cancel()
+ res, err := c.do(ctx, http.MethodPost, "/api/v1/attachments", token, h, body)
+ if err != nil {
+ return Attachment{}, err
+ }
+ defer res.Body.Close()
+ var out Attachment
+ raw, err := io.ReadAll(io.LimitReader(res.Body, 64<<10))
+ if err == nil {
+ err = json.Unmarshal(raw, &out)
+ }
+ if err != nil || out.ID == "" {
+ return Attachment{}, fmt.Errorf("equipo: upload: %w", errors.Join(err, errors.New("no attachment in the answer")))
+ }
+ return out, nil
+}
+
+// OpenAttachment reads one of the person's files (its preview, an image's
+// thumbnail, with preview): the answer unread, for the caller to stream
+// and close. It is bounded by ctx, and by FileTimeout for the headers. A
+// file that isn't the person's, or is gone, is ErrNotFound.
+func (c *Client) OpenAttachment(ctx context.Context, token, id string, preview bool) (*http.Response, error) {
+ path := "/api/v1/attachments/" + url.PathEscape(id)
+ if preview {
+ path += "/preview"
+ }
+ return c.do(ctx, http.MethodGet, path, token, nil, nil)
+}
+
+// DeleteAttachment deletes one of the person's unsent uploads. Equipo's
+// 204, and its 404 (not the person's, or already gone), are done; a file
+// already sent is 409 attachment_sent.
+func (c *Client) DeleteAttachment(ctx context.Context, token, id string) error {
+ _, err := c.call(ctx, http.MethodDelete, "/api/v1/attachments/"+url.PathEscape(id), token, "", nil, nil, nil)
+ if errors.Is(err, ErrNotFound) {
+ return nil
+ }
+ return err
+}
diff --git a/internal/equipo/files_test.go b/internal/equipo/files_test.go
new file mode 100644
index 0000000..ee4ccc1
--- /dev/null
+++ b/internal/equipo/files_test.go
@@ -0,0 +1,208 @@
+package equipo_test
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "image"
+ "image/color"
+ "image/png"
+ "io"
+ "mime"
+ "net/http"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/base/internal/equipo"
+ "amadan.net/oficina/base/internal/equipo/equipotest"
+)
+
+// pngOf is a w×h PNG.
+func pngOf(t *testing.T, w, h int) []byte {
+ t.Helper()
+ img := image.NewNRGBA(image.Rect(0, 0, w, h))
+ img.Set(0, 0, color.NRGBA{R: 200, A: 255})
+ var b bytes.Buffer
+ if err := png.Encode(&b, img); err != nil {
+ t.Fatal(err)
+ }
+ return b.Bytes()
+}
+
+// An upload carries the bytes, the type, the name (RFC 2231 beyond ASCII)
+// and the bearer, and no Idempotency-Key: Equipo's upload takes none.
+func TestUploadSendsTheFile(t *testing.T) {
+ f := equipotest.New(t)
+ c := equipo.New(f.URL)
+ cred := signIn(t, f, c)
+ shot := pngOf(t, 40, 30)
+ at, err := c.Upload(context.Background(), cred.Token, "Captura de pantalla – día 1.png", "image/png", shot)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.HasPrefix(at.ID, "at_") || at.Kind != "image" || at.MediaType != "image/png" || at.Size != int64(len(shot)) ||
+ at.Width != 40 || at.Height != 30 || at.Name != "Captura de pantalla – día 1.png" {
+ t.Fatalf("attachment: %+v", at)
+ }
+ calls := f.Calls("/api/v1/attachments")
+ if len(calls) != 1 {
+ t.Fatalf("calls: %d", len(calls))
+ }
+ h := calls[0].Header
+ if h.Get("Authorization") != "Bearer "+cred.Token || h.Get("Content-Type") != "image/png" || len(h.Values("Idempotency-Key")) != 0 {
+ t.Errorf("headers: %v", h)
+ }
+ if !strings.Contains(h.Get("Content-Disposition"), "filename*=utf-8''") {
+ t.Errorf("disposition: %q", h.Get("Content-Disposition"))
+ }
+ if _, params, err := mime.ParseMediaType(h.Get("Content-Disposition")); err != nil || params["filename"] != at.Name {
+ t.Errorf("disposition %q: %v %v", h.Get("Content-Disposition"), params, err)
+ }
+ if data, _, _, _, ok := f.Upload(at.ID); !ok || !bytes.Equal(data, shot) {
+ t.Fatalf("the fake holds %d bytes, ok %v", len(data), ok)
+ }
+}
+
+// Equipo's refusals come back with their codes.
+func TestUploadRefusals(t *testing.T) {
+ f := equipotest.New(t)
+ c := equipo.New(f.URL)
+ cred := signIn(t, f, c)
+ ctx := context.Background()
+ heic := append([]byte("\x00\x00\x00\x18ftypheic"), make([]byte, 64)...)
+ for name, tc := range map[string]struct {
+ body []byte
+ typ string
+ status int
+ code string
+ }{
+ "too large": {bytes.Repeat([]byte("a"), equipo.MaxUpload+1), "text/plain", 413, "attachment_too_large"},
+ "type": {[]byte("\x00\x01\x02\x03binary"), "application/octet-stream", 415, "attachment_type"},
+ "heic": {heic, "image/heic", 415, "attachment_heic"},
+ "pixels": {pngOf(t, 12001, 1), "image/png", 413, "attachment_pixels"},
+ } {
+ _, err := c.Upload(ctx, cred.Token, "x", tc.typ, tc.body)
+ var e *equipo.Error
+ if !errors.As(err, &e) || e.Status != tc.status || e.Code != tc.code {
+ t.Errorf("%s: %v, want %d %s", name, err, tc.status, tc.code)
+ }
+ }
+ for i := 0; i < 20; i++ {
+ if _, err := c.Upload(ctx, cred.Token, "n.txt", "text/plain", []byte("note")); err != nil {
+ t.Fatalf("upload %d: %v", i, err)
+ }
+ }
+ _, err := c.Upload(ctx, cred.Token, "n.txt", "text/plain", []byte("note"))
+ if e := (*equipo.Error)(nil); !errors.As(err, &e) || e.Status != 409 || e.Code != "attachment_limit" {
+ t.Fatalf("21st: %v", err)
+ }
+ f.BusyNextUpload()
+ _, err = c.Upload(ctx, cred.Token, "n.txt", "text/plain", []byte("note"))
+ if e := (*equipo.Error)(nil); !errors.As(err, &e) || e.Status != 503 || e.RetryAfter != "1" {
+ t.Fatalf("busy: %#v", err)
+ }
+}
+
+// A send with files names them in order; without, its body is what it
+// always was. A runner that can't take files is ErrAttachmentsUnavailable.
+func TestSendWithFiles(t *testing.T) {
+ f := equipotest.New(t)
+ c := equipo.New(f.URL)
+ cred := signIn(t, f, c)
+ ctx := context.Background()
+ f.Hold = true
+ if _, err := c.Send(ctx, cred.Token, "plain", "k-0", nil); err != nil {
+ t.Fatal(err)
+ }
+ if body := strings.TrimSpace(f.Calls("/api/v1/assistant/messages")[0].Body); body != `{"idempotency_key":"k-0","text":"plain"}` {
+ t.Fatalf("words-only body: %s", body)
+ }
+ a, _ := c.Upload(ctx, cred.Token, "a.md", "text/markdown", []byte("# A"))
+ b, _ := c.Upload(ctx, cred.Token, "b.png", "image/png", pngOf(t, 4, 4))
+ if _, err := c.Send(ctx, cred.Token, "", "k-1", []string{b.ID, a.ID}); !errors.Is(err, equipo.ErrAttachmentsUnavailable) {
+ t.Fatalf("not ready: %v", err)
+ }
+ f.FilesReady(true)
+ if snap, err := c.Snapshot(ctx, cred.Token); err != nil || !snap.CanAttach {
+ t.Fatalf("snapshot: %+v %v", snap, err)
+ }
+ sent, err := c.Send(ctx, cred.Token, "", "k-1", []string{b.ID, a.ID})
+ if err != nil {
+ t.Fatal(err)
+ }
+ calls := f.Calls("/api/v1/assistant/messages")
+ var body struct {
+ Attachments []string `json:"attachments"`
+ }
+ if err := json.Unmarshal([]byte(calls[len(calls)-1].Body), &body); err != nil || len(body.Attachments) != 2 || body.Attachments[0] != b.ID {
+ t.Fatalf("body: %s", calls[len(calls)-1].Body)
+ }
+ got := sent.Message.Attachments
+ if len(got) != 2 || got[0].ID != b.ID || got[0].Kind != "image" || got[1].Name != "a.md" || got[1].MediaType != "text/markdown" {
+ t.Fatalf("sent: %+v", sent.Message)
+ }
+ snap, _ := c.Snapshot(ctx, cred.Token)
+ last := snap.Messages[len(snap.Messages)-1]
+ if len(last.Attachments) != 2 || last.Attachments[1].ID != a.ID || last.Attachments[0].Width != 4 {
+ t.Fatalf("snapshot message: %+v", last)
+ }
+}
+
+// A read is the answer unread; another's file, or one gone, is
+// ErrNotFound. Deleting an unsent upload is done, and so is one already
+// gone; one sent is Equipo's 409.
+func TestOpenAndDeleteAttachment(t *testing.T) {
+ f := equipotest.New(t)
+ c := equipo.New(f.URL)
+ cred := signIn(t, f, c)
+ other := signIn(t, f, c)
+ ctx := context.Background()
+ shot := pngOf(t, 8, 8)
+ at, _ := c.Upload(ctx, cred.Token, "s.png", "image/png", shot)
+ res, err := c.OpenAttachment(ctx, cred.Token, at.ID, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, _ := io.ReadAll(res.Body)
+ res.Body.Close()
+ if res.StatusCode != 200 || !bytes.Equal(got, shot) || res.Header.Get("Content-Type") != "image/png" {
+ t.Fatalf("read: %d %q %d bytes", res.StatusCode, res.Header.Get("Content-Type"), len(got))
+ }
+ if _, err := c.OpenAttachment(ctx, other.Token, at.ID, false); !errors.Is(err, equipo.ErrNotFound) {
+ t.Fatalf("another's: %v", err)
+ }
+ if err := c.DeleteAttachment(ctx, other.Token, at.ID); err != nil {
+ t.Fatalf("another's delete: %v", err)
+ }
+ if _, _, _, _, ok := f.Upload(at.ID); !ok {
+ t.Fatal("another person deleted it")
+ }
+ if err := c.DeleteAttachment(ctx, cred.Token, at.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, _, _, ok := f.Upload(at.ID); ok {
+ t.Fatal("still there")
+ }
+ if err := c.DeleteAttachment(ctx, cred.Token, at.ID); err != nil {
+ t.Fatalf("again: %v", err)
+ }
+ if _, err := c.OpenAttachment(ctx, cred.Token, at.ID, false); !errors.Is(err, equipo.ErrNotFound) {
+ t.Fatalf("gone: %v", err)
+ }
+ f.FilesReady(true)
+ f.Hold = true
+ sentFile, _ := c.Upload(ctx, cred.Token, "n.txt", "text/plain", []byte("note"))
+ if _, err := c.Send(ctx, cred.Token, "with a note", "k-9", []string{sentFile.ID}); err != nil {
+ t.Fatal(err)
+ }
+ err = c.DeleteAttachment(ctx, cred.Token, sentFile.ID)
+ if e := (*equipo.Error)(nil); !errors.As(err, &e) || e.Status != 409 || e.Code != "attachment_sent" {
+ t.Fatalf("sent: %v", err)
+ }
+ for _, call := range f.Calls("/api/v1/attachments/" + sentFile.ID) {
+ if call.Method == http.MethodDelete && call.Header.Get("Authorization") != "Bearer "+cred.Token {
+ t.Errorf("delete headers: %v", call.Header)
+ }
+ }
+}
diff --git a/internal/web/ask_relay.go b/internal/web/ask_relay.go
index cd184aa..4c54c8a 100644
--- a/internal/web/ask_relay.go
+++ b/internal/web/ask_relay.go
@@ -129,7 +129,7 @@ func (a *app) askSend(w http.ResponseWriter, r *http.Request) {
}
return
}
- sent, err := a.ask.client.Send(r.Context(), c.token, text, askKey(r.PostFormValue("key")))
+ sent, err := a.ask.client.Send(r.Context(), c.token, text, askKey(r.PostFormValue("key")), nil)
a.askDone(w, r, c, err, sent)
}