From 4195c7aac3d1695b3d59f734d18705b1bfbaf96d Mon Sep 17 00:00:00 2001 From: Fabian Meyer <44942030+dinooo13@users.noreply.github.com> Date: Sat, 7 Nov 2026 02:17:07 +0100 Subject: [PATCH] Policy: an organisation's profile pins the engine, forces polish, the learner and update checks, Clipboard mode A configuration profile's Custom Settings payload for de.dinooo13.pladder, forced values only: AllowedEngines, AllowedPolishModels, PolishDictations, LearnCorrections, UpdateChecks and ClipboardMode. ManagedPolicy in Core applies it on top of the user's settings, which stay all the file holds; it is read at launch and on the two-second permission poll. Managed controls are disabled with "Managed by your organisation." Clipboard mode keeps the app off Accessibility even with the grant: no prompt, no tap, no Cmd+V, no field read. The correction learner gets a switch in the Dictionary tab, on by default. docs/MANAGED.md is the admin guide, with an example profile. Refs #109 Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 5 +- INSTALL.md | 2 +- Sources/Pladder/AppModel.swift | 124 ++++++++++--- Sources/Pladder/CorrectionInbox.swift | 7 +- .../Pladder/Overlay/OverlayController.swift | 4 +- Sources/Pladder/PermissionMonitor.swift | 26 ++- Sources/Pladder/PladderApp.swift | 8 +- .../Pladder/Resources/Localizable.xcstrings | 60 +++++++ Sources/Pladder/Screenshots.swift | 12 +- Sources/Pladder/Settings/DictionaryView.swift | 16 ++ .../Settings/GeneralSettingsView.swift | 23 ++- .../Pladder/Settings/TextSettingsView.swift | 19 +- Sources/Pladder/StatusText.swift | 13 +- .../PladderCore/Models/ManagedPolicy.swift | 156 +++++++++++++++++ Sources/PladderCore/Models/Settings.swift | 4 + .../PladderSystem/ManagedPolicySource.swift | 29 ++++ Sources/PladderSystem/PasteboardOutput.swift | 8 +- .../PladderCoreTests/ManagedPolicyTests.swift | 164 ++++++++++++++++++ Tests/PladderCoreTests/SettingsTests.swift | 5 + .../ManagedPolicySourceTests.swift | 31 ++++ Tests/PladderSystemTests/PasteFlowTests.swift | 13 ++ Tests/PladderTests/CorrectionInboxTests.swift | 35 +++- docs/ARCHITECTURE.md | 47 ++++- docs/DESIGN.md | 11 +- docs/MANAGED.md | 160 +++++++++++++++++ docs/PRIVACY.md | 2 +- docs/USAGE.md | 6 +- scripts/make-screenshots.sh | 3 +- 28 files changed, 938 insertions(+), 55 deletions(-) create mode 100644 Sources/PladderCore/Models/ManagedPolicy.swift create mode 100644 Sources/PladderSystem/ManagedPolicySource.swift create mode 100644 Tests/PladderCoreTests/ManagedPolicyTests.swift create mode 100644 Tests/PladderSystemTests/ManagedPolicySourceTests.swift create mode 100644 docs/MANAGED.md diff --git a/CLAUDE.md b/CLAUDE.md index 8bbbea9..0fa038f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -59,10 +59,11 @@ swift run -c release pladder-cli polish-set docs/polish-set.json --model s1-mini | Hotkey | Hold Option+Space by default, either Option; any key or chord can be recorded | A CGEvent tap (Accessibility, no Input Monitoring) matches the chord and swallows its regular key so it never reaches the target app. Sides are ignored in a chord with a regular key and kept for a modifier-only chord, so the tap and Carbon agree | | Interrupted press | A non-chord key within 1 s of the chord press cancels the recording without transcribing | Anyone who records a lone Command key shares it with Cmd+C, Cmd+V and Cmd+Tab; the overlay waits 150 ms before showing so those never flash it. Option+Space shares no modifier with them | | Secure Event Input | `IsSecureEventInputEnabled()` polled with the grant; sustained 3 s and a chord Carbon can register → Carbon monitor until it clears | A password field or Terminal's Secure Keyboard Entry stops taps receiving key events; modifier-only chords are unaffected and stay on the tap | -| Without Accessibility | Carbon `RegisterEventHotKey` plus clipboard-only output | A standard account cannot grant Accessibility without an admin. Carbon needs no permission but wants exactly one regular key and collapses left and right, so modifier-only chords are refused in the recorder; the transcript is left on the clipboard and the overlay says "press ⌘V". A stored chord Carbon cannot register, a lone Right Command say, is stood in for by the default Option+Space and the menu names it; the stored chord returns with the grant. `CopySymbolicHotKeys` only feeds the warning that an enabled macOS shortcut owns the recorded chord. `AppModel` polls the grant every two seconds and swaps the monitor in both directions | +| Without Accessibility (Clipboard mode) | Carbon `RegisterEventHotKey` plus clipboard-only output | A standard account cannot grant Accessibility without an admin. Carbon needs no permission but wants exactly one regular key and collapses left and right, so modifier-only chords are refused in the recorder; the transcript is left on the clipboard and the overlay says "press ⌘V". A stored chord Carbon cannot register, a lone Right Command say, is stood in for by the default Option+Space and the menu names it; the stored chord returns with the grant. `CopySymbolicHotKeys` only feeds the warning that an enabled macOS shortcut owns the recorded chord. `AppModel` polls the grant every two seconds and swaps the monitor in both directions | | Send key | Press V (configurable) while the hotkey is held and Return is posted 50 ms after the target app reads the paste, or 400 ms after Cmd+V if nothing reads it | Sends a chat message or runs a command without a second trip to the keyboard; the Return is posted from a detached task so it stays off the release-to-paste path, and waits for the read so an app that reads late gets the text first (Chromium's early read starts the wait too, so there it is as early as a fixed delay); a Return still owed when the next paste starts goes out ahead of that paste's Cmd+V. V because the index finger of the hand holding Option+Space rests on it, so the other hand stays on the mouse; Right Option, the default before, needed both hands. A letter is fine here: it is swallowed only while the chord is held. Needs Accessibility like the paste: Carbon registers only the chord, so there Option+V reaches the app. Only for a held recording: a latched one ends on the closing press, before any send key could arm | | Polish toggle | A Text-tab toggle (Polish section, marked Beta), off by default, no key of its own. When on, every dictation runs the usual pipeline, then Apple's on-device model (FoundationModels, `PladderRefine`) with a fixed cleanup prompt, then pastes | Self-corrections, spoken punctuation, number words and lists are beyond the deterministic processors, and the model runs on device with nothing to download. It costs one to three seconds and sits on the normal hotkey's path, which is why it is marked experimental and off: the branch is one Bool read; the session is prewarmed at key-down; transcripts under four words skip it; anything the model cannot do (Apple Intelligence off, refusal, an answer cut off at its token limit, the 8 s budget, which covers loading the model and every chunk of a long dictation) pastes the text as dictated. Logged as its own `polished release-to-paste` line | -| Learned corrections | After a paste the field is watched through Accessibility for up to 60 s; a word the user corrects that passes a token diff, a phonetic gate (Soundex or edit distance ≤ 2) and a yes/no review by the on-device model becomes one menu line, "Learned “x” → “y”? Add / Dismiss" | Nothing runs before Cmd+V is posted: the hook is in `AppModel.handle(.inserted)`, the watcher lives on its own thread and reads only the pasted range plus a margin, the review runs on a detached task and waits while a dictation is in flight, since it shares Apple's model with the polish. Only a paste that stayed in its field is watched: not a copy, not a send. Present only with Accessibility and Apple Intelligence, absent otherwise, no setting, no change to the menu bar glyph. Dismissed pairs go to `dismissed-corrections.json`, not settings, so a bug there can never cost the dictionary. Pure case changes are never proposed. Terminals and TUIs expose a screen buffer, not a field, so nothing is learned there | +| Learned corrections | After a paste the field is watched through Accessibility for up to 60 s; a word the user corrects that passes a token diff, a phonetic gate (Soundex or edit distance ≤ 2) and a yes/no review by the on-device model becomes one menu line, "Learned “x” → “y”? Add / Dismiss" | Nothing runs before Cmd+V is posted: the hook is in `AppModel.handle(.inserted)`, the watcher lives on its own thread and reads only the pasted range plus a margin, the review runs on a detached task and waits while a dictation is in flight, since it shares Apple's model with the polish. Only a paste that stayed in its field is watched: not a copy, not a send. Present only with Accessibility and Apple Intelligence, absent otherwise, no change to the menu bar glyph. One switch, "Suggest entries from my corrections" in the Dictionary tab, on by default and shown only where the learner can run: it reads other apps' fields, and revoking the grant the paste needs was the only other way to stop that. Dismissed pairs go to `dismissed-corrections.json`, not settings, so a bug there can never cost the dictionary. Pure case changes are never proposed. Terminals and TUIs expose a screen buffer, not a field, so nothing is learned there | +| Managed policy | A configuration profile's Custom Settings payload for `de.dinooo13.pladder`, read with `CFPreferences`, forced values only: `AllowedEngines` and `AllowedPolishModels` (lists, one pins the picker), `PolishDictations`, `LearnCorrections` and `UpdateChecks` (force a toggle on or off; `UpdateChecks = false` also removes Check for Updates…), `ClipboardMode` (Clipboard mode even with the grant: never asks for Accessibility, no tap, no ⌘V, no field read). Read at launch and on the two-second permission poll; applied on top of the user's settings, never written to the file. Managed controls are disabled, never hidden, with "Managed by your organisation." under the group (docs/MANAGED.md) | An organisation that must answer what the app reads and sends had nothing to point at: every choice was in a file the user owns. Managed preferences are root-owned, set by any MDM or by an admin by hand, and need no format, server or request of Pladder's own; a `defaults write` by the user is not forced, so it cannot pose as policy. Keeping the user's own settings underneath means removing the profile loses nothing. A typo is logged and ignored, and a list with no known ID is ignored whole, so a profile never leaves the app without an engine. Offline model provisioning, and the dictionary, keys and the rest, are out of it | | Toggle key | Another recordable chord, off by default. A chord of its own latches at release however long the press; equal to the push-to-talk chord it makes that key hybrid: a tap under 400 ms latches, a longer hold stops at release. The next press of any chord, Escape or the 10 min cap ends a latched recording. The overlay is the same as for a held recording, in and out; only the menu's status line says which key stops it | Two-minute dictations should not need a key held for two minutes. Handy and VoiceInk default to hybrid on one key; here it is opt-in, because a stray tap would otherwise leave the microphone open until the cap pastes two minutes of room noise. Hold, toggle and hybrid are decided in `HotkeyGestureTracker`, a clockless value type timed by the instant each monitor stamps on its events, so both monitors behave alike and a press that waits for the microphone cannot make the next release look longer. A same-chord press within 50 ms of its release is a bounce (some Bluetooth keyboards do this mid-hold): it never acts, and the first one seen turns on a 50 ms settle before every stopping release for the rest of the run, so only a keyboard that needs it pays for it and the release path is otherwise untouched. No separate press debounce: both monitors already report alternating presses and releases. Without Accessibility the toggle chord registers with Carbon like the key; one Carbon cannot register has no stand-in, except that a hybrid chord follows the key's. With a lone modifier as a hybrid key, the Command of a later Cmd+C ends a latched recording | | Escape | Discards a recording without transcribing and plays the stop sound; taken only while a recording is on | Never taken globally, so Escape keeps closing dialogs. On the tap `HotkeyChordSet` catches it before the chord trackers, so the interrupted-press rule never sees it, and Escape with the chord's own modifiers held still counts; Carbon registers the bare key around each recording, from the main queue so the release path never waits on it. Under Secure Event Input a modifier-only chord stays on the tap, where no key-down arrives, so Escape cannot cancel there | | Output | Clipboard + simulated Cmd+V; the transcript is a pasteboard promise and the old clipboard comes back off the critical path, 400 ms after Cmd+V if the target app has read it by then, otherwise 200 ms after it does, or after 8 s if nothing does | Universal, fast. Waiting for the read as well as the 400 ms: an app busy when Cmd+V arrives reads late, and the timer alone handed it the old clipboard (issue #40). A read never shortens the 400 ms, because Chromium sometimes reads once before the real paste and the pasteboard serves the second read itself. The promise is served on the main thread, so a busy Pladder main thread delays the target's read; the `paste` log line records when it came. It relies on the nspasteboard.org markers: without them Universal Clipboard reads every write within ~15 ms, which would pass for the paste | diff --git a/INSTALL.md b/INSTALL.md index 74e98ad..1c75d9a 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -36,7 +36,7 @@ Settings opens by itself the first time, with what Pladder still needs at the to 1. **Allow the microphone.** Click **Allow…** and accept the macOS prompt. That is what records your voice. 2. **Allow Accessibility.** Click **Allow…**, then **Open System Settings** in the alert; System Settings opens on the Accessibility list; switch Pladder on. That is what lets Pladder see the push-to-talk key in other apps, paste the result, and notice when you correct a word it got wrong. It does not need Input Monitoring. - On a standard (non-administrator) account, ticking that box asks for an administrator password, so ask an admin to do it once — the grant is keyed to the app's code signature and survives updates. Without it Pladder still works in a reduced form: Option+Space works the same, any combination with a regular key can be recorded in Settings (a modifier-only key such as Right Command needs Accessibility, and Option+Space stands in for it until then), and the transcript is left on the clipboard for you to paste with ⌘V. Managed Macs can pre-approve Accessibility for Pladder with an MDM Privacy Preferences Policy Control (PPPC) profile, which needs no prompt at all. + On a standard (non-administrator) account, ticking that box asks for an administrator password, so ask an admin to do it once — the grant is keyed to the app's code signature and survives updates. Without it Pladder still works in a reduced form: Option+Space works the same, any combination with a regular key can be recorded in Settings (a modifier-only key such as Right Command needs Accessibility, and Option+Space stands in for it until then), and the transcript is left on the clipboard for you to paste with ⌘V. Managed Macs can pre-approve Accessibility for Pladder with an MDM Privacy Preferences Policy Control (PPPC) profile, which needs no prompt at all, or keep Pladder off it with a profile of their own; what an organisation can fix is in [docs/MANAGED.md](docs/MANAGED.md). Apple Intelligence, if it is on, powers learned corrections and, if you pick it, the experimental polish; nothing else needs it. 3. **Wait for the model.** The first run downloads the Parakeet Ultra CoreML models from Hugging Face into `~/Library/Application Support/FluidAudio/Models` and compiles them. Settings and the menu show the progress, the menu bar icon is dimmed meanwhile, and the push-to-talk key is disabled until the model is ready. This happens once; later launches load in well under a second. diff --git a/Sources/Pladder/AppModel.swift b/Sources/Pladder/AppModel.swift index f63a61a..6c083b2 100644 --- a/Sources/Pladder/AppModel.swift +++ b/Sources/Pladder/AppModel.swift @@ -37,18 +37,22 @@ final class AppModel { private static let hotkeyLog = Logger(subsystem: "de.dinooo13.pladder", category: "hotkey") private static let settingsLog = Logger(subsystem: "de.dinooo13.pladder", category: "settings") + // The settings in effect: the user's own with the managed policy on top. An edit goes back + // into the user's own, which is all the file ever holds. var settings: Settings { - get { storedSettings } - set { - let old = storedSettings - guard newValue != old else { return } - storedSettings = newValue - settingsChanged(from: old) - } + get { effectiveSettings } + set { apply(user: policy.userSettings(from: newValue, stored: userSettings), policy: policy) } } - private var storedSettings: Settings + private var effectiveSettings: Settings + @ObservationIgnored private var userSettings: Settings + private(set) var policy: ManagedPolicy + @ObservationIgnored private let readPolicy: PolicyReader + @ObservationIgnored private var policyProblems: [ManagedPolicy.Problem] = [] + @ObservationIgnored private let output = PasteboardOutput() - init(location: SettingsLocation) { + typealias PolicyReader = ([EngineID]) -> (policy: ManagedPolicy, problems: [ManagedPolicy.Problem]) + + init(location: SettingsLocation, readPolicy: @escaping PolicyReader = { ManagedPolicySource().read(knownEngines: $0) }) { // The catalog's detail is an English catalog key, worded here, where the catalog is. var registry = EngineRegistry() for var entry in StandardEngines.entries { @@ -79,21 +83,30 @@ final class AppModel { } // Only these have a switch any more; one left off by an older build would be stuck. initial.disabledProcessors.formIntersection(StandardProcessors.switchable) - storedSettings = initial - - let permissions = PermissionMonitor() + userSettings = initial + self.readPolicy = readPolicy + let (policy, problems) = readPolicy(registry.available.map(\.id)) + self.policy = policy + policyProblems = problems + Self.log(problems) + if !policy.isEmpty { Self.log(policy) } + let effective = policy.apply(to: initial) + effectiveSettings = effective + output.setClipboardMode(policy.clipboardMode) + + let permissions = PermissionMonitor(clipboardMode: policy.clipboardMode) self.permissions = permissions - let hotkeys = HotkeyRouter(accessibilityTrusted: permissions.accessibilityTrusted, hotkey: initial.hotkey) + let hotkeys = HotkeyRouter(accessibilityTrusted: permissions.accessibilityTrusted, hotkey: effective.hotkey) self.hotkeys = hotkeys let polish = PolishModelController() self.polish = polish let events = self.events let coordinator = DictationCoordinator( - settings: DictationSettings(initial), + settings: DictationSettings(effective), registry: registry, capture: AVAudioEngineCapture(), - output: PasteboardOutput(), + output: output, outputMuter: OutputMuteController( control: CoreAudioOutputMute(), log: { Self.muteLog.info("\($0, privacy: .public)") }), @@ -107,6 +120,7 @@ final class AppModel { self.coordinator = coordinator hotkeys.attach(coordinator) corrections = CorrectionInbox(dismissedURL: location.dismissedCorrectionsURL) + corrections.isLearning = effective.learnCorrections updates = UpdateController() overlay = OverlayController(coordinator: coordinator, pastes: { [permissions] in permissions.accessibilityTrusted }) @@ -128,9 +142,10 @@ final class AppModel { overlay.start() coordinator.start() polish.apply(model: settings.polishModel, polishing: settings.polishDictations) - updates.start(automaticChecks: settings.checksForUpdatesAutomatically) + // Not started at all under a policy that allows no update check. + if policy.allowsUpdateChecks { updates.start(automaticChecks: settings.checksForUpdatesAutomatically) } // Written now, so only this launch counts as the first. - if isFirstLaunch { try? store.save(settings) } + if isFirstLaunch { try? store.save(userSettings) } } // True once, on the first launch only, and never for the demo or the screenshots, @@ -147,7 +162,10 @@ final class AppModel { await coordinator.shutdown() } + // On the permission poll, so a profile installed or removed while the app runs applies + // within two seconds; a dictation in flight finishes under the values it started with. private func permissionsRefreshed() { + refreshPolicy() hotkeys.update( accessibilityTrusted: permissions.accessibilityTrusted, secureInputEnabled: permissions.secureInputEnabled) @@ -163,6 +181,62 @@ final class AppModel { // MARK: Settings + private func refreshPolicy() { + let (next, problems) = readPolicy(registry.available.map(\.id)) + if problems != policyProblems { + policyProblems = problems + Self.log(problems) + } + guard next != policy else { return } + Self.log(next) + apply(user: userSettings, policy: next) + if started, next.allowsUpdateChecks { updates.start(automaticChecks: settings.checksForUpdatesAutomatically) } + } + + private func apply(user: Settings, policy next: ManagedPolicy) { + let old = effectiveSettings + let userChanged = user != userSettings + userSettings = user + if next != policy { + if next.clipboardMode != policy.clipboardMode { + output.setClipboardMode(next.clipboardMode) + // Before `permissionsRefreshed` hands the router the grant, so it routes by the new mode. + permissions.clipboardMode = next.clipboardMode + } + policy = next + } + let effective = next.apply(to: user) + if effective != old { + effectiveSettings = effective + settingsChanged(from: old) + } + guard userChanged else { return } + do { + try store.save(user) + } catch { + Self.settingsLog.error("could not save settings: \(error.localizedDescription, privacy: .public)") + } + } + + // `.public`: an admin reads these to see what a profile did, and they hold no user data. + private static func log(_ problems: [ManagedPolicy.Problem]) { + for problem in problems { + switch problem { + case .wrongType(let key): + settingsLog.error("managed policy: \(key.rawValue, privacy: .public) has the wrong type and is ignored") + case .unknownValues(let key, let values): + settingsLog.error("managed policy: \(key.rawValue, privacy: .public) names unknown values, ignored: \(values.joined(separator: ", "), privacy: .public)") + case .noKnownValue(let key): + settingsLog.error("managed policy: \(key.rawValue, privacy: .public) names nothing this build knows and is ignored") + } + } + } + + private static func log(_ policy: ManagedPolicy) { + let keys = policy.managedKeys.map(\.rawValue).joined(separator: ", ") + settingsLog.notice("managed policy: \(keys.isEmpty ? "none" : keys, privacy: .public)") + } + private func settingsChanged(from old: Settings) { let change = SettingsChange(from: old, to: settings) let monitor = change.hotkey ? hotkeys.hotkeyChanged(to: settings.hotkey) : nil @@ -176,10 +250,8 @@ final class AppModel { if change.updateChecks { updates.apply(automaticChecks: settings.checksForUpdatesAutomatically) } - do { - try store.save(settings) - } catch { - Self.settingsLog.error("could not save settings: \(error.localizedDescription, privacy: .public)") + if settings.learnCorrections != corrections.isLearning { + corrections.isLearning = settings.learnCorrections } } @@ -278,10 +350,18 @@ final class AppModel { ? hotkeys.displayName(of: toggle) : hold return MenuStatus.Chords( hold: hold, stop: stop, - accessibilityOff: standIn != nil, + accessibilityOff: !permissions.accessibilityTrusted, secureKeyboardEntry: hotkeys.usesCarbonForSecureInput) } + // A policy that allows no update check leaves no way to start one, by hand either. + var offersUpdates: Bool { updates.isAvailable && policy.allowsUpdateChecks } + + // Where the correction learner can run at all; elsewhere its switch would do nothing. + var canLearnCorrections: Bool { + permissions.accessibilityTrusted && polish.availability == .available + } + func setHotkeySuspended(_ suspended: Bool) { coordinator.isHotkeySuspended = suspended } diff --git a/Sources/Pladder/CorrectionInbox.swift b/Sources/Pladder/CorrectionInbox.swift index 5a11163..55dbf2e 100644 --- a/Sources/Pladder/CorrectionInbox.swift +++ b/Sources/Pladder/CorrectionInbox.swift @@ -10,6 +10,10 @@ import PladderSystem final class CorrectionInbox { private(set) var proposals: [CorrectionProposal] = [] static let maximumProposals = 3 + // Off: no field is watched and no review runs; what was waiting goes with it. + var isLearning = true { + didSet { if !isLearning, !proposals.isEmpty { proposals = [] } } + } @ObservationIgnored var dictionary: () -> [DictionaryEntry] = { [] } @ObservationIgnored var addRules: ([DictionaryEntry]) -> Void = { _ in } @ObservationIgnored var waitUntilQuiet: @MainActor () async -> Void = {} @@ -44,6 +48,7 @@ final class CorrectionInbox { private func waitForQuiet() async { await waitUntilQuiet() } func pasted(_ text: String) { + guard isLearning else { return } learner?.pasted(text) } @@ -64,7 +69,7 @@ final class CorrectionInbox { private func propose(_ proposal: CorrectionProposal) { let key = proposal.pair.key - guard !proposals.contains(where: { $0.pair.key == key }), + guard isLearning, !proposals.contains(where: { $0.pair.key == key }), !dictionary().hasRule(for: proposal.pair.heard) else { return } proposals = Array(([proposal] + proposals).prefix(Self.maximumProposals)) } diff --git a/Sources/Pladder/Overlay/OverlayController.swift b/Sources/Pladder/Overlay/OverlayController.swift index bf9eb70..625670e 100644 --- a/Sources/Pladder/Overlay/OverlayController.swift +++ b/Sources/Pladder/Overlay/OverlayController.swift @@ -210,7 +210,9 @@ final class OverlayController { presentTask = Task { [weak self] in // Off the main thread and inside the present delay: an app slow to answer // Accessibility costs the pill its new place, never its timing. - let field = Task.detached(priority: .userInitiated) { FocusedField.frame() } + // Clipboard mode reads no other app's field, even with the grant. + let readsField = self?.pastes() ?? false + let field = Task.detached(priority: .userInitiated) { readsField ? FocusedField.frame() : nil } try? await Task.sleep(for: Self.presentDelay) guard !Task.isCancelled, let self, self.running else { return } self.panel.avoiding = await field.value diff --git a/Sources/Pladder/PermissionMonitor.swift b/Sources/Pladder/PermissionMonitor.swift index 4f22736..dc0fe41 100644 --- a/Sources/Pladder/PermissionMonitor.swift +++ b/Sources/Pladder/PermissionMonitor.swift @@ -8,9 +8,17 @@ import PladderSystem @MainActor @Observable final class PermissionMonitor { - private(set) var accessibilityTrusted = Permissions.isAccessibilityTrusted + // The grant in effect: never in Clipboard mode, where the app does without it on purpose. + private(set) var accessibilityTrusted: Bool private(set) var microphoneStatus = Permissions.microphoneStatus private(set) var secureInputEnabled = SecureInput.isEnabled + // Set by a managed policy. The grant is then never asked for, nor even checked. + var clipboardMode: Bool { + didSet { + guard clipboardMode != oldValue else { return } + refreshAccessibility() + } + } @ObservationIgnored var onRefresh: () -> Void = {} @@ -18,7 +26,12 @@ final class PermissionMonitor { private static let pollInterval: Duration = .seconds(2) - var needsAccessibility: Bool { !accessibilityTrusted } + init(clipboardMode: Bool = false) { + self.clipboardMode = clipboardMode + accessibilityTrusted = !clipboardMode && Permissions.isAccessibilityTrusted + } + + var needsAccessibility: Bool { !clipboardMode && !accessibilityTrusted } var needsMicrophone: Bool { microphoneStatus != .authorized } var needsAnyPermission: Bool { needsAccessibility || needsMicrophone } @@ -35,8 +48,7 @@ final class PermissionMonitor { // Assigns only what changed, so views reading one grant are not redrawn every poll. func refresh() { - let trusted = Permissions.isAccessibilityTrusted - if trusted != accessibilityTrusted { accessibilityTrusted = trusted } + refreshAccessibility() let microphone = Permissions.microphoneStatus if microphone != microphoneStatus { microphoneStatus = microphone } let secure = SecureInput.isEnabled @@ -44,10 +56,16 @@ final class PermissionMonitor { onRefresh() } + private func refreshAccessibility() { + let trusted = !clipboardMode && Permissions.isAccessibilityTrusted + if trusted != accessibilityTrusted { accessibilityTrusted = trusted } + } + // The system alert first, which has its own button to System Settings; opening the pane // as well put two system windows up at once. Once the alert has been seen this launch, // the pane directly, since macOS shows the alert only for an app not yet in the list. func grantAccessibility() { + guard !clipboardMode else { return } if promptedForAccessibility { Permissions.openAccessibilitySettings() } else { diff --git a/Sources/Pladder/PladderApp.swift b/Sources/Pladder/PladderApp.swift index 6833375..9d03b5d 100644 --- a/Sources/Pladder/PladderApp.swift +++ b/Sources/Pladder/PladderApp.swift @@ -15,7 +15,9 @@ struct PladderApp: App { init() { let isDeveloperMode = OverlayDemo.isRequested || Screenshots.directory != nil self.isDeveloperMode = isDeveloperMode - let model = AppModel(location: isDeveloperMode ? .scratch : .live) + let model = isDeveloperMode + ? AppModel(location: .scratch, readPolicy: Screenshots.readPolicy) + : AppModel(location: .live) _model = State(initialValue: model) // Deferred, so the app has finished launching before the Accessibility prompt. if OverlayDemo.isRequested { @@ -176,14 +178,14 @@ private struct MenuContent: View { // Only after a scheduled check found it: Sparkle's window waits for this click, so it // never takes focus from a dictation. - if let version = model.updates.waitingVersion { + if model.offersUpdates, let version = model.updates.waitingVersion { Button("Pladder \(version) is available — Install…") { model.updates.checkForUpdates() } } Button("About Pladder") { NSApp.activate(ignoringOtherApps: true) NSApp.orderFrontStandardAboutPanel(nil) } - if model.updates.isAvailable { + if model.offersUpdates { Button("Check for Updates…") { model.updates.checkForUpdates() } .disabled(!model.updates.canCheck) } diff --git a/Sources/Pladder/Resources/Localizable.xcstrings b/Sources/Pladder/Resources/Localizable.xcstrings index 6601476..d7975ab 100644 --- a/Sources/Pladder/Resources/Localizable.xcstrings +++ b/Sources/Pladder/Resources/Localizable.xcstrings @@ -1660,6 +1660,66 @@ } } } + }, + "In Clipboard mode, %@ can’t be detected. %@ works in its place.": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Im Zwischenablagemodus wird %1$@ nicht erkannt. %2$@ funktioniert an ihrer Stelle." + } + } + } + }, + "In Clipboard mode, %@ can’t be detected, so the hands-free key is off.": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Im Zwischenablagemodus wird %@ nicht erkannt, deshalb ist die Freihandtaste aus." + } + } + } + }, + "The send key doesn’t work in Clipboard mode.": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Die Sendetaste funktioniert im Zwischenablagemodus nicht." + } + } + } + }, + "Managed by your organisation.": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Von deiner Organisation verwaltet." + } + } + } + }, + "Suggest entries from my corrections": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Einträge aus meinen Korrekturen vorschlagen" + } + } + } + }, + "When you fix a pasted word, the menu offers it as a rule.": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Wenn du ein eingefügtes Wort korrigierst, bietet das Menü es als Regel an." + } + } + } } }, "version": "1.0" diff --git a/Sources/Pladder/Screenshots.swift b/Sources/Pladder/Screenshots.swift index 7f6a5db..7f2cfe6 100644 --- a/Sources/Pladder/Screenshots.swift +++ b/Sources/Pladder/Screenshots.swift @@ -13,6 +13,16 @@ enum Screenshots { } static var capturesMenu: Bool { CommandLine.arguments.contains("--menu") } + + // Never the Mac's own profile, so a capture shows the same on every Mac. `--managed`: every + // managed control, disabled where a profile pins it; Clipboard mode would hide some of them. + static let readPolicy: AppModel.PolicyReader = { engines in + guard CommandLine.arguments.contains("--managed") else { return (.none, []) } + let policy = ManagedPolicy( + allowedEngines: engines.last.map { [$0] }, allowedPolishModels: [.appleIntelligence], + polishDictations: true, learnCorrections: false, updateChecks: false) + return (policy, []) + } // The app's own model, on the throwaway settings file, which the real Settings scene shows. static var appModel: AppModel? @@ -30,7 +40,7 @@ enum Screenshots { // `--settings`: each Settings tab, for reviewing the window without opening it. if CommandLine.arguments.contains("--settings") { - let model = AppModel(location: .scratch) + let model = AppModel(location: .scratch, readPolicy: readPolicy) for scheme in [ColorScheme.light, .dark] { let suffix = scheme == .dark ? "dark" : "light" for (tab, name) in [(SettingsTab.general, "general"), (.text, "text"), (.dictionary, "dictionary")] { diff --git a/Sources/Pladder/Settings/DictionaryView.swift b/Sources/Pladder/Settings/DictionaryView.swift index 5c39bb4..b4fc2a8 100644 --- a/Sources/Pladder/Settings/DictionaryView.swift +++ b/Sources/Pladder/Settings/DictionaryView.swift @@ -41,6 +41,22 @@ struct DictionaryView: View { WarningLabel(String(localized: "Two rules undo each other, so both are ignored.")) } } + // The learner reads other apps' fields, so it gets a switch of its own, beside what it + // adds to; where it cannot run at all the switch would do nothing. + if model.canLearnCorrections { + Section { + Toggle(isOn: $model.settings.learnCorrections) { + Text("Suggest entries from my corrections") + Text("When you fix a pasted word, the menu offers it as a rule.") + } + .accessibilityHint(Text("When you fix a pasted word, the menu offers it as a rule.")) + .disabled(model.policy.learnCorrections != nil) + } footer: { + if model.policy.learnCorrections != nil { + Text(ManagedText.footer) + } + } + } } .formStyle(.grouped) .alert( diff --git a/Sources/Pladder/Settings/GeneralSettingsView.swift b/Sources/Pladder/Settings/GeneralSettingsView.swift index d783aa0..e043c28 100644 --- a/Sources/Pladder/Settings/GeneralSettingsView.swift +++ b/Sources/Pladder/Settings/GeneralSettingsView.swift @@ -134,11 +134,16 @@ private struct StartupSection: View { WarningLabel(error) } if model.updates.isAvailable { + // Its own line, not the group's footer: the rest of the group is the user's. Toggle(isOn: $model.settings.checksForUpdatesAutomatically) { Text("Check for updates automatically") Text("Asks GitHub once a day for a newer Pladder. Sends nothing about you.") + if model.policy.updateChecks != nil { + Text(ManagedText.footer) + } } .accessibilityHint(Text("Asks GitHub once a day for a newer Pladder. Sends nothing about you.")) + .disabled(model.policy.updateChecks != nil) } Toggle("Play start and stop sounds", isOn: $model.settings.playSounds) Toggle(isOn: $model.settings.muteOutputWhileDictating) { @@ -171,7 +176,7 @@ private struct ShortcutsSection: View { if let warning = HotkeyWarning.forKey( model.settings.hotkey, standIn: model.hotkeys.standInHotkey, systemShortcuts: model.hotkeys.systemShortcuts) { - WarningLabel(warning.text) + WarningLabel(warning.text(inClipboardMode: model.policy.clipboardMode)) } LabeledContent { HotkeyRecorderField( @@ -191,7 +196,7 @@ private struct ShortcutsSection: View { model.settings.toggleHotkey, hotkey: model.settings.hotkey, accessibilityTrusted: model.permissions.accessibilityTrusted, systemShortcuts: model.hotkeys.systemShortcuts) { - WarningLabel(warning.text) + WarningLabel(warning.text(inClipboardMode: model.policy.clipboardMode)) } LabeledContent { HotkeyRecorderField( @@ -208,7 +213,7 @@ private struct ShortcutsSection: View { if let warning = HotkeyWarning.forSendKey( model.settings.submitKey, hotkey: model.settings.hotkey, accessibilityTrusted: model.permissions.accessibilityTrusted) { - WarningLabel(warning.text) + WarningLabel(warning.text(inClipboardMode: model.policy.clipboardMode)) } } } @@ -240,7 +245,7 @@ private struct SpeechModelSection: View { var body: some View { Section { Picker(selection: $model.settings.engineID) { - ForEach(model.registry.available) { entry in + ForEach(engines) { entry in Text(LocalizedStringKey(entry.displayName)).tag(entry.id) } } label: { @@ -249,13 +254,23 @@ private struct SpeechModelSection: View { Text(verbatim: model.registry.entry(for: model.settings.engineID)?.detail ?? "") } .accessibilityHint(Text(verbatim: model.registry.entry(for: model.settings.engineID)?.detail ?? "")) + .disabled(model.policy.pinsEngine) if !model.showsGetStarted { SpeechModelProgress(model: model) } } header: { Text("Speech Model") + } footer: { + if model.policy.allowedEngines != nil { + Text(ManagedText.footer) + } } } + + private var engines: [EngineRegistry.Entry] { + let allowed = model.policy.engines(from: model.registry.available.map(\.id)) + return model.registry.available.filter { allowed.contains($0.id) } + } } extension OverlayStyle { diff --git a/Sources/Pladder/Settings/TextSettingsView.swift b/Sources/Pladder/Settings/TextSettingsView.swift index 4896522..2a4f15b 100644 --- a/Sources/Pladder/Settings/TextSettingsView.swift +++ b/Sources/Pladder/Settings/TextSettingsView.swift @@ -42,25 +42,38 @@ struct TextSettingsView: View { Text("Beta. On-device AI fixes self-corrections, lists and punctuation.") } .accessibilityHint(Text("Beta. On-device AI fixes self-corrections, lists and punctuation.")) + .disabled(model.policy.polishDictations != nil) if model.settings.polishDictations { Picker("Model", selection: $model.settings.polishModel) { - ForEach(PolishModel.allCases, id: \.self) { choice in + ForEach(model.policy.polishModels, id: \.self) { choice in Text(choice.displayName).tag(choice) } } + .disabled(model.policy.pinsPolishModel) polishModelStatus } } header: { Text("Polish") } footer: { - if model.settings.polishDictations { - Text(verbatim: model.settings.polishModel.summary) + VStack(alignment: .leading, spacing: 4) { + if model.settings.polishDictations { + Text(verbatim: model.settings.polishModel.summary) + } + if polishIsManaged { + Text(ManagedText.footer) + } } } } .formStyle(.grouped) } + // The model's picker is managed only while it is shown. + private var polishIsManaged: Bool { + model.policy.polishDictations != nil + || (model.settings.polishDictations && model.policy.allowedPolishModels != nil) + } + @ViewBuilder private var polishModelStatus: some View { if let status = model.polish.status { diff --git a/Sources/Pladder/StatusText.swift b/Sources/Pladder/StatusText.swift index 3efcf14..7b81b17 100644 --- a/Sources/Pladder/StatusText.swift +++ b/Sources/Pladder/StatusText.swift @@ -135,6 +135,10 @@ extension ModelFileFailure { } } +enum ManagedText { + static let footer = String(localized: "Managed by your organisation.") +} + enum MenuStatus { struct Chords { var hold: String @@ -225,8 +229,15 @@ enum ProcessorText { } extension HotkeyWarning { - @MainActor var text: String { + // In Clipboard mode by policy the grant is not the user's to give, so no sentence asks for it. + @MainActor func text(inClipboardMode clipboardMode: Bool) -> String { switch self { + case .standIn(let stored, let standIn) where clipboardMode: + String(localized: "In Clipboard mode, \(stored.displayName) can’t be detected. \(standIn.sideAgnosticDisplayName) works in its place.") + case .toggleNeedsAccessibility(let toggle) where clipboardMode: + String(localized: "In Clipboard mode, \(toggle.displayName) can’t be detected, so the hands-free key is off.") + case .sendKeyNeedsAccessibility where clipboardMode: + String(localized: "The send key doesn’t work in Clipboard mode.") case .standIn(let stored, let standIn): String(localized: "Without Accessibility, \(stored.displayName) can’t be detected. \(standIn.sideAgnosticDisplayName) works in its place until you allow it.") case .systemShortcut(let owner, let chord): diff --git a/Sources/PladderCore/Models/ManagedPolicy.swift b/Sources/PladderCore/Models/ManagedPolicy.swift new file mode 100644 index 0000000..089b824 --- /dev/null +++ b/Sources/PladderCore/Models/ManagedPolicy.swift @@ -0,0 +1,156 @@ +import Foundation + +// What an organisation's configuration profile fixes. Never written to the settings file: +// the app applies it on top of the user's own settings. See docs/ARCHITECTURE.md, +// "Managed policy". +public struct ManagedPolicy: Sendable, Equatable { + public enum Key: String, CaseIterable, Sendable { + case allowedEngines = "AllowedEngines" + case polishDictations = "PolishDictations" + case allowedPolishModels = "AllowedPolishModels" + case learnCorrections = "LearnCorrections" + case clipboardMode = "ClipboardMode" + case updateChecks = "UpdateChecks" + } + + // For the log: an admin's typo must be findable, and it never stops the app. + public enum Problem: Sendable, Equatable { + case wrongType(Key) + case unknownValues(Key, [String]) + case noKnownValue(Key) + } + + // A list: what the picker may offer, one entry pins it. nil leaves the choice to the user. + public var allowedEngines: [EngineID]? + public var allowedPolishModels: [PolishModel]? + // A toggle: forced on or off. nil leaves it to the user. + public var polishDictations: Bool? + public var learnCorrections: Bool? + public var updateChecks: Bool? + // Only `true` means anything: a profile cannot grant Accessibility through Pladder. + public var clipboardMode: Bool + + public static let none = ManagedPolicy() + + public init( + allowedEngines: [EngineID]? = nil, allowedPolishModels: [PolishModel]? = nil, + polishDictations: Bool? = nil, learnCorrections: Bool? = nil, updateChecks: Bool? = nil, + clipboardMode: Bool = false + ) { + self.allowedEngines = allowedEngines + self.allowedPolishModels = allowedPolishModels + self.polishDictations = polishDictations + self.learnCorrections = learnCorrections + self.updateChecks = updateChecks + self.clipboardMode = clipboardMode + } + + // `value` hands over only what a profile forces, as the property list decoded it. + public static func read( + _ value: (Key) -> Any?, knownEngines: [EngineID] + ) -> (policy: ManagedPolicy, problems: [Problem]) { + var problems: [Problem] = [] + func bool(_ key: Key) -> Bool? { + guard let raw = value(key) else { return nil } + // A property list `` bridges to Bool too; only `` and `` count. + guard let number = raw as? NSNumber, CFGetTypeID(number) == CFBooleanGetTypeID() else { + problems.append(.wrongType(key)) + return nil + } + return number.boolValue + } + func list(_ key: Key, _ make: (String) -> T?) -> [T]? { + guard let raw = value(key) else { return nil } + guard let strings = raw as? [String] else { + problems.append(.wrongType(key)) + return nil + } + var seen: Set = [] + var known: [T] = [] + var unknown: [String] = [] + for string in strings where seen.insert(string).inserted { + if let item = make(string) { known.append(item) } else { unknown.append(string) } + } + if !unknown.isEmpty { problems.append(.unknownValues(key, unknown)) } + // A list of typos, or an empty one, would leave the picker with nothing to run. + guard !known.isEmpty else { + problems.append(.noKnownValue(key)) + return nil + } + return known + } + + let policy = ManagedPolicy( + allowedEngines: list(.allowedEngines) { id in + knownEngines.first { $0.rawValue == id } + }, + allowedPolishModels: list(.allowedPolishModels, PolishModel.init(rawValue:)), + polishDictations: bool(.polishDictations), + learnCorrections: bool(.learnCorrections), + updateChecks: bool(.updateChecks), + clipboardMode: bool(.clipboardMode) ?? false + ) + return (policy, problems) + } + + public var isEmpty: Bool { self == .none } + + public func apply(to settings: Settings) -> Settings { + var settings = settings + if let engines = allowedEngines, !engines.contains(settings.engineID) { + settings.engineID = engines[0] + } + if let models = allowedPolishModels, !models.contains(settings.polishModel) { + settings.polishModel = models[0] + } + if let polishDictations { settings.polishDictations = polishDictations } + if let learnCorrections { settings.learnCorrections = learnCorrections } + if let updateChecks { settings.checksForUpdatesAutomatically = updateChecks } + return settings + } + + // The views edit the settings in effect; this turns an edit back into the user's own, so + // a managed value never reaches the settings file and removing the profile gives every + // choice back. A value the edit left as the policy had it keeps what the user stored. + public func userSettings(from edited: Settings, stored: Settings) -> Settings { + let effective = apply(to: stored) + var user = edited + if edited.engineID == effective.engineID { user.engineID = stored.engineID } + if edited.polishModel == effective.polishModel { user.polishModel = stored.polishModel } + if edited.polishDictations == effective.polishDictations { user.polishDictations = stored.polishDictations } + if edited.learnCorrections == effective.learnCorrections { user.learnCorrections = stored.learnCorrections } + if edited.checksForUpdatesAutomatically == effective.checksForUpdatesAutomatically { + user.checksForUpdatesAutomatically = stored.checksForUpdatesAutomatically + } + return user + } + + // In the order the app offers them. + public func engines(from available: [EngineID]) -> [EngineID] { + guard let allowedEngines else { return available } + return available.filter(allowedEngines.contains) + } + + public var polishModels: [PolishModel] { + guard let allowedPolishModels else { return PolishModel.allCases } + return PolishModel.allCases.filter(allowedPolishModels.contains) + } + + public var pinsEngine: Bool { allowedEngines?.count == 1 } + public var pinsPolishModel: Bool { allowedPolishModels?.count == 1 } + // The update check is the app's one request a user can start: off, there is none at all. + public var allowsUpdateChecks: Bool { updateChecks != false } + + public var managedKeys: [Key] { + Key.allCases.filter { key in + switch key { + case .allowedEngines: allowedEngines != nil + case .polishDictations: polishDictations != nil + case .allowedPolishModels: allowedPolishModels != nil + case .learnCorrections: learnCorrections != nil + case .clipboardMode: clipboardMode + case .updateChecks: updateChecks != nil + } + } + } +} diff --git a/Sources/PladderCore/Models/Settings.swift b/Sources/PladderCore/Models/Settings.swift index f287699..b0bf8ea 100644 --- a/Sources/PladderCore/Models/Settings.swift +++ b/Sources/PladderCore/Models/Settings.swift @@ -26,6 +26,7 @@ public struct Settings: Codable, Sendable, Equatable { public var muteOutputWhileDictating: Bool public var overlayStyle: OverlayStyle public var checksForUpdatesAutomatically: Bool + public var learnCorrections: Bool // The defaults, here and nowhere else: the decoder starts from them too. public init(engineID: EngineID) { @@ -44,6 +45,7 @@ public struct Settings: Codable, Sendable, Equatable { muteOutputWhileDictating = false overlayStyle = .compact checksForUpdatesAutomatically = false + learnCorrections = true } private enum CodingKeys: String, CodingKey { @@ -52,6 +54,7 @@ public struct Settings: Codable, Sendable, Equatable { case playSounds case muteOutputWhileDictating, overlayStyle case checksForUpdatesAutomatically + case learnCorrections } private enum LegacyKeys: String, CodingKey { @@ -109,6 +112,7 @@ public struct Settings: Codable, Sendable, Equatable { if let value = read(Bool.self, .muteOutputWhileDictating) { muteOutputWhileDictating = value } if let value = read(OverlayStyle.self, .overlayStyle) { overlayStyle = value } if let value = read(Bool.self, .checksForUpdatesAutomatically) { checksForUpdatesAutomatically = value } + if let value = read(Bool.self, .learnCorrections) { learnCorrections = value } } public mutating func setProcessor(_ id: String, enabled: Bool) { diff --git a/Sources/PladderSystem/ManagedPolicySource.swift b/Sources/PladderSystem/ManagedPolicySource.swift new file mode 100644 index 0000000..2addd70 --- /dev/null +++ b/Sources/PladderSystem/ManagedPolicySource.swift @@ -0,0 +1,29 @@ +import CoreFoundation +import Foundation +import PladderCore + +// A configuration profile's Custom Settings payload for the app's domain, which macOS keeps +// in the root-owned /Library/Managed Preferences. Only forced values count: one the user +// wrote with `defaults`, or one in /Library/Preferences, is not. See docs/ARCHITECTURE.md, +// "Managed policy". +public struct ManagedPolicySource: Sendable { + public static let defaultDomain = "de.dinooo13.pladder" + + public let domain: String + + // `swift run` has no bundle identifier, and reads the app's domain all the same. + public init(domain: String = Bundle.main.bundleIdentifier ?? ManagedPolicySource.defaultDomain) { + self.domain = domain + } + + // Synchronized first, so a profile installed or removed while the app runs is seen. + public func read(knownEngines: [EngineID]) -> (policy: ManagedPolicy, problems: [ManagedPolicy.Problem]) { + let app = domain as CFString + CFPreferencesAppSynchronize(app) + return ManagedPolicy.read({ key in + let name = key.rawValue as CFString + guard CFPreferencesAppValueIsForced(name, app) else { return nil } + return CFPreferencesCopyAppValue(name, app) + }, knownEngines: knownEngines) + } +} diff --git a/Sources/PladderSystem/PasteboardOutput.swift b/Sources/PladderSystem/PasteboardOutput.swift index 8bfe96b..b2e7ea2 100644 --- a/Sources/PladderSystem/PasteboardOutput.swift +++ b/Sources/PladderSystem/PasteboardOutput.swift @@ -29,6 +29,7 @@ public final class PasteboardOutput: TextOutput { private static let log = Logger(subsystem: "de.dinooo13.pladder", category: "paste") private let owedReturn = Mutex(nil) + private let clipboardMode = Atomic(false) // Posted once, by its own timer or by the next paste, which must not go out ahead. private final class OwedReturn: Sendable {} @@ -52,6 +53,11 @@ public final class PasteboardOutput: TextOutput { keeper = ClipboardKeeper(pasteboard: pasteboard, clock: clock, snapshotLimit: snapshotLimit) } + // Clipboard mode by policy: copied as without the grant, even with it. + public func setClipboardMode(_ on: Bool) { + clipboardMode.store(on, ordering: .relaxed) + } + // A warm layout lookup is about a microsecond; the first in a process is tens of // milliseconds, paid at the first key-down. public func prepare() async { @@ -66,7 +72,7 @@ public final class PasteboardOutput: TextOutput { public func insert(_ text: String, submit: Bool) async throws -> InsertResult { // Posting to the HID event tap needs Accessibility. Without it the transcript stays // on the clipboard: no restore, and no Return, which needs the same grant. - guard isTrusted() else { + guard !clipboardMode.load(ordering: .relaxed), isTrusted() else { await keeper.copy(text) return .copied } diff --git a/Tests/PladderCoreTests/ManagedPolicyTests.swift b/Tests/PladderCoreTests/ManagedPolicyTests.swift new file mode 100644 index 0000000..d44a9b4 --- /dev/null +++ b/Tests/PladderCoreTests/ManagedPolicyTests.swift @@ -0,0 +1,164 @@ +import Foundation +import Testing +@testable import PladderCore + +@Suite struct ManagedPolicyTests { + private static let ultra = EngineID("parakeet-ultra-incremental") + private static let v3 = EngineID("parakeet-tdt-v3-incremental") + private static let engines = [ultra, v3] + + private static func read(_ values: [ManagedPolicy.Key: Any]) -> (policy: ManagedPolicy, problems: [ManagedPolicy.Problem]) { + ManagedPolicy.read({ values[$0] }, knownEngines: engines) + } + + private static var user: Settings { + var settings = Settings(engineID: ultra) + settings.polishModel = .s1Mini + return settings + } + + @Test func noForcedValueIsNoPolicy() { + let (policy, problems) = Self.read([:]) + #expect(policy == .none) + #expect(policy.isEmpty) + #expect(problems.isEmpty) + } + + @Test func everyKeyIsRead() { + let (policy, problems) = Self.read([ + .allowedEngines: [Self.v3.rawValue], + .polishDictations: false, + .allowedPolishModels: ["appleIntelligence"], + .learnCorrections: true, + .clipboardMode: true, + .updateChecks: false, + ]) + #expect(problems.isEmpty) + #expect(policy == ManagedPolicy( + allowedEngines: [Self.v3], allowedPolishModels: [.appleIntelligence], + polishDictations: false, learnCorrections: true, updateChecks: false, clipboardMode: true)) + #expect(policy.managedKeys == ManagedPolicy.Key.allCases) + } + + @Test func anUnknownEngineIsDroppedAndTheRestKept() { + let (policy, problems) = Self.read([.allowedEngines: ["whisper", Self.v3.rawValue]]) + #expect(policy.allowedEngines == [Self.v3]) + #expect(problems == [.unknownValues(.allowedEngines, ["whisper"])]) + } + + @Test func aListWithNoKnownEngineIsIgnoredAsAWhole() { + let (policy, problems) = Self.read([.allowedEngines: ["whisper"]]) + #expect(policy.allowedEngines == nil) + #expect(problems == [.unknownValues(.allowedEngines, ["whisper"]), .noKnownValue(.allowedEngines)]) + } + + @Test func anEmptyListIsIgnored() { + let (policy, problems) = Self.read([.allowedEngines: [String](), .allowedPolishModels: [String]()]) + #expect(policy == .none) + #expect(problems == [.noKnownValue(.allowedEngines), .noKnownValue(.allowedPolishModels)]) + } + + @Test func anUnknownPolishModelIsDropped() { + let (policy, problems) = Self.read([.allowedPolishModels: ["gpt", "s1Mini8Bit", "s1Mini8Bit"]]) + #expect(policy.allowedPolishModels == [.s1Mini8Bit]) + #expect(problems == [.unknownValues(.allowedPolishModels, ["gpt"])]) + } + + @Test func aValueOfTheWrongTypeIsIgnored() { + let (policy, problems) = Self.read([ + .allowedEngines: Self.v3.rawValue, + .polishDictations: "false", + .learnCorrections: 0, + .clipboardMode: 1, + ]) + #expect(policy == .none) + #expect(problems == [ + .wrongType(.allowedEngines), .wrongType(.polishDictations), + .wrongType(.learnCorrections), .wrongType(.clipboardMode), + ]) + } + + @Test func clipboardModeFalseIsNoPolicy() { + #expect(Self.read([.clipboardMode: false]).policy == .none) + } + + @Test func noPolicyLeavesTheSettingsAlone() { + #expect(ManagedPolicy.none.apply(to: Self.user) == Self.user) + } + + @Test func aStoredEngineOutsideTheListRunsTheFirstAllowed() { + let policy = ManagedPolicy(allowedEngines: [Self.v3]) + #expect(policy.apply(to: Self.user).engineID == Self.v3) + #expect(policy.pinsEngine) + } + + @Test func aStoredEngineInsideTheListStays() { + let policy = ManagedPolicy(allowedEngines: [Self.v3, Self.ultra]) + #expect(policy.apply(to: Self.user).engineID == Self.ultra) + #expect(!policy.pinsEngine) + #expect(policy.engines(from: Self.engines) == [Self.ultra, Self.v3]) + } + + @Test func polishIsForcedOnOrOff() { + var user = Self.user + user.polishDictations = true + #expect(!ManagedPolicy(polishDictations: false).apply(to: user).polishDictations) + user.polishDictations = false + #expect(ManagedPolicy(polishDictations: true).apply(to: user).polishDictations) + } + + @Test func aPinnedPolishModelReplacesTheStoredOne() { + let policy = ManagedPolicy(allowedPolishModels: [.appleIntelligence]) + #expect(policy.apply(to: Self.user).polishModel == .appleIntelligence) + #expect(policy.pinsPolishModel) + #expect(policy.polishModels == [.appleIntelligence]) + #expect(ManagedPolicy.none.polishModels == PolishModel.allCases) + } + + @Test func learnedCorrectionsAreForcedOnOrOff() { + var user = Self.user + #expect(!ManagedPolicy(learnCorrections: false).apply(to: user).learnCorrections) + user.learnCorrections = false + #expect(ManagedPolicy(learnCorrections: true).apply(to: user).learnCorrections) + } + + @Test func updateChecksAreForcedOnOrOff() { + var user = Self.user + #expect(ManagedPolicy(updateChecks: true).apply(to: user).checksForUpdatesAutomatically) + user.checksForUpdatesAutomatically = true + let off = ManagedPolicy(updateChecks: false) + #expect(!off.apply(to: user).checksForUpdatesAutomatically) + #expect(!off.allowsUpdateChecks) + #expect(ManagedPolicy(updateChecks: true).allowsUpdateChecks) + #expect(ManagedPolicy.none.allowsUpdateChecks) + } + + @Test func clipboardModeChangesNoSetting() { + #expect(ManagedPolicy(clipboardMode: true).apply(to: Self.user) == Self.user) + } + + @Test func anEditElsewhereKeepsTheUsersOwnManagedValues() { + let policy = ManagedPolicy( + allowedEngines: [Self.v3], allowedPolishModels: [.appleIntelligence], + polishDictations: true, learnCorrections: false, updateChecks: true) + var edited = policy.apply(to: Self.user) + edited.playSounds = false + var expected = Self.user + expected.playSounds = false + #expect(policy.userSettings(from: edited, stored: Self.user) == expected) + } + + @Test func aChoiceAmongSeveralAllowedIsTheUsersOwn() { + let policy = ManagedPolicy(allowedEngines: [Self.ultra, Self.v3]) + var edited = policy.apply(to: Self.user) + edited.engineID = Self.v3 + #expect(policy.userSettings(from: edited, stored: Self.user).engineID == Self.v3) + } + + @Test func withoutAPolicyAnEditIsTakenAsIs() { + var edited = Self.user + edited.engineID = Self.v3 + edited.learnCorrections = false + #expect(ManagedPolicy.none.userSettings(from: edited, stored: Self.user) == edited) + } +} diff --git a/Tests/PladderCoreTests/SettingsTests.swift b/Tests/PladderCoreTests/SettingsTests.swift index f99696d..3088147 100644 --- a/Tests/PladderCoreTests/SettingsTests.swift +++ b/Tests/PladderCoreTests/SettingsTests.swift @@ -21,6 +21,7 @@ import Testing settings.muteOutputWhileDictating = true settings.overlayStyle = .menuBar settings.checksForUpdatesAutomatically = true + settings.learnCorrections = false try store.save(settings) #expect(store.load() == settings) } @@ -39,6 +40,10 @@ import Testing #expect(!Self.defaults.checksForUpdatesAutomatically) } + @Test func learnedCorrectionsAreOnUntilTheUserTurnsThemOff() { + #expect(Self.defaults.learnCorrections) + } + @Test func legacyPolishChordMigratesToTheToggle() throws { let json = #"{"engineID":"echo","polishHotkey":{"keyCodes":[59,31]}}"# let decoded = try JSONDecoder().decode(Settings.self, from: Data(json.utf8)) diff --git a/Tests/PladderSystemTests/ManagedPolicySourceTests.swift b/Tests/PladderSystemTests/ManagedPolicySourceTests.swift new file mode 100644 index 0000000..7673cc5 --- /dev/null +++ b/Tests/PladderSystemTests/ManagedPolicySourceTests.swift @@ -0,0 +1,31 @@ +import CoreFoundation +import Foundation +import PladderCore +import Testing +@testable import PladderSystem + +// A domain of its own, never the app's: that one holds the running copy's Sparkle state. +@Suite struct ManagedPolicySourceTests { + @Test func aValueTheUserWroteIsIgnored() { + let domain = "de.dinooo13.pladder.tests.\(UUID().uuidString)" + let app = domain as CFString + defer { + for key in ManagedPolicy.Key.allCases { CFPreferencesSetAppValue(key.rawValue as CFString, nil, app) } + CFPreferencesAppSynchronize(app) + let plist = FileManager.default.homeDirectoryForCurrentUser + .appending(path: "Library/Preferences/\(domain).plist") + try? FileManager.default.removeItem(at: plist) + } + CFPreferencesSetAppValue(ManagedPolicy.Key.clipboardMode.rawValue as CFString, kCFBooleanTrue, app) + CFPreferencesSetAppValue( + ManagedPolicy.Key.allowedEngines.rawValue as CFString, ["parakeet-tdt-v3-incremental"] as CFArray, app) + CFPreferencesAppSynchronize(app) + #expect(CFPreferencesCopyAppValue(ManagedPolicy.Key.clipboardMode.rawValue as CFString, app) != nil) + + let (policy, problems) = ManagedPolicySource(domain: domain) + .read(knownEngines: [EngineID("parakeet-tdt-v3-incremental")]) + + #expect(policy == .none) + #expect(problems.isEmpty) + } +} diff --git a/Tests/PladderSystemTests/PasteFlowTests.swift b/Tests/PladderSystemTests/PasteFlowTests.swift index 2877b22..d8a7aa0 100644 --- a/Tests/PladderSystemTests/PasteFlowTests.swift +++ b/Tests/PladderSystemTests/PasteFlowTests.swift @@ -151,6 +151,19 @@ extension PasteboardTests { #expect(h.poster.keys == [PasteHarness.keyV]) } + @Test func clipboardModeCopiesWithTheGrantAndPostsNoKey() async throws { + let h = PasteHarness(clipboard: "original") + h.output.setClipboardMode(true) + + let result = try await h.output.insert("hello", submit: true) + + #expect(result == .copied) + #expect(h.clipboard == "hello") + #expect(h.poster.keys.isEmpty) + h.output.setClipboardMode(false) + #expect(try await h.output.insert("again", submit: false) == .pasted) + } + @Test func copyingTheLastTranscriptCarriesTheMarkersAndEndsThePendingRestore() async throws { let h = PasteHarness(clipboard: "original") diff --git a/Tests/PladderTests/CorrectionInboxTests.swift b/Tests/PladderTests/CorrectionInboxTests.swift index c3a6e4e..356deed 100644 --- a/Tests/PladderTests/CorrectionInboxTests.swift +++ b/Tests/PladderTests/CorrectionInboxTests.swift @@ -12,11 +12,12 @@ import Testing private let kotlen = CorrectionPair(heard: "Kotlen", corrected: "Kotlin") private func inbox( - pasting observations: [PasteObservation], reviewer: FakeCorrectionReviewer = FakeCorrectionReviewer() + pasting observations: [PasteObservation], reviewer: FakeCorrectionReviewer = FakeCorrectionReviewer(), + observer: FakePasteObserver? = nil ) throws -> (CorrectionInbox, URL) { let dismissedURL = try scratchDirectory("pladder-inbox").appending(path: "dismissed-corrections.json") let inbox = CorrectionInbox( - dismissedURL: dismissedURL, observer: FakePasteObserver(observations), reviewer: reviewer) + dismissedURL: dismissedURL, observer: observer ?? FakePasteObserver(observations), reviewer: reviewer) return (inbox, dismissedURL) } @@ -88,4 +89,34 @@ import Testing #expect(await waitUntil { inbox.proposals.contains { $0.pair == jemini } }) #expect(inbox.proposals.map(\.pair) == [jemini]) } + + @Test func switchedOffNoFieldIsWatched() async throws { + let observer = FakePasteObserver([Self.claudPaste]) + let (inbox, _) = try inbox(pasting: [], observer: observer) + inbox.isLearning = false + inbox.pasted(Self.claudPaste.pasted) + try await Task.sleep(for: .milliseconds(100)) + #expect(observer.pasted.isEmpty) + #expect(inbox.proposals.isEmpty) + } + + @Test func switchingOffDropsTheWaitingProposals() async throws { + let (inbox, _) = try inbox(pasting: [Self.claudPaste]) + inbox.pasted(Self.claudPaste.pasted) + #expect(await waitUntil { inbox.proposals.count == 1 }) + inbox.isLearning = false + #expect(inbox.proposals.isEmpty) + } + + @Test func aProposalArrivingAfterSwitchingOffIsDropped() async throws { + let (inbox, _) = try inbox(pasting: [Self.claudPaste]) + let quiet = Gate() + inbox.waitUntilQuiet = { await quiet.wait() } + inbox.pasted(Self.claudPaste.pasted) + #expect(await eventually { await quiet.arrivals == 1 }) + inbox.isLearning = false + await quiet.open() + try await Task.sleep(for: .milliseconds(100)) + #expect(inbox.proposals.isEmpty) + } } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index de2c9e2..030536d 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -395,7 +395,10 @@ the text and may offer a dictionary rule. Nothing of it runs before Cmd+V is posted. `CorrectionLearner` runs the stages in order, each cheaper than the next: -1. **Reviewer available?** Without Apple Intelligence the field is not even +1. **Switched on, reviewer available?** With "Suggest entries from my + corrections" off (`learnCorrections`, which a managed policy can force), + `CorrectionInbox` never hands the learner a paste, and drops a proposal + still on its way. Without Apple Intelligence the field is not even watched. 2. **Watch** (`AXPasteObserver`). On its own thread, since every AX call blocks on the target app. The focused element must be a text area, text @@ -458,6 +461,43 @@ The coordinator sees only `DictationSettings`, and the app assigns a new value only when that part changed. `PLADDER_SETTINGS_PATH` points a test copy at a file of its own. +## Managed policy + +An organisation fixes some choices with a configuration profile; what the +keys do, for admins, is in [MANAGED.md](MANAGED.md). The parts: + +- **`ManagedPolicySource`** (`PladderSystem`) reads the profile's keys from the + app's preference domain with `CFPreferencesCopyAppValue`, and only those + `CFPreferencesAppValueIsForced` reports, which are the ones in the + root-owned `/Library/Managed Preferences`. A value the user wrote with + `defaults` is never forced. It calls `CFPreferencesAppSynchronize` before + every read, so a profile installed while the app runs is seen. +- **`ManagedPolicy`** (`PladderCore`) is the value: a list per picker, an + optional Bool per toggle, and `clipboardMode`. `read` turns the raw + property-list values into it, dropping unknown IDs and ignoring a list with + no known one or a value of the wrong type (an `` for a Boolean + too), each reported as a `Problem` for the log. +- **`AppModel`** keeps the user's `Settings`, which is all the file ever + holds, and the settings in effect, `policy.apply(to:)` of them; everything + else, the coordinator and the views included, sees only the latter. A view's + edit comes back through `userSettings(from:stored:)`: a managed value the + edit left as the policy set it keeps what the user had stored, so a save + never writes a managed value and removing the profile gives every choice + back. +- **When.** At launch, before anything is built, so the first monitor is + already the right one, then on the permission poll, every two seconds; + applied only when it changed, through the same `SettingsChange` reactions a + user's edit gets. Nothing is read per dictation, so the release-to-paste + path is untouched. + +**Clipboard mode** is the state the app is in without Accessibility, kept on +purpose: `PermissionMonitor` reports the grant as absent without checking it +and never asks for it, so `HotkeyRouting` picks Carbon and the tap is never +installed; `PasteboardOutput.setClipboardMode` copies instead of posting ⌘V +even with the grant (one relaxed atomic load before the grant check); the +overlay reads no focused field; and the learner never runs, since nothing is +pasted. + ## Superseded work Most of the races the reviews found had one shape: work that outlives what it @@ -521,7 +561,8 @@ redo. The parts split off it: - `HotkeyRouter` holds both monitors and applies what `HotkeyRouting` decides: the tap or Carbon, and the stand-in chord. - `PermissionMonitor` polls Accessibility, the microphone and Secure Event - Input every two seconds for the app's life. + Input every two seconds for the app's life; the app reads the managed policy + on the same poll ([Managed policy](#managed-policy)). - `PolishModelController` owns the polish model, its download and its memory. - `CorrectionInbox` holds the learned-correction proposals. - `UpdateController` holds the updater ([Updates](#updates)). @@ -537,7 +578,7 @@ update controller with their system parts swapped for fakes: the router's monitors (beside a real coordinator), the controller's model files and Metal warm-up, the inbox's Accessibility observer and reviewer, and Sparkle. `AppModel` and the overlay need a running `NSApplication`, so what they decide is a Core value instead: -`HotkeyRouting` and `SettingsChange`. +`HotkeyRouting`, `SettingsChange` and `ManagedPolicy`. ## Updates diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 0ce8afd..e834dcc 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -47,7 +47,15 @@ Three rules decide most questions: macOS `.help` and the accessibility hint are one attribute, so a control with help puts the hint first in it. - **Permissions are asked from a button beside a sentence** saying what the grant is - for ("Lets Pladder paste for you. …"), never by a system prompt at launch. + for ("Lets Pladder paste for you. …"), never by a system prompt at launch. In + Clipboard mode by policy Accessibility is never asked for, and no sentence says + "until you allow it". +- **A managed setting is disabled, never hidden:** the control shows the value the + organisation's profile set, a picker offers only the allowed entries (disabled + when there is one), and the group gets one footer line, "Managed by your + organisation."; in a group the user still owns the rest of, that line is the + control's own second subtitle instead. Without a profile nothing of it shows + (docs/MANAGED.md). - **Get Started** is the top of General only while setup is under way, and stays to the end of that session with "Pladder is ready" and a field to try the first dictation in. A routine model load at launch is not setup. @@ -157,6 +165,7 @@ Look at it before calling it done, light and dark, in English and German: scripts/make-screenshots.sh --settings-scene # the real Settings window, each tab scripts/make-screenshots.sh --settings-scene --get-started # General at its tallest scripts/make-screenshots.sh --settings-scene --accessibility # what VoiceOver is given +scripts/make-screenshots.sh --settings-scene --managed # every managed control, disabled scripts/make-screenshots.sh --menu # the real menu scripts/overlay-demo.sh [dir] [--style …] [--reduce-motion] # every pill path, as contact sheets ``` diff --git a/docs/MANAGED.md b/docs/MANAGED.md new file mode 100644 index 0000000..aaaf4a6 --- /dev/null +++ b/docs/MANAGED.md @@ -0,0 +1,160 @@ +# Managing Pladder + +For an organisation's IT: how to fix, on the Macs you manage, which speech model +Pladder runs, whether it polishes dictations with a language model, whether it +watches text fields to learn corrections, whether it uses Accessibility at all, +and whether it checks for updates. A user cannot undo any of it without admin +rights. + +Everything here is optional. A Mac without a profile behaves exactly as before. + +## How it works + +Pladder reads a **configuration profile** with a Custom Settings payload +(`com.apple.ManagedClient.preferences`) for the preference domain +**`de.dinooo13.pladder`**. Deploy it with any MDM (Jamf, Kandji, Intune, Mosyle, +…) or, on a Mac with no MDM, install it by hand in System Settings → General → +Device Management, which needs an admin, as removing it does. + +- Only values a profile forces count. `defaults write de.dinooo13.pladder …` by + the user, or a file in `/Library/Preferences`, is ignored. +- Pladder never writes the managed domain, and never writes a managed value into + its own settings file. Removing the profile gives every user their own choices + back. +- A profile installed or removed while Pladder runs takes effect within about two + seconds, without a relaunch. A dictation already on its way out finishes under + the values it started with. +- A managed control stays visible in Settings, disabled on its managed value, with + "Managed by your organisation." under its group. +- Nothing is reported anywhere: no telemetry, as ever. + +## Keys + +Two kinds of key, one rule each: **a toggle key forces that toggle** on or off; +**a picker key is a list of what the picker may offer**, and a list of one pins +it. A key that is missing leaves that choice to the user. + +| Key | Type | Effect | +|---|---|---| +| `AllowedEngines` | Array of strings | The speech models the picker offers, by ID: `parakeet-ultra-incremental` (Parakeet Ultra, the default) and `parakeet-tdt-v3-incremental` (Parakeet TDT v3). One ID pins it. A user's stored choice outside the list runs the first allowed model | +| `PolishDictations` | Boolean | Forces the Polish toggle. `false`: no polish model is downloaded or loaded. `true`: every dictation is polished; where the model cannot run (Apple Intelligence off, say) the text is pasted as dictated | +| `AllowedPolishModels` | Array of strings | The polish models the picker offers: `appleIntelligence`, `s1Mini`, `s1Mini8Bit`. `appleIntelligence` alone means nothing is ever downloaded for polish. One pins it | +| `LearnCorrections` | Boolean | Forces "Suggest entries from my corrections" in the Dictionary tab. `false`: no text field is ever read after a paste and no correction is reviewed. `true`: on, where Accessibility and Apple Intelligence allow it | +| `ClipboardMode` | Boolean | `true`: Clipboard mode, below. `false` is the same as leaving the key out | +| `UpdateChecks` | Boolean | Forces "Check for updates automatically". `false` also removes Check for Updates… from the menu, so Pladder makes no update request at all; use it when you deploy updates yourself. `true`: once a day | + +A value of the wrong type, an ID Pladder does not know, or a list with no ID it +knows is ignored and logged, so a typo never leaves Pladder without a speech +model. A forced `s1Mini` or `s1Mini8Bit` with polish on downloads its file (805 MB +or 1.5 GB, from Hugging Face, checked against its SHA-256) at the next dictation, +as a user's choice would. + +### Clipboard mode + +Without Accessibility Pladder still works: it hears its talk key through the +system's hotkey registration, which needs no permission, and leaves the +transcript on the clipboard for the user to paste with ⌘V. `ClipboardMode = true` +keeps it that way even when Accessibility is granted: + +- It never asks for Accessibility: no button in Settings, no menu item. +- It installs no event tap and posts no keystrokes: no ⌘V, no send key. +- It reads no other app's text field: not to place the recording indicator, not to + learn corrections. +- A talk key of modifiers alone, such as Right Command, cannot be registered; + Option+Space stands in for it. + +## Example profile + +Pins Parakeet TDT v3, turns polish and the correction learner off, and stops +update checks. Change the two `PayloadUUID`s (`uuidgen`) and the identifiers to +your own before deploying it. + +```xml + + + + + PayloadType + Configuration + PayloadVersion + 1 + PayloadIdentifier + com.example.pladder + PayloadUUID + 6B1F5E2A-3C4D-4E8F-9A0B-1C2D3E4F5A6B + PayloadDisplayName + Pladder + PayloadScope + System + PayloadContent + + + PayloadType + com.apple.ManagedClient.preferences + PayloadVersion + 1 + PayloadIdentifier + com.example.pladder.preferences + PayloadUUID + 7C2A6F3B-4D5E-4F90-8B1C-2D3E4F5A6B7C + PayloadDisplayName + Pladder settings + PayloadContent + + de.dinooo13.pladder + + Forced + + + mcx_preference_settings + + AllowedEngines + + parakeet-tdt-v3-incremental + + PolishDictations + + LearnCorrections + + UpdateChecks + + + + + + + + + + +``` + +To see what Pladder made of a profile: + +```sh +/usr/bin/log show --last 10m --style compact --predicate 'subsystem == "de.dinooo13.pladder" && category == "settings"' +``` + +It logs `managed policy: ` at launch and whenever the profile +changes, and one line for each value it ignored. + +## Permissions + +- **Microphone** cannot be granted by a profile: a Privacy Preferences Policy + Control (PPPC) payload can only deny it. Each user answers the macOS prompt once. +- **Accessibility** can be pre-granted with a PPPC payload for the bundle ID + `de.dinooo13.pladder` and its Developer ID code requirement (`codesign -dr - + /Applications/Pladder.app`), so the user is never asked. Leave it out, or set + `ClipboardMode`, to keep Pladder off Accessibility. + +## Not covered + +- **Offline model provisioning.** A pinned speech model still downloads about + 700 MB from Hugging Face at first launch. A Mac that cannot reach + `huggingface.co` cannot dictate yet. +- The dictionary, the cleanup steps, the keys, the recording indicator and the + sounds stay the user's. +- The policy binds Pladder as distributed. Someone who builds it from source can + run a copy without it; stopping that is app allow-listing's job (Gatekeeper, + your MDM). +- `pladder-cli`, a developer tool, reads no policy. diff --git a/docs/PRIVACY.md b/docs/PRIVACY.md index c19c0ee..592b5dd 100644 --- a/docs/PRIVACY.md +++ b/docs/PRIVACY.md @@ -4,7 +4,7 @@ Privacy here is not a policy, it is how the thing is built. Audio and text never - **Audio never leaves the Mac.** The microphone is open only while the key is held, and macOS shows the orange indicator only then. Audio goes from the microphone to the Neural Engine and is discarded. - **Text never leaves the Mac.** The transcript exists long enough to be pasted. Your previous clipboard is put back afterwards. -- **Learning a correction reads only what was pasted.** After a paste, Pladder watches the field it pasted into for up to a minute through Accessibility, to notice when you fix a word. It reads only the pasted words and a little context, keeps nothing, and asks before adding anything to the dictionary. The check that a correction is plausible runs on Apple's on-device model. +- **Learning a correction reads only what was pasted.** After a paste, Pladder watches the field it pasted into for up to a minute through Accessibility, to notice when you fix a word. It reads only the pasted words and a little context, keeps nothing, and asks before adding anything to the dictionary. Turn it off in Settings, Dictionary. The check that a correction is plausible runs on Apple's on-device model. - **Polish runs on the Mac too.** Apple's model is part of macOS; S1-mini by Superwhisper runs on your Mac's GPU through llama.cpp. - **Two kinds of request, neither with your words.** Pladder downloads its models once from Hugging Face: the speech model, about 700 MB, on first launch, and, only if you pick S1-mini for the experimental polish, that model too, pinned to a commit and checked against its SHA-256. After that it works with Wi-Fi off. And it checks for updates on GitHub, where its source and releases are: when you choose Check for Updates… in the menu, or once a day if you turn on automatic checks in Settings, which are off until you do. A check fetches one small file, the newest release's `appcast.xml`, and sends nothing about you, your Mac or your dictations; an update it finds is installed only once both its Developer ID signature and its EdDSA signature check out. There is no crash reporter and no analytics. - **No account.** Nothing to sign up for, nothing to log in to, nothing to cancel. diff --git a/docs/USAGE.md b/docs/USAGE.md index 793413a..5d5c6b3 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -31,9 +31,9 @@ For a long dictation, record a **Hands-free** key in Settings: one tap starts a Escape discards a recording without transcribing, held or toggled. It is taken only while a recording is on, so the rest of the time it keeps closing dialogs. -### Without Accessibility +### Clipboard mode, without Accessibility -On an account that cannot grant Accessibility, Pladder still works in a reduced form: Option+Space behaves the same, any combination with a regular key can be recorded, and the transcript is left on the clipboard for you to paste with ⌘V. The send key needs Accessibility, like the paste. [INSTALL.md](../INSTALL.md#first-launch) explains the grant. +On an account that cannot grant Accessibility, Pladder still works in Clipboard mode: Option+Space behaves the same, any combination with a regular key can be recorded, and the transcript is left on the clipboard for you to paste with ⌘V. The send key needs Accessibility, like the paste. [INSTALL.md](../INSTALL.md#first-launch) explains the grant. An organisation can also keep Pladder in Clipboard mode on purpose, even with the grant ([MANAGED.md](MANAGED.md)). ## Your words @@ -43,7 +43,7 @@ A dictionary turns what the model hears into what you meant. "clode code" become ### Learned corrections -Correct a word by hand after a dictation and Pladder offers to remember it: the menu lists it under Suggested Corrections as **Add “x” → “y” to Dictionary**, with **Dismiss** below. Nothing is added until you say so. The pair is checked on device first, so only a plausible mishearing is offered, and a change of case never is. This needs Accessibility and Apple Intelligence. Terminals show a screen rather than a text field, so nothing is learned there. What Pladder reads to notice a correction is in [PRIVACY.md](PRIVACY.md). +Correct a word by hand after a dictation and Pladder offers to remember it: the menu lists it under Suggested Corrections as **Add “x” → “y” to Dictionary**, with **Dismiss** below. Nothing is added until you say so. The pair is checked on device first, so only a plausible mishearing is offered, and a change of case never is. This needs Accessibility and Apple Intelligence; turn it off with **Suggest entries from my corrections** in Settings, Dictionary. Terminals show a screen rather than a text field, so nothing is learned there. What Pladder reads to notice a correction is in [PRIVACY.md](PRIVACY.md). ## Cleaning up the text diff --git a/scripts/make-screenshots.sh b/scripts/make-screenshots.sh index 5f0e5c2..1652aa8 100755 --- a/scripts/make-screenshots.sh +++ b/scripts/make-screenshots.sh @@ -6,12 +6,13 @@ # so it is safe to run while another Pladder is in use; it shows a few # windows for a second or two. # -# Usage: scripts/make-screenshots.sh [dir] [--settings | --settings-scene [--accessibility | --get-started] | --menu] (default: docs/images) +# Usage: scripts/make-screenshots.sh [dir] [--settings | --settings-scene [--accessibility | --get-started] | --menu] [--managed] (default: docs/images) # --settings each Settings tab, light and dark, for reviewing the window # --settings-scene the real Settings window, toolbar and key window included # --settings-scene --accessibility the Settings window's accessibility tree, as text # --settings-scene --get-started the General tab at its tallest, with the end of Get Started # --menu the real menu of a status item of its own, opened in-process; the copy then exits +# --managed any of the above under a sample managed policy: every managed control disabled set -euo pipefail ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"