Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

fix(ios): enrich notifications and live activity updates

leepokai94398c8521c9
diff --git a/CLAUDE.md b/CLAUDE.md
index d8eaa8af..0cef44b6 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -30,7 +30,7 @@ Bot-based remote for coding agents: persistent named bots on your computer, mess
- Remote screen (`host/src/screen.rs` is the reference): phones view/control the computer over WebRTC (hardware H.264, non-trickle SDP relayed by `screenOffer`, input on data channels `input` / `input-fast`); bots get the built-in `computer` MCP server (`codync-host mcp computer`, `host/src/mcp.rs`) when their `computer` flag is on. Capture/input live in a helper on `~/.codync/screen.sock`: `apps/screen-macos` (macOS, launchd agent via `SMAppService`, owns the TCC grants) or `apps/screen-linux` (`codync-screen`: portals + GStreamer, started by the host). Off by default; `setScreenEnabled` is accepted only from loopback. An interactive phone takes over (bots may only look).
- Multiple computers per account are future work, not a current priority: the product targets one computer. The multi-computer structure (`AccountStore`, `BotReference`) stays because relay/accounts/SSH build on it; don't extend or polish multi-computer features unless asked.
- Environments: **dev** (`dev-api.codync.dev`, Clerk development instance, Debug builds) and **main** (`api.codync.dev`, Clerk production, Release builds); `apps/shared/Config/<env>.plist` becomes `AccountConfig.plist`. Details: [spec §14.0](docs/reference/remote-relay.md).
-- Push: iOS registers its APNs token with `relay/` → gets an AES-GCM ticket → gives it (plus its X25519 push key) to the host; the host seals title/body to that key and a Notification Service Extension opens it, so `relay/` sees only generic text. Only two alert kinds: *needs you* and *done*, suppressed while the iOS app is connected.
+- Push: iOS registers its APNs token with `relay/` → gets an AES-GCM ticket → gives it (plus its X25519 push key) to the host; the host seals title/body to that key and a Notification Service Extension opens it, so `relay/` sees only generic text. Alert kinds: *needs you*, *done*, and *failed*, suppressed while the iOS app is connected. Delivery and lifecycle: [notification design](docs/design/push-and-live-activity.md).
- Voice call (iPhone): on-device speech in, bot's final replies read aloud; the host sees plain messages. Pro cloud-realtime plan: [docs/features/voice-call.md](docs/features/voice-call.md).
- Usage: local only — `claude -p /usage --no-session-persistence`, the Claude status line (`codync-host statusline`, wrapping any existing one), Claude ACP `usage_update` rate-limit meta, Codex rollout files. Never call provider APIs with agent credentials.
- macOS app is thin: embeds `codync-host` in `Contents/MacOS` (Xcode post-build script runs cargo), installs it as a launchd agent via `codync-host install`; menu bar shows status/pairing/usage and opens the native chat window (NavigationSplitView over `CodyncUI`). Not sandboxed, not Mac App Store (the host must spawn CLIs).
diff --git a/apps/ios/App/CodyncApp.swift b/apps/ios/App/CodyncApp.swift
index d83aacc3..c98975ee 100644
--- a/apps/ios/App/CodyncApp.swift
+++ b/apps/ios/App/CodyncApp.swift
@@ -247,6 +247,13 @@ final class AppStore {
final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
UNUserNotificationCenter.current().delegate = self
+ let open = UNNotificationAction(identifier: "openConversation", title: "Open conversation", options: [.foreground])
+ let review = UNNotificationAction(identifier: "reviewRequest", title: "Review request", options: [.foreground])
+ UNUserNotificationCenter.current().setNotificationCategories([
+ UNNotificationCategory(identifier: "done", actions: [open], intentIdentifiers: []),
+ UNNotificationCategory(identifier: "needsInput", actions: [review], intentIdentifiers: []),
+ UNNotificationCategory(identifier: "failed", actions: [open], intentIdentifiers: []),
+ ])
return true
}
diff --git a/apps/ios/App/Push.swift b/apps/ios/App/Push.swift
index 9ace10d6..8b06f38a 100644
--- a/apps/ios/App/Push.swift
+++ b/apps/ios/App/Push.swift
@@ -24,11 +24,17 @@ private func relayTicket(token: Data, kind: String) async throws -> String {
req.httpMethod = "POST"
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.httpBody = try JSONEncoder().encode(Body(token: token.map { String(format: "%02x", $0) }.joined(), env: apnsEnvironment, kind: kind))
- let (data, _) = try await URLSession.shared.data(for: req)
- return try JSONDecoder().decode(Res.self, from: data).ticket
+ req.timeoutInterval = 15
+ let (data, response) = try await URLSession.shared.data(for: req)
+ guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else {
+ throw URLError(.badServerResponse)
+ }
+ let ticket = try JSONDecoder().decode(Res.self, from: data).ticket
+ guard !ticket.isEmpty else { throw URLError(.cannotParseResponse) }
+ return ticket
}
-/// Registers this phone for "needs you" / "done" alerts with every computer it's connected to.
+/// Registers this phone for input, completion, and failure alerts with every computer it's connected to.
/// Each ticket carries this context's push key so the computer can seal the alert text (spec §6.7).
@MainActor
final class PushRegistrar {
@@ -61,10 +67,11 @@ final class PushRegistrar {
func syncDevice(with store: BotStore) {
let id = store.computer.id
stores[id] = WeakStore(store: store)
+ LiveActivities.shared.resume(with: store)
guard let token = deviceToken else {
Task {
let settings = await UNUserNotificationCenter.current().notificationSettings()
- if settings.authorizationStatus == .authorized { UIApplication.shared.registerForRemoteNotifications() }
+ if settings.authorizationStatus == .authorized || settings.authorizationStatus == .provisional { UIApplication.shared.registerForRemoteNotifications() }
}
return
}
@@ -93,7 +100,7 @@ final class PushRegistrar {
final class LiveActivities {
static let shared = LiveActivities()
- private var requests: [UUID: Task<Void, Never>] = [:]
+ private var requests: [String: Task<Void, Never>] = [:]
#if DEBUG
/// Simulator-only visual verification. No host, relay, or APNs request.
@@ -140,30 +147,53 @@ final class LiveActivities {
guard UserDefaults.standard.object(forKey: "liveActivitiesEnabled") as? Bool ?? true else { return }
guard ActivityAuthorizationInfo().areActivitiesEnabled, Self.find(ref) == nil, let client = store.client else { return }
let attributes = BotActivityAttributes(bot: bot, computerId: ref.computerId, link: store.storage.botURL(ref))
- let id = UUID()
- requests[id] = Task.detached { [weak self] in
- await Self.request(attributes: attributes, client: client)
- await self?.finishedRequest(id)
+ do {
+ let state = BotActivityAttributes.ContentState(status: "working", activity: "", startedAt: .now)
+ let activity = try Activity.request(attributes: attributes,
+ content: .init(state: state, staleDate: .now + 15 * 60), pushType: .token)
+ observe(activity, client: client)
+ } catch {
+ log.error("Live activity not started: \(error.localizedDescription)")
}
}
- private func finishedRequest(_ id: UUID) { requests[id] = nil }
+ /// Reattach token observers after a relaunch or connection replacement.
+ func resume(with store: BotStore) {
+ guard UserDefaults.standard.object(forKey: "liveActivitiesEnabled") as? Bool ?? true else { return }
+ guard let client = store.client else { return }
+ for activity in Activity<BotActivityAttributes>.activities
+ where activity.attributes.computerId == store.computer.id {
+ observe(activity, client: client)
+ }
+ }
- private nonisolated static func request(attributes: BotActivityAttributes, client: HostClient) async {
- // Start with status only. Later foreground updates may add the current ACP step locally.
- let state = BotActivityAttributes.ContentState(status: "working", activity: "", startedAt: .now)
- do {
- try Task.checkCancellation()
- let activity = try Activity.request(attributes: attributes, content: .init(state: state, staleDate: .now + 15 * 60), pushType: .token)
+ private func observe(_ activity: Activity<BotActivityAttributes>, client: HostClient) {
+ requests[activity.id]?.cancel()
+ requests[activity.id] = Task {
+ if let token = activity.pushToken { await Self.register(token, activity: activity, client: client) }
for await token in activity.pushTokenUpdates {
- guard !Task.isCancelled else { break }
- guard let ticket = try? await relayTicket(token: token, kind: "liveactivity") else { continue }
- guard !Task.isCancelled else { break }
- try? await client.registerActivity(botId: attributes.botId, ticket: ticket)
+ guard !Task.isCancelled else { return }
+ await Self.register(token, activity: activity, client: client)
+ }
+ }
+ }
+
+ private static func register(_ token: Data, activity: Activity<BotActivityAttributes>, client: HostClient) async {
+ for attempt in 0..<3 {
+ do {
+ try Task.checkCancellation()
+ guard activity.activityState == .active || activity.activityState == .stale else { return }
+ let ticket = try await relayTicket(token: token, kind: "liveactivity")
+ try Task.checkCancellation()
+ try await client.registerActivity(botId: activity.attributes.botId, ticket: ticket)
+ return
+ } catch is CancellationError {
+ return
+ } catch {
+ log.error("Live activity registration failed: \(error.localizedDescription)")
+ guard attempt < 2 else { return }
+ do { try await Task.sleep(for: .seconds(attempt + 1)) } catch { return }
}
- if Task.isCancelled { await activity.end(nil, dismissalPolicy: .immediate) }
- } catch {
- log.info("live activity not started: \(error.localizedDescription)")
}
}
diff --git a/apps/ios/NotificationService/NotificationService.swift b/apps/ios/NotificationService/NotificationService.swift
index ba2436f6..2ad9d850 100644
--- a/apps/ios/NotificationService/NotificationService.swift
+++ b/apps/ios/NotificationService/NotificationService.swift
@@ -1,7 +1,8 @@
import CodyncKit
import UserNotifications
+import os
-/// APNs and the push relay only carry "Needs you" / "Done"; the real title and text arrive
+/// APNs and the push relay carry generic fallback text; the private title and text arrive
/// sealed to this account's push key (spec §6.7). Opening them is local work only: no network.
final class NotificationService: UNNotificationServiceExtension {
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
@@ -11,10 +12,13 @@ final class NotificationService: UNNotificationServiceExtension {
let computerId = info["computerId"] as? String,
let ctx = info["ctx"] as? String,
let alert = DeviceIdentity.openPush(sealed: sealed, computerId: computerId, contextID: ctx) else {
+ Logger(subsystem: "com.pokai.Codync.ios", category: "NotificationService")
+ .error("Showing notification fallback: sealed content or shared key unavailable")
contentHandler(request.content)
return
}
content.title = alert.title
+ content.subtitle = alert.subtitle ?? ""
content.body = alert.body
contentHandler(content)
}
diff --git a/apps/ios/Views/SettingsView.swift b/apps/ios/Views/SettingsView.swift
index d402d71d..6ff2cef4 100644
--- a/apps/ios/Views/SettingsView.swift
+++ b/apps/ios/Views/SettingsView.swift
@@ -72,7 +72,7 @@ struct SettingsView: View {
}
}
- CardSection {
+ CardSection("Notifications", footer: "Get a result summary, a request for input, or a failure notice. Notification previews follow your iOS settings.") {
notificationsRow
}
@@ -200,22 +200,18 @@ struct SettingsView: View {
closeSheets { store.screenRequest = ScreenRequest() }
}
- @ViewBuilder private var notificationsRow: some View {
- if notificationsAllowed == true {
- ValueRow("Notifications", value: "On")
- } else {
- Button {
- if notificationsAllowed == false {
- UIApplication.shared.open(URL(string: UIApplication.openNotificationSettingsURLString)!)
- } else {
- Task { notificationsAllowed = await PushRegistrar.shared.requestAuthorization() }
- }
- } label: {
- ValueRow("Notifications", value: notificationsAllowed == false ? "Off in Settings" : "Turn on")
- .contentShape(Rectangle())
+ private var notificationsRow: some View {
+ Button {
+ if notificationsAllowed != nil {
+ UIApplication.shared.open(URL(string: UIApplication.openNotificationSettingsURLString)!)
+ } else {
+ Task { notificationsAllowed = await PushRegistrar.shared.requestAuthorization() }
}
- .buttonStyle(.plain)
+ } label: {
+ ValueRow("Notifications", value: notificationsAllowed == true ? "On" : notificationsAllowed == false ? "Off in Settings" : "Turn on")
+ .contentShape(Rectangle())
}
+ .buttonStyle(.plain)
}
}
diff --git a/docs/README.md b/docs/README.md
index 6dd72362..11d42c52 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -26,6 +26,7 @@ Source review, a passing build, local integration tests and production acceptanc
- [Remote screen](features/remote-screen.md)
- [Marketplace and agent setup](features/marketplace.md)
- [Widgets, Live Activities and onboarding](design/mobile-widgets.md)
+- [Notifications and background Live Activity updates](design/push-and-live-activity.md)
## Documentation layout
diff --git a/docs/design/mobile-widgets.md b/docs/design/mobile-widgets.md
index 2686617a..1f6d611d 100644
--- a/docs/design/mobile-widgets.md
+++ b/docs/design/mobile-widgets.md
@@ -63,11 +63,11 @@ State 分頁的 Live Activity 頁顯示鎖定畫面形式,Dynamic Island 頁
- Working:顯示目前工作,有開始時間才顯示計時。
- Needs you:顯示待回應提示;審批與文字回應在 App 處理。
- Done:完成勾號與查看結果提示。
-- Stopped:錯誤圖示,不會誤顯示成完成。
+- Failed:錯誤圖示,不會誤顯示成完成。
- Update delayed:ActivityKit 回報 stale 時顯示延遲提示,不繼續顯示即時計時。
- 未知狀態:保守顯示 Waiting for update,不宣稱任務完成。
-既有生命週期繼續由手機送出任務時啟動、App 接收事件時更新、完成時結束。App 本地更新設定 15 分鐘 stale date;沒有更新不代表工作失敗。遠端推播沿用現有 relay/host 合約,這輪未變更後端。關閉 Live Activities 會結束目前活動並阻止之後自動啟動。
+既有生命週期繼續由手機送出任務時啟動、App 接收事件時更新、完成時結束。App 本地更新設定 15 分鐘 stale date;沒有更新不代表工作失敗。遠端推播現在也設定 15 分鐘 stale date、保留錯誤結束狀態,並支援重新註冊活動票券;完整合約與通知設計見 [Notifications and Live Activities](push-and-live-activity.md)。關閉 Live Activities 會結束目前活動並阻止之後自動啟動。
Dynamic Island 固定黑底,文字採淺色;Lock Screen 卡片配合系統外觀。`ActivityCards.swift` 共用主要內容,正式 Dynamic Island 由系統 region 排版,App 裡顯示示意容器。[Apple DynamicIsland API](https://developer.apple.com/documentation/widgetkit/dynamicisland)
diff --git a/docs/design/push-and-live-activity.md b/docs/design/push-and-live-activity.md
new file mode 100644
index 00000000..33724750
--- /dev/null
+++ b/docs/design/push-and-live-activity.md
@@ -0,0 +1,132 @@
+# Notifications, Live Activities and Dynamic Island
+
+Updated: 2026-09-27. This describes the implemented notification contract and its delivery limits. Deployment and real-device acceptance are separate from local tests.
+
+## Experience
+
+| Event | Notification | Live Activity / Dynamic Island |
+| --- | --- | --- |
+| A task is sent from this iPhone | No alert | Start one activity for this bot |
+| Working | No alert for each tool call | Bot identity and working orb |
+| Input or permission needed | Bot name, “Response needed”, request summary; “Review request” action | Needs you; keep the activity alive |
+| Completed | Bot name, “Task complete”, final reply preview; “Open conversation” action | Done, then dismiss after 60 seconds |
+| Failed | Bot name, “Task failed”, failure summary; “Open conversation” action | Error state, then dismiss after 60 seconds |
+| No fresh update for 15 minutes | No synthetic failure alert | Update delayed; never infer completion |
+
+The encrypted title is limited to 80 characters and the body to 400 characters. The body is an excerpt of the agent's final answer, not a newly generated summary. System notification previews, text truncation, Focus, sounds and delivery timing remain controlled by iOS. There is no invented completion percentage or per-tool notification stream.
+
+Notification actions open the scoped conversation. Permission approval still requires the normal in-app permission card. An account mismatch does not navigate into another account. Notifications are grouped by computer plus bot. Muted and hidden bots do not alert. The existing host-wide suppression while an iOS event connection is open remains in place; independent foreground suppression for multiple phones is not implemented.
+
+Use Settings → Notifications to request access or open the iOS notification settings, including when access is already enabled. Per-bot notification preferences remain in the bot editor. State → Live Activity controls automatic activity creation and shows system authorization. Turning it off ends this phone's activities.
+
+## Responsibilities and privacy
+
+```mermaid
+flowchart LR
+ H[Host: bot events and private summary] -->|sealed alert or status-only activity| W[relay/ APNs Worker]
+ W --> A[Apple APNs]
+ A --> N[iOS Notification Service Extension]
+ N -->|decrypt locally| B[Notification banner]
+ A --> K[ActivityKit]
+ K --> L[Lock Screen and Dynamic Island]
+```
+
+- `host/` owns event meaning, device tickets, task state and notification encryption.
+- `relay/` holds the APNs signing key, opens opaque tickets and selects the APNs environment/topic. It has no notification decryption key.
+- `cloud/` handles accounts and the encrypted connection. It is a separate service from the APNs Worker; no new Durable Object or D1 table is needed for this change.
+- The notification extension decrypts the title, optional subtitle and body using the account context's shared Keychain key. This is local work and does not require a network fetch. [Apple notification content modification](https://developer.apple.com/documentation/usernotifications/modifying-content-in-newly-delivered-notifications)
+- ActivityKit renders both Lock Screen and Dynamic Island. A separate Dynamic Island Worker or event API is unnecessary. APNs updates use a dedicated activity token, not the normal notification token. [Apple ActivityKit push updates](https://developer.apple.com/documentation/ActivityKit/starting-and-updating-live-activities-with-activitykit-push-notifications)
+
+Remote activity content contains only `status`, empty `activity`, and `startedAt`. Foreground app updates may show the current step from the encrypted connection; a remote update clears that free text. The notification service extension is not an ActivityKit decryption stage. The UI therefore does not promise private task summaries in background Live Activities. Bot identity and its deep link are set locally when starting the activity.
+
+## Registration and lifecycle
+
+1. iOS registers its APNs token with `POST /register` using `kind: alert` and its build environment.
+2. The Worker returns an AES-GCM ticket. The phone sends it with its X25519 push public key and account context to `registerDevice` on the host.
+3. Registration atomically replaces previous alert tickets for that device identity. Randomized tickets must not accumulate, retain obsolete keys or generate duplicate notifications.
+4. A foreground task submission starts an ActivityKit activity with `pushType: .token`. The phone registers each activity token using `kind: liveactivity`, then calls `registerActivity` for the bot.
+5. Activity registration replaces the previous ticket for this device and bot. The app retries registration up to three times and reattaches token observers after reconnect/relaunch. Cancellation stops retries.
+6. The host sends current state after registration, including terminal state if the task already finished. An idle bot with an unanswered main-chat user message waits for its actor to start rather than reporting immediate completion.
+7. Status transitions send updates; idle/error sends an end event preserving that status and removes the activity tickets. The group view follows its member runtime using the existing group state logic.
+8. App-local updates set a 15-minute stale date. Remote updates now do the same. A long task with no status transition may become stale; this is an honest “Update delayed”, not an assertion that its process stopped.
+
+An existing activity can receive background APNs updates. Automatically starting activities for tasks initiated elsewhere is not enabled: that requires a separate push-to-start token flow and product preferences. Home Screen widgets keep their existing WidgetKit refresh scheduling and do not become real-time feeds through this change.
+
+## Worker contract
+
+Alert kinds are `done`, `needsInput`, and `failed`. The public APNs alert always has title `Codync` and a useful fallback sentence. The encrypted payload carries the private fields. `mutable-content: 1` requests extension processing. The public routing fields are `botId`, `computerId`, and `ctx`; `thread-id` is `<computerId>:<botId>`.
+
+Live Activity requests carry:
+
+```json
+{
+ "ticket": "<opaque activity ticket>",
+ "liveActivity": {
+ "event": "update",
+ "timestamp": 1790500000,
+ "staleDate": 1790500900,
+ "contentState": {
+ "status": "needsInput",
+ "activity": "",
+ "startedAt": 812192700
+ }
+ }
+}
+```
+
+`timestamp`, `stale-date`, and `dismissal-date` use Unix seconds. `startedAt` uses Swift Date's 2001 reference epoch. The Worker preserves the host event timestamp rather than replacing it with delivery time. Older hosts that omit it use Worker receipt time.
+
+- Topic: `com.pokai.Codync.ios.push-type.liveactivity`; push type: `liveactivity`.
+- Working updates use APNs priority 5; input requests and end events use 10.
+- Updates set `stale-date`; ends set `dismissal-date` to event time plus 60 seconds. Expiration follows that deadline. Ordinary alerts expire after one hour.
+- Invalid environment, kind, activity event, state or dates return 400. Remote activity free text is rejected. Alert custom data cannot overwrite `aps`; alert payloads larger than 4096 bytes return 413.
+- Unregistered/bad device tokens return 410. Provider signing-token errors remain delivery errors and do not invalidate a device ticket.
+
+Host delivery is currently best effort with a 10-second request timeout. There is no durable delivery queue or delivery receipt from iOS; a successful APNs response does not prove display. Second-resolution timestamps also do not provide a unique run identifier. Durable retries and activity identities per task would need a follow-up protocol change; this implementation does not claim exactly-once or guaranteed ordered delivery.
+
+## Why only “Done” appeared
+
+The previous public fallback was literally `Codync / Done`. Any missing `sealed`, `ctx`, inaccessible shared key, failed authentication or extension packaging problem kept that fallback. Source inspection confirms that path; identifying which branch ran on a specific installed phone needs device logs.
+
+Registration previously accumulated random tickets, including tickets with obsolete/missing push keys. Re-registering now removes those old records for the same device. The fallback itself now says “Your task is complete. Open Codync to read the result.” Failure and input requests have distinct fallback sentences.
+
+For a phone that still shows fallback text:
+
+1. Open the updated app and connect to the updated host so token/key registration completes.
+2. Verify the installed app embeds `CodyncNotificationService.appex`, and the service principal class is the generated module's `NotificationService`.
+3. Verify signed app and extension share the same expanded `CodyncKeychainGroup` and Keychain entitlement. Source plist equality alone does not verify a signed installation.
+4. Inspect device logs for categories `Push`, `PushDecrypt`, and `NotificationService`. They distinguish missing keys, Keychain failures, failed content authentication/decoding and fallback delivery without printing keys or message contents.
+5. Test after the first unlock following a reboot. Keys intentionally use `AfterFirstUnlockThisDeviceOnly`; pre-unlock fallback is expected.
+
+## Configuration and release checks
+
+The APNs Worker uses the existing secrets `APNS_TEAM_ID`, `APNS_KEY_ID`, `APNS_SIGNING_KEY`, and `TICKET_KEY`; see the [relay deployment guide](../../relay/README.md). Keep `TICKET_KEY` stable across deployments. Rotating it invalidates every existing ticket. Tickets are bearer capabilities accepted by the Worker and must not be logged.
+
+The app bundle is `com.pokai.Codync.ios`. App and notification extension share `group.com.pokai.Codync` and the expanded shared Keychain access group. `project.yml` embeds both extension targets and enables `NSSupportsLiveActivities`; no new entitlement is required by these changes. Confirm sandbox versus production against the signed provisioning profile, especially for distribution builds.
+
+Deployment order: Worker → host → iOS. The optional encrypted subtitle remains compatible with clients that decode only title/body. New clients accept older encrypted payloads without subtitles. The new `failed` category requires the updated app for its custom action. Follow the repository's stop-old-process/relaunch rules when installing builds.
+
+### Acceptance matrix
+
+| Check | Expected result |
+| --- | --- |
+| Re-register twice with a new key | One alert ticket for that device, latest key retained |
+| Rotate an activity token | One ticket for that device and bot; other bots/devices unaffected |
+| Task succeeds in background | Decrypted bot title, status subtitle, result excerpt; activity ends |
+| Task fails in background | Failure alert and error activity; no success checkmark |
+| Permission requested | Review action opens scoped conversation; activity stays live |
+| Stop receiving state updates | Stale UI hides the old foreground step |
+| Reopen app with an active activity | Token observer resumes and registration retries on transient failure |
+| Wrong key / signed extension missing access | Readable generic fallback and a diagnostic log |
+| Provider credentials expire | Device ticket is retained for credential repair |
+| Worker receives private activity text / oversized alert | Rejected before APNs |
+
+Local tests cover payload generation, error classification, request validation, ticket replacement, Swift payload decoding and crypto vectors. A signed physical-device run with the deployed Worker is still required for extension execution, locked-device Keychain access, action navigation, Focus behavior, token rotation and background ActivityKit delivery.
+
+### Local verification — 2026-09-27
+
+- Host: `cargo fmt --check`, `cargo clippy --all-targets -- -D warnings`, and all 147 unit/integration tests passed.
+- Swift: `swift test --package-path kit` passed, 51 tests including encrypted push vectors and the optional notification subtitle.
+- Relay: `npm test` and `npm run typecheck` passed, including malformed requests and activity payload checks.
+- iOS: Debug simulator build passed with both extensions embedded. The built notification extension has the expected service entry point. Signing and device Keychain access were not verified by this unsigned build.
+- Design document relative links and `git diff --check` passed. No Worker deployment or phone installation was performed.
diff --git a/docs/reference/remote-relay.md b/docs/reference/remote-relay.md
index 278fd2d3..02eae8b3 100644
--- a/docs/reference/remote-relay.md
+++ b/docs/reference/remote-relay.md
@@ -323,10 +323,10 @@ epk, eprv = 新的 X25519 金鑰對(每則通知、每個 ticket 各自新產
ss = X25519(eprv, pushKey) ← 全零拒絕
prk = HKDF-Extract(salt = "codync/push/v1" ‖ cidRaw ‖ pushKey ‖ epk, ikm = ss)
key = HKDF-Expand(prk, "codync/push-key/v1", 32)
-ct = ChaCha20-Poly1305(key, nonce = 12 × 0x00, plaintext = {"title","body"} JSON, aad = cidRaw)
+ct = ChaCha20-Poly1305(key, nonce = 12 × 0x00, plaintext = {"title","subtitle"?,"body"} JSON, aad = cidRaw)
sealed = b64url(epk ‖ ct)
```
-送給 `relay/` 的 body:`alert = {"title":"Codync","body":"Needs you"|"Done"}`(通用文字,依 kind)、`mutableContent: true`、`threadId = botId`、`category = kind`、`data = {"botId","computerId","ctx":<SharedStore.Context.id>,"sealed"}`。Notification Service Extension 依 `ctx` 從共用 Keychain 取 push key、解開後替換 title/body;解不開就保留通用文字。Live Activity 的 `contentState` 只含 `status` 與 `startedAt`(`activity` 固定為空字串),不含任何自由文字。向量 `push`。
+送給 `relay/` 的 body:`alert` 為 Codync 與依 kind 選擇的通用說明句、`mutableContent: true`、`threadId = computerId:botId`、`category = done|needsInput|failed`、`data = {"botId","computerId","ctx":<SharedStore.Context.id>,"sealed"}`。Notification Service Extension 依 `ctx` 從共用 Keychain 取 push key、解開後替換 title/subtitle/body;解不開就保留通用文字。Live Activity 的 `contentState` 只含 `status` 與 `startedAt`(`activity` 固定為空字串),不含任何自由文字。向量 `push` 保留沒有 subtitle 的相容格式。通知呈現、票券更新、ActivityKit 時間與部署驗收見 [通知與 Live Activity 設計](../design/push-and-live-activity.md)。
---
diff --git a/host/src/agent/bot.rs b/host/src/agent/bot.rs
index e7b21030..be1f116b 100644
--- a/host/src/agent/bot.rs
+++ b/host/src/agent/bot.rs
@@ -1105,9 +1105,14 @@ impl Actor {
if !self.stop_requested && !delegated && !grouped {
let body =
final_text.unwrap_or_else(|| if failed { "The agent failed.".into() } else { "Finished.".into() });
- push::notify(&self.hub, &self.cfg, &self.cfg.name, &body, AlertKind::Done);
+ push::notify(
+ &self.hub,
+ &self.cfg,
+ &self.cfg.name,
+ &body,
+ if failed { AlertKind::Failed } else { AlertKind::Done },
+ );
}
- push::live_activity_end(&self.hub, &self.cfg.id);
}
// MARK: agent → client
diff --git a/host/src/api/mod.rs b/host/src/api/mod.rs
index 8717091e..0d3f65b8 100644
--- a/host/src/api/mod.rs
+++ b/host/src/api/mod.rs
@@ -8,7 +8,7 @@ use crate::LockExt;
use crate::agent::backends;
use crate::agent::bot::Cmd;
use crate::api::devices::{Caller, Forbidden};
-use crate::hub::Hub;
+use crate::hub::{BotStatus, Hub};
use crate::remote::crypto;
use crate::store::{BotConfig, DeviceSource, EntryKind, Lane, ReadScope};
use crate::{market, usage};
@@ -411,7 +411,32 @@ pub async fn dispatch(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value) -
json!({})
}
"registerActivity" => {
- hub.store.add_activity_ticket(str_arg(&b, "ticket")?, str_arg(&b, "botId")?, caller.device_key())?;
+ let bot_id = str_arg(&b, "botId")?;
+ let row = hub.store.bot(bot_id)?.filter(|row| !row.deleted).ok_or_else(|| anyhow!("unknown bot"))?;
+ hub.store.add_activity_ticket(str_arg(&b, "ticket")?, bot_id, caller.device_key())?;
+ // Registration can finish after the task does. Send the current state immediately.
+ let state = hub.bot_json(&row);
+ let status = match state["status"].as_str() {
+ Some("working") => BotStatus::Working,
+ Some("needsInput") => BotStatus::NeedsInput,
+ Some("error") => BotStatus::Error,
+ _ => BotStatus::Idle,
+ };
+ // A send is acknowledged before its actor necessarily starts. An unanswered user
+ // message must not end the activity as "done" during that window.
+ let pending = status == BotStatus::Idle
+ && hub.store.last_message(bot_id).is_some_and(|message| message.author.is_none());
+ if !pending {
+ crate::remote::push::live_activity_update(
+ hub,
+ bot_id,
+ &crate::hub::Runtime {
+ status,
+ started_at: state["startedAt"].as_i64(),
+ ..crate::hub::Runtime::default()
+ },
+ );
+ }
json!({})
}
"refreshBackends" => {
diff --git a/host/src/remote/channel.rs b/host/src/remote/channel.rs
index c9c78c44..dfcbfd0e 100644
--- a/host/src/remote/channel.rs
+++ b/host/src/remote/channel.rs
@@ -800,13 +800,16 @@ mod tests {
#[tokio::test]
async fn revoking_closes_the_channel_and_its_subscription() {
let hub = temp_hub();
+ let bot = serde_json::from_value(json!({"id": "b1", "name": "Test", "createdAt": 0})).unwrap();
+ hub.store.save_bot(&bot).unwrap();
+ hub.set_runtime("b1", |runtime| runtime.status = crate::hub::BotStatus::Working);
let key = paired_phone(&hub).await;
let dk = crypto::b64(key.verifying_key().as_bytes());
let mut p = Phone::direct(&hub, key);
p.hello(&hub, false).await;
assert!(p.call(1, "registerDevice", json!({"ticket": "t1", "name": "iPhone"})).await["ok"].is_object());
assert!(p.call(2, "registerActivity", json!({"ticket": "a1", "botId": "b1"})).await["ok"].is_object());
- p.send(json!({"id": 3, "sub": "events", "b": {"since": 0, "client": "ios"}})).await;
+ p.send(json!({"id": 3, "sub": "events", "b": {"since": hub.store.current_rev(), "client": "ios"}})).await;
let hello = p.recv().await.unwrap();
assert_eq!((hello["id"].as_u64(), hello["ev"]["type"].as_str()), (Some(3), Some("hello")));
assert!(hub.ios_connected());
diff --git a/host/src/remote/push.rs b/host/src/remote/push.rs
index 3e70ab9d..24ef7424 100644
--- a/host/src/remote/push.rs
+++ b/host/src/remote/push.rs
@@ -1,7 +1,7 @@
//! Push via the Codync relay (it holds the APNs key; the host only holds opaque
//! per-device tickets the relay issued to the phone).
//!
-//! Like Grok Bot there are only two alert kinds: "needs you" and "done", and
+//! Alerts cover completion, input requests, and failures;
//! none are sent while the phone app is connected (it's in the foreground).
use crate::LockExt;
@@ -15,12 +15,13 @@ use std::sync::{LazyLock, Mutex};
use std::time::{Duration, Instant};
use x25519_dalek::StaticSecret;
-/// The two alert kinds (wire values double as the APNs category).
+/// Alert kinds (wire values double as the APNs category).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum AlertKind {
Done,
NeedsInput,
+ Failed,
}
/// (bot id, kind) → last alert.
@@ -60,7 +61,16 @@ fn post(url: String, body: Value) {
});
}
+fn purge_dead_tickets(hub: &Hub) {
+ for t in std::mem::take(&mut *GONE.locked()) {
+ if let Err(error) = hub.store.remove_push_ticket(&t) {
+ tracing::warn!(%error, "couldn't forget a dead push ticket");
+ }
+ }
+}
+
pub fn notify(hub: &Hub, bot: &BotConfig, title: &str, body: &str, kind: AlertKind) {
+ purge_dead_tickets(hub);
if bot.notify == Some(false) || bot.hidden || hub.ios_connected() {
return;
}
@@ -68,17 +78,20 @@ pub fn notify(hub: &Hub, bot: &BotConfig, title: &str, body: &str, kind: AlertKi
return;
}
let Some(relay) = relay_url(hub) else { return };
- for t in std::mem::take(&mut *GONE.locked()) {
- if let Err(error) = hub.store.remove_push_ticket(&t) {
- tracing::warn!(%error, "couldn't forget a dead push ticket");
- }
- }
// The relay and APNs only see a generic line; the real one is sealed to each device (§6.7).
let generic = match kind {
- AlertKind::NeedsInput => "Needs you",
- AlertKind::Done => "Done",
+ AlertKind::NeedsInput => "A bot needs your response. Open Codync to review.",
+ AlertKind::Done => "Your task is complete. Open Codync to read the result.",
+ AlertKind::Failed => "A task could not finish. Open Codync to review the issue.",
};
- let secret = json!({"title": title, "body": crate::agent::acp::truncate(body, 140)}).to_string();
+ let subtitle = match kind {
+ AlertKind::Done => "Task complete",
+ AlertKind::NeedsInput => "Response needed",
+ AlertKind::Failed => "Task failed",
+ };
+ let secret = json!({"title": crate::agent::acp::truncate(title, 80), "subtitle": subtitle,
+ "body": crate::agent::acp::truncate(body, 400)})
+ .to_string();
let computer_id = hub.identity.computer_id();
for t in hub.store.push_tickets() {
let mut data = json!({"botId": bot.id, "computerId": computer_id, "ctx": t.ctx});
@@ -95,7 +108,7 @@ pub fn notify(hub: &Hub, bot: &BotConfig, title: &str, body: &str, kind: AlertKi
"ticket": t.ticket,
"alert": {"title": "Codync", "body": generic},
"mutableContent": true,
- "threadId": bot.id,
+ "threadId": format!("{computer_id}:{}", bot.id),
"category": kind,
"data": data,
}),
@@ -103,33 +116,56 @@ pub fn notify(hub: &Hub, bot: &BotConfig, title: &str, body: &str, kind: AlertKi
}
}
-/// Live Activity status updates for bots a phone is watching. Only the status enum and
-/// start time travel: no free text leaves the computer this way.
+/// Live Activities carry only status and dates. Task text stays in the encrypted channel.
pub fn live_activity_update(hub: &Hub, bot_id: &str, rt: &Runtime) {
- let tickets = hub.store.activity_tickets(bot_id);
- if tickets.is_empty() {
- return;
- }
+ purge_dead_tickets(hub);
let Some(relay) = relay_url(hub) else { return };
- #[allow(clippy::cast_precision_loss)] // epoch milliseconds fit an f64 mantissa until year 287,396
- let started_at = rt.started_at.map(|ms| ms as f64 / 1000.0 - SWIFT_REFERENCE_EPOCH);
- let state = json!({"status": rt.status, "activity": "", "startedAt": started_at});
+ let terminal = matches!(rt.status, BotStatus::Idle | BotStatus::Error);
+ let tickets = if terminal { hub.store.take_activity_tickets(bot_id) } else { hub.store.activity_tickets(bot_id) };
+ let activity = activity_payload(rt);
for ticket in tickets {
- post(
- format!("{relay}/push"),
- json!({"ticket": ticket, "liveActivity": {"event": "update", "contentState": state}}),
- );
+ post(format!("{relay}/push"), json!({"ticket": ticket, "liveActivity": activity}));
}
}
-pub fn live_activity_end(hub: &Hub, bot_id: &str) {
- let tickets = hub.store.take_activity_tickets(bot_id);
- let Some(relay) = relay_url(hub) else { return };
- let state = json!({"status": BotStatus::Idle, "activity": "", "startedAt": null});
- for ticket in tickets {
- post(
- format!("{relay}/push"),
- json!({"ticket": ticket, "liveActivity": {"event": "end", "contentState": state}}),
- );
+fn activity_payload(rt: &Runtime) -> Value {
+ #[allow(clippy::cast_precision_loss)]
+ let started_at = rt.started_at.map(|ms| ms as f64 / 1000.0 - SWIFT_REFERENCE_EPOCH);
+ let terminal = matches!(rt.status, BotStatus::Idle | BotStatus::Error);
+ let timestamp = crate::store::now_ms() / 1000;
+ json!({
+ "event": if terminal { "end" } else { "update" },
+ "timestamp": timestamp,
+ "staleDate": timestamp + 15 * 60,
+ "contentState": {"status": rt.status, "activity": "", "startedAt": started_at},
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn activity_failure_ends_with_error_and_never_includes_task_text() {
+ let payload = activity_payload(&Runtime {
+ status: BotStatus::Error,
+ activity: "secret file".into(),
+ ..Runtime::default()
+ });
+ assert_eq!(payload["event"], "end");
+ assert_eq!(payload["contentState"]["status"], "error");
+ assert_eq!(payload["contentState"]["activity"], "");
+ }
+
+ #[test]
+ fn waiting_for_input_stays_live_with_a_freshness_deadline() {
+ let payload = activity_payload(&Runtime {
+ status: BotStatus::NeedsInput,
+ started_at: Some(978_307_201_000),
+ ..Runtime::default()
+ });
+ assert_eq!(payload["event"], "update");
+ assert_eq!(payload["contentState"]["startedAt"], 1.0);
+ assert_eq!(payload["staleDate"].as_i64().unwrap() - payload["timestamp"].as_i64().unwrap(), 900);
}
}
diff --git a/host/src/store.rs b/host/src/store.rs
index 274364c2..678cb99d 100644
--- a/host/src/store.rs
+++ b/host/src/store.rs
@@ -832,17 +832,23 @@ impl Store {
ctx: Option<&str>,
name: &str,
) -> Result<()> {
- let c = self.db.locked();
- c.execute(
+ let mut c = self.db.locked();
+ let tx = c.transaction()?;
+ // Relay tickets use a random nonce; registering again must replace this device's old ticket.
+ tx.execute("DELETE FROM push_tickets WHERE device_key = ?1", [device_key])?;
+ tx.execute(
"INSERT INTO push_tickets(ticket, device_key, push_key, ctx, name, created_at) VALUES(?1, ?2, ?3, ?4, ?5, ?6)
ON CONFLICT(ticket) DO UPDATE SET device_key = ?2, push_key = ?3, ctx = ?4, name = ?5",
params![ticket, device_key, push_key, ctx, name, now_ms()],
)?;
+ tx.commit()?;
Ok(())
}
pub fn remove_push_ticket(&self, ticket: &str) -> Result<()> {
- self.db.locked().execute("DELETE FROM push_tickets WHERE ticket = ?1", [ticket])?;
+ let c = self.db.locked();
+ c.execute("DELETE FROM push_tickets WHERE ticket = ?1", [ticket])?;
+ c.execute("DELETE FROM activity_tickets WHERE ticket = ?1", [ticket])?;
Ok(())
}
@@ -856,12 +862,15 @@ impl Store {
}
pub fn add_activity_ticket(&self, ticket: &str, bot_id: &str, device_key: &str) -> Result<()> {
- let c = self.db.locked();
- c.execute(
+ let mut c = self.db.locked();
+ let tx = c.transaction()?;
+ tx.execute("DELETE FROM activity_tickets WHERE device_key = ?1 AND bot_id = ?2", params![device_key, bot_id])?;
+ tx.execute(
"INSERT INTO activity_tickets(ticket, bot_id, device_key, created_at) VALUES(?1, ?2, ?3, ?4)
ON CONFLICT(ticket) DO UPDATE SET bot_id = ?2, device_key = ?3",
params![ticket, bot_id, device_key, now_ms()],
)?;
+ tx.commit()?;
Ok(())
}
@@ -980,6 +989,25 @@ mod tests {
assert!(s.activity_tickets("b1").is_empty());
}
+ #[test]
+ fn registration_replaces_old_keys_and_activity_tokens_for_one_device_only() {
+ let s = temp_store();
+ s.add_push_ticket("old", "phone", None, Some("local"), "Phone").unwrap();
+ s.add_push_ticket("other", "other-phone", Some("other-key"), Some("local"), "Other").unwrap();
+ s.add_push_ticket("new", "phone", Some("new-key"), Some("local"), "Phone").unwrap();
+ let tickets = s.push_tickets();
+ assert_eq!(tickets.len(), 2);
+ assert!(!tickets.iter().any(|t| t.ticket == "old"));
+ assert_eq!(tickets.iter().find(|t| t.ticket == "new").unwrap().push_key.as_deref(), Some("new-key"));
+ s.add_activity_ticket("old-activity", "bot", "phone").unwrap();
+ s.add_activity_ticket("new-activity", "bot", "phone").unwrap();
+ s.add_activity_ticket("other-bot", "bot2", "phone").unwrap();
+ assert_eq!(s.activity_tickets("bot"), ["new-activity"]);
+ s.remove_push_ticket("new-activity").unwrap();
+ assert!(s.activity_tickets("bot").is_empty());
+ assert_eq!(s.activity_tickets("bot2"), ["other-bot"]);
+ }
+
#[test]
fn migrations_replace_the_old_ticket_table_and_add_threads() {
let dir = std::env::temp_dir().join(format!("codync-test-{}", uuid::Uuid::new_v4()));
diff --git a/kit/Sources/CodyncKit/Client/DeviceIdentity.swift b/kit/Sources/CodyncKit/Client/DeviceIdentity.swift
index 55922af6..fc9b2a9f 100644
--- a/kit/Sources/CodyncKit/Client/DeviceIdentity.swift
+++ b/kit/Sources/CodyncKit/Client/DeviceIdentity.swift
@@ -1,6 +1,7 @@
import CryptoKit
import Foundation
import Security
+import os
/// This app install's keys for one account context (§3.2): an Ed25519 device key that hosts
/// authorize, and an X25519 push key that opens notification contents. Private keys stay in the Keychain.
@@ -56,17 +57,27 @@ public struct DeviceIdentity: Sendable {
/// For the Notification Service Extension: opens §6.7's `sealed` with the push key of
/// `contextID`. Never creates keys; nil when anything doesn't check out.
- public static func openPush(sealed: String, computerId: ComputerID, contextID: String) -> (title: String, body: String)? {
- guard let raw = try? Keychain.read(service: pushService, account: contextID),
- let key = try? Curve25519.KeyAgreement.PrivateKey(rawRepresentation: raw) else { return nil }
- return openPush(sealed: sealed, computerId: computerId, key: key)
+ public static func openPush(sealed: String, computerId: ComputerID, contextID: String) -> PushAlert? {
+ let log = Logger(subsystem: "com.pokai.Codync.ios", category: "PushDecrypt")
+ do {
+ guard let raw = try Keychain.read(service: pushService, account: contextID) else {
+ log.error("Notification push key missing; re-register this device")
+ return nil
+ }
+ let key = try Curve25519.KeyAgreement.PrivateKey(rawRepresentation: raw)
+ let alert = openPush(sealed: sealed, computerId: computerId, key: key)
+ if alert == nil { log.error("Notification authentication or content decoding failed") }
+ return alert
+ } catch {
+ log.error("Notification key unavailable: \(error.localizedDescription)")
+ return nil
+ }
}
- static func openPush(sealed: String, computerId: ComputerID, key: Curve25519.KeyAgreement.PrivateKey) -> (title: String, body: String)? {
- struct Alert: Decodable { var title: String; var body: String }
+ static func openPush(sealed: String, computerId: ComputerID, key: Curve25519.KeyAgreement.PrivateKey) -> PushAlert? {
guard let plain = try? RelayCrypto.openPush(sealed: sealed, computerId: computerId, pushPrivate: key),
- let alert = try? JSONDecoder().decode(Alert.self, from: plain) else { return nil }
- return (alert.title, alert.body)
+ let alert = try? JSONDecoder().decode(PushAlert.self, from: plain) else { return nil }
+ return alert
}
}
diff --git a/kit/Sources/CodyncKit/Models/BotActivityPresentation.swift b/kit/Sources/CodyncKit/Models/BotActivityPresentation.swift
index 9a11e450..e8a11048 100644
--- a/kit/Sources/CodyncKit/Models/BotActivityPresentation.swift
+++ b/kit/Sources/CodyncKit/Models/BotActivityPresentation.swift
@@ -28,7 +28,7 @@ public struct BotActivityPresentation: Hashable, Sendable {
case .working: "Working"
case .needsInput: "Needs you"
case .completed: "Done"
- case .failed: "Stopped"
+ case .failed: "Failed"
case .stale: "Update delayed"
case .waiting: "Waiting for update"
}
diff --git a/kit/Sources/CodyncKit/Models/PushAlert.swift b/kit/Sources/CodyncKit/Models/PushAlert.swift
new file mode 100644
index 00000000..8c821cf4
--- /dev/null
+++ b/kit/Sources/CodyncKit/Models/PushAlert.swift
@@ -0,0 +1,8 @@
+import Foundation
+
+/// Private notification content. Only the host and the device can read these fields.
+public struct PushAlert: Decodable, Sendable {
+ public let title: String
+ public let subtitle: String?
+ public let body: String
+}
diff --git a/kit/Tests/CodyncKitTests/ActivityPresentationTests.swift b/kit/Tests/CodyncKitTests/ActivityPresentationTests.swift
index 278f3e26..9b4a339e 100644
--- a/kit/Tests/CodyncKitTests/ActivityPresentationTests.swift
+++ b/kit/Tests/CodyncKitTests/ActivityPresentationTests.swift
@@ -5,6 +5,7 @@ import Testing
@Test func activityErrorAndUnknownStatusNeverLookCompleted() {
let error = BotActivityPresentation(status: "error", activity: "", startedAt: .now)
#expect(error.phase == .failed)
+ #expect(error.title == "Failed")
#expect(error.symbol != "checkmark")
#expect(!error.showsTimer)
let unknown = BotActivityPresentation(status: "new-host-status", activity: "", startedAt: .now)
diff --git a/kit/Tests/CodyncKitTests/PushAlertTests.swift b/kit/Tests/CodyncKitTests/PushAlertTests.swift
new file mode 100644
index 00000000..6f779f20
--- /dev/null
+++ b/kit/Tests/CodyncKitTests/PushAlertTests.swift
@@ -0,0 +1,11 @@
+import Foundation
+import Testing
+@testable import CodyncKit
+
+@Test func pushContentAcceptsAnOptionalStatusSubtitle() throws {
+ let current = try JSONDecoder().decode(PushAlert.self, from: Data(#"{"title":"Reviewer","subtitle":"Task complete","body":"All tests passed."}"#.utf8))
+ #expect(current.subtitle == "Task complete")
+ #expect(current.body == "All tests passed.")
+ let olderHost = try JSONDecoder().decode(PushAlert.self, from: Data(#"{"title":"Reviewer","body":"All tests passed."}"#.utf8))
+ #expect(olderHost.subtitle == nil)
+}
diff --git a/relay/README.md b/relay/README.md
index fad65cde..55b94e82 100644
--- a/relay/README.md
+++ b/relay/README.md
@@ -2,8 +2,8 @@
Cloudflare Worker that holds the APNs key and forwards pushes for codync-host.
The phone exchanges its APNs token for an AES-GCM **ticket** (`POST /register`);
-hosts only ever see tickets (`POST /push`). A ticket is useless without the
-worker's `TICKET_KEY`, and it only reaches the one device it was issued for.
+hosts only ever see tickets (`POST /push`). A ticket is a bearer capability: anyone holding it can ask this Worker to push
+to its device. Only the Worker can decrypt the raw APNs token. Do not log tickets.
## Deploy
@@ -26,3 +26,11 @@ Rotating `TICKET_KEY` invalidates every ticket; phones re-register on launch.
npm test # ticket seal/open round trip, `mutableContent` → `mutable-content: 1`
npm run typecheck
```
+
+## Notifications and Live Activities
+
+See the [notification design](../docs/design/push-and-live-activity.md) for event
+copy, encrypted content, ActivityKit payloads, configuration and device acceptance.
+The Worker handles alerts and updates/ends for activities started on the phone.
+Dynamic Island shares the ActivityKit update stream. This Worker does not start
+activities remotely or refresh Home Screen widgets.
diff --git a/relay/src/index.ts b/relay/src/index.ts
index 03d062b6..8aacae88 100644
--- a/relay/src/index.ts
+++ b/relay/src/index.ts
@@ -93,8 +93,10 @@ const json = (body: unknown, status = 200) => Response.json(body, { status });
async function register(req: Request, env: Env): Promise<Response> {
const body = (await req.json().catch(() => null)) as { token?: string; env?: string; kind?: string } | null;
- if (!body?.token || !/^[0-9a-fA-F]{32,200}$/.test(body.token)) return json({ error: "invalid token" }, 400);
- const e: ApnsEnv = body.env === "production" ? "production" : "sandbox";
+ if (typeof body?.token !== "string" || !/^(?:[0-9a-fA-F]{2}){16,100}$/.test(body.token)) return json({ error: "invalid token" }, 400);
+ if (body.env !== "production" && body.env !== "sandbox") return json({ error: "invalid environment" }, 400);
+ if (body.kind !== "alert" && body.kind !== "liveactivity") return json({ error: "invalid kind" }, 400);
+ const e: ApnsEnv = body.env;
const k: Kind = body.kind === "liveactivity" ? "liveactivity" : "alert";
return json({ ticket: await sealTicket(env, { t: body.token, e, k }) });
}
@@ -106,7 +108,7 @@ export interface PushBody {
category?: string;
data?: Record<string, unknown>;
mutableContent?: boolean;
- liveActivity?: { event?: "update" | "end"; contentState?: Record<string, unknown> };
+ liveActivity?: { event?: "update" | "end"; timestamp?: number; staleDate?: number; contentState?: Record<string, unknown> };
}
/** The `aps` dictionary for an alert push. */
@@ -121,6 +123,31 @@ export function alertAps(body: PushBody & { alert: NonNullable<PushBody["alert"]
return aps;
}
+/** ActivityKit dates use Unix seconds; startedAt inside content-state uses Swift's Date epoch. */
+export function liveActivityAps(la: NonNullable<PushBody["liveActivity"]>, now = Math.floor(Date.now() / 1000)): Record<string, unknown> {
+ const state = la.contentState;
+ if (!state || typeof state.status !== "string" || !["working", "needsInput", "idle", "error"].includes(state.status) ||
+ state.activity !== "" || !(state.startedAt == null || (typeof state.startedAt === "number" && Number.isFinite(state.startedAt)))) {
+ throw new Error("invalid contentState");
+ }
+ if (la.event !== "update" && la.event !== "end") throw new Error("invalid activity event");
+ const timestamp = la.timestamp ?? now;
+ const staleDate = la.staleDate ?? timestamp + 900;
+ if (!Number.isSafeInteger(timestamp) || timestamp < 0 || timestamp > now + 60 ||
+ !Number.isSafeInteger(staleDate) || staleDate < timestamp) throw new Error("invalid activity dates");
+ const aps: Record<string, unknown> = {
+ timestamp, event: la.event,
+ "content-state": { status: state.status, activity: "", startedAt: state.startedAt ?? null },
+ };
+ if (la.event === "end") aps["dismissal-date"] = timestamp + 60;
+ else aps["stale-date"] = staleDate;
+ return aps;
+}
+
+export function tokenIsGone(error: { reason?: string; statusCode?: number }): boolean {
+ return error.statusCode === 410 || ["Unregistered", "BadDeviceToken"].includes(error.reason ?? "");
+}
+
async function push(req: Request, env: Env): Promise<Response> {
const body = (await req.json().catch(() => null)) as PushBody | null;
const t = body?.ticket ? await openTicket(env, body.ticket) : null;
@@ -128,23 +155,35 @@ async function push(req: Request, env: Env): Promise<Response> {
// ponytail: no per-ticket rate limit; add a Durable Object counter if tickets get abused.
try {
if (t.k === "alert") {
- if (!body.alert) return json({ error: "alert required" }, 400);
- await client(env, t.e, "alert").send(
- new Notification(t.t, {
+ if (!body.alert || typeof body.alert !== "object" ||
+ (body.alert.title !== undefined && typeof body.alert.title !== "string") ||
+ (body.alert.body !== undefined && typeof body.alert.body !== "string") ||
+ (body.data !== undefined && (!body.data || typeof body.data !== "object" || Array.isArray(body.data) || "aps" in body.data))) {
+ return json({ error: "invalid alert" }, 400);
+ }
+ const notification = new Notification(t.t, {
type: PushType.alert,
priority: Priority.immediate,
aps: alertAps({ ...body, alert: body.alert }),
data: body.data ?? {},
- }),
- );
+ expiration: Math.floor(Date.now() / 1000) + 3600,
+ });
+ if (new TextEncoder().encode(JSON.stringify(notification.buildApnsOptions())).length > 4096) {
+ return json({ error: "payload too large" }, 413);
+ }
+ await client(env, t.e, "alert").send(notification);
} else {
const la = body.liveActivity;
if (!la) return json({ error: "liveActivity required" }, 400);
- const now = Math.floor(Date.now() / 1000);
- const aps: Record<string, unknown> = { timestamp: now, event: la.event ?? "update", "content-state": la.contentState ?? {} };
- if (la.event === "end") aps["dismissal-date"] = now + 60;
+ let aps: Record<string, unknown>;
+ try { aps = liveActivityAps(la); }
+ catch { return json({ error: "invalid liveActivity" }, 400); }
await client(env, t.e, "liveactivity").send(
- new Notification(t.t, { type: PushType.liveactivity, priority: Priority.immediate, aps }),
+ new Notification(t.t, {
+ type: PushType.liveactivity,
+ priority: la.event === "end" || la.contentState?.status === "needsInput" ? Priority.immediate : Priority.throttled,
+ expiration: Number(aps["stale-date"] ?? aps["dismissal-date"]), aps,
+ }),
);
}
return json({ ok: true });
@@ -153,7 +192,7 @@ async function push(req: Request, env: Env): Promise<Response> {
const e = err as { reason?: string; statusCode?: number; message?: string };
const reason = e.reason ?? e.message ?? String(err);
// Dead device token: tell the host to drop the ticket.
- const gone = e.statusCode === 410 || /Unregistered|BadDeviceToken|ExpiredToken/.test(reason);
+ const gone = tokenIsGone(e);
return json({ error: reason, gone }, gone ? 410 : 502);
}
}
diff --git a/relay/test/push.test.ts b/relay/test/push.test.ts
index f67e4df3..32b398b3 100644
--- a/relay/test/push.test.ts
+++ b/relay/test/push.test.ts
@@ -1,6 +1,6 @@
// Alert aps: `mutableContent` passes through as `mutable-content: 1`, and only when asked.
import assert from "node:assert/strict";
-import { alertAps } from "../src/index.ts";
+import worker, { alertAps, liveActivityAps, tokenIsGone, sealTicket } from "../src/index.ts";
const base = { alert: { title: "Codync", body: "Needs you" }, threadId: "b1", category: "needsInput" };
assert.equal(alertAps({ ...base, mutableContent: true })["mutable-content"], 1);
@@ -8,3 +8,34 @@ assert.equal("mutable-content" in alertAps(base), false);
assert.equal("mutable-content" in alertAps({ ...base, mutableContent: false }), false);
assert.deepEqual(alertAps(base).alert, { title: "Codync", body: "Needs you" });
console.log("push tests ok");
+
+const state = { status: "working", activity: "", startedAt: 1 };
+const update = liveActivityAps({ event: "update", timestamp: 100, contentState: state }, 100);
+assert.equal(update.timestamp, 100);
+assert.equal(update["stale-date"], 1000);
+assert.equal("dismissal-date" in update, false);
+const ended = liveActivityAps({ event: "end", timestamp: 100, contentState: { ...state, status: "error" } }, 150);
+assert.equal(ended["dismissal-date"], 160);
+assert.equal((ended["content-state"] as typeof state).status, "error");
+assert.equal("stale-date" in ended, false);
+assert.throws(() => liveActivityAps({ event: "update", contentState: { ...state, activity: "private task text" } }));
+assert.throws(() => liveActivityAps({ event: "update", timestamp: 200, contentState: state }, 100));
+assert.throws(() => liveActivityAps({ event: "update", contentState: { ...state, status: "unknown" } }));
+assert.throws(() => liveActivityAps({ event: "update", contentState: { ...state, status: ["working"] } }));
+assert.equal(tokenIsGone({ reason: "ExpiredProviderToken", statusCode: 403 }), false);
+assert.equal(tokenIsGone({ reason: "Unregistered", statusCode: 410 }), true);
+assert.equal(tokenIsGone({ reason: "BadDeviceToken", statusCode: 400 }), true);
+console.log("Live Activity payload tests ok");
+
+const env = { TICKET_KEY: btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32)))) } as any;
+const ticket = await sealTicket(env, { t: "ab".repeat(32), e: "sandbox", k: "alert" });
+async function request(path: string, body: unknown) {
+ return worker.fetch(new Request(`https://relay.test${path}`, { method: "POST", body: JSON.stringify(body) }), env);
+}
+assert.equal((await request("/register", { token: "ab".repeat(32), env: "typo", kind: "alert" })).status, 400);
+assert.equal((await request("/push", { ticket, alert: { title: 123 } })).status, 400);
+assert.equal((await request("/push", { ticket, alert: { body: "fallback" }, data: { aps: {} } })).status, 400);
+assert.equal((await request("/push", { ticket, alert: { body: "fallback" }, data: { sealed: "x".repeat(4096) } })).status, 413);
+const activityTicket = await sealTicket(env, { t: "ab".repeat(32), e: "sandbox", k: "liveactivity" });
+assert.equal((await request("/push", { ticket: activityTicket, liveActivity: { event: "start", contentState: state } })).status, 400);
+console.log("push request validation tests ok");