Merge branch 'notify/actions' into main
61 files changed,
+3,302
−179
.rastrillo/budgets.txt+8 −4docs/api/equipo-v1.md+46 −1docs/api/equipo-v1.openapi.json+235 −20docs/superpowers/plans/2026-11-27-notification-actions.md+194 −0docs/superpowers/plans/CONTROLLER-REPORT-notification-actions.md+215 −0internal/equipo/app.go+1 −0internal/equipo/chat/card_read.go+35 −0internal/equipo/chat/http.go+45 −2internal/equipo/chat/models.go+1 −1internal/equipo/chat/notification_actions.go+134 −0internal/equipo/chat/notification_actions_test.go+158 −0internal/equipo/chat/notification_card_test.go+114 −0internal/equipo/chat/notification_http_test.go+105 −0internal/equipo/chat/notification_payload.go+78 −0internal/equipo/chat/notification_payload_test.go+235 −0internal/equipo/chat/notification_review_test.go+128 −0internal/equipo/chat/projects.go+103 −78internal/equipo/chat/push.go+13 −1internal/equipo/chat/store.go+7 −6internal/equipo/config.go+4 −0internal/equipo/conversation/card_id_test.go+44 −0internal/equipo/migrations/0111_notification_actions.sql+10 −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/api.go+20 −16internal/wire/push.go+32 −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/API/Thin.swift+2 −0native/apple/Sources/EquipoKit/Pairing/DeviceAccount.swift+17 −0native/apple/Sources/EquipoKit/Push/NotificationDispatcher.swift+209 −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+23 −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+119 −0native/apple/Tests/EquipoKitTests/NotificationDispatchTests.swift+256 −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 passed — run details
CI log
=== prepare ===
ci-box: machine: aarch64, 32 CPUs, 62 GiB memory, kernel 7.0.0-1017-aws
ci-box: python 3.12.3; Docker version 29.1.3, build 29.1.3-0ubuntu3~24.04.2
ci-box: user namespaces allowed: 233151
ci-box: cgroup: cgroup2fs
ci-box: disk /home/ci/work/repos/oficina__equipo/wt/main: Type Size Avail | ext4 96G 86G
ci-box: disk /home/ci/.cache/equipo-ci-box: Type Size Avail | ext4 96G 86G
ci-box: bwrap: fetched and verified in 0.3s
ci-box: claude: fetched and verified in 2.0s
ci-box: codex: fetched and verified in 3.5s
ci-box: codex-code-mode-host: fetched and verified in 1.5s
ci-box: libwrap: fetched and verified in 0.3s
ci-box: socat: fetched and verified in 0.4s
npm warn deprecated node-domexception@1.0.0: Use your platform's native DOMException instead
ci-box: image pulled in 10.0s
ci-box: pi: installed and verified in 7.1s
ci-box: opencode: installed and verified in 2.2s
ci-box: chromium 156.0.8078.79-1~deb13u1: 76 packages fetched, verified and unpacked in 9.2s
ci-box: clone deepened in 4.8s
ci-box: file times set from content: 3201 files, 211 directories
ci-box: ready in 17.9s
=== 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.146s
=== compile ===
go build ./...
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py compile
+ go build -tags testbuild ./...
4.5s
+ 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
rastrillo: budget test: go test failed
--- FAIL amadan.net/oficina/equipo/internal/headless TestHeadless
=== RUN TestHeadless
--- FAIL: TestHeadless (68.72s)
--- FAIL amadan.net/oficina/equipo/internal/headless TestHeadless/4c_rebase
=== RUN TestHeadless/4c_rebase
time=2026-11-27T00:07:50.974Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-27T00:07:50.974Z level=INFO msg="startup phase done" phase=state_lock took=79µs
time=2026-11-27T00:07:50.974Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-27T00:07:50.974Z level=INFO msg="startup phase done" phase=claim_roots took=82µs
time=2026-11-27T00:07:50.974Z level=INFO msg="startup phase" phase=sweep
time=2026-11-27T00:07:51.010Z level=INFO msg="startup phase done" phase=sweep took=35.856ms
time=2026-11-27T00:07:51.010Z level=INFO msg="startup phase" phase=credentials
time=2026-11-27T00:07:51.010Z level=INFO msg="startup phase done" phase=credentials took=102µs
time=2026-11-27T00:07:51.010Z level=INFO msg="startup phase" phase=open_state
time=2026-11-27T00:07:51.059Z level=INFO msg="startup phase done" phase=open_state took=48.9ms
time=2026-11-27T00:07:51.059Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-27T00:07:51.060Z level=INFO msg=connecting host=127.0.0.1:34561 protocol=32
time=2026-11-27T00:07:51.062Z level=INFO msg=connected host=127.0.0.1:34561 took=2.397ms
time=2026-11-27T00:07:51.062Z level=INFO msg="capabilities gathering"
time=2026-11-27T00:07:51.063Z level=INFO msg="capabilities gathered" took=676µs tags=linux,claude,go
time=2026-11-27T00:07:51.064Z level=INFO msg="hello sent" protocol=32
time=2026-11-27T00:07:51.070Z level=INFO msg=welcome protocol=32 role=primary generation=1
time=2026-11-27T00:07:51.936Z level=INFO msg="connection checked" connection=claude-1 state=healthy
time=2026-11-27T00:07:55.819Z level=INFO msg="kept sessions" kept=1 bytes=2939 expired=0
time=2026-11-27T00:08:01.594Z level=INFO msg="kept sessions" kept=2 bytes=5145 expired=0
merge_test.go:245: steps [engineering:done checks:passed review:approve merge:merge_conflict engineering:queued], want [engineering:done checks:passed review:approve merge:merge_conflict engineering:done checks:passed review:approve merge:done] (in_progress )
time=2026-11-27T00:08:01.698Z level=WARN msg="step clone" err="signal: killed"
time=2026-11-27T00:08:01.698Z level=WARN msg="step sweep" err=cancelled
time=2026-11-27T00:08:01.698Z level=WARN msg="kept sessions" err=cancelled
--- FAIL: TestHeadless/4c_rebase (11.20s)
--- FAIL amadan.net/oficina/equipo/internal/headless (package output)
FAIL
rastrillo-budget/v1 ran 1m8.72s
FAIL amadan.net/oficina/equipo/internal/headless 68.986s
receipt: test step 1m10.375s 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 1m8.72s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m8.72s amadan.net/oficina/equipo/internal/headless TestHeadless
exit status 1
+ go test -tags testbuild -timeout 15m -run '^TestHeadless$/^4c_rebase$|^TestHeadless$/^4b_ask$|^TestHeadless$/^4c_checks_card$|^TestHeadless$/^4_step_crash$' -v -run '^TestHeadless$/^4c_rebase$' -count=1 ./internal/headless (retry, once)
##############################################################################
FLAKE ./internal/headless:TestHeadless/4c_rebase headless-work 10659d1f3c85c08da49e049653fb8f61440810a5 11.20s 82.18
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
machine: 32 CPUs, load 82.61, cpu waiting 44.57%, memory waiting 0.00%, io waiting 0.39%
--- 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
rastrillo: budget test: go test failed
--- FAIL amadan.net/oficina/equipo/internal/headless TestHeadless
=== RUN TestHeadless
--- FAIL: TestHeadless (76.88s)
--- FAIL amadan.net/oficina/equipo/internal/headless TestHeadless/2b_desk_failure
=== RUN TestHeadless/2b_desk_failure
time=2026-11-27T00:07:14.192Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-27T00:07:14.193Z level=INFO msg="startup phase done" phase=state_lock took=155µs
time=2026-11-27T00:07:14.193Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-27T00:07:14.193Z level=INFO msg="startup phase done" phase=claim_roots took=103µs
time=2026-11-27T00:07:14.193Z level=INFO msg="startup phase" phase=sweep
time=2026-11-27T00:07:14.223Z level=INFO msg="startup phase done" phase=sweep took=29.823ms
time=2026-11-27T00:07:14.223Z level=INFO msg="startup phase" phase=credentials
time=2026-11-27T00:07:14.223Z level=INFO msg="startup phase done" phase=credentials took=132µs
time=2026-11-27T00:07:14.223Z level=INFO msg="startup phase" phase=open_state
time=2026-11-27T00:07:14.265Z level=INFO msg="startup phase done" phase=open_state took=42.478ms
time=2026-11-27T00:07:14.266Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-27T00:07:14.267Z level=INFO msg=connecting host=127.0.0.1:41987 protocol=32
time=2026-11-27T00:07:14.269Z level=INFO msg=connected host=127.0.0.1:41987 took=1.88ms
time=2026-11-27T00:07:14.269Z level=INFO msg="capabilities gathering"
time=2026-11-27T00:07:14.270Z level=INFO msg="capabilities gathered" took=933µs tags=linux,claude,go
time=2026-11-27T00:07:14.270Z level=INFO msg="hello sent" protocol=32
time=2026-11-27T00:07:14.274Z level=INFO msg=welcome protocol=32 role=primary generation=1
time=2026-11-27T00:07:15.109Z level=INFO msg="connection checked" connection=claude-1 state=healthy
time=2026-11-27T00:07:16.770Z level=WARN msg="coordinator desk" err=*os.LinkError
movein_test.go:304: introductions 0, coordinator moving_in
--- FAIL: TestHeadless/2b_desk_failure (3.04s)
--- FAIL amadan.net/oficina/equipo/internal/headless (package output)
FAIL
rastrillo-budget/v1 ran 1m16.877s
FAIL amadan.net/oficina/equipo/internal/headless 77.124s
receipt: test step 1m18.575s 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 1m16.877s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m16.88s amadan.net/oficina/equipo/internal/headless TestHeadless
exit status 1
+ go 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$' -v -run '^TestHeadless$/^2b_desk_failure$' -count=1 ./internal/headless (retry, once)
##############################################################################
FLAKE ./internal/headless:TestHeadless/2b_desk_failure headless-review 10659d1f3c85c08da49e049653fb8f61440810a5 3.04s 82.15
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
machine: 32 CPUs, load 79.98, cpu waiting 45.20%, memory waiting 0.00%, io waiting 0.45%
--- 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 1m19.632s 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 1m17.198s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m7.11s amadan.net/oficina/equipo/internal/headless TestHeadlessConnections
receipt: slow test 5.71s amadan.net/oficina/equipo/internal/headless TestHeadlessTokenPasteEndToEnd
receipt: slow test 4.38s amadan.net/oficina/equipo/internal/headless TestHeadlessTokenConnection
machine: 32 CPUs, load 82.15, cpu waiting 44.95%, memory waiting 0.00%, io waiting 0.48%
--- 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 1m16.15s 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.947s amadan.net/oficina/equipo/internal/headless
receipt: slow test 35.75s amadan.net/oficina/equipo/internal/headless TestMacWorker
receipt: slow test 20.54s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 8.99s amadan.net/oficina/equipo/internal/headless TestHeadlessPrewarm
receipt: slow test 8.66s amadan.net/oficina/equipo/internal/headless TestHeadlessAttachments
machine: 32 CPUs, load 80.16, cpu waiting 44.01%, 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 1m35.474s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m33.178s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m4.19s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 9.12s amadan.net/oficina/equipo/internal/headless TestHeadlessRunnerKillLeavesNoCopies
receipt: slow test 8.09s amadan.net/oficina/equipo/internal/headless TestHeadlessCopyRotation
receipt: slow test 7.15s amadan.net/oficina/equipo/internal/headless TestHeadlessPolicyGuards
receipt: slow test 4.62s amadan.net/oficina/equipo/internal/headless TestHeadlessNewHouseRuleStartsFresh
machine: 32 CPUs, load 82.61, cpu waiting 44.59%, memory waiting 0.00%, io waiting 0.36%
--- 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.893s 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 2m43.461s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m37.98s amadan.net/oficina/equipo/internal/headless TestHeadlessAssistant
receipt: slow test 18.36s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 8.7s amadan.net/oficina/equipo/internal/headless TestHeadlessResearchHandoff
receipt: slow test 6.63s amadan.net/oficina/equipo/internal/headless TestHeadlessTurnBatching
receipt: slow test 6.52s amadan.net/oficina/equipo/internal/headless TestHeadlessBatchAfterRefusedReply
machine: 32 CPUs, load 34.71, cpu waiting 15.29%, memory waiting 0.00%, io waiting 0.11%
--- 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.339s 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.6s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 9.55s amadan.net/oficina/equipo/internal/thintest TestContractTeamJobSettledStates
receipt: slow test 6.77s amadan.net/oficina/equipo/internal/thintest TestExplorePreviewsOff
receipt: slow test 5s amadan.net/oficina/equipo/internal/thintest TestContractTeamNudgePersonNeeds
receipt: slow test 3.79s amadan.net/oficina/equipo/internal/thintest TestContractPreviewHeldUntilPublishAnswer
receipt: slow test 3.65s amadan.net/oficina/equipo/internal/thintest TestContractTeamUpdatePersonNeeds
machine: 32 CPUs, load 49.96, cpu waiting 25.20%, 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.693s 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 1m55.713s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 9.61s amadan.net/oficina/equipo/internal/thintest TestContractRetryPreviewUnverifiedMerge
receipt: slow test 9.11s amadan.net/oficina/equipo/internal/thintest TestContractPreviewNotScheduled
receipt: slow test 4.99s amadan.net/oficina/equipo/internal/thintest TestContractPublishNotOffered
receipt: slow test 4.51s amadan.net/oficina/equipo/internal/thintest TestContractMacRecheckMergeAuthority
receipt: slow test 2.96s amadan.net/oficina/equipo/internal/thintest TestContractPausedJob
machine: 32 CPUs, load 61.94, cpu waiting 33.36%, 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 5m7.479s, over the 45s its record on line 44 allows; reported only, timing fails on CI
receipt: test step 5m13.143s 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 5m7.479s amadan.net/oficina/equipo/internal/runner/thin
receipt: slow test 36.99s amadan.net/oficina/equipo/internal/runner/thin TestModelsProbeAnsweredByAnotherModel
receipt: slow test 36.91s amadan.net/oficina/equipo/internal/runner/thin TestModelsEngineeringProbesThenRunsTheStrongest
receipt: slow test 36.82s amadan.net/oficina/equipo/internal/runner/thin TestModelsUnhealthyRetriedOnDemand
receipt: slow test 18.47s amadan.net/oficina/equipo/internal/runner/thin TestModelsProbeRunsInsideTheAdmission
receipt: slow test 10.05s amadan.net/oficina/equipo/internal/runner/thin TestTimeoutKeepsNothingForAnOlderInstance
machine: 32 CPUs, load 3.88, cpu waiting 1.29%, 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 50.922s 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 49.897s amadan.net/oficina/equipo/internal/runner
receipt: slow test 29.86s amadan.net/oficina/equipo/internal/runner TestDirectBugWorkflow
receipt: slow test 20.02s amadan.net/oficina/equipo/internal/runner TestEnrolKeepsTheRole
machine: 32 CPUs, load 57.91, cpu waiting 34.42%, memory waiting 0.00%, io waiting 0.77%
--- 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.627s 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.363s amadan.net/oficina/equipo/internal/runner
receipt: slow test 51.37s amadan.net/oficina/equipo/internal/runner TestPlanWorkflowCandidateOrder
receipt: slow test 43.85s amadan.net/oficina/equipo/internal/runner TestPlanWorkflowFeature
receipt: slow test 8.44s amadan.net/oficina/equipo/internal/runner TestCoordinatorRecoveryCallRefusalKeepsServing
receipt: slow test 1.53s amadan.net/oficina/equipo/internal/runner TestCoordinatorRefusalMatrix
machine: 32 CPUs, load 80.37, cpu waiting 41.62%, memory waiting 0.00%, io waiting 0.65%
--- 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 35.775s 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 34.955s amadan.net/oficina/equipo/internal/runner
receipt: slow test 5.12s amadan.net/oficina/equipo/internal/runner TestDirectFaultIsolation
receipt: slow test 3.21s amadan.net/oficina/equipo/internal/runner TestClaimRefusalsBackOff
receipt: slow test 3.12s amadan.net/oficina/equipo/internal/runner TestCoordinatorRecoveryRefusedKeepsServing
receipt: slow test 2.6s amadan.net/oficina/equipo/internal/runner TestToolVerbUnderFakeHarness
receipt: slow test 1.61s amadan.net/oficina/equipo/internal/runner TestReportPostsRetryExactRequest
machine: 32 CPUs, load 41.11, cpu waiting 22.27%, memory waiting 0.00%, io waiting 1.01%
--- 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.5%, load 30.41
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 1m9.482s 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.512s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 29.14s amadan.net/oficina/equipo/internal/equipotest TestAuthorityCoreIntegration
receipt: slow test 29s amadan.net/oficina/equipo/internal/equipotest TestBootstrapNamesOwnersSetting
receipt: slow test 26.99s amadan.net/oficina/equipo/internal/equipotest TestAccountLabelMigration
receipt: slow test 24.09s amadan.net/oficina/equipo/internal/equipotest TestBudgetConfigurationFailuresAreAtomic
receipt: slow test 23.91s amadan.net/oficina/equipo/internal/equipotest TestAccountConcurrentDuplicate
machine: 32 CPUs, load 78.88, cpu waiting 43.61%, 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.0%, load 30.41
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 1m19.424s 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 1m17.286s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 20.07s amadan.net/oficina/equipo/internal/equipotest TestProjectsFailuresRollBack
receipt: slow test 20.05s amadan.net/oficina/equipo/internal/equipotest TestProjectWritesRequireCurrentOwner
receipt: slow test 20.05s amadan.net/oficina/equipo/internal/equipotest TestProjectRetryAndRevision
receipt: slow test 20.02s amadan.net/oficina/equipo/internal/equipotest TestProjectOwnersAreMembers
receipt: slow test 19.98s amadan.net/oficina/equipo/internal/equipotest TestProjectRejectsUnsafeBinding
machine: 32 CPUs, load 70.70, cpu waiting 37.83%, memory waiting 0.00%, io waiting 0.29%
--- 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.0%, load 30.41
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 1m17.65s 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 1m11.86s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 16.6s amadan.net/oficina/equipo/internal/equipotest TestReleaseStampContract
receipt: slow test 13.48s amadan.net/oficina/equipo/internal/equipotest TestRosterChangesAffectExistingSession
receipt: slow test 10.48s amadan.net/oficina/equipo/internal/equipotest TestRosterRemovalWhileAssigned
receipt: slow test 10.44s amadan.net/oficina/equipo/internal/equipotest TestRosterRemovalRollsBack
receipt: slow test 7.35s amadan.net/oficina/equipo/internal/equipotest TestRosterBootstrapOnce
machine: 32 CPUs, load 70.70, cpu waiting 39.04%, 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.0%, load 30.41
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.578s 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.669s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 26.12s amadan.net/oficina/equipo/internal/equipotest TestSigninNoProof
receipt: slow test 25.61s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsSeedRollback
receipt: slow test 25.6s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsSeedExistingTeam
receipt: slow test 23.78s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsSeedOnce
receipt: slow test 23.75s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsUpgrade
machine: 32 CPUs, load 78.88, cpu waiting 43.61%, 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.5%, load 30.41
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.797s 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.286s amadan.net/oficina/equipo/internal/plan3test
receipt: slow test 3.78s amadan.net/oficina/equipo/internal/plan3test TestPlan3Upgrade
receipt: slow test 3.57s amadan.net/oficina/equipo/internal/plan3test TestCoordinatorAcceptance3B
receipt: slow test 1.66s amadan.net/oficina/equipo/internal/plan3test TestConversationQuestionRace
receipt: slow test 1.52s amadan.net/oficina/equipo/internal/plan3test TestCoordinatorAcceptance3A
receipt: slow test 1.33s amadan.net/oficina/equipo/internal/plan3test TestPlanMigrationUpgrade
machine: 32 CPUs, load 80.14, cpu waiting 45.09%, memory waiting 0.00%, io waiting 0.42%
--- 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.0%, load 30.41
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/runner/metered TestMeteredRaceAdmitsExactlyOne
=== RUN TestMeteredRaceAdmitsExactlyOne
meter_test.go:205: round 5: ran map[], held map[engineering:busy review:busy]
--- FAIL: TestMeteredRaceAdmitsExactlyOne (0.21s)
--- FAIL amadan.net/oficina/equipo/internal/runner/metered (package output)
FAIL
rastrillo-budget/v1 ran 2.069s
FAIL amadan.net/oficina/equipo/internal/runner/metered 2.114s
budget note: internal/equipo took 2m26.26s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/equipo/chat took 25.914s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/idtest took 2m4.43s, 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 54.056s, over the 15s its record on line 40 allows; reported only, timing fails on CI
budget note: internal/runner/forge took 23.738s, over the 20s its record on line 35 allows; reported only, timing fails on CI
budget note: internal/runner/provider/claude/realcli took 16.957s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/runner/provider/pi took 1m23.744s, over the 1m0s its record on line 27 allows; reported only, timing fails on CI
budget note: internal/runner/workspace took 14.863s, over the 10s the default allows; reported only, timing fails on CI
receipt: test step 2m32.333s 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 2m26.26s amadan.net/oficina/equipo/internal/equipo
receipt: slow package 2m4.43s amadan.net/oficina/equipo/internal/idtest
receipt: slow package 1m23.744s amadan.net/oficina/equipo/internal/runner/provider/pi
receipt: slow package 1m11.256s amadan.net/oficina/equipo/internal/runner/provider/opencode
receipt: slow package 1m1.894s amadan.net/oficina/equipo/internal/runner/checks
receipt: slow test 54.91s amadan.net/oficina/equipo/internal/idtest TestDoorRemembersOficinaID
receipt: slow test 49.44s amadan.net/oficina/equipo/cmd/equipo-runner TestReleaseRunnerHasNoFakeWorker
receipt: slow test 46.3s amadan.net/oficina/equipo/internal/idtest TestDoorNeverJudgesANativeSession
receipt: slow test 46.3s amadan.net/oficina/equipo/internal/idtest TestDoorStepUpIsLocal
receipt: slow test 46.3s amadan.net/oficina/equipo/internal/idtest TestDoorOficinaSettingsUnreadableIsNoLoop
rastrillo: budget test: go test failed
exit status 1
+ go test -tags testbuild -timeout 15m -v -run '^TestMeteredRaceAdmitsExactlyOne$' -count=1 ./internal/runner/metered (retry, once)
##############################################################################
FLAKE ./internal/runner/metered:TestMeteredRaceAdmitsExactlyOne rest 10659d1f3c85c08da49e049653fb8f61440810a5 0.21s 26.41
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
machine: 32 CPUs, load 26.41, cpu waiting 11.72%, memory waiting 0.00%, io waiting 0.08%
--- 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.258s 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.422s amadan.net/oficina/equipo/internal/headless
receipt: slow test 38.88s amadan.net/oficina/equipo/internal/headless TestBrowserDraftIsTheMessage
receipt: slow test 14.69s amadan.net/oficina/equipo/internal/headless TestBrowserDraftStreamsFormatted
receipt: slow test 10.41s amadan.net/oficina/equipo/internal/headless TestBrowserChat
receipt: slow test 7.31s amadan.net/oficina/equipo/internal/headless TestBrowserComposer
receipt: slow test 6.25s amadan.net/oficina/equipo/internal/headless TestBrowserChatSendStaysOnPage
machine: 32 CPUs, load 79.98, cpu waiting 45.10%, memory waiting 0.00%, io waiting 0.43%
--- 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 1m34.645s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m32.817s amadan.net/oficina/equipo/internal/headless
receipt: slow test 27.9s amadan.net/oficina/equipo/internal/headless TestBrowserRailFollowsWork
receipt: slow test 23s amadan.net/oficina/equipo/internal/headless TestBrowserTaskThread
receipt: slow test 13.2s amadan.net/oficina/equipo/internal/headless TestBrowserReceiptFollowsReview
receipt: slow test 10.55s amadan.net/oficina/equipo/internal/headless TestBrowserTaskCard
receipt: slow test 9.56s amadan.net/oficina/equipo/internal/headless TestBrowserAskAfterMerge
machine: 32 CPUs, load 82.61, cpu waiting 44.59%, memory waiting 0.00%, io waiting 0.36%
--- 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.97s 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 1m52.384s amadan.net/oficina/equipo/internal/headless
receipt: slow test 13.89s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsConversation
receipt: slow test 13.59s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsAddPage
receipt: slow test 12.7s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsAdd
receipt: slow test 11.33s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsMeteredLimitRequired
receipt: slow test 11.29s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsSignInEmail
machine: 32 CPUs, load 66.64, cpu waiting 34.42%, 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
--- FAIL amadan.net/oficina/equipo/internal/headless TestBrowserCopyContinue
rastrillo: budget test: go test failed
=== RUN TestBrowserCopyContinue
time=2026-11-27T00:07:31.183Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-27T00:07:31.183Z level=INFO msg="startup phase done" phase=state_lock took=375µs
time=2026-11-27T00:07:31.183Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-27T00:07:31.184Z level=INFO msg="startup phase done" phase=claim_roots took=450µs
time=2026-11-27T00:07:31.185Z level=INFO msg="startup phase" phase=sweep
time=2026-11-27T00:07:31.265Z level=INFO msg="startup phase done" phase=sweep took=80.907ms
time=2026-11-27T00:07:31.269Z level=INFO msg="startup phase" phase=credentials
time=2026-11-27T00:07:31.269Z level=INFO msg="startup phase done" phase=credentials took=218µs
time=2026-11-27T00:07:31.269Z level=INFO msg="startup phase" phase=open_state
time=2026-11-27T00:07:31.346Z level=INFO msg="startup phase done" phase=open_state took=77.081ms
time=2026-11-27T00:07:31.347Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-27T00:07:31.354Z level=INFO msg=connecting host=127.0.0.1:44031 protocol=32
time=2026-11-27T00:07:31.356Z level=INFO msg=connected host=127.0.0.1:44031 took=1.509ms
time=2026-11-27T00:07:31.356Z level=INFO msg="capabilities gathering"
time=2026-11-27T00:07:31.357Z level=INFO msg="capabilities gathered" took=1.05ms tags=linux,claude,go
time=2026-11-27T00:07:31.360Z level=INFO msg="hello sent" protocol=32
time=2026-11-27T00:07:31.363Z level=INFO msg=welcome protocol=32 role=primary generation=1
browser_copy_test.go:90: waiting for !document.querySelector('[data-copy-continue]'): context deadline exceeded (last evaluation: context deadline exceeded)
--- FAIL: TestBrowserCopyContinue (6.43s)
--- FAIL amadan.net/oficina/equipo/internal/headless (package output)
FAIL
rastrillo-budget/v1 ran 1m34.576s
FAIL amadan.net/oficina/equipo/internal/headless 94.784s
receipt: test step 1m36.023s 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 1m34.576s amadan.net/oficina/equipo/internal/headless
receipt: slow test 15s amadan.net/oficina/equipo/internal/headless TestBrowserThinkingAndCards
receipt: slow test 11.13s amadan.net/oficina/equipo/internal/headless TestBrowserWaitingTurns
receipt: slow test 10.96s amadan.net/oficina/equipo/internal/headless TestBrowserStalePageReloads
receipt: slow test 9.49s amadan.net/oficina/equipo/internal/headless TestBrowserMoveIn
receipt: slow test 7.81s amadan.net/oficina/equipo/internal/headless TestBrowserEmptyExplore
exit status 1
+ go test -tags browser,testbuild -timeout 15m -run '^(TestBrowserAskAfterMerge|TestBrowserChat|TestBrowserChatSendStaysOnPage|TestBrowserComposer|TestBrowserComposerDock|TestBrowserComposerFocus|TestBrowserComposerReconcile|TestBrowserConnectionsAdd|TestBrowserConnectionsAddPage|TestBrowserConnectionsConversation|TestBrowserConnectionsCopyLink|TestBrowserConnectionsEndedNote|TestBrowserConnectionsMeteredLimitRequired|TestBrowserConnectionsOpenCodeGoLimitRequired|TestBrowserConnectionsSignIn|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$' -v -run '^TestBrowserCopyContinue$' -count=1 ./internal/headless (retry, once)
##############################################################################
FLAKE ./internal/headless:TestBrowserCopyContinue browser-headless-rest 10659d1f3c85c08da49e049653fb8f61440810a5 6.43s 78.88
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
machine: 32 CPUs, load 74.24, cpu waiting 42.38%, memory waiting 0.00%, io waiting 0.33%
--- 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.301s 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.536s amadan.net/oficina/equipo/internal/equipo
receipt: slow test 1.81s amadan.net/oficina/equipo/internal/equipo TestBrowserPreviewPassExchange
receipt: slow test 720ms 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 10.648s, over the 10s the default allows; reported only, timing fails on CI
receipt: test step 12.06s 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 10.648s amadan.net/oficina/equipo/internal/idtest
receipt: slow test 8.43s amadan.net/oficina/equipo/internal/idtest TestBrowserSmartDoor
receipt: slow test 2.21s 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.553s 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.101s amadan.net/oficina/equipo/internal/plan3test
receipt: slow test 2.1s 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
receipt: test step 3m38.453s 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 3m36.829s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 23.12s amadan.net/oficina/equipo/internal/thintest TestBrowserAccessRequest
receipt: slow test 14.39s amadan.net/oficina/equipo/internal/thintest TestBrowserSettingsTeams
receipt: slow test 12.04s amadan.net/oficina/equipo/internal/thintest TestBrowserThinkingCycles
receipt: slow test 10.66s amadan.net/oficina/equipo/internal/thintest TestBrowserPlacementQuestionAndPending
receipt: slow test 8.74s amadan.net/oficina/equipo/internal/thintest TestBrowserRhythm
machine: 32 CPUs, load 11.19, cpu waiting 4.46%, memory waiting 0.00%, io waiting 0.02%
--- 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.73s
ok ./internal/headless TestHeadlessConnections/C4_claude_sign_in 1.14s
ok ./internal/headless TestHeadlessConnections/C5_engineering_failover 9.04s
ok ./internal/headless TestHeadlessConnections/C5_engineering_to_codex 8.57s
ok ./internal/headless TestHeadlessConnections/C5_engineering_waits 27.36s
+ 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 (63s)
ok ./internal/headless TestHeadlessConnections/C5_review_auth 21.27s
ok ./internal/headless TestHeadlessConnections/C5_review_failover 11.38s
ok ./internal/headless TestHeadlessConnections/C5_review_on_codex 10.30s
ok ./internal/headless TestHeadlessConnections/C5_review_other_family_first 17.65s
+ go test -tags testbuild -timeout 15m -v -run '^TestMixedVersions$' ./internal/headless (21s)
ok ./internal/headless TestMixedVersions 18.54s
+ go test -tags testbuild -timeout 15m -v -run '^TestCheckSandboxDeniedPathsTampering$' ./internal/runner/checks (2s)
ok ./internal/runner/checks TestCheckSandboxDeniedPathsTampering 0.87s
+ go test -tags testbuild -timeout 15m -v -run '^TestRunnerCancelAndSupersede$' ./internal/runner/thin (2s)
ok ./internal/runner/thin TestRunnerCancelAndSupersede 0.06s
quarantine: 0 flaked (passed on the retry), 0 failed
machine: 32 CPUs, load 80.37, cpu waiting 42.09%, memory waiting 0.00%, io waiting 0.63%
--- 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.299s 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.949s amadan.net/oficina/equipo/internal/runner/checks
receipt: slow package 212ms amadan.net/oficina/equipo/internal/runner/provider/claude
receipt: slow package 64ms amadan.net/oficina/equipo/internal/runner/provider/codex
receipt: slow package 3ms amadan.net/oficina/equipo/internal/runner/provider
receipt: slow package 2ms amadan.net/oficina/equipo/internal/runner/provider/pi
receipt: slow test 5.63s amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPathsGoFixture
receipt: slow test 1.69s amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPaths
receipt: slow test 470ms amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPathsCache
receipt: slow test 210ms amadan.net/oficina/equipo/internal/runner/provider/claude TestDirectJournalAdapterBarrier
receipt: slow test 120ms 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.479s 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.143s amadan.net/oficina/equipo/internal/runner/containment
receipt: slow test 290ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceReadOnlyScratch
receipt: slow test 230ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceRecoveryUnavailableProof
receipt: slow test 130ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceDirectPolicyAdmission
receipt: slow test 120ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceRecoveryCleansScratch
receipt: slow test 110ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceReapsOrphans
machine: 32 CPUs, load 28.17, cpu waiting 11.63%, memory waiting 0.00%, io waiting 1.36%
--- 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.0%, load 30.41
shard 25: make runner-dead-references lanes-check build vet fmt-check spacing budget migration-check
python3 scripts/runner-dead-references.py
reference scan: 2913 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.620s
machine: 32 CPUs, load 82.15, cpu waiting 44.95%, memory waiting 0.00%, io waiting 0.48%
--- 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.0%, load 30.41
shard 26: make staticcheck
go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 -tags browser,perf,testbuild ./...
machine: 32 CPUs, load 67.29, cpu waiting 36.04%, 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.0%, load 30.41
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 47.11, cpu waiting 23.93%, memory waiting 0.00%, io waiting 0.97%
--- 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.0%, load 30.41
shard 28: make gitleaks
[90m12:07AM[0m [32mINF[0m [1mUnknown SCM platform. Use --platform to include links in findings.[0m [36mhost=[0mamadan.net
[90m12:07AM[0m [32mINF[0m [1m1222 commits scanned.[0m
[90m12:07AM[0m [32mINF[0m [1mscanned ~67710628 bytes (67.71 MB) in 24.3s[0m
[90m12:07AM[0m [32mINF[0m [1mno leaks found[0m
machine: 32 CPUs, load 67.29, cpu waiting 36.04%, memory waiting 0.00%, io waiting 0.74%
=== perf ===
go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -no-time -require TestPerfScreens,TestPerfBoot -tags perf -count=1 -p 1 -parallel 1 -run '^TestPerf' ./...
perf: GET /: median 1.037ms, worst 1.115ms, budget 150ms
perf: GET /api/runner/protocol: median 76µs, worst 116µs, budget 150ms
perf: GET /api/v1/account-setups/{id}: median 580µs, worst 651µs, budget 150ms
perf: GET /api/v1/accounts: median 419µs, worst 441µs, budget 150ms
perf: GET /api/v1/auth/devices: median 449µs, worst 534µs, budget 150ms
perf: GET /api/v1/budgets: median 483µs, worst 537µs, budget 150ms
perf: GET /api/v1/capabilities: median 253µs, worst 290µs, budget 150ms
perf: GET /api/v1/cards/{id}: median 1.208ms, worst 1.252ms, budget 150ms
perf: GET /api/v1/connections: median 558µs, worst 604µs, budget 150ms
perf: GET /api/v1/connections/{id}: median 515µs, worst 552µs, budget 150ms
perf: GET /api/v1/conversation: median 904µs, worst 1.019ms, budget 150ms
perf: GET /api/v1/conversation/cards: median 1.415ms, worst 1.492ms, budget 150ms
perf: GET /api/v1/coordinator: median 1.781ms, worst 1.821ms, budget 150ms
perf: GET /api/v1/invites/{id}: median 457µs, worst 537µs, budget 150ms
perf: GET /api/v1/journey: median 8.561ms, worst 11.316ms, budget 150ms
perf: GET /api/v1/me: median 483µs, worst 573µs, budget 150ms
perf: GET /api/v1/me/settings: median 554µs, worst 635µs, budget 150ms
perf: GET /api/v1/needs-you: median 8.265ms, worst 8.472ms, budget 150ms
perf: GET /api/v1/notifications: median 1.565ms, worst 1.649ms, budget 150ms
perf: GET /api/v1/onboarding: median 381µs, worst 418µs, budget 150ms
perf: GET /api/v1/people: median 423µs, worst 465µs, budget 150ms
perf: GET /api/v1/playbooks: median 579µs, worst 609µs, budget 150ms
perf: GET /api/v1/playbooks/{id}: median 518µs, worst 543µs, budget 150ms
perf: GET /api/v1/playbooks/{id}/template-diff: median 805µs, worst 897µs, budget 150ms
perf: GET /api/v1/preferences: median 729µs, worst 781µs, budget 150ms
perf: GET /api/v1/projects/{id}: median 441µs, worst 475µs, budget 150ms
perf: GET /api/v1/projects/{id}/settings: median 557µs, worst 601µs, budget 150ms
perf: GET /api/v1/roster: median 446µs, worst 462µs, budget 150ms
perf: GET /api/v1/runners/{id}: median 425µs, worst 447µs, budget 150ms
perf: GET /api/v1/specialists: median 7.827ms, worst 8.09ms, budget 150ms
perf: GET /api/v1/specialists/{id}: median 7.789ms, worst 7.834ms, budget 150ms
perf: GET /api/v1/specialists/{id}/template-diff: median 783µs, worst 847µs, budget 150ms
perf: GET /api/v1/tasks/{id}/plan: median 1.097ms, worst 1.116ms, budget 150ms
perf: GET /api/v1/tasks/{id}/thread: median 677µs, worst 744µs, budget 150ms
perf: GET /api/v1/teams: median 398µs, worst 446µs, budget 150ms
perf: GET /api/v1/templates: median 574µs, worst 610µs, budget 150ms
perf: GET /api/v1/templates/{id}: median 426µs, worst 450µs, budget 150ms
perf: GET /auth/callback: median 86µs, worst 118µs, budget 150ms
perf: GET /auth/devices/{id}: median 3.689ms, worst 3.745ms, budget 150ms
perf: GET /auth/verify: median 75µs, worst 95µs, budget 150ms
perf: GET /connections: median 4.093ms, worst 4.213ms, budget 150ms
perf: GET /conversation: median 8.01ms, worst 8.157ms, budget 150ms
perf: GET /conversation/connections: median 239µs, worst 268µs, budget 150ms
perf: GET /conversation/notebook: median 232µs, worst 272µs, budget 150ms
perf: GET /conversation/settings: median 4.327ms, worst 4.602ms, budget 150ms
perf: GET /conversation/settings/autonomy: median 4.47ms, worst 4.524ms, budget 150ms
perf: GET /conversation/settings/connections: median 6.773ms, worst 6.841ms, budget 150ms
perf: GET /conversation/settings/connections/add: median 6.922ms, worst 6.979ms, budget 150ms
perf: GET /conversation/settings/copy: median 4.425ms, worst 4.546ms, budget 150ms
perf: GET /conversation/settings/housekeeping: median 4.424ms, worst 4.564ms, budget 150ms
perf: GET /conversation/settings/machines: median 4.706ms, worst 4.785ms, budget 150ms
perf: GET /conversation/settings/machines/add: median 4.694ms, worst 4.797ms, budget 150ms
perf: GET /conversation/settings/notebook: median 3.73ms, worst 3.809ms, budget 150ms
perf: GET /conversation/settings/thinking: median 4.415ms, worst 6.731ms, budget 150ms
perf: GET /housekeeping: median 4.175ms, worst 4.284ms, budget 150ms
perf: GET /invites/new: median 584µs, worst 609µs, budget 150ms
perf: GET /invites/{id}: median 626µs, worst 641µs, budget 150ms
perf: GET /jobs: median 3.731ms, worst 3.82ms, budget 150ms
perf: GET /jobs/{id}: median 4.928ms, worst 5.053ms, budget 150ms
perf: GET /journey: median 10.39ms, worst 10.544ms, budget 150ms
perf: GET /nav/rail: median 3.251ms, worst 3.365ms, budget 150ms
perf: GET /needs-you: median 10.045ms, worst 10.233ms, budget 150ms
perf: GET /onboarding: median 4.356ms, worst 4.621ms, budget 150ms
perf: GET /people: median 3.947ms, worst 5.633ms, budget 150ms
perf: GET /playbook-suggestions/{suggestion}: median 4.844ms, worst 5.003ms, budget 150ms
perf: GET /playbooks: median 4.378ms, worst 4.467ms, budget 150ms
perf: GET /playbooks/new: median 4.574ms, worst 4.706ms, budget 150ms
perf: GET /playbooks/{id}: median 4.947ms, worst 5.086ms, budget 150ms
perf: GET /playbooks/{id}/edit: median 4.918ms, worst 4.966ms, budget 150ms
perf: GET /playbooks/{id}/template-diff: median 4.171ms, worst 4.29ms, budget 150ms
perf: GET /preferences: median 4.518ms, worst 4.647ms, budget 150ms
perf: GET /preferences/sources/{source}: median 4.335ms, worst 4.426ms, budget 150ms
perf: GET /projects: median 6.09ms, worst 6.206ms, budget 150ms
perf: GET /projects/accounts: median 3.999ms, worst 4.207ms, budget 150ms
perf: GET /projects/new: median 4.212ms, worst 6.038ms, budget 150ms
perf: GET /projects/{id}: median 10.656ms, worst 10.791ms, budget 150ms
perf: GET /projects/{id}/edit: median 4.018ms, worst 4.117ms, budget 150ms
perf: GET /runners/enrol: median 4.686ms, worst 4.732ms, budget 150ms
perf: GET /settings: median 3.759ms, worst 3.846ms, budget 150ms
perf: GET /settings/coordinator: median 5.671ms, worst 5.882ms, budget 150ms
perf: GET /settings/devices: median 3.621ms, worst 3.692ms, budget 150ms
perf: GET /settings/recovery: median 3.735ms, worst 3.88ms, budget 150ms
perf: GET /settings/recovery/release: median 3.73ms, worst 3.814ms, budget 150ms
perf: GET /settings/thinking: median 231µs, worst 258µs, budget 150ms
perf: GET /signed-out: median 248µs, worst 261µs, budget 150ms
perf: GET /signin: median 279µs, worst 291µs, budget 150ms
perf: GET /specialists/new: median 3.683ms, worst 3.781ms, budget 150ms
perf: GET /specialists/{key}: median 11.238ms, worst 14.84ms, budget 150ms
perf: GET /specialists/{key}/edit: median 3.975ms, worst 4.264ms, budget 150ms
perf: GET /specialists/{key}/template-diff: median 4.048ms, worst 4.092ms, budget 150ms
perf: GET /tasks: median 5.97ms, worst 6.083ms, budget 150ms
perf: GET /tasks/new: median 3.564ms, worst 3.691ms, budget 150ms
perf: GET /tasks/{id}: median 5.728ms, worst 5.883ms, budget 150ms
perf: GET /tasks/{id}/merge: median 5.085ms, worst 5.154ms, budget 150ms
perf: GET /tasks/{id}/move: median 5.022ms, worst 5.076ms, budget 150ms
perf: GET /tasks/{id}/plan: median 5.956ms, worst 6.024ms, budget 150ms
perf: GET /tasks/{id}/preview: median 1.565ms, worst 1.661ms, budget 150ms
perf: GET /tasks/{id}/questions/{question}: median 5.614ms, worst 5.775ms, budget 150ms
perf: GET /tasks/{id}/rendered-change: median 5.21ms, worst 5.259ms, budget 150ms
perf: GET /tasks/{id}/rendered-change/{hash}.png: median 4.636ms, worst 4.794ms, budget 150ms
perf: GET /tasks/{id}/thread: median 8.107ms, worst 8.298ms, budget 150ms
perf: GET /team/{specialist}: median 4.776ms, worst 4.917ms, budget 150ms
perf: GET /teams: median 10.17ms, worst 10.284ms, budget 150ms
perf: GET /templates: median 3.786ms, worst 3.909ms, budget 150ms
perf: GET /usage: median 4.613ms, worst 4.734ms, budget 150ms
perf: GET /work: median 3.449ms, worst 3.58ms, budget 150ms
perf: GET /auth/devices/{id}: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /connections: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /conversation: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /conversation/settings: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /conversation/settings/autonomy: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /conversation/settings/connections: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /conversation/settings/connections/add: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /conversation/settings/copy: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /conversation/settings/housekeeping: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /conversation/settings/machines: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /conversation/settings/machines/add: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /conversation/settings/notebook: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /conversation/settings/thinking: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /housekeeping: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /invites/new: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /invites/{id}: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /jobs: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /jobs/{id}: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /journey: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /nav/rail: 0 bytes of framework CSS and JS, gzipped; 16000-byte budget
perf: GET /needs-you: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /onboarding: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /people: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /playbook-suggestions/{suggestion}: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /playbooks: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /playbooks/new: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /playbooks/{id}: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /playbooks/{id}/edit: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /playbooks/{id}/template-diff: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /preferences: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /preferences/sources/{source}: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /projects: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /projects/accounts: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /projects/new: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /projects/{id}: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /projects/{id}/edit: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /runners/enrol: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /settings: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /settings/coordinator: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /settings/devices: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /settings/recovery: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /settings/recovery/release: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /signed-out: 30270 bytes of framework CSS and JS, gzipped; 40000-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /specialists/new: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /specialists/{key}: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /specialists/{key}/edit: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /specialists/{key}/template-diff: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /tasks: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /tasks/new: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /tasks/{id}: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /tasks/{id}/merge: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /tasks/{id}/move: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /tasks/{id}/plan: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /tasks/{id}/preview: 25954 bytes of framework CSS and JS, gzipped; 40000-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /tasks/{id}/questions/{question}: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /tasks/{id}/rendered-change: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /tasks/{id}/thread: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /team/{specialist}: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /teams: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /templates: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /usage: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: GET /work: 57416 bytes of framework CSS and JS, gzipped; 60600-byte budget; it links the whole tokens.css: add Assets: assets to ui.PagesConfig (PagesConfig.Assets) in render.go, and in the layout use {{path $ pageStylesheet}} in place of static/tokens.css and replace the busy.js, live.js, light.js and anchor.js tags and the neededScripts line (or the select.js, calendar.js and datetime.js tags) with {{range pageScripts}}, keeping rastrillo.js and shell.js
perf: cold boot: median 158ms of [156.493386ms 157.961953ms 159.055283ms], budget 500ms
receipt: test step 48.613s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 88 without tests, 0 failed
receipt: slow package 10.277s amadan.net/oficina/equipo/internal/equipotest
receipt: slow package 1ms amadan.net/oficina/equipo/internal/stagingtest
receipt: slow package 0s amadan.net/oficina/equipo/cmd/equipo
receipt: slow package 0s amadan.net/oficina/equipo/cmd/equipo-runner
receipt: slow package 0s amadan.net/oficina/equipo/cmd/equipo-tool-proxy
receipt: slow test 9.75s amadan.net/oficina/equipo/internal/equipotest TestPerfScreens
receipt: slow test 520ms amadan.net/oficina/equipo/internal/equipotest TestPerfBoot
=== cache ===
ci-box: build cache /home/ci/work/repos/oficina__equipo/cache/go-build: 4.00 GiB in 26084 files
ci-box: module cache /home/ci/work/repos/oficina__equipo/cache/go-mod: 1.15 GiB in 40997 files
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index e5ae5dc7..c676c95b 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 work, check-db copy and notification actions; measured 23297/6175 source/test lines. |
| +size internal/wire 7448 - Protocol 31 facts, protocol 32 unfinished work, task evidence, CI units and bound notification inputs; measured 7448/3297 source/test lines. |
| 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, paused work, Assistant, merge authority, check-db inventory and direct-card contracts; measured 940/12024 source/test lines. |
| time internal/runner/forge 20s Plan 3 CI repair measured 10.527s for the full package (controller CI 10.407s). |
| time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full package (controller CI 10.709s); |
| @@ -56,7 +56,7 @@ perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for device |
| perf GET /api/v1/assistant/snapshot skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen. |
| perf GET /api/v1/assistant/messages skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen. |
| perf GET /api/v1/assistant/events skip Assistant event stream (Server-Sent Events), bearer-only and long-lived; not a screen. |
| -size internal/equipo/chat 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 35801 10650 File facts, previews, merge authority, unfinished work, CI feedback, notification receipts and direct card reads; measured 35801/10650 source/test lines. |
| perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}. |
| perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}. |
| perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections. |
| @@ -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..2e3b16bc 100644 |
| --- a/docs/api/equipo-v1.md |
| +++ b/docs/api/equipo-v1.md |
| @@ -223,7 +223,7 @@ Project items are ordered with your stars first, followed by recent team activit |
| For a plain conversation, the server resolves exact trusted names: owner-set team names, titles set by an owner, and repository keys (`amadan.net/owner/name`, also accepted as `owner/name`). When no owner-set title exists, the repository basename also matches. A unique trusted match takes priority over a learned personal name. A personal name can resolve a name with no trusted match or with several trusted matches. An unknown or ambiguous name opens a placement card only in a person turn whose request asks for work in a named project. A person turn responds to a person's message. A move-in turn is the Coordinator's initial setup work. Discovery searches, move-in turns and explore turns do not open that card. |
| -The card offers up to five reachable projects and, when more are available, "Choose another project." Starred projects come first. Name similarity and recent activity order the remaining choices. Each option is at most 80 bytes. Answer through `POST /api/v1/cards/{id}/answer`. The server marks the typed placement card with `placement_by_name: true`, including after a remember-name opt-out. Ordinary questions without options do not carry this marker. Choosing another project keeps the card open, increments its revision and replaces the options with a text field. That response has the updated `card`; its `message` and `turn` are empty, and no turn starts. Submit the new revision and a project name or repository as `choice`. An unresolved or ambiguous name returns 422 `invalid_input`, leaving the card open. An open typed placement card can also take a composer message in that same conversation as its answer, including device `POST /api/v1/messages`. The whole message must resolve to one available project using the resolver above, or be that name in one of these short phrases: "It should go in <name>", "Put it in <name>" or "Use <name>", optionally ending with " please". Matching ignores case. A valid answer closes the card and resumes the original request, keeping the person's complete words in history. A composer message passes through an open card unless it clearly names one available project as described above. Messages with `project_id` or attachments always follow normal send behavior. Cards that are set aside, answered or closed never consume composer messages. An open card never causes a composer message to return 422. Retries preserve the original message and outcome. Other conversations are unaffected. |
| +The card offers up to five reachable projects and, when more are available, "Choose another project." Starred projects come first. Name similarity and recent activity order the remaining choices. Each option is at most 80 bytes. Answer through `POST /api/v1/cards/{id}/answer`. The server marks the typed placement card with `placement_by_name: true`, including after a remember-name opt-out. Ordinary questions without options do not carry this marker. Every placement question, with options or by name, also carries `placement_question: true`; notifications never offer an action on it, so it opens in the app. Choosing another project keeps the card open, increments its revision and replaces the options with a text field. That response has the updated `card`; its `message` and `turn` are empty, and no turn starts. Submit the new revision and a project name or repository as `choice`. An unresolved or ambiguous name returns 422 `invalid_input`, leaving the card open. An open typed placement card can also take a composer message in that same conversation as its answer, including device `POST /api/v1/messages`. The whole message must resolve to one available project using the resolver above, or be that name in one of these short phrases: "It should go in <name>", "Put it in <name>" or "Use <name>", optionally ending with " please". Matching ignores case. A valid answer closes the card and resumes the original request, keeping the person's complete words in history. A composer message passes through an open card unless it clearly names one available project as described above. Messages with `project_id` or attachments always follow normal send behavior. Cards that are set aside, answered or closed never consume composer messages. An open card never causes a composer message to return 422. Retries preserve the original message and outcome. Other conversations are unaffected. |
| A named placement card includes optional `remember_name`, the suggested private name. The web card shows a checked "Remember '<name>' for this project" box and an editable 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. The web sends the name explicitly when the box is checked. Clients without the control do not learn a name on a plain tap. The model may suggest the prefilled name, but only the person's final project answer with explicit `remember_name` learns it. Choosing another project preserves an edited suggestion or removes it after an opt-out. Learning waits for the later valid answer, which must also send the name explicitly. Composer answers skip learning. Names are trimmed and stored in lowercase for that person only. They must contain at least three Unicode characters, be at most 120 bytes, be valid UTF-8, and contain no newline or NUL. Stopwords and feature phrases are not learned. An ineligible name skips learning without refusing the project choice. Capitalisation and sentence shape do not determine learning. A repository key outside the allowlist retains the existing access-request flow. |
| @@ -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..a8cd7a2c 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,12 @@ |
| "Card": { |
| "type": "object", |
| "properties": { |
| + "placement_by_name": { |
| + "type": "boolean" |
| + }, |
| + "placement_question": { |
| + "type": "boolean" |
| + }, |
| "remember_name": { |
| "type": "string" |
| }, |
| @@ -18987,9 +19103,6 @@ |
| }, |
| "aside": { |
| "type": "boolean" |
| - }, |
| - "placement_by_name": { |
| - "type": "boolean" |
| } |
| }, |
| "required": [ |
| @@ -21121,6 +21234,10 @@ |
| "ProjectList": { |
| "type": "object", |
| "properties": { |
| + "cursor": { |
| + "type": "integer", |
| + "format": "int64" |
| + }, |
| "connections": { |
| "type": "array", |
| "items": { |
| @@ -21153,10 +21270,6 @@ |
| }, |
| "home": { |
| "type": "string" |
| - }, |
| - "cursor": { |
| - "type": "integer", |
| - "format": "int64" |
| } |
| }, |
| "required": [ |
| @@ -22226,8 +22339,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 +22456,9 @@ |
| ], |
| "format": "int64" |
| }, |
| + "hosted": { |
| + "$ref": "#/components/schemas/StepHosted" |
| + }, |
| "askable": { |
| "type": "boolean" |
| }, |
| @@ -22423,10 +22540,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 +24010,13 @@ |
| "RegisterPush": { |
| "type": "object", |
| "properties": { |
| + "actions_version": { |
| + "type": "integer", |
| + "format": "int64" |
| + }, |
| + "binding_id": { |
| + "type": "string" |
| + }, |
| "token": { |
| "type": "string" |
| }, |
| @@ -24397,6 +24517,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 +24727,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| new file mode 100644 |
| index 00000000..b0dcfb8f |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-27-notification-actions.md |
| @@ -0,0 +1,194 @@ |
| +# Notification actions, slice 8 |
| + |
| +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. |
| + |
| +## Flow and privacy |
| + |
| +Use ordinary UserNotifications categories on iPhone and Mac, with the |
| +existing app screens after unlock. No notification content or service |
| +extension, new bundle ID or signing capability is needed. |
| + |
| +Keep today's alert title and clipped question/task preview unchanged. |
| +APNs gains versioned routing and binding data only: a notification ID, |
| +registration binding ID, card kind/ID/revision, or task ID/revision and |
| +failed step ID/revision/attempt. It carries no credentials, email address, |
| +new question text, option text, checks logs, Review summary or preview URL. |
| +The registration binding is a random non-secret identifier stored for the |
| +current origin/person/device session and rotated on account changes. |
| +It prevents a delayed notification being acted on using another account. |
| +The client chooses the API origin from its authenticated session, never |
| +from a payload URL. A binding is routing data, never authority. |
| + |
| +**Privacy tradeoff for approval:** the mockup shows arbitrary question |
| +options on the lock screen. Those are additional private, model-written |
| +text that today's push does not send. This slice instead offers direct |
| +text entry only for an optionless question whose complete question fits |
| +today's preview. An option question, or a clipped question, opens the |
| +bound question card after unlock, with every option visible. There is no |
| +generic Yes/No mapping, numbered choice guessing or free-text answer to a |
| +card that only accepts its listed options. Arbitrary option buttons in the |
| +notification would require a separate privacy decision and dynamic |
| +notification UI work. |
| + |
| +## Categories and action titles |
| + |
| +Register fixed versioned categories at launch, while keeping `needs_you`. |
| +All response actions below use `.authenticationRequired` **and** |
| +`.foreground`: unlock, then open the app to handle the response and show |
| +any failure. Free-text entry is supplied by |
| +`UNTextInputNotificationAction`; its submitted answer is handled without a |
| +second Send tap. Foreground handling also makes a 409 reliably presentable, |
| +rather than hoping a background handler can open the app later. |
| + |
| +| Category | Actions | What the tap does | |
| +| --- | --- | --- | |
| +| `equipo.question.text.v1` | Answer (text input), Open the task when task-bound | Submit the typed answer to the exact card revision; display the question/conversation and result. | |
| +| `equipo.question.choices.v1` | Answer | Open the exact question after unlock; fetch and display its options, then the person's choice submits. | |
| +| `equipo.stopped.v1` | Try again, Open the task | Retry the named failed attempt only, using the existing creator and termination rules. | |
| +| `equipo.merge.v1` | Merge, Open the task | Load fresh facts and show the existing Merge confirmation. No write on the notification tap or on unlock. | |
| +| `needs_you` and unsupported kinds | Existing default tap | Open the card/task without submitting anything. | |
| + |
| +A dismiss gesture has no write semantics. Do not add Not now as a |
| +notification button: it could be confused with dismissing the notification |
| +rather than answering or setting aside a card. Access, placement, held, |
| +direction, policy and other unfamiliar cards retain open-only handling. |
| +Merge categories apply only to merge kinds the existing native helper |
| +fully understands and offers; they cannot expose an otherwise hidden merge. |
| + |
| +Apple documents [authenticationRequired](https://developer.apple.com/documentation/usernotifications/unnotificationactionoptions/authenticationrequired) |
| +as requiring unlock before delivery, and |
| +[foreground](https://developer.apple.com/documentation/usernotifications/unnotificationactionoptions/foreground) |
| +as opening the app for further interaction. Fixed categories and text input |
| +follow [actionable notification types](https://developer.apple.com/documentation/usernotifications/declaring-your-actionable-notification-types). |
| +Keep at most two actions per category so the primary action is available in |
| +the limited layouts too. |
| + |
| +## Server binding and retries |
| + |
| +The push is captured in the same transaction as the card/task change. |
| +Keep the sealed outbox, current-device checks, deduplication and 4 KiB |
| +payload bound. Unknown, incomplete or oversize action metadata falls back |
| +to today's open-only payload; it must not lose the underlying alert. |
| + |
| +Two existing API limitations need additive changes: |
| +`AnswerCard` checks revision but a repeated successful answer currently |
| +returns a conflict, and `RetryTask` currently reads no request body or |
| +revision. Add a notification-capable contract to these existing routes: |
| + |
| +- `POST /cards/{id}/answer`: retain exact `revision` and `choice`; accept |
| + an optional idempotency key. Question option choices remain model text |
| + with the existing generated-origin attribution. |
| +- `POST /tasks/{id}/retry`: accept an optional bound request with task |
| + revision, step ID/revision/attempt and idempotency key. Every supplied |
| + binding must match inside the write transaction before calling the same |
| + retry helper. Missing or partial bindings from the new notification |
| + dispatcher refuse the action; it never falls back to unbound retry. |
| + Existing callers without a body retain their current API behavior. |
| + |
| +A durable, indexed operation receipt records the key, request digest and |
| +result identifiers/attempt atomically with the action. Scope it to the |
| +authenticated person/device, route and target; identical retries return |
| +the original result, a changed body with the same key is |
| +`api.idempotency_conflict`. Recheck the active member/device before any |
| +receipt read. Store no duplicate answer text in receipts or audit logs. |
| +Retain receipts for seven days, prune in bounded batches; after pruning, |
| +the original card revision or step attempt still prevents repeating the |
| +effect. Add an additive migration and schema snapshot. |
| + |
| +Native persists the original key and exact request before POST in a |
| +bounded, protected pending-action journal, bound to origin, person and |
| +session generation. Credentials remain in the keychain. Duplicate delegate |
| +delivery and relaunch reuse that request; no automatic new key or rebinding |
| +to the latest revision. Clear completed/definitely refused entries and |
| +clear all entries on sign-out/account switch; expire pending sends after |
| +24 hours without replay. A new notification cannot be replaced by an |
| +earlier uncertain send. No background retry timer sends without the |
| +person's requested retry. |
| + |
| +All writes reuse current roster, ownership, visibility and task/card rules |
| +inside their transaction, with the real authenticated actor and existing |
| +audit semantics. A stale answer shows `api.card_stale` or |
| +`api.card_answered`; a changed retry binding shows `api.not_retryable`. |
| +On 409, open/refetch the relevant card or task and show those reviewed |
| +words. Never apply the old response to its replacement. Other errors use |
| +the existing offline, read/write failure and API copy mappings. |
| + |
| +## Merge facts and confirmation |
| + |
| +The notification's Merge action is navigation to a confirmation, not merge |
| +authorization. After unlock, fetch task detail and the bound card. Show |
| +candidate/branch, Checks status and reasons, Review status and the current |
| +candidate's Review summary, using slice 3's evidence selection. Link to |
| +Changed files and Preview through their existing screens. |
| + |
| +Require a distinct final Merge tap through `TaskDetailModel` and its |
| +existing server action. If the card revision/candidate moved, open the |
| +updated task with the reviewed changed words, without preselecting its new |
| +Merge decision. If facts cannot be read, show the read failure and no Merge |
| +button. A change while the confirmation is open invalidates the intent; |
| +the final server transaction still rechecks authority and current merge |
| +eligibility. Notification payload facts never authorize a merge. |
| + |
| +## Compatibility and copy |
| + |
| +Advertise `notification_actions_v1` through `GET /capabilities`. |
| +Only after that signal does a new app include the version and registration |
| +binding in `POST /push-registrations`; older servers use strict JSON |
| +decoding, so sending new fields speculatively is unsafe. The new server |
| +stores the opt-in per registration and sends actionable categories only |
| +there. Missing capability, old registration, old payload, unknown version, |
| +unknown action or malformed binding means open-only. Preserve existing |
| +`kind/card_id/task_id/turn_id` fields so older apps can still route an |
| +unexpected new payload safely. Document all additive fields and request |
| +bodies in OpenAPI and the API guide; no runner protocol change. |
| + |
| +No new product copy proposed: |
| + |
| +| Use | Existing key | Exact words | |
| +| --- | --- | --- | |
| +| Question action | `chat.card.answer` | Answer | |
| +| Text input submit | `composer.send` (native reviewed) | Send | |
| +| Text input placeholder | `conversation.placeholder` (native reviewed) | Message | |
| +| Retry action | `work.pause.try_again` | Try again | |
| +| Merge action | `chat.card.merge` | Merge | |
| +| Task navigation | `task.open` (native reviewed) | Open the task | |
| + |
| +Keep imported web strings byte-identical under parity. Reuse the existing |
| +Merge confirmation, facts and error copy; send any unforeseen new words |
| +to the controller before marking them reviewed. |
| + |
| +## Verification |
| + |
| +Test first, then break each guard and record the failing test: |
| + |
| +- Go/contracts: private-text-free, bounded payloads; category eligibility; |
| + registration opt-in and binding; strict old-client compatibility; |
| + snapshot revisions; question ownership/options; stale revisions and |
| + step attempts; creator/termination and current membership/device checks; |
| + concurrent identical retries, lost reply, changed-body key reuse and |
| + replay after receipt expiry. Confirm one answer/attempt/audit effect. |
| +- Native/fake server: category flags and identifiers; direct free-text and |
| + option-card routing; no partial/unknown payload writes; same key/body |
| + after relaunch; account switch/sign-out; 409 opens refreshed card with |
| + exact words; offline failure; Merge shows current-candidate evidence and |
| + cannot POST before the separate confirmation or after invalidation. |
| +- Simulator, narrowly: delivered fixture payloads, text entry, cold launch, |
| + option-card routing, Merge facts/confirmation, Dynamic Type and VoiceOver |
| + labels. Mac notification action delivery and navigation too. |
| +- **Physical device required:** real APNs on a locked iPhone; hidden |
| + previews; Face ID/passcode success and cancellation; submit before/after |
| + unlock; terminated-app delivery; background/offline/lost reply; system |
| + notification grouping and any mirrored Watch action. Simulator evidence |
| + cannot prove the unlock guarantee. These checks precede enabling the |
| + server capability in production. |
| + |
| +No local full gate. Before a narrow Go/Swift/build/simulator run, check load, |
| +swap and other heavy jobs; wait above load 20 or with two other heavy jobs. |
| +Use one job, at most four workers, and reuse/shut down the simulator. |
| +Linux hub CI runs the full server gates, contracts and schema checks; |
| +native-only checks follow the established Apple lane. Record mutations, |
| +device limitations and screenshots in the slice 8 controller report. |
| + |
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..5f063634 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-notification-actions.md |
| @@ -0,0 +1,215 @@ |
| +# 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. |
| + |
| +## First CI follow-up |
| + |
| +CI at `209cf741` passed the notification, card, contract and security tests, |
| +but failed four budget reasons longer than 200 bytes and the existing |
| +`TestBrowserRosterVisual` spacing assertion in all four appearances, including |
| +its retry. Budget reasons now retain the measured counts and a concise reason; |
| +`go test -p 4 ./internal/testci -run '^TestBudgetRecordsAreShort$' -count=1` |
| +passes (`budget-reasons.log`). The browser assertion is unchanged, with computed |
| +spacing diagnostics added. Main `a2619ce3` had green CI. No browser templates, |
| +CSS or scripts differ from main. The first local narrow browser invocation |
| +could not locate Chromium; the installed Playwright browser was then located, |
| +but load exceeded 20, so the next narrow run is left to hub CI. |
| + |
| +## Review fixes (Fable) |
| + |
| +Taken over from the Codex implementer's uncommitted worktree. The roster |
| +spacing change moved to its own branch, `fix/roster-visual-report-card` |
| +(`4836c9f2`); this branch's `roster_browser_test.go` is back to main's, so |
| +the diagnostic log added at `18cd2fcb` is gone too. |
| + |
| +- **Placement cards are open-only.** `cardView` sets `placement_question` |
| + on every placement question (options or by name; OpenAPI and API notes |
| + updated). `notificationIntent` returns open-only when `Placement` is set. |
| + Native decodes the field and, after the bound card read, opens any |
| + placement question instead of writing. `TestNotificationPlacementPushRuleIsOpenOnly` |
| + covers both states through the real card-event enqueue and `cardView`. |
| +- **Try again eligibility.** The intent is offered exactly when |
| + `retryReason` accepts the failed, terminated newest step, and never for |
| + a Merge or Publish step. The bound write still goes through |
| + `personRetry`. Enqueued through the real task push: Engineering and |
| + Checks failures are offered; Merge, non-owner, another step person and |
| + no runner are not. Failed Review and Publish steps raise no task alert |
| + (Review reads `NeedsReviewBlocked`; `task_fails` fires only on |
| + `NeedsRetry`, and progress ignores Publish), so their eligibility is |
| + read through `notificationIntent` directly: Review is offered, Publish is not. |
| +- **403 on registration.** When a registration with actions is refused 403, |
| + `PushRegistrar` re-reads `/capabilities` and, when actions are off, |
| + registers again without the action fields (once; no loop). |
| +- **App-side guard.** The dispatcher writes the journal and POSTs only |
| + while protected data is available and the app is active; otherwise it |
| + opens the card. The guard sits immediately before the journal save and |
| + before the POST, not at the start of the action: a `.foreground` |
| + response usually arrives while the app is still `.inactive`, and the |
| + card and capability reads are harmless. A restored journal entry skips |
| + the save, so the POST guard is tested separately. The inherited |
| + in-progress change was trimmed: a check in the 409 path dismissed by the |
| + card ID, not the notice, and the `answer()` placement check was |
| + unreachable (run re-reads the card first). |
| + |
| +Evidence: notification Go tests pass; `./internal/wire/...` and |
| +`plan3test -run 'Notification|Contract'` pass; Linux build, vet and |
| +staticcheck v0.7.0 on `chat` and `wire` are clean. Native: 22 notification |
| +tests in 10 suites pass; iOS Simulator app build succeeds (UIKit branch). |
| + |
| +Mutations, every one killed and restored: |
| + |
| +| Guard | Killed by | |
| +|---|---| |
| +| intent skips `Placement` | PlacementPushRuleIsOpenOnly/options, /by-name | |
| +| `cardView` sets `PlacementQuestion` | PlacementPushRuleIsOpenOnly/options, /by-name | |
| +| intent consults `retryReason` | RetryPushRuleRefusals/member, /other-step-person, /no-runner | |
| +| intent refuses Merge | RetryPushRuleRefusals/merge | |
| +| intent refuses Publish | RetryPushRuleRefusals/publish | |
| +| native placement refusal after read | wrongBindingDisabledCapabilityAndStaleCardNeverWrite | |
| +| native decodes `placement_question` | wrongBindingDisabledCapabilityAndStaleCardNeverWrite | |
| +| foreground guard before journal save | lockedOrInactiveBeforeOrAfterReadNeverJournalsOrPosts | |
| +| foreground guard before POST | restoredReplyNeverResendsWhileLockedOrInactive | |
| +| guard requires protected data | both foreground tests | |
| +| guard requires active | both foreground tests | |
| +| registrar 403 fallback | forbiddenActionsRefreshCapabilitiesAndRegisterOpenOnly | |
| + |
| +Not run: physical-device checks (above), browser tests (hub CI). The |
| +capability stays off by default. |
| + |
| +CI at `f49270cf` failed two shards: `TestBrowserRosterVisual` (this branch |
| +then had main's test; fixed by merging main `6616af91`) and the size budget |
| +(chat 35801/10650, wire 7448 lines; exemptions raised to the measured |
| +counts). Headless flakes in the same run passed on their retry. |
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/models.go b/internal/equipo/chat/models.go| index 3b0444a9..0fd04e0f 100644 |
| --- a/internal/equipo/chat/models.go |
| +++ b/internal/equipo/chat/models.go |
| @@ -11,7 +11,7 @@ import ( |
| ) |
| // Models are the tables this package owns, for the migration check. |
| -var Models = append([]any{&projectNameRecord{}, &cardVisibility{}, &cardThreadRecord{}, ©AttemptRecord{}, ©ReviewRecord{}, ©FeedbackRecord{}, &turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, ¬ebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &starRecord{}, &questionRecord{}, &connectionRecord{}, &usageRecord{}, &distinctRecord{}, &hkRecord{}, &hkFailureRecord{}, &hkSettingsRecord{}, &fileRecord{}, &fileDataRecord{}, &transferRecord{}, &mergePolicyRecord{}, &mergeAuditRecord{}, &specialistRecord{}, &grantRecord{}, &specialistAuditRecord{}, &researchSourceRecord{}, &researchAddressRecord{}, &researchPrefixRecord{}, &researchInventoryRecord{}, &researchRecord{}, &researchFetchRecord{}, &taskFileRecord{}, &taskFileDataRecord{}, &releaseRecord{}, &adviceRecord{}, &assistantHostRecord{}, &handoffRecord{}, &handoffTurnRecord{}, &handoffTaskRecord{}, &handoffActionRecord{}, &connectTurnRecord{}, &carriedRecord{}, &zoneRecord{}}, push.Models...) |
| +var Models = append([]any{¬ificationReceipt{}, &projectNameRecord{}, &cardVisibility{}, &cardThreadRecord{}, ©AttemptRecord{}, ©ReviewRecord{}, ©FeedbackRecord{}, &turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, ¬ebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &starRecord{}, &questionRecord{}, &connectionRecord{}, &usageRecord{}, &distinctRecord{}, &hkRecord{}, &hkFailureRecord{}, &hkSettingsRecord{}, &fileRecord{}, &fileDataRecord{}, &transferRecord{}, &mergePolicyRecord{}, &mergeAuditRecord{}, &specialistRecord{}, &grantRecord{}, &specialistAuditRecord{}, &researchSourceRecord{}, &researchAddressRecord{}, &researchPrefixRecord{}, &researchInventoryRecord{}, &researchRecord{}, &researchFetchRecord{}, &taskFileRecord{}, &taskFileDataRecord{}, &releaseRecord{}, &adviceRecord{}, &assistantHostRecord{}, &handoffRecord{}, &handoffTurnRecord{}, &handoffTaskRecord{}, &handoffActionRecord{}, &connectTurnRecord{}, &carriedRecord{}, &zoneRecord{}}, push.Models...) |
| type turnRecord struct { |
| CreateRepo string |
diff --git a/internal/equipo/chat/notification_actions.go b/internal/equipo/chat/notification_actions.go| new file mode 100644 |
| index 00000000..2eaca454 |
| --- /dev/null |
| +++ b/internal/equipo/chat/notification_actions.go |
| @@ -0,0 +1,134 @@ |
| +package chat |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "gorm.io/gorm" |
| +) |
| + |
| +// Notification actions remain off until the operator completes device checks. |
| +func (s *Store) SetNotificationActions(enabled bool) { s.notificationActions.Store(enabled) } |
| +func (s *Store) NotificationActions() bool { return s.notificationActions.Load() } |
| + |
| +type notificationReceipt struct { |
| + Person string `gorm:"primaryKey"` |
| + Credential string `gorm:"primaryKey"` |
| + Operation string `gorm:"primaryKey"` |
| + Target string `gorm:"primaryKey"` |
| + Key string `gorm:"primaryKey"` |
| + Digest string |
| + CardID string |
| + MessageID string |
| + TurnID string |
| + Attempt int64 |
| + ExpiresAt time.Time `gorm:"index:notification_receipt_expiry"` |
| +} |
| + |
| +func (notificationReceipt) TableName() string { return "chat_notification_receipts" } |
| + |
| +func (t *txn) actionReceipt(person, credential, operation, target, key string, input any) (*notificationReceipt, bool, error) { |
| + if !t.s.NotificationActions() || credential == "" { |
| + return nil, false, ErrForbidden |
| + } |
| + if !validKey(key) { |
| + return nil, false, ErrInvalid |
| + } |
| + if err := t.s.pushCurrent(t.db, person, credential); err != nil { |
| + return nil, false, ErrForbidden |
| + } |
| + raw, err := json.Marshal(input) |
| + if err != nil { |
| + return nil, false, err |
| + } |
| + digest := sha256.Sum256(raw) |
| + r := notificationReceipt{Person: person, Credential: credential, Operation: operation, Target: target, Key: key, Digest: hex.EncodeToString(digest[:]), ExpiresAt: t.now().Add(7 * 24 * time.Hour)} |
| + // A bounded batch, plus this exact expired key, avoids unbounded cleanup. |
| + if err = t.db.Exec("DELETE FROM chat_notification_receipts WHERE rowid IN (SELECT rowid FROM chat_notification_receipts WHERE expires_at <= ? LIMIT 100)", t.now()).Error; err != nil { |
| + return nil, false, err |
| + } |
| + query := t.db.Where("person = ? AND credential = ? AND operation = ? AND target = ? AND key = ?", person, credential, operation, target, key) |
| + if err = query.Where("expires_at <= ?", t.now()).Delete(¬ificationReceipt{}).Error; err != nil { |
| + return nil, false, err |
| + } |
| + var prior notificationReceipt |
| + err = t.db.Where("person = ? AND credential = ? AND operation = ? AND target = ? AND key = ?", person, credential, operation, target, key).Take(&prior).Error |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return &r, false, nil |
| + } |
| + if err != nil { |
| + return nil, false, err |
| + } |
| + if prior.Digest != r.Digest { |
| + return nil, false, ErrConflict |
| + } |
| + return &prior, true, nil |
| +} |
| + |
| +func (t *txn) receiptAnswer(r notificationReceipt) (out wire.Answered, err error) { |
| + var c cardRecord |
| + if err = t.db.Where("id = ? AND person = ?", r.CardID, r.Person).Take(&c).Error; err != nil { |
| + return out, err |
| + } |
| + if out.Card, err = t.cardView(c); err != nil { |
| + return out, err |
| + } |
| + if r.MessageID != "" { |
| + var m messageRecord |
| + if err = t.db.Where("id = ? AND person = ?", r.MessageID, r.Person).Take(&m).Error; err != nil { |
| + return out, err |
| + } |
| + out.Message = messageView(m) |
| + } |
| + if r.TurnID != "" { |
| + var turn turnRecord |
| + if err = t.db.Where("id = ? AND person = ?", r.TurnID, r.Person).Take(&turn).Error; err != nil { |
| + return out, err |
| + } |
| + out.Turn, err = t.turnView(turn) |
| + } |
| + return out, err |
| +} |
| + |
| +// RetryTaskBound retries exactly the failure seen in the notification. |
| +func (s *Store) RetryTaskBound(ctx context.Context, person, credential, id string, in wire.RetryTask) (attempt int64, err error) { |
| + if in.Revision <= 0 || in.StepRevision <= 0 || in.Attempt <= 0 || in.StepID == "" || in.IdempotencyKey == "" { |
| + return 0, ErrInvalid |
| + } |
| + err = s.tx(ctx, func(t *txn) error { |
| + if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| + return err |
| + } |
| + r, prior, err := t.actionReceipt(person, credential, "retry", id, in.IdempotencyKey, in) |
| + if err != nil { |
| + return err |
| + } |
| + if prior { |
| + attempt = r.Attempt |
| + return nil |
| + } |
| + k, err := t.loadTask(id) |
| + if err != nil { |
| + return err |
| + } |
| + st, found, err := t.latestStep(id) |
| + if err != nil { |
| + return err |
| + } |
| + if k.Revision != in.Revision || !found || st.ID != in.StepID || st.Revision != in.StepRevision || st.Attempt != in.Attempt { |
| + return ErrNotRetryable |
| + } |
| + attempt, err = t.personRetry(person, id, in.StepID, false) |
| + if err != nil { |
| + return err |
| + } |
| + r.Attempt = attempt |
| + return t.db.Create(r).Error |
| + }) |
| + return attempt, err |
| +} |
diff --git a/internal/equipo/chat/notification_actions_test.go b/internal/equipo/chat/notification_actions_test.go| new file mode 100644 |
| index 00000000..0888fcfd |
| --- /dev/null |
| +++ b/internal/equipo/chat/notification_actions_test.go |
| @@ -0,0 +1,158 @@ |
| +package chat |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "context" |
| + "errors" |
| + "gorm.io/gorm" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestNotificationAnswerReceipt(t *testing.T) { |
| + r := newPushRig(t) |
| + r.s.SetNotificationActions(true) |
| + c := r.card("nc1", wire.CardOpen) |
| + in := wire.AnswerCard{Revision: c.Revision, Choice: "main", IdempotencyKey: "notification-answer-1"} |
| + a, _, err := r.s.AnswerDevice(r.ctx, hkOwner, "cr_phone", c.ID, in) |
| + r.must(err) |
| + b, _, err := r.s.AnswerDevice(r.ctx, hkOwner, "cr_phone", c.ID, in) |
| + r.must(err) |
| + if a.Message.ID == "" || b.Message.ID != a.Message.ID || b.Turn.ID != a.Turn.ID { |
| + t.Fatal("retry lost original result", a, b) |
| + } |
| + if got := r.count("SELECT count(*) FROM chat_messages WHERE idempotency_key = 'card:nc1'"); got != 1 { |
| + t.Fatal(got) |
| + } |
| + in.Choice = "release" |
| + 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) { |
| + t.Fatal("revoked receipt read", err) |
| + } |
| + r.revoked["cr_phone"] = false |
| + r.now = r.now.Add(8 * 24 * time.Hour) |
| + if _, _, err = r.s.AnswerDevice(r.ctx, hkOwner, "cr_phone", c.ID, in); !errors.Is(err, ErrCardConflict) { |
| + t.Fatal("expired receipt repeated action", err) |
| + } |
| +} |
| + |
| +func TestNotificationRetryBinding(t *testing.T) { |
| + for _, mutate := range []string{"task", "step", "revision", "attempt", "creator", "terminated", "none"} { |
| + t.Run(mutate, func(t *testing.T) { |
| + r := newPushRig(t) |
| + r.s.SetNotificationActions(true) |
| + k := r.task("tk-notify", "Fix", hkOwner) |
| + r.step(&k, "st-notify", wire.SpecialistEngineering, wire.StepFailed) |
| + k = r.load(k.ID) |
| + in := wire.RetryTask{Revision: k.Revision, StepID: "st-notify", StepRevision: 1, Attempt: 1, IdempotencyKey: "notification-retry-1"} |
| + person := hkOwner |
| + switch mutate { |
| + case "task": |
| + in.Revision++ |
| + case "step": |
| + in.StepID = "other" |
| + case "revision": |
| + in.StepRevision++ |
| + case "attempt": |
| + in.Attempt++ |
| + case "creator": |
| + 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) |
| + } |
| + first, err := r.s.RetryTaskBound(r.ctx, person, "cr_phone", k.ID, in) |
| + if mutate != "none" { |
| + if err == nil { |
| + t.Fatal("accepted changed binding") |
| + } |
| + return |
| + } |
| + r.must(err) |
| + again, err := r.s.RetryTaskBound(r.ctx, person, "cr_phone", k.ID, in) |
| + r.must(err) |
| + if first != again || first != 2 { |
| + t.Fatal(first, again) |
| + } |
| + in.Attempt++ |
| + if _, err = r.s.RetryTaskBound(r.ctx, person, "cr_phone", k.ID, in); !errors.Is(err, ErrConflict) { |
| + t.Fatal(err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +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..312d47ea |
| --- /dev/null |
| +++ b/internal/equipo/chat/notification_payload.go |
| @@ -0,0 +1,78 @@ |
| +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: |
| + // A placement question (options or by name) resolves a project |
| + // in the app, never from the alert. |
| + if c.Placement != "" { |
| + return in |
| + } |
| + 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 || |
| + st.Specialist == wire.SpecialistMerge || st.Specialist == wire.SpecialistPublish { |
| + return in |
| + } |
| + // Offered exactly when the person's Retry would accept this step; |
| + // the bound write still goes through personRetry. |
| + if reason, err := t.retryReason(k, st, device.Person); err != nil || reason != "" { |
| + 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/notification_review_test.go b/internal/equipo/chat/notification_review_test.go| new file mode 100644 |
| index 00000000..16ca9c55 |
| --- /dev/null |
| +++ b/internal/equipo/chat/notification_review_test.go |
| @@ -0,0 +1,128 @@ |
| +package chat |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/push" |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "encoding/json" |
| + "gorm.io/gorm" |
| + "testing" |
| +) |
| + |
| +func TestNotificationPlacementPushRuleIsOpenOnly(t *testing.T) { |
| + for _, byName := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "options", true: "by-name"}[byName], 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.clear() |
| + placement, _ := json.Marshal(placementData{ByName: byName}) |
| + options := `["Use existing","New project"]` |
| + if byName { |
| + options = `[]` |
| + } |
| + c := cardRecord{ID: "c_placement", Person: hkOwner, Kind: wire.CardQuestion, State: wire.CardOpen, Question: "Which project?", Options: options, Placement: string(placement), Revision: 1, CreatedAt: r.now, UpdatedAt: r.now} |
| + r.must(r.tx(func(tx *txn) error { |
| + if err := tx.db.Create(&c).Error; err != nil { |
| + return err |
| + } |
| + return tx.cardEvent(c) |
| + })) |
| + rows := r.outbox() |
| + if len(rows) != 1 { |
| + t.Fatalf("rows %d", len(rows)) |
| + } |
| + var p struct { |
| + APS struct{ Category string } |
| + Equipo wire.PushData |
| + } |
| + r.must(json.Unmarshal([]byte(rows[0].Payload), &p)) |
| + if p.Equipo.Actions != nil || p.APS.Category != push.CategoryNeedsYou { |
| + t.Fatalf("placement offered action: %+v", p) |
| + } |
| + var view wire.Card |
| + r.must(r.tx(func(tx *txn) (err error) { view, err = tx.cardView(c); return err })) |
| + if !view.PlacementQuestion || view.PlacementByName != byName { |
| + t.Fatalf("placement marker: %+v", view) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestNotificationRetryPushRuleRefusals offers Try again exactly when the |
| +// person's Retry would accept the failed step. Review and Publish failures |
| +// raise no task alert (a failed Review needs a decision, not a Retry, and a |
| +// publish never drives the task), so their eligibility is read through |
| +// notificationIntent directly; every other case uses the real enqueue path. |
| +func TestNotificationRetryPushRuleRefusals(t *testing.T) { |
| + for _, mode := range []string{"valid", "checks", "review", "member", "merge", "publish", "other-step-person", "no-runner"} { |
| + t.Run(mode, func(t *testing.T) { |
| + r := newPushRig(t) |
| + r.s.SetNotificationActions(true) |
| + device := wire.RegisterPush{Token: pushDevice, Environment: wire.APNsProduction, Platform: wire.PlatformIOS, ActionsVersion: 1, BindingID: "12345678-1234-4234-8234-123456789abc"} |
| + r.register(hkOwner, "cr_phone", device) |
| + k := r.task("tk_notify", "Fix", hkOwner) |
| + r.stage(&k, wire.StageInProgress) |
| + if mode == "member" { |
| + r.s.authority.Me = func(*gorm.DB, string) (wire.Me, error) { return wire.Me{Role: "member"}, nil } |
| + } |
| + if mode == "no-runner" { |
| + r.s.authority.PrimaryRunner = func(*gorm.DB, string) (string, error) { return "", nil } |
| + } |
| + specialist := map[string]string{"checks": wire.SpecialistChecks, "review": wire.SpecialistReview, "merge": wire.SpecialistMerge, "publish": wire.SpecialistPublish}[mode] |
| + if specialist == "" { |
| + specialist = wire.SpecialistEngineering |
| + } |
| + person := hkOwner |
| + if mode == "other-step-person" { |
| + person = "other@example.com" |
| + } |
| + offered := mode == "valid" || mode == "checks" || mode == "review" |
| + r.clear() |
| + r.must(r.tx(func(tx *txn) error { |
| + st := stepRecord{ID: "st_notify", TaskID: k.ID, Idx: 1, Person: person, Specialist: specialist, State: wire.StepFailed, Terminated: true, Revision: 1, Attempt: 1, CreatedAt: r.now, UpdatedAt: r.now} |
| + if err := tx.db.Create(&st).Error; err != nil { |
| + return err |
| + } |
| + return tx.saveTask(&k) |
| + })) |
| + check := func(category string, actions *wire.PushActions) { |
| + t.Helper() |
| + if offered && (actions == nil || category != "equipo.stopped.v1" || actions.StepID != "st_notify") { |
| + t.Fatalf("missing retry: %s %+v", category, actions) |
| + } |
| + if !offered && actions != nil { |
| + t.Fatalf("refused step offered retry: %s %+v", category, actions) |
| + } |
| + } |
| + alerts := 0 |
| + for _, row := range r.outbox() { |
| + if row.Kind != push.KindAlert && row.Kind != push.KindPassive { |
| + continue |
| + } |
| + alerts++ |
| + var p struct { |
| + APS struct{ Category string } |
| + Equipo wire.PushData |
| + } |
| + r.must(json.Unmarshal([]byte(row.Payload), &p)) |
| + check(p.APS.Category, p.Equipo.Actions) |
| + } |
| + if mode == "review" || mode == "publish" { |
| + if alerts != 0 { |
| + t.Fatalf("%s failure raised %d task alerts", mode, alerts) |
| + } |
| + var out push.Intent |
| + r.must(r.tx(func(tx *txn) error { |
| + in := push.Intent{Kind: push.KindPassive, Data: wire.PushData{Kind: wire.PushTask, TaskID: k.ID}} |
| + out = tx.notificationIntent(in, push.Registration{Person: hkOwner, ActionsVersion: 1, BindingID: device.BindingID}) |
| + return nil |
| + })) |
| + check(out.Category, out.Data.Actions) |
| + return |
| + } |
| + if alerts == 0 { |
| + t.Fatal("real task push did not enqueue an alert") |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/equipo/chat/projects.go b/internal/equipo/chat/projects.go| index 5b938ae9..ebe629e1 100644 |
| --- a/internal/equipo/chat/projects.go |
| +++ b/internal/equipo/chat/projects.go |
| @@ -290,6 +290,7 @@ func (t *txn) cardView(c cardRecord) (wire.Card, error) { |
| } |
| v.RememberName = data.RequestedName |
| v.PlacementByName = data.ByName |
| + v.PlacementQuestion = c.Kind == wire.CardQuestion |
| } |
| if c.Access != "" { |
| if err := json.Unmarshal([]byte(c.Access), &v.Access); err != nil { |
| @@ -674,7 +675,12 @@ func (s *Store) Card(ctx context.Context, person, id string) (out wire.Card, err |
| // Answer answers a question card. The answer becomes the person's next |
| // message, so the coordinator reads it in a new turn. A stale revision or |
| // a card already answered is a conflict carrying the current card. |
| -func (s *Store) Answer(ctx context.Context, person, id string, in wire.AnswerCard) (out wire.Answered, current wire.Card, err error) { |
| +func (s *Store) Answer(ctx context.Context, person, id string, in wire.AnswerCard) (wire.Answered, wire.Card, error) { |
| + return s.AnswerDevice(ctx, person, "", id, in) |
| +} |
| + |
| +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 |
| @@ -683,87 +689,106 @@ func (s *Store) Answer(ctx context.Context, person, id string, in wire.AnswerCar |
| if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| return err |
| } |
| - var c cardRecord |
| - if err := t.db.Where("id = ? AND person = ? AND "+coordinatorRole, id, person).First(&c).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| - return ErrNotFound |
| - } else if err != nil { |
| - return err |
| - } |
| - if c.Kind == wire.CardHome { |
| - card, cur, e := t.answerHome(person, c, in) |
| - out.Card, current = card, cur |
| - return e |
| - } |
| - if c.Kind == wire.CardAccess { |
| - card, cur, e := t.answerAccess(person, c, in) |
| - out.Card, current = card, cur |
| - return e |
| - } |
| - if c.Kind == wire.CardCombined { |
| - card, cur, e := t.answerCombined(person, c, in) |
| - out.Card, current = card, cur |
| - return e |
| - } |
| - if c.Kind == wire.CardDirection { |
| - card, cur, e := t.answerDirection(person, c, in) |
| - out.Card, current = card, cur |
| - return e |
| - } |
| - if c.Kind == wire.CardSpecialist { |
| - card, cur, e := t.answerSpecialist(person, c, in) |
| - out.Card, current = card, cur |
| - return e |
| - } |
| - if c.Kind == wire.CardResearchSources { |
| - card, cur, e := t.answerResearchSources(person, c, in) |
| - out.Card, current = card, cur |
| - return e |
| - } |
| - if c.Kind == wire.CardResearchInventory { |
| - card, cur, e := t.answerResearchInventory(person, c, in) |
| - out.Card, current = card, cur |
| - return e |
| - } |
| - if c.Kind == wire.CardAdvice { |
| - card, cur, e := t.answerAdvice(person, c, in) |
| - out.Card, current = card, cur |
| - return e |
| - } |
| - if c.Kind == wire.CardHeld { |
| - card, cur, e := t.answerHeld(person, c, in) |
| - out.Card, current = card, cur |
| - return e |
| - } |
| - if c.Kind == wire.CardMerge { |
| - card, cur, e := t.answerMerge(person, c, in) |
| - out.Card, current = card, cur |
| - return e |
| - } |
| - if c.Kind == wire.CardPublish { |
| - card, cur, e := t.answerPublish(person, c, in) |
| - out.Card, current = card, cur |
| - return e |
| + var receipt *notificationReceipt |
| + if in.IdempotencyKey != "" { |
| + var prior bool |
| + receipt, prior, err = t.actionReceipt(person, credential, "answer", id, in.IdempotencyKey, digestInput) |
| + if err != nil { |
| + return err |
| + } |
| + if prior { |
| + out, err = t.receiptAnswer(*receipt) |
| + return err |
| + } |
| } |
| - if c.Kind == wire.CardMergeShips || c.Kind == wire.CardMergePolicy || c.Kind == wire.CardMergeReceipt { |
| - var card, cur wire.Card |
| - var e error |
| - switch c.Kind { |
| - case wire.CardMergeShips: |
| - card, cur, e = t.answerShips(person, c, in) |
| - case wire.CardMergePolicy: |
| - card, cur, e = t.answerPolicyCard(person, c, in) |
| - default: |
| - card, cur, e = t.answerReceipt(person, c, in) |
| + err = func() error { |
| + var c cardRecord |
| + if err := t.db.Where("id = ? AND person = ? AND "+coordinatorRole, id, person).First(&c).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| + return ErrNotFound |
| + } else if err != nil { |
| + return err |
| + } |
| + if c.Kind == wire.CardHome { |
| + card, cur, e := t.answerHome(person, c, in) |
| + out.Card, current = card, cur |
| + return e |
| + } |
| + if c.Kind == wire.CardAccess { |
| + card, cur, e := t.answerAccess(person, c, in) |
| + out.Card, current = card, cur |
| + return e |
| + } |
| + if c.Kind == wire.CardCombined { |
| + card, cur, e := t.answerCombined(person, c, in) |
| + out.Card, current = card, cur |
| + return e |
| + } |
| + if c.Kind == wire.CardDirection { |
| + card, cur, e := t.answerDirection(person, c, in) |
| + out.Card, current = card, cur |
| + return e |
| } |
| - out.Card, current = card, cur |
| + if c.Kind == wire.CardSpecialist { |
| + card, cur, e := t.answerSpecialist(person, c, in) |
| + out.Card, current = card, cur |
| + return e |
| + } |
| + if c.Kind == wire.CardResearchSources { |
| + card, cur, e := t.answerResearchSources(person, c, in) |
| + out.Card, current = card, cur |
| + return e |
| + } |
| + if c.Kind == wire.CardResearchInventory { |
| + card, cur, e := t.answerResearchInventory(person, c, in) |
| + out.Card, current = card, cur |
| + return e |
| + } |
| + if c.Kind == wire.CardAdvice { |
| + card, cur, e := t.answerAdvice(person, c, in) |
| + out.Card, current = card, cur |
| + return e |
| + } |
| + if c.Kind == wire.CardHeld { |
| + card, cur, e := t.answerHeld(person, c, in) |
| + out.Card, current = card, cur |
| + return e |
| + } |
| + if c.Kind == wire.CardMerge { |
| + card, cur, e := t.answerMerge(person, c, in) |
| + out.Card, current = card, cur |
| + return e |
| + } |
| + if c.Kind == wire.CardPublish { |
| + card, cur, e := t.answerPublish(person, c, in) |
| + out.Card, current = card, cur |
| + return e |
| + } |
| + if c.Kind == wire.CardMergeShips || c.Kind == wire.CardMergePolicy || c.Kind == wire.CardMergeReceipt { |
| + var card, cur wire.Card |
| + var e error |
| + switch c.Kind { |
| + case wire.CardMergeShips: |
| + card, cur, e = t.answerShips(person, c, in) |
| + case wire.CardMergePolicy: |
| + card, cur, e = t.answerPolicyCard(person, c, in) |
| + default: |
| + card, cur, e = t.answerReceipt(person, c, in) |
| + } |
| + out.Card, current = card, cur |
| + return e |
| + } |
| + if c.Kind != wire.CardQuestion && c.Kind != wire.CardProject { |
| + return ErrNotFound |
| + } |
| + var e error |
| + out, current, e = t.answerQuestionOrigin(person, c, in, originComposer) |
| return e |
| + }() |
| + if err != nil || receipt == nil { |
| + return err |
| } |
| - if c.Kind != wire.CardQuestion && c.Kind != wire.CardProject { |
| - return ErrNotFound |
| - } |
| - var e error |
| - out, current, e = t.answerQuestionOrigin(person, c, in, originComposer) |
| - return e |
| + receipt.CardID, receipt.MessageID, receipt.TurnID = out.Card.ID, out.Message.ID, out.Turn.ID |
| + return t.db.Create(receipt).Error |
| }) |
| return out, current, 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/chat/store.go b/internal/equipo/chat/store.go| index 7baa640e..8d0148a6 100644 |
| --- a/internal/equipo/chat/store.go |
| +++ b/internal/equipo/chat/store.go |
| @@ -95,12 +95,13 @@ type Authority struct { |
| // Store owns the chat tables. |
| type Store struct { |
| - db *db.DB |
| - authority Authority |
| - hub *Hub |
| - now func() time.Time |
| - process string |
| - tap atomic.Pointer[func(runner string, raw []byte)] |
| + notificationActions atomic.Bool |
| + db *db.DB |
| + authority Authority |
| + hub *Hub |
| + now func() time.Time |
| + process string |
| + tap atomic.Pointer[func(runner string, raw []byte)] |
| // Housekeeping: the detectors (housekeeping.Default unless a test |
| // declares others), the team's id once read, and the loop's clock |
| // (quiet hours, the day's budget, the digest), nil for now. |
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/0111_notification_actions.sql b/internal/equipo/migrations/0111_notification_actions.sql| new file mode 100644 |
| index 00000000..34c940fa |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0111_notification_actions.sql |
| @@ -0,0 +1,10 @@ |
| +-- Notification actions are opt-in per device and disabled by default. |
| +ALTER TABLE push_registrations ADD COLUMN actions_version integer; |
| +ALTER TABLE push_registrations ADD COLUMN binding_id text; |
| +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/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/api.go b/internal/wire/api.go| index 0f5ebb02..7378c47b 100644 |
| --- a/internal/wire/api.go |
| +++ b/internal/wire/api.go |
| @@ -355,19 +355,22 @@ type AddProject struct { |
| // Card is something in the conversation the person can act on: a project |
| // the coordinator added (Remove) or a question (answer). |
| type Card struct { |
| - PlacementByName bool `json:"placement_by_name,omitempty"` |
| - RememberName string `json:"remember_name,omitempty"` |
| - Access *AccessRequest `json:"access,omitempty"` |
| - ID string `json:"id"` |
| - Revision int64 `json:"revision"` |
| - Kind string `json:"kind"` |
| - State string `json:"state"` |
| - TurnID string `json:"turn_id"` |
| - ProjectID string `json:"project_id"` |
| - Name string `json:"name"` |
| - Question string `json:"question"` |
| - Options []string `json:"options"` |
| - Choice string `json:"choice"` |
| + PlacementByName bool `json:"placement_by_name,omitempty"` |
| + // PlacementQuestion marks every placement question, with options or |
| + // by name: it is answered in the app, never from a notification. |
| + PlacementQuestion bool `json:"placement_question,omitempty"` |
| + RememberName string `json:"remember_name,omitempty"` |
| + Access *AccessRequest `json:"access,omitempty"` |
| + ID string `json:"id"` |
| + Revision int64 `json:"revision"` |
| + Kind string `json:"kind"` |
| + State string `json:"state"` |
| + TurnID string `json:"turn_id"` |
| + ProjectID string `json:"project_id"` |
| + Name string `json:"name"` |
| + Question string `json:"question"` |
| + Options []string `json:"options"` |
| + Choice string `json:"choice"` |
| // TaskID names the task a task card reports. |
| TaskID string `json:"task_id"` |
| CreatedAt time.Time `json:"created_at"` |
| @@ -401,9 +404,10 @@ type Card struct { |
| // AnswerCard is the body of POST /api/v1/cards/{id}/answer. Revision must |
| // be the card's current revision. |
| type AnswerCard struct { |
| - RememberName *string `json:"remember_name,omitempty"` |
| - Choice string `json:"choice"` |
| - Revision int64 `json:"revision"` |
| + IdempotencyKey string `json:"idempotency_key,omitempty"` |
| + RememberName *string `json:"remember_name,omitempty"` |
| + Choice string `json:"choice"` |
| + Revision int64 `json:"revision"` |
| // Note is the person's words with an answer that takes them (a |
| // direction card's Try again). |
| Note string `json:"note,omitempty"` |
diff --git a/internal/wire/push.go b/internal/wire/push.go| index cf26f0e3..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. |
| @@ -129,3 +144,12 @@ type SetCardVisibility struct { |
| Aside bool `json:"aside"` |
| Revision int64 `json:"revision"` |
| } |
| + |
| +// RetryTask binds notification retry to the exact failed attempt shown. |
| +type RetryTask struct { |
| + Revision int64 `json:"revision"` |
| + StepID string `json:"step_id"` |
| + StepRevision int64 `json:"step_revision"` |
| + Attempt int64 `json:"attempt"` |
| + IdempotencyKey string `json:"idempotency_key"` |
| +} |
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/API/Thin.swift b/native/apple/Sources/EquipoKit/API/Thin.swift| index 9086996a..89beca89 100644 |
| --- a/native/apple/Sources/EquipoKit/API/Thin.swift |
| +++ b/native/apple/Sources/EquipoKit/API/Thin.swift |
| @@ -44,6 +44,8 @@ public struct ThinTurn: Codable, Sendable, Identifiable, Equatable { |
| public struct ThinCard: Codable, Sendable, Identifiable, Equatable { |
| public var rememberName: String? = nil |
| public var placementByName: Bool? = nil |
| + public var placementQuestion: Bool? = nil |
| + public var isPlacementQuestion: Bool { placementQuestion == true || placementByName == true } |
| public var isTypedProjectChoice: Bool { placementByName == true } |
| public var answerFieldKey: String { isTypedProjectChoice ? "projects.other" : "chat.card.answer" } |
| public var id: String |
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..f9244615 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/Push/NotificationDispatcher.swift |
| @@ -0,0 +1,209 @@ |
| +import Foundation |
| +import Observation |
| +import EquipoShareCore |
| +#if os(iOS) |
| +import UIKit |
| +#elseif os(macOS) |
| +import AppKit |
| +#endif |
| + |
| +struct NotificationAppState { |
| + var active: Bool |
| + var protectedData: Bool |
| + @MainActor static var current: Self { |
| + #if os(iOS) |
| + Self(active: UIApplication.shared.applicationState == .active, protectedData: UIApplication.shared.isProtectedDataAvailable) |
| + #elseif os(macOS) |
| + Self(active: NSApplication.shared.isActive, protectedData: true) |
| + #else |
| + Self(active: false, protectedData: false) |
| + #endif |
| + } |
| +} |
| + |
| +@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 } |
| + private let appState: () -> NotificationAppState |
| + init(journal: ActionJournal, appState: @escaping () -> NotificationAppState = { .current }) { |
| + self.journal = journal; self.appState = appState |
| + } |
| + 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) |
| + } |
| + /// Writes only while the device is unlocked and the app is active in the |
| + /// foreground; otherwise the notification opens its card instead. |
| + private func foreground(_ response: NotificationResponse) -> Bool { |
| + let state = appState() |
| + guard state.active && state.protectedData else { |
| + onRoute?(response.route); dismiss(response.binding.notificationId) |
| + return false |
| + } |
| + return true |
| + } |
| + 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) |
| + // A placement question resolves a project in the app, never here. |
| + guard !card.isPlacementQuestion else { onRoute?(response.route); dismiss(id); return } |
| + 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) |
| + } |
| + guard foreground(response) else { return } |
| + try journal.save(id: id, binding: selection.id, body: JSONEncoder().encode(Stored(response: response, write: write))) |
| + } |
| + guard current(session, selection), foreground(response) 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..4ccc54d8 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) |
| @@ -125,6 +137,14 @@ public final class PushRegistrar { |
| accepted = (bearer, body) |
| } catch let error as EquipoAPIError { |
| guard lifetime?.isActive != false, generation == self.generation else { return } |
| + if error.status == 403, body.actionsVersion == 1 { |
| + let enabled = try? await client.notificationActionsEnabled() |
| + guard lifetime?.isActive != false, generation == self.generation else { return } |
| + if enabled == false { |
| + actionsEnabled = false; capabilityRead = true; again = true |
| + } |
| + return |
| + } |
| // A refusal is final for this body; anything else waits for the next sync. |
| if let status = error.status, status == 400 || status == 422 { refused = (bearer, body) } |
| return |
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..102a5177 |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/NotificationActionTests.swift |
| @@ -0,0 +1,119 @@ |
| +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)) |
| + } |
| + } |
| +} |
| + |
| +@MainActor @Suite struct NotificationRegistrationFallbackTests { |
| + @Test func forbiddenActionsRefreshCapabilitiesAndRegisterOpenOnly() async throws { |
| + let server = ScriptedTransport() |
| + server.on("GET /capabilities", .success(APIResponse(status: 200, data: Data(#"{"notification_actions_v1":true}"#.utf8)))) |
| + server.on("GET /capabilities", .success(APIResponse(status: 200, data: Data("{}".utf8)))) |
| + server.on("POST /push-registrations", .success(APIResponse(status: 403, data: Data(#"{"code":"forbidden"}"#.utf8)))) |
| + server.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: server, token: "secret"), bindingID: NotificationActionTests.binding) |
| + #expect(server.sent("GET /capabilities").count == 2) |
| + let posts = server.sent("POST /push-registrations") |
| + try #require(posts.count == 2) |
| + let raw = try #require(posts[1].body) |
| + let body = try #require(JSONSerialization.jsonObject(with: raw) as? [String: Any]) |
| + #expect(body["actions_version"] == nil) |
| + #expect(body["binding_id"] == nil) |
| + await registrar.sync() |
| + #expect(server.sent("POST /push-registrations").count == 2) |
| + } |
| +} |
diff --git a/native/apple/Tests/EquipoKitTests/NotificationDispatchTests.swift b/native/apple/Tests/EquipoKitTests/NotificationDispatchTests.swift| new file mode 100644 |
| index 00000000..8e802b86 |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/NotificationDispatchTests.swift |
| @@ -0,0 +1,256 @@ |
| +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), appState: { .init(active: true, protectedData: true) }) |
| + 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), appState: { .init(active: true, protectedData: true) }) |
| + 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", "placement", "by-name"] { |
| + 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)))) |
| + } |
| + if mode == "placement" || mode == "by-name" { |
| + let 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 = [] |
| + var raw = try #require(JSONSerialization.jsonObject(with: Self.encode(card)) as? [String: Any]) |
| + raw[mode == "placement" ? "placement_question" : "placement_by_name"] = true |
| + server.replace("GET /cards/card_1", with: .success(APIResponse(status: 200, data: try JSONSerialization.data(withJSONObject: raw)))) |
| + } |
| + 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), appState: { .init(active: true, protectedData: true) }) |
| + 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), appState: { .init(active: true, protectedData: true) }) |
| + 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), appState: { .init(active: true, protectedData: true) }) |
| + 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) |
| + } |
| +} |
| + |
| +@MainActor @Suite struct NotificationForegroundTests { |
| + @Test func lockedOrInactiveBeforeOrAfterReadNeverJournalsOrPosts() async throws { |
| + for mode in ["locked", "inactive", "locked-late", "inactive-late"] { |
| + let (_, _, server, directory, selection) = try NotificationDispatchTests.setup() |
| + defer { try? FileManager.default.removeItem(at: directory) } |
| + let gate = GatedTransport(inner: server, route: "GET /cards/card_1") |
| + gate.hold = mode.hasSuffix("late") |
| + let session = try TaskDetailModelTests.model(gate).session |
| + var state = NotificationAppState(active: true, protectedData: true) |
| + if mode == "locked" { state.protectedData = false } |
| + if mode == "inactive" { state.active = false } |
| + let dispatcher = NotificationDispatcher(journal: ActionJournal(directory: directory), appState: { state }) |
| + dispatcher.attach(session: session, selection: selection) |
| + var route: PushRoute? |
| + dispatcher.onRoute = { route = $0 } |
| + let response = try #require(NotificationResponse(userInfo: NotificationActionTests.payload(), category: "equipo.question.text.v1", action: "answer", text: "answer")) |
| + let job = Task { await dispatcher.receive(response) } |
| + if mode.hasSuffix("late") { |
| + await gate.waitUntilHeld() |
| + if mode == "locked-late" { state.protectedData = false } else { state.active = false } |
| + gate.release() |
| + } |
| + await job.value |
| + #expect(server.sent("POST /cards/card_1/answer").isEmpty) |
| + #expect(try ActionJournal(directory: directory).pending(binding: selection.id).isEmpty) |
| + #expect(route == .card("card_1")) |
| + } |
| + } |
| + @Test func restoredReplyNeverResendsWhileLockedOrInactive() async throws { |
| + for state in [NotificationAppState(active: false, protectedData: true), NotificationAppState(active: true, protectedData: false)] { |
| + let (dispatcher, session, 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) |
| + try #require(server.sent("POST /cards/card_1/answer").count == 1) |
| + let restored = NotificationDispatcher(journal: ActionJournal(directory: directory), appState: { state }) |
| + restored.attach(session: session, selection: selection) |
| + let notice = try #require(restored.notices.first) |
| + await restored.retry(notice) |
| + #expect(server.sent("POST /cards/card_1/answer").count == 1) |
| + #expect(try ActionJournal(directory: directory).load(id: response.binding.notificationId, binding: selection.id) != nil, "the exact request stays for a foreground retry") |
| + } |
| + } |
| +} |
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) } |
| +} |