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(apps): keep messages held on the phone and warn before a join removes phones

leepokaic79fd6ca870c
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.kt
index 342e1c53..961013fe 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.kt
@@ -96,8 +96,7 @@ fun AppStore.discard(send: PendingSend) = action("discard:" + send.nonce) {
refresh()
}
fun AppStore.cancelQueued(send: PendingSend) = action("cancel:" + send.nonce) {
- if (state.value.computer.cloud == null) {
- // No relay holds it: it only waits on this phone.
+ if (discardsOnPhone(state.value.computer.cloud, send.status)) {
withContext(Dispatchers.IO) { requireNotNull(database).discard(send.nonce) }
refresh()
return@action
@@ -161,7 +160,7 @@ internal suspend fun AppStore.deliver(send: PendingSend) {
/** A send that failed. With no relay holding it, a message waits here until the computer can be reached (`reconcileMailbox`). */
internal fun afterFailure(send: PendingSend, cloud: String?, error: Exception): PendingSend =
- if (cloud == null && error is IOException && error !is HostError) send.copy(status = SendStatus.Waiting)
+ if (cloud == null && error is IOException && error !is HostError) send.copy(status = SendStatus.Held)
else send.copy(status = SendStatus.Failed, error = error.message ?: "Couldn't send.")
/** Can't reach a computer with no relay: text waits on this phone until it can (iOS `BotStore.holdsOnPhone`). */
@@ -171,6 +170,9 @@ internal fun holdsOnPhone(cloud: String?, link: LinkState): Boolean = cloud == n
else -> false
}
+/** No relay holds it, so taking it back touches only this phone (iOS `BotStore.cancelQueued`). */
+internal fun discardsOnPhone(cloud: String?, status: SendStatus): Boolean = cloud == null || status == SendStatus.Held
+
internal suspend fun AppStore.savePending(send: PendingSend) {
withContext(Dispatchers.IO) { requireNotNull(database).save(send) }
refresh()
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt
index cdd320cb..69d222eb 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt
@@ -251,22 +251,33 @@ private fun AppStore.showConnection(link: LinkState) {
}
}
-/** What waited on this phone, ready to go with the same nonces, oldest first. */
-internal fun heldOnPhone(pending: List<PendingSend>): List<PendingSend> =
- pending.filter { it.status == SendStatus.Waiting }.sortedBy { it.createdAt }.map { it.copy(status = SendStatus.Sending) }
+/**
+ * What waited on this phone, ready to go with the same nonces, oldest first. With no relay now ([cloud] is null), what a
+ * relay held can't be asked about, so it goes too.
+ */
+internal fun readyToSend(pending: List<PendingSend>, cloud: String?): List<PendingSend> =
+ pending.filter { it.status == SendStatus.Held || (it.status == SendStatus.Waiting && cloud == null) }
+ .sortedBy { it.createdAt }.map { it.copy(status = SendStatus.Sending) }
+
+/** Delivers [ready] one at a time, leaving out what was taken back while an earlier one was on its way ([stillPending]). */
+internal suspend fun deliverInTurn(ready: List<PendingSend>, stillPending: suspend (PendingSend) -> Boolean, deliver: suspend (PendingSend) -> Unit) {
+ for (send in ready) if (stillPending(send)) deliver(send)
+}
private suspend fun AppStore.reconcileMailbox(active: EncryptedChannel) {
- // No relay holds them: what waited on this phone goes now, with the same nonces.
- if (state.value.computer.cloud == null) {
- for (send in heldOnPhone(state.value.pending)) deliver(send)
- return
- }
+ // What waited on this phone goes now, with the same nonces, also when the computer has joined an account since.
+ val cloud = state.value.computer.cloud
+ deliverInTurn(readyToSend(state.value.pending, cloud), { send ->
+ refresh() // A take-back may have reached the database and not yet the state.
+ state.value.pending.any { it.nonce == send.nonce }
+ }) { deliver(it) }
+ if (cloud == null) return
if (active.route != HostRoute.Relay || state.value.pending.none { it.status in listOf(SendStatus.Waiting, SendStatus.Delivering) }) return
try {
val response = active.queued()
- val held = response.getValue("items").jsonArray.associate { it.jsonObject.getValue("nonce").jsonPrimitive.content to it.jsonObject.getValue("state").jsonPrimitive.content }
+ val inRelay = response.getValue("items").jsonArray.associate { it.jsonObject.getValue("nonce").jsonPrimitive.content to it.jsonObject.getValue("state").jsonPrimitive.content }
for (send in state.value.pending.filter { it.status in listOf(SendStatus.Waiting, SendStatus.Delivering) }) {
- savePending(send.copy(status = when (held[send.nonce]) {
+ savePending(send.copy(status = when (inRelay[send.nonce]) {
"queued" -> SendStatus.Waiting
"delivering" -> SendStatus.Delivering
else -> SendStatus.Failed
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt b/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt
index c8b547d6..1a9c4b90 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt
@@ -233,7 +233,7 @@ internal val Entry.reactions: List<String> get() = (data["reactions"] as? JsonAr
SendStatus.Sending -> Text(state.uploadProgress[send.nonce]?.let { "Uploading files · $it%" } ?: "Sending…",
style = Type.caption2, color = Palette.tertiary)
SendStatus.Delivering -> Text("Delivered to the computer", style = Type.caption2, color = Palette.tertiary)
- SendStatus.Waiting -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ SendStatus.Waiting, SendStatus.Held -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Text("Waiting for the computer to come online", style = Type.caption2, color = Palette.tertiary)
Box(Modifier.clickable(role = Role.Button) { store.cancelQueued(send) }.semantics { contentDescription = "Don't send" }) {
Symbol("xmark.circle", size = 14.dp, tint = Palette.tertiary)
diff --git a/apps/android/app/src/test/kotlin/com/codync/android/QueuedMessagesTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/QueuedMessagesTest.kt
index a48fcc71..71ca7d33 100644
--- a/apps/android/app/src/test/kotlin/com/codync/android/QueuedMessagesTest.kt
+++ b/apps/android/app/src/test/kotlin/com/codync/android/QueuedMessagesTest.kt
@@ -6,6 +6,7 @@ import com.codync.android.core.HostRoute
import com.codync.android.core.LinkState
import com.codync.android.core.PendingSend
import com.codync.android.core.SendStatus
+import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import org.junit.Assert.assertEquals
@@ -19,10 +20,35 @@ class QueuedMessagesTest {
@Test fun `with no relay a message that can't go waits on the phone and goes with the same nonce`() {
val held = afterFailure(send("n1"), null, java.io.IOException("Can't reach the computer."))
- assertEquals(SendStatus.Waiting, held.status)
- val pending = listOf(send("n2", 2, SendStatus.Waiting), held, send("n3", 3, SendStatus.Failed))
- assertEquals(listOf("n1", "n2"), heldOnPhone(pending).map { it.nonce })
- assertEquals(setOf(SendStatus.Sending), heldOnPhone(pending).map { it.status }.toSet())
+ assertEquals(SendStatus.Held, held.status)
+ val pending = listOf(send("n2", 2, SendStatus.Held), held, send("n3", 3, SendStatus.Failed))
+ assertEquals(listOf("n1", "n2"), readyToSend(pending, null).map { it.nonce })
+ assertEquals(setOf(SendStatus.Sending), readyToSend(pending, null).map { it.status }.toSet())
+ }
+
+ @Test fun `what waits on the phone still goes after the computer joins an account, and the relay answers for the rest`() {
+ val pending = listOf(send("phone", 1, SendStatus.Held), send("relay", 2, SendStatus.Waiting))
+ assertEquals(listOf("phone"), readyToSend(pending, "https://api.codync.dev").map { it.nonce })
+ }
+
+ @Test fun `with no relay left, what a relay held goes too`() {
+ assertEquals(listOf("relay"), readyToSend(listOf(send("relay", 1, SendStatus.Waiting)), null).map { it.nonce })
+ }
+
+ @Test fun `a message taken back while an earlier one goes doesn't go`() = runBlocking {
+ val pending = mutableListOf("n1", "n2", "n3")
+ val delivered = mutableListOf<String>()
+ deliverInTurn(pending.map { send(it, status = SendStatus.Held) }, { it.nonce in pending }) { sent ->
+ delivered += sent.nonce
+ pending -= "n2"
+ }
+ assertEquals(listOf("n1", "n3"), delivered)
+ }
+
+ @Test fun `taking a message back touches only the phone unless a relay holds it`() {
+ assertTrue(discardsOnPhone(null, SendStatus.Waiting))
+ assertTrue(discardsOnPhone("https://api.codync.dev", SendStatus.Held))
+ assertFalse(discardsOnPhone("https://api.codync.dev", SendStatus.Waiting))
}
@Test fun `with a relay or a refusal a message that can't go fails`() {
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt
index d0d00636..06a2d6e1 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt
@@ -123,8 +123,9 @@ private fun isImageName(name: String) = name.substringAfterLast('.', "").lowerca
/** Unicode control and format characters, which a file name may not contain. */
private val CONTROLS = setOf(Character.CONTROL, Character.FORMAT)
+/** [Waiting]: in the relay's mailbox. [Held]: on this phone, until the computer can be reached. */
@Serializable
-enum class SendStatus { Sending, Waiting, Delivering, Failed }
+enum class SendStatus { Sending, Waiting, Delivering, Failed, Held }
@Serializable
data class PendingSend(
diff --git a/apps/desktop/e2e/optional-sign-in.spec.ts b/apps/desktop/e2e/optional-sign-in.spec.ts
index 2be54b7e..4a7255f1 100644
--- a/apps/desktop/e2e/optional-sign-in.spec.ts
+++ b/apps/desktop/e2e/optional-sign-in.spec.ts
@@ -1,12 +1,21 @@
import { test, expect, type Page } from '@playwright/test'
import type { CloudStatus } from '../src/shared/models.ts'
import { pairAsSignedOutPhone } from './phone.ts'
-import { api, attach, openGeneralSettings, sandbox, setPref } from './sandbox.ts'
+import { api, attach, freezeHost, openGeneralSettings, sandbox, setPref } from './sandbox.ts'
// docs/plans/optional-sign-in.md.
const status = (page: Page) => api<CloudStatus>(page, 'cloudStatus', {})
const owner = async (page: Page) => (await status(page)).owner?.userId ?? null
+const devices = async (page: Page) => (await api<{ devices: { name: string; key: string }[] }>(page, 'devices', {})).devices
+
+/** Asks the computer to let in a phone with no account, under `name`. */
+const pair = async (page: Page, name: string) => {
+ const { pairingUrl } = await api<{ pairingUrl: string }>(page, 'pairing', {})
+ const { computerId } = await api<{ computerId: string }>(page, 'hello', {})
+ const code = new URL(pairingUrl).searchParams.get('code') as string
+ return pairAsSignedOutPhone(sandbox().port, computerId, code, name)
+}
/** As on an identity this app never saw or kept out of an account. */
const forgetChoices = (page: Page) =>
@@ -20,28 +29,21 @@ const forgetChoices = (page: Page) =>
test('a phone with no account is asked about, on a computer in no account', async () => {
const { browser, page } = await attach()
const dialog = page.getByRole('alertdialog')
- const devices = async () => (await api<{ devices: { name: string; key: string }[] }>(page, 'devices', {})).devices
- const pair = async (name: string) => {
- const { pairingUrl } = await api<{ pairingUrl: string }>(page, 'pairing', {})
- const { computerId } = await api<{ computerId: string }>(page, 'hello', {})
- const code = new URL(pairingUrl).searchParams.get('code') as string
- return pairAsSignedOutPhone(sandbox().port, computerId, code, name)
- }
try {
test.skip((await owner(page)) !== null, 'Needs a computer in no account: `npm run dev -- --cdp`, without `--cloud`.')
- const refused = pair('Stranger phone')
+ const refused = pair(page, 'Stranger phone')
await expect(dialog.getByRole('heading', { name: 'Let Stranger phone in?' })).toBeVisible()
await expect(dialog.getByText(/It can connect only over Wi-Fi or Tailscale/)).toBeVisible()
await expect(dialog.getByRole('button', { name: 'Add to account' })).toHaveCount(0)
await dialog.getByRole('button', { name: "Don't allow" }).click()
expect((await refused).err?.status).toBe(403)
- const allowed = pair('E2E phone')
+ const allowed = pair(page, 'E2E phone')
await expect(dialog.getByRole('heading', { name: 'Let E2E phone in?' })).toBeVisible()
await dialog.getByRole('button', { name: 'Let in' }).click()
expect((await allowed).ok).toBeTruthy()
- const phone = (await devices()).find((device) => device.name === 'E2E phone')
+ const phone = (await devices(page)).find((device) => device.name === 'E2E phone')
expect(phone).toBeTruthy()
await api(page, 'revokeDevice', { key: phone?.key })
} finally {
@@ -81,11 +83,13 @@ test('the welcome lets you go on without an account, and it stays that way', asy
})
test('signed in, a computer in no account is asked about once, and Add to account asks again', async () => {
- // Leaving an account and joining one each wait on the dev cloud.
- test.setTimeout(180_000)
+ // Leaving an account and joining one each wait on the dev cloud; a host that doesn't answer takes its 20 seconds.
+ test.setTimeout(210_000)
const { browser, page } = await attach()
const prompt = page.getByRole('alertdialog')
const question = prompt.getByRole('heading', { name: 'Add this computer to your account?' })
+ const add = prompt.getByRole('button', { name: 'Add to account' })
+ const removes = prompt.getByText(/These phones lose access and must pair again: .*Joining phone\./)
const started = await status(page)
const on = await api<CloudStatus>(page, 'setCloud', { enabled: true })
if (!on.enabled) await browser.close()
@@ -93,10 +97,15 @@ test('signed in, a computer in no account is asked about once, and Add to accoun
try {
if (on.owner) await api(page, 'unclaim', {})
await expect.poll(() => owner(page), { timeout: 30_000 }).toBeNull()
+ const joining = pair(page, 'Joining phone')
+ await prompt.getByRole('button', { name: 'Let in' }).click()
+ expect((await joining).ok).toBeTruthy()
await forgetChoices(page)
await page.reload()
await expect(question).toBeVisible({ timeout: 20_000 })
+ await expect(removes).toBeVisible()
+ await expect(add).toBeEnabled()
await prompt.getByRole('button', { name: 'Not now' }).click()
await expect(prompt).toHaveCount(0)
expect(await owner(page)).toBeNull()
@@ -108,11 +117,30 @@ test('signed in, a computer in no account is asked about once, and Add to accoun
await page.getByRole('dialog').getByRole('button', { name: 'Computers', exact: true }).click()
await expect(page.getByText('Not in an account: only Wi-Fi and Tailscale reach it.')).toBeVisible()
+ // Windows has no signal that freezes a process.
+ if (process.platform !== 'win32') {
+ // A computer that doesn't answer: nothing to agree to yet, then a warning that can't name anyone.
+ const thaw = freezeHost()
+ try {
+ await page.getByRole('button', { name: 'Add to account' }).click()
+ await expect(question).toBeVisible()
+ await expect(add).toBeDisabled()
+ await expect(prompt.getByText('Phones paired without this account lose access and must pair again.')).toBeVisible({ timeout: 30_000 })
+ await expect(add).toBeEnabled()
+ } finally {
+ thaw()
+ }
+ await prompt.getByRole('button', { name: 'Not now' }).click()
+ await expect(prompt).toHaveCount(0)
+ }
+
await page.getByRole('button', { name: 'Add to account' }).click()
await expect(question).toBeVisible()
- await prompt.getByRole('button', { name: 'Add to account' }).click()
+ await expect(removes).toBeVisible()
+ await add.click()
await expect(prompt).toHaveCount(0)
await expect.poll(() => owner(page), { timeout: 60_000 }).not.toBeNull()
+ await expect.poll(async () => (await devices(page)).map((device) => device.name)).not.toContain('Joining phone')
} finally {
if (!started.owner && (await owner(page).catch(() => null))) await api(page, 'unclaim', {}).catch(() => {})
await api(page, 'setCloud', { enabled: started.enabled }).catch(() => {})
diff --git a/apps/desktop/e2e/sandbox.ts b/apps/desktop/e2e/sandbox.ts
index 896bdeda..b14696d8 100644
--- a/apps/desktop/e2e/sandbox.ts
+++ b/apps/desktop/e2e/sandbox.ts
@@ -1,4 +1,5 @@
import { chromium, type Browser, type Page } from '@playwright/test'
+import { execFileSync } from 'node:child_process'
import { readFileSync } from 'node:fs'
import { homedir } from 'node:os'
import { basename, join, resolve } from 'node:path'
@@ -23,6 +24,13 @@ export function sandbox() {
return { name, port, cdp: port + 10000 }
}
+/** Freezes the sandbox host, still connected and answering nothing, until the function it returns. Not on Windows. */
+export function freezeHost() {
+ const pid = Number(execFileSync('lsof', ['-t', '-sTCP:LISTEN', `-iTCP:${sandbox().port}`], { encoding: 'utf8' }).trim())
+ process.kill(pid, 'SIGSTOP')
+ return () => process.kill(pid, 'SIGCONT')
+}
+
/** Attaches to the sandbox app's main window over the DevTools protocol. */
export async function attach(): Promise<{ browser: Browser; page: Page }> {
const { cdp } = sandbox()
diff --git a/apps/desktop/src/renderer/components/Overlay.tsx b/apps/desktop/src/renderer/components/Overlay.tsx
index 481bf6ec..f8de1992 100644
--- a/apps/desktop/src/renderer/components/Overlay.tsx
+++ b/apps/desktop/src/renderer/components/Overlay.tsx
@@ -164,6 +164,7 @@ export function Sheet({ open, onClose, width, height, maxHeight, dismissOnDim =
export interface DialogAction {
title: string
destructive?: boolean
+ disabled?: boolean
action: () => void
}
@@ -214,6 +215,7 @@ export function Dialog({ open, title, message, actions, cancel = 'Cancel', onCan
<button
key={a.title}
className={`dialog-button ${a.destructive ? 'destructive' : 'prominent'}`}
+ disabled={a.disabled}
onClick={() => {
onClose()
a.action()
diff --git a/apps/desktop/src/renderer/components/overlay.css b/apps/desktop/src/renderer/components/overlay.css
index 7bb42180..3dd17fbd 100644
--- a/apps/desktop/src/renderer/components/overlay.css
+++ b/apps/desktop/src/renderer/components/overlay.css
@@ -192,10 +192,13 @@
background: var(--danger-fill);
color: var(--on-danger);
}
-.dialog-button:active {
+.dialog-button:active:not(:disabled) {
transform: scale(0.98);
opacity: 0.85;
}
+.dialog-button:disabled {
+ opacity: 0.4;
+}
/* Floating layers cover the title bar's drag regions (sidebar header, thread chrome), which
would turn clicks on them into window drags. A menu takes the whole window, so a click
diff --git a/apps/desktop/src/renderer/lib/account-copy.test.ts b/apps/desktop/src/renderer/lib/account-copy.test.ts
index daba1615..a4410ef5 100644
--- a/apps/desktop/src/renderer/lib/account-copy.test.ts
+++ b/apps/desktop/src/renderer/lib/account-copy.test.ts
@@ -47,6 +47,7 @@ test('the answers offered follow what the host says the phone may get', () => {
test('the phones a join removes follow what it says', () => {
assert.equal(withJoinRemoves(tr, 'Add it?', []), 'Add it?')
assert.equal(withJoinRemoves(tr, 'Add it?', ['Old']), 'Add it? These phones lose access and must pair again: Old.')
+ assert.equal(withJoinRemoves(tr, 'Add it?', null), 'Add it? Phones paired without this account lose access and must pair again.')
})
test('a phone without an email is a Codync account, and names keep their braces', () => {
diff --git a/apps/desktop/src/renderer/lib/account-copy.ts b/apps/desktop/src/renderer/lib/account-copy.ts
index baf88b00..ce1ab53d 100644
--- a/apps/desktop/src/renderer/lib/account-copy.ts
+++ b/apps/desktop/src/renderer/lib/account-copy.ts
@@ -12,9 +12,9 @@ export function joinRemovesText(tr: Tr, names: readonly string[] | null | undefi
return names?.length ? fill(tr('These phones lose access and must pair again: {names}.'), { names: names.join(', ') }) : ''
}
-/** `text`, then the phones a join removes. */
+/** `text`, then the phones a join removes. `null`: the computer couldn't say, so the warning stays general. */
export const withJoinRemoves = (tr: Tr, text: string, names: readonly string[] | null | undefined) =>
- [text, joinRemovesText(tr, names)].filter(Boolean).join(' ')
+ [text, names === null ? tr('Phones paired without this account lose access and must pair again.') : joinRemovesText(tr, names)].filter(Boolean).join(' ')
/**
* A phone scanned a computer in no account, or a paired phone asks to add it to its account. A signed-in phone may
diff --git a/apps/desktop/src/renderer/store/cloud.ts b/apps/desktop/src/renderer/store/cloud.ts
index 75c3b489..7f1e4c84 100644
--- a/apps/desktop/src/renderer/store/cloud.ts
+++ b/apps/desktop/src/renderer/store/cloud.ts
@@ -241,15 +241,15 @@ export class CloudModel extends Observable {
analytics.track({ event: 'join_offer_answered', outcome: joined ? 'added' : 'failed' })
}
- /** The phones `store`'s computer would remove by joining the signed-in account. A host before this method removes the same phones and can't name them. */
- joinWouldRemove = async (store: BotStore): Promise<string[]> => {
+ /** The phones `store`'s computer would remove by joining the signed-in account. `null`: it couldn't say. A host before this method removes the same phones and can't name them. */
+ joinWouldRemove = async (store: BotStore): Promise<string[] | null> => {
const userId = this.userId
if (!userId) return []
try {
return (await (await store.ready()).call<{ names: string[] }>('joinWouldRemove', { userId })).names
} catch (error) {
this.fail(error, true)
- return []
+ return null
}
}
diff --git a/apps/desktop/src/renderer/views/JoinAccountPrompt.tsx b/apps/desktop/src/renderer/views/JoinAccountPrompt.tsx
index 43a23585..5c5672f0 100644
--- a/apps/desktop/src/renderer/views/JoinAccountPrompt.tsx
+++ b/apps/desktop/src/renderer/views/JoinAccountPrompt.tsx
@@ -29,7 +29,8 @@ export function JoinAccountPrompt() {
cancel={null}
actions={store ? [
{ title: 'Not now', action: () => app.cloud.declineJoin(store) },
- { title: 'Add to account', action: () => void app.cloud.acceptJoin(store) },
+ // Not before it says which phones this removes.
+ { title: 'Add to account', disabled: names === undefined, action: () => void app.cloud.acceptJoin(store) },
] : []}
onClose={() => {}}
/>
diff --git a/apps/desktop/src/renderer/views/settings/ComputersView.tsx b/apps/desktop/src/renderer/views/settings/ComputersView.tsx
index 81d4802d..4775fd65 100644
--- a/apps/desktop/src/renderer/views/settings/ComputersView.tsx
+++ b/apps/desktop/src/renderer/views/settings/ComputersView.tsx
@@ -289,7 +289,8 @@ function ManagedComputerCard({ store, ssh: overSSH, nested = false }: { store: B
title={tr('Add {name} to your account first').replaceAll('{name}', () => name)}
message={withJoinRemoves(tr, tr('Your phone reaches {name} from anywhere through your account. Adding it also turns this on.').replaceAll('{name}', () => name), joinRemoves)}
actions={[
- { title: 'Add to account', action: () => void run(() => app.cloud.addFromReach(store)) },
+ // Not before it says which phones this removes.
+ { title: 'Add to account', disabled: joinRemoves === undefined, action: () => void run(() => app.cloud.addFromReach(store)) },
{ title: 'Use your own relay', action: () => void run(() => app.cloud.useOwnRelay(store)) },
]}
onCancel={() => analytics.track({ event: 'reach_account_answered', outcome: 'cancelled' })}
diff --git a/apps/desktop/src/renderer/views/use-join-removes.ts b/apps/desktop/src/renderer/views/use-join-removes.ts
index c9b0d94b..7f371895 100644
--- a/apps/desktop/src/renderer/views/use-join-removes.ts
+++ b/apps/desktop/src/renderer/views/use-join-removes.ts
@@ -2,11 +2,12 @@ import { useEffect, useState } from 'react'
import type { BotStore } from '../store/bot-store'
import { useApp } from '../store/context'
-/** What `load` answers about `store`, while `open`. */
-function useNames(load: (store: BotStore) => Promise<string[]>, store: BotStore | null, open: boolean) {
- const [names, setNames] = useState<string[]>([])
+/** What `load` answers about `store`, while `open`; `undefined` until it has. */
+function useNames(load: (store: BotStore) => Promise<string[] | null>, store: BotStore | null, open: boolean) {
+ const [names, setNames] = useState<string[] | null>()
useEffect(() => {
- if (!open || !store) return setNames([])
+ setNames(undefined)
+ if (!open || !store) return
let current = true
void load(store).then((found) => current && setNames(found))
return () => {
@@ -16,7 +17,7 @@ function useNames(load: (store: BotStore) => Promise<string[]>, store: BotStore
return names
}
-/** The names of the phones `store`'s computer would remove by joining the signed-in account, while `open`. */
+/** The names of the phones `store`'s computer would remove by joining the signed-in account, while `open`; `null`: it couldn't say. */
export function useJoinRemoves(store: BotStore | null, open: boolean) {
const { cloud } = useApp()
return useNames(cloud.joinWouldRemove, store, open)
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift b/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift
index 560f7a93..7280f3cd 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift
@@ -19,7 +19,7 @@ public struct EntryData: Codable, Hashable, Sendable {
public var addFallback: Bool?
public var text: String?
public var final: Bool?
- /// user: queued | sent | cancelled | failed · tool: pending | in_progress | completed | failed · permission: pending | answered | cancelled | expired
+ /// user: queued | sent | cancelled | failed, and before the computer has it: sending | waiting (in the relay) | held (on this phone) | delivering · tool: pending | in_progress | completed | failed · permission: pending | answered | cancelled | expired
public var status: String?
/// user: taken back while it waited (`unqueue`): it never went out, and no view reads it (`BotStore.chat`).
public var removed: Bool?
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
index 0bf25232..0ec50a27 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
@@ -1880,5 +1880,6 @@
"This account already has its own key on this phone. Scan the code of each computer you paired without an account again; your messages are kept.": "Dieses Konto hat auf diesem Telefon bereits einen eigenen Schlüssel. Scanne den Code jedes Computers erneut, den du ohne Konto gekoppelt hast. Deine Nachrichten bleiben erhalten.",
"{email} wants to use this computer, which then joins {email}'s account.": "{email} möchte diesen Computer verwenden, der dann dem Konto von {email} beitritt.",
"Sign in there with {email} and add it to your account, and it shows up here.": "Melde dich dort mit {email} an und füge ihn deinem Konto hinzu, dann erscheint er hier.",
- "Scan with the Codync app or the iPhone Camera.": "Scanne mit der Codync-App oder der iPhone-Kamera."
+ "Scan with the Codync app or the iPhone Camera.": "Scanne mit der Codync-App oder der iPhone-Kamera.",
+ "Phones paired without this account lose access and must pair again.": "Nicht mit diesem Konto gekoppelte Telefone verlieren den Zugriff und müssen neu gekoppelt werden."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
index 7a950501..ff85b4d9 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
@@ -1880,5 +1880,6 @@
"This account already has its own key on this phone. Scan the code of each computer you paired without an account again; your messages are kept.": "Esta cuenta ya tiene su propia clave en este teléfono. Vuelve a escanear el código de cada ordenador que emparejaste sin cuenta; tus mensajes se conservan.",
"{email} wants to use this computer, which then joins {email}'s account.": "{email} quiere usar este ordenador, que luego se une a la cuenta de {email}.",
"Sign in there with {email} and add it to your account, and it shows up here.": "Inicia sesión allí con {email} y añádelo a tu cuenta, y aparecerá aquí.",
- "Scan with the Codync app or the iPhone Camera.": "Escanea con la app de Codync o la cámara del iPhone."
+ "Scan with the Codync app or the iPhone Camera.": "Escanea con la app de Codync o la cámara del iPhone.",
+ "Phones paired without this account lose access and must pair again.": "Los teléfonos emparejados sin esta cuenta pierden el acceso y deben emparejarse de nuevo."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
index 5dd74700..e2fab904 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
@@ -1880,5 +1880,6 @@
"This account already has its own key on this phone. Scan the code of each computer you paired without an account again; your messages are kept.": "Ce compte a déjà sa propre clé sur ce téléphone. Scannez à nouveau le code de chaque ordinateur jumelé sans compte ; vos messages sont conservés.",
"{email} wants to use this computer, which then joins {email}'s account.": "{email} veut utiliser cet ordinateur, qui rejoint alors le compte de {email}.",
"Sign in there with {email} and add it to your account, and it shows up here.": "Connectez-vous-y avec {email} et ajoutez-le à votre compte : il apparaîtra ici.",
- "Scan with the Codync app or the iPhone Camera.": "Scannez avec l'app Codync ou l'appareil photo de l'iPhone."
+ "Scan with the Codync app or the iPhone Camera.": "Scannez avec l'app Codync ou l'appareil photo de l'iPhone.",
+ "Phones paired without this account lose access and must pair again.": "Les téléphones jumelés sans ce compte perdent l'accès et devront être jumelés à nouveau."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json
index 2e6893ad..62fa6085 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json
@@ -1880,5 +1880,6 @@
"This account already has its own key on this phone. Scan the code of each computer you paired without an account again; your messages are kept.": "Questo account ha già una propria chiave su questo telefono. Scansiona di nuovo il codice di ogni computer associato senza account; i tuoi messaggi restano.",
"{email} wants to use this computer, which then joins {email}'s account.": "{email} vuole usare questo computer, che poi entra nell'account di {email}.",
"Sign in there with {email} and add it to your account, and it shows up here.": "Accedi lì con {email} e aggiungilo al tuo account: comparirà qui.",
- "Scan with the Codync app or the iPhone Camera.": "Scansiona con l'app Codync o la fotocamera dell'iPhone."
+ "Scan with the Codync app or the iPhone Camera.": "Scansiona con l'app Codync o la fotocamera dell'iPhone.",
+ "Phones paired without this account lose access and must pair again.": "I telefoni associati senza questo account perdono l'accesso e devono essere associati di nuovo."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
index 49602de3..66c6b9cd 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
@@ -1880,5 +1880,6 @@
"This account already has its own key on this phone. Scan the code of each computer you paired without an account again; your messages are kept.": "このアカウントはこの電話に独自のキーを持っています。アカウントなしでペアリングした各コンピュータのコードをもう一度スキャンしてください。メッセージは保持されます。",
"{email} wants to use this computer, which then joins {email}'s account.": "{email} がこのコンピュータを使おうとしています。このコンピュータは {email} のアカウントに参加します。",
"Sign in there with {email} and add it to your account, and it shows up here.": "そこで {email} でサインインしてアカウントに追加すると、ここに表示されます。",
- "Scan with the Codync app or the iPhone Camera.": "Codync アプリまたは iPhone のカメラでスキャンしてください。"
+ "Scan with the Codync app or the iPhone Camera.": "Codync アプリまたは iPhone のカメラでスキャンしてください。",
+ "Phones paired without this account lose access and must pair again.": "このアカウントでペアリングしていないスマートフォンはアクセスを失い、再度ペアリングが必要です。"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
index b6e9e33a..66f78a49 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
@@ -1880,5 +1880,6 @@
"This account already has its own key on this phone. Scan the code of each computer you paired without an account again; your messages are kept.": "이 계정은 이 휴대폰에 자체 키가 이미 있습니다. 계정 없이 페어링한 각 컴퓨터의 코드를 다시 스캔하세요. 메시지는 유지됩니다.",
"{email} wants to use this computer, which then joins {email}'s account.": "{email}이(가) 이 컴퓨터를 사용하려고 합니다. 컴퓨터는 {email} 계정에 참여합니다.",
"Sign in there with {email} and add it to your account, and it shows up here.": "거기서 {email}(으)로 로그인하고 계정에 추가하면 여기에 표시됩니다.",
- "Scan with the Codync app or the iPhone Camera.": "Codync 앱 또는 iPhone 카메라로 스캔하세요."
+ "Scan with the Codync app or the iPhone Camera.": "Codync 앱 또는 iPhone 카메라로 스캔하세요.",
+ "Phones paired without this account lose access and must pair again.": "이 계정으로 페어링하지 않은 휴대폰은 접근 권한을 잃으며 다시 페어링해야 합니다."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json
index 97b57c47..94a2da4b 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json
@@ -1880,5 +1880,6 @@
"This account already has its own key on this phone. Scan the code of each computer you paired without an account again; your messages are kept.": "Esta conta já tem a própria chave neste celular. Escaneie de novo o código de cada computador que você pareou sem conta; suas mensagens são mantidas.",
"{email} wants to use this computer, which then joins {email}'s account.": "{email} quer usar este computador, que depois entra na conta de {email}.",
"Sign in there with {email} and add it to your account, and it shows up here.": "Entre lá com {email} e adicione-o à sua conta, e ele aparece aqui.",
- "Scan with the Codync app or the iPhone Camera.": "Escaneie com o app Codync ou a câmera do iPhone."
+ "Scan with the Codync app or the iPhone Camera.": "Escaneie com o app Codync ou a câmera do iPhone.",
+ "Phones paired without this account lose access and must pair again.": "Celulares pareados sem esta conta perdem o acesso e precisam parear de novo."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json
index ad8ad218..2fb80745 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json
@@ -1880,5 +1880,6 @@
"This account already has its own key on this phone. Scan the code of each computer you paired without an account again; your messages are kept.": "У этого аккаунта уже есть свой ключ на этом телефоне. Снова отсканируйте код каждого компьютера, сопряжённого без аккаунта; ваши сообщения сохранятся.",
"{email} wants to use this computer, which then joins {email}'s account.": "{email} хочет использовать этот компьютер, который затем присоединится к аккаунту {email}.",
"Sign in there with {email} and add it to your account, and it shows up here.": "Войдите там как {email} и добавьте его в аккаунт: он появится здесь.",
- "Scan with the Codync app or the iPhone Camera.": "Отсканируйте в приложении Codync или камерой iPhone."
+ "Scan with the Codync app or the iPhone Camera.": "Отсканируйте в приложении Codync или камерой iPhone.",
+ "Phones paired without this account lose access and must pair again.": "Телефоны, сопряжённые без этого аккаунта, потеряют доступ, и их нужно будет сопрячь заново."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
index 2a42c953..9f53cd77 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
@@ -1880,5 +1880,6 @@
"This account already has its own key on this phone. Scan the code of each computer you paired without an account again; your messages are kept.": "这个账户在这部手机上已有自己的密钥。请重新扫描每台未登录时配对的电脑的二维码;消息会保留。",
"{email} wants to use this computer, which then joins {email}'s account.": "{email} 想使用这台电脑,电脑随后会加入 {email} 的账户。",
"Sign in there with {email} and add it to your account, and it shows up here.": "在那里用 {email} 登录并将电脑加入账户,它就会显示在这里。",
- "Scan with the Codync app or the iPhone Camera.": "用 Codync App 或 iPhone 相机扫描。"
+ "Scan with the Codync app or the iPhone Camera.": "用 Codync App 或 iPhone 相机扫描。",
+ "Phones paired without this account lose access and must pair again.": "未用此账户配对的手机将失去访问权限,必须重新配对。"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
index d7904a96..ed6ab2cc 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
@@ -1880,5 +1880,6 @@
"This account already has its own key on this phone. Scan the code of each computer you paired without an account again; your messages are kept.": "這個賬戶在這支手機上已有自己的金鑰。請重新掃描每台未登入時配對的電腦的 QR 碼;訊息會保留。",
"{email} wants to use this computer, which then joins {email}'s account.": "{email} 想使用這台電腦,電腦隨後會加入 {email} 的賬戶。",
"Sign in there with {email} and add it to your account, and it shows up here.": "在那裡用 {email} 登入並將電腦加入賬戶,它就會顯示在這裡。",
- "Scan with the Codync app or the iPhone Camera.": "用 Codync App 或 iPhone 相機掃描。"
+ "Scan with the Codync app or the iPhone Camera.": "用 Codync App 或 iPhone 相機掃描。",
+ "Phones paired without this account lose access and must pair again.": "未用此賬戶配對的手機將失去存取權,必須重新配對。"
}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Cache.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Cache.swift
index 83a7df19..76f707f7 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Cache.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Cache.swift
@@ -28,10 +28,19 @@ extension BotStore {
hostId = cache.hostId
rev = cache.rev
bots = Dictionary(cache.bots.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })
- entries = Dictionary(grouping: cache.entries, by: \.botId)
+ entries = Dictionary(grouping: cache.entries.map(Self.afterRelaunch), by: \.botId)
applyIcons(cache.icons ?? [:])
}
+ /// A message on its way when the app went may or may not have arrived: failed, with a Resend that reuses its nonce.
+ /// If the computer got it, the events catch-up replaces it by clientNonce.
+ private static func afterRelaunch(_ entry: Entry) -> Entry {
+ guard entry.id.hasPrefix("local-"), entry.data.status == "sending" else { return entry }
+ var entry = entry
+ entry.data.status = "failed"
+ return entry
+ }
+
func scheduleSave() {
guard !retired else { return }
saveTask?.cancel()
@@ -43,11 +52,11 @@ extension BotStore {
public func saveCache() {
guard !retired else { return }
- // Keep the newest 200 entries per bot; older ones page in from the host. Local queued and
- // failed messages stay visible so they can be cancelled or retried after a relaunch.
+ // Keep the newest 200 entries per bot; older ones page in from the host. Local messages the
+ // computer may not have stay visible so they can be cancelled or retried after a relaunch.
let kept = entries.values.flatMap { list in
list.filter { !$0.id.hasPrefix("local-") }.suffix(200)
- + list.filter { $0.id.hasPrefix("local-") && ["waiting", "delivering", "failed"].contains($0.data.status) }
+ + list.filter { $0.id.hasPrefix("local-") && ["sending", "waiting", "held", "delivering", "failed"].contains($0.data.status) }
}
let cachedBots = bots.values.map { bot in var bot = bot; bot.customIcon = nil; return bot }
let cache = Cache(stamp: "\(Self.appBuild)/\(hello?.version ?? "")", hostId: hostId, rev: rev, bots: cachedBots, entries: kept, icons: icons)
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Connection.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Connection.swift
index 79f29ce7..cb38e09d 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Connection.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Connection.swift
@@ -216,12 +216,15 @@ extension BotStore {
Task { [weak self] in
for await computer in updates {
guard let self, !self.retired else { return }
+ let hadRelay = self.computer.cloud != nil
// The transport's copy of this device's picks may be older.
self.updateComputer { current in
var next = computer
next.keepDevicePicks(from: current)
current = next
}
+ // The relay it had was the only one to ask about what it held.
+ if hadRelay, self.computer.cloud == nil { await self.reconcileQueued(remote) }
}
}
Task { [weak self] in
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sending.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sending.swift
index 764f0cb5..56396e2b 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sending.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sending.swift
@@ -127,7 +127,7 @@ extension BotStore {
if outgoingFiles[nonce] != nil { lastError = "Couldn't send the files: \(error.localizedDescription)" }
// With no relay holding it, a message waits here until the computer can be reached (`sendHeld`).
let holds = computer.cloud == nil && (error as? HostError)?.isTransient == true
- markLocal(nonce: nonce, botId: botId, status: holds ? "waiting" : "failed")
+ markLocal(nonce: nonce, botId: botId, status: holds ? "held" : "failed")
return holds ? .queued : .failed
}
}
@@ -188,7 +188,7 @@ extension BotStore {
/// Takes a waiting message back out of the mailbox, unless the computer already has it.
public func cancelQueued(_ entry: Entry) {
- if computer.cloud == nil {
+ if computer.cloud == nil || entry.data.status == "held" {
// No relay holds it: it only waits on this phone.
discard(entry)
if let bot = bots[entry.botId] { onSent?(bot, .cancelled) }
@@ -224,21 +224,24 @@ extension BotStore {
/// "Failed" is safe even if one was delivered: the events catch-up replaces it by clientNonce,
/// and a resend reuses that nonce, so the computer never runs it twice.
func reconcileQueued(_ remote: any RemoteTransport) async {
- let waiting = entries.values.flatMap { $0 }.filter { $0.data.status == "waiting" }
- guard !waiting.isEmpty else { return }
- guard computer.cloud != nil else { return sendHeld(waiting) }
- let heldItems: [QueuedItem]
+ let local = entries.values.flatMap { $0 }
+ // What waits on this phone goes now, also when the computer has joined an account since. With no relay
+ // now, what a relay held can't be asked about: it goes with the same nonce too.
+ sendHeld(local.filter { $0.data.status == "held" || ($0.data.status == "waiting" && computer.cloud == nil) })
+ let waiting = local.filter { $0.data.status == "waiting" }
+ guard computer.cloud != nil, !waiting.isEmpty else { return }
+ let relayItems: [QueuedItem]
do {
- heldItems = try await remote.listQueued()
+ relayItems = try await remote.listQueued()
} catch {
log.debug("mailbox reconciliation deferred: \(error.localizedDescription)")
return
}
- let held = Dictionary(heldItems.map { ($0.nonce, $0.state) }, uniquingKeysWith: { a, _ in a })
+ let inRelay = Dictionary(relayItems.map { ($0.nonce, $0.state) }, uniquingKeysWith: { a, _ in a })
guard !retired else { return }
for e in waiting {
guard let nonce = e.data.clientNonce else { continue }
- switch held[nonce] {
+ switch inRelay[nonce] {
case "queued": break
case .some: markLocal(nonce: nonce, botId: e.botId, status: "delivering")
case nil: markLocal(nonce: nonce, botId: e.botId, status: "failed")
@@ -247,10 +250,11 @@ extension BotStore {
saveCache()
}
- /// The computer is back, and it has no relay: what waited on this phone goes now, with the same nonces. Files are
+ /// The computer is back: what waited on this phone goes now, with the same nonces. Files are
/// kept only in memory: a message whose files went with the app stays for the user to resend, not half sent.
- private func sendHeld(_ waiting: [Entry]) {
- for entry in waiting.sorted(by: { $0.createdAt < $1.createdAt }) {
+ private func sendHeld(_ held: [Entry]) {
+ guard !held.isEmpty else { return }
+ for entry in held.sorted(by: { $0.createdAt < $1.createdAt }) {
let filesGone = entry.data.attachments?.isEmpty == false && entry.data.clientNonce.flatMap { outgoingFiles[$0] } == nil
if filesGone, let nonce = entry.data.clientNonce {
markLocal(nonce: nonce, botId: entry.botId, status: "failed")
diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift
index ff5dabac..bf5df8c6 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift
@@ -165,7 +165,7 @@ struct UserBubble: View {
.font(.caption2.bold())
case "cancelled":
Text(L10n.tr("Not sent — stopped")).font(.caption2).foregroundStyle(Palette.tertiary)
- case "waiting":
+ case "waiting", "held":
HStack(spacing: 10) {
Text(L10n.tr("Waiting for the computer to come online")).foregroundStyle(Palette.tertiary)
Button(L10n.tr("Cancel"), systemImage: "xmark.circle") { model.cancelQueued(entry) }
diff --git a/apps/ios/Kit/Tests/CodyncUITests/HeldMessageTests.swift b/apps/ios/Kit/Tests/CodyncUITests/HeldMessageTests.swift
new file mode 100644
index 00000000..f0654e02
--- /dev/null
+++ b/apps/ios/Kit/Tests/CodyncUITests/HeldMessageTests.swift
@@ -0,0 +1,183 @@
+import Foundation
+import Testing
+@testable import CodyncKit
+@testable import CodyncUI
+
+/// A computer in no account has no relay: the phone holds the message, and sends it when the computer is back.
+/// Each try at reaching it makes a new link; the computer's back on the latest (`back`).
+@MainActor private final class NoRelay {
+ let (storage, suite) = context()
+ private(set) var links: [FakeRemote] = []
+ private var state = LinkState.failed("Can't reach your computer.")
+ private(set) lazy var store: BotStore = {
+ var computer = randomComputer("Mac")
+ computer.cloud = nil
+ return BotStore(computer: computer, storage: storage) { [unowned self] _ in
+ let link = FakeRemote(state)
+ links.append(link)
+ return link
+ }
+ }()
+
+ func start() async {
+ store.setActive(true)
+ #expect(await until { store.isOffline })
+ }
+
+ func back() async {
+ state = .ready(.direct)
+ guard let link = links.last else { return }
+ await link.set(state)
+ #expect(await until { await link.subscribed })
+ await link.emit(botEvent("b1", name: "Bot", rev: 1))
+ }
+
+ func sent() async -> [String] {
+ var all: [String] = []
+ for link in links { all += await link.sent }
+ return all
+ }
+
+ func end() {
+ store.retire()
+ UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite)
+ }
+}
+
+@MainActor @Test func withNoRelayAMessageWaitsOnThePhoneAndGoesWithTheSameNonce() async throws {
+ let phone = NoRelay()
+ defer { phone.end() }
+ await phone.start()
+ let store = phone.store
+ #expect(store.holdsOnPhone && !store.canQueue)
+
+ store.send("hi", to: "b1")
+ #expect(await until { store.chat("b1").first?.data.status == "held" })
+ let nonce = try #require(store.chat("b1").first?.data.clientNonce)
+ let enqueued = await phone.links.last?.enqueued
+ #expect(enqueued?.isEmpty == true, "there's no relay to hold it")
+
+ await phone.back()
+ #expect(await until { await phone.sent() == ["hi"] })
+ #expect(store.chat("b1").first?.data.clientNonce == nonce)
+ #expect(!store.holdsOnPhone)
+}
+
+@MainActor @Test func withNoRelayCancellingAWaitingMessageStaysOnThePhone() async throws {
+ let phone = NoRelay()
+ defer { phone.end() }
+ await phone.start()
+ let store = phone.store
+ store.send("hi", to: "b1")
+ #expect(await until { store.chat("b1").first?.data.status == "held" })
+ store.cancelQueued(try #require(store.chat("b1").first))
+ #expect(store.chat("b1").isEmpty)
+ await phone.back()
+ try await Task.sleep(for: .milliseconds(100))
+ #expect(await phone.sent().isEmpty, "a message taken back never goes")
+}
+
+@MainActor @Test func aHeldMessageWhoseFilesWentWithTheAppWaitsForTheUser() async throws {
+ let phone = NoRelay()
+ defer { phone.end() }
+ await phone.start()
+ let store = phone.store
+ var data = EntryData(text: "see this", status: "held", clientNonce: "n1")
+ data.attachments = [Attachment(id: UUID().uuidString, name: "a.txt", size: 1)]
+ store.upsert(Entry(id: "local-n1", seq: .max, botId: "b1", rev: 0, kind: "user", turn: 0, data: data, createdAt: 1, updatedAt: 0))
+ await phone.back()
+ #expect(await until { store.chat("b1").first?.data.status == "failed" })
+ #expect(await phone.sent().isEmpty, "not without its files")
+}
+
+@MainActor @Test func aResendKeepsTheCallItWasSaidIn() async throws {
+ let phone = NoRelay()
+ defer { phone.end() }
+ await phone.start()
+ let store = phone.store
+ store.send("hi", to: "b1", call: "call-1")
+ #expect(await until { store.chat("b1").first?.data.status == "held" })
+ store.retry(try #require(store.chat("b1").first))
+ #expect(store.chat("b1").first?.data.call == "call-1")
+}
+
+@MainActor @Test func aMessageHeldOnThePhoneStillGoesAfterTheComputerJoinsAnAccount() async throws {
+ let phone = NoRelay()
+ defer { phone.end() }
+ await phone.start()
+ let store = phone.store
+ store.send("hi", to: "b1")
+ #expect(await until { store.chat("b1").first?.data.status == "held" })
+ let nonce = try #require(store.chat("b1").first?.data.clientNonce)
+ store.updateComputer { $0.cloud = URL(string: "https://api.codync.dev") }
+
+ await phone.back()
+ #expect(await until { await phone.sent() == ["hi"] })
+ #expect(store.chat("b1").first?.data.clientNonce == nonce)
+ #expect(store.chat("b1").first?.data.status != "failed")
+}
+
+@MainActor @Test func aHeldMessageIsTakenBackOnThePhoneAfterTheComputerJoinsAnAccount() async throws {
+ let phone = NoRelay()
+ defer { phone.end() }
+ await phone.start()
+ let store = phone.store
+ store.send("hi", to: "b1")
+ #expect(await until { store.chat("b1").first?.data.status == "held" })
+ store.updateComputer { $0.cloud = URL(string: "https://api.codync.dev") }
+ store.cancelQueued(try #require(store.chat("b1").first))
+ #expect(store.chat("b1").isEmpty)
+}
+
+private func localEntry(_ nonce: String, status: String) -> Entry {
+ Entry(id: "local-\(nonce)", seq: .max, botId: "b1", rev: 0, kind: "user", turn: 0,
+ data: EntryData(text: "hi", status: status, clientNonce: nonce), createdAt: 1, updatedAt: 0)
+}
+
+@MainActor @Test func withNoRelayLeftWhatARelayHeldGoesWithTheSameNonce() async throws {
+ let phone = NoRelay()
+ defer { phone.end() }
+ await phone.start()
+ let store = phone.store
+ store.upsert(localEntry("n1", status: "waiting"))
+ await phone.back()
+ #expect(await until { await phone.sent() == ["hi"] })
+ #expect(store.chat("b1").first?.data.clientNonce == "n1")
+}
+
+@MainActor @Test func whatARelayHeldGoesOnceHelloSaysTheRelayIsGone() async throws {
+ let (storage, suite) = context()
+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+ let fake = FakeRemote(.hostOffline(lastSeen: nil))
+ var computer = randomComputer("Mac")
+ let store = BotStore(computer: computer, storage: storage) { _ in fake }
+ defer { store.retire() }
+ store.setActive(true)
+ #expect(await until { store.connection == .computerOffline(lastSeen: nil) })
+ store.send("hi", to: "b1")
+ #expect(await until { await fake.enqueued.count == 1 })
+ let nonce = try #require(store.chat("b1").first?.data.clientNonce)
+
+ await fake.set(.ready(.direct))
+ #expect(await until { await fake.subscribed })
+ await fake.emit(botEvent("b1", name: "Bot", rev: 1))
+ computer.cloud = nil
+ await fake.emit(computer)
+ #expect(await until { await fake.sent == ["hi"] })
+ #expect(store.chat("b1").first?.data.clientNonce == nonce)
+}
+
+@MainActor @Test func aRelaunchKeepsWhatWaitsOnThePhoneAndFailsWhatWasOnItsWay() {
+ let (storage, suite) = context()
+ defer { storage.erase(); UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+ let computer = randomComputer("Mac")
+ let before = BotStore(computer: computer, storage: storage) { _ in FakeRemote(.ready(.direct)) }
+ before.upsert(localEntry("held", status: "held"))
+ before.upsert(localEntry("sending", status: "sending"))
+ before.retire()
+
+ let after = BotStore(computer: computer, storage: storage) { _ in FakeRemote(.ready(.direct)) }
+ defer { after.retire() }
+ let statuses = Dictionary(after.chat("b1").map { ($0.id, $0.data.status) }, uniquingKeysWith: { a, _ in a })
+ #expect(statuses == ["local-held": "held", "local-sending": "failed"])
+}
diff --git a/apps/ios/Kit/Tests/CodyncUITests/StoreTestFixtures.swift b/apps/ios/Kit/Tests/CodyncUITests/StoreTestFixtures.swift
index 5b675534..b7c622b4 100644
--- a/apps/ios/Kit/Tests/CodyncUITests/StoreTestFixtures.swift
+++ b/apps/ios/Kit/Tests/CodyncUITests/StoreTestFixtures.swift
@@ -156,7 +156,16 @@ actor FakeRemote: RemoteTransport {
AsyncStream { c in Task { await self.addState(c) } }
}
- nonisolated func computerUpdates() -> AsyncStream<Computer> { AsyncStream { _ in } }
+ private var computerSinks: [AsyncStream<Computer>.Continuation] = []
+ private func addComputer(_ c: AsyncStream<Computer>.Continuation) { computerSinks.append(c) }
+ /// What the host's `hello` says about the computer, once the link is up.
+ func emit(_ computer: Computer) {
+ for s in computerSinks { s.yield(computer) }
+ }
+
+ nonisolated func computerUpdates() -> AsyncStream<Computer> {
+ AsyncStream { c in Task { await self.addComputer(c) } }
+ }
private var enqueueError: (any Error)?
/// Every later `enqueue` throws `error`.
diff --git a/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swift b/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swift
index 6dd3e3b8..1315e1ec 100644
--- a/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swift
+++ b/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swift
@@ -102,104 +102,6 @@ import Testing
#expect(await fake.sent.isEmpty)
}
-/// A computer in no account has no relay: the phone holds the message, and sends it when the computer is back.
-/// Each try at reaching it makes a new link; the computer's back on the latest (`back`).
-@MainActor private final class NoRelay {
- let (storage, suite) = context()
- private(set) var links: [FakeRemote] = []
- private var state = LinkState.failed("Can't reach your computer.")
- private(set) lazy var store: BotStore = {
- var computer = randomComputer("Mac")
- computer.cloud = nil
- return BotStore(computer: computer, storage: storage) { [unowned self] _ in
- let link = FakeRemote(state)
- links.append(link)
- return link
- }
- }()
-
- func start() async {
- store.setActive(true)
- #expect(await until { store.isOffline })
- }
-
- func back() async {
- state = .ready(.direct)
- guard let link = links.last else { return }
- await link.set(state)
- #expect(await until { await link.subscribed })
- await link.emit(botEvent("b1", name: "Bot", rev: 1))
- }
-
- func sent() async -> [String] {
- var all: [String] = []
- for link in links { all += await link.sent }
- return all
- }
-
- func end() {
- store.retire()
- UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite)
- }
-}
-
-@MainActor @Test func withNoRelayAMessageWaitsOnThePhoneAndGoesWithTheSameNonce() async throws {
- let phone = NoRelay()
- defer { phone.end() }
- await phone.start()
- let store = phone.store
- #expect(store.holdsOnPhone && !store.canQueue)
-
- store.send("hi", to: "b1")
- #expect(await until { store.chat("b1").first?.data.status == "waiting" })
- let nonce = try #require(store.chat("b1").first?.data.clientNonce)
- let enqueued = await phone.links.last?.enqueued
- #expect(enqueued?.isEmpty == true, "there's no relay to hold it")
-
- await phone.back()
- #expect(await until { await phone.sent() == ["hi"] })
- #expect(store.chat("b1").first?.data.clientNonce == nonce)
- #expect(!store.holdsOnPhone)
-}
-
-@MainActor @Test func withNoRelayCancellingAWaitingMessageStaysOnThePhone() async throws {
- let phone = NoRelay()
- defer { phone.end() }
- await phone.start()
- let store = phone.store
- store.send("hi", to: "b1")
- #expect(await until { store.chat("b1").first?.data.status == "waiting" })
- store.cancelQueued(try #require(store.chat("b1").first))
- #expect(store.chat("b1").isEmpty)
- await phone.back()
- try await Task.sleep(for: .milliseconds(100))
- #expect(await phone.sent().isEmpty, "a message taken back never goes")
-}
-
-@MainActor @Test func aHeldMessageWhoseFilesWentWithTheAppWaitsForTheUser() async throws {
- let phone = NoRelay()
- defer { phone.end() }
- await phone.start()
- let store = phone.store
- var data = EntryData(text: "see this", status: "waiting", clientNonce: "n1")
- data.attachments = [Attachment(id: UUID().uuidString, name: "a.txt", size: 1)]
- store.upsert(Entry(id: "local-n1", seq: .max, botId: "b1", rev: 0, kind: "user", turn: 0, data: data, createdAt: 1, updatedAt: 0))
- await phone.back()
- #expect(await until { store.chat("b1").first?.data.status == "failed" })
- #expect(await phone.sent().isEmpty, "not without its files")
-}
-
-@MainActor @Test func aResendKeepsTheCallItWasSaidIn() async throws {
- let phone = NoRelay()
- defer { phone.end() }
- await phone.start()
- let store = phone.store
- store.send("hi", to: "b1", call: "call-1")
- #expect(await until { store.chat("b1").first?.data.status == "waiting" })
- store.retry(try #require(store.chat("b1").first))
- #expect(store.chat("b1").first?.data.call == "call-1")
-}
-
@MainActor @Test func offlineSendsWaitInTheMailbox() async throws {
let (storage, suite) = context()
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
diff --git a/apps/maestro/held-message-delivered.yaml b/apps/maestro/held-message-delivered.yaml
new file mode 100644
index 00000000..e56741a1
--- /dev/null
+++ b/apps/maestro/held-message-delivered.yaml
@@ -0,0 +1,15 @@
+# What held-message.yaml left waiting on the phone reaches the computer once, and what it took back never does. Start the
+# sandbox again, with the app still open on that chat, and then:
+# maestro --device "<simulator udid>,<adb serial>" test --shard-all 2 --include-tags held-message-delivered \
+# -e HOST_PORT=<sandbox port> -e HOST_TOKEN="$(cat ~/.codync-dev-<sandbox name>/token)" -e BOT_ID=<the bot's id> apps/maestro
+appId: com.pokai.Codync.ios.dev
+tags:
+ - held-message-delivered
+---
+- extendedWaitUntil:
+ notVisible: "Waiting for the computer to come online"
+ timeout: 60000
+- assertVisible: "held ${maestro.platform}"
+- assertNotVisible: "take back ${maestro.platform}"
+- takeScreenshot: held-delivered
+- runScript: held-message.js
diff --git a/apps/maestro/held-message.js b/apps/maestro/held-message.js
new file mode 100644
index 00000000..9c21b0cb
--- /dev/null
+++ b/apps/maestro/held-message.js
@@ -0,0 +1,11 @@
+// Asks the host (HOST_PORT, HOST_TOKEN, BOT_ID, passed with `-e`) what reached it for held-message-delivered.yaml: this
+// phone's held message once, and nothing it took back.
+const res = http.post(`http://127.0.0.1:${HOST_PORT}/api/history`, {
+ headers: { Authorization: `Bearer ${HOST_TOKEN}`, 'Content-Type': 'application/json' },
+ body: JSON.stringify({ botId: BOT_ID, limit: 100 }),
+})
+if (res.status !== 200) throw new Error(`history: ${res.status} ${res.body}`)
+const count = (text) => json(res.body).entries.filter((entry) => entry.data.text === text).length
+const held = count(`held ${maestro.platform}`)
+const takenBack = count(`take back ${maestro.platform}`)
+if (held !== 1 || takenBack !== 0) throw new Error(`The host has the held message ${held} times and the taken back one ${takenBack} times.`)
diff --git a/apps/maestro/held-message.yaml b/apps/maestro/held-message.yaml
new file mode 100644
index 00000000..c420f7e3
--- /dev/null
+++ b/apps/maestro/held-message.yaml
@@ -0,0 +1,55 @@
+# A computer in no account has no relay, so what a phone sends while it can't reach the computer waits on the phone: it
+# can be taken back, and the rest goes when the computer is back (held-message-delivered.yaml). Pair the phone first
+# (signed-out-pairing.yaml) with a sandbox in no account (`npm run dev`, without `--cloud`), and keep the app open. With
+# the sandbox running, make a bot the phone then shows:
+# curl -H "Authorization: Bearer $(cat ~/.codync-dev-<sandbox name>/token)" -H 'Content-Type: application/json' \
+# -d '{"name":"Held check","backend":"custom","command":"python3 -X utf8 -u '"$PWD"'/host/tests/fixtures/steer_agent.py plain 1","connectors":[],"skills":[],"notify":false}' \
+# http://127.0.0.1:<sandbox port>/api/createBot
+# Stop the sandbox, and only then:
+# maestro --device "<simulator udid>,<adb serial>" test --shard-all 2 --include-tags held-message -e BOT_NAME="Held check" apps/maestro
+appId: com.pokai.Codync.ios.dev
+tags:
+ - held-message
+---
+- runFlow:
+ when:
+ platform: iOS
+ commands:
+ - launchApp:
+ appId: com.pokai.Codync.ios.dev
+ stopApp: false
+- runFlow:
+ when:
+ platform: Android
+ commands:
+ - launchApp:
+ appId: com.pokai.Codync.android.dev
+ stopApp: false
+- tapOn: ${BOT_NAME}
+# Android says it can't load the chat's history, 20 seconds after it opens.
+- runFlow:
+ when:
+ platform: Android
+ commands:
+ - extendedWaitUntil:
+ visible: "Something went wrong"
+ timeout: 30000
+ - tapOn: "OK"
+- tapOn: "Ask ${BOT_NAME}"
+- inputText: "take back ${maestro.platform}"
+- tapOn: "Send"
+# Up to how long the phone tries the computer before it holds the message.
+- extendedWaitUntil:
+ visible: "Waiting for the computer to come online"
+ timeout: 60000
+- takeScreenshot: held-take-back
+- tapOn: "Cancel|Don't send"
+- assertNotVisible: "take back ${maestro.platform}"
+- assertNotVisible: "Waiting for the computer to come online"
+- tapOn: "Ask ${BOT_NAME}"
+- inputText: "held ${maestro.platform}"
+- tapOn: "Send"
+- extendedWaitUntil:
+ visible: "Waiting for the computer to come online"
+ timeout: 60000
+- takeScreenshot: held-waiting
diff --git a/docs/architecture/connections.md b/docs/architecture/connections.md
index 18a4d79e..1976b5c3 100644
--- a/docs/architecture/connections.md
+++ b/docs/architecture/connections.md
@@ -52,7 +52,7 @@ The phone finds and pairs every computer itself. A computer the phone hasn't pai
| Away | Tap it in the account list, compare 6 digits on the computer, Allow (or **Skip the 6-digit check**) | Must already be in your account |
- The host checks a signed-in phone's account from a proof the cloud signed, never from what the phone says. The check works offline (a signature), so computers with the cloud off or on a private relay still pair in person. A phone with no proof is a signed-out phone; a proof that doesn't check out is refused, never treated as none.
-- A QR pairing records the phone's account on the computer, or that it has none. When a host changes the account it belongs to, it drops every device of another account and every phone with none, after a warning that names them.
+- A QR pairing records the phone's account on the computer, or that it has none. When a host changes the account it belongs to, it drops every device of another account and every phone with none, after a warning that names them (a general one when the host can't say).
- Joining an account on a scan is how a headless computer "signs in": there is no `codync-host login`. A computer may also join through a manager's **Add to account**, which uses the manager app's account, or later through a paired signed-in phone's **Add to account**, which asks on the computer again.
## Accounts on a phone
diff --git a/docs/plans/optional-sign-in.md b/docs/plans/optional-sign-in.md
index fe651594..3b068202 100644
--- a/docs/plans/optional-sign-in.md
+++ b/docs/plans/optional-sign-in.md
@@ -10,7 +10,7 @@ Agreed 2026-11-06, built in 2.41.0. Reverses part of [require sign-in](require-s
- **A computer in no account may have phones of different accounts.** It confirms each one.
- **TURN stays relay only.** `hostScreenIce` already requires an account and doesn't change. A direct session contacts no STUN or TURN provider ([remote screen](../features/remote-screen.md)).
- **Public webhooks need a computer in an account.**
-- **A computer that joins an account removes its signed-out phones and other accounts' phones.** A dialog warns first and names them. They pair again, signed in to that account.
+- **A computer that joins an account removes its signed-out phones and other accounts' phones.** A dialog warns first and names them; Add to account waits for the names, and a computer that can't say gets a general warning. They pair again, signed in to that account.
- **The screen follows the Connection choice:** Auto goes direct, then TURN; Cloudflare first the other way round; Wi-Fi or Tailscale only never asks. A computer in no account shows no choice.
| Phone | Computer in no account | In the phone's account | In another account |
@@ -27,7 +27,7 @@ These follow the recommendations already given. Say if one is wrong.
- Direct means anything off Codync's infrastructure: LAN, Tailscale, `CODYNC_EXTERNAL_URL`, the user's own tunnel, a private relay.
- Signing out returns to the welcome screen. The account's computers and chats stay locked, and the signed-out space is separate and starts empty.
- LAN discovery ships in the first version, because any phone of a computer in no account has no other way to find a changed address. It advertises only while the computer is in no account, so a computer in an account never needs a multicast permission.
-- A message that can't leave a phone with no relay waits there and goes when the computer is back, with the same nonce.
+- A message that can't leave a phone with no relay waits there and goes when the computer is back, with the same nonce, also if the computer has joined an account since.
## How it's built