Compare commits
16 Commits
ed624218ec
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| b8541465ec | |||
| a4f5a89026 | |||
| 1889439ed7 | |||
| 977665806f | |||
| 0f4e110512 | |||
| 4f1e90ad8d | |||
| 46901f2b62 | |||
| 3c7931d710 | |||
| 7e5937ab3f | |||
| cd119d3b8f | |||
| f32397ea34 | |||
| 101a3860a9 | |||
| 7c4e9abc46 | |||
| 0199e9a7f0 | |||
| c0447ca327 | |||
| 08949d136c |
@@ -29,7 +29,7 @@ DerivedData must stay outside ~/Documents (iCloud adds Finder attributes and cod
|
|||||||
|
|
||||||
## Network core (globe 🌐 in the header)
|
## Network core (globe 🌐 in the header)
|
||||||
- mihomo runs as root: LaunchDaemon `local.maksar.brov.netd`, binary + config + keys + API secret in `/Library/Application Support/BroV/` (root, 0700). Nothing user-writable is read by root.
|
- mihomo runs as root: LaunchDaemon `local.maksar.brov.netd`, binary + config + keys + API secret in `/Library/Application Support/BroV/` (root, 0700). Nothing user-writable is read by root.
|
||||||
- BroV never sees the config or the API secret: it talks to the narrow root helper `scripts/netcore/netctl.py` (LaunchDaemon `local.maksar.brov.netctl`, socket `/var/run/brov-netctl.sock`, only the installing user) — commands: state, select, delay, tun (on = clean core restart, refused while the AmneziaVPN app is open; also points the Mac DNS into the core), add_key, hide, unhide.
|
- BroV never sees the config or the API secret: it talks to the narrow root helper `scripts/netcore/netctl.py` (LaunchDaemon `local.maksar.brov.netctl`, socket `/var/run/brov-netctl.sock`, only the installing user) — commands: state, select, delay, tun (on = clean core restart, refused while the AmneziaVPN app is open; also points the Mac DNS into the core), add_key, hide, unhide, refresh, rebind (the Mac changed networks: clean core restart — WireGuard tunnels stay bound to the old address, and re-creating them via a provider reload leaked sockets).
|
||||||
- `scripts/netcore/gen.py` builds the config (Amnezia keys → provider `keys/amnezia.yaml`, single vless:// links added in BroV → provider `vless-keys` from `keys/vless.txt`, WireGuard clients, VLESS subscription). Install/update: `sudo sh scripts/netcore/install.sh` (verifies the mihomo SHA256, migrates keys). Never commit keys, configs or the guide (`~/.brov-secrets`).
|
- `scripts/netcore/gen.py` builds the config (Amnezia keys → provider `keys/amnezia.yaml`, single vless:// links added in BroV → provider `vless-keys` from `keys/vless.txt`, WireGuard clients, VLESS subscription). Install/update: `sudo sh scripts/netcore/install.sh` (verifies the mihomo SHA256, migrates keys). Never commit keys, configs or the guide (`~/.brov-secrets`).
|
||||||
- Reloading the whole core config drops every connection (including this chat); group switches and provider reloads don't.
|
- Reloading the whole core config drops every connection (including this chat); group switches and provider reloads don't.
|
||||||
|
|
||||||
|
|||||||
@@ -5,5 +5,8 @@
|
|||||||
<!-- Hardened runtime: BroV drives Terminal, Music and Mail through Apple Events. -->
|
<!-- Hardened runtime: BroV drives Terminal, Music and Mail through Apple Events. -->
|
||||||
<key>com.apple.security.automation.apple-events</key>
|
<key>com.apple.security.automation.apple-events</key>
|
||||||
<true/>
|
<true/>
|
||||||
|
<!-- Hardened runtime: the mic in the chat (dictation). -->
|
||||||
|
<key>com.apple.security.device.audio-input</key>
|
||||||
|
<true/>
|
||||||
</dict>
|
</dict>
|
||||||
</plist>
|
</plist>
|
||||||
|
|||||||
@@ -33,6 +33,10 @@
|
|||||||
<string>BroV jumps to your terminal, sends mail and controls Music.</string>
|
<string>BroV jumps to your terminal, sends mail and controls Music.</string>
|
||||||
<key>NSHighResolutionCapable</key>
|
<key>NSHighResolutionCapable</key>
|
||||||
<true/>
|
<true/>
|
||||||
|
<key>NSMicrophoneUsageDescription</key>
|
||||||
|
<string>BroV слушает микрофон, когда ты диктуешь сообщение в чат.</string>
|
||||||
|
<key>NSSpeechRecognitionUsageDescription</key>
|
||||||
|
<string>BroV превращает твой голос в текст сообщения в чате.</string>
|
||||||
<key>NSSupportsAutomaticGraphicsSwitching</key>
|
<key>NSSupportsAutomaticGraphicsSwitching</key>
|
||||||
<true/>
|
<true/>
|
||||||
</dict>
|
</dict>
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
// MARK: - ApprovalQueue
|
||||||
|
//
|
||||||
|
// From upstream Coucou e391a14 (#563, after #157 by @Mydao57), MIT. BroV adds `danger`.
|
||||||
|
// Pure FIFO queue of pending PermissionRequests. No AppKit, no SwiftUI, no I/O:
|
||||||
|
// HookServer owns the sockets, timers and UI, and mutates this value on the main actor only.
|
||||||
|
// The head is the request currently shown on the approval card.
|
||||||
|
|
||||||
|
struct QueuedApproval: Equatable, Sendable {
|
||||||
|
let id: UUID
|
||||||
|
/// Client socket, held open until the user decides. Closed by the owner's dispatch source.
|
||||||
|
let fd: Int32
|
||||||
|
let sessionId: String
|
||||||
|
/// "integration_claude", "agent_cursor" or "agent_codex".
|
||||||
|
let pillId: String
|
||||||
|
let projectName: String
|
||||||
|
let cwd: String
|
||||||
|
let tool: String
|
||||||
|
let command: String
|
||||||
|
/// tool_input serialized with sortedKeys, "" if absent. Used to match PostToolUse.
|
||||||
|
let inputKey: String
|
||||||
|
/// Host app / bundle id of the session, so the card's pill keeps showing where it runs.
|
||||||
|
var hostApp: String? = nil
|
||||||
|
var bundleId: String = ""
|
||||||
|
/// BroV: why this request looks destructive (DangerCheck), empty when nothing matched.
|
||||||
|
var danger: [String] = []
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ApprovalQueue: Sendable {
|
||||||
|
/// Upper bound of simultaneously pending requests. Each one holds a socket and a 115 s timer
|
||||||
|
/// and the card only shows one at a time, so beyond this the newest falls back to its terminal.
|
||||||
|
static let maxPending = 5
|
||||||
|
|
||||||
|
enum EnqueueResult: Equatable, Sendable { case accepted, rejectedFull }
|
||||||
|
|
||||||
|
private(set) var entries: [QueuedApproval] = []
|
||||||
|
|
||||||
|
var head: QueuedApproval? { entries.first }
|
||||||
|
var count: Int { entries.count }
|
||||||
|
var isEmpty: Bool { entries.isEmpty }
|
||||||
|
|
||||||
|
func contains(id: UUID) -> Bool { entries.contains { $0.id == id } }
|
||||||
|
|
||||||
|
/// 1-based position of the entry in the queue, nil if absent.
|
||||||
|
func position(of id: UUID) -> Int? {
|
||||||
|
entries.firstIndex { $0.id == id }.map { $0 + 1 }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True when the queued requests do not all come from the same session and agent.
|
||||||
|
var hasMixedSources: Bool {
|
||||||
|
guard let first = entries.first else { return false }
|
||||||
|
return entries.contains { $0.sessionId != first.sessionId || $0.pillId != first.pillId }
|
||||||
|
}
|
||||||
|
|
||||||
|
func hasEntries(forPill pillId: String) -> Bool {
|
||||||
|
entries.contains { $0.pillId == pillId }
|
||||||
|
}
|
||||||
|
|
||||||
|
mutating func enqueue(_ entry: QueuedApproval, maxPending: Int = ApprovalQueue.maxPending) -> EnqueueResult {
|
||||||
|
guard entries.count < maxPending else { return .rejectedFull }
|
||||||
|
entries.append(entry)
|
||||||
|
return .accepted
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes only the entry with this id. Other entries keep their order.
|
||||||
|
@discardableResult
|
||||||
|
mutating func remove(id: UUID) -> QueuedApproval? {
|
||||||
|
guard let idx = entries.firstIndex(where: { $0.id == id }) else { return nil }
|
||||||
|
return entries.remove(at: idx)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Entries made moot by a later hook event of the same agent. Matching is per request
|
||||||
|
/// (session + agent, plus tool and input for PostToolUse), never by pill alone.
|
||||||
|
func resolved(byEvent name: String, sessionId: String, pillId: String,
|
||||||
|
tool: String, inputKey: String) -> [QueuedApproval] {
|
||||||
|
switch name {
|
||||||
|
case "PostToolUse", "PostToolUseFailure":
|
||||||
|
return entries.filter {
|
||||||
|
$0.pillId == pillId && $0.sessionId == sessionId
|
||||||
|
&& $0.tool == tool && $0.inputKey == inputKey
|
||||||
|
}
|
||||||
|
case "Stop", "StopFailure", "UserPromptSubmit", "SessionEnd", "Interrupt":
|
||||||
|
return entries.filter { $0.pillId == pillId && $0.sessionId == sessionId }
|
||||||
|
default:
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -147,7 +147,11 @@ final class ClaudeCodeCLI {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
p.waitUntilExit()
|
p.waitUntilExit()
|
||||||
|
// cancel() (new message, new dialog, closed tab) drops our reference before the
|
||||||
|
// process dies; `claude` catches SIGTERM and exits 143 instead of dying on the signal.
|
||||||
|
let stoppedByUs = process !== p
|
||||||
if process === p { process = nil }
|
if process === p { process = nil }
|
||||||
|
if stoppedByUs && parser.finalText == nil { throw CancellationError() }
|
||||||
|
|
||||||
if let error = parser.errorMessage {
|
if let error = parser.errorMessage {
|
||||||
if error.localizedCaseInsensitiveContains("authenticate") || error.localizedCaseInsensitiveContains("login") {
|
if error.localizedCaseInsensitiveContains("authenticate") || error.localizedCaseInsensitiveContains("login") {
|
||||||
@@ -161,6 +165,9 @@ final class ClaudeCodeCLI {
|
|||||||
if p.terminationReason == .uncaughtSignal { throw CancellationError() }
|
if p.terminationReason == .uncaughtSignal { throw CancellationError() }
|
||||||
if parser.finalText == nil, p.terminationStatus != 0 {
|
if parser.finalText == nil, p.terminationStatus != 0 {
|
||||||
let stderr = String(data: err.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
|
let stderr = String(data: err.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
|
||||||
|
if p.terminationStatus == 143 || p.terminationStatus == 130 {
|
||||||
|
throw ClaudeCodeCLIError.failed("Ответ прерван: процесс claude остановили снаружи. Отправь сообщение ещё раз.")
|
||||||
|
}
|
||||||
let last = stderr.split(separator: "\n").last.map(String.init) ?? "код выхода \(p.terminationStatus)"
|
let last = stderr.split(separator: "\n").last.map(String.init) ?? "код выхода \(p.terminationStatus)"
|
||||||
throw ClaudeCodeCLIError.failed("claude: \(last)")
|
throw ClaudeCodeCLIError.failed("claude: \(last)")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,51 +38,116 @@ final class HookServer: @unchecked Sendable {
|
|||||||
private var serverFD: Int32 = -1
|
private var serverFD: Int32 = -1
|
||||||
private let connectionLock = NSLock()
|
private let connectionLock = NSLock()
|
||||||
private var connectionCount = 0
|
private var connectionCount = 0
|
||||||
private var pendingApprovalFD: Int32 = -1 // held open while user decides
|
/// Permission requests waiting for a click, oldest first; the head is on the card.
|
||||||
private var approvalFDSource: (any DispatchSourceRead)? = nil // monitors pendingApprovalFD
|
/// Each one holds its nb-hook connection open until it is answered or dropped (upstream #563).
|
||||||
|
private var approvals = ApprovalQueue()
|
||||||
|
/// One read source per queued request: it notices the client hanging up, and its
|
||||||
|
/// cancel handler is the only place the request's fd is closed.
|
||||||
|
private var approvalSources: [UUID: any DispatchSourceRead] = [:]
|
||||||
private var pendingQuestionFD: Int32 = -1 // held open while user answers AskUserQuestion
|
private var pendingQuestionFD: Int32 = -1 // held open while user answers AskUserQuestion
|
||||||
private var questionFDSource: (any DispatchSourceRead)? = nil // monitors pendingQuestionFD
|
private var questionFDSource: (any DispatchSourceRead)? = nil // monitors pendingQuestionFD
|
||||||
private var questionPillId: String = "" // pill that owns the pending question
|
private var questionPillId: String = "" // pill that owns the pending question
|
||||||
private var focusBeforeQuestion: String? = nil // saved focus to restore after question
|
private var focusBeforeQuestion: String? = nil // saved focus to restore after question
|
||||||
private var activeSessionId: String? = nil // current Claude Code session
|
private var activeSessionId: String? = nil // current Claude Code session
|
||||||
private var focusBeforeApproval: String? = nil // saved focus to restore after approval
|
private var focusBeforeApproval: String? = nil // saved focus to restore after approval
|
||||||
|
private var sessions = PillSessionRegistry() // live sessions behind each pill (upstream #562)
|
||||||
|
|
||||||
private init() {}
|
private init() {}
|
||||||
|
|
||||||
// MARK: - Approval fd helpers
|
// MARK: - Approval queue helpers (upstream #563)
|
||||||
|
|
||||||
|
/// Note shown when a request was answered outside BroV.
|
||||||
@MainActor
|
@MainActor
|
||||||
private func cancelApprovalFDSource() {
|
private func handledNote(pill: String) -> String {
|
||||||
approvalFDSource?.cancel()
|
switch pill {
|
||||||
approvalFDSource = nil
|
case "agent_cursor": return "Решено в Cursor."
|
||||||
|
case "agent_codex": return "Решено в Codex."
|
||||||
|
default: return "Решено в VS Code."
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Cancels the approval fd source (which closes the fd via its cancel handler), shows a
|
/// Note shown when a request waited too long and went back to the agent.
|
||||||
/// 3-second note, clears approval state, then collapses the island.
|
|
||||||
@MainActor
|
@MainActor
|
||||||
private func dismissApprovalCard(note: String) {
|
private func waitingNote(pill: String) -> String {
|
||||||
// cancelApprovalFDSource() triggers the cancel handler which closes the fd.
|
switch pill {
|
||||||
// Never close the fd here directly — Apple requires it to happen in the cancel handler.
|
case "agent_cursor": return "Всё ещё ждёт в Cursor."
|
||||||
cancelApprovalFDSource()
|
case "agent_codex": return "Всё ещё ждёт в Codex."
|
||||||
pendingApprovalFD = -1
|
default: return "Всё ещё ждёт в VS Code."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Puts the oldest waiting request on the card. When the card already shows it, only
|
||||||
|
/// its "n waiting" count is refreshed (no sound, no focus change).
|
||||||
|
@MainActor
|
||||||
|
private func showApprovalHead() {
|
||||||
let state = AppState.shared
|
let state = AppState.shared
|
||||||
let pillId = state.pendingApproval?.pillId ?? "integration_claude"
|
guard let head = approvals.head else { return }
|
||||||
|
if let shown = state.pendingApproval, shown.id == head.id {
|
||||||
|
if shown.queueCount != approvals.count { state.pendingApproval?.queueCount = approvals.count }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
state.updateTask(id: head.pillId, state: .approval)
|
||||||
|
state.pendingApproval = ApprovalInfo(sessionId: head.sessionId, tool: head.tool,
|
||||||
|
command: head.command, inputKey: head.inputKey,
|
||||||
|
pillId: head.pillId, danger: head.danger, id: head.id,
|
||||||
|
queueCount: approvals.count,
|
||||||
|
projectName: head.projectName)
|
||||||
|
if !head.danger.isEmpty { NotificationCenter.default.post(name: .triggerEmote, object: BotEmote.surprised) }
|
||||||
|
state.isPinned = true
|
||||||
|
// Approval always forces the island open — the user must be able to respond.
|
||||||
|
// Save the focus once, so it comes back when the last request is gone.
|
||||||
|
if focusBeforeApproval == nil { focusBeforeApproval = state.focusId }
|
||||||
|
withAnimation(.spring(response: 0.5, dampingFraction: 0.72)) { state.focusId = head.pillId }
|
||||||
|
expandIfNeeded(to: .approval)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Takes one request out of the queue. With `answer`, the decision is written to its
|
||||||
|
/// nb-hook first; without, the connection just closes and the agent asks again itself.
|
||||||
|
/// The cancel handler of its source closes the fd — never close it directly.
|
||||||
|
/// The next request in line then takes the card; when none is left the card closes,
|
||||||
|
/// with `note` for three seconds if one is given.
|
||||||
|
@MainActor
|
||||||
|
private func removeApproval(id: UUID, answer json: String? = nil, note: String? = nil) {
|
||||||
|
guard let entry = approvals.remove(id: id) else { return }
|
||||||
|
let source = approvalSources.removeValue(forKey: id)
|
||||||
|
if let json {
|
||||||
|
let fd = entry.fd
|
||||||
|
Task.detached { [weak self] in
|
||||||
|
// Write while the fd is still valid, then cancel → the cancel handler closes it.
|
||||||
|
self?.sendLine(fd: fd, text: json)
|
||||||
|
DispatchQueue.main.async { source?.cancel() }
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
source?.cancel()
|
||||||
|
}
|
||||||
|
|
||||||
|
let state = AppState.shared
|
||||||
|
if !approvals.hasEntries(forPill: entry.pillId) {
|
||||||
|
state.updateTask(id: entry.pillId, state: .working)
|
||||||
|
clearPillBadge(id: entry.pillId)
|
||||||
|
}
|
||||||
|
if approvals.head != nil {
|
||||||
|
showApprovalHead()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Last request gone: close the card and give the focus back.
|
||||||
state.pendingApproval = nil
|
state.pendingApproval = nil
|
||||||
state.isPinned = false
|
state.isPinned = false
|
||||||
state.updateTask(id: pillId, state: .working)
|
|
||||||
clearPillBadge(id: pillId)
|
|
||||||
// Restore focus to the pill that was focused before the approval card appeared.
|
|
||||||
if let prev = focusBeforeApproval {
|
if let prev = focusBeforeApproval {
|
||||||
focusBeforeApproval = nil
|
focusBeforeApproval = nil
|
||||||
if state.focusId == pillId, state.tasks.contains(where: { $0.id == prev }) {
|
if state.focusId == entry.pillId, state.tasks.contains(where: { $0.id == prev }) {
|
||||||
withAnimation(.spring(response: 0.5, dampingFraction: 0.72)) { state.focusId = prev }
|
withAnimation(.spring(response: 0.5, dampingFraction: 0.72)) { state.focusId = prev }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if let note {
|
||||||
state.noteMessage = note
|
state.noteMessage = note
|
||||||
state.view = .note
|
state.view = .note
|
||||||
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
|
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
|
||||||
NotificationCenter.default.post(name: .islandCollapse, object: nil)
|
NotificationCenter.default.post(name: .islandCollapse, object: nil)
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
state.view = state.tasks.isEmpty ? .empty : .overview
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Question fd helpers
|
// MARK: - Question fd helpers
|
||||||
@@ -376,42 +441,37 @@ final class HookServer: @unchecked Sendable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let focused = state.focusId == agentId
|
let focused = state.focusId == agentId
|
||||||
|
// Several sessions can share one pill (it is chosen from the client, not from the
|
||||||
|
// session). The registry tells a turn-ending event whether it may touch the pill,
|
||||||
|
// and which session owns the project name shown on it.
|
||||||
|
let display = PillSessionRegistry.Display(
|
||||||
|
session: sessionId,
|
||||||
|
projectName: isExternalAgent ? (validAgent ?? projectName) : projectName,
|
||||||
|
cwd: isExternalAgent ? "" : cwd)
|
||||||
|
|
||||||
#if PHONE_LINK
|
#if PHONE_LINK
|
||||||
// The iPhone's "last turn" (prompt, actions, diffs, answer).
|
// The iPhone's "last turn" (prompt, actions, diffs, answer).
|
||||||
if !isExternalAgent { TurnRecorder.shared.record(event: name, payload: payload, pillId: agentId) }
|
if !isExternalAgent { TurnRecorder.shared.record(event: name, payload: payload, pillId: agentId) }
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// While a permission request is pending, dismiss when the resolving event arrives,
|
// Waiting permission requests: an event that settles one (its tool finished, or its
|
||||||
// then continue normal processing. Only skip normal processing when unresolved.
|
// turn ended) takes it off the card, then is processed normally.
|
||||||
if let pending = state.pendingApproval, agentId == pending.pillId {
|
if !approvals.isEmpty {
|
||||||
let handledNote: String
|
let eventTool = payload["tool_name"] as? String ?? ""
|
||||||
switch pending.pillId {
|
let eventKey = Self.approvalInputKey(payload["tool_input"] as? [String: Any] ?? [:])
|
||||||
case "agent_cursor": handledNote = "Решено в Cursor."
|
for entry in approvals.resolved(byEvent: name, sessionId: sessionId, pillId: agentId,
|
||||||
case "agent_codex": handledNote = "Решено в Codex."
|
tool: eventTool, inputKey: eventKey) {
|
||||||
default: handledNote = "Решено в VS Code."
|
removeApproval(id: entry.id, note: handledNote(pill: entry.pillId))
|
||||||
}
|
}
|
||||||
var resolved = false
|
// A session still waiting on a decision is held back (its parallel tool calls
|
||||||
switch name {
|
// would pull the pill out of its approval state). Other sessions go through.
|
||||||
case "PostToolUse", "PostToolUseFailure":
|
if approvals.entries.contains(where: { $0.pillId == agentId && $0.sessionId == sessionId }) {
|
||||||
// Only dismiss when this exact tool call finished — same session, tool and input.
|
return
|
||||||
// Other parallel tools finishing must not close the card.
|
|
||||||
if sessionId == pending.sessionId,
|
|
||||||
(payload["tool_name"] as? String ?? "") == pending.tool,
|
|
||||||
Self.approvalInputKey(payload["tool_input"] as? [String: Any] ?? [:]) == pending.inputKey {
|
|
||||||
dismissApprovalCard(note: handledNote)
|
|
||||||
resolved = true
|
|
||||||
}
|
}
|
||||||
case "Stop", "StopFailure", "UserPromptSubmit", "SessionEnd", "Interrupt":
|
|
||||||
// Turn ended or session interrupted — the permission is moot.
|
|
||||||
if sessionId == pending.sessionId {
|
|
||||||
dismissApprovalCard(note: handledNote)
|
|
||||||
resolved = true
|
|
||||||
}
|
}
|
||||||
default: break
|
// A sibling session's event must not take the pill out of its approval state.
|
||||||
}
|
defer {
|
||||||
if !resolved { return }
|
if approvals.hasEntries(forPill: agentId) { state.updateTask(id: agentId, state: .approval) }
|
||||||
// Approval dismissed — fall through so the resolving event updates state normally.
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// BroV: crash watch + login status.
|
// BroV: crash watch + login status.
|
||||||
@@ -432,7 +492,8 @@ final class HookServer: @unchecked Sendable {
|
|||||||
|
|
||||||
case "SessionStart":
|
case "SessionStart":
|
||||||
activeSessionId = sessionId
|
activeSessionId = sessionId
|
||||||
if isExternalAgent { upsertExternalAgent(id: agentId, name: validAgent!) } else { upsertWorkspaceTask(id: agentId, projectName: projectName, cwd: cwd) }
|
upsertTask(pill: agentId, display: display, working: false,
|
||||||
|
externalAgent: isExternalAgent ? validAgent : nil)
|
||||||
if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) { state.tasks[idx].finalLine = nil }
|
if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) { state.tasks[idx].finalLine = nil }
|
||||||
nbLog("SessionStart \(isExternalAgent ? agentId : projectName) (\(sessionId.prefix(8)))")
|
nbLog("SessionStart \(isExternalAgent ? agentId : projectName) (\(sessionId.prefix(8)))")
|
||||||
if state.isPresent { expandIfNeeded(to: .overview) }
|
if state.isPresent { expandIfNeeded(to: .overview) }
|
||||||
@@ -440,7 +501,8 @@ final class HookServer: @unchecked Sendable {
|
|||||||
|
|
||||||
case "UserPromptSubmit":
|
case "UserPromptSubmit":
|
||||||
activeSessionId = sessionId
|
activeSessionId = sessionId
|
||||||
if isExternalAgent { upsertExternalAgent(id: agentId, name: validAgent!) } else { upsertWorkspaceTask(id: agentId, projectName: projectName, cwd: cwd) }
|
upsertTask(pill: agentId, display: display, working: true,
|
||||||
|
externalAgent: isExternalAgent ? validAgent : nil)
|
||||||
if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) { state.tasks[idx].finalLine = nil }
|
if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) { state.tasks[idx].finalLine = nil }
|
||||||
state.updateTask(id: agentId, state: .thinking)
|
state.updateTask(id: agentId, state: .thinking)
|
||||||
if let prompt = payload["prompt"] as? String, !prompt.isEmpty {
|
if let prompt = payload["prompt"] as? String, !prompt.isEmpty {
|
||||||
@@ -455,7 +517,8 @@ final class HookServer: @unchecked Sendable {
|
|||||||
// AskUserQuestion is handled via the dedicated --ask hook.
|
// AskUserQuestion is handled via the dedicated --ask hook.
|
||||||
// Skip state/step update here to avoid flickering over the question card.
|
// Skip state/step update here to avoid flickering over the question card.
|
||||||
guard tool != "AskUserQuestion" else { break }
|
guard tool != "AskUserQuestion" else { break }
|
||||||
if isExternalAgent { upsertExternalAgent(id: agentId, name: validAgent!) } else { upsertWorkspaceTask(id: agentId, projectName: projectName, cwd: cwd) }
|
upsertTask(pill: agentId, display: display, working: true,
|
||||||
|
externalAgent: isExternalAgent ? validAgent : nil)
|
||||||
state.updateTask(id: agentId, state: .working)
|
state.updateTask(id: agentId, state: .working)
|
||||||
let input = payload["tool_input"] as? [String: Any] ?? [:]
|
let input = payload["tool_input"] as? [String: Any] ?? [:]
|
||||||
let step = frenchStep(tool: tool, input: input)
|
let step = frenchStep(tool: tool, input: input)
|
||||||
@@ -463,6 +526,7 @@ final class HookServer: @unchecked Sendable {
|
|||||||
nbLog("PreToolUse \(tool)")
|
nbLog("PreToolUse \(tool)")
|
||||||
|
|
||||||
case "PostToolUse":
|
case "PostToolUse":
|
||||||
|
sessions.note(pill: agentId, display: display, working: true)
|
||||||
state.updateTask(id: agentId, state: .working)
|
state.updateTask(id: agentId, state: .working)
|
||||||
// Live diff for Edit / MultiEdit / Write
|
// Live diff for Edit / MultiEdit / Write
|
||||||
let diffTool = payload["tool_name"] as? String ?? ""
|
let diffTool = payload["tool_name"] as? String ?? ""
|
||||||
@@ -474,10 +538,12 @@ final class HookServer: @unchecked Sendable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
case "PostToolUseFailure":
|
case "PostToolUseFailure":
|
||||||
|
sessions.note(pill: agentId, display: display, working: true)
|
||||||
state.updateTask(id: agentId, state: .working)
|
state.updateTask(id: agentId, state: .working)
|
||||||
appendStep(id: agentId, step: "⚠ ошибка")
|
appendStep(id: agentId, step: "⚠ ошибка")
|
||||||
|
|
||||||
case "Notification":
|
case "Notification":
|
||||||
|
sessions.note(pill: agentId, display: display, working: false)
|
||||||
let message = payload["message"] as? String ?? ""
|
let message = payload["message"] as? String ?? ""
|
||||||
let lower = message.lowercased()
|
let lower = message.lowercased()
|
||||||
if lower.contains("rate limit") || lower.contains("limite d") {
|
if lower.contains("rate limit") || lower.contains("limite d") {
|
||||||
@@ -489,15 +555,21 @@ final class HookServer: @unchecked Sendable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
case "Stop":
|
case "Stop":
|
||||||
state.updateTask(id: agentId, state: .finished)
|
let scope = sessions.endTurn(pill: agentId, session: sessionId)
|
||||||
let rawFinal = (payload["last_assistant_message"] as? String)
|
let rawFinal = (payload["last_assistant_message"] as? String)
|
||||||
?? (payload["message"] as? String) ?? ""
|
?? (payload["message"] as? String) ?? ""
|
||||||
let finalText = DiffEngine.toOneLine(rawFinal)
|
let finalText = DiffEngine.toOneLine(rawFinal)
|
||||||
if !finalText.isEmpty {
|
// The step log is shared, so the conclusion is worth showing either way.
|
||||||
appendStep(id: agentId, step: finalText)
|
if !finalText.isEmpty { appendStep(id: agentId, step: finalText) }
|
||||||
if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) {
|
// Another session is still mid-turn behind this pill: the finished state, the
|
||||||
state.tasks[idx].finalLine = finalText
|
// sound and the idle reset below would land on its work. Its own Stop comes later.
|
||||||
|
guard scope == .pill else {
|
||||||
|
nbLog("Stop \(sessionId.prefix(8)) — \(sessions.workingCount(pill: agentId)) session(s) still working on \(agentId)")
|
||||||
|
break
|
||||||
}
|
}
|
||||||
|
state.updateTask(id: agentId, state: .finished)
|
||||||
|
if !finalText.isEmpty, let idx = state.tasks.firstIndex(where: { $0.id == agentId }) {
|
||||||
|
state.tasks[idx].finalLine = finalText
|
||||||
}
|
}
|
||||||
SoundEngine.shared.play("finish")
|
SoundEngine.shared.play("finish")
|
||||||
if focused {
|
if focused {
|
||||||
@@ -506,6 +578,8 @@ final class HookServer: @unchecked Sendable {
|
|||||||
setPillBadge(id: agentId, badge: .finished)
|
setPillBadge(id: agentId, badge: .finished)
|
||||||
}
|
}
|
||||||
DispatchQueue.main.asyncAfter(deadline: .now() + 5.2) {
|
DispatchQueue.main.asyncAfter(deadline: .now() + 5.2) {
|
||||||
|
// A session (this one or a sibling) may have started a new turn meanwhile.
|
||||||
|
guard self.sessions.workingCount(pill: agentId) == 0 else { return }
|
||||||
if isExternalAgent {
|
if isExternalAgent {
|
||||||
AppState.shared.removeTask(id: agentId)
|
AppState.shared.removeTask(id: agentId)
|
||||||
} else {
|
} else {
|
||||||
@@ -515,6 +589,7 @@ final class HookServer: @unchecked Sendable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
case "StopFailure":
|
case "StopFailure":
|
||||||
|
guard sessions.endTurn(pill: agentId, session: sessionId) == .pill else { break }
|
||||||
state.updateTask(id: agentId, state: .error)
|
state.updateTask(id: agentId, state: .error)
|
||||||
SoundEngine.shared.play("error")
|
SoundEngine.shared.play("error")
|
||||||
if focused {
|
if focused {
|
||||||
@@ -525,11 +600,18 @@ final class HookServer: @unchecked Sendable {
|
|||||||
|
|
||||||
case "Interrupt":
|
case "Interrupt":
|
||||||
// Codex: user stopped the turn
|
// Codex: user stopped the turn
|
||||||
|
guard sessions.endTurn(pill: agentId, session: sessionId) == .pill else { break }
|
||||||
activeSessionId = nil
|
activeSessionId = nil
|
||||||
state.updateTask(id: agentId, state: .idle)
|
state.updateTask(id: agentId, state: .idle)
|
||||||
clearPillBadge(id: agentId)
|
clearPillBadge(id: agentId)
|
||||||
|
|
||||||
case "SessionEnd":
|
case "SessionEnd":
|
||||||
|
// Only the last session behind the pill may take the card and its diffs down.
|
||||||
|
guard sessions.endSession(pill: agentId, session: sessionId) == .pill else {
|
||||||
|
nbLog("SessionEnd \(sessionId.prefix(8)) — \(sessions.liveCount(pill: agentId)) session(s) left on \(agentId)")
|
||||||
|
applyDisplayOwner(pill: agentId)
|
||||||
|
break
|
||||||
|
}
|
||||||
activeSessionId = nil
|
activeSessionId = nil
|
||||||
if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) { state.tasks[idx].finalLine = nil }
|
if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) { state.tasks[idx].finalLine = nil }
|
||||||
state.clearSessionDiffs(for: agentId)
|
state.clearSessionDiffs(for: agentId)
|
||||||
@@ -566,6 +648,32 @@ final class HookServer: @unchecked Sendable {
|
|||||||
/// Creates a dynamic pill for a third-party agent on first event, then no-ops.
|
/// Creates a dynamic pill for a third-party agent on first event, then no-ops.
|
||||||
/// ID format: "agent_<name>" — never collides with "integration_*" pills.
|
/// ID format: "agent_<name>" — never collides with "integration_*" pills.
|
||||||
/// Inserted right after integration_claude so it appears in the visible prefix(4).
|
/// Inserted right after integration_claude so it appears in the visible prefix(4).
|
||||||
|
/// Records the session an event came from, then refreshes its card. `externalAgent`
|
||||||
|
/// is the validated `coucou_agent` name for a third-party agent pill, nil for a
|
||||||
|
/// workspace pill.
|
||||||
|
@MainActor
|
||||||
|
private func upsertTask(pill: String, display: PillSessionRegistry.Display,
|
||||||
|
working: Bool, externalAgent: String?) {
|
||||||
|
sessions.note(pill: pill, display: display, working: working)
|
||||||
|
if let externalAgent {
|
||||||
|
upsertExternalAgent(id: pill, name: externalAgent)
|
||||||
|
} else {
|
||||||
|
upsertWorkspaceTask(id: pill, projectName: display.projectName, cwd: display.cwd,
|
||||||
|
session: display.session)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes the pill's name and cwd from the session that owns it: used when the owner
|
||||||
|
/// ends and a sibling session inherits the card.
|
||||||
|
@MainActor
|
||||||
|
private func applyDisplayOwner(pill: String) {
|
||||||
|
guard let owner = sessions.displayOwner(of: pill),
|
||||||
|
let idx = AppState.shared.tasks.firstIndex(where: { $0.id == pill }),
|
||||||
|
!owner.projectName.isEmpty else { return }
|
||||||
|
AppState.shared.tasks[idx].name = owner.projectName
|
||||||
|
if !owner.cwd.isEmpty { AppState.shared.tasks[idx].sessionCwd = owner.cwd }
|
||||||
|
}
|
||||||
|
|
||||||
@MainActor
|
@MainActor
|
||||||
private func upsertExternalAgent(id: String, name: String) {
|
private func upsertExternalAgent(id: String, name: String) {
|
||||||
let state = AppState.shared
|
let state = AppState.shared
|
||||||
@@ -689,80 +797,68 @@ final class HookServer: @unchecked Sendable {
|
|||||||
let command = DangerCheck.describe(tool: tool, input: toolInput)
|
let command = DangerCheck.describe(tool: tool, input: toolInput)
|
||||||
let danger = DangerCheck.reasons(tool: tool, input: toolInput)
|
let danger = DangerCheck.reasons(tool: tool, input: toolInput)
|
||||||
|
|
||||||
if pendingApprovalFD >= 0 {
|
// Several requests can wait at once (several sessions or agents): they queue, the
|
||||||
// Displace the previous request: write "ask" then cancel its source.
|
// card shows the oldest. Past the cap, the newest goes back to its own terminal.
|
||||||
// The cancel handler closes the old fd — never close it directly.
|
let entry = QueuedApproval(id: UUID(), fd: fd, sessionId: sessionId, pillId: pillId,
|
||||||
let old = pendingApprovalFD
|
projectName: projectName, cwd: cwd, tool: tool,
|
||||||
let oldSource = approvalFDSource
|
command: command, inputKey: inputKey, danger: danger)
|
||||||
approvalFDSource = nil
|
guard approvals.enqueue(entry) == .accepted else {
|
||||||
|
nbLog("PermissionRequest \(tool): \(ApprovalQueue.maxPending) already waiting, asked in the terminal")
|
||||||
Task.detached { [weak self] in
|
Task.detached { [weak self] in
|
||||||
// "ask" → nb-hook outputs nothing → Claude Code re-asks
|
self?.sendLine(fd: fd, text: #"{"permissionDecision":"ask"}"#)
|
||||||
self?.sendLine(fd: old, text: #"{"permissionDecision":"ask"}"#)
|
close(fd)
|
||||||
DispatchQueue.main.async { oldSource?.cancel() }
|
|
||||||
}
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
pendingApprovalFD = fd
|
|
||||||
activeSessionId = sessionId
|
activeSessionId = sessionId
|
||||||
|
|
||||||
upsertWorkspaceTask(id: pillId, projectName: projectName, cwd: cwd)
|
upsertTask(pill: pillId,
|
||||||
|
display: PillSessionRegistry.Display(session: sessionId, projectName: projectName, cwd: cwd),
|
||||||
|
working: true, externalAgent: nil)
|
||||||
state.updateTask(id: pillId, state: .approval)
|
state.updateTask(id: pillId, state: .approval)
|
||||||
state.pendingApproval = ApprovalInfo(sessionId: sessionId, tool: tool,
|
|
||||||
command: command, inputKey: inputKey, pillId: pillId,
|
|
||||||
danger: danger)
|
|
||||||
if !danger.isEmpty { NotificationCenter.default.post(name: .triggerEmote, object: BotEmote.surprised) }
|
|
||||||
state.isPinned = true
|
|
||||||
SoundEngine.shared.play("approval")
|
SoundEngine.shared.play("approval")
|
||||||
|
|
||||||
// Approval always forces the island open — user must be able to respond.
|
// Monitor fd: if the agent closes the connection (answered in its own UI), drop the
|
||||||
// Save current focus so we can restore it when the card is dismissed.
|
// request. The cancel handler closes the fd — never close it anywhere else.
|
||||||
if focusBeforeApproval == nil { focusBeforeApproval = state.focusId }
|
let entryId = entry.id
|
||||||
withAnimation(.spring(response: 0.5, dampingFraction: 0.72)) { state.focusId = pillId }
|
|
||||||
expandIfNeeded(to: .approval)
|
|
||||||
|
|
||||||
// Monitor fd: if the editor closes the connection (handled externally), dismiss the card.
|
|
||||||
// The cancel handler closes the fd — never close it anywhere else.
|
|
||||||
let capturedPillId = pillId
|
let capturedPillId = pillId
|
||||||
let source = DispatchSource.makeReadSource(fileDescriptor: fd, queue: .main)
|
let source = DispatchSource.makeReadSource(fileDescriptor: fd, queue: .main)
|
||||||
source.setEventHandler { [weak self] in
|
source.setEventHandler { [weak self] in
|
||||||
guard let self, self.pendingApprovalFD == fd else { return }
|
guard let self, self.approvals.contains(id: entryId) else { return }
|
||||||
let note: String
|
self.removeApproval(id: entryId, note: self.handledNote(pill: capturedPillId))
|
||||||
switch capturedPillId {
|
|
||||||
case "agent_cursor": note = "Решено в Cursor."
|
|
||||||
case "agent_codex": note = "Решено в Codex."
|
|
||||||
default: note = "Решено в VS Code."
|
|
||||||
}
|
|
||||||
self.dismissApprovalCard(note: note)
|
|
||||||
}
|
}
|
||||||
source.setCancelHandler { close(fd) }
|
source.setCancelHandler { close(fd) }
|
||||||
source.resume()
|
source.resume()
|
||||||
approvalFDSource = source
|
approvalSources[entryId] = source
|
||||||
|
|
||||||
// 115s safety timeout — show a note and cancel without sending a decision.
|
// 115 s safety timeout per request — drop without a decision. nb-hook reads EOF from
|
||||||
// nb-hook reads EOF from the cancel handler's close and exits; Claude Code / Codex re-asks.
|
// the cancel handler's close and exits; the agent asks again itself.
|
||||||
let captured = fd
|
|
||||||
DispatchQueue.main.asyncAfter(deadline: .now() + 115) { [weak self] in
|
DispatchQueue.main.asyncAfter(deadline: .now() + 115) { [weak self] in
|
||||||
guard let self, self.pendingApprovalFD == captured else { return }
|
guard let self, self.approvals.contains(id: entryId) else { return }
|
||||||
let note: String
|
self.removeApproval(id: entryId, note: self.waitingNote(pill: capturedPillId))
|
||||||
switch capturedPillId {
|
|
||||||
case "agent_cursor": note = "Всё ещё ждёт в Cursor."
|
|
||||||
case "agent_codex": note = "Всё ещё ждёт в Codex."
|
|
||||||
default: note = "Всё ещё ждёт в VS Code."
|
|
||||||
}
|
|
||||||
self.dismissApprovalCard(note: note)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Called by ApprovalView buttons. Writes the decision to the waiting nb-hook and cleans up.
|
showApprovalHead()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Called by ApprovalView buttons and the iPhone. Writes the decision to the waiting
|
||||||
|
/// nb-hook of request `id` — the one that was on screen. A click that lands after the
|
||||||
|
/// card moved on to another request is ignored, so it can never answer the wrong one.
|
||||||
@MainActor
|
@MainActor
|
||||||
func sendApprovalDecision(_ decision: String) {
|
func sendApprovalDecision(_ decision: String, for id: UUID? = nil) {
|
||||||
Haptic.tap()
|
Haptic.tap()
|
||||||
let fd = pendingApprovalFD
|
guard let head = approvals.head else {
|
||||||
pendingApprovalFD = -1
|
// A card with nothing behind it any more: just close it.
|
||||||
// Capture source before nulling — we send the decision first, then cancel the source.
|
let s = AppState.shared
|
||||||
// The cancel handler closes the fd; never close it directly.
|
s.pendingApproval = nil
|
||||||
let source = approvalFDSource
|
s.isPinned = false
|
||||||
approvalFDSource = nil
|
s.view = s.tasks.isEmpty ? .empty : .overview
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if let id, id != head.id {
|
||||||
|
nbLog("Approval decision for a request no longer on the card, ignored")
|
||||||
|
return
|
||||||
|
}
|
||||||
let json: String
|
let json: String
|
||||||
switch decision {
|
switch decision {
|
||||||
case "allow": json = #"{"permissionDecision":"allow"}"#
|
case "allow": json = #"{"permissionDecision":"allow"}"#
|
||||||
@@ -770,31 +866,7 @@ final class HookServer: @unchecked Sendable {
|
|||||||
case "ask": json = #"{"permissionDecision":"ask"}"#
|
case "ask": json = #"{"permissionDecision":"ask"}"#
|
||||||
default: json = #"{"permissionDecision":"deny"}"#
|
default: json = #"{"permissionDecision":"deny"}"#
|
||||||
}
|
}
|
||||||
|
removeApproval(id: head.id, answer: json)
|
||||||
if fd >= 0 {
|
|
||||||
Task.detached { [weak self] in
|
|
||||||
// Write decision while fd is still valid, then cancel source → cancel handler closes fd
|
|
||||||
self?.sendLine(fd: fd, text: json)
|
|
||||||
DispatchQueue.main.async { source?.cancel() }
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
source?.cancel()
|
|
||||||
}
|
|
||||||
|
|
||||||
let state = AppState.shared
|
|
||||||
let pillId = state.pendingApproval?.pillId ?? "integration_claude"
|
|
||||||
state.pendingApproval = nil
|
|
||||||
state.isPinned = false
|
|
||||||
state.updateTask(id: pillId, state: .working)
|
|
||||||
clearPillBadge(id: pillId)
|
|
||||||
// Restore focus to the pill that was focused before the approval card appeared.
|
|
||||||
if let prev = focusBeforeApproval {
|
|
||||||
focusBeforeApproval = nil
|
|
||||||
if state.focusId == pillId, state.tasks.contains(where: { $0.id == prev }) {
|
|
||||||
withAnimation(.spring(response: 0.5, dampingFraction: 0.72)) { state.focusId = prev }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
state.view = state.tasks.isEmpty ? .empty : .overview
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Question request
|
// MARK: - Question request
|
||||||
@@ -851,7 +923,9 @@ final class HookServer: @unchecked Sendable {
|
|||||||
activeSessionId = sessionId
|
activeSessionId = sessionId
|
||||||
questionPillId = pillId
|
questionPillId = pillId
|
||||||
|
|
||||||
upsertWorkspaceTask(id: pillId, projectName: projectName, cwd: cwd)
|
upsertTask(pill: pillId,
|
||||||
|
display: PillSessionRegistry.Display(session: sessionId, projectName: projectName, cwd: cwd),
|
||||||
|
working: true, externalAgent: nil)
|
||||||
state.updateTask(id: pillId, state: .question)
|
state.updateTask(id: pillId, state: .question)
|
||||||
state.pendingQuestion = parsed
|
state.pendingQuestion = parsed
|
||||||
state.isPinned = true
|
state.isPinned = true
|
||||||
@@ -890,9 +964,12 @@ final class HookServer: @unchecked Sendable {
|
|||||||
/// If the task already exists (persistent), just updates name/cwd.
|
/// If the task already exists (persistent), just updates name/cwd.
|
||||||
/// If missing (transient), creates it and inserts after the main pill.
|
/// If missing (transient), creates it and inserts after the main pill.
|
||||||
@MainActor
|
@MainActor
|
||||||
private func upsertWorkspaceTask(id: String, projectName: String, cwd: String = "") {
|
private func upsertWorkspaceTask(id: String, projectName: String, cwd: String = "", session: String) {
|
||||||
let state = AppState.shared
|
let state = AppState.shared
|
||||||
if let idx = state.tasks.firstIndex(where: { $0.id == id }) {
|
if let idx = state.tasks.firstIndex(where: { $0.id == id }) {
|
||||||
|
// Name and cwd belong to the session that owns the pill (the oldest one still
|
||||||
|
// running): a second session under the same client can't rename the card.
|
||||||
|
guard sessions.ownsDisplay(pill: id, session: session) else { return }
|
||||||
state.tasks[idx].name = projectName
|
state.tasks[idx].name = projectName
|
||||||
if !cwd.isEmpty { state.tasks[idx].sessionCwd = cwd }
|
if !cwd.isEmpty { state.tasks[idx].sessionCwd = cwd }
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -449,6 +449,9 @@ struct ChatResizeHandle: View {
|
|||||||
DragGesture(minimumDistance: 2, coordinateSpace: .global)
|
DragGesture(minimumDistance: 2, coordinateSpace: .global)
|
||||||
.onChanged { g in
|
.onChanged { g in
|
||||||
if startHeight == nil {
|
if startHeight == nil {
|
||||||
|
// A translation card on the home view goes along into the chat
|
||||||
|
// instead of disappearing.
|
||||||
|
if state.translation != nil { TranslatorRun.moveToChat(state: state) }
|
||||||
if state.view != .prompt {
|
if state.view != .prompt {
|
||||||
state.chatDetent = 0
|
state.chatDetent = 0
|
||||||
state.view = .prompt
|
state.view = .prompt
|
||||||
|
|||||||
@@ -298,12 +298,32 @@ struct ApprovalView: View {
|
|||||||
|
|
||||||
var approval: ApprovalInfo? { state.pendingApproval }
|
var approval: ApprovalInfo? { state.pendingApproval }
|
||||||
|
|
||||||
|
/// The pill, named after the session that asks (several sessions can share a pill).
|
||||||
|
private var asker: AgentTask? {
|
||||||
|
guard var task = state.focusTask else { return nil }
|
||||||
|
if let project = approval?.projectName, !project.isEmpty { task.name = project }
|
||||||
|
return task
|
||||||
|
}
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
let danger = approval?.danger ?? []
|
let danger = approval?.danger ?? []
|
||||||
|
// Captured when the card is drawn: a click answers the request that was on screen,
|
||||||
|
// and is ignored if the card has moved on to the next one since.
|
||||||
|
let shownId = approval?.id
|
||||||
ZStack {
|
ZStack {
|
||||||
CardBackground(wash: danger.isEmpty ? .amber : .red)
|
CardBackground(wash: danger.isEmpty ? .amber : .red)
|
||||||
VStack(alignment: .leading, spacing: 5) {
|
VStack(alignment: .leading, spacing: 5) {
|
||||||
AgentWho(task: state.focusTask, label: "просит разрешение")
|
HStack(spacing: 7) {
|
||||||
|
AgentWho(task: asker, label: "просит разрешение")
|
||||||
|
// Other requests waiting behind this one: "1/3".
|
||||||
|
if let count = approval?.queueCount, count > 1 {
|
||||||
|
Text(verbatim: "1/\(count)")
|
||||||
|
.font(.system(size: 12, weight: .semibold))
|
||||||
|
.foregroundColor(Color(hex: "#8E939C"))
|
||||||
|
.monospacedDigit()
|
||||||
|
.help("Ещё \(count - 1) ждут в очереди")
|
||||||
|
}
|
||||||
|
}
|
||||||
CodeBlock(text: approval?.command ?? approval?.tool ?? "…")
|
CodeBlock(text: approval?.command ?? approval?.tool ?? "…")
|
||||||
if !danger.isEmpty {
|
if !danger.isEmpty {
|
||||||
HStack(alignment: .top, spacing: 5) {
|
HStack(alignment: .top, spacing: 5) {
|
||||||
@@ -320,16 +340,16 @@ struct ApprovalView: View {
|
|||||||
}
|
}
|
||||||
HStack(spacing: 8) {
|
HStack(spacing: 8) {
|
||||||
SecondaryButton("Запретить") {
|
SecondaryButton("Запретить") {
|
||||||
HookServer.shared.sendApprovalDecision("deny")
|
HookServer.shared.sendApprovalDecision("deny", for: shownId)
|
||||||
}
|
}
|
||||||
PrimaryButton("Разрешить") {
|
PrimaryButton("Разрешить") {
|
||||||
HookServer.shared.sendApprovalDecision("allow")
|
HookServer.shared.sendApprovalDecision("allow", for: shownId)
|
||||||
}
|
}
|
||||||
// Codex rejects updatedPermissions, so "Always" is not offered.
|
// Codex rejects updatedPermissions, so "Always" is not offered.
|
||||||
// Never for a dangerous command: one click must not save a destructive rule.
|
// Never for a dangerous command: one click must not save a destructive rule.
|
||||||
if approval?.pillId != "agent_codex" && danger.isEmpty {
|
if approval?.pillId != "agent_codex" && danger.isEmpty {
|
||||||
SecondaryButton("Всегда") {
|
SecondaryButton("Всегда") {
|
||||||
HookServer.shared.sendApprovalDecision("always")
|
HookServer.shared.sendApprovalDecision("always", for: shownId)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1169,10 +1189,43 @@ struct MailView: View {
|
|||||||
|
|
||||||
// MARK: - Prompt (chat)
|
// MARK: - Prompt (chat)
|
||||||
|
|
||||||
|
/// The mic's right-click menu: Automatic (the user's languages) or one fixed language.
|
||||||
|
private struct DictationLanguageMenu: View {
|
||||||
|
@Bindable var dictation: MacDictation
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
let automatic = MacDictation.automaticLocales().map(\.identifier)
|
||||||
|
Picker("Язык диктовки", selection: $dictation.language) {
|
||||||
|
Text("Автоматически (" + automatic.map(MacDictation.name(of:)).joined(separator: ", ") + ")")
|
||||||
|
.tag(MacDictation.automatic)
|
||||||
|
ForEach(quickChoices(automatic), id: \.self) { id in
|
||||||
|
Text(MacDictation.name(of: id)).tag(id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.pickerStyle(.inline)
|
||||||
|
Menu("Другие языки") {
|
||||||
|
Picker("Язык диктовки", selection: $dictation.language) {
|
||||||
|
ForEach(MacDictation.allLanguages, id: \.self) { id in
|
||||||
|
Text(MacDictation.name(of: id)).tag(id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.pickerStyle(.inline)
|
||||||
|
.labelsHidden()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Automatic's languages, plus the fixed one when it is another.
|
||||||
|
private func quickChoices(_ automatic: [String]) -> [String] {
|
||||||
|
let chosen = dictation.language
|
||||||
|
return chosen == MacDictation.automatic || automatic.contains(chosen) ? automatic : automatic + [chosen]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
struct PromptView: View {
|
struct PromptView: View {
|
||||||
@ObservedObject var state: AppState
|
@ObservedObject var state: AppState
|
||||||
@State private var text: String = ""
|
@State private var text: String = ""
|
||||||
@FocusState private var focused: Bool
|
@FocusState private var focused: Bool
|
||||||
|
@State private var dictation = MacDictation()
|
||||||
@State private var showModelPicker = false
|
@State private var showModelPicker = false
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
@@ -1267,6 +1320,26 @@ struct PromptView: View {
|
|||||||
.focused($focused)
|
.focused($focused)
|
||||||
.onSubmit { sendMessage() }
|
.onSubmit { sendMessage() }
|
||||||
|
|
||||||
|
// Dictate instead of typing (on-device speech recognition when available).
|
||||||
|
Button {
|
||||||
|
Task {
|
||||||
|
if dictation.isRecording { text = await dictation.finish() }
|
||||||
|
else { await dictation.start(from: text) }
|
||||||
|
}
|
||||||
|
} label: {
|
||||||
|
Image(systemName: dictation.isRecording ? "mic.fill" : "mic")
|
||||||
|
.font(.system(size: 11, weight: .semibold))
|
||||||
|
.foregroundColor(dictation.isRecording ? Color(hex: "#F4505E") : Color(hex: "#8E939C"))
|
||||||
|
.frame(width: 18, height: 18)
|
||||||
|
.contentShape(Rectangle())
|
||||||
|
}
|
||||||
|
.buttonStyle(.plain)
|
||||||
|
.help(dictation.isRecording ? "Остановить диктовку" : "Диктовать (правый клик — выбрать язык)")
|
||||||
|
.contextMenu { DictationLanguageMenu(dictation: dictation) }
|
||||||
|
.onChange(of: dictation.transcript) { _, _ in
|
||||||
|
if dictation.isRecording { text = dictation.text }
|
||||||
|
}
|
||||||
|
|
||||||
Button(action: sendMessage) {
|
Button(action: sendMessage) {
|
||||||
Image(systemName: "arrow.up")
|
Image(systemName: "arrow.up")
|
||||||
.font(.system(size: 11, weight: .semibold))
|
.font(.system(size: 11, weight: .semibold))
|
||||||
@@ -1325,6 +1398,14 @@ struct PromptView: View {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private func sendMessage() {
|
private func sendMessage() {
|
||||||
|
// Still dictating: take the final words (and the right language) before sending.
|
||||||
|
if dictation.isRecording {
|
||||||
|
Task {
|
||||||
|
text = await dictation.finish()
|
||||||
|
sendMessage()
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
let query = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
let query = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
guard !query.isEmpty else { return }
|
guard !query.isEmpty else { return }
|
||||||
text = ""
|
text = ""
|
||||||
|
|||||||
@@ -303,6 +303,7 @@ final class IslandWindowController: NSWindowController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Mouse in screen coords (Y flipped, origin top-left) for Bot look-at
|
// Mouse in screen coords (Y flipped, origin top-left) for Bot look-at
|
||||||
|
Self.islandScreenFrame = panel.screen?.frame
|
||||||
let screenH = panel.screen?.frame.height ?? NSScreen.main!.frame.height
|
let screenH = panel.screen?.frame.height ?? NSScreen.main!.frame.height
|
||||||
let newPos = CGPoint(x: mouse.x - (panel.screen?.frame.minX ?? 0), y: screenH - mouse.y)
|
let newPos = CGPoint(x: mouse.x - (panel.screen?.frame.minX ?? 0), y: screenH - mouse.y)
|
||||||
let cur = AppState.shared.mousePosition
|
let cur = AppState.shared.mousePosition
|
||||||
@@ -363,6 +364,21 @@ final class IslandWindowController: NSWindowController {
|
|||||||
|
|
||||||
private var lastMouse: CGPoint = .zero
|
private var lastMouse: CGPoint = .zero
|
||||||
|
|
||||||
|
/// Mochi's look target from the current mouse position, in the same coordinates the poll
|
||||||
|
/// uses (the island's screen, y from its top).
|
||||||
|
/// Frame of the screen the island is on, kept by the poll.
|
||||||
|
static var islandScreenFrame: CGRect?
|
||||||
|
|
||||||
|
static func trackMouseLook() {
|
||||||
|
let app = AppState.shared
|
||||||
|
guard app.mode != .hidden || app.mochiOnDesktop else { return }
|
||||||
|
guard let frame = islandScreenFrame ?? NSScreen.main?.frame else { return }
|
||||||
|
let mouse = NSEvent.mouseLocation
|
||||||
|
let pos = CGPoint(x: mouse.x - frame.minX, y: frame.height - mouse.y)
|
||||||
|
let cur = app.mousePosition
|
||||||
|
if abs(pos.x - cur.x) > 1 || abs(pos.y - cur.y) > 1 { app.mousePosition = pos }
|
||||||
|
}
|
||||||
|
|
||||||
// MARK: - Bot-head hover (love emote — mirrors prototype botHover())
|
// MARK: - Bot-head hover (love emote — mirrors prototype botHover())
|
||||||
|
|
||||||
private func botHoverIn(mousePos: CGPoint) {
|
private func botHoverIn(mousePos: CGPoint) {
|
||||||
@@ -719,6 +735,17 @@ final class IslandWindowController: NSWindowController {
|
|||||||
self?.handleDizzy()
|
self?.handleDizzy()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Eye tracking at the mouse's own rate (from upstream b5b04c2): the look target
|
||||||
|
// followed the island poll (10–30 Hz), so the head turned in steps. Nothing runs while
|
||||||
|
// the mouse is still; a hidden island skips the work.
|
||||||
|
NSEvent.addGlobalMonitorForEvents(matching: [.mouseMoved, .leftMouseDragged]) { _ in
|
||||||
|
MainActor.assumeIsolated { IslandWindowController.trackMouseLook() }
|
||||||
|
}
|
||||||
|
NSEvent.addLocalMonitorForEvents(matching: [.mouseMoved, .leftMouseDragged]) { event in
|
||||||
|
MainActor.assumeIsolated { IslandWindowController.trackMouseLook() }
|
||||||
|
return event
|
||||||
|
}
|
||||||
|
|
||||||
// Window attach drag.
|
// Window attach drag.
|
||||||
// Uses MainActor.assumeIsolated (synchronous) to avoid race with pollFrame().
|
// Uses MainActor.assumeIsolated (synchronous) to avoid race with pollFrame().
|
||||||
// Global mouseUp is the reliable fallback when cursor is outside our panel frame.
|
// Global mouseUp is the reliable fallback when cursor is outside our panel frame.
|
||||||
|
|||||||
@@ -0,0 +1,301 @@
|
|||||||
|
#if !APPSTORE
|
||||||
|
import AVFoundation
|
||||||
|
import Carbon
|
||||||
|
import Speech
|
||||||
|
|
||||||
|
/// Speech to text for the notch chat, on-device when the Mac supports it.
|
||||||
|
/// From upstream Coucou (#334, #353, review fixes 3b0e987), MIT.
|
||||||
|
///
|
||||||
|
/// Apple's recognizer only understands one language per request, so "Automatic" (the default)
|
||||||
|
/// listens with up to three recognizers at once — the user's languages (macOS languages,
|
||||||
|
/// keyboard layouts, then English) — shows the one that won last time while you speak, and when
|
||||||
|
/// you stop keeps the transcript the recognizers were the most confident about. A fixed language
|
||||||
|
/// can be chosen from the mic's right-click menu.
|
||||||
|
///
|
||||||
|
/// Not main-actor bound, because the audio tap and the recognizers call back on their own
|
||||||
|
/// threads; the published values are set on the main actor.
|
||||||
|
@Observable
|
||||||
|
final class MacDictation: @unchecked Sendable {
|
||||||
|
static let automatic = "auto"
|
||||||
|
private static let languageKey = "dictationLanguage"
|
||||||
|
/// The language that won the last automatic dictation: shown first next time.
|
||||||
|
private static let lastHeardKey = "dictationLastLocale"
|
||||||
|
private static let maxCandidates = 3
|
||||||
|
|
||||||
|
var isRecording = false
|
||||||
|
var transcript = ""
|
||||||
|
/// What was typed before dictating, kept in front of the words.
|
||||||
|
var prefix = ""
|
||||||
|
/// `automatic` or a locale identifier (the mic's right-click menu).
|
||||||
|
var language: String = UserDefaults.standard.string(forKey: MacDictation.languageKey) ?? MacDictation.automatic {
|
||||||
|
didSet { UserDefaults.standard.set(language, forKey: Self.languageKey) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@ObservationIgnored private let engine = AVAudioEngine()
|
||||||
|
@ObservationIgnored private var candidates: [Candidate] = []
|
||||||
|
/// The candidate whose words are shown while speaking.
|
||||||
|
@ObservationIgnored private var lead = 0
|
||||||
|
@ObservationIgnored private var finishing: CheckedContinuation<Void, Never>?
|
||||||
|
@ObservationIgnored private var isFinishing = false
|
||||||
|
@ObservationIgnored private var tapInstalled = false
|
||||||
|
|
||||||
|
/// The text field's content: what was typed, then the words heard so far.
|
||||||
|
var text: String { prefix + transcript }
|
||||||
|
|
||||||
|
/// One recognizer listening in one language.
|
||||||
|
private final class Candidate {
|
||||||
|
let locale: Locale
|
||||||
|
let recognizer: SFSpeechRecognizer
|
||||||
|
let request = SFSpeechAudioBufferRecognitionRequest()
|
||||||
|
var task: SFSpeechRecognitionTask?
|
||||||
|
var words = ""
|
||||||
|
/// Mean confidence of the words (Apple fills it in on the final result).
|
||||||
|
var confidence: Float = 0
|
||||||
|
var finished = false
|
||||||
|
|
||||||
|
init(locale: Locale, recognizer: SFSpeechRecognizer) {
|
||||||
|
self.locale = locale
|
||||||
|
self.recognizer = recognizer
|
||||||
|
request.shouldReportPartialResults = true
|
||||||
|
if recognizer.supportsOnDeviceRecognition { request.requiresOnDeviceRecognition = true }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Start / finish
|
||||||
|
|
||||||
|
@MainActor func start(from text: String) async {
|
||||||
|
guard !isRecording, await Self.authorized() else { return }
|
||||||
|
let built = Self.makeCandidates(language == Self.automatic ? Self.automaticLocales() : [Locale(identifier: language)])
|
||||||
|
guard !built.isEmpty, Self.startEngine(engine, feeding: built.map(\.request)) else { return }
|
||||||
|
tapInstalled = true
|
||||||
|
prefix = text.isEmpty || text.hasSuffix(" ") ? text : text + " "
|
||||||
|
transcript = ""
|
||||||
|
candidates = built
|
||||||
|
lead = 0
|
||||||
|
isRecording = true
|
||||||
|
NotificationCenter.default.post(name: .dictationDidStart, object: nil)
|
||||||
|
for (index, candidate) in built.enumerated() {
|
||||||
|
candidate.task = Self.recognize(candidate) { [weak self] words, confidence, final, failed in
|
||||||
|
Task { @MainActor in
|
||||||
|
self?.update(index, words: words, confidence: confidence, final: final, failed: failed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stops listening and returns the field's text with the most likely transcript.
|
||||||
|
@MainActor func finish() async -> String {
|
||||||
|
guard isRecording else { return text }
|
||||||
|
isFinishing = true
|
||||||
|
stopEngine()
|
||||||
|
candidates.forEach { $0.request.endAudio() }
|
||||||
|
// With several languages, wait a moment for the final results: they carry the confidence.
|
||||||
|
if candidates.count > 1, !candidates.allSatisfy(\.finished) {
|
||||||
|
await withCheckedContinuation { continuation in
|
||||||
|
finishing = continuation
|
||||||
|
Task { @MainActor [weak self] in
|
||||||
|
try? await Task.sleep(for: .milliseconds(1200))
|
||||||
|
self?.resumeFinishing()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let best = bestCandidate() {
|
||||||
|
transcript = best.words
|
||||||
|
if candidates.count > 1 {
|
||||||
|
UserDefaults.standard.set(best.locale.identifier, forKey: Self.lastHeardKey)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tearDown()
|
||||||
|
return text
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cancels without waiting (the view went away).
|
||||||
|
@MainActor func stop() {
|
||||||
|
guard isRecording || !candidates.isEmpty else { return }
|
||||||
|
tearDown()
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor private func stopEngine() {
|
||||||
|
engine.stop()
|
||||||
|
if tapInstalled { engine.inputNode.removeTap(onBus: 0) }
|
||||||
|
tapInstalled = false
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor private func tearDown() {
|
||||||
|
stopEngine()
|
||||||
|
candidates.forEach { $0.request.endAudio(); $0.task?.cancel() }
|
||||||
|
candidates = []
|
||||||
|
lead = 0
|
||||||
|
NotificationCenter.default.post(name: .dictationDidEnd, object: nil)
|
||||||
|
isRecording = false
|
||||||
|
isFinishing = false
|
||||||
|
resumeFinishing()
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor private func resumeFinishing() {
|
||||||
|
finishing?.resume()
|
||||||
|
finishing = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Results
|
||||||
|
|
||||||
|
@MainActor private func update(_ index: Int, words: String?, confidence: Float, final: Bool, failed: Bool) {
|
||||||
|
guard index < candidates.count else { return }
|
||||||
|
let candidate = candidates[index]
|
||||||
|
if let words { candidate.words = words }
|
||||||
|
if confidence > 0 { candidate.confidence = confidence }
|
||||||
|
if final || failed { candidate.finished = true }
|
||||||
|
|
||||||
|
if isFinishing {
|
||||||
|
if candidates.allSatisfy(\.finished) { resumeFinishing() }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// A recognizer that gives up while you speak (no model, busy…) hands over to the next one.
|
||||||
|
if index == lead, candidate.finished, candidate.words.isEmpty,
|
||||||
|
let next = candidates.firstIndex(where: { !$0.finished }) {
|
||||||
|
lead = next
|
||||||
|
transcript = candidates[next].words
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// When Apple reports confidences while speaking, follow the clearly better language.
|
||||||
|
let current = candidates[lead]
|
||||||
|
if index != lead, candidate.confidence > current.confidence + 0.15,
|
||||||
|
candidate.words.split(separator: " ").count >= 3 {
|
||||||
|
lead = index
|
||||||
|
}
|
||||||
|
if index == lead { transcript = candidate.words }
|
||||||
|
if candidates.allSatisfy(\.finished) { tearDown() }
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor private func bestCandidate() -> Candidate? {
|
||||||
|
guard lead < candidates.count else { return nil }
|
||||||
|
let leader = candidates[lead]
|
||||||
|
let best = candidates
|
||||||
|
.filter { !$0.words.isEmpty }
|
||||||
|
.max { $0.confidence < $1.confidence }
|
||||||
|
guard let best, best.confidence > leader.confidence else { return leader }
|
||||||
|
return best
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Audio and recognizers (off the main actor: they call back on their own threads)
|
||||||
|
|
||||||
|
nonisolated private static func startEngine(_ engine: AVAudioEngine, feeding requests: [SFSpeechAudioBufferRecognitionRequest]) -> Bool {
|
||||||
|
let input = engine.inputNode
|
||||||
|
input.installTap(onBus: 0, bufferSize: 1024, format: input.outputFormat(forBus: 0)) { buffer, _ in
|
||||||
|
for request in requests { request.append(buffer) }
|
||||||
|
}
|
||||||
|
engine.prepare()
|
||||||
|
do { try engine.start() } catch {
|
||||||
|
input.removeTap(onBus: 0)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
nonisolated private static func recognize(
|
||||||
|
_ candidate: Candidate,
|
||||||
|
report: @escaping @Sendable (String?, Float, Bool, Bool) -> Void
|
||||||
|
) -> SFSpeechRecognitionTask {
|
||||||
|
candidate.recognizer.recognitionTask(with: candidate.request) { result, error in
|
||||||
|
let words = result?.bestTranscription.formattedString
|
||||||
|
let segments = result?.bestTranscription.segments ?? []
|
||||||
|
let confidence = segments.isEmpty ? 0 : segments.map(\.confidence).reduce(0, +) / Float(segments.count)
|
||||||
|
report(words, confidence, result?.isFinal ?? false, error != nil)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Recognizers that can run now. Extra languages in Automatic only listen on-device,
|
||||||
|
/// so the audio never goes to Apple in a language you didn't speak.
|
||||||
|
private static func makeCandidates(_ locales: [Locale]) -> [Candidate] {
|
||||||
|
var out: [Candidate] = []
|
||||||
|
for locale in locales {
|
||||||
|
guard let recognizer = SFSpeechRecognizer(locale: locale), recognizer.isAvailable else { continue }
|
||||||
|
if !out.isEmpty && !recognizer.supportsOnDeviceRecognition { continue }
|
||||||
|
out.append(Candidate(locale: locale, recognizer: recognizer))
|
||||||
|
}
|
||||||
|
if out.isEmpty, let fallback = SFSpeechRecognizer(), fallback.isAvailable {
|
||||||
|
out.append(Candidate(locale: fallback.locale, recognizer: fallback))
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Languages
|
||||||
|
|
||||||
|
/// The languages Automatic listens for: last winner, macOS languages, keyboard layouts,
|
||||||
|
/// Coucou's own language, then English — one per language, up to three.
|
||||||
|
static func automaticLocales() -> [Locale] {
|
||||||
|
var ids: [String] = []
|
||||||
|
if let last = UserDefaults.standard.string(forKey: lastHeardKey) { ids.append(last) }
|
||||||
|
// The Mac's languages (not Coucou's override in Settings → General → Language).
|
||||||
|
ids += (CFPreferencesCopyValue("AppleLanguages" as CFString, kCFPreferencesAnyApplication,
|
||||||
|
kCFPreferencesCurrentUser, kCFPreferencesAnyHost) as? [String]) ?? []
|
||||||
|
ids += keyboardLanguages()
|
||||||
|
ids += Locale.preferredLanguages
|
||||||
|
ids.append("en-US")
|
||||||
|
|
||||||
|
let supported = Array(SFSpeechRecognizer.supportedLocales())
|
||||||
|
var seen = Set<String>()
|
||||||
|
var out: [Locale] = []
|
||||||
|
for id in ids {
|
||||||
|
guard let locale = match(id, in: supported) else { continue }
|
||||||
|
let language = locale.language.languageCode?.identifier ?? locale.identifier
|
||||||
|
guard seen.insert(language).inserted else { continue }
|
||||||
|
out.append(locale)
|
||||||
|
if out.count == maxCandidates { break }
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every language the recognizer knows, by name.
|
||||||
|
static var allLanguages: [String] {
|
||||||
|
SFSpeechRecognizer.supportedLocales()
|
||||||
|
.map(\.identifier)
|
||||||
|
.sorted { name(of: $0).localizedCaseInsensitiveCompare(name(of: $1)) == .orderedAscending }
|
||||||
|
}
|
||||||
|
|
||||||
|
static func name(of identifier: String) -> String {
|
||||||
|
let name = Locale.current.localizedString(forIdentifier: identifier) ?? identifier
|
||||||
|
return name.prefix(1).uppercased() + name.dropFirst()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "fr" or "fr_FR" → the recognizer locale for it, preferring the Mac's region.
|
||||||
|
private static func match(_ id: String, in supported: [Locale]) -> Locale? {
|
||||||
|
let wanted = id.replacingOccurrences(of: "_", with: "-").lowercased()
|
||||||
|
if let exact = supported.first(where: { $0.identifier.replacingOccurrences(of: "_", with: "-").lowercased() == wanted }) {
|
||||||
|
return exact
|
||||||
|
}
|
||||||
|
let language = Locale(identifier: id).language.languageCode?.identifier
|
||||||
|
let sameLanguage = supported.filter { $0.language.languageCode?.identifier == language }
|
||||||
|
let region = Locale(identifier: id).region ?? Locale.current.region
|
||||||
|
return sameLanguage.first { $0.region == region }
|
||||||
|
?? sameLanguage.min { $0.identifier < $1.identifier }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The main language of each enabled keyboard layout ("fr" for AZERTY, "en" for ABC…).
|
||||||
|
private static func keyboardLanguages() -> [String] {
|
||||||
|
let filter = ["TISPropertyInputSourceCategory": "TISCategoryKeyboardInputSource"] as CFDictionary
|
||||||
|
guard let list = TISCreateInputSourceList(filter, false)?.takeRetainedValue() as? [TISInputSource] else { return [] }
|
||||||
|
return list.compactMap { source in
|
||||||
|
guard let raw = TISGetInputSourceProperty(source, "TISPropertyInputSourceLanguages" as CFString) else { return nil }
|
||||||
|
let languages = Unmanaged<CFArray>.fromOpaque(raw).takeUnretainedValue() as? [String]
|
||||||
|
return languages?.first
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func authorized() async -> Bool {
|
||||||
|
let speech = await withCheckedContinuation { continuation in
|
||||||
|
SFSpeechRecognizer.requestAuthorization { continuation.resume(returning: $0 == .authorized) }
|
||||||
|
}
|
||||||
|
guard speech else { return false }
|
||||||
|
return await AVAudioApplication.requestRecordPermission()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Dictation notification names
|
||||||
|
// Defined here so both MacDictation and VoiceEngine can reference them without
|
||||||
|
// cross-file ordering issues in SourceKit.
|
||||||
|
extension Notification.Name {
|
||||||
|
static let dictationDidStart = Notification.Name("notchBuddy.dictationDidStart")
|
||||||
|
static let dictationDidEnd = Notification.Name("notchBuddy.dictationDidEnd")
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -57,6 +57,16 @@ final class NetCore: ObservableObject {
|
|||||||
|
|
||||||
/// Delays measured by the group test (covers the subscription nodes too).
|
/// Delays measured by the group test (covers the subscription nodes too).
|
||||||
private var measured: [String: Int] = [:]
|
private var measured: [String: Int] = [:]
|
||||||
|
/// Failed checks in a row per proxy. An AmneziaWG 3 tunnel idle for a while can miss one
|
||||||
|
/// check while its handshake warms up, so «нет ответа» is shown only after two misses.
|
||||||
|
private var misses: [String: Int] = [:]
|
||||||
|
|
||||||
|
private func record(_ name: String, _ delay: Int) {
|
||||||
|
if delay > 0 { misses[name] = 0; measured[name] = delay; return }
|
||||||
|
let n = (misses[name] ?? 0) + 1
|
||||||
|
misses[name] = n
|
||||||
|
if n >= 2 { measured[name] = 0 } // first miss: keep the previous result
|
||||||
|
}
|
||||||
|
|
||||||
static let clientInfo: [String: (title: String, subnet: String)] = [
|
static let clientInfo: [String: (title: String, subnet: String)] = [
|
||||||
"saga": ("Сага", "192.168.8.0/24"),
|
"saga": ("Сага", "192.168.8.0/24"),
|
||||||
@@ -143,6 +153,8 @@ final class NetCore: ObservableObject {
|
|||||||
awgNames.sort()
|
awgNames.sort()
|
||||||
func lastDelay(_ name: String) -> Int? {
|
func lastDelay(_ name: String) -> Int? {
|
||||||
if let d = measured[name] { return d }
|
if let d = measured[name] { return d }
|
||||||
|
// One miss so far: the core's history already says 0, don't show it yet.
|
||||||
|
if misses[name] == 1 { return nil }
|
||||||
if let h = proxies[name]?["history"] as? [[String: Any]], let d = h.last?["delay"] as? Int { return d }
|
if let h = proxies[name]?["history"] as? [[String: Any]], let d = h.last?["delay"] as? Int { return d }
|
||||||
return providerDelay[name]
|
return providerDelay[name]
|
||||||
}
|
}
|
||||||
@@ -186,17 +198,17 @@ final class NetCore: ObservableObject {
|
|||||||
func measure() async {
|
func measure() async {
|
||||||
busy = true
|
busy = true
|
||||||
if let m = (await call(["cmd": "delay", "group": "ai-out"], timeout: 15))?["delays"] as? [String: Int] {
|
if let m = (await call(["cmd": "delay", "group": "ai-out"], timeout: 15))?["delays"] as? [String: Int] {
|
||||||
measured = m
|
for (k, v) in m { record(k, v) }
|
||||||
// Members that didn't answer are missing from the map: mark them dead.
|
// Members that didn't answer are missing from the map: count a miss.
|
||||||
for e in exits where e.id != "auto" && m[e.id] == nil { measured[e.id] = 0 }
|
for e in exits where e.id != "auto" && m[e.id] == nil { record(e.id, 0) }
|
||||||
}
|
}
|
||||||
if let m = (await call(["cmd": "delay", "group": "amnezia"], timeout: 15))?["delays"] as? [String: Int] {
|
if let m = (await call(["cmd": "delay", "group": "amnezia"], timeout: 15))?["delays"] as? [String: Int] {
|
||||||
for (k, v) in m { measured[k] = v }
|
for (k, v) in m { record(k, v) }
|
||||||
for c in amneziaConns where c.id != "amnezia-auto" && m[c.id] == nil { measured[c.id] = 0 }
|
for c in amneziaConns where c.id != "amnezia-auto" && m[c.id] == nil { record(c.id, 0) }
|
||||||
}
|
}
|
||||||
for c in clients where c.on {
|
for c in clients where c.on {
|
||||||
if let m = (await call(["cmd": "delay", "proxy": c.id], timeout: 15))?["delays"] as? [String: Int] {
|
if let m = (await call(["cmd": "delay", "proxy": c.id], timeout: 15))?["delays"] as? [String: Int] {
|
||||||
for (k, v) in m { measured[k] = v }
|
for (k, v) in m { record(k, v) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
await refresh()
|
await refresh()
|
||||||
@@ -216,7 +228,7 @@ final class NetCore: ObservableObject {
|
|||||||
_ = await call(["cmd": "select", "group": "\(id)-sw", "name": on ? id : off])
|
_ = await call(["cmd": "select", "group": "\(id)-sw", "name": on ? id : off])
|
||||||
SoundEngine.shared.play(on ? "pop" : "close")
|
SoundEngine.shared.play(on ? "pop" : "close")
|
||||||
if on, let m = (await call(["cmd": "delay", "proxy": id], timeout: 15))?["delays"] as? [String: Int] {
|
if on, let m = (await call(["cmd": "delay", "proxy": id], timeout: 15))?["delays"] as? [String: Int] {
|
||||||
for (k, v) in m { measured[k] = v }
|
for (k, v) in m { record(k, v) }
|
||||||
}
|
}
|
||||||
await refresh()
|
await refresh()
|
||||||
}
|
}
|
||||||
@@ -267,7 +279,7 @@ final class NetCore: ObservableObject {
|
|||||||
busy = false
|
busy = false
|
||||||
if r?["ok"] as? Bool == true {
|
if r?["ok"] as? Bool == true {
|
||||||
lastError = nil
|
lastError = nil
|
||||||
measured.removeValue(forKey: name)
|
measured.removeValue(forKey: name); misses.removeValue(forKey: name)
|
||||||
SoundEngine.shared.play(cmd == "hide" ? "close" : "pop")
|
SoundEngine.shared.play(cmd == "hide" ? "close" : "pop")
|
||||||
} else {
|
} else {
|
||||||
lastError = "Не получилось: \(r?["error"] as? String ?? "помощник не ответил")."
|
lastError = "Не получилось: \(r?["error"] as? String ?? "помощник не ответил")."
|
||||||
@@ -300,9 +312,10 @@ final class NetCore: ObservableObject {
|
|||||||
// MARK: Network changes
|
// MARK: Network changes
|
||||||
//
|
//
|
||||||
// Moving between home / Saga / Planet9 Wi-Fi, waking from sleep or AmneziaVPN going on
|
// 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.
|
// 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
|
// (seen: Amnezia sockets still on 192.168.68.x after moving to Saga). A few seconds after
|
||||||
// once instead of at the next scheduled check.
|
// the change the tunnels are re-created (netctl rebind), then everything is re-tested so
|
||||||
|
// "auto" and "exit" re-pick at once.
|
||||||
|
|
||||||
private var pathMonitor: NWPathMonitor?
|
private var pathMonitor: NWPathMonitor?
|
||||||
private var recheckTask: Task<Void, Never>?
|
private var recheckTask: Task<Void, Never>?
|
||||||
@@ -317,11 +330,45 @@ final class NetCore: ObservableObject {
|
|||||||
pathMonitor = m
|
pathMonitor = m
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// IPv4 addresses of the physical adapters (en*), sorted: what "another network" means.
|
||||||
|
private var lastAddresses: String?
|
||||||
|
|
||||||
|
private static func physicalAddresses() -> String {
|
||||||
|
var out: [String] = []
|
||||||
|
var ifap: UnsafeMutablePointer<ifaddrs>?
|
||||||
|
guard getifaddrs(&ifap) == 0, let first = ifap else { return "" }
|
||||||
|
defer { freeifaddrs(ifap) }
|
||||||
|
var p: UnsafeMutablePointer<ifaddrs>? = first
|
||||||
|
while let cur = p {
|
||||||
|
let name = String(cString: cur.pointee.ifa_name)
|
||||||
|
if name.hasPrefix("en"), let sa = cur.pointee.ifa_addr, sa.pointee.sa_family == UInt8(AF_INET) {
|
||||||
|
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 {
|
||||||
|
out.append(name + "=" + String(cString: host))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p = cur.pointee.ifa_next
|
||||||
|
}
|
||||||
|
return out.sorted().joined(separator: ",")
|
||||||
|
}
|
||||||
|
|
||||||
private func networkChanged() {
|
private func networkChanged() {
|
||||||
recheckTask?.cancel()
|
recheckTask?.cancel()
|
||||||
recheckTask = Task {
|
recheckTask = Task {
|
||||||
try? await Task.sleep(for: .seconds(4))
|
try? await Task.sleep(for: .seconds(4))
|
||||||
guard !Task.isCancelled else { return }
|
guard !Task.isCancelled else { return }
|
||||||
|
let now = Self.physicalAddresses()
|
||||||
|
// A moment without an address (DHCP renew, Wi-Fi blip) is not another network:
|
||||||
|
// only a change between two real addresses counts, else the core would restart
|
||||||
|
// when the same address comes back.
|
||||||
|
let moved = !now.isEmpty && lastAddresses != nil && now != lastAddresses
|
||||||
|
if !now.isEmpty { lastAddresses = now }
|
||||||
|
if moved {
|
||||||
|
// Another network: the WireGuard tunnels (Amnezia, clients) are still bound to
|
||||||
|
// the old address — a clean core restart re-binds them without leaking.
|
||||||
|
_ = await call(["cmd": "rebind"], timeout: 30)
|
||||||
|
try? await Task.sleep(for: .seconds(6))
|
||||||
|
}
|
||||||
_ = await call(["cmd": "delay", "group": "auto"], timeout: 15)
|
_ = await call(["cmd": "delay", "group": "auto"], timeout: 15)
|
||||||
_ = await call(["cmd": "delay", "group": "amnezia"], timeout: 15)
|
_ = await call(["cmd": "delay", "group": "amnezia"], timeout: 15)
|
||||||
_ = await call(["cmd": "delay", "group": "exit"], timeout: 15)
|
_ = await call(["cmd": "delay", "group": "exit"], timeout: 15)
|
||||||
|
|||||||
@@ -147,10 +147,10 @@ final class ApprovalRelay {
|
|||||||
switch decision {
|
switch decision {
|
||||||
case "allow":
|
case "allow":
|
||||||
log("allowed from the iPhone: \(pending.tool)")
|
log("allowed from the iPhone: \(pending.tool)")
|
||||||
HookServer.shared.sendApprovalDecision("allow")
|
HookServer.shared.sendApprovalDecision("allow", for: pending.id)
|
||||||
case "deny":
|
case "deny":
|
||||||
log("denied from the iPhone: \(pending.tool)")
|
log("denied from the iPhone: \(pending.tool)")
|
||||||
HookServer.shared.sendApprovalDecision("deny")
|
HookServer.shared.sendApprovalDecision("deny", for: pending.id)
|
||||||
default:
|
default:
|
||||||
log("unknown decision '\(decision)', ignored")
|
log("unknown decision '\(decision)', ignored")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,162 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
// MARK: - PillSessionRegistry
|
||||||
|
//
|
||||||
|
// From upstream Coucou 5652ea8 (#562, after #245 by @TheodoreRiant), MIT. Unchanged.
|
||||||
|
|
||||||
|
/// Keeps track of the agent sessions living behind each pill.
|
||||||
|
///
|
||||||
|
/// A pill is picked from the client that sent the event — bundle ID,
|
||||||
|
/// `term_program`, `coucou_agent` — never from the session. Two `claude`
|
||||||
|
/// started in two projects under VS Code therefore land on the same
|
||||||
|
/// `integration_claude`, while `AppState.tasks` holds one entry per pill.
|
||||||
|
/// Without a session set, the first session to end wipes the card and the
|
||||||
|
/// diffs the second one is still filling.
|
||||||
|
///
|
||||||
|
/// A value type on purpose: the hook server owns one copy and every change
|
||||||
|
/// goes through a `mutating` call, so no other object can alias the state.
|
||||||
|
struct PillSessionRegistry {
|
||||||
|
|
||||||
|
/// A session unheard of for this long counts as gone. A `SessionEnd` that
|
||||||
|
/// never arrives — a killed terminal, a crash — would otherwise pin a card
|
||||||
|
/// to a session nobody is running any more.
|
||||||
|
static let maxSilence: TimeInterval = 12 * 3600
|
||||||
|
|
||||||
|
/// A session mid-turn emits a hook event every few seconds, so this long
|
||||||
|
/// without one means its `Stop` went missing. Stops counting it as working,
|
||||||
|
/// which is what keeps a sibling session from staying stuck out of its
|
||||||
|
/// finished state. Longer than any tool call Claude Code will wait on.
|
||||||
|
static let maxTurnSilence: TimeInterval = 30 * 60
|
||||||
|
|
||||||
|
/// How far a terminal event is allowed to reach.
|
||||||
|
enum TerminalScope: Equatable {
|
||||||
|
/// No other session is mid-turn behind this pill, so the pill may
|
||||||
|
/// follow: finished state, sound, badge, card removal.
|
||||||
|
case pill
|
||||||
|
/// Another session is still working — leave the pill as it is.
|
||||||
|
case sessionOnly
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a pill shows while a session owns it.
|
||||||
|
struct Display: Equatable {
|
||||||
|
var session: String
|
||||||
|
var projectName: String
|
||||||
|
var cwd: String
|
||||||
|
/// Terminal the session runs in (bundle id), for "Open terminal".
|
||||||
|
var hostApp: String? = nil
|
||||||
|
/// Bundle id of the client (VS Code, Cursor…) that sent the event.
|
||||||
|
var bundleId: String = ""
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct Session {
|
||||||
|
var projectName: String
|
||||||
|
var cwd: String
|
||||||
|
var hostApp: String?
|
||||||
|
var bundleId: String
|
||||||
|
var isWorking: Bool
|
||||||
|
var lastSeen: Date
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct Pill {
|
||||||
|
/// Live sessions, oldest first. The first one owns name and cwd.
|
||||||
|
var order: [String] = []
|
||||||
|
var sessions: [String: Session] = [:]
|
||||||
|
}
|
||||||
|
|
||||||
|
private var pills: [String: Pill] = [:]
|
||||||
|
|
||||||
|
// MARK: - Recording activity
|
||||||
|
|
||||||
|
/// Records the session that sent an event as live behind `pill`.
|
||||||
|
/// `working` says whether the event means the session is mid-turn: a
|
||||||
|
/// `PreToolUse` does, a `SessionStart` or a stray notification does not.
|
||||||
|
mutating func note(pill: String, display: Display, working: Bool, now: Date = Date()) {
|
||||||
|
var p = pills[pill] ?? Pill()
|
||||||
|
sweep(&p, now: now)
|
||||||
|
if p.sessions[display.session] == nil {
|
||||||
|
p.order.append(display.session)
|
||||||
|
}
|
||||||
|
var session = p.sessions[display.session]
|
||||||
|
?? Session(projectName: display.projectName, cwd: display.cwd,
|
||||||
|
hostApp: display.hostApp, bundleId: display.bundleId,
|
||||||
|
isWorking: false, lastSeen: now)
|
||||||
|
session.projectName = display.projectName
|
||||||
|
if !display.cwd.isEmpty { session.cwd = display.cwd }
|
||||||
|
if display.hostApp != nil { session.hostApp = display.hostApp }
|
||||||
|
if !display.bundleId.isEmpty { session.bundleId = display.bundleId }
|
||||||
|
if working { session.isWorking = true }
|
||||||
|
session.lastSeen = now
|
||||||
|
p.sessions[display.session] = session
|
||||||
|
pills[pill] = p
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Terminal events
|
||||||
|
|
||||||
|
/// Ends a session's turn without ending the session: a `Stop` closes a
|
||||||
|
/// turn, and the user can send another prompt right after.
|
||||||
|
///
|
||||||
|
/// A session we have never seen stays untracked — Coucou can start in the
|
||||||
|
/// middle of one, and a session we only ever heard stop owns nothing.
|
||||||
|
mutating func endTurn(pill: String, session: String, now: Date = Date()) -> TerminalScope {
|
||||||
|
var p = pills[pill] ?? Pill()
|
||||||
|
sweep(&p, now: now)
|
||||||
|
p.sessions[session]?.isWorking = false
|
||||||
|
p.sessions[session]?.lastSeen = now
|
||||||
|
if p.order.isEmpty { pills.removeValue(forKey: pill) } else { pills[pill] = p }
|
||||||
|
return p.sessions.values.contains(where: \.isWorking) ? .sessionOnly : .pill
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drops a session for good. `.pill` only when it was the last one live,
|
||||||
|
/// so the card and the diffs survive a sibling session ending.
|
||||||
|
mutating func endSession(pill: String, session: String, now: Date = Date()) -> TerminalScope {
|
||||||
|
var p = pills[pill] ?? Pill()
|
||||||
|
sweep(&p, now: now)
|
||||||
|
p.order.removeAll { $0 == session }
|
||||||
|
p.sessions.removeValue(forKey: session)
|
||||||
|
guard !p.order.isEmpty else {
|
||||||
|
pills.removeValue(forKey: pill)
|
||||||
|
return .pill
|
||||||
|
}
|
||||||
|
pills[pill] = p
|
||||||
|
return .sessionOnly
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Reading
|
||||||
|
|
||||||
|
/// The session whose project name and cwd the pill shows. Ownership goes
|
||||||
|
/// to the oldest live session and only moves on when that one ends, so a
|
||||||
|
/// single name field stops flipping between two parallel sessions.
|
||||||
|
func displayOwner(of pill: String) -> Display? {
|
||||||
|
guard let p = pills[pill], let id = p.order.first,
|
||||||
|
let session = p.sessions[id] else { return nil }
|
||||||
|
return Display(session: id, projectName: session.projectName, cwd: session.cwd,
|
||||||
|
hostApp: session.hostApp, bundleId: session.bundleId)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether this session may write the pill's name and cwd. True when the
|
||||||
|
/// pill has no live session yet, so a first event is never dropped.
|
||||||
|
func ownsDisplay(pill: String, session: String) -> Bool {
|
||||||
|
guard let owner = displayOwner(of: pill) else { return true }
|
||||||
|
return owner.session == session
|
||||||
|
}
|
||||||
|
|
||||||
|
func liveCount(pill: String) -> Int { pills[pill]?.order.count ?? 0 }
|
||||||
|
|
||||||
|
func workingCount(pill: String) -> Int {
|
||||||
|
pills[pill]?.sessions.values.filter(\.isWorking).count ?? 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Silence sweep
|
||||||
|
|
||||||
|
private func sweep(_ pill: inout Pill, now: Date) {
|
||||||
|
for (id, session) in pill.sessions.map({ ($0.key, $0.value) }) {
|
||||||
|
let silence = now.timeIntervalSince(session.lastSeen)
|
||||||
|
if silence > Self.maxSilence {
|
||||||
|
pill.sessions.removeValue(forKey: id)
|
||||||
|
pill.order.removeAll { $0 == id }
|
||||||
|
} else if session.isWorking, silence > Self.maxTurnSilence {
|
||||||
|
pill.sessions[id]?.isWorking = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,6 +17,8 @@ struct TranslationResult: Equatable {
|
|||||||
var engine: String = ""
|
var engine: String = ""
|
||||||
var error: String? = nil
|
var error: String? = nil
|
||||||
var loading = true
|
var loading = true
|
||||||
|
/// The user stretched the notch while it was still translating: finish into the chat.
|
||||||
|
var toChat = false
|
||||||
}
|
}
|
||||||
|
|
||||||
@MainActor
|
@MainActor
|
||||||
@@ -42,6 +44,7 @@ enum TranslatorRun {
|
|||||||
state.translation?.engine = engine
|
state.translation?.engine = engine
|
||||||
state.translation?.loading = false
|
state.translation?.loading = false
|
||||||
SoundEngine.shared.play("pop")
|
SoundEngine.shared.play("pop")
|
||||||
|
if state.translation?.toChat == true { moveToChat(state: state) }
|
||||||
} catch {
|
} catch {
|
||||||
guard state.translation?.source == source else { return }
|
guard state.translation?.source == source else { return }
|
||||||
state.translation?.error = error.localizedDescription
|
state.translation?.error = error.localizedDescription
|
||||||
@@ -50,6 +53,20 @@ enum TranslatorRun {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Moves a finished translation into a chat: the full text, room to grow (the handle
|
||||||
|
/// stretches the chat), and follow-up questions go to the same dialog.
|
||||||
|
static func moveToChat(state: AppState) {
|
||||||
|
guard let result = state.translation else { return }
|
||||||
|
if result.loading, result.error == nil { state.translation?.toChat = true; return }
|
||||||
|
state.translation = nil
|
||||||
|
guard result.error == nil else { return }
|
||||||
|
if state.tabs.count < AppState.maxTabs { state.openTab(.chat) } else { state.view = .prompt }
|
||||||
|
if let tab = state.activeTabId {
|
||||||
|
ChatTabs.shared.seed(tab, "Исходный текст:\n\(result.source)\n\nПеревод:\n\(result.text)\n\nВопросы ниже — про этот перевод.")
|
||||||
|
}
|
||||||
|
state.chatHistory.append(ChatMessage(role: .assistant, content: "**Перевод:**\n\n\(result.text)"))
|
||||||
|
}
|
||||||
|
|
||||||
private static func show(_ state: AppState) {
|
private static func show(_ state: AppState) {
|
||||||
if state.mode != .expanded || !(state.view == .overview || state.view == .empty) {
|
if state.mode != .expanded || !(state.view == .overview || state.view == .empty) {
|
||||||
NotificationCenter.default.post(name: .hookExpand, object: IslandView.overview)
|
NotificationCenter.default.post(name: .hookExpand, object: IslandView.overview)
|
||||||
@@ -118,7 +135,13 @@ enum SelectionGrabber {
|
|||||||
_ = AXIsProcessTrustedWithOptions(opts)
|
_ = AXIsProcessTrustedWithOptions(opts)
|
||||||
return clipboardText()
|
return clipboardText()
|
||||||
}
|
}
|
||||||
if let s = axSelection(), !s.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return s }
|
if let s = axSelection(), !s.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
|
||||||
|
// Browsers and Electron apps often report only the visible part of a selection.
|
||||||
|
// If the user copied it, the clipboard holds the whole thing.
|
||||||
|
if let clip = clipboardText(), clip.count > s.count,
|
||||||
|
clip.contains(s.trimmingCharacters(in: .whitespacesAndNewlines)) { return clip }
|
||||||
|
return s
|
||||||
|
}
|
||||||
// ⌘C only when BroV isn't the key window (hotkey path); from a click in the notch
|
// ⌘C only when BroV isn't the key window (hotkey path); from a click in the notch
|
||||||
// the keystroke would land in BroV itself.
|
// the keystroke would land in BroV itself.
|
||||||
if NSApp.keyWindow == nil, let s = await copyViaCommandC(), !s.isEmpty { return s }
|
if NSApp.keyWindow == nil, let s = await copyViaCommandC(), !s.isEmpty { return s }
|
||||||
@@ -206,7 +229,7 @@ struct TranslationCard: View {
|
|||||||
Text(result.source).lineLimit(1).font(.system(size: 11.5)).foregroundColor(Color(hex: "#6B7079"))
|
Text(result.source).lineLimit(1).font(.system(size: 11.5)).foregroundColor(Color(hex: "#6B7079"))
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
ScrollView(.vertical, showsIndicators: false) {
|
ScrollView(.vertical, showsIndicators: true) {
|
||||||
Text(result.text)
|
Text(result.text)
|
||||||
.font(.system(size: 12.5))
|
.font(.system(size: 12.5))
|
||||||
.textSelection(.enabled)
|
.textSelection(.enabled)
|
||||||
@@ -219,12 +242,7 @@ struct TranslationCard: View {
|
|||||||
SoundEngine.shared.play("blip")
|
SoundEngine.shared.play("blip")
|
||||||
}
|
}
|
||||||
FuncButton(symbol: "bubble.left", title: "В чат") {
|
FuncButton(symbol: "bubble.left", title: "В чат") {
|
||||||
if state.tabs.count < AppState.maxTabs { state.openTab(.chat) } else { state.view = .prompt }
|
TranslatorRun.moveToChat(state: state)
|
||||||
if let tab = state.activeTabId {
|
|
||||||
ChatTabs.shared.seed(tab, "Исходный текст:\n\(result.source)\n\nПеревод:\n\(result.text)\n\nВопросы ниже — про этот перевод.")
|
|
||||||
}
|
|
||||||
state.chatHistory.append(ChatMessage(role: .assistant, content: "**Перевод:**\n\n\(result.text)"))
|
|
||||||
state.translation = nil
|
|
||||||
}
|
}
|
||||||
Text(result.source).lineLimit(1).font(.system(size: 10.5)).foregroundColor(Color(hex: "#5F646D"))
|
Text(result.source).lineLimit(1).font(.system(size: 10.5)).foregroundColor(Color(hex: "#5F646D"))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,6 +41,12 @@ struct ApprovalInfo: Sendable {
|
|||||||
var pillId: String
|
var pillId: String
|
||||||
/// Why this request looks destructive (DangerCheck), empty when nothing matched.
|
/// Why this request looks destructive (DangerCheck), empty when nothing matched.
|
||||||
var danger: [String] = []
|
var danger: [String] = []
|
||||||
|
/// Queued request this card answers: a decision is only accepted for this id.
|
||||||
|
var id: UUID = UUID()
|
||||||
|
/// Requests waiting, this one included; the card shows the count when above 1.
|
||||||
|
var queueCount: Int = 1
|
||||||
|
/// Project of the session that asks (several sessions can share one pill).
|
||||||
|
var projectName: String = ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Pill badge (shown on pill edge when non-focused task has an alert)
|
// MARK: - Pill badge (shown on pill edge when non-focused task has an alert)
|
||||||
|
|||||||
@@ -72,6 +72,8 @@ targets:
|
|||||||
CFBundleShortVersionString: "0.1.0"
|
CFBundleShortVersionString: "0.1.0"
|
||||||
CFBundlePackageType: APPL
|
CFBundlePackageType: APPL
|
||||||
LSUIElement: YES
|
LSUIElement: YES
|
||||||
|
NSMicrophoneUsageDescription: "BroV слушает микрофон, когда ты диктуешь сообщение в чат."
|
||||||
|
NSSpeechRecognitionUsageDescription: "BroV превращает твой голос в текст сообщения в чате."
|
||||||
NSHighResolutionCapable: YES
|
NSHighResolutionCapable: YES
|
||||||
NSSupportsAutomaticGraphicsSwitching: YES
|
NSSupportsAutomaticGraphicsSwitching: YES
|
||||||
NSAppleEventsUsageDescription: "BroV jumps to your terminal, sends mail and controls Music."
|
NSAppleEventsUsageDescription: "BroV jumps to your terminal, sends mail and controls Music."
|
||||||
|
|||||||
+91
-13
@@ -31,8 +31,8 @@ CFG = {
|
|||||||
"api_port": int(os.environ.get("API_PORT", "8787")),
|
"api_port": int(os.environ.get("API_PORT", "8787")),
|
||||||
"db": os.environ.get("DB_PATH", "/var/lib/brov-ops/ops.db"),
|
"db": os.environ.get("DB_PATH", "/var/lib/brov-ops/ops.db"),
|
||||||
"tz": os.environ.get("TZ_NAME", "Europe/Moscow"),
|
"tz": os.environ.get("TZ_NAME", "Europe/Moscow"),
|
||||||
"claude": os.environ.get("CLAUDE_BIN", "claude"),
|
"kimi": os.environ.get("KIMI_BIN", "kimi"),
|
||||||
"model": os.environ.get("CLAUDE_MODEL", "haiku"),
|
"model": os.environ.get("KIMI_MODEL", ""),
|
||||||
"whisper": os.environ.get("WHISPER_MODEL", "small"),
|
"whisper": os.environ.get("WHISPER_MODEL", "small"),
|
||||||
"digest_hour": int(os.environ.get("DIGEST_HOUR", "9")),
|
"digest_hour": int(os.environ.get("DIGEST_HOUR", "9")),
|
||||||
"quiet_from": int(os.environ.get("QUIET_FROM", "22")),
|
"quiet_from": int(os.environ.get("QUIET_FROM", "22")),
|
||||||
@@ -82,8 +82,42 @@ def owner_only(handler):
|
|||||||
|
|
||||||
|
|
||||||
async def send_long(update: Update, text: str, **kw):
|
async def send_long(update: Update, text: str, **kw):
|
||||||
for i in range(0, len(text), 3800):
|
"""Splits long text; extra kwargs (buttons) go only on the last chunk."""
|
||||||
await update.effective_message.reply_text(text[i:i + 3800], parse_mode=ParseMode.HTML, **kw)
|
chunks = [text[i:i + 3800] for i in range(0, len(text), 3800)] or [""]
|
||||||
|
for i, chunk in enumerate(chunks):
|
||||||
|
last = i == len(chunks) - 1
|
||||||
|
await update.effective_message.reply_text(chunk, parse_mode=ParseMode.HTML, **(kw if last else {}))
|
||||||
|
|
||||||
|
|
||||||
|
def one_task_buttons(task_id: int) -> InlineKeyboardMarkup:
|
||||||
|
"""Buttons under a single task card — same callbacks as reminders."""
|
||||||
|
return InlineKeyboardMarkup([[
|
||||||
|
InlineKeyboardButton("✓ Сделано", callback_data=f"done:task:{task_id}"),
|
||||||
|
InlineKeyboardButton("⏰ Перенести", callback_data=f"snooze:task:{task_id}")]])
|
||||||
|
|
||||||
|
|
||||||
|
def flat_tasks(tree: list) -> list:
|
||||||
|
"""[(task, depth)] in display order."""
|
||||||
|
out = []
|
||||||
|
|
||||||
|
def walk(nodes, depth):
|
||||||
|
for n in nodes:
|
||||||
|
out.append((n, depth))
|
||||||
|
walk(n["children"], depth + 1)
|
||||||
|
walk(tree, 0)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
async def send_task_cards(update: Update, tree: list, limit: int = 12):
|
||||||
|
"""Every open task as its own message: task text, then Сделано / Перенести."""
|
||||||
|
tasks = flat_tasks(tree)
|
||||||
|
today = ops.today()
|
||||||
|
for t, depth in tasks[:limit]:
|
||||||
|
await update.effective_message.reply_text(fmt.task_line(t, depth, today),
|
||||||
|
parse_mode=ParseMode.HTML,
|
||||||
|
reply_markup=one_task_buttons(t["id"]))
|
||||||
|
if len(tasks) > limit:
|
||||||
|
await update.effective_message.reply_text(f"…и ещё {len(tasks) - limit}. Повтори /tasks.")
|
||||||
|
|
||||||
|
|
||||||
@owner_only
|
@owner_only
|
||||||
@@ -97,13 +131,22 @@ async def cmd_start(update: Update, ctx):
|
|||||||
|
|
||||||
@owner_only
|
@owner_only
|
||||||
async def cmd_today(update: Update, ctx):
|
async def cmd_today(update: Update, ctx):
|
||||||
await send_long(update, fmt.agenda(locked(ops.agenda)))
|
with lock:
|
||||||
|
agenda, tree = ops.agenda(), ops.task_tree()
|
||||||
|
await send_long(update, fmt.agenda(agenda))
|
||||||
|
await send_task_cards(update, tree)
|
||||||
|
|
||||||
|
|
||||||
@owner_only
|
@owner_only
|
||||||
async def cmd_tasks(update: Update, ctx):
|
async def cmd_tasks(update: Update, ctx):
|
||||||
lines = fmt.tree(locked(ops.task_tree))
|
with lock:
|
||||||
await send_long(update, "\n".join(lines) if lines else "Открытых задач нет 👌")
|
tree = ops.task_tree()
|
||||||
|
if not tree:
|
||||||
|
await update.effective_message.reply_text("Открытых задач нет 👌")
|
||||||
|
return
|
||||||
|
await update.effective_message.reply_text(
|
||||||
|
f"Открытые задачи ({len(flat_tasks(tree))}) — по одной, жми Сделано или Перенести:")
|
||||||
|
await send_task_cards(update, tree)
|
||||||
|
|
||||||
|
|
||||||
@owner_only
|
@owner_only
|
||||||
@@ -132,17 +175,24 @@ def repeat_buttons(sub: dict) -> InlineKeyboardMarkup:
|
|||||||
InlineKeyboardButton("Нет, закрыть", callback_data=f"rep:sub:{sub['id']}:0")]])
|
InlineKeyboardButton("Нет, закрыть", callback_data=f"rep:sub:{sub['id']}:0")]])
|
||||||
|
|
||||||
|
|
||||||
|
# Free-text asks that should end with the task list's buttons (nothing was changed, just shown).
|
||||||
|
LIST_HINTS = ("задач", "дела", "делы", "делах", "план", "список", "что там", "что горит",
|
||||||
|
"today", "tasks", "агенда")
|
||||||
|
|
||||||
|
|
||||||
async def think(update: Update, text: str):
|
async def think(update: Update, text: str):
|
||||||
msg = await update.effective_message.reply_text("🤔 думаю…")
|
msg = await update.effective_message.reply_text("🤔 думаю…")
|
||||||
paid: list = []
|
paid: list = []
|
||||||
try:
|
try:
|
||||||
answer = await asyncio.to_thread(brain.handle_text, ops, text, lock, CFG["claude"], CFG["model"], paid)
|
answer = await asyncio.to_thread(brain.handle_text, ops, text, lock, CFG["kimi"], CFG["model"], paid)
|
||||||
except OpsError as e:
|
except OpsError as e:
|
||||||
answer = f"Не получилось: {e}"
|
answer = f"Не получилось: {e}"
|
||||||
except Exception as e: # Claude timeout, CLI missing…
|
except Exception as e: # Kimi timeout, CLI missing…
|
||||||
log.exception("brain")
|
log.exception("brain")
|
||||||
answer = f"Ошибка: {e.__class__.__name__}"
|
answer = f"Ошибка: {e.__class__.__name__}"
|
||||||
await msg.edit_text(answer[:4000])
|
await msg.edit_text(answer[:4000])
|
||||||
|
if "✓" not in answer and any(h in text.lower() for h in LIST_HINTS):
|
||||||
|
await send_task_cards(update, locked(ops.task_tree))
|
||||||
for sid in paid: # paid by text: ask «repeat?» with buttons
|
for sid in paid: # paid by text: ask «repeat?» with buttons
|
||||||
s = locked(ops.sub, sid)
|
s = locked(ops.sub, sid)
|
||||||
if s["paid"] and s["active"]:
|
if s["paid"] and s["active"]:
|
||||||
@@ -213,6 +263,13 @@ async def on_button(update: Update, ctx):
|
|||||||
note = "⏰ Напомню завтра"
|
note = "⏰ Напомню завтра"
|
||||||
except OpsError as e:
|
except OpsError as e:
|
||||||
note = f"Не получилось: {e}"
|
note = f"Не получилось: {e}"
|
||||||
|
if action in ("done", "snooze") and kind == "task" and q.message.reply_markup:
|
||||||
|
# Task-list message (several task rows): drop the row just handled, keep the rest tappable.
|
||||||
|
# A single-row reminder keyboard is removed entirely, as before.
|
||||||
|
kb = q.message.reply_markup.inline_keyboard
|
||||||
|
if len(kb) > 1:
|
||||||
|
rows = [row for row in kb if not any(b.callback_data == f"{action}:task:{ref}" for b in row)]
|
||||||
|
markup = InlineKeyboardMarkup(rows) if rows else None
|
||||||
await q.answer()
|
await q.answer()
|
||||||
await q.edit_message_text(q.message.text + "\n\n" + note, reply_markup=markup)
|
await q.edit_message_text(q.message.text + "\n\n" + note, reply_markup=markup)
|
||||||
|
|
||||||
@@ -289,14 +346,14 @@ async def api_say(request):
|
|||||||
if not text:
|
if not text:
|
||||||
raise web.HTTPBadRequest(text="empty")
|
raise web.HTTPBadRequest(text="empty")
|
||||||
try:
|
try:
|
||||||
answer = await asyncio.to_thread(brain.handle_text, ops, text, lock, CFG["claude"], CFG["model"])
|
answer = await asyncio.to_thread(brain.handle_text, ops, text, lock, CFG["kimi"], CFG["model"])
|
||||||
except OpsError as e:
|
except OpsError as e:
|
||||||
return ok({"ok": False, "answer": str(e)})
|
return ok({"ok": False, "answer": str(e)})
|
||||||
return ok({"ok": True, "answer": answer})
|
return ok({"ok": True, "answer": answer})
|
||||||
|
|
||||||
|
|
||||||
async def api_action(request):
|
async def api_action(request):
|
||||||
"""One direct action from a BroV button (done, paid, timer…), no Claude involved."""
|
"""One direct action from a BroV button (done, paid, timer…), no Kimi involved."""
|
||||||
check_auth(request)
|
check_auth(request)
|
||||||
body = await request.json()
|
body = await request.json()
|
||||||
if body.get("op") == "snooze":
|
if body.get("op") == "snooze":
|
||||||
@@ -308,7 +365,7 @@ async def api_action(request):
|
|||||||
|
|
||||||
|
|
||||||
async def api_delete(request):
|
async def api_delete(request):
|
||||||
"""Delete by an explicit click in BroV (Claude never deletes)."""
|
"""Delete by an explicit click in BroV (Kimi never deletes)."""
|
||||||
check_auth(request)
|
check_auth(request)
|
||||||
body = await request.json()
|
body = await request.json()
|
||||||
kind, ref = str(body.get("kind")), int(body.get("id"))
|
kind, ref = str(body.get("kind")), int(body.get("id"))
|
||||||
@@ -380,12 +437,15 @@ async def main():
|
|||||||
log.warning("TELEGRAM_TOKEN not set: API only")
|
log.warning("TELEGRAM_TOKEN not set: API only")
|
||||||
await asyncio.Event().wait()
|
await asyncio.Event().wait()
|
||||||
proxy = CFG["proxy"] or None
|
proxy = CFG["proxy"] or None
|
||||||
|
|
||||||
|
def build_tg() -> Application:
|
||||||
builder = (Application.builder().token(CFG["token"])
|
builder = (Application.builder().token(CFG["token"])
|
||||||
.request(HTTPXRequest(proxy=proxy, connect_timeout=10, read_timeout=20, write_timeout=20,
|
.request(HTTPXRequest(proxy=proxy, connect_timeout=10, read_timeout=20, write_timeout=20,
|
||||||
pool_timeout=10, connection_pool_size=8))
|
pool_timeout=10, connection_pool_size=8))
|
||||||
.get_updates_request(PollRequest(proxy=proxy, connect_timeout=10, read_timeout=40,
|
.get_updates_request(PollRequest(proxy=proxy, connect_timeout=10, read_timeout=40,
|
||||||
write_timeout=10, pool_timeout=10)))
|
write_timeout=10, pool_timeout=10)))
|
||||||
tg = builder.build()
|
tg = builder.build()
|
||||||
|
|
||||||
async def on_error(update, ctx):
|
async def on_error(update, ctx):
|
||||||
log.error("handler failed", exc_info=ctx.error)
|
log.error("handler failed", exc_info=ctx.error)
|
||||||
tg.add_error_handler(on_error)
|
tg.add_error_handler(on_error)
|
||||||
@@ -398,12 +458,30 @@ async def main():
|
|||||||
tg.add_handler(CallbackQueryHandler(on_button))
|
tg.add_handler(CallbackQueryHandler(on_button))
|
||||||
tg.add_handler(MessageHandler(filters.VOICE | filters.AUDIO, on_voice))
|
tg.add_handler(MessageHandler(filters.VOICE | filters.AUDIO, on_voice))
|
||||||
tg.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, on_text))
|
tg.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, on_text))
|
||||||
async with tg:
|
return tg
|
||||||
|
|
||||||
|
# A Telegram/proxy outage must not kill the API, calendar and reminders. Every retry
|
||||||
|
# builds a FRESH Application: 06.11.2026 a proxy hiccup poisoned the shared httpx pool
|
||||||
|
# (PoolTimeout on every get_me) and reusing the same tg object looped forever — the API
|
||||||
|
# answered, the bot stayed dead for 2.5 days. If a fresh app still can't start 10 times
|
||||||
|
# (~5 minutes), exit and let systemd bring up a clean process.
|
||||||
|
fails = 0
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
async with build_tg() as tg:
|
||||||
await tg.start()
|
await tg.start()
|
||||||
await tg.updater.start_polling(drop_pending_updates=False, timeout=25)
|
await tg.updater.start_polling(drop_pending_updates=False, timeout=25)
|
||||||
|
fails = 0
|
||||||
asyncio.create_task(reminder_loop(tg.bot))
|
asyncio.create_task(reminder_loop(tg.bot))
|
||||||
asyncio.create_task(poll_watchdog())
|
asyncio.create_task(poll_watchdog())
|
||||||
await asyncio.Event().wait()
|
await asyncio.Event().wait()
|
||||||
|
except Exception:
|
||||||
|
fails += 1
|
||||||
|
log.exception("Telegram unavailable (attempt %d); API remains active, retrying in 30 s", fails)
|
||||||
|
if fails >= 10:
|
||||||
|
log.error("Telegram still broken after %d fresh attempts — restarting", fails)
|
||||||
|
os._exit(1)
|
||||||
|
await asyncio.sleep(30)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
+36
-2
@@ -5,6 +5,8 @@ import json
|
|||||||
import os
|
import os
|
||||||
import subprocess
|
import subprocess
|
||||||
import tempfile
|
import tempfile
|
||||||
|
import time
|
||||||
|
from collections import deque
|
||||||
|
|
||||||
from .core import Ops, OpsError, client_name, ru_day
|
from .core import Ops, OpsError, client_name, ru_day
|
||||||
|
|
||||||
@@ -45,6 +47,8 @@ INSTRUCTIONS = """Ты — помощник-менеджер системног
|
|||||||
- После pay_sub добавляй repeat_sub, только если пользователь сам сказал, продлевать или нет
|
- После pay_sub добавляй repeat_sub, только если пользователь сам сказал, продлевать или нет
|
||||||
(«оплатил и продлеваем», «больше не нужна»); иначе в reply спроси, повторять ли.
|
(«оплатил и продлеваем», «больше не нужна»); иначе в reply спроси, повторять ли.
|
||||||
- reply — 1–3 строки, без markdown-заголовков.
|
- reply — 1–3 строки, без markdown-заголовков.
|
||||||
|
- Ниже может быть «Недавний разговор»: короткие ответы вроде «да», «поправь», «не надо»,
|
||||||
|
«перенеси на пятницу» относятся к нему. Не повторяй действия, которые там уже сделаны.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
ALLOWED = {"add_task", "update_task", "complete_task", "reopen_task", "start_timer", "stop_timer",
|
ALLOWED = {"add_task", "update_task", "complete_task", "reopen_task", "start_timer", "stop_timer",
|
||||||
@@ -172,14 +176,44 @@ def _only(d: dict, *keys) -> dict:
|
|||||||
return {k: d[k] for k in keys if k in d}
|
return {k: d[k] for k in keys if k in d}
|
||||||
|
|
||||||
|
|
||||||
|
# Recent exchanges, shared by Telegram and BroV (one owner): each `claude -p` call starts
|
||||||
|
# from scratch, so without this «да, поправь» has nothing to refer to. Memory only — a
|
||||||
|
# restart forgets the conversation, not the data.
|
||||||
|
HISTORY_TURNS = 6
|
||||||
|
HISTORY_TTL = 2 * 3600
|
||||||
|
_history: deque = deque(maxlen=HISTORY_TURNS)
|
||||||
|
|
||||||
|
|
||||||
|
def history_text(now: float | None = None) -> str:
|
||||||
|
now = time.time() if now is None else now
|
||||||
|
recent = [h for h in _history if now - h[0] <= HISTORY_TTL]
|
||||||
|
if not recent:
|
||||||
|
return ""
|
||||||
|
lines = ["Недавний разговор (старое сверху):"]
|
||||||
|
for _, said, answered in recent:
|
||||||
|
lines.append("Пользователь: " + said[:500])
|
||||||
|
lines.append("Ты: " + answered[:700])
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
def remember(said: str, answered: str, now: float | None = None):
|
||||||
|
_history.append((time.time() if now is None else now, said.strip(), answered.strip()))
|
||||||
|
|
||||||
|
|
||||||
def handle_text(ops: Ops, text: str, lock, claude_bin: str = "claude", model: str = "haiku",
|
def handle_text(ops: Ops, text: str, lock, claude_bin: str = "claude", model: str = "haiku",
|
||||||
paid: list | None = None) -> str:
|
paid: list | None = None) -> str:
|
||||||
"""One message in, one answer out (actions taken + Claude's reply). The database lock
|
"""One message in, one answer out (actions taken + Claude's reply). The database lock
|
||||||
is held only while reading the state and applying the actions, not while Claude thinks."""
|
is held only while reading the state and applying the actions, not while Claude thinks."""
|
||||||
with lock:
|
with lock:
|
||||||
prompt = snapshot(ops) + "\n\nСообщение пользователя:\n" + text.strip()
|
prompt = snapshot(ops)
|
||||||
|
past = history_text()
|
||||||
|
if past:
|
||||||
|
prompt += "\n\n" + past
|
||||||
|
prompt += "\n\nСообщение пользователя:\n" + text.strip()
|
||||||
plan = parse_plan(ask_claude(prompt, claude_bin, model))
|
plan = parse_plan(ask_claude(prompt, claude_bin, model))
|
||||||
with lock:
|
with lock:
|
||||||
lines = apply_plan(ops, plan, paid)
|
lines = apply_plan(ops, plan, paid)
|
||||||
reply = str(plan.get("reply", "")).strip()
|
reply = str(plan.get("reply", "")).strip()
|
||||||
return "\n".join(([reply] if reply else []) + lines) or "Готово."
|
answer = "\n".join(([reply] if reply else []) + lines) or "Готово."
|
||||||
|
remember(text, answer)
|
||||||
|
return answer
|
||||||
|
|||||||
@@ -55,6 +55,16 @@ def tree(nodes: list, depth: int = 0) -> list[str]:
|
|||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def task_line(t: dict, depth: int, today: date) -> str:
|
||||||
|
"""One task as a standalone card text (sent as its own message with buttons)."""
|
||||||
|
mark = "⏱" if t["running"] else ("▶️" if t["status"] == "doing" else "📌")
|
||||||
|
due = f"\nСрок: {human_day(t['due'], today)}" if t["due"] else ""
|
||||||
|
mins = f"\nУчтено: {t['minutes']} мин" if t["minutes"] else ""
|
||||||
|
client = f" [{client_name(t['client'])}]" if t["client"] else ""
|
||||||
|
indent = "└ " * depth
|
||||||
|
return f"{indent}{mark} <b>{escape(t['title'])}</b>{client}{due}{mins}"
|
||||||
|
|
||||||
|
|
||||||
def subs(rows: list, by_client: dict, today: date) -> str:
|
def subs(rows: list, by_client: dict, today: date) -> str:
|
||||||
"""Grouped by company, each with its monthly total."""
|
"""Grouped by company, each with its monthly total."""
|
||||||
if not rows:
|
if not rows:
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
[Unit]
|
[Unit]
|
||||||
Description=BroV Ops proxy core (mihomo, proxy mode only: Telegram + Claude for brov-ops)
|
Description=BroV Ops proxy core (Xray, HTTP proxy on 127.0.0.1:7890: Telegram + Kimi for brov-ops)
|
||||||
After=network-online.target
|
After=network-online.target
|
||||||
Wants=network-online.target
|
Wants=network-online.target
|
||||||
|
|
||||||
[Service]
|
[Service]
|
||||||
User=brovops
|
User=brovops
|
||||||
Group=brovops
|
Group=brovops
|
||||||
ExecStart=/usr/local/bin/mihomo -d /etc/brov-ops/proxy -f /etc/brov-ops/proxy/config.yaml
|
ExecStart=/opt/brov-ops/xray run -config /etc/brov-ops/proxy/xray.json
|
||||||
Restart=always
|
Restart=always
|
||||||
RestartSec=5
|
RestartSec=5
|
||||||
NoNewPrivileges=yes
|
NoNewPrivileges=yes
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Build /etc/brov-ops/proxy/xray.json from a nodes file of vless:// links.
|
||||||
|
|
||||||
|
Usage: gen-xray.py <nodes.txt> <out xray.json>
|
||||||
|
|
||||||
|
The nodes file holds one vless:// link per line (comments and blanks skipped).
|
||||||
|
Subscription contents are accepted too: base64 blob that decodes to vless:// lines.
|
||||||
|
Only REALITY+tcp VLESS nodes are used (that is what brov-ops' proxy runs on).
|
||||||
|
The first node becomes the outbound; extra nodes go into a round-robin balancer.
|
||||||
|
"""
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
from urllib.parse import parse_qs, urlparse
|
||||||
|
|
||||||
|
|
||||||
|
def links(path: str) -> list[str]:
|
||||||
|
raw = open(path, encoding="utf-8").read().strip()
|
||||||
|
if "vless://" not in raw: # maybe a base64 subscription blob
|
||||||
|
try:
|
||||||
|
raw = base64.b64decode(raw).decode("utf-8")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return [ln.strip() for ln in raw.splitlines() if ln.strip().startswith("vless://")]
|
||||||
|
|
||||||
|
|
||||||
|
def outbound(link: str, tag: str) -> dict:
|
||||||
|
u = urlparse(link)
|
||||||
|
q = {k: v[0] for k, v in parse_qs(u.query).items()}
|
||||||
|
if q.get("security") != "reality" or q.get("type", "tcp") != "tcp":
|
||||||
|
raise ValueError(f"пропускаю не-REALITY узел: {link[:40]}…")
|
||||||
|
return {
|
||||||
|
"tag": tag,
|
||||||
|
"protocol": "vless",
|
||||||
|
"settings": {"vnext": [{
|
||||||
|
"address": u.hostname,
|
||||||
|
"port": u.port or 443,
|
||||||
|
"users": [{"id": u.username, "encryption": q.get("encryption", "none"),
|
||||||
|
**({"flow": q["flow"]} if q.get("flow") else {})}],
|
||||||
|
}]},
|
||||||
|
"streamSettings": {
|
||||||
|
"network": "tcp",
|
||||||
|
"security": "reality",
|
||||||
|
"realitySettings": {
|
||||||
|
"serverName": q.get("sni", ""),
|
||||||
|
"fingerprint": q.get("fp", "chrome"),
|
||||||
|
"publicKey": q["pbk"],
|
||||||
|
"shortId": q.get("sid", ""),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
nodes_path, out_path = sys.argv[1], sys.argv[2]
|
||||||
|
found = links(nodes_path)
|
||||||
|
if not found:
|
||||||
|
raise SystemExit("✗ в файле узлов нет ни одной vless:// ссылки")
|
||||||
|
outbounds, tags = [], []
|
||||||
|
for i, link in enumerate(found):
|
||||||
|
try:
|
||||||
|
ob = outbound(link, f"node{i}")
|
||||||
|
except (ValueError, KeyError) as e:
|
||||||
|
print(f"⚠ {e}", file=sys.stderr)
|
||||||
|
continue
|
||||||
|
outbounds.append(ob)
|
||||||
|
tags.append(ob["tag"])
|
||||||
|
if not outbounds:
|
||||||
|
raise SystemExit("✗ ни одного рабочего REALITY-узла")
|
||||||
|
cfg = {
|
||||||
|
"log": {"loglevel": "warning"},
|
||||||
|
"inbounds": [{"listen": "127.0.0.1", "port": 7890, "protocol": "http",
|
||||||
|
"settings": {"timeout": 0}}],
|
||||||
|
"outbounds": outbounds,
|
||||||
|
}
|
||||||
|
if len(tags) > 1:
|
||||||
|
cfg["routing"] = {"balancers": [{"tag": "out", "selector": tags}]}
|
||||||
|
with open(out_path, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(cfg, f, indent=1, ensure_ascii=False)
|
||||||
|
f.write("\n")
|
||||||
|
print(f"✓ xray.json: {len(tags)} узл(а)")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
+51
-61
@@ -3,8 +3,8 @@
|
|||||||
# sudo sh ops/deploy/install.sh
|
# sudo sh ops/deploy/install.sh
|
||||||
#
|
#
|
||||||
# Puts the service in /opt/brov-ops (user brovops), data in /var/lib/brov-ops, settings in
|
# Puts the service in /opt/brov-ops (user brovops), data in /var/lib/brov-ops, settings in
|
||||||
# /etc/brov-ops (root, 600). Telegram and Claude go through a local proxy core (mihomo in
|
# /etc/brov-ops (root, 600). Telegram and Kimi go through a local proxy core (Xray in
|
||||||
# proxy mode on 127.0.0.1:7890 — only this service uses it, the VM itself is not tunnelled).
|
# HTTP-proxy mode on 127.0.0.1:7890 — only this service uses it, the VM is not tunnelled).
|
||||||
#
|
#
|
||||||
# Secrets on the first run: the VLESS subscription URL and the Telegram bot token are taken
|
# Secrets on the first run: the VLESS subscription URL and the Telegram bot token are taken
|
||||||
# from ~/.brovops-sub and ~/.brovops-token of the user running sudo (moved into
|
# from ~/.brovops-sub and ~/.brovops-token of the user running sudo (moved into
|
||||||
@@ -16,14 +16,14 @@ set -e
|
|||||||
HERE=$(cd "$(dirname "$0")/.." && pwd)
|
HERE=$(cd "$(dirname "$0")/.." && pwd)
|
||||||
ETC=/etc/brov-ops
|
ETC=/etc/brov-ops
|
||||||
PROXY_DIR=$ETC/proxy
|
PROXY_DIR=$ETC/proxy
|
||||||
MIHOMO_VERSION=v1.19.32
|
XRAY_VERSION=26.10.31
|
||||||
MIHOMO_GZ_SHA=8451100836c9eda194331c2babfad490b2faf30cebc1a04b0e76fd8ac2d35d10
|
XRAY_ZIP_SHA=e4bd9119f50ae7c41658b1abd0679ae06f98bd864a2907ff33f2f2cf7081b214
|
||||||
MIHOMO_BIN_SHA=3122d100e8177501776109f1a6253a694611627cf4d7c7ec82705855cf8626a8
|
XRAY_BIN_SHA=cc4b84d3069569f297a61f04b914f2bb37e9d202fd7b84cb50def1fc30fd40e1
|
||||||
PROXY=http://127.0.0.1:7890
|
PROXY=http://127.0.0.1:7890
|
||||||
|
|
||||||
echo "→ Пакеты"
|
echo "→ Пакеты"
|
||||||
apt-get update -qq
|
apt-get update -qq
|
||||||
apt-get install -y -qq python3-venv python3-pip ffmpeg curl ca-certificates openssl >/dev/null
|
apt-get install -y -qq python3-venv python3-pip ffmpeg curl ca-certificates openssl unzip >/dev/null
|
||||||
|
|
||||||
id brovops >/dev/null 2>&1 || useradd --system --create-home --home-dir /home/brovops --shell /usr/sbin/nologin brovops
|
id brovops >/dev/null 2>&1 || useradd --system --create-home --home-dir /home/brovops --shell /usr/sbin/nologin brovops
|
||||||
install -d -m 755 /opt/brov-ops
|
install -d -m 755 /opt/brov-ops
|
||||||
@@ -31,13 +31,15 @@ install -d -m 750 -o brovops -g brovops /var/lib/brov-ops
|
|||||||
install -d -m 750 -o root -g brovops $ETC
|
install -d -m 750 -o root -g brovops $ETC
|
||||||
install -d -m 700 -o brovops -g brovops $PROXY_DIR
|
install -d -m 700 -o brovops -g brovops $PROXY_DIR
|
||||||
|
|
||||||
echo "→ Прокси-ядро (mihomo $MIHOMO_VERSION)"
|
echo "→ Прокси-ядро (Xray $XRAY_VERSION)"
|
||||||
if [ "$(sha256sum /usr/local/bin/mihomo 2>/dev/null | cut -d' ' -f1)" != "$MIHOMO_BIN_SHA" ]; then
|
# Xray, не mihomo: 05.11.2026 mihomo не смог в REALITY handshake против Xray-сервера
|
||||||
|
# (REALITY authentication failed), а Xray-клиент ходит стабильно. Версия и суммы pinned.
|
||||||
|
if [ "$(sha256sum /opt/brov-ops/xray 2>/dev/null | cut -d' ' -f1)" != "$XRAY_BIN_SHA" ]; then
|
||||||
TMP=$(mktemp -d)
|
TMP=$(mktemp -d)
|
||||||
curl -fsSL -o "$TMP/m.gz" "https://github.com/MetaCubeX/mihomo/releases/download/$MIHOMO_VERSION/mihomo-linux-amd64-$MIHOMO_VERSION.gz"
|
curl -fsSL -o "$TMP/x.zip" "https://github.com/XTLS/Xray-core/releases/download/v$XRAY_VERSION/Xray-linux-64.zip"
|
||||||
[ "$(sha256sum "$TMP/m.gz" | cut -d' ' -f1)" = "$MIHOMO_GZ_SHA" ] || { echo "✗ архив mihomo не совпал с контрольной суммой"; exit 1; }
|
[ "$(sha256sum "$TMP/x.zip" | cut -d' ' -f1)" = "$XRAY_ZIP_SHA" ] || { echo "✗ архив Xray не совпал с контрольной суммой"; exit 1; }
|
||||||
gunzip -c "$TMP/m.gz" > "$TMP/mihomo"
|
unzip -q -o "$TMP/x.zip" -d "$TMP"
|
||||||
install -m 755 "$TMP/mihomo" /usr/local/bin/mihomo
|
install -m 755 "$TMP/xray" /opt/brov-ops/xray
|
||||||
rm -rf "$TMP"
|
rm -rf "$TMP"
|
||||||
fi
|
fi
|
||||||
USER_HOME=$(getent passwd "${SUDO_USER:-root}" | cut -d: -f6)
|
USER_HOME=$(getent passwd "${SUDO_USER:-root}" | cut -d: -f6)
|
||||||
@@ -54,51 +56,30 @@ ask_secret() { # prompt → stdout, input not echoed
|
|||||||
# Server list: the subscription content as a file (~/.brovops-nodes — when the subscription
|
# Server list: the subscription content as a file (~/.brovops-nodes — when the subscription
|
||||||
# page itself is blocked from here) and/or the subscription URL (~/.brovops-sub).
|
# page itself is blocked from here) and/or the subscription URL (~/.brovops-sub).
|
||||||
NODES=$(take_file nodes); [ -n "$NODES" ] && printf '%s\n' "$NODES" > $PROXY_DIR/nodes.txt
|
NODES=$(take_file nodes); [ -n "$NODES" ] && printf '%s\n' "$NODES" > $PROXY_DIR/nodes.txt
|
||||||
SUBURL=$(take_file sub); [ -n "$SUBURL" ] && printf '%s\n' "$SUBURL" > $PROXY_DIR/vless.sub
|
SUBURL=$(take_file sub)
|
||||||
|
if [ -n "$SUBURL" ]; then
|
||||||
|
case "$SUBURL" in
|
||||||
|
vless://*) printf '%s\n' "$SUBURL" > $PROXY_DIR/nodes.txt ;; # a single key, not a subscription
|
||||||
|
*) printf '%s\n' "$SUBURL" > $PROXY_DIR/vless.sub ;;
|
||||||
|
esac
|
||||||
|
fi
|
||||||
if [ ! -s $PROXY_DIR/nodes.txt ] && [ ! -s $PROXY_DIR/vless.sub ]; then
|
if [ ! -s $PROXY_DIR/nodes.txt ] && [ ! -s $PROXY_DIR/vless.sub ]; then
|
||||||
ask_secret "Ссылка подписки VLESS (ввод скрыт): " > $PROXY_DIR/vless.sub
|
ask_secret "Ссылка подписки VLESS (ввод скрыт): " > $PROXY_DIR/vless.sub
|
||||||
[ -s $PROXY_DIR/vless.sub ] || { echo "✗ нет ни подписки, ни списка серверов"; exit 1; }
|
[ -s $PROXY_DIR/vless.sub ] || { echo "✗ нет ни подписки, ни списка серверов"; exit 1; }
|
||||||
fi
|
fi
|
||||||
PROVIDERS=""; USE=""
|
# Xray не умеет подписки сам: скачиваем список узлов один раз при установке и генерируем
|
||||||
if [ -s $PROXY_DIR/nodes.txt ]; then
|
# статичный xray.json из vless:// ссылок (REALITY). Обновление узлов — правка nodes.txt
|
||||||
PROVIDERS="$PROVIDERS
|
# и повторный запуск gen-xray.py + systemctl restart brov-ops-proxy.
|
||||||
nodes:
|
if [ ! -s $PROXY_DIR/nodes.txt ] && [ -s $PROXY_DIR/vless.sub ]; then
|
||||||
type: file
|
curl -fsSL -m 30 -o $PROXY_DIR/nodes.txt "$(head -n1 $PROXY_DIR/vless.sub | tr -d '\r\n ')" \
|
||||||
path: ./nodes.txt
|
|| { echo "✗ подписка не скачалась — положи узлы файлом ~/.brovops-nodes"; exit 1; }
|
||||||
health-check: {enable: true, url: \"https://www.gstatic.com/generate_204\", interval: 300}"
|
|
||||||
USE="nodes"
|
|
||||||
fi
|
fi
|
||||||
if [ -s $PROXY_DIR/vless.sub ]; then
|
python3 "$HERE/deploy/gen-xray.py" $PROXY_DIR/nodes.txt $PROXY_DIR/xray.json
|
||||||
SUB=$(head -n1 $PROXY_DIR/vless.sub | tr -d '\r\n ')
|
|
||||||
PROVIDERS="$PROVIDERS
|
|
||||||
vless:
|
|
||||||
type: http
|
|
||||||
url: \"$SUB\"
|
|
||||||
path: ./vless.yaml
|
|
||||||
interval: 43200
|
|
||||||
proxy: DIRECT
|
|
||||||
health-check: {enable: true, url: \"https://www.gstatic.com/generate_204\", interval: 300}"
|
|
||||||
USE="${USE:+$USE, }vless"
|
|
||||||
fi
|
|
||||||
umask 077
|
|
||||||
cat > $PROXY_DIR/config.yaml <<EOF
|
|
||||||
# Generated by install.sh — proxy for brov-ops only (no TUN, nothing system-wide).
|
|
||||||
mixed-port: 7890
|
|
||||||
bind-address: 127.0.0.1
|
|
||||||
allow-lan: false
|
|
||||||
mode: rule
|
|
||||||
log-level: warning
|
|
||||||
ipv6: false
|
|
||||||
proxy-providers:$PROVIDERS
|
|
||||||
proxy-groups:
|
|
||||||
- {name: out, type: url-test, use: [$USE], url: "https://www.gstatic.com/generate_204", interval: 120, tolerance: 100}
|
|
||||||
rules:
|
|
||||||
- MATCH,out
|
|
||||||
EOF
|
|
||||||
umask 022
|
|
||||||
chown -R brovops:brovops $PROXY_DIR
|
chown -R brovops:brovops $PROXY_DIR
|
||||||
chmod 600 $PROXY_DIR/*
|
chmod 600 $PROXY_DIR/*
|
||||||
install -m 644 "$HERE/deploy/brov-ops-proxy.service" /etc/systemd/system/
|
install -m 644 "$HERE/deploy/brov-ops-proxy.service" /etc/systemd/system/
|
||||||
|
# Drop-in from the manual 05.11 hotfix and any mihomo leftovers must not override the unit.
|
||||||
|
rm -rf /etc/systemd/system/brov-ops-proxy.service.d
|
||||||
systemctl daemon-reload
|
systemctl daemon-reload
|
||||||
systemctl enable --now brov-ops-proxy >/dev/null
|
systemctl enable --now brov-ops-proxy >/dev/null
|
||||||
systemctl restart brov-ops-proxy
|
systemctl restart brov-ops-proxy
|
||||||
@@ -108,24 +89,33 @@ curl -s -m 8 -o /dev/null -w " Telegram через прокси: HTTP %{http_co
|
|||||||
echo "→ Код и Python-окружение"
|
echo "→ Код и Python-окружение"
|
||||||
cp -r "$HERE/brovops" "$HERE/requirements.txt" /opt/brov-ops/
|
cp -r "$HERE/brovops" "$HERE/requirements.txt" /opt/brov-ops/
|
||||||
[ -x /opt/brov-ops/venv/bin/python ] || python3 -m venv /opt/brov-ops/venv
|
[ -x /opt/brov-ops/venv/bin/python ] || python3 -m venv /opt/brov-ops/venv
|
||||||
HTTPS_PROXY=$PROXY /opt/brov-ops/venv/bin/pip install -q --upgrade pip
|
/opt/brov-ops/venv/bin/pip install -q --upgrade pip
|
||||||
HTTPS_PROXY=$PROXY /opt/brov-ops/venv/bin/pip install -q -r /opt/brov-ops/requirements.txt
|
/opt/brov-ops/venv/bin/pip install -q -r /opt/brov-ops/requirements.txt
|
||||||
|
|
||||||
echo "→ Claude Code"
|
echo "→ Kimi Code"
|
||||||
CLAUDE=/home/brovops/.local/bin/claude
|
KIMI=/home/brovops/.kimi-code/bin/kimi
|
||||||
if [ ! -x $CLAUDE ]; then
|
if [ ! -x $KIMI ]; then
|
||||||
sudo -u brovops -H env HTTPS_PROXY=$PROXY HTTP_PROXY=$PROXY sh -c 'curl -fsSL https://claude.ai/install.sh | bash' >/dev/null
|
# Kimi and PyPI are reachable directly; only Telegram requires the local proxy.
|
||||||
|
sudo -u brovops -H sh -c 'curl -fsSL https://code.kimi.com/kimi-code/install.sh | bash' >/dev/null
|
||||||
fi
|
fi
|
||||||
[ -x $CLAUDE ] && echo " ✓ $($CLAUDE --version 2>/dev/null)" || echo " ⚠ Claude Code не установился"
|
[ -x $KIMI ] && echo " ✓ $($KIMI --version 2>/dev/null)" || echo " ⚠ Kimi Code не установился"
|
||||||
|
|
||||||
echo "→ Настройки"
|
echo "→ Настройки"
|
||||||
if [ ! -f $ETC/config.env ]; then
|
if [ ! -f $ETC/config.env ]; then
|
||||||
# Whisper "small" needs ~1 GB on top of Claude: on a small VM take "base".
|
# Whisper "small" needs ~1 GB on top of Kimi: on a small VM take "base".
|
||||||
MEM_MB=$(awk '/MemTotal/ {print int($2/1024)}' /proc/meminfo)
|
MEM_MB=$(awk '/MemTotal/ {print int($2/1024)}' /proc/meminfo)
|
||||||
WHISPER=small; [ "$MEM_MB" -lt 3500 ] && WHISPER=base
|
WHISPER=small; [ "$MEM_MB" -lt 3500 ] && WHISPER=base
|
||||||
sed -e "s|^API_TOKEN=.*|API_TOKEN=$(openssl rand -hex 24)|" -e "s|^CLAUDE_BIN=.*|CLAUDE_BIN=$CLAUDE|" \
|
sed -e "s|^API_TOKEN=.*|API_TOKEN=$(openssl rand -hex 24)|" -e "s|^KIMI_BIN=.*|KIMI_BIN=$KIMI|" \
|
||||||
-e "s|^WHISPER_MODEL=.*|WHISPER_MODEL=$WHISPER|" "$HERE/deploy/config.env.example" > $ETC/config.env
|
-e "s|^WHISPER_MODEL=.*|WHISPER_MODEL=$WHISPER|" "$HERE/deploy/config.env.example" > $ETC/config.env
|
||||||
|
else
|
||||||
|
# Migrate an existing installation without touching tokens, owner or other settings.
|
||||||
|
# Old global proxy variables were for Claude; Telegram has its own TELEGRAM_PROXY.
|
||||||
|
sed -i -e "s|^CLAUDE_BIN=.*|KIMI_BIN=$KIMI|" -e "s|^CLAUDE_MODEL=.*|KIMI_MODEL=|" \
|
||||||
|
-e '/^HTTPS_PROXY=/d' -e '/^HTTP_PROXY=/d' $ETC/config.env
|
||||||
fi
|
fi
|
||||||
|
grep -q "^KIMI_BIN=" $ETC/config.env || echo "KIMI_BIN=$KIMI" >> $ETC/config.env
|
||||||
|
grep -q "^KIMI_MODEL=" $ETC/config.env || echo "KIMI_MODEL=" >> $ETC/config.env
|
||||||
|
grep -q "^KIMI_PROXY=" $ETC/config.env || echo "KIMI_PROXY=" >> $ETC/config.env
|
||||||
if ! grep -q "^TELEGRAM_TOKEN=." $ETC/config.env; then
|
if ! grep -q "^TELEGRAM_TOKEN=." $ETC/config.env; then
|
||||||
TOK=$(take_file token)
|
TOK=$(take_file token)
|
||||||
[ -n "$TOK" ] || TOK=$(ask_secret "Токен бота от @BotFather (ввод скрыт): ")
|
[ -n "$TOK" ] || TOK=$(ask_secret "Токен бота от @BotFather (ввод скрыт): ")
|
||||||
@@ -148,9 +138,9 @@ systemctl is-active --quiet brov-ops && echo "✓ brov-ops работает" ||
|
|||||||
cat <<EOF
|
cat <<EOF
|
||||||
|
|
||||||
Дальше (один раз):
|
Дальше (один раз):
|
||||||
1. Войти в Claude под своей подпиской:
|
1. Войти в Kimi под своей подпиской:
|
||||||
sudo -u brovops -H env HTTPS_PROXY=$PROXY HTTP_PROXY=$PROXY $CLAUDE
|
sudo -u brovops -H $KIMI login
|
||||||
(в нём /login, потом /exit), затем: sudo systemctl restart brov-ops
|
Завершить device-code авторизацию, затем: sudo systemctl restart brov-ops
|
||||||
2. Написать боту /start — первый, кто напишет, станет владельцем.
|
2. Написать боту /start — первый, кто напишет, станет владельцем.
|
||||||
Токен для BroV (API_TOKEN): sudo grep API_TOKEN $ETC/config.env
|
Токен для BroV (API_TOKEN): sudo grep API_TOKEN $ETC/config.env
|
||||||
EOF
|
EOF
|
||||||
|
|||||||
@@ -174,5 +174,26 @@ class Company(unittest.TestCase):
|
|||||||
os.remove(path)
|
os.remove(path)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
class HistoryTest(unittest.TestCase):
|
||||||
|
def test_follow_up_sees_previous_exchange(self):
|
||||||
|
brain._history.clear()
|
||||||
|
o = Ops(connect(":memory:"))
|
||||||
|
seen = []
|
||||||
|
def fake(prompt, *a, **k):
|
||||||
|
seen.append(prompt)
|
||||||
|
return '{"actions":[],"reply":"Ок"}'
|
||||||
|
brain.ask_claude = fake
|
||||||
|
brain.handle_text(o, "задача посмотреть бегущий по лезвию 2033", threading.Lock())
|
||||||
|
brain.handle_text(o, "да, поправь", threading.Lock())
|
||||||
|
self.assertNotIn("Недавний разговор", seen[0])
|
||||||
|
self.assertIn("бегущий по лезвию 2033", seen[1])
|
||||||
|
self.assertLess(seen[1].index("Недавний разговор"), seen[1].index("да, поправь"))
|
||||||
|
|
||||||
|
def test_old_history_expires(self):
|
||||||
|
brain._history.clear()
|
||||||
|
brain.remember("старое", "ответ", now=0)
|
||||||
|
self.assertEqual(brain.history_text(now=brain.HISTORY_TTL + 1), "")
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
+53
-19
@@ -68,12 +68,43 @@ def mid(v, default):
|
|||||||
return (int(m.group(1)) + int(m.group(2))) // 2 if m else int(v)
|
return (int(m.group(1)) + int(m.group(2))) // 2 if m else int(v)
|
||||||
|
|
||||||
|
|
||||||
def amnezia(path, name):
|
def decode_key(path):
|
||||||
|
"""vpn:// → (payload, description). Two formats are shared by Amnezia:
|
||||||
|
the JSON one (containers → awg → last_config) and, from newer apps, a plain AmneziaWG
|
||||||
|
.conf ([Interface] / [Peer]) under the same base64url + 4-byte length + zlib wrapping."""
|
||||||
key = open(path).read().strip()[len("vpn://"):]
|
key = open(path).read().strip()[len("vpn://"):]
|
||||||
key += "=" * (-len(key) % 4)
|
key += "=" * (-len(key) % 4)
|
||||||
j = json.loads(zlib.decompress(base64.urlsafe_b64decode(key)[4:]))
|
text = zlib.decompress(base64.urlsafe_b64decode(key)[4:]).decode("utf-8")
|
||||||
awg = j["containers"][0]["awg"]
|
if text.lstrip().startswith("["):
|
||||||
|
return conf_to_last_config(text), ""
|
||||||
|
j = json.loads(text)
|
||||||
|
cont = j["containers"][0]
|
||||||
|
if "awg" not in cont:
|
||||||
|
raise ValueError("это не AmneziaWG (контейнер %s) — пока поддерживается только AmneziaWG"
|
||||||
|
% cont.get("container"))
|
||||||
|
awg = cont["awg"]
|
||||||
c = awg["last_config"] if isinstance(awg["last_config"], dict) else json.loads(awg["last_config"])
|
c = awg["last_config"] if isinstance(awg["last_config"], dict) else json.loads(awg["last_config"])
|
||||||
|
return c, j.get("description") or ""
|
||||||
|
|
||||||
|
|
||||||
|
def conf_to_last_config(text):
|
||||||
|
"""An AmneziaWG .conf → the same field names the JSON key uses."""
|
||||||
|
p = configparser.ConfigParser()
|
||||||
|
p.optionxform = str
|
||||||
|
p.read_string(text)
|
||||||
|
i, peer = p["Interface"], p["Peer"]
|
||||||
|
host, port = peer["Endpoint"].rsplit(":", 1)
|
||||||
|
c = {k: v for k, v in i.items() if k not in ("Address", "PrivateKey", "DNS", "MTU")}
|
||||||
|
c.update({"hostName": host.strip("[]"), "port": port,
|
||||||
|
"client_ip": i["Address"].split(",")[0].split("/")[0].strip(),
|
||||||
|
"client_priv_key": i["PrivateKey"], "server_pub_key": peer["PublicKey"],
|
||||||
|
"psk_key": peer.get("PresharedKey", ""), "mtu": i.get("MTU", "1376"),
|
||||||
|
"persistent_keep_alive": peer.get("PersistentKeepalive", "25")})
|
||||||
|
return c
|
||||||
|
|
||||||
|
|
||||||
|
def amnezia(path, name):
|
||||||
|
c, _ = decode_key(path)
|
||||||
ver = 3 if c.get("HeaderProtectionKey") else 2
|
ver = 3 if c.get("HeaderProtectionKey") else 2
|
||||||
opt = {"version": ver, "jc": int(c["Jc"]), "jmin": int(c["Jmin"]), "jmax": int(c["Jmax"]),
|
opt = {"version": ver, "jc": int(c["Jc"]), "jmin": int(c["Jmin"]), "jmax": int(c["Jmax"]),
|
||||||
"s1": int(c["S1"]), "s2": int(c["S2"])}
|
"s1": int(c["S1"]), "s2": int(c["S2"])}
|
||||||
@@ -176,7 +207,12 @@ def main():
|
|||||||
with open(os.open(prov, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as f:
|
with open(os.open(prov, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as f:
|
||||||
f.write(y({"proxies": awg}) + "\n")
|
f.write(y({"proxies": awg}) + "\n")
|
||||||
clients = {n: c for n, c in CLIENTS.items() if os.path.exists(os.path.join(SRC, c[0]))}
|
clients = {n: c for n, c in CLIENTS.items() if os.path.exists(os.path.join(SRC, c[0]))}
|
||||||
proxies = [wg(n, f) for n, (f, _, _) in clients.items()]
|
# Client tunnels live in a provider file too: after a network change BroV re-creates
|
||||||
|
# them (netctl rebind) so their WireGuard sockets bind to the new address.
|
||||||
|
client_proxies = [wg(n, f) for n, (f, _, _) in clients.items()]
|
||||||
|
with open(os.open(os.path.join(KEYS, "clients.yaml"), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as f:
|
||||||
|
f.write(y({"proxies": client_proxies}) + "\n")
|
||||||
|
proxies = []
|
||||||
sub = open(os.path.join(SRC, "vless.sub")).read().strip()
|
sub = open(os.path.join(SRC, "vless.sub")).read().strip()
|
||||||
|
|
||||||
rules = ([] if "home" in clients else [f"IP-CIDR,{HOME_NET},DIRECT,no-resolve"]) + [
|
rules = ([] if "home" in clients else [f"IP-CIDR,{HOME_NET},DIRECT,no-resolve"]) + [
|
||||||
@@ -193,21 +229,23 @@ def main():
|
|||||||
# Fetch through the exit: the subscription host is unreachable directly from home
|
# Fetch through the exit: the subscription host is unreachable directly from home
|
||||||
# (the pull failed with EOF and the node list went stale).
|
# (the pull failed with EOF and the node list went stale).
|
||||||
"type": "http", "url": sub, "interval": 3600, "path": "./providers/vless.yaml", "proxy": "exit",
|
"type": "http", "url": sub, "interval": 3600, "path": "./providers/vless.yaml", "proxy": "exit",
|
||||||
"health-check": {"enable": True, "url": TEST_URL, "interval": 300}}
|
"health-check": {"enable": True, "url": TEST_URL, "interval": 300, "timeout": 8000}}
|
||||||
if hid["vless"]:
|
if hid["vless"]:
|
||||||
# Hidden nodes stay in the subscription, the core just skips them.
|
# Hidden nodes stay in the subscription, the core just skips them.
|
||||||
vless["exclude-filter"] = "^(?:" + "|".join(rx(n) for n in hid["vless"]) + ")$"
|
vless["exclude-filter"] = "^(?:" + "|".join(rx(n) for n in hid["vless"]) + ")$"
|
||||||
# Single VLESS links added in BroV: a provider of their own (only when there are any —
|
# Single VLESS links added in BroV: a provider of their own (only when there are any —
|
||||||
# mihomo refuses an empty provider file).
|
# mihomo refuses an empty provider file).
|
||||||
extra_prov = {}
|
extra_prov = {}
|
||||||
|
clients_prov = {"clients": {"type": "file", "path": "./keys/clients.yaml",
|
||||||
|
"health-check": {"enable": False, "url": TEST_URL}}} if clients else {}
|
||||||
vless_file = os.path.join(KEYS, "vless.txt")
|
vless_file = os.path.join(KEYS, "vless.txt")
|
||||||
if os.path.exists(vless_file) and any(l.strip().startswith("vless://") for l in open(vless_file)):
|
if os.path.exists(vless_file) and any(l.strip().startswith("vless://") for l in open(vless_file)):
|
||||||
extra_prov["vless-keys"] = {"type": "file", "path": "./keys/vless.txt",
|
extra_prov["vless-keys"] = {"type": "file", "path": "./keys/vless.txt",
|
||||||
"health-check": {"enable": True, "url": TEST_URL, "interval": 300}}
|
"health-check": {"enable": True, "url": TEST_URL, "interval": 300, "timeout": 8000}}
|
||||||
if hid["vless"]:
|
if hid["vless"]:
|
||||||
extra_prov["vless-keys"]["exclude-filter"] = vless["exclude-filter"]
|
extra_prov["vless-keys"]["exclude-filter"] = vless["exclude-filter"]
|
||||||
awg_prov = {"type": "file", "path": "./keys/amnezia.yaml",
|
awg_prov = {"type": "file", "path": "./keys/amnezia.yaml",
|
||||||
"health-check": {"enable": True, "url": TEST_URL, "interval": 300}}
|
"health-check": {"enable": True, "url": TEST_URL, "interval": 300, "timeout": 8000}}
|
||||||
|
|
||||||
cfg = {
|
cfg = {
|
||||||
"mixed-port": 7890, "allow-lan": False, "mode": "rule", "log-level": "error", "ipv6": False,
|
"mixed-port": 7890, "allow-lan": False, "mode": "rule", "log-level": "error", "ipv6": False,
|
||||||
@@ -223,30 +261,31 @@ def main():
|
|||||||
"nameserver": ["https://1.1.1.1/dns-query#exit", "https://8.8.8.8/dns-query#exit"],
|
"nameserver": ["https://1.1.1.1/dns-query#exit", "https://8.8.8.8/dns-query#exit"],
|
||||||
"direct-nameserver": ["77.88.8.8", "77.88.8.1"]},
|
"direct-nameserver": ["77.88.8.8", "77.88.8.1"]},
|
||||||
"proxies": proxies,
|
"proxies": proxies,
|
||||||
"proxy-providers": {"amnezia-keys": awg_prov, "vless-cluster": vless, **extra_prov},
|
"proxy-providers": {"amnezia-keys": awg_prov, "vless-cluster": vless, **extra_prov, **clients_prov},
|
||||||
"proxy-groups": [
|
"proxy-groups": [
|
||||||
# What traffic actually uses: the exit picked in BroV while it answers, "auto"
|
# What traffic actually uses: the exit picked in BroV while it answers, "auto"
|
||||||
# when it doesn't (a pinned connection that dies no longer takes the Mac offline).
|
# when it doesn't (a pinned connection that dies no longer takes the Mac offline).
|
||||||
# Back to the pick as soon as it answers again. Checked every 30 s and right after
|
# Back to the pick as soon as it answers again. Checked every 30 s and right after
|
||||||
# 3 failed connections.
|
# 3 failed connections.
|
||||||
{"name": "exit", "type": "fallback", "proxies": ["ai-out", "auto"],
|
{"name": "exit", "type": "fallback", "proxies": ["ai-out", "auto"],
|
||||||
"url": TEST_URL, "interval": 30, "timeout": 4000, "max-failed-times": 3, "lazy": False},
|
"url": TEST_URL, "interval": 30, "timeout": 8000, "max-failed-times": 3, "lazy": False},
|
||||||
# What BroV's globe panel switches: "auto", the Amnezia group, or one VLESS node.
|
# What BroV's globe panel switches: "auto", the Amnezia group, or one VLESS node.
|
||||||
{"name": "ai-out", "type": "select", "proxies": ["auto", "amnezia"], "use": ["vless-cluster", *extra_prov]},
|
{"name": "ai-out", "type": "select", "proxies": ["auto", "amnezia"], "use": ["vless-cluster", *extra_prov]},
|
||||||
# Fastest alive exit among every Amnezia connection and every VLESS node;
|
# Fastest alive exit among every Amnezia connection and every VLESS node;
|
||||||
# switches only when another one is 100+ ms faster.
|
# switches only when another one is 100+ ms faster.
|
||||||
{"name": "auto", "type": "url-test", "use": ["amnezia-keys", "vless-cluster", *extra_prov],
|
{"name": "auto", "type": "url-test", "use": ["amnezia-keys", "vless-cluster", *extra_prov],
|
||||||
"url": TEST_URL, "interval": 60, "timeout": 4000, "max-failed-times": 3,
|
"url": TEST_URL, "interval": 60, "timeout": 8000, "max-failed-times": 3,
|
||||||
"tolerance": 100, "lazy": False},
|
"tolerance": 100, "lazy": False},
|
||||||
# Amnezia: "amnezia-auto" (fastest connection) or one fixed connection.
|
# Amnezia: "amnezia-auto" (fastest connection) or one fixed connection.
|
||||||
{"name": "amnezia", "type": "select", "proxies": ["amnezia-auto"], "use": ["amnezia-keys"]},
|
{"name": "amnezia", "type": "select", "proxies": ["amnezia-auto"], "use": ["amnezia-keys"]},
|
||||||
{"name": "amnezia-auto", "type": "url-test", "use": ["amnezia-keys"],
|
{"name": "amnezia-auto", "type": "url-test", "use": ["amnezia-keys"],
|
||||||
"url": TEST_URL, "interval": 60, "timeout": 4000, "max-failed-times": 3,
|
"url": TEST_URL, "interval": 60, "timeout": 8000, "max-failed-times": 3,
|
||||||
"tolerance": 100, "lazy": False},
|
"tolerance": 100, "lazy": False},
|
||||||
] + [
|
] + [
|
||||||
# Client networks: off (REJECT) until switched on in BroV.
|
# Client networks: off (REJECT) until switched on in BroV.
|
||||||
# Client networks: first option = "off" (REJECT, or DIRECT for home).
|
# Client networks: first option = "off" (REJECT, or DIRECT for home).
|
||||||
{"name": f"{n}-sw", "type": "select", "proxies": [off, n]} for n, (_, _, off) in clients.items()
|
{"name": f"{n}-sw", "type": "select", "proxies": [off], "use": ["clients"], "filter": f"^{n}$"}
|
||||||
|
for n, (_, _, off) in clients.items()
|
||||||
],
|
],
|
||||||
"rules": rules,
|
"rules": rules,
|
||||||
}
|
}
|
||||||
@@ -263,14 +302,9 @@ def check(path):
|
|||||||
raw = open(path).read().strip()
|
raw = open(path).read().strip()
|
||||||
if not raw.startswith("vpn://"):
|
if not raw.startswith("vpn://"):
|
||||||
raise ValueError("ключ должен начинаться с vpn://")
|
raise ValueError("ключ должен начинаться с vpn://")
|
||||||
key = raw[len("vpn://"):]
|
_, description = decode_key(path)
|
||||||
key += "=" * (-len(key) % 4)
|
|
||||||
j = json.loads(zlib.decompress(base64.urlsafe_b64decode(key)[4:]))
|
|
||||||
cont = j["containers"][0]
|
|
||||||
if "awg" not in cont:
|
|
||||||
raise ValueError("это не AmneziaWG (контейнер %s) — пока поддерживается только AmneziaWG" % cont.get("container"))
|
|
||||||
p = amnezia(path, "check")
|
p = amnezia(path, "check")
|
||||||
print(json.dumps({"ok": True, "name": j.get("description") or p["server"], "server": p["server"],
|
print(json.dumps({"ok": True, "name": description or p["server"], "server": p["server"],
|
||||||
"port": p["port"], "version": p["amnezia-wg-option"]["version"]}, ensure_ascii=False))
|
"port": p["port"], "version": p["amnezia-wg-option"]["version"]}, ensure_ascii=False))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(json.dumps({"ok": False, "error": str(e) or e.__class__.__name__}, ensure_ascii=False))
|
print(json.dumps({"ok": False, "error": str(e) or e.__class__.__name__}, ensure_ascii=False))
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ allows exactly these operations:
|
|||||||
tun {on} traffic capture on (fresh core start) / off; remembered
|
tun {on} traffic capture on (fresh core start) / off; remembered
|
||||||
add_key {text} vpn:// Amnezia key (checked by gen.py) or a vless:// link: stored, core updated
|
add_key {text} vpn:// Amnezia key (checked by gen.py) or a vless:// link: stored, core updated
|
||||||
refresh {} re-download the VLESS subscription now (new cluster nodes), no reload
|
refresh {} re-download the VLESS subscription now (new cluster nodes), no reload
|
||||||
|
rebind {} the Mac moved to another network: clean core restart (WireGuard
|
||||||
|
tunnels bind to the new address, nothing leaks)
|
||||||
hide {name} take an Amnezia connection or a VLESS node out of the list and
|
hide {name} take an Amnezia connection or a VLESS node out of the list and
|
||||||
out of "auto" (the key / subscription stay, nothing is deleted)
|
out of "auto" (the key / subscription stay, nothing is deleted)
|
||||||
unhide {name} put it back
|
unhide {name} put it back
|
||||||
@@ -84,7 +86,7 @@ def cmd_state(_):
|
|||||||
for name, p in proxies.items():
|
for name, p in proxies.items():
|
||||||
keep[name] = {"now": p.get("now"), "all": p.get("all"), "history": (p.get("history") or [])[-1:]}
|
keep[name] = {"now": p.get("now"), "all": p.get("all"), "history": (p.get("history") or [])[-1:]}
|
||||||
providers = {}
|
providers = {}
|
||||||
for prov in ("vless-cluster", "vless-keys", "amnezia-keys"):
|
for prov in ("vless-cluster", "vless-keys", "amnezia-keys", "clients"):
|
||||||
try:
|
try:
|
||||||
lst = api("GET", "/providers/proxies/" + prov).get("proxies", [])
|
lst = api("GET", "/providers/proxies/" + prov).get("proxies", [])
|
||||||
except Exception:
|
except Exception:
|
||||||
@@ -106,12 +108,13 @@ def cmd_select(r):
|
|||||||
|
|
||||||
|
|
||||||
def cmd_delay(r):
|
def cmd_delay(r):
|
||||||
test = "url=" + q(TEST_URL) + "&timeout=5000"
|
test = "url=" + q(TEST_URL) + "&timeout=8000" # AmneziaWG 3 handshakes after idle can take 5+ s
|
||||||
if r.get("group") in DELAY_GROUPS:
|
if r.get("group") in DELAY_GROUPS:
|
||||||
return {"ok": True, "delays": api("GET", "/group/%s/delay?%s" % (q(r["group"]), test), timeout=10)}
|
return {"ok": True, "delays": api("GET", "/group/%s/delay?%s" % (q(r["group"]), test), timeout=15)}
|
||||||
if r.get("proxy") in CLIENT_TUNNELS:
|
if r.get("proxy") in CLIENT_TUNNELS:
|
||||||
try:
|
try:
|
||||||
d = api("GET", "/proxies/%s/delay?%s" % (q(r["proxy"]), test), timeout=10).get("delay", 0)
|
d = api("GET", "/providers/proxies/clients/%s/healthcheck?%s" % (q(r["proxy"]), test),
|
||||||
|
timeout=15).get("delay", 0)
|
||||||
except Exception:
|
except Exception:
|
||||||
d = 0
|
d = 0
|
||||||
return {"ok": True, "delays": {r["proxy"]: d}}
|
return {"ok": True, "delays": {r["proxy"]: d}}
|
||||||
@@ -135,6 +138,22 @@ def network_services():
|
|||||||
return [l for l in out[1:] if l and not l.startswith("*")]
|
return [l for l in out[1:] if l and not l.startswith("*")]
|
||||||
|
|
||||||
|
|
||||||
|
def active_services():
|
||||||
|
"""Hardware services that carry traffic right now: Wi-Fi or a wired adapter (en*) with
|
||||||
|
status active. Touching the others — «iPhone USB», Thunderbolt Bridge, VPN services —
|
||||||
|
made macOS re-check them and offer the iPhone's hotspot over and over."""
|
||||||
|
order = subprocess.run(["/usr/sbin/networksetup", "-listnetworkserviceorder"],
|
||||||
|
capture_output=True, text=True, timeout=10).stdout
|
||||||
|
out = []
|
||||||
|
for name, port, dev in re.findall(r"\(\d+\) (.+)\n\(Hardware Port: ([^,]*), Device: ([^)]*)\)", order):
|
||||||
|
if not re.fullmatch(r"en\d+", dev) or "iphone" in (name + port).lower():
|
||||||
|
continue
|
||||||
|
status = subprocess.run(["/sbin/ifconfig", dev], capture_output=True, text=True, timeout=5).stdout
|
||||||
|
if "status: active" in status:
|
||||||
|
out.append(name.strip())
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
def dns_of(service):
|
def dns_of(service):
|
||||||
out = subprocess.run(["/usr/sbin/networksetup", "-getdnsservers", service],
|
out = subprocess.run(["/usr/sbin/networksetup", "-getdnsservers", service],
|
||||||
capture_output=True, text=True, timeout=10).stdout.splitlines()
|
capture_output=True, text=True, timeout=10).stdout.splitlines()
|
||||||
@@ -153,11 +172,15 @@ def dns_to_core():
|
|||||||
backup = json.load(f)
|
backup = json.load(f)
|
||||||
except (OSError, ValueError):
|
except (OSError, ValueError):
|
||||||
backup = {}
|
backup = {}
|
||||||
|
active = set(active_services())
|
||||||
for svc in network_services():
|
for svc in network_services():
|
||||||
cur = dns_of(svc)
|
cur = dns_of(svc)
|
||||||
|
if svc in active:
|
||||||
if cur != [CORE_DNS]:
|
if cur != [CORE_DNS]:
|
||||||
backup[svc] = cur
|
backup[svc] = cur
|
||||||
set_dns(svc, [CORE_DNS])
|
set_dns(svc, [CORE_DNS])
|
||||||
|
elif cur == [CORE_DNS]: # set by an older version: give it back
|
||||||
|
set_dns(svc, [x for x in backup.pop(svc, []) if x != CORE_DNS])
|
||||||
fd = os.open(DNS_BACKUP, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
|
fd = os.open(DNS_BACKUP, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
|
||||||
with os.fdopen(fd, "w") as f:
|
with os.fdopen(fd, "w") as f:
|
||||||
json.dump(backup, f)
|
json.dump(backup, f)
|
||||||
@@ -395,6 +418,30 @@ def cmd_refresh(_):
|
|||||||
"removed": sorted(before - set(after))}
|
"removed": sorted(before - set(after))}
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_rebind(_):
|
||||||
|
"""After the Mac moved to another network (its address changed): a clean core restart.
|
||||||
|
mihomo's WireGuard outbounds stay bound to the old address; re-creating them through a
|
||||||
|
provider reload leaked every old tunnel (16.10: 652 UDP sockets, 677 MB, the Amnezia
|
||||||
|
servers stopped answering the handshake flood). A restart leaves nothing behind, and
|
||||||
|
the move has dropped the open TCP connections anyway. TUN comes back as tun.json says;
|
||||||
|
the DNS follows the newly active adapter."""
|
||||||
|
subprocess.run(["/bin/launchctl", "kickstart", "-k", "system/" + CORE_LABEL], capture_output=True, timeout=20)
|
||||||
|
for _ in range(40):
|
||||||
|
time.sleep(0.25)
|
||||||
|
try:
|
||||||
|
api("GET", "/configs", timeout=2)
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
with open(os.path.join(CORE, "tun.json")) as f:
|
||||||
|
if json.load(f).get("on", True):
|
||||||
|
dns_to_core()
|
||||||
|
except (OSError, ValueError):
|
||||||
|
pass
|
||||||
|
return {"ok": True, "restarted": True}
|
||||||
|
|
||||||
|
|
||||||
def cmd_hide(r):
|
def cmd_hide(r):
|
||||||
return change_hidden(r.get("name"), True)
|
return change_hidden(r.get("name"), True)
|
||||||
|
|
||||||
@@ -405,7 +452,7 @@ def cmd_unhide(r):
|
|||||||
|
|
||||||
COMMANDS = {"state": cmd_state, "select": cmd_select, "delay": cmd_delay, "tun": cmd_tun,
|
COMMANDS = {"state": cmd_state, "select": cmd_select, "delay": cmd_delay, "tun": cmd_tun,
|
||||||
"add_key": cmd_add_key, "hide": cmd_hide, "unhide": cmd_unhide,
|
"add_key": cmd_add_key, "hide": cmd_hide, "unhide": cmd_unhide,
|
||||||
"refresh": cmd_refresh}
|
"refresh": cmd_refresh, "rebind": cmd_rebind}
|
||||||
|
|
||||||
|
|
||||||
# MARK: - Socket server
|
# MARK: - Socket server
|
||||||
|
|||||||
Executable
+8
@@ -0,0 +1,8 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
TEST_DIR="$(mktemp -d "${TMPDIR:-/tmp}/coucou-approval-queue.XXXXXX")"
|
||||||
|
trap 'rm -rf "$TEST_DIR"' EXIT
|
||||||
|
swiftc NotchBuddy/Sources/App/ApprovalQueue.swift \
|
||||||
|
tests/ApprovalQueueTests.swift -o "$TEST_DIR/approval-queue-tests"
|
||||||
|
"$TEST_DIR/approval-queue-tests"
|
||||||
Executable
+8
@@ -0,0 +1,8 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
TEST_DIR="$(mktemp -d "${TMPDIR:-/tmp}/coucou-session-registry.XXXXXX")"
|
||||||
|
trap 'rm -rf "$TEST_DIR"' EXIT
|
||||||
|
swiftc NotchBuddy/Sources/App/PillSessionRegistry.swift \
|
||||||
|
tests/PillSessionRegistryTests.swift -o "$TEST_DIR/session-registry-tests"
|
||||||
|
"$TEST_DIR/session-registry-tests"
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
@main
|
||||||
|
enum ApprovalQueueTests {
|
||||||
|
static func entry(_ n: Int, session: String = "s1", pill: String = "integration_claude",
|
||||||
|
tool: String = "Bash", key: String = "{}") -> QueuedApproval {
|
||||||
|
QueuedApproval(id: UUID(), fd: Int32(n), sessionId: session, pillId: pill,
|
||||||
|
projectName: "p", cwd: "/", tool: tool, command: "cmd\(n)", inputKey: key)
|
||||||
|
}
|
||||||
|
|
||||||
|
static func main() {
|
||||||
|
// FIFO: head is the oldest, removal of the head promotes the next
|
||||||
|
var q = ApprovalQueue()
|
||||||
|
let a = entry(1), b = entry(2), c = entry(3)
|
||||||
|
for e in [a, b, c] { precondition(q.enqueue(e) == .accepted) }
|
||||||
|
precondition(q.count == 3 && q.head == a)
|
||||||
|
precondition(q.position(of: a.id) == 1 && q.position(of: c.id) == 3)
|
||||||
|
precondition(q.remove(id: a.id) == a)
|
||||||
|
precondition(q.head == b && q.count == 2)
|
||||||
|
|
||||||
|
// Removal on disconnect / timeout of a non-head entry leaves the others untouched
|
||||||
|
precondition(q.remove(id: c.id) == c)
|
||||||
|
precondition(q.head == b && q.count == 1)
|
||||||
|
precondition(q.remove(id: c.id) == nil) // already gone: no-op
|
||||||
|
precondition(q.remove(id: b.id) == b && q.isEmpty && q.head == nil)
|
||||||
|
|
||||||
|
// Cap: the newest is rejected, queue unchanged
|
||||||
|
var full = ApprovalQueue()
|
||||||
|
let all = (1...ApprovalQueue.maxPending).map { entry($0) }
|
||||||
|
for e in all { precondition(full.enqueue(e) == .accepted) }
|
||||||
|
precondition(full.enqueue(entry(99)) == .rejectedFull)
|
||||||
|
precondition(full.entries == all)
|
||||||
|
// Room again after a removal
|
||||||
|
_ = full.remove(id: all[0].id)
|
||||||
|
precondition(full.enqueue(entry(97), maxPending: ApprovalQueue.maxPending) == .accepted)
|
||||||
|
|
||||||
|
// Event matching is per request: session + agent, never the pill alone
|
||||||
|
var m = ApprovalQueue()
|
||||||
|
let s1 = entry(1, session: "s1", tool: "Bash", key: "{\"command\":\"ls\"}")
|
||||||
|
let s2 = entry(2, session: "s2", tool: "Bash", key: "{\"command\":\"ls\"}")
|
||||||
|
let cur = entry(3, session: "s1", pill: "agent_cursor", tool: "Bash", key: "{\"command\":\"ls\"}")
|
||||||
|
for e in [s1, s2, cur] { _ = m.enqueue(e) }
|
||||||
|
let pt = m.resolved(byEvent: "PostToolUse", sessionId: "s1", pillId: "integration_claude",
|
||||||
|
tool: "Bash", inputKey: "{\"command\":\"ls\"}")
|
||||||
|
precondition(pt == [s1])
|
||||||
|
precondition(m.resolved(byEvent: "PostToolUse", sessionId: "s1", pillId: "integration_claude",
|
||||||
|
tool: "Bash", inputKey: "{\"command\":\"pwd\"}").isEmpty)
|
||||||
|
precondition(m.resolved(byEvent: "PostToolUse", sessionId: "s1", pillId: "integration_claude",
|
||||||
|
tool: "Read", inputKey: "{\"command\":\"ls\"}").isEmpty)
|
||||||
|
precondition(m.resolved(byEvent: "Stop", sessionId: "s2", pillId: "integration_claude",
|
||||||
|
tool: "", inputKey: "") == [s2])
|
||||||
|
precondition(m.resolved(byEvent: "Stop", sessionId: "s1", pillId: "agent_cursor",
|
||||||
|
tool: "", inputKey: "") == [cur])
|
||||||
|
precondition(m.resolved(byEvent: "Stop", sessionId: "other", pillId: "integration_claude",
|
||||||
|
tool: "", inputKey: "").isEmpty)
|
||||||
|
precondition(m.resolved(byEvent: "PreToolUse", sessionId: "s1", pillId: "integration_claude",
|
||||||
|
tool: "Bash", inputKey: "{\"command\":\"ls\"}").isEmpty)
|
||||||
|
|
||||||
|
// Mixed sources and per-pill lookup
|
||||||
|
precondition(m.hasMixedSources)
|
||||||
|
precondition(m.hasEntries(forPill: "agent_cursor") && !m.hasEntries(forPill: "agent_codex"))
|
||||||
|
var same = ApprovalQueue()
|
||||||
|
_ = same.enqueue(entry(1)); _ = same.enqueue(entry(2, tool: "Edit"))
|
||||||
|
precondition(!same.hasMixedSources)
|
||||||
|
|
||||||
|
print("pass")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,207 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
@main
|
||||||
|
enum PillSessionRegistryTests {
|
||||||
|
|
||||||
|
static var failures = 0
|
||||||
|
|
||||||
|
static func check(_ label: String, _ got: Bool) {
|
||||||
|
if got { print(" ✓ \(label)") }
|
||||||
|
else { print(" ✗ \(label)"); failures += 1 }
|
||||||
|
}
|
||||||
|
|
||||||
|
static let claude = "integration_claude"
|
||||||
|
|
||||||
|
static func display(_ session: String, _ project: String, _ cwd: String = "")
|
||||||
|
-> PillSessionRegistry.Display {
|
||||||
|
PillSessionRegistry.Display(session: session, projectName: project, cwd: cwd)
|
||||||
|
}
|
||||||
|
|
||||||
|
static func main() {
|
||||||
|
|
||||||
|
// ── one session alone: the pill follows it all the way ──────────────────
|
||||||
|
print("\nSingle session")
|
||||||
|
do {
|
||||||
|
var reg = PillSessionRegistry()
|
||||||
|
reg.note(pill: claude, display: display("a", "coucou", "/tmp/coucou"), working: false)
|
||||||
|
check("one live session", reg.liveCount(pill: claude) == 1)
|
||||||
|
check("not working after SessionStart", reg.workingCount(pill: claude) == 0)
|
||||||
|
|
||||||
|
reg.note(pill: claude, display: display("a", "coucou", "/tmp/coucou"), working: true)
|
||||||
|
check("working after a tool call", reg.workingCount(pill: claude) == 1)
|
||||||
|
|
||||||
|
check("Stop reaches the pill", reg.endTurn(pill: claude, session: "a") == .pill)
|
||||||
|
check("still live between turns", reg.liveCount(pill: claude) == 1)
|
||||||
|
check("SessionEnd reaches the pill",
|
||||||
|
reg.endSession(pill: claude, session: "a") == .pill)
|
||||||
|
check("pill is empty", reg.liveCount(pill: claude) == 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── two sessions on one pill: this is the defect ────────────────────────
|
||||||
|
// Negative cases: an implementation that always answers .pill fails here.
|
||||||
|
print("\nTwo sessions behind one pill")
|
||||||
|
do {
|
||||||
|
var reg = PillSessionRegistry()
|
||||||
|
reg.note(pill: claude, display: display("a", "coucou", "/a"), working: true)
|
||||||
|
reg.note(pill: claude, display: display("b", "lokil", "/b"), working: true)
|
||||||
|
check("both live", reg.liveCount(pill: claude) == 2)
|
||||||
|
check("both working", reg.workingCount(pill: claude) == 2)
|
||||||
|
|
||||||
|
check("A's Stop must not touch the pill while B works",
|
||||||
|
reg.endTurn(pill: claude, session: "a") == .sessionOnly)
|
||||||
|
check("B still working", reg.workingCount(pill: claude) == 1)
|
||||||
|
check("A's SessionEnd must not remove the card",
|
||||||
|
reg.endSession(pill: claude, session: "a") == .sessionOnly)
|
||||||
|
check("B alone now", reg.liveCount(pill: claude) == 1)
|
||||||
|
|
||||||
|
check("B's Stop reaches the pill", reg.endTurn(pill: claude, session: "b") == .pill)
|
||||||
|
check("B's SessionEnd reaches the pill",
|
||||||
|
reg.endSession(pill: claude, session: "b") == .pill)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── a resting sibling does not hold the pill back ───────────────────────
|
||||||
|
print("\nResting sibling")
|
||||||
|
do {
|
||||||
|
var reg = PillSessionRegistry()
|
||||||
|
reg.note(pill: claude, display: display("a", "coucou"), working: true)
|
||||||
|
reg.note(pill: claude, display: display("b", "lokil"), working: true)
|
||||||
|
_ = reg.endTurn(pill: claude, session: "b")
|
||||||
|
check("A's Stop reaches the pill once B rests",
|
||||||
|
reg.endTurn(pill: claude, session: "a") == .pill)
|
||||||
|
check("A's SessionEnd still spares B's card",
|
||||||
|
reg.endSession(pill: claude, session: "a") == .sessionOnly)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── name and cwd: owned by one session, handed over when it leaves ──────
|
||||||
|
print("\nDisplay ownership")
|
||||||
|
do {
|
||||||
|
var reg = PillSessionRegistry()
|
||||||
|
reg.note(pill: claude, display: display("a", "coucou", "/a"), working: true)
|
||||||
|
reg.note(pill: claude, display: display("b", "lokil", "/b"), working: true)
|
||||||
|
check("oldest session owns the name", reg.displayOwner(of: claude)?.session == "a")
|
||||||
|
check("name is A's", reg.displayOwner(of: claude)?.projectName == "coucou")
|
||||||
|
check("A may write the card", reg.ownsDisplay(pill: claude, session: "a"))
|
||||||
|
check("B may not rename the card under A",
|
||||||
|
!reg.ownsDisplay(pill: claude, session: "b"))
|
||||||
|
|
||||||
|
// B keeps working; the name must not flip.
|
||||||
|
reg.note(pill: claude, display: display("b", "lokil", "/b"), working: true)
|
||||||
|
check("name still A's after more B events",
|
||||||
|
reg.displayOwner(of: claude)?.projectName == "coucou")
|
||||||
|
|
||||||
|
_ = reg.endSession(pill: claude, session: "a")
|
||||||
|
check("B inherits the display", reg.displayOwner(of: claude)?.session == "b")
|
||||||
|
check("name is now B's", reg.displayOwner(of: claude)?.projectName == "lokil")
|
||||||
|
check("cwd is now B's", reg.displayOwner(of: claude)?.cwd == "/b")
|
||||||
|
check("B may write the card now", reg.ownsDisplay(pill: claude, session: "b"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── empty cwd must not erase a known one ────────────────────────────────
|
||||||
|
print("\nPartial payloads")
|
||||||
|
do {
|
||||||
|
var reg = PillSessionRegistry()
|
||||||
|
reg.note(pill: claude, display: display("a", "coucou", "/a"), working: true)
|
||||||
|
reg.note(pill: claude, display: display("a", "coucou", ""), working: false)
|
||||||
|
check("cwd kept when the event carries none",
|
||||||
|
reg.displayOwner(of: claude)?.cwd == "/a")
|
||||||
|
check("working flag is sticky inside a turn", reg.workingCount(pill: claude) == 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── pills are independent ──────────────────────────────────────────────
|
||||||
|
print("\nSeparate pills")
|
||||||
|
do {
|
||||||
|
var reg = PillSessionRegistry()
|
||||||
|
reg.note(pill: claude, display: display("a", "coucou"), working: true)
|
||||||
|
reg.note(pill: "agent_cursor", display: display("b", "lokil"), working: true)
|
||||||
|
check("Cursor's Stop reaches its own pill",
|
||||||
|
reg.endTurn(pill: "agent_cursor", session: "b") == .pill)
|
||||||
|
check("Claude untouched", reg.workingCount(pill: claude) == 1)
|
||||||
|
check("an unknown pill is empty", reg.liveCount(pill: "agent_codex") == 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── sessions we never saw start ─────────────────────────────────────────
|
||||||
|
print("\nUntracked sessions")
|
||||||
|
do {
|
||||||
|
var reg = PillSessionRegistry()
|
||||||
|
check("a Stop from nowhere reaches the pill",
|
||||||
|
reg.endTurn(pill: claude, session: "ghost") == .pill)
|
||||||
|
check("it owns nothing", reg.liveCount(pill: claude) == 0)
|
||||||
|
check("a SessionEnd from nowhere reaches the pill",
|
||||||
|
reg.endSession(pill: claude, session: "ghost") == .pill)
|
||||||
|
|
||||||
|
reg.note(pill: claude, display: display("a", "coucou"), working: true)
|
||||||
|
check("a Stop from nowhere spares a working session",
|
||||||
|
reg.endTurn(pill: claude, session: "ghost") == .sessionOnly)
|
||||||
|
check("a SessionEnd from nowhere spares a live session",
|
||||||
|
reg.endSession(pill: claude, session: "ghost") == .sessionOnly)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── a Stop that never arrives must not hold the other session back ─────
|
||||||
|
print("\nTurn silence")
|
||||||
|
do {
|
||||||
|
var reg = PillSessionRegistry()
|
||||||
|
let start = Date(timeIntervalSince1970: 1_000_000)
|
||||||
|
reg.note(pill: claude, display: display("a", "coucou"), working: true, now: start)
|
||||||
|
reg.note(pill: claude, display: display("b", "lokil"), working: true, now: start)
|
||||||
|
|
||||||
|
let soon = start.addingTimeInterval(PillSessionRegistry.maxTurnSilence - 60)
|
||||||
|
reg.note(pill: claude, display: display("b", "lokil"), working: true, now: soon)
|
||||||
|
check("A still working just under the limit",
|
||||||
|
reg.endTurn(pill: claude, session: "b", now: soon) == .sessionOnly)
|
||||||
|
|
||||||
|
let late = start.addingTimeInterval(PillSessionRegistry.maxTurnSilence + 60)
|
||||||
|
reg.note(pill: claude, display: display("b", "lokil"), working: true, now: late)
|
||||||
|
check("silent A no longer counts as working",
|
||||||
|
reg.workingCount(pill: claude) == 1)
|
||||||
|
check("B's Stop reaches the pill again",
|
||||||
|
reg.endTurn(pill: claude, session: "b", now: late) == .pill)
|
||||||
|
check("A is still live", reg.liveCount(pill: claude) == 2)
|
||||||
|
check("A still owns the display", reg.displayOwner(of: claude)?.session == "a")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── a SessionEnd that never arrives must not pin the card forever ──────
|
||||||
|
print("\nSilence sweep")
|
||||||
|
do {
|
||||||
|
var reg = PillSessionRegistry()
|
||||||
|
let start = Date(timeIntervalSince1970: 1_000_000)
|
||||||
|
reg.note(pill: claude, display: display("a", "coucou"), working: true, now: start)
|
||||||
|
reg.note(pill: claude, display: display("b", "lokil"), working: true, now: start)
|
||||||
|
|
||||||
|
let later = start.addingTimeInterval(PillSessionRegistry.maxSilence + 60)
|
||||||
|
reg.note(pill: claude, display: display("b", "lokil"), working: true, now: later)
|
||||||
|
check("silent A swept", reg.liveCount(pill: claude) == 1)
|
||||||
|
check("B owns the display", reg.displayOwner(of: claude)?.session == "b")
|
||||||
|
check("B's SessionEnd clears the pill",
|
||||||
|
reg.endSession(pill: claude, session: "b", now: later) == .pill)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── the terminal ("Open terminal") follows the display owner ────────────
|
||||||
|
print("\nTerminal of the owner")
|
||||||
|
do {
|
||||||
|
var reg = PillSessionRegistry()
|
||||||
|
reg.note(pill: claude,
|
||||||
|
display: PillSessionRegistry.Display(session: "a", projectName: "coucou",
|
||||||
|
cwd: "/tmp/coucou",
|
||||||
|
hostApp: "com.googlecode.iterm2"),
|
||||||
|
working: true)
|
||||||
|
reg.note(pill: claude,
|
||||||
|
display: PillSessionRegistry.Display(session: "b", projectName: "lokil",
|
||||||
|
cwd: "/tmp/lokil",
|
||||||
|
hostApp: "com.apple.Terminal"),
|
||||||
|
working: true)
|
||||||
|
check("A's terminal shown", reg.displayOwner(of: claude)?.hostApp == "com.googlecode.iterm2")
|
||||||
|
_ = reg.endSession(pill: claude, session: "a")
|
||||||
|
check("B's terminal once A ends", reg.displayOwner(of: claude)?.hostApp == "com.apple.Terminal")
|
||||||
|
check("B's folder once A ends", reg.displayOwner(of: claude)?.cwd == "/tmp/lokil")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── finish ─────────────────────────────────────────────────────────────
|
||||||
|
if failures == 0 {
|
||||||
|
print("\nAll tests passed.")
|
||||||
|
exit(0)
|
||||||
|
} else {
|
||||||
|
print("\n\(failures) test(s) failed.")
|
||||||
|
exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user