Astra round 1: pixel cap, JPEG walk to EOI, restartable relay, quotas
- Images over 12,000 px a side or 40 MP are refused from the header. - The JPEG walk copies each scan and goes on through EOI; metadata after a scan and anything after EOI are dropped. - Finishing a relayed file is restartable through <id>.ready; only a wrong hash discards; filesystem errors keep every chunk, no ack. - Files.Sweep bounds the runner's attachments per person and overall, oldest first, never one a running turn needs; it reconciles records. - Non-image files download; a POST landing first reconciles the chips. - No inline style attributes: hues and widths by data attributes. Each with a test that failed first.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
27 files changed,
+771
−66
docs/superpowers/plans/COMPOSER-PROGRESS.md+49 −0docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+1 −0internal/attach/attach.go+13 −0internal/attach/attach_test.go+57 −0internal/attach/attachtest/attachtest.go+16 −0internal/attach/location.go+29 −4internal/attach/scale.go+4 −1internal/equipo/chat/attachments.go+3 −0internal/equipo/chat/attachments_http.go+6 −4internal/equipo/chat/http.go+2 −0internal/equipo/chat_page.go+2 −0internal/equipo/copy.go+1 −0internal/equipo/static/chat-stream.js+21 −6internal/equipo/static/equipo.css+19 −0internal/equipo/templates/housekeeping.html+1 −1internal/equipo/templates/models.html+1 −1internal/equipo/templates/work_parts.html+6 −6internal/equipo/templates/work_projects.html+1 −1internal/equipo/work_views.go+8 −6internal/headless/browser_attach_test.go+33 −0internal/runner/thin/files.go+252 −36internal/runner/thin/files_test.go+161 −0internal/runner/thin/run.go+2 −0internal/runner/thin/state.go+21 −0internal/thintest/attachments_contract_test.go+19 −0internal/thintest/inline_style_test.go+38 −0internal/thintest/inner_browser_test.go+5 −0
CI passed — run details
diff --git a/docs/superpowers/plans/COMPOSER-PROGRESS.md b/docs/superpowers/plans/COMPOSER-PROGRESS.md| index 8ab0d6dd..b397ef69 100644 |
| --- a/docs/superpowers/plans/COMPOSER-PROGRESS.md |
| +++ b/docs/superpowers/plans/COMPOSER-PROGRESS.md |
| @@ -340,6 +340,55 @@ the x inside it. |
| - HEIC conversion relies on Safari's own decoder: Linux WebKit cannot |
| decode HEIC, so it is witnessed only on a device. |
| +## Round: Astra round 1 (on 8334e25), REQUEST CHANGES |
| + |
| +Four Important and two Minor (`~/.cache/tmp/equipo/comprev-final.md`), |
| +each with a test that failed first, plus the inline styles seen on |
| +staging: |
| +1. Pixels: an image's size is read from its header and over 12,000 px a |
| + side or 40 megapixels is refused before anything decodes (`TooBig`, |
| + `Inspect`, `Preview`, `ForModel`); API code `attachment_pixels`. |
| + `TestPixelCap` (a 100,000 x 100,000 PNG header; failed with the check |
| + off), and the contract test's upload of that header (413). |
| +2. GPS: the JPEG walk no longer stops at the first scan: each scan's |
| + entropy-coded data is copied and the walk goes on through EOI; |
| + metadata segments after a scan are dropped, and nothing after EOI is |
| + kept (appended images). `TestStripLocationAfterScan` (GPS after the |
| + scan and after EOI; failed on the old walk). |
| +3. Finishing is restartable: the checked part becomes `<id>.ready` by a |
| + rename (no chunk is written once it exists), then chmod, mkdir and the |
| + rename into the desk; replay picks up at the next step. Only a wrong |
| + size or hash discards; any filesystem error returns (no ack) and keeps |
| + every chunk and record. `TestAttachmentFinishCrashes` fails each step |
| + in turn (verify, ready, chmod, mkdir, rename, forget): the frame is not |
| + acked, the records stay, the replay delivers the file 0400 with nothing |
| + left over. Failed with the old "discard on any error". |
| +4. Disk bounds: `Files.Sweep` every ten minutes (`Files.Run`) and after |
| + each delivery: parts past two days go with their records, records with |
| + no file go, delivered files past 14 days go, and over a quota (per |
| + person 500 MB or 1,000 files; the runner 2 GB or 4,000) the oldest go |
| + first. Never a file a running turn names, nor one delivered in the |
| + last hour (its message frame follows its chunks). `TestAttachmentSweep` |
| + (quota per person and overall, protection, retention, stale part and |
| + orphan records); failed with the quota off, protection off, or orphans |
| + kept. |
| +5. Every file that is not an image is served `attachment` (HTML accepted |
| + as plain text downloads). Contract test; failed first. |
| +6. A send whose POST lands before its event takes the server's |
| + attachments at once. `TestBrowserComposerReconcile` holds the event |
| + stream back (Fetch interception); failed on the old script. |
| +7. Inline styles (production's CSP refuses them): avatar and monogram |
| + hues are one of 24 steps (`data-h`), meter and spread widths whole |
| + percents (`data-w`), the mark's motes fixed in CSS; no |
| + `unsafe-inline`, no script. `TestPagesNoInlineStyle` (every gallery |
| + screen, in CI) failed first on /tasks, /projects, /housekeeping and |
| + the task and project pages; `TestBrowserInnerScreens` checks under the |
| + policy that avatars have a hue, bars a width, and nothing has a style |
| + attribute (failed on the old templates). |
| + |
| +New copy, accepted for now: `api.attachment_pixels` "That image is too |
| +large: at most 12,000 pixels on a side and 40 megapixels." |
| + |
| ## Staging |
| Not restaged (the controller sequences it). |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index 0e91096a..bfc326d8 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -5150,6 +5150,7 @@ records remain unchanged. |
| | `api.attachment_too_large` | That file is over 10 MB. | Composer and attachments (2026-11-08) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `api.attachment_type` | Equipo takes images (PNG, JPEG, WebP, GIF) and text, Markdown, CSV, JSON, log and PDF files. | Composer and attachments (2026-11-08) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `api.attachment_heic` | HEIC photos cannot be read yet. Share it as a JPEG and try again. | Composer and attachments (2026-11-08) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| +| `api.attachment_pixels` | That image is too large: at most 12,000 pixels on a side and 40 megapixels. | Composer and attachments (2026-11-08) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `api.attachment_limit` | Too many files are waiting to send. Send or remove some first. | Composer and attachments (2026-11-08) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `settings.saved` | Saved | Composer and attachments (2026-11-08) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `chat.housekeeping.link` | Housekeeping | Housekeeping slice 1 (Housekeeping view, digest, receipts) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
diff --git a/internal/attach/attach.go b/internal/attach/attach.go| index baa15d57..4b4898b7 100644 |
| --- a/internal/attach/attach.go |
| +++ b/internal/attach/attach.go |
| @@ -29,6 +29,10 @@ const ( |
| MaxChunks = (MaxBytes + ChunkBytes - 1) / ChunkBytes |
| // MaxName bounds a stored name, in bytes. |
| MaxName = 120 |
| + // MaxSide and MaxPixels bound an image's size, read from its header |
| + // before anything decodes it: a small file can claim a huge canvas. |
| + MaxSide = 12000 |
| + MaxPixels = 40_000_000 |
| ) |
| // Kinds. |
| @@ -56,8 +60,14 @@ var ( |
| ErrTooLarge = errors.New("attach: too large") |
| ErrType = errors.New("attach: type not allowed") |
| ErrHEIC = errors.New("attach: heic") |
| + ErrPixels = errors.New("attach: too many pixels") |
| ) |
| +// TooBig reports image dimensions over MaxSide or MaxPixels. |
| +func TooBig(w, h int) bool { |
| + return w > MaxSide || h > MaxSide || int64(w)*int64(h) > MaxPixels |
| +} |
| + |
| // Info is what Inspect found. |
| type Info struct { |
| Kind, MediaType, Name string |
| @@ -121,6 +131,9 @@ func Inspect(name, declared string, data []byte) (Info, []byte, error) { |
| if w == 0 || h == 0 { |
| return Info{}, nil, ErrType |
| } |
| + if TooBig(w, h) { |
| + return Info{}, nil, ErrPixels |
| + } |
| return Info{Kind: KindImage, MediaType: sniffed, Name: withExt(name, sniffed), Width: w, Height: h}, clean, nil |
| case sniffed == PDF: |
| if (ext != "" && ext != ".pdf") || (declared != "" && declared != PDF && declared != "application/octet-stream" && (strings.HasPrefix(declared, "image/") || strings.HasPrefix(declared, "text/"))) { |
diff --git a/internal/attach/attach_test.go b/internal/attach/attach_test.go| index 356738ae..5c1fa572 100644 |
| --- a/internal/attach/attach_test.go |
| +++ b/internal/attach/attach_test.go |
| @@ -331,3 +331,60 @@ func TestRenditions(t *testing.T) { |
| t.Fatalf("preview width %d", w) |
| } |
| } |
| + |
| +// pngHeader is a PNG that claims w by h: a signature, IHDR and IEND, |
| +// which is all a header read looks at. |
| +func pngHeader(w, h uint32) []byte { |
| + ihdr := binary.BigEndian.AppendUint32(nil, w) |
| + ihdr = binary.BigEndian.AppendUint32(ihdr, h) |
| + ihdr = append(ihdr, 8, 6, 0, 0, 0) |
| + out := []byte("\x89PNG\r\n\x1a\n") |
| + out = append(out, chunk("IHDR", ihdr)...) |
| + return append(out, chunk("IEND", nil)...) |
| +} |
| + |
| +// Astra round 1: a small file may claim a canvas that decoding would |
| +// allocate in full. The header is read first; more than 12,000 px on a |
| +// side or 40 megapixels is refused before anything decodes. |
| +func TestPixelCap(t *testing.T) { |
| + for _, size := range [][2]uint32{{100000, 100000}, {12001, 10}, {10, 12001}, {8000, 6000}} { |
| + if _, _, err := Inspect("huge.png", "image/png", pngHeader(size[0], size[1])); !errors.Is(err, ErrPixels) { |
| + t.Fatalf("%dx%d: %v, want refused for its pixels", size[0], size[1], err) |
| + } |
| + if _, _, err := Preview(PNG, pngHeader(size[0], size[1])); !errors.Is(err, ErrPixels) { |
| + t.Fatalf("%dx%d: a preview was attempted: %v", size[0], size[1], err) |
| + } |
| + if _, _, ok := ForModel(PNG, pngHeader(size[0], size[1])); ok { |
| + t.Fatalf("%dx%d: a model image was attempted", size[0], size[1]) |
| + } |
| + } |
| + if !TooBig(12000, 3334) || TooBig(12000, 3333) { |
| + t.Fatal("the 40 megapixel line moved") |
| + } |
| +} |
| + |
| +// Astra round 1: GPS placed after the scan, or after the end of the |
| +// image, survived. Every segment is walked through EOI; metadata after a |
| +// scan and anything after EOI are dropped. |
| +func TestStripLocationAfterScan(t *testing.T) { |
| + raw := jpegOf(t, 40, 20) |
| + exif := segment(0xe1, append([]byte("Exif\x00\x00"), exifWithGPS(1)...)) |
| + eoi := len(raw) - 2 |
| + late := append(append(append([]byte{}, raw[:eoi]...), exif...), raw[eoi:]...) |
| + trailing := append(append([]byte{}, raw...), exif...) |
| + for name, b := range map[string][]byte{"after the scan": late, "after EOI": trailing} { |
| + if !hasGPSMark(b) { |
| + t.Fatalf("%s: fixture has no GPS", name) |
| + } |
| + _, clean, err := Inspect("late.jpg", "", b) |
| + if err != nil { |
| + t.Fatalf("%s: %v", name, err) |
| + } |
| + if hasGPSMark(clean) { |
| + t.Fatalf("%s: location survived", name) |
| + } |
| + if img, err := jpeg.Decode(bytes.NewReader(clean)); err != nil || img.Bounds().Dx() != 40 { |
| + t.Fatalf("%s: no longer decodes: %v", name, err) |
| + } |
| + } |
| +} |
diff --git a/internal/attach/attachtest/attachtest.go b/internal/attach/attachtest/attachtest.go| index 98dfc536..e2c9e375 100644 |
| --- a/internal/attach/attachtest/attachtest.go |
| +++ b/internal/attach/attachtest/attachtest.go |
| @@ -5,6 +5,7 @@ package attachtest |
| import ( |
| "bytes" |
| "encoding/binary" |
| + "hash/crc32" |
| "image" |
| "image/color" |
| "image/jpeg" |
| @@ -74,3 +75,18 @@ func tiff(orientation uint16) []byte { |
| } |
| return b |
| } |
| + |
| +// PNGHeader is a PNG that claims w by h: a signature, IHDR and IEND only. |
| +func PNGHeader(w, h uint32) []byte { |
| + ihdr := binary.BigEndian.AppendUint32(nil, w) |
| + ihdr = append(binary.BigEndian.AppendUint32(ihdr, h), 8, 6, 0, 0, 0) |
| + out := []byte("\x89PNG\r\n\x1a\n") |
| + out = append(out, pngChunk("IHDR", ihdr)...) |
| + return append(out, pngChunk("IEND", nil)...) |
| +} |
| + |
| +func pngChunk(kind string, data []byte) []byte { |
| + out := binary.BigEndian.AppendUint32(nil, uint32(len(data))) |
| + out = append(append(out, kind...), data...) |
| + return binary.BigEndian.AppendUint32(out, crc32.ChecksumIEEE(append([]byte(kind), data...))) |
| +} |
diff --git a/internal/attach/location.go b/internal/attach/location.go| index d5e012cc..66b12a4e 100644 |
| --- a/internal/attach/location.go |
| +++ b/internal/attach/location.go |
| @@ -43,6 +43,7 @@ func stripJPEG(b []byte) ([]byte, error) { |
| out := bytes.NewBuffer(make([]byte, 0, len(b))) |
| out.Write(b[:2]) |
| i := 2 |
| + scanned := false |
| for i < len(b) { |
| if b[i] != 0xff { |
| return nil, errFormat |
| @@ -56,7 +57,7 @@ func stripJPEG(b []byte) ([]byte, error) { |
| marker := b[i] |
| i++ |
| switch { |
| - case marker == 0xd9: // EOI |
| + case marker == 0xd9: // EOI: anything after it (appended images) goes |
| out.Write([]byte{0xff, marker}) |
| return out.Bytes(), nil |
| case marker >= 0xd0 && marker <= 0xd7, marker == 0x01: |
| @@ -72,10 +73,30 @@ func stripJPEG(b []byte) ([]byte, error) { |
| } |
| seg := b[i+2 : i+n] |
| if marker == 0xda { |
| - // Start of scan: the entropy-coded data and the rest follow as is. |
| + // Start of scan: its header, then the entropy-coded data up to |
| + // the next marker (stuffed bytes and restart markers are data). |
| + // The walk goes on after it: a progressive JPEG has more scans, |
| + // and a segment after a scan is read like any other. |
| out.Write([]byte{0xff, marker}) |
| - out.Write(b[i:]) |
| - return out.Bytes(), nil |
| + out.Write(b[i : i+n]) |
| + j := i + n |
| + for j < len(b) { |
| + if b[j] == 0xff && j+1 < len(b) { |
| + next := b[j+1] |
| + if next == 0x00 || next >= 0xd0 && next <= 0xd7 { |
| + out.Write(b[j : j+2]) |
| + j += 2 |
| + continue |
| + } |
| + if next != 0xff { |
| + break |
| + } |
| + } |
| + out.WriteByte(b[j]) |
| + j++ |
| + } |
| + i, scanned = j, true |
| + continue |
| } |
| drop := false |
| switch marker { |
| @@ -92,6 +113,10 @@ func stripJPEG(b []byte) ([]byte, error) { |
| case 0xed: // APP13: Photoshop IRB with IPTC (city, sublocation) |
| drop = true |
| } |
| + // Metadata after a scan has no business there: it goes. |
| + if scanned && marker >= 0xe1 && marker <= 0xef { |
| + drop = true |
| + } |
| if !drop { |
| out.Write([]byte{0xff, marker}) |
| out.Write(b[i : i+2]) |
diff --git a/internal/attach/scale.go b/internal/attach/scale.go| index b30a5282..d118012c 100644 |
| --- a/internal/attach/scale.go |
| +++ b/internal/attach/scale.go |
| @@ -26,6 +26,9 @@ func Preview(mediaType string, b []byte) (out []byte, ok bool, err error) { |
| return nil, false, nil |
| } |
| w, h := Dimensions(mediaType, b) |
| + if w == 0 || TooBig(w, h) { |
| + return nil, false, ErrPixels |
| + } |
| turn := 1 |
| if mediaType == JPEG { |
| turn = Orientation(b) |
| @@ -49,7 +52,7 @@ func ForModel(mediaType string, b []byte) (out []byte, outType string, ok bool) |
| if w > 0 && max(w, h) <= ModelEdge && len(b) <= ModelBytes && turn == 1 { |
| return b, mediaType, true |
| } |
| - if mediaType == WebP { |
| + if mediaType == WebP || w == 0 || TooBig(w, h) { |
| return nil, "", false |
| } |
| out, err := scaled(b, turn, ModelEdge, 85) |
diff --git a/internal/equipo/chat/attachments.go b/internal/equipo/chat/attachments.go| index 67be0036..c5f85b06 100644 |
| --- a/internal/equipo/chat/attachments.go |
| +++ b/internal/equipo/chat/attachments.go |
| @@ -21,6 +21,7 @@ var ( |
| ErrAttachmentType = errors.New("chat: attachment type") |
| ErrAttachmentHEIC = errors.New("chat: attachment heic") |
| ErrAttachmentLimit = errors.New("chat: too many unsent attachments") |
| + ErrAttachmentPixels = errors.New("chat: attachment too many pixels") |
| ) |
| // Unsent uploads are kept a day, and a person holds at most this many. |
| @@ -74,6 +75,8 @@ func (s *Store) Upload(ctx context.Context, person, name, declared string, data |
| return out, ErrAttachmentTooLarge |
| case errors.Is(err, attach.ErrHEIC): |
| return out, ErrAttachmentHEIC |
| + case errors.Is(err, attach.ErrPixels): |
| + return out, ErrAttachmentPixels |
| case err != nil: |
| return out, ErrAttachmentType |
| } |
diff --git a/internal/equipo/chat/attachments_http.go b/internal/equipo/chat/attachments_http.go| index 1e99abd8..88d5edbd 100644 |
| --- a/internal/equipo/chat/attachments_http.go |
| +++ b/internal/equipo/chat/attachments_http.go |
| @@ -55,7 +55,7 @@ func (h *HTTP) attachment(preview bool) handler { |
| // ServeAttachment writes one of the person's attachments with its sniffed |
| // type and nothing a browser could run: nosniff and a sandboxing CSP. |
| -// Images and text show inline; a PDF downloads. |
| +// Images show inline; every other file downloads. |
| func ServeAttachment(w http.ResponseWriter, r *http.Request, s *Store, person, id string, preview bool, fail func(error)) { |
| meta, data, err := s.AttachmentData(r.Context(), person, id, preview) |
| if err != nil { |
| @@ -66,9 +66,11 @@ func ServeAttachment(w http.ResponseWriter, r *http.Request, s *Store, person, i |
| if strings.HasPrefix(media, "text/") || media == attach.JSON { |
| media += "; charset=utf-8" |
| } |
| - disposition := "inline" |
| - if meta.MediaType == attach.PDF { |
| - disposition = "attachment" |
| + // An image shows inline; every other file downloads (Astra round 1: |
| + // text accepted as plain text may be HTML). |
| + disposition := "attachment" |
| + if attach.IsImage(meta.MediaType) { |
| + disposition = "inline" |
| } |
| h := w.Header() |
| h.Set("Content-Type", media) |
diff --git a/internal/equipo/chat/http.go b/internal/equipo/chat/http.go| index 869d7156..3836d295 100644 |
| --- a/internal/equipo/chat/http.go |
| +++ b/internal/equipo/chat/http.go |
| @@ -281,6 +281,8 @@ func (h *HTTP) fail(w http.ResponseWriter, r *http.Request, err error) { |
| personapi.WriteError(w, r, http.StatusUnsupportedMediaType, "attachment_type", nil) |
| case errors.Is(err, ErrAttachmentHEIC): |
| personapi.WriteError(w, r, http.StatusUnsupportedMediaType, "attachment_heic", nil) |
| + case errors.Is(err, ErrAttachmentPixels): |
| + personapi.WriteError(w, r, http.StatusRequestEntityTooLarge, "attachment_pixels", nil) |
| case errors.Is(err, ErrAttachmentLimit): |
| personapi.WriteError(w, r, 409, "attachment_limit", nil) |
| default: |
diff --git a/internal/equipo/chat_page.go b/internal/equipo/chat_page.go| index 1dfbd5b4..cf0268f3 100644 |
| --- a/internal/equipo/chat_page.go |
| +++ b/internal/equipo/chat_page.go |
| @@ -326,6 +326,8 @@ func uploadRefusal(err error) (string, int) { |
| return "attachment_type", http.StatusUnsupportedMediaType |
| case errors.Is(err, chat.ErrAttachmentHEIC): |
| return "attachment_heic", http.StatusUnsupportedMediaType |
| + case errors.Is(err, chat.ErrAttachmentPixels): |
| + return "attachment_pixels", http.StatusRequestEntityTooLarge |
| case errors.Is(err, chat.ErrAttachmentLimit): |
| return "attachment_limit", http.StatusConflict |
| } |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index 875f1ada..4497a072 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -1084,6 +1084,7 @@ var pageCopy = map[string]string{ |
| "api.attachment_too_large": "That file is over 10 MB.", |
| "api.attachment_type": "Equipo takes images (PNG, JPEG, WebP, GIF) and text, Markdown, CSV, JSON, log and PDF files.", |
| "api.attachment_heic": "HEIC photos cannot be read yet. Share it as a JPEG and try again.", |
| + "api.attachment_pixels": "That image is too large: at most 12,000 pixels on a side and 40 megapixels.", |
| "api.attachment_limit": "Too many files are waiting to send. Send or remove some first.", |
| // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): conversation.send |
| "conversation.send": "Send message", |
diff --git a/internal/equipo/static/chat-stream.js b/internal/equipo/static/chat-stream.js| index 06a69678..d4789925 100644 |
| --- a/internal/equipo/static/chat-stream.js |
| +++ b/internal/equipo/static/chat-stream.js |
| @@ -504,10 +504,7 @@ |
| var own = template("equipo-own-template"); |
| own.dataset.message = v.id; |
| own.querySelector("[equipo-message-body]").textContent = v.text; |
| - sentFiles(own, (v.attachments || []).map(function (a) { |
| - var at = "/conversation/attachments/" + encodeURIComponent(a.id); |
| - return { kind: a.kind, name: a.name, size: a.size, href: at, src: at + "/preview", width: a.width, height: a.height, id: a.id }; |
| - })); |
| + sentFiles(own, served(v.attachments)); |
| own.querySelector("time").textContent = new Date(v.created_at).toTimeString().slice(0, 5); |
| var waiting = feed.querySelector("[equipo-thinking]"); |
| feed.insertBefore(own, waiting); |
| @@ -594,6 +591,13 @@ |
| feed.insertBefore(el, feed.querySelector("[equipo-thinking]")); |
| scroll(); |
| } |
| + // served is a message's attachments as the server keeps them. |
| + function served(list) { |
| + return (list || []).map(function (a) { |
| + var at = "/conversation/attachments/" + encodeURIComponent(a.id); |
| + return { kind: a.kind, name: a.name, size: a.size, href: at, src: at + "/preview", width: a.width, height: a.height, id: a.id }; |
| + }); |
| + } |
| // sentFiles draws a message's attachments inside the person's own |
| // message, above the words: a thumbnail or a file chip. |
| function sentFiles(el, files) { |
| @@ -639,8 +643,19 @@ |
| .then(function (sent) { |
| local.delete(el); |
| delete el.dataset.pending; |
| - if (feed.querySelector('[data-message="' + CSS.escape(sent.message.id) + '"]')) el.remove(); |
| - else el.dataset.message = sent.message.id; |
| + if (feed.querySelector('[data-message="' + CSS.escape(sent.message.id) + '"]')) { |
| + el.remove(); |
| + return; |
| + } |
| + el.dataset.message = sent.message.id; |
| + // The post landed before its event: the attachments become the |
| + // server's (links that work; an upload that failed meanwhile goes). |
| + var box = el.querySelector("[equipo-message-files]"); |
| + if (box && !box.hidden) { |
| + box.replaceChildren(); |
| + box.hidden = true; |
| + sentFiles(el, served(sent.message.attachments)); |
| + } |
| }) |
| .catch(function () { |
| delete el.dataset.pending; |
diff --git a/internal/equipo/static/equipo.css b/internal/equipo/static/equipo.css| index c3311727..05f5e657 100644 |
| --- a/internal/equipo/static/equipo.css |
| +++ b/internal/equipo/static/equipo.css |
| @@ -1087,3 +1087,22 @@ a[equipo-source]:hover { color: var(--rst-text); text-decoration: underline; tex |
| [equipo-saved-tick] .icon { inline-size: 1em; block-size: 1em; margin: 0; } |
| [data-settings-live] [aria-busy="true"] form, [data-settings-live][aria-busy="true"] form { opacity: .7; } |
| @media (prefers-reduced-motion: reduce) { [equipo-saved-tick] { transition: none; } } |
| + |
| +/* Colours and widths the page cannot set inline (production's policy |
| + refuses style attributes): a hue in 24 steps, a width in whole percent, |
| + and the mark's three motes. */ |
| +[data-h="0"] { --h: 0; } [data-h="15"] { --h: 15; } [data-h="30"] { --h: 30; } [data-h="45"] { --h: 45; } [data-h="60"] { --h: 60; } [data-h="75"] { --h: 75; } [data-h="90"] { --h: 90; } [data-h="105"] { --h: 105; } [data-h="120"] { --h: 120; } [data-h="135"] { --h: 135; } [data-h="150"] { --h: 150; } [data-h="165"] { --h: 165; } [data-h="180"] { --h: 180; } [data-h="195"] { --h: 195; } [data-h="210"] { --h: 210; } [data-h="225"] { --h: 225; } [data-h="240"] { --h: 240; } [data-h="255"] { --h: 255; } [data-h="270"] { --h: 270; } [data-h="285"] { --h: 285; } [data-h="300"] { --h: 300; } [data-h="315"] { --h: 315; } [data-h="330"] { --h: 330; } [data-h="345"] { --h: 345; } |
| +[data-w="0"] { inline-size: 0%; } [data-w="1"] { inline-size: 1%; } [data-w="2"] { inline-size: 2%; } [data-w="3"] { inline-size: 3%; } [data-w="4"] { inline-size: 4%; } [data-w="5"] { inline-size: 5%; } [data-w="6"] { inline-size: 6%; } [data-w="7"] { inline-size: 7%; } [data-w="8"] { inline-size: 8%; } [data-w="9"] { inline-size: 9%; } |
| +[data-w="10"] { inline-size: 10%; } [data-w="11"] { inline-size: 11%; } [data-w="12"] { inline-size: 12%; } [data-w="13"] { inline-size: 13%; } [data-w="14"] { inline-size: 14%; } [data-w="15"] { inline-size: 15%; } [data-w="16"] { inline-size: 16%; } [data-w="17"] { inline-size: 17%; } [data-w="18"] { inline-size: 18%; } [data-w="19"] { inline-size: 19%; } |
| +[data-w="20"] { inline-size: 20%; } [data-w="21"] { inline-size: 21%; } [data-w="22"] { inline-size: 22%; } [data-w="23"] { inline-size: 23%; } [data-w="24"] { inline-size: 24%; } [data-w="25"] { inline-size: 25%; } [data-w="26"] { inline-size: 26%; } [data-w="27"] { inline-size: 27%; } [data-w="28"] { inline-size: 28%; } [data-w="29"] { inline-size: 29%; } |
| +[data-w="30"] { inline-size: 30%; } [data-w="31"] { inline-size: 31%; } [data-w="32"] { inline-size: 32%; } [data-w="33"] { inline-size: 33%; } [data-w="34"] { inline-size: 34%; } [data-w="35"] { inline-size: 35%; } [data-w="36"] { inline-size: 36%; } [data-w="37"] { inline-size: 37%; } [data-w="38"] { inline-size: 38%; } [data-w="39"] { inline-size: 39%; } |
| +[data-w="40"] { inline-size: 40%; } [data-w="41"] { inline-size: 41%; } [data-w="42"] { inline-size: 42%; } [data-w="43"] { inline-size: 43%; } [data-w="44"] { inline-size: 44%; } [data-w="45"] { inline-size: 45%; } [data-w="46"] { inline-size: 46%; } [data-w="47"] { inline-size: 47%; } [data-w="48"] { inline-size: 48%; } [data-w="49"] { inline-size: 49%; } |
| +[data-w="50"] { inline-size: 50%; } [data-w="51"] { inline-size: 51%; } [data-w="52"] { inline-size: 52%; } [data-w="53"] { inline-size: 53%; } [data-w="54"] { inline-size: 54%; } [data-w="55"] { inline-size: 55%; } [data-w="56"] { inline-size: 56%; } [data-w="57"] { inline-size: 57%; } [data-w="58"] { inline-size: 58%; } [data-w="59"] { inline-size: 59%; } |
| +[data-w="60"] { inline-size: 60%; } [data-w="61"] { inline-size: 61%; } [data-w="62"] { inline-size: 62%; } [data-w="63"] { inline-size: 63%; } [data-w="64"] { inline-size: 64%; } [data-w="65"] { inline-size: 65%; } [data-w="66"] { inline-size: 66%; } [data-w="67"] { inline-size: 67%; } [data-w="68"] { inline-size: 68%; } [data-w="69"] { inline-size: 69%; } |
| +[data-w="70"] { inline-size: 70%; } [data-w="71"] { inline-size: 71%; } [data-w="72"] { inline-size: 72%; } [data-w="73"] { inline-size: 73%; } [data-w="74"] { inline-size: 74%; } [data-w="75"] { inline-size: 75%; } [data-w="76"] { inline-size: 76%; } [data-w="77"] { inline-size: 77%; } [data-w="78"] { inline-size: 78%; } [data-w="79"] { inline-size: 79%; } |
| +[data-w="80"] { inline-size: 80%; } [data-w="81"] { inline-size: 81%; } [data-w="82"] { inline-size: 82%; } [data-w="83"] { inline-size: 83%; } [data-w="84"] { inline-size: 84%; } [data-w="85"] { inline-size: 85%; } [data-w="86"] { inline-size: 86%; } [data-w="87"] { inline-size: 87%; } [data-w="88"] { inline-size: 88%; } [data-w="89"] { inline-size: 89%; } |
| +[data-w="90"] { inline-size: 90%; } [data-w="91"] { inline-size: 91%; } [data-w="92"] { inline-size: 92%; } [data-w="93"] { inline-size: 93%; } [data-w="94"] { inline-size: 94%; } [data-w="95"] { inline-size: 95%; } [data-w="96"] { inline-size: 96%; } [data-w="97"] { inline-size: 97%; } [data-w="98"] { inline-size: 98%; } [data-w="99"] { inline-size: 99%; } |
| +[data-w="100"] { inline-size: 100%; } |
| +[equipo-mark] [data-m="1"] { --dx: .9em; --dy: -.6em; --d: .3s; --dur: 4.6s; } |
| +[equipo-mark] [data-m="2"] { --dx: 1.5em; --dy: -.1em; --d: 2.1s; --dur: 5.7s; } |
| +[equipo-mark] [data-m="3"] { --dx: 1.1em; --dy: .5em; --d: 3.8s; --dur: 5.1s; } |
diff --git a/internal/equipo/templates/housekeeping.html b/internal/equipo/templates/housekeeping.html| index e58c1e25..eb592d33 100644 |
| --- a/internal/equipo/templates/housekeeping.html |
| +++ b/internal/equipo/templates/housekeeping.html |
| @@ -7,7 +7,7 @@ |
| <p equipo-hk-to-settings><a href="/conversation/settings#housekeeping" data-hk-settings-link>{{copy "housekeeping.settings_link"}}</a></p></header> |
| {{if .Paused}}<p equipo-hk-paused role="status">{{copy "housekeeping.paused"}}</p>{{end}} |
| <section equipo-hk-part aria-labelledby="hk-today"><h2 id="hk-today">{{copy "housekeeping.today"}}</h2> |
| -<ul equipo-hk-meters role="list">{{range .Meters}}<li equipo-conn-meter data-hk-meter><span>{{.Label}}</span><span equipo-conn-bar aria-hidden="true"><i style="inline-size:{{.Percent}}%"></i></span><span><b>{{.Used}}</b>{{with .Held}}, {{.}}{{end}}</span></li>{{end}}</ul></section> |
| +<ul equipo-hk-meters role="list">{{range .Meters}}<li equipo-conn-meter data-hk-meter><span>{{.Label}}</span><span equipo-conn-bar aria-hidden="true"><i data-w="{{.Percent}}"></i></span><span><b>{{.Used}}</b>{{with .Held}}, {{.}}{{end}}</span></li>{{end}}</ul></section> |
| <section equipo-hk-part aria-labelledby="hk-actions"><h2 id="hk-actions">{{copy "housekeeping.actions"}}</h2> |
| {{if .Actions}}<ol equipo-hk-list role="list">{{range .Actions}}<li equipo-hk-action data-action="{{.ID}}"{{if .Undone}} data-undone{{end}}{{if .Waiting}} data-waiting{{end}}><p equipo-hk-line>{{icon "check-circle"}}<span>{{.Line}}</span></p><p equipo-hk-meta><time datetime="{{.At}}">{{.When}}</time>{{with .Evidence}}<span>{{.}}</span>{{end}}{{with .State}}<span data-hk-state>{{.}}</span>{{end}}{{if .Undoable}}<span>{{.Until}}</span>{{end}}</p>{{if .Undoable}}<form method="post" action="/housekeeping/actions/{{.ID}}/undo" equipo-hk-undo><button equipo-link type="submit" data-hk-undo>{{copy "housekeeping.undo"}}</button></form>{{end}}</li>{{end}}</ol>{{else}}<p data-empty-state="housekeeping.actions_empty" equipo-hk-empty>{{copy "housekeeping.actions_empty"}}</p>{{end}}</section> |
| {{if .Refusals}}<section equipo-hk-part aria-labelledby="hk-refusals"><h2 id="hk-refusals">{{copy "housekeeping.refusals"}}</h2><ol equipo-hk-list role="list">{{range .Refusals}}<li equipo-hk-action data-action="{{.ID}}" data-refused><p equipo-hk-line>{{icon "x-circle"}}<span>{{.Line}}</span></p><p equipo-hk-meta><time datetime="{{.At}}">{{.When}}</time><span data-hk-state>{{.State}}</span></p></li>{{end}}</ol></section>{{end}} |
diff --git a/internal/equipo/templates/models.html b/internal/equipo/templates/models.html| index 5ee5c7a1..9f60450c 100644 |
| --- a/internal/equipo/templates/models.html |
| +++ b/internal/equipo/templates/models.html |
| @@ -49,7 +49,7 @@ |
| {{template "conn-mark" .Provider}} |
| <div equipo-conn-body> |
| <p equipo-conn-head><span equipo-conn-name>{{.Name}}</span><span equipo-conn-account>{{.Label}}{{with .Plan}}, {{.}}{{end}}</span>{{if .Preferred}}<span equipo-conn-pref>{{icon "star"}}{{copy "chat.connections.preferred"}}</span>{{end}}</p> |
| -<p equipo-conn-facts><span equipo-conn-state data-connection-state data-s="{{.State}}">{{.Words}}</span>{{range .Meters}}<span equipo-conn-meter data-level="{{.Level}}"><span equipo-conn-bar><i style="inline-size:{{.Used}}%"></i></span><span>{{.Name}} <b>{{.Used}}%</b>{{with .Resets}}, {{.}}{{end}}</span></span>{{end}}</p> |
| +<p equipo-conn-facts><span equipo-conn-state data-connection-state data-s="{{.State}}">{{.Words}}</span>{{range .Meters}}<span equipo-conn-meter data-level="{{.Level}}"><span equipo-conn-bar><i data-w="{{.Used}}"></i></span><span>{{.Name}} <b>{{.Used}}%</b>{{with .Resets}}, {{.}}{{end}}</span></span>{{end}}</p> |
| {{if .Roles}}<p equipo-conn-roles><span equipo-conn-roles-label>{{copy "chat.connections.serving"}}</span>{{range .Roles}}<span equipo-conn-chip{{if .Live}} data-live{{end}}>{{if .Live}}{{template "conn-star"}}{{end}}{{.Name}}</span>{{end}}</p>{{else}}{{with .RolesNote}}<p equipo-conn-roles><span equipo-conn-roles-note>{{.}}</span></p>{{end}}{{end}} |
| </div> |
| <div equipo-conn-side> |
diff --git a/internal/equipo/templates/work_parts.html b/internal/equipo/templates/work_parts.html| index 92231f92..fcb6fc4f 100644 |
| --- a/internal/equipo/templates/work_parts.html |
| +++ b/internal/equipo/templates/work_parts.html |
| @@ -2,14 +2,14 @@ |
| the stage track, badges, the row and the decision card. Every row is |
| clickable as a whole through its title link's ::after; the few |
| controls inside a row sit above it. */}} |
| -{{define "mark"}}<span equipo-sparkle equipo-mark{{if eq . "s"}} data-size="s"{{end}} aria-hidden="true"><svg viewBox="0 0 16 16" focusable="false"><path d="M8 0C8.6 4.6 11.4 7.4 16 8 11.4 8.6 8.6 11.4 8 16 7.4 11.4 4.6 8.6 0 8 4.6 7.4 7.4 4.6 8 0Z"/><circle cx="8" cy="8" r="1.7"/></svg><i data-sat="1"></i><i data-sat="2"></i><i data-sat="3"></i>{{if ne . "s"}}<i data-mote style="--dx:.9em;--dy:-.6em;--d:.3s;--dur:4.6s"></i><i data-mote="light" style="--dx:1.5em;--dy:-.1em;--d:2.1s;--dur:5.7s"></i><i data-mote style="--dx:1.1em;--dy:.5em;--d:3.8s;--dur:5.1s"></i>{{end}}</span>{{end}} |
| +{{define "mark"}}<span equipo-sparkle equipo-mark{{if eq . "s"}} data-size="s"{{end}} aria-hidden="true"><svg viewBox="0 0 16 16" focusable="false"><path d="M8 0C8.6 4.6 11.4 7.4 16 8 11.4 8.6 8.6 11.4 8 16 7.4 11.4 4.6 8.6 0 8 4.6 7.4 7.4 4.6 8 0Z"/><circle cx="8" cy="8" r="1.7"/></svg><i data-sat="1"></i><i data-sat="2"></i><i data-sat="3"></i>{{if ne . "s"}}<i data-mote data-m="1"></i><i data-mote="light" data-m="2"></i><i data-mote data-m="3"></i>{{end}}</span>{{end}} |
| {{define "elapsed"}}<span equipo-clock data-since="{{since .}}">{{elapsed .}}</span>{{end}} |
| -{{define "av"}}<span equipo-av style="--h:{{.Hue}}" title="{{.Address}}" aria-hidden="true">{{.Initials}}</span>{{end}} |
| -{{define "av-l"}}<span equipo-av data-size="l" style="--h:{{.Hue}}" title="{{.Address}}" aria-hidden="true">{{.Initials}}</span>{{end}} |
| +{{define "av"}}<span equipo-av data-h="{{.Hue}}" title="{{.Address}}" aria-hidden="true">{{.Initials}}</span>{{end}} |
| +{{define "av-l"}}<span equipo-av data-size="l" data-h="{{.Hue}}" title="{{.Address}}" aria-hidden="true">{{.Initials}}</span>{{end}} |
| {{define "who"}}<span equipo-who>{{template "av" .}}<span title="{{.Address}}">{{if .You}}{{copy "work.you"}}{{else}}{{.Name}}{{end}}</span></span>{{end}} |
| -{{define "mono"}}<span equipo-mono style="--h:{{.Hue}}" title="{{.Title}}" aria-hidden="true">{{.Letter}}</span>{{end}} |
| -{{define "mono-l"}}<span equipo-mono data-size="l" style="--h:{{.Hue}}" title="{{.Title}}" aria-hidden="true">{{.Letter}}</span>{{end}} |
| -{{define "mono-s"}}<span equipo-mono data-size="s" style="--h:{{.Hue}}" aria-hidden="true">{{.Letter}}</span>{{end}} |
| +{{define "mono"}}<span equipo-mono data-h="{{.Hue}}" title="{{.Title}}" aria-hidden="true">{{.Letter}}</span>{{end}} |
| +{{define "mono-l"}}<span equipo-mono data-size="l" data-h="{{.Hue}}" title="{{.Title}}" aria-hidden="true">{{.Letter}}</span>{{end}} |
| +{{define "mono-s"}}<span equipo-mono data-size="s" data-h="{{.Hue}}" aria-hidden="true">{{.Letter}}</span>{{end}} |
| {{define "track"}}<ol equipo-track aria-hidden="true">{{range .Track}}<li data-s="{{.State}}"{{if .Tone}} data-tone="{{.Tone}}"{{end}}{{if .Live}} data-live{{end}} title="{{.Label}}">{{if .Live}}{{template "mark" "s"}}{{end}}</li>{{end}}</ol>{{end}} |
| {{define "track-full"}}<ol equipo-track-full data-track aria-label="{{.StageLine}}">{{range .Track}}<li data-s="{{.State}}"{{if .Tone}} data-tone="{{.Tone}}"{{end}}{{if .Live}} data-live{{end}}{{if eq .State "current"}} aria-current="step"{{end}}><span equipo-dot>{{if .Live}}{{template "mark" "s"}}{{end}}</span><span>{{.Label}}</span>{{with .At}}<small><time datetime="{{.Format "2006-01-02T15:04:05Z07:00"}}">{{.Format "15:04"}}</time></small>{{end}}</li>{{end}}</ol>{{end}} |
| {{define "badge"}}<span equipo-badge2 data-kind="{{.Kind}}" data-tone="{{.Tone}}" title="{{.Title}}">{{if .Live}}{{template "mark" "s"}}{{else if .Icon}}{{icon .Icon}}{{end}}<span>{{.Text}}</span></span>{{end}} |
diff --git a/internal/equipo/templates/work_projects.html b/internal/equipo/templates/work_projects.html| index 31343ed7..c957ee96 100644 |
| --- a/internal/equipo/templates/work_projects.html |
| +++ b/internal/equipo/templates/work_projects.html |
| @@ -13,5 +13,5 @@ |
| {{with .Description}}<p equipo-desc>{{.}}</p>{{end}} |
| <p equipo-facts>{{template "project-facts" .}}{{if .People}}<span equipo-avs>{{range .People}}{{template "av" .}}{{end}}</span>{{end}}</p> |
| </div> |
| -<div equipo-row-side>{{if .Last}}<span equipo-ago{{agoData .LastAt ""}}>{{.Last}}</span>{{end}}<span equipo-spread><span equipo-bar>{{range .Spread}}<i data-k="{{.Key}}" style="inline-size:{{.Width}}" title="{{.Title}}"></i>{{end}}</span><a href="/tasks?project={{.ID}}" equipo-n>{{if eq .Tasks 1}}{{copy "work.project.one_task"}}{{else}}{{printf (copy "work.project.tasks") .Tasks}}{{end}}</a></span>{{with .Words}}<span equipo-quiet>{{.}}</span>{{end}}</div> |
| +<div equipo-row-side>{{if .Last}}<span equipo-ago{{agoData .LastAt ""}}>{{.Last}}</span>{{end}}<span equipo-spread><span equipo-bar>{{range .Spread}}<i data-k="{{.Key}}" data-w="{{.Width}}" title="{{.Title}}"></i>{{end}}</span><a href="/tasks?project={{.ID}}" equipo-n>{{if eq .Tasks 1}}{{copy "work.project.one_task"}}{{else}}{{printf (copy "work.project.tasks") .Tasks}}{{end}}</a></span>{{with .Words}}<span equipo-quiet>{{.}}</span>{{end}}</div> |
| </li>{{end}} |
diff --git a/internal/equipo/work_views.go b/internal/equipo/work_views.go| index a486aa17..26ae3491 100644 |
| --- a/internal/equipo/work_views.go |
| +++ b/internal/equipo/work_views.go |
| @@ -34,11 +34,12 @@ func personOf(address, viewer string) personLine { |
| } |
| // hueOf is a stable hue for a name, so a person or project keeps its |
| -// colour everywhere. |
| +// colour everywhere: one of 24 steps of 15 degrees, each a class in |
| +// equipo.css ([data-h]), since the page's policy refuses inline styles. |
| func hueOf(s string) int { |
| h := fnv.New32a() |
| h.Write([]byte(s)) |
| - return int(h.Sum32() % 360) |
| + return int(h.Sum32()%24) * 15 |
| } |
| // monoLine is a project's letter monogram with a stable hue, until |
| @@ -847,9 +848,10 @@ func groupTasks(ts []taskLine) []taskGroup { |
| // spreadPart is one colour of a project's task spread. |
| type spreadPart struct { |
| - Key string |
| - N int |
| - Width string |
| + Key string |
| + N int |
| + // Width is the part's share in whole percent ([data-w] in equipo.css). |
| + Width int |
| Title string |
| } |
| @@ -889,7 +891,7 @@ func projectLineOf(p wire.Project, tasks []taskLine, viewer string, now time.Tim |
| } |
| w := fmt.Sprintf(copyText("work.spread."+k), n[k]) |
| words = append(words, w) |
| - line.Spread = append(line.Spread, spreadPart{Key: k, N: n[k], Width: fmt.Sprintf("%.1f%%", float64(n[k])*100/float64(line.Tasks)), Title: w}) |
| + line.Spread = append(line.Spread, spreadPart{Key: k, N: n[k], Width: max(1, int(float64(n[k])*100/float64(line.Tasks)+0.5)), Title: w}) |
| } |
| line.Words = strings.Join(words, ", ") |
| for _, who := range p.People { |
diff --git a/internal/headless/browser_attach_test.go b/internal/headless/browser_attach_test.go| index 1e87779d..f4f39ecd 100644 |
| --- a/internal/headless/browser_attach_test.go |
| +++ b/internal/headless/browser_attach_test.go |
| @@ -15,6 +15,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/browsertest" |
| "github.com/chromedp/cdproto/cdp" |
| "github.com/chromedp/cdproto/emulation" |
| + "github.com/chromedp/cdproto/fetch" |
| "github.com/chromedp/chromedp" |
| ) |
| @@ -251,3 +252,35 @@ func TestBrowserComposer(t *testing.T) { |
| p.stop() |
| } |
| } |
| + |
| +// TestBrowserComposerReconcile: Astra round 1: when the send's POST lands |
| +// before its message event, the message kept this device's provisional |
| +// attachments (a file chip linking to "#"). With the event stream held |
| +// back, the sent message's attachments become the server's at once: the |
| +// image from its preview, the file linking to its download. |
| +func TestBrowserComposerReconcile(t *testing.T) { |
| + _, inst, r := localEnv(t) |
| + r.start(t) |
| + c := inst.Cookie() |
| + dir := t.TempDir() |
| + img := filepath.Join(dir, "screen.png") |
| + notes := filepath.Join(dir, "notes.md") |
| + os.WriteFile(img, attachtest.PNG(120, 80), 0600) |
| + os.WriteFile(notes, []byte("# Notes\n"), 0600) |
| + p := openPage(t, inst.URL, c.Name, c.Value, 1280, 900, true) |
| + defer p.stop() |
| + // Hold every event stream request: none ever reaches the page. |
| + p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| + _, err := cdp.Call(ctx, target, fetch.Enable, fetch.EnableParams{Patterns: []*fetch.RequestPattern{{URLPattern: "*/api/v1/events*"}}}) |
| + return err |
| + })) |
| + p.run(chromedp.Reload(), browsertest.Wait(`!!document.querySelector('#composer[data-enhanced]') && !!window.EquipoAttach`)) |
| + p.run(chromedp.SetUploadFiles(chromedp.CSS(`[data-picker="image"]`), []string{img})) |
| + p.run(chromedp.SetUploadFiles(chromedp.CSS(`[data-picker="file"]`), []string{notes})) |
| + p.run(browsertest.Wait(`document.querySelectorAll('[equipo-chip][data-state="ready"]').length===2`)) |
| + p.check(typeText("held back"), "type") |
| + p.run(chromedp.Click(chromedp.CSS(`[equipo-send]`))) |
| + own := `[...document.querySelectorAll('[equipo-message="own"]')].find(e=>e.textContent.includes('held back'))` |
| + p.run(browsertest.Wait(`(()=>{const li=` + own + `;return !!li&&!!li.dataset.message&&!li.hasAttribute('data-pending')})()`)) |
| + p.check(`(()=>{const li=`+own+`,f=li.querySelector('[equipo-file-chip]'),i=li.querySelector('[equipo-file-thumb] img');return li.querySelectorAll('[equipo-message-files] > a').length===2&&!!f&&/^\/conversation\/attachments\/at_[a-z0-9]+$/.test(new URL(f.href).pathname)&&!!i&&/^\/conversation\/attachments\/at_[a-z0-9]+\/preview$/.test(new URL(i.src).pathname)})()`, "the sent message kept its provisional attachments") |
| +} |
diff --git a/internal/runner/thin/files.go b/internal/runner/thin/files.go| index 9a99d1b1..8584c1d3 100644 |
| --- a/internal/runner/thin/files.go |
| +++ b/internal/runner/thin/files.go |
| @@ -12,7 +12,9 @@ import ( |
| "os" |
| "path/filepath" |
| "regexp" |
| + "sort" |
| "strings" |
| + "sync" |
| "time" |
| "amadan.net/oficina/equipo/internal/attach" |
| @@ -38,15 +40,48 @@ const ( |
| keepFiles = 14 * 24 * time.Hour |
| // keepParts is how long an unfinished one waits for its chunks. |
| keepParts = 2 * 24 * time.Hour |
| + // keepFresh spares a file just delivered: its message frame, and so |
| + // the running turn that protects it, comes after its chunks. |
| + keepFresh = time.Hour |
| ) |
| var attachmentID = regexp.MustCompile(`^at_[a-z0-9]{8,60}$`) |
| -// Files receives attachment chunks for every person. |
| +// Files receives attachment chunks for every person and keeps the |
| +// runner's disk bounded (Sweep). |
| type Files struct { |
| State *State |
| SessionRoot string |
| Logger *slog.Logger |
| + // Quota bounds what delivered attachments may hold; zero is DefaultQuota. |
| + Quota Quota |
| + |
| + mu sync.Mutex |
| + // fault fails a step of finishing a file, in tests of a crash there. |
| + fault func(step string) error |
| +} |
| + |
| +// Quota bounds delivered attachments, per person and on the whole runner. |
| +// Over it the oldest go first; a file a running turn names never goes. |
| +type Quota struct { |
| + PersonBytes, PersonFiles, TotalBytes, TotalFiles int64 |
| +} |
| + |
| +// DefaultQuota: fifty full messages a person, four people's worth in all. |
| +var DefaultQuota = Quota{PersonBytes: 500 << 20, PersonFiles: 1000, TotalBytes: 2 << 30, TotalFiles: 4000} |
| + |
| +func (f *Files) quota() Quota { |
| + if f.Quota == (Quota{}) { |
| + return DefaultQuota |
| + } |
| + return f.Quota |
| +} |
| + |
| +func (f *Files) step(name string) error { |
| + if f.fault != nil { |
| + return f.fault(name) |
| + } |
| + return nil |
| } |
| // valid reports a chunk the runner will write: a known kind and type, a |
| @@ -74,31 +109,47 @@ func validChunk(c wire.AttachmentChunk) bool { |
| return len(c.Data) == want |
| } |
| +// errMismatch is a whole file whose size or SHA-256 is wrong: its bytes |
| +// came wrong and cannot be put right here, so it is discarded. |
| +var errMismatch = errors.New("attachment size or sha256 does not match") |
| + |
| // Accept applies one chunk exactly once. A chunk that is not valid is |
| // dropped (logged, then acked): the turn that names it fails visibly. |
| -// Only an I/O failure returns an error, so the frame is resent. |
| +// Any filesystem failure returns an error, so the frame is not acked and |
| +// comes again, with every chunk written so far kept: finishing restarts |
| +// from where it stopped. |
| func (f *Files) Accept(ctx context.Context, frameID string, c wire.AttachmentChunk) error { |
| if !validChunk(c) { |
| f.log("attachment chunk refused", errors.New(c.ID)) |
| _, err := f.State.SeenResult(ctx, frameID) |
| return err |
| } |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| desk, err := OpenDesk(f.SessionRoot, c.Person) |
| if err != nil { |
| return err |
| } |
| final := filepath.Join(desk.Dir, attachmentsDir, c.ID, c.Name) |
| + incoming := filepath.Join(filepath.Dir(desk.Dir), "incoming") |
| + part, ready := filepath.Join(incoming, c.ID+".part"), filepath.Join(incoming, c.ID+".ready") |
| if info, err := os.Lstat(final); err == nil && info.Mode().IsRegular() && info.Size() == c.Size { |
| + // Delivered already (an ack was lost, or the turn moved): tidy up |
| + // what a crash after delivery may have left, then ack. |
| + if err := f.forget(ctx, c.ID, part, ready); err != nil { |
| + return err |
| + } |
| _, err := f.State.SeenResult(ctx, frameID) |
| return err |
| } |
| - incoming := filepath.Join(filepath.Dir(desk.Dir), "incoming") |
| - if err := os.MkdirAll(incoming, 0700); err != nil { |
| - return err |
| - } |
| - part := filepath.Join(incoming, c.ID+".part") |
| - if err := writeAt(part, int64(c.Index)*attach.ChunkBytes, c.Data); err != nil { |
| - return err |
| + if _, err := os.Lstat(ready); err != nil { |
| + // Not yet whole: write this chunk. |
| + if err := os.MkdirAll(incoming, 0700); err != nil { |
| + return err |
| + } |
| + if err := writeAt(part, int64(c.Index)*attach.ChunkBytes, c.Data); err != nil { |
| + return err |
| + } |
| } |
| have := 0 |
| err = f.State.tx(ctx, func(t *sql.Tx) error { |
| @@ -113,13 +164,34 @@ func (f *Files) Accept(ctx context.Context, frameID string, c wire.AttachmentChu |
| if err != nil || have < c.Count { |
| return err |
| } |
| - if err := finish(part, final, c.Size, c.SHA256); err != nil { |
| - // A file that does not match is discarded; its turn fails. |
| + err = f.finish(part, ready, final, c.Size, c.SHA256) |
| + if errors.Is(err, errMismatch) { |
| + // Discarded: the turn that names it fails; a resend starts afresh. |
| f.log("attachment discarded", err) |
| os.Remove(part) |
| + return f.forget(ctx, c.ID, part, ready) |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + if err := f.forget(ctx, c.ID, part, ready); err != nil { |
| + return err |
| } |
| - _, err = f.State.db.ExecContext(ctx, "DELETE FROM file_chunks WHERE attachment_id=?", c.ID) |
| - f.prune(desk, incoming) |
| + f.sweep(ctx, false) |
| + return nil |
| +} |
| + |
| +// forget drops a finished or discarded file's chunk records and leftovers. |
| +func (f *Files) forget(ctx context.Context, id, part, ready string) error { |
| + if err := f.step("forget"); err != nil { |
| + return err |
| + } |
| + for _, p := range []string{part, ready} { |
| + if err := os.Remove(p); err != nil && !errors.Is(err, fs.ErrNotExist) { |
| + return err |
| + } |
| + } |
| + _, err := f.State.db.ExecContext(ctx, "DELETE FROM file_chunks WHERE attachment_id=?", id) |
| return err |
| } |
| @@ -136,45 +208,189 @@ func writeAt(path string, off int64, data []byte) error { |
| return file.Sync() |
| } |
| -// finish checks the assembled file and moves it into the desk, read-only. |
| -func finish(part, final string, size int64, sum string) error { |
| - in, err := os.Open(part) |
| +// finish checks the assembled file and moves it into the desk, read-only, |
| +// through steps that each survive a crash: the checked file becomes |
| +// <id>.ready by a rename (no more chunks are written once it exists), is |
| +// made read-only, and is renamed into the desk. Replay picks up at |
| +// whichever step was next. Only a wrong size or hash is errMismatch. |
| +func (f *Files) finish(part, ready, final string, size int64, sum string) error { |
| + if _, err := os.Lstat(ready); errors.Is(err, fs.ErrNotExist) { |
| + if err := f.step("verify"); err != nil { |
| + return err |
| + } |
| + if err := check(part, size, sum); err != nil { |
| + return err |
| + } |
| + if err := f.step("ready"); err != nil { |
| + return err |
| + } |
| + if err := os.Rename(part, ready); err != nil { |
| + return err |
| + } |
| + } else if err != nil { |
| + return err |
| + } else if err := check(ready, size, sum); err != nil { |
| + return err |
| + } |
| + if err := f.step("chmod"); err != nil { |
| + return err |
| + } |
| + if err := os.Chmod(ready, 0400); err != nil { |
| + return err |
| + } |
| + if err := f.step("mkdir"); err != nil { |
| + return err |
| + } |
| + if err := os.MkdirAll(filepath.Dir(final), 0700); err != nil { |
| + return err |
| + } |
| + if err := f.step("rename"); err != nil { |
| + return err |
| + } |
| + return os.Rename(ready, final) |
| +} |
| + |
| +// check reads a file whole: errMismatch when its size or hash is wrong, |
| +// any other error when it cannot be read. |
| +func check(path string, size int64, sum string) error { |
| + in, err := os.Open(path) |
| if err != nil { |
| return err |
| } |
| + defer in.Close() |
| h := sha256.New() |
| n, err := io.Copy(h, in) |
| - in.Close() |
| if err != nil { |
| return err |
| } |
| if n != size || hex.EncodeToString(h.Sum(nil)) != sum { |
| - return errors.New("attachment size or sha256 does not match") |
| + return errMismatch |
| } |
| - if err := os.MkdirAll(filepath.Dir(final), 0700); err != nil { |
| - return err |
| - } |
| - if err := os.Chmod(part, 0400); err != nil { |
| - return err |
| + return nil |
| +} |
| + |
| +// Run sweeps every interval until ctx ends: the bounds below, for every |
| +// person, whether or not anything arrives. |
| +func (f *Files) Run(ctx context.Context, every time.Duration) { |
| + t := time.NewTicker(every) |
| + defer t.Stop() |
| + for { |
| + f.Sweep(ctx) |
| + select { |
| + case <-ctx.Done(): |
| + return |
| + case <-t.C: |
| + } |
| } |
| - return os.Rename(part, final) |
| } |
| -// prune removes delivered attachments past keepFiles and unfinished ones |
| -// past keepParts. |
| -func (f *Files) prune(desk *Desk, incoming string) { |
| - cut := time.Now().Add(-keepFiles) |
| - dirs, _ := os.ReadDir(filepath.Join(desk.Dir, attachmentsDir)) |
| - for _, d := range dirs { |
| - if info, err := d.Info(); err == nil && d.IsDir() && attachmentID.MatchString(d.Name()) && info.ModTime().Before(cut) { |
| - removeAll(filepath.Join(desk.Dir, attachmentsDir, d.Name())) |
| +// Sweep keeps the runner's attachments bounded and its records true: |
| +// unfinished files past keepParts go with their chunk records; chunk |
| +// records with no file go; delivered files past keepFiles go; then, over |
| +// the quota for a person or the runner, the oldest delivered files go |
| +// first. A file a running turn names, or one delivered in the last hour, |
| +// is never removed for the quota. |
| +func (f *Files) Sweep(ctx context.Context) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.sweep(ctx, true) |
| +} |
| + |
| +type heldDir struct { |
| + person, path, id string |
| + at time.Time |
| + bytes, files int64 |
| +} |
| + |
| +func (f *Files) sweep(ctx context.Context, records bool) { |
| + if f.SessionRoot == "" { |
| + return |
| + } |
| + protect := f.State.runningAttachments(ctx) |
| + people, _ := os.ReadDir(f.SessionRoot) |
| + var all []heldDir |
| + partial := map[string]bool{} |
| + for _, p := range people { |
| + if !p.IsDir() { |
| + continue |
| + } |
| + base := filepath.Join(f.SessionRoot, p.Name()) |
| + incoming := filepath.Join(base, "incoming") |
| + entries, _ := os.ReadDir(incoming) |
| + for _, e := range entries { |
| + name := e.Name() |
| + id := strings.TrimSuffix(strings.TrimSuffix(name, ".part"), ".ready") |
| + info, err := e.Info() |
| + if err != nil || id == name { |
| + continue |
| + } |
| + if info.ModTime().Before(time.Now().Add(-keepParts)) && !protect[id] { |
| + os.Remove(filepath.Join(incoming, name)) |
| + f.State.db.ExecContext(ctx, "DELETE FROM file_chunks WHERE attachment_id=?", id) |
| + continue |
| + } |
| + partial[id] = true |
| } |
| + root := filepath.Join(base, "desk", attachmentsDir) |
| + dirs, _ := os.ReadDir(root) |
| + for _, d := range dirs { |
| + info, err := d.Info() |
| + if err != nil || !d.IsDir() || !attachmentID.MatchString(d.Name()) { |
| + continue |
| + } |
| + h := heldDir{person: p.Name(), path: filepath.Join(root, d.Name()), id: d.Name(), at: info.ModTime()} |
| + files, _ := os.ReadDir(h.path) |
| + for _, x := range files { |
| + if xi, err := x.Info(); err == nil { |
| + h.bytes += xi.Size() |
| + h.files++ |
| + } |
| + } |
| + if h.at.Before(time.Now().Add(-keepFiles)) && !protect[h.id] { |
| + removeAll(h.path) |
| + continue |
| + } |
| + all = append(all, h) |
| + } |
| + } |
| + if records { |
| + // Chunk records whose file is gone (pruned, or never written). |
| + rows, err := f.State.db.QueryContext(ctx, "SELECT DISTINCT attachment_id FROM file_chunks") |
| + if err == nil { |
| + var gone []string |
| + for rows.Next() { |
| + var id string |
| + if rows.Scan(&id) == nil && !partial[id] { |
| + gone = append(gone, id) |
| + } |
| + } |
| + rows.Close() |
| + for _, id := range gone { |
| + f.State.db.ExecContext(ctx, "DELETE FROM file_chunks WHERE attachment_id=?", id) |
| + } |
| + } |
| + } |
| + // Oldest first, within each person, then over the whole runner. |
| + sort.Slice(all, func(i, j int) bool { return all[i].at.Before(all[j].at) }) |
| + q := f.quota() |
| + byPerson := map[string][2]int64{} |
| + var total [2]int64 |
| + for _, h := range all { |
| + v := byPerson[h.person] |
| + byPerson[h.person] = [2]int64{v[0] + h.bytes, v[1] + h.files} |
| + total[0] += h.bytes |
| + total[1] += h.files |
| } |
| - parts, _ := os.ReadDir(incoming) |
| - for _, p := range parts { |
| - if info, err := p.Info(); err == nil && strings.HasSuffix(p.Name(), ".part") && info.ModTime().Before(time.Now().Add(-keepParts)) { |
| - os.Remove(filepath.Join(incoming, p.Name())) |
| + for _, h := range all { |
| + v := byPerson[h.person] |
| + over := v[0] > q.PersonBytes || v[1] > q.PersonFiles || total[0] > q.TotalBytes || total[1] > q.TotalFiles |
| + if !over || protect[h.id] || h.at.After(time.Now().Add(-keepFresh)) { |
| + continue |
| } |
| + removeAll(h.path) |
| + byPerson[h.person] = [2]int64{v[0] - h.bytes, v[1] - h.files} |
| + total[0] -= h.bytes |
| + total[1] -= h.files |
| } |
| } |
diff --git a/internal/runner/thin/files_test.go b/internal/runner/thin/files_test.go| index 18ad0cb4..2d6f8fc0 100644 |
| --- a/internal/runner/thin/files_test.go |
| +++ b/internal/runner/thin/files_test.go |
| @@ -5,6 +5,7 @@ import ( |
| "crypto/sha256" |
| "encoding/hex" |
| "encoding/json" |
| + "errors" |
| "os" |
| "path/filepath" |
| "strings" |
| @@ -170,3 +171,163 @@ func TestAttachmentIntegrity(t *testing.T) { |
| t.Fatal("a changed file was used") |
| } |
| } |
| + |
| +func filesRig(t *testing.T) (*Files, context.Context) { |
| + t.Helper() |
| + ctx := context.Background() |
| + state, err := OpenState(ctx, t.TempDir()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { state.Close() }) |
| + root := filepath.Join(t.TempDir(), "sessions") |
| + os.MkdirAll(root, 0700) |
| + return &Files{State: state, SessionRoot: root}, ctx |
| +} |
| + |
| +func chunksOf(person, id, name string, data []byte) ([]wire.AttachmentChunk, wire.AttachmentRef) { |
| + sum := sha256.Sum256(data) |
| + ref := wire.AttachmentRef{ID: id, Kind: wire.AttachmentFile, Name: name, MediaType: attach.Text, Size: int64(len(data)), SHA256: hex.EncodeToString(sum[:])} |
| + n := attach.Chunks(ref.Size) |
| + var out []wire.AttachmentChunk |
| + for i := 0; i < n; i++ { |
| + out = append(out, wire.AttachmentChunk{Person: person, AttachmentRef: ref, Index: i, Count: n, Data: data[i*attach.ChunkBytes : min(len(data), (i+1)*attach.ChunkBytes)]}) |
| + } |
| + return out, ref |
| +} |
| + |
| +// Astra round 1: a filesystem failure while finishing deleted the chunks |
| +// and let the frame be acked, so the file could never be rebuilt; a crash |
| +// between chmod and rename left a part replay could not write. At each |
| +// step of finishing, a failure returns an error (the frame is not acked) |
| +// and keeps every chunk; replaying the frame delivers the file whole. |
| +func TestAttachmentFinishCrashes(t *testing.T) { |
| + data := []byte(strings.Repeat("crash at each step\n", 16000)) // 3 chunks |
| + for _, step := range []string{"verify", "ready", "chmod", "mkdir", "rename", "forget"} { |
| + t.Run(step, func(t *testing.T) { |
| + t.Parallel() |
| + f, ctx := filesRig(t) |
| + chunks, ref := chunksOf("p@example.com", "at_crash"+step, "build.log", data) |
| + for i, c := range chunks[:len(chunks)-1] { |
| + if err := f.Accept(ctx, "c"+itoa(int64(i)), c); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + f.fault = func(s string) error { |
| + if s == step { |
| + return errors.New("disk said no at " + s) |
| + } |
| + return nil |
| + } |
| + last := chunks[len(chunks)-1] |
| + if err := f.Accept(ctx, "c-last", last); err == nil { |
| + t.Fatal("a failure while finishing was acked") |
| + } |
| + var rows int |
| + f.State.db.QueryRow("SELECT count(*) FROM file_chunks WHERE attachment_id=?", ref.ID).Scan(&rows) |
| + if step != "forget" && rows != len(chunks) { |
| + t.Fatalf("%d of %d chunk records kept", rows, len(chunks)) |
| + } |
| + f.fault = nil |
| + if err := f.Accept(ctx, "c-last", last); err != nil { |
| + t.Fatalf("replay: %v", err) |
| + } |
| + desk, _ := OpenDesk(f.SessionRoot, "p@example.com") |
| + held, err := heldFiles(desk, []wire.AttachmentRef{ref}) |
| + if err != nil { |
| + t.Fatalf("not delivered after replay: %v", err) |
| + } |
| + if info, _ := os.Stat(held[0].Host); info.Mode().Perm() != 0400 { |
| + t.Fatalf("mode %v", info.Mode()) |
| + } |
| + left, _ := filepath.Glob(filepath.Join(filepath.Dir(desk.Dir), "incoming", "*")) |
| + f.State.db.QueryRow("SELECT count(*) FROM file_chunks").Scan(&rows) |
| + if len(left) != 0 || rows != 0 { |
| + t.Fatalf("left %v and %d records", left, rows) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Astra round 1: retention had no aggregate bound and ran only when a |
| +// file arrived. Sweep removes stale parts with their records, records with |
| +// no file, files past retention, and, over a person's or the runner's |
| +// quota, the oldest delivered files first; never one a running turn names. |
| +func TestAttachmentSweep(t *testing.T) { |
| + f, ctx := filesRig(t) |
| + f.Quota = Quota{PersonBytes: 250, PersonFiles: 100, TotalBytes: 1 << 30, TotalFiles: 4} |
| + deliver := func(person, id string, age time.Duration) wire.AttachmentRef { |
| + t.Helper() |
| + chunks, ref := chunksOf(person, id, "n.txt", []byte(strings.Repeat("x", 100))) |
| + if err := f.Accept(ctx, "f-"+id, chunks[0]); err != nil { |
| + t.Fatal(err) |
| + } |
| + desk, _ := OpenDesk(f.SessionRoot, person) |
| + at := time.Now().Add(-age) |
| + if err := os.Chtimes(filepath.Join(desk.Dir, attachmentsDir, id), at, at); err != nil { |
| + t.Fatal(err) |
| + } |
| + return ref |
| + } |
| + exists := func(person, id string) bool { |
| + desk, _ := OpenDesk(f.SessionRoot, person) |
| + _, err := os.Stat(filepath.Join(desk.Dir, attachmentsDir, id)) |
| + return err == nil |
| + } |
| + const a, b = "a@example.com", "b@example.com" |
| + // a1, the oldest, is named by a running turn; so is b1, past retention. |
| + ref := func(id string) wire.AttachmentRef { |
| + _, r := chunksOf("", id, "n.txt", []byte(strings.Repeat("x", 100))) |
| + return r |
| + } |
| + if err := f.State.Accept(ctx, "m1", wire.MessageCommand{Person: a, TurnID: "t_1", Attempt: 1, Text: "x", PersonText: []string{"x"}, Tail: []wire.TailMessage{}, Attachments: []wire.AttachmentRef{ref("at_a1aaaaaaaa"), ref("at_b1bbbbbbbb")}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + deliver(a, "at_a1aaaaaaaa", 5*time.Hour) |
| + deliver(a, "at_a2aaaaaaaa", 4*time.Hour) |
| + deliver(a, "at_a3aaaaaaaa", 3*time.Hour) |
| + deliver(a, "at_a4aaaaaaaa", 2*time.Hour) |
| + deliver(b, "at_b1bbbbbbbb", 15*24*time.Hour) |
| + deliver(b, "at_b2bbbbbbbb", 6*time.Hour) |
| + deliver(b, "at_b3bbbbbbbb", 30*time.Minute) |
| + // A stale part with its records, and records with no file at all. |
| + desk, _ := OpenDesk(f.SessionRoot, b) |
| + incoming := filepath.Join(filepath.Dir(desk.Dir), "incoming") |
| + os.MkdirAll(incoming, 0700) |
| + stale := filepath.Join(incoming, "at_stale0000.part") |
| + os.WriteFile(stale, []byte("half"), 0600) |
| + then := time.Now().Add(-3 * 24 * time.Hour) |
| + os.Chtimes(stale, then, then) |
| + fresh := filepath.Join(incoming, "at_fresh0000.part") |
| + os.WriteFile(fresh, []byte("half"), 0600) |
| + for _, id := range []string{"at_stale0000", "at_orphan000", "at_fresh0000"} { |
| + f.State.db.Exec("INSERT INTO file_chunks(attachment_id, idx) VALUES(?,0)", id) |
| + } |
| + f.Sweep(ctx) |
| + // Person a: 400 bytes over 250; a1 is protected, so a2 and a3 go. |
| + for id, want := range map[string]bool{"at_a1aaaaaaaa": true, "at_a2aaaaaaaa": false, "at_a3aaaaaaaa": false, "at_a4aaaaaaaa": true} { |
| + if exists(a, id) != want { |
| + t.Fatalf("%s kept=%v, want %v", id, !want, want) |
| + } |
| + } |
| + // The runner: at most 4 files; b1 is protected though past retention. |
| + for id, want := range map[string]bool{"at_b1bbbbbbbb": true, "at_b2bbbbbbbb": false, "at_b3bbbbbbbb": true} { |
| + if exists(b, id) != want { |
| + t.Fatalf("%s kept=%v, want %v", id, !want, want) |
| + } |
| + } |
| + if _, err := os.Stat(stale); !os.IsNotExist(err) { |
| + t.Fatal("a stale part stayed") |
| + } |
| + var ids []string |
| + rows, _ := f.State.db.Query("SELECT attachment_id FROM file_chunks ORDER BY 1") |
| + for rows.Next() { |
| + var id string |
| + rows.Scan(&id) |
| + ids = append(ids, id) |
| + } |
| + rows.Close() |
| + if strings.Join(ids, ",") != "at_fresh0000" { |
| + t.Fatalf("chunk records left %v, want only the fresh part's", ids) |
| + } |
| +} |
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go| index b085e430..8fce75ad 100644 |
| --- a/internal/runner/thin/run.go |
| +++ b/internal/runner/thin/run.go |
| @@ -120,6 +120,8 @@ func Run(ctx context.Context, c runner.Config, o Options) error { |
| defer cancel() |
| link := &Link{Origin: c.Origin, Token: creds.Bearer.Token, State: state, Logger: o.Logger, Connected: o.Connected} |
| link.Files = &Files{State: state, SessionRoot: o.Claude.SessionRoot, Logger: o.Logger} |
| + // Attachments stay bounded whether or not anything arrives. |
| + go link.Files.Run(ctx, 10*time.Minute) |
| fg := o.Forge |
| if fg == nil { |
| fg = NewFileForge(c.AmadanCredentialPath, c.StateDir, !o.NoCreate) |
diff --git a/internal/runner/thin/state.go b/internal/runner/thin/state.go| index 323f4776..124b121f 100644 |
| --- a/internal/runner/thin/state.go |
| +++ b/internal/runner/thin/state.go |
| @@ -594,3 +594,24 @@ func (s *State) saveSession(ctx context.Context, person, provider, account, id, |
| _, err := s.db.ExecContext(ctx, "INSERT INTO sessions(person, provider, account, session_id, last_turn, updated_at) VALUES(?,?,?,?,?,?) ON CONFLICT(person, provider) DO UPDATE SET account=excluded.account, session_id=excluded.session_id, last_turn=excluded.last_turn, updated_at=excluded.updated_at", person, provider, account, id, turn, now()) |
| return err |
| } |
| + |
| +// runningAttachments are the attachment ids the person's running turns |
| +// name: files the sweep must keep. |
| +func (s *State) runningAttachments(ctx context.Context) map[string]bool { |
| + out := map[string]bool{} |
| + rows, err := s.db.QueryContext(ctx, "SELECT attachments FROM runs WHERE state=?", runRunning) |
| + if err != nil { |
| + return out |
| + } |
| + defer rows.Close() |
| + for rows.Next() { |
| + var raw string |
| + var refs []wire.AttachmentRef |
| + if rows.Scan(&raw) == nil && json.Unmarshal([]byte(raw), &refs) == nil { |
| + for _, r := range refs { |
| + out[r.ID] = true |
| + } |
| + } |
| + } |
| + return out |
| +} |
diff --git a/internal/thintest/attachments_contract_test.go b/internal/thintest/attachments_contract_test.go| index cc8b5fa5..8bc6ede1 100644 |
| --- a/internal/thintest/attachments_contract_test.go |
| +++ b/internal/thintest/attachments_contract_test.go |
| @@ -70,6 +70,21 @@ func TestContractAttachments(t *testing.T) { |
| if err != nil || file.Name != "notes.md" || file.MediaType != attach.Markdown || file.Kind != wire.AttachmentFile { |
| t.Fatalf("file upload %+v %v", file, err) |
| } |
| + // Astra round 1: every file that is not an image downloads, never |
| + // shows inline (text accepted as plain text may be HTML). |
| + for name, body := range map[string][]byte{"page.html": []byte("<html><script>alert(1)</script></html>"), "notes2.md": []byte("# hi")} { |
| + a, err := r.client.Upload(r.ctx, name, "text/html", body) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + _, h, err := r.client.Attachment(r.ctx, a.ID, false) |
| + if err != nil || !strings.HasPrefix(h.Get("Content-Disposition"), "attachment;") || !strings.HasPrefix(h.Get("Content-Type"), "text/plain") && !strings.HasPrefix(h.Get("Content-Type"), "text/markdown") { |
| + t.Fatalf("%s served as %q %q", name, h.Get("Content-Disposition"), h.Get("Content-Type")) |
| + } |
| + } |
| + if _, h, _ := r.client.Attachment(r.ctx, img.ID, false); !strings.HasPrefix(h.Get("Content-Disposition"), "inline;") { |
| + t.Fatalf("an image no longer shows inline: %q", h.Get("Content-Disposition")) |
| + } |
| // Limits, refused in words by code. |
| _, err = r.client.Upload(r.ctx, "IMG_0002.HEIC", "image/heic", []byte("\x00\x00\x00\x18ftypheic\x00\x00\x00\x00mif1heic")) |
| @@ -83,6 +98,10 @@ func TestContractAttachments(t *testing.T) { |
| if status, code := errCode(err); status != http.StatusRequestEntityTooLarge || code != "attachment_too_large" { |
| t.Fatalf("too large %d %s", status, code) |
| } |
| + _, err = r.client.Upload(r.ctx, "huge.png", "image/png", attachtest.PNGHeader(100000, 100000)) |
| + if status, code := errCode(err); status != http.StatusRequestEntityTooLarge || code != "attachment_pixels" { |
| + t.Fatalf("a 100,000 px square %d %s", status, code) |
| + } |
| _, err = r.client.Upload(r.ctx, "tool.exe", "application/octet-stream", []byte{0x4d, 0x5a, 0, 1, 2}) |
| if status, code := errCode(err); status != http.StatusUnsupportedMediaType || code != "attachment_type" { |
| t.Fatalf("binary %d %s", status, code) |
diff --git a/internal/thintest/inline_style_test.go b/internal/thintest/inline_style_test.go| new file mode 100644 |
| index 00000000..fb81552b |
| --- /dev/null |
| +++ b/internal/thintest/inline_style_test.go |
| @@ -0,0 +1,38 @@ |
| +package thintest |
| + |
| +import ( |
| + "regexp" |
| + "testing" |
| +) |
| + |
| +// inlineStyle is a style attribute in markup, which production's policy |
| +// refuses (style-src has no 'unsafe-inline'); the page then draws without |
| +// it (Paul's staging: avatar hues, meter widths, the mark's motes). |
| +var inlineStyle = regexp.MustCompile(`<[^>]*\sstyle=`) |
| + |
| +// TestPagesNoInlineStyle: no screen of the gallery renders an inline style |
| +// attribute: colours and widths come from classes and data attributes. |
| +func TestPagesNoInlineStyle(t *testing.T) { |
| + g := newGallery(t) |
| + a := g.a |
| + owner := a.inst.Cookie() |
| + paths := []string{"/conversation", "/tasks", "/projects", "/needs-you", "/housekeeping", "/conversation/settings", "/settings/thinking", "/conversation/connections", "/conversation/notebook", "/work"} |
| + for _, id := range []string{g.unchecked, g.stopped, g.noras, g.merging, g.running, g.looking} { |
| + if id != "" { |
| + paths = append(paths, "/tasks/"+id) |
| + } |
| + } |
| + projects, err := a.client.Projects(a.ctx) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, p := range projects.Items { |
| + paths = append(paths, "/projects/"+p.ID) |
| + } |
| + for _, path := range paths { |
| + page := a.get(owner, path, 200) |
| + if m := inlineStyle.FindAllString(page, 3); len(m) > 0 { |
| + t.Errorf("%s renders inline styles: %q", path, m) |
| + } |
| + } |
| +} |
diff --git a/internal/thintest/inner_browser_test.go b/internal/thintest/inner_browser_test.go| index a58d5ca9..a49adb0a 100644 |
| --- a/internal/thintest/inner_browser_test.go |
| +++ b/internal/thintest/inner_browser_test.go |
| @@ -265,6 +265,11 @@ func TestBrowserInnerScreens(t *testing.T) { |
| } |
| } |
| + // Under production's policy (no inline styles): avatars and |
| + // monograms carry their hue and the spread bars their widths. |
| + p.open("/projects") |
| + p.check(`(()=>{const h=e=>getComputedStyle(e).getPropertyValue('--h').trim();const av=document.querySelector('[equipo-av]'),mono=document.querySelector('[equipo-mono]'),bar=document.querySelector('[equipo-bar] i');return !!av&&h(av)!==''&&!!mono&&h(mono)!==''&&!!bar&&bar.getBoundingClientRect().width>0&&!document.querySelector('[style]')})()`, "a hue or a bar width is missing under the policy") |
| + |
| // Timeline entries: one plain line each, the rest behind Details, |
| // closed by default; Details opens by keyboard and by click. |
| p.open("/tasks/" + g.unchecked) |