Skip to content

feat(chatd): push chat events to the iOS app over APNs - #416

Merged
ibetitsmike merged 12 commits into
mainfrom
mike/apns-push
Nov 23, 2026
Merged

ibetitsmike merged 12 commits into
mainfrom
mike/apns-push

Conversation

@ibetitsmike

@ibetitsmike ibetitsmike commented Nov 21, 2026 •

Copy link
Copy Markdown
Owner

Xum opened this PR for Mike.
The fork maintainer took it over on 2026-11-23 with Mike's go-ahead.

Chat pushes now reach the Coder for iOS app over APNs, in the fork-apns-push experiment. coderd talks to APNs itself, so there is no relay and no Notification Service Extension. With the experiment off or no APNs key, chatd gets upstream's web push dispatcher unchanged.

What sends a push

Nothing new. The new dispatcher wraps upstream's web push dispatcher and receives what chatd already sends:

  • a root chat's turn that ends waiting or paused,
  • a turn that ends in error,
  • the fork's mid-turn ask_user_question push.

Sub-agent chats, requires_action and interrupts still send nothing. chatd.go is not edited.

Dispatch starts the APNs sends on a goroutine, then sends the web push and returns its result, so APNs never fails or slows the web push or the turn, and a slow web push never delays APNs. The goroutine's context is the caller's without cancel, plus a 10 s timeout on the dispatcher's clock. Each device is sent on its own goroutine under that timeout, so one stalled device does not use up the time of the others. API close waits for sends in flight.

Each device picks the events it wants. Dispatch carries no status, so the dispatcher reads the chat's status:

Chat status Event Devices that get it
error agent error agent_errors on
waiting, paused finished turn finished_turns or questions on
anything else (running, ...) question questions on

A turn that ends with a question looks like a finished turn to the server, which is why questions also gets finished turns. One race is accepted: if a new turn starts before a finished-turn push reads the status, that push is treated as a question.

Web push off. When web push is off and APNs is set up, the dispatcher's PublicKey() returns a fixed non-empty value. chatd uses the key only to decide whether to send at all (chatd.go webpushConfigured). The browser routes and buildinfo read upstream's dispatcher, so they never see this value.

APNs

  • Auth is token based: an ES256 provider token signed with golang-jwt/jwt/v4, kept for 40 minutes, and remade once on 403 ExpiredProviderToken. Concurrent sends that hit the same expired token share one re-sign: the client re-signs only if its cached token is still the one that failed. Requests go over HTTP/2 through net/http. No new module.
  • Headers: apns-push-type: alert, priority 10, expiration 24 h, apns-collapse-id = chat ID.
  • Payload: aps.alert (chat title and body), thread-id, and sound: chime.caf when the device asks for sound. Also link: coder-ios://chat/<id> and deployment (the access URL). A body that would push the payload past 4096 bytes is cut to the longest prefix of whole runes that fits, plus an ellipsis.
  • APNs answers:
    • 410 deletes the device.
    • 400 BadDeviceToken retries once in the other environment and stores that environment if it works; otherwise the device is deleted.
    • 400 DeviceTokenNotForTopic deletes the device without a retry.
    • The delete and the environment move apply only if the row's updated_at is not later than a bound. For a 410 with a timestamp the bound is that timestamp, so only a registration after APNs saw the token go invalid keeps its row. Otherwise the bound is the row the push read, so a device that registered again while a push was in flight keeps its row.
    • 429 and 5xx are logged and dropped.
  • Logs never contain a device token or the provider token. A device shows up as the first 8 hex characters of its token's SHA-256.

Options

