Merge branch 'push/server' into main
61 files changed,
+5,397
−25
.rastrillo/budgets.txt+4 −4cmd/equipo/main.go+4 −0docs/api/equipo-v1.md+21 −0docs/api/equipo-v1.openapi.json+303 −0docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+12 −0internal/equipo/app.go+15 −1internal/equipo/chat/http.go+6 −0internal/equipo/chat/hub.go+27 −1internal/equipo/chat/inner.go+1 −1internal/equipo/chat/models.go+6 −2internal/equipo/chat/projects.go+17 −1internal/equipo/chat/push.go+552 −0internal/equipo/chat/push_http.go+61 −0internal/equipo/chat/push_review_test.go+87 −0internal/equipo/chat/push_test.go+638 −0internal/equipo/chat/roster.go+45 −8internal/equipo/chat/store.go+16 −1internal/equipo/chat/tasks.go+3 −0internal/equipo/chat_wiring.go+15 −0internal/equipo/config.go+12 −0internal/equipo/copy.go+12 −0internal/equipo/invitations.go+3 −1internal/equipo/mailer.go+30 −0internal/equipo/migrations/0096_push.sql+19 −0internal/equipo/migrations/0097_push_hold.sql+2 −0internal/equipo/migrations/schema.sql+14 −0internal/equipo/migrations_test.go+46 −0internal/equipo/person_devices.go+2 −1internal/equipo/personapi/devices.go+46 −0internal/equipo/push/budget_test.go+9 −0internal/equipo/push/outcome_test.go+388 −0internal/equipo/push/payload.go+116 −0internal/equipo/push/payload_test.go+108 −0internal/equipo/push/push.go+169 −0internal/equipo/push/review_test.go+289 −0internal/equipo/push/rules.go+283 −0internal/equipo/push/rules_test.go+201 −0internal/equipo/push/sender.go+359 −0internal/equipo/push/sender_state.go+80 −0internal/equipo/push/sender_test.go+422 −0internal/equipo/push/store.go+359 −0internal/equipo/push/testdata/activity-end.json+17 −0internal/equipo/push/testdata/activity-needs.json+15 −0internal/equipo/push/testdata/activity-replaced.json+17 −0internal/equipo/push/testdata/activity-start.json+24 −0internal/equipo/push/testdata/activity-update.json+15 −0internal/equipo/push/testdata/badge.json+5 −0internal/equipo/push/testdata/card.json+16 −0internal/equipo/push/testdata/reply.json+13 −0internal/equipo/push/testdata/task-done.json+14 −0internal/equipo/push/testdata/task-failed.json+14 −0internal/equipo/push/transport.go+137 −0internal/equipo/push_config_test.go+59 −0internal/equipo/setup/invites.go+4 −0internal/equipo/setup/roster.go+5 −0internal/plan3test/plan3_release_test.go+4 −1internal/plan3test/push_device_test.go+85 −0internal/wire/api.go+3 −0internal/wire/push.go+128 −0internal/wire/wireschema/wireschema.go+15 −3internal/wire/wireschema/wireschema_test.go+5 −0
CI passed — run details
CI log
=== prepare ===
ci-box: machine: aarch64, 32 CPUs, 62 GiB memory, kernel 7.0.0-1017-aws
ci-box: python 3.12.3; Docker version 29.1.3, build 29.1.3-0ubuntu3~24.04.2
ci-box: user namespaces allowed: 233151
ci-box: cgroup: cgroup2fs
ci-box: disk /home/ci/work/repos/oficina__equipo/wt/main: Type Size Avail | ext4 96G 86G
ci-box: disk /home/ci/.cache/equipo-ci-box: Type Size Avail | ext4 96G 86G
ci-box: bwrap: fetched and verified in 0.3s
ci-box: claude: fetched and verified in 4.7s
ci-box: codex: fetched and verified in 3.6s
ci-box: codex-code-mode-host: fetched and verified in 1.4s
ci-box: libwrap: fetched and verified in 0.3s
ci-box: socat: fetched and verified in 0.4s
npm warn deprecated node-domexception@1.0.0: Use your platform's native DOMException instead
ci-box: image pulled in 10.0s
ci-box: pi: installed and verified in 7.6s
ci-box: opencode: installed and verified in 1.9s
ci-box: chromium 156.0.8078.79-1~deb13u1: 76 packages fetched, verified and unpacked in 10.2s
ci-box: clone deepened in 3.2s
ci-box: file times set from content: 2764 files, 176 directories
ci-box: ready in 17.7s
=== copy ===
EQUIPO_RELEASE_COPY_CHECK=1 CGO_ENABLED=0 go test ./internal/equipotest -run '^TestReleaseCopyReviewed$' -count=1
ok amadan.net/oficina/equipo/internal/equipotest 0.249s
=== compile ===
go build ./...
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py compile
+ go build -tags testbuild ./...
4.6s
+ go list -export -test -tags testbuild -f ./...
5.0s
+ go list -export -test -tags browser,testbuild -f ./internal/equipo ./internal/headless ./internal/idtest ./internal/plan3test ./internal/thintest
3.1s
go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 -version
staticcheck 2026.1 (v0.7.0)
go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 -version
Go: go1.26.11
Scanner: govulncheck@v1.8.0
DB: https://vuln.go.dev
DB updated: 2026-11-11 02:51:11 +0000 UTC
go run github.com/zricethezav/gitleaks/v8@v8.30.1 version
version is set by build process
=== check ===
--- shard 0 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-work: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestHeadless$/^4c_rebase$|^TestHeadless$/^4b_ask$|^TestHeadless$/^4c_checks_card$|^TestHeadless$/^4_step_crash$' ./internal/headless
receipt: test step 1m31.435s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m29.382s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m29.38s amadan.net/oficina/equipo/internal/headless TestHeadless
machine: 32 CPUs, load 62.00, cpu waiting 40.58%, memory waiting 0.00%, io waiting 0.47%
--- shard 1 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-review: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestHeadless$/^4_review$|^TestHeadless$/^2b_access$|^TestHeadless$/^runner_crash$|^TestHeadless$/^2b_first_message$|^TestHeadless$/^4_checks_honest$|^TestHeadless$/^7_stream_resume$|^TestHeadless$/^2b_notebook$|^TestHeadless$/^2b_move_in$|^TestHeadless$/^2b_desk_failure$|^TestHeadless$/^cancel$' ./internal/headless
receipt: test step 1m34.897s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m32.07s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m32.07s amadan.net/oficina/equipo/internal/headless TestHeadless
machine: 32 CPUs, load 61.28, cpu waiting 40.56%, memory waiting 0.00%, io waiting 0.46%
--- shard 2 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-connections: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestHeadlessConnections$|^TestHeadlessTokenPasteEndToEnd$|^TestHeadlessTokenConnection$' ./internal/headless
receipt: test step 1m35.746s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m33.745s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m22.34s amadan.net/oficina/equipo/internal/headless TestHeadlessConnections
receipt: slow test 6.23s amadan.net/oficina/equipo/internal/headless TestHeadlessTokenPasteEndToEnd
receipt: slow test 5.17s amadan.net/oficina/equipo/internal/headless TestHeadlessTokenConnection
machine: 32 CPUs, load 61.28, cpu waiting 40.08%, memory waiting 0.00%, io waiting 0.44%
--- shard 3 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-mac: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestMacWorker$|^TestHeadlessAttachments$|^TestHeadlessPrewarm$|^TestHeadless$/^1_first_token$|^TestHeadless$/^6_quick_messages$|^TestHeadless$/^8_instance_restart$|^TestHeadless$/^3_runner_offline$' ./internal/headless
receipt: test step 1m31.052s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m28.313s amadan.net/oficina/equipo/internal/headless
receipt: slow test 45.31s amadan.net/oficina/equipo/internal/headless TestMacWorker
receipt: slow test 22.42s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 10.88s amadan.net/oficina/equipo/internal/headless TestHeadlessAttachments
receipt: slow test 9.7s amadan.net/oficina/equipo/internal/headless TestHeadlessPrewarm
machine: 32 CPUs, load 62.00, cpu waiting 40.58%, memory waiting 0.00%, io waiting 0.47%
--- shard 4 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-guards: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestHeadlessCopyRotation$|^TestHeadlessPolicyGuards$|^TestHeadlessRunnerKillLeavesNoCopies$|^TestHeadlessNewHouseRuleStartsFresh$|^TestHeadless$/^3_engineering$|^TestHeadless$/^3_step_cancel$|^TestHeadless$/^3_step_contained$|^TestHeadless$/^3_empty_repo$|^TestHeadless$/^3_empty_engineering$|^TestHeadless$/^3_empty_merge$|^TestHeadless$/^3_empty_merge_rebuilt$|^TestHeadless$/^3_empty_fix_round$' ./internal/headless
receipt: test step 1m49.099s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m46.625s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m8.17s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 12.85s amadan.net/oficina/equipo/internal/headless TestHeadlessRunnerKillLeavesNoCopies
receipt: slow test 10.66s amadan.net/oficina/equipo/internal/headless TestHeadlessCopyRotation
receipt: slow test 8.91s amadan.net/oficina/equipo/internal/headless TestHeadlessPolicyGuards
receipt: slow test 6.04s amadan.net/oficina/equipo/internal/headless TestHeadlessNewHouseRuleStartsFresh
machine: 32 CPUs, load 52.43, cpu waiting 33.30%, memory waiting 0.00%, io waiting 0.35%
--- shard 5 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-rest: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -skip '^TestHeadless$/^4c_rebase$|^TestHeadless$/^4b_ask$|^TestHeadless$/^4c_checks_card$|^TestHeadless$/^4_step_crash$|^TestHeadless$/^4_review$|^TestHeadless$/^2b_access$|^TestHeadless$/^runner_crash$|^TestHeadless$/^2b_first_message$|^TestHeadless$/^4_checks_honest$|^TestHeadless$/^7_stream_resume$|^TestHeadless$/^2b_notebook$|^TestHeadless$/^2b_move_in$|^TestHeadless$/^2b_desk_failure$|^TestHeadless$/^cancel$|^TestHeadlessConnections$|^TestHeadlessTokenPasteEndToEnd$|^TestHeadlessTokenConnection$|^TestMacWorker$|^TestHeadlessAttachments$|^TestHeadlessPrewarm$|^TestHeadless$/^1_first_token$|^TestHeadless$/^6_quick_messages$|^TestHeadless$/^8_instance_restart$|^TestHeadless$/^3_runner_offline$|^TestHeadlessCopyRotation$|^TestHeadlessPolicyGuards$|^TestHeadlessRunnerKillLeavesNoCopies$|^TestHeadlessNewHouseRuleStartsFresh$|^TestHeadless$/^3_engineering$|^TestHeadless$/^3_step_cancel$|^TestHeadless$/^3_step_contained$|^TestHeadless$/^3_empty_repo$|^TestHeadless$/^3_empty_engineering$|^TestHeadless$/^3_empty_merge$|^TestHeadless$/^3_empty_merge_rebuilt$|^TestHeadless$/^3_empty_fix_round$' ./internal/headless
receipt: test step 3m18.916s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 3m16.081s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m54.02s amadan.net/oficina/equipo/internal/headless TestHeadlessAssistant
receipt: slow test 23.99s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 11.36s amadan.net/oficina/equipo/internal/headless TestHeadlessResearchHandoff
receipt: slow test 8.13s amadan.net/oficina/equipo/internal/headless TestHeadlessClaudeSignIn
receipt: slow test 7.33s amadan.net/oficina/equipo/internal/headless TestHeadlessTurnBatching
machine: 32 CPUs, load 16.29, cpu waiting 7.74%, memory waiting 0.00%, io waiting 0.07%
--- shard 6 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane thintest: ./internal/thintest
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^Test([^C]|C[^o]|Co[^n]|Con[^t])|^TestContract(Assistant|Outcome|Team|Handoff|HostAllowlist|HostIsPerPerson|Look|Use[A-Z]|RemoteCall|LanesRunAtOnce|NoMergeQuestionWhenGateMerges|PreviewHeldUntilPublishAnswer|PreviewNotHeldBelow19|PublishNeedsOwnerAnswer)' ./internal/thintest
receipt: test step 2m6.598s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 2m4.434s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 8.12s amadan.net/oficina/equipo/internal/thintest TestContractTeamJobSettledStates
receipt: slow test 6.73s amadan.net/oficina/equipo/internal/thintest TestExplorePreviewsOff
receipt: slow test 3.77s amadan.net/oficina/equipo/internal/thintest TestContractPreviewHeldUntilPublishAnswer
receipt: slow test 3.46s amadan.net/oficina/equipo/internal/thintest TestContractTeamNudgePersonNeeds
receipt: slow test 2.52s amadan.net/oficina/equipo/internal/thintest TestResearchDoneFallsBack
machine: 32 CPUs, load 42.18, cpu waiting 24.70%, memory waiting 0.00%, io waiting 0.25%
--- shard 7 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane thintest-contract: ./internal/thintest
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -skip '^Test([^C]|C[^o]|Co[^n]|Con[^t])|^TestContract(Assistant|Outcome|Team|Handoff|HostAllowlist|HostIsPerPerson|Look|Use[A-Z]|RemoteCall|LanesRunAtOnce|NoMergeQuestionWhenGateMerges|PreviewHeldUntilPublishAnswer|PreviewNotHeldBelow19|PublishNeedsOwnerAnswer)' ./internal/thintest
receipt: test step 1m26.346s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m23.642s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 9.03s amadan.net/oficina/equipo/internal/thintest TestContractPreviewNotScheduled
receipt: slow test 4.98s amadan.net/oficina/equipo/internal/thintest TestContractPublishNotOffered
receipt: slow test 4.41s amadan.net/oficina/equipo/internal/thintest TestContractMacRecheckMergeAuthority
receipt: slow test 2.37s amadan.net/oficina/equipo/internal/thintest TestContractPreview
receipt: slow test 2.35s amadan.net/oficina/equipo/internal/thintest TestContractPublishNameTaken
machine: 32 CPUs, load 63.13, cpu waiting 40.31%, memory waiting 0.00%, io waiting 0.52%
--- shard 8 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane runner-thin: ./internal/runner/thin
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m ./internal/runner/thin
budget note: internal/runner/thin took 4m41.011s, over the 45s its record on line 44 allows; reported only, timing fails on CI
receipt: test step 4m46.561s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 4m41.011s amadan.net/oficina/equipo/internal/runner/thin
receipt: slow test 37.08s amadan.net/oficina/equipo/internal/runner/thin TestModelsEngineeringProbesThenRunsTheStrongest
receipt: slow test 37.03s amadan.net/oficina/equipo/internal/runner/thin TestModelsProbeAnsweredByAnotherModel
receipt: slow test 36.78s amadan.net/oficina/equipo/internal/runner/thin TestModelsUnhealthyRetriedOnDemand
receipt: slow test 18.49s amadan.net/oficina/equipo/internal/runner/thin TestModelsProbeRunsInsideTheAdmission
receipt: slow test 7.06s amadan.net/oficina/equipo/internal/runner/thin TestOpenCodeStepsRealOpenCode
machine: 32 CPUs, load 4.25, cpu waiting 1.78%, memory waiting 0.00%, io waiting 0.01%
--- shard 9 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane runner-bug: ./internal/runner
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestDirectBugWorkflow$|^TestEnrolKeepsTheRole$' ./internal/runner
receipt: test step 51.132s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 50.165s amadan.net/oficina/equipo/internal/runner
receipt: slow test 30.13s amadan.net/oficina/equipo/internal/runner TestDirectBugWorkflow
receipt: slow test 20.02s amadan.net/oficina/equipo/internal/runner TestEnrolKeepsTheRole
machine: 32 CPUs, load 54.15, cpu waiting 32.07%, memory waiting 0.00%, io waiting 0.96%
--- shard 10 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane runner-plans: ./internal/runner
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestPlanWorkflowCandidateOrder$|^TestPlanWorkflowFeature$|^TestCoordinatorRecoveryCallRefusalKeepsServing$|^TestCoordinatorRefusalMatrix$' ./internal/runner
receipt: test step 1m1.132s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 59.78s amadan.net/oficina/equipo/internal/runner
receipt: slow test 49.64s amadan.net/oficina/equipo/internal/runner TestPlanWorkflowCandidateOrder
receipt: slow test 45.74s amadan.net/oficina/equipo/internal/runner TestPlanWorkflowFeature
receipt: slow test 8.4s amadan.net/oficina/equipo/internal/runner TestCoordinatorRecoveryCallRefusalKeepsServing
receipt: slow test 1.72s amadan.net/oficina/equipo/internal/runner TestCoordinatorRefusalMatrix
machine: 32 CPUs, load 63.07, cpu waiting 38.00%, memory waiting 0.00%, io waiting 0.79%
--- shard 11 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane runner-rest: ./internal/runner
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -skip '^TestDirectBugWorkflow$|^TestEnrolKeepsTheRole$|^TestPlanWorkflowCandidateOrder$|^TestPlanWorkflowFeature$|^TestCoordinatorRecoveryCallRefusalKeepsServing$|^TestCoordinatorRefusalMatrix$' ./internal/runner
receipt: test step 36.079s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 35.229s amadan.net/oficina/equipo/internal/runner
receipt: slow test 5.14s amadan.net/oficina/equipo/internal/runner TestDirectFaultIsolation
receipt: slow test 3.46s amadan.net/oficina/equipo/internal/runner TestClaimRefusalsBackOff
receipt: slow test 3.15s amadan.net/oficina/equipo/internal/runner TestCoordinatorRecoveryRefusedKeepsServing
receipt: slow test 2.43s amadan.net/oficina/equipo/internal/runner TestToolVerbUnderFakeHarness
receipt: slow test 1.61s amadan.net/oficina/equipo/internal/runner TestReportPostsRetryExactRequest
machine: 32 CPUs, load 30.46, cpu waiting 20.84%, memory waiting 0.00%, io waiting 1.22%
--- shard 12 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: equipotest-a started 30s late; cpu waiting 36.8%, load 22.67
test lane equipotest-a: ./internal/equipotest
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^Test[A-D]|^TestQ' ./internal/equipotest
receipt: test step 1m7.152s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m5.245s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 27.48s amadan.net/oficina/equipo/internal/equipotest TestAuthorityCoreIntegration
receipt: slow test 27.36s amadan.net/oficina/equipo/internal/equipotest TestBootstrapNamesOwnersSetting
receipt: slow test 25.39s amadan.net/oficina/equipo/internal/equipotest TestAccountLabelMigration
receipt: slow test 22.67s amadan.net/oficina/equipo/internal/equipotest TestBudgetConfigurationFailuresAreAtomic
receipt: slow test 22.44s amadan.net/oficina/equipo/internal/equipotest TestAuthorityGrantReferences
machine: 32 CPUs, load 61.28, cpu waiting 39.10%, memory waiting 0.00%, io waiting 0.43%
--- shard 13 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: equipotest-e started 30s late; cpu waiting 36.8%, load 22.67
test lane equipotest-e: ./internal/equipotest
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^Test[E-P]' ./internal/equipotest
receipt: test step 1m15.335s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m13.235s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 19.36s amadan.net/oficina/equipo/internal/equipotest TestProjectRetryAndRevision
receipt: slow test 19.33s amadan.net/oficina/equipo/internal/equipotest TestProjectRejectsUnsafeBinding
receipt: slow test 19.32s amadan.net/oficina/equipo/internal/equipotest TestProjectConcurrentRetry
receipt: slow test 19.23s amadan.net/oficina/equipo/internal/equipotest TestProjectsReopen
receipt: slow test 19.21s amadan.net/oficina/equipo/internal/equipotest TestProjectOwnersAreMembers
machine: 32 CPUs, load 56.38, cpu waiting 35.45%, memory waiting 0.00%, io waiting 0.37%
--- shard 14 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: equipotest-r started 30s late; cpu waiting 36.8%, load 22.67
test lane equipotest-r: ./internal/equipotest
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestR' ./internal/equipotest
receipt: test step 1m12.875s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m7.635s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 14.51s amadan.net/oficina/equipo/internal/equipotest TestReleaseStampContract
receipt: slow test 13.02s amadan.net/oficina/equipo/internal/equipotest TestRosterChangesAffectExistingSession
receipt: slow test 10.23s amadan.net/oficina/equipo/internal/equipotest TestRosterRemovalRollsBack
receipt: slow test 10.03s amadan.net/oficina/equipo/internal/equipotest TestRosterRemovalWhileAssigned
receipt: slow test 7.2s amadan.net/oficina/equipo/internal/equipotest TestRosterBootstrapOnce
machine: 32 CPUs, load 59.90, cpu waiting 36.55%, memory waiting 0.00%, io waiting 0.39%
--- shard 15 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: equipotest-rest started 30s late; cpu waiting 36.8%, load 22.67
test lane equipotest-rest: ./internal/equipotest
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -skip '^Test[A-D]|^TestQ|^Test[E-P]|^TestR' ./internal/equipotest
receipt: test step 1m8.193s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m6.217s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 25.52s amadan.net/oficina/equipo/internal/equipotest TestSigninNoProof
receipt: slow test 24.42s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsSeedExistingTeam
receipt: slow test 24.41s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsSeedRollback
receipt: slow test 22.66s amadan.net/oficina/equipo/internal/equipotest TestSpecialistSettingsRollbackAndUnavailable
receipt: slow test 22.58s amadan.net/oficina/equipo/internal/equipotest TestSigninBackgroundSweep
machine: 32 CPUs, load 61.28, cpu waiting 39.10%, memory waiting 0.00%, io waiting 0.43%
--- shard 16 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: plan3test started 30s late; cpu waiting 36.8%, load 22.67
test lane plan3test: ./internal/plan3test
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m ./internal/plan3test
receipt: test step 54.082s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 51.782s amadan.net/oficina/equipo/internal/plan3test
receipt: slow test 3.65s amadan.net/oficina/equipo/internal/plan3test TestPlan3Upgrade
receipt: slow test 3.53s amadan.net/oficina/equipo/internal/plan3test TestCoordinatorAcceptance3B
receipt: slow test 1.6s amadan.net/oficina/equipo/internal/plan3test TestCoordinatorAcceptance3A
receipt: slow test 1.45s amadan.net/oficina/equipo/internal/plan3test TestConversationQuestionRace
receipt: slow test 1.43s amadan.net/oficina/equipo/internal/plan3test TestInviteMigration
machine: 32 CPUs, load 64.45, cpu waiting 40.49%, memory waiting 0.00%, io waiting 0.54%
--- shard 17 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: rest started 30s late; cpu waiting 36.8%, load 22.67
test lane rest: ./cmd/equipo ./cmd/equipo-runner ./cmd/equipo-tool-proxy ./internal/advice ./internal/attach ./internal/attach/attachtest ./internal/chatmarkdown ./internal/chatsend ./internal/chatstream ./internal/coordinator ./internal/coordinatorcontract ./internal/coordinatormail ./internal/copydesk ./internal/equipo ./internal/equipo/activity ./internal/equipo/assist ./internal/equipo/chat ./internal/equipo/conversation ./internal/equipo/conversation/chatstate ./internal/equipo/housekeeping ./internal/equipo/icons ./internal/equipo/identity ./internal/equipo/kernel ./internal/equipo/library ./internal/equipo/mergegate ./internal/equipo/notifications ./internal/equipo/oficina ./internal/equipo/oficina/oficinatest ./internal/equipo/oficinaid ./internal/equipo/ownermode ./internal/equipo/personapi ./internal/equipo/planning ./internal/equipo/push ./internal/equipo/setup ./internal/equipo/team ./internal/equipo/teamcontract ./internal/equipo/triage ./internal/fakeclaude ./internal/fakecodex ./internal/fakeopencode ./internal/fakepi ./internal/idtest ./internal/ownermodetest ./internal/release ./internal/runner/checks ./internal/runner/connect ./internal/runner/containment ./internal/runner/containment/sysunix ./internal/runner/egress ./internal/runner/forge ./internal/runner/forge/forgetest ./internal/runner/heartbeat ./internal/runner/mac ./internal/runner/mcpresource ./internal/runner/metered ./internal/runner/planflow ./internal/runner/provider ./internal/runner/provider/claude ./internal/runner/provider/codex ./internal/runner/provider/gotoolchain ./internal/runner/provider/opencode ./internal/runner/provider/pi ./internal/runner/setup ./internal/runner/transporttest ./internal/runner/webread ./internal/runner/workspace ./internal/runnerproto ./internal/schedule ./internal/sealbox ./internal/specialist ./internal/stagingtest ./internal/taskplan ./internal/testci ./internal/toolproxy ./internal/websource ./internal/wire ./internal/wire/wireschema ./internal/wire/wiretest ./tools/drive
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m ./cmd/equipo ./cmd/equipo-runner ./cmd/equipo-tool-proxy ./internal/advice ./internal/attach ./internal/attach/attachtest ./internal/chatmarkdown ./internal/chatsend ./internal/chatstream ./internal/coordinator ./internal/coordinatorcontract ./internal/coordinatormail ./internal/copydesk ./internal/equipo ./internal/equipo/activity ./internal/equipo/assist ./internal/equipo/chat ./internal/equipo/conversation ./internal/equipo/conversation/chatstate ./internal/equipo/housekeeping ./internal/equipo/icons ./internal/equipo/identity ./internal/equipo/kernel ./internal/equipo/library ./internal/equipo/mergegate ./internal/equipo/notifications ./internal/equipo/oficina ./internal/equipo/oficina/oficinatest ./internal/equipo/oficinaid ./internal/equipo/ownermode ./internal/equipo/personapi ./internal/equipo/planning ./internal/equipo/push ./internal/equipo/setup ./internal/equipo/team ./internal/equipo/teamcontract ./internal/equipo/triage ./internal/fakeclaude ./internal/fakecodex ./internal/fakeopencode ./internal/fakepi ./internal/idtest ./internal/ownermodetest ./internal/release ./internal/runner/checks ./internal/runner/connect ./internal/runner/containment ./internal/runner/containment/sysunix ./internal/runner/egress ./internal/runner/forge ./internal/runner/forge/forgetest ./internal/runner/heartbeat ./internal/runner/mac ./internal/runner/mcpresource ./internal/runner/metered ./internal/runner/planflow ./internal/runner/provider ./internal/runner/provider/claude ./internal/runner/provider/codex ./internal/runner/provider/gotoolchain ./internal/runner/provider/opencode ./internal/runner/provider/pi ./internal/runner/setup ./internal/runner/transporttest ./internal/runner/webread ./internal/runner/workspace ./internal/runnerproto ./internal/schedule ./internal/sealbox ./internal/specialist ./internal/stagingtest ./internal/taskplan ./internal/testci ./internal/toolproxy ./internal/websource ./internal/wire ./internal/wire/wireschema ./internal/wire/wiretest ./tools/drive
cache miss: amadan.net/oficina/equipo/internal/copydesk: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/equipo/team: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/forge: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/webread: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runnerproto: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/workspace: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/checks: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/containment: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/provider/opencode: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/testci: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/provider/pi: its inputs changed
--- FAIL amadan.net/oficina/equipo/internal/runner/metered TestMeteredRaceAdmitsExactlyOne
=== RUN TestMeteredRaceAdmitsExactlyOne
meter_test.go:205: round 1: ran map[], held map[ask:busy review:busy]
--- FAIL: TestMeteredRaceAdmitsExactlyOne (0.04s)
--- FAIL amadan.net/oficina/equipo/internal/runner/metered (package output)
FAIL
rastrillo-budget/v1 ran 2.151s
FAIL amadan.net/oficina/equipo/internal/runner/metered 2.190s
budget note: internal/equipo took 27.305s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/equipo/chat took 17.127s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/equipo/setup took 11.9s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/idtest took 43.835s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/release took 19.39s, over the 10s the default allows (measured on the run this cached result came from); reported only, timing fails on CI
budget note: internal/runner/containment took 49.724s, over the 15s its record on line 40 allows; reported only, timing fails on CI
budget note: internal/runner/workspace took 11.182s, over the 10s the default allows; reported only, timing fails on CI
receipt: test step 2m17.631s against a 60s target (the gate's other steps are not in this figure)
receipt: 35 packages ran, 25 cached, 18 without tests, 1 failed
receipt: slow package 1m10.355s amadan.net/oficina/equipo/internal/runner/provider/opencode
receipt: slow package 58.063s amadan.net/oficina/equipo/internal/runner/provider/pi
receipt: slow package 56.592s amadan.net/oficina/equipo/internal/runner/checks
receipt: slow package 49.724s amadan.net/oficina/equipo/internal/runner/containment
receipt: slow package 43.835s amadan.net/oficina/equipo/internal/idtest
receipt: slow test 24.28s amadan.net/oficina/equipo/internal/runner/provider/opencode TestOpenCodeAcceptanceHostileRepository
receipt: slow test 22.03s amadan.net/oficina/equipo/internal/runner/containment TestEngineeringOfflineGo
receipt: slow test 21.84s amadan.net/oficina/equipo/cmd/equipo-runner TestReleaseRunnerHasNoFakeWorker
receipt: slow test 12.65s amadan.net/oficina/equipo/internal/idtest TestIDCallbackGuardAndPendingNonce
receipt: slow test 11.65s amadan.net/oficina/equipo/internal/runner/provider/opencode TestOpenCodeP1OnlyOpenCodeReachable
rastrillo: budget test: go test failed
exit status 1
+ go test -tags testbuild -timeout 15m -v -run '^TestMeteredRaceAdmitsExactlyOne$' -count=1 ./internal/runner/metered (retry, once)
##############################################################################
FLAKE ./internal/runner/metered:TestMeteredRaceAdmitsExactlyOne rest d5bdedac06e43a9a7f3850530ec5c9a0584e1282 0.04s 25.12
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
machine: 32 CPUs, load 25.12, cpu waiting 12.75%, memory waiting 0.00%, io waiting 0.12%
--- shard 18 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
browser: /opt/chromium-156.0.8078.79-1_deb13u1/chrome: Chromium 156.0.8078.79
browser lane browser-headless-chat: ./internal/headless
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^TestBrowserChat$|^TestBrowserChatSendStaysOnPage$|^TestBrowserComposer$|^TestBrowserComposerReconcile$|^TestBrowserComposerFocus$|^TestBrowserComposerDock$|^TestBrowserDraftStreamsFormatted$|^TestBrowserDraftIsTheMessage$' ./internal/headless
--- FAIL amadan.net/oficina/equipo/internal/headless TestBrowserChat
=== RUN TestBrowserChat
time=2026-11-20T13:48:55.147Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-20T13:48:55.148Z level=INFO msg="startup phase done" phase=state_lock took=235µs
time=2026-11-20T13:48:55.148Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-20T13:48:55.148Z level=INFO msg="startup phase done" phase=claim_roots took=195µs
time=2026-11-20T13:48:55.148Z level=INFO msg="startup phase" phase=sweep
time=2026-11-20T13:48:55.211Z level=INFO msg="startup phase done" phase=sweep took=62.634ms
time=2026-11-20T13:48:55.211Z level=INFO msg="startup phase" phase=credentials
time=2026-11-20T13:48:55.211Z level=INFO msg="startup phase done" phase=credentials took=227µs
time=2026-11-20T13:48:55.211Z level=INFO msg="startup phase" phase=open_state
time=2026-11-20T13:48:55.263Z level=INFO msg="startup phase done" phase=open_state took=51.567ms
time=2026-11-20T13:48:55.263Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-20T13:48:55.264Z level=INFO msg=connecting host=127.0.0.1:33551 protocol=28
time=2026-11-20T13:48:55.265Z level=INFO msg=connected host=127.0.0.1:33551 took=1.354ms
time=2026-11-20T13:48:55.265Z level=INFO msg="capabilities gathering"
time=2026-11-20T13:48:55.267Z level=INFO msg="capabilities gathered" took=1.441ms tags=linux,claude,go
time=2026-11-20T13:48:55.272Z level=INFO msg="hello sent" protocol=28
time=2026-11-20T13:48:55.275Z level=INFO msg=welcome protocol=28 role=primary generation=1
time=2026-11-20T13:48:57.433Z level=INFO msg="connection checked" connection=claude-1 state=healthy
browser_test.go:46: waiting for [...document.querySelectorAll('[equipo-message="incoming"] [equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes('fake coordinator')): context deadline exceeded (last evaluation: context deadline exceeded)
--- FAIL: TestBrowserChat (6.43s)
--- FAIL amadan.net/oficina/equipo/internal/headless TestBrowserChatSendStaysOnPage
=== RUN TestBrowserChatSendStaysOnPage
time=2026-11-20T13:49:01.502Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-20T13:49:01.502Z level=INFO msg="startup phase done" phase=state_lock took=66µs
time=2026-11-20T13:49:01.502Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-20T13:49:01.502Z level=INFO msg="startup phase done" phase=claim_roots took=89µs
time=2026-11-20T13:49:01.502Z level=INFO msg="startup phase" phase=sweep
time=2026-11-20T13:49:01.567Z level=INFO msg="startup phase done" phase=sweep took=64.741ms
time=2026-11-20T13:49:01.567Z level=INFO msg="startup phase" phase=credentials
time=2026-11-20T13:49:01.567Z level=INFO msg="startup phase done" phase=credentials took=125µs
time=2026-11-20T13:49:01.567Z level=INFO msg="startup phase" phase=open_state
time=2026-11-20T13:49:01.647Z level=INFO msg="startup phase done" phase=open_state took=80.193ms
time=2026-11-20T13:49:01.647Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-20T13:49:01.648Z level=INFO msg=connecting host=127.0.0.1:35393 protocol=28
time=2026-11-20T13:49:01.654Z level=INFO msg=connected host=127.0.0.1:35393 took=6.507ms
time=2026-11-20T13:49:01.655Z level=INFO msg="capabilities gathering"
time=2026-11-20T13:49:01.655Z level=INFO msg="capabilities gathered" took=782µs tags=linux,claude,go
time=2026-11-20T13:49:01.658Z level=INFO msg="hello sent" protocol=28
time=2026-11-20T13:49:01.682Z level=INFO msg=welcome protocol=28 role=primary generation=1
time=2026-11-20T13:49:03.695Z level=INFO msg="connection checked" connection=claude-1 state=healthy
browser_test.go:108: waiting for [...document.querySelectorAll('[equipo-message="incoming"] [equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes('fake coordinator')): context deadline exceeded (last evaluation: context deadline exceeded)
--- FAIL: TestBrowserChatSendStaysOnPage (6.33s)
--- FAIL amadan.net/oficina/equipo/internal/headless TestBrowserDraftIsTheMessage
=== RUN TestBrowserDraftIsTheMessage
time=2026-11-20T13:49:07.848Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-20T13:49:07.848Z level=INFO msg="startup phase done" phase=state_lock took=159µs
time=2026-11-20T13:49:07.848Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-20T13:49:07.849Z level=INFO msg="startup phase done" phase=claim_roots took=137µs
time=2026-11-20T13:49:07.849Z level=INFO msg="startup phase" phase=sweep
time=2026-11-20T13:49:07.911Z level=INFO msg="startup phase done" phase=sweep took=62.241ms
time=2026-11-20T13:49:07.911Z level=INFO msg="startup phase" phase=credentials
time=2026-11-20T13:49:07.911Z level=INFO msg="startup phase done" phase=credentials took=108µs
time=2026-11-20T13:49:07.911Z level=INFO msg="startup phase" phase=open_state
time=2026-11-20T13:49:07.983Z level=INFO msg="startup phase done" phase=open_state took=72.414ms
time=2026-11-20T13:49:07.984Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-20T13:49:07.987Z level=INFO msg=connecting host=127.0.0.1:46245 protocol=28
time=2026-11-20T13:49:07.988Z level=INFO msg=connected host=127.0.0.1:46245 took=1.364ms
time=2026-11-20T13:49:07.989Z level=INFO msg="capabilities gathering"
time=2026-11-20T13:49:07.991Z level=INFO msg="capabilities gathered" took=2.152ms tags=linux,claude,go
time=2026-11-20T13:49:07.992Z level=INFO msg="hello sent" protocol=28
time=2026-11-20T13:49:08.000Z level=INFO msg=welcome protocol=28 role=primary generation=1
time=2026-11-20T13:49:10.364Z level=INFO msg="connection checked" connection=claude-1 state=healthy
browser_thinking_test.go:106: waiting for !!window.__m: context deadline exceeded (last evaluation: <nil>)
--- FAIL: TestBrowserDraftIsTheMessage (8.35s)
--- FAIL amadan.net/oficina/equipo/internal/headless (package output)
FAIL
rastrillo-budget/v1 ran 49.985s
FAIL amadan.net/oficina/equipo/internal/headless 50.329s
receipt: test step 52.366s against a 60s target (the gate's other steps are not in this figure)
receipt: 0 packages ran, 0 cached, 0 without tests, 1 failed
receipt: slow package 49.985s amadan.net/oficina/equipo/internal/headless
receipt: slow test 15.76s amadan.net/oficina/equipo/internal/headless TestBrowserDraftStreamsFormatted
receipt: slow test 8.35s amadan.net/oficina/equipo/internal/headless TestBrowserDraftIsTheMessage
receipt: slow test 7.97s amadan.net/oficina/equipo/internal/headless TestBrowserComposer
receipt: slow test 6.43s amadan.net/oficina/equipo/internal/headless TestBrowserChat
receipt: slow test 6.33s amadan.net/oficina/equipo/internal/headless TestBrowserChatSendStaysOnPage
rastrillo: budget test: go test failed
exit status 1
+ go test -tags browser,testbuild -timeout 15m -run '^TestBrowserChat$|^TestBrowserChatSendStaysOnPage$|^TestBrowserComposer$|^TestBrowserComposerReconcile$|^TestBrowserComposerFocus$|^TestBrowserComposerDock$|^TestBrowserDraftStreamsFormatted$|^TestBrowserDraftIsTheMessage$' -v -run '^TestBrowserChat$|^TestBrowserChatSendStaysOnPage$|^TestBrowserDraftIsTheMessage$' -count=1 ./internal/headless (retry, once)
##############################################################################
FLAKE ./internal/headless:TestBrowserChat browser-headless-chat d5bdedac06e43a9a7f3850530ec5c9a0584e1282 6.43s 54.15
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
##############################################################################
FLAKE ./internal/headless:TestBrowserChatSendStaysOnPage browser-headless-chat d5bdedac06e43a9a7f3850530ec5c9a0584e1282 6.33s 54.15
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
##############################################################################
FLAKE ./internal/headless:TestBrowserDraftIsTheMessage browser-headless-chat d5bdedac06e43a9a7f3850530ec5c9a0584e1282 8.35s 54.15
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
machine: 32 CPUs, load 52.43, cpu waiting 33.30%, memory waiting 0.00%, io waiting 0.35%
--- shard 19 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
browser: /opt/chromium-156.0.8078.79-1_deb13u1/chrome: Chromium 156.0.8078.79
browser lane browser-headless-work: ./internal/headless
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^TestBrowserTaskCard$|^TestBrowserReceiptFollowsReview$|^TestBrowserRailFollowsWork$|^TestBrowserTaskThread$|^TestBrowserAskAfterMerge$|^TestBrowserReceiptsDesktop$|^TestBrowserReceiptsTouch$' ./internal/headless
rastrillo: budget test: go test failed
--- FAIL amadan.net/oficina/equipo/internal/headless TestBrowserRailFollowsWork
=== RUN TestBrowserRailFollowsWork
time=2026-11-20T13:48:51.551Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-20T13:48:51.552Z level=INFO msg="startup phase done" phase=state_lock took=68µs
time=2026-11-20T13:48:51.552Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-20T13:48:51.552Z level=INFO msg="startup phase done" phase=claim_roots took=89µs
time=2026-11-20T13:48:51.552Z level=INFO msg="startup phase" phase=sweep
time=2026-11-20T13:48:51.585Z level=INFO msg="startup phase done" phase=sweep took=33.343ms
time=2026-11-20T13:48:51.585Z level=INFO msg="startup phase" phase=credentials
time=2026-11-20T13:48:51.586Z level=INFO msg="startup phase done" phase=credentials took=452µs
time=2026-11-20T13:48:51.586Z level=INFO msg="startup phase" phase=open_state
time=2026-11-20T13:48:51.630Z level=INFO msg="startup phase done" phase=open_state took=44.704ms
time=2026-11-20T13:48:51.631Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-20T13:48:51.632Z level=INFO msg=connecting host=127.0.0.1:34319 protocol=28
time=2026-11-20T13:48:51.633Z level=INFO msg=connected host=127.0.0.1:34319 took=1.062ms
time=2026-11-20T13:48:51.633Z level=INFO msg="capabilities gathering"
time=2026-11-20T13:48:51.634Z level=INFO msg="capabilities gathered" took=580µs tags=linux,claude,go
time=2026-11-20T13:48:51.638Z level=INFO msg="hello sent" protocol=28
time=2026-11-20T13:48:51.639Z level=INFO msg=welcome protocol=28 role=primary generation=1
time=2026-11-20T13:48:53.051Z level=INFO msg="connection checked" connection=claude-1 state=healthy
time=2026-11-20T13:49:02.862Z level=INFO msg="kept sessions" kept=1 bytes=2770 expired=0
time=2026-11-20T13:49:07.864Z level=INFO msg="kept sessions" kept=2 bytes=4922 expired=0
time=2026-11-20T13:49:08.791Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-20T13:49:08.791Z level=INFO msg="startup phase done" phase=state_lock took=140µs
time=2026-11-20T13:49:08.791Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-20T13:49:08.791Z level=INFO msg="startup phase done" phase=claim_roots took=79µs
time=2026-11-20T13:49:08.791Z level=INFO msg="startup phase" phase=sweep
time=2026-11-20T13:49:08.828Z level=INFO msg="startup phase done" phase=sweep took=37.132ms
time=2026-11-20T13:49:08.828Z level=INFO msg="startup phase" phase=credentials
time=2026-11-20T13:49:08.828Z level=INFO msg="startup phase done" phase=credentials took=129µs
time=2026-11-20T13:49:08.828Z level=INFO msg="startup phase" phase=open_state
time=2026-11-20T13:49:08.878Z level=INFO msg="startup phase done" phase=open_state took=50.277ms
time=2026-11-20T13:49:08.879Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-20T13:49:08.880Z level=INFO msg=connecting host=127.0.0.1:42705 protocol=28
time=2026-11-20T13:49:08.881Z level=INFO msg=connected host=127.0.0.1:42705 took=1.01ms
time=2026-11-20T13:49:08.881Z level=INFO msg="capabilities gathering"
time=2026-11-20T13:49:08.882Z level=INFO msg="capabilities gathered" took=625µs tags=linux,claude,go
time=2026-11-20T13:49:08.883Z level=INFO msg="hello sent" protocol=28
time=2026-11-20T13:49:08.889Z level=INFO msg=welcome protocol=28 role=primary generation=1
time=2026-11-20T13:49:11.022Z level=INFO msg="connection checked" connection=claude-1 state=healthy
browser_review_test.go:57: waiting for document.querySelector('#rail [data-specialist="engineering"]')?.dataset.state==='working' && document.querySelector('#rail [data-specialist="engineering"]').querySelector('[equipo-nav-task]')?.textContent==='Slow sidebar change' && document.querySelector('#nav-tasks [data-count]')?.textContent==='1': context deadline exceeded (last evaluation: <nil>)
--- FAIL: TestBrowserRailFollowsWork (23.67s)
--- FAIL amadan.net/oficina/equipo/internal/headless (package output)
FAIL
rastrillo-budget/v1 ran 1m38.233s
FAIL amadan.net/oficina/equipo/internal/headless 98.549s
receipt: test step 1m39.889s against a 60s target (the gate's other steps are not in this figure)
receipt: 0 packages ran, 0 cached, 0 without tests, 1 failed
receipt: slow package 1m38.233s amadan.net/oficina/equipo/internal/headless
receipt: slow test 27.39s amadan.net/oficina/equipo/internal/headless TestBrowserTaskThread
receipt: slow test 23.67s amadan.net/oficina/equipo/internal/headless TestBrowserRailFollowsWork
receipt: slow test 14.81s amadan.net/oficina/equipo/internal/headless TestBrowserReceiptFollowsReview
receipt: slow test 11.28s amadan.net/oficina/equipo/internal/headless TestBrowserAskAfterMerge
receipt: slow test 11.07s amadan.net/oficina/equipo/internal/headless TestBrowserTaskCard
exit status 1
+ go test -tags browser,testbuild -timeout 15m -run '^TestBrowserTaskCard$|^TestBrowserReceiptFollowsReview$|^TestBrowserRailFollowsWork$|^TestBrowserTaskThread$|^TestBrowserAskAfterMerge$|^TestBrowserReceiptsDesktop$|^TestBrowserReceiptsTouch$' -v -run '^TestBrowserRailFollowsWork$' -count=1 ./internal/headless (retry, once)
##############################################################################
FLAKE ./internal/headless:TestBrowserRailFollowsWork browser-headless-work d5bdedac06e43a9a7f3850530ec5c9a0584e1282 23.67s 59.90
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
machine: 32 CPUs, load 42.18, cpu waiting 26.40%, memory waiting 0.00%, io waiting 0.27%
--- shard 20 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
browser: /opt/chromium-156.0.8078.79-1_deb13u1/chrome: Chromium 156.0.8078.79
browser lane browser-headless-connections: ./internal/headless
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^TestBrowserConnections|^TestBrowserPasteBox$|^TestBrowserPasteCopiesItsBox$' ./internal/headless
receipt: test step 1m48.718s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m46.852s amadan.net/oficina/equipo/internal/headless
receipt: slow test 17.29s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsConversation
receipt: slow test 14.63s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsAdd
receipt: slow test 13.21s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsAddPage
receipt: slow test 10.97s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsMeteredLimitRequired
receipt: slow test 10.51s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsOpenCodeGoLimitRequired
machine: 32 CPUs, load 52.43, cpu waiting 33.30%, memory waiting 0.00%, io waiting 0.35%
--- shard 21 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
browser: /opt/chromium-156.0.8078.79-1_deb13u1/chrome: Chromium 156.0.8078.79
browser lane browser-headless-rest: ./internal/headless
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^(TestBrowserAskAfterMerge|TestBrowserChat|TestBrowserChatSendStaysOnPage|TestBrowserComposer|TestBrowserComposerDock|TestBrowserComposerFocus|TestBrowserComposerReconcile|TestBrowserConnectionsAdd|TestBrowserConnectionsAddPage|TestBrowserConnectionsConversation|TestBrowserConnectionsCopyLink|TestBrowserConnectionsEndedNote|TestBrowserConnectionsMeteredLimitRequired|TestBrowserConnectionsOpenCodeGoLimitRequired|TestBrowserConnectionsSignIn|TestBrowserConnectionsSignInSwitch|TestBrowserConnectionsToken|TestBrowserCopyContinue|TestBrowserCopySettingAndFlag|TestBrowserDraftIsTheMessage|TestBrowserDraftStreamsFormatted|TestBrowserEmptyExplore|TestBrowserMoveIn|TestBrowserNotebook|TestBrowserNotebookLook|TestBrowserPasteBox|TestBrowserPasteBoxLook|TestBrowserPasteCopiesItsBox|TestBrowserRailFollowsWork|TestBrowserReceiptFollowsReview|TestBrowserReceiptsDesktop|TestBrowserReceiptsTouch|TestBrowserRefreshRace|TestBrowserStalePageReloads|TestBrowserTaskCard|TestBrowserTaskThread|TestBrowserThinkingAndCards|TestBrowserUsageAndAdvice|TestBrowserWaitingTurns|TestNotebookScreenshots)$' -skip '^TestBrowserChat$|^TestBrowserChatSendStaysOnPage$|^TestBrowserComposer$|^TestBrowserComposerReconcile$|^TestBrowserComposerFocus$|^TestBrowserComposerDock$|^TestBrowserDraftStreamsFormatted$|^TestBrowserDraftIsTheMessage$|^TestBrowserTaskCard$|^TestBrowserReceiptFollowsReview$|^TestBrowserRailFollowsWork$|^TestBrowserTaskThread$|^TestBrowserAskAfterMerge$|^TestBrowserReceiptsDesktop$|^TestBrowserReceiptsTouch$|^TestBrowserConnections|^TestBrowserPasteBox$|^TestBrowserPasteCopiesItsBox$' ./internal/headless
rastrillo: budget test: go test failed
--- FAIL amadan.net/oficina/equipo/internal/headless TestBrowserEmptyExplore
=== RUN TestBrowserEmptyExplore
time=2026-11-20T13:49:44.704Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-20T13:49:44.704Z level=INFO msg="startup phase done" phase=state_lock took=75µs
time=2026-11-20T13:49:44.704Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-20T13:49:44.704Z level=INFO msg="startup phase done" phase=claim_roots took=95µs
time=2026-11-20T13:49:44.704Z level=INFO msg="startup phase" phase=sweep
time=2026-11-20T13:49:44.734Z level=INFO msg="startup phase done" phase=sweep took=29.172ms
time=2026-11-20T13:49:44.734Z level=INFO msg="startup phase" phase=credentials
time=2026-11-20T13:49:44.734Z level=INFO msg="startup phase done" phase=credentials took=225µs
time=2026-11-20T13:49:44.734Z level=INFO msg="startup phase" phase=open_state
time=2026-11-20T13:49:44.776Z level=INFO msg="startup phase done" phase=open_state took=41.706ms
time=2026-11-20T13:49:44.776Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-20T13:49:44.777Z level=INFO msg=connecting host=127.0.0.1:45057 protocol=28
time=2026-11-20T13:49:44.778Z level=INFO msg=connected host=127.0.0.1:45057 took=999µs
time=2026-11-20T13:49:44.778Z level=INFO msg="capabilities gathering"
time=2026-11-20T13:49:44.779Z level=INFO msg="capabilities gathered" took=919µs tags=linux,claude,go
time=2026-11-20T13:49:44.780Z level=INFO msg="hello sent" protocol=28
time=2026-11-20T13:49:44.786Z level=INFO msg=welcome protocol=28 role=primary generation=1
time=2026-11-20T13:49:46.007Z level=INFO msg="connection checked" connection=claude-1 state=healthy
browser_receipts_test.go:169: waiting for [...document.querySelectorAll('[equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes("I'm your coordinator")): context deadline exceeded (last evaluation: <nil>)
--- FAIL: TestBrowserEmptyExplore (5.91s)
--- FAIL amadan.net/oficina/equipo/internal/headless (package output)
FAIL
rastrillo-budget/v1 ran 1m38.013s
FAIL amadan.net/oficina/equipo/internal/headless 98.346s
receipt: test step 1m40.369s against a 60s target (the gate's other steps are not in this figure)
receipt: 0 packages ran, 0 cached, 0 without tests, 1 failed
receipt: slow package 1m38.013s amadan.net/oficina/equipo/internal/headless
receipt: slow test 15.48s amadan.net/oficina/equipo/internal/headless TestBrowserThinkingAndCards
receipt: slow test 13.46s amadan.net/oficina/equipo/internal/headless TestBrowserWaitingTurns
receipt: slow test 11.61s amadan.net/oficina/equipo/internal/headless TestBrowserStalePageReloads
receipt: slow test 11.08s amadan.net/oficina/equipo/internal/headless TestBrowserMoveIn
receipt: slow test 8.69s amadan.net/oficina/equipo/internal/headless TestBrowserNotebookLook
exit status 1
+ go test -tags browser,testbuild -timeout 15m -run '^(TestBrowserAskAfterMerge|TestBrowserChat|TestBrowserChatSendStaysOnPage|TestBrowserComposer|TestBrowserComposerDock|TestBrowserComposerFocus|TestBrowserComposerReconcile|TestBrowserConnectionsAdd|TestBrowserConnectionsAddPage|TestBrowserConnectionsConversation|TestBrowserConnectionsCopyLink|TestBrowserConnectionsEndedNote|TestBrowserConnectionsMeteredLimitRequired|TestBrowserConnectionsOpenCodeGoLimitRequired|TestBrowserConnectionsSignIn|TestBrowserConnectionsSignInSwitch|TestBrowserConnectionsToken|TestBrowserCopyContinue|TestBrowserCopySettingAndFlag|TestBrowserDraftIsTheMessage|TestBrowserDraftStreamsFormatted|TestBrowserEmptyExplore|TestBrowserMoveIn|TestBrowserNotebook|TestBrowserNotebookLook|TestBrowserPasteBox|TestBrowserPasteBoxLook|TestBrowserPasteCopiesItsBox|TestBrowserRailFollowsWork|TestBrowserReceiptFollowsReview|TestBrowserReceiptsDesktop|TestBrowserReceiptsTouch|TestBrowserRefreshRace|TestBrowserStalePageReloads|TestBrowserTaskCard|TestBrowserTaskThread|TestBrowserThinkingAndCards|TestBrowserUsageAndAdvice|TestBrowserWaitingTurns|TestNotebookScreenshots)$' -skip '^TestBrowserChat$|^TestBrowserChatSendStaysOnPage$|^TestBrowserComposer$|^TestBrowserComposerReconcile$|^TestBrowserComposerFocus$|^TestBrowserComposerDock$|^TestBrowserDraftStreamsFormatted$|^TestBrowserDraftIsTheMessage$|^TestBrowserTaskCard$|^TestBrowserReceiptFollowsReview$|^TestBrowserRailFollowsWork$|^TestBrowserTaskThread$|^TestBrowserAskAfterMerge$|^TestBrowserReceiptsDesktop$|^TestBrowserReceiptsTouch$|^TestBrowserConnections|^TestBrowserPasteBox$|^TestBrowserPasteCopiesItsBox$' -v -run '^TestBrowserEmptyExplore$' -count=1 ./internal/headless (retry, once)
##############################################################################
FLAKE ./internal/headless:TestBrowserEmptyExplore browser-headless-rest d5bdedac06e43a9a7f3850530ec5c9a0584e1282 5.91s 59.90
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
machine: 32 CPUs, load 52.43, cpu waiting 33.30%, memory waiting 0.00%, io waiting 0.35%
--- shard 22 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
browser: /opt/chromium-156.0.8078.79-1_deb13u1/chrome: Chromium 156.0.8078.79
browser lane browser-rest: ./internal/equipo
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^(TestBrowserPreviewBlocksNavigation)$' ./internal/equipo
receipt: test step 2.315s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 517ms amadan.net/oficina/equipo/internal/equipo
receipt: slow test 520ms amadan.net/oficina/equipo/internal/equipo TestBrowserPreviewBlocksNavigation
browser lane browser-rest: ./internal/idtest
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^(TestBrowserOficinaIDDoor)$' ./internal/idtest
receipt: test step 2.998s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1.695s amadan.net/oficina/equipo/internal/idtest
receipt: slow test 1.69s amadan.net/oficina/equipo/internal/idtest TestBrowserOficinaIDDoor
browser lane browser-rest: ./internal/plan3test
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^(TestTeamsHierarchyBrowser)$' ./internal/plan3test
receipt: test step 3.134s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1.85s amadan.net/oficina/equipo/internal/plan3test
receipt: slow test 1.85s amadan.net/oficina/equipo/internal/plan3test TestTeamsHierarchyBrowser
browser lane browser-rest: ./internal/thintest
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^(TestBrowserAccessEmojiByline|TestBrowserAccessFinalOutcomes|TestBrowserAccessRequest|TestBrowserAccessReview|TestBrowserActivitySubjects|TestBrowserAutonomySettings|TestBrowserCoordinatorQueue|TestBrowserEmptyConversation|TestBrowserHousekeeping|TestBrowserInnerGallery|TestBrowserInnerScreens|TestBrowserInstantThinking|TestBrowserInstantThinkingQueued|TestBrowserMachines|TestBrowserPhoneIndex|TestBrowserPlacementQuestionAndPending|TestBrowserProjectPlacement|TestBrowserProjectsList|TestBrowserReportActionFeedback|TestBrowserReportNextSteps|TestBrowserReportThread|TestBrowserRollup|TestBrowserRosterAlignment|TestBrowserRosterDecisionStates|TestBrowserRosterQuietDay|TestBrowserRosterReports|TestBrowserRosterSetAside|TestBrowserRosterSubchat|TestBrowserRosterThinking|TestBrowserRosterVisual|TestBrowserSettingsHousekeepingGroups|TestBrowserSettingsMenu|TestBrowserSettingsRail|TestBrowserSettingsSaveBar|TestBrowserSettingsShots|TestBrowserSettingsStayOnPage|TestBrowserSettingsTeams|TestBrowserShipsButtons|TestBrowserSpecialistRows|TestBrowserSpendFollowsAnswers|TestBrowserTaskRows|TestBrowserTeamPanel|TestBrowserThinkingCycles|TestBrowserThinkingLinesClear|TestBrowserThinkingSteady|TestBrowserThinkingWords|TestBrowserTokenRowEmail|TestBrowserTrackPulse|TestBrowserTrackStarCentre)$' ./internal/thintest
receipt: test step 3m24.806s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 3m23.201s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 17.93s amadan.net/oficina/equipo/internal/thintest TestBrowserAccessRequest
receipt: slow test 14.34s amadan.net/oficina/equipo/internal/thintest TestBrowserSettingsTeams
receipt: slow test 12.01s amadan.net/oficina/equipo/internal/thintest TestBrowserThinkingCycles
receipt: slow test 10.63s amadan.net/oficina/equipo/internal/thintest TestBrowserPlacementQuestionAndPending
receipt: slow test 8.19s amadan.net/oficina/equipo/internal/thintest TestBrowserInnerScreens
machine: 32 CPUs, load 12.06, cpu waiting 5.93%, memory waiting 0.00%, io waiting 0.05%
--- shard 23 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
shard 23: make test-quarantine
python3 scripts/ci-test.py quarantine
quarantine: 12 tests from scripts/ci-quarantine.txt; a failure is retried once, and a pass on the retry is reported as a flake
+ go test -tags testbuild -timeout 15m -v -run '^TestHeadlessConnections$/^A5_cancel_and_sign_out$|^TestHeadlessConnections$/^C4_claude_sign_in$|^TestHeadlessConnections$/^C5_engineering_failover$|^TestHeadlessConnections$/^C5_engineering_to_codex$|^TestHeadlessConnections$/^C5_engineering_waits$' ./internal/headless (58s)
ok ./internal/headless TestHeadlessConnections/A5_cancel_and_sign_out 5.20s
ok ./internal/headless TestHeadlessConnections/C4_claude_sign_in 1.36s
ok ./internal/headless TestHeadlessConnections/C5_engineering_failover 11.01s
ok ./internal/headless TestHeadlessConnections/C5_engineering_to_codex 12.03s
ok ./internal/headless TestHeadlessConnections/C5_engineering_waits 26.15s
+ go test -tags testbuild -timeout 15m -v -run '^TestHeadlessConnections$/^C5_review_auth$|^TestHeadlessConnections$/^C5_review_failover$|^TestHeadlessConnections$/^C5_review_on_codex$|^TestHeadlessConnections$/^C5_review_other_family_first$' ./internal/headless (75s)
ok ./internal/headless TestHeadlessConnections/C5_review_auth 30.59s
ok ./internal/headless TestHeadlessConnections/C5_review_failover 13.96s
ok ./internal/headless TestHeadlessConnections/C5_review_on_codex 12.45s
ok ./internal/headless TestHeadlessConnections/C5_review_other_family_first 15.75s
+ go test -tags testbuild -timeout 15m -v -run '^TestMixedVersions$' ./internal/headless (25s)
ok ./internal/headless TestMixedVersions 22.55s
+ go test -tags testbuild -timeout 15m -v -run '^TestCheckSandboxDeniedPathsTampering$' ./internal/runner/checks (2s)
ok ./internal/runner/checks TestCheckSandboxDeniedPathsTampering 0.93s
+ go test -tags testbuild -timeout 15m -v -run '^TestRunnerCancelAndSupersede$' ./internal/runner/thin (2s)
ok ./internal/runner/thin TestRunnerCancelAndSupersede 0.06s
quarantine: 0 flaked (passed on the retry), 0 failed
machine: 32 CPUs, load 65.10, cpu waiting 40.29%, memory waiting 0.00%, io waiting 0.62%
--- shard 24 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
shard 24: make runner-host
python3 scripts/runner-prerequisites.py
CGO_ENABLED=0 RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py retried runner-host -run 'TestDirect|TestProvider|TestCheckSandbox' -count=1 ./internal/runner/provider/... ./internal/runner/checks
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -no-time -run 'TestDirect|TestProvider|TestCheckSandbox' -count=1 ./internal/runner/provider/... ./internal/runner/checks
receipt: test step 13.516s against a 60s target (the gate's other steps are not in this figure)
receipt: 4 packages ran, 0 cached, 3 without tests, 0 failed
receipt: slow package 8.145s amadan.net/oficina/equipo/internal/runner/checks
receipt: slow package 196ms amadan.net/oficina/equipo/internal/runner/provider/claude
receipt: slow package 72ms amadan.net/oficina/equipo/internal/runner/provider/codex
receipt: slow package 3ms amadan.net/oficina/equipo/internal/runner/provider
receipt: slow package 0s amadan.net/oficina/equipo/internal/runner/provider/gotoolchain
receipt: slow test 5.83s amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPathsGoFixture
receipt: slow test 1.8s amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPaths
receipt: slow test 380ms amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPathsCache
receipt: slow test 200ms amadan.net/oficina/equipo/internal/runner/provider/claude TestDirectJournalAdapterBarrier
receipt: slow test 110ms amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxToolchain
CGO_ENABLED=0 RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py retried runner-host -run '^TestNamespace' -count=1 ./internal/runner/containment
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -no-time -run '^TestNamespace' -count=1 ./internal/runner/containment
receipt: test step 3.525s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 3.139s amadan.net/oficina/equipo/internal/runner/containment
receipt: slow test 300ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceReadOnlyScratch
receipt: slow test 210ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceRecoveryUnavailableProof
receipt: slow test 130ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceDirectPolicyAdmission
receipt: slow test 110ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceRecoveryCleansScratch
receipt: slow test 110ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceRecoveryMalformedRecord
machine: 32 CPUs, load 10.77, cpu waiting 10.48%, memory waiting 0.00%, io waiting 1.65%
--- shard 25 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: runner-dead-references started 30s late; cpu waiting 36.8%, load 22.67
shard 25: make runner-dead-references lanes-check build vet fmt-check budget migration-check
python3 scripts/runner-dead-references.py
reference scan: 2478 text files, 2846 matches, 0 failures
python3 scripts/ci-test.py check
lanes: 18 lanes and 5 browser lanes run every test once; 20-check@29
CGO_ENABLED=0 go build ./...
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -o /dev/null ./cmd/equipo-runner
go vet ./...
go vet -tags testbuild ./internal/runner/thin ./internal/headless
GOOS=darwin GOARCH=arm64 go vet ./cmd/equipo-runner/... ./internal/runner/... ./internal/wire/... ./internal/release/...
go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget size
budget size: 88 directories within budget
CGO_ENABLED=0 go test ./internal/equipo -run '^TestMigrationModels$' -count=1
ok amadan.net/oficina/equipo/internal/equipo 2.523s
machine: 32 CPUs, load 65.10, cpu waiting 40.29%, memory waiting 0.00%, io waiting 0.62%
--- shard 26 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: staticcheck started 30s late; cpu waiting 36.8%, load 22.67
shard 26: make staticcheck
go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 -tags browser,perf,testbuild ./...
machine: 32 CPUs, load 54.15, cpu waiting 34.90%, memory waiting 0.00%, io waiting 0.90%
--- shard 27 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: govulncheck started 30s late; cpu waiting 36.8%, load 22.67
shard 27: make govulncheck
go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 ./...
=== Symbol Results ===
No vulnerabilities found.
Your code is affected by 0 vulnerabilities.
This scan also found 0 vulnerabilities in packages you import and 5
vulnerabilities in modules you require, but your code doesn't appear to call
these vulnerabilities.
Use '-show verbose' for more details.
machine: 32 CPUs, load 30.46, cpu waiting 22.67%, memory waiting 0.00%, io waiting 1.18%
--- shard 28 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: gitleaks started 30s late; cpu waiting 36.8%, load 22.67
shard 28: make gitleaks
[90m1:48PM[0m [32mINF[0m [1mUnknown SCM platform. Use --platform to include links in findings.[0m [36mhost=[0mamadan.net
[90m1:49PM[0m [32mINF[0m [1m1055 commits scanned.[0m
[90m1:49PM[0m [32mINF[0m [1mscanned ~60354008 bytes (60.35 MB) in 24.3s[0m
[90m1:49PM[0m [32mINF[0m [1mno leaks found[0m
machine: 32 CPUs, load 54.15, cpu waiting 34.90%, memory waiting 0.00%, io waiting 0.90%
=== perf ===
go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -no-time -require TestPerfScreens,TestPerfBoot -tags perf -count=1 -p 1 -parallel 1 -run '^TestPerf' ./...
perf: GET /: median 1.171ms, worst 1.242ms, budget 150ms
perf: GET /api/runner/protocol: median 91µs, worst 118µs, budget 150ms
perf: GET /api/v1/account-setups/{id}: median 647µs, worst 691µs, budget 150ms
perf: GET /api/v1/accounts: median 495µs, worst 1.823ms, budget 150ms
perf: GET /api/v1/auth/devices: median 473µs, worst 496µs, budget 150ms
perf: GET /api/v1/budgets: median 495µs, worst 560µs, budget 150ms
perf: GET /api/v1/capabilities: median 253µs, worst 285µs, budget 150ms
perf: GET /api/v1/cards/{id}: median 1.28ms, worst 1.382ms, budget 150ms
perf: GET /api/v1/connections: median 592µs, worst 632µs, budget 150ms
perf: GET /api/v1/connections/{id}: median 561µs, worst 614µs, budget 150ms
perf: GET /api/v1/conversation: median 901µs, worst 952µs, budget 150ms
perf: GET /api/v1/conversation/cards: median 1.412ms, worst 1.473ms, budget 150ms
perf: GET /api/v1/coordinator: median 1.703ms, worst 1.816ms, budget 150ms
perf: GET /api/v1/invites/{id}: median 476µs, worst 591µs, budget 150ms
perf: GET /api/v1/journey: median 7.616ms, worst 7.821ms, budget 150ms
perf: GET /api/v1/me: median 439µs, worst 459µs, budget 150ms
perf: GET /api/v1/me/settings: median 510µs, worst 528µs, budget 150ms
perf: GET /api/v1/needs-you: median 7.428ms, worst 7.536ms, budget 150ms
perf: GET /api/v1/notifications: median 1.731ms, worst 1.812ms, budget 150ms
perf: GET /api/v1/onboarding: median 401µs, worst 457µs, budget 150ms
perf: GET /api/v1/people: median 451µs, worst 543µs, budget 150ms
perf: GET /api/v1/playbooks: median 589µs, worst 663µs, budget 150ms
perf: GET /api/v1/playbooks/{id}: median 541µs, worst 576µs, budget 150ms
perf: GET /api/v1/playbooks/{id}/template-diff: median 850µs, worst 928µs, budget 150ms
perf: GET /api/v1/preferences: median 746µs, worst 800µs, budget 150ms
perf: GET /api/v1/projects/{id}: median 455µs, worst 477µs, budget 150ms
perf: GET /api/v1/projects/{id}/settings: median 598µs, worst 624µs, budget 150ms
perf: GET /api/v1/roster: median 475µs, worst 517µs, budget 150ms
perf: GET /api/v1/runners/{id}: median 441µs, worst 465µs, budget 150ms
perf: GET /api/v1/specialists: median 8.329ms, worst 8.506ms, budget 150ms
perf: GET /api/v1/specialists/{id}: median 8.058ms, worst 8.223ms, budget 150ms
perf: GET /api/v1/specialists/{id}/template-diff: median 852µs, worst 941µs, budget 150ms
perf: GET /api/v1/tasks/{id}/plan: median 1.097ms, worst 1.206ms, budget 150ms
perf: GET /api/v1/tasks/{id}/thread: median 715µs, worst 773µs, budget 150ms
perf: GET /api/v1/teams: median 433µs, worst 468µs, budget 150ms
perf: GET /api/v1/templates: median 600µs, worst 671µs, budget 150ms
perf: GET /api/v1/templates/{id}: median 458µs, worst 531µs, budget 150ms
perf: GET /auth/callback: median 80µs, worst 102µs, budget 150ms
perf: GET /auth/devices/{id}: median 3.431ms, worst 3.71ms, budget 150ms
perf: GET /auth/verify: median 91µs, worst 134µs, budget 150ms
perf: GET /connections: median 3.948ms, worst 6.434ms, budget 150ms
perf: GET /conversation: median 7.681ms, worst 8.125ms, budget 150ms
perf: GET /conversation/connections: median 253µs, worst 265µs, budget 150ms
perf: GET /conversation/notebook: median 245µs, worst 288µs, budget 150ms
perf: GET /conversation/settings: median 3.939ms, worst 4.246ms, budget 150ms
perf: GET /conversation/settings/autonomy: median 3.633ms, worst 3.708ms, budget 150ms
perf: GET /conversation/settings/connections: median 6.167ms, worst 6.343ms, budget 150ms
perf: GET /conversation/settings/connections/add: median 6.612ms, worst 6.648ms, budget 150ms
perf: GET /conversation/settings/copy: median 3.715ms, worst 3.766ms, budget 150ms
perf: GET /conversation/settings/housekeeping: median 4.196ms, worst 4.588ms, budget 150ms
perf: GET /conversation/settings/machines: median 4.742ms, worst 6.171ms, budget 150ms
perf: GET /conversation/settings/machines/add: median 4.861ms, worst 5.029ms, budget 150ms
perf: GET /conversation/settings/notebook: median 3.517ms, worst 3.57ms, budget 150ms
perf: GET /conversation/settings/thinking: median 3.991ms, worst 4.13ms, budget 150ms
perf: GET /housekeeping: median 3.785ms, worst 3.892ms, budget 150ms
perf: GET /invites/new: median 588µs, worst 618µs, budget 150ms
perf: GET /invites/{id}: median 658µs, worst 703µs, budget 150ms
perf: GET /jobs: median 3.267ms, worst 3.384ms, budget 150ms
perf: GET /jobs/{id}: median 4.422ms, worst 4.545ms, budget 150ms
perf: GET /journey: median 11.9ms, worst 12.042ms, budget 150ms
perf: GET /nav/rail: median 3.25ms, worst 6.505ms, budget 150ms
perf: GET /needs-you: median 12.028ms, worst 12.268ms, budget 150ms
perf: GET /onboarding: median 4.309ms, worst 4.401ms, budget 150ms
perf: GET /people: median 3.378ms, worst 3.524ms, budget 150ms
perf: GET /playbook-suggestions/{suggestion}: median 5.094ms, worst 5.367ms, budget 150ms
perf: GET /playbooks: median 4.378ms, worst 4.638ms, budget 150ms
perf: GET /playbooks/new: median 4.541ms, worst 4.573ms, budget 150ms
perf: GET /playbooks/{id}: median 5.454ms, worst 5.577ms, budget 150ms
perf: GET /playbooks/{id}/edit: median 5.353ms, worst 5.67ms, budget 150ms
perf: GET /playbooks/{id}/template-diff: median 4.324ms, worst 4.488ms, budget 150ms
perf: GET /preferences: median 4.5ms, worst 7.116ms, budget 150ms
perf: GET /preferences/sources/{source}: median 4.068ms, worst 4.328ms, budget 150ms
perf: GET /projects: median 5.416ms, worst 5.714ms, budget 150ms
perf: GET /projects/accounts: median 3.707ms, worst 3.885ms, budget 150ms
perf: GET /projects/new: median 3.706ms, worst 3.817ms, budget 150ms
perf: GET /projects/{id}: median 10.431ms, worst 10.94ms, budget 150ms
perf: GET /projects/{id}/edit: median 3.787ms, worst 3.839ms, budget 150ms
perf: GET /runners/enrol: median 4.62ms, worst 4.84ms, budget 150ms
perf: GET /settings: median 3.425ms, worst 3.52ms, budget 150ms
perf: GET /settings/coordinator: median 5.381ms, worst 5.543ms, budget 150ms
perf: GET /settings/devices: median 3.56ms, worst 5.968ms, budget 150ms
perf: GET /settings/recovery: median 3.563ms, worst 3.636ms, budget 150ms
perf: GET /settings/recovery/release: median 3.384ms, worst 3.455ms, budget 150ms
perf: GET /settings/thinking: median 228µs, worst 281µs, budget 150ms
perf: GET /signin: median 321µs, worst 357µs, budget 150ms
perf: GET /specialists/new: median 3.399ms, worst 3.484ms, budget 150ms
perf: GET /specialists/{key}: median 10.879ms, worst 11.012ms, budget 150ms
perf: GET /specialists/{key}/edit: median 3.672ms, worst 3.722ms, budget 150ms
perf: GET /specialists/{key}/template-diff: median 3.716ms, worst 3.778ms, budget 150ms
perf: GET /tasks: median 5.134ms, worst 5.253ms, budget 150ms
perf: GET /tasks/new: median 3.147ms, worst 3.209ms, budget 150ms
perf: GET /tasks/{id}: median 5.539ms, worst 5.683ms, budget 150ms
perf: GET /tasks/{id}/merge: median 5.245ms, worst 5.447ms, budget 150ms
perf: GET /tasks/{id}/move: median 4.798ms, worst 5.06ms, budget 150ms
perf: GET /tasks/{id}/plan: median 5.91ms, worst 6.288ms, budget 150ms
perf: GET /tasks/{id}/preview: median 1.553ms, worst 1.656ms, budget 150ms
perf: GET /tasks/{id}/questions/{question}: median 5.233ms, worst 5.435ms, budget 150ms
perf: GET /tasks/{id}/rendered-change: median 4.891ms, worst 4.994ms, budget 150ms
perf: GET /tasks/{id}/rendered-change/{hash}.png: median 4.498ms, worst 4.56ms, budget 150ms
perf: GET /tasks/{id}/thread: median 8.256ms, worst 8.485ms, budget 150ms
perf: GET /team/{specialist}: median 4.3ms, worst 4.56ms, budget 150ms
perf: GET /teams: median 10.762ms, worst 13.238ms, budget 150ms
perf: GET /templates: median 3.463ms, worst 3.591ms, budget 150ms
perf: GET /usage: median 4.363ms, worst 4.417ms, budget 150ms
perf: GET /work: median 3.066ms, worst 3.09ms, budget 150ms
perf: cold boot: median 262ms of [260.759063ms 261.569092ms 263.766843ms], budget 500ms
receipt: test step 47.083s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 84 without tests, 0 failed
receipt: slow package 8.991s amadan.net/oficina/equipo/internal/equipotest
receipt: slow package 0s amadan.net/oficina/equipo/cmd/equipo-runner
receipt: slow package 0s amadan.net/oficina/equipo/cmd/equipo-tool-proxy
receipt: slow package 0s amadan.net/oficina/equipo/internal/advice
receipt: slow package 0s amadan.net/oficina/equipo/internal/attach
receipt: slow test 8.15s amadan.net/oficina/equipo/internal/equipotest TestPerfScreens
receipt: slow test 840ms amadan.net/oficina/equipo/internal/equipotest TestPerfBoot
=== cache ===
ci-box: build cache /home/ci/work/repos/oficina__equipo/cache/go-build: 3.92 GiB in 24259 files
ci-box: module cache /home/ci/work/repos/oficina__equipo/cache/go-mod: 0.84 GiB in 27329 files
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index b5b0f186..1df51253 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -14,8 +14,8 @@ perf GET /* skip Unknown private paths render 404; this fallback contains no scr |
| time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial reruns measured 18.079s and 22.031s. Keep migration, recovery, accounting and concurrency assertions; 60s leaves 30 percent headroom above loaded CI. |
| time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage. |
| -size internal/equipo 21407 - Fable follow-up: base and diagnostic gates, preview isolation and provenance guards; empty conversation starters (copy and the scriptless draft); measured 21394/3196 source/test lines. |
| -size internal/wire 6637 - Fable follow-up: base and diagnostic gates, preview isolation and provenance guards; measured 6637/2972 source/test lines. |
| +size internal/equipo 21493 - Merge main conversation starters and work status with native push configuration; measured 21493/3385 source/test lines. |
| +size internal/wire 6768 - Native slice 2 push registrations and set aside, with main integrated; measured 6768/2972 source/test lines. |
| size internal/equipotest - 12013 Task 21 repairs historical migration and conversation fixtures after Plan 3; measured 0/12013 source/test lines. |
| time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded); |
| time internal/runner 330s Plan 3 CI repair measured 292.120s for the full package (controller CI 472.184s). |
| @@ -30,7 +30,7 @@ size internal/runner/provider 5603 - Fable follow-up: base and diagnostic gates, |
| time internal/plan3test 300s Initial cap for combined browser and runner acceptance; measure at both usable stops. |
| -size internal/plan3test - 11358 Plan 3 release-boundary and copy-inventory contracts in one package; measured 940/11358 source/test lines. |
| +size internal/plan3test - 11446 Plan 3 release-boundary and copy-inventory contracts in one package, and native slice 2 push registration lifetime; measured 940/11446 source/test lines. |
| time internal/runner/forge 20s Plan 3 CI repair measured 10.527s for the full package (controller CI 10.407s). |
| time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full package (controller CI 10.709s); |
| @@ -56,7 +56,7 @@ perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for device |
| perf GET /api/v1/assistant/snapshot skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen. |
| perf GET /api/v1/assistant/messages skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen. |
| perf GET /api/v1/assistant/events skip Assistant event stream (Server-Sent Events), bearer-only and long-lived; not a screen. |
| -size internal/equipo/chat 31301 - Fable follow-up: base and diagnostic gates, preview isolation and provenance guards; measured 31167/6180 source/test lines. |
| +size internal/equipo/chat 32021 - Merge main carried messages with native push and activity review fixes; measured 32021/6905 source/test lines. |
| perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}. |
| perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}. |
| perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections. |
diff --git a/cmd/equipo/main.go b/cmd/equipo/main.go| index 5f3930a7..6b63bc68 100644 |
| --- a/cmd/equipo/main.go |
| +++ b/cmd/equipo/main.go |
| @@ -34,6 +34,10 @@ func run(logger *slog.Logger, started time.Time) error { |
| if err != nil { |
| return err |
| } |
| + // Pushes too: only here, where Equipo serves. |
| + if cfg.Push, err = equipo.Pusher(cfg, logger, os.Getenv); err != nil { |
| + return err |
| + } |
| opts, err := rastrillo.Resolve(rastrillo.Options{DBPath: cfg.DatabaseName, Logger: logger}) |
| if err != nil { |
| return err |
diff --git a/docs/api/equipo-v1.md b/docs/api/equipo-v1.md| index b883b91b..8ffe18c3 100644 |
| --- a/docs/api/equipo-v1.md |
| +++ b/docs/api/equipo-v1.md |
| @@ -119,6 +119,27 @@ A successful answer returns `200` with `card`, `message` and `turn`. When the an |
| Cancel a turn in flight with `POST /api/v1/turns/{id}/cancel`. It returns `202` with the turn’s `attempt`, or `409 turn_ended` once the turn has ended. Post to a task’s thread with `POST /api/v1/tasks/{id}/thread`. Move a task to another project with `POST /api/v1/tasks/{id}/move`. The contract lists the other routes and their request bodies. |
| +Set a card aside with `POST /api/v1/cards/{id}/visibility`, sending `{"aside":true,"revision":2}`, or `false` to bring it back. It never answers, cancels or starts anything, and the card stays in Needs you. It returns `200` with the card. Its `aside` is `true` while you have set it aside. An outdated revision or a card that no longer waits on you returns `409 card_stale` with the current card. |
| + |
| +## Receive pushes on a device |
| + |
| +Register the device with `POST /api/v1/push-registrations` and the device's bearer token: |
| + |
| +```json |
| +{"token":"<APNs token, hex>","environment":"production","platform":"ios","start_token":"<Live Activity push-to-start token, hex>"} |
| +``` |
| + |
| +`environment` is `production` or `development`. `platform` is `ios` or `macos`. Only `ios` sends `start_token`. The registration belongs to the device credential that sends it. A new registration replaces the previous one. A token belongs to one device credential at a time. Registering it removes it from any other device credential and anything waiting for that credential. It returns `200` with `environment`, `platform`, `live_activities` and `updated_at`, never a token. The registration is deleted when the device is revoked, when its person leaves the team, or when Apple says the token is no longer valid (`Unregistered`, `ExpiredToken`, `BadDeviceToken` or `DeviceTokenNotForTopic`). |
| + |
| +The server decides on pushes in the same transaction as the change, so a change that does not happen pushes nothing: |
| + |
| +- an alert when a card waits on you, with the card's question. `apns-collapse-id` is the card's ID and `equipo` is `{"kind":"card","card_id":"<card ID>","task_id":"<task ID or empty>"}`; |
| +- an alert when the coordinator replies while you have no `/events` stream open, with the reply's first line and `{"kind":"reply","turn_id":"<turn ID>"}`; |
| +- a passive alert when a task you started ends, or when one of its steps stops and waits for Retry, with `{"kind":"task","task_id":"<task ID>"}`; |
| +- the badge showing your Needs you count when the device registers and whenever that count changes. |
| + |
| +Alerts that wait on you have the category `needs_you`. Each task you started gets a Live Activity, at most three at once for you: those of the three most recently started tasks. It starts by push-to-start when work starts, with `attributes-type` `EquipoTaskAttributes` and attributes `{"task_id":"<task ID>"}`. Its content state has `task_id`, `title`, `stage`, `specialist`, `activity`, `needs_you`, `tone` (`positive`, `warning` or `negative`) and, at the end, `outcome` (`done`, `cancelled`, or `replaced` when a newer task took its place). It updates when the stage, step or `needs_you` changes, and at most once a minute for a new activity line. When the task starts needing you, the update is urgent but has no alert: the decision card's alert is the only sound. Send each running activity's own token with `POST /api/v1/push-registrations/activities`, `{"task_id":"tk...","token":"<hex>"}`, which returns `204`. When the token is received, the activity gets the task's full current state. After the task ends, the token is accepted only while the activity's end notification is waiting to be sent. The server then sends the end notification immediately. After that, it returns `409 task_ended`. The server forgets the token when the activity ends. |
| + |
| ## Talk to the Assistant |
| The routes under `/api/v1/assistant` serve Base's chat with the Assistant. Every route, `events` included, takes only `Authorization: Bearer <token>` with a person device token (audience `equipo.person.v1`). A session cookie is not accepted, and a request without a bearer gets `401 unauthenticated`. Every response has `Cache-Control: no-store`. Errors have the same body as the rest of this API: `code`, `copy_key`, `request_id` and, where it applies, `current_revision`. |
diff --git a/docs/api/equipo-v1.openapi.json b/docs/api/equipo-v1.openapi.json| index 0ae1655d..6320e411 100644 |
| --- a/docs/api/equipo-v1.openapi.json |
| +++ b/docs/api/equipo-v1.openapi.json |
| @@ -13395,6 +13395,218 @@ |
| "x-rejectUnknownFields": true |
| } |
| } |
| + }, |
| + "/cards/{id}/visibility": { |
| + "post": { |
| + "operationId": "post_cards_id_visibility", |
| + "summary": "Set a card aside, or bring it back", |
| + "description": "Send `aside` and the card's current `revision`. Setting a card aside never answers, cancels or starts anything: it stays in Needs you, and the card's `aside` says it is set aside for you. The answer is 200 with the card. A stale revision, or a card that no longer waits on you, is 409 with `code` `card_stale` and the card as it is now.", |
| + "security": [ |
| + { |
| + "personBearer": [] |
| + } |
| + ], |
| + "parameters": [ |
| + { |
| + "name": "id", |
| + "in": "path", |
| + "required": true, |
| + "schema": { |
| + "type": "string", |
| + "minLength": 1 |
| + } |
| + } |
| + ], |
| + "responses": { |
| + "200": { |
| + "description": "OK", |
| + "headers": { |
| + "Cache-Control": { |
| + "schema": { |
| + "const": "no-store" |
| + } |
| + } |
| + }, |
| + "content": { |
| + "application/json": { |
| + "schema": { |
| + "$ref": "#/components/schemas/Card" |
| + } |
| + } |
| + } |
| + }, |
| + "409": { |
| + "description": "Conflict: the resource as it is now", |
| + "headers": { |
| + "Cache-Control": { |
| + "schema": { |
| + "const": "no-store" |
| + } |
| + } |
| + }, |
| + "content": { |
| + "application/json": { |
| + "schema": { |
| + "$ref": "#/components/schemas/CardConflict" |
| + } |
| + } |
| + } |
| + }, |
| + "401": { |
| + "$ref": "#/components/responses/unauthenticated" |
| + }, |
| + "default": { |
| + "description": "An error, with one of the codes in `Error`", |
| + "headers": { |
| + "Cache-Control": { |
| + "schema": { |
| + "const": "no-store" |
| + } |
| + } |
| + }, |
| + "content": { |
| + "application/json": { |
| + "schema": { |
| + "$ref": "#/components/schemas/Error" |
| + } |
| + } |
| + } |
| + } |
| + }, |
| + "requestBody": { |
| + "required": true, |
| + "content": { |
| + "application/json": { |
| + "schema": { |
| + "$ref": "#/components/schemas/SetCardVisibility" |
| + } |
| + } |
| + }, |
| + "x-maxBytes": 32768, |
| + "x-rejectUnknownFields": true |
| + } |
| + } |
| + }, |
| + "/push-registrations": { |
| + "post": { |
| + "operationId": "post_push_registrations", |
| + "summary": "Register this device for push notifications", |
| + "description": "A device bearer only (a browser session is 401). Send the APNs device `token` (hex), its `environment` (`production` or `development`), the app's `platform` (`ios` or `macos`) and, on iPhone, the Live Activity push-to-start `start_token`. The registration belongs to the paired device credential that sends it and replaces its earlier one; a token belongs to one credential at a time, so registering it removes it from any other (with what waited for that credential). It is deleted when the device is revoked, when its person leaves the team, or when Apple reports the token `Unregistered`, `ExpiredToken`, `BadDeviceToken` or `DeviceTokenNotForTopic`. Tokens are never echoed, logged or audited. The answer is 200 with the registration, without its tokens. Pushes: an alert when a card waits on you (collapse ID the card, `equipo.card_id` to open it), when the coordinator replies while no `/events` stream is open (the reply's first line, `equipo.turn_id`), and a passive alert when a task you started ends or a step of it stops (`equipo.task_id`); the badge is your Needs you count, sent when the device registers and whenever it changes; for each task you started, at most three, a Live Activity (`attributes-type` `EquipoTaskAttributes`, attributes `{task_id}`, content state `LiveActivityState`) starts when work starts, updates on its stage, step or needs-you change (urgent, without an alert, when it starts needing you) and at most once a minute for its activity line, and ends with the outcome.", |
| + "security": [ |
| + { |
| + "personBearer": [] |
| + } |
| + ], |
| + "parameters": [], |
| + "responses": { |
| + "200": { |
| + "description": "OK", |
| + "headers": { |
| + "Cache-Control": { |
| + "schema": { |
| + "const": "no-store" |
| + } |
| + } |
| + }, |
| + "content": { |
| + "application/json": { |
| + "schema": { |
| + "$ref": "#/components/schemas/PushRegistration" |
| + } |
| + } |
| + } |
| + }, |
| + "401": { |
| + "$ref": "#/components/responses/unauthenticated" |
| + }, |
| + "default": { |
| + "description": "An error, with one of the codes in `Error`", |
| + "headers": { |
| + "Cache-Control": { |
| + "schema": { |
| + "const": "no-store" |
| + } |
| + } |
| + }, |
| + "content": { |
| + "application/json": { |
| + "schema": { |
| + "$ref": "#/components/schemas/Error" |
| + } |
| + } |
| + } |
| + } |
| + }, |
| + "requestBody": { |
| + "required": true, |
| + "content": { |
| + "application/json": { |
| + "schema": { |
| + "$ref": "#/components/schemas/RegisterPush" |
| + } |
| + } |
| + }, |
| + "x-maxBytes": 32768, |
| + "x-rejectUnknownFields": true |
| + } |
| + } |
| + }, |
| + "/push-registrations/activities": { |
| + "post": { |
| + "operationId": "post_push_registrations_activities", |
| + "summary": "Register a running Live Activity's update token", |
| + "description": "A device bearer only. Send the `task_id` the Live Activity follows (a task you started; another's is 404) and the activity's own push `token` (hex). The activity then gets the task's current state in full. Once the task ended, the token is accepted only while the activity's end waits to be sent (the end then goes at once), else 409 `task_ended`. Updates and the end go to it; the server forgets it when the activity ends. 204.", |
| + "security": [ |
| + { |
| + "personBearer": [] |
| + } |
| + ], |
| + "parameters": [], |
| + "responses": { |
| + "204": { |
| + "description": "No Content", |
| + "headers": { |
| + "Cache-Control": { |
| + "schema": { |
| + "const": "no-store" |
| + } |
| + } |
| + } |
| + }, |
| + "401": { |
| + "$ref": "#/components/responses/unauthenticated" |
| + }, |
| + "default": { |
| + "description": "An error, with one of the codes in `Error`", |
| + "headers": { |
| + "Cache-Control": { |
| + "schema": { |
| + "const": "no-store" |
| + } |
| + } |
| + }, |
| + "content": { |
| + "application/json": { |
| + "schema": { |
| + "$ref": "#/components/schemas/Error" |
| + } |
| + } |
| + } |
| + } |
| + }, |
| + "requestBody": { |
| + "required": true, |
| + "content": { |
| + "application/json": { |
| + "schema": { |
| + "$ref": "#/components/schemas/RegisterActivity" |
| + } |
| + } |
| + }, |
| + "x-maxBytes": 32768, |
| + "x-rejectUnknownFields": true |
| + } |
| + } |
| } |
| }, |
| "components": { |
| @@ -18025,6 +18237,9 @@ |
| }, |
| "advice": { |
| "$ref": "#/components/schemas/Advice" |
| + }, |
| + "aside": { |
| + "type": "boolean" |
| } |
| }, |
| "required": [ |
| @@ -22811,6 +23026,94 @@ |
| ], |
| "additionalProperties": false, |
| "x-go-type": "wire.ProjectAutonomy" |
| + }, |
| + "PushRegistration": { |
| + "type": "object", |
| + "properties": { |
| + "environment": { |
| + "type": "string", |
| + "enum": [ |
| + "production", |
| + "development" |
| + ] |
| + }, |
| + "platform": { |
| + "type": "string", |
| + "enum": [ |
| + "ios", |
| + "macos" |
| + ] |
| + }, |
| + "live_activities": { |
| + "type": "boolean" |
| + }, |
| + "updated_at": { |
| + "type": "string", |
| + "format": "date-time" |
| + } |
| + }, |
| + "required": [ |
| + "environment", |
| + "platform", |
| + "live_activities", |
| + "updated_at" |
| + ], |
| + "additionalProperties": false, |
| + "x-go-type": "wire.PushRegistration" |
| + }, |
| + "RegisterActivity": { |
| + "type": "object", |
| + "properties": { |
| + "task_id": { |
| + "type": "string" |
| + }, |
| + "token": { |
| + "type": "string" |
| + } |
| + }, |
| + "additionalProperties": false, |
| + "x-go-type": "wire.RegisterActivity" |
| + }, |
| + "RegisterPush": { |
| + "type": "object", |
| + "properties": { |
| + "token": { |
| + "type": "string" |
| + }, |
| + "environment": { |
| + "type": "string", |
| + "enum": [ |
| + "production", |
| + "development" |
| + ] |
| + }, |
| + "platform": { |
| + "type": "string", |
| + "enum": [ |
| + "ios", |
| + "macos" |
| + ] |
| + }, |
| + "start_token": { |
| + "type": "string" |
| + } |
| + }, |
| + "additionalProperties": false, |
| + "x-go-type": "wire.RegisterPush" |
| + }, |
| + "SetCardVisibility": { |
| + "type": "object", |
| + "properties": { |
| + "aside": { |
| + "type": "boolean" |
| + }, |
| + "revision": { |
| + "type": "integer", |
| + "format": "int64" |
| + } |
| + }, |
| + "additionalProperties": false, |
| + "x-go-type": "wire.SetCardVisibility" |
| } |
| }, |
| "responses": { |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index 69dfa1d8..6d9a935e 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -6750,6 +6750,18 @@ records remain unchanged. |
| | `access.waiting` | Waiting for your approval on Amadan… | Copy specialist | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) | |
| | `access.reopen` | Open Amadan again | Copy specialist | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) | |
| | `copyMissingSMTP` | A configured mail sender is required. Enable CARLOS mail submission or configure CARLOS_SMTP_HOST and CARLOS_SMTP_FROM, unless local logged mail is enabled. | boot error when Equipo has no mail channel: neither CARLOS mail submission nor CARLOS_SMTP_HOST and CARLOS_SMTP_FROM (mail submission, 2026-11-17; Luna, codex gpt-5.6-luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-17) | |
| +| `copyLoggedPushPublic` | Unset EQUIPO_ALLOW_LOGGED_PUSH on a public origin. It is only allowed on loopback or staging. | boot error: EQUIPO_ALLOW_LOGGED_PUSH on a public origin (native slice 2 push, 2026-11-20; Luna, codex gpt-5.6-luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) | |
| +| `copyCarlosPushUnavailable` | CARLOS push submission is not available in this version of Equipo. Unset CARLOS_PUSH. | boot error: CARLOS_PUSH=submit before this build has the CARLOS push client (native slice 2 push, 2026-11-20; Luna, codex gpt-5.6-luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) | |
| +| `copyPushBoth` | Set EQUIPO_ALLOW_LOGGED_PUSH or CARLOS_PUSH, not both. | boot error: EQUIPO_ALLOW_LOGGED_PUSH and CARLOS_PUSH both set (native slice 2 push, 2026-11-20; Luna, codex gpt-5.6-luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) | |
| +| `push.card.title` | Needs you | notification title when a card waits on the person (body: the card's question) (native slice 2 push, 2026-11-20; Luna, codex gpt-5.6-luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) | |
| +| `push.card.body` | A decision is waiting for you. | notification body when the waiting card has no question (native slice 2 push, 2026-11-20; Luna, codex gpt-5.6-luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) | |
| +| `push.reply.title` | Coordinator replied | notification title when the coordinator replied while no stream was open (body: the reply's first line) (native slice 2 push, 2026-11-20; Luna, codex gpt-5.6-luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) | |
| +| `push.task.done` | Done. | passive notification body when a task the person started is done (title: the task) (native slice 2 push, 2026-11-20; Luna, codex gpt-5.6-luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) | |
| +| `push.task.cancelled` | Cancelled. | passive notification body when that task is cancelled (title: the task) (native slice 2 push, 2026-11-20; Luna, codex gpt-5.6-luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) | |
| +| `push.task.failed` | A step failed. Open the task to retry the step. | passive notification body when a step of that task failed and waits for Retry (title: the task) (native slice 2 push, 2026-11-20; Luna, codex gpt-5.6-luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) | |
| +| `push.activity.started` | Work has started. | alert with a task's Live Activity starting (title: the task) (native slice 2 push, 2026-11-20; Luna, codex gpt-5.6-luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) | |
| +| `docs/api/equipo-v1.md / Talk to your Coordinator from a device: set aside` | Set a card aside with `POST /api/v1/cards/{id}/visibility`, sending `{"aside":true,"revision":2}`, or `false` to bring it back. It never answers, cancels or starts anything, and the card stays in Needs you. It returns `200` with the card. Its `aside` is `true` while you have set it aside. An outdated revision or a card that no longer waits on you returns `409 card_stale` with the current card. | API doc: Set aside for a device (native slice 2, 2026-11-20; Luna, codex gpt-5.6-luna, house rules) | Document section; COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) | |
| +| `docs/api/equipo-v1.md / Receive pushes on a device` | ## Receive pushes on a device<br><br>Register the device with `POST /api/v1/push-registrations` and the device's bearer token:<br><br>```json<br>{"token":"<APNs token, hex>","environment":"production","platform":"ios","start_token":"<Live Activity push-to-start token, hex>"}<br>```<br><br>`environment` is `production` or `development`. `platform` is `ios` or `macos`. Only `ios` sends `start_token`. The registration belongs to the device credential that sends it. A new registration replaces the previous one. A token belongs to one device credential at a time. Registering it removes it from any other device credential and anything waiting for that credential. It returns `200` with `environment`, `platform`, `live_activities` and `updated_at`, never a token. The registration is deleted when the device is revoked, when its person leaves the team, or when Apple says the token is no longer valid (`Unregistered`, `ExpiredToken`, `BadDeviceToken` or `DeviceTokenNotForTopic`).<br><br>The server decides on pushes in the same transaction as the change, so a change that does not happen pushes nothing:<br><br>- an alert when a card waits on you, with the card's question. `apns-collapse-id` is the card's ID and `equipo` is `{"kind":"card","card_id":"<card ID>","task_id":"<task ID or empty>"}`;<br>- an alert when the coordinator replies while you have no `/events` stream open, with the reply's first line and `{"kind":"reply","turn_id":"<turn ID>"}`;<br>- a passive alert when a task you started ends, or when one of its steps stops and waits for Retry, with `{"kind":"task","task_id":"<task ID>"}`;<br>- the badge showing your Needs you count when the device registers and whenever that count changes.<br><br>Alerts that wait on you have the category `needs_you`. Each task you started gets a Live Activity, at most three at once for you: those of the three most recently started tasks. It starts by push-to-start when work starts, with `attributes-type` `EquipoTaskAttributes` and attributes `{"task_id":"<task ID>"}`. Its content state has `task_id`, `title`, `stage`, `specialist`, `activity`, `needs_you`, `tone` (`positive`, `warning` or `negative`) and, at the end, `outcome` (`done`, `cancelled`, or `replaced` when a newer task took its place). It updates when the stage, step or `needs_you` changes, and at most once a minute for a new activity line. When the task starts needing you, the update is urgent but has no alert: the decision card's alert is the only sound. Send each running activity's own token with `POST /api/v1/push-registrations/activities`, `{"task_id":"tk...","token":"<hex>"}`, which returns `204`. When the token is received, the activity gets the task's full current state. After the task ends, the token is accepted only while the activity's end notification is waiting to be sent. The server then sends the end notification immediately. After that, it returns `409 task_ended`. The server forgets the token when the activity ends. | API doc: push registrations, what pushes and the Live Activity content state (native slice 2, 2026-11-20, revised after review 2026-11-20; Luna, codex gpt-5.6-luna, house rules) | Document section; COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) | |
| | `conversation.start.label` | Ways to start | Copy specialist | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-20) | |
| | `conversation.start.bug` | Fix a bug | Copy specialist | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-20) | |
| | `conversation.start.bug_draft` | Fix a bug where | Copy specialist | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-20) | |
diff --git a/internal/equipo/app.go b/internal/equipo/app.go| index d0f35224..69ada63f 100644 |
| --- a/internal/equipo/app.go |
| +++ b/internal/equipo/app.go |
| @@ -17,6 +17,7 @@ import ( |
| "github.com/go-chi/chi/v5" |
| "amadan.net/oficina/equipo/internal/equipo/personapi" |
| + "amadan.net/oficina/equipo/internal/equipo/push" |
| "amadan.net/oficina/equipo/internal/release" |
| "amadan.net/oficina/equipo/internal/wire" |
| "amadan.net/rastrillo/rastrillo" |
| @@ -32,6 +33,8 @@ import ( |
| ) |
| type application struct { |
| + // push is the push transport (Config.Push); nil, no sender runs. |
| + push push.Transport |
| home *oficinaid.HTTP |
| installAssets *release.InstallAssets |
| executionEnabled bool |
| @@ -72,6 +75,11 @@ func (a *application) startBackground() *background.Group { |
| defer stop() |
| a.store.Chat().ServeRemoteCalls(calls) |
| }) |
| + // The push sender, only where serving built a transport. |
| + if a.push != nil { |
| + sender := a.store.Chat().PushSender(a.push) |
| + a.background.Go(func() { sender.Serve(calls, a.store.Chat().PushWake(), pushEvery) }) |
| + } |
| a.background.Loop(context.Background(), time.Minute, func() { |
| ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| defer cancel() |
| @@ -107,6 +115,10 @@ func (a *application) startBackground() *background.Group { |
| return &a.background |
| } |
| +// pushEvery is how often the push sender looks for due rows without a |
| +// wake (retries, another process's writes). |
| +const pushEvery = 5 * time.Second |
| + |
| // App composes the router and embedded assets used by every harness. |
| func App(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logger) (*http.ServeMux, error) { |
| r, err := Router(d, cfg, mailer, logger) |
| @@ -169,6 +181,8 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| "skipped", migrated.Skipped, "adopted", migrated.Adopted) |
| store.chatExecution, store.chatTestPeople, store.chatOrigin, store.chatAssistantHosts = cfg.ExecutionEnabled, cfg.TestPeople, cfg.Origin, cfg.AssistantHosts |
| + // The push outbox is written only where a sender will drain it. |
| + store.Chat().SetPush(cfg.Push != nil) |
| // What the Assistant's provider calls could not do, by call id only. |
| store.Chat().SetLogger(logger) |
| if cfg.OficinaConnectOrigin != "" { |
| @@ -213,7 +227,7 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| if err != nil { |
| return nil, err |
| } |
| - a := &application{installAssets: release.NewInstallAssets(cfg.RunnerReleaseDir, rastrillo.BuildVersion, release.BuildManifest()), executionEnabled: cfg.ExecutionEnabled, Router: chi.NewRouter(), auth: authentication, store: store, logger: logger, nonces: pow.SQLNonces(d.Writer()), origin: cfg.Origin} |
| + a := &application{installAssets: release.NewInstallAssets(cfg.RunnerReleaseDir, rastrillo.BuildVersion, release.BuildManifest()), executionEnabled: cfg.ExecutionEnabled, Router: chi.NewRouter(), auth: authentication, store: store, logger: logger, nonces: pow.SQLNonces(d.Writer()), origin: cfg.Origin, push: cfg.Push} |
| if cfg.Home != nil { |
| storeID, e := oficinaid.New(d.Writer(), cfg.Origin, cfg.Home) |
| if e != nil { |
diff --git a/internal/equipo/chat/http.go b/internal/equipo/chat/http.go| index 05155197..7f0741c4 100644 |
| --- a/internal/equipo/chat/http.go |
| +++ b/internal/equipo/chat/http.go |
| @@ -85,6 +85,9 @@ func (h *HTTP) Mount(r chi.Router) { |
| r.Post("/projects", h.bearer(h.addProject)) |
| r.Delete("/projects/{id}", h.bearer(h.removeProject)) |
| r.Post("/cards/{id}/answer", h.bearer(h.answer)) |
| + r.Post("/cards/{id}/visibility", h.bearer(h.cardVisibility)) |
| + r.Post("/push-registrations", h.bearer(h.registerPush)) |
| + r.Post("/push-registrations/activities", h.bearer(h.registerActivity)) |
| r.Get("/notebook", h.bearer(h.notebook)) |
| r.Post("/notebook/reset", h.bearer(h.resetNotebook)) |
| r.Delete("/notebook/corrections/{id}", h.bearer(h.removePlacementNote)) |
| @@ -627,6 +630,9 @@ func (h *HTTP) events(w http.ResponseWriter, r *http.Request) { |
| // cursor, rechecking the person before each batch and ping. |
| func (h *HTTP) stream(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal, lane string, read func(context.Context, string, int64, int) ([]wire.Event, error)) { |
| ctx := personapi.WithVerifiedPrincipal(r.Context(), p) |
| + if lane == wire.LaneCoordinator { |
| + defer h.Store.Hub().Follow(p.Address)() |
| + } |
| // Live-only events (a glance) come from the moment the stream opens. |
| live, stop := h.Store.Hub().Live(p.Address, lane) |
| defer stop() |
diff --git a/internal/equipo/chat/hub.go b/internal/equipo/chat/hub.go| index de56ed80..ce8ac102 100644 |
| --- a/internal/equipo/chat/hub.go |
| +++ b/internal/equipo/chat/hub.go |
| @@ -19,6 +19,9 @@ type Hub struct { |
| // never stored (a glance): sent to whoever is following now, and |
| // missed by anyone who is not. |
| live map[*liveSub]bool |
| + // streams counts each person's open /events streams in this process |
| + // (Streaming): a reply pushes only to someone not following. |
| + streams map[string]int |
| } |
| type liveSub struct { |
| @@ -27,7 +30,7 @@ type liveSub struct { |
| } |
| func NewHub() *Hub { |
| - return &Hub{waiters: map[string]chan struct{}{}, runners: map[string]registration{}, closing: make(chan struct{}), live: map[*liveSub]bool{}} |
| + return &Hub{waiters: map[string]chan struct{}{}, runners: map[string]registration{}, closing: make(chan struct{}), live: map[*liveSub]bool{}, streams: map[string]int{}} |
| } |
| // Live follows the person's live-only events in one lane, until stop. |
| @@ -44,6 +47,29 @@ func (h *Hub) Live(person, lane string) (events <-chan wire.Event, stop func()) |
| } |
| } |
| +// Follow counts an open /events stream of the person's until done. |
| +func (h *Hub) Follow(person string) (done func()) { |
| + h.mu.Lock() |
| + h.streams[person]++ |
| + h.mu.Unlock() |
| + return func() { |
| + h.mu.Lock() |
| + defer h.mu.Unlock() |
| + if h.streams[person]--; h.streams[person] <= 0 { |
| + delete(h.streams, person) |
| + } |
| + } |
| +} |
| + |
| +// Streaming reports whether the person has an /events stream open in this |
| +// process. Another process's (a deploy overlap) is not seen: a reply then |
| +// may push while they watch, never the other way round. |
| +func (h *Hub) Streaming(person string) bool { |
| + h.mu.Lock() |
| + defer h.mu.Unlock() |
| + return h.streams[person] > 0 |
| +} |
| + |
| // publish hands a live-only event to the person's streams in its lane |
| // in this process, without waiting for any. |
| func (h *Hub) publish(person, lane string, e wire.Event) { |
diff --git a/internal/equipo/chat/inner.go b/internal/equipo/chat/inner.go| index 12e77d0f..58b55de6 100644 |
| --- a/internal/equipo/chat/inner.go |
| +++ b/internal/equipo/chat/inner.go |
| @@ -115,7 +115,7 @@ func (t *txn) stepActivity(l Lease, v *wire.StepActivityReport) error { |
| return err |
| } |
| } |
| - return nil |
| + return t.pushLine(s, lines[len(lines)-1]) |
| } |
| // taskExtras fills what the screens show around a task: the creator's |
diff --git a/internal/equipo/chat/models.go b/internal/equipo/chat/models.go| index 0107066e..ae54e7cd 100644 |
| --- a/internal/equipo/chat/models.go |
| +++ b/internal/equipo/chat/models.go |
| @@ -4,10 +4,14 @@ |
| // event are written in one transaction. |
| package chat |
| -import "time" |
| +import ( |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/push" |
| +) |
| // Models are the tables this package owns, for the migration check. |
| -var Models = []any{&cardVisibility{}, &cardThreadRecord{}, ©AttemptRecord{}, ©ReviewRecord{}, ©FeedbackRecord{}, &turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, ¬ebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &starRecord{}, &questionRecord{}, &connectionRecord{}, &usageRecord{}, &distinctRecord{}, &hkRecord{}, &hkFailureRecord{}, &hkSettingsRecord{}, &fileRecord{}, &fileDataRecord{}, &transferRecord{}, &mergePolicyRecord{}, &mergeAuditRecord{}, &specialistRecord{}, &grantRecord{}, &specialistAuditRecord{}, &researchSourceRecord{}, &researchAddressRecord{}, &researchPrefixRecord{}, &researchInventoryRecord{}, &researchRecord{}, &researchFetchRecord{}, &taskFileRecord{}, &taskFileDataRecord{}, &releaseRecord{}, &adviceRecord{}, &assistantHostRecord{}, &handoffRecord{}, &handoffTurnRecord{}, &handoffTaskRecord{}, &handoffActionRecord{}, &connectTurnRecord{}, &carriedRecord{}} |
| +var Models = append([]any{&cardVisibility{}, &cardThreadRecord{}, ©AttemptRecord{}, ©ReviewRecord{}, ©FeedbackRecord{}, &turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, ¬ebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &starRecord{}, &questionRecord{}, &connectionRecord{}, &usageRecord{}, &distinctRecord{}, &hkRecord{}, &hkFailureRecord{}, &hkSettingsRecord{}, &fileRecord{}, &fileDataRecord{}, &transferRecord{}, &mergePolicyRecord{}, &mergeAuditRecord{}, &specialistRecord{}, &grantRecord{}, &specialistAuditRecord{}, &researchSourceRecord{}, &researchAddressRecord{}, &researchPrefixRecord{}, &researchInventoryRecord{}, &researchRecord{}, &researchFetchRecord{}, &taskFileRecord{}, &taskFileDataRecord{}, &releaseRecord{}, &adviceRecord{}, &assistantHostRecord{}, &handoffRecord{}, &handoffTurnRecord{}, &handoffTaskRecord{}, &handoffActionRecord{}, &connectTurnRecord{}, &carriedRecord{}}, push.Models...) |
| type turnRecord struct { |
| CreateRepo string |
diff --git a/internal/equipo/chat/projects.go b/internal/equipo/chat/projects.go| index 5d2dfa30..173090e8 100644 |
| --- a/internal/equipo/chat/projects.go |
| +++ b/internal/equipo/chat/projects.go |
| @@ -291,6 +291,12 @@ func (t *txn) cardView(c cardRecord) (wire.Card, error) { |
| if c.Kind == wire.CardHome { |
| v.Name = c.Choice |
| } |
| + // Set aside is the card's person's presentation (D5), never its state. |
| + var aside []bool |
| + if err := t.db.Model(&cardVisibility{}).Where("person = ? AND card_id = ?", c.Person, c.ID).Pluck("aside", &aside).Error; err != nil { |
| + return v, err |
| + } |
| + v.Aside = len(aside) == 1 && aside[0] |
| if c.Kind == wire.CardAccess || c.Kind == wire.CardMerge || c.Kind == wire.CardMergeShips || c.Kind == wire.CardMergePolicy || c.Kind == wire.CardMergeReceipt || c.Kind == wire.CardPublish { |
| v.Name = c.Name |
| } |
| @@ -346,7 +352,12 @@ func (t *txn) cardView(c cardRecord) (wire.Card, error) { |
| return v, nil |
| } |
| -func (t *txn) cardEvent(c cardRecord) error { |
| +func (t *txn) cardEvent(c cardRecord) error { return t.cardEventPush(c, true) } |
| + |
| +// cardEventPush is cardEvent; pushes false for a change that is no card |
| +// change to its person's devices (setting it aside), which runs no push |
| +// rule. |
| +func (t *txn) cardEventPush(c cardRecord, pushes bool) error { |
| if c.Held { |
| // Quiet hours: the conversation hears of it at its visible time. |
| return nil |
| @@ -365,6 +376,11 @@ func (t *txn) cardEvent(c cardRecord) error { |
| if err := t.event(c.Lane, c.Person, wire.EventCard, "card", c.ID, c.Revision, c.TurnID, "", 0, v); err != nil { |
| return err |
| } |
| + if pushes { |
| + if err := t.pushCard(c, v); err != nil { |
| + return err |
| + } |
| + } |
| // A hand-off's team card is the Assistant's too. A card in a job |
| // thread goes to the thread's stream, never the person's. |
| return t.mirrorCard(c) |
diff --git a/internal/equipo/chat/push.go b/internal/equipo/chat/push.go| new file mode 100644 |
| index 00000000..d0e34bde |
| --- /dev/null |
| +++ b/internal/equipo/chat/push.go |
| @@ -0,0 +1,552 @@ |
| +package chat |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "slices" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/push" |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "gorm.io/gorm" |
| +) |
| + |
| +// Push (native slice 2): the engine writes push_outbox rows in the |
| +// transaction of the change that pushes (push.Rules decides), for the |
| +// person's registered devices that are still current. The outbox is |
| +// written only while the instance has a push transport (SetPush). |
| +// |
| +// A push is never worth an engine write: the push work of a change runs |
| +// in a savepoint (pushSafe), and when it fails (a lookup, a seal, a reply |
| +// that cannot be read) only it is rolled back and logged, without tokens |
| +// or text, and the change commits without its pushes. Tokens and |
| +// payloads are sealed at rest (push.Box), so neither is ever SQL text. |
| + |
| +// SetPush turns the outbox on: the serve path does, once it built a |
| +// transport; a seed, a one-shot or a test that does not never writes it. |
| +func (s *Store) SetPush(on bool) { s.pushOn.Store(on) } |
| + |
| +// PushWake is woken after a commit that wrote pushes. |
| +func (s *Store) PushWake() <-chan struct{} { return s.pushWake } |
| + |
| +func (s *Store) wakePush() { |
| + select { |
| + case s.pushWake <- struct{}{}: |
| + default: |
| + } |
| +} |
| + |
| +// pushBox seals push's tokens and payloads with the instance key. |
| +func (s *Store) pushBox() push.Box { |
| + return push.Box{Seal: s.authority.Seal, Open: s.authority.Open} |
| +} |
| + |
| +// PushSender drains this store's outbox through tr. |
| +func (s *Store) PushSender(tr push.Transport) *push.Sender { |
| + return &push.Sender{Transport: tr, Now: s.now, Check: s.pushCurrent, Box: s.pushBox(), |
| + Write: func(ctx context.Context, fn func(*gorm.DB) error) error { |
| + return s.tx(ctx, func(t *txn) error { return fn(t.db) }) |
| + }, |
| + Errorf: s.pushWarn} |
| +} |
| + |
| +func (s *Store) pushWarn(msg string, args ...any) { |
| + if l := s.logger.Load(); l != nil { |
| + l.Warn(msg, args...) |
| + } |
| +} |
| + |
| +// pushCurrent: the person is an active member and the device credential |
| +// still valid (Authority.PushDevice). push.ErrGone when the person left |
| +// or the device was revoked; push.ErrNotCurrent when it cannot take a |
| +// push now; another error is a lookup that failed. |
| +func (s *Store) pushCurrent(tx *gorm.DB, person, credential string) error { |
| + var n int64 |
| + if err := tx.Raw("SELECT count(*) FROM members WHERE address = ? AND active = 1", person).Scan(&n).Error; err != nil { |
| + return err |
| + } |
| + if n != 1 { |
| + return push.ErrGone |
| + } |
| + if s.authority.PushDevice == nil { |
| + return push.ErrNotCurrent |
| + } |
| + return s.authority.PushDevice(tx, person, credential) |
| +} |
| + |
| +// RegisterPush is POST /api/v1/push-registrations: the device credential's |
| +// registration, replacing its earlier one and taking its tokens from any |
| +// other credential. Audited without its tokens. With the outbox on, the |
| +// device hears the badge at once, and what the person's open tasks show |
| +// now is remembered, so their outcomes push even when this is the first |
| +// device the person registered. |
| +func (s *Store) RegisterPush(ctx context.Context, person, credential string, in wire.RegisterPush) (out wire.PushRegistration, err error) { |
| + if credential == "" { |
| + return out, ErrForbidden |
| + } |
| + if push.Validate(in) != nil { |
| + return out, ErrInvalid |
| + } |
| + err = s.tx(ctx, func(t *txn) error { |
| + if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| + return err |
| + } |
| + if err := s.pushCurrent(t.db, person, credential); err != nil { |
| + return ErrForbidden |
| + } |
| + if out, err = push.Register(t.db, s.pushBox(), person, credential, in, t.now()); err != nil { |
| + return err |
| + } |
| + if err := s.authority.Audit(t.db, person, "push.register", credential); err != nil { |
| + return err |
| + } |
| + if !s.pushOn.Load() { |
| + return nil |
| + } |
| + if err := t.pushSeed(person); err != nil { |
| + return err |
| + } |
| + device, err := push.Device(t.db, person, credential) |
| + if err != nil { |
| + return err |
| + } |
| + _, err = t.enqueuePush(person, device, push.Badge()) |
| + return err |
| + }) |
| + return out, err |
| +} |
| + |
| +// pushSeed remembers what the person's open tasks show now, keeping what |
| +// their Live Activities were told. |
| +func (t *txn) pushSeed(person string) error { |
| + var rows []taskRecord |
| + if err := t.db.Where("creator = ? AND stage NOT IN ?", person, []string{wire.StageDone, wire.StageCancelled}).Order("created_at, id").Limit(wire.MaxTaskList).Find(&rows).Error; err != nil { |
| + return err |
| + } |
| + for _, k := range rows { |
| + v, err := t.taskView(k) |
| + if err != nil { |
| + return err |
| + } |
| + m, err := push.LoadMemory(t.db, person, k.ID) |
| + if err != nil { |
| + return err |
| + } |
| + if err := push.SaveMemory(t.db, person, k.ID, m.Remember(pushTaskOf(v, t.s.authority.Copy)), t.now()); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// RegisterActivity is POST /api/v1/push-registrations/activities: a |
| +// running Live Activity's token for a task the person started. Once the |
| +// task ended it is taken only while a push for it still waits to go to |
| +// the device (its activity's end), which then goes at once; before, the |
| +// activity hears the task's whole state now, which it may have missed |
| +// while the server had no token for it. |
| +func (s *Store) RegisterActivity(ctx context.Context, person, credential string, in wire.RegisterActivity) error { |
| + if credential == "" { |
| + return ErrForbidden |
| + } |
| + return s.tx(ctx, func(t *txn) error { |
| + if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| + return err |
| + } |
| + if err := s.pushCurrent(t.db, person, credential); err != nil { |
| + return ErrForbidden |
| + } |
| + var k taskRecord |
| + if err := t.db.Where("id = ? AND creator = ?", in.TaskID, person).Take(&k).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| + return ErrNotFound |
| + } else if err != nil { |
| + return err |
| + } |
| + ended := wire.FinalStage(k.Stage) |
| + if ended { |
| + waiting, err := push.Waiting(t.db, credential, k.ID) |
| + if err != nil { |
| + return err |
| + } |
| + if !waiting { |
| + return ErrTaskEnded |
| + } |
| + } |
| + if err := push.RegisterActivity(t.db, s.pushBox(), person, credential, k.ID, in.Token, t.now()); errors.Is(err, push.ErrInvalid) { |
| + return ErrInvalid |
| + } else if err != nil { |
| + return err |
| + } |
| + if err := s.authority.Audit(t.db, person, "push.activity", credential+" "+k.ID); err != nil { |
| + return err |
| + } |
| + if ended { |
| + t.pushed = true |
| + return push.Hurry(t.db, credential, k.ID, t.now()) |
| + } |
| + if !s.pushOn.Load() { |
| + return nil |
| + } |
| + return t.pushCatchUp(person, credential, k) |
| + }) |
| +} |
| + |
| +// pushCatchUp sends a running activity its task's whole state, to the |
| +// device whose token just arrived, and remembers the activity running. |
| +func (t *txn) pushCatchUp(person, credential string, k taskRecord) error { |
| + m, err := push.LoadMemory(t.db, person, k.ID) |
| + if err != nil { |
| + return err |
| + } |
| + if m.Ended { |
| + // A late token for a replaced activity can deliver its end, but |
| + // must never revive the activity or enqueue a catch-up update. |
| + t.pushed = true |
| + return push.Hurry(t.db, credential, k.ID, t.now()) |
| + } |
| + v, err := t.taskView(k) |
| + if err != nil { |
| + return err |
| + } |
| + after := pushTaskOf(v, t.s.authority.Copy) |
| + device, err := push.Device(t.db, person, credential) |
| + if err != nil { |
| + return err |
| + } |
| + if _, err := t.enqueuePush(person, device, push.CatchUp(after)); err != nil { |
| + return err |
| + } |
| + now := t.now() |
| + next := m.Remember(after) |
| + if !m.Live() { |
| + next.Started, next.Ended = &now, false |
| + } |
| + return push.SaveMemory(t.db, person, k.ID, next, now) |
| +} |
| + |
| +// pushSafe runs a change's push work in a savepoint while the outbox is |
| +// on: its failure rolls back only the push work, is logged, and never |
| +// fails the change. |
| +func (t *txn) pushSafe(what string, fn func() error) error { |
| + if !t.s.pushOn.Load() { |
| + return nil |
| + } |
| + if err := t.db.SavePoint("push").Error; err != nil { |
| + t.s.pushWarn("push skipped", "change", what, "err", err) |
| + return nil |
| + } |
| + if err := fn(); err != nil { |
| + if rerr := t.db.RollbackTo("push").Error; rerr != nil { |
| + return rerr |
| + } |
| + t.s.pushWarn("push skipped", "change", what, "err", err) |
| + } |
| + return nil |
| +} |
| + |
| +// pushDevices are the person's current registrations, none while the |
| +// outbox is off. |
| +func (t *txn) pushDevices(person string) ([]push.Registration, error) { |
| + if !t.s.pushOn.Load() || person == "" { |
| + return nil, nil |
| + } |
| + all, err := push.Devices(t.db, person) |
| + if err != nil || len(all) == 0 { |
| + return nil, err |
| + } |
| + var out []push.Registration |
| + for _, d := range all { |
| + if t.s.pushCurrent(t.db, person, d.Credential) == nil { |
| + out = append(out, d) |
| + } |
| + } |
| + return out, nil |
| +} |
| + |
| +// enqueuePush writes an intent's rows, one a device that can take it, |
| +// and reports how many. A payload over APNs' limit is no push. |
| +func (t *txn) enqueuePush(person string, devices []push.Registration, in push.Intent) (int, error) { |
| + if len(devices) == 0 { |
| + return 0, nil |
| + } |
| + badge := 0 |
| + if in.Kind == push.KindBadge { |
| + n, err := t.needsYouCount(person) |
| + if err != nil { |
| + return 0, err |
| + } |
| + badge = n |
| + } |
| + now := t.now() |
| + raw, typ, err := push.Render(in, t.s.authority.Copy, badge, now) |
| + if errors.Is(err, push.ErrTooLarge) { |
| + t.s.pushWarn("push too large", "rule", in.Rule, "task", in.TaskID) |
| + return 0, nil |
| + } |
| + if err != nil { |
| + return 0, err |
| + } |
| + written := 0 |
| + for _, d := range devices { |
| + target := push.TargetDevice |
| + switch in.Kind { |
| + case push.KindActivityStart: |
| + if !startable(d) { |
| + continue |
| + } |
| + target = push.TargetStart |
| + case push.KindActivityUpdate, push.KindActivityEnd: |
| + has, err := push.HasActivity(t.db, d.Credential, in.TaskID) |
| + if err != nil { |
| + return written, err |
| + } |
| + // An update needs the activity's own token: without it the row |
| + // would only be dropped, and the activity hears the whole state |
| + // when its token arrives (pushCatchUp). An end waits a while |
| + // for the token. |
| + if d.Platform != wire.PlatformIOS || !has && (in.Kind == push.KindActivityUpdate || d.StartToken == "") { |
| + continue |
| + } |
| + target = push.TargetActivity |
| + } |
| + r := push.OutboxRecord{Person: person, Credential: d.Credential, Kind: in.Kind, Target: target, TaskID: in.TaskID, PushType: typ, Priority: in.Priority, CollapseID: in.CollapseID, Dedupe: in.Dedupe, Payload: string(raw), NextAt: now, CreatedAt: now, UpdatedAt: now} |
| + if err := push.Enqueue(t.db, t.s.pushBox(), r, in.Coalesce); err != nil { |
| + return written, err |
| + } |
| + written++ |
| + } |
| + if written > 0 { |
| + t.pushed = true |
| + } |
| + return written, nil |
| +} |
| + |
| +// startable: the device can start a Live Activity by push. |
| +func startable(d push.Registration) bool { |
| + return d.Platform == wire.PlatformIOS && d.StartToken != "" |
| +} |
| + |
| +// needsYouCount is the person's Needs you count (GET /needs-you), for the |
| +// badge. An error stays an error: never a zero. |
| +func (t *txn) needsYouCount(person string) (int, error) { |
| + var rows []taskRecord |
| + if err := t.db.Where("creator = ? AND stage NOT IN ?", person, []string{wire.StageDone, wire.StageCancelled}).Limit(wire.MaxTaskList).Find(&rows).Error; err != nil { |
| + return 0, err |
| + } |
| + n := 0 |
| + for _, k := range rows { |
| + v, err := t.taskView(k) |
| + if err != nil { |
| + return 0, err |
| + } |
| + if v.NeedsYou != "" { |
| + n++ |
| + } |
| + } |
| + return n, nil |
| +} |
| + |
| +// pushIntents writes each intent for the person's devices, and reports |
| +// the rows written. A once-only intent is decided once for the person, |
| +// devices or not (push_once), and never again. |
| +func (t *txn) pushIntents(person string, devices []push.Registration, intents []push.Intent) (int, error) { |
| + written := 0 |
| + for _, in := range intents { |
| + if in.Dedupe != "" { |
| + first, err := push.Once(t.db, person, in.Dedupe, t.now()) |
| + if err != nil { |
| + return written, err |
| + } |
| + if !first { |
| + continue |
| + } |
| + } |
| + n, err := t.enqueuePush(person, devices, in) |
| + if err != nil { |
| + return written, err |
| + } |
| + written += n |
| + } |
| + return written, nil |
| +} |
| + |
| +// pushCard: a card that waits on its person opened. Its alert is decided |
| +// even with no device registered, so a card opened before a device was |
| +// never alerts later. |
| +func (t *txn) pushCard(c cardRecord, v wire.Card) error { |
| + return t.pushSafe("card", func() error { |
| + card := push.Card{ID: c.ID, Kind: c.Kind, State: c.State, Lane: c.Lane, Question: v.Question, TaskID: c.TaskID, AccessFinal: v.Access != nil && wire.AccessFinal(v.Access.State)} |
| + intents := push.Decide(push.Change{Kind: push.ChangeCard, Now: t.now(), Card: card}) |
| + if len(intents) == 0 { |
| + return nil |
| + } |
| + devices, err := t.pushDevices(c.Person) |
| + if err != nil { |
| + return err |
| + } |
| + _, err = t.pushIntents(c.Person, devices, intents) |
| + return err |
| + }) |
| +} |
| + |
| +// pushReply: the coordinator's turn ended. |
| +func (t *txn) pushReply(r turnRecord) error { |
| + if r.State != wire.TurnReplied || r.ReplyID == "" { |
| + return nil |
| + } |
| + return t.pushSafe("reply", func() error { |
| + devices, err := t.pushDevices(r.Person) |
| + if err != nil || len(devices) == 0 { |
| + return err |
| + } |
| + var m messageRecord |
| + if err := t.db.Where("id = ? AND person = ?", r.ReplyID, r.Person).Take(&m).Error; err != nil { |
| + return err |
| + } |
| + reply := push.Reply{TurnID: r.ID, Lane: r.Lane, Kind: r.Kind, State: r.State, Text: m.Text} |
| + _, err = t.pushIntents(r.Person, devices, push.Decide(push.Change{Kind: push.ChangeReply, Now: t.now(), Reply: reply, Streaming: t.s.hub.Streaming(r.Person)})) |
| + return err |
| + }) |
| +} |
| + |
| +// pushTask: a task was written; its creator's devices hear what changed. |
| +func (t *txn) pushTask(v wire.Task) error { |
| + return t.pushSafe("task", func() error { |
| + devices, err := t.pushDevices(v.Creator) |
| + if err != nil || len(devices) == 0 { |
| + return err |
| + } |
| + before, err := push.LoadMemory(t.db, v.Creator, v.ID) |
| + if err != nil { |
| + return err |
| + } |
| + after := pushTaskOf(v, t.s.authority.Copy) |
| + now := t.now() |
| + next := before.Remember(after) |
| + for _, in := range push.Decide(push.Change{Kind: push.ChangeTask, Now: now, Before: before, After: after}) { |
| + if in.Kind == push.KindActivityStart { |
| + if !slices.ContainsFunc(devices, startable) { |
| + continue |
| + } |
| + if err := t.pushMakeRoom(v.Creator, devices); err != nil { |
| + return err |
| + } |
| + } |
| + n, err := t.pushIntents(v.Creator, devices, []push.Intent{in}) |
| + if err != nil { |
| + return err |
| + } |
| + switch { |
| + case in.Kind == push.KindActivityStart && n > 0: |
| + next.Started, next.Ended = &now, false |
| + case in.Kind == push.KindActivityEnd: |
| + next.Ended = true |
| + } |
| + } |
| + return push.SaveMemory(t.db, v.Creator, v.ID, next, now) |
| + }) |
| +} |
| + |
| +// pushMakeRoom ends the oldest Live Activities so a new one is at most |
| +// wire.MaxLiveActivities. |
| +func (t *txn) pushMakeRoom(person string, devices []push.Registration) error { |
| + live, err := push.LiveTasks(t.db, person) |
| + if err != nil { |
| + return err |
| + } |
| + for len(live) >= wire.MaxLiveActivities { |
| + old := live[0] |
| + live = live[1:] |
| + m, err := push.LoadMemory(t.db, person, old.TaskID) |
| + if err != nil { |
| + return err |
| + } |
| + if _, err := t.enqueuePush(person, devices, push.Replace(m.Task(old.TaskID))); err != nil { |
| + return err |
| + } |
| + m.Ended = true |
| + if err := push.SaveMemory(t.db, person, old.TaskID, m, t.now()); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// pushLine: a running step of a task reported an activity line. Only a |
| +// line some device was sent is remembered as told. |
| +func (t *txn) pushLine(s stepRecord, line wire.ActivityLine) error { |
| + return t.pushSafe("line", func() error { |
| + var k taskRecord |
| + if err := t.db.Where("id = ?", s.TaskID).Take(&k).Error; err != nil { |
| + return err |
| + } |
| + devices, err := t.pushDevices(k.Creator) |
| + if err != nil || len(devices) == 0 { |
| + return err |
| + } |
| + before, err := push.LoadMemory(t.db, k.Creator, k.ID) |
| + if err != nil || !before.Live() { |
| + return err |
| + } |
| + after := before.Task(k.ID) |
| + after.Activity = activityLine(line, t.s.authority.Copy) |
| + now := t.now() |
| + intents := push.Decide(push.Change{Kind: push.ChangeLine, Now: now, Before: before, After: after}) |
| + if len(intents) == 0 { |
| + return nil |
| + } |
| + n, err := t.pushIntents(k.Creator, devices, intents) |
| + if err != nil || n == 0 { |
| + return err |
| + } |
| + next := before.Remember(after) |
| + next.LineAt = &now |
| + return push.SaveMemory(t.db, k.Creator, k.ID, next, now) |
| + }) |
| +} |
| + |
| +// pushTaskOf is a task as its Live Activity shows it: the step working |
| +// now (running or queued, else the last done), its newest line, and |
| +// Roster's tone. |
| +func pushTaskOf(v wire.Task, copy func(string) string) push.Task { |
| + k := push.Task{ID: v.ID, Title: v.Title, Stage: v.Stage, NeedsYou: v.NeedsYou, Tone: wire.TonePositive} |
| + steps := v.Steps |
| + var current *wire.Step |
| + for j := len(steps) - 1; j >= 0 && current == nil; j-- { |
| + if steps[j].State == wire.StepRunning || steps[j].State == wire.StepQueued { |
| + current = &steps[j] |
| + } |
| + } |
| + for j := len(steps) - 1; j >= 0 && current == nil; j-- { |
| + if steps[j].State == wire.StepDone { |
| + current = &steps[j] |
| + } |
| + } |
| + if current != nil { |
| + k.Specialist, k.StepID = current.Specialist, current.ID |
| + if current.State == wire.StepRunning { |
| + k.Working = true |
| + k.Activity = copy("work.activity.working") |
| + if n := len(current.Activity); n > 0 { |
| + k.Activity = activityLine(current.Activity[n-1], copy) |
| + } |
| + } |
| + } |
| + switch { |
| + case v.Checks == wire.ChecksFailed || v.Verdict == wire.VerdictChanges: |
| + k.Tone = wire.ToneNegative |
| + case v.NeedsYou != "": |
| + k.Tone = wire.ToneWarning |
| + } |
| + return k |
| +} |
| + |
| +// activityLine is a step's activity line in words (the web's |
| +// activityText). |
| +func activityLine(a wire.ActivityLine, copy func(string) string) string { |
| + format := copy("work.activity." + a.Kind) |
| + if a.Subject == "" || a.Kind == wire.ActivityOther || format == "" { |
| + return copy("work.activity.working") |
| + } |
| + return push.Clip(fmt.Sprintf(format, a.Subject)) |
| +} |
diff --git a/internal/equipo/chat/push_http.go b/internal/equipo/chat/push_http.go| new file mode 100644 |
| index 00000000..7673e2fa |
| --- /dev/null |
| +++ b/internal/equipo/chat/push_http.go |
| @@ -0,0 +1,61 @@ |
| +package chat |
| + |
| +import ( |
| + "errors" |
| + "net/http" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/personapi" |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "github.com/go-chi/chi/v5" |
| +) |
| + |
| +// registerPush is POST /api/v1/push-registrations: 200 with the |
| +// registration, without its tokens. A device bearer only. |
| +func (h *HTTP) registerPush(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| + var in wire.RegisterPush |
| + if err := readJSON(r, &in); err != nil { |
| + h.fail(w, r, err) |
| + return |
| + } |
| + out, err := h.Store.RegisterPush(r.Context(), p.Address, p.CredentialID, in) |
| + if err != nil { |
| + h.fail(w, r, err) |
| + return |
| + } |
| + writeJSON(w, http.StatusOK, out) |
| +} |
| + |
| +// registerActivity is POST /api/v1/push-registrations/activities: 204. |
| +func (h *HTTP) registerActivity(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| + var in wire.RegisterActivity |
| + if err := readJSON(r, &in); err != nil { |
| + h.fail(w, r, err) |
| + return |
| + } |
| + if err := h.Store.RegisterActivity(r.Context(), p.Address, p.CredentialID, in); err != nil { |
| + h.fail(w, r, err) |
| + return |
| + } |
| + w.WriteHeader(http.StatusNoContent) |
| +} |
| + |
| +// cardVisibility is POST /api/v1/cards/{id}/visibility: 200 with the |
| +// card; 409 card_stale with the card as it is when its revision moved or |
| +// it no longer waits on the person. |
| +func (h *HTTP) cardVisibility(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| + var in wire.SetCardVisibility |
| + if err := readJSON(r, &in); err != nil { |
| + h.fail(w, r, err) |
| + return |
| + } |
| + out, err := h.Store.SetCardVisibility(r.Context(), p.Address, chi.URLParam(r, "id"), in) |
| + if errors.Is(err, ErrCardConflict) { |
| + writeJSON(w, http.StatusConflict, wire.CardConflict{Code: "card_stale", CopyKey: "api.card_stale", RequestID: r.Header.Get("Idempotency-Key"), Card: out}) |
| + return |
| + } |
| + if err != nil { |
| + h.fail(w, r, err) |
| + return |
| + } |
| + writeJSON(w, http.StatusOK, out) |
| +} |
diff --git a/internal/equipo/chat/push_review_test.go b/internal/equipo/chat/push_review_test.go| new file mode 100644 |
| index 00000000..4da857bd |
| --- /dev/null |
| +++ b/internal/equipo/chat/push_review_test.go |
| @@ -0,0 +1,87 @@ |
| +package chat |
| + |
| +import ( |
| + "context" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/push" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +func TestPushLateTokenKeepsReplacedActivityEnded(t *testing.T) { |
| + r := newPushRig(t) |
| + for _, id := range []string{"tk1", "tk2", "tk3", "tk4"} { |
| + k := r.task(id, "Task "+id, hkOwner) |
| + r.step(&k, "s"+id, wire.SpecialistEngineering, wire.StepRunning) |
| + } |
| + r.must(r.s.db.G.Model(&push.OutboxRecord{}).Where("task_id = ? AND kind = ?", "tk1", push.KindActivityEnd).Update("next_at", r.now.Add(time.Hour)).Error) |
| + r.must(r.activity("cr_phone", "tk1")) |
| + live, err := push.LiveTasks(r.s.db.G, hkOwner) |
| + r.must(err) |
| + if len(live) != 3 || live[0].TaskID != "tk2" { |
| + t.Fatalf("late token revived replaced activity: %d live", len(live)) |
| + } |
| + for _, row := range r.outbox() { |
| + if row.TaskID == "tk1" && row.Kind == push.KindActivityUpdate { |
| + t.Fatal("replaced activity received catch-up") |
| + } |
| + if row.TaskID == "tk1" && row.Kind == push.KindActivityEnd && row.NextAt.After(r.now) { |
| + t.Fatal("pending replacement end was not hurried") |
| + } |
| + } |
| + k := r.task("tk5", "Task tk5", hkOwner) |
| + r.step(&k, "stk5", wire.SpecialistEngineering, wire.StepRunning) |
| + var ends []string |
| + for _, row := range r.outbox() { |
| + if row.Kind == push.KindActivityEnd && strings.Contains(row.Payload, `"outcome":"replaced"`) { |
| + ends = append(ends, row.TaskID) |
| + } |
| + } |
| + if strings.Join(ends, " ") != "tk1 tk2" { |
| + t.Fatalf("unexpected replaced tasks: %v", ends) |
| + } |
| +} |
| + |
| +type reviewPushTransport func(push.Message) (push.Result, error) |
| + |
| +func (f reviewPushTransport) Send(_ context.Context, m push.Message) (push.Result, error) { |
| + return f(m) |
| +} |
| + |
| +func TestPushDelayedStartAcceptsTokenAndEnds(t *testing.T) { |
| + r := newPushRig(t) |
| + k := r.task("tk1", "Short task", hkOwner) |
| + r.step(&k, "s1", wire.SpecialistEngineering, wire.StepRunning) |
| + var start push.OutboxRecord |
| + r.must(r.s.db.G.Where("kind = ?", push.KindActivityStart).Take(&start).Error) |
| + delayed := true |
| + ended := false |
| + sender := r.s.PushSender(reviewPushTransport(func(m push.Message) (push.Result, error) { |
| + if m.ID == start.ID && delayed { |
| + return push.Result{Status: 503}, nil |
| + } |
| + if strings.Contains(string(m.Payload), `"event":"end"`) { |
| + ended = true |
| + } |
| + return push.Result{Status: 200}, nil |
| + })) |
| + drain := func() { _, err := sender.Drain(r.ctx); r.must(err) } |
| + drain() |
| + r.stage(&k, wire.StageCancelled) |
| + for i := 0; i < 14; i++ { |
| + drain() |
| + r.now = r.now.Add(time.Minute) |
| + } |
| + delayed = false |
| + r.now = r.now.Add(2 * time.Minute) |
| + drain() |
| + if err := r.activity("cr_phone", "tk1"); err != nil { |
| + t.Fatal("late token refused:", err) |
| + } |
| + drain() |
| + if !ended { |
| + t.Fatal("delayed start left an activity without its end") |
| + } |
| +} |
diff --git a/internal/equipo/chat/push_test.go b/internal/equipo/chat/push_test.go| new file mode 100644 |
| index 00000000..05e1cd49 |
| --- /dev/null |
| +++ b/internal/equipo/chat/push_test.go |
| @@ -0,0 +1,638 @@ |
| +package chat |
| + |
| +import ( |
| + "context" |
| + "encoding/base64" |
| + "encoding/json" |
| + "errors" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/personapi" |
| + "amadan.net/oficina/equipo/internal/equipo/push" |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "gorm.io/gorm" |
| +) |
| + |
| +const ( |
| + pushDevice = "aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11" |
| + pushStart = "bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22" |
| + pushMac = "dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44" |
| +) |
| + |
| +// pushRig is a housekeeping rig with the outbox on, owner's iPhone |
| +// registered (credential cr_phone) and devices current until revoked. |
| +type pushRig struct { |
| + *hkRig |
| + revoked map[string]bool |
| + audits []string |
| +} |
| + |
| +func newPushRig(t *testing.T) *pushRig { |
| + t.Helper() |
| + r := &pushRig{hkRig: newHKRig(t), revoked: map[string]bool{}} |
| + r.s.authority.PushDevice = func(_ *gorm.DB, person, credential string) error { |
| + if r.revoked[credential] || !strings.HasPrefix(credential, "cr_") { |
| + return ErrForbidden |
| + } |
| + return nil |
| + } |
| + r.s.authority.Audit = func(_ *gorm.DB, actor, kind, record string) error { |
| + r.audits = append(r.audits, actor+" "+kind+" "+record) |
| + return nil |
| + } |
| + // Sealing as the instance key does, for the tests: what it seals never |
| + // shows the token or the text. |
| + r.s.authority.Seal = func(domain string, v any) (string, error) { |
| + b, err := json.Marshal(v) |
| + return domain + ":" + base64.StdEncoding.EncodeToString(b), err |
| + } |
| + r.s.authority.Open = func(domain, sealed string, v any) error { |
| + raw, ok := strings.CutPrefix(sealed, domain+":") |
| + if !ok { |
| + return errors.New("sealed for another domain") |
| + } |
| + b, err := base64.StdEncoding.DecodeString(raw) |
| + if err != nil { |
| + return err |
| + } |
| + return json.Unmarshal(b, v) |
| + } |
| + r.s.SetPush(true) |
| + r.register(hkOwner, "cr_phone", wire.RegisterPush{Token: pushDevice, Environment: wire.APNsProduction, Platform: wire.PlatformIOS, StartToken: pushStart}) |
| + r.clear() |
| + return r |
| +} |
| + |
| +// clear forgets the rows written so far (a registration's badge). |
| +func (r *pushRig) clear() { |
| + r.t.Helper() |
| + r.must(r.s.db.G.Where("1 = 1").Delete(&push.OutboxRecord{}).Error) |
| +} |
| + |
| +func (r *pushRig) register(person, credential string, in wire.RegisterPush) { |
| + r.t.Helper() |
| + if _, err := r.s.RegisterPush(r.ctx, person, credential, in); err != nil { |
| + r.t.Fatal(err) |
| + } |
| +} |
| + |
| +// outbox is the rows written, oldest first, their payloads opened. |
| +func (r *pushRig) outbox() []push.OutboxRecord { |
| + r.t.Helper() |
| + var out []push.OutboxRecord |
| + r.must(r.s.db.G.Order("created_at, kind, collapse_id").Find(&out).Error) |
| + for i := range out { |
| + p, err := r.s.pushBox().OpenPayload(out[i].Payload) |
| + r.must(err) |
| + out[i].Payload = p |
| + } |
| + return out |
| +} |
| + |
| +// activity sends the running activity's own token for the task, as the |
| +// app does once the activity started. |
| +func (r *pushRig) activity(credential, task string) error { |
| + return r.s.RegisterActivity(r.ctx, hkOwner, credential, wire.RegisterActivity{TaskID: task, Token: pushStart}) |
| +} |
| + |
| +func kinds(rows []push.OutboxRecord) string { |
| + var out []string |
| + for _, row := range rows { |
| + out = append(out, row.Kind) |
| + } |
| + return strings.Join(out, " ") |
| +} |
| + |
| +// step saves the task with a step of its in the state given. |
| +func (r *pushRig) step(k *taskRecord, id, specialist, state string) { |
| + r.t.Helper() |
| + r.must(r.tx(func(t *txn) error { |
| + s := stepRecord{ID: id, TaskID: k.ID, Idx: 1, Specialist: specialist, Person: k.Creator, State: state, Attempt: 1, Terminated: state == wire.StepFailed, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now} |
| + if err := t.db.Save(&s).Error; err != nil { |
| + return err |
| + } |
| + return t.saveTask(k) |
| + })) |
| + r.now = r.now.Add(time.Second) |
| +} |
| + |
| +func (r *pushRig) stage(k *taskRecord, stage string) { |
| + r.t.Helper() |
| + k.Stage = stage |
| + r.must(r.tx(func(t *txn) error { return t.saveTask(k) })) |
| + r.now = r.now.Add(time.Second) |
| +} |
| + |
| +// TestPushOutboxInEngineTransaction: the rows are written by the change's |
| +// own transaction, beside its event, and vanish with it when it rolls |
| +// back; with the outbox off nothing is written. |
| +func TestPushOutboxInEngineTransaction(t *testing.T) { |
| + r := newPushRig(t) |
| + k := r.task("tk1", "Fix login", hkOwner) |
| + events := r.count("SELECT count(*) FROM chat_events") |
| + boom := errors.New("boom") |
| + err := r.tx(func(t *txn) error { |
| + s := stepRecord{ID: "s1", TaskID: k.ID, Idx: 1, Specialist: wire.SpecialistEngineering, Person: hkOwner, State: wire.StepRunning, Attempt: 1, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now} |
| + if err := t.db.Create(&s).Error; err != nil { |
| + return err |
| + } |
| + if err := t.saveTask(&k); err != nil { |
| + return err |
| + } |
| + var n int64 |
| + if err := t.db.Model(&push.OutboxRecord{}).Count(&n).Error; err != nil || n != 1 { |
| + r.t.Errorf("inside the transaction: %d rows, %v", n, err) |
| + } |
| + return boom |
| + }) |
| + if !errors.Is(err, boom) || len(r.outbox()) != 0 || r.count("SELECT count(*) FROM chat_events") != events || r.count("SELECT count(*) FROM push_tasks") != 0 { |
| + t.Fatal("a rolled back change left its push behind") |
| + } |
| + k = r.load("tk1") |
| + r.s.SetPush(false) |
| + r.step(&k, "s1", wire.SpecialistEngineering, wire.StepRunning) |
| + if len(r.outbox()) != 0 { |
| + t.Fatal("the outbox was written while off") |
| + } |
| + r.s.SetPush(true) |
| + r.stage(&k, wire.StageInProgress) |
| + if got := kinds(r.outbox()); got != push.KindActivityStart { |
| + t.Fatalf("outbox %q", got) |
| + } |
| +} |
| + |
| +// TestPushTaskLifecycle drives a task through the engine: dispatch starts |
| +// its Live Activity by push-to-start, a stage change updates it, needing |
| +// the person updates it urgently with the badge (their Needs you count), |
| +// and its end alerts passively and ends the activity. |
| +func TestPushTaskLifecycle(t *testing.T) { |
| + r := newPushRig(t) |
| + k := r.task("tk1", "Fix login", hkOwner) |
| + r.stage(&k, wire.StageNoted) |
| + if len(r.outbox()) != 0 { |
| + t.Fatal("a noted task pushed") |
| + } |
| + r.step(&k, "s1", wire.SpecialistEngineering, wire.StepRunning) |
| + rows := r.outbox() |
| + if kinds(rows) != push.KindActivityStart || rows[0].Target != push.TargetStart || rows[0].Priority != 10 || rows[0].PushType != push.TypeLiveActivity { |
| + t.Fatalf("start %+v", rows) |
| + } |
| + var p struct { |
| + APS struct { |
| + ContentState wire.LiveActivityState `json:"content-state"` |
| + } `json:"aps"` |
| + } |
| + r.must(json.Unmarshal([]byte(rows[0].Payload), &p)) |
| + if s := p.APS.ContentState; s.TaskID != "tk1" || s.Specialist != wire.SpecialistEngineering || s.Activity != "work.activity.working" || s.Tone != wire.TonePositive { |
| + t.Fatalf("content state %+v", s) |
| + } |
| + // The activity's own token arrives: it hears the whole state at once. |
| + r.must(r.activity("cr_phone", "tk1")) |
| + if rows = r.outbox(); kinds(rows[1:]) != push.KindActivityUpdate || rows[1].Priority != 10 || rows[1].Target != push.TargetActivity { |
| + t.Fatalf("catch-up %+v", rows[1:]) |
| + } |
| + r.stage(&k, wire.StageInReview) |
| + if rows = r.outbox(); kinds(rows[2:]) != push.KindActivityUpdate || rows[2].Priority != 5 || rows[2].Target != push.TargetActivity { |
| + t.Fatalf("update %+v", rows[2:]) |
| + } |
| + r.step(&k, "s1", wire.SpecialistEngineering, wire.StepDone) |
| + r.stage(&k, wire.StageReadyToMerge) |
| + rows = r.outbox() |
| + last := rows[len(rows)-2:] |
| + // Urgent and silent: a card, if any, is the one sound. |
| + if kinds(last) != "activity_update badge" || last[0].Priority != 10 || strings.Contains(last[0].Payload, `"alert"`) || last[1].Payload != `{"aps":{"badge":1}}` { |
| + t.Fatalf("needs you %+v", last) |
| + } |
| + r.stage(&k, wire.StageDone) |
| + rows = r.outbox() |
| + last = rows[len(rows)-2:] |
| + // The unsent badge took the new count (it coalesces). |
| + if kinds(last) != "activity_end passive" || last[1].CollapseID != "task:tk1" || rows[len(rows)-3].Payload != `{"aps":{"badge":0}}` { |
| + t.Fatalf("end %s", kinds(rows)) |
| + } |
| + // Seen again ended: nothing more. |
| + n := len(rows) |
| + r.stage(&k, wire.StageDone) |
| + if len(r.outbox()) != n { |
| + t.Fatal("an ended task pushed again") |
| + } |
| +} |
| + |
| +// TestPushAtMostThreeActivities: a fourth dispatched task ends the oldest |
| +// started one's Live Activity. |
| +func TestPushAtMostThreeActivities(t *testing.T) { |
| + r := newPushRig(t) |
| + for _, id := range []string{"tk1", "tk2", "tk3", "tk4"} { |
| + k := r.task(id, "Task "+id, hkOwner) |
| + r.step(&k, "s"+id, wire.SpecialistEngineering, wire.StepRunning) |
| + } |
| + var ends []push.OutboxRecord |
| + for _, row := range r.outbox() { |
| + if row.Kind == push.KindActivityEnd { |
| + ends = append(ends, row) |
| + } |
| + } |
| + if len(ends) != 1 || ends[0].TaskID != "tk1" || !strings.Contains(ends[0].Payload, `"outcome":"replaced"`) { |
| + t.Fatalf("ends %+v", ends) |
| + } |
| + live, err := push.LiveTasks(r.s.db.G, hkOwner) |
| + if err != nil || len(live) != wire.MaxLiveActivities || live[0].TaskID != "tk2" { |
| + t.Fatalf("live %+v %v", live, err) |
| + } |
| +} |
| + |
| +// TestPushActivityLineOnceAMinute: activity lines update a running |
| +// activity at most once a minute. |
| +func TestPushActivityLineOnceAMinute(t *testing.T) { |
| + r := newPushRig(t) |
| + k := r.task("tk1", "Fix login", hkOwner) |
| + r.step(&k, "s1", wire.SpecialistEngineering, wire.StepRunning) |
| + s := stepRecord{ID: "s1", TaskID: "tk1", Person: hkOwner} |
| + line := func(subject string) { |
| + r.must(r.tx(func(t *txn) error { |
| + return t.pushLine(s, wire.ActivityLine{Kind: wire.ActivityRead, Subject: subject, At: r.now}) |
| + })) |
| + } |
| + // No token yet: the line goes nowhere, and is not remembered as told. |
| + line("README.md") |
| + if kinds(r.outbox()) != push.KindActivityStart { |
| + t.Fatalf("a line with no activity token %s", kinds(r.outbox())) |
| + } |
| + r.must(r.activity("cr_phone", "tk1")) |
| + line("README.md") |
| + r.now = r.now.Add(20 * time.Second) |
| + line("main.go") |
| + r.now = r.now.Add(time.Minute) |
| + line("go.mod") |
| + rows := r.outbox() |
| + if kinds(rows) != "activity_start activity_update activity_update activity_update" || !strings.Contains(rows[2].Payload, "work.activity.read") || !strings.Contains(rows[3].Payload, "go.mod") { |
| + t.Fatalf("lines %s", kinds(rows)) |
| + } |
| +} |
| + |
| +func (r *pushRig) card(id, state string) cardRecord { return r.cardFor(hkOwner, id, state) } |
| + |
| +func (r *pushRig) cardFor(person, id, state string) cardRecord { |
| + r.t.Helper() |
| + c := cardRecord{ID: id, Person: person, Kind: wire.CardQuestion, State: state, Question: "Which branch should the fix go on?", Options: `["main","release"]`, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now} |
| + r.must(r.tx(func(t *txn) error { |
| + if err := t.db.Create(&c).Error; err != nil { |
| + return err |
| + } |
| + return t.cardEvent(c) |
| + })) |
| + return c |
| +} |
| + |
| +// TestPushCardOpensOnce: an open card alerts its person once, with its |
| +// question; written again, or set aside, it does not alert again, and |
| +// set aside it keeps its place in Needs you. |
| +func TestPushCardOpensOnce(t *testing.T) { |
| + r := newPushRig(t) |
| + c := r.card("c1", wire.CardOpen) |
| + rows := r.outbox() |
| + if kinds(rows) != push.KindAlert || rows[0].CollapseID != "c1" || rows[0].Priority != 10 || !strings.Contains(rows[0].Payload, "Which branch should the fix go on?") { |
| + t.Fatalf("card alert %+v", rows) |
| + } |
| + r.must(r.tx(func(t *txn) error { return t.cardEvent(c) })) |
| + out, err := r.s.SetCardVisibility(r.ctx, hkOwner, "c1", wire.SetCardVisibility{Aside: true, Revision: 1}) |
| + if err != nil || !out.Aside || out.State != wire.CardOpen { |
| + t.Fatalf("set aside %+v %v", out, err) |
| + } |
| + if len(r.outbox()) != 1 { |
| + t.Fatal("the card alerted again") |
| + } |
| + r.card("c2", wire.CardAnswered) |
| + if len(r.outbox()) != 1 { |
| + t.Fatal("an answered card alerted") |
| + } |
| + // The mark outlives the outbox: pruned rows do not make it alert again. |
| + r.must(r.s.db.G.Where("1 = 1").Delete(&push.OutboxRecord{}).Error) |
| + r.must(r.tx(func(t *txn) error { return t.cardEvent(c) })) |
| + if len(r.outbox()) != 0 { |
| + t.Fatal("the card alerted again once its row was pruned") |
| + } |
| + // A card that opened before the person had a device never alerts. |
| + r.cardFor(hkMember, "c3", wire.CardOpen) |
| + r.register(hkMember, "cr_member", wire.RegisterPush{Token: pushMac, Environment: wire.APNsProduction, Platform: wire.PlatformMacOS}) |
| + r.must(r.tx(func(t *txn) error { |
| + var c cardRecord |
| + if err := t.db.Where("id = ?", "c3").Take(&c).Error; err != nil { |
| + return err |
| + } |
| + return t.cardEvent(c) |
| + })) |
| + for _, row := range r.outbox() { |
| + if row.Kind == push.KindAlert { |
| + t.Fatal("a card older than the device alerted", row.CollapseID) |
| + } |
| + } |
| +} |
| + |
| +// TestPushNeverToRemovedOrRevoked: a person off the roster, or a device |
| +// revoked, gets no row at all. |
| +func TestPushNeverToRemovedOrRevoked(t *testing.T) { |
| + r := newPushRig(t) |
| + r.register(hkOwner, "cr_mac", wire.RegisterPush{Token: pushMac, Environment: wire.APNsProduction, Platform: wire.PlatformMacOS}) |
| + r.clear() |
| + r.revoked["cr_mac"] = true |
| + r.card("c1", wire.CardOpen) |
| + rows := r.outbox() |
| + if len(rows) != 1 || rows[0].Credential != "cr_phone" { |
| + t.Fatalf("revoked device pushed: %+v", rows) |
| + } |
| + r.must(r.tx(func(t *txn) error { return t.db.Exec("UPDATE members SET active = 0 WHERE address = ?", hkOwner).Error })) |
| + r.card("c2", wire.CardOpen) |
| + if len(r.outbox()) != 1 { |
| + t.Fatal("a removed person was pushed") |
| + } |
| +} |
| + |
| +// TestPushReplyOnlyWhenNotFollowing: a finished reply alerts with its |
| +// first line, unless the person has the stream open. |
| +func TestPushReplyOnlyWhenNotFollowing(t *testing.T) { |
| + r := newPushRig(t) |
| + reply := func(id string) { |
| + r.must(r.tx(func(t *txn) error { |
| + turn := turnRecord{ID: id, Person: hkOwner, State: wire.TurnRunning, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now} |
| + m := messageRecord{ID: "m_" + id, Person: hkOwner, IdempotencyKey: "reply:" + id, Role: wire.RoleCoordinator, Text: "**Done.** The fix is on its branch.\nDetails follow.", TurnID: id, Revision: 1, CreatedAt: r.now} |
| + if err := t.db.Create(&turn).Error; err != nil { |
| + return err |
| + } |
| + if err := t.db.Create(&m).Error; err != nil { |
| + return err |
| + } |
| + turn.State, turn.ReplyID = wire.TurnReplied, m.ID |
| + return t.saveTurn(&turn) |
| + })) |
| + } |
| + done := r.s.Hub().Follow(hkOwner) |
| + reply("t_watched") |
| + if len(r.outbox()) != 0 { |
| + t.Fatal("pushed a reply the person was watching") |
| + } |
| + done() |
| + reply("t_away") |
| + rows := r.outbox() |
| + if len(rows) != 1 || rows[0].CollapseID != "reply:t_away" || !strings.Contains(rows[0].Payload, `"body":"Done. The fix is on its branch."`) { |
| + t.Fatalf("reply %+v", rows) |
| + } |
| +} |
| + |
| +// TestRegisterPushAuthority: only a device credential of a current |
| +// person registers; the audit names the credential, never a token; an |
| +// activity token is only for a task of the person's that has not ended. |
| +func TestRegisterPushAuthority(t *testing.T) { |
| + r := newPushRig(t) |
| + in := wire.RegisterPush{Token: pushDevice, Environment: wire.APNsProduction, Platform: wire.PlatformIOS} |
| + // A browser session has no device credential: refused even where the |
| + // device check would pass. |
| + check := r.s.authority.PushDevice |
| + r.s.authority.PushDevice = func(*gorm.DB, string, string) error { return nil } |
| + if _, err := r.s.RegisterPush(r.ctx, hkOwner, "", in); !errors.Is(err, ErrForbidden) { |
| + t.Fatal("a browser session registered", err) |
| + } |
| + r.s.authority.PushDevice = check |
| + r.revoked["cr_phone"] = true |
| + if _, err := r.s.RegisterPush(r.ctx, hkOwner, "cr_phone", in); !errors.Is(err, ErrForbidden) { |
| + t.Fatal("a revoked device registered", err) |
| + } |
| + r.revoked["cr_phone"] = false |
| + if _, err := r.s.RegisterPush(r.ctx, hkOwner, "cr_phone", wire.RegisterPush{Token: "nothex", Environment: wire.APNsProduction, Platform: wire.PlatformIOS}); !errors.Is(err, ErrInvalid) { |
| + t.Fatal("a bad token registered", err) |
| + } |
| + for _, a := range r.audits { |
| + if strings.Contains(a, pushDevice) || strings.Contains(a, pushStart) { |
| + t.Fatal("token in audit", a) |
| + } |
| + } |
| + if len(r.audits) != 1 || r.audits[0] != hkOwner+" push.register cr_phone" { |
| + t.Fatalf("audits %v", r.audits) |
| + } |
| + r.task("tk_mine", "Mine", hkOwner) |
| + r.task("tk_theirs", "Theirs", hkMember) |
| + act := func(task string) error { |
| + return r.s.RegisterActivity(r.ctx, hkOwner, "cr_phone", wire.RegisterActivity{TaskID: task, Token: pushStart}) |
| + } |
| + if err := act("tk_theirs"); !errors.Is(err, ErrNotFound) { |
| + t.Fatal("another's task", err) |
| + } |
| + if err := act("tk_mine"); err != nil { |
| + t.Fatal(err) |
| + } |
| + k := r.load("tk_mine") |
| + r.stage(&k, wire.StageCancelled) |
| + // Its end waits for the device: the token is still taken. |
| + if err := act("tk_mine"); err != nil { |
| + t.Fatal("an ended task whose end waits", err) |
| + } |
| + r.must(r.s.db.G.Model(&push.OutboxRecord{}).Where("1 = 1").Update("state", push.StateSent).Error) |
| + if err := act("tk_mine"); !errors.Is(err, ErrTaskEnded) { |
| + t.Fatal("an ended task with nothing waiting", err) |
| + } |
| +} |
| + |
| +// TestPushRegistrationAnswersNoToken: the registration answers its |
| +// environment and platform, never a token. |
| +func TestPushRegistrationAnswersNoToken(t *testing.T) { |
| + r := newPushRig(t) |
| + h := &HTTP{Store: r.s} |
| + out, err := h.Store.RegisterPush(personapi.WithVerifiedPrincipal(context.Background(), personapi.PersonPrincipal{Address: hkOwner, CredentialID: "cr_phone"}), hkOwner, "cr_phone", wire.RegisterPush{Token: pushDevice, Environment: wire.APNsDevelopment, Platform: wire.PlatformIOS, StartToken: pushStart}) |
| + raw, _ := json.Marshal(out) |
| + if err != nil || !out.LiveActivities || strings.Contains(string(raw), pushDevice) || strings.Contains(string(raw), pushStart) { |
| + t.Fatalf("registration %s %v", raw, err) |
| + } |
| +} |
| + |
| +// TestSetAsideKeepsNeedsYou (D5): a card set aside still waits on its |
| +// person, so its task stays in Needs you and the badge does not move; a |
| +// stale revision or a card that no longer waits is a conflict carrying |
| +// the card as it is. |
| +func TestSetAsideKeepsNeedsYou(t *testing.T) { |
| + r := newPushRig(t) |
| + k := r.task("tk1", "Fix login", hkOwner) |
| + r.stage(&k, wire.StageReadyToMerge) |
| + c := cardRecord{ID: "c1", Person: hkOwner, Kind: wire.CardQuestion, State: wire.CardOpen, TaskID: "tk1", Question: "Merge it?", Options: `["yes","no"]`, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now} |
| + r.must(r.s.db.G.Create(&c).Error) |
| + before := len(r.outbox()) |
| + // c1 opened with no alert decided (as one opened before push): setting |
| + // it aside runs no push rule, so it does not alert now. |
| + out, err := r.s.SetCardVisibility(r.ctx, hkOwner, "c1", wire.SetCardVisibility{Aside: true, Revision: 1}) |
| + if err != nil || !out.Aside || out.Revision != 1 { |
| + t.Fatalf("aside %+v %v", out, err) |
| + } |
| + list, err := r.s.NeedsYou(r.ctx, hkOwner) |
| + if err != nil || len(list.Items) != 1 || list.Items[0].ID != "tk1" { |
| + t.Fatalf("needs you %+v %v", list.Items, err) |
| + } |
| + for _, row := range r.outbox()[before:] { |
| + if row.Kind == push.KindBadge { |
| + t.Fatal("setting aside moved the badge") |
| + } |
| + if row.Kind == push.KindAlert { |
| + t.Fatal("setting aside alerted", row.CollapseID) |
| + } |
| + } |
| + if out, err := r.s.SetCardVisibility(r.ctx, hkOwner, "c1", wire.SetCardVisibility{Aside: false, Revision: 7}); !errors.Is(err, ErrCardConflict) || out.ID != "c1" || !out.Aside { |
| + t.Fatalf("stale %+v %v", out, err) |
| + } |
| + r.must(r.s.db.G.Model(&cardRecord{}).Where("id = ?", "c1").Update("state", wire.CardAnswered).Error) |
| + if out, err := r.s.SetCardVisibility(r.ctx, hkOwner, "c1", wire.SetCardVisibility{Aside: false, Revision: 1}); !errors.Is(err, ErrCardConflict) || out.State != wire.CardAnswered { |
| + t.Fatalf("answered %+v %v", out, err) |
| + } |
| + if _, err := r.s.SetCardVisibility(r.ctx, hkMember, "c1", wire.SetCardVisibility{Aside: true, Revision: 1}); !errors.Is(err, ErrNotFound) { |
| + t.Fatal("another person's card", err) |
| + } |
| +} |
| + |
| +// TestPushTokenMovesToNewCredential: A signs out offline and B pairs on |
| +// the same phone. Its token is B's alone: A's card questions never reach |
| +// B's lock screen, and A's queued pushes go nowhere. |
| +func TestPushTokenMovesToNewCredential(t *testing.T) { |
| + r := newPushRig(t) |
| + r.card("c_before", wire.CardOpen) |
| + r.register(hkMember, "cr_b", wire.RegisterPush{Token: pushDevice, Environment: wire.APNsProduction, Platform: wire.PlatformIOS, StartToken: pushStart}) |
| + r.card("c_a", wire.CardOpen) |
| + r.cardFor(hkMember, "c_b", wire.CardOpen) |
| + for _, row := range r.outbox() { |
| + switch { |
| + case row.Credential == "cr_phone" && row.State == push.StatePending: |
| + t.Fatalf("A's push still waits for the phone: %+v", row) |
| + case row.Person == hkOwner && row.Credential == "cr_b": |
| + t.Fatalf("A's push went to B: %+v", row) |
| + } |
| + } |
| + var regs []push.Registration |
| + r.must(r.s.db.G.Find(®s).Error) |
| + if len(regs) != 1 || regs[0].Credential != "cr_b" || regs[0].Person != hkMember { |
| + t.Fatalf("registrations %+v", regs) |
| + } |
| + got := map[string]bool{} |
| + for _, row := range r.outbox() { |
| + got[row.Credential+" "+row.CollapseID] = true |
| + } |
| + if !got["cr_b c_b"] { |
| + t.Fatalf("B's card did not alert B: %v", got) |
| + } |
| +} |
| + |
| +// TestPushActivityTokenAfterEnd: a short task cancelled before its |
| +// activity's token arrived still ends its activity: the token is taken |
| +// while the end waits, and the end goes at once. An update with no token |
| +// is never written, and the activity hears the whole state when its token |
| +// arrives. |
| +func TestPushActivityTokenAfterEnd(t *testing.T) { |
| + r := newPushRig(t) |
| + k := r.task("tk1", "Fix login", hkOwner) |
| + r.step(&k, "s1", wire.SpecialistEngineering, wire.StepRunning) |
| + r.stage(&k, wire.StageInReview) |
| + if kinds(r.outbox()) != push.KindActivityStart { |
| + t.Fatalf("an update with no token was written: %s", kinds(r.outbox())) |
| + } |
| + r.stage(&k, wire.StageCancelled) |
| + var end push.OutboxRecord |
| + r.must(r.s.db.G.Where("kind = ?", push.KindActivityEnd).Take(&end).Error) |
| + r.must(r.s.db.G.Model(&end).Updates(map[string]any{"attempts": 3, "next_at": r.now.Add(time.Hour)}).Error) |
| + if err := r.activity("cr_phone", "tk1"); err != nil { |
| + t.Fatal("the end waits, yet the token was refused:", err) |
| + } |
| + r.must(r.s.db.G.Where("id = ?", end.ID).Take(&end).Error) |
| + if end.State != push.StatePending || end.NextAt.After(r.now) { |
| + t.Fatalf("the end did not go at once: %+v", end) |
| + } |
| + if has, err := push.HasActivity(r.s.db.G, "cr_phone", "tk1"); err != nil || !has { |
| + t.Fatal("token not kept", err) |
| + } |
| + |
| + k2 := r.task("tk2", "Add search", hkOwner) |
| + r.step(&k2, "s2", wire.SpecialistEngineering, wire.StepRunning) |
| + r.stage(&k2, wire.StageInReview) |
| + n := len(r.outbox()) |
| + r.must(r.activity("cr_phone", "tk2")) |
| + rows := r.outbox()[n:] |
| + if kinds(rows) != push.KindActivityUpdate || !strings.Contains(rows[0].Payload, `"stage":"in_review"`) || rows[0].Target != push.TargetActivity { |
| + t.Fatalf("catch-up %+v", rows) |
| + } |
| +} |
| + |
| +// TestPushFirstDeviceHearsOutcomes: a task already waiting on the person |
| +// when their first device registers sets the badge at once, and its merge |
| +// still pushes Done and the badge. |
| +func TestPushFirstDeviceHearsOutcomes(t *testing.T) { |
| + r := newPushRig(t) |
| + k := r.task("tk1", "Fix login", hkMember) |
| + r.stage(&k, wire.StageReadyToMerge) |
| + r.register(hkMember, "cr_m", wire.RegisterPush{Token: pushMac, Environment: wire.APNsProduction, Platform: wire.PlatformMacOS}) |
| + rows := r.outbox() |
| + if len(rows) != 1 || rows[0].Credential != "cr_m" || rows[0].Payload != `{"aps":{"badge":1}}` { |
| + t.Fatalf("registration badge %+v", rows) |
| + } |
| + r.clear() |
| + r.stage(&k, wire.StageDone) |
| + rows = r.outbox() |
| + if kinds(rows) != "badge passive" || rows[0].Payload != `{"aps":{"badge":0}}` || !strings.Contains(rows[1].Payload, "push.task.done") { |
| + t.Fatalf("outcome %s %+v", kinds(rows), rows) |
| + } |
| +} |
| + |
| +// TestPushNeverFailsTheWrite: push bookkeeping that fails rolls back alone |
| +// and the change commits; nothing pushes. |
| +func TestPushNeverFailsTheWrite(t *testing.T) { |
| + r := newPushRig(t) |
| + k := r.task("tk1", "Fix login", hkOwner) |
| + r.must(r.s.db.G.Exec("DROP TABLE push_tasks").Error) |
| + r.step(&k, "s1", wire.SpecialistEngineering, wire.StepRunning) |
| + if got := r.load("tk1"); got.Revision != k.Revision { |
| + t.Fatalf("the task write did not commit: revision %d, want %d", got.Revision, k.Revision) |
| + } |
| + if len(r.outbox()) != 0 { |
| + t.Fatal("a failed push left rows") |
| + } |
| + // A reply whose message cannot be read: the turn is still saved. |
| + r.must(r.tx(func(t *txn) error { |
| + turn := turnRecord{ID: "t1", Person: hkOwner, State: wire.TurnRunning, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now} |
| + if err := t.db.Create(&turn).Error; err != nil { |
| + return err |
| + } |
| + turn.State, turn.ReplyID = wire.TurnReplied, "m_missing" |
| + return t.saveTurn(&turn) |
| + })) |
| + var turn turnRecord |
| + r.must(r.s.db.G.Where("id = ?", "t1").Take(&turn).Error) |
| + if turn.State != wire.TurnReplied { |
| + t.Fatal("the turn was not saved") |
| + } |
| + // Push work that wrote before it failed (the card's once-only mark, |
| + // then no outbox) is undone, and the card is still written. |
| + r.must(r.s.db.G.Exec("DROP TABLE push_outbox").Error) |
| + r.card("c1", wire.CardOpen) |
| + if r.count("SELECT count(*) FROM chat_cards WHERE id = 'c1'") != 1 || r.count("SELECT count(*) FROM push_once") != 0 { |
| + t.Fatal("a failed push kept its part, or lost the card") |
| + } |
| +} |
| + |
| +// TestPushStartsOnlyWhereItCan: with no device that can start a Live |
| +// Activity (a Mac only), a dispatch ends no older activity to make room. |
| +func TestPushStartsOnlyWhereItCan(t *testing.T) { |
| + r := newPushRig(t) |
| + for _, id := range []string{"tk1", "tk2", "tk3"} { |
| + k := r.task(id, "Task "+id, hkOwner) |
| + r.step(&k, "s"+id, wire.SpecialistEngineering, wire.StepRunning) |
| + } |
| + r.must(r.s.db.G.Where("credential = ?", "cr_phone").Delete(&push.Registration{}).Error) |
| + r.register(hkOwner, "cr_mac", wire.RegisterPush{Token: pushMac, Environment: wire.APNsProduction, Platform: wire.PlatformMacOS}) |
| + r.clear() |
| + k := r.task("tk4", "Task tk4", hkOwner) |
| + r.step(&k, "stk4", wire.SpecialistEngineering, wire.StepRunning) |
| + for _, row := range r.outbox() { |
| + if row.Kind == push.KindActivityEnd { |
| + t.Fatalf("ended %s to make room for an activity that never starts", row.TaskID) |
| + } |
| + } |
| + live, err := push.LiveTasks(r.s.db.G, hkOwner) |
| + if err != nil || len(live) != 3 { |
| + t.Fatalf("live %+v %v", live, err) |
| + } |
| +} |
diff --git a/internal/equipo/chat/roster.go b/internal/equipo/chat/roster.go| index c780f27c..3d321efa 100644 |
| --- a/internal/equipo/chat/roster.go |
| +++ b/internal/equipo/chat/roster.go |
| @@ -59,15 +59,51 @@ type CardThreadTurn struct { |
| func (s *Store) SetCardAside(ctx context.Context, person, id string, revision int64, aside bool) error { |
| return s.tx(ctx, func(t *txn) error { |
| - if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| + _, err := t.setCardAside(person, id, revision, aside) |
| + return err |
| + }) |
| +} |
| + |
| +// SetCardVisibility is POST /api/v1/cards/{id}/visibility: SetCardAside |
| +// for a device, answering the card as the person sees it now, and on a |
| +// stale revision ErrCardConflict with the card as it is. |
| +func (s *Store) SetCardVisibility(ctx context.Context, person, id string, in wire.SetCardVisibility) (out wire.Card, err error) { |
| + var c cardRecord |
| + err = s.tx(ctx, func(t *txn) error { |
| + var err error |
| + c, err = t.setCardAside(person, id, in.Revision, in.Aside) |
| + if err != nil { |
| return err |
| } |
| - var c cardRecord |
| - if err := t.db.Where("id = ? AND person = ? AND "+coordinatorRole, id, person).First(&c).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| - return ErrNotFound |
| - } else if err != nil { |
| - return err |
| + out, err = t.cardView(c) |
| + return err |
| + }) |
| + if errors.Is(err, ErrCardConflict) && c.ID != "" { |
| + if rerr := s.read(ctx, func(tx *gorm.DB) error { |
| + var e error |
| + out, e = (&txn{s: s, ctx: ctx, db: tx}).cardView(c) |
| + return e |
| + }); rerr != nil { |
| + return out, rerr |
| } |
| + } |
| + return out, err |
| +} |
| + |
| +// setCardAside sets the card aside (or back) for its person: the card, and |
| +// ErrCardConflict with it when its revision moved or it no longer waits. |
| +func (t *txn) setCardAside(person, id string, revision int64, aside bool) (c cardRecord, err error) { |
| + s := t.s |
| + ctx := t.ctx |
| + if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| + return c, err |
| + } |
| + if err := t.db.Where("id = ? AND person = ? AND "+coordinatorRole, id, person).First(&c).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| + return c, ErrNotFound |
| + } else if err != nil { |
| + return c, err |
| + } |
| + return c, func() error { |
| if c.Revision != revision { |
| return ErrCardConflict |
| } |
| @@ -97,8 +133,9 @@ func (s *Store) SetCardAside(ctx context.Context, person, id string, revision in |
| if err := s.authority.Audit(t.db, person, "card.visibility", id); err != nil { |
| return err |
| } |
| - return t.cardEvent(c) |
| - }) |
| + // Setting aside is no news to the person's devices: no push rule. |
| + return t.cardEventPush(c, false) |
| + }() |
| } |
| func (s *Store) CardPresentations(ctx context.Context, person string, ids []string) (out map[string]CardPresentation, err error) { |
diff --git a/internal/equipo/chat/store.go b/internal/equipo/chat/store.go| index 069283fd..542092d5 100644 |
| --- a/internal/equipo/chat/store.go |
| +++ b/internal/equipo/chat/store.go |
| @@ -82,6 +82,10 @@ type Authority struct { |
| // AssistantHosts are the origins a person may register as their |
| // Base host (EQUIPO_ASSISTANT_HOSTS), lowercased. |
| AssistantHosts []string |
| + // PushDevice re-checks a device credential of the person's, for a |
| + // push to it: nil while it is still valid (not revoked or expired). |
| + // Unset, nothing pushes. |
| + PushDevice func(tx *gorm.DB, person, credential string) error |
| // Seal and Open keep a secret sealed with the instance key, bound to |
| // domain (a host token). |
| Seal func(domain string, v any) (string, error) |
| @@ -114,6 +118,9 @@ type Store struct { |
| logger atomic.Pointer[slog.Logger] |
| // warm limits how often opening Base warms an Assistant (warm.go). |
| warm warmGate |
| + // pushOn writes the push outbox (SetPush); pushWake wakes its sender. |
| + pushOn atomic.Bool |
| + pushWake chan struct{} |
| } |
| // SetFrameTap sees every frame the instance sends a runner, as sent |
| @@ -124,7 +131,7 @@ func NewStore(d *db.DB, a Authority, hub *Hub) *Store { |
| if hub == nil { |
| hub = NewHub() |
| } |
| - return &Store{db: d, authority: a, hub: hub, now: func() time.Time { return time.Now().UTC() }, process: newID("p"), detectors: housekeeping.Default(), remote: make(chan struct{}, 1)} |
| + return &Store{db: d, authority: a, hub: hub, now: func() time.Time { return time.Now().UTC() }, process: newID("p"), detectors: housekeeping.Default(), remote: make(chan struct{}, 1), pushWake: make(chan struct{}, 1)} |
| } |
| // SetClock replaces the store's clock (tests: the 30-minute offline rule |
| @@ -166,6 +173,9 @@ func (s *Store) tx(ctx context.Context, fn func(*txn) error) error { |
| if t.pending { |
| s.wakeRemote() |
| } |
| + if t.pushed { |
| + s.wakePush() |
| + } |
| return nil |
| } |
| @@ -192,6 +202,8 @@ type txn struct { |
| // live are events for the streams following now, never stored, |
| // published once the transaction commits. |
| live []liveEvent |
| + // pushed: the transaction wrote the push outbox. |
| + pushed bool |
| } |
| func (t *txn) now() time.Time { return t.s.now() } |
| @@ -267,6 +279,9 @@ func (t *txn) saveTurn(r *turnRecord) error { |
| if err := t.turnEvent(*r); err != nil { |
| return err |
| } |
| + if err := t.pushReply(*r); err != nil { |
| + return err |
| + } |
| // Every way a turn ends comes here: a hand-off's Coordinator turn |
| // that ends may leave its hand-off with nothing more to do, and once |
| // the Assistant's team_update turn about a job ends, its card may say |
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go| index 945d6321..887f700c 100644 |
| --- a/internal/equipo/chat/tasks.go |
| +++ b/internal/equipo/chat/tasks.go |
| @@ -702,6 +702,9 @@ func (t *txn) taskEvent(k taskRecord) error { |
| return err |
| } |
| } |
| + if slices.Contains(members, k.Creator) { |
| + return t.pushTask(v) |
| + } |
| return nil |
| } |
diff --git a/internal/equipo/chat_wiring.go b/internal/equipo/chat_wiring.go| index 278cf891..f59bbf75 100644 |
| --- a/internal/equipo/chat_wiring.go |
| +++ b/internal/equipo/chat_wiring.go |
| @@ -12,6 +12,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/equipo/assist" |
| "amadan.net/oficina/equipo/internal/equipo/chat" |
| "amadan.net/oficina/equipo/internal/equipo/personapi" |
| + "amadan.net/oficina/equipo/internal/equipo/push" |
| "amadan.net/oficina/equipo/internal/wire" |
| "gorm.io/gorm" |
| ) |
| @@ -45,6 +46,20 @@ func (s *Store) Chat() *chat.Store { |
| Audit: func(tx *gorm.DB, actor, kind, record string) error { |
| return appendAudit(tx, Actor{Address: actor}, kind, record) |
| }, |
| + // A push goes only to a device credential still valid now; only |
| + // a revoked one (or its person signed out everywhere) is gone. |
| + PushDevice: func(tx *gorm.DB, person, credential string) error { |
| + state, err := s.personDevices().PushState(tx, credential, person) |
| + switch { |
| + case err != nil: |
| + return err |
| + case state == personapi.PushGone: |
| + return push.ErrGone |
| + case state != personapi.PushCurrent: |
| + return push.ErrNotCurrent |
| + } |
| + return nil |
| + }, |
| ActivityLabel: activityLabel, |
| Copy: copyText, |
| Origin: s.chatOrigin, |
diff --git a/internal/equipo/config.go b/internal/equipo/config.go| index 7c6cecdf..6d42d7d4 100644 |
| --- a/internal/equipo/config.go |
| +++ b/internal/equipo/config.go |
| @@ -2,6 +2,7 @@ package equipo |
| import ( |
| "amadan.net/oficina/equipo/internal/equipo/oficina" |
| + "amadan.net/oficina/equipo/internal/equipo/push" |
| "amadan.net/oficina/home/connect" |
| "errors" |
| "net" |
| @@ -20,6 +21,12 @@ type Config struct { |
| InstanceKey string |
| Owners []string |
| AllowLoggedMail bool |
| + // AllowLoggedPush (EQUIPO_ALLOW_LOGGED_PUSH=1) logs pushes instead of |
| + // sending them; like logged mail, only on loopback or staging. |
| + AllowLoggedPush bool |
| + // Push is the push transport, built by Pusher on the serve path only |
| + // (main's run) and set there; nil everywhere else: no outbox, no sender. |
| + Push push.Transport |
| // MailConfigured is true when the platform gave Equipo a way to |
| // send: CARLOS mail submission (CARLOS_MAIL=submit) or SMTP |
| // (CARLOS_SMTP_HOST and CARLOS_SMTP_FROM). Mailer builds the sender. |
| @@ -51,6 +58,7 @@ func LoadConfig(getenv func(string) string) (Config, error) { |
| Origin: strings.TrimSpace(getenv("EQUIPO_ORIGIN")), |
| InstanceKey: strings.TrimSpace(getenv("EQUIPO_INSTANCE_KEY")), |
| AllowLoggedMail: getenv("EQUIPO_ALLOW_LOGGED_MAIL") == "1", |
| + AllowLoggedPush: getenv("EQUIPO_ALLOW_LOGGED_PUSH") == "1", |
| DatabaseName: strings.TrimSpace(getenv("EQUIPO_DATABASE")), |
| } |
| raw := connect.Credentials{Issuer: getenv("EQUIPO_HOME_ISSUER"), ConsumerID: getenv("EQUIPO_HOME_CONSUMER_ID"), KeysBase64: getenv("EQUIPO_HOME_KEYS_BASE64"), DEKBase64: getenv("EQUIPO_HOME_DEK_BASE64")} |
| @@ -138,6 +146,10 @@ func (cfg Config) validate() error { |
| //lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go. |
| return errors.New(copyLoggedMailPublic) |
| } |
| + if cfg.AllowLoggedPush && !local && !stagingMailOrigin.MatchString(cfg.Origin) { |
| + //lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go. |
| + return errors.New(copyLoggedPushPublic) |
| + } |
| if cfg.OficinaConnectOrigin != "" { |
| if _, err := oficina.New(cfg.oficinaConfig(), oficinaStore{}, oficinaSealer{}); err != nil { |
| //lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go. |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index cebf6c70..4c4d45a4 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -23,6 +23,10 @@ const ( |
| copyMissingStage = "The sign-in layout is missing. Check the Rastrillo installation." |
| copyInvalidRoot = "The app handler is missing. Configure the Equipo app before serving." |
| + copyLoggedPushPublic = "Unset EQUIPO_ALLOW_LOGGED_PUSH on a public origin. It is only allowed on loopback or staging." // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) |
| + copyCarlosPushUnavailable = "CARLOS push submission is not available in this version of Equipo. Unset CARLOS_PUSH." // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) |
| + copyPushBoth = "Set EQUIPO_ALLOW_LOGGED_PUSH or CARLOS_PUSH, not both." // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) |
| + |
| copyRunnerPending = "Waiting for you to approve this machine in your browser." |
| copyRunnerRateLimited = "Too many attempts. Wait before trying again." |
| copyBrand = "Equipo" |
| @@ -2023,6 +2027,14 @@ var pageCopy = map[string]string{ |
| "form.last-owner": copyLastOwner, |
| "form.account-label-exists": copyAccountLabelExists, |
| + "push.card.title": "Needs you", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) |
| + "push.card.body": "A decision is waiting for you.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) |
| + "push.reply.title": "Coordinator replied", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) |
| + "push.task.done": "Done.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) |
| + "push.task.cancelled": "Cancelled.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) |
| + "push.task.failed": "A step failed. Open the task to retry the step.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) |
| + "push.activity.started": "Work has started.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) |
| + |
| "nav.account": "Account", |
| "brand": copyBrand, |
| "nav.conversation": "Conversation", |
diff --git a/internal/equipo/invitations.go b/internal/equipo/invitations.go| index 36d998d0..f2ff11f4 100644 |
| --- a/internal/equipo/invitations.go |
| +++ b/internal/equipo/invitations.go |
| @@ -3,6 +3,7 @@ package equipo |
| import ( |
| "context" |
| + "amadan.net/oficina/equipo/internal/equipo/push" |
| "amadan.net/oficina/equipo/internal/equipo/setup" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| "gorm.io/gorm" |
| @@ -24,7 +25,8 @@ func (s *Store) invitationsAt(tx *gorm.DB) *setup.Store { |
| RevokeRunners: func(tx *gorm.DB, address string) error { |
| return revokePersonRunners(tx, address, s.runnerClock.Now().UTC()) |
| }, |
| - Fence: func(tx *gorm.DB) error { return s.fenceAuthority(tx.Statement.Context, tx, 0) }, |
| + ForgetPush: push.ForgetPerson, |
| + Fence: func(tx *gorm.DB) error { return s.fenceAuthority(tx.Statement.Context, tx, 0) }, |
| }) |
| } |
diff --git a/internal/equipo/mailer.go b/internal/equipo/mailer.go| index 09bc0748..48cf6e76 100644 |
| --- a/internal/equipo/mailer.go |
| +++ b/internal/equipo/mailer.go |
| @@ -1,8 +1,10 @@ |
| package equipo |
| import ( |
| + "errors" |
| "log/slog" |
| + "amadan.net/oficina/equipo/internal/equipo/push" |
| "amadan.net/rastrillo/rastrillo/mail" |
| ) |
| @@ -30,3 +32,31 @@ func Mailer(cfg Config, logger *slog.Logger) (mail.Sender, error) { |
| } |
| return mail.FromCarlos("CARLOS", logger) |
| } |
| + |
| +// Pusher builds the push transport. Call it only where Equipo serves |
| +// (main's run), as Mailer: a seed or one-shot has no control socket and |
| +// sends nothing. EQUIPO_ALLOW_LOGGED_PUSH (admitted by LoadConfig on |
| +// loopback or staging only) logs every push; CARLOS_PUSH=submit is the |
| +// CARLOS platform's push submission (push.FromCarlos, a seam until the |
| +// platform verb exists); both refuse boot; neither is no push at all |
| +// (nil, nil). |
| +func Pusher(cfg Config, logger *slog.Logger, getenv func(string) string) (push.Transport, error) { |
| + if cfg.AllowLoggedPush && getenv(push.CarlosPushEnv) != "" { |
| + // Never one silently over the other. |
| + //lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go. |
| + return nil, errors.New(copyPushBoth) |
| + } |
| + if cfg.AllowLoggedPush { |
| + if cfg.validate() != nil { |
| + //lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go. |
| + return nil, errors.New(copyLoggedPushPublic) |
| + } |
| + return push.Logged{Logger: logger}, nil |
| + } |
| + t, err := push.FromCarlos(getenv) |
| + if err != nil { |
| + //lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go. |
| + return nil, errors.New(copyCarlosPushUnavailable) |
| + } |
| + return t, nil |
| +} |
diff --git a/internal/equipo/migrations/0096_push.sql b/internal/equipo/migrations/0096_push.sql| new file mode 100644 |
| index 00000000..4cf9d522 |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0096_push.sql |
| @@ -0,0 +1,19 @@ |
| +-- Push for the native apps (slice 2): each paired device credential's |
| +-- APNs registration, running Live Activities' update tokens, the outbox |
| +-- the engine writes in the transaction of a change, what each person's |
| +-- devices were last told about a task they started, and each once-only |
| +-- push decided for a person. Tokens and payloads are sealed. Cards open |
| +-- before push existed count as alerted: they opened before any device |
| +-- could hear of them. |
| +CREATE TABLE push_registrations (credential text PRIMARY KEY, person text, token text, environment text, platform text, start_token text, created_at datetime, updated_at datetime); |
| +CREATE INDEX push_registration_person ON push_registrations(person); |
| +CREATE TABLE push_activities (credential text, task_id text, person text, token text, created_at datetime, PRIMARY KEY (credential, task_id)); |
| +CREATE INDEX push_activity_person ON push_activities(person); |
| +CREATE TABLE push_outbox (id text PRIMARY KEY, person text, credential text, kind text, target text, task_id text, push_type text, priority integer, collapse_id text, dedupe text, payload text, state text, next_at datetime, attempts integer, lease_until datetime, status integer, reason text, apns_id text, sent_at datetime, created_at datetime, updated_at datetime); |
| +CREATE INDEX push_outbox_due ON push_outbox(state, next_at); |
| +CREATE INDEX push_outbox_dedupe ON push_outbox(dedupe); |
| +CREATE INDEX push_outbox_credential ON push_outbox(credential); |
| +CREATE INDEX push_outbox_person ON push_outbox(person); |
| +CREATE TABLE push_tasks (person text, task_id text, title text, tone text, stage text, needs_you text, specialist text, step_id text, activity text, started_at datetime, ended numeric, line_at datetime, updated_at datetime, PRIMARY KEY (person, task_id)); |
| +CREATE TABLE push_once (person text, key text, created_at datetime, PRIMARY KEY (person, key)); |
| +INSERT INTO push_once (person, key, created_at) SELECT person, 'card:' || id, CURRENT_TIMESTAMP FROM chat_cards WHERE state IN ('open', 'ask'); |
diff --git a/internal/equipo/migrations/0097_push_hold.sql b/internal/equipo/migrations/0097_push_hold.sql| new file mode 100644 |
| index 00000000..35e28cc4 |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0097_push_hold.sql |
| @@ -0,0 +1,2 @@ |
| +-- Keep CARLOS retry deadlines across drains, newly queued pushes and restarts. |
| +CREATE TABLE push_holds (id text PRIMARY KEY, until datetime); |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index 638fb713..ac24d893 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -736,3 +736,17 @@ WHERE CASE WHEN json_valid(entries) THEN json_type(entries) = 'array' ELSE 0 END |
| ALTER TABLE chat_steps ADD COLUMN base_checks text; |
| CREATE TABLE chat_turn_carried (turn_id text, message_id text, person text, PRIMARY KEY (turn_id, message_id)); |
| + |
| +CREATE TABLE push_registrations (credential text PRIMARY KEY, person text, token text, environment text, platform text, start_token text, created_at datetime, updated_at datetime); |
| +CREATE INDEX push_registration_person ON push_registrations(person); |
| +CREATE TABLE push_activities (credential text, task_id text, person text, token text, created_at datetime, PRIMARY KEY (credential, task_id)); |
| +CREATE INDEX push_activity_person ON push_activities(person); |
| +CREATE TABLE push_outbox (id text PRIMARY KEY, person text, credential text, kind text, target text, task_id text, push_type text, priority integer, collapse_id text, dedupe text, payload text, state text, next_at datetime, attempts integer, lease_until datetime, status integer, reason text, apns_id text, sent_at datetime, created_at datetime, updated_at datetime); |
| +CREATE INDEX push_outbox_due ON push_outbox(state, next_at); |
| +CREATE INDEX push_outbox_dedupe ON push_outbox(dedupe); |
| +CREATE INDEX push_outbox_credential ON push_outbox(credential); |
| +CREATE INDEX push_outbox_person ON push_outbox(person); |
| +CREATE TABLE push_tasks (person text, task_id text, title text, tone text, stage text, needs_you text, specialist text, step_id text, activity text, started_at datetime, ended numeric, line_at datetime, updated_at datetime, PRIMARY KEY (person, task_id)); |
| +CREATE TABLE push_once (person text, key text, created_at datetime, PRIMARY KEY (person, key)); |
| +-- Keep CARLOS retry deadlines across drains, newly queued pushes and restarts. |
| +CREATE TABLE push_holds (id text PRIMARY KEY, until datetime); |
diff --git a/internal/equipo/migrations_test.go b/internal/equipo/migrations_test.go| index fca99a26..c50e8796 100644 |
| --- a/internal/equipo/migrations_test.go |
| +++ b/internal/equipo/migrations_test.go |
| @@ -138,3 +138,49 @@ func TestAssistantLaneMigrationKeepsKeys(t *testing.T) { |
| t.Fatal("a second Coordinator message with a historical key") |
| } |
| } |
| + |
| +// Cards already waiting when push arrives opened before any device could |
| +// hear of them: 0096 marks them alerted, so a later write of one (setting |
| +// it aside included) never alerts it late. Others are not marked. |
| +func TestPushMigrationMarksOpenCards(t *testing.T) { |
| + ctx := context.Background() |
| + all := Schema.All() |
| + at := -1 |
| + for i, m := range all { |
| + if m.ID == "equipo/0096_push" { |
| + at = i |
| + } |
| + } |
| + if at < 0 { |
| + t.Fatal("no 0096_push") |
| + } |
| + d, err := migrate.Replay(ctx, all[:at]) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer d.Close() |
| + for id, state := range map[string]string{"c_open": "open", "c_ask": "ask", "c_answered": "answered"} { |
| + if _, err = d.ExecContext(ctx, "INSERT INTO chat_cards(id, person, kind, state, revision) VALUES (?, 'ana@example.com', 'question', ?, 1)", id, state); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if _, err = d.ExecContext(ctx, all[at].SQL); err != nil { |
| + t.Fatal(err) |
| + } |
| + rows, err := d.QueryContext(ctx, "SELECT key FROM push_once WHERE person = 'ana@example.com' ORDER BY key") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer rows.Close() |
| + var keys []string |
| + for rows.Next() { |
| + var k string |
| + if err := rows.Scan(&k); err != nil { |
| + t.Fatal(err) |
| + } |
| + keys = append(keys, k) |
| + } |
| + if strings.Join(keys, " ") != "card:c_ask card:c_open" { |
| + t.Fatalf("marked %v", keys) |
| + } |
| +} |
diff --git a/internal/equipo/person_devices.go b/internal/equipo/person_devices.go| index 2d5320dd..4809d95c 100644 |
| --- a/internal/equipo/person_devices.go |
| +++ b/internal/equipo/person_devices.go |
| @@ -5,6 +5,7 @@ import ( |
| "net/http" |
| "amadan.net/oficina/equipo/internal/equipo/personapi" |
| + "amadan.net/oficina/equipo/internal/equipo/push" |
| ) |
| type PersonDeviceChallenge = personapi.PersonDeviceChallenge |
| @@ -12,7 +13,7 @@ type PersonDeviceProof = personapi.PersonDeviceProof |
| type PersonCredential = personapi.PersonCredential |
| func (s *Store) personDevices() *personapi.DeviceStore { |
| - return &personapi.DeviceStore{Write: s.write, Read: s.invitationRead, Member: memberAt, Instance: runnerInstance, Audit: appendAudit, Key: s.personKey, Origin: s.personOrigin, Now: s.runnerClock.Now, Invalid: ErrInvalid, Forbidden: ErrForbidden, NotFound: ErrNotFound, Conflict: ErrConflict} |
| + return &personapi.DeviceStore{Write: s.write, Read: s.invitationRead, Member: memberAt, Instance: runnerInstance, Audit: appendAudit, Key: s.personKey, Origin: s.personOrigin, Now: s.runnerClock.Now, Revoked: push.ForgetCredential, Invalid: ErrInvalid, Forbidden: ErrForbidden, NotFound: ErrNotFound, Conflict: ErrConflict} |
| } |
| func (s *Store) BeginPersonDevice(ctx context.Context, key, label, request string) (PersonDeviceChallenge, error) { |
| return s.personDevices().Begin(ctx, key, label, request) |
diff --git a/internal/equipo/personapi/devices.go b/internal/equipo/personapi/devices.go| index ff8f610c..09db92ca 100644 |
| --- a/internal/equipo/personapi/devices.go |
| +++ b/internal/equipo/personapi/devices.go |
| @@ -96,6 +96,10 @@ type DeviceStore struct { |
| Key, Origin string |
| Now func() time.Time |
| Invalid, Forbidden, NotFound, Conflict error |
| + |
| + // Revoked runs in the revoking transaction: what else the device |
| + // held goes with it (its push registration). Nil is nothing. |
| + Revoked func(tx *gorm.DB, id string) error |
| } |
| func (s *DeviceStore) mac(domain, value string) string { |
| @@ -466,6 +470,43 @@ func (s *DeviceStore) VerifyAt(tx *gorm.DB, id, token string) (p PersonPrincipal |
| } |
| return PersonPrincipal{Address: row.Person, CredentialID: row.ID, SessionEpoch: row.SessionEpoch}, nil |
| } |
| + |
| +// What PushState says of a device credential, for a push to it. |
| +const ( |
| + PushCurrent = "current" // valid: it takes pushes |
| + PushGone = "gone" // revoked, never exchanged, another person's or instance's, or signed out everywhere: never again |
| + PushExpired = "expired" // its token expired: not now, but its registration stays |
| +) |
| + |
| +// PushState is VerifyAt for a push: it tells a device gone for good from |
| +// one only expired, and an error is a lookup that failed, never either. |
| +func (s *DeviceStore) PushState(tx *gorm.DB, id, person string) (string, error) { |
| + var row DeviceRecord |
| + if e := tx.Where("id=?", id).Take(&row).Error; errors.Is(e, gorm.ErrRecordNotFound) { |
| + return PushGone, nil |
| + } else if e != nil { |
| + return "", e |
| + } |
| + instance, e := s.Instance(tx) |
| + if e != nil { |
| + return "", e |
| + } |
| + if instance != row.InstanceID || row.ExchangedAt == nil || row.RevokedAt != nil || row.Person != person { |
| + return PushGone, nil |
| + } |
| + m, e := s.Member(tx, row.Person) |
| + if e != nil { |
| + return "", e |
| + } |
| + if !m.Active || row.SessionEpoch < m.SessionEpoch { |
| + return PushGone, nil |
| + } |
| + if !s.Now().Before(row.TokenExpiresAt) { |
| + return PushExpired, nil |
| + } |
| + return PushCurrent, nil |
| +} |
| + |
| func (s *DeviceStore) Verify(ctx context.Context, token string) (p PersonPrincipal, err error) { |
| err = s.Write(WithoutRequest(ctx), func(tx *gorm.DB) error { |
| var e error |
| @@ -559,6 +600,11 @@ func (s *DeviceStore) RevokeRevision(ctx context.Context, a kernel.Actor, id str |
| if e := tx.Model(&DeviceRecord{}).Where("id=?", id).Select("revoked_at", "revision", "result_cipher", "begin_cipher").Updates(&r).Error; e != nil { |
| return e |
| } |
| + if s.Revoked != nil { |
| + if e := s.Revoked(tx, id); e != nil { |
| + return e |
| + } |
| + } |
| if e := s.Audit(tx, a, "person_device.revoke", id); e != nil { |
| return e |
| } |
diff --git a/internal/equipo/push/budget_test.go b/internal/equipo/push/budget_test.go| new file mode 100644 |
| index 00000000..2dba09c6 |
| --- /dev/null |
| +++ b/internal/equipo/push/budget_test.go |
| @@ -0,0 +1,9 @@ |
| +package push |
| + |
| +import ( |
| + "amadan.net/rastrillo/rastrillo/budget" |
| + "os" |
| + "testing" |
| +) |
| + |
| +func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } |
diff --git a/internal/equipo/push/outcome_test.go b/internal/equipo/push/outcome_test.go| new file mode 100644 |
| index 00000000..ce2a4b7d |
| --- /dev/null |
| +++ b/internal/equipo/push/outcome_test.go |
| @@ -0,0 +1,388 @@ |
| +package push |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "log" |
| + "regexp" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "gorm.io/gorm" |
| + "gorm.io/gorm/logger" |
| +) |
| + |
| +var uuidShape = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`) |
| + |
| +// TestRowIDIsAnAPNsID: every row's ID, sent as apns-id, is a canonical |
| +// lowercase UUID (Apple answers 400 BadMessageId to anything else). |
| +func TestRowIDIsAnAPNsID(t *testing.T) { |
| + seen := map[string]bool{} |
| + for range 200 { |
| + id := NewID() |
| + if !uuidShape.MatchString(id) || seen[id] { |
| + t.Fatalf("id %q", id) |
| + } |
| + seen[id] = true |
| + } |
| + r := newRig(t) |
| + r.enqueue(KindAlert, TargetDevice, "c1", false) |
| + if id := r.rows()[0].ID; !uuidShape.MatchString(id) { |
| + t.Fatalf("row id %q", id) |
| + } |
| +} |
| + |
| +// TestJudge: what each answer of the CARLOS verb (design §4.2) does to |
| +// its row. |
| +func TestJudge(t *testing.T) { |
| + for name, c := range map[string]struct { |
| + res Result |
| + err error |
| + want Verdict |
| + }{ |
| + "delivered": {Result{Status: 200}, nil, Verdict{Act: ActSent}}, |
| + "no answer": {Result{}, errors.New("reset"), Verdict{Act: ActRetry, Wait: Backoff(3)}}, |
| + "Unregistered": {Result{Status: 410, Reason: ReasonUnregistered}, nil, Verdict{Act: ActGone}}, |
| + "ExpiredToken": {Result{Status: 410, Reason: ReasonExpiredToken}, nil, Verdict{Act: ActGone}}, |
| + "BadDeviceToken": {Result{Status: 400, Reason: ReasonBadDeviceToken}, nil, Verdict{Act: ActGone}}, |
| + "DeviceTokenNotForTopic": {Result{Status: 400, Reason: ReasonDeviceTokenNotForTopic}, nil, Verdict{Act: ActGone}}, |
| + "Apple throttles a device": {Result{Status: 429, Reason: "TooManyRequests"}, nil, Verdict{Act: ActRetry, Wait: Backoff(3), Device: true}}, |
| + "Apple 500": {Result{Status: 500}, nil, Verdict{Act: ActRetry, Wait: 4 * AppleRetry}}, |
| + "Apple 503": {Result{Status: 503}, nil, Verdict{Act: ActRetry, Wait: 4 * AppleRetry}}, |
| + "another Apple 4xx": {Result{Status: 400, Reason: "BadCollapseId"}, nil, Verdict{Act: ActFail}}, |
| + "BAD_REQUEST": {Result{Refused: 400, Code: "BAD_REQUEST"}, nil, Verdict{Act: ActFail}}, |
| + "PAYLOAD_TOO_LARGE": {Result{Refused: 400, Code: "PAYLOAD_TOO_LARGE"}, nil, Verdict{Act: ActFail}}, |
| + "401": {Result{Refused: 401}, nil, Verdict{Act: ActFail}}, |
| + "TOPIC_NOT_ALLOWED": {Result{Refused: 403, Code: "TOPIC_NOT_ALLOWED"}, nil, Verdict{Act: ActFail}}, |
| + "ENVIRONMENT_NOT_ARMED": {Result{Refused: 403, Code: "ENVIRONMENT_NOT_ARMED"}, nil, Verdict{Act: ActFail}}, |
| + "PAUSED": {Result{Refused: 429, Code: "PAUSED", RetryAfter: 300 * time.Second}, nil, Verdict{Act: ActHold, Wait: 300 * time.Second, Stop: true}}, |
| + "RATE": {Result{Refused: 429, Code: "RATE", RetryAfter: time.Second}, nil, Verdict{Act: ActHold, Wait: time.Second, Stop: true}}, |
| + "PUSHER_UNAVAILABLE": {Result{Refused: 503, Code: "PUSHER_UNAVAILABLE", RetryAfter: 5 * time.Second}, nil, Verdict{Act: ActHold, Wait: 5 * time.Second, Stop: true}}, |
| + "APNS_UNAVAILABLE": {Result{Refused: 503, Code: "APNS_UNAVAILABLE", RetryAfter: 60 * time.Second}, nil, Verdict{Act: ActHold, Wait: 60 * time.Second, Stop: true}}, |
| + "a platform 410 is not gone": {Result{Refused: 410, Code: "X"}, nil, Verdict{Act: ActFail}}, |
| + "a platform 503 without a code": {Result{Refused: 503, RetryAfter: 5 * time.Second}, nil, Verdict{Act: ActHold, Wait: 5 * time.Second, Stop: true}}, |
| + } { |
| + if got := Judge(c.res, c.err, 2); got != c.want { |
| + t.Errorf("%s: %+v, want %+v", name, got, c.want) |
| + } |
| + } |
| + if Judge(Result{Status: 500}, nil, 0).Wait != AppleRetry { |
| + t.Fatal("Apple's trouble is retried after 15 minutes first") |
| + } |
| +} |
| + |
| +// carlos answers each send as the CARLOS verb would, through CarlosResult. |
| +func (r *rig) carlos(status int, retryAfter, body string) { |
| + r.answer = func(Message) (Result, error) { return CarlosResult(status, retryAfter, []byte(body)) } |
| +} |
| + |
| +// TestSenderCarlosOutcomes: the sender acts on every CARLOS outcome. A |
| +// platform hold (PAUSED, RATE, PUSHER_UNAVAILABLE, APNS_UNAVAILABLE) |
| +// waits its Retry-After without spending an attempt and ends the pass; |
| +// a refusal fails the row; Apple throttling one device holds its other |
| +// rows; Apple's own trouble waits 15 minutes. |
| +func TestSenderCarlosOutcomes(t *testing.T) { |
| + for code, wait := range map[string]time.Duration{"PAUSED": 300 * time.Second, "RATE": time.Second, "PUSHER_UNAVAILABLE": 5 * time.Second, "APNS_UNAVAILABLE": 60 * time.Second} { |
| + r := newRig(t) |
| + r.enqueue(KindAlert, TargetDevice, "c1", false) |
| + r.enqueue(KindAlert, TargetDevice, "c2", false) |
| + status := 429 |
| + if strings.HasSuffix(code, "UNAVAILABLE") { |
| + status = 503 |
| + } |
| + r.carlos(status, jsonInt(int64(wait/time.Second)), `{"code":"`+code+`"}`) |
| + if r.drain() != 0 || len(r.sent) != 1 { |
| + t.Fatalf("%s: the pass went on after a hold: %d sends", code, len(r.sent)) |
| + } |
| + var row OutboxRecord |
| + r.must(r.d.G.Where("id = ?", r.sent[0].ID).Take(&row).Error) |
| + if row.State != StatePending || row.Attempts != 0 || !row.NextAt.Equal(at.Add(wait)) || row.Reason != code { |
| + t.Fatalf("%s: row %+v", code, row) |
| + } |
| + } |
| + for _, refusal := range []struct { |
| + status int |
| + body string |
| + }{{400, `{"code":"BAD_REQUEST"}`}, {400, `{"code":"PAYLOAD_TOO_LARGE"}`}, {401, "unauthorized\n"}, {403, `{"code":"TOPIC_NOT_ALLOWED"}`}, {403, `{"code":"ENVIRONMENT_NOT_ARMED"}`}} { |
| + r := newRig(t) |
| + r.enqueue(KindAlert, TargetDevice, "c1", false) |
| + r.carlos(refusal.status, "", refusal.body) |
| + r.drain() |
| + var n int64 |
| + r.d.G.Model(&Registration{}).Count(&n) |
| + if row := r.rows()[0]; row.State != StateFailed || n != 1 { |
| + t.Fatalf("%d %s: row %+v, registrations %d", refusal.status, refusal.body, row, n) |
| + } |
| + } |
| + |
| + r := newRig(t) |
| + r.enqueue(KindAlert, TargetDevice, "c1", false) |
| + r.enqueue(KindAlert, TargetDevice, "c2", false) |
| + r.carlos(200, "", `{"status":429,"apns_id":"x","reason":"TooManyRequests"}`) |
| + r.must(r.d.G.Model(&OutboxRecord{}).Where("collapse_id = ?", "c2").Update("next_at", at.Add(time.Second)).Error) |
| + r.drain() |
| + for _, row := range r.rows() { |
| + if row.State != StatePending || row.NextAt.Before(at.Add(Backoff(1))) { |
| + t.Fatalf("Apple throttled the device but %s did not wait: %+v", row.CollapseID, row) |
| + } |
| + } |
| + |
| + r = newRig(t) |
| + r.enqueue(KindAlert, TargetDevice, "c1", false) |
| + r.carlos(200, "", `{"status":503,"apns_id":"x","reason":"ServiceUnavailable"}`) |
| + r.drain() |
| + if row := r.rows()[0]; row.State != StatePending || !row.NextAt.Equal(at.Add(AppleRetry)) || row.Attempts != 1 { |
| + t.Fatalf("Apple 503 %+v", row) |
| + } |
| + |
| + for _, body := range []string{`{"status":410,"apns_id":"x","reason":"ExpiredToken","timestamp":` + jsonInt(at.Add(time.Hour).UnixMilli()) + `}`, `{"status":400,"apns_id":"x","reason":"DeviceTokenNotForTopic"}`} { |
| + r := newRig(t) |
| + r.enqueue(KindAlert, TargetDevice, "c1", false) |
| + r.carlos(200, "", body) |
| + r.drain() |
| + var n int64 |
| + r.d.G.Model(&Registration{}).Count(&n) |
| + if n != 0 { |
| + t.Fatalf("%s kept the registration", body) |
| + } |
| + } |
| + // A 410 whose token Apple last knew before this registration: the |
| + // registration is newer, and stays. |
| + r = newRig(t) |
| + r.enqueue(KindAlert, TargetDevice, "c1", false) |
| + r.carlos(200, "", `{"status":410,"apns_id":"x","reason":"Unregistered","timestamp":`+jsonInt(at.Add(-time.Hour).UnixMilli())+`}`) |
| + r.drain() |
| + var n int64 |
| + r.d.G.Model(&Registration{}).Count(&n) |
| + if n != 1 { |
| + t.Fatal("a registration newer than Apple's 410 was deleted") |
| + } |
| +} |
| + |
| +func jsonInt(n int64) string { b, _ := json.Marshal(n); return string(b) } |
| + |
| +// TestCarlosRequest: a message as the verb takes it (design §4.1): the |
| +// field names, apns_id the row's UUID, expiration in Unix seconds, the |
| +// payload a compact object, and nothing over the limits. |
| +func TestCarlosRequest(t *testing.T) { |
| + m := Message{ID: NewID(), Token: devToken, Environment: wire.APNsProduction, Topic: Topic, PushType: TypeAlert, Priority: 10, CollapseID: "c1", Expiration: at, Payload: []byte("{\n \"aps\": {\"badge\": 3}\n}")} |
| + raw, err := CarlosRequestOf(m) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var got map[string]any |
| + if err := json.Unmarshal(raw, &got); err != nil { |
| + t.Fatal(err) |
| + } |
| + want := map[string]any{"device_token": devToken, "topic": Topic, "push_type": "alert", "priority": float64(10), "collapse_id": "c1", "expiration": float64(at.Unix()), "apns_id": m.ID, "environment": "production", "payload": map[string]any{"aps": map[string]any{"badge": float64(3)}}} |
| + if g, _ := json.Marshal(got); string(g) != func() string { w, _ := json.Marshal(want); return string(w) }() { |
| + t.Fatalf("request %s", raw) |
| + } |
| + if !bytes.Contains(raw, []byte(`"payload":{"aps":{"badge":3}}`)) { |
| + t.Fatalf("payload not compacted: %s", raw) |
| + } |
| + // The limit is on the payload as sent, compacted: spaces do not count. |
| + fits := `{"aps":{"alert":{"body":"` + strings.Repeat("x", MaxPayload-40) + `"}}}` |
| + m.Payload = []byte(strings.ReplaceAll(fits, ":", " : ")) |
| + if raw, err := CarlosRequestOf(m); err != nil || !bytes.Contains(raw, []byte(fits)) { |
| + t.Fatal("a payload that fits once compacted", err) |
| + } |
| + m.Payload = []byte(`{"aps":{"alert":{"body":"` + strings.Repeat("x", MaxPayload) + `"}}}`) |
| + if _, err := CarlosRequestOf(m); !errors.Is(err, ErrTooLarge) { |
| + t.Fatal("an oversized payload", err) |
| + } |
| + m.Payload = []byte(`["not an object"]`) |
| + if _, err := CarlosRequestOf(m); err == nil { |
| + t.Fatal("a payload that is not an object") |
| + } |
| +} |
| + |
| +// TestCarlosResult: the verb's answers read back: Apple's answer on a |
| +// 200 (with a 410's timestamp in milliseconds), the platform's code and |
| +// Retry-After otherwise, a 401's plain text without a code. |
| +func TestCarlosResult(t *testing.T) { |
| + r, err := CarlosResult(200, "", []byte(`{"status":410,"apns_id":"a1","reason":"Unregistered","timestamp":1763683200000}`)) |
| + if err != nil || r.Status != 410 || r.APNsID != "a1" || !r.Timestamp.Equal(time.UnixMilli(1763683200000)) || !r.Apple() || !r.Gone() { |
| + t.Fatalf("Apple's 410 %+v %v", r, err) |
| + } |
| + r, err = CarlosResult(429, "300", []byte(`{"code":"PAUSED"}`)) |
| + if err != nil || r.Refused != 429 || r.Code != "PAUSED" || r.RetryAfter != 300*time.Second || r.Apple() { |
| + t.Fatalf("PAUSED %+v %v", r, err) |
| + } |
| + if r, err = CarlosResult(401, "", []byte("unauthorized")); err != nil || r.Refused != 401 || r.Code != "" || r.Apple() { |
| + t.Fatalf("401 %+v %v", r, err) |
| + } |
| + if _, err := CarlosResult(200, "", []byte("{}")); err == nil { |
| + t.Fatal("a 200 without Apple's answer") |
| + } |
| +} |
| + |
| +// TestSenderCheckOutcomes: only a device gone for good (revoked, its |
| +// person removed) loses its registration; one not current now (expired) |
| +// has the row dropped and stays registered; a failed lookup sends nothing |
| +// and keeps the row for a later pass. |
| +func TestSenderCheckOutcomes(t *testing.T) { |
| + for name, c := range map[string]struct { |
| + err error |
| + state string |
| + regs int64 |
| + }{ |
| + "gone": {ErrGone, StateDropped, 0}, |
| + "expired": {ErrNotCurrent, StateDropped, 1}, |
| + "lookup err": {errors.New("database is locked"), StatePending, 1}, |
| + } { |
| + r := newRig(t) |
| + r.enqueue(KindAlert, TargetDevice, "c1", false) |
| + r.s.Check = func(*gorm.DB, string, string) error { return c.err } |
| + r.drain() |
| + var n int64 |
| + r.d.G.Model(&Registration{}).Count(&n) |
| + if row := r.rows()[0]; len(r.sent) != 0 || row.State != c.state || n != c.regs { |
| + t.Fatalf("%s: sent %d, row %+v, registrations %d", name, len(r.sent), row, n) |
| + } |
| + } |
| +} |
| + |
| +// TestSenderExpiredAndOversized: a row past its expiration is dropped |
| +// unsent; a payload over 4 KB is never sent. |
| +func TestSenderExpiredAndOversized(t *testing.T) { |
| + r := newRig(t) |
| + r.enqueue(KindActivityUpdate, TargetDevice, "", false) |
| + r.now = at.Add(time.Hour) |
| + r.drain() |
| + if row := r.rows()[0]; len(r.sent) != 0 || row.State != StateDropped || row.Reason != "expired" { |
| + t.Fatalf("expired %+v", row) |
| + } |
| + r = newRig(t) |
| + sealed, err := testBox.seal(domainPayload, `{"aps":{"alert":{"body":"`+strings.Repeat("x", MaxPayload)+`"}}}`) |
| + r.must(err) |
| + r.must(r.d.G.Create(&OutboxRecord{ID: NewID(), Person: "p@example.com", Credential: "cr1", Kind: KindAlert, Target: TargetDevice, PushType: TypeAlert, Priority: 10, Payload: sealed, State: StatePending, NextAt: at, CreatedAt: at, UpdatedAt: at}).Error) |
| + r.drain() |
| + if row := r.rows()[0]; len(r.sent) != 0 || row.State != StateFailed || row.Reason != "payload_too_large" { |
| + t.Fatalf("oversized %+v", row) |
| + } |
| + big := Intent{Kind: KindActivityUpdate, TaskID: "tk1", State: &wire.LiveActivityState{TaskID: "tk1", Activity: strings.Repeat("y", MaxPayload)}} |
| + if _, _, err := Render(big, copyStub, 0, at); !errors.Is(err, ErrTooLarge) { |
| + t.Fatal("Render wrote an oversized payload", err) |
| + } |
| + r.must(r.d.G.Transaction(func(tx *gorm.DB) error { |
| + if err := Enqueue(tx, testBox, OutboxRecord{Credential: "cr1", Payload: strings.Repeat("z", MaxPayload+1)}, false); !errors.Is(err, ErrTooLarge) { |
| + t.Error("Enqueue kept an oversized payload", err) |
| + } |
| + return nil |
| + })) |
| +} |
| + |
| +// TestSenderTimeoutAndScrub: a send has the sender's deadline, and a |
| +// transport's error or answer never brings the token into a log or row. |
| +func TestSenderTimeoutAndScrub(t *testing.T) { |
| + r := newRig(t) |
| + r.enqueue(KindAlert, TargetDevice, "c1", false) |
| + r.s.Timeout = 50 * time.Millisecond |
| + var logged []string |
| + r.s.Errorf = func(msg string, args ...any) { |
| + for _, a := range args { |
| + if e, ok := a.(error); ok { |
| + logged = append(logged, e.Error()) |
| + } |
| + } |
| + } |
| + r.s.Transport = transportFunc(func(ctx context.Context, m Message) (Result, error) { |
| + deadline, ok := ctx.Deadline() |
| + if !ok || time.Until(deadline) > 50*time.Millisecond { |
| + t.Error("no send deadline") |
| + } |
| + <-ctx.Done() |
| + return Result{Reason: "dial " + strings.ToUpper(m.Token)}, errors.New("POST https://api.push.apple.com/3/device/" + m.Token + ": " + ctx.Err().Error()) |
| + }) |
| + r.drain() |
| + row := r.rows()[0] |
| + if row.State != StatePending || row.Attempts != 1 || len(logged) != 1 { |
| + t.Fatalf("row %+v, logged %v", row, logged) |
| + } |
| + if strings.Contains(strings.ToLower(logged[0]+row.Reason), devToken) || !strings.Contains(logged[0], "deadline exceeded") { |
| + t.Fatalf("token reached the log or row: %q %q", logged[0], row.Reason) |
| + } |
| +} |
| + |
| +// TestTokensNeverSQLText: registering, keeping an activity token, |
| +// writing a push and sending it never puts a token or a payload's text |
| +// into a statement, as the database's slow and failed query log would |
| +// print it; at rest they are sealed. |
| +func TestTokensNeverSQLText(t *testing.T) { |
| + r := newRig(t) |
| + var sql bytes.Buffer |
| + logged := r.d.G.Session(&gorm.Session{Logger: logger.New(log.New(&sql, "", 0), logger.Config{LogLevel: logger.Info})}) |
| + r.s.Write = func(ctx context.Context, fn func(*gorm.DB) error) error { |
| + return logged.WithContext(ctx).Transaction(fn) |
| + } |
| + const text = "Merge the login fix on main?" |
| + r.must(logged.Transaction(func(tx *gorm.DB) error { |
| + if _, err := Register(tx, testBox, "p@example.com", "cr1", wire.RegisterPush{Token: devToken, Environment: wire.APNsProduction, Platform: wire.PlatformIOS, StartToken: startToken}, at); err != nil { |
| + return err |
| + } |
| + if err := RegisterActivity(tx, testBox, "p@example.com", "cr1", "tk1", actToken, at); err != nil { |
| + return err |
| + } |
| + return Enqueue(tx, testBox, OutboxRecord{Person: "p@example.com", Credential: "cr1", Kind: KindAlert, Target: TargetDevice, PushType: TypeAlert, Priority: 10, Payload: `{"aps":{"alert":{"body":"` + text + `"}}}`, NextAt: at, CreatedAt: at, UpdatedAt: at}, false) |
| + })) |
| + if r.drain() != 1 || string(r.sent[0].Payload) != `{"aps":{"alert":{"body":"`+text+`"}}}` || r.sent[0].Token != devToken { |
| + t.Fatalf("sent %+v", r.sent) |
| + } |
| + for _, secret := range []string{devToken, startToken, actToken, text} { |
| + if strings.Contains(sql.String(), secret) { |
| + t.Fatalf("%q is SQL text", secret) |
| + } |
| + } |
| + if !strings.Contains(sql.String(), "push_outbox") { |
| + t.Fatal("the statements were not captured") |
| + } |
| +} |
| + |
| +// TestRegisterTakesTokens: a token another credential holds (the phone |
| +// signed out offline and paired again) leaves that credential: its |
| +// registration, what waits for it, and its activity tokens holding it. |
| +func TestRegisterTakesTokens(t *testing.T) { |
| + r := newRig(t) |
| + // A token that will not open (sealed under another key) stops nothing. |
| + r.must(r.d.G.Create(&Registration{Credential: "cr_old", Person: "o@example.com", Token: "not sealed here", CreatedAt: at, UpdatedAt: at}).Error) |
| + r.must(r.d.G.Transaction(func(tx *gorm.DB) error { |
| + return RegisterActivity(tx, testBox, "p@example.com", "cr1", "tk1", actToken, at) |
| + })) |
| + r.enqueue(KindAlert, TargetDevice, "c1", false) |
| + r.must(r.d.G.Transaction(func(tx *gorm.DB) error { |
| + _, err := Register(tx, testBox, "q@example.com", "cr2", wire.RegisterPush{Token: startToken, Environment: wire.APNsProduction, Platform: wire.PlatformIOS}, at) |
| + return err |
| + })) |
| + var regs []Registration |
| + r.must(r.d.G.Find(®s).Error) |
| + if len(regs) != 2 || regs[0].Credential != "cr2" && regs[1].Credential != "cr2" || r.rows()[0].State != StateDropped { |
| + t.Fatalf("cr1 kept the token: %+v", regs) |
| + } |
| + for _, reg := range regs { |
| + if reg.Credential == "cr1" { |
| + t.Fatal("cr1 kept the token") |
| + } |
| + } |
| + // cr1 registers again with its own token and keeps an activity's; |
| + // that activity token, registered by cr2, leaves cr1 alone. |
| + r.must(r.d.G.Transaction(func(tx *gorm.DB) error { |
| + if _, err := Register(tx, testBox, "p@example.com", "cr1", wire.RegisterPush{Token: devToken, Environment: wire.APNsProduction, Platform: wire.PlatformIOS}, at); err != nil { |
| + return err |
| + } |
| + return RegisterActivity(tx, testBox, "p@example.com", "cr1", "tk1", actToken, at) |
| + })) |
| + r.must(r.d.G.Transaction(func(tx *gorm.DB) error { |
| + return RegisterActivity(tx, testBox, "q@example.com", "cr2", "tk2", actToken, at) |
| + })) |
| + var acts []ActivityToken |
| + r.must(r.d.G.Find(&acts).Error) |
| + r.must(r.d.G.Find(®s).Error) |
| + if len(acts) != 1 || acts[0].Credential != "cr2" || len(regs) != 3 { |
| + t.Fatalf("activity tokens %+v, registrations %d", acts, len(regs)) |
| + } |
| +} |
diff --git a/internal/equipo/push/payload.go b/internal/equipo/push/payload.go| new file mode 100644 |
| index 00000000..f5de160d |
| --- /dev/null |
| +++ b/internal/equipo/push/payload.go |
| @@ -0,0 +1,116 @@ |
| +package push |
| + |
| +import ( |
| + "encoding/json" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +type alertText struct { |
| + Title string `json:"title"` |
| + Body string `json:"body"` |
| +} |
| + |
| +type aps struct { |
| + Alert *alertText `json:"alert,omitempty"` |
| + Badge *int `json:"badge,omitempty"` |
| + Sound string `json:"sound,omitempty"` |
| + Category string `json:"category,omitempty"` |
| + ThreadID string `json:"thread-id,omitempty"` |
| + InterruptionLevel string `json:"interruption-level,omitempty"` |
| + Timestamp int64 `json:"timestamp,omitempty"` |
| + Event string `json:"event,omitempty"` |
| + ContentState *wire.LiveActivityState `json:"content-state,omitempty"` |
| + AttributesType string `json:"attributes-type,omitempty"` |
| + Attributes *wire.LiveActivityAttributes `json:"attributes,omitempty"` |
| + DismissalDate int64 `json:"dismissal-date,omitempty"` |
| +} |
| + |
| +type payload struct { |
| + APS aps `json:"aps"` |
| + Equipo *wire.PushData `json:"equipo,omitempty"` |
| +} |
| + |
| +// EndShown is how long an ended task's Live Activity stays on the Lock |
| +// Screen; one replaced by a newer task's goes at once. |
| +const EndShown = time.Hour |
| + |
| +// Render is an intent's APNs payload and push type, its words from copy |
| +// (Intent literals first), badge the person's Needs you count for a badge. |
| +func Render(in Intent, copy func(string) string, badge int, now time.Time) ([]byte, string, error) { |
| + text := func(literal, key string) string { |
| + if literal != "" { |
| + return literal |
| + } |
| + if key == "" { |
| + return "" |
| + } |
| + return copy(key) |
| + } |
| + p := payload{} |
| + typ := TypeAlert |
| + switch in.Kind { |
| + case KindAlert, KindPassive: |
| + p.APS.Alert = &alertText{Title: text(in.Title, in.TitleKey), Body: text(in.Body, in.BodyKey)} |
| + p.APS.Category = in.Category |
| + data := in.Data |
| + p.Equipo = &data |
| + if in.Kind == KindPassive { |
| + p.APS.InterruptionLevel = "passive" |
| + } else { |
| + p.APS.Sound = "default" |
| + } |
| + if in.Data.TaskID != "" { |
| + p.APS.ThreadID = "task:" + in.Data.TaskID |
| + } |
| + case KindBadge: |
| + n := badge |
| + p.APS.Badge = &n |
| + case KindActivityStart, KindActivityUpdate, KindActivityEnd: |
| + typ = TypeLiveActivity |
| + p.APS.Timestamp = now.Unix() |
| + p.APS.ContentState = in.State |
| + switch in.Kind { |
| + case KindActivityStart: |
| + p.APS.Event = "start" |
| + p.APS.AttributesType = wire.LiveActivityAttributesType |
| + p.APS.Attributes = &wire.LiveActivityAttributes{TaskID: in.TaskID} |
| + case KindActivityUpdate: |
| + p.APS.Event = "update" |
| + case KindActivityEnd: |
| + p.APS.Event = "end" |
| + p.APS.DismissalDate = now.Add(EndShown).Unix() |
| + if in.State != nil && in.State.Outcome == wire.PushOutcomeReplaced { |
| + p.APS.DismissalDate = now.Unix() |
| + } |
| + } |
| + if title := text(in.Title, in.TitleKey); title != "" { |
| + p.APS.Alert = &alertText{Title: title, Body: text(in.Body, in.BodyKey)} |
| + p.APS.Sound = "default" |
| + } |
| + } |
| + raw, err := json.Marshal(p) |
| + if err == nil && len(raw) > MaxPayload { |
| + return nil, typ, ErrTooLarge |
| + } |
| + return raw, typ, err |
| +} |
| + |
| +// TopicFor is the apns-topic of a push type. |
| +func TopicFor(pushType string) string { |
| + if pushType == TypeLiveActivity { |
| + return Topic + ".push-type.liveactivity" |
| + } |
| + return Topic |
| +} |
| + |
| +// Expiration is how long Apple keeps trying a push of a kind: an alert or |
| +// badge a day, a Live Activity change an hour (a newer one follows). |
| +func Expiration(kind string, created time.Time) time.Time { |
| + switch kind { |
| + case KindActivityStart, KindActivityUpdate, KindActivityEnd: |
| + return created.Add(time.Hour) |
| + } |
| + return created.Add(24 * time.Hour) |
| +} |
diff --git a/internal/equipo/push/payload_test.go b/internal/equipo/push/payload_test.go| new file mode 100644 |
| index 00000000..85c723ca |
| --- /dev/null |
| +++ b/internal/equipo/push/payload_test.go |
| @@ -0,0 +1,108 @@ |
| +package push |
| + |
| +import ( |
| + "bytes" |
| + "encoding/json" |
| + "os" |
| + "path/filepath" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// copyStub stands for copy.go: the key in brackets. |
| +func copyStub(key string) string { return "[" + key + "]" } |
| + |
| +// TestPayloadGoldens holds every kind of push's APNs payload to its |
| +// golden in testdata (EQUIPO_PUSH_GOLDEN=1 rewrites them): the shapes the |
| +// native apps decode. |
| +func TestPayloadGoldens(t *testing.T) { |
| + working := task(wire.StageInProgress, "", true) |
| + working.Activity = "Reading README.md" |
| + ready := task(wire.StageReadyToMerge, wire.NeedsMerge, false) |
| + ready.Tone = wire.ToneWarning |
| + done := task(wire.StageDone, "", false) |
| + pick := func(c Change, rule string) Intent { |
| + for _, in := range Decide(c) { |
| + if in.Rule == rule { |
| + return in |
| + } |
| + } |
| + t.Fatalf("no %s", rule) |
| + return Intent{} |
| + } |
| + cases := map[string]struct { |
| + in Intent |
| + badge int |
| + typ string |
| + }{ |
| + "card": {pick(Change{Kind: ChangeCard, Card: Card{ID: "c1", Kind: wire.CardMerge, State: wire.CardOpen, Question: "Merge the login fix?", TaskID: "tk1"}}, "card_opens"), 0, TypeAlert}, |
| + "reply": {pick(Change{Kind: ChangeReply, Reply: Reply{TurnID: "t1", Kind: wire.TurnPerson, State: wire.TurnReplied, Text: "Done. The fix is on its branch.\nMore."}}, "reply_unseen"), 0, TypeAlert}, |
| + "task-done": {pick(Change{Kind: ChangeTask, Before: seen(ready, true), After: done}, "task_ends"), 0, TypeAlert}, |
| + "task-failed": {pick(Change{Kind: ChangeTask, Before: seen(working, true), After: task(wire.StageInProgress, wire.NeedsRetry, false)}, "task_fails"), 0, TypeAlert}, |
| + "badge": {pick(Change{Kind: ChangeTask, Before: seen(working, true), After: ready}, "badge"), 2, TypeAlert}, |
| + "activity-start": {pick(Change{Kind: ChangeTask, Before: seen(task(wire.StageNoted, "", false), false), After: working}, "activity_start"), 0, TypeLiveActivity}, |
| + "activity-update": {pick(Change{Kind: ChangeLine, Now: at, Before: seen(task(wire.StageInProgress, "", true), true), After: working}, "activity_line"), 0, TypeLiveActivity}, |
| + "activity-needs": {pick(Change{Kind: ChangeTask, Before: seen(working, true), After: ready}, "activity_update"), 0, TypeLiveActivity}, |
| + "activity-end": {pick(Change{Kind: ChangeTask, Before: seen(ready, true), After: done}, "activity_end"), 0, TypeLiveActivity}, |
| + "activity-replaced": {Replace(working), 0, TypeLiveActivity}, |
| + } |
| + for name, c := range cases { |
| + raw, typ, err := Render(c.in, copyStub, c.badge, at) |
| + if err != nil { |
| + t.Fatal(name, err) |
| + } |
| + if typ != c.typ { |
| + t.Errorf("%s: push type %s, want %s", name, typ, c.typ) |
| + } |
| + if len(raw) > 4096 { |
| + t.Errorf("%s: %d bytes, over APNs' 4 KB", name, len(raw)) |
| + } |
| + var pretty bytes.Buffer |
| + if err := json.Indent(&pretty, raw, "", " "); err != nil { |
| + t.Fatal(err) |
| + } |
| + pretty.WriteByte('\n') |
| + path := filepath.Join("testdata", name+".json") |
| + if os.Getenv("EQUIPO_PUSH_GOLDEN") == "1" { |
| + if err := os.WriteFile(path, pretty.Bytes(), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + continue |
| + } |
| + want, err := os.ReadFile(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !bytes.Equal(want, pretty.Bytes()) { |
| + t.Errorf("%s payload differs from its golden:\n%s", name, pretty.String()) |
| + } |
| + } |
| + if TopicFor(TypeLiveActivity) != "works.oficina.equipo.push-type.liveactivity" || TopicFor(TypeAlert) != "works.oficina.equipo" { |
| + t.Fatal("topics") |
| + } |
| +} |
| + |
| +// TestPayloadContentState: a push-to-start carries the task's content |
| +// state and attributes as the app's Codable types decode them. |
| +func TestPayloadContentState(t *testing.T) { |
| + k := task(wire.StageInProgress, "", true) |
| + raw, _, err := Render(Decide(Change{Kind: ChangeTask, Before: seen(task(wire.StageNoted, "", false), false), After: k})[0], copyStub, 0, at) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var p struct { |
| + APS struct { |
| + ContentState wire.LiveActivityState `json:"content-state"` |
| + Attributes wire.LiveActivityAttributes `json:"attributes"` |
| + AttributesType string `json:"attributes-type"` |
| + } `json:"aps"` |
| + } |
| + if err := json.Unmarshal(raw, &p); err != nil { |
| + t.Fatal(err) |
| + } |
| + want := wire.LiveActivityState{TaskID: "tk1", Title: "Fix login", Stage: wire.StageInProgress, Specialist: wire.SpecialistEngineering, NeedsYou: "", Tone: wire.TonePositive} |
| + if p.APS.ContentState != want || p.APS.Attributes.TaskID != "tk1" || p.APS.AttributesType != wire.LiveActivityAttributesType { |
| + t.Fatalf("content state %+v", p.APS) |
| + } |
| +} |
diff --git a/internal/equipo/push/push.go b/internal/equipo/push/push.go| new file mode 100644 |
| index 00000000..a20f6f57 |
| --- /dev/null |
| +++ b/internal/equipo/push/push.go |
| @@ -0,0 +1,169 @@ |
| +// Package push is Equipo's push notifications for the native apps (plan |
| +// 2026-11-20-equipo-native-slice-2.md): device registrations, the outbox |
| +// the conversation engine writes in the transaction of each change, the |
| +// rule table deciding what pushes whom, the APNs payloads, and the sender |
| +// that drains the outbox through a Transport. |
| +// |
| +// Tokens are secrets: they live only in the registration tables and are |
| +// handed to the transport. They are never logged, audited or echoed. |
| +package push |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "time" |
| +) |
| + |
| +// Topic is the apps' bundle ID; a Live Activity's topic adds |
| +// ".push-type.liveactivity". |
| +const Topic = "works.oficina.equipo" |
| + |
| +// Kinds of push, each one outbox row. |
| +const ( |
| + KindAlert = "alert" |
| + KindPassive = "passive" |
| + KindBadge = "badge" |
| + KindActivityStart = "activity_start" |
| + KindActivityUpdate = "activity_update" |
| + KindActivityEnd = "activity_end" |
| +) |
| + |
| +// APNs push types (apns-push-type). |
| +const ( |
| + TypeAlert = "alert" |
| + TypeLiveActivity = "liveactivity" |
| +) |
| + |
| +// Targets: which of a device's tokens a row goes to. |
| +const ( |
| + TargetDevice = "device" // the registration's APNs token |
| + TargetStart = "start" // its Live Activity push-to-start token |
| + TargetActivity = "activity" // a running activity's own update token |
| +) |
| + |
| +// Message is one push as the transport sends it. ID is the outbox row's, |
| +// a canonical lowercase UUID stable across retries: the transport sends it |
| +// as apns-id, so a retried send is the same notification. |
| +type Message struct { |
| + ID string |
| + Token string |
| + Environment string |
| + Topic string |
| + PushType string |
| + Priority int |
| + CollapseID string |
| + Expiration time.Time |
| + Payload []byte |
| +} |
| + |
| +// Result is one send's answer. When Apple answered, Status is Apple's HTTP |
| +// status, Reason the reason it gave on a refusal (BadDeviceToken, |
| +// Unregistered, ...), APNsID the apns-id it answered with and Timestamp, |
| +// on a 410, when it last knew the token valid. When the platform refused |
| +// or could not reach Apple (CARLOS's non-200 answers), Refused is the |
| +// platform's HTTP status, Code its code (PAUSED, RATE, ...), and |
| +// RetryAfter its Retry-After. |
| +type Result struct { |
| + Status int |
| + Reason string |
| + APNsID string |
| + Timestamp time.Time |
| + Refused int |
| + Code string |
| + RetryAfter time.Duration |
| +} |
| + |
| +// Apple's reasons that mean the token is gone for good. |
| +const ( |
| + ReasonUnregistered = "Unregistered" |
| + ReasonExpiredToken = "ExpiredToken" |
| + ReasonBadDeviceToken = "BadDeviceToken" |
| + ReasonDeviceTokenNotForTopic = "DeviceTokenNotForTopic" |
| +) |
| + |
| +// Apple reports whether Apple answered (the platform neither |
| +// refused the push nor failed to reach Apple). |
| +func (r Result) Apple() bool { return r.Refused == 0 && r.Code == "" } |
| + |
| +// Gone reports whether Apple's answer means the token will never work |
| +// again: the registration (or activity token) is deleted. |
| +func (r Result) Gone() bool { |
| + if !r.Apple() { |
| + return false |
| + } |
| + switch r.Reason { |
| + case ReasonUnregistered, ReasonExpiredToken, ReasonBadDeviceToken, ReasonDeviceTokenNotForTopic: |
| + return true |
| + } |
| + return r.Status == 410 |
| +} |
| + |
| +// Transport delivers one push. An error is a delivery that did not reach |
| +// Apple or the platform (retried); a Result is their answer, whatever it |
| +// was. An error's text must never carry the token: the sender scrubs it |
| +// anyway before it is logged. |
| +type Transport interface { |
| + Send(ctx context.Context, m Message) (Result, error) |
| +} |
| + |
| +// ErrNoActivity: an activity update or end with no running activity's |
| +// token on file yet. |
| +var ErrNoActivity = errors.New("push: no activity token") |
| + |
| +// The device checks' answers (Sender.Check, the engine's own): ErrGone, |
| +// the device was revoked or its person removed, so its registration is |
| +// deleted; ErrNotCurrent, it cannot take a push now (its credential |
| +// expired) but stays registered. Any other error is a lookup that failed: |
| +// the row is tried again later. |
| +var ( |
| + ErrGone = errors.New("push: device revoked or person removed") |
| + ErrNotCurrent = errors.New("push: device not current") |
| +) |
| + |
| +// Box seals the tokens and payloads push keeps at rest, with the instance |
| +// key (Authority.Seal and Open), so neither reaches SQL text, and so |
| +// neither reaches the database's slow or failed query log. |
| +type Box struct { |
| + Seal func(domain string, v any) (string, error) |
| + Open func(domain, sealed string, v any) error |
| +} |
| + |
| +// Sealing domains. |
| +const ( |
| + domainToken = "push.token" |
| + domainPayload = "push.payload" |
| +) |
| + |
| +func (b Box) seal(domain, v string) (string, error) { |
| + if v == "" { |
| + return "", nil |
| + } |
| + if b.Seal == nil { |
| + return "", ErrNoBox |
| + } |
| + return b.Seal(domain, v) |
| +} |
| + |
| +func (b Box) open(domain, sealed string) (string, error) { |
| + if sealed == "" { |
| + return "", nil |
| + } |
| + if b.Open == nil { |
| + return "", ErrNoBox |
| + } |
| + var v string |
| + err := b.Open(domain, sealed, &v) |
| + return v, err |
| +} |
| + |
| +// OpenPayload is a row's payload as sent. |
| +func (b Box) OpenPayload(sealed string) (string, error) { return b.open(domainPayload, sealed) } |
| + |
| +// ErrNoBox: push has no instance key to seal with; nothing is kept. |
| +var ErrNoBox = errors.New("push: no sealing") |
| + |
| +// MaxPayload is APNs' (and the CARLOS verb's) limit on a payload, minified. |
| +const MaxPayload = 4096 |
| + |
| +// ErrTooLarge is a payload over MaxPayload: it is never written or sent. |
| +var ErrTooLarge = errors.New("push: payload too large") |
diff --git a/internal/equipo/push/review_test.go b/internal/equipo/push/review_test.go| new file mode 100644 |
| index 00000000..fe66e89c |
| --- /dev/null |
| +++ b/internal/equipo/push/review_test.go |
| @@ -0,0 +1,289 @@ |
| +package push |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "gorm.io/gorm" |
| +) |
| + |
| +func TestSenderInvalidationKeepsNewRegistration(t *testing.T) { |
| + for _, target := range []string{TargetDevice, TargetStart, TargetActivity} { |
| + for _, change := range []string{"rotated400", "rotated410", "renewed410", "unchanged400", "unchanged410", "rotated200", "unchanged200"} { |
| + if strings.HasSuffix(change, "200") && target != TargetActivity { |
| + continue |
| + } |
| + t.Run(target+"/"+change, func(t *testing.T) { |
| + r := newRig(t) |
| + kind := KindAlert |
| + if target == TargetStart { |
| + kind = KindActivityStart |
| + } |
| + if target == TargetActivity { |
| + kind = KindActivityUpdate |
| + if strings.HasSuffix(change, "200") { |
| + kind = KindActivityEnd |
| + } |
| + r.must(RegisterActivity(r.d.G, testBox, "p@example.com", "cr1", "tk1", actToken, r.now)) |
| + } |
| + r.enqueue(kind, target, "", false) |
| + r.answer = func(m Message) (Result, error) { |
| + if !strings.HasPrefix(change, "unchanged") { |
| + token := m.Token |
| + if strings.HasPrefix(change, "rotated") { |
| + token = strings.Repeat("dd", 32) |
| + } |
| + r.must(r.d.G.Transaction(func(tx *gorm.DB) error { |
| + if target == TargetActivity { |
| + return RegisterActivity(tx, testBox, "p@example.com", "cr1", "tk1", token, at.Add(time.Second)) |
| + } |
| + in := wire.RegisterPush{Token: devToken, StartToken: startToken, Platform: wire.PlatformIOS, Environment: wire.APNsDevelopment} |
| + if target == TargetStart { |
| + in.StartToken = token |
| + } else { |
| + in.Token = token |
| + } |
| + _, err := Register(tx, testBox, "p@example.com", "cr1", in, at.Add(time.Second)) |
| + return err |
| + })) |
| + } |
| + if strings.HasSuffix(change, "200") { |
| + return Result{Status: 200}, nil |
| + } |
| + if strings.HasSuffix(change, "400") { |
| + return Result{Status: 400, Reason: "BadDeviceToken"}, nil |
| + } |
| + return Result{Status: 410, Reason: "Unregistered", Timestamp: at}, nil |
| + } |
| + r.drain() |
| + var n int64 |
| + if target == TargetActivity { |
| + r.must(r.d.G.Model(&ActivityToken{}).Count(&n).Error) |
| + } else { |
| + var regs []Registration |
| + r.must(r.d.G.Find(®s).Error) |
| + for _, reg := range regs { |
| + if target == TargetDevice || reg.StartToken != "" { |
| + n++ |
| + } |
| + } |
| + } |
| + want := int64(1) |
| + if strings.HasPrefix(change, "unchanged") { |
| + want = 0 |
| + } |
| + if n != want { |
| + t.Fatalf("registrations = %d, want %d", n, want) |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +func TestSenderQuarantinesUnreadableRows(t *testing.T) { |
| + for _, broken := range []string{"payload", "token"} { |
| + t.Run(broken, func(t *testing.T) { |
| + r := newRig(t) |
| + for i := 0; i < PassSize; i++ { |
| + r.enqueue(KindAlert, TargetDevice, fmt.Sprint(i), false) |
| + } |
| + if broken == "payload" { |
| + r.must(r.d.G.Model(&OutboxRecord{}).Where("1 = 1").Update("payload", "unreadable").Error) |
| + } else { |
| + r.must(r.d.G.Model(&Registration{}).Where("credential = ?", "cr1").Update("token", "unreadable").Error) |
| + } |
| + original := r.s.Box.Open |
| + r.s.Box.Open = func(domain, sealed string, v any) error { |
| + if sealed == "unreadable" { |
| + return errors.New("private token or payload must not escape") |
| + } |
| + return original(domain, sealed, v) |
| + } |
| + var logs []string |
| + r.s.Errorf = func(msg string, args ...any) { logs = append(logs, fmt.Sprint(msg, args)) } |
| + r.drain() |
| + for _, row := range r.rows() { |
| + if row.State != StateFailed || row.Reason != "unreadable_"+broken { |
| + t.Fatalf("unreadable row not quarantined: state=%s reason=%s", row.State, row.Reason) |
| + } |
| + } |
| + if strings.Contains(strings.Join(logs, " "), "private") { |
| + t.Fatal("decryption error leaked") |
| + } |
| + if broken == "token" { |
| + _, err := Register(r.d.G, testBox, "p@example.com", "cr1", wire.RegisterPush{Token: devToken, Platform: wire.PlatformIOS, Environment: wire.APNsDevelopment}, r.now) |
| + r.must(err) |
| + } |
| + r.now = r.now.Add(time.Second) |
| + r.enqueue(KindAlert, TargetDevice, "valid", false) |
| + if r.drain() != 1 { |
| + t.Fatal("valid row starved") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestSenderClaimsCurrentBadge(t *testing.T) { |
| + r := newRig(t) |
| + r.enqueue(KindBadge, TargetDevice, "badge", true) |
| + stale := r.rows()[0] |
| + latest := stale |
| + latest.Payload = `{"aps":{"badge":7}}` |
| + latest.Priority = 5 |
| + r.must(Enqueue(r.d.G, testBox, latest, true)) |
| + _, err := r.s.one(context.Background(), stale) |
| + r.must(err) |
| + if len(r.sent) != 1 || string(r.sent[0].Payload) != latest.Payload || r.sent[0].Priority != 5 { |
| + t.Fatal("sent stale coalesced badge") |
| + } |
| +} |
| + |
| +func TestSenderEndWaitsForDelayedStart(t *testing.T) { |
| + r := newRig(t) |
| + r.enqueue(KindActivityStart, TargetStart, "start", false) |
| + r.answer = func(Message) (Result, error) { return Result{Status: 503}, nil } |
| + r.drain() |
| + r.now = r.now.Add(time.Second) |
| + r.enqueue(KindActivityEnd, TargetActivity, "end", false) |
| + for r.now.Before(at.Add(AppleRetry)) { |
| + r.drain() |
| + var end OutboxRecord |
| + r.must(r.d.G.Where("kind = ?", KindActivityEnd).Take(&end).Error) |
| + if end.State != StatePending { |
| + t.Fatal("end abandoned before delayed start") |
| + } |
| + r.now = end.NextAt |
| + if r.now.After(at.Add(AppleRetry)) { |
| + r.now = at.Add(AppleRetry) |
| + } |
| + } |
| + r.now = at.Add(AppleRetry) |
| + r.answer = func(Message) (Result, error) { return Result{Status: 200}, nil } |
| + r.drain() |
| + r.must(RegisterActivity(r.d.G, testBox, "p@example.com", "cr1", "tk1", actToken, r.now)) |
| + r.must(Hurry(r.d.G, "cr1", "tk1", r.now)) |
| + if r.drain() != 1 { |
| + t.Fatal("late activity was not ended") |
| + } |
| +} |
| + |
| +func TestSenderThrottlesAlreadyReadBatch(t *testing.T) { |
| + r := newRig(t) |
| + for i := 0; i < 3; i++ { |
| + r.enqueue(KindAlert, TargetDevice, fmt.Sprint(i), false) |
| + } |
| + r.answer = func(Message) (Result, error) { return Result{Status: 429, Reason: "TooManyRequests"}, nil } |
| + r.drain() |
| + if len(r.sent) != 1 { |
| + t.Fatalf("sent %d rows through token throttle", len(r.sent)) |
| + } |
| + r.drain() |
| + if len(r.sent) != 1 { |
| + t.Fatal("next drain ignored token throttle") |
| + } |
| + r.now = r.now.Add(FirstRetry) |
| + r.answer = func(Message) (Result, error) { return Result{Status: 200}, nil } |
| + if r.drain() != 3 { |
| + t.Fatal("throttle did not expire") |
| + } |
| +} |
| + |
| +func TestSenderPlatformHoldAcrossDrains(t *testing.T) { |
| + for _, code := range []string{"PAUSED", "RATE", "PUSHER_UNAVAILABLE", "APNS_UNAVAILABLE"} { |
| + t.Run(code, func(t *testing.T) { |
| + r := newRig(t) |
| + r.enqueue(KindAlert, TargetDevice, "first", false) |
| + r.answer = func(Message) (Result, error) { |
| + return Result{Refused: 503, Code: code, RetryAfter: 300 * time.Second}, nil |
| + } |
| + r.drain() |
| + r.enqueue(KindBadge, TargetDevice, "new", false) |
| + // A fresh sender must observe the same persisted platform hold. |
| + old := r.s |
| + r.s = &Sender{Write: old.Write, Transport: old.Transport, Check: old.Check, Box: old.Box, Now: old.Now} |
| + r.now = at.Add(299 * time.Second) |
| + r.drain() |
| + if len(r.sent) != 1 { |
| + t.Fatal("platform hold forgotten across drains") |
| + } |
| + r.now = at.Add(300 * time.Second) |
| + r.answer = func(Message) (Result, error) { return Result{Status: 200}, nil } |
| + if r.drain() != 2 { |
| + t.Fatal("platform hold did not expire") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestActivityTokenDoesNotHurryDelayedStart(t *testing.T) { |
| + r := newRig(t) |
| + r.enqueue(KindActivityStart, TargetStart, "start", false) |
| + r.answer = func(Message) (Result, error) { return Result{Status: 503}, nil } |
| + r.drain() |
| + r.enqueue(KindActivityEnd, TargetActivity, "end", false) |
| + r.must(Hurry(r.d.G, "cr1", "tk1", r.now)) |
| + var start OutboxRecord |
| + r.must(r.d.G.Where("kind = ?", KindActivityStart).Take(&start).Error) |
| + if !start.NextAt.Equal(at.Add(AppleRetry)) { |
| + t.Fatal("token arrival bypassed Apple's retry delay") |
| + } |
| +} |
| + |
| +func TestSenderLastAttemptStillThrottlesBatch(t *testing.T) { |
| + r := newRig(t) |
| + r.enqueue(KindAlert, TargetDevice, "first", false) |
| + r.must(r.d.G.Model(&OutboxRecord{}).Where("1 = 1").Update("attempts", MaxAttempts-1).Error) |
| + r.now = r.now.Add(time.Second) |
| + r.enqueue(KindAlert, TargetDevice, "second", false) |
| + r.answer = func(Message) (Result, error) { return Result{Status: 429}, nil } |
| + r.drain() |
| + if len(r.sent) != 1 { |
| + t.Fatal("exhausted row bypassed device throttle") |
| + } |
| +} |
| + |
| +func TestSenderMissingTokenWaitIsBounded(t *testing.T) { |
| + r := newRig(t) |
| + r.enqueue(KindActivityEnd, TargetActivity, "end", false) |
| + r.drain() |
| + if r.rows()[0].Attempts != 0 { |
| + t.Fatal("missing token spent a delivery attempt") |
| + } |
| + r.now = Expiration(KindActivityEnd, at).Add(-time.Second) |
| + r.drain() |
| + if r.rows()[0].State != StatePending { |
| + t.Fatal("end abandoned inside its lifetime") |
| + } |
| + r.now = Expiration(KindActivityEnd, at) |
| + r.drain() |
| + if r.rows()[0].State != StateDropped { |
| + t.Fatal("missing token waited beyond expiry") |
| + } |
| +} |
| + |
| +func TestSenderPlatformHoldLookupFailsClosed(t *testing.T) { |
| + r := newRig(t) |
| + r.enqueue(KindAlert, TargetDevice, "one", false) |
| + r.must(r.d.G.Migrator().DropTable(&HoldRecord{})) |
| + r.drain() |
| + if len(r.sent) != 0 || r.rows()[0].State != StatePending { |
| + t.Fatal("unknown platform hold treated as ready") |
| + } |
| +} |
| + |
| +func TestSenderPlatformHoldCannotBeShortened(t *testing.T) { |
| + r := newRig(t) |
| + r.must(holdPlatform(r.d.G, at.Add(300*time.Second))) |
| + r.must(holdPlatform(r.d.G, at.Add(time.Second))) |
| + r.enqueue(KindAlert, TargetDevice, "one", false) |
| + r.now = at.Add(2 * time.Second) |
| + r.drain() |
| + if len(r.sent) != 0 { |
| + t.Fatal("shorter overlapping response released platform hold") |
| + } |
| +} |
diff --git a/internal/equipo/push/rules.go b/internal/equipo/push/rules.go| new file mode 100644 |
| index 00000000..34703b24 |
| --- /dev/null |
| +++ b/internal/equipo/push/rules.go |
| @@ -0,0 +1,283 @@ |
| +package push |
| + |
| +import ( |
| + "strings" |
| + "time" |
| + "unicode/utf8" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// Changes the engine reports, each from the transaction that made it. |
| +const ( |
| + ChangeCard = "card" // a card was written (cardEvent) |
| + ChangeReply = "reply" // a turn was saved (saveTurn) |
| + ChangeTask = "task" // a task was written (taskEvent) |
| + ChangeLine = "line" // a running step reported an activity line |
| +) |
| + |
| +// Change is one engine change, as the rules read it. Only the fields of |
| +// its kind are set. |
| +type Change struct { |
| + Kind string |
| + Now time.Time |
| + Card Card |
| + // Reply is a saved turn; Streaming whether the person has an /events |
| + // stream open now. |
| + Reply Reply |
| + Streaming bool |
| + // Before is what the person's push memory held for the task; After the |
| + // task now. A line change carries the new line in After.Activity. |
| + Before Memory |
| + After Task |
| +} |
| + |
| +// Card is a card as the rules read it. It alerts once in its life: its |
| +// alert's once-only key (Dedupe) is decided once for the person. |
| +type Card struct { |
| + ID, Kind, State, Lane, Question, TaskID string |
| + // AccessFinal: an access card whose request already ended. |
| + AccessFinal bool |
| +} |
| + |
| +// Reply is a saved turn and its reply's text. |
| +type Reply struct { |
| + TurnID, Lane, Kind, State, Text string |
| +} |
| + |
| +// Task is a task the person started, as a Live Activity shows it. |
| +type Task struct { |
| + ID, Title, Stage, NeedsYou, Specialist, StepID, Activity, Tone string |
| + // Working: a step of it is running on a runner (it was dispatched). |
| + Working bool |
| +} |
| + |
| +// Final reports whether the task ended. |
| +func (k Task) Final() bool { return wire.FinalStage(k.Stage) } |
| + |
| +// Memory is what the person's devices were last told about a task. |
| +type Memory struct { |
| + Seen bool |
| + Title, Tone, Stage, NeedsYou, Specialist, StepID, Activity string |
| + // Started is when its Live Activity started; Ended once it ended. |
| + Started *time.Time |
| + Ended bool |
| + // LineAt is when an activity line last updated the Live Activity. |
| + LineAt *time.Time |
| +} |
| + |
| +// Task is the task as the memory last showed it. |
| +func (m Memory) Task(id string) Task { |
| + return Task{ID: id, Title: m.Title, Tone: m.Tone, Stage: m.Stage, NeedsYou: m.NeedsYou, Specialist: m.Specialist, StepID: m.StepID, Activity: m.Activity} |
| +} |
| + |
| +// Remember is the memory after the devices were told about k. |
| +func (m Memory) Remember(k Task) Memory { |
| + m.Seen, m.Title, m.Tone, m.Stage, m.NeedsYou, m.Specialist, m.StepID, m.Activity = true, k.Title, k.Tone, k.Stage, k.NeedsYou, k.Specialist, k.StepID, k.Activity |
| + return m |
| +} |
| + |
| +// Live reports whether the task's Live Activity is running. |
| +func (m Memory) Live() bool { return m.Started != nil && !m.Ended } |
| + |
| +// Intent is one push a rule asks for: its kind, priority and collapse ID, |
| +// a once-only key (Dedupe: the push is decided once for the person, ever) |
| +// or Coalesce (a newer one replaces one not yet |
| +// sent), its words (literal Title and Body, else copy keys), where a tap |
| +// goes (Data), and a Live Activity's state. |
| +type Intent struct { |
| + Rule string |
| + Kind string |
| + Priority int |
| + CollapseID string |
| + Dedupe string |
| + Coalesce bool |
| + Title string |
| + TitleKey string |
| + Body string |
| + BodyKey string |
| + Category string |
| + Data wire.PushData |
| + State *wire.LiveActivityState |
| + // TaskID names the task a Live Activity push follows. |
| + TaskID string |
| +} |
| + |
| +// LineEvery is how often an activity line may update a Live Activity, to |
| +// stay inside Apple's update budget. |
| +const LineEvery = time.Minute |
| + |
| +// CategoryNeedsYou is the alert category whose only action is Open (D4). |
| +const CategoryNeedsYou = "needs_you" |
| + |
| +// Rule is one row of the table: when it applies to a change, and the push. |
| +type Rule struct { |
| + Name string |
| + When func(Change) bool |
| + Push func(Change) Intent |
| +} |
| + |
| +// Rules is the table: every rule that applies to a change pushes. |
| +var Rules = []Rule{ |
| + // A card that waits on the person opens: an alert, collapsed by card. |
| + {"card_opens", func(c Change) bool { |
| + return c.Kind == ChangeCard && c.Card.Lane == wire.LaneCoordinator && waits(c.Card) |
| + }, func(c Change) Intent { |
| + in := Intent{Kind: KindAlert, Priority: 10, CollapseID: c.Card.ID, Dedupe: "card:" + c.Card.ID, TitleKey: "push.card.title", Body: Clip(c.Card.Question), Category: CategoryNeedsYou, Data: wire.PushData{Kind: wire.PushCard, CardID: c.Card.ID, TaskID: c.Card.TaskID}} |
| + if in.Body == "" { |
| + in.BodyKey = "push.card.body" |
| + } |
| + return in |
| + }}, |
| + // The coordinator replied to the person while no stream is open: an |
| + // alert with the reply's first line (D2). |
| + {"reply_unseen", func(c Change) bool { |
| + r := c.Reply |
| + return c.Kind == ChangeReply && r.Lane == wire.LaneCoordinator && r.Kind == wire.TurnPerson && r.State == wire.TurnReplied && !c.Streaming && FirstLine(r.Text) != "" |
| + }, func(c Change) Intent { |
| + return Intent{Kind: KindAlert, Priority: 10, CollapseID: "reply:" + c.Reply.TurnID, Dedupe: "reply:" + c.Reply.TurnID, TitleKey: "push.reply.title", Body: FirstLine(c.Reply.Text), Data: wire.PushData{Kind: wire.PushReply, TurnID: c.Reply.TurnID}} |
| + }}, |
| + // A task the person started ends: a passive alert with its outcome. |
| + {"task_ends", func(c Change) bool { |
| + return c.Kind == ChangeTask && c.Before.Seen && c.After.Final() && !wire.FinalStage(c.Before.Stage) |
| + }, func(c Change) Intent { |
| + in := taskAlert(c, outcome(c.After)) |
| + in.Dedupe = "outcome:" + c.After.ID + ":" + outcome(c.After) |
| + return in |
| + }}, |
| + // A step of it failed (it waits for Retry): a passive alert too. |
| + {"task_fails", func(c Change) bool { |
| + return c.Kind == ChangeTask && c.Before.Seen && !c.After.Final() && c.After.NeedsYou == wire.NeedsRetry && c.Before.NeedsYou != wire.NeedsRetry |
| + }, func(c Change) Intent { |
| + return taskAlert(c, wire.PushOutcomeFailed) |
| + }}, |
| + // Needs you changed: the badge, the newest count replacing any unsent. |
| + {"badge", func(c Change) bool { |
| + return c.Kind == ChangeTask && c.Before.Seen && c.Before.NeedsYou != c.After.NeedsYou |
| + }, func(c Change) Intent { |
| + return Badge() |
| + }}, |
| + // It was dispatched: its Live Activity starts, by push-to-start. |
| + {"activity_start", func(c Change) bool { |
| + return c.Kind == ChangeTask && c.After.Working && !c.After.Final() && c.Before.Started == nil |
| + }, func(c Change) Intent { |
| + return Intent{Kind: KindActivityStart, Priority: 10, TaskID: c.After.ID, Title: Clip(c.After.Title), BodyKey: "push.activity.started", State: state(c.After, "")} |
| + }}, |
| + // Its stage, step or needs-you changed: an update, urgent when it now |
| + // needs the person. Never with an alert: what needs the person sounds |
| + // once, by its card's alert (or a failed step's passive one), not |
| + // again on the Lock Screen's activity. |
| + {"activity_update", func(c Change) bool { |
| + b, a := c.Before, c.After |
| + return c.Kind == ChangeTask && b.Live() && !a.Final() && (b.Stage != a.Stage || b.StepID != a.StepID || b.Specialist != a.Specialist || b.NeedsYou != a.NeedsYou) |
| + }, func(c Change) Intent { |
| + in := Intent{Kind: KindActivityUpdate, Priority: 5, TaskID: c.After.ID, State: state(c.After, "")} |
| + if c.After.NeedsYou != "" && c.After.NeedsYou != c.Before.NeedsYou { |
| + in.Priority = 10 |
| + } |
| + return in |
| + }}, |
| + // A new activity line: an update at most once a minute a task. |
| + {"activity_line", func(c Change) bool { |
| + b := c.Before |
| + return c.Kind == ChangeLine && b.Live() && c.After.Activity != b.Activity && (b.LineAt == nil || c.Now.Sub(*b.LineAt) >= LineEvery) |
| + }, func(c Change) Intent { |
| + return Intent{Kind: KindActivityUpdate, Priority: 5, TaskID: c.After.ID, State: state(c.After, "")} |
| + }}, |
| + // It ended: the Live Activity ends with the outcome. |
| + {"activity_end", func(c Change) bool { |
| + return c.Kind == ChangeTask && c.Before.Live() && c.After.Final() |
| + }, func(c Change) Intent { |
| + return Intent{Kind: KindActivityEnd, Priority: 10, TaskID: c.After.ID, State: state(c.After, outcome(c.After))} |
| + }}, |
| +} |
| + |
| +// Decide is every push the table asks for a change, in table order. |
| +func Decide(c Change) []Intent { |
| + var out []Intent |
| + for _, r := range Rules { |
| + if r.When(c) { |
| + in := r.Push(c) |
| + in.Rule = r.Name |
| + out = append(out, in) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// Badge is the person's Needs you count, the newest replacing any unsent. |
| +func Badge() Intent { |
| + return Intent{Rule: "badge", Kind: KindBadge, Priority: 5, CollapseID: "badge", Coalesce: true, Data: wire.PushData{Kind: wire.PushBadge}} |
| +} |
| + |
| +// CatchUp is a running activity's whole state, sent when its own token |
| +// arrives: what it missed while the server had no token for it. |
| +func CatchUp(k Task) Intent { |
| + return Intent{Rule: "activity_token", Kind: KindActivityUpdate, Priority: 10, TaskID: k.ID, State: state(k, "")} |
| +} |
| + |
| +// Replace ends the Live Activity of a task to make room for a newer one. |
| +func Replace(k Task) Intent { |
| + return Intent{Rule: "activity_cap", Kind: KindActivityEnd, Priority: 5, TaskID: k.ID, State: state(k, wire.PushOutcomeReplaced)} |
| +} |
| + |
| +// waits reports whether a card waits on its person: open (or asking), not |
| +// a receipt, and not an access request that already ended. |
| +func waits(c Card) bool { |
| + if c.State != wire.CardOpen && c.State != wire.CardHomeAsk { |
| + return false |
| + } |
| + switch c.Kind { |
| + case wire.CardProject, wire.CardTask, wire.CardCombined, wire.CardHousekeeping, wire.CardDigest, wire.CardMergeReceipt: |
| + return false |
| + case wire.CardHome: |
| + return c.State == wire.CardHomeAsk |
| + case wire.CardAccess: |
| + return !c.AccessFinal |
| + } |
| + return true |
| +} |
| + |
| +func taskAlert(c Change, outcome string) Intent { |
| + return Intent{Kind: KindPassive, Priority: 5, CollapseID: "task:" + c.After.ID, Title: Clip(c.After.Title), BodyKey: "push.task." + outcome, Data: wire.PushData{Kind: wire.PushTask, TaskID: c.After.ID}} |
| +} |
| + |
| +func outcome(k Task) string { |
| + if k.Stage == wire.StageDone { |
| + return wire.PushOutcomeDone |
| + } |
| + return wire.PushOutcomeCancelled |
| +} |
| + |
| +func state(k Task, outcome string) *wire.LiveActivityState { |
| + return &wire.LiveActivityState{TaskID: k.ID, Title: Clip(k.Title), Stage: k.Stage, Specialist: k.Specialist, Activity: k.Activity, NeedsYou: k.NeedsYou, Tone: k.Tone, Outcome: outcome} |
| +} |
| + |
| +// MaxText bounds an alert's title or body, so a payload stays well under |
| +// APNs' 4 KB. |
| +const MaxText = 178 |
| + |
| +// Clip trims s to MaxText runes, with an ellipsis when it cut. |
| +func Clip(s string) string { |
| + s = strings.TrimSpace(s) |
| + if utf8.RuneCountInString(s) <= MaxText { |
| + return s |
| + } |
| + r := []rune(s) |
| + return strings.TrimSpace(string(r[:MaxText-1])) + "…" |
| +} |
| + |
| +// FirstLine is a reply's first line with text, as plain words: leading |
| +// heading and list marks and emphasis stars dropped, clipped. |
| +func FirstLine(s string) string { |
| + for line := range strings.SplitSeq(s, "\n") { |
| + line = strings.TrimSpace(line) |
| + line = strings.TrimLeft(line, "#>-*+ ") |
| + line = strings.ReplaceAll(line, "**", "") |
| + line = strings.ReplaceAll(line, "`", "") |
| + if line = strings.TrimSpace(line); line != "" { |
| + return Clip(line) |
| + } |
| + } |
| + return "" |
| +} |
diff --git a/internal/equipo/push/rules_test.go b/internal/equipo/push/rules_test.go| new file mode 100644 |
| index 00000000..f389eb68 |
| --- /dev/null |
| +++ b/internal/equipo/push/rules_test.go |
| @@ -0,0 +1,201 @@ |
| +package push |
| + |
| +import ( |
| + "slices" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +var at = time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC) |
| + |
| +func rules(c Change) []string { |
| + var out []string |
| + for _, in := range Decide(c) { |
| + out = append(out, in.Rule) |
| + } |
| + return out |
| +} |
| + |
| +func only(t *testing.T, c Change, want ...string) []Intent { |
| + t.Helper() |
| + if got := rules(c); !slices.Equal(got, want) { |
| + t.Fatalf("rules %v, want %v", got, want) |
| + } |
| + return Decide(c) |
| +} |
| + |
| +func started() *time.Time { s := at.Add(-time.Hour); return &s } |
| + |
| +// TestRuleCardOpens: a card that waits on the person alerts once, by its |
| +// card, urgently, with its question (its key decided once for the |
| +// person); receipts, other lanes, ended access requests and answered |
| +// cards do not. |
| +func TestRuleCardOpens(t *testing.T) { |
| + open := Card{ID: "c1", Kind: wire.CardMerge, State: wire.CardOpen, Question: "Merge the login fix?", TaskID: "tk1"} |
| + in := only(t, Change{Kind: ChangeCard, Card: open}, "card_opens")[0] |
| + if in.Kind != KindAlert || in.Priority != 10 || in.CollapseID != "c1" || in.Dedupe != "card:c1" || in.Body != "Merge the login fix?" || in.TitleKey != "push.card.title" || in.Category != CategoryNeedsYou { |
| + t.Fatalf("card alert %+v", in) |
| + } |
| + if in.Data != (wire.PushData{Kind: wire.PushCard, CardID: "c1", TaskID: "tk1"}) { |
| + t.Fatalf("tap data %+v", in.Data) |
| + } |
| + noQuestion := open |
| + noQuestion.Question = "" |
| + if in := only(t, Change{Kind: ChangeCard, Card: noQuestion}, "card_opens")[0]; in.Body != "" || in.BodyKey != "push.card.body" { |
| + t.Fatalf("no question %+v", in) |
| + } |
| + ask := Card{ID: "c2", Kind: wire.CardHome, State: wire.CardHomeAsk} |
| + only(t, Change{Kind: ChangeCard, Card: ask}, "card_opens") |
| + for name, c := range map[string]Card{ |
| + "answered": {ID: "c", Kind: wire.CardMerge, State: wire.CardAnswered}, |
| + "receipt": {ID: "c", Kind: wire.CardTask, State: wire.CardOpen}, |
| + "project": {ID: "c", Kind: wire.CardProject, State: wire.CardOpen}, |
| + "home set": {ID: "c", Kind: wire.CardHome, State: wire.CardHomeSet}, |
| + "assistant": {ID: "c", Kind: wire.CardMerge, State: wire.CardOpen, Lane: wire.LaneAssistant}, |
| + "job thread": {ID: "c", Kind: wire.CardMerge, State: wire.CardOpen, Lane: wire.JobLane("h1")}, |
| + "access done": {ID: "c", Kind: wire.CardAccess, State: wire.CardOpen, AccessFinal: true}, |
| + } { |
| + if got := rules(Change{Kind: ChangeCard, Card: c}); len(got) != 0 { |
| + t.Errorf("%s pushed %v", name, got) |
| + } |
| + } |
| +} |
| + |
| +// TestRuleReplyUnseen: a finished reply to the person's message alerts |
| +// with its first line only when no stream is open. |
| +func TestRuleReplyUnseen(t *testing.T) { |
| + r := Reply{TurnID: "t1", Kind: wire.TurnPerson, State: wire.TurnReplied, Text: "\n## **Done.** The fix is on its branch.\nMore detail here."} |
| + in := only(t, Change{Kind: ChangeReply, Reply: r}, "reply_unseen")[0] |
| + if in.Body != "Done. The fix is on its branch." || in.CollapseID != "reply:t1" || in.Dedupe != "reply:t1" || in.Priority != 10 || in.Data.TurnID != "t1" { |
| + t.Fatalf("reply alert %+v", in) |
| + } |
| + if got := rules(Change{Kind: ChangeReply, Reply: r, Streaming: true}); len(got) != 0 { |
| + t.Fatalf("an open stream still pushed %v", got) |
| + } |
| + for name, mod := range map[string]func(*Reply){ |
| + "move in": func(r *Reply) { r.Kind = wire.TurnMoveIn }, |
| + "failed": func(r *Reply) { r.State = wire.TurnFailed }, |
| + "running": func(r *Reply) { r.State = wire.TurnRunning }, |
| + "assistant": func(r *Reply) { r.Lane = wire.LaneAssistant }, |
| + "empty": func(r *Reply) { r.Text = " \n " }, |
| + } { |
| + c := r |
| + mod(&c) |
| + if got := rules(Change{Kind: ChangeReply, Reply: c}); len(got) != 0 { |
| + t.Errorf("%s pushed %v", name, got) |
| + } |
| + } |
| + if long := FirstLine(strings.Repeat("word ", 100)); len([]rune(long)) != MaxText || !strings.HasSuffix(long, "…") { |
| + t.Fatalf("not clipped: %d", len([]rune(long))) |
| + } |
| +} |
| + |
| +func task(stage, needs string, working bool) Task { |
| + return Task{ID: "tk1", Title: "Fix login", Stage: stage, NeedsYou: needs, Specialist: wire.SpecialistEngineering, StepID: "s1", Working: working, Tone: wire.TonePositive} |
| +} |
| + |
| +func seen(k Task, live bool) Memory { |
| + m := Memory{}.Remember(k) |
| + if live { |
| + m.Started = started() |
| + } |
| + return m |
| +} |
| + |
| +// TestRuleTaskLifecycle walks a task the person started: dispatch starts |
| +// its Live Activity, a stage change updates it at priority 5, needing the |
| +// person updates it at 10 with an alert and the badge, failing alerts |
| +// passively, and the end alerts and ends the activity with the outcome. |
| +func TestRuleTaskLifecycle(t *testing.T) { |
| + noted := task(wire.StageNoted, "", false) |
| + // Recorded, nothing running: no push yet (no memory: first sighting). |
| + only(t, Change{Kind: ChangeTask, After: noted}) |
| + only(t, Change{Kind: ChangeTask, Before: seen(noted, false), After: noted}) |
| + |
| + working := task(wire.StageInProgress, "", true) |
| + in := only(t, Change{Kind: ChangeTask, Before: seen(noted, false), After: working}, "activity_start")[0] |
| + if in.Kind != KindActivityStart || in.Priority != 10 || in.TaskID != "tk1" || in.State == nil || in.State.Stage != wire.StageInProgress || in.Title != "Fix login" { |
| + t.Fatalf("start %+v", in) |
| + } |
| + // Already started: no second start. |
| + only(t, Change{Kind: ChangeTask, Before: seen(working, true), After: working}) |
| + |
| + review := task(wire.StageInReview, "", true) |
| + review.Specialist, review.StepID = wire.SpecialistReview, "s2" |
| + if in := only(t, Change{Kind: ChangeTask, Before: seen(working, true), After: review}, "activity_update")[0]; in.Priority != 5 || in.Title != "" { |
| + t.Fatalf("stage update %+v", in) |
| + } |
| + step := working |
| + step.StepID = "s3" |
| + only(t, Change{Kind: ChangeTask, Before: seen(working, true), After: step}, "activity_update") |
| + |
| + ready := task(wire.StageReadyToMerge, wire.NeedsMerge, false) |
| + ready.Tone = wire.ToneWarning |
| + got := only(t, Change{Kind: ChangeTask, Before: seen(review, true), After: ready}, "badge", "activity_update") |
| + if got[0].Kind != KindBadge || got[0].CollapseID != "badge" || !got[0].Coalesce { |
| + t.Fatalf("badge %+v", got[0]) |
| + } |
| + // Urgent but silent: the card's alert is the one sound. |
| + if in := got[1]; in.Priority != 10 || in.Title != "" || in.TitleKey != "" || in.BodyKey != "" || in.State.NeedsYou != wire.NeedsMerge || in.State.Tone != wire.ToneWarning { |
| + t.Fatalf("needs you update %+v", in) |
| + } |
| + |
| + failed := task(wire.StageInProgress, wire.NeedsRetry, false) |
| + got = only(t, Change{Kind: ChangeTask, Before: seen(working, true), After: failed}, "task_fails", "badge", "activity_update") |
| + if got[0].Kind != KindPassive || got[0].BodyKey != "push.task.failed" || got[0].Dedupe != "" { |
| + t.Fatalf("failed alert %+v", got[0]) |
| + } |
| + |
| + done := task(wire.StageDone, "", false) |
| + got = only(t, Change{Kind: ChangeTask, Before: seen(ready, true), After: done}, "task_ends", "badge", "activity_end") |
| + if got[0].Kind != KindPassive || got[0].BodyKey != "push.task.done" || got[0].Dedupe != "outcome:tk1:done" || got[0].CollapseID != "task:tk1" { |
| + t.Fatalf("done alert %+v", got[0]) |
| + } |
| + if end := got[2]; end.Kind != KindActivityEnd || end.State.Outcome != wire.PushOutcomeDone { |
| + t.Fatalf("end %+v", end) |
| + } |
| + cancelled := task(wire.StageCancelled, "", false) |
| + if in := only(t, Change{Kind: ChangeTask, Before: seen(working, false), After: cancelled}, "task_ends")[0]; in.BodyKey != "push.task.cancelled" { |
| + t.Fatalf("cancelled %+v", in) |
| + } |
| + // An ended task seen again pushes nothing; one first seen ended neither. |
| + only(t, Change{Kind: ChangeTask, Before: seen(done, false), After: done}) |
| + only(t, Change{Kind: ChangeTask, After: done}) |
| + // An ended activity is not updated or ended again. |
| + m := seen(working, true) |
| + m.Ended = true |
| + only(t, Change{Kind: ChangeTask, Before: m, After: review}) |
| +} |
| + |
| +// TestRuleActivityLine: a new line updates the activity at most once a |
| +// minute a task, only while it runs. |
| +func TestRuleActivityLine(t *testing.T) { |
| + m := seen(task(wire.StageInProgress, "", true), true) |
| + line := m.Task("tk1") |
| + line.Activity = "Reading README.md" |
| + only(t, Change{Kind: ChangeLine, Now: at, Before: m, After: line}, "activity_line") |
| + recent := at.Add(-30 * time.Second) |
| + m.LineAt = &recent |
| + only(t, Change{Kind: ChangeLine, Now: at, Before: m, After: line}) |
| + old := at.Add(-LineEvery) |
| + m.LineAt = &old |
| + if in := only(t, Change{Kind: ChangeLine, Now: at, Before: m, After: line}, "activity_line")[0]; in.Priority != 5 || in.State.Activity != "Reading README.md" { |
| + t.Fatalf("line %+v", in) |
| + } |
| + same := m |
| + same.Activity = line.Activity |
| + only(t, Change{Kind: ChangeLine, Now: at, Before: same, After: line}) |
| + notLive := seen(task(wire.StageInProgress, "", true), false) |
| + only(t, Change{Kind: ChangeLine, Now: at, Before: notLive, After: line}) |
| +} |
| + |
| +// TestReplaceEndsAtOnce: the activity a newer one replaces ends now. |
| +func TestReplaceEndsAtOnce(t *testing.T) { |
| + in := Replace(task(wire.StageInProgress, "", true)) |
| + if in.Kind != KindActivityEnd || in.State.Outcome != wire.PushOutcomeReplaced { |
| + t.Fatalf("replace %+v", in) |
| + } |
| +} |
diff --git a/internal/equipo/push/sender.go b/internal/equipo/push/sender.go| new file mode 100644 |
| index 00000000..edd8b0c2 |
| --- /dev/null |
| +++ b/internal/equipo/push/sender.go |
| @@ -0,0 +1,359 @@ |
| +package push |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "strings" |
| + "time" |
| + |
| + "gorm.io/gorm" |
| +) |
| + |
| +// Sender drains the outbox through a Transport. Write runs one write |
| +// transaction; Check re-checks, inside it, that the person is on the |
| +// roster and the device credential is still valid: nil, ErrGone (the |
| +// registration is deleted), ErrNotCurrent (the row is dropped, the |
| +// registration kept) or a lookup error (the row is tried again later). |
| +type Sender struct { |
| + Write func(context.Context, func(*gorm.DB) error) error |
| + Transport Transport |
| + Check func(tx *gorm.DB, person, credential string) error |
| + Box Box |
| + Now func() time.Time |
| + // Timeout bounds one send; zero is SendTimeout. |
| + Timeout time.Duration |
| + // Errorf reports what a pass could not do; never a token or payload. |
| + Errorf func(msg string, args ...any) |
| +} |
| + |
| +// Sending limits: rows a pass reads, how long a claim holds, one send's |
| +// deadline, the retry backoff and the attempts before a row fails, Apple's |
| +// own trouble's first wait, and how long ended rows are kept. |
| +const ( |
| + PassSize = 50 |
| + Lease = time.Minute |
| + SendTimeout = 30 * time.Second |
| + FirstRetry = 5 * time.Second |
| + MaxRetry = 10 * time.Minute |
| + MaxAttempts = 8 |
| + AppleRetry = 15 * time.Minute |
| + Keep = 7 * 24 * time.Hour |
| +) |
| + |
| +// Backoff is the wait before attempt n+1 (n sends have failed). |
| +func Backoff(n int) time.Duration { |
| + d := FirstRetry |
| + for i := 1; i < n && d < MaxRetry; i++ { |
| + d *= 2 |
| + } |
| + return min(d, MaxRetry) |
| +} |
| + |
| +// What the sender does with a row after a send. |
| +const ( |
| + ActSent = "sent" // Apple accepted it |
| + ActRetry = "retry" // try again after Wait, an attempt counted |
| + ActHold = "hold" // the platform asked to wait Wait; not an attempt |
| + ActGone = "gone" // Apple says the token is gone: forget it, fail |
| + ActFail = "fail" // never retried: a bug in the request or a refusal |
| +) |
| + |
| +// Verdict is what a send's answer means for its row: the action, the |
| +// wait before the next try, whether the device's other rows wait too |
| +// (Apple throttling that device), and whether the pass stops (the |
| +// platform is paused, over its rate or unavailable: every other row would |
| +// be refused the same). |
| +type Verdict struct { |
| + Act string |
| + Wait time.Duration |
| + Device bool |
| + Stop bool |
| +} |
| + |
| +// Judge reads one send's answer (the CARLOS verb's, platform-push- |
| +// submission design §4.2), n being the attempts already made. |
| +func Judge(res Result, err error, n int) Verdict { |
| + switch { |
| + case err != nil: |
| + return Verdict{Act: ActRetry, Wait: Backoff(n + 1)} |
| + case !res.Apple(): |
| + if res.Refused == 429 || res.Refused == 503 { |
| + return Verdict{Act: ActHold, Wait: max(res.RetryAfter, time.Second), Stop: true} |
| + } |
| + // 400 BAD_REQUEST or PAYLOAD_TOO_LARGE, 401, 403 TOPIC_NOT_ALLOWED |
| + // or ENVIRONMENT_NOT_ARMED: retrying sends the same refusal. |
| + return Verdict{Act: ActFail} |
| + case res.Status >= 200 && res.Status < 300: |
| + return Verdict{Act: ActSent} |
| + case res.Gone(): |
| + return Verdict{Act: ActGone} |
| + case res.Status == 429: |
| + return Verdict{Act: ActRetry, Wait: Backoff(n + 1), Device: true} |
| + case res.Status >= 500: |
| + // Apple's guidance: not at once, after 15 minutes, then backoff. |
| + return Verdict{Act: ActRetry, Wait: AppleRetry << min(n, 3)} |
| + } |
| + return Verdict{Act: ActFail} |
| +} |
| + |
| +// Drain sends every due row once, and reports how many Apple accepted. |
| +func (s *Sender) Drain(ctx context.Context) (sent int, err error) { |
| + now := s.Now() |
| + var due []OutboxRecord |
| + err = s.Write(ctx, func(tx *gorm.DB) error { |
| + if err := tx.Where("state <> ? AND updated_at < ?", StatePending, now.Add(-Keep)).Delete(&OutboxRecord{}).Error; err != nil { |
| + return err |
| + } |
| + return tx.Where("state = ? AND next_at <= ? AND (lease_until IS NULL OR lease_until < ?)", StatePending, now, now).Order("next_at, created_at, id").Limit(PassSize).Find(&due).Error |
| + }) |
| + if err != nil { |
| + return 0, err |
| + } |
| + for _, r := range due { |
| + if ctx.Err() != nil { |
| + return sent, ctx.Err() |
| + } |
| + v, err := s.one(ctx, r) |
| + if err != nil { |
| + s.errorf("push not sent", "id", r.ID, "err", err) |
| + } |
| + if v.Act == ActSent { |
| + sent++ |
| + } |
| + if v.Stop { |
| + break |
| + } |
| + } |
| + return sent, nil |
| +} |
| + |
| +// one claims a row, sends it and records the answer. |
| +func (s *Sender) one(ctx context.Context, r OutboxRecord) (Verdict, error) { |
| + var m Message |
| + claimed := false |
| + err := s.Write(ctx, func(tx *gorm.DB) error { |
| + now := s.Now() |
| + held, err := platformHeld(tx, now) |
| + if err != nil || held { |
| + return err |
| + } |
| + res := tx.Model(&OutboxRecord{}).Where("id = ? AND state = ? AND next_at <= ? AND (lease_until IS NULL OR lease_until < ?)", r.ID, StatePending, now, now).Select("lease_until").Updates(map[string]any{"lease_until": now.Add(Lease)}) |
| + if res.Error != nil || res.RowsAffected != 1 { |
| + return res.Error |
| + } |
| + // A coalescing write or another sender may have changed this row |
| + // since Drain read its batch. Use the row we just claimed. |
| + if err := tx.Where("id = ?", r.ID).Take(&r).Error; err != nil { |
| + return err |
| + } |
| + if !now.Before(Expiration(r.Kind, r.CreatedAt)) { |
| + return finish(tx, r.ID, StateDropped, Result{Reason: "expired"}, now) |
| + } |
| + if err := s.Check(tx, r.Person, r.Credential); err != nil { |
| + switch { |
| + case errors.Is(err, ErrGone): |
| + // Revoked or removed: never sent, and the device forgotten. |
| + if err := ForgetCredential(tx, r.Credential); err != nil { |
| + return err |
| + } |
| + return finish(tx, r.ID, StateDropped, Result{Reason: "not_current"}, now) |
| + case errors.Is(err, ErrNotCurrent): |
| + return finish(tx, r.ID, StateDropped, Result{Reason: "not_current"}, now) |
| + } |
| + // A lookup failed: the claim lapses and a later pass tries. |
| + return err |
| + } |
| + token, env, err := s.token(tx, r) |
| + if errors.Is(err, ErrNoActivity) { |
| + if r.Kind == KindActivityEnd { |
| + // An end is created after its start and updates, with the |
| + // same lifetime. Wait to expiry, without spending delivery |
| + // attempts, so an Apple-delayed start can still be ended. |
| + wait := min(max(FirstRetry, now.Sub(r.CreatedAt)), MaxRetry) |
| + wait = min(wait, Expiration(r.Kind, r.CreatedAt).Sub(now)) |
| + return retry(tx, r, now, wait, false, Result{Reason: "no_token"}) |
| + } |
| + return finish(tx, r.ID, StateDropped, Result{Reason: "no_token"}, now) |
| + } |
| + if errors.Is(err, errUnreadableToken) { |
| + return finish(tx, r.ID, StateFailed, Result{Reason: "unreadable_token"}, now) |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + payload, err := s.Box.OpenPayload(r.Payload) |
| + if err != nil { |
| + return finish(tx, r.ID, StateFailed, Result{Reason: "unreadable_payload"}, now) |
| + } |
| + if len(payload) > MaxPayload { |
| + return finish(tx, r.ID, StateFailed, Result{Reason: "payload_too_large"}, now) |
| + } |
| + claimed = true |
| + m = Message{ID: r.ID, Token: token, Environment: env, Topic: TopicFor(r.PushType), PushType: r.PushType, Priority: r.Priority, CollapseID: r.CollapseID, Expiration: Expiration(r.Kind, r.CreatedAt), Payload: []byte(payload)} |
| + return nil |
| + }) |
| + if err != nil || !claimed { |
| + return Verdict{}, err |
| + } |
| + timeout := s.Timeout |
| + if timeout <= 0 { |
| + timeout = SendTimeout |
| + } |
| + sendCtx, cancel := context.WithTimeout(ctx, timeout) |
| + result, sendErr := s.Transport.Send(sendCtx, m) |
| + cancel() |
| + if sendErr != nil { |
| + sendErr = scrubbed(sendErr, m.Token) |
| + } |
| + result.Reason = scrub(result.Reason, m.Token) |
| + result.Code = scrub(result.Code, m.Token) |
| + v := Judge(result, sendErr, r.Attempts) |
| + err = s.Write(context.WithoutCancel(ctx), func(tx *gorm.DB) error { |
| + now := s.Now() |
| + switch v.Act { |
| + case ActHold: |
| + if err := holdPlatform(tx, now.Add(v.Wait)); err != nil { |
| + return err |
| + } |
| + return retry(tx, r, now, v.Wait, false, result) |
| + case ActRetry: |
| + if v.Device { |
| + // Apple throttles this device: its other rows wait too. |
| + if err := tx.Model(&OutboxRecord{}).Where("credential = ? AND state = ? AND lease_until IS NULL AND next_at < ?", r.Credential, StatePending, now.Add(v.Wait)).Select("next_at").Updates(map[string]any{"next_at": now.Add(v.Wait)}).Error; err != nil { |
| + return err |
| + } |
| + } |
| + if r.Attempts+1 >= MaxAttempts { |
| + return finish(tx, r.ID, StateFailed, result, now) |
| + } |
| + return retry(tx, r, now, v.Wait, true, result) |
| + case ActGone: |
| + if err := s.forgetToken(tx, r, m.Token, result.Timestamp); err != nil { |
| + return err |
| + } |
| + return finish(tx, r.ID, StateFailed, result, now) |
| + case ActSent: |
| + if r.Kind == KindActivityEnd { |
| + if err := s.forgetToken(tx, r, m.Token, time.Time{}); err != nil { |
| + return err |
| + } |
| + } |
| + return finish(tx, r.ID, StateSent, result, now) |
| + } |
| + return finish(tx, r.ID, StateFailed, result, now) |
| + }) |
| + if sendErr != nil && err == nil { |
| + err = sendErr |
| + } |
| + return v, err |
| +} |
| + |
| +// scrub takes a token out of text a transport gave back. |
| +func scrub(text, token string) string { |
| + if token == "" || text == "" { |
| + return text |
| + } |
| + i := strings.Index(strings.ToLower(text), strings.ToLower(token)) |
| + for i >= 0 { |
| + text = text[:i] + "[token]" + text[i+len(token):] |
| + i = strings.Index(strings.ToLower(text), strings.ToLower(token)) |
| + } |
| + return text |
| +} |
| + |
| +// scrubbed is a transport's error with the token taken out of its text; |
| +// only the text survives, never the error's own fields. |
| +func scrubbed(err error, token string) error { |
| + return errors.New(scrub(err.Error(), token)) |
| +} |
| + |
| +// token is the row's token as the device registered it now, opened. |
| +func (s *Sender) token(tx *gorm.DB, r OutboxRecord) (token, env string, err error) { |
| + var reg Registration |
| + if err := tx.Where("credential = ? AND person = ?", r.Credential, r.Person).Take(®).Error; err != nil { |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return "", "", ErrNoActivity |
| + } |
| + return "", "", err |
| + } |
| + sealed := reg.Token |
| + switch r.Target { |
| + case TargetStart: |
| + if reg.StartToken == "" { |
| + return "", "", ErrNoActivity |
| + } |
| + sealed = reg.StartToken |
| + case TargetActivity: |
| + var a ActivityToken |
| + err := tx.Where("credential = ? AND task_id = ?", r.Credential, r.TaskID).Take(&a).Error |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return "", "", ErrNoActivity |
| + } |
| + if err != nil { |
| + return "", "", err |
| + } |
| + sealed = a.Token |
| + } |
| + token, err = s.Box.open(domainToken, sealed) |
| + if err != nil { |
| + return "", "", errUnreadableToken |
| + } |
| + return token, reg.Environment, nil |
| +} |
| + |
| +// retry puts a row back for wait, keeping the answer if there was one; |
| +// counted, it was an attempt. |
| +func retry(tx *gorm.DB, r OutboxRecord, now time.Time, wait time.Duration, counted bool, res Result) error { |
| + attempts := r.Attempts |
| + if counted { |
| + attempts++ |
| + } |
| + return tx.Model(&OutboxRecord{}).Where("id = ?", r.ID).Select("attempts", "next_at", "lease_until", "updated_at", "status", "reason").Updates(map[string]any{"attempts": attempts, "next_at": now.Add(wait), "lease_until": nil, "updated_at": now, "status": res.Status, "reason": reasonOf(res)}).Error |
| +} |
| + |
| +// reasonOf is what a row keeps of an answer: Apple's reason, else the |
| +// platform's code. |
| +func reasonOf(res Result) string { |
| + if res.Reason != "" { |
| + return res.Reason |
| + } |
| + return res.Code |
| +} |
| + |
| +func finish(tx *gorm.DB, id, state string, res Result, now time.Time) error { |
| + fields := map[string]any{"state": state, "status": res.Status, "reason": reasonOf(res), "apns_id": res.APNsID, "lease_until": nil, "updated_at": now, "attempts": gorm.Expr("attempts + 1")} |
| + if state == StateSent { |
| + fields["sent_at"] = now |
| + } |
| + if state == StateDropped { |
| + fields["attempts"] = gorm.Expr("attempts") |
| + } |
| + keys := make([]string, 0, len(fields)) |
| + for k := range fields { |
| + keys = append(keys, k) |
| + } |
| + return tx.Model(&OutboxRecord{}).Where("id = ?", id).Select(keys).Updates(fields).Error |
| +} |
| + |
| +func (s *Sender) errorf(msg string, args ...any) { |
| + if s.Errorf != nil { |
| + s.Errorf(msg, args...) |
| + } |
| +} |
| + |
| +// Serve drains the outbox every interval and at each wake, until ctx ends. |
| +func (s *Sender) Serve(ctx context.Context, wake <-chan struct{}, every time.Duration) { |
| + tick := time.NewTicker(every) |
| + defer tick.Stop() |
| + for { |
| + if _, err := s.Drain(ctx); err != nil && ctx.Err() == nil { |
| + s.errorf("push outbox not drained", "err", err) |
| + } |
| + select { |
| + case <-ctx.Done(): |
| + return |
| + case <-tick.C: |
| + case <-wake: |
| + } |
| + } |
| +} |
diff --git a/internal/equipo/push/sender_state.go b/internal/equipo/push/sender_state.go| new file mode 100644 |
| index 00000000..cc58126f |
| --- /dev/null |
| +++ b/internal/equipo/push/sender_state.go |
| @@ -0,0 +1,80 @@ |
| +package push |
| + |
| +import ( |
| + "errors" |
| + "time" |
| + |
| + "gorm.io/gorm" |
| + "gorm.io/gorm/clause" |
| +) |
| + |
| +// HoldRecord keeps the platform's retry deadline across passes and sender |
| +// restarts. The single platform row covers new and already queued pushes. |
| +type HoldRecord struct { |
| + ID string `gorm:"primaryKey"` |
| + Until time.Time |
| +} |
| + |
| +func (HoldRecord) TableName() string { return "push_holds" } |
| + |
| +func platformHeld(tx *gorm.DB, now time.Time) (bool, error) { |
| + var n int64 |
| + err := tx.Model(&HoldRecord{}).Where("id = ? AND until > ?", "platform", now).Count(&n).Error |
| + return n > 0, err |
| +} |
| + |
| +func holdPlatform(tx *gorm.DB, until time.Time) error { |
| + return tx.Clauses(clause.OnConflict{ |
| + Columns: []clause.Column{{Name: "id"}}, |
| + DoUpdates: clause.Assignments(map[string]any{"until": gorm.Expr("MAX(push_holds.until, excluded.until)")}), |
| + }).Create(&HoldRecord{ID: "platform", Until: until}).Error |
| +} |
| + |
| +// Never expose an opener's error: it can include token or payload text. |
| +var errUnreadableToken = errors.New("push: unreadable token") |
| + |
| +// forgetToken only invalidates the token this send used. A renewal after |
| +// Apple's last-valid timestamp also survives, for every token type. |
| +// Compare opened tokens in Go; neither tokens nor their hashes enter SQL. |
| +func (s *Sender) forgetToken(tx *gorm.DB, r OutboxRecord, sent string, apple time.Time) error { |
| + var sealed string |
| + var registered time.Time |
| + if r.Target == TargetActivity { |
| + var a ActivityToken |
| + err := tx.Where("credential = ? AND task_id = ?", r.Credential, r.TaskID).Take(&a).Error |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return nil |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + sealed, registered = a.Token, a.CreatedAt |
| + } else { |
| + var reg Registration |
| + err := tx.Where("credential = ?", r.Credential).Take(®).Error |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return nil |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + sealed, registered = reg.Token, reg.UpdatedAt |
| + if r.Target == TargetStart { |
| + sealed = reg.StartToken |
| + } |
| + } |
| + current, err := s.Box.open(domainToken, sealed) |
| + if err != nil { |
| + return errUnreadableToken |
| + } |
| + if current != sent || !apple.IsZero() && registered.After(apple) { |
| + return nil |
| + } |
| + switch r.Target { |
| + case TargetStart: |
| + return tx.Model(&Registration{}).Where("credential = ?", r.Credential).Select("start_token").Updates(map[string]any{"start_token": ""}).Error |
| + case TargetActivity: |
| + return tx.Where("credential = ? AND task_id = ?", r.Credential, r.TaskID).Delete(&ActivityToken{}).Error |
| + } |
| + return ForgetCredential(tx, r.Credential) |
| +} |
diff --git a/internal/equipo/push/sender_test.go b/internal/equipo/push/sender_test.go| new file mode 100644 |
| index 00000000..cc242272 |
| --- /dev/null |
| +++ b/internal/equipo/push/sender_test.go |
| @@ -0,0 +1,422 @@ |
| +package push |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "log/slog" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "gorm.io/gorm" |
| +) |
| + |
| +const ( |
| + devToken = "aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11" |
| + startToken = "bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22" |
| + actToken = "cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33" |
| +) |
| + |
| +// testBox seals as the instance key does for the tests' purposes: what |
| +// it seals never shows the token or the text. |
| +var testBox = Box{ |
| + Seal: func(domain string, v any) (string, error) { |
| + b, err := json.Marshal(v) |
| + return domain + ":" + base64.StdEncoding.EncodeToString(b), err |
| + }, |
| + Open: func(domain, sealed string, v any) error { |
| + raw, ok := strings.CutPrefix(sealed, domain+":") |
| + if !ok { |
| + return errors.New("sealed for another domain") |
| + } |
| + b, err := base64.StdEncoding.DecodeString(raw) |
| + if err != nil { |
| + return err |
| + } |
| + return json.Unmarshal(b, v) |
| + }, |
| +} |
| + |
| +type rig struct { |
| + t *testing.T |
| + d *db.DB |
| + now time.Time |
| + current map[string]bool // credential -> still valid |
| + sent []Message |
| + answer func(Message) (Result, error) |
| + s *Sender |
| +} |
| + |
| +func newRig(t *testing.T) *rig { |
| + t.Helper() |
| + d, err := db.Open(filepath.Join(t.TempDir(), "push.db"), slog.New(slog.NewTextHandler(io.Discard, nil))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { _ = d.Close() }) |
| + if err := d.G.AutoMigrate(Models...); err != nil { |
| + t.Fatal(err) |
| + } |
| + r := &rig{t: t, d: d, now: at, current: map[string]bool{"cr1": true}} |
| + r.answer = func(m Message) (Result, error) { return Result{Status: 200, APNsID: "apple-" + m.ID}, nil } |
| + r.s = &Sender{ |
| + Write: func(ctx context.Context, fn func(*gorm.DB) error) error { return d.G.WithContext(ctx).Transaction(fn) }, |
| + Transport: transportFunc(func(_ context.Context, m Message) (Result, error) { |
| + r.sent = append(r.sent, m) |
| + return r.answer(m) |
| + }), |
| + Check: func(_ *gorm.DB, person, credential string) error { |
| + if person != "p@example.com" || !r.current[credential] { |
| + return ErrGone |
| + } |
| + return nil |
| + }, |
| + Box: testBox, |
| + Now: func() time.Time { return r.now }, |
| + } |
| + r.must(d.G.Transaction(func(tx *gorm.DB) error { |
| + _, err := Register(tx, testBox, "p@example.com", "cr1", wire.RegisterPush{Token: devToken, Environment: wire.APNsDevelopment, Platform: wire.PlatformIOS, StartToken: startToken}, at) |
| + return err |
| + })) |
| + return r |
| +} |
| + |
| +type transportFunc func(context.Context, Message) (Result, error) |
| + |
| +func (f transportFunc) Send(ctx context.Context, m Message) (Result, error) { return f(ctx, m) } |
| + |
| +func (r *rig) must(err error) { |
| + r.t.Helper() |
| + if err != nil { |
| + r.t.Fatal(err) |
| + } |
| +} |
| + |
| +func (r *rig) enqueue(kind, target, collapse string, coalesce bool) { |
| + r.t.Helper() |
| + typ := TypeAlert |
| + if strings.HasPrefix(kind, "activity") { |
| + typ = TypeLiveActivity |
| + } |
| + row := OutboxRecord{Person: "p@example.com", Credential: "cr1", Kind: kind, Target: target, TaskID: "tk1", PushType: typ, Priority: 10, CollapseID: collapse, Payload: `{"aps":{}}`, NextAt: r.now, CreatedAt: r.now, UpdatedAt: r.now} |
| + r.must(r.d.G.Transaction(func(tx *gorm.DB) error { return Enqueue(tx, testBox, row, coalesce) })) |
| +} |
| + |
| +// opened is a token or payload as sealed at rest, opened. |
| +func (r *rig) opened(domain, sealed string) string { |
| + r.t.Helper() |
| + v, err := testBox.open(domain, sealed) |
| + r.must(err) |
| + return v |
| +} |
| + |
| +func (r *rig) rows() []OutboxRecord { |
| + var out []OutboxRecord |
| + r.must(r.d.G.Order("created_at, collapse_id, kind").Find(&out).Error) |
| + return out |
| +} |
| + |
| +func (r *rig) drain() int { |
| + r.t.Helper() |
| + n, err := r.s.Drain(context.Background()) |
| + if err != nil { |
| + r.t.Fatal(err) |
| + } |
| + return n |
| +} |
| + |
| +// TestSenderSendsOnceAndRecordsApple: a row goes once, with its id as |
| +// apns-id, the token read from the registration, the topic of its push |
| +// type, and Apple's answer kept; a second pass sends nothing. |
| +func TestSenderSendsOnceAndRecordsApple(t *testing.T) { |
| + r := newRig(t) |
| + r.enqueue(KindAlert, TargetDevice, "c1", false) |
| + if r.drain() != 1 || r.drain() != 0 || len(r.sent) != 1 { |
| + t.Fatalf("sent %d", len(r.sent)) |
| + } |
| + m := r.sent[0] |
| + row := r.rows()[0] |
| + if !uuidShape.MatchString(m.ID) || m.ID != row.ID || m.Token != devToken || m.Topic != Topic || m.Environment != wire.APNsDevelopment || m.CollapseID != "c1" || m.Priority != 10 { |
| + t.Fatalf("message %+v", m) |
| + } |
| + if row.State != StateSent || row.Status != 200 || row.APNsID != "apple-"+row.ID || row.SentAt == nil || row.Attempts != 1 { |
| + t.Fatalf("row %+v", row) |
| + } |
| +} |
| + |
| +// TestSenderRetryIsTheSamePush: a failed delivery is retried after the |
| +// backoff with the same id and collapse ID, and once accepted never sent |
| +// again; Apple's throttling is retried the same way. |
| +func TestSenderRetryIsTheSamePush(t *testing.T) { |
| + r := newRig(t) |
| + r.enqueue(KindAlert, TargetDevice, "c1", false) |
| + calls := 0 |
| + r.answer = func(m Message) (Result, error) { |
| + calls++ |
| + switch calls { |
| + case 1: |
| + return Result{}, errors.New("connection reset") |
| + case 2: |
| + return Result{Status: 429, Reason: "TooManyRequests"}, nil |
| + } |
| + return Result{Status: 200, APNsID: m.ID}, nil |
| + } |
| + r.drain() |
| + if row := r.rows()[0]; row.State != StatePending || row.Attempts != 1 || !row.NextAt.Equal(at.Add(FirstRetry)) { |
| + t.Fatalf("after a failure %+v", row) |
| + } |
| + if r.drain() != 0 || len(r.sent) != 1 { |
| + t.Fatal("retried before the backoff") |
| + } |
| + r.now = at.Add(FirstRetry) |
| + r.drain() |
| + if row := r.rows()[0]; row.State != StatePending || row.Attempts != 2 || row.Status != 429 || row.Reason != "TooManyRequests" { |
| + t.Fatalf("after throttling %+v", row) |
| + } |
| + r.now = r.now.Add(Backoff(2)) |
| + if r.drain() != 1 { |
| + t.Fatal("not sent on the third try") |
| + } |
| + r.now = r.now.Add(time.Hour) |
| + r.drain() |
| + if len(r.sent) != 3 || r.sent[0].ID != r.sent[2].ID || r.sent[0].CollapseID != r.sent[2].CollapseID { |
| + t.Fatalf("sends %d", len(r.sent)) |
| + } |
| + if Backoff(1) != FirstRetry || Backoff(2) != 2*FirstRetry || Backoff(30) != MaxRetry { |
| + t.Fatal("backoff") |
| + } |
| +} |
| + |
| +// TestSenderGivesUp: after MaxAttempts failed deliveries the row fails. |
| +func TestSenderGivesUp(t *testing.T) { |
| + r := newRig(t) |
| + r.enqueue(KindAlert, TargetDevice, "c1", false) |
| + r.answer = func(Message) (Result, error) { return Result{Status: 503, Reason: "ServiceUnavailable"}, nil } |
| + for i := 0; i < MaxAttempts; i++ { |
| + r.drain() |
| + r.now = r.now.Add(2 * time.Hour) |
| + } |
| + if row := r.rows()[0]; row.State != StateFailed || row.Status != 503 || len(r.sent) != MaxAttempts { |
| + t.Fatalf("row %+v after %d sends", row, len(r.sent)) |
| + } |
| +} |
| + |
| +// TestSenderForgetsGoneTokens: Unregistered or BadDeviceToken deletes the |
| +// registration and drops what waits for it; on a push-to-start token it |
| +// clears that token only; on an activity's, that activity's. |
| +func TestSenderForgetsGoneTokens(t *testing.T) { |
| + for _, reason := range []string{ReasonUnregistered, ReasonBadDeviceToken} { |
| + r := newRig(t) |
| + r.enqueue(KindAlert, TargetDevice, "c1", false) |
| + r.enqueue(KindAlert, TargetDevice, "c2", false) |
| + r.answer = func(Message) (Result, error) { return Result{Status: 400, Reason: reason}, nil } |
| + r.drain() |
| + var n int64 |
| + r.d.G.Model(&Registration{}).Count(&n) |
| + states := map[string]int{} |
| + rows := r.rows() |
| + for _, row := range rows { |
| + states[row.State+" "+row.Reason]++ |
| + } |
| + if n != 0 || len(r.sent) != 1 || states[StateFailed+" "+reason] != 1 || states[StateDropped+" forgotten"] != 1 { |
| + t.Fatalf("%s: registrations %d, sent %d, rows %+v", reason, n, len(r.sent), rows) |
| + } |
| + } |
| + r := newRig(t) |
| + r.enqueue(KindActivityStart, TargetStart, "", false) |
| + r.answer = func(Message) (Result, error) { return Result{Status: 410, Reason: ReasonUnregistered}, nil } |
| + r.drain() |
| + var reg Registration |
| + r.must(r.d.G.Take(®).Error) |
| + if reg.StartToken != "" || r.opened(domainToken, reg.Token) != devToken || r.sent[0].Token != startToken || r.sent[0].Topic != Topic+".push-type.liveactivity" { |
| + t.Fatalf("start token %+v", reg) |
| + } |
| + r.must(r.d.G.Transaction(func(tx *gorm.DB) error { |
| + return RegisterActivity(tx, testBox, "p@example.com", "cr1", "tk1", actToken, at) |
| + })) |
| + r.enqueue(KindActivityUpdate, TargetActivity, "", false) |
| + r.drain() |
| + var acts int64 |
| + r.d.G.Model(&ActivityToken{}).Count(&acts) |
| + if acts != 0 || r.sent[1].Token != actToken { |
| + t.Fatal("activity token kept after Unregistered") |
| + } |
| +} |
| + |
| +// TestSenderNeverSendsToRevokedOrRemoved: a device no longer current |
| +// (revoked, its person removed) is never sent to; its registration goes. |
| +func TestSenderNeverSendsToRevokedOrRemoved(t *testing.T) { |
| + r := newRig(t) |
| + r.enqueue(KindAlert, TargetDevice, "c1", false) |
| + r.current["cr1"] = false |
| + r.drain() |
| + var n int64 |
| + r.d.G.Model(&Registration{}).Count(&n) |
| + if len(r.sent) != 0 || n != 0 || r.rows()[0].State != StateDropped { |
| + t.Fatalf("sent %d, registrations %d", len(r.sent), n) |
| + } |
| +} |
| + |
| +// TestSenderActivityTokens: an update waits for no token (dropped), an end |
| +// waits for the app's token a while, and a delivered end forgets it. |
| +func TestSenderActivityTokens(t *testing.T) { |
| + r := newRig(t) |
| + r.enqueue(KindActivityUpdate, TargetActivity, "", false) |
| + r.enqueue(KindActivityEnd, TargetActivity, "", false) |
| + r.drain() |
| + rows := r.rows() |
| + // Ordered by kind: the end, then the update. |
| + if len(r.sent) != 0 || rows[1].State != StateDropped || rows[1].Reason != "no_token" || rows[0].State != StatePending || rows[0].Attempts != 0 { |
| + t.Fatalf("rows %+v", rows) |
| + } |
| + r.must(r.d.G.Transaction(func(tx *gorm.DB) error { |
| + return RegisterActivity(tx, testBox, "p@example.com", "cr1", "tk1", actToken, at) |
| + })) |
| + r.now = r.now.Add(FirstRetry) |
| + r.drain() |
| + var acts int64 |
| + r.d.G.Model(&ActivityToken{}).Count(&acts) |
| + if len(r.sent) != 1 || r.sent[0].Token != actToken || acts != 0 { |
| + t.Fatalf("end sent %d, tokens left %d", len(r.sent), acts) |
| + } |
| +} |
| + |
| +// TestSenderClaimsOnce: a row another sender holds (an overlapping |
| +// process) is not sent again until its lease ends. |
| +func TestSenderClaimsOnce(t *testing.T) { |
| + r := newRig(t) |
| + r.enqueue(KindAlert, TargetDevice, "c1", false) |
| + lease := r.now.Add(Lease) |
| + r.must(r.d.G.Model(&OutboxRecord{}).Where("1 = 1").Update("lease_until", lease).Error) |
| + if r.drain() != 0 || len(r.sent) != 0 { |
| + t.Fatal("sent a row another sender holds") |
| + } |
| + r.now = lease.Add(time.Second) |
| + if r.drain() != 1 { |
| + t.Fatal("an expired lease was not taken over") |
| + } |
| +} |
| + |
| +// TestEnqueueCoalesceAndOnce: a coalescing push replaces the unsent one |
| +// with the same collapse ID; a once-only key is decided once for a |
| +// person, kept apart from the outbox (pruned rows do not forget it). |
| +func TestEnqueueCoalesceAndOnce(t *testing.T) { |
| + r := newRig(t) |
| + r.enqueue(KindBadge, TargetDevice, "badge", true) |
| + r.enqueue(KindBadge, TargetDevice, "badge", true) |
| + if n := len(r.rows()); n != 1 { |
| + t.Fatalf("%d rows", n) |
| + } |
| + r.drain() |
| + r.enqueue(KindBadge, TargetDevice, "badge", true) |
| + if n := len(r.rows()); n != 2 { |
| + t.Fatalf("a sent badge was overwritten: %d rows", n) |
| + } |
| + r.must(r.d.G.Transaction(func(tx *gorm.DB) error { |
| + for i, want := range []bool{true, false} { |
| + first, err := Once(tx, "p@example.com", "card:c1", at) |
| + if err != nil || first != want { |
| + t.Errorf("once %d: %v %v", i, first, err) |
| + } |
| + } |
| + return nil |
| + })) |
| + r.now = r.now.Add(Keep + time.Hour) |
| + r.drain() |
| + for _, row := range r.rows() { |
| + if row.State == StateSent { |
| + t.Fatal("ended rows not pruned") |
| + } |
| + } |
| + r.must(r.d.G.Transaction(func(tx *gorm.DB) error { |
| + if first, err := Once(tx, "p@example.com", "card:c1", r.now); first || err != nil { |
| + t.Error("pruning forgot the alert", err) |
| + } |
| + return nil |
| + })) |
| +} |
| + |
| +// TestRegisterValidates: hex tokens of a sane length, the two |
| +// environments and platforms, a start token only on iPhone; a new |
| +// registration replaces the device's. |
| +func TestRegisterValidates(t *testing.T) { |
| + good := wire.RegisterPush{Token: devToken, Environment: wire.APNsProduction, Platform: wire.PlatformMacOS} |
| + if Validate(good) != nil { |
| + t.Fatal("good refused") |
| + } |
| + for name, mod := range map[string]func(*wire.RegisterPush){ |
| + "short": func(p *wire.RegisterPush) { p.Token = "abcd" }, |
| + "not hex": func(p *wire.RegisterPush) { p.Token = strings.Repeat("zz", 32) }, |
| + "long": func(p *wire.RegisterPush) { p.Token = strings.Repeat("a", wire.MaxPushToken+2) }, |
| + "environment": func(p *wire.RegisterPush) { p.Environment = "sandbox" }, |
| + "platform": func(p *wire.RegisterPush) { p.Platform = "watchos" }, |
| + "mac start": func(p *wire.RegisterPush) { p.StartToken = startToken }, |
| + "bad start": func(p *wire.RegisterPush) { p.Platform, p.StartToken = wire.PlatformIOS, "xyz" }, |
| + } { |
| + p := good |
| + mod(&p) |
| + if Validate(p) == nil { |
| + t.Errorf("%s accepted", name) |
| + } |
| + } |
| + r := newRig(t) |
| + r.must(r.d.G.Transaction(func(tx *gorm.DB) error { |
| + out, err := Register(tx, testBox, "p@example.com", "cr1", good, at) |
| + if out.LiveActivities || out.Platform != wire.PlatformMacOS { |
| + t.Errorf("registration %+v", out) |
| + } |
| + return err |
| + })) |
| + var regs []Registration |
| + r.must(r.d.G.Find(®s).Error) |
| + if len(regs) != 1 || regs[0].StartToken != "" || regs[0].Platform != wire.PlatformMacOS { |
| + t.Fatalf("not replaced: %+v", regs) |
| + } |
| +} |
| + |
| +// TestLoggedTransportKeepsTokensOut: the logged transport logs that a push |
| +// would go, never its token or payload. |
| +func TestLoggedTransportKeepsTokensOut(t *testing.T) { |
| + var buf bytes.Buffer |
| + l := Logged{Logger: slog.New(slog.NewTextHandler(&buf, nil))} |
| + res, err := l.Send(context.Background(), Message{ID: "pu1", Token: devToken, Payload: []byte(`{"aps":{"alert":{"body":"Merge the login fix?"}}}`)}) |
| + if err != nil || res.Status != 200 { |
| + t.Fatal(res, err) |
| + } |
| + sum := sha256.Sum256([]byte(devToken)) |
| + if strings.Contains(buf.String(), devToken) || strings.Contains(buf.String(), hex.EncodeToString(sum[:4])) || strings.Contains(buf.String(), "login fix") || !strings.Contains(buf.String(), "pu1") { |
| + t.Fatalf("log %s", buf.String()) |
| + } |
| +} |
| + |
| +// TestCarlosSeam: CARLOS_PUSH unset is no transport; submit refuses until |
| +// the platform verb exists. |
| +func TestCarlosSeam(t *testing.T) { |
| + if tr, err := FromCarlos(func(string) string { return "" }); tr != nil || err != nil { |
| + t.Fatal("unset", tr, err) |
| + } |
| + if _, err := FromCarlos(func(k string) string { return map[string]string{CarlosPushEnv: "submit"}[k] }); !errors.Is(err, ErrCarlosPushUnavailable) { |
| + t.Fatal("submit", err) |
| + } |
| +} |
| + |
| +// TestSenderClaimRace: a row another sender claimed after this one read |
| +// it (two processes in a deploy overlap) is not sent twice. |
| +func TestSenderClaimRace(t *testing.T) { |
| + r := newRig(t) |
| + r.enqueue(KindAlert, TargetDevice, "c1", false) |
| + row := r.rows()[0] |
| + r.must(r.d.G.Model(&OutboxRecord{}).Where("id = ?", row.ID).Update("lease_until", r.now.Add(Lease)).Error) |
| + if v, err := r.s.one(context.Background(), row); v.Act != "" || err != nil || len(r.sent) != 0 { |
| + t.Fatalf("sent a row another sender claimed: %v %v", v, err) |
| + } |
| +} |
diff --git a/internal/equipo/push/store.go b/internal/equipo/push/store.go| new file mode 100644 |
| index 00000000..56c0410f |
| --- /dev/null |
| +++ b/internal/equipo/push/store.go |
| @@ -0,0 +1,359 @@ |
| +package push |
| + |
| +import ( |
| + "crypto/rand" |
| + "errors" |
| + "fmt" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "gorm.io/gorm" |
| + "gorm.io/gorm/clause" |
| +) |
| + |
| +// Models are the push tables, for the migration check (chat.Models |
| +// carries them). |
| +var Models = []any{&Registration{}, &ActivityToken{}, &OutboxRecord{}, &MemoryRecord{}, &OnceRecord{}, &HoldRecord{}} |
| + |
| +// Registration is a paired device's push registration, one per device |
| +// credential: a new one replaces it, and one APNs token belongs to one |
| +// credential (the newest to register it). Token and StartToken are sealed |
| +// (Box); Registrations from Devices hold them sealed. |
| +type Registration struct { |
| + Credential string `gorm:"primaryKey"` |
| + Person string `gorm:"index:push_registration_person"` |
| + Token string |
| + Environment string |
| + Platform string |
| + StartToken string |
| + CreatedAt time.Time |
| + UpdatedAt time.Time |
| +} |
| + |
| +func (Registration) TableName() string { return "push_registrations" } |
| + |
| +// ActivityToken is a running Live Activity's own update token, on one |
| +// device, for one task; Token is sealed. |
| +type ActivityToken struct { |
| + Credential string `gorm:"primaryKey"` |
| + TaskID string `gorm:"primaryKey"` |
| + Person string `gorm:"index:push_activity_person"` |
| + Token string |
| + CreatedAt time.Time |
| +} |
| + |
| +func (ActivityToken) TableName() string { return "push_activities" } |
| + |
| +// Outbox row states. |
| +const ( |
| + StatePending = "pending" |
| + StateSent = "sent" |
| + StateFailed = "failed" |
| + // StateDropped: never sent, because the device or person is gone or |
| + // no token was ever on file. |
| + StateDropped = "dropped" |
| +) |
| + |
| +// OutboxRecord is one push to one device. The token is not copied here: |
| +// the sender reads it from the registration when it sends, so a revoked |
| +// device or a replaced token never receives an old row. ID is a canonical |
| +// lowercase UUID, sent as apns-id; Payload is sealed (Box). |
| +type OutboxRecord struct { |
| + ID string `gorm:"primaryKey"` |
| + Person string `gorm:"index:push_outbox_person"` |
| + Credential string `gorm:"index:push_outbox_credential"` |
| + Kind string |
| + Target string |
| + TaskID string |
| + PushType string |
| + Priority int |
| + CollapseID string |
| + Dedupe string `gorm:"index:push_outbox_dedupe"` |
| + Payload string |
| + State string `gorm:"index:push_outbox_due,priority:1"` |
| + NextAt time.Time `gorm:"index:push_outbox_due,priority:2"` |
| + Attempts int |
| + LeaseUntil *time.Time |
| + // Apple's answer to the newest send. |
| + Status int |
| + Reason string |
| + APNsID string `gorm:"column:apns_id"` |
| + SentAt *time.Time |
| + CreatedAt time.Time |
| + UpdatedAt time.Time |
| +} |
| + |
| +func (OutboxRecord) TableName() string { return "push_outbox" } |
| + |
| +// MemoryRecord is what a person's devices were last told about a task |
| +// they started (Memory). |
| +type MemoryRecord struct { |
| + Person string `gorm:"primaryKey"` |
| + TaskID string `gorm:"primaryKey"` |
| + Title string |
| + Tone string |
| + Stage string |
| + NeedsYou string |
| + Specialist string |
| + StepID string |
| + Activity string |
| + StartedAt *time.Time |
| + Ended bool |
| + LineAt *time.Time |
| + UpdatedAt time.Time |
| +} |
| + |
| +func (MemoryRecord) TableName() string { return "push_tasks" } |
| + |
| +// OnceRecord marks a once-only push (a card's alert, a reply's, a task's |
| +// outcome) as decided for a person, whether or not a device took it. It |
| +// is kept while the person is, never pruned with the outbox, so a card |
| +// alerts once in its life. |
| +type OnceRecord struct { |
| + Person string `gorm:"primaryKey"` |
| + Key string `gorm:"primaryKey"` |
| + CreatedAt time.Time |
| +} |
| + |
| +func (OnceRecord) TableName() string { return "push_once" } |
| + |
| +// ErrInvalid is a registration the server refuses. |
| +var ErrInvalid = errors.New("push: invalid registration") |
| + |
| +func hexToken(s string) bool { |
| + if len(s) < 32 || len(s) > wire.MaxPushToken || len(s)%2 != 0 { |
| + return false |
| + } |
| + for _, r := range s { |
| + if !(r >= '0' && r <= '9' || r >= 'a' && r <= 'f' || r >= 'A' && r <= 'F') { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// Validate checks a registration: hex tokens, a known environment and |
| +// platform, and a push-to-start token only on iPhone. |
| +func Validate(in wire.RegisterPush) error { |
| + if !hexToken(in.Token) || in.StartToken != "" && !hexToken(in.StartToken) { |
| + return ErrInvalid |
| + } |
| + if in.Environment != wire.APNsProduction && in.Environment != wire.APNsDevelopment { |
| + return ErrInvalid |
| + } |
| + if in.Platform != wire.PlatformIOS && in.Platform != wire.PlatformMacOS || in.Platform == wire.PlatformMacOS && in.StartToken != "" { |
| + return ErrInvalid |
| + } |
| + return nil |
| +} |
| + |
| +// Register replaces the credential's registration. A token another |
| +// credential holds (the phone signed out offline and paired again, maybe |
| +// as someone else) is taken from it: that credential's registration, what |
| +// waits for it and its activity tokens holding the token go. |
| +func Register(tx *gorm.DB, box Box, person, credential string, in wire.RegisterPush, now time.Time) (wire.PushRegistration, error) { |
| + if err := Validate(in); err != nil { |
| + return wire.PushRegistration{}, err |
| + } |
| + token, start := strings.ToLower(in.Token), strings.ToLower(in.StartToken) |
| + mine := map[string]bool{token: true} |
| + if start != "" { |
| + mine[start] = true |
| + } |
| + if err := takeTokens(tx, box, credential, mine); err != nil { |
| + return wire.PushRegistration{}, err |
| + } |
| + sealed, err := box.seal(domainToken, token) |
| + if err != nil { |
| + return wire.PushRegistration{}, err |
| + } |
| + sealedStart, err := box.seal(domainToken, start) |
| + if err != nil { |
| + return wire.PushRegistration{}, err |
| + } |
| + r := Registration{Credential: credential, Person: person, Token: sealed, Environment: in.Environment, Platform: in.Platform, StartToken: sealedStart, CreatedAt: now, UpdatedAt: now} |
| + err = tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "credential"}}, DoUpdates: clause.AssignmentColumns([]string{"person", "token", "environment", "platform", "start_token", "updated_at"})}).Create(&r).Error |
| + return wire.PushRegistration{Environment: r.Environment, Platform: r.Platform, LiveActivities: start != "", UpdatedAt: now}, err |
| +} |
| + |
| +// takeTokens forgets every other credential's registration holding one of |
| +// the tokens, and every other credential's activity token that is one. |
| +// Tokens are sealed, so they are compared opened, in Go: never in SQL. A |
| +// token that will not open cannot be this one, and never stops a |
| +// registration. |
| +func takeTokens(tx *gorm.DB, box Box, credential string, tokens map[string]bool) error { |
| + var regs []Registration |
| + if err := tx.Where("credential <> ?", credential).Find(®s).Error; err != nil { |
| + return err |
| + } |
| + for _, r := range regs { |
| + for _, sealed := range []string{r.Token, r.StartToken} { |
| + t, err := box.open(domainToken, sealed) |
| + if err == nil && t != "" && tokens[t] { |
| + if err := ForgetCredential(tx, r.Credential); err != nil { |
| + return err |
| + } |
| + break |
| + } |
| + } |
| + } |
| + var acts []ActivityToken |
| + if err := tx.Where("credential <> ?", credential).Find(&acts).Error; err != nil { |
| + return err |
| + } |
| + for _, a := range acts { |
| + t, err := box.open(domainToken, a.Token) |
| + if err == nil && tokens[t] { |
| + if err := tx.Where("credential = ? AND task_id = ?", a.Credential, a.TaskID).Delete(&ActivityToken{}).Error; err != nil { |
| + return err |
| + } |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// RegisterActivity keeps a running activity's update token, taken from |
| +// any other credential that held it. |
| +func RegisterActivity(tx *gorm.DB, box Box, person, credential, task, token string, now time.Time) error { |
| + if !hexToken(token) || task == "" { |
| + return ErrInvalid |
| + } |
| + token = strings.ToLower(token) |
| + if err := takeTokens(tx, box, credential, map[string]bool{token: true}); err != nil { |
| + return err |
| + } |
| + sealed, err := box.seal(domainToken, token) |
| + if err != nil { |
| + return err |
| + } |
| + a := ActivityToken{Credential: credential, TaskID: task, Person: person, Token: sealed, CreatedAt: now} |
| + return tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "credential"}, {Name: "task_id"}}, DoUpdates: clause.AssignmentColumns([]string{"person", "token", "created_at"})}).Create(&a).Error |
| +} |
| + |
| +// Waiting reports whether a push for the task still waits to go to the |
| +// device (an activity's end waiting for its token). |
| +func Waiting(tx *gorm.DB, credential, task string) (bool, error) { |
| + var n int64 |
| + err := tx.Model(&OutboxRecord{}).Where("credential = ? AND task_id = ? AND state = ?", credential, task, StatePending).Count(&n).Error |
| + return n > 0, err |
| +} |
| + |
| +// Hurry makes activity updates and ends due now: their token just arrived. |
| +// A start's Apple retry deadline must stay intact. |
| +func Hurry(tx *gorm.DB, credential, task string, now time.Time) error { |
| + return tx.Model(&OutboxRecord{}).Where("credential = ? AND task_id = ? AND target = ? AND state = ? AND lease_until IS NULL", credential, task, TargetActivity, StatePending).Select("next_at").Updates(map[string]any{"next_at": now}).Error |
| +} |
| + |
| +// ForgetCredential deletes a device's registration, its activity tokens |
| +// and what still waits to go to it: the device was revoked, or Apple said |
| +// its token is gone. |
| +func ForgetCredential(tx *gorm.DB, credential string) error { |
| + if err := tx.Where("credential = ?", credential).Delete(&Registration{}).Error; err != nil { |
| + return err |
| + } |
| + if err := tx.Where("credential = ?", credential).Delete(&ActivityToken{}).Error; err != nil { |
| + return err |
| + } |
| + return tx.Model(&OutboxRecord{}).Where("credential = ? AND state = ?", credential, StatePending).Select("state", "reason", "lease_until").Updates(map[string]any{"state": StateDropped, "reason": "forgotten", "lease_until": nil}).Error |
| +} |
| + |
| +// ForgetPerson deletes everything push holds for a person removed from the |
| +// roster. |
| +func ForgetPerson(tx *gorm.DB, person string) error { |
| + for _, m := range []any{&Registration{}, &ActivityToken{}, &MemoryRecord{}, &OnceRecord{}} { |
| + if err := tx.Where("person = ?", person).Delete(m).Error; err != nil { |
| + return err |
| + } |
| + } |
| + return tx.Model(&OutboxRecord{}).Where("person = ? AND state = ?", person, StatePending).Select("state", "reason", "lease_until").Updates(map[string]any{"state": StateDropped, "reason": "forgotten", "lease_until": nil}).Error |
| +} |
| + |
| +// Devices are the person's registrations, oldest first, their tokens |
| +// sealed. |
| +func Devices(tx *gorm.DB, person string) ([]Registration, error) { |
| + var out []Registration |
| + err := tx.Where("person = ?", person).Order("created_at, credential").Find(&out).Error |
| + return out, err |
| +} |
| + |
| +// Device is one credential's registration, its tokens sealed. |
| +func Device(tx *gorm.DB, person, credential string) ([]Registration, error) { |
| + var out []Registration |
| + err := tx.Where("person = ? AND credential = ?", person, credential).Find(&out).Error |
| + return out, err |
| +} |
| + |
| +// HasActivity reports whether a device has a running activity's token for |
| +// the task. |
| +func HasActivity(tx *gorm.DB, credential, task string) (bool, error) { |
| + var n int64 |
| + err := tx.Model(&ActivityToken{}).Where("credential = ? AND task_id = ?", credential, task).Count(&n).Error |
| + return n > 0, err |
| +} |
| + |
| +// LoadMemory is the person's memory of a task (Seen false when none). |
| +func LoadMemory(tx *gorm.DB, person, task string) (Memory, error) { |
| + var r MemoryRecord |
| + err := tx.Where("person = ? AND task_id = ?", person, task).Take(&r).Error |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return Memory{}, nil |
| + } |
| + if err != nil { |
| + return Memory{}, err |
| + } |
| + return Memory{Seen: true, Title: r.Title, Tone: r.Tone, Stage: r.Stage, NeedsYou: r.NeedsYou, Specialist: r.Specialist, StepID: r.StepID, Activity: r.Activity, Started: r.StartedAt, Ended: r.Ended, LineAt: r.LineAt}, nil |
| +} |
| + |
| +// SaveMemory records what the devices were told about a task. |
| +func SaveMemory(tx *gorm.DB, person, task string, m Memory, now time.Time) error { |
| + r := MemoryRecord{Person: person, TaskID: task, Title: m.Title, Tone: m.Tone, Stage: m.Stage, NeedsYou: m.NeedsYou, Specialist: m.Specialist, StepID: m.StepID, Activity: m.Activity, StartedAt: m.Started, Ended: m.Ended, LineAt: m.LineAt, UpdatedAt: now} |
| + return tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "person"}, {Name: "task_id"}}, DoUpdates: clause.AssignmentColumns([]string{"title", "tone", "stage", "needs_you", "specialist", "step_id", "activity", "started_at", "ended", "line_at", "updated_at"})}).Create(&r).Error |
| +} |
| + |
| +// LiveTasks are the tasks with a running Live Activity for the person, |
| +// oldest start first. |
| +func LiveTasks(tx *gorm.DB, person string) ([]MemoryRecord, error) { |
| + var out []MemoryRecord |
| + err := tx.Where("person = ? AND started_at IS NOT NULL AND ended = ?", person, false).Order("started_at, task_id").Find(&out).Error |
| + return out, err |
| +} |
| + |
| +// Enqueue writes one row, its payload sealed: over an unsent one with |
| +// the same collapse ID when it coalesces. |
| +func Enqueue(tx *gorm.DB, box Box, r OutboxRecord, coalesce bool) error { |
| + if len(r.Payload) > MaxPayload { |
| + return ErrTooLarge |
| + } |
| + sealed, err := box.seal(domainPayload, r.Payload) |
| + if err != nil { |
| + return err |
| + } |
| + r.Payload = sealed |
| + if coalesce { |
| + res := tx.Model(&OutboxRecord{}).Where("credential = ? AND collapse_id = ? AND state = ? AND lease_until IS NULL", r.Credential, r.CollapseID, StatePending).Select("payload", "priority", "next_at", "updated_at").Updates(map[string]any{"payload": r.Payload, "priority": r.Priority, "next_at": r.NextAt, "updated_at": r.UpdatedAt}) |
| + if res.Error != nil || res.RowsAffected > 0 { |
| + return res.Error |
| + } |
| + } |
| + r.ID = NewID() |
| + r.State = StatePending |
| + return tx.Create(&r).Error |
| +} |
| + |
| +// NewID is a row ID: a random (version 4) UUID, canonical and lowercase, |
| +// as apns-id must be. |
| +func NewID() string { |
| + var b [16]byte |
| + _, _ = rand.Read(b[:]) |
| + b[6] = b[6]&0x0f | 0x40 |
| + b[8] = b[8]&0x3f | 0x80 |
| + return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]) |
| +} |
| + |
| +// Once marks a once-only push decided for the person, and reports |
| +// whether this is the first time. |
| +func Once(tx *gorm.DB, person, key string, now time.Time) (bool, error) { |
| + res := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&OnceRecord{Person: person, Key: key, CreatedAt: now}) |
| + return res.RowsAffected == 1, res.Error |
| +} |
diff --git a/internal/equipo/push/testdata/activity-end.json b/internal/equipo/push/testdata/activity-end.json| new file mode 100644 |
| index 00000000..f31a93d6 |
| --- /dev/null |
| +++ b/internal/equipo/push/testdata/activity-end.json |
| @@ -0,0 +1,17 @@ |
| +{ |
| + "aps": { |
| + "timestamp": 1795176000, |
| + "event": "end", |
| + "content-state": { |
| + "task_id": "tk1", |
| + "title": "Fix login", |
| + "stage": "done", |
| + "specialist": "engineering", |
| + "activity": "", |
| + "needs_you": "", |
| + "tone": "positive", |
| + "outcome": "done" |
| + }, |
| + "dismissal-date": 1795179600 |
| + } |
| +} |
diff --git a/internal/equipo/push/testdata/activity-needs.json b/internal/equipo/push/testdata/activity-needs.json| new file mode 100644 |
| index 00000000..7aa14c88 |
| --- /dev/null |
| +++ b/internal/equipo/push/testdata/activity-needs.json |
| @@ -0,0 +1,15 @@ |
| +{ |
| + "aps": { |
| + "timestamp": 1795176000, |
| + "event": "update", |
| + "content-state": { |
| + "task_id": "tk1", |
| + "title": "Fix login", |
| + "stage": "ready_to_merge", |
| + "specialist": "engineering", |
| + "activity": "", |
| + "needs_you": "merge", |
| + "tone": "warning" |
| + } |
| + } |
| +} |
diff --git a/internal/equipo/push/testdata/activity-replaced.json b/internal/equipo/push/testdata/activity-replaced.json| new file mode 100644 |
| index 00000000..e317cfde |
| --- /dev/null |
| +++ b/internal/equipo/push/testdata/activity-replaced.json |
| @@ -0,0 +1,17 @@ |
| +{ |
| + "aps": { |
| + "timestamp": 1795176000, |
| + "event": "end", |
| + "content-state": { |
| + "task_id": "tk1", |
| + "title": "Fix login", |
| + "stage": "in_progress", |
| + "specialist": "engineering", |
| + "activity": "Reading README.md", |
| + "needs_you": "", |
| + "tone": "positive", |
| + "outcome": "replaced" |
| + }, |
| + "dismissal-date": 1795176000 |
| + } |
| +} |
diff --git a/internal/equipo/push/testdata/activity-start.json b/internal/equipo/push/testdata/activity-start.json| new file mode 100644 |
| index 00000000..30373829 |
| --- /dev/null |
| +++ b/internal/equipo/push/testdata/activity-start.json |
| @@ -0,0 +1,24 @@ |
| +{ |
| + "aps": { |
| + "alert": { |
| + "title": "Fix login", |
| + "body": "[push.activity.started]" |
| + }, |
| + "sound": "default", |
| + "timestamp": 1795176000, |
| + "event": "start", |
| + "content-state": { |
| + "task_id": "tk1", |
| + "title": "Fix login", |
| + "stage": "in_progress", |
| + "specialist": "engineering", |
| + "activity": "Reading README.md", |
| + "needs_you": "", |
| + "tone": "positive" |
| + }, |
| + "attributes-type": "EquipoTaskAttributes", |
| + "attributes": { |
| + "task_id": "tk1" |
| + } |
| + } |
| +} |
diff --git a/internal/equipo/push/testdata/activity-update.json b/internal/equipo/push/testdata/activity-update.json| new file mode 100644 |
| index 00000000..2c53c274 |
| --- /dev/null |
| +++ b/internal/equipo/push/testdata/activity-update.json |
| @@ -0,0 +1,15 @@ |
| +{ |
| + "aps": { |
| + "timestamp": 1795176000, |
| + "event": "update", |
| + "content-state": { |
| + "task_id": "tk1", |
| + "title": "Fix login", |
| + "stage": "in_progress", |
| + "specialist": "engineering", |
| + "activity": "Reading README.md", |
| + "needs_you": "", |
| + "tone": "positive" |
| + } |
| + } |
| +} |
diff --git a/internal/equipo/push/testdata/badge.json b/internal/equipo/push/testdata/badge.json| new file mode 100644 |
| index 00000000..a20f01ab |
| --- /dev/null |
| +++ b/internal/equipo/push/testdata/badge.json |
| @@ -0,0 +1,5 @@ |
| +{ |
| + "aps": { |
| + "badge": 2 |
| + } |
| +} |
diff --git a/internal/equipo/push/testdata/card.json b/internal/equipo/push/testdata/card.json| new file mode 100644 |
| index 00000000..ec33e8df |
| --- /dev/null |
| +++ b/internal/equipo/push/testdata/card.json |
| @@ -0,0 +1,16 @@ |
| +{ |
| + "aps": { |
| + "alert": { |
| + "title": "[push.card.title]", |
| + "body": "Merge the login fix?" |
| + }, |
| + "sound": "default", |
| + "category": "needs_you", |
| + "thread-id": "task:tk1" |
| + }, |
| + "equipo": { |
| + "kind": "card", |
| + "card_id": "c1", |
| + "task_id": "tk1" |
| + } |
| +} |
diff --git a/internal/equipo/push/testdata/reply.json b/internal/equipo/push/testdata/reply.json| new file mode 100644 |
| index 00000000..6e416f51 |
| --- /dev/null |
| +++ b/internal/equipo/push/testdata/reply.json |
| @@ -0,0 +1,13 @@ |
| +{ |
| + "aps": { |
| + "alert": { |
| + "title": "[push.reply.title]", |
| + "body": "Done. The fix is on its branch." |
| + }, |
| + "sound": "default" |
| + }, |
| + "equipo": { |
| + "kind": "reply", |
| + "turn_id": "t1" |
| + } |
| +} |
diff --git a/internal/equipo/push/testdata/task-done.json b/internal/equipo/push/testdata/task-done.json| new file mode 100644 |
| index 00000000..c7d93c99 |
| --- /dev/null |
| +++ b/internal/equipo/push/testdata/task-done.json |
| @@ -0,0 +1,14 @@ |
| +{ |
| + "aps": { |
| + "alert": { |
| + "title": "Fix login", |
| + "body": "[push.task.done]" |
| + }, |
| + "thread-id": "task:tk1", |
| + "interruption-level": "passive" |
| + }, |
| + "equipo": { |
| + "kind": "task", |
| + "task_id": "tk1" |
| + } |
| +} |
diff --git a/internal/equipo/push/testdata/task-failed.json b/internal/equipo/push/testdata/task-failed.json| new file mode 100644 |
| index 00000000..d2131e6b |
| --- /dev/null |
| +++ b/internal/equipo/push/testdata/task-failed.json |
| @@ -0,0 +1,14 @@ |
| +{ |
| + "aps": { |
| + "alert": { |
| + "title": "Fix login", |
| + "body": "[push.task.failed]" |
| + }, |
| + "thread-id": "task:tk1", |
| + "interruption-level": "passive" |
| + }, |
| + "equipo": { |
| + "kind": "task", |
| + "task_id": "tk1" |
| + } |
| +} |
diff --git a/internal/equipo/push/transport.go b/internal/equipo/push/transport.go| new file mode 100644 |
| index 00000000..126d92ac |
| --- /dev/null |
| +++ b/internal/equipo/push/transport.go |
| @@ -0,0 +1,137 @@ |
| +package push |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "log/slog" |
| + "strconv" |
| + "strings" |
| + "time" |
| +) |
| + |
| +// Logged is the local and staging transport: it sends nothing and logs |
| +// that a push would have gone, with its kind and size but never its |
| +// token, anything derived from it, or its payload (a payload can quote a |
| +// person's card). Boot allows it only on loopback or a staging origin |
| +// (EQUIPO_ALLOW_LOGGED_PUSH), as EQUIPO_ALLOW_LOGGED_MAIL is for mail. |
| +type Logged struct { |
| + Logger *slog.Logger |
| + // Sent sees each message (tests and the local drive); nil is none. |
| + Sent func(Message) |
| +} |
| + |
| +// Send logs the push and answers as Apple would to a delivered one. |
| +func (l Logged) Send(_ context.Context, m Message) (Result, error) { |
| + if l.Sent != nil { |
| + l.Sent(m) |
| + } |
| + if l.Logger != nil { |
| + l.Logger.Info("push logged", "id", m.ID, "type", m.PushType, "priority", m.Priority, "collapse", m.CollapseID, "environment", m.Environment, "bytes", len(m.Payload)) |
| + } |
| + return Result{Status: 200, APNsID: m.ID}, nil |
| +} |
| + |
| +// CarlosPushEnv is set to "submit" by the CARLOS agent when the platform |
| +// sends this instance's pushes (D1: the Apple key stays on the CARLOS box). |
| +const CarlosPushEnv = "CARLOS_PUSH" |
| + |
| +// ErrCarlosPushUnavailable refuses boot when CARLOS_PUSH=submit asks for a |
| +// transport this build does not have yet. |
| +var ErrCarlosPushUnavailable = errors.New("push: CARLOS push submission is not available in this build") |
| + |
| +// FromCarlos is the CARLOS platform push submission transport: POST |
| +// /v1/push on the instance's control socket ($CARLOS_CONTROL_SOCKET) with |
| +// Authorization: Bearer $CARLOS_ADMIN_TOKEN, as mail's submit |
| +// (mail.FromCarlos). The contract (carlos/platform, design/platform-push- |
| +// submission, docs/superpowers/specs/2026-11-20-platform-push-submission- |
| +// design.md §4, awaiting Paul) is here already: the body is |
| +// CarlosRequestOf(m), the answer CarlosResult(status, Retry-After, body), |
| +// and the Sender acts on every outcome (Judge). |
| +// |
| +// SEAM (2026-11-20): neither the CARLOS verb nor rastrillo's push client |
| +// exists yet. When they land, build the client here from the process |
| +// environment and return it as a Transport: it sends CarlosRequestOf(m) |
| +// and returns CarlosResult of the answer, retrying nothing itself (the |
| +// outbox retries). Until then CARLOS_PUSH=submit refuses boot rather than |
| +// dropping pushes silently. |
| +func FromCarlos(getenv func(string) string) (Transport, error) { |
| + if getenv(CarlosPushEnv) != "submit" { |
| + return nil, nil |
| + } |
| + return nil, ErrCarlosPushUnavailable |
| +} |
| + |
| +// CarlosMaxBody is the verb's limit on a request body. |
| +const CarlosMaxBody = 8 << 10 |
| + |
| +// CarlosRequest is the verb's request body (§4.1). |
| +type CarlosRequest struct { |
| + DeviceToken string `json:"device_token"` |
| + Topic string `json:"topic"` |
| + PushType string `json:"push_type"` |
| + Priority int `json:"priority"` |
| + CollapseID string `json:"collapse_id,omitempty"` |
| + Expiration *int64 `json:"expiration,omitempty"` |
| + APNsID string `json:"apns_id,omitempty"` |
| + Environment string `json:"environment"` |
| + Payload json.RawMessage `json:"payload"` |
| +} |
| + |
| +// CarlosRequestOf is a message as the verb takes it: the payload a |
| +// compact JSON object of at most MaxPayload bytes, the whole body at most |
| +// CarlosMaxBody. |
| +func CarlosRequestOf(m Message) ([]byte, error) { |
| + var payload bytes.Buffer |
| + if err := json.Compact(&payload, m.Payload); err != nil || payload.Len() == 0 || payload.Bytes()[0] != '{' { |
| + return nil, errors.New("push: payload is not a JSON object") |
| + } |
| + if payload.Len() > MaxPayload { |
| + return nil, ErrTooLarge |
| + } |
| + r := CarlosRequest{DeviceToken: m.Token, Topic: m.Topic, PushType: m.PushType, Priority: m.Priority, CollapseID: m.CollapseID, APNsID: m.ID, Environment: m.Environment, Payload: payload.Bytes()} |
| + if !m.Expiration.IsZero() { |
| + at := m.Expiration.Unix() |
| + r.Expiration = &at |
| + } |
| + raw, err := json.Marshal(r) |
| + if err == nil && len(raw) > CarlosMaxBody { |
| + return nil, ErrTooLarge |
| + } |
| + return raw, err |
| +} |
| + |
| +// carlosAnswer is the verb's answer body: Apple's answer on a 200 |
| +// (status, apns_id, reason, timestamp in milliseconds on a 410), the |
| +// platform's code otherwise. |
| +type carlosAnswer struct { |
| + Status int `json:"status"` |
| + APNsID string `json:"apns_id"` |
| + Reason string `json:"reason"` |
| + Timestamp int64 `json:"timestamp"` |
| + Code string `json:"code"` |
| +} |
| + |
| +// CarlosResult reads the verb's answer (§4.2): a 200 is Apple's answer, |
| +// passed through; anything else is the platform's refusal, its code (a |
| +// 401's body is plain text: no code) and Retry-After in seconds. |
| +func CarlosResult(status int, retryAfter string, body []byte) (Result, error) { |
| + var a carlosAnswer |
| + if status == 200 { |
| + if err := json.Unmarshal(body, &a); err != nil || a.Status == 0 { |
| + return Result{}, errors.New("push: CARLOS answered 200 without Apple's answer") |
| + } |
| + r := Result{Status: a.Status, Reason: a.Reason, APNsID: a.APNsID} |
| + if a.Timestamp > 0 { |
| + r.Timestamp = time.UnixMilli(a.Timestamp).UTC() |
| + } |
| + return r, nil |
| + } |
| + _ = json.Unmarshal(body, &a) |
| + r := Result{Refused: status, Code: a.Code} |
| + if n, err := strconv.Atoi(strings.TrimSpace(retryAfter)); err == nil && n > 0 { |
| + r.RetryAfter = time.Duration(n) * time.Second |
| + } |
| + return r, nil |
| +} |
diff --git a/internal/equipo/push_config_test.go b/internal/equipo/push_config_test.go| new file mode 100644 |
| index 00000000..2fba36ee |
| --- /dev/null |
| +++ b/internal/equipo/push_config_test.go |
| @@ -0,0 +1,59 @@ |
| +package equipo |
| + |
| +import ( |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/push" |
| +) |
| + |
| +// TestLoggedPushBoundary: logged push, like logged mail, only on loopback |
| +// or a staging origin, refused at LoadConfig and again by Pusher. |
| +func TestLoggedPushBoundary(t *testing.T) { |
| + for origin, allowed := range map[string]bool{ |
| + "http://127.0.0.1:4321": true, |
| + "https://equipo-staging-0123456789abcdef.bds.oncarlos.com": true, |
| + "https://equipo.bds.oncarlos.com": false, |
| + "https://equipo-staging-0123456789abcdef.bds.oncarlos.com.evil.test": false, |
| + } { |
| + env := map[string]string{"EQUIPO_ORIGIN": origin, "EQUIPO_INSTANCE_KEY": "k", "CARLOS_MAIL": "submit", "EQUIPO_ALLOW_LOGGED_PUSH": "1"} |
| + cfg, err := LoadConfig(func(k string) string { return env[k] }) |
| + if (err == nil) != allowed { |
| + t.Fatalf("%s: allowed=%v error=%v", origin, allowed, err) |
| + } |
| + if _, err := Pusher(Config{Origin: origin, InstanceKey: "k", AllowLoggedPush: true}, nil, func(string) string { return "" }); (err == nil) != allowed { |
| + t.Fatalf("%s: Pusher allowed=%v error=%v", origin, allowed, err) |
| + } |
| + if allowed { |
| + if tr, err := Pusher(cfg, nil, func(string) string { return "" }); err != nil || tr == nil { |
| + t.Fatalf("%s: no logged transport %v", origin, err) |
| + } else if _, ok := tr.(push.Logged); !ok { |
| + t.Fatalf("%s: %T", origin, tr) |
| + } |
| + } |
| + } |
| +} |
| + |
| +// TestPusherChannels: no push setting is no push at all; CARLOS_PUSH=submit |
| +// refuses until the platform's push submission exists (the seam). |
| +func TestPusherChannels(t *testing.T) { |
| + cfg := Config{Origin: "https://equipo.bds.oncarlos.com", InstanceKey: "k"} |
| + if tr, err := Pusher(cfg, nil, func(string) string { return "" }); tr != nil || err != nil { |
| + t.Fatalf("unset: %v %v", tr, err) |
| + } |
| + _, err := Pusher(cfg, nil, func(k string) string { return map[string]string{push.CarlosPushEnv: "submit"}[k] }) |
| + if err == nil || err.Error() != copyCarlosPushUnavailable { |
| + t.Fatalf("submit: %v", err) |
| + } |
| +} |
| + |
| +// TestPusherRefusesBoth: logged push and CARLOS submission together refuse |
| +// boot, never one silently over the other. |
| +func TestPusherRefusesBoth(t *testing.T) { |
| + cfg := Config{Origin: "http://127.0.0.1:4321", InstanceKey: "k", AllowLoggedPush: true} |
| + for _, v := range []string{"submit", "anything"} { |
| + _, err := Pusher(cfg, nil, func(k string) string { return map[string]string{push.CarlosPushEnv: v}[k] }) |
| + if err == nil || err.Error() != copyPushBoth { |
| + t.Fatalf("%s: %v", v, err) |
| + } |
| + } |
| +} |
diff --git a/internal/equipo/setup/invites.go b/internal/equipo/setup/invites.go| index 213c4ebc..e6bc8c7d 100644 |
| --- a/internal/equipo/setup/invites.go |
| +++ b/internal/equipo/setup/invites.go |
| @@ -59,6 +59,10 @@ type Dependencies struct { |
| Member func(*gorm.DB, string) (kernel.Member, error) |
| Audit func(*gorm.DB, kernel.Actor, string, string) error |
| Invalid, Forbidden, NotFound, Conflict, Unavailable, Expired error |
| + |
| + // ForgetPush deletes a removed person's push registrations; nil is |
| + // none to forget. |
| + ForgetPush func(*gorm.DB, string) error |
| } |
| type Store struct { |
| tx *gorm.DB |
diff --git a/internal/equipo/setup/roster.go b/internal/equipo/setup/roster.go| index 4fa232bf..11373295 100644 |
| --- a/internal/equipo/setup/roster.go |
| +++ b/internal/equipo/setup/roster.go |
| @@ -123,6 +123,11 @@ func (s *Store) SetMember(actor Actor, address string, role Role, active bool, r |
| if err := s.deps.RevokeRunners(tx, address); err != nil { |
| return err |
| } |
| + if s.deps.ForgetPush != nil { |
| + if err := s.deps.ForgetPush(tx, address); err != nil { |
| + return err |
| + } |
| + } |
| if err := tx.Exec("DELETE FROM sessions WHERE subject = ?", address).Error; err != nil { |
| return err |
| } |
diff --git a/internal/plan3test/plan3_release_test.go b/internal/plan3test/plan3_release_test.go| index e67e4abb..90187195 100644 |
| --- a/internal/plan3test/plan3_release_test.go |
| +++ b/internal/plan3test/plan3_release_test.go |
| @@ -187,8 +187,11 @@ func plan3CopyInventory(t *testing.T) { |
| // Luna's delegated pass on the boot refusal for CARLOS mail submission. |
| acceptedInjection := slices.Contains([]string{"autonomy.title", "autonomy.lede", "autonomy.auto_merge_ci", "autonomy.auto_merge_ci_help", "autonomy.public_previews", "autonomy.public_previews_help", "autonomy.empty", "work.reason.base_checks_failed", "chat.merge.not.base_failed", "chat.merge.not.base_checks", "chat.merge.not.gates", "chat.merge.not.review_truncated", "work.reason.base_gate_unavailable", "work.reason.preview_secrets", "work.reason.preview_scanner", "work.reason.preview_public_disabled", "work.reason.preview_host", "work.reason.preview_headers", "autonomy.auto_merge_sensitive", "autonomy.auto_merge_sensitive_help", "work.reason.preview_header_missing", "preview.unsafe_question", "preview.unsafe_help", "preview.unsafe_open", "preview.wrapper_title"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Astra, 2026-11-19)") |
| acceptedMail := key == "copyMissingSMTP" && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Luna, 2026-11-17)") |
| + // Luna's delegated pass on native slice 2's push strings and API |
| + // prose (Paul, 2026-11-20: Luna's verdicts are the review). |
| + acceptedPush := slices.Contains([]string{"copyLoggedPushPublic", "copyCarlosPushUnavailable", "copyPushBoth", "push.card.title", "push.card.body", "push.reply.title", "push.task.done", "push.task.cancelled", "push.task.failed", "push.activity.started", "docs/api/equipo-v1.md / Talk to your Coordinator from a device: set aside", "docs/api/equipo-v1.md / Receive pushes on a device"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20)") |
| acceptedCopy := strings.TrimSuffix(cells[3], " |") == "COPY ACCEPTED BY DELEGATION (Copy, record-bound) sha256:"+copydesk.Hash(rows[key]) |
| - if !acceptedInjection && !acceptedMail && !acceptedAccess && !acceptedPlacementEdges && !acceptedPlacement && !acceptedReportActions && !acceptedRoster && !acceptedCopy && !strings.Contains(cells[3], "COPY REVIEW REQUIRED") && !acceptedAll && !acceptedGuide && !acceptedRound2 && !acceptedStarter && !acceptedDelegation && !approvedPublish && !approvedAssistant && !approvedJobs && !approvedOficina { |
| + if !acceptedInjection && !acceptedMail && !acceptedPush && !acceptedAccess && !acceptedPlacementEdges && !acceptedPlacement && !acceptedReportActions && !acceptedRoster && !acceptedCopy && !strings.Contains(cells[3], "COPY REVIEW REQUIRED") && !acceptedAll && !acceptedGuide && !acceptedRound2 && !acceptedStarter && !acceptedDelegation && !approvedPublish && !approvedAssistant && !approvedJobs && !approvedOficina { |
| t.Fatal("entry has no copy review status or applicable acceptance", key) |
| } |
| } |
diff --git a/internal/plan3test/push_device_test.go b/internal/plan3test/push_device_test.go| new file mode 100644 |
| index 00000000..2a5653dd |
| --- /dev/null |
| +++ b/internal/plan3test/push_device_test.go |
| @@ -0,0 +1,85 @@ |
| +package plan3test |
| + |
| +import ( |
| + "errors" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/push" |
| + "gorm.io/gorm" |
| +) |
| + |
| +const pushToken = "aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11" |
| + |
| +func registerPush(t *testing.T, f *fixture, token string) { |
| + t.Helper() |
| + w := deviceRequest(t, f, token, "POST", "/api/v1/push-registrations", `{"token":"`+pushToken+`","environment":"production","platform":"ios","start_token":"`+strings.ToUpper(pushToken)+`"}`, "push", "") |
| + expectHTTP(t, w, 200) |
| + if strings.Contains(strings.ToLower(w.Body.String()), pushToken) || !strings.Contains(w.Body.String(), `"live_activities":true`) { |
| + t.Fatal("registration answer", w.Body.String()) |
| + } |
| +} |
| + |
| +// pushCurrent is the sender's own check of a device: nil while it may be |
| +// pushed to. |
| +func pushCurrent(t *testing.T, f *fixture, credential string) error { |
| + t.Helper() |
| + s := f.Store.Chat().PushSender(push.Logged{}) |
| + var out error |
| + must(t, f.DB.G.Transaction(func(tx *gorm.DB) error { out = s.Check(tx, owner.Address, credential); return nil })) |
| + return out |
| +} |
| + |
| +// TestPushRegistrationLifetime: a paired device registers with its own |
| +// bearer (a browser session cannot); the registration is the |
| +// credential's, never audited with its tokens, and it goes when the |
| +// device is revoked or its person is removed, after which the sender's |
| +// check refuses the device. |
| +func TestPushRegistrationLifetime(t *testing.T) { |
| + f := newFixture(t) |
| + cred := approvedDevice(t, f) |
| + expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/push-registrations", `{"token":"`+pushToken+`","environment":"production","platform":"ios"}`, "browser", ""), 401) |
| + registerPush(t, f, cred.Token) |
| + registerPush(t, f, cred.Token) |
| + if f.count(t, "SELECT count(*) FROM push_registrations WHERE credential = ? AND person = ?", cred.ID, owner.Address) != 1 { |
| + t.Fatal("not one registration for the device") |
| + } |
| + if f.count(t, "SELECT count(*) FROM audit_events WHERE kind = 'push.register' AND record_id = ?", cred.ID) != 2 || f.count(t, "SELECT count(*) FROM audit_events WHERE lower(record_id) LIKE ? OR lower(kind) LIKE ?", "%"+pushToken+"%", "%"+pushToken+"%") != 0 { |
| + t.Fatal("registration audit") |
| + } |
| + if err := pushCurrent(t, f, cred.ID); err != nil { |
| + t.Fatal("a current device refused", err) |
| + } |
| + // Sealed at rest with the instance key: no token in the table. |
| + if f.count(t, "SELECT count(*) FROM push_registrations WHERE lower(token) LIKE ? OR lower(start_token) LIKE ?", "%"+pushToken+"%", "%"+pushToken+"%") != 0 { |
| + t.Fatal("a token kept in the clear") |
| + } |
| + // Only revocation or removal is gone: an expired credential is not |
| + // current now, and keeps its registration. |
| + var expires time.Time |
| + must(t, f.DB.G.Raw("SELECT token_expires_at FROM person_devices WHERE id = ?", cred.ID).Scan(&expires).Error) |
| + must(t, f.DB.G.Exec("UPDATE person_devices SET token_expires_at = ? WHERE id = ?", time.Now().Add(-time.Hour).UTC(), cred.ID).Error) |
| + if err := pushCurrent(t, f, cred.ID); !errors.Is(err, push.ErrNotCurrent) { |
| + t.Fatal("an expired device", err) |
| + } |
| + must(t, f.DB.G.Exec("UPDATE person_devices SET token_expires_at = ? WHERE id = ?", expires, cred.ID).Error) |
| + expectHTTP(t, deviceRequest(t, f, cred.Token, "DELETE", "/api/v1/auth/devices/"+cred.ID, `{}`, "revoke", `"3"`), 200) |
| + if f.count(t, "SELECT count(*) FROM push_registrations") != 0 { |
| + t.Fatal("a revoked device kept its registration") |
| + } |
| + if err := pushCurrent(t, f, cred.ID); !errors.Is(err, push.ErrGone) { |
| + t.Fatal("a revoked device may still be pushed", err) |
| + } |
| + |
| + second := approvedDevice(t, f) |
| + registerPush(t, f, second.Token) |
| + must(t, f.Store.SetMember(ctx, peer, owner.Address, equipo.RoleMember, false, 1)) |
| + if f.count(t, "SELECT count(*) FROM push_registrations") != 0 { |
| + t.Fatal("a removed person kept a registration") |
| + } |
| + if err := pushCurrent(t, f, second.ID); !errors.Is(err, push.ErrGone) { |
| + t.Fatal("a removed person's device may still be pushed", err) |
| + } |
| +} |
diff --git a/internal/wire/api.go b/internal/wire/api.go| index 2195f0e0..5d60196f 100644 |
| --- a/internal/wire/api.go |
| +++ b/internal/wire/api.go |
| @@ -380,6 +380,9 @@ type Card struct { |
| Site *CardSite `json:"site,omitempty"` |
| // Advice is an advice card's advice; absent on every other card. |
| Advice *Advice `json:"advice,omitempty"` |
| + // Aside: the person set the card aside (POST /cards/{id}/visibility). |
| + // It still waits on them and stays in Needs you; absent when not. |
| + Aside bool `json:"aside,omitempty"` |
| } |
| // AnswerCard is the body of POST /api/v1/cards/{id}/answer. Revision must |
diff --git a/internal/wire/push.go b/internal/wire/push.go| new file mode 100644 |
| index 00000000..5fb64e64 |
| --- /dev/null |
| +++ b/internal/wire/push.go |
| @@ -0,0 +1,128 @@ |
| +package wire |
| + |
| +import "time" |
| + |
| +// Push (native slice 2, plan 2026-11-20-equipo-native-slice-2.md): a |
| +// paired device registers its APNs token; the engine writes pushes to an |
| +// outbox in the transaction of the change; a sender delivers them. |
| + |
| +// Push environments: the APNs gateway a token belongs to. |
| +const ( |
| + APNsProduction = "production" |
| + APNsDevelopment = "development" |
| +) |
| + |
| +// Device platforms. Only iOS starts Live Activities (macOS shows the |
| +// iPhone's in its menu bar). |
| +const ( |
| + PlatformIOS = "ios" |
| + PlatformMacOS = "macos" |
| +) |
| + |
| +// MaxPushToken bounds an APNs token in hex: Apple's are 32 bytes today |
| +// and may grow. |
| +const MaxPushToken = 400 |
| + |
| +// RegisterPush is the body of POST /api/v1/push-registrations: the |
| +// device's APNs token, its environment and platform, and on iPhone the |
| +// Live Activity push-to-start token. It is bound to the paired device |
| +// credential that sends it and replaces that credential's earlier one. |
| +type RegisterPush struct { |
| + Token string `json:"token"` |
| + Environment string `json:"environment"` |
| + Platform string `json:"platform"` |
| + StartToken string `json:"start_token,omitempty"` |
| +} |
| + |
| +// PushRegistration is what the server keeps for the device, without its |
| +// tokens (which are never echoed). LiveActivities is whether a |
| +// push-to-start token is on file. |
| +type PushRegistration struct { |
| + Environment string `json:"environment"` |
| + Platform string `json:"platform"` |
| + LiveActivities bool `json:"live_activities"` |
| + UpdatedAt time.Time `json:"updated_at"` |
| +} |
| + |
| +// RegisterActivity is the body of POST |
| +// /api/v1/push-registrations/activities: a running Live Activity's own |
| +// update token, for the task it follows. The server forgets it when the |
| +// activity ends. |
| +type RegisterActivity struct { |
| + TaskID string `json:"task_id"` |
| + Token string `json:"token"` |
| +} |
| + |
| +// LiveActivityAttributesType is the app's ActivityAttributes type, named in a |
| +// push-to-start payload ("attributes-type"). |
| +const LiveActivityAttributesType = "EquipoTaskAttributes" |
| + |
| +// LiveActivityAttributes are a task Live Activity's fixed attributes. |
| +type LiveActivityAttributes struct { |
| + TaskID string `json:"task_id"` |
| +} |
| + |
| +// Live Activity tones, as Roster's stage track: amber waits on you, red |
| +// only for a failure. |
| +const ( |
| + TonePositive = "positive" |
| + ToneWarning = "warning" |
| + ToneNegative = "negative" |
| +) |
| + |
| +// Live Activity and task outcomes. |
| +const ( |
| + PushOutcomeDone = "done" |
| + PushOutcomeCancelled = "cancelled" |
| + PushOutcomeFailed = "failed" |
| + // PushOutcomeReplaced ends an activity to make room for a newer |
| + // task's (at most MaxLiveActivities a person). |
| + PushOutcomeReplaced = "replaced" |
| +) |
| + |
| +// MaxLiveActivities is how many task Live Activities a person has at |
| +// once: the most recently started tasks'. |
| +const MaxLiveActivities = 3 |
| + |
| +// LiveActivityState is a task Live Activity's content state, the app's |
| +// Codable ContentState: the task, its stage (Task.stage), the specialist |
| +// working on it (Step.specialist), the newest activity line, what it |
| +// needs from you (Task.needs_you, "" when nothing), the tone, and once it |
| +// ended, the outcome. |
| +type LiveActivityState struct { |
| + TaskID string `json:"task_id"` |
| + Title string `json:"title"` |
| + Stage string `json:"stage"` |
| + Specialist string `json:"specialist"` |
| + Activity string `json:"activity"` |
| + NeedsYou string `json:"needs_you"` |
| + Tone string `json:"tone"` |
| + Outcome string `json:"outcome,omitempty"` |
| +} |
| + |
| +// PushData is what an alert carries beside aps, under "equipo", for the |
| +// app to open the right place when it is tapped: a card, a task, or the |
| +// conversation (a reply). |
| +type PushData struct { |
| + Kind string `json:"kind"` |
| + CardID string `json:"card_id,omitempty"` |
| + TaskID string `json:"task_id,omitempty"` |
| + TurnID string `json:"turn_id,omitempty"` |
| +} |
| + |
| +// PushData kinds. |
| +const ( |
| + PushCard = "card" |
| + PushReply = "reply" |
| + PushTask = "task" |
| + PushBadge = "badge" |
| +) |
| + |
| +// SetCardVisibility is the body of POST /api/v1/cards/{id}/visibility: |
| +// set the card aside (or bring it back) for the person, at the card's |
| +// current revision. It never answers, cancels or starts anything; the |
| +// card stays in Needs you. |
| +type SetCardVisibility struct { |
| + Aside bool `json:"aside"` |
| + Revision int64 `json:"revision"` |
| +} |
diff --git a/internal/wire/wireschema/wireschema.go b/internal/wire/wireschema/wireschema.go| index bbd6712d..920fc4be 100644 |
| --- a/internal/wire/wireschema/wireschema.go |
| +++ b/internal/wire/wireschema/wireschema.go |
| @@ -107,7 +107,13 @@ var Ops = map[string]Op{ |
| "GET /advice": {nil, map[string]any{"200": wire.AdviceList{}}}, |
| "POST /advice/{id}/act": {wire.AdviceAction{}, map[string]any{"200": wire.Advice{}}}, |
| "POST /advice/{id}/dismiss": {wire.AdviceAction{}, map[string]any{"200": wire.Advice{}}}, |
| - "GET /events": {nil, map[string]any{"200": wire.Event{}}}, |
| + |
| + // Push and set aside (native slice 2). |
| + "POST /cards/{id}/visibility": {wire.SetCardVisibility{}, map[string]any{"200": wire.Card{}, "409": wire.CardConflict{}}}, |
| + "POST /push-registrations": {wire.RegisterPush{}, map[string]any{"200": wire.PushRegistration{}}}, |
| + "POST /push-registrations/activities": {wire.RegisterActivity{}, map[string]any{"204": nil}}, |
| + |
| + "GET /events": {nil, map[string]any{"200": wire.Event{}}}, |
| } |
| // EventData is what each kind of event on GET /events carries in |
| @@ -167,8 +173,14 @@ var Enums = map[string][]string{ |
| "UsageTotals.by": wire.UsageGroupings, |
| "CardConflict.code": {"card_stale", "card_answered"}, |
| "ActionConflict.code": {"not_undoable"}, |
| - "Event.type": eventKeys(0), |
| - "Event.resource": eventKeys(1), |
| + |
| + "RegisterPush.environment": {wire.APNsProduction, wire.APNsDevelopment}, |
| + "RegisterPush.platform": {wire.PlatformIOS, wire.PlatformMacOS}, |
| + "PushRegistration.environment": {wire.APNsProduction, wire.APNsDevelopment}, |
| + "PushRegistration.platform": {wire.PlatformIOS, wire.PlatformMacOS}, |
| + |
| + "Event.type": eventKeys(0), |
| + "Event.resource": eventKeys(1), |
| } |
| // eventKeys are the event types (part 0) or resources (part 1) |
diff --git a/internal/wire/wireschema/wireschema_test.go b/internal/wire/wireschema/wireschema_test.go| index 425731f2..a88f818b 100644 |
| --- a/internal/wire/wireschema/wireschema_test.go |
| +++ b/internal/wire/wireschema/wireschema_test.go |
| @@ -159,6 +159,11 @@ var families = map[string]struct{ prefix, other, zero string }{ |
| "UsageTotals.period": {"Usage", "UsageByConnection UsageByRole UsageByProject UsageByTask UsageByModel UsageProbe", ""}, // probe: a usage row's role |
| "UsageTotals.by": {"UsageBy", "", ""}, |
| "Event.type": {"Event", "EventPing EventGlance", ""}, // a ping is not an Event; a glance is the Assistant's |
| + |
| + "RegisterPush.environment": {"APNs", "", ""}, |
| + "RegisterPush.platform": {"Platform", "", ""}, |
| + "PushRegistration.environment": {"APNs", "", ""}, |
| + "PushRegistration.platform": {"Platform", "", ""}, |
| } |
| // parseGo parses the Go files in dir, tests apart. |