OpenTalon / app · opentalon.ai / native / Sources / OpenTalon / OpenTalonApp.swift
| 1 | import AppKit |
| 2 | import Darwin |
| 3 | import Sparkle |
| 4 | import SwiftUI |
| 5 | |
| 6 | @main |
| 7 | enum OpenTalonApp { |
| 8 | @MainActor static func main() { |
| 9 | // Failed pipe writes are reported as service errors instead of terminating the GUI. |
| 10 | signal(SIGPIPE, SIG_IGN) |
| 11 | if CommandLine.arguments.contains("--daily-backup") { exit(runDailyBackup()) } |
| 12 | if CommandLine.arguments.contains("--background"), |
| 13 | !CommandLine.arguments.contains("--workspace-launch") { |
| 14 | exit(launchBackgroundWorkspace()) |
| 15 | } |
| 16 | let app = NSApplication.shared |
| 17 | let delegate = AppController() |
| 18 | app.delegate = delegate |
| 19 | withExtendedLifetime(delegate) { app.run() } |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | @MainActor |
| 24 | final class AppController: NSObject, NSApplicationDelegate, NSWindowDelegate, NSToolbarDelegate, SPUUpdaterDelegate { |
| 25 | private let sidebarTool = NSToolbarItem.Identifier("Sidebar") |
| 26 | private let titleTool = NSToolbarItem.Identifier("WorkspaceTitle") |
| 27 | private let dashboardTool = NSToolbarItem.Identifier("Dashboard") |
| 28 | private let searchTool = NSToolbarItem.Identifier("Search") |
| 29 | private let settingsTool = NSToolbarItem.Identifier("Settings") |
| 30 | private let background = CommandLine.arguments.contains("--background") |
| 31 | private var window: NSWindow? |
| 32 | private var lock: Int32 = -1 |
| 33 | private var quitting = false |
| 34 | private var terminationSignal: DispatchSourceSignal? |
| 35 | private var model: WorkspaceModel! |
| 36 | private var updaterController: SPUStandardUpdaterController? |
| 37 | |
| 38 | func applicationDidFinishLaunching(_ notification: Notification) { |
| 39 | let profile = workspaceProfile() |
| 40 | let useDefaults = profile.resolvingSymlinksInPath() == defaultWorkspaceProfile().resolvingSymlinksInPath() |
| 41 | model = WorkspaceModel(profile: profile, useDefaults: useDefaults) |
| 42 | model.service.onExit = { [weak self] in |
| 43 | guard let self, self.background, self.window == nil else { return } |
| 44 | NSApp.terminate(nil) |
| 45 | } |
| 46 | configureTerminationSignal() |
| 47 | model.appearanceChanged = { [weak self] theme in |
| 48 | self?.window?.appearance = Self.windowAppearance(theme) |
| 49 | } |
| 50 | NSApp.setActivationPolicy(background ? .accessory : .regular) |
| 51 | model.retryWorkspace = { [weak self] in self?.openWorkspace(profile) } |
| 52 | openWorkspace(profile) |
| 53 | if background && lock < 0 { |
| 54 | NSApp.terminate(nil) |
| 55 | return |
| 56 | } |
| 57 | configureMenus() |
| 58 | if !background { showWorkspace(nil) } |
| 59 | } |
| 60 | |
| 61 | private func openWorkspace(_ profile: URL) { |
| 62 | guard lock < 0 else { return } |
| 63 | model.startupError = nil |
| 64 | model.workspaceLocked = false |
| 65 | do { |
| 66 | lock = try acquireProfile(profile) |
| 67 | try model.service.start(profile: profile, visible: !background || window?.isVisible == true) |
| 68 | } catch let error as ServiceFailure where error.code == "PROFILE_OPEN" { |
| 69 | model.workspaceLocked = true |
| 70 | } catch { |
| 71 | if lock >= 0 { |
| 72 | close(lock) |
| 73 | lock = -1 |
| 74 | } |
| 75 | model.startupError = error.localizedDescription |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows: Bool) -> Bool { |
| 80 | showWorkspace(nil) |
| 81 | return false |
| 82 | } |
| 83 | |
| 84 | func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { false } |
| 85 | |
| 86 | func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply { |
| 87 | if quitting || model == nil { return .terminateNow } |
| 88 | guard permitClose() else { return .terminateCancel } |
| 89 | guard model.service.ready else { |
| 90 | model.service.stop() |
| 91 | return .terminateNow |
| 92 | } |
| 93 | quitting = true |
| 94 | model.service.onExit = { NSApp.reply(toApplicationShouldTerminate: true) } |
| 95 | model.service.stop() |
| 96 | return .terminateLater |
| 97 | } |
| 98 | |
| 99 | private func configureTerminationSignal() { |
| 100 | signal(SIGTERM, SIG_IGN) |
| 101 | let source = DispatchSource.makeSignalSource(signal: SIGTERM, queue: .main) |
| 102 | source.setEventHandler { [weak self] in |
| 103 | guard let self, self.model.service.ready else { exit(EXIT_SUCCESS) } |
| 104 | self.model.service.onExit = { exit(EXIT_SUCCESS) } |
| 105 | self.model.service.stop() |
| 106 | DispatchQueue.main.asyncAfter(deadline: .now() + 10) { exit(EXIT_FAILURE) } |
| 107 | } |
| 108 | source.resume() |
| 109 | terminationSignal = source |
| 110 | } |
| 111 | |
| 112 | func windowShouldClose(_ sender: NSWindow) -> Bool { permitClose() } |
| 113 | |
| 114 | func windowWillClose(_ notification: Notification) { reportWindow(visible: false) } |
| 115 | |
| 116 | func windowDidBecomeKey(_ notification: Notification) { model.isWorkspaceWindowKey = true } |
| 117 | |
| 118 | func windowDidResignKey(_ notification: Notification) { model.isWorkspaceWindowKey = false } |
| 119 | |
| 120 | private func reportWindow(visible: Bool) { |
| 121 | guard model.service.ready else { return } |
| 122 | Task { |
| 123 | let _: EmptyResponse? = try? await model.service.call("native_window_state", ["visible": visible]) |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | private func permitClose() -> Bool { |
| 128 | guard model?.draftDirty == true else { return true } |
| 129 | let alert = NSAlert() |
| 130 | alert.messageText = "Your task has unsaved text" |
| 131 | alert.informativeText = "Save or discard the task or revision request draft before closing." |
| 132 | alert.addButton(withTitle: "Keep editing") |
| 133 | if let window, window.isVisible { alert.beginSheetModal(for: window) } |
| 134 | else { alert.runModal() } |
| 135 | return false |
| 136 | } |
| 137 | |
| 138 | private func startUpdaterIfConfigured() { |
| 139 | guard updaterController == nil, |
| 140 | Bundle.main.object(forInfoDictionaryKey: "SUFeedURL") != nil else { return } |
| 141 | let updater = SPUStandardUpdaterController( |
| 142 | startingUpdater: false, updaterDelegate: self, userDriverDelegate: nil |
| 143 | ) |
| 144 | updaterController = updater |
| 145 | configureMenus() |
| 146 | updater.startUpdater() |
| 147 | } |
| 148 | |
| 149 | func updater(_ updater: SPUUpdater, shouldPostponeRelaunchForUpdate item: SUAppcastItem, |
| 150 | untilInvokingBlock install: @escaping () -> Void) -> Bool { |
| 151 | guard updateWouldInterruptWork else { return false } |
| 152 | Task { |
| 153 | while updateWouldInterruptWork { |
| 154 | try? await Task.sleep(for: .seconds(1)) |
| 155 | } |
| 156 | install() |
| 157 | } |
| 158 | return true |
| 159 | } |
| 160 | |
| 161 | private var updateWouldInterruptWork: Bool { |
| 162 | model.draftDirty || model.agentChat.busy || model.workspace?.agentRuns.contains(where: \.active) == true |
| 163 | } |
| 164 | |
| 165 | @objc private func showWorkspace(_ sender: Any?) { |
| 166 | if NSApp.activationPolicy() != .regular { NSApp.setActivationPolicy(.regular) } |
| 167 | startUpdaterIfConfigured() |
| 168 | if window == nil { |
| 169 | let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1480, height: 910), |
| 170 | styleMask: [.titled, .closable, .miniaturizable, .resizable], |
| 171 | backing: .buffered, defer: false) |
| 172 | window.title = "OpenTalon" |
| 173 | window.titleVisibility = .hidden |
| 174 | window.appearance = Self.windowAppearance(model.workspace?.theme ?? .system) |
| 175 | window.toolbarStyle = .unified |
| 176 | let toolbar = NSToolbar(identifier: "Workspace") |
| 177 | toolbar.delegate = self |
| 178 | toolbar.displayMode = .iconOnly |
| 179 | window.toolbar = toolbar |
| 180 | window.isReleasedWhenClosed = false |
| 181 | window.delegate = self |
| 182 | window.contentMinSize = NSSize(width: 980, height: 640) |
| 183 | window.contentView = NSHostingView(rootView: WorkspaceView().environment(model)) |
| 184 | window.center() |
| 185 | if !model.isolatedProfile { |
| 186 | window.setFrameAutosaveName("OpenTalonWorkspace") |
| 187 | } |
| 188 | self.window = window |
| 189 | } |
| 190 | window?.makeKeyAndOrderFront(nil) |
| 191 | reportWindow(visible: true) |
| 192 | NSApp.activate(ignoringOtherApps: true) |
| 193 | } |
| 194 | |
| 195 | @objc private func about(_ sender: Any?) { |
| 196 | showWorkspace(sender) |
| 197 | if model.sheet == nil { model.navigate(.about) } |
| 198 | } |
| 199 | |
| 200 | @objc private func settings(_ sender: Any?) { |
| 201 | showWorkspace(sender) |
| 202 | if model.workspace != nil { model.sheet = .settings } |
| 203 | } |
| 204 | |
| 205 | @objc private func newTask(_ sender: Any?) { |
| 206 | showWorkspace(sender) |
| 207 | if model.sheet == nil { model.newTask() } |
| 208 | } |
| 209 | |
| 210 | @objc private func findTasks(_ sender: Any?) { |
| 211 | showWorkspace(sender) |
| 212 | if model.sheet == nil { model.findTasks() } |
| 213 | } |
| 214 | |
| 215 | |
| 216 | private static func windowAppearance(_ theme: Theme) -> NSAppearance? { |
| 217 | switch theme { |
| 218 | case .system: nil |
| 219 | case .graphite: NSAppearance(named: .darkAqua) |
| 220 | case .paper, .light: NSAppearance(named: .aqua) |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { |
| 225 | [sidebarTool, titleTool, dashboardTool, searchTool, settingsTool, .flexibleSpace] |
| 226 | } |
| 227 | |
| 228 | func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { |
| 229 | [sidebarTool, titleTool, .flexibleSpace, dashboardTool, searchTool, settingsTool] |
| 230 | } |
| 231 | |
| 232 | func toolbar(_ toolbar: NSToolbar, itemForItemIdentifier identifier: NSToolbarItem.Identifier, |
| 233 | willBeInsertedIntoToolbar flag: Bool) -> NSToolbarItem? { |
| 234 | if identifier == titleTool { |
| 235 | let title = NSTextField(labelWithString: "OpenTalon") |
| 236 | title.font = .systemFont(ofSize: 13, weight: .semibold) |
| 237 | title.textColor = .labelColor |
| 238 | title.sizeToFit() |
| 239 | let item = NSToolbarItem(itemIdentifier: identifier) |
| 240 | item.view = title |
| 241 | item.visibilityPriority = .high |
| 242 | return item |
| 243 | } |
| 244 | let spec: (label: String, symbol: String, action: Selector) |
| 245 | switch identifier { |
| 246 | case sidebarTool: spec = (sidebarActionTitle, "sidebar.left", #selector(toggleSidebar(_:))) |
| 247 | case dashboardTool: spec = ("Dashboard", "square.grid.2x2", #selector(dashboard(_:))) |
| 248 | case searchTool: spec = ("Find tasks", "magnifyingglass", #selector(findTasks(_:))) |
| 249 | case settingsTool: spec = ("Settings", "gearshape", #selector(settings(_:))) |
| 250 | default: return nil |
| 251 | } |
| 252 | let item = NSToolbarItem(itemIdentifier: identifier) |
| 253 | item.label = spec.label |
| 254 | item.paletteLabel = identifier == sidebarTool ? "Toggle Sidebar" : spec.label |
| 255 | item.toolTip = spec.label |
| 256 | item.image = NSImage(systemSymbolName: spec.symbol, accessibilityDescription: spec.label) |
| 257 | item.target = self |
| 258 | item.action = spec.action |
| 259 | item.isBordered = true |
| 260 | return item |
| 261 | } |
| 262 | |
| 263 | private var sidebarActionTitle: String { model.showsSidebar ? "Hide Sidebar" : "Show Sidebar" } |
| 264 | |
| 265 | @objc private func toggleSidebar(_ sender: Any?) { |
| 266 | model.showsSidebar.toggle() |
| 267 | if let item = window?.toolbar?.items.first(where: { $0.itemIdentifier == sidebarTool }) { |
| 268 | item.label = sidebarActionTitle |
| 269 | item.toolTip = sidebarActionTitle |
| 270 | item.image?.accessibilityDescription = sidebarActionTitle |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | @objc private func dashboard(_ sender: Any?) { |
| 275 | showWorkspace(sender) |
| 276 | if model.sheet == nil { model.navigate(.dashboard) } |
| 277 | } |
| 278 | |
| 279 | private func configureMenus() { |
| 280 | let main = NSMenu() |
| 281 | NSApp.mainMenu = main |
| 282 | let app = menu("OpenTalon", in: main) |
| 283 | add("About OpenTalon", #selector(about(_:)), "", to: app, target: self) |
| 284 | if let updaterController { |
| 285 | add("Check for Updates…", #selector(SPUStandardUpdaterController.checkForUpdates(_:)), |
| 286 | "", to: app, target: updaterController) |
| 287 | } |
| 288 | add("Show OpenTalon", #selector(showWorkspace(_:)), "", to: app, target: self) |
| 289 | app.addItem(.separator()) |
| 290 | add("Settings…", #selector(settings(_:)), ",", to: app, target: self) |
| 291 | app.addItem(.separator()) |
| 292 | add("Hide OpenTalon", #selector(NSApplication.hide(_:)), "h", to: app) |
| 293 | let hideOthers = add("Hide Others", #selector(NSApplication.hideOtherApplications(_:)), "h", to: app) |
| 294 | hideOthers.keyEquivalentModifierMask = [.command, .option] |
| 295 | add("Show All", #selector(NSApplication.unhideAllApplications(_:)), "", to: app) |
| 296 | app.addItem(.separator()) |
| 297 | add("Quit OpenTalon", #selector(NSApplication.terminate(_:)), "q", to: app) |
| 298 | |
| 299 | let file = menu("File", in: main) |
| 300 | add("New task", #selector(newTask(_:)), "n", to: file, target: self) |
| 301 | add("Find tasks", #selector(findTasks(_:)), "f", to: file, target: self) |
| 302 | file.addItem(.separator()) |
| 303 | add("Close", #selector(NSWindow.performClose(_:)), "w", to: file) |
| 304 | |
| 305 | let edit = menu("Edit", in: main) |
| 306 | add("Undo", Selector(("undo:")), "z", to: edit) |
| 307 | let redo = add("Redo", Selector(("redo:")), "z", to: edit) |
| 308 | redo.keyEquivalentModifierMask = [.command, .shift] |
| 309 | edit.addItem(.separator()) |
| 310 | add("Cut", #selector(NSText.cut(_:)), "x", to: edit) |
| 311 | add("Copy", #selector(NSText.copy(_:)), "c", to: edit) |
| 312 | add("Paste", #selector(NSText.paste(_:)), "v", to: edit) |
| 313 | add("Select All", #selector(NSText.selectAll(_:)), "a", to: edit) |
| 314 | |
| 315 | let view = menu("View", in: main) |
| 316 | let sidebar = add("Toggle Sidebar", #selector(toggleSidebar(_:)), "s", to: view, target: self) |
| 317 | sidebar.keyEquivalentModifierMask = [.command, .control] |
| 318 | let fullscreen = add("Toggle Full Screen", #selector(NSWindow.toggleFullScreen(_:)), "f", to: view) |
| 319 | fullscreen.keyEquivalentModifierMask = [.command, .control] |
| 320 | let window = menu("Window", in: main) |
| 321 | NSApp.windowsMenu = window |
| 322 | add("Minimize", #selector(NSWindow.performMiniaturize(_:)), "m", to: window) |
| 323 | add("Zoom", #selector(NSWindow.performZoom(_:)), "", to: window) |
| 324 | add("Bring All to Front", #selector(NSApplication.arrangeInFront(_:)), "", to: window) |
| 325 | } |
| 326 | |
| 327 | private func menu(_ title: String, in parent: NSMenu) -> NSMenu { |
| 328 | let item = NSMenuItem() |
| 329 | let menu = NSMenu(title: title) |
| 330 | item.submenu = menu |
| 331 | parent.addItem(item) |
| 332 | return menu |
| 333 | } |
| 334 | |
| 335 | @discardableResult |
| 336 | private func add(_ title: String, _ selector: Selector, _ key: String, to menu: NSMenu, target: AnyObject? = nil) -> NSMenuItem { |
| 337 | let item = NSMenuItem(title: title, action: selector, keyEquivalent: key) |
| 338 | item.target = target |
| 339 | menu.addItem(item) |
| 340 | return item |
| 341 | } |
| 342 | } |
| 343 | |
| 344 | private func workspaceProfile() -> URL { |
| 345 | if let override = ProcessInfo.processInfo.environment["OPENTALON_PROFILE"] { |
| 346 | return URL(fileURLWithPath: override, isDirectory: true) |
| 347 | } |
| 348 | return defaultWorkspaceProfile() |
| 349 | } |
| 350 | |
| 351 | private func defaultWorkspaceProfile() -> URL { |
| 352 | FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] |
| 353 | .appendingPathComponent("OpenTalon Native", isDirectory: true) |
| 354 | } |
| 355 | |
| 356 | private func launchBackgroundWorkspace() -> Int32 { |
| 357 | // Launch through macOS so an MCP client's process context does not initialize AppKit. |
| 358 | let launcher = Process() |
| 359 | launcher.executableURL = URL(fileURLWithPath: "/usr/bin/open") |
| 360 | launcher.currentDirectoryURL = Bundle.main.bundleURL |
| 361 | launcher.arguments = [ |
| 362 | "-g", "-j", "-n", "-a", Bundle.main.bundleURL.path, |
| 363 | "--env", "OPENTALON_PROFILE=\(workspaceProfile().path)", |
| 364 | "--args", "--background", "--workspace-launch" |
| 365 | ] |
| 366 | do { |
| 367 | try launcher.run() |
| 368 | launcher.waitUntilExit() |
| 369 | return launcher.terminationStatus |
| 370 | } catch { |
| 371 | return 1 |
| 372 | } |
| 373 | } |
| 374 | |
| 375 | private func acquireProfile(_ profile: URL) throws -> Int32 { |
| 376 | try FileManager.default.createDirectory(at: profile, withIntermediateDirectories: true, |
| 377 | attributes: [.posixPermissions: 0o700]) |
| 378 | let legacy = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] |
| 379 | .appendingPathComponent("OpenTalon Prototype", isDirectory: true) |
| 380 | guard profile.resolvingSymlinksInPath() != legacy.resolvingSymlinksInPath() else { |
| 381 | throw ServiceFailure(code: "LEGACY_PROFILE", message: "Copy the Electron workspace from Settings instead of opening it directly.") |
| 382 | } |
| 383 | let file = profile.appendingPathComponent(".native-instance.lock") |
| 384 | let descriptor = open(file.path, O_RDWR | O_CREAT | O_CLOEXEC | O_NOFOLLOW, S_IRUSR | S_IWUSR) |
| 385 | guard descriptor >= 0 else { |
| 386 | throw ServiceFailure(code: "PROFILE_ACCESS", message: "Could not open the native data folder.") |
| 387 | } |
| 388 | while flock(descriptor, LOCK_EX | LOCK_NB) != 0 { |
| 389 | let failure = errno |
| 390 | if failure == EINTR { continue } |
| 391 | close(descriptor) |
| 392 | if failure == EWOULDBLOCK { |
| 393 | throw ServiceFailure(code: "PROFILE_OPEN", message: "This native workspace is already open.") |
| 394 | } |
| 395 | throw ServiceFailure(code: "PROFILE_ACCESS", message: "Could not lock the native data folder.") |
| 396 | } |
| 397 | return descriptor |
| 398 | } |
| 399 | |
| 400 | private func runDailyBackup() -> Int32 { |
| 401 | let profile = workspaceProfile() |
| 402 | guard FileManager.default.fileExists(atPath: profile.appendingPathComponent("opentalon.sqlite").path), |
| 403 | let resources = Bundle.main.resourceURL else { return 0 } |
| 404 | do { |
| 405 | let lock = try acquireProfile(profile) |
| 406 | defer { close(lock) } |
| 407 | let process = Process() |
| 408 | process.executableURL = resources.deletingLastPathComponent().appendingPathComponent("Helpers/node") |
| 409 | process.currentDirectoryURL = profile |
| 410 | process.arguments = [resources.appendingPathComponent("service/backup-once.cjs").path, profile.path] |
| 411 | var environment = ProcessInfo.processInfo.environment |
| 412 | environment.removeValue(forKey: "NODE_OPTIONS") |
| 413 | environment.removeValue(forKey: "NODE_PATH") |
| 414 | environment["PWD"] = profile.path |
| 415 | process.environment = environment |
| 416 | try process.run() |
| 417 | process.waitUntilExit() |
| 418 | return process.terminationStatus |
| 419 | } catch let error as ServiceFailure where error.code == "PROFILE_OPEN" { |
| 420 | // The regular app is already responsible for daily snapshots. |
| 421 | return 0 |
| 422 | } catch { |
| 423 | return 1 |
| 424 | } |
| 425 | } |