Merge origin/main (5105b89) into abilities-phase1
12 files changed,
+2,640
−60
.rastrillo/budgets.txt+2 −0docs/api/base-native-v1.md+75 −3docs/superpowers/plans/2026-11-28-native-slice2-part1.md+722 −0docs/superpowers/specs/2026-11-23-base-native-design.md+704 −2internal/web/api_team.go+232 −0internal/web/app.go+5 −0internal/web/main_test.go+5 −1internal/web/people.go+105 −41internal/web/store.go+39 −12internal/web/team_internal_test.go+235 −0internal/webtest/api_team_test.go+508 −0internal/webtest/oficina_harness_test.go+8 −1
CI passed — run details
CI log
=== build === CGO_ENABLED=0 go build ./... === vet === go vet ./... === fmt-check === === staticcheck === go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./... === govulncheck === go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 ./... No vulnerabilities found. === gitleaks === [90m11:01AM[0m [32mINF[0m [1mUnknown SCM platform. Use --platform to include links in findings.[0m [36mhost=[0mamadan.net [90m11:01AM[0m [32mINF[0m [1m1 commits scanned.[0m [90m11:01AM[0m [32mINF[0m [1mscanned ~2935619 bytes (2.94 MB) in 279ms[0m [90m11:01AM[0m [32mINF[0m [1mno leaks found[0m === budget === go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget size budget size: 22 directories within budget === script-test === scripts/prepare-apps_test.sh ok releases lookup failure stops before ship ok app owned elsewhere stops the script ok apps listing failure stops before create ok ambiguous release dir is refused ok explicit version resolves the ambiguity ok releases match is exact, not substring ok shipped version is only promoted, existing app not created ok fresh account creates, ships, promotes to edge, enables ok failing promote stops the script ok ship is retried while uploads are rate limited all passed hack/fonts_test.sh fonts_test: ok === test === go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -count=1 ./... receipt: test step 9.787s against a 60s target (the gate's other steps are not in this figure) receipt: 16 packages ran, 0 cached, 6 without tests, 0 failed receipt: slow package 8.79s amadan.net/oficina/base/internal/webtest receipt: slow package 739ms amadan.net/oficina/base/internal/issuer receipt: slow package 675ms amadan.net/oficina/base/internal/equipo receipt: slow package 592ms amadan.net/oficina/base/internal/operations receipt: slow package 225ms amadan.net/oficina/base/internal/web receipt: slow test 1.52s amadan.net/oficina/base/internal/webtest TestHomeDoesNotWaitOnAStalledSnapshot receipt: slow test 1.09s amadan.net/oficina/base/internal/webtest TestAskZoneIsToldOnce receipt: slow test 610ms amadan.net/oficina/base/internal/webtest TestAskUploadStalledBodyFreesItsSlot receipt: slow test 510ms amadan.net/oficina/base/internal/operations TestOperationsRefusals receipt: slow test 510ms amadan.net/oficina/base/internal/equipo TestUploadRefusals === native === strings: copy review's strings.json is not here (git-ignored); its comparison skipped strings: 121 in the catalog, 118 used worktree-lib_test: ok
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| new file mode 100644 |
| index 0000000..0eca99e |
| --- /dev/null |
| +++ b/.rastrillo/budgets.txt |
| @@ -0,0 +1,2 @@ |
| +time internal/webtest 20s end-to-end web tests drive real servers, uploads and Equipo fakes; 8-13s on the hub since attachments |
| +size internal/webtest - 8500 test lines past 8000 with the Store and People JSON; the split by feature is owed, see discussion 8 |
diff --git a/docs/api/base-native-v1.md b/docs/api/base-native-v1.md| index 06e9d03..3dc572f 100644 |
| --- a/docs/api/base-native-v1.md |
| +++ b/docs/api/base-native-v1.md |
| @@ -2,9 +2,9 @@ |
| What Base's Mac and iPhone app may rely on. Everything here is pinned by |
| tests in `internal/webtest` (`native_test.go`, `api_test.go`, |
| -`ask_native_contract_test.go`, `ask_oficina_native_test.go`). The Ask |
| -routes are the same ones the web's `ask.js` uses, so a change that breaks |
| -this document breaks the web too. |
| +`api_team_test.go`, `ask_native_contract_test.go`, |
| +`ask_oficina_native_test.go`). The Ask routes are the same ones the web's |
| +`ask.js` uses, so a change that breaks this document breaks the web too. |
| ## Signing in |
| @@ -81,6 +81,78 @@ this document breaks the web too. |
| `currentColor`. Own pages' `url`s are Base's web pages. |
| - Optional keys are absent, never `null` or `""`. |
| +## Store and People |
| + |
| +What the Store and People pages show, from the same builders, behind the |
| +same member gate: any member's session, the native one or the web's |
| +cookie. Every answer is JSON and `no-store`. A refusal is |
| +`{"code": "…"}`. Without a session, or for someone who is no longer a |
| +member, every route answers `401 {"code":"unauthenticated"}`, as above. |
| +An app that hears `404` from a read is talking to an older Base, and opens |
| +the web page instead. |
| + |
| +### `GET /api/v1/store` |
| + |
| +```json |
| +{ |
| + "owner": true, |
| + "rows": [ |
| + {"id": "welcome", "name": "Welcome", "summary": "…", "tint": "amber", "icon_svg": "<svg …>", "state": "installed", "error": ""}, |
| + {"id": "scratchpad", "name": "Scratchpad", "summary": "…", "tint": "rose", "icon_svg": "<svg …>", "state": "installing", "error": ""}, |
| + {"id": "contra", "name": "Contra", "summary": "…", "tint": "teal", "icon_svg": "<svg …>", "state": "failed", "error": "The app did not start answering"} |
| + ] |
| +} |
| +``` |
| + |
| +- `rows` is the whole catalogue, in its order. `state` is `""` (not |
| + installed), `installing`, `installed` or `failed`. `error` is a failed |
| + install's reason, and may be `""` (show "The install didn't finish."). |
| +- `owner` is whether this member may install and uninstall. Every member |
| + sees the same rows. |
| +- `icon_svg` is line art drawn in `currentColor` on `tint`, as in |
| + `/api/v1/home`. |
| +- `503 {"code":"unavailable"}`: Base couldn't read its installs. |
| + |
| +### `GET /api/v1/people` |
| + |
| +```json |
| +{ |
| + "owner": true, |
| + "people": [ |
| + {"id": "…", "initial": "O", "name": "", "email": "owner@acme.test", "role": "owner"}, |
| + {"id": "…", "initial": "A", "name": "Ana Ruiz", "email": "ana@acme.test", "role": "member"}, |
| + {"id": "…", "initial": "B", "name": "", "email": "bob@acme.test", "role": "invited"} |
| + ] |
| +} |
| +``` |
| + |
| +- `people` is everyone here, in the order they were invited, as the page |
| + lists them. |
| +- `role` is `owner`, `member`, or `invited` (hasn't signed in yet). |
| +- `name` is `""` for someone who has given none: show `email` then. |
| + `initial` is the first letter of the name, or else of the address. |
| +- `owner` is whether this member may invite. |
| +- `503 {"code":"unavailable"}`: Base couldn't read its members. |
| +- Nothing removes a member: `DELETE /api/v1/people/{id}` isn't a route. |
| + |
| +### The writes |
| + |
| +The owner's alone. They are POSTs, inside Base's CSRF check, which the |
| +kit's `Origin` passes. Install and uninstall take no body (one is |
| +ignored); an invite takes JSON. |
| + |
| +| Route | Answers | |
| +|---|---| |
| +| `POST /api/v1/store/{app}/install` | `202 {"store": …}` with the app installing: poll `GET /api/v1/store` every 2 s while any row is. An app already installing answers `202`, and one already installed `200`, and neither starts anything. A failed row may be installed again (the page's "Try again"). If the install couldn't be started, the store is read again: a row that now shows installing (another request started it) answers `202` as it stands; anything else is `503 unavailable`, and nothing was started. A row that still reads failed then shows an earlier failure, not this attempt. | |
| +| `POST /api/v1/store/{app}/uninstall` | `200 {"store": …}`, also when it was uninstalled already. `409 {"code":"busy"}` while it is still installing ("This app is still installing. Try again in a moment."). `503 unavailable`. | |
| +| `POST /api/v1/people` | Body `{"email": "…"}`, trimmed and lowercased. `200 {"person": …}`, a person as in `GET /api/v1/people`: invited now, or already here (nothing is sent then). `422 {"code":"bad_email"}`: not one plain address. `502 {"code":"mail_failed"}`: they are invited but the email wasn't delivered; invite them again to send it. `415 {"code":"json_only"}` for a body that isn't `application/json`, `413 {"code":"too_large"}` over 4 KiB, `400 {"code":"bad_request"}` for JSON that doesn't parse. `503 unavailable`. | |
| + |
| +Every write also answers `403 {"code":"owner_only"}` to a member who isn't |
| +the owner, before anything else, and the Store's `404 |
| +{"code":"unknown_app"}` for an app the catalogue doesn't have. A POST with |
| +no `Origin` (or another site's) is `403` in plain text, from the CSRF |
| +check. |
| + |
| ## Ask Base |
| No Ask route answers `401` while Base's session is good: Equipo refusing |
diff --git a/docs/superpowers/plans/2026-11-28-native-slice2-part1.md b/docs/superpowers/plans/2026-11-28-native-slice2-part1.md| new file mode 100644 |
| index 0000000..42566d9 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-28-native-slice2-part1.md |
| @@ -0,0 +1,722 @@ |
| +# Base on the Mac and iPhone, slice 2 part 1: Implementation Plan |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task by task. Steps use checkbox (`- [ ]`) syntax for tracking. Every task is tests first: write the failing test, see it fail, make it pass, then run the task's gate. |
| + |
| +**Revision 3** (2026-11-28). Revision 2 answered Fable's plan review |
| +(`.superpowers/sdd/2026-11-28-native-slice2/plan-review.md`): B1, S1 to |
| +S13, and the nits taken. Fable approved it, and revision 3 folds in the |
| +re-review's R1 to R3 and its six nits. "Review" at the end maps each |
| +finding to where it is answered. |
| + |
| +**Goal:** In the Mac and iPhone apps, a person opens Store and People |
| +natively instead of on the web, and folds the Apps section away (remembered |
| +for them on that device). They also attach files in Ask: |
| +- the paperclip or `+`, with Photos, Camera, Files and Paste; |
| +- paste and drop; |
| +- HEIC to JPEG on the device; |
| +- chips, files in the sent bubble, and Quick Look. |
| + |
| +**Spec:** `docs/superpowers/specs/2026-11-23-base-native-design.md` §7, approved by Paul on 2026-11-28 with every recommendation. |
| +- Part 1 is 7.4, 7.5 (Apps folding only) and 7.6. |
| +- The files design (`2026-11-26-ask-attachments-design.md`) binds too: R1, R3, R5, D1 to D8. |
| +- The mockups are `.superpowers/mockups/native-s2/` (git-ignored; `python3 build.py`), sections 3 and 4. |
| + |
| +**Not in part 1:** notifications (part 2), decisions on the cards (part 3), "Made with Base" and opening documents (part 4). |
| + |
| +**Architecture:** |
| +- **Base's server** gains five JSON routes beside the Store and People pages, using the same builders and owner checks behind the member gate. They land and deploy first, on their own branch: they add no words, so they don't wait for copy review. The files routes are already live (`07ec2ec`, `docs/api/base-native-v1.md` "Files"). |
| +- **rastrillo/native** gains `NativeHTTP.upload`. Uploads need `Content-Disposition`, upload progress and their own timeout, and the kit has none of these: `responseDetails` takes a path, method, body and content type only (`bb989a7`). The change goes on its own kit branch with its own review. Base then repins and forwards `upload` through `SwappableTransport`, the transport its client actually uses (`BaseSession.swift:286-305`). |
| +- **The app (BaseKit)** gains: |
| + - Store and People models and screens, shared by both platforms; |
| + - the Apps fold; |
| + - `BaseKit/Attachments/`, copied from Equipo (R5) and then adapted to Base's relay and rules. |
| + |
| +**Tech stack:** as slice 1. |
| +- **Server:** Go (`GOTOOLCHAIN=go1.26.11`, `CGO_ENABLED=0`), chi, rastrillo. |
| +- **Native:** Swift 6.2 / SwiftUI on macOS 26 and iOS 26, RastrilloApple, `PhotosUI`, `QuickLook` / `QuickLookUI`, `ImageIO`, `UniformTypeIdentifiers`. |
| + |
| +**Repositories and branches:** |
| + |
| +| Repo | Tasks | Branch | Lands | |
| +|---|---|---|---| |
| +| **Base** | 1 to 4 | `api/store-people` from `origin/main` | First. Deployed in Task 4, before any app change | |
| +| **rastrillo/native** | 5 | `upload` from `origin/main` | After its own Fable review | |
| +| **Base** | 6 to 21 | `native/slice2-part1` from `origin/main`, once `design/native-slice2` (this plan) and `api/store-people` have landed | After the review (Task 21) and Luna's copy review (Task 22) | |
| +| Controller | 22 | copy review (Luna, from 2026-12-02), land, release | | |
| + |
| +Part C starts with Spike M, and includes Task 16A only if the spike says |
| +so: 22 numbered tasks, one spike, and one conditional task. |
| + |
| +**Equipo** needs no change. The code it lends is copied from origin/main `8bd40ed1`. Its attachment files are unchanged at `57f370c5` (Fable). |
| + |
| +## Machine hygiene (every task) |
| + |
| +- **One heavy job at a time.** Before any `swift test`, `swift build`, `build-iphone.sh`, `snapshots.sh`, `check-native.sh` or Go test run, check: |
| + ``` |
| + sysctl -n vm.loadavg; pgrep -fl 'xcodebuild|swift-(build|test)|xctest|go (test|build|vet)' |
| + ``` |
| + Wait while the 1-minute load is over 20, or while two or more heavy jobs from other sessions are running. |
| +- **Cap the job's parallelism:** `go test -p 4`, `swift test -j 4`, `swift build -j 4`. Task 6 makes `check-native.sh` pass `-j 4` too. |
| +- **Give every heavy command a timeout in minutes.** |
| +- **Never run the whole Go suite or `make ci` locally.** |
| +- **Simulators:** reuse the "Rastrillo Snapshots" simulator that `snapshots.sh` uses. Never create one. |
| + |
| +## Gates |
| + |
| +| Gate | Command | When | |
| +|---|---|---| |
| +| **Go, narrow** | `GOTOOLCHAIN=go1.26.11 go test -p 4 -count=1 ./internal/web ./internal/webtest -run '<tests>'` (timeout 10 min) | Tasks 1 to 3 | |
| +| **Swift, narrow** | `swift test --package-path native/apple -j 4 --filter '<suites>'` (timeout 15 min). It compiles the package for macOS only | Every native task, while iterating and at its end | |
| +| **iPhone compile** | `native/scripts/build-iphone.sh simulator` (timeout 20 min) | Tasks that touch `#if os(iOS)` code: 10, 11, 14, 18, 19 | |
| +| **Native gate** | `native/scripts/check-native.sh` (timeout 40 min): the catalog, every BaseKit test, BaseMac, and the iPhone Simulator build | **Twice only:** after Task 12 (the big copy), and in Task 21 before asking for the merge | |
| +| **Screenshots** | `native/scripts/snapshots.sh compare mac`, then `iphone` (timeout 20 min each) | Tasks that change a picture: 9, 10, 11, 16A (if taken), 17, 18, 19, and once in Task 21. Use `record` only for pictures the task means to change, and review the contact sheets beside the mockups before committing them | |
| +| **Hub CI** | push, then `AMADAN_HOME=$HOME/.amadan-claude-agent amadan ci status oficina/base -branch <branch> -json` | After each push | |
| + |
| +**What hub CI proves (checked 2026-11-28 on `382e86c`).** |
| +- It runs `make ci`: build, vet, fmt, staticcheck, govulncheck, gitleaks, budget, script tests, and the whole Go suite. |
| +- Its native step is `check-native.sh --core-only`. Its log shows only "strings: … in the catalog" and "worktree-lib_test: ok". |
| +- So it checks the string catalog and nothing else native. **No Swift is compiled or tested on the hub.** |
| +- A green hub verdict proves the Go and the catalog. Swift is proven only by the local gates above, and each task's commit says which ran. |
| + |
| +## Plan decisions |
| + |
| +- **P1. Five JSON routes, from the pages' own builders** (spec 7.4, as amended). |
| + - The routes: |
| + - `GET /api/v1/store` |
| + - `POST /api/v1/store/{app}/install` |
| + - `POST /api/v1/store/{app}/uninstall` |
| + - `GET /api/v1/people` |
| + - `POST /api/v1/people` |
| + - **Shared builders.** Task 1 moves the reading into `storeContent` and `peopleContent`, and the invite into `invitePerson`. |
| + - **Writes** take JSON or no body. They need a member's session (the native one or the web cookie: the same gate) and pass Base's CSRF check, which the kit's `Origin` satisfies. |
| +- **P2. Answers.** Every answer is `Cache-Control: no-store`. |
| + |
| + | Route | Answers | |
| + |---|---| |
| + | `GET /api/v1/store` | `200 {owner, rows}`; `503 {"code":"unavailable"}` when the installs can't be read | |
| + | `POST …/install` | `202 {"store"}` with the app installing. An app already installing answers `202` and one already installed answers `200`; neither calls `Start`. When `Start` fails, the store is read again: if the row now shows installing (another request claimed it), `202` as it stands; otherwise `503 unavailable`, and nothing was claimed. `Start` fails only before its claim, so a row reading failed then is an earlier failure (Fable's code review, should-fix 1). Also `403 owner_only`, `404 unknown_app` | |
| + | `POST …/uninstall` | `200 {"store"}`, also when already uninstalled; `409 {"code":"busy"}`; `403`; `404`; `503` | |
| + | `GET /api/v1/people` | `200 {owner, people: [{id, initial, name, email, role}]}`. `role` is `owner`, `member` or `invited`, so there's no `joined`. `503` when members can't be read | |
| + | `POST /api/v1/people` | `200 {"person"}`: the person invited, or already here. Also `422 {"code":"bad_email"}`; `502 {"code":"mail_failed"}` (invite again to retry); `403 owner_only`; `415` for a non-JSON body; `503` | |
| + |
| +- **P3. The app falls back to the web for an older server.** If a Store or People read answers `404`, the sidebar row opens the web page, as slice 1 does. With the server deployed first (Task 4) this is only a guard. |
| +- **P4. Store polling.** |
| + - It polls every 2 s while a row is installing and the screen is showing. |
| + - It stops when nothing is installing, or when the screen goes away. |
| + - On an error it backs off: 2, 4, 8, then every 15 s. |
| + - On `401` it stops, and the session handles it. |
| +- **P5. Folding is local.** |
| + - `SidebarFolds` keys the Apps state in `UserDefaults.standard` on `base.fold.apps.<accountKey>`. |
| + - `accountKey` is `sha256(origin + "\n" + account id)`, first 16 bytes, hex. The account id is the one the session holds (`BaseSession.account`), so the state is right before `/api/v1/me` loads, and offline. |
| + - It starts open, and is never synced. |
| +- **P6. The kit's upload** (Task 5): |
| + ```swift |
| + func upload(_ path: String, body: Data, contentType: String, filename: String, |
| + maxBytes: Int, progress: @escaping @Sendable (Double) -> Void) async throws -> NativeResponse |
| + ``` |
| + - It is a `NativeTransport` requirement with **no default** (B1). A conformer that doesn't forward it fails to compile. |
| + - It sends `Content-Length`; Base answers `411` without it. |
| + - It sends `Content-Disposition: attachment; filename*=UTF-8''<percent-encoded>`, as Equipo does (`EquipoKit/API/Attachments.swift:21-22`). |
| + - It sets `URLRequest.timeoutInterval = 90` on the upload only. The session's 30 s default stays for everything else. Base waits up to 10 s for a slot and 60 s for Equipo (S2). |
| + - Progress comes from `didSendBodyData`, and only grows. |
| + - `maxBytes` bounds the response body. |
| + - It returns any status, with headers. `401` handling is the caller's (S1). |
| +- **P7. What's copied from Equipo, file by file** (from origin/main `8bd40ed1`; each copy starts with a line naming its source path and SHA): |
| + |
| + | Equipo file | Base file | How | |
| + |---|---|---| |
| + | `native/share/Sources/EquipoShareCore/AttachmentFile.swift` | `Attachments/AttachmentFile.swift` | copied, then gains `convertedFrom` (the "from HEIC" line) and a size check before reading (Tasks 14, 16) | |
| + | `native/share/Sources/EquipoShareCore/FileAttachment.swift` | `Attachments/FileAttachment.swift` | as it is | |
| + | `EquipoKit/Attachments/AttachmentDraft.swift` | `Attachments/AttachmentDraft.swift` | copied, then Base's rules (Tasks 14, 15) | |
| + | `EquipoKit/Attachments/AttachmentViews.swift` | `Attachments/AttachmentViews.swift` | copied. Its full-size preview is deleted in Task 19, where Quick Look replaces it | |
| + | `EquipoKit/Attachments/PhoneAttachmentPicker.swift` | `Attachments/PhoneAttachmentPicker.swift` | copied without the screenshot rows (`RecentScreenshot` isn't copied) | |
| + | `EquipoMac/AttachmentPromises.swift` | `Attachments/AttachmentPromises.swift` | as it is | |
| + | `EquipoMac/MacComposer.swift` (only `accepts(_:)` and the pasteboard reading `onAttachments` does) | `Attachments/MacPasteboard.swift` | the reading only. `ComposerEditor`, the `NSTextView` subclass, isn't copied; Task 17 says why | |
| + | `EquipoKit/Attachments/AttachmentsFixture.swift`, `EquipoMac/MacAttachmentsFixture.swift` | `Tests/BaseSnapshots/AttachmentFixtures.swift` | adapted: draft items and sent messages with images generated in code, no session, no network | |
| + | Tests: `AttachmentTests`, `AttachmentReviewTests`, `MacAttachmentTests` | `Tests/BaseKitTests/` | copied | |
| + |
| + - **Not copied on purpose:** |
| + - `AttachmentFollowupTests` and `AttachmentHTTPTests`, which test Equipo's own transport; |
| + - `RecentScreenshot.swift`, which needs Photos permission (spec 7.6); |
| + - `ShareFixture.swift` and the share extension. |
| + - Equipo's `Fixtures/attachments/large.webp` is copied. Larger fixtures are generated in tests, never committed. |
| +- **P8. Where Base differs from Equipo's native files code:** |
| + 1. **Remove deletes the upload** (`DELETE /ask/attachments/{id}`, D6). A `409 attachment_sent` means it went with a message: the chip just goes, with nothing shown or announced. Remove is disabled while a send is in flight. |
| + 2. **Two at a time, preparing and uploading.** One gate admits two files at once from preparing through to their upload's answer, in order (S8). |
| + 3. **Busy is retried three times.** A `503 busy` is retried after `max(Retry-After, 2 s / 4 s / 8 s)`. The ring restarts at 0 on each try. After the third, the chip shows "Too many uploads at once. Try again in a moment." with Retry (S9). |
| + 4. **Discard only when the session ends** (S6, S7). |
| + - `BaseSession.end()` captures the old client before clearing it, and starts a best-effort `POST /ask/attachments/discard` (five ids a call), bounded at 2 s. It never holds up `end()`. |
| + - `end()` covers the Sign out button, an account switch, a rejected session, and the kit's step change. When another Oficina app signed the ID out, the session is gone first and the discard fails silently. |
| + - Nothing is discarded on background or quit. Equipo's 24-hour drop catches those and a killed app. |
| + 5. **Uploads survive the background.** |
| + - On iPhone an upload in flight runs inside `beginBackgroundTask`, so it can finish. |
| + - If its answer is lost, the chip shows Retry. A retry is a second upload, since the route takes no key, so the orphan may count against the 20 for a day. That is accepted. |
| + 6. **The paperclip and `+` show only while `can_attach`** (`AskSnapshot` gains it). |
| + 7. **D5.** |
| + - `409 files:"unavailable"` on send keeps Ask ready, drops `can_attach`, and marks every chip with the web's words. The words can then be sent alone. |
| + - `422 files:"stale"` marks the chips "This file has expired. Attach it again." |
| + 8. **D8:** text on the pasteboard beyond the files' own names is pasted as text (through `PasteMarkdown`, as now). Otherwise its images and files are attached. |
| + 9. **The refusal words are the web's** (copy review 13), keyed by code: `attachment_too_large`, `_type`, `_heic`, `_pixels`, `_limit`, `busy`. |
| + - A plain-text `400`, which is Base's body deadline on a slow link, shows the web's "Couldn't upload. Try again." with Retry. |
| +- **P9. The cache** (spec 7.6 and 7.9, 12, as amended; S11): |
| + - **Path:** `FileManager.urls(.cachesDirectory)/Attachments/<accountKey>/<attachment id>/<name>`. |
| + - `accountKey` is P5's. |
| + - `<attachment id>` is checked against `[A-Za-z0-9_-]{1,64}`. |
| + - `<name>` is the server's name reduced to its last path component, with `/`, `\`, NUL, a leading `.` and `..` removed, and cut to at most 120 bytes of UTF-8 on a character boundary. Its extension is replaced with the media type's (`UTType(mimeType:).preferredFilenameExtension`; `bin` when unknown). |
| + - **Protection:** each file `0600`, excluded from backup, and on iOS written with `NSFileProtectionComplete`. |
| + - **One download per id at a time:** an actor holds the in-flight tasks, and a second tap awaits the first. |
| + - **Dates:** at download, the file's modification date is set to the message's `created_at`, or to the download time when the message has none (`AskMessage.createdAt` is optional). The sweep removes anything dated more than 14 days ago. |
| + - **Files open in Quick Look are skipped** (R3). The cache keeps the set of ids being previewed. A file the sweep skipped, and one already past its 14 days when it was opened, is removed when its preview closes. |
| + - **The sweep** also removes the folders of accounts not signed in now. It runs at launch, on every scene going active, when the Mac window opens, and on a daily timer while the Mac app runs. |
| + - **Cleared** on `end()` and when Ask is disconnected (`AskModel` sees `disconnected`). |
| + - **Previews** go in a 64-item memory cache, bounded at 2 MiB each. |
| + - **Privacy manifest:** the sweep reads file dates, so `PrivacyInfo.xcprivacy` gains `NSPrivacyAccessedAPICategoryFileTimestamp` with reason `C617.1`. |
| +- **P10. Camera, Photos and Files.** |
| + - **Camera** needs `NSCameraUsageDescription` in `ios/project.yml`. |
| + - **Photos** goes through `PhotosPicker` (`matching: .images`, which gives a Live Photo's still). Each item is loaded as a file through a `FileRepresentation` transferable, never as `Data`. |
| + - The file's URL is valid only inside the importing closure, so it is staged there (Equipo's `stage`, into a private directory the draft owns). |
| + - It is then prepared from the staged URL (`prepareFile`), with its size checked before anything is read into memory. |
| + - **Files** goes through `fileImporter`. |
| + - **On the Mac,** `fileImporter` takes the nine types plus HEIC, HEIF and TIFF. |
| + - **Before reading:** |
| + - a non-image file over 10 MiB is refused from its size alone; |
| + - an image over 128 MiB is refused. |
| + - **Names:** Camera and Photos items are named `Photo 1.jpg`, `Photo 2.jpg`, … in the order chosen, so "Remove Photo 2.jpg" says which one. |
| +- **P11. Strings.** |
| + - Words the web already has keep the web's approved text, under native keys. |
| + - New words are drafted with a `DRAFT 2026-11-28` comment and listed in `copy-review/slice2-part1.json` (main checkout, git-ignored) for Luna from 2026-12-02. |
| + - The release waits for that review. Building and the internal TestFlight build don't. |
| +- **P12. Version numbers.** |
| + - The mid-branch internal TestFlight build for the device check is **0.1.3 (4)**, for Paul only. |
| + - The release is **0.1.3 (5)**, Mac and TestFlight. |
| + |
| +## File map |
| + |
| +``` |
| +Base, api/store-people |
| + internal/web/store.go people.go storeContent, peopleContent, invitePerson |
| + internal/web/api_team.go NEW: the five handlers |
| + internal/web/app.go the routes beside /api/v1/home |
| + internal/web/team_internal_test.go NEW |
| + internal/webtest/api_team_test.go NEW |
| + docs/api/base-native-v1.md "Store" and "People" |
| + |
| +rastrillo/native, upload |
| + Sources/RastrilloApple/NativeHTTP.swift NativeTransport.swift |
| + Sources/RastrilloTestSupport/ScriptedTransport.swift |
| + Tests/RastrilloAppleTests/NativeHTTPUploadTests.swift NEW |
| + APPLE.md |
| + |
| +Base, native/slice2-part1 (native/apple/Sources/BaseKit unless shown) |
| + Session/BaseSession.swift SwappableTransport.upload; end() discards and clears the cache |
| + API/Client.swift API/Models.swift store, people, files, can_attach |
| + Team/StoreModel StoreView PeopleModel PeopleView .swift NEW |
| + Home/SidebarFolds.swift NEW; Home/BaseActions.swift |
| + Mac/MacMainView.swift MacPane, the Apps fold, the drop target |
| + Phone/PhoneAskScreen.swift AppsSheet: the fold, "Your team", NavigationStack |
| + Attachments/ (P7's files, and NEW: AttachGate, AttachIntake, AttachmentCache, QuickLook) |
| + Ask/Composer.swift Thread.swift AskModel.swift PasteMarkdown.swift |
| + ../BaseMac/BaseMacApp.swift the Paste command (Task 17) |
| + Resources/Localizable.xcstrings |
| + native/ios/project.yml native/PrivacyInfo.xcprivacy native/scripts/check-native.sh (-j 4) |
| + Tests/BaseKitTests/… Tests/BaseSnapshots/TeamSnapshots.swift AttachmentFixtures.swift AskSnapshots.swift |
| +``` |
| + |
| +--- |
| + |
| +## Part A: the server (branch `api/store-people`) |
| + |
| +### Task 1: Store and People builders, shared |
| + |
| +**Files:** `internal/web/store.go`, `people.go`, `team_internal_test.go` (new). |
| + |
| +- [ ] **Tests first:** |
| + - **`storeContent`:** a row per catalogue entry, with its state and error, plus `owner` and `installing`. A failed read is an error. |
| + - **`peopleContent`:** a row per member, with `initial`, `name`, `email` and `role`. |
| + - **`invitePerson`:** returns `inviteOK` with the member, or `inviteBadEmail` or `inviteMailFailed`. |
| + - It sends only until one invitation has been delivered. |
| + - An address already here sends nothing and answers that member. |
| +- [ ] Move the reads out of `storePage` and `people`, and the write out of `invite`. The pages render the same. |
| +- [ ] **Gate:** `go test -p 4 -count=1 ./internal/web -run 'TestStoreContent|TestPeopleContent|TestInvitePerson'` and `./internal/webtest -run 'TestStore|TestPeople|TestInvite'`. The existing page tests pass unchanged. |
| + |
| +### Task 2: The reads |
| + |
| +**Files:** `internal/web/api_team.go` (new), `app.go`, `internal/webtest/api_team_test.go` (new), `docs/api/base-native-v1.md`. |
| + |
| +- [ ] **Tests first** (`newHomeApp`, `link`, `nativeSignIn`, `nativeGet` from `native_test.go`): |
| + - **`TestAPIStore`:** P2's shape, `no-store`, `application/json`, in catalogue order. |
| + - Installing, installed and failed rows, the failed one with its error. |
| + - A member who isn't the owner gets `"owner": false`. |
| + - A failing installs read gets `503 unavailable`. |
| + - **`TestAPIPeople`:** the owner, a member and an invited address, with their roles, in the page's order. A web-cookie session gets the same answer (nit 4). |
| + - **`TestAPITeamRefusesWithoutSession`:** `401 {"code":"unauthenticated"}` with no session, and for a removed member. |
| + - **`TestAPIPeopleHasNoRemove`:** `DELETE /api/v1/people/<id>` is not 2xx (404 or 405), and the member is still there. |
| +- [ ] Implement both reads, and route them beside `/api/v1/home`. |
| +- [ ] **Docs:** "Store" and "People" in `base-native-v1.md`, from P2. |
| +- [ ] **Gate:** `go test -p 4 -count=1 ./internal/webtest -run 'TestAPIStore|TestAPIPeople|TestAPITeam'`. |
| + |
| +### Task 3: The writes |
| + |
| +**Files:** `internal/web/api_team.go`, `app.go`, `internal/webtest/api_team_test.go`, `docs/api/base-native-v1.md`. |
| + |
| +- [ ] **Tests first:** |
| + - **`TestAPIStoreInstall`:** |
| + - the owner gets `202` with the row installing, and `Start` is called once; |
| + - an app already installing gets `202`, and one already installed gets `200`, with `Start` not called; |
| + - a `Start` that fails while another request has claimed the install (the row reads installing) gets `202`; |
| + - a `Start` that fails having claimed nothing gets `503`, a failed row's retry included; |
| + - a member gets `403 owner_only`, and an unknown app `404 unknown_app`; |
| + - no `Origin` gets `403` (CSRF). |
| + - **`TestAPIStoreUninstall`:** `200`; `409 busy` (an installer answering `install.ErrBusy`); `200` when already uninstalled; `403`; `404`. |
| + - **`TestAPIPeopleInvite`:** |
| + - the owner gets `200 {"person"}`, sent once (`capturingMailer`); |
| + - the same address again sends nothing, and gets `200` with that member; |
| + - an address that isn't one gets `422 bad_email`; |
| + - a failing mailer gets `502 mail_failed`, then a second invite sends; |
| + - a member gets `403`; |
| + - a form body gets `415`; |
| + - a body over 4 KiB gets `413`. |
| +- [ ] Implement them. |
| +- [ ] **Docs:** P2's table. |
| +- [ ] **Gate:** `go test -p 4 -count=1 ./internal/webtest -run 'TestAPIStore|TestAPIPeople'`. Push, and read hub CI, which runs the whole Go suite. |
| + |
| +### Task 4: Land and deploy the server |
| + |
| +- [ ] Ask for a short review of `api/store-people` (Fable, or Codex Astra when Fable is limited) and answer it on the branch. Then land it on main through the hub, and read hub CI on main. |
| +- [ ] **Note the rollback SHA:** the release now live on `base.oficina.works` (`curl -sS -D - -o /dev/null https://base.oficina.works/api/version | grep -i x-carlos-version`). Write it in the branch handoff. |
| +- [ ] **Deploy** as the Base runbook does: account `bds`, app `base`, release and promote. Base was deployed this way on 2026-11-27, after its adoption into team oficina, as `07ec2ec`. Restart if the promote needs it, since "live" can mean the old process. |
| +- [ ] **Confirm:** |
| + - `x-carlos-version` shows the new release; |
| + - `curl -s https://base.oficina.works/api/v1/store` answers `401 {"code":"unauthenticated"}`, not `404`, which proves the route is there. |
| +- [ ] **The lagged team:** check whether it runs a Base (`carlos instances list --app base` on its account). This deploy is Paul's Base only. A lagged rollout waits for Paul. |
| +- [ ] **Rollback,** if needed: promote the noted SHA, then check `/api/version` again. |
| + |
| +## Part B: the kit (rastrillo/native, branch `upload`) |
| + |
| +### Task 5: `NativeHTTP.upload` |
| + |
| +**Files:** `Sources/RastrilloApple/NativeHTTP.swift`, `NativeTransport.swift`, `Sources/RastrilloTestSupport/ScriptedTransport.swift`, `Tests/RastrilloAppleTests/NativeHTTPUploadTests.swift` (new), `APPLE.md`. |
| + |
| +- [ ] **Tests first, in two kinds** (R1): |
| + - **Against a small HTTP listener on `127.0.0.1`** (a test helper on `Network.framework`; `NativeHTTP.origin` allows `http` there). A `URLProtocol` stub never sees an upload task's body or `Content-Length`, and gets no `didSendBodyData`. These tests check: |
| + - the body arrives whole, and `Content-Length` equals its size; |
| + - progress only grows and ends at 1.0; |
| + - a response the listener holds back still completes. The helper takes a hold time; the test uses 2 s, and Task 21 runs it once by hand at 45 s. |
| + - **With a `URLProtocol` stub,** through a test seam: an internal `NativeHTTP` init that takes the `URLSessionConfiguration`, so the stub's protocol class can be set. These tests check: |
| + - `POST` and `Content-Type`; |
| + - `Content-Disposition` is `attachment; filename*=UTF-8''…`, with `é`, spaces, `"`, `/` and `;` percent-encoded; |
| + - the request's `timeoutInterval` is 90, and a `responseDetails` request's is still the session default; |
| + - `413`, `503` (with `Retry-After`) and `401` come back as a `NativeResponse` with their headers, never thrown; |
| + - a response over `maxBytes` throws; |
| + - cancelling the task cancels the upload. |
| + - **`ScriptedTransport.upload`** records the filename and the body's size. |
| +- [ ] **Implement it** with a `URLSessionUploadTask` and a task delegate, reusing `makeRequest` and `BoundedBody`. |
| + - It is a requirement with **no default** (B1). |
| + - Every in-repo conformer forwards or implements it: `NativeHTTP`, `ScriptedTransport`, and any in the kit's tests. |
| + - `APPLE.md` says that an app's own wrapping transport must forward it, naming Base's `SwappableTransport` as the example. |
| +- [ ] **Gate:** in rastrillo/native, `swift test -j 4 --filter NativeHTTPUploadTests`, then that repo's native gate once. |
| +- [ ] **Review:** ask Fable to review the `upload` branch (Codex Astra if Fable is limited), with this task and P6 as the brief. Answer every finding, then land it on rastrillo/native main and note the SHA. |
| + |
| +## Part C: the app (branch `native/slice2-part1`) |
| + |
| +### Spike M: Mac paste and drop, before anything else in Part C (R2) |
| + |
| +A short spike on a scratch branch, whose code is thrown away. It settles |
| +whether the Mac composer stays the SwiftUI field (Task 17 as written) or |
| +becomes Equipo's `NSTextView` editor first (Task 16A). Time box: half a |
| +day. |
| + |
| +- [ ] **Paste.** Try two ways, and keep the one that works: |
| + - retarget the existing Edit ▸ Paste item: find it by action `paste:` in `NSApp.mainMenu` after launch, and again whenever SwiftUI rebuilds the menu. It keeps AppKit's localised titles (nit 2); |
| + - `CommandGroup(replacing: .pasteboard)`, re-adding the standard items. |
| + |
| + Prove, by hand, in the main window's Ask composer: |
| + - a screenshot and a Finder file attach; |
| + - text from Pages pastes as text; |
| + - rich text still becomes Markdown; |
| + - the menu panel's composer, Settings and the sign-in code field still paste plain text. |
| +- [ ] **Drop.** Narrow the field and its field editor to text drag types, re-applied on **every** focus gain, because the shared field editor re-registers its own types each time it's set up for a field. |
| + - Prove, by hand: a Finder file dropped on the field, on the thread, and on the field after focus has left it and come back. Each attaches and inserts no path. |
| +- [ ] **Record the outcome** in the branch handoff and in this plan's Review, with what was seen. |
| + - If both hold, Task 17 goes ahead as written, with the way chosen here. |
| + - If either fails, Task 16A is taken before Task 17. |
| + |
| +### Task 6: Repin, and forward `upload` through `SwappableTransport` |
| + |
| +**Files:** `native/apple/Package.swift`, `native/ios/project.yml` (`RastrilloNative.revision`), `Session/BaseSession.swift`, `Tests/BaseKitTests/SessionTests.swift`, `native/scripts/check-native.sh`. |
| + |
| +- [ ] **Tests first:** |
| + - `SwappableTransport.upload` reaches the current inner transport; |
| + - after `swap(_:)`, the next upload reaches the new one; |
| + - an upload started before a swap finishes on the transport it started on. |
| +- [ ] Bump the kit to Task 5's SHA, and add `SwappableTransport.upload`. Without it the package doesn't compile, which is the point. |
| +- [ ] `check-native.sh` passes `-j 4` to `swift test` and `swift build`. |
| +- [ ] **Gate:** `swift test --package-path native/apple -j 4 --filter BaseKitTests.SessionTests`, then `build-iphone.sh simulator`. |
| + |
| +### Task 7: The client for Store and People |
| + |
| +**Files:** `API/Models.swift`, `API/Client.swift`, `Tests/BaseKitTests/ClientTests.swift`, `Fixtures/store.json`, `Fixtures/people.json`. |
| + |
| +- [ ] **Tests first (`ScriptedTransport`):** |
| + - `store()` and `people()` decode; |
| + - `install(app:)` and `uninstall(app:)` post with `Origin`, and decode the store; |
| + - `busy`, `owner_only`, `unknown_app` and `unavailable` map to `BaseAPIError` cases; |
| + - `invite(email:)` posts JSON and decodes `{"person"}`; `bad_email` and `mail_failed` map; |
| + - a `404` on a read maps to `.notOnThisBase` (P3); |
| + - a `401` calls `rejected`. |
| +- [ ] Add `StoreData`, `StoreRow` (with `State`), `PeopleData`, `Person` (with `Role`), and the five calls. |
| +- [ ] **Gate:** `swift test … --filter BaseKitTests.ClientTests`. |
| + |
| +### Task 8: Store and People models |
| + |
| +**Files:** `Team/StoreModel.swift`, `Team/PeopleModel.swift`, `Tests/BaseKitTests/StoreModelTests.swift`, `PeopleModelTests.swift`. |
| + |
| +- [ ] **Tests first (a clock and client you control):** |
| + - **`StoreModel`:** |
| + - P4's polling, backoff and stop on `401`; |
| + - `install` shows installing at once; |
| + - `uninstall` confirms first (`pendingUninstall`); |
| + - `busy` shows "This app is still installing. Try again in a moment."; |
| + - a failed row shows its error, or "The install didn't finish."; |
| + - a member sees no buttons; |
| + - an `announcement` is produced only when a row changes to installed or failed, never on a poll that changes nothing. |
| + - **`PeopleModel`:** |
| + - it loads; |
| + - `invite` trims and lowercases; |
| + - each error has the web's words and is exposed as an announcement; |
| + - success clears the field and reloads; |
| + - Invite is busy while in flight (the 650 ms spinner rule). |
| +- [ ] Implement both as `@MainActor @Observable` classes. |
| +- [ ] **Gate:** `swift test … --filter 'BaseKitTests.StoreModelTests|BaseKitTests.PeopleModelTests'`. |
| + |
| +### Task 9: Store and People screens |
| + |
| +**Files:** `Team/StoreView.swift`, `Team/PeopleView.swift`, `Tests/BaseSnapshots/TeamSnapshots.swift` (new). |
| + |
| +- [ ] **Snapshots first,** as the mockups `mac-store`, `mac-people`, `phone-store` and `phone-people`: |
| + - Store as the owner (installed, installing, failed) and as a member; |
| + - People as the owner (invite field, an invited row) and as a member; |
| + - the uninstall confirmation; |
| + - Mac and iPhone, light and dark, iPhone also at AX3. |
| +- [ ] **Build them** from the look's parts. |
| + - **Uninstall** confirms with the web's words. |
| + - **VoiceOver:** each row is one element. |
| + - An owner's installed row has a named action, "Uninstall", and a failed row has "Try again". |
| + - Polling never moves focus. |
| + - The model's announcements are posted (`AccessibilityNotification.Announcement`), as are the invite's errors (the web's `role="status"`). |
| +- [ ] **Gate:** `snapshots.sh record mac` and `record iphone` for the new pictures only. Review them beside the mockups, then `compare` both. |
| + |
| +### Task 10: Getting to Store and People |
| + |
| +**Files:** `Mac/MacMainView.swift`, `Phone/PhoneAskScreen.swift`, `Home/BaseActions.swift`, `Tests/BaseKitTests/AskViewTests.swift`, `OpenerTests.swift`. |
| + |
| +- [ ] **Tests first:** |
| + - choosing `store` or `people` sets `MacPane.store` or `.people` and never calls `openURL`; |
| + - when a read answered `.notOnThisBase`, the same choice opens the web page; |
| + - `AppsSheet` lists "Your team": Store, and People with the count of people once `/api/v1/people` has loaded, and no count before; |
| + - `settings` is unchanged. |
| +- [ ] **Mac:** `MacMainView` gains `@State var pane: MacPane`. The Ask Base, Store and People rows select it. |
| +- [ ] **iPhone:** `AppsSheet` wraps its content in a `NavigationStack`, and the "Your team" rows push the screens. |
| +- [ ] **Gate:** `swift test … --filter 'BaseKitTests.AskViewTests|BaseKitTests.OpenerTests'`, then `build-iphone.sh simulator`, then `snapshots.sh compare`. The main window and the apps sheet change, so record those after review. |
| + |
| +### Task 11: The Apps section folds |
| + |
| +**Files:** `Home/SidebarFolds.swift` (new), `Mac/MacMainView.swift`, `Phone/PhoneAskScreen.swift`, `Tests/BaseKitTests/SidebarFoldsTests.swift`, `BaseSnapshots/MacSnapshots.swift`, `AskSnapshots.swift`. |
| + |
| +- [ ] **Tests first:** |
| + - it starts open; |
| + - a new `SidebarFolds` for the same account remembers; |
| + - another account, or another Base, has its own state; |
| + - the key is P5's hash, with no address or origin in clear; |
| + - it works with no `me` loaded. |
| +- [ ] **Build the heading** on both platforms: a button with a chevron, and the count when folded. |
| + - **Mac keyboard:** Space toggles it; ← folds and → unfolds. |
| + - **VoiceOver:** "Apps, expanded" or "Apps, collapsed". |
| + - **Reduce Motion:** no chevron animation. |
| +- [ ] **Snapshots:** the Mac sidebar folded and open; the apps sheet folded, also at AX3. |
| +- [ ] **Gate:** `swift test … --filter BaseKitTests.SidebarFoldsTests`, `build-iphone.sh simulator`, then `snapshots.sh compare` after a reviewed record. |
| + |
| +### Task 12: Copy Equipo's files code into BaseKit (R5) |
| + |
| +**Files:** P7's table, and nothing else. |
| + |
| +- [ ] Copy each file in P7, with its provenance line. |
| +- [ ] **Make them compile and nothing more:** |
| + - Base names; |
| + - `BaseText` for strings; |
| + - an `AttachmentClient` protocol in place of `EquipoClient`, with `upload`, `delete`, `data(id:preview:)` and `download(id:to:)`. |
| + - Behaviour is unchanged. |
| +- [ ] **Run the copied tests.** Mark any that assert behaviour P8 changes with `// Base differs: Task 14` or `Task 15`, and skip them (`XCTSkip`) until then. |
| +- [ ] **Gate:** `swift test … --filter 'BaseKitTests.Attachment'`, then **`check-native.sh`** (the first of its two runs). |
| + |
| +### Task 13: The files client |
| + |
| +**Files:** `API/Client.swift`, `API/Models.swift`, `Tests/BaseKitTests/ClientTests.swift`, `Fixtures/attachment.json`. |
| + |
| +- [ ] **Tests first:** |
| + - **`AskSnapshot.canAttach`** decodes `can_attach`, and is `false` when it's missing. |
| + - **`upload`:** |
| + - it goes through the transport's `upload` to `/ask/attachments`, and decodes `201`; |
| + - each refusal maps to its code; |
| + - `503 busy` carries `Retry-After`; |
| + - a plain-text `400` maps to `.uploadFailed`; |
| + - a `401 unauthenticated` calls `rejected` (S1). |
| + - **`deleteAttachment`:** `204` and `404` are done; `409 attachment_sent` is `.alreadySent`. |
| + - **`discard(ids:)`:** five per call. |
| + - **`attachmentData(id, preview: true)`:** bounded at 2 MiB. |
| + - **`downloadAttachment(id, to:)`:** uses the transport's `download`. |
| + - **`send(text, key, attachments:)`:** repeats the field in order. |
| + - **On send:** `409 files:"unavailable"` maps to `.filesUnavailable`, and `422 files:"stale"` to `.filesStale`. Neither changes the phase. |
| +- [ ] Implement these. `BaseClient` conforms to `AttachmentClient`. |
| +- [ ] **Gate:** `swift test … --filter BaseKitTests.ClientTests`. |
| + |
| +### Task 14: The draft's rules |
| + |
| +**Files:** `Attachments/AttachmentDraft.swift`, `Attachments/AttachGate.swift` (new), `Session/BaseSession.swift`, `Tests/BaseKitTests/AttachmentDraftTests.swift`, `SessionTests.swift`. |
| + |
| +- [ ] **Tests first (a scripted client and a clock):** |
| + - **P8.1, Remove:** |
| + - Remove deletes; |
| + - `.alreadySent` drops the chip silently; |
| + - Remove is disabled while sending. |
| + - **P8.2, the gate:** |
| + - with five files added at once, at most two are preparing or uploading at any moment, in order; |
| + - a sixth file is refused at the chip. |
| + - **P8.3, busy:** |
| + - three retries with backoff; |
| + - the ring restarts at 0; |
| + - then the busy chip, with Retry. |
| + - **P8.4, discard:** |
| + - `end()` reads the unsent ids from the draft and captures the client **before** `ask?.dispose()` clears them. It then starts a discard bounded at 2 s, and returns at once; |
| + - a discard that answers `401` is dropped silently; |
| + - nothing is discarded on background. |
| + - **P8.5, background:** |
| + - an upload in flight is wrapped in a background task, behind a protocol the test fakes; |
| + - the task's expiry handler cancels the upload and shows Retry; |
| + - files still queued behind the gate wait for the foreground and don't fail; |
| + - a lost answer shows Retry. |
| + - **The PDF line:** a PDF chip says "Ask can't read PDFs yet." |
| +- [ ] Turn each `// Base differs: Task 14` test around. Add the iOS `UIApplication` conformer of the background-task protocol. |
| +- [ ] **Gate:** `swift test … --filter 'BaseKitTests.AttachmentDraftTests|BaseKitTests.SessionTests'`, then `build-iphone.sh simulator` (the conformer is iOS-only). |
| + |
| +### Task 15: Sending with files, and D5 |
| + |
| +**Files:** `Ask/AskModel.swift`, `Attachments/AttachmentDraft.swift`, `Tests/BaseKitTests/AskModelTests.swift`. |
| + |
| +- [ ] **Tests first:** |
| + - Send waits for every upload; |
| + - the text may be empty with files; |
| + - the sent message's files clear the chips; |
| + - a failed send keeps them, and a resend reuses the key; |
| + - with `can_attach` false there is no paperclip or `+`, and `add` refuses; |
| + - **D5:** after `.filesUnavailable` Ask stays ready, and the words go alone with one tap; `.filesStale` marks the chips; |
| + - switching accounts ends the old draft (Task 14's discard). |
| +- [ ] Implement these, and turn each `// Base differs: Task 15` test around. |
| +- [ ] **Gate:** `swift test … --filter 'BaseKitTests.AskModelTests|BaseKitTests.AttachmentDraftTests'`. |
| + |
| +### Task 16: Files prepared on the device |
| + |
| +**Files:** `Attachments/AttachmentFile.swift`, `Tests/BaseKitTests/AttachmentFileTests.swift`. |
| + |
| +- [ ] **Tests first.** Fixtures are generated in the test with `CGImageDestination` (a HEIC, a 7952×5304 JPEG, a TIFF, a 2000 px PNG with GPS); nothing large is committed. |
| + - HEIC, HEIF and TIFF become JPEG, and `convertedFrom` says what from; |
| + - over 2560 px is scaled down, keeping its aspect; |
| + - **converted output** has no EXIF location (S10); |
| + - a PNG or JPEG at or under 2560 px goes up byte for byte, since Equipo strips location on arrival; |
| + - the 48 MP photo comes out under 10 MiB and 40 MP; |
| + - a non-image over 10 MiB is refused from its size, without being read; |
| + - an image over 128 MiB is refused; |
| + - an unknown type gets the web's types line. |
| +- [ ] Wire it into the draft behind Task 14's gate, off the main actor. |
| +- [ ] **Gate:** `swift test … --filter BaseKitTests.AttachmentFileTests`. |
| + |
| +### Task 16A: The Mac composer becomes an `NSTextView` (only if Spike M failed) |
| + |
| +**Files:** `Ask/Composer.swift`, `Mac/MacComposerEditor.swift` (new, from Equipo's `ComposerEditor` in `EquipoMac/MacComposer.swift`, P7 amended), `Tests/BaseKitTests/ComposerTests.swift`, `BaseSnapshots/AskSnapshots.swift`. |
| + |
| +- [ ] **Tests first:** every behaviour `ComposerTests` pins today still holds on the new editor: |
| + - Return sends, and Shift- or Option-Return starts a new line; |
| + - marked text (an input method) is never sent half typed; |
| + - undo and redo; |
| + - a rich paste becomes Markdown; |
| + - the placeholder; |
| + - the focus ring. |
| +- [ ] Move `ComposerInput`'s Mac half (undo, IME, rich paste) into the editor. The iPhone half is unchanged. |
| +- [ ] **Gate:** `swift test … --filter BaseKitTests.ComposerTests`, then `snapshots.sh compare mac` (the composer must look the same). |
| +- [ ] **Its own review** (Fable, or Codex Astra) before Task 17 starts. |
| + |
| +### Task 17: Attaching on the Mac |
| + |
| +**Files:** `Attachments/AttachIntake.swift` (new), `Attachments/MacPasteboard.swift`, `AttachmentPromises.swift`, `Ask/Composer.swift`, `Mac/MacMainView.swift`, `../BaseMac/BaseMacApp.swift`, `Tests/BaseKitTests/MacAttachmentTests.swift`, `AttachIntakeTests.swift`, `BaseSnapshots/AskSnapshots.swift`. |
| + |
| +**Why not Equipo's editor.** |
| +- Equipo's Mac composer is `ComposerEditor`, an `NSTextView` subclass that overrides `paste(_:)` and the dragging methods. |
| +- Base's composer is a SwiftUI field whose window field editor it only observes (`ComposerInput`, `Composer.swift:103-135`), so there's nothing to subclass. |
| +- Base takes Paste and drops where they arrive instead. |
| + |
| +- [ ] **Tests first (platform-neutral):** `AttachIntake.decide(_ contents: PasteboardContents) -> .attach([Item]) | .text` implements D8: |
| + - an image alone attaches; |
| + - files alone attach; |
| + - text with an image (Pages, Word, Excel) is text; |
| + - text that is only the files' own names attaches; |
| + - a file promise attaches. |
| +- [ ] **Paste: the menu's Paste,** the way Spike M chose: the retargeted existing item, or the replaced group. |
| + - ⌘V arrives at it through the menu, as every key equivalent does. |
| + - **Only the main window's Ask composer asks `AttachIntake`.** `ComposerInput` gains `attaches`, set by `MacMainView`'s composer alone. The menu panel's composer (which doesn't attach in part 1), Settings and the sign-in code field always get the plain `paste:`. `focused` alone can't tell the two composers apart. On `.attach` it attaches, and the field gets nothing. |
| + - **Otherwise** it sends `NSText.paste(_:)` down the responder chain, setting `ComposerInput`'s `pasting` flag first. This is required: the rich-paste path detects Paste by the menu item's action being `paste:` (`Composer.swift:136-139`), which the command's item no longer has. |
| + - **Test:** a rich paste through the new command still becomes Markdown (HTML on the pasteboard, Markdown in the field), and the menu panel's composer pastes text even with an image on the pasteboard. |
| + - **Accepted:** Paste from the field's own context menu calls the field editor directly, bypassing the command, so an image pasted that way does nothing. The menu, ⌘V, drop and the paperclip all attach. |
| +- [ ] **Drop: on the pane.** |
| + - The Ask pane takes `.onDrop(of: [.fileURL, .image, file promise types], isTargeted:)` and shows the outline (mockup `mac-drop`). |
| + - So that a drag over the field reaches the pane and doesn't insert a path, `ComposerInput` registers the field and its field editor for text types only (`registerForDraggedTypes([.string])` after `unregisterDraggedTypes()`). |
| + - It does this on **every focus gain**, not once in `start()`, because the window's shared field editor re-registers its own types each time. |
| + - Plain text can still be dragged into the field. |
| + - With Task 16A taken, the editor's own dragging overrides do this instead. |
| +- [ ] **The paperclip:** left of Send, only while `can_attach`. It opens `fileImporter` (multiple selection, P10's types). |
| +- [ ] **The menu panel's composer** doesn't attach in part 1. Drops there are refused quietly. |
| +- [ ] **Chips and accessibility:** |
| + - chips above the field, wrapping, at most 196 pt tall, then scrolling; |
| + - **keyboard:** Tab reaches each chip; Delete removes it; Return retries a failed one; |
| + - **VoiceOver:** |
| + - Remove and Retry are named actions; |
| + - the ring has a value ("62 percent"), updated without announcing each step; |
| + - "{name} attached" and "{name} not attached: {reason}" are announced (the web's words); |
| + - **Reduce Motion:** the ring jumps rather than animates. |
| +- [ ] **Snapshots,** as `mac-attach` and `mac-drop`, light and dark. |
| +- [ ] **Gate:** `swift test … --filter 'BaseKitTests.AttachIntakeTests|BaseKitTests.MacAttachmentTests'`, then `snapshots.sh compare mac` after a reviewed record. |
| + |
| +### Task 18: Attaching on the iPhone |
| + |
| +**Files:** `Attachments/PhoneAttachmentPicker.swift`, `Attachments/AttachSources.swift` (new, platform-neutral), `Ask/Composer.swift` (`ComposerPaste`, `ComposerInput` on iOS), `Phone/PhoneAskScreen.swift`, `native/ios/project.yml`, `Tests/BaseKitTests/AttachSourcesTests.swift`, `BaseSnapshots/AskSnapshots.swift`. |
| + |
| +- [ ] **Tests first, on the platform-neutral `AttachSources`** (it holds the logic; the iOS views only call it): |
| + - which sources the menu offers: Photos, Camera only when available (injected), Files, and Paste only when the pasteboard says it has images or files (`UIPasteboard.hasImages` / `hasURLs`, injected); |
| + - how many more Photos may be chosen: `5 - chips`; |
| + - the names (P10: `Photo 1.jpg`…); |
| + - that the paste of an image through the field (`ComposerPaste`) attaches it and inserts nothing. |
| +- [ ] **The `+` menu:** Photos, Camera, Files and Paste, Equipo's four, with Equipo's labels as drafts for Base's review. |
| + - Paste reads the pasteboard as Equipo's `paste()` does, so the system shows its paste prompt. |
| +- [ ] **The field takes a pasted image.** |
| + - `ComposerInput` sets the `UITextView`'s `pasteConfiguration` to accept `public.image` as well as text. |
| + - `ComposerPaste`'s transform hands image items to the draft (`setNoResult()`), and leaves text as now. |
| +- [ ] **The rest:** |
| + - the chips are one line that scrolls sideways; |
| + - `NSCameraUsageDescription` is added (DRAFT: "Base uses the camera to take a photo for Ask."); |
| + - **VoiceOver,** as in Task 17. |
| +- [ ] **Snapshots,** as `phone-attach`: the menu open, chips with a "from HEIC" photo and one uploading, light and dark, and AX3. |
| +- [ ] **Gate:** `swift test … --filter BaseKitTests.AttachSourcesTests`, `build-iphone.sh simulator`, then `snapshots.sh compare iphone` after a reviewed record. |
| +- [ ] **On a device,** with internal TestFlight build **0.1.3 (4)** (DRAFT strings; Paul only): |
| + - five 48 MP photos picked at once (S8); |
| + - a Live Photo (its still); |
| + - a ProRAW photo (the 2560 px path); |
| + - Camera; |
| + - Files; |
| + - a pasted screenshot; |
| + - background during an upload. |
| + |
| + Note the results in the commit. |
| + |
| +### Task 19: Files in the thread, Quick Look, and the cache |
| + |
| +**Files:** `Ask/Thread.swift`, `Attachments/AttachmentViews.swift`, `Attachments/AttachmentCache.swift` (new), `Attachments/QuickLook.swift` (new), `Session/BaseSession.swift`, `Ask/AskModel.swift`, `BaseMac/BaseMacApp.swift`, `native/PrivacyInfo.xcprivacy`, `Tests/BaseKitTests/AttachmentCacheTests.swift`, `AskViewTests.swift`, `BaseSnapshots/AskSnapshots.swift`. |
| + |
| +- [ ] **Tests first:** |
| + - **The bubble:** thumbnails (from `/preview`), then pills (mark, name, size), then the words. A lone image draws larger. A failed thumbnail shows its name. |
| + - A thumbnail's label is "Image, {name}"; a pill's is "{name}, {size}"; both have the button trait. |
| + - **The cache:** every P9 rule, each a test. |
| + - The path, and sanitised names such as `../x.command` stored as `x.txt` for a `text/plain` file. |
| + - `0600`, excluded from backup, and `.complete` (iOS, checked through an injected file-attributes protocol). |
| + - One download per id. |
| + - The message date as the file date (the download time without one), and the 14-day sweep. |
| + - The sweep skips an id open in Quick Look, and removes an expired one when its preview closes. |
| + - Other accounts' folders removed. |
| + - Cleared on `end()` and on `disconnected`. |
| + - The sweep's triggers, each injected. |
| + - **Quick Look:** |
| + - the Mac opens `QLPreviewPanel` on click, or Space on a selected file; |
| + - the iPhone presents `QLPreviewController`, which has Share; |
| + - focus returns to the thumbnail when it closes; |
| + - a `404` shows "This file isn't available any more." (DRAFT). |
| +- [ ] Build it. |
| + - Remove the names line, `FilesLine` (`Thread.swift:135-159`). |
| + - Delete the copied full-size preview in `AttachmentViews.swift`. |
| + - Add the privacy manifest's `C617.1`. |
| +- [ ] **Snapshots:** the bubble as `mac-quicklook` (the bubble only) and `phone-sent`, light and dark, and the iPhone at AX3. |
| +- [ ] **Gate:** `swift test … --filter 'BaseKitTests.AttachmentCacheTests|BaseKitTests.AskViewTests'`, `build-iphone.sh simulator`, then `snapshots.sh compare` after a reviewed record. |
| + |
| +### Task 20: Strings |
| + |
| +**Files:** `Resources/Localizable.xcstrings`; `copy-review/slice2-part1.json` (main checkout, git-ignored). |
| + |
| +- [ ] **Every string from Tasks 8 to 19 is in the catalog.** The web's approved words are reused verbatim: the Store and People pages, and `data-w-*` in `chat.html`. |
| +- [ ] **These are new, drafted** (`DRAFT 2026-11-28`) and listed for Luna with their context: |
| + - "from HEIC"; |
| + - Photos, Camera, Files, Paste (Equipo's approved words, which Base reviews in its own voice); |
| + - "Your team"; |
| + - "Apps, expanded" and "Apps, collapsed"; |
| + - "Image, {name}"; |
| + - "This file isn't available any more."; |
| + - "Photo {n}"; |
| + - the camera's purpose string. |
| +- [ ] **Gate:** `python3 native/scripts/check-strings.py`. |
| + |
| +### Task 21: The branch's last checks |
| + |
| +- [ ] **`check-native.sh` once** (the second of its two runs), then `snapshots.sh compare` for both platforms once. |
| +- [ ] **Push and read hub CI** on the tip. It proves Go and the catalog only (Gates). |
| +- [ ] **Hand checks on a Mac with this build,** against the deployed server (Task 4): |
| + - Store install and uninstall on a test Base; |
| + - an invite to a test address; |
| + - Apps folds, and stays folded after a relaunch and offline; |
| + - paste, drop, the paperclip and Quick Look; |
| + - sign-out clears `Caches/Attachments/<accountKey>`; |
| + - an upload whose answer is held for 45 s still completes: Task 5's listener helper, run once by hand with a 45 s hold. |
| +- [ ] **An independent code review** of the whole branch (Fable, or Codex Astra), with this plan and spec 7.4 to 7.6 as the brief. Answer it on the branch. |
| + |
| +### Task 22 (Controller): Copy review, land, release |
| + |
| +- [ ] Luna reviews `copy-review/slice2-part1.json` from 2026-12-02. Run `sync-strings.py`, then `check-strings.py`. |
| +- [ ] Land the branch on main through the hub, and read hub CI on main. |
| +- [ ] Release **0.1.3 (5):** Mac through Sparkle (`release-mac.sh`) and TestFlight (`testflight.sh`). |
| +- [ ] **Check the release:** |
| + - the appcast lists 0.1.3; |
| + - TestFlight shows build 5 processed; |
| + - one Mac takes the update and opens Store natively. |
| + |
| +## Review |
| + |
| +How each finding from Fable's plan review (2026-11-28) is answered: |
| + |
| +| Finding | Answer | |
| +|---|---| |
| +| **B1** | P6 and Task 5: `upload` is a requirement with no default. Task 6 forwards it in `SwappableTransport`, with tests through it, including a swap mid-session | |
| +| **S1** | The `401` test moved from the kit (Task 5) to the client (Task 13, Task 7), where `rejected` is called | |
| +| **S2** | P6: a per-request timeout of 90 s, tested by inspecting the request. P8.9: a plain-text `400` shows the failed chip with Retry | |
| +| **S3** | Task 5 is on its own rastrillo/native branch, with its own Fable review before it lands. Base repins after (Task 6) | |
| +| **S4** | Gates: `check-native.sh` twice only (after Task 12, and in Task 21), filtered `swift test` per task, `build-iphone.sh` where iOS code changes, `-j 4` in the script. Hub CI's native step stated as it is (`--core-only`: the catalog only). Task 18's logic lives in the platform-neutral `AttachSources` | |
| +| **S5** | Task 17: Paste through a replaced Edit menu command, and drop on the pane with the field's drag types narrowed. Proven by hand in step 1, with Equipo's `ComposerEditor` as the fallback. Task 18: the `+` menu keeps Paste, and the field accepts image pastes (`pasteConfiguration`, `ComposerPaste`). P7: the fixtures adapted | |
| +| **S6** | P8.4 and P8.5: no discard on background. Uploads run as background tasks. A lost answer gives Retry, and the orphan is accepted and written down | |
| +| **S7** | P8.4: discard from `end()` with the old client, bounded at 2 s, never blocking. It covers every cause of `end()`. The kit's sign-out from another app is stated. The cache hangs off `end()`, and the launch sweep removes other accounts' folders. No quit hook: quitting is left to the 24-hour drop | |
| +| **S8** | P8.2 and Task 14: one gate for preparing and uploading, two at a time. P10: sizes checked before reading, and Photos loaded as files. Task 18: five 48 MP photos on the device | |
| +| **S9** | P8.3: three tries with backoff, the ring restarting, then the busy chip with Retry | |
| +| **S10** | Task 16: location checked on converted output only. Small PNGs and JPEGs go up as they are (Equipo strips on arrival). `convertedFrom` makes `AttachmentFile` "copied, then changed" in P7 | |
| +| **S11** | P9: exact path and name sanitising, the hashed account, iOS `.complete`, the date from the message, sweeps at launch, active, window open and daily, clearing on disconnect, one download per id, and Share copies stated (spec 7.6 amended) | |
| +| **S12** | P2: `503` everywhere a read can fail; a failed `Start` decided; repeat installs decided; invite answers `{"person"}` (spec 7.4 amended); `joined` dropped; a no-Remove test (Task 2) | |
| +| **S13** | Part A lands and deploys first (Task 4), with a rollback SHA, a live `/api/version` check with a restart if needed, a `401`-not-`404` route check, and the lagged team named. P12: 0.1.3 (4) internal and 0.1.3 (5) release | |
| +| **Accessibility** | Tasks 9, 11, 17, 18, 19: the ring's value, keyboard and VoiceOver actions, numbered photo names, quiet polling, named row actions, bubble labels and focus return, announced invite errors, and the missing AX3 and dark snapshots | |
| +| **Nits taken** | 1 (P7's "not copied on purpose"); 2 (fixtures generated); 3 (`@escaping`, `maxBytes`, `Content-Length`); 4 ("a member's session"); 5 (the count from `/api/v1/people` only); 6 (spec 7.5: a button heading); 7 (P5 keyed on the account); 8 (P4 backoff, stop on `401`); 9 (Task 19 deletes the preview); 10 (Live Photo and ProRAW on the device); 11 (`attachment_sent`: the chip just goes); 12 (Remove disabled while sending) | |
| +| **Order** | Task 12 is split into 14 and 15. Task 12 names every file it copies | |
| + |
| +How the re-review (2026-11-28, approved) is folded in: |
| + |
| +| Finding | Answer | |
| +|---|---| |
| +| **R1** | Task 5: body, `Content-Length` and progress tested against a `127.0.0.1` listener. The `URLProtocol` stub, through a configuration seam, keeps the header and status tests | |
| +| **R2** | Spike M at the start of Part C proves paste and drop. The `NSTextView` fallback is its own Task 16A, with its own review. The drag-type narrowing is re-applied on every focus gain. Only the main window's Ask composer uses `AttachIntake`. A test checks that rich paste still becomes Markdown through the command | |
| +| **R3** | P9: the sweep skips files open in Quick Look and removes expired ones on close. A message without `created_at` dates its file at download | |
| +| **Nit 1** | Task 14: the expiry handler cancels and shows Retry; queued files wait for the foreground; `build-iphone.sh` added to its gate | |
| +| **Nit 2** | Spike M tries retargeting the existing Paste item first. Context-menu Paste bypassing the command is accepted and stated (Task 17) | |
| +| **Nit 3** | P10: Photos staged inside the importing closure, then prepared from the URL | |
| +| **Nit 4** | P9: the 120-byte cut falls on a character boundary | |
| +| **Nit 5** | Task 4: account `bds`, as Base was deployed on 2026-11-27 (`07ec2ec`) | |
| +| **Nit 6** | Task 21: a hand check that an upload held for 45 s completes | |
diff --git a/docs/superpowers/specs/2026-11-23-base-native-design.md b/docs/superpowers/specs/2026-11-23-base-native-design.md| index 2ca4c41..081c914 100644 |
| --- a/docs/superpowers/specs/2026-11-23-base-native-design.md |
| +++ b/docs/superpowers/specs/2026-11-23-base-native-design.md |
| @@ -17,6 +17,12 @@ Decided by Paul so far: |
| (2026-11-23). |
| - **Ask is set up during sign-in, in slice 1** (2026-11-23): nobody approves |
| a code in Equipo before Ask works (3.8). |
| +- **Slice 2 approved with every recommendation** (2026-11-28): section 7, |
| + and its rulings in 7.9. |
| +- **Jobs started in Equipo stay in Equipo, and jobs started in Base stay in |
| + Base** (2026-11-28): notifications, decision cards and Live Activities. |
| +- **Base takes over the Live Activity for jobs started from Ask** in slice 3 |
| + (2026-11-28). |
| Mockups: `.superpowers/mockups/native/` (git-ignored: it holds the licensed |
| font; `python3 build.py` draws it), shown to Paul on 2026-11-23. |
| @@ -186,6 +192,8 @@ fork all of that. |
| moment it changes, and Base only sees it while relaying a chat. |
| - **Blocked on** the CARLOS push verb and the ruling on who holds the Apple |
| push key, the same blockers as Equipo's own push. |
| +- **Decided in section 7** (2026-11-28): Equipo sends, to registrations |
| + Base relays, and each app hears only the jobs started in it (7.2). |
| ### 3.6 The look |
| @@ -259,7 +267,8 @@ Ask's existing "isn't set up for you yet" state. |
| 4. **Store, People and Settings in slice 1?** Recommended: Settings natively |
| (account, appearance, sign out, Equipo connection). Store and People open |
| Base on the web in slice 1 and go native in slice 2. |
| -5. **Notifications:** sent by Equipo (recommended) or by Base. |
| +5. **Notifications:** sent by Equipo (recommended) or by Base. Decided |
| + (Paul, 2026-11-28): Equipo (7.2, 7.9). |
| ## 5. Not doing |
| @@ -277,6 +286,699 @@ Ask's existing "isn't set up for you yet" state. |
| opening as in 3.4, Settings. |
| - Mockups first, for Paul to approve. Then the plan. |
| 2. **Notifications, Store and People native, and the jobs design's |
| - decisions on cards** (if not already built for the web). |
| + decisions on cards** (if not already built for the web). Specified in |
| + section 7, in four parts (7.11); part 1 is planned in |
| + `docs/superpowers/plans/2026-11-28-native-slice2-part1.md`. |
| 3. **Siri and Shortcuts** ("Ask Base"), a share extension ("Send to Base"), |
| and Live Activities for running jobs. |
| + |
| +## 7. Slice 2: notifications, decisions on cards, Store and People, files |
| + |
| +Approved by Paul on 2026-11-28, with every recommendation as written (7.9). |
| +Read against Base main `07ec2ec`, Equipo origin/main `8bd40ed1`, CARLOS |
| +origin/main `e210550b1` and its push branch `379d97d17` |
| +(`design/platform-push-submission`), rastrillo `0033fa0e` (v0.47.0), |
| +rastrillo/native `bb989a7`, Docs `78fb1db`, Sheets `76b7abc`, Slides |
| +`a27d28d`, Home `88f610a`. |
| + |
| +Mockups: `.superpowers/mockups/native-s2/` (git-ignored: it holds the |
| +licensed font; `python3 build.py` draws them), shown to Paul on 2026-11-28. |
| + |
| +Rulings this section works under: |
| + |
| +- **Keep working through the plan in order** (Paul, 2026-11-28). |
| +- **"Equipo jobs started in Equipo should stay in Equipo and jobs started in |
| + Base should stay in Base"** (Paul, 2026-11-28). That covers notifications, |
| + decision cards and, later, Live Activities. Base shows and notifies only |
| + the jobs started from Ask, and Equipo only its own. |
| +- **In slice 3, Base takes over the Live Activity for jobs started from Ask**, |
| + so there's never a duplicate with Equipo's (Paul, 2026-11-28). |
| +- **Files in Ask** (2026-11-26): Equipo holds the bytes (R1), the Assistant |
| + reads a file for 14 days (R3), and native copies Equipo's attachment code |
| + into BaseKit (R5). |
| + |
| +### 7.1 What exists today |
| + |
| +#### Push |
| + |
| +- **CARLOS `/v1/push` is a spec, not code on main.** |
| + - The spec was approved on 2026-11-20: |
| + `docs/superpowers/specs/2026-11-20-platform-push-submission-design.md` |
| + at `379d97d17`. |
| + - The build is uncommitted work in `carlos/platform-wt-push-build` |
| + (`internal/pusher/`, `internal/pushsubmit/`). Main and v0.44.0 have no |
| + pusher. |
| + - A box-local `carlos-pusher` holds the Apple key, plus a grant file that |
| + names which `(account, app)` may push to which topic (decisions 4 and 9, |
| + and §5 `apns.conf`): |
| + ``` |
| + key NS36T57NS4 9U4A84C4WK production works.oficina.equipo |
| + grant <sqid>/equipo works.oficina.equipo |
| + ``` |
| +- **rastrillo's push client** (`push.FromCarlos`, `push.Submit`) is |
| + uncommitted on `feat/push-submit` in `rastrillo/rastrillo-push-submit`, and |
| + has no tag. |
| +- **Equipo can't send to its own app yet.** |
| + - Registrations, the outbox and the payloads are all built. |
| + - The transport is a stub: `push.FromCarlos` refuses boot when |
| + `CARLOS_PUSH=submit` (`internal/equipo/push/transport.go:50-64`, "SEAM |
| + (2026-11-20)"). |
| + - The topic is a constant, `push.Topic = "works.oficina.equipo"` |
| + (`push/push.go:19`). |
| +- **Equipo's registrations have no app or topic.** |
| + - The table is `push_registrations(credential PRIMARY KEY, person, token, |
| + environment, platform, start_token, …)` |
| + (`migrations/0096_push.sql:8`), with `actions_version` and |
| + `binding_id` added in 0111. |
| + - The routes are `POST /api/v1/push-registrations` and |
| + `…/activities` (`chat/http.go:95-96`). |
| + - Recipients are `push.Devices(person)` (`push/store.go:286`). |
| +- **The Apple key is topic-specific and production-only.** From the CARLOS |
| + spec's "Facts (2026-11-20)": |
| + > "key ID `NS36T57NS4`, Team ID `9U4A84C4WK`. It is **production only** |
| + > and **topic-specific**: its only topic is `works.oficina.equipo` … The |
| + > `.p8` has not been downloaded yet; Apple allows one download." |
| + |
| + So Equipo's key can't push to `works.oficina.base`, and Base needs a key of |
| + its own. |
| +- **Base's app has no push.** Both entitlements files say "No push until |
| + slice 2" (`native/ios/BasePhone.entitlements`, |
| + `native/macos/DeveloperID.entitlements`). Equipo's Mac app shows that a |
| + Developer ID app can get push: it carries |
| + `com.apple.developer.aps-environment = production` |
| + (`equipo native/macos/DeveloperID.entitlements:10-11`). |
| + |
| +#### Where a job started (for the ruling) |
| + |
| +- **Every turn, card and task has a lane** (`wire/assistant.go:8-24`). |
| + - `""` is the Coordinator (Equipo's own conversation). |
| + - `assistant` is Base's Ask. |
| + - `job:h_<id>` is "the Coordinator thread of one job Base handed off". |
| +- **A task's lane comes from the turn that made it.** `chat_tasks.lane` is |
| + set in `chat/tasks.go:866` (migration 0084), and cards inherit it |
| + (`tasks.go:898`). |
| +- **Hand-offs list their tasks** in `chat_handoff_tasks(handoff_id, task_id)` |
| + (0079), and their lane in `chat_handoffs.lane` (0083). |
| + - Hand-offs from before job threads existed have an empty lane. |
| + - Their tasks still appear in `chat_handoff_tasks`, so that table is the |
| + reliable test. |
| +- **Equipo's push rules only half follow the ruling today** |
| + (`push/rules.go:123-200`). |
| + - **Followed:** `card_opens` and `reply_unseen` fire only for the |
| + Coordinator lane (`:126`, `:138`). |
| + - **Not followed:** `task_ends`, `task_fails`, `badge` and the four |
| + `activity_*` rules check no lane. A task Base handed off therefore ends, |
| + fails and runs a Live Activity on Equipo's app today. |
| + - **Why:** `pushTask` (`chat/push.go:426`) builds the change from |
| + `wire.Task`, which has no lane field. |
| +- **No message records which client sent it.** `PersonPrincipal` carries |
| + the credential for each request, but it isn't stored |
| + (`personapi/types.go:16-21`). The lane is the origin, and it is enough. |
| + |
| +#### Decisions on cards |
| + |
| +- **"The jobs design's decisions on cards"** means phase 1 of |
| + `2026-11-20-jobs-that-keep-moving-design.md`, plus Paul's addendum on |
| + context and a recommendation: |
| + - **K1:** the job card carries `ask`, `options`, `actions` and |
| + `receipts`. |
| + - **K2:** one act endpoint, bound to the decision and its revision. |
| + - **K6:** stops, with their reasons and next steps. |
| + - **K11:** "What next?" on a first look. |
| + - **Addendum:** each decision gets context, a link, a recommended option |
| + and a line for each option. |
| + - Folding (K9) is phase 4. |
| +- **None of it is built.** |
| + - **Equipo:** there is no `JobAsk` and no job act route on origin/main. |
| + `decision-cards-context` (`cf0614ec`, 11-20) is unmerged. |
| + - **Base:** `equipo.Card` has no `Ask`, `Actions` or `Receipts` |
| + (`internal/equipo/chat.go:60-76`), and there is no `/ask/jobs/{id}/act` |
| + (`internal/web/ask.go:47-68`). |
| +- **What Base can act on today:** |
| + - question, confirm and outcome cards (`POST /ask/cards/{id}/answer`); |
| + - a paused job's Carry on now (`POST /ask/cards/{id}/carry_on`). |
| + - A job pill shows only its state, its status and one more sentence. |
| +- **Waiting cards** (Equipo `50029aba`) aren't something Base draws. They |
| + are a note in the Assistant's frame, listing Equipo's own open cards |
| + (`chat/waiting_cards.go`). |
| + |
| +#### Store and People on the web |
| + |
| +- **Store** (`internal/web/store.go:32-116`, `templates/store.html`): |
| + - It lists the catalogue: Welcome, Scratchpad and Contra |
| + (`internal/catalog/catalog.json`). |
| + - Each app shows its state: installing, installed or failed (with the |
| + reason). |
| + - The owner can Install, Try again, or Uninstall (with a confirm page). |
| + Everyone else sees "Installed". |
| + - The page refreshes every 2 s while anything is installing. |
| +- **People** (`internal/web/people.go:30-96`, `templates/people.html`): |
| + - It lists the members, each with their initial, name or address, and |
| + Owner, Member or Invited ("Invited. Hasn't signed in yet."). |
| + - The owner can invite by address. The invitation is sent again until one |
| + is delivered. |
| + - There is no Remove: `store.RemoveMember` exists but no route calls it. |
| +- **Neither has JSON.** The native app opens both on the web: |
| + `apiHomeRead` points Base's own pages at `origin + href` |
| + (`internal/web/api.go:115-118`). |
| + |
| +#### Files in Ask |
| + |
| +- **The server side is done.** Slice 1 landed on Base `07ec2ec` and in |
| + Equipo (`can_attach`, `wire/assistant.go:157`; `read_attachment`). |
| +- **Native has every route it needs**, documented in |
| + `docs/api/base-native-v1.md:262-311`: upload, delete, discard, read and |
| + preview. |
| +- **The app shows files only as a line of names** today |
| + (`BaseKit/Ask/Thread.swift:135-159`). |
| +- **Equipo's native code to copy (R5):** |
| + |
| + | File | What it does | |
| + |---|---| |
| + | `EquipoKit/API/Attachments.swift` | the client | |
| + | `Attachments/PhoneAttachmentPicker.swift` | `PhotosPicker`, `fileImporter`, paste | |
| + | `AttachmentDraft.swift` | draft state and refusal codes | |
| + | `AttachmentViews.swift` | the chips (`AttachmentDraftStrip`), the bubble's thumbnails (`MessageAttachments`), the full-size preview | |
| + | `native/share/Sources/EquipoShareCore/AttachmentFile.swift:58-93` | HEIC, HEIF and TIFF to JPEG, a 2560 px long edge | |
| + | `EquipoMac/MacComposer.swift:13-31`, `AttachmentPromises.swift` | paste, drag, and file promises on the Mac | |
| + |
| + Equipo has no Quick Look. |
| + |
| +#### Opening Docs, Sheets and Slides |
| + |
| +- **Base can launch the Docs or Sheets app, not open a document in it.** |
| + - On the Mac, `Opener.mac` opens the app by its bundle ID |
| + (`BaseKit/Home/Opener.swift:22`). |
| + - On the iPhone, everything except Calls and Equipo opens on the web |
| + (`Opener.swift:34`). |
| +- **The kit can open a path; the apps don't use it yet.** |
| + - The kit handles `<scheme>://open?path=…` (`rastrillo/native` |
| + `NativeConnection.swift:82-123`, since `8dc540a`). |
| + - Docs and Sheets pin kits from before that change (`0254817` and |
| + `1e36aac`), and neither sets `onOpen`. |
| +- **No universal links:** |
| + - The only association file is Home's, and it is webcredentials only |
| + (`home internal/home/native_passkey.go:285-312`). |
| + - The app hosts' `/.well-known/apple-app-site-association` answer 404. |
| + - No app claims `applinks:`. |
| +- **Slides has no native app**, and doesn't mount `/native/oficina-id`. |
| +- **Nothing can be framed, and there's no read-only view.** |
| + - Every app sends `frame-ancestors 'none'` and `X-Frame-Options: DENY` |
| + (`rastrillo serve.go:464,480`). |
| + - None has a signed-in read-only or embed view. |
| + - The only read-only pages are the owner's public links: Docs `/p/{token}`, |
| + Sheets `/l/{token}`, Slides `/s/{token}`. |
| +- **Exports exist:** |
| + - Docs: `/d/{sqid}/export.pdf` and `.md`. |
| + - Sheets: `/sheets/{id}/export.xlsx`. |
| + - Slides: a PDF job (`POST /d/{sqid}/export`). |
| +- **Path-based team URLs don't work natively.** `NativeHTTP.origin` rejects |
| + an origin with a path (`NativeHTTP.swift:94-100`), and Docs is the pilot |
| + for path-based teams (ruling 11-26). |
| + |
| +### 7.2 Notifications |
| + |
| +#### Who sends |
| + |
| +**Decided (7.9, 1): Equipo, through its outbox, to the Base app's |
| +registrations**, as 3.5 said. Equipo learns of every change in the |
| +transaction that makes it. It already has everything else: the outbox, |
| +once-only dedupe, collapse, holds, sealed payloads, retries, action |
| +bindings and receipts. Base would have to build all of that again. |
| + |
| +- **The app still talks only to Base** (3.2). |
| + - It registers its token with Base: `POST /api/v1/push` with `{token, |
| + environment, platform, install, start_token: null}`. |
| + - Base relays the registration to Equipo with the person's bearer, adding |
| + `app: "base"`. |
| + - Answers from a notification go to Base's own routes, as everything else |
| + does. |
| +- **The alternative** was Base sending. Equipo would call Base, as the |
| + Assistant's host, on every job change, and Base would keep its own |
| + devices, outbox and CARLOS grant. Rejected: it is a second outbox and a |
| + new callback channel, for words Equipo already writes. A job card's words |
| + are already Base-facing (Base shows them as given). |
| + |
| +#### What Equipo changes |
| + |
| +- **E-P1. Registrations know their app and device.** |
| + - `push_registrations` gains `app` (`equipo` | `base`) and `install` (the |
| + app install's id). |
| + - The key becomes `(credential, install)`. Base holds one Equipo |
| + credential per person, but that person may have Base on a Mac and on an |
| + iPhone. |
| + - The topic follows from `app`. `push.Topic` becomes a lookup. |
| +- **E-P2. One rule for where work started.** A change is Base's when: |
| + - its lane is `assistant` or starts `job:`; or |
| + - its task is in `chat_handoff_tasks`, which catches hand-offs from |
| + before job threads. |
| + |
| + The rule is computed once into `push.Change` as `Origin`, because |
| + `wire.Task` has no lane. Every rule then reads it: |
| + - Equipo-origin changes go only to `app = equipo` devices. |
| + - Base-origin changes go only to `app = base` devices. |
| + - The rules that don't look at the lane today (`task_ends`, `task_fails`, |
| + `badge`) gain the check. That stops Equipo's app hearing about Ask jobs, |
| + which fixes a breach of the ruling that exists today. |
| +- **E-P3. Base's rules, from the Assistant-lane job card**, not the task. |
| + - A job is a hand-off that may run several tasks. Base knows it by its |
| + job card id. |
| + - Each rule's collapse id is the job card's id, so a newer state replaces |
| + the older notification on every device. |
| + - Its thread id is `job:<card>`. |
| + - Its dedupe is the card's id, state and decision. |
| + - The table follows. |
| +- **E-P4. Base's payload.** |
| + - `aps.alert{title: job title, body: the decision's text or the state |
| + line}`, plus `category`, `thread-id` and `interruption-level`. |
| + - A custom key: |
| + ``` |
| + base: {origin, member, job, revision, decision, actions: {binding, notification_id}} |
| + ``` |
| + - The app needs `origin` and `member` to pick the right account, since |
| + the kit holds several. The words never name Equipo (Review 8). |
| +- **E-P5. Withdraw on settle.** |
| + - When a decision is settled anywhere (a tap, the web, another device), |
| + Equipo sends a background push for that job. |
| + - The app then removes the notifications delivered in its thread |
| + (`removeDeliveredNotifications`). |
| + - Each app also tidies itself whenever it opens. |
| +- **E-P6. The grant.** On each box running an Equipo that serves a Base: |
| + ``` |
| + key <BASE-KEY-ID> 9U4A84C4WK production works.oficina.base |
| + grant <equipo-sqid>/equipo works.oficina.base |
| + ``` |
| + The Live Activity topic `works.oficina.base.push-type.liveactivity` is |
| + allowed with it (CARLOS spec §5). |
| + |
| +#### Which job events notify |
| + |
| +Decided (7.9, 2): |
| + |
| +| Job state (Base's pill) | Notification | Actions (with K1/K2; until then, a tap opens the job) | |
| +|---|---|---| |
| +| Asking: a question | alert | its choices (recommended first, at most 3), and Something else… when words are allowed | |
| +| Asking: "First look ready" | alert | Build it; Try again… (asks "What should change?") | |
| +| Asking: needs your OK (approvals) or replace | alert | none: a tap opens the job (approvals stay on Equipo's pages, K6; Replace drops work) | |
| +| Ready to try | alert | Try it (opens the link) | |
| +| Stopped, with Try again offered | alert | Try again | |
| +| Stopped, otherwise | alert | none | |
| +| Paused | quiet (`passive`) | none: Carry on now spends money, so it stays in the app | |
| +| Done | quiet (`passive`) | none | |
| +| Working, any stage | never | (Live Activities, slice 3) | |
| +| The Assistant replied with no Ask open | alert, Ask's own (7.9, 4) | none | |
| + |
| +- **Never on a notification:** Drop it, Dismiss, Replace it, or anything |
| + that publishes, spends or grants without a confirm in the app. |
| +- **The badge** on the app's icon counts the jobs waiting on you, the same |
| + number as the sidebar's. |
| +- **In the foreground**, a job on screen shows no banner. Anything else |
| + shows one. |
| + |
| +#### The buttons |
| + |
| +- **Actions answer without opening the app.** They use |
| + `.authenticationRequired` and not `.foreground`, so the device must be |
| + unlocked. |
| + - Each is bound to the decision and revision the notification showed, with |
| + its notification id as the idempotency key. |
| + - A `409` (the decision has moved on) answers nothing. The app posts a |
| + local "That's changed since. Open it to see." with Open. |
| + - Equipo's buttons, by contrast, all bring the app forward |
| + (`NotificationResponse.swift:81-93`). |
| +- **Labels are the decision's own** ("Fri 18 Dec"), so categories can't be |
| + fixed ahead. |
| + - A notification service extension (iOS, and macOS 11 or later) registers |
| + one category per decision before the notification shows. |
| + - If that ever loses the race, the fallback is Equipo's: one "Choose…" |
| + that opens the app at the decision. (7.9, 3) |
| +- **On the Mac,** a banner's actions sit under Options. Alert style shows |
| + them as buttons. Both work the same. |
| + |
| +#### Not notifying twice |
| + |
| +- **By construction** (E-P2). A job started in Ask notifies only Base's |
| + devices, and a job started in Equipo only Equipo's. A person with both |
| + apps hears each job once. |
| +- **Across devices:** collapse by job, and withdraw on settle (E-P5). |
| +- **No fallback** (7.9, 5). With no Base app installed, an Ask |
| + job does not notify through Equipo's app. Web push for Base is for later. |
| + |
| +#### What slice 2 does so that slice 3 can take over Live Activities |
| + |
| +1. **The origin rule (E-P2) decides the Live Activity rules too.** |
| + - Slice 2 makes `activity_*` read `Origin`. |
| + - Until slice 3 ships, Base-origin tasks keep Equipo's Live Activity, as |
| + today (7.9, 6). |
| + - Then one Equipo release switches them to Base's start tokens. It |
| + switches only for people whose Base registration carries a |
| + `start_token`, so there is never both and never a gap. |
| +2. **Registrations carry `start_token` from day one** (null until slice 3). |
| + `app` decides the topic (`works.oficina.base.push-type.liveactivity`). |
| +3. **One activity per job, not per task.** Slice 2's collapse ids already |
| + map a task to its hand-off and then to its job card |
| + (`chat_handoff_tasks`). The activity reuses that mapping. |
| +4. **The payload names `origin` and `member`**, so the widget extension can |
| + pick the account. |
| +5. **The same Base push key serves Live Activities.** The extension needs |
| + its own App ID (`works.oficina.base.activity`) in slice 3. |
| + |
| +### 7.3 Decisions on the cards |
| + |
| +- **Native draws what the web draws, from the same JSON** (3.3). It does |
| + that once the jobs design's phase 1 is in Equipo and Base's web (7.9, 10), and |
| + is never built native-first. |
| +- **`Models.swift` gains** the K1 fields: `ask{kind, decision, text, words, |
| + note}`, `options`, `actions`, `receipts`, `updated_at` and `hidden`. It |
| + also gains the addendum's `context`, `link`, `recommended` and each |
| + option's `detail`. |
| +- **The pill** carries the decision under it, as the mockups show: |
| + - the context, the link to the thing, the question; |
| + - the choices, with Recommended and why; |
| + - Something else as a one-line field. |
| +- **Actions:** |
| + - Try again opens its field. |
| + - Drop it confirms ("Drop this job too?"). |
| + - Stops show their reason and Try again. |
| +- **The act:** `POST /ask/jobs/{id}/act` as JSON, with the idempotency key |
| + and revision. A `409` redraws the card from the answer. |
| +- **The job view** adds the first look's picture as a link, the receipts, |
| + Dismiss with Undo for 8 s, and "Open in Equipo" as the title's link. |
| +- **Placement:** jobs that need you move to the end of the thread. |
| + "Waiting on you" and "N finished" fold, by `state` and `updated_at` |
| + (K9, phase 4, when the web has it). |
| + |
| +### 7.4 Store and People, native |
| + |
| +A small JSON API beside the pages, built from the same builders, behind the |
| +same owner checks: |
| + |
| +- **`GET /api/v1/store`:** `{owner, rows: [{id, name, summary, tint, |
| + icon_svg, state, error}]}`. `state` is `""`, `installing`, `installed` or |
| + `failed`. |
| +- **`POST /api/v1/store/{app}/install`:** `202 {store}`, then poll every |
| + 2 s while any row is installing, as the web does. |
| + - An app already installing answers `202`, and one already installed |
| + `200`, both with the store and without starting anything. |
| + - If starting the install fails, the store is read again. A row that now |
| + shows installing (another request started it) answers `202` as it |
| + stands. Otherwise the answer is `503 unavailable`, and nothing was |
| + claimed: starting fails only before its claim, so a row that still |
| + reads failed shows an earlier failure. |
| +- **`POST /api/v1/store/{app}/uninstall`:** `200 {store}`, `409 busy` |
| + while installing, `403 owner_only` if not the owner. |
| +- **`GET /api/v1/people`:** `{owner, people: [{id, initial, name, email, |
| + role}]}`. `role` is `owner`, `member` or `invited` (not yet signed in), |
| + so no separate `joined` is sent. |
| +- **`POST /api/v1/people`:** `{email}`. It answers `200 {person}` with the |
| + person invited (or already here), `422 bad_email`, `502 mail_failed` |
| + (invite again to retry), or `403 owner_only`. |
| +- **Every route** answers `503 unavailable` when Base can't read its own |
| + store, as the pages do, and `401 unauthenticated` without a member's |
| + session. Nothing removes a member: `DELETE /api/v1/people/{id}` stays |
| + unrouted. |
| +- **Where they show:** |
| + - **Mac:** in the window's pane, from the sidebar. |
| + - **iPhone:** pushed from the apps sheet's new "Your team" section. |
| + - Uninstall confirms with the web's words. |
| +- **`GET /api/v1/home`'s** `own` apps keep their web URLs for older builds. |
| + New builds route Store and People natively by `id`. |
| +- **Not doing:** removing a member. The web has no such action either. |
| + |
| +### 7.5 The sidebar |
| + |
| +- **Apps folds** (Paul). |
| + - On both, the "Apps" heading is a button with a chevron: in the Mac's |
| + glass sidebar (which isn't a `List`, so not `Section(isExpanded:)`) and |
| + in the iPhone's apps sheet. |
| + - Folded, it shows the count. |
| + - The state is remembered for each person on each device, in |
| + `UserDefaults`. It is keyed by a hash of the signed-in account the |
| + session already holds, so it is right before `/api/v1/me` loads and |
| + offline. It isn't synced, and the web's rail setting (migration 0007) |
| + is its own. |
| + - It starts open. |
| +- **Made with Base.** Decided yes (7.9, 7). It lists what you made through |
| + Ask that has an address: |
| + - **What:** a published site, which shows a filled dot and its address; or |
| + a first look that is still up, which shows a hollow dot and "First |
| + look". Newest first, at most five, then "Show all". |
| + - **Whose:** only jobs started in Base (the ruling). Equipo's own projects |
| + stay in Equipo. |
| + - **Data:** |
| + - Published sites are in `chat_steps.publish`, and reach a task as |
| + `wire.Task.site{app, url, state, at}` (`wire/tasks.go:457`, |
| + `publish.go:102`). |
| + - A task's job is found through `chat_handoff_tasks`. |
| + - `chat_project_places` (0112) holds the deploy binding but no person. |
| + `GET /api/v1/projects` has no site URL (`api.go:302-334`). |
| + - So Equipo adds `GET /api/v1/assistant/made`: the person's Base-origin |
| + jobs with a site or a live first look, as `{job, title, url, kind, |
| + state, at}`. Base relays it as `GET /api/v1/made`, and the web can |
| + show it too. |
| + - **A click** opens the address in the browser. The context menu adds |
| + "Show the job" and "Copy address". |
| + - **Why yes:** it is what Base is for ("something to see very quickly"). |
| + Without it, a finished site falls out of the snapshot after 7 days |
| + (K9), and the only way back to it is Equipo. |
| + - **Why it might be no:** a new Equipo route and section for what may be |
| + only a handful of sites. It comes last in the slice for that reason. |
| + - **Later**, Docs and Sheets the Assistant made through `use` could list |
| + here too. |
| + |
| +### 7.6 Files in Ask, native (attachments slice 2) |
| + |
| +No server change: the routes exist. BaseKit copies Equipo's code (R5) and |
| +points it at Base's `/ask/attachments`. |
| + |
| +- **Mac:** |
| + - A paperclip left of Send opens the file panel. |
| + - Files can be dropped on the composer or anywhere on the window; the |
| + outline uses the web's words. |
| + - ⌘V pastes. A paste with words pastes the words (D8). Base's composer is |
| + a SwiftUI field, not Equipo's `NSTextView`, so Base takes Paste in its |
| + own Edit menu command and narrows the field's drag types. The plan |
| + says how, and when it falls back to Equipo's editor. |
| + - File promises are honoured, from Photos and Mail. |
| +- **iPhone:** a `+` left of the field, with Photos (`PhotosPicker`, no |
| + permission needed), Camera (`NSCameraUsageDescription`), Files and Paste |
| + (as Equipo's menu has). The field also takes a pasted image. |
| +- **On the device,** HEIC, HEIF and TIFF become JPEG, and anything over |
| + 2560 px is scaled down, before uploading (`AttachmentFile.swift`). A chip |
| + says "from HEIC". 48 MP photos stop being refused. |
| + - At most two files are prepared at once, behind the same gate as the |
| + uploads. A file whose size already rules it out is refused without |
| + being read. |
| + - Only converted output loses its metadata on the device. A PNG or JPEG |
| + at or under 2560 px goes up as it is, and Equipo strips an image's |
| + location on arrival (files spec 1.1). |
| +- **Chips:** |
| + - each has a thumbnail, name, size, an upload ring and Remove; |
| + - Remove deletes the upload; |
| + - uploads and chips survive the app going to the background. An upload |
| + in flight runs as a background task so it can finish. A lost answer |
| + shows Retry, and a retry is a second upload, so an orphan may count |
| + against the 20 for a day; |
| + - unsent uploads are discarded, as best the app can, when the session |
| + ends (`end()`: sign-out, account switch, a rejected session), bounded |
| + at 2 s. When another Oficina app signs the ID out, the session has |
| + gone before Base hears, so nothing can be discarded. Equipo's 24-hour |
| + drop catches that, a killed app, and quitting; |
| + - two uploads at a time. A busy answer is retried by itself up to three |
| + times with backoff, then the chip says busy and offers Retry; |
| + - the paperclip shows only while `can_attach`; |
| + - every refusal has the web's words (copy review 13), and the PDF chip |
| + says "Ask can't read PDFs yet."; |
| + - refused files never take Ask down (D5). |
| +- **In the thread:** thumbnails, then file pills, then the words, as the |
| + web draws them. |
| + - On the Mac, a click or Space opens Quick Look (`QLPreviewPanel`), with |
| + Open with Preview and Share. |
| + - On the iPhone, a tap opens `QLPreviewController`, with Share. |
| + - The original is fetched from `/ask/attachments/{id}` into the app's |
| + cache (7.9, 12): |
| + - **Path:** `Caches/Attachments/<account hash>/<attachment id>/<name>`. |
| + The name is its last path component, with the extension taken from |
| + the media type, so a file can't preview or open as another type. |
| + - **Protection:** kept out of backups. On iOS it uses |
| + `NSFileProtectionComplete`. |
| + - **When it's cleared:** |
| + - on `end()`, and when Ask is disconnected; |
| + - 14 days after the message was sent (the file's date is set to the |
| + message's at download); |
| + - folders of accounts no longer signed in are cleared too; |
| + - the sweep runs at launch, on each return to the foreground, and on |
| + the Mac each time a window opens and daily. |
| + - **One download per file:** a double tap shares it. |
| + - **Copies:** Share and Open with Preview hand a copy to another app, |
| + which is outside these rules once the person sends it there. |
| +- **Not doing:** Equipo's "recent screenshot" suggestion |
| + (`RecentScreenshot.swift`). It needs Photos permission. |
| + |
| +### 7.7 Opening Docs, Sheets and Slides |
| + |
| +#### In the right app (decided for slice 2: 7.9, 9) |
| + |
| +- **When a reply links an Oficina document,** Base opens it in the |
| + installed app with `works.oficina.docs://open?path=/d/<sqid>` (Sheets: |
| + `/sheets/<id>`), and otherwise on the web. |
| + - Base recognises a link by its host, from `BASE_OFICINA_APPS`, and by |
| + the app's path patterns. |
| + - On the iPhone, Base adds both schemes to `LSApplicationQueriesSchemes`. |
| +- **Each app needs** a kit repin to `8dc540a` or later, and an `onOpen` |
| + that routes the path to the document: |
| + - **Mac:** look up the local document by its sqid and open its window. |
| + - **iPhone:** push the document. |
| +- **Slides** opens on the web: it has no native app. |
| +- **Later:** universal links, once portero serves `applinks` (Home spec |
| + appendix D). They make the same links work from anywhere. |
| +- **Flag:** path-based team URLs (the Docs pilot) need `NativeHTTP.origin` |
| + to accept a path before any of this works for them. |
| + |
| +#### A read-only view inside Base (7.9, 8) |
| + |
| +| | WKWebView of the web app | Render from JSON | Quick Look of an export | |
| +|---|---|---|---| |
| +| **Sign-in** | Needs a web session in the view's cookie store. Home's slice D is for the default browser and isn't built. A cookie bridge (an exchanged native session put into `WKHTTPCookieStore`) is possible, but no spec sanctions it, and `/native/web/end` isn't served | An exchanged session for that app | An exchanged session: Base asks Oficina ID for an assertion addressed to Docs and trades it at Docs' `/native/oficina-id`, as it already does for Equipo. No second sign-in | |
| +| **What each app needs** | A read-only or embed view, which none has today. Framing headers don't matter to a top-level web view | Docs keeps only CRDT updates (`/d/{sqid}/updates`), so Base would need a Yjs reader and a renderer. Sheets' cells are workable | Nothing for Docs (PDF) or Sheets (XLSX). Slides needs `/native/oficina-id` mounted | |
| +| **Fidelity** | Exact and live | Base's own drawing, which drifts from each app | A faithful snapshot, not live | |
| +| **Cost** | High: a new view in three apps, plus a web-session story for embedded views and its security review | Highest, and duplicated per app | Lowest | |
| + |
| +- **Decided: Quick Look of the export now** (7.9, 8). |
| + - Mac: `QLPreviewView` in a pane beside Ask, as in the mockup. |
| + - iPhone: `QLPreviewController`. |
| + - The bar says "Read only" and holds **Edit in Oficina Docs**. It opens |
| + the Docs app at that document when it's installed (as above), and |
| + otherwise the web. |
| + - It reuses slice 2's Quick Look code, and the session is per app and |
| + asked for only when needed. |
| +- **WKWebView later**, once slice D gives embedded views a sanctioned |
| + sign-in and the apps have a read-only view. Then it becomes live. |
| +- **Placement:** after the rest of slice 2. Its Slides half waits on Slides |
| + mounting the exchange. |
| + |
| +### 7.8 Paul's portal steps (Apple Developer, team 9U4A84C4WK) |
| + |
| +1. **Identifiers → `works.oficina.base`:** |
| + - Tick **Push Notifications**, then Save. Changing a capability makes the |
| + existing profiles invalid. |
| + - Don't create a Push certificate: the key replaces it. |
| +2. **Keys → "+":** |
| + - Name: "Oficina Base Push Production". |
| + - Tick **Apple Push Notifications service (APNs)**, then Configure. |
| + - **Environment: Production.** TestFlight and Developer ID builds both |
| + use production. |
| + - **Key restriction: Topic Specific, topic `works.oficina.base`.** This |
| + matches Equipo's key, and CARLOS's decision 5 counts on a key for one |
| + topic. |
| + - Save, Continue, Register. |
| +3. **Download `AuthKey_<KEYID>.p8` once**, and note the Key ID. |
| + - Apple allows a single download. |
| + - It goes to the operator for `/etc/carlos-pusher/` on each box running |
| + an Equipo that serves a Base (E-P6). |
| + - It must never go in a repo or a chat. |
| + - Equipo's own `.p8` (`NS36T57NS4`) hasn't been downloaded yet either. |
| + Doing both in one sitting saves a second trip. |
| +4. **Profiles:** regenerate the iOS App Store profile and the macOS |
| + Developer ID profile for `works.oficina.base`, so that both carry |
| + `aps-environment`. Install them where the release scripts read |
| + `OFICINA_PROVISIONING_PROFILE`. |
| +5. **For the notification service extension (7.9, 3):** |
| + - register `works.oficina.base.notify` (iOS and macOS) with the App |
| + Group `group.works.oficina` on iOS and `9U4A84C4WK.works.oficina` on |
| + the Mac; |
| + - make its two profiles. |
| +6. **In slice 3 (not now):** `works.oficina.base.activity` for the widget |
| + extension. |
| + |
| +### 7.9 Paul's rulings (2026-11-28) |
| + |
| +Paul approved every recommendation as written. Each is now decided: |
| + |
| +1. **Who sends Base's notifications.** **Decided:** Equipo, through its |
| + outbox, to registrations Base relays (7.2). Alternative: Base sends. |
| +2. **Which job states notify.** **Decided:** the table in 7.2. Asking, |
| + first look, ready and stopped alert. Done and paused are quiet. Working |
| + never notifies. |
| +3. **Buttons on notifications.** **Decided:** |
| + - the decision's own choices, answered without opening the app, through |
| + a notification service extension; |
| + - never Drop, Replace, publishing or spending; |
| + - "Choose…" as the fallback. |
| +4. **Assistant replies.** When the Assistant answers and no Ask is open |
| + anywhere, should Base notify? **Decided:** yes, as Equipo does for its |
| + Coordinator (`reply_unseen`). |
| +5. **A person without the Base app.** Should Ask jobs fall back to Equipo's |
| + app? **Decided:** no, by the ruling. Web push for Base later. |
| +6. **Equipo's Live Activities for Ask jobs until slice 3.** **Decided:** |
| + keep them until Base's ship, then switch in one release (7.2), so |
| + there's never a gap. Alternative: stop them now. |
| +7. **"Made with Base" in the sidebar.** **Decided:** yes, named "Made |
| + with Base", listing published sites and live first looks from Ask jobs, |
| + with a new Equipo route. Last in the slice. Alternative names: "Your |
| + sites", "Things you made". |
| +8. **Reading a Doc inside Base.** **Decided:** Quick Look of the export |
| + now, with Edit in Oficina Docs; a web view later, after slice D. |
| +9. **Opening a linked Doc or Sheet in its app.** **Decided:** yes in |
| + slice 2, through `://open?path=`. It needs Docs and Sheets to repin and |
| + route the path. |
| +10. **Decisions on cards wait for the web.** **Decided:** yes. Native |
| + follows phase 1 on the web and is never built first, so both read the |
| + same JSON. |
| +11. **The push key.** **Decided:** a production, topic-specific key for |
| + `works.oficina.base`. Alternative: one team-wide key for every Oficina |
| + app. That is simpler, but it loses the per-app bound CARLOS relies on. |
| +12. **Opened files on the device.** **Decided:** kept in the app's cache, |
| + out of backups, cleared on sign-out and after 14 days (matching R3). |
| + Never anywhere else. |
| + |
| +### 7.10 Blockers |
| + |
| +- **B1. CARLOS `/v1/push`:** the spec is approved, but the build is |
| + uncommitted and undeployed (`carlos/platform-wt-push-build`). |
| +- **B2. rastrillo `push`:** uncommitted, no tag (`feat/push-submit`). |
| +- **B3. Equipo's transport seam:** `push/transport.go:50-64`. It also needs |
| + E-P1 to E-P6 (7.2). |
| +- **B4. Apple:** the Base push key doesn't exist yet, and Paul downloads it |
| + (7.8). The App ID needs Push Notifications and new profiles. Equipo's |
| + `.p8` isn't downloaded either. |
| +- **B5. The jobs design's phase 1** isn't built in Equipo or Base. It is |
| + needed for decisions on the cards and for notification buttons. |
| +- **B6. "Made with Base"** needs Equipo's `GET /api/v1/assistant/made`. |
| +- **B7. Opening documents** needs the Docs and Sheets kit repins and |
| + `onOpen`. Slides needs its exchange mounted. Path-based teams need the |
| + kit's origin fix. |
| + |
| +### 7.11 Slice plan |
| + |
| +In the plan's order (Paul, 2026-11-28). Within slice 2, the unblocked parts |
| +come first. |
| + |
| +1. **2a. No blockers.** |
| + - Store and People: the JSON API (7.4) and native screens. |
| + - Apps folding. |
| + - Files in Ask: native copy of Equipo's code, Quick Look, and the HEIC |
| + conversion. |
| + - Copy review of the new strings. |
| +2. **2b. Notifications, tap to open.** Needs B1 to B4. |
| + - Base: `POST /api/v1/push` relay. |
| + - Equipo: E-P1 to E-P6. |
| + - App: registration, categories, the badge, foreground rules, withdraw. |
| + - Ships without buttons. |
| +3. **2c. Decisions on the cards, and notification buttons.** Needs B5. |
| + - Pills, the job view, the act, folding when the web has it. |
| + - Then the service extension and the bound actions. |
| +4. **2d. Made with Base, and opening documents.** Needs B6 and B7. |
| + - The sidebar section. |
| + - `://open` into Docs and Sheets. |
| + - The Quick Look viewer with Edit in Oficina Docs. |
| + |
| +The mockups are signed off (2026-11-28). Each part gets a plan, reviews as before, |
| +and TestFlight and Sparkle releases. |
| + |
| +### 7.12 Not doing in slice 2 |
| + |
| +- Siri, Shortcuts, the share extension and Live Activities: slice 3. |
| +- Removing members natively. |
| +- Base paths for approvals (K6 keeps them on Equipo's pages). |
| +- A live embedded editor of any Oficina app. |
diff --git a/internal/web/api_team.go b/internal/web/api_team.go| new file mode 100644 |
| index 0000000..b278838 |
| --- /dev/null |
| +++ b/internal/web/api_team.go |
| @@ -0,0 +1,232 @@ |
| +package web |
| + |
| +import ( |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "net/http" |
| + |
| + "github.com/go-chi/chi/v5" |
| + |
| + "amadan.net/oficina/base/internal/catalog" |
| + "amadan.net/oficina/base/internal/install" |
| + "amadan.net/oficina/base/internal/store" |
| +) |
| + |
| +// Store and People for the native app (docs/api/base-native-v1.md "Store" |
| +// and "People"): what the pages of the same names show, from the same |
| +// builders, behind the same member gate and owner checks. |
| + |
| +type apiStoreRow struct { |
| + ID string `json:"id"` |
| + Name string `json:"name"` |
| + Summary string `json:"summary"` |
| + Tint string `json:"tint"` |
| + IconSVG string `json:"icon_svg"` |
| + // State is "", "installing", "installed" or "failed"; Error is a |
| + // failed install's reason, and may be "". |
| + State string `json:"state"` |
| + Error string `json:"error"` |
| +} |
| + |
| +type apiStore struct { |
| + Owner bool `json:"owner"` |
| + Rows []apiStoreRow `json:"rows"` |
| +} |
| + |
| +func storeJSON(c storeContent) apiStore { |
| + out := apiStore{Owner: c.IsOwner, Rows: []apiStoreRow{}} |
| + for _, r := range c.Rows { |
| + out.Rows = append(out.Rows, apiStoreRow{ID: r.ID, Name: r.Name, Summary: r.Summary, Tint: r.Tint, IconSVG: r.Icon, State: r.State, Error: r.Error}) |
| + } |
| + return out |
| +} |
| + |
| +type apiPerson struct { |
| + ID string `json:"id"` |
| + Initial string `json:"initial"` |
| + // Name is "" for someone who has given none; show Email then. |
| + Name string `json:"name"` |
| + Email string `json:"email"` |
| + // Role is "owner", "member" or "invited" (not yet signed in). |
| + Role string `json:"role"` |
| +} |
| + |
| +type apiPeople struct { |
| + Owner bool `json:"owner"` |
| + People []apiPerson `json:"people"` |
| +} |
| + |
| +func personJSON(p personRow) apiPerson { |
| + return apiPerson{ID: p.ID, Initial: p.Initial, Name: p.Name, Email: p.Email, Role: p.Role} |
| +} |
| + |
| +// apiStoreRead is GET /api/v1/store. |
| +func (a *app) apiStoreRead(w http.ResponseWriter, r *http.Request) { |
| + me, _ := CurrentMember(r) |
| + c, err := a.storeContent(r.Context(), me) |
| + if err != nil { |
| + a.logger.Error("api store", "err", err) |
| + writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"}) |
| + return |
| + } |
| + writeJSON(w, http.StatusOK, storeJSON(c)) |
| +} |
| + |
| +// apiPeopleRead is GET /api/v1/people. |
| +func (a *app) apiPeopleRead(w http.ResponseWriter, r *http.Request) { |
| + me, _ := CurrentMember(r) |
| + c, err := a.peopleContent(r.Context(), me) |
| + if err != nil { |
| + a.logger.Error("api people", "err", err) |
| + writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"}) |
| + return |
| + } |
| + out := apiPeople{Owner: c.IsOwner, People: []apiPerson{}} |
| + for _, p := range c.People { |
| + out.People = append(out.People, personJSON(p)) |
| + } |
| + writeJSON(w, http.StatusOK, out) |
| +} |
| + |
| +// apiStoreAnswer is a Store write's answer: the store as it now stands. |
| +type apiStoreAnswer struct { |
| + Store apiStore `json:"store"` |
| +} |
| + |
| +// apiOwner is the catalogue entry named in the URL when the member asking |
| +// is the owner. Otherwise it answers 403 owner_only or 404 unknown_app, in |
| +// that order, as the page's owner check does. |
| +func (a *app) apiOwner(w http.ResponseWriter, me store.Member, id string) (catalog.Entry, bool) { |
| + if me.Role != "owner" { |
| + writeJSON(w, http.StatusForbidden, apiError{Code: "owner_only"}) |
| + return catalog.Entry{}, false |
| + } |
| + e, ok := catalog.Get(id) |
| + if !ok { |
| + writeJSON(w, http.StatusNotFound, apiError{Code: "unknown_app"}) |
| + return catalog.Entry{}, false |
| + } |
| + return e, true |
| +} |
| + |
| +// apiStoreInstall is POST /api/v1/store/{app}/install. It answers 202 with |
| +// the app installing, and the app polls the store until it isn't. An app |
| +// already installing answers 202 and one installed 200, and neither starts |
| +// anything. Start returns an error only from before its claim (install.go), |
| +// so when it fails the store is read again: a row that now reads installing |
| +// was claimed by another request and is answered 202 as it stands, and |
| +// anything else, a failed row included (that failure is an earlier one), |
| +// is 503: this attempt never started. |
| +func (a *app) apiStoreInstall(w http.ResponseWriter, r *http.Request) { |
| + me, _ := CurrentMember(r) |
| + e, ok := a.apiOwner(w, me, chi.URLParam(r, "app")) |
| + if !ok { |
| + return |
| + } |
| + c, err := a.storeContent(r.Context(), me) |
| + if err != nil { |
| + a.logger.Error("api install", "app", e.ID, "err", err) |
| + writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"}) |
| + return |
| + } |
| + switch row, _ := c.row(e.ID); row.State { |
| + case "installing": |
| + writeJSON(w, http.StatusAccepted, apiStoreAnswer{storeJSON(c)}) |
| + return |
| + case "installed": |
| + writeJSON(w, http.StatusOK, apiStoreAnswer{storeJSON(c)}) |
| + return |
| + } |
| + startErr := a.inst.Start(r.Context(), e.ID) |
| + if startErr != nil { |
| + a.logger.Error("api install", "app", e.ID, "err", startErr) |
| + } |
| + if c, err = a.storeContent(r.Context(), me); err != nil { |
| + a.logger.Error("api install", "app", e.ID, "err", err) |
| + writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"}) |
| + return |
| + } |
| + if row, _ := c.row(e.ID); startErr != nil && row.State != "installing" { |
| + writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"}) |
| + return |
| + } |
| + writeJSON(w, http.StatusAccepted, apiStoreAnswer{storeJSON(c)}) |
| +} |
| + |
| +// apiStoreUninstall is POST /api/v1/store/{app}/uninstall: 200 with the |
| +// store, also when it was uninstalled already, and 409 busy while it is |
| +// still installing. |
| +func (a *app) apiStoreUninstall(w http.ResponseWriter, r *http.Request) { |
| + me, _ := CurrentMember(r) |
| + e, ok := a.apiOwner(w, me, chi.URLParam(r, "app")) |
| + if !ok { |
| + return |
| + } |
| + switch err := a.inst.Uninstall(r.Context(), e.ID); { |
| + case errors.Is(err, install.ErrBusy): |
| + writeJSON(w, http.StatusConflict, apiError{Code: "busy"}) |
| + return |
| + case errors.Is(err, store.ErrNoInstall): |
| + // Already uninstalled. |
| + case err != nil: |
| + a.logger.Error("api uninstall", "app", e.ID, "err", err) |
| + writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"}) |
| + return |
| + } |
| + c, err := a.storeContent(r.Context(), me) |
| + if err != nil { |
| + a.logger.Error("api uninstall", "app", e.ID, "err", err) |
| + writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"}) |
| + return |
| + } |
| + writeJSON(w, http.StatusOK, apiStoreAnswer{storeJSON(c)}) |
| +} |
| + |
| +// maxInviteBody bounds POST /api/v1/people's body, {"email": …}. |
| +const maxInviteBody = 4 << 10 |
| + |
| +// apiPeopleInvite is POST /api/v1/people, {"email": …}: the People form's |
| +// invitation, as JSON. It answers 200 with the person, invited now or |
| +// already here. |
| +func (a *app) apiPeopleInvite(w http.ResponseWriter, r *http.Request) { |
| + me, _ := CurrentMember(r) |
| + if me.Role != "owner" { |
| + writeJSON(w, http.StatusForbidden, apiError{Code: "owner_only"}) |
| + return |
| + } |
| + if !isJSONBody(r) { |
| + writeJSON(w, http.StatusUnsupportedMediaType, apiError{Code: "json_only"}) |
| + return |
| + } |
| + raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxInviteBody)) |
| + if err != nil { |
| + if mbe := (*http.MaxBytesError)(nil); errors.As(err, &mbe) { |
| + writeJSON(w, http.StatusRequestEntityTooLarge, apiError{Code: "too_large"}) |
| + return |
| + } |
| + writeJSON(w, http.StatusBadRequest, apiError{Code: "bad_request"}) |
| + return |
| + } |
| + var in struct { |
| + Email string `json:"email"` |
| + } |
| + if err := json.Unmarshal(raw, &in); err != nil { |
| + writeJSON(w, http.StatusBadRequest, apiError{Code: "bad_request"}) |
| + return |
| + } |
| + m, res, err := a.invitePerson(r.Context(), in.Email) |
| + switch { |
| + case err != nil: |
| + a.logger.Error("api invite", "err", err) |
| + writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"}) |
| + case res == inviteBadEmail: |
| + writeJSON(w, http.StatusUnprocessableEntity, apiError{Code: "bad_email"}) |
| + case res == inviteMailFailed: |
| + writeJSON(w, http.StatusBadGateway, apiError{Code: "mail_failed"}) |
| + default: |
| + writeJSON(w, http.StatusOK, struct { |
| + Person apiPerson `json:"person"` |
| + }{personJSON(personFor(m))}) |
| + } |
| +} |
diff --git a/internal/web/app.go b/internal/web/app.go| index ce5b2e1..6f429c9 100644 |
| --- a/internal/web/app.go |
| +++ b/internal/web/app.go |
| @@ -213,6 +213,11 @@ func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger |
| r.Post("/settings/appearance", a.settingsAppearance) |
| r.Get("/api/v1/me", a.apiMeRead) |
| r.Get("/api/v1/home", a.apiHomeRead) |
| + r.Get("/api/v1/store", a.apiStoreRead) |
| + r.Get("/api/v1/people", a.apiPeopleRead) |
| + r.Post("/api/v1/store/{app}/install", a.apiStoreInstall) |
| + r.Post("/api/v1/store/{app}/uninstall", a.apiStoreUninstall) |
| + r.Post("/api/v1/people", a.apiPeopleInvite) |
| r.With(ownSignInOnly).Post(registerBeginPath, a.pk.RegisterBegin) |
| r.With(ownSignInOnly).Post(registerFinishPath, a.pk.RegisterFinish) |
| r.Method(http.MethodGet, "/authorize", authorize) |
diff --git a/internal/web/main_test.go b/internal/web/main_test.go| index f5e07b5..2ce8b44 100644 |
| --- a/internal/web/main_test.go |
| +++ b/internal/web/main_test.go |
| @@ -7,4 +7,8 @@ import ( |
| "amadan.net/rastrillo/rastrillo/budget" |
| ) |
| -func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } |
| +func TestMain(m *testing.M) { |
| + code := budget.Main(m) |
| + teamSchema.Remove() |
| + os.Exit(code) |
| +} |
diff --git a/internal/web/people.go b/internal/web/people.go| index 576a892..a46bc8b 100644 |
| --- a/internal/web/people.go |
| +++ b/internal/web/people.go |
| @@ -12,81 +12,145 @@ import ( |
| ) |
| type personRow struct { |
| + ID string |
| Initial string |
| Name string |
| Email string |
| - Owner bool |
| - Joined bool |
| + // Role is "owner", "member" (signed in at least once) or "invited" |
| + // (not yet), as the page's tag says. |
| + Role string |
| + Owner bool |
| + // Joined is true once they have signed in. |
| + Joined bool |
| } |
| type peoplePage struct { |
| - Name string |
| - IsOwner bool |
| + Name string |
| + peopleContent |
| BadEmail bool |
| MailFailed bool |
| - People []personRow |
| } |
| -func (a *app) people(w http.ResponseWriter, r *http.Request) { |
| - me, _ := CurrentMember(r) |
| - ms, err := store.Members(r.Context(), a.db) |
| +// peopleContent is what People shows a member: everyone here, in the |
| +// order they were invited. The People page and the JSON (GET |
| +// /api/v1/people) both draw from it. |
| +type peopleContent struct { |
| + IsOwner bool |
| + People []personRow |
| +} |
| + |
| +func (a *app) peopleContent(ctx context.Context, me store.Member) (peopleContent, error) { |
| + ms, err := store.Members(ctx, a.db) |
| if err != nil { |
| - a.logger.Error("people: list", "err", err) |
| - http.Error(w, "unavailable", http.StatusServiceUnavailable) |
| - return |
| + return peopleContent{}, fmt.Errorf("members: %w", err) |
| } |
| - page := peoplePage{Name: a.cfg.Name, IsOwner: me.Role == "owner", BadEmail: r.URL.Query().Get("problem") == "email", MailFailed: r.URL.Query().Get("problem") == "mail"} |
| + c := peopleContent{IsOwner: me.Role == "owner"} |
| for _, m := range ms { |
| - label := m.Name |
| - if label == "" { |
| - label = m.Email |
| - } |
| - page.People = append(page.People, personRow{ |
| - Initial: strings.ToUpper(string([]rune(label)[:1])), |
| - Name: m.Name, Email: m.Email, |
| - Owner: m.Role == "owner", Joined: m.JoinedAt != nil, |
| - }) |
| + c.People = append(c.People, personFor(m)) |
| } |
| - w.Header().Set("Cache-Control", "no-store") |
| - a.render(w, r, "people", page) |
| + return c, nil |
| } |
| -// invite adds a teammate and emails them where to sign in. Only the owner may. |
| -// Inviting an address that is already here changes nothing and sends nothing. |
| -func (a *app) invite(w http.ResponseWriter, r *http.Request) { |
| +func personFor(m store.Member) personRow { |
| + label := m.Name |
| + if label == "" { |
| + label = m.Email |
| + } |
| + p := personRow{ |
| + ID: m.ID, |
| + Initial: strings.ToUpper(string([]rune(label)[:1])), |
| + Name: m.Name, Email: m.Email, |
| + Owner: m.Role == "owner", Joined: m.JoinedAt != nil, |
| + } |
| + switch { |
| + case p.Owner: |
| + p.Role = "owner" |
| + case p.Joined: |
| + p.Role = "member" |
| + default: |
| + p.Role = "invited" |
| + } |
| + return p |
| +} |
| + |
| +func (a *app) people(w http.ResponseWriter, r *http.Request) { |
| me, _ := CurrentMember(r) |
| - if me.Role != "owner" { |
| - http.Error(w, "forbidden", http.StatusForbidden) |
| + c, err := a.peopleContent(r.Context(), me) |
| + if err != nil { |
| + a.logger.Error("people", "err", err) |
| + http.Error(w, "unavailable", http.StatusServiceUnavailable) |
| return |
| } |
| - email := strings.ToLower(strings.TrimSpace(r.PostFormValue("email"))) |
| + w.Header().Set("Cache-Control", "no-store") |
| + a.render(w, r, "people", peoplePage{Name: a.cfg.Name, peopleContent: c, |
| + BadEmail: r.URL.Query().Get("problem") == "email", MailFailed: r.URL.Query().Get("problem") == "mail"}) |
| +} |
| + |
| +// inviteResult is how an invitation went, apart from Base failing to read |
| +// or write its own store. |
| +type inviteResult int |
| + |
| +const ( |
| + // inviteOK: the person is here, invited now or before. |
| + inviteOK inviteResult = iota |
| + // inviteBadEmail: what was given isn't one plain email address. |
| + inviteBadEmail |
| + // inviteMailFailed: they are invited, but the email wasn't delivered. |
| + // Inviting them again sends it. |
| + inviteMailFailed |
| +) |
| + |
| +// invitePerson adds a teammate by address, trimmed and lowercased, and |
| +// emails them where to sign in. An address already here changes nothing. |
| +// It sends until one invitation has been delivered, so a failed send is |
| +// retried by inviting again. The caller checks that the member asking is |
| +// the owner. |
| +func (a *app) invitePerson(ctx context.Context, raw string) (store.Member, inviteResult, error) { |
| + email := strings.ToLower(strings.TrimSpace(raw)) |
| addr, err := netmail.ParseAddress(email) |
| if err != nil || addr.Address != email || addr.Name != "" { |
| - http.Redirect(w, r, "/people?problem=email", http.StatusSeeOther) |
| - return |
| + return store.Member{}, inviteBadEmail, nil |
| } |
| - m, _, err := store.Invite(r.Context(), a.db, email) |
| + m, _, err := store.Invite(ctx, a.db, email) |
| if err != nil { |
| - a.logger.Error("invite", "err", err) |
| - http.Error(w, "unavailable", http.StatusServiceUnavailable) |
| - return |
| + return store.Member{}, 0, fmt.Errorf("invite: %w", err) |
| } |
| - // Send until one invitation has been delivered, so a failed send can be |
| - // retried by inviting again. |
| if m.Role == "member" && m.JoinedAt == nil && m.InviteSentAt == nil { |
| - ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), 20*time.Second) |
| + // The send outlives the request: a person who gives up waiting |
| + // mustn't leave a half-sent invitation. |
| + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 20*time.Second) |
| defer cancel() |
| subject, body := invitationEmail(a.cfg.Name, a.cfg.Origin) |
| if err := a.mailer.Send(ctx, email, subject, body); err != nil { |
| a.logger.Error("invite: send", "err", err) |
| - http.Redirect(w, r, "/people?problem=mail", http.StatusSeeOther) |
| - return |
| + return m, inviteMailFailed, nil |
| } |
| if err := store.MarkInviteSent(ctx, a.db, m.ID); err != nil { |
| a.logger.Error("invite: mark sent", "err", err) |
| } |
| } |
| - http.Redirect(w, r, "/people", http.StatusSeeOther) |
| + return m, inviteOK, nil |
| +} |
| + |
| +// invite is the People page's form. Only the owner may. |
| +func (a *app) invite(w http.ResponseWriter, r *http.Request) { |
| + me, _ := CurrentMember(r) |
| + if me.Role != "owner" { |
| + http.Error(w, "forbidden", http.StatusForbidden) |
| + return |
| + } |
| + _, res, err := a.invitePerson(r.Context(), r.PostFormValue("email")) |
| + switch { |
| + case err != nil: |
| + a.logger.Error("invite", "err", err) |
| + http.Error(w, "unavailable", http.StatusServiceUnavailable) |
| + case res == inviteBadEmail: |
| + http.Redirect(w, r, "/people?problem=email", http.StatusSeeOther) |
| + case res == inviteMailFailed: |
| + http.Redirect(w, r, "/people?problem=mail", http.StatusSeeOther) |
| + default: |
| + http.Redirect(w, r, "/people", http.StatusSeeOther) |
| + } |
| } |
| func invitationEmail(name, origin string) (subject, body string) { |
diff --git a/internal/web/store.go b/internal/web/store.go| index 81e6c37..f2f29c8 100644 |
| --- a/internal/web/store.go |
| +++ b/internal/web/store.go |
| @@ -1,7 +1,9 @@ |
| package web |
| import ( |
| + "context" |
| "errors" |
| + "fmt" |
| "html/template" |
| "net/http" |
| @@ -22,35 +24,60 @@ type storeRow struct { |
| func (s storeRow) IconHTML() template.HTML { return template.HTML(s.Icon) } |
| type storePage struct { |
| - Name string |
| + Name string |
| + storeContent |
| + Busy bool |
| +} |
| + |
| +// storeContent is what the Store shows a member: a row per catalogue |
| +// entry, in the catalogue's order, with its install's state and error. The |
| +// Store page and the JSON (GET /api/v1/store) both draw from it. |
| +type storeContent struct { |
| IsOwner bool |
| - Busy bool |
| Installing bool |
| Rows []storeRow |
| } |
| -func (a *app) storePage(w http.ResponseWriter, r *http.Request) { |
| - me, _ := CurrentMember(r) |
| - installs, err := store.Installs(r.Context(), a.db) |
| +// row is the entry id's row, and false when the catalogue has no such app. |
| +func (c storeContent) row(id string) (storeRow, bool) { |
| + for _, r := range c.Rows { |
| + if r.ID == id { |
| + return r, true |
| + } |
| + } |
| + return storeRow{}, false |
| +} |
| + |
| +func (a *app) storeContent(ctx context.Context, me store.Member) (storeContent, error) { |
| + installs, err := store.Installs(ctx, a.db) |
| if err != nil { |
| - a.logger.Error("store: installs", "err", err) |
| - http.Error(w, "unavailable", http.StatusServiceUnavailable) |
| - return |
| + return storeContent{}, fmt.Errorf("installs: %w", err) |
| } |
| state := map[string]store.Install{} |
| for _, in := range installs { |
| state[in.App] = in |
| } |
| - page := storePage{Name: a.cfg.Name, IsOwner: me.Role == "owner", Busy: r.URL.Query().Get("problem") == "busy"} |
| + c := storeContent{IsOwner: me.Role == "owner"} |
| for _, e := range catalog.All() { |
| in := state[e.ID] |
| - page.Rows = append(page.Rows, storeRow{Entry: e, State: in.State, Error: in.Error}) |
| + c.Rows = append(c.Rows, storeRow{Entry: e, State: in.State, Error: in.Error}) |
| if in.State == "installing" { |
| - page.Installing = true |
| + c.Installing = true |
| } |
| } |
| + return c, nil |
| +} |
| + |
| +func (a *app) storePage(w http.ResponseWriter, r *http.Request) { |
| + me, _ := CurrentMember(r) |
| + c, err := a.storeContent(r.Context(), me) |
| + if err != nil { |
| + a.logger.Error("store", "err", err) |
| + http.Error(w, "unavailable", http.StatusServiceUnavailable) |
| + return |
| + } |
| w.Header().Set("Cache-Control", "no-store") |
| - a.render(w, r, "store", page) |
| + a.render(w, r, "store", storePage{Name: a.cfg.Name, storeContent: c, Busy: r.URL.Query().Get("problem") == "busy"}) |
| } |
| // owner returns the catalogue entry named in the URL when the signed-in |
diff --git a/internal/web/team_internal_test.go b/internal/web/team_internal_test.go| new file mode 100644 |
| index 0000000..1029e1d |
| --- /dev/null |
| +++ b/internal/web/team_internal_test.go |
| @@ -0,0 +1,235 @@ |
| +package web |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "log/slog" |
| + "strings" |
| + "sync" |
| + "testing" |
| + |
| + "amadan.net/rastrillo/rastrillo/dbtest" |
| + |
| + "amadan.net/oficina/base/internal/catalog" |
| + "amadan.net/oficina/base/internal/config" |
| + "amadan.net/oficina/base/internal/store" |
| +) |
| + |
| +// The Store and People builders, shared by the pages and their JSON |
| +// (docs/api/base-native-v1.md "Store" and "People"). |
| + |
| +var teamSchema = dbtest.FromSet(store.BootSchema) |
| + |
| +// teamMailer records what it sends, or fails while fail is set. |
| +type teamMailer struct { |
| + mu sync.Mutex |
| + to []string |
| + fail bool |
| +} |
| + |
| +func (m *teamMailer) Send(_ context.Context, to, _, _ string) error { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + if m.fail { |
| + return errors.New("smtp down") |
| + } |
| + m.to = append(m.to, to) |
| + return nil |
| +} |
| + |
| +func (m *teamMailer) sent() int { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + return len(m.to) |
| +} |
| + |
| +// teamApp is just enough of the app for the builders: a database with the |
| +// owner in it, a name and origin, and a mailer. |
| +func teamApp(t *testing.T) (*app, *teamMailer, store.Member) { |
| + t.Helper() |
| + db := teamSchema.Open(t) |
| + if err := store.Bootstrap(t.Context(), db, "owner@acme.test"); err != nil { |
| + t.Fatal(err) |
| + } |
| + owner, _, err := store.MemberByEmail(t.Context(), db, "owner@acme.test") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + m := &teamMailer{} |
| + return &app{db: db, cfg: config.Config{Name: "Acme", Origin: "https://base.acme.test"}, mailer: m, logger: slog.New(slog.DiscardHandler)}, m, owner |
| +} |
| + |
| +func setInstall(t *testing.T, db *sql.DB, app, state, errMsg string) { |
| + t.Helper() |
| + if _, err := db.Exec(`INSERT INTO installs (app, host, state, error, updated_at) VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP) |
| + ON CONFLICT (app) DO UPDATE SET state = excluded.state, error = excluded.error`, app, app+".acme.test", state, errMsg); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func TestStoreContent(t *testing.T) { |
| + a, _, owner := teamApp(t) |
| + all := catalog.All() |
| + if len(all) < 3 { |
| + t.Fatalf("the catalogue has %d entries; this test needs three", len(all)) |
| + } |
| + setInstall(t, a.db, all[0].ID, "installed", "") |
| + setInstall(t, a.db, all[1].ID, "failed", "The app did not start answering") |
| + |
| + c, err := a.storeContent(t.Context(), owner) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !c.IsOwner || c.Installing { |
| + t.Errorf("owner %v, installing %v", c.IsOwner, c.Installing) |
| + } |
| + if len(c.Rows) != len(all) { |
| + t.Fatalf("%d rows for %d catalogue entries", len(c.Rows), len(all)) |
| + } |
| + for i, e := range all { |
| + if c.Rows[i].ID != e.ID { |
| + t.Fatalf("row %d is %q, want the catalogue's order (%q)", i, c.Rows[i].ID, e.ID) |
| + } |
| + } |
| + if r := c.Rows[0]; r.State != "installed" || r.Error != "" { |
| + t.Errorf("installed row: %+v", r) |
| + } |
| + if r := c.Rows[1]; r.State != "failed" || r.Error != "The app did not start answering" { |
| + t.Errorf("failed row: %+v", r) |
| + } |
| + if r := c.Rows[2]; r.State != "" { |
| + t.Errorf("an app never installed: state %q", r.State) |
| + } |
| + |
| + setInstall(t, a.db, all[2].ID, "installing", "") |
| + member, _, err := store.Invite(t.Context(), a.db, "maria@acme.test") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c, err = a.storeContent(t.Context(), member) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if c.IsOwner || !c.Installing || c.Rows[2].State != "installing" { |
| + t.Errorf("a member, with one installing: owner %v, installing %v, %+v", c.IsOwner, c.Installing, c.Rows[2]) |
| + } |
| + |
| + // A failed read is an error, never an empty store. |
| + if _, err := a.db.Exec(`DROP TABLE installs`); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := a.storeContent(t.Context(), owner); err == nil { |
| + t.Error("storeContent with the installs unreadable: no error") |
| + } |
| +} |
| + |
| +func TestPeopleContent(t *testing.T) { |
| + a, _, owner := teamApp(t) |
| + ana, _, err := store.Invite(t.Context(), a.db, "ana@acme.test") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := a.db.Exec(`UPDATE members SET name = 'Ana Ruiz' WHERE id = ?`, ana.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := store.MarkJoined(t.Context(), a.db, ana.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := store.MarkJoined(t.Context(), a.db, owner.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + maria, _, err := store.Invite(t.Context(), a.db, "maria@acme.test") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + c, err := a.peopleContent(t.Context(), owner) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !c.IsOwner { |
| + t.Error("the owner reads as not the owner") |
| + } |
| + var got []string |
| + for _, p := range c.People { |
| + got = append(got, strings.Join([]string{p.ID, p.Initial, p.Name, p.Email, p.Role}, "|")) |
| + } |
| + want := []string{ |
| + owner.ID + "|O||owner@acme.test|owner", |
| + ana.ID + "|A|Ana Ruiz|ana@acme.test|member", |
| + maria.ID + "|M||maria@acme.test|invited", |
| + } |
| + if strings.Join(got, "\n") != strings.Join(want, "\n") { |
| + t.Fatalf("people:\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) |
| + } |
| + |
| + c, err = a.peopleContent(t.Context(), maria) |
| + if err != nil || c.IsOwner { |
| + t.Errorf("a member: owner %v, %v", c.IsOwner, err) |
| + } |
| + |
| + if _, err := a.db.Exec(`DROP TABLE members`); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := a.peopleContent(t.Context(), owner); err == nil { |
| + t.Error("peopleContent with the members unreadable: no error") |
| + } |
| +} |
| + |
| +func TestInvitePerson(t *testing.T) { |
| + a, mail, owner := teamApp(t) |
| + ctx := t.Context() |
| + |
| + m, res, err := a.invitePerson(ctx, " Maria@Acme.test ") |
| + if err != nil || res != inviteOK || m.Email != "maria@acme.test" || m.Role != "member" { |
| + t.Fatalf("invite: %+v %v %v", m, res, err) |
| + } |
| + if mail.sent() != 1 { |
| + t.Fatalf("%d invitations sent, want 1", mail.sent()) |
| + } |
| + // Delivered once, it is never sent again. |
| + again, res, err := a.invitePerson(ctx, "maria@acme.test") |
| + if err != nil || res != inviteOK || again.ID != m.ID || mail.sent() != 1 { |
| + t.Fatalf("invite again: %+v %v %v, %d sent", again, res, err, mail.sent()) |
| + } |
| + // An address already here, the owner's, sends nothing and answers them. |
| + if o, res, err := a.invitePerson(ctx, "owner@acme.test"); err != nil || res != inviteOK || o.ID != owner.ID || mail.sent() != 1 { |
| + t.Fatalf("invite the owner: %+v %v %v, %d sent", o, res, err, mail.sent()) |
| + } |
| + |
| + for _, bad := range []string{"", "not an email", "Maria <maria@acme.test>", "maria@acme.test, bob@acme.test"} { |
| + if _, res, err := a.invitePerson(ctx, bad); err != nil || res != inviteBadEmail { |
| + t.Errorf("invite %q: %v %v", bad, res, err) |
| + } |
| + } |
| + if ms, _ := store.Members(ctx, a.db); len(ms) != 2 { |
| + t.Errorf("%d members after the bad addresses, want 2", len(ms)) |
| + } |
| + |
| + // A failed send leaves the member invited with nothing delivered, so |
| + // inviting again sends. |
| + mail.mu.Lock() |
| + mail.fail = true |
| + mail.mu.Unlock() |
| + if _, res, err := a.invitePerson(ctx, "bob@acme.test"); err != nil || res != inviteMailFailed { |
| + t.Fatalf("invite with the mail down: %v %v", res, err) |
| + } |
| + mail.mu.Lock() |
| + mail.fail = false |
| + mail.mu.Unlock() |
| + if b, res, err := a.invitePerson(ctx, "bob@acme.test"); err != nil || res != inviteOK || b.Email != "bob@acme.test" || mail.sent() != 2 { |
| + t.Fatalf("invite after the failure: %+v %v %v, %d sent", b, res, err, mail.sent()) |
| + } |
| + if b, _, _ := store.MemberByEmail(ctx, a.db, "bob@acme.test"); b.InviteSentAt == nil { |
| + t.Error("the delivery was not recorded") |
| + } |
| + |
| + // The store failing is an error. |
| + if _, err := a.db.Exec(`DROP TABLE members`); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, _, err := a.invitePerson(ctx, "carla@acme.test"); err == nil { |
| + t.Error("invite with the members unwritable: no error") |
| + } |
| +} |
diff --git a/internal/webtest/api_team_test.go b/internal/webtest/api_team_test.go| new file mode 100644 |
| index 0000000..8390d9c |
| --- /dev/null |
| +++ b/internal/webtest/api_team_test.go |
| @@ -0,0 +1,508 @@ |
| +package webtest |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "net/url" |
| + "reflect" |
| + "strings" |
| + "sync" |
| + "testing" |
| + |
| + "amadan.net/oficina/base/internal/catalog" |
| + "amadan.net/oficina/base/internal/install" |
| + "amadan.net/oficina/base/internal/store" |
| +) |
| + |
| +// Store and People for the native app (docs/api/base-native-v1.md "Store" |
| +// and "People"): the pages' own builders and owner checks, as JSON. |
| + |
| +type apiStoreRowShape struct { |
| + ID string `json:"id"` |
| + Name string `json:"name"` |
| + Summary string `json:"summary"` |
| + Tint string `json:"tint"` |
| + IconSVG string `json:"icon_svg"` |
| + State string `json:"state"` |
| + Error string `json:"error"` |
| +} |
| + |
| +type apiStoreShape struct { |
| + Owner bool `json:"owner"` |
| + Rows []apiStoreRowShape `json:"rows"` |
| +} |
| + |
| +type apiPersonShape struct { |
| + ID string `json:"id"` |
| + Initial string `json:"initial"` |
| + Name string `json:"name"` |
| + Email string `json:"email"` |
| + Role string `json:"role"` |
| +} |
| + |
| +type apiPeopleShape struct { |
| + Owner bool `json:"owner"` |
| + People []apiPersonShape `json:"people"` |
| +} |
| + |
| +// jsonAnswer checks an answer's status, that it is JSON and never cached, |
| +// and decodes it. |
| +func jsonAnswer[T any](t *testing.T, where string, r Resp, code int) T { |
| + t.Helper() |
| + if r.Code != code || r.Header.Get("Content-Type") != "application/json" || r.Header.Get("Cache-Control") != "no-store" { |
| + t.Fatalf("%s: %d %q %q, want %d JSON no-store: %s", where, r.Code, r.Header.Get("Content-Type"), r.Header.Get("Cache-Control"), code, r.Body) |
| + } |
| + return decode[T](t, r) |
| +} |
| + |
| +// refusedWith checks a JSON refusal's status and code. |
| +func refusedWith(t *testing.T, where string, r Resp, code int, want string) { |
| + t.Helper() |
| + got := jsonAnswer[map[string]any](t, where, r, code) |
| + if !reflect.DeepEqual(got, map[string]any{"code": want}) { |
| + t.Errorf("%s: %s, want {\"code\":%q}", where, r.Body, want) |
| + } |
| +} |
| + |
| +// maria is a member who isn't the owner, signed in on the native app. |
| +func (a *testApp) maria() *testApp { |
| + a.t.Helper() |
| + if _, _, err := store.Invite(context.Background(), a.DB, "maria@acme.test"); err != nil { |
| + a.t.Fatal(err) |
| + } |
| + a.newBrowser().link("maria@acme.test", "subject-maria") |
| + return a.nativeSignIn("subject-maria") |
| +} |
| + |
| +func TestAPIStore(t *testing.T) { |
| + a := newHomeApp(t) |
| + a.link(ownerAddress, "subject-owner") |
| + a.setInstall("welcome", "installed", "") |
| + a.setInstall("scratchpad", "installing", "") |
| + a.setInstall("contra", "failed", "The app did not start answering") |
| + app := a.nativeSignIn("subject-owner") |
| + |
| + r := app.nativeGet("/api/v1/store") |
| + var raw map[string]json.RawMessage |
| + if err := json.Unmarshal([]byte(r.Body), &raw); err != nil || len(raw) != 2 { |
| + t.Fatalf("store's keys: %v %s", err, r.Body) |
| + } |
| + s := jsonAnswer[apiStoreShape](t, "store", r, 200) |
| + if !s.Owner { |
| + t.Error("the owner reads as not the owner") |
| + } |
| + all := catalog.All() |
| + if len(s.Rows) != len(all) { |
| + t.Fatalf("%d rows for %d catalogue entries", len(s.Rows), len(all)) |
| + } |
| + for i, e := range all { |
| + row := s.Rows[i] |
| + if row.ID != e.ID || row.Name != e.Name || row.Summary != e.Summary || row.Tint != e.Tint || row.IconSVG != e.Icon || !strings.HasPrefix(row.IconSVG, "<svg") { |
| + t.Errorf("row %d: %+v, want the catalogue's %q in its order", i, row, e.ID) |
| + } |
| + } |
| + states := map[string]string{} |
| + for _, row := range s.Rows { |
| + states[row.ID] = row.State + "|" + row.Error |
| + } |
| + if want := map[string]string{"welcome": "installed|", "scratchpad": "installing|", "contra": "failed|The app did not start answering"}; !reflect.DeepEqual(states, want) { |
| + t.Errorf("states: %v, want %v", states, want) |
| + } |
| + |
| + // A member who isn't the owner sees the same rows. |
| + m := jsonAnswer[apiStoreShape](t, "member's store", a.maria().nativeGet("/api/v1/store"), 200) |
| + if m.Owner || !reflect.DeepEqual(m.Rows, s.Rows) { |
| + t.Errorf("member's store: owner %v, rows differ: %v", m.Owner, !reflect.DeepEqual(m.Rows, s.Rows)) |
| + } |
| + |
| + // The installs unreadable. |
| + if _, err := a.DB.Exec(`DROP TABLE installs`); err != nil { |
| + t.Fatal(err) |
| + } |
| + refusedWith(t, "installs unreadable", app.nativeGet("/api/v1/store"), http.StatusServiceUnavailable, "unavailable") |
| +} |
| + |
| +func TestAPIPeople(t *testing.T) { |
| + a := newHomeApp(t) |
| + a.link(ownerAddress, "subject-owner") |
| + ana, _, err := store.Invite(t.Context(), a.DB, "ana@acme.test") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := a.DB.Exec(`UPDATE members SET name = 'Ana Ruiz' WHERE id = ?`, ana.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + a.newBrowser().link("ana@acme.test", "subject-ana") |
| + invited, _, err := store.Invite(t.Context(), a.DB, "bob@acme.test") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + r := a.nativeSignIn("subject-owner").nativeGet("/api/v1/people") |
| + var raw map[string]json.RawMessage |
| + if err := json.Unmarshal([]byte(r.Body), &raw); err != nil || len(raw) != 2 { |
| + t.Fatalf("people's keys: %v %s", err, r.Body) |
| + } |
| + p := jsonAnswer[apiPeopleShape](t, "people", r, 200) |
| + want := apiPeopleShape{Owner: true, People: []apiPersonShape{ |
| + {ID: a.ownerID(), Initial: "O", Name: "", Email: ownerAddress, Role: "owner"}, |
| + {ID: ana.ID, Initial: "A", Name: "Ana Ruiz", Email: "ana@acme.test", Role: "member"}, |
| + {ID: invited.ID, Initial: "B", Name: "", Email: "bob@acme.test", Role: "invited"}, |
| + }} |
| + if !reflect.DeepEqual(p, want) { |
| + t.Fatalf("people:\n got %+v\nwant %+v", p, want) |
| + } |
| + // Each row has exactly these keys: no joined. |
| + var rows struct { |
| + People []map[string]any `json:"people"` |
| + } |
| + _ = json.Unmarshal([]byte(r.Body), &rows) |
| + if len(rows.People[0]) != 5 { |
| + t.Errorf("a person's keys: %v", rows.People[0]) |
| + } |
| + |
| + // Ana, a member, and the owner's own browser session on the web, get |
| + // the same people. |
| + if got := jsonAnswer[apiPeopleShape](t, "ana's people", a.nativeSignIn("subject-ana").nativeGet("/api/v1/people"), 200); got.Owner || !reflect.DeepEqual(got.People, want.People) { |
| + t.Errorf("ana's people: %+v", got) |
| + } |
| + if got := jsonAnswer[apiPeopleShape](t, "web session's people", a.get("/api/v1/people"), 200); !reflect.DeepEqual(got, want) { |
| + t.Errorf("web session's people: %+v", got) |
| + } |
| + |
| + // A member row that can't be read: the list fails, while the owner's |
| + // own row, which the gate reads, still can be. |
| + if _, err := a.DB.Exec(`INSERT INTO members (id, email, role, invited_at) VALUES ('broken', 'broken@acme.test', 'member', 'not a time')`); err != nil { |
| + t.Fatal(err) |
| + } |
| + refusedWith(t, "members unreadable", a.nativeSignIn("subject-owner").nativeGet("/api/v1/people"), http.StatusServiceUnavailable, "unavailable") |
| +} |
| + |
| +func TestAPITeamRefusesWithoutSession(t *testing.T) { |
| + a := newHomeApp(t) |
| + a.link(ownerAddress, "subject-owner") |
| + maria := a.maria() |
| + none := a.newBrowser() |
| + for _, p := range []string{"/api/v1/store", "/api/v1/people"} { |
| + r := none.nativeGet(p) |
| + refusedWith(t, "no session, "+p, r, http.StatusUnauthorized, "unauthenticated") |
| + if r.Location() != "" { |
| + t.Errorf("no session, %s: redirected to %q", p, r.Location()) |
| + } |
| + } |
| + |
| + // Maria, removed, is nobody. |
| + m, _, err := store.MemberByEmail(t.Context(), a.DB, "maria@acme.test") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := store.RemoveMember(t.Context(), a.DB, m.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, p := range []string{"/api/v1/store", "/api/v1/people"} { |
| + refusedWith(t, "removed, "+p, maria.nativeGet(p), http.StatusUnauthorized, "unauthenticated") |
| + } |
| +} |
| + |
| +// Nothing removes a member (spec 7.4): there is no route to. |
| +func TestAPIPeopleHasNoRemove(t *testing.T) { |
| + a := newHomeApp(t) |
| + a.link(ownerAddress, "subject-owner") |
| + ana, _, err := store.Invite(t.Context(), a.DB, "ana@acme.test") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + app := a.nativeSignIn("subject-owner") |
| + req, _ := http.NewRequest(http.MethodDelete, a.base+"/api/v1/people/"+ana.ID, nil) |
| + req.Header.Set("Origin", homeOrigin) |
| + req.Header.Set("Accept", "application/json") |
| + if r := app.do(req); r.Code != http.StatusNotFound && r.Code != http.StatusMethodNotAllowed { |
| + t.Errorf("DELETE /api/v1/people/<id>: %d %s", r.Code, r.Body) |
| + } |
| + if _, ok, err := store.MemberByEmail(t.Context(), a.DB, "ana@acme.test"); err != nil || !ok { |
| + t.Errorf("ana is gone: %v %v", ok, err) |
| + } |
| +} |
| + |
| +// teamInstaller is an Installer whose answers each test decides. start runs |
| +// inside Start, after the call is counted, and its error is Start's. |
| +type teamInstaller struct { |
| + mu sync.Mutex |
| + starts []string |
| + uninstalls []string |
| + start func(app string) error |
| + uninstallErr error |
| +} |
| + |
| +func (i *teamInstaller) Start(_ context.Context, app string) error { |
| + i.mu.Lock() |
| + i.starts = append(i.starts, app) |
| + start := i.start |
| + i.mu.Unlock() |
| + if start != nil { |
| + return start(app) |
| + } |
| + return nil |
| +} |
| + |
| +func (i *teamInstaller) Uninstall(_ context.Context, app string) error { |
| + i.mu.Lock() |
| + defer i.mu.Unlock() |
| + i.uninstalls = append(i.uninstalls, app) |
| + return i.uninstallErr |
| +} |
| + |
| +func (i *teamInstaller) counts() (starts, uninstalls int) { |
| + i.mu.Lock() |
| + defer i.mu.Unlock() |
| + return len(i.starts), len(i.uninstalls) |
| +} |
| + |
| +// rowState is app's state in a store answer. |
| +func rowState(t *testing.T, s apiStoreShape, app string) string { |
| + t.Helper() |
| + for _, r := range s.Rows { |
| + if r.ID == app { |
| + return r.State |
| + } |
| + } |
| + t.Fatalf("no row %q in %+v", app, s) |
| + return "" |
| +} |
| + |
| +type apiStoreAnswer struct { |
| + Store apiStoreShape `json:"store"` |
| +} |
| + |
| +// postNoOrigin is a native POST without the Origin the CSRF check needs. |
| +func (a *testApp) postNoOrigin(target string) Resp { |
| + a.t.Helper() |
| + req, _ := http.NewRequest(http.MethodPost, a.base+target, nil) |
| + req.Header.Set("Accept", "application/json") |
| + return a.do(req) |
| +} |
| + |
| +func TestAPIStoreInstall(t *testing.T) { |
| + inst := &teamInstaller{} |
| + a := newHomeAppInstalling(t, inst, nil) |
| + a.link(ownerAddress, "subject-owner") |
| + app := a.nativeSignIn("subject-owner") |
| + // The real Installer claims the install before Start returns. |
| + inst.start = func(id string) error { a.setInstall(id, "installing", ""); return nil } |
| + |
| + got := jsonAnswer[apiStoreAnswer](t, "install", app.nativePost("/api/v1/store/scratchpad/install", ""), http.StatusAccepted) |
| + if rowState(t, got.Store, "scratchpad") != "installing" || !got.Store.Owner { |
| + t.Errorf("install answered %+v", got.Store) |
| + } |
| + if s, _ := inst.counts(); s != 1 { |
| + t.Fatalf("%d Start calls, want 1", s) |
| + } |
| + |
| + // Already installing: 202 as it stands. Installed: 200. Neither starts. |
| + got = jsonAnswer[apiStoreAnswer](t, "installing again", app.nativePost("/api/v1/store/scratchpad/install", "{}"), http.StatusAccepted) |
| + if rowState(t, got.Store, "scratchpad") != "installing" { |
| + t.Errorf("installing again: %+v", got.Store) |
| + } |
| + a.setInstall("scratchpad", "installed", "") |
| + got = jsonAnswer[apiStoreAnswer](t, "installed", app.nativePost("/api/v1/store/scratchpad/install", ""), http.StatusOK) |
| + if rowState(t, got.Store, "scratchpad") != "installed" { |
| + t.Errorf("installed: %+v", got.Store) |
| + } |
| + if s, _ := inst.counts(); s != 1 { |
| + t.Fatalf("%d Start calls after the repeats, want 1", s) |
| + } |
| + |
| + // The real Start returns an error only from before its claim, so a |
| + // failed Start never started this attempt. A failed row whose retry |
| + // can't start is 503, not the old failure answered as if it ran. |
| + a.setInstall("contra", "failed", "The app did not start answering") |
| + inst.start = func(string) error { return errors.New("database locked") } |
| + refusedWith(t, "retry not started", app.nativePost("/api/v1/store/contra/install", ""), http.StatusServiceUnavailable, "unavailable") |
| + // Nor does an app never installed show anything for it. |
| + if _, err := a.DB.Exec(`DELETE FROM installs WHERE app = 'contra'`); err != nil { |
| + t.Fatal(err) |
| + } |
| + refusedWith(t, "start failed, nothing claimed", app.nativePost("/api/v1/store/contra/install", ""), http.StatusServiceUnavailable, "unavailable") |
| + // Another request claimed it meanwhile: the row reads installing, 202. |
| + inst.start = func(id string) error { |
| + a.setInstall(id, "installing", "") |
| + return errors.New("already claimed") |
| + } |
| + got = jsonAnswer[apiStoreAnswer](t, "claimed by another request", app.nativePost("/api/v1/store/contra/install", ""), http.StatusAccepted) |
| + if rowState(t, got.Store, "contra") != "installing" { |
| + t.Errorf("claimed by another request: %+v", got.Store) |
| + } |
| + // A failed row's retry that starts is 202, installing. |
| + a.setInstall("contra", "failed", "") |
| + inst.start = func(id string) error { a.setInstall(id, "installing", ""); return nil } |
| + got = jsonAnswer[apiStoreAnswer](t, "try again", app.nativePost("/api/v1/store/contra/install", ""), http.StatusAccepted) |
| + if rowState(t, got.Store, "contra") != "installing" { |
| + t.Errorf("try again: %+v", got.Store) |
| + } |
| + before, _ := inst.counts() |
| + |
| + refusedWith(t, "unknown app", app.nativePost("/api/v1/store/nope/install", ""), http.StatusNotFound, "unknown_app") |
| + refusedWith(t, "member", a.maria().nativePost("/api/v1/store/scratchpad/install", ""), http.StatusForbidden, "owner_only") |
| + if r := app.postNoOrigin("/api/v1/store/scratchpad/install"); r.Code != http.StatusForbidden { |
| + t.Errorf("no Origin: %d %s", r.Code, r.Body) |
| + } |
| + if r := app.postFrom("https://evil.test", "/api/v1/store/scratchpad/install", nil); r.Code != http.StatusForbidden { |
| + t.Errorf("another site: %d %s", r.Code, r.Body) |
| + } |
| + if s, _ := inst.counts(); s != before { |
| + t.Errorf("a refused install reached Start (%d -> %d)", before, s) |
| + } |
| +} |
| + |
| +func TestAPIStoreUninstall(t *testing.T) { |
| + inst := &teamInstaller{} |
| + a := newHomeAppInstalling(t, inst, nil) |
| + a.link(ownerAddress, "subject-owner") |
| + app := a.nativeSignIn("subject-owner") |
| + a.setInstall("scratchpad", "installed", "") |
| + |
| + // The real Installer removes the row; the fake leaves that to the test. |
| + got := jsonAnswer[apiStoreAnswer](t, "uninstall", app.nativePost("/api/v1/store/scratchpad/uninstall", ""), http.StatusOK) |
| + if !got.Store.Owner || len(got.Store.Rows) != len(catalog.All()) { |
| + t.Errorf("uninstall answered %+v", got.Store) |
| + } |
| + if _, u := inst.counts(); u != 1 { |
| + t.Fatalf("%d Uninstall calls, want 1", u) |
| + } |
| + |
| + inst.uninstallErr = install.ErrBusy |
| + refusedWith(t, "busy", app.nativePost("/api/v1/store/scratchpad/uninstall", ""), http.StatusConflict, "busy") |
| + inst.uninstallErr = store.ErrNoInstall |
| + jsonAnswer[apiStoreAnswer](t, "already uninstalled", app.nativePost("/api/v1/store/scratchpad/uninstall", ""), http.StatusOK) |
| + inst.uninstallErr = errors.New("platform down") |
| + refusedWith(t, "uninstall failed", app.nativePost("/api/v1/store/scratchpad/uninstall", ""), http.StatusServiceUnavailable, "unavailable") |
| + inst.uninstallErr = nil |
| + _, before := inst.counts() |
| + |
| + refusedWith(t, "unknown app", app.nativePost("/api/v1/store/nope/uninstall", ""), http.StatusNotFound, "unknown_app") |
| + refusedWith(t, "member", a.maria().nativePost("/api/v1/store/scratchpad/uninstall", ""), http.StatusForbidden, "owner_only") |
| + if r := app.postNoOrigin("/api/v1/store/scratchpad/uninstall"); r.Code != http.StatusForbidden { |
| + t.Errorf("no Origin: %d %s", r.Code, r.Body) |
| + } |
| + if _, u := inst.counts(); u != before { |
| + t.Errorf("a refused uninstall reached Uninstall (%d -> %d)", before, u) |
| + } |
| + |
| + // The store unreadable after the uninstall. |
| + if _, err := a.DB.Exec(`DROP TABLE installs`); err != nil { |
| + t.Fatal(err) |
| + } |
| + refusedWith(t, "store unreadable", app.nativePost("/api/v1/store/scratchpad/uninstall", ""), http.StatusServiceUnavailable, "unavailable") |
| +} |
| + |
| +type apiPersonAnswer struct { |
| + Person apiPersonShape `json:"person"` |
| +} |
| + |
| +func TestAPIPeopleInvite(t *testing.T) { |
| + a := newHomeApp(t) |
| + a.link(ownerAddress, "subject-owner") |
| + app := a.nativeSignIn("subject-owner") |
| + n := len(a.mailbox()) |
| + |
| + got := jsonAnswer[apiPersonAnswer](t, "invite", app.nativePost("/api/v1/people", `{"email":" Maria@Acme.test "}`), http.StatusOK) |
| + m, ok, err := store.MemberByEmail(t.Context(), a.DB, "maria@acme.test") |
| + if err != nil || !ok { |
| + t.Fatalf("maria: %v %v", ok, err) |
| + } |
| + if want := (apiPersonShape{ID: m.ID, Initial: "M", Email: "maria@acme.test", Role: "invited"}); got.Person != want { |
| + t.Errorf("invite answered %+v, want %+v", got.Person, want) |
| + } |
| + box := a.mailbox() |
| + if len(box) != n+1 || box[len(box)-1].To != "maria@acme.test" { |
| + t.Fatalf("want one invitation to maria, mailbox grew by %d", len(box)-n) |
| + } |
| + |
| + // The same address again sends nothing, and answers the same person. |
| + again := jsonAnswer[apiPersonAnswer](t, "invite again", app.nativePost("/api/v1/people", `{"email":"maria@acme.test"}`), http.StatusOK) |
| + if again.Person != got.Person || len(a.mailbox()) != n+1 { |
| + t.Errorf("invite again: %+v, mailbox grew by %d", again.Person, len(a.mailbox())-n) |
| + } |
| + // The owner is already here. |
| + if o := jsonAnswer[apiPersonAnswer](t, "invite the owner", app.nativePost("/api/v1/people", `{"email":"`+ownerAddress+`"}`), http.StatusOK); o.Person.Role != "owner" || o.Person.ID != a.ownerID() { |
| + t.Errorf("invite the owner: %+v", o.Person) |
| + } |
| + |
| + for _, body := range []string{`{"email":"not an email"}`, `{"email":""}`, `{}`, `{"email":"Bob <bob@acme.test>"}`} { |
| + refusedWith(t, "bad address "+body, app.nativePost("/api/v1/people", body), http.StatusUnprocessableEntity, "bad_email") |
| + } |
| + |
| + // A failing mailer: 502, and inviting again sends. |
| + a.mail.mu.Lock() |
| + a.mail.fail = true |
| + a.mail.mu.Unlock() |
| + refusedWith(t, "mail down", app.nativePost("/api/v1/people", `{"email":"bob@acme.test"}`), http.StatusBadGateway, "mail_failed") |
| + a.mail.mu.Lock() |
| + a.mail.fail = false |
| + a.mail.mu.Unlock() |
| + bob := jsonAnswer[apiPersonAnswer](t, "retry", app.nativePost("/api/v1/people", `{"email":"bob@acme.test"}`), http.StatusOK) |
| + if bob.Person.Email != "bob@acme.test" || len(a.mailbox()) != n+2 { |
| + t.Errorf("retry: %+v, mailbox grew by %d", bob.Person, len(a.mailbox())-n) |
| + } |
| + // Refusals that send nothing. Maria signs in first, which mails her a |
| + // sign-in link. |
| + maria := a.maria() |
| + sent := len(a.mailbox()) |
| + refusedWith(t, "member", maria.nativePost("/api/v1/people", `{"email":"carla@acme.test"}`), http.StatusForbidden, "owner_only") |
| + form := app.postFrom(homeOrigin, "/api/v1/people", url.Values{"email": {"carla@acme.test"}}) |
| + if form.Code != http.StatusUnsupportedMediaType { |
| + t.Errorf("a form body: %d %s", form.Code, form.Body) |
| + } |
| + big := `{"email":"carla@acme.test","pad":"` + strings.Repeat("x", 4<<10) + `"}` |
| + if r := app.nativePost("/api/v1/people", big); r.Code != http.StatusRequestEntityTooLarge { |
| + t.Errorf("a body over 4 KiB: %d %s", r.Code, r.Body) |
| + } |
| + if r := app.nativePost("/api/v1/people", `{"email":`); r.Code != http.StatusBadRequest { |
| + t.Errorf("broken JSON: %d %s", r.Code, r.Body) |
| + } |
| + if len(a.mailbox()) != sent { |
| + t.Errorf("a refused invite sent mail") |
| + } |
| + // Inside the CSRF check: no Origin, or another site's, with a JSON body. |
| + for _, origin := range []string{"", "https://evil.test"} { |
| + req, _ := http.NewRequest(http.MethodPost, a.base+"/api/v1/people", strings.NewReader(`{"email":"carla@acme.test"}`)) |
| + req.Header.Set("Content-Type", "application/json") |
| + req.Header.Set("Accept", "application/json") |
| + if origin != "" { |
| + req.Header.Set("Origin", origin) |
| + } |
| + if r := app.do(req); r.Code != http.StatusForbidden { |
| + t.Errorf("invite with Origin %q: %d %s", origin, r.Code, r.Body) |
| + } |
| + } |
| + if len(a.mailbox()) != sent { |
| + t.Errorf("a refused invite sent mail") |
| + } |
| + if _, ok, _ := store.MemberByEmail(t.Context(), a.DB, "carla@acme.test"); ok { |
| + t.Error("a refused invite added carla") |
| + } |
| + |
| + // The owner's web session (the cookie from signing in on the web) may |
| + // write too: it is the same member gate. |
| + if web := jsonAnswer[apiPersonAnswer](t, "invite from the web session", a.nativePost("/api/v1/people", `{"email":"dana@acme.test"}`), http.StatusOK); web.Person.Email != "dana@acme.test" { |
| + t.Errorf("invite from the web session: %+v", web.Person) |
| + } |
| + |
| + // The members can't be written. |
| + if _, err := a.DB.Exec(`CREATE TRIGGER no_invites BEFORE INSERT ON members BEGIN SELECT RAISE(ABORT, 'locked'); END`); err != nil { |
| + t.Fatal(err) |
| + } |
| + refusedWith(t, "members unwritable", app.nativePost("/api/v1/people", `{"email":"erin@acme.test"}`), http.StatusServiceUnavailable, "unavailable") |
| +} |
| + |
| +// Without a session every write is 401, as the reads are. |
| +func TestAPITeamWritesRefuseWithoutSession(t *testing.T) { |
| + a := newHomeApp(t) |
| + a.link(ownerAddress, "subject-owner") |
| + none := a.newBrowser() |
| + for _, p := range []string{"/api/v1/store/scratchpad/install", "/api/v1/store/scratchpad/uninstall", "/api/v1/people"} { |
| + refusedWith(t, "no session, POST "+p, none.nativePost(p, `{"email":"x@acme.test"}`), http.StatusUnauthorized, "unauthenticated") |
| + } |
| +} |
diff --git a/internal/webtest/oficina_harness_test.go b/internal/webtest/oficina_harness_test.go| index 32daf42..2cba342 100644 |
| --- a/internal/webtest/oficina_harness_test.go |
| +++ b/internal/webtest/oficina_harness_test.go |
| @@ -57,6 +57,13 @@ func newHomeApp(t *testing.T) *testApp { return newHomeAppWith(t, nil) } |
| // newHomeAppWith is newHomeApp with a last say over the configuration. |
| func newHomeAppWith(t *testing.T, tweak func(*config.Config)) *testApp { |
| + t.Helper() |
| + return newHomeAppInstalling(t, noInstaller{}, tweak) |
| +} |
| + |
| +// newHomeAppInstalling is newHomeAppWith with the Installer of the |
| +// caller's choice. |
| +func newHomeAppInstalling(t *testing.T, inst web.Installer, tweak func(*config.Config)) *testApp { |
| t.Helper() |
| logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| d, err := db.Open(homeSchema.Path(t), logger) |
| @@ -90,7 +97,7 @@ func newHomeAppWith(t *testing.T, tweak func(*config.Config)) *testApp { |
| tweak(&cfg) |
| } |
| mailer := &capturingMailer{} |
| - h, err := web.App(d, cfg, mailer, noInstaller{}, logger) |
| + h, err := web.App(d, cfg, mailer, inst, logger) |
| if err != nil { |
| t.Fatalf("web.App: %v", err) |
| } |