hop
Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key.
Brought by drakestapleton
| 1 | import Foundation |
| 2 | |
| 3 | /// Problems with a settings file, in plain words. They are shown in Hop's window and written to hop.log. |
| 4 | /// A file Hop could not read is never saved over. |
| 5 | enum SettingsFile { |
| 6 | nonisolated(unsafe) private static var messages: [String] = [] |
| 7 | nonisolated(unsafe) private static var brokenPaths: Set<String> = [] |
| 8 | private static let lock = NSLock() |
| 9 | |
| 10 | static var notices: [String] { lock.lock(); defer { lock.unlock() }; return messages } |
| 11 | static func note(_ s: String) { lock.lock(); if !messages.contains(s) { messages.append(s) }; lock.unlock() } |
| 12 | static func isBroken(_ url: URL) -> Bool { lock.lock(); defer { lock.unlock() }; return brokenPaths.contains(url.path) } |
| 13 | |
| 14 | /// Why a file did not decode, short enough to show. |
| 15 | static func why(_ error: Error) -> String { |
| 16 | func at(_ c: DecodingError.Context) -> String { c.codingPath.isEmpty ? "" : " at " + c.codingPath.map { $0.intValue.map { "[\($0)]" } ?? $0.stringValue }.joined(separator: ".") } |
| 17 | switch error { |
| 18 | case DecodingError.dataCorrupted(let c): |
| 19 | return ((c.underlyingError as NSError?)?.userInfo["NSDebugDescription"] as? String ?? c.debugDescription) + at(c) |
| 20 | case DecodingError.typeMismatch(_, let c), DecodingError.valueNotFound(_, let c): return c.debugDescription + at(c) |
| 21 | case DecodingError.keyNotFound(let k, let c): return "\"\(k.stringValue)\" is missing" + at(c) |
| 22 | default: return error.localizedDescription |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | /// The file exists but is not valid settings: leave it exactly as it is, keep one copy beside it |
| 27 | /// (<name>.bad-<UTC time>), refuse to save over it for the rest of this run, and say so. Returns the message. |
| 28 | @discardableResult |
| 29 | static func keepBroken(_ url: URL, _ data: Data?, why: String) -> String { |
| 30 | let fm = FileManager.default, dir = url.deletingLastPathComponent(), base = url.lastPathComponent + ".bad-" |
| 31 | var copy: String? |
| 32 | if let data { |
| 33 | copy = ((try? fm.contentsOfDirectory(atPath: dir.path)) ?? []).filter { $0.hasPrefix(base) } |
| 34 | .first { (try? Data(contentsOf: dir.appendingPathComponent($0))) == data } // already kept |
| 35 | if copy == nil { |
| 36 | let f = DateFormatter(); f.dateFormat = "yyyyMMdd'T'HHmmss'Z'"; f.timeZone = TimeZone(identifier: "UTC"); f.locale = Locale(identifier: "en_US_POSIX") |
| 37 | let name = base + f.string(from: Date()), dest = dir.appendingPathComponent(name) |
| 38 | if (try? data.write(to: dest)) != nil { |
| 39 | try? fm.setAttributes([.posixPermissions: 0o600], ofItemAtPath: dest.path); copy = name |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | lock.lock(); brokenPaths.insert(url.path); lock.unlock() |
| 44 | let msg = "\(url.lastPathComponent) could not be read (\(why)). Hop left the file as it is, is running on its built-in settings, and will not save over it. " |
| 45 | + (copy.map { "A copy is at \($0) in the same folder. " } ?? "") |
| 46 | + "Fix \(url.path) (menu bar icon, Settings) and reopen Hop." |
| 47 | note(msg) |
| 48 | return msg |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | /// User-editable settings, stored as JSON at ~/Library/Application Support/Hop/config.json. |
| 53 | /// Secrets never live here: anything secret is a Keychain entry referenced by name. |
| 54 | struct ModelEndpoint: Codable, Identifiable, Hashable { |
| 55 | var id: String { name } |
| 56 | var name: String // label shown in the picker |
| 57 | var baseURL: String // OpenAI-compatible base, e.g. http://127.0.0.1:8080/v1 |
| 58 | var model: String // model id sent in the request |
| 59 | var keychainKey: String? // optional Vault entry holding the bearer token |
| 60 | var kind: String = "openai" // "openai" = HTTP server, "claude-cli" = Claude Code with your subscription |
| 61 | var rewrite: Bool = true // false = never used to rewrite or polish selected text (for small models that mangle it) |
| 62 | var cost: String? // "free" or "paid", only when the user wrote it in the config; Hop shows it as written and never guesses |
| 63 | /// How strong this model is when Hop picks who answers: 1 instant, 2 fast, 3 strong, 4 frontier. Only when the |
| 64 | /// user wrote it in the config; absent = Hop's own rule (Fusion.seats: an own model counts as strong). |
| 65 | var tier: Int? |
| 66 | |
| 67 | init(name: String, baseURL: String, model: String, keychainKey: String? = nil, kind: String = "openai", rewrite: Bool = true) { |
| 68 | self.name = name; self.baseURL = baseURL; self.model = model; self.keychainKey = keychainKey; self.kind = kind; self.rewrite = rewrite |
| 69 | } |
| 70 | init(from decoder: Decoder) throws { |
| 71 | let c = try decoder.container(keyedBy: CodingKeys.self) |
| 72 | name = try c.decode(String.self, forKey: .name) |
| 73 | baseURL = try c.decodeIfPresent(String.self, forKey: .baseURL) ?? "" |
| 74 | model = try c.decodeIfPresent(String.self, forKey: .model) ?? "" |
| 75 | keychainKey = try c.decodeIfPresent(String.self, forKey: .keychainKey) |
| 76 | kind = try c.decodeIfPresent(String.self, forKey: .kind) ?? "openai" |
| 77 | rewrite = try c.decodeIfPresent(Bool.self, forKey: .rewrite) ?? true |
| 78 | let said = (try? c.decodeIfPresent(String.self, forKey: .cost))?.lowercased() |
| 79 | cost = said == "free" || said == "paid" ? said : nil |
| 80 | tier = (try? c.decodeIfPresent(Int.self, forKey: .tier)).flatMap { (1...4).contains($0) ? $0 : nil } |
| 81 | } |
| 82 | |
| 83 | /// Where a request to this model goes, judged by its address and nothing else. It says nothing about cost: |
| 84 | /// a forwarded port on this Mac's own address can lead to any service. |
| 85 | enum Place: String { case thisMac = "on this Mac", network = "on your network", online = "online" } |
| 86 | var place: Place { |
| 87 | guard kind == "openai", let host = URL(string: baseURL)?.host?.lowercased() else { return .online } |
| 88 | if host == "127.0.0.1" || host == "localhost" || host == "::1" { return .thisMac } |
| 89 | return host.hasSuffix(".local") ? .network : .online |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | /// Keeps an ssh port-forward open to a service that only listens on another computer of yours. |
| 94 | struct Tunnel: Codable, Hashable { |
| 95 | var localPort: Int |
| 96 | var remotePort: Int |
| 97 | var sshHost: String // ssh alias of that computer, as in ~/.ssh/config |
| 98 | |
| 99 | static func validPort(_ p: Int) -> Bool { (1...65535).contains(p) } |
| 100 | var valid: Bool { Self.validPort(localPort) && Self.validPort(remotePort) } |
| 101 | } |
| 102 | |
| 103 | struct FactoryAction: Codable, Identifiable, Hashable { |
| 104 | var id: String { name } |
| 105 | var name: String // button label |
| 106 | var command: String // shell command run on the factory host over ssh |
| 107 | var mutating: Bool // true = asks before running |
| 108 | } |
| 109 | |
| 110 | /// A coding agent Hop can hand a request to. {prompt} is replaced by the request (passed as one argument). |
| 111 | struct AgentEngine: Codable, Identifiable, Hashable { |
| 112 | var id: String { name } |
| 113 | var name: String |
| 114 | var command: [String] |
| 115 | /// What Hop should know about this agent when it picks who does the work, for a tool it has no entry for or |
| 116 | /// when its own table is wrong for you: `tier` 1 instant, 2 fast, 3 strong, 4 frontier; `family` who makes the |
| 117 | /// model; `cost` next to the others (only the order matters). Absent = Hop's table (Fusion.known). |
| 118 | var tier: Int? = nil |
| 119 | var family: String? = nil |
| 120 | var cost: Int? = nil |
| 121 | var tool: String { command.first ?? "" } |
| 122 | /// In a command, this stands for Hop itself (`hop fuse ...`), wherever the app is installed. |
| 123 | static let selfTool = "{hop}" |
| 124 | /// This entry runs Hop's own chooser (an older "Hop picks" entry, or a preview build's). Hop picks for every |
| 125 | /// request now, so such an entry is never a mind to hand work to: it would only choose again. |
| 126 | var isHopItself: Bool { |
| 127 | tool == Self.selfTool || command.contains { ($0 as NSString).lastPathComponent == "Hop" && $0.contains("/") } && command.contains("fuse") |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | struct HopConfig: Codable { |
| 132 | /// Advanced opt-in: inspect the generated parking-lot request before sending it. |
| 133 | var reviewParkedIdeasBeforeSorting = false |
| 134 | var hotkey: String = "cmd+space" |
| 135 | /// Models for the Ask screen. Out of the box: the Claude CLI, if it is installed. Add any OpenAI-compatible server. |
| 136 | var models: [ModelEndpoint] = [ |
| 137 | ModelEndpoint(name: "Claude (your subscription)", baseURL: "", model: "sonnet", kind: "claude-cli"), |
| 138 | ] |
| 139 | var defaultModel: String? = nil |
| 140 | /// Ask uses your own model first (an OpenAI-compatible model on this Mac or your network that answers its |
| 141 | /// `/health`) when `defaultModel` is not set. Absent = on when such a model is listed; `false` switches it off. |
| 142 | var preferOwnModel: Bool? = nil |
| 143 | /// ssh port-forwards Hop keeps open. None unless you add them. |
| 144 | var tunnels: [Tunnel] = [] |
| 145 | /// Optional: a loopback address of a factory dashboard. Empty = the Factory screen is not shown. |
| 146 | var factoryURL: String = "" |
| 147 | /// What the agent calls you in its standing instructions. Empty = "the user". |
| 148 | var ownerName: String = "" |
| 149 | /// Personal agent on this Mac. {prompt} is replaced by the request text (passed as one argument). |
| 150 | var agentCommand: [String] = ["claude", "-p", "{prompt}", "--output-format", "stream-json", "--verbose"] |
| 151 | var agentWorkingDirectory: String = NSHomeDirectory() |
| 152 | /// Every coding agent Hop knows how to run once and read back. Only the ones installed on this Mac are offered. |
| 153 | var agentEngines: [AgentEngine] = [ |
| 154 | AgentEngine(name: "Claude Code", command: ["claude", "-p", "{prompt}", "--output-format", "stream-json", "--verbose"]), |
| 155 | AgentEngine(name: "Codex", command: ["codex", "exec", "--skip-git-repo-check", "{prompt}"]), |
| 156 | AgentEngine(name: "Grok", command: ["grok", "-p", "{prompt}"]), |
| 157 | AgentEngine(name: "Gemini", command: ["gemini", "-p", "{prompt}"]), |
| 158 | AgentEngine(name: "Antigravity", command: ["agy", "-p", "{prompt}"]), |
| 159 | AgentEngine(name: "Muse", command: ["muse", "exec", "{prompt}"]), |
| 160 | AgentEngine(name: "OpenCode", command: ["opencode", "run", "{prompt}"]), |
| 161 | AgentEngine(name: "Cursor", command: ["cursor-agent", "-p", "--output-format", "text", "{prompt}"]), |
| 162 | AgentEngine(name: "Hermes", command: ["hermes", "-z", "{prompt}"]), |
| 163 | ] |
| 164 | /// The minds Hop may hand a request to. Empty = one per installed agent above and one per model server |
| 165 | /// (Sources/Fusion.swift, `Fusion.seats`). |
| 166 | var fusionSeats: [FusionSeat] = [] |
| 167 | /// The most minds Hop asks at once when it fuses (1 = it never fuses). |
| 168 | var fusionMaxSeats = 3 |
| 169 | /// How many times Hop may hand an answer it is not sure of to a stronger mind. |
| 170 | var fusionEscalations = 1 |
| 171 | /// Flags that switch off a coding tool's own approval prompts or sandbox. The built-in commands above carry none |
| 172 | /// of them; add them in the config file only if you want that. |
| 173 | static let unattendedFlags: Set<String> = ["--dangerously-bypass-approvals-and-sandbox", "--dangerously-skip-permissions", |
| 174 | "--always-approve", "--yolo", "-y", "-f", "--force"] |
| 175 | /// The built-in commands of Hop before 0.3.0 that switched a tool's approval prompts or sandbox off. A saved |
| 176 | /// entry that is exactly one of these is brought to the new built-in command when the config is read, |
| 177 | /// unless `keepAgentFlags` is true. Commands the user wrote differently are never touched. |
| 178 | static let oldUnattendedBuiltins: [String: [String]] = [ |
| 179 | "Codex": ["codex", "exec", "--skip-git-repo-check", "--dangerously-bypass-approvals-and-sandbox", "{prompt}"], |
| 180 | "Grok": ["grok", "--always-approve", "-p", "{prompt}"], |
| 181 | "Gemini": ["gemini", "-y", "-p", "{prompt}"], |
| 182 | "Cursor": ["cursor-agent", "-p", "-f", "--output-format", "text", "{prompt}"], |
| 183 | "Hermes": ["hermes", "--yolo", "-z", "{prompt}"], |
| 184 | ] |
| 185 | /// True = "I have read the agent commands in this file and want them exactly as written", flags and all. |
| 186 | var keepAgentFlags = false |
| 187 | /// Names of the agents whose saved command still switches approval prompts or the sandbox off. |
| 188 | var unattendedEngines: [String] { agentEngines.filter { !Set($0.command).isDisjoint(with: Self.unattendedFlags) }.map(\.name) } |
| 189 | /// Set while reading: which built-in entries were brought to the new commands (not saved in the file). |
| 190 | var migratedEngines: [String] = [] |
| 191 | /// The names of the built-in agents this settings file has already been offered. A built-in agent that a |
| 192 | /// newer Hop brings (Muse, Antigravity) is added to `agentEngines` once; one the person removed stays removed. |
| 193 | var knownBuiltins: [String] = [] |
| 194 | /// The built-in agents of every Hop before `knownBuiltins` existed (0.3.0 to 0.5.0). |
| 195 | static let builtinsBefore = ["Claude Code", "Codex", "Grok", "Gemini", "OpenCode", "Cursor", "Hermes"] |
| 196 | /// Set while reading: built-in agents that were added just now, and whether `knownBuiltins` changed (neither |
| 197 | /// is saved in the file; the app writes the settings back once when the second is true). |
| 198 | var addedEngines: [String] = [] |
| 199 | var builtinsChanged = false |
| 200 | var agentEngine: String = "Claude Code" |
| 201 | /// Plain Enter sends a sentence (three or more words) that matches nothing to the agent. Off by default: |
| 202 | /// a search for a file that does not exist looks the same. Shift-Enter always sends on purpose. |
| 203 | var enterSendsToAgent = false |
| 204 | /// How much of the agent's work the Agent screen shows: "answers" (what it says), "steps" (also the name of |
| 205 | /// each tool it uses), "commands" (also the command, file or search behind each step) or "output" (also what |
| 206 | /// came back). The Agent screen has the same choice; a word Hop does not know reads as "steps". |
| 207 | var agentDetail: String = AgentDetail.steps.rawValue |
| 208 | /// The user has said yes once to "the agent can read and change files on this Mac". Hop asks before the first run. |
| 209 | static let currentAgentConsentVersion = 1 |
| 210 | var agentConfirmed = false |
| 211 | var agentConsentVersion = 0 |
| 212 | var agentToolsAllowed: Bool { agentConfirmed && agentConsentVersion == Self.currentAgentConsentVersion } |
| 213 | var cortex = CortexConfig() |
| 214 | /// Optional: ssh alias of the factory host, and buttons that run a command there. |
| 215 | var factoryHost: String = "" |
| 216 | var factoryActions: [FactoryAction] = [] |
| 217 | /// Optional: the factory's shared board, a text file on the factory host with one post per line. Read over ssh |
| 218 | /// for the Swarm section, never written. Used only when factoryHost is set; empty = not read. |
| 219 | var factoryBoard: String = "~/handoffs/BOARD.md" |
| 220 | /// Where the Swarm section looks for agent swarms on this Mac: every |
| 221 | /// <folder>/<conversation>/.system_generated/swarm that holds a board.jsonl and a members.json. Read only. |
| 222 | var swarmFolders: [String] = ["~/.gemini/antigravity/brain"] |
| 223 | var clipboardLimit: Int = 500 |
| 224 | var indexRoots: [String] = [NSHomeDirectory(), "/Applications", "/System/Applications"] |
| 225 | /// Optional: other computers of yours, searched by Find over ssh. None unless you add them. |
| 226 | var machines: [Machine] = [] |
| 227 | var indexSkipNames: [String] = ["Library", "node_modules", ".git", "target", "build", "dist", |
| 228 | "DerivedData", "__pycache__", "venv", ".venv", ".cache", |
| 229 | "Caches", ".Trash", "site-packages", ".build", "Pods"] |
| 230 | |
| 231 | init() {} |
| 232 | |
| 233 | /// Where Hop keeps its files. `HOP_CONFIG_DIR` points it somewhere else (tests use this so they never |
| 234 | /// read or write the real settings). |
| 235 | static var dir: URL { |
| 236 | let override = ProcessInfo.processInfo.environment["HOP_CONFIG_DIR"] ?? "" |
| 237 | let u = override.isEmpty |
| 238 | ? FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("Hop", isDirectory: true) |
| 239 | : URL(fileURLWithPath: override, isDirectory: true) |
| 240 | try? FileManager.default.createDirectory(at: u, withIntermediateDirectories: true, |
| 241 | attributes: [.posixPermissions: 0o700]) |
| 242 | return u |
| 243 | } |
| 244 | static var url: URL { dir.appendingPathComponent("config.json") } |
| 245 | |
| 246 | /// The result of reading one settings file: the settings to run on, and what the user has to be told. |
| 247 | struct Loaded { var config: HopConfig; var problem: String?; var notes: [String] } |
| 248 | |
| 249 | /// Reads a config file. A file that is not valid settings is never changed: Hop keeps a copy |
| 250 | /// (config.json.bad-<UTC time>), runs on the built-in settings in memory, and says which file is broken. |
| 251 | static func read(_ url: URL) -> Loaded { |
| 252 | guard FileManager.default.fileExists(atPath: url.path) else { return Loaded(config: HopConfig(), problem: nil, notes: []) } |
| 253 | guard let d = try? Data(contentsOf: url) else { |
| 254 | return Loaded(config: HopConfig(), problem: SettingsFile.keepBroken(url, nil, why: "the file cannot be opened"), notes: []) |
| 255 | } |
| 256 | do { |
| 257 | var c = try JSONDecoder().decode(HopConfig.self, from: d) |
| 258 | let notes = c.repair() |
| 259 | return Loaded(config: c, problem: nil, notes: notes) |
| 260 | } catch { |
| 261 | return Loaded(config: HopConfig(), problem: SettingsFile.keepBroken(url, d, why: SettingsFile.why(error)), notes: []) |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | /// Makes a decoded config safe to run on and returns what was changed, in plain words. |
| 266 | mutating func repair() -> [String] { |
| 267 | var notes: [String] = [] |
| 268 | // A shortcut that would take over a typing key is not used; the value in the file is left as written. |
| 269 | if let problem = Hotkey.resolve(hotkey).problem { notes.append(problem) } |
| 270 | // A port outside 1..65535 cannot be opened: skip that entry instead of failing at launch. |
| 271 | for t in tunnels where !t.valid { |
| 272 | notes.append("config.json: the forwarded port \(t.localPort) -> \(t.sshHost):\(t.remotePort) was skipped. Ports must be between 1 and 65535.") |
| 273 | } |
| 274 | tunnels.removeAll { !$0.valid } |
| 275 | if cortex.enabled, !cortex.host.isEmpty, let p = URL(string: cortex.url)?.port, !(Tunnel.validPort(p) && Tunnel.validPort(cortex.remotePort)) { |
| 276 | notes.append("config.json: Cortex is not forwarded: port \(p) -> \(cortex.host):\(cortex.remotePort) is not between 1 and 65535.") |
| 277 | } |
| 278 | // Built-in agent commands saved by an older Hop: bring them to the commands that keep the tools' own prompts. |
| 279 | if !keepAgentFlags { |
| 280 | let safe = Dictionary(uniqueKeysWithValues: HopConfig().agentEngines.map { ($0.name, $0.command) }) |
| 281 | for i in agentEngines.indices { |
| 282 | let e = agentEngines[i] |
| 283 | if Self.oldUnattendedBuiltins[e.name] == e.command, let now = safe[e.name] { agentEngines[i].command = now; migratedEngines.append(e.name) } |
| 284 | } |
| 285 | if !migratedEngines.isEmpty { |
| 286 | notes.append("The built-in commands for \(migratedEngines.joined(separator: ", ")) no longer switch off those tools' own approval prompts or sandbox. To run them unattended again, add the flags to agentEngines in config.json and set keepAgentFlags to true.") |
| 287 | } |
| 288 | } |
| 289 | // Built-in agents this file has not been offered yet (a newer Hop knows more tools): add them once. Only to a |
| 290 | // list that still holds one of Hop's own entries: a list the person emptied, or filled with their own |
| 291 | // commands alone, is theirs and stays as it is. |
| 292 | let builtins = HopConfig().agentEngines |
| 293 | let keepsHopsList = agentEngines.contains { e in builtins.contains { $0.name == e.name } } |
| 294 | for b in builtins where keepsHopsList && !knownBuiltins.contains(b.name) && !agentEngines.contains(where: { $0.name == b.name || $0.command == b.command }) { |
| 295 | agentEngines.append(b); addedEngines.append(b.name) |
| 296 | } |
| 297 | if Set(builtins.map(\.name)) != Set(knownBuiltins) { knownBuiltins = builtins.map(\.name); builtinsChanged = true } |
| 298 | // The chooser takes 1 to 8 minds at once and 0 to 3 hand-ons (Omega/FUSE.md, input words 8 and 9). |
| 299 | if !(1...8).contains(fusionMaxSeats) { |
| 300 | let use = min(max(fusionMaxSeats, 1), 8) |
| 301 | notes.append("config.json: fusionMaxSeats is \(fusionMaxSeats); it must be between 1 and 8. Hop uses \(use).") |
| 302 | fusionMaxSeats = use |
| 303 | } |
| 304 | if !(0...3).contains(fusionEscalations) { |
| 305 | let use = min(max(fusionEscalations, 0), 3) |
| 306 | notes.append("config.json: fusionEscalations is \(fusionEscalations); it must be between 0 and 3. Hop uses \(use).") |
| 307 | fusionEscalations = use |
| 308 | } |
| 309 | return notes |
| 310 | } |
| 311 | |
| 312 | /// Every forwarded port Hop keeps open: the configured ones, plus the one to Cortex when it runs on another computer. |
| 313 | var links: [Tunnel] { |
| 314 | var l = tunnels.filter(\.valid) |
| 315 | let cx = cortex |
| 316 | if cx.enabled, !cx.host.isEmpty, let port = URL(string: cx.url)?.port, !l.contains(where: { $0.localPort == port }) { |
| 317 | let t = Tunnel(localPort: port, remotePort: cx.remotePort, sshHost: cx.host) |
| 318 | if t.valid { l.append(t) } |
| 319 | } |
| 320 | return l |
| 321 | } |
| 322 | |
| 323 | static func load() -> HopConfig { |
| 324 | let u = url |
| 325 | guard FileManager.default.fileExists(atPath: u.path) else { // first run: write the built-in settings out |
| 326 | var c = HopConfig() |
| 327 | c.knownBuiltins = c.agentEngines.map(\.name) // a new file has been offered every built-in agent of this Hop |
| 328 | c.save() |
| 329 | return c |
| 330 | } |
| 331 | let r = read(u) |
| 332 | r.notes.forEach(SettingsFile.note) |
| 333 | return r.config |
| 334 | } |
| 335 | |
| 336 | func save() { |
| 337 | guard !SettingsFile.isBroken(HopConfig.url) else { return } // never over a file Hop could not read |
| 338 | let enc = JSONEncoder() |
| 339 | enc.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] |
| 340 | if let d = try? enc.encode(self) { |
| 341 | try? d.write(to: HopConfig.url, options: .atomic) |
| 342 | try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: HopConfig.url.path) |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | enum CodingKeys: String, CodingKey { |
| 347 | case reviewParkedIdeasBeforeSorting, hotkey, models, defaultModel, preferOwnModel, agentCommand, agentWorkingDirectory, factoryHost, |
| 348 | factoryURL, tunnels, factoryActions, clipboardLimit, indexRoots, indexSkipNames, machines, |
| 349 | agentEngines, agentEngine, cortex, ownerName, enterSendsToAgent, agentDetail, agentConfirmed, agentConsentVersion, keepAgentFlags, |
| 350 | factoryBoard, swarmFolders, fusionSeats, fusionMaxSeats, fusionEscalations, knownBuiltins |
| 351 | } |
| 352 | |
| 353 | /// The Factory screen and the factory sign-ins exist only once a factory address is set. |
| 354 | /// The shortcut Hop registers: `hotkey` when it is a safe one, the default otherwise. |
| 355 | var effectiveHotkey: String { Hotkey.resolve(hotkey).use } |
| 356 | var factoryEnabled: Bool { !factoryURL.trimmingCharacters(in: .whitespaces).isEmpty } |
| 357 | /// How the agent refers to the person it works for. |
| 358 | var owner: String { let n = ownerName.trimmingCharacters(in: .whitespaces); return n.isEmpty ? "the user" : n } |
| 359 | |
| 360 | /// Tolerates configs written by older builds that lack newer keys. |
| 361 | init(from decoder: Decoder) throws { |
| 362 | self.init() |
| 363 | let c = try decoder.container(keyedBy: CodingKeys.self) |
| 364 | reviewParkedIdeasBeforeSorting = try c.decodeIfPresent(Bool.self, forKey: .reviewParkedIdeasBeforeSorting) ?? false |
| 365 | hotkey = try c.decodeIfPresent(String.self, forKey: .hotkey) ?? hotkey |
| 366 | models = try c.decodeIfPresent([ModelEndpoint].self, forKey: .models) ?? models |
| 367 | defaultModel = try c.decodeIfPresent(String.self, forKey: .defaultModel) ?? defaultModel |
| 368 | preferOwnModel = try c.decodeIfPresent(Bool.self, forKey: .preferOwnModel) ?? preferOwnModel |
| 369 | agentCommand = try c.decodeIfPresent([String].self, forKey: .agentCommand) ?? agentCommand |
| 370 | agentWorkingDirectory = try c.decodeIfPresent(String.self, forKey: .agentWorkingDirectory) ?? agentWorkingDirectory |
| 371 | factoryHost = try c.decodeIfPresent(String.self, forKey: .factoryHost) ?? factoryHost |
| 372 | factoryURL = try c.decodeIfPresent(String.self, forKey: .factoryURL) ?? factoryURL |
| 373 | tunnels = try c.decodeIfPresent([Tunnel].self, forKey: .tunnels) ?? tunnels |
| 374 | factoryActions = try c.decodeIfPresent([FactoryAction].self, forKey: .factoryActions) ?? factoryActions |
| 375 | clipboardLimit = try c.decodeIfPresent(Int.self, forKey: .clipboardLimit) ?? clipboardLimit |
| 376 | indexRoots = try c.decodeIfPresent([String].self, forKey: .indexRoots) ?? indexRoots |
| 377 | indexSkipNames = try c.decodeIfPresent([String].self, forKey: .indexSkipNames) ?? indexSkipNames |
| 378 | machines = try c.decodeIfPresent([Machine].self, forKey: .machines) ?? machines |
| 379 | agentEngines = try c.decodeIfPresent([AgentEngine].self, forKey: .agentEngines) ?? agentEngines |
| 380 | agentEngine = try c.decodeIfPresent(String.self, forKey: .agentEngine) ?? agentEngine |
| 381 | cortex = try c.decodeIfPresent(CortexConfig.self, forKey: .cortex) ?? cortex |
| 382 | ownerName = try c.decodeIfPresent(String.self, forKey: .ownerName) ?? ownerName |
| 383 | enterSendsToAgent = try c.decodeIfPresent(Bool.self, forKey: .enterSendsToAgent) ?? enterSendsToAgent |
| 384 | agentDetail = try c.decodeIfPresent(String.self, forKey: .agentDetail) ?? agentDetail |
| 385 | agentConsentVersion = try c.decodeIfPresent(Int.self, forKey: .agentConsentVersion) ?? 0 |
| 386 | agentConfirmed = (try c.decodeIfPresent(Bool.self, forKey: .agentConfirmed) ?? false) |
| 387 | && agentConsentVersion == Self.currentAgentConsentVersion |
| 388 | keepAgentFlags = try c.decodeIfPresent(Bool.self, forKey: .keepAgentFlags) ?? keepAgentFlags |
| 389 | factoryBoard = try c.decodeIfPresent(String.self, forKey: .factoryBoard) ?? factoryBoard |
| 390 | swarmFolders = try c.decodeIfPresent([String].self, forKey: .swarmFolders) ?? swarmFolders |
| 391 | fusionSeats = try c.decodeIfPresent([FusionSeat].self, forKey: .fusionSeats) ?? fusionSeats |
| 392 | fusionMaxSeats = try c.decodeIfPresent(Int.self, forKey: .fusionMaxSeats) ?? fusionMaxSeats |
| 393 | fusionEscalations = try c.decodeIfPresent(Int.self, forKey: .fusionEscalations) ?? fusionEscalations |
| 394 | // A file from before this key was offered the built-in agents of its time (`builtinsBefore`): what it lacks |
| 395 | // of those the person removed, and it stays removed. Only agents newer than that are added, once (`repair`). |
| 396 | knownBuiltins = try c.decodeIfPresent([String].self, forKey: .knownBuiltins) ?? Self.builtinsBefore |
| 397 | } |
| 398 | } |