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(relay): deduplicate pushes for the same phone

leepokai3961134e6122
diff --git a/apps/ios/App/CodyncApp.swift b/apps/ios/App/CodyncApp.swift
index c98975ee..fd8b598a 100644
--- a/apps/ios/App/CodyncApp.swift
+++ b/apps/ios/App/CodyncApp.swift
@@ -254,6 +254,9 @@ final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCent
UNNotificationCategory(identifier: "needsInput", actions: [review], intentIdentifiers: []),
UNNotificationCategory(identifier: "failed", actions: [open], intentIdentifiers: []),
])
+ #if DEBUG
+ PushRegistrar.shared.verifyDeliveryIfRequested()
+ #endif
return true
}
diff --git a/apps/ios/App/Push.swift b/apps/ios/App/Push.swift
index 8b06f38a..cb42718d 100644
--- a/apps/ios/App/Push.swift
+++ b/apps/ios/App/Push.swift
@@ -46,6 +46,41 @@ final class PushRegistrar {
private struct WeakStore { weak var store: BotStore? }
+ #if DEBUG
+ /// Device acceptance checks can inspect only the explicitly selected test bot's notifications.
+ /// No keys, tickets, account identifiers, or unrelated notification content are logged.
+ func verifyDeliveryIfRequested() {
+ guard let botId = ProcessInfo.processInfo.environment["CODYNC_PUSH_VERIFY_BOT"] else { return }
+ let activities = Activity<BotActivityAttributes>.activities.filter { $0.attributes.botId == botId }.map {
+ ["status": $0.content.state.status, "state": String(describing: $0.activityState)]
+ }
+ Task {
+ let center = UNUserNotificationCenter.current()
+ let settings = await center.notificationSettings()
+ let delivered = await center.deliveredNotifications().filter {
+ $0.request.content.userInfo["botId"] as? String == botId
+ }
+ let notifications = delivered.map {
+ ["title": $0.request.content.title, "subtitle": $0.request.content.subtitle,
+ "body": $0.request.content.body, "category": $0.request.content.categoryIdentifier]
+ }
+ if ProcessInfo.processInfo.environment["CODYNC_PUSH_CLEAR_TEST_NOTIFICATIONS"] == "1" {
+ center.removeDeliveredNotifications(withIdentifiers: delivered.map { $0.request.identifier })
+ }
+ let result: [String: Any] = [
+ "notifications": notifications, "activities": activities,
+ "authorization": settings.authorizationStatus.rawValue,
+ "alerts": settings.alertSetting.rawValue,
+ "notificationCenter": settings.notificationCenterSetting.rawValue,
+ ]
+ if let data = try? JSONSerialization.data(withJSONObject: result, options: [.sortedKeys]),
+ let text = String(data: data, encoding: .utf8) {
+ print("CODYNC_PUSH_VERIFICATION \(text)")
+ }
+ }
+ }
+ #endif
+
func deactivate() {
registrations.values.forEach { $0.cancel() }
registrations = [:]
diff --git a/docs/design/push-and-live-activity.md b/docs/design/push-and-live-activity.md
index 1118a5d5..d135d630 100644
--- a/docs/design/push-and-live-activity.md
+++ b/docs/design/push-and-live-activity.md
@@ -54,7 +54,11 @@ An existing activity can receive background APNs updates. Automatically starting
## 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>`.
+Alert kinds are `done`, `needsInput`, and `failed`.
+
+Hosts submit an event's alert requests in registration order to `POST /push-batch` as `{ "notifications": [<push request>, ...] }` (1–256 entries). The Worker decrypts the tickets and sends only the last request for each physical APNs destination, environment and token kind. It returns indexed statuses; superseded tickets and HTTP 410 results are forgotten by the host on its next push operation. Superseded identities also lose their older ticket rows so they cannot reappear on the next event. This requires no new database, no plaintext notification content, and no change to the ticket encryption scheme. Live Activity updates continue using `/push` because each activity has its own token.
+
+ 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:
@@ -86,7 +90,7 @@ Host delivery is currently best effort with a 10-second request timeout. There i
## 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.
+The previous public fallback was literally `Codync / Done`. Any missing `sealed`, `ctx`, inaccessible shared key, failed authentication or extension packaging problem kept that fallback. Device verification reproduced a more specific cause: five authorized device identities pointed to this phone. One current identity decrypted the completion normally; four obsolete identities produced generic fallbacks for the same event. The batched Worker path now selects the latest registration for the physical token across those identities.
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.
@@ -121,11 +125,11 @@ Deployment order: Worker → host → iOS. The optional encrypted subtitle remai
| 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 tests cover payload generation, error classification, request validation, ticket replacement, Swift payload decoding and crypto vectors. The signed device checks below cover extension execution and background ActivityKit delivery. Focus behavior, pre-first-unlock behavior, action navigation and OS-driven token rotation still need separate acceptance scenarios.
### Local verification — 2026-09-27
-- Host: `cargo fmt --check`, `cargo clippy --all-targets -- -D warnings`, and all 147 unit/integration tests passed.
+- Host: `cargo fmt --check`, `cargo clippy --all-targets -- -D warnings`, and all 148 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.
@@ -134,9 +138,21 @@ Local tests cover payload generation, error classification, request validation,
### Deployment and device verification — 2026-09-27
-- Deployed `codync-relay`, version `d29a7eb4-f22e-4e27-a393-d563a5e56ff3`; `/health` returned HTTP 200.
+- Deployed `codync-relay`, version `2ba1d27c-116c-423d-87e4-2a7749575bd3`; `/health` returned HTTP 200.
- Built and restarted the signed Mac app and its launchd host. The running host includes the new notification implementation; its health endpoint returned success.
- Built and installed the signed Debug iOS app on the paired iPhone 16 Pro Max. App and notification extension both resolve their shared Keychain group to `7FUM8A8H72.com.pokai.Codync`, with the matching App Group. The app uses the development APNs environment.
- The live host contained 191 tickets across five device identities. The active phone's group shrank from ten rows to one on reconnect. Added regression coverage ensures older groups also send through only their newest stored ticket.
- Two encrypted test alerts returned HTTP 200 from the deployed Worker/APNs path. Device logs confirm the notification service extension executed, with no recorded decryption failure for those tests.
-- Visual notification content and background ActivityKit acceptance remain under verification; APNs acceptance and extension invocation alone are not recorded as a complete device pass.
+- Debug device diagnostics read iOS-delivered notifications for the temporary verification bot and confirmed the decrypted title `Push verification`, subtitle `Task complete`, and final result body. The same inspection identified the four obsolete-identity fallbacks, leading to physical-destination deduplication in the Worker.
+- A task started from the iPhone created a real Live Activity. While the app was on the Home Screen, an APNs needs-input update changed the Dynamic Island indicator to amber. Releasing the controlled host task ended the activity and removed its host ticket. The stale-date payload passed automated checks, but its delayed visual transition was not conclusively observed on the device.
+
+
+For repeatable Debug-only acceptance, launch the app with `CODYNC_PUSH_VERIFY_BOT` set to the temporary test bot ID. The console's `CODYNC_PUSH_VERIFICATION` line reports only that bot's delivered notifications, current activities and authorization state. It does not expose keys, tickets, account IDs or other bots' notifications. Release builds do not include this diagnostic.
+
+- The deployed batch endpoint received five tickets for one physical phone and returned four superseded results plus one successful delivery. Device diagnostics confirmed exactly one new decrypted notification and no additional generic fallbacks. The user also confirmed the complete title and body were visible.
+- The updated running host executed controlled failure and success tasks. Its next delivery automatically removed obsolete identity rows, leaving one valid alert ticket in the live database.
+- Final signed iOS and macOS Debug builds passed after the batch fix.
+
+Set `CODYNC_PUSH_CLEAR_TEST_NOTIFICATIONS=1` alongside the Debug verification bot ID to remove only that bot's delivered test notifications after reporting them.
+
+- Final device diagnostics confirmed one decrypted failure (`Push verification / Task failed / The agent failed.`), one additional decrypted success, no new generic fallback, and no remaining test activity. The temporary bot was deleted and its delivered notifications were cleared.
diff --git a/host/src/remote/push.rs b/host/src/remote/push.rs
index 24ef7424..ad2821aa 100644
--- a/host/src/remote/push.rs
+++ b/host/src/remote/push.rs
@@ -49,7 +49,14 @@ fn throttled(key: (String, AlertKind), min_gap: Duration) -> bool {
fn post(url: String, body: Value) {
tokio::spawn(async move {
match crate::http().post(&url).json(&body).timeout(Duration::from_secs(10)).send().await {
- Ok(r) if r.status().is_success() => {}
+ Ok(r) if r.status().is_success() => {
+ if let Some(notifications) = body["notifications"].as_array() {
+ match r.json::<Value>().await {
+ Ok(reply) => record_batch_results(notifications, &reply),
+ Err(error) => tracing::warn!(%error, "invalid relay batch response"),
+ }
+ }
+ }
Ok(r) if r.status() == reqwest::StatusCode::GONE => {
if let Some(t) = body["ticket"].as_str() {
GONE.locked().push(t.to_owned());
@@ -61,6 +68,18 @@ fn post(url: String, body: Value) {
});
}
+fn record_batch_results(notifications: &[Value], reply: &Value) {
+ for result in reply["results"].as_array().into_iter().flatten() {
+ let Some(index) = result["index"].as_u64().and_then(|index| usize::try_from(index).ok()) else { continue };
+ let Some(ticket) = notifications.get(index).and_then(|item| item["ticket"].as_str()) else { continue };
+ if result["status"] == 410 || result["superseded"] == true {
+ GONE.locked().push(ticket.to_owned());
+ } else if result["status"] != 200 {
+ tracing::warn!(status = ?result["status"], "relay rejected a batched notification");
+ }
+ }
+}
+
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) {
@@ -93,6 +112,7 @@ pub fn notify(hub: &Hub, bot: &BotConfig, title: &str, body: &str, kind: AlertKi
"body": crate::agent::acp::truncate(body, 400)})
.to_string();
let computer_id = hub.identity.computer_id();
+ let mut notifications = Vec::new();
for t in hub.store.push_tickets() {
let mut data = json!({"botId": bot.id, "computerId": computer_id, "ctx": t.ctx});
if let Some(key) = t.push_key.as_deref().and_then(|k| crypto::unb64_n::<32>(k).ok()) {
@@ -102,17 +122,17 @@ pub fn notify(hub: &Hub, bot: &BotConfig, title: &str, body: &str, kind: AlertKi
Err(error) => tracing::warn!(error = format!("{error:#}"), "couldn't seal a notification"),
}
}
- post(
- format!("{relay}/push"),
- json!({
- "ticket": t.ticket,
- "alert": {"title": "Codync", "body": generic},
- "mutableContent": true,
- "threadId": format!("{computer_id}:{}", bot.id),
- "category": kind,
- "data": data,
- }),
- );
+ notifications.push(json!({
+ "ticket": t.ticket,
+ "alert": {"title": "Codync", "body": generic},
+ "mutableContent": true,
+ "threadId": format!("{computer_id}:{}", bot.id),
+ "category": kind,
+ "data": data,
+ }));
+ }
+ if !notifications.is_empty() {
+ post(format!("{relay}/push-batch"), json!({"notifications": notifications}));
}
}
diff --git a/host/src/store.rs b/host/src/store.rs
index 69844070..700ed511 100644
--- a/host/src/store.rs
+++ b/host/src/store.rs
@@ -847,14 +847,20 @@ impl Store {
pub fn remove_push_ticket(&self, ticket: &str) -> Result<()> {
let c = self.db.locked();
- c.execute("DELETE FROM push_tickets WHERE ticket = ?1", [ticket])?;
+ // If the newest ticket for an identity is dead or superseded, do not fall back
+ // to its older rows on the next delivery. A concurrently replaced ticket is untouched.
+ c.execute(
+ "DELETE FROM push_tickets WHERE device_key = (SELECT device_key FROM push_tickets WHERE ticket = ?1)
+ AND rowid <= (SELECT rowid FROM push_tickets WHERE ticket = ?1)",
+ [ticket],
+ )?;
c.execute("DELETE FROM activity_tickets WHERE ticket = ?1", [ticket])?;
Ok(())
}
pub fn push_tickets(&self) -> Vec<PushTicket> {
let c = self.db.locked();
- let rows = c.prepare("SELECT ticket, push_key, ctx FROM push_tickets WHERE rowid IN (SELECT MAX(rowid) FROM push_tickets GROUP BY device_key)").and_then(|mut st| {
+ let rows = c.prepare("SELECT ticket, push_key, ctx FROM push_tickets WHERE rowid IN (SELECT MAX(rowid) FROM push_tickets GROUP BY device_key) ORDER BY rowid").and_then(|mut st| {
st.query_map([], |r| Ok(PushTicket { ticket: r.get(0)?, push_key: r.get(1)?, ctx: r.get(2)? }))?
.collect::<rusqlite::Result<Vec<_>>>()
});
@@ -1000,6 +1006,8 @@ mod tests {
assert_eq!(tickets.len(), 2);
assert!(!tickets.iter().any(|ticket| ticket.ticket == "old"));
assert_eq!(s.activity_tickets("bot"), ["new-a"]);
+ s.remove_push_ticket("new").unwrap();
+ assert_eq!(s.push_tickets().iter().map(|ticket| ticket.ticket.as_str()).collect::<Vec<_>>(), ["other"]);
}
#[test]
diff --git a/relay/src/index.ts b/relay/src/index.ts
index 8aacae88..9c908746 100644
--- a/relay/src/index.ts
+++ b/relay/src/index.ts
@@ -197,6 +197,37 @@ async function push(req: Request, env: Env): Promise<Response> {
}
}
+/** One physical APNs destination receives only the newest registration for this event.
+ * The host cannot do this comparison itself because it never sees raw APNs tokens.
+ */
+export function latestTicketIndices(tickets: Array<TicketPayload | null>): Set<number> {
+ const latest = new Map<string, number>();
+ tickets.forEach((ticket, index) => {
+ if (ticket) latest.set(`${ticket.e}:${ticket.k}:${ticket.t.toLowerCase()}`, index);
+ });
+ return new Set(latest.values());
+}
+
+export async function pushBatch(req: Request, env: Env, deliver = push): Promise<Response> {
+ const body = await req.json().catch(() => null) as { notifications?: PushBody[] } | null;
+ const notifications = body?.notifications;
+ if (!Array.isArray(notifications) || notifications.length === 0 || notifications.length > 256) {
+ return json({ error: "invalid notification batch" }, 400);
+ }
+ const tickets = await Promise.all(notifications.map(notification =>
+ typeof notification?.ticket === "string" ? openTicket(env, notification.ticket) : null));
+ const latest = latestTicketIndices(tickets);
+ const results = await Promise.all(notifications.map(async (notification, index) => {
+ if (!tickets[index]) return { index, status: 403 };
+ if (!latest.has(index)) return { index, status: 200, superseded: true };
+ const response = await deliver(new Request(req.url, {
+ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(notification),
+ }), env);
+ return { index, status: response.status };
+ }));
+ return json({ results });
+}
+
export default {
async fetch(req: Request, env: Env): Promise<Response> {
const { pathname } = new URL(req.url);
@@ -204,6 +235,7 @@ export default {
if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
if (pathname === "/register") return register(req, env);
if (pathname === "/push") return push(req, env);
+ if (pathname === "/push-batch") return pushBatch(req, env);
return json({ error: "not found" }, 404);
},
};
diff --git a/relay/test/push.test.ts b/relay/test/push.test.ts
index 32b398b3..821a6147 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 worker, { alertAps, liveActivityAps, tokenIsGone, sealTicket } from "../src/index.ts";
+import worker, { alertAps, liveActivityAps, tokenIsGone, sealTicket, latestTicketIndices, pushBatch } 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);
@@ -39,3 +39,30 @@ assert.equal((await request("/push", { ticket, alert: { body: "fallback" }, data
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");
+
+// Old account/device identities may still point to the exact same physical phone.
+assert.deepEqual([...latestTicketIndices([
+ { t: "AB", e: "sandbox", k: "alert" },
+ { t: "ab", e: "sandbox", k: "alert" },
+ { t: "ab", e: "production", k: "alert" },
+ { t: "ab", e: "sandbox", k: "liveactivity" },
+ null,
+])], [1, 2, 3]);
+const newerTicket = await sealTicket(env, { t: "ab".repeat(32), e: "sandbox", k: "alert" });
+const sent: string[] = [];
+const batch = await pushBatch(new Request("https://relay.test/push-batch", {
+ method: "POST", body: JSON.stringify({ notifications: [
+ { ticket, alert: { body: "old-key" } },
+ { ticket: newerTicket, alert: { body: "current-key" } },
+ { ticket: "invalid" },
+ ] }),
+}), env, async request => {
+ sent.push((await request.json() as any).alert.body);
+ return Response.json({ ok: true });
+});
+assert.deepEqual(sent, ["current-key"]);
+assert.deepEqual(await batch.json(), { results: [
+ { index: 0, status: 200, superseded: true }, { index: 1, status: 200 }, { index: 2, status: 403 },
+] });
+assert.equal((await request("/push-batch", { notifications: [] })).status, 400);
+console.log("physical device deduplication tests ok");