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: alerts for a phone that signed back in no longer depend on the computer's clock

leepokaid4c46a014787
diff --git a/cloud/src/routes/host.ts b/cloud/src/routes/host.ts
index cb30ad3f..5bfde269 100644
--- a/cloud/src/routes/host.ts
+++ b/cloud/src/routes/host.ts
@@ -134,8 +134,9 @@ export async function hostState(c: Ctx) {
created_at: number;
expires_at: number;
}>();
- // 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.
+ // The account's phones that signed out, and how long ago (relative, so the host's clock needn't match this one): 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, signed_out_at FROM devices WHERE owner_user_id = ? AND signed_out_at IS NOT NULL AND revoked_at IS NULL",
@@ -145,7 +146,7 @@ export async function hostState(c: Ctx) {
: { results: [] };
return {
owner: owner ? { userId: owner.user_id, email: owner.email } : null,
- signedOutDevices: signedOut.results.map((d) => ({ deviceKey: d.sign_pub, signedOutAt: d.signed_out_at })),
+ signedOutDevices: signedOut.results.map((d) => ({ deviceKey: d.sign_pub, signedOutAgo: c.now - 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 b13f65e1..f5f0549b 100644
--- a/cloud/test/api.test.ts
+++ b/cloud/test/api.test.ts
@@ -266,15 +266,14 @@ describe("devices", () => {
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");
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(marks).toEqual([{ deviceKey: u.dk, signedOutAgo: expect.any(Number) }]);
+ // In ms, as the host's push tickets: it drops the ones that came up to then, counted back on its own clock.
+ expect(marks[0].signedOutAgo).toBeGreaterThanOrEqual(0);
+ expect(marks[0].signedOutAgo).toBeLessThanOrEqual(Date.now() - before);
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);
diff --git a/docs/plans/require-sign-in.md b/docs/plans/require-sign-in.md
index b1fc4fb4..6bc12f10 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 `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.
+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 how long ago it signed out (relative, so the computer's clock needn't match the cloud's): 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.
diff --git a/docs/reference/remote-relay.md b/docs/reference/remote-relay.md
index 7d636836..a1a9384a 100644
--- a/docs/reference/remote-relay.md
+++ b/docs/reference/remote-relay.md
@@ -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"}],
- "signedOutDevices":[{"deviceKey","signedOutAt"}]}
+ "signedOutDevices":[{"deviceKey","signedOutAgo"}]}
```
- grants 只含:grant active、device 未撤銷、device.owner == computer.owner。host 只把它當成「可續約/應刪除」的清單(§4.3)。`signedOutDevices` 是電腦所屬帳號裡登出的裝置(未撤銷)與登出時間(ms),host 只刪掉它們在那之前登記的 push tickets,不動裝置列:手機登回來後送來的新 ticket 可能比清掉標記的 `POST /v1/devices` 先到,要留著。
+ 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 6a37dd33..7f566a72 100644
--- a/host/src/remote/cloud.rs
+++ b/host/src/remote/cloud.rs
@@ -310,7 +310,8 @@ struct State {
#[serde(rename_all = "camelCase")]
struct SignedOut {
device_key: String,
- signed_out_at: i64,
+ /// How long before the cloud answered (ms): relative, so its clock needn't match this computer's.
+ signed_out_ago: i64,
}
#[derive(Deserialize)]
@@ -349,9 +350,11 @@ pub async fn pull(hub: &Hub, base: &str) -> Result<()> {
.context("reading the cloud state")?;
apply_grants(hub, &state.grants)?;
// 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.
+ // the cloud hears of it. Counted back from after the answer, a slow one drops a ticket a moment too new (sent
+ // again on the phone's next connection) rather than keep one too old.
+ let now = now_ms();
for device in &state.signed_out_devices {
- hub.store.remove_push_tickets_until(&device.device_key, device.signed_out_at)?;
+ hub.store.remove_push_tickets_until(&device.device_key, now - device.signed_out_ago)?;
}
super::owner::remember(hub, state.owner.as_ref())?;
let in_account = state.owner.is_some();
@@ -824,18 +827,18 @@ 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();
- let state = |at: i64| {
+ let state = |signed_out_ago: i64| {
json!({"owner": {"userId": "user_1"}, "grants": [], "requests": [],
- "signedOutDevices": [{"deviceKey": "signed out", "signedOutAt": at}]})
+ "signedOutDevices": [{"deviceKey": "signed out", "signedOutAgo": signed_out_ago}]})
};
- *fake.state.lock().unwrap() = state(now_ms());
+ *fake.state.lock().unwrap() = state(0);
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;
+ // Signed out a minute ago; signing back in, the new ticket can reach this computer before the cloud clears
+ // the mark.
hub.store.add_push_ticket("t3", "signed out", None, Some("ctx"), "iPhone").unwrap();
- *fake.state.lock().unwrap() = state(signed_out_at);
+ *fake.state.lock().unwrap() = state(60_000);
pull(&hub, &base).await.unwrap();
assert_eq!(tickets(), ["t2", "t3"], "a ticket sent after signing out keeps its alerts");
}