From c112eda89295aacf43564727df04c5e424da1d75 Mon Sep 17 00:00:00 2001 From: Heitor Ramon Ribeiro Date: Thu, 5 Nov 2026 22:33:50 -0300 Subject: [PATCH 1/4] feat(mobile): edit Device aliases with native prompt ownership --- docs/architecture/phone-app.md | 2 +- docs/architecture/phone-interface.md | 2 + mobile/app/settings/device/[id].tsx | 2 + mobile/app/settings/index.tsx | 21 +---- mobile/src/core/engine.ts | 8 ++ mobile/src/core/model.ts | 2 + mobile/src/i18n/zh.ts | 6 ++ mobile/src/ui/DeviceRename.test.tsx | 124 +++++++++++++++++++++++++++ mobile/src/ui/DeviceRename.tsx | 103 ++++++++++++++++++++++ 9 files changed, 251 insertions(+), 19 deletions(-) create mode 100644 mobile/src/ui/DeviceRename.test.tsx create mode 100644 mobile/src/ui/DeviceRename.tsx diff --git a/docs/architecture/phone-app.md b/docs/architecture/phone-app.md index 5671f85e..3af07e69 100644 --- a/docs/architecture/phone-app.md +++ b/docs/architecture/phone-app.md @@ -13,7 +13,7 @@ Phone release versions come from the root package; EAS remote versions own store 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`. `bun 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 `bun 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 dd7e9361..92e9f465 100644 --- a/docs/architecture/phone-interface.md +++ b/docs/architecture/phone-interface.md @@ -12,6 +12,8 @@ The composer retains text, attachments, mention picks and reply in a process-mem 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 39d3eb7b..0b1ee4f4 100644 --- a/mobile/app/settings/index.tsx +++ b/mobile/app/settings/index.tsx @@ -8,12 +8,13 @@ import { engine } from "../../src/core/engine"; import { CUSTOM_PRESETS, customProviderNamed, deviceName, isCustomProvider, isRunner, providerLabel } from "../../src/core/model"; import { deviceIsOnline, useStore } from "../../src/core/store"; 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, @@ -36,7 +37,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"); @@ -79,11 +79,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(""); @@ -186,17 +181,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 d5b87494..aa4d3399 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 c2027c5a..7984d2f9 100644 --- a/mobile/src/i18n/zh.ts +++ b/mobile/src/i18n/zh.ts @@ -358,6 +358,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..cc8a7f36 --- /dev/null +++ b/mobile/src/ui/DeviceRename.test.tsx @@ -0,0 +1,124 @@ +import { expect, mock, test } from "bun:test"; +import { fileURLToPath } from "node:url"; +import type { Device } from "../core/model"; + +if (process.env.BEANS_DEVICE_RENAME_HOST === "1") install(); +else test("Device naming consumer in an isolated Bun host", () => { + const child = Bun.spawnSync([process.execPath, "test", "--isolate", fileURLToPath(import.meta.url)], { + env: { ...process.env, BEANS_DEVICE_RENAME_HOST: "1" }, stdout: "pipe", stderr: "pipe", + }); + expect(child.exitCode, child.stdout.toString() + child.stderr.toString()).toBe(0); +}); + +function install() { + // 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, + }; + mock.module("react", () => ({ ...react, default: react })); + const jsx = (type: unknown, props: Node["props"]) => ({ type, props }); + mock.module("react/jsx-runtime", () => ({ jsx, jsxs: jsx, Fragment: "Fragment" })); + mock.module("react/jsx-dev-runtime", () => ({ jsxDEV: jsx, Fragment: "Fragment" })); + const platform = { OS: "ios" }; + let buttons: Button[] = [], alerts: string[] = []; + mock.module("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); }, + } })); + mock.module("@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" }) })); + mock.module("@expo/ui/jetpack-compose/modifiers", () => ({ fillMaxWidth: () => ({}) })); + mock.module("./forms", () => ({ Row: "Row" })); + mock.module("../i18n", () => ({ t: (value: string) => value })); + mock.module("expo-web-browser", () => ({})); + mock.module("../core/host", () => ({ hostFacts: () => ({}) })); + mock.module("../core/prefs", () => ({ coreHome: () => "unused", loadPrefs: () => ({}), savePrefs: () => {}, pathOf: (value: string) => value, wipePrefs: () => {} })); + mock.module("../core/push", () => ({ clearPushes: () => {}, installPushHandlers: () => {}, registerForPushes: () => {} })); + const calls: Array<{ method: string; params: unknown }> = []; + let reply: () => Promise = async () => null; + mock.module("../../modules/beans-core", () => ({ request: (method: string, params: unknown) => { calls.push({ method, params }); return reply(); } })); + const { useStore }: typeof import("../core/store") = require("../core/store"); + const { deviceName }: typeof import("../core/model") = require("../core/model"); + const { DeviceRename }: typeof import("./DeviceRename") = require("./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 replaced = os === "ios" ? () => buttons[1]!.onPress!("replaced") : find(find(root, "Confirm"), "Button")!.props.onClick!; + useStore.setState({ devices: [{ ...device, machine_key: "replacement" }] }); + useStore.setState({ devices: [device] }); + replaced(); 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} + ; +} From 2afac336f7c82bc9dd2723e123ffe83ea149472c Mon Sep 17 00:00:00 2001 From: Heitor Ramon Ribeiro Date: Fri, 6 Nov 2026 11:51:58 +0000 Subject: [PATCH 2/4] chore(tooling): propagate reviewed Beans AI tooling --- .codegraph-version | 1 + .codegraph/.gitignore | 5 +++ AGENTS.md | 2 + docs/ai-tooling.md | 86 +++++++++++++++++++++++++++++++++++++++++++ scripts/codegraph.sh | 17 +++++++++ 5 files changed, 111 insertions(+) create mode 100644 .codegraph-version create mode 100644 .codegraph/.gitignore create mode 100644 docs/ai-tooling.md create mode 100755 scripts/codegraph.sh diff --git a/.codegraph-version b/.codegraph-version new file mode 100644 index 00000000..fdd3be6d --- /dev/null +++ b/.codegraph-version @@ -0,0 +1 @@ +1.6.2 diff --git a/.codegraph/.gitignore b/.codegraph/.gitignore new file mode 100644 index 00000000..d20c0fe4 --- /dev/null +++ b/.codegraph/.gitignore @@ -0,0 +1,5 @@ +# CodeGraph data files — local to each machine, not for committing. +# Ignore everything in .codegraph/ except this file itself, so transient +# files (the database, daemon.pid, sockets, logs) never show up in git. +* +!.gitignore diff --git a/AGENTS.md b/AGENTS.md index a6f3edd8..e4ffb564 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,5 +1,7 @@ # Beans +For T3 onboarding, retrieval, command output and model reservations, follow [AI tooling](docs/ai-tooling.md). Product work remains HOLD until Heitor explicitly says OK. + Read [ARCHITECTURE.md](./ARCHITECTURE.md) before writing code, then the subject docs it lists for the parts you change. Identity is a local key pair. Paired Devices sync through an E2E relay. Provider credentials belong to the account: they sync to every paired Device as a blob encrypted with the account key. The AppKit app talks to the local CLI. diff --git a/docs/ai-tooling.md b/docs/ai-tooling.md new file mode 100644 index 00000000..b781f692 --- /dev/null +++ b/docs/ai-tooling.md @@ -0,0 +1,86 @@ +# Prepare and use AI tooling + +Read [AGENTS.md](../AGENTS.md), [BEANS.md](../BEANS.md) and [ARCHITECTURE.md](../ARCHITECTURE.md) before changing Beans. `CLAUDE.md` points to `AGENTS.md`; preserve that link and all existing instructions. + +## Keep product work on HOLD + +This preparation permits onboarding, tooling installation, independently reviewed tooling PRs, normal tooling merges and branch propagation. Product work remains HOLD until Heitor explicitly says OK. Green checks, a tooling merge and completed propagation do not release product work. Do not merge product PRs during this rollout. + +The central coordinator owns global settings and routing. Read `/Users/heitor/.config/ai-tooling/COORDINATION.md` and the current `GLOBAL-ROLLOUT.md` linked there. Report global configuration gaps to that coordinator. Keep one external rollout REPORT with commands, exit codes, receipt hashes, exact heads, resources and blockers. + +Target `bloodf/beans` explicitly for GitHub operations. `origin` is the Beans repository; `upstream` is `egoist/lorca`. T3's upstream canonical identity does not authorize upstream publication or integration. Confirm remotes, branch, HEAD, current base, worktrees and dirty state before writing. Similar source content does not prove ancestry. + +Preserve all refs with a verified Git bundle before propagation. Save staged and unstaged patches, untracked files and their hashes separately. Use an isolated tooling checkout. Preserve existing worktrees and previous work. Do not use automatic stash, `reset --hard`, force push or shared cleanup. + +## Retrieve source with CodeGraph 1.6.2 + +The standalone CLI is pinned by `.codegraph-version`. `scripts/codegraph.sh` checks the installed version, disables telemetry for its process and runs from this checkout's root. Keep CodeGraph outside application dependencies. + +Use the existing installation when it matches the pin. For workstation installation, inspect the installer at `https://raw.githubusercontent.com/colbymchenry/codegraph/f72c9d2efb14454ff4f9fd7b8460abd82f19a287/install.sh`, then run the inspected file with `CODEGRAPH_VERSION=v1.6.2`. Installation and user-specific MCP configuration belong to the central coordinator. + +Run these commands from the repository root: + +```sh +sh scripts/codegraph.sh init --yes +sh scripts/codegraph.sh sync +sh scripts/codegraph.sh status --json +sh scripts/codegraph.sh query dispatch --limit 5 --json +sh scripts/codegraph.sh callers dispatch --file crates/cli/src/api.rs --limit 5 --json +sh scripts/codegraph.sh explore --max-files 3 'api dispatch websocket serve' +``` + +Start with a bounded query before broad source reads. For exact text, missing results or unsupported syntax, use bounded `rg` and exact file ranges. Inspect the actual definition and caller before changing a flow. A graph relationship does not prove runtime behavior or complete dynamic call coverage. + +Each worktree has its own `.codegraph/` index. Do not copy databases between checkouts. Run `sync` and inspect `status --json` after checkout or edits. Check indexed languages, file/node counts, pending changes, worktree mismatch and index completion. Rebuild with `index` after changing include/exclude/extension rules. Version 1.6.2 has no `--strict` flag. + +Track only `.codegraph/.gitignore` inside `.codegraph/`. The ignore file excludes databases, logs, sockets, locks and daemon state. Never commit generated graphs or index data. With a configured CodeGraph MCP, keep the default single `codegraph_explore` tool; otherwise use the same bounded CLI commands. + +## Preserve command status with RTK 1.0.1 + +Read `/Users/heitor/.codex/RTK.md` when present. With a native RTK PreToolUse hook, run normal commands and do not wrap them twice. Without a native hook, use supported explicit commands such as `rtk git status` and `rtk gh pr list --repo bloodf/beans`. MiniMax uses this CLI route. Do not assume one harness's hooks apply to another. + +Preserve the actual exit code and first failure receipt. If condensed output is empty, contradictory or unusable, recover it with `rtk bypass ` or the stored raw receipt. Diagnose the first failure before another attempt. Do not weaken a check, timeout, baseline, security boundary or review requirement to obtain green results. + +## Use Caveman and Ponytail + +Use concise, complete Portuguese sentences with the user. Keep errors, identifiers, numbers and negations exact. Write code, persisted documents and critical instructions in complete language. + +Inspect the affected flow and callers, reuse existing code and standard libraries, and make the smallest complete change. Verify behavior at the relevant boundary. Preserve security, accessibility, approval, encryption and data-loss controls. Installation, synthetic probes, local checks, hosted checks and live behavior are separate evidence. + +## Verify TokenEconomizer per harness + +Reuse the central installation. Preserve the mode without auxiliary paid model calls: `microskills=envfacts`, `loopguard=off`, `repomap=off` and `toolprune=propose`. Do not set a paid model or enable paid proposers. Keep orchestration, review, device and required verification tools available; proposals cannot override project policy. + +From the checkout, inspect effective state without a model call: + +```sh +"${TOKENECONOMIZER_HOME:-$HOME/.tokeneconomizer}/bin/te" --host codex --cwd "$PWD" status +"${TOKENECONOMIZER_HOME:-$HOME/.tokeneconomizer}/bin/te" --host codex --cwd "$PWD" config show +"${TOKENECONOMIZER_HOME:-$HOME/.tokeneconomizer}/bin/te" --host codex --cwd "$PWD" repos list +``` + +Confirm the repository identity is the Beans origin and verify a worktree maps to that same repository. Record the installed adapter's supported events for each harness actually used. Codex's installed hook file declares `SessionStart`, `UserPromptSubmit`, `PostToolUse`, `Stop` and `SessionEnd`; declaration alone does not prove delivery through T3. + +Separate configuration present from fresh-session runtime proof. Loading a skill, starting a process or seeing a zero-session status does not prove the full lifecycle. Record unproved events as UNKNOWN. Do not invent adapters or hook support for Antigravity, MiniMax or another harness. TokenEconomizer learns repository facts and proposes tool pruning; it is not a generic output compressor. No local token savings are claimed without measurement. + +## Reserve every worker through the central dispatcher + +Before each tooling worker, reserve a route: + +```sh +t3-model-route reserve --project beans --purpose tooling --task '' +``` + +Launch only the exact returned provider, model and options through the applicable T3 delegation mechanism. Antigravity accepts Google models only. MiniMax M3.1 Flash requires `m:minimax:MiniMax-M3.1-Flash:v:thinking`. Quota UNKNOWN is not proof of capacity. Never substitute another project, provider or model, retry quota blindly, edit the global helper or implement a local round robin. + +Give each worker exact scope and file ownership. State that concurrent work must be preserved. Record the lease, task/run, provider, model and terminal outcome. Release only the exact lease after terminal evidence. Start no top-level thread for a worker. Use a fresh independent reviewer for each review or re-check, with the exact base/head and applicable risk requirements. No author approves their own change. + +## Verify and propagate tooling + +Keep the existing Beans gates. `bun run check:docs`, `bun run check:catalog` and the same-repository PR test matrix remain applicable. Inspect the current workflow definitions before execution; a local tooling smoke does not replace hosted checks. Product homes, accounts, relays, signing inputs and deployments are not tooling fixtures. + +Create one tooling PR against current Beans `main` and link it immediately to T3. Merge only after independent exact-head review and the real required checks pass. When waiting for hosted checks, use T3's PR watch and end the run; do not poll CI. + +Before propagation, prepare a per-ref plan with original head, target payload, old-head ancestry proof and recovery instructions. Append only tooling to every existing local and origin branch, including historical branches and open PR heads. Preserve each branch's existing instruction and ignore bytes. Do not merge unrelated product history, silently resolve divergence or recreate a branch absent from the server. Push fast-forward with explicit refspecs. Stop on the first remote write failure, re-read remote state and report to central before retry or a strategy change. + +Recheck current remote and PR heads, rescan for new refs, validate indexes in used checkouts and settle owned processes and leases. Record any uncovered ref as BLOCKED with a concrete reason. Product work still waits for Heitor's explicit OK. diff --git a/scripts/codegraph.sh b/scripts/codegraph.sh new file mode 100755 index 00000000..d6aa27fb --- /dev/null +++ b/scripts/codegraph.sh @@ -0,0 +1,17 @@ +#!/bin/sh +# Run from any directory with the repository's reviewed CodeGraph version. +set -eu +codegraph_root=$(CDPATH= cd "$(dirname "$0")/.." && pwd) +cd "$codegraph_root" +codegraph_expected=$(cat .codegraph-version) +if ! command -v codegraph >/dev/null 2>&1; then + echo "CodeGraph $codegraph_expected required. See docs/ai-tooling.md." >&2 + exit 1 +fi +codegraph_actual=$(codegraph --version) +if [ "$codegraph_actual" != "$codegraph_expected" ]; then + echo "CodeGraph $codegraph_expected required; found $codegraph_actual. See docs/ai-tooling.md." >&2 + exit 1 +fi +export CODEGRAPH_TELEMETRY=0 +exec codegraph "$@" From c054ea8974ec1cd94ae3239e49472de9e7dd744b Mon Sep 17 00:00:00 2001 From: Heitor Ramon Ribeiro Date: Sat, 7 Nov 2026 03:15:22 -0300 Subject: [PATCH 3/4] test: use reachable device metadata transition --- mobile/src/ui/DeviceRename.test.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/mobile/src/ui/DeviceRename.test.tsx b/mobile/src/ui/DeviceRename.test.tsx index cc8a7f36..52ded303 100644 --- a/mobile/src/ui/DeviceRename.test.tsx +++ b/mobile/src/ui/DeviceRename.test.tsx @@ -115,10 +115,10 @@ function install() { useStore.setState({ devices: [] }); useStore.setState({ devices: [device] }); removed(); await Promise.resolve(); expect(calls.length).toBe(admitted); open(); - const replaced = os === "ios" ? () => buttons[1]!.onPress!("replaced") : find(find(root, "Confirm"), "Button")!.props.onClick!; - useStore.setState({ devices: [{ ...device, machine_key: "replacement" }] }); + 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] }); - replaced(); await Promise.resolve(); expect(calls.length).toBe(admitted); + changedOs(); await Promise.resolve(); expect(calls.length).toBe(admitted); } finally { for (const cleanup of cleanups) cleanup(); } }); } From 48884fa375f66aad48f420a5f960083e37cd3763 Mon Sep 17 00:00:00 2001 From: Heitor Ramon Ribeiro Date: Sat, 7 Nov 2026 17:37:44 -0300 Subject: [PATCH 4/4] docs: move phone build and identity details into phone subject --- ARCHITECTURE.md | 4 ++-- docs/architecture/phone-app.md | 4 ++++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 579db40c..7410dd72 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -128,7 +128,7 @@ beans/ .github/workflows/ # release.yml: manual signed Beans releases; test.yml: full PR/manual test matrix; docs.yml: PR/manual doc check; catalog.yml: PR/manual catalog/index check ``` -`pnpm run android` rebuilds the Rust core for Android, then builds and runs the Expo dev client on the Android emulator. `cd mobile && pnpm run core` rebuilds the Rust core for both phone platforms; `pnpm run mobile:dev` is the iOS development loop described below. +See [Phone development](docs/architecture/phone-app.md#development-loop) for phone rebuild commands. `pnpm run dev` runs the macOS Beans Dev loop; `pnpm run build` produces the Beans release bundle. See [macOS development and builds](docs/architecture/macos-app.md#development-and-builds) for rebuild, launch and SDK-stamping mechanisms. `pnpm run relay` runs a local relay. The [phone development loop](docs/architecture/phone-app.md#development-loop) fingerprints native inputs, rebuilds stale pieces and leaves production Beans processes alone. @@ -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 af97f15e..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. @@ -56,4 +58,6 @@ The production app icon uses the coral Beans mark. Editable SVG masters in `desi ## Development loop +`pnpm run android` rebuilds the Rust core for Android, then builds and runs the Expo dev client on the Android emulator. `cd mobile && pnpm run core` rebuilds the Rust core for both phone platforms; `pnpm run mobile:dev` is the iOS development loop described here. + `pnpm run mobile:dev` (`scripts/mobile.ts`) is the Beans Dev phone loop on the iOS Simulator, or on `--device `: it fingerprints the crates the phone links, the prebuild inputs (Expo config, assets, `package.json`, plugins, targets), the pod inputs with the checkout's path, and the native module sources (stamps in `mobile/.expo/dev-stamps.json`), rebuilds what is stale (`pnpm run core ios`, a clean `expo prebuild`, `pod install`, `expo run:ios`), starts Metro, and opens the dev client on it. A Rust save while it runs rebuilds the core and installs the app again. The Mac and phone loops leave production Beans processes alone, so all builds run side by side.