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: a phone that signs back in keeps getting alerts from every computer

leepokai55988f7a479b
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreAccount.kt b/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreAccount.kt
index b14ca019..8c5c84b3 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreAccount.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreAccount.kt
@@ -38,6 +38,9 @@ fun AccountStore.signOut() = sessionAction {
val account = cloud?.pinningToken()
transitions.withLock {
NativeAccounts.signOut(old.sessionId)
+ // No push ticket goes out from here (a background registration finishes first): a computer keeps one that
+ // reaches it after the account marks this phone signed out, taking it for one sent on signing back in.
+ PushDelivery.retire(getApplication())
account?.let { bestEffort("tell the account this phone signed out") { it.signOutThisDevice() } }
switchAway(old.userId)
}
diff --git a/apps/ios/App/AppStore+Account.swift b/apps/ios/App/AppStore+Account.swift
index 4aba2dd7..1fda0187 100644
--- a/apps/ios/App/AppStore+Account.swift
+++ b/apps/ios/App/AppStore+Account.swift
@@ -22,6 +22,10 @@ extension AppStore {
leaving = true
await account.signOut()
if hasLeft(userID) {
+ // No push ticket goes out from here: a computer keeps one that reaches it after the account marks this
+ // iPhone signed out, taking it for one sent on signing back in.
+ accounts.onConnected = nil
+ PushRegistrar.shared.deactivate()
await tell(computers: { try await $0.unregisterDevice() }, cloud: cloud, account: { try await $0.signOutThisDevice() })
}
finishLeaving()
diff --git a/cloud/migrations/0006_signed_out_devices.sql b/cloud/migrations/0006_signed_out_devices.sql
index 860dabd1..0bdfe8e5 100644
--- a/cloud/migrations/0006_signed_out_devices.sql
+++ b/cloud/migrations/0006_signed_out_devices.sql
@@ -1,3 +1,4 @@
-- A phone that signed out keeps its key and its access, but its notifications stop: the account's computers drop
--- its push tickets on their next state pull (`signedOut` in GET /v1/host/state). Registering it again clears this.
+-- the push tickets it registered up to then on their next state pull (`signedOutDevices` in GET /v1/host/state, with
+-- `signed_out_at`). Registering it again clears this.
ALTER TABLE devices ADD COLUMN signed_out_at INTEGER;
diff --git a/cloud/src/routes/host.ts b/cloud/src/routes/host.ts
index b718638f..cb30ad3f 100644
--- a/cloud/src/routes/host.ts
+++ b/cloud/src/routes/host.ts
@@ -134,17 +134,18 @@ export async function hostState(c: Ctx) {
created_at: number;
expires_at: number;
}>();
- // The account's phones that signed out: the host drops their push tickets.
+ // The account's phones that signed out, and when: the host drops their push tickets from before then, so a ticket
+ // sent after signing back in survives a pull that lands before the phone's `POST /v1/devices` clears the mark.
const signedOut = comp.owner_user_id
? await c.env.DB.prepare(
- "SELECT sign_pub FROM devices WHERE owner_user_id = ? AND signed_out_at IS NOT NULL AND revoked_at IS NULL",
+ "SELECT sign_pub, signed_out_at FROM devices WHERE owner_user_id = ? AND signed_out_at IS NOT NULL AND revoked_at IS NULL",
)
.bind(comp.owner_user_id)
- .all<{ sign_pub: string }>()
+ .all<{ sign_pub: string; signed_out_at: number }>()
: { results: [] };
return {
owner: owner ? { userId: owner.user_id, email: owner.email } : null,
- signedOut: signedOut.results.map((d) => d.sign_pub),
+ signedOutDevices: signedOut.results.map((d) => ({ deviceKey: d.sign_pub, signedOutAt: d.signed_out_at })),
grants: grants.results.map((g) => ({
grantId: g.id,
deviceKey: g.sign_pub,
diff --git a/cloud/test/api.test.ts b/cloud/test/api.test.ts
index 5fba26e9..b13f65e1 100644
--- a/cloud/test/api.test.ts
+++ b/cloud/test/api.test.ts
@@ -261,14 +261,20 @@ describe("devices", () => {
const elsewhere = await newHost();
expect((await claim(u, host)).status).toBe(200);
expect((await claim(other, elsewhere)).status).toBe(200);
- const signedOut = async (h: TestHost) => (await call("GET", "/v1/host/state", { key: h.sign })).body.signedOut;
+ const signedOut = async (h: TestHost) => (await call("GET", "/v1/host/state", { key: h.sign })).body.signedOutDevices;
expect(await signedOut(host)).toEqual([]);
const [hostWs, elsewhereWs] = await Promise.all([hostSocket(host), hostSocket(elsewhere)]);
+ const before = Date.now();
expect((await call("POST", "/v1/devices/sign-out", { token: u.token, key: u.key })).status).toBe(200);
+ const after = Date.now();
// The account's computers pull now, not at their next poll; another account's hear nothing.
await hostWs.nextT("cloud.changed");
await elsewhereWs.none((m) => m.t === "cloud.changed");
- expect(await signedOut(host)).toEqual([u.dk]);
+ const marks = await signedOut(host);
+ expect(marks).toEqual([{ deviceKey: u.dk, signedOutAt: expect.any(Number) }]);
+ // In ms, as the host's push tickets: it drops the ones that came up to then.
+ expect(marks[0].signedOutAt).toBeGreaterThanOrEqual(before);
+ expect(marks[0].signedOutAt).toBeLessThanOrEqual(after);
expect(await signedOut(elsewhere)).toEqual([]);
// Still in the account, so signing back in needs no new access: registering again clears it.
expect((await call("POST", "/v1/devices/certificate", { token: u.token, key: u.key })).status).toBe(200);
@@ -513,7 +519,7 @@ describe("revocation reaches the relay", () => {
await grantAccess(u, host);
expect((await call("POST", "/v1/host/unclaim", { key: host.sign, body: {} })).status).toBe(200);
const state = await call("GET", "/v1/host/state", { key: host.sign });
- expect(state.body).toEqual({ owner: null, grants: [], requests: [], signedOut: [] });
+ expect(state.body).toEqual({ owner: null, grants: [], requests: [], signedOutDevices: [] });
expect((await call("GET", "/v1/computers", { token: u.token })).body.computers).toEqual([]);
});
@@ -582,7 +588,7 @@ describe("Clerk webhook", () => {
const id = `msg_${ref.b64url(ref.random(8))}`;
expect((await deliver(id, { type: "user.deleted", data: { id: u.userId } })).status).toBe(200);
expect((await call("GET", "/v1/me", { token: u.token })).body.error.code).toBe("accountDeleted");
- expect((await call("GET", "/v1/host/state", { key: host.sign })).body).toEqual({ owner: null, grants: [], requests: [], signedOut: [] });
+ expect((await call("GET", "/v1/host/state", { key: host.sign })).body).toEqual({ owner: null, grants: [], requests: [], signedOutDevices: [] });
expect((await deliver(id, { type: "user.deleted", data: { id: u.userId } })).status).toBe(200);
const n = await env.DB.prepare("SELECT COUNT(*) AS n FROM processed_events WHERE event_id = ?").bind(id).first<{ n: number }>();
expect(n?.n).toBe(1);
diff --git a/docs/architecture/connections.md b/docs/architecture/connections.md
index b784d71f..758c4938 100644
--- a/docs/architecture/connections.md
+++ b/docs/architecture/connections.md
@@ -62,7 +62,7 @@ Decided 2026-11-02. A computer is in one account at most; a phone may know sever
| What happens | On the phone | Computers and cloud |
| --- | --- | --- |
| The Clerk session ends on its own (expired, revoked elsewhere) | The sign-in screen; the account's key, computers and drafts stay. Signing in to the same account connects as before: no scan, no 6-digit check | Unchanged |
-| **Sign out** | The key, computers and drafts stay; signing back in to the same account connects as before, no scan, no check | The phone stays a device. Its alerts stop: the computers it reaches drop its push tickets (`unregisterDevice`), the account marks it signed out (`POST /v1/devices/sign-out`) and the other computers drop them on their next state pull (`signedOut`). Registering again at sign-in clears the mark |
+| **Sign out** | The key, computers and drafts stay; signing back in to the same account connects as before, no scan, no check | The phone stays a device. Its alerts stop: the computers it reaches drop its push tickets (`unregisterDevice`), the account marks it signed out (`POST /v1/devices/sign-out`) and the other computers drop those registered before it on their next state pull (`signedOutDevices`). Registering again at sign-in clears the mark |
| Using another account | Only after signing out: both Clerk instances stay single-session (`single_session_mode`) | As signing out: the first account's computers keep the phone, without alerts, until it comes back |
| **Start over**, **Delete account** | Start over erases every account's keys and data, accounts signed out here included; Delete account erases that account's | The open account's computers drop the phone (`forgetDevice`), the cloud revokes it (Delete account: Clerk's webhook does) |
diff --git a/docs/plans/require-sign-in.md b/docs/plans/require-sign-in.md
index 5bf59e08..b1fc4fb4 100644
--- a/docs/plans/require-sign-in.md
+++ b/docs/plans/require-sign-in.md
@@ -49,7 +49,7 @@ Built in 2.35.0 as handing the key back; changed before release (2026-11-02) to
1. **Clerk:** sign out first. When that fails nothing below runs. The cloud call below needs a session token, so one is taken before (`CloudClient.pinningToken()`); it stays valid until it expires. The account's stores stay open until the steps below finish (`AppStore.leaving` on iOS, `transitions` on Android).
2. **Computers this phone can reach:** `unregisterDevice` drops its push tickets (Android: closing each computer's store does it, `AppStore.retire`). The device stays.
-3. **Cloud:** `POST /v1/devices/sign-out` (Clerk + `Codync-Sig`) marks the device signed out and tells the account's computers to pull their state, whose `signedOut` lists it: each drops its push tickets. `POST /v1/devices`, which the phone sends with every refresh of the account's computers (opening the account, coming back to the foreground), clears the mark, so a failed one is retried. `CloudClient.signOutThisDevice()` and its Android twin.
+3. **Cloud:** `POST /v1/devices/sign-out` (Clerk + `Codync-Sig`) marks the device signed out and tells the account's computers to pull their state, whose `signedOutDevices` lists it with its sign-out time: each drops the push tickets registered up to then (a ticket sent after signing back in can arrive before `POST /v1/devices` clears the mark). The phone stops registering push before this call (iOS `PushRegistrar.deactivate()`, Android `PushDelivery.retire`), so no ticket from the phone that is signing out comes later. `POST /v1/devices`, which the phone sends with every refresh of the account's computers (opening the account, coming back to the foreground), clears the mark, so a failed one is retried. `CloudClient.signOutThisDevice()` and its Android twin.
4. Switch context. The account's key, computers and drafts stay on the phone.
The two calls are best effort, with a short timeout each. Signing out never fails because a computer or the cloud is unreachable.
@@ -152,7 +152,7 @@ After either case the signed-out context is erased (on iOS except a mirror cache
| Fresh install | The welcome shows only sign-in. Signing in leads to pairing, and a QR pair works |
| Upgrade | With the previous build signed out, pair by QR. Install this build: the gate counts the computer. Sign in: the computer is there and connects without scanning, and push still arrives |
| Merge case | Unit tests only: with sign-in required, a phone can't pair signed out any more, so this only happens to someone who was signed in on an older build and had also paired signed out (the older builds can't take the test sign-in ticket) |
-| Sign out | The computer keeps the phone but has no push ticket for it; the cloud's host state lists it in `signedOut`. Sign back in: it connects without a scan and registers push again |
+| Sign out | The computer keeps the phone but has no push ticket for it; the cloud's host state lists it in `signedOutDevices`. Sign back in: it connects without a scan and registers push again |
| Delete account | The test user is gone in Clerk, and the computers leave the account (`--prune` cleans up) |
| Desktop | Signed out shows the welcome with no skip. Sign out returns to it. Signed in to a second test account, the footer notice shows and reopens the move choice |
diff --git a/docs/reference/remote-relay.md b/docs/reference/remote-relay.md
index 2ae476ee..7d636836 100644
--- a/docs/reference/remote-relay.md
+++ b/docs/reference/remote-relay.md
@@ -88,7 +88,7 @@ See [architecture](../architecture/overview.md) and [file structure](../architec
- 桌面 App(`apps/desktop/src/main/cloud.ts`):每個帳號一把 Ed25519 device key,seed 以 Electron `safeStorage`(OS keychain)加密後存在 app 的 userData 目錄;只用於雲端 `/v1` API 的 `Codync-Sig`。
- iOS App、Widgets、NotificationService 共用 access group `$(AppIdentifierPrefix)com.pokai.Codync`(`project.yml` 對這三個 target 加 `keychain-access-groups` entitlement;`CodyncKit` 從 Info.plist `CodyncKeychainGroup` 讀 group,缺值則不設 group)。
- 私鑰永不離開 Keychain/process;雲端只存公鑰。
-- 帳號登出:先在 Clerk 登出(失敗就什麼都不變)。成功後只停通知、保留金鑰:連得到的電腦呼叫 `unregisterDevice` 刪掉 push tickets;雲端 `POST /v1/devices/sign-out`(用登出前先取的 session token)標記這台裝置已登出,帳號的其他電腦下次拉 `/v1/host/state` 時依 `signedOut` 刪掉它的 push tickets。各自最多數秒、失敗不擋登出。該 context 的 device key、computers、草稿都留著,同一帳號登回來直接連上(`POST /v1/devices` 清掉標記)。**Start over**/刪除帳號才交還金鑰:連得到的電腦呼叫 `forgetDevice`(舊版 host 改呼叫 `unregisterDevice`),雲端 `DELETE /v1/devices/{id}`(刪除帳號由 `user.deleted` webhook 處理),再刪除 device key、computers 快取、mailbox 草稿、widget snapshot;Start over 連這支手機上登出過的帳號一起刪。刪除帳號先在 Clerk 刪除使用者,成功後才交還給電腦。
+- 帳號登出:先在 Clerk 登出(失敗就什麼都不變)。成功後只停通知、保留金鑰:連得到的電腦呼叫 `unregisterDevice` 刪掉 push tickets;雲端 `POST /v1/devices/sign-out`(用登出前先取的 session token)標記這台裝置已登出,帳號的其他電腦下次拉 `/v1/host/state` 時依 `signedOutDevices` 刪掉它在登出前登記的 push tickets。各自最多數秒、失敗不擋登出。該 context 的 device key、computers、草稿都留著,同一帳號登回來直接連上(`POST /v1/devices` 清掉標記)。**Start over**/刪除帳號才交還金鑰:連得到的電腦呼叫 `forgetDevice`(舊版 host 改呼叫 `unregisterDevice`),雲端 `DELETE /v1/devices/{id}`(刪除帳號由 `user.deleted` webhook 處理),再刪除 device key、computers 快取、mailbox 草稿、widget snapshot;Start over 連這支手機上登出過的帳號一起刪。刪除帳號先在 Clerk 刪除使用者,成功後才交還給電腦。
- 有 Clerk 的 build 一律要求登入([require sign-in](../plans/require-sign-in.md)):`local` context 只留給沒有 Clerk 的 build,以及登入前遷移的來源。某個帳號 context 第一次使用時,若 `local` 有電腦或金鑰:該 context 在這支手機上是新的(沒有金鑰、沒有電腦)就整包搬過去,金鑰一起搬,電腦不用重新掃;已有自己的金鑰就只合併電腦清單,那些電腦會顯示需要重新配對。之後清掉 `local`(iOS `SharedStore.Context.adopt(from:)`、Android `LocalStore.adopt`)。
### 3.3 Per-(device, host) E2E 金鑰
@@ -519,9 +519,9 @@ The route table below summarizes the contract. Executable schema and validation
{"owner":{"userId":"user_…","email":"[email protected]"} | null,
"grants":[{"grantId","deviceKey","deviceName","platform","scopes":["control","screen"]}],
"requests":[{"requestId","deviceKey","deviceName","platform","email","commit","hostNonce"?,"deviceNonce"?,"createdAt","expiresAt"}],
- "signedOut":["<deviceKey>"]}
+ "signedOutDevices":[{"deviceKey","signedOutAt"}]}
```
- grants 只含:grant active、device 未撤銷、device.owner == computer.owner。host 只把它當成「可續約/應刪除」的清單(§4.3)。`signedOut` 是電腦所屬帳號裡登出的裝置(未撤銷),host 刪掉它們的 push tickets,不動裝置列。
+ grants 只含:grant active、device 未撤銷、device.owner == computer.owner。host 只把它當成「可續約/應刪除」的清單(§4.3)。`signedOutDevices` 是電腦所屬帳號裡登出的裝置(未撤銷)與登出時間(ms),host 只刪掉它們在那之前登記的 push tickets,不動裝置列:手機登回來後送來的新 ticket 可能比清掉標記的 `POST /v1/devices` 先到,要留著。
- `POST /v1/host/access-requests/{id}/nonce` `{"nonce"}` → `{}`(`cloud/src/routes/host.ts`;已設過 → `409`)
- `POST /v1/host/grants/{grantId}/revoke` `{}` → `{}`(host 在本機撤銷帳號來源裝置時同步 D1,`revoked_reason='owner'`;失敗記錄並存入 `grant_revokes` 重試,本機撤銷已生效)
- `POST /v1/host/access-requests/{id}/decision` `{"decision":"approve"|"deny"}` → `{"status","grantId"?}`(`cloud/src/routes/host.ts` 的原子更新;request 過期 → `410 requestExpired`;approve 要求 `device_nonce IS NOT NULL`,否則 `409`)
diff --git a/host/src/remote/cloud.rs b/host/src/remote/cloud.rs
index d76ee0e9..6a37dd33 100644
--- a/host/src/remote/cloud.rs
+++ b/host/src/remote/cloud.rs
@@ -303,7 +303,14 @@ struct State {
requests: Vec<StateRequest>,
/// The account's phones that signed out: they keep their access, but get no alerts until they sign back in.
#[serde(default)]
- signed_out: Vec<String>,
+ signed_out_devices: Vec<SignedOut>,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct SignedOut {
+ device_key: String,
+ signed_out_at: i64,
}
#[derive(Deserialize)]
@@ -341,8 +348,10 @@ pub async fn pull(hub: &Hub, base: &str) -> Result<()> {
let state: State = serde_json::from_value(call(hub, base, Method::GET, "/v1/host/state", None).await?)
.context("reading the cloud state")?;
apply_grants(hub, &state.grants)?;
- for device in &state.signed_out {
- hub.store.remove_push_tickets(device)?;
+ // Only tickets from before signing out: the phone sends a new one on signing back in, which can arrive before
+ // the cloud hears of it.
+ for device in &state.signed_out_devices {
+ hub.store.remove_push_tickets_until(&device.device_key, device.signed_out_at)?;
}
super::owner::remember(hub, state.owner.as_ref())?;
let in_account = state.owner.is_some();
@@ -815,11 +824,20 @@ mod tests {
let base = fake_cloud(fake.clone()).await;
hub.store.add_push_ticket("t1", "signed out", None, Some("ctx"), "iPhone").unwrap();
hub.store.add_push_ticket("t2", "still in", None, Some("ctx"), "Pixel").unwrap();
- *fake.state.lock().unwrap() =
- json!({"owner": {"userId": "user_1"}, "grants": [], "requests": [], "signedOut": ["signed out"]});
+ let state = |at: i64| {
+ json!({"owner": {"userId": "user_1"}, "grants": [], "requests": [],
+ "signedOutDevices": [{"deviceKey": "signed out", "signedOutAt": at}]})
+ };
+ *fake.state.lock().unwrap() = state(now_ms());
+ pull(&hub, &base).await.unwrap();
+ let tickets = || hub.store.push_tickets().into_iter().map(|t| t.ticket).collect::<Vec<_>>();
+ assert_eq!(tickets(), ["t2"]);
+ // Signing back in: the new ticket can reach this computer before the cloud clears the mark.
+ let signed_out_at = now_ms() - 1;
+ hub.store.add_push_ticket("t3", "signed out", None, Some("ctx"), "iPhone").unwrap();
+ *fake.state.lock().unwrap() = state(signed_out_at);
pull(&hub, &base).await.unwrap();
- let tickets: Vec<String> = hub.store.push_tickets().into_iter().map(|t| t.ticket).collect();
- assert_eq!(tickets, ["t2"]);
+ assert_eq!(tickets(), ["t2", "t3"], "a ticket sent after signing out keeps its alerts");
}
#[tokio::test]
diff --git a/host/src/store/devices.rs b/host/src/store/devices.rs
index 93869ccd..7e73dc03 100644
--- a/host/src/store/devices.rs
+++ b/host/src/store/devices.rs
@@ -187,6 +187,14 @@ impl Store {
Ok(())
}
+ /// As `remove_push_tickets`, for the tickets a device registered up to `until` (ms): a newer one came after it
+ /// signed back in.
+ pub fn remove_push_tickets_until(&self, device_key: &str, until: i64) -> Result<()> {
+ let c = self.db.locked();
+ c.execute("DELETE FROM push_tickets WHERE device_key = ?1 AND created_at <= ?2", params![device_key, until])?;
+ Ok(())
+ }
+
pub fn remove_push_ticket(&self, ticket: &str) -> Result<()> {
let c = self.db.locked();
// If the newest ticket for an identity is dead or superseded, do not fall back