From 23b1ea4f45e735fd39c39b9bec21f549c398b224 Mon Sep 17 00:00:00 2001 From: maksarsanjeev Date: Sat, 10 Oct 2026 02:49:03 +0300 Subject: [PATCH] =?UTF-8?q?Memoji=20menu=20and=20=C2=AB=D0=94=D0=B5=D0=BB?= =?UTF-8?q?=D0=B0=C2=BB=20panel=20for=20BroV=20Ops?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A click on the Memoji (not a drag) opens a menu: Дела (agenda counts), stop timer, пипетка, переводчик, кофе. The slap on click is gone; hover love and drag-to-window stay. - «Дела»: overdue / today / this week from the homelab service with Done/Paid, timer and Tomorrow buttons, the running timer, and a text box that goes to the service's Claude. - Settings → Чат → «Дела (хоумлаб)»: service URL and API token (Keychain). - CLAUDE.md: the BroV Ops section. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 6 + NotchBuddy/Sources/App/AppState.swift | 2 + NotchBuddy/Sources/App/IslandRootView.swift | 14 + .../Sources/App/IslandWindowController.swift | 15 +- NotchBuddy/Sources/App/Ops.swift | 373 ++++++++++++++++++ NotchBuddy/Sources/App/SettingsView.swift | 4 +- 6 files changed, 410 insertions(+), 4 deletions(-) create mode 100644 NotchBuddy/Sources/App/Ops.swift diff --git a/CLAUDE.md b/CLAUDE.md index 330b8ab..d46faec 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -33,3 +33,9 @@ DerivedData must stay outside ~/Documents (iCloud adds Finder attributes and cod - `scripts/netcore/gen.py` builds the config (Amnezia keys → provider `keys/amnezia.yaml`, 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. +## BroV Ops (homelab manager, `ops/`) +- Separate service on the homelab Ubuntu VM (Hyper-V): tasks with subtasks + timer, subscriptions + payments, routines. Python, SQLite, systemd (`brov-ops`), user `brovops`. Tests: `python3 -m unittest discover -s ops/tests`. +- Free text → `claude -p` (Haiku, the user's subscription, logged in on the VM) → JSON actions; only the whitelist in `brain.ALLOWED` is applied, nothing is deleted. Voice from Telegram → faster-whisper on the VM first (Claude doesn't take audio). +- Telegram and Claude are blocked from Russia: the service goes through its own proxy-only mihomo (`brov-ops-proxy`, 127.0.0.1:7890, VLESS subscription in /etc/brov-ops/proxy/vless.sub). No system-wide VPN on the VM. +- Secrets (bot token, API token, subscription) only in /etc/brov-ops on the VM; BroV keeps the API token in the Keychain (`brov-ops-token`), URL in UserDefaults `opsURL`. +- BroV side: `Ops.swift` — click on the Memoji opens the menu (Дела, timer, пипетка, переводчик, кофе); settings in Settings → Чат → «Дела (хоумлаб)». The ops service is independent of BroV and of the VPN core: restarting either doesn't touch the others. diff --git a/NotchBuddy/Sources/App/AppState.swift b/NotchBuddy/Sources/App/AppState.swift index 2a75881..8465624 100644 --- a/NotchBuddy/Sources/App/AppState.swift +++ b/NotchBuddy/Sources/App/AppState.swift @@ -259,6 +259,8 @@ final class AppState: ObservableObject { // Context for prompt (window attach / file) @Published var promptContext: PromptContext? = nil + /// Click on the Memoji: the functions menu (Дела, пипетка, переводчик, кофе). + @Published var botMenuOpen = false /// The chat is open in the notch: a dropped file attaches to it instead of the shelf. var chatOnScreen: Bool { view == .prompt && mode == .expanded } diff --git a/NotchBuddy/Sources/App/IslandRootView.swift b/NotchBuddy/Sources/App/IslandRootView.swift index 764db18..e4e2c27 100644 --- a/NotchBuddy/Sources/App/IslandRootView.swift +++ b/NotchBuddy/Sources/App/IslandRootView.swift @@ -101,6 +101,20 @@ struct IslandContainer: View { .opacity(uploadActive || greetingActive || (state.mode == .expanded && state.view == .terminal) ? 0 : 1) .animation(.easeInOut(duration: 0.25), value: uploadActive || greetingActive) + // Anchor for the menu that opens on a click on the Memoji. + if state.mode == .expanded { + let (bx, by, bd, _) = botPosition(mode: state.mode, view: state.view, islandW: islandWidth, + islandH: islandHeight, uploadProgress: state.uploadProgress, + hasNotch: state.hasNotch) + Color.clear + .frame(width: bd, height: bd) + .position(x: bx, y: by) + .allowsHitTesting(false) + .popover(isPresented: $state.botMenuOpen, arrowEdge: .bottom) { + BroMenu(state: state) + } + } + CountdownBar(state: state, islandW: islandWidth) // Pull handle: drag the bottom edge to grow the chat (⅓, ½, full screen). diff --git a/NotchBuddy/Sources/App/IslandWindowController.swift b/NotchBuddy/Sources/App/IslandWindowController.swift index 6ca34d3..3f1bb37 100644 --- a/NotchBuddy/Sources/App/IslandWindowController.swift +++ b/NotchBuddy/Sources/App/IslandWindowController.swift @@ -35,6 +35,7 @@ final class IslandWindowController: NSWindowController { // Window attach drag (M8) private var attachDragStart: NSPoint? = nil + private var botClickPending = false private var pendingIslandClick = false // any island click → expand on mouseUp private var inAttachDrag = false private var dragGhostPanel: NSPanel? = nil @@ -723,9 +724,8 @@ final class IslandWindowController: NSWindowController { // Notch Mochi is invisible when on desktop — no drag, no slap guard !self.state.mochiOnDesktop else { return } self.attachDragStart = NSEvent.mouseLocation - // Post slap only when expanded - guard self.state.mode == .expanded else { return } - NotificationCenter.default.post(name: .triggerSlap, object: nil) + // A click (not a drag) on the Memoji opens its menu on mouse-up. + self.botClickPending = self.state.mode == .expanded } return event } @@ -791,7 +791,16 @@ final class IslandWindowController: NSWindowController { MainActor.assumeIsolated { let hadPendingClick = self.pendingIslandClick let wasDragging = self.inAttachDrag + let botClick = self.botClickPending && !wasDragging self.pendingIslandClick = false + self.botClickPending = false + if botClick && self.state.mode == .expanded { + self.state.botMenuOpen.toggle() + if self.state.botMenuOpen { + NotificationCenter.default.post(name: .triggerEmote, object: BotEmote.happy) + SoundEngine.shared.play("pop") + } + } if wasDragging { finishDrag() } else { diff --git a/NotchBuddy/Sources/App/Ops.swift b/NotchBuddy/Sources/App/Ops.swift new file mode 100644 index 0000000..57411f7 --- /dev/null +++ b/NotchBuddy/Sources/App/Ops.swift @@ -0,0 +1,373 @@ +import SwiftUI +import AppKit + +// MARK: - BroV Ops (the homelab manager) in the notch +// +// The service runs on the homelab VM (ops/ in this repo): tasks with subtasks and a +// timer, subscriptions and payments, routines. BroV talks to its small HTTP API on the +// home network (or through the "Дом" tunnel). Click on the Memoji → menu → «Дела». + +struct OpsItem: Identifiable, Equatable { + var kind: String // task | sub | routine + var ref: Int + var title: String + var date: String + var client: String + var amount: Double? + var currency: String? + var id: String { "\(kind)-\(ref)" } +} + +struct OpsAgenda: Equatable { + var overdue: [OpsItem] = [] + var today: [OpsItem] = [] + var soon: [OpsItem] = [] + var running: (id: Int, title: String, minutes: Int)? + var monthly: [String: Double] = [:] + + static func == (a: OpsAgenda, b: OpsAgenda) -> Bool { + a.overdue == b.overdue && a.today == b.today && a.soon == b.soon + && a.running?.id == b.running?.id && a.running?.minutes == b.running?.minutes && a.monthly == b.monthly + } +} + +@MainActor +final class OpsClient: ObservableObject { + static let shared = OpsClient() + static let urlKey = "opsURL" + static let tokenKey = "brov-ops-token" + + @Published var agenda = OpsAgenda() + @Published var reachable: Bool? = nil // nil = not configured + @Published var busy = false + @Published var lastAnswer: String? + + var baseURL: String { + (UserDefaults.standard.string(forKey: Self.urlKey) ?? "").trimmingCharacters(in: .whitespacesAndNewlines) + } + /// Read once from the Keychain, updated by Settings. + var token: String = Keychain.load(key: OpsClient.tokenKey) ?? "" + var configured: Bool { !baseURL.isEmpty && !token.isEmpty } + + private func request(_ path: String, body: [String: Any]? = nil, timeout: TimeInterval = 8) async -> Any? { + guard configured, let url = URL(string: baseURL + path) else { reachable = nil; return nil } + var req = URLRequest(url: url, timeoutInterval: timeout) + req.setValue("Bearer " + token, forHTTPHeaderField: "Authorization") + if let body { + req.httpMethod = "POST" + req.setValue("application/json", forHTTPHeaderField: "Content-Type") + req.httpBody = try? JSONSerialization.data(withJSONObject: body) + } + do { + let (data, resp) = try await URLSession.shared.data(for: req) + guard (resp as? HTTPURLResponse)?.statusCode == 200 else { reachable = false; return nil } + reachable = true + return try JSONSerialization.jsonObject(with: data) + } catch { + reachable = false + return nil + } + } + + func refresh() async { + guard let j = await request("/api/agenda") as? [String: Any] else { return } + func items(_ key: String) -> [OpsItem] { + (j[key] as? [[String: Any]] ?? []).compactMap { d in + guard let kind = d["kind"] as? String, let ref = d["id"] as? Int else { return nil } + return OpsItem(kind: kind, ref: ref, title: d["title"] as? String ?? "", date: d["date"] as? String ?? "", + client: d["client"] as? String ?? "", amount: d["amount"] as? Double, + currency: d["currency"] as? String) + } + } + var a = OpsAgenda(overdue: items("overdue"), today: items("due_today"), soon: items("soon")) + if let r = j["running"] as? [String: Any], let id = r["id"] as? Int { + a.running = (id, r["title"] as? String ?? "", r["minutes"] as? Int ?? 0) + } + a.monthly = j["monthly_cost"] as? [String: Double] ?? [:] + agenda = a + } + + /// Free text → the service's Claude brain (same as Telegram). + func say(_ text: String) async { + busy = true + defer { busy = false } + let r = await request("/api/say", body: ["text": text], timeout: 120) as? [String: Any] + lastAnswer = r?["answer"] as? String ?? (reachable == false ? "Сервис дел не отвечает." : nil) + await refresh() + } + + /// A direct action from a button: done / paid / timer / snooze. + func act(_ body: [String: Any]) async { + let r = await request("/api/action", body: body) as? [String: Any] + if let lines = r?["result"] as? [String] { lastAnswer = lines.joined(separator: "\n") } + SoundEngine.shared.play("pop") + await refresh() + } + + func done(_ it: OpsItem) async { + switch it.kind { + case "task": await act(["op": "complete_task", "id": it.ref]) + case "sub": await act(["op": "pay_sub", "id": it.ref]) + default: await act(["op": "done_routine", "id": it.ref]) + } + } + + var attentionCount: Int { agenda.overdue.count + agenda.today.count } +} + +// MARK: - Menu on the Memoji + +struct BroMenu: View { + @ObservedObject var state: AppState + @ObservedObject private var ops = OpsClient.shared + @ObservedObject private var coffee = Coffee.shared + @State private var page = 0 // 0 = menu, 1 = «Дела» + + var body: some View { + Group { + if page == 1 { + OpsPanel(state: state, back: { withAnimation(.easeOut(duration: 0.15)) { page = 0 } }) + } else { + VStack(alignment: .leading, spacing: 2) { + FuncRow(symbol: "checklist", color: "#D97757", title: "Дела", + subtitle: opsSubtitle, hint: ops.attentionCount > 0 ? "\(ops.attentionCount)" : nil) { + withAnimation(.easeOut(duration: 0.15)) { page = 1 } + } + if let r = ops.agenda.running { + FuncRow(symbol: "stop.circle", color: "#F4505E", title: "Стоп таймер", + subtitle: "\(r.title) · \(r.minutes) мин", hint: nil) { + Task { await ops.act(["op": "stop_timer"]) } + } + } + Divider().padding(.vertical, 4) + FuncRow(symbol: "eyedropper", color: "#F472B6", title: "Пипетка", + subtitle: "цвет пикселя во всех форматах", hint: nil) { + state.botMenuOpen = false + ColorPicking.start(state: state) + } + FuncRow(symbol: "character.bubble", color: "#60A5FA", title: "Переводчик", + subtitle: "выделенный текст RU ↔ EN", hint: "⌥`") { + state.botMenuOpen = false + TranslatorRun.start(state: state) + } + FuncRow(symbol: coffee.on ? "cup.and.saucer.fill" : "cup.and.saucer", color: "#D97757", + title: coffee.on ? "Кофе: включён" : "Кофе-режим", + subtitle: coffee.on ? "Мак не засыпает — нажми, чтобы выключить" : "не давать Маку засыпать", + hint: nil) { + coffee.toggle() + } + } + .padding(8) + .frame(width: 290) + } + } + .notchPopoverStyle() + .task { await ops.refresh() } + } + + private var opsSubtitle: String { + guard ops.configured else { return "подключи сервис в Настройках → Чат" } + if ops.reachable == false { return "сервис не отвечает" } + let a = ops.agenda + if a.overdue.isEmpty && a.today.isEmpty { return a.soon.isEmpty ? "ничего не горит" : "на неделе: \(a.soon.count)" } + return [a.overdue.isEmpty ? nil : "просрочено \(a.overdue.count)", + a.today.isEmpty ? nil : "сегодня \(a.today.count)"].compactMap { $0 }.joined(separator: " · ") + } +} + +// MARK: - «Дела» panel + +struct OpsPanel: View { + @ObservedObject var state: AppState + let back: () -> Void + @ObservedObject private var ops = OpsClient.shared + @State private var text = "" + @FocusState private var focused: Bool + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + HStack(spacing: 6) { + Button(action: back) { + Image(systemName: "chevron.left").font(.system(size: 11, weight: .semibold)) + } + .buttonStyle(.plain) + Text("Дела").font(.system(size: 14, weight: .semibold)) + Spacer() + if ops.busy { ProgressView().controlSize(.mini) } + Button { Task { await ops.refresh() } } label: { + Image(systemName: "arrow.clockwise").font(.system(size: 11)) + } + .buttonStyle(.plain) + .help("Обновить") + } + .foregroundColor(Color(hex: "#B0B5BE")) + + if !ops.configured { + Text("Сервис дел не подключён. Настройки → Чат → «Дела (хоумлаб)»: адрес и токен из /etc/brov-ops/config.env на ВМ.") + .font(.system(size: 11.5)).foregroundColor(Color(hex: "#B0B5BE")) + .fixedSize(horizontal: false, vertical: true) + } else if ops.reachable == false { + Text("Сервис дел не отвечает. Ты не дома? Включи сеть «Дом» в 🌐.") + .font(.system(size: 11.5)).foregroundColor(Color(hex: "#FB923C")) + .fixedSize(horizontal: false, vertical: true) + } + + if let r = ops.agenda.running { + HStack(spacing: 8) { + Image(systemName: "timer").foregroundColor(Color(hex: "#34D399")) + Text(r.title).font(.system(size: 12, weight: .semibold)).lineLimit(1) + Text("\(r.minutes) мин").font(.system(size: 11)).monospacedDigit().foregroundColor(Color(hex: "#8E939C")) + Spacer() + Button("Стоп") { Task { await ops.act(["op": "stop_timer"]) } } + .buttonStyle(.plain).font(.system(size: 11, weight: .medium)).foregroundColor(Color(hex: "#F4505E")) + } + .padding(8) + .background(RoundedRectangle(cornerRadius: 8).fill(Color(hex: "#34D399").opacity(0.10))) + } + + ScrollView(.vertical, showsIndicators: false) { + VStack(alignment: .leading, spacing: 2) { + section("ПРОСРОЧЕНО", ops.agenda.overdue, "#F4505E") + section("СЕГОДНЯ", ops.agenda.today, "#F5A524") + section("НА НЕДЕЛЕ", ops.agenda.soon, "#8E939C") + if ops.configured && ops.reachable == true && ops.agenda.overdue.isEmpty + && ops.agenda.today.isEmpty && ops.agenda.soon.isEmpty { + Text("На неделю ничего не горит 👌").font(.system(size: 12)).foregroundColor(Color(hex: "#8E939C")) + .padding(.vertical, 6) + } + } + } + .frame(maxHeight: 260) + + if let a = ops.lastAnswer, !a.isEmpty { + Text(a).font(.system(size: 11)).foregroundColor(Color(hex: "#B0B5BE")) + .textSelection(.enabled) + .fixedSize(horizontal: false, vertical: true) + .padding(8) + .frame(maxWidth: .infinity, alignment: .leading) + .background(RoundedRectangle(cornerRadius: 8).fill(Color.white.opacity(0.05))) + } + + HStack(spacing: 6) { + TextField("Записать: «продлить домен до 15.11, 1200 ₽»", text: $text) + .textFieldStyle(.plain) + .font(.system(size: 12.5)) + .focused($focused) + .onSubmit(send) + Button(action: send) { + Image(systemName: "arrow.up").font(.system(size: 10, weight: .bold)) + .foregroundColor(Color(hex: "#0B0C0E")) + .frame(width: 20, height: 20) + .background(Circle().fill(Color(hex: text.isEmpty ? "#5F646D" : "#D97757"))) + } + .buttonStyle(.plain) + .disabled(text.isEmpty || ops.busy || !ops.configured) + } + .padding(.horizontal, 10).padding(.vertical, 7) + .background(RoundedRectangle(cornerRadius: 10).fill(Color.white.opacity(0.07))) + } + .padding(12) + .frame(width: 380) + .foregroundColor(Color(hex: "#F5F6F8")) + .onAppear { focused = true } + } + + private func send() { + let t = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard !t.isEmpty else { return } + text = "" + Task { await ops.say(t) } + } + + @ViewBuilder private func section(_ title: String, _ items: [OpsItem], _ color: String) -> some View { + if !items.isEmpty { + Text(title).font(.system(size: 9.5, weight: .bold)).foregroundColor(Color(hex: color)) + .padding(.top, 6).padding(.bottom, 2) + ForEach(items) { OpsRow(item: $0) } + } + } +} + +struct OpsRow: View { + let item: OpsItem + @ObservedObject private var ops = OpsClient.shared + @State private var hovered = false + + private var icon: String { + switch item.kind { case "sub": return "creditcard"; case "routine": return "arrow.triangle.2.circlepath"; default: return "pin" } + } + + var body: some View { + HStack(spacing: 8) { + Image(systemName: icon).font(.system(size: 11)).foregroundColor(Color(hex: "#8E939C")).frame(width: 14) + VStack(alignment: .leading, spacing: 1) { + Text(item.title).font(.system(size: 12, weight: .medium)).lineLimit(1) + Text(subtitle).font(.system(size: 10.5)).foregroundColor(Color(hex: "#6B7079")).lineLimit(1) + } + Spacer(minLength: 4) + if hovered { + if item.kind == "task" { + small("timer", "Засечь время") { Task { await ops.act(["op": "start_timer", "id": item.ref]) } } + } + small("clock.arrow.circlepath", "Завтра") { + Task { await ops.act(["op": "snooze", "kind": item.kind, "id": item.ref, "days": 1]) } + } + } + small(item.kind == "sub" ? "rublesign.circle" : "checkmark.circle", + item.kind == "sub" ? "Оплачено" : "Сделано") { Task { await ops.done(item) } } + } + .padding(.horizontal, 6).padding(.vertical, 5) + .background(RoundedRectangle(cornerRadius: 7).fill(Color.white.opacity(hovered ? 0.06 : 0))) + .onHover { hovered = $0 } + } + + private var subtitle: String { + var parts = [item.date] + if let a = item.amount { parts.append("\(a.formatted()) \(item.currency ?? "")") } + if !item.client.isEmpty { parts.append(item.client) } + return parts.joined(separator: " · ") + } + + private func small(_ symbol: String, _ help: String, _ action: @escaping () -> Void) -> some View { + Button(action: action) { + Image(systemName: symbol).font(.system(size: 13)).foregroundColor(Color(hex: "#B0B5BE")) + } + .buttonStyle(.plain) + .help(help) + } +} + +// MARK: - Settings + +struct OpsSettingsBox: View { + @State private var url = UserDefaults.standard.string(forKey: OpsClient.urlKey) ?? "" + @State private var token = Keychain.load(key: OpsClient.tokenKey) ?? "" + @State private var status: String? + + var body: some View { + GroupBox("Дела (хоумлаб)") { + VStack(alignment: .leading, spacing: 8) { + Text("Сервис дел на виртуалке хоумлаба: задачи, подписки, регламент. Адрес вида http://192.168.10.50:8787, токен — API_TOKEN из /etc/brov-ops/config.env на ВМ (хранится в Связке ключей).") + .font(.system(size: 11)).foregroundColor(.secondary) + .fixedSize(horizontal: false, vertical: true) + TextField("Адрес сервиса", text: $url).textFieldStyle(.roundedBorder) + SecureField("Токен", text: $token).textFieldStyle(.roundedBorder) + HStack { + Button("Сохранить и проверить") { + UserDefaults.standard.set(url.trimmingCharacters(in: .whitespacesAndNewlines), forKey: OpsClient.urlKey) + let t = token.trimmingCharacters(in: .whitespacesAndNewlines) + Keychain.save(key: OpsClient.tokenKey, value: t) + OpsClient.shared.token = t + Task { + await OpsClient.shared.refresh() + status = OpsClient.shared.reachable == true ? "✓ Подключено" : "✗ Не отвечает или неверный токен" + } + } + .buttonStyle(.borderedProminent) + if let status { Text(status).font(.system(size: 11)).foregroundColor(.secondary) } + } + } + .padding(6) + } + } +} diff --git a/NotchBuddy/Sources/App/SettingsView.swift b/NotchBuddy/Sources/App/SettingsView.swift index adf7cfd..fca70b8 100644 --- a/NotchBuddy/Sources/App/SettingsView.swift +++ b/NotchBuddy/Sources/App/SettingsView.swift @@ -218,7 +218,9 @@ struct SettingsView: View { switch selectedSection { case "activepills": activePillsSection case "agents": agentsSection - case "chat": chatSection + case "chat": + chatSection + OpsSettingsBox() case "integrations": integrationsSection case "shortcuts": ShortcutsSettingsView() default: generalSection