diff --git a/desktop/src/l10n/zh.ts b/desktop/src/l10n/zh.ts index 9005dbf2..828cb8f3 100644 --- a/desktop/src/l10n/zh.ts +++ b/desktop/src/l10n/zh.ts @@ -636,6 +636,9 @@ export const zh: Record = { "Remove…": "移除…", "Removing…": "正在移除…", "Rename": "重命名", + "Rename Device": "重命名设备", + "Leave blank to use the machine name.": "留空以使用机器名称。", + "Device names must be at most 64 characters": "设备名称最多为 64 个字符", "Rename Chat": "重命名聊天", "Rename Chat…": "重命名聊天…", "Rename…": "重命名…", diff --git a/desktop/src/model/deviceNames.test.ts b/desktop/src/model/deviceNames.test.ts new file mode 100644 index 00000000..c4710a59 --- /dev/null +++ b/desktop/src/model/deviceNames.test.ts @@ -0,0 +1,36 @@ +import { beforeAll, expect, test } from "vitest"; +import type { AppStore } from "./store"; + +let Store: typeof AppStore; +beforeAll(async () => { + const location = Object.getOwnPropertyDescriptor(globalThis, "location"); + Object.defineProperty(globalThis, "location", { configurable: true, value: { search: "?platform=linux" } }); + try { Store = (await import("./store")).AppStore; } + finally { + if (location) Object.defineProperty(globalThis, "location", location); + else Reflect.deleteProperty(globalThis, "location"); + } +}); + +test("Device aliases preserve original names, reset blank input, and reject revoked ownership", async () => { + class DemoStore extends Store { override get isMock() { return true; } } + const store = new DemoStore(); + store.isConnected = true; + store.hasIdentity = true; + store.identityID = "account-a"; + store.devices = [{ id: "peer", name: "Original", model: "PC", os: "linux", osVersion: "", isThisDevice: false, status: "offline", lastSeen: 0, machineKey: "key", plugins: [], version: "" }]; + const owner = store.deviceNamingOwner("peer"); + await store.setDeviceName("peer", "Office", owner); + expect(store.device("peer")).toMatchObject({ name: "Office", machineName: "Original" }); + await store.setDeviceName("peer", "", owner); + expect(store.device("peer")).toMatchObject({ name: "Original", machineName: "Original" }); + store.identityID = "account-b"; + expect(owner()).toBe(false); + await store.setDeviceName("peer", "Wrong account", owner); + expect(store.device("peer")?.name).toBe("Original"); + const cancelled = store.deviceNamingOwner("peer"); + await store.setDeviceName("peer", "Cancelled", () => false); + expect(store.device("peer")?.name).toBe("Original"); + store.devices = []; + expect(cancelled()).toBe(false); +}); diff --git a/desktop/src/model/models.ts b/desktop/src/model/models.ts index 268b821a..a38d60d5 100644 --- a/desktop/src/model/models.ts +++ b/desktop/src/model/models.ts @@ -475,6 +475,8 @@ export function deviceStatusLabel(status: DeviceStatus): string { export interface Device { id: string; name: string; + /** Original machine-reported name, separate from the account alias. */ + machineName?: string; model: string; os: DeviceOS; osVersion: string; diff --git a/desktop/src/model/store.ts b/desktop/src/model/store.ts index 887ed402..82ee0263 100644 --- a/desktop/src/model/store.ts +++ b/desktop/src/model/store.ts @@ -332,6 +332,7 @@ export class AppStore { private started = false; private startupTimer: ReturnType | null = null; private bootstrapGeneration = 0; + private deviceNamingGeneration = 0; private isBootstrapping = true; private bootstrapEvents: { name: string; data: unknown }[] = []; private isApplyingBootstrap = false; @@ -788,6 +789,7 @@ export class AppStore { private emit(event: StoreEvent): void { if (this.isApplyingBootstrap) return; + if (event.kind === "snapshotReplaced" || event.kind === "identityChanged" || event.kind === "connectionChanged") this.deviceNamingGeneration++; for (const listener of [...this.listeners]) listener(event); } @@ -1969,6 +1971,38 @@ export class AppStore { return created.phrase; } + /** Captures account, snapshot, connection and target ownership for a naming prompt. */ + deviceNamingOwner(id: string): () => boolean { + const identity = this.identityID, generation = this.deviceNamingGeneration; + const target = this.device(id), key = target?.machineKey, os = target?.os; + return () => { + const current = this.device(id); + return this.isConnected && this.hasIdentity === true && (this.isMock || !!identity) + && identity === this.identityID && generation === this.deviceNamingGeneration + && !!current && current.os !== "unknown" && current.machineKey === key && current.os === os; + }; + } + + /** Sets an account alias; confirmed blank input resets to the machine-reported name. */ + async setDeviceName(id: string, name: string, owns: () => boolean): Promise { + const admitted = this.deviceNamingOwner(id); + if (!owns() || !admitted()) return; + if (!this.isMock) { + await this.request("device.set_name", { id, name }); + if (!owns() || !admitted()) return; + return; + } + const trimmed = name.trim(); + if (Array.from(trimmed).length > 64) throw new RequestError(L("Device names must be at most 64 characters")); + if (!owns()) return; + this.devices = this.devices.map((device) => { + if (device.id !== id) return device; + const machineName = device.machineName ?? device.name; + return { ...device, machineName, name: trimmed || machineName }; + }); + this.emit({ kind: "rosterChanged" }); + } + /** Unpairs another Device. The CLI has the relay drop its key; the Device wipes its copy of the * account the next time it connects. Throws when the relay could not be told. */ async unpairDevice(id: string): Promise { diff --git a/desktop/src/model/wire.ts b/desktop/src/model/wire.ts index c63c42e8..a4ab1192 100644 --- a/desktop/src/model/wire.ts +++ b/desktop/src/model/wire.ts @@ -92,6 +92,7 @@ export interface WireParsedServers { export interface WireDevice { id: string; name: string; + machine_name?: string; model: string; os: string; os_version: string; @@ -490,6 +491,7 @@ export function toDevice(wire: WireDevice): Device { return { id: wire.id, name: wire.unknown ? L("Unknown Device") : wire.name, + machineName: wire.machine_name ?? wire.name, model: wire.model, os: wire.unknown ? "unknown" : (oses as string[]).includes(wire.os) ? (wire.os as DeviceOS) : "linux", osVersion: wire.os_version, diff --git a/desktop/src/ui/settings/deviceNames.browser.tsx b/desktop/src/ui/settings/deviceNames.browser.tsx new file mode 100644 index 00000000..269fdbb6 --- /dev/null +++ b/desktop/src/ui/settings/deviceNames.browser.tsx @@ -0,0 +1,83 @@ +import { flush } from "solid-js"; +import { render } from "@solidjs/web"; +import { setLanguage } from "../../l10n"; +import { store } from "../../model/store"; +import type { WireSnapshot } from "../../model/wire"; +import { settingsDeviceID } from "../root"; +import { SheetHost } from "../overlay"; +import { SettingsPage } from "./panes"; + +export async function checkDeviceNamingConsumer() { + const assert = (value: unknown, message: string) => { if (!value) throw new Error(message); }; + const settle = async () => { await Promise.resolve(); flush(); await new Promise((r) => setTimeout(r, 0)); flush(); }; + setLanguage("en"); + Object.defineProperty(store, "isMock", { configurable: true, get: () => false }); + const events = store as unknown as { handle(name: string, data: unknown): void }; + const snapshot = (identity = "account-a"): WireSnapshot => ({ + version: "fixture", identity_id: identity, has_identity: true, is_identity_device: true, + relay_connected: false, running_chat_ids: [], bots: [], chats: [], devices: ["peer", "other"].map((id) => ({ + id, name: "Original", machine_name: "Machine", model: "PC", os: "linux", os_version: "", + is_this_device: false, status: "offline", last_seen: 0, machine_key: id, plugins: [], version: "fixture", + })), + }); + events.handle("snapshot", snapshot()); + store.setConnected(true); + const calls: { method: string; params: Record }[] = []; + let resolve!: (value: unknown) => void; + let reject!: (error: Error) => void; + Object.defineProperty(store, "transport", { configurable: true, value: { + request: (method: string, params: Record) => { + calls.push({ method, params }); + return new Promise((yes, no) => { resolve = yes; reject = no; }); + }, + } }); + const root = document.createElement("div"); + root.id = "root"; + document.body.append(root); + settingsDeviceID.set("peer"); + const dispose = render(() => <>, root); + const button = (text: string) => [...document.querySelectorAll("button")].find((x) => x.textContent?.trim() === text); + const dialogs = () => document.querySelectorAll("[role=dialog]").length; + const open = async () => { + await settle(); + const rename = button("Rename…"); + assert(rename, "Device pane has no Rename action"); rename!.click(); await settle(); + assert(dialogs() === 1, "Naming prompt did not mount"); + const input = document.querySelector("[role=dialog] input")!; + assert(input?.value === "Original" && input.placeholder === "Machine", "Alias and machine names are not distinct"); + return input; + }; + const submit = async (value: string) => { + const input = await open(); input.value = value; input.dispatchEvent(new Event("input", { bubbles: true })); await settle(); + button("Rename")!.click(); await settle(); + assert(button("Rename")!.disabled, "Pending alias can be submitted twice"); + }; + try { + await submit(""); + assert(calls.length === 1 && calls[0]!.method === "device.set_name" && calls[0]!.params.id === "peer" && calls[0]!.params.name === "", `Blank reset did not reach the real store transport: ${JSON.stringify(calls)}`); + resolve(null); await settle(); assert(dialogs() === 0, "Accepted alias did not close prompt"); + await submit("Office"); reject(new Error("Synthetic refusal")); await settle(); + assert(document.querySelector("[role=alert]")?.textContent?.includes("Synthetic refusal"), "Current refusal is not visible"); + assert(document.querySelector("[role=dialog] input")?.value === "Office", "Refusal discarded the draft"); + button("Cancel")!.click(); await settle(); + for (const transition of ["account", "reconnect", "target", "cancel"] as const) { + settingsDeviceID.set("peer"); events.handle("snapshot", snapshot()); store.setConnected(true); await settle(); + const owner = store.deviceNamingOwner("peer"); + await submit("Pending"); + if (transition === "account") { events.handle("snapshot", snapshot("account-b")); events.handle("snapshot", snapshot()); } + if (transition === "reconnect") { store.setConnected(false); store.setConnected(true); } + if (transition === "target") settingsDeviceID.set("other"); + if (transition === "cancel") button("Cancel")!.click(); + await settle(); assert(dialogs() === 0, `${transition} retained the prompt`); + reject(new Error("Late refusal")); await settle(); + assert(!document.querySelector("[role=alert]"), `${transition} published a stale failure`); + assert(store.device("peer")?.name === "Original", `${transition} changed a replacement view`); + if (transition === "account" || transition === "reconnect") { + assert(!owner(), `${transition} restored stale ownership`); + const before = calls.length; await store.setDeviceName("peer", "Late", owner); + assert(calls.length === before, `${transition} admitted a stale request`); + } + } + return { reset: "transport verified", refusal: "draft retained", transitions: 4, lateErrors: "suppressed", accountABA: "rejected" }; + } finally { dispose(); root.remove(); } +} diff --git a/desktop/src/ui/settings/panes.tsx b/desktop/src/ui/settings/panes.tsx index 42ebc071..274b2b17 100644 --- a/desktop/src/ui/settings/panes.tsx +++ b/desktop/src/ui/settings/panes.tsx @@ -2,7 +2,7 @@ // controllers: section cards and footnotes in one scrolling column, the window's title bar carrying // the page title. General and Advanced also fill the small Settings window onboarding opens. -import { createEffect, createMemo, createSignal, For, onSettled, Show } from "solid-js"; +import { createEffect, createMemo, createSignal, For, onCleanup, onSettled, Show } from "solid-js"; import type { JSX } from "@solidjs/web"; import { files, host, hostInfo, onUpdaterChanged, preferences, setPreferences, type UpdaterState } from "../../host"; import { parseCLIPort } from "../../host/cliPort"; @@ -29,7 +29,7 @@ import { import { onStoreEvent, track } from "../../model/reactive"; import { errorText, store } from "../../model/store"; import { newBot, presentMarketplace } from "../actions"; -import { HoverButton, PopUpButton, Switch, TextArea } from "../controls"; +import { HoverButton, PopUpButton, Switch, TextArea, TextField } from "../controls"; import { Icon } from "../icons"; import { alert, presentSheet, Sheet } from "../overlay"; import { open, revealed, settingsDeviceID } from "../root"; @@ -773,9 +773,49 @@ function StatusDot(props: { status: Device["status"] }) { return ; } +function DeviceNamePrompt(props: { device: Device; owns: () => boolean; dismiss: () => void }) { + const [name, setName] = createSignal(props.device.name); + const [busy, setBusy] = createSignal(false); + const [error, setError] = createSignal(null); + const stop = store.subscribe(() => { if (!props.owns()) props.dismiss(); }); + onCleanup(stop); + const save = async () => { + if (busy() || !props.owns()) return; + setBusy(true); + setError(null); + try { + await store.setDeviceName(props.device.id, name(), props.owns); + if (props.owns()) props.dismiss(); + } catch (failure) { + if (props.owns()) setError(errorText(failure)); + } finally { + if (props.owns()) setBusy(false); + } + }; + return void save()} onCancel={props.dismiss}> + + {(message) => } + ; +} + /** The picked Device itself: what it is, whether it is online, its machine key, and Unpair. */ function DevicePane() { const device = pickedDevice; + let namingSheet: { dismiss(): void } | undefined; + let namingActive = true; + onCleanup(() => { namingActive = false; namingSheet?.dismiss(); }); + createEffect(() => settingsDeviceID.read(), () => { namingSheet?.dismiss(); }); + const rename = () => { + const current = device(); + if (!current) return; + const admitted = store.deviceNamingOwner(current.id); + let open = true; + const owns = () => open && namingActive && settingsDeviceID.get() === current.id && admitted(); + if (!owns()) return; + namingSheet?.dismiss(); + namingSheet = presentSheet((dismiss) => , () => { open = false; }); + }; + const relay = () => { track.roster(); track.connection(); @@ -825,6 +865,7 @@ function DevicePane() { + diff --git a/desktop/test-browser.ts b/desktop/test-browser.ts index 54ee0be0..176ae1c8 100644 --- a/desktop/test-browser.ts +++ b/desktop/test-browser.ts @@ -8,6 +8,7 @@ import { createServer } from "vite"; import type { ViteDevServer } from "vite"; const expected: Record = { + "src/ui/settings/deviceNames.browser.tsx": "checkDeviceNamingConsumer", "src/ui/compact.browser.tsx": "checkCompactActionRow", "src/ui/chat/cards.browser.tsx": "checkCommandCardInput", "src/ui/chat/composer.browser.tsx": "checkComposerSendAck", diff --git a/docs/architecture/desktop-app.md b/docs/architecture/desktop-app.md index ca3c5671..cc3e5452 100644 --- a/docs/architecture/desktop-app.md +++ b/docs/architecture/desktop-app.md @@ -42,6 +42,7 @@ The opt-in native window offers Diagnostics through `native_diagnostics.go`. Gen Under the OS Reduce Motion setting the presence dot, the spinner, the working row's shimmer and the sheet and popover entrances hold still instead of pulsing, spinning, sweeping, fading or sliding; the elements stay and keep their state. The Solid command palette uses shared `chats.search` content matches for Chats, Messages and Files, while actions/settings keep fuzzy matching. File rows open the existing owning chat; no file bytes are indexed. Store changes invalidate and refresh an unchanged query. The input names its listbox and active option; arrows select, Return opens and Escape dismisses. An incomplete-history notice identifies local downloaded-history coverage. Task results await the durable task API. - **Updates** (`updater.go`): the app owns MyGo archive checks and guarded install-on-quit. Every candidate is a stable `beans-v` release from `bloodf/beans` with signed readiness, a validated archive hash and compatible selected relay. Automatic checks run every 15 minutes when enabled; saved preferences and skipped versions remain in `updater.json`. Users choose Install on Quit, Later or Skip; the app never forces an unattended relaunch. Installation requires the app-owned drain-capable CLI and its private update-control token. Before spawn the launcher supplies only the eventual token path; the current app-owned child's matching READY precedes existing-directory/format admission and exclusive token creation. It creates neither directory nor marker, and preserves existing token bytes and permissions. Explicit operator settings, including an empty disable, remain inherited, but app-owned installation does not read operator token files. Token failure leaves the admitted CLI running with installation unavailable. Quit checks retain drafts and reject running work, pin a separate local websocket to the child PID/launcher generation/selected port, and take a 30-minute Runner admission lease before approval. The page becomes inert during the guard; cancellation restores it and releases the same Runner's lease. Relay selection and lease readiness are checked again before quit. The quit callback waits for the idle child to exit before swapping resources, while retaining the instance lock; Windows stops the approved idle child without waiting for the app's own exit. Native update dialogs use the page's live `L()` bridge. Development and package-managed non-writable installs omit update controls. [Desktop releases](../releasing-desktop.md) describes prerequisites and platform constraints. +- **Device aliases**: known Devices offer Rename in Settings, using `device.set_name` and blank input to restore the machine name. The prompt retains account, connection, snapshot and target ownership; losing that ownership closes it and rejects late publication. See [Device names](device-names.md). - **Device versions**: Device details shows the reported CLI/core version. Beans leaves standalone CLI self-update status absent and rejects its requests; this does not change the app-owned signed updater. Windows update-control admission queries the opened directory, marker and token handles for owner/DACL evidence. The owner belongs to the current account or LocalSystem; process group membership, including Administrators, is not a privacy grant. Effective foreign token data-read/write grants and directory/marker replacement, write or security-control grants are refused, including inherited grants. Missing DACLs, unsupported ACE forms and security-query failures fail closed. Existing objects are never repaired or repermissioned. Only an exclusively created token receives the current-user owner and a protected current-user DACL, which are checked before its secret is written.