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.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat(desktop): ask to add a computer before reaching it from anywhere
leepokai84887365a83e
diff --git a/apps/desktop/e2e/agent-logos.spec.ts b/apps/desktop/e2e/agent-logos.spec.tsindex e298a55f..206043ff 100644--- a/apps/desktop/e2e/agent-logos.spec.ts+++ b/apps/desktop/e2e/agent-logos.spec.ts@@ -1,6 +1,6 @@import { test, expect, type Page } from '@playwright/test'import type { HostSnapshot } from '../src/shared/ipc.ts'-import { attach } from './sandbox.ts'+import { attach, openGeneralSettings } from './sandbox.ts'type Bridge = {codync: {@@ -23,11 +23,6 @@ function call<T>(page: Page, method: string, body: unknown): Promise<T> {const createBot = async (page: Page, body: object) => (await call<{ bot: { id: string } }>(page, 'createBot', body)).bot.id-async function openGeneralSettings(page: Page) {- await page.locator('.sidebar-account').click()- await page.locator('.account-panel').getByText('Settings', { exact: true }).click()-}-test('bots on different agents show their logos until Show agent logos is turned off', async () => {const { browser, page } = await attach()const run = Date.now()diff --git a/apps/desktop/e2e/reach-anywhere.spec.ts b/apps/desktop/e2e/reach-anywhere.spec.tsnew file mode 100644index 00000000..b39421d4--- /dev/null+++ b/apps/desktop/e2e/reach-anywhere.spec.ts@@ -0,0 +1,97 @@+import { test, expect, type Page } from '@playwright/test'+import type { CloudStatus } from '../src/shared/models.ts'+import { api, attach, openGeneralSettings } from './sandbox.ts'++const status = (page: Page) => api<CloudStatus>(page, 'cloudStatus', {})+const owner = async (page: Page) => (await status(page)).owner?.userId ?? null++/** As on an identity this app never saw in an account: only `keptOut` can stop `mayAutoClaim` then. */+const forgetClaims = (page: Page) =>+ page.evaluate(() => {+ for (const key of Object.keys(localStorage)) {+ if (key.startsWith('claimedComputerIds.') || key.startsWith('keptOutOfAccount.')) localStorage.removeItem(key)+ }+ })++async function openComputers(page: Page) {+ await page.reload()+ await openGeneralSettings(page)+ await page.getByRole('dialog').getByRole('button', { name: 'Computers', exact: true }).click()+}++test('turning on Reach from anywhere asks to add a computer in no account first', async () => {+ // Each relay restart keeps the old relay up for 10 seconds, and the status forgets the owner only after that.+ test.setTimeout(180_000)+ const { browser, page } = await attach()+ const started = await status(page)+ const reach = page.getByRole('switch', { name: /Reach from anywhere/ })+ const dialog = page.getByRole('alertdialog')+ const turnedOnWithoutAsking = async () => {+ await reach.click()+ await expect(reach).toHaveAttribute('aria-checked', 'true')+ await expect(dialog).toHaveCount(0)+ }+ const on = await api<CloudStatus>(page, 'setCloud', { enabled: true })+ if (!on.enabled) await browser.close()+ test.skip(!on.enabled, 'Needs the dev cloud on: `npm run dev -- --cdp --cloud`.')+ try {+ if (!on.joinsAccountOnEnable) await api(page, 'unclaim', {})+ await api(page, 'setCloud', { enabled: false })+ await forgetClaims(page)+ await openComputers(page)+ await expect(reach).toHaveAttribute('aria-checked', 'false')++ // Cancel leaves it off.+ await reach.click()+ await expect(dialog.getByRole('heading', { name: /^Add .+ to your account first$/ })).toBeVisible()+ await dialog.getByRole('button', { name: 'Cancel' }).click()+ await expect(dialog).toHaveCount(0)+ await expect(reach).toHaveAttribute('aria-checked', 'false')+ expect((await status(page)).enabled).toBe(false)++ // Use your own relay turns it on, and a computer this app never saw in the account stays out until the address is saved.+ await reach.click()+ await dialog.getByRole('button', { name: 'Use your own relay' }).click()+ await expect(dialog).toHaveCount(0)+ await expect(reach).toHaveAttribute('aria-checked', 'true')+ await expect(page.getByText('Relay address', { exact: true })).toBeVisible()+ await openComputers(page)+ await expect(page.getByText('Not in your account', { exact: true })).toBeVisible()+ await page.waitForTimeout(5_000)+ expect(await owner(page)).toBeNull()++ // A saved private relay never asks: it has no accounts, though off the status names no relay.+ await api(page, 'setCloudUrl', { url: 'https://relay.example.com' })+ await reach.click()+ await expect(dialog).toHaveCount(0)+ await expect(reach).toHaveAttribute('aria-checked', 'false')+ await expect.poll(async () => (await status(page)).relay, { timeout: 30_000 }).toBe('codync')+ await turnedOnWithoutAsking()+ expect((await status(page)).relay).toBe('private')+ await api(page, 'setCloudUrl', { url: null })++ // Add to account turns it on and adds it.+ await api(page, 'setCloud', { enabled: false })+ await expect(reach).toHaveAttribute('aria-checked', 'false')+ await reach.click()+ await dialog.getByRole('button', { name: 'Add to account' }).click()+ await expect(dialog).toHaveCount(0)+ await expect(reach).toHaveAttribute('aria-checked', 'true')+ await expect.poll(() => owner(page), { timeout: 60_000 }).not.toBeNull()++ // Off never asks, and neither does back on for a computer in an account, once the status has forgotten its owner.+ await reach.click()+ await expect(reach).toHaveAttribute('aria-checked', 'false')+ await expect(dialog).toHaveCount(0)+ await expect.poll(() => owner(page), { timeout: 30_000 }).toBeNull()+ await turnedOnWithoutAsking()+ await expect.poll(() => owner(page), { timeout: 60_000 }).not.toBeNull()+ } finally {+ // Back to how it started. A computer that started in an account ends in it, unless the run failed before adding it.+ await api(page, 'setCloudUrl', { url: null }).catch(() => {})+ if (started.joinsAccountOnEnable && (await owner(page).catch(() => null))) await api(page, 'unclaim', {}).catch(() => {})+ await api(page, 'setCloud', { enabled: started.enabled }).catch(() => {})+ await page.reload()+ await browser.close()+ }+})diff --git a/apps/desktop/e2e/sandbox.ts b/apps/desktop/e2e/sandbox.tsindex fff77f77..5945ffcd 100644--- a/apps/desktop/e2e/sandbox.ts+++ b/apps/desktop/e2e/sandbox.ts@@ -35,6 +35,12 @@ export async function attach(): Promise<{ browser: Browser; page: Page }> {return { browser, page }}+/** Opens Settings from the account panel, on its General page. */+export async function openGeneralSettings(page: Page) {+ await page.locator('.sidebar-account').click()+ await page.locator('.account-panel').getByText('Settings', { exact: true }).click()+}+type Host = {snapshot(): Promise<HostSnapshot>call(baseURL: string, token: string, method: string, body: unknown, timeoutMs: number): Promise<unknown>diff --git a/apps/desktop/src/renderer/components/Overlay.tsx b/apps/desktop/src/renderer/components/Overlay.tsxindex 042af223..481bf6ec 100644--- a/apps/desktop/src/renderer/components/Overlay.tsx+++ b/apps/desktop/src/renderer/components/Overlay.tsx@@ -168,12 +168,14 @@ export interface DialogAction {}/** A centered card over a dimmed screen with the actions and Cancel (`.codyncDialog`). */-export function Dialog({ open, title, message, actions, cancel = 'Cancel', onClose, children }: {+export function Dialog({ open, title, message, actions, cancel = 'Cancel', onCancel, onClose, children }: {open: booleantitle: stringmessage?: string | nullactions: DialogAction[]cancel?: string | null+ /** Closed without an action; `onClose` follows, as it does after an action. */+ onCancel?: () => voidonClose: () => void/** A field between the text and the buttons (a name to type); `data-autofocus` on it takes the focus. */children?: ReactNode@@ -184,13 +186,17 @@ export function Dialog({ open, title, message, actions, cancel = 'Cancel', onCloconst layer = useRef<HTMLDivElement>(null)const id = useId()if (open) last.current = { title, message, actions, children }- useEscape(open && cancel !== null, onClose, layer)+ const dismiss = () => {+ onCancel?.()+ onClose()+ }+ useEscape(open && cancel !== null, dismiss, layer)useModalFocus(open, mounted, layer)if (!mounted) return nullconst shownContent = last.currentreturn createPortal(<div ref={layer} className={`dialog ${shown ? 'shown' : ''}`} role="alertdialog" aria-modal aria-labelledby={`${id}-title`} aria-describedby={shownContent.message ? `${id}-message` : undefined}>- <div className="dialog-dim" onClick={() => cancel !== null && onClose()} />+ <div className="dialog-dim" onClick={() => cancel !== null && dismiss()} /><div className="dialog-card" data-modal-card tabIndex={-1}><div className="dialog-text">{/* Callers translate the sentence, then insert names. A second pass would also translate a device named "Done". */}@@ -200,7 +206,7 @@ export function Dialog({ open, title, message, actions, cancel = 'Cancel', onClo{shownContent.children}<div className="dialog-buttons">{cancel !== null ? (- <button className="dialog-button" data-autofocus onClick={onClose}>+ <button className="dialog-button" data-autofocus onClick={dismiss}>{tr(cancel)}</button>) : null}diff --git a/apps/desktop/src/renderer/store/cloud.ts b/apps/desktop/src/renderer/store/cloud.tsindex 2266c642..6d421e81 100644--- a/apps/desktop/src/renderer/store/cloud.ts+++ b/apps/desktop/src/renderer/store/cloud.ts@@ -1,3 +1,4 @@+import type { ClaimFailure } from '@shared/analytics'import type { CloudStatus, ClaimSignature } from '@shared/models'import { accountMismatch, mayAutoClaim, mayJoinAfterInstall, mayOfferMove, type AccountMismatch, type ClaimCandidate } from '../lib/auto-claim'import { Observable } from '../lib/observable'@@ -5,6 +6,7 @@ import { isOlderCopy } from '../lib/older-copy'import { relayAddressToSave } from '../lib/relay-address'import { pref, type Pref } from '../lib/prefs'import { account } from './account'+import { analytics } from './analytics'import type { AppModel } from './app-model'import type { BotStore } from './bot-store'import { trNow } from '../lib/l10n.ts'@@ -42,6 +44,10 @@ export class CloudError extends Error {}}+/** `reach_account_answered`'s `error`: the category of a failed claim, never its message. */+const claimFailure = (error: unknown): ClaimFailure =>+ !(error instanceof CloudError) ? 'host' : error.code === 'unreachable' ? 'unreachable' : 'refused'+async function request<T>(method: string, path: string, body?: unknown, signed = false): Promise<T> {const res = await window.codync.cloud.request(method, path, body, signed)if (!res.ok) throw new CloudError(res.error.status, res.error.code, res.error.message)@@ -284,28 +290,51 @@ export class CloudModel extends Observable {/** §4.2 A: makes a computer this app manages part of the account; its cloud is turned on first. */async claim(store: BotStore, quiet = false): Promise<boolean> {- const user = this.userId- if (!user || !store.client) {- if (!quiet) this.app.setError(trNow('Sign in first.'))+ try {+ await this.join(store)+ return true+ } catch (error) {+ this.fail(error, quiet)return false}+ }++ private async join(store: BotStore) {+ const user = this.userId+ if (!user || !store.client) throw new Error(trNow('Sign in first.'))const out = keptOut(user)out.set(out.get().filter((x) => x !== store.computer.id))+ const client = await store.ready()+ if (!store.cloud?.enabled) await this.enableCloud(store)+ const challenge = await request<{ claimId: string; nonce: string }>('POST', 'v1/claims', {})+ const signed = await client.call<ClaimSignature>('claimSign', { claimId: challenge.claimId, nonce: challenge.nonce, userId: user })+ await request('POST', `v1/claims/${challenge.claimId}/complete`, signed)+ // Only against a list that came back: one that didn't can't tell which earlier identities are gone.+ if ((await this.refresh(true)) && store === this.app.local) await this.forgetEarlierIdentities(user, store.computer.id)+ }++ /** Asked before Reach from anywhere turns on (`joinsAccountOnEnable`): Add to account, which turns it on too. */+ async addFromReach(store: BotStore) {try {- const client = await store.ready()- if (!store.cloud?.enabled) await this.enableCloud(store)- const challenge = await request<{ claimId: string; nonce: string }>('POST', 'v1/claims', {})- const signed = await client.call<ClaimSignature>('claimSign', { claimId: challenge.claimId, nonce: challenge.nonce, userId: user })- await request('POST', `v1/claims/${challenge.claimId}/complete`, signed)- // Only against a list that came back: one that didn't can't tell which earlier identities are gone.- if ((await this.refresh(true)) && store === this.app.local) await this.forgetEarlierIdentities(user, store.computer.id)- return true+ await this.join(store)+ analytics.track({ event: 'reach_account_answered', outcome: 'added' })} catch (error) {- this.fail(error, quiet)- return false+ this.fail(error)+ analytics.track({ event: 'reach_account_answered', outcome: 'failed', error: claimFailure(error) })}}+ /**+ * Asked before Reach from anywhere turns on: Use your own relay. It's on the Codync relay until its address is saved,+ * so it's kept out of auto-claim meanwhile (`keptOut`; Add to account still adds it).+ */+ async useOwnRelay(store: BotStore) {+ const user = this.userId+ if (user) include(keptOut(user), store.computer.id)+ analytics.track({ event: 'reach_account_answered', outcome: 'own_relay' })+ await this.setCloud(store, true)+ }+/*** This computer's host got new keys (a reset data folder, a reinstall): the identities claimed* before are dead copies of it, so they leave the account instead of showing up twice. One stilldiff --git a/apps/desktop/src/renderer/views/settings/ComputersView.tsx b/apps/desktop/src/renderer/views/settings/ComputersView.tsxindex 59588361..02c51396 100644--- a/apps/desktop/src/renderer/views/settings/ComputersView.tsx+++ b/apps/desktop/src/renderer/views/settings/ComputersView.tsx@@ -8,6 +8,7 @@ import { HStack, Spacer, VStack } from '../../components/Stack'import { Text } from '../../components/Text'import { useModel } from '../../lib/observable'import { useAccount } from '../../store/account'+import { analytics } from '../../store/analytics'import type { CloudComputer } from '../../store/cloud'import type { BotStore } from '../../store/bot-store'import { StoreContext, useApp } from '../../store/context'@@ -114,6 +115,7 @@ function ManagedComputerCard({ store, ssh: overSSH, nested = false }: { store: Bconst [showVoice, setShowVoice] = useState(false)const [confirmUnclaim, setConfirmUnclaim] = useState(false)const [confirmAutoApproval, setConfirmAutoApproval] = useState(false)+ const [askAccount, setAskAccount] = useState(false)const cloud = store.cloudconst owner = cloud?.owner ?? nullconst autoApproval = cloud?.approval === 'auto'@@ -136,6 +138,14 @@ function ManagedComputerCard({ store, ssh: overSSH, nested = false }: { store: B}})+ // Turning it on asks to add a computer that would be in no account (`joinsAccountOnEnable`). Signed out, the welcome+ // covers Settings and a build without accounts has none to join; a saved session still restoring makes the switch wait.+ const asksAccount = cloud?.joinsAccountOnEnable === true+ const setReach = (on: boolean) => {+ if (on && asksAccount && account.isSignedIn) setAskAccount(true)+ else void run(() => app.cloud.setCloud(store, on))+ }+// A private relay has no accounts: no claim, no access requests.const privateRelay = cloud?.relay === 'private'// The host's error is shown as it wrote it.@@ -186,7 +196,7 @@ function ManagedComputerCard({ store, ssh: overSSH, nested = false }: { store: B// Until the host gives its cloud status, there's no way to tell its relay or account....(cloud? [- <Switch key="cloud" className="settings-appear" on={cloud.enabled} disabled={busy || !manageable} onChange={(on) => run(() => app.cloud.setCloud(store, on))}>+ <Switch key="cloud" className="settings-appear" on={cloud.enabled} disabled={busy || !manageable || (asksAccount && !cloud.enabled && !account.isReady)} onChange={setReach}><span className="settings-stack"><Text>{tr(`Reach from anywhere`)}</Text><Text size="caption" tone={cloud.lastError ? 'attention' : 'secondary'}>{cloudLine}</Text>@@ -269,6 +279,17 @@ function ManagedComputerCard({ store, ssh: overSSH, nested = false }: { store: Bactions={[{ title: 'Skip the check', destructive: true, action: () => setApproval('auto') }]}onClose={() => setConfirmAutoApproval(false)}/>+ <Dialog+ open={askAccount}+ title={tr('Add {name} to your account first').replaceAll('{name}', () => name)}+ message={tr('Your phone reaches {name} from anywhere through your account. Adding it also turns this on.').replaceAll('{name}', () => name)}+ actions={[+ { title: 'Add to account', 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' })}+ onClose={() => setAskAccount(false)}+ /><Dialogopen={confirmUnclaim}title={tr('Remove {name} from the account?').replaceAll('{name}', name)}diff --git a/apps/desktop/src/shared/analytics.ts b/apps/desktop/src/shared/analytics.tsindex 444c5609..08b8e753 100644--- a/apps/desktop/src/shared/analytics.ts+++ b/apps/desktop/src/shared/analytics.ts@@ -37,6 +37,10 @@ export type VoiceFailure = 'none' | 'microphone' | 'connection' | 'provider'/** What came of a window whose page crashed: it loaded again, or crashed too often and stays down. */export type WindowRecoveryOutcome = 'reloaded' | 'gave_up'+/** How the ask before Reach from anywhere turns on ended. */+export type ReachOutcome = 'added' | 'own_relay' | 'cancelled' | 'failed'+/** Why a computer couldn't be added to the account: the cloud couldn't be reached, it refused, or the host failed. */+export type ClaimFailure = 'unreachable' | 'refused' | 'host'export type AnalyticsEvent =| { event: 'app_opened'; at_login: boolean }@@ -53,6 +57,7 @@ export type AnalyticsEvent =| { event: 'voice_call_started'; engine: VoiceCallEngine }| { event: 'voice_call_quality'; engine: VoiceCallEngine; ready_ms?: number; reconnects: number; stuck: VoiceStuck; failure: VoiceFailure }| { event: 'window_recovery'; outcome: WindowRecoveryOutcome }+ | { event: 'reach_account_answered'; outcome: ReachOutcome; error?: ClaimFailure }/** `track`'s body: the event with its properties, from the desktop app. */export const trackBody = (event: AnalyticsEvent) => ({ ...event, app: 'desktop' as const })diff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.tsindex 02ec3f2e..2be470e1 100644--- a/apps/desktop/src/shared/models.ts+++ b/apps/desktop/src/shared/models.ts@@ -596,6 +596,8 @@ export interface CloudStatus {assistants?: boolean | null/** In no account while it could join one: a signed-in phone that pairs asks to bring it into its account. Absent from older hosts. */canJoinAccount?: boolean | null+ /** Turned on, the cloud would leave it in no account on a Codync cloud; known with the cloud off too. Absent from older hosts, which just turn on. */+ joinsAccountOnEnable?: boolean | null}export interface ClaimSignature {diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.jsonindex 8888a9a4..29e2d9e8 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json@@ -1806,5 +1806,8 @@"D removes": "D entfernt","S sends this now": "S sendet diese jetzt","D removes the last": "D entfernt die letzte",- "Update Codync on {host}: sending now and taking back need {version} or newer.": "Aktualisiere Codync auf {host}: Jetzt senden und Zurücknehmen brauchen {version} oder neuer."+ "Update Codync on {host}: sending now and taking back need {version} or newer.": "Aktualisiere Codync auf {host}: Jetzt senden und Zurücknehmen brauchen {version} oder neuer.",+ "Add {name} to your account first": "Füge {name} zuerst zu deinem Konto hinzu",+ "Your phone reaches {name} from anywhere through your account. Adding it also turns this on.": "Dein Telefon erreicht {name} von überall über dein Konto. Beim Hinzufügen wird dies auch aktiviert.",+ "Use your own relay": "Eigenes Relay verwenden"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.jsonindex afaa748d..6503942c 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json@@ -1806,5 +1806,8 @@"D removes": "D elimina","S sends this now": "S envía este ahora","D removes the last": "D elimina el último",- "Update Codync on {host}: sending now and taking back need {version} or newer.": "Actualiza Codync en {host}: enviar ahora y retirar necesitan {version} o una versión más reciente."+ "Update Codync on {host}: sending now and taking back need {version} or newer.": "Actualiza Codync en {host}: enviar ahora y retirar necesitan {version} o una versión más reciente.",+ "Add {name} to your account first": "Primero añade {name} a tu cuenta",+ "Your phone reaches {name} from anywhere through your account. Adding it also turns this on.": "Tu teléfono accede a {name} desde cualquier lugar a través de tu cuenta. Al añadirlo también se activa esta opción.",+ "Use your own relay": "Usar tu propio relé"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.jsonindex d80d7963..0cfb87ad 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json@@ -1806,5 +1806,8 @@"D removes": "D retire","S sends this now": "S envoie celui-ci maintenant","D removes the last": "D retire le dernier",- "Update Codync on {host}: sending now and taking back need {version} or newer.": "Mettez à jour Codync sur {host} : l’envoi immédiat et le retrait nécessitent {version} ou une version plus récente."+ "Update Codync on {host}: sending now and taking back need {version} or newer.": "Mettez à jour Codync sur {host} : l’envoi immédiat et le retrait nécessitent {version} ou une version plus récente.",+ "Add {name} to your account first": "Ajoutez d'abord {name} à votre compte",+ "Your phone reaches {name} from anywhere through your account. Adding it also turns this on.": "Votre téléphone accède à {name} de partout via votre compte. L'ajouter active aussi cette option.",+ "Use your own relay": "Utiliser votre propre relais"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.jsonindex 17d1f365..dcaaa0b0 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json@@ -1806,5 +1806,8 @@"D removes": "D rimuove","S sends this now": "S invia questo ora","D removes the last": "D rimuove l'ultimo",- "Update Codync on {host}: sending now and taking back need {version} or newer.": "Aggiorna Codync su {host}: per inviare subito e ritirare un messaggio serve la versione {version} o successiva."+ "Update Codync on {host}: sending now and taking back need {version} or newer.": "Aggiorna Codync su {host}: per inviare subito e ritirare un messaggio serve la versione {version} o successiva.",+ "Add {name} to your account first": "Prima aggiungi {name} al tuo account",+ "Your phone reaches {name} from anywhere through your account. Adding it also turns this on.": "Il telefono raggiunge {name} da ovunque tramite il tuo account. Aggiungendolo attivi anche questa opzione.",+ "Use your own relay": "Usa il tuo relay"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.jsonindex 49accab1..c8ff17b9 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json@@ -1806,5 +1806,8 @@"D removes": "D 削除","S sends this now": "S これを今すぐ送信","D removes the last": "D 最後のものを削除",- "Update Codync on {host}: sending now and taking back need {version} or newer.": "{host} の Codync をアップデートしてください。今すぐ送信と取り消しには {version} 以降が必要です。"+ "Update Codync on {host}: sending now and taking back need {version} or newer.": "{host} の Codync をアップデートしてください。今すぐ送信と取り消しには {version} 以降が必要です。",+ "Add {name} to your account first": "先に {name} をアカウントに追加してください",+ "Your phone reaches {name} from anywhere through your account. Adding it also turns this on.": "スマートフォンはアカウントを通じてどこからでも {name} にアクセスします。追加すると、この機能もオンになります。",+ "Use your own relay": "自分のリレーを使う"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.jsonindex 1cbf3d85..3553984c 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json@@ -1806,5 +1806,8 @@"D removes": "D 제거","S sends this now": "S 이것을 지금 보내기","D removes the last": "D 마지막 것 제거",- "Update Codync on {host}: sending now and taking back need {version} or newer.": "{host}에서 Codync를 업데이트하세요. 지금 보내기와 취소를 쓰려면 {version} 이상이 필요합니다."+ "Update Codync on {host}: sending now and taking back need {version} or newer.": "{host}에서 Codync를 업데이트하세요. 지금 보내기와 취소를 쓰려면 {version} 이상이 필요합니다.",+ "Add {name} to your account first": "먼저 {name}을(를) 계정에 추가하세요",+ "Your phone reaches {name} from anywhere through your account. Adding it also turns this on.": "휴대폰은 계정을 통해 어디서나 {name}에 접근합니다. 추가하면 이 기능도 켜집니다.",+ "Use your own relay": "내 릴레이 사용"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.jsonindex 70640618..be89a0b1 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json@@ -1806,5 +1806,8 @@"D removes": "D remove","S sends this now": "S envia esta agora","D removes the last": "D remove a última",- "Update Codync on {host}: sending now and taking back need {version} or newer.": "Atualize o Codync em {host}: enviar agora e retirar precisam da versão {version} ou mais recente."+ "Update Codync on {host}: sending now and taking back need {version} or newer.": "Atualize o Codync em {host}: enviar agora e retirar precisam da versão {version} ou mais recente.",+ "Add {name} to your account first": "Primeiro adicione {name} à sua conta",+ "Your phone reaches {name} from anywhere through your account. Adding it also turns this on.": "Seu telefone acessa {name} de qualquer lugar pela sua conta. Ao adicionar, isto também é ativado.",+ "Use your own relay": "Usar seu próprio relay"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.jsonindex 9b4edac2..40ec2865 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json@@ -1806,5 +1806,8 @@"D removes": "D убирает","S sends this now": "S отправляет это сейчас","D removes the last": "D убирает последнее",- "Update Codync on {host}: sending now and taking back need {version} or newer.": "Обновите Codync на {host}: отправке сейчас и отзыву нужна версия {version} или новее."+ "Update Codync on {host}: sending now and taking back need {version} or newer.": "Обновите Codync на {host}: отправке сейчас и отзыву нужна версия {version} или новее.",+ "Add {name} to your account first": "Сначала добавьте {name} в аккаунт",+ "Your phone reaches {name} from anywhere through your account. Adding it also turns this on.": "Телефон подключается к {name} из любой точки через ваш аккаунт. При добавлении эта функция тоже включится.",+ "Use your own relay": "Использовать свой ретранслятор"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.jsonindex f526152c..11417d3d 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json@@ -1806,5 +1806,8 @@"D removes": "D 移除","S sends this now": "S 立即发送这条","D removes the last": "D 移除最后一条",- "Update Codync on {host}: sending now and taking back need {version} or newer.": "请在 {host} 上更新 Codync:立即发送和收回需要 {version} 或更高版本。"+ "Update Codync on {host}: sending now and taking back need {version} or newer.": "请在 {host} 上更新 Codync:立即发送和收回需要 {version} 或更高版本。",+ "Add {name} to your account first": "请先将 {name} 加入你的账户",+ "Your phone reaches {name} from anywhere through your account. Adding it also turns this on.": "你的手机会通过账户从任何地方连接 {name}。加入后也会开启此功能。",+ "Use your own relay": "使用自己的中继"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.jsonindex 004fe743..406723bb 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json@@ -1806,5 +1806,8 @@"D removes": "D 移除","S sends this now": "S 立即送出這則","D removes the last": "D 移除最後一則",- "Update Codync on {host}: sending now and taking back need {version} or newer.": "請在 {host} 上更新 Codync:立即送出和收回需要 {version} 或更新的版本。"+ "Update Codync on {host}: sending now and taking back need {version} or newer.": "請在 {host} 上更新 Codync:立即送出和收回需要 {version} 或更新的版本。",+ "Add {name} to your account first": "請先將 {name} 加入你的賬戶",+ "Your phone reaches {name} from anywhere through your account. Adding it also turns this on.": "你的手機會透過賬戶從任何地方連到 {name}。加入後也會開啟這個功能。",+ "Use your own relay": "使用自己的中繼"}diff --git a/docs/guides/accounts-and-ssh.md b/docs/guides/accounts-and-ssh.mdindex fafbe883..cfcfcd3c 100644--- a/docs/guides/accounts-and-ssh.md+++ b/docs/guides/accounts-and-ssh.md@@ -245,7 +245,10 @@ such action: removing a computer from the account takes the desktop app (or `codon that computer), and phones manage only their own access (pair or forget, revoke, ask). See [desktop app](../architecture/desktop-app.md).**Computers & devices** (Settings) shows, for this computer and each SSH computer:-*Reach from anywhere* (`setCloud`, on/off; the host's build decides which cloud),+*Reach from anywhere* (`setCloud`, on/off; the host's build decides which cloud; when the host's+`cloudStatus` says `joinsAccountOnEnable`, read from what it saved since the status names no owner or+relay with the cloud off, turning it on first asks: *Add to account* turns it on too, *Use your own+relay* turns it on and keeps this identity out of auto-claim (`keptOutOfAccount`) until the address is saved; older hosts just turn on),*Relay address* and, for a private relay, a write-only *Relay token* (`setCloudUrl`; thehost's `cloudStatus` says `relay: "private"` and `tokenSet`, and there the account rows are hiddenand auto-claim never runs), *Add to account* (claim: `POST /v1/claims` → loopback `claimSign` → complete) anddiff --git a/docs/reference/analytics-events.md b/docs/reference/analytics-events.mdindex a640720b..8d0178bc 100644--- a/docs/reference/analytics-events.md+++ b/docs/reference/analytics-events.md@@ -103,6 +103,7 @@ host answers and sends it once the host is up.| `credential_saved` | host | A key, login or vault is saved (clearing one isn't) | `kind` (`login`/`onepassword`/`connector`/`composio`/`voice`/`agent_env`) || `agent_setup_started` | host | `agentSetup` (an agent's install or sign-in terminal) | `agent` || `agent_signed_in` | host | `agentAuthenticate` | `agent` |+| `reach_account_answered` | host `track` (desktop) | The ask before *Reach from anywhere* turns on for a computer in no account ended | `outcome` (`added`/`own_relay`/`cancelled`/`failed`), `error` on `failed` (`unreachable`: the cloud couldn't be reached; `refused`: it refused; `host`: the host failed) || `setting_changed` | host, iOS, Android | A setting is switched | `setting` (host: `remote_access`/`remote_access_url` (`on`: a relay address is saved, never the address)/`approval` (`on`: approved without the code)/`automatic_updates`/`remote_screen`/`cloud_assistants`; phones: `push`/`live_activities`), `on` || `host_update_installed` | host | `installHostUpdate` | — || `network_joined` | host | `networkCreate` / `networkJoin`: the computer is in a network of the user's computers | `via` (`create`/`invite`), never a name, invite or connector address |diff --git a/host/src/analytics.rs b/host/src/analytics.rsindex 64941623..22dfe9e7 100644--- a/host/src/analytics.rs+++ b/host/src/analytics.rs@@ -103,6 +103,8 @@ pub enum Event {AgentSetupStarted,AgentSignedIn,SettingChanged,+ /// The desktop app's ask before Reach from anywhere turns on for a computer in no account.+ ReachAccountAnswered,HostUpdateInstalled,/// `networkCreate` or `networkJoin`: this computer is in a network of the user's computers.NetworkJoined,@@ -173,6 +175,7 @@ impl Event {Self::AgentSetupStarted => "agent_setup_started",Self::AgentSignedIn => "agent_signed_in",Self::SettingChanged => "setting_changed",+ Self::ReachAccountAnswered => "reach_account_answered",Self::HostUpdateInstalled => "host_update_installed",Self::NetworkJoined => "network_joined",Self::NetworkChanged => "network_changed",diff --git a/host/src/analytics/reported.rs b/host/src/analytics/reported.rsindex 67104b9c..fa45aa47 100644--- a/host/src/analytics/reported.rs+++ b/host/src/analytics/reported.rs@@ -85,6 +85,12 @@ pub enum Reported {WindowRecovery {outcome: WindowRecoveryOutcome,},+ ReachAccountAnswered {+ outcome: ReachOutcome,+ /// Why adding the computer failed.+ #[serde(skip_serializing_if = "Option::is_none")]+ error: Option<ClaimFailure>,+ },}// Value lists. A value a newer client adds arrives as `other` instead of being refused.@@ -212,6 +218,29 @@ pub enum VoiceFailure {Other,}+/// How the ask before Reach from anywhere turns on ended.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum ReachOutcome {+ Added,+ OwnRelay,+ Cancelled,+ Failed,+ #[serde(other)]+ Other,+}++/// Why a computer couldn't be added to the account.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum ClaimFailure {+ Unreachable,+ Refused,+ Host,+ #[serde(other)]+ Other,+}+impl Track {/// The body to send for `event`, as `app` (what the terminal UI posts).pub fn body(app: App, event: Reported) -> Value {@@ -310,6 +339,14 @@ mod tests {),(json!({"event": "window_recovery", "app": "desktop", "outcome": "reloaded"}), Event::WindowRecovery),(json!({"event": "window_recovery", "app": "desktop", "outcome": "gave_up"}), Event::WindowRecovery),+ (+ json!({"event": "reach_account_answered", "app": "desktop", "outcome": "own_relay"}),+ Event::ReachAccountAnswered,+ ),+ (+ json!({"event": "reach_account_answered", "app": "desktop", "outcome": "failed", "error": "refused"}),+ Event::ReachAccountAnswered,+ ),];for (body, event) in cases {let mut expected = body.clone();diff --git a/host/src/remote/cloud.rs b/host/src/remote/cloud.rsindex 7f566a72..ff1b644a 100644--- a/host/src/remote/cloud.rs+++ b/host/src/remote/cloud.rs@@ -16,7 +16,7 @@ use std::sync::Mutex;use std::time::Duration;use tokio::sync::watch;-pub use super::cloud_url::{Address, RelayKind, TokenChange, current, set_cloud, set_cloud_url, show, url};+pub use super::cloud_url::{Address, RelayKind, TokenChange, current, set_cloud, set_cloud_url, show, url, when_on};/// How long one successful state pull keeps an account device allowed.pub const LEASE_MS: i64 = 15 * 60 * 1000;@@ -66,6 +66,9 @@ pub struct CloudStatus {/// In no account while it could join one (the Codync cloud on): a signed-in phone that pairs asks to bring it/// into its account. Kept by [`update_status`], so every app words it the same.pub can_join_account: bool,+ /// Turned on, the cloud would leave this computer in no account on a Codync cloud, so the desktop app asks to add+ /// it first. Known with the cloud off too, unlike the fields above; kept by [`update_status`].+ pub joins_account_on_enable: bool,}/// How account devices get in (`setApproval`, local only).@@ -145,11 +148,13 @@ impl Cloud {/// Changes the status and tells this computer's apps when it actually changed.pub fn update_status(hub: &Hub, f: impl FnOnce(&mut CloudStatus)) {+ let joins_account_on_enable = super::owner::joins_account_on_enable(&hub.store);let changed = {let mut s = hub.cloud.status.locked();let before = s.clone();f(&mut s);s.can_join_account = s.enabled && s.relay == RelayKind::Codync && s.owner.is_none();+ s.joins_account_on_enable = joins_account_on_enable;(*s != before).then(|| s.clone())};if let Some(s) = changed {diff --git a/host/src/remote/cloud_url.rs b/host/src/remote/cloud_url.rsindex 1e4687fb..5d0ea45e 100644--- a/host/src/remote/cloud_url.rs+++ b/host/src/remote/cloud_url.rs@@ -53,8 +53,15 @@ struct Candidate<'a> {/// The cloud in use: its public address, its kind, and the registration token when it has one.pub fn current(store: &Store) -> Option<Address> {- let off =- std::env::var("CODYNC_CLOUD").is_ok_and(|v| v == "off") || store.kv_get(ENABLED).as_deref() == Some("false");+ if store.kv_get(ENABLED).as_deref() == Some("false") {+ return None;+ }+ when_on(store)+}++/// The cloud this computer uses with Reach from anywhere on. `CODYNC_CLOUD=off` keeps it off whatever the switch says.+pub fn when_on(store: &Store) -> Option<Address> {+ let off = std::env::var("CODYNC_CLOUD").is_ok_and(|v| v == "off");if cfg!(test) {// No fake cloud, no cloud: a test never reaches a real one.let url = store.kv_get("test_cloud_url")?;@@ -363,4 +370,23 @@ mod tests {assert_eq!((status.token_set, status.relay), (false, RelayKind::Codync));assert!(!set_cloud(&hub, false).unwrap().enabled);}++ #[test]+ fn with_the_cloud_off_the_status_still_says_whether_turning_it_on_joins_an_account() {+ let hub = temp_hub();+ hub.store.kv_set("test_cloud_url", "https://relay.example.com").unwrap();+ assert!(set_cloud(&hub, false).unwrap().joins_account_on_enable, "in no account, on the Codync cloud");++ hub.store.kv_set("test_cloud_token", "s3cret-token-value").unwrap();+ let private = set_cloud(&hub, false).unwrap();+ assert_eq!(private.relay, RelayKind::Codync, "off, the status names no relay");+ assert!(!private.joins_account_on_enable, "a saved private relay has no accounts");+ hub.store.kv_delete("test_cloud_token").unwrap();++ let owner = cloud::Owner { user_id: "user_1".into(), email: None };+ crate::remote::owner::remember(&hub, Some(&owner)).unwrap();+ let in_account = set_cloud(&hub, false).unwrap();+ assert_eq!(in_account.owner, None, "off, the status names no account");+ assert!(!in_account.joins_account_on_enable, "it goes back to the account it was in");+ }}diff --git a/host/src/remote/owner.rs b/host/src/remote/owner.rsindex e2665986..7a916ddf 100644--- a/host/src/remote/owner.rs+++ b/host/src/remote/owner.rs@@ -20,9 +20,19 @@ const SIGNED: &str = "account_claims_signed";/// with the Codync cloud off or a private relay, where it is in no account either (as its status says).pub fn owner(store: &Store) -> Option<Owner> {cloud::current(store).filter(|address| address.kind == RelayKind::Codync)?;+ recorded(store)+}++/// The account last recorded, whichever relay is in use now.+fn recorded(store: &Store) -> Option<Owner> {store.kv_get(OWNER).and_then(|v| serde_json::from_str::<Option<Owner>>(&v).ok()).flatten()}+/// `CloudStatus::joins_account_on_enable`: read from what's saved, as the status says nothing of it with the cloud off.+pub fn joins_account_on_enable(store: &Store) -> bool {+ cloud::when_on(store).is_some_and(|address| address.kind == RelayKind::Codync) && recorded(store).is_none()+}+/// Records the account the cloud reports. When it is another one than before (joining one, moving, or leaving),/// every device let in for another account goes; joining a first account keeps the phones paired before devices/// recorded their account. The first record after an upgrade only records. The devices go first, so a failurediff --git a/private-relay/README.md b/private-relay/README.mdindex 311123bb..aa1ecad9 100644--- a/private-relay/README.md+++ b/private-relay/README.md@@ -88,7 +88,7 @@ Open TCP 443 to the internet. Leave 8788 on loopback.## Point a computer at it-On the computer (not on the VPS), in Codync's Computers settings, turn on Reach from anywhere, set Relay address to `https://relay.example.com`, and paste the same value as `CODYNC_PRIVATE_RELAY_TOKEN` into Relay token. The token stays on that computer: it is sent only in the `Codync-Relay-Token` header when the computer enrolls, never in a URL, and phones never see it. Or:+On the computer (not on the VPS), in Codync's Computers settings, turn on Reach from anywhere (choose Use your own relay if Codync asks you to add the computer to your account), set Relay address to `https://relay.example.com`, and paste the same value as `CODYNC_PRIVATE_RELAY_TOKEN` into Relay token. The token stays on that computer: it is sent only in the `Codync-Relay-Token` header when the computer enrolls, never in a URL, and phones never see it. Or:```bashcodync-host cloud --url https://relay.example.com --tokendiff --git a/web/content/docs/remote-access.mdx b/web/content/docs/remote-access.mdxindex 892556de..a6e16ae0 100644--- a/web/content/docs/remote-access.mdx+++ b/web/content/docs/remote-access.mdx@@ -86,11 +86,15 @@ With the relay off:- Devices approved through your account can't connect. Devices paired with a QR code still can.- Deliveries to public routine webhooks no longer reach the computer. Local ones keep working. The relay still accepts deliveries at the old public URLs and keeps them, readable, for up to 72 hours; they run if you turn the relay back on within that time. To stop them, remove the URL from the sender, or delete the routine or replace its key while the relay is on.+## Turning the relay on++In the desktop app, open **Settings → Computers** and turn on **Reach from anywhere** on the computer's card. A computer in no account has to join yours first: Codync asks you to add it, and adding it turns the relay on too. **Use your own relay** in the same window turns it on without joining your account, since your own relay has no accounts. Until you set **Relay address**, it connects through the Codync relay; see [Your own relay](#your-own-relay). On a computer without the desktop app, run `codync-host cloud --enable`.+## Your own relayYou can run a relay yourself and point a computer at it, instead of the Codync relay on Cloudflare. Chat stays end-to-end encrypted either way. The relay still cannot read it. How to set one up on a server is in the [private relay README](https://github.com/leepokai/Codync/blob/main/private-relay/README.md).-On the computer, open **Settings → Computers**, turn on **Reach from anywhere**, and set **Relay address** to your relay, such as `https://relay.example.com`. A **Relay token** field then appears: paste the token the relay was started with. The field never shows the token again; it says it's saved, and typing a new one replaces it. On a computer without the desktop app:+On the computer, open **Settings → Computers**, turn on **Reach from anywhere** (choose **Use your own relay** if Codync asks you to add the computer to your account), and set **Relay address** to your relay, such as `https://relay.example.com`. A **Relay token** field then appears: paste the token the relay was started with. The field never shows the token again; it says it's saved, and typing a new one replaces it. On a computer without the desktop app:```shcodync-host cloud --url https://relay.example.com --token