oficina / equipo Public

Protocol 32: the Assistant's send takes files (Tasks 2-8)

Human

Prompt

Build Equipo's half of file attachments in Base Ask, slice 1, task by task from the approved plan on design/assistant-attachments; take Fable's cheap Equipo nits.

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

  Protocol 32 (Encode refuses Assistant files and drops earlier below it); the Assistant's send takes files only with a primary seen at 32 (409 attachments_unavailable), can_attach in the snapshot; DELETE /api/v1/attachments/{id}; earlier files on the Assistant's frames (14 days, 20, earlier_more, given way first); files-only text in every lane and the tail's sent-files line; the fence fails older runners' Assistant turns with files and acks their chunks; hand-offs leave files behind (files_left_behind); API docs and OpenAPI; three strings pending copy review.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 45b3d2847e4d8e732c80de8e81f74b1d3acd000c parent bffe07d
37 files changed, +1,255 −74
  • .rastrillo/budgets.txt +6 −6
  • docs/api/equipo-v1.md +12 −2
  • docs/api/equipo-v1.openapi.json +77 −9
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +3 −0
  • internal/equipo/chat/assistant_files_test.go +447 −0
  • internal/equipo/chat/attachments.go +81 −2
  • internal/equipo/chat/attachments_http.go +10 −0
  • internal/equipo/chat/handoff.go +73 −9
  • internal/equipo/chat/handoff_test.go +68 −0
  • internal/equipo/chat/http.go +5 −0
  • internal/equipo/chat/lane.go +95 −21
  • internal/equipo/chat/store.go +53 −4
  • internal/equipo/copy.go +7 −0
  • internal/runner/thin/files.go +1 −1
  • internal/thintest/assistant.go +6 −0
  • internal/thintest/assistant_contract_test.go +3 −1
  • internal/thintest/assistant_files_contract_test.go +142 −0
  • internal/thintest/attachments_contract_test.go +1 −1
  • internal/thintest/client.go +6 −0
  • internal/wire/assistant.go +24 −0
  • internal/wire/assistant_files_test.go +82 −0
  • internal/wire/assistant_test.go +1 −1
  • internal/wire/change_files_test.go +1 −1
  • internal/wire/frames.go +17 −1
  • internal/wire/injection_test.go +2 −2
  • internal/wire/mixed_protocol_test.go +1 −1
  • internal/wire/models_test.go +1 −1
  • internal/wire/opencode_test.go +1 −1
  • internal/wire/pinned_release_test.go +1 −1
  • internal/wire/publish_test.go +1 −1
  • internal/wire/runners.go +21 −3
  • internal/wire/runners_test.go +1 −1
  • internal/wire/schedule_test.go +1 −1
  • internal/wire/stuck_test.go +1 −1
  • internal/wire/usage_test.go +1 −1
  • internal/wire/warm_test.go +1 −1
  • internal/wire/wireschema/wireschema.go +1 −0
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 546de20f..a1c98c9f 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -14,8 +14,8 @@ perf GET /* skip Unknown private paths render 404; this fallback contains no scr
time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial reruns measured 18.079s and 22.031s. Keep migration, recovery, accounting and concurrency assertions; 60s leaves 30 percent headroom above loaded CI.
time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage.
-size internal/equipo 23238 - Native preview pass issuance, bound wrapper grants, Retry/timeline and honest no-access merge copy; measured 23238 source lines (2026-11-26).
-size internal/wire 7199 - Protocol 31 display facts, shared path validation, native task evidence fields and merge credential reasons; measured 7199 source lines (2026-11-26).
+size internal/equipo 23265 - Native preview pass issuance, bound wrapper grants, Retry/timeline, honest no-access merge copy and the composer's Remove deleting its upload; measured 23265 source lines (2026-11-26).
+size internal/wire 7264 - Protocol 31 display facts, shared path validation, native task evidence fields, merge credential reasons and protocol 32's Assistant files; measured 7264 source lines (2026-11-26).
size internal/equipotest - 12017 Task 21 repairs historical migration and conversation fixtures after Plan 3, and the Rastrillo upgrade contract comparing served assets with what Assets serves; measured 0/12017 source/test lines.
time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded);
time internal/runner 330s Plan 3 CI repair measured 292.120s for the full package (controller CI 472.184s).
@@ -38,7 +38,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full
perf GET /releases/* skip Verified runner release file downloads, not browser GET screens.
perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen.
time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s;
-size internal/runner/thin 28824 23538 Protocol 31 display facts, merge credential fallback, validation and Engineering-only publication guards; measured 28824/23538 (2026-11-26).
+size internal/runner/thin 29106 23893 Protocol 31 display facts, merge credential fallback, validation, Engineering-only publication guards and the Assistant's read_attachment with its notes; measured 29106/23893 (2026-11-26).
time internal/thintest 240s Thin contract and page tests, the Assistant's and the models' included, share one harness. Measured 202s on a shared 16 CPU box (2026-11-13); CI runs two lanes.
time internal/runner/mac 30s Mac runners (Darwin worker): real process groups killed after a grace and proven gone (SIGTERM, SIGKILL, the marker sweep), and the probes run end to end with fake srt and xcodebuild, P6 killing.
time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s).
@@ -56,7 +56,7 @@ perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for device
perf GET /api/v1/assistant/snapshot skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen.
perf GET /api/v1/assistant/messages skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen.
perf GET /api/v1/assistant/events skip Assistant event stream (Server-Sent Events), bearer-only and long-lived; not a screen.
-size internal/equipo/chat 34984 9873 Detail-only file facts, hosted projection, completion time, no-access merges and transactional preview task reads; measured 34984/9873 (2026-11-26).
+size internal/equipo/chat 35265 10388 Detail-only file facts, hosted projection, completion time, no-access merges, transactional preview task reads and the Assistant's files (send, earlier, fence, hand-off, delete); measured 35265/10388 (2026-11-26).
perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}.
perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}.
perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections.
@@ -70,8 +70,8 @@ perf GET /api/v1/tasks/{id}/files/{file} skip Research kept images: bearer-only
perf GET /tasks/{id}/files/{file} skip Research kept images: the bytes of one image, shown on the task page; a file, not a screen.
perf GET /api/v1/runners skip Mac runners person API: bearer-only JSON for devices; the browser shows runners in the Team section.
time cmd/equipo-runner 60s TestReleaseRunnerHasNoFakeWorker builds the release runner and the thin package under testbuild (about 12s locally).
-size internal/headless - 11437 Grant scenarios for a named repository (hub #48); the sign-in's account email at 1280 and 390; measured 11437 test lines.
-size internal/thintest - 35229 Protocol 31 facts and detail-only contracts, stuck tasks, paused-job clock, no-access merges; measured 35229 test lines (2026-11-26).
+size internal/headless - 11763 Grant scenarios for a named repository (hub #48); the sign-in's account email at 1280 and 390; the Assistant's files end to end, on staging and live; measured 11763 test lines (2026-11-26).
+size internal/thintest - 35373 Protocol 31 facts and detail-only contracts, stuck tasks, paused-job clock, no-access merges, the Assistant's files and the upload delete; measured 35373 test lines (2026-11-26).
perf GET /api/v1/projects/{id}/merge-policy skip Merge authority person API: bearer-only JSON for devices; the browser reads the policy on /projects/{id}.
perf GET /api/v1/usage skip Thin v1 person API: bearer-only JSON for devices; the browser reads usage through /usage.
diff --git a/docs/api/equipo-v1.md b/docs/api/equipo-v1.md
index 6221cff7..2dd7d5eb 100644
--- a/docs/api/equipo-v1.md
+++ b/docs/api/equipo-v1.md
@@ -98,6 +98,8 @@ Use a UTF-8 `idempotency_key` of 1–128 bytes. The prefixes `reply:`, `card:` a
To send images or files, upload each to `POST /api/v1/attachments` first. Send the file’s bytes as the body, its media type in `Content-Type`, and its name in the `filename` or `filename*` parameter of `Content-Disposition`. Each upload is limited to 10 MiB. Add the returned IDs to the message’s `attachments` array, at most five. The uploads must be yours and not already attached to another message. Text may be empty when you send attachments.
+An upload you have not sent is kept for 24 hours, and you may hold at most 20. To remove one before sending it, call `DELETE /api/v1/attachments/{id}`. The answer is `204` once it is gone. It is `404 not_found` when the upload is not yours or no longer exists: treat that as done. It is `409 attachment_sent` when it is already on a message; sent files stay.
+
Follow the conversation with `GET /api/v1/events?after=<cursor>`, a stream of Server-Sent Events. A nonempty `after` takes precedence over `Last-Event-ID`. With neither, the stream starts at the newest event. The stream opens with `retry: 2000`. Each stored event has an `id: <cursor>` line, an `event: <type>` line and a `data:` line containing the event as JSON. A `ping` arrives every 20 seconds, with only `{"type":"ping"}` as its data. A cursor older than the retained events returns `410 cursor_expired`. Read the snapshot again and follow from its cursor.
Each stored event has `cursor`, `type`, `resource`, `id`, `revision` and `data`. It may also have `turn_id`, `message_id` and `attempt`. The `type` and `resource` pair determines the `data` schema, such as `MessageEvent` or `ActivityStepEvent`:
@@ -146,7 +148,7 @@ The routes under `/api/v1/assistant` serve Base's chat with the Assistant. Every
The Assistant keeps its own conversation. Its messages, turns, cards and events never appear in the Coordinator's, and an ID from the Coordinator's conversation is `404 not_found` on every Assistant route.
-Start with `GET /api/v1/assistant/snapshot`. It returns `me`, the newest messages and their turns, the cards, the event `cursor`, and `available`. `available` is false when you have no runner of your own, or when your runner needs an update before it can answer the Assistant. Read older messages with `GET /api/v1/assistant/messages?before=<message ID>&limit=<count>`. `limit` is 1 to 200 and defaults to 50. The `before` in the response is the cursor for the page before; it is empty at the start of the conversation.
+Start with `GET /api/v1/assistant/snapshot`. It returns `me`, the newest messages and their turns, the cards, the event `cursor`, `available` and `can_attach`. `available` is false when you have no runner of your own, or when your runner needs an update before it can answer the Assistant. `can_attach` is true when a message with attachments would be taken now: your runner of your own was last seen on protocol 32 or later. Offer files only when it is true. Read older messages with `GET /api/v1/assistant/messages?before=<message ID>&limit=<count>`. `limit` is 1 to 200 and defaults to 50. The `before` in the response is the cursor for the page before; it is empty at the start of the conversation.
Send a message with `POST /api/v1/assistant/messages` and a key of your choosing, 1 to 128 bytes, in the body:
@@ -154,7 +156,15 @@ Send a message with `POST /api/v1/assistant/messages` and a key of your choosing
{"text":"What can I do here?","idempotency_key":"<a new key for each message>"}
```
-A new message is `201`, with the message and its turn. The same key and text again return `200` with the same result; the same key with other text is `409 idempotency_conflict`. Without a runner of your own the answer is `409 no_runner`, and with a runner that needs an update it is `409 runner_too_old`. Nothing is stored in either case. The Assistant takes words only, so a message with `attachments` is `422 invalid_input`.
+A new message is `201`, with the message and its turn. The same key and text again return `200` with the same result; the same key with other text is `409 idempotency_conflict`. Without a runner of your own the answer is `409 no_runner`, and with a runner that needs an update it is `409 runner_too_old`. Nothing is stored in either case.
+
+A message to the Assistant may carry files. Upload each with `POST /api/v1/attachments`, as for the Coordinator, and send the IDs in `attachments`, at most five. Text may be empty when you send attachments:
+
+```json
+{"text":"What does this say?","attachments":["at_…"],"idempotency_key":"<a new key for each message>"}
+```
+
+The same key with the same text and files returns `200`; the same key with other files is `409 idempotency_conflict`. An upload that is not yours, already sent, or more than a day old is `422 invalid_input`, and so is a sixth file. Files need your runner of your own on protocol 32 or later: until it has been seen there, a message with `attachments` is `409 attachments_unavailable` and nothing is stored, while words alone still go. `can_attach` in the snapshot gives the same answer in advance. The Assistant reads the files in the turn they arrive and, while your runner still holds them (up to 14 days), in later turns too. When you hand work to the team from a message with files, the job goes ahead without them. Card answers and job threads take words only.
Follow the conversation with `GET /api/v1/assistant/events?after=<cursor>`, a stream of Server-Sent Events. `after` wins over `Last-Event-ID`. With neither, the stream starts at the newest event. The stream opens with `retry: 2000`, then sends each event as `id: <cursor>`, `event: <type>` and `data:` with the event as JSON, whose own `data` field holds the message, turn, delta, glance, card or activity. The types are `message`, `turn`, `delta`, `glance`, `card` and `activity`, and a `ping` comes every 20 seconds. A cursor that is too old is `410 cursor_expired`. Read the snapshot again and follow from its cursor.
diff --git a/docs/api/equipo-v1.openapi.json b/docs/api/equipo-v1.openapi.json
index 0e042779..30c9b403 100644
--- a/docs/api/equipo-v1.openapi.json
+++ b/docs/api/equipo-v1.openapi.json
@@ -9349,7 +9349,7 @@
}
},
"409": {
- "description": "idempotency_conflict, no_runner or runner_too_old",
+ "description": "idempotency_conflict, no_runner, runner_too_old or attachments_unavailable",
"headers": {
"Cache-Control": {
"schema": {
@@ -10193,6 +10193,59 @@
}
}
}
+ },
+ "delete": {
+ "operationId": "delete_attachments_id",
+ "summary": "Delete one of your uploads you have not sent",
+ "description": "Removes the upload and its bytes, so it no longer counts towards the 20 unsent uploads you may hold. `404 not_found` when it is not yours or no longer exists: treat that as done. `409 attachment_sent` when it is on a message already; sent files stay.",
+ "security": [
+ {
+ "personBearer": []
+ }
+ ],
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "minLength": 1
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "Deleted",
+ "headers": {
+ "Cache-Control": {
+ "schema": {
+ "const": "no-store"
+ }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/unauthenticated"
+ },
+ "default": {
+ "description": "An error, with one of the codes in `Error`",
+ "headers": {
+ "Cache-Control": {
+ "schema": {
+ "const": "no-store"
+ }
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ }
+ }
}
},
"/attachments/{id}/preview": {
@@ -14392,7 +14445,9 @@
"already_running",
"offer_changed",
"preview_changed",
- "preview_expired"
+ "preview_expired",
+ "attachments_unavailable",
+ "attachment_sent"
]
},
"copy_key": {
@@ -14444,7 +14499,9 @@
"budgets.forbidden",
"budgets.revision_conflict",
"api.already_running",
- "api.offer_changed"
+ "api.offer_changed",
+ "api.attachments_unavailable",
+ "api.attachment_sent"
]
},
"request_id": {
@@ -17525,7 +17582,8 @@
"no_runner",
"runner_too_old",
"turn_ended",
- "host_not_allowed"
+ "host_not_allowed",
+ "attachments_unavailable"
]
},
"copy_key": {
@@ -17541,7 +17599,8 @@
"api.no_runner",
"api.runner_too_old",
"api.turn_ended",
- "api.host_not_allowed"
+ "api.host_not_allowed",
+ "api.attachments_unavailable"
]
},
"request_id": {
@@ -17699,6 +17758,12 @@
"type": "null"
}
]
+ },
+ "attachments": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/MessageAttachment"
+ }
}
},
"required": [
@@ -17992,6 +18057,10 @@
},
"available": {
"type": "boolean"
+ },
+ "can_attach": {
+ "type": "boolean",
+ "description": "A message with attachments would be taken now: your runner of your own was last seen on protocol 32 or later. Offer files only when true."
}
},
"required": [
@@ -18000,7 +18069,8 @@
"turns",
"cards",
"cursor",
- "available"
+ "available",
+ "can_attach"
],
"additionalProperties": false
},
@@ -18028,7 +18098,6 @@
"properties": {
"text": {
"type": "string",
- "minLength": 1,
"x-maxBytes": 16384
},
"idempotency_key": {
@@ -18038,14 +18107,13 @@
},
"attachments": {
"type": "array",
- "maxItems": 0,
+ "maxItems": 5,
"items": {
"type": "string"
}
}
},
"required": [
- "text",
"idempotency_key"
],
"additionalProperties": false
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index be78a21d..d1596ef4 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -6914,6 +6914,9 @@ records remain unchanged.
| `work.reason.amadan_unreachable` | Amadan could not be reached to confirm Equipo may merge here | Copy specialist | Runtime; COPY APPROVED (Paul, 2026-11-25, copy-review 6wxwi7zo3fph5nu4nm6eipptfq, unchanged) |
| `assistant.team.no_access` | The change is ready, but it can't go live until access to publish it is set up. | Told to the Assistant: where the work stands once going live was refused for want of access (merge_credential, merge_forbidden), instead of "waits for a go-ahead" | Runtime; COPY APPROVED (Paul, 2026-11-26, coordinator session, unchanged) |
| `assistant.job.detail.no_access` | It can't go live until access to publish it is set up. | Base job card: a stopped job's sentence more when going live was refused for want of access | Runtime; COPY APPROVED (Paul, 2026-11-26, coordinator session, unchanged) |
+| `runnerDraftCopy.api.attachments_unavailable` | Files can't be read right now. Send your message without them, or try again later. | Copy specialist | COPY REVIEW PENDING |
+| `runnerDraftCopy.api.attachment_sent` | This file has already been sent. | Copy specialist | COPY REVIEW PENDING |
+| `runnerDraftCopy.chat.activity.read_attachment` | Reading your file… | Copy specialist | COPY REVIEW PENDING |
## Task 21
diff --git a/internal/equipo/chat/assistant_files_test.go b/internal/equipo/chat/assistant_files_test.go
new file mode 100644
index 00000000..93fd7d5b
--- /dev/null
+++ b/internal/equipo/chat/assistant_files_test.go
@@ -0,0 +1,447 @@
+package chat
+
+import (
+ "encoding/json"
+ "errors"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+ "gorm.io/gorm"
+)
+
+// The Assistant's files (assistant attachments spec 2026-11-26, A1 to A6),
+// at the store: its send takes files only with a primary seen at protocol
+// 32, the snapshot says so, and its frames carry the files of the
+// conversation.
+
+// filesRig is a hkRig whose primary was last seen at protocol (none: no
+// session row).
+func filesRig(t *testing.T, protocol int) *hkRig {
+ t.Helper()
+ r := newHKRig(t)
+ if protocol > 0 {
+ r.must(r.s.db.G.Create(&runnerSessionRecord{RunnerID: "RUNNER1", Generation: 1, Connected: true, Protocol: protocol, SeenAt: r.now}).Error)
+ }
+ return r
+}
+
+// upload keeps a small text file for person.
+func (r *hkRig) upload(person, name, body string) string {
+ r.t.Helper()
+ a, err := r.s.Upload(r.ctx, person, name, "text/markdown", []byte(body))
+ r.must(err)
+ return a.ID
+}
+
+func ids(files []wire.MessageAttachment) []string {
+ out := make([]string, 0, len(files))
+ for _, f := range files {
+ out = append(out, f.ID)
+ }
+ return out
+}
+
+// unsent counts the person's uploads on no message.
+func (r *hkRig) unsent(person string) int64 {
+ return r.count("SELECT count(*) FROM chat_attachments WHERE person = ? AND message_id = ''", person)
+}
+
+// TestAssistantSendTakesFiles (A1): with a primary at 32 the Assistant's
+// send takes up to five of the person's own unsent uploads, in order, as
+// the Coordinator's does, and every view of the message carries them.
+func TestAssistantSendTakesFiles(t *testing.T) {
+ r := filesRig(t, wire.ProtocolAssistantFiles)
+ lane := r.s.Lane(wire.LaneAssistant)
+ a, b := r.upload(hkOwner, "a.md", "# a"), r.upload(hkOwner, "b.md", "# b")
+ sent, created, err := lane.Send(r.ctx, hkOwner, wire.SendMessage{Text: "Read these", Attachments: []string{a, b}, IdempotencyKey: "k1"})
+ if err != nil || !created {
+ t.Fatalf("send %v %v", created, err)
+ }
+ want := []string{a, b}
+ if !slices.Equal(ids(sent.Message.Attachments), want) {
+ t.Fatalf("sent with %v", ids(sent.Message.Attachments))
+ }
+ snap, err := lane.Snapshot(r.ctx, hkOwner)
+ if err != nil || len(snap.Messages) != 1 || !slices.Equal(ids(snap.Messages[0].Attachments), want) {
+ t.Fatalf("snapshot %+v %v", snap.Messages, err)
+ }
+ page, err := lane.Messages(r.ctx, hkOwner, "", 10)
+ if err != nil || len(page.Items) != 1 || !slices.Equal(ids(page.Items[0].Attachments), want) {
+ t.Fatalf("page %+v %v", page.Items, err)
+ }
+ events, err := lane.Events(r.ctx, hkOwner, 0, 50)
+ r.must(err)
+ found := false
+ for _, e := range events {
+ if e.Type == wire.EventMessage && strings.Contains(string(e.Data), a) && strings.Contains(string(e.Data), b) {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatalf("no message event with both files: %+v", events)
+ }
+
+ // Files with no words.
+ c := r.upload(hkOwner, "c.md", "# c")
+ if _, created, err := lane.Send(r.ctx, hkOwner, wire.SendMessage{Attachments: []string{c}, IdempotencyKey: "k2"}); err != nil || !created {
+ t.Fatalf("files only %v %v", created, err)
+ }
+ // The same key and files again is the same message; other files are
+ // a conflict.
+ again, created, err := lane.Send(r.ctx, hkOwner, wire.SendMessage{Text: "Read these", Attachments: []string{a, b}, IdempotencyKey: "k1"})
+ if err != nil || created || again.Message.ID != sent.Message.ID {
+ t.Fatalf("replay %v %v", created, err)
+ }
+ d := r.upload(hkOwner, "d.md", "# d")
+ if _, _, err := lane.Send(r.ctx, hkOwner, wire.SendMessage{Text: "Read these", Attachments: []string{a, d}, IdempotencyKey: "k1"}); !errors.Is(err, ErrConflict) {
+ t.Fatalf("replay with other files: %v", err)
+ }
+
+ // Refused as invalid: six files, another person's upload, a file
+ // already sent, an upload past its day, a project.
+ six := []string{}
+ for i := range 6 {
+ six = append(six, r.upload(hkOwner, "s"+string(rune('a'+i))+".md", "x"))
+ }
+ theirs := r.upload(hkMember, "theirs.md", "# theirs")
+ stale := r.upload(hkOwner, "stale.md", "# stale")
+ for name, in := range map[string]wire.SendMessage{
+ "six": {Text: "x", Attachments: six, IdempotencyKey: "k3"},
+ "theirs": {Text: "x", Attachments: []string{theirs}, IdempotencyKey: "k4"},
+ "sent": {Text: "x", Attachments: []string{a}, IdempotencyKey: "k5"},
+ "project": {Text: "x", ProjectID: "p1", IdempotencyKey: "k6"},
+ } {
+ if _, _, err := lane.Send(r.ctx, hkOwner, in); !errors.Is(err, ErrInvalid) {
+ t.Fatalf("%s: %v", name, err)
+ }
+ }
+ r.now = r.now.Add(unsentFor + time.Minute)
+ if _, _, err := lane.Send(r.ctx, hkOwner, wire.SendMessage{Text: "x", Attachments: []string{stale}, IdempotencyKey: "k7"}); !errors.Is(err, ErrInvalid) {
+ t.Fatalf("an upload past its day: %v", err)
+ }
+}
+
+// TestAssistantSendFilesNeedProtocol32 (A1, A6): files need a primary
+// last seen at 32. One older, or never seen, refuses the send with files
+// and stores nothing; the same words alone pass. No primary is no_runner.
+func TestAssistantSendFilesNeedProtocol32(t *testing.T) {
+ for name, protocol := range map[string]int{"at 31": wire.Protocol31, "never seen": 0} {
+ t.Run(name, func(t *testing.T) {
+ r := filesRig(t, protocol)
+ lane := r.s.Lane(wire.LaneAssistant)
+ a, b := r.upload(hkOwner, "a.md", "# a"), r.upload(hkOwner, "b.md", "# b")
+ if _, _, err := lane.Send(r.ctx, hkOwner, wire.SendMessage{Text: "Read these", Attachments: []string{a, b}, IdempotencyKey: "k1"}); !errors.Is(err, ErrAttachmentsUnavailable) {
+ t.Fatalf("send with files: %v", err)
+ }
+ if n := r.count("SELECT count(*) FROM chat_messages"); n != 0 || r.count("SELECT count(*) FROM chat_turns") != 0 || r.unsent(hkOwner) != 2 {
+ t.Fatalf("a refused send stored something: %d messages, %d unsent", n, r.unsent(hkOwner))
+ }
+ if _, created, err := lane.Send(r.ctx, hkOwner, wire.SendMessage{Text: "Read these", IdempotencyKey: "k1"}); err != nil || !created {
+ t.Fatalf("words alone: %v %v", created, err)
+ }
+ })
+ }
+ r := filesRig(t, 0)
+ r.s.authority.PrimaryRunner = func(*gorm.DB, string) (string, error) { return "", nil }
+ a := r.upload(hkOwner, "a.md", "# a")
+ if _, _, err := r.s.Lane(wire.LaneAssistant).Send(r.ctx, hkOwner, wire.SendMessage{Text: "x", Attachments: []string{a}, IdempotencyKey: "k1"}); !errors.Is(err, ErrNoRunner) {
+ t.Fatalf("no primary: %v", err)
+ }
+}
+
+// TestAssistantSnapshotCanAttach (A1): can_attach is exactly the answer
+// the send with files gets.
+func TestAssistantSnapshotCanAttach(t *testing.T) {
+ for name, tc := range map[string]struct {
+ protocol int
+ primary bool
+ want bool
+ }{
+ "at 32": {wire.ProtocolAssistantFiles, true, true},
+ "at 31": {wire.Protocol31, true, false},
+ "never seen": {0, true, false},
+ "no runner": {0, false, false},
+ } {
+ t.Run(name, func(t *testing.T) {
+ r := filesRig(t, tc.protocol)
+ if !tc.primary {
+ r.s.authority.PrimaryRunner = func(*gorm.DB, string) (string, error) { return "", nil }
+ }
+ snap, err := r.s.Lane(wire.LaneAssistant).Snapshot(r.ctx, hkOwner)
+ if err != nil || snap.CanAttach != tc.want {
+ t.Fatalf("can_attach %v, want %v: %v", snap.CanAttach, tc.want, err)
+ }
+ var check error
+ r.must(r.tx(func(t *txn) error { check = t.filesRunner(hkOwner); return nil }))
+ if (check == nil) != snap.CanAttach {
+ t.Fatalf("snapshot %v, send check %v", snap.CanAttach, check)
+ }
+ })
+ }
+}
+
+// TestDeleteUnsent (A2): the person deletes their own unsent upload, its
+// row and bytes, audited by id, and its slot is free again. Gone, or
+// another person's, is not found; one already sent stays.
+func TestDeleteUnsent(t *testing.T) {
+ r := filesRig(t, wire.ProtocolAssistantFiles)
+ var audits []string
+ r.s.authority.Audit = func(_ *gorm.DB, actor, kind, record string) error {
+ audits = append(audits, actor+" "+kind+" "+record)
+ return nil
+ }
+ held := []string{}
+ for i := range maxUnsent {
+ held = append(held, r.upload(hkOwner, "f"+string(rune('a'+i))+".md", "x"))
+ }
+ if _, err := r.s.Upload(r.ctx, hkOwner, "more.md", "text/markdown", []byte("x")); !errors.Is(err, ErrAttachmentLimit) {
+ t.Fatalf("the 21st upload: %v", err)
+ }
+ gone := held[0]
+ if err := r.s.DeleteUnsent(r.ctx, hkOwner, gone); err != nil {
+ t.Fatal(err)
+ }
+ if n := r.count("SELECT count(*) FROM chat_attachments WHERE id = ?", gone) + r.count("SELECT count(*) FROM chat_attachment_data WHERE id = ?", gone); n != 0 {
+ t.Fatalf("%d rows left", n)
+ }
+ if !slices.Contains(audits, hkOwner+" "+auditAttachmentDelete+" "+gone) {
+ t.Fatalf("audits %q", audits)
+ }
+ if _, err := r.s.Upload(r.ctx, hkOwner, "more.md", "text/markdown", []byte("x")); err != nil {
+ t.Fatalf("the 21st upload after a delete: %v", err)
+ }
+ if err := r.s.DeleteUnsent(r.ctx, hkOwner, gone); !errors.Is(err, ErrNotFound) {
+ t.Fatalf("second delete: %v", err)
+ }
+ if err := r.s.DeleteUnsent(r.ctx, hkMember, held[1]); !errors.Is(err, ErrNotFound) || r.unsent(hkOwner) != maxUnsent {
+ t.Fatalf("another person's: %v", err)
+ }
+ if _, _, err := r.s.Lane(wire.LaneAssistant).Send(r.ctx, hkOwner, wire.SendMessage{Attachments: []string{held[1]}, IdempotencyKey: "k1"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := r.s.DeleteUnsent(r.ctx, hkOwner, held[1]); !errors.Is(err, ErrAttachmentSent) || r.count("SELECT count(*) FROM chat_attachment_data WHERE id = ?", held[1]) != 1 {
+ t.Fatalf("a sent upload: %v", err)
+ }
+}
+
+// past records a person message in lane at, in a turn that was dispatched
+// and replied, carrying newly uploaded files (by name).
+func (r *hkRig) past(lane, text string, at time.Time, names ...string) []string {
+ r.t.Helper()
+ turn := turnRecord{ID: newID("t_"), Person: hkOwner, State: wire.TurnReplied, Attempt: 1, Dispatched: true, DispatchedAt: &at, Revision: 1, CreatedAt: at, UpdatedAt: at, Lane: lane}
+ r.must(r.s.db.G.Create(&turn).Error)
+ m := messageRecord{ID: newID("m_"), Person: hkOwner, IdempotencyKey: newID("k_"), Role: wire.RolePerson, Text: text, TurnID: turn.ID, Revision: 1, CreatedAt: at, Lane: lane, Origin: originComposer}
+ r.must(r.s.db.G.Create(&m).Error)
+ var ids []string
+ for i, name := range names {
+ id := r.upload(hkOwner, name, "# "+name)
+ r.must(r.s.db.G.Model(&fileRecord{}).Where("id = ?", id).Updates(map[string]any{"message_id": m.ID, "position": i + 1}).Error)
+ ids = append(ids, id)
+ }
+ return ids
+}
+
+// lastFrame is the newest message command queued for the runner.
+func (r *hkRig) lastFrame() wire.MessageCommand {
+ r.t.Helper()
+ var c commandRecord
+ r.must(r.s.db.G.Where("kind = ?", wire.FrameMessage).Order("seq DESC").First(&c).Error)
+ var m wire.MessageCommand
+ r.must(json.Unmarshal([]byte(c.Body), &m))
+ return m
+}
+
+func refIDs(refs []wire.AttachmentRef) []string {
+ out := []string{}
+ for _, f := range refs {
+ out = append(out, f.ID)
+ }
+ return out
+}
+
+// TestAssistantFrameEarlier (A4): an Assistant person turn's frame lists
+// the files of the person's own Assistant messages from the last 14 days,
+// newest first, without this turn's own; never the Coordinator's, never
+// older. A files-only message in the tail names its files.
+func TestAssistantFrameEarlier(t *testing.T) {
+ r := filesRig(t, wire.ProtocolAssistantFiles)
+ day := 24 * time.Hour
+ r.past(wire.LaneAssistant, "an old one", r.now.Add(-15*day), "old.md")
+ two := r.past(wire.LaneAssistant, "see these", r.now.Add(-3*day), "a.md", "b.md")
+ one := r.past(wire.LaneAssistant, "", r.now.Add(-day), "c.md")
+ r.past(wire.LaneCoordinator, "the coordinator's", r.now.Add(-day), "coord.md")
+ mine := r.upload(hkOwner, "now.md", "# now")
+ if _, _, err := r.s.Lane(wire.LaneAssistant).Send(r.ctx, hkOwner, wire.SendMessage{Text: "hello", Attachments: []string{mine}, IdempotencyKey: "k1"}); err != nil {
+ t.Fatal(err)
+ }
+ m := r.lastFrame()
+ if want := []string{one[0], two[0], two[1]}; !slices.Equal(refIDs(m.Earlier), want) || m.EarlierMore != 0 {
+ t.Fatalf("earlier %v (+%d), want %v", refIDs(m.Earlier), m.EarlierMore, want)
+ }
+ if !slices.Equal(refIDs(m.Attachments), []string{mine}) || m.Earlier[0].Name != "c.md" || m.Earlier[0].SHA256 == "" || m.Earlier[0].Size == 0 {
+ t.Fatalf("frame %+v", m)
+ }
+ var tail []string
+ for _, x := range m.Tail {
+ tail = append(tail, x.Text)
+ }
+ if !slices.Contains(tail, "(sent files: c.md)") || !slices.Contains(tail, "see these") || slices.Contains(tail, "") {
+ t.Fatalf("tail %q", tail)
+ }
+}
+
+// TestAssistantFrameEarlierCap: at most 20, newest first; earlier_more
+// counts the rest.
+func TestAssistantFrameEarlierCap(t *testing.T) {
+ r := filesRig(t, wire.ProtocolAssistantFiles)
+ var all []string
+ for i := range 5 {
+ ids := r.past(wire.LaneAssistant, "batch", r.now.Add(-time.Duration(5-i)*time.Hour), "1.md", "2.md", "3.md", "4.md", "5.md")
+ all = append(ids, all...)
+ }
+ // all is newest message first; each message's files in their order.
+ want := []string{}
+ for i := 0; i < 25; i += 5 {
+ want = append(want, all[i:i+5]...)
+ }
+ if _, _, err := r.s.Lane(wire.LaneAssistant).Send(r.ctx, hkOwner, wire.SendMessage{Text: "hello", IdempotencyKey: "k1"}); err != nil {
+ t.Fatal(err)
+ }
+ m := r.lastFrame()
+ if !slices.Equal(refIDs(m.Earlier), want[:wire.MaxEarlierFiles]) || m.EarlierMore != 5 {
+ t.Fatalf("earlier %d (+%d)", len(m.Earlier), m.EarlierMore)
+ }
+}
+
+// TestFrameEarlierOnlyAssistantPersonTurns: a team_update turn and a
+// Coordinator turn carry no earlier files.
+func TestFrameEarlierOnlyAssistantPersonTurns(t *testing.T) {
+ r := filesRig(t, wire.ProtocolAssistantFiles)
+ r.past(wire.LaneAssistant, "see this", r.now.Add(-time.Hour), "a.md")
+ r.past(wire.LaneCoordinator, "and this", r.now.Add(-time.Hour), "b.md")
+ update := turnRecord{ID: newID("t_"), Person: hkOwner, State: wire.TurnQueued, Attempt: 1, Kind: wire.TurnTeamUpdate, Note: "The team finished.", Revision: 1, CreatedAt: r.now, UpdatedAt: r.now, Lane: wire.LaneAssistant}
+ r.must(r.s.db.G.Create(&update).Error)
+ r.must(r.tx(func(t *txn) error { return t.dispatch(&update) }))
+ if m := r.lastFrame(); m.Kind != wire.TurnTeamUpdate || m.Earlier != nil || m.EarlierMore != 0 {
+ t.Fatalf("team_update frame %+v", m)
+ }
+ if _, _, err := r.s.Send(r.ctx, hkOwner, wire.SendMessage{Text: "hello", IdempotencyKey: "k1"}); err != nil {
+ t.Fatal(err)
+ }
+ if m := r.lastFrame(); m.Lane != wire.LaneCoordinator || m.Earlier != nil {
+ t.Fatalf("coordinator frame %+v", m)
+ }
+}
+
+// TestFilesOnlyText: one files-only message reaches the model as
+// "(files only, no words)", as it already did among several messages. It
+// is so in every lane: the Coordinator's single files-only message went as
+// empty text before.
+func TestFilesOnlyText(t *testing.T) {
+ r := filesRig(t, wire.ProtocolAssistantFiles)
+ a := r.upload(hkOwner, "a.md", "# a")
+ if _, _, err := r.s.Lane(wire.LaneAssistant).Send(r.ctx, hkOwner, wire.SendMessage{Attachments: []string{a}, IdempotencyKey: "k1"}); err != nil {
+ t.Fatal(err)
+ }
+ if m := r.lastFrame(); !strings.HasPrefix(m.Text, filesOnly) || len(m.PersonText) != 1 || m.PersonText[0] != "" {
+ t.Fatalf("assistant text %q, person %q", m.Text, m.PersonText)
+ }
+ b := r.upload(hkOwner, "b.md", "# b")
+ if _, _, err := r.s.Send(r.ctx, hkOwner, wire.SendMessage{Attachments: []string{b}, IdempotencyKey: "k2"}); err != nil {
+ t.Fatal(err)
+ }
+ if m := r.lastFrame(); m.Lane != wire.LaneCoordinator || !strings.HasPrefix(m.Text, filesOnly+"\n\n") {
+ t.Fatalf("coordinator text %q", m.Text)
+ }
+ if got := turnText([]string{"hi"}, [][]string{{"a.md"}}); got != "hi" {
+ t.Fatalf("words with files %q", got)
+ }
+ if got := turnText([]string{""}, [][]string{nil}); got != "" {
+ t.Fatalf("no words and no files %q", got)
+ }
+}
+
+// TestFrameEarlierGivesWayFirst: a frame too big for the runner drops its
+// earlier files before the tail, oldest first, and counts them in
+// earlier_more.
+func TestFrameEarlierGivesWayFirst(t *testing.T) {
+ r := filesRig(t, wire.ProtocolAssistantFiles)
+ r.past(wire.LaneAssistant, "the file", r.now.Add(-2*time.Hour), "a.md", "b.md")
+ long := strings.Repeat("word ", (wire.MaxMessageBytes-64)/5)
+ for i := range 16 {
+ r.past(wire.LaneAssistant, long, r.now.Add(-time.Hour+time.Duration(i)*time.Minute))
+ }
+ if _, _, err := r.s.Lane(wire.LaneAssistant).Send(r.ctx, hkOwner, wire.SendMessage{Text: "hello", IdempotencyKey: "k1"}); err != nil {
+ t.Fatal(err)
+ }
+ m := r.lastFrame()
+ raw, _ := json.Marshal(m)
+ if len(m.Earlier) != 0 || m.EarlierMore != 2 || len(raw) > frameRoom || len(m.Tail) == 0 {
+ t.Fatalf("earlier %d (+%d), tail %d, %d bytes", len(m.Earlier), m.EarlierMore, len(m.Tail), len(raw))
+ }
+}
+
+// TestFenceAssistantFiles (A6): a primary connecting below 32 fails its
+// person's Assistant turns in flight that carry files (runner_too_old),
+// and acks their message and attachment commands, so the older runner
+// gets neither. Other turns go on. At 32, or from a worker, nothing
+// changes.
+func TestFenceAssistantFiles(t *testing.T) {
+ setup := func(t *testing.T) (*hkRig, wire.Sent, wire.Sent) {
+ r := filesRig(t, wire.ProtocolAssistantFiles)
+ lane := r.s.Lane(wire.LaneAssistant)
+ a, b := r.upload(hkOwner, "a.md", "# a"), r.upload(hkOwner, "b.md", "# b")
+ withFiles, _, err := lane.Send(r.ctx, hkOwner, wire.SendMessage{Text: "read these", Attachments: []string{a, b}, IdempotencyKey: "k1"})
+ r.must(err)
+ words, _, err := lane.Send(r.ctx, hkOwner, wire.SendMessage{Text: "and hello", IdempotencyKey: "k2"})
+ r.must(err)
+ return r, withFiles, words
+ }
+ unacked := func(r *hkRig, kind string) int64 {
+ return r.count("SELECT count(*) FROM runner_commands WHERE kind = ? AND acked_at IS NULL", kind)
+ }
+ connect := func(r *hkRig, protocol int, role string) {
+ r.must(r.tx(func(t *txn) error {
+ return t.fenceLanes(Lease{Runner: RunnerPrincipal{Person: hkOwner, RunnerID: "RUNNER1"}, Protocol: protocol, Role: role})
+ }))
+ }
+ state := func(r *hkRig, id string) turnRecord {
+ var k turnRecord
+ r.must(r.s.db.G.Where("id = ?", id).First(&k).Error)
+ return k
+ }
+
+ r, withFiles, words := setup(t)
+ if unacked(r, wire.FrameAttachment) != 2 || unacked(r, wire.FrameMessage) != 1 {
+ t.Fatalf("before: %d chunks, %d messages", unacked(r, wire.FrameAttachment), unacked(r, wire.FrameMessage))
+ }
+ connect(r, wire.Protocol31, wire.RolePrimary)
+ if k := state(r, withFiles.Turn.ID); k.State != wire.TurnFailed || k.Reason != reasonRunnerTooOld {
+ t.Fatalf("the turn with files %s %s", k.State, k.Reason)
+ }
+ if n := unacked(r, wire.FrameAttachment); n != 0 {
+ t.Fatalf("%d attachment commands still waiting", n)
+ }
+ if k := state(r, words.Turn.ID); !slices.Contains(wire.InFlight, k.State) || !k.Dispatched {
+ t.Fatalf("the turn with words %s dispatched %v", k.State, k.Dispatched)
+ }
+ if m := r.lastFrame(); m.TurnID != words.Turn.ID || unacked(r, wire.FrameMessage) != 1 {
+ t.Fatalf("waiting message %+v", m)
+ }
+
+ for name, tc := range map[string]struct {
+ protocol int
+ role string
+ }{"at 32": {wire.ProtocolAssistantFiles, wire.RolePrimary}, "a worker at 31": {wire.Protocol31, wire.RoleWorker}} {
+ t.Run(name, func(t *testing.T) {
+ r, withFiles, words := setup(t)
+ connect(r, tc.protocol, tc.role)
+ if state(r, withFiles.Turn.ID).State == wire.TurnFailed || state(r, words.Turn.ID).State == wire.TurnFailed || unacked(r, wire.FrameAttachment) != 2 {
+ t.Fatal("a turn was fenced")
+ }
+ })
+ }
+}
diff --git a/internal/equipo/chat/attachments.go b/internal/equipo/chat/attachments.go
index 9560bf95..197eb575 100644
--- a/internal/equipo/chat/attachments.go
+++ b/internal/equipo/chat/attachments.go
@@ -116,6 +116,49 @@ func (s *Store) Upload(ctx context.Context, person, name, declared string, data
return out, err
}
+// ErrAttachmentSent: the upload is on a message already, so it stays
+// (409 attachment_sent).
+var ErrAttachmentSent = errors.New("chat: attachment sent")
+
+// auditAttachmentDelete is a deleted unsent upload, audited by id alone.
+const auditAttachmentDelete = "attachment.delete"
+
+// DeleteUnsent deletes one of the person's own unsent uploads, its row
+// and its bytes, in one transaction with the roster check, and audits
+// it by id: the person removed it before sending, so it no longer counts
+// against maxUnsent. An id that is not the person's, or no longer
+// exists, is ErrNotFound; one on a message already is ErrAttachmentSent.
+// A send racing it either links the file first (then this is
+// ErrAttachmentSent) or finds it gone (ErrInvalid): linkFiles links only
+// a row still unsent.
+func (s *Store) DeleteUnsent(ctx context.Context, person, id string) error {
+ return s.tx(ctx, func(t *txn) error {
+ if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
+ return err
+ }
+ var r fileRecord
+ if err := t.db.Select("id", "message_id").Where("id = ? AND person = ?", id, person).First(&r).Error; errors.Is(err, gorm.ErrRecordNotFound) {
+ return ErrNotFound
+ } else if err != nil {
+ return err
+ }
+ if r.MessageID != "" {
+ return ErrAttachmentSent
+ }
+ res := t.db.Where("id = ? AND person = ? AND message_id = ''", id, person).Delete(&fileRecord{})
+ if res.Error != nil {
+ return res.Error
+ }
+ if res.RowsAffected != 1 {
+ return ErrNotFound
+ }
+ if err := t.db.Where("id = ?", id).Delete(&fileDataRecord{}).Error; err != nil {
+ return err
+ }
+ return s.authority.Audit(t.db, person, auditAttachmentDelete, id)
+ })
+}
+
func (t *txn) dropUnsent(person string, before time.Time) error {
var ids []string
q := t.db.Model(&fileRecord{}).Where("message_id = '' AND created_at < ?", before)
@@ -160,10 +203,12 @@ func sendHash(text string, files []string) string {
}
// linkFiles puts the person's unsent uploads on message m, in order. An id
-// that is not the person's, or already sent, refuses the whole send.
+// that is not the person's, already sent, or past its day unsent (it is
+// dropped with the next upload) refuses the whole send.
func (t *txn) linkFiles(m messageRecord, ids []string) error {
+ kept := t.now().Add(-unsentFor)
for i, id := range ids {
- res := t.db.Model(&fileRecord{}).Where("id = ? AND person = ? AND message_id = ''", id, m.Person).Select("message_id", "position").Updates(&fileRecord{MessageID: m.ID, Position: i + 1})
+ res := t.db.Model(&fileRecord{}).Where("id = ? AND person = ? AND message_id = '' AND created_at >= ?", id, m.Person, kept).Select("message_id", "position").Updates(&fileRecord{MessageID: m.ID, Position: i + 1})
if res.Error != nil {
return res.Error
}
@@ -275,6 +320,40 @@ func (t *txn) relayFiles(person string, messages []string) ([]wire.AttachmentRef
return refs, names, nil
}
+// earlierFiles is what a turn's frame names as Earlier: the files of the
+// person's own messages in lane sent since since, in turns already
+// dispatched (so their bytes went to the runner), apart from exclude's
+// messages; newest message first, each message's files in order, at most
+// limit. more counts the rest. No bytes are sent again: the runner holds
+// them, or no longer does, and says so.
+func (t *txn) earlierFiles(person, lane string, exclude []string, since time.Time, limit int) (refs []wire.AttachmentRef, more int, err error) {
+ if len(exclude) == 0 {
+ exclude = []string{""}
+ }
+ q := t.db.Table("chat_attachments AS a").Joins("JOIN chat_messages AS m ON m.id = a.message_id").
+ Where("a.person = ? AND m.person = ? AND m.role = ? AND coalesce(m.lane, '') = ? AND m.created_at >= ? AND m.id NOT IN ?", person, person, wire.RolePerson, lane, since, exclude).
+ Where("m.turn_id IN (SELECT id FROM chat_turns WHERE person = ? AND dispatched = ?)", person, true)
+ var total int64
+ if err := q.Session(&gorm.Session{}).Count(&total).Error; err != nil {
+ return nil, 0, err
+ }
+ var rows []fileRecord
+ if err := q.Session(&gorm.Session{}).Select("a.*").Order("m.seq DESC, a.position").Limit(limit).Find(&rows).Error; err != nil {
+ return nil, 0, err
+ }
+ refs = make([]wire.AttachmentRef, 0, len(rows))
+ for _, r := range rows {
+ refs = append(refs, wire.AttachmentRef{ID: r.ID, Kind: r.Kind, Name: r.Name, MediaType: r.MediaType, Size: r.Size, SHA256: r.SHA256})
+ }
+ return refs, int(total) - len(refs), nil
+}
+
+// sentFilesLine is a files-only person message as the tail shows it:
+// the names of the files it carried.
+func sentFilesLine(names []string) string {
+ return "(sent files: " + strings.Join(names, ", ") + ")"
+}
+
// hydrate fills an attachment frame's bytes from the stored file.
func hydrate(tx *gorm.DB, body string) (string, error) {
var c wire.AttachmentChunk
diff --git a/internal/equipo/chat/attachments_http.go b/internal/equipo/chat/attachments_http.go
index 16327565..356c75e1 100644
--- a/internal/equipo/chat/attachments_http.go
+++ b/internal/equipo/chat/attachments_http.go
@@ -46,6 +46,16 @@ func (h *HTTP) upload(w http.ResponseWriter, r *http.Request, p personapi.Person
h.fail(w, r, err)
}
+// deleteUpload is DELETE /api/v1/attachments/{id}: the person removes an
+// upload they have not sent. 204 once it is gone.
+func (h *HTTP) deleteUpload(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
+ if err := h.Store.DeleteUnsent(r.Context(), p.Address, chi.URLParam(r, "id")); err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+}
+
// attachment is GET /api/v1/attachments/{id} and its preview.
func (h *HTTP) attachment(preview bool) handler {
return func(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
diff --git a/internal/equipo/chat/handoff.go b/internal/equipo/chat/handoff.go
index 7becee0f..faf31488 100644
--- a/internal/equipo/chat/handoff.go
+++ b/internal/equipo/chat/handoff.go
@@ -164,9 +164,9 @@ func (teamProvider) List(context.Context, string) ([]assist.Operation, error) {
// model; people never read them.
var teamOps = []assist.Operation{
{Name: opTeamRequest, App: "Team", Scope: "team", Idempotent: true,
- Description: "Hand software work (build, fix or change an app or site) to the person's team, who take it from there. words quotes the person's own message in this turn, word for word; context is anything you know that helps, kept apart from their words as your reference. Returns the request id.",
+ Description: "Hand software work (build, fix or change an app or site) to the person's team, who take it from there. words quotes the person's own message in this turn, word for word; context is anything you know that helps, kept apart from their words as your reference. The job can't see the person's attached files: when their message had some, files_left_behind says how many, and you tell the person the team works without them. A message of files with no words has nothing to quote: ask the person, in words, what they want done. Returns the request id.",
Input: json.RawMessage(`{"type":"object","properties":{"words":{"type":"string","description":"The person's own words from their message in this turn, quoted exactly."},"context":{"type":"string","maxLength":4000,"description":"What you know that helps: kept apart from the person's words, as reference."},"title":{"type":"string","maxLength":60,"description":"A short name for this job, in the person's terms, such as \"Fixing the sign-in page\"."}},"required":["words"],"additionalProperties":false}`),
- Output: json.RawMessage(`{"type":"object","properties":{"request":{"type":"string"},"status":{"type":"string"},"title":{"type":"string"}}}`)},
+ Output: json.RawMessage(`{"type":"object","properties":{"request":{"type":"string"},"status":{"type":"string"},"title":{"type":"string"},"files_left_behind":{"type":"integer"}}}`)},
{Name: opTeamStatus, App: "Team", Scope: "team", ReadOnly: true, Idempotent: true,
Description: "Read-only: where the work handed to the team stands, in plain words, with each job's open question: one request (request), the person's open requests (none given), or those and the work they started with the team themselves (all). Open requests come ten at a time, newest first; when more are open, next is set: pass it as after to read the ten after them.",
Input: json.RawMessage(`{"type":"object","properties":{"request":{"type":"string"},"all":{"type":"boolean"},"after":{"type":"string","description":"The next of the page before, to read on."}},"additionalProperties":false}`),
@@ -230,21 +230,34 @@ func (s *Store) teamRequest(ctx context.Context, call toolCallRecord, input json
err := s.tx(ctx, func(t *txn) error {
var h handoffRecord
if err := t.db.Where("ledger_key = ? AND person = ?", key, call.Person).Limit(1).Find(&h).Error; err != nil || h.ID != "" {
- out = requestResult(h)
+ if err == nil {
+ out, err = t.requestResult(h)
+ }
return err
}
r, err := t.liveCall(call)
if err != nil {
return err
}
+ left, err := t.turnFiles(r)
+ if err != nil {
+ return err
+ }
words, err := t.quote(r, in.Words)
if err != nil {
+ if wordless, e := t.filesOnlyTurn(r); e != nil {
+ return e
+ } else if wordless {
+ return errFilesNoWords
+ }
return err
}
// The same words handed over again in this turn, in other
// arguments, are the same request.
if err := t.db.Where("assistant_turn = ? AND person = ? AND EXISTS (SELECT 1 FROM chat_messages m WHERE m.id = chat_handoffs.message_id AND m.text = ?)", r.ID, r.Person, words).Limit(1).Find(&h).Error; err != nil || h.ID != "" {
- out = requestResult(h)
+ if err == nil {
+ out, err = t.requestResult(h)
+ }
return err
}
switch err := t.jobRunner(r.Person); {
@@ -254,7 +267,13 @@ func (s *Store) teamRequest(ctx context.Context, call toolCallRecord, input json
return err
}
now := t.now()
- h = handoffRecord{ID: newID("h_"), Person: r.Person, AssistantTurn: r.ID, Context: referenceText(in.Context), LedgerKey: key, State: handoffOpen, Title: strings.TrimSpace(in.Title), CreatedAt: now, UpdatedAt: now}
+ // The job can't see the person's files (R6): its context says so,
+ // as the instance's own reference.
+ reference := strings.TrimSpace(in.Context)
+ if left > 0 {
+ reference = strings.TrimSpace(reference + " " + filesLeftBehind(left))
+ }
+ h = handoffRecord{ID: newID("h_"), Person: r.Person, AssistantTurn: r.ID, Context: referenceText(reference), LedgerKey: key, State: handoffOpen, Title: strings.TrimSpace(in.Title), CreatedAt: now, UpdatedAt: now}
if h.Title == "" {
h.Title = fallbackTitle(words)
}
@@ -271,7 +290,9 @@ func (s *Store) teamRequest(ctx context.Context, call toolCallRecord, input json
}); err != nil {
return err
}
- out = requestResult(h)
+ if out, err = t.requestResult(h); err != nil {
+ return err
+ }
if err := t.s.authority.Audit(t.db, r.Person, auditHandoff, h.ID); err != nil {
return err
}
@@ -280,9 +301,52 @@ func (s *Store) teamRequest(ctx context.Context, call toolCallRecord, input json
return out, err
}
-func requestResult(h handoffRecord) json.RawMessage {
- raw, _ := json.Marshal(map[string]string{"request": h.ID, "status": "sent", "title": h.Title})
- return raw
+// requestResult is team_request's answer for h: with files_left_behind
+// when the Assistant turn it came from carried files the job can't see.
+func (t *txn) requestResult(h handoffRecord) (json.RawMessage, error) {
+ out := map[string]any{"request": h.ID, "status": "sent", "title": h.Title}
+ left, err := t.turnFiles(turnRecord{ID: h.AssistantTurn, Person: h.Person})
+ if err != nil {
+ return nil, err
+ }
+ if left > 0 {
+ out["files_left_behind"] = left
+ }
+ raw, _ := json.Marshal(out)
+ return raw, nil
+}
+
+// filesLeftBehind is the instance's line in a job's reference when the
+// person's request carried n files: told to the Coordinator, never the
+// person's words.
+func filesLeftBehind(n int64) string {
+ files := strconv.FormatInt(n, 10) + " files"
+ if n == 1 {
+ files = "1 file"
+ }
+ return "The person attached " + files + " to this request in their conversation. This job cannot see them."
+}
+
+// errFilesNoWords: the turn's messages are files with no words, so there
+// is nothing of the person's to hand over.
+var errFilesNoWords = assist.Failure{Code: "invalid_input", Message: "The person's message has files and no words, so there is nothing of theirs to hand over. Ask them, in words, what they want done."}
+
+// turnFiles counts the files on the person's messages in turn r.
+func (t *txn) turnFiles(r turnRecord) (int64, error) {
+ var n int64
+ err := t.db.Model(&fileRecord{}).Where("person = ? AND message_id IN (SELECT id FROM chat_messages WHERE turn_id = ? AND person = ? AND role = ?)", r.Person, r.ID, r.Person, wire.RolePerson).Count(&n).Error
+ return n, err
+}
+
+// filesOnlyTurn says the person's messages in turn r have files and no
+// words at all.
+func (t *txn) filesOnlyTurn(r turnRecord) (bool, error) {
+ var worded int64
+ if err := t.db.Model(&messageRecord{}).Where("turn_id = ? AND person = ? AND role = ? AND text <> ''", r.ID, r.Person, wire.RolePerson).Count(&worded).Error; err != nil || worded > 0 {
+ return false, err
+ }
+ n, err := t.turnFiles(r)
+ return n > 0, err
}
// validTitle says a title the model gave is one line of at most maxTitle
diff --git a/internal/equipo/chat/handoff_test.go b/internal/equipo/chat/handoff_test.go
index 65b0f273..1b68487c 100644
--- a/internal/equipo/chat/handoff_test.go
+++ b/internal/equipo/chat/handoff_test.go
@@ -3,6 +3,7 @@ package chat
import (
"context"
"encoding/json"
+ "errors"
"io"
"log/slog"
"os"
@@ -12,6 +13,7 @@ import (
"time"
"unicode/utf8"
+ "amadan.net/oficina/equipo/internal/equipo/assist"
"amadan.net/oficina/equipo/internal/wire"
"amadan.net/rastrillo/rastrillo/db"
"gorm.io/gorm"
@@ -141,3 +143,69 @@ func TestGoingLiveCause(t *testing.T) {
}
}
}
+
+// TestTeamRequestLeavesFilesBehind (A5): a hand-off from an Assistant turn
+// whose message carries files goes ahead without them. The result says
+// how many stayed behind, the job thread's message has none, and the
+// job's context ends with the instance's line about them, also on a
+// repeated call. Without files there is no field and no line; a message
+// of files alone has no words to hand over, so nothing is made.
+func TestTeamRequestLeavesFilesBehind(t *testing.T) {
+ request := func(t *testing.T, text string, files ...string) (*hkRig, json.RawMessage, error) {
+ r := filesRig(t, wire.ProtocolAssistantFiles)
+ turn := turnRecord{ID: "t_1", Person: hkOwner, State: wire.TurnRunning, Kind: wire.TurnPerson, Attempt: 1, Dispatched: true, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now, Lane: wire.LaneAssistant}
+ r.must(r.s.db.G.Create(&turn).Error)
+ r.must(r.s.db.G.Create(&messageRecord{ID: "m_1", Person: hkOwner, IdempotencyKey: "a-1", Role: wire.RolePerson, Text: text, TurnID: "t_1", Revision: 1, CreatedAt: r.now, Lane: wire.LaneAssistant, Origin: originComposer}).Error)
+ for i, name := range files {
+ id := r.upload(hkOwner, name, "# "+name)
+ r.must(r.s.db.G.Model(&fileRecord{}).Where("id = ?", id).Updates(map[string]any{"message_id": "m_1", "position": i + 1}).Error)
+ }
+ call := toolCallRecord{CallID: "t_1/1/u1", Person: hkOwner, TurnID: "t_1", Attempt: 1, Name: wire.ToolUse, Lane: wire.LaneAssistant, Operation: opTeamRequest}
+ out, err := r.s.TeamProvider().Invoke(withCall(r.ctx, call), hkOwner, opTeamRequest, json.RawMessage(`{"words":"Fix the login page","context":"Tito's web app."}`), "5f0c2d3e-0000-5000-8000-000000000001")
+ return r, out, err
+ }
+ result := func(t *testing.T, raw json.RawMessage) map[string]any {
+ var m map[string]any
+ if err := json.Unmarshal(raw, &m); err != nil {
+ t.Fatal(err)
+ }
+ return m
+ }
+
+ r, out, err := request(t, "Please fix the login page", "shot.md", "notes.md")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := result(t, out); got["files_left_behind"] != float64(2) {
+ t.Fatalf("result %s", out)
+ }
+ var h handoffRecord
+ r.must(r.s.db.G.First(&h).Error)
+ if want := "Tito's web app. " + filesLeftBehind(2); h.Context != want {
+ t.Fatalf("context %q, want %q", h.Context, want)
+ }
+ if n := r.count("SELECT count(*) FROM chat_attachments WHERE message_id = ?", h.MessageID); n != 0 {
+ t.Fatalf("the job's message has %d files", n)
+ }
+ call := toolCallRecord{CallID: "t_1/1/u1", Person: hkOwner, TurnID: "t_1", Attempt: 1, Name: wire.ToolUse, Lane: wire.LaneAssistant, Operation: opTeamRequest}
+ again, err := r.s.TeamProvider().Invoke(withCall(r.ctx, call), hkOwner, opTeamRequest, json.RawMessage(`{"words":"Fix the login page"}`), "5f0c2d3e-0000-5000-8000-000000000001")
+ if err != nil || string(again) != string(out) {
+ t.Fatalf("again %s %v", again, err)
+ }
+
+ _, out, err = request(t, "Please fix the login page")
+ if err != nil || strings.Contains(string(out), "files_left_behind") {
+ t.Fatalf("without files %s %v", out, err)
+ }
+ r, _, err = request(t, "", "shot.md")
+ var f assist.Failure
+ if !errors.As(err, &f) || f.Code != "invalid_input" || r.count("SELECT count(*) FROM chat_handoffs") != 0 {
+ t.Fatalf("files alone: %v", err)
+ }
+ if filesLeftBehind(1) != "The person attached 1 file to this request in their conversation. This job cannot see them." {
+ t.Fatalf("one file: %q", filesLeftBehind(1))
+ }
+ if !strings.Contains(teamOps[0].Description, "files_left_behind") || !strings.Contains(string(teamOps[0].Output), "files_left_behind") {
+ t.Fatal("the operation does not say the job can't see the files")
+ }
+}
diff --git a/internal/equipo/chat/http.go b/internal/equipo/chat/http.go
index 17ff1ac3..d8493a7d 100644
--- a/internal/equipo/chat/http.go
+++ b/internal/equipo/chat/http.go
@@ -76,6 +76,7 @@ func (h *HTTP) Mount(r chi.Router) {
r.Get("/messages", h.bearer(h.messages))
r.Post("/messages", h.bearer(h.send))
r.Post("/attachments", h.bearer(h.upload))
+ r.Delete("/attachments/{id}", h.bearer(h.deleteUpload))
r.Get("/attachments/{id}", h.bearer(h.attachment(false)))
r.Get("/attachments/{id}/preview", h.bearer(h.attachment(true)))
r.Get("/turns/{id}", h.bearer(h.turn))
@@ -426,6 +427,10 @@ func (h *HTTP) fail(w http.ResponseWriter, r *http.Request, err error) {
personapi.WriteError(w, r, 409, "runner_too_old", nil)
case errors.Is(err, ErrNoRunner):
personapi.WriteError(w, r, 409, "no_runner", nil)
+ case errors.Is(err, ErrAttachmentsUnavailable):
+ personapi.WriteError(w, r, 409, "attachments_unavailable", nil)
+ case errors.Is(err, ErrAttachmentSent):
+ personapi.WriteError(w, r, 409, "attachment_sent", nil)
case errors.Is(err, ErrModelsNotAllowed):
personapi.WriteError(w, r, 422, "models_not_allowed", nil)
case errors.Is(err, ErrActionConflict):
diff --git a/internal/equipo/chat/lane.go b/internal/equipo/chat/lane.go
index 056b6fc2..d5f8fd3e 100644
--- a/internal/equipo/chat/lane.go
+++ b/internal/equipo/chat/lane.go
@@ -45,12 +45,19 @@ func (s *Store) Lane(lane string) *LaneStore { return &LaneStore{s: s, lane: lan
// Send records a person message in the lane. Only a person whose primary
// runner can carry the lane's turns may send (ErrNoRunner,
-// ErrRunnerTooOld); a message already sent answers as it did. The lane
-// takes words only.
+// ErrRunnerTooOld); a message already sent answers as it did. The
+// Assistant's lane takes files too, as the Coordinator's does, but only
+// with a primary last seen at ProtocolAssistantFiles
+// (ErrAttachmentsUnavailable): never on a guess that fenceLanes would
+// fail later. Every other lane takes words only.
func (l *LaneStore) Send(ctx context.Context, person string, in wire.SendMessage) (out wire.Sent, created bool, err error) {
- if in.Text = strings.TrimSpace(in.Text); in.Text == "" || len(in.Text) > wire.MaxMessageBytes || !utf8.ValidString(in.Text) || strings.ContainsRune(in.Text, 0) || len(in.Attachments) > 0 || in.ProjectID != "" || !validKey(in.IdempotencyKey) {
+ files := len(in.Attachments) > 0
+ if in.Text = strings.TrimSpace(in.Text); in.Text == "" && !files || len(in.Text) > wire.MaxMessageBytes || !utf8.ValidString(in.Text) || strings.ContainsRune(in.Text, 0) || files && l.lane != wire.LaneAssistant || in.ProjectID != "" || !validKey(in.IdempotencyKey) {
return out, false, ErrInvalid
}
+ if err := checkFiles(in.Attachments); err != nil {
+ return out, false, err
+ }
key := in.IdempotencyKey
err = l.s.tx(ctx, func(t *txn) error {
if err := l.s.authority.CurrentPerson(ctx, t.db); err != nil {
@@ -61,12 +68,16 @@ func (l *LaneStore) Send(ctx context.Context, person string, in wire.SendMessage
return err
}
if sent == 0 {
- if err := t.laneRunner(person); err != nil {
+ check := t.laneRunner
+ if files {
+ check = t.filesRunner
+ }
+ if err := check(person); err != nil {
return err
}
}
var err error
- if out, created, err = t.sendOrigin(l.lane, person, key, in.Text, nil, originComposer, nil); err != nil || !created {
+ if out, created, err = t.sendOrigin(l.lane, person, key, in.Text, in.Attachments, originComposer, nil); err != nil || !created {
return err
}
return t.s.authority.Audit(t.db, person, auditAssistantSend, out.Message.ID)
@@ -93,62 +104,117 @@ func (t *txn) laneRunner(person string) error { return t.runnerAt(person, wire.P
func (t *txn) jobRunner(person string) error { return t.runnerAt(person, wire.ProtocolJobs) }
// runnerAt refuses a person with no primary, or one that last spoke a
-// protocol before least.
+// protocol before least. A primary never seen yet may.
func (t *txn) runnerAt(person string, least int) error {
- primary, err := t.s.authority.PrimaryRunner(t.db, person)
+ protocol, seen, err := t.primaryProtocol(person)
+ if err != nil || !seen {
+ return err
+ }
+ if protocol < least {
+ return ErrRunnerTooOld
+ }
+ return nil
+}
+
+// ErrAttachmentsUnavailable: the person's primary runner cannot read the
+// Assistant's files (409 attachments_unavailable). Words still go.
+var ErrAttachmentsUnavailable = errors.New("chat: attachments unavailable")
+
+// filesRunner refuses an Assistant send with files unless the person's
+// primary was last seen at ProtocolAssistantFiles or later: none is
+// ErrNoRunner; one older, or never seen, is ErrAttachmentsUnavailable.
+// Stricter than runnerAt on purpose: a send with files is never taken on
+// a guess and then failed by fenceLanes. The snapshot's can_attach is
+// this check.
+func (t *txn) filesRunner(person string) error {
+ protocol, seen, err := t.primaryProtocol(person)
if err != nil {
return err
}
+ if !seen || protocol < wire.ProtocolAssistantFiles {
+ return ErrAttachmentsUnavailable
+ }
+ return nil
+}
+
+// primaryProtocol is the protocol the person's primary last spoke, and
+// whether it was ever seen. No primary is ErrNoRunner.
+func (t *txn) primaryProtocol(person string) (int, bool, error) {
+ primary, err := t.s.authority.PrimaryRunner(t.db, person)
+ if err != nil {
+ return 0, false, err
+ }
if primary == "" {
- return ErrNoRunner
+ return 0, false, ErrNoRunner
}
var r runnerSessionRecord
err = t.db.Select("protocol").Where("runner_id = ?", primary).First(&r).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
- return nil
+ return 0, false, nil
}
if err != nil {
- return err
- }
- if r.Protocol < least {
- return ErrRunnerTooOld
+ return 0, false, err
}
- return nil
+ return r.Protocol, true, nil
}
// fenceLanes fails the person's turns in flight that their primary
// cannot carry when it connects older: every lane but their own below
-// the Assistant's protocol, the job threads below protocol 22. The
-// runner would drop every frame of them. Their message commands leave
-// the mailbox, so none is ever sent.
+// the Assistant's protocol, the job threads below protocol 22, and the
+// Assistant's turns with files below protocol 32 (wire.Encode would
+// refuse them). The runner would drop every frame of them. Their message
+// commands, and their files' attachment commands, leave the mailbox, so
+// none is ever sent; the lane's next turn then goes.
func (t *txn) fenceLanes(l Lease) error {
- if l.Protocol >= wire.ProtocolJobs || l.Role != wire.RolePrimary {
+ if l.Protocol >= wire.ProtocolAssistantFiles || l.Role != wire.RolePrimary {
return nil
}
if primary, err := t.s.authority.PrimaryRunner(t.db, l.Runner.Person); err != nil || primary != l.Runner.RunnerID {
return err
}
- lanes := "lane LIKE 'job:%'"
- if l.Protocol < wire.ProtocolAssistant {
+ lanes := assistantWithFiles
+ switch {
+ case l.Protocol < wire.ProtocolAssistant:
lanes = "coalesce(lane, '') <> ''"
+ case l.Protocol < wire.ProtocolJobs:
+ lanes = "lane LIKE 'job:%' OR " + assistantWithFiles
}
var rows []turnRecord
- if err := t.db.Where("person = ? AND "+lanes+" AND state IN ?", l.Runner.Person, wire.InFlight).Order("created_at, id").Find(&rows).Error; err != nil {
+ if err := t.db.Where("person = ? AND ("+lanes+") AND state IN ?", l.Runner.Person, wire.InFlight).Order("created_at, id").Find(&rows).Error; err != nil {
return err
}
+ next := map[string]bool{}
for i := range rows {
r := &rows[i]
if err := t.db.Model(&commandRecord{}).Where("person = ? AND kind = ? AND acked_at IS NULL AND body LIKE ?", r.Person, wire.FrameMessage, `%"turn_id":"`+r.ID+`"%`).Update("acked_at", t.now()).Error; err != nil {
return err
}
+ var files []string
+ if err := t.db.Model(&fileRecord{}).Where("person = ? AND message_id IN (SELECT id FROM chat_messages WHERE turn_id = ?)", r.Person, r.ID).Pluck("id", &files).Error; err != nil {
+ return err
+ }
+ for _, id := range files {
+ // Ids are at_ and [a-z0-9]: nothing in them is a LIKE pattern.
+ if err := t.db.Model(&commandRecord{}).Where("person = ? AND kind = ? AND acked_at IS NULL AND body LIKE ?", r.Person, wire.FrameAttachment, `%"id":"`+id+`"%`).Update("acked_at", t.now()).Error; err != nil {
+ return err
+ }
+ }
r.State, r.Reason = wire.TurnFailed, reasonRunnerTooOld
if err := t.saveTurn(r); err != nil {
return err
}
+ next[r.Lane] = true
+ }
+ if next[wire.LaneAssistant] {
+ return t.dispatchNext(l.Runner.Person, wire.LaneAssistant)
}
return nil
}
+// assistantWithFiles selects the Assistant's turns whose messages carry
+// files.
+const assistantWithFiles = "lane = '" + wire.LaneAssistant + "' AND EXISTS (SELECT 1 FROM chat_messages m JOIN chat_attachments a ON a.message_id = m.id WHERE m.turn_id = chat_turns.id)"
+
// reasonRunnerTooOld ends a lane turn its runner cannot carry.
const reasonRunnerTooOld = "runner_too_old"
@@ -192,6 +258,14 @@ func (l *LaneStore) Snapshot(ctx context.Context, person string) (out wire.Assis
case !errors.Is(e, ErrNoRunner) && !errors.Is(e, ErrRunnerTooOld):
return e
}
+ if l.lane == wire.LaneAssistant {
+ switch e = t.filesRunner(person); {
+ case e == nil:
+ out.CanAttach = true
+ case !errors.Is(e, ErrNoRunner) && !errors.Is(e, ErrAttachmentsUnavailable):
+ return e
+ }
+ }
rows, e := t.laneCards(person, l.lane)
if e == nil && l.lane == wire.LaneAssistant {
rows, e = t.withActiveJobs(person, rows)
diff --git a/internal/equipo/chat/store.go b/internal/equipo/chat/store.go
index 7baa640e..4f5a8699 100644
--- a/internal/equipo/chat/store.go
+++ b/internal/equipo/chat/store.go
@@ -374,10 +374,29 @@ func (t *txn) dispatch(r *turnRecord) error {
for _, m := range carried {
inFrame[m.ID] = true
}
+ // A files-only person message has no words: the tail names its files.
+ var wordless []string
+ for _, m := range prior {
+ if m.Role == wire.RolePerson && m.Text == "" {
+ wordless = append(wordless, m.ID)
+ }
+ }
+ sentFiles, err := filesOf(t.db, wordless)
+ if err != nil {
+ return err
+ }
tail := make([]wire.TailMessage, 0, len(prior))
for i := len(prior) - 1; i >= 0; i-- {
if !inFrame[prior[i].ID] {
- tail = append(tail, wire.TailMessage{Role: prior[i].Role, Text: prior[i].Text})
+ text := prior[i].Text
+ if files := sentFiles[prior[i].ID]; len(files) > 0 {
+ names := make([]string, 0, len(files))
+ for _, f := range files {
+ names = append(names, f.Name)
+ }
+ text = sentFilesLine(names)
+ }
+ tail = append(tail, wire.TailMessage{Role: prior[i].Role, Text: text})
}
}
texts := make([]string, 0, len(mine))
@@ -425,6 +444,13 @@ func (t *txn) dispatch(r *turnRecord) error {
}
}
cmd := wire.MessageCommand{Person: r.Person, TurnID: r.ID, Attempt: r.Attempt, Kind: r.Kind, Attachments: files, Lane: r.Lane}
+ if r.Lane == wire.LaneAssistant && r.Kind == wire.TurnPerson {
+ // The files the person attached earlier in the conversation, that
+ // the runner may still hold (assistant attachments spec A4).
+ if cmd.Earlier, cmd.EarlierMore, err = t.earlierFiles(r.Person, r.Lane, ids, now.Add(-wire.RunnerKeepFiles), wire.MaxEarlierFiles); err != nil {
+ return err
+ }
+ }
if wire.CoordinatorRole(r.Lane) {
block, err := t.projectBlock(r.Person)
if err != nil {
@@ -435,8 +461,24 @@ func (t *txn) dispatch(r *turnRecord) error {
return err
}
}
- // The tail gives way first, then the oldest unanswered message: a
+ // The earlier files give way first, oldest first (counted in
+ // earlier_more), then the tail, then the oldest unanswered message: a
// runner refuses a frame too big, every time it is resent.
+ for {
+ full := cmd
+ full.Tail = tail
+ if full.Text, err = t.withUnanswered(carried, text); err != nil {
+ return err
+ }
+ raw, err := json.Marshal(full)
+ if err != nil {
+ return err
+ }
+ if len(raw) <= frameRoom || len(cmd.Earlier) == 0 {
+ break
+ }
+ cmd.Earlier, cmd.EarlierMore = cmd.Earlier[:len(cmd.Earlier)-1], cmd.EarlierMore+1
+ }
for {
words := make([]string, 0, len(carried)+len(own))
for _, m := range carried {
@@ -604,14 +646,21 @@ func (t *txn) batchFull(turn, text string, files int) (bool, error) {
return size > batchRoom, nil
}
+// filesOnly stands for the words of a message that has files and none.
+const filesOnly = "(files only, no words)"
+
// turnText is what the coordinator reads for a turn's messages. One
-// message is its words alone (none, for a move-in or explore turn).
+// message is its words alone (none, for a move-in or explore turn), or
+// filesOnly when it has files and no words, in every lane.
// Several (sent while another turn ran) are each set apart, oldest
// first, with the names of the files each one carried, so the
// coordinator can tell them apart and answer them together. Every runner
// reads Text as the person's words, so the frame is the same at every
// protocol.
func turnText(texts []string, files [][]string) string {
+ if len(texts) == 1 && texts[0] == "" && len(files[0]) > 0 {
+ return filesOnly
+ }
if len(texts) < 2 {
return strings.Join(texts, "")
}
@@ -625,7 +674,7 @@ func turnText(texts []string, files [][]string) string {
}
b.WriteString(":\n")
if text == "" {
- text = "(files only, no words)"
+ text = filesOnly
}
b.WriteString(text)
}
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index b9dbb521..74d309a6 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -2793,11 +2793,18 @@ var runnerDraftCopy = map[string]string{
"api.runner_too_old": "Your runner needs an update for this. Update it and try again.", // COPY APPROVED (Paul, 2026-11-13, copy-review jbltdd2mvwblrz4en6xfhv6d2y, unchanged)
// PUT /api/v1/assistant/host with an origin the operator has not allowed.
"api.host_not_allowed": "Equipo is not set up to connect to this address.", // COPY APPROVED (Paul, 2026-11-13, copy-review jbltdd2mvwblrz4en6xfhv6d2y, unchanged)
+ // The Assistant's files (assistant attachments spec 2026-11-26): a send
+ // with files while the person's runner can't read them yet, and removing
+ // an upload that is already on a message.
+ "api.attachments_unavailable": "Files can't be read right now. Send your message without them, or try again later.", // COPY REVIEW PENDING
+ "api.attachment_sent": "This file has already been sent.", // COPY REVIEW PENDING
// The line while the Assistant looks at what it can do, reads how an
// operation works, or runs one.
"chat.activity.look": "Looking at what I can do…", // COPY APPROVED (Paul, 2026-11-13, copy-review jbltdd2mvwblrz4en6xfhv6d2y, unchanged)
"chat.activity.describe": "Checking what it needs…", // COPY APPROVED (Paul, 2026-11-13, copy-review jbltdd2mvwblrz4en6xfhv6d2y, unchanged)
"chat.activity.use": "Working on it…", // COPY APPROVED (Paul, 2026-11-13, copy-review jbltdd2mvwblrz4en6xfhv6d2y, unchanged)
+ // The line while the Assistant reads a file the person attached.
+ "chat.activity.read_attachment": "Reading your file…", // COPY REVIEW PENDING
// What the Assistant is told of work handed to the team (team_status
// and team_update turns): one line per stage, the line when the work
// stopped and needs someone, the preview and the published address
diff --git a/internal/runner/thin/files.go b/internal/runner/thin/files.go
index d92374a3..4aaa6052 100644
--- a/internal/runner/thin/files.go
+++ b/internal/runner/thin/files.go
@@ -39,7 +39,7 @@ CREATE TABLE IF NOT EXISTS file_refused (attachment_id TEXT PRIMARY KEY, at TEXT
// attachmentsDir is the desk's attachments directory.
attachmentsDir = "attachments"
// keepFiles is how long a delivered attachment stays on the runner.
- keepFiles = 14 * 24 * time.Hour
+ keepFiles = wire.RunnerKeepFiles
// keepParts is how long an unfinished one waits for its chunks.
keepParts = 2 * 24 * time.Hour
// admitIncoming and admitDelivered are an admitted file's states: its
diff --git a/internal/thintest/assistant.go b/internal/thintest/assistant.go
index 300f5d7f..45d5fcd4 100644
--- a/internal/thintest/assistant.go
+++ b/internal/thintest/assistant.go
@@ -27,6 +27,12 @@ func (a *AssistantClient) Send(ctx context.Context, text, key string) (out wire.
return out, a.c.do(ctx, "POST", assistantPath+"/messages", wire.SendMessage{Text: text, IdempotencyKey: key}, &out)
}
+// SendWith is POST /api/v1/assistant/messages with attachments (ids
+// from Upload).
+func (a *AssistantClient) SendWith(ctx context.Context, text, key string, files []string) (out wire.Sent, err error) {
+ return out, a.c.do(ctx, "POST", assistantPath+"/messages", wire.SendMessage{Text: text, IdempotencyKey: key, Attachments: files}, &out)
+}
+
// Messages is GET /api/v1/assistant/messages.
func (a *AssistantClient) Messages(ctx context.Context, before string, limit int) (out wire.MessagePage, err error) {
path := assistantPath + "/messages?limit=" + strconv.Itoa(limit)
diff --git a/internal/thintest/assistant_contract_test.go b/internal/thintest/assistant_contract_test.go
index 25770f83..25bd1a9d 100644
--- a/internal/thintest/assistant_contract_test.go
+++ b/internal/thintest/assistant_contract_test.go
@@ -122,7 +122,9 @@ func TestContractAssistantConversation(t *testing.T) {
if _, err = a.Send(r.ctx, "something else", "a-1"); Status(err) != http.StatusConflict {
t.Fatalf("conflict %v", err)
}
- if status, _, body = raw(t, "POST", r.inst.URL+"/api/v1/assistant/messages", r.client.Token, nil, `{"text":"with a file","idempotency_key":"a-2","attachments":["at_x"]}`); status != 422 || !bytes.Contains(body, []byte(`"invalid_input"`)) {
+ // Files need a runner on protocol 32 (assistant attachments spec A1);
+ // this one speaks 19, so nothing is stored.
+ if status, _, body = raw(t, "POST", r.inst.URL+"/api/v1/assistant/messages", r.client.Token, nil, `{"text":"with a file","idempotency_key":"a-2","attachments":["at_x"]}`); status != http.StatusConflict || !bytes.Contains(body, []byte(`"attachments_unavailable"`)) {
t.Fatalf("attachments %d %s", status, body)
}
diff --git a/internal/thintest/assistant_files_contract_test.go b/internal/thintest/assistant_files_contract_test.go
new file mode 100644
index 00000000..d863b279
--- /dev/null
+++ b/internal/thintest/assistant_files_contract_test.go
@@ -0,0 +1,142 @@
+package thintest
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "slices"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// errorBody is a refusal's status and body (code, copy key, request id).
+func errorBody(t *testing.T, err error) (int, wire.Error) {
+ t.Helper()
+ s, ok := err.(*ErrStatus)
+ if !ok {
+ t.Fatalf("not a refusal: %v", err)
+ }
+ var e wire.Error
+ if json.Unmarshal(s.Body, &e) != nil {
+ t.Fatalf("body %s", s.Body)
+ }
+ return s.Status, e
+}
+
+// nextMessage reads the runner's frames up to the next message command
+// (warm, acks and attachment chunks go before it).
+func nextMessage(t *testing.T, r *rig, f *FakeRunner) *wire.MessageCommand {
+ t.Helper()
+ for {
+ frame, body, err := f.Next(r.ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if frame.Type == wire.FrameMessage {
+ return body.(*wire.MessageCommand)
+ }
+ }
+}
+
+// TestContractAssistantFiles (assistant attachments spec A1): over the
+// person API, as Base calls it. With a primary at 31 the snapshot says
+// can_attach false and a send with files is 409 attachments_unavailable
+// with the usual body, while words still go; with one at 32 it says true,
+// and the files ride to the runner in the Assistant's lane.
+func TestContractAssistantFiles(t *testing.T) {
+ r := newRig(t)
+ a := r.client.Assistant()
+ old := r.dialAt(wire.Protocol31)
+ up, err := r.client.Upload(r.ctx, "notes.md", "text/markdown", []byte("# Notes\nThe word is heron.\n"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if snap, err := a.Snapshot(r.ctx); err != nil || !snap.Available || snap.CanAttach {
+ t.Fatalf("snapshot at 31 %+v %v", snap, err)
+ }
+ _, err = a.SendWith(r.ctx, "What does it say?", "a-1", []string{up.ID})
+ if status, e := errorBody(t, err); status != http.StatusConflict || e.Code != "attachments_unavailable" || e.CopyKey != "api.attachments_unavailable" || e.RequestID == "" {
+ t.Fatalf("send with files at 31: %d %+v", status, e)
+ }
+ if _, err := a.Send(r.ctx, "Words alone", "a-2"); err != nil {
+ t.Fatalf("words at 31: %v", err)
+ }
+ nextMessage(t, r, old)
+
+ r = newRig(t)
+ a = r.client.Assistant()
+ if up, err = r.client.Upload(r.ctx, "notes.md", "text/markdown", []byte("# Notes\nThe word is heron.\n")); err != nil {
+ t.Fatal(err)
+ }
+ current := r.dialAt(wire.ProtocolAssistantFiles)
+ if snap, err := a.Snapshot(r.ctx); err != nil || !snap.CanAttach {
+ t.Fatalf("snapshot at 32 %+v %v", snap, err)
+ }
+ sent, err := a.SendWith(r.ctx, "What does it say?", "a-3", []string{up.ID})
+ if err != nil || len(sent.Message.Attachments) != 1 || sent.Message.Attachments[0].ID != up.ID {
+ t.Fatalf("send at 32 %+v %v", sent, err)
+ }
+ m := nextMessage(t, r, current)
+ if m.Lane != wire.LaneAssistant || m.TurnID != sent.Turn.ID || len(m.Attachments) != 1 || m.Attachments[0].ID != up.ID {
+ t.Fatalf("message frame %+v", m)
+ }
+}
+
+// TestContractAttachmentDelete (spec A2): the person deletes their own
+// unsent upload with their bearer. Gone is 404 (another person's too), a
+// sent one is 409 attachment_sent, and a browser session is refused.
+func TestContractAttachmentDelete(t *testing.T) {
+ r := newRig(t)
+ r.dialAt(wire.ProtocolAssistantFiles)
+ up := func(name string) string {
+ t.Helper()
+ a, err := r.client.Upload(r.ctx, name, "text/markdown", []byte("# "+name))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return a.ID
+ }
+ gone, sent := up("gone.md"), up("sent.md")
+ for _, auth := range []struct {
+ token string
+ cookie bool
+ }{{"", false}, {"", true}} {
+ var cookie *http.Cookie
+ if auth.cookie {
+ cookie = r.inst.Cookie()
+ }
+ if status, _, body := raw(t, http.MethodDelete, r.inst.URL+"/api/v1/attachments/"+gone, auth.token, cookie, ""); status != http.StatusUnauthorized {
+ t.Fatalf("delete without a bearer (cookie %v): %d %s", auth.cookie, status, body)
+ }
+ }
+ if err := r.client.DeleteAttachment(r.ctx, gone); err != nil {
+ t.Fatalf("delete: %v", err)
+ }
+ if _, _, err := r.client.Attachment(r.ctx, gone, false); err == nil {
+ t.Fatal("a deleted upload still reads")
+ }
+ if status, e := errorBody(t, r.client.DeleteAttachment(r.ctx, gone)); status != http.StatusNotFound || e.Code != "not_found" {
+ t.Fatalf("second delete %d %+v", status, e)
+ }
+ if _, err := r.client.Assistant().SendWith(r.ctx, "", "a-1", []string{sent}); err != nil {
+ t.Fatal(err)
+ }
+ if status, e := errorBody(t, r.client.DeleteAttachment(r.ctx, sent)); status != http.StatusConflict || e.Code != "attachment_sent" || e.CopyKey != "api.attachment_sent" {
+ t.Fatalf("delete a sent upload %d %+v", status, e)
+ }
+ // Another person's id is not theirs to know of.
+ const address = "member@example.com"
+ if err := r.inst.Store.SetMember(context.Background(), equipo.Actor{Address: Owner}, address, equipo.RoleMember, true, 0); err != nil {
+ t.Fatal(err)
+ }
+ member := NewClient(r.inst.URL, r.inst.DeviceTokenFor(t, address))
+ if status, e := errorBody(t, member.DeleteAttachment(r.ctx, up("mine.md"))); status != http.StatusNotFound {
+ t.Fatalf("another person's upload %d %+v", status, e)
+ }
+ page, err := r.client.Assistant().Messages(r.ctx, "", 5)
+ if err != nil || len(page.Items) != 1 || !slices.ContainsFunc(page.Items[0].Attachments, func(a wire.MessageAttachment) bool { return a.ID == sent }) {
+ t.Fatalf("the sent file left its message %+v %v", page.Items, err)
+ }
+}
diff --git a/internal/thintest/attachments_contract_test.go b/internal/thintest/attachments_contract_test.go
index 9dd30c0f..55d291a8 100644
--- a/internal/thintest/attachments_contract_test.go
+++ b/internal/thintest/attachments_contract_test.go
@@ -180,7 +180,7 @@ func TestContractAttachments(t *testing.T) {
if !bytes.Equal(whole, notes) || !bytes.Equal(frames[0].chunk.Data, kept) {
t.Fatal("the chunks do not make the files")
}
- if len(cmd.Attachments) != 2 || cmd.Attachments[1].SHA256 != file.SHA256 || withoutProjectContext(t, cmd.Text) != "" || len(cmd.PersonText) != 1 || cmd.PersonText[0] != "" {
+ if len(cmd.Attachments) != 2 || cmd.Attachments[1].SHA256 != file.SHA256 || withoutProjectContext(t, cmd.Text) != "(files only, no words)" || len(cmd.PersonText) != 1 || cmd.PersonText[0] != "" {
t.Fatalf("message command %+v", cmd)
}
diff --git a/internal/thintest/client.go b/internal/thintest/client.go
index a5b907e7..0f0ba5f7 100644
--- a/internal/thintest/client.go
+++ b/internal/thintest/client.go
@@ -75,6 +75,12 @@ func (c *Client) SendWith(ctx context.Context, text, key string, files []string)
return out, c.do(ctx, "POST", "/api/v1/messages", wire.SendMessage{Text: text, IdempotencyKey: key, Attachments: files}, &out)
}
+// DeleteAttachment is DELETE /api/v1/attachments/{id}: one of the
+// person's own unsent uploads.
+func (c *Client) DeleteAttachment(ctx context.Context, id string) error {
+ return c.do(ctx, "DELETE", "/api/v1/attachments/"+id, nil, nil)
+}
+
// Upload is POST /api/v1/attachments: the bytes, their type and name.
func (c *Client) Upload(ctx context.Context, name, mediaType string, data []byte) (out wire.MessageAttachment, err error) {
r, err := http.NewRequestWithContext(ctx, "POST", c.Origin+"/api/v1/attachments", bytes.NewReader(data))
diff --git a/internal/wire/assistant.go b/internal/wire/assistant.go
index c3beb74e..2f362552 100644
--- a/internal/wire/assistant.go
+++ b/internal/wire/assistant.go
@@ -145,6 +145,9 @@ type AssistantSnapshot struct {
Cards []AssistantCard `json:"cards"`
Cursor int64 `json:"cursor"`
Available bool `json:"available"`
+ // CanAttach says a send with files would be taken now: the person's
+ // primary runner was last seen at ProtocolAssistantFiles or later.
+ CanAttach bool `json:"can_attach"`
}
// AssistantAnswered answers a card answer: the card, the person's answer
@@ -195,6 +198,27 @@ func downgradeAssistant(body any, protocol int) (bool, error) {
return false, nil
}
+// downgradeAssistantFiles says a message as a runner older than
+// ProtocolAssistantFiles reads it: the Assistant took words only, so an
+// Assistant message with files is refused (the send check and fenceLanes
+// keep one from being made), and earlier and earlier_more are dropped
+// (on a copy of the list: the caller's is untouched). It reports whether
+// anything changed.
+func downgradeAssistantFiles(body any, protocol int) (bool, error) {
+ v, ok := body.(*MessageCommand)
+ if !ok {
+ return false, nil
+ }
+ if v.Lane == LaneAssistant && len(v.Attachments) > 0 {
+ return false, fmt.Errorf("%w: an Assistant message with files at protocol %d", ErrProtocol, protocol)
+ }
+ if v.Earlier == nil && v.EarlierMore == 0 {
+ return false, nil
+ }
+ v.Earlier, v.EarlierMore = nil, 0
+ return true, nil
+}
+
// downgradeJobs says f as a runner older than ProtocolJobs speaks it: it
// knows the Coordinator's and the Assistant's lanes and no other, so a
// message in any other lane is refused and a sync loses every session in
diff --git a/internal/wire/assistant_files_test.go b/internal/wire/assistant_files_test.go
new file mode 100644
index 00000000..71db11cc
--- /dev/null
+++ b/internal/wire/assistant_files_test.go
@@ -0,0 +1,82 @@
+package wire_test
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// Protocol 32 (assistant attachments spec A6): the Assistant's own turns
+// carry files and the earlier files of the conversation. Below 32 an
+// Assistant message with files is refused, earlier and earlier_more are
+// dropped, and the Coordinator's and a job's frames go as they are.
+func TestProtocol32AssistantFiles(t *testing.T) {
+ if wire.Protocol32 != 32 || wire.ProtocolAssistantFiles != wire.Protocol32 || wire.ProtocolCurrent != wire.ProtocolAssistantFiles || wire.Spoken(99) != 32 {
+ t.Fatalf("assistant files %d, current %d", wire.ProtocolAssistantFiles, wire.ProtocolCurrent)
+ }
+ if wire.RunnerKeepFiles != 14*24*time.Hour {
+ t.Fatalf("keep %v", wire.RunnerKeepFiles)
+ }
+ file := wire.AttachmentRef{ID: "at_abcdefgh", Kind: wire.AttachmentFile, Name: "notes.md", MediaType: "text/markdown", Size: 4, SHA256: "aa"}
+ old := wire.AttachmentRef{ID: "at_olderone", Kind: wire.AttachmentImage, Name: "a.png", MediaType: "image/png", Size: 9, SHA256: "bb"}
+ msg := func(lane string, files []wire.AttachmentRef, earlier []wire.AttachmentRef, more int) wire.Frame {
+ f, err := wire.NewFrame("m", wire.FrameMessage, wire.MessageCommand{Person: "p", TurnID: "t", Attempt: 1, Kind: wire.TurnPerson, Text: "hi", PersonText: []string{"hi"}, Tail: []wire.TailMessage{}, Attachments: files, Lane: lane, Earlier: earlier, EarlierMore: more})
+ if err != nil {
+ t.Fatal(err)
+ }
+ return f
+ }
+ withFiles := msg(wire.LaneAssistant, []wire.AttachmentRef{file}, nil, 0)
+ withEarlier := msg(wire.LaneAssistant, nil, []wire.AttachmentRef{old}, 3)
+ coordinator := msg(wire.LaneCoordinator, []wire.AttachmentRef{file}, nil, 0)
+ job := msg(wire.JobLane("h_abc"), []wire.AttachmentRef{file}, nil, 0)
+
+ // At 32 everything goes out as it is.
+ for _, f := range []wire.Frame{withFiles, withEarlier, coordinator, job} {
+ if got, err := wire.Encode(f, wire.Protocol32); err != nil || !bytes.Equal(got.Data, f.Data) {
+ t.Fatalf("changed at 32: %v %s", err, got.Data)
+ }
+ }
+ // At 31 an Assistant message with files is refused.
+ if _, err := wire.Encode(withFiles, wire.Protocol31); !errors.Is(err, wire.ErrProtocol) {
+ t.Fatalf("assistant files at 31: %v", err)
+ }
+ // earlier and earlier_more are dropped, and nothing else.
+ got, err := wire.Encode(withEarlier, wire.Protocol31)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if want := msg(wire.LaneAssistant, nil, nil, 0); !bytes.Equal(got.Data, want.Data) {
+ t.Fatalf("earlier at 31:\n got %s\nwant %s", got.Data, want.Data)
+ }
+ var fields map[string]json.RawMessage
+ if err := json.Unmarshal(withEarlier.Data, &fields); err != nil || fields["earlier"] == nil || string(fields["earlier_more"]) != "3" {
+ t.Fatalf("earlier at 32: %s", withEarlier.Data)
+ }
+ // Coordinator and job frames with files are unchanged.
+ for _, f := range []wire.Frame{coordinator, job} {
+ if got, err := wire.Encode(f, wire.Protocol31); err != nil || !bytes.Equal(got.Data, f.Data) {
+ t.Fatalf("lane frame changed at 31: %v %s", err, got.Data)
+ }
+ }
+ // An Assistant message without files or earlier goes unchanged too.
+ plain := msg(wire.LaneAssistant, nil, nil, 0)
+ if got, err := wire.Encode(plain, wire.Protocol31); err != nil || !bytes.Equal(got.Data, plain.Data) {
+ t.Fatalf("plain assistant at 31: %v", err)
+ }
+}
+
+// The snapshot says whether a send with files would be taken.
+func TestAssistantSnapshotCanAttach(t *testing.T) {
+ _, got := jsonKeys(t, wire.AssistantSnapshot{CanAttach: true})
+ if string(got["can_attach"]) != "true" {
+ t.Fatalf("can_attach %s", got["can_attach"])
+ }
+ if _, got = jsonKeys(t, wire.AssistantSnapshot{}); string(got["can_attach"]) != "false" {
+ t.Fatalf("can_attach when false %s", got["can_attach"])
+ }
+}
diff --git a/internal/wire/assistant_test.go b/internal/wire/assistant_test.go
index 4e8a748b..3f98a7af 100644
--- a/internal/wire/assistant_test.go
+++ b/internal/wire/assistant_test.go
@@ -81,7 +81,7 @@ func TestAssistantCardJSON(t *testing.T) {
// A runner that speaks 24 or more is spoken to at 24, the warm
// protocol; glances came at 23 and jobs at 22.
func TestSpokenIs24(t *testing.T) {
- if wire.Spoken(99) != 31 || wire.ProtocolCurrent != wire.ProtocolChangeFiles || wire.ProtocolWarm != wire.Protocol24 || wire.ProtocolGlance != wire.Protocol23 || wire.ProtocolJobs != wire.Protocol22 || wire.ProtocolCopy != wire.Protocol21 || wire.ProtocolUsageRefresh != wire.Protocol20 || wire.ProtocolAssistant != wire.Protocol19 {
+ if wire.Spoken(99) != 32 || wire.ProtocolCurrent != wire.ProtocolAssistantFiles || wire.ProtocolWarm != wire.Protocol24 || wire.ProtocolGlance != wire.Protocol23 || wire.ProtocolJobs != wire.Protocol22 || wire.ProtocolCopy != wire.Protocol21 || wire.ProtocolUsageRefresh != wire.Protocol20 || wire.ProtocolAssistant != wire.Protocol19 {
t.Fatalf("spoken %d, current %d", wire.Spoken(99), wire.ProtocolCurrent)
}
}
diff --git a/internal/wire/change_files_test.go b/internal/wire/change_files_test.go
index cd74f040..530afe17 100644
--- a/internal/wire/change_files_test.go
+++ b/internal/wire/change_files_test.go
@@ -11,7 +11,7 @@ import (
)
func TestProtocol31ChangeFiles(t *testing.T) {
- if wire.ProtocolChangeFiles != 31 || wire.ProtocolCurrent != 31 {
+ if wire.ProtocolChangeFiles != 31 || wire.ProtocolCurrent != 32 {
t.Fatal("protocol not 31")
}
facts := &wire.ChangeFiles{Base: strings.Repeat("a", 40), SHA: strings.Repeat("b", 40), Files: 1, Additions: 1, Entries: []wire.ChangedFile{{Path: "a.txt", Status: "added", Additions: 1}}}
diff --git a/internal/wire/frames.go b/internal/wire/frames.go
index 0f09798a..4d09eaa5 100644
--- a/internal/wire/frames.go
+++ b/internal/wire/frames.go
@@ -270,7 +270,23 @@ type MessageCommand struct {
// LaneAssistant for the Assistant (protocol 19; Encode refuses an
// Assistant message below it).
Lane string `json:"lane,omitempty"`
-}
+ // Earlier are the files the person attached to their own Assistant
+ // messages within RunnerKeepFiles before this turn, newest first, at
+ // most MaxEarlierFiles; EarlierMore counts those beyond. No bytes come
+ // with them: the runner holds them already, or no longer does. Only an
+ // Assistant person turn carries them (protocol 32; Encode drops both
+ // below it).
+ Earlier []AttachmentRef `json:"earlier,omitempty"`
+ EarlierMore int `json:"earlier_more,omitempty"`
+}
+
+// RunnerKeepFiles is how long a runner keeps a delivered attachment, and
+// so how far back a turn's Earlier files reach. A runner may have removed
+// one sooner, for room.
+const RunnerKeepFiles = 14 * 24 * time.Hour
+
+// MaxEarlierFiles bounds a message frame's Earlier.
+const MaxEarlierFiles = 20
// AttachmentRef names one attachment a turn carries.
type AttachmentRef struct {
diff --git a/internal/wire/injection_test.go b/internal/wire/injection_test.go
index 49ac9e94..f959af53 100644
--- a/internal/wire/injection_test.go
+++ b/internal/wire/injection_test.go
@@ -7,10 +7,10 @@ import (
)
func TestInjectionProtocolDowngrade(t *testing.T) {
- if wire.ProtocolInjectionDefences != 28 || wire.ProtocolCurrent != 31 {
+ if wire.ProtocolInjectionDefences != 28 || wire.ProtocolCurrent != 32 {
t.Fatal("injection guarantees require protocol 28")
}
- for version, want := range map[int]int{26: 26, 27: 27, 28: 28, 29: 29, 30: 30, 31: 31, 99: 31} {
+ for version, want := range map[int]int{26: 26, 27: 27, 28: 28, 29: 29, 30: 30, 31: 31, 32: 32, 99: 32} {
if got := wire.Spoken(version); got != want {
t.Fatalf("negotiated %d as %d, want %d", version, got, want)
}
diff --git a/internal/wire/mixed_protocol_test.go b/internal/wire/mixed_protocol_test.go
index 73a547f3..c77714d6 100644
--- a/internal/wire/mixed_protocol_test.go
+++ b/internal/wire/mixed_protocol_test.go
@@ -15,7 +15,7 @@ import (
// both go out whole; at 11 both are downgraded. The numbers are written
// out so that pointing ProtocolResearch back at 12 fails here.
func TestEncodeMixedMeteredAndResearch(t *testing.T) {
- if wire.ProtocolMetered != wire.Protocol12 || wire.ProtocolResearch != wire.Protocol13 || wire.ProtocolCurrent != wire.Protocol31 {
+ if wire.ProtocolMetered != wire.Protocol12 || wire.ProtocolResearch != wire.Protocol13 || wire.ProtocolCurrent != wire.Protocol32 {
t.Fatalf("metered %d, research %d, current %d", wire.ProtocolMetered, wire.ProtocolResearch, wire.ProtocolCurrent)
}
metered := wire.HeldConnection{LocalID: "tensorx-1", Person: "p", Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, State: wire.ConnHealthy, Harness: wire.HarnessPi, Upstream: "https://api.tensorx.ai", Billing: wire.BillingMetered, Model: "z-ai/glm-5.3", Budget: &wire.Budget{Day: 1, Month: 2, Currency: "USD"}, Spend: &wire.Spend{Currency: "USD"}}
diff --git a/internal/wire/models_test.go b/internal/wire/models_test.go
index 892faa67..7bbd770d 100644
--- a/internal/wire/models_test.go
+++ b/internal/wire/models_test.go
@@ -94,7 +94,7 @@ func modelsFrames(t *testing.T) map[string]wire.Frame {
// protocol is checked because an older step in Encode's chain could
// undo a newer one (S5's bug).
func TestEncodeBelowProtocol18AgainstFrozenSchemas(t *testing.T) {
- if wire.ProtocolModels != wire.Protocol18 || wire.ProtocolCurrent != wire.Protocol31 {
+ if wire.ProtocolModels != wire.Protocol18 || wire.ProtocolCurrent != wire.Protocol32 {
t.Fatalf("models %d, current %d", wire.ProtocolModels, wire.ProtocolCurrent)
}
fs := modelsFrames(t)
diff --git a/internal/wire/opencode_test.go b/internal/wire/opencode_test.go
index 6458a7ef..19dc6f35 100644
--- a/internal/wire/opencode_test.go
+++ b/internal/wire/opencode_test.go
@@ -57,7 +57,7 @@ func providersIn(t *testing.T, raw []byte) (providers, harnesses []string) {
// leave hello and sync, its usage rows leave every report, and a connect
// or a report about one is refused. At 17 nothing changes.
func TestEncodeBelowProtocol17DropsOpenCode(t *testing.T) {
- if wire.ProtocolOpenCode != wire.Protocol17 || wire.ProtocolCurrent != wire.Protocol31 {
+ if wire.ProtocolOpenCode != wire.Protocol17 || wire.ProtocolCurrent != wire.Protocol32 {
t.Fatalf("opencode %d, current %d", wire.ProtocolOpenCode, wire.ProtocolCurrent)
}
budget := &wire.Budget{Day: 1_000_000, Month: 10_000_000, Currency: "USD", Revision: 1}
diff --git a/internal/wire/pinned_release_test.go b/internal/wire/pinned_release_test.go
index aeb0eb6c..8cd0b5b2 100644
--- a/internal/wire/pinned_release_test.go
+++ b/internal/wire/pinned_release_test.go
@@ -13,7 +13,7 @@ import (
// carrying a pinned release loses the release and its pin; an unpinned
// release is unchanged from protocol 14.
func TestEncodePinnedReleaseBelow29(t *testing.T) {
- if wire.ProtocolPinnedRelease != wire.Protocol29 || wire.ProtocolCurrent != wire.Protocol31 {
+ if wire.ProtocolPinnedRelease != wire.Protocol29 || wire.ProtocolCurrent != wire.Protocol32 {
t.Fatalf("pinned %d, current %d", wire.ProtocolPinnedRelease, wire.ProtocolCurrent)
}
pinned, err := wire.NewFrame("f1", wire.FrameRelease, wire.ReleaseCommand{ID: "rl_1", Person: "p", TaskID: "tk1", StepID: "s1", StepRevision: 1, Connection: "claude-1"})
diff --git a/internal/wire/publish_test.go b/internal/wire/publish_test.go
index d47cb0c2..b2322f13 100644
--- a/internal/wire/publish_test.go
+++ b/internal/wire/publish_test.go
@@ -17,7 +17,7 @@ import (
// and a hello's sites capability are dropped, so nothing a protocol 15
// peer decodes strictly carries them.
func TestEncodeBelowProtocol16DropsPublish(t *testing.T) {
- if wire.ProtocolPublish != wire.Protocol16 || wire.ProtocolCurrent != wire.Protocol31 {
+ if wire.ProtocolPublish != wire.Protocol16 || wire.ProtocolCurrent != wire.Protocol32 {
t.Fatalf("publish %d, current %d", wire.ProtocolPublish, wire.ProtocolCurrent)
}
publish := wire.DispatchCommand{Person: "p", TaskID: "tk", StepID: "s", Attempt: 1, Specialist: wire.SpecialistPublish, Findings: []wire.Finding{}, CandidateSHA: strings.Repeat("e", 40), Publish: &wire.PublishDispatch{App: "site-sample", Into: "main"}}
diff --git a/internal/wire/runners.go b/internal/wire/runners.go
index 56d363f6..576a5eb7 100644
--- a/internal/wire/runners.go
+++ b/internal/wire/runners.go
@@ -57,6 +57,7 @@ const (
Protocol29 = 29
Protocol30 = 30
Protocol31 = 31
+ Protocol32 = 32
// ProtocolSpend is the first protocol with a fix round's Feedback and
// a usage row's Turns; Encode drops both below it.
ProtocolSpend = Protocol3
@@ -197,7 +198,15 @@ const (
ProtocolStuckTasks = Protocol30
// ProtocolChangeFiles adds bounded Engineering file-list facts.
ProtocolChangeFiles = Protocol31
- ProtocolCurrent = ProtocolChangeFiles
+ // ProtocolAssistantFiles is the first protocol whose Assistant turns
+ // carry the person's files and the files they attached earlier in the
+ // conversation (assistant attachments spec 2026-11-26, A6): a message's
+ // attachments in the Assistant's lane, its earlier and earlier_more.
+ // Below it Encode refuses an Assistant message with attachments and
+ // drops earlier and earlier_more (downgradeAssistantFiles); the
+ // Coordinator's and a job's frames are unchanged.
+ ProtocolAssistantFiles = Protocol32
+ ProtocolCurrent = ProtocolAssistantFiles
)
// Runner roles. A person's first runner is the primary: the coordinator,
@@ -611,7 +620,9 @@ var ErrProtocol = errors.New("wire: frame not in this protocol")
// protocol 2 frame type is refused (ErrProtocol).
//
// Below ProtocolGlance a glance frame is refused, and below ProtocolWarm
-// a warm command.
+// a warm command. Below ProtocolAssistantFiles an Assistant message with
+// attachments is refused and a message's earlier files are dropped
+// (downgradeAssistantFiles).
func Encode(f Frame, protocol int) (Frame, error) {
if protocol >= ProtocolCurrent {
return f, nil
@@ -633,12 +644,19 @@ func Encode(f Frame, protocol int) (Frame, error) {
return Frame{}, ErrProtocol
}
changed := false
+ if protocol < ProtocolAssistantFiles {
+ dropped, err := downgradeAssistantFiles(body, protocol)
+ if err != nil {
+ return Frame{}, err
+ }
+ changed = dropped
+ }
if protocol < ProtocolStuckTasks {
dropped, err := downgradeStuck(body, protocol)
if err != nil {
return Frame{}, err
}
- changed = dropped
+ changed = dropped || changed
}
if protocol < ProtocolChangeFiles {
if v, ok := body.(*StepReport); ok && v.ChangeFiles != nil {
diff --git a/internal/wire/runners_test.go b/internal/wire/runners_test.go
index d54328bd..0d89926d 100644
--- a/internal/wire/runners_test.go
+++ b/internal/wire/runners_test.go
@@ -413,7 +413,7 @@ func TestEncodeBelowProtocol9DropsPreviews(t *testing.T) {
if _, err := wire.Encode(d, wire.ProtocolPreview); err != nil {
t.Fatal(err)
}
- if wire.ProtocolCurrent != wire.ProtocolChangeFiles || wire.ProtocolStuckTasks != 30 || wire.ProtocolPinnedRelease != 29 || wire.ProtocolInjectionDefences != 28 || wire.ProtocolWarm != 24 || wire.ProtocolGlance != 23 || wire.ProtocolJobs != 22 || wire.ProtocolCopy != 21 || wire.ProtocolUsageRefresh != 20 || wire.ProtocolAssistant != 19 || wire.ProtocolModels != 18 || wire.ProtocolOpenCode != 17 || wire.ProtocolPublish != 16 || wire.ProtocolReadings != 15 || wire.ProtocolScheduler != 14 || wire.ProtocolResearch != 13 || wire.ProtocolMetered != 12 || wire.ProtocolPreviewHost != 11 || wire.ProtocolExplore != 10 || wire.ProtocolPreview != 9 {
+ if wire.ProtocolCurrent != wire.ProtocolAssistantFiles || wire.ProtocolStuckTasks != 30 || wire.ProtocolPinnedRelease != 29 || wire.ProtocolInjectionDefences != 28 || wire.ProtocolWarm != 24 || wire.ProtocolGlance != 23 || wire.ProtocolJobs != 22 || wire.ProtocolCopy != 21 || wire.ProtocolUsageRefresh != 20 || wire.ProtocolAssistant != 19 || wire.ProtocolModels != 18 || wire.ProtocolOpenCode != 17 || wire.ProtocolPublish != 16 || wire.ProtocolReadings != 15 || wire.ProtocolScheduler != 14 || wire.ProtocolResearch != 13 || wire.ProtocolMetered != 12 || wire.ProtocolPreviewHost != 11 || wire.ProtocolExplore != 10 || wire.ProtocolPreview != 9 {
t.Fatalf("current %d", wire.ProtocolCurrent)
}
}
diff --git a/internal/wire/schedule_test.go b/internal/wire/schedule_test.go
index 5eab12b5..a1835b00 100644
--- a/internal/wire/schedule_test.go
+++ b/internal/wire/schedule_test.go
@@ -17,7 +17,7 @@ import (
// refused anything that spends, never handed it), and a dispatch loses
// its priority, deadline and release; what 13 already had is unchanged.
func TestEncodeBelowProtocol14DropsScheduler(t *testing.T) {
- if wire.ProtocolScheduler != wire.Protocol14 || wire.ProtocolCurrent != wire.Protocol31 {
+ if wire.ProtocolScheduler != wire.Protocol14 || wire.ProtocolCurrent != wire.Protocol32 {
t.Fatalf("scheduler %d, current %d", wire.ProtocolScheduler, wire.ProtocolCurrent)
}
by := time.Date(2026, 11, 20, 17, 0, 0, 0, time.UTC)
diff --git a/internal/wire/stuck_test.go b/internal/wire/stuck_test.go
index ea32482a..88b77839 100644
--- a/internal/wire/stuck_test.go
+++ b/internal/wire/stuck_test.go
@@ -14,7 +14,7 @@ import (
// Stuck tasks (protocol 30): a hello's tool health is a fixed state per
// pinned tool, never a path, and an older instance never hears it.
func TestProtocol30ToolHealth(t *testing.T) {
- if wire.ProtocolStuckTasks != wire.Protocol30 || wire.ProtocolCurrent != wire.Protocol31 || wire.Spoken(99) != 31 {
+ if wire.ProtocolStuckTasks != wire.Protocol30 || wire.ProtocolCurrent != wire.Protocol32 || wire.Spoken(99) != 32 {
t.Fatalf("stuck %d, current %d", wire.ProtocolStuckTasks, wire.ProtocolCurrent)
}
caps := func(h *wire.ToolHealth) wire.Capabilities {
diff --git a/internal/wire/usage_test.go b/internal/wire/usage_test.go
index 5b254189..6769a87e 100644
--- a/internal/wire/usage_test.go
+++ b/internal/wire/usage_test.go
@@ -44,7 +44,7 @@ func headrooms(t *testing.T, raw []byte) []map[string]json.RawMessage {
// decodes strictly against the frozen protocol 14 headroom, and the
// caller's own values are untouched; at 15 nothing changes.
func TestEncodeBelowProtocol15DropsReadingTimes(t *testing.T) {
- if wire.ProtocolReadings != wire.Protocol15 || wire.ProtocolCurrent != wire.Protocol31 {
+ if wire.ProtocolReadings != wire.Protocol15 || wire.ProtocolCurrent != wire.Protocol32 {
t.Fatalf("readings %d, current %d", wire.ProtocolReadings, wire.ProtocolCurrent)
}
at := time.Date(2026, 11, 12, 9, 58, 0, 0, time.UTC)
diff --git a/internal/wire/warm_test.go b/internal/wire/warm_test.go
index 66bd188d..7e850fda 100644
--- a/internal/wire/warm_test.go
+++ b/internal/wire/warm_test.go
@@ -13,7 +13,7 @@ import (
// other (durable, acked), and Encode refuses it below 24: an older
// runner's strict decoder would close the stream on it.
func TestEncodeWarmBelow24(t *testing.T) {
- if wire.ProtocolWarm != 24 || wire.ProtocolCurrent != wire.ProtocolChangeFiles || wire.Spoken(99) != 31 {
+ if wire.ProtocolWarm != 24 || wire.ProtocolCurrent != wire.ProtocolAssistantFiles || wire.Spoken(99) != 32 {
t.Fatalf("protocols %d %d", wire.ProtocolWarm, wire.ProtocolCurrent)
}
f, err := wire.NewFrame("c1", wire.FrameWarm, wire.WarmCommand{Person: "ana@example.com"})
diff --git a/internal/wire/wireschema/wireschema.go b/internal/wire/wireschema/wireschema.go
index f3644000..ac7966c5 100644
--- a/internal/wire/wireschema/wireschema.go
+++ b/internal/wire/wireschema/wireschema.go
@@ -48,6 +48,7 @@ var Ops = map[string]Op{
"POST /attachments": {Bytes{}, map[string]any{"201": wire.MessageAttachment{}}},
"GET /attachments/{id}": {nil, map[string]any{"200": Bytes{}}},
"GET /attachments/{id}/preview": {nil, map[string]any{"200": Bytes{}}},
+ "DELETE /attachments/{id}": {nil, map[string]any{"204": nil}},
"GET /turns/{id}": {nil, map[string]any{"200": wire.Turn{}}},
"POST /turns/{id}/cancel": {nil, map[string]any{"202": wire.CancelAccepted{}}},
"POST /turns/{id}/retry": {nil, map[string]any{"202": wire.Turn{}}},