release: native macOS preview, approved graph identity, and guarded CLI failover

This commit is contained in:
public-repo-gate
2026-09-13 16:36:15 +03:00
parent 74c9f07f59
commit 04d0ece7ff
56 changed files with 16087 additions and 4002 deletions
+2
View File
@@ -0,0 +1,2 @@
.build/
.swiftpm/
+15
View File
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>CFBundleExecutable</key><string>Mnemazine</string>
<key>CFBundleIdentifier</key><string>org.mnemazine.menubar</string>
<key>CFBundleName</key><string>Mnemazine</string>
<key>CFBundleDisplayName</key><string>Мнемозина</string>
<key>CFBundleIconFile</key><string>AppIcon</string>
<key>CFBundlePackageType</key><string>APPL</string>
<key>CFBundleShortVersionString</key><string>0.1.0</string>
<key>CFBundleVersion</key><string>1</string>
<key>LSMinimumSystemVersion</key><string>14.0</string>
<key>LSUIElement</key><true/>
<key>NSHighResolutionCapable</key><true/>
</dict></plist>
+8
View File
@@ -0,0 +1,8 @@
// swift-tools-version: 5.9
import PackageDescription
let package = Package(
name: "Mnemazine", platforms: [.macOS(.v14)],
products: [.executable(name: "Mnemazine", targets: ["Mnemazine"])],
targets: [.executableTarget(name: "Mnemazine"),
.testTarget(name: "MnemazineTests", dependencies: ["Mnemazine"])])
+147
View File
@@ -0,0 +1,147 @@
import Foundation
struct Job: Decodable, Identifiable, Sendable {
let id: String
let kind: String
let status: String
var query: String?
var input_text: String?
var files: [JobFile]?
var result: JobResult?
var error: JobError?
var created_at: String?
var title: String { input_text ?? query ?? files?.map(\.name).joined(separator: ", ") ?? kind }
var active: Bool { status == "queued" || status == "running" }
var statusLabel: String {
["queued": "В очереди", "running": "Обрабатываю", "completed": "Готово",
"failed": "Не получилось", "cancelled": "Отменено"][status] ?? status
}
}
struct JobFile: Decodable, Sendable {
let name: String
let original: String?
let snapshot: String?
}
struct JobError: Decodable, Sendable {
let message: String
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let text = try? container.decode(String.self) { message = text }
else {
let fields = try decoder.container(keyedBy: CodingKeys.self)
message = try fields.decodeIfPresent(String.self, forKey: .message) ?? "Ошибка обработки"
}
}
enum CodingKeys: String, CodingKey { case message }
}
struct JobResult: Decodable, Sendable {
var text: String?
var report_path: String?
var sources: [Source]?
}
struct Source: Decodable, Sendable {
var title: String?
var path: String?
var url: String?
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let string = try? container.decode(String.self) {
title = string; path = string.hasPrefix("/") ? string : nil
url = string.hasPrefix("https://") || string.hasPrefix("http://") ? string : nil
} else {
let fields = try decoder.container(keyedBy: CodingKeys.self)
title = try fields.decodeIfPresent(String.self, forKey: .title)
path = try fields.decodeIfPresent(String.self, forKey: .path)
url = try fields.decodeIfPresent(String.self, forKey: .url)
}
}
enum CodingKeys: String, CodingKey { case title, path, url }
var target: URL? {
if let path, path.hasPrefix("/") {
let target = URL(fileURLWithPath: path)
guard ["md", "markdown", "txt", "pdf", "docx", "rtf", "csv", "json", "png", "jpg", "jpeg"].contains(target.pathExtension.lowercased()) else { return nil }
return target
}
guard let url, let target = URL(string: url), ["https", "http"].contains(target.scheme) else { return nil }
return target
}
}
struct Envelope: Decodable, Sendable {
var job: Job?
var jobs: [Job]?
var providers: [CLIProvider]?
}
struct CLIProvider: Decodable, Identifiable, Sendable {
let name: String
let installed: Bool
let supported: Bool
var cooldown: CLICooldown?
var id: String { name }
var status: String {
if !installed { return "Не установлен" }
if !supported { return "Нужен адаптер" }
if let cooldown {
return "Лимит до " + Date(timeIntervalSince1970: cooldown.until / 1000).formatted(date: .omitted, time: .shortened)
}
return "Найден · вход проверится при вызове"
}
}
struct CLICooldown: Decodable, Sendable { let reason: String; let until: Double }
enum Backend {
static func arguments(_ command: String, kind: String? = nil, query: String? = nil,
mode: String = "local", files: [URL] = [], id: String? = nil, text: String? = nil) -> [String] {
var args = ["scripts/mnemazine-jobs.mjs", command]
if let kind { args += ["--kind", kind] }
if let query { args += ["--query", query] }
if let text { args += ["--text", text] }
if command == "submit" { args += ["--mode", mode] }
for file in files { args += ["--file", file.path] }
if let id { args += ["--id", id] }
return args
}
// Process and both pipe readers live off the main actor. Drain stderr in parallel:
// a verbose child must never fill its pipe and deadlock the menu.
static func run(repository: String, node: String, args: [String]) async throws -> Envelope {
try await Task.detached {
guard FileManager.default.fileExists(atPath: repository + "/scripts/mnemazine-jobs.mjs") else {
throw NSError(domain: "Mnemazine", code: 1, userInfo: [NSLocalizedDescriptionKey: "Выбери папку Mnemazine в настройках."])
}
guard node.hasPrefix("/"), FileManager.default.isExecutableFile(atPath: node) else {
throw NSError(domain: "Mnemazine", code: 2, userInfo: [NSLocalizedDescriptionKey: "Node.js не найден. Выбери исполняемый файл в настройках."])
}
let process = Process()
process.executableURL = URL(fileURLWithPath: node)
process.arguments = args
process.currentDirectoryURL = URL(fileURLWithPath: repository)
var env = ProcessInfo.processInfo.environment
env["PATH"] = URL(fileURLWithPath: node).deletingLastPathComponent().path + ":/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:" + (env["PATH"] ?? "")
process.environment = env
let output = Pipe(), errors = Pipe()
process.standardOutput = output; process.standardError = errors
process.standardInput = FileHandle.nullDevice
try process.run()
let timeout = Task.detached {
try? await Task.sleep(for: .seconds(30))
if !Task.isCancelled, process.isRunning { process.terminate() }
}
defer { timeout.cancel() }
let errorRead = Task.detached { errors.fileHandleForReading.readDataToEndOfFile() }
let data = output.fileHandleForReading.readDataToEndOfFile()
process.waitUntilExit()
let errorData = await errorRead.value
guard process.terminationStatus == 0 else {
let message = String(data: errorData, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines)
throw NSError(domain: "Mnemazine", code: Int(process.terminationStatus), userInfo: [NSLocalizedDescriptionKey: message?.isEmpty == false ? message! : "Команда завершилась с ошибкой \(process.terminationStatus)"])
}
return try JSONDecoder().decode(Envelope.self, from: data)
}.value
}
}
+89
View File
@@ -0,0 +1,89 @@
import AppKit
import SwiftUI
struct ReadablePlate: ViewModifier {
var cornerRadius: CGFloat = 12
@Environment(\.accessibilityReduceTransparency) private var reduceTransparency
func body(content: Content) -> some View {
if reduceTransparency {
content.background(Color(nsColor: .windowBackgroundColor), in: RoundedRectangle(cornerRadius: cornerRadius))
} else {
content.background(.regularMaterial, in: RoundedRectangle(cornerRadius: cornerRadius))
}
}
}
struct ClearGlassPlate: ViewModifier {
@Environment(\.accessibilityReduceTransparency) private var reduceTransparency
func body(content: Content) -> some View {
if reduceTransparency {
content.background(Color(nsColor: .windowBackgroundColor), in: RoundedRectangle(cornerRadius: 16))
} else if #available(macOS 26.0, *) {
content.glassEffect(.clear, in: .rect(cornerRadius: 16))
} else {
content.background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 16))
}
}
}
struct GlassWindow: ViewModifier {
@Environment(\.accessibilityReduceTransparency) private var reduceTransparency
func body(content: Content) -> some View {
content
.background {
if reduceTransparency { Color(nsColor: .windowBackgroundColor).ignoresSafeArea() }
else { WindowGlassSurface().ignoresSafeArea() }
}
.background(WindowBacking(opaque: reduceTransparency).frame(width: 0, height: 0))
}
}
private struct WindowGlassSurface: NSViewRepresentable {
func makeNSView(context: Context) -> NSView {
if #available(macOS 26.0, *) {
let glass = NSGlassEffectView()
glass.style = .regular
glass.cornerRadius = 16
return glass
}
let blur = NSVisualEffectView()
blur.material = .hudWindow
blur.blendingMode = .behindWindow
blur.state = .active
blur.wantsLayer = true
blur.layer?.cornerRadius = 16
blur.layer?.masksToBounds = true
return blur
}
func updateNSView(_ view: NSView, context: Context) {}
}
@MainActor
func configureGlassWindow(_ window: NSWindow, opaque: Bool) {
// Extend only the background under native traffic lights; SwiftUI keeps
// interactive content within the window's titlebar safe area.
window.styleMask.insert(.fullSizeContentView)
window.isOpaque = opaque
window.backgroundColor = opaque ? .windowBackgroundColor : .clear
window.titlebarAppearsTransparent = true
window.isReleasedWhenClosed = false
}
private struct WindowBacking: NSViewRepresentable {
let opaque: Bool
func makeNSView(context: Context) -> Anchor { Anchor(opaque: opaque) }
func updateNSView(_ view: Anchor, context: Context) {
view.shouldBeOpaque = opaque
view.applyBacking()
}
final class Anchor: NSView {
var shouldBeOpaque: Bool
init(opaque: Bool) { self.shouldBeOpaque = opaque; super.init(frame: .zero) }
required init?(coder: NSCoder) { fatalError("Use init(opaque:)") }
override func viewDidMoveToWindow() { super.viewDidMoveToWindow(); applyBacking() }
func applyBacking() {
guard let window else { return }
configureGlassWindow(window, opaque: shouldBeOpaque)
}
}
}
@@ -0,0 +1,87 @@
import SwiftUI
struct MarkdownBlock: Equatable {
enum Kind: Equatable { case paragraph, heading(Int), quote, code, item, divider }
var kind: Kind
var text: String
// ponytail: the result format needs prose, lists, quotes and fenced code.
// Tables remain selectable text until real reports require a table renderer.
static func parse(_ text: String) -> [MarkdownBlock] {
var blocks: [MarkdownBlock] = []
var paragraph: [String] = [], code: [String] = []
var inCode = false
func flush() {
if !paragraph.isEmpty { blocks.append(.init(kind: .paragraph, text: paragraph.joined(separator: "\n"))); paragraph = [] }
}
for line in text.components(separatedBy: .newlines) {
if line.hasPrefix("```") {
flush()
if inCode { blocks.append(.init(kind: .code, text: code.joined(separator: "\n"))); code = [] }
inCode.toggle(); continue
}
if inCode { code.append(line); continue }
let trimmed = line.trimmingCharacters(in: .whitespaces)
if trimmed.isEmpty { flush(); continue }
let heading = line.prefix { $0 == "#" }.count
if (1...6).contains(heading), line.dropFirst(heading).first == " " {
flush(); blocks.append(.init(kind: .heading(heading), text: String(line.dropFirst(heading + 1))))
} else if trimmed == "---" || trimmed == "***" {
flush(); blocks.append(.init(kind: .divider, text: ""))
} else if trimmed.hasPrefix("> ") {
flush(); blocks.append(.init(kind: .quote, text: String(trimmed.dropFirst(2))))
} else if trimmed.hasPrefix("- ") || trimmed.hasPrefix("* ") {
flush(); blocks.append(.init(kind: .item, text: "• " + trimmed.dropFirst(2)))
} else if trimmed.range(of: #"^\d+\. "#, options: .regularExpression) != nil {
flush(); blocks.append(.init(kind: .item, text: trimmed))
} else { paragraph.append(line) }
}
flush()
if inCode { blocks.append(.init(kind: .code, text: code.joined(separator: "\n"))) }
return blocks
}
static func inline(_ text: String) -> AttributedString {
var result = (try? AttributedString(markdown: text, options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace))) ?? AttributedString(text)
// Markdown comes from documents and models. Links may navigate the web;
// local documents are opened using the separate vetted source buttons.
for run in result.runs {
if let link = run.link, !["https", "http"].contains(link.scheme?.lowercased() ?? "") {
result[run.range].link = nil
}
}
return result
}
}
struct MarkdownContent: View {
let text: String
var body: some View {
VStack(alignment: .leading, spacing: 12) {
ForEach(Array(MarkdownBlock.parse(text).enumerated()), id: \.offset) { _, block in
switch block.kind {
case .heading(let level):
Text(MarkdownBlock.inline(block.text))
.font(level == 1 ? .title : level == 2 ? .title2 : .headline)
.fontWeight(.semibold).accessibilityAddTraits(.isHeader)
case .code:
ScrollView(.horizontal) {
Text(block.text).font(.system(.body, design: .monospaced)).padding(12)
}.background(.quaternary, in: RoundedRectangle(cornerRadius: 8))
case .quote:
HStack(alignment: .top, spacing: 12) {
RoundedRectangle(cornerRadius: 2).fill(.secondary).frame(width: 3)
Text(MarkdownBlock.inline(block.text)).foregroundStyle(.secondary)
}.fixedSize(horizontal: false, vertical: true)
case .item:
Text(MarkdownBlock.inline(block.text)).padding(.leading, 8)
case .divider: Divider()
case .paragraph: Text(MarkdownBlock.inline(block.text))
}
}
}.textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)
.environment(\.openURL, OpenURLAction { url in
["http", "https"].contains(url.scheme?.lowercased() ?? "") ? .systemAction : .discarded
})
}
}
+513
View File
@@ -0,0 +1,513 @@
import AppKit
import SwiftUI
import UniformTypeIdentifiers
@MainActor
final class Store: ObservableObject {
@Published var jobs: [Job] = []
@Published var error: String?
@Published var busy = false
@Published var selectedID: String?
@Published var pendingFiles: [URL] = []
@Published var deep = false
var openWindow: ((String) -> Void)?
var panelSizeChanged: ((CGSize) -> Void)?
@Published var repository: String { didSet { UserDefaults.standard.set(repository, forKey: "repository") } }
@Published var node: String { didSet { UserDefaults.standard.set(node, forKey: "node") } }
private var refreshing = false
init() {
repository = UserDefaults.standard.string(forKey: "repository") ?? Bundle.main.object(forInfoDictionaryKey: "MnemazineRepository") as? String ?? ""
node = UserDefaults.standard.string(forKey: "node") ?? Bundle.main.object(forInfoDictionaryKey: "MnemazineNode") as? String ?? ["/opt/homebrew/bin/node", "/usr/local/bin/node", "/usr/bin/node"].first { FileManager.default.isExecutableFile(atPath: $0) } ?? ""
}
var configured: Bool { !repository.isEmpty && !node.isEmpty }
var selected: Job? { jobs.first { $0.id == selectedID } }
func refresh() async {
guard configured, !refreshing else { return }
refreshing = true
defer { refreshing = false }
do { jobs = try await Backend.run(repository: repository, node: node, args: Backend.arguments("list")).jobs ?? [] }
catch { self.error = error.localizedDescription }
}
func submit(kind: String, query: String? = nil, mode: String = "local", files: [URL] = [], text: String? = nil) async {
guard !busy else { return }
busy = true; error = nil
defer { busy = false }
do {
let result = try await Backend.run(repository: repository, node: node, args: Backend.arguments("submit", kind: kind, query: query, mode: mode, files: files, text: text))
selectedID = result.job?.id
await refresh()
} catch { self.error = error.localizedDescription }
}
func action(_ command: String, id: String) async {
do {
_ = try await Backend.run(repository: repository, node: node, args: Backend.arguments(command, id: id))
await refresh()
} catch { self.error = error.localizedDescription }
}
func chooseFiles() {
let panel = NSOpenPanel()
panel.allowsMultipleSelection = true; panel.canChooseDirectories = false
panel.message = "Файлы попадут в очередь Мнемозины. Оригиналы останутся на месте."
panel.begin { response in
guard response == .OK else { return }
Task { @MainActor in self.pendingFiles = panel.urls }
}
}
func chooseRepository() {
let panel = NSOpenPanel(); panel.canChooseFiles = false; panel.canChooseDirectories = true
panel.message = "Выбери папку проекта Mnemazine"
panel.begin { response in
guard response == .OK, let url = panel.url else { return }
Task { @MainActor in self.repository = url.path; await self.refresh() }
}
}
func chooseNode() {
let panel = NSOpenPanel(); panel.message = "Выбери исполняемый файл node"
panel.begin { response in
guard response == .OK, let url = panel.url else { return }
Task { @MainActor in self.node = url.path; await self.refresh() }
}
}
}
@main
struct MnemazineApp: App {
@NSApplicationDelegateAdaptor(StatusAppDelegate.self) private var delegate
var body: some Scene {
Settings { EmptyView() }
}
}
struct GlassPlate: ViewModifier {
@Environment(\.accessibilityReduceTransparency) private var reduceTransparency
func body(content: Content) -> some View {
if reduceTransparency { content.background(Color(nsColor: .windowBackgroundColor), in: RoundedRectangle(cornerRadius: 16)) }
else {
if #available(macOS 26.0, *) {
content.background(.thinMaterial, in: RoundedRectangle(cornerRadius: 16))
.glassEffect(.regular, in: .rect(cornerRadius: 16))
} else { content.background(.regularMaterial, in: RoundedRectangle(cornerRadius: 16)) }
}
}
}
func fileActionAccessibilityLabel(configured: Bool, pendingCount: Int) -> String {
if !configured { return "Открыть настройки Мнемозины" }
if pendingCount > 0 { return "Обработать файлы: \(pendingCount)" }
return "Добавить файлы: перенеси сюда или нажми для выбора"
}
struct MenuPanel: View {
@EnvironmentObject var store: Store
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@State private var input = ""
@State private var mode: SpotlightMode = .search
@State private var clipboard = ClipboardPreview()
@State private var confirmedRequest: SpotlightRequest?
@State private var confirmedFiles: [URL] = []
@State private var confirmExternal = false
@State private var targeted = false
@State private var validation: String?
@State private var panel = MenuPanelWindow()
@FocusState private var inputFocused: Bool
@Namespace private var glassNamespace
var body: some View {
VStack(spacing: 0) {
glassHeader
if mode != .search || validation != nil {
VStack(alignment: .leading, spacing: 14) {
if let validation {
Text(validation).font(.callout).foregroundStyle(.red).textSelection(.enabled)
}
expansion
}.padding(18).frame(maxWidth: .infinity, alignment: .leading)
.modifier(ReadablePlate(cornerRadius: 20)).padding(.top, 12)
.transition(.opacity)
}
}.frame(width: min(620, (NSScreen.main?.visibleFrame.width ?? 672) - 52))
.padding(10)
.animation(reduceMotion ? nil : .spring(response: 0.32, dampingFraction: 0.86), value: targeted)
.animation(reduceMotion ? nil : .spring(response: 0.32, dampingFraction: 0.86), value: mode)
.background(GeometryReader { proxy in
Color.clear.preference(key: SpotlightSizeKey.self, value: proxy.size)
})
.onPreferenceChange(SpotlightSizeKey.self) { size in
guard size.width > 0, size.height > 0 else { return }
store.panelSizeChanged?(size)
}
.background(MenuPanelAnchor(panel: panel).frame(width: 0, height: 0))
.onAppear { DispatchQueue.main.async { panel.window?.makeKey(); inputFocused = true } }
.onExitCommand { panel.window?.close() }
.task { await store.refresh() }
.dropDestination(for: URL.self) { urls, _ in
guard !store.busy, !urls.isEmpty, urls.allSatisfy(\.isFileURL) else { return false }
store.pendingFiles = urls; mode = .files; validation = nil
return true
} isTargeted: { targeted = $0 }
.onChange(of: store.pendingFiles) { _, files in
if !files.isEmpty { mode = .files; validation = nil }
}
.alert("Передать данные для обработки?", isPresented: $confirmExternal) {
Button("Отмена", role: .cancel) {}
Button("Отправить и обработать") { sendConfirmed() }
} message: {
Text(confirmedRequest?.kind == "ingest" || !confirmedFiles.isEmpty
? "Содержимое будет передано настроенной модели для исследования с вебом. Оригиналы файлов сохранятся. Полный текст страницы и расшифровка видео не гарантируются."
: "Провайдер получит запрос и найденные фрагменты памяти.")
}
}
@ViewBuilder private var glassHeader: some View {
if #available(macOS 26.0, *) {
GlassEffectContainer(spacing: 6) { headerRow }
} else { headerRow }
}
private var headerRow: some View {
HStack(spacing: 8) {
HStack(spacing: 12) {
if targeted {
Image(systemName: "doc.badge.plus").font(.system(size: 28, weight: .light))
VStack(alignment: .leading, spacing: 3) {
Text("Отпусти файл здесь").font(.system(size: 24))
Text("Сначала покажу выбранное").font(.caption).foregroundStyle(.secondary)
}
Spacer()
} else {
if mode == .search {
Button { select(.search) } label: {
Image(systemName: "magnifyingglass").font(.system(size: 24))
.foregroundStyle(.secondary)
}.buttonStyle(.plain).help("Поиск").accessibilityLabel("Поиск")
} else { modeCircle(mode, selected: true) }
if case .received(let summary) = SpotlightHeaderContent.resolve(targeted: false, mode: mode, files: store.pendingFiles.map(\.lastPathComponent)) {
Text(summary).font(.system(size: 20)).lineLimit(1)
.frame(maxWidth: .infinity, alignment: .leading)
.accessibilityLabel("Получены файлы: " + summary)
} else {
TextField(mode.placeholder, text: $input).textFieldStyle(.plain)
.font(.system(size: 26)).focused($inputFocused).onSubmit { performAction() }
.disabled(mode == .files || mode == .settings).accessibilityLabel(mode.placeholder)
}
if store.busy { ProgressView().controlSize(.small) }
}
}.padding(.leading, mode == .search || targeted ? 22 : 11).padding(.trailing, 20)
.frame(maxWidth: .infinity).frame(height: 64)
.modifier(SpotlightCapsule(id: "search", namespace: glassNamespace))
if !targeted {
ForEach(SpotlightGlassLayout.externalModes(selected: mode), id: \.self) { option in
modeCircle(option, selected: false)
}
}
}.contextMenu {
Button("Очередь и результаты") { show("queue") }
Button("Выйти") { NSApp.terminate(nil) }.keyboardShortcut("q")
}
}
private func modeCircle(_ option: SpotlightMode, selected: Bool) -> some View {
Button { select(selected ? .search : option) } label: {
Image(systemName: option.symbol).font(.system(size: 17))
.frame(width: 42, height: 42).contentShape(Circle())
}.buttonStyle(.plain)
.modifier(SpotlightCapsule(id: "mode-" + option.rawValue, namespace: glassNamespace, circle: true))
.help(selected ? "Вернуться к поиску" : option.rawValue)
.accessibilityLabel(selected ? option.rawValue + ", вернуться к поиску" : option.rawValue)
.accessibilityAddTraits(selected ? .isSelected : [])
}
@ViewBuilder private var expansion: some View {
switch mode {
case .search: EmptyView()
case .link:
Text("Добавь ссылку, название или короткий текст в строку сверху.").font(.callout).foregroundStyle(.secondary)
Text("Модель исследует тему с вебом. Получение полного текста страницы или видео не гарантируется.")
.font(.caption).foregroundStyle(.secondary)
Button("Исследовать и добавить") { performAction() }.buttonStyle(.borderedProminent).disabled(store.busy || input.isEmpty)
case .files:
filePreview
case .clipboard:
if !clipboard.files.isEmpty {
Text("Файлы из буфера").font(.headline)
ScrollView {
VStack(alignment: .leading, spacing: 8) {
ForEach(clipboard.files, id: \.self) { file in
Label(file.lastPathComponent, systemImage: "doc").lineLimit(1)
}
}.frame(maxWidth: .infinity, alignment: .leading)
}.frame(maxHeight: 115)
} else if !clipboard.text.isEmpty {
Text("Прочитано по нажатию «Буфер»").font(.caption).foregroundStyle(.secondary)
ScrollView { Text(clipboard.text).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading) }.frame(maxHeight: 100)
} else { Text("В буфере нет текста или файлов.").foregroundStyle(.secondary) }
HStack {
Button("Прочитать снова") { select(.clipboard) }
Spacer()
Button("Добавить в память") { performAction() }.buttonStyle(.borderedProminent)
.disabled(store.busy || (clipboard.files.isEmpty && input.isEmpty))
}
case .settings:
SettingsView(embedded: true).frame(height: 390)
}
}
private var filePreview: some View {
VStack(alignment: .leading, spacing: 12) {
if store.pendingFiles.isEmpty {
Label("Перенеси файлы в это окно", systemImage: "tray.and.arrow.down").font(.headline)
} else {
ScrollView {
VStack(alignment: .leading, spacing: 8) {
ForEach(store.pendingFiles, id: \.self) { file in
Label(file.lastPathComponent, systemImage: "doc").lineLimit(1).help(file.path)
}
}.frame(maxWidth: .infinity, alignment: .leading)
}.frame(maxHeight: 115)
Text("Оригиналы останутся на месте.").font(.caption).foregroundStyle(.secondary)
}
HStack {
Button("Выбрать файлы…") { store.chooseFiles() }.keyboardShortcut("o")
if !store.pendingFiles.isEmpty {
Button("Убрать") { store.pendingFiles = [] }
Spacer()
Button("Обработать") { performAction() }.buttonStyle(.borderedProminent).disabled(store.busy)
}
}
}
}
private func select(_ option: SpotlightMode) {
mode = option; validation = nil
if let preview = ClipboardPreview.onSelection(option, read: {
let pasteboard = NSPasteboard.general
let urls = pasteboard.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL] ?? []
return ClipboardPreview(text: urls.isEmpty ? pasteboard.string(forType: .string) ?? pasteboard.string(forType: .URL) ?? "" : "", files: urls)
}) {
clipboard = preview
input = preview.text
}
if option != .files && option != .settings { inputFocused = true }
}
private func performAction() {
guard !store.busy else { return }
guard store.configured else { mode = .settings; return }
validation = nil
let files = mode == .files ? store.pendingFiles : mode == .clipboard ? clipboard.files : []
if !files.isEmpty {
confirmedFiles = files; confirmedRequest = nil; confirmExternal = true; return
}
guard let request = SpotlightRequest.resolve(mode: mode, input: input) else {
if input.utf8.count > 8192 { validation = "Текст больше 8 КиБ. Сохрани его в файл и добавь через «Файлы»." }
return
}
confirmedFiles = []; confirmedRequest = request
if request.kind == "ingest" || store.deep { confirmExternal = true }
else { sendConfirmed() }
}
private func sendConfirmed() {
let files = confirmedFiles, request = confirmedRequest
let executionMode = !files.isEmpty || request?.kind == "ingest" || store.deep ? "deep" : "local"
Task {
if !files.isEmpty { await store.submit(kind: "ingest", mode: "deep", files: files) }
else if let request { await store.submit(kind: request.kind, query: request.query, mode: executionMode, text: request.text) }
else { return }
if store.error == nil && !files.isEmpty { store.pendingFiles = [] }
show(store.error == nil && files.isEmpty && request?.kind != "ingest" ? "result" : "queue")
}
}
private func show(_ id: String) { panel.window?.close(); store.openWindow?(id) }
}
private struct SpotlightSizeKey: PreferenceKey {
static var defaultValue: CGSize = .zero
static func reduce(value: inout CGSize, nextValue: () -> CGSize) { value = nextValue() }
}
struct SearchRequest: Equatable {
let kind: String
let query: String
static func parse(_ input: String) -> SearchRequest {
let text = input.trimmingCharacters(in: .whitespacesAndNewlines)
let prefix = "сделай справку"
let lower = text.lowercased()
if lower == prefix || lower.hasPrefix(prefix + " ") || lower.hasPrefix(prefix + ":") || lower.hasPrefix(prefix + "\n") {
let topic = String(text.dropFirst(prefix.count)).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines.union(CharacterSet(charactersIn: ":")))
return .init(kind: "brief", query: topic.isEmpty ? text : topic)
}
return .init(kind: "search", query: text)
}
}
struct QueueView: View {
@EnvironmentObject var store: Store
var body: some View {
VStack(alignment: .leading, spacing: 16) {
HStack {
Text("Очередь").font(.title2.weight(.semibold))
Spacer()
Button { Task { await store.refresh() } } label: { Image(systemName: "arrow.clockwise") }
.accessibilityLabel("Обновить очередь")
}.padding(12).modifier(ReadablePlate())
if let error = store.error {
HStack {
Text(error).foregroundStyle(.red).textSelection(.enabled)
Button("Скрыть") { store.error = nil }
}.padding(12).modifier(GlassPlate())
}
if store.jobs.isEmpty {
ContentUnavailableView("Пока нет задач", systemImage: "tray", description: Text("Добавь файлы или задай вопрос через значок в строке меню."))
.modifier(ReadablePlate())
} else {
ScrollView {
LazyVStack(alignment: .leading, spacing: 10) {
ForEach(Array(store.jobs.sorted { ($0.created_at ?? "") > ($1.created_at ?? "") }.prefix(20))) { job in
HStack(spacing: 0) {
Button {
store.selectedID = job.id; store.openWindow?("result")
} label: {
VStack(alignment: .leading, spacing: 5) {
Text(job.title).lineLimit(2).frame(maxWidth: .infinity, alignment: .leading)
Text(job.statusLabel).font(.caption).foregroundStyle(.secondary)
if let error = job.error { Text(error.message).font(.caption).foregroundStyle(.red).lineLimit(3) }
}.padding(14).contentShape(Rectangle())
}.buttonStyle(.plain).accessibilityLabel("\(job.title), \(job.statusLabel), открыть")
.accessibilityValue(job.error?.message ?? "")
if job.active {
Button("Отменить") { Task { await store.action("cancel", id: job.id) } }
.padding(.trailing, 14)
} else if ["failed", "cancelled"].contains(job.status) {
Button("Повторить") { Task { await store.action("retry", id: job.id) } }
.padding(.trailing, 14)
}
}.modifier(GlassPlate())
}
}
}
}
}.padding(22).frame(minWidth: 460, minHeight: 320)
.modifier(GlassWindow())
.task {
while !Task.isCancelled {
await store.refresh()
try? await Task.sleep(for: .seconds(2))
}
}
}
}
@MainActor
final class MenuPanelWindow {
weak var window: NSWindow?
}
struct MenuPanelAnchor: NSViewRepresentable {
let panel: MenuPanelWindow
func makeNSView(context: Context) -> NSView { Anchor(panel: panel) }
func updateNSView(_ nsView: NSView, context: Context) {}
private final class Anchor: NSView {
let panel: MenuPanelWindow
init(panel: MenuPanelWindow) { self.panel = panel; super.init(frame: .zero) }
required init?(coder: NSCoder) { fatalError("Use init(panel:)") }
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
panel.window = window
window?.isReleasedWhenClosed = false
// MenuBarExtra owns a nonactivating NSPanel. Make it key without
// activating the whole app so normal typing reaches the search field.
if window?.isVisible == true { window?.makeKey() }
}
}
}
struct ResultView: View {
@EnvironmentObject var store: Store
var body: some View {
Group {
if let job = store.selected {
ScrollView {
VStack(alignment: .leading, spacing: 16) {
Text(job.title).font(.title2).textSelection(.enabled)
Text(job.statusLabel).foregroundStyle(.secondary)
if let error = job.error { Text(error.message).foregroundStyle(.red).textSelection(.enabled) }
if let text = job.result?.text { MarkdownContent(text: text) }
if let report = job.result?.report_path, report.hasPrefix("/") {
Button("Открыть справку") { NSWorkspace.shared.open(URL(fileURLWithPath: report)) }
}
if let sources = job.result?.sources, !sources.isEmpty {
Divider(); Text("Источники").font(.headline)
ForEach(Array(sources.enumerated()), id: \.offset) { _, source in
if let url = source.target {
Button(source.title ?? source.path ?? source.url ?? "Источник") { NSWorkspace.shared.open(url) }
} else { Text(source.title ?? "Источник без ссылки") }
}
}
if job.active { ProgressView("Задача продолжается. Окно можно закрыть.") }
}.padding(20).modifier(ReadablePlate(cornerRadius: 16)).padding(20)
}
} else { ContentUnavailableView("Выбери задачу", systemImage: "doc.text.magnifyingglass", description: Text("Открой результат из очереди в строке меню.")).modifier(ReadablePlate()).padding(20) }
}.frame(minWidth: 500, minHeight: 350)
.modifier(GlassWindow())
.task {
while !Task.isCancelled {
await store.refresh()
try? await Task.sleep(for: .seconds(2))
}
}
}
}
struct SettingsView: View {
var embedded = false
@EnvironmentObject var store: Store
@State private var providers: [CLIProvider] = []
@State private var providerError: String?
@ViewBuilder var body: some View {
if embedded { settingsContent }
else { settingsContent.modifier(GlassWindow()) }
}
private var settingsContent: some View {
ScrollView {
VStack(alignment: .leading, spacing: 20) {
Text("Настройки").font(.title2.weight(.semibold))
LabeledContent("Папка Mnemazine") {
VStack(alignment: .leading) {
Text(store.repository.isEmpty ? "Не выбрана" : store.repository)
.font(.caption).lineLimit(2).truncationMode(.middle)
.textSelection(.enabled).help(store.repository)
Button("Выбрать папку…") { store.chooseRepository() }
}
}
LabeledContent("Node.js") {
VStack(alignment: .leading) {
Text(store.node.isEmpty ? "Не найден" : store.node)
.font(.caption).lineLimit(2).truncationMode(.middle)
.textSelection(.enabled).help(store.node)
Button("Выбрать Node.js…") { store.chooseNode() }
}
}
Toggle("Глубокий поиск с AI", isOn: $store.deep)
VStack(alignment: .leading, spacing: 10) {
HStack {
Text("Установленные CLI").font(.headline)
Spacer()
Button("Обновить") { Task { await refreshProviders() } }
}
ForEach(providers) { provider in
HStack {
Text(provider.name)
Spacer()
Text(provider.status).font(.caption).foregroundStyle(.secondary)
}
}
if let providerError { Text(providerError).font(.caption).foregroundStyle(.red) }
Text("При лимите используется следующий разрешённый CLI. Неизвестные программы без адаптера не запускаются. Доступность модели и авторизация проверяются при работе.")
.font(.caption).foregroundStyle(.secondary)
}
Text("Перед каждым AI-запросом появится подтверждение передачи запроса и фрагментов памяти. После перезапуска поиск снова локальный.")
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
Text("Обработка файлов использует настроенный pipeline Mnemazine и может обращаться к внешним AI-сервисам. Поиск по умолчанию локальный.")
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
}.padding(20).modifier(ReadablePlate(cornerRadius: 16)).padding(20)
}.frame(minWidth: embedded ? 0 : 520, minHeight: embedded ? 0 : 420)
.task { await refreshProviders() }
}
func refreshProviders() async {
do {
providers = try await Backend.run(repository: store.repository, node: store.node,
args: ["scripts/mnemazine-cli-discover.mjs"]).providers ?? []
providerError = nil
} catch { providerError = error.localizedDescription }
}
}
@@ -0,0 +1,32 @@
import AppKit
enum MnemazineMark {
static func image() -> NSImage {
// Approved option 5: eight nodes and nine bonds, extended horizontally.
let image = NSImage(size: NSSize(width: 32, height: 18), flipped: false) { _ in
let nodes: [NSPoint] = [.init(x: 3, y: 13), .init(x: 3, y: 5),
.init(x: 9, y: 9), .init(x: 17, y: 13),
.init(x: 17, y: 5), .init(x: 24, y: 9),
.init(x: 29, y: 13), .init(x: 29, y: 5)]
NSColor.black.setStroke()
let links = NSBezierPath()
links.lineWidth = 1
links.lineCapStyle = .round
for (a, b) in [(0, 2), (1, 2), (2, 3), (2, 4), (3, 4),
(3, 6), (4, 5), (5, 6), (5, 7)] {
links.move(to: nodes[a]); links.line(to: nodes[b])
}
links.stroke()
NSColor.black.setFill()
for node in nodes {
let radius: CGFloat = 1.5
NSBezierPath(ovalIn: NSRect(x: node.x - radius, y: node.y - radius,
width: radius * 2, height: radius * 2)).fill()
}
return true
}
image.isTemplate = true
image.accessibilityDescription = "Мнемозина: граф памяти"
return image
}
}
@@ -0,0 +1,26 @@
import SwiftUI
struct SpotlightCapsule: ViewModifier {
let id: String
let namespace: Namespace.ID
var circle = false
@Environment(\.accessibilityReduceTransparency) private var reduceTransparency
@Environment(\.accessibilityReduceMotion) private var reduceMotion
func body(content: Content) -> some View {
if reduceTransparency {
content.background(Color(nsColor: .windowBackgroundColor), in: RoundedRectangle(cornerRadius: circle ? 21 : 32))
} else if #available(macOS 26.0, *) {
if circle {
content.glassEffect(.regular.interactive(), in: .circle)
.glassEffectID(id, in: namespace)
.glassEffectTransition(reduceMotion ? .identity : .matchedGeometry)
} else {
content.glassEffect(.regular, in: .capsule)
.glassEffectID(id, in: namespace)
.glassEffectTransition(reduceMotion ? .identity : .matchedGeometry)
}
} else {
content.background(.regularMaterial, in: RoundedRectangle(cornerRadius: circle ? 21 : 32))
}
}
}
@@ -0,0 +1,65 @@
import Foundation
enum SpotlightGlassLayout {
static func externalModes(selected: SpotlightMode) -> [SpotlightMode] {
[.link, .files, .clipboard, .settings].filter { $0 != selected }
}
}
enum SpotlightHeaderContent: Equatable {
case input, drop, received(String)
static func resolve(targeted: Bool, mode: SpotlightMode, files: [String]) -> SpotlightHeaderContent {
if targeted { return .drop }
guard mode == .files, let first = files.first else { return .input }
return .received(files.count == 1 ? first : "\(first) и ещё \(files.count - 1)")
}
}
enum SpotlightMode: String, CaseIterable {
case search = "Поиск", link = "Ссылка", files = "Файлы", clipboard = "Буфер", settings = "Настройки"
var symbol: String {
switch self {
case .search: return "magnifyingglass"
case .link: return "link"
case .files: return "folder"
case .clipboard: return "doc.on.clipboard"
case .settings: return "gearshape"
}
}
var placeholder: String {
switch self {
case .search: return "Поиск в памяти"
case .link: return "Ссылка или название"
case .files: return "Добавить файлы"
case .clipboard: return "Текст из буфера"
case .settings: return "Настройки Мнемозины"
}
}
}
struct ClipboardPreview: Equatable {
var text: String = ""
var files: [URL] = []
static func onSelection(_ mode: SpotlightMode, read: () -> ClipboardPreview) -> ClipboardPreview? {
mode == .clipboard ? read() : nil
}
}
struct SpotlightRequest: Equatable {
let kind: String
var query: String? = nil
var text: String? = nil
static func resolve(mode: SpotlightMode, input: String) -> SpotlightRequest? {
let input = input.trimmingCharacters(in: .whitespacesAndNewlines)
guard !input.isEmpty else { return nil }
switch mode {
case .search:
let search = SearchRequest.parse(input)
return .init(kind: search.kind, query: search.query)
case .link, .clipboard:
guard input.utf8.count <= 8192 else { return nil }
return .init(kind: "ingest", text: input)
case .files, .settings: return nil
}
}
}
@@ -0,0 +1,126 @@
import AppKit
import SwiftUI
@MainActor
final class StatusAppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {
private let store = Store()
private var statusItem: NSStatusItem?
private var panel: SearchPanel?
private var windows: [String: NSWindow] = [:]
func applicationDidFinishLaunching(_ notification: Notification) {
NSApp.setActivationPolicy(.accessory)
store.openWindow = { [weak self] id in self?.showWindow(id) }
store.panelSizeChanged = { [weak self] size in self?.resizePanel(size) }
let item = NSStatusBar.system.statusItem(withLength: 40)
item.button?.image = MnemazineMark.image()
item.button?.image?.isTemplate = true
item.button?.target = self
item.button?.action = #selector(togglePanel)
item.button?.setAccessibilityLabel("Мнемозина")
statusItem = item
DispatchQueue.main.async { [weak self] in self?.showPanel() }
}
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
showPanel()
return false
}
@objc private func togglePanel() {
if panel?.isVisible == true { panel?.orderOut(nil); return }
showPanel()
}
private func showPanel() {
let panel = panel ?? makePanel()
let screen = statusItem?.button?.window?.screen?.visibleFrame ?? NSScreen.main?.visibleFrame ?? .zero
let top = screen.maxY - min(140, screen.height * 0.18)
let origin = NSPoint(x: screen.midX - panel.frame.width / 2,
y: max(screen.minY + 16, top - panel.frame.height))
panel.setFrameOrigin(origin)
let animate = !panel.isVisible && !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion
panel.alphaValue = animate ? 0 : 1
panel.orderFrontRegardless()
panel.makeKey()
if animate {
NSAnimationContext.runAnimationGroup { context in
context.duration = 0.18
panel.animator().alphaValue = 1
}
}
Task { await store.refresh() }
}
private func resizePanel(_ size: CGSize) {
guard let panel, size.width.isFinite, size.height.isFinite, size.width > 0, size.height > 0 else { return }
let screen = panel.screen?.visibleFrame ?? NSScreen.main?.visibleFrame ?? .zero
let width = min(size.width, max(320, screen.width - 32))
let height = min(size.height, max(200, screen.height - 48))
guard abs(panel.frame.width - width) > 0.5 || abs(panel.frame.height - height) > 0.5 else { return }
let top = panel.frame.maxY
panel.setFrame(NSRect(x: min(max(panel.frame.midX - width / 2, screen.minX + 16), screen.maxX - width - 16),
y: max(screen.minY + 16, top - height), width: width, height: height), display: true)
}
private func makePanel() -> SearchPanel {
let view = NSHostingView(rootView: MenuPanel().environmentObject(store))
let panel = SearchPanel(contentRect: NSRect(x: 0, y: 0, width: 640, height: 160),
styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
panel.isOpaque = false
panel.backgroundColor = .clear
panel.hasShadow = false
panel.isReleasedWhenClosed = false
panel.hidesOnDeactivate = false
// Keep the drop target visible while the user grabs a file in Finder.
// Only Escape, the status button, or explicit navigation hides it.
panel.level = .statusBar
panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
panel.contentView = view
panel.setContentSize(view.fittingSize)
self.panel = panel
return panel
}
private func showWindow(_ id: String) {
panel?.orderOut(nil)
if let window = windows[id] {
window.makeKeyAndOrderFront(nil); NSApp.activate(ignoringOtherApps: true); return
}
let content: AnyView
let title: String
let size: NSSize
switch id {
case "settings":
content = AnyView(SettingsView().environmentObject(store)); title = "Мнемозина · настройки"; size = .init(width: 560, height: 370)
case "queue":
content = AnyView(QueueView().environmentObject(store)); title = "Мнемозина · очередь"; size = .init(width: 560, height: 460)
default:
content = AnyView(ResultView().environmentObject(store)); title = "Мнемозина · результат"; size = .init(width: 760, height: 640)
}
let window = NSWindow(contentRect: NSRect(origin: .zero, size: size),
styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false)
window.title = title
configureGlassWindow(window, opaque: NSWorkspace.shared.accessibilityDisplayShouldReduceTransparency)
window.delegate = self
window.contentView = NSHostingView(rootView: content)
windows[id] = window
window.center()
window.makeKeyAndOrderFront(nil)
NSApp.activate(ignoringOtherApps: true)
}
func windowWillClose(_ notification: Notification) {
guard let window = notification.object as? NSWindow,
let id = windows.first(where: { $0.value === window })?.key else { return }
window.contentView = nil
windows.removeValue(forKey: id)
}
}
private final class SearchPanel: NSPanel {
override var canBecomeKey: Bool { true }
override var canBecomeMain: Bool { false }
override func cancelOperation(_ sender: Any?) { orderOut(nil) }
}
@@ -0,0 +1,23 @@
import XCTest
@testable import Mnemazine
final class AccessibilityLabelTests: XCTestCase {
func testApprovedGraphMarkIsWideAndAdaptsToMenuAppearance() {
let image = MnemazineMark.image()
XCTAssertEqual(image.size.width, 32)
XCTAssertEqual(image.size.height, 18)
XCTAssertTrue(image.isTemplate)
XCTAssertEqual(image.accessibilityDescription, "Мнемозина: граф памяти")
}
func testFileActionLabelMatchesActionAndSettingsTakePrecedence() {
XCTAssertEqual(fileActionAccessibilityLabel(configured: false, pendingCount: 0),
"Открыть настройки Мнемозины")
XCTAssertEqual(fileActionAccessibilityLabel(configured: false, pendingCount: 3),
"Открыть настройки Мнемозины")
XCTAssertEqual(fileActionAccessibilityLabel(configured: true, pendingCount: 0),
"Добавить файлы: перенеси сюда или нажми для выбора")
XCTAssertEqual(fileActionAccessibilityLabel(configured: true, pendingCount: 3),
"Обработать файлы: 3")
}
}
@@ -0,0 +1,33 @@
import XCTest
@testable import Mnemazine
final class BackendTests: XCTestCase {
func testTextIntakeArgumentsAndSnapshotWithoutOriginal() throws {
let input = "https://www.youtube.com/watch?v=abc&list=123"
XCTAssertEqual(Backend.arguments("submit", kind: "ingest", mode: "deep", text: input),
["scripts/mnemazine-jobs.mjs", "submit", "--kind", "ingest", "--text", input, "--mode", "deep"])
let data = Data(#"{"job":{"id":"url-job","kind":"ingest","status":"queued","input_text":"Название видео","files":[{"name":"research-request.md","snapshot":"/tmp/source.md"}]}}"#.utf8)
let job = try JSONDecoder().decode(Envelope.self, from: data).job!
XCTAssertEqual(job.title, "Название видео")
XCTAssertNil(job.files?.first?.original)
}
func testArgumentsKeepUntrustedTextAsSingleArgument() {
let query = "строка с пробелом; $(touch /tmp/no)\nещё"
XCTAssertEqual(Backend.arguments("submit", kind: "brief", query: query),
["scripts/mnemazine-jobs.mjs", "submit", "--kind", "brief", "--query", query, "--mode", "local"])
XCTAssertEqual(Backend.arguments("submit", kind: "ingest", mode: "deep", files: [URL(fileURLWithPath: "/tmp/мой файл.pdf")]).suffix(4),
["--mode", "deep", "--file", "/tmp/мой файл.pdf"])
}
func testCompletedAndFailedEnvelopes() throws {
let data = Data(#"{"jobs":[{"id":"a","kind":"brief","status":"completed","result":{"text":"ответ","sources":["/tmp/a.md",{"title":"web","url":"https://example.com"}]}},{"id":"b","kind":"ingest","status":"failed","files":[{"name":"файл.pdf","original":"/tmp/файл.pdf","snapshot":"/tmp/job/файл.pdf","sha256":"abc"}],"error":{"message":"отказ","code":3}}]}"#.utf8)
let jobs = try JSONDecoder().decode(Envelope.self, from: data).jobs!
XCTAssertEqual(jobs[0].result?.sources?.first?.target?.path, "/tmp/a.md")
XCTAssertEqual(jobs[1].error?.message, "отказ")
XCTAssertFalse(jobs[1].active)
XCTAssertEqual(jobs[1].title, "файл.pdf")
let unsafe = try JSONDecoder().decode(Source.self, from: Data(#"{"url":"file:///etc/passwd"}"#.utf8))
XCTAssertNil(unsafe.target)
let executable = try JSONDecoder().decode(Source.self, from: Data(#"{"path":"/tmp/run.command"}"#.utf8))
XCTAssertNil(executable.target)
}
}
@@ -0,0 +1,14 @@
import XCTest
@testable import Mnemazine
final class MarkdownTests: XCTestCase {
func testReportBlocksAndUnclosedFence() {
let blocks = MarkdownBlock.parse("# Справка\n\nАбзац **жирный**\n\n- пункт\n> цитата\n```swift\nlet x = 1")
XCTAssertEqual(blocks.map(\.kind), [.heading(1), .paragraph, .item, .quote, .code])
XCTAssertEqual(blocks.last?.text, "let x = 1")
}
func testUnsafeLinksArePlainText() {
let text = MarkdownBlock.inline("[плохой](file:///tmp/run.command) [сайт](https://example.com)")
XCTAssertEqual(text.runs.compactMap(\.link), [URL(string: "https://example.com")!])
}
}
@@ -0,0 +1,16 @@
import Foundation
import XCTest
final class PanelPersistenceTests: XCTestCase {
func testFinderDragDoesNotDismissPanel() throws {
// Regression: an outside-click monitor dismissed the target before a
// Finder drag could reach it. Guard the presentation boundary itself.
let package = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
let source = try String(contentsOf: package.appendingPathComponent("Sources/Mnemazine/StatusAppDelegate.swift"), encoding: .utf8)
XCTAssertFalse(source.contains("addGlobalMonitorForEvents"))
XCTAssertFalse(source.contains("addLocalMonitorForEvents"))
XCTAssertTrue(source.contains("panel.hidesOnDeactivate = false"))
XCTAssertTrue(source.contains(".nonactivatingPanel"))
XCTAssertTrue(source.contains("override func cancelOperation"))
}
}
@@ -0,0 +1,11 @@
import XCTest
@testable import Mnemazine
final class SearchRequestTests: XCTestCase {
func testExplicitBriefPrefix() {
XCTAssertEqual(SearchRequest.parse(" Сделай справку: про память "), .init(kind: "brief", query: "про память"))
XCTAssertEqual(SearchRequest.parse("СДЕЛАЙ СПРАВКУ\nисточники"), .init(kind: "brief", query: "источники"))
XCTAssertEqual(SearchRequest.parse("найди информацию"), .init(kind: "search", query: "найди информацию"))
XCTAssertEqual(SearchRequest.parse("сделай справкуXYZ"), .init(kind: "search", query: "сделай справкуXYZ"))
}
}
@@ -0,0 +1,37 @@
import XCTest
@testable import Mnemazine
final class SpotlightModeTests: XCTestCase {
func testSelectedGlassControlHasOnePosition() {
XCTAssertEqual(SpotlightGlassLayout.externalModes(selected: .search), [.link, .files, .clipboard, .settings])
for selected in [SpotlightMode.link, .files, .clipboard, .settings] {
XCTAssertEqual(SpotlightGlassLayout.externalModes(selected: selected).count, 3)
XCTAssertFalse(SpotlightGlassLayout.externalModes(selected: selected).contains(selected))
}
}
func testDropPreviewReturnsToReceivedFileWithoutClipboardRead() {
XCTAssertEqual(SpotlightHeaderContent.resolve(targeted: true, mode: .clipboard, files: []), .drop)
XCTAssertEqual(SpotlightHeaderContent.resolve(targeted: false, mode: .files, files: ["paper.pdf"]), .received("paper.pdf"))
XCTAssertEqual(SpotlightHeaderContent.resolve(targeted: false, mode: .files, files: ["a.md", "b.md"]), .received("a.md и ещё 1"))
XCTAssertEqual(SpotlightHeaderContent.resolve(targeted: false, mode: .search, files: ["a.md"]), .input)
}
func testClipboardOnlyReadsOnExplicitSelection() {
var reads = 0
let read = { reads += 1; return ClipboardPreview(text: "секрет") }
for mode in [SpotlightMode.search, .link, .files, .settings] {
XCTAssertNil(ClipboardPreview.onSelection(mode, read: read))
}
XCTAssertEqual(reads, 0)
XCTAssertEqual(ClipboardPreview.onSelection(.clipboard, read: read)?.text, "секрет")
XCTAssertEqual(reads, 1)
}
func testExplicitModeDispatch() {
XCTAssertEqual(SpotlightRequest.resolve(mode: .search, input: "Сделай справку: память")?.kind, "brief")
XCTAssertEqual(SpotlightRequest.resolve(mode: .link, input: "https://example.com"), .init(kind: "ingest", text: "https://example.com"))
XCTAssertEqual(SpotlightRequest.resolve(mode: .clipboard, input: "короткий текст")?.kind, "ingest")
XCTAssertNil(SpotlightRequest.resolve(mode: .files, input: "не отправлять"))
XCTAssertNil(SpotlightRequest.resolve(mode: .settings, input: "не отправлять"))
XCTAssertNil(SpotlightRequest.resolve(mode: .clipboard, input: String(repeating: "я", count: 4097)))
XCTAssertNotNil(SpotlightRequest.resolve(mode: .clipboard, input: String(repeating: "я", count: 4096)))
}
}
@@ -0,0 +1,84 @@
import AppKit
import SwiftUI
import XCTest
@testable import Mnemazine
final class WindowSurfaceTests: XCTestCase {
@MainActor
func testGlassCoversNativeTitlebarAndKeepsWindowControlsAfterResize() throws {
try XCTSkipIf(NSWorkspace.shared.accessibilityDisplayShouldReduceTransparency,
"Glass geometry requires transparency enabled; opaque backing is tested separately.")
let window = makeWindow()
defer { window.close() }
let host = NSHostingView(rootView: VStack {
ContentProbe().frame(height: 20)
Spacer()
}.modifier(GlassWindow()))
window.contentView = host
for size in [NSSize(width: 560, height: 370), NSSize(width: 740, height: 520)] {
window.setContentSize(size)
host.layoutSubtreeIfNeeded()
let surface = try XCTUnwrap(descendants(of: host).first { view in
if #available(macOS 26.0, *), view is NSGlassEffectView { return true }
return view is NSVisualEffectView
})
let surfaceRect = surface.convert(surface.bounds, to: nil)
let hostRect = host.convert(host.bounds, to: nil)
XCTAssertEqual(surfaceRect.minY, hostRect.minY, accuracy: 1)
XCTAssertEqual(surfaceRect.maxY, hostRect.maxY, accuracy: 1)
XCTAssertEqual(surfaceRect.width, hostRect.width, accuracy: 1)
XCTAssertGreaterThan(surfaceRect.maxY, window.contentLayoutRect.maxY)
let close = try XCTUnwrap(window.standardWindowButton(.closeButton))
XCTAssertTrue(surfaceRect.contains(close.convert(close.bounds, to: nil)))
let content = try XCTUnwrap(descendants(of: host).first { $0 is ContentProbe.View })
XCTAssertLessThanOrEqual(content.convert(content.bounds, to: nil).maxY,
window.contentLayoutRect.maxY + 1, "Content must stay below native window controls")
if #available(macOS 26.0, *), let glass = surface as? NSGlassEffectView {
XCTAssertEqual(glass.cornerRadius, 16)
XCTAssertEqual(glass.style, .regular)
} else {
XCTAssertEqual(surface.layer?.cornerRadius, 16)
XCTAssertEqual(surface.layer?.masksToBounds, true)
}
}
XCTAssertTrue(window.styleMask.contains([.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView]))
XCTAssertTrue(window.isMovable)
XCTAssertNotNil(window.standardWindowButton(.miniaturizeButton))
XCTAssertNotNil(window.standardWindowButton(.zoomButton))
}
@MainActor
func testReduceTransparencyChangesBackingWithoutRemovingNativeChrome() {
let window = makeWindow()
defer { window.close() }
configureGlassWindow(window, opaque: true)
XCTAssertTrue(window.isOpaque)
XCTAssertEqual(window.backgroundColor, .windowBackgroundColor)
XCTAssertTrue(window.styleMask.contains(.fullSizeContentView))
configureGlassWindow(window, opaque: false)
XCTAssertFalse(window.isOpaque)
XCTAssertEqual(window.backgroundColor, .clear)
XCTAssertNotNil(window.standardWindowButton(.closeButton))
}
@MainActor
private func makeWindow() -> NSWindow {
_ = NSApplication.shared
let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 560, height: 370),
styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false)
configureGlassWindow(window, opaque: false)
return window
}
@MainActor
private func descendants(of view: NSView) -> [NSView] {
view.subviews.flatMap { [$0] + descendants(of: $0) }
}
}
private struct ContentProbe: NSViewRepresentable {
final class View: NSView {}
func makeNSView(context: Context) -> View { View() }
func updateNSView(_ view: View, context: Context) {}
}