diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 8a7c8f70..a4222e00 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -138,7 +138,7 @@ Implemented mechanisms include crypto and blob sync, relay storage, CLI identity Next: keychain storage, a cost budget per chat. -The phone app (`mobile/`) pairs as a Device with `os` `ios`, `ipados`, or `android`; it is never a Runner and does not hold the master secret. The Device that creates or restores the identity holds the master secret. +See [Phone app](docs/architecture/phone-app.md) for phone identity and key ownership. ## Open points diff --git a/docs/architecture/phone-app.md b/docs/architecture/phone-app.md index a7d349c9..f597c766 100644 --- a/docs/architecture/phone-app.md +++ b/docs/architecture/phone-app.md @@ -2,6 +2,8 @@ `mobile/` is an Expo app (React Native, expo-router, TypeScript) for iOS and Android. A phone is a Device and never a Runner, and it links the same Device core the CLI is built from rather than porting it: `crates/mobile` (`beans-mobile`) wraps the `beans` library, built without the `runner` and `server` features, in a UniFFI object with three calls, and `mobile/modules/beans-core` is the Expo native module around it. +The phone app (`mobile/`) pairs as a Device with `os` `ios`, `ipados`, or `android`; it is never a Runner and does not hold the master secret. The Device that creates or restores the identity holds the master secret. + Beans and Beans Dev install separately as `ai.amoena.beans` and `ai.amoena.beans.dev` with primary schemes `beans` and `beans-dev`. Both also register `beans` to open the pairing links the Rust core emits; if another installed app claims that scheme, scan or paste the code inside Beans to choose the target app. Their iOS app/keychain groups are `group.ai.amoena.beans` and `group.ai.amoena.beans.dev`. Android prebuild requires an operator-supplied existing `BEANS_GOOGLE_SERVICES_FILE`; the Android-only plugin validates the file/project and a client matching the actual production or Dev application id. Missing or mismatched input fails clearly. iOS prebuild does not require Firebase. Fresh core roots are `beans-v2/core` and `beans-dev-v2/core`; storage and push decryption validate the marker before any account mutation. Existing distribution ids/groups remain unchanged, but old-format accounts and unversioned backups are incompatible and are not migrated. `pnpm run android:release` builds the Rust core, runs a clean production prebuild, and assembles the release APK with a keystore outside the repo. The Android signing plugin adds the release signing configuration from `BEANS_ANDROID_KEYSTORE`, `BEANS_ANDROID_KEYSTORE_PASSWORD`, `BEANS_ANDROID_KEY_ALIAS`, and `BEANS_ANDROID_KEY_PASSWORD`; the script loads the complete set from `BEANS_ANDROID_ENV` or `~/.config/beans/android/keystore.env`, requiring both the env file and keystore to have mode 0600. Inherited signing values cannot fill missing file entries. It leaves the development signing configuration alone. The Android locale plugin puts the English permission descriptions from `mobile/locales/en.json` into default resources so translated resources have fallbacks. @@ -19,7 +21,7 @@ Chat deletion awaits core success before removing the chat or draft; rejection r JS `coreHome()` returns `beans-v2/core` or `beans-dev-v2/core` without mkdir; core owns marker-before-write validation and creation. Android PushService independently selects the exact same variant root under its files directory. Native input/generator source names are `BeansCore`, `BeansCoreModule`, `beans-mobile` and `uniffi.beans_mobile`; generated Swift/Kotlin/JNI/xcframework outputs remain generator-owned. - **The native module** (`mobile/modules/beans-core`, picked up by Expo autolinking): a Swift `Module` and a Kotlin one, each about forty lines, forwarding `start`, `request`, and `wake` and turning the listener's frames into a `sendEvent`. `pnpm run core` (`build.ts`) builds the Rust for `aarch64-apple-ios` and the simulator into an xcframework with the UniFFI Swift beside it, and for `arm64-v8a` and `x86_64` with `cargo ndk` into `jniLibs` with the Kotlin (over JNA). The built pieces are gitignored; a Rust change needs `pnpm run core` and a native rebuild, a JS change is a Metro reload. -- **The JS side** (`mobile/src/core`): `engine.ts` starts the core, mirrors its events into the zustand store (`store.ts`, the way the macOS app's AppStore mirrors the CLI: `snapshot`, `roster.changed`, `message.*`, `job.*`, `chat.usage`, `relay.status`, `identity.changed`; events that arrive while a `bootstrap` snapshot is on its way wait and apply after it, as in the macOS app, so a snapshot built before the relay connected cannot undo that `relay.status`), and offers the screens the same verbs the macOS app has, each one request (`chats.send`, `bots.create`, `bots.update`, `pair.accept`, `providers.connect_*`, `providers.list_models`, `providers.api_key`, `providers.disconnect`, `device.rename`, `device.unpair`, `device.update`, `identity.forget`, `sync.wake`, …). `prefs.ts` keeps the one thing that is the phone's own, the dictation language. Nothing about the account is stored outside the core's folder. +- **The JS side** (`mobile/src/core`): `engine.ts` starts the core, mirrors its events into the zustand store (`store.ts`, the way the macOS app's AppStore mirrors the CLI: `snapshot`, `roster.changed`, `message.*`, `job.*`, `chat.usage`, `relay.status`, `identity.changed`; events that arrive while a `bootstrap` snapshot is on its way wait and apply after it, as in the macOS app, so a snapshot built before the relay connected cannot undo that `relay.status`), and offers the screens the same verbs the macOS app has, each one request (`chats.send`, `bots.create`, `bots.update`, `pair.accept`, `providers.connect_*`, `providers.list_models`, `providers.api_key`, `providers.disconnect`, `device.rename`, `device.set_name`, `device.unpair`, `device.update`, `identity.forget`, `sync.wake`, …). `prefs.ts` keeps the one thing that is the phone's own, the dictation language. Nothing about the account is stored outside the core's folder. - **Message mentions**: text bodies carry an optional `mentions` string array of bot IDs resolved by the Rust core; empty lists are omitted on the wire. The phone models that field and validates any returned list before a send acknowledgement updates the store or clears the composer draft. Resolved IDs may include uniquely named bots found in the text, not only composer picks. The transcript renders the original text as Markdown; mention IDs remain routing metadata. - **Pairing**: the phone scans or pastes the exact `beans://pair?v=2&…` code, or opens that versioned link. Scheme, authority, version and duplicated fields are validated before core dispatch/persistence; arbitrary `pair?` strings are not accepted. The sealed handshake requires `beans-v2` and protocol 5. Deep-link handling validates the original `expo-linking` URL, not reconstructed router params, so duplicate/version evidence survives. Scan, paste and manual entry share that validation before invoking the core. Unknown fields, malformed escapes, invalid relay credentials/query/fragment, noncanonical 32-byte keys and invalid/oversized nonces reject. - **Relay status**: the chat list's title slot (`src/ui/ChatsScreen.tsx`) stays empty while the relay connects, and speaks once that has taken a second, or four after the app comes to the foreground, when the socket the suspension killed is replaced: "Connecting…" with a spinner, or, once a try has failed (`relayError`), "Can’t connect" or, for an unknown machine, "Pair this phone again" beside a warning glyph. A tap on those opens an alert with the error (`src/ui/relay.ts`) and Try Now (a wake) or Unpair This Phone. "Update Beans to sync" takes the slot over all of them. Settings › Account › Relay shows the error in place of "Connecting…". diff --git a/docs/architecture/phone-interface.md b/docs/architecture/phone-interface.md index d14e5724..8aae5a7d 100644 --- a/docs/architecture/phone-interface.md +++ b/docs/architecture/phone-interface.md @@ -16,6 +16,8 @@ At drag release and momentum completion, transcript following is recomputed from A Device's screen under Settings (`app/settings/device/[id].tsx`) shows its reported CLI/core version without self-update controls or an unchecked up-to-date claim; see [CLI service and updates](service-updates.md#service-management). Provider credential screens use API-key fields and an in-app browser for subscription OAuth, the same browser that opens a computer's plugin sign-in from its card. Custom providers follow the built-in ones; OpenAI Compatible and Anthropic Compatible open the explicit protocol form (`app/settings/custom-provider.tsx`: name, API menu, base URL with the URL the CLI will call and, for a server on localhost, a note to name it as the Runners reach it, optional key, a Models row, and a Default Model menu). Models slides in the server's listed models with a native search bar offering Add "…" for an unlisted id (`app/settings/custom-models.tsx`); the forms share rows through `src/ui/modelDraft.ts`. +Every known paired Device offers Rename… through `src/ui/DeviceRename.tsx`. Settings › This phone uses the same action. iOS uses the native text prompt; Android uses the installed Jetpack Compose alert dialog and text field. Cancel and Android dismissal send nothing. The phone trims the submitted name, rejects more than 64 Unicode characters, and sends `device.set_name { id, name }`, expecting `null`; blank resets the alias. Snapshot `Device.name` is the effective account name and `machine_name` is the original machine name; roster events publish changes without optimistic local renaming. Prompts and error completions retain their account, relay, local Device and selected target ownership, with synchronous revocation on authority changes, target removal or target key/OS replacement and revocation on selection changes or unmount. The core persistence and rollout contract is in [Device names](device-names.md). + Settings › This phone › Diagnostics generates a report only after an explicit tap, using the local native core’s `diagnostics.report` method. The screen validates schema 1 and rebuilds a recursive allowlist before displaying selectable JSON; Copy Report and Share Report use those exact reviewed bytes. Disclosure names the selected relay host/port, including private hosts, configured-only providers, cached plugin setup, Runner presence rather than work readiness, and the busy-port limitation. The core may check public relay health; the screen never uploads automatically or probes providers. Unsupported schemas, invalid reports and request/copy/share failures display fixed localized messages, with no raw error or snapshot/status fallback. Existing observable ready/paired identity, Device, relay URL, connection and update-required fields fence account authority; their transitions, route blur and backgrounding discard the report and invalidate pending completions. An explicit OS copy/share already admitted under captured authority is not rolled back by later teardown. English and Simplified Chinese use the existing phone translation table. Each reviewed diagnostics report retains its validated request generation. Copy/Share admission compares that stored generation with the current generation, and completion uses the same stored token, so an account or lifecycle change away and back cannot reauthorize a stale rendered report before React clears it. diff --git a/mobile/app/settings/device/[id].tsx b/mobile/app/settings/device/[id].tsx index ca7b67c4..56d0c4aa 100644 --- a/mobile/app/settings/device/[id].tsx +++ b/mobile/app/settings/device/[id].tsx @@ -14,6 +14,7 @@ import { Row, Section } from "../../../src/ui/forms"; import { lastSeen } from "../../../src/ui/format"; import { Symbol } from "../../../src/ui/Symbol"; import { usePalette } from "../../../src/ui/theme"; +import { DeviceRename } from "../../../src/ui/DeviceRename"; const OS_NAMES: Record = { macos: "macOS", linux: "Linux", windows: "Windows", ios: "iOS", ipados: "iPadOS", android: "Android" }; @@ -94,6 +95,7 @@ export default function DeviceScreen() { {online ? t("Online") : lastSeen(seen)} +
{runner && (
diff --git a/mobile/app/settings/index.tsx b/mobile/app/settings/index.tsx index de02fa9b..fed2f770 100644 --- a/mobile/app/settings/index.tsx +++ b/mobile/app/settings/index.tsx @@ -9,12 +9,13 @@ import { CUSTOM_PRESETS, customProviderNamed, deviceName, isCustomProvider, isRu import { deviceIsOnline, useStore } from "../../src/core/store"; import { checkUpdates, dismissUpdate, installUpdate, setUpdateChecks, useUpdates } from "../../src/core/updates"; import { deviceLanguage, languageNames, languages, setAppLanguage, t, useLanguage } from "../../src/i18n"; -import { FieldRow, MenuRow, Row, Section, ToggleRow, type MenuChoice } from "../../src/ui/forms"; +import { MenuRow, Row, Section, ToggleRow, type MenuChoice } from "../../src/ui/forms"; import { lastSeen } from "../../src/ui/format"; import { Symbol } from "../../src/ui/Symbol"; import { usePalette } from "../../src/ui/theme"; import { deviceSymbol } from "../../src/ui/devices"; import { CloseToolbar } from "../../src/ui/navigation"; +import { DeviceRename } from "../../src/ui/DeviceRename"; import { automaticLanguage, languageName, @@ -37,7 +38,6 @@ export default function SettingsScreen() { const paused = useStore((s) => s.paused); const providers = useStore((s) => s.providers); const thisDevice = devices.find((d) => d.is_this_device); - const [name, setName] = useState(thisDevice?.name ?? ""); const [addingRule, setAddingRule] = useState(false); const [ruleText, setRuleText] = useState(""); const [ruleBehavior, setRuleBehavior] = useState<"allow" | "ask">("allow"); @@ -82,11 +82,6 @@ export default function SettingsScreen() { a.id === thisId ? -1 : b.id === thisId ? 1 : Number(!!a.unknown) - Number(!!b.unknown) || a.name.localeCompare(b.name), ); - function commitName() { - if (thisDevice && name.trim() && name.trim() !== thisDevice.name) - void engine.renameDevice(name); - } - function addRule() { if (Platform.OS === "android") { setRuleText(""); @@ -189,17 +184,7 @@ export default function SettingsScreen() { title={t("This phone")} footer={t("How this phone shows up in the Device list on your other Devices.")} > - + {thisDevice ? : null} 64) throw new Error(t("Device names must be 64 characters or fewer.")); + const result = await core.request("device.set_name", { id, name: trimmed }); + if (result !== null) throw new Error(t("Could not rename Device")); + } + /// Joins the identity the pairing string names. The core posts the request (`pair.posted` /// marks that) and waits for the other Device to accept; `signal` aborts the wait in the core too, /// which answers "Pairing cancelled". diff --git a/mobile/src/core/model.ts b/mobile/src/core/model.ts index fd127a3d..18388980 100644 --- a/mobile/src/core/model.ts +++ b/mobile/src/core/model.ts @@ -58,6 +58,8 @@ export interface Device { /// The machine signing public key, base64url. id: string; name: string; + /// The original machine name, before the account's alias. + machine_name?: string; model: string; os: string; os_version: string; diff --git a/mobile/src/i18n/zh.ts b/mobile/src/i18n/zh.ts index e6df2dd0..032e81fd 100644 --- a/mobile/src/i18n/zh.ts +++ b/mobile/src/i18n/zh.ts @@ -364,6 +364,12 @@ export const zh: Record = { "Sad": "难过", "Same as Base": "与基础相同", "Save": "保存", + "Rename…": "重命名…", + "Rename": "重命名", + "Rename Device": "重命名设备", + "Could not rename Device": "无法重命名设备", + "Device names must be 64 characters or fewer.": "设备名称不能超过 64 个字符。", + "Every paired Device shows this name. Leave it blank to use the name the machine goes by.": "所有已配对设备都会显示此名称。留空可恢复设备原本的名称。", "Scan Code": "扫描配对码", "Scared": "害怕", "Search": "搜索", diff --git a/mobile/src/ui/DeviceRename.test.tsx b/mobile/src/ui/DeviceRename.test.tsx new file mode 100644 index 00000000..b803225e --- /dev/null +++ b/mobile/src/ui/DeviceRename.test.tsx @@ -0,0 +1,113 @@ +import { expect, test, vi } from "vitest"; +import type { Device } from "../core/model"; + + // Follow the existing mobile hook-slot boundary; native presentation needs device proof. + type Node = { type: unknown; props: { children?: unknown; value?: { value: string }; onPress?: () => void; onClick?: () => void; onDismissRequest?: () => void } }; + type Button = { text: string; onPress?: (value?: string) => void }; + let slots: unknown[] = [], cursor = 0; + let effects: Array<() => void> = [], cleanups: Array<() => void> = []; + function slot(make: () => T) { const index = cursor++; if (!(index in slots)) slots[index] = make(); return { index, value: slots[index] as T }; } + const react = { + useRef: (value: T) => slot(() => ({ current: value })).value, + useState: (value: T) => { const item = slot(() => value); return [item.value, (next: T) => { slots[item.index] = next; }]; }, + useEffect: (effect: () => () => void) => { const item = slot(() => false); if (!item.value) { slots[item.index] = true; effects.push(() => { cleanups.push(effect()); }); } }, + useSyncExternalStore: (_subscribe: unknown, snapshot: () => unknown) => snapshot(), + useDebugValue: () => {}, + useMemo: (compute: () => T) => compute(), + useCallback: (callback: T) => callback, + }; + vi.doMock("react", () => ({ ...react, default: react })); + const jsx = (type: unknown, props: Node["props"]) => ({ type, props }); + vi.doMock("react/jsx-runtime", () => ({ jsx, jsxs: jsx, Fragment: "Fragment" })); + vi.doMock("react/jsx-dev-runtime", () => ({ jsxDEV: jsx, Fragment: "Fragment" })); + const platform = { OS: "ios" }; + let buttons: Button[] = [], alerts: string[] = []; + vi.doMock("react-native", () => ({ Platform: platform, AppState: { currentState: "active", addEventListener: () => ({ remove() {} }) }, Alert: { + prompt: (_title: string, _message: string, actions: Button[]) => { buttons = actions; }, + alert: (title: string) => { alerts.push(title); }, + } })); + vi.doMock("@expo/ui/jetpack-compose", () => ({ useNativeState: (value: string) => slot(() => ({ value })).value, Column: "Column", Host: "Host", Text: "Text", TextButton: "Button", OutlinedTextField: Object.assign(() => null, { displayName: "Input", Placeholder: "Placeholder" }), AlertDialog: Object.assign(() => null, { displayName: "Dialog", Title: "Title", Text: "Body", ConfirmButton: "Confirm", DismissButton: "Dismiss" }) })); + vi.doMock("@expo/ui/jetpack-compose/modifiers", () => ({ fillMaxWidth: () => ({}) })); + vi.doMock("./forms", () => ({ Row: "Row" })); + vi.doMock("../i18n", () => ({ t: (value: string) => value })); + vi.doMock("expo-web-browser", () => ({})); + vi.doMock("../core/host", () => ({ hostFacts: () => ({}) })); + vi.doMock("../core/prefs", () => ({ coreHome: () => "unused", loadPrefs: () => ({}), savePrefs: () => {}, pathOf: (value: string) => value, wipePrefs: () => {} })); + vi.doMock("../core/push", () => ({ clearPushes: () => {}, installPushHandlers: () => {}, registerForPushes: () => {} })); + const calls: Array<{ method: string; params: unknown }> = []; + let reply: () => Promise = async () => null; + vi.doMock("../../modules/beans-core", () => ({ request: (method: string, params: unknown) => { calls.push({ method, params }); return reply(); } })); + const { useStore } = await import("../core/store"); + const { deviceName } = await import("../core/model"); + const { DeviceRename } = await import("./DeviceRename"); + const device: Device = { id: "target", name: "Alias", machine_name: "Original", model: "", os: "android", os_version: "", machine_key: "target", is_this_device: false, status: "offline", last_seen: 0, unknown: false }; + function find(node: unknown, type: unknown): Node | undefined { + if (Array.isArray(node)) return node.map(child => find(child, type)).find(Boolean); + if (!node || typeof node !== "object" || !("type" in node) || !("props" in node)) return; + const item = node as Node; + return item.type === type || (item.type as { displayName?: unknown } | null)?.displayName === type ? item : find(item.props.children, type); + } + test.each(["ios", "android"])("%s naming targets paired Devices and revokes stale prompts", async os => { + slots = []; cursor = 0; effects = []; cleanups = []; calls.length = 0; alerts = []; platform.OS = os; reply = async () => null; + useStore.setState({ paired: true, identityId: "account", deviceId: "phone", relayUrl: "relay", devices: [device] }); + let root: unknown; + const render = (target = device) => { cursor = 0; root = DeviceRename({ device: target }); for (const effect of effects.splice(0)) effect(); }; + const open = () => { render(); find(root, "Row")!.props.onPress!(); render(); }; + const submit = async (name: string) => { + if (os === "ios") buttons[1]!.onPress!(name); + else { find(root, "Input")!.props.value!.value = name; find(find(root, "Confirm"), "Button")!.props.onClick!(); } + await Promise.resolve(); await Promise.resolve(); await Promise.resolve(); + }; + try { + expect(deviceName(device)).toBe("Alias"); + render({ ...device, unknown: true }); expect(find(root, "Row")).toBeUndefined(); + open(); + if (os === "ios") buttons[0]!.onPress!(); else find(root, "Dialog")!.props.onDismissRequest!(); + expect(calls).toEqual([]); + open(); await submit(" " + "😀".repeat(64) + " "); + expect(calls).toEqual([{ method: "device.set_name", params: { id: "target", name: "😀".repeat(64) } }]); + expect(useStore.getState().devices[0]!.name).toBe("Alias"); + open(); await submit(" "); + expect(calls.at(-1)).toEqual({ method: "device.set_name", params: { id: "target", name: "" } }); + open(); await submit("\uFEFF"); + expect(calls.at(-1)).toEqual({ method: "device.set_name", params: { id: "target", name: "\uFEFF" } }); + const count = calls.length; + open(); await submit("😀".repeat(65)); expect(calls.length).toBe(count); expect(alerts).toContain("Could not rename Device"); + open(); + if (os === "android") find(root, "Input")!.props.value!.value = "stale"; + const staleSubmit = os === "ios" ? () => buttons[1]!.onPress!("stale") : find(find(root, "Confirm"), "Button")!.props.onClick!; + useStore.setState({ identityId: "other" }); useStore.setState({ identityId: "account" }); + staleSubmit(); await Promise.resolve(); expect(calls.length).toBe(count); + open(); + const wrongTarget = os === "ios" ? () => buttons[1]!.onPress!("wrong target") : find(find(root, "Confirm"), "Button")!.props.onClick!; + render({ ...device, id: "other" }); + wrongTarget(); await Promise.resolve(); expect(calls.length).toBe(count); + render(); + const { promise, reject } = Promise.withResolvers(); + reply = () => promise; + open(); await submit("pending"); + const before = alerts.length; + useStore.setState({ relayUrl: "other" }); useStore.setState({ relayUrl: "relay" }); + reject(new Error("old account failure")); await Promise.resolve(); await Promise.resolve(); await Promise.resolve(); + expect(alerts.length).toBe(before); + const failure = Promise.withResolvers(); + reply = () => failure.promise; + open(); + const dismiss = os === "android" ? find(root, "Dialog")!.props.onDismissRequest : undefined; + await submit("retry"); + dismiss?.(); + failure.reject(new Error("current failure")); + await Promise.resolve(); await Promise.resolve(); await Promise.resolve(); + expect(alerts.length).toBe(before + 1); + open(); + const removed = os === "ios" ? () => buttons[1]!.onPress!("removed") : find(find(root, "Confirm"), "Button")!.props.onClick!; + const admitted = calls.length; + useStore.setState({ devices: [] }); useStore.setState({ devices: [device] }); + removed(); await Promise.resolve(); expect(calls.length).toBe(admitted); + open(); + const changedOs = os === "ios" ? () => buttons[1]!.onPress!("changed OS") : find(find(root, "Confirm"), "Button")!.props.onClick!; + useStore.setState({ devices: [{ ...device, os: "ios" }] }); + useStore.setState({ devices: [device] }); + changedOs(); await Promise.resolve(); expect(calls.length).toBe(admitted); + } finally { for (const cleanup of cleanups) cleanup(); } + }); diff --git a/mobile/src/ui/DeviceRename.tsx b/mobile/src/ui/DeviceRename.tsx new file mode 100644 index 00000000..96236c41 --- /dev/null +++ b/mobile/src/ui/DeviceRename.tsx @@ -0,0 +1,103 @@ +import { useNativeState, AlertDialog, Column, Host, OutlinedTextField, Text as ComposeText, TextButton } from "@expo/ui/jetpack-compose"; +import { fillMaxWidth } from "@expo/ui/jetpack-compose/modifiers"; +import { useEffect, useRef, useState } from "react"; +import { Alert, Platform } from "react-native"; +import { engine } from "../core/engine"; +import { deviceName, type Device } from "../core/model"; +import { useStore } from "../core/store"; +import { t } from "../i18n"; +import { Row } from "./forms"; + +type Attempt = { active: boolean; submitted: boolean; id: string; name: string }; + +/** Native prompts retain their original account and selected Device, including across awaits. */ +export function DeviceRename({ device }: { device: Device }) { + const [dialog, setDialog] = useState(null); + const authority = useStore(state => state); + const text = useNativeState(""); + const current = useRef(null); + const selected = useRef(device.id); + if (selected.current !== device.id) { + if (current.current) current.current.active = false; + selected.current = device.id; + } + useEffect(() => { + const unsubscribe = useStore.subscribe((state, previous) => { + const target = state.devices.find(item => item.id === selected.current); + const prior = previous.devices.find(item => item.id === selected.current); + if (state.identityId !== previous.identityId || state.deviceId !== previous.deviceId + || state.relayUrl !== previous.relayUrl || state.paired !== previous.paired + || !target || target.unknown || target.machine_key !== prior?.machine_key || target.os !== prior?.os) { + if (current.current) current.current.active = false; + setDialog(null); + } + }); + return () => { + unsubscribe(); + if (current.current) current.current.active = false; + }; + }, []); + + function valid(attempt: Attempt) { + const state = useStore.getState(); + return attempt.active && current.current === attempt && selected.current === attempt.id + && state.paired && state.devices.some(item => item.id === attempt.id && !item.unknown); + } + function cancel(attempt: Attempt) { + if (attempt.submitted) return; + attempt.active = false; + setDialog(null); + } + async function submit(attempt: Attempt, value: string) { + if (!valid(attempt) || attempt.submitted) return; + attempt.submitted = true; + setDialog(null); + const name = value; + if (name === attempt.name) return; + try { + await engine.setDeviceName(attempt.id, name); + } catch (error: unknown) { + if (valid(attempt)) Alert.alert(t("Could not rename Device"), error instanceof Error ? error.message : t("Could not rename Device")); + } + } + function open() { + if (current.current) current.current.active = false; + const state = useStore.getState(); + if (selected.current !== device.id || state.identityId !== authority.identityId + || state.deviceId !== authority.deviceId || state.relayUrl !== authority.relayUrl + || state.paired !== authority.paired) return; + const attempt: Attempt = { active: true, submitted: false, id: device.id, name: device.name }; + current.current = attempt; + if (!valid(attempt)) return; + if (Platform.OS === "ios") { + Alert.prompt(t("Rename Device"), t("Every paired Device shows this name. Leave it blank to use the name the machine goes by."), [ + { text: t("Cancel"), style: "cancel", onPress: () => cancel(attempt) }, + { text: t("Rename"), onPress: (value?: string) => { void submit(attempt, value ?? ""); } }, + ], "plain-text", device.name); + } else { + text.value = device.name; + setDialog(attempt); + } + } + if (device.unknown) return null; + return <> + + {Platform.OS === "android" && dialog?.active && dialog.id === device.id ? ( + + cancel(dialog)}> + {t("Rename Device")} + + + {t("Every paired Device shows this name. Leave it blank to use the name the machine goes by.")} + + {device.machine_name || device.name} + + + + { void submit(dialog, text.value); }}>{t("Rename")} + cancel(dialog)}>{t("Cancel")} + + + ) : null} + ; +}