diff --git a/README.md b/README.md index 8fa7f4e..eb057b3 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,10 @@ agent in one session list, read, type into and wait on the others. Runs on macOS, Linux and Windows 10 (1809+) / 11. Needs Java 25+ and Maven 3.6.3+. Tested on macOS and Windows 11 with JDK 26, and on Ubuntu 24.04 with JDK 25 and Maven 3.8. +A native macOS port in Swift and AppKit lives in its own repo, +[microhm-appkit](https://github.com/ghosthack/microhm-appkit). It keeps copies of the +phone page, its tests and the icon from this repo; change those files here. + ## Features - **Sidebar.** Sessions with their state (working, waiting for input, idle, dead), sort by diff --git a/app/src/main/resources/web/app.js b/app/src/main/resources/web/app.js index b4f417d..d828a94 100644 --- a/app/src/main/resources/web/app.js +++ b/app/src/main/resources/web/app.js @@ -21,6 +21,7 @@ let sessions = []; // running, from the server let ended = []; // saved sessions that are not running let renderedList = null; const screens = new Map(); // the last screen seen of each session, shown at once on return +const startedAs = new Map(); // names given in the New form, shown until the server's views arrive let listTimer = null; let stream = null; let current = null; // the session being shown @@ -396,7 +397,7 @@ function showSession(name) { show("session-view"); problem("session-problem", ""); const known = screens.get(name) || sessions.find((s) => s.name === name); - $("session-title").textContent = known ? (known.display || known.name) : name; + $("session-title").textContent = known ? (known.display || known.name) : (startedAs.get(name) || name); setSessionState(known ? known.state : ""); drawnStyled = null; $("scroller").style.background = ""; @@ -1153,6 +1154,7 @@ async function startSession(event) { $("new-prompt").value = ""; // the reply reads " started (...)"; the session takes the form's place in history const started = result.text.split(" ")[0]; + if (name) startedAs.set(started, name); replaceView("s=" + encodeURIComponent(started)); } catch (e) { failed("new-problem", e); diff --git a/swift/.gitignore b/swift/.gitignore deleted file mode 100644 index 4c799be..0000000 --- a/swift/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -.build/ -.build-*/ -dist/ -*.xcodeproj -.swiftpm/ diff --git a/swift/PORTING.md b/swift/PORTING.md deleted file mode 100644 index b09cd0d..0000000 --- a/swift/PORTING.md +++ /dev/null @@ -1,49 +0,0 @@ -# Swift port — conventions - -The native macOS port of micro-harness-manager. The Java sources in `../vt`, `../pty`, -`../mux` and `../app` are the specification: port behaviour faithfully, including -comments that explain *why*. Don't redesign. Where Java uses a JVM-only trick (FFM, -the `ControllingTerminal` re-exec, AOT caches, FlatLaf, Swing), use the native macOS -equivalent. - -## Module map - -| Swift target | Java source | Notes | -|---|---|---| -| `MicrohmShared` | — | `MicrohmPaths` (state dirs, ports), `Log`. Shared by all. | -| `MicrohmVT` | `vt/` | Terminal emulator core. Same type names (`TerminalEmulator`, `HeadlessTerminal`, `Line`, `Style`, `ScreenSerializer`, `VtTokenizer`, `KeyNames`, `CharWidth`…). | -| `MicrohmPTY` | `pty/` | POSIX ptys only (`forkpty`/`posix_spawn` + `TIOCSCTTY` natively; no ConPTY). | -| `MicrohmMux` | `mux/` | Daemon (server), client library, CLI logic, protocol v1 **wire-identical** to Java. | -| `microhm-mux` | `mux/.../Main`, `cli/` | Executable: the CLI *and* the daemon (`microhm-mux serve …`, the way the Java launcher starts it). | -| `MicrohmCore` | `app/` minus `ui/`, `terminal/` | Harness plugins, state detection, registry, settings, usage, status, control (SessionController), session launch, MCP server, MCP host, phone server (serves `Resources/web` verbatim). | -| `MicrohmTerminal` | `app/terminal/` | AppKit `TerminalView` (Core Text/Core Graphics), key/mouse/paste encoders, box drawing, palettes, fonts, links, selection. | -| `MicrohmApp` | `app/ui/`, `MicroHarnessManagerApp` | The AppKit app: main window, sidebar, dialogs, settings, menu-bar icon. | -| `microhm-host` | `app/mcphost/McpHost` | Headless background host serving MCP + phone after the app quits. | - -## Rules - -- **Swift 6 toolchain, language mode 5** (set in `Package.swift`), macOS 14+. No - third-party packages: Foundation, Darwin, Network, AppKit, CoreText, CoreImage only. -- **Names.** Keep Java class and method names (Swift-cased) so modules ported in - parallel can code against the Java signatures and still line up. Java records become - structs, enums stay enums, interfaces become protocols. Make the API another module - uses `public`. -- **Concurrency.** Threads + locks (`NSLock`, `DispatchQueue`) the way Java does it are - fine. Don't fight strict concurrency. Mark shared mutable classes `@unchecked Sendable`. -- **Paths.** Never touch `~/.micro-harness-manager` (the user's live Java install). All - state goes through `MicrohmPaths` (default `~/.micro-harness-manager-swift`, override - `MICROHM_HOME`). Default ports are 7402 (MCP) and 7403 (phone). -- **Wire compatibility.** The mux protocol (frames, JSON field names, ops, errors) and the - phone page's HTTP API must match the Java implementation byte for byte where it - matters, so the Java CLI (`../microhm-mux`) and the unmodified web page work against - the Swift servers. -- **Tests.** XCTest, in `Tests/Tests`. Port the Java tests that pin behaviour - (VT golden files are in `Tests/MicrohmVTTests/golden`, loaded via `Bundle.module`). - Tests that spawn processes use temp dirs and set `MicrohmPaths.homeOverride` or - `MICROHM_HOME`, never the real home. -- **Building in parallel.** Several people build at once: always pass your own scratch - path, e.g. `swift build --scratch-path .build-vt` / `swift test --scratch-path .build-vt - --filter MicrohmVTTests`. Only edit files in your own target dirs. If you must touch - `Package.swift`, change only your own target's entry, with a minimal Edit. -- Delete your target's `_Placeholder.swift` / `PlaceholderTests.swift` once you have - real files. diff --git a/swift/Package.swift b/swift/Package.swift deleted file mode 100644 index 02e6ae9..0000000 --- a/swift/Package.swift +++ /dev/null @@ -1,35 +0,0 @@ -// swift-tools-version: 6.0 -// Microhm — native macOS port of micro-harness-manager. See PORTING.md. -import PackageDescription - -let v5: [SwiftSetting] = [.swiftLanguageMode(.v5)] - -let package = Package( - name: "Microhm", - platforms: [.macOS(.v14)], - products: [ - .executable(name: "Microhm", targets: ["MicrohmApp"]), - .executable(name: "microhm-mux", targets: ["microhm-mux"]), - .executable(name: "microhm-host", targets: ["microhm-host"]), - ], - targets: [ - .target(name: "MicrohmShared", swiftSettings: v5), - .target(name: "MicrohmVT", dependencies: ["MicrohmShared"], swiftSettings: v5), - .target(name: "MicrohmPTY", dependencies: ["MicrohmShared"], swiftSettings: v5), - .target(name: "MicrohmMux", dependencies: ["MicrohmShared", "MicrohmVT", "MicrohmPTY"], swiftSettings: v5), - .target(name: "MicrohmCore", dependencies: ["MicrohmShared", "MicrohmVT", "MicrohmMux"], - resources: [.copy("Resources/web")], swiftSettings: v5), - .target(name: "MicrohmTerminal", dependencies: ["MicrohmShared", "MicrohmVT"], swiftSettings: v5), - .target(name: "MicrohmStatusItem", swiftSettings: v5), - .executableTarget(name: "MicrohmApp", dependencies: ["MicrohmCore", "MicrohmTerminal", "MicrohmStatusItem"], - resources: [.copy("Resources/app-icon.png"), .copy("Resources/provider-icons")], - swiftSettings: v5), - .executableTarget(name: "microhm-mux", dependencies: ["MicrohmMux"], swiftSettings: v5), - .executableTarget(name: "microhm-host", dependencies: ["MicrohmCore", "MicrohmStatusItem"], swiftSettings: v5), - .testTarget(name: "MicrohmVTTests", dependencies: ["MicrohmVT"], resources: [.copy("golden")], swiftSettings: v5), - .testTarget(name: "MicrohmPTYTests", dependencies: ["MicrohmPTY"], swiftSettings: v5), - .testTarget(name: "MicrohmMuxTests", dependencies: ["MicrohmMux"], swiftSettings: v5), - .testTarget(name: "MicrohmCoreTests", dependencies: ["MicrohmCore"], swiftSettings: v5), - .testTarget(name: "MicrohmTerminalTests", dependencies: ["MicrohmTerminal"], swiftSettings: v5), - ] -) diff --git a/swift/README.md b/swift/README.md deleted file mode 100644 index cb592a7..0000000 --- a/swift/README.md +++ /dev/null @@ -1,60 +0,0 @@ -# Microhm for macOS (Swift) - -A native macOS port of micro-harness-manager: AppKit, Core Text and Swift, with no -third-party packages. Everything in the main [README](../README.md) applies: -- the sidebar of agent and shell sessions with their states; -- sessions that outlive the app in a background daemon; -- the harness plugins; -- the MCP server and the phone page; -- usage budgets; -- the menu-bar icon. - -The exceptions are listed under [Differences from the Java app](#differences-from-the-java-app). - -## Build and run - -```sh -scripts/build-app.sh # dist/Microhm.app (release, ad-hoc signed) -open dist/Microhm.app -swift test # 803 tests -scripts/phone-e2e.sh # the phone page's Playwright suite against the Swift server -``` - -`SIGN_IDENTITY="Developer ID Application: …" scripts/build-app.sh` signs for distribution. - -The bundle holds three executables in `Contents/MacOS`: -- `Microhm` is the app. -- `microhm-mux` is the session daemon and its CLI (`list`, `capture`, `attach`, `shutdown`, …). -- `microhm-host` is the background host. It keeps MCP, the phone page and the menu-bar icon - running after the app quits, and hands them back when the app reopens. - -## Side by side with the Java app - -| | Java | Swift | -|---|---|---| -| State directory | `~/.micro-harness-manager` | `~/.micro-harness-manager-swift` (`MICROHM_HOME`) | -| Daemon home | `…/mux` | `…/mux` (`MICROHM_MUX_HOME`) | -| MCP port | 7392 | 7402 | -| Phone port | 7393 | 7403 | - -The daemon speaks the same wire protocol (v1) as the Java one. The Java `microhm-mux` CLI -drives a Swift daemon, and the other way round. A Unix socket path must stay under 104 -bytes, so keep `MICROHM_MUX_HOME` short. - -## Layout - -See [PORTING.md](PORTING.md) for the module map: `MicrohmVT` (emulator), `MicrohmPTY`, -`MicrohmMux` (daemon, client, CLI), `MicrohmCore` (harnesses, registry, settings, controller, -MCP, phone), `MicrohmTerminal` (the terminal view), `MicrohmStatusItem` and `MicrohmApp`. - -## Differences from the Java app - -- macOS only (14+). There is no ConPTY or Windows/Linux tray code. -- `forkpty` replaces the `ControllingTerminal` JVM trampoline. -- The Performance tab shows the process's memory, CPU and threads in place of JVM heap and GC. -- `MICROHM_UI_DEBUG=` turns on a development hook. On SIGUSR1 the app runs commands - from `/command` (`select`, `new`, `settings N`, `type …`, `snapshot NAME`, `quit`, …) - and renders its own windows to PNG, so the UI can be checked without screen-recording - permission. -- Additions: dropping files on a terminal types their shell-quoted paths, and the Budgets panel folds - away to a one-line summary (its last good figures stay up, marked stale, when a refresh fails). diff --git a/swift/Sources/MicrohmApp/App/AppDelegate.swift b/swift/Sources/MicrohmApp/App/AppDelegate.swift deleted file mode 100644 index 8c60dde..0000000 --- a/swift/Sources/MicrohmApp/App/AppDelegate.swift +++ /dev/null @@ -1,312 +0,0 @@ -import AppKit -import MicrohmStatusItem -import MicrohmCore -import MicrohmShared - -/// The application: builds the model, the main window, the menu bar and the status item; -/// starts the MCP server and phone page when Settings say so; persists and applies -/// Settings; and tidies up on quit (Java's `MicroHarnessManagerApp` + `MainWindow`'s -/// shutdown). -final class AppDelegate: NSObject, NSApplicationDelegate { - - private var model: AppModel? - private var mainWindow: MainWindowController? - private var settingsWindow: SettingsWindowController? - private let statusItem = StatusItemController() - private let settingsQueue = DispatchQueue(label: "microhm-app-settings") - /// How long quitting waits for the backend's shutdown (servers, background host). - private static let SHUTDOWN_WAIT_SECONDS: Double = 3 - private let serviceQueue = DispatchQueue(label: "microhm-services") - private var statusTimer: Timer? - - func applicationWillFinishLaunching(_ notification: Notification) { - NSApp.mainMenu = MainMenu.build(appDelegate: self) - if let icon = AppResources.appIcon, Bundle.main.bundleIdentifier == nil { - // a plain SwiftPM executable has no bundle icon; the .app has its .icns - NSApp.applicationIconImage = icon - } - } - - func applicationDidFinishLaunching(_ notification: Notification) { - let model = AppModel.makeDefault() - self.model = model - Log.info("started; backend: \(model.backend.name); home: \(MicrohmPaths.home.path)", tag: "app") - - let window = MainWindowController(model: model) - window.onOpenSettings = { [weak self] in self?.showSettings(nil) } - window.onLiveSessionsChanged = { [weak self] in self?.updateStatusItem() } - mainWindow = window - window.showWindow(nil) - window.window?.makeKeyAndOrderFront(nil) - StartupTimes.markWindowShown() - NSApp.activate(ignoringOtherApps: true) - - startServices(model.backend) - - statusItem.onOpen = { [weak self] in self?.showMainWindow(nil) } - statusItem.onHide = { [weak self] in - self?.statusItem.remove() - self?.settingsQueue.async { AppSettings.saveTrayIconEnabled(false) } - } - if AppSettings.trayIconEnabled() { - statusItem.show() - } - // the MCP and phone servers change state off the main thread: keep the menu honest - let timer = Timer(timeInterval: 5, repeats: true) { [weak self] _ in self?.updateStatusItem() } - RunLoop.main.add(timer, forMode: .common) - statusTimer = timer - updateStatusItem() - DebugHooks.install { [weak self] verb, args in self?.debugCommand(verb, args) } - } - - private func debugCommand(_ verb: String, _ args: [String]) { - switch verb { - case "dark": NSApp.appearance = NSAppearance(named: .darkAqua) - case "light": NSApp.appearance = NSAppearance(named: .aqua) - case "system": NSApp.appearance = nil - case "select": args.first.map { mainWindow?.debugSelect($0) } - case "settings": - showSettings(nil) - if let tab = args.first.flatMap(Int.init), - let tabs = settingsWindow?.window?.contentViewController as? NSTabViewController, - tab < tabs.tabViewItems.count { - tabs.selectedTabViewItemIndex = tab - } - case "new": mainWindow?.newSession(nil) - case "create": - if args.count >= 2, let harness = HarnessType(rawValue: args[1]) { - mainWindow?.debugCreate(args[0], harness, message: args.count > 2 ? args.dropFirst(2).joined(separator: " ") : nil) - } - case "type": - // real key events through the window, so the test covers keyDown → input - // method → encoder → daemon, the path a person's typing takes - guard let window = mainWindow?.window else { break } - let text = args.joined(separator: " ") - func post(_ chars: String, keyCode: UInt16) { - for type in [NSEvent.EventType.keyDown, .keyUp] { - if let event = NSEvent.keyEvent(with: type, location: .zero, modifierFlags: [], - timestamp: ProcessInfo.processInfo.systemUptime, - windowNumber: window.windowNumber, context: nil, - characters: chars, charactersIgnoringModifiers: chars, - isARepeat: false, keyCode: keyCode) { - window.sendEvent(event) - } - } - } - for ch in text { post(String(ch), keyCode: ch == " " ? 49 : 0) } - post("\r", keyCode: 36) - case "quit": NSApp.terminate(nil) - case "refresh": mainWindow?.refreshSessions(nil) - case "usage": mainWindow?.showUsage(nil) - case "budgets": mainWindow?.debugToggleBudgets() - case "about": showAbout(nil) - case "batch": mainWindow?.batchCloseSessions(nil) - case "kill": mainWindow?.killSession(nil) - case "endsheet": - for window in NSApp.windows { - if let sheet = window.attachedSheet { window.endSheet(sheet) } - } - case "closeaux": - for window in NSApp.windows where window !== mainWindow?.window && window.isVisible { - window.close() - } - case "size": - if args.count == 2, let w = Double(args[0]), let h = Double(args[1]) { - mainWindow?.window?.setContentSize(NSSize(width: w, height: h)) - } - case "sort": mainWindow?.debugSort(args.first ?? "session") - case "dump": - func walk(_ view: NSView, _ depth: Int) { - if let field = view as? NSTextField, !field.stringValue.isEmpty { - Log.info("dump: \(field.stringValue) hidden=\(field.isHiddenOrHasHiddenAncestor) frame=\(field.frame)", tag: "debug") - } - view.subviews.forEach { walk($0, depth + 1) } - } - for window in NSApp.windows where window.isVisible { - Log.info("dump window \(window.title) \(type(of: window)) sheet=\(window.isSheet) appearance=\(window.effectiveAppearance.name.rawValue)", tag: "debug") - window.contentView.map { walk($0, 0) } - } - default: Log.warn("unknown debug command \(verb)", tag: "debug") - } - } - - /// Starts the MCP server and phone page when their settings are on. A taken port - /// leaves the app running without it — Settings can pick another. - private func startServices(_ backend: SessionBackend) { - serviceQueue.async { [weak self] in - if AppSettings.mcpServerEnabled() { - let port = AppSettings.mcpPort() - do { - try backend.startMcp(port: port, token: AppSettings.mcpToken()) - } catch { - Log.warn("MCP server could not start on \(port): \(error)", tag: "app") - self?.warn("MCP server", "The MCP server could not start on port \(port): \(error.localizedDescription)\n" - + "\(AppModel.appName) runs without it; pick another port in Settings.") - } - } - if AppSettings.phoneServerEnabled() { - let port = AppSettings.phonePort() - do { - try backend.startPhone(port: port, token: AppSettings.phoneToken()) - } catch { - Log.warn("phone page could not start on \(port): \(error)", tag: "app") - self?.warn("Phone page", "The phone page could not start on port \(port): \(error.localizedDescription)\n" - + "\(AppModel.appName) runs without it; pick another port in Settings.") - } - } - DispatchQueue.main.async { self?.updateStatusItem() } - } - } - - private func warn(_ title: String, _ message: String) { - DispatchQueue.main.async { [weak self] in - self?.mainWindow?.showAlert(title, message, style: .warning) - } - } - - private func updateStatusItem() { - guard let model, statusItem.isShown else { return } - let live = mainWindow?.liveManagedEntries.count ?? 0 - let backend = model.backend - serviceQueue.async { [weak self] in - let mcp = backend.mcpRunning ? AppSettings.mcpPort() : nil - let phone = backend.phoneRunning ? AppSettings.phonePort() : nil - DispatchQueue.main.async { - self?.statusItem.update(liveSessions: live, mcpPort: mcp, phonePort: phone) - } - } - } - - // MARK: - menu actions - - @objc func showAbout(_ sender: Any?) { - let credits = NSMutableAttributedString( - string: "Runs coding agents — Claude Code, Codex, Cursor Agent, Grok, OpenCode, Pi, Muse — and shells side by side, in sessions that outlive the window.\n\nState: \(SidebarEntry.abbreviate(MicrohmPaths.home.path))", - attributes: [.font: NSFont.systemFont(ofSize: NSFont.smallSystemFontSize), - .foregroundColor: NSColor.secondaryLabelColor]) - var options: [NSApplication.AboutPanelOptionKey: Any] = [ - .applicationName: AppModel.appName, - .credits: credits, - ] - if Bundle.main.infoDictionary?["CFBundleShortVersionString"] == nil { - options[.applicationVersion] = "1.0.0" - options[.version] = "SwiftPM build" - } - if let icon = AppResources.appIcon { - options[.applicationIcon] = icon - } - NSApp.orderFrontStandardAboutPanel(options: options) - NSApp.activate(ignoringOtherApps: true) - } - - @objc func showSettings(_ sender: Any?) { - guard let model else { return } - let controller = settingsWindow ?? SettingsWindowController() - settingsWindow = controller - let backend = model.backend - controller.phoneLink = { port in backend.phoneLink(port: port, token: AppSettings.phoneToken()) } - controller.shells = backend.installedShells() - controller.describeShell = { backend.describeShell($0) } - controller.onSave = { [weak self] result in self?.applySettings(result) } - controller.present() - } - - @objc func showMainWindow(_ sender: Any?) { - mainWindow?.showWindow(nil) - mainWindow?.window?.makeKeyAndOrderFront(nil) - NSApp.activate(ignoringOtherApps: true) - } - - @objc func openProjectPage(_ sender: Any?) { - if let url = URL(string: "https://github.com/ghosthack/micro-harness-manager") { - NSWorkspace.shared.open(url) - } - } - - @objc func revealLog(_ sender: Any?) { - NSWorkspace.shared.activateFileViewerSelecting([MicrohmPaths.appLog]) - } - - // MARK: - settings - - /// Persists Settings off the main thread, applies them to the window at once, and - /// starts, restarts or stops the MCP server and phone page to match. - private func applySettings(_ result: SettingsResult) { - guard let model else { return } - let backend = model.backend - let mcpWasRunning = backend.mcpRunning - settingsQueue.async { [weak self] in - result.persist() - self?.serviceQueue.async { - if SettingsResult.mcpNeedsApply(result.mcpChanged, enabled: result.mcpServerEnabled, running: mcpWasRunning) { - self?.applyMcp(backend, result) - } - self?.applyPhone(backend, result) - DispatchQueue.main.async { self?.updateStatusItem() } - } - } - // the window's own copy of the settings, applied now so the change shows at once - mainWindow?.applySettings(result) - if result.trayIcon { statusItem.show() } else { statusItem.remove() } - updateStatusItem() - } - - /// A regenerated token is saved first; a running server then restarts with it. - private func applyMcp(_ backend: SessionBackend, _ result: SettingsResult) { - let token = result.mcpTokenRegenerated ? AppSettings.regenerateMcpToken() : AppSettings.mcpToken() - backend.stopMcp() - guard result.mcpServerEnabled else { return } - do { - try backend.startMcp(port: result.mcpPort, token: token) - } catch { - warn("MCP server", "The MCP server could not start on port \(result.mcpPort): \(error.localizedDescription)\n" - + "Pick another port in Settings.") - } - } - - private func applyPhone(_ backend: SessionBackend, _ result: SettingsResult) { - if !result.phoneServerEnabled { - backend.stopPhone() - return - } - do { - try backend.startPhone(port: result.phonePort, token: AppSettings.phoneToken()) - } catch { - warn("Phone page", "The phone page could not start on port \(result.phonePort): \(error.localizedDescription)\n" - + "Pick another port in Settings.") - } - } - - // MARK: - lifecycle - - func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { - true - } - - func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool { - if !flag { showMainWindow(nil) } - return true - } - - func applicationWillTerminate(_ notification: Notification) { - statusTimer?.invalidate() - mainWindow?.shutdown() - statusItem.remove() - // stops serving and hands MCP to the background host while sessions live. Daemon - // calls are involved (the phone's size-backs, the host's session check): off the - // main thread and bounded, so a wedged daemon cannot hang quitting. - if let backend = model?.backend { - let done = DispatchSemaphore(value: 0) - DispatchQueue.global(qos: .userInitiated).async { - backend.shutdown() - done.signal() - } - if done.wait(timeout: .now() + AppDelegate.SHUTDOWN_WAIT_SECONDS) == .timedOut { - Log.warn("quitting before the backend finished shutting down", tag: "app") - } - } - settingsQueue.sync {} - Log.info("quit", tag: "app") - InstanceLock.release(RegistryPaths.resolve()) - } -} diff --git a/swift/Sources/MicrohmApp/Dialogs/BatchOperationSheet.swift b/swift/Sources/MicrohmApp/Dialogs/BatchOperationSheet.swift deleted file mode 100644 index 9b2ff05..0000000 --- a/swift/Sources/MicrohmApp/Dialogs/BatchOperationSheet.swift +++ /dev/null @@ -1,304 +0,0 @@ -import AppKit -import MicrohmCore - -/// The graceful-close ladder for one session in a batch (Java's `BatchCloseDialog -/// .attemptClose` and the Shutdown loop): nil when it closed, otherwise the "name — -/// reason" line for the summary. Blocks: run it off the main thread. -enum BatchActions { - static func close(_ entry: SessionEntry, _ lastPolled: SessionState?, _ closer: GracefulCloser, - _ registry: SessionRegistry) -> String? { - let name = entry.sessionName - do { - let result = try closer.close(name, HarnessPlugins.of(entry.harnessType), lastPolled) - if let id = result.harnessSessionIdOpt { - registry.recordHarnessSessionId(name, id) - } - switch result.outcome { - case .closed, .alreadyGone: return nil - case .busyState: return "\(name) — \(result.detail)" - case .busyForeground: return "\(name) — '\(result.detail)' is still running in it" - case .noQuitSyntax: return "\(name) — no verified graceful-quit syntax" - case .quitTimeout, .exitTimeout: return "\(name) — didn't exit in time" - } - } catch { - return "\(name) — \(error.localizedDescription)" - } - } -} - -/// "Pick some sessions, then act on them" (Java's `BatchOperationDialog` and -/// `SessionChecklist`): a checklist grouped by folder with tri-state folder boxes and -/// Select All, then a live progress pass, then a summary of whatever could not be done. -/// The pass is sequential — two mutations racing on one daemon or registry is needless -/// risk for something this destructive. -final class BatchOperationSheet: NSWindowController { - - struct Words { - let gerund: String - let past: String - let infinitive: String - } - - private static var current: BatchOperationSheet? - - private var groups: [(title: String, members: [SidebarEntry])] = [] - private var boxes: [ObjectIdentifier: NSButton] = [:] - private var headerBoxes: [NSButton] = [] - private let selectAll = NSButton(checkboxWithTitle: "Select All", target: nil, action: nil) - private let confirmButton = NSButton() - private let cancelButton = NSButton() - private let doneButton = NSButton() - private let checklist = NSScrollView() - private let progress = NSProgressIndicator() - private let progressLabel = NSTextField(labelWithString: "") - private let summary = NSTextField(wrappingLabelWithString: "") - private var candidates: [SidebarEntry] = [] - - private var words = Words(gerund: "", past: "", infinitive: "") - private var queue = DispatchQueue.global() - private var operation: (SidebarEntry) -> String? = { _ in nil } - private var onSucceeded: (SidebarEntry) -> Void = { _ in } - private var onFinished: () -> Void = {} - - static func present(on parent: NSWindow, title: String, intro: String, confirm: String, - candidates: [SidebarEntry], defaultChecked: (SidebarEntry) -> Bool, - rowLabel: (SidebarEntry) -> String, words: Words, queue: DispatchQueue, - operation: @escaping (SidebarEntry) -> String?, - onSucceeded: @escaping (SidebarEntry) -> Void, onFinished: @escaping () -> Void) { - guard current == nil, !candidates.isEmpty else { return } - let sheet = BatchOperationSheet() - sheet.words = words - sheet.queue = queue - sheet.operation = operation - sheet.onSucceeded = onSucceeded - sheet.onFinished = onFinished - sheet.build(title: title, intro: intro, confirm: confirm, candidates: candidates, - defaultChecked: defaultChecked, rowLabel: rowLabel) - current = sheet - guard let window = sheet.window else { return } - parent.beginSheet(window) { _ in current = nil } - } - - private init() { - let window = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 520, height: 440), - styleMask: [.titled, .docModalWindow], backing: .buffered, defer: true) - super.init(window: window) - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("not used") - } - - private func build(title: String, intro: String, confirm: String, candidates: [SidebarEntry], - defaultChecked: (SidebarEntry) -> Bool, rowLabel: (SidebarEntry) -> String) { - guard let window else { return } - self.candidates = candidates - window.title = title - let heading = NSTextField(labelWithString: title) - heading.font = .systemFont(ofSize: 15, weight: .semibold) - let introLabel = NSTextField(wrappingLabelWithString: intro) - introLabel.textColor = .secondaryLabelColor - - var byFolder: [String: [SidebarEntry]] = [:] - for entry in candidates { - let key = entry.abbreviatedPath.isEmpty ? entry.sessionName : entry.abbreviatedPath - byFolder[key, default: []].append(entry) - } - groups = byFolder.keys.sorted { $0.localizedCaseInsensitiveCompare($1) == .orderedAscending }.map { key in - (key, (byFolder[key] ?? []).sorted { $0.displayName.localizedCaseInsensitiveCompare($1.displayName) == .orderedAscending }) - } - - let rows = NSStackView() - rows.orientation = .vertical - rows.alignment = .leading - rows.spacing = 5 - rows.edgeInsets = NSEdgeInsets(top: 8, left: 10, bottom: 8, right: 10) - for (index, group) in groups.enumerated() { - let header = NSButton(checkboxWithTitle: "\(group.title) (\(group.members.count))", target: self, - action: #selector(headerToggled(_:))) - header.font = .systemFont(ofSize: NSFont.systemFontSize, weight: .semibold) - header.allowsMixedState = true - header.tag = index - headerBoxes.append(header) - if index > 0 { rows.setCustomSpacing(10, after: rows.arrangedSubviews.last ?? header) } - rows.addArrangedSubview(header) - for entry in group.members { - let box = NSButton(checkboxWithTitle: "\(entry.displayName) — \(rowLabel(entry))", target: self, - action: #selector(boxToggled(_:))) - box.image = nil - box.state = defaultChecked(entry) ? .on : .off - boxes[ObjectIdentifier(entry)] = box - let indent = NSStackView(views: [NSView(), harnessIcon(entry), box]) - indent.spacing = 4 - indent.arrangedSubviews[0].widthAnchor.constraint(equalToConstant: 14).isActive = true - rows.addArrangedSubview(indent) - } - } - let document = FlippedView() - rows.translatesAutoresizingMaskIntoConstraints = false - document.addSubview(rows) - document.translatesAutoresizingMaskIntoConstraints = false - NSLayoutConstraint.activate([ - rows.leadingAnchor.constraint(equalTo: document.leadingAnchor), - rows.trailingAnchor.constraint(equalTo: document.trailingAnchor), - rows.topAnchor.constraint(equalTo: document.topAnchor), - rows.bottomAnchor.constraint(equalTo: document.bottomAnchor), - ]) - checklist.documentView = document - checklist.hasVerticalScroller = true - checklist.borderType = .bezelBorder - checklist.translatesAutoresizingMaskIntoConstraints = false - document.widthAnchor.constraint(equalTo: checklist.contentView.widthAnchor).isActive = true - let listHeight = min(300, max(120, rows.fittingSize.height + 8)) - checklist.heightAnchor.constraint(equalToConstant: listHeight).isActive = true - - selectAll.target = self - selectAll.action = #selector(selectAllToggled(_:)) - - progress.style = .bar - progress.isIndeterminate = false - progress.isHidden = true - progressLabel.isHidden = true - summary.isHidden = true - summary.isSelectable = true - - cancelButton.title = "Cancel" - cancelButton.bezelStyle = .push - cancelButton.keyEquivalent = "\u{1b}" - cancelButton.target = self - cancelButton.action = #selector(cancel(_:)) - confirmButton.title = confirm - confirmButton.bezelStyle = .push - confirmButton.target = self - confirmButton.action = #selector(run(_:)) - doneButton.title = "Done" - doneButton.bezelStyle = .push - doneButton.keyEquivalent = "\r" - doneButton.target = self - doneButton.action = #selector(cancel(_:)) - doneButton.isHidden = true - let buttons = NSStackView(views: [NSView(), cancelButton, confirmButton, doneButton]) - buttons.spacing = 10 - - let stack = NSStackView(views: [heading, introLabel, selectAll, checklist, progressLabel, progress, summary, buttons]) - stack.orientation = .vertical - stack.alignment = .leading - stack.spacing = 10 - stack.edgeInsets = NSEdgeInsets(top: 20, left: 20, bottom: 20, right: 20) - stack.translatesAutoresizingMaskIntoConstraints = false - let content = NSView() - content.addSubview(stack) - NSLayoutConstraint.activate([ - stack.leadingAnchor.constraint(equalTo: content.leadingAnchor), - stack.trailingAnchor.constraint(equalTo: content.trailingAnchor), - stack.topAnchor.constraint(equalTo: content.topAnchor), - stack.bottomAnchor.constraint(equalTo: content.bottomAnchor), - content.widthAnchor.constraint(equalToConstant: 520), - ]) - for view in [introLabel, checklist, progress, summary, buttons] { - view.widthAnchor.constraint(equalTo: stack.widthAnchor, constant: -40).isActive = true - } - window.contentView = content - window.setContentSize(content.fittingSize) - refreshTriState() - } - - private func harnessIcon(_ entry: SidebarEntry) -> NSView { - let view = NSImageView(image: HarnessIcons.image(entry.harnessType, size: 13)) - view.contentTintColor = .secondaryLabelColor - return view - } - - private var selected: [SidebarEntry] { - groups.flatMap(\.members).filter { boxes[ObjectIdentifier($0)]?.state == .on } - } - - private func refreshTriState() { - for (index, group) in groups.enumerated() where index < headerBoxes.count { - let on = group.members.filter { boxes[ObjectIdentifier($0)]?.state == .on }.count - headerBoxes[index].state = on == 0 ? .off : (on == group.members.count ? .on : .mixed) - } - let total = boxes.count - let on = boxes.values.filter { $0.state == .on }.count - selectAll.state = on == total && total > 0 ? .on : .off - confirmButton.isEnabled = on > 0 - confirmButton.keyEquivalent = on > 0 ? "\r" : "" - } - - @objc private func boxToggled(_ sender: NSButton) { - refreshTriState() - } - - @objc private func headerToggled(_ sender: NSButton) { - guard sender.tag >= 0, sender.tag < groups.count else { return } - // a mixed header click selects the whole folder - let state: NSControl.StateValue = sender.state == .off ? .off : .on - sender.state = state - for entry in groups[sender.tag].members { - boxes[ObjectIdentifier(entry)]?.state = state - } - refreshTriState() - } - - @objc private func selectAllToggled(_ sender: NSButton) { - for box in boxes.values { - box.state = sender.state - } - refreshTriState() - } - - @objc private func cancel(_ sender: Any?) { - guard let window else { return } - window.sheetParent?.endSheet(window) - } - - @objc private func run(_ sender: Any?) { - let chosen = selected - guard !chosen.isEmpty else { return } - confirmButton.isHidden = true - cancelButton.isEnabled = false - selectAll.isEnabled = false - checklist.isHidden = true - progress.isHidden = false - progressLabel.isHidden = false - progress.maxValue = Double(chosen.count) - progress.doubleValue = 0 - progressLabel.stringValue = "\(words.gerund) \(chosen.count) session\(chosen.count == 1 ? "" : "s")…" - let operation = self.operation - let words = self.words - queue.async { [weak self] in - var succeeded = 0 - var failed: [String] = [] - for (index, entry) in chosen.enumerated() { - DispatchQueue.main.async { - self?.progressLabel.stringValue = "\(words.gerund) '\(entry.sessionName)'… (\(index + 1) of \(chosen.count))" - } - let failure = operation(entry) - DispatchQueue.main.async { - if let failure { - failed.append(failure) - } else { - succeeded += 1 - self?.onSucceeded(entry) - } - self?.progress.doubleValue = Double(index + 1) - } - } - DispatchQueue.main.async { - guard let self else { return } - var text = "\(words.past) \(succeeded) of \(chosen.count) session\(chosen.count == 1 ? "" : "s")." - if !failed.isEmpty { - text += "\n\nCould not \(words.infinitive) \(failed.count):\n" + failed.map { "• " + $0 }.joined(separator: "\n") - } - self.summary.stringValue = text - self.summary.isHidden = false - self.progressLabel.stringValue = "Done." - self.cancelButton.isHidden = true - self.doneButton.isHidden = false - self.window.map { $0.setContentSize($0.contentView?.fittingSize ?? $0.frame.size) } - self.onFinished() - } - } - } -} diff --git a/swift/Sources/MicrohmApp/Dialogs/NewSessionSheet.swift b/swift/Sources/MicrohmApp/Dialogs/NewSessionSheet.swift deleted file mode 100644 index f5e9d65..0000000 --- a/swift/Sources/MicrohmApp/Dialogs/NewSessionSheet.swift +++ /dev/null @@ -1,276 +0,0 @@ -import AppKit -import MicrohmCore - -/// The New Session sheet (Java's `OpenSessionDialog`, plus the phone page's optional -/// name and first message): folder (with Choose…), harness, name, first message, and a -/// resume id under Advanced. -final class NewSessionSheet: NSWindowController, NSWindowDelegate { - - struct Result { - let projectPath: URL - let harness: HarnessType - let displayName: String? - let firstMessage: String? - let resumeId: String? - } - - private static var current: NewSessionSheet? - - private let pathField = NSTextField() - private let harnessPopup = NSPopUpButton() - private let nameField = NSTextField() - private let messageView = NSTextView() - private let resumeField = NSTextField() - private let shellLabel = NSTextField(labelWithString: "") - private let errorLabel = NSTextField(labelWithString: "") - private var completion: ((Result?) -> Void)? - - static func present(on parent: NSWindow, prefillPath: String?, prefillHarness: HarnessType?, - shellDescription: String, completion: @escaping (Result?) -> Void) { - guard current == nil else { return } - let sheet = NewSessionSheet(prefillPath: prefillPath, prefillHarness: prefillHarness, shell: shellDescription) - sheet.completion = completion - current = sheet - guard let window = sheet.window else { return } - parent.beginSheet(window) { _ in - current = nil - } - window.makeFirstResponder(sheet.pathField) - } - - private init(prefillPath: String?, prefillHarness: HarnessType?, shell: String) { - let window = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 540, height: 400), - styleMask: [.titled, .docModalWindow], backing: .buffered, defer: true) - window.title = "New Session" - super.init(window: window) - build(prefillPath: prefillPath, prefillHarness: prefillHarness, shell: shell) - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("not used") - } - - private func build(prefillPath: String?, prefillHarness: HarnessType?, shell: String) { - guard let window else { return } - let title = NSTextField(labelWithString: "New Session") - title.font = .systemFont(ofSize: 15, weight: .semibold) - let subtitle = NSTextField(wrappingLabelWithString: "Start an agent or a shell in a folder. Sessions keep running in the background daemon.") - subtitle.textColor = .secondaryLabelColor - subtitle.font = .systemFont(ofSize: NSFont.smallSystemFontSize) - - pathField.stringValue = SidebarEntry.abbreviate(prefillPath ?? NSHomeDirectory()) - pathField.placeholderString = "~/Projects/my-app" - pathField.lineBreakMode = .byTruncatingHead - pathField.setAccessibilityLabel("Folder") - let choose = NSButton(title: "Choose…", target: self, action: #selector(chooseFolder(_:))) - let pathRow = NSStackView(views: [pathField, choose]) - pathRow.spacing = 8 - pathRow.distribution = .fill - // the field takes the row's width; the button keeps its own - pathField.translatesAutoresizingMaskIntoConstraints = false - pathField.setContentHuggingPriority(.defaultLow, for: .horizontal) - pathField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) - choose.setContentHuggingPriority(.required, for: .horizontal) - pathRow.translatesAutoresizingMaskIntoConstraints = false - pathRow.widthAnchor.constraint(equalToConstant: 380).isActive = true - - for type in HarnessType.allCases { - harnessPopup.addItem(withTitle: type == .shell ? "Shell" : "\(SidebarView.label(type)) · \(type.id)") - harnessPopup.lastItem?.image = HarnessIcons.image(type, size: 16) - harnessPopup.lastItem?.representedObject = type.id - } - if let prefillHarness, let index = HarnessType.allCases.firstIndex(of: prefillHarness) { - harnessPopup.selectItem(at: index) - } - harnessPopup.target = self - harnessPopup.action = #selector(harnessChanged(_:)) - - nameField.placeholderString = "Optional — shown in the sidebar" - nameField.setAccessibilityLabel("Name") - - messageView.isRichText = false - messageView.font = .systemFont(ofSize: NSFont.systemFontSize) - messageView.isAutomaticQuoteSubstitutionEnabled = false - messageView.isAutomaticDashSubstitutionEnabled = false - messageView.textContainerInset = NSSize(width: 4, height: 5) - messageView.setAccessibilityLabel("First message") - let messageScroll = NSScrollView() - messageScroll.documentView = messageView - messageScroll.hasVerticalScroller = true - messageScroll.borderType = .bezelBorder - messageScroll.drawsBackground = true - messageView.drawsBackground = true - messageView.backgroundColor = .textBackgroundColor - messageView.textColor = .labelColor - messageView.insertionPointColor = .labelColor - // a text view in a scroll view needs a real frame and a tracking container, or it - // lays out at zero width and nothing (not even its background) is drawn - messageView.frame = NSRect(x: 0, y: 0, width: 380, height: 72) - messageView.minSize = NSSize(width: 0, height: 72) - messageView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) - messageView.isVerticallyResizable = true - messageView.isHorizontallyResizable = false - messageView.textContainer?.widthTracksTextView = true - messageView.autoresizingMask = [.width] - messageScroll.translatesAutoresizingMaskIntoConstraints = false - messageScroll.heightAnchor.constraint(equalToConstant: 72).isActive = true - messageScroll.widthAnchor.constraint(equalToConstant: 380).isActive = true - let messageHint = hint("Optional. Typed into the agent once it is ready at its prompt.") - - resumeField.placeholderString = "Blank starts a fresh conversation" - resumeField.setAccessibilityLabel("Resume session id") - - shellLabel.stringValue = shell - shellLabel.textColor = .secondaryLabelColor - let shellHint = hint("Change it in Settings → Sessions → Shell.") - - let grid = NSGridView(views: [ - [label("Folder:"), pathRow], - [label("Harness:"), harnessPopup], - [label("Name:"), nameField], - [label("First message:"), messageScroll], - [NSGridCell.emptyContentView, messageHint], - [label("Resume id:"), resumeField], - [label("Shell:"), shellLabel], - [NSGridCell.emptyContentView, shellHint], - ]) - grid.rowSpacing = 8 - grid.columnSpacing = 10 - grid.column(at: 0).xPlacement = .trailing - grid.rowAlignment = .firstBaseline - grid.row(at: 3).yPlacement = .top - grid.row(at: 4).topPadding = -4 - grid.row(at: 7).topPadding = -4 - for row in [3] { - grid.cell(atColumnIndex: 0, rowIndex: row).yPlacement = .top - } - grid.column(at: 1).width = 380 - - errorLabel.textColor = .systemRed - errorLabel.font = .systemFont(ofSize: NSFont.smallSystemFontSize) - errorLabel.isHidden = true - - let cancel = NSButton(title: "Cancel", target: self, action: #selector(cancel(_:))) - cancel.keyEquivalent = "\u{1b}" - let create = NSButton(title: "Start Session", target: self, action: #selector(create(_:))) - create.keyEquivalent = "\r" - create.bezelColor = .controlAccentColor - let buttons = NSStackView(views: [errorLabel, NSView(), cancel, create]) - buttons.spacing = 10 - - let stack = NSStackView(views: [title, subtitle, grid, buttons]) - stack.orientation = .vertical - stack.alignment = .leading - stack.spacing = 10 - stack.setCustomSpacing(4, after: title) - stack.setCustomSpacing(16, after: subtitle) - stack.setCustomSpacing(18, after: grid) - stack.edgeInsets = NSEdgeInsets(top: 20, left: 20, bottom: 20, right: 20) - stack.translatesAutoresizingMaskIntoConstraints = false - let content = NSView() - content.addSubview(stack) - NSLayoutConstraint.activate([ - stack.leadingAnchor.constraint(equalTo: content.leadingAnchor), - stack.trailingAnchor.constraint(equalTo: content.trailingAnchor), - stack.topAnchor.constraint(equalTo: content.topAnchor), - stack.bottomAnchor.constraint(equalTo: content.bottomAnchor), - buttons.widthAnchor.constraint(equalTo: stack.widthAnchor, constant: -40), - subtitle.widthAnchor.constraint(equalTo: stack.widthAnchor, constant: -40), - ]) - window.contentView = content - harnessChanged(nil) - } - - private func label(_ text: String) -> NSTextField { - let field = NSTextField(labelWithString: text) - field.alignment = .right - return field - } - - private func hint(_ text: String) -> NSTextField { - let field = NSTextField(labelWithString: text) - field.font = .systemFont(ofSize: NSFont.smallSystemFontSize) - field.textColor = .tertiaryLabelColor - return field - } - - private var selectedHarness: HarnessType { - let index = harnessPopup.indexOfSelectedItem - let all = HarnessType.allCases - return index >= 0 && index < all.count ? all[index] : .claudeCode - } - - @objc private func harnessChanged(_ sender: Any?) { - // a first message and a resume id mean nothing to a plain shell - let shell = selectedHarness == .shell - messageView.isEditable = !shell - messageView.textColor = shell ? .tertiaryLabelColor : .labelColor - resumeField.isEnabled = !shell - } - - @objc private func chooseFolder(_ sender: Any?) { - guard let window else { return } - let panel = NSOpenPanel() - panel.canChooseDirectories = true - panel.canChooseFiles = false - panel.allowsMultipleSelection = false - panel.canCreateDirectories = true - panel.prompt = "Choose" - panel.message = "Choose the folder the session starts in." - let current = expanded(pathField.stringValue) - panel.directoryURL = URL(fileURLWithPath: current.isEmpty ? NSHomeDirectory() : current) - panel.beginSheetModal(for: window) { [weak self] response in - if response == .OK, let url = panel.url { - self?.pathField.stringValue = SidebarEntry.abbreviate(url.path) - } - } - } - - private func expanded(_ text: String) -> String { - (text.trimmingCharacters(in: .whitespacesAndNewlines) as NSString).expandingTildeInPath - } - - private func showError(_ text: String) { - errorLabel.stringValue = text - errorLabel.isHidden = false - NSSound.beep() - } - - @objc private func create(_ sender: Any?) { - let path = expanded(pathField.stringValue) - guard !path.isEmpty else { - showError("A folder is required.") - return - } - var isDirectory: ObjCBool = false - guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory), isDirectory.boolValue else { - showError("'\(SidebarEntry.abbreviate(path))' is not a folder.") - return - } - let name = nameField.stringValue.trimmingCharacters(in: .whitespacesAndNewlines) - if name.count > 64 || name.contains("·") || name.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) }) { - showError("A name is at most 64 characters, on one line, without “·”.") - return - } - let harness = selectedHarness - let message = messageView.string.trimmingCharacters(in: .whitespacesAndNewlines) - let resume = resumeField.stringValue.trimmingCharacters(in: .whitespacesAndNewlines) - finish(Result(projectPath: URL(fileURLWithPath: path), harness: harness, - displayName: name.isEmpty ? nil : name, - firstMessage: harness == .shell || message.isEmpty ? nil : message, - resumeId: harness == .shell || resume.isEmpty ? nil : resume)) - } - - @objc private func cancel(_ sender: Any?) { - finish(nil) - } - - private func finish(_ result: Result?) { - guard let window else { return } - let completion = self.completion - self.completion = nil - window.sheetParent?.endSheet(window) - completion?(result) - } -} diff --git a/swift/Sources/MicrohmApp/Dialogs/PreflightDialog.swift b/swift/Sources/MicrohmApp/Dialogs/PreflightDialog.swift deleted file mode 100644 index 4b0afca..0000000 --- a/swift/Sources/MicrohmApp/Dialogs/PreflightDialog.swift +++ /dev/null @@ -1,173 +0,0 @@ -import AppKit -import MicrohmCore - -/// The shared confirmation for actions that end a session (Java's `PreflightDialog`): one -/// copy and layout for every entry point, so the toolbar, the menus and the keyboard never -/// drift into different confirmations. Cancel is the default button — Return never ends a -/// session by accident. -enum PreflightDialog { - - /// One affected session as the review list shows it. - struct Session { - let displayName: String - let sessionName: String - let status: String - - init(_ entry: SidebarEntry) { - displayName = entry.displayName - sessionName = entry.sessionName - status = entry.statusPhrase - } - - var label: String { - let name = displayName == sessionName ? displayName : "\(displayName) (\(sessionName))" - return "\(name) — \(status)" - } - } - - struct Request { - let title: String - let prompt: String - let sessions: [Session] - let consequence: String - let confirmLabel: String - let destructive: Bool - - static func kill(_ session: Session) -> Request { - Request(title: "Kill session", prompt: "Kill “\(session.displayName)”?", sessions: [session], - consequence: "This kills the session and ends the harness process inside it. " - + "Any unsaved terminal work is lost, and this cannot be undone.", - confirmLabel: "Kill Session", destructive: true) - } - - static func close(_ session: Session) -> Request { - Request(title: "Close session", prompt: "Close “\(session.displayName)” gracefully?", sessions: [session], - consequence: "\(AppModel.appName) will ask the harness and its shell to exit. If the session " - + "closes, its terminal and scrollback cannot be restored, but its saved entry remains " - + "available to Resume. If it is busy or does not exit in time, it is left running.", - confirmLabel: "Close Session", destructive: false) - } - - static func reload(_ session: Session) -> Request { - Request(title: "Reload session", prompt: "Reload “\(session.displayName)”?", sessions: [session], - consequence: "\(AppModel.appName) will ask the harness and its shell to exit, then immediately " - + "relaunch the harness in a fresh session, resuming its conversation where it left off. " - + "Useful after the harness auto-updates and needs a restart to pick up the new version. " - + "If it is busy or does not exit in time, it is left running.", - confirmLabel: "Reload Session", destructive: false) - } - - static func closeAll(_ sessions: [Session]) -> Request { - Request(title: "Close all sessions", - prompt: "Close \(sessions.count == 1 ? "the live session" : "all \(sessions.count) live sessions")?", - sessions: sessions, - consequence: "Each harness is asked to exit gracefully. A closed terminal and its scrollback " - + "cannot be restored, but every saved entry remains available to Resume. Busy sessions " - + "and sessions that do not exit in time are left running and reported afterward.", - confirmLabel: "Close All", destructive: false) - } - } - - /// Shows `request` as a sheet on `window` (app-modal without one) and reports the answer. - static func present(_ request: Request, on window: NSWindow?, completion: @escaping (Bool) -> Void) { - guard !request.sessions.isEmpty else { - completion(false) - return - } - let alert = NSAlert() - alert.alertStyle = request.destructive ? .critical : .warning - alert.messageText = request.prompt - alert.informativeText = request.consequence - let confirm = alert.addButton(withTitle: request.confirmLabel) - let cancel = alert.addButton(withTitle: "Cancel") - confirm.hasDestructiveAction = request.destructive - // Cancel stays the default: Return must never end a session by accident - confirm.keyEquivalent = "" - cancel.keyEquivalent = "\r" - alert.accessoryView = review(request.sessions) - if let window, window.attachedSheet == nil, window.isVisible { - alert.beginSheetModal(for: window) { response in - completion(response == .alertFirstButtonReturn) - } - } else { - completion(alert.runModal() == .alertFirstButtonReturn) - } - } - - /// The affected sessions: a plain list for a few, a scrolling one for many. - private static func review(_ sessions: [Session]) -> NSView { - let rows = NSStackView() - rows.orientation = .vertical - rows.alignment = .leading - rows.spacing = 4 - rows.edgeInsets = NSEdgeInsets(top: 8, left: 10, bottom: 8, right: 10) - for session in sessions { - let label = NSTextField(wrappingLabelWithString: "• " + session.label) - label.font = .systemFont(ofSize: NSFont.smallSystemFontSize) - label.preferredMaxLayoutWidth = 280 - rows.addArrangedSubview(label) - } - let box = NSBox() - box.boxType = .custom - box.cornerRadius = 6 - box.borderColor = .separatorColor - box.fillColor = NSColor.labelColor.withAlphaComponent(0.04) - box.contentViewMargins = .zero - let height = min(170, rows.fittingSize.height) - if sessions.count <= 6 { - box.contentView = rows - box.frame = NSRect(x: 0, y: 0, width: 300, height: rows.fittingSize.height) - return box - } - let scroll = NSScrollView(frame: NSRect(x: 0, y: 0, width: 300, height: height)) - scroll.hasVerticalScroller = true - scroll.drawsBackground = false - let document = FlippedView(frame: NSRect(x: 0, y: 0, width: 284, height: rows.fittingSize.height)) - rows.frame = document.bounds - rows.autoresizingMask = [.width] - document.addSubview(rows) - scroll.documentView = document - box.contentView = scroll - box.frame = NSRect(x: 0, y: 0, width: 300, height: height) - return box - } -} - -final class FlippedView: NSView { - override var isFlipped: Bool { true } -} - -/// Rename: a custom sidebar name, or Clear to go back to the harness's own. -enum RenameSheet { - enum Choice { - case rename(String) - case clear - case cancel - } - - static func present(on window: NSWindow, current: String, inherited: String, - completion: @escaping (Choice) -> Void) { - let alert = NSAlert() - alert.messageText = "Rename Session" - alert.informativeText = "Inherited from the harness: \(inherited)" - let field = NSTextField(frame: NSRect(x: 0, y: 0, width: 300, height: 24)) - field.stringValue = current - field.placeholderString = inherited - alert.accessoryView = field - alert.addButton(withTitle: "Rename") - alert.addButton(withTitle: "Cancel") - alert.addButton(withTitle: "Clear") - alert.window.initialFirstResponder = field - alert.beginSheetModal(for: window) { response in - switch response { - case .alertFirstButtonReturn: completion(.rename(field.stringValue)) - case .alertThirdButtonReturn: completion(.clear) - default: completion(.cancel) - } - } - DispatchQueue.main.async { - alert.window.makeFirstResponder(field) - field.selectText(nil) - } - } -} diff --git a/swift/Sources/MicrohmApp/Dialogs/UsageWindowController.swift b/swift/Sources/MicrohmApp/Dialogs/UsageWindowController.swift deleted file mode 100644 index 6500398..0000000 --- a/swift/Sources/MicrohmApp/Dialogs/UsageWindowController.swift +++ /dev/null @@ -1,295 +0,0 @@ -import AppKit -import MicrohmCore - -/// Usage & Limits (Java's `UsageLimitsDialog`): pick a harness, see its provider account's -/// limit windows, how much of each is used and when it resets, plus usage statistics. -/// Loading runs in the background; a newer request supersedes an older one. -final class UsageWindowController: NSWindowController, NSWindowDelegate { - - private static var shared: UsageWindowController? - - private let usage: HarnessUsageService - private let harnessPopup = NSPopUpButton() - private let refreshButton = NSButton() - private let content = NSStackView() - private let scroll = NSScrollView() - private var requestSequence = 0 - private static let resetFormat: DateFormatter = { - let f = DateFormatter() - f.dateStyle = .medium - f.timeStyle = .short - return f - }() - - static func show(initial: HarnessType, usage: HarnessUsageService) { - let controller = shared ?? UsageWindowController(usage: usage) - shared = controller - controller.select(initial == .shell ? .claudeCode : initial) - controller.showWindow(nil) - controller.window?.makeKeyAndOrderFront(nil) - controller.load() - } - - private init(usage: HarnessUsageService) { - self.usage = usage - let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 560, height: 520), - styleMask: [.titled, .closable, .resizable, .miniaturizable, .fullSizeContentView], - backing: .buffered, defer: true) - window.title = "Usage & Limits" - window.minSize = NSSize(width: 460, height: 360) - window.toolbarStyle = .unifiedCompact - window.setFrameAutosaveName("MicrohmUsageWindow") - super.init(window: window) - window.delegate = self - build() - window.center() - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("not used") - } - - private func build() { - guard let window else { return } - for type in HarnessType.allCases where type != .shell { - harnessPopup.addItem(withTitle: SidebarView.label(type)) - harnessPopup.lastItem?.image = HarnessIcons.image(type, size: 16) - } - harnessPopup.target = self - harnessPopup.action = #selector(harnessChanged(_:)) - refreshButton.bezelStyle = .push - refreshButton.image = HarnessIcons.symbol("arrow.clockwise", "Refresh") - refreshButton.imagePosition = .imageLeading - refreshButton.title = "Refresh" - refreshButton.keyEquivalent = "r" - refreshButton.keyEquivalentModifierMask = .command - refreshButton.target = self - refreshButton.action = #selector(refresh(_:)) - let harnessLabel = NSTextField(labelWithString: "Harness:") - let selector = NSStackView(views: [harnessLabel, harnessPopup, NSView(), refreshButton]) - selector.spacing = 8 - selector.translatesAutoresizingMaskIntoConstraints = false - - content.orientation = .vertical - content.alignment = .leading - content.spacing = 12 - content.edgeInsets = NSEdgeInsets(top: 4, left: 20, bottom: 20, right: 20) - content.translatesAutoresizingMaskIntoConstraints = false - let document = FlippedView() - document.translatesAutoresizingMaskIntoConstraints = false - document.addSubview(content) - scroll.documentView = document - scroll.hasVerticalScroller = true - scroll.drawsBackground = false - scroll.translatesAutoresizingMaskIntoConstraints = false - - let root = NSView() - root.addSubview(selector) - root.addSubview(scroll) - NSLayoutConstraint.activate([ - selector.topAnchor.constraint(equalTo: root.safeAreaLayoutGuide.topAnchor, constant: 14), - selector.leadingAnchor.constraint(equalTo: root.leadingAnchor, constant: 20), - selector.trailingAnchor.constraint(equalTo: root.trailingAnchor, constant: -20), - scroll.topAnchor.constraint(equalTo: selector.bottomAnchor, constant: 12), - scroll.leadingAnchor.constraint(equalTo: root.leadingAnchor), - scroll.trailingAnchor.constraint(equalTo: root.trailingAnchor), - scroll.bottomAnchor.constraint(equalTo: root.bottomAnchor), - document.leadingAnchor.constraint(equalTo: scroll.contentView.leadingAnchor), - document.trailingAnchor.constraint(equalTo: scroll.contentView.trailingAnchor), - document.topAnchor.constraint(equalTo: scroll.contentView.topAnchor), - content.leadingAnchor.constraint(equalTo: document.leadingAnchor), - content.trailingAnchor.constraint(equalTo: document.trailingAnchor), - content.topAnchor.constraint(equalTo: document.topAnchor), - content.bottomAnchor.constraint(equalTo: document.bottomAnchor), - ]) - window.contentView = root - } - - private var budgeted: [HarnessType] { HarnessType.allCases.filter { $0 != .shell } } - - private func select(_ harness: HarnessType) { - if let index = budgeted.firstIndex(of: harness) { - harnessPopup.selectItem(at: index) - } - } - - private var selectedHarness: HarnessType { - let index = harnessPopup.indexOfSelectedItem - return index >= 0 && index < budgeted.count ? budgeted[index] : .claudeCode - } - - /// ⌘W closes this window (in the main window it closes the selected session). - @objc func closeSession(_ sender: Any?) { - window?.performClose(sender) - } - - @objc private func harnessChanged(_ sender: Any?) { load() } - @objc private func refresh(_ sender: Any?) { load() } - - private func load() { - let harness = selectedHarness - requestSequence += 1 - let request = requestSequence - harnessPopup.isEnabled = false - refreshButton.isEnabled = false - replace([loadingView(harness)]) - let usage = self.usage - DispatchQueue.global(qos: .userInitiated).async { [weak self] in - let result = Result { try usage.load(harness) } - DispatchQueue.main.async { - guard let self, request == self.requestSequence else { return } - self.harnessPopup.isEnabled = true - self.refreshButton.isEnabled = true - switch result { - case .success(let snapshot): self.replace(self.snapshotViews(snapshot)) - case .failure(let error): self.replace(self.errorViews(harness, error)) - } - } - } - } - - private func replace(_ views: [NSView]) { - content.arrangedSubviews.forEach { $0.removeFromSuperview() } - for view in views { - content.addArrangedSubview(view) - if view is CardView { - view.widthAnchor.constraint(equalTo: content.widthAnchor, constant: -40).isActive = true - } else { - view.widthAnchor.constraint(lessThanOrEqualTo: content.widthAnchor, constant: -40).isActive = true - } - } - } - - private func loadingView(_ harness: HarnessType) -> NSView { - let spinner = NSProgressIndicator() - spinner.style = .spinning - spinner.controlSize = .small - spinner.startAnimation(nil) - let label = NSTextField(labelWithString: "Loading \(SidebarView.label(harness)) usage…") - label.textColor = .secondaryLabelColor - let row = NSStackView(views: [spinner, label]) - row.spacing = 8 - return row - } - - private func snapshotViews(_ snapshot: UsageSnapshot) -> [NSView] { - var views: [NSView] = [] - let heading = NSTextField(labelWithString: snapshot.heading) - heading.font = .systemFont(ofSize: 17, weight: .semibold) - views.append(heading) - views.append(muted("Source: \(snapshot.source)")) - if snapshot.limits.isEmpty { - views.append(NSTextField(labelWithString: "No live limit windows available.")) - } else { - for limit in snapshot.limits { - views.append(limitCard(limit)) - } - } - if !snapshot.statistics.isEmpty { - let title = NSTextField(labelWithString: "Usage details") - title.font = .systemFont(ofSize: NSFont.systemFontSize, weight: .semibold) - views.append(title) - let grid = NSGridView(views: snapshot.statistics.map { stat -> [NSView] in - let value = NSTextField(labelWithString: stat.value) - value.font = .monospacedDigitSystemFont(ofSize: NSFont.smallSystemFontSize, weight: .medium) - value.isSelectable = true - let label = muted("\(stat.label):") - label.setContentHuggingPriority(.required, for: .horizontal) - value.setContentHuggingPriority(.required, for: .horizontal) - // an empty third column takes the slack, so values sit beside their labels - let slack = NSView() - slack.setContentHuggingPriority(.defaultLow - 1, for: .horizontal) - return [label, value, slack] - }) - grid.rowSpacing = 4 - grid.columnSpacing = 14 - grid.xPlacement = .leading - grid.rowAlignment = .firstBaseline - views.append(grid) - } - if let note = snapshot.note { - let label = NSTextField(wrappingLabelWithString: note) - label.textColor = .secondaryLabelColor - label.font = .systemFont(ofSize: NSFont.smallSystemFontSize) - views.append(label) - } - return views - } - - private func limitCard(_ limit: UsageSnapshot.Limit) -> NSView { - let title = NSTextField(labelWithString: limit.label) - title.font = .systemFont(ofSize: NSFont.systemFontSize, weight: .semibold) - let used = NSTextField(labelWithString: "\(limit.usedPercent)% used") - used.font = .monospacedDigitSystemFont(ofSize: NSFont.smallSystemFontSize, weight: .medium) - used.textColor = limit.usedPercent >= 90 ? .systemRed : (limit.usedPercent >= 70 ? .systemOrange : .secondaryLabelColor) - let top = NSStackView(views: [title, NSView(), used]) - let bar = NSProgressIndicator() - bar.style = .bar - bar.isIndeterminate = false - bar.minValue = 0 - bar.maxValue = 100 - bar.doubleValue = Double(max(0, min(100, limit.usedPercent))) - var detail: [String] = [] - if let text = limit.detail { detail.append(text) } - if let reset = limit.resetsAt { detail.append("Resets \(UsageWindowController.resetFormat.string(from: reset))") } - let stack = NSStackView(views: [top, bar]) - stack.orientation = .vertical - stack.alignment = .leading - stack.spacing = 6 - if !detail.isEmpty { - stack.addArrangedSubview(muted(detail.joined(separator: " · "))) - } - stack.edgeInsets = NSEdgeInsets(top: 10, left: 12, bottom: 10, right: 12) - for view in [top, bar] { - view.widthAnchor.constraint(equalTo: stack.widthAnchor, constant: -24).isActive = true - } - return CardView(stack) - } - - private func errorViews(_ harness: HarnessType, _ error: Error) -> [NSView] { - let heading = NSTextField(labelWithString: "Couldn’t load \(SidebarView.label(harness)) usage") - heading.font = .systemFont(ofSize: NSFont.systemFontSize, weight: .semibold) - let detail = NSTextField(wrappingLabelWithString: error.localizedDescription) - detail.textColor = .secondaryLabelColor - return [heading, detail] - } - - private func muted(_ text: String) -> NSTextField { - let label = NSTextField(labelWithString: text) - label.textColor = .secondaryLabelColor - label.font = .systemFont(ofSize: NSFont.smallSystemFontSize) - return label - } -} - -/// A rounded, softly filled card around one view. -final class CardView: NSView { - init(_ content: NSView) { - super.init(frame: .zero) - wantsLayer = true - layer?.cornerRadius = 8 - layer?.borderWidth = 1 - translatesAutoresizingMaskIntoConstraints = false - content.translatesAutoresizingMaskIntoConstraints = false - addSubview(content) - NSLayoutConstraint.activate([ - content.leadingAnchor.constraint(equalTo: leadingAnchor), - content.trailingAnchor.constraint(equalTo: trailingAnchor), - content.topAnchor.constraint(equalTo: topAnchor), - content.bottomAnchor.constraint(equalTo: bottomAnchor), - ]) - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("not used") - } - - override func updateLayer() { - layer?.backgroundColor = NSColor.labelColor.withAlphaComponent(0.035).cgColor - layer?.borderColor = NSColor.separatorColor.cgColor - } - - override var wantsUpdateLayer: Bool { true } -} diff --git a/swift/Sources/MicrohmApp/Main/MainMenu.swift b/swift/Sources/MicrohmApp/Main/MainMenu.swift deleted file mode 100644 index f79e6d5..0000000 --- a/swift/Sources/MicrohmApp/Main/MainMenu.swift +++ /dev/null @@ -1,271 +0,0 @@ -import AppKit -import MicrohmCore - -/// The menu bar, and the sidebar's sort, filter and context menus. Session items use -/// nil-targeted actions, so they reach the main window controller through the responder -/// chain and validate against its current selection. -enum MainMenu { - - static func build(appDelegate: AppDelegate) -> NSMenu { - let main = NSMenu() - let name = AppModel.appName - - // App - let app = submenu(main, name) - app.addItem(withTitle: "About \(name)", action: #selector(AppDelegate.showAbout(_:)), keyEquivalent: "") - .target = appDelegate - app.addItem(.separator()) - app.addItem(withTitle: "Settings…", action: #selector(AppDelegate.showSettings(_:)), keyEquivalent: ",") - .target = appDelegate - app.addItem(.separator()) - let services = NSMenu(title: "Services") - app.addItem(withTitle: "Services", action: nil, keyEquivalent: "").submenu = services - NSApp.servicesMenu = services - app.addItem(.separator()) - app.addItem(withTitle: "Hide \(name)", action: #selector(NSApplication.hide(_:)), keyEquivalent: "h") - app.addItem(withTitle: "Hide Others", action: #selector(NSApplication.hideOtherApplications(_:)), - keyEquivalent: "h").keyEquivalentModifierMask = [.command, .option] - app.addItem(withTitle: "Show All", action: #selector(NSApplication.unhideAllApplications(_:)), keyEquivalent: "") - app.addItem(.separator()) - app.addItem(withTitle: "Quit \(name)", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q") - - // File - let file = submenu(main, "File") - add(file, "New Session…", #selector(MainWindowController.newSession(_:)), "n") - add(file, "New Session Here…", #selector(MainWindowController.newSessionHere(_:)), "n", [.command, .shift]) - add(file, "New Shell Here", #selector(MainWindowController.newShellHere(_:)), "t") - add(file, "Duplicate Session", #selector(MainWindowController.duplicateSession(_:)), "d") - file.addItem(.separator()) - add(file, "Close Session…", #selector(MainWindowController.closeSession(_:)), "w") - add(file, "Close Window", #selector(NSWindow.performClose(_:)), "w", [.command, .option]) - - // Edit — the terminal answers copy:, paste: and selectAll: itself - let edit = submenu(main, "Edit") - add(edit, "Undo", Selector(("undo:")), "z") - add(edit, "Redo", Selector(("redo:")), "z", [.command, .shift]) - edit.addItem(.separator()) - add(edit, "Cut", #selector(NSText.cut(_:)), "x") - add(edit, "Copy", #selector(NSText.copy(_:)), "c") - add(edit, "Paste", #selector(NSText.paste(_:)), "v") - add(edit, "Select All", #selector(NSText.selectAll(_:)), "a") - - // Session - let session = submenu(main, "Session") - add(session, "Rename…", #selector(MainWindowController.renameSession(_:)), "") - add(session, "Copy Path", #selector(MainWindowController.copySessionPath(_:)), "c", [.command, .option]) - add(session, "Show in Finder", #selector(MainWindowController.revealSessionFolder(_:)), "r", [.command, .shift]) - session.addItem(.separator()) - add(session, "Detach", #selector(MainWindowController.detachSession(_:)), "") - add(session, "Close…", #selector(MainWindowController.closeSession(_:)), "") - add(session, "Reload…", #selector(MainWindowController.reloadSession(_:)), "r", [.command, .option]) - add(session, "Kill…", #selector(MainWindowController.killSession(_:)), "") - session.addItem(.separator()) - add(session, "Resume…", #selector(MainWindowController.resumeSession(_:)), "") - add(session, "Remove from Registry", #selector(MainWindowController.removeFromRegistry(_:)), "\u{8}") - session.addItem(.separator()) - add(session, "Close All Sessions…", #selector(MainWindowController.closeAllSessions(_:)), "") - add(session, "Batch Close…", #selector(MainWindowController.batchCloseSessions(_:)), "") - add(session, "Remove Dead Sessions…", #selector(MainWindowController.removeDeadSessions(_:)), "") - session.addItem(.separator()) - add(session, "Usage & Limits", #selector(MainWindowController.showUsage(_:)), "u", [.command, .shift]) - add(session, "Refresh", #selector(MainWindowController.refreshSessions(_:)), "r") - - // View - let view = submenu(main, "View") - add(view, "Toggle Sidebar", #selector(NSSplitViewController.toggleSidebar(_:)), "s", [.command, .control]) - add(view, "Go to Session List", #selector(MainWindowController.focusSidebar(_:)), "l", [.command, .shift]) - view.addItem(.separator()) - let sort = NSMenuItem(title: "Sort By", action: nil, keyEquivalent: "") - sort.submenu = sortMenu(nil) - view.addItem(sort) - let filter = NSMenuItem(title: "Show Statuses", action: nil, keyEquivalent: "") - filter.submenu = statusFilterMenu(nil) - view.addItem(filter) - let harness = NSMenuItem(title: "Show Harnesses", action: nil, keyEquivalent: "") - harness.submenu = harnessFilterMenu(nil) - view.addItem(harness) - add(view, "Group by Folder", #selector(MainWindowController.toggleFolderGroups(_:)), "") - view.addItem(.separator()) - add(view, "Use Light Appearance", #selector(MainWindowController.toggleAppearance(_:)), "") - view.addItem(.separator()) - add(view, "Bigger", #selector(MainWindowController.terminalZoomIn(_:)), "=") - let plus = add(view, "Bigger", #selector(MainWindowController.terminalZoomIn(_:)), "+") - plus.isAlternate = true - plus.isHidden = true - add(view, "Smaller", #selector(MainWindowController.terminalZoomOut(_:)), "-") - add(view, "Default Size", #selector(MainWindowController.terminalZoomReset(_:)), "0") - view.addItem(.separator()) - add(view, "Scroll Page Up", #selector(MainWindowController.scrollSessionPageUp(_:)), "\u{F72C}", [.command]) - add(view, "Scroll Page Down", #selector(MainWindowController.scrollSessionPageDown(_:)), "\u{F72D}", [.command]) - add(view, "Scroll to Top", #selector(MainWindowController.scrollSessionToTop(_:)), "\u{F729}", [.command]) - add(view, "Scroll to Bottom", #selector(MainWindowController.scrollSessionToBottom(_:)), "\u{F72B}", [.command]) - view.addItem(.separator()) - add(view, "Enter Full Screen", #selector(NSWindow.toggleFullScreen(_:)), "f", [.command, .control]) - - // Window - let window = submenu(main, "Window") - add(window, "Minimize", #selector(NSWindow.performMiniaturize(_:)), "m") - add(window, "Zoom", #selector(NSWindow.performZoom(_:)), "") - window.addItem(.separator()) - add(window, "Show Next Session", #selector(MainWindowController.selectNextSession(_:)), "\t", [.control]) - add(window, "Show Previous Session", #selector(MainWindowController.selectPreviousSession(_:)), "\t", - [.control, .shift]) - for n in 1...9 { - let item = add(window, n == 9 ? "Show Last Session" : "Show Session \(n)", - #selector(MainWindowController.selectSessionNumber(_:)), String(n), [.control]) - item.tag = n - } - window.addItem(.separator()) - add(window, "Main Window", #selector(AppDelegate.showMainWindow(_:)), "0", [.command, .option]).target = appDelegate - add(window, "Bring All to Front", #selector(NSApplication.arrangeInFront(_:)), "") - NSApp.windowsMenu = window - - // Help - let help = submenu(main, "Help") - add(help, "\(name) on GitHub", #selector(AppDelegate.openProjectPage(_:)), "").target = appDelegate - add(help, "Show Log File", #selector(AppDelegate.revealLog(_:)), "").target = appDelegate - NSApp.helpMenu = help - return main - } - - private static func submenu(_ parent: NSMenu, _ title: String) -> NSMenu { - let menu = NSMenu(title: title) - let item = NSMenuItem(title: title, action: nil, keyEquivalent: "") - item.submenu = menu - parent.addItem(item) - return menu - } - - @discardableResult - private static func add(_ menu: NSMenu, _ title: String, _ action: Selector, _ key: String, - _ modifiers: NSEvent.ModifierFlags = [.command]) -> NSMenuItem { - let item = NSMenuItem(title: title, action: action, keyEquivalent: key) - item.keyEquivalentModifierMask = key.isEmpty ? [] : modifiers - menu.addItem(item) - return item - } - - // MARK: - sidebar menus - - static func sortMenu(_ target: AnyObject?) -> NSMenu { - let menu = NSMenu(title: "Sort By") - for mode in SidebarView.SortMode.allCases { - let item = NSMenuItem(title: mode.label, action: #selector(MainWindowController.sortBy(_:)), keyEquivalent: "") - item.representedObject = mode.key - item.target = target - menu.addItem(item) - } - menu.addItem(.separator()) - let descending = NSMenuItem(title: "Descending", action: #selector(MainWindowController.toggleSortDescending(_:)), - keyEquivalent: "") - descending.target = target - menu.addItem(descending) - if target != nil { - menu.addItem(.separator()) - let group = NSMenuItem(title: "Group by Folder", action: #selector(MainWindowController.toggleFolderGroups(_:)), - keyEquivalent: "") - group.target = target - group.toolTip = "Applies while sorting by folder." - menu.addItem(group) - } - return menu - } - - static func statusFilterMenu(_ target: AnyObject?) -> NSMenu { - let menu = NSMenu(title: "Show Statuses") - for status in SidebarView.FilterStatus.allCases { - let item = NSMenuItem(title: status.label, action: #selector(MainWindowController.toggleStatusFilter(_:)), - keyEquivalent: "") - item.tag = status.rawValue - item.target = target - item.image = statusDot(status) - menu.addItem(item) - } - menu.addItem(.separator()) - let showAll = NSMenuItem(title: "Show All Statuses", action: #selector(MainWindowController.showAllStatuses(_:)), - keyEquivalent: "") - showAll.target = target - menu.addItem(showAll) - let hideAll = NSMenuItem(title: "Hide All Statuses", action: #selector(MainWindowController.hideAllStatuses(_:)), - keyEquivalent: "") - hideAll.target = target - menu.addItem(hideAll) - return menu - } - - static func harnessFilterMenu(_ target: AnyObject?) -> NSMenu { - let menu = NSMenu(title: "Show Harnesses") - for (index, family) in SidebarView.HarnessFamily.allCases.enumerated() { - let item = NSMenuItem(title: family.label, action: #selector(MainWindowController.toggleHarnessFilter(_:)), - keyEquivalent: "") - item.tag = index - item.target = target - item.image = HarnessIcons.image(family.harnessType, size: 14) - menu.addItem(item) - } - menu.addItem(.separator()) - let showAll = NSMenuItem(title: "Show All Harnesses", action: #selector(MainWindowController.showAllHarnesses(_:)), - keyEquivalent: "") - showAll.target = target - menu.addItem(showAll) - let hideAll = NSMenuItem(title: "Hide All Harnesses", action: #selector(MainWindowController.hideAllHarnesses(_:)), - keyEquivalent: "") - hideAll.target = target - menu.addItem(hideAll) - return menu - } - - private static func statusDot(_ status: SidebarView.FilterStatus) -> NSImage { - let color: NSColor - switch status { - case .working: color = StatusColors.working - case .waitingForInput: color = StatusColors.waiting - case .idle, .dead: color = StatusColors.idle - case .statusPending: color = .clear - } - return NSImage(size: NSSize(width: 10, height: 10), flipped: false) { rect in - let dot = NSBezierPath(ovalIn: rect.insetBy(dx: 1, dy: 1)) - color.setFill() - dot.fill() - if status == .statusPending || status == .dead { - StatusColors.idle.setStroke() - dot.lineWidth = 1.2 - dot.stroke() - } - return true - } - } - - /// The row's context menu: rename, the stop ladder (gentlest first) or resume/remove, - /// then the "here" actions. Items carry the row's session name, so they act on the - /// clicked row. - static func contextMenu(for entry: SidebarEntry, attached: Bool) -> NSMenu { - let menu = NSMenu() - func add(_ title: String, _ action: Selector, _ symbol: String? = nil) { - let item = NSMenuItem(title: title, action: action, keyEquivalent: "") - item.representedObject = entry.sessionName - if let symbol { item.image = HarnessIcons.symbol(symbol, nil) } - menu.addItem(item) - } - add("Rename…", #selector(MainWindowController.renameSession(_:)), "pencil") - menu.addItem(.separator()) - switch entry.status { - case .live: - add("Detach", #selector(MainWindowController.detachSession(_:)), "eject") - add("Close…", #selector(MainWindowController.closeSession(_:)), "xmark.circle") - add("Reload…", #selector(MainWindowController.reloadSession(_:)), "arrow.clockwise") - add("Kill…", #selector(MainWindowController.killSession(_:)), "bolt.circle") - case .dead: - add("Resume…", #selector(MainWindowController.resumeSession(_:)), "play.circle") - add("Remove from Registry", #selector(MainWindowController.removeFromRegistry(_:)), "trash") - } - menu.addItem(.separator()) - add("New Session Here…", #selector(MainWindowController.newSessionHere(_:)), "folder.badge.plus") - add("New Shell Here", #selector(MainWindowController.newShellHere(_:)), "apple.terminal") - add("Duplicate", #selector(MainWindowController.duplicateSession(_:)), "plus.square.on.square") - menu.addItem(.separator()) - add("Copy Path", #selector(MainWindowController.copySessionPath(_:)), "doc.on.doc") - add("Show in Finder", #selector(MainWindowController.revealSessionFolder(_:)), "folder") - return menu - } -} diff --git a/swift/Sources/MicrohmApp/Main/MainToolbar.swift b/swift/Sources/MicrohmApp/Main/MainToolbar.swift deleted file mode 100644 index 8de3e0a..0000000 --- a/swift/Sources/MicrohmApp/Main/MainToolbar.swift +++ /dev/null @@ -1,142 +0,0 @@ -import AppKit -import MicrohmCore - -/// The window's unified toolbar (Java's control row): the sidebar toggle, the create -/// actions, the optional paging, stop-ladder and batch groups, and on the trailing side -/// usage, settings and the light/dark switch. Settings → Toolbar picks labels and groups; -/// a change rebuilds the toolbar. -final class MainToolbar: NSObject, NSToolbarDelegate { - - private enum Item { - static let newSession = NSToolbarItem.Identifier("microhm.new") - static let newHere = NSToolbarItem.Identifier("microhm.newHere") - static let shellHere = NSToolbarItem.Identifier("microhm.shellHere") - static let duplicate = NSToolbarItem.Identifier("microhm.duplicate") - static let pageUp = NSToolbarItem.Identifier("microhm.pageUp") - static let pageDown = NSToolbarItem.Identifier("microhm.pageDown") - static let detach = NSToolbarItem.Identifier("microhm.detach") - static let close = NSToolbarItem.Identifier("microhm.close") - static let kill = NSToolbarItem.Identifier("microhm.kill") - static let closeAll = NSToolbarItem.Identifier("microhm.closeAll") - static let batchClose = NSToolbarItem.Identifier("microhm.batchClose") - static let removeDead = NSToolbarItem.Identifier("microhm.removeDead") - static let usage = NSToolbarItem.Identifier("microhm.usage") - static let settings = NSToolbarItem.Identifier("microhm.settings") - static let theme = NSToolbarItem.Identifier("microhm.theme") - } - - let toolbar: NSToolbar - private weak var owner: MainWindowController? - private var themeItem: NSToolbarItem? - - init(owner: MainWindowController) { - self.owner = owner - toolbar = NSToolbar(identifier: "MicrohmMainToolbar-\(UUID().uuidString)") - super.init() - toolbar.delegate = self - toolbar.displayMode = owner.toolbarLabels ? .iconAndLabel : .iconOnly - toolbar.allowsUserCustomization = false - toolbar.autosavesConfiguration = false - } - - func validate() { - toolbar.validateVisibleItems() - } - - func updateThemeItem() { - guard let themeItem, let owner else { return } - let dark = owner.isDark - themeItem.image = HarnessIcons.symbol(dark ? "sun.max" : "moon", dark ? "Light" : "Dark") - themeItem.label = dark ? "Light" : "Dark" - themeItem.toolTip = dark ? "Switch to the light appearance" : "Switch to the dark appearance" - } - - func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { - guard let owner else { return [] } - var items: [NSToolbarItem.Identifier] = [.toggleSidebar, .sidebarTrackingSeparator, - Item.newSession, Item.newHere, Item.shellHere, Item.duplicate] - if owner.toolbarPageButtons { - items += [.space, Item.pageUp, Item.pageDown] - } - if owner.toolbarStopLadder { - items += [.space, Item.detach, Item.close, Item.kill, Item.closeAll] - } - if owner.toolbarBatchActions { - items += [.space, Item.batchClose, Item.removeDead] - } - items += [.flexibleSpace, Item.usage, Item.settings, Item.theme] - return items - } - - func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { - toolbarDefaultItemIdentifiers(toolbar) - } - - func toolbar(_ toolbar: NSToolbar, itemForItemIdentifier id: NSToolbarItem.Identifier, - willBeInsertedIntoToolbar flag: Bool) -> NSToolbarItem? { - switch id { - case Item.newSession: - return item(id, "New…", "plus.rectangle.on.folder", "Start a new session… (⌘N)", - #selector(MainWindowController.newSession(_:))) - case Item.newHere: - return item(id, "New Here", "folder.badge.plus", "New session where the selected session is (⇧⌘N)", - #selector(MainWindowController.newSessionHere(_:))) - case Item.shellHere: - return item(id, "Shell Here", "apple.terminal", "New shell in the selected session's folder (⌘T)", - #selector(MainWindowController.newShellHere(_:))) - case Item.duplicate: - return item(id, "Duplicate", "plus.square.on.square", "Duplicate the selected session (⌘D)", - #selector(MainWindowController.duplicateSession(_:))) - case Item.pageUp: - return item(id, "Page Up", "chevron.up.2", "Scroll the selected session one page up", - #selector(MainWindowController.scrollSessionPageUp(_:))) - case Item.pageDown: - return item(id, "Page Down", "chevron.down.2", "Scroll the selected session one page down", - #selector(MainWindowController.scrollSessionPageDown(_:))) - case Item.detach: - return item(id, "Detach", "eject", "Detach the selected session (keeps it running)", - #selector(MainWindowController.detachSession(_:))) - case Item.close: - return item(id, "Close", "xmark.circle", "Close the selected session gracefully (⌘W)", - #selector(MainWindowController.closeSession(_:))) - case Item.kill: - return item(id, "Kill", "bolt.circle", "Kill the selected session…", - #selector(MainWindowController.killSession(_:))) - case Item.closeAll: - return item(id, "Close All", "power", "Gracefully close all live sessions…", - #selector(MainWindowController.closeAllSessions(_:))) - case Item.batchClose: - return item(id, "Batch Close", "checklist", "Close a chosen batch of live sessions…", - #selector(MainWindowController.batchCloseSessions(_:))) - case Item.removeDead: - return item(id, "Remove Dead", "trash", "Remove a chosen batch of dead sessions from the registry…", - #selector(MainWindowController.removeDeadSessions(_:))) - case Item.usage: - return item(id, "Usage", "gauge.with.dots.needle.50percent", "Show harness usage and limits", - #selector(MainWindowController.showUsage(_:))) - case Item.settings: - return item(id, "Settings", "gearshape", "Settings (⌘,)", #selector(MainWindowController.openSettings(_:))) - case Item.theme: - let item = item(id, "Light", "sun.max", "", #selector(MainWindowController.toggleAppearance(_:))) - themeItem = item - updateThemeItem() - return item - default: - return nil - } - } - - private func item(_ id: NSToolbarItem.Identifier, _ label: String, _ symbol: String, _ tip: String, - _ action: Selector) -> NSToolbarItem { - let item = NSToolbarItem(itemIdentifier: id) - item.label = label - item.paletteLabel = label - item.toolTip = tip - item.image = HarnessIcons.symbol(symbol, label) - item.action = action - item.target = owner - item.isBordered = true - item.autovalidates = true - return item - } -} diff --git a/swift/Sources/MicrohmApp/Main/MainWindowController.swift b/swift/Sources/MicrohmApp/Main/MainWindowController.swift deleted file mode 100644 index ca519e9..0000000 --- a/swift/Sources/MicrohmApp/Main/MainWindowController.swift +++ /dev/null @@ -1,1512 +0,0 @@ -import AppKit -import MicrohmCore -import MicrohmShared -import MicrohmTerminal - -/// The main window: the sessions sidebar on the left, the selected session's terminal on -/// the right, a unified toolbar on top (Java's `MainWindow`). Owns the window's session -/// state — the reconciled rows, the attached terminals, the status polling — and every -/// session action the toolbar, the menus and the keyboard reach. -/// -/// Threading: everything here runs on the main thread except the closures handed to -/// `background`, which make the blocking daemon round trips (listing, attaching, -/// capturing, creating, killing) and hop back with `DispatchQueue.main.async`. -final class MainWindowController: NSWindowController, NSWindowDelegate, SidebarViewControllerDelegate, - NSMenuItemValidation, NSToolbarItemValidation { - - static let sidebarWidth: CGFloat = 280 - /// Keep the session part of the window title useful without a prompt-derived Codex - /// preview crowding out everything else. - static let windowTitleSessionMaxChars = 64 - - let model: AppModel - private var backend: SessionBackend { model.backend } - private var registry: SessionRegistry { model.registry } - - private let splitController = NSSplitViewController() - let sidebar = SidebarViewController() - private let terminalArea = TerminalAreaViewController() - private var sidebarItem: NSSplitViewItem? - private var toolbarController: MainToolbar? - - /// Runs every blocking daemon round trip, so the main thread only paints and reacts. - private let background = DispatchQueue(label: "microhm-background", qos: .userInitiated, attributes: .concurrent) - /// Serializes settings rewrites so rapid UI changes cannot land out of order. - private let settingsQueue = DispatchQueue(label: "microhm-settings") - - private var statusPoller: SessionStatusPoller! - private var gracefulCloser: GracefulCloser! - private var statusPollTimer: Timer? - private var activeTabPollTimer: Timer? - private var keyMonitor: Any? - private var appearanceObservation: NSKeyValueObservation? - - /// Complete reconciled set; the sidebar shows its sorted/filtered projection. - private var allEntries: [SidebarEntry] = [] - /// Live terminal attachments, keyed by session name. Survive sidebar rebuilds. - private var attached: [String: SessionTerminal] = [:] - /// Attaches in flight, each mapped to its generation ticket: a later - /// `removeAttachment` invalidates a result that has not landed yet. - private var attaching: [String: Int] = [:] - private var attachGeneration: [String: Int] = [:] - /// Sessions in the order they were first attached this run — the Ctrl+Tab order. - private var attachOrder: [String] = [] - /// Live rows a poll found gone, already being refreshed away. - private var goneSessions: Set = [] - private var refreshFailureShowing = false - private let refreshTickets = SidebarRefreshTickets() - private var budgetsLoaded = false - private var budgetRefreshSeq = 0 - private var createInFlight = false - private var disposed = false - private var lastSelectedSessionName: String? - private var activeTabCatchUpAt: [String: Date] = [:] - - // view settings, seeded from AppSettings - private(set) var sidebarSort = SidebarView.SortMode.sessionName - private(set) var sidebarSortDescending = false - private(set) var visibleStatuses = Set(SidebarView.FilterStatus.allCases) - private(set) var visibleHarnesses = Set(SidebarView.HarnessFamily.allCases) - private(set) var toolbarLabels = AppSettings.toolbarLabels() - private(set) var toolbarPageButtons = AppSettings.toolbarPageButtons() - private(set) var toolbarStopLadder = AppSettings.toolbarStopLadder() - private(set) var toolbarBatchActions = AppSettings.toolbarBatchActions() - private var pageKeys = AppSettings.pageKeys() - private var sidebarBackground = MainWindowController.effectiveSidebarBackground() - private var rightPaneMatchesSidebar = AppSettings.rightPaneMatchesSidebar() - private var terminalBackgroundOverride = AppSettings.terminalBackgroundOverride() - private var sidebarReticule = AppSettings.sidebarReticule() - private(set) var sidebarFolderGroups = AppSettings.sidebarFolderGroups() - private var terminalFontFamily = AppSettings.terminalFontFamily() - private var terminalFontSize = AppSettings.terminalFontSize() - private var statusPollInterval = Double(AppSettings.statusPollIntervalMs()) / 1000 - private var statusPollingEnabled = AppSettings.statusPollingEnabled() - private var activeTabPollMode = AppSettings.activeTabPollMode() - - /// Called whenever the number of live sessions may have changed (the status item). - var onLiveSessionsChanged: (() -> Void)? - var onOpenSettings: (() -> Void)? - - init(model: AppModel) { - self.model = model - let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1180, height: 760), - styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView], - backing: .buffered, defer: false) - window.title = AppModel.appName - window.titleVisibility = .visible - window.toolbarStyle = .unified - window.minSize = NSSize(width: 640, height: 400) - window.setFrameAutosaveName("MicrohmMainWindow") - window.tabbingMode = .disallowed - super.init(window: window) - window.delegate = self - - statusPoller = SessionStatusPoller(backend, { [background] task in background.async(execute: task) }, - { task in DispatchQueue.main.async(execute: task) }, SystemClock.shared) - gracefulCloser = GracefulCloser(backend, 0.25, 10, 5) - - restoreSidebarViewSettings() - buildContent() - installToolbar() - applyAppearance() - applySurfaces() - updateSidebarControls() - // the split view controller sizes the window to its views' fitting size - window.setContentSize(NSSize(width: 1180, height: 760)) - if !window.setFrameUsingName("MicrohmMainWindow") { - window.center() - } - - backend.setEventHandlers(changed: { [weak self] _ in - // never reselect: an agent's spawn must not steal focus - DispatchQueue.main.async { self?.refreshSidebar(nil) } - }, killed: { [weak self] session in - DispatchQueue.main.async { self?.sessionKilledExternally(session) } - }, runEnded: { [weak self] session in - DispatchQueue.main.async { self?.dropRuntimeArtifacts(session) } - }) - - startPollTimers() - installKeyMonitor() - appearanceObservation = NSApp.observe(\.effectiveAppearance, options: [.new]) { [weak self] _, _ in - DispatchQueue.main.async { self?.effectiveAppearanceChanged() } - } - refreshSidebar(nil) - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("not used") - } - - // MARK: - layout - - private func buildContent() { - sidebar.delegate = self - sidebar.reticuleEnabled = sidebarReticule - sidebar.loadViewIfNeeded() - sidebar.budgetPanel.onRefresh = { [weak self] in self?.refreshHarnessBudgets() } - terminalArea.onNewSession = { [weak self] in self?.newSession(nil) } - terminalArea.onResume = { [weak self] in self?.resumeSession(nil) } - - let sidebarItem = NSSplitViewItem(sidebarWithViewController: sidebar) - sidebarItem.minimumThickness = 200 - sidebarItem.maximumThickness = 460 - sidebarItem.canCollapse = true - sidebarItem.allowsFullHeightLayout = true - sidebarItem.titlebarSeparatorStyle = .none - self.sidebarItem = sidebarItem - let contentItem = NSSplitViewItem(viewController: terminalArea) - contentItem.titlebarSeparatorStyle = .line - splitController.addSplitViewItem(sidebarItem) - splitController.addSplitViewItem(contentItem) - splitController.splitView.autosaveName = "MicrohmSplit" - window?.contentViewController = splitController - if UserDefaults.standard.object(forKey: "NSSplitView Subview Frames MicrohmSplit") == nil { - splitController.splitView.setPosition(MainWindowController.sidebarWidth, ofDividerAt: 0) - } - } - - private func installToolbar() { - let toolbar = MainToolbar(owner: self) - toolbarController = toolbar - window?.toolbar = toolbar.toolbar - } - - /// Rebuilds the toolbar after a Settings change to labels or the optional groups. - private func rebuildToolbar() { - installToolbar() - } - - // MARK: - appearance - - /// Applies `ui.theme`: explicit light or dark, or (unset) the system's, live. - private func applyAppearance() { - if AppModel.hasExplicitSetting("ui.theme") { - NSApp.appearance = NSAppearance(named: AppSettings.uiTheme() == .light ? .aqua : .darkAqua) - } else { - NSApp.appearance = nil - } - } - - var isDark: Bool { - let appearance = window?.effectiveAppearance ?? NSApp.effectiveAppearance - return appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua - } - - private func effectiveAppearanceChanged() { - guard !disposed else { return } - applySurfaces() - toolbarController?.updateThemeItem() - } - - /// The toolbar's sun/moon: switches between light and dark, live, and saves it. - @objc func toggleAppearance(_ sender: Any?) { - let theme: AppSettings.UiTheme = isDark ? .light : .dark - NSApp.appearance = NSAppearance(named: theme == .light ? .aqua : .darkAqua) - settingsQueue.async { AppSettings.saveUiTheme(theme) } - // the explicit-setting check reads the file: apply now, not after the save lands - applySurfaces() - toolbarController?.updateThemeItem() - } - - /// `sidebar.background` as this port reads it: unset means the native translucent - /// sidebar (the setting's "default"). - static func effectiveSidebarBackground() -> AppSettings.SidebarBackground { - AppModel.hasExplicitSetting("sidebar.background") ? AppSettings.sidebarBackground() : .default - } - - /// The sidebar's solid fill, or nil for the system's translucent source list. - private func sidebarFill() -> NSColor? { - switch sidebarBackground { - case .default: return nil - case .uiGray: return .windowBackgroundColor - case .terminal: return isDark ? .black : .white - } - } - - /// Re-resolves every surface: on startup, Settings Save and every theme switch. - private func applySurfaces() { - let fill = sidebarFill() - sidebar.applyBackground(fill) - terminalArea.applyBackground(rightPaneMatchesSidebar ? fill : nil) - for terminal in attached.values { - applyTerminalBackground(terminal) - } - } - - private func applyTerminalBackground(_ terminal: SessionTerminal) { - let light = !isDark - if rightPaneMatchesSidebar, let fill = sidebarFill(), let rgb = MainWindowController.rgb(fill, in: window) { - terminal.applyBackground(rgb, light: light) - } else if let pin = terminalBackgroundOverride { - terminal.applyBackground(light: pin == .white) - } else { - terminal.applyBackground(light: light) - } - } - - /// `0xRRGGBB` of a (possibly dynamic) colour as the window draws it. - static func rgb(_ color: NSColor, in window: NSWindow?) -> Int? { - var result: Int? - (window?.effectiveAppearance ?? NSApp.effectiveAppearance).performAsCurrentDrawingAppearance { - guard let c = color.usingColorSpace(.sRGB) else { return } - let r = Int((c.redComponent * 255).rounded()), g = Int((c.greenComponent * 255).rounded()) - let b = Int((c.blueComponent * 255).rounded()) - result = (r << 16) | (g << 8) | b - } - return result - } - - // MARK: - sidebar view settings - - private func restoreSidebarViewSettings() { - let saved = AppSettings.sidebarViewSettings() - sidebarSort = SidebarView.SortMode.fromKey(saved.sort) - sidebarSortDescending = saved.descending - visibleStatuses = Set(SidebarView.FilterStatus.allCases.filter { !saved.hiddenStatuses.contains($0.key) }) - visibleHarnesses = Set(SidebarView.HarnessFamily.allCases.filter { !saved.hiddenHarnessFamilies.contains($0.key) }) - } - - /// Only the folder sort keeps a folder's sessions adjacent, so grouping follows the - /// setting and the current sort together. - private var folderGrouping: Bool { - sidebarFolderGroups && sidebarSort == .directoryName - } - - /// Applies one view change immediately, then saves its snapshot in the background. - private func applySidebarViewChange() { - updateSidebarControls() - rebuildVisibleSidebar(lastSelectedSessionName, activate: false) - let hiddenStatuses = Set(SidebarView.FilterStatus.allCases.filter { !visibleStatuses.contains($0) }.map(\.key)) - let hiddenHarnesses = Set(SidebarView.HarnessFamily.allCases.filter { !visibleHarnesses.contains($0) }.map(\.key)) - let sort = sidebarSort.key - let descending = sidebarSortDescending - settingsQueue.async { - AppSettings.saveSidebarViewSettings(sort, descending, hiddenStatuses, hiddenHarnesses) - } - } - - private func updateSidebarControls() { - let total = SidebarView.FilterStatus.allCases.count - let totalHarnesses = SidebarView.HarnessFamily.allCases.count - let filter = visibleStatuses.count == total ? "Filter: All" : "Filter: \(visibleStatuses.count)/\(total)" - let harness = visibleHarnesses.count == totalHarnesses - ? "Harness: All" : "Harness: \(visibleHarnesses.count)/\(totalHarnesses)" - sidebar.updateControls(sortLabel: sidebarSort.label, sortDescending: sidebarSortDescending, - filterSummary: filter, filtering: visibleStatuses.count != total, - harnessSummary: harness, harnessFiltering: visibleHarnesses.count != totalHarnesses) - } - - @objc func sortBy(_ sender: NSMenuItem) { - guard let mode = sender.representedObject as? String else { return } - sidebarSort = SidebarView.SortMode.fromKey(mode) - applySidebarViewChange() - } - - @objc func toggleSortDescending(_ sender: Any?) { - sidebarSortDescending.toggle() - applySidebarViewChange() - } - - @objc func toggleStatusFilter(_ sender: NSMenuItem) { - guard let status = SidebarView.FilterStatus(rawValue: sender.tag) else { return } - if visibleStatuses.contains(status) { visibleStatuses.remove(status) } else { visibleStatuses.insert(status) } - applySidebarViewChange() - } - - @objc func showAllStatuses(_ sender: Any?) { - visibleStatuses = Set(SidebarView.FilterStatus.allCases) - applySidebarViewChange() - } - - @objc func hideAllStatuses(_ sender: Any?) { - visibleStatuses = [] - applySidebarViewChange() - } - - @objc func toggleHarnessFilter(_ sender: NSMenuItem) { - let families = SidebarView.HarnessFamily.allCases - guard sender.tag >= 0, sender.tag < families.count else { return } - let family = families[sender.tag] - if visibleHarnesses.contains(family) { visibleHarnesses.remove(family) } else { visibleHarnesses.insert(family) } - applySidebarViewChange() - } - - @objc func showAllHarnesses(_ sender: Any?) { - visibleHarnesses = Set(SidebarView.HarnessFamily.allCases) - applySidebarViewChange() - } - - @objc func hideAllHarnesses(_ sender: Any?) { - visibleHarnesses = [] - applySidebarViewChange() - } - - @objc func toggleFolderGroups(_ sender: Any?) { - sidebarFolderGroups.toggle() - let on = sidebarFolderGroups - settingsQueue.async { AppSettings.saveSidebarFolderGroups(on) } - rebuildVisibleSidebar(lastSelectedSessionName, activate: false) - } - - func sidebarSortMenu(_ sidebar: SidebarViewController) -> NSMenu { MainMenu.sortMenu(self) } - func sidebarStatusFilterMenu(_ sidebar: SidebarViewController) -> NSMenu { MainMenu.statusFilterMenu(self) } - func sidebarHarnessFilterMenu(_ sidebar: SidebarViewController) -> NSMenu { MainMenu.harnessFilterMenu(self) } - - // MARK: - refresh / reconciliation - - /// Reconciles the registry against the daemon off the main thread — listing is a - /// socket round trip, and a wedged daemon must never freeze painting — then applies - /// the result. Only the newest of overlapping refreshes applies (`refreshTickets`). - /// `quiet`: a refresh nobody asked for (a session ended by itself) fails silently. - func refreshSidebar(_ reselect: String?, quiet: Bool = false) { - guard !disposed else { return } - let seq = refreshTickets.issue(reselect) - let registry = self.registry - let backend = self.backend - background.async { [weak self] in - let result: ReconciliationResult - do { - result = Reconciler.reconcile(registry.sessions(), try backend.listSessions()) - } catch { - DispatchQueue.main.async { - guard let self else { return } - self.refreshTickets.failed(seq) - if quiet || self.refreshFailureShowing || self.disposed { return } - self.refreshFailureShowing = true - self.showAlert("Refresh failed", "The session daemon is unreachable: \(error.localizedDescription)", - style: .critical) { self.refreshFailureShowing = false } - } - return - } - DispatchQueue.main.async { - guard let self, !self.disposed, self.refreshTickets.isCurrent(seq) else { return } - self.applySidebar(result, reselect: self.refreshTickets.takeReselect()) - } - } - } - - private func applySidebar(_ result: ReconciliationResult, reselect: String?) { - goneSessions.removeAll() - let toReselect = reselect ?? sidebar.selectedEntry?.sessionName - // Carry each live row's last poll result across the rebuild: acting on one - // session must not blank every other session's badge until the next tick. - var previousLive: [String: SidebarEntry] = [:] - for entry in allEntries where entry.status == .live { - previousLive[entry.sessionName] = entry - } - // Sessions that left the daemon leave a dead connection behind; evict it so - // reattach and Resume start clean, and so Ctrl+Tab stops cycling onto ghosts. - let live = Set(result.liveManaged.map(\.sessionName)) - let toEvict = Set(attached.keys).union(attaching.keys).subtracting(live) - for name in toEvict { - removeAttachment(name) - statusPoller.forget(name) - } - allEntries = [] - for entry in result.liveManaged { - let row = SidebarEntry.live(entry) - row.isAttached = attached[entry.sessionName] != nil - if let previous = previousLive[entry.sessionName] { - if previous.state != nil { - row.setState(previous.state, previous.stateReason) - } - row.setPaneTitle(previous.paneTitle) - } - allEntries.append(row) - } - for entry in result.deadRegistered { - allEntries.append(SidebarEntry.dead(entry)) - } - if reselect != nil { - lastSelectedSessionName = reselect - } - rebuildVisibleSidebar(toReselect, activate: toReselect != nil) - if !budgetsLoaded { - budgetsLoaded = true - refreshHarnessBudgets() - } - onLiveSessionsChanged?() - } - - /// Rebuilds the visible projection without disturbing cached terminal attachments. - private func rebuildVisibleSidebar(_ reselect: String?, activate: Bool) { - let visible = SidebarView.sorted(allEntries.filter { SidebarView.isVisible($0, visibleStatuses, visibleHarnesses) }, - sidebarSort, descending: sidebarSortDescending) - let previouslySelected = sidebar.selectedEntry?.sessionName - sidebar.reticuleEnabled = sidebarReticule - sidebar.setEntries(visible, grouping: folderGrouping, select: nil) - var selected = reselect.flatMap { name in visible.contains { $0.sessionName == name } ? name : nil } - let reselectHidden = reselect != nil && selected == nil - if selected == nil, let previouslySelected, visible.contains(where: { $0.sessionName == previouslySelected }) { - // the reselect target (e.g. a session just created) may be filtered out — - // don't drop the user's still-live prior selection because of it - selected = previouslySelected - } - sidebar.select(sessionName: selected, scroll: true) - if reselectHidden, let reselect, allEntries.contains(where: { $0.sessionName == reselect }) { - terminalArea.showBanner("'\(reselect)' was created but is hidden by your current filter.") - } - if allEntries.isEmpty { - sidebar.setEmptyText("No sessions yet.\nPress ⌘N to start one.") - } else { - sidebar.setEmptyText(visible.isEmpty ? "Every session is hidden by the current filters." : "") - } - if sidebar.selectedEntry != nil, activate { - activateSelected() - } else { - let entry = sidebar.selectedEntry - updateWindowTitle(entry) - if entry == nil { - terminalArea.showDefault() - } - toolbarController?.validate() - } - } - - /// Thread-safe in Java; here always called on main: a session killed by something - /// other than this window (an agent's MCP `kill`) drops exactly what Kill drops. - private func sessionKilledExternally(_ session: String) { - guard !disposed else { return } - dropSessionArtifacts(session) - refreshSidebar(nil) - } - - // MARK: - selection → lazy attach - - func sidebarSelectionDidChange(_ sidebar: SidebarViewController) { - activateSelected() - } - - func sidebarActivate(_ sidebar: SidebarViewController) { - activateSelected() - } - - func sidebar(_ sidebar: SidebarViewController, menuFor entry: SidebarEntry) -> NSMenu? { - MainMenu.contextMenu(for: entry, attached: entry.isAttached) - } - - /// Reflects the current selection in the terminal area, attaching lazily. - private func activateSelected() { - let entry = sidebar.selectedEntry - updateWindowTitle(entry) - defer { toolbarController?.validate() } - guard let entry else { - terminalArea.showDefault() - return - } - lastSelectedSessionName = entry.sessionName - switch entry.status { - case .live: - attachAndShow(entry) - maybeCatchUpActiveTab(entry) - case .dead: - terminalArea.showDead(entry.displayName) - } - } - - /// Window title: the selected session's name, its folder as the subtitle. - private func updateWindowTitle(_ entry: SidebarEntry?) { - guard let window else { return } - guard let entry else { - window.title = AppModel.appName - window.subtitle = "" - return - } - window.title = MainWindowController.ellipsizeRight(entry.displayName, MainWindowController.windowTitleSessionMaxChars) - window.subtitle = entry.abbreviatedPath - } - - static func ellipsizeRight(_ text: String, _ max: Int) -> String { - if text.count <= max { return text } - if max <= 1 { return "…" } - return String(text.prefix(max - 1)).trimmingCharacters(in: .whitespaces) + "…" - } - - /// Attaches on first selection only; re-selecting an attached session just shows its - /// terminal. A cached terminal whose stream died is evicted and replaced. - private func attachAndShow(_ entry: SidebarEntry) { - let name = entry.sessionName - if let terminal = attached[name], !terminal.isAlive { - removeAttachment(name) - statusPoller.forget(name) // a dead connection means that lifecycle ended - } - if let terminal = attached[name] { - terminalArea.showTerminal(name) - terminal.focus() - return - } - if attaching[name] == nil { - let generation = bumpAttachGeneration(name) - attaching[name] = generation - let disableWheel = entry.harnessType == .codex && AppSettings.codexMouseWheelDisabled() - let backend = self.backend - background.async { [weak self] in - do { - let transport = try backend.attach(name, columns: SessionTerminal.columns, rows: SessionTerminal.rows) - DispatchQueue.main.async { - self?.landAttach(name, generation, transport, disableWheel) - } - } catch { - DispatchQueue.main.async { - self?.failAttach(name, generation, error.localizedDescription) - } - } - } - } - if isSelected(name) { - terminalArea.showPlaceholder("Attaching to '\(entry.displayName)'…", progress: true) - } - } - - private func bumpAttachGeneration(_ name: String) -> Int { - let next = (attachGeneration[name] ?? 0) + 1 - attachGeneration[name] = next - return next - } - - private func isCurrentAttach(_ name: String, _ generation: Int) -> Bool { - (attachGeneration[name] ?? 0) == generation - } - - private func settleInFlight(_ name: String, _ generation: Int) { - if attaching[name] == generation { - attaching[name] = nil - } - } - - /// Builds the terminal for a landed attach and caches it whatever the selection is - /// now; shows it only if its row is still selected. A superseded result is closed. - private func landAttach(_ name: String, _ generation: Int, _ transport: TerminalTransport, _ disableWheel: Bool) { - settleInFlight(name, generation) - if disposed || !isCurrentAttach(name, generation) { - transport.close() - return - } - let config = SessionTerminal.Config( - background: nil, light: !isDark, - palette: AnsiPalettes.forSetting(MainWindowController.palette(AppSettings.terminalPalette())), - scrollbarHidden: AppSettings.terminalScrollbarHidden(), mouseWheelDisabled: disableWheel, - fontFamily: terminalFontFamily, fontSize: terminalFontSize, optionAsMeta: AppSettings.optionAsMeta()) - let terminal = SessionTerminal(transport: transport, config: config, name: name) - terminal.applyPageKeys(pageKeys) - applyTerminalBackground(terminal) - // a session that ends by itself (exit typed in a shell) must stop showing as live - terminal.onEnded { [weak self] in - self?.refreshSidebar(nil, quiet: true) - } - attached[name] = terminal - if !attachOrder.contains(name) { - attachOrder.append(name) - } - terminalArea.addTerminal(name, view: terminal.view) - if let row = findEntry(name) { - row.isAttached = true - sidebar.reload(row) - } - toolbarController?.validate() - if isSelected(name) { - terminalArea.showTerminal(name) - terminal.focus() - } - } - - /// Shown only while the row is still selected, so keystrokes never land in the wrong - /// session's terminal. - private func failAttach(_ name: String, _ generation: Int, _ message: String) { - settleInFlight(name, generation) - if isCurrentAttach(name, generation), isSelected(name) { - terminalArea.showPlaceholder("Failed to attach to '\(name)': \(message)", symbol: "exclamationmark.triangle") - } - } - - private func isSelected(_ name: String) -> Bool { - sidebar.selectedEntry?.sessionName == name - } - - private func findEntry(_ name: String) -> SidebarEntry? { - allEntries.first { $0.sessionName == name } - } - - /// Drops one terminal and invalidates any attach still in flight, without touching - /// the daemon. - private func removeAttachment(_ name: String) { - _ = bumpAttachGeneration(name) - attaching[name] = nil - if let terminal = attached.removeValue(forKey: name) { - terminal.detach() - terminalArea.removeTerminal(name) - } - attachOrder.removeAll { $0 == name } - } - - static func palette(_ setting: AppSettings.TerminalPalette) -> AnsiPalettes.Palette { - switch setting { - case .macosTerminal: return .macosTerminal - case .iterm2: return .iterm2 - case .xterm: return .xterm - } - } - - // MARK: - status polling - - private func startPollTimers() { - statusPollTimer?.invalidate() - activeTabPollTimer?.invalidate() - statusPollTimer = nil - activeTabPollTimer = nil - if statusPollingEnabled { - let timer = Timer(timeInterval: statusPollInterval, repeats: true) { [weak self] _ in self?.pollLiveSessions() } - timer.tolerance = statusPollInterval * 0.1 - RunLoop.main.add(timer, forMode: .common) - statusPollTimer = timer - DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in self?.pollLiveSessions() } - } else if activeTabPollMode == .scheduled { - let timer = Timer(timeInterval: statusPollInterval, repeats: true) { [weak self] _ in self?.pollActiveTabOnly() } - RunLoop.main.add(timer, forMode: .common) - activeTabPollTimer = timer - } - } - - private func pollLiveSessions() { - let live = allEntries.filter { $0.status == .live }.map(\.sessionEntry) - poll(live) - } - - private func pollActiveTabOnly() { - guard let entry = sidebar.selectedEntry, entry.status == .live else { return } - poll([entry.sessionEntry]) - } - - /// One round of polls; a backend that pins states (the demo) answers without capturing. - private func poll(_ sessions: [SessionEntry], _ completion: ((String, SessionStatusPoller.PollResult) -> Void)? = nil) { - guard !sessions.isEmpty, !disposed else { return } - var real: [SessionEntry] = [] - for session in sessions { - if let fixed = backend.fixedClassification(session.sessionName) { - onFixedStatus(session.sessionName, fixed) - } else { - real.append(session) - } - } - if !real.isEmpty { - statusPoller.pollAll(real) { [weak self] name, result in - self?.onStatusResult(name, result) - completion?(name, result) - } - } - } - - private func onFixedStatus(_ name: String, _ classification: Classification) { - guard let entry = allEntries.first(where: { $0.status == .live && $0.sessionName == name }) else { return } - if entry.state != classification.state || entry.stateReason != classification.reason { - entry.setState(classification.state, classification.reason) - rowChanged(entry, oldStatus: nil, oldDisplayName: entry.displayName) - } - } - - private func onStatusResult(_ name: String, _ result: SessionStatusPoller.PollResult) { - guard !disposed else { return } - if result.sessionGone, goneSessions.insert(name).inserted { - refreshSidebar(nil, quiet: true) // the daemon no longer has it: the row goes dead - } - guard let entry = allEntries.first(where: { $0.status == .live && $0.sessionName == name }) else { - return // went dead or was removed between the poll firing and this result - } - let oldStatus = SidebarView.filterStatus(entry) - let oldDisplayName = entry.displayName - let oldState = entry.state, oldReason = entry.stateReason, oldTitle = entry.paneTitle - if result.stateConfirmed { - entry.setState(result.classification.state, result.classification.reason) - } - entry.setPaneTitle(result.paneTitle) - let changed = oldState != entry.state || oldReason != entry.stateReason || oldTitle != entry.paneTitle - if changed { - rowChanged(entry, oldStatus: oldStatus, oldDisplayName: oldDisplayName) - } - } - - /// Repaints one row, or rebuilds the list when its filter membership or sort - /// position may have moved. - private func rowChanged(_ entry: SidebarEntry, oldStatus: SidebarView.FilterStatus?, oldDisplayName: String) { - let newStatus = SidebarView.filterStatus(entry) - let statusMoved = oldStatus == nil || oldStatus != newStatus - let filterMayChange = statusMoved && visibleStatuses.count != SidebarView.FilterStatus.allCases.count - let orderMayChange = (sidebarSort == .status && statusMoved) - || (sidebarSort == .sessionName && oldDisplayName != entry.displayName) - if filterMayChange || orderMayChange { - rebuildVisibleSidebar(lastSelectedSessionName, activate: false) - } else { - sidebar.reload(entry) - } - if sidebar.selectedEntry === entry { - updateWindowTitle(entry) // a /rename must reach the window title too - } - onLiveSessionsChanged?() - } - - /// ONCE active-tab mode: with the periodic timer off, catch a newly selected live - /// session's badge up the moment it becomes the active tab (rate-limited per session). - private func maybeCatchUpActiveTab(_ entry: SidebarEntry) { - guard !statusPollingEnabled, activeTabPollMode == .once else { return } - let last = entry.state - guard last == nil || last == .working || last == .waitingForInput else { return } - let now = Date() - if let firedAt = activeTabCatchUpAt[entry.sessionName], now.timeIntervalSince(firedAt) < statusPollInterval { - return - } - activeTabCatchUpAt[entry.sessionName] = now - let sessionEntry = entry.sessionEntry - background.async { [weak self] in - _ = self?.catchUpConfirmedState(sessionEntry, last) - } - } - - /// With the periodic timer off, a never-polled (or stale busy) session has no - /// confirmed state, and Close/Reload would refuse forever. Polls a few times until a - /// confirmed classification lands (the detector needs two samples). Blocks: call it - /// off the main thread. A no-op while the periodic timer runs. - private func catchUpConfirmedState(_ session: SessionEntry, _ lastPolled: SessionState?) -> SessionState? { - let staleOrUnknown = lastPolled == nil || lastPolled == .working || lastPolled == .waitingForInput - var polling = true - DispatchQueue.main.sync { polling = self.statusPollingEnabled } - if !staleOrUnknown || polling { - return lastPolled - } - if let fixed = backend.fixedClassification(session.sessionName) { - return fixed.state - } - let deadline = Date().addingTimeInterval(7) - while Date() < deadline { - if let confirmed = pollOnceForConfirmedState(session) { - return confirmed - } - Thread.sleep(forTimeInterval: 1) - } - return nil - } - - private func pollOnceForConfirmedState(_ session: SessionEntry) -> SessionState? { - let done = DispatchSemaphore(value: 0) - let lock = NSLock() - var state: SessionState? - DispatchQueue.main.async { [weak self] in - guard let self else { done.signal(); return } - self.statusPoller.pollAll([session]) { [weak self] name, result in - self?.onStatusResult(name, result) - lock.lock() - state = result.stateConfirmed ? result.classification.state : nil - lock.unlock() - done.signal() - } - } - _ = done.wait(timeout: .now() + 3) - lock.lock(); defer { lock.unlock() } - return state - } - - /// Loads one provider quota snapshot per harness with a live session. - func refreshHarnessBudgets() { - budgetRefreshSeq += 1 - let sequence = budgetRefreshSeq - let harnesses = HarnessBudgetPanel.budgetedHarnesses(SidebarView.activeHarnesses(allEntries)) - sidebar.budgetPanel.showLoading(harnesses) - let usage = model.usage - for harness in harnesses { - background.async { [weak self] in - do { - let snapshot = try usage.load(harness) - DispatchQueue.main.async { - guard let self, sequence == self.budgetRefreshSeq else { return } - self.sidebar.budgetPanel.showSnapshot(harness, snapshot) - } - } catch { - DispatchQueue.main.async { - guard let self, sequence == self.budgetRefreshSeq else { return } - self.sidebar.budgetPanel.showError(harness, error) - } - } - } - } - } - - // MARK: - keyboard - - /// Ctrl+Tab / Ctrl+Shift+Tab and Ctrl+1..9 switch sessions. Taken before the focused - /// terminal sees them — it would otherwise send them to the program — and only while - /// this window is key with no sheet on it. - private func installKeyMonitor() { - keyMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in - guard let self, let window = self.window, event.window === window, window.isKeyWindow, - window.attachedSheet == nil else { - return event - } - let flags = event.modifierFlags.intersection([.shift, .control, .option, .command]) - guard flags.contains(.control), !flags.contains(.command), !flags.contains(.option) else { return event } - if event.keyCode == 48 { // Tab - self.cycleAttached(flags.contains(.shift) ? -1 : 1) - return nil - } - if !flags.contains(.shift), let digit = event.charactersIgnoringModifiers.flatMap(Int.init), (1...9).contains(digit) { - self.jumpToNthSession(digit) - return nil - } - return event - } - } - - /// Cycles through the sessions in the order they were first attached (fixed - /// position, like a browser's tab strip), wrapping at both ends. - private func cycleAttached(_ direction: Int) { - let visible = Set(sidebar.visibleEntries.map(\.sessionName)) - let cycle = attachOrder.filter { attached[$0] != nil && visible.contains($0) } - guard !cycle.isEmpty else { return } - let current = sidebar.selectedEntry?.sessionName - let next: Int - if let current, let index = cycle.firstIndex(of: current) { - next = ((index + direction) % cycle.count + cycle.count) % cycle.count - } else { - next = direction > 0 ? 0 : cycle.count - 1 - } - selectSession(cycle[next]) - } - - /// Ctrl+1..8 jump to the nth visible session; Ctrl+9 always to the last. - private func jumpToNthSession(_ n: Int) { - let rows = sidebar.visibleEntries - guard !rows.isEmpty else { return } - let index = n == 9 ? rows.count - 1 : n - 1 - guard index >= 0, index < rows.count else { return } - selectSession(rows[index].sessionName) - } - - private func selectSession(_ name: String) { - if sidebar.select(sessionName: name, scroll: true) { - activateSelected() - } - } - - @objc func selectNextSession(_ sender: Any?) { cycleAttached(1) } - @objc func selectPreviousSession(_ sender: Any?) { cycleAttached(-1) } - @objc func selectSessionNumber(_ sender: NSMenuItem) { jumpToNthSession(sender.tag) } - - /// Reachable from the View menu even when nothing inside the split view has focus. - @objc func toggleSidebar(_ sender: Any?) { - splitController.toggleSidebar(sender) - } - - @objc func focusSidebar(_ sender: Any?) { - window?.makeFirstResponder(sidebar.outlineView) - } - - // MARK: - terminal font and paging - - private func adjustTerminalFontSize(to size: Int) { - let adjusted = AppSettings.clampTerminalFontSize(size) - guard adjusted != terminalFontSize else { return } - terminalFontSize = adjusted - for terminal in attached.values { - terminal.applyFont(family: terminalFontFamily, size: terminalFontSize) - } - let family = terminalFontFamily - settingsQueue.async { AppSettings.saveTerminalFont(family, adjusted) } - } - - @objc func terminalZoomIn(_ sender: Any?) { adjustTerminalFontSize(to: terminalFontSize + 1) } - @objc func terminalZoomOut(_ sender: Any?) { adjustTerminalFontSize(to: terminalFontSize - 1) } - @objc func terminalZoomReset(_ sender: Any?) { adjustTerminalFontSize(to: AppSettings.defaultTerminalFontSize) } - - private var selectedTerminal: SessionTerminal? { - guard let entry = sidebar.selectedEntry, entry.status == .live else { return nil } - return attached[entry.sessionName] - } - - @objc func scrollSessionPageUp(_ sender: Any?) { selectedTerminal?.pageUp() } - @objc func scrollSessionPageDown(_ sender: Any?) { selectedTerminal?.pageDown() } - @objc func scrollSessionToTop(_ sender: Any?) { selectedTerminal?.scrollToTop() } - @objc func scrollSessionToBottom(_ sender: Any?) { selectedTerminal?.scrollToBottom() } - - // MARK: - validation - - var liveManagedEntries: [SidebarEntry] { allEntries.filter { $0.status == .live } } - private var deadEntries: [SidebarEntry] { allEntries.filter { $0.status == .dead } } - - func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { - if let action = menuItem.action { - switch action { - case #selector(sortBy(_:)): - menuItem.state = (menuItem.representedObject as? String) == sidebarSort.key ? .on : .off - case #selector(toggleSortDescending(_:)): - menuItem.state = sidebarSortDescending ? .on : .off - case #selector(toggleStatusFilter(_:)): - let status = SidebarView.FilterStatus(rawValue: menuItem.tag) - menuItem.state = status.map { visibleStatuses.contains($0) } == true ? .on : .off - case #selector(toggleHarnessFilter(_:)): - let families = SidebarView.HarnessFamily.allCases - menuItem.state = menuItem.tag >= 0 && menuItem.tag < families.count - && visibleHarnesses.contains(families[menuItem.tag]) ? .on : .off - case #selector(toggleFolderGroups(_:)): - menuItem.state = sidebarFolderGroups ? .on : .off - case #selector(toggleAppearance(_:)): - menuItem.title = isDark ? "Use Light Appearance" : "Use Dark Appearance" - default: - break - } - } - return validate(menuItem.action) - } - - func validateToolbarItem(_ item: NSToolbarItem) -> Bool { - validate(item.action) - } - - /// Enables each action exactly when it would do something (Java's - /// `updateSelectionButtons`, plus the context menu's per-status offerings). - func validate(_ action: Selector?) -> Bool { - guard let action else { return true } - let entry = sidebar.selectedEntry - switch action { - case #selector(newSession(_:)): - return !createInFlight - case #selector(newSessionHere(_:)): - return !createInFlight - case #selector(newShellHere(_:)), #selector(duplicateSession(_:)): - return entry != nil && !createInFlight - case #selector(scrollSessionPageUp(_:)), #selector(scrollSessionPageDown(_:)), - #selector(scrollSessionToTop(_:)), #selector(scrollSessionToBottom(_:)): - return selectedTerminal != nil - case #selector(detachSession(_:)): - return entry?.status == .live && entry?.isAttached == true - case #selector(closeSession(_:)), #selector(killSession(_:)), #selector(reloadSession(_:)): - return entry?.status == .live - case #selector(resumeSession(_:)), #selector(removeFromRegistry(_:)): - return entry?.status == .dead - case #selector(renameSession(_:)), #selector(copySessionPath(_:)), #selector(revealSessionFolder(_:)): - return entry != nil - case #selector(closeAllSessions(_:)), #selector(batchCloseSessions(_:)): - return !liveManagedEntries.isEmpty - case #selector(removeDeadSessions(_:)): - return !deadEntries.isEmpty - case #selector(selectNextSession(_:)), #selector(selectPreviousSession(_:)): - return attached.count > 0 - case #selector(selectSessionNumber(_:)): - return !sidebar.visibleEntries.isEmpty - case #selector(terminalZoomIn(_:)): - return terminalFontSize < AppSettings.maxTerminalFontSize - case #selector(terminalZoomOut(_:)): - return terminalFontSize > AppSettings.minTerminalFontSize - default: - return true - } - } - - // MARK: - session actions - - @objc func newSession(_ sender: Any?) { - showNewSessionSheet(prefillPath: nil, prefillHarness: nil) - } - - /// "Another one of these, right there": the New sheet seeded with the selected - /// session's folder and harness. - @objc func newSessionHere(_ sender: Any?) { - guard let entry = sidebar.selectedEntry else { - newSession(sender) - return - } - showNewSessionSheet(prefillPath: entry.sessionEntry.projectPath, prefillHarness: entry.harnessType) - } - - private func showNewSessionSheet(prefillPath: String?, prefillHarness: HarnessType?) { - guard let window, !createInFlight else { return } - let shell = backend.describeShell(AppSettings.sessionShell()) - NewSessionSheet.present(on: window, prefillPath: prefillPath, prefillHarness: prefillHarness, - shellDescription: shell) { [weak self] result in - guard let self, let result else { return } - self.createSession(result.projectPath, result.harness, resumeId: result.resumeId, - displayName: result.displayName, firstMessage: result.firstMessage) - } - } - - /// ⌘T: a new shell in the selected session's folder. No selection is a no-op. - @objc func newShellHere(_ sender: Any?) { - guard let entry = sidebar.selectedEntry else { return } - createSession(URL(fileURLWithPath: entry.sessionEntry.projectPath), .shell) - } - - /// ⌘D: a fresh session of the same harness in the same folder — no resume id, so a - /// dead row duplicates to a new life rather than resuming the old one. - @objc func duplicateSession(_ sender: Any?) { - guard let entry = clickedOrSelected(sender) else { return } - createSession(URL(fileURLWithPath: entry.sessionEntry.projectPath), entry.harnessType) - } - - /// Creates and registers a new session off the main thread (several daemon round - /// trips); `createInFlight` doubles as reentry protection. - private func createSession(_ path: URL, _ harness: HarnessType, resumeId: String? = nil, - displayName: String? = nil, firstMessage: String? = nil) { - guard !createInFlight else { return } - var isDirectory: ObjCBool = false - guard FileManager.default.fileExists(atPath: path.path, isDirectory: &isDirectory), isDirectory.boolValue else { - showAlert("Invalid path", "'\(path.path)' is not a folder.", style: .warning) - return - } - createInFlight = true - toolbarController?.validate() - let backend = self.backend - background.async { [weak self] in - do { - let name = try backend.create(projectPath: path, harness: harness, resumeId: resumeId, - displayName: displayName, firstMessage: firstMessage, - onNoResumeSyntax: { self?.warnNoResumeSyntax(harness) }) - DispatchQueue.main.async { - guard let self else { return } - self.createInFlight = false - self.refreshSidebar(name) - } - } catch { - DispatchQueue.main.async { - guard let self else { return } - self.createInFlight = false - self.toolbarController?.validate() - self.showAlert("Couldn’t start the session", error.localizedDescription, style: .critical) - self.refreshSidebar(nil) // reflect whatever half-state the failure left - } - } - } - } - - private func warnNoResumeSyntax(_ harness: HarnessType) { - DispatchQueue.main.async { [weak self] in - self?.showAlert("No resume syntax", - "'\(harness.id)' has no known resume syntax — starting a fresh session instead.", - style: .warning) - } - } - - /// The row a context-menu item was built for, else the selection. - private func clickedOrSelected(_ sender: Any?) -> SidebarEntry? { - if let item = sender as? NSMenuItem, let name = item.representedObject as? String { - return findEntry(name) - } - return sidebar.selectedEntry - } - - @objc func detachSession(_ sender: Any?) { - guard let entry = clickedOrSelected(sender), entry.status == .live, entry.isAttached else { return } - removeAttachment(entry.sessionName) - entry.isAttached = false - sidebar.reload(entry) - toolbarController?.validate() - if isSelected(entry.sessionName) { - terminalArea.showPlaceholder("'\(entry.displayName)' is detached and still running. Select it again to reattach.", - symbol: "pause.circle") - } - } - - /// ⌘W: gracefully ends the selected live session — the harness quits itself and the - /// shell under it exits; the registry entry stays as a resumable row. Refuses (with an - /// explanation) while anything is in progress. - @objc func closeSession(_ sender: Any?) { - guard let entry = clickedOrSelected(sender) else { return } - gracefulCloseFlow(entry, reload: false) - } - - /// Close, then immediately relaunch the harness from the resume id just captured. - @objc func reloadSession(_ sender: Any?) { - guard let entry = clickedOrSelected(sender) else { return } - gracefulCloseFlow(entry, reload: true) - } - - private func gracefulCloseFlow(_ entry: SidebarEntry, reload: Bool) { - guard entry.status == .live else { return } - let sessionEntry = entry.sessionEntry - let lastPolled = entry.state - let name = sessionEntry.sessionName - let plugin = HarnessPlugins.of(sessionEntry.harnessType) - let review = PreflightDialog.Session(entry) - let closer = gracefulCloser! - background.async { [weak self] in - guard let self else { return } - do { - let resolved = self.catchUpConfirmedState(sessionEntry, lastPolled) - let blocker = try closer.preflight(name, plugin, resolved) - DispatchQueue.main.async { - if let blocker { - self.handleGracefulCloseResult(name, blocker) - return - } - PreflightDialog.present(reload ? .reload(review) : .close(review), on: self.window) { confirmed in - if confirmed { - self.executeGracefulClose(sessionEntry, plugin, resolved, reloadAfter: reload) - } - } - } - } catch { - DispatchQueue.main.async { - self.showAlert(reload ? "Reload pre-flight failed" : "Close pre-flight failed", - "Could not check whether '\(name)' can \(reload ? "reload" : "close") safely: \(error.localizedDescription)", - style: .critical) - } - } - } - } - - private func executeGracefulClose(_ sessionEntry: SessionEntry, _ plugin: HarnessPlugin, _ lastPolled: SessionState?, - reloadAfter: Bool) { - let name = sessionEntry.sessionName - let closer = gracefulCloser! - let registry = self.registry - terminalArea.showBanner(reloadAfter ? "Reloading '\(name)'…" : "Closing '\(name)'…") - background.async { [weak self] in - do { - let result = try closer.close(name, plugin, lastPolled) - // persist the provider's exit receipt before the terminal is dropped: the - // row survives close and now knows which conversation Resume must reopen - if let id = result.harnessSessionIdOpt { - registry.recordHarnessSessionId(name, id) - } - let closedOk = result.outcome == .closed || result.outcome == .alreadyGone - DispatchQueue.main.async { - guard let self else { return } - if reloadAfter && closedOk { - self.dropRuntimeArtifacts(name) - self.resume(registry.find(name) ?? sessionEntry) - } else { - self.handleGracefulCloseResult(name, result) - } - } - } catch { - DispatchQueue.main.async { - self?.showAlert("Close failed", "Graceful close of '\(name)' failed: \(error.localizedDescription)", - style: .critical) - } - } - } - } - - /// Cleanup on success, an explanation on refusal (refusals leave the session intact). - private func handleGracefulCloseResult(_ name: String, _ result: GracefulCloser.Result) { - switch result.outcome { - case .closed, .alreadyGone: - dropRuntimeArtifacts(name) - refreshSidebar(nil) - case .busyState: - showAlert("Session busy", "'\(name)' is not closed: \(result.detail).", style: .informational) - case .busyForeground: - showAlert("Session busy", "'\(name)' is not closed: '\(result.detail)' is still running in it.", - style: .informational) - case .noQuitSyntax: - showAlert("No quit syntax", - "'\(result.detail)' has no verified graceful-quit syntax — use Kill Session… to force it.", - style: .warning) - case .quitTimeout: - showAlert("Close timed out", - "Sent '\(result.detail)' but the harness in '\(name)' didn't exit in time — leaving the session as it is.", - style: .warning) - refreshSidebar(nil) - case .exitTimeout: - showAlert("Close timed out", - "Sent 'exit' but the shell in '\(name)' didn't end in time — something may still be running in it.", - style: .warning) - refreshSidebar(nil) - } - } - - @objc func killSession(_ sender: Any?) { - guard let entry = clickedOrSelected(sender), entry.status == .live else { return } - let name = entry.sessionName - PreflightDialog.present(.kill(PreflightDialog.Session(entry)), on: window) { [weak self] confirmed in - guard confirmed, let self else { return } - let backend = self.backend - self.background.async { [weak self] in - // cleanup only if the session is really gone: a failed kill must not - // orphan a running harness by deleting its registry entry - var gone: Bool - var failure: String? - do { - try backend.killSession(name) - gone = true - } catch { - failure = error.localizedDescription - gone = !((try? backend.hasSession(name)) ?? true) - } - DispatchQueue.main.async { - guard let self else { return } - if gone { - self.dropSessionArtifacts(name) - } else { - self.showAlert("Kill failed", - "Kill failed: \(failure ?? "unknown error")\nThe session is still running; its registry entry is kept.", - style: .critical) - } - self.refreshSidebar(nil) - } - } - } - } - - @objc func resumeSession(_ sender: Any?) { - guard let entry = clickedOrSelected(sender), entry.status == .dead else { return } - resume(entry.sessionEntry) - } - - private func resume(_ sessionEntry: SessionEntry) { - let name = sessionEntry.sessionName - // a fresh lifecycle under the same name: reset quiescence timing and evict any - // terminal left over from the dead one - statusPoller.forget(name) - removeAttachment(name) - let backend = self.backend - if isSelected(name) { - terminalArea.showPlaceholder("Resuming '\(name)'…", progress: true) - } - background.async { [weak self] in - do { - try backend.resume(sessionEntry, onNoResumeSyntax: { self?.warnNoResumeSyntax(sessionEntry.harnessType) }) - DispatchQueue.main.async { self?.refreshSidebar(name) } - } catch { - DispatchQueue.main.async { - guard let self else { return } - self.showAlert("Resume failed", "Failed to resume '\(name)': \(error.localizedDescription)", - style: .critical) - self.refreshSidebar(nil) - } - } - } - } - - @objc func removeFromRegistry(_ sender: Any?) { - guard let entry = clickedOrSelected(sender), entry.status == .dead else { return } - let name = entry.sessionName - registry.remove(name) - discardMcpConfig(name) - statusPoller.forget(name) - refreshSidebar(nil) - } - - /// Changes only the user-facing sidebar name; the session key stays. - @objc func renameSession(_ sender: Any?) { - guard let entry = clickedOrSelected(sender), let current = registry.find(entry.sessionName), - let window else { return } - RenameSheet.present(on: window, current: current.displayName ?? "", inherited: entry.detectedName) { [weak self] choice in - guard let self else { return } - switch choice { - case .cancel: - return - case .clear: - self.registry.put(current.withDisplayName(nil)) - case .rename(let name): - self.registry.put(current.withDisplayName(name)) - } - self.refreshSidebar(entry.sessionName) - } - } - - @objc func copySessionPath(_ sender: Any?) { - guard let entry = clickedOrSelected(sender) else { return } - NSPasteboard.general.clearContents() - NSPasteboard.general.setString(entry.sessionEntry.projectPath, forType: .string) - } - - @objc func revealSessionFolder(_ sender: Any?) { - guard let entry = clickedOrSelected(sender) else { return } - NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: entry.sessionEntry.projectPath) - } - - /// Close All: every live session through the same ladder as Close; whatever refuses - /// or times out is reported together at the end. - @objc func closeAllSessions(_ sender: Any?) { - let live = liveManagedEntries - guard !live.isEmpty else { return } - PreflightDialog.present(.closeAll(live.map(PreflightDialog.Session.init)), on: window) { [weak self] confirmed in - guard confirmed, let self else { return } - let targets = live.map { ($0.sessionEntry, $0.state) } - let closer = self.gracefulCloser! - let registry = self.registry - self.background.async { [weak self] in - var closed: [String] = [] - var leftRunning: [String] = [] - for (entry, lastPolled) in targets { - if let failure = BatchActions.close(entry, lastPolled, closer, registry) { - leftRunning.append(failure) - } else { - closed.append(entry.sessionName) - } - } - DispatchQueue.main.async { - guard let self else { return } - closed.forEach(self.dropRuntimeArtifacts) - if !leftRunning.isEmpty { - self.showAlert("Some sessions are still running", "Left running:\n" + leftRunning.joined(separator: "\n"), - style: .informational) - } - self.refreshSidebar(nil) - } - } - } - } - - @objc func batchCloseSessions(_ sender: Any?) { - let live = liveManagedEntries - guard !live.isEmpty, let window else { return } - let closer = gracefulCloser! - let registry = self.registry - BatchOperationSheet.present( - on: window, title: "Close a batch of sessions", - intro: "Idle sessions are pre-selected. Uncheck any folder or session you want to leave running.", - confirm: "Close Selected", candidates: live, defaultChecked: { $0.state == .idle }, - rowLabel: { $0.statusPhrase }, words: .init(gerund: "Closing", past: "Closed", infinitive: "close"), - queue: background, - operation: { entry in BatchActions.close(entry.sessionEntry, entry.state, closer, registry) }, - onSucceeded: { [weak self] entry in self?.dropRuntimeArtifacts(entry.sessionName) }, - onFinished: { [weak self] in self?.refreshSidebar(nil) }) - } - - @objc func removeDeadSessions(_ sender: Any?) { - let dead = deadEntries - guard !dead.isEmpty, let window else { return } - let registry = self.registry - let poller = statusPoller! - BatchOperationSheet.present( - on: window, title: "Remove dead sessions", - intro: "Removing forgets a session for good — its saved conversation can no longer be resumed. " - + "Uncheck any folder or session you want to keep.", - confirm: "Remove Selected", candidates: dead, defaultChecked: { _ in true }, - rowLabel: { $0.harnessType.id }, words: .init(gerund: "Removing", past: "Removed", infinitive: "remove"), - queue: background, - operation: { entry in - registry.remove(entry.sessionName) - poller.forget(entry.sessionName) - return nil - }, - onSucceeded: { [weak self] entry in self?.discardMcpConfig(entry.sessionName) }, - onFinished: { [weak self] in self?.refreshSidebar(nil) }) - } - - /// Runtime state of an ended lifecycle; the saved entry stays (resumable). - private func dropRuntimeArtifacts(_ name: String) { - removeAttachment(name) - statusPoller.forget(name) - } - - /// Runtime state plus the saved entry: Kill and Remove from registry only. - private func dropSessionArtifacts(_ name: String) { - dropRuntimeArtifacts(name) - registry.remove(name) - discardMcpConfig(name) - } - - private func discardMcpConfig(_ name: String) { - let backend = self.backend - background.async { backend.discardMcpConfig(name) } - } - - @objc func showUsage(_ sender: Any?) { - UsageWindowController.show(initial: sidebar.selectedEntry?.harnessType ?? .claudeCode, usage: model.usage) - } - - @objc func openSettings(_ sender: Any?) { - onOpenSettings?() - } - - @objc func refreshSessions(_ sender: Any?) { - refreshSidebar(nil) - refreshHarnessBudgets() - } - - // MARK: - settings - - /// Applies a saved Settings sheet live: surfaces, terminals, polling, toolbar. - func applySettings(_ result: SettingsResult) { - pageKeys = result.pageKeys - toolbarLabels = result.toolbarLabels - toolbarPageButtons = result.toolbarPageButtons - toolbarStopLadder = result.toolbarStopLadder - toolbarBatchActions = result.toolbarBatchActions - sidebarBackground = result.sidebarBackground - rightPaneMatchesSidebar = result.rightPaneMatchesSidebar - terminalBackgroundOverride = result.backgroundOverride - sidebarReticule = result.sidebarReticule - sidebarFolderGroups = result.sidebarFolderGroups - terminalFontFamily = result.fontFamily - terminalFontSize = AppSettings.clampTerminalFontSize(result.fontSize) - statusPollInterval = Double(AppSettings.clampStatusPollIntervalMs(result.statusPollIntervalMs)) / 1000 - statusPollingEnabled = result.statusPollingEnabled - activeTabPollMode = result.activeTabPollMode - startPollTimers() - applySurfaces() - rebuildVisibleSidebar(lastSelectedSessionName, activate: false) - updateSidebarControls() - rebuildToolbar() - for (name, terminal) in attached { - terminal.applyPalette(MainWindowController.palette(result.palette)) - terminal.applyFont(family: terminalFontFamily, size: terminalFontSize) - terminal.applyOptionAsMeta(result.optionAsMeta) - terminal.applyPageKeys(result.pageKeys) - terminal.applyMouseWheelDisabled(result.codexMouseWheelDisabled && findEntry(name)?.harnessType == .codex) - } - } - - // MARK: - alerts - - /// A sheet on the window; app-modal when another sheet is already up. - func showAlert(_ title: String, _ message: String, style: NSAlert.Style, completion: (() -> Void)? = nil) { - let alert = NSAlert() - alert.messageText = title - alert.informativeText = message - alert.alertStyle = style - if let window, window.attachedSheet == nil, window.isVisible { - alert.beginSheetModal(for: window) { _ in completion?() } - } else { - alert.runModal() - completion?() - } - } - - /// `DebugHooks`: start a session as the New sheet would. - func debugCreate(_ path: String, _ harness: HarnessType, message: String?) { - createSession(URL(fileURLWithPath: path), harness, firstMessage: message) - } - - /// `DebugHooks`: select a row as a click would. - func debugToggleBudgets() { - sidebar.budgetPanel.toggleCollapsed(nil) - } - - func debugSelect(_ name: String) { - selectSession(name) - } - - // MARK: - lifecycle - - func windowWillClose(_ notification: Notification) { - NSApp.terminate(nil) - } - - /// Everything the window does on quit: stops timers, detaches every terminal (kills - /// nothing). - func shutdown() { - guard !disposed else { return } - disposed = true - statusPollTimer?.invalidate() - activeTabPollTimer?.invalidate() - if let keyMonitor { - NSEvent.removeMonitor(keyMonitor) - } - appearanceObservation = nil - for terminal in attached.values { - terminal.detach() - } - settingsQueue.sync {} - } -} - -extension MainWindowController { - /// `DebugHooks`: switch the sort as the Sort menu would. - func debugSort(_ key: String) { - let item = NSMenuItem() - item.representedObject = key - sortBy(item) - } -} diff --git a/swift/Sources/MicrohmApp/Main/TerminalAreaViewController.swift b/swift/Sources/MicrohmApp/Main/TerminalAreaViewController.swift deleted file mode 100644 index 9e2789e..0000000 --- a/swift/Sources/MicrohmApp/Main/TerminalAreaViewController.swift +++ /dev/null @@ -1,246 +0,0 @@ -import AppKit - -/// The right pane: exactly one "card" at a time — the empty-selection message, an -/// "Attaching…"/detached/failed placeholder, the dead-session message, or one attached -/// session's terminal — plus a transient banner floating over whichever is showing. -/// Terminal views stay in the hierarchy while hidden, so switching sessions never rebuilds -/// a terminal (Java's CardLayout). -final class TerminalAreaViewController: NSViewController { - - var onNewSession: (() -> Void)? - var onResume: (() -> Void)? - - private let cards = NSView() - private let defaultCard = MessageCard() - private let placeholderCard = MessageCard() - private let deadCard = MessageCard() - private let banner = BannerView() - private var terminals: [String: NSView] = [:] - private var bannerHide: DispatchWorkItem? - private(set) var visibleTerminal: String? - - override func loadView() { - let root = BackgroundView() - cards.translatesAutoresizingMaskIntoConstraints = false - root.addSubview(cards) - for card in [defaultCard, placeholderCard, deadCard] { - add(card) - } - defaultCard.set(symbol: "rectangle.stack.badge.plus", - title: "No session selected", - message: "Select a session in the sidebar, or start a new one.", - button: "New Session…", action: { [weak self] in self?.onNewSession?() }) - banner.translatesAutoresizingMaskIntoConstraints = false - banner.isHidden = true - root.addSubview(banner) - NSLayoutConstraint.activate([ - cards.leadingAnchor.constraint(equalTo: root.leadingAnchor), - cards.trailingAnchor.constraint(equalTo: root.trailingAnchor), - cards.topAnchor.constraint(equalTo: root.safeAreaLayoutGuide.topAnchor), - cards.bottomAnchor.constraint(equalTo: root.bottomAnchor), - banner.topAnchor.constraint(equalTo: root.safeAreaLayoutGuide.topAnchor, constant: 10), - banner.centerXAnchor.constraint(equalTo: root.centerXAnchor), - banner.widthAnchor.constraint(lessThanOrEqualTo: root.widthAnchor, constant: -32), - root.widthAnchor.constraint(greaterThanOrEqualToConstant: 360), - ]) - view = root - show(defaultCard) - } - - private func add(_ card: NSView) { - card.translatesAutoresizingMaskIntoConstraints = false - cards.addSubview(card) - NSLayoutConstraint.activate([ - card.leadingAnchor.constraint(equalTo: cards.leadingAnchor), - card.trailingAnchor.constraint(equalTo: cards.trailingAnchor), - card.topAnchor.constraint(equalTo: cards.topAnchor), - card.bottomAnchor.constraint(equalTo: cards.bottomAnchor), - ]) - } - - private func show(_ card: NSView) { - for view in cards.subviews { - view.isHidden = view !== card - } - visibleTerminal = terminals.first { $0.value === card }?.key - } - - // MARK: - cards - - func showDefault() { - show(defaultCard) - } - - /// "Attaching to 'x'…", "'x' is detached…", "Failed to attach…". - func showPlaceholder(_ message: String, symbol: String = "hourglass", progress: Bool = false) { - placeholderCard.set(symbol: symbol, title: nil, message: message, button: nil, action: nil, progress: progress) - show(placeholderCard) - } - - func showDead(_ sessionName: String) { - deadCard.set(symbol: "moon.zzz", - title: "'\(sessionName)' has stopped", - message: "Its saved entry can be resumed, or right-click it in the sidebar to remove it.", - button: "Resume…", action: { [weak self] in self?.onResume?() }) - show(deadCard) - } - - func addTerminal(_ name: String, view terminalView: NSView) { - if let old = terminals[name], old !== terminalView { - old.removeFromSuperview() - } - terminals[name] = terminalView - if terminalView.superview !== cards { - terminalView.isHidden = true - add(terminalView) - } - } - - func removeTerminal(_ name: String) { - terminals.removeValue(forKey: name)?.removeFromSuperview() - if visibleTerminal == name { - visibleTerminal = nil - } - } - - func showTerminal(_ name: String) { - guard let terminal = terminals[name] else { return } - show(terminal) - } - - /// The right pane's surface behind the message cards (the terminals paint their own). - func applyBackground(_ color: NSColor?) { - (view as? BackgroundView)?.fill = color - } - - // MARK: - banner - - /// A transient message over whichever card is showing; a fresh message restarts the clock. - func showBanner(_ text: String) { - banner.text = text - banner.isHidden = false - banner.alphaValue = 1 - bannerHide?.cancel() - let hide = DispatchWorkItem { [weak self] in - NSAnimationContext.runAnimationGroup({ context in - context.duration = 0.25 - self?.banner.animator().alphaValue = 0 - }, completionHandler: { - self?.banner.isHidden = true - }) - } - bannerHide = hide - DispatchQueue.main.asyncAfter(deadline: .now() + 4, execute: hide) - } -} - -/// A solid fill when one is set; otherwise the window background. -final class BackgroundView: NSView { - var fill: NSColor? { didSet { needsDisplay = true } } - - override func draw(_ dirtyRect: NSRect) { - (fill ?? .windowBackgroundColor).setFill() - dirtyRect.fill() - } -} - -/// A centred symbol, title, message and optional button: the empty states. -final class MessageCard: NSView { - private let imageView = NSImageView() - private let titleField = NSTextField(labelWithString: "") - private let messageField = NSTextField(wrappingLabelWithString: "") - private let button = NSButton(title: "", target: nil, action: nil) - private let spinner = NSProgressIndicator() - private var action: (() -> Void)? - - override init(frame frameRect: NSRect) { - super.init(frame: frameRect) - imageView.symbolConfiguration = .init(pointSize: 40, weight: .light) - imageView.contentTintColor = .tertiaryLabelColor - titleField.font = .systemFont(ofSize: 17, weight: .semibold) - titleField.textColor = .secondaryLabelColor - titleField.alignment = .center - messageField.alignment = .center - messageField.textColor = .secondaryLabelColor - messageField.preferredMaxLayoutWidth = 420 - button.bezelStyle = .push - button.controlSize = .large - button.target = self - button.action = #selector(clicked(_:)) - spinner.style = .spinning - spinner.controlSize = .small - let stack = NSStackView(views: [imageView, spinner, titleField, messageField, button]) - stack.orientation = .vertical - stack.alignment = .centerX - stack.spacing = 10 - stack.setCustomSpacing(18, after: imageView) - stack.setCustomSpacing(16, after: messageField) - stack.translatesAutoresizingMaskIntoConstraints = false - addSubview(stack) - NSLayoutConstraint.activate([ - stack.centerXAnchor.constraint(equalTo: centerXAnchor), - stack.centerYAnchor.constraint(equalTo: centerYAnchor, constant: -20), - stack.leadingAnchor.constraint(greaterThanOrEqualTo: leadingAnchor, constant: 24), - messageField.widthAnchor.constraint(lessThanOrEqualToConstant: 420), - ]) - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("not used") - } - - func set(symbol: String, title: String?, message: String, button title2: String?, action: (() -> Void)?, - progress: Bool = false) { - imageView.image = progress ? nil : HarnessIcons.symbol(symbol) - imageView.isHidden = progress - spinner.isHidden = !progress - if progress { spinner.startAnimation(nil) } else { spinner.stopAnimation(nil) } - titleField.stringValue = title ?? "" - titleField.isHidden = title == nil - messageField.stringValue = message - button.title = title2 ?? "" - button.isHidden = title2 == nil - self.action = action - } - - @objc private func clicked(_ sender: Any?) { - action?() - } -} - -/// The floating banner: a rounded, translucent capsule with one line of text. -final class BannerView: NSVisualEffectView { - private let label = NSTextField(labelWithString: "") - - var text: String { - get { label.stringValue } - set { label.stringValue = newValue } - } - - override init(frame frameRect: NSRect) { - super.init(frame: frameRect) - material = .hudWindow - blendingMode = .withinWindow - state = .active - wantsLayer = true - layer?.cornerRadius = 10 - layer?.masksToBounds = true - label.font = .systemFont(ofSize: 12, weight: .medium) - label.lineBreakMode = .byTruncatingMiddle - label.translatesAutoresizingMaskIntoConstraints = false - addSubview(label) - NSLayoutConstraint.activate([ - label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 14), - label.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -14), - label.topAnchor.constraint(equalTo: topAnchor, constant: 7), - label.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -7), - ]) - setAccessibilityRole(.staticText) - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("not used") - } -} diff --git a/swift/Sources/MicrohmApp/Model/AppModel.swift b/swift/Sources/MicrohmApp/Model/AppModel.swift deleted file mode 100644 index 67a62b3..0000000 --- a/swift/Sources/MicrohmApp/Model/AppModel.swift +++ /dev/null @@ -1,205 +0,0 @@ -import Foundation -import MicrohmCore -import MicrohmShared -import MicrohmTerminal - -/// Everything the window needs from the session daemon, the launcher, the MCP stack and -/// the phone page, as one seam. This protocol and its implementations (in this folder) are -/// the only code in the app that touches `control/`, `session/`, `daemon/`, `mcp/`, -/// `mcphost/` and `phone/` — the window, dialogs and status item only ever see -/// `AppModel`. Every call here may block (socket round trips, process launches): callers -/// run them off the main thread. -/// -/// Error semantics mirror Java's `SessionHost`: "no server running" is not an error for -/// `listSessions` (empty) and `hasSession` (false); everything else throws with a -/// message fit for the user. -protocol SessionBackend: StatusSessionHost { - - /// Short description for the About panel and the log. - var name: String { get } - - func listSessions() throws -> [String] - func killSession(_ session: String) throws - - /// Opens an attach stream to `session` at the given grid size. - func attach(_ session: String, columns: Int, rows: Int) throws -> TerminalTransport - - /// Creates and registers a new session; returns its session name. `firstMessage`, when - /// present, is typed into the agent once it is ready at its prompt (the phone page's - /// and MCP spawn's "prompt"). - func create(projectPath: URL, harness: HarnessType, resumeId: String?, displayName: String?, - firstMessage: String?, onNoResumeSyntax: @escaping () -> Void) throws -> String - - /// Starts a fresh daemon session under a dead row's name and relaunches its harness. - func resume(_ entry: SessionEntry, onNoResumeSyntax: @escaping () -> Void) throws - - /// Deletes a gone session's MCP config file (its copy of the token). - func discardMcpConfig(_ session: String) - - // MCP server - var mcpRunning: Bool { get } - func startMcp(port: Int, token: String) throws - func stopMcp() - - // phone page - var phoneRunning: Bool { get } - func startPhone(port: Int, token: String) throws - func stopPhone() - func phoneLink(port: Int, token: String) -> String - - /// Sessions created or killed outside the window (MCP agents, the phone page). The - /// callbacks may fire on any thread. - func setEventHandlers(changed: @escaping (String?) -> Void, killed: @escaping (String) -> Void, - runEnded: @escaping (String) -> Void) - - /// The New dialog's "Shell:" line, and Settings' shell choices. - func describeShell(_ setting: String) -> String - func installedShells() -> [(value: String, label: String)] - - /// Demo backends pin each session's state so screenshots show every badge; real - /// backends return nil and the status poller decides. - func fixedClassification(_ session: String) -> Classification? - - /// The app is quitting: stop serving and hand off to the background host if needed. - func shutdown() -} - -extension SessionBackend { - func fixedClassification(_ session: String) -> Classification? { nil } -} - -/// The app's model: the session registry (real, from `MicrohmCore`) and the backend -/// seam. Created once in `AppDelegate`. -final class AppModel: @unchecked Sendable { - - static let appName = "Microhm" - - let registry: SessionRegistry - let backend: SessionBackend - let usage: HarnessUsageService - - init(registry: SessionRegistry, backend: SessionBackend, usage: HarnessUsageService = HarnessUsageService()) { - self.registry = registry - self.backend = backend - self.usage = usage - } - - /// Picks the backend: `MICROHM_DEMO=1` for the canned demo sessions (screenshots, - /// UI work without a daemon); otherwise the real daemon stack once it is linked in, - /// and until then a stand-in that reports the daemon unavailable. - static func makeDefault() -> AppModel { - let registry = SessionRegistry.load() - let env = ProcessInfo.processInfo.environment - if env["MICROHM_DEMO"] == "1" { - return AppModel(registry: registry, backend: DemoBackend(registry: registry), - usage: HarnessUsageService(loader: DemoBackend.usage)) - } - return AppModel(registry: registry, backend: CoreBackendFactory.make(registry: registry)) - } - - /// Whether `ui.theme` is set explicitly; unset, the app follows the system live. - static func hasExplicitSetting(_ key: String) -> Bool { - guard let text = try? String(contentsOf: AppSettings.settingsFile(), encoding: .isoLatin1) else { - return false - } - for raw in text.split(whereSeparator: \.isNewline) { - let line = raw.trimmingCharacters(in: .whitespaces) - if line.hasPrefix("#") || line.hasPrefix("!") { continue } - if line.hasPrefix(key) { - let rest = line.dropFirst(key.count).trimmingCharacters(in: .whitespaces) - if rest.hasPrefix("=") || rest.hasPrefix(":") { return true } - } - } - return false - } -} - -/// A backend for when the daemon stack is not available in this build: the sidebar shows -/// the registry's sessions as dead (resumable once it is), and anything that needs the -/// daemon fails with a clear message instead of crashing. -final class UnavailableBackend: SessionBackend, @unchecked Sendable { - let reason: String - var name: String { "unavailable (\(reason))" } - - init(reason: String) { - self.reason = reason - } - - private func failure() -> Error { - AppError("The session daemon is not available in this build: \(reason)") - } - - func listSessions() throws -> [String] { [] } - func hasSession(_ session: String) throws -> Bool { false } - func sendKeys(_ session: String, _ command: String) throws { throw failure() } - func capture(_ session: String) throws -> Screen { Screen("", true, Date()) } - func killSession(_ session: String) throws { throw failure() } - func attach(_ session: String, columns: Int, rows: Int) throws -> TerminalTransport { throw failure() } - func create(projectPath: URL, harness: HarnessType, resumeId: String?, displayName: String?, - firstMessage: String?, onNoResumeSyntax: @escaping () -> Void) throws -> String { - throw failure() - } - func resume(_ entry: SessionEntry, onNoResumeSyntax: @escaping () -> Void) throws { throw failure() } - func discardMcpConfig(_ session: String) {} - var mcpRunning: Bool { false } - func startMcp(port: Int, token: String) throws { throw failure() } - func stopMcp() {} - var phoneRunning: Bool { false } - func startPhone(port: Int, token: String) throws { throw failure() } - func stopPhone() {} - func phoneLink(port: Int, token: String) -> String { PhoneLink.link(port: port, token: token) } - func setEventHandlers(changed: @escaping (String?) -> Void, killed: @escaping (String) -> Void, - runEnded: @escaping (String) -> Void) {} - func describeShell(_ setting: String) -> String { ShellChoices.describe(setting) } - func installedShells() -> [(value: String, label: String)] { ShellChoices.installed() } - func shutdown() {} -} - -/// A plain error with a user-facing message. -struct AppError: Error, LocalizedError, CustomStringConvertible { - let message: String - init(_ message: String) { self.message = message } - var description: String { message } - var errorDescription: String? { message } -} - -/// Java's `PhoneService.link`: `http://:/#`. Used by -/// backends that have no phone service of their own. -enum PhoneLink { - static func link(port: Int, token: String) -> String { - "http://\(lanAddress() ?? "localhost"):\(port)/#k=\(token)" - } - - /// The first non-loopback IPv4 address, preferring en0. - static func lanAddress() -> String? { - var addrs: UnsafeMutablePointer? - guard getifaddrs(&addrs) == 0, let first = addrs else { return nil } - defer { freeifaddrs(addrs) } - var candidates: [(String, String)] = [] - var cursor: UnsafeMutablePointer? = first - while let ifa = cursor { - defer { cursor = ifa.pointee.ifa_next } - guard let sa = ifa.pointee.ifa_addr, sa.pointee.sa_family == UInt8(AF_INET) else { continue } - let flags = Int32(ifa.pointee.ifa_flags) - guard flags & IFF_UP != 0, flags & IFF_LOOPBACK == 0 else { continue } - var host = [CChar](repeating: 0, count: Int(NI_MAXHOST)) - if getnameinfo(sa, socklen_t(sa.pointee.sa_len), &host, socklen_t(host.count), nil, 0, NI_NUMERICHOST) == 0 { - let name = String(cString: ifa.pointee.ifa_name) - candidates.append((name, String(cString: host))) - } - } - return (candidates.first { $0.0 == "en0" } ?? candidates.first)?.1 - } -} - -/// The shells a session can start in, as the core's `SessionShell` lists them. -enum ShellChoices { - static func describe(_ setting: String) -> String { - SessionShell.system().describe(setting) - } - - static func installed() -> [(value: String, label: String)] { - let shells = SessionShell.system() - return shells.installedNames().map { ($0, shells.displayName($0)) } - } -} diff --git a/swift/Sources/MicrohmApp/Model/CoreBackend.swift b/swift/Sources/MicrohmApp/Model/CoreBackend.swift deleted file mode 100644 index db0ceff..0000000 --- a/swift/Sources/MicrohmApp/Model/CoreBackend.swift +++ /dev/null @@ -1,111 +0,0 @@ -import Foundation -import MicrohmCore -import MicrohmShared -import MicrohmTerminal - -/// The daemon attachment is already push-style; it only needs to be named a transport. -extension SessionServerConnection: TerminalTransport {} - -/// Builds the real backend over the core's daemon stack. -enum CoreBackendFactory { - static func make(registry: SessionRegistry) -> SessionBackend { - CoreBackend(registry: registry, host: SessionServerHost.forDefaultHome()) - } -} - -/// The real backend (Java's wiring in `MicroHarnessManagerApp` and `MainWindow`): the -/// session daemon (`SessionServerHost`), and over it the `McpStack` — the launcher that -/// creates and resumes sessions, the session controller behind the MCP tools and the -/// phone page, the MCP service, the events agents' spawns and kills raise, and the phone -/// service. Only newSession ever spawns the daemon; with no daemon running every other call -/// answers "no sessions", so an app with no sessions costs nothing. -final class CoreBackend: SessionBackend, @unchecked Sendable { - var name: String { "daemon at \(MicrohmPaths.muxHome.path)" } - - private let registry: SessionRegistry - private let host: SessionServerHost - private let stack: McpStack - private var tokens: [SessionEvents.Token] = [] - private let tokensLock = NSLock() - - init(registry: SessionRegistry, host: SessionServerHost) { - self.registry = registry - self.host = host - self.stack = McpStack.create(registry, host) - // the phone page draws sessions in the app's own ANSI palette - PhoneService.palette = { StyledScreen.palette(AppSettings.terminalPalette()) } - } - - // StatusSessionHost - func hasSession(_ session: String) throws -> Bool { try host.hasSession(session) } - func sendKeys(_ session: String, _ command: String) throws { try host.sendKeys(session, command) } - func capture(_ session: String) throws -> Screen { try host.capture(session) } - - func listSessions() throws -> [String] { try host.listSessions() } - func killSession(_ session: String) throws { try host.killSession(session) } - - func attach(_ session: String, columns: Int, rows: Int) throws -> TerminalTransport { - try host.attachConnection(session, columns, rows) - } - - func create(projectPath: URL, harness: HarnessType, resumeId: String?, displayName: String?, - firstMessage: String?, onNoResumeSyntax: @escaping () -> Void) throws -> String { - guard let firstMessage, resumeId == nil else { - return try stack.launcher.create(projectPath, harness, resumeId, displayName, [:], - onNoResumeSyntax: onNoResumeSyntax) - } - // A first message goes through the controller's spawn, which types it in once the - // agent is ready at its prompt (the phone page's New does the same). - var args: [(String, CoreJSON)] = [("harness", .string(harness.id)), ("project", .string(projectPath.path)), - ("prompt", .string(firstMessage))] - if let displayName { - args.append(("name", .string(displayName))) - } - let result = stack.controller.call(nil, "spawn", CoreJSON.obj(args)) - if result.isError { - throw AppError(result.text) - } - // " started ( in )…" - return result.text.split(separator: " ").first.map(String.init) ?? "" - } - - func resume(_ entry: SessionEntry, onNoResumeSyntax: @escaping () -> Void) throws { - try stack.launcher.resume(entry, onNoResumeSyntax) - } - - func discardMcpConfig(_ session: String) { - stack.launcher.discardMcpConfig(session) - } - - var mcpRunning: Bool { stack.service.isRunning() } - func startMcp(port: Int, token: String) throws { try stack.service.start(port, token) } - func stopMcp() { stack.service.stop() } - - var phoneRunning: Bool { stack.phone.isRunning() } - func startPhone(port: Int, token: String) throws { try stack.phone.start(port, token) } - func stopPhone() { stack.phone.stop() } - func phoneLink(port: Int, token: String) -> String { PhoneService.link(port, token) } - - func setEventHandlers(changed: @escaping (String?) -> Void, killed: @escaping (String) -> Void, - runEnded: @escaping (String) -> Void) { - let events = stack.events - tokensLock.lock() - tokens.append(events.addSessionsChangedListener(changed)) - tokens.append(events.addSessionKilledListener(killed)) - tokens.append(events.addSessionRunEndedListener(runEnded)) - tokensLock.unlock() - } - - func describeShell(_ setting: String) -> String { ShellChoices.describe(setting) } - func installedShells() -> [(value: String, label: String)] { ShellChoices.installed() } - - /// Stops serving, then — however many sessions still run — hands MCP and the phone - /// page to the background host, which takes the registry until the app is back. - func shutdown() { - stack.service.stop() - stack.phone.stop() - if HostLauncher.launchIfNeeded(registry, host) { - Log.info("background host started for the sessions still running", tag: "app") - } - } -} diff --git a/swift/Sources/MicrohmApp/Model/DemoBackend.swift b/swift/Sources/MicrohmApp/Model/DemoBackend.swift deleted file mode 100644 index 6321c62..0000000 --- a/swift/Sources/MicrohmApp/Model/DemoBackend.swift +++ /dev/null @@ -1,261 +0,0 @@ -import Foundation -import MicrohmCore -import MicrohmTerminal - -/// Canned sessions for UI work and screenshots (`MICROHM_DEMO=1`): a few live sessions in -/// every state, one dead one, terminals that draw a plausible screen and echo typing. -/// Never starts a daemon or a process; its registry rows go to whatever `MICROHM_HOME` -/// points at. -final class DemoBackend: SessionBackend, @unchecked Sendable { - var name: String { "demo" } - - private let lock = NSLock() - private var live: [String: Classification?] = [:] - private let registry: SessionRegistry - private var mcpOn = false - private var phoneOn = false - private var changed: ((String?) -> Void)? - - init(registry: SessionRegistry) { - self.registry = registry - let home = NSHomeDirectory() - let microhm = home + "/Projects/gitlab/micro-harness-manager" - let site = home + "/Projects/site" - let notes = home + "/Documents/notes" - let api = home + "/Projects/api" - let seed: [(String, String, HarnessType, String?, Classification?, Bool)] = [ - ("mhm-micro-harness-manager", microhm, .claudeCode, "Port the AppKit UI", - Classification(.working, .high, "spinner on screen", .plugin), true), - ("mhm-micro-harness-manager-2", microhm, .codex, nil, - Classification(.waitingForInput, .high, "approval prompt", .plugin), true), - ("mhm-micro-harness-manager-3", microhm, .shell, nil, - Classification(.idle, .high, "shell prompt", .behavioral), true), - ("mhm-site", site, .claudeCode, "Landing page copy", - Classification(.idle, .medium, "quiet composer", .plugin), true), - ("mhm-notes", notes, .opencode, nil, nil, true), - ("mhm-api", api, .grok, "Rate limiter", nil, false), - ] - for (name, path, harness, display, state, isLive) in seed { - if registry.find(name) == nil { - let entry = SessionEntry.newlyCreated(name, path, harness, nil) - registry.put(display.map { entry.withDisplayName($0) } ?? entry) - } - if isLive { - live[name] = .some(state) - } - } - } - - func listSessions() throws -> [String] { - lock.lock(); defer { lock.unlock() } - return Array(live.keys) - } - - func hasSession(_ session: String) throws -> Bool { - lock.lock(); defer { lock.unlock() } - return live[session] != nil - } - - func sendKeys(_ session: String, _ command: String) throws {} - - func capture(_ session: String) throws -> Screen { - let alive = (try? hasSession(session)) ?? false - return Screen("$ ", !alive, Date(), "zsh", 1, "") - } - - func fixedClassification(_ session: String) -> Classification? { - lock.lock(); defer { lock.unlock() } - if let state = live[session] { return state } - return nil - } - - func killSession(_ session: String) throws { - lock.lock() - live[session] = nil - lock.unlock() - } - - func attach(_ session: String, columns: Int, rows: Int) throws -> TerminalTransport { - guard try hasSession(session) else { throw AppError("no session named \(session)") } - Thread.sleep(forTimeInterval: 0.15) // a daemon connect takes a moment - let harness = registry.find(session)?.harnessType ?? .shell - return DemoTransport(screen: DemoScreens.screen(for: harness, session: session)) - } - - func create(projectPath: URL, harness: HarnessType, resumeId: String?, displayName: String?, - firstMessage: String?, onNoResumeSyntax: @escaping () -> Void) throws -> String { - let name = try SessionNaming.deriveUnique(projectPath) { [self] candidate in - registry.find(candidate) != nil || ((try? hasSession(candidate)) ?? false) - } - let entry = SessionEntry.newlyCreated(name, projectPath.path, harness, resumeId) - registry.put(displayName.map { entry.withDisplayName($0) } ?? entry) - lock.lock() - live[name] = .some(nil) - lock.unlock() - return name - } - - func resume(_ entry: SessionEntry, onNoResumeSyntax: @escaping () -> Void) throws { - lock.lock() - live[entry.sessionName] = .some(Classification(.idle, .low, "resumed", .behavioral)) - lock.unlock() - } - - func discardMcpConfig(_ session: String) {} - - var mcpRunning: Bool { mcpOn } - func startMcp(port: Int, token: String) throws { mcpOn = true } - func stopMcp() { mcpOn = false } - - var phoneRunning: Bool { phoneOn } - func startPhone(port: Int, token: String) throws { phoneOn = true } - func stopPhone() { phoneOn = false } - func phoneLink(port: Int, token: String) -> String { PhoneLink.link(port: port, token: token) } - - func setEventHandlers(changed: @escaping (String?) -> Void, killed: @escaping (String) -> Void, - runEnded: @escaping (String) -> Void) { - self.changed = changed - } - - func describeShell(_ setting: String) -> String { ShellChoices.describe(setting) } - func installedShells() -> [(value: String, label: String)] { ShellChoices.installed() } - func shutdown() {} -} - -/// A transport that paints a canned screen, then echoes what is typed. -final class DemoTransport: TerminalTransport, @unchecked Sendable { - var onBytes: ((Data) -> Void)? - var onEnd: (() -> Void)? - private let screen: String - private var closed = false - - init(screen: String) { - self.screen = screen - } - - func start() { - let bytes = Data(screen.utf8) - DispatchQueue.global().asyncAfter(deadline: .now() + 0.05) { [weak self] in - self?.onBytes?(bytes) - } - } - - func send(_ bytes: Data) { - var echo = Data() - for byte in bytes { - switch byte { - case 0x0D: echo.append(contentsOf: [0x0D, 0x0A]) - case 0x7F: echo.append(contentsOf: [0x08, 0x20, 0x08]) - default: echo.append(byte) - } - } - onBytes?(echo) - } - - func resize(cols: Int, rows: Int) {} - - var isAlive: Bool { !closed } - - func close() { - closed = true - } -} - -enum DemoScreens { - private static let esc = "\u{1B}[" - - static func screen(for harness: HarnessType, session: String) -> String { - switch harness { - case .claudeCode: return claude - case .codex: return codex - default: return shell(session) - } - } - - private static var claude: String { - let o = esc + "38;5;209m", d = esc + "2m", r = esc + "0m", b = esc + "1m", g = esc + "32m" - return """ - \(o)╭───────────────────────────────────────────────╮\(r)\r - \(o)│\(r) \(o)✻\(r) Welcome to \(b)Claude Code\(r)! \(o)│\(r)\r - \(o)│\(r) \(o)│\(r)\r - \(o)│\(r) \(d)cwd: ~/Projects/gitlab/micro-harness-manager\(r)\(o)│\(r)\r - \(o)╰───────────────────────────────────────────────╯\(r)\r - \r - \(b)>\(r) Port the sidebar to an NSOutlineView source list\r - \r - \(g)⏺\(r) I'll start with the row view: avatar, name, path and badge.\r - \r - \(g)⏺\(r) \(b)Update\(r)(swift/Sources/MicrohmApp/Sidebar/SidebarCellView.swift)\r - ⎿ Updated with \(g)142 additions\(r) and \(esc)31m3 removals\(r)\r - \r - \(o)✶\(r) Compiling… \(d)(12s · ↓ 2.1k tokens · esc to interrupt)\(r)\r - \r - \(d)╭─────────────────────────────────────────────────────────╮\(r)\r - \(d)│\(r) > \(d)│\(r)\r - \(d)╰─────────────────────────────────────────────────────────╯\(r)\r - \(d)⏵⏵ accept edits on (shift+tab to cycle)\(r) - """ - } - - private static var codex: String { - let c = esc + "36m", d = esc + "2m", r = esc + "0m", b = esc + "1m", y = esc + "33m" - return """ - \(b)>_ OpenAI Codex\(r) \(d)(v0.58)\(r)\r - \r - \(c)model:\(r) gpt-5-codex \(d)/model to change\(r)\r - \(c)directory:\(r) ~/Projects/gitlab/micro-harness-manager\r - \r - \(b)▌\(r) Run the Swift test suite and fix what fails\r - \r - \(y)•\(r) Ran swift test --scratch-path .build-ui\r - └ \(d)Build complete! (41.2s)\(r)\r - \r - \(b)Allow command?\(r)\r - \(c)$ git checkout -- swift/Package.resolved\(r)\r - \r - \(b)› 1. Yes, proceed\(r)\r - 2. Yes, and don't ask again for this command\r - 3. No, and tell Codex what to do differently \(d)esc\(r)\r - \r - \(d)Press enter to confirm or esc to cancel\(r) - """ - } - - private static func shell(_ session: String) -> String { - let g = esc + "32m", bl = esc + "34m", d = esc + "2m", r = esc + "0m", b = esc + "1m" - return """ - \(d)Last login: Fri Nov 20 09:41:07 on ttys004\(r)\r - \(g)\(b)tester@m2air\(r) \(bl)micro-harness-manager\(r) % git status --short\r - M swift/Sources/microhm-mux/main.swift\r - ?? swift/Sources/MicrohmApp/\r - \(g)\(b)tester@m2air\(r) \(bl)micro-harness-manager\(r) % ls swift/Sources\r - \(bl)MicrohmApp\(r) \(bl)MicrohmMux\(r) \(bl)MicrohmShared\(r) \(bl)MicrohmVT\(r)\r - \(bl)MicrohmCore\(r) \(bl)MicrohmPTY\(r) \(bl)MicrohmTerminal\(r) \(bl)microhm-mux\(r)\r - \(g)\(b)tester@m2air\(r) \(bl)micro-harness-manager\(r) % - """ - } -} - -extension DemoBackend { - /// Canned budgets, so the demo never calls a provider's usage API (repeated launches - /// would get the real account rate-limited). Resets are relative to now. - @Sendable static func usage(_ harness: HarnessType) throws -> UsageSnapshot { - let now = Date() - func hours(_ h: Double) -> Date { now.addingTimeInterval(h * 3600) } - switch harness { - case .claudeCode: - return UsageSnapshot("Claude Code subscription", "Demo figures", [ - .init("Current session (5 hours)", 12, hours(3.4), nil), - .init("Current week (all models)", 41, hours(113.2), nil), - .init("Current week (Fable)", 8, hours(113.2), nil), - ], [.init("Extra usage", "Disabled")], nil) - case .codex: - return UsageSnapshot("Codex account", "Demo figures", [ - .init("Codex · 5 hours", 27, hours(1.6), nil), - .init("Codex · 1 week", 63, hours(52), nil), - ], [.init("Plan", "Plus")], nil) - default: - return try HarnessUsageService().load(harness) - } - } -} diff --git a/swift/Sources/MicrohmApp/Resources/app-icon.png b/swift/Sources/MicrohmApp/Resources/app-icon.png deleted file mode 100644 index d7f3286..0000000 Binary files a/swift/Sources/MicrohmApp/Resources/app-icon.png and /dev/null differ diff --git a/swift/Sources/MicrohmApp/Resources/provider-icons/NOTICE.md b/swift/Sources/MicrohmApp/Resources/provider-icons/NOTICE.md deleted file mode 100644 index aa4aa6b..0000000 --- a/swift/Sources/MicrohmApp/Resources/provider-icons/NOTICE.md +++ /dev/null @@ -1,36 +0,0 @@ -# AI provider marks - -These files retain the published geometry of the OpenAI, Anthropic, Cursor, Grok, OpenCode, Pi and Muse -marks, sourced through the `development-iconography` project and flattened -into a small, themeable SVG profile. OpenAI, Anthropic, and Cursor are -trademarks of their respective owners. The marks are included only to identify -the corresponding provider; inclusion does not imply endorsement or -affiliation. - -Geometry provenance: - -- OpenAI: the CC0-licensed Simple Icons OpenAI asset, checked against OpenAI's - published Blossom. -- Anthropic: Anthropic's first-party press kit. -- Cursor: Cursor's first-party brand assets; the 2D mark is used here. - -The source SVGs intentionally carry no literal fill. The app supplies its -current foreground colour so the marks retain contrast in light, dark, and -selected sidebar rows. - -Additional geometry sources: - -- Grok: its two-part symbol derives from https://grok.com/images/favicon.svg. -- OpenCode: https://opencode.ai/brand and the official asset at - https://github.com/anomalyco/opencode/blob/dev/packages/console/app/src/asset/brand/opencode-logo-light.svg. - Clip/mask scaffolding is removed; the shaded inset uses relative opacity so it - remains visible with the current foreground tint. -- Pi: the compact blocky mark supplied by the official https://pi.dev/press-kit, - from https://pi.dev/favicon.svg. -- Muse: the stylized m from - https://muse.ai/images/landing/brand/muse-logo.svg. Its published path is retained; - the source gradient is replaced by the host foreground, consistent with other - harness icons. This is the supplied visual identity for the Muse CLI entry. - -The added source view boxes include modest optical padding. Marks identify their -corresponding entries; they do not imply affiliation or endorsement. diff --git a/swift/Sources/MicrohmApp/Resources/provider-icons/anthropic.svg b/swift/Sources/MicrohmApp/Resources/provider-icons/anthropic.svg deleted file mode 100644 index a5d9580..0000000 --- a/swift/Sources/MicrohmApp/Resources/provider-icons/anthropic.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/swift/Sources/MicrohmApp/Resources/provider-icons/cursor.svg b/swift/Sources/MicrohmApp/Resources/provider-icons/cursor.svg deleted file mode 100644 index 66a6865..0000000 --- a/swift/Sources/MicrohmApp/Resources/provider-icons/cursor.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/swift/Sources/MicrohmApp/Resources/provider-icons/grok.svg b/swift/Sources/MicrohmApp/Resources/provider-icons/grok.svg deleted file mode 100644 index 67074b1..0000000 --- a/swift/Sources/MicrohmApp/Resources/provider-icons/grok.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/swift/Sources/MicrohmApp/Resources/provider-icons/muse.svg b/swift/Sources/MicrohmApp/Resources/provider-icons/muse.svg deleted file mode 100644 index 83e16b3..0000000 --- a/swift/Sources/MicrohmApp/Resources/provider-icons/muse.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/swift/Sources/MicrohmApp/Resources/provider-icons/openai.svg b/swift/Sources/MicrohmApp/Resources/provider-icons/openai.svg deleted file mode 100644 index 302d08f..0000000 --- a/swift/Sources/MicrohmApp/Resources/provider-icons/openai.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/swift/Sources/MicrohmApp/Resources/provider-icons/opencode.svg b/swift/Sources/MicrohmApp/Resources/provider-icons/opencode.svg deleted file mode 100644 index 27bcb60..0000000 --- a/swift/Sources/MicrohmApp/Resources/provider-icons/opencode.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/swift/Sources/MicrohmApp/Resources/provider-icons/pi.svg b/swift/Sources/MicrohmApp/Resources/provider-icons/pi.svg deleted file mode 100644 index 7b1086f..0000000 --- a/swift/Sources/MicrohmApp/Resources/provider-icons/pi.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/swift/Sources/MicrohmApp/Settings/SettingsResult.swift b/swift/Sources/MicrohmApp/Settings/SettingsResult.swift deleted file mode 100644 index 54504b3..0000000 --- a/swift/Sources/MicrohmApp/Settings/SettingsResult.swift +++ /dev/null @@ -1,80 +0,0 @@ -import Foundation -import MicrohmCore - -/// The Settings window's choices on Save (Java's `SettingsDialog.Result`). The window -/// never touches disk or a session itself: `AppDelegate` persists this and the main -/// window applies it. -struct SettingsResult { - var backgroundOverride: AppSettings.TerminalBackground? - var palette: AppSettings.TerminalPalette - var scrollbarHidden: Bool - var codexMouseWheelDisabled: Bool - var optionAsMeta: Bool - var pageKeys: Bool - var toolbarLabels: Bool - var toolbarPageButtons: Bool - var toolbarStopLadder: Bool - var toolbarBatchActions: Bool - var sidebarBackground: AppSettings.SidebarBackground - var rightPaneMatchesSidebar: Bool - var sidebarReticule: Bool - var sidebarFolderGroups: Bool - var fontFamily: String - var fontSize: Int - var statusPollingEnabled: Bool - var statusPollIntervalMs: Int - var activeTabPollMode: AppSettings.ActiveTabPollMode - var mcpServerEnabled: Bool - var mcpPort: Int - var mcpTokenRegenerated: Bool - var mcpChanged: Bool - var trayIcon: Bool - var sessionShell: String - var directLaunch: Bool - var mcpSessionLogs: Bool - var phoneServerEnabled: Bool - var phonePort: Int - - /// Whether Save must re-apply the MCP server: switched on or off, a new port while it - /// stays on, or a regenerated token (the running server must restart with it). - static func mcpChanged(wasEnabled: Bool, wasPort: Int, enabled: Bool, port: Int, tokenRegenerated: Bool) -> Bool { - enabled != wasEnabled || (enabled && port != wasPort) || tokenRegenerated - } - - /// Whether a Save applies the MCP server: an MCP change, or the server is meant to be - /// on but is not running (a bind that failed earlier is retried by any Save). - static func mcpNeedsApply(_ mcpChanged: Bool, enabled: Bool, running: Bool) -> Bool { - mcpChanged || (enabled && !running) - } - - /// Writes every choice, the way Java's Save does (one settings rewrite per key). Runs - /// on the settings queue, never the main thread. - func persist() { - AppSettings.saveTerminalBackgroundOverride(backgroundOverride) - AppSettings.saveTerminalPalette(palette) - AppSettings.saveTerminalScrollbarHidden(scrollbarHidden) - AppSettings.saveCodexMouseWheelDisabled(codexMouseWheelDisabled) - AppSettings.saveOptionAsMeta(optionAsMeta) - AppSettings.savePageKeys(pageKeys) - AppSettings.saveToolbarLabels(toolbarLabels) - AppSettings.saveToolbarPageButtons(toolbarPageButtons) - AppSettings.saveToolbarStopLadder(toolbarStopLadder) - AppSettings.saveToolbarBatchActions(toolbarBatchActions) - AppSettings.saveSidebarBackground(sidebarBackground) - AppSettings.saveRightPaneMatchesSidebar(rightPaneMatchesSidebar) - AppSettings.saveSidebarReticule(sidebarReticule) - AppSettings.saveSidebarFolderGroups(sidebarFolderGroups) - AppSettings.saveTerminalFont(fontFamily, fontSize) - AppSettings.saveStatusPollIntervalMs(statusPollIntervalMs) - AppSettings.saveStatusPollingEnabled(statusPollingEnabled) - AppSettings.saveActiveTabPollMode(activeTabPollMode) - AppSettings.saveMcpServerEnabled(mcpServerEnabled) - AppSettings.saveMcpPort(mcpPort) - AppSettings.saveMcpSessionLogs(mcpSessionLogs) - AppSettings.saveTrayIconEnabled(trayIcon) - AppSettings.saveSessionShell(sessionShell) - AppSettings.saveDirectLaunch(directLaunch) - AppSettings.savePhoneServerEnabled(phoneServerEnabled) - AppSettings.savePhonePort(phonePort) - } -} diff --git a/swift/Sources/MicrohmApp/Settings/SettingsWindowController.swift b/swift/Sources/MicrohmApp/Settings/SettingsWindowController.swift deleted file mode 100644 index 68063a4..0000000 --- a/swift/Sources/MicrohmApp/Settings/SettingsWindowController.swift +++ /dev/null @@ -1,653 +0,0 @@ -import AppKit -import MicrohmCore - -/// Settings (Java's `SettingsDialog`): a window with toolbar tabs — Sessions, Look, -/// Input, Agents, Phone, Performance — seeded from the settings file on open. Save hands -/// the choices to `onSave`; Cancel (or closing the window) drops them. Tabs keep unsaved -/// edits while switching. -final class SettingsWindowController: NSWindowController, NSWindowDelegate { - - var onSave: ((SettingsResult) -> Void)? - /// The phone page link for the current port (the backend knows the address). - var phoneLink: ((Int) -> String)? - var shells: [(value: String, label: String)] = [] - var describeShell: ((String) -> String)? - - private let tabs = NSTabViewController() - - // Sessions - private let pollingBox = NSButton(checkboxWithTitle: "Poll sessions for their status badge", target: nil, action: nil) - private let pollInterval = NumberField(min: AppSettings.minStatusPollIntervalMs, max: AppSettings.maxStatusPollIntervalMs, step: 500) - private let activeTabPopup = NSPopUpButton() - private let shellPopup = NSPopUpButton() - private let directLaunchBox = NSButton(checkboxWithTitle: "Start agents in one step (zsh, bash, sh, fish)", target: nil, action: nil) - private let trayBox = NSButton(checkboxWithTitle: "Show a menu-bar icon with the running sessions", target: nil, action: nil) - // Look - private let sidebarBackgroundPopup = NSPopUpButton() - private let matchRightPaneBox = NSButton(checkboxWithTitle: "Match the right pane to the sidebar", target: nil, action: nil) - private let reticuleBox = NSButton(checkboxWithTitle: "Dither sessions that are not attached", target: nil, action: nil) - private let folderGroupsBox = NSButton(checkboxWithTitle: "Group same-folder sessions under one heading", target: nil, action: nil) - private let labelsBox = NSButton(checkboxWithTitle: "Show text labels under the icons", target: nil, action: nil) - private let pageButtonsBox = NSButton(checkboxWithTitle: "Page Up / Page Down", target: nil, action: nil) - private let stopLadderBox = NSButton(checkboxWithTitle: "Detach, Close, Kill, Close All", target: nil, action: nil) - private let batchBox = NSButton(checkboxWithTitle: "Batch Close, Remove Dead", target: nil, action: nil) - private let terminalBackgroundPopup = NSPopUpButton() - private let fontPopup = NSPopUpButton() - private let fontSize = NumberField(min: AppSettings.minTerminalFontSize, max: AppSettings.maxTerminalFontSize, step: 1) - private let palettePopup = NSPopUpButton() - private let scrollbarBox = NSButton(checkboxWithTitle: "Hide the scrollbar", target: nil, action: nil) - // Input - private let optionMetaBox = NSButton(checkboxWithTitle: "Use Option as Meta", target: nil, action: nil) - private let pageKeysBox = NSButton(checkboxWithTitle: "Page Up/Down and Home/End scroll the scrollback", target: nil, action: nil) - private let codexWheelBox = NSButton(checkboxWithTitle: "Don't send mouse wheel events to Codex", target: nil, action: nil) - // Agents - private let mcpBox = NSButton(checkboxWithTitle: "Let agents in its sessions list, read and drive other sessions", target: nil, action: nil) - private let mcpPort = NumberField(min: AppSettings.minMcpPort, max: AppSettings.maxMcpPort, step: 1, grouping: false) - private let regenerateButton = NSButton(title: "Regenerate Token", target: nil, action: nil) - private let sessionLogsBox = NSButton(checkboxWithTitle: "Keep a log of each session an agent reads, in its project", target: nil, action: nil) - // Phone - private let phoneBox = NSButton(checkboxWithTitle: "Serve a page phones on your network can use", target: nil, action: nil) - private let phonePort = NumberField(min: AppSettings.minMcpPort, max: AppSettings.maxMcpPort, step: 1, grouping: false) - private let qrView = NSImageView() - private let linkField = NSTextField(labelWithString: "") - private let copyLinkButton = NSButton(title: "Copy Link", target: nil, action: nil) - // Performance - private let perfGrid = NSGridView() - - private var mcpWasEnabled = false - private var mcpWasPort = 0 - private var regenerateToken = false - - init() { - let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 640, height: 470), - styleMask: [.titled, .closable], backing: .buffered, defer: true) - window.title = "Settings" - window.toolbarStyle = .preference - super.init(window: window) - window.delegate = self - buildTabs() - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("not used") - } - - /// Re-reads the settings file into every control, then shows the window. - func present() { - load() - if window?.isVisible != true { - window?.center() - } - showWindow(nil) - window?.makeKeyAndOrderFront(nil) - } - - // MARK: - building - - private func buildTabs() { - tabs.tabStyle = .toolbar - tabs.transitionOptions = [] - addTab("Sessions", "rectangle.stack", sessionsPage()) - addTab("Look", "paintpalette", lookPage()) - addTab("Input", "keyboard", inputPage()) - addTab("Agents", "point.3.connected.trianglepath.dotted", agentsPage()) - addTab("Phone", "iphone", phonePage()) - addTab("Performance", "speedometer", performancePage()) - - window?.contentViewController = tabs - } - - /// Each tab is its page over the shared footer (Save applies every tab), at one fixed - /// size so switching tabs never resizes the window. - private func addTab(_ label: String, _ symbol: String, _ view: NSView) { - let content = NSView() - let footer = footerBar() - for part in [view, footer] { - part.translatesAutoresizingMaskIntoConstraints = false - content.addSubview(part) - } - NSLayoutConstraint.activate([ - view.leadingAnchor.constraint(equalTo: content.leadingAnchor), - view.trailingAnchor.constraint(equalTo: content.trailingAnchor), - view.topAnchor.constraint(equalTo: content.topAnchor), - footer.topAnchor.constraint(equalTo: view.bottomAnchor), - footer.leadingAnchor.constraint(equalTo: content.leadingAnchor), - footer.trailingAnchor.constraint(equalTo: content.trailingAnchor), - footer.bottomAnchor.constraint(equalTo: content.bottomAnchor), - content.widthAnchor.constraint(equalToConstant: 660), - content.heightAnchor.constraint(equalToConstant: 520), - ]) - let controller = NSViewController() - controller.view = content - controller.title = label - let item = NSTabViewItem(viewController: controller) - item.label = label - item.image = HarnessIcons.symbol(symbol, label) - tabs.addTabViewItem(item) - } - - private func footerBar() -> NSView { - let hint = NSTextField(labelWithString: "Save applies changes from every tab.") - hint.font = .systemFont(ofSize: NSFont.smallSystemFontSize) - hint.textColor = .tertiaryLabelColor - hint.toolTip = AppSettings.settingsFile().path - let cancel = NSButton(title: "Cancel", target: self, action: #selector(cancel(_:))) - cancel.keyEquivalent = "\u{1b}" - let save = NSButton(title: "Save", target: self, action: #selector(save(_:))) - save.keyEquivalent = "\r" - let stack = NSStackView(views: [hint, NSView(), cancel, save]) - stack.spacing = 10 - stack.edgeInsets = NSEdgeInsets(top: 12, left: 20, bottom: 16, right: 20) - let separator = NSBox() - separator.boxType = .separator - let wrapper = NSStackView(views: [separator, stack]) - wrapper.orientation = .vertical - wrapper.spacing = 0 - separator.widthAnchor.constraint(equalTo: wrapper.widthAnchor).isActive = true - stack.widthAnchor.constraint(equalTo: wrapper.widthAnchor).isActive = true - return wrapper - } - - /// One settings page: right-aligned labels, controls, small muted notes. - private func page(_ rows: [(String, NSView, [String])]) -> NSView { - let grid = NSGridView() - grid.rowSpacing = 8 - grid.columnSpacing = 12 - for (label, control, notes) in rows { - let title = NSTextField(labelWithString: label) - title.alignment = .right - let row = grid.addRow(with: [label.isEmpty ? NSGridCell.emptyContentView : title, control]) - if control is NSStackView && !(control is NumberField) { - // a group has no baseline of its own: line the label up with its top - row.rowAlignment = .none - row.yPlacement = .top - title.setContentHuggingPriority(.required, for: .vertical) - } - for note in notes { - let field = NSTextField(wrappingLabelWithString: note) - field.font = .systemFont(ofSize: NSFont.smallSystemFontSize) - field.textColor = .secondaryLabelColor - field.preferredMaxLayoutWidth = 400 - let noteRow = grid.addRow(with: [NSGridCell.emptyContentView, field]) - noteRow.topPadding = -4 - } - if let last = grid.row(at: grid.numberOfRows - 1) as NSGridRow? { - last.bottomPadding = 6 - } - } - grid.column(at: 0).xPlacement = .trailing - grid.column(at: 0).width = 150 - grid.column(at: 1).width = 410 - grid.rowAlignment = .firstBaseline - grid.translatesAutoresizingMaskIntoConstraints = false - let view = NSView() - view.addSubview(grid) - NSLayoutConstraint.activate([ - grid.topAnchor.constraint(equalTo: view.topAnchor, constant: 22), - grid.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: -10), - grid.bottomAnchor.constraint(lessThanOrEqualTo: view.bottomAnchor, constant: -16), - ]) - return view - } - - private func sessionsPage() -> NSView { - for (title, mode) in [("Off", AppSettings.ActiveTabPollMode.off), ("Once, on select", .once), - ("Scheduled while selected", .scheduled)] { - activeTabPopup.addItem(withTitle: title) - activeTabPopup.lastItem?.representedObject = mode.rawValue - } - pollingBox.target = self - pollingBox.action = #selector(updateEnabled(_:)) - activeTabPopup.target = self - activeTabPopup.action = #selector(updateEnabled(_:)) - shellPopup.target = self - shellPopup.action = #selector(shellChosen(_:)) - let interval = NSStackView(views: [pollInterval, NSTextField(labelWithString: "ms")]) - return page([ - ("Status polling:", pollingBox, ["Off freezes status badges and pane titles."]), - ("Poll interval:", interval, ["Milliseconds between status polls. Applies live."]), - ("Selected session:", activeTabPopup, ["While polling is off, keeps the selected session's badge fresh."]), - ("Shell:", shellPopup, ["For new sessions. Your default is your login shell."]), - ("Agent start:", directLaunchBox, ["On: the shell starts the agent itself, so nothing is typed during startup. Other shells always type it."]), - ("Menu bar:", trayBox, ["Shows how many sessions run and whether MCP is serving."]), - ]) - } - - private func lookPage() -> NSView { - for (title, value) in [("Translucent (system)", AppSettings.SidebarBackground.default), - ("Window gray", .uiGray), ("Black / white (follows appearance)", .terminal)] { - sidebarBackgroundPopup.addItem(withTitle: title) - sidebarBackgroundPopup.lastItem?.representedObject = value.rawValue - } - for (title, value) in [("Follow appearance", ""), ("Black", AppSettings.TerminalBackground.black.rawValue), - ("White", AppSettings.TerminalBackground.white.rawValue)] { - terminalBackgroundPopup.addItem(withTitle: title) - terminalBackgroundPopup.lastItem?.representedObject = value - } - for (title, value) in [("macOS Terminal", AppSettings.TerminalPalette.macosTerminal), ("iTerm2", .iterm2), - ("xterm", .xterm)] { - palettePopup.addItem(withTitle: title) - palettePopup.lastItem?.representedObject = value.rawValue - } - matchRightPaneBox.target = self - matchRightPaneBox.action = #selector(updateEnabled(_:)) - let font = NSStackView(views: [fontPopup, fontSize, NSTextField(labelWithString: "pt")]) - font.spacing = 6 - let groups = NSStackView(views: [pageButtonsBox, stopLadderBox, batchBox]) - groups.orientation = .vertical - groups.alignment = .leading - groups.spacing = 4 - return page([ - ("Sidebar:", sidebarBackgroundPopup, []), - ("", matchRightPaneBox, []), - ("", reticuleBox, []), - ("Folder groups:", folderGroupsBox, ["Applies while sorting by folder."]), - ("Toolbar:", labelsBox, []), - ("Toolbar groups:", groups, []), - ("Terminal background:", terminalBackgroundPopup, []), - ("Terminal font:", font, ["Applies live. ⌘+ and ⌘− resize it too."]), - ("ANSI palette:", palettePopup, ["The 16 base colours. Applies live, to open terminals too."]), - ("Scrollbar:", scrollbarBox, ["Applies to terminals attached from now on."]), - ]) - } - - private func inputPage() -> NSView { - page([ - ("Option key:", optionMetaBox, ["On: Option+letter is Meta (word motion, shortcuts).", - "Off: Option types accents and symbols (Option+e, e = é). Applies live."]), - ("Paging keys:", pageKeysBox, ["Off passes all four keys through to the program. Full-screen programs always get them."]), - ("Codex mouse wheel:", codexWheelBox, ["On by default. Applies live to Codex sessions."]), - ]) - } - - private func agentsPage() -> NSView { - mcpBox.target = self - mcpBox.action = #selector(updateEnabled(_:)) - regenerateButton.target = self - regenerateButton.action = #selector(regenerate(_:)) - let warning = NSTextField(wrappingLabelWithString: - "Turning this on lets every agent you start read and type into your other sessions, and start new ones (a shell included) in any folder. Leave it off for agents you would not give that.") - warning.font = .systemFont(ofSize: NSFont.smallSystemFontSize) - warning.textColor = .systemOrange - warning.preferredMaxLayoutWidth = 400 - return page([ - ("MCP server:", mcpBox, ["Off by default. Loopback only, token-protected; applies on Save.", - "New Claude Code and Codex sessions connect automatically."]), - ("", warning, []), - ("Port:", mcpPort, []), - ("Token:", regenerateButton, ["A new token restarts the server. Earlier sessions reconnect after Resume."]), - ("Session logs:", sessionLogsBox, ["Copies the sessions an agent reads into .microhm-sessions/ in its project, as plain text: for agents that cannot read outside it."]), - ]) - } - - private func phonePage() -> NSView { - phoneBox.target = self - phoneBox.action = #selector(updateEnabled(_:)) - phonePort.onChange = { [weak self] in self?.updatePhoneLink() } - copyLinkButton.target = self - copyLinkButton.action = #selector(copyLink(_:)) - qrView.imageScaling = .scaleProportionallyUpOrDown - qrView.translatesAutoresizingMaskIntoConstraints = false - qrView.widthAnchor.constraint(equalToConstant: 148).isActive = true - qrView.heightAnchor.constraint(equalToConstant: 148).isActive = true - qrView.wantsLayer = true - qrView.layer?.cornerRadius = 8 - qrView.layer?.masksToBounds = true - linkField.font = .monospacedSystemFont(ofSize: NSFont.smallSystemFontSize, weight: .regular) - linkField.textColor = .secondaryLabelColor - linkField.lineBreakMode = .byTruncatingMiddle - linkField.isSelectable = true - linkField.preferredMaxLayoutWidth = 240 - let hint = NSTextField(wrappingLabelWithString: "Point the phone's camera at the code, then tap the link it shows. Safari remembers it after that.") - hint.font = .systemFont(ofSize: NSFont.smallSystemFontSize) - hint.textColor = .secondaryLabelColor - hint.preferredMaxLayoutWidth = 240 - let side = NSStackView(views: [hint, linkField, copyLinkButton]) - side.orientation = .vertical - side.alignment = .leading - side.spacing = 8 - let link = NSStackView(views: [qrView, side]) - link.alignment = .top - link.spacing = 14 - return page([ - ("Phone page:", phoneBox, ["Off by default. Applies on Save and keeps running after you quit."]), - ("Port:", phonePort, []), - ("Link:", link, ["Anyone with the link can type into your sessions, shells included. Plain HTTP, meant for a home network or a VPN such as Tailscale."]), - ]) - } - - private func performancePage() -> NSView { - perfGrid.rowSpacing = 6 - perfGrid.columnSpacing = 14 - let refresh = NSButton(title: "Refresh", target: self, action: #selector(refreshPerformance(_:))) - let copy = NSButton(title: "Copy", target: self, action: #selector(copyPerformance(_:))) - copy.toolTip = "Copy these figures as text, for a bug report" - let buttons = NSStackView(views: [refresh, copy]) - let note = NSTextField(labelWithString: "Figures for this run of the app. Nothing here is a setting.") - note.font = .systemFont(ofSize: NSFont.smallSystemFontSize) - note.textColor = .secondaryLabelColor - let stack = NSStackView(views: [perfGrid, note, buttons]) - stack.orientation = .vertical - stack.alignment = .leading - stack.spacing = 14 - stack.translatesAutoresizingMaskIntoConstraints = false - let view = NSView() - view.addSubview(stack) - NSLayoutConstraint.activate([ - stack.topAnchor.constraint(equalTo: view.topAnchor, constant: 22), - stack.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 60), - ]) - refreshPerformance(nil) - return view - } - - // MARK: - load / save - - private func load() { - pollingBox.state = AppSettings.statusPollingEnabled() ? .on : .off - pollInterval.value = AppSettings.statusPollIntervalMs() - select(activeTabPopup, AppSettings.activeTabPollMode().rawValue) - loadShells() - directLaunchBox.state = AppSettings.directLaunch() ? .on : .off - trayBox.state = AppSettings.trayIconEnabled() ? .on : .off - - select(sidebarBackgroundPopup, MainWindowController.effectiveSidebarBackground().rawValue) - matchRightPaneBox.state = AppSettings.rightPaneMatchesSidebar() ? .on : .off - reticuleBox.state = AppSettings.sidebarReticule() ? .on : .off - folderGroupsBox.state = AppSettings.sidebarFolderGroups() ? .on : .off - labelsBox.state = AppSettings.toolbarLabels() ? .on : .off - pageButtonsBox.state = AppSettings.toolbarPageButtons() ? .on : .off - stopLadderBox.state = AppSettings.toolbarStopLadder() ? .on : .off - batchBox.state = AppSettings.toolbarBatchActions() ? .on : .off - select(terminalBackgroundPopup, AppSettings.terminalBackgroundOverride()?.rawValue ?? "") - loadFonts(AppSettings.terminalFontFamily()) - fontSize.value = AppSettings.terminalFontSize() - select(palettePopup, AppSettings.terminalPalette().rawValue) - scrollbarBox.state = AppSettings.terminalScrollbarHidden() ? .on : .off - - optionMetaBox.state = AppSettings.optionAsMeta() ? .on : .off - pageKeysBox.state = AppSettings.pageKeys() ? .on : .off - codexWheelBox.state = AppSettings.codexMouseWheelDisabled() ? .on : .off - - mcpWasEnabled = AppSettings.mcpServerEnabled() - mcpWasPort = AppSettings.mcpPort() - mcpBox.state = mcpWasEnabled ? .on : .off - mcpPort.value = mcpWasPort - regenerateToken = false - regenerateButton.title = "Regenerate Token" - regenerateButton.isEnabled = true - sessionLogsBox.state = AppSettings.mcpSessionLogs() ? .on : .off - - phoneBox.state = AppSettings.phoneServerEnabled() ? .on : .off - phonePort.value = AppSettings.phonePort() - updatePhoneLink() - updateEnabled(nil) - refreshPerformance(nil) - } - - private func select(_ popup: NSPopUpButton, _ raw: String) { - if let item = popup.itemArray.first(where: { ($0.representedObject as? String) == raw }) { - popup.select(item) - } - } - - private func loadShells() { - shellPopup.removeAllItems() - let current = AppSettings.sessionShell() - shellPopup.addItem(withTitle: describeShell?("") ?? "Your default") - shellPopup.lastItem?.representedObject = "" - for shell in shells { - shellPopup.addItem(withTitle: shell.label) - shellPopup.lastItem?.representedObject = shell.value - } - if !current.isEmpty, !shellPopup.itemArray.contains(where: { ($0.representedObject as? String) == current }) { - shellPopup.addItem(withTitle: describeShell?(current) ?? current) - shellPopup.lastItem?.representedObject = current - } - shellPopup.menu?.addItem(.separator()) - shellPopup.addItem(withTitle: "Other…") - shellPopup.lastItem?.representedObject = nil - select(shellPopup, current) - } - - private var lastShellIndex = 0 - - @objc private func shellChosen(_ sender: NSPopUpButton) { - guard sender.selectedItem?.representedObject == nil, let window else { - lastShellIndex = sender.indexOfSelectedItem - return - } - let panel = NSOpenPanel() - panel.directoryURL = URL(fileURLWithPath: "/bin") - panel.message = "Choose a shell" - panel.canChooseFiles = true - panel.canChooseDirectories = false - panel.beginSheetModal(for: window) { [weak self] response in - guard let self else { return } - if response == .OK, let path = panel.url?.path { - let index = max(0, self.shellPopup.numberOfItems - 2) - self.shellPopup.insertItem(withTitle: self.describeShell?(path) ?? path, at: index) - self.shellPopup.item(at: index)?.representedObject = path - self.shellPopup.selectItem(at: index) - self.lastShellIndex = index - } else { - self.shellPopup.selectItem(at: self.lastShellIndex) - } - } - } - - private func loadFonts(_ current: String) { - fontPopup.removeAllItems() - let manager = NSFontManager.shared - let fixed = Set(manager.availableFontNames(with: .fixedPitchFontMask) ?? []) - var families = manager.availableFontFamilies.filter { family in - (manager.availableMembers(ofFontFamily: family) ?? []).contains { member in - (member.first as? String).map(fixed.contains) ?? false - } - } - // a family from a hand-edited file is kept even when not installed - if !families.contains(current) { - families.insert(current, at: 0) - } - for family in families.sorted() { - fontPopup.addItem(withTitle: family) - if let font = NSFont(name: family, size: 13) { - fontPopup.lastItem?.attributedTitle = NSAttributedString(string: family, attributes: [.font: font]) - } - } - fontPopup.selectItem(withTitle: current) - } - - @objc private func updateEnabled(_ sender: Any?) { - let polling = pollingBox.state == .on - let scheduled = (activeTabPopup.selectedItem?.representedObject as? String) == AppSettings.ActiveTabPollMode.scheduled.rawValue - pollInterval.isEnabled = polling || scheduled - activeTabPopup.isEnabled = !polling - terminalBackgroundPopup.isEnabled = matchRightPaneBox.state == .off - || (sidebarBackgroundPopup.selectedItem?.representedObject as? String) == AppSettings.SidebarBackground.default.rawValue - let mcp = mcpBox.state == .on - mcpPort.isEnabled = mcp - sessionLogsBox.isEnabled = mcp - let phone = phoneBox.state == .on - phonePort.isEnabled = true - qrView.alphaValue = phone ? 1 : 0.35 - } - - @objc private func regenerate(_ sender: Any?) { - // regenerated on Save, not on click, so Cancel really cancels - regenerateToken = true - regenerateButton.title = "Token Regenerates on Save" - regenerateButton.isEnabled = false - } - - private func updatePhoneLink() { - let link = phoneLink?(phonePort.value) ?? "" - linkField.stringValue = link - linkField.toolTip = link - qrView.image = QRCode.image(link, scale: 6) - copyLinkButton.title = "Copy Link" - } - - @objc private func copyLink(_ sender: Any?) { - NSPasteboard.general.clearContents() - NSPasteboard.general.setString(linkField.stringValue, forType: .string) - copyLinkButton.title = "Copied" - } - - @objc private func refreshPerformance(_ sender: Any?) { - let rows = PerfStats.snapshot() - // same rows as last time: update the values in place - if perfGrid.numberOfRows == rows.count, perfGrid.numberOfColumns == 2 { - for (i, row) in rows.enumerated() { - (perfGrid.cell(atColumnIndex: 0, rowIndex: i).contentView as? NSTextField)?.stringValue = row.label + ":" - (perfGrid.cell(atColumnIndex: 1, rowIndex: i).contentView as? NSTextField)?.stringValue = row.value - } - return - } - // removeRow leaves the row's views in the grid, drawn over the new ones - while perfGrid.numberOfRows > 0 { - for c in 0.. 0 { - perfGrid.column(at: 0).xPlacement = .trailing - } - } - - @objc private func copyPerformance(_ sender: Any?) { - NSPasteboard.general.clearContents() - NSPasteboard.general.setString(PerfStats.asText(PerfStats.snapshot()), forType: .string) - } - - /// ⌘W closes this window (in the main window it closes the selected session). - @objc func closeSession(_ sender: Any?) { - window?.performClose(sender) - } - - @objc private func cancel(_ sender: Any?) { - window?.close() - } - - @objc private func save(_ sender: Any?) { - window?.makeFirstResponder(nil) // commit a field still being edited - let mcpEnabled = mcpBox.state == .on - let port = AppSettings.clampMcpPort(mcpPort.value) - let result = SettingsResult( - backgroundOverride: (terminalBackgroundPopup.selectedItem?.representedObject as? String) - .flatMap { AppSettings.TerminalBackground(rawValue: $0) }, - palette: (palettePopup.selectedItem?.representedObject as? String) - .flatMap { AppSettings.TerminalPalette(rawValue: $0) } ?? .macosTerminal, - scrollbarHidden: scrollbarBox.state == .on, - codexMouseWheelDisabled: codexWheelBox.state == .on, - optionAsMeta: optionMetaBox.state == .on, - pageKeys: pageKeysBox.state == .on, - toolbarLabels: labelsBox.state == .on, - toolbarPageButtons: pageButtonsBox.state == .on, - toolbarStopLadder: stopLadderBox.state == .on, - toolbarBatchActions: batchBox.state == .on, - sidebarBackground: (sidebarBackgroundPopup.selectedItem?.representedObject as? String) - .flatMap { AppSettings.SidebarBackground(rawValue: $0) } ?? .default, - rightPaneMatchesSidebar: matchRightPaneBox.state == .on, - sidebarReticule: reticuleBox.state == .on, - sidebarFolderGroups: folderGroupsBox.state == .on, - fontFamily: fontPopup.titleOfSelectedItem ?? AppSettings.terminalFontFamily(), - fontSize: AppSettings.clampTerminalFontSize(fontSize.value), - statusPollingEnabled: pollingBox.state == .on, - statusPollIntervalMs: AppSettings.clampStatusPollIntervalMs(pollInterval.value), - activeTabPollMode: (activeTabPopup.selectedItem?.representedObject as? String) - .flatMap { AppSettings.ActiveTabPollMode(rawValue: $0) } ?? .once, - mcpServerEnabled: mcpEnabled, - mcpPort: port, - mcpTokenRegenerated: regenerateToken, - mcpChanged: SettingsResult.mcpChanged(wasEnabled: mcpWasEnabled, wasPort: mcpWasPort, enabled: mcpEnabled, - port: port, tokenRegenerated: regenerateToken), - trayIcon: trayBox.state == .on, - sessionShell: shellPopup.selectedItem?.representedObject as? String ?? "", - directLaunch: directLaunchBox.state == .on, - mcpSessionLogs: sessionLogsBox.state == .on, - phoneServerEnabled: phoneBox.state == .on, - phonePort: AppSettings.clampMcpPort(phonePort.value)) - onSave?(result) - window?.close() - } -} - -/// An integer field with a stepper, clamped to its range. -final class NumberField: NSStackView, NSTextFieldDelegate { - private let field = NSTextField() - private let stepper = NSStepper() - private let min: Int - private let max: Int - var onChange: (() -> Void)? - - init(min: Int, max: Int, step: Int, grouping: Bool = true) { - self.min = min - self.max = max - super.init(frame: .zero) - let formatter = NumberFormatter() - formatter.numberStyle = .decimal - formatter.usesGroupingSeparator = grouping - formatter.minimum = NSNumber(value: min) - formatter.maximum = NSNumber(value: max) - formatter.allowsFloats = false - field.formatter = formatter - field.alignment = .right - field.delegate = self - field.translatesAutoresizingMaskIntoConstraints = false - field.widthAnchor.constraint(equalToConstant: 72).isActive = true - stepper.minValue = Double(min) - stepper.maxValue = Double(max) - stepper.increment = Double(step) - stepper.valueWraps = false - stepper.target = self - stepper.action = #selector(stepped(_:)) - addArrangedSubview(field) - addArrangedSubview(stepper) - spacing = 2 - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("not used") - } - - var value: Int { - get { Swift.max(min, Swift.min(max, field.integerValue)) } - set { - let clamped = Swift.max(min, Swift.min(max, newValue)) - field.integerValue = clamped - stepper.integerValue = clamped - } - } - - var isEnabled: Bool { - get { field.isEnabled } - set { - field.isEnabled = newValue - stepper.isEnabled = newValue - } - } - - @objc private func stepped(_ sender: NSStepper) { - field.integerValue = sender.integerValue - onChange?() - } - - func controlTextDidChange(_ obj: Notification) { - stepper.integerValue = field.integerValue - onChange?() - } -} diff --git a/swift/Sources/MicrohmApp/Sidebar/HarnessBudgetPanel.swift b/swift/Sources/MicrohmApp/Sidebar/HarnessBudgetPanel.swift deleted file mode 100644 index 4d1814b..0000000 --- a/swift/Sources/MicrohmApp/Sidebar/HarnessBudgetPanel.swift +++ /dev/null @@ -1,373 +0,0 @@ -import AppKit -import MicrohmCore - -/// Harness-level provider quota summary shown below the session list (Java's -/// `HarnessBudgetPanel`): for each harness with a live session, how much of its session -/// and weekly budget is left, and how long until each resets. -final class HarnessBudgetPanel: NSView { - - struct Budget: Equatable { - let availablePercent: Int - let description: String - let resetsAt: Date? - } - - struct Summary: Equatable { - let session: Budget? - let week: Budget? - let fable: Budget? - let credits: Budget? - } - - struct Reset: Equatable { - let value: String - let remainingPercent: Int - let tooltip: String - } - - private static let weekSeconds: Double = 7 * 86_400 - private static let sessionSeconds: Double = 5 * 3600 - - var onRefresh: (() -> Void)? - - private let content = NSStackView() - private let headingButton = NSButton() - /// One line of what is left, shown in the header while the panel is collapsed. - private let collapsedSummary = NSTextField(labelWithString: "") - private static let collapsedKey = "MicrohmBudgetsCollapsed" - private var collapsed = UserDefaults.standard.bool(forKey: HarnessBudgetPanel.collapsedKey) { - didSet { UserDefaults.standard.set(collapsed, forKey: HarnessBudgetPanel.collapsedKey) } - } - private let refreshButton = NSButton() - private var active: [HarnessType] = [] - private var snapshots: [HarnessType: UsageSnapshot] = [:] - private var errors: [HarnessType: String] = [:] - private var loading: Set = [] - var now: () -> Date = Date.init - - override init(frame frameRect: NSRect) { - super.init(frame: frameRect) - // the heading folds the panel away, for short windows and long session lists - headingButton.isBordered = false - headingButton.imagePosition = .imageTrailing - headingButton.imageHugsTitle = true - headingButton.target = self - headingButton.action = #selector(toggleCollapsed(_:)) - headingButton.setButtonType(.momentaryChange) - collapsedSummary.font = .monospacedDigitSystemFont(ofSize: 10, weight: .regular) - collapsedSummary.textColor = .tertiaryLabelColor - collapsedSummary.lineBreakMode = .byTruncatingTail - collapsedSummary.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) - refreshButton.bezelStyle = .accessoryBarAction - refreshButton.showsBorderOnlyWhileMouseInside = true - refreshButton.controlSize = .small - refreshButton.image = HarnessIcons.symbol("arrow.clockwise", "Update budgets", pointSize: 10) - refreshButton.imagePosition = .imageOnly - refreshButton.toolTip = "Update budgets" - refreshButton.target = self - refreshButton.action = #selector(refresh(_:)) - let header = NSStackView(views: [headingButton, collapsedSummary, NSView(), refreshButton]) - header.orientation = .horizontal - - content.orientation = .vertical - content.alignment = .leading - content.spacing = 8 - - let stack = NSStackView(views: [header, content]) - stack.orientation = .vertical - stack.alignment = .leading - stack.spacing = 4 - stack.edgeInsets = NSEdgeInsets(top: 6, left: 18, bottom: 10, right: 10) - stack.translatesAutoresizingMaskIntoConstraints = false - addSubview(stack) - NSLayoutConstraint.activate([ - stack.leadingAnchor.constraint(equalTo: leadingAnchor), - stack.trailingAnchor.constraint(equalTo: trailingAnchor), - stack.topAnchor.constraint(equalTo: topAnchor), - stack.bottomAnchor.constraint(equalTo: bottomAnchor), - header.widthAnchor.constraint(equalTo: stack.widthAnchor, constant: -28), - content.widthAnchor.constraint(equalTo: stack.widthAnchor, constant: -28), - ]) - render() - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("not used") - } - - @objc func toggleCollapsed(_ sender: Any?) { - collapsed.toggle() - render() - } - - private func updateHeading() { - let title = NSAttributedString(string: "Budgets", attributes: [ - .font: NSFont.systemFont(ofSize: 11, weight: .semibold), - .foregroundColor: NSColor.secondaryLabelColor, - ]) - headingButton.attributedTitle = title - headingButton.image = HarnessIcons.symbol(collapsed ? "chevron.right" : "chevron.down", - collapsed ? "Show budgets" : "Hide budgets", pointSize: 8, weight: .semibold) - headingButton.contentTintColor = .tertiaryLabelColor - headingButton.toolTip = collapsed ? "Show budgets" : "Hide budgets" - collapsedSummary.isHidden = !collapsed - // collapsed: each harness's session budget (else its week) in one line - collapsedSummary.stringValue = active.compactMap { harness -> String? in - guard let snapshot = snapshots[harness] else { return nil } - let summary = HarnessBudgetPanel.summarize(snapshot) - guard let budget = summary.session ?? summary.week else { return nil } - return "\(SidebarView.label(harness)) \(budget.availablePercent)%" - }.joined(separator: " · ") - } - - @objc private func refresh(_ sender: Any?) { - onRefresh?() - } - - /// Every harness except the plain shell has a provider budget. - static func budgetedHarnesses(_ harnesses: [HarnessType]) -> [HarnessType] { - harnesses.filter { $0 != .shell } - } - - func showLoading(_ harnesses: [HarnessType]) { - active = HarnessBudgetPanel.budgetedHarnesses(harnesses) - let keep = Set(active) - snapshots = snapshots.filter { keep.contains($0.key) } - errors = errors.filter { keep.contains($0.key) } - loading = keep - refreshButton.isEnabled = active.isEmpty - render() - } - - func showSnapshot(_ harness: HarnessType, _ snapshot: UsageSnapshot) { - guard active.contains(harness) else { return } - snapshots[harness] = snapshot - errors[harness] = nil - loading.remove(harness) - refreshButton.isEnabled = loading.isEmpty - render() - } - - func showError(_ harness: HarnessType, _ error: Error) { - guard active.contains(harness) else { return } - let message = (error as? LocalizedError)?.errorDescription ?? "\(error)" - // a failed refresh keeps the last figures on screen, marked as stale - errors[harness] = message.isEmpty ? "Usage unavailable" : message - loading.remove(harness) - refreshButton.isEnabled = loading.isEmpty - render() - } - - private func render() { - updateHeading() - content.arrangedSubviews.forEach { $0.removeFromSuperview() } - // emptied rather than hidden: a hidden arranged view loses its width constraint - if collapsed { return } - if active.isEmpty { - content.addArrangedSubview(muted("No budgets available.")) - return - } - for harness in active { - let row = harnessRow(harness) - content.addArrangedSubview(row) - row.widthAnchor.constraint(equalTo: content.widthAnchor).isActive = true - } - } - - private func harnessRow(_ harness: HarnessType) -> NSView { - let icon = NSImageView(image: HarnessIcons.image(harness, size: 13)) - icon.contentTintColor = .labelColor - let name = NSTextField(labelWithString: SidebarView.label(harness)) - name.font = .systemFont(ofSize: 12, weight: .semibold) - let title = NSStackView(views: [icon, name]) - title.spacing = 5 - if snapshots[harness] != nil, let error = errors[harness] { - // the last refresh failed; the figures below are from the one before - let stale = NSImageView(image: HarnessIcons.symbol("exclamationmark.triangle", "Stale", pointSize: 10)) - stale.contentTintColor = .tertiaryLabelColor - let tip = "Last refresh failed: \(error). Showing the earlier figures." - stale.toolTip = tip - name.toolTip = tip - title.addArrangedSubview(stale) - } - let rows = NSStackView(views: [title]) - rows.orientation = .vertical - rows.alignment = .leading - rows.spacing = 3 - rows.translatesAutoresizingMaskIntoConstraints = false - - if loading.contains(harness), snapshots[harness] == nil { - rows.addArrangedSubview(muted("Loading usage…")) - return rows - } - if snapshots[harness] == nil, let error = errors[harness] { - let label = muted("Usage unavailable") - label.toolTip = error - rows.addArrangedSubview(label) - return rows - } - guard let snapshot = snapshots[harness], !snapshot.limits.isEmpty else { - let label = muted("Provider limits unavailable") - label.toolTip = snapshots[harness]?.note - rows.addArrangedSubview(label) - return rows - } - let summary = HarnessBudgetPanel.summarize(snapshot) - let clock = now() - // one line per budget: what is left, and how long until it refills - if let session = summary.session { - let reset = HarnessBudgetPanel.sessionReset(session.resetsAt, clock) - addFull(rows, budgetRow(session, "Session", reset.map { "\($0.value) left" }, reset?.tooltip)) - } - if let week = summary.week { - let reset = HarnessBudgetPanel.weeklyReset(week.resetsAt, clock) - addFull(rows, budgetRow(week, "Week", reset.map { HarnessBudgetPanel.days($0.value) }, reset?.tooltip)) - } - if let fable = summary.fable { - addFull(rows, budgetRow(fable, "Fable", nil, nil)) - } - if let credits = summary.credits { - let reset = HarnessBudgetPanel.monthlyReset(clock) - addFull(rows, budgetRow(credits, "Credits", HarnessBudgetPanel.days(reset.value), reset.tooltip)) - } - return rows - } - - private func addFull(_ rows: NSStackView, _ row: NSView) { - rows.addArrangedSubview(row) - row.widthAnchor.constraint(equalTo: rows.widthAnchor).isActive = true - } - - private static func days(_ value: String) -> String { - value == "1" ? "1 day" : "\(value) days" - } - - private func budgetRow(_ budget: Budget, _ metric: String, _ reset: String?, _ resetTip: String?) -> NSView { - let metricField = NSTextField(labelWithString: metric) - metricField.font = .systemFont(ofSize: 11) - metricField.textColor = .secondaryLabelColor - metricField.translatesAutoresizingMaskIntoConstraints = false - metricField.widthAnchor.constraint(equalToConstant: 46).isActive = true - let bar = NSProgressIndicator() - bar.style = .bar - bar.isIndeterminate = false - bar.controlSize = .small - bar.minValue = 0 - bar.maxValue = 100 - bar.doubleValue = Double(max(0, min(100, budget.availablePercent))) - bar.setAccessibilityLabel("\(metric) budget available") - bar.translatesAutoresizingMaskIntoConstraints = false - bar.widthAnchor.constraint(greaterThanOrEqualToConstant: 40).isActive = true - bar.setContentHuggingPriority(.defaultLow, for: .horizontal) - let valueField = NSTextField(labelWithString: "\(budget.availablePercent)%") - valueField.font = .monospacedDigitSystemFont(ofSize: 11, weight: .medium) - valueField.alignment = .right - valueField.textColor = budget.availablePercent <= 10 ? .systemRed : (budget.availablePercent <= 25 ? .systemOrange : .labelColor) - valueField.translatesAutoresizingMaskIntoConstraints = false - valueField.widthAnchor.constraint(equalToConstant: 34).isActive = true - let resetField = NSTextField(labelWithString: reset ?? "") - resetField.font = .monospacedDigitSystemFont(ofSize: 10, weight: .regular) - resetField.textColor = .tertiaryLabelColor - resetField.alignment = .right - resetField.translatesAutoresizingMaskIntoConstraints = false - resetField.widthAnchor.constraint(equalToConstant: 64).isActive = true - let row = NSStackView(views: [metricField, bar, valueField, resetField]) - row.spacing = 6 - let tooltip = "\(budget.description) · \(budget.availablePercent)% available" + (resetTip.map { " · \($0)" } ?? "") - row.toolTip = tooltip - for view in row.arrangedSubviews { view.toolTip = tooltip } - return row - } - - private func muted(_ text: String) -> NSTextField { - let label = NSTextField(labelWithString: text) - label.font = .systemFont(ofSize: 11) - label.textColor = .tertiaryLabelColor - return label - } - - // MARK: - summary (ported as is) - - static func summarize(_ snapshot: UsageSnapshot) -> Summary { - let limits = snapshot.limits - let rateLimits = limits.filter { !isFable($0.label) && !isCredits($0.label) } - var session: Budget? - var week: Budget? - if !rateLimits.isEmpty { - let shortest = rateLimits.first { isShortWindow($0.label) } - ?? rateLimits.min { ($0.resetsAt ?? .distantFuture) < ($1.resetsAt ?? .distantFuture) } - session = shortest.map(availableBudget) - let longest = rateLimits.first { isAllModelsWeek($0.label) } - ?? rateLimits.first { isLongWindow($0.label) } - ?? rateLimits.max { ($0.resetsAt ?? .distantPast) < ($1.resetsAt ?? .distantPast) } - week = longest.map(availableBudget) - } - let fable = limits.first { isFable($0.label) }.map(availableBudget) - let credits = limits.first { isCredits($0.label) }.map(availableBudget) - return Summary(session: session, week: week, fable: fable, credits: credits) - } - - private static func availableBudget(_ limit: UsageSnapshot.Limit) -> Budget { - Budget(availablePercent: 100 - limit.usedPercent, description: limit.label, resetsAt: limit.resetsAt) - } - - private static func clampPercent(_ value: Double) -> Int { - max(0, min(100, Int(value.rounded()))) - } - - static func weeklyReset(_ reset: Date?, _ now: Date) -> Reset? { - guard let reset else { return nil } - let seconds = reset.timeIntervalSince(now).rounded(.down) - if seconds <= 0 { - return Reset(value: "0", remainingPercent: 0, tooltip: "Weekly reset due") - } - let days = max(1, Int((seconds + 86_399) / 86_400)) - return Reset(value: String(days), remainingPercent: clampPercent(seconds * 100 / weekSeconds), - tooltip: "\(days) \(days == 1 ? "day" : "days") until weekly reset") - } - - /// Anthropic's extra_usage credit window carries no reset timestamp, so this assumes - /// a calendar-month cycle (observed empirically: the account resets on the 1st). - static func monthlyReset(_ now: Date) -> Reset { - let calendar = Calendar.current - let startOfMonth = calendar.date(from: calendar.dateComponents([.year, .month], from: now)) ?? now - let nextMonth = calendar.date(byAdding: .month, value: 1, to: startOfMonth) ?? now.addingTimeInterval(30 * 86_400) - let seconds = max(0, nextMonth.timeIntervalSince(now)) - let days = max(1, Int((seconds + 86_399) / 86_400)) - let monthDays = calendar.range(of: .day, in: .month, for: now)?.count ?? 30 - return Reset(value: String(days), remainingPercent: clampPercent(seconds * 100 / Double(monthDays * 86_400)), - tooltip: "\(days) \(days == 1 ? "day" : "days") until monthly reset") - } - - static func sessionReset(_ reset: Date?, _ now: Date) -> Reset? { - guard let reset else { return nil } - let seconds = max(0, reset.timeIntervalSince(now).rounded(.down)) - let totalMinutes = Int(seconds) / 60 - // a day or more reads as days and hours, so a long window fits the column - let remaining = totalMinutes >= 24 * 60 - ? "\(totalMinutes / (24 * 60))d \((totalMinutes / 60) % 24)h" - : "\(totalMinutes / 60)h" + String(format: "%02d", totalMinutes % 60) + "m" - return Reset(value: remaining, remainingPercent: clampPercent(seconds * 100 / sessionSeconds), - tooltip: seconds == 0 ? "Session reset due" : "\(remaining) left in session") - } - - private static func isShortWindow(_ label: String) -> Bool { - let l = label.lowercased() - return l.contains("session") || l.contains("hour") || l.contains("minute") - } - - private static func isLongWindow(_ label: String) -> Bool { - let l = label.lowercased() - return l.contains("week") || l.contains("month") || l.contains("day") - } - - private static func isAllModelsWeek(_ label: String) -> Bool { - let l = label.lowercased() - return l.contains("all models") - || (isLongWindow(label) && !isFable(label) && !l.contains("opus") && !l.contains("sonnet")) - } - - private static func isFable(_ label: String) -> Bool { label.lowercased().contains("fable") } - private static func isCredits(_ label: String) -> Bool { label.lowercased().contains("credit") } -} diff --git a/swift/Sources/MicrohmApp/Sidebar/SidebarCellView.swift b/swift/Sources/MicrohmApp/Sidebar/SidebarCellView.swift deleted file mode 100644 index c72b0d1..0000000 --- a/swift/Sources/MicrohmApp/Sidebar/SidebarCellView.swift +++ /dev/null @@ -1,383 +0,0 @@ -import AppKit -import MicrohmCore - -/// Status colours shared by the sidebar badges, the status item and the batch lists -/// (Java's `SidebarCellRenderer.WORKING`/`WAITING`/`IDLE`, here the system's own greens -/// and oranges so they adapt to light, dark and increased contrast). -enum StatusColors { - static var working: NSColor { .systemGreen } - static var waiting: NSColor { .systemOrange } - static var idle: NSColor { .systemGray } -} - -/// A sidebar row, laid out like a macOS source list (Java's `SidebarCellRenderer`): -/// -/// - **Avatar** (left): the harness's mark on a soft rounded tile, with the session's -/// status as a presence badge on the tile's corner — green working (it breathes while -/// attached), orange waiting, gray idle, a hollow ring while the first poll is pending, -/// a cross for a dead session, whose whole avatar also fades. -/// - **Text** (middle): the session's name, and under it the project path in a muted, -/// smaller face, truncated from the left so the project folder survives. Inside a folder -/// group the path line is dropped (the group header carries it). -/// - **Attention pill** (right): shown only for a session waiting on the human, the one -/// state worth interrupting for. Everything calm stays quiet. -final class SidebarCellView: NSTableCellView { - - static let identifier = NSUserInterfaceItemIdentifier("SidebarCell") - - private let avatar = AvatarView() - private let nameField = NSTextField(labelWithString: "") - private let pathField = NSTextField(labelWithString: "") - private let pill = AttentionPill() - private let reticule = ReticuleView() - private var textStackTopToCenter: NSLayoutConstraint? - private var dead = false - - override init(frame frameRect: NSRect) { - super.init(frame: frameRect) - identifier = SidebarCellView.identifier - - nameField.font = .systemFont(ofSize: NSFont.systemFontSize) - nameField.lineBreakMode = .byTruncatingTail - nameField.cell?.truncatesLastVisibleLine = true - nameField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) - pathField.font = .systemFont(ofSize: NSFont.smallSystemFontSize) - pathField.textColor = .secondaryLabelColor - pathField.lineBreakMode = .byTruncatingHead - pathField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) - textField = nameField - - let lines = NSStackView(views: [nameField, pathField]) - lines.orientation = .vertical - lines.alignment = .leading - lines.spacing = 1 - lines.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) - - for view in [avatar, lines, pill, reticule] as [NSView] { - view.translatesAutoresizingMaskIntoConstraints = false - addSubview(view) - } - pill.setContentCompressionResistancePriority(.required, for: .horizontal) - pill.setContentHuggingPriority(.required, for: .horizontal) - NSLayoutConstraint.activate([ - avatar.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 2), - avatar.centerYAnchor.constraint(equalTo: centerYAnchor), - avatar.widthAnchor.constraint(equalToConstant: AvatarView.side), - avatar.heightAnchor.constraint(equalToConstant: AvatarView.side), - lines.leadingAnchor.constraint(equalTo: avatar.trailingAnchor, constant: 9), - lines.centerYAnchor.constraint(equalTo: centerYAnchor), - lines.trailingAnchor.constraint(lessThanOrEqualTo: pill.leadingAnchor, constant: -6), - pill.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -4), - pill.centerYAnchor.constraint(equalTo: centerYAnchor), - reticule.leadingAnchor.constraint(equalTo: leadingAnchor), - reticule.trailingAnchor.constraint(equalTo: trailingAnchor), - reticule.topAnchor.constraint(equalTo: topAnchor), - reticule.bottomAnchor.constraint(equalTo: bottomAnchor), - ]) - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("not used") - } - - func configure(_ entry: SidebarEntry, grouped: Bool, reticuleEnabled: Bool) { - dead = entry.status == .dead - nameField.stringValue = entry.displayName - pathField.stringValue = entry.abbreviatedPath - pathField.isHidden = grouped - toolTip = entry.tooltipText - - avatar.glyph = HarnessIcons.image(entry.harnessType, size: 16) - avatar.faded = dead - avatar.badge = AvatarView.Badge.of(entry) - avatar.pulsing = entry.status == .live && entry.isAttached && entry.state == .working - pill.isHidden = dead || entry.state != .waitingForInput - reticule.isHidden = !(reticuleEnabled && entry.status == .live && !entry.isAttached) - setAccessibilityLabel("\(entry.displayName), \(SidebarView.label(entry.harnessType)), \(entry.statusPhrase)") - applyColors() - } - - override var backgroundStyle: NSView.BackgroundStyle { - didSet { applyColors() } - } - - private func applyColors() { - let emphasized = backgroundStyle == .emphasized - nameField.textColor = emphasized ? .alternateSelectedControlTextColor : (dead ? .secondaryLabelColor : .labelColor) - pathField.textColor = emphasized ? NSColor.alternateSelectedControlTextColor.withAlphaComponent(0.75) : .secondaryLabelColor - avatar.emphasized = emphasized - pill.emphasized = emphasized - } -} - -/// The harness mark on a rounded tile, with the status badge on its corner. -final class AvatarView: NSView { - static let side: CGFloat = 28 - - enum Badge { - case working, waiting, idle, pending, dead - - static func of(_ entry: SidebarEntry) -> Badge { - if entry.status == .dead { return .dead } - switch entry.state { - case .working?: return .working - case .waitingForInput?: return .waiting - case .idle?: return .idle - case nil: return .pending - } - } - } - - var glyph: NSImage? { didSet { needsDisplay = true } } - var faded = false { didSet { needsDisplay = true } } - var emphasized = false { didSet { needsDisplay = true; updateBadge() } } - var badge: Badge = .pending { didSet { updateBadge() } } - var pulsing = false { - didSet { - if pulsing != oldValue { updatePulse() } - } - } - - private let badgeLayer = CAShapeLayer() - - override init(frame frameRect: NSRect) { - super.init(frame: frameRect) - wantsLayer = true - layer?.addSublayer(badgeLayer) - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("not used") - } - - override var isFlipped: Bool { true } - - override func layout() { - super.layout() - updateBadge() - } - - override func viewDidChangeEffectiveAppearance() { - super.viewDidChangeEffectiveAppearance() - updateBadge() - } - - override func viewDidMoveToWindow() { - super.viewDidMoveToWindow() - updatePulse() - } - - override func draw(_ dirtyRect: NSRect) { - let tile = bounds.insetBy(dx: 1, dy: 1) - let path = NSBezierPath(roundedRect: tile, xRadius: 7, yRadius: 7) - let base: NSColor = emphasized ? .alternateSelectedControlTextColor : .labelColor - base.withAlphaComponent(emphasized ? 0.2 : 0.08).setFill() - path.fill() - guard let glyph else { return } - let size: CGFloat = 16 - let rect = NSRect(x: tile.midX - size / 2, y: tile.midY - size / 2, width: size, height: size) - let tinted = NSImage(size: rect.size, flipped: false) { r in - glyph.draw(in: r) - base.set() - r.fill(using: .sourceAtop) - return true - } - tinted.draw(in: rect, from: .zero, operation: .sourceOver, fraction: faded ? 0.4 : 0.9, - respectFlipped: true, hints: nil) - } - - private func updateBadge() { - let diameter: CGFloat = 11 - // a flipped view's layer is geometry-flipped too: this is the bottom-right corner - CATransaction.begin() - CATransaction.setDisableActions(true) - defer { CATransaction.commit() } - badgeLayer.frame = CGRect(x: bounds.maxX - diameter + 2, y: bounds.maxY - diameter + 2, - width: diameter, height: diameter) - let ring: NSColor = emphasized ? .controlAccentColor : .windowBackgroundColor - var fill: NSColor = .clear - var stroke: NSColor = ring - var lineWidth: CGFloat = 2 - var path = CGPath(ellipseIn: CGRect(x: 1, y: 1, width: diameter - 2, height: diameter - 2), transform: nil) - effectiveAppearance.performAsCurrentDrawingAppearance { - switch badge { - case .working: - fill = StatusColors.working - case .waiting: - fill = StatusColors.waiting - case .idle: - fill = StatusColors.idle - case .pending: - fill = ring - stroke = StatusColors.idle - lineWidth = 1.6 - path = CGPath(ellipseIn: CGRect(x: 2, y: 2, width: diameter - 4, height: diameter - 4), transform: nil) - case .dead: - let cross = CGMutablePath() - cross.addEllipse(in: CGRect(x: 1, y: 1, width: diameter - 2, height: diameter - 2)) - fill = StatusColors.idle - path = cross - } - badgeLayer.path = path - badgeLayer.fillColor = fill.cgColor - badgeLayer.strokeColor = stroke.cgColor - badgeLayer.lineWidth = lineWidth - } - badgeLayer.sublayers?.forEach { $0.removeFromSuperlayer() } - if badge == .dead { - let x = CAShapeLayer() - let p = CGMutablePath() - let inset: CGFloat = 3.6 - p.move(to: CGPoint(x: inset, y: inset)) - p.addLine(to: CGPoint(x: diameter - inset, y: diameter - inset)) - p.move(to: CGPoint(x: diameter - inset, y: inset)) - p.addLine(to: CGPoint(x: inset, y: diameter - inset)) - x.path = p - x.lineWidth = 1.4 - x.lineCap = .round - effectiveAppearance.performAsCurrentDrawingAppearance { - x.strokeColor = NSColor.windowBackgroundColor.cgColor - } - badgeLayer.addSublayer(x) - } - } - - /// Only the attached working dot breathes — a veiled (not-attached) row keeps its dot - /// still, so the row reads as quiet. Core Animation drives it: no timer, no redraws. - private func updatePulse() { - badgeLayer.removeAnimation(forKey: "pulse") - guard pulsing, window != nil else { - badgeLayer.opacity = 1 - return - } - let animation = CABasicAnimation(keyPath: "opacity") - animation.fromValue = 1.0 - animation.toValue = 0.3 - animation.duration = 0.9 - animation.autoreverses = true - animation.repeatCount = .infinity - animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) - badgeLayer.add(animation, forKey: "pulse") - } -} - -/// "Waiting", as an amber pill: the one row state that asks for the human. -final class AttentionPill: NSView { - private let label = NSTextField(labelWithString: "Waiting") - var emphasized = false { didSet { needsDisplay = true; applyColors() } } - - override init(frame frameRect: NSRect) { - super.init(frame: frameRect) - label.font = .systemFont(ofSize: 10, weight: .semibold) - label.translatesAutoresizingMaskIntoConstraints = false - addSubview(label) - NSLayoutConstraint.activate([ - label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 7), - label.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -7), - label.topAnchor.constraint(equalTo: topAnchor, constant: 2), - label.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -2), - ]) - setAccessibilityElement(true) - setAccessibilityRole(.staticText) - setAccessibilityLabel("Waiting for input") - applyColors() - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("not used") - } - - private func applyColors() { - label.textColor = emphasized ? StatusColors.waiting : StatusColors.waiting - } - - override func draw(_ dirtyRect: NSRect) { - let path = NSBezierPath(roundedRect: bounds, xRadius: bounds.height / 2, yRadius: bounds.height / 2) - (emphasized ? NSColor.white : StatusColors.waiting.withAlphaComponent(0.18)).setFill() - path.fill() - } -} - -/// The screen door over a live row that is not attached yet (Settings → Look → -/// Reticule): every other pixel veiled in the window's background. -final class ReticuleView: NSView { - override func hitTest(_ point: NSPoint) -> NSView? { nil } - - override func draw(_ dirtyRect: NSRect) { - let scale = window?.backingScaleFactor ?? 2 - let step = 2 / scale * 1.0 - NSColor.windowBackgroundColor.withAlphaComponent(0.55).setFill() - var y = bounds.minY - var row = 0 - while y < bounds.maxY { - var x = bounds.minX + (row % 2 == 0 ? 0 : step) - while x < bounds.maxX { - NSRect(x: x, y: y, width: step, height: step).fill() - x += step * 2 - } - y += step - row += 1 - } - } -} - -/// A folder group's heading: the folder's name, its parent path muted, and the number of -/// sessions in it at the trailing edge. -final class FolderHeaderView: NSTableCellView { - static let identifier = NSUserInterfaceItemIdentifier("FolderHeader") - - private let icon = NSImageView() - private let folderField = NSTextField(labelWithString: "") - private let parentField = NSTextField(labelWithString: "") - private let countField = NSTextField(labelWithString: "") - - override init(frame frameRect: NSRect) { - super.init(frame: frameRect) - identifier = FolderHeaderView.identifier - icon.image = HarnessIcons.symbol("folder", "Folder", pointSize: 11, weight: .semibold) - icon.contentTintColor = .secondaryLabelColor - folderField.font = .systemFont(ofSize: 11, weight: .semibold) - folderField.textColor = .secondaryLabelColor - folderField.lineBreakMode = .byTruncatingTail - folderField.setContentCompressionResistancePriority(.defaultLow + 1, for: .horizontal) - parentField.font = .systemFont(ofSize: 11) - parentField.textColor = .tertiaryLabelColor - parentField.lineBreakMode = .byTruncatingHead - parentField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) - countField.font = .monospacedDigitSystemFont(ofSize: 11, weight: .regular) - countField.textColor = .tertiaryLabelColor - countField.setContentCompressionResistancePriority(.required, for: .horizontal) - textField = folderField - for view in [icon, folderField, parentField, countField] { - view.translatesAutoresizingMaskIntoConstraints = false - addSubview(view) - } - NSLayoutConstraint.activate([ - icon.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 2), - icon.centerYAnchor.constraint(equalTo: folderField.centerYAnchor), - folderField.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 5), - folderField.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -4), - parentField.leadingAnchor.constraint(equalTo: folderField.trailingAnchor, constant: 6), - parentField.firstBaselineAnchor.constraint(equalTo: folderField.firstBaselineAnchor), - parentField.trailingAnchor.constraint(lessThanOrEqualTo: countField.leadingAnchor, constant: -8), - countField.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -6), - countField.firstBaselineAnchor.constraint(equalTo: folderField.firstBaselineAnchor), - ]) - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("not used") - } - - func configure(_ group: FolderGroup) { - folderField.stringValue = group.folderName - parentField.stringValue = SidebarEntry.abbreviate(group.parentPath) - countField.stringValue = String(group.entries.count) - toolTip = SidebarEntry.abbreviate(group.path) - setAccessibilityLabel("\(group.folderName), \(group.entries.count) sessions") - } -} diff --git a/swift/Sources/MicrohmApp/Sidebar/SidebarModel.swift b/swift/Sources/MicrohmApp/Sidebar/SidebarModel.swift deleted file mode 100644 index c8cc5d3..0000000 --- a/swift/Sources/MicrohmApp/Sidebar/SidebarModel.swift +++ /dev/null @@ -1,340 +0,0 @@ -import Foundation -import MicrohmCore - -/// One row in the sidebar: a registered `SessionEntry`, live or dead (Java's `SidebarEntry`). -/// A class, not a struct: the status poller updates a row's state in place and the outline -/// view keeps object identity across reloads of a single row. -final class SidebarEntry { - - enum Status { case live, dead } - - let status: Status - let sessionEntry: SessionEntry - var sessionName: String { sessionEntry.sessionName } - var harnessType: HarnessType { sessionEntry.harnessType } - var isAttached = false - - /// Latest status-poll result. Nil until the first poll tick lands (or always, for - /// dead entries — those are never polled). - private(set) var state: SessionState? - /// Reason paired with `state`; nil exactly when the state is. - private(set) var stateReason: String? - - /// Latest pane title the harness set via OSC (e.g. Claude Code's /rename); empty - /// until a poll reports one. Kept even when a later poll reports none — a harness - /// mid-redraw must not make the name flicker off. - private(set) var paneTitle = "" - - private init(_ status: Status, _ entry: SessionEntry) { - self.status = status - self.sessionEntry = entry - } - - static func live(_ entry: SessionEntry) -> SidebarEntry { SidebarEntry(.live, entry) } - static func dead(_ entry: SessionEntry) -> SidebarEntry { SidebarEntry(.dead, entry) } - - func setState(_ state: SessionState?, _ reason: String?) { - self.state = state - self.stateReason = reason - } - - func setPaneTitle(_ title: String?) { - let name = SidebarEntry.withoutStatusGlyph(title ?? "") - if !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { - paneTitle = name - } - } - - private static let statusGlyph = try? NSRegularExpression( - pattern: "^\\s*[\\x{2800}-\\x{28FF}\\x{2722}-\\x{273D}\\x{00B7}\\x{2022}\\x{25CF}]+(\\s+|$)") - - /// Harnesses prefix their terminal title with a live status mark: Claude Code's `✳` - /// when idle, a braille spinner frame while working. The row already shows status in - /// its badge, and a mark that changes every frame would make the name (and a name - /// sort) flicker, so it is dropped from the name. - static func withoutStatusGlyph(_ title: String) -> String { - guard let regex = statusGlyph else { return title.trimmingCharacters(in: .whitespaces) } - let range = NSRange(title.startIndex..., in: title) - let stripped = regex.stringByReplacingMatches(in: title, range: range, withTemplate: "") - return stripped.trimmingCharacters(in: .whitespacesAndNewlines) - } - - /// The session's name as shown to the user: an explicit persisted rename, then the - /// harness-set OSC title (e.g. Claude Code's /rename), then the session name. - var displayName: String { - if let name = sessionEntry.displayName, !name.trimmingCharacters(in: .whitespaces).isEmpty { - return name - } - return detectedName - } - - /// Best name supplied by the harness/provider, before any persisted sidebar override. - var detectedName: String { paneTitle.isEmpty ? sessionName : paneTitle } - - /// Project path with the home directory abbreviated to `~`. - var abbreviatedPath: String { SidebarEntry.abbreviate(sessionEntry.projectPath) } - - static func abbreviate(_ path: String) -> String { - let home = NSHomeDirectory() - if !home.isEmpty, path.hasPrefix(home) { - return "~" + path.dropFirst(home.count) - } - return path - } - - /// The sidebar row's tooltip: name, session key, harness and latest status reason. - var tooltipText: String { - var lines = [displayName] - if displayName != sessionName { - lines.append(sessionName) - } - lines.append(harnessType.id) - switch status { - case .live: - if let state { - lines.append("\(state.rawValue) — \(stateReason ?? "")") - } else { - lines.append("status pending first poll…") - } - case .dead: - // dead isn't gone — Resume… brings it back - lines.append("dead — right-click to resume") - } - return lines.joined(separator: "\n") - } - - /// Human status for pre-flight reviews and batch checklists. - var statusPhrase: String { - if status == .dead { return "already stopped" } - guard let state else { return "live; status pending" } - switch state { - case .working: return "working" - case .waitingForInput: return "waiting for input" - case .idle: return "idle" - } - } -} - -/// Sorting and filtering vocabulary for the sidebar session list (Java's `SidebarView`). -enum SidebarView { - - enum SortMode: String, CaseIterable { - case sessionName = "session" - case directoryName = "folder" - case status = "status" - - var key: String { rawValue } - - var label: String { - switch self { - case .sessionName: return "Name" - case .directoryName: return "Folder" - case .status: return "Status" - } - } - - static func fromKey(_ key: String) -> SortMode { - allCases.first { $0.key.caseInsensitiveCompare(key) == .orderedSame } ?? .sessionName - } - } - - /// Every state a row can visibly occupy, including rows not covered by polling. The - /// order is the status sort's: attention first, then active/quiet, then lifecycle. - enum FilterStatus: Int, CaseIterable { - case waitingForInput, working, idle, statusPending, dead - - var key: String { - switch self { - case .waitingForInput: return "waiting" - case .working: return "working" - case .idle: return "idle" - case .statusPending: return "pending" - case .dead: return "dead" - } - } - - var label: String { - switch self { - case .waitingForInput: return "Waiting for input" - case .working: return "Working" - case .idle: return "Idle" - case .statusPending: return "Status pending" - case .dead: return "Dead" - } - } - } - - /// The harness identities a row can carry. - enum HarnessFamily: CaseIterable { - case claudeCode, codex, cursorAgent, grok, opencode, pi, muse, shell - - var harnessType: HarnessType { - switch self { - case .claudeCode: return .claudeCode - case .codex: return .codex - case .cursorAgent: return .cursorAgent - case .grok: return .grok - case .opencode: return .opencode - case .pi: return .pi - case .muse: return .muse - case .shell: return .shell - } - } - - var key: String { - switch self { - case .claudeCode: return "claude" - case .codex: return "codex" - case .cursorAgent: return "cursor" - case .grok: return "grok" - case .opencode: return "opencode" - case .pi: return "pi" - case .muse: return "muse" - case .shell: return "shell" - } - } - - var label: String { SidebarView.label(harnessType) } - - static func of(_ type: HarnessType) -> HarnessFamily { - allCases.first { $0.harnessType == type } ?? .shell - } - } - - /// The short provider name people know a harness by. - static func label(_ type: HarnessType) -> String { - switch type { - case .claudeCode: return "Claude" - case .codex: return "Codex" - case .cursorAgent: return "Cursor" - case .grok: return "Grok" - case .opencode: return "OpenCode" - case .pi: return "Pi" - case .muse: return "Muse" - case .shell: return "Shell" - } - } - - static func filterStatus(_ entry: SidebarEntry) -> FilterStatus { - if entry.status == .dead { return .dead } - switch entry.state { - case .working?: return .working - case .waitingForInput?: return .waitingForInput - case .idle?: return .idle - case nil: return .statusPending - } - } - - static func isVisible(_ entry: SidebarEntry, _ statuses: Set, - _ families: Set) -> Bool { - statuses.contains(filterStatus(entry)) && families.contains(HarnessFamily.of(entry.harnessType)) - } - - /// Case-insensitive first, then exact, like Java's `CASE_INSENSITIVE_ORDER.thenComparing(naturalOrder())`. - static func textOrder(_ a: String, _ b: String) -> ComparisonResult { - let folded = a.compare(b, options: [.caseInsensitive]) - if folded != .orderedSame { return folded } - return a == b ? .orderedSame : (a < b ? .orderedAscending : .orderedDescending) - } - - /// The sort's comparison, with the session key as the final tie-break so the order is - /// total and stable across rebuilds. - static func compare(_ a: SidebarEntry, _ b: SidebarEntry, _ mode: SortMode) -> ComparisonResult { - var primary: ComparisonResult - switch mode { - case .sessionName: - primary = textOrder(a.displayName, b.displayName) - case .directoryName: - primary = textOrder(directoryName(a), directoryName(b)) - if primary == .orderedSame { - // Full path outranks the session name so two folders sharing a basename - // cannot interleave — folder groups need each folder's rows contiguous. - primary = textOrder(folderGroupKey(a), folderGroupKey(b)) - } - case .status: - let x = filterStatus(a).rawValue, y = filterStatus(b).rawValue - primary = x == y ? .orderedSame : (x < y ? .orderedAscending : .orderedDescending) - } - return primary != .orderedSame ? primary : textOrder(a.sessionName, b.sessionName) - } - - static func sorted(_ entries: [SidebarEntry], _ mode: SortMode, descending: Bool) -> [SidebarEntry] { - entries.sorted { a, b in - let order = compare(a, b, mode) - return descending ? order == .orderedDescending : order == .orderedAscending - } - } - - /// Unique harnesses which currently have at least one live session, in enum order. - static func activeHarnesses(_ entries: [SidebarEntry]) -> [HarnessType] { - let live = Set(entries.filter { $0.status == .live }.map(\.harnessType)) - return HarnessType.allCases.filter { live.contains($0) } - } - - /// What makes two adjacent rows part of the same folder group: their full project path. - static func folderGroupKey(_ entry: SidebarEntry) -> String { - entry.sessionEntry.projectPath.trimmingCharacters(in: .whitespaces).isEmpty - ? "" : entry.sessionEntry.projectPath - } - - static func directoryName(_ entry: SidebarEntry) -> String { - let path = entry.sessionEntry.projectPath - if path.trimmingCharacters(in: .whitespaces).isEmpty { return "" } - let last = (path as NSString).lastPathComponent - return last.isEmpty ? path : last - } -} - -/// A run of same-folder rows in the outline, headed once by the folder. -final class FolderGroup { - let key: String - let path: String - var entries: [SidebarEntry] - - init(key: String, path: String, entries: [SidebarEntry]) { - self.key = key - self.path = path - self.entries = entries - } - - var folderName: String { - let name = (path as NSString).lastPathComponent - return name.isEmpty ? path : name - } - - var parentPath: String { - let parent = (path as NSString).deletingLastPathComponent - return parent == path ? "" : parent - } -} - -/// Refresh tickets: reconciliation runs off the main thread, so a slow older refresh must -/// not overwrite the sidebar state of a newer one — nor may a newer reselect-nothing -/// refresh drop an older one's reselect target (Java's `SidebarRefreshTickets`). -final class SidebarRefreshTickets { - private var issued: Int64 = 0 - private var pendingReselect: String? - private var pendingReselectSeq: Int64 = 0 - - func issue(_ reselect: String?) -> Int64 { - issued += 1 - if let reselect { - pendingReselect = reselect - pendingReselectSeq = issued - } - return issued - } - - func isCurrent(_ seq: Int64) -> Bool { seq == issued } - - func failed(_ seq: Int64) { - if pendingReselect != nil, pendingReselectSeq <= seq { - pendingReselect = nil - } - } - - func takeReselect() -> String? { - defer { pendingReselect = nil } - return pendingReselect - } -} diff --git a/swift/Sources/MicrohmApp/Sidebar/SidebarViewController.swift b/swift/Sources/MicrohmApp/Sidebar/SidebarViewController.swift deleted file mode 100644 index a6892de..0000000 --- a/swift/Sources/MicrohmApp/Sidebar/SidebarViewController.swift +++ /dev/null @@ -1,388 +0,0 @@ -import AppKit -import MicrohmCore - -protocol SidebarViewControllerDelegate: AnyObject { - /// The user changed the selection (not a programmatic reselect). - func sidebarSelectionDidChange(_ sidebar: SidebarViewController) - /// The context menu for a right-clicked row (already selected). - func sidebar(_ sidebar: SidebarViewController, menuFor entry: SidebarEntry) -> NSMenu? - func sidebarSortMenu(_ sidebar: SidebarViewController) -> NSMenu - func sidebarStatusFilterMenu(_ sidebar: SidebarViewController) -> NSMenu - func sidebarHarnessFilterMenu(_ sidebar: SidebarViewController) -> NSMenu - /// A double-click or Return on a row. - func sidebarActivate(_ sidebar: SidebarViewController) -} - -/// The sidebar: a "Sessions" heading with the sort and filter controls, the session list -/// (a source-list outline, grouped by folder when asked), and the budgets panel at the -/// bottom. Owns no session state — `MainWindowController` hands it the visible rows. -final class SidebarViewController: NSViewController, NSOutlineViewDataSource, NSOutlineViewDelegate, NSMenuDelegate { - - weak var delegate: SidebarViewControllerDelegate? - - let outlineView = SidebarOutlineView() - private let scrollView = NSScrollView() - let budgetPanel = HarnessBudgetPanel() - private let sortButton = NSButton() - private let filterButton = NSButton() - private let harnessButton = NSButton() - private let heading = NSTextField(labelWithString: "Sessions") - private let emptyLabel = NSTextField(wrappingLabelWithString: "") - private let backgroundView = NSView() - - /// Top-level outline items: `FolderGroup`s (when grouping) and `SidebarEntry`s. - private var roots: [AnyObject] = [] - /// The visible sessions in on-screen order — what Ctrl+1..9 counts. - private(set) var visibleEntries: [SidebarEntry] = [] - private(set) var grouping = false - var reticuleEnabled = false - /// Set while the list is rebuilt, so the rebuild's own selection changes are not - /// reported as the user's. - private var rebuilding = false - - override func loadView() { - let root = NSView() - root.translatesAutoresizingMaskIntoConstraints = false - backgroundView.wantsLayer = true - backgroundView.translatesAutoresizingMaskIntoConstraints = false - root.addSubview(backgroundView) - - heading.font = .systemFont(ofSize: 11, weight: .semibold) - heading.textColor = .secondaryLabelColor - heading.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) - - for (button, symbol, name, action) in [ - (sortButton, "arrow.up.arrow.down", "Sort", #selector(showSortMenu(_:))), - (filterButton, "line.3.horizontal.decrease.circle", "Filter statuses", #selector(showFilterMenu(_:))), - (harnessButton, "square.stack.3d.up", "Filter harnesses", #selector(showHarnessMenu(_:))), - ] { - button.bezelStyle = .accessoryBarAction - button.showsBorderOnlyWhileMouseInside = true - button.controlSize = .small - button.font = .systemFont(ofSize: NSFont.smallSystemFontSize) - button.image = HarnessIcons.symbol(symbol, nil, pointSize: 12) - button.imagePosition = .imageOnly - button.refusesFirstResponder = true - button.setAccessibilityLabel(name) - button.target = self - button.action = action - button.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) - } - let header = NSStackView(views: [heading, NSView(), sortButton, filterButton, harnessButton]) - header.orientation = .horizontal - header.spacing = 2 - header.edgeInsets = NSEdgeInsets(top: 0, left: 18, bottom: 0, right: 8) - header.translatesAutoresizingMaskIntoConstraints = false - root.addSubview(header) - - let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier("session")) - column.isEditable = false - outlineView.addTableColumn(column) - outlineView.outlineTableColumn = column - outlineView.headerView = nil - outlineView.style = .sourceList - outlineView.rowSizeStyle = .custom - outlineView.indentationPerLevel = 0 - outlineView.floatsGroupRows = false - outlineView.allowsEmptySelection = true - outlineView.allowsMultipleSelection = false - outlineView.dataSource = self - outlineView.delegate = self - outlineView.target = self - outlineView.doubleAction = #selector(doubleClicked(_:)) - outlineView.setAccessibilityLabel("Sessions") - let menu = NSMenu() - menu.delegate = self - outlineView.menu = menu - outlineView.onReturn = { [weak self] in - guard let self else { return } - self.delegate?.sidebarActivate(self) - } - - scrollView.documentView = outlineView - scrollView.hasVerticalScroller = true - scrollView.autohidesScrollers = true - scrollView.drawsBackground = false - scrollView.translatesAutoresizingMaskIntoConstraints = false - root.addSubview(scrollView) - - emptyLabel.alignment = .center - emptyLabel.textColor = .tertiaryLabelColor - emptyLabel.font = .systemFont(ofSize: NSFont.smallSystemFontSize) - emptyLabel.translatesAutoresizingMaskIntoConstraints = false - root.addSubview(emptyLabel) - - let separator = NSBox() - separator.boxType = .separator - separator.translatesAutoresizingMaskIntoConstraints = false - root.addSubview(separator) - budgetPanel.translatesAutoresizingMaskIntoConstraints = false - root.addSubview(budgetPanel) - - NSLayoutConstraint.activate([ - backgroundView.leadingAnchor.constraint(equalTo: root.leadingAnchor), - backgroundView.trailingAnchor.constraint(equalTo: root.trailingAnchor), - backgroundView.topAnchor.constraint(equalTo: root.topAnchor), - backgroundView.bottomAnchor.constraint(equalTo: root.bottomAnchor), - header.topAnchor.constraint(equalTo: root.safeAreaLayoutGuide.topAnchor, constant: 4), - header.leadingAnchor.constraint(equalTo: root.leadingAnchor), - header.trailingAnchor.constraint(equalTo: root.trailingAnchor), - header.heightAnchor.constraint(equalToConstant: 26), - scrollView.topAnchor.constraint(equalTo: header.bottomAnchor, constant: 2), - scrollView.leadingAnchor.constraint(equalTo: root.leadingAnchor), - scrollView.trailingAnchor.constraint(equalTo: root.trailingAnchor), - scrollView.bottomAnchor.constraint(equalTo: separator.topAnchor), - emptyLabel.centerYAnchor.constraint(equalTo: scrollView.centerYAnchor, constant: -20), - emptyLabel.leadingAnchor.constraint(equalTo: root.leadingAnchor, constant: 24), - emptyLabel.trailingAnchor.constraint(equalTo: root.trailingAnchor, constant: -24), - separator.leadingAnchor.constraint(equalTo: root.leadingAnchor, constant: 12), - separator.trailingAnchor.constraint(equalTo: root.trailingAnchor, constant: -12), - budgetPanel.topAnchor.constraint(equalTo: separator.bottomAnchor), - budgetPanel.leadingAnchor.constraint(equalTo: root.leadingAnchor), - budgetPanel.trailingAnchor.constraint(equalTo: root.trailingAnchor), - budgetPanel.bottomAnchor.constraint(equalTo: root.bottomAnchor), - root.widthAnchor.constraint(greaterThanOrEqualToConstant: 180), - ]) - view = root - } - - // MARK: - content - - /// Replaces the visible rows and restores the selection to `select` (a session name) - /// when it is still visible. Never reports the change as the user's. - func setEntries(_ entries: [SidebarEntry], grouping: Bool, select target: String?) { - rebuilding = true - defer { rebuilding = false } - self.grouping = grouping - visibleEntries = entries - roots = [] - if grouping { - var current: FolderGroup? - for entry in entries { - let key = SidebarView.folderGroupKey(entry) - if key.isEmpty { - current = nil - roots.append(entry) - } else if let group = current, group.key == key { - group.entries.append(entry) - } else { - let group = FolderGroup(key: key, path: entry.sessionEntry.projectPath, entries: [entry]) - roots.append(group) - current = group - } - } - } else { - roots = entries - } - outlineView.reloadData() - outlineView.expandItem(nil, expandChildren: true) - select(sessionName: target, scroll: true) - } - - /// The empty list's hint, e.g. "No sessions yet" or "Every session is filtered out". - func setEmptyText(_ text: String) { - emptyLabel.stringValue = text - emptyLabel.isHidden = !visibleEntries.isEmpty || text.isEmpty - } - - var selectedEntry: SidebarEntry? { - let row = outlineView.selectedRow - return row >= 0 ? outlineView.item(atRow: row) as? SidebarEntry : nil - } - - /// Selects `sessionName`'s row (nil, or a hidden row, clears the selection). Not - /// reported to the delegate. - @discardableResult - func select(sessionName: String?, scroll: Bool) -> Bool { - let wasRebuilding = rebuilding - rebuilding = true - defer { rebuilding = wasRebuilding } - guard let sessionName, let entry = visibleEntries.first(where: { $0.sessionName == sessionName }) else { - outlineView.deselectAll(nil) - return false - } - let row = outlineView.row(forItem: entry) - guard row >= 0 else { - outlineView.deselectAll(nil) - return false - } - outlineView.selectRowIndexes(IndexSet(integer: row), byExtendingSelection: false) - if scroll { - outlineView.scrollRowToVisible(row) - } - return true - } - - /// Redraws one session's row in place (state, title or attachment changed). - func reload(_ entry: SidebarEntry) { - let row = outlineView.row(forItem: entry) - guard row >= 0, let cell = outlineView.view(atColumn: 0, row: row, makeIfNecessary: false) as? SidebarCellView else { - return - } - cell.configure(entry, grouped: grouping && !SidebarView.folderGroupKey(entry).isEmpty, - reticuleEnabled: reticuleEnabled) - } - - func reloadAllRows() { - for entry in visibleEntries { - reload(entry) - } - } - - /// Heading controls: compact icon buttons (the sidebar is too narrow for "Sort: - /// Session" labels); a filled glyph shows a filter is hiding something, and the - /// tooltips carry the full summaries. - func updateControls(sortLabel: String, sortDescending: Bool, filterSummary: String, filtering: Bool, - harnessSummary: String, harnessFiltering: Bool) { - filterButton.image = HarnessIcons.symbol(filtering ? "line.3.horizontal.decrease.circle.fill" - : "line.3.horizontal.decrease.circle", "Filter", pointSize: 12) - filterButton.contentTintColor = filtering ? .controlAccentColor : nil - harnessButton.image = HarnessIcons.symbol(harnessFiltering ? "square.stack.3d.up.fill" : "square.stack.3d.up", - "Harnesses", pointSize: 12) - harnessButton.contentTintColor = harnessFiltering ? .controlAccentColor : nil - sortButton.toolTip = "Sort: \(sortLabel) (\(sortDescending ? "descending" : "ascending")) — choose how sessions are sorted" - filterButton.toolTip = "\(filterSummary) — choose which statuses are visible" - harnessButton.toolTip = "\(harnessSummary) — choose which harness families are visible" - heading.stringValue = "Sessions · by \(sortLabel.lowercased())" - } - - /// The sidebar surface: the system's translucent source list, or a solid fill. - func applyBackground(_ color: NSColor?) { - view.effectiveAppearance.performAsCurrentDrawingAppearance { - backgroundView.layer?.backgroundColor = color?.cgColor - } - let style: NSTableView.Style = color == nil ? .sourceList : .fullWidth - outlineView.backgroundColor = color ?? .clear - guard outlineView.style != style else { return } - // a style change re-measures rows; keep the selection across the reload - let selected = selectedEntry?.sessionName - outlineView.style = style - outlineView.reloadData() - outlineView.expandItem(nil, expandChildren: true) - select(sessionName: selected, scroll: false) - } - - // MARK: - actions - - @objc private func showSortMenu(_ sender: NSButton) { - guard let delegate else { return } - popUp(delegate.sidebarSortMenu(self), under: sender) - } - - @objc private func showFilterMenu(_ sender: NSButton) { - guard let delegate else { return } - popUp(delegate.sidebarStatusFilterMenu(self), under: sender) - } - - @objc private func showHarnessMenu(_ sender: NSButton) { - guard let delegate else { return } - popUp(delegate.sidebarHarnessFilterMenu(self), under: sender) - } - - private func popUp(_ menu: NSMenu, under button: NSButton) { - menu.popUp(positioning: nil, at: NSPoint(x: 0, y: button.bounds.height + 4), in: button) - } - - @objc private func doubleClicked(_ sender: Any?) { - guard outlineView.clickedRow >= 0, outlineView.item(atRow: outlineView.clickedRow) is SidebarEntry else { return } - delegate?.sidebarActivate(self) - } - - // MARK: - context menu - - func menuNeedsUpdate(_ menu: NSMenu) { - menu.removeAllItems() - let row = outlineView.clickedRow - // a click in the blank area below the list must not select (and attach) anything - guard row >= 0, let entry = outlineView.item(atRow: row) as? SidebarEntry else { return } - if outlineView.selectedRow != row { - outlineView.selectRowIndexes(IndexSet(integer: row), byExtendingSelection: false) - } - guard let built = delegate?.sidebar(self, menuFor: entry) else { return } - for item in built.items { - built.removeItem(item) - menu.addItem(item) - } - } - - // MARK: - data source - - func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int { - if item == nil { return roots.count } - return (item as? FolderGroup)?.entries.count ?? 0 - } - - func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any { - if item == nil { return roots[index] } - if let group = item as? FolderGroup { return group.entries[index] } - return NSNull() - } - - func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool { - item is FolderGroup - } - - // MARK: - delegate - - func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? { - if let group = item as? FolderGroup { - let view = outlineView.makeView(withIdentifier: FolderHeaderView.identifier, owner: self) as? FolderHeaderView - ?? FolderHeaderView(frame: .zero) - view.configure(group) - return view - } - guard let entry = item as? SidebarEntry else { return nil } - let view = outlineView.makeView(withIdentifier: SidebarCellView.identifier, owner: self) as? SidebarCellView - ?? SidebarCellView(frame: .zero) - view.configure(entry, grouped: grouping && !SidebarView.folderGroupKey(entry).isEmpty, - reticuleEnabled: reticuleEnabled) - return view - } - - func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat { - if item is FolderGroup { - return outlineView.row(forItem: item) == 0 ? 22 : 30 - } - if let entry = item as? SidebarEntry, grouping, !SidebarView.folderGroupKey(entry).isEmpty { - return 36 - } - return 44 - } - - func outlineView(_ outlineView: NSOutlineView, isGroupItem item: Any) -> Bool { - item is FolderGroup - } - - func outlineView(_ outlineView: NSOutlineView, shouldShowOutlineCellForItem item: Any) -> Bool { - false - } - - func outlineView(_ outlineView: NSOutlineView, shouldCollapseItem item: Any) -> Bool { - false - } - - func outlineView(_ outlineView: NSOutlineView, shouldSelectItem item: Any) -> Bool { - item is SidebarEntry - } - - func outlineViewSelectionDidChange(_ notification: Notification) { - if !rebuilding { - delegate?.sidebarSelectionDidChange(self) - } - } -} - -/// The session list: Return activates the selected row (focuses its terminal). -final class SidebarOutlineView: NSOutlineView { - var onReturn: (() -> Void)? - - override func keyDown(with event: NSEvent) { - if event.keyCode == 36 || event.keyCode == 76 { // Return, keypad Enter - onReturn?() - return - } - super.keyDown(with: event) - } - - override func frameOfOutlineCell(atRow row: Int) -> NSRect { .zero } -} diff --git a/swift/Sources/MicrohmApp/Support/DebugHooks.swift b/swift/Sources/MicrohmApp/Support/DebugHooks.swift deleted file mode 100644 index be46071..0000000 --- a/swift/Sources/MicrohmApp/Support/DebugHooks.swift +++ /dev/null @@ -1,64 +0,0 @@ -import AppKit -import Darwin - -/// Development aid for UI work, inert unless `MICROHM_UI_DEBUG` names a directory: on -/// SIGUSR1 the app reads `/command` and runs its lines — `snapshot ` writes -/// every visible window of the app to `/-.png`; `dark`, `light`, `system` -/// switch the appearance; `select `, `settings [tab]`, `new`, `usage`, `about`, -/// `menu `, `key` drive the UI — so a session can be screenshotted without -/// screen-recording permission or accessibility scripting. -enum DebugHooks { - nonisolated(unsafe) private static var source: DispatchSourceSignal? - - static func install(_ handler: @escaping (String, [String]) -> Void) { - guard let dir = ProcessInfo.processInfo.environment["MICROHM_UI_DEBUG"], !dir.isEmpty else { return } - signal(SIGUSR1, SIG_IGN) - let source = DispatchSource.makeSignalSource(signal: SIGUSR1, queue: .main) - source.setEventHandler { - let file = URL(fileURLWithPath: dir).appendingPathComponent("command") - guard let text = try? String(contentsOf: file, encoding: .utf8) else { return } - var delay = 0.0 - for line in text.split(separator: "\n") { - let words = line.split(separator: " ").map(String.init) - guard let verb = words.first else { continue } - if verb == "wait", let seconds = words.dropFirst().first.flatMap(Double.init) { - delay += seconds - continue - } - if verb == "snapshot" { - let name = words.dropFirst().first ?? "snapshot" - DispatchQueue.main.asyncAfter(deadline: .now() + delay) { snapshot(dir: dir, name: name) } - } else { - DispatchQueue.main.asyncAfter(deadline: .now() + delay) { handler(verb, Array(words.dropFirst())) } - } - } - } - source.resume() - self.source = source - } - - /// Every visible window, rendered by the app itself. - static func snapshot(dir: String, name: String) { - var index = 0 - for window in NSApp.orderedWindows where window.isVisible { - guard let frameView = window.contentView?.superview else { continue } - let bounds = frameView.bounds - guard let rep = frameView.bitmapImageRepForCachingDisplay(in: bounds) else { continue } - frameView.cacheDisplay(in: bounds, to: rep) - guard let png = rep.representation(using: .png, properties: [:]) else { continue } - index += 1 - let url = URL(fileURLWithPath: dir).appendingPathComponent("\(name)-\(index).png") - try? png.write(to: url) - } - // also sheets attached to windows - for window in NSApp.windows { - guard let sheet = window.attachedSheet, let frameView = sheet.contentView?.superview else { continue } - let bounds = frameView.bounds - guard let rep = frameView.bitmapImageRepForCachingDisplay(in: bounds) else { continue } - frameView.cacheDisplay(in: bounds, to: rep) - guard let png = rep.representation(using: .png, properties: [:]) else { continue } - index += 1 - try? png.write(to: URL(fileURLWithPath: dir).appendingPathComponent("\(name)-sheet-\(index).png")) - } - } -} diff --git a/swift/Sources/MicrohmApp/Support/HarnessIcons.swift b/swift/Sources/MicrohmApp/Support/HarnessIcons.swift deleted file mode 100644 index 4cfa6a4..0000000 --- a/swift/Sources/MicrohmApp/Support/HarnessIcons.swift +++ /dev/null @@ -1,85 +0,0 @@ -import AppKit -import MicrohmCore - -/// The app's resources, found without `Bundle.module`: SwiftPM's generated accessor -/// traps when its bundle is not where it expects, and the .app built by -/// `scripts/build-app.sh` keeps resource bundles in Contents/Resources. A missing -/// resource here only ever means a missing icon. -enum AppResources { - static let bundleName = "Microhm_MicrohmApp.bundle" - - static let bundle: Bundle? = { - let exe = Bundle.main.executableURL?.resolvingSymlinksInPath().deletingLastPathComponent() - let candidates = [ - Bundle.main.resourceURL?.appendingPathComponent(bundleName), - Bundle.main.bundleURL.appendingPathComponent(bundleName), - exe?.appendingPathComponent(bundleName), - exe?.deletingLastPathComponent().appendingPathComponent("Resources").appendingPathComponent(bundleName), - ].compactMap { $0 } - for url in candidates where FileManager.default.fileExists(atPath: url.path) { - if let bundle = Bundle(url: url) { return bundle } - } - return nil - }() - - static func url(_ relativePath: String) -> URL? { - guard let base = bundle?.resourceURL ?? bundle?.bundleURL else { return nil } - let url = base.appendingPathComponent(relativePath) - return FileManager.default.fileExists(atPath: url.path) ? url : nil - } - - static let appIcon: NSImage? = url("app-icon.png").flatMap { NSImage(contentsOf: $0) } -} - -/// Harness identities: the providers' flat marks (SVG, tinted as template images) and an -/// SF Symbol for the plain shell. Cached per type and size. -enum HarnessIcons { - private static var cache: [String: NSImage] = [:] - - private static func svgName(_ type: HarnessType) -> String? { - switch type { - case .claudeCode: return "anthropic" - case .codex: return "openai" - case .cursorAgent: return "cursor" - case .grok: return "grok" - case .opencode: return "opencode" - case .pi: return "pi" - case .muse: return "muse" - case .shell: return nil - } - } - - /// A template image (tints with the surrounding text colour) `size` points square. - static func image(_ type: HarnessType, size: CGFloat = 16) -> NSImage { - let key = "\(type.id)@\(size)" - if let cached = cache[key] { return cached } - let image: NSImage - if let name = svgName(type), let url = AppResources.url("provider-icons/\(name).svg"), - let svg = NSImage(contentsOf: url) { - image = NSImage(size: NSSize(width: size, height: size), flipped: false) { rect in - svg.draw(in: rect) - return true - } - } else { - let config = NSImage.SymbolConfiguration(pointSize: size * 0.82, weight: .medium) - image = NSImage(systemSymbolName: "terminal", accessibilityDescription: type.id)? - .withSymbolConfiguration(config) ?? NSImage(size: NSSize(width: size, height: size)) - } - image.isTemplate = true - image.accessibilityDescription = SidebarView.label(type) - cache[key] = image - return image - } - - /// An SF Symbol, or an empty image if the system lacks it (never nil). - static func symbol(_ name: String, _ description: String? = nil, pointSize: CGFloat? = nil, - weight: NSFont.Weight = .regular) -> NSImage { - var image = NSImage(systemSymbolName: name, accessibilityDescription: description) - ?? NSImage(systemSymbolName: "questionmark.square.dashed", accessibilityDescription: description) - ?? NSImage(size: NSSize(width: 16, height: 16)) - if let pointSize, let configured = image.withSymbolConfiguration(.init(pointSize: pointSize, weight: weight)) { - image = configured - } - return image - } -} diff --git a/swift/Sources/MicrohmApp/Support/QRCode.swift b/swift/Sources/MicrohmApp/Support/QRCode.swift deleted file mode 100644 index d89642c..0000000 --- a/swift/Sources/MicrohmApp/Support/QRCode.swift +++ /dev/null @@ -1,31 +0,0 @@ -import AppKit -import CoreImage - -/// QR codes for a phone camera to read off the screen (Java's `QrImages`): black on white -/// whatever the theme — cameras need the contrast — with the standard 4-module quiet zone. -enum QRCode { - static let border = 4 - - static func image(_ text: String, scale: Int) -> NSImage? { - guard !text.isEmpty, let filter = CIFilter(name: "CIQRCodeGenerator") else { return nil } - filter.setValue(Data(text.utf8), forKey: "inputMessage") - filter.setValue("M", forKey: "inputCorrectionLevel") - guard let output = filter.outputImage else { return nil } - let modules = Int(output.extent.width) - let context = CIContext(options: [.useSoftwareRenderer: false]) - guard let cg = context.createCGImage(output, from: output.extent) else { return nil } - let side = (modules + border * 2) * scale - let image = NSImage(size: NSSize(width: side, height: side), flipped: false) { rect in - NSColor.white.setFill() - rect.fill() - guard let ctx = NSGraphicsContext.current?.cgContext else { return true } - ctx.interpolationQuality = .none - let inset = CGFloat(border * scale) - ctx.draw(cg, in: CGRect(x: inset, y: inset, width: CGFloat(modules * scale), height: CGFloat(modules * scale))) - return true - } - image.accessibilityDescription = "QR code for \(text)" - return image - } -} - diff --git a/swift/Sources/MicrohmApp/main.swift b/swift/Sources/MicrohmApp/main.swift deleted file mode 100644 index 3688565..0000000 --- a/swift/Sources/MicrohmApp/main.swift +++ /dev/null @@ -1,61 +0,0 @@ -import AppKit -import MicrohmCore -import MicrohmShared - -// Entry point: the AppKit app, as a plain SwiftPM executable or inside the Microhm.app -// that scripts/build-app.sh builds. One app per state directory (`MICROHM_HOME`, default -// ~/.micro-harness-manager-swift); logs go to its app.log. - -StartupTimes.markMain() -_ = try? MicrohmPaths.ensureDirectory(MicrohmPaths.home) -Log.shared.open(MicrohmPaths.appLog) - -let app = NSApplication.shared -app.setActivationPolicy(.regular) - -/// Takes the registry's instance lock (Java's `lockInstance`). A background host holding it -/// (the app was closed while sessions ran) is stopped and the lock taken over; anything -/// else holding it is another app. A lock that cannot even be attempted runs unguarded. -func lockInstance() -> InstanceLock.Result { - let registryFile = RegistryPaths.resolve() - var lock = InstanceLock.tryAcquire(registryFile) - if lock == .HELD { - // a host that just took the lock writes its record right after; give it a moment - for _ in 0..<20 where HostOwner.read(registryFile) == nil { - Thread.sleep(forTimeInterval: 0.05) - } - if HostOwner.read(registryFile) != nil, HostOwner.stop(registryFile, 5) { - lock = InstanceLock.acquire(registryFile, 5) - } - } - return lock -} - -switch lockInstance() { -case .ACQUIRED: - break -case .HELD: - Log.warn("another instance holds \(InstanceLock.lockFile(RegistryPaths.resolve()).path); exiting", tag: "app") - // bring the running one forward instead of opening a second window on the same state - let me = ProcessInfo.processInfo.processIdentifier - let others = NSWorkspace.shared.runningApplications.filter { - $0.processIdentifier != me && $0.executableURL?.lastPathComponent == "Microhm" - } - if let other = others.first { - other.activate() - } else { - let alert = NSAlert() - alert.messageText = "\(AppModel.appName) is already running" - alert.informativeText = "Another \(AppModel.appName) is using \(MicrohmPaths.home.path)." - alert.alertStyle = .critical - app.activate(ignoringOtherApps: true) - alert.runModal() - } - exit(1) -case .UNAVAILABLE: - Log.warn("instance lock unavailable; running unguarded", tag: "app") -} - -let delegate = AppDelegate() -app.delegate = delegate -app.run() diff --git a/swift/Sources/MicrohmCore/Resources/web/app.css b/swift/Sources/MicrohmCore/Resources/web/app.css deleted file mode 100644 index 0488193..0000000 --- a/swift/Sources/MicrohmCore/Resources/web/app.css +++ /dev/null @@ -1,311 +0,0 @@ -/* Microhm phone page. Flat, in the manner of iOS's own apps: the system font, grouped - lists on a grey ground, hairline separators, one accent. Status is always a dot and a - word in the same type. */ -:root { - --ground: #f2f2f7; - --surface: #ffffff; - --fill: rgba(120, 120, 128, 0.12); /* flat tiles, fields, unselected chips */ - --fill-strong: rgba(120, 120, 128, 0.22); - --text: #1c1c1e; - --muted: #8a8a8e; - --hairline: rgba(60, 60, 67, 0.18); - --accent: #007aff; - --accent-soft: rgba(0, 122, 255, 0.12); - --on-accent: #ffffff; - --waiting: #d97706; - --working: #16a34a; - --idle: #9ca3af; - --ended: #c7c7cc; - --danger: #ff3b30; - --send: #34c759; - /* macOS push-button bezel */ - --bezel: #ffffff; - --bezel-pressed: #e8e8ed; - --bezel-edge: rgba(0, 0, 0, 0.14); - --bezel-shadow: 0 0.5px 1.5px rgba(0, 0, 0, 0.18); - --term-bg: #16181d; - --term-text: #d9dee6; - --mono: ui-monospace, "SF Mono", Menlo, monospace; - color-scheme: light; -} -@media (prefers-color-scheme: dark) { - :root { - --ground: #000000; - --surface: #1c1c1e; - --fill: rgba(118, 118, 128, 0.24); - --fill-strong: rgba(118, 118, 128, 0.36); - --text: #f2f2f7; - --muted: #98989f; - --hairline: rgba(84, 84, 88, 0.6); - --accent: #0a84ff; - --accent-soft: rgba(10, 132, 255, 0.2); - --on-accent: #ffffff; - --waiting: #fbbf24; - --working: #4ade80; - --idle: #8e8e93; - --ended: #48484a; - --danger: #ff453a; - --send: #30d158; - --bezel: #3a3a3c; - --bezel-pressed: #4a4a4e; - --bezel-edge: rgba(255, 255, 255, 0.1); - --bezel-shadow: 0 0.5px 1.5px rgba(0, 0, 0, 0.5); - --term-bg: #0d0e11; - color-scheme: dark; - } -} - -* { box-sizing: border-box; } -/* The page never scrolls as a whole: only the list, the screen and the form do. */ -html, body { height: 100%; overflow: hidden; overscroll-behavior: none; } -/* Taps are taps: no double-tap zoom, no grey flash, no text selection on controls. */ -html { touch-action: manipulation; -webkit-tap-highlight-color: transparent; } -body { - margin: 0; background: var(--ground); color: var(--text); - font: 17px/1.3 -apple-system, BlinkMacSystemFont, system-ui, sans-serif; - -webkit-text-size-adjust: 100%; -} -[hidden] { display: none !important; } -button, input, select, textarea { font: inherit; color: inherit; } -button { - touch-action: manipulation; -webkit-user-select: none; user-select: none; - border: 0; background: none; padding: 0; cursor: pointer; -} -button:disabled { opacity: 0.4; } -h1, h2 { margin: 0; } - -.view { - display: flex; flex-direction: column; - height: 100%; height: 100dvh; - padding-top: env(safe-area-inset-top); - padding-left: env(safe-area-inset-left); - padding-right: env(safe-area-inset-right); -} - -/* ---------------------------------------------------------------- navigation bar */ - -/* Equal side columns keep the title centered whatever the buttons say. */ -.nav { - display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: 8px; - min-height: 52px; padding: 4px 16px; - background: var(--ground); - border-bottom: 0.5px solid var(--hairline); -} -.nav h1 { font-size: 17px; font-weight: 600; text-align: center; } -.nav > :first-child { justify-self: start; } -.nav > :last-child { justify-self: end; } -.nav-title { display: flex; flex-direction: column; align-items: center; min-width: 0; max-width: 60vw; } -.nav-title h1 { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } - -/* One button for every icon action, as on iPhone: a 36-point circle, the height of the - message field. Neutral ones are a grey disc; the ones with a meaning are solid colour - with a white mark: close red, send green. Play and stop on the list are neutral. */ -.btn { - width: 36px; height: 36px; flex: none; display: grid; place-items: center; - border-radius: 50%; background: var(--fill); color: var(--text); -} -.btn:active { background: var(--fill-strong); } -.btn.close { background: var(--danger); color: #fff; } -.btn.default { background: var(--send); color: #fff; } -.btn.close:active, .btn.default:active { filter: brightness(0.88); } -/* not on offer right now (Close while the session is busy): faded */ -.btn.unavailable { opacity: 0.35; } -.btn.busy { animation: busy 1s ease-in-out infinite alternate; } -@keyframes busy { from { opacity: 1; } to { opacity: 0.35; } } -/* a toggle that is open (the funnel, the keys), or filters that hide sessions */ -.btn.on { background: var(--fill-strong); } -.btn.filtered { color: var(--accent); } - -/* ---------------------------------------------------------------- status: dot + word */ - -.status { - display: inline-flex; align-items: center; gap: 6px; - font-size: 13px; font-weight: 500; color: var(--muted); white-space: nowrap; -} -.status::before { - content: ""; width: 8px; height: 8px; border-radius: 50%; background: var(--idle); flex: none; -} -.status:empty::before { display: none; } -.status.WAITING_FOR_INPUT { color: var(--waiting); } -.status.WAITING_FOR_INPUT::before { background: var(--waiting); } -.status.WORKING { color: var(--working); } -.status.WORKING::before { background: var(--working); animation: pulse 1.6s ease-in-out infinite; } -.status.ENDED::before { background: var(--ended); } -@keyframes pulse { 50% { opacity: 0.35; } } -@media (prefers-reduced-motion: reduce) { .status.WORKING::before { animation: none; } } - -/* ---------------------------------------------------------------- list controls */ - -.controls { display: flex; gap: 8px; align-items: center; padding: 10px 16px 6px; } -.segmented { - flex: 1; display: grid; grid-auto-flow: column; grid-auto-columns: 1fr; - background: var(--fill); border-radius: 9px; padding: 2px; -} -.segmented button { font-size: 13px; font-weight: 500; padding: 6px 0; border-radius: 7px; } -.segmented button[aria-pressed="true"] { background: var(--surface); font-weight: 600; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08); } -.icon-button { width: 34px; height: 30px; border-radius: 9px; background: var(--fill); font-size: 15px; } - -.filters { - display: flex; gap: 6px; overflow-x: auto; padding: 4px 16px 10px; scrollbar-width: none; -} -.filters::-webkit-scrollbar { display: none; } -/* Filter toggles: on is a filled chip with a check, off an outlined one with a plus. - No colour change: the mark says which. */ -.chip { - flex: none; font-size: 13px; font-weight: 500; padding: 5px 12px 5px 9px; border-radius: 999px; - border: 1px solid var(--hairline); color: var(--muted); background: none; -} -.chip::before { content: "+"; display: inline-block; width: 14px; font-weight: 600; } -.chip[aria-pressed="true"] { background: var(--fill-strong); border-color: transparent; color: var(--text); } -.chip[aria-pressed="true"]::before { content: "✓"; } -.chip-gap { flex: none; width: 1px; background: var(--hairline); margin: 4px 4px; } - -/* ---------------------------------------------------------------- the list */ - -.list { flex: 1; overflow-y: auto; overscroll-behavior: contain; padding: 0 16px calc(24px + env(safe-area-inset-bottom)); } -.group-head { - margin: 18px 4px 6px; font-size: 13px; color: var(--muted); - display: flex; gap: 8px; align-items: baseline; min-width: 0; -} -.group-head b { font-weight: 600; text-transform: uppercase; letter-spacing: 0.04em; flex: none; } -.group-head span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; direction: rtl; text-align: left; } -.group { background: var(--surface); border-radius: 12px; overflow: hidden; } -.list > .group:first-child { margin-top: 6px; } -.row { - display: grid; grid-template-columns: 1fr auto; align-items: center; gap: 12px; - padding: 0 12px 0 0; position: relative; min-height: 60px; -} -.row-main { - display: flex; flex-direction: column; gap: 2px; min-width: 0; - padding: 10px 0 10px 16px; color: inherit; text-decoration: none; -} -.row-side { display: flex; align-items: center; gap: 12px; } -.row + .row::before { - content: ""; position: absolute; top: 0; left: 16px; right: 0; border-top: 0.5px solid var(--hairline); -} -a.row-main:active { background: var(--fill); } -.row .name { font-size: 17px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.row .where { font-size: 13px; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.row.ended .name { color: var(--muted); } - -.empty { text-align: center; color: var(--muted); font-size: 15px; padding: 48px 24px; } - -/* ---------------------------------------------------------------- one session */ - -.scroller { - flex: 1; min-height: 0; overflow: auto; overscroll-behavior: contain; - background: var(--term-bg); color: var(--term-text); padding: 10px 10px 12px; -} -.screen, .history { margin: 0; font: 12px/15px var(--mono); } -/* Box and block characters are drawn as shapes filling their cell (see "cell glyphs" in - app.js): exactly one character wide and one line tall, in the text colour. The line - height is whole pixels so rows meet on pixel edges, with no seams. */ -.g { - display: inline-block; height: 15px; vertical-align: top; /* width: the run's cells, set inline */ - background-color: currentColor; - -webkit-mask-size: 100% 100%; mask-size: 100% 100%; - -webkit-mask-repeat: no-repeat; mask-repeat: no-repeat; -} - -/* Until the first screen arrives: a quiet spinner in the middle of the dark area. */ -.connecting { - min-height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; - color: rgba(217, 222, 230, 0.6); font-size: 13px; -} -.spinner { - width: 20px; height: 20px; border-radius: 50%; - border: 2px solid rgba(217, 222, 230, 0.18); border-top-color: rgba(217, 222, 230, 0.75); - animation: spin 0.9s linear infinite; -} -@keyframes spin { to { transform: rotate(360deg); } } -@media (prefers-reduced-motion: reduce) { .spinner { animation: pulse 1.6s ease-in-out infinite; } } - -/* While the earlier output loads: a thin bar and how much of it has arrived. */ -.progress { - display: flex; align-items: center; gap: 10px; padding: 6px 12px; - background: var(--term-bg); color: rgba(217, 222, 230, 0.6); font-size: 12px; - font-variant-numeric: tabular-nums; - border-bottom: 1px solid rgba(255, 255, 255, 0.06); -} -.progress-track { flex: 1; height: 3px; border-radius: 2px; background: rgba(217, 222, 230, 0.15); overflow: hidden; } -.progress-track i { display: block; height: 100%; width: 0; background: var(--accent); border-radius: 2px; transition: width 0.2s ease-out; } -.progress span { flex: none; } -/* The session runs at the size that fits here (phoneSize in app.js): lines never wrap. */ -.screen { white-space: pre; } -/* A web link on the screen (findLinks in app.js): its own colours, underlined; a tap opens it. */ -.screen a { color: inherit; text-decoration: underline; text-underline-offset: 2px; text-decoration-thickness: 1px; } -/* Earlier lines were drawn at whatever width the session had then: wrap them. */ -.history { white-space: pre-wrap; overflow-wrap: anywhere; opacity: 0.7; } -.history:not(:empty) { padding-bottom: 8px; margin-bottom: 8px; border-bottom: 1px dashed rgba(255, 255, 255, 0.16); } - -/* The keys, behind the button left of the message field: a keypad, four to a row, like - the keyboard's own keys. */ -.keys { - display: grid; grid-template-columns: repeat(4, 1fr); gap: 7px; padding: 10px 10px 4px; - background: var(--ground); border-top: 0.5px solid var(--hairline); - -webkit-user-select: none; user-select: none; -} -.keys button { - height: 42px; border-radius: 9px; background: var(--surface); - box-shadow: 0 1px 0 rgba(0, 0, 0, 0.12); font-size: 16px; font-weight: 500; -} -.keys button:active { background: var(--fill-strong); } -.keys .stop { color: var(--danger); } - -.compose { - display: flex; gap: 8px; align-items: flex-end; - padding: 6px 10px calc(8px + env(safe-area-inset-bottom)); background: var(--ground); -} -.compose textarea { - flex: 1; resize: none; max-height: 40vh; border: 0; border-radius: 18px; outline: none; - padding: 7px 14px; background: var(--fill); font-size: 16px; line-height: 22px; /* 16px: no zoom on focus */ -} - - -/* ---------------------------------------------------------------- forms */ - -.form { flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 22px; padding: 18px 16px calc(24px + env(safe-area-inset-bottom)); } -.form .group { display: flex; flex-direction: column; } -.field { display: grid; grid-template-columns: 110px 1fr; align-items: center; gap: 12px; padding: 0 16px; min-height: 48px; position: relative; } -.field + .field::before { content: ""; position: absolute; top: 0; left: 16px; right: 0; border-top: 0.5px solid var(--hairline); } -.field > span { font-size: 17px; } -.field.stacked { grid-template-columns: 1fr; padding: 12px 16px; gap: 6px; } -.field.stacked > span { font-size: 13px; color: var(--muted); } -.field input, .field select, .field textarea { - border: 0; outline: none; background: none; font-size: 17px; width: 100%; min-width: 0; padding: 12px 0; -} -.field select { color: var(--accent); text-align: right; direction: rtl; -webkit-appearance: none; appearance: none; } -.field textarea { padding: 0; resize: none; } - -.primary { - width: 100%; padding: 14px; border-radius: 12px; font-size: 17px; font-weight: 600; - background: var(--accent); color: var(--on-accent); -} -.primary.danger { background: var(--danger); color: #fff; } -.secondary { width: 100%; padding: 14px; border-radius: 12px; font-size: 17px; font-weight: 600; background: var(--fill); color: var(--accent); } - -/* A calm line, not an alarm: what went wrong and what to do, in plain words. */ -.problem { - margin: 6px 16px 0; padding: 8px 12px; border-radius: 10px; font-size: 14px; - background: var(--fill); color: var(--muted); -} - -/* ---------------------------------------------------------------- sheet */ - -.sheet-backdrop { - position: fixed; inset: 0; z-index: 10; background: rgba(0, 0, 0, 0.35); - display: flex; align-items: flex-end; -} -.sheet { - width: 100%; background: var(--surface); border-radius: 14px 14px 0 0; - padding: 22px 16px calc(16px + env(safe-area-inset-bottom)); - display: flex; flex-direction: column; gap: 10px; -} -.sheet h2 { font-size: 20px; font-weight: 600; } -.sheet p { margin: 0 0 8px; color: var(--muted); font-size: 15px; line-height: 1.4; } -.sheet-spinner { border-color: var(--fill-strong); border-top-color: var(--muted); margin: 4px 0 8px; } -.sheet .primary, .sheet .secondary { border-radius: 999px; } - -.locked { margin: auto; padding: 24px; max-width: 420px; display: flex; flex-direction: column; gap: 12px; } -.locked h1 { font-size: 22px; } -.locked p { margin: 0; color: var(--muted); line-height: 1.45; } diff --git a/swift/Sources/MicrohmCore/Resources/web/app.js b/swift/Sources/MicrohmCore/Resources/web/app.js deleted file mode 100644 index b4f417d..0000000 --- a/swift/Sources/MicrohmCore/Resources/web/app.js +++ /dev/null @@ -1,1238 +0,0 @@ -// Microhm phone page. Plain script, no build step: edit, save, refresh. -// Views by address: "#" the list, "#s=" one session, "#new" the new-session form. -// The phone link carries the secret as "#k="; it is traded for a cookie at once. -"use strict"; - -const $ = (id) => document.getElementById(id); - -// Every state a row can show, in Status order; the same dot and word everywhere. -const STATUS = { - WAITING_FOR_INPUT: { label: "Waiting", rank: 0 }, - WORKING: { label: "Working", rank: 1 }, - IDLE: { label: "Idle", rank: 2 }, - ENDED: { label: "Ended", rank: 3 }, -}; -const AGENT = { - "claude-code": "Claude", codex: "Codex", "cursor-agent": "Cursor", grok: "Grok", - opencode: "OpenCode", pi: "Pi", muse: "Muse", shell: "Shell", -}; - -let sessions = []; // running, from the server -let ended = []; // saved sessions that are not running -let renderedList = null; -const screens = new Map(); // the last screen seen of each session, shown at once on return -let listTimer = null; -let stream = null; -let current = null; // the session being shown -let retryDelay = 1000; // reconnecting backs off, so a failing server is not hammered -const MAX_RETRY_DELAY = 15000; - -// ------------------------------------------------------------------ server calls - -class Locked extends Error {} - -async function api(path, body) { - const options = body === undefined ? {} : { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(body), - }; - let response; - try { - response = await fetch(path, options); - } catch (e) { - // Safari's own words for this are "Load failed" - throw new Error("Can't reach Microhm. Is it running, and is this phone on your network?"); - } - if (response.status === 401) throw new Locked(); - const data = await response.json().catch(() => ({})); - if (!response.ok || data.ok === false) throw new Error(data.error || data.text || response.statusText); - return data; -} - -async function login(token) { - try { - await api("/api/login", { token }); - } catch (e) { - // a stale link: fall through to the locked screen if the cookie does not work either - } - history.replaceState(null, "", location.pathname); -} - -// ------------------------------------------------------------------ routing - -// The list is home, and history holds at most the list and one view above it, so Safari's -// swipe back (and its back button) always lands on the list. Opening a session or the form -// from the list adds that one entry; leaving it by the page's own buttons steps back -// through it rather than adding another; starting a session takes the form's place. -let fromList = false; // the view shown sits one history entry above the list -let navigation = null; // "open" or "replace": how the next address change came about - -/** From the list to a view: one history entry above the list. */ -function openView(hash) { - navigation = "open"; - location.hash = hash; -} - -/** This view's history entry becomes {@code hash}'s, still above the list if it was. */ -function replaceView(hash) { - navigation = "replace"; - location.replace("#" + hash); -} - -/** Back to the list: the entry below when there is one, else this entry becomes the list - * (a view reached by a link or a reload has no list below it). */ -function toList() { - if (fromList) history.back(); else replaceView(""); -} - -function route() { - const hash = decodeURIComponent(location.hash.slice(1)); - if (navigation === "open") fromList = true; - else if (navigation !== "replace") fromList = false; // swipe back or forward, a link, a reload - navigation = null; - stopList(); - stopStream(); - hideSheet(); - current = null; - if (hash.startsWith("s=")) { - showSession(hash.slice(2)); - } else if (hash === "new") { - showNew(); - } else { - showList(); - } -} - -function show(id) { - for (const view of document.querySelectorAll(".view")) view.hidden = view.id !== id; -} - -function locked() { - stopList(); - stopStream(); - show("locked-view"); -} - -function problem(id, message) { - const el = $(id); - el.textContent = message || ""; - el.hidden = !message; -} - -function failed(id, e) { - if (e instanceof Locked) return locked(); - problem(id, e.message); -} - -// ------------------------------------------------------------------ list: sort, filter, group - -// Sort and filters, kept on this phone. The same choices as Microhm's sidebar. -const view = loadView(); - -function loadView() { - const saved = readJson("view2") || {}; - return { - // grouped by folder unless chosen otherwise: easiest on the eyes - sort: ["status", "session", "folder"].includes(saved.sort) ? saved.sort : "folder", - descending: !!saved.descending, - hiddenStates: new Set(saved.hiddenStates || []), - hiddenAgents: new Set(saved.hiddenAgents || []), - }; -} - -function saveView() { - writeJson("view2", { - sort: view.sort, descending: view.descending, - hiddenStates: [...view.hiddenStates], hiddenAgents: [...view.hiddenAgents], - }); - renderedList = null; - renderList(); -} - -async function showList() { - show("list-view"); - renderControls(); - await refreshList(); - listTimer = setInterval(refreshList, 3000); -} - -function stopList() { - clearInterval(listTimer); - listTimer = null; -} - -async function refreshList() { - try { - const data = await api("/api/sessions"); - problem("list-problem", ""); - sessions = data.sessions; - ended = data.ended || []; - renderList(); - } catch (e) { - failed("list-problem", e); - } -} - -function label(s) { - return s.display || s.name; -} - -function folder(project) { - return (project || "").split(/[\\/]/).filter(Boolean).pop() || project || ""; -} - -function allRows() { - return [ - ...sessions.map((s) => ({ ...s, ended: false })), - ...ended.map((s) => ({ ...s, state: "ENDED", ended: true })), - ]; -} - -function compareRows(a, b) { - const byName = label(a).localeCompare(label(b), undefined, { sensitivity: "base" }); - let primary = 0; - if (view.sort === "status") { - primary = (STATUS[a.state]?.rank ?? 9) - (STATUS[b.state]?.rank ?? 9); - } else if (view.sort === "folder") { - // the full path next, so two folders with the same name never interleave - primary = folder(a.project).localeCompare(folder(b.project), undefined, { sensitivity: "base" }) - || (a.project || "").localeCompare(b.project || ""); - } - return (view.descending ? -1 : 1) * (primary || byName); -} - -// The sort and filter rows start hidden; the funnel shows them. It turns blue while -// filters hide some sessions, so a short list is never a mystery. -function toggleControls() { - const open = $("controls").hidden; - $("controls").hidden = !open; - $("filters").hidden = !open; - renderControls(); -} - -function renderControls() { - const open = !$("controls").hidden; - const filtered = view.hiddenStates.size > 0 || view.hiddenAgents.size > 0; - const funnel = $("view-button"); - funnel.setAttribute("aria-expanded", String(open)); - funnel.classList.toggle("on", open); - funnel.classList.toggle("filtered", filtered); - for (const button of $("sort").querySelectorAll("button")) { - button.setAttribute("aria-pressed", String(button.dataset.sort === view.sort)); - } - $("direction").textContent = view.descending ? "↑" : "↓"; - const filters = $("filters"); - filters.replaceChildren(); - for (const [state, info] of Object.entries(STATUS)) { - filters.append(chip(info.label, !view.hiddenStates.has(state), () => toggle(view.hiddenStates, state))); - } - const agents = [...new Set(allRows().map((s) => s.harness))].sort(); - if (agents.length > 1) { - const gap = document.createElement("span"); - gap.className = "chip-gap"; - filters.append(gap); - for (const agent of agents) { - filters.append(chip(AGENT[agent] || agent, !view.hiddenAgents.has(agent), () => toggle(view.hiddenAgents, agent))); - } - } -} - -function chip(text, on, onClick) { - const button = document.createElement("button"); - button.type = "button"; - button.className = "chip"; - button.textContent = text; - button.setAttribute("aria-pressed", String(on)); - button.onclick = onClick; - return button; -} - -function toggle(set, key) { - if (set.has(key)) set.delete(key); else set.add(key); - saveView(); - renderControls(); -} - -function renderList() { - const rows = allRows(); - const key = JSON.stringify([rows, view.sort, view.descending, [...view.hiddenStates], [...view.hiddenAgents]]); - if (key === renderedList) return; - renderedList = key; - renderControls(); - const list = $("sessions"); - list.replaceChildren(); - if (rows.length === 0) { - list.append(empty("No sessions yet. Tap New to start one.")); - return; - } - const shown = rows - .filter((s) => !view.hiddenStates.has(s.state) && !view.hiddenAgents.has(s.harness)) - .sort(compareRows); - if (shown.length === 0) { - list.append(empty("Nothing matches the filters.")); - return; - } - if (view.sort === "folder") { - // one group per folder, headed by its name and path, like the sidebar's folder groups - let group = null; - let path = null; - for (const s of shown) { - if (s.project !== path) { - path = s.project; - const head = document.createElement("div"); - head.className = "group-head"; - const name = document.createElement("b"); - name.textContent = folder(path); - const full = document.createElement("span"); - full.textContent = path; - head.append(name, full); - group = document.createElement("div"); - group.className = "group"; - list.append(head, group); - } - group.append(row(s)); - } - } else { - const group = document.createElement("div"); - group.className = "group"; - for (const s of shown) group.append(row(s)); - list.append(group); - } -} - -function empty(text) { - const p = document.createElement("p"); - p.className = "empty"; - p.textContent = text; - return p; -} - -// play: a triangle drawn with a thick round-joined stroke, so its corners are soft -const ICON_PLAY = ''; -const ICON_STOP = ''; - -// A row: the name and where on the left (tap to open a running session), its status and -// one action on the right: play resumes an ended session, stop closes a running one. -function row(s) { - const el = document.createElement("div"); - el.className = "row" + (s.ended ? " ended" : ""); - const main = document.createElement(s.ended ? "div" : "a"); - main.className = "row-main"; - if (!s.ended) { - main.href = "#s=" + encodeURIComponent(s.name); - main.onclick = () => { navigation = "open"; }; // the link itself goes there - } - const name = document.createElement("span"); - name.className = "name"; - name.textContent = label(s); - const where = document.createElement("span"); - where.className = "where"; - // an ended agent without a saved conversation starts a new one when resumed - const fresh = s.ended && !s.conversation && s.harness !== "shell" ? " · new conversation" : ""; - where.textContent = (AGENT[s.harness] || s.harness) + (view.sort === "folder" ? "" : " · " + folder(s.project)) + fresh; - main.append(name, where); - const side = document.createElement("div"); - side.className = "row-side"; - const action = document.createElement("button"); - action.type = "button"; - if (s.ended) { - action.className = "btn play"; - action.setAttribute("aria-label", "Resume " + label(s)); - action.innerHTML = ICON_PLAY; - action.onclick = () => resumeSession(s, action); - side.append(status("ENDED"), action); - } else { - action.className = "btn stop" + (closable(s.state) ? "" : " unavailable"); - action.setAttribute("aria-label", "Close " + label(s)); - action.innerHTML = ICON_STOP; - // close from the list: open the session, so you see what you close, and ask there - action.onclick = () => { - closeOnOpen = s.name; - openView("s=" + encodeURIComponent(s.name)); - }; - side.append(status(s.state), action); - } - el.append(main, side); - return el; -} - -/** Whether Close is on offer: only an idle session (the server checks again). */ -function closable(state) { - return state === "IDLE"; -} - -function status(state) { - const el = document.createElement("span"); - setStatus(el, state); - return el; -} - -function setStatus(el, state) { - el.className = "status " + (state || ""); - el.textContent = state ? (STATUS[state]?.label || state.toLowerCase()) : ""; -} - -async function resumeSession(s, button) { - button.disabled = true; - try { - const result = await api("/api/resume", { session: s.name }); - openView("s=" + encodeURIComponent(result.name)); - } catch (e) { - failed("list-problem", e); - button.disabled = false; - } -} - -// ------------------------------------------------------------------ one session - -let lastView = null; -let stickToBottom = true; -let closeOnOpen = null; // a session to offer closing once its view is open (from the list) - -function showSession(name) { - current = name; - retryDelay = 1000; - show("session-view"); - problem("session-problem", ""); - const known = screens.get(name) || sessions.find((s) => s.name === name); - $("session-title").textContent = known ? (known.display || known.name) : name; - setSessionState(known ? known.state : ""); - drawnStyled = null; - $("scroller").style.background = ""; - $("scroller").style.color = ""; - $("screen").textContent = known && known.text !== undefined ? known.text : ""; - if (known && known.styled) drawStyled(known.styled); - // nothing to show yet: say it is on its way rather than leave the area black - $("connecting").hidden = !!(known && known.text && known.text.trim()); - $("progress").hidden = true; - $("history").textContent = histories.get(name) || ""; - lastView = known && known.text !== undefined ? known : null; - stickToBottom = true; - scrollToBottom(); - openStream(); - if (closeOnOpen === name) { - closeOnOpen = null; - closeFlow(name, $("session-title").textContent, true); - } -} - -function setSessionState(state) { - setStatus($("session-state"), state); - // like the sidebar, Close looks unavailable unless the session is idle - $("close-button").classList.toggle("unavailable", !closable(state)); -} - -function openStream() { - stopStream(); - const size = phoneSize(); - streamWidth = window.innerWidth; - const es = new EventSource("/api/stream?session=" + encodeURIComponent(current) - + "&cols=" + size.cols + "&rows=" + size.rows + "&styled=1"); - stream = es; - es.onmessage = (event) => { - problem("session-problem", ""); - retryDelay = 1000; - renderScreen(JSON.parse(event.data)); - }; - es.addEventListener("history", (event) => appendHistory(JSON.parse(event.data))); - es.addEventListener("exited", () => { - setSessionState("ENDED"); - stopStream(); - }); - es.addEventListener("problem", (event) => { - problem("session-problem", JSON.parse(event.data).error); - }); - es.onerror = async () => { - // Reconnect ourselves, waiting longer each time: 1 s, 2 s, 4 s … up to 15 s. EventSource - // would retry at once and forever, and a server that keeps dropping the stream would - // make the page flicker. Asking for the screen first tells a 401 or an ended session. - if (stream !== es) return; - es.close(); - const delay = retryDelay; - retryDelay = Math.min(retryDelay * 2, MAX_RETRY_DELAY); - if (delay >= 4000) problem("session-problem", "The connection keeps dropping. Trying again…"); - setTimeout(async () => { - if (stream !== es) return; // left the session, or a newer stream took over - try { - await api("/api/screen?session=" + encodeURIComponent(current)); - openStream(); - } catch (e) { - failed("session-problem", e); - if (!(e instanceof Locked)) { - // ended, or the Mac is unreachable: show it as such and stop retrying - setSessionState("ENDED"); - stopStream(); - } - } - }, delay); - }; -} - -function stopStream() { - if (stream) stream.close(); - stream = null; -} - -function scrollToBottom() { - const scroller = $("scroller"); - scroller.scrollTop = scroller.scrollHeight; -} - -function atBottom() { - const scroller = $("scroller"); - return scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight < 40; -} - -// Scrollback: the stream sends what the session still holds, then each line as it -// scrolls off the screen. Kept per session, capped so a long session stays light. -const MAX_HISTORY_CHARS = 400000; -const histories = new Map(); - -function appendHistory(chunk) { - showProgress(chunk); - if (!chunk.reset && !chunk.text) return; - const stick = atBottom(); - const el = $("history"); - let text = (chunk.reset ? "" : el.textContent) + (el.textContent && !chunk.reset && chunk.text ? "\n" : "") + chunk.text; - text = text.replace(/\n+$/, ""); - if (text.length > MAX_HISTORY_CHARS) text = text.slice(text.indexOf("\n", text.length - MAX_HISTORY_CHARS) + 1); - el.textContent = text; - histories.set(current, text); - if (stick) scrollToBottom(); -} - -// The first scrollback arrives in pieces that count up to its total: a bar while it does. -function showProgress(chunk) { - if (chunk.total === undefined || chunk.done) { - $("progress").hidden = true; - return; - } - $("progress").hidden = false; - $("progress-fill").style.width = Math.round(100 * chunk.loaded / chunk.total) + "%"; - $("progress-text").textContent = "Loading earlier output · " + size(chunk.loaded) + " of " + size(chunk.total); -} - -function size(bytes) { - if (bytes < 1024) return bytes + " B"; - if (bytes < 1024 * 1024) return Math.round(bytes / 1024) + " KB"; - return (bytes / (1024 * 1024)).toFixed(1) + " MB"; -} - -function renderScreen(view) { - if (view.name !== current && view.display !== current) return; // a late event from the last session - // keep the spinner while the screen is still blank: after the phone resizes a session, - // its program (Claude Code, say) clears and redraws, which can take a moment - $("connecting").hidden = view.text.trim().length > 0; - screens.set(current, view); - const screen = $("screen"); - const stick = stickToBottom || atBottom(); - stickToBottom = false; - $("session-title").textContent = view.display || view.name; - setSessionState(view.state); - if (view.styled) { - drawStyled(view.styled, view.columns); - } else if (screen.textContent !== view.text) { - drawnStyled = null; - screen.textContent = view.text; - } - lastView = view; - if (stick) scrollToBottom(); -} - -// The screen in colour: rows of runs, each with its colours (absent: the terminal's -// defaults, which also paint the area) and style bits (bold 1, dim 2, italic 4, -// underline 8, strikethrough 16; an underline's kind: double 32, curly 64, dotted 128, -// dashed 256), as the server draws them with the Mac's palette. -let drawnStyled = null; - -function drawStyled(styled, columns) { - const key = JSON.stringify(styled.rows); - if (key === drawnStyled) return; - drawnStyled = key; - const scroller = $("scroller"); - scroller.style.background = styled.bg; - scroller.style.color = styled.fg; - const links = findLinks(styled.rows.map((runs) => runs.map((run) => run.t).join("")), columns); - $("screen").innerHTML = styled.rows.map((runs, i) => rowHtml(runs, styled.bg, links[i])).join("\n"); -} - -// Web links on the screen, tapped to open. A long link may run on over several rows: the -// program broke it at the right edge itself (Claude Code does), going on in the next row -// at the same indent, or the terminal wrapped it (the next row then starts with it). The -// Mac window finds them the same way (Links.java). -const LINK = /https?:\/\/[^\s<>"'`]+/g; -const LINK_GOES_ON = /^[^\s<>"'`]+/; - -/** Per row, the pieces of links on it: {from, to, url}, in characters (code points). */ -function findLinks(texts, columns) { - const rows = texts.map((t) => Array.from(t)); - const found = rows.map(() => []); - const taken = rows.map(() => 0); // characters already part of a link from above - rows.forEach((chars, i) => { - const text = chars.join(""); - for (const m of text.matchAll(LINK)) { - const start = Array.from(text.slice(0, m.index)).length; - if (start < taken[i]) continue; - const base = indent(chars); - let end = start + Array.from(m[0]).length; - let raw = m[0]; - const pieces = [{ row: i, from: start, to: end }]; - for (let row = i; row + 1 < rows.length && goesOn(rows[row], end, columns); row++) { - const next = rows[row + 1]; - const at = indent(next); - // the same indent; or none, after a row filled to the edge (a terminal wrap) - if (at !== base && !(at === 0 && end === columns)) break; - const piece = next.slice(at).join("").match(LINK_GOES_ON); - if (!piece) break; - end = at + Array.from(piece[0]).length; - taken[row + 1] = end; - pieces.push({ row: row + 1, from: at, to: end }); - raw += piece[0]; - } - const url = trimLink(raw); - let cut = Array.from(raw).length - Array.from(url).length; - for (let p = pieces.length - 1; p >= 0 && cut > 0; p--) { - const drop = Math.min(cut, pieces[p].to - pieces[p].from); - pieces[p].to -= drop; - cut -= drop; - } - for (const p of pieces) if (p.to > p.from) found[p.row].push({ from: p.from, to: p.to, url }); - } - }); - return found; -} - -/** Nothing follows the link on its row, and it reaches the right edge (a program may leave - * a column or two free there). */ -function goesOn(chars, end, columns) { - return !!columns && end >= columns - 2 && chars.slice(end).join("").trim() === ""; -} - -function indent(chars) { - let n = 0; - while (n < chars.length && chars[n] === " ") n++; - return n; -} - -/** Leaves out what usually ends the sentence around a link: trailing punctuation, and a - * closing bracket the link did not open. */ -function trimLink(url) { - const count = (s, c) => s.split(c).length - 1; - for (;;) { - const last = url.slice(-1); - const pair = { ")": "(", "]": "[", "}": "{" }[last]; - if (last && ".,;:!?".includes(last)) url = url.slice(0, -1); - else if (pair && count(url, pair) < count(url, last)) url = url.slice(0, -1); - else return url; - } -} - -/** - * One row as HTML. The row is taken apart into cells and put back together so that every - * stretch of solid colour becomes one shape: a space on a coloured background is drawn as - * a full block in that colour, and neighbouring box and block cells of the same colour join - * into one run (see runSvg), whichever styled run they came from. Separate pieces meeting - * off a device pixel leave a faint seam; Claude's logo mixes blocks and coloured spaces. - */ -function rowHtml(runs, screenBackground, links = []) { - const cells = []; - for (const run of runs) { - // a background the same as the screen's is no background: Claude's logo paints part of - // its body on an explicit black, and that must still join the cells beside it - const b = run.b && run.b !== screenBackground ? run.b : null; - for (const ch of run.t) { - if (ch === " " && b) { - cells.push({ ch: "█", f: b, b: null, s: 0, tile: true }); - } else { - cells.push({ ch, f: run.f || null, b, s: run.s || 0, tile: isTile(ch.codePointAt(0)) }); - } - } - } - for (const link of links) { - for (let x = link.from; x < link.to && x < cells.length; x++) cells[x].link = link.url; - } - let html = ""; - let group = null; - const flush = () => { - if (!group) return; - const inner = group.tile ? tileHtml(group) : textHtml(group); - html += group.link ? '' + inner + "" : inner; - group = null; - }; - for (const cell of cells) { - const key = (cell.tile ? "T" : "X") + "|" + cell.f + "|" + cell.b + "|" + (cell.tile ? cell.s & 2 : cell.s) + "|" + (cell.link || ""); - if (!group || group.key !== key) { - flush(); - group = { key, tile: cell.tile, f: cell.f, b: cell.b, s: cell.s, link: cell.link, text: "", count: 0 }; - } - group.text += cell.ch; - group.count++; - } - flush(); - return html; -} - -/** A run of box and block cells: one shape across all of them, in their colour. */ -function tileHtml(group) { - let css = "width:" + group.count + "ch;"; - if (group.f) css += "color:" + group.f + ";"; - if (group.s & 2) css += "opacity:.6;"; - const shape = ''; - return group.b ? '' + shape + "" : shape; -} - -function textHtml(group) { - const text = escapeHtml(group.text); - let css = ""; - if (group.f) css += "color:" + group.f + ";"; - if (group.b) css += "background:" + group.b + ";"; - if (group.s & 1) css += "font-weight:700;"; - if (group.s & 2) css += "opacity:.6;"; - if (group.s & 4) css += "font-style:italic;"; - const lines = (group.s & 8 ? " underline" : "") + (group.s & 16 ? " line-through" : ""); - if (lines) css += "text-decoration:" + lines + underlineStyle(group.s) + ";"; - return css ? '' + text + "" : text; -} - -/** The underline's kind (double 32, curly 64, dotted 128, dashed 256) as a CSS line style. */ -function underlineStyle(bits) { - if (!(bits & 8)) return ""; - if (bits & 32) return " double"; - if (bits & 64) return " wavy"; - if (bits & 128) return " dotted"; - if (bits & 256) return " dashed"; - return ""; -} - -function escapeHtml(text) { - return text.replace(/&/g, "&").replace(//g, ">"); -} - -// ------------------------------------------------------------------ cell glyphs - -// Box drawing (U+2500–257F) and block elements (U+2580–259F) are drawn as shapes that fill -// their cell exactly, as the Mac window's BoxDrawing does: a font's glyph box is not the -// cell, so stacked rows of blocks (Claude's logo) and box borders leave gaps and steps. -// Each shape is an 8 × 16 SVG used as a mask over the text colour, one CSS class per -// character, made the first time it appears. Light lines are an eighth of the cell wide, -// heavy twice that, double lines two light strokes a light width apart. - -const GW = 8, GH = 16, LIGHT = 1, HEAVY = 2; -// URDL arm weights (0 none, 1 light, 2 heavy, 3 double; "d" dashed), as in BoxDrawing.java -const LINES_1 = ["0101", "0202", "1010", "2020", "d", "d", "d", "d", "d", "d", "d", "d", - "0110", "0210", "0120", "0220", "0011", "0012", "0021", "0022", - "1100", "1200", "2100", "2200", "1001", "1002", "2001", "2002", - "1110", "1210", "2110", "1120", "2120", "2210", "1220", "2220", - "1011", "1012", "2011", "1021", "2021", "2012", "1022", "2022", - "0111", "0112", "0211", "0212", "0121", "0122", "0221", "0222", - "1101", "1102", "1201", "1202", "2101", "2102", "2201", "2202", - "1111", "1112", "1211", "1212", "2111", "1121", "2121", "2112", - "2211", "1122", "1221", "2212", "1222", "2122", "2221", "2222"]; -const LINES_2 = ["0303", "3030", "0310", "0130", "0330", "0013", "0031", "0033", - "1300", "3100", "3300", "1003", "3001", "3003", "1310", "3130", - "3330", "1013", "3031", "3033", "0313", "0131", "0333", "1303", - "3101", "3303", "1313", "3131", "3333"]; -const LINES_3 = ["0001", "1000", "0100", "0010", "0002", "2000", "0200", "0020", - "0201", "1020", "0102", "2010"]; -// U+2596–259F: bit 1 upper left, 2 upper right, 4 lower left, 8 lower right -const QUADRANTS = [4, 8, 1, 1 | 4 | 8, 1 | 8, 1 | 2 | 4, 1 | 2 | 8, 2, 2 | 4, 2 | 4 | 8]; - -// ⏺ (U+23FA), Claude Code's bullet (it blinks while a tool runs): no monospace font has it, -// so iPhone Safari falls back to Apple Color Emoji, a grey tile wider than the cell that -// ignores the run's colour. Drawn as a dot in the text colour instead. -const RECORD = 0x23fa; - -function isTile(cp) { - return (cp >= 0x2500 && cp <= 0x259f) || cp === RECORD; -} - -const runClasses = new Map(); // run text -> class name -let glyphSheet = null; - -/** The class that draws the run {@code text} as one shape, its CSS rule added on first use. */ -function runClass(text) { - let name = runClasses.get(text); - if (!name) { - name = "g" + runClasses.size.toString(36); - runClasses.set(text, name); - if (!glyphSheet) { - glyphSheet = document.createElement("style"); - document.head.append(glyphSheet); - } - const url = "url('data:image/svg+xml;utf8," + encodeURIComponent(runSvg(text)) + "')"; - glyphSheet.append("." + name + "{-webkit-mask-image:" + url + ";mask-image:" + url + "}\n"); - } - return name; -} - -/** - * The mask for a run of tile characters side by side: one SVG spanning the whole run. - * Every solid rectangle of every character goes into ONE path. Shapes drawn separately are - * each antialiased on their own, and where two meet off a device-pixel boundary (a cell is - * 7.2 px wide, 21.6 device pixels on an iPhone) their half-covered edges leave a faint dark - * seam, every 4 or 5 cells. Within one path a shared edge is interior: no seam. - */ -function runSvg(text) { - const out = { solid: "", parts: [] }; - let i = 0; - for (const ch of text) { - glyphInto(ch.codePointAt(0), i * GW, out); - i++; - } - if (out.solid) out.parts.unshift(''); - return '' + out.parts.join("") + ""; -} - -function glyphSvg(cp) { - return runSvg(String.fromCodePoint(cp)); -} - -/** One character's shapes, {@code dx} units to the right, added to {@code out}. */ -function glyphInto(cp, dx, out) { - const parts = out.parts; - const rect = (x, y, w, h, opacity) => { - if (!(w > 0 && h > 0)) return; - if (opacity) { - parts.push(''); - } else { - out.solid += "M" + (x + dx) + " " + y + "h" + w + "v" + h + "h" + (-w) + "z"; - } - }; - const stroke = (d) => parts.push(''); - if (cp === RECORD) { - // a dot about a lowercase letter wide, centred on the lowercase height - parts.push(''); - } else if (cp >= 0x2580) { - block(cp, rect); - } else { - let arms = null; - if (cp <= 0x254b) arms = LINES_1[cp - 0x2500]; - else if (cp >= 0x2550 && cp <= 0x256c) arms = LINES_2[cp - 0x2550]; - else if (cp >= 0x2574) arms = LINES_3[cp - 0x2574]; - if (arms && arms !== "d") { - const [u, r, d, l] = [...arms].map(Number); - if (u === 3 || r === 3 || d === 3 || l === 3) doubleLines(rect, u, r, d, l); - else lines(rect, u, r, d, l); - } else if ([0x2504, 0x2505, 0x2508, 0x2509, 0x254c, 0x254d].includes(cp)) { - dashes(rect, cp >= 0x254c ? 2 : cp >= 0x2508 ? 4 : 3, (cp & 1) === 0 ? LIGHT : HEAVY, true); - } else if ([0x2506, 0x2507, 0x250a, 0x250b, 0x254e, 0x254f].includes(cp)) { - dashes(rect, cp >= 0x254c ? 2 : cp >= 0x2508 ? 4 : 3, (cp & 1) === 0 ? LIGHT : HEAVY, false); - } else if (cp >= 0x256d && cp <= 0x2570) { - // ╭ ╮ ╯ ╰: straight to the cell edges, rounded through the centre - const cx = GW / 2, cy = GH / 2, radius = Math.min(GW, GH) / 2; - const toRight = cp === 0x256d || cp === 0x2570, toBottom = cp === 0x256d || cp === 0x256e; - const ex = toRight ? GW : 0, ey = toBottom ? GH : 0; - const sx = toRight ? Math.min(cx + radius, ex) : Math.max(cx - radius, ex); - const sy = toBottom ? Math.min(cy + radius, ey) : Math.max(cy - radius, ey); - stroke("M" + cx + " " + ey + "L" + cx + " " + sy + "Q" + cx + " " + cy + " " + sx + " " + cy + "L" + ex + " " + cy); - } else if (cp >= 0x2571 && cp <= 0x2573) { - if (cp !== 0x2572) stroke("M" + GW + " 0L0 " + GH); - if (cp !== 0x2571) stroke("M0 0L" + GW + " " + GH); - } - } -} - -function thickness(weight) { - return weight === 2 ? HEAVY : weight === 0 ? 0 : LIGHT; -} - -// Light and heavy arms: each reaches past the centre by the perpendicular strokes' half -// width, so corners and junctions are filled. -function lines(rect, u, r, d, l) { - const tu = thickness(u), tr = thickness(r), td = thickness(d), tl = thickness(l); - const vertical = Math.max(tu, td), horizontal = Math.max(tl, tr); - if (tu > 0) { - const band = horizontal > 0 ? horizontal : tu; - rect((GW - tu) / 2, 0, tu, (GH - band) / 2 + band); - } - if (td > 0) { - const band = horizontal > 0 ? horizontal : td; - const start = (GH - band) / 2; - rect((GW - td) / 2, start, td, GH - start); - } - if (tl > 0) { - const band = vertical > 0 ? vertical : tl; - rect(0, (GH - tl) / 2, (GW - band) / 2 + band, tl); - } - if (tr > 0) { - const band = vertical > 0 ? vertical : tr; - const start = (GW - band) / 2; - rect(start, (GH - tr) / 2, GW - start, tr); - } -} - -// A double arm is two light strokes at ±t from the single stroke; where it meets a -// perpendicular arm its outer stroke runs to that arm's far stroke, its inner to the near. -function doubleLines(rect, u, r, d, l) { - const t = LIGHT; - const up = u > 0, right = r > 0, down = d > 0, left = l > 0; - const vx = (GW - t) / 2, hy = (GH - t) / 2; - const vDouble = u === 3 || d === 3, hDouble = l === 3 || r === 3; - const xa = vDouble ? vx - t : vx, xb = vDouble ? vx + t : vx; - const ya = hDouble ? hy - t : hy, yb = hDouble ? hy + t : hy; - const v = (x, y0, y1) => rect(x, y0, t, y1 - y0); - const h = (y, x0, x1) => rect(x0, y, x1 - x0, t); - if (up) { - if (u === 3) { v(xa, 0, (left ? ya : yb) + t); v(xb, 0, (right ? ya : yb) + t); } - else v(vx, 0, left && right ? (down ? yb : ya) + t : yb + t); - } - if (down) { - if (d === 3) { v(xa, left ? yb : ya, GH); v(xb, right ? yb : ya, GH); } - else v(vx, left && right ? (up ? ya : yb) : ya, GH); - } - if (left) { - if (l === 3) { h(ya, 0, (up ? xa : xb) + t); h(yb, 0, (down ? xa : xb) + t); } - else h(hy, 0, up && down ? (right ? xb : xa) + t : xb + t); - } - if (right) { - if (r === 3) { h(ya, up ? xb : xa, GW); h(yb, down ? xb : xa, GW); } - else h(hy, up && down ? (left ? xa : xb) : xa, GW); - } -} - -function dashes(rect, n, t, horizontal) { - const length = horizontal ? GW : GH; - const slot = length / n; - const gap = Math.max(0.5, slot / 3); - for (let i = 0; i < n; i++) { - const a = i * slot + gap / 2, b = (i + 1) * slot - gap / 2; - if (b <= a) continue; - if (horizontal) rect(a, (GH - t) / 2, b - a, t); - else rect((GW - t) / 2, a, t, b - a); - } -} - -function block(cp, rect) { - if (cp === 0x2580) rect(0, 0, GW, GH / 2); - else if (cp >= 0x2581 && cp <= 0x2588) { const top = GH - GH * (cp - 0x2580) / 8; rect(0, top, GW, GH - top); } - else if (cp >= 0x2589 && cp <= 0x258f) rect(0, 0, GW * (8 - (cp - 0x2588)) / 8, GH); - else if (cp === 0x2590) rect(GW / 2, 0, GW / 2, GH); - else if (cp >= 0x2591 && cp <= 0x2593) rect(0, 0, GW, GH, (cp - 0x2590) * 0.25); - else if (cp === 0x2594) rect(0, 0, GW, GH / 8); - else if (cp === 0x2595) rect(GW - GW / 8, 0, GW / 8, GH); - else { - const bits = QUADRANTS[cp - 0x2596]; - if (bits & 1) rect(0, 0, GW / 2, GH / 2); - if (bits & 2) rect(GW / 2, 0, GW / 2, GH / 2); - if (bits & 4) rect(0, GH / 2, GW / 2, GH / 2); - if (bits & 8) rect(GW / 2, GH / 2, GW / 2, GH / 2); - } -} - - -// The columns and rows that fit the screen area at its font size: the session runs at -// this size while the phone watches it (the server gives the old size back afterwards). -let streamWidth = 0; - -function phoneSize() { - const scroller = $("scroller"); - const box = getComputedStyle(scroller); - const style = getComputedStyle($("screen")); - const width = scroller.clientWidth - parseFloat(box.paddingLeft) - parseFloat(box.paddingRight); - const height = scroller.clientHeight - parseFloat(box.paddingTop) - parseFloat(box.paddingBottom); - const ctx = phoneSize.ctx || (phoneSize.ctx = document.createElement("canvas").getContext("2d")); - ctx.font = style.fontSize + " " + style.fontFamily; - const charWidth = ctx.measureText("M".repeat(20)).width / 20; - const fontSize = parseFloat(style.fontSize); - const lineHeight = parseFloat(style.lineHeight) || fontSize * 1.35; - return { - cols: Math.max(20, Math.floor(width / charWidth)), - rows: Math.max(5, Math.floor(height / lineHeight)), - }; -} - -async function pressKeys(keys) { - try { - await api("/api/keys", { session: current, keys }); - } catch (e) { - failed("session-problem", e); - } -} - -async function sendMessage(event) { - event.preventDefault(); - const box = $("message"); - const text = box.value; - $("send-button").disabled = true; - try { - // an empty message just presses Enter - await api("/api/send", { session: current, text, enter: true }); - box.value = ""; - growMessage(); - } catch (e) { - failed("session-problem", e); - } finally { - $("send-button").disabled = false; - } -} - -// Attach: the file goes to Microhm, which keeps it (in the session's project, under a -// .microhm folder git ignores) and answers where; that path goes into -// the message at the cursor, so the agent can open it (a screenshot of the problem, say). -async function attachFiles() { - const input = $("attach-input"); - const files = Array.from(input.files || []); - input.value = ""; // picking the same file again still fires - if (!files.length) return; - const button = $("attach-button"); - button.disabled = true; - button.classList.add("busy"); - try { - for (const file of files) { - insertInMessage(await uploadFile(file)); - } - } catch (e) { - failed("session-problem", e); - } finally { - button.disabled = false; - button.classList.remove("busy"); - } -} - -async function uploadFile(file) { - let response; - try { - // into the session's project, where its agent can read it without asking - response = await fetch("/api/upload?session=" + encodeURIComponent(current || "") - + "&name=" + encodeURIComponent(file.name || ""), { - method: "POST", - headers: { "Content-Type": file.type || "application/octet-stream" }, - body: file, - }); - } catch (e) { - throw new Error("Can't reach Microhm. Is it running, and is this phone on your network?"); - } - if (response.status === 401) throw new Locked(); - const data = await response.json().catch(() => ({})); - if (!response.ok || !data.path) throw new Error(data.error || response.statusText || "The file was not sent"); - return data.path; -} - -// Puts text at the cursor, with a space on either side where it would touch a word. -function insertInMessage(text) { - const box = $("message"); - const start = box.selectionStart ?? box.value.length; - const end = box.selectionEnd ?? start; - const before = box.value.slice(0, start); - const after = box.value.slice(end); - const lead = before && !/\s$/.test(before) ? " " : ""; - const trail = after.startsWith(" ") ? "" : " "; - box.value = before + lead + text + trail + after; - const caret = (before + lead + text + trail).length; - box.setSelectionRange(caret, caret); - growMessage(); -} - -function growMessage() { - const box = $("message"); - // Measuring collapses the box for a moment; the screen above grows, its scroll position - // is clamped, and the box growing back would leave the screen a line up from where it was, - // until the next screen update scrolled it back: the screen shook with every keystroke. - // Keep the screen's distance from its bottom instead (the reader's place, or the bottom). - const scroller = $("scroller"); - const fromBottom = scroller.scrollHeight - scroller.clientHeight - scroller.scrollTop; - box.style.height = "auto"; - box.style.height = box.scrollHeight + "px"; - scroller.scrollTop = scroller.scrollHeight - scroller.clientHeight - fromBottom; -} - -// Close asks first, the way Microhm's Close does: a session whose agent is working or -// waiting for you, or that has a program running, is not closed. From the session view -// it goes back to the list afterwards; from the list it stays. -let sheetToken = 0; // which question the sheet is showing: a late answer to an old one is ignored - -async function closeFlow(name, title, fromSession) { - const problemId = fromSession ? "session-problem" : "list-problem"; - // the sheet comes up at once; the Mac's answer (a second or two) fills it in - const token = showSheet({ title: "Close " + title + "?", text: "Checking whether it can close…", busy: true }); - let check; - try { - check = await api("/api/close-check?session=" + encodeURIComponent(name)); - } catch (e) { - if (token !== sheetToken) return; - hideSheet(); - return failed(problemId, e); - } - if (token !== sheetToken) return; // closed, or another question took its place - if (!check.closable) { - showSheet({ title: "Can't close " + title + " now", text: check.reason, cancel: "OK" }); - return; - } - showSheet({ - title: "Close " + title + "?", - text: "The agent is asked to quit and its shell exits. You can resume it later from the list.", - confirm: "Close", - onConfirm: async (button) => { - button.disabled = true; - button.textContent = "Closing…"; - // stop watching first: the session ending is expected, not something to report - if (fromSession && current === name) { - stopStream(); - problem("session-problem", ""); - } - try { - await api("/api/close", { session: name }); - hideSheet(); - if (fromSession) toList(); else refreshList(); - } catch (e) { - hideSheet(); - failed(problemId, e); - } - }, - }); -} - -// ------------------------------------------------------------------ sheet - -function showSheet({ title, text, confirm, onConfirm, cancel, busy }) { - sheetToken++; - $("sheet-title").textContent = title; - $("sheet-text").textContent = text || ""; - $("sheet-spinner").hidden = !busy; - const confirmButton = $("sheet-confirm"); - confirmButton.hidden = !confirm; - confirmButton.disabled = false; - confirmButton.textContent = confirm || ""; - confirmButton.onclick = onConfirm ? () => onConfirm(confirmButton) : null; - $("sheet-cancel").textContent = cancel || "Cancel"; - $("sheet").hidden = false; - return sheetToken; -} - -function hideSheet() { - sheetToken++; - $("sheet").hidden = true; -} - -// ------------------------------------------------------------------ new session - -let harnesses = null; - -async function showNew() { - show("new-view"); - problem("new-problem", ""); - try { - if (!harnesses) harnesses = (await api("/api/harnesses")).harnesses; - if (sessions.length === 0 && ended.length === 0) { - const data = await api("/api/sessions"); - sessions = data.sessions; - ended = data.ended || []; - } - } catch (e) { - failed("new-problem", e); - } - const select = $("new-harness"); - if (select.options.length === 0 && harnesses) { - for (const id of harnesses) select.append(new Option(AGENT[id] || id, id)); - select.value = readPref("harness") || "claude-code"; - } - const projects = [...new Set(allRows().map((s) => s.project).filter(Boolean))].sort(); - $("projects").replaceChildren(...projects.map((p) => new Option(p))); - if (!$("new-project").value) $("new-project").value = readPref("project") || ""; -} - -async function startSession(event) { - event.preventDefault(); - const body = { - harness: $("new-harness").value, - project: $("new-project").value.trim(), - }; - const name = $("new-name").value.trim(); - const prompt = $("new-prompt").value.trim(); - if (name) body.name = name; - if (prompt) body.prompt = prompt; - $("start-button").disabled = true; - try { - const result = await api("/api/spawn", body); - writePref("harness", body.harness); - writePref("project", body.project); - $("new-name").value = ""; - $("new-prompt").value = ""; - // the reply reads " started (...)"; the session takes the form's place in history - const started = result.text.split(" ")[0]; - replaceView("s=" + encodeURIComponent(started)); - } catch (e) { - failed("new-problem", e); - } finally { - $("start-button").disabled = false; - } -} - -// ------------------------------------------------------------------ small things - -function readPref(key) { - try { return localStorage.getItem("mhm." + key); } catch (e) { return null; } -} - -function writePref(key, value) { - try { localStorage.setItem("mhm." + key, value); } catch (e) { /* private mode */ } -} - -function readJson(key) { - try { return JSON.parse(readPref(key)); } catch (e) { return null; } -} - -function writeJson(key, value) { - writePref(key, JSON.stringify(value)); -} - -// ------------------------------------------------------------------ start - -$("new-button").onclick = () => openView("new"); -$("view-button").onclick = toggleControls; -$("back-button").onclick = toList; -$("cancel-new").onclick = toList; -$("close-button").onclick = () => closeFlow(current, $("session-title").textContent, true); -$("sheet-cancel").onclick = hideSheet; -$("sheet").addEventListener("click", (event) => { if (event.target === $("sheet")) hideSheet(); }); -$("sort").addEventListener("click", (event) => { - const button = event.target.closest("button[data-sort]"); - if (!button) return; - view.sort = button.dataset.sort; - saveView(); -}); -$("direction").onclick = () => { - view.descending = !view.descending; - saveView(); -}; -// the keypad stays out of the way until asked for; this phone remembers if it was open -function setKeysOpen(open) { - $("keys").hidden = !open; - $("keys-button").classList.toggle("on", open); - $("keys-button").setAttribute("aria-expanded", String(open)); - writePref("keys", open ? "1" : "0"); -} -setKeysOpen(readPref("keys") === "1"); -$("keys-button").onclick = () => setKeysOpen($("keys").hidden); -$("keys").addEventListener("click", (event) => { - const button = event.target.closest("button[data-keys]"); - if (button) pressKeys([button.dataset.keys]); -}); -$("attach-button").onclick = () => $("attach-input").click(); -$("attach-input").addEventListener("change", attachFiles); -$("compose").addEventListener("submit", sendMessage); -$("message").addEventListener("input", growMessage); -$("new-form").addEventListener("submit", startSession); -window.addEventListener("hashchange", route); -// Turning the phone changes the width: ask for the new size. The keyboard only changes -// the height, and must not shrink the session. -window.addEventListener("resize", () => { - if (current && !$("session-view").hidden && stream && Math.abs(window.innerWidth - streamWidth) > 20) { - openStream(); - } -}); -// Safari drops the stream while the phone sleeps; pick it up again on return -document.addEventListener("visibilitychange", () => { - if (document.visibilityState === "visible" && current && !$("session-view").hidden - && (!stream || stream.readyState === EventSource.CLOSED)) { - openStream(); - } -}); - -(async () => { - if (location.hash.startsWith("#k=")) await login(location.hash.slice(3)); - route(); -})(); diff --git a/swift/Sources/MicrohmCore/Resources/web/icon.png b/swift/Sources/MicrohmCore/Resources/web/icon.png deleted file mode 100644 index df604a0..0000000 Binary files a/swift/Sources/MicrohmCore/Resources/web/icon.png and /dev/null differ diff --git a/swift/Sources/MicrohmCore/Resources/web/index.html b/swift/Sources/MicrohmCore/Resources/web/index.html deleted file mode 100644 index 48d78fb..0000000 --- a/swift/Sources/MicrohmCore/Resources/web/index.html +++ /dev/null @@ -1,140 +0,0 @@ - - - - - - - - - - - - - -Microhm - - - - - - - - - - - - - - - - - - - - - diff --git a/swift/Sources/MicrohmCore/Resources/web/manifest.webmanifest b/swift/Sources/MicrohmCore/Resources/web/manifest.webmanifest deleted file mode 100644 index 71db924..0000000 --- a/swift/Sources/MicrohmCore/Resources/web/manifest.webmanifest +++ /dev/null @@ -1,9 +0,0 @@ -{ - "name": "Microhm", - "short_name": "Microhm", - "start_url": "/", - "display": "standalone", - "background_color": "#f2f2f7", - "theme_color": "#f2f2f7", - "icons": [{ "src": "icon.png", "sizes": "180x180", "type": "image/png" }] -} diff --git a/swift/Sources/MicrohmCore/control/DaemonCompat.swift b/swift/Sources/MicrohmCore/control/DaemonCompat.swift deleted file mode 100644 index 5a1b21c..0000000 --- a/swift/Sources/MicrohmCore/control/DaemonCompat.swift +++ /dev/null @@ -1,89 +0,0 @@ -import Foundation -import MicrohmMux -import MicrohmShared - -/// What the running daemon is known not to support. The daemon outlives app upgrades — it -/// keeps running until its last session ends — so the controller may talk to one that -/// predates input, wait, watch or annotated capture. The first refusal of a feature -/// (`isUnsupported`) is remembered for that daemon, identified by the pid its ping -/// reports, so the controller stops asking and takes its fallback at once; everything is -/// forgotten once a different daemon (or none) answers. -/// -/// Thread-safe; never holds its lock across a daemon round trip. -final class DaemonCompat: @unchecked Sendable { - - /// A protocol feature newer daemons have and old ones refuse. - enum Feature: String { - case ANNOTATED_CAPTURE, INPUT, WAIT, WATCH - } - - private let pidSource: () throws -> Int64? - private let lock = NSLock() - private var missing: Set = [] - /// The daemon `missing` describes; -1 = unknown (its ping did not answer). - private var missingPid: Int64 = -1 - - init(_ pid: @escaping () throws -> Int64?) { - self.pidSource = pid - } - - /// Whether `error` is a daemon's refusal of an op it predates. - static func isUnsupported(_ error: Error) -> Bool { - (error as? SessionServerException)?.isUnsupported ?? false - } - - /// Whether `feature` is worth trying: not known to be missing from the running daemon. - func has(_ feature: Feature) -> Bool { - lock.lock(); defer { lock.unlock() } - return !missing.contains(feature) - } - - /// The old daemon's pid as its ping reported it, -1 when unknown. - func pid() -> Int64 { - lock.lock(); defer { lock.unlock() } - return missingPid - } - - /// Records that the running daemon refused `feature`; true the first time (for this - /// daemon), so the caller can log it once. - @discardableResult - func markMissing(_ feature: Feature) -> Bool { - let current = ping() - lock.lock(); defer { lock.unlock() } - if missing.isEmpty { - missingPid = current - } - let first = missing.insert(feature).inserted - if first && missing.count == 1 { - Log.info("the running daemon (pid \(missingPid)) predates \(feature.rawValue); micro-harness-manager " - + "falls back until it is replaced (once every session has ended)", tag: "control") - } - return first - } - - /// Forgets what was missing once the daemon that lacked it is gone: a different pid (or - /// none) answers the ping. A no-op — no round trip — while nothing is missing. - func revalidate() { - lock.lock() - if missing.isEmpty { - lock.unlock() - return - } - let known = missingPid - lock.unlock() - let current = ping() - lock.lock(); defer { lock.unlock() } - if current < 0 || current != known { - if !missing.isEmpty { - Log.info("the daemon changed (pid \(known) -> \(current < 0 ? "none" : String(current))); trying " - + "every feature again", tag: "control") - } - missing.removeAll() - missingPid = -1 - } - } - - private func ping() -> Int64 { - ((try? pidSource()) ?? nil) ?? -1 - } -} diff --git a/swift/Sources/MicrohmCore/control/DaemonControl.swift b/swift/Sources/MicrohmCore/control/DaemonControl.swift deleted file mode 100644 index 890cfcb..0000000 --- a/swift/Sources/MicrohmCore/control/DaemonControl.swift +++ /dev/null @@ -1,145 +0,0 @@ -import Foundation -import MicrohmMux - -/// What the `SessionController` needs from the session daemon — a seam so tests can drive -/// the controller without a daemon. The production implementation is -/// `ClientDaemonControl` over the app's `SessionServerClient`. Every call may block on a -/// socket round trip and may throw (no server, no such session, a refused request); the -/// controller turns those into tool errors. -/// -/// A daemon outlives app upgrades, so the one running may predate some of these calls -/// (input, wait, watch, label, capture formats other than text, capture history): it -/// refuses them with a `SessionServerException` whose `isUnsupported` is true, and capture -/// reports `outputBytes` as -1 (unknown). The controller degrades on those. -public protocol DaemonControl: AnyObject { - - /// Every session the daemon hosts; empty when no daemon runs. - func list() throws -> [SessionInfo] - - /// The screen in `format`; nil when the session (or the daemon) is gone. - func capture(_ name: String, _ format: CaptureFormat) throws -> SessionCapture? - - /// `capture` plus the scrollback lines added after the first `since` ever added, those - /// still held (`SessionCapture.history`): pass back the previous capture's `added` to - /// get each line once. A daemon that predates history refuses it as unsupported. - func captureSince(_ name: String, _ format: CaptureFormat, _ since: Int64) throws -> SessionCapture? - - /// `text` (nil = none) pasted or typed, then the named `keys` (nil or empty = none). - /// With `requireBracketedPaste` a paste into a program that has not enabled bracketed - /// paste is refused with nothing written — a `SessionServerException` whose message is - /// `MuxProtocol.ERROR_BRACKETED_PASTE_DISABLED` — instead of being typed raw. An unknown - /// key name fails before anything is written. - func input(_ name: String, _ text: String?, _ paste: Bool, _ requireBracketedPaste: Bool, _ keys: [String]?) throws - - /// Blocks until the output is quiet; see `Session.awaitQuiet`. - func awaitQuiet(_ name: String, _ sinceBytes: Int64, _ quietMs: Int64, _ timeoutMs: Int64) throws -> WaitResult - - /// Streams the events of every session, including later ones, to `onEvent` until - /// closed or until the daemon ends the stream (`DaemonWatch.isOpen` false). - func watch(_ quietMs: Int64, _ onEvent: @escaping (SessionEvent) -> Void) throws -> DaemonWatch - - /// The old `send-keys` op every daemon supports: `text` typed as is (not a paste — a - /// newline in it submits), then when `enter` the server's 400 ms pause and Enter. Only - /// used when the daemon predates `input`. - func sendKeys(_ name: String, _ text: String, _ enter: Bool) throws - - /// Resizes `name`'s terminal for every viewer: a moment's attach at that size, which - /// the daemon applies and keeps after the detach. - func resize(_ name: String, _ columns: Int, _ rows: Int) throws - - /// The running daemon's process id (from ping); nil when none answers. - func daemonPid() throws -> Int64? - - /// Whether a daemon answers a ping right now — what tells "the session is gone" from - /// "the daemon is unreachable" when `list` or `capture` comes back empty. - func ping() throws -> Bool - - func kill(_ name: String) throws - - /// Merges `changes` into the session's labels (a nil value removes a key). - func label(_ name: String, _ changes: [String: String?]) throws -} - -public extension DaemonControl { - func input(_ name: String, _ text: String?, _ paste: Bool, _ keys: [String]?) throws { - try input(name, text, paste, false, keys) - } - - func resize(_ name: String, _ columns: Int, _ rows: Int) throws { - throw SessionHostException("resize is not supported") - } -} - -/// A live event stream. -public protocol DaemonWatch: AnyObject { - var isOpen: Bool { get } - func close() -} - -/// `DaemonControl` over the daemon client library — a pass-through; the client never -/// spawns a daemon for any of these calls. -public final class ClientDaemonControl: DaemonControl, @unchecked Sendable { - - private let client: SessionServerClient - - public init(_ client: SessionServerClient) { - self.client = client - } - - public func list() throws -> [SessionInfo] { - try client.list() - } - - public func capture(_ name: String, _ format: CaptureFormat) throws -> SessionCapture? { - try client.capture(name, format: format) - } - - public func captureSince(_ name: String, _ format: CaptureFormat, _ since: Int64) throws -> SessionCapture? { - try client.captureSince(name, format: format, since: since) - } - - public func input(_ name: String, _ text: String?, _ paste: Bool, _ requireBracketedPaste: Bool, - _ keys: [String]?) throws { - try client.input(name, text: text, paste: paste, requireBracketedPaste: requireBracketedPaste, keys: keys) - } - - public func awaitQuiet(_ name: String, _ sinceBytes: Int64, _ quietMs: Int64, _ timeoutMs: Int64) throws -> WaitResult { - try client.awaitQuiet(name, sinceBytes: sinceBytes, quietMs: quietMs, timeoutMs: timeoutMs) - } - - public func watch(_ quietMs: Int64, _ onEvent: @escaping (SessionEvent) -> Void) throws -> DaemonWatch { - ClientWatch(try client.watch(names: nil, quietMs: quietMs, onEvent: onEvent)) - } - - public func sendKeys(_ name: String, _ text: String, _ enter: Bool) throws { - try client.sendKeys(name, text: text, enter: enter) - } - - public func resize(_ name: String, _ columns: Int, _ rows: Int) throws { - // attaching at a size resizes the session; closing detaches and the size stays - try client.attach(name, columns: columns, rows: rows).close() - } - - public func daemonPid() throws -> Int64? { - try client.ping()?.pid - } - - public func ping() throws -> Bool { - try client.isServerRunning() - } - - public func kill(_ name: String) throws { - try client.kill(name) - } - - public func label(_ name: String, _ changes: [String: String?]) throws { - _ = try client.label(name, changes: changes) - } - - private final class ClientWatch: DaemonWatch { - let watch: SessionServerClient.Watch - init(_ watch: SessionServerClient.Watch) { self.watch = watch } - var isOpen: Bool { watch.isOpen } - func close() { watch.close() } - } -} diff --git a/swift/Sources/MicrohmCore/control/HarnessTranscripts.swift b/swift/Sources/MicrohmCore/control/HarnessTranscripts.swift deleted file mode 100644 index 6b0c232..0000000 --- a/swift/Sources/MicrohmCore/control/HarnessTranscripts.swift +++ /dev/null @@ -1,86 +0,0 @@ -import Foundation - -/// Finds a session's conversation transcript on disk, for the `list` tool. May block for a -/// moment (Codex is found through `lsof`); never throws. -/// -/// - project: the session's project directory -/// - harnessSessionId: the harness's own conversation id when known -/// - paneProcessId: the PID of the session's shell, or -1 -public typealias TranscriptLocator = (_ harness: HarnessType, _ project: URL, _ harnessSessionId: String?, - _ paneProcessId: Int64) -> URL? - -public enum TranscriptLocators { - public static let none: TranscriptLocator = { _, _, _, _ in nil } -} - -/// The transcript locations the app knows: -/// - Codex: the rollout file its process has open (found from the pane's process tree, see -/// `CodexSessionNameResolver.transcript`); -/// - Claude Code: its per-project JSONL directory (`ClaudeProjects`): the session's own -/// `.jsonl` when the id is known (nothing until Claude has written it), else the -/// project's newest file — which the caller must not present as this session's when other -/// Claude sessions share the project; -/// - Muse: the `session.jsonl` of the session directory whose lock its process holds open -/// (`MuseSessions`); -/// - Grok: the `chat_history.jsonl` of the session its process registered in -/// `active_sessions.json` (`GrokSessions`). -/// Other harnesses have none (yet). -public final class HarnessTranscripts: @unchecked Sendable { - - private let claudeProjects: URL - private let codex: CodexSessionNameResolver - private let muse: (Int64) -> URL? - private let grok: (Int64) -> URL? - - /// - muse: a pane's Muse transcript, from the pane's shell pid - /// - grok: a pane's Grok transcript, from the pane's shell pid - public init(_ claudeProjects: URL, _ codex: CodexSessionNameResolver, - _ muse: @escaping (Int64) -> URL? = { _ in nil }, _ grok: @escaping (Int64) -> URL? = { _ in nil }) { - self.claudeProjects = claudeProjects - self.codex = codex - self.muse = muse - self.grok = grok - } - - /// `~/.claude/projects` (or `$CLAUDE_CONFIG_DIR/projects`), the default Codex home, - /// Muse's sessions under its data directory and `$GROK_HOME`. - public static func standard() -> HarnessTranscripts { - let museRoot = MuseSessions.root() - let grokHome = GrokSessions.home() - let museLocator = OpenFileLocator.overLsof(MuseSessions.isExecutable) { MuseSessions.transcriptOf(museRoot, $0) } - return HarnessTranscripts(ClaudeProjects.root(), CodexSessionNameResolver(), - { museLocator.apply($0) }, { grokTranscript(grokHome, $0) }) - } - - /// The newest transcript of the Grok processes under the pane. - static func grokTranscript(_ grokHome: URL, _ paneProcessId: Int64) -> URL? { - OpenFileLocator.processes(paneProcessId, GrokSessions.isExecutable) - .compactMap { GrokSessions.transcript(grokHome, $0.pid, $0.startMillis) } - .max { (PathCompat.lastModifiedMillis($0) ?? 0) < (PathCompat.lastModifiedMillis($1) ?? 0) } - } - - /// As a `TranscriptLocator`. - public var locator: TranscriptLocator { - { [self] harness, project, id, pid in transcript(harness, project, id, pid) } - } - - public func transcript(_ harness: HarnessType, _ project: URL, _ harnessSessionId: String?, - _ paneProcessId: Int64) -> URL? { - switch harness { - case .codex: return codex.transcript(paneProcessId) - case .claudeCode: return claude(project, harnessSessionId) - case .muse: return paneProcessId > 0 ? muse(paneProcessId) : nil - case .grok: return paneProcessId > 0 ? grok(paneProcessId) : nil - default: return nil - } - } - - private func claude(_ project: URL, _ harnessSessionId: String?) -> URL? { - if let id = harnessSessionId { - // never another session's file: a known id whose conversation has no message - // yet has no transcript - return ClaudeProjects.transcript(claudeProjects, project, id) - } - return ClaudeProjects.newest(claudeProjects, project) - } -} diff --git a/swift/Sources/MicrohmCore/control/ScreenDiff.swift b/swift/Sources/MicrohmCore/control/ScreenDiff.swift deleted file mode 100644 index 2691b20..0000000 --- a/swift/Sources/MicrohmCore/control/ScreenDiff.swift +++ /dev/null @@ -1,127 +0,0 @@ -import Foundation - -/// Pure text helpers behind the `read` tool: turning an annotated capture into the lines an -/// agent sees and the plain text state detection compares, working out which lines are new -/// since the caller's previous read, and capping the output. Lengths count UTF-16 units, -/// as Java's `String.length()` did. -enum ScreenDiff { - - /// the daemon's annotated-capture markers (see `HeadlessTerminal.annotatedText`). - static let SELECTION_MARKER = "▶ " - static let CURSOR_MARKER = "▮" - - /// An incremental read needs at least this many non-blank lines of overlap. - static let MIN_OVERLAP = 3 - /// More new lines than this share of the screen and the whole screen is returned. - static let MAX_NEW_SHARE = 0.6 - - /// The new lines of a read and how many unchanged lines precede them on screen. - struct Delta: Equatable { - let unchangedAbove: Int - let lines: [String] - } - - /// The screen's lines with trailing blank lines dropped (the empty rows below the - /// content), markers kept: what a read shows. - static func bodyLines(_ annotated: String) -> [String] { - var lines = JavaText.lines(annotated) - while let last = lines.last, isBlank(last) { - lines.removeLast() - } - return lines - } - - /// The annotated capture back as the daemon's plain `text` capture: no selection prefix, - /// no cursor marker, no trailing whitespace — what the harness plugins' patterns and the - /// state detector were written against. - static func plain(_ annotated: String) -> String { - var out = "" - for line in JavaText.lines(annotated) { - let l = line.hasPrefix(SELECTION_MARKER) ? String(line.dropFirst(SELECTION_MARKER.count)) : line - out += JavaText.stripTrailing(l.replacingOccurrences(of: CURSOR_MARKER, with: "")) - out += "\n" - } - return out - } - - /// A plain-text capture with trailing whitespace dropped from every line, as `plain` - /// leaves it — for a daemon that only gives plain text, whose real `▶ `/`▮` characters - /// must not be taken for markers. - static func trimmed(_ text: String) -> String { - var out = "" - for line in JavaText.lines(text) { - out += JavaText.stripTrailing(line) - out += "\n" - } - return out - } - - /// The lines of `current` that are new since `previous`, or nil when the whole screen - /// should be shown. The overlap is the longest leading block of `current` (at least - /// `MIN_OVERLAP` non-blank lines) that occurs as a contiguous block in `previous`: - /// output scrolled up by the new lines below it. Everything after that block is - /// returned — new output, and the prompt or footer area, changed or not. No such - /// overlap, nothing after it, or more than `MAX_NEW_SHARE` of the screen new: nil. - static func newLines(_ previous: [String], _ current: [String]) -> Delta? { - let size = current.count - let maxNew = Int((Double(size) * MAX_NEW_SHARE).rounded(.down)) - var k = size - 1 - while k >= 1 && size - k <= maxNew { - let prefix = Array(current[0.. String { - let joined = lines.joined(separator: "\n") - if joined.utf16.count <= maxChars { - return joined - } - let budget = maxChars - 40 // room for the omission line - var used = 0 - var first = lines.count - while first > 0 && used + lines[first - 1].utf16.count + 1 <= budget { - first -= 1 - used += lines[first].utf16.count + 1 - } - var kept = Array(lines[first...]) - if kept.isEmpty { - let last = lines[lines.count - 1] - let units = Array(last.utf16) - let tail = units[max(0, units.count - budget)...] - kept.append(String(decoding: tail, as: UTF16.self)) - first = lines.count - 1 - } - return "… (\(first) earlier lines omitted)\n" + kept.joined(separator: "\n") - } - - private static func occursIn(_ haystack: [String], _ block: [String]) -> Bool { - if block.count > haystack.count { return false } - var start = 0 - outer: while start + block.count <= haystack.count { - for i in 0.. Int { - lines.filter { !isBlank($0) }.count - } - - private static func isBlank(_ line: String) -> Bool { - JavaText.isBlank(line.replacingOccurrences(of: CURSOR_MARKER, with: "")) - } -} diff --git a/swift/Sources/MicrohmCore/control/SessionController.swift b/swift/Sources/MicrohmCore/control/SessionController.swift deleted file mode 100644 index 409fe69..0000000 --- a/swift/Sources/MicrohmCore/control/SessionController.swift +++ /dev/null @@ -1,1916 +0,0 @@ -import Foundation -import MicrohmMux -import MicrohmShared - -/// The MCP session controller: the tools agents running in micro-harness-manager's -/// sessions use to list, read, drive, watch, start and end each other. Everything -/// harness-specific (state detection, chrome masking, transcripts) lives here, on top of -/// the daemon's generic input/capture/wait/watch. -/// -/// Per session the controller keeps its own `SessionTracker` (state detection fed by every -/// capture it takes); per (caller, session) what that caller last read, so reads are -/// incremental; and the pending one-shot notifications and spawn prompts, which a -/// background monitor re-evaluates — once a second while anything is pending, and at once -/// when the daemon's event stream reports activity in a session involved. The monitor runs -/// while the MCP server does (`serverStarted`/`serverStopped`); it reconnects the event -/// stream with backoff when the daemon restarts or is not running yet. -/// -/// Thread-safe: tool calls arrive on concurrent request threads. -public final class SessionController: McpToolset, @unchecked Sendable { - - static let TOOL_LIST = "list" - static let TOOL_READ = "read" - static let TOOL_SEND = "send" - static let TOOL_KEYS = "keys" - static let TOOL_NOTIFY = "notify" - static let TOOL_SPAWN = "spawn" - static let TOOL_KILL = "kill" - - /// Label a spawned session carries naming the session whose agent spawned it. - static let LABEL_SPAWNED_BY = "spawned-by" - - static let MAX_BODY_CHARS = 8000 - /// Cap on the changed lines a read shows when only status lines changed. - static let MAX_STATUS_CHARS = 2000 - static let NOTICE_PREFIX = "[micro-harness-manager] " - /// Appended to a read's header when the daemon only gave plain text. - static let OLD_DAEMON_NOTE = "(old daemon: no selection/cursor markers)" - static let OLD_DAEMON_REPLACED = "It is replaced automatically once every session has ended and a new one starts." - /// A multi-line paste the session's program would receive as typed lines. - static let MULTI_LINE_REFUSED = "this session doesn't accept multi-line pastes; send one line at a time" - + " (line breaks and control characters can only be pasted where the program enables bracketed paste)" - static let DAEMON_UNREACHABLE = "the session daemon is not answering; try again shortly" - - /// Whether `ch`, written raw (no bracketed paste), would act as a key rather than as - /// text: a line break or any other C0 control except tab, DEL, or a C1 control. - static func actsAsKeyOutsidePaste(_ ch: UInt32) -> Bool { - (ch < 0x20 && ch != 0x09) || (ch >= 0x7f && ch <= 0x9f) - } - - /// How many times an owed Enter (after its text was pasted) is tried before giving up. - static let MAX_ENTER_ATTEMPTS = 5 - - /// Every duration the controller waits on (seconds, or milliseconds where named), - /// injectable so tests run instantly. - public struct Timings: Sendable { - var tick: TimeInterval - var enterDelay: TimeInterval - var shortQuiescence: TimeInterval - var longQuiescence: TimeInterval - var notifyTtl: TimeInterval - var promptTimeout: TimeInterval - var keysQuietMs: Int64 - var keysTimeoutMs: Int64 - var watchQuietMs: Int64 - var watchBackoffMin: TimeInterval - var watchBackoffMax: TimeInterval - - public static let DEFAULT = Timings(tick: 1, enterDelay: 0.4, shortQuiescence: 5, longQuiescence: 20, - notifyTtl: 30 * 60, promptTimeout: 120, keysQuietMs: 300, - keysTimeoutMs: 3000, watchQuietMs: 500, watchBackoffMin: 1, - watchBackoffMax: 30) - } - - /// `Thread.sleep`, replaceable in tests. - typealias Sleeper = (TimeInterval) throws -> Void - /// Runs a delivery off the monitor (its own thread in production; inline in tests). - typealias Executor = (@escaping () -> Void) -> Void - - /// What a notify waits for. - enum Trigger: String, CaseIterable { - case FINISHED = "finished" - case NEEDS_INPUT = "needs-input" - case EXITED = "exited" - case ANY_CHANGE = "any-change" - - var id: String { rawValue } - - var description: String { - switch self { - case .FINISHED: return "finished" - case .NEEDS_INPUT: return "needs input" - case .EXITED: return "exited" - case .ANY_CHANGE: return "changed" - } - } - - static func fromId(_ id: String) -> Trigger? { - Trigger(rawValue: id) - } - } - - private let daemon: DaemonControl - private let registry: SessionRegistry - private let spawner: SessionSpawner - private let clock: MicrohmClock - private let transcripts: TranscriptLocator - private let sleeper: Sleeper - private let deliveries: Executor - private let timings: Timings - private var toolList: [ToolDef] = [] - private let compat: DaemonCompat - - private let stateLock = NSLock() - private var trackers: [String: SessionTracker] = [:] - /// Keyed by `seenKey`. - private var seen: [String: Seen] = [:] - /// Guarded by `pendingLock`, as is `prompts`. - private var notifications: [Notification] = [] - private var prompts: [PromptDelivery] = [] - private let pendingLock = NSRecursiveLock() - /// Display names (lower case) of spawns in flight, between their uniqueness check and - /// their creation returning; guarded by `stateLock`. - private var spawningDisplays: Set = [] - - private let logs = SessionLogs() - /// Whether logs are kept at all (the user's setting, asked on each use). - private let sessionLogs: () -> Bool - /// The logs being kept, by file path: whose, of which session, in which folder. - private var mirrors: [String: Mirror] = [:] - private let mirrorLock = NSRecursiveLock() - - /// The monitor's wake-up: a pending flag (one permit) under a condition. - private let wakeCondition = NSCondition() - private var wakePending = false - /// Guarded by `monitorLock`. - private let monitorLock = NSLock() - private var monitor: MonitorThread? - - /// The production controller: standard transcript locations, real sleeps, deliveries on - /// their own threads. - public convenience init(_ daemon: DaemonControl, _ registry: SessionRegistry, _ spawner: SessionSpawner, - _ clock: MicrohmClock = SystemClock.shared) { - let standard = HarnessTranscripts.standard() - self.init(daemon, registry, spawner, clock, standard.locator, { Thread.sleep(forTimeInterval: $0) }, - { task in Thread.detachNewThread(task) }, Timings.DEFAULT, { AppSettings.mcpSessionLogs() }) - } - - init(_ daemon: DaemonControl, _ registry: SessionRegistry, _ spawner: SessionSpawner, _ clock: MicrohmClock, - _ transcripts: @escaping TranscriptLocator, _ sleeper: @escaping Sleeper, _ deliveries: @escaping Executor, - _ timings: Timings, _ sessionLogs: @escaping () -> Bool) { - self.daemon = daemon - self.registry = registry - self.spawner = spawner - self.clock = clock - self.transcripts = transcripts - self.sleeper = sleeper - self.deliveries = deliveries - self.timings = timings - self.sessionLogs = sessionLogs - self.compat = DaemonCompat { try daemon.daemonPid() } - self.toolList = SessionController.toolDefs() - } - - // MARK: - McpToolset - - public func tools() -> [ToolDef] { - toolList - } - - public func call(_ caller: String?, _ tool: String, _ arguments: CoreJSON) -> ToolResult { - let args = arguments.isObject ? arguments : CoreJSON.object([]) - do { - compat.revalidate() - let text: String - switch tool { - case SessionController.TOOL_LIST: text = try list(caller) - case SessionController.TOOL_READ: text = try read(caller, args) - case SessionController.TOOL_SEND: text = try send(caller, args) - case SessionController.TOOL_KEYS: text = try keys(caller, args) - case SessionController.TOOL_NOTIFY: text = try notify(caller, args) - case SessionController.TOOL_SPAWN: text = try spawn(caller, args) - case SessionController.TOOL_KILL: text = try kill(caller, args) - default: throw ToolError("unknown tool: " + tool) - } - return ToolResult.ok(text) - } catch let e as ToolError { - return ToolResult.error(e.message) - } catch { - Log.debug("tool \(tool) failed: \(error)", tag: "control") - return ToolResult.error(tool + " failed: " + errorMessage(error)) - } - } - - // MARK: - phone page - - /// A running session as the phone page lists it; `state` is a `SessionState` name, or - /// `EXITED`. - public struct SessionSummary: Equatable, Sendable { - public let name: String - public let display: String? - public let harness: String - public let state: String - public let project: String - - public init(_ name: String, _ display: String?, _ harness: String, _ state: String, _ project: String) { - self.name = name - self.display = display - self.harness = harness - self.state = state - self.project = project - } - } - - /// One session's screen as plain text (no markers), with what the page shows above it. - public struct ScreenView: Equatable, Sendable { - public let name: String - public let display: String? - public let harness: String - public let state: String - public let reason: String - public let title: String - public let text: String - public let columns: Int - public let rows: Int - public let outputBytes: Int64 - public let alive: Bool - - public init(_ name: String, _ display: String?, _ harness: String, _ state: String, _ reason: String, - _ title: String, _ text: String, _ columns: Int, _ rows: Int, _ outputBytes: Int64, _ alive: Bool) { - self.name = name - self.display = display - self.harness = harness - self.state = state - self.reason = reason - self.title = title - self.text = text - self.columns = columns - self.rows = rows - self.outputBytes = outputBytes - self.alive = alive - } - } - - /// The running sessions, classified, in the daemon's order. No daemon is no sessions: it - /// exits with its last session and starts again with the next. - public func summaries() throws -> [SessionSummary] { - compat.revalidate() - var out: [SessionSummary] = [] - for info in try daemon.list() where info.alive { - // (its program ended: the daemon drops it shortly, the phone lists it as ended) - let target = self.target(info) - let state = try observe(target)?.classification.state.name ?? "EXITED" - out.append(SessionSummary(target.name, target.display, target.harness.id, state, target.project)) - } - return out - } - - /// `session`'s screen (by name or display name); nil once it has exited. Throws a - /// message for the user when no session matches or the daemon does not answer. - public func screen(_ session: String) throws -> ScreenView? { - compat.revalidate() - let target: Target - do { - target = try resolve(session) - } catch let e as ToolError where e.kind == .unreachable { - if !reachable() { - // no daemon: it exits with its last session, so this one has ended - return nil - } - throw e - } - guard let obs = try observe(target) else { return nil } - let c = obs.classification - let capture = obs.capture - return ScreenView(target.name, target.display, target.harness.id, c.state.name, c.reason, capture.title, - obs.plain, capture.columns, capture.rows, capture.outputBytes, capture.alive) - } - - /// A registered session that is not running: what the phone page offers to resume. - /// `conversation` is whether its harness conversation can be picked up again (an id was - /// recorded); without one, resuming starts the harness fresh in its folder. - public struct EndedSession: Equatable, Sendable { - public let name: String - public let display: String? - public let harness: String - public let project: String - public let conversation: Bool - public let created: Date? - } - - /// Registered sessions the daemon is not running, newest first. No daemon: all of them. - public func ended() throws -> [EndedSession] { - let live = Set(try daemon.list().filter(\.alive).map(\.name)) - return registry.sessions() - .filter { !live.contains($0.sessionName) } - .sorted { $0.createdAt > $1.createdAt } - .map { EndedSession(name: $0.sessionName, display: $0.displayName, harness: $0.harnessType.id, - project: $0.projectPath, conversation: $0.harnessSessionIdOpt != nil, - created: $0.createdAt) } - } - - /// Starts the ended registered session `session` (its name or sidebar name) again, as - /// the window's Resume does; returns its name. - public func resume(_ session: String) throws -> String { - compat.revalidate() - let live = Set(try daemon.list().filter(\.alive).map(\.name)) - guard let entry = registry.sessions().first(where: { - $0.sessionName == session || ($0.displayName.map { $0.caseInsensitiveCompare(session) == .orderedSame } ?? false) - }) else { - throw ToolError("no saved session named " + session) - } - if live.contains(entry.sessionName) { - throw ToolError(entry.sessionName + " is already running") - } - forget(entry.sessionName) - try spawner.resume(entry) - return entry.sessionName - } - - /// Scrollback lines as plain text, oldest first, and the count to pass back as `since` - /// next time; `alternateScreen` while a full-screen program runs. - public struct HistoryView: Equatable, Sendable { - public let text: String - public let added: Int64 - public let alternateScreen: Bool - - public init(_ text: String, _ added: Int64, _ alternateScreen: Bool) { - self.text = text - self.added = added - self.alternateScreen = alternateScreen - } - } - - /// The scrollback lines `session` added after the first `since` (0: all it still - /// holds); nil once it has exited, or from a daemon without history. - public func history(_ session: String, _ since: Int64) throws -> HistoryView? { - compat.revalidate() - let target = try resolve(session) - do { - guard let h = try daemon.captureSince(target.name, .TEXT, since)?.history else { return nil } - return HistoryView(h.text, h.added, h.alternateScreen) - } catch where DaemonCompat.isUnsupported(error) { - return nil - } - } - - /// A screen as the daemon's styled capture: the redraw stream that reproduces it, with - /// the size to replay it at. - public struct AnsiView: Equatable, Sendable { - public let text: String - public let columns: Int - public let rows: Int - - public init(_ text: String, _ columns: Int, _ rows: Int) { - self.text = text - self.columns = columns - self.rows = rows - } - } - - /// `session`'s screen with its styles; nil once it has exited, or from a daemon without - /// the styled capture. - public func ansi(_ session: String) throws -> AnsiView? { - compat.revalidate() - let target = try resolve(session) - do { - return try daemon.capture(target.name, .ANSI).map { AnsiView($0.text, $0.columns, $0.rows) } - } catch where DaemonCompat.isUnsupported(error) { - return nil - } - } - - /// Resizes `session` (by name or display name) for every viewer. - public func resize(_ session: String, _ columns: Int, _ rows: Int) throws { - compat.revalidate() - try daemon.resize(try resolve(session).name, columns, rows) - } - - /// Starts the background monitor (idempotent). - public func serverStarted() { - monitorLock.lock(); defer { monitorLock.unlock() } - if monitor != nil { - return - } - let m = MonitorThread() - monitor = m - let thread = Thread { [self] in - monitorLoop(m) - m.done.signal() - } - thread.name = "mhm-control-monitor" - m.thread = thread - thread.start() - } - - /// Stops the background monitor, waiting briefly for it to close its event stream. - /// Pending notifications and prompts are kept for the next start. - public func serverStopped() { - monitorLock.lock() - let stopping = monitor - monitor = nil - monitorLock.unlock() - if let stopping { - stopping.stopped = true - wake() - _ = stopping.done.wait(timeout: .now() + 1) - } - } - - /// Whether `m` is still the current monitor — a monitor replaced by a quick stop/start - /// that outlived its join notices here and ends. - private func isCurrentMonitor(_ m: MonitorThread) -> Bool { - monitorLock.lock(); defer { monitorLock.unlock() } - return monitor === m - } - - // MARK: - tools - - private func list(_ caller: String?) throws -> String { - let infos = try daemon.list() - if infos.isEmpty && !reachable() { - return "no sessions are running (" + SessionController.DAEMON_UNREACHABLE + ")" - } - forgetAllBut(Set(infos.map(\.name))) - if infos.isEmpty { - return "no sessions are running" - } - let targets = infos.map { self.target($0) } - let callerDir = SessionController.callerDir(caller, targets) - var sb = "" - for (i, info) in infos.enumerated() { - let target = targets[i] - let obs = try observe(target) - let state = obs?.classification.state.name ?? "EXITED" - let pid = obs?.capture.processId ?? info.pid - let transcript = transcriptOf(target, pid, targets) ?? "-" - sb += target.name + " · " + (target.display ?? "-") - sb += " · " + target.harness.id - sb += " · " + state - sb += " · " + target.project - sb += " · transcript: " + transcript - sb += " · log: " + (keptLog(caller, callerDir, target)?.path ?? "-") - if target.name == caller { - sb += " (you)" - } - sb += "\n" - } - return JavaText.stripTrailing(sb) - } - - private func read(_ caller: String?, _ args: CoreJSON) throws -> String { - let infos = try liveSessions() - let target = try resolve(try SessionController.requiredText(args, "session"), infos) - let full = args.path("full").asBoolean(false) - guard let obs = try observe(target) else { - return target.name + " · exited" - } - let pid = obs.capture.processId - let all = infos.map { self.target($0) } - let log = logOf(caller, SessionController.callerDir(caller, all), target) - return render(caller, target, obs, full) { - SessionController.earlierOutputNote(self.transcriptOf(target, pid, all), log) - } - } - - /// Where a whole-screen read says the earlier output is; nil when nowhere. - static func earlierOutputNote(_ transcript: String?, _ log: URL?) -> String? { - if transcript == nil && log == nil { - return nil - } - var note = "… (earlier output is in " - if let transcript { - note += "the transcript, " + transcript + (log != nil ? ", and in " : "") - } - if let log { - note += "the screen log, " + log.path - } - note += ": grep or tail " + (transcript != nil && log != nil ? "them" : "it") + ")" - return note - } - - // MARK: - screen logs - - /// Whose log, of which session (and harness), in which folder. - private final class Mirror { - var callers: Set = [] - let session: String - let harness: HarnessType - let dir: URL - - init(_ session: String, _ harness: HarnessType, _ dir: URL) { - self.session = session - self.harness = harness - self.dir = dir - } - } - - /// The project folder of the calling session, where its logs go; nil when the caller is - /// not a running session with a project folder. - private static func callerDir(_ caller: String?, _ all: [Target]) -> URL? { - guard let caller, !JavaText.isBlank(caller), - let project = all.first(where: { $0.name == caller })?.project, project != "-" else { - return nil - } - var isDir: ObjCBool = false - guard FileManager.default.fileExists(atPath: project, isDirectory: &isDir), isDir.boolValue else { - return nil - } - return URL(fileURLWithPath: project) - } - - /// `target`'s log for `caller` when one is being kept for it and is there (not one that - /// could not be written), without starting one: what list shows. - private func keptLog(_ caller: String?, _ callerDir: URL?, _ target: Target) -> URL? { - guard let callerDir, let caller, target.name != caller, sessionLogs() else { - return nil - } - let file = SessionLogs.file(callerDir, target.name) - mirrorLock.lock() - let kept = mirrors[file.path]?.callers.contains(caller) ?? false - mirrorLock.unlock() - var st = stat() - return kept && lstat(file.path, &st) == 0 && (st.st_mode & S_IFMT) == S_IFREG ? file : nil - } - - /// `target`'s log for `caller`, brought up to date and kept so from now on: what a read - /// starts, so a session's output is copied into the caller's project only once the - /// caller has looked at that session. Nil for the caller's own session, without a - /// caller folder, or when it can't be written. - private func logOf(_ caller: String?, _ callerDir: URL?, _ target: Target) -> URL? { - guard let callerDir, let caller, target.name != caller, sessionLogs() else { - return nil - } - let file = SessionLogs.file(callerDir, target.name) - // agents sharing a project share the file: it is kept while any of them is running - mirrorLock.lock() - let mirror = mirrors[file.path] ?? Mirror(target.name, target.harness, callerDir) - mirror.callers.insert(caller) - mirrors[file.path] = mirror - mirrorLock.unlock() - do { - try syncLog(file, mirror) - return file - } catch { - Log.debug("could not write \(file.path): \(error)", tag: "control") - if let e = error as? ToolError, e.kind == .unreachable { - return file - } - // kept all the same: the next sample tries again (the folder may come back) - return nil - } - } - - /// Appends what is new in the mirrored session to its log; stops keeping a log whose - /// session has ended (after its last lines). - private func syncLog(_ file: URL, _ mirror: Mirror) throws { - let log = try logs.open(mirror.dir, mirror.session) - log.lock.lock(); defer { log.lock.unlock() } - var capture = try captureForLog(mirror.session, log.since()) - if let c = capture, log.pid != 0, c.processId != log.pid { - try log.restarted(c.processId, clock.instant()) - capture = try captureForLog(mirror.session, 0) - } - guard let c = capture else { - if !reachable() { - throw ToolError.unreachable() - } - stopLog(file) - return - } - let plugin = HarnessPlugins.of(mirror.harness) - try log.record(c, { plugin.maskChrome($0) }, clock.instant()) - if !c.alive { - stopLog(file) - } - } - - private func stopLog(_ file: URL) { - mirrorLock.lock() - mirrors.removeValue(forKey: file.path) - mirrorLock.unlock() - logs.close(file) - } - - /// The screen as text with the scrollback added since `since`. - private func captureForLog(_ name: String, _ since: Int64) throws -> SessionCapture? { - try daemon.captureSince(name, .TEXT, since) - } - - /// One pass over the logs being kept: drops those whose caller has gone (all of them - /// once the setting is off), and brings the rest up to date. - private func syncLogs() throws { - mirrorLock.lock() - let kept = mirrors - mirrorLock.unlock() - if kept.isEmpty { - return - } - if !sessionLogs() { // turned off: the logs kept so far stay as they are - kept.keys.forEach { stopLog(URL(fileURLWithPath: $0)) } - return - } - let infos = try daemon.list() - if infos.isEmpty && !reachable() { - return - } - let live = Set(infos.map(\.name)) - for (path, mirror) in kept { - mirrorLock.lock() - mirror.callers.formIntersection(live) - let empty = mirror.callers.isEmpty - mirrorLock.unlock() - let file = URL(fileURLWithPath: path) - if empty { - stopLog(file) - continue - } - do { - try syncLog(file, mirror) - } catch { - Log.debug("could not update \(path): \(error)", tag: "control") - } - } - } - - /// The session's transcript as list shows it: the file, or — for a claude-code session - /// whose id is unknown while other claude-code sessions share its project — the folder - /// with a note. Nil when there is none. `all` is every live session. - private func transcriptOf(_ target: Target, _ pid: Int64, _ all: [Target]) -> String? { - let id = target.entry?.harnessSessionIdOpt - let siblings = all.filter { $0.harness == target.harness && $0.project == target.project }.count - guard let found = transcripts(target.harness, URL(fileURLWithPath: target.project), id, pid) else { - return nil - } - if id == nil && target.harness == .claudeCode && siblings > 1 { - // the newest file there may well be a sibling's: point at the folder - return found.deletingLastPathComponent().path + "/" + " (id unknown and other claude-code sessions" - + " share this project: one of these files, not necessarily the newest)" - } - return found.path - } - - private func send(_ caller: String?, _ args: CoreJSON) throws -> String { - let target = try resolve(try SessionController.requiredText(args, "session")) - guard let textNode = args.get("text"), textNode.isTextual else { - throw ToolError("text is required (a string)") - } - let enter = args.path("enter").asBoolean(true) - try SessionController.refuseSelf(caller, target, "send to") - let text = textNode.asText() - if text.isEmpty && !enter { - throw ToolError("nothing to send: text is empty and enter is false") - } - try type(target.name, text, enter, false, true) {} - return "sent to " + target.name - } - - private func keys(_ caller: String?, _ args: CoreJSON) throws -> String { - let target = try resolve(try SessionController.requiredText(args, "session")) - guard let keysNode = args.get("keys"), keysNode.isArray, !keysNode.isEmpty else { - throw ToolError("keys is required: a non-empty array of key names, e.g. [\"Down\",\"Enter\"]") - } - var keys: [String] = [] - for k in keysNode.elements { - if !k.isTextual || k.asText().isEmpty { - throw ToolError("every key must be a non-empty string, e.g. \"Enter\", \"y\", \"C-c\"") - } - keys.append(k.asText()) - } - if !compat.has(.INPUT) { - throw ToolError(keysNeedNewerDaemon()) - } - guard let before = try capture(target.name) else { - throw ToolError(target.name + " has exited") - } - do { - try daemon.input(target.name, nil, false, keys) - } catch where DaemonCompat.isUnsupported(error) { - compat.markMissing(.INPUT) - throw ToolError(keysNeedNewerDaemon()) - } - if compat.has(.WAIT) { - do { - _ = try daemon.awaitQuiet(target.name, before.capture.outputBytes, timings.keysQuietMs, - timings.keysTimeoutMs) - } catch where DaemonCompat.isUnsupported(error) { - compat.markMissing(.WAIT) - } - } - guard let obs = try observe(target) else { - return target.name + " · exited" - } - return render(caller, target, obs, true) - } - - private func notify(_ caller: String?, _ args: CoreJSON) throws -> String { - guard let caller, !JavaText.isBlank(caller) else { - throw ToolError("notify only works from a session micro-harness-manager launched: the " - + "notification is typed into your session, and this connection does not say which " - + "session that is") - } - guard let on = Trigger.fromId(args.path("on").asText("") ?? "") else { - throw ToolError("on must be one of: finished, needs-input, exited, any-change") - } - let requested = try SessionController.sessionsArgument(args) - let infos = try liveSessions() - guard let callerInfo = infos.first(where: { $0.name == caller }) else { - throw ToolError("your session " + caller + " is not a running session, so a " - + "notification could not be delivered to it") - } - if target(callerInfo).harness == .shell { - throw ToolError("notify cannot deliver to " + caller + ": it is a plain shell session, where the " - + "notification line would be typed at the shell prompt and run as a command. Notifications " - + "only go to agent sessions (claude-code, codex, …); poll with read instead") - } - // resolve and validate every session before registering any, so a failure registers nothing - var targets: [Target] = [] - for argument in requested { - let target = try resolve(argument, infos) - if target.name == caller { - throw ToolError("notify watches other sessions, not your own (" + caller + ")") - } - if !targets.contains(where: { $0.name == target.name }) { - targets.append(target) - } - } - var observed: [String: Observation?] = [:] - for target in targets { - observed[target.name] = .some(try observe(target)) - } - var replies: [String] = [] - for target in targets { - guard let o = observed[target.name] ?? nil, o.capture.alive else { - replies.append(target.name + " has already exited; nothing registered") - continue - } - // a session whose spawn prompt is not typed in yet is about to work on it - let awaitPrompt = (on == .FINISHED || on == .NEEDS_INPUT) && promptPending(target.name) - let state = awaitPrompt ? SessionState.working : o.classification.state - if on == .FINISHED && state != .working { - replies.append(target.name + " is already \(state.name) (not working); nothing registered") - continue - } - if on == .NEEDS_INPUT && state == .waitingForInput { - replies.append(target.name + " is already \(state.name); nothing registered") - continue - } - var reply = "will notify " + caller + " when " + target.name + " " + on.id - pendingLock.lock() - let duplicate = notifications.contains { - $0.message == nil && $0.caller == caller && $0.target == target.name && $0.trigger == on - } - if duplicate { - reply = "already registered: " + reply - } else { - let n = Notification(caller, target.name, on, o.masked, clock.instant()) - n.awaitPrompt = awaitPrompt - notifications.append(n) - } - pendingLock.unlock() - replies.append(reply) - } - wake() - return replies.joined(separator: "\n") - } - - /// Whether a spawn prompt for `session` is still waiting or being typed in. - private func promptPending(_ session: String) -> Bool { - pendingLock.lock(); defer { pendingLock.unlock() } - return prompts.contains { $0.session == session } - } - - private func spawn(_ caller: String?, _ args: CoreJSON) throws -> String { - let harnessId = try SessionController.requiredText(args, "harness") - guard let harness = try? HarnessType.fromId(harnessId) else { - throw ToolError("unknown harness " + harnessId + "; one of: " + SessionController.harnessIds()) - } - let project = try SessionController.expandProject(try SessionController.requiredText(args, "project")) - let display = try SessionController.optionalText(args, "name").map(JavaText.strip) - // the name becomes part of each line of list's reply: one with a line break (or - // list's own separator) in it would let an agent forge rows other agents read - if let d = display, d.utf16.count > 64 - || d.utf16.contains(where: { ($0 < 0x20) || ($0 >= 0x7f && $0 <= 0x9f) || $0 == 0x00B7 }) { - throw ToolError("name must be at most 64 characters, on one line, without \"·\"") - } - let prompt = try SessionController.optionalText(args, "prompt") - let labels: [String: String] = caller.map { JavaText.isBlank($0) ? [:] : [SessionController.LABEL_SPAWNED_BY: $0] } ?? [:] - // the check and the creation are one step: a reservation keeps a concurrent spawn - // from taking the same name before this one's label and registry row exist - let reservation = display?.lowercased() - if let reservation { - stateLock.lock() - let added = spawningDisplays.insert(reservation).inserted - stateLock.unlock() - if !added { - throw ToolError("name already in use by a session being spawned; choose another") - } - } - defer { - if let reservation { - stateLock.lock() - spawningDisplays.remove(reservation) - stateLock.unlock() - } - } - if let wanted = display { - // daemon.list(), not liveSessions(): a daemon that is not running has no - // session to clash with, and the spawn below is what starts it. - for info in try daemon.list() { - let live = target(info) - if (live.display.map { wanted.caseInsensitiveCompare($0) == .orderedSame } ?? false) || wanted == live.name { - throw ToolError("name already in use by " + live.name + "; choose another") - } - } - } - let name = try spawner.spawn(SpawnRequest(harness, project, display, labels)) - var reply = name + " started (" + harness.id + " in " + project.path + ")" - if let prompt { - pendingLock.lock() - prompts.append(PromptDelivery(name, prompt, caller, clock.instant().addingTimeInterval(timings.promptTimeout))) - pendingLock.unlock() - wake() - reply += "; the prompt will be typed in once it is ready at its prompt" - } - return reply - } - - private func kill(_ caller: String?, _ args: CoreJSON) throws -> String { - let target = try resolve(try SessionController.requiredText(args, "session")) - try SessionController.refuseSelf(caller, target, "kill") - try spawner.kill(target.name) - forget(target.name) - return "killed " + target.name - } - - // MARK: - reading - - /// The read-style answer for `obs`, recording what `caller` has now seen; when it shows - /// the whole screen it ends with `wholeScreenNote` (asked lazily: finding a transcript - /// may fork lsof). - private func render(_ caller: String?, _ target: Target, _ obs: Observation, _ full: Bool, - _ wholeScreenNote: () -> String? = { nil }) -> String { - let header = SessionController.header(target, obs) - let lines = obs.body - let bytes = obs.capture.outputBytes - stateLock.lock() - let key = SessionController.seenKey(caller, target.name) - let previous = seen[key] - seen[key] = Seen(outputBytes: bytes, masked: obs.masked, lines: lines, plain: obs.plain) - stateLock.unlock() - if !full, let previous { - // outputBytes is -1 (unknown) from a daemon that predates the counter - let sameOutput = previous.outputBytes >= 0 && bytes >= 0 && previous.outputBytes == bytes - if sameOutput || previous.plain == obs.plain { - return header + " · unchanged" - } - if previous.masked == obs.masked { - let changed = SessionController.changedLines(previous.lines, lines) - return header + " · only status lines changed" - + (changed.isEmpty ? "" : "\n" + ScreenDiff.cap(changed, SessionController.MAX_STATUS_CHARS)) - } - if let delta = ScreenDiff.newLines(previous.lines, lines) { - return header + "\n… (\(delta.unchangedAbove) lines above already seen; full=true shows the whole screen)\n" - + ScreenDiff.cap(delta.lines, SessionController.MAX_BODY_CHARS) - } - } - let screen = header + "\n" + ScreenDiff.cap(lines, SessionController.MAX_BODY_CHARS) - return wholeScreenNote().map { screen + "\n" + $0 } ?? screen - } - - private static func header(_ target: Target, _ obs: Observation) -> String { - let c = obs.classification - let title = obs.capture.title - return target.name + " · " + target.harness.id + " · " + c.state.name + " (" + c.reason + ")" - + (!JavaText.isBlank(title) ? " · " + JavaText.strip(title) : "") - + (obs.annotated ? "" : " " + OLD_DAEMON_NOTE) - } - - /// The lines of `current` that `previous` does not have (as many times): what changed - /// when only masked lines did. - private static func changedLines(_ previous: [String], _ current: [String]) -> [String] { - var before: [String: Int] = [:] - previous.forEach { before[$0, default: 0] += 1 } - var changed: [String] = [] - for line in current { - let n = before[line, default: 0] - 1 - before[line] = n - if n < 0 { - changed.append(line) - } - } - return changed - } - - /// A capture and whether it is annotated (an old daemon only gives plain text). - private struct Captured { - let capture: SessionCapture - let annotated: Bool - } - - /// The annotated screen, or plain text from a daemon that predates capture formats. - private func capture(_ name: String) throws -> Captured? { - if compat.has(.ANNOTATED_CAPTURE) { - do { - return try daemon.capture(name, .ANNOTATED).map { Captured(capture: $0, annotated: true) } - } catch where DaemonCompat.isUnsupported(error) { - compat.markMissing(.ANNOTATED_CAPTURE) - } - } - return try daemon.capture(name, .TEXT).map { Captured(capture: $0, annotated: false) } - } - - /// Captures the screen and classifies it; nil when the session is gone. - private func observe(_ target: Target) throws -> Observation? { - guard let captured = try capture(target.name) else { - if !reachable() { - throw ToolError.unreachable() // not gone: the daemon may be restarting - } - forget(target.name) - return nil - } - let c = captured.capture - let annotated = captured.annotated - stateLock.lock() - let tracker: SessionTracker - if let existing = trackers[target.name], existing.harness == target.harness { - tracker = existing - } else { - tracker = SessionTracker(target.harness, clock, timings.shortQuiescence, timings.longQuiescence) - trackers[target.name] = tracker - } - stateLock.unlock() - let text = c.text - let plain = annotated ? ScreenDiff.plain(text) : ScreenDiff.trimmed(text) - let classification = tracker.classify( - SessionTracker.screen(plain, c.alive, clock.instant(), c.foregroundCommand, c.processId, c.title)) { - self.probeQuiet(target.name, $0) - } - return Observation(capture: c, annotated: annotated, classification: classification, - masked: tracker.plugin.maskChrome(text), body: ScreenDiff.bodyLines(text), plain: plain, - tracker: tracker) - } - - /// Whether the session's output has been quiet this long; false (no backdating) when - /// the daemon predates wait. - private func probeQuiet(_ name: String, _ quiet: TimeInterval) -> Bool { - if !compat.has(.WAIT) { - return false - } - do { - let result = try daemon.awaitQuiet(name, -1, Int64((quiet * 1000).rounded()), 0) - return result.quiet && result.alive - } catch { - if DaemonCompat.isUnsupported(error) { - compat.markMissing(.WAIT) - } - return false - } - } - - // MARK: - resolution - - private func resolve(_ argument: String) throws -> Target { - try resolve(argument, try liveSessions()) - } - - /// `DaemonControl.list`, but an empty answer from a daemon that does not answer is - /// unreachable, never "no sessions". - private func liveSessions() throws -> [SessionInfo] { - let infos = try daemon.list() - if infos.isEmpty && !reachable() { - throw ToolError.unreachable() - } - return infos - } - - /// Whether the daemon answers a ping; a failing ping counts as no. - private func reachable() -> Bool { - (try? daemon.ping()) ?? false - } - - /// The daemon session `argument` names: a session name, else a registry display name - /// (case-insensitive), else a `display` label. - private func resolve(_ argument: String, _ infos: [SessionInfo]) throws -> Target { - if let info = infos.first(where: { $0.name == argument }) { - return target(info) - } - let targets = infos.map { self.target($0) } - for registryName in [true, false] { - let matches = targets.filter { t in - let candidate = registryName ? t.entry?.displayName : t.labels[SessionLauncher.LABEL_DISPLAY] - return candidate.map { $0.caseInsensitiveCompare(argument) == .orderedSame } ?? false - } - if matches.count == 1 { - return matches[0] - } - if matches.count > 1 { - throw ToolError("\"" + argument + "\" is ambiguous: " + matches.map(\.name).joined(separator: ", ") - + " — use the session name") - } - } - let registered = registry.find(argument) ?? registry.sessions().first { - $0.displayName.map { $0.caseInsensitiveCompare(argument) == .orderedSame } ?? false - } - if let registered { - throw ToolError(registered.sessionName + " is not running") - } - throw ToolError("no such session: " + argument + " (list shows the sessions)") - } - - private func target(_ info: SessionInfo) -> Target { - let labels = info.labels - let entry = registry.find(info.name) - let harness = entry?.harnessType ?? SessionController.harnessFromLabel(labels[SessionLauncher.LABEL_HARNESS]) - let display = entry?.displayName.flatMap { JavaText.isBlank($0) ? nil : $0 } - ?? SessionController.blankToNil(labels[SessionLauncher.LABEL_DISPLAY]) - let project = entry?.projectPath ?? SessionController.blankToNil(labels[SessionLauncher.LABEL_PROJECT]) - ?? info.workdir.path - return Target(name: info.name, entry: entry, labels: labels, harness: harness, display: display, project: project) - } - - private static func harnessFromLabel(_ id: String?) -> HarnessType { - guard let id, let type = try? HarnessType.fromId(id) else { return .shell } - return type - } - - // MARK: - typing - - /// Types in two phases: pastes `text` (unless empty or `pasted` — a retry after the - /// paste went in but the Enter did not), runs `onPasted`, then after the enter delay - /// presses Enter. Against a daemon that predates input it falls back to the old - /// send-keys op, which types the text as is and presses Enter after its own pause. - /// - /// `multiLineNeedsBracketedPaste`: when `text` has a line break or another control - /// character, refuse the paste (nothing written, a paste refusal) unless the session's - /// program enabled bracketed paste — otherwise each line would arrive as typed, the - /// first newline would submit early, and ESC or ^C would act as keys. - private func type(_ session: String, _ text: String, _ enter: Bool, _ pasted: Bool, - _ multiLineNeedsBracketedPaste: Bool, _ onPasted: () -> Void) throws { - if !compat.has(.INPUT) { - try typeLegacy(session, pasted ? "" : text, enter) - onPasted() - return - } - if !pasted && !text.isEmpty { - let requireBracketed = multiLineNeedsBracketedPaste - && text.utf16.contains { SessionController.actsAsKeyOutsidePaste(UInt32($0)) } - do { - try daemon.input(session, text, true, requireBracketed, nil) - } catch { - if requireBracketed && SessionController.isBracketedPasteRefusal(error) { - throw ToolError(SessionController.MULTI_LINE_REFUSED, .pasteRefusal) - } - if !DaemonCompat.isUnsupported(error) { - throw error - } - compat.markMissing(.INPUT) - try typeLegacy(session, text, enter) - onPasted() - return - } - onPasted() - if enter { - try sleeper(timings.enterDelay) - } - } - if enter { - do { - try daemon.input(session, nil, false, ["Enter"]) - } catch where DaemonCompat.isUnsupported(error) { - compat.markMissing(.INPUT) - try typeLegacy(session, "", true) - } - } - } - - /// `text` through the old send-keys op: typed as is, so a newline would submit a line - /// and a control character would act as a key — such text is refused. - private func typeLegacy(_ session: String, _ text: String, _ enter: Bool) throws { - if text.utf16.contains(where: { $0 == 0x0A || $0 == 0x0D }) { - throw ToolError("the running daemon (pid \(compat.pid())) predates pasting, so text is typed as is and " - + "every newline would submit a line: send one line at a time. " - + SessionController.OLD_DAEMON_REPLACED, .legacyRefusal) - } - if text.utf16.contains(where: { ($0 < 0x20 && $0 != 0x09) || ($0 >= 0x7f && $0 < 0xa0) }) { - throw ToolError("the running daemon (pid \(compat.pid())) predates pasting, so text is typed as is and " - + "control characters in it would act as keys: remove them. " - + SessionController.OLD_DAEMON_REPLACED, .legacyRefusal) - } - if text.isEmpty && !enter { - return - } - try daemon.sendKeys(session, text, enter) - } - - /// Whether `error` is the daemon refusing a paste the program did not enable bracketed - /// paste for. - private static func isBracketedPasteRefusal(_ error: Error) -> Bool { - (error as? SessionServerException)?.message == MuxProtocol.ERROR_BRACKETED_PASTE_DISABLED - } - - private func keysNeedNewerDaemon() -> String { - "keys needs a newer daemon; the running one (pid \(compat.pid())) predates it. " - + SessionController.OLD_DAEMON_REPLACED - } - - // MARK: - monitor - - /// Whether the monitor has anything to evaluate. - func hasPending() -> Bool { - pendingLock.lock(); defer { pendingLock.unlock() } - return !notifications.isEmpty || !prompts.isEmpty - } - - /// One monitor pass: fires the registrations whose condition holds, delivers spawn - /// prompts to sessions now ready (and gives up on ones that never got there), and types - /// fired notifications into callers idle at their harness's prompt. Internal so tests - /// drive it with a mutable clock instead of the background thread. - func tick() throws { - try syncLogs() - if !hasPending() { - return - } - let infos = try daemon.list() - if infos.isEmpty && !reachable() { - // not "every session is gone": the daemon does not answer — judge nothing now - Log.debug("control monitor: the session daemon is not answering; skipping this pass", tag: "control") - return - } - var live: [String: Target] = [:] - for info in infos { - live[info.name] = target(info) - } - var observed: [String: Look] = [:] - let now = clock.instant() - evaluateRegistrations(live, &observed, now) - evaluatePrompts(live, &observed, now) - deliverNotifications(live, &observed, now) - } - - /// One monitor look at a session: seen, gone, or unknown (the capture failed for some - /// other reason, or the daemon stopped answering — try again next tick rather than take - /// it for gone). - private struct Look { - let obs: Observation? - let unknown: Bool - - static let GONE = Look(obs: nil, unknown: false) - static let UNKNOWN = Look(obs: nil, unknown: true) - - var gone: Bool { - !unknown && (obs == nil || !obs!.capture.alive) - } - } - - private func observeOnce(_ name: String, _ live: [String: Target], _ observed: inout [String: Look]) -> Look { - if let look = observed[name] { - return look - } - let look: Look - if let target = live[name] { - do { - look = try observe(target).map { Look(obs: $0, unknown: false) } ?? .GONE - } catch { - Log.debug("monitor could not capture \(name): \(error)", tag: "control") - look = .UNKNOWN - } - } else { - forget(name) - look = .GONE - } - observed[name] = look - return look - } - - private func evaluateRegistrations(_ live: [String: Target], _ observed: inout [String: Look], _ now: Date) { - pendingLock.lock() - let armed = notifications.filter { $0.message == nil } - pendingLock.unlock() - for n in armed { - if live[n.caller] == nil { - drop(n, "its caller " + n.caller + " is gone") - continue - } - let look = observeOnce(n.target, live, &observed) - if look.unknown { - continue - } - if look.gone { - fire(n, "exited", "EXITED", now) - continue - } - let o = look.obs! - let state = o.classification.state - if n.trigger == .FINISHED || n.trigger == .NEEDS_INPUT { - pendingLock.lock() - let waitingForPrompt = n.awaitPrompt - pendingLock.unlock() - if waitingForPrompt { - if now.timeIntervalSince(n.registered) > timings.notifyTtl { - drop(n, n.target + " did not take up its spawn prompt within " - + "\(Int(timings.notifyTtl / 60)) min") - continue - } - // only once the spawn prompt is in and the session has reacted to it: - // working on it, asking something, or its harness gone back to a shell - let reacted = state == .working || state == .waitingForInput - || o.tracker.atShell(o.capture.foregroundCommand) - if promptPending(n.target) || !reacted { - continue - } - pendingLock.lock() - n.awaitPrompt = false - pendingLock.unlock() - } - } - let fired: Bool - switch n.trigger! { - case .FINISHED: fired = state != .working - case .NEEDS_INPUT: fired = state == .waitingForInput - case .EXITED: fired = false - case .ANY_CHANGE: fired = o.masked != n.baseline - } - if fired { - fire(n, n.trigger!.description, state.name, now) - } - } - } - - private func evaluatePrompts(_ live: [String: Target], _ observed: inout [String: Look], _ now: Date) { - pendingLock.lock() - let waiting = prompts.filter { !$0.delivering } - pendingLock.unlock() - for p in waiting { - pendingLock.lock() - let enterOwed = p.pasted - pendingLock.unlock() - let look = live[p.session] != nil ? observeOnce(p.session, live, &observed) : .GONE - if enterOwed { - // the prompt is in its composer: only Enter is owed, whatever the session - // looks like now and however late it is - if look.gone { - abandon(p, "exited after its prompt was pasted, before it was submitted", live, now) - continue - } - } else { - let late = now > p.deadline - if look.unknown && !late { - continue - } - if look.gone || late { - abandon(p, look.gone ? "exited before its prompt could be sent" - : "did not reach its prompt within \(Int(timings.promptTimeout)) s, so the prompt was not sent", - live, now) - continue - } - let o = look.obs! - let ready = o.classification.state == .idle && o.tracker.harnessRunning(o.capture.foregroundCommand) - if !ready { - continue - } - } - pendingLock.lock() - if p.delivering || !prompts.contains(where: { $0 === p }) { - pendingLock.unlock() - continue // another monitor pass took it meanwhile - } - p.delivering = true - let pasted = p.pasted - pendingLock.unlock() - deliveries { [self] in - do { - try type(p.session, p.prompt, true, pasted, true) { - pendingLock.lock() - p.pasted = true - pendingLock.unlock() - } - pendingLock.lock() - prompts.removeAll { $0 === p } - pendingLock.unlock() - } catch let e as ToolError where e.kind == .legacyRefusal || e.kind == .pasteRefusal { - abandon(p, "could not be given its prompt: " + e.message, live, clock.instant()) - } catch { - Log.warn("could not type the spawn prompt into \(p.session): \(error)", tag: "control") - pendingLock.lock() - p.delivering = false - var giveUp = false - if p.pasted { - p.enterAttempts += 1 - giveUp = p.enterAttempts >= SessionController.MAX_ENTER_ATTEMPTS - } - pendingLock.unlock() - if giveUp { - abandon(p, "had its prompt pasted but not submitted: pressing Enter failed (" - + errorMessage(error) + "); press Enter in it with the keys tool", live, clock.instant()) - } - } - } - } - } - - /// Gives up on `p`: tells its requester why, and lets notifications that were waiting - /// for the prompt judge the session as it is. - private func abandon(_ p: PromptDelivery, _ why: String, _ live: [String: Target], _ now: Date) { - pendingLock.lock() - guard prompts.contains(where: { $0 === p }) else { - pendingLock.unlock() - return - } - prompts.removeAll { $0 === p } - pendingLock.unlock() - Log.info("spawned session \(p.session) \(why)", tag: "control") - pendingLock.lock() - notifications.filter { $0.target == p.session }.forEach { $0.awaitPrompt = false } - pendingLock.unlock() - if let requesterName = p.requester, let requester = live[requesterName], requester.harness != .shell { - let notice = Notification(requesterName, p.session, nil, nil, now) - notice.message = SessionController.NOTICE_PREFIX + p.session + " " + why + ". Use the read tool to see it." - notice.firedAt = now - pendingLock.lock() - notifications.append(notice) - pendingLock.unlock() - } - } - - private func deliverNotifications(_ live: [String: Target], _ observed: inout [String: Look], _ now: Date) { - var callers: [String] = [] - var byCaller: [String: [Notification]] = [:] - pendingLock.lock() - for n in notifications where n.message != nil && !n.delivering { - if byCaller[n.caller] == nil { - callers.append(n.caller) - } - byCaller[n.caller, default: []].append(n) - } - pendingLock.unlock() - for caller in callers { - var ready: [Notification] = [] - for n in byCaller[caller]! { - pendingLock.lock() - let enterOwed = n.pasted - pendingLock.unlock() - // a pasted notice only owes its Enter: never dropped as undelivered - if !enterOwed && now.timeIntervalSince(n.firedAt!) > timings.notifyTtl { - drop(n, "undelivered for \(Int(timings.notifyTtl / 60)) min while \(caller) was busy") - } else { - ready.append(n) - } - } - if ready.isEmpty { - continue - } - let look = live[caller] != nil ? observeOnce(caller, live, &observed) : .GONE - if look.gone { - ready.forEach { drop($0, "its caller " + caller + " is gone") } - continue - } - // only into the caller's own harness, idle at its prompt: never while it waits - // for an answer (Enter would pick an option) and never into a bare shell — except - // the Enter owed for a notice already pasted, which goes in regardless - let atItsPrompt = !look.unknown - && look.obs!.classification.state == .idle - && live[caller]!.harness != .shell - && look.obs!.tracker.harnessRunning(look.obs!.capture.foregroundCommand) - pendingLock.lock() - let free = ready.filter { n in !n.delivering && notifications.contains { $0 === n } } - let enterOnly = free.filter(\.pasted) - let pasted = !enterOnly.isEmpty - let batch = pasted ? enterOnly : atItsPrompt ? free : [] - batch.forEach { $0.delivering = true } - pendingLock.unlock() - if batch.isEmpty { - continue // held until the caller is ready for input - } - // the old send-keys op types as is, where a newline would submit - let text = pasted ? "" : batch.map { $0.message! }.joined(separator: compat.has(.INPUT) ? "\n" : " ") - deliveries { [self] in - do { - try type(caller, text, true, pasted, false) { - pendingLock.lock() - batch.forEach { $0.pasted = true } - pendingLock.unlock() - } - pendingLock.lock() - notifications.removeAll { n in batch.contains { $0 === n } } - pendingLock.unlock() - } catch { - Log.warn("could not deliver a notification to \(caller): \(error)", tag: "control") - var givenUp: [Notification] = [] - pendingLock.lock() - for n in batch { - n.delivering = false - if n.pasted { - n.enterAttempts += 1 - if n.enterAttempts >= SessionController.MAX_ENTER_ATTEMPTS { - givenUp.append(n) - } - } - } - pendingLock.unlock() - givenUp.forEach { - drop($0, "it was pasted into \(caller) but not submitted: pressing Enter failed (" - + errorMessage(error) + ")") - } - } - } - } - } - - private func fire(_ n: Notification, _ description: String, _ state: String, _ now: Date) { - pendingLock.lock(); defer { pendingLock.unlock() } - n.message = SessionController.NOTICE_PREFIX + n.target + " " + description + " (" + state - + "). Use the read tool to see it." - n.firedAt = now - } - - private func drop(_ n: Notification, _ why: String) { - Log.info("dropping notification for \(n.caller) about \(n.target): \(why)", tag: "control") - pendingLock.lock(); defer { pendingLock.unlock() } - notifications.removeAll { $0 === n } - } - - /// One monitor's life: stopped by `serverStopped`, which waits on `done`. - private final class MonitorThread: @unchecked Sendable { - var thread: Thread? - @Atomic var stopped = false - let done = DispatchSemaphore(value: 0) - } - - private func monitorLoop(_ m: MonitorThread) { - var watch: DaemonWatch? - var backoff = timings.watchBackoffMin - var nextAttempt = Date() - defer { watch?.close() } - while isCurrentMonitor(m) && !m.stopped { - compat.revalidate() - if compat.has(.WATCH) && (watch == nil || !watch!.isOpen) && Date() >= nextAttempt { - watch?.close() - do { - watch = try daemon.watch(timings.watchQuietMs) { [weak self] in self?.onEvent($0) } - backoff = timings.watchBackoffMin - } catch { - watch = nil - if DaemonCompat.isUnsupported(error) { - // logged once per daemon; the monitor polls on its tick instead - compat.markMissing(.WATCH) - } else { - Log.debug("daemon watch unavailable, retrying in \(backoff) s: \(error)", tag: "control") - nextAttempt = Date().addingTimeInterval(backoff) - backoff = min(backoff * 2, timings.watchBackoffMax) - } - } - } - do { - try tick() - } catch { - Log.debug("control monitor tick failed: \(error)", tag: "control") - } - wakeCondition.lock() - let deadline = Date().addingTimeInterval(timings.tick) - while !wakePending && !m.stopped && Date() < deadline { - _ = wakeCondition.wait(until: deadline) - } - wakePending = false - wakeCondition.unlock() - } - } - - private func onEvent(_ event: SessionEvent) { - if event.type == MuxProtocol.EVENT_EXIT { - forget(event.name) - } - if hasPending() { - wake() - } - } - - private func wake() { - wakeCondition.lock() - wakePending = true - wakeCondition.broadcast() - wakeCondition.unlock() - } - - /// Whether the background monitor is running (tests). - func monitorRunning() -> Bool { - monitorLock.lock(); defer { monitorLock.unlock() } - return monitor != nil - } - - // MARK: - bookkeeping - - private func forget(_ session: String) { - stateLock.lock(); defer { stateLock.unlock() } - trackers.removeValue(forKey: session) - let suffix = "\u{0}" + session - seen = seen.filter { !$0.key.hasSuffix(suffix) } - } - - private func forgetAllBut(_ live: Set) { - stateLock.lock(); defer { stateLock.unlock() } - trackers = trackers.filter { live.contains($0.key) } - seen = seen.filter { key, _ in - guard let cut = key.firstIndex(of: "\u{0}") else { return false } - return live.contains(String(key[key.index(after: cut)...])) - } - } - - private static func seenKey(_ caller: String?, _ session: String) -> String { - (caller ?? "") + "\u{0}" + session - } - - private static func refuseSelf(_ caller: String?, _ target: Target, _ verb: String) throws { - if let caller, target.name == caller { - throw ToolError("refusing to " + verb + " your own session (" + caller + ")") - } - } - - private static func sessionsArgument(_ args: CoreJSON) throws -> [String] { - var names: [String] = [] - for field in ["session", "sessions"] { - guard let node = args.get(field), !node.isNull else { continue } - if node.isTextual && !JavaText.isBlank(node.asText()) { - let name = JavaText.strip(node.asText()) - if !names.contains(name) { names.append(name) } - } else if node.isArray { - for n in node.elements { - if !n.isTextual || JavaText.isBlank(n.asText()) { - throw ToolError(field + " must hold session names (strings)") - } - let name = JavaText.strip(n.asText()) - if !names.contains(name) { names.append(name) } - } - } else { - throw ToolError(field + " must be a session name or an array of them") - } - } - if names.isEmpty { - throw ToolError("session is required (a session name, or sessions: an array of them)") - } - return names - } - - private static func requiredText(_ args: CoreJSON, _ field: String) throws -> String { - guard let node = args.get(field), node.isTextual, !JavaText.isBlank(node.asText()) else { - throw ToolError(field + " is required (a string)") - } - return JavaText.strip(node.asText()) - } - - private static func optionalText(_ args: CoreJSON, _ field: String) throws -> String? { - guard let node = args.get(field), !node.isNull else { - return nil - } - if !node.isTextual { - throw ToolError(field + " must be a string") - } - let text = node.asText() - return JavaText.isBlank(text) ? nil : text - } - - /// `~` and `~/…` expanded; must name an existing directory by absolute path. - static func expandProject(_ text: String) throws -> URL { - let home = ProcessInfo.processInfo.environment["HOME"] ?? NSHomeDirectory() - let expanded = text == "~" ? home : text.hasPrefix("~/") ? home + text.dropFirst() : text - if expanded.contains("\u{0}") { - throw ToolError("not a valid path: " + text) - } - if !expanded.hasPrefix("/") { - throw ToolError("project must be an absolute path (or start with ~): " + text) - } - let path = PathCompat.normalize(URL(fileURLWithPath: expanded)) - var isDir: ObjCBool = false - if !FileManager.default.fileExists(atPath: path.path, isDirectory: &isDir) || !isDir.boolValue { - throw ToolError("project is not an existing directory: " + path.path) - } - return path - } - - private static func harnessIds() -> String { - HarnessType.allCases.map(\.id).joined(separator: ", ") - } - - private static func blankToNil(_ s: String?) -> String? { - guard let s, !JavaText.isBlank(s) else { return nil } - return s - } - - // MARK: - types - - /// A resolved daemon session and what the registry and its labels say about it. - private struct Target { - let name: String - let entry: SessionEntry? - let labels: [String: String] - let harness: HarnessType - let display: String? - let project: String - } - - /// One capture of a session, classified. `body` is the annotated screen's lines; - /// `masked` its chrome-free text for change comparison. - private struct Observation { - let capture: SessionCapture - let annotated: Bool - let classification: Classification - let masked: String - let body: [String] - let plain: String - let tracker: SessionTracker - } - - /// What one caller last read of one session; `plain` is the unmasked screen without - /// markers. - private struct Seen { - let outputBytes: Int64 - let masked: String - let lines: [String] - let plain: String - } - - /// A notify registration; `message` is set once it fired. Mutable fields are guarded by - /// `pendingLock`. A nil trigger is an internal notice. - private final class Notification { - let caller: String - let target: String - let trigger: Trigger? - let baseline: String? - let registered: Date - var message: String? - var firedAt: Date? - var delivering = false - /// The message is in the caller's composer; only its Enter is still owed. - var pasted = false - /// Failed tries of the owed Enter. - var enterAttempts = 0 - /// Registered while the target's spawn prompt was pending: FINISHED and NEEDS_INPUT - /// wait until the prompt is in and the target has reacted (seen WORKING or - /// WAITING_FOR_INPUT, or back at a shell); dropped when that takes longer than the - /// notify TTL. - var awaitPrompt = false - - init(_ caller: String, _ target: String, _ trigger: Trigger?, _ baseline: String?, _ registered: Date) { - self.caller = caller - self.target = target - self.trigger = trigger - self.baseline = baseline - self.registered = registered - } - } - - /// A spawn prompt waiting for its session to be ready. Mutable fields are guarded by - /// `pendingLock`. - private final class PromptDelivery { - let session: String - let prompt: String - let requester: String? - let deadline: Date - var delivering = false - /// The prompt is in the composer; only its Enter is still owed. - var pasted = false - /// Failed tries of the owed Enter. - var enterAttempts = 0 - - init(_ session: String, _ prompt: String, _ requester: String?, _ deadline: Date) { - self.session = session - self.prompt = prompt - self.requester = requester - self.deadline = deadline - } - } - - /// A caller mistake, reported verbatim as the tool's error text. `kind` tells the - /// special ones apart: text the old send-keys fallback cannot type safely, a multi-line - /// paste the program has not enabled bracketed paste for (nothing was written; retrying - /// cannot help), and a daemon that did not answer (a session that could not be listed - /// or captured is not known to be gone). - struct ToolError: Error, CustomStringConvertible, LocalizedError { - enum Kind { - case plain, legacyRefusal, pasteRefusal, unreachable - } - - let message: String - let kind: Kind - - init(_ message: String, _ kind: Kind = .plain) { - self.message = message - self.kind = kind - } - - static func unreachable() -> ToolError { - ToolError(SessionController.DAEMON_UNREACHABLE, .unreachable) - } - - var description: String { message } - var errorDescription: String? { message } - } - - // MARK: - tool definitions - - private static func toolDefs() -> [ToolDef] { - [ - ToolDef(TOOL_LIST, LIST_DESCRIPTION, schema()), - ToolDef(TOOL_READ, READ_DESCRIPTION, required(schema( - prop("session", "string", SESSION_ARG), - prop("full", "boolean", "true: return the whole screen even if you have seen it. " - + "Default false: only what changed since your last read.")), - "session")), - ToolDef(TOOL_SEND, SEND_DESCRIPTION, required(schema( - prop("session", "string", SESSION_ARG), - prop("text", "string", "The message to type, as one block (newlines do not submit; " - + "multi-line text needs a session that accepts pastes)."), - prop("enter", "boolean", "Press Enter after the text to submit it. Default true.")), - "session", "text")), - ToolDef(TOOL_KEYS, KEYS_DESCRIPTION, required(schema( - prop("session", "string", SESSION_ARG), - stringArray("keys", "Key names pressed in order, e.g. [\"Down\",\"Enter\"], [\"y\"], " - + "[\"Esc\"], [\"C-c\"]. See the tool description for every name.")), - "session", "keys")), - ToolDef(TOOL_NOTIFY, NOTIFY_DESCRIPTION, required(schema( - prop("session", "string", "The session to watch (name or display name)."), - stringArray("sessions", "Several sessions to watch instead; each notifies separately."), - enumProp("on", "What to be told about.", ["finished", "needs-input", "exited", "any-change"])), - "on")), - ToolDef(TOOL_SPAWN, SPAWN_DESCRIPTION, required(schema( - enumProp("harness", "Which agent (or plain shell) to run.", HarnessType.allCases.map(\.id)), - prop("project", "string", "The directory to run it in: an existing absolute path, ~ allowed."), - prop("name", "string", "Optional display name for the sidebar and for addressing it."), - prop("prompt", "string", "Optional first message, typed in once the harness is ready " - + "(multi-line only where the harness accepts pastes).")), - "harness", "project")), - ToolDef(TOOL_KILL, KILL_DESCRIPTION, required(schema(prop("session", "string", SESSION_ARG)), "session")), - ] - } - - private static let SESSION_ARG = "The session: its name (mhm-…) or display name, as shown by list." - - static let LIST_DESCRIPTION = """ - List the sessions you can see and drive: every terminal session \ - micro-harness-manager hosts (coding agents and shells), one per line: - `name · display name · harness · STATE · project · transcript: path · log: path` - Your own session is marked (you). STATE is WORKING (busy, output changing), \ - WAITING_FOR_INPUT (a question, approval or menu waits for an answer) or IDLE (at its \ - prompt, or its harness is not running). Address a session by its name or display name. - transcript is the harness's own conversation log (JSONL) when micro-harness-manager can find \ - it (claude-code, codex, muse, grok), else "-" — or, when it can't tell which file is a \ - session's, the folder with a note saying so. History lives there, not on screen: search \ - it with your file tools (grep, tail, read a line range) — never load a whole transcript, \ - they get large. Where the replies are: claude-code rows with "type":"assistant"; codex \ - "type":"response_item" rows whose payload is an assistant message; muse \ - "assistant_message_committed" events (session.jsonl); grok rows with "type":"assistant" \ - (chat_history.jsonl). - log is a plain-text copy of the session's output kept inside your own project \ - when the user has turned session logs on (Settings → Agent control), in \ - .microhm-sessions/ (git-ignored), for any harness — use it when the transcript is \ - outside what you may read, or for a shell. It holds the lines that scrolled off the \ - screen (the screen itself is what read shows); for a full-screen program, its \ - screen's lines as they appear, each new line once and without the harness's status \ - bars, under `--- microhm ·