interplane.Get Omega
Read in your language

hop

Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key.

Brought by drakestapleton

branch main Branches Tags History

hop / Sources / Model.swift

599 lines · 34189 bytes Raw Blame History
1import AppKit
2import SwiftUI
3import Combine
4
5enum Tab: String, CaseIterable, Identifiable {
6 /// `all` is the one box: apps, files, copied text, Hop's screens and questions in a single list. Hop opens on it.
7 /// `agent` is the one conversation: a question is answered and a request is carried out in the same place.
8 case all = "Everything", clipboard = "Clipboard", find = "Find", agent = "Agent", factory = "Factory", accounts = "Accounts", voice = "Voice"
9 var id: String { rawValue }
10 /// The screens offered with these settings: Factory appears only once a factory address is set.
11 static func shown(_ cfg: HopConfig) -> [Tab] { allCases.filter { $0 != .factory || cfg.factoryEnabled } }
12 var icon: String {
13 switch self {
14 case .all: "sparkle.magnifyingglass"
15 case .find: "magnifyingglass"; case .clipboard: "doc.on.clipboard"
16 case .agent: "person.crop.circle.badge.checkmark"; case .factory: "building.2"; case .accounts: "key"; case .voice: "waveform"
17 }
18 }
19 var placeholder: String {
20 switch self {
21 case .all: "Open an app, find a file, paste something you copied, or ask…"
22 case .find: "Find files and apps…"; case .clipboard: "Search clipboard, or type what's bugging you…"
23 case .agent: "Ask anything, or say what you need done… (Enter to send)"
24 case .factory: "Tell the factory what to do… (Enter to send)"; case .accounts: "Filter saved accounts…"
25 case .voice: "Hold Fn anywhere and talk. Type here to search what you dictated…"
26 }
27 }
28}
29
30/// One agent run, as Hop follows it: the whole last thing the agent said (what Cortex is given when the run ends
31/// well) and the messages the run put on the screen. Set and read on the main queue only.
32final class AnswerBox: @unchecked Sendable { var text: String?; var shown: Set<UUID> = [] }
33
34@MainActor
35final class AppModel: ObservableObject {
36 @Published var tab: Tab = .all { didSet { selection = 0; if tab == .all || (tab == .find && query.isEmpty) { searchFiles() }; refreshSmart() } }
37 // The text field writes the same text back when Enter is pressed. That is not a change: it must not move the
38 // highlight to the top (Down then Enter would do the first line), restart the searches or rebuild the list.
39 @Published var query = "" { didSet { guard query != oldValue else { return }; selection = 0; if tab == .find || tab == .all { searchFiles() }; refreshSmart() } }
40 @Published var selection = 0
41 /// The one box's list for what is typed: apps, screens, copied text, files, then the agent.
42 @Published var smartRows: [SmartRow] = []
43 /// Enter was pressed on the agent line, as the top line, while this Mac was still searching its files for the
44 /// text (see `run`). It is carried out when that search is done, and forgotten when the text changes, the box
45 /// is left or a new conversation is started.
46 var sendWhenSettled: String?
47 /// The moment Hop was opened: which app was in front. Set by `captureContext()` each time the window appears.
48 var context = HopContext()
49 /// Apps that were in front lately, newest first. In memory only.
50 var recentApps: [String] = []
51 let appCatalog = AppCatalog()
52 var launchDryRun: ((String) -> Void)? // UI self-test: record the app instead of opening it
53 var openSettings: () -> Void = {}
54 var quitApp: () -> Void = {}
55 private var watchers = Set<AnyCancellable>()
56 @Published var fileHits: [FileIndex.Hit] = []
57 @Published var modelName: String = ""
58 /// The one conversation. Questions and requests go in here alike, and so does whatever answers them.
59 @Published var agentLog: [ChatMessage] = []
60 /// A message is being answered or worked on.
61 @Published var agentRunning = false
62 let parkingLot = ParkingLot(file: HopConfig.dir.appendingPathComponent("parking-lot/ideas.json"))
63 /// The last answer can be asked again of a stronger mind (`PickOutcome.strongerLeft`).
64 @Published var strongerLeft = false
65 /// Decides who takes each message, and runs it (Pick.swift). Hop's screen never names a model or a tool to choose.
66 lazy var pick = Pick(model: self)
67 /// The agent finished while Hop was hidden; the next open lands on its answer.
68 @Published var agentUnseen = false
69 var agentDryRun: ((String) -> Void)? // UI self-test: record the request instead of running an agent
70 /// Asked once, before the first agent tool runs (`Pick`): may tools like this one work on this Mac? Tests
71 /// replace it so no window is shown.
72 var confirmAgentRun: (String) -> Bool = { tool in
73 let alert = NSAlert()
74 alert.messageText = "Let Hop use \(tool) and your other agent tools on this Mac?"
75 alert.informativeText = "For this request Hop wants to use \(tool). An agent tool can read and change files on this Mac. Hop chooses which of your installed tools does each request, so your yes counts for all of them.\n\nHop asks this once. What a tool may do without asking is that tool's own setting."
76 alert.addButton(withTitle: "Run"); alert.addButton(withTitle: "Cancel")
77 return alert.runModal() == .alertFirstButtonReturn
78 }
79 var learnFromAgent = true // UI self-test turns this off so test requests are not saved as knowledge
80 var isPanelVisible: () -> Bool = { true }
81 /// Hop's window is on screen. The sky moves only then.
82 @Published var panelShown = false
83 /// Counted up when a click elsewhere in the window should leave the text box ready to type in.
84 @Published var boxFocus = 0
85 /// Something is being worked on: the spirit quickens.
86 var busy: Bool { agentRunning || factoryRunning || floorLoading }
87 @Published var factoryLog: [ChatMessage] = []
88 @Published var factoryRunning = false
89 @Published var floor = FactorySnapshot()
90 @Published var floorLoading = false
91 private var pendingQuestion: String? // factory chat item waiting for the user's answer
92 @Published var vault: [VaultEntry] = []
93 @Published var indexStatus = ""
94
95 var config: HopConfig
96 let clipboard: ClipboardStore
97 let index: FileIndex
98 let tunnels: TunnelManager
99 let dictation = Dictation()
100 let cortex: Cortex
101 @Published private(set) var notices: [String] = [] // problems with a settings file, shown under the box
102 var tabs: [Tab] { Tab.shown(config) }
103 /// The hint in the box. It promises "type a problem" on Clipboard only when plain Enter really sends it.
104 var placeholder: String {
105 if tab == .agent { return "Let the ideas flow… (Enter parks it for later)" }
106 return tab == .clipboard && !config.enterSendsToAgent ? "Search clipboard… (⇧Enter sends what you typed to the agent)" : tab.placeholder
107 }
108 @Published var agentDetail: AgentDetail = .steps { didSet { if agentDetail.rawValue != config.agentDetail { config.agentDetail = agentDetail.rawValue; config.save() } } }
109 var hide: () -> Void = {}
110 private var factoryRun: CommandRun?
111 private var searchWork: DispatchWorkItem?
112
113 init(startServices: Bool = true) {
114 config = HopConfig.load()
115 agentDetail = AgentDetail(setting: config.agentDetail)
116 clipboard = ClipboardStore(limit: config.clipboardLimit, enabled: startServices)
117 index = FileIndex(roots: config.indexRoots, skipNames: config.indexSkipNames)
118 tunnels = TunnelManager(startServices ? config.links : [])
119 cortex = Cortex(config.cortex)
120 modelName = config.defaultModel ?? config.models.first?.name ?? ""
121 vault = startServices ? Vault.list() : []
122 // The focused background checks need the real model routes without clipboard, accounts,
123 // indexing, dictation services or network connections on the operator's desktop.
124 if !startServices { dictation.model = self; return }
125 updateIndexStatus()
126 if index.builtAt == nil || index.builtAt! < Date().addingTimeInterval(-1800) { rebuildIndex() }
127 refreshMachineIndexes()
128 searchFiles() // empty box shows your most-used items right away
129 dictation.attach(self)
130 cortex.warm()
131 if !config.migratedEngines.isEmpty || config.builtinsChanged { config.save() } // the safer built-in commands, and built-in agents new in this Hop, are written back once
132 notices = SettingsFile.notices // anything wrong with a settings file: shown in the window
133 for n in notices { AppDelegate.log("settings: " + n) }
134 DispatchQueue.main.asyncAfter(deadline: .now() + 20) { [weak self] in self?.cortex.flush() } // send anything still queued from last time
135 // Something new was copied, or history was unlocked, while the one box is showing matches.
136 clipboard.$items.receive(on: RunLoop.main).sink { [weak self] _ in self?.refreshSmart() }.store(in: &watchers)
137 // Which app comes to the front, so the box can offer "the one you were just in". Only the app's place on
138 // disk is kept, in memory; macOS sends this to every app and it needs no permission.
139 NSWorkspace.shared.notificationCenter.publisher(for: NSWorkspace.didActivateApplicationNotification).sink { [weak self] n in
140 guard let app = n.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication,
141 app.activationPolicy == .regular, let path = app.bundleURL?.path else { return }
142 MainActor.assumeIsolated { self?.noteFront(path) }
143 }.store(in: &watchers)
144 Timer.scheduledTimer(withTimeInterval: 1800, repeats: true) { [weak self] _ in
145 MainActor.assumeIsolated { self?.rebuildIndex(); self?.refreshMachineIndexes() }
146 }
147 }
148
149 // MARK: Find
150 func rebuildIndex() {
151 indexStatus = "Indexing your files in the background…"
152 index.rebuild { [weak self] in DispatchQueue.main.async { self?.updateIndexStatus(); self?.searchFiles() } }
153 }
154 func updateIndexStatus() {
155 if let d = index.builtAt {
156 let f = RelativeDateTimeFormatter(); f.unitsStyle = .short
157 indexStatus = "\(index.count.formatted()) items indexed \(f.localizedString(for: d, relativeTo: Date()))"
158 }
159 }
160 /// Local results show at once; each other machine's results merge in as they arrive.
161 func searchFiles() {
162 cortex.searchSoon(tab == .find || tab == .all ? query : "")
163 searchWork?.cancel()
164 remoteSearch?.cancel()
165 remotePending = false
166 if query.trimmingCharacters(in: .whitespaces).isEmpty { // empty box: your most-used things
167 localHits = []; remoteHits = [:]; remoteNote = ""; fileHits = Recents.shared.top(9); settledQuery = ""; refreshSmart(); return
168 }
169 let q = query, idx = index, machines = config.machines
170 let w = DispatchWorkItem { [weak self] in
171 let hits = idx.search(q)
172 DispatchQueue.main.async {
173 guard let self, self.query == q else { return }
174 self.localHits = hits; self.remoteHits = [:]; self.mergeHits()
175 self.settledQuery = q
176 self.refreshSmart()
177 }
178 }
179 searchWork = w
180 DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 0.04, execute: w)
181 guard q.trimmingCharacters(in: .whitespaces).count >= 2, !machines.isEmpty else { remoteNote = ""; return }
182 remotePending = true
183 remoteSearch = Task { [weak self] in
184 try? await Task.sleep(nanoseconds: 220_000_000) // wait for typing to pause
185 if Task.isCancelled { return }
186 for m in machines {
187 let r = await Remote.search(m, q)
188 if Task.isCancelled { return }
189 guard let self, self.query == q else { return }
190 self.remoteHits[m.name] = r.hits
191 self.remoteNote = r.error ?? ""
192 self.mergeHits()
193 }
194 if !Task.isCancelled, let self, self.query == q { self.remotePending = false; self.refreshSmart() } // an Enter may be waiting for this
195 }
196 }
197 private var localHits: [FileIndex.Hit] = []
198 private var remoteHits: [String: [FileIndex.Hit]] = [:]
199 private var remoteSearch: Task<Void, Never>?
200 @Published var remoteNote = ""
201 @Published private(set) var remotePending = false // another machine is still searching
202 @Published private(set) var settledQuery = "" // last text this Mac finished searching for
203 private func mergeHits() {
204 let all = (localHits + remoteHits.values.flatMap { $0 }).map { h -> (FileIndex.Hit, Int) in (h, h.score + Recents.shared.boost(h)) }
205 fileHits = Array(all.sorted { $0.1 > $1.1 }.prefix(60).map(\.0))
206 refreshSmart()
207 }
208 /// Reads the list of apps again (a new one may have been installed since Hop last opened).
209 func refreshApps() { appCatalog.refresh { [weak self] in DispatchQueue.main.async { self?.refreshSmart() } } }
210 func refreshMachineIndexes() {
211 let machines = config.machines
212 Task { for m in machines { await Remote.refreshIndex(m) } }
213 }
214
215 func open(_ path: String, reveal: Bool = false) {
216 let u = URL(fileURLWithPath: path)
217 if reveal { NSWorkspace.shared.activateFileViewerSelecting([u]) } else { NSWorkspace.shared.open(u) }
218 hide()
219 }
220
221 /// Opens a result from any machine. Remote files are copied to this Mac first;
222 /// ⌘Enter (or a remote folder) puts "machine:path" on the clipboard instead.
223 func open(_ hit: FileIndex.Hit, reveal: Bool = false) {
224 Recents.shared.record(hit)
225 guard let name = hit.machine, let m = config.machines.first(where: { $0.name == name }) else {
226 open(hit.path, reveal: reveal); return
227 }
228 let path = hit.isFolder ? String(hit.path.dropLast()) : hit.path
229 if reveal || hit.isFolder {
230 let pb = NSPasteboard.general; pb.clearContents(); pb.setString("\(m.ssh):\(path)", forType: .string)
231 remoteNote = "Copied \(m.name) path to the clipboard. Paste it to your agent to work with it."
232 return
233 }
234 remoteNote = "Bringing \((path as NSString).lastPathComponent) over from \(m.name)…"
235 Task { [weak self] in
236 do {
237 let local = try await Remote.fetch(m, path)
238 NSWorkspace.shared.open(local)
239 self?.remoteNote = ""
240 self?.hide()
241 } catch {
242 let pb = NSPasteboard.general; pb.clearContents(); pb.setString("\(m.ssh):\(path)", forType: .string)
243 self?.remoteNote = error.localizedDescription
244 }
245 }
246 }
247
248 // MARK: Clipboard
249 var clipResults: [ClipItem] { clipboard.search(query) }
250 func paste(_ item: ClipItem) {
251 clipboard.copy(item)
252 hide()
253 if AXIsProcessTrusted() {
254 DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) {
255 let src = CGEventSource(stateID: .combinedSessionState)
256 let down = CGEvent(keyboardEventSource: src, virtualKey: 9, keyDown: true)
257 let up = CGEvent(keyboardEventSource: src, virtualKey: 9, keyDown: false)
258 down?.flags = .maskCommand; up?.flags = .maskCommand
259 down?.post(tap: .cghidEventTap); up?.post(tap: .cghidEventTap)
260 }
261 }
262 }
263
264 // MARK: Models
265 var currentModel: ModelEndpoint? { config.models.first { $0.name == modelName } ?? config.models.first }
266
267 /// The line under an answer from a model server: where the request went, the cost only if the user wrote one
268 /// for this model in the config, tokens and time, then who answered (`AskRoute.who`). Hop never works out a cost itself.
269 nonisolated static func answerMeta(_ ep: ModelEndpoint, tokens: Int, seconds: Double, who: String? = nil) -> String {
270 ([(ep.place == .thisMac ? "🏠 " : "") + ep.place.rawValue, ep.cost, "\(Savings.short(tokens)) tokens", String(format: "%.1f s", seconds), who] as [String?])
271 .compactMap { $0 }.joined(separator: " · ")
272 }
273 nonisolated static let cortexNotesHeader = "Notes from the user's own knowledge base. Use them when they are relevant and say so when they do not cover the question:\n"
274
275 /// New tokens Claude processed for one reply (cache reads are cheap, so they are left out).
276 nonisolated static func claudeTokens(_ j: [String: Any]) -> Int? {
277 guard let u = j["usage"] as? [String: Any] else { return nil }
278 let n = ["input_tokens", "output_tokens", "cache_creation_input_tokens"].compactMap { u[$0] as? Int }.reduce(0, +)
279 return n > 0 ? n : nil
280 }
281
282 // MARK: Agent (the one conversation)
283 /// The one way a message is sent, whatever it is: a question, a request, a follow-up. There is no separate
284 /// "ask" and "do": who answers, and with which tools, is decided for each message by `Pick`.
285 func runAgent() {
286 let text = query.trimmingCharacters(in: .whitespacesAndNewlines)
287 guard !text.isEmpty, !agentRunning else { return }
288 query = ""
289 if let dry = agentDryRun { dry(text); return }
290 let history = Self.history(agentLog)
291 agentLog.append(ChatMessage(role: "user", text: text))
292 begin(text, history: history, stronger: false)
293 }
294
295 /// The last message again, to a stronger mind. Its answer takes the place of the one on show. When the
296 /// stronger mind gives none (it failed, was stopped, or the person said no to a tool), the answer that was
297 /// there comes back: a good answer is never lost to a failed try for a better one.
298 func runStronger() {
299 guard strongerLeft, !agentRunning, let i = agentLog.lastIndex(where: { $0.role == "user" }) else { return }
300 let text = agentLog[i].requestText ?? agentLog[i].text, history = Self.history(Array(agentLog[..<i]))
301 let was = Array(agentLog[(i + 1)...])
302 agentLog.removeSubrange((i + 1)...)
303 strongerLeft = false
304 if let dry = agentDryRun { dry(text); return }
305 setAside = was
306 begin(text, history: history, stronger: true, assessmentOnly: agentLog[i].assessmentOnly)
307 }
308 /// What Stronger took off the screen, until the stronger run has given its own answer.
309 private var setAside: [ChatMessage] = []
310 /// A stronger try is over. When it gave no answer (`ok` false), what it took off the screen (`aside`) comes
311 /// back right after the request, and the half answer the try left behind (`halfReply`) is dropped: the earlier
312 /// answer alone is what the next mind is told was said. Returns whether the earlier answer was put back.
313 nonisolated static func restore(_ log: inout [ChatMessage], aside: [ChatMessage], halfReply: UUID?, ok: Bool) -> Bool {
314 guard !aside.isEmpty, !ok, let i = log.lastIndex(where: { $0.role == "user" }) else { return false }
315 if let halfReply, let at = log.firstIndex(where: { $0.id == halfReply }), at > i { log.remove(at: at) }
316 log.insert(contentsOf: aside, at: i + 1)
317 return true
318 }
319
320 /// What a mind is given of the conversation so far: what was said and what was answered. Hop's own notes
321 /// and empty answers are left out.
322 nonisolated static func history(_ log: [ChatMessage]) -> [ChatMessage] {
323 log.filter { ($0.role == "user" || $0.role == "assistant") && !$0.text.isEmpty }.map { message in
324 guard let request = message.requestText else { return message }
325 var expanded = message
326 expanded.text = request; expanded.requestText = nil
327 return expanded
328 }
329 }
330
331 /// Sorting never replaces the draft or switches off capture. The generated prompt stays behind the scene.
332 func sortParkedIdeas(request: String? = nil) {
333 guard !agentRunning, !parkingLot.ideas.isEmpty else { return }
334 let text = request ?? parkingLot.sortingPrompt
335 let history = Self.history(agentLog)
336 agentLog.append(ChatMessage(role: "user", text: "Sort my parked ideas by feasibility and importance.", requestText: text, assessmentOnly: true))
337 if let dry = agentDryRun { dry(text); return }
338 begin(text, history: history, stronger: false, assessmentOnly: true)
339 }
340
341 private var replyID: UUID? // the answer being written
342 private var runID = 0 // a run that was stopped or cleared away says nothing more
343 private var runMark = 0 // how long the conversation was when the run began
344 private func begin(_ text: String, history: [ChatMessage], stronger: Bool, assessmentOnly: Bool = false) {
345 agentRunning = true; strongerLeft = false; replyID = nil
346 runID += 1; runMark = agentLog.count
347 let run = runID
348 pick.start(text, history: history, stronger: stronger, assessmentOnly: assessmentOnly,
349 say: { [weak self] line in if let self, self.runID == run { self.take(line) } },
350 done: { [weak self] outcome in if let self, self.runID == run { self.finished(outcome) } })
351 }
352
353 /// One line from the run that is answering. The answer is one message that grows; the small lines about who
354 /// was chosen, and anything that went wrong, go in before it so the answer stays the newest thing on show.
355 func take(_ line: PickLine) {
356 let at = replyID.flatMap { id in agentLog.firstIndex { $0.id == id } }
357 switch line {
358 case .progress(let s), .problem(let s):
359 let note = ChatMessage(role: "note", text: s)
360 if let at { agentLog.insert(note, at: at) } else { agentLog.append(note) }
361 case .answer(let piece):
362 if let at { agentLog[at].text += piece }
363 else { let reply = ChatMessage(role: "assistant", text: piece); replyID = reply.id; agentLog.append(reply) }
364 case .restart:
365 if let at { agentLog.remove(at: at) }
366 replyID = nil
367 }
368 }
369
370 /// The run is over: the line under the answer, whether a stronger mind is left to try, and a sound when
371 /// Hop was hidden meanwhile so the next open lands on the answer.
372 func finished(_ o: PickOutcome) {
373 agentRunning = false
374 strongerLeft = o.strongerLeft
375 var putBack = false
376 if !setAside.isEmpty {
377 if Self.restore(&agentLog, aside: setAside, halfReply: replyID, ok: o.ok) { // no stronger answer came: the earlier one is back, and can be tried again
378 runMark += setAside.count
379 strongerLeft = true
380 putBack = true
381 replyID = nil
382 }
383 setAside = []
384 }
385 if let i = replyID.flatMap({ id in agentLog.firstIndex { $0.id == id } }) {
386 if agentLog[i].text.isEmpty { agentLog.remove(at: i) } else if !o.meta.isEmpty { agentLog[i].meta = o.meta }
387 }
388 replyID = nil
389 // The person said no to running a tool: nothing ran, so the request goes back in the box to send again or change.
390 // (Not after Stronger: there the message was answered already, and that answer is back on the screen.)
391 if o.declined, !putBack, query.isEmpty, let i = agentLog.lastIndex(where: { $0.role == "user" }) { query = agentLog.remove(at: i).text }
392 if agentLog.count <= runMark, !o.declined { agentLog.append(ChatMessage(role: "note", text: "(no reply)")) }
393 if !isPanelVisible() {
394 agentUnseen = true
395 NSSound(named: o.ok ? "Glass" : "Basso")?.play()
396 }
397 }
398 /// The name the older single `agentCommand` goes by. It counts only when none of the listed agents is installed.
399 nonisolated static let legacyEngineName = "Custom command"
400 /// Which of the configured agents are installed. One lookup for the app, the self-test and the tests: the login
401 /// shell's PATH plus the usual tool folders (see CommandRun.extraPath).
402 nonisolated static func detectEngines(_ cfg: HopConfig) async -> [AgentEngine] {
403 let all = cfg.agentEngines, legacy = cfg.agentCommand
404 do {
405 let box = LineBox()
406 // One probe per line. Built as a list and joined, so an empty agentEngines list still makes a valid script.
407 var probes = all.map { "command -v \(Shell.quote($0.tool)) >/dev/null 2>&1 && echo \(Shell.quote($0.name))" }
408 if let tool = legacy.first, !tool.isEmpty { probes.append("command -v \(Shell.quote(tool)) >/dev/null 2>&1 && echo HOP-LEGACY-COMMAND") }
409 probes.append("true")
410 let script = probes.joined(separator: "\n")
411 let code: Int32 = await withCheckedContinuation { c in
412 CommandRun(["sh", "-c", script]).start(onLine: { box.add($0) }, onExit: { c.resume(returning: $0) })
413 }
414 if code != 0 { await MainActor.run { AppDelegate.log("agents: the lookup script ended with exit \(code)") } } // never silently "nothing installed"
415 let names = Set(box.text.split(separator: "\n").map(String.init))
416 var found = all.filter { names.contains($0.name) }
417 if found.isEmpty, names.contains("HOP-LEGACY-COMMAND") { found = [AgentEngine(name: legacyEngineName, command: legacy)] }
418 return found
419 }
420 }
421
422 func stopAgent() {
423 guard agentRunning else { return }
424 let run = runID
425 pick.stop()
426 if agentRunning, runID == run { // the run did not close itself: close it here
427 finished(PickOutcome(ok: false, by: "", meta: "", acted: false, strongerLeft: false))
428 if agentLog.last?.text == "(no reply)" { agentLog.removeLast() }
429 agentLog.append(ChatMessage(role: "note", text: "Stopped."))
430 }
431 runID += 1 // closed by itself or here: whatever that run still says is dropped
432 }
433 /// A new conversation: nothing of the old one is kept, here or in whatever was answering.
434 func newAgent() { stopAgent(); agentLog.removeAll(); strongerLeft = false; setAside = []; sendWhenSettled = nil; pick.forget() }
435
436 // MARK: Factory
437 func refreshFactory() {
438 guard config.factoryEnabled, !floorLoading else { return }
439 floorLoading = true
440 let base = config.factoryURL
441 Task { [weak self] in
442 let snap = await FactoryClient.snapshot(base)
443 self?.floor = snap
444 self?.floorLoading = false
445 }
446 }
447
448 /// Plain-English request to the factory. Its dispatcher picks a droid and hands it the job,
449 /// or asks a clarifying question (the user's next message answers it).
450 func askFactory() {
451 let text = query.trimmingCharacters(in: .whitespacesAndNewlines)
452 guard !text.isEmpty, !factoryRunning else { return }
453 query = ""
454 factoryLog.append(ChatMessage(role: "user", text: text))
455 factoryRunning = true
456 let base = config.factoryURL, answering = pendingQuestion
457 pendingQuestion = nil
458 Task { [weak self] in
459 do {
460 let id = try await FactoryClient.ask(base, text: text, answerTo: answering)
461 var last = ""
462 var finished = false
463 for _ in 0..<90 where !finished {
464 try? await Task.sleep(nanoseconds: 1_500_000_000)
465 guard let item = await FactoryClient.chatItem(base, id: id) else { continue }
466 let state = item["state"] as? String ?? ""
467 if state == last { continue }
468 last = state
469 switch state {
470 case "ask":
471 self?.pendingQuestion = id
472 self?.factoryLog.append(ChatMessage(role: "assistant", text: "❓ " + (item["question"] as? String ?? "The factory has a question.") + "\n(Your next message answers this.)"))
473 finished = true
474 case "delivered":
475 let who = item["droid_name"] as? String ?? "a droid"
476 self?.factoryLog.append(ChatMessage(role: "assistant", text: "✓ Handed to \(who): " + (item["message"] as? String ?? "")))
477 finished = true
478 case "error":
479 self?.factoryLog.append(ChatMessage(role: "note", text: item["note"] as? String ?? "The factory couldn't take that."))
480 finished = true
481 default: break
482 }
483 }
484 if !finished {
485 self?.factoryLog.append(ChatMessage(role: "note", text: "Sent. The dispatcher is still deciding; the floor will show the result."))
486 }
487 } catch {
488 self?.factoryLog.append(ChatMessage(role: "note", text: error.localizedDescription))
489 }
490 self?.factoryRunning = false
491 self?.refreshFactory()
492 }
493 }
494
495 func runAction(_ a: FactoryAction) {
496 if a.mutating {
497 let alert = NSAlert()
498 alert.messageText = "Run “\(a.name)” on the factory?"
499 alert.informativeText = "This changes what the factory is doing."
500 alert.addButton(withTitle: "Run"); alert.addButton(withTitle: "Cancel")
501 guard alert.runModal() == .alertFirstButtonReturn else { return }
502 }
503 guard !factoryRunning else { return }
504 factoryLog.append(ChatMessage(role: "user", text: a.name))
505 factoryRunning = true
506 let run = Shell.ssh(host: config.factoryHost, a.command)
507 factoryRun = run
508 let collected = LineBox()
509 run.start(onLine: { collected.add($0) }, onExit: { code in
510 DispatchQueue.main.async { [weak self] in
511 guard let self else { return }
512 self.factoryRunning = false
513 var body = collected.text
514 if code == 255 { body = "Can't reach \(self.config.factoryHost). Is the network or VPN to it connected?\n" + body }
515 self.factoryLog.append(ChatMessage(role: code == 0 ? "assistant" : "note", text: body.isEmpty ? "(no output, exit \(code))" : body))
516 }
517 })
518 }
519 func openFloor() { if let u = URL(string: config.factoryURL) { NSWorkspace.shared.open(u) }; hide() }
520 func stopFactory() { factoryRun?.stop() }
521
522 // MARK: Accounts
523 func reloadVault() { vault = Vault.list() }
524 func copySecret(_ e: VaultEntry) {
525 guard let s = Vault.secret(e.account) else { return }
526 let pb = NSPasteboard.general
527 pb.clearContents()
528 pb.declareTypes([.string, NSPasteboard.PasteboardType("org.nspasteboard.ConcealedType")], owner: nil)
529 pb.setString(s, forType: .string) // marked concealed so clipboard history skips it
530 pb.setString("", forType: NSPasteboard.PasteboardType("org.nspasteboard.ConcealedType"))
531 }
532
533 // MARK: Keyboard
534 var rowCount: Int {
535 switch tab {
536 case .all: smartShown
537 case .find: fileHits.count; case .clipboard: clipResults.count
538 case .accounts: vault.filter { query.isEmpty || $0.account.localizedCaseInsensitiveContains(query) }.count
539 default: 0
540 }
541 }
542 func move(_ d: Int) { let n = rowCount; guard n > 0 else { return }; selection = min(max(0, selection + d), n - 1) }
543 /// Tab / Shift-Tab (or ←/→ in an empty box) moves between screens.
544 func cycleTab(_ d: Int) {
545 let all = tabs
546 let i = all.firstIndex(of: tab) ?? 0
547 tab = all[(i + d + all.count) % all.count]
548 }
549
550 /// Hand whatever is typed to the agent, from any screen, and watch it answer or work.
551 func fixIt() {
552 let text = query.trimmingCharacters(in: .whitespacesAndNewlines)
553 guard !text.isEmpty else { return }
554 guard !agentRunning else {
555 agentLog.append(ChatMessage(role: "note", text: "Still working. Your draft has not been sent."))
556 return
557 }
558 tab = .agent
559 query = text
560 runAgent()
561 }
562
563 /// The rule behind `enterSendsToAgent`: only when the user switched it on, and only for sentence-like text.
564 nonisolated static func sentenceGoesToAgent(_ query: String, enabled: Bool) -> Bool {
565 enabled && query.split(whereSeparator: \.isWhitespace).count >= 3
566 }
567
568 /// True when plain Enter sends the text to the agent. Never by default: three words with no match can just as
569 /// well be a search for a file that is not there. With `enterSendsToAgent` on, it applies to sentence-like text
570 /// (3+ words) that matches nothing. ⇧Enter sends anything to the agent from any screen, on purpose.
571 var enterGoesToAgent: Bool {
572 guard Self.sentenceGoesToAgent(query, enabled: config.enterSendsToAgent), !agentRunning else { return false }
573 switch tab {
574 case .clipboard, .accounts: return rowCount == 0
575 case .find: return fileHits.isEmpty && settledQuery == query && !remotePending
576 default: return false
577 }
578 }
579
580 func submit(alt: Bool) {
581 if enterGoesToAgent { fixIt(); return }
582 switch tab {
583 case .all: // the one box: Enter does the highlighted line, typed or not
584 if selection < smartShown, smartRows.indices.contains(selection) { run(smartRows[selection], alt: alt) }
585 case .find: if fileHits.indices.contains(selection) { open(fileHits[selection], reveal: alt) }
586 case .clipboard: let r = clipResults; if r.indices.contains(selection) { paste(r[selection]) }
587 case .agent:
588 let saved = parkingLot.capture(query)
589 if saved { query = ""; boxFocus += 1 }
590 if !UITest.active && (saved || parkingLot.problem != nil) {
591 NSAccessibility.post(element: NSApplication.shared, notification: .announcementRequested,
592 userInfo: [.announcement: saved ? "Idea saved to the parking lot." : parkingLot.problem!,
593 .priority: NSAccessibilityPriorityLevel.medium.rawValue])
594 }
595 case .factory: askFactory()
596 case .accounts, .voice: break
597 }
598 }
599}