oficina / equipo Public

Merge branch 'native/oficina-id' into main

claude agent, operated by paul@keymail.dev 1943f5cf2dfb1b613dcc9d1d617195f03b66a59a parent ecb94beparent 5d73803
34 files changed, +2,383 −89
  • native/OFICINA-ID-REPORT.md +496 −0
  • native/apple/Package.resolved +2 −2
  • native/apple/Package.swift +3 −3
  • native/apple/Sources/EquipoActivity/Resources/Localizable.xcstrings +55 −0
  • native/apple/Sources/EquipoKit/API/Transport.swift +10 −1
  • native/apple/Sources/EquipoKit/OficinaID/EquipoOficinaID.swift +292 −0
  • native/apple/Sources/EquipoKit/OficinaID/EquipoRenewingTransport.swift +53 −0
  • native/apple/Sources/EquipoKit/Pairing/DeviceAccount.swift +34 −12
  • native/apple/Sources/EquipoKit/Pairing/Pairing.swift +71 −16
  • native/apple/Sources/EquipoKit/Push/PhoneDelegate.swift +3 −0
  • native/apple/Sources/EquipoKit/Push/PushRegistrar.swift +12 −8
  • native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings +55 −0
  • native/apple/Sources/EquipoKit/Session/EquipoSession.swift +61 −17
  • native/apple/Sources/EquipoKit/Session/SignInLifetime.swift +67 −0
  • native/apple/Sources/EquipoKit/UI/Screens/AccountScreen.swift +7 −3
  • native/apple/Sources/EquipoKit/UI/Screens/AppModel.swift +112 −19
  • native/apple/Sources/EquipoKit/UI/Screens/OficinaAccountMenu.swift +39 −0
  • native/apple/Sources/EquipoKit/UI/Screens/OficinaNotice.swift +30 −0
  • native/apple/Sources/EquipoKit/UI/Screens/PhoneRoot.swift +7 −3
  • native/apple/Sources/EquipoKit/UI/Screens/SignInView.swift +47 −0
  • native/apple/Sources/EquipoMac/EquipoMacApp.swift +6 −2
  • native/apple/Tests/EquipoKitTests/OficinaIDTests.swift +759 −0
  • native/apple/Tests/EquipoKitTests/PushTests.swift +14 −0
  • native/apple/Tests/EquipoKitTests/SessionTests.swift +1 −1
  • native/apple/Tests/EquipoKitTests/SetAsideTests.swift +1 −1
  • native/apple/Tests/EquipoKitTests/SignInLifetimeTests.swift +27 −0
  • native/apple/Tests/EquipoKitTests/Support.swift +3 −0
  • native/ios/EquipoPhone.entitlements +10 −0
  • native/macos/DeveloperID.entitlements +10 −0
  • native/scripts/build-mac.sh +3 −0
  • native/scripts/check-native.sh +3 −0
  • native/scripts/check-oficina-id.py +52 −0
  • native/scripts/check-sign-in-lifetime.py +32 −0
  • native/scripts/strings.json +6 −1

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.2s
ci-box: codex: fetched and verified in 3.4s
ci-box: codex-code-mode-host: fetched and verified in 1.3s
ci-box: libwrap: fetched and verified in 0.3s
ci-box: socat: fetched and verified in 0.3s
npm warn deprecated node-domexception@1.0.0: Use your platform's native DOMException instead
ci-box: image pulled in 9.9s
ci-box: pi: installed and verified in 7.5s
ci-box: opencode: installed and verified in 2.2s
ci-box: chromium 156.0.8078.79-1~deb13u1: 76 packages fetched, verified and unpacked in 8.6s
ci-box: clone deepened in 3.2s
ci-box: file times set from content: 2818 files, 185 directories
ci-box: ready in 16.6s
=== 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.247s
=== compile ===
go build ./...
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py compile
+ go build -tags testbuild ./...
  1.1s
+ go list -export -test -tags testbuild -f  ./...
  0.6s
+ go list -export -test -tags browser,testbuild -f  ./internal/equipo ./internal/headless ./internal/idtest ./internal/plan3test ./internal/thintest
  0.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-11 02:51:11 +0000 UTC

go run github.com/zricethezav/gitleaks/v8@v8.30.1 version
version is set by build process
=== check ===
--- shard 0 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-work: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestHeadless$/^4c_rebase$|^TestHeadless$/^4b_ask$|^TestHeadless$/^4c_checks_card$|^TestHeadless$/^4_step_crash$' ./internal/headless
cache miss: amadan.net/oficina/equipo/internal/headless: its inputs changed

receipt: test step 1m21.117s 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 1m19.532s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m19.53s amadan.net/oficina/equipo/internal/headless TestHeadless
machine: 32 CPUs, load 35.34, cpu waiting 21.11%, memory waiting 0.00%, io waiting 0.47%
--- shard 1 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-review: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestHeadless$/^4_review$|^TestHeadless$/^2b_access$|^TestHeadless$/^runner_crash$|^TestHeadless$/^2b_first_message$|^TestHeadless$/^4_checks_honest$|^TestHeadless$/^7_stream_resume$|^TestHeadless$/^2b_notebook$|^TestHeadless$/^2b_move_in$|^TestHeadless$/^2b_desk_failure$|^TestHeadless$/^cancel$' ./internal/headless
cache miss: amadan.net/oficina/equipo/internal/headless: its inputs changed

receipt: test step 1m23.179s 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 1m21.431s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m21.43s amadan.net/oficina/equipo/internal/headless TestHeadless
machine: 32 CPUs, load 34.03, cpu waiting 20.65%, memory waiting 0.00%, io waiting 0.46%
--- shard 2 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-connections: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestHeadlessConnections$|^TestHeadlessTokenPasteEndToEnd$|^TestHeadlessTokenConnection$' ./internal/headless
cache miss: amadan.net/oficina/equipo/internal/headless: its inputs changed

receipt: test step 1m24.384s 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 1m22.209s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m11.63s amadan.net/oficina/equipo/internal/headless TestHeadlessConnections
receipt: slow test 5.77s amadan.net/oficina/equipo/internal/headless TestHeadlessTokenPasteEndToEnd
receipt: slow test 4.81s amadan.net/oficina/equipo/internal/headless TestHeadlessTokenConnection
machine: 32 CPUs, load 34.03, cpu waiting 20.65%, memory waiting 0.00%, io waiting 0.46%
--- 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
cache miss: amadan.net/oficina/equipo/internal/headless: its inputs changed

receipt: test step 1m19.478s 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.777s amadan.net/oficina/equipo/internal/headless
receipt: slow test 37.23s amadan.net/oficina/equipo/internal/headless TestMacWorker
receipt: slow test 20.41s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 10.49s amadan.net/oficina/equipo/internal/headless TestHeadlessAttachments
receipt: slow test 9.64s amadan.net/oficina/equipo/internal/headless TestHeadlessPrewarm
machine: 32 CPUs, load 35.34, cpu waiting 21.48%, memory waiting 0.00%, io waiting 0.49%
--- shard 4 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-guards: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestHeadlessCopyRotation$|^TestHeadlessPolicyGuards$|^TestHeadlessRunnerKillLeavesNoCopies$|^TestHeadlessNewHouseRuleStartsFresh$|^TestHeadless$/^3_engineering$|^TestHeadless$/^3_step_cancel$|^TestHeadless$/^3_step_contained$|^TestHeadless$/^3_empty_repo$|^TestHeadless$/^3_empty_engineering$|^TestHeadless$/^3_empty_merge$|^TestHeadless$/^3_empty_merge_rebuilt$|^TestHeadless$/^3_empty_fix_round$' ./internal/headless
cache miss: amadan.net/oficina/equipo/internal/headless: its inputs changed

receipt: test step 1m37.883s 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 1m36.169s amadan.net/oficina/equipo/internal/headless
receipt: slow test 59.96s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 11.42s amadan.net/oficina/equipo/internal/headless TestHeadlessRunnerKillLeavesNoCopies
receipt: slow test 10.14s amadan.net/oficina/equipo/internal/headless TestHeadlessCopyRotation
receipt: slow test 8.83s amadan.net/oficina/equipo/internal/headless TestHeadlessPolicyGuards
receipt: slow test 5.82s amadan.net/oficina/equipo/internal/headless TestHeadlessNewHouseRuleStartsFresh
machine: 32 CPUs, load 29.11, cpu waiting 16.70%, 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_empty_repo$|^TestHeadless$/^3_empty_engineering$|^TestHeadless$/^3_empty_merge$|^TestHeadless$/^3_empty_merge_rebuilt$|^TestHeadless$/^3_empty_fix_round$' ./internal/headless
cache miss: amadan.net/oficina/equipo/internal/headless: its inputs changed

