Terminal: drop files / paperclip; net core: fallback exit, re-test on network change, hide/unhide connections

- term.macOS: dropping files over an open terminal or the paperclip types their
  shell-escaped paths (bracketed paste when the program asks for it).
- Traffic now goes through a fallback group "exit": the pick while it answers,
  "auto" when it doesn't. A pinned connection that dies no longer cuts the Mac off.
- Faster checks (exit 30 s, auto 60 s, 3 failures trigger a re-test) and a re-test
  of every group 4 s after any network change (Wi-Fi switch, sleep, AmneziaVPN).
- hide/unhide instead of deleting keys: Amnezia connections and VLESS nodes leave the
  list and "auto"; kept on disk, returned from "Убранные".
- Core logs are owner-only (they can contain the subscription URL).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
maksarsanjeev
2026-10-09 23:25:47 +03:00
parent 9e02402555
commit 422c538df6
9 changed files with 373 additions and 56 deletions
+1
View File
@@ -26,6 +26,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
Self.pruneInbox()
setupMenuBarItem()
CodexUsageMonitor.shared.start()
NetCore.shared.startWatchingNetwork()
AgentWatch.shared.start()
AgentAuth.shared.start()
setupIsland()
@@ -110,6 +110,8 @@ final class IslandWindowController: NSWindowController {
dropView.autoresizingMask = [.width, .height]
dropView.onDragEntered = { [weak self] loc in
Task { @MainActor in
// Over an open terminal the file goes into its command line, not the shelf.
if TerminalStore.shared.activeTab != nil { return }
let iLoc = self?.windowToIsland(loc) ?? CGPoint(x: 320, y: 88)
AppState.shared.fileDragOver = true
// enterZone sets isActive=true BEFORE hookExpand triggers re-render,
@@ -121,6 +123,7 @@ final class IslandWindowController: NSWindowController {
}
dropView.onDragUpdated = { [weak self] loc in
Task { @MainActor in
if TerminalStore.shared.activeTab != nil { return }
let iLoc = self?.windowToIsland(loc) ?? CGPoint(x: 320, y: 88)
UploadSequenceEngine.shared.updateCursor(x: iLoc.x, y: iLoc.y)
}
@@ -135,6 +138,10 @@ final class IslandWindowController: NSWindowController {
}
dropView.onFilesDropped = { urls in
Task { @MainActor in
if let tab = TerminalStore.shared.activeTab {
TerminalStore.shared.insertPaths(urls, into: tab)
return
}
await FileDropHandler.handle(urls: urls, state: AppState.shared)
}
}
+169 -24
View File
@@ -1,5 +1,6 @@
import SwiftUI
import AppKit
import Network
// MARK: - Networks (globe in the header)
//
@@ -9,6 +10,7 @@ import AppKit
// • right column — client networks: groups "<client>-sw" switched between REJECT and
// the client's WireGuard tunnel.
// Switching a group never reloads the core, so open connections (this chat) survive.
// Traffic goes through "exit": the pick in "ai-out" while it answers, "auto" when it doesn't.
struct NetExit: Identifiable, Equatable {
var id: String // proxy name in the core
@@ -44,6 +46,14 @@ final class NetCore: ObservableObject {
@Published var amneziaConns: [NetExit] = []
@Published var amneziaNow = ""
@Published var amneziaAutoPick = ""
/// What traffic really uses: "ai-out" (the pick) or "auto" when the pick stopped answering.
@Published var exitNow = ""
/// Connections taken out of the list (Amnezia keys and VLESS nodes), can be put back.
@Published var hidden: [NetExit] = []
/// Asked before hiding: the connection's proxy name.
@Published var pendingHide: String?
var fallbackActive: Bool { exitNow == "auto" && currentExit != "auto" }
/// Delays measured by the group test (covers the subscription nodes too).
private var measured: [String: Int] = [:]
@@ -60,7 +70,7 @@ final class NetCore: ObservableObject {
//
// The core, its config, keys and API secret are root-only. BroV only talks to the
// narrow helper over /var/run/brov-netctl.sock (owner: this user, 0600): state, select,
// delay, tun, add_key, remove_key — nothing that could rewrite the core config.
// delay, tun, add_key, hide, unhide — nothing that could point traffic elsewhere.
private nonisolated static let socketPath = "/var/run/brov-netctl.sock"
@@ -136,6 +146,11 @@ final class NetCore: ObservableObject {
if let h = proxies[name]?["history"] as? [[String: Any]], let d = h.last?["delay"] as? Int { return d }
return providerDelay[name]
}
exitNow = proxies["exit"]?["now"] as? String ?? ""
let hid = st["hidden"] as? [String: [String]] ?? [:]
hidden = ((hid["amnezia"] ?? []) + (hid["vless"] ?? [])).map {
NetExit(id: $0, title: Self.pretty($0).0, subtitle: Self.pretty($0).1, delay: nil)
}
amneziaNow = proxies["amnezia"]?["now"] as? String ?? ""
amneziaAutoPick = proxies["amnezia-auto"]?["now"] as? String ?? ""
let amneziaEffective = amneziaNow == "amnezia-auto" ? amneziaAutoPick : amneziaNow
@@ -234,12 +249,65 @@ final class NetCore: ObservableObject {
return (true, "Ключ «\(name)» сохранён (\(server)), но сервер пока не отвечает. Он будет участвовать в выборе, когда оживёт.")
}
func removeAmnezia(_ proxyName: String) async {
_ = await call(["cmd": "remove_key", "name": proxyName])
SoundEngine.shared.play("close")
/// Takes a connection out of the list and out of "auto" (nothing is deleted).
func hide(_ name: String) async {
await changeHidden(name, cmd: "hide")
}
func unhide(_ name: String) async {
await changeHidden(name, cmd: "unhide")
}
private func changeHidden(_ name: String, cmd: String) async {
busy = true
let r = await call(["cmd": cmd, "name": name], timeout: 40)
busy = false
if r?["ok"] as? Bool == true {
lastError = nil
measured.removeValue(forKey: name)
SoundEngine.shared.play(cmd == "hide" ? "close" : "pop")
} else {
lastError = "Не получилось: \(r?["error"] as? String ?? "помощник не ответил")."
}
try? await Task.sleep(for: .milliseconds(500))
await refresh()
}
/// VLESS nodes come from the subscription: hiding one rebuilds the core config.
static func needsReload(_ name: String) -> Bool { !name.hasPrefix("AWG ") }
// MARK: Network changes
//
// Moving between home / Saga / Planet9 Wi-Fi, waking from sleep or AmneziaVPN going on
// and off leaves the WireGuard tunnels talking from an address that no longer exists.
// Re-test everything a few seconds after the change so "auto" and "exit" re-pick at
// once instead of at the next scheduled check.
private var pathMonitor: NWPathMonitor?
private var recheckTask: Task<Void, Never>?
func startWatchingNetwork() {
guard pathMonitor == nil else { return }
let m = NWPathMonitor()
m.pathUpdateHandler = { _ in
Task { @MainActor in NetCore.shared.networkChanged() }
}
m.start(queue: DispatchQueue(label: "brov.net.path"))
pathMonitor = m
}
private func networkChanged() {
recheckTask?.cancel()
recheckTask = Task {
try? await Task.sleep(for: .seconds(4))
guard !Task.isCancelled else { return }
_ = await call(["cmd": "delay", "group": "auto"], timeout: 15)
_ = await call(["cmd": "delay", "group": "amnezia"], timeout: 15)
_ = await call(["cmd": "delay", "group": "exit"], timeout: 15)
await refresh()
}
}
static var amneziaRunning: Bool {
// The app holds routes; its background AmneziaVPN-service doesn't.
NSWorkspace.shared.runningApplications.contains { $0.localizedName == "AmneziaVPN" }
@@ -334,6 +402,16 @@ struct NetPanel: View {
}
}
if net.running, net.tunOn, NetCore.amneziaRunning {
Text("Открыто приложение AmneziaVPN, а ядро тоже перехватывает трафик — они мешают друг другу. Выключи что-то одно.")
.font(.system(size: 11.5)).foregroundColor(Color(hex: "#FB923C"))
.fixedSize(horizontal: false, vertical: true).frame(width: 444, alignment: .leading)
}
if net.running, net.fallbackActive {
Text("«\(NetCore.pretty(net.currentExit).0)» не отвечает — сейчас трафик идёт через Авто (\(NetCore.pretty(net.autoPick).0)). Вернётся сам, когда выбранный выход оживёт.")
.font(.system(size: 11.5)).foregroundColor(Color(hex: "#F5A524"))
.fixedSize(horizontal: false, vertical: true).frame(width: 444, alignment: .leading)
}
if let err = net.lastError {
Text(err).font(.system(size: 11.5)).foregroundColor(Color(hex: "#FB923C"))
.fixedSize(horizontal: false, vertical: true).frame(width: 444, alignment: .leading)
@@ -361,13 +439,16 @@ struct NetPanel: View {
if e.id == "amnezia" {
AmneziaSection(net: net, exit: e)
} else {
NetRow(title: e.title, subtitle: e.subtitle, delay: e.delay,
isOn: net.currentExit == e.id, accent: "#D97757") {
guard net.currentExit != e.id else { return }
Task { await net.select(exit: e.id) }
RemovableRow(removable: e.id != "auto") { net.pendingHide = e.id } row: {
NetRow(title: e.title, subtitle: e.subtitle, delay: e.delay,
isOn: net.currentExit == e.id, accent: "#D97757") {
guard net.currentExit != e.id else { return }
Task { await net.select(exit: e.id) }
}
}
}
}
if !net.hidden.isEmpty { HiddenSection(net: net) }
}
.frame(width: 230)
@@ -391,6 +472,18 @@ struct NetPanel: View {
}
}
.padding(14)
.confirmationDialog("Убрать «\(NetCore.pretty(net.pendingHide ?? "").0)»?",
isPresented: Binding(get: { net.pendingHide != nil }, set: { if !$0 { net.pendingHide = nil } })) {
Button("Убрать", role: .destructive) {
if let n = net.pendingHide { Task { await net.hide(n) } }
net.pendingHide = nil
}
Button("Отмена", role: .cancel) { net.pendingHide = nil }
} message: {
Text(NetCore.needsReload(net.pendingHide ?? "")
? "Узел пропадёт из списка и из «Авто». Ядро перечитает настройки — открытые соединения (и этот чат) на секунду переподключатся. Вернуть можно в «Убранные»."
: "Подключение пропадёт из списка и из «Авто». Ключ останется на Маке — вернуть можно в «Убранные».")
}
.task {
await net.refresh()
if net.running { await net.measure() }
@@ -453,7 +546,6 @@ struct AmneziaSection: View {
let exit: NetExit
@State private var expanded = false
@State private var adding = false
@State private var confirmRemove: String?
var body: some View {
VStack(alignment: .leading, spacing: 2) {
@@ -484,13 +576,10 @@ struct AmneziaSection: View {
if expanded {
VStack(alignment: .leading, spacing: 1) {
ForEach(net.amneziaConns) { c in
NetRow(title: c.title, subtitle: c.subtitle, delay: c.delay,
isOn: net.currentExit == "amnezia" && net.amneziaNow == c.id, accent: "#D97757") {
Task { await net.select(amnezia: c.id) }
}
.contextMenu {
if c.id != "amnezia-auto" {
Button("Удалить подключение…", role: .destructive) { confirmRemove = c.id }
RemovableRow(removable: c.id != "amnezia-auto") { net.pendingHide = c.id } row: {
NetRow(title: c.title, subtitle: c.subtitle, delay: c.delay,
isOn: net.currentExit == "amnezia" && net.amneziaNow == c.id, accent: "#D97757") {
Task { await net.select(amnezia: c.id) }
}
}
}
@@ -515,16 +604,72 @@ struct AmneziaSection: View {
}
}
}
.confirmationDialog("Удалить подключение «\(NetCore.pretty(confirmRemove ?? "").0)»?",
isPresented: Binding(get: { confirmRemove != nil }, set: { if !$0 { confirmRemove = nil } })) {
Button("Удалить", role: .destructive) {
if let n = confirmRemove { Task { await net.removeAmnezia(n) } }
confirmRemove = nil
}
}
/// A row with a "−" that appears on hover: takes the connection out of the list.
struct RemovableRow<Row: View>: View {
let removable: Bool
let onRemove: () -> Void
@ViewBuilder let row: () -> Row
@State private var hovered = false
var body: some View {
HStack(spacing: 2) {
row()
if removable && hovered {
Button(action: onRemove) {
Image(systemName: "minus.circle.fill")
.font(.system(size: 12))
.foregroundColor(Color(hex: "#8E939C"))
}
.buttonStyle(.plain)
.help("Убрать из списка и из «Авто»")
.transition(.opacity)
}
Button("Отмена", role: .cancel) { confirmRemove = nil }
} message: {
Text("Ключ будет удалён с этого Мака. Вернуть можно, вставив его снова.")
}
.onHover { h in withAnimation(.easeOut(duration: 0.12)) { hovered = h } }
}
}
/// Connections taken out of the list, each with "Вернуть".
struct HiddenSection: View {
@ObservedObject var net: NetCore
@State private var expanded = false
var body: some View {
VStack(alignment: .leading, spacing: 2) {
Button { withAnimation(.easeOut(duration: 0.15)) { expanded.toggle() } } label: {
HStack(spacing: 4) {
Text("Убранные (\(net.hidden.count))").font(.system(size: 11, weight: .medium))
Image(systemName: expanded ? "chevron.up" : "chevron.down").font(.system(size: 8, weight: .bold))
}
.foregroundColor(Color(hex: "#8E939C"))
.padding(.horizontal, 8).padding(.vertical, 5)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
if expanded {
ForEach(net.hidden) { h in
HStack(spacing: 8) {
VStack(alignment: .leading, spacing: 1) {
Text(h.title).font(.system(size: 12, weight: .medium)).foregroundColor(Color(hex: "#8E939C"))
Text(h.subtitle).font(.system(size: 10.5)).foregroundColor(Color(hex: "#5F646D")).lineLimit(1)
}
Spacer(minLength: 4)
Button { Task { await net.unhide(h.id) } } label: {
Text("Вернуть").font(.system(size: 11, weight: .medium))
.padding(.horizontal, 8).frame(height: 20)
.background(Capsule().fill(Color.white.opacity(0.08)))
}
.buttonStyle(.plain)
.disabled(net.busy)
}
.padding(.horizontal, 8).padding(.vertical, 3)
}
}
}
.padding(.top, 4)
}
}
+55
View File
@@ -127,6 +127,48 @@ final class TerminalStore: NSObject, LocalProcessTerminalViewDelegate {
}
}
/// The terminal tab on screen right now, if any (drops and the paperclip go there).
var activeTab: UUID? {
let s = AppState.shared
guard s.view == .terminal, s.mode == .expanded, let id = s.activeTabId,
s.tabs.first(where: { $0.id == id })?.kind == .terminal else { return nil }
return id
}
/// Types the files' paths at the prompt, shell-escaped like Terminal.app does on a drop.
/// Sent as a bracketed paste when the program asks for it (claude then attaches images).
func insertPaths(_ urls: [URL], into id: UUID) {
guard let v = views[id], !urls.isEmpty else { return }
let text = urls.map { Self.shellEscaped($0.path) }.joined(separator: " ") + " "
if v.getTerminal().bracketedPasteMode {
v.send(txt: "\u{1b}[200~" + text + "\u{1b}[201~")
} else {
v.send(txt: text)
}
v.window?.makeFirstResponder(v)
}
func choosePaths(for id: UUID) {
let panel = NSOpenPanel()
panel.canChooseFiles = true
panel.canChooseDirectories = true
panel.allowsMultipleSelection = true
panel.prompt = "Вставить"
panel.message = "Пути выбранных файлов появятся в терминале"
NSApp.activate(ignoringOtherApps: true)
if panel.runModal() == .OK { insertPaths(panel.urls, into: id) }
}
static func shellEscaped(_ path: String) -> String {
let special = Set(" \t!\"#$&'()*,;<=>?[\\]^`{|}~")
var out = ""
for ch in path {
if special.contains(ch) { out.append("\\") }
out.append(ch)
}
return out
}
private func tabId(of source: TerminalView) -> UUID? {
views.first(where: { $0.value === source })?.key
}
@@ -184,6 +226,19 @@ struct TerminalScreen: View {
TerminalTabView(tabId: id)
.padding(.horizontal, 10)
.padding(.vertical, 8)
.overlay(alignment: .topTrailing) {
Button { TerminalStore.shared.choosePaths(for: id) } label: {
Image(systemName: "paperclip")
.font(.system(size: 11, weight: .semibold))
.foregroundColor(Color(hex: "#8E939C"))
.frame(width: 24, height: 24)
.background(Circle().fill(Color.white.opacity(0.08)))
}
.buttonStyle(.plain)
.help("Вставить путь к файлу (или перетащи файл в терминал)")
.padding(.top, 8)
.padding(.trailing, 14)
}
}
}
.padding(.top, 4)