Flag Env Default
--chat-apns-key-file CODER_CHAT_APNS_KEY_FILE empty (APNs off)
--chat-apns-key-id CODER_CHAT_APNS_KEY_ID empty
--chat-apns-team-id CODER_CHAT_APNS_TEAM_ID empty
--chat-apns-topic CODER_CHAT_APNS_TOPIC empty (the bundle ID of an app of the key's team)

APNs needs the key file, key ID, team ID and topic. The topic has no default: an APNs key can push only to the apps of its own team.

Ops note: with fork-apns-push on, set CODER_CHAT_APNS_TOPIC to the iOS app's bundle ID. Without it APNs stays off and coderd logs that --chat-apns-topic is missing. The key option is a path, so the key never appears in the deployment config. No APNs misconfiguration stops the server: with the experiment on, a missing option, or a key file that cannot be read or is not a PKCS #8 P-256 key, logs an error at startup that names the missing options or the load error and turns APNs off. chatd then keeps upstream's dispatcher and the APNs routes answer 404, as they do without a key.

API

These are fork routes, behind RequireExperiment. They act on the caller and authorize as webpush_subscription owned by the caller, like upstream's browser subscriptions.

Route Body Result
POST /api/v2/chats/fork/push/apns device_token (hex), environment (sandbox or production), finished_turns, questions, agent_errors, sound 204, insert or update. A token that belonged to another user moves to the caller.
DELETE /api/v2/chats/fork/push/apns device_token 204, also when nothing is registered.
POST /api/v2/chats/fork/push/apns/test device_token 204 when APNs accepted the push, 502 with APNs's answer when it did not or did not answer within the send timeout, 404 for a device the caller has not registered. The caller also needs notification_message:create on themselves, like upstream's web push test, else 403.

Device tokens must be hex, up to 200 characters. The routes store and look them up in lower case, so one device never has two rows. A user keeps at most 10 devices: a registration deletes that user's oldest others in the same statement, and a push goes only to the newest 10, since two registrations at once can pass the limit.

All three answer 404 "APNs is not configured." without a key. The app reads a 403 or 404 as "no server push" and keeps its local notifications.

Schema

One chatd node, chat_apns_devices. The device token is the key, with a CHECK that it is lower case hex, the table references users with ON DELETE CASCADE, and it is indexed by user. Its queries are in forkdb, authorized in dbauthz and timed in dbmetrics:

  • The dispatcher reads and prunes devices as the notifier, like upstream's web push cleanup.
  • It reads the chat as chatd.
  • Moving a device to the other environment checks create, like the upsert, because webpush_subscription defines no update action.

Hook lines in upstream files

coderd/coderd.go gets three hook lines: the chatd config takes api.forkChatPushDispatcher(options.WebPushDispatcher), API gains a forkPush field, and Close calls api.closeForkPushDispatcher() after chatd closes. The design named only the first one. The field and the close hook are there so the test route can reach the APNs client and shutdown can wait for sends in flight.

Scope decisions

  • Devices stay user scoped, not organization scoped: a push goes to the chat owner, like upstream's web push subscriptions.
  • One APNs key serves both environments: Apple's token based keys are valid for sandbox and production alike.
  • The event kind is read from the chat status when the push is built, not carried from chatd, because that would need a change in upstream chatd.go. The race above is accepted.
  • Pushes of one chat are not serialized for the collapse ID. Events of one chat are a turn apart, and APNs does not promise order across requests.

Tests

  • fork_apns_internal_test.go checks the client against a fake APNs (httptest with HTTP/2 and TLS):
    • the HTTP/2 path, each header, the payload, and the JWT, verified with the test key,
    • token reuse and refresh, and one re-sign for concurrent sends on an expired token,
    • ExpiredProviderToken, 410 with and without a timestamp, 429 and 500,
    • the size cut with ASCII, accents, JSON escapes and emoji,
    • key file errors (RSA, P-384, not PEM),
    • no token in a transport error.
  • fork_push_dispatcher_internal_test.go (package coderd, real database behind dbauthz, fake APNs, fake web push):
    • with the experiment off, no key, or a key without the experiment, chatd gets the inner dispatcher itself,
    • a missing option, an unreadable key file or a non-PEM one logs one error (the missing flags, or the load error without the file's contents) and leaves chatd with the inner dispatcher,
    • the status to event mapping, the event filter per status and toggle, and the web-push-off case (APNs only, web push not called),
    • 410 deletes, BadDeviceToken moves the device to production, DeviceTokenNotForTopic deletes without a retry, 429 and 500 keep the device, web push is still sent, and no token is in any log line,
    • the send timeout on a mock clock, one stalled device not blocking another, a blocked web push not delaying APNs, and a push to the newest 10 devices only,
    • a rejection that races a newer registration or predates it keeps the row, and a 410 timestamp after a new registration deletes it, in 10 cases,
    • the test push route: 404 for an unregistered device, 204 with an upper case token, 502 plus delete for a token rejected in both environments, and 502 with the device kept when APNs stalls.
  • fork_push_devices_test.go uses coderdtest and never sends a push:
    • the experiment gate (403) and no key (404),
    • validation, upsert, a token moving between users, DELETE idempotent, and a member who cannot remove or test another user's device,
    • upper case tokens are stored and deleted in lower case,
    • a key without notification_message:create gets 403 on the test push.
  • TestForkQuerier has cases for the six queries. TestUpsertChatAPNsDeviceKeepsTheNewest checks the per-user limit, a re-registration and a token moving between users. The codersdk option and experiment tests are extended.
  • Regenerated: forkdb, apidoc, typesGenerated.ts, CLI and config docs, API docs, and the server help golden files.

Not exercised: a real APNs key and an iOS device.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-23T16:59:23.252717Z 453fa09 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Mike added 2 commits November 21, 2026 23:28
A bad key path or key file after a config edit must not stop the daily
server. The dispatcher logs the reason and hands chatd upstream's
dispatcher, so the APNs routes answer 404 as they do without a key.
One rule for every APNs misconfiguration: log it and leave push off.
Validate no longer rejects partial APNs options; the dispatcher logs the
missing flags at error level and hands chatd upstream's dispatcher.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 54f7cc6056

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coderd/fork_push_devices.go Resolved
Comment thread coderd/fork_push_export_test.go Resolved
Comment thread coderd/fork_apns.go Resolved
Comment thread coderd/fork_push_dispatcher.go Resolved
Comment thread coderd/fork_apns.go Resolved
Comment thread coderd/fork_push_devices.go Resolved
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

Mike authorized the maintainer on 2026-11-23 to take this PR over and merge it when it passes the gates. The maintainer now owns it, and a workstream will finish it on this branch with no force-push.

State at takeover: head c108556237, 14 commits behind main 720ef7bbcd. fork-ci run 44957247726 is green on that head. There is no Codex receipt for this head, and 7 review threads are open (4 P1, 3 P2).

Plan:

  1. Merge main into the branch.
  2. Fix the P1s (organization scope for registrations, canonical device tokens, drop the export-test shim, keep registrations newer than a 410). Fix the P2s or answer each with a reason.
  3. Get a fresh fork-ci run and a clean Codex receipt on the final head.
  4. The maintainer verifies the tests with a negative control, then merges on its own deploy.

This cannot be tested end to end here: that needs a real APNs key and an iOS device. The merge comment will say so.

…0, authorize test pushes, coalesce token refresh
… export shim

Move the dispatcher and test push tests into fork_push_dispatcher_internal_test.go
so no export_test.go shim is needed, add tests for canonical tokens, the test
push authorization and rejections that race a newer registration, and follow
the log message and dbauthz lint rules.
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@codex review

Head 9ed58fe: the five accepted findings are fixed (lower case tokens with a CHECK, conditional delete and environment move on rejection, test push authorization, one re-sign for concurrent refreshes, internal tests instead of the export shim).

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9ed58fe6fc

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coderd/fork_push_dispatcher.go Resolved
Comment thread coderd/fork_push_dispatcher.go Resolved
Comment thread coderd/fork_push_devices.go Resolved
Comment thread coderd/fork_push_dispatcher.go Resolved
Comment thread coderd/fork_push_devices.go Resolved
Comment thread coderd/fork_push_dispatcher.go Resolved
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d596a8d15d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coderd/fork_push_dispatcher.go Resolved
Comment thread coderd/fork_push_devices.go Resolved
Comment thread coderd/fork_push_dispatcher.go Resolved
Comment thread codersdk/fork_chat_config.go Resolved
… require the APNs topic

Start APNs before web push and run the send timeout on a quartz clock.
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 453fa09d57

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@ibetitsmike
ibetitsmike merged commit 53f1cd0 into main Nov 23, 2026
11 checks passed
@ibetitsmike
ibetitsmike deleted the mike/apns-push branch November 23, 2026 17:15
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

Merged as 53f1cd0 (squash), under Mike's order of 2026-11-23 that the lead finishes and merges this PR.

Gates on head 453fa09, checked by the lead:

  1. Head is the verified SHA (the merge used --match-head-commit).
  2. Every check run passed. fork-ci run 45221771443 on this exact head passed (agent-sdk, build, chat-tests, forkdb, graph, schema, site).
  3. Codex receipt 7107981105: "Didn't find any major issues", Reviewed commit 453fa09.
  4. 0 unresolved review threads. Over three Codex rounds: 14 fixed, 4 declined as minor or defensive with a reason (org scope: devices are user scoped like upstream webpush_subscriptions; one key per environment; event kind across the async dispatch would need an upstream chatd.go edit; per-chat ordering, which APNs does not guarantee anyway).
  5. Not behind main 720ef7b.
  6. Test evidence the lead ran in the PR worktree, under the flock:
    • go test ./coderd/ -run 'TestForkChatAPNs|TestForkChatPush' -count=1 -v: 28 PASS.
    • go test ./coderd/database/forkdb/ -run TestUpsertChatAPNsDeviceKeepsTheNewest -count=1: PASS.
    • Negative control: the notification_message:create check disabled, TestForkChatAPNsTestPushNeedsNotificationPermission FAIL.
    • Negative control: lower-case canonicalization disabled, TestForkChatAPNsDeviceTokenIsCanonical FAIL.
    • Files restored and the tree is clean at the head.

Scope and ops notes:

  • Everything sits behind the fork-apns-push experiment and the APNs key options. Without both, the web push dispatcher is passed through unchanged and the routes return 404.
  • With the experiment on, CODER_CHAT_APNS_TOPIC must be set to the iOS app's bundle ID. If it is missing, APNs stays off and an error is logged.
  • The chatdmig node 01a20017..._chat_apns_devices creates the chat_apns_devices table on deploy, whether or not the experiment is on.

Not exercised: a real APNs key, a real iOS device, real APNs responses for DeviceTokenNotForTopic and the 410 timestamp (only mocked), and concurrent registrations racing past the 10-device cap (only the cut at dispatch is tested for that case).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant