#if !APPSTORE import AppKit import SwiftUI import UserNotifications // MARK: - BrainRunner @MainActor final class BrainRunner: ObservableObject { static let shared = BrainRunner() @AppStorage("brainBinaryPath") var customPath: String = "" // Persisted across launches — skips file-candidate scan on subsequent starts @AppStorage("brainDiscoveredPath") private var discoveredPath: String = "" // In-process cache (avoids repeated isExecutableFile calls within a session) private var cachedPath: String? = nil private var discovered = false var binaryPath: String? { if !customPath.isEmpty && FileManager.default.isExecutableFile(atPath: customPath) { return customPath } if let c = cachedPath { return c } // Check persisted path from previous launch if !discoveredPath.isEmpty && FileManager.default.isExecutableFile(atPath: discoveredPath) { cachedPath = discoveredPath discovered = true return discoveredPath } return nil } var isInstalled: Bool { binaryPath != nil } // Run brain and return stdout as Data. Throws on non-zero exit. // `stdin`: what brain reads on its standard input (a secret, never put in the arguments). func run(_ args: [String], stdin: Data? = nil) async throws -> Data { let bin = try await resolvedBinary() return try await Task.detached(priority: .userInitiated) { let proc = Process() // brain's native module only loads in the Node that installed it: `npm run build` writes // that Node's path next to cli.js (dist/node-path). Run with it when it's there, never // with whichever `node` comes first in the app's PATH. let cli = URL(fileURLWithPath: bin).resolvingSymlinksInPath() let pinned = (try? String(contentsOf: cli.deletingLastPathComponent().appendingPathComponent("node-path"), encoding: .utf8))? .trimmingCharacters(in: .whitespacesAndNewlines) if let node = pinned, FileManager.default.isExecutableFile(atPath: node) { proc.executableURL = URL(fileURLWithPath: node) proc.arguments = [cli.path] + args } else { proc.executableURL = URL(fileURLWithPath: bin) proc.arguments = args } // A Mac app gets a bare PATH: give brain its node (next to the binary) and `claude`. var env = ProcessInfo.processInfo.environment let home = NSHomeDirectory() let nodeDir = pinned.map { URL(fileURLWithPath: $0).deletingLastPathComponent().path } env["PATH"] = ([nodeDir, URL(fileURLWithPath: bin).deletingLastPathComponent().path, "\(home)/.local/bin", "\(home)/.claude/local", "/opt/homebrew/bin", "/usr/local/bin", env["PATH"] ?? "/usr/bin:/bin"] as [String?]).compactMap { $0 }.joined(separator: ":") proc.environment = env let pipe = Pipe() proc.standardOutput = pipe proc.standardError = FileHandle.nullDevice let input = stdin.map { _ in Pipe() } if let input { proc.standardInput = input } try proc.run() if let input, let stdin { input.fileHandleForWriting.write(stdin) try? input.fileHandleForWriting.close() } // Read before waiting: a big output would otherwise fill the pipe and block both sides. let out = pipe.fileHandleForReading.readDataToEndOfFile() proc.waitUntilExit() guard proc.terminationStatus == 0 else { throw BrainError.nonZeroExit(Int(proc.terminationStatus)) } return out }.value } func run(_ args: [String], stdin: Data? = nil, as type: T.Type) async throws -> T { let data = try await run(args, stdin: stdin) return try JSONDecoder().decode(type, from: data) } // Called once at app start to prime the cache func discoverAsync() { guard !discovered else { return } let custom = customPath Task.detached(priority: .background) { [weak self] in let found = Self.findBinary(customPath: custom) await MainActor.run { [weak self] in self?.cachedPath = found if let f = found { self?.discoveredPath = f } self?.discovered = true } } } // MARK: - Private helpers private func resolvedBinary() async throws -> String { if let bin = binaryPath { return bin } // Not yet cached — discover now on background thread let custom = customPath let found = await Task.detached(priority: .userInitiated) { Self.findBinary(customPath: custom) }.value if let f = found { cachedPath = f discoveredPath = f discovered = true return f } throw BrainError.notInstalled } private nonisolated static func findBinary(customPath: String) -> String? { if !customPath.isEmpty && FileManager.default.isExecutableFile(atPath: customPath) { return customPath } let home = NSHomeDirectory() if let nvm = NvmBinaryLocator.find("brain", nvmDir: "\(home)/.nvm") { return nvm } let candidates = [ "/usr/local/bin/brain", "/opt/homebrew/bin/brain", ] for path in candidates where FileManager.default.isExecutableFile(atPath: path) { return path } return discoverViashell() } private nonisolated static func discoverViashell() -> String? { let proc = Process() proc.executableURL = URL(fileURLWithPath: "/bin/zsh") proc.arguments = ["-l", "-c", "which brain"] let pipe = Pipe() proc.standardOutput = pipe proc.standardError = Pipe() guard (try? proc.run()) != nil else { return nil } proc.waitUntilExit() guard proc.terminationStatus == 0 else { return nil } let out = String(data: pipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8)? .trimmingCharacters(in: .whitespacesAndNewlines) guard let path = out, !path.isEmpty, FileManager.default.isExecutableFile(atPath: path) else { return nil } return path } } enum BrainError: LocalizedError { case notInstalled case nonZeroExit(Int) var errorDescription: String? { switch self { case .notInstalled: return "brain binary not found" case .nonZeroExit(let code): return "brain exited with code \(code)" } } } // MARK: - Decodable models struct BrainSearchResult: Decodable, Identifiable { let id: String let titre: String let source: String let date: String let extrait: String let lien: String let projet: String let nbMentions: Int } struct BrainSearchResponse: Decodable { let total: Int let results: [BrainSearchResult] } /// `brain suggest --json`: what the search page shows before anything is typed. struct BrainSuggestions: Decodable { let recent: [BrainSearchResult] let searches: [String] } struct BrainMessage: Decodable { let role: String let text: String } struct BrainElement: Decodable { let kind: String let texte: String let statut: String? } struct BrainConversationDetail: Decodable { let id: String let titre: String let source: String let date: String let lien: String let projet: String let projets: [String] let messages: [BrainMessage] let elements: [BrainElement]? } struct BrainGraphNode: Decodable, Identifiable, Sendable { let id: String let kind: String let label: String let date: String? let projet: String? let x: Double? // pre-computed sphere position from brain let y: Double? let z: Double? } struct BrainGraphEdge: Decodable, Sendable { let from: String let to: String } /// `brain page --json`: everything memory knows about one star of the galaxy. struct BrainNodePage: Decodable { struct Section: Decodable { let title: String; let items: [String] } struct Source: Decodable { let id: String; let title: String; let date: String } let id: String let kind: String let title: String let date: String? let file: String? let link: String? let messages: Int? let firstRequest: String? let text: String? let reason: String? let summary: String? let sections: [Section] let sources: [Source] let projects: [String] } struct BrainGraphResponse: Decodable, Sendable { let nodes: [BrainGraphNode] let edges: [BrainGraphEdge] } struct BrainGroupe: Decodable { let titre: String let count: Int let freqJours: Double? let histogram: [Int] } struct BrainErreur: Decodable { let texte: String let statut: String let count: Int let derniereDate: String } struct BrainPatternConversation: Decodable, Hashable { let id: String let titre: String let date: String } /// A task you keep asking Claude to do, that could become a skill (`brain patterns`). struct BrainPattern: Decodable, Identifiable { let id: String let nom: String let description: String let projet: String let conversations: [BrainPatternConversation] /// Files of the project that show the task ("CLAUDE.md", "scripts/release.sh"…) let sources: [String]? let count: Int let freqJours: Double? let histogram: [Int] let skillPath: String? let skillName: String? let installe: Bool? } struct BrainPatternsResponse: Decodable { let generatedAt: String? let stale: Int /// The analysis should start by itself (never done, or something changed and the last run is old enough) let due: Bool? /// An analysis is already running (another window, the terminal) let running: Bool? /// The index could not be read: the patterns are the last ones found let error: String? let patterns: [BrainPattern] } /// What `brain patterns --json` prints when it fails. private struct BrainErrorReply: Decodable { let error: String } /// Finds by itself the tasks you keep doing with Claude that could become skills: when Memory opens /// and the last analysis is due, `brain patterns` reads the projects whose conversations or files /// changed, in the background. Shared by the Memory pages so a single run happens at a time. @MainActor final class SkillDetection: ObservableObject { static let shared = SkillDetection() @Published private(set) var result: BrainPatternsResponse? = nil @Published private(set) var running = false /// Why the last analysis failed (shown above the cards, which stay as they were) @Published private(set) var failure: String? = nil /// The last analysis, from the cache: instant, no Claude call. func load() async { if let r = try? await fetch(["patterns", "--json", "--cached"]) { result = r failure = r.error } } /// The reply, or the error brain printed (a JSON `{error}`), as a thrown message. private func fetch(_ args: [String]) async throws -> BrainPatternsResponse { let data = try await BrainRunner.shared.run(args) if let r = try? JSONDecoder().decode(BrainPatternsResponse.self, from: data) { return r } if let e = try? JSONDecoder().decode(BrainErrorReply.self, from: data) { throw PatternsFailure(message: e.error) } throw PatternsFailure(message: "brain patterns") } struct PatternsFailure: Error { let message: String } /// Called when a Memory page opens: analyses only if it is due. func runIfDue() async { guard !running else { return } await load() if result?.running == true { await waitForOtherRun() } else if result?.due == true { await analyze() } } /// Claude reads the projects whose conversations or files changed (all of them the first time). func analyze() async { guard !running else { return } running = true failure = nil let started = Date() // the arrow turns at least one full turn, even when brain answers at once do { let r = try await fetch(["patterns", "--json"]) result = r if r.running == true { await waitForOtherRun() } } catch let e as PatternsFailure { failure = e.message // the cards found before stay on the page } catch { failure = "brain patterns" } let shown = Date().timeIntervalSince(started) if shown < 1.1 { try? await Task.sleep(for: .seconds(1.1 - shown)) } running = false } /// Another run (the terminal, an older window) holds the lock: show it running, check back now and then. private func waitForOtherRun() async { running = true for _ in 0..<120 { try? await Task.sleep(for: .seconds(15)) await load() if result?.running != true { break } } running = false } } /// `brain skill` / `brain install-skill` reply: either the result or an error message. struct BrainSkillResult: Decodable { let name: String? let path: String? let markdown: String? let backup: String? let error: String? } struct BrainArtifact: Decodable { let kind: String let count: Int } struct BrainRecurrencesResponse: Decodable { let groupes: [BrainGroupe] let erreurs: [BrainErreur] let artifacts: [BrainArtifact] } struct BrainRawIndex: Decodable { let messages: Int let conversations: Int let sessions: Int } struct BrainStatus: Decodable { let depth: String let rawIndex: BrainRawIndex? let pause: String? let dailyLimit: Int let concurrency: Int } // MARK: - MemorySearchModel @MainActor final class MemorySearchModel: ObservableObject { @Published var query: String = "" @Published var filter: MemoryFilter = .all @Published var results: [BrainSearchResult] = [] @Published var total: Int = 0 @Published var offset: Int = 0 @Published var isLoading: Bool = false @Published var selected: BrainSearchResult? = nil @Published var detail: BrainConversationDetail? = nil @Published var detailLoading: Bool = false @Published var hasIndex: Bool = true /// Recent conversations and searches worth trying, shown while the field is empty @Published var suggestions: BrainSuggestions? = nil private var searchTask: Task? enum MemoryFilter: String, CaseIterable { case all, claude, code var label: String { switch self { case .all: return String(localized: "hub.memory.search.all") case .claude: return "Claude.ai" case .code: return "Claude Code" } } var source: String? { switch self { case .all: return nil case .claude: return "claude" case .code: return "code" } } } func search(loadMore: Bool = false) { searchTask?.cancel() let q = query.trimmingCharacters(in: .whitespaces) let lOffset = loadMore ? offset : 0 if !loadMore { results = [] total = 0 offset = 0 } guard !q.isEmpty else { return } isLoading = true searchTask = Task { var args = ["search", q, "--json", "--limit", "20", "--offset", "\(lOffset)"] if let src = filter.source { args += ["--source", src] } do { let resp = try await BrainRunner.shared.run(args, as: BrainSearchResponse.self) guard !Task.isCancelled else { return } if loadMore { results += resp.results } else { results = resp.results } total = resp.total offset = results.count hasIndex = true } catch BrainError.nonZeroExit { hasIndex = false } catch {} isLoading = false } } func loadSuggestions() { Task { if let s = try? await BrainRunner.shared.run(["suggest", "--json"], as: BrainSuggestions.self) { suggestions = s } } } /// A suggested search: fill the field and run it. func searchFor(_ text: String) { query = text search() } func loadDetail(_ result: BrainSearchResult) { selected = result detail = nil detailLoading = true Task { do { let d = try await BrainRunner.shared.run(["show", result.id, "--json"], as: BrainConversationDetail.self) detail = d } catch {} detailLoading = false } } func copyResumeCommand() { guard let sel = selected else { return } NSPasteboard.general.clearContents() NSPasteboard.general.setString("claude --resume \(sel.id)", forType: .string) } } // MARK: - HubMemorySearchPage struct HubMemorySearchPage: View { @StateObject private var model = MemorySearchModel() @ObservedObject private var runner = BrainRunner.shared @FocusState private var fieldFocused: Bool @State private var resumeCopied = false var body: some View { HStack(spacing: 0) { listPanel if model.selected != nil { Divider().background(HubTheme.line) detailPanel .frame(width: 350) } } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) .background(HubTheme.panel) .onAppear { // Check index Task { do { let status = try await BrainRunner.shared.run(["status", "--json"], as: BrainStatus.self) model.hasIndex = (status.rawIndex?.conversations ?? 0) > 0 } catch { model.hasIndex = false } if model.hasIndex { model.loadSuggestions() } // skills to suggest are looked for in the background when Memory opens, if it is due if model.hasIndex { await SkillDetection.shared.runIfDue() } } } .onKeyPress(.return) { model.search() return .handled } } // MARK: List panel @ViewBuilder private var listPanel: some View { VStack(alignment: .leading, spacing: 0) { // Hero HubHero(page: .memorySearch, title: String(localized: "hub.page.memory-search")) .padding(.horizontal, 28) .padding(.top, 24) if !runner.isInstalled { notInstalledCard } else if !model.hasIndex && model.results.isEmpty { noIndexCard } else { searchUI } } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) } @ViewBuilder private var notInstalledCard: some View { ScrollView { VStack(alignment: .leading, spacing: 16) { HubGlowCard(color: Color(hex: "#22D3EE")) { VStack(alignment: .leading, spacing: 12) { Text(String(localized: "hub.memory.not-installed")) .font(.system(size: 17, weight: .semibold)) Text(String(localized: "hub.memory.not-installed.detail")) .font(.system(size: 13)) .foregroundColor(HubTheme.secondary) Text(verbatim: "npm install -g coucou-brain") .font(.system(size: 13, design: .monospaced)) .padding(.horizontal, 12) .padding(.vertical, 8) .background(RoundedRectangle(cornerRadius: 8).fill(Color.white.opacity(0.07))) .textSelection(.enabled) Text(verbatim: "brain index") .font(.system(size: 13, design: .monospaced)) .padding(.horizontal, 12) .padding(.vertical, 8) .background(RoundedRectangle(cornerRadius: 8).fill(Color.white.opacity(0.07))) .textSelection(.enabled) } } } .padding(.horizontal, 28) .padding(.top, 20) } } @ViewBuilder private var noIndexCard: some View { ScrollView { VStack(alignment: .leading, spacing: 16) { HubCard { VStack(alignment: .leading, spacing: 12) { Text(String(localized: "hub.memory.index-missing")) .font(.system(size: 17, weight: .semibold)) Text(String(localized: "hub.memory.index-missing.detail")) .font(.system(size: 13)) .foregroundColor(HubTheme.secondary) Text(verbatim: "brain index") .font(.system(size: 13, design: .monospaced)) .padding(.horizontal, 12) .padding(.vertical, 8) .background(RoundedRectangle(cornerRadius: 8).fill(Color.white.opacity(0.07))) .textSelection(.enabled) } } } .padding(.horizontal, 28) .padding(.top, 20) } } @ViewBuilder private var searchUI: some View { VStack(alignment: .leading, spacing: 12) { // Search field HubField(placeholder: String(localized: "hub.memory.search.placeholder"), text: $model.query, onSubmit: { model.search() }) .focused($fieldFocused) .padding(.horizontal, 28) .padding(.top, 16) // Filter bar HStack(spacing: 6) { ForEach(MemorySearchModel.MemoryFilter.allCases, id: \.self) { f in Button(f.label) { model.filter = f; model.search() } .buttonStyle(MemoryFilterButtonStyle(selected: model.filter == f)) } Spacer(minLength: 0) } .padding(.horizontal, 28) // Results if model.isLoading && model.results.isEmpty { ProgressView() .frame(maxWidth: .infinity, alignment: .center) .padding(.top, 40) } else if model.results.isEmpty && model.query.trimmingCharacters(in: .whitespaces).isEmpty { // nothing typed yet: searches worth trying and the last conversations suggestionsView } else if model.results.isEmpty && !model.query.isEmpty { HubEmptyState(text: String(localized: "hub.memory.search.no-results"), state: .sleeping, color: "#22D3EE") .frame(maxWidth: .infinity) .padding(.top, 40) } else { ScrollView { LazyVStack(alignment: .leading, spacing: 4) { ForEach(model.results) { result in MemoryResultRow(result: result, selected: model.selected?.id == result.id, query: model.query) { model.loadDetail(result) } } if model.results.count < model.total { Button(String(localized: "hub.memory.search.load-more")) { model.search(loadMore: true) } .buttonStyle(HubButtonStyle()) .padding(.vertical, 8) .frame(maxWidth: .infinity, alignment: .center) } } .padding(.horizontal, 28) .padding(.bottom, 20) } } } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) } @ViewBuilder private var suggestionsView: some View { ScrollView { VStack(alignment: .leading, spacing: 14) { if let s = model.suggestions, !s.searches.isEmpty { HubLabel(String(localized: "hub.memory.search.try")) .padding(.top, 8) HubWrap(spacing: 8) { ForEach(s.searches, id: \.self) { word in SuggestionChip(text: word) { model.searchFor(word) } } } } if let s = model.suggestions, !s.recent.isEmpty { HubLabel(String(localized: "hub.memory.search.recent")) .padding(.top, 8) LazyVStack(alignment: .leading, spacing: 4) { ForEach(s.recent) { conv in MemoryResultRow(result: conv, selected: model.selected?.id == conv.id, query: "") { model.loadDetail(conv) } } } } else if model.suggestions == nil { ProgressView() .frame(maxWidth: .infinity, alignment: .center) .padding(.top, 40) } } .padding(.horizontal, 28) .padding(.bottom, 20) } } // MARK: Detail panel @ViewBuilder private var detailPanel: some View { ScrollView { VStack(alignment: .leading, spacing: 14) { if model.detailLoading { ProgressView() .frame(maxWidth: .infinity, alignment: .center) .padding(.top, 40) } else if let d = model.detail { // Header VStack(alignment: .leading, spacing: 6) { Text(d.titre) .font(.system(size: 15, weight: .semibold)) .foregroundColor(HubTheme.text) HStack(spacing: 8) { MemorySourceBadge(source: d.source) Text(d.date) .font(.system(size: 11)) .foregroundColor(HubTheme.muted) } } HubDivider() // Messages VStack(alignment: .leading, spacing: 8) { ForEach(Array(d.messages.prefix(8).enumerated()), id: \.offset) { _, msg in MemoryMessageRow(message: msg) } if d.messages.count > 8 { Text(String(format: String(localized: "hub.memory.show.more-messages"), d.messages.count - 8)) .font(.system(size: 11)) .foregroundColor(HubTheme.muted) } } HubDivider() // Elements if let elements = d.elements, !elements.isEmpty { VStack(alignment: .leading, spacing: 6) { Text(String(localized: "hub.memory.show.elements")) .font(.system(size: 11, weight: .bold)) .tracking(1.1) .foregroundColor(HubTheme.muted) ForEach(Array(elements.enumerated()), id: \.offset) { _, el in MemoryElementRow(element: el) } } } else { Text(String(localized: "hub.memory.show.not-digested")) .font(.system(size: 12)) .foregroundColor(HubTheme.muted) .italic() } HubDivider() // Actions VStack(spacing: 8) { Button(String(localized: "hub.memory.show.open-claude")) { if let url = URL(string: d.lien), !d.lien.isEmpty { NSWorkspace.shared.open(url) } } .buttonStyle(HubButtonStyle()) .disabled(d.lien.isEmpty) .frame(maxWidth: .infinity) Button(resumeCopied ? String(localized: "hub.memory.show.resume.copied") : String(localized: "hub.memory.show.resume")) { model.copyResumeCommand() resumeCopied = true Task { try? await Task.sleep(nanoseconds: 2_000_000_000) resumeCopied = false } } .buttonStyle(HubButtonStyle(primary: false)) .frame(maxWidth: .infinity) Button(String(localized: "hub.memory.show.copy-link")) { if !d.lien.isEmpty { NSPasteboard.general.clearContents() NSPasteboard.general.setString(d.lien, forType: .string) } } .buttonStyle(HubButtonStyle(primary: false)) .disabled(d.lien.isEmpty) .frame(maxWidth: .infinity) } } } .padding(18) } .background(HubTheme.panel) } } // MARK: - HighlightedText private struct HighlightedText: View { let text: String let query: String var body: some View { let terms = query.lowercased().split(separator: " ").map(String.init) var attrStr = AttributedString(text) for term in terms where term.count >= 2 { var searchText = text.lowercased() var baseOffset = 0 while let range = searchText.range(of: term) { let start = baseOffset + searchText.distance(from: searchText.startIndex, to: range.lowerBound) let length = term.count if let attrRange = Range(NSRange(location: start, length: length), in: attrStr) { attrStr[attrRange].foregroundColor = Color(hex: "#22D3EE") attrStr[attrRange].font = .system(size: 12).bold() } let advance = searchText.distance(from: range.lowerBound, to: range.upperBound) baseOffset += searchText.distance(from: searchText.startIndex, to: range.upperBound) searchText = String(searchText[range.upperBound...]) if searchText.isEmpty { break } _ = advance } } return Text(attrStr) } } // MARK: - MemoryResultRow private struct MemoryResultRow: View { let result: BrainSearchResult let selected: Bool let query: String let action: () -> Void @State private var hover = false var body: some View { Button(action: action) { HStack(alignment: .top, spacing: 10) { // Cyan left border when selected RoundedRectangle(cornerRadius: 2) .fill(selected ? Color(hex: "#22D3EE") : Color.clear) .frame(width: 3) .padding(.vertical, 4) VStack(alignment: .leading, spacing: 4) { HStack(spacing: 8) { Text(result.titre) .font(.system(size: 13, weight: .semibold)) .foregroundColor(HubTheme.text) .lineLimit(1) Spacer(minLength: 0) MemorySourceBadge(source: result.source) Text(result.date) .font(.system(size: 11)) .foregroundColor(HubTheme.muted) } if !result.extrait.isEmpty { HighlightedText(text: result.extrait, query: query) .font(.system(size: 12)) .foregroundColor(HubTheme.secondary) .lineLimit(2) } if !result.projet.isEmpty { Text(result.projet) .font(.system(size: 11)) .foregroundColor(HubTheme.muted) .padding(.horizontal, 6) .padding(.vertical, 2) .background(RoundedRectangle(cornerRadius: 4).fill(Color.white.opacity(0.07))) } } } .padding(.horizontal, 12) .padding(.vertical, 8) .background(RoundedRectangle(cornerRadius: 10) .fill(Color.white.opacity(selected ? 0.08 : (hover ? 0.04 : 0)))) .contentShape(Rectangle()) } .buttonStyle(.plain) .onHover { hover = $0 } } } // MARK: - MemoryMessageRow private struct MemoryMessageRow: View { let message: BrainMessage var body: some View { HStack(alignment: .top, spacing: 8) { Text(message.role == "human" ? "You" : "Claude") .font(.system(size: 11, weight: .bold)) .foregroundColor(message.role == "human" ? Color(hex: "#22D3EE") : HubTheme.accent) .frame(width: 44, alignment: .trailing) Text(String(message.text.prefix(200))) .font(.system(size: 12)) .foregroundColor(HubTheme.secondary) .lineLimit(3) .frame(maxWidth: .infinity, alignment: .leading) } } } // MARK: - MemoryElementRow private struct MemoryElementRow: View { let element: BrainElement var body: some View { HStack(alignment: .top, spacing: 8) { Text(element.statut ?? "") .font(.system(size: 12)) Text(element.kind) .font(.system(size: 10, weight: .bold)) .padding(.horizontal, 6) .padding(.vertical, 2) .background(RoundedRectangle(cornerRadius: 4).fill(kindColor(element.kind).opacity(0.2))) .foregroundColor(kindColor(element.kind)) Text(element.texte) .font(.system(size: 12)) .foregroundColor(HubTheme.body) .lineLimit(3) .frame(maxWidth: .infinity, alignment: .leading) } } private func kindColor(_ kind: String) -> Color { switch kind { case "décision": return Color(hex: "#A78BFA") case "leçon": return Color(hex: "#34D399") case "fait": return Color(hex: "#F7B32B") case "préf": return Color(hex: "#F472B6") default: return HubTheme.secondary } } } // MARK: - MemorySourceBadge private struct MemorySourceBadge: View { let source: String var body: some View { Text(source == "claude" ? "Claude.ai" : "Claude Code") .font(.system(size: 10, weight: .semibold)) .padding(.horizontal, 6) .padding(.vertical, 2) .background(RoundedRectangle(cornerRadius: 4) .fill(source == "claude" ? Color(hex: "#FB923C").opacity(0.2) : Color(hex: "#3B9EFF").opacity(0.2))) .foregroundColor(source == "claude" ? Color(hex: "#FB923C") : Color(hex: "#3B9EFF")) } } // MARK: - SuggestionChip /// A search worth trying: a magnifier and a word, lit up under the pointer. private struct SuggestionChip: View { let text: String let action: () -> Void @State private var hover = false var body: some View { Button(action: action) { HStack(spacing: 6) { Image(systemName: "magnifyingglass") .font(.system(size: 10, weight: .semibold)) Text(verbatim: text) .font(.system(size: 12)) } .foregroundColor(hover ? Color(hex: "#22D3EE") : HubTheme.body) .padding(.horizontal, 11) .padding(.vertical, 6) .background(Capsule().fill(hover ? Color(hex: "#22D3EE").opacity(0.14) : Color.white.opacity(0.06))) .overlay(Capsule().strokeBorder(hover ? Color(hex: "#22D3EE").opacity(0.45) : HubTheme.line)) .contentShape(Capsule()) } .buttonStyle(.plain) .onHover { h in withAnimation(.easeOut(duration: 0.15)) { hover = h } } } } // MARK: - MemoryFilterButtonStyle private struct MemoryFilterButtonStyle: ButtonStyle { let selected: Bool func makeBody(configuration: Configuration) -> some View { configuration.label .font(.system(size: 12, weight: selected ? .semibold : .regular)) .padding(.horizontal, 10) .padding(.vertical, 5) .background(RoundedRectangle(cornerRadius: 7) .fill(selected ? Color(hex: "#22D3EE").opacity(0.18) : Color.white.opacity(0.07))) .overlay(RoundedRectangle(cornerRadius: 7) .strokeBorder(selected ? Color(hex: "#22D3EE").opacity(0.5) : Color.clear)) .foregroundColor(selected ? Color(hex: "#22D3EE") : HubTheme.secondary) .scaleEffect(configuration.isPressed ? 0.97 : 1) } } // MARK: - Graph page: see MemoryGalaxy.swift // MARK: - HubMemoryRecurrencesPage struct HubMemoryRecurrencesPage: View { @ObservedObject var router: HubRouter @State private var data: BrainRecurrencesResponse? = nil @State private var mochiWorking: String? = nil // pattern whose Mochi is being written @State private var mochiDraft: MochiDraft? = nil // Mochi shown in its editor @ObservedObject private var detection = SkillDetection.shared @State private var isLoading = true @State private var working: String? = nil // pattern whose skill is being written @State private var draft: SkillDraft? = nil // skill shown for review @State private var notice: String? = nil struct SkillDraft: Identifiable { let id: String // pattern id let name: String let path: String let markdown: String let installed: Bool } var body: some View { HubPageScaffold(title: String(localized: "hub.page.memory-recurrences")) { if isLoading { ProgressView() .frame(maxWidth: .infinity, alignment: .center) .padding(.top, 40) } else { let patterns = detection.result let analyzing = detection.running // What could become a skill: tasks you keep doing with Claude, found in your conversations and project files HStack(alignment: .firstTextBaseline) { HubLabel(String(localized: "hub.memory.patterns.title")) Spacer() if let p = patterns, p.generatedAt != nil { if analyzing { Text(String(localized: "hub.memory.patterns.analyzing")) .font(.system(size: 11)) .foregroundColor(HubTheme.secondary) .lineLimit(1) } else if p.stale > 0 { Text(String(format: String(localized: "hub.memory.patterns.stale"), p.stale)) .font(.system(size: 11)) .foregroundColor(HubTheme.secondary) } RefreshIconButton(spinning: analyzing, help: String(localized: "hub.memory.patterns.refresh"), action: analyze) } } if let failure = detection.failure, notice == nil { Text(String(format: String(localized: "hub.memory.patterns.error"), failure)) .font(.system(size: 12)) .foregroundColor(HubTheme.body) .lineLimit(3) .padding(.bottom, 4) } if let notice { Text(notice) .font(.system(size: 12)) .foregroundColor(HubTheme.body) .padding(.bottom, 4) } // while Claude reads again, the cards found before stay on the page if analyzing, (patterns?.patterns ?? []).isEmpty { HubEmptyState(text: String(localized: "hub.memory.patterns.analyzing"), state: .thinking, color: "#22D3EE") } else if patterns?.generatedAt == nil { VStack(spacing: 12) { HubEmptyState(text: String(localized: "hub.memory.patterns.never"), color: "#22D3EE") Button(action: analyze) { Text(String(localized: "hub.memory.patterns.analyze")) } .buttonStyle(HubButtonStyle(primary: true)) } .frame(maxWidth: .infinity) } else if let list = patterns?.patterns, !list.isEmpty { LazyVGrid(columns: [GridItem(.adaptive(minimum: 260), spacing: 12, alignment: .top)], spacing: 12) { ForEach(list) { p in SkillPatternCard(pattern: p, working: working == p.id, mochiWorking: mochiWorking == p.id, onCreate: { createSkill(p) }, onView: { viewSkill(p) }, onMochi: { createMochi(p) }) } } } else { HubEmptyState(text: String(localized: "hub.memory.patterns.empty"), color: "#22D3EE") } if let d = data { // Errors HubLabel(String(localized: "hub.memory.recurrences.errors")) .padding(.top, 8) if d.erreurs.isEmpty { HubEmptyState(text: String(localized: "hub.memory.recurrences.errors.empty"), color: "#22D3EE") } else { HubCard { VStack(alignment: .leading, spacing: 0) { ForEach(Array(d.erreurs.enumerated()), id: \.offset) { idx, err in if idx > 0 { HubDivider() } HStack(spacing: 10) { Text(err.statut) .font(.system(size: 14)) Text(err.texte) .font(.system(size: 13)) .foregroundColor(HubTheme.body) .lineLimit(2) .frame(maxWidth: .infinity, alignment: .leading) Text(verbatim: String(UnicodeScalar(0x00D7)!) + String(err.count)) .font(.system(size: 12, weight: .semibold)) .foregroundColor(HubTheme.red) } .padding(.vertical, 10) } } } } // Artifacts HubLabel(String(localized: "hub.memory.recurrences.created")) .padding(.top, 8) if d.artifacts.isEmpty { HubEmptyState(text: String(localized: "hub.memory.recurrences.created"), color: "#22D3EE") } else { ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: 10) { ForEach(Array(d.artifacts.enumerated()), id: \.offset) { _, a in RecurrenceArtifactBadge(artifact: a) } } } } } } } .sheet(item: $draft) { d in SkillDraftSheet(draft: d, onInstall: { install(d) }, onOpen: { NSWorkspace.shared.open(URL(fileURLWithPath: d.path)) }, onClose: { draft = nil }) } .sheet(item: $mochiDraft) { d in MochiEditor(draft: d, done: { mochiDraft = nil }, saved: { router.page = .mochisTeam }) } .onAppear { Task { data = try? await BrainRunner.shared.run(["recurrences", "--json"], as: BrainRecurrencesResponse.self) await detection.load() isLoading = false await detection.runIfDue() } } } // The Relire / Analyser buttons: Claude reads the projects that changed now, without waiting. private func analyze() { notice = nil Task { await detection.analyze() } } // Claude writes the skill from the pattern's conversations; you review it before installing. private func createSkill(_ p: BrainPattern) { working = p.id notice = nil Task { do { let r = try await BrainRunner.shared.run(["skill", p.id, "--json"], as: BrainSkillResult.self) if let path = r.path, let markdown = r.markdown { draft = SkillDraft(id: p.id, name: r.name ?? "", path: path, markdown: markdown, installed: false) } else { notice = String(format: String(localized: "hub.memory.patterns.error"), r.error ?? "brain skill") } } catch { notice = String(format: String(localized: "hub.memory.patterns.error"), "brain skill") } working = nil await reloadPatterns() } } // Claude writes a Mochi from the pattern's conversations; it opens in the editor, saved only on click. private func createMochi(_ p: BrainPattern) { mochiWorking = p.id notice = nil Task { struct Reply: Decodable { let error: String? } do { let data = try await BrainRunner.shared.run(["mochi", "from-pattern", p.id, "--json"]) if let m = try? JSONDecoder().decode(BrainMochiFromPattern.self, from: data) { mochiDraft = MochiDraft(fromPattern: m) } else { let e = (try? JSONDecoder().decode(Reply.self, from: data))?.error notice = String(format: String(localized: "hub.memory.patterns.error"), e ?? "brain mochi from-pattern") } } catch { notice = String(format: String(localized: "hub.memory.patterns.error"), "brain mochi from-pattern") } mochiWorking = nil } } private func viewSkill(_ p: BrainPattern) { guard let path = p.skillPath, let markdown = try? String(contentsOfFile: path, encoding: .utf8) else { createSkill(p); return } draft = SkillDraft(id: p.id, name: p.skillName ?? "", path: path, markdown: markdown, installed: p.installe ?? false) } // Only after the click in the sheet: copied to ~/.claude/skills//SKILL.md (an existing one is backed up first). private func install(_ d: SkillDraft) { Task { do { let r = try await BrainRunner.shared.run(["install-skill", d.id, "--json"], as: BrainSkillResult.self) if let path = r.path { notice = String(format: String(localized: "hub.memory.patterns.installed-at"), path.replacingOccurrences(of: NSHomeDirectory(), with: "~")) } else { notice = String(format: String(localized: "hub.memory.patterns.error"), r.error ?? "brain install-skill") } } catch { notice = String(format: String(localized: "hub.memory.patterns.error"), "brain install-skill") } draft = nil await reloadPatterns() } } private func reloadPatterns() async { await detection.load() } } // MARK: - SkillPatternCard /// One task you keep asking Claude: how often, when, a few of the conversations, and its skill. private struct SkillPatternCard: View { let pattern: BrainPattern let working: Bool let mochiWorking: Bool let onCreate: () -> Void let onView: () -> Void let onMochi: () -> Void private var recent: [BrainPatternConversation] { Array(pattern.conversations.suffix(3).reversed()) } private var sourcesLine: String { guard let s = pattern.sources, !s.isEmpty else { return " " } return String(format: String(localized: "hub.memory.patterns.from-files"), s.prefix(3).joined(separator: ", ")) } // Every card keeps the same rows and line counts, so they all have the same height in the grid. var body: some View { HubCard(padding: 14) { VStack(alignment: .leading, spacing: 8) { Text(pattern.nom) .font(.system(size: 13, weight: .semibold)) .foregroundColor(HubTheme.text) .lineLimit(2, reservesSpace: true) Text(verbatim: pattern.description) .font(.system(size: 11.5)) .foregroundColor(HubTheme.secondary) .lineLimit(2, reservesSpace: true) HStack(spacing: 6) { if pattern.count > 0 { Text(String(format: String(localized: "hub.memory.recurrences.times"), pattern.count)) .font(.system(size: 11)) .foregroundColor(HubTheme.secondary) } if let freq = pattern.freqJours { Text(String(format: String(localized: "hub.memory.recurrences.freq-days"), freq)) .font(.system(size: 11)) .foregroundColor(HubTheme.muted) } Text(verbatim: "· " + pattern.projet) .font(.system(size: 11)) .foregroundColor(HubTheme.muted) .lineLimit(1) } // the project files it shows in (a release checklist in CLAUDE.md, a script run by hand) Text(verbatim: sourcesLine) .font(.system(size: 11)) .foregroundColor(HubTheme.secondary) .lineLimit(1) // how often, week by week (the row stays, empty, for a task seen only in the files) let maxVal = max(1, pattern.histogram.max() ?? 1) HStack(alignment: .bottom, spacing: 2) { if pattern.histogram.contains(where: { $0 > 0 }) { ForEach(Array(pattern.histogram.enumerated()), id: \.offset) { _, v in RoundedRectangle(cornerRadius: 1.5) .fill(Color(hex: "#22D3EE").opacity(0.5 + 0.5 * Double(v) / Double(maxVal))) .frame(width: 10, height: max(2, 24 * Double(v) / Double(maxVal))) } } } .frame(height: 26, alignment: .bottom) // a few of the conversations it was found in, always three rows VStack(alignment: .leading, spacing: 2) { ForEach(0..<3, id: \.self) { i in Text(verbatim: i < recent.count ? "· " + recent[i].titre : " ") .font(.system(size: 11)) .foregroundColor(HubTheme.muted) .lineLimit(1) } } HStack(spacing: 8) { if working { ProgressView().controlSize(.small) Text(String(localized: "hub.memory.patterns.creating")) .font(.system(size: 11)) .foregroundColor(HubTheme.secondary) } else if pattern.skillPath != nil { Button(action: onView) { Text(pattern.installe == true ? String(localized: "hub.memory.patterns.installed") : String(localized: "hub.memory.patterns.view")) } .buttonStyle(HubButtonStyle(primary: false)) } else { Button(action: onCreate) { Text(String(localized: "hub.memory.patterns.create")) } .buttonStyle(HubButtonStyle(primary: false)) } if !working { if mochiWorking { ProgressView().controlSize(.small) Text(String(localized: "hub.memory.patterns.mochi-creating")) .font(.system(size: 11)) .foregroundColor(HubTheme.secondary) } else { Button(action: onMochi) { Label(String(localized: "hub.memory.patterns.mochi"), systemImage: "sparkles") } .buttonStyle(.plain) .font(.system(size: 12, weight: .semibold)) .foregroundColor(Color(hex: "#A78BFA")) .help(String(localized: "hub.memory.patterns.mochi-help")) } } } .font(.system(size: 11)) .padding(.top, 4) } } } } // MARK: - RefreshIconButton /// The round arrow that reads the projects again: lights up under the pointer, turns while it works. private struct RefreshIconButton: View { let spinning: Bool let help: String let action: () -> Void @State private var hovering = false @State private var angle: Double = 0 var body: some View { Button { guard !spinning else { return } startTurning() // turns at once, before brain even starts action() } label: { Image(systemName: "arrow.clockwise") .font(.system(size: 13, weight: .semibold)) .rotationEffect(.degrees(angle)) .foregroundColor(hovering || spinning ? Color(hex: "#22D3EE") : HubTheme.secondary) .frame(width: 30, height: 30) .background(Circle().fill(hovering ? Color(hex: "#22D3EE").opacity(0.14) : Color.white.opacity(0.06))) .overlay(Circle().strokeBorder(hovering ? Color(hex: "#22D3EE").opacity(0.45) : HubTheme.line)) .scaleEffect(hovering && !spinning ? 1.06 : 1) .contentShape(Circle()) } .buttonStyle(.plain) .onHover { h in withAnimation(.easeOut(duration: 0.15)) { hovering = h } } .onChange(of: spinning, initial: true) { _, now in if now { startTurning() } else { stopTurning() } } .help(help) .accessibilityLabel(help) } private func startTurning() { guard angle == 0 else { return } withAnimation(.linear(duration: 0.9).repeatForever(autoreverses: false)) { angle = 360 } } // back to rest without animating (that also ends the endless turn) private func stopTurning() { var t = Transaction() t.disablesAnimations = true withTransaction(t) { angle = 0 } } } // MARK: - SkillDraftSheet /// The skill Claude wrote, to read before it goes into ~/.claude/skills. Nothing is installed without the click. private struct SkillDraftSheet: View { let draft: HubMemoryRecurrencesPage.SkillDraft let onInstall: () -> Void let onOpen: () -> Void let onClose: () -> Void var body: some View { VStack(alignment: .leading, spacing: 16) { Text(String(localized: "hub.memory.patterns.sheet.title")) .font(.system(size: 17, weight: .bold)) Text(String(format: String(localized: "hub.memory.patterns.sheet.subtitle"), draft.name)) .font(.system(size: 12)) .foregroundColor(HubTheme.secondary) ScrollView { Text(draft.markdown) .font(.system(size: 12, design: .monospaced)) .foregroundColor(HubTheme.body) .frame(maxWidth: .infinity, alignment: .leading) .padding(12) .background(RoundedRectangle(cornerRadius: 8).fill(HubTheme.field)) .textSelection(.enabled) } .frame(maxHeight: 420) HStack(spacing: 10) { Button(action: onOpen) { Text(String(localized: "hub.memory.patterns.sheet.open")) } .buttonStyle(HubButtonStyle(primary: false)) Spacer() Button(action: onClose) { Text(String(localized: "hub.memory.patterns.sheet.close")) } .buttonStyle(HubButtonStyle(primary: false)) Button(action: onInstall) { Text(draft.installed ? String(localized: "hub.memory.patterns.sheet.reinstall") : String(localized: "hub.memory.patterns.sheet.install")) } .buttonStyle(HubButtonStyle(primary: true)) } } .padding(24) .frame(width: 620) .background(HubTheme.panel) } } // MARK: - RecurrenceArtifactBadge private struct RecurrenceArtifactBadge: View { let artifact: BrainArtifact var body: some View { VStack(spacing: 4) { Text(verbatim: String(artifact.count)) .font(.system(size: 24, weight: .bold)) .foregroundColor(Color(hex: "#22D3EE")) Text(artifact.kind) .font(.system(size: 11)) .foregroundColor(HubTheme.secondary) } .padding(.horizontal, 18) .padding(.vertical, 14) .background(RoundedRectangle(cornerRadius: 12).fill(HubTheme.card)) .overlay(RoundedRectangle(cornerRadius: 12).strokeBorder(Color(hex: "#22D3EE").opacity(0.15))) } } // MARK: - SettingsJsonDiffSheet private struct SettingsJsonDiffSheet: View { let diffText: String let onConfirm: () -> Void let onCancel: () -> Void var body: some View { VStack(alignment: .leading, spacing: 16) { Text(String(localized: "hub.memory.settings.hooks.diff-title")) .font(.system(size: 17, weight: .bold)) Text(String(localized: "hub.memory.settings.hooks.diff-subtitle")) .font(.system(size: 12)) .foregroundColor(HubTheme.secondary) ScrollView { Text(diffText) .font(.system(size: 12, design: .monospaced)) .foregroundColor(HubTheme.body) .frame(maxWidth: .infinity, alignment: .leading) .padding(12) .background(RoundedRectangle(cornerRadius: 8).fill(HubTheme.field)) .textSelection(.enabled) } .frame(maxHeight: 320) HStack(spacing: 10) { Spacer() Button(action: onCancel) { Text(String(localized: "hub.memory.settings.hooks.cancel")) } .buttonStyle(HubButtonStyle(primary: false)) Button(action: onConfirm) { Text(String(localized: "hub.memory.settings.hooks.confirm")) } .buttonStyle(HubButtonStyle(primary: true)) } } .padding(24) .frame(width: 500) .background(HubTheme.panel) .foregroundColor(HubTheme.text) .preferredColorScheme(.dark) } } // MARK: - HooksMCPSection @MainActor private struct HooksMCPSection: View { @State private var hooksEnabled = false @State private var mcpEnabled = false @State private var showDiff = false @State private var diffContent = "" @State private var pendingAction: SettingsJsonAction? = nil @State private var errorMessage: String? = nil enum SettingsJsonAction { case enableHooks, disableHooks, enableMcp, disableMcp } var body: some View { // same spacing as the other cards' rows (HubCard puts 12 between them) VStack(alignment: .leading, spacing: 12) { HubRow(title: String(localized: "hub.memory.settings.hooks.title"), detail: String(localized: "hub.memory.settings.hooks.detail")) { Button(hooksEnabled ? String(localized: "hub.memory.settings.turn-off") : String(localized: "hub.memory.settings.turn-on")) { pendingAction = hooksEnabled ? .disableHooks : .enableHooks diffContent = computeHooksDiff(enable: !hooksEnabled) showDiff = true } .buttonStyle(HubButtonStyle(primary: !hooksEnabled)) } HubDivider() HubRow(title: String(localized: "hub.memory.settings.mcp.title"), detail: String(localized: "hub.memory.settings.mcp.detail")) { Button(mcpEnabled ? String(localized: "hub.memory.settings.turn-off") : String(localized: "hub.memory.settings.turn-on")) { pendingAction = mcpEnabled ? .disableMcp : .enableMcp diffContent = computeMcpDiff(enable: !mcpEnabled) showDiff = true } .buttonStyle(HubButtonStyle(primary: !mcpEnabled)) } if let err = errorMessage { Text(err) .font(.system(size: 11)) .foregroundColor(HubTheme.red) } } .onAppear { refreshStatus() BrainRunner.shared.discoverAsync() } .sheet(isPresented: $showDiff) { SettingsJsonDiffSheet( diffText: diffContent, onConfirm: { showDiff = false applyAction() }, onCancel: { showDiff = false } ) } } private func refreshStatus() { let (hasHooks, hasMcp) = readCurrentStatus() hooksEnabled = hasHooks mcpEnabled = hasMcp } private func readCurrentStatus() -> (Bool, Bool) { let path = "\(NSHomeDirectory())/.claude/settings.json" guard let data = FileManager.default.contents(atPath: path), let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return (false, false) } let hooks = json["hooks"] as? [String: Any] ?? [:] let ss = (hooks["SessionStart"] as? [[String: Any]]) ?? [] let hasHooks = ss.contains { group in ((group["hooks"] as? [[String: Any]]) ?? []).contains { h in (h["command"] as? String)?.contains("brain-session-start") == true } } let mcp = json["mcpServers"] as? [String: Any] ?? [:] let hasMcp = mcp["coucou-brain"] != nil return (hasHooks, hasMcp) } private func computeHooksDiff(enable: Bool) -> String { if enable { let hooksDir = readHooksDir() let nodeCmd = findNodeCommand() return """ + "hooks": { + "SessionStart": [{ + "hooks": [{"type": "command", + "command": "\(nodeCmd) \\"\(hooksDir)/brain-session-start.js\\"", + "timeout": 8, "statusMessage": "Loading brain context..."}] + }], + "UserPromptSubmit": [{ + "hooks": [{"type": "command", + "command": "\(nodeCmd) \\"\(hooksDir)/brain-prompt.js\\"", + "timeout": 5}] + }] + } """ } else { return """ - entries "brain-session-start" in SessionStart - entries "brain-prompt" in UserPromptSubmit """ } } private func computeMcpDiff(enable: Bool) -> String { if enable { return """ + "mcpServers": { + "coucou-brain": { + "type": "stdio", + "command": "brain", + "args": ["mcp"] + } + } """ } else { return """ - "mcpServers": { "coucou-brain": ... } """ } } private func readHooksDir() -> String { let path = "\(NSHomeDirectory())/.claude/brain-hooks.json" if let data = FileManager.default.contents(atPath: path), let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let dir = json["hooksDir"] as? String { return dir } if let bin = BrainRunner.shared.binaryPath { let dir = URL(fileURLWithPath: bin).deletingLastPathComponent() .appendingPathComponent("../hooks").standardized.path return dir } return "\(NSHomeDirectory())/Developer/coucou/brain/hooks" } private func findNodeCommand() -> String { let candidates = [ "\(NSHomeDirectory())/.nvm/alias/default/bin/node", "/opt/homebrew/opt/node@22/bin/node", "/opt/homebrew/bin/node", "/usr/local/bin/node", ] for c in candidates where FileManager.default.isExecutableFile(atPath: c) { return c } return "node" } private func applyAction() { guard let action = pendingAction else { return } let path = "\(NSHomeDirectory())/.claude/settings.json" let formatter = DateFormatter() formatter.dateFormat = "yyyyMMdd-HHmmss" let backupPath = path + ".backup-" + formatter.string(from: Date()) do { try brainSettingsApply(path: path, backupPath: backupPath) { json in switch action { case .enableHooks: brainHooksAdd(to: &json, hooksDir: readHooksDir(), nodeCmd: findNodeCommand()) case .disableHooks: brainHooksRemove(from: &json) case .enableMcp: brainMcpAdd(to: &json) case .disableMcp: brainMcpRemove(from: &json) } } refreshStatus() errorMessage = nil } catch MemorySettingsError.fileNotFound { errorMessage = NSLocalizedString("hub.memory.settings.hooks.error-read", value: "Impossible de lire ~/.claude/settings.json", comment: "") } catch MemorySettingsError.invalidJSON { errorMessage = NSLocalizedString("hub.memory.settings.hooks.error-json", value: "Le fichier n'est pas du JSON valide — aucune écriture effectuée.", comment: "") } catch MemorySettingsError.backupFailed { errorMessage = NSLocalizedString("hub.memory.settings.hooks.error-backup", value: "Impossible de créer la sauvegarde — aucune écriture effectuée.", comment: "") } catch MemorySettingsError.serializationError { errorMessage = NSLocalizedString("hub.memory.settings.hooks.error-serial", value: "Erreur de sérialisation — aucune écriture effectuée.", comment: "") } catch { errorMessage = String(format: NSLocalizedString("hub.memory.settings.hooks.error-write", value: "Erreur écriture : %@", comment: ""), error.localizedDescription) } } } // MARK: - HubMemorySettingsPage struct HubMemorySettingsPage: View { @ObservedObject private var runner = BrainRunner.shared @AppStorage("brainBinaryPath") private var customPath: String = "" @State private var status: BrainStatus? = nil @State private var isImporting = false @State private var importSuccess: String? = nil @State private var confirmWipe = false @State private var isWiping = false @State private var currentDepth: String = "search" // B2: persisted reminder toggle @AppStorage("brainImportReminder") private var reminder: Bool = false private let depths: [(String, String, String)] = [ ("search", "Recherche uniquement", "Cherche dans le texte brut"), ("live", "Digestion en direct", "Résume chaque nouvelle conversation"), ("full", "Rétroactif complet", "Rejoue l'historique complet"), ] var body: some View { HubPageScaffold(title: String(localized: "hub.page.memory-settings")) { // Status card if let st = status { HubGlowCard(color: Color(hex: "#22D3EE")) { VStack(alignment: .leading, spacing: 8) { if let idx = st.rawIndex { HStack(spacing: 20) { statItem(label: "Conversations", value: "\(idx.conversations)") statItem(label: "Sessions", value: "\(idx.sessions)") statItem(label: "Messages", value: "\(idx.messages)") } } else { Text(String(localized: "hub.memory.settings.no-index")) .font(.system(size: 13)) .foregroundColor(HubTheme.secondary) } if let pause = st.pause { Text(String(format: String(localized: "hub.memory.settings.paused"), pause)) .font(.system(size: 11)) .foregroundColor(HubTheme.muted) } } } } else { ProgressView() } // Sources HubLabel(String(localized: "hub.memory.settings.sources")) HubCard { // Claude Code HubRow(title: "Claude Code") { Text(String(localized: "hub.memory.settings.auto-indexed")) .font(.system(size: 11)) .foregroundColor(HubTheme.green) .padding(.horizontal, 7) .padding(.vertical, 3) .background(RoundedRectangle(cornerRadius: 5).fill(HubTheme.green.opacity(0.15))) } HubDivider() // Claude.ai VStack(alignment: .leading, spacing: 10) { HubRow(title: "Claude.ai") { Button(String(localized: "hub.memory.settings.import")) { isImporting = true } .buttonStyle(HubButtonStyle()) } if let msg = importSuccess { Text(msg) .font(.system(size: 12)) .foregroundColor(HubTheme.green) .padding(.leading, 4) } } .onDrop(of: [.fileURL], isTargeted: nil) { providers in handleDrop(providers) return true } HubDivider() // B2: Monthly reminder toggle with @AppStorage + UserNotifications HubRow(title: String(localized: "hub.memory.settings.sources.reminder-title"), detail: String(localized: "hub.memory.settings.sources.reminder-detail")) { Toggle("", isOn: $reminder) .toggleStyle(.switch) .labelsHidden() .onChange(of: reminder) { _, new in if new { scheduleMonthlyReminder() } else { cancelReminder() } } } } .fileImporter(isPresented: $isImporting, allowedContentTypes: [.zip]) { result in if case .success(let url) = result { importZip(url) } } // B1: Claude Code hooks + MCP section let claudeCodeSectionTitle = "CLAUDE CODE" HubLabel(claudeCodeSectionTitle) HubCard { HooksMCPSection() } // Depth HubLabel(String(localized: "hub.memory.settings.depth")) HubCard { VStack(alignment: .leading, spacing: 0) { ForEach(Array(depths.enumerated()), id: \.offset) { idx, depth in if idx > 0 { HubDivider() } Button { setDepth(depth.0) } label: { HStack(spacing: 12) { Image(systemName: currentDepth == depth.0 ? "checkmark.circle.fill" : "circle") .foregroundColor(currentDepth == depth.0 ? Color(hex: "#22D3EE") : HubTheme.muted) VStack(alignment: .leading, spacing: 2) { Text(depth.1) .font(.system(size: 13, weight: .medium)) .foregroundColor(HubTheme.text) Text(depth.2) .font(.system(size: 11)) .foregroundColor(HubTheme.secondary) } Spacer(minLength: 0) } .padding(.vertical, 10) .contentShape(Rectangle()) } .buttonStyle(.plain) } } } // B3: Progress indicator under depth selector if let st = status, let idx = st.rawIndex, idx.messages > 0 { HStack(spacing: 10) { Image(systemName: "checkmark.circle") .foregroundColor(HubTheme.green) .font(.system(size: 12)) Text(String(format: String(localized: "hub.memory.settings.index-info"), idx.messages, currentDepth)) .font(.system(size: 12)) .foregroundColor(HubTheme.secondary) } .padding(.horizontal, 4) } // Privacy HubLabel(String(localized: "hub.memory.settings.privacy")) HubCard { HubRow(title: String(localized: "hub.memory.settings.open-folder")) { Button(String(localized: "hub.memory.settings.open-folder")) { let url = URL(fileURLWithPath: NSHomeDirectory() + "/CoucouBrain") NSWorkspace.shared.open(url) } .buttonStyle(HubButtonStyle()) } HubDivider() HubRow(title: String(localized: "hub.memory.settings.wipe")) { Button(String(localized: "hub.memory.settings.wipe")) { confirmWipe = true } .buttonStyle(HubButtonStyle()) .foregroundColor(HubTheme.red) } } .alert(String(localized: "hub.memory.settings.wipe.confirm-title"), isPresented: $confirmWipe) { Button(String(localized: "hub.memory.settings.wipe.confirm-action"), role: .destructive) { wipeIndex() } Button(String(localized: "hub.memory.settings.wipe.cancel"), role: .cancel) {} } message: { Text(String(localized: "hub.memory.settings.wipe.confirm-message")) } } .onAppear { loadStatus() } } @ViewBuilder private func statItem(label: String, value: String) -> some View { VStack(alignment: .leading, spacing: 2) { Text(value) .font(.system(size: 20, weight: .bold)) .foregroundColor(Color(hex: "#22D3EE")) Text(label) .font(.system(size: 11)) .foregroundColor(HubTheme.secondary) } } private func loadStatus() { Task { do { status = try await BrainRunner.shared.run(["status", "--json"], as: BrainStatus.self) currentDepth = status?.depth ?? "search" } catch {} } } private func setDepth(_ value: String) { currentDepth = value Task { _ = try? await BrainRunner.shared.run(["config", "set", "depth", value, "--json"]) } } private func importZip(_ url: URL) { Task { do { _ = url.startAccessingSecurityScopedResource() defer { url.stopAccessingSecurityScopedResource() } let result = try await BrainRunner.shared.run(["import", url.path, "--json"], as: BrainImportResponse.self) importSuccess = "Importé : \(result.conversations) conversations, \(result.messages) messages" await loadStatusAsync() } catch { importSuccess = "Erreur lors de l'import" } } } private func handleDrop(_ providers: [NSItemProvider]) { for provider in providers { _ = provider.loadObject(ofClass: URL.self) { url, _ in guard let url, url.pathExtension == "zip" else { return } Task { @MainActor in importZip(url) } } } } private func wipeIndex() { isWiping = true Task { _ = try? await BrainRunner.shared.run(["wipe", "--yes", "--json"]) status = nil isWiping = false } } @MainActor private func loadStatusAsync() async { do { status = try await BrainRunner.shared.run(["status", "--json"], as: BrainStatus.self) currentDepth = status?.depth ?? "search" } catch {} } // B2: Monthly reminder via UserNotifications private func scheduleMonthlyReminder() { let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.alert]) { _, _ in } center.removePendingNotificationRequests(withIdentifiers: ["brain-monthly-import"]) let content = UNMutableNotificationContent() content.title = "Mémoire Coucou" content.body = "Export tes conversations Claude.ai ce mois-ci : claude.ai/settings/export" var comps = DateComponents() comps.day = 1; comps.hour = 10; comps.minute = 0 let trigger = UNCalendarNotificationTrigger(dateMatching: comps, repeats: true) let req = UNNotificationRequest(identifier: "brain-monthly-import", content: content, trigger: trigger) center.add(req) { _ in } } private func cancelReminder() { UNUserNotificationCenter.current() .removePendingNotificationRequests(withIdentifiers: ["brain-monthly-import"]) } } // A minimal Decodable for brain import response private struct BrainImportResponse: Decodable { let ok: Bool let conversations: Int let messages: Int } #endif