Add bound notification actions and direct card reads
54 files changed,
+2,401
−80
.rastrillo/budgets.txt+8 −4docs/api/equipo-v1.md+45 −0docs/api/equipo-v1.openapi.json+232 −20docs/superpowers/plans/2026-11-27-notification-actions.md+1 −1docs/superpowers/plans/CONTROLLER-REPORT-notification-actions.md+136 −0internal/equipo/app.go+1 −0internal/equipo/chat/card_read.go+35 −0internal/equipo/chat/http.go+45 −2internal/equipo/chat/notification_actions_test.go+75 −1internal/equipo/chat/notification_card_test.go+114 −0internal/equipo/chat/notification_http_test.go+105 −0internal/equipo/chat/notification_payload.go+67 −0internal/equipo/chat/notification_payload_test.go+235 −0internal/equipo/chat/projects.go+2 −1internal/equipo/chat/push.go+13 −1internal/equipo/config.go+4 −0internal/equipo/conversation/card_id_test.go+44 −0internal/equipo/migrations/schema.sql+9 −1internal/equipo/notification_config_test.go+16 −0internal/equipo/person_api.go+1 −1internal/equipo/personapi/conversation.go+7 −5internal/equipo/personapi/handler.go+1 −0internal/equipo/personapi/notification_capability_test.go+29 −0internal/equipo/push/store.go+22 −10internal/plan3test/notification_card_test.go+46 −0internal/plan3test/person_api_device_contract_test.go+1 −1internal/wire/push.go+23 −8internal/wire/wireschema/notification_test.go+39 −0internal/wire/wireschema/wireschema.go+29 −3internal/wire/wireschema/wireschema_test.go+10 −0native/apple/Sources/EquipoKit/API/Push.swift+16 −0native/apple/Sources/EquipoKit/Pairing/DeviceAccount.swift+17 −0native/apple/Sources/EquipoKit/Push/NotificationDispatcher.swift+174 −0native/apple/Sources/EquipoKit/Push/NotificationResponse.swift+96 −0native/apple/Sources/EquipoKit/Push/NotificationSelection.swift+15 −0native/apple/Sources/EquipoKit/Push/Notifications.swift+12 −7native/apple/Sources/EquipoKit/Push/PhoneDelegate.swift+2 −1native/apple/Sources/EquipoKit/Push/PushRegistrar.swift+15 −3native/apple/Sources/EquipoKit/Push/PushRoute.swift+1 −2native/apple/Sources/EquipoKit/Session/EquipoSession.swift+9 −0native/apple/Sources/EquipoKit/UI/NotificationActionPresenter.swift+62 −0native/apple/Sources/EquipoKit/UI/NotificationFixture.swift+101 −0native/apple/Sources/EquipoKit/UI/Screens/AppModel.swift+16 −1native/apple/Sources/EquipoKit/UI/Screens/PhoneRoot.swift+2 −0native/apple/Sources/EquipoKit/UI/TaskConfirmationSheet.swift+4 −3native/apple/Sources/EquipoKit/UI/TaskViewFixture.swift+1 −1native/apple/Sources/EquipoMac/EquipoMacApp.swift+6 −2native/apple/Tests/EquipoKitTests/NotificationActionTests.swift+97 −0native/apple/Tests/EquipoKitTests/NotificationDispatchTests.swift+202 −0native/apple/Tests/EquipoKitTests/NotificationJournalTests.swift+38 −0native/ios/Sources/EquipoPhoneApp.swift+2 −1native/ios/UITests/NotificationActionUITests.swift+34 −0native/ios/project.yml+20 −0native/share/Sources/EquipoShareCore/ActionJournal.swift+64 −0
CI failed — 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/notify__actions: Type Size Avail | ext4 96G 85G
ci-box: disk /home/ci/.cache/equipo-ci-box: Type Size Avail | ext4 96G 85G
ci-box: bwrap: fetched and verified in 0.3s
ci-box: claude: fetched and verified in 1.6s
ci-box: codex: fetched and verified in 4.7s
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 9.9s
ci-box: pi: installed and verified in 7.5s
ci-box: opencode: installed and verified in 2.3s
ci-box: chromium 156.0.8078.79-1~deb13u1: 76 packages fetched, verified and unpacked in 9.5s
ci-box: clone deepened in 4.2s
ci-box: file times set from content: 3200 files, 211 directories
ci-box: ready in 19.2s
=== 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.143s
=== compile ===
go build ./...
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py compile
+ go build -tags testbuild ./...
4.4s
+ go list -export -test -tags testbuild -f ./...
4.9s
+ go list -export -test -tags browser,testbuild -f ./internal/equipo ./internal/headless ./internal/idtest ./internal/plan3test ./internal/thintest
3.3s
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-24 15:56:00 +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 1m17.643s 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 1m15.018s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m15.02s amadan.net/oficina/equipo/internal/headless TestHeadless
machine: 32 CPUs, load 64.47, cpu waiting 41.70%, memory waiting 0.00%, io waiting 0.49%
--- 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 1m18.262s 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 1m16.054s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m16.05s amadan.net/oficina/equipo/internal/headless TestHeadless
machine: 32 CPUs, load 64.47, cpu waiting 41.70%, memory waiting 0.00%, io waiting 0.49%
--- 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 1m18.386s 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 1m16.1s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m6.31s amadan.net/oficina/equipo/internal/headless TestHeadlessConnections
receipt: slow test 5.39s amadan.net/oficina/equipo/internal/headless TestHeadlessTokenPasteEndToEnd
receipt: slow test 4.4s amadan.net/oficina/equipo/internal/headless TestHeadlessTokenConnection
machine: 32 CPUs, load 64.19, cpu waiting 41.64%, memory waiting 0.00%, io waiting 0.47%
--- 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 1m15.834s 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.633s amadan.net/oficina/equipo/internal/headless
receipt: slow test 36.77s amadan.net/oficina/equipo/internal/headless TestMacWorker
receipt: slow test 19.09s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 9.06s amadan.net/oficina/equipo/internal/headless TestHeadlessPrewarm
receipt: slow test 8.71s amadan.net/oficina/equipo/internal/headless TestHeadlessAttachments
machine: 32 CPUs, load 64.47, cpu waiting 41.45%, memory waiting 0.00%, io waiting 0.51%
--- 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_step_refused$|^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 1m34.363s 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 1m31.829s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m2.29s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 9.47s amadan.net/oficina/equipo/internal/headless TestHeadlessRunnerKillLeavesNoCopies
receipt: slow test 8.21s amadan.net/oficina/equipo/internal/headless TestHeadlessCopyRotation
receipt: slow test 7.05s amadan.net/oficina/equipo/internal/headless TestHeadlessPolicyGuards
receipt: slow test 4.82s amadan.net/oficina/equipo/internal/headless TestHeadlessNewHouseRuleStartsFresh
machine: 32 CPUs, load 61.64, cpu waiting 41.30%, memory waiting 0.00%, io waiting 0.37%
--- 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_step_refused$|^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 2m45.058s 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 2m42.39s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m37.27s amadan.net/oficina/equipo/internal/headless TestHeadlessAssistant
receipt: slow test 18.35s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 8.58s amadan.net/oficina/equipo/internal/headless TestHeadlessResearchHandoff
receipt: slow test 6.56s amadan.net/oficina/equipo/internal/headless TestHeadlessTurnBatching
receipt: slow test 6.48s amadan.net/oficina/equipo/internal/headless TestHeadlessBatchAfterRefusedReply
machine: 32 CPUs, load 26.21, cpu waiting 13.76%, memory waiting 0.00%, io waiting 0.10%
--- 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 2m15.506s 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 2m13.421s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 9.74s amadan.net/oficina/equipo/internal/thintest TestContractTeamJobSettledStates
receipt: slow test 6.77s amadan.net/oficina/equipo/internal/thintest TestExplorePreviewsOff
receipt: slow test 3.98s amadan.net/oficina/equipo/internal/thintest TestContractTeamNudgePersonNeeds
receipt: slow test 3.85s amadan.net/oficina/equipo/internal/thintest TestContractPreviewHeldUntilPublishAnswer
receipt: slow test 3.62s amadan.net/oficina/equipo/internal/thintest TestContractTeamUpdatePersonNeeds
machine: 32 CPUs, load 39.39, cpu waiting 22.66%, memory waiting 0.00%, io waiting 0.18%
--- 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 1m57.515s 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 1m54.829s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 9.61s amadan.net/oficina/equipo/internal/thintest TestContractRetryPreviewUnverifiedMerge
receipt: slow test 9.08s amadan.net/oficina/equipo/internal/thintest TestContractPreviewNotScheduled
receipt: slow test 4.94s amadan.net/oficina/equipo/internal/thintest TestContractPublishNotOffered
receipt: slow test 4.54s amadan.net/oficina/equipo/internal/thintest TestContractMacRecheckMergeAuthority
receipt: slow test 3s amadan.net/oficina/equipo/internal/thintest TestContractPausedJob
machine: 32 CPUs, load 50.15, cpu waiting 29.95%, memory waiting 0.00%, io waiting 0.25%
--- 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 5m6.736s, over the 45s its record on line 44 allows; reported only, timing fails on CI
receipt: test step 5m12.861s 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 5m6.736s amadan.net/oficina/equipo/internal/runner/thin
receipt: slow test 37s amadan.net/oficina/equipo/internal/runner/thin TestModelsProbeAnsweredByAnotherModel
receipt: slow test 36.88s amadan.net/oficina/equipo/internal/runner/thin TestModelsEngineeringProbesThenRunsTheStrongest
receipt: slow test 36.81s amadan.net/oficina/equipo/internal/runner/thin TestModelsUnhealthyRetriedOnDemand
receipt: slow test 18.48s amadan.net/oficina/equipo/internal/runner/thin TestModelsProbeRunsInsideTheAdmission
receipt: slow test 9.99s amadan.net/oficina/equipo/internal/runner/thin TestTimeoutKeepsNothingForAnOlderInstance
machine: 32 CPUs, load 3.08, cpu waiting 1.16%, memory waiting 0.00%, io waiting 0.00%
--- 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 52.03s 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.093s amadan.net/oficina/equipo/internal/runner
receipt: slow test 31.06s amadan.net/oficina/equipo/internal/runner TestDirectBugWorkflow
receipt: slow test 20.03s amadan.net/oficina/equipo/internal/runner TestEnrolKeepsTheRole
machine: 32 CPUs, load 55.28, cpu waiting 34.79%, memory waiting 0.00%, io waiting 0.76%
--- 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 1m2.369s 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 1m1.112s amadan.net/oficina/equipo/internal/runner
receipt: slow test 51.07s amadan.net/oficina/equipo/internal/runner TestPlanWorkflowCandidateOrder
receipt: slow test 45.46s amadan.net/oficina/equipo/internal/runner TestPlanWorkflowFeature
receipt: slow test 8.42s amadan.net/oficina/equipo/internal/runner TestCoordinatorRecoveryCallRefusalKeepsServing
receipt: slow test 1.6s amadan.net/oficina/equipo/internal/runner TestCoordinatorRefusalMatrix
machine: 32 CPUs, load 65.86, cpu waiting 40.19%, memory waiting 0.00%, io waiting 0.64%
--- 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.26s 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.417s amadan.net/oficina/equipo/internal/runner
receipt: slow test 5.14s amadan.net/oficina/equipo/internal/runner TestDirectFaultIsolation
receipt: slow test 3.25s amadan.net/oficina/equipo/internal/runner TestClaimRefusalsBackOff
receipt: slow test 3.13s amadan.net/oficina/equipo/internal/runner TestCoordinatorRecoveryRefusedKeepsServing
receipt: slow test 2.94s amadan.net/oficina/equipo/internal/runner TestToolVerbUnderFakeHarness
receipt: slow test 1.61s amadan.net/oficina/equipo/internal/runner TestReportPostsRetryExactRequest
machine: 32 CPUs, load 35.90, cpu waiting 22.36%, memory waiting 0.00%, io waiting 1.00%
--- 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 41.1%, load 26.84
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 1m8.658s 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.827s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 28.3s amadan.net/oficina/equipo/internal/equipotest TestAuthorityCoreIntegration
receipt: slow test 28.19s amadan.net/oficina/equipo/internal/equipotest TestBootstrapNamesOwnersSetting
receipt: slow test 25.96s amadan.net/oficina/equipo/internal/equipotest TestAccountLabelMigration
receipt: slow test 23.27s amadan.net/oficina/equipo/internal/equipotest TestAccountLabelDuplicates
receipt: slow test 23.19s amadan.net/oficina/equipo/internal/equipotest TestBudgetConfigurationFailuresAreAtomic
machine: 32 CPUs, load 60.15, cpu waiting 39.29%, memory waiting 0.00%, io waiting 0.34%
--- 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 41.1%, load 26.84
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 1m18.629s 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 1m16.723s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 19.95s amadan.net/oficina/equipo/internal/equipotest TestProjectRequestActorAndUpdate
receipt: slow test 19.93s amadan.net/oficina/equipo/internal/equipotest TestProjectBindingUniqueness
receipt: slow test 19.91s amadan.net/oficina/equipo/internal/equipotest TestProjectKindsAndDefaultBranch
receipt: slow test 19.88s amadan.net/oficina/equipo/internal/equipotest TestProjectWritesRequireCurrentOwner
receipt: slow test 19.86s amadan.net/oficina/equipo/internal/equipotest TestProjectOwnersAreMembers
machine: 32 CPUs, load 53.91, cpu waiting 33.90%, memory waiting 0.00%, io waiting 0.28%
--- 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 41.1%, load 26.84
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 1m15.545s 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 1m10.133s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 15.49s amadan.net/oficina/equipo/internal/equipotest TestReleaseStampContract
receipt: slow test 13.21s amadan.net/oficina/equipo/internal/equipotest TestRosterChangesAffectExistingSession
receipt: slow test 10.32s amadan.net/oficina/equipo/internal/equipotest TestRosterRemovalWhileAssigned
receipt: slow test 10.26s amadan.net/oficina/equipo/internal/equipotest TestRosterRemovalRollsBack
receipt: slow test 7.2s amadan.net/oficina/equipo/internal/equipotest TestRosterProtectsLastOwner
machine: 32 CPUs, load 56.77, cpu waiting 36.13%, memory waiting 0.00%, io waiting 0.30%
--- 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 41.1%, load 26.84
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 1m9.272s 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.297s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 25.47s amadan.net/oficina/equipo/internal/equipotest TestSigninNoProof
receipt: slow test 25.34s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsSeedExistingTeam
receipt: slow test 25.25s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsSeedRollback
receipt: slow test 23.45s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsUpgrade
receipt: slow test 23.35s amadan.net/oficina/equipo/internal/equipotest TestSpecialistSettingsRollbackAndUnavailable
machine: 32 CPUs, load 60.15, cpu waiting 39.29%, memory waiting 0.00%, io waiting 0.34%
--- 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 41.1%, load 26.84
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 55.495s 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 53.508s amadan.net/oficina/equipo/internal/plan3test
receipt: slow test 3.8s amadan.net/oficina/equipo/internal/plan3test TestPlan3Upgrade
receipt: slow test 3.5s amadan.net/oficina/equipo/internal/plan3test TestCoordinatorAcceptance3B
receipt: slow test 1.83s amadan.net/oficina/equipo/internal/plan3test TestConversationQuestionRace
receipt: slow test 1.62s amadan.net/oficina/equipo/internal/plan3test TestCoordinatorAcceptance3A
receipt: slow test 1.3s amadan.net/oficina/equipo/internal/plan3test TestPlanMigrationUpgrade
machine: 32 CPUs, load 64.34, cpu waiting 41.13%, memory waiting 0.00%, io waiting 0.43%
--- 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 41.1%, load 26.84
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/door ./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/pause ./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/claude/realcli ./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/forgekey ./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/door ./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/pause ./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/claude/realcli ./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/forgekey ./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/provider/claude/realcli: 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/containment: its inputs changed
--- FAIL amadan.net/oficina/equipo/internal/testci TestBudgetRecordsAreShort
=== RUN TestBudgetRecordsAreShort
budgets_file_test.go:37: .rastrillo/budgets.txt:17: reason is 248 bytes, over 200
budgets_file_test.go:37: .rastrillo/budgets.txt:18: reason is 236 bytes, over 200
budgets_file_test.go:37: .rastrillo/budgets.txt:33: reason is 213 bytes, over 200
budgets_file_test.go:37: .rastrillo/budgets.txt:59: reason is 236 bytes, over 200
--- FAIL: TestBudgetRecordsAreShort (0.00s)
--- FAIL amadan.net/oficina/equipo/internal/testci (package output)
FAIL
rastrillo-budget/v1 ran 2.269s
FAIL amadan.net/oficina/equipo/internal/testci 2.275s
budget note: internal/equipo took 2m21.622s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/equipo/chat took 22.771s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/equipo/setup took 14.94s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/idtest took 1m53.988s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/release took 41.44s, 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 48.75s, over the 15s its record on line 40 allows; reported only, timing fails on CI
budget note: internal/runner/forge took 20.12s, over the 20s its record on line 35 allows; reported only, timing fails on CI
budget note: internal/runner/provider/claude/realcli took 14.143s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/runner/provider/pi took 1m20.409s, over the 1m0s its record on line 27 allows; reported only, timing fails on CI
budget note: internal/runner/workspace took 11.189s, over the 10s the default allows; reported only, timing fails on CI
receipt: test step 2m28.129s against a 60s target (the gate's other steps are not in this figure)
receipt: 37 packages ran, 28 cached, 17 without tests, 1 failed
receipt: slow package 2m21.622s amadan.net/oficina/equipo/internal/equipo
receipt: slow package 1m53.988s amadan.net/oficina/equipo/internal/idtest
receipt: slow package 1m20.409s amadan.net/oficina/equipo/internal/runner/provider/pi
receipt: slow package 1m7.638s amadan.net/oficina/equipo/internal/runner/provider/opencode
receipt: slow package 56.176s amadan.net/oficina/equipo/internal/runner/checks
receipt: slow test 55s amadan.net/oficina/equipo/internal/idtest TestDoorRemembersOficinaID
receipt: slow test 46.66s amadan.net/oficina/equipo/internal/idtest TestDoorOficinaSettingsUnreadableIsNoLoop
receipt: slow test 46.36s amadan.net/oficina/equipo/internal/idtest TestDoorStepUpIsLocal
receipt: slow test 45.94s amadan.net/oficina/equipo/internal/idtest TestDoorNeverJudgesANativeSession
receipt: slow test 45.85s amadan.net/oficina/equipo/internal/idtest TestDoorForgetsOficinaIDForARefusedSession
rastrillo: budget test: go test failed
exit status 1
+ go test -tags testbuild -timeout 15m -v -run '^TestBudgetRecordsAreShort$' -count=1 ./internal/testci (retry, once)
FAILED TWICE ./internal/testci:TestBudgetRecordsAreShort rest
=== RUN TestBudgetRecordsAreShort
budgets_file_test.go:37: .rastrillo/budgets.txt:17: reason is 248 bytes, over 200
budgets_file_test.go:37: .rastrillo/budgets.txt:18: reason is 236 bytes, over 200
budgets_file_test.go:37: .rastrillo/budgets.txt:33: reason is 213 bytes, over 200
budgets_file_test.go:37: .rastrillo/budgets.txt:59: reason is 236 bytes, over 200
--- FAIL: TestBudgetRecordsAreShort (0.00s)
FAIL
rastrillo-budget/v1 ran 0s
FAIL amadan.net/oficina/equipo/internal/testci 0.004s
FAIL
machine: 32 CPUs, load 20.84, cpu waiting 10.90%, memory waiting 0.00%, io waiting 0.08%
make: *** [Makefile:113: ci-shard] Error 1
amadan: step check shard 17 of 29 failed: exit status 2
--- 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
receipt: test step 1m25.267s 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.638s amadan.net/oficina/equipo/internal/headless
receipt: slow test 38.5s amadan.net/oficina/equipo/internal/headless TestBrowserDraftIsTheMessage
receipt: slow test 14.88s amadan.net/oficina/equipo/internal/headless TestBrowserDraftStreamsFormatted
receipt: slow test 10.77s amadan.net/oficina/equipo/internal/headless TestBrowserChat
receipt: slow test 7.15s amadan.net/oficina/equipo/internal/headless TestBrowserComposer
receipt: slow test 6.36s amadan.net/oficina/equipo/internal/headless TestBrowserChatSendStaysOnPage
machine: 32 CPUs, load 64.34, cpu waiting 41.06%, memory waiting 0.00%, io waiting 0.41%
--- 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
receipt: test step 1m31.779s 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.373s amadan.net/oficina/equipo/internal/headless
receipt: slow test 27.07s amadan.net/oficina/equipo/internal/headless TestBrowserRailFollowsWork
receipt: slow test 21.64s amadan.net/oficina/equipo/internal/headless TestBrowserTaskThread
receipt: slow test 13.08s amadan.net/oficina/equipo/internal/headless TestBrowserReceiptFollowsReview
receipt: slow test 9.95s amadan.net/oficina/equipo/internal/headless TestBrowserTaskCard
receipt: slow test 9.27s amadan.net/oficina/equipo/internal/headless TestBrowserAskAfterMerge
machine: 32 CPUs, load 62.31, cpu waiting 41.31%, memory waiting 0.00%, io waiting 0.39%
--- 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 1m53.628s 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 1m51.304s amadan.net/oficina/equipo/internal/headless
receipt: slow test 13.72s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsConversation
receipt: slow test 13.41s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsAddPage
receipt: slow test 12.57s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsAdd
receipt: slow test 11.42s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsMeteredLimitRequired
receipt: slow test 11.33s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsSignInEmail
machine: 32 CPUs, load 50.15, cpu waiting 31.91%, memory waiting 0.00%, io waiting 0.26%
--- 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|TestBrowserConnectionsSignInEmail|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
receipt: test step 1m31.915s 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.719s amadan.net/oficina/equipo/internal/headless
receipt: slow test 14.83s amadan.net/oficina/equipo/internal/headless TestBrowserThinkingAndCards
receipt: slow test 11.36s amadan.net/oficina/equipo/internal/headless TestBrowserStalePageReloads
receipt: slow test 10.79s amadan.net/oficina/equipo/internal/headless TestBrowserWaitingTurns
receipt: slow test 9.63s amadan.net/oficina/equipo/internal/headless TestBrowserMoveIn
receipt: slow test 7.73s amadan.net/oficina/equipo/internal/headless TestBrowserEmptyExplore
machine: 32 CPUs, load 62.31, cpu waiting 41.31%, memory waiting 0.00%, io waiting 0.39%
--- 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|TestBrowserPreviewPassExchange)$' ./internal/equipo
receipt: test step 4.349s 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 2.433s amadan.net/oficina/equipo/internal/equipo
receipt: slow test 1.78s amadan.net/oficina/equipo/internal/equipo TestBrowserPreviewPassExchange
receipt: slow test 660ms 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|TestBrowserSmartDoor)$' ./internal/idtest
budget note: internal/idtest took 11.238s, over the 10s the default allows; reported only, timing fails on CI
receipt: test step 12.604s 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 11.238s amadan.net/oficina/equipo/internal/idtest
receipt: slow test 8.94s amadan.net/oficina/equipo/internal/idtest TestBrowserSmartDoor
receipt: slow test 2.29s 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.671s 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 2.065s amadan.net/oficina/equipo/internal/plan3test
receipt: slow test 2.06s 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|TestBrowserEndedNoteStaysGone|TestBrowserHousekeeping|TestBrowserInnerGallery|TestBrowserInnerScreens|TestBrowserInstantThinking|TestBrowserInstantThinkingQueued|TestBrowserMachines|TestBrowserPausedWork|TestBrowserPhoneIndex|TestBrowserPlacementQuestionAndPending|TestBrowserProjectPlacement|TestBrowserProjectsList|TestBrowserReportActionFeedback|TestBrowserReportNextSteps|TestBrowserReportThread|TestBrowserRhythm|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|TestBrowserTryAgain)$' ./internal/thintest
rastrillo: budget test: go test failed
--- FAIL amadan.net/oficina/equipo/internal/thintest TestBrowserRosterVisual
=== RUN TestBrowserRosterVisual
--- FAIL: TestBrowserRosterVisual (1.53s)
--- FAIL amadan.net/oficina/equipo/internal/thintest TestBrowserRosterVisual/1280-light
=== RUN TestBrowserRosterVisual/1280-light
roster_browser_test.go:41: report spacing left the inset scale
--- FAIL: TestBrowserRosterVisual/1280-light (0.33s)
--- FAIL amadan.net/oficina/equipo/internal/thintest TestBrowserRosterVisual/1280-dark
=== RUN TestBrowserRosterVisual/1280-dark
roster_browser_test.go:41: report spacing left the inset scale
--- FAIL: TestBrowserRosterVisual/1280-dark (0.29s)
--- FAIL amadan.net/oficina/equipo/internal/thintest TestBrowserRosterVisual/390-light
=== RUN TestBrowserRosterVisual/390-light
roster_browser_test.go:41: report spacing left the inset scale
--- FAIL: TestBrowserRosterVisual/390-light (0.30s)
--- FAIL amadan.net/oficina/equipo/internal/thintest TestBrowserRosterVisual/390-dark
=== RUN TestBrowserRosterVisual/390-dark
roster_browser_test.go:41: report spacing left the inset scale
--- FAIL: TestBrowserRosterVisual/390-dark (0.30s)
--- FAIL amadan.net/oficina/equipo/internal/thintest (package output)
FAIL
rastrillo-budget/v1 ran 3m35.957s
FAIL amadan.net/oficina/equipo/internal/thintest 216.232s
receipt: test step 3m37.675s 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 3m35.957s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 24.88s amadan.net/oficina/equipo/internal/thintest TestBrowserAccessRequest
receipt: slow test 14.42s amadan.net/oficina/equipo/internal/thintest TestBrowserSettingsTeams
receipt: slow test 12.07s amadan.net/oficina/equipo/internal/thintest TestBrowserThinkingCycles
receipt: slow test 10.66s amadan.net/oficina/equipo/internal/thintest TestBrowserPlacementQuestionAndPending
receipt: slow test 8.86s amadan.net/oficina/equipo/internal/thintest TestBrowserRhythm
exit status 1
+ go test -tags browser,testbuild -timeout 15m -run '^(TestBrowserAccessEmojiByline|TestBrowserAccessFinalOutcomes|TestBrowserAccessRequest|TestBrowserAccessReview|TestBrowserActivitySubjects|TestBrowserAutonomySettings|TestBrowserCoordinatorQueue|TestBrowserEmptyConversation|TestBrowserEndedNoteStaysGone|TestBrowserHousekeeping|TestBrowserInnerGallery|TestBrowserInnerScreens|TestBrowserInstantThinking|TestBrowserInstantThinkingQueued|TestBrowserMachines|TestBrowserPausedWork|TestBrowserPhoneIndex|TestBrowserPlacementQuestionAndPending|TestBrowserProjectPlacement|TestBrowserProjectsList|TestBrowserReportActionFeedback|TestBrowserReportNextSteps|TestBrowserReportThread|TestBrowserRhythm|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|TestBrowserTryAgain)$' -v -run '^TestBrowserRosterVisual$/^1280\-dark$|^TestBrowserRosterVisual$/^1280\-light$|^TestBrowserRosterVisual$/^390\-dark$|^TestBrowserRosterVisual$/^390\-light$' -count=1 ./internal/thintest (retry, once)
FAILED TWICE ./internal/thintest:TestBrowserRosterVisual/1280-dark browser-rest
FAILED TWICE ./internal/thintest:TestBrowserRosterVisual/1280-light browser-rest
FAILED TWICE ./internal/thintest:TestBrowserRosterVisual/390-dark browser-rest
FAILED TWICE ./internal/thintest:TestBrowserRosterVisual/390-light browser-rest
=== RUN TestBrowserRosterVisual
=== RUN TestBrowserRosterVisual/1280-light
roster_browser_test.go:41: report spacing left the inset scale
=== RUN TestBrowserRosterVisual/1280-dark
roster_browser_test.go:41: report spacing left the inset scale
=== RUN TestBrowserRosterVisual/390-light
roster_browser_test.go:41: report spacing left the inset scale
=== RUN TestBrowserRosterVisual/390-dark
roster_browser_test.go:41: report spacing left the inset scale
--- FAIL: TestBrowserRosterVisual (2.66s)
--- FAIL: TestBrowserRosterVisual/1280-light (0.37s)
--- FAIL: TestBrowserRosterVisual/1280-dark (0.29s)
--- FAIL: TestBrowserRosterVisual/390-light (0.29s)
--- FAIL: TestBrowserRosterVisual/390-dark (0.30s)
FAIL
rastrillo-budget/v1 ran 2.658s
FAIL amadan.net/oficina/equipo/internal/thintest 2.817s
FAIL
machine: 32 CPUs, load 7.93, cpu waiting 3.75%, memory waiting 0.00%, io waiting 0.02%
make: *** [Makefile:113: ci-shard] Error 1
amadan: step check shard 22 of 29 failed: exit status 2
--- 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 (54s)
ok ./internal/headless TestHeadlessConnections/A5_cancel_and_sign_out 4.52s
ok ./internal/headless TestHeadlessConnections/C4_claude_sign_in 1.17s
ok ./internal/headless TestHeadlessConnections/C5_engineering_failover 8.68s
ok ./internal/headless TestHeadlessConnections/C5_engineering_to_codex 9.02s
ok ./internal/headless TestHeadlessConnections/C5_engineering_waits 28.24s
+ 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 (56s)
ok ./internal/headless TestHeadlessConnections/C5_review_auth 12.55s
ok ./internal/headless TestHeadlessConnections/C5_review_failover 11.47s
ok ./internal/headless TestHeadlessConnections/C5_review_on_codex 9.94s
ok ./internal/headless TestHeadlessConnections/C5_review_other_family_first 19.38s
+ go test -tags testbuild -timeout 15m -v -run '^TestMixedVersions$' ./internal/headless (21s)
ok ./internal/headless TestMixedVersions 18.73s
+ go test -tags testbuild -timeout 15m -v -run '^TestCheckSandboxDeniedPathsTampering$' ./internal/runner/checks (2s)
ok ./internal/runner/checks TestCheckSandboxDeniedPathsTampering 0.94s
+ go test -tags testbuild -timeout 15m -v -run '^TestRunnerCancelAndSupersede$' ./internal/runner/thin (2s)
ok ./internal/runner/thin TestRunnerCancelAndSupersede 0.05s
quarantine: 0 flaked (passed on the retry), 0 failed
machine: 32 CPUs, load 63.58, cpu waiting 38.72%, memory waiting 0.00%, io waiting 0.69%
--- 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.943s against a 60s target (the gate's other steps are not in this figure)
receipt: 4 packages ran, 0 cached, 4 without tests, 0 failed
receipt: slow package 7.842s amadan.net/oficina/equipo/internal/runner/checks
receipt: slow package 183ms amadan.net/oficina/equipo/internal/runner/provider/claude
receipt: slow package 69ms amadan.net/oficina/equipo/internal/runner/provider/codex
receipt: slow package 2ms amadan.net/oficina/equipo/internal/runner/provider
receipt: slow package 1ms amadan.net/oficina/equipo/internal/runner/provider/opencode
receipt: slow test 5.52s amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPathsGoFixture
receipt: slow test 1.8s amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPaths
receipt: slow test 400ms amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPathsCache
receipt: slow test 180ms amadan.net/oficina/equipo/internal/runner/provider/claude TestDirectJournalAdapterBarrier
receipt: slow test 100ms 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.589s 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.164s amadan.net/oficina/equipo/internal/runner/containment
receipt: slow test 300ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceReadOnlyScratch
receipt: slow test 200ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceRecoveryUnavailableProof
receipt: slow test 150ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceDirectPolicyAdmission
receipt: slow test 120ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceRecoveryReusedPID
receipt: slow test 110ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceRecoveryMalformedRecord
machine: 32 CPUs, load 11.91, cpu waiting 11.83%, memory waiting 0.00%, io waiting 1.35%
--- 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 41.1%, load 26.84
shard 25: make runner-dead-references lanes-check build vet fmt-check spacing budget migration-check
python3 scripts/runner-dead-references.py
reference scan: 2912 text files, 3229 matches, 0 failures
python3 native/scripts/check-share.py
Share packaging, keychain-only boundary and reviewed copy verified
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 tool fiesta spacing -skip tokens.css internal/equipo/static
go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget size
budget size: 92 directories within budget
CGO_ENABLED=0 go test ./internal/equipo -run '^TestMigrationModels$' -count=1
ok amadan.net/oficina/equipo/internal/equipo 2.615s
machine: 32 CPUs, load 64.47, cpu waiting 41.70%, memory waiting 0.00%, io waiting 0.49%
--- 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 41.1%, load 26.84
shard 26: make staticcheck
go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 -tags browser,perf,testbuild ./...
machine: 32 CPUs, load 63.58, cpu waiting 36.27%, memory waiting 0.00%, io waiting 0.74%
--- 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 41.1%, load 26.84
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 10
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 35.90, cpu waiting 25.74%, memory waiting 0.00%, io waiting 0.93%
--- 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 41.1%, load 26.84
shard 28: make gitleaks
[90m11:20PM[0m [32mINF[0m [1mUnknown SCM platform. Use --platform to include links in findings.[0m [36mhost=[0mamadan.net
[90m11:20PM[0m [32mINF[0m [1m1218 commits scanned.[0m
[90m11:20PM[0m [32mINF[0m [1mscanned ~67687108 bytes (67.69 MB) in 26.1s[0m
[90m11:20PM[0m [32mINF[0m [1mno leaks found[0m
machine: 32 CPUs, load 63.58, cpu waiting 37.63%, memory waiting 0.00%, io waiting 0.71%
amadan: job failed at step check shards 17, 22 of 29 — its output is above, not at the tail of this log
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index e5ae5dc7..780f5313 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 23293 - Preview grants, Retry/timeline, no-access merges, kept timed-out work, and reviewed check-db operator copy; previews run again on done tasks; measured 23293 source lines (2026-11-26). |
| -size internal/wire 7420 - Protocol 31 display facts, path validation, task evidence, merge reasons; protocol 32 unfinished work, shell_unavailable, CI units (2026-11-26); measured 7420 source lines. |
| +size internal/equipo 23297 - Preview grants, Retry/timeline, no-access merges, kept timed-out work, and reviewed check-db operator copy; previews run again on done tasks; measured 23293 source lines (2026-11-26). Notification actions and direct card reads; measured 23297/6175. |
| +size internal/wire 7445 - Protocol 31 display facts, path validation, task evidence, merge reasons; protocol 32 unfinished work, shell_unavailable, CI units (2026-11-26); measured 7420 source lines. Notification actions and direct card reads; measured 7445/3297. |
| size internal/equipotest - 12017 Task 21 repairs historical migration and conversation fixtures after Plan 3, and the Rastrillo upgrade contract comparing served assets with what Assets serves; measured 0/12017 source/test lines. |
| time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded); |
| time internal/runner 330s Plan 3 CI repair measured 292.120s for the full package (controller CI 472.184s). |
| @@ -30,7 +30,7 @@ size internal/runner/provider 5731 - 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 - 11978 Preview pass, paused-work, Assistant, stuck-task, merge credential, no-access and check-db release inventory; measured 11978 test lines (2026-11-26). |
| +size internal/plan3test - 12024 Preview pass, paused-work, Assistant, stuck-task, merge credential, no-access and check-db release inventory; measured 11978 test lines (2026-11-26). Notification actions and direct card reads; measured 940/12024. |
| 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 35473 9910 File facts, hosted projection, no-access merges, preview reads; unfinished work, shell-less rounds, CI feedback; previews on done tasks (2026-11-26); measured 35473/9910. |
| +size internal/equipo/chat 35789 10522 File facts, hosted projection, no-access merges, preview reads; unfinished work, shell-less rounds, CI feedback; previews on done tasks (2026-11-26); measured 35473/9910. Notification actions and direct card reads; measured 35789/10522. |
| 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. |
| @@ -77,3 +77,7 @@ perf GET /api/v1/projects/{id}/merge-policy skip Merge authority person API: bea |
| perf GET /api/v1/usage skip Thin v1 person API: bearer-only JSON for devices; the browser reads usage through /usage. |
| perf GET /api/v1/advice skip Thin v1 person API: bearer-only JSON for devices; the browser reads advice through /usage and /conversation. |
| perf GET /native/preview/exchange skip Rejects GET with 404; only a same-origin, body-only POST can consume a preview pass. |
| + |
| +# GET /api/v1/cards/{id} retains the measured legacy screen path. Its c_ device |
| +# branch uses an indexed primary-key lookup, one current-member/device check, |
| +# and the same bounded cardView as the snapshot; no list scan or new route. |
diff --git a/docs/api/equipo-v1.md b/docs/api/equipo-v1.md| index 6221cff7..8dac8a60 100644 |
| --- a/docs/api/equipo-v1.md |
| +++ b/docs/api/equipo-v1.md |
| @@ -231,3 +231,48 @@ A named placement card includes optional `remember_name`, the suggested private |
| Oficina Connect credentials use the separate [agent-access interface](agent-access.md). |
| It lists active projects and recent tasks, reads one task, and reads Needs you. |
| + |
| +### Notification actions (opt-in) |
| + |
| +`GET /capabilities` advertises `notification_actions_v1`, false by default. |
| +After completing the physical-device unlock and privacy checks, an operator |
| +can enable it with `EQUIPO_NOTIFICATION_ACTIONS=1`. An app must first read |
| +that capability before adding `actions_version: 1` and a random canonical |
| +lowercase UUID `binding_id` to its push registration. Older servers strictly |
| +reject unknown registration fields. Rotate the binding on account or sign-in |
| +changes; never take an API origin or credential from a notification. |
| + |
| +Opted-in alerts may use `equipo.question.text.v1`, |
| +`equipo.question.choices.v1`, `equipo.merge.v1` or `equipo.stopped.v1`. |
| +The existing alert text is unchanged. The optional `equipo.actions` object |
| +contains version, registration binding and notification IDs, plus the card |
| +kind and revision, or task revision and failed step ID, revision and attempt. |
| +It contains no option text, checks, review summary or credentials. Text input |
| +is offered only for an optionless question already shown in full in the |
| +alert. Unknown, incomplete and oversized metadata retains open-only behavior. |
| +Every response requires foreground activation and authentication. Merge only |
| +opens fresh task facts and the existing confirmation; unlock does not merge. |
| + |
| +`POST /cards/{id}/answer` accepts an optional `idempotency_key` in addition to |
| +its revision and choice. `POST /tasks/{id}/retry` still accepts an empty body |
| +or `{}` for existing callers. Notification retries instead supply all of |
| +`revision`, `step_id`, `step_revision`, `attempt` and `idempotency_key`. |
| +Partial bindings are invalid; stale bindings return `409 not_retryable`. |
| + |
| +Bound writes require the capability and a current device and person. A receipt |
| +stores a digest and result identifiers atomically with the write, scoped to |
| +person, credential, operation, target and key. Repeating the same request |
| +returns its original result identifiers; the result's presentation fields may |
| +reflect current state. A changed request under that key returns |
| +`409 idempotency_conflict`. Receipts expire after seven days. The native app |
| +keeps the immutable request before POST for at most 24 hours and retries only |
| +when the person requests it. A 409 opens/refetches the relevant task or card; |
| +it never applies an old answer to a replacement revision. |
| + |
| +A bound notification reads its card directly at `GET /cards/{id}`; it never |
| +searches only the snapshot's newest 50 cards. The reserved `c_` prefix chooses |
| +the thin store before authorization or lookup. Those reads require a current |
| +device and member, the same person, Coordinator lane and a card that is not |
| +held. Their projection and revision are identical to the snapshot's. A missing |
| +or invisible card returns `not_found`, with no fallback to another store. |
| +Legacy IDs keep the earlier person API projection on this same URL. |
diff --git a/docs/api/equipo-v1.openapi.json b/docs/api/equipo-v1.openapi.json| index 0e042779..d4226bab 100644 |
| --- a/docs/api/equipo-v1.openapi.json |
| +++ b/docs/api/equipo-v1.openapi.json |
| @@ -643,7 +643,14 @@ |
| "content": { |
| "application/json": { |
| "schema": { |
| - "$ref": "#/components/schemas/PersonAPICard" |
| + "oneOf": [ |
| + { |
| + "$ref": "#/components/schemas/Card" |
| + }, |
| + { |
| + "$ref": "#/components/schemas/PersonAPICard" |
| + } |
| + ] |
| } |
| } |
| } |
| @@ -676,7 +683,83 @@ |
| "$ref": "#/components/responses/unavailable" |
| } |
| }, |
| - "x-plan-part": "3a" |
| + "x-plan-part": "3a", |
| + "x-earlierPersonAPI": { |
| + "when": "The id does not start with c_.", |
| + "operation": { |
| + "operationId": "get_cards_id", |
| + "parameters": [ |
| + { |
| + "name": "id", |
| + "in": "path", |
| + "required": true, |
| + "schema": { |
| + "type": "string", |
| + "minLength": 1 |
| + } |
| + } |
| + ], |
| + "responses": { |
| + "200": { |
| + "description": "OK", |
| + "headers": { |
| + "ETag": { |
| + "schema": { |
| + "type": "string", |
| + "pattern": "^\"(0|[1-9][0-9]*)\"$" |
| + } |
| + }, |
| + "Cache-Control": { |
| + "schema": { |
| + "const": "no-store" |
| + } |
| + } |
| + }, |
| + "content": { |
| + "application/json": { |
| + "schema": { |
| + "$ref": "#/components/schemas/PersonAPICard" |
| + } |
| + } |
| + } |
| + }, |
| + "401": { |
| + "$ref": "#/components/responses/unauthenticated" |
| + }, |
| + "403": { |
| + "$ref": "#/components/responses/forbidden" |
| + }, |
| + "404": { |
| + "$ref": "#/components/responses/not_found" |
| + }, |
| + "405": { |
| + "$ref": "#/components/responses/method_not_allowed" |
| + }, |
| + "409": { |
| + "$ref": "#/components/responses/revision_conflict" |
| + }, |
| + "410": { |
| + "$ref": "#/components/responses/cursor_expired" |
| + }, |
| + "422": { |
| + "$ref": "#/components/responses/invalid_input" |
| + }, |
| + "428": { |
| + "$ref": "#/components/responses/precondition_required" |
| + }, |
| + "503": { |
| + "$ref": "#/components/responses/unavailable" |
| + } |
| + }, |
| + "x-plan-part": "3a" |
| + } |
| + }, |
| + "description": "Direct card read, independent of the snapshot window. IDs beginning `c_` select the thin store and require a device bearer; all others select the earlier person API. There is no lookup fallback. The oneOf is distinguished by the ID prefix and required shape: thin Card includes state and question; PersonAPICard includes resource_id and actions. Thin reads enforce current membership and device, current person, Coordinator lane and not held, returning the snapshot cardView projection and revision. Missing, invisible and wrong-store cards are not_found.", |
| + "security": [ |
| + { |
| + "personBearer": [] |
| + } |
| + ] |
| } |
| }, |
| "/tasks": { |
| @@ -10277,7 +10360,7 @@ |
| "post": { |
| "operationId": "post_cards_id_answer", |
| "summary": "Answer a card", |
| - "description": "Send one of the card's `options` as `choice`, with the card's current `revision`. The answer is 200 with the card, your answer as a message, and its turn. A stale revision is 409 with `code` `card_stale`; a card that is answered, changed or removed is 409 with `code` `card_answered`. Both carry the card as it is now. A named placement card includes optional `remember_name`, the suggested private name. Card answers accept optional `remember_name`: only an explicit nonempty string confirms a name. An empty string or omission skips learning. The field is honoured only on a card that already carries a suggestion.", |
| + "description": "Send one of the card's `options` as `choice`, with the card's current `revision`. The answer is 200 with the card, your answer as a message, and its turn. A stale revision is 409 with `code` `card_stale`; a card that is answered, changed or removed is 409 with `code` `card_answered`. Both carry the card as it is now. A named placement card includes optional `remember_name`, the suggested private name. Card answers accept optional `remember_name`: only an explicit nonempty string confirms a name. An empty string or omission skips learning. The field is honoured only on a card that already carries a suggestion. An optional idempotency_key enables seven-day device/person-scoped receipts when notification_actions_v1 is enabled; a changed body under the same key is 409 idempotency_conflict. No duplicate answer text is retained in the receipt.", |
| "security": [ |
| { |
| "personBearer": [] |
| @@ -10324,7 +10407,14 @@ |
| "content": { |
| "application/json": { |
| "schema": { |
| - "$ref": "#/components/schemas/CardConflict" |
| + "oneOf": [ |
| + { |
| + "$ref": "#/components/schemas/CardConflict" |
| + }, |
| + { |
| + "$ref": "#/components/schemas/Error" |
| + } |
| + ] |
| } |
| } |
| } |
| @@ -12730,7 +12820,7 @@ |
| "post": { |
| "operationId": "post_tasks_id_retry", |
| "summary": "Retry a task that stopped", |
| - "description": "202 with the attempt; 409 `not_retryable` when it cannot be retried.", |
| + "description": "202 with the attempt; 409 `not_retryable` when it cannot be retried. With notification_actions_v1, an optional bound body pins task revision and failed step ID/revision/attempt. Every field is required when any is present. Empty/no body remains the legacy request. Same device/person/key/body returns the original attempt for seven days; changed body is 409 idempotency_conflict.", |
| "security": [ |
| { |
| "personBearer": [] |
| @@ -12785,6 +12875,18 @@ |
| } |
| } |
| } |
| + }, |
| + "requestBody": { |
| + "required": false, |
| + "content": { |
| + "application/json": { |
| + "schema": { |
| + "$ref": "#/components/schemas/RetryTask" |
| + } |
| + } |
| + }, |
| + "x-maxBytes": 32768, |
| + "x-rejectUnknownFields": true |
| } |
| } |
| }, |
| @@ -13828,7 +13930,7 @@ |
| "/auth/devices/native": { |
| "post": { |
| "operationId": "post_auth_devices_native", |
| - "description": "Register a device using only its own live home-assertion-native session cookie and same-origin request evidence (send the exact instance Origin). JSON only. Idempotency-Key is not required; each success creates a new credential. The credential expires seven days after the source session was minted, and is revoked when that session is deleted. Paired credentials retain thirty days. public_key is canonical unpadded base64url of the 32-byte Curve25519 signing public key; label is 1–128 UTF-8 bytes without NUL, CR or LF.", |
| + "description": "Register a device using only its own live home-assertion-native session cookie and same-origin request evidence (send the exact instance Origin). JSON only. Idempotency-Key is not required; each success creates a new credential. The credential expires seven days after the source session was minted, and is revoked when that session is deleted. Paired credentials retain thirty days. public_key is canonical unpadded base64url of the 32-byte Curve25519 signing public key; label is 1\u2013128 UTF-8 bytes without NUL, CR or LF.", |
| "security": [ |
| { |
| "browserSession": [] |
| @@ -15483,6 +15585,11 @@ |
| }, |
| "part": { |
| "const": "3b" |
| + }, |
| + "notification_actions_v1": { |
| + "type": "boolean", |
| + "default": false, |
| + "description": "Disabled unless EQUIPO_NOTIFICATION_ACTIONS=1. Enable in production only after physical-device unlock and privacy checks." |
| } |
| }, |
| "required": [ |
| @@ -18655,6 +18762,9 @@ |
| "AnswerCard": { |
| "type": "object", |
| "properties": { |
| + "idempotency_key": { |
| + "type": "string" |
| + }, |
| "remember_name": { |
| "type": "string" |
| }, |
| @@ -18906,6 +19016,9 @@ |
| "Card": { |
| "type": "object", |
| "properties": { |
| + "placement_by_name": { |
| + "type": "boolean" |
| + }, |
| "remember_name": { |
| "type": "string" |
| }, |
| @@ -18987,9 +19100,6 @@ |
| }, |
| "aside": { |
| "type": "boolean" |
| - }, |
| - "placement_by_name": { |
| - "type": "boolean" |
| } |
| }, |
| "required": [ |
| @@ -21121,6 +21231,10 @@ |
| "ProjectList": { |
| "type": "object", |
| "properties": { |
| + "cursor": { |
| + "type": "integer", |
| + "format": "int64" |
| + }, |
| "connections": { |
| "type": "array", |
| "items": { |
| @@ -21153,10 +21267,6 @@ |
| }, |
| "home": { |
| "type": "string" |
| - }, |
| - "cursor": { |
| - "type": "integer", |
| - "format": "int64" |
| } |
| }, |
| "required": [ |
| @@ -22226,8 +22336,9 @@ |
| "Step": { |
| "type": "object", |
| "properties": { |
| - "hosted": { |
| - "$ref": "#/components/schemas/StepHosted" |
| + "change_files": { |
| + "$ref": "#/components/schemas/ChangeFiles", |
| + "description": "Bounded presentation facts, included only on GET /tasks/{id} detail reads. Absent from task lists, snapshots, events and Coordinator tools." |
| }, |
| "base_checks": { |
| "type": "string" |
| @@ -22342,6 +22453,9 @@ |
| ], |
| "format": "int64" |
| }, |
| + "hosted": { |
| + "$ref": "#/components/schemas/StepHosted" |
| + }, |
| "askable": { |
| "type": "boolean" |
| }, |
| @@ -22423,10 +22537,6 @@ |
| }, |
| "retried_by": { |
| "type": "string" |
| - }, |
| - "change_files": { |
| - "description": "Bounded presentation facts, included only on GET /tasks/{id} detail reads. Absent from task lists, snapshots, events and Coordinator tools.", |
| - "$ref": "#/components/schemas/ChangeFiles" |
| } |
| }, |
| "required": [ |
| @@ -23897,6 +24007,13 @@ |
| "RegisterPush": { |
| "type": "object", |
| "properties": { |
| + "actions_version": { |
| + "type": "integer", |
| + "format": "int64" |
| + }, |
| + "binding_id": { |
| + "type": "string" |
| + }, |
| "token": { |
| "type": "string" |
| }, |
| @@ -24397,6 +24514,31 @@ |
| ], |
| "additionalProperties": false, |
| "x-go-type": "wire.ChangedFile" |
| + }, |
| + "RetryTask": { |
| + "type": "object", |
| + "properties": { |
| + "revision": { |
| + "type": "integer", |
| + "format": "int64" |
| + }, |
| + "step_id": { |
| + "type": "string" |
| + }, |
| + "step_revision": { |
| + "type": "integer", |
| + "format": "int64" |
| + }, |
| + "attempt": { |
| + "type": "integer", |
| + "format": "int64" |
| + }, |
| + "idempotency_key": { |
| + "type": "string" |
| + } |
| + }, |
| + "additionalProperties": false, |
| + "x-go-type": "wire.RetryTask" |
| } |
| }, |
| "responses": { |
| @@ -24582,5 +24724,75 @@ |
| ], |
| "x-requestCanonicalInputIncludes": "original_revision", |
| "x-copyReview": "COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)", |
| - "x-device-proof-message": "Decode challenge as unpadded base64url JSON [instance_id, random]. Sign the UTF-8 compact JSON array [\"equipo.person.device.v1\", instance_id, id, challenge, nonce] with Ed25519. Public key and signature are unpadded base64url." |
| + "x-device-proof-message": "Decode challenge as unpadded base64url JSON [instance_id, random]. Sign the UTF-8 compact JSON array [\"equipo.person.device.v1\", instance_id, id, challenge, nonce] with Ed25519. Public key and signature are unpadded base64url.", |
| + "x-apns-schemas": { |
| + "PushData": { |
| + "type": "object", |
| + "additionalProperties": false, |
| + "properties": { |
| + "kind": { |
| + "type": "string" |
| + }, |
| + "card_id": { |
| + "type": "string" |
| + }, |
| + "task_id": { |
| + "type": "string" |
| + }, |
| + "turn_id": { |
| + "type": "string" |
| + }, |
| + "actions": { |
| + "$ref": "#/x-apns-schemas/PushActions" |
| + } |
| + }, |
| + "required": [ |
| + "kind" |
| + ] |
| + }, |
| + "PushActions": { |
| + "type": "object", |
| + "additionalProperties": false, |
| + "description": "APNs routing metadata only. No option text or authority. Missing/unknown/incomplete metadata means open-only.", |
| + "properties": { |
| + "version": { |
| + "type": "integer", |
| + "const": 1 |
| + }, |
| + "binding_id": { |
| + "type": "string" |
| + }, |
| + "notification_id": { |
| + "type": "string" |
| + }, |
| + "card_kind": { |
| + "type": "string" |
| + }, |
| + "card_revision": { |
| + "type": "integer", |
| + "format": "int64" |
| + }, |
| + "task_revision": { |
| + "type": "integer", |
| + "format": "int64" |
| + }, |
| + "step_id": { |
| + "type": "string" |
| + }, |
| + "step_revision": { |
| + "type": "integer", |
| + "format": "int64" |
| + }, |
| + "attempt": { |
| + "type": "integer", |
| + "format": "int64" |
| + } |
| + }, |
| + "required": [ |
| + "version", |
| + "binding_id", |
| + "notification_id" |
| + ] |
| + } |
| + } |
| } |
diff --git a/docs/superpowers/plans/2026-11-27-notification-actions.md b/docs/superpowers/plans/2026-11-27-notification-actions.md| index beae36dd..b0dcfb8f 100644 |
| --- a/docs/superpowers/plans/2026-11-27-notification-actions.md |
| +++ b/docs/superpowers/plans/2026-11-27-notification-actions.md |
| @@ -1,6 +1,6 @@ |
| # Notification actions, slice 8 |
| -Status: proposed, awaiting controller approval before code. |
| +Status: approved by the controller, including privacy and durable-receipt rulings. |
| Date: 2026-11-27. Branch: `notify/actions`, from `origin/main` at |
| `602b91fe`. This replaces D4's open-only rule for the actions below. |
| Landing is allowed; production deployment waits for the production upgrade. |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-notification-actions.md b/docs/superpowers/plans/CONTROLLER-REPORT-notification-actions.md| new file mode 100644 |
| index 00000000..4cb88fe0 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-notification-actions.md |
| @@ -0,0 +1,136 @@ |
| +# Notification actions, slice 8 |
| + |
| +Branch: `notify/actions`. Approved design: `2026-11-27-notification-actions.md`. |
| +Normal merges of main `8ac4dbaf` and `a2619ce3` (merge `69219bb0`); no runner protocol change. |
| + |
| +## Behavior and release boundary |
| + |
| +Notification actions are opt-in at both ends. Production defaults off; |
| +`EQUIPO_NOTIFICATION_ACTIONS=1` enables the capability after the physical-device |
| +checks below. Old registrations, old payloads, unknown categories and malformed |
| +bindings retain open-only behavior. Every native response action requires |
| +`.authenticationRequired` and `.foreground`. |
| + |
| +The mockup's model-written lock-screen option buttons were deliberately not |
| +built, pending any future privacy decision by Paul. Only optionless questions |
| +whose complete text is already in today's alert offer direct text entry. |
| +Other questions open their bound card after unlock. The alert adds no private |
| +text. Merge opens fresh task detail, Checks and the current candidate's Review |
| +summary, then the existing confirmation with a separate final tap. |
| + |
| +Server receipts bind person, credential, operation, target, request key and |
| +digest. They retain result identifiers for seven days, not duplicate answer |
| +text. Repeated answers return those identifiers with current presentation |
| +fields; timestamp formatting need not be byte-identical to the first response. |
| +Native stores the exact request before POST, keeps uncertain writes for at most |
| +24 hours and never retries on a timer. Credentials stay in the Keychain. |
| +The registration binding rotates with the account or device sign-in. |
| + |
| +Migration 0111 adds receipt storage and registration opt-in fields, with the |
| +schema snapshot. The existing API routes are extended; no new GET route or |
| +performance-budget exemption is introduced. |
| + |
| +## Test-first evidence |
| + |
| +Scratch logs: physical TMPDIR `notify-actions-evidence/` (archive before handoff). |
| +Commands use `GOMAXPROCS=4 GOTOOLCHAIN=go1.26.11 CGO_ENABLED=0`, `go test -p 4`, |
| +and `swift test --package-path native/apple --jobs 4 --disable-xctest --filter 'Notification.*Tests'`. |
| +No full local gate. Machine load/swap and other heavy jobs checked before each |
| +run; work paused above load 20, including a spike above 100. |
| + |
| +- `new-guards-red.log`: changed whitespace under an answer key was incorrectly |
| + accepted. `new-guards-green.log`: digest now uses the submitted body before |
| + answer trimming; notification and migration checks pass. |
| +- `payload-red.log`, `http-red.log`, `server-contract.log`: capability, payload |
| + opt-in and HTTP binding tests started red, then pass, including old empty |
| + retry requests and partial/unknown binding refusal. |
| +- `schema-red.log`: bound retry undocumented. `receipts-schema.log`: generated |
| + retry and both 409 response shapes pass; concurrent receipt deliveries produce |
| + one answer, and current membership/device checks apply before receipt reads. |
| +- `native-parser-red.log`, `native-journal-red2.log`, `native-dispatch-red.log`: |
| + missing native functionality before implementation. |
| +- `native-dispatch-green3.log`: 13/14 tests pass; lost-reply restoration caught |
| + snake-case decoding of the journal envelope. Corrected to plain Codable for |
| + the envelope; original HTTP request remains unchanged. `native-dispatch-green4.log`: all 14 focused tests pass. |
| +- `merge-options-red.log`: the filter omitted the web's `not_now` and `wait_mac` alternatives. The allowlist now covers those known merge choices. |
| +- `native-restore-red.log`: pending replies did not reappear after relaunch. `native-restore-green.log`: all 17 focused tests pass. Restoration exposes an explicit Retry and never posts automatically. Account switch, sign-out cleanup and stale-response refresh tests pass. |
| +- Sign-in lifetime source guard and parity: pass, 336 web strings byte-identical. |
| + |
| +## Direct card read and compatibility |
| + |
| +`GET /cards/{id}` remains the same URL. Reserved `c_` IDs select the thin |
| +store before lookup, with no fallback after any refusal; other IDs preserve |
| +`personapi` and `ProjectCard`. Thin reads use an indexed primary-key lookup, |
| +current person/member/device checks, Coordinator lane and not-held visibility, |
| +and `cardView` plus its revision/ETag. OpenAPI's oneOf distinguishes the thin |
| +Card shape (state/question) from PersonAPICard (resource_id/actions); the |
| +compatibility operation and both shapes have contract coverage. |
| + |
| +The old newest-50 scan fails `card-read-red.log`; `card-contract-green.log` |
| +passes the older-than-window question/options, projection byte equality, |
| +visibility, dispatch and legacy regression tests. Native tests place both the |
| +bound question and merge outside the snapshot, then use the direct read. |
| +`final-go-focused.log` passes the six focused packages, including migration |
| +snapshot, API copy and operation/schema checks. |
| + |
| +Legacy message and Coordinator-turn IDs use crypto/rand.Text's RFC 4648 |
| +uppercase Base32 alphabet, which contains neither lowercase c nor underscore; |
| +native question aliases start `native:`. The generator and aliases are pinned |
| +by `TestLegacyCardIDsCannotUseThinPrefix`. A counts-only read of the production |
| +CARLOS replica at transaction 206586 (2026-11-26 23:08:47 UTC) found 68 legacy |
| +conversation_cards and 341 coordinator_turns, with zero c_ IDs in both tables. |
| +No live database writes or row contents were read. The existing measured legacy |
| +GET perf path remains; its new device branch uses a primary-key lookup instead |
| +of a list scan. No new route or perf exemption. |
| + |
| +## Mutations |
| + |
| +All 19 server mutations die: digesting the trimmed answer; ignoring receipt |
| +digest mismatch, disabled capability or current device; dropping task revision, |
| +step revision or attempt; ignoring the retry receipt; exposing text input for |
| +option/clipped questions; dropping retry creator/termination or merge-choice |
| +validation; and dropping direct-card person, held, lane, current-person, |
| +member/device or store-prefix checks. The initially noncompiling device |
| +mutation was corrected and rerun: only its valid failed test is counted. |
| + |
| +All 19 native mutations die: dropping unlock, foreground, payload version, |
| +registration capability, response account binding, journal-before-POST, |
| +question options, switch-notice cleanup, sign-out journal cleanup, |
| +stale refresh, journal binding/expiry/count, double-submit guard, final Merge |
| +tap, card revision, dispatch capability, omitting the direct stale-card refresh and replacing direct lookup with the |
| +snapshot window. Every mutation was restored. Logs are |
| +`mutation-<name>.log` and `mutation-native-<name>.log`, with per-case JSON results. |
| +A narrow SwiftPM invocation stalled before running tests; its helper was |
| +sampled and terminated, then the explicit Swift Testing invocation ran. It is |
| +not counted as a killed mutation. |
| + |
| +The stale-response regression also first failed (`stale-direct-red.log`): a |
| +409 refreshed only the snapshot and retained the old card. It now refetches the |
| +bound ID for navigation, merges the current projection, and never changes the |
| +original request's key/body/revision. The restored native suite passes all 19 |
| +tests (`final-native-focused.log`). Merge confirmations use the large phone |
| +sheet so the checks, Review summary and final decision fit; long content remains |
| +scrollable. No new copy. |
| + |
| +## Physical-device checks still required |
| + |
| +Real APNs on a locked iPhone; hidden previews; Face ID/passcode success and |
| +cancellation; submit before/after unlock; terminated-app delivery; offline and |
| +lost replies; grouping and mirrored Watch actions. Simulator and unit tests do |
| +not prove the unlock guarantee. Keep the production capability off until these |
| +pass. No deployment or release performed. |
| + |
| +## Captures and handoff validation |
| + |
| +iPhone UI tests pass: 2 tests, 0 failures (`iphone-ui-final.log`). Both |
| +captures are in `site/build/slice8/`; the Merge capture shows facts, summary and |
| +the final Merge/Not now buttons. The first run hit XCTest's 128-character |
| +identifier limit; its assertion now uses NSPredicate. The existing booted |
| +iPhone 18 Pro was reused and the fixture app terminated. No simulator created |
| +or booted. Mac capture uses an in-app NSView snapshot with its sheet backing |
| +composited to an opaque image, without screen-capture permission. |
| + |
| +The restored native run has 19 notification tests in 8 suites. Mac builds |
| +(`mac-build.log`). The no-credential-write guard, share packaging/copy guard and |
| +336-key parity check pass. Full suites belong to Linux hub CI; its head and |
| +verdict are recorded in the handoff and archived CI JSON after push. |
diff --git a/internal/equipo/app.go b/internal/equipo/app.go| index 0de853b4..d1e24a3b 100644 |
| --- a/internal/equipo/app.go |
| +++ b/internal/equipo/app.go |
| @@ -186,6 +186,7 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| 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) |
| + store.Chat().SetNotificationActions(cfg.NotificationActions) |
| // What the Assistant's provider calls could not do, by call id only. |
| store.Chat().SetLogger(logger) |
| if cfg.OficinaConnectOrigin != "" { |
diff --git a/internal/equipo/chat/card_read.go b/internal/equipo/chat/card_read.go| new file mode 100644 |
| index 00000000..a087705c |
| --- /dev/null |
| +++ b/internal/equipo/chat/card_read.go |
| @@ -0,0 +1,35 @@ |
| +package chat |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "strings" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "gorm.io/gorm" |
| +) |
| + |
| +// DeviceCard reads one Coordinator card without the snapshot's newest-50 |
| +// window. c_ is reserved for thin cards; legacy ids never fall through here. |
| +func (s *Store) DeviceCard(ctx context.Context, person, credential, id string) (out wire.Card, err error) { |
| + if !strings.HasPrefix(id, "c_") { |
| + return out, ErrNotFound |
| + } |
| + err = s.read(ctx, func(tx *gorm.DB) error { |
| + if s.authority.CurrentPerson(ctx, tx) != nil { |
| + return ErrNotFound |
| + } |
| + if s.pushCurrent(tx, person, credential) != nil { |
| + return ErrNotFound |
| + } |
| + var c cardRecord |
| + if err := tx.Where("id = ? AND person = ? AND (held IS NULL OR held = ?) AND coalesce(lane, '') = ?", id, person, false, wire.LaneCoordinator).Take(&c).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| + return ErrNotFound |
| + } else if err != nil { |
| + return err |
| + } |
| + out, err = (&txn{s: s, db: tx, viewer: person}).cardView(c) |
| + return err |
| + }) |
| + return |
| +} |
diff --git a/internal/equipo/chat/http.go b/internal/equipo/chat/http.go| index 17ff1ac3..9df65fb2 100644 |
| --- a/internal/equipo/chat/http.go |
| +++ b/internal/equipo/chat/http.go |
| @@ -88,6 +88,7 @@ func (h *HTTP) Mount(r chi.Router) { |
| r.Delete("/projects/{id}/names", h.bearer(h.projectForgetName)) |
| r.Post("/projects", h.bearer(h.addProject)) |
| r.Delete("/projects/{id}", h.bearer(h.removeProject)) |
| + r.Get("/cards/{id}", h.thinOr("GET /cards/{id}", thinCard, h.bearer(h.card))) |
| 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)) |
| @@ -537,7 +538,7 @@ func (h *HTTP) answer(w http.ResponseWriter, r *http.Request, p personapi.Person |
| h.fail(w, r, err) |
| return |
| } |
| - out, current, err := h.Store.Answer(r.Context(), p.Address, chi.URLParam(r, "id"), in) |
| + out, current, err := h.Store.AnswerDevice(r.Context(), p.Address, p.CredentialID, chi.URLParam(r, "id"), in) |
| if errors.Is(err, ErrCardConflict) { |
| // A card the person can still act on was only stale; one that is |
| // done (answered, changed, removed) is answered. |
| @@ -839,7 +840,36 @@ func (h *HTTP) cancelTask(w http.ResponseWriter, r *http.Request, p personapi.Pe |
| } |
| func (h *HTTP) retryTask(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| - attempt, err := h.Store.RetryTask(r.Context(), p.Address, chi.URLParam(r, "id")) |
| + var bound *wire.RetryTask |
| + if r.Body != nil && r.ContentLength != 0 { |
| + var raw json.RawMessage |
| + if err := readJSON(r, &raw); err != nil { |
| + h.fail(w, r, err) |
| + return |
| + } |
| + var fields map[string]json.RawMessage |
| + if json.Unmarshal(raw, &fields) != nil || fields == nil { |
| + h.fail(w, r, ErrInvalid) |
| + return |
| + } |
| + // Existing native clients send an empty JSON object. Any supplied field |
| + // opts into binding; a partial or unknown body never becomes legacy retry. |
| + if len(fields) > 0 { |
| + var input wire.RetryTask |
| + if wire.Strict(raw, &input) != nil { |
| + h.fail(w, r, ErrInvalid) |
| + return |
| + } |
| + bound = &input |
| + } |
| + } |
| + var attempt int64 |
| + var err error |
| + if bound != nil { |
| + attempt, err = h.Store.RetryTaskBound(r.Context(), p.Address, p.CredentialID, chi.URLParam(r, "id"), *bound) |
| + } else { |
| + attempt, err = h.Store.RetryTask(r.Context(), p.Address, chi.URLParam(r, "id")) |
| + } |
| if err != nil { |
| h.fail(w, r, err) |
| return |
| @@ -1089,3 +1119,16 @@ func (h *HTTP) removePlacementNote(w http.ResponseWriter, r *http.Request, p per |
| } |
| w.WriteHeader(http.StatusNoContent) |
| } |
| + |
| +// Legacy cards use rand.Text identifiers (or native:/Coordinator aliases), |
| +// never the thin store's c_ prefix. Dispatch is independent of visibility. |
| +func thinCard(r *http.Request) bool { return strings.HasPrefix(chi.URLParam(r, "id"), "c_") } |
| +func (h *HTTP) card(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| + out, err := h.Store.DeviceCard(r.Context(), p.Address, p.CredentialID, chi.URLParam(r, "id")) |
| + if err != nil { |
| + h.fail(w, r, err) |
| + return |
| + } |
| + w.Header().Set("ETag", fmt.Sprintf(`"%d"`, out.Revision)) |
| + writeJSON(w, http.StatusOK, out) |
| +} |
diff --git a/internal/equipo/chat/notification_actions_test.go b/internal/equipo/chat/notification_actions_test.go| index dfef6c15..0888fcfd 100644 |
| --- a/internal/equipo/chat/notification_actions_test.go |
| +++ b/internal/equipo/chat/notification_actions_test.go |
| @@ -2,7 +2,10 @@ package chat |
| import ( |
| "amadan.net/oficina/equipo/internal/wire" |
| + "context" |
| "errors" |
| + "gorm.io/gorm" |
| + "strings" |
| "testing" |
| "time" |
| ) |
| @@ -26,6 +29,10 @@ func TestNotificationAnswerReceipt(t *testing.T) { |
| if _, _, err = r.s.AnswerDevice(r.ctx, hkOwner, "cr_phone", c.ID, in); !errors.Is(err, ErrConflict) { |
| t.Fatal("changed body", err) |
| } |
| + in.Choice = " main " |
| + if _, _, err = r.s.AnswerDevice(r.ctx, hkOwner, "cr_phone", c.ID, in); !errors.Is(err, ErrConflict) { |
| + t.Fatal("changed untrimmed body", err) |
| + } |
| in.Choice = "main" |
| r.revoked["cr_phone"] = true |
| if _, _, err = r.s.AnswerDevice(r.ctx, hkOwner, "cr_phone", c.ID, in); !errors.Is(err, ErrForbidden) { |
| @@ -58,7 +65,7 @@ func TestNotificationRetryBinding(t *testing.T) { |
| case "attempt": |
| in.Attempt++ |
| case "creator": |
| - person = "other@example.com" |
| + r.must(r.s.db.G.Model(&taskRecord{}).Where("id = ?", k.ID).Update("creator", "other@example.com").Error) |
| case "terminated": |
| r.must(r.s.db.G.Model(&stepRecord{}).Where("id = ?", in.StepID).Update("terminated", false).Error) |
| } |
| @@ -82,3 +89,70 @@ func TestNotificationRetryBinding(t *testing.T) { |
| }) |
| } |
| } |
| + |
| +func TestNotificationReceiptsRequireCurrentAuthority(t *testing.T) { |
| + for _, mode := range []string{"disabled", "credential", "member", "device", "invalid-key", "other-device", "inactive-member"} { |
| + t.Run(mode, func(t *testing.T) { |
| + r := newPushRig(t) |
| + r.s.SetNotificationActions(true) |
| + c := r.card("authority-card", wire.CardOpen) |
| + in := wire.AnswerCard{Revision: c.Revision, Choice: "main", IdempotencyKey: "authority-answer"} |
| + _, _, err := r.s.AnswerDevice(r.ctx, hkOwner, "cr_phone", c.ID, in) |
| + r.must(err) |
| + credential := "cr_phone" |
| + switch mode { |
| + case "disabled": |
| + r.s.SetNotificationActions(false) |
| + case "credential": |
| + credential = "" |
| + case "member": |
| + r.s.authority.CurrentPerson = func(context.Context, *gorm.DB) error { return ErrForbidden } |
| + case "device": |
| + r.revoked[credential] = true |
| + case "invalid-key": |
| + in.IdempotencyKey = strings.Repeat("x", 129) |
| + case "other-device": |
| + credential = "cr_other" |
| + case "inactive-member": |
| + r.must(r.s.db.G.Exec("UPDATE members SET active = 0 WHERE address = ?", hkOwner).Error) |
| + } |
| + if _, _, err = r.s.AnswerDevice(r.ctx, hkOwner, credential, c.ID, in); err == nil { |
| + t.Fatal("receipt bypassed current authority or binding") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestNotificationConcurrentReceiptsDoNotRepeatEffects(t *testing.T) { |
| + r := newPushRig(t) |
| + r.s.SetNotificationActions(true) |
| + c := r.card("concurrent-card", wire.CardOpen) |
| + in := wire.AnswerCard{Revision: c.Revision, Choice: "main", IdempotencyKey: "concurrent-answer"} |
| + start := make(chan struct{}) |
| + results := make(chan wire.Answered, 4) |
| + failures := make(chan error, 4) |
| + for range 4 { |
| + go func() { |
| + <-start |
| + result, _, err := r.s.AnswerDevice(r.ctx, hkOwner, "cr_phone", c.ID, in) |
| + results <- result |
| + failures <- err |
| + }() |
| + } |
| + close(start) |
| + var first wire.Answered |
| + for i := 0; i < 4; i++ { |
| + got := <-results |
| + if err := <-failures; err != nil { |
| + t.Fatal(err) |
| + } |
| + if i == 0 { |
| + first = got |
| + } else if got.Message.ID != first.Message.ID || got.Turn.ID != first.Turn.ID { |
| + t.Fatal("duplicate effect") |
| + } |
| + } |
| + if r.count("SELECT count(*) FROM chat_notification_receipts") != 1 || r.count("SELECT count(*) FROM chat_messages WHERE idempotency_key = 'card:concurrent-card'") != 1 { |
| + t.Fatal("duplicate receipt or message") |
| + } |
| +} |
diff --git a/internal/equipo/chat/notification_card_test.go b/internal/equipo/chat/notification_card_test.go| new file mode 100644 |
| index 00000000..47de314a |
| --- /dev/null |
| +++ b/internal/equipo/chat/notification_card_test.go |
| @@ -0,0 +1,114 @@ |
| +package chat |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/personapi" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "github.com/go-chi/chi/v5" |
| + "net/http" |
| + "net/http/httptest" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "gorm.io/gorm" |
| +) |
| + |
| +func TestNotificationCardDirectRead(t *testing.T) { |
| + r := newPushRig(t) |
| + old := r.card("c_old", wire.CardOpen) |
| + r.must(r.s.db.G.Model(&cardRecord{}).Where("id = ?", old.ID).Update("revision", 7).Error) |
| + for i := 0; i < wire.MaxProjectCards; i++ { |
| + r.now = r.now.Add(time.Second) |
| + r.card(fmt.Sprintf("c_new%03d", i), wire.CardOpen) |
| + } |
| + var cards []wire.Card |
| + r.must(r.tx(func(t *txn) error { var err error; cards, err = t.snapshotCards(hkOwner); return err })) |
| + for _, c := range cards { |
| + if c.ID == old.ID { |
| + t.Fatal("fixture did not exceed window") |
| + } |
| + } |
| + got, err := r.s.DeviceCard(r.ctx, hkOwner, "cr_phone", old.ID) |
| + r.must(err) |
| + if got.Question != old.Question || len(got.Options) != 2 || got.Options[0] != "main" || got.Revision != 7 { |
| + t.Fatal(got) |
| + } |
| + for _, c := range cards { |
| + direct, err := r.s.DeviceCard(r.ctx, hkOwner, "cr_phone", c.ID) |
| + r.must(err) |
| + a, _ := json.Marshal(c) |
| + b, _ := json.Marshal(direct) |
| + if string(a) != string(b) { |
| + t.Fatalf("projection differs: %s != %s", a, b) |
| + } |
| + } |
| +} |
| + |
| +func TestNotificationCardVisibility(t *testing.T) { |
| + for _, mode := range []string{"missing", "person", "held", "lane", "member", "device", "current", "wrong-store"} { |
| + t.Run(mode, func(t *testing.T) { |
| + r := newPushRig(t) |
| + c := r.card("c_read", wire.CardOpen) |
| + id := c.ID |
| + switch mode { |
| + case "missing": |
| + id = "c_missing" |
| + case "person": |
| + r.must(r.s.db.G.Model(&cardRecord{}).Where("id = ?", id).Update("person", "other@example.com").Error) |
| + case "held": |
| + r.must(r.s.db.G.Model(&cardRecord{}).Where("id = ?", id).Update("held", true).Error) |
| + case "lane": |
| + r.must(r.s.db.G.Model(&cardRecord{}).Where("id = ?", id).Update("lane", wire.LaneAssistant).Error) |
| + case "member": |
| + r.must(r.s.db.G.Exec("UPDATE members SET active = 0 WHERE address = ?", hkOwner).Error) |
| + case "device": |
| + r.revoked["cr_phone"] = true |
| + case "current": |
| + r.s.authority.CurrentPerson = func(context.Context, *gorm.DB) error { return ErrForbidden } |
| + case "wrong-store": |
| + r.must(r.s.db.G.Model(&cardRecord{}).Where("id = ?", id).Update("id", "LEGACYCARD").Error) |
| + id = "LEGACYCARD" |
| + } |
| + if _, err := r.s.DeviceCard(r.ctx, hkOwner, "cr_phone", id); !errors.Is(err, ErrNotFound) { |
| + t.Fatalf("%s: %v", mode, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestNotificationCardDispatchDoesNotFallThrough(t *testing.T) { |
| + r := newPushRig(t) |
| + c := r.card("c_route", wire.CardOpen) |
| + legacyCalls := 0 |
| + legacy := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { legacyCalls++; w.Write([]byte(`{"legacy":true}`)) }) |
| + h := &HTTP{Store: r.s, Old: map[string]http.Handler{"GET /cards/{id}": legacy}, Authenticate: func(*http.Request) (personapi.PersonPrincipal, error) { |
| + return personapi.PersonPrincipal{Address: hkOwner, CredentialID: "cr_phone"}, nil |
| + }} |
| + router := chi.NewRouter() |
| + h.Mount(router) |
| + for _, id := range []string{c.ID, "c_missing", "LEGACY"} { |
| + req := httptest.NewRequest("GET", "/cards/"+id, nil) |
| + req.Header.Set("Authorization", "Bearer fixture") |
| + w := httptest.NewRecorder() |
| + router.ServeHTTP(w, req) |
| + switch id { |
| + case c.ID: |
| + var card wire.Card |
| + r.must(json.Unmarshal(w.Body.Bytes(), &card)) |
| + if w.Code != 200 || card.ID != c.ID || w.Header().Get("ETag") != `"1"` || w.Header().Get("Cache-Control") != "no-store" { |
| + t.Fatal(w.Code, w.Body.String(), w.Header()) |
| + } |
| + case "c_missing": |
| + if w.Code != 404 || legacyCalls != 0 { |
| + t.Fatal("thin refusal fell through", w.Code, legacyCalls) |
| + } |
| + case "LEGACY": |
| + if w.Body.String() != `{"legacy":true}` || legacyCalls != 1 { |
| + t.Fatal("legacy route changed", w.Body.String(), legacyCalls) |
| + } |
| + } |
| + } |
| +} |
diff --git a/internal/equipo/chat/notification_http_test.go b/internal/equipo/chat/notification_http_test.go| new file mode 100644 |
| index 00000000..5735f1cf |
| --- /dev/null |
| +++ b/internal/equipo/chat/notification_http_test.go |
| @@ -0,0 +1,105 @@ |
| +package chat |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/personapi" |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "github.com/go-chi/chi/v5" |
| +) |
| + |
| +func TestNotificationHTTPRetryCompatibility(t *testing.T) { |
| + for _, mode := range []string{"legacy", "empty", "bound", "stale", "partial", "zero", "unknown", "null"} { |
| + t.Run(mode, func(t *testing.T) { |
| + r := newPushRig(t) |
| + r.s.SetNotificationActions(true) |
| + k := r.task("tk-http", "Fix", hkOwner) |
| + r.step(&k, "st-http", wire.SpecialistEngineering, wire.StepFailed) |
| + k = r.load(k.ID) |
| + input := wire.RetryTask{Revision: k.Revision, StepID: "st-http", StepRevision: 1, Attempt: 1, IdempotencyKey: "notification-http-retry"} |
| + if mode == "stale" { |
| + input.Revision++ |
| + } |
| + raw, _ := json.Marshal(input) |
| + body := string(raw) |
| + switch mode { |
| + case "legacy": |
| + body = "" |
| + case "empty": |
| + body = "{ }" |
| + case "partial": |
| + body = `{"revision":1}` |
| + case "zero": |
| + body = `{"revision":0}` |
| + case "unknown": |
| + body = `{"extra":1}` |
| + case "null": |
| + body = "null" |
| + } |
| + send := func() *httptest.ResponseRecorder { |
| + route := chi.NewRouteContext() |
| + route.URLParams.Add("id", k.ID) |
| + req := httptest.NewRequest("POST", "/tasks/"+k.ID+"/retry", strings.NewReader(body)).WithContext(context.WithValue(r.ctx, chi.RouteCtxKey, route)) |
| + if body != "" { |
| + req.Header.Set("Content-Type", "application/json") |
| + } |
| + res := httptest.NewRecorder() |
| + (&HTTP{Store: r.s}).retryTask(res, req, personapi.PersonPrincipal{Address: hkOwner, CredentialID: "cr_phone"}) |
| + return res |
| + } |
| + got := send() |
| + want := 422 |
| + if mode == "legacy" || mode == "empty" || mode == "bound" { |
| + want = 202 |
| + } |
| + if mode == "stale" { |
| + want = 409 |
| + } |
| + if got.Code != want { |
| + t.Fatal(mode, got.Code, got.Body.String()) |
| + } |
| + if mode == "bound" { |
| + again := send() |
| + if again.Code != 202 || again.Body.String() != got.Body.String() { |
| + t.Fatal("replay", again.Code, again.Body.String()) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestNotificationHTTPAnswerReceipt(t *testing.T) { |
| + r := newPushRig(t) |
| + r.s.SetNotificationActions(true) |
| + c := r.card("c-http", wire.CardOpen) |
| + send := func(choice string) *httptest.ResponseRecorder { |
| + raw, _ := json.Marshal(wire.AnswerCard{Revision: c.Revision, Choice: choice, IdempotencyKey: "notification-http-answer"}) |
| + route := chi.NewRouteContext() |
| + route.URLParams.Add("id", c.ID) |
| + req := httptest.NewRequest("POST", "/cards/"+c.ID+"/answer", strings.NewReader(string(raw))).WithContext(context.WithValue(r.ctx, chi.RouteCtxKey, route)) |
| + req.Header.Set("Content-Type", "application/json") |
| + res := httptest.NewRecorder() |
| + (&HTTP{Store: r.s}).answer(res, req, personapi.PersonPrincipal{Address: hkOwner, CredentialID: "cr_phone"}) |
| + return res |
| + } |
| + first, again := send("main"), send("main") |
| + if first.Code != 200 || again.Code != 200 { |
| + t.Fatal(first.Code, again.Code) |
| + } |
| + var a, b wire.Answered |
| + r.must(json.Unmarshal(first.Body.Bytes(), &a)) |
| + r.must(json.Unmarshal(again.Body.Bytes(), &b)) |
| + // Receipts retain result identities, not duplicate message text or a stale |
| + // response snapshot. A later read can include newer presentation timestamps. |
| + if a.Message.ID == "" || a.Message.ID != b.Message.ID || a.Turn.ID != b.Turn.ID || a.Card.ID != b.Card.ID || a.Card.Revision != b.Card.Revision { |
| + t.Fatal(a, b) |
| + } |
| + changed := send("release") |
| + if changed.Code != 409 || !strings.Contains(changed.Body.String(), "idempotency_conflict") { |
| + t.Fatal(changed.Code, changed.Body.String()) |
| + } |
| +} |
diff --git a/internal/equipo/chat/notification_payload.go b/internal/equipo/chat/notification_payload.go| new file mode 100644 |
| index 00000000..0ed4fed6 |
| --- /dev/null |
| +++ b/internal/equipo/chat/notification_payload.go |
| @@ -0,0 +1,67 @@ |
| +package chat |
| + |
| +import ( |
| + "encoding/json" |
| + "slices" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/push" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// notificationIntent enriches only an opted-in device's existing alert. Any |
| +// unknown or incomplete state remains open-only. The receiver must recheck all |
| +// authority and current state; this payload is not a capability. |
| +func (t *txn) notificationIntent(in push.Intent, device push.Registration) push.Intent { |
| + if !t.s.NotificationActions() || device.ActionsVersion != 1 || !push.ValidActionBinding(device.BindingID) || |
| + (in.Kind != push.KindAlert && in.Kind != push.KindPassive) { |
| + return in |
| + } |
| + a := &wire.PushActions{Version: 1, BindingID: device.BindingID, NotificationID: push.NewID()} |
| + switch in.Data.Kind { |
| + case wire.PushCard: |
| + var c cardRecord |
| + if t.db.Where("id = ? AND person = ?", in.Data.CardID, device.Person).Take(&c).Error != nil || |
| + c.State != wire.CardOpen || c.Revision <= 0 || c.Held { |
| + return in |
| + } |
| + var options []string |
| + if c.Options != "" && json.Unmarshal([]byte(c.Options), &options) != nil { |
| + return in |
| + } |
| + switch c.Kind { |
| + case wire.CardQuestion: |
| + in.Category = "equipo.question.choices.v1" |
| + if len(options) == 0 && c.Question != "" && in.Body == c.Question && in.BodyKey == "" { |
| + in.Category = "equipo.question.text.v1" |
| + } |
| + case wire.CardMerge: |
| + if c.TaskID == "" || c.TaskID != in.Data.TaskID || !slices.Contains(options, "merge") { |
| + return in |
| + } |
| + for _, option := range options { |
| + if !slices.Contains([]string{wire.ChoiceMerge, wire.ChoiceWait, wire.ChoiceWaitMac, wire.ChoiceNotNow}, option) { |
| + return in |
| + } |
| + } |
| + in.Category = "equipo.merge.v1" |
| + default: |
| + return in |
| + } |
| + a.CardKind, a.CardRevision = c.Kind, c.Revision |
| + case wire.PushTask: |
| + k, err := t.loadTask(in.Data.TaskID) |
| + if err != nil || k.Creator != device.Person || wire.FinalStage(k.Stage) || k.CancelRequested || k.CopyHold || k.MoveProject != "" { |
| + return in |
| + } |
| + st, found, err := t.latestStep(k.ID) |
| + if err != nil || !found || st.State != wire.StepFailed || !st.Terminated || st.Revision <= 0 || st.Attempt <= 0 { |
| + return in |
| + } |
| + a.TaskRevision, a.StepID, a.StepRevision, a.Attempt = k.Revision, st.ID, st.Revision, st.Attempt |
| + in.Category = "equipo.stopped.v1" |
| + default: |
| + return in |
| + } |
| + in.Data.Actions = a |
| + return in |
| +} |
diff --git a/internal/equipo/chat/notification_payload_test.go b/internal/equipo/chat/notification_payload_test.go| new file mode 100644 |
| index 00000000..17f0cfd4 |
| --- /dev/null |
| +++ b/internal/equipo/chat/notification_payload_test.go |
| @@ -0,0 +1,235 @@ |
| +package chat |
| + |
| +import ( |
| + "encoding/json" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/push" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +func TestNotificationPayloadPrivacyAndOptIn(t *testing.T) { |
| + for _, mode := range []string{"text", "options", "clipped", "unknown", "disabled", "closed", "malformed"} { |
| + t.Run(mode, func(t *testing.T) { |
| + r := newPushRig(t) |
| + r.s.SetNotificationActions(true) |
| + r.register(hkOwner, "cr_phone", wire.RegisterPush{Token: pushDevice, Environment: wire.APNsProduction, Platform: wire.PlatformIOS, ActionsVersion: 1, BindingID: "12345678-1234-4234-8234-123456789abc"}) |
| + r.register(hkOwner, "cr_mac", wire.RegisterPush{Token: pushMac, Environment: wire.APNsProduction, Platform: wire.PlatformMacOS}) |
| + c := r.card("notification-card", wire.CardOpen) |
| + c.Options = "[]" |
| + switch mode { |
| + case "options": |
| + c.Options = `["PRIVATE option not in the alert"]` |
| + case "clipped": |
| + c.Question = strings.Repeat("Question ", 100) |
| + case "unknown": |
| + c.Kind = "future" |
| + case "disabled": |
| + r.s.SetNotificationActions(false) |
| + case "closed": |
| + c.State = wire.CardAnswered |
| + case "malformed": |
| + c.Options = `{"bad":"options"}` |
| + } |
| + r.must(r.s.db.G.Save(&c).Error) |
| + r.clear() |
| + in := push.Intent{Kind: push.KindAlert, Body: push.Clip(c.Question), Category: push.CategoryNeedsYou, Data: wire.PushData{Kind: wire.PushCard, CardID: c.ID}} |
| + r.must(r.tx(func(tx *txn) error { |
| + devices, err := push.Device(tx.db, hkOwner, "cr_phone") |
| + if err != nil { |
| + return err |
| + } |
| + legacy, err := push.Device(tx.db, hkOwner, "cr_mac") |
| + if err != nil { |
| + return err |
| + } |
| + _, err = tx.enqueuePush(hkOwner, append(devices, legacy...), in) |
| + return err |
| + })) |
| + rows := r.outbox() |
| + if len(rows) != 2 { |
| + t.Fatal(len(rows)) |
| + } |
| + for _, row := range rows { |
| + var payload struct { |
| + APS struct { |
| + Category string |
| + Alert struct{ Body string } |
| + } |
| + Equipo wire.PushData |
| + } |
| + r.must(json.Unmarshal([]byte(row.Payload), &payload)) |
| + if payload.APS.Alert.Body != in.Body || strings.Contains(row.Payload, "PRIVATE") || len(row.Payload) > push.MaxPayload { |
| + t.Fatal("changed preview or leaked options", mode) |
| + } |
| + active := row.Credential == "cr_phone" && (mode == "text" || mode == "options" || mode == "clipped") |
| + if !active { |
| + if payload.Equipo.Actions != nil || payload.APS.Category != push.CategoryNeedsYou { |
| + t.Fatal("not open-only", mode, row.Credential) |
| + } |
| + continue |
| + } |
| + a := payload.Equipo.Actions |
| + if a == nil || a.Version != 1 || a.BindingID != "12345678-1234-4234-8234-123456789abc" || a.CardRevision != c.Revision || a.CardKind != c.Kind || a.NotificationID == "" { |
| + t.Fatal("missing binding", a) |
| + } |
| + want := "equipo.question.choices.v1" |
| + if mode == "text" { |
| + want = "equipo.question.text.v1" |
| + } |
| + if payload.APS.Category != want { |
| + t.Fatal(payload.APS.Category, want) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestNotificationRegistrationGates(t *testing.T) { |
| + r := newPushRig(t) |
| + in := wire.RegisterPush{Token: pushDevice, Environment: wire.APNsProduction, Platform: wire.PlatformIOS, ActionsVersion: 1, BindingID: "12345678-1234-4234-8234-123456789abc"} |
| + if _, err := r.s.RegisterPush(r.ctx, hkOwner, "cr_phone", in); err == nil { |
| + t.Fatal("off by default") |
| + } |
| + r.s.SetNotificationActions(true) |
| + for _, mode := range []string{"version", "missing", "invalid", "unexpected"} { |
| + bad := in |
| + switch mode { |
| + case "version": |
| + bad.ActionsVersion = 2 |
| + case "missing": |
| + bad.BindingID = "" |
| + case "invalid": |
| + bad.BindingID = "https://untrusted.invalid" |
| + case "unexpected": |
| + bad.ActionsVersion = 0 |
| + } |
| + if _, err := r.s.RegisterPush(r.ctx, hkOwner, "cr_phone", bad); err == nil { |
| + t.Fatal(mode) |
| + } |
| + } |
| +} |
| + |
| +func TestNotificationRetryPayloadBindsOnlyTheCurrentFailure(t *testing.T) { |
| + for _, mode := range []string{"valid", "creator", "done", "cancel", "copy", "moving", "running", "unterminated", "revision", "attempt"} { |
| + t.Run(mode, func(t *testing.T) { |
| + r := newPushRig(t) |
| + r.s.SetNotificationActions(true) |
| + k := r.task("tk-bind", "Fix", hkOwner) |
| + r.step(&k, "st-bind", wire.SpecialistEngineering, wire.StepFailed) |
| + k = r.load(k.ID) |
| + device := push.Registration{Person: hkOwner, ActionsVersion: 1, BindingID: "12345678-1234-4234-8234-123456789abc"} |
| + switch mode { |
| + case "creator": |
| + device.Person = "other@example.com" |
| + case "done": |
| + k.Stage = wire.StageDone |
| + case "cancel": |
| + k.CancelRequested = true |
| + case "copy": |
| + k.CopyHold = true |
| + case "moving": |
| + k.MoveProject = "another" |
| + case "running": |
| + r.must(r.s.db.G.Model(&stepRecord{}).Where("id = ?", "st-bind").Update("state", wire.StepRunning).Error) |
| + case "unterminated": |
| + r.must(r.s.db.G.Model(&stepRecord{}).Where("id = ?", "st-bind").Update("terminated", false).Error) |
| + case "revision": |
| + r.must(r.s.db.G.Model(&stepRecord{}).Where("id = ?", "st-bind").Update("revision", 0).Error) |
| + case "attempt": |
| + r.must(r.s.db.G.Model(&stepRecord{}).Where("id = ?", "st-bind").Update("attempt", 0).Error) |
| + } |
| + r.must(r.s.db.G.Save(&k).Error) |
| + in := push.Intent{Kind: push.KindPassive, Data: wire.PushData{Kind: wire.PushTask, TaskID: k.ID}} |
| + var out push.Intent |
| + r.must(r.tx(func(tx *txn) error { out = tx.notificationIntent(in, device); return nil })) |
| + if mode != "valid" { |
| + if out.Data.Actions != nil { |
| + t.Fatal(mode) |
| + } |
| + return |
| + } |
| + a := out.Data.Actions |
| + if a == nil || a.TaskRevision != k.Revision || a.StepID != "st-bind" || a.StepRevision != 1 || a.Attempt != 1 || out.Category != "equipo.stopped.v1" { |
| + t.Fatal(a) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestNotificationOversizeBindingFallsBackToOriginalAlert(t *testing.T) { |
| + r := newPushRig(t) |
| + r.s.SetNotificationActions(true) |
| + r.register(hkOwner, "cr_phone", wire.RegisterPush{Token: pushDevice, Environment: wire.APNsProduction, Platform: wire.PlatformIOS, ActionsVersion: 1, BindingID: "12345678-1234-4234-8234-123456789abc"}) |
| + c := r.card("c-size", wire.CardOpen) |
| + r.clear() |
| + in := push.Intent{Kind: push.KindAlert, Category: push.CategoryNeedsYou, Body: strings.Repeat("x", 3800), Data: wire.PushData{Kind: wire.PushCard, CardID: c.ID}} |
| + raw, _, err := push.Render(in, r.s.authority.Copy, 0, r.now) |
| + r.must(err) |
| + if len(raw) > push.MaxPayload { |
| + t.Fatal(len(raw)) |
| + } |
| + r.must(r.tx(func(tx *txn) error { |
| + d, e := push.Device(tx.db, hkOwner, "cr_phone") |
| + if e != nil { |
| + return e |
| + } |
| + _, e = tx.enqueuePush(hkOwner, d, in) |
| + return e |
| + })) |
| + rows := r.outbox() |
| + if len(rows) != 1 || rows[0].Payload != string(raw) { |
| + t.Fatal("lost alert or retained partial binding", len(rows)) |
| + } |
| +} |
| + |
| +func TestNotificationMergePayloadIsNavigationOnly(t *testing.T) { |
| + for _, mode := range []string{"valid", "not_now", "wait_mac", "unknown-option", "no-merge", "no-task", "other-task", "other-person", "held", "revision"} { |
| + t.Run(mode, func(t *testing.T) { |
| + r := newPushRig(t) |
| + r.s.SetNotificationActions(true) |
| + c := r.card("c-merge", wire.CardOpen) |
| + c.Kind = wire.CardMerge |
| + c.TaskID = "tk" |
| + c.Options = `["merge","wait"]` |
| + switch mode { |
| + case "not_now", "wait_mac": |
| + c.Options = `["merge","` + mode + `"]` |
| + case "unknown-option": |
| + c.Options = `["merge","future"]` |
| + case "no-merge": |
| + c.Options = `["wait"]` |
| + case "no-task": |
| + c.TaskID = "" |
| + case "other-task": |
| + c.TaskID = "other" |
| + case "other-person": |
| + c.Person = "other@example.com" |
| + case "held": |
| + c.Held = true |
| + case "revision": |
| + c.Revision = 0 |
| + } |
| + r.must(r.s.db.G.Save(&c).Error) |
| + in := push.Intent{Kind: push.KindAlert, Category: push.CategoryNeedsYou, Data: wire.PushData{Kind: wire.PushCard, CardID: c.ID, TaskID: "tk"}} |
| + var out push.Intent |
| + r.must(r.tx(func(tx *txn) error { |
| + out = tx.notificationIntent(in, push.Registration{Person: hkOwner, ActionsVersion: 1, BindingID: "12345678-1234-4234-8234-123456789abc"}) |
| + return nil |
| + })) |
| + if mode != "valid" && mode != "not_now" && mode != "wait_mac" { |
| + if out.Data.Actions != nil { |
| + t.Fatal(mode) |
| + } |
| + return |
| + } |
| + if out.Category != "equipo.merge.v1" || out.Data.Actions == nil || out.Data.Actions.CardRevision != c.Revision { |
| + t.Fatal(out) |
| + } |
| + if out.Data.Actions.StepID != "" || out.Data.Actions.TaskRevision != 0 { |
| + t.Fatal("merge must not carry write authority") |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/equipo/chat/projects.go b/internal/equipo/chat/projects.go| index c1d5d621..d469afba 100644 |
| --- a/internal/equipo/chat/projects.go |
| +++ b/internal/equipo/chat/projects.go |
| @@ -679,6 +679,7 @@ func (s *Store) Answer(ctx context.Context, person, id string, in wire.AnswerCar |
| } |
| func (s *Store) AnswerDevice(ctx context.Context, person, credential, id string, in wire.AnswerCard) (out wire.Answered, current wire.Card, err error) { |
| + digestInput := in |
| in.Choice = strings.TrimSpace(in.Choice) |
| if in.Choice == "" || len(in.Choice) > wire.MaxMessageBytes || !utf8.ValidString(in.Choice) || strings.ContainsRune(in.Choice, 0) { |
| return out, current, ErrInvalid |
| @@ -690,7 +691,7 @@ func (s *Store) AnswerDevice(ctx context.Context, person, credential, id string, |
| var receipt *notificationReceipt |
| if in.IdempotencyKey != "" { |
| var prior bool |
| - receipt, prior, err = t.actionReceipt(person, credential, "answer", id, in.IdempotencyKey, in) |
| + receipt, prior, err = t.actionReceipt(person, credential, "answer", id, in.IdempotencyKey, digestInput) |
| if err != nil { |
| return err |
| } |
diff --git a/internal/equipo/chat/push.go b/internal/equipo/chat/push.go| index d6487ec6..cbb3237b 100644 |
| --- a/internal/equipo/chat/push.go |
| +++ b/internal/equipo/chat/push.go |
| @@ -81,6 +81,9 @@ func (s *Store) pushCurrent(tx *gorm.DB, person, credential string) error { |
| // 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 in.ActionsVersion != 0 && !s.NotificationActions() { |
| + return out, ErrForbidden |
| + } |
| if credential == "" { |
| return out, ErrForbidden |
| } |
| @@ -310,7 +313,16 @@ func (t *txn) enqueuePush(person string, devices []push.Registration, in push.In |
| } |
| 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} |
| + // Add bindings per opted-in registration. An oversized enrichment keeps |
| + // the original alert, never a partial or actionable unbound payload. |
| + deviceRaw := raw |
| + enriched := t.notificationIntent(in, d) |
| + if enriched.Data.Actions != nil { |
| + if candidate, _, renderErr := push.Render(enriched, t.s.authority.Copy, badge, now); renderErr == nil { |
| + deviceRaw = candidate |
| + } |
| + } |
| + 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(deviceRaw), NextAt: now, CreatedAt: now, UpdatedAt: now} |
| if err := push.Enqueue(t.db, t.s.pushBox(), r, in.Coalesce); err != nil { |
| return written, err |
| } |
diff --git a/internal/equipo/config.go b/internal/equipo/config.go| index a6f60157..ab71278f 100644 |
| --- a/internal/equipo/config.go |
| +++ b/internal/equipo/config.go |
| @@ -26,6 +26,9 @@ type Config struct { |
| // AllowLoggedPush (EQUIPO_ALLOW_LOGGED_PUSH=1) logs pushes instead of |
| // sending them; like logged mail, only on loopback or staging. |
| AllowLoggedPush bool |
| + // NotificationActions is off until physical-device unlock and privacy checks. |
| + // Enable explicitly with EQUIPO_NOTIFICATION_ACTIONS=1 after those checks. |
| + NotificationActions 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 |
| @@ -61,6 +64,7 @@ func LoadConfig(getenv func(string) string) (Config, error) { |
| InstanceKey: strings.TrimSpace(getenv("EQUIPO_INSTANCE_KEY")), |
| AllowLoggedMail: getenv("EQUIPO_ALLOW_LOGGED_MAIL") == "1", |
| AllowLoggedPush: getenv("EQUIPO_ALLOW_LOGGED_PUSH") == "1", |
| + NotificationActions: getenv("EQUIPO_NOTIFICATION_ACTIONS") == "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")} |
diff --git a/internal/equipo/conversation/card_id_test.go b/internal/equipo/conversation/card_id_test.go| new file mode 100644 |
| index 00000000..ed6e0ccb |
| --- /dev/null |
| +++ b/internal/equipo/conversation/card_id_test.go |
| @@ -0,0 +1,44 @@ |
| +package conversation |
| + |
| +import ( |
| + "crypto/rand" |
| + "os" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// crypto/rand.Text's RFC 4648 alphabet contains neither lowercase c nor _. |
| +// Every persisted legacy card borrows its message's ID; Coordinator cards |
| +// borrow their turn's ID, and native questions have a native: prefix. |
| +func TestLegacyCardIDsCannotUseThinPrefix(t *testing.T) { |
| + const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" |
| + for i := 0; i < 256; i++ { |
| + id := rand.Text() |
| + if strings.HasPrefix(id, "c_") || strings.ContainsAny(id, "c_") { |
| + t.Fatal("legacy ID overlaps thin namespace") |
| + } |
| + for _, r := range id { |
| + if !strings.ContainsRune(alphabet, r) { |
| + t.Fatal("legacy generator alphabet changed") |
| + } |
| + } |
| + } |
| + // Pin the actual generators as well, so a generator replacement must |
| + // explicitly revisit the shared-route namespace contract. |
| + for _, file := range []string{"store.go", "coordinator.go"} { |
| + raw, err := os.ReadFile(file) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !strings.Contains(string(raw), "ID: rand.Text()") { |
| + t.Fatal(file, "changed its legacy ID generator") |
| + } |
| + } |
| + raw, err := os.ReadFile("cards.go") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !strings.Contains(string(raw), `ID: "native:" + q.ID`) { |
| + t.Fatal("native question alias prefix changed") |
| + } |
| +} |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index fdf32512..b1de56d8 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -737,7 +737,7 @@ 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 TABLE push_registrations (credential text PRIMARY KEY, person text, token text, environment text, platform text, start_token text, created_at datetime, updated_at datetime, actions_version integer, binding_id text); |
| 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); |
| @@ -799,3 +799,11 @@ CREATE INDEX preview_grant_expiry ON preview_grants(expires_at); |
| -- Replace pending passes and active grants by indexed device/task identity. |
| CREATE INDEX idx_preview_passes_device_task ON preview_passes(credential, task_id); |
| CREATE INDEX idx_preview_grants_device_task ON preview_grants(credential, task_id); |
| + |
| +CREATE TABLE chat_notification_receipts ( |
| + person text, credential text, operation text, target text, key text, |
| + digest text, card_id text, message_id text, turn_id text, attempt integer, |
| + expires_at datetime, |
| + PRIMARY KEY (person, credential, operation, target, key) |
| +); |
| +CREATE INDEX notification_receipt_expiry ON chat_notification_receipts(expires_at); |
diff --git a/internal/equipo/notification_config_test.go b/internal/equipo/notification_config_test.go| new file mode 100644 |
| index 00000000..3c56efd7 |
| --- /dev/null |
| +++ b/internal/equipo/notification_config_test.go |
| @@ -0,0 +1,16 @@ |
| +package equipo |
| + |
| +import "testing" |
| + |
| +func TestNotificationActionsOffByDefault(t *testing.T) { |
| + for _, value := range []string{"", "0", "true", "1"} { |
| + env := map[string]string{"EQUIPO_ORIGIN": "https://equipo.bds.oncarlos.com", "EQUIPO_INSTANCE_KEY": "fixture", "CARLOS_MAIL": "submit", "EQUIPO_NOTIFICATION_ACTIONS": value} |
| + cfg, err := LoadConfig(func(k string) string { return env[k] }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if cfg.NotificationActions != (value == "1") { |
| + t.Fatal(value, cfg.NotificationActions) |
| + } |
| + } |
| +} |
diff --git a/internal/equipo/person_api.go b/internal/equipo/person_api.go| index 2112891d..ed0a6ad3 100644 |
| --- a/internal/equipo/person_api.go |
| +++ b/internal/equipo/person_api.go |
| @@ -37,7 +37,7 @@ func (s *Store) personAPIRouter() chi.Router { |
| } |
| return nil |
| }} |
| - h := &personapi.Handler{App: s, CursorCodec: kernel.CursorCodec{Key: s.personKey}, Authenticate: auth.Authenticate, AuthenticateRoute: auth.AuthenticateRoute, Invalid: ErrInvalid, Forbidden: ErrForbidden, NotFound: ErrNotFound, Conflict: ErrConflict, Unavailable: ErrUnavailable, CursorExpired: ErrCursorExpired} |
| + h := &personapi.Handler{App: s, NotificationActions: s.Chat().NotificationActions, CursorCodec: kernel.CursorCodec{Key: s.personKey}, Authenticate: auth.Authenticate, AuthenticateRoute: auth.AuthenticateRoute, Invalid: ErrInvalid, Forbidden: ErrForbidden, NotFound: ErrNotFound, Conflict: ErrConflict, Unavailable: ErrUnavailable, CursorExpired: ErrCursorExpired} |
| r := h.Router() |
| // The thin task routes share three paths with the old engine's; until |
| // the slice 7 sweep, those keep serving the old tasks. |
diff --git a/internal/equipo/personapi/conversation.go b/internal/equipo/personapi/conversation.go| index 4dda8cf8..8ca3b551 100644 |
| --- a/internal/equipo/personapi/conversation.go |
| +++ b/internal/equipo/personapi/conversation.go |
| @@ -62,12 +62,14 @@ func (h *Handler) read(ctx context.Context, a kernel.Actor, op, id, cursor strin |
| v, err := h.App.TaskPlan(ctx, a, id) |
| return Result{ProjectPlan(v), v.Revision}, err |
| case "capabilities": |
| + enabled := h.NotificationActions != nil && h.NotificationActions() |
| return Result{struct { |
| - Version string `json:"version"` |
| - BrowserSession bool `json:"browser_session"` |
| - DeviceBearer bool `json:"device_bearer"` |
| - Part string `json:"part"` |
| - }{"1.0.0", true, true, "3b"}, 1}, nil |
| + NotificationActions bool `json:"notification_actions_v1"` |
| + Version string `json:"version"` |
| + BrowserSession bool `json:"browser_session"` |
| + DeviceBearer bool `json:"device_bearer"` |
| + Part string `json:"part"` |
| + }{enabled, "1.0.0", true, true, "3b"}, 1}, nil |
| } |
| out, err := h.App.PersonAPIRead(ctx, a, op, id, cursor, limit) |
| if err != nil { |
diff --git a/internal/equipo/personapi/handler.go b/internal/equipo/personapi/handler.go| index c4fde992..0a52c158 100644 |
| --- a/internal/equipo/personapi/handler.go |
| +++ b/internal/equipo/personapi/handler.go |
| @@ -17,6 +17,7 @@ import ( |
| ) |
| type Handler struct { |
| + NotificationActions func() bool |
| App Application |
| CursorCodec kernel.CursorCodec |
| Authenticate func(*http.Request) (PersonPrincipal, error) |
diff --git a/internal/equipo/personapi/notification_capability_test.go b/internal/equipo/personapi/notification_capability_test.go| new file mode 100644 |
| index 00000000..b24a57db |
| --- /dev/null |
| +++ b/internal/equipo/personapi/notification_capability_test.go |
| @@ -0,0 +1,29 @@ |
| +package personapi |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "context" |
| + "encoding/json" |
| + "testing" |
| +) |
| + |
| +func TestNotificationCapabilityOptIn(t *testing.T) { |
| + for _, enabled := range []bool{false, true} { |
| + h := Handler{NotificationActions: func() bool { return enabled }} |
| + out, err := h.read(context.Background(), kernel.Actor{}, "capabilities", "", "", 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + raw, err := json.Marshal(out.Value) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var value map[string]any |
| + if err := json.Unmarshal(raw, &value); err != nil { |
| + t.Fatal(err) |
| + } |
| + if value["notification_actions_v1"] != enabled { |
| + t.Fatal(string(raw)) |
| + } |
| + } |
| +} |
diff --git a/internal/equipo/push/store.go b/internal/equipo/push/store.go| index 56c0410f..49f421fa 100644 |
| --- a/internal/equipo/push/store.go |
| +++ b/internal/equipo/push/store.go |
| @@ -4,6 +4,7 @@ import ( |
| "crypto/rand" |
| "errors" |
| "fmt" |
| + "regexp" |
| "strings" |
| "time" |
| @@ -21,14 +22,16 @@ var Models = []any{&Registration{}, &ActivityToken{}, &OutboxRecord{}, &MemoryRe |
| // 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 |
| + ActionsVersion int |
| + BindingID string |
| + 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" } |
| @@ -135,7 +138,16 @@ func hexToken(s string) bool { |
| // Validate checks a registration: hex tokens, a known environment and |
| // platform, and a push-to-start token only on iPhone. |
| +var actionBindingPattern = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`) |
| + |
| +func ValidActionBinding(id string) bool { return actionBindingPattern.MatchString(id) } |
| + |
| func Validate(in wire.RegisterPush) error { |
| + if (in.ActionsVersion != 0 && in.ActionsVersion != 1) || |
| + (in.ActionsVersion == 0 && in.BindingID != "") || |
| + (in.ActionsVersion == 1 && !ValidActionBinding(in.BindingID)) { |
| + return ErrInvalid |
| + } |
| if !hexToken(in.Token) || in.StartToken != "" && !hexToken(in.StartToken) { |
| return ErrInvalid |
| } |
| @@ -172,8 +184,8 @@ func Register(tx *gorm.DB, box Box, person, credential string, in wire.RegisterP |
| 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 |
| + r := Registration{ActionsVersion: in.ActionsVersion, BindingID: in.BindingID, 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", "actions_version", "binding_id"})}).Create(&r).Error |
| return wire.PushRegistration{Environment: r.Environment, Platform: r.Platform, LiveActivities: start != "", UpdatedAt: now}, err |
| } |
diff --git a/internal/plan3test/notification_card_test.go b/internal/plan3test/notification_card_test.go| new file mode 100644 |
| index 00000000..de951778 |
| --- /dev/null |
| +++ b/internal/plan3test/notification_card_test.go |
| @@ -0,0 +1,46 @@ |
| +package plan3test |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/personapi" |
| + "amadan.net/oficina/equipo/internal/wire/wireschema" |
| + "encoding/json" |
| + "os" |
| + "reflect" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestNotificationLegacyCardAndContract(t *testing.T) { |
| + f := newFixture(t) |
| + proposed(t, f) |
| + list := apiRequest(t, f, owner, "GET", "/api/v1/conversation/cards", "", "", "") |
| + expectHTTP(t, list, 200) |
| + page := apiValue[personapi.Page[personapi.Card]](t, list) |
| + if len(page.Items) == 0 { |
| + t.Fatal("missing legacy fixture") |
| + } |
| + c := page.Items[0] |
| + if strings.HasPrefix(c.ID, "c_") { |
| + t.Fatal("legacy id collides with reserved thin prefix", c.ID) |
| + } |
| + response := apiRequest(t, f, owner, "GET", "/api/v1/cards/"+c.ID, "", "", "") |
| + expectHTTP(t, response, 200) |
| + got := apiValue[personapi.Card](t, response) |
| + if !reflect.DeepEqual(c, got) { |
| + t.Fatal("legacy projection changed", c, got) |
| + } |
| + raw, err := os.ReadFile("../../docs/api/equipo-v1.openapi.json") |
| + must(t, err) |
| + var doc map[string]any |
| + must(t, json.Unmarshal(raw, &doc)) |
| + schema := doc["paths"].(map[string]any)["/cards/{id}"].(map[string]any)["get"].(map[string]any)["responses"].(map[string]any)["200"].(map[string]any)["content"].(map[string]any)["application/json"].(map[string]any)["schema"].(map[string]any) |
| + schemas := doc["components"].(map[string]any)["schemas"].(map[string]any) |
| + must(t, wireschema.Validate(schemas, deviceJSON(t, got), schema, "legacy")) |
| + raw, err = os.ReadFile("../../native/apple/Tests/EquipoKitTests/Fixtures/thin/snapshot.json") |
| + must(t, err) |
| + var snapshot map[string]any |
| + must(t, json.Unmarshal(raw, &snapshot)) |
| + for _, card := range snapshot["cards"].([]any) { |
| + must(t, wireschema.Validate(schemas, card, schema, "thin")) |
| + } |
| +} |
diff --git a/internal/plan3test/person_api_device_contract_test.go b/internal/plan3test/person_api_device_contract_test.go| index b8bdfc83..8aa27254 100644 |
| --- a/internal/plan3test/person_api_device_contract_test.go |
| +++ b/internal/plan3test/person_api_device_contract_test.go |
| @@ -28,7 +28,7 @@ import ( |
| // Authorization header, by the id's prefix, or not at all (replaced). |
| var deviceShared = map[string]string{ |
| "GET /tasks": "device", "GET /needs-you": "device", "GET /runners": "device", "GET /connections": "device", "GET /specialists": "device", |
| - "GET /tasks/{id}": "tk", "POST /tasks/{id}/cancel": "tk", "GET /questions/{id}": "q_", |
| + "GET /cards/{id}": "c_", "GET /tasks/{id}": "tk", "POST /tasks/{id}/cancel": "tk", "GET /questions/{id}": "q_", |
| "GET /connections/{id}": "cn_", "DELETE /connections/{id}": "cn_", |
| "GET /projects": "replaced", "POST /projects": "replaced", |
| } |
diff --git a/internal/wire/push.go b/internal/wire/push.go| index 4355a835..7b91052a 100644 |
| --- a/internal/wire/push.go |
| +++ b/internal/wire/push.go |
| @@ -28,10 +28,12 @@ const MaxPushToken = 400 |
| // 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"` |
| + ActionsVersion int `json:"actions_version,omitempty"` |
| + BindingID string `json:"binding_id,omitempty"` |
| + 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 |
| @@ -106,11 +108,24 @@ type LiveActivityState struct { |
| // 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). |
| +// PushActions is routing and revision metadata only, never authority or text. |
| +type PushActions struct { |
| + Version int `json:"version"` |
| + BindingID string `json:"binding_id"` |
| + NotificationID string `json:"notification_id"` |
| + CardKind string `json:"card_kind,omitempty"` |
| + CardRevision int64 `json:"card_revision,omitempty"` |
| + TaskRevision int64 `json:"task_revision,omitempty"` |
| + StepID string `json:"step_id,omitempty"` |
| + StepRevision int64 `json:"step_revision,omitempty"` |
| + Attempt int64 `json:"attempt,omitempty"` |
| +} |
| 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"` |
| + Actions *PushActions `json:"actions,omitempty"` |
| + Kind string `json:"kind"` |
| + CardID string `json:"card_id,omitempty"` |
| + TaskID string `json:"task_id,omitempty"` |
| + TurnID string `json:"turn_id,omitempty"` |
| } |
| // PushData kinds. |
diff --git a/internal/wire/wireschema/notification_test.go b/internal/wire/wireschema/notification_test.go| new file mode 100644 |
| index 00000000..2404114e |
| --- /dev/null |
| +++ b/internal/wire/wireschema/notification_test.go |
| @@ -0,0 +1,39 @@ |
| +package wireschema |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "encoding/json" |
| + "testing" |
| +) |
| + |
| +func TestNotificationOperationSchemas(t *testing.T) { |
| + if _, ok := Ops["POST /tasks/{id}/retry"].In.(wire.RetryTask); !ok { |
| + t.Fatal("retry binding is undocumented") |
| + } |
| + var answer map[string]any |
| + if err := json.Unmarshal(Body(Ops["POST /cards/{id}/answer"].Out["409"]), &answer); err != nil { |
| + t.Fatal(err) |
| + } |
| + alternatives, ok := answer["oneOf"].([]any) |
| + if !ok || len(alternatives) != 2 { |
| + t.Fatal("card and idempotency conflicts must both be documented", answer) |
| + } |
| + want := map[string]bool{"#/components/schemas/CardConflict": true, "#/components/schemas/Error": true} |
| + for _, entry := range alternatives { |
| + delete(want, entry.(map[string]any)["$ref"].(string)) |
| + } |
| + if len(want) != 0 { |
| + t.Fatal(want) |
| + } |
| + raw := Generate()["RegisterPush"] |
| + var registration map[string]any |
| + if err := json.Unmarshal(raw, ®istration); err != nil { |
| + t.Fatal(err) |
| + } |
| + properties := registration["properties"].(map[string]any) |
| + for _, key := range []string{"binding_id", "actions_version"} { |
| + if properties[key] == nil { |
| + t.Fatal(key) |
| + } |
| + } |
| +} |
diff --git a/internal/wire/wireschema/wireschema.go b/internal/wire/wireschema/wireschema.go| index f3644000..21e48f1d 100644 |
| --- a/internal/wire/wireschema/wireschema.go |
| +++ b/internal/wire/wireschema/wireschema.go |
| @@ -33,6 +33,16 @@ type Op struct { |
| // Bytes is a body of raw bytes: an upload or a file. |
| type Bytes struct{} |
| +// OneOf documents an operation with distinct response shapes at one status. |
| +type OneOf []any |
| + |
| +// APIError refers to the reviewed Error schema, maintained with the API's |
| +// complete copy-code inventory rather than generated from a single handler. |
| +type APIError struct{} |
| + |
| +// LegacyCard preserves the earlier person API projection on the shared URL. |
| +type LegacyCard struct{} |
| + |
| // accepted is POST /tasks/{id}/move's 202 body, a map in the |
| // handler: written inline. |
| var accepted = struct { |
| @@ -51,6 +61,7 @@ var Ops = map[string]Op{ |
| "GET /turns/{id}": {nil, map[string]any{"200": wire.Turn{}}}, |
| "POST /turns/{id}/cancel": {nil, map[string]any{"202": wire.CancelAccepted{}}}, |
| "POST /turns/{id}/retry": {nil, map[string]any{"202": wire.Turn{}}}, |
| + "GET /cards/{id}": {nil, map[string]any{"200": OneOf{wire.Card{}, LegacyCard{}}}}, |
| "GET /snapshot": {nil, map[string]any{"200": wire.Snapshot{}}}, |
| "PUT /projects/{id}/star": {wire.SetProjectStar{}, map[string]any{"200": wire.Project{}}}, |
| "DELETE /projects/{id}/names": {wire.ForgetProjectName{}, map[string]any{"204": nil}}, |
| @@ -58,14 +69,14 @@ var Ops = map[string]Op{ |
| "GET /projects": {nil, map[string]any{"200": wire.ProjectList{}}}, |
| "POST /projects": {wire.AddProject{}, map[string]any{"200": wire.Project{}, "201": wire.Project{}}}, |
| "DELETE /projects/{id}": {nil, map[string]any{"200": wire.Project{}}}, |
| - "POST /cards/{id}/answer": {wire.AnswerCard{}, map[string]any{"200": wire.Answered{}, "409": wire.CardConflict{}}}, |
| + "POST /cards/{id}/answer": {wire.AnswerCard{}, map[string]any{"200": wire.Answered{}, "409": OneOf{wire.CardConflict{}, APIError{}}}}, |
| "GET /notebook": {nil, map[string]any{"200": wire.Notebook{}}}, |
| "POST /notebook/reset": {nil, map[string]any{"202": wire.Coordinator{}}}, |
| "DELETE /notebook/corrections/{id}": {nil, map[string]any{"204": nil}}, |
| "GET /tasks": {nil, map[string]any{"200": wire.TaskList{}}}, |
| "GET /tasks/{id}": {nil, map[string]any{"200": wire.Task{}}}, |
| "POST /tasks/{id}/cancel": {nil, map[string]any{"202": wire.TaskAccepted{}}}, |
| - "POST /tasks/{id}/retry": {nil, map[string]any{"202": wire.TaskAccepted{}}}, |
| + "POST /tasks/{id}/retry": {wire.RetryTask{}, map[string]any{"202": wire.TaskAccepted{}}}, |
| "POST /tasks/{id}/move": {wire.MoveTask{}, map[string]any{"202": accepted}}, |
| "PUT /tasks/{id}/priority": {wire.SetPriority{}, map[string]any{"200": wire.Task{}}}, |
| "POST /tasks/{id}/run-now": {wire.RunNow{}, map[string]any{"202": wire.RunNowAccepted{}}}, |
| @@ -345,7 +356,22 @@ func nullable(s *ordered) *ordered { |
| return obj("anyOf", []any{s, obj("type", "null")}) |
| } |
| -func (g *gen) ref(v any) *ordered { return g.of(reflect.TypeOf(v)) } |
| +func (g *gen) ref(v any) *ordered { |
| + if _, ok := v.(LegacyCard); ok { |
| + return obj("$ref", "#/components/schemas/PersonAPICard") |
| + } |
| + if _, ok := v.(APIError); ok { |
| + return obj("$ref", "#/components/schemas/Error") |
| + } |
| + if values, ok := v.(OneOf); ok { |
| + variants := make([]*ordered, 0, len(values)) |
| + for _, value := range values { |
| + variants = append(variants, g.ref(value)) |
| + } |
| + return obj("oneOf", variants) |
| + } |
| + return g.of(reflect.TypeOf(v)) |
| +} |
| func (g *gen) of(t reflect.Type) *ordered { |
| if why := unsupported(t); why != "" { |
diff --git a/internal/wire/wireschema/wireschema_test.go b/internal/wire/wireschema/wireschema_test.go| index 232839b5..21e8c9ed 100644 |
| --- a/internal/wire/wireschema/wireschema_test.go |
| +++ b/internal/wire/wireschema/wireschema_test.go |
| @@ -577,6 +577,16 @@ func TestOpsAreWhatTheHandlersWrite(t *testing.T) { |
| want := map[string]string{} |
| for status, v := range op.Out { |
| want[status] = opName(v) |
| + // A handler's primary body must be one of its documented |
| + // variants. Compatibility routes and fail() supply the others. |
| + if variants, ok := v.(OneOf); ok { |
| + for _, variant := range variants { |
| + if opName(variant) == got[status] { |
| + want[status] = got[status] |
| + break |
| + } |
| + } |
| + } |
| } |
| if !reflect.DeepEqual(got, want) { |
| t.Errorf("%s (%s) writes %v; Ops says %v", key, name, got, want) |
diff --git a/native/apple/Sources/EquipoKit/API/Push.swift b/native/apple/Sources/EquipoKit/API/Push.swift| index 955d1b03..ded2992a 100644 |
| --- a/native/apple/Sources/EquipoKit/API/Push.swift |
| +++ b/native/apple/Sources/EquipoKit/API/Push.swift |
| @@ -27,6 +27,8 @@ public struct PushRegistrationBody: Codable, Sendable, Equatable { |
| public var environment: APNsEnvironment |
| public var platform: PushPlatform |
| public var startToken: String? |
| + public var actionsVersion: Int? |
| + public var bindingId: String? |
| public init(token: String, environment: APNsEnvironment, platform: PushPlatform, startToken: String? = nil) { |
| self.token = token; self.environment = environment; self.platform = platform |
| // Only an iPhone has a push-to-start token; the server refuses one from a Mac. |
| @@ -81,3 +83,17 @@ extension EquipoClient { |
| id.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed.subtracting(CharacterSet(charactersIn: "/"))) ?? id |
| } |
| } |
| + |
| +struct NotificationCapabilities: Decodable { let notificationActionsV1: Bool? } |
| +extension EquipoClient { |
| + func notificationCard(_ id: String) async throws -> ThinCard { |
| + try await get("/cards/\(escape(id))") |
| + } |
| + func notificationActionsEnabled() async throws -> Bool { |
| + let value: NotificationCapabilities = try await get("/capabilities") |
| + return value.notificationActionsV1 == true |
| + } |
| + func retryNotification(task: String, write: PendingWrite) async throws { |
| + let _: TaskAccepted = try await post("/tasks/\(escape(task))/retry", write) |
| + } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/Pairing/DeviceAccount.swift b/native/apple/Sources/EquipoKit/Pairing/DeviceAccount.swift| index 044d2ec5..7f2ccc98 100644 |
| --- a/native/apple/Sources/EquipoKit/Pairing/DeviceAccount.swift |
| +++ b/native/apple/Sources/EquipoKit/Pairing/DeviceAccount.swift |
| @@ -40,10 +40,16 @@ public struct DeviceAccounts: Sendable { |
| case save(DeviceAccount) |
| case remove(DeviceAccount) |
| case route(String) |
| + case selectForNotifications(DeviceAccount) |
| + case clearNotificationSelection(DeviceAccount) |
| case selectForSharing(DeviceAccount) |
| case clearShareSelection(DeviceAccount) |
| } |
| + public var notificationSelection: NotificationSelection? { |
| + store.read(NotificationSelection.key).flatMap { try? JSONDecoder().decode(NotificationSelection.self, from: $0) } |
| + } |
| + |
| public func all() -> [DeviceAccount] { |
| let origins = (store.read(Self.index).flatMap { try? JSONDecoder().decode([URL].self, from: $0) }) ?? [] |
| return origins.compactMap { origin in store.read(origin.absoluteString).flatMap { try? JSONDecoder().decode(DeviceAccount.self, from: $0) } } |
| @@ -62,9 +68,20 @@ public struct DeviceAccounts: Sendable { |
| case .remove(let account): |
| guard all().contains(where: { $0.origin == account.origin && $0.keySeed == account.keySeed }) else { return } |
| if let data = store.read(ShareSelection.key), let selection = try? JSONDecoder().decode(ShareSelection.self, from: data), selection.origin == account.origin { store.remove(ShareSelection.key) } |
| + if notificationSelection?.origin == account.origin { store.remove(NotificationSelection.key) } |
| store.remove(account.origin.absoluteString) |
| let origins = all().map(\.origin).filter { $0 != account.origin } |
| try store.write(try JSONEncoder().encode(origins), account: Self.index) |
| + case .selectForNotifications(let account): |
| + guard account.isUsable(), let person = account.address, !person.isEmpty, let credential = account.credential?.id else { |
| + store.remove(NotificationSelection.key); return |
| + } |
| + if notificationSelection?.matches(account) == true { return } |
| + let selection = NotificationSelection(id: UUID().uuidString.lowercased(), origin: account.origin, person: person, |
| + credential: credential, sessionHash: account.oficinaSessionHash) |
| + try store.write(try JSONEncoder().encode(selection), account: NotificationSelection.key) |
| + case .clearNotificationSelection(let account): |
| + if notificationSelection?.matches(account) == true { store.remove(NotificationSelection.key) } |
| case .selectForSharing(let account): |
| guard account.isUsable(), let person = account.address, !person.isEmpty else { store.remove(ShareSelection.key); return } |
| let old = store.read(ShareSelection.key).flatMap { try? JSONDecoder().decode(ShareSelection.self, from: $0) } |
diff --git a/native/apple/Sources/EquipoKit/Push/NotificationDispatcher.swift b/native/apple/Sources/EquipoKit/Push/NotificationDispatcher.swift| new file mode 100644 |
| index 00000000..dbd86430 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/Push/NotificationDispatcher.swift |
| @@ -0,0 +1,174 @@ |
| +import Foundation |
| +import Observation |
| +import EquipoShareCore |
| + |
| +@MainActor @Observable final class NotificationNotice: Identifiable { |
| + let response: NotificationResponse |
| + nonisolated let id: String |
| + var error: String? |
| + var canRetry = false |
| + var busy = false |
| + var card: ThinCard? |
| + var context: MacTaskContext? |
| + var choice = "" |
| + init(_ response: NotificationResponse) { self.response = response; id = response.binding.notificationId } |
| +} |
| + |
| +/// Foreground responses only. A saved request is retried only on a response |
| +/// delivery or the person's Retry tap, never by refresh or a background timer. |
| +@MainActor @Observable final class NotificationDispatcher { |
| + private let journal: ActionJournal |
| + private var session: EquipoSession? |
| + private var selection: NotificationSelection? |
| + private var queued: [NotificationResponse] = [] |
| + private var inFlight: Set<String> = [] |
| + var notices: [NotificationNotice] = [] |
| + var onRoute: ((PushRoute) -> Void)? |
| + private struct Stored: Codable { let response: NotificationResponse; let write: PendingWrite } |
| + init(journal: ActionJournal) { self.journal = journal } |
| + static func live() -> NotificationDispatcher { |
| + let folder = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] |
| + .appendingPathComponent("Equipo/NotificationActions", isDirectory: true) |
| + .appendingPathComponent(Bundle.main.bundleIdentifier ?? "unbundled", isDirectory: true) |
| + return NotificationDispatcher(journal: ActionJournal(directory: folder)) |
| + } |
| + func attach(session: EquipoSession, selection: NotificationSelection?) { |
| + let restoring = self.session !== session || self.selection != selection |
| + if let old = self.selection, old != selection { clear() } |
| + self.session = session; self.selection = selection |
| + if restoring, let selection, current(session, selection), let records = try? journal.pending(binding: selection.id) { |
| + for data in records { |
| + guard let stored = try? JSONDecoder().decode(Stored.self, from: data), stored.response.binding.bindingId == selection.id, |
| + !notices.contains(where: { $0.id == stored.response.binding.notificationId }) else { continue } |
| + let notice = NotificationNotice(stored.response) |
| + notice.canRetry = true; notice.error = EquipoStrings.text("native.share.unconfirmed") |
| + notices.append(notice) |
| + } |
| + } |
| + let pending = queued; queued = [] |
| + for response in pending { Task { await receive(response) } } |
| + } |
| + func clear() { |
| + session = nil; selection = nil; queued = []; notices = []; inFlight = [] |
| + journal.clear() |
| + } |
| + private func current(_ session: EquipoSession, _ selection: NotificationSelection) -> Bool { |
| + self.session === session && self.selection == selection && session.lifetime.isActive && !session.isInvalidated && selection.matches(session.account) |
| + } |
| + func dismiss(_ id: String) { notices.removeAll { $0.id == id } } |
| + func receive(_ response: NotificationResponse) async { |
| + guard let session, selection != nil else { |
| + if queued.count < 32, !queued.contains(response) { queued.append(response) } |
| + return |
| + } |
| + guard let selection, current(session, selection), response.binding.bindingId == selection.id else { return } |
| + if response.intent == .open { onRoute?(response.taskID.map(PushRoute.task) ?? response.route); return } |
| + guard !inFlight.contains(response.binding.notificationId) else { return } |
| + let notice: NotificationNotice |
| + if let existing = notices.first(where: { $0.id == response.binding.notificationId }) { |
| + guard existing.response == response else { existing.error = EquipoStrings.text("api.idempotency_conflict"); return } |
| + notice = existing |
| + } else { notice = NotificationNotice(response); notices.append(notice) } |
| + await run(notice, session: session, selection: selection) |
| + } |
| + func retry(_ notice: NotificationNotice) async { |
| + guard notice.canRetry, let session, let selection, current(session, selection) else { return } |
| + await run(notice, session: session, selection: selection) |
| + } |
| + func answer(_ notice: NotificationNotice, choice: String) async { |
| + guard !notice.busy, let card = notice.card, let session, let selection, current(session, selection), |
| + card.revision == notice.response.binding.cardRevision, card.isOpen, card.kind == "question", |
| + (card.options?.isEmpty != false ? !choice.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty : card.options!.contains(choice)), |
| + choice.utf8.count <= 16 * 1024 else { return } |
| + notice.choice = choice |
| + await run(notice, session: session, selection: selection, selectedChoice: choice) |
| + } |
| + private func run(_ notice: NotificationNotice, session: EquipoSession, selection: NotificationSelection, selectedChoice: String? = nil) async { |
| + let response = notice.response, id = notice.id |
| + guard !inFlight.contains(id), current(session, selection) else { return } |
| + inFlight.insert(id); notice.busy = true; notice.error = nil |
| + defer { inFlight.remove(id); notice.busy = false } |
| + do { |
| + guard try await session.client.notificationActionsEnabled() else { onRoute?(response.route); dismiss(id); return } |
| + guard current(session, selection) else { return } |
| + let saved = try journal.load(id: id, binding: selection.id) |
| + let stored: Stored? |
| + if let saved { |
| + let value = try JSONDecoder().decode(Stored.self, from: saved) |
| + guard value.response == response else { notice.error = EquipoStrings.text("api.idempotency_conflict"); return } |
| + stored = value |
| + } else { stored = nil } |
| + let write: PendingWrite |
| + if let stored { write = stored.write } |
| + else { |
| + if response.intent == .retry { write = try response.pendingWrite() } |
| + else { |
| + if response.intent == .merge { |
| + let snapshot = try await session.client.snapshot() |
| + guard current(session, selection) else { return } |
| + session.apply(snapshot) |
| + } |
| + guard let cardID = response.cardID else { throw EquipoAPIError.undecodable } |
| + let card = try await session.client.notificationCard(cardID) |
| + guard current(session, selection) else { return } |
| + session.applyCard(card) |
| + guard card.revision == response.binding.cardRevision, card.isOpen else { |
| + throw EquipoAPIError.server(status: 409, body: APIErrorBody(code: "card_stale", copyKey: "", requestId: "", currentRevision: nil)) |
| + } |
| + if response.intent == .merge { |
| + guard card.kind == "merge", card.taskId == response.taskID, let task = response.taskID else { throw EquipoAPIError.undecodable } |
| + let context = MacTaskContext(session: session, taskID: task) |
| + await context.load() |
| + guard current(session, selection) else { return } |
| + if let error = context.detail.readFailure { notice.error = error; return } |
| + guard context.detail.decision.card?.id == card.id, context.detail.decision.card?.revision == card.revision, |
| + context.detail.decision.canAnswer("merge", note: "") else { throw EquipoAPIError.status(409) } |
| + notice.context = context |
| + await context.detail.answer(card, choice: "merge", note: "") |
| + return |
| + } |
| + guard card.kind == "question" else { throw EquipoAPIError.status(409) } |
| + if response.intent == .question, selectedChoice == nil { notice.card = card; return } |
| + let choice: String |
| + if case .answer(let text) = response.intent { |
| + guard card.options?.isEmpty != false else { throw EquipoAPIError.status(409) } |
| + choice = text |
| + } else if let selectedChoice, |
| + card.options?.isEmpty != false || card.options?.contains(selectedChoice) == true { choice = selectedChoice } |
| + else { throw EquipoAPIError.undecodable } |
| + let body: [String: AnyEncodable] = ["choice": .init(choice), "revision": .init(card.revision), "idempotency_key": .init(id)] |
| + write = PendingWrite(body: try EquipoJSON.encoder.encode(body), ifMatch: card.revision, key: id) |
| + } |
| + try journal.save(id: id, binding: selection.id, body: JSONEncoder().encode(Stored(response: response, write: write))) |
| + } |
| + guard current(session, selection) else { return } |
| + if response.intent == .retry, let task = response.taskID { try await session.client.retryNotification(task: task, write: write) } |
| + else if let card = response.cardID { let _: Answered = try await session.client.answer(card: card, write) } |
| + else { throw EquipoAPIError.undecodable } |
| + guard current(session, selection) else { return } |
| + try journal.remove(id: id, binding: selection.id) |
| + onRoute?(response.route); dismiss(id) |
| + await session.refresh() |
| + } catch { |
| + guard current(session, selection) else { return } |
| + notice.error = TaskActionFailure.words(error) |
| + let api = error as? EquipoAPIError |
| + if api?.endsSession == true { session.invalidate(); clear(); return } |
| + let definite = api?.status.map { (400..<500).contains($0) && ![401, 403, 408, 425, 429].contains($0) } == true && !(api?.code?.isEmpty ?? true) |
| + notice.canRetry = !definite |
| + if definite { try? journal.remove(id: id, binding: selection.id); notice.card = nil } |
| + if api?.status == 409 { |
| + notice.canRetry = false; notice.card = nil; notice.context = nil |
| + // A stale card may be older than the snapshot window. Fetch its |
| + // current projection for navigation without rebinding this write. |
| + if let id = response.cardID, let card = try? await session.client.notificationCard(id) { |
| + guard current(session, selection) else { return } |
| + session.applyCard(card) |
| + } |
| + guard current(session, selection) else { return } |
| + onRoute?(response.route) |
| + await session.refresh() |
| + } |
| + } |
| + } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/Push/NotificationResponse.swift b/native/apple/Sources/EquipoKit/Push/NotificationResponse.swift| new file mode 100644 |
| index 00000000..e011596e |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/Push/NotificationResponse.swift |
| @@ -0,0 +1,96 @@ |
| +import Foundation |
| +import UserNotifications |
| + |
| +/// Routing metadata is never authority. All IDs remain bound to the active |
| +/// registration; revisions are checked again by the server in its transaction. |
| +public struct NotificationBinding: Codable, Equatable, Sendable { |
| + public let version: Int |
| + public let bindingId: String |
| + public let notificationId: String |
| + public let cardKind: String? |
| + public let cardRevision: Int64? |
| + public let taskRevision: Int64? |
| + public let stepId: String? |
| + public let stepRevision: Int64? |
| + public let attempt: Int64? |
| + static func uuid(_ value: String) -> Bool { UUID(uuidString: value)?.uuidString.lowercased() == value } |
| + static func id(_ value: String?) -> Bool { |
| + guard let value, !value.isEmpty, value.utf8.count <= 128 else { return false } |
| + return value.utf8.allSatisfy { (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) || $0 == 45 || $0 == 95 } |
| + } |
| +} |
| + |
| +public struct NotificationResponse: Codable, Equatable, Sendable { |
| + public enum Intent: Codable, Equatable, Sendable { case answer(String), question, retry, merge, open } |
| + public let binding: NotificationBinding |
| + public let cardID: String? |
| + public let taskID: String? |
| + public let intent: Intent |
| + public var route: PushRoute { cardID.map(PushRoute.card) ?? taskID.map(PushRoute.task) ?? .conversation } |
| + public init?(userInfo: [AnyHashable: Any], category: String, action: String, text: String?) { |
| + guard let data = userInfo["equipo"] as? [String: Any], let raw = data["actions"] as? [String: Any], |
| + JSONSerialization.isValidJSONObject(raw), let encoded = try? JSONSerialization.data(withJSONObject: raw), |
| + let binding = try? EquipoJSON.decoder.decode(NotificationBinding.self, from: encoded), |
| + binding.version == 1, NotificationBinding.uuid(binding.bindingId), NotificationBinding.uuid(binding.notificationId) else { return nil } |
| + let card = data["card_id"] as? String, task = data["task_id"] as? String |
| + if let card, !NotificationBinding.id(card) { return nil } |
| + if let task, !NotificationBinding.id(task) { return nil } |
| + let intent: Intent |
| + switch category { |
| + case "equipo.question.text.v1", "equipo.question.choices.v1": |
| + guard data["kind"] as? String == "card", NotificationBinding.id(card), binding.cardKind == "question", (binding.cardRevision ?? 0) > 0 else { return nil } |
| + if action == "open", task != nil { intent = .open } |
| + else if action == "answer", category == "equipo.question.choices.v1" { intent = .question } |
| + else if action == "answer", let text, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, |
| + text.utf8.count <= 16 * 1024, !text.contains("\0") { intent = .answer(text) } |
| + else { return nil } |
| + case "equipo.merge.v1": |
| + guard data["kind"] as? String == "card", NotificationBinding.id(card), NotificationBinding.id(task), |
| + binding.cardKind == "merge", (binding.cardRevision ?? 0) > 0 else { return nil } |
| + if action == "merge" { intent = .merge } |
| + else if action == "open" { intent = .open } |
| + else { return nil } |
| + case "equipo.stopped.v1": |
| + guard data["kind"] as? String == "task", NotificationBinding.id(task), NotificationBinding.id(binding.stepId), |
| + (binding.taskRevision ?? 0) > 0, (binding.stepRevision ?? 0) > 0, (binding.attempt ?? 0) > 0 else { return nil } |
| + if action == "retry" { intent = .retry } |
| + else if action == "open" { intent = .open } |
| + else { return nil } |
| + default: return nil |
| + } |
| + self.binding = binding; cardID = card; taskID = task; self.intent = intent |
| + } |
| + func pendingWrite() throws -> PendingWrite { |
| + let key = binding.notificationId |
| + var body: [String: AnyEncodable] = ["idempotency_key": .init(key)] |
| + let revision: Int64 |
| + switch intent { |
| + case .answer(let text): |
| + guard let value = binding.cardRevision else { throw EquipoAPIError.undecodable } |
| + revision = value; body["choice"] = .init(text) |
| + case .retry: |
| + guard let value = binding.taskRevision, let step = binding.stepId, let stepRevision = binding.stepRevision, let attempt = binding.attempt else { throw EquipoAPIError.undecodable } |
| + revision = value; body["step_id"] = .init(step); body["step_revision"] = .init(stepRevision); body["attempt"] = .init(attempt) |
| + default: throw EquipoAPIError.undecodable |
| + } |
| + body["revision"] = .init(revision) |
| + return PendingWrite(body: try EquipoJSON.encoder.encode(body), ifMatch: revision, key: key) |
| + } |
| +} |
| + |
| +@MainActor enum NotificationCategories { |
| + static var all: Set<UNNotificationCategory> { |
| + let flags: UNNotificationActionOptions = [.authenticationRequired, .foreground] |
| + func action(_ id: String, _ key: String.LocalizationValue) -> UNNotificationAction { UNNotificationAction(identifier: id, title: EquipoStrings.text(key), options: flags) } |
| + let open = action("open", "task.open") |
| + let text = UNTextInputNotificationAction(identifier: "answer", title: EquipoStrings.text("chat.card.answer"), options: flags, |
| + textInputButtonTitle: EquipoStrings.text("composer.send"), textInputPlaceholder: EquipoStrings.text("conversation.placeholder")) |
| + return [ |
| + UNNotificationCategory(identifier: "needs_you", actions: [], intentIdentifiers: []), |
| + UNNotificationCategory(identifier: "equipo.question.text.v1", actions: [text, open], intentIdentifiers: []), |
| + UNNotificationCategory(identifier: "equipo.question.choices.v1", actions: [action("answer", "chat.card.answer")], intentIdentifiers: []), |
| + UNNotificationCategory(identifier: "equipo.merge.v1", actions: [action("merge", "chat.card.merge"), open], intentIdentifiers: []), |
| + UNNotificationCategory(identifier: "equipo.stopped.v1", actions: [action("retry", "work.pause.try_again"), open], intentIdentifiers: []) |
| + ] |
| + } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/Push/NotificationSelection.swift b/native/apple/Sources/EquipoKit/Push/NotificationSelection.swift| new file mode 100644 |
| index 00000000..c90b9233 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/Push/NotificationSelection.swift |
| @@ -0,0 +1,15 @@ |
| +import Foundation |
| + |
| +/// Saved only in the Keychain. The random ID is public routing data, while |
| +/// credential identity and the Oficina session hash bind it to one sign-in. |
| +public struct NotificationSelection: Codable, Equatable, Sendable { |
| + static let key = "notification.selection" |
| + public let id: String |
| + public let origin: URL |
| + public let person: String |
| + let credential: String |
| + let sessionHash: String? |
| + func matches(_ account: DeviceAccount) -> Bool { |
| + origin == account.origin && person == account.address && credential == account.credential?.id && sessionHash == account.oficinaSessionHash |
| + } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/Push/Notifications.swift b/native/apple/Sources/EquipoKit/Push/Notifications.swift| index 23b802bb..cae83523 100644 |
| --- a/native/apple/Sources/EquipoKit/Push/Notifications.swift |
| +++ b/native/apple/Sources/EquipoKit/Push/Notifications.swift |
| @@ -51,13 +51,13 @@ public final class RemoteRegistration { |
| } |
| } |
| -/// UNUserNotificationCenter and APNs registration, for both apps. Alerts |
| -/// that wait on you have the category `needs_you`, with no actions: a |
| -/// notification opens the app, and you answer there (D4). |
| +/// UserNotifications registration and foreground, unlock-required responses. |
| +/// Old and unknown payloads retain open-only navigation. |
| @MainActor |
| public final class SystemNotifications: NSObject, NotificationSystem, UNUserNotificationCenterDelegate { |
| public static let needsYouCategory = "needs_you" |
| /// Called with where a tapped notification goes. |
| + public var onResponse: ((NotificationResponse) -> Void)? |
| public var onRoute: ((PushRoute) -> Void)? |
| private let remote = RemoteRegistration( |
| authorize: { _ = try? await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) }, |
| @@ -83,7 +83,7 @@ public final class SystemNotifications: NSObject, NotificationSystem, UNUserNoti |
| super.init() |
| let center = UNUserNotificationCenter.current() |
| center.delegate = self |
| - center.setNotificationCategories([UNNotificationCategory(identifier: Self.needsYouCategory, actions: [], intentIdentifiers: [])]) |
| + center.setNotificationCategories(NotificationCategories.all) |
| } |
| public func askAndRegister() { |
| @@ -104,8 +104,13 @@ public final class SystemNotifications: NSObject, NotificationSystem, UNUserNoti |
| } |
| public nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async { |
| - guard response.actionIdentifier == UNNotificationDefaultActionIdentifier, |
| - let route = PushRoute(userInfo: response.notification.request.content.userInfo) else { return } |
| - await MainActor.run { self.onRoute?(route) } |
| + guard response.actionIdentifier != UNNotificationDismissActionIdentifier else { return } |
| + let content = response.notification.request.content |
| + if let action = NotificationResponse(userInfo: content.userInfo, category: content.categoryIdentifier, |
| + action: response.actionIdentifier, text: (response as? UNTextInputNotificationResponse)?.userText) { |
| + await MainActor.run { self.onResponse?(action) } |
| + } else if let route = PushRoute(userInfo: content.userInfo) { |
| + await MainActor.run { self.onRoute?(route) } |
| + } |
| } |
| } |
diff --git a/native/apple/Sources/EquipoKit/Push/PhoneDelegate.swift b/native/apple/Sources/EquipoKit/Push/PhoneDelegate.swift| index cf948ec3..b0efcec5 100644 |
| --- a/native/apple/Sources/EquipoKit/Push/PhoneDelegate.swift |
| +++ b/native/apple/Sources/EquipoKit/Push/PhoneDelegate.swift |
| @@ -12,8 +12,9 @@ public final class EquipoPhoneDelegate: NSObject, UIApplicationDelegate { |
| public func application(_ application: UIApplication, didFinishLaunchingWithOptions options: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { |
| #if DEBUG && targetEnvironment(simulator) |
| - if ProcessInfo.processInfo.environment["EQUIPO_SHARE_FIXTURE"] != nil || ProcessInfo.processInfo.environment["EQUIPO_SCREENSHOT_FIXTURE"] != nil { return true } |
| + if ProcessInfo.processInfo.environment["EQUIPO_NOTIFICATION_FIXTURE"] != nil || ProcessInfo.processInfo.environment["EQUIPO_SHARE_FIXTURE"] != nil || ProcessInfo.processInfo.environment["EQUIPO_SCREENSHOT_FIXTURE"] != nil { return true } |
| #endif |
| + notifications.onResponse = { [weak self] response in self?.model.notificationResponse(response) } |
| notifications.onRoute = { [weak self] route in self?.model.open(route) } |
| model.liveActivities.start() |
| // A push can launch the app without creating a view. Validate the |
diff --git a/native/apple/Sources/EquipoKit/Push/PushRegistrar.swift b/native/apple/Sources/EquipoKit/Push/PushRegistrar.swift| index c9754d3a..12c363f0 100644 |
| --- a/native/apple/Sources/EquipoKit/Push/PushRegistrar.swift |
| +++ b/native/apple/Sources/EquipoKit/Push/PushRegistrar.swift |
| @@ -13,6 +13,9 @@ public final class PushRegistrar { |
| public private(set) var deviceToken: String? |
| public private(set) var startToken: String? |
| + private var bindingID: String? |
| + private var actionsEnabled = false |
| + private var capabilityRead = false |
| private var client: EquipoClient? |
| private var lifetime: SignInLifetime? |
| /// The registration the current session's server has, by bearer. |
| @@ -44,9 +47,10 @@ public final class PushRegistrar { |
| /// The paired session's client, or nil once there is none. A new one |
| /// is a new credential: everything is registered with it again. |
| - public func attach(_ client: EquipoClient?, lifetime: SignInLifetime? = nil) async { |
| + public func attach(_ client: EquipoClient?, lifetime: SignInLifetime? = nil, bindingID: String? = nil) async { |
| guard lifetime?.isActive != false else { return } |
| - if client?.token != self.client?.token || lifetime !== self.lifetime { |
| + if client?.token != self.client?.token || lifetime !== self.lifetime || bindingID != self.bindingID { |
| + actionsEnabled = false; capabilityRead = false |
| generation += 1 |
| // Another session (another team, a new credential, or none): it |
| // keeps only the activities its own instance started. At launch |
| @@ -62,6 +66,7 @@ public final class PushRegistrar { |
| } |
| self.client = client |
| self.lifetime = lifetime |
| + self.bindingID = bindingID |
| await sync() |
| } |
| @@ -98,7 +103,9 @@ public final class PushRegistrar { |
| /// when this build cannot receive pushes at all. |
| public var body: PushRegistrationBody? { |
| guard let deviceToken, let environment else { return nil } |
| - return PushRegistrationBody(token: deviceToken, environment: environment, platform: platform, startToken: startToken) |
| + var result = PushRegistrationBody(token: deviceToken, environment: environment, platform: platform, startToken: startToken) |
| + if actionsEnabled, let bindingID { result.actionsVersion = 1; result.bindingId = bindingID } |
| + return result |
| } |
| /// Sends whatever the server does not have yet. One pass at a time; a |
| @@ -117,6 +124,11 @@ public final class PushRegistrar { |
| let lifetime = self.lifetime |
| guard lifetime?.isActive != false, let client, let bearer = client.token else { return } |
| let generation = self.generation |
| + if !capabilityRead, let bindingID, NotificationBinding.uuid(bindingID) { |
| + let enabled = (try? await client.notificationActionsEnabled()) == true |
| + guard lifetime?.isActive != false, generation == self.generation else { return } |
| + actionsEnabled = enabled; capabilityRead = true |
| + } |
| if let body, !(accepted?.bearer == bearer && accepted?.body == body), !(refused?.bearer == bearer && refused?.body == body) { |
| do { |
| let write = try PendingWrite.json(body) |
diff --git a/native/apple/Sources/EquipoKit/Push/PushRoute.swift b/native/apple/Sources/EquipoKit/Push/PushRoute.swift| index 910fe0fb..0d5401d8 100644 |
| --- a/native/apple/Sources/EquipoKit/Push/PushRoute.swift |
| +++ b/native/apple/Sources/EquipoKit/Push/PushRoute.swift |
| @@ -1,7 +1,6 @@ |
| import Foundation |
| -/// Where a tapped notification or Live Activity takes the person (D4: a |
| -/// notification only opens the app; nothing is answered from it). Read from |
| +/// Open-only routing for default taps, old payloads and Live Activities. Read from |
| /// the alert's `equipo` object (wire.PushData) or the app's own link. |
| public enum PushRoute: Equatable, Sendable { |
| /// A card waits on you: the conversation, at that card. |
diff --git a/native/apple/Sources/EquipoKit/Session/EquipoSession.swift b/native/apple/Sources/EquipoKit/Session/EquipoSession.swift| index 6f72f519..a6b1a793 100644 |
| --- a/native/apple/Sources/EquipoKit/Session/EquipoSession.swift |
| +++ b/native/apple/Sources/EquipoKit/Session/EquipoSession.swift |
| @@ -100,6 +100,7 @@ public final class EquipoSession { |
| projectCatalog = ProjectCatalog(client: client, lifetime: lifetime) |
| if !account.isUsable() { status = .signedOut } |
| try? accounts.commit(.selectForSharing(account), lifetime: lifetime) |
| + try? accounts.commit(.selectForNotifications(account), lifetime: lifetime) |
| } |
| public var origin: URL { account.origin } |
| @@ -177,6 +178,11 @@ public final class EquipoSession { |
| } |
| } |
| + func applyCard(_ card: ThinCard) { |
| + guard !isInvalidated else { return } |
| + cards = Self.merge(cards, [card]) |
| + } |
| + |
| func apply(_ snapshot: Snapshot, projectGeneration: Int? = nil) { |
| guard !isInvalidated else { return } |
| me = snapshot.me |
| @@ -201,6 +207,7 @@ public final class EquipoSession { |
| account.teamName = snapshot.me.teamName; account.address = snapshot.me.address |
| try? accounts.commit(.save(account), lifetime: lifetime) |
| try? accounts.commit(.selectForSharing(account), lifetime: lifetime) |
| + try? accounts.commit(.selectForNotifications(account), lifetime: lifetime) |
| } |
| } |
| @@ -510,6 +517,7 @@ public final class EquipoSession { |
| guard !isInvalidated else { return } |
| self.account = account |
| try? accounts.commit(.selectForSharing(account), lifetime: lifetime) |
| + try? accounts.commit(.selectForNotifications(account), lifetime: lifetime) |
| revocationTransport = transport |
| client = EquipoClient(transport: LifetimeTransport(inner: transport, lifetime: lifetime), token: account.credential?.token) |
| projectCatalog.client = client |
| @@ -528,6 +536,7 @@ public final class EquipoSession { |
| /// not prevent a completed network response from reaching persistence. |
| func invalidate() { |
| try? accounts.commit(.clearShareSelection(account), lifetime: lifetime) |
| + try? accounts.commit(.clearNotificationSelection(account), lifetime: lifetime) |
| lifetime.end() |
| previews.invalidate() |
| attachments.clear() |
diff --git a/native/apple/Sources/EquipoKit/UI/NotificationActionPresenter.swift b/native/apple/Sources/EquipoKit/UI/NotificationActionPresenter.swift| new file mode 100644 |
| index 00000000..858acb5a |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/UI/NotificationActionPresenter.swift |
| @@ -0,0 +1,62 @@ |
| +import SwiftUI |
| + |
| +/// A foreground response keeps its feedback above pane and inspector changes. |
| +public struct NotificationActionPresenter: ViewModifier { |
| + let model: EquipoAppModel |
| + public init(model: EquipoAppModel) { self.model = model } |
| + public func body(content: Content) -> some View { |
| + content.sheet(isPresented: Binding(get: { !model.notificationActions.notices.isEmpty }, set: { showing in |
| + if !showing { model.notificationActions.notices = [] } |
| + })) { |
| + if let notice = model.notificationActions.notices.first { |
| + NotificationActionView(dispatcher: model.notificationActions, notice: notice) |
| + .id(notice.id) |
| + } |
| + } |
| + } |
| +} |
| + |
| +struct NotificationActionView: View { |
| + let dispatcher: NotificationDispatcher |
| + @Bindable var notice: NotificationNotice |
| + @State private var choice = "" |
| + var body: some View { |
| + NavigationStack { |
| + Group { |
| + if let context = notice.context { TaskScreen(context: context).modifier(SettingsSheetPresenter(session: context.detail.session)) } |
| + else { |
| + ScrollView { |
| + VStack(alignment: .leading, spacing: 16) { |
| + if let card = notice.card { |
| + Text(verbatim: card.question).font(.headline).textSelection(.enabled) |
| + if let options = card.options, !options.isEmpty { |
| + ForEach(options, id: \.self) { option in |
| + Button { Task { await dispatcher.answer(notice, choice: option) } } label: { Text(verbatim: option) } |
| + .buttonStyle(.bordered).disabled(notice.busy || notice.canRetry) |
| + } |
| + } else { |
| + TextField(EquipoStrings.text("chat.card.answer"), text: $choice, axis: .vertical) |
| + .textFieldStyle(.roundedBorder).disabled(notice.busy || notice.canRetry) |
| + Button(EquipoStrings.text("chat.card.answer")) { Task { await dispatcher.answer(notice, choice: choice) } } |
| + .disabled(notice.busy || notice.canRetry || choice.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) |
| + } |
| + } |
| + if notice.card == nil, case .answer(let text) = notice.response.intent { |
| + Text(verbatim: text).lineLimit(3).textSelection(.enabled) |
| + } |
| + if notice.busy { ProgressView().accessibilityLabel(EquipoStrings.text("work.details.task")) } |
| + if let error = notice.error { Text(error).foregroundStyle(Palette.negative) } |
| + if notice.canRetry { |
| + Button(EquipoStrings.text("work.pause.try_again")) { Task { await dispatcher.retry(notice) } }.disabled(notice.busy) |
| + } |
| + }.padding(20).frame(maxWidth: .infinity, alignment: .leading) |
| + } |
| + } |
| + } |
| + .toolbar { ToolbarItem(placement: .cancellationAction) { |
| + Button(EquipoStrings.text("chat.connections.dismiss")) { dispatcher.dismiss(notice.id) } |
| + } } |
| + } |
| + .frame(minWidth: 300, minHeight: 300) |
| + } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/UI/NotificationFixture.swift b/native/apple/Sources/EquipoKit/UI/NotificationFixture.swift| new file mode 100644 |
| index 00000000..52581a98 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/UI/NotificationFixture.swift |
| @@ -0,0 +1,101 @@ |
| +#if DEBUG |
| +import SwiftUI |
| +import Observation |
| +import EquipoShareCore |
| +#if os(macOS) |
| +import AppKit |
| +#endif |
| + |
| +/// Offline review fixture for the real foreground response and confirmation. |
| +/// It does not register with APNs or contact a live account. |
| +public struct NotificationFixture: View { |
| + @State private var model = FixtureModel() |
| + public init() {} |
| + public var body: some View { |
| + Group { |
| + if let notice = model.dispatcher.notices.first { |
| + NotificationActionView(dispatcher: model.dispatcher, notice: notice) |
| + } else { ProgressView().accessibilityLabel(EquipoStrings.text("work.details.task")) } |
| + } |
| + .preferredColorScheme(.light) |
| + .task { |
| + await model.open() |
| + #if os(macOS) |
| + if let path = ProcessInfo.processInfo.environment["EQUIPO_FIXTURE_CAPTURE"] { |
| + try? await Task.sleep(for: .seconds(2)) |
| + if let window = NSApp.windows.first(where: { $0.isVisible && $0.isSheet }) ?? NSApp.windows.first(where: { $0.isVisible }), |
| + let view = window.contentView { |
| + view.layoutSubtreeIfNeeded(); window.displayIfNeeded() |
| + if let bitmap = view.bitmapImageRepForCachingDisplay(in: view.bounds) { |
| + view.cacheDisplay(in: view.bounds, to: bitmap) |
| + // AppKit's sheet background is composited by WindowServer |
| + // and absent from an NSView snapshot. Render that backing |
| + // here so the capture is opaque without screen permission. |
| + let capture = NSImage(size: view.bounds.size) |
| + capture.lockFocus() |
| + NSColor.white.setFill(); NSBezierPath(rect: NSRect(origin: .zero, size: view.bounds.size)).fill() |
| + let content = NSImage(size: view.bounds.size); content.addRepresentation(bitmap) |
| + content.draw(in: NSRect(origin: .zero, size: view.bounds.size), from: .zero, operation: .sourceOver, fraction: 1) |
| + capture.unlockFocus() |
| + if let tiff = capture.tiffRepresentation, let opaque = NSBitmapImageRep(data: tiff), |
| + let data = opaque.representation(using: .png, properties: [:]) { _ = FileManager.default.createFile(atPath: path, contents: data) } |
| + } |
| + } |
| + } |
| + #endif |
| + } |
| + .onDisappear { model.dispatcher.clear(); try? FileManager.default.removeItem(at: model.directory) } |
| + } |
| + @MainActor private final class FixtureModel { |
| + let session: EquipoSession |
| + let dispatcher: NotificationDispatcher |
| + let selection: NotificationSelection |
| + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("equipo-notification-fixture-" + UUID().uuidString) |
| + init() { |
| + let transport = NotificationFixtureTransport() |
| + let accounts = DeviceAccounts(store: MemorySecretStore()) |
| + var account = DeviceAccount.new(origin: transport.origin, label: "Fixture") |
| + account.address = "paul@example.com"; account.teamName = "Oficina" |
| + account.credential = DeviceCredential(id: "fixture", token: "fixture", audience: "equipo.person.v1", instanceId: "fixture", expiresAt: .distantFuture) |
| + session = EquipoSession(account: account, accounts: accounts, transport: transport) |
| + selection = accounts.notificationSelection! |
| + dispatcher = NotificationDispatcher(journal: ActionJournal(directory: directory)) |
| + dispatcher.attach(session: session, selection: selection) |
| + } |
| + func open() async { |
| + await session.refresh() |
| + let question = ProcessInfo.processInfo.environment["EQUIPO_NOTIFICATION_FIXTURE"] == "question" |
| + let data: [AnyHashable: Any] = ["equipo": ["kind": "card", "card_id": "card_merge", "task_id": "tk_fixture", "actions": ["version": 1, "binding_id": selection.id, "notification_id": "22222222-2222-4222-8222-222222222222", "card_kind": question ? "question" : "merge", "card_revision": 3]]] |
| + if let response = NotificationResponse(userInfo: data, category: question ? "equipo.question.choices.v1" : "equipo.merge.v1", action: question ? "answer" : "merge", text: nil) { |
| + await dispatcher.receive(response) |
| + } |
| + } |
| + } |
| +} |
| + |
| +private struct NotificationFixtureTransport: EquipoTransport { |
| + let underlying = TaskViewFixtureTransport() |
| + var origin: URL { underlying.origin } |
| + func send(_ request: APIRequest) async throws -> APIResponse { |
| + if request.method == "POST" { throw EquipoAPIError.offline } |
| + if request.path == "/capabilities" { return APIResponse(status: 200, data: Data(#"{"notification_actions_v1":true}"#.utf8)) } |
| + if request.path.hasPrefix("/cards/") { |
| + let snapshot = try await send(APIRequest("GET", "/snapshot")) |
| + let data = try JSONSerialization.jsonObject(with: snapshot.data) as! [String: Any] |
| + let cards = data["cards"] as! [[String: Any]] |
| + return APIResponse(status: 200, data: try JSONSerialization.data(withJSONObject: cards[0])) |
| + } |
| + let response = try await underlying.send(request) |
| + if request.path == "/snapshot", ProcessInfo.processInfo.environment["EQUIPO_NOTIFICATION_FIXTURE"] == "question", |
| + var snapshot = try JSONSerialization.jsonObject(with: response.data) as? [String: Any], |
| + var cards = snapshot["cards"] as? [[String: Any]], !cards.isEmpty { |
| + cards[0]["kind"] = "question"; cards[0]["question"] = "Should the badge clear when you switch teams too?" |
| + cards[0]["options"] = ["Clear it when switching teams", "Keep each team’s count"] |
| + snapshot["cards"] = cards |
| + return APIResponse(status: 200, data: try JSONSerialization.data(withJSONObject: snapshot)) |
| + } |
| + return response |
| + } |
| + func lines(_ request: APIRequest) async throws -> AsyncThrowingStream<String, Error> { AsyncThrowingStream { $0.finish() } } |
| +} |
| +#endif |
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/AppModel.swift b/native/apple/Sources/EquipoKit/UI/Screens/AppModel.swift| index ce1cbcaa..0589ff0a 100644 |
| --- a/native/apple/Sources/EquipoKit/UI/Screens/AppModel.swift |
| +++ b/native/apple/Sources/EquipoKit/UI/Screens/AppModel.swift |
| @@ -22,6 +22,7 @@ public final class EquipoAppModel { |
| /// Where a tapped notification or Live Activity asked to go, until the |
| /// screens have gone there. |
| public var destination: Destination? |
| + let notificationActions = NotificationDispatcher.live() |
| @ObservationIgnored public let push: PushRegistrar |
| @ObservationIgnored let notifications: NotificationSystem? |
| @@ -48,6 +49,7 @@ public final class EquipoAppModel { |
| #if os(iOS) |
| liveActivities = LiveActivities(registrar: push) |
| #endif |
| + notificationActions.onRoute = { [weak self] route in self?.open(route) } |
| oficina.suspended = showingPairing |
| oficina.onAccount = { [weak self] account, transport, lifetime in self?.adopt(account, transport: transport, lifetime: lifetime) } |
| oficina.onLeave = { [weak self] in |
| @@ -125,11 +127,13 @@ public final class EquipoAppModel { |
| if isForeground { session?.startLive() } |
| notifications?.askAndRegister() |
| guard let session else { return } |
| + notificationActions.attach(session: session, selection: accounts.notificationSelection) |
| let client = session.client, lifetime = session.lifetime |
| let push = self.push |
| + let bindingID = accounts.notificationSelection?.id |
| Task { |
| guard lifetime.isActive else { return } |
| - await push.attach(client, lifetime: lifetime) |
| + await push.attach(client, lifetime: lifetime, bindingID: bindingID) |
| } |
| } |
| @@ -166,6 +170,7 @@ public final class EquipoAppModel { |
| /// No team: nothing more is registered, no badge, no task on the Lock Screen. |
| private func forgetPushes() { |
| + notificationActions.clear() |
| let push = self.push |
| Task { [weak self] in |
| guard self?.session == nil else { return } |
| @@ -181,6 +186,16 @@ public final class EquipoAppModel { |
| #endif |
| } |
| + public func notificationResponse(_ response: NotificationResponse) { |
| + Task { await notificationActions.receive(response) } |
| + } |
| + public func notificationBindingChanged() { |
| + guard let session else { return } |
| + notificationActions.attach(session: session, selection: accounts.notificationSelection) |
| + let binding = accounts.notificationSelection?.id |
| + Task { await push.attach(session.client, lifetime: session.lifetime, bindingID: binding) } |
| + } |
| + |
| /// Where a tapped notification or Live Activity goes. |
| public func open(_ route: PushRoute) { destination = route.destination } |
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/PhoneRoot.swift b/native/apple/Sources/EquipoKit/UI/Screens/PhoneRoot.swift| index abb89761..07cdb65e 100644 |
| --- a/native/apple/Sources/EquipoKit/UI/Screens/PhoneRoot.swift |
| +++ b/native/apple/Sources/EquipoKit/UI/Screens/PhoneRoot.swift |
| @@ -33,6 +33,8 @@ public struct PhoneRoot: View { |
| } |
| } |
| .tint(Palette.accent) |
| + .modifier(NotificationActionPresenter(model: model)) |
| + .onChange(of: model.session?.account.address) { model.notificationBindingChanged() } |
| .onChange(of: phase) { _, now in now == .active ? model.foreground() : model.background() } |
| .onChange(of: model.session?.status) { _, status in if status == .signedOut { model.sessionEnded() } } |
| .onChange(of: model.session?.needsYouCount) { _, count in model.needsYouChanged(count) } |
diff --git a/native/apple/Sources/EquipoKit/UI/TaskConfirmationSheet.swift b/native/apple/Sources/EquipoKit/UI/TaskConfirmationSheet.swift| index b8941108..1392fd62 100644 |
| --- a/native/apple/Sources/EquipoKit/UI/TaskConfirmationSheet.swift |
| +++ b/native/apple/Sources/EquipoKit/UI/TaskConfirmationSheet.swift |
| @@ -5,7 +5,7 @@ struct TaskConfirmationSheet: View { |
| @Bindable var model: TaskDetailModel |
| let confirmation: TaskConfirmation |
| var body: some View { |
| - VStack(alignment: .leading, spacing: 18) { |
| + ScrollView { VStack(alignment: .leading, spacing: 18) { |
| // COPY APPROVED: Luna, 2026-11-26 (cancel title and detail). |
| Text(EquipoStrings.text(confirmation.action == .cancel ? "native.task.cancel_confirm" : confirmation.action == .undoMerge ? "native.task.undo_confirm" : "work.decide.adopt_ask")) |
| .font(.title2.bold()) |
| @@ -17,6 +17,7 @@ struct TaskConfirmationSheet: View { |
| } else if let task = model.task { |
| Text(task.title).font(.headline) |
| FactsView(facts: TaskReport(task, needsYou: !task.needsYou.isEmpty).facts.filter { $0.label != EquipoStrings.text("fact.branch") }, wide: false) |
| + TaskReviewSummary(task: task) |
| if task.checks != "passed" { Text(EquipoStrings.text("work.decide.unchecked_ask")).font(.headline) } |
| if !task.branch.isEmpty { detail(EquipoStrings.text("work.details.branch"), task.branch) } |
| if !task.candidateSha.isEmpty { detail(EquipoStrings.text("work.details.commit"), task.candidateSha) } |
| @@ -25,8 +26,8 @@ struct TaskConfirmationSheet: View { |
| Task { await model.confirm() } |
| }.buttonStyle(.borderedProminent).accessibilityIdentifier("task-confirm") |
| Button(EquipoStrings.text("chat.card.not_now"), role: .cancel) { model.confirmation = nil } |
| - }.padding(24).frame(minWidth: 280, maxWidth: 540, alignment: .leading) |
| - .presentationDetents([.medium, .large]) |
| + }.padding(24) }.frame(minWidth: 280, maxWidth: 540, minHeight: 320, idealHeight: 560, alignment: .leading) |
| + .presentationDetents(confirmation.action == .merge ? [.large] : [.medium, .large]) |
| } |
| private func detail(_ label: String, _ value: String) -> some View { |
| VStack(alignment: .leading, spacing: 4) { |
diff --git a/native/apple/Sources/EquipoKit/UI/TaskViewFixture.swift b/native/apple/Sources/EquipoKit/UI/TaskViewFixture.swift| index f8c2ce5e..368cc4ee 100644 |
| --- a/native/apple/Sources/EquipoKit/UI/TaskViewFixture.swift |
| +++ b/native/apple/Sources/EquipoKit/UI/TaskViewFixture.swift |
| @@ -44,7 +44,7 @@ public struct TaskViewFixture: View { |
| } |
| } |
| -private struct TaskViewFixtureTransport: EquipoTransport { |
| +struct TaskViewFixtureTransport: EquipoTransport { |
| private var changes: Bool { (ProcessInfo.processInfo.environment["EQUIPO_TASK_FIXTURE"] ?? "").hasPrefix("changes") } |
| private var candidate: String { changes ? String(repeating: "b", count: 40) : "3f9c2a167de8" } |
| private var hosted: Bool { ProcessInfo.processInfo.environment["EQUIPO_TASK_FIXTURE"] == "hosted" } |
diff --git a/native/apple/Sources/EquipoMac/EquipoMacApp.swift b/native/apple/Sources/EquipoMac/EquipoMacApp.swift| index b83fbf5b..c71b5914 100644 |
| --- a/native/apple/Sources/EquipoMac/EquipoMacApp.swift |
| +++ b/native/apple/Sources/EquipoMac/EquipoMacApp.swift |
| @@ -19,7 +19,7 @@ import SwiftUI |
| #if DEBUG |
| // Offline fixture captures must run this build, without an updater |
| // replacing it with a published app during the capture. |
| - if ProcessInfo.processInfo.environment["EQUIPO_MAC_POWER_FIXTURE"] != nil || ProcessInfo.processInfo.environment["EQUIPO_PREVIEW_FIXTURE"] != nil || ProcessInfo.processInfo.environment["EQUIPO_TASK_FIXTURE"] != nil || ProcessInfo.processInfo.environment["EQUIPO_NEEDS_FIXTURE"] != nil || ProcessInfo.processInfo.environment["EQUIPO_STOPPED_FIXTURE"] != nil || ProcessInfo.processInfo.environment["EQUIPO_ATTACHMENTS_FIXTURE"] != nil { return nil } |
| + if ProcessInfo.processInfo.environment["EQUIPO_NOTIFICATION_FIXTURE"] != nil || ProcessInfo.processInfo.environment["EQUIPO_MAC_POWER_FIXTURE"] != nil || ProcessInfo.processInfo.environment["EQUIPO_PREVIEW_FIXTURE"] != nil || ProcessInfo.processInfo.environment["EQUIPO_TASK_FIXTURE"] != nil || ProcessInfo.processInfo.environment["EQUIPO_NEEDS_FIXTURE"] != nil || ProcessInfo.processInfo.environment["EQUIPO_STOPPED_FIXTURE"] != nil || ProcessInfo.processInfo.environment["EQUIPO_ATTACHMENTS_FIXTURE"] != nil { return nil } |
| #endif |
| return NativeUpdater(policy: .quiet) |
| }() |
| @@ -29,7 +29,8 @@ import SwiftUI |
| Window(EquipoStrings.text("app.name"), id: "main") { |
| Group { |
| #if DEBUG |
| - if ProcessInfo.processInfo.environment["EQUIPO_MAC_POWER_FIXTURE"] != nil { MacPowerFixture(model: model) } |
| + if ProcessInfo.processInfo.environment["EQUIPO_NOTIFICATION_FIXTURE"] != nil { NotificationFixture() } |
| + else if ProcessInfo.processInfo.environment["EQUIPO_MAC_POWER_FIXTURE"] != nil { MacPowerFixture(model: model) } |
| else if ProcessInfo.processInfo.environment["EQUIPO_PREVIEW_FIXTURE"] != nil { PreviewFixture() } |
| else if ProcessInfo.processInfo.environment["EQUIPO_NEEDS_FIXTURE"] != nil { MacNeedsFixture() } |
| else if ProcessInfo.processInfo.environment["EQUIPO_STOPPED_FIXTURE"]?.hasPrefix("conversation-") == true { StoppedConversationFixture() } |
| @@ -85,6 +86,7 @@ final class EquipoMacDelegate: NSObject, NSApplicationDelegate { |
| #if DEBUG |
| if ProcessInfo.processInfo.environment["EQUIPO_MAC_POWER_FIXTURE"] != nil { NSApp.appearance = NSAppearance(named: .aqua) } |
| #endif |
| + notifications.onResponse = { [weak self] response in self?.model.notificationResponse(response); NSApp.activate() } |
| notifications.onRoute = { [weak self] route in |
| self?.model.open(route) |
| NSApp.activate() |
| @@ -114,6 +116,7 @@ struct MacRoot: View { |
| } |
| .tint(Color(nsColor: .webAccent)) |
| .frame(minWidth: 860, minHeight: 560) |
| + .modifier(NotificationActionPresenter(model: model)) |
| .modifier(MacSessionLifecycle(model: model)) |
| } |
| } |
| @@ -145,6 +148,7 @@ struct MacSessionLifecycle: ViewModifier { |
| NSApp.occlusionState.contains(.visible) ? model.foreground() : model.background() |
| } |
| .onChange(of: model.session?.status) { _, status in if status == .signedOut { model.sessionEnded() } } |
| + .onChange(of: model.session?.account.address) { model.notificationBindingChanged() } |
| .onChange(of: model.session?.needsYouCount) { _, count in model.needsYouChanged(count) } |
| } |
| } |
diff --git a/native/apple/Tests/EquipoKitTests/NotificationActionTests.swift b/native/apple/Tests/EquipoKitTests/NotificationActionTests.swift| new file mode 100644 |
| index 00000000..12735d90 |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/NotificationActionTests.swift |
| @@ -0,0 +1,97 @@ |
| +import Foundation |
| +import Testing |
| +import UserNotifications |
| +@testable import EquipoKit |
| + |
| +@MainActor @Suite struct NotificationActionTests { |
| + static let binding = "11111111-1111-1111-1111-111111111111" |
| + static let notification = "22222222-2222-2222-2222-222222222222" |
| + static func payload(_ changes: [String: Any] = [:]) -> [AnyHashable: Any] { |
| + var actions: [String: Any] = ["version": 1, "binding_id": binding, "notification_id": notification, "card_kind": "question", "card_revision": 4] |
| + for (key, value) in changes { actions[key] = value } |
| + return ["equipo": ["kind": "card", "card_id": "card_1", "task_id": "task_1", "actions": actions]] |
| + } |
| + @Test func onlyKnownCompleteBindingsCanAct() throws { |
| + let info = Self.payload() |
| + let answer = try #require(NotificationResponse(userInfo: info, category: "equipo.question.text.v1", action: "answer", text: "My answer")) |
| + #expect(answer.intent == .answer("My answer")) |
| + #expect(answer.binding.cardRevision == 4) |
| + for changes: [String: Any] in [["version": 2], ["version": true], ["card_revision": 0], ["card_revision": true], ["binding_id": "wrong"], ["notification_id": ""], ["card_kind": "merge"]] { |
| + #expect(NotificationResponse(userInfo: Self.payload(changes), category: "equipo.question.text.v1", action: "answer", text: "answer") == nil) |
| + } |
| + #expect(NotificationResponse(userInfo: info, category: "unknown", action: "answer", text: "answer") == nil) |
| + #expect(NotificationResponse(userInfo: info, category: "equipo.question.text.v1", action: "merge", text: nil) == nil) |
| + #expect(NotificationResponse(userInfo: info, category: "equipo.question.text.v1", action: "answer", text: nil) == nil) |
| + #expect(NotificationResponse(userInfo: info, category: "equipo.question.choices.v1", action: "answer", text: "ignored")?.intent == .question) |
| + } |
| + @Test func everyResponseRequiresUnlockAndForeground() { |
| + let categories = NotificationCategories.all |
| + #expect(categories.first(where: { $0.identifier == "needs_you" })?.actions.isEmpty == true) |
| + #expect(categories.count == 5) |
| + for category in categories where category.identifier != "needs_you" { |
| + #expect(!category.actions.isEmpty && category.actions.count <= 2) |
| + for action in category.actions { |
| + #expect(action.options.contains(.authenticationRequired)) |
| + #expect(action.options.contains(.foreground)) |
| + } |
| + } |
| + let text = categories.first { $0.identifier == "equipo.question.text.v1" } |
| + #expect(text?.actions.first is UNTextInputNotificationAction) |
| + let choices = categories.first { $0.identifier == "equipo.question.choices.v1" } |
| + #expect(!(choices?.actions.first is UNTextInputNotificationAction)) |
| + } |
| + @Test func receiptBodyKeepsOriginalKeyAndRevision() throws { |
| + let response = try #require(NotificationResponse(userInfo: Self.payload(), category: "equipo.question.text.v1", action: "answer", text: " My answer ")) |
| + let write = try response.pendingWrite() |
| + let body = try #require(JSONSerialization.jsonObject(with: write.body) as? [String: Any]) |
| + #expect(body["choice"] as? String == " My answer ") |
| + #expect(body["revision"] as? Int == 4) |
| + #expect(body["idempotency_key"] as? String == write.key) |
| + #expect(write.key == Self.notification) |
| + #expect(write.ifMatch == 4) |
| + let merge = try #require(NotificationResponse(userInfo: Self.payload(["card_kind": "merge"]), category: "equipo.merge.v1", action: "merge", text: nil)) |
| + #expect(throws: (any Error).self) { try merge.pendingWrite() } |
| + } |
| +} |
| + |
| +@MainActor @Suite struct NotificationBindingTests { |
| + @Test func stableOnRelaunchButRotatesAcrossSignIns() throws { |
| + let store = MemorySecretStore() |
| + let accounts = DeviceAccounts(store: store) |
| + var account = DeviceAccount.new(origin: URL(string: "https://equipo.test")!, label: "Phone") |
| + account.address = "person@example.test" |
| + account.credential = DeviceCredential(id: "device1", token: "secret", audience: "equipo", instanceId: "team", expiresAt: .distantFuture) |
| + try accounts.commit(.selectForNotifications(account), lifetime: accounts.lifetimes.current) |
| + let original = try #require(accounts.notificationSelection) |
| + try accounts.commit(.selectForNotifications(account), lifetime: accounts.lifetimes.current) |
| + #expect(accounts.notificationSelection == original) |
| + let restored = DeviceAccounts(store: store) |
| + try restored.commit(.selectForNotifications(account), lifetime: restored.lifetimes.current) |
| + #expect(restored.notificationSelection == original) |
| + account.credential = DeviceCredential(id: "device2", token: "new-secret", audience: "equipo", instanceId: "team", expiresAt: .distantFuture) |
| + try accounts.commit(.selectForNotifications(account), lifetime: accounts.lifetimes.current) |
| + #expect(accounts.notificationSelection?.id != original.id) |
| + try accounts.commit(.clearNotificationSelection(account), lifetime: accounts.lifetimes.current) |
| + #expect(accounts.notificationSelection == nil) |
| + try accounts.commit(.selectForNotifications(account), lifetime: accounts.lifetimes.current) |
| + let stale = accounts.lifetimes.current |
| + accounts.lifetimes.begin() |
| + #expect(throws: (any Error).self) { try accounts.commit(.clearNotificationSelection(account), lifetime: stale) } |
| + #expect(accounts.notificationSelection != nil) |
| + } |
| + @Test func registrationOptsInOnlyAfterCapability() async throws { |
| + for enabled in [false, true] { |
| + let transport = ScriptedTransport() |
| + transport.on("GET /capabilities", .success(APIResponse(status: 200, data: Data("{\"notification_actions_v1\":\(enabled)}".utf8)))) |
| + transport.on("POST /push-registrations", .success(APIResponse(status: 200, data: Data(#"{"environment":"production","platform":"macos","live_activities":false,"updated_at":"2026-11-27T10:00:00Z"}"#.utf8)))) |
| + let registrar = PushRegistrar(environment: .production, platform: .macos) |
| + await registrar.deviceTokenChanged(Data(repeating: 1, count: 32)) |
| + await registrar.attach(EquipoClient(transport: transport, token: "secret"), bindingID: NotificationActionTests.binding) |
| + let sent = try #require(transport.sent("POST /push-registrations").first) |
| + let raw = try #require(sent.body) |
| + let body = try #require(JSONSerialization.jsonObject(with: raw) as? [String: Any]) |
| + #expect((body["actions_version"] as? Int) == (enabled ? 1 : nil)) |
| + #expect((body["binding_id"] as? String) == (enabled ? NotificationActionTests.binding : nil)) |
| + } |
| + } |
| +} |
diff --git a/native/apple/Tests/EquipoKitTests/NotificationDispatchTests.swift b/native/apple/Tests/EquipoKitTests/NotificationDispatchTests.swift| new file mode 100644 |
| index 00000000..1a70874f |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/NotificationDispatchTests.swift |
| @@ -0,0 +1,202 @@ |
| +import Foundation |
| +import Testing |
| +import EquipoShareCore |
| +@testable import EquipoKit |
| + |
| +@MainActor @Suite struct NotificationDispatchTests { |
| + static func encode<T: Encodable>(_ value: T) throws -> Data { |
| + let encoder = EquipoJSON.encoder; encoder.dateEncodingStrategy = .iso8601 |
| + return try encoder.encode(value) |
| + } |
| + static func setup() throws -> (NotificationDispatcher, EquipoSession, ScriptedTransport, URL, NotificationSelection) { |
| + let server = ScriptedTransport() |
| + let detail = try TaskDetailModelTests.model(server) |
| + let selection = NotificationSelection(id: NotificationActionTests.binding, origin: server.origin, |
| + person: detail.session.account.address!, credential: "fixture", sessionHash: nil) |
| + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) |
| + let dispatcher = NotificationDispatcher(journal: ActionJournal(directory: directory)) |
| + dispatcher.attach(session: detail.session, selection: selection) |
| + server.on("GET /capabilities", .success(APIResponse(status: 200, data: Data(#"{"notification_actions_v1":true}"#.utf8)))) |
| + var snapshot: Snapshot = try Fixture.decode("thin/snapshot") |
| + var card = try #require(snapshot.cards?.first) |
| + card.id = "card_1"; card.revision = 4; card.kind = "question"; card.state = "open"; card.options = []; card.question = "Which?" |
| + snapshot.cards = [] // Bound card has aged out of the newest-50 snapshot. |
| + server.on("GET /cards/card_1", .success(APIResponse(status: 200, data: try Self.encode(card)))) |
| + server.on("GET /snapshot", .success(APIResponse(status: 200, data: try Self.encode(snapshot)))) |
| + return (dispatcher, detail.session, server, directory, selection) |
| + } |
| + @Test func lostReplyRelaunchReusesBodyAndKeyFromDisk() async throws { |
| + let (dispatcher, session, server, directory, selection) = try Self.setup() |
| + defer { try? FileManager.default.removeItem(at: directory) } |
| + server.on("POST /cards/card_1/answer", .failure(EquipoAPIError.offline)) |
| + let response = try #require(NotificationResponse(userInfo: NotificationActionTests.payload(), category: "equipo.question.text.v1", action: "answer", text: "my answer")) |
| + await dispatcher.receive(response) |
| + let first = try #require(server.sent("POST /cards/card_1/answer").first) |
| + #expect(dispatcher.notices.first?.canRetry == true) |
| + let restored = NotificationDispatcher(journal: ActionJournal(directory: directory)) |
| + restored.attach(session: session, selection: selection) |
| + #expect(restored.notices.first?.canRetry == true) |
| + #expect(server.sent("POST /cards/card_1/answer").count == 1, "restoration must not send automatically") |
| + // Current card is no longer open: the original request must still reach |
| + // the server's receipt lookup after a lost successful reply. |
| + server.replace("GET /snapshot", with: .failure(EquipoAPIError.status(500))) |
| + await restored.receive(response) |
| + let requests = server.sent("POST /cards/card_1/answer") |
| + try #require(requests.count == 2) |
| + #expect(first.body == requests[1].body) |
| + #expect(first.idempotencyKey == requests[1].idempotencyKey) |
| + #expect(first.ifMatch == requests[1].ifMatch) |
| + } |
| + @Test func wrongBindingDisabledCapabilityAndStaleCardNeverWrite() async throws { |
| + for mode in ["binding", "capability", "stale", "options", "ended"] { |
| + let (dispatcher, session, server, directory, _) = try Self.setup() |
| + defer { try? FileManager.default.removeItem(at: directory) } |
| + var changes: [String: Any] = [:] |
| + if mode == "binding" { changes["binding_id"] = NotificationActionTests.notification } |
| + if mode == "stale" { changes["card_revision"] = 3 } |
| + if mode == "capability" { server.replace("GET /capabilities", with: .success(APIResponse(status: 200, data: Data("{}".utf8)))) } |
| + if mode == "ended" { session.invalidate() } |
| + if mode == "options" { |
| + var snapshot: Snapshot = try Fixture.decode("thin/snapshot") |
| + var card = try #require(snapshot.cards?.first) |
| + card.id = "card_1"; card.revision = 4; card.kind = "question"; card.state = "open"; card.options = ["yes"] |
| + snapshot.cards = [card] |
| + server.replace("GET /cards/card_1", with: .success(APIResponse(status: 200, data: try Self.encode(card)))) |
| + } |
| + let response = try #require(NotificationResponse(userInfo: NotificationActionTests.payload(changes), category: "equipo.question.text.v1", action: "answer", text: "answer")) |
| + await dispatcher.receive(response) |
| + #expect(server.requests.allSatisfy { $0.method == "GET" }) |
| + } |
| + } |
| +} |
| + |
| +@MainActor @Suite struct NotificationMergeTests { |
| + @Test func mergeReadsFreshFactsAndOnlyPreparesConfirmation() async throws { |
| + let server = TaskDetailServer(), detail = try TaskDetailModelTests.model(server) |
| + await detail.load() |
| + let task = try #require(detail.task) |
| + var snapshot: Snapshot = try Fixture.decode("thin/snapshot") |
| + let card = try TaskDecisionTests.card(task) |
| + snapshot.cards = [card] |
| + let transport = NotificationMergeTransport(inner: server, snapshot: snapshot) |
| + let session = try TaskDetailModelTests.model(transport).session |
| + let selection = NotificationSelection(id: NotificationActionTests.binding, origin: transport.origin, person: session.account.address!, credential: "fixture", sessionHash: nil) |
| + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) |
| + defer { try? FileManager.default.removeItem(at: directory) } |
| + let dispatcher = NotificationDispatcher(journal: ActionJournal(directory: directory)) |
| + dispatcher.attach(session: session, selection: selection) |
| + var payload = NotificationActionTests.payload(["card_kind": "merge", "card_revision": card.revision]) |
| + var data = try #require(payload["equipo"] as? [String: Any]); data["card_id"] = card.id; data["task_id"] = task.id; payload["equipo"] = data |
| + let response = try #require(NotificationResponse(userInfo: payload, category: "equipo.merge.v1", action: "merge", text: nil)) |
| + await dispatcher.receive(response) |
| + let context = try #require(dispatcher.notices.first?.context) |
| + #expect(context.detail.confirmation?.card?.id == card.id) |
| + #expect(context.detail.task?.candidateSha == task.candidateSha) |
| + #expect(await server.writes == 0) |
| + await server.answerSuccessfully(card) |
| + await context.detail.confirm() |
| + #expect(await server.writes == 1) |
| + } |
| +} |
| +private struct NotificationMergeTransport: EquipoTransport { |
| + let inner: TaskDetailServer |
| + let snapshot: Snapshot |
| + var origin: URL { inner.origin } |
| + func send(_ request: APIRequest) async throws -> APIResponse { |
| + if request.path == "/capabilities" { return APIResponse(status: 200, data: Data(#"{"notification_actions_v1":true}"#.utf8)) } |
| + if request.method == "GET", request.path.hasPrefix("/cards/") { return try await APIResponse(status: 200, data: NotificationDispatchTests.encode(snapshot.cards!.first!)) } |
| + if request.path == "/snapshot" { |
| + var recent = snapshot; recent.cards = [] // The bound merge is outside the list window too. |
| + return try await APIResponse(status: 200, data: NotificationDispatchTests.encode(recent)) |
| + } |
| + return try await inner.send(request) |
| + } |
| + func lines(_ request: APIRequest) async throws -> AsyncThrowingStream<String, Error> { try await inner.lines(request) } |
| +} |
| + |
| +@MainActor @Suite struct NotificationLifecycleTests { |
| + @Test func accountSwitchWhileReadingCannotSubmit() async throws { |
| + let (_, session, server, directory, selection) = try NotificationDispatchTests.setup() |
| + defer { try? FileManager.default.removeItem(at: directory) } |
| + let gate = GatedTransport(inner: server, route: "GET /capabilities") |
| + gate.hold = true |
| + let gatedSession = try TaskDetailModelTests.model(gate).session |
| + let dispatcher = NotificationDispatcher(journal: ActionJournal(directory: directory)) |
| + dispatcher.attach(session: gatedSession, selection: selection) |
| + let response = try #require(NotificationResponse(userInfo: NotificationActionTests.payload(), category: "equipo.question.text.v1", action: "answer", text: "answer")) |
| + let work = Task { await dispatcher.receive(response) } |
| + await gate.waitUntilHeld() |
| + dispatcher.attach(session: session, selection: NotificationSelection(id: NotificationActionTests.notification, origin: session.origin, person: session.account.address!, credential: "fixture", sessionHash: nil)) |
| + gate.release(); await work.value |
| + #expect(server.sent("POST /cards/card_1/answer").isEmpty) |
| + #expect(dispatcher.notices.isEmpty) |
| + } |
| + @Test func signOutClearsPendingDiskAndNoTimerRetries() async throws { |
| + let (dispatcher, _, server, directory, selection) = try NotificationDispatchTests.setup() |
| + defer { try? FileManager.default.removeItem(at: directory) } |
| + server.on("POST /cards/card_1/answer", .failure(EquipoAPIError.offline)) |
| + let response = try #require(NotificationResponse(userInfo: NotificationActionTests.payload(), category: "equipo.question.text.v1", action: "answer", text: "answer")) |
| + await dispatcher.receive(response) |
| + let journal = ActionJournal(directory: directory) |
| + #expect(try journal.load(id: response.binding.notificationId, binding: selection.id) != nil) |
| + #expect(server.sent("POST /cards/card_1/answer").count == 1) |
| + dispatcher.clear() |
| + #expect(try journal.load(id: response.binding.notificationId, binding: selection.id) == nil) |
| + #expect(dispatcher.notices.isEmpty) |
| + } |
| + @Test func staleResponseRefreshesAndShowsReviewedWords() async throws { |
| + let (dispatcher, session, server, directory, selection) = try NotificationDispatchTests.setup() |
| + defer { try? FileManager.default.removeItem(at: directory) } |
| + let fixture: Snapshot = try Fixture.decode("thin/snapshot") |
| + var updated = try #require(fixture.cards?.first) |
| + updated.id = "card_1"; updated.revision = 5; updated.kind = "question"; updated.state = "open"; updated.question = "Changed question?" |
| + server.on("GET /cards/card_1", .success(APIResponse(status: 200, data: try NotificationDispatchTests.encode(updated)))) |
| + server.on("POST /cards/card_1/answer", .success(APIResponse(status: 409, data: Data(#"{"code":"card_stale","copy_key":"api.card_stale","request_id":"test"}"#.utf8)))) |
| + var route: PushRoute? |
| + dispatcher.onRoute = { route = $0 } |
| + let response = try #require(NotificationResponse(userInfo: NotificationActionTests.payload(), category: "equipo.question.text.v1", action: "answer", text: "answer")) |
| + await dispatcher.receive(response) |
| + #expect(route == .card("card_1")) |
| + #expect(dispatcher.notices.first?.error == EquipoStrings.text("api.card_stale")) |
| + #expect(dispatcher.notices.first?.canRetry == false) |
| + #expect(server.sent("GET /snapshot").count == 1) |
| + #expect(server.sent("GET /cards/card_1").count == 2) |
| + #expect(session.cards.first(where: { $0.id == "card_1" })?.revision == 5) |
| + #expect(try ActionJournal(directory: directory).load(id: response.binding.notificationId, binding: selection.id) == nil) |
| + } |
| +} |
| + |
| +@MainActor @Suite struct NotificationDuplicateTests { |
| + @Test func doubleRetryCannotStartASecondInflightPost() async throws { |
| + let (_, _, server, directory, selection) = try NotificationDispatchTests.setup() |
| + defer { try? FileManager.default.removeItem(at: directory) } |
| + let gate = GatedTransport(inner: server, route: "POST /cards/card_1/answer") |
| + let session = try TaskDetailModelTests.model(gate).session |
| + let dispatcher = NotificationDispatcher(journal: ActionJournal(directory: directory)) |
| + dispatcher.attach(session: session, selection: selection) |
| + server.on("POST /cards/card_1/answer", .failure(EquipoAPIError.offline)) |
| + let response = try #require(NotificationResponse(userInfo: NotificationActionTests.payload(), category: "equipo.question.text.v1", action: "answer", text: "answer")) |
| + await dispatcher.receive(response) |
| + let notice = try #require(dispatcher.notices.first) |
| + try #require(server.sent("POST /cards/card_1/answer").count == 1) |
| + gate.hold = true |
| + let first = Task { await dispatcher.retry(notice) } |
| + await gate.waitUntilHeld() |
| + await dispatcher.retry(notice) |
| + gate.release(); await first.value |
| + #expect(server.sent("POST /cards/card_1/answer").count == 2) |
| + } |
| + @Test func changingDelegateBodyNeverReplacesEarlierPendingRequest() async throws { |
| + let (dispatcher, _, server, directory, selection) = try NotificationDispatchTests.setup() |
| + defer { try? FileManager.default.removeItem(at: directory) } |
| + server.on("POST /cards/card_1/answer", .failure(EquipoAPIError.offline)) |
| + let first = try #require(NotificationResponse(userInfo: NotificationActionTests.payload(), category: "equipo.question.text.v1", action: "answer", text: "first")) |
| + let changed = try #require(NotificationResponse(userInfo: NotificationActionTests.payload(), category: "equipo.question.text.v1", action: "answer", text: "second")) |
| + await dispatcher.receive(first) |
| + let before = try ActionJournal(directory: directory).load(id: first.binding.notificationId, binding: selection.id) |
| + await dispatcher.receive(changed) |
| + #expect(server.sent("POST /cards/card_1/answer").count == 1) |
| + #expect(dispatcher.notices.first?.error == EquipoStrings.text("api.idempotency_conflict")) |
| + #expect(try ActionJournal(directory: directory).load(id: first.binding.notificationId, binding: selection.id) == before) |
| + } |
| +} |
diff --git a/native/apple/Tests/EquipoKitTests/NotificationJournalTests.swift b/native/apple/Tests/EquipoKitTests/NotificationJournalTests.swift| new file mode 100644 |
| index 00000000..05055a77 |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/NotificationJournalTests.swift |
| @@ -0,0 +1,38 @@ |
| +import Foundation |
| +import Testing |
| +import EquipoShareCore |
| +@testable import EquipoKit |
| + |
| +@Suite struct NotificationJournalTests { |
| + @Test func requestIsDurableBoundAndNeverReplacedOrExtended() throws { |
| + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) |
| + defer { try? FileManager.default.removeItem(at: directory) } |
| + let journal = ActionJournal(directory: directory) |
| + let now = Date(timeIntervalSince1970: 100000) |
| + let body = Data("original request".utf8) |
| + try journal.save(id: "event-a", binding: "session-a", body: body, now: now) |
| + let restored = ActionJournal(directory: directory) |
| + #expect(try restored.load(id: "event-a", binding: "session-a", now: now) == body) |
| + #expect(try restored.load(id: "event-a", binding: "session-b", now: now) == nil) |
| + #expect(throws: (any Error).self) { try restored.save(id: "event-a", binding: "session-a", body: Data("changed".utf8), now: now) } |
| + try restored.save(id: "event-b", binding: "session-a", body: Data("independent".utf8), now: now) |
| + try restored.save(id: "event-a", binding: "session-a", body: body, now: now.addingTimeInterval(86399)) |
| + #expect(try restored.load(id: "event-a", binding: "session-a", now: now.addingTimeInterval(86400)) == nil) |
| + restored.clear() |
| + #expect(try restored.load(id: "event-b", binding: "session-a", now: now) == nil) |
| + } |
| + @Test func boundedAndCompletedEntriesAreRemoved() throws { |
| + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) |
| + defer { try? FileManager.default.removeItem(at: directory) } |
| + let journal = ActionJournal(directory: directory) |
| + #expect(throws: (any Error).self) { try journal.save(id: "big", binding: "a", body: Data(repeating: 1, count: 64 * 1024 + 1)) } |
| + for n in 0..<32 { try journal.save(id: "event-\(n)", binding: "a", body: Data([1])) } |
| + #expect(throws: (any Error).self) { try journal.save(id: "overflow", binding: "a", body: Data([1])) } |
| + try journal.remove(id: "event-0", binding: "a") |
| + #expect(try ActionJournal(directory: directory).load(id: "event-0", binding: "a") == nil) |
| + try journal.save(id: "replacement", binding: "a", body: Data([2])) |
| + let files = try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil) |
| + #expect(files.count == 1) |
| + #expect((try FileManager.default.attributesOfItem(atPath: files[0].path)[.posixPermissions] as? NSNumber)?.intValue == 0o600) |
| + } |
| +} |
diff --git a/native/ios/Sources/EquipoPhoneApp.swift b/native/ios/Sources/EquipoPhoneApp.swift| index 0bb0ce01..85512ebc 100644 |
| --- a/native/ios/Sources/EquipoPhoneApp.swift |
| +++ b/native/ios/Sources/EquipoPhoneApp.swift |
| @@ -7,7 +7,8 @@ struct EquipoPhoneApp: App { |
| var body: some Scene { |
| WindowGroup { |
| #if DEBUG |
| - if ProcessInfo.processInfo.environment["EQUIPO_SHARE_FIXTURE"] != nil { |
| + if ProcessInfo.processInfo.environment["EQUIPO_NOTIFICATION_FIXTURE"] != nil { NotificationFixture() } |
| + else if ProcessInfo.processInfo.environment["EQUIPO_SHARE_FIXTURE"] != nil { |
| #if targetEnvironment(simulator) |
| ShareFixture() |
| #else |
diff --git a/native/ios/UITests/NotificationActionUITests.swift b/native/ios/UITests/NotificationActionUITests.swift| new file mode 100644 |
| index 00000000..4664325d |
| --- /dev/null |
| +++ b/native/ios/UITests/NotificationActionUITests.swift |
| @@ -0,0 +1,34 @@ |
| +import XCTest |
| + |
| +/// The unlocked foreground half only. Real APNs, Face ID and hidden previews |
| +/// remain a physical-device gate before enabling production capability. |
| +final class NotificationActionUITests: XCTestCase { |
| + @MainActor func testBoundQuestionShowsItsOptions() { |
| + let app = XCUIApplication() |
| + app.launchEnvironment["EQUIPO_NOTIFICATION_FIXTURE"] = "question" |
| + app.launch() |
| + defer { app.terminate() } |
| + XCTAssertTrue(app.staticTexts["Should the badge clear when you switch teams too?"].waitForExistence(timeout: 10)) |
| + XCTAssertTrue(app.buttons["Clear it when switching teams"].exists) |
| + XCTAssertTrue(app.buttons["Keep each team’s count"].exists) |
| + capture("iphone-notification-question") |
| + } |
| + @MainActor func testMergeShowsFreshEvidenceBeforeFinalTap() { |
| + let app = XCUIApplication() |
| + app.launchEnvironment["EQUIPO_NOTIFICATION_FIXTURE"] = "merge" |
| + app.launch() |
| + defer { app.terminate() } |
| + XCTAssertTrue(app.buttons["task-confirm"].waitForExistence(timeout: 10)) |
| + XCTAssertTrue(app.staticTexts["Approved"].firstMatch.exists) |
| + XCTAssertTrue(app.staticTexts.matching(NSPredicate(format: "label BEGINSWITH %@", "The badge now resets when the person signs out.")).firstMatch.exists) |
| + XCTAssertTrue(app.staticTexts["equipo/needs-badge-sign-out"].exists) |
| + XCTAssertTrue(app.staticTexts["3f9c2a167de8"].exists) |
| + capture("iphone-notification-merge") |
| + app.buttons["task-confirm"].tap() |
| + XCTAssertTrue(app.buttons["task-confirm"].waitForNonExistence(timeout: 5)) |
| + } |
| + @MainActor private func capture(_ name: String) { |
| + let attachment = XCTAttachment(screenshot: XCUIScreen.main.screenshot()) |
| + attachment.name = name; attachment.lifetime = .keepAlways; add(attachment) |
| + } |
| +} |
diff --git a/native/ios/project.yml b/native/ios/project.yml| index 68a69667..d5a518dc 100644 |
| --- a/native/ios/project.yml |
| +++ b/native/ios/project.yml |
| @@ -147,6 +147,18 @@ targets: |
| GENERATE_INFOPLIST_FILE: true |
| TEST_TARGET_NAME: EquipoPhone |
| + NotificationActionUITests: |
| + type: bundle.ui-testing |
| + platform: iOS |
| + sources: [UITests/NotificationActionUITests.swift] |
| + dependencies: |
| + - target: EquipoPhone |
| + settings: |
| + base: |
| + PRODUCT_BUNDLE_IDENTIFIER: works.oficina.equipo.notification-tests |
| + GENERATE_INFOPLIST_FILE: true |
| + TEST_TARGET_NAME: EquipoPhone |
| + |
| AttachmentSourceUITests: |
| type: bundle.ui-testing |
| platform: iOS |
| @@ -217,3 +229,11 @@ schemes: |
| ShareUITests: [test] |
| test: |
| targets: [ShareUITests] |
| + |
| + NotificationActionsUI: |
| + build: |
| + targets: |
| + EquipoPhone: all |
| + NotificationActionUITests: [test] |
| + test: |
| + targets: [NotificationActionUITests] |
diff --git a/native/share/Sources/EquipoShareCore/ActionJournal.swift b/native/share/Sources/EquipoShareCore/ActionJournal.swift| new file mode 100644 |
| index 00000000..7d3867c8 |
| --- /dev/null |
| +++ b/native/share/Sources/EquipoShareCore/ActionJournal.swift |
| @@ -0,0 +1,64 @@ |
| +import Foundation |
| + |
| +/// Protected, bounded immutable requests for the foreground app. Callers |
| +/// serialize access on MainActor. No credential belongs in a record. Unlike |
| +/// the share journal, every read requires the exact sign-in generation. |
| +public struct ActionJournal: Sendable { |
| + private let directory: URL |
| + private var file: URL { directory.appendingPathComponent("actions.json") } |
| + private struct Entry: Codable { let id: String; let binding: String; let body: Data; let created: Date } |
| + public init(directory: URL) { self.directory = directory } |
| + private func entries(now: Date) throws -> [Entry] { |
| + guard FileManager.default.fileExists(atPath: file.path) else { return [] } |
| + let handle = try FileHandle(forReadingFrom: file); defer { try? handle.close() } |
| + let raw = try handle.read(upToCount: 3 * 1024 * 1024 + 1) ?? Data() |
| + guard raw.count <= 3 * 1024 * 1024 else { throw ShareFailure.unconfirmed } |
| + let all = try JSONDecoder().decode([Entry].self, from: raw) |
| + guard all.count <= 32, all.allSatisfy({ $0.body.count <= 64 * 1024 }) else { throw ShareFailure.unconfirmed } |
| + let current = all.filter { now >= $0.created && now.timeIntervalSince($0.created) < 86400 } |
| + if current.count != all.count { try persist(current) } |
| + return current |
| + } |
| + private func persist(_ entries: [Entry]) throws { |
| + if entries.isEmpty { |
| + if FileManager.default.fileExists(atPath: file.path) { try FileManager.default.removeItem(at: file) } |
| + return |
| + } |
| + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) |
| + var folder = directory; var values = URLResourceValues(); values.isExcludedFromBackup = true; try folder.setResourceValues(values) |
| + let data = try JSONEncoder().encode(entries) |
| + guard data.count <= 3 * 1024 * 1024 else { throw ShareFailure.unconfirmed } |
| + #if os(iOS) |
| + try data.write(to: file, options: [.atomic, .completeFileProtection]) |
| + #else |
| + try data.write(to: file, options: .atomic) |
| + #endif |
| + try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: file.path) |
| + } |
| + /// Restore only the active sign-in. Other generations cannot reappear |
| + /// after an account change, including a change while the app was closed. |
| + public func pending(binding: String, now: Date = Date()) throws -> [Data] { |
| + let all = try entries(now: now) |
| + let current = all.filter { $0.binding == binding } |
| + if all.count != current.count { try persist(current) } |
| + return current.map(\.body) |
| + } |
| + public func load(id: String, binding: String, now: Date = Date()) throws -> Data? { |
| + try entries(now: now).first { $0.id == id && $0.binding == binding }?.body |
| + } |
| + public func save(id: String, binding: String, body: Data, now: Date = Date()) throws { |
| + guard !id.isEmpty, id.utf8.count <= 128, !binding.isEmpty, binding.utf8.count <= 4096, body.count <= 64 * 1024 else { throw ShareFailure.unconfirmed } |
| + var all = try entries(now: now) |
| + if let existing = all.first(where: { $0.id == id && $0.binding == binding }) { |
| + guard existing.body == body else { throw ShareFailure.unconfirmed } |
| + return |
| + } |
| + guard all.count < 32 else { throw ShareFailure.unconfirmed } |
| + all.append(Entry(id: id, binding: binding, body: body, created: now)) |
| + try persist(all) |
| + } |
| + public func remove(id: String, binding: String, now: Date = Date()) throws { |
| + try persist(entries(now: now).filter { $0.id != id || $0.binding != binding }) |
| + } |
| + public func clear() { try? FileManager.default.removeItem(at: file) } |
| +} |