diff --git a/docs/architecture/macos-app.md b/docs/architecture/macos-app.md index 5bc48c08..617b02db 100644 --- a/docs/architecture/macos-app.md +++ b/docs/architecture/macos-app.md @@ -23,6 +23,8 @@ Native installation uses a health-only strict decoder shared with its compatibil Settings rows share `Settings/SettingsRows.swift`: accessory rows keep a 10 pt gap between the wrapping label and the trailing control, and their height grows with the label. A settings pop-up takes at most 55% of its row, truncates long selected titles before the chevron platter, and keeps the full choice in its native menu and tooltip. Each accessory exposes its row label to accessibility clients. General's update row puts the version and last-check status below the label and native Check for Updates action, so the status wraps without squeezing the action. `sh macos/Tests/run-settings-layout.sh` checks production AppKit rows at 280, 360, 504, and 760 pt with English and Chinese text in light and dark appearances; `SettingsLayoutTests` also runs in the existing `BeansTests` target. +Known Devices offer a native Rename prompt using `device.set_name`; blank input restores the machine name. Prompt intent is separate from the displayed model. Account, connection, snapshot, target membership/key and view generations fence confirmation and late errors. See [Device names](device-names.md). + The Devices pane reports the CLI/core version. Beans does not advertise standalone CLI self-update availability; its native app updater continues to use Beans signed readiness and Runner admission drain. Help › Diagnostics… (Command-Option-Shift-D) opens a resizable native review window and requests only `diagnostics.report` through the existing local CLI client. The window displays schema-1 JSON with an explicit relay host/port disclosure and configured-only provider, cache-only anonymous plugin, and presence-only Runner limitations; a busy port is a note rather than failure proof. Refresh clears the previous report and disables sharing until a new report succeeds. Copy Report (Command-Shift-C) and Export Report… (Command-Shift-S) share only the reviewed report, with export using a native JSON save sheet; nothing uploads automatically. Unsupported schemas and request/validation failures show fixed messages without raw errors or snapshot fallback. The typed consumer discards unknown fields and preserves nullable report fields. English and Simplified Chinese labels use the existing `L()` tables and update in the open window when the app language changes; selectable report text, accessibility labels and a native key-view loop support review. See the [report contract](runtime.md#diagnostics-report). diff --git a/macos/Resources/zh-Hans.lproj/Localizable.strings b/macos/Resources/zh-Hans.lproj/Localizable.strings index e9e6c45a..082b34bc 100644 --- a/macos/Resources/zh-Hans.lproj/Localizable.strings +++ b/macos/Resources/zh-Hans.lproj/Localizable.strings @@ -636,6 +636,11 @@ "Rename Chat" = "重命名聊天"; "Rename Chat…" = "重命名聊天…"; "Rename…" = "重命名…"; +"Rename Device" = "重命名设备"; +"Device name" = "设备名称"; +"Couldn’t rename Device" = "无法重命名设备"; +"Keep the name to 64 characters" = "名称不能超过 64 个字符"; +"This name appears on every paired Device. Leave it blank to use the machine’s name." = "此名称会显示在每台已配对设备上。留空以使用机器名称。"; "Reply" = "回复"; "Reply failed: %@" = "回复失败:%@"; "Reply…" = "回复…"; diff --git a/macos/Sources/Beans/Model/AppStore.swift b/macos/Sources/Beans/Model/AppStore.swift index 3233c326..1168c70f 100644 --- a/macos/Sources/Beans/Model/AppStore.swift +++ b/macos/Sources/Beans/Model/AppStore.swift @@ -79,6 +79,11 @@ final class AppStore { /// True when the CLI answers on localhost (mock: toggled from the Debug menu). private(set) var isConnected = false + private var deviceNaming = DeviceNameOwnership() + var deviceNameOwner: UInt64? { + guard isConnected, hasIdentity == true, (isMock || (!isBootstrapping && identityID != nil)) else { return nil } + return deviceNaming.generation + } /// The first connection is still loading. The window is visible throughout this phase. private(set) var isStarting = true /// nil until the CLI has supplied the initial snapshot. @@ -478,6 +483,7 @@ final class AppStore { private func emit(_ event: StoreEvent) { guard !isApplyingBootstrap else { return } + deviceNaming.observe(event, devices: devices) subscriptions.removeAll { $0.owner == nil } for subscription in subscriptions { subscription.handler(event) @@ -1649,6 +1655,25 @@ final class AppStore { return created.phrase } + func setDeviceName(_ id: Device.ID, name: String, owner: UInt64) async throws { + guard deviceNameOwner == owner, let current = device(id), current.os != .unknown else { + throw CancellationError() + } + let name = name.trimmingCharacters(in: .whitespacesAndNewlines) + guard name.unicodeScalars.count <= 64 else { + throw CLIClient.RequestError(message: L("Keep the name to 64 characters")) + } + if isMock { + guard let index = devices.firstIndex(where: { $0.id == id }) else { return } + let original = current.machineName.isEmpty ? current.name : current.machineName + devices[index].machineName = original + devices[index].name = name.isEmpty ? original : name + emit(.rosterChanged) + return + } + _ = try await client.request("device.set_name", ["id": id, "name": name]) + guard deviceNameOwner == owner else { throw CancellationError() } + } /// 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. func unpairDevice(_ id: Device.ID) async throws { diff --git a/macos/Sources/Beans/Model/Models.swift b/macos/Sources/Beans/Model/Models.swift index 24bf809d..3f4d491c 100644 --- a/macos/Sources/Beans/Model/Models.swift +++ b/macos/Sources/Beans/Model/Models.swift @@ -423,6 +423,8 @@ struct Device: Identifiable, Hashable { /// Set for a CLI that updates itself (one installed with the site's script); a CLI an app /// carries updates with the app. var update: CLIUpdate? = nil + /// Original machine-reported name, independent of the account alias. + var machineName: String = "" /// A self-updating CLI's updates, as its `machine` blob says. struct CLIUpdate: Hashable { @@ -1205,3 +1207,28 @@ extension Format { return "\(count)" } } + +/// A naming prompt's target excludes mutable labels and presence. +struct DeviceNameTarget: Equatable { + let id: Device.ID + let machineKey: String + let os: Device.OS + init(_ device: Device) { id = device.id; machineKey = device.machineKey; os = device.os } +} + +/// Connection/account epochs and membership changes revoke old naming intents. +struct DeviceNameOwnership { + private(set) var generation: UInt64 = 0 + private var targets: [Device.ID: DeviceNameTarget] = [:] + mutating func observe(_ event: StoreEvent, devices: [Device]) { + let reset: Bool + switch event { + case .connectionChanged, .snapshotReplaced, .identityChanged: reset = true + case .rosterChanged: reset = false + default: return + } + let next = devices.reduce(into: [Device.ID: DeviceNameTarget]()) { $0[$1.id] = DeviceNameTarget($1) } + if reset || next != targets { generation &+= 1 } + targets = next + } +} diff --git a/macos/Sources/Beans/Model/Protocol.swift b/macos/Sources/Beans/Model/Protocol.swift index d7a7edce..83e1ef0c 100644 --- a/macos/Sources/Beans/Model/Protocol.swift +++ b/macos/Sources/Beans/Model/Protocol.swift @@ -251,6 +251,7 @@ enum Wire { struct Device: Decodable { var id: String var name: String + var machineName: String? var model: String var os: String var osVersion: String @@ -752,7 +753,8 @@ extension Wire.Device { machineKey: machineKey, plugins: (plugins ?? []).map { $0.toModel() }, version: version ?? "", - update: update.map { Device.CLIUpdate(auto: $0.auto, latest: $0.latest, state: $0.state, error: $0.error) } + update: update.map { Device.CLIUpdate(auto: $0.auto, latest: $0.latest, state: $0.state, error: $0.error) }, + machineName: machineName ?? name ) } } diff --git a/macos/Sources/Beans/Settings/DeviceSettingsViewControllers.swift b/macos/Sources/Beans/Settings/DeviceSettingsViewControllers.swift index 3edc4ce8..8298143d 100644 --- a/macos/Sources/Beans/Settings/DeviceSettingsViewControllers.swift +++ b/macos/Sources/Beans/Settings/DeviceSettingsViewControllers.swift @@ -427,15 +427,29 @@ final class PluginsSettingsViewController: DevicePaneViewController { final class AboutDeviceSettingsViewController: DevicePaneViewController { private let header = DeviceHeaderView() private let machineSection = SectionView(title: L("Machine")) + private var renameGeneration: UInt64 = 0 + private var renameTarget: DeviceNameTarget? override func viewDidLoad() { title = L("Devices") add(header) addSection(machineSection) super.viewDidLoad() + header.onRename = { [weak self] in self?.askDeviceName() } + } + + override func viewWillAppear() { + super.viewWillAppear() + renameGeneration &+= 1 + reload() } override func reload() { + let target = device.map(DeviceNameTarget.init) + if renameTarget != target { + renameGeneration &+= 1 + renameTarget = target + } guard let device else { return } header.configure(device: device) @@ -478,6 +492,72 @@ final class AboutDeviceSettingsViewController: DevicePaneViewController { machineSection.setRows(rows) } + override func viewWillDisappear() { + renameGeneration &+= 1 + super.viewWillDisappear() + } + + private func askDeviceName() { + guard let device, device.os != .unknown, let owner = store.deviceNameOwner, + let window = view.window else { return } + let generation = renameGeneration + let prompt = DeviceNamePrompt(device: device, owner: owner, generation: generation) + prompt.alert.beginSheetModal(for: window) { [weak self] response in + guard let self, self.renameGeneration == generation, + self.deviceID == device.id, self.store.deviceNameOwner == owner, + let name = prompt.name(for: response, owner: self.store.deviceNameOwner, + target: self.deviceID, generation: self.renameGeneration) else { return } + Task { @MainActor [weak self] in + guard let self, self.renameGeneration == generation, + self.deviceID == device.id, self.store.deviceNameOwner == owner else { return } + do { + try await self.store.setDeviceName(device.id, name: name, owner: owner) + } catch is CancellationError { + return + } catch { + guard self.renameGeneration == generation, self.deviceID == device.id, + self.store.deviceNameOwner == owner else { return } + let alert = NSAlert() + alert.messageText = L("Couldn’t rename Device") + alert.informativeText = error.localizedDescription + await alert.beginSheetModal(for: window) + } + } + } + } + +} + +/// The native prompt keeps the proposed name separate from the displayed Device. +@MainActor +final class DeviceNamePrompt { + let alert = NSAlert() + let field: NSTextField + private let owner: UInt64 + private let target: Device.ID + private let generation: UInt64 + + init(device: Device, owner: UInt64, generation: UInt64) { + self.owner = owner + self.target = device.id + self.generation = generation + field = NSTextField(string: device.name) + alert.messageText = L("Rename Device") + alert.informativeText = L("This name appears on every paired Device. Leave it blank to use the machine’s name.") + alert.addButton(withTitle: L("Rename")) + alert.addButton(withTitle: L("Cancel")) + field.frame = NSRect(x: 0, y: 0, width: 300, height: 24) + field.placeholderString = device.machineName + field.setAccessibilityLabel(L("Device name")) + alert.accessoryView = field + alert.window.initialFirstResponder = field + } + + func name(for response: NSApplication.ModalResponse, owner: UInt64?, target: Device.ID?, generation: UInt64) -> String? { + guard response == .alertFirstButtonReturn, owner == self.owner, + target == self.target, generation == self.generation else { return nil } + return field.stringValue + } } final class DeviceHeaderView: NSView { @@ -486,6 +566,8 @@ final class DeviceHeaderView: NSView { private let model = Build.label("", font: .systemFont(ofSize: 12.5), color: .secondaryLabelColor) private let dot = StatusDotView(size: 8) private let status = Build.label("", font: .systemFont(ofSize: 11.5, weight: .medium)) + var onRename: (() -> Void)? + private lazy var renameButton = NSButton(title: L("Rename…"), target: self, action: #selector(rename)) init() { super.init(frame: .zero) @@ -494,7 +576,7 @@ final class DeviceHeaderView: NSView { icon.contentTintColor = .secondaryLabelColor let statusLine = Build.stack([dot, status], orientation: .horizontal, spacing: 6) - let text = Build.stack([name, model, statusLine], spacing: 3) + let text = Build.stack([name, renameButton, model, statusLine], spacing: 3) text.setCustomSpacing(8, after: model) addSubview(icon) @@ -515,12 +597,14 @@ final class DeviceHeaderView: NSView { @available(*, unavailable) required init?(coder: NSCoder) { fatalError() } + @objc private func rename() { onRename?() } func configure(device: Device) { icon.image = NSImage(systemSymbolName: device.symbolName, accessibilityDescription: nil) icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 34, weight: .regular) name.stringValue = device.name model.stringValue = "\(device.model) · \(device.osVersion)" model.isHidden = device.os == .unknown + renameButton.isHidden = device.os == .unknown dot.status = device.status switch device.status { diff --git a/macos/Tests/Notifications/DeviceNamePromptTests.swift b/macos/Tests/Notifications/DeviceNamePromptTests.swift new file mode 100644 index 00000000..9975bb26 --- /dev/null +++ b/macos/Tests/Notifications/DeviceNamePromptTests.swift @@ -0,0 +1,98 @@ +import AppKit +import XCTest +@testable import Beans + +@MainActor +final class DeviceNamePromptTests: XCTestCase { + func testObservedRemovalAndReturnCannotRestoreAnOpenPrompt() throws { + _ = NSApplication.shared + let json = #"{"id":"peer","name":"Office","machine_name":"MacBook","model":"MacBook","os":"macos","os_version":"26","machine_key":"peer","is_this_device":false,"status":"offline","last_seen":0}"# + let device = try Wire.decoder.decode(Wire.Device.self, from: Data(json.utf8)).toModel() + var ownership = DeviceNameOwnership() + ownership.observe(.snapshotReplaced, devices: [device]) + let prompt = DeviceNamePrompt(device: device, owner: ownership.generation, generation: 3) + prompt.field.stringValue = "Stale alias" + + ownership.observe(.rosterChanged, devices: []) + XCTAssertNil(prompt.name(for: .alertFirstButtonReturn, owner: ownership.generation, + target: device.id, generation: 3)) + // A returning machine blob can retain the same full id and abbreviated key. + ownership.observe(.rosterChanged, devices: [device]) + XCTAssertNil(prompt.name(for: .alertFirstButtonReturn, owner: ownership.generation, + target: device.id, generation: 3)) + let fresh = DeviceNamePrompt(device: device, owner: ownership.generation, generation: 3) + fresh.field.stringValue = "Fresh alias" + XCTAssertEqual(fresh.name(for: .alertFirstButtonReturn, owner: ownership.generation, + target: device.id, generation: 3), "Fresh alias") + } + + func testUnknownDeviceAndReturnCannotRestoreAnOpenPrompt() throws { + _ = NSApplication.shared + let knownJSON = #"{"id":"peer","name":"Office","machine_name":"MacBook","model":"MacBook","os":"macos","os_version":"26","machine_key":"peer","is_this_device":false,"status":"offline","last_seen":0}"# + let unknownJSON = #"{"id":"peer","name":"","model":"","os":"","os_version":"","machine_key":"peer","is_this_device":false,"status":"offline","last_seen":0,"unknown":true}"# + let known = try Wire.decoder.decode(Wire.Device.self, from: Data(knownJSON.utf8)).toModel() + let unknown = try Wire.decoder.decode(Wire.Device.self, from: Data(unknownJSON.utf8)).toModel() + XCTAssertEqual(unknown.os, .unknown) + var ownership = DeviceNameOwnership() + ownership.observe(.snapshotReplaced, devices: [known]) + let prompt = DeviceNamePrompt(device: known, owner: ownership.generation, generation: 3) + prompt.field.stringValue = "Stale alias" + ownership.observe(.rosterChanged, devices: [unknown]) + ownership.observe(.rosterChanged, devices: [known]) + XCTAssertNil(prompt.name(for: .alertFirstButtonReturn, owner: ownership.generation, + target: known.id, generation: 3)) + } + + func testCancelAndRevokedOwnersDoNotProduceRenameIntent() throws { + _ = NSApplication.shared + let json = #"{"id":"peer","name":"Office","machine_name":"MacBook","model":"MacBook","os":"macos","os_version":"26","machine_key":"peer","is_this_device":false,"status":"offline","last_seen":0}"# + let device = try Wire.decoder.decode(Wire.Device.self, from: Data(json.utf8)).toModel() + XCTAssertEqual(device.name, "Office") + XCTAssertEqual(device.machineName, "MacBook") + let prompt = DeviceNamePrompt(device: device, owner: 7, generation: 3) + XCTAssertTrue(prompt.alert.accessoryView === prompt.field) + XCTAssertEqual(prompt.field.stringValue, "Office") + prompt.field.stringValue = "Changed" + XCTAssertNil(prompt.name(for: .alertSecondButtonReturn, owner: 7, target: "peer", generation: 3)) + XCTAssertNil(prompt.name(for: .alertFirstButtonReturn, owner: nil, target: "peer", generation: 3)) + XCTAssertNil(prompt.name(for: .alertFirstButtonReturn, owner: 8, target: "peer", generation: 3)) + XCTAssertNil(prompt.name(for: .alertFirstButtonReturn, owner: 7, target: "other", generation: 3)) + XCTAssertNil(prompt.name(for: .alertFirstButtonReturn, owner: 7, target: "peer", generation: 4)) + XCTAssertEqual(prompt.name(for: .alertFirstButtonReturn, owner: 7, target: "peer", generation: 3), "Changed") + prompt.field.stringValue = "" + XCTAssertEqual(prompt.name(for: .alertFirstButtonReturn, owner: 7, target: "peer", generation: 3), "") + XCTAssertEqual(device.name, "Office", "Editing or canceling the prompt must not mutate the displayed model.") + } + func testTargetBindingTracksRemovalAndReplacementButNotLabels() throws { + let json = #"{"id":"peer","name":"Office","machine_name":"MacBook","model":"MacBook","os":"macos","os_version":"26","machine_key":"peer","is_this_device":false,"status":"offline","last_seen":0}"# + let device = try Wire.decoder.decode(Wire.Device.self, from: Data(json.utf8)).toModel() + var ownership = DeviceNameOwnership() + ownership.observe(.snapshotReplaced, devices: [device]) + let admitted = ownership.generation + let original = DeviceNameTarget(device) + var renamed = device + renamed.name = "New label" + renamed.machineName = "New machine label" + XCTAssertEqual(DeviceNameTarget(renamed), original) + ownership.observe(.rosterChanged, devices: [renamed]) + XCTAssertEqual(ownership.generation, admitted, "Label changes preserve the open prompt") + ownership.observe(.rosterChanged, devices: []) + ownership.observe(.rosterChanged, devices: [device]) + XCTAssertNotEqual(ownership.generation, admitted, "Remove/reappear must revoke the old prompt") + let restored = ownership.generation + var replaced = device + replaced.machineKey = "replacement" + XCTAssertNotEqual(DeviceNameTarget(replaced), original) + ownership.observe(.rosterChanged, devices: [replaced]) + ownership.observe(.rosterChanged, devices: [device]) + XCTAssertNotEqual(ownership.generation, restored, "Key replacement and return must revoke the old prompt") + for event in [StoreEvent.connectionChanged, .identityChanged, .snapshotReplaced] { + let before = ownership.generation + ownership.observe(event, devices: [device]) + XCTAssertNotEqual(ownership.generation, before) + } + replaced = device + replaced.os = .linux + XCTAssertNotEqual(DeviceNameTarget(replaced), original) + } +}