receipt: test step 3m11.3s 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 3m9.207s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m46.88s amadan.net/oficina/equipo/internal/headless TestHeadlessAssistant
receipt: slow test 24.34s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 11.6s amadan.net/oficina/equipo/internal/headless TestHeadlessResearchHandoff
receipt: slow test 8.19s amadan.net/oficina/equipo/internal/headless TestHeadlessClaudeSignIn
receipt: slow test 7.36s amadan.net/oficina/equipo/internal/headless TestHeadlessTurnBatching
machine: 32 CPUs, load 8.20, cpu waiting 3.51%, memory waiting 0.00%, io waiting 0.06%
--- 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 505ms against a 60s target (the gate's other steps are not in this figure)
receipt: 0 packages ran, 1 cached, 0 without tests, 0 failed
receipt: slow package 1m59.88s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 7.85s amadan.net/oficina/equipo/internal/thintest TestContractTeamJobSettledStates
receipt: slow test 6.77s amadan.net/oficina/equipo/internal/thintest TestExplorePreviewsOff
receipt: slow test 3.71s amadan.net/oficina/equipo/internal/thintest TestContractPreviewHeldUntilPublishAnswer
receipt: slow test 3.46s amadan.net/oficina/equipo/internal/thintest TestContractTeamNudgePersonNeeds
receipt: slow test 2.5s amadan.net/oficina/equipo/internal/thintest TestResearchDoneFallsBack
machine: 32 CPUs, load 1.17, cpu waiting 0.65%, memory waiting 0.00%, io waiting 1.82%
--- 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 416ms against a 60s target (the gate's other steps are not in this figure)
receipt: 0 packages ran, 1 cached, 0 without tests, 0 failed
receipt: slow package 1m22.447s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 9.07s amadan.net/oficina/equipo/internal/thintest TestContractPreviewNotScheduled
receipt: slow test 5.01s amadan.net/oficina/equipo/internal/thintest TestContractPublishNotOffered
receipt: slow test 4.43s amadan.net/oficina/equipo/internal/thintest TestContractMacRecheckMergeAuthority
receipt: slow test 2.4s amadan.net/oficina/equipo/internal/thintest TestContractPreview
receipt: slow test 2.35s amadan.net/oficina/equipo/internal/thintest TestContractPublishNameTaken
machine: 32 CPUs, load 1.17, cpu waiting 0.65%, memory waiting 0.00%, io waiting 1.82%
--- 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
cache miss: amadan.net/oficina/equipo/internal/runner/thin: its inputs changed
budget note: internal/runner/thin took 4m28.295s, over the 45s its record on line 44 allows; reported only, timing fails on CI

receipt: test step 4m41.159s 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 4m28.295s amadan.net/oficina/equipo/internal/runner/thin
receipt: slow test 36.96s amadan.net/oficina/equipo/internal/runner/thin TestModelsProbeAnsweredByAnotherModel
receipt: slow test 36.92s amadan.net/oficina/equipo/internal/runner/thin TestModelsEngineeringProbesThenRunsTheStrongest
receipt: slow test 36.75s amadan.net/oficina/equipo/internal/runner/thin TestModelsUnhealthyRetriedOnDemand
receipt: slow test 18.45s amadan.net/oficina/equipo/internal/runner/thin TestModelsProbeRunsInsideTheAdmission
receipt: slow test 6.87s amadan.net/oficina/equipo/internal/runner/thin TestOpenCodeStepsRealOpenCode
machine: 32 CPUs, load 2.37, cpu waiting 0.78%, memory waiting 0.00%, io waiting 0.01%
--- shard 9 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane runner-bug: ./internal/runner
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestDirectBugWorkflow$|^TestEnrolKeepsTheRole$' ./internal/runner
cache miss: amadan.net/oficina/equipo/internal/runner: its inputs changed

receipt: test step 47.442s 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 46.32s amadan.net/oficina/equipo/internal/runner
receipt: slow test 26.29s amadan.net/oficina/equipo/internal/runner TestDirectBugWorkflow
receipt: slow test 20.03s amadan.net/oficina/equipo/internal/runner TestEnrolKeepsTheRole
machine: 32 CPUs, load 34.47, cpu waiting 20.66%, memory waiting 0.00%, io waiting 0.84%
--- 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
cache miss: amadan.net/oficina/equipo/internal/runner: its inputs changed

receipt: test step 46.412s 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 44.459s amadan.net/oficina/equipo/internal/runner
receipt: slow test 34.53s amadan.net/oficina/equipo/internal/runner TestPlanWorkflowCandidateOrder
receipt: slow test 30.27s amadan.net/oficina/equipo/internal/runner TestPlanWorkflowFeature
receipt: slow test 8.38s amadan.net/oficina/equipo/internal/runner TestCoordinatorRecoveryCallRefusalKeepsServing
receipt: slow test 1.53s amadan.net/oficina/equipo/internal/runner TestCoordinatorRefusalMatrix
machine: 32 CPUs, load 34.86, cpu waiting 20.51%, memory waiting 0.00%, io waiting 0.87%
--- 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
cache miss: amadan.net/oficina/equipo/internal/runner: its inputs changed

receipt: test step 35.106s 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.282s amadan.net/oficina/equipo/internal/runner
receipt: slow test 5.11s amadan.net/oficina/equipo/internal/runner TestDirectFaultIsolation
receipt: slow test 3.51s amadan.net/oficina/equipo/internal/runner TestClaimRefusalsBackOff
receipt: slow test 3.11s amadan.net/oficina/equipo/internal/runner TestCoordinatorRecoveryRefusedKeepsServing
receipt: slow test 2.28s amadan.net/oficina/equipo/internal/runner TestToolVerbUnderFakeHarness
receipt: slow test 1.61s amadan.net/oficina/equipo/internal/runner TestCoordinatorTransientRefusalKeepsServing
machine: 32 CPUs, load 29.36, cpu waiting 15.15%, memory waiting 0.00%, io waiting 1.03%
--- 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 28.3%, load 23.65
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
cache miss: amadan.net/oficina/equipo/internal/equipotest: its inputs changed

receipt: test step 1m4.52s 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 1m2.6s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 26.87s amadan.net/oficina/equipo/internal/equipotest TestAuthorityCoreIntegration
receipt: slow test 26.78s amadan.net/oficina/equipo/internal/equipotest TestBootstrapNamesOwnersSetting
receipt: slow test 24.93s amadan.net/oficina/equipo/internal/equipotest TestAccountLabelMigration
receipt: slow test 22.36s amadan.net/oficina/equipo/internal/equipotest TestBudgetConfigurationFailuresAreAtomic
receipt: slow test 22.12s amadan.net/oficina/equipo/internal/equipotest TestAuthorityProjectKinds
machine: 32 CPUs, load 31.30, cpu waiting 17.26%, memory waiting 0.00%, io waiting 0.37%
--- 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 28.3%, load 23.65
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 409ms against a 60s target (the gate's other steps are not in this figure)
receipt: 0 packages ran, 1 cached, 0 without tests, 0 failed
receipt: slow package 1m13.463s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 19.28s amadan.net/oficina/equipo/internal/equipotest TestProjectRejectsUnsafeBinding
receipt: slow test 19.28s amadan.net/oficina/equipo/internal/equipotest TestProjectWritesRequireCurrentOwner
receipt: slow test 19.26s amadan.net/oficina/equipo/internal/equipotest TestProjectsSharedAndGrouped
receipt: slow test 19.24s amadan.net/oficina/equipo/internal/equipotest TestProjectsReopen
receipt: slow test 19.23s amadan.net/oficina/equipo/internal/equipotest TestProjectsFailuresRollBack
machine: 32 CPUs, load 23.65, cpu waiting 11.19%, memory waiting 0.00%, io waiting 1.14%
--- 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 28.3%, load 23.65
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
cache miss: amadan.net/oficina/equipo/internal/equipotest: its inputs changed

receipt: test step 1m14.456s 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 1m2.761s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 14.06s amadan.net/oficina/equipo/internal/equipotest TestReleaseStampContract
receipt: slow test 12.87s amadan.net/oficina/equipo/internal/equipotest TestRosterChangesAffectExistingSession
receipt: slow test 9.87s amadan.net/oficina/equipo/internal/equipotest TestRosterRemovalWhileAssigned
receipt: slow test 9.79s amadan.net/oficina/equipo/internal/equipotest TestRosterRemovalRollsBack
receipt: slow test 6.8s amadan.net/oficina/equipo/internal/equipotest TestRosterBootstrapOnce
machine: 32 CPUs, load 27.82, cpu waiting 14.68%, memory waiting 0.00%, io waiting 0.31%
--- 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 28.3%, load 23.65
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 488ms against a 60s target (the gate's other steps are not in this figure)
receipt: 0 packages ran, 1 cached, 0 without tests, 0 failed
receipt: slow package 1m5.999s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 25.51s amadan.net/oficina/equipo/internal/equipotest TestSigninNoProof
receipt: slow test 24.3s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsSeedExistingTeam
receipt: slow test 24.28s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsSeedRollback
receipt: slow test 22.57s amadan.net/oficina/equipo/internal/equipotest TestSigninCSRF
receipt: slow test 22.51s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsUpgrade
machine: 32 CPUs, load 23.65, cpu waiting 12.10%, memory waiting 0.00%, io waiting 1.10%
--- 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 28.3%, load 23.65
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 575ms against a 60s target (the gate's other steps are not in this figure)
receipt: 0 packages ran, 1 cached, 0 without tests, 0 failed
receipt: slow package 51.258s amadan.net/oficina/equipo/internal/plan3test
receipt: slow test 3.54s amadan.net/oficina/equipo/internal/plan3test TestPlan3Upgrade
receipt: slow test 3.48s amadan.net/oficina/equipo/internal/plan3test TestCoordinatorAcceptance3B
receipt: slow test 1.51s amadan.net/oficina/equipo/internal/plan3test TestCoordinatorAcceptance3A
receipt: slow test 1.5s amadan.net/oficina/equipo/internal/plan3test TestConversationQuestionRace
receipt: slow test 1.26s amadan.net/oficina/equipo/internal/plan3test TestPlanMigrationUpgrade
machine: 32 CPUs, load 23.65, cpu waiting 12.10%, memory waiting 0.00%, io waiting 1.10%
--- 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 28.3%, load 23.65
test lane rest: ./cmd/equipo ./cmd/equipo-runner ./cmd/equipo-tool-proxy ./internal/advice ./internal/attach ./internal/attach/attachtest ./internal/chatmarkdown ./internal/chatsend ./internal/chatstream ./internal/coordinator ./internal/coordinatorcontract ./internal/coordinatormail ./internal/copydesk ./internal/equipo ./internal/equipo/activity ./internal/equipo/assist ./internal/equipo/chat ./internal/equipo/conversation ./internal/equipo/conversation/chatstate ./internal/equipo/housekeeping ./internal/equipo/icons ./internal/equipo/identity ./internal/equipo/kernel ./internal/equipo/library ./internal/equipo/mergegate ./internal/equipo/notifications ./internal/equipo/oficina ./internal/equipo/oficina/oficinatest ./internal/equipo/oficinaid ./internal/equipo/ownermode ./internal/equipo/personapi ./internal/equipo/planning ./internal/equipo/push ./internal/equipo/setup ./internal/equipo/team ./internal/equipo/teamcontract ./internal/equipo/triage ./internal/fakeclaude ./internal/fakecodex ./internal/fakeopencode ./internal/fakepi ./internal/idtest ./internal/ownermodetest ./internal/release ./internal/runner/checks ./internal/runner/connect ./internal/runner/containment ./internal/runner/containment/sysunix ./internal/runner/egress ./internal/runner/forge ./internal/runner/forge/forgetest ./internal/runner/heartbeat ./internal/runner/mac ./internal/runner/mcpresource ./internal/runner/metered ./internal/runner/planflow ./internal/runner/provider ./internal/runner/provider/claude ./internal/runner/provider/codex ./internal/runner/provider/gotoolchain ./internal/runner/provider/opencode ./internal/runner/provider/pi ./internal/runner/setup ./internal/runner/transporttest ./internal/runner/webread ./internal/runner/workspace ./internal/runnerproto ./internal/schedule ./internal/sealbox ./internal/specialist ./internal/stagingtest ./internal/taskplan ./internal/testci ./internal/toolproxy ./internal/websource ./internal/wire ./internal/wire/wireschema ./internal/wire/wiretest ./tools/drive
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m ./cmd/equipo ./cmd/equipo-runner ./cmd/equipo-tool-proxy ./internal/advice ./internal/attach ./internal/attach/attachtest ./internal/chatmarkdown ./internal/chatsend ./internal/chatstream ./internal/coordinator ./internal/coordinatorcontract ./internal/coordinatormail ./internal/copydesk ./internal/equipo ./internal/equipo/activity ./internal/equipo/assist ./internal/equipo/chat ./internal/equipo/conversation ./internal/equipo/conversation/chatstate ./internal/equipo/housekeeping ./internal/equipo/icons ./internal/equipo/identity ./internal/equipo/kernel ./internal/equipo/library ./internal/equipo/mergegate ./internal/equipo/notifications ./internal/equipo/oficina ./internal/equipo/oficina/oficinatest ./internal/equipo/oficinaid ./internal/equipo/ownermode ./internal/equipo/personapi ./internal/equipo/planning ./internal/equipo/push ./internal/equipo/setup ./internal/equipo/team ./internal/equipo/teamcontract ./internal/equipo/triage ./internal/fakeclaude ./internal/fakecodex ./internal/fakeopencode ./internal/fakepi ./internal/idtest ./internal/ownermodetest ./internal/release ./internal/runner/checks ./internal/runner/connect ./internal/runner/containment ./internal/runner/containment/sysunix ./internal/runner/egress ./internal/runner/forge ./internal/runner/forge/forgetest ./internal/runner/heartbeat ./internal/runner/mac ./internal/runner/mcpresource ./internal/runner/metered ./internal/runner/planflow ./internal/runner/provider ./internal/runner/provider/claude ./internal/runner/provider/codex ./internal/runner/provider/gotoolchain ./internal/runner/provider/opencode ./internal/runner/provider/pi ./internal/runner/setup ./internal/runner/transporttest ./internal/runner/webread ./internal/runner/workspace ./internal/runnerproto ./internal/schedule ./internal/sealbox ./internal/specialist ./internal/stagingtest ./internal/taskplan ./internal/testci ./internal/toolproxy ./internal/websource ./internal/wire ./internal/wire/wireschema ./internal/wire/wiretest ./tools/drive
cache miss: amadan.net/oficina/equipo/internal/copydesk: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/webread: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/provider/opencode: 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: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/workspace: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/equipo/team: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/provider/codex: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/checks: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/containment: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/provider/pi: its inputs changed
budget note: internal/equipo took 47.923s, over the 10s the default allows (measured on the run this cached result came from); reported only, timing fails on CI
budget note: internal/equipo/chat took 12.599s, over the 10s the default allows (measured on the run this cached result came from); reported only, timing fails on CI
budget note: internal/equipo/setup took 10.811s, over the 10s the default allows (measured on the run this cached result came from); reported only, timing fails on CI
budget note: internal/idtest took 42.254s, over the 10s the default allows (measured on the run this cached result came from); reported only, timing fails on CI
budget note: internal/release took 19.39s, over the 10s the default allows (measured on the run this cached result came from); reported only, timing fails on CI
budget note: internal/runner/containment took 38.783s, over the 15s its record on line 40 allows; reported only, timing fails on CI

receipt: test step 2m15.086s against a 60s target (the gate's other steps are not in this figure)
receipt: 11 packages ran, 50 cached, 18 without tests, 0 failed
receipt: slow package 52.877s amadan.net/oficina/equipo/internal/runner/provider/opencode
receipt: slow package 51.638s amadan.net/oficina/equipo/internal/runner/provider/pi
receipt: slow package 47.923s amadan.net/oficina/equipo/internal/equipo
receipt: slow package 42.254s amadan.net/oficina/equipo/internal/idtest
receipt: slow package 38.783s amadan.net/oficina/equipo/internal/runner/containment
receipt: slow test 21.6s amadan.net/oficina/equipo/internal/runner/provider/opencode TestOpenCodeAcceptanceHostileRepository
receipt: slow test 16.66s amadan.net/oficina/equipo/cmd/equipo-runner TestReleaseRunnerHasNoFakeWorker
receipt: slow test 15.47s amadan.net/oficina/equipo/internal/runner/containment TestEngineeringOfflineGo
receipt: slow test 11.08s amadan.net/oficina/equipo/internal/idtest TestIDCallbackGuardAndPendingNonce
receipt: slow test 10.99s amadan.net/oficina/equipo/internal/equipo TestAgentReadRechecksIdentity
machine: 32 CPUs, load 11.45, cpu waiting 5.42%, memory waiting 0.00%, io waiting 0.11%
--- 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 1m22.537s 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 1m20.915s amadan.net/oficina/equipo/internal/headless
receipt: slow test 37.24s amadan.net/oficina/equipo/internal/headless TestBrowserDraftIsTheMessage
receipt: slow test 15.01s amadan.net/oficina/equipo/internal/headless TestBrowserDraftStreamsFormatted
receipt: slow test 10.37s amadan.net/oficina/equipo/internal/headless TestBrowserChat
receipt: slow test 7.75s amadan.net/oficina/equipo/internal/headless TestBrowserComposer
receipt: slow test 5.93s amadan.net/oficina/equipo/internal/headless TestBrowserChatSendStaysOnPage
machine: 32 CPUs, load 34.03, cpu waiting 20.65%, memory waiting 0.00%, io waiting 0.46%
--- 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 1m32.168s 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 1m30.557s amadan.net/oficina/equipo/internal/headless
receipt: slow test 25.65s amadan.net/oficina/equipo/internal/headless TestBrowserRailFollowsWork
receipt: slow test 22.64s amadan.net/oficina/equipo/internal/headless TestBrowserTaskThread
receipt: slow test 14.24s amadan.net/oficina/equipo/internal/headless TestBrowserReceiptFollowsReview
receipt: slow test 10.19s amadan.net/oficina/equipo/internal/headless TestBrowserAskAfterMerge
receipt: slow test 8.08s amadan.net/oficina/equipo/internal/headless TestBrowserTaskCard
machine: 32 CPUs, load 31.30, cpu waiting 17.81%, memory waiting 0.00%, io waiting 0.38%
--- 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
cache miss: amadan.net/oficina/equipo/internal/headless: its inputs changed

receipt: test step 1m39.857s 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 1m38.356s amadan.net/oficina/equipo/internal/headless
receipt: slow test 14.01s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsConversation
receipt: slow test 12.99s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsAdd
receipt: slow test 12.91s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsAddPage
receipt: slow test 10.21s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsMeteredLimitRequired
receipt: slow test 10.12s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsOpenCodeGoLimitRequired
machine: 32 CPUs, load 27.82, cpu waiting 15.65%, memory waiting 0.00%, io waiting 0.33%
--- shard 21 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
browser: /opt/chromium-156.0.8078.79-1_deb13u1/chrome: Chromium 156.0.8078.79
browser lane browser-headless-rest: ./internal/headless
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^(TestBrowserAskAfterMerge|TestBrowserChat|TestBrowserChatSendStaysOnPage|TestBrowserComposer|TestBrowserComposerDock|TestBrowserComposerFocus|TestBrowserComposerReconcile|TestBrowserConnectionsAdd|TestBrowserConnectionsAddPage|TestBrowserConnectionsConversation|TestBrowserConnectionsCopyLink|TestBrowserConnectionsEndedNote|TestBrowserConnectionsMeteredLimitRequired|TestBrowserConnectionsOpenCodeGoLimitRequired|TestBrowserConnectionsSignIn|TestBrowserConnectionsSignInSwitch|TestBrowserConnectionsToken|TestBrowserCopyContinue|TestBrowserCopySettingAndFlag|TestBrowserDraftIsTheMessage|TestBrowserDraftStreamsFormatted|TestBrowserEmptyExplore|TestBrowserMoveIn|TestBrowserNotebook|TestBrowserNotebookLook|TestBrowserPasteBox|TestBrowserPasteBoxLook|TestBrowserPasteCopiesItsBox|TestBrowserRailFollowsWork|TestBrowserReceiptFollowsReview|TestBrowserReceiptsDesktop|TestBrowserReceiptsTouch|TestBrowserRefreshRace|TestBrowserStalePageReloads|TestBrowserTaskCard|TestBrowserTaskThread|TestBrowserThinkingAndCards|TestBrowserUsageAndAdvice|TestBrowserWaitingTurns|TestNotebookScreenshots)$' -skip '^TestBrowserChat$|^TestBrowserChatSendStaysOnPage$|^TestBrowserComposer$|^TestBrowserComposerReconcile$|^TestBrowserComposerFocus$|^TestBrowserComposerDock$|^TestBrowserDraftStreamsFormatted$|^TestBrowserDraftIsTheMessage$|^TestBrowserTaskCard$|^TestBrowserReceiptFollowsReview$|^TestBrowserRailFollowsWork$|^TestBrowserTaskThread$|^TestBrowserAskAfterMerge$|^TestBrowserReceiptsDesktop$|^TestBrowserReceiptsTouch$|^TestBrowserConnections|^TestBrowserPasteBox$|^TestBrowserPasteCopiesItsBox$' ./internal/headless
rastrillo: budget test: go test failed
--- FAIL amadan.net/oficina/equipo/internal/headless TestBrowserThinkingAndCards
=== RUN   TestBrowserThinkingAndCards
time=2026-11-21T07:25:31.718Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-21T07:25:31.718Z level=INFO msg="startup phase done" phase=state_lock took=73µs
time=2026-11-21T07:25:31.718Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-21T07:25:31.718Z level=INFO msg="startup phase done" phase=claim_roots took=79µs
time=2026-11-21T07:25:31.718Z level=INFO msg="startup phase" phase=sweep
time=2026-11-21T07:25:31.746Z level=INFO msg="startup phase done" phase=sweep took=28.053ms
time=2026-11-21T07:25:31.746Z level=INFO msg="startup phase" phase=credentials
time=2026-11-21T07:25:31.746Z level=INFO msg="startup phase done" phase=credentials took=130µs
time=2026-11-21T07:25:31.747Z level=INFO msg="startup phase" phase=open_state
time=2026-11-21T07:25:31.788Z level=INFO msg="startup phase done" phase=open_state took=41.222ms
time=2026-11-21T07:25:31.788Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-21T07:25:31.790Z level=INFO msg=connecting host=127.0.0.1:40795 protocol=28
time=2026-11-21T07:25:31.791Z level=INFO msg=connected host=127.0.0.1:40795 took=1.288ms
time=2026-11-21T07:25:31.791Z level=INFO msg="capabilities gathering"
time=2026-11-21T07:25:31.792Z level=INFO msg="capabilities gathered" took=548µs tags=linux,claude,go
time=2026-11-21T07:25:31.793Z level=INFO msg="hello sent" protocol=28
time=2026-11-21T07:25:31.799Z level=INFO msg=welcome protocol=28 role=primary generation=1
time=2026-11-21T07:25:32.984Z level=INFO msg="connection checked" connection=claude-1 state=healthy
    browser_cards_test.go:66: waiting for (()=>{const l=document.querySelector('[equipo-thinking] [equipo-activity]');return !!l && l.textContent==='Adding oficina/sample…'})(): context deadline exceeded (last evaluation: context deadline exceeded)
--- FAIL: TestBrowserThinkingAndCards (6.82s)

--- FAIL amadan.net/oficina/equipo/internal/headless TestBrowserEmptyExplore
=== RUN   TestBrowserEmptyExplore
time=2026-11-21T07:26:30.304Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-21T07:26:30.304Z level=INFO msg="startup phase done" phase=state_lock took=68µs
time=2026-11-21T07:26:30.304Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-21T07:26:30.304Z level=INFO msg="startup phase done" phase=claim_roots took=76µs
time=2026-11-21T07:26:30.304Z level=INFO msg="startup phase" phase=sweep
time=2026-11-21T07:26:30.332Z level=INFO msg="startup phase done" phase=sweep took=27.858ms
time=2026-11-21T07:26:30.332Z level=INFO msg="startup phase" phase=credentials
time=2026-11-21T07:26:30.332Z level=INFO msg="startup phase done" phase=credentials took=119µs
time=2026-11-21T07:26:30.332Z level=INFO msg="startup phase" phase=open_state
time=2026-11-21T07:26:30.372Z level=INFO msg="startup phase done" phase=open_state took=40.03ms
time=2026-11-21T07:26:30.372Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-21T07:26:30.373Z level=INFO msg=connecting host=127.0.0.1:41799 protocol=28
time=2026-11-21T07:26:30.374Z level=INFO msg=connected host=127.0.0.1:41799 took=904µs
time=2026-11-21T07:26:30.374Z level=INFO msg="capabilities gathering"
time=2026-11-21T07:26:30.375Z level=INFO msg="capabilities gathered" took=390µs tags=linux,claude,go
time=2026-11-21T07:26:30.375Z level=INFO msg="hello sent" protocol=28
time=2026-11-21T07:26:30.380Z level=INFO msg=welcome protocol=28 role=primary generation=1
time=2026-11-21T07:26:31.461Z level=INFO msg="connection checked" connection=claude-1 state=healthy
    browser_receipts_test.go:169: waiting for [...document.querySelectorAll('[equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes("I'm your coordinator")): context deadline exceeded (last evaluation: context deadline exceeded)
--- FAIL: TestBrowserEmptyExplore (5.82s)

--- FAIL amadan.net/oficina/equipo/internal/headless (package output)
FAIL
rastrillo-budget/v1 ran 1m18.982s
FAIL	amadan.net/oficina/equipo/internal/headless	79.264s


receipt: test step 1m20.452s 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 1m18.982s amadan.net/oficina/equipo/internal/headless
receipt: slow test 11.76s amadan.net/oficina/equipo/internal/headless TestBrowserStalePageReloads
receipt: slow test 10.75s amadan.net/oficina/equipo/internal/headless TestBrowserMoveIn
receipt: slow test 9.96s amadan.net/oficina/equipo/internal/headless TestBrowserWaitingTurns
receipt: slow test 7.95s amadan.net/oficina/equipo/internal/headless TestBrowserRefreshRace
receipt: slow test 6.82s amadan.net/oficina/equipo/internal/headless TestBrowserThinkingAndCards
exit status 1
+ go test -tags browser,testbuild -timeout 15m -run '^(TestBrowserAskAfterMerge|TestBrowserChat|TestBrowserChatSendStaysOnPage|TestBrowserComposer|TestBrowserComposerDock|TestBrowserComposerFocus|TestBrowserComposerReconcile|TestBrowserConnectionsAdd|TestBrowserConnectionsAddPage|TestBrowserConnectionsConversation|TestBrowserConnectionsCopyLink|TestBrowserConnectionsEndedNote|TestBrowserConnectionsMeteredLimitRequired|TestBrowserConnectionsOpenCodeGoLimitRequired|TestBrowserConnectionsSignIn|TestBrowserConnectionsSignInSwitch|TestBrowserConnectionsToken|TestBrowserCopyContinue|TestBrowserCopySettingAndFlag|TestBrowserDraftIsTheMessage|TestBrowserDraftStreamsFormatted|TestBrowserEmptyExplore|TestBrowserMoveIn|TestBrowserNotebook|TestBrowserNotebookLook|TestBrowserPasteBox|TestBrowserPasteBoxLook|TestBrowserPasteCopiesItsBox|TestBrowserRailFollowsWork|TestBrowserReceiptFollowsReview|TestBrowserReceiptsDesktop|TestBrowserReceiptsTouch|TestBrowserRefreshRace|TestBrowserStalePageReloads|TestBrowserTaskCard|TestBrowserTaskThread|TestBrowserThinkingAndCards|TestBrowserUsageAndAdvice|TestBrowserWaitingTurns|TestNotebookScreenshots)$' -skip '^TestBrowserChat$|^TestBrowserChatSendStaysOnPage$|^TestBrowserComposer$|^TestBrowserComposerReconcile$|^TestBrowserComposerFocus$|^TestBrowserComposerDock$|^TestBrowserDraftStreamsFormatted$|^TestBrowserDraftIsTheMessage$|^TestBrowserTaskCard$|^TestBrowserReceiptFollowsReview$|^TestBrowserRailFollowsWork$|^TestBrowserTaskThread$|^TestBrowserAskAfterMerge$|^TestBrowserReceiptsDesktop$|^TestBrowserReceiptsTouch$|^TestBrowserConnections|^TestBrowserPasteBox$|^TestBrowserPasteCopiesItsBox$' -v -run '^TestBrowserEmptyExplore$|^TestBrowserThinkingAndCards$' -count=1 ./internal/headless   (retry, once)
##############################################################################
FLAKE ./internal/headless:TestBrowserEmptyExplore browser-headless-rest 1943f5cf2dfb1b613dcc9d1d617195f03b66a59a 5.82s 34.03
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
##############################################################################
FLAKE ./internal/headless:TestBrowserThinkingAndCards browser-headless-rest 1943f5cf2dfb1b613dcc9d1d617195f03b66a59a 6.82s 34.03
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
machine: 32 CPUs, load 27.82, cpu waiting 14.68%, memory waiting 0.00%, io waiting 0.31%
--- shard 22 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
browser: /opt/chromium-156.0.8078.79-1_deb13u1/chrome: Chromium 156.0.8078.79
browser lane browser-rest: ./internal/equipo
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^(TestBrowserPreviewBlocksNavigation)$' ./internal/equipo

receipt: test step 344ms against a 60s target (the gate's other steps are not in this figure)
receipt: 0 packages ran, 1 cached, 0 without tests, 0 failed
receipt: slow package 521ms amadan.net/oficina/equipo/internal/equipo
receipt: slow test 520ms amadan.net/oficina/equipo/internal/equipo TestBrowserPreviewBlocksNavigation
browser lane browser-rest: ./internal/idtest
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^(TestBrowserOficinaIDDoor)$' ./internal/idtest

receipt: test step 197ms against a 60s target (the gate's other steps are not in this figure)
receipt: 0 packages ran, 1 cached, 0 without tests, 0 failed
receipt: slow package 1.662s amadan.net/oficina/equipo/internal/idtest
receipt: slow test 1.66s 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 223ms against a 60s target (the gate's other steps are not in this figure)
receipt: 0 packages ran, 1 cached, 0 without tests, 0 failed
receipt: slow package 1.946s amadan.net/oficina/equipo/internal/plan3test
receipt: slow test 1.95s amadan.net/oficina/equipo/internal/plan3test TestTeamsHierarchyBrowser
browser lane browser-rest: ./internal/thintest
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^(TestBrowserAccessEmojiByline|TestBrowserAccessFinalOutcomes|TestBrowserAccessRequest|TestBrowserAccessReview|TestBrowserActivitySubjects|TestBrowserAutonomySettings|TestBrowserCoordinatorQueue|TestBrowserEmptyConversation|TestBrowserHousekeeping|TestBrowserInnerGallery|TestBrowserInnerScreens|TestBrowserInstantThinking|TestBrowserInstantThinkingQueued|TestBrowserMachines|TestBrowserPhoneIndex|TestBrowserPlacementQuestionAndPending|TestBrowserProjectPlacement|TestBrowserProjectsList|TestBrowserReportActionFeedback|TestBrowserReportNextSteps|TestBrowserReportThread|TestBrowserRollup|TestBrowserRosterAlignment|TestBrowserRosterDecisionStates|TestBrowserRosterQuietDay|TestBrowserRosterReports|TestBrowserRosterSetAside|TestBrowserRosterSubchat|TestBrowserRosterThinking|TestBrowserRosterVisual|TestBrowserSettingsHousekeepingGroups|TestBrowserSettingsMenu|TestBrowserSettingsRail|TestBrowserSettingsSaveBar|TestBrowserSettingsShots|TestBrowserSettingsStayOnPage|TestBrowserSettingsTeams|TestBrowserShipsButtons|TestBrowserSpecialistRows|TestBrowserSpendFollowsAnswers|TestBrowserTaskRows|TestBrowserTeamPanel|TestBrowserThinkingCycles|TestBrowserThinkingLinesClear|TestBrowserThinkingSteady|TestBrowserThinkingWords|TestBrowserTokenRowEmail|TestBrowserTrackPulse|TestBrowserTrackStarCentre)$' ./internal/thintest

receipt: test step 254ms against a 60s target (the gate's other steps are not in this figure)
receipt: 0 packages ran, 1 cached, 0 without tests, 0 failed
receipt: slow package 3m19.851s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 17.53s amadan.net/oficina/equipo/internal/thintest TestBrowserAccessRequest
receipt: slow test 14.33s amadan.net/oficina/equipo/internal/thintest TestBrowserSettingsTeams
receipt: slow test 11.95s amadan.net/oficina/equipo/internal/thintest TestBrowserThinkingCycles
receipt: slow test 10.53s amadan.net/oficina/equipo/internal/thintest TestBrowserPlacementQuestionAndPending
receipt: slow test 8.05s amadan.net/oficina/equipo/internal/thintest TestBrowserInnerScreens
machine: 32 CPUs, load 4.12, cpu waiting 1.51%, memory waiting 0.00%, io waiting 1.76%
--- 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   (53s)
ok ./internal/headless TestHeadlessConnections/A5_cancel_and_sign_out 5.43s
ok ./internal/headless TestHeadlessConnections/C4_claude_sign_in 1.40s
ok ./internal/headless TestHeadlessConnections/C5_engineering_failover 9.33s
ok ./internal/headless TestHeadlessConnections/C5_engineering_to_codex 10.04s
ok ./internal/headless TestHeadlessConnections/C5_engineering_waits 24.88s
+ 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 12.73s
ok ./internal/headless TestHeadlessConnections/C5_review_failover 14.32s
ok ./internal/headless TestHeadlessConnections/C5_review_on_codex 20.63s
ok ./internal/headless TestHeadlessConnections/C5_review_other_family_first 13.37s
+ go test -tags testbuild -timeout 15m -v -run '^TestMixedVersions$' ./internal/headless   (22s)
ok ./internal/headless TestMixedVersions 20.17s
+ go test -tags testbuild -timeout 15m -v -run '^TestCheckSandboxDeniedPathsTampering$' ./internal/runner/checks   (2s)
ok ./internal/runner/checks TestCheckSandboxDeniedPathsTampering 0.79s
+ go test -tags testbuild -timeout 15m -v -run '^TestRunnerCancelAndSupersede$' ./internal/runner/thin   (1s)
ok ./internal/runner/thin TestRunnerCancelAndSupersede 0.06s
quarantine: 0 flaked (passed on the retry), 0 failed
machine: 32 CPUs, load 37.10, cpu waiting 21.98%, memory waiting 0.00%, io waiting 0.64%
--- 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 8.176s against a 60s target (the gate's other steps are not in this figure)
receipt: 4 packages ran, 0 cached, 3 without tests, 0 failed
receipt: slow package 7.089s amadan.net/oficina/equipo/internal/runner/checks
receipt: slow package 151ms amadan.net/oficina/equipo/internal/runner/provider/claude
receipt: slow package 61ms amadan.net/oficina/equipo/internal/runner/provider/codex
receipt: slow package 1ms amadan.net/oficina/equipo/internal/runner/provider
receipt: slow package 0s amadan.net/oficina/equipo/internal/runner/provider/gotoolchain
receipt: slow test 5.16s amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPathsGoFixture
receipt: slow test 1.57s amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPaths
receipt: slow test 270ms amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPathsCache
receipt: slow test 150ms amadan.net/oficina/equipo/internal/runner/provider/claude TestDirectJournalAdapterBarrier
receipt: slow test 80ms 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.142s 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.813s amadan.net/oficina/equipo/internal/runner/containment
receipt: slow test 260ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceReadOnlyScratch
receipt: slow test 190ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceRecoveryUnavailableProof
receipt: slow test 120ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceDirectPolicyAdmission
receipt: slow test 110ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceRecoveryCleansScratch
receipt: slow test 100ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceOpenCodeBinaryAfterAttestation
machine: 32 CPUs, load 9.65, cpu waiting 4.56%, memory waiting 0.00%, io waiting 1.54%
--- 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 28.3%, load 23.65
shard 25: make runner-dead-references lanes-check build vet fmt-check budget migration-check
python3 scripts/runner-dead-references.py
reference scan: 2531 text files, 2846 matches, 0 failures
python3 scripts/ci-test.py check
lanes: 18 lanes and 5 browser lanes run every test once; 20-check@29
CGO_ENABLED=0 go build ./...
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -o /dev/null ./cmd/equipo-runner
go vet ./...
go vet -tags testbuild ./internal/runner/thin ./internal/headless
GOOS=darwin GOARCH=arm64 go vet ./cmd/equipo-runner/... ./internal/runner/... ./internal/wire/... ./internal/release/...
go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget size
budget size: 88 directories within budget
CGO_ENABLED=0 go test ./internal/equipo -run '^TestMigrationModels$' -count=1
ok  	amadan.net/oficina/equipo/internal/equipo	2.540s
machine: 32 CPUs, load 34.86, cpu waiting 20.51%, memory waiting 0.00%, io waiting 0.87%
--- 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 28.3%, load 23.65
shard 26: make staticcheck
go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 -tags browser,perf,testbuild ./...
machine: 32 CPUs, load 29.36, cpu waiting 13.53%, memory waiting 0.00%, io waiting 1.06%
--- 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 28.3%, load 23.65
shard 27: make govulncheck
go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 ./...
=== Symbol Results ===

No vulnerabilities found.

Your code is affected by 0 vulnerabilities.
This scan also found 0 vulnerabilities in packages you import and 5
vulnerabilities in modules you require, but your code doesn't appear to call
these vulnerabilities.
Use '-show verbose' for more details.
machine: 32 CPUs, load 29.36, cpu waiting 15.15%, memory waiting 0.00%, io waiting 1.03%
--- 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 28.3%, load 23.65
shard 28: make gitleaks
7:25AM INF Unknown SCM platform. Use --platform to include links in findings. host=amadan.net
7:26AM INF 1073 commits scanned.
7:26AM INF scanned ~60816913 bytes (60.82 MB) in 13.3s
7:26AM INF no leaks found
machine: 32 CPUs, load 34.86, cpu waiting 19.68%, memory waiting 0.00%, io waiting 0.90%
=== perf ===
go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -no-time -require TestPerfScreens,TestPerfBoot -tags perf -count=1 -p 1 -parallel 1 -run '^TestPerf' ./...
perf: GET /: median 1.051ms, worst 1.116ms, budget 150ms
perf: GET /api/runner/protocol: median 86µs, worst 125µs, budget 150ms
perf: GET /api/v1/account-setups/{id}: median 605µs, worst 632µs, budget 150ms
perf: GET /api/v1/accounts: median 415µs, worst 433µs, budget 150ms
perf: GET /api/v1/auth/devices: median 478µs, worst 565µs, budget 150ms
perf: GET /api/v1/budgets: median 499µs, worst 551µs, budget 150ms
perf: GET /api/v1/capabilities: median 266µs, worst 289µs, budget 150ms
perf: GET /api/v1/cards/{id}: median 1.22ms, worst 1.296ms, budget 150ms
perf: GET /api/v1/connections: median 618µs, worst 660µs, budget 150ms
perf: GET /api/v1/connections/{id}: median 600µs, worst 617µs, budget 150ms
perf: GET /api/v1/conversation: median 943µs, worst 1.007ms, budget 150ms
perf: GET /api/v1/conversation/cards: median 1.596ms, worst 1.652ms, budget 150ms
perf: GET /api/v1/coordinator: median 1.937ms, worst 2.081ms, budget 150ms
perf: GET /api/v1/invites/{id}: median 475µs, worst 515µs, budget 150ms
perf: GET /api/v1/journey: median 7.435ms, worst 7.885ms, budget 150ms
perf: GET /api/v1/me: median 422µs, worst 469µs, budget 150ms
perf: GET /api/v1/me/settings: median 508µs, worst 587µs, budget 150ms
perf: GET /api/v1/needs-you: median 7.218ms, worst 7.321ms, budget 150ms
perf: GET /api/v1/notifications: median 1.695ms, worst 1.752ms, budget 150ms
perf: GET /api/v1/onboarding: median 405µs, worst 472µs, budget 150ms
perf: GET /api/v1/people: median 452µs, worst 489µs, budget 150ms
perf: GET /api/v1/playbooks: median 605µs, worst 657µs, budget 150ms
perf: GET /api/v1/playbooks/{id}: median 545µs, worst 589µs, budget 150ms
perf: GET /api/v1/playbooks/{id}/template-diff: median 850µs, worst 908µs, budget 150ms
perf: GET /api/v1/preferences: median 767µs, worst 801µs, budget 150ms
perf: GET /api/v1/projects/{id}: median 482µs, worst 507µs, budget 150ms
perf: GET /api/v1/projects/{id}/settings: median 589µs, worst 617µs, budget 150ms
perf: GET /api/v1/roster: median 488µs, worst 516µs, budget 150ms
perf: GET /api/v1/runners/{id}: median 421µs, worst 444µs, budget 150ms
perf: GET /api/v1/specialists: median 8.102ms, worst 8.219ms, budget 150ms
perf: GET /api/v1/specialists/{id}: median 7.796ms, worst 7.994ms, budget 150ms
perf: GET /api/v1/specialists/{id}/template-diff: median 878µs, worst 935µs, budget 150ms
perf: GET /api/v1/tasks/{id}/plan: median 1.224ms, worst 1.262ms, budget 150ms
perf: GET /api/v1/tasks/{id}/thread: median 769µs, worst 876µs, budget 150ms
perf: GET /api/v1/teams: median 459µs, worst 478µs, budget 150ms
perf: GET /api/v1/templates: median 625µs, worst 662µs, budget 150ms
perf: GET /api/v1/templates/{id}: median 486µs, worst 502µs, budget 150ms
perf: GET /auth/callback: median 99µs, worst 154µs, budget 150ms
perf: GET /auth/devices/{id}: median 3.472ms, worst 5.833ms, budget 150ms
perf: GET /auth/verify: median 75µs, worst 92µs, budget 150ms
perf: GET /connections: median 3.704ms, worst 3.836ms, budget 150ms
perf: GET /conversation: median 7.279ms, worst 7.505ms, budget 150ms
perf: GET /conversation/connections: median 251µs, worst 262µs, budget 150ms
perf: GET /conversation/notebook: median 242µs, worst 262µs, budget 150ms
perf: GET /conversation/settings: median 3.863ms, worst 3.996ms, budget 150ms
perf: GET /conversation/settings/autonomy: median 3.544ms, worst 3.633ms, budget 150ms
perf: GET /conversation/settings/connections: median 6.116ms, worst 6.304ms, budget 150ms
perf: GET /conversation/settings/connections/add: median 6.239ms, worst 6.485ms, budget 150ms
perf: GET /conversation/settings/copy: median 3.588ms, worst 3.672ms, budget 150ms
perf: GET /conversation/settings/housekeeping: median 4.265ms, worst 6.629ms, budget 150ms
perf: GET /conversation/settings/machines: median 4.407ms, worst 4.586ms, budget 150ms
perf: GET /conversation/settings/machines/add: median 4.345ms, worst 4.5ms, budget 150ms
perf: GET /conversation/settings/notebook: median 3.349ms, worst 3.389ms, budget 150ms
perf: GET /conversation/settings/thinking: median 3.863ms, worst 3.978ms, budget 150ms
perf: GET /housekeeping: median 3.63ms, worst 3.74ms, budget 150ms
perf: GET /invites/new: median 587µs, worst 665µs, budget 150ms
perf: GET /invites/{id}: median 623µs, worst 643µs, budget 150ms
perf: GET /jobs: median 3.252ms, worst 3.318ms, budget 150ms
perf: GET /jobs/{id}: median 4.389ms, worst 4.497ms, budget 150ms
perf: GET /journey: median 12.199ms, worst 15.226ms, budget 150ms
perf: GET /nav/rail: median 3.217ms, worst 3.293ms, budget 150ms
perf: GET /needs-you: median 11.656ms, worst 11.951ms, budget 150ms
perf: GET /onboarding: median 4.188ms, worst 4.288ms, budget 150ms
perf: GET /people: median 3.525ms, worst 3.59ms, budget 150ms
perf: GET /playbook-suggestions/{suggestion}: median 4.971ms, worst 5.106ms, budget 150ms
perf: GET /playbooks: median 4.546ms, worst 4.701ms, budget 150ms
perf: GET /playbooks/new: median 4.644ms, worst 4.8ms, budget 150ms
perf: GET /playbooks/{id}: median 4.412ms, worst 4.473ms, budget 150ms
perf: GET /playbooks/{id}/edit: median 4.417ms, worst 4.573ms, budget 150ms
perf: GET /playbooks/{id}/template-diff: median 3.803ms, worst 5.92ms, budget 150ms
perf: GET /preferences: median 4.267ms, worst 4.409ms, budget 150ms
perf: GET /preferences/sources/{source}: median 3.971ms, worst 4.067ms, budget 150ms
perf: GET /projects: median 5.124ms, worst 5.251ms, budget 150ms
perf: GET /projects/accounts: median 3.469ms, worst 3.618ms, budget 150ms
perf: GET /projects/new: median 3.529ms, worst 3.549ms, budget 150ms
perf: GET /projects/{id}: median 10.214ms, worst 10.398ms, budget 150ms
perf: GET /projects/{id}/edit: median 3.622ms, worst 3.717ms, budget 150ms
perf: GET /runners/enrol: median 4.298ms, worst 4.609ms, budget 150ms
perf: GET /settings: median 3.361ms, worst 3.436ms, budget 150ms
perf: GET /settings/coordinator: median 5.76ms, worst 7.883ms, budget 150ms
perf: GET /settings/devices: median 3.389ms, worst 3.443ms, budget 150ms
perf: GET /settings/recovery: median 3.322ms, worst 3.454ms, budget 150ms
perf: GET /settings/recovery/release: median 3.315ms, worst 3.447ms, budget 150ms
perf: GET /settings/thinking: median 256µs, worst 271µs, budget 150ms
perf: GET /signin: median 297µs, worst 323µs, budget 150ms
perf: GET /specialists/new: median 3.32ms, worst 3.491ms, budget 150ms
perf: GET /specialists/{key}: median 10.548ms, worst 10.919ms, budget 150ms
perf: GET /specialists/{key}/edit: median 3.529ms, worst 3.683ms, budget 150ms
perf: GET /specialists/{key}/template-diff: median 3.602ms, worst 3.735ms, budget 150ms
perf: GET /tasks: median 5.031ms, worst 5.216ms, budget 150ms
perf: GET /tasks/new: median 3.156ms, worst 3.217ms, budget 150ms
perf: GET /tasks/{id}: median 5.691ms, worst 7.597ms, budget 150ms
perf: GET /tasks/{id}/merge: median 4.708ms, worst 4.82ms, budget 150ms
perf: GET /tasks/{id}/move: median 4.52ms, worst 4.608ms, budget 150ms
perf: GET /tasks/{id}/plan: median 5.545ms, worst 5.699ms, budget 150ms
perf: GET /tasks/{id}/preview: median 1.482ms, worst 1.552ms, budget 150ms
perf: GET /tasks/{id}/questions/{question}: median 5.038ms, worst 5.12ms, budget 150ms
perf: GET /tasks/{id}/rendered-change: median 4.601ms, worst 4.67ms, budget 150ms
perf: GET /tasks/{id}/rendered-change/{hash}.png: median 4.124ms, worst 4.252ms, budget 150ms
perf: GET /tasks/{id}/thread: median 7.659ms, worst 7.854ms, budget 150ms
perf: GET /team/{specialist}: median 4.19ms, worst 4.322ms, budget 150ms
perf: GET /teams: median 10.21ms, worst 10.47ms, budget 150ms
perf: GET /templates: median 3.389ms, worst 3.443ms, budget 150ms
perf: GET /usage: median 4.133ms, worst 4.211ms, budget 150ms
perf: GET /work: median 2.993ms, worst 3.076ms, budget 150ms
perf: cold boot: median 264ms of [262.797468ms 263.634253ms 264.3883ms], budget 500ms

receipt: test step 30.074s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 84 without tests, 0 failed
receipt: slow package 8.861s amadan.net/oficina/equipo/internal/equipotest
receipt: slow package 0s amadan.net/oficina/equipo/cmd/equipo-runner
receipt: slow package 0s amadan.net/oficina/equipo/cmd/equipo-tool-proxy
receipt: slow package 0s amadan.net/oficina/equipo/internal/advice
receipt: slow package 0s amadan.net/oficina/equipo/internal/attach
receipt: slow test 8.02s amadan.net/oficina/equipo/internal/equipotest TestPerfScreens
receipt: slow test 840ms amadan.net/oficina/equipo/internal/equipotest TestPerfBoot
=== cache ===
ci-box: build cache /home/ci/work/repos/oficina__equipo/cache/go-build: 2.95 GiB in 21861 files
ci-box: module cache /home/ci/work/repos/oficina__equipo/cache/go-mod: 0.87 GiB in 28256 files
diff --git a/native/OFICINA-ID-REPORT.md b/native/OFICINA-ID-REPORT.md
new file mode 100644
index 00000000..eb375418
--- /dev/null
+++ b/native/OFICINA-ID-REPORT.md
@@ -0,0 +1,496 @@
+# Oficina ID native adoption
+
+Branch: `native/oficina-id`. Implements step 5 of the approved
+[spec](../docs/superpowers/specs/2026-11-20-equipo-native-oficina-id.md).
+
+## What a person sees
+
+- First Oficina app: the kit's Welcome, passkey or email/code, then the team.
+- One readable Oficina ID and one Equipo team: straight in, with no sign-in
+ form or team address. Several identities use the kit's identity chooser.
+- Several Equipo teams: the kit's Team step. The account menu can change teams.
+- No Equipo teams: the kit's zero-teams help. Other apps' teams are filtered out.
+- Other ways to sign in: the existing address, code and browser approval.
+ Saved pairings still open. This route suspends automatic Oficina ID sign-in;
+ Sign in with Oficina ID returns to it.
+- Sign out: the kit forgets the shared identity and its app sessions; Equipo
+ forgets and best-effort revokes that identity's device credentials, detaches
+ push registration, unregisters remote notifications, clears the badge and
+ ends Live Activities. Use another goes through the kit's confirmation and
+ the same cleanup. Signing out elsewhere also clears Equipo's native account.
+- An outage during renewal keeps the conversation and pending writes, with
+ a retry notice when the kit reports the failure. Foreground and stream
+ retries recover when Home returns.
+
+The existing server contract still requires an Oficina ID linked to an active
+Equipo member. A directory entry alone grants no access; the kit shows the
+server's refusal.
+
+## Implementation
+
+`RastrilloApple` was initially pinned to Docs' `1e36aac95ed252848722926efc8ba8f9dc803216`.
+The current pin is `a18c32b3584ab5cadb8327f8f52a6186721f58dd`; see the kit update below.
+The kit selects an identity/team and mints its session. Equipo posts the session
+cookie, same-origin header, a fresh Curve25519 signing public key and device
+label to the native device endpoint. It persists the returned bearer and key
+in `DeviceAccounts`, as pairing does. Engine requests remain device bearers.
+
+Optional account metadata binds a saved device to its identity, team and the
+hash of its source session. Existing account JSON still decodes. Renewal updates
+the current `EquipoSession` without discarding its conversation or pending
+writes. The kit renews on foreground and a 24-hour clock; an updated session
+registers a replacement device and retires the previous device best effort.
+HTTP 401/403 and rejected event streams re-mint and retry once, retaining the
+original request body, revision and idempotency key. A definite permission
+refusal remains a 403 after the retry. Re-mints are coalesced and
+limited to once a minute. Late answers after leaving cannot restore an account.
+
+Both entitlement files retain the old default Keychain group first,
+`9U4A84C4WK.works.oficina.equipo`, followed by the shared identity group.
+They add the platform's App Group and webcredentials association and retain
+push entitlements. The new signing check verifies the old default group.
+
+Mac packaging already delegates to the kit's bundler, which at the pinned
+revision supports both `--provisioning-profile` and `--entitlements`, embeds the
+profile before signing and strips restricted grants from ad hoc development
+builds. The wrapper now documents these options; the gate exercises profile
+embedding and ad hoc behavior with dummy bytes and mocked signing. The existing
+configuration retains the private profile path. No profile is copied into this
+repository and verification does not read it or invoke a signing identity.
+
+## Verification
+
+Tests use `FakeOficinaIDService`, in-memory identity/device stores and
+`ScriptedTransport`. No test uses a real identity or Keychain. The initial suite
+failed on the absent adoption; additional failing tests exposed native-device
+rejection, cold-launch orphan cleanup, recovery after a Home outage and starting the
+conversation when sign-in completes in an already active scene. A final
+regression test distinguishes definite permission refusals from renewal outages.
+
+The native gate is `native/scripts/check-native.sh`: signing contract, API
+fixtures, strings, web parity, reference scan, Swift tests, Mac build and an
+unsigned iOS Simulator build. The initial gate passed 114 Swift tests, including 20 Oficina ID adoption tests.
+All 28 deliberate mutations below failed their selected check; each change was
+restored before the final gate. Two initially surviving mutations led to stronger
+assertions for local credential removal and absence of fallback Home requests.
+
+Live loopback check:
+
+```sh
+CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPersonAPINativeLiveExchange$' -count=1
+```
+
+Passed. The existing test runs fake Home and the production Equipo router on
+loopback listeners, exchanges an assertion, registers a device, checks the
+session/device expiry match and reads the engine snapshot with the bearer.
+The Swift integration suite tests the app side separately with the kit fake;
+this was not a signed app or passkey UI smoke test.
+
+## Copy reviewed by Luna
+
+Five new English strings; existing Equipo strings are unchanged:
+
+| Key | Text |
+| --- | --- |
+| `oficina.sign_in` | Sign in with Oficina ID |
+| `oficina.connecting` | Connecting to your team |
+| `oficina.device_failed` | Could not connect to this team. |
+| `oficina.retry` | Connect again |
+| `oficina.current_team` | Current team |
+
+The onboarding, Other ways to sign in, Use another Oficina ID, identity/team
+rows, replacement confirmation and identity-labelled Sign out reuse the kit's
+copy. Both existing string catalogs are generated from the English source;
+string and web-parity checks pass. Luna reviewed all five strings; her three
+edits are applied exactly. Her brief and result are copied below.
+
+## Controller follow-up
+
+Review the branch. The five strings have Luna's delegated approval. Signed-device/shared-Keychain and
+Developer ID launch checks remain with the controller: this task does not
+change profiles, identities, App Store Connect or Keychains. Nothing is merged,
+deployed or uploaded.
+
+## Deliberate mutations
+
+Each Swift mutation ran `swift test --package-path native/apple --filter` with
+its protecting test, observing an assertion failure (not a compiler failure).
+The signing mutations ran `python3 native/scripts/check-oficina-id.py`. Kit
+mutations used a temporary module copy because SwiftPM's checkout is read-only.
+
+| Guard broken | Protecting check |
+| --- | --- |
+| Same-origin header | `firstAppShowsWelcomeThenKeepsDeviceAndFreshKey` |
+| Cookie restricted to device registration | `onlyDeviceRegistrationMaySendTheSessionCookie` |
+| Submitted public key matches fresh stored key | `firstAppShowsWelcomeThenKeepsDeviceAndFreshKey` |
+| Device persisted before adoption | `firstAppShowsWelcomeThenKeepsDeviceAndFreshKey` |
+| Directory filtered for Equipo | `oneIdentityGoesStraightInAndSeveralTeamsOrNoneUseKit` |
+| Credential bound to its source session | `renewsAfter24HoursWithoutReplacingConversationSession` |
+| Late device response refused after sign-out | `lateRegistrationCannotRestoreSignedOutDevice` |
+| Orphaned credential removed on cold launch | `nativeCredentialWhoseIdentityWasRemovedCannotSurviveRelaunch` |
+| Old paired account restored | `oldSavedPairingStillLoadsWithoutOficinaID` |
+| Re-mint rate limited | `repeatedRejectionsAreRateLimitedAndKeepConversation` |
+| Device endpoint refusal re-mints | `deviceEndpointRejectionRemintsTheKitSession` |
+| Engine 403 re-mints | `rejectionsRemintOnceAndRetryWithTheNewBearer` |
+| Retry uses replacement bearer | `rejectionsRemintOnceAndRetryWithTheNewBearer` |
+| Clock waits 24 hours | `dailyTimerRenewsWhileAppStaysOpen` |
+| Equipo device revoked | `signOutStopsPushesAndRevokesThisDevice` |
+| Notifications unregistered and badge cleared | `signOutStopsPushesAndRevokesThisDevice` |
+| Kit identity signs out | `signOutStopsPushesAndRevokesThisDevice` |
+| Unavailable team retried on foreground | `foregroundRecoversAfterARejectedSessionMetAnOutage` |
+| Shared sign-out leaves fallback pairing alone | `sharedIdentityRemovalLeavesAnActiveFallbackPairingAlone` |
+| Local device removed on sign-out | `signOutStopsPushesAndRevokesThisDevice` |
+| Fallback suppresses automatic Home requests | `pairingFallbackSuspendsStraightInAndReturnResumesIt` |
+| Old default Keychain group retained | Signing check |
+| Mac profile embedded | Signing check with dummy profile and mocked signing |
+| Ad hoc build strips restricted grants | Signing check with dummy profile and mocked signing |
+| Foreground sign-in starts conversation | `signingInWhileAlreadyForegroundStartsTheConversation` |
+| Push registrar detached on sign-out | `signOutStopsPushesAndRevokesThisDevice` |
+| Definite permission refusal remains a 403 | `aDefinite403StaysARefusalAfterRemint` |
+| Event-stream authentication re-mints | `rejectedEventStreamRemintsAndPreservesCursor` |
+
+
+## Independent review fixes
+
+Astra requested changes at `7f4e1006`: a snapshot released after sign-out could
+save the departed account's bearer and private key while updating its team name;
+a failed re-mint could leave the kit unavailable with no error string and hence
+no recovery notice.
+
+The three new regression tests first failed with six assertions. The snapshot
+was held until after sign-out, then released: the old session became ready and
+saved its credential again. A held renewal plus a queued session update also
+restored metadata. The unavailable test reproduced an engine 401 followed by
+Home offline, with both error strings nil and no notice.
+
+Departing sessions now become permanently invalid before they are released.
+Snapshot completion, direct metadata application and renewal all respect that
+invalidation. Sign-out, replacement, pairing fallback and session expiry use the
+same invalidation. Native device registration retains its existing epoch/state
+check before persistence, tested with a renewal response released after sign-out.
+Pairing sign-out forgets its credential before network cleanup, so a late
+revocation cannot remove a newly saved credential at the same origin. Push
+cleanup remains in place.
+
+The mounted conversation explicitly shows the kit's unavailable title when the
+kit is unavailable, even without error strings. Its Connect again button retries
+the kit and refreshes the conversation. Recovery removes the notice.
+
+Regression commands:
+
+```sh
+swift test --package-path native/apple --filter 'OficinaIDTests/(lateSnapshot|lateRenewal|unavailableRenewal)'
+swift test --package-path native/apple --filter OficinaIDTests
+```
+
+First command before fixes: three tests failed, six assertions. The mutation
+checks remove one guard at a time and run its selected test, requiring an
+assertion failure rather than a compiler error; every mutation is restored.
+
+| Guard broken | Regression test |
+| --- | --- |
+| Invalidate departing session | lateSnapshotCannotRestoreSignedOutDevice |
+| Ignore late snapshot completion | lateSnapshotCannotRestoreSignedOutDevice |
+| Ignore direct metadata on invalid session | lateRenewalCannotRestoreSignedOutDevice |
+| Refuse renewal of invalid session | lateRenewalCannotRestoreSignedOutDevice |
+| Reject native device response from departed epoch | lateRenewalCannotRestoreSignedOutDevice |
+| Show unavailable notice without an error | unavailableRenewalShowsRecoveryWithoutAnErrorString |
+| Invalidate when switching to pairing | departingSessionCannotPersistAfterItsReplacement |
+| Invalidate when replacing team | departingSessionCannotPersistAfterItsReplacement |
+| Forget paired credential before revocation awaits | latePairingRevocationCannotRemoveANewCredential |
+
+The review gate passed `native/scripts/check-native.sh`: 119 Swift tests in
+14 suites (25 Oficina ID tests), Mac build, unsigned iOS Simulator build,
+7 fixtures, 169 strings, 23 parity entries and a clean reference scan. All nine
+review mutations above failed their intended assertion and were restored. The
+loopback native exchange test also passed again. Logs are under the ignored
+`native/build/logs` directory: `review-red.log`, `review-mutations`,
+`review-native-gate.log` and `review-loopback.log`.
+
+## Luna's brief and verdict
+
+The controller supplied this review from `gpt-5.6-luna`, with Paul's instruction
+to apply the verdicts as approved copy. Source: the controller's `luna-oid`
+brief and result, copied verbatim below. All three changes are applied in
+`strings.json` and both generated catalogs. None has a web parity mapping.
+
+### Brief
+
+# Copy review brief: Equipo's apps sign in with Oficina ID (native, 2026-11-20)
+
+Paul delegates copy review for this work to you. You are the copy editor. Your
+edits will be applied as approved copy.
+
+## Context
+
+Equipo is Oficina's team app, on iPhone and Mac. It now signs in with Oficina
+ID, the one account behind every Oficina app. It uses a shared sign-in kit
+whose own screens (Welcome, "Sign in with a passkey", email and code, choosing
+a team, "Other ways to sign in…", "Sign out", "Try again") are reviewed
+already and are not yours to change. The strings below are Equipo's own and
+appear next to the kit's. With an Oficina ID already on the device, the app
+goes straight in. The person never types anything. "Other ways to sign in…"
+opens the older pairing (type the team's address, approve a code in the
+browser).
+
+## The strings (ids are fixed, text is yours to change)
+
+- `oficina.sign_in`: a button at the bottom of the pairing screen, which
+ takes the person back to signing in with Oficina ID. Draft: `Sign in with Oficina ID`
+- `oficina.connecting`: the label of a spinner, shown after Oficina ID has
+ signed the person in while the app gets its own access to the chosen team
+ (normally a second or less). Draft: `Signing in to your team`
+- `oficina.device_failed`: an error shown on that same screen when the app
+ could not get access to the team (network or server failure). Below it are
+ a retry button, "Other ways to sign in…" and "Sign out". Draft:
+ `Could not sign in to this team. Try again.`
+- `oficina.retry`: the retry button under that error. Draft: `Try again`.
+ The kit already has a "Try again" string of its own.
+- `oficina.current_team`: the accessibility label (VoiceOver) of a checkmark
+ next to the team the app is using, in the account menu's list of teams.
+ Draft: `Current team`
+
+## House rules (Paul's, all binding)
+
+- No em dashes, ever. No exclamation marks.
+- Plain words. No jargon a reader would not know. Short. Sentence case.
+- Say what happened and what to do.
+- Use the product names exactly: Oficina ID, Equipo.
+- Do not change the facts. If something looks wrong, flag it.
+
+## Output
+
+1. A table of every string: `id | current | new (or "unchanged") | why`.
+2. A list of flagged rows: `id | problem`.
+3. One line of counts: changed, flagged, left alone.
+
+### Verdict
+
+| id | current | new | why |
+|---|---|---|---|
+| `oficina.sign_in` | Sign in with Oficina ID | unchanged | Clear and accurate. |
+| `oficina.connecting` | Signing in to your team | Connecting to your team | Oficina ID has already signed the person in. |
+| `oficina.device_failed` | Could not sign in to this team. Try again. | Could not connect to this team. | Describes the app's access problem. The retry button gives the next step. |
+| `oficina.retry` | Try again | Connect again | Avoids repeating the sign-in kit's “Try again” label. |
+| `oficina.current_team` | Current team | unchanged | Clear accessibility label. |
+
+Flagged rows:
+
+| id | problem |
+|---|---|
+| `oficina.connecting` | “Signing in” suggests the person is signing in again. |
+| `oficina.device_failed` | “Sign in” describes the wrong failure, and the sentence duplicates the retry button. |
+| `oficina.retry` | Duplicates the sign-in kit's “Try again” label. |
+
+Changed: 3. Flagged: 3. Left alone: 2.
+
+
+## Shared sign-in lifetime review
+
+Astra's re-review of `f90cf412` found two further crossings of the sign-in
+boundary: cancelled pairing could persist a late exchange or `/me` answer,
+and a departed card-answer retry could borrow the bearer of a later sign-in
+to the same identity and team.
+
+Before implementation, the new reproductions failed with 19 assertions across
+two tests (the pairing test has four cases: exchange or `/me`, each with and
+without signing out after switching to Oficina ID). The persistence source
+check also failed because there was no common guarded commit boundary.
+
+`SignInLifetime` now represents authority for one sign-in. `SignInLifetimes`
+is shared through `DeviceAccounts` by pairing, Oficina ID and the app model.
+Beginning another sign-in ends the previous token. Pairing captures its token
+synchronously when Start is tapped, before scheduling its task. An approved
+pairing hands that same token to the conversation. Native renewal retains its
+token; identity/team/origin changes, cancellation, replacement and sign-out end
+it. A token cannot be reactivated.
+
+Every Equipo-owned write of a device, private key, account index or sign-in
+route goes through `DeviceAccounts.commit`. The raw store is private. Commit
+requires the captured token to be both active and the current token. Its check
+and writes are synchronous on MainActor. Removal also matches the saved private
+key, so cleanup cannot remove another sign-in's saved account at the same
+origin. The pinned kit continues to own its shared identity store and its own
+epoch checks; Equipo does not write that store directly.
+
+Bound async flows:
+
+- Pairing start, challenge retries, exchange polling, credential persistence,
+ authenticated `/me`, and metadata persistence.
+- Native startup/restore, selection callbacks, Home renewal, rejection recovery,
+ native device registration and credential installation.
+- Snapshot/task/Needs you refresh, metadata persistence, stream setup and
+ consumption, reconnects and queued refreshes.
+- Message and thread sends, waiting-message delivery, card answers, Set aside
+ and Undo retries, and turn cancellation.
+- Retained clients and credential providers. Both the transport and its provider
+ capture the original token; matching the same identity/team after another
+ sign-in cannot authorize them.
+- Session renewal/adoption, foreground continuation and push attachment. Push
+ registration passes also retain the lifetime alongside their existing
+ generation check. A queued old attachment cannot replace the new session.
+
+A scene's daily clock is an app-level scheduler: each renewal it starts captures
+the then-current token, while an already running renewal retains its original
+token. Old registration/renewal tasks cannot clear a newer task's coalescing
+slot because those slots have distinct task IDs.
+
+Late pairing exchanges and native device mints are decoded so their abandoned
+credentials can be revoked best effort. Revocation is the sole network cleanup
+allowed after a lifetime ends: `DeviceRevocation` uses only the abandoned
+credential, never a current credential provider, and never persists anything.
+Cancelling after a pairing credential arrived also schedules revocation at once.
+
+Additional regressions cover cancellation without a replacement sign-in,
+ended/foreign persistence tokens, late transport responses and later requests,
+both write retry loops stopping without a sleep, a retained provider refusing a
+later sign-in's bearer, late push attachment, and abandoned native revocation.
+`check-sign-in-lifetime.py` is part of the native gate. It rejects raw store or
+Keychain writes outside the approved boundary and rejects an unguarded commit.
+
+Mutation commands use `swift test --package-path native/apple --filter` with
+the listed regression, or `python3 native/scripts/check-sign-in-lifetime.py`.
+Each mutation must produce an assertion failure, not a compiler error, and is
+restored before the gate:
+
+| Mutation | Regression |
+| --- | --- |
+| Pairing cancellation leaves token active | cancellingPairingAloneEndsItsLifetime |
+| New lifetime leaves previous token active | endedTransportRefusesLateResponsesAndNewRequests |
+| Commit skips lifetime validation | endedOrForeignLifetimesCannotPersistAnything |
+| Provider ignores captured lifetime | departedWriteCannotRetryWithALaterSignInsBearer |
+| Answer/visibility retries ignore ended lifetime | endedWriteLoopsDoNotWaitOrRetry |
+| Abandoned pairing is not revoked | cancelledPairingCannotOverwriteNativeSignIn |
+| Abandoned native device is not revoked | lateRenewalCannotRestoreSignedOutDevice |
+| Push attach accepts an ended lifetime | lateAttachCannotReplaceTheNextSignIn |
+| Transport ignores lifetime | endedTransportRefusesLateResponsesAndNewRequests |
+| Source has unguarded commit | check-sign-in-lifetime.py |
+| Source adds raw secret-store write | check-sign-in-lifetime.py |
+| Source adds another writer inside DeviceAccounts | check-sign-in-lifetime.py |
+| Native sign-out leaves onboarding token active | signOutBeforeRegistrationEndsThePendingLifetime |
+| App sign-out leaves onboarding token active | signOutBeforeRegistrationEndsThePendingLifetime |
+| Session removal ends the gate before forgetting | signingOutAfterTheSessionEndsStillForgetsItsCredential |
+
+The early sign-out regression first failed at both entry points, then passed.
+Cancellation-alone also tests signing out while pairing is pending, ensuring
+its staged key is removed before the token ends. All fifteen deliberate
+mutations failed their assertions and were restored. Evidence is in the ignored
+`native/build/logs/lifetime-*` logs, including the two mutation result files.
+
+No user-facing strings changed in this review. Luna's approved copy above is
+unchanged. Signed-device and shared-Keychain launch checks remain with the
+controller; this work does not touch actual profiles, identities or Keychains.
+
+The final audit also reproduced sign-out after session removal: ending the token
+before forgetting could correctly reject the later cleanup write. Session removal,
+account switching and pairing fallback now forget through the still-valid token,
+then end it. Terminal engine authentication failure likewise removes its saved
+credential before invalidation. No stale-token exception was added to commit.
+
+
+Final lifetime gate: `native/scripts/check-native.sh` passed with 128 tests in
+15 Swift suites, both native builds, the lifetime persistence scan, 7 fixtures,
+169 strings, 23 parity entries and a clean reference scan. The loopback native
+exchange test passed again. The existing push sign-out regression also passes:
+notification cleanup still runs when sessionEnded is called with no session,
+while a nested coordinator callback is handled only once.
+
+
+## Shared kit stale-grant fix
+
+Both Package.swift and Package.resolved now pin rastrillo/native main at
+`a18c32b3584ab5cadb8327f8f52a6186721f58dd`, as supplied by the controller.
+The kit binds grant-ended handling to its epoch and the grant and stamps
+identity items with their grant ID, protecting a newer sign-in from a stale
+refreshTeams response. No shared-kit source was changed in this worktree.
+
+Equipo has no custom OficinaSecureStore conformances or wrappers. Its sign-in
+tests use the kit's OficinaMemoryStore directly; the pinned implementation
+supports tagged and referenced conditional writes. No adapter changes are
+needed. The existing Equipo lifetime regressions remain in place; no additional
+Equipo regression or guard was introduced in this dependency-only update.
+No user-facing strings changed.
+
+Validation: `native/scripts/check-native.sh` passed at this pin: 128 Swift tests
+in 15 suites, Mac build, unsigned iOS Simulator build, lifetime persistence
+scan, old-default-Keychain-group and profile-embedding checks, 7 fixtures,
+169 strings, 23 parity entries and the reference scan (2527 files, 2846 matches,
+0 failures). Evidence: `native/build/logs/kit-pin-native-gate.log`.
+
+
+## Fable final-review follow-up
+
+The first two P3 findings are fixed. Leaving Oficina sign-in now removes every
+saved DeviceAccount with an oficinaIdentity and best-effort revokes each bearer,
+even before the bridge synchronizes or the kit loads an identity. Pairing-made
+accounts remain saved. The bridge observes the kit identity during onboarding,
+so confirmed Use another also performs this cleanup from Continue as and
+unavailable. Cleanup tasks retain earlier revocations when a second leave has
+nothing left to remove. All persistence still uses the lifetime-guarded commit.
+
+The app distinguishes the kit leaving from the server ending a session. A local
+sign-out or confirmed identity replacement clears endedTeam. A server-ended
+session retains the existing team notice when pairing opens. Push cleanup and
+lifetime invalidation still run in both cases. No strings changed.
+
+Tests were added before the fixes. Running
+`swift test --package-path native/apple --filter 'leavingBeforeBridgeSynchronizes|onlyServerSessionEnd|permissionRefusalDuringHomeOutage'`
+failed with 28 assertions: all eight combinations of Continue as/unavailable
+and app sign-out/bridge sign-out/replacement/pairing, the three deliberate-leave
+notice cases, and the lost kit session. The tests also retain a pairing-made
+account and require revocation of both native accounts, including another
+identity. A further three-case regression covers leaving before any identity
+has loaded. Evidence: `native/build/logs/fable-p3-red.log`,
+`fable-p3-green.log` and `fable-p3-boundaries.log` in the same log directory.
+
+### Remaining kit limitation: 403 during Home outage
+
+The third P3 is reproduced but cannot be safely fixed through the current kit
+API. At the pinned revision, OficinaIDModel.sessionRejected deletes the stored
+session before calling open. open can fall back during an outage only to the
+stored session it reads, which has already been deleted. renewIfNeeded retains
+sessions on outage but refuses to mint until the stored session is 24 hours
+old. choose/retry reuse a fresh session, so they cannot force a re-mint for a
+possibly stale 403. Equipo must not manufacture kit timestamps or restore
+session records outside the kit's grant/epoch guards.
+
+No kit source, pin or 403 behavior was changed. The needed kit change is an
+API for forced renewal that preserves a still-usable session until a replacement
+is available, or until authoritative evidence says the session/grant has ended.
+The controller must arrange that shared-kit change before this third finding
+can be closed.
+
+permissionRefusalDuringHomeOutageKeepsTheKitSession remains an executable
+reproduction using FakeOficinaIDService and ScriptedTransport. Only its missing
+stored-session assertion is marked with Swift Testing's withKnownIssue; it
+reports one known issue and fails on unexpected success when the kit is fixed.
+The surrounding assertions still require the actual 403 and the mounted
+conversation. This is documented outstanding work, not a fixed or mutation-checked
+guard. The initial unmarked assertion failure is recorded in the red log.
+
+
+Eight deliberate mutations were caught by assertion failures, then restored:
+
+| Mutation | Regression |
+| --- | --- |
+| Remove only the tracked identity's accounts | leavingBeforeBridgeSynchronizesForgetsEveryNativeAccount |
+| Stop observing identity before synchronization | leavingBeforeBridgeSynchronizesForgetsEveryNativeAccount |
+| Gate bridge sign-out on a loaded identity | leavingBeforeIdentityLoadsForgetsTheSavedBearer |
+| Gate pairing fallback cleanup on a loaded identity | leavingBeforeIdentityLoadsForgetsTheSavedBearer |
+| Route app sign-out away from the bridge before identity loads | leavingBeforeIdentityLoadsForgetsTheSavedBearer |
+| Skip saved native bearer revocation | leavingBeforeBridgeSynchronizesForgetsEveryNativeAccount |
+| Report kit leave as server-ended | onlyServerSessionEndShowsTheEndedTeamNotice |
+| Clear the notice for a real server-ended session | onlyServerSessionEndShowsTheEndedTeamNotice |
+
+Each mutation ran `swift test --package-path native/apple --filter` with the
+listed regression. All eight returned an assertion failure, not a build failure.
+Evidence: `native/build/logs/fable-p3-mutations/results.json` and its sibling logs.
+
+
+Final native gate: `native/scripts/check-native.sh` passed with 132 tests in
+15 suites and the one explicitly recorded kit issue described above. The Mac
+and unsigned iOS Simulator builds, lifetime persistence scan, old default
+Keychain group and profile checks, 7 fixtures, 169 strings, 23 parity entries
+and reference scan all passed. Evidence: `native/build/logs/fable-p3-native-gate.log`.
+The original fifteen lifetime mutations and regressions remain in place.
+No actual Keychain, provisioning profile or signing identity was changed.
diff --git a/native/apple/Package.resolved b/native/apple/Package.resolved
index 1e58fce5..68c3f531 100644
--- a/native/apple/Package.resolved
+++ b/native/apple/Package.resolved
@@ -1,12 +1,12 @@
{
- "originHash" : "2a6af65c7a784d5b21d8800f9821f79e73fca703bcece0ae1f22243bdbe1c584",
+ "originHash" : "f8647e79c0ca0df01bafdd02c9beb5a09a910e056cadf98437c25797abe06489",
"pins" : [
{
"identity" : "native",
"kind" : "remoteSourceControl",
"location" : "https://amadan.net/rastrillo/native",
"state" : {
- "revision" : "f1c7a14db2ddb8960afabc8268cd92c490543397"
+ "revision" : "a18c32b3584ab5cadb8327f8f52a6186721f58dd"
}
},
{
diff --git a/native/apple/Package.swift b/native/apple/Package.swift
index 493bbdb4..54b5e4d3 100644
--- a/native/apple/Package.swift
+++ b/native/apple/Package.swift
@@ -2,10 +2,10 @@
import PackageDescription
import Foundation
-// rastrillo/native at the revision Docs uses. OFICINA_NATIVE_PACKAGE_PATH
+// rastrillo/native with grant-bound sign-in lifetime handling. OFICINA_NATIVE_PACKAGE_PATH
// points at a local checkout instead, for work on the kit itself.
let sharedNative: Package.Dependency = ProcessInfo.processInfo.environment["OFICINA_NATIVE_PACKAGE_PATH"].map { .package(name: "native", path: $0) }
- ?? .package(url: "https://amadan.net/rastrillo/native", revision: "f1c7a14db2ddb8960afabc8268cd92c490543397")
+ ?? .package(url: "https://amadan.net/rastrillo/native", revision: "a18c32b3584ab5cadb8327f8f52a6186721f58dd")
let package = Package(
name: "EquipoNative",
@@ -32,7 +32,7 @@ let package = Package(
.product(name: "RastrilloMacUpdates", package: "native", condition: .when(platforms: [.macOS]))],
path: "Sources/EquipoMac"),
.testTarget(name: "EquipoKitTests",
- dependencies: ["EquipoKit", "EquipoActivity", .product(name: "RastrilloNative", package: "native")],
+ dependencies: ["EquipoKit", "EquipoActivity", .product(name: "RastrilloTestSupport", package: "native"), .product(name: "RastrilloNative", package: "native")],
resources: [.copy("Fixtures")]),
]
)
diff --git a/native/apple/Sources/EquipoActivity/Resources/Localizable.xcstrings b/native/apple/Sources/EquipoActivity/Resources/Localizable.xcstrings
index 3387547a..f280a180 100644
--- a/native/apple/Sources/EquipoActivity/Resources/Localizable.xcstrings
+++ b/native/apple/Sources/EquipoActivity/Resources/Localizable.xcstrings
@@ -706,6 +706,61 @@
}
}
},
+ "oficina.connecting": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Connecting to your team"
+ }
+ }
+ }
+ },
+ "oficina.current_team": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Current team"
+ }
+ }
+ }
+ },
+ "oficina.device_failed": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Could not connect to this team."
+ }
+ }
+ }
+ },
+ "oficina.retry": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Connect again"
+ }
+ }
+ }
+ },
+ "oficina.sign_in": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Sign in with Oficina ID"
+ }
+ }
+ }
+ },
"pairing.approve_lede": {
"extractionState": "manual",
"localizations": {
diff --git a/native/apple/Sources/EquipoKit/API/Transport.swift b/native/apple/Sources/EquipoKit/API/Transport.swift
index e383ef61..e7501610 100644
--- a/native/apple/Sources/EquipoKit/API/Transport.swift
+++ b/native/apple/Sources/EquipoKit/API/Transport.swift
@@ -10,10 +10,12 @@ public struct APIRequest: Sendable, Equatable {
public var bearer: String?
public var idempotencyKey: String?
public var ifMatch: Int64?
+ public var nativeSession: NativeSession?
public init(_ method: String, _ path: String, query: [URLQueryItem] = [], body: Data? = nil,
- bearer: String? = nil, idempotencyKey: String? = nil, ifMatch: Int64? = nil) {
+ bearer: String? = nil, idempotencyKey: String? = nil, ifMatch: Int64? = nil, nativeSession: NativeSession? = nil) {
self.method = method; self.path = path; self.query = query; self.body = body
+ self.nativeSession = nativeSession
self.bearer = bearer; self.idempotencyKey = idempotencyKey; self.ifMatch = ifMatch
}
@@ -34,6 +36,13 @@ public struct APIRequest: Sendable, Equatable {
r.httpBody = body
r.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
+ if let nativeSession {
+ // Only the bridge may send a cookie. Engine and pairing requests
+ // stay bearer-only, including after renewal.
+ guard path == "/auth/devices/native", method == "POST", bearer == nil else { throw EquipoAPIError.badOrigin }
+ r.setValue(origin.absoluteString, forHTTPHeaderField: "Origin")
+ r.setValue("\(nativeSession.name)=\(nativeSession.value)", forHTTPHeaderField: "Cookie")
+ }
if let bearer { r.setValue("Bearer \(bearer)", forHTTPHeaderField: "Authorization") }
if let idempotencyKey { r.setValue(idempotencyKey, forHTTPHeaderField: "Idempotency-Key") }
if let ifMatch { r.setValue("\"\(ifMatch)\"", forHTTPHeaderField: "If-Match") }
diff --git a/native/apple/Sources/EquipoKit/OficinaID/EquipoOficinaID.swift b/native/apple/Sources/EquipoKit/OficinaID/EquipoOficinaID.swift
new file mode 100644
index 00000000..29c3ca80
--- /dev/null
+++ b/native/apple/Sources/EquipoKit/OficinaID/EquipoOficinaID.swift
@@ -0,0 +1,292 @@
+import Combine
+import CryptoKit
+import Foundation
+import Observation
+import RastrilloApple
+
+/// The kit owns identity, team choice and session renewal. Equipo turns
+/// that session into its existing device bearer and keeps it in DeviceAccounts.
+@MainActor @Observable
+public final class EquipoOficinaID {
+ public let model: OficinaIDModel
+ public private(set) var error: String?
+ public private(set) var busy = false
+ public private(set) var account: DeviceAccount?
+ public var suspended = false
+ @ObservationIgnored var onAccount: ((DeviceAccount, EquipoTransport, SignInLifetime) -> Void)?
+ @ObservationIgnored var onLeave: (() -> Void)?
+ @ObservationIgnored private var watch: AnyCancellable?
+ @ObservationIgnored private var registration: (state: OficinaSignedIn, lifetime: SignInLifetime, id: UUID, task: Task<Void, Never>)?
+ @ObservationIgnored public private(set) var cleanup: Task<Void, Never>?
+ @ObservationIgnored private var renewal: (id: UUID, task: Task<Void, Never>)?
+ private let accounts: DeviceAccounts
+ private let makeTransport: @Sendable (URL) -> EquipoTransport
+ private let label: () -> String
+ private let now: @Sendable () -> Date
+ private var started = false
+ private var lifetime: SignInLifetime?
+ private var selected: String?
+ private var lastRejection: Date?
+ private var identityID: String?
+
+ nonisolated public static let configuration = OficinaIDConfiguration(app: "equipo", appName: "Equipo")
+ nonisolated public static var appGroup: String {
+ #if os(macOS)
+ "9U4A84C4WK.works.oficina"
+ #else
+ "group.works.oficina"
+ #endif
+ }
+
+ public init(model: OficinaIDModel, accounts: DeviceAccounts,
+ makeTransport: @escaping @Sendable (URL) -> EquipoTransport,
+ now: @escaping @Sendable () -> Date = Date.init, label: @escaping () -> String) {
+ self.model = model; self.accounts = accounts; self.makeTransport = makeTransport
+ self.now = now; self.label = label
+ lifetime = accounts.lifetimes.current
+ watch = model.$step.sink { [weak self] step in
+ self?.stepChanged(step)
+ }
+ }
+
+ public func start() async {
+ guard !started else { return }
+ started = true
+ if suspended { model.suspendStraightIn() }
+ let lifetime = accounts.lifetimes.current
+ await model.start()
+ guard lifetime.isActive else { return }
+ // Another app may have signed this identity out while Equipo was
+ // closed. A successful negative lookup removes its background bearer;
+ // an unreadable Keychain leaves it alone.
+ for saved in accounts.all() {
+ if let identity = saved.oficinaIdentity, (try? model.store.hasIdentity(identity)) == false {
+ try? accounts.commit(.remove(saved), lifetime: lifetime)
+ Task { await self.revoke(saved) }
+ }
+ }
+ await model.refreshTeams()
+ guard lifetime.isActive else { return }
+ await synchronize()
+ }
+
+ private func stepChanged(_ step: OficinaIDModel.Step) {
+ // @Published delivers before step is set. Invalidate synchronously,
+ // then read the new step in a task. A late device answer cannot revive it.
+ let previousIdentity = identityID
+ identityID = model.identity?.id
+ if identityID == nil, previousIdentity != nil { forget() }
+ switch step {
+ case .signedIn(let state):
+ guard !suspended else { return }
+ let selection = state.identity.id + "|" + state.team.sqid + "|" + state.origin.absoluteString
+ if selected != nil && selected != selection || lifetime?.isActive != true || lifetime !== accounts.lifetimes.current {
+ onLeave?()
+ lifetime?.end()
+ registration?.task.cancel(); registration = nil
+ renewal?.task.cancel(); renewal = nil
+ lastRejection = nil; busy = false
+ lifetime = accounts.lifetimes.begin()
+ }
+ selected = selection
+ guard let lifetime else { return }
+ Task { [weak self] in
+ guard lifetime.isActive else { return }
+ await self?.synchronize()
+ }
+ case .loading, .unavailable: break // Keep the conversation over an outage.
+ default:
+ if selected != nil {
+ onLeave?()
+ lifetime?.end(); lifetime = nil; selected = nil
+ account = nil
+ }
+ }
+ }
+
+ /// Also called after model actions, so their callers can await the bridge.
+ public func synchronize() async {
+ guard !suspended, let lifetime, lifetime.isActive, case .signedIn(let state) = model.step else { return }
+ if let registration, registration.state == state, registration.lifetime === lifetime {
+ await registration.task.value; return
+ }
+ let id = UUID()
+ let waiting = Task { [weak self] in
+ guard let self else { return }
+ await self.register(state, lifetime: lifetime)
+ }
+ registration = (state, lifetime, id, waiting)
+ await waiting.value
+ if registration?.id == id { registration = nil }
+ }
+
+ private func register(_ state: OficinaSignedIn, lifetime: SignInLifetime) async {
+ let hash = Self.hash(state.session.value)
+ if let saved = accounts.all().first(where: {
+ $0.origin == state.origin && $0.oficinaIdentity == state.identity.id && $0.oficinaTeam == state.team.sqid
+ && $0.oficinaSessionHash == hash && $0.isUsable(now: now())
+ }) {
+ guard current(state, lifetime: lifetime) else { return }
+ install(saved, lifetime: lifetime)
+ return
+ }
+ busy = true; error = nil
+ defer { if self.lifetime === lifetime { busy = false } }
+ // Fresh Curve25519 signing key, exactly as pairing creates one.
+ var next = DeviceAccount.new(origin: state.origin, label: label())
+ next.oficinaIdentity = state.identity.id
+ next.oficinaTeam = state.team.sqid
+ next.oficinaSessionHash = hash
+ next.teamName = state.team.name
+ let previous = accounts.all().first { $0.origin == state.origin }
+ do {
+ try lifetime.check()
+ let body = try EquipoJSON.encoder.encode(["public_key": try next.publicKey(), "label": next.label])
+ let transport = makeTransport(state.origin)
+ next.credential = try await EquipoClient(transport: transport, token: nil).send(
+ APIRequest("POST", "/auth/devices/native", body: body, nativeSession: state.session))
+ guard current(state, lifetime: lifetime) else { await revoke(next); return }
+ do { try accounts.commit(.save(next), lifetime: lifetime) }
+ catch { await revoke(next); throw error }
+ install(next, lifetime: lifetime)
+ if let previous, previous.credential?.id != next.credential?.id {
+ Task { await self.revoke(previous) }
+ }
+ } catch {
+ guard current(state, lifetime: lifetime) else { return }
+ self.error = String(localized: "oficina.device_failed", bundle: .module)
+ if let api = error as? EquipoAPIError, api.status == 401 || api.status == 403,
+ lastRejection.map({ now().timeIntervalSince($0) >= 60 }) ?? true {
+ lastRejection = now()
+ await model.refreshTeams(maxAge: 0)
+ guard current(state, lifetime: lifetime) else { return }
+ await model.sessionRejected()
+ // A new kit session gets a new registration. Never await our
+ // own in-flight registration when Home left the step unchanged.
+ if lifetime.isActive, model.step != .signedIn(state) { await synchronize() }
+ }
+ }
+ }
+
+ private func current(_ state: OficinaSignedIn, lifetime: SignInLifetime) -> Bool {
+ !suspended && lifetime.isActive && self.lifetime === lifetime && model.step == .signedIn(state)
+ }
+
+ private func install(_ next: DeviceAccount, lifetime: SignInLifetime) {
+ guard lifetime.isActive else { return }
+ error = nil
+ guard account != next else { return }
+ account = next
+ let origin = next.origin, identity = next.oficinaIdentity, team = next.oficinaTeam
+ let transport = EquipoRenewingTransport(inner: makeTransport(origin), lifetime: lifetime, credential: { [weak self] in
+ guard let self, lifetime.isActive, self.lifetime === lifetime, !self.suspended, self.model.identity?.id == identity,
+ let current = self.account, current.origin == origin, current.oficinaTeam == team else { return nil }
+ return current.credential?.token
+ }, rejected: { [weak self] in
+ guard lifetime.isActive else { return }
+ await self?.rejected()
+ })
+ onAccount?(next, transport, lifetime)
+ }
+
+ public func renewIfNeeded() async {
+ guard !suspended, let lifetime, lifetime.isActive else { return }
+ if let renewal { await renewal.task.value; return }
+ let id = UUID()
+ let task = Task {
+ guard lifetime.isActive else { return }
+ if case .unavailable = model.step { await model.retry() }
+ else { await model.renewIfNeeded() }
+ guard lifetime.isActive else { return }
+ await synchronize()
+ }
+ renewal = (id, task)
+ await task.value
+ if renewal?.id == id { renewal = nil }
+ }
+
+ /// Coalesced and limited to once a minute within the same sign-in.
+ func rejected() async {
+ guard !suspended, let lifetime, lifetime.isActive else { return }
+ if let renewal { await renewal.task.value; return }
+ if let lastRejection, now().timeIntervalSince(lastRejection) < 60 { return }
+ lastRejection = now()
+ let id = UUID()
+ let task = Task {
+ guard lifetime.isActive else { return }
+ await model.refreshTeams(maxAge: 0)
+ guard lifetime.isActive else { return }
+ if case .unavailable = model.step { await model.retry() }
+ else { await model.sessionRejected() }
+ guard lifetime.isActive else { return }
+ await synchronize()
+ }
+ renewal = (id, task)
+ await task.value
+ if renewal?.id == id { renewal = nil }
+ }
+
+ /// Leave Equipo's native account locally before any network cleanup.
+ /// The kit may also reach this through Use another or another app's sign-out.
+ /// Saved native bearers can predate this bridge's first synchronization.
+ /// Remove all of them, while leaving pairing-made accounts alone.
+ private func forget() {
+ registration?.task.cancel(); registration = nil
+ renewal?.task.cancel(); renewal = nil
+ let removalLifetime = accounts.lifetimes.current
+ let old = accounts.all().filter { $0.oficinaIdentity != nil }
+ for account in old { try? accounts.commit(.remove(account), lifetime: removalLifetime) }
+ lifetime?.end(); lifetime = nil; selected = nil
+ busy = false
+ account = nil; error = nil; lastRejection = nil
+ onLeave?()
+ if !old.isEmpty {
+ let previousCleanup = cleanup
+ cleanup = Task {
+ await previousCleanup?.value
+ for account in old { await self.revoke(account) }
+ }
+ }
+ }
+
+ /// The app removes the conversation while this lifetime still owns its
+ /// persistence. Forget first; ending the token closes the write gate.
+ func sessionEnded(lifetime: SignInLifetime) {
+ guard self.lifetime === lifetime, lifetime.isActive else { return }
+ forget()
+ }
+
+ public func signOut() {
+ identityID = nil
+ forget()
+ lifetime?.end(); lifetime = nil; selected = nil
+ model.signOut()
+ }
+
+ public func pause() {
+ suspended = true
+ identityID = nil
+ forget()
+ lifetime?.end(); lifetime = nil; selected = nil
+ registration?.task.cancel(); registration = nil
+ renewal?.task.cancel(); renewal = nil
+ model.suspendStraightIn()
+ account = nil; busy = false; lastRejection = nil
+ }
+
+ public func resume() async {
+ suspended = false
+ let lifetime = accounts.lifetimes.begin()
+ self.lifetime = lifetime
+ try? accounts.commit(.route("oficina"), lifetime: lifetime)
+ await model.resumeStraightIn()
+ guard lifetime.isActive else { return }
+ await synchronize()
+ }
+
+ private func revoke(_ account: DeviceAccount) async {
+ await DeviceRevocation.revoke(account, transport: makeTransport(account.origin))
+ }
+
+ private static func hash(_ value: String) -> String { Base64URL.encode(Data(SHA256.hash(data: Data(value.utf8)))) }
+}
diff --git a/native/apple/Sources/EquipoKit/OficinaID/EquipoRenewingTransport.swift b/native/apple/Sources/EquipoKit/OficinaID/EquipoRenewingTransport.swift
new file mode 100644
index 00000000..5a65889b
--- /dev/null
+++ b/native/apple/Sources/EquipoKit/OficinaID/EquipoRenewingTransport.swift
@@ -0,0 +1,53 @@
+import Foundation
+
+/// Supplies the current device bearer on every request, including requests
+/// retained by a conversation across renewal. Cookies never reach the engine.
+struct EquipoRenewingTransport: EquipoTransport {
+ let inner: EquipoTransport
+ let lifetime: SignInLifetime
+ let credential: @MainActor @Sendable () -> String?
+ let rejected: @MainActor @Sendable () async -> Void
+ var origin: URL { inner.origin }
+
+ private func authorized(_ request: APIRequest) async throws -> APIRequest {
+ try await lifetime.check()
+ guard let token = await credential() else { throw EquipoAPIError.signedOut }
+ var request = request
+ request.bearer = token
+ return request
+ }
+
+ func send(_ request: APIRequest) async throws -> APIResponse {
+ let first = try await authorized(request)
+ let response = try await inner.send(first)
+ guard response.status == 401 || response.status == 403 else { return response }
+ try await lifetime.check()
+ await rejected()
+ let retry = try await authorized(request)
+ guard retry.bearer != first.bearer else {
+ // A permission refusal is definite. An ended credential during
+ // a Home outage keeps pending writes until a later renewal.
+ if response.status == 403 { return response }
+ throw EquipoAPIError.offline
+ }
+ let retried = try await inner.send(retry)
+ guard retried.status != 401 else { throw EquipoAPIError.offline }
+ return retried
+ }
+
+ func lines(_ request: APIRequest) async throws -> AsyncThrowingStream<String, Error> {
+ let first = try await authorized(request)
+ do { return try await inner.lines(first) }
+ catch let error as EquipoAPIError where error.status == 401 || error.status == 403 {
+ try await lifetime.check()
+ await rejected()
+ let retry = try await authorized(request)
+ guard retry.bearer != first.bearer else {
+ if error.status == 403 { throw error }
+ throw EquipoAPIError.offline
+ }
+ do { return try await inner.lines(retry) }
+ catch let error as EquipoAPIError where error.status == 401 { throw EquipoAPIError.offline }
+ }
+ }
+}
diff --git a/native/apple/Sources/EquipoKit/Pairing/DeviceAccount.swift b/native/apple/Sources/EquipoKit/Pairing/DeviceAccount.swift
index 7ebb9afd..bab1b818 100644
--- a/native/apple/Sources/EquipoKit/Pairing/DeviceAccount.swift
+++ b/native/apple/Sources/EquipoKit/Pairing/DeviceAccount.swift
@@ -11,6 +11,11 @@ public struct DeviceAccount: Codable, Sendable, Equatable {
public var credential: DeviceCredential?
public var teamName: String?
public var address: String?
+ /// Absent on saved pairings from before Oficina ID. The session hash
+ /// binds this bearer to the kit session that minted it, without a second cookie.
+ public var oficinaIdentity: String?
+ public var oficinaTeam: String?
+ public var oficinaSessionHash: String?
/// Throws if the stored key is damaged; pairing then starts again with a new one.
public func signingKey() throws -> Curve25519.Signing.PrivateKey { try .init(rawRepresentation: keySeed) }
@@ -25,23 +30,40 @@ public struct DeviceAccount: Codable, Sendable, Equatable {
/// The paired teams on this device. Slice 1 uses one; the store keeps the
/// list shape so several teams can follow.
public struct DeviceAccounts: Sendable {
- let store: SecretStore
+ private let store: SecretStore
static let index = "accounts"
- public init(store: SecretStore) { self.store = store }
+ public let lifetimes: SignInLifetimes
+ @MainActor public init(store: SecretStore) { self.store = store; lifetimes = SignInLifetimes() }
+ var signInRoute: String? { store.read("signin.route").flatMap { String(data: $0, encoding: .utf8) } }
+
+ public enum Change {
+ case save(DeviceAccount)
+ case remove(DeviceAccount)
+ case route(String)
+ }
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) } }
}
- public func save(_ account: DeviceAccount) throws {
- try store.write(try JSONEncoder().encode(account), account: account.origin.absoluteString)
- var origins = all().map(\.origin)
- if !origins.contains(account.origin) { origins.append(account.origin) }
- try store.write(try JSONEncoder().encode(origins), account: Self.index)
- }
- public func remove(_ origin: URL) {
- store.remove(origin.absoluteString)
- let origins = all().map(\.origin).filter { $0 != origin }
- try? store.write((try? JSONEncoder().encode(origins)) ?? Data("[]".utf8), account: Self.index)
+ /// Every device, private key, index and route write passes this boundary.
+ /// Check and write are synchronous on MainActor, so ending a lifetime
+ /// cannot interleave with persistence. Removal also matches the saved key.
+ @MainActor public func commit(_ change: Change, lifetime: SignInLifetime) throws {
+ try lifetimes.require(lifetime)
+ switch change {
+ case .save(let account):
+ try store.write(try JSONEncoder().encode(account), account: account.origin.absoluteString)
+ var origins = all().map(\.origin)
+ if !origins.contains(account.origin) { origins.append(account.origin) }
+ try store.write(try JSONEncoder().encode(origins), account: Self.index)
+ case .remove(let account):
+ guard all().contains(where: { $0.origin == account.origin && $0.keySeed == account.keySeed }) else { return }
+ 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 .route(let route):
+ try store.write(Data(route.utf8), account: "signin.route")
+ }
}
}
diff --git a/native/apple/Sources/EquipoKit/Pairing/Pairing.swift b/native/apple/Sources/EquipoKit/Pairing/Pairing.swift
index 502034d1..6c77d81f 100644
--- a/native/apple/Sources/EquipoKit/Pairing/Pairing.swift
+++ b/native/apple/Sources/EquipoKit/Pairing/Pairing.swift
@@ -29,6 +29,10 @@ public final class PairingModel {
private let sleep: @Sendable (Duration) async throws -> Void
private let now: @Sendable () -> Date
private var task: Task<Void, Never>?
+ private(set) var lifetime: SignInLifetime?
+ private var pendingAccount: DeviceAccount?
+ private var retiring: Set<Data> = []
+ public private(set) var cleanup: Task<Void, Never>?
/// The floor the API sets; the server enforces it too.
public static let minimumInterval: Duration = .seconds(5)
@@ -62,44 +66,83 @@ public final class PairingModel {
}
public func start(origin: URL, label: String) {
- task?.cancel()
- task = Task { await run(origin: origin, label: label) }
+ let lifetime = begin()
+ task = Task { await run(origin: origin, label: label, lifetime: lifetime) }
+ }
+
+ private func begin() -> SignInLifetime {
+ cancel()
+ let lifetime = accounts.lifetimes.begin()
+ self.lifetime = lifetime
+ return lifetime
+ }
+
+ /// Transfers this exact lifetime to the conversation without ending it.
+ func handoff() -> SignInLifetime? {
+ guard let lifetime, lifetime.isActive else { return nil }
+ self.lifetime = nil; pendingAccount = nil; task = nil
+ return lifetime
+ }
+
+ public func cancel() {
+ if let lifetime {
+ if let pendingAccount {
+ try? accounts.commit(.remove(pendingAccount), lifetime: lifetime)
+ retire(pendingAccount)
+ }
+ lifetime.end()
+ }
+ task?.cancel(); task = nil; lifetime = nil
+ pendingAccount = nil; account = nil; step = .enterTeam
}
- public func cancel() { task?.cancel(); task = nil; step = .enterTeam }
func run(origin: URL, label: String) async {
+ await run(origin: origin, label: label, lifetime: begin())
+ }
+
+ private func run(origin: URL, label: String, lifetime: SignInLifetime) async {
+ guard lifetime.isActive else { return }
step = .requesting
- // The key is saved before the server hears of it, so a crash after
- // the challenge never strands a credential bound to a lost key.
var account = accounts.all().first { $0.origin == origin && $0.credential == nil } ?? .new(origin: origin, label: label)
+ pendingAccount = account
do {
- try accounts.save(account)
+ try accounts.commit(.save(account), lifetime: lifetime)
let client = EquipoClient(transport: makeTransport(origin), token: nil)
let begin = try PendingWrite.json(["public_key": try account.publicKey(), "label": label])
- let challenge: DeviceChallenge = try await retrying { try await client.beginDevice(begin) }
+ let challenge: DeviceChallenge = try await retrying(lifetime: lifetime) { try await client.beginDevice(begin) }
+ try lifetime.check()
guard let verification = URL(string: challenge.verificationUri), Self.verificationIsTrusted(verification, origin: origin) else {
throw PairingError.badChallenge
}
step = .waiting(code: challenge.userCode, verification: verification, expires: challenge.expiresAt)
let proof = try PendingWrite.json(DeviceProof.body(for: challenge, key: try account.signingKey(), nonce: DeviceProof.nonce()))
var interval = max(Self.minimumInterval, .seconds(challenge.pollIntervalSeconds))
- while !Task.isCancelled {
+ while lifetime.isActive && !Task.isCancelled {
if now() >= challenge.expiresAt { step = .expired; return }
try await sleep(interval)
+ try lifetime.check()
do {
- let credential = try await client.exchangeDevice(proof)
- account.credential = credential
- // The server now holds a live device: keep it before anything else can fail.
- try accounts.save(account)
+ // Decode a late minted credential before checking the
+ // lifetime so it can be revoked with its own bearer.
+ account.credential = try await client.exchangeDevice(proof)
+ guard lifetime.isActive else { retire(account); return }
+ do { try accounts.commit(.save(account), lifetime: lifetime) }
+ catch { retire(account); throw error }
+ pendingAccount = account
self.account = account
- if let me = try? await EquipoClient(transport: makeTransport(origin), token: credential.token).me() {
+ let transport = LifetimeTransport(inner: makeTransport(origin), lifetime: lifetime)
+ let me = try? await EquipoClient(transport: transport, token: account.credential?.token).me()
+ guard lifetime.isActive else { retire(account); return }
+ if let me {
account.teamName = me.teamName; account.address = me.person.address
- try? accounts.save(account)
+ try accounts.commit(.save(account), lifetime: lifetime)
+ pendingAccount = account
self.account = account
}
step = .approved(teamName: account.teamName ?? origin.host ?? "")
return
} catch let error as EquipoAPIError {
+ try lifetime.check()
switch error.code {
case "authorization_pending": continue
case "slow_down": interval += .seconds(5)
@@ -113,20 +156,32 @@ public final class PairingModel {
} catch is CancellationError {
return
} catch let error as EquipoAPIError {
+ guard lifetime.isActive else { return }
step = .failed(Self.describe(error))
} catch {
+ guard lifetime.isActive else { return }
step = .failed(String(localized: "pairing.failed", bundle: .module))
}
}
- private func retrying<T: Sendable>(_ attempt: @Sendable () async throws -> T) async throws -> T {
+ private func retrying<T: Sendable>(lifetime: SignInLifetime, _ attempt: @Sendable () async throws -> T) async throws -> T {
var tries = 0
while true {
+ try lifetime.check()
do { return try await attempt() }
- catch EquipoAPIError.offline where tries < 2 { tries += 1; try await sleep(.seconds(2)) }
+ catch EquipoAPIError.offline where tries < 2 {
+ try lifetime.check()
+ tries += 1; try await sleep(.seconds(2))
+ }
}
}
+ private func retire(_ account: DeviceAccount) {
+ guard account.credential != nil, retiring.insert(account.keySeed).inserted else { return }
+ let transport = makeTransport(account.origin)
+ cleanup = Task { await DeviceRevocation.revoke(account, transport: transport) }
+ }
+
static func describe(_ error: EquipoAPIError) -> String {
switch error {
case .offline: return String(localized: "pairing.offline", bundle: .module)
diff --git a/native/apple/Sources/EquipoKit/Push/PhoneDelegate.swift b/native/apple/Sources/EquipoKit/Push/PhoneDelegate.swift
index 7a52911a..ad500d50 100644
--- a/native/apple/Sources/EquipoKit/Push/PhoneDelegate.swift
+++ b/native/apple/Sources/EquipoKit/Push/PhoneDelegate.swift
@@ -13,6 +13,9 @@ public final class EquipoPhoneDelegate: NSObject, UIApplicationDelegate {
public func application(_ application: UIApplication, didFinishLaunchingWithOptions options: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
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
+ // shared identity and attach its device before sending activity tokens.
+ Task { await model.start() }
return true
}
diff --git a/native/apple/Sources/EquipoKit/Push/PushRegistrar.swift b/native/apple/Sources/EquipoKit/Push/PushRegistrar.swift
index 9743851b..c9754d3a 100644
--- a/native/apple/Sources/EquipoKit/Push/PushRegistrar.swift
+++ b/native/apple/Sources/EquipoKit/Push/PushRegistrar.swift
@@ -14,6 +14,7 @@ public final class PushRegistrar {
public private(set) var startToken: String?
private var client: EquipoClient?
+ private var lifetime: SignInLifetime?
/// The registration the current session's server has, by bearer.
private var accepted: (bearer: String, body: PushRegistrationBody)?
/// A registration the server refused as invalid: not sent again as is.
@@ -43,8 +44,9 @@ 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?) async {
- if client?.token != self.client?.token {
+ public func attach(_ client: EquipoClient?, lifetime: SignInLifetime? = nil) async {
+ guard lifetime?.isActive != false else { return }
+ if client?.token != self.client?.token || lifetime !== self.lifetime {
generation += 1
// Another session (another team, a new credential, or none): it
// keeps only the activities its own instance started. At launch
@@ -59,6 +61,7 @@ public final class PushRegistrar {
onSessionChanged?()
}
self.client = client
+ self.lifetime = lifetime
await sync()
}
@@ -111,16 +114,17 @@ public final class PushRegistrar {
}
private func pass() async {
- guard let client, let bearer = client.token else { return }
+ let lifetime = self.lifetime
+ guard lifetime?.isActive != false, let client, let bearer = client.token else { return }
let generation = self.generation
if let body, !(accepted?.bearer == bearer && accepted?.body == body), !(refused?.bearer == bearer && refused?.body == body) {
do {
let write = try PendingWrite.json(body)
_ = try await client.registerPush(write)
- guard generation == self.generation else { return }
+ guard lifetime?.isActive != false, generation == self.generation else { return }
accepted = (bearer, body)
} catch let error as EquipoAPIError {
- guard generation == self.generation else { return }
+ guard lifetime?.isActive != false, generation == self.generation else { 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
@@ -131,13 +135,13 @@ public final class PushRegistrar {
for (task, token) in activities.sorted(by: { $0.key < $1.key })
.filter({ Self.same($0.value.origin, client.origin) }).map({ ($0.key, $0.value.token) })
where acceptedActivities[task] != token && closedActivities[task] != token {
- guard generation == self.generation else { return }
+ guard lifetime?.isActive != false, generation == self.generation else { return }
do {
try await client.registerActivity(try PendingWrite.json(ActivityTokenBody(taskId: task, token: token)))
- guard generation == self.generation else { return }
+ guard lifetime?.isActive != false, generation == self.generation else { return }
acceptedActivities[task] = token
} catch let error as EquipoAPIError {
- guard generation == self.generation else { return }
+ guard lifetime?.isActive != false, generation == self.generation else { return }
// Ended, or not this person's task: the server will never take it,
// and the activity ends here too.
if error.status == 404 || error.status == 409 || error.status == 400 {
diff --git a/native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings b/native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings
index 3387547a..f280a180 100644
--- a/native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings
+++ b/native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings
@@ -706,6 +706,61 @@
}
}
},
+ "oficina.connecting": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Connecting to your team"
+ }
+ }
+ }
+ },
+ "oficina.current_team": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Current team"
+ }
+ }
+ }
+ },
+ "oficina.device_failed": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Could not connect to this team."
+ }
+ }
+ }
+ },
+ "oficina.retry": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Connect again"
+ }
+ }
+ }
+ },
+ "oficina.sign_in": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Sign in with Oficina ID"
+ }
+ }
+ }
+ },
"pairing.approve_lede": {
"extractionState": "manual",
"localizations": {
diff --git a/native/apple/Sources/EquipoKit/Session/EquipoSession.swift b/native/apple/Sources/EquipoKit/Session/EquipoSession.swift
index 25ed5cf6..024e6ea6 100644
--- a/native/apple/Sources/EquipoKit/Session/EquipoSession.swift
+++ b/native/apple/Sources/EquipoKit/Session/EquipoSession.swift
@@ -22,6 +22,10 @@ public final class EquipoSession {
let write: PendingWrite
}
+ /// A departing session can never become current again, even if a read
+ /// or credential renewal ignores cancellation and completes later.
+ public let lifetime: SignInLifetime
+ var isInvalidated: Bool { !lifetime.isActive }
public private(set) var status: Status = .loading
public private(set) var account: DeviceAccount
public private(set) var me: ThinMe?
@@ -40,8 +44,9 @@ public final class EquipoSession {
public private(set) var refreshFailed = false
public private(set) var cursor: Int64 = 0
- public let client: EquipoClient
+ public private(set) var client: EquipoClient
private let accounts: DeviceAccounts
+ private var revocationTransport: EquipoTransport
private let runner = CoalescedRunner()
private var live: Task<Void, Never>?
/// Reads asked for by the stream: one runs at a time, and a burst
@@ -55,12 +60,16 @@ public final class EquipoSession {
private var unsettledVisibility: [String: PendingWrite] = [:]
private let sleep: @Sendable (Duration) async throws -> Void
- public init(account: DeviceAccount, accounts: DeviceAccounts, transport: EquipoTransport? = nil,
+ public init(account: DeviceAccount, accounts: DeviceAccounts, transport: EquipoTransport? = nil, lifetime: SignInLifetime? = nil,
sleep: @escaping @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) }) {
self.account = account
self.accounts = accounts
self.sleep = sleep
- self.client = EquipoClient(transport: transport ?? URLSessionTransport(origin: account.origin), token: account.credential?.token)
+ let lifetime = lifetime ?? accounts.lifetimes.current
+ self.lifetime = lifetime
+ let transport = transport ?? URLSessionTransport(origin: account.origin)
+ self.revocationTransport = transport
+ self.client = EquipoClient(transport: LifetimeTransport(inner: transport, lifetime: lifetime), token: account.credential?.token)
if !account.isUsable() { status = .signedOut }
}
@@ -83,12 +92,14 @@ public final class EquipoSession {
}
private func refreshPass() async {
+ guard !isInvalidated else { return }
let client = self.client
do {
async let snapshotRead = client.snapshot()
async let taskRead = client.tasks()
async let needsRead = client.needsYou()
let (snapshot, taskList, needsList) = try await (snapshotRead, taskRead, needsRead)
+ guard !isInvalidated else { return }
apply(snapshot)
tasks = taskList.items ?? []
needsYou = needsList.items ?? []
@@ -101,14 +112,17 @@ public final class EquipoSession {
Task { await self.deliver(id) }
}
} catch let error as EquipoAPIError where error.endsSession {
+ guard !isInvalidated else { return }
endSession()
} catch is CancellationError {
} catch {
+ guard !isInvalidated else { return }
refreshFailed = true
}
}
func apply(_ snapshot: Snapshot) {
+ guard !isInvalidated else { return }
me = snapshot.me
messages = Self.merge(messages, snapshot.messages ?? [])
turns = Self.merge(turns, snapshot.turns ?? [])
@@ -120,7 +134,7 @@ public final class EquipoSession {
stopping.formIntersection(liveIDs)
if account.teamName != snapshot.me.teamName {
account.teamName = snapshot.me.teamName; account.address = snapshot.me.address
- try? accounts.save(account)
+ try? accounts.commit(.save(account), lifetime: lifetime)
}
}
@@ -137,12 +151,13 @@ public final class EquipoSession {
/// updates the thinking line; anything else is read again through the
/// snapshot. A dropped stream reconnects with backoff.
public func startLive() {
- guard live == nil else { return }
+ guard !isInvalidated, live == nil else { return }
live = Task { [weak self] in
var backoff = Backoff()
while !Task.isCancelled {
guard let self, self.status != .signedOut else { return }
if self.status == .loading { await self.refresh() }
+ guard self.lifetime.isActive else { return }
do {
let lines = try await self.client.events(after: self.cursor)
backoff = Backoff()
@@ -166,7 +181,7 @@ public final class EquipoSession {
/// a change to something the screens show reads them again; the rest
/// (runners, connections, pings) is not this app's.
func handle(_ line: String) async {
- guard line.hasPrefix("data:") else { return }
+ guard lifetime.isActive, line.hasPrefix("data:") else { return }
let json = Data(line.dropFirst(5).trimmingCharacters(in: .whitespaces).utf8)
guard let event = try? EquipoJSON.decoder.decode(EventEnvelope.self, from: json) else { return }
if let c = event.cursor { cursor = max(cursor, c) }
@@ -182,6 +197,7 @@ public final class EquipoSession {
/// Reads again soon, without holding up the stream.
func requestRefresh() {
+ guard lifetime.isActive else { return }
if pendingRead != nil { readAgain = true; return }
pendingRead = Task { [weak self] in
guard let self else { return }
@@ -232,7 +248,7 @@ public final class EquipoSession {
public func send(_ text: String, inThreadOf taskID: String? = nil) async {
let text = text.trimmingCharacters(in: .whitespacesAndNewlines)
- guard !text.isEmpty, let write = try? EquipoClient.message(text) else { return }
+ guard lifetime.isActive, !text.isEmpty, let write = try? EquipoClient.message(text) else { return }
outgoing.append(Outgoing(id: write.key, text: text, taskID: taskID, state: .sending, write: write))
await deliver(write.key)
}
@@ -241,12 +257,13 @@ public final class EquipoSession {
public func retry(_ id: String) async { await deliver(id) }
private func deliver(_ id: String) async {
- guard let index = outgoing.firstIndex(where: { $0.id == id }) else { return }
+ guard lifetime.isActive, let index = outgoing.firstIndex(where: { $0.id == id }) else { return }
outgoing[index].state = .sending
let item = outgoing[index]
do {
if let taskID = item.taskID {
let entry = try await client.postThread(task: taskID, item.write)
+ guard lifetime.isActive else { return }
if let i = tasks.firstIndex(where: { $0.id == taskID }) {
var thread = tasks[i].thread ?? []
if !thread.contains(where: { $0.id == entry.id }) { thread.append(entry) }
@@ -254,15 +271,18 @@ public final class EquipoSession {
}
} else {
let sent = try await client.send(item.write)
+ guard lifetime.isActive else { return }
messages = Self.merge(messages, [sent.message])
turns = Self.merge(turns, [sent.turn])
}
outgoing.removeAll { $0.id == id }
await refresh()
} catch let error as EquipoAPIError {
+ guard lifetime.isActive else { return }
if error.endsSession { endSession(); return }
if let i = outgoing.firstIndex(where: { $0.id == id }) { outgoing[i].state = error == .offline ? .waiting : .failed }
} catch {
+ guard lifetime.isActive else { return }
// Cancelled on the way: it may yet be sent, as itself.
if let i = outgoing.firstIndex(where: { $0.id == id }) { outgoing[i].state = error is CancellationError ? .waiting : .failed }
}
@@ -281,19 +301,23 @@ public final class EquipoSession {
/// Answers a card as the person saw it, bound to that revision. A lost
/// answer is retried as itself; a stale one is never sent again.
public func answer(_ card: ThinCard, choice: String, note: String? = nil) async -> AnswerOutcome {
+ guard lifetime.isActive else { return .failed }
guard card.isOpen else { return .changed }
let slot = "\(card.id)#\(card.revision)#\(choice)#\(note ?? "")"
guard let write = unsettledAnswers[slot] ?? (try? EquipoClient.answer(choice, note: note, to: card)) else { return .failed }
unsettledAnswers[slot] = write
var attempts = 0
while true {
+ guard lifetime.isActive else { return .failed }
do {
let answered = try await client.answer(card: card.id, write)
+ guard lifetime.isActive else { return .failed }
unsettledAnswers[slot] = nil
cards = Self.merge(cards, [answered.card])
await refresh()
return .answered
} catch let error as EquipoAPIError {
+ guard lifetime.isActive else { return .failed }
if error == .offline, attempts < 2 { attempts += 1; try? await sleep(.seconds(2)); continue }
// Offline: it may have landed; keep it to send again as itself.
if error != .offline { unsettledAnswers[slot] = nil }
@@ -310,18 +334,22 @@ public final class EquipoSession {
/// card stays in Needs you. `.answered` means the server took it; a
/// card that changed is shown as it is now and never sent again.
public func setAside(_ card: ThinCard, _ aside: Bool) async -> AnswerOutcome {
+ guard lifetime.isActive else { return .failed }
guard Feed.canSetAside(card) else { return .changed }
let slot = "\(card.id)#\(card.revision)#\(aside)"
guard let write = unsettledVisibility[slot] ?? (try? EquipoClient.visibility(aside: aside, of: card)) else { return .failed }
unsettledVisibility[slot] = write
var attempts = 0
while true {
+ guard lifetime.isActive else { return .failed }
do {
let updated = try await client.setVisibility(card: card.id, write)
+ guard lifetime.isActive else { return .failed }
unsettledVisibility[slot] = nil
cards = Self.merge(cards, [updated])
return .answered
} catch let error as EquipoAPIError {
+ guard lifetime.isActive else { return .failed }
if error == .offline, attempts < 2 { attempts += 1; try? await sleep(.seconds(2)); continue }
// Offline: it may have landed; keep it to send again as itself.
if error != .offline { unsettledVisibility[slot] = nil }
@@ -337,31 +365,47 @@ public final class EquipoSession {
/// Says whether the server took it; on false, Stop is offered again.
@discardableResult
public func stop(_ turn: ThinTurn) async -> Bool {
+ guard lifetime.isActive else { return false }
guard !stopping.contains(turn.id) else { return true }
stopping.insert(turn.id)
do { try await client.cancelTurn(turn.id) } catch { stopping.remove(turn.id); return false }
+ guard lifetime.isActive else { return false }
await refresh()
return true
}
+ /// A renewed Oficina ID credential keeps the conversation and pending
+ /// writes mounted. Every new request uses the replacement bearer.
+ func renew(_ account: DeviceAccount, transport: EquipoTransport) {
+ guard !isInvalidated else { return }
+ self.account = account
+ revocationTransport = transport
+ client = EquipoClient(transport: LifetimeTransport(inner: transport, lifetime: lifetime), token: account.credential?.token)
+ if status == .signedOut { status = .loading }
+ }
+
// MARK: Signing out
private func endSession() {
+ try? accounts.commit(.remove(account), lifetime: lifetime)
+ invalidate()
+ }
+
+ /// Called before the app releases this session. Cancellation alone does
+ /// not prevent a completed network response from reaching persistence.
+ func invalidate() {
+ lifetime.end()
status = .signedOut
stopLive()
pendingRead?.cancel(); pendingRead = nil
}
- /// Revokes this device on the server, then forgets it here. Forgetting
- /// happens even if the server cannot be reached.
+ /// Forgets this device immediately, then revokes it best effort. No
+ /// late cleanup may remove a newly signed-in account at the same origin.
public func signOut() async {
- stopLive()
- if let id = account.credential?.id, let page = try? await client.devices(),
- let device = page.items.first(where: { $0.id == id }) {
- _ = try? await client.revokeDevice(id, EquipoClient.empty(ifMatch: device.revision))
- }
- accounts.remove(origin)
- status = .signedOut
+ try? accounts.commit(.remove(account), lifetime: lifetime)
+ invalidate()
+ await DeviceRevocation.revoke(account, transport: revocationTransport)
}
}
diff --git a/native/apple/Sources/EquipoKit/Session/SignInLifetime.swift b/native/apple/Sources/EquipoKit/Session/SignInLifetime.swift
new file mode 100644
index 00000000..fbe915e7
--- /dev/null
+++ b/native/apple/Sources/EquipoKit/Session/SignInLifetime.swift
@@ -0,0 +1,67 @@
+import Foundation
+
+/// Authority for one sign-in, shared by every task it starts. Renewal keeps
+/// the same lifetime; sign-out, switching accounts and cancellation end it.
+@MainActor public final class SignInLifetime {
+ public private(set) var isActive = true
+ public func end() { isActive = false }
+ func check() throws { guard isActive else { throw CancellationError() } }
+}
+
+/// One current sign-in across pairing and Oficina ID. A stale task cannot
+/// acquire a replacement token; only an explicit sign-in transition begins one.
+@MainActor public final class SignInLifetimes {
+ public private(set) var current = SignInLifetime()
+ @discardableResult public func begin() -> SignInLifetime {
+ current.end()
+ current = SignInLifetime()
+ return current
+ }
+ func require(_ lifetime: SignInLifetime) throws {
+ try lifetime.check()
+ guard current === lifetime else { throw CancellationError() }
+ }
+}
+
+/// Engine traffic is confined to its original lifetime, including clients
+/// retained by views, retries and push registration after the session leaves.
+struct LifetimeTransport: EquipoTransport {
+ let inner: EquipoTransport
+ let lifetime: SignInLifetime
+ var origin: URL { inner.origin }
+ func send(_ request: APIRequest) async throws -> APIResponse {
+ try await lifetime.check()
+ let response = try await inner.send(request)
+ try await lifetime.check()
+ return response
+ }
+ func lines(_ request: APIRequest) async throws -> AsyncThrowingStream<String, Error> {
+ try await lifetime.check()
+ let stream = try await inner.lines(request)
+ try await lifetime.check()
+ return AsyncThrowingStream { continuation in
+ let task = Task {
+ do {
+ for try await line in stream {
+ try await lifetime.check()
+ continuation.yield(line)
+ }
+ continuation.finish()
+ } catch { continuation.finish(throwing: error) }
+ }
+ continuation.onTermination = { _ in task.cancel() }
+ }
+ }
+}
+
+/// The only traffic allowed after a lifetime ends: best-effort revocation
+/// with the abandoned credential itself. Never consults a current bearer.
+enum DeviceRevocation {
+ static func revoke(_ account: DeviceAccount, transport: EquipoTransport) async {
+ let client = EquipoClient(transport: transport, token: account.credential?.token)
+ if let id = account.credential?.id, let page = try? await client.devices(),
+ let device = page.items.first(where: { $0.id == id }) {
+ _ = try? await client.revokeDevice(id, EquipoClient.empty(ifMatch: device.revision))
+ }
+ }
+}
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/AccountScreen.swift b/native/apple/Sources/EquipoKit/UI/Screens/AccountScreen.swift
index 58c87859..08ac53cd 100644
--- a/native/apple/Sources/EquipoKit/UI/Screens/AccountScreen.swift
+++ b/native/apple/Sources/EquipoKit/UI/Screens/AccountScreen.swift
@@ -20,9 +20,13 @@ public struct AccountScreen: View {
LabeledContent(String(localized: "account.until", bundle: .module), value: expires.formatted(date: .long, time: .omitted))
}
}
- Section {
- Button(String(localized: "account.sign_out", bundle: .module), role: .destructive) { confirming = true }
- } footer: { Text(String(localized: "account.sign_out_footer", bundle: .module)) }
+ if session.account.oficinaIdentity != nil {
+ EquipoOficinaAccountMenu(app: model, model: model.oficina.model)
+ } else {
+ Section {
+ Button(String(localized: "account.sign_out", bundle: .module), role: .destructive) { confirming = true }
+ } footer: { Text(String(localized: "account.sign_out_footer", bundle: .module)) }
+ }
}
.formStyle(.grouped)
.confirmationDialog(String(localized: "account.sign_out_confirm", bundle: .module), isPresented: $confirming) {
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/AppModel.swift b/native/apple/Sources/EquipoKit/UI/Screens/AppModel.swift
index dca5a66d..85bcf1c8 100644
--- a/native/apple/Sources/EquipoKit/UI/Screens/AppModel.swift
+++ b/native/apple/Sources/EquipoKit/UI/Screens/AppModel.swift
@@ -11,6 +11,12 @@ public final class EquipoAppModel {
public let accounts: DeviceAccounts
public private(set) var session: EquipoSession?
public let pairing: PairingModel
+ public let oficina: EquipoOficinaID
+ public private(set) var showingPairing: Bool
+ private var started = false
+ private var isForeground = false
+ private var endingSession = false
+ private let makeTransport: @Sendable (URL) -> EquipoTransport
/// Set when the server ended the session, so pairing can say why.
public private(set) var endedTeam: String?
/// Where a tapped notification or Live Activity asked to go, until the
@@ -24,67 +30,147 @@ public final class EquipoAppModel {
#endif
public init(store: SecretStore = KeychainSecretStore(), notifications: NotificationSystem? = nil,
- push: PushRegistrar = PushRegistrar()) {
+ push: PushRegistrar = PushRegistrar(), oficinaModel: OficinaIDModel? = nil,
+ makeTransport: @escaping @Sendable (URL) -> EquipoTransport = { URLSessionTransport(origin: $0) },
+ now: @escaping @Sendable () -> Date = Date.init, deviceLabel: (() -> String)? = nil) {
+ self.makeTransport = makeTransport
accounts = DeviceAccounts(store: store)
- pairing = PairingModel(accounts: accounts)
+ pairing = PairingModel(accounts: accounts, makeTransport: makeTransport)
+ let old = accounts.all().first { $0.oficinaIdentity == nil && $0.isUsable() }
+ let route = accounts.signInRoute
+ showingPairing = route.map { $0 == "pairing" } ?? (old != nil)
+ oficina = EquipoOficinaID(model: oficinaModel ?? .live(configuration: EquipoOficinaID.configuration,
+ appGroup: EquipoOficinaID.appGroup),
+ accounts: accounts, makeTransport: makeTransport, now: now,
+ label: deviceLabel ?? { PairingView.deviceLabel })
self.notifications = notifications
self.push = push
#if os(iOS)
liveActivities = LiveActivities(registrar: push)
#endif
- if let account = accounts.all().first(where: { $0.isUsable() }) {
+ oficina.suspended = showingPairing
+ oficina.onAccount = { [weak self] account, transport, lifetime in self?.adopt(account, transport: transport, lifetime: lifetime) }
+ oficina.onLeave = { [weak self] in
+ guard let self, !self.showingPairing else { return }
+ self.sessionEnded(serverEnded: false)
+ }
+ if showingPairing, let account = old {
// Written again so a slice 1 credential becomes readable after
// first unlock, for Live Activity tokens sent in the background.
- try? accounts.save(account)
- session = EquipoSession(account: account, accounts: accounts)
+ try? accounts.commit(.save(account), lifetime: accounts.lifetimes.current)
+ session = EquipoSession(account: account, accounts: accounts, transport: makeTransport(account.origin))
sessionStarted()
}
}
public var needsPairing: Bool { session == nil || session?.status == .signedOut }
+ public func start() async {
+ guard !started else { return }
+ started = true
+ await oficina.start()
+ }
+
+ /// The view's task cancels this clock when its scene goes away. A scene
+ /// that stays open still renews daily, without waiting for a foreground.
+ public func runRenewals(sleep: @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) }) async {
+ await start()
+ while !Task.isCancelled {
+ do { try await sleep(.seconds(24 * 60 * 60)) } catch { return }
+ await oficina.renewIfNeeded()
+ }
+ }
+
+ public func otherWays() {
+ showingPairing = true
+ oficina.pause()
+ session?.invalidate(); session = nil
+ pairing.cancel()
+ let lifetime = accounts.lifetimes.begin()
+ try? accounts.commit(.route("pairing"), lifetime: lifetime)
+ forgetPushes()
+ }
+
+ public func useOficinaID() async {
+ showingPairing = false
+ pairing.cancel()
+ await oficina.resume()
+ }
+
/// After pairing approves this device.
public func paired() {
- guard let account = pairing.account else { return }
- adopt(account)
+ guard let account = pairing.account, let lifetime = pairing.handoff() else { return }
+ adopt(account, transport: makeTransport(account.origin), lifetime: lifetime)
foreground()
}
- func adopt(_ account: DeviceAccount, transport: EquipoTransport? = nil) {
+ func adopt(_ account: DeviceAccount, transport: EquipoTransport? = nil, lifetime: SignInLifetime? = nil) {
+ let lifetime = lifetime ?? (session == nil ? accounts.lifetimes.current : accounts.lifetimes.begin())
+ guard lifetime.isActive else { return }
endedTeam = nil
- session = EquipoSession(account: account, accounts: accounts, transport: transport)
+ if let session, session.lifetime === lifetime, !session.isInvalidated, account.oficinaIdentity != nil,
+ session.account.oficinaIdentity == account.oficinaIdentity,
+ session.account.oficinaTeam == account.oficinaTeam, session.origin == account.origin, let transport {
+ session.renew(account, transport: transport)
+ } else {
+ session?.invalidate()
+ session = EquipoSession(account: account, accounts: accounts, transport: transport, lifetime: lifetime)
+ }
sessionStarted()
}
/// There is a team: ask to notify (the system asks once), register with
/// APNs, and register this device with the team's server.
private func sessionStarted() {
+ if isForeground { session?.startLive() }
notifications?.askAndRegister()
- let client = session?.client
+ guard let session else { return }
+ let client = session.client, lifetime = session.lifetime
let push = self.push
- Task { await push.attach(client) }
+ Task {
+ guard lifetime.isActive else { return }
+ await push.attach(client, lifetime: lifetime)
+ }
}
- /// The server ended the session (revoked, removed or expired): pair again.
- public func sessionEnded() {
- endedTeam = session?.teamName
+ /// Leave the conversation. Only a server-ended session names the team
+ /// in the pairing notice; kit sign-out and replacement are local choices.
+ public func sessionEnded(serverEnded: Bool = true) {
+ guard !endingSession else { return }
+ endingSession = true
+ defer { endingSession = false }
+ let departing = session
+ endedTeam = serverEnded ? departing?.teamName : nil
session = nil
+ // Remove through the still-current lifetime before ending it. The
+ // coordinator's onLeave can call back here; session is already nil.
+ if let departing, departing.account.oficinaIdentity != nil { oficina.sessionEnded(lifetime: departing.lifetime) }
+ departing?.invalidate()
pairing.cancel()
forgetPushes()
}
public func signOut() async {
- await session?.signOut()
+ if session?.account.oficinaIdentity != nil || !showingPairing {
+ oficina.signOut()
+ return
+ }
+ let departing = session
session = nil
endedTeam = nil
pairing.cancel()
+ if departing == nil { accounts.lifetimes.current.end() }
forgetPushes()
+ await departing?.signOut()
}
/// No team: nothing more is registered, no badge, no task on the Lock Screen.
private func forgetPushes() {
let push = self.push
- Task { await push.attach(nil) }
+ Task { [weak self] in
+ guard self?.session == nil else { return }
+ await push.attach(nil)
+ }
notifications?.setBadge(0)
// Even if the server never heard of the sign-out, this device stops
// receiving the team's notifications; pairing again registers anew.
@@ -105,11 +191,18 @@ public final class EquipoAppModel {
}
public func foreground() {
+ isForeground = true
NativeConnectivity.shared.foregrounded()
let push = self.push
Task { await push.sync() }
- guard let session else { return }
- session.startLive()
+ let lifetime = accounts.lifetimes.current
+ Task {
+ await start()
+ guard lifetime.isActive else { return }
+ await oficina.renewIfNeeded()
+ guard lifetime.isActive else { return }
+ if isForeground { session?.startLive() }
+ }
}
- public func background() { session?.stopLive() }
+ public func background() { isForeground = false; session?.stopLive() }
}
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/OficinaAccountMenu.swift b/native/apple/Sources/EquipoKit/UI/Screens/OficinaAccountMenu.swift
new file mode 100644
index 00000000..0c0b0706
--- /dev/null
+++ b/native/apple/Sources/EquipoKit/UI/Screens/OficinaAccountMenu.swift
@@ -0,0 +1,39 @@
+import RastrilloApple
+import SwiftUI
+
+/// The same account menu composition as Docs, using the kit's rows,
+/// identity replacement confirmation and sign-out words.
+struct EquipoOficinaAccountMenu: View {
+ let app: EquipoAppModel
+ @ObservedObject var model: OficinaIDModel
+ private var teams: [OficinaTeam] {
+ guard let identity = model.identity else { return [] }
+ return (model.store.teams(identity.id)?.teams ?? []).filter { $0.origin(for: "equipo") != nil }
+ }
+ var body: some View {
+ Section {
+ if let identity = model.identity { OficinaIdentityRow(identity: identity) }
+ ForEach(teams) { team in
+ Button {
+ Task { await model.choose(team); await app.oficina.synchronize() }
+ } label: {
+ HStack {
+ OficinaTeamRow(team: team)
+ if app.session?.account.oficinaTeam == team.sqid {
+ Image(systemName: "checkmark").accessibilityLabel(String(localized: "oficina.current_team", bundle: .module))
+ }
+ }
+ }.buttonStyle(.plain).disabled(model.busy)
+ }
+ if let error = app.oficina.error { Text(error).foregroundStyle(.secondary) }
+ if let error = model.error { OficinaErrorLine(error) }
+ Button(OficinaIDText.text("continue.another")) { model.useAnother() }
+ Button(OficinaIDText.text("otherWays")) { app.otherWays() }
+ Button(OficinaIDText.text("signOut", model.identity?.label ?? ""), role: .destructive) {
+ Task { await app.signOut() }
+ }
+ }
+ .task { await model.refreshTeams() }
+ .oficinaReplaceConfirmation(model)
+ }
+}
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/OficinaNotice.swift b/native/apple/Sources/EquipoKit/UI/Screens/OficinaNotice.swift
new file mode 100644
index 00000000..3e7e7207
--- /dev/null
+++ b/native/apple/Sources/EquipoKit/UI/Screens/OficinaNotice.swift
@@ -0,0 +1,30 @@
+import RastrilloApple
+import SwiftUI
+
+/// A failed re-mint leaves the conversation mounted, with a way to retry.
+public struct EquipoOficinaNotice: View {
+ private let app: EquipoAppModel
+ @ObservedObject private var model: OficinaIDModel
+ public init(model: EquipoAppModel) { app = model; self.model = model.oficina.model }
+ var message: String? {
+ if let error = app.oficina.error ?? model.error { return error }
+ if case .unavailable = model.step { return OficinaIDText.text("unavailable.title") }
+ return nil
+ }
+ public var body: some View {
+ if let error = message {
+ VStack(alignment: .leading, spacing: 8) {
+ OficinaErrorLine(error)
+ Button(String(localized: "oficina.retry", bundle: .module)) {
+ Task {
+ await app.oficina.renewIfNeeded()
+ await app.session?.refresh()
+ }
+ }.disabled(model.busy || app.oficina.busy)
+ }
+ .padding(12)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(.background)
+ }
+ }
+}
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/PhoneRoot.swift b/native/apple/Sources/EquipoKit/UI/Screens/PhoneRoot.swift
index 74165076..06a9919d 100644
--- a/native/apple/Sources/EquipoKit/UI/Screens/PhoneRoot.swift
+++ b/native/apple/Sources/EquipoKit/UI/Screens/PhoneRoot.swift
@@ -4,7 +4,7 @@ import SwiftUI
/// The iPhone app: pairing until there is a team, then Conversation, Needs
/// you and Tasks as tabs, with the task view pushed from any of them.
public struct PhoneRoot: View {
- @State var model: EquipoAppModel
+ @State private var model: EquipoAppModel
@Environment(\.scenePhase) private var phase
public init(model: EquipoAppModel = EquipoAppModel()) { _model = State(initialValue: model) }
@@ -12,8 +12,12 @@ public struct PhoneRoot: View {
Group {
if let session = model.session, session.status != .signedOut {
PhoneTabs(model: model, session: session)
+ .id(ObjectIdentifier(session))
+ .safeAreaInset(edge: .top, spacing: 0) {
+ if session.account.oficinaIdentity != nil { EquipoOficinaNotice(model: model) }
+ }
} else {
- PairingView(model: model)
+ EquipoSignInView(model: model)
}
}
.tint(Palette.accent)
@@ -28,7 +32,7 @@ public struct PhoneRoot: View {
}
// A Live Activity's tap: its task.
.onOpenURL { url in if let route = PushRoute(url: url) { model.open(route) } }
- .task { model.foreground() }
+ .task { model.foreground(); await model.runRenewals() }
}
}
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/SignInView.swift b/native/apple/Sources/EquipoKit/UI/Screens/SignInView.swift
new file mode 100644
index 00000000..b11dd02d
--- /dev/null
+++ b/native/apple/Sources/EquipoKit/UI/Screens/SignInView.swift
@@ -0,0 +1,47 @@
+import RastrilloApple
+import SwiftUI
+
+/// Both platforms use the kit's full onboarding, with pairing as an explicit route.
+public struct EquipoSignInView: View {
+ let app: EquipoAppModel
+ public init(model: EquipoAppModel) { app = model }
+ public var body: some View {
+ if app.showingPairing {
+ PairingView(model: app)
+ .safeAreaInset(edge: .bottom) {
+ Button(String(localized: "oficina.sign_in", bundle: .module)) {
+ Task { await app.useOficinaID() }
+ }.padding()
+ }
+ } else {
+ EquipoOnboarding(app: app, model: app.oficina.model)
+ }
+ }
+}
+
+private struct EquipoOnboarding: View {
+ let app: EquipoAppModel
+ @ObservedObject var model: OficinaIDModel
+ var body: some View {
+ Group {
+ if case .signedIn = model.step {
+ VStack(spacing: 16) {
+ if let error = app.oficina.error {
+ Text(error)
+ Button(String(localized: "oficina.retry", bundle: .module)) {
+ Task { await app.oficina.synchronize() }
+ }
+ } else {
+ ProgressView(String(localized: "oficina.connecting", bundle: .module))
+ }
+ Button(OficinaIDText.text("otherWays")) { app.otherWays() }
+ Button(OficinaIDText.text("signOut", model.identity?.label ?? ""), role: .destructive) {
+ app.oficina.signOut()
+ }
+ }.padding(24)
+ } else {
+ OficinaOnboardingView(model: model, otherWays: { app.otherWays() })
+ }
+ }
+ }
+}
diff --git a/native/apple/Sources/EquipoMac/EquipoMacApp.swift b/native/apple/Sources/EquipoMac/EquipoMacApp.swift
index 2277974b..ce7ea393 100644
--- a/native/apple/Sources/EquipoMac/EquipoMacApp.swift
+++ b/native/apple/Sources/EquipoMac/EquipoMacApp.swift
@@ -68,13 +68,17 @@ struct MacRoot: View {
Group {
if let session = model.session, !model.needsPairing {
MacMainView(model: model, session: session)
+ .id(ObjectIdentifier(session))
+ .safeAreaInset(edge: .top, spacing: 0) {
+ if session.account.oficinaIdentity != nil { EquipoOficinaNotice(model: model) }
+ }
} else {
- PairingView(model: model).frame(minWidth: 560, minHeight: 520)
+ EquipoSignInView(model: model).frame(minWidth: 560, minHeight: 520)
}
}
.tint(Color(nsColor: .webAccent))
.frame(minWidth: 860, minHeight: 560)
- .onAppear { model.foreground() }
+ .task { model.foreground(); await model.runRenewals() }
.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in model.foreground() }
// Live while a window can be seen, even beside another app.
.onReceive(NotificationCenter.default.publisher(for: NSApplication.didChangeOcclusionStateNotification)) { _ in
diff --git a/native/apple/Tests/EquipoKitTests/OficinaIDTests.swift b/native/apple/Tests/EquipoKitTests/OficinaIDTests.swift
new file mode 100644
index 00000000..645efc58
--- /dev/null
+++ b/native/apple/Tests/EquipoKitTests/OficinaIDTests.swift
@@ -0,0 +1,759 @@
+import Foundation
+import RastrilloApple
+import RastrilloTestSupport
+import Testing
+@testable import EquipoKit
+
+private final class IDClock: @unchecked Sendable {
+ private let lock = NSLock()
+ private var date = Date()
+ var now: Date { lock.withLock { date } }
+ func advance(_ seconds: TimeInterval) { lock.withLock { date += seconds } }
+}
+
+@MainActor private final class IDFixture {
+ let service = FakeOficinaIDService()
+ let shared = OficinaMemoryStore()
+ let privateStore = OficinaMemoryStore()
+ let secrets = MemorySecretStore()
+ let transport = ScriptedTransport()
+ let clock = IDClock()
+ let notifications = FakeNotifications()
+ let suite = "EquipoIDTests.\(UUID().uuidString)"
+ let defaults: UserDefaults
+ let model: OficinaIDModel
+ let app: EquipoAppModel
+
+ init(held: (any EquipoTransport)? = nil) {
+ defaults = UserDefaults(suiteName: suite)!
+ let store = OficinaIDStore(shared: shared, appPrivate: privateStore, group: defaults)
+ let clock = clock
+ model = OficinaIDModel(configuration: EquipoOficinaID.configuration, store: store, service: service,
+ passkeys: FakePasskeys(), makeKey: { OficinaSoftwareKey() }, now: { clock.now }, appDefaults: defaults)
+ let transport = transport
+ app = EquipoAppModel(store: secrets, notifications: notifications, push: PushRegistrar(environment: nil), oficinaModel: model,
+ makeTransport: { _ in if let held { held } else { transport } }, now: { clock.now }, deviceLabel: { "Test phone" })
+ service.addPerson(email: "person@example.test", identityID: "id-1")
+ service.setTeams([team()], for: "id-1")
+ service.admit("id-1", at: transport.origin, as: .linked)
+ transport.on("POST /auth/devices/native", fixture: "device-credential")
+ transport.on("GET /auth/devices", fixture: "devices")
+ transport.on("DELETE /auth/devices/dev_01JD5Z4Q2X", fixture: "ack")
+ }
+ deinit { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+ func team(_ id: String = "t1", app: String = "equipo") -> OficinaTeam {
+ OficinaTeam(sqid: id, label: id, name: "Team \(id)", role: "member", apps: [
+ OficinaTeamApp(app: app, origin: transport.origin.absoluteString, consumerID: id)
+ ])
+ }
+ func signIn() async {
+ await app.start()
+ model.continueWithEmail(); model.email = "person@example.test"
+ await model.submitEmail(); model.code = FakeOficinaIDService.goodCode
+ await model.submitCode()
+ await app.oficina.synchronize()
+ }
+ func seedIdentity() async throws {
+ let key = OficinaSoftwareKey()
+ let start = try await service.startCode(email: "person@example.test", key: key, platform: "macos")
+ guard case .granted(let grant) = try await service.verifyCode(start: start.start, code: FakeOficinaIDService.goodCode, key: key) else { throw EquipoAPIError.signedOut }
+ _ = try model.store.add(grant: grant, key: key, label: "Person", labelSource: .email, method: "code", now: clock.now)
+ }
+}
+
+@MainActor @Suite struct OficinaIDTests {
+ @Test func firstAppShowsWelcomeThenKeepsDeviceAndFreshKey() async throws {
+ let f = IDFixture()
+ await f.app.start()
+ #expect(f.model.step == .welcome)
+ #expect(f.app.session == nil)
+ #expect(!f.app.showingPairing)
+ await f.signIn()
+ let account = try #require(f.app.session?.account)
+ #expect(account.oficinaIdentity == "id-1")
+ #expect(account.oficinaTeam == "t1")
+ #expect(f.app.accounts.all() == [account])
+ let request = try #require(f.transport.sent("POST /auth/devices/native").first)
+ let body = try JSONDecoder().decode([String: String].self, from: #require(request.body))
+ #expect(body == ["public_key": try account.publicKey(), "label": "Test phone"])
+ let wire = try request.urlRequest(origin: f.transport.origin)
+ #expect(wire.url?.path == "/api/v1/auth/devices/native")
+ #expect(wire.value(forHTTPHeaderField: "Origin") == f.transport.origin.absoluteString)
+ #expect(wire.value(forHTTPHeaderField: "Cookie")?.hasPrefix("__Host-rastrillo_session=") == true)
+ #expect(wire.value(forHTTPHeaderField: "Authorization") == nil)
+ #expect(wire.value(forHTTPHeaderField: "Content-Type") == "application/json")
+ #expect(!wire.httpShouldHandleCookies)
+ await f.app.oficina.synchronize()
+ #expect(f.transport.sent("POST /auth/devices/native").count == 1)
+ let bearer = try APIRequest("GET", "/snapshot", bearer: account.credential?.token).urlRequest(origin: account.origin)
+ #expect(bearer.value(forHTTPHeaderField: "Cookie") == nil)
+ }
+
+ @Test func oneIdentityGoesStraightInAndSeveralTeamsOrNoneUseKit() async throws {
+ for count in [0, 1, 2] {
+ let f = IDFixture()
+ f.service.setTeams((0..<count).map { f.team("t\($0)") } + [f.team("docs", app: "docs")], for: "id-1")
+ try await f.seedIdentity()
+ await f.app.start()
+ if count == 1 {
+ #expect(f.app.session?.account.oficinaTeam == "t0")
+ } else if count == 0 {
+ #expect(f.model.step == .noTeams)
+ #expect(f.app.session == nil)
+ } else {
+ guard case .teams(let teams) = f.model.step else { Issue.record("expected kit's team step"); return }
+ #expect(teams.count == 2)
+ #expect(f.app.session == nil)
+ await f.model.choose(teams[1]); await f.app.oficina.synchronize()
+ #expect(f.app.session?.account.oficinaTeam == "t1")
+ }
+ }
+ }
+
+ @Test func renewsAfter24HoursWithoutReplacingConversationSession() async throws {
+ let f = IDFixture(); await f.signIn()
+ let original = try #require(f.app.session)
+ let key = original.account.keySeed
+ await f.app.oficina.renewIfNeeded()
+ #expect(f.transport.sent("POST /auth/devices/native").count == 1)
+ f.clock.advance(24 * 60 * 60 + 1)
+ await f.app.oficina.renewIfNeeded()
+ #expect(f.transport.sent("POST /auth/devices/native").count == 2)
+ #expect(f.app.session === original)
+ #expect(f.app.session?.account.keySeed != key)
+ }
+
+ @Test func rejectionsRemintOnceAndRetryWithTheNewBearer() async throws {
+ for status in [401, 403] {
+ let f = IDFixture(); await f.signIn()
+ let original = try #require(f.app.session)
+ let next = String(decoding: Fixture.data("device-credential"), as: UTF8.self).replacingOccurrences(of: "TOKENFIXTURE", with: "RENEWED")
+ f.transport.replace("POST /auth/devices/native", with: .success(APIResponse(status: 200, data: Data(next.utf8))))
+ f.transport.on("GET /me", .success(APIResponse(status: status, data: Data())), .success(APIResponse(status: 200, data: Fixture.data("me"))))
+ _ = try await original.client.me()
+ #expect(f.transport.sent("POST /auth/devices/native").count == 2)
+ #expect(f.transport.sent("GET /me").count == 2)
+ #expect(f.transport.sent("GET /me").last?.bearer == "equipo.person.v1.RENEWED")
+ // Both ordinary requests remain device bearers, never cookies.
+ #expect(f.transport.sent("GET /me").allSatisfy { $0.bearer != nil && $0.nativeSession == nil })
+ }
+ }
+
+ @Test func offlineRenewalKeepsAccountAndSignOutForgetsItImmediately() async throws {
+ let f = IDFixture(); await f.signIn()
+ let original = try #require(f.app.session)
+ f.clock.advance(24 * 60 * 60 + 1)
+ f.service.failNext("assert", with: .offline)
+ await f.app.oficina.renewIfNeeded()
+ #expect(f.app.session === original)
+ await f.app.signOut()
+ #expect(f.app.session == nil)
+ #expect(f.app.accounts.all().isEmpty)
+ #expect(f.model.identity == nil)
+ await f.app.oficina.cleanup?.value
+ await f.model.cleanup?.value
+ #expect(f.service.liveGrants == 0)
+ #expect(!f.transport.sent("GET /auth/devices").isEmpty)
+ }
+
+ @Test func pairingFallbackSuspendsStraightInAndReturnResumesIt() async throws {
+ let f = IDFixture(); try await f.seedIdentity()
+ f.app.otherWays()
+ await f.app.start()
+ #expect(f.app.showingPairing)
+ #expect(f.model.step == .welcome)
+ #expect(!f.service.calls.contains { $0.hasPrefix("assert ") })
+ #expect(f.app.session == nil)
+ #expect(f.transport.sent("POST /auth/devices/native").isEmpty)
+ await f.app.useOficinaID()
+ #expect(!f.app.showingPairing)
+ #expect(f.app.session != nil)
+ }
+
+ @Test func foregroundRecoversAfterARejectedSessionMetAnOutage() async throws {
+ let f = IDFixture(); await f.signIn()
+ let original = try #require(f.app.session)
+ f.service.failNext("assert", at: f.transport.origin.absoluteString, with: .offline)
+ f.transport.on("GET /me", .success(APIResponse(status: 401, data: Data())))
+ _ = try? await original.client.me()
+ #expect(f.app.session === original)
+ guard case .unavailable = f.model.step else { Issue.record("expected an unavailable team"); return }
+ f.clock.advance(61)
+ await f.app.oficina.renewIfNeeded()
+ guard case .signedIn = f.model.step else { Issue.record("foreground did not recover"); return }
+ #expect(f.app.session === original)
+ #expect(f.transport.sent("POST /auth/devices/native").count == 2)
+ }
+
+ @Test func signingInWhileAlreadyForegroundStartsTheConversation() async throws {
+ let f = IDFixture()
+ await f.app.start()
+ f.app.foreground()
+ await f.signIn()
+ for _ in 0..<100 {
+ if !f.transport.sent("GET /snapshot").isEmpty { break }
+ try await Task.sleep(for: .milliseconds(10))
+ }
+ f.app.background()
+ #expect(!f.transport.sent("GET /snapshot").isEmpty)
+ }
+
+ @Test func dailyTimerRenewsWhileAppStaysOpen() async throws {
+ let f = IDFixture(); await f.signIn()
+ let sleep = IDDailySleep(clock: f.clock)
+ await f.app.runRenewals(sleep: { try await sleep.wait($0) })
+ #expect(f.transport.sent("POST /auth/devices/native").count == 2)
+ #expect(await sleep.waits == [.seconds(86400), .seconds(86400)])
+ }
+
+ @Test func aDefinite403StaysARefusalAfterRemint() async throws {
+ let f = IDFixture(); await f.signIn()
+ let next = String(decoding: Fixture.data("device-credential"), as: UTF8.self).replacingOccurrences(of: "TOKENFIXTURE", with: "RENEWED")
+ f.transport.replace("POST /auth/devices/native", with: .success(APIResponse(status: 200, data: Data(next.utf8))))
+ f.transport.on("GET /me", .success(APIResponse(status: 403, data: Data())))
+ do {
+ _ = try await f.app.session?.client.me()
+ Issue.record("the permission refusal disappeared")
+ } catch let error as EquipoAPIError {
+ #expect(error.status == 403)
+ }
+ #expect(f.transport.sent("GET /me").count == 2)
+ #expect(f.transport.sent("POST /auth/devices/native").count == 2)
+ }
+
+ @Test func rejectedEventStreamRemintsAndPreservesCursor() async throws {
+ for status in [401, 403] {
+ let f = IDFixture(); await f.signIn()
+ let next = String(decoding: Fixture.data("device-credential"), as: UTF8.self).replacingOccurrences(of: "TOKENFIXTURE", with: "RENEWED")
+ f.transport.replace("POST /auth/devices/native", with: .success(APIResponse(status: 200, data: Data(next.utf8))))
+ f.transport.onStream(.failure(.status(status)), .success([]))
+ let session = try #require(f.app.session)
+ let stream = try await session.client.events(after: 42)
+ for try await _ in stream {}
+ let requests = f.transport.sent("GET /events")
+ #expect(requests.count == 2)
+ #expect(requests.allSatisfy { $0.query == [URLQueryItem(name: "after", value: "42")] })
+ #expect(requests.last?.bearer == "equipo.person.v1.RENEWED")
+ #expect(f.transport.sent("POST /auth/devices/native").count == 2)
+ }
+ }
+
+ @Test func repeatedRejectionsAreRateLimitedAndKeepConversation() async throws {
+ let f = IDFixture(); await f.signIn()
+ let original = try #require(f.app.session)
+ f.transport.on("GET /me", .success(APIResponse(status: 401, data: Data())))
+ for _ in 0..<3 { _ = try? await original.client.me() }
+ #expect(f.transport.sent("POST /auth/devices/native").count == 2)
+ #expect(f.app.session === original)
+ }
+
+ @Test func signOutStopsPushesAndRevokesThisDevice() async throws {
+ let f = IDFixture(); await f.signIn()
+ #expect(f.notifications.asked > 0)
+ await f.app.push.attach(f.app.session?.client)
+ let generation = f.app.push.generation
+ f.app.needsYouChanged(3)
+ await f.app.signOut()
+ #expect(f.notifications.unregistered == 1)
+ #expect(f.app.accounts.all().isEmpty)
+ #expect(f.notifications.badges.last == 0)
+ #expect(f.app.session == nil)
+ await f.app.oficina.cleanup?.value
+ #expect(f.app.push.generation == generation + 1)
+ #expect(f.transport.sent("DELETE /auth/devices/dev_01JD5Z4Q2X").count == 1)
+ let count = f.transport.sent("POST /auth/devices/native").count
+ await f.app.oficina.renewIfNeeded()
+ #expect(f.transport.sent("POST /auth/devices/native").count == count)
+ #expect(f.model.step == .welcome)
+ }
+
+ @Test func replacementThroughKitAlsoForgetsDeviceAndPushes() async throws {
+ let f = IDFixture(); await f.signIn()
+ f.model.useAnother()
+ #expect(f.app.session != nil)
+ f.model.cancelReplace()
+ #expect(f.app.session != nil)
+ f.model.useAnother(); f.model.confirmReplace()
+ #expect(f.app.session == nil)
+ #expect(f.app.accounts.all().isEmpty)
+ #expect(f.notifications.unregistered == 1)
+ #expect(f.model.step == .email)
+ }
+
+ @Test func sharedIdentityRemovalLeavesAnActiveFallbackPairingAlone() async throws {
+ let f = IDFixture(); await f.signIn()
+ f.app.otherWays()
+ var paired = DeviceAccount.new(origin: f.transport.origin, label: "Paired")
+ paired.credential = try Fixture.decode("device-credential")
+ try f.app.accounts.commit(.save(paired), lifetime: f.app.accounts.lifetimes.current)
+ f.app.adopt(paired, transport: f.transport)
+ f.model.signOut()
+ #expect(f.app.session?.account == paired)
+ #expect(f.app.accounts.all() == [paired])
+ }
+
+ @Test func onlyDeviceRegistrationMaySendTheSessionCookie() throws {
+ for path in ["/snapshot", "/auth/devices", "/auth/devices/exchange"] {
+ #expect(throws: EquipoAPIError.badOrigin) {
+ try APIRequest("POST", path, nativeSession: NativeSession(name: "session", value: "fixture"))
+ .urlRequest(origin: URL(string: "https://example.test")!)
+ }
+ }
+ }
+
+ @Test func deviceEndpointRejectionRemintsTheKitSession() async throws {
+ let f = IDFixture()
+ f.transport.replace("POST /auth/devices/native", with: .success(APIResponse(status: 403, data: Data())))
+ f.transport.on("POST /auth/devices/native", fixture: "device-credential")
+ await f.signIn()
+ #expect(f.app.session != nil)
+ #expect(f.transport.sent("POST /auth/devices/native").count == 2)
+ let cookies = f.transport.sent("POST /auth/devices/native").compactMap { $0.nativeSession?.value }
+ #expect(Set(cookies).count == 2)
+ }
+
+ @Test func nativeCredentialWhoseIdentityWasRemovedCannotSurviveRelaunch() async throws {
+ let f = IDFixture(); await f.signIn()
+ try f.model.store.remove("id-1")
+ let transport = f.transport
+ let freshModel = OficinaIDModel(configuration: EquipoOficinaID.configuration,
+ store: OficinaIDStore(shared: f.shared, appPrivate: f.privateStore, group: f.defaults),
+ service: f.service, passkeys: FakePasskeys(), makeKey: { OficinaSoftwareKey() }, appDefaults: f.defaults)
+ let relaunched = EquipoAppModel(store: f.secrets, push: PushRegistrar(environment: nil), oficinaModel: freshModel,
+ makeTransport: { _ in transport })
+ await relaunched.start()
+ #expect(relaunched.session == nil)
+ #expect(relaunched.accounts.all().isEmpty)
+ }
+
+ @Test func lateRegistrationCannotRestoreSignedOutDevice() async throws {
+ let held = HeldIDTransport()
+ let f = IDFixture(held: held)
+ try await f.seedIdentity()
+ let start = Task { await f.app.start() }
+ await held.waitUntilEntered()
+ await f.app.signOut()
+ await held.release()
+ await start.value
+ #expect(f.app.session == nil)
+ #expect(f.app.accounts.all().isEmpty)
+ #expect(f.model.identity == nil)
+ }
+
+ @Test func lateSnapshotCannotRestoreSignedOutDevice() async throws {
+ let held = HeldEquipoRead()
+ let f = IDFixture(held: held)
+ await f.signIn()
+ let departed = try #require(f.app.session)
+ await held.hold("/snapshot")
+ let refresh = Task { await departed.refresh() }
+ await held.waitUntilEntered()
+ await f.app.signOut()
+ #expect(f.app.accounts.all().isEmpty)
+ await held.release()
+ await refresh.value
+ #expect(departed.status == .signedOut)
+ #expect(departed.me == nil)
+ #expect(f.app.session == nil)
+ #expect(f.app.accounts.all().isEmpty)
+ }
+
+ @Test func lateRenewalCannotRestoreSignedOutDevice() async throws {
+ let held = HeldEquipoRead()
+ let f = IDFixture(held: held)
+ await f.signIn()
+ let departed = try #require(f.app.session)
+ let oldAccount = departed.account
+ f.clock.advance(86401)
+ await held.nativeToken("ABANDONED")
+ await held.hold("/auth/devices/native")
+ let renewal = Task { await f.app.oficina.renewIfNeeded() }
+ await held.waitUntilEntered()
+ await f.app.signOut()
+ await held.release()
+ await renewal.value
+ #expect(f.app.session == nil)
+ #expect(f.app.accounts.all().isEmpty)
+ #expect(f.app.oficina.account == nil)
+ #expect(f.model.identity == nil)
+ #expect(await held.sent("DELETE /auth/devices/dev_01JD5Z4Q2X").contains { $0.bearer == "equipo.person.v1.ABANDONED" })
+ // Even a queued adoption and direct metadata update cannot reopen
+ // the departed session or save its private key again.
+ departed.renew(oldAccount, transport: held)
+ departed.apply(try Fixture.decode("thin/snapshot"))
+ #expect(departed.status == .signedOut)
+ #expect(f.app.accounts.all().isEmpty)
+ }
+
+ @Test(arguments: ["pairing", "replacement", "ended"])
+ func departingSessionCannotPersistAfterItsReplacement(_ route: String) async throws {
+ let held = HeldEquipoRead()
+ let f = IDFixture(held: held); await f.signIn()
+ let departed = try #require(f.app.session)
+ await held.hold("/snapshot")
+ let refresh = Task { await departed.refresh() }
+ await held.waitUntilEntered()
+ switch route {
+ case "pairing": f.app.otherWays()
+ case "replacement":
+ var next = departed.account
+ next.oficinaTeam = "replacement"
+ try f.app.accounts.commit(.save(next), lifetime: f.app.accounts.lifetimes.current)
+ f.app.adopt(next, transport: held)
+ default: f.app.sessionEnded()
+ }
+ let saved = f.app.accounts.all()
+ await held.release()
+ await refresh.value
+ #expect(departed.status == .signedOut)
+ #expect(departed.me == nil)
+ #expect(f.app.accounts.all() == saved)
+ }
+
+ @Test func latePairingRevocationCannotRemoveANewCredential() async throws {
+ let held = HeldEquipoRead()
+ let accounts = DeviceAccounts(store: MemorySecretStore())
+ var old = DeviceAccount.new(origin: held.origin, label: "Old phone")
+ old.credential = try Fixture.decode("device-credential")
+ try accounts.commit(.save(old), lifetime: accounts.lifetimes.current)
+ let departed = EquipoSession(account: old, accounts: accounts, transport: held)
+ await held.hold("/auth/devices")
+ let signOut = Task { await departed.signOut() }
+ await held.waitUntilEntered()
+ #expect(departed.status == .signedOut)
+ #expect(accounts.all().isEmpty)
+ var replacement = old
+ replacement.keySeed = DeviceAccount.new(origin: held.origin, label: "New phone").keySeed
+ accounts.lifetimes.begin()
+ try accounts.commit(.save(replacement), lifetime: accounts.lifetimes.current)
+ await held.release()
+ await signOut.value
+ #expect(accounts.all() == [replacement])
+ }
+
+ @Test func unavailableRenewalShowsRecoveryWithoutAnErrorString() async throws {
+ let f = IDFixture(); await f.signIn()
+ let original = try #require(f.app.session)
+ #expect(EquipoOficinaNotice(model: f.app).message == nil)
+ f.service.failNext("assert", at: f.transport.origin.absoluteString, with: .offline)
+ f.transport.on("GET /me", .success(APIResponse(status: 401, data: Data())))
+ _ = try? await original.client.me()
+ guard case .unavailable = f.model.step else { Issue.record("expected an unavailable team"); return }
+ #expect(f.app.oficina.error == nil)
+ #expect(f.model.error == nil)
+ #expect(EquipoOficinaNotice(model: f.app).message == OficinaIDText.text("unavailable.title"))
+ #expect(f.app.session === original)
+ await f.app.oficina.renewIfNeeded()
+ #expect(EquipoOficinaNotice(model: f.app).message == nil)
+ #expect(f.app.session === original)
+ }
+
+ @Test(arguments: ["/auth/devices/exchange", "/me"], [false, true])
+ func cancelledPairingCannotOverwriteNativeSignIn(_ boundary: String, _ signOut: Bool) async throws {
+ let held = HeldEquipoRead()
+ let f = IDFixture(held: held)
+ try await f.seedIdentity()
+ f.app.otherWays(); await f.app.start()
+ await held.hold(boundary)
+ f.app.pairing.start(origin: held.origin, label: "Abandoned pairing")
+ await held.waitUntilEntered()
+ await held.nativeToken("NEW_SIGN_IN")
+ await f.app.useOficinaID()
+ let native = try #require(f.app.session?.account)
+ if signOut { await f.app.signOut(); await f.app.oficina.cleanup?.value }
+ await held.release()
+ // Wait for the abandoned pairing's network cleanup as well as /me.
+ for _ in 0..<200 {
+ if await held.sent("DELETE /auth/devices/dev_01JD5Z4Q2X").contains(where: { $0.bearer == "equipo.person.v1.TOKENFIXTURE" }) { break }
+ try await Task.sleep(for: .milliseconds(5))
+ }
+ #expect(f.app.accounts.all() == (signOut ? [] : [native]))
+ #expect(f.app.pairing.account == nil)
+ #expect(f.app.pairing.step == .enterTeam)
+ #expect(await held.sent("DELETE /auth/devices/dev_01JD5Z4Q2X").contains { $0.bearer == "equipo.person.v1.TOKENFIXTURE" })
+ }
+
+ @Test func departedWriteCannotRetryWithALaterSignInsBearer() async throws {
+ let held = HeldEquipoRead()
+ let f = IDFixture(held: held); await f.signIn()
+ let departed = try #require(f.app.session)
+ let outer = try #require(departed.client.transport as? LifetimeTransport)
+ let renewing = try #require(outer.inner as? EquipoRenewingTransport)
+ let snapshot: Snapshot = try Fixture.decode("thin/snapshot")
+ let card = try #require(snapshot.cards?.first { $0.isOpen })
+ let route = "POST /cards/\(card.id)/answer"
+ await held.answerFailure(route)
+ await held.hold("/cards/\(card.id)/answer")
+ let answer = Task { await departed.answer(card, choice: "wait_mac") }
+ await held.waitUntilEntered()
+ await f.app.signOut()
+ await f.app.oficina.cleanup?.value
+ await f.model.cleanup?.value
+ await held.nativeToken("NEW_SIGN_IN")
+ await f.signIn()
+ #expect(f.app.session?.account.credential?.token == "equipo.person.v1.NEW_SIGN_IN")
+ #expect(renewing.credential() == nil)
+ await held.release()
+ #expect(await answer.value == .failed)
+ #expect(await held.sent(route).count == 1)
+ // A retained client is also bound, independently of the write loop.
+ _ = try? await departed.client.me()
+ #expect(await held.sent("GET /me").isEmpty)
+ }
+
+ @Test(arguments: [false, true])
+ func endedWriteLoopsDoNotWaitOrRetry(_ aside: Bool) async throws {
+ let held = HeldEquipoRead()
+ let f = IDFixture(held: held); await f.signIn()
+ let current = try #require(f.app.session)
+ let sleeps = Sleeps()
+ let worker = EquipoSession(account: current.account, accounts: f.app.accounts,
+ transport: current.client.transport, lifetime: current.lifetime, sleep: sleeps.sleep)
+ let snapshot: Snapshot = try Fixture.decode("thin/snapshot")
+ let card = try #require(snapshot.cards?.first { $0.kind == "merge" && $0.isOpen })
+ let path = "/cards/\(card.id)/" + (aside ? "visibility" : "answer")
+ await held.answerFailure("POST " + path)
+ await held.hold(path)
+ let write = Task { aside ? await worker.setAside(card, true) : await worker.answer(card, choice: "wait_mac") }
+ await held.waitUntilEntered()
+ await f.app.signOut()
+ await held.release()
+ #expect(await write.value == .failed)
+ #expect(sleeps.waits.isEmpty)
+ #expect(await held.sent("POST " + path).count == 1)
+ }
+
+ @Test func endedTransportRefusesLateResponsesAndNewRequests() async throws {
+ let held = HeldEquipoRead()
+ let lifetimes = SignInLifetimes()
+ let lifetime = lifetimes.current
+ let transport = LifetimeTransport(inner: held, lifetime: lifetime)
+ await held.hold("/me")
+ let read = Task { try await transport.send(APIRequest("GET", "/me", bearer: "old")) }
+ await held.waitUntilEntered()
+ lifetimes.begin()
+ await held.release()
+ var rejected = false
+ do { _ = try await read.value } catch is CancellationError { rejected = true }
+ #expect(rejected)
+ _ = try? await transport.send(APIRequest("GET", "/snapshot", bearer: "old"))
+ #expect(await held.sent("GET /snapshot").isEmpty)
+ }
+
+ @Test(arguments: [false, true])
+ func cancellingPairingAloneEndsItsLifetime(_ signOut: Bool) async throws {
+ let held = HeldEquipoRead()
+ let f = IDFixture(held: held)
+ f.app.otherWays(); await f.app.start()
+ await held.hold("/auth/devices/exchange")
+ f.app.pairing.start(origin: held.origin, label: "Cancelled")
+ await held.waitUntilEntered()
+ let lifetime = try #require(f.app.pairing.lifetime)
+ if signOut { await f.app.signOut() } else { f.app.pairing.cancel() }
+ #expect(!lifetime.isActive)
+ await held.release()
+ for _ in 0..<200 {
+ if !(await held.sent("DELETE /auth/devices/dev_01JD5Z4Q2X")).isEmpty { break }
+ try await Task.sleep(for: .milliseconds(5))
+ }
+ #expect(f.app.accounts.all().isEmpty)
+ #expect(f.app.pairing.step == .enterTeam)
+ #expect(await held.sent("DELETE /auth/devices/dev_01JD5Z4Q2X").count == 1)
+ }
+
+ @Test(arguments: [false, true])
+ func signOutBeforeRegistrationEndsThePendingLifetime(_ throughKit: Bool) async {
+ let f = IDFixture()
+ let lifetime = f.app.accounts.lifetimes.current
+ if throughKit { f.app.oficina.signOut() } else { await f.app.signOut() }
+ #expect(!lifetime.isActive)
+ #expect(f.app.accounts.all().isEmpty)
+ }
+
+ @Test func signingOutAfterTheSessionEndsStillForgetsItsCredential() async throws {
+ let f = IDFixture(); await f.signIn()
+ f.app.sessionEnded()
+ await f.app.signOut()
+ #expect(f.app.accounts.all().isEmpty)
+ await f.app.oficina.cleanup?.value
+ #expect(f.transport.sent("DELETE /auth/devices/dev_01JD5Z4Q2X").count == 1)
+ }
+
+ @Test(arguments: ["continueAs", "unavailable"], ["appSignOut", "bridgeSignOut", "replacement", "pairing"])
+ func leavingBeforeBridgeSynchronizesForgetsEveryNativeAccount(_ landing: String, _ route: String) async throws {
+ let f = IDFixture()
+ try await f.seedIdentity()
+ var native = DeviceAccount.new(origin: f.transport.origin, label: "Saved native")
+ native.credential = try Fixture.decode("device-credential")
+ native.oficinaIdentity = "id-1"
+ var another = native
+ another.origin = URL(string: "https://another.example.test")!
+ another.oficinaIdentity = "another-identity"
+ var paired = native
+ paired.origin = URL(string: "https://paired.example.test")!
+ paired.oficinaIdentity = nil
+ for account in [native, another, paired] {
+ try f.app.accounts.commit(.save(account), lifetime: f.app.accounts.lifetimes.current)
+ }
+ f.service.failNext("assert", with: .offline)
+ await f.app.start()
+ if landing == "unavailable" {
+ f.service.failNext("assert", at: f.transport.origin.absoluteString, with: .offline)
+ await f.model.choose(f.team())
+ }
+ if landing == "continueAs" {
+ guard case .continueAs = f.model.step else { Issue.record("expected Continue as"); return }
+ } else {
+ guard case .unavailable = f.model.step else { Issue.record("expected unavailable"); return }
+ }
+ #expect(f.app.oficina.account == nil)
+ #expect(f.app.session == nil)
+ switch route {
+ case "appSignOut": await f.app.signOut()
+ case "bridgeSignOut": f.app.oficina.signOut()
+ case "replacement": f.model.useAnother(); f.model.confirmReplace()
+ default: f.app.otherWays()
+ }
+ #expect(f.app.accounts.all() == [paired])
+ await f.app.oficina.cleanup?.value
+ #expect(f.transport.sent("DELETE /auth/devices/dev_01JD5Z4Q2X").count == 2)
+ #expect(f.app.accounts.all() == [paired])
+ }
+
+ @Test(arguments: ["appSignOut", "bridgeSignOut", "pairing"])
+ func leavingBeforeIdentityLoadsForgetsTheSavedBearer(_ route: String) async throws {
+ let f = IDFixture()
+ var native = DeviceAccount.new(origin: f.transport.origin, label: "Saved native")
+ native.credential = try Fixture.decode("device-credential")
+ native.oficinaIdentity = "id-1"
+ try f.app.accounts.commit(.save(native), lifetime: f.app.accounts.lifetimes.current)
+ #expect(f.model.identity == nil)
+ switch route {
+ case "appSignOut": await f.app.signOut()
+ case "bridgeSignOut": f.app.oficina.signOut()
+ default: f.app.otherWays()
+ }
+ #expect(f.app.accounts.all().isEmpty)
+ await f.app.oficina.cleanup?.value
+ #expect(f.transport.sent("DELETE /auth/devices/dev_01JD5Z4Q2X").count == 1)
+ }
+
+ @Test(arguments: ["appSignOut", "bridgeSignOut", "replacement", "server"])
+ func onlyServerSessionEndShowsTheEndedTeamNotice(_ route: String) async throws {
+ let f = IDFixture(); await f.signIn()
+ let team = try #require(f.app.session?.teamName)
+ switch route {
+ case "appSignOut": await f.app.signOut()
+ case "bridgeSignOut": f.app.oficina.signOut()
+ case "replacement": f.model.useAnother(); f.model.confirmReplace()
+ default: f.app.sessionEnded()
+ }
+ f.app.otherWays()
+ #expect(f.app.endedTeam == (route == "server" ? team : nil))
+ }
+
+ @Test func permissionRefusalDuringHomeOutageKeepsTheKitSession() async throws {
+ let f = IDFixture(); await f.signIn()
+ let original = try #require(f.app.session)
+ let credential = try #require(try f.model.store.credential("id-1"))
+ let stored = try #require(f.model.store.session(grantID: credential.grantID, origin: f.transport.origin))
+ f.service.failNext("assert", at: f.transport.origin.absoluteString, with: .offline)
+ f.transport.on("GET /me", .success(APIResponse(status: 403, data: Data())))
+ do {
+ _ = try await original.client.me()
+ Issue.record("expected the permission refusal")
+ } catch let error as EquipoAPIError { #expect(error.status == 403) }
+ // The kit's only forced re-mint API deletes before contacting Home.
+ // Keep this executable reproduction until the kit can preserve a usable
+ // session during forced renewal. Unexpected success fails this test.
+ withKnownIssue("Kit sessionRejected deletes the usable session before an offline re-mint") {
+ #expect(f.model.store.session(grantID: credential.grantID, origin: f.transport.origin)?.session == stored.session)
+ }
+ #expect(f.app.session === original)
+ }
+
+ @Test func oldSavedPairingStillLoadsWithoutOficinaID() throws {
+ let f = IDFixture()
+ var account = DeviceAccount.new(origin: f.transport.origin, label: "Old phone")
+ account.credential = try Fixture.decode("device-credential")
+ try f.app.accounts.commit(.save(account), lifetime: f.app.accounts.lifetimes.current)
+ let relaunched = EquipoAppModel(store: f.secrets, push: PushRegistrar(environment: nil), oficinaModel: f.model)
+ #expect(relaunched.session?.account == account)
+ #expect(relaunched.showingPairing)
+ }
+}
+
+/// Holds the first device answer until sign-out has invalidated its request.
+private actor HeldIDTransport: EquipoTransport {
+ nonisolated let origin = URL(string: "https://oficina.example.test")!
+ private var entered = false
+ private var continuation: CheckedContinuation<Void, Never>?
+ func send(_ request: APIRequest) async throws -> APIResponse {
+ if request.path == "/auth/devices/native" {
+ entered = true
+ await withCheckedContinuation { continuation = $0 }
+ return APIResponse(status: 200, data: Fixture.data("device-credential"))
+ }
+ return APIResponse(status: 404, data: Data())
+ }
+ func lines(_ request: APIRequest) async throws -> AsyncThrowingStream<String, Error> { throw EquipoAPIError.offline }
+ func waitUntilEntered() async {
+ while !entered { await Task.yield() }
+ }
+ func release() { continuation?.resume(); continuation = nil }
+}
+
+private actor IDDailySleep {
+ let clock: IDClock
+ var waits: [Duration] = []
+ init(clock: IDClock) { self.clock = clock }
+ func wait(_ duration: Duration) throws {
+ waits.append(duration)
+ if waits.count > 1 { throw CancellationError() }
+ clock.advance(86401)
+ }
+}
+
+/// Lets an actual scripted response arrive after its caller has signed out.
+/// Cancellation deliberately does not release it: a network reply can be late.
+private actor HeldEquipoRead: EquipoTransport {
+ nonisolated let origin = URL(string: "https://oficina.example.test")!
+ private let script = ScriptedTransport()
+ private var path: String?
+ private var entered = false
+ private var continuation: CheckedContinuation<Void, Never>?
+ init() {
+ script.on("POST /auth/devices/native", fixture: "device-credential")
+ script.on("POST /auth/devices", fixture: "device-challenge")
+ script.on("POST /auth/devices/exchange", fixture: "device-credential")
+ script.on("GET /me", fixture: "me")
+ script.on("GET /auth/devices", fixture: "devices")
+ script.on("DELETE /auth/devices/dev_01JD5Z4Q2X", fixture: "ack")
+ script.on("GET /snapshot", fixture: "thin/snapshot")
+ script.on("GET /tasks", fixture: "thin/tasks")
+ script.on("GET /needs-you", fixture: "thin/needs-you")
+ }
+ func hold(_ path: String) { self.path = path; entered = false }
+ func send(_ request: APIRequest) async throws -> APIResponse {
+ let response: Result<APIResponse, Error>
+ do { response = .success(try await script.send(request)) }
+ catch { response = .failure(error) }
+ if request.path == path {
+ path = nil
+ entered = true
+ await withCheckedContinuation { continuation = $0 }
+ }
+ return try response.get()
+ }
+ func nativeToken(_ value: String) {
+ let data = String(decoding: Fixture.data("device-credential"), as: UTF8.self).replacingOccurrences(of: "TOKENFIXTURE", with: value)
+ script.replace("POST /auth/devices/native", with: .success(APIResponse(status: 200, data: Data(data.utf8))))
+ }
+ func answerFailure(_ route: String) {
+ script.on(route, .failure(.offline), .success(APIResponse(status: 200, data: Fixture.data("thin/answered"))))
+ }
+ func sent(_ route: String) -> [APIRequest] { script.sent(route) }
+ func lines(_ request: APIRequest) async throws -> AsyncThrowingStream<String, Error> { throw EquipoAPIError.offline }
+ func waitUntilEntered() async { while !entered { await Task.yield() } }
+ func release() { continuation?.resume(); continuation = nil }
+}
diff --git a/native/apple/Tests/EquipoKitTests/PushTests.swift b/native/apple/Tests/EquipoKitTests/PushTests.swift
index 8b2d372a..86b31235 100644
--- a/native/apple/Tests/EquipoKitTests/PushTests.swift
+++ b/native/apple/Tests/EquipoKitTests/PushTests.swift
@@ -25,6 +25,20 @@ private func json(_ request: APIRequest) throws -> [String: String] {
}
@MainActor @Suite struct PushRegistrationTests {
+ @Test func lateAttachCannotReplaceTheNextSignIn() async throws {
+ let t = ScriptedTransport(); registered(t)
+ let r = PushRegistrar(environment: .production, platform: .ios)
+ let lifetimes = SignInLifetimes()
+ let old = lifetimes.current
+ await r.deviceTokenChanged(deviceToken)
+ let next = lifetimes.begin()
+ await r.attach(client(t, "new-sign-in"), lifetime: next)
+ let generation = r.generation
+ await r.attach(client(t, "old-sign-in"), lifetime: old)
+ #expect(r.generation == generation)
+ #expect(t.sent("POST /push-registrations").map(\.bearer) == ["new-sign-in"])
+ }
+
@Test func theBodyIsTheServersShapeInLowercaseHex() throws {
let body = PushRegistrationBody(token: PushToken.hex(deviceToken), environment: .production, platform: .ios, startToken: PushToken.hex(startToken))
let sent = try JSONSerialization.jsonObject(with: try EquipoJSON.encoder.encode(body)) as! [String: String]
diff --git a/native/apple/Tests/EquipoKitTests/SessionTests.swift b/native/apple/Tests/EquipoKitTests/SessionTests.swift
index c6ae99cc..e9fcc784 100644
--- a/native/apple/Tests/EquipoKitTests/SessionTests.swift
+++ b/native/apple/Tests/EquipoKitTests/SessionTests.swift
@@ -6,7 +6,7 @@ import Testing
var account = DeviceAccount.new(origin: t.origin, label: "Test")
account.credential = try Fixture.decode("device-credential")
let accounts = DeviceAccounts(store: store)
- try accounts.save(account)
+ try accounts.commit(.save(account), lifetime: accounts.lifetimes.current)
return EquipoSession(account: account, accounts: accounts, transport: t, sleep: { _ in })
}
diff --git a/native/apple/Tests/EquipoKitTests/SetAsideTests.swift b/native/apple/Tests/EquipoKitTests/SetAsideTests.swift
index c3d341b8..de942556 100644
--- a/native/apple/Tests/EquipoKitTests/SetAsideTests.swift
+++ b/native/apple/Tests/EquipoKitTests/SetAsideTests.swift
@@ -16,7 +16,7 @@ import Testing
var account = DeviceAccount.new(origin: t.origin, label: "Test")
account.credential = try Fixture.decode("device-credential")
let accounts = DeviceAccounts(store: MemorySecretStore())
- try accounts.save(account)
+ try accounts.commit(.save(account), lifetime: accounts.lifetimes.current)
let s = EquipoSession(account: account, accounts: accounts, transport: t, sleep: { _ in })
await s.refresh()
return s
diff --git a/native/apple/Tests/EquipoKitTests/SignInLifetimeTests.swift b/native/apple/Tests/EquipoKitTests/SignInLifetimeTests.swift
new file mode 100644
index 00000000..ecc02e61
--- /dev/null
+++ b/native/apple/Tests/EquipoKitTests/SignInLifetimeTests.swift
@@ -0,0 +1,27 @@
+import Foundation
+import Testing
+@testable import EquipoKit
+
+@MainActor @Suite struct SignInLifetimeTests {
+ @Test func endedOrForeignLifetimesCannotPersistAnything() throws {
+ let store = MemorySecretStore()
+ let accounts = DeviceAccounts(store: store)
+ let old = accounts.lifetimes.current
+ var account = DeviceAccount.new(origin: URL(string: "https://example.test")!, label: "Test")
+ account.credential = try Fixture.decode("device-credential")
+ try accounts.commit(.save(account), lifetime: old)
+ old.end()
+ let before = store.accounts.sorted().map { store.read($0) }
+ for token in [old, SignInLifetimes().current] {
+ for change in [DeviceAccounts.Change.save(account), .remove(account), .route("pairing")] {
+ #expect(throws: CancellationError.self) { try accounts.commit(change, lifetime: token) }
+ }
+ }
+ #expect(store.accounts.sorted().map { store.read($0) } == before)
+ let next = accounts.lifetimes.begin()
+ #expect(!old.isActive)
+ #expect(next !== old)
+ try accounts.commit(.remove(account), lifetime: next)
+ #expect(accounts.all().isEmpty)
+ }
+}
diff --git a/native/apple/Tests/EquipoKitTests/Support.swift b/native/apple/Tests/EquipoKitTests/Support.swift
index 2b16896d..379289ce 100644
--- a/native/apple/Tests/EquipoKitTests/Support.swift
+++ b/native/apple/Tests/EquipoKitTests/Support.swift
@@ -13,6 +13,9 @@ final class ScriptedTransport: EquipoTransport, @unchecked Sendable {
func on(_ route: String, _ answers: Result<APIResponse, EquipoAPIError>...) {
lock.withLock { script[route, default: []] += answers }
}
+ func replace(_ route: String, with answer: Result<APIResponse, EquipoAPIError>) {
+ lock.withLock { script[route] = [answer] }
+ }
func on(_ route: String, fixture: String, status: Int = 200) { on(route, .success(APIResponse(status: status, data: Fixture.data(fixture)))) }
func on(_ route: String, status: Int, fixture: String) { on(route, .success(APIResponse(status: status, data: Fixture.data(fixture)))) }
diff --git a/native/ios/EquipoPhone.entitlements b/native/ios/EquipoPhone.entitlements
index 527170f6..8e48c363 100644
--- a/native/ios/EquipoPhone.entitlements
+++ b/native/ios/EquipoPhone.entitlements
@@ -9,5 +9,15 @@
profiles must carry aps-environment. -->
<key>aps-environment</key>
<string>$(EQUIPO_APS_ENVIRONMENT)</string>
+ <!-- Keep the old default group first so saved pairings remain readable. -->
+ <key>keychain-access-groups</key>
+ <array>
+ <string>9U4A84C4WK.works.oficina.equipo</string>
+ <string>9U4A84C4WK.works.oficina.id</string>
+ </array>
+ <key>com.apple.security.application-groups</key>
+ <array><string>group.works.oficina</string></array>
+ <key>com.apple.developer.associated-domains</key>
+ <array><string>webcredentials:id.oficina.works</string></array>
</dict>
</plist>
diff --git a/native/macos/DeveloperID.entitlements b/native/macos/DeveloperID.entitlements
index 72cdda88..df6e8b58 100644
--- a/native/macos/DeveloperID.entitlements
+++ b/native/macos/DeveloperID.entitlements
@@ -9,5 +9,15 @@
it (bundle-mac.py), gets no APNs token and does not register. -->
<key>com.apple.developer.aps-environment</key>
<string>production</string>
+ <!-- Keep the old default group first so saved pairings remain readable. -->
+ <key>keychain-access-groups</key>
+ <array>
+ <string>9U4A84C4WK.works.oficina.equipo</string>
+ <string>9U4A84C4WK.works.oficina.id</string>
+ </array>
+ <key>com.apple.security.application-groups</key>
+ <array><string>9U4A84C4WK.works.oficina</string></array>
+ <key>com.apple.developer.associated-domains</key>
+ <array><string>webcredentials:id.oficina.works</string></array>
</dict>
</plist>
diff --git a/native/scripts/build-mac.sh b/native/scripts/build-mac.sh
index 4ef6fb92..9b9f433d 100755
--- a/native/scripts/build-mac.sh
+++ b/native/scripts/build-mac.sh
@@ -3,6 +3,9 @@
# "Oficina Equipo" in Finder and the Dock, "Equipo" in its menus, Sparkle
# configured from mac-updates.json. Signs ad hoc unless --sign-identity says
# otherwise; never notarises or publishes.
+# --provisioning-profile PATH and --entitlements PATH override mac-updates.json.
+# The pinned kit embeds the profile at Contents/embedded.provisionprofile
+# before signing. Ad hoc builds omit restricted grants and never open a profile.
set -eu
cd "$(dirname "$0")/.."
swift package --package-path apple resolve
diff --git a/native/scripts/check-native.sh b/native/scripts/check-native.sh
index 13cb067a..af401099 100755
--- a/native/scripts/check-native.sh
+++ b/native/scripts/check-native.sh
@@ -5,6 +5,9 @@
set -eu
cd "$(dirname "$0")/.."
logs=build/logs; mkdir -p "$logs"
+swift package --package-path apple resolve
+python3 scripts/check-oficina-id.py
+python3 scripts/check-sign-in-lifetime.py
python3 scripts/check-fixtures.py
python3 scripts/check-strings.py
python3 scripts/check-parity.py
diff --git a/native/scripts/check-oficina-id.py b/native/scripts/check-oficina-id.py
new file mode 100644
index 00000000..be8101fb
--- /dev/null
+++ b/native/scripts/check-oficina-id.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python3
+"""Oficina ID's signing contract, without reading a profile or Keychain."""
+import importlib.util
+import json
+import os
+from pathlib import Path
+import plistlib
+import tempfile
+from unittest.mock import patch
+
+root = Path(__file__).resolve().parents[1]
+config = json.loads((root / 'mac-updates.json').read_text())
+old_default = '9U4A84C4WK.works.oficina.equipo'
+for relative, group, push in [
+ ('ios/EquipoPhone.entitlements', 'group.works.oficina', 'aps-environment'),
+ ('macos/DeveloperID.entitlements', '9U4A84C4WK.works.oficina', 'com.apple.developer.aps-environment'),
+]:
+ values = plistlib.loads((root / relative).read_bytes())
+ # An unspecified access group still selects the old app-private group.
+ assert values['keychain-access-groups'] == [old_default, '9U4A84C4WK.works.oficina.id'], relative
+ assert values['com.apple.security.application-groups'] == [group], relative
+ assert values['com.apple.developer.associated-domains'] == ['webcredentials:id.oficina.works'], relative
+ assert push in values, relative
+assert config['bundle_id'] == 'works.oficina.equipo'
+
+kit = Path(os.environ.get('OFICINA_NATIVE_PACKAGE_PATH', root / 'apple/.build/checkouts/native'))
+spec = importlib.util.spec_from_file_location('mac_updates', kit / 'tools/mac_updates.py')
+module = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(module)
+# Exercise the bundler used by build-mac.sh, with dummy bytes and mocked
+# signing. Never read the private profile or invoke codesign in this check.
+with tempfile.TemporaryDirectory() as temp:
+ temp = Path(temp)
+ app = temp / 'Equipo.app'
+ (app / 'Contents').mkdir(parents=True)
+ (app / 'Contents/Info.plist').write_bytes(plistlib.dumps({'CFBundleIdentifier': config['bundle_id']}))
+ profile = temp / 'fixture.provisionprofile'
+ profile.write_bytes(b'profile fixture')
+ entitlements = root / config['entitlements']
+ assert module.signing_declaration(None, entitlements, profile, {}) == (entitlements, profile)
+ with patch.object(module, 'decode_profile', return_value={}), \
+ patch.object(module, 'signing_entitlements', return_value=({}, [])), \
+ patch.object(module, 'verify_signature'), patch.object(module.subprocess, 'run'):
+ module.sign_bundle(app, 'fixture identity', entitlements, profile)
+ assert (app / 'Contents/embedded.provisionprofile').read_bytes() == profile.read_bytes()
+ # Ad hoc builds neither open the real profile nor retain restricted grants.
+ with patch.object(module, 'decode_profile', side_effect=AssertionError('opened profile')), \
+ patch.object(module.subprocess, 'run'):
+ granted = module.sign_bundle(app, '-', entitlements, temp / 'absent-profile')
+ assert 'keychain-access-groups' not in granted
+ assert not (app / 'Contents/embedded.provisionprofile').exists()
+print('Oficina ID: old default Keychain group, shared grants and Mac profile embedding checked')
diff --git a/native/scripts/check-sign-in-lifetime.py b/native/scripts/check-sign-in-lifetime.py
new file mode 100644
index 00000000..f7d770c5
--- /dev/null
+++ b/native/scripts/check-sign-in-lifetime.py
@@ -0,0 +1,32 @@
+#!/usr/bin/env python3
+"""Equipo's only device/Keychain mutation boundary is lifetime-guarded commit."""
+from pathlib import Path
+import re
+
+root = Path(__file__).resolve().parents[1]
+sources = root / 'apple/Sources/EquipoKit'
+account = sources / 'Pairing/DeviceAccount.swift'
+text = account.read_text()
+assert 'func commit(' in text, 'DeviceAccounts must expose one guarded commit function'
+start = text.index('{', text.index('func commit('))
+depth = 1
+end = start + 1
+while depth:
+ depth += (text[end] == '{') - (text[end] == '}')
+ end += 1
+commit = text[start:end]
+outside = text[:start] + text[end:]
+assert not re.search(r'store\.(?:write|remove)\s*\(', outside), 'persistence outside commit'
+assert 'try lifetimes.require(lifetime)' in commit, 'commit must reject an ended or foreign lifetime'
+assert commit.index('try lifetimes.require(lifetime)') < commit.index('store.write('), 'guard must precede persistence'
+for path in [*sources.rglob('*.swift'), *(root / 'ios').rglob('*.swift'), *(root / 'macos').rglob('*.swift')]:
+ value = path.read_text()
+ if path != account:
+ assert not re.search(r'\b(?:accounts|self\.accounts)\.(?:save|remove)\s*\(', value), f'unguarded account write: {path}'
+ assert not re.search(r'\.write\s*\(', value), f'raw secret-store write: {path}'
+ assert not re.search(r'\b\w*(?:store|Store)\.remove\s*\(', value), f'raw secret-store removal: {path}'
+ if path.name != 'SecretStore.swift':
+ assert not re.search(r'\bSecItem(?:Add|Update|Delete)\s*\(', value), f'raw Keychain write: {path}'
+assert 'private let store: SecretStore' in text, 'raw store must stay private'
+assert not re.search(r'func (?:save|remove)\(', text), 'do not add a persistence bypass'
+print('Sign-in lifetime: device and Keychain writes use the guarded commit')
diff --git a/native/scripts/strings.json b/native/scripts/strings.json
index a9d7d919..5055573a 100644
--- a/native/scripts/strings.json
+++ b/native/scripts/strings.json
@@ -162,5 +162,10 @@
"thread.sent": "Sent",
"track.position %@ %@": "%1$@ of %2$@",
"track.spoken %@": "Stage: %@",
- "work.tl.merge_dropped": "An earlier attempt to add this change was dropped when the task became an exploration."
+ "work.tl.merge_dropped": "An earlier attempt to add this change was dropped when the task became an exploration.",
+ "oficina.device_failed": "Could not connect to this team.",
+ "oficina.sign_in": "Sign in with Oficina ID",
+ "oficina.retry": "Connect again",
+ "oficina.connecting": "Connecting to your team",
+ "oficina.current_team": "Current team"
}