Skip to content

A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.

Live diff: see file changes in the notch (#177)

Louis054030636fc1
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 11d347e9..ac7254e1 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -33,6 +33,9 @@ jobs:
- name: Test ask question
run: bash scripts/test-ask-question.sh
+ - name: Diff engine tests
+ run: bash scripts/test-diff-engine.sh
+
- name: Build
run: |
xcodebuild \
diff --git a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj
index 273baf38..30bb0db3 100644
--- a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj
+++ b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj
@@ -43,6 +43,7 @@
62C4EE3F74DAA59764729E62 /* UploadCanvasView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B241B043223AFBBFB7418A5E /* UploadCanvasView.swift */; };
63F9F3AAC881D3EDDDD8AED9 /* UserIdentity.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4A13AEE6E06F46CEC9D908C /* UserIdentity.swift */; };
651FA3F09608DE5D02D61CCE /* BotCanvasView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A29F4C0B02BE91654D02AA0C /* BotCanvasView.swift */; };
+ 6697436AA05A3F92C1DD85C3 /* DiffEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3DB24C2469551040FBAA4DBF /* DiffEngine.swift */; };
68A950E3C23FD612639D9776 /* IslandViewContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA02B08886939FF6FE0475DD /* IslandViewContent.swift */; };
6D158183870434FEDF07E050 /* LocalChat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8790ACE9F73BD74640A0F20C /* LocalChat.swift */; };
6FC65C190ED614C664C9BC17 /* SafeWebURL.swift in Sources */ = {isa = PBXBuildFile; fileRef = B2FDED98F7F6C755A72C97A3 /* SafeWebURL.swift */; };
@@ -64,6 +65,7 @@
B605F976F4141435F27CF266 /* IslandRootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 15A1A8206F73376F4CAF2057 /* IslandRootView.swift */; };
C0E18D0F6F5F6D131E6066B8 /* GreetingCanvasView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C581F7B1A9F14B281B60063E /* GreetingCanvasView.swift */; };
C18227D148D99FE6EE3CC51A /* GithubPoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8CB8B6E5E9DA6164F979E88F /* GithubPoller.swift */; };
+ C1A29371181553FB4169E195 /* DiffEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3DB24C2469551040FBAA4DBF /* DiffEngine.swift */; };
C24D863967D8D32D828ED4B1 /* BotEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4540F630F8BA04AFFFA3979 /* BotEngine.swift */; };
C61DDE2EC5FDDB39E4AA3B34 /* IslandWindowController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D710BD7834228045869D0184 /* IslandWindowController.swift */; };
C808B654C84D9F71DBF8493A /* GithubPoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8CB8B6E5E9DA6164F979E88F /* GithubPoller.swift */; };
@@ -97,6 +99,7 @@
3104222B3F17BA5E8DEA5277 /* CalcomPoller.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CalcomPoller.swift; sourceTree = "<group>"; };
3232F258523DD8D09B670363 /* FileDropView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FileDropView.swift; sourceTree = "<group>"; };
3B6A38B5686C4A1F15AB5D29 /* PillCatalog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PillCatalog.swift; sourceTree = "<group>"; };
+ 3DB24C2469551040FBAA4DBF /* DiffEngine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiffEngine.swift; sourceTree = "<group>"; };
4DC2A07E42245A8CF3BBD2AB /* CoucouAppStore.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = CoucouAppStore.app; sourceTree = BUILT_PRODUCTS_DIR; };
4F142FB3952B5F0639383047 /* MusicController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MusicController.swift; sourceTree = "<group>"; };
506824380E9C80B9BC6DCE72 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
@@ -150,6 +153,7 @@
F4263B550838CC5614569D13 /* ClaudePlanCardView.swift */,
8BF22817EC70748F2D1FB2E7 /* ClaudePlanGauge.swift */,
A83D5410BD030B243ADDCFF4 /* ClaudeService.swift */,
+ 3DB24C2469551040FBAA4DBF /* DiffEngine.swift */,
3232F258523DD8D09B670363 /* FileDropView.swift */,
8CB8B6E5E9DA6164F979E88F /* GithubPoller.swift */,
C581F7B1A9F14B281B60063E /* GreetingCanvasView.swift */,
@@ -330,6 +334,7 @@
94E0849D13762C6EC8548FEF /* ClaudePlanCardView.swift in Sources */,
D861479F6E7EAD07A6AC2105 /* ClaudePlanGauge.swift in Sources */,
2DEB459FBD0BA3CEAAA5FDE9 /* ClaudeService.swift in Sources */,
+ 6697436AA05A3F92C1DD85C3 /* DiffEngine.swift in Sources */,
E776C7D1DE5C62EA8D4BA3E3 /* FileDropView.swift in Sources */,
C808B654C84D9F71DBF8493A /* GithubPoller.swift in Sources */,
8C32A0C3EAF536D3836F61D5 /* GreetingCanvasView.swift in Sources */,
@@ -375,6 +380,7 @@
18D47AE663EB96BE5638D5F7 /* ClaudePlanCardView.swift in Sources */,
E9C21D11BCB72C392436D19E /* ClaudePlanGauge.swift in Sources */,
0329E76BA4A8FEEA8A6D76E7 /* ClaudeService.swift in Sources */,
+ C1A29371181553FB4169E195 /* DiffEngine.swift in Sources */,
2132477000FD77F7EB234DAA /* FileDropView.swift in Sources */,
C18227D148D99FE6EE3CC51A /* GithubPoller.swift in Sources */,
C0E18D0F6F5F6D131E6066B8 /* GreetingCanvasView.swift in Sources */,
diff --git a/NotchBuddy/Sources/App/AppState.swift b/NotchBuddy/Sources/App/AppState.swift
index 48247158..9ef42b48 100644
--- a/NotchBuddy/Sources/App/AppState.swift
+++ b/NotchBuddy/Sources/App/AppState.swift
@@ -291,6 +291,57 @@ final class AppState: ObservableObject {
// Pending AskUserQuestion from Claude Code hook
@Published var pendingQuestion: AskQuestion? = nil
+ // Per-pill flat list of FileDiffs, in order of reception.
+ // Not @Published — steps[] changes already trigger redraws.
+ var sessionDiffs: [String: [FileDiff]] = [:]
+ private var sessionDiffTimers: [String: DispatchWorkItem] = [:]
+ // Monotonically increasing — never reset, not even in clearSessionDiffs.
+ private var nextDiffId: Int = 0
+
+ @discardableResult
+ func appendSessionDiff(_ diff: FileDiff, for pillId: String) -> Int {
+ var d = diff
+ d.id = nextDiffId
+ nextDiffId += 1
+ if sessionDiffs[pillId] == nil { sessionDiffs[pillId] = [] }
+ sessionDiffs[pillId]!.append(d)
+ // Keep at most 50 diffs per pill; drop oldest first
+ while sessionDiffs[pillId]!.count > 50 {
+ sessionDiffs[pillId]!.removeFirst()
+ }
+ resetSessionDiffTimer(for: pillId)
+ return d.id
+ }
+
+ func clearSessionDiffs(for pillId: String) {
+ sessionDiffTimers[pillId]?.cancel()
+ sessionDiffTimers.removeValue(forKey: pillId)
+ sessionDiffs.removeValue(forKey: pillId)
+ // nextDiffId intentionally NOT reset — ids remain unique across sessions
+ }
+
+ /// Unique touched files for a pill, in first-touch order, with summed totals.
+ func touchedFiles(for pillId: String) -> [(path: String, added: Int, removed: Int)] {
+ guard let diffs = sessionDiffs[pillId] else { return [] }
+ var seen: [String: (added: Int, removed: Int)] = [:]
+ var order: [String] = []
+ for d in diffs {
+ if seen[d.path] == nil { order.append(d.path) }
+ let p = seen[d.path] ?? (0, 0)
+ seen[d.path] = (p.added + d.added, p.removed + d.removed)
+ }
+ return order.map { path in let t = seen[path]!; return (path, t.added, t.removed) }
+ }
+
+ private func resetSessionDiffTimer(for pillId: String) {
+ sessionDiffTimers[pillId]?.cancel()
+ let work = DispatchWorkItem { [weak self] in
+ DispatchQueue.main.async { self?.clearSessionDiffs(for: pillId) }
+ }
+ sessionDiffTimers[pillId] = work
+ DispatchQueue.global().asyncAfter(deadline: .now() + 3600, execute: work)
+ }
+
#if !APPSTORE
@Published var musicPlaying: Bool = false
@Published var musicAutomationDenied: Bool = false
diff --git a/NotchBuddy/Sources/App/DiffEngine.swift b/NotchBuddy/Sources/App/DiffEngine.swift
new file mode 100644
index 00000000..d7164bc2
--- /dev/null
+++ b/NotchBuddy/Sources/App/DiffEngine.swift
@@ -0,0 +1,270 @@
+import Foundation
+
+// MARK: - Types
+
+struct DiffLine: Equatable {
+ enum Kind: Equatable { case context, added, removed }
+ var kind: Kind
+ var text: String
+ var origLine: Int // 1-based; -1 for pure adds
+ var newLine: Int // 1-based; -1 for pure removes
+}
+
+struct DiffHunk: Equatable {
+ var origStart: Int
+ var newStart: Int
+ var lines: [DiffLine]
+}
+
+struct FileDiff: Equatable {
+ var id: Int = 0 // stable identifier assigned by AppState.appendSessionDiff
+ var path: String
+ var added: Int
+ var removed: Int
+ var hunks: [DiffHunk]
+ var tooLarge: Bool
+ var isNewFile: Bool // true when produced by DiffEngine.fromNew (Write tool)
+
+ var name: String { URL(fileURLWithPath: path).lastPathComponent }
+
+ static let maxBytes = 200 * 1024
+ static let maxLines = 4000
+}
+
+// MARK: - DiffEngine
+
+enum DiffEngine {
+
+ // MARK: Public API
+
+ static func fromEdit(old: String, new: String, path: String) -> FileDiff {
+ // Size guard
+ if old.utf8.count + new.utf8.count > FileDiff.maxBytes {
+ return countFallback(old: old, new: new, path: path, tooLarge: true)
+ }
+ let oldLines = splitLines(old)
+ let newLines = splitLines(new)
+ if oldLines.count + newLines.count > FileDiff.maxLines {
+ return countFallback(old: old, new: new, path: path, tooLarge: true)
+ }
+ // LCS is O(m*n) — bail out before quadratic blowup
+ if oldLines.count * newLines.count > 1_000_000 {
+ return countFallback(old: old, new: new, path: path, tooLarge: true)
+ }
+ let flat = buildDiffLines(oldLines: oldLines, newLines: newLines)
+ let hunks = buildHunks(from: flat, context: 3)
+ let added = flat.filter { $0.kind == .added }.count
+ let removed = flat.filter { $0.kind == .removed }.count
+ return FileDiff(path: path, added: added, removed: removed, hunks: hunks, tooLarge: false, isNewFile: false)
+ }
+
+ static func fromNew(content: String, path: String) -> FileDiff {
+ // Size guard (same limits as fromEdit)
+ if content.utf8.count > FileDiff.maxBytes {
+ let lineCount = content.components(separatedBy: "\n").count
+ return FileDiff(path: path, added: lineCount, removed: 0, hunks: [], tooLarge: true, isNewFile: true)
+ }
+ let lines = splitLines(content)
+ if lines.count > FileDiff.maxLines {
+ return FileDiff(path: path, added: lines.count, removed: 0, hunks: [], tooLarge: true, isNewFile: true)
+ }
+ let diffLines = lines.enumerated().map { (i, text) in
+ DiffLine(kind: .added, text: text, origLine: -1, newLine: i + 1)
+ }
+ let hunk = diffLines.isEmpty ? nil : DiffHunk(origStart: 0, newStart: 1, lines: diffLines)
+ return FileDiff(
+ path: path,
+ added: diffLines.count,
+ removed: 0,
+ hunks: hunk.map { [$0] } ?? [],
+ tooLarge: false,
+ isNewFile: true
+ )
+ }
+
+ // MARK: - Line splitting
+
+ private static func splitLines(_ text: String) -> [String] {
+ // Normalize CRLF → LF
+ let normalized = text.replacingOccurrences(of: "\r\n", with: "\n")
+ var parts = normalized.components(separatedBy: "\n")
+ // Drop trailing empty element that results from a trailing newline
+ if parts.last == "" { parts.removeLast() }
+ return parts
+ }
+
+ // MARK: - LCS-based diff
+
+ private static func buildDiffLines(oldLines: [String], newLines: [String]) -> [DiffLine] {
+ let m = oldLines.count
+ let n = newLines.count
+
+ // Build LCS DP table
+ // dp[i][j] = LCS length of oldLines[0..<i] and newLines[0..<j]
+ var dp = [[Int]](repeating: [Int](repeating: 0, count: n + 1), count: m + 1)
+ for i in 1...max(1, m) {
+ for j in 1...max(1, n) {
+ guard i <= m && j <= n else { continue }
+ if oldLines[i - 1] == newLines[j - 1] {
+ dp[i][j] = dp[i - 1][j - 1] + 1
+ } else {
+ dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
+ }
+ }
+ }
+
+ // Backtrack to get matching pairs
+ var matches: [(Int, Int)] = [] // (oldIdx 0-based, newIdx 0-based)
+ var i = m, j = n
+ while i > 0 && j > 0 {
+ if oldLines[i - 1] == newLines[j - 1] {
+ matches.append((i - 1, j - 1))
+ i -= 1; j -= 1
+ } else if dp[i - 1][j] >= dp[i][j - 1] {
+ i -= 1
+ } else {
+ j -= 1
+ }
+ }
+ matches.reverse()
+
+ // Build flat diff from LCS pairs
+ var result: [DiffLine] = []
+ var prevOld = -1
+ var prevNew = -1
+
+ for (oi, ni) in matches {
+ // Removed lines between last match and this old match
+ for k in (prevOld + 1)..<oi {
+ result.append(DiffLine(kind: .removed, text: oldLines[k],
+ origLine: k + 1, newLine: -1))
+ }
+ // Added lines between last match and this new match
+ for k in (prevNew + 1)..<ni {
+ result.append(DiffLine(kind: .added, text: newLines[k],
+ origLine: -1, newLine: k + 1))
+ }
+ // Context line (the match)
+ result.append(DiffLine(kind: .context, text: oldLines[oi],
+ origLine: oi + 1, newLine: ni + 1))
+ prevOld = oi
+ prevNew = ni
+ }
+
+ // Remaining removes
+ for k in (prevOld + 1)..<m {
+ result.append(DiffLine(kind: .removed, text: oldLines[k],
+ origLine: k + 1, newLine: -1))
+ }
+ // Remaining adds
+ for k in (prevNew + 1)..<n {
+ result.append(DiffLine(kind: .added, text: newLines[k],
+ origLine: -1, newLine: k + 1))
+ }
+
+ return result
+ }
+
+ // MARK: - Hunk building
+
+ private static func buildHunks(from lines: [DiffLine], context: Int) -> [DiffHunk] {
+ guard !lines.isEmpty else { return [] }
+
+ // Find indices of changed lines
+ var changedIndices: [Int] = []
+ for (i, line) in lines.enumerated() {
+ if line.kind != .context { changedIndices.append(i) }
+ }
+ guard !changedIndices.isEmpty else { return [] }
+
+ // Expand ±context around each changed line
+ let ranges: [(Int, Int)] = changedIndices.map {
+ (max(0, $0 - context), min(lines.count - 1, $0 + context))
+ }
+
+ // Merge overlapping ranges
+ var merged: [(Int, Int)] = []
+ for r in ranges {
+ if let last = merged.last, r.0 <= last.1 + 1 {
+ merged[merged.count - 1] = (last.0, max(last.1, r.1))
+ } else {
+ merged.append(r)
+ }
+ }
+
+ // Build hunks
+ var hunks: [DiffHunk] = []
+ for (start, end) in merged {
+ let hunkLines = Array(lines[start...end])
+ let origStart = hunkLines.first(where: { $0.origLine > 0 })?.origLine ?? 1
+ let newStart = hunkLines.first(where: { $0.newLine > 0 })?.newLine ?? 1
+ hunks.append(DiffHunk(origStart: origStart, newStart: newStart, lines: hunkLines))
+ }
+ return hunks
+ }
+
+ // MARK: - Count fallback (tooLarge)
+
+ private static func countFallback(old: String, new: String, path: String, tooLarge: Bool) -> FileDiff {
+ let oldLines = old.components(separatedBy: "\n")
+ let newLines = new.components(separatedBy: "\n")
+ let oldSet = Set(oldLines)
+ let newSet = Set(newLines)
+ let added = newLines.filter { !$0.isEmpty && !oldSet.contains($0) }.count
+ let removed = oldLines.filter { !$0.isEmpty && !newSet.contains($0) }.count
+ return FileDiff(path: path, added: added, removed: removed, hunks: [], tooLarge: tooLarge, isNewFile: false)
+ }
+
+ // MARK: - toOneLine
+
+ /// Converts a possibly multi-line, markdown-formatted string to a single line of plain text.
+ /// Strips `**`, `__`, backticks and leading `#` chars from each line, collapses whitespace.
+ static func toOneLine(_ text: String, maxChars: Int = 200) -> String {
+ var s = text
+ s = s.replacingOccurrences(of: "**", with: "")
+ s = s.replacingOccurrences(of: "__", with: "")
+ s = s.replacingOccurrences(of: "`", with: "")
+ let processed: [String] = s.components(separatedBy: "\n").compactMap { line in
+ var l = line
+ while l.hasPrefix("#") { l = String(l.dropFirst()) }
+ let trimmed = l.trimmingCharacters(in: .whitespaces)
+ return trimmed.isEmpty ? nil : trimmed
+ }
+ let joined = processed.joined(separator: " ")
+ let collapsed = joined.components(separatedBy: .whitespaces)
+ .filter { !$0.isEmpty }
+ .joined(separator: " ")
+ return String(collapsed.prefix(maxChars))
+ }
+}
+
+// MARK: - String diff step encoding
+
+public extension String {
+ /// Private-use character used as the diff step marker prefix.
+ static let diffStepMarker = "\u{E001}"
+
+ /// True if this step string encodes a file diff.
+ var isDiffStep: Bool { hasPrefix(Self.diffStepMarker) }
+
+ /// Parses a diff step string.
+ /// Format: `"\u{E001}<filename>\t<added>:<removed>:<diffId>"`
+ func parseDiffStep() -> (filename: String, added: Int, removed: Int, diffId: Int)? {
+ guard isDiffStep else { return nil }
+ let body = String(dropFirst()) // drop the marker character
+ guard let tabIdx = body.firstIndex(of: "\t") else { return nil }
+ let filename = String(body[body.startIndex..<tabIdx])
+ let rest = String(body[body.index(after: tabIdx)...])
+ let parts = rest.split(separator: ":", maxSplits: 2, omittingEmptySubsequences: false)
+ guard parts.count == 3,
+ let added = Int(parts[0]),
+ let removed = Int(parts[1]),
+ let diffId = Int(parts[2]) else { return nil }
+ return (filename, added, removed, diffId)
+ }
+
+ /// Creates a diff step string from its components.
+ static func makeDiffStep(filename: String, added: Int, removed: Int, diffId: Int) -> String {
+ "\(diffStepMarker)\(filename)\t\(added):\(removed):\(diffId)"
+ }
+}
diff --git a/NotchBuddy/Sources/App/HookServer.swift b/NotchBuddy/Sources/App/HookServer.swift
index 5f21d514..ca734bfd 100644
--- a/NotchBuddy/Sources/App/HookServer.swift
+++ b/NotchBuddy/Sources/App/HookServer.swift
@@ -414,6 +414,7 @@ final class HookServer: @unchecked Sendable {
case "SessionStart":
activeSessionId = sessionId
if isExternalAgent { upsertExternalAgent(id: agentId, name: validAgent!) } else { upsertWorkspaceTask(id: agentId, projectName: projectName, cwd: cwd) }
+ if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) { state.tasks[idx].finalLine = nil }
nbLog("SessionStart \(isExternalAgent ? agentId : projectName) (\(sessionId.prefix(8)))")
if state.isPresent { expandIfNeeded(to: .overview) }
SoundEngine.shared.play("work")
@@ -421,6 +422,7 @@ final class HookServer: @unchecked Sendable {
case "UserPromptSubmit":
activeSessionId = sessionId
if isExternalAgent { upsertExternalAgent(id: agentId, name: validAgent!) } else { upsertWorkspaceTask(id: agentId, projectName: projectName, cwd: cwd) }
+ if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) { state.tasks[idx].finalLine = nil }
state.updateTask(id: agentId, state: .thinking)
if let prompt = payload["prompt"] as? String, !prompt.isEmpty {
appendStep(id: agentId, step: String(prompt.prefix(60)))
@@ -430,6 +432,7 @@ final class HookServer: @unchecked Sendable {
case "PreToolUse":
activeSessionId = sessionId
let tool = payload["tool_name"] as? String ?? "Tool"
+ if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) { state.tasks[idx].finalLine = nil }
// AskUserQuestion is handled via the dedicated --ask hook.
// Skip state/step update here to avoid flickering over the question card.
guard tool != "AskUserQuestion" else { break }
@@ -442,6 +445,14 @@ final class HookServer: @unchecked Sendable {
case "PostToolUse":
state.updateTask(id: agentId, state: .working)
+ // Live diff for Edit / MultiEdit / Write
+ let diffTool = payload["tool_name"] as? String ?? ""
+ let diffInput = payload["tool_input"] as? [String: Any] ?? [:]
+ if let diff = buildFileDiff(tool: diffTool, input: diffInput, pillId: agentId) {
+ let idx = state.appendSessionDiff(diff, for: agentId)
+ let step = String.makeDiffStep(filename: diff.name, added: diff.added, removed: diff.removed, diffId: idx)
+ appendStep(id: agentId, step: step)
+ }
case "PostToolUseFailure":
state.updateTask(id: agentId, state: .working)
@@ -460,8 +471,14 @@ final class HookServer: @unchecked Sendable {
case "Stop":
state.updateTask(id: agentId, state: .finished)
- if let message = payload["message"] as? String, !message.isEmpty {
- appendStep(id: agentId, step: String(message.prefix(60)))
+ let rawFinal = (payload["last_assistant_message"] as? String)
+ ?? (payload["message"] as? String) ?? ""
+ let finalText = DiffEngine.toOneLine(rawFinal)
+ if !finalText.isEmpty {
+ appendStep(id: agentId, step: finalText)
+ if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) {
+ state.tasks[idx].finalLine = finalText
+ }
}
SoundEngine.shared.play("finish")
if focused {
@@ -495,6 +512,8 @@ final class HookServer: @unchecked Sendable {
case "SessionEnd":
activeSessionId = nil
+ if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) { state.tasks[idx].finalLine = nil }
+ state.clearSessionDiffs(for: agentId)
state.removeTask(id: agentId)
case "SubagentStart":
@@ -982,6 +1001,45 @@ final class HookServer: @unchecked Sendable {
return "Exécute"
}
+ // MARK: - Live diff helpers
+
+ @MainActor
+ private func buildFileDiff(tool: String, input: [String: Any], pillId: String) -> FileDiff? {
+ switch tool {
+ case "Edit":
+ guard let old = input["old_string"] as? String,
+ let new = input["new_string"] as? String,
+ let path = input["file_path"] as? String,
+ !old.isEmpty || !new.isEmpty else { return nil }
+ let d = DiffEngine.fromEdit(old: old, new: new, path: path)
+ return (d.added > 0 || d.removed > 0) ? d : nil
+
+ case "MultiEdit":
+ guard let path = input["file_path"] as? String,
+ let edits = input["edits"] as? [[String: Any]], !edits.isEmpty else { return nil }
+ var totalAdded = 0, totalRemoved = 0, allHunks: [DiffHunk] = [], anyLarge = false
+ for edit in edits {
+ guard let old = edit["old_string"] as? String,
+ let new = edit["new_string"] as? String else { continue }
+ let d = DiffEngine.fromEdit(old: old, new: new, path: path)
+ totalAdded += d.added; totalRemoved += d.removed
+ allHunks.append(contentsOf: d.hunks); if d.tooLarge { anyLarge = true }
+ }
+ guard totalAdded > 0 || totalRemoved > 0 else { return nil }
+ return FileDiff(path: path, added: totalAdded, removed: totalRemoved,
+ hunks: allHunks, tooLarge: anyLarge, isNewFile: false)
+
+ case "Write":
+ guard let path = input["file_path"] as? String,
+ let content = input["content"] as? String, !content.isEmpty else { return nil }
+ let d = DiffEngine.fromNew(content: content, path: path)
+ return (d.added > 0 || d.removed > 0) ? d : nil
+
+ default:
+ return nil
+ }
+ }
+
/// Collapses whitespace so a multi-line command stays one ticker row.
private func oneLine(_ text: String, limit: Int = 60) -> String {
let collapsed = text.split(whereSeparator: { $0.isNewline || $0 == "\t" })
diff --git a/NotchBuddy/Sources/App/IslandTypes.swift b/NotchBuddy/Sources/App/IslandTypes.swift
index 356a0681..e4b0581b 100644
--- a/NotchBuddy/Sources/App/IslandTypes.swift
+++ b/NotchBuddy/Sources/App/IslandTypes.swift
@@ -59,6 +59,7 @@ struct AgentTask: Identifiable, Equatable {
var miniEye: EyeShape? = nil
var pillBadge: PillBadge? = nil // alert badge shown on pill when not focused
var sessionCwd: String? = nil // last known working directory (Claude Code sessions)
+ var finalLine: String? = nil // last assistant message shown as static text after Stop
}
enum AgentSource: Equatable {
diff --git a/NotchBuddy/Sources/App/IslandViewContent.swift b/NotchBuddy/Sources/App/IslandViewContent.swift
index 12749de4..40335816 100644
--- a/NotchBuddy/Sources/App/IslandViewContent.swift
+++ b/NotchBuddy/Sources/App/IslandViewContent.swift
@@ -34,6 +34,7 @@ struct IslandViewContent: View {
struct OverviewView: View {
@ObservedObject var state: AppState
@State private var showingN8nDetail = false
+ @State private var activeDiffId: Int? = nil
var agent: AgentTask? { state.focusTask }
@@ -46,7 +47,9 @@ struct OverviewView: View {
// Title row + ticker stacked (or integration card)
if let agent = agent {
if agent.isIntegration {
- IntegrationCardView(task: agent, showingDetail: $showingN8nDetail)
+ IntegrationCardView(task: agent, showingDetail: $showingN8nDetail, onDiffTap: { diffIdx in
+ withAnimation(.easeIn(duration: 0.16)) { activeDiffId = diffIdx }
+ })
} else {
VStack(alignment: .leading, spacing: 0) {
HStack(spacing: 6) {
@@ -82,7 +85,9 @@ struct OverviewView: View {
.padding(.leading, 108)
.padding(.trailing, 36)
- TickerView(task: agent)
+ TickerView(task: agent, onDiffTap: { diffIdx in
+ withAnimation(.easeIn(duration: 0.16)) { activeDiffId = diffIdx }
+ })
.frame(height: 44)
.padding(.top, 6)
.padding(.leading, 108)
@@ -102,11 +107,20 @@ struct OverviewView: View {
}
#endif
+ // Diff overlay — replaces ticker when a diff step is tapped
+ if let diffId = activeDiffId,
+ let task = agent,
+ let diff = state.sessionDiffs[task.id]?.first(where: { $0.id == diffId }) {
+ CardBackground(wash: nil)
+ DiffCardView(diff: diff, onDismiss: { activeDiffId = nil })
+ .transition(.opacity)
+ }
+
// ↗ jump button — last in ZStack so it renders on top; hidden while any detail is open
#if !APPSTORE
- let hideJumpButton = showingN8nDetail || state.showingPlanDetail
+ let hideJumpButton = showingN8nDetail || state.showingPlanDetail || activeDiffId != nil
#else
- let hideJumpButton = showingN8nDetail
+ let hideJumpButton = showingN8nDetail || activeDiffId != nil
#endif
if !hideJumpButton {
Button(action: { openAgentTarget(agent) }) {
@@ -132,16 +146,17 @@ struct OverviewView: View {
}
.onChange(of: state.focusId) { _, _ in
showingN8nDetail = false
+ activeDiffId = nil
#if !APPSTORE
withAnimation(.easeIn(duration: 0.16)) { state.showingPlanDetail = false }
#endif
}
#if !APPSTORE
.onChange(of: state.view) { _, v in
- if v != .overview { state.showingPlanDetail = false }
+ if v != .overview { state.showingPlanDetail = false; activeDiffId = nil }
}
.onChange(of: state.mode) { _, m in
- if m != .expanded { state.showingPlanDetail = false }
+ if m != .expanded { state.showingPlanDetail = false; activeDiffId = nil }
}
#endif
}
@@ -512,37 +527,226 @@ struct ErrorView: View {
struct FinishedView: View {
@ObservedObject var state: AppState
+ @State private var showingDiff: FileDiff? = nil
var body: some View {
ZStack {
CardBackground(wash: .green)
- VStack(alignment: .leading, spacing: 5) {
- AgentWho(task: state.focusTask, label: "Claude Code finished")
- Text(state.focusTask?.steps.last ?? "Session finished")
- .font(.system(size: 15, weight: .semibold))
- HStack(spacing: 8) {
- #if !APPSTORE
- PrimaryButton("Open terminal") {
- let terminalBundleIds = ["com.apple.Terminal", "com.googlecode.iterm2", "net.kovidgoyal.kitty", "com.mitchellh.ghostty"]
- let activated = terminalBundleIds.compactMap { id in
- NSWorkspace.shared.runningApplications.first { $0.bundleIdentifier == id }
- }.first.map { $0.activate(options: .activateIgnoringOtherApps) }
- if activated == nil {
- NSWorkspace.shared.open(URL(fileURLWithPath: "/System/Applications/Utilities/Terminal.app"))
+ if let diff = showingDiff {
+ DiffCardView(diff: diff, onDismiss: { showingDiff = nil })
+ .transition(.opacity)
+ } else {
+ VStack(alignment: .leading, spacing: 5) {
+ AgentWho(task: state.focusTask, label: "Claude Code finished")
+ Text({
+ if let fl = state.focusTask?.finalLine { return fl }
+ if let s = state.focusTask?.steps.last(where: { !$0.isDiffStep }) { return s }
+ return "Session finished"
+ }())
+ .font(.system(size: 15, weight: .semibold))
+ HStack(spacing: 8) {
+ #if !APPSTORE
+ PrimaryButton("Open terminal") {
+ let terminalBundleIds = ["com.apple.Terminal", "com.googlecode.iterm2", "net.kovidgoyal.kitty", "com.mitchellh.ghostty"]
+ let activated = terminalBundleIds.compactMap { id in
+ NSWorkspace.shared.runningApplications.first { $0.bundleIdentifier == id }
+ }.first.map { $0.activate(options: .activateIgnoringOtherApps) }
+ if activated == nil {
+ NSWorkspace.shared.open(URL(fileURLWithPath: "/System/Applications/Utilities/Terminal.app"))
+ }
+ NotificationCenter.default.post(name: .islandCollapse, object: nil)
+ }
+ #endif
+ SecondaryButton("OK") {
+ NotificationCenter.default.post(name: .islandCollapse, object: nil)
}
- NotificationCenter.default.post(name: .islandCollapse, object: nil)
}
- #endif
- SecondaryButton("OK") {
- NotificationCenter.default.post(name: .islandCollapse, object: nil)
+ // Touched files (up to 4)
+ let files = state.touchedFiles(for: state.focusTask?.id ?? "")
+ if !files.isEmpty {
+ let shown = Array(files.prefix(4))
+ VStack(alignment: .leading, spacing: 2) {
+ ForEach(shown.indices, id: \.self) { i in
+ let f = shown[i]
+ Button(action: {
+ withAnimation(.easeIn(duration: 0.16)) {
+ if let taskId = state.focusTask?.id,
+ let diffs = state.sessionDiffs[taskId],
+ let last = diffs.last(where: { $0.path == f.path }) {
+ showingDiff = last
+ }
+ }
+ }) {
+ HStack(spacing: 4) {
+ Text(URL(fileURLWithPath: f.path).lastPathComponent)
+ .font(.system(size: 10.5))
+ .foregroundColor(Color(hex: "#9398A1"))
+ .lineLimit(1).truncationMode(.middle)
+ if f.added > 0 {
+ Text("+\(f.added)")
+ .font(.system(size: 9, weight: .medium).monospaced())
+ .foregroundColor(Color(hex: "#22C55E"))
+ }
+ if f.removed > 0 {
+ Text("−\(f.removed)")
+ .font(.system(size: 9, weight: .medium).monospaced())
+ .foregroundColor(Color(hex: "#F4505E"))
+ }
+ }
+ }
+ .buttonStyle(.plain)
+ }
+ if files.count > 4 {
+ Text("+ \(files.count - 4) more")
+ .font(.system(size: 10))
+ .foregroundColor(Color(hex: "#6B7079"))
+ }
+ }
+ }
+ }
+ .padding(.leading, 116)
+ .padding(.trailing, 16)
+ .padding(.vertical, 4)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .transition(.opacity)
+ }
+ }
+ }
+}
+
+// MARK: - Diff Card
+
+struct DiffCardView: View {
+ let diff: FileDiff
+ let onDismiss: () -> Void
+
+ private var allLines: [DiffLine] { diff.hunks.flatMap { $0.lines } }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ // Header
+ HStack(spacing: 6) {
+ Button(action: onDismiss) {
+ HStack(spacing: 3) {
+ Image(systemName: "chevron.left")
+ .font(.system(size: 8, weight: .medium))
+ Text(diff.name)
+ .font(.system(size: 12, weight: .semibold))
+ .lineLimit(1)
+ }
+ .foregroundColor(Color(hex: "#F5F6F8"))
+ }
+ .buttonStyle(.plain)
+ Spacer(minLength: 2)
+ if diff.added > 0 {
+ Text("+\(diff.added)")
+ .font(.system(size: 10, weight: .medium).monospaced())
+ .foregroundColor(Color(hex: "#22C55E"))
+ }
+ if diff.removed > 0 {
+ Text("−\(diff.removed)")
+ .font(.system(size: 10, weight: .medium).monospaced())
+ .foregroundColor(Color(hex: "#F4505E"))
+ }
+ Button(action: { openInEditor(diff) }) {
+ Image(systemName: "arrow.up.right")
+ .font(.system(size: 8, weight: .medium))
+ .foregroundColor(Color(hex: "#5F646D"))
+ .frame(width: 14, height: 14)
+ .background(Color.white.opacity(0.07))
+ .clipShape(Circle())
+ }
+ .buttonStyle(.plain)
+ }
+ .padding(.top, 6)
+ .padding(.bottom, 3)
+
+ // Content
+ if diff.tooLarge {
+ Text("Diff too large")
+ .font(.system(size: 10.5))
+ .foregroundColor(Color(hex: "#6B7079"))
+ } else if allLines.isEmpty {
+ Text("No changes")
+ .font(.system(size: 10.5))
+ .foregroundColor(Color(hex: "#6B7079"))
+ } else {
+ ScrollView(.vertical, showsIndicators: false) {
+ VStack(alignment: .leading, spacing: 0) {
+ ForEach(Array(allLines.enumerated()), id: \.offset) { _, line in
+ DiffLineRowView(line: line)
+ }
}
}
}
- .padding(.leading, 116)
- .padding(.trailing, 16)
- .padding(.vertical, 4)
- .frame(maxWidth: .infinity, alignment: .leading)
}
+ .padding(.leading, 108)
+ .padding(.trailing, 10)
+ .padding(.vertical, 4)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
+ .onExitCommand { onDismiss() }
+ }
+
+ private func openInEditor(_ diff: FileDiff) {
+ let path = diff.path
+ #if !APPSTORE
+ let codePaths = ["/opt/homebrew/bin/code", "/usr/local/bin/code", "/usr/bin/code",
+ "\(NSHomeDirectory())/.nvm/current/bin/code"]
+ if let codePath = codePaths.first(where: { FileManager.default.fileExists(atPath: $0) }) {
+ let p = Process()
+ p.executableURL = URL(fileURLWithPath: codePath)
+ // Write: open at line 1; Edit/MultiEdit: open file without line number
+ p.arguments = diff.isNewFile ? ["-g", "\(path):1"] : [path]
+ try? p.run()
+ return
+ }
+ #endif
+ NSWorkspace.shared.open(URL(fileURLWithPath: path))
+ }
+}
+
+struct DiffLineRowView: View {
+ let line: DiffLine
+
+ private var bgColor: Color {
+ switch line.kind {
+ case .added: return Color(hex: "#22C55E").opacity(0.12)
+ case .removed: return Color(hex: "#F4505E").opacity(0.12)
+ case .context: return Color.clear
+ }
+ }
+ private var fgColor: Color {
+ switch line.kind {
+ case .added: return Color(hex: "#86EFAC")
+ case .removed: return Color(hex: "#FCA5A5")
+ case .context: return Color(hex: "#6B7079")
+ }
+ }
+ private var symbol: String {
+ switch line.kind {
+ case .added: return "+"
+ case .removed: return "−"
+ case .context: return " "
+ }
+ }
+
+ var body: some View {
+ HStack(spacing: 0) {
+ Text(symbol)
+ .font(.system(size: 10.5).monospaced())
+ .foregroundColor(line.kind == .added ? Color(hex: "#22C55E") :
+ line.kind == .removed ? Color(hex: "#F4505E") :
+ Color(hex: "#454850"))
+ .frame(width: 12, alignment: .leading)
+ Text(line.text)
+ .font(.system(size: 10.5).monospaced())
+ .foregroundColor(fgColor)
+ .lineLimit(1)
+ .truncationMode(.tail)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .background(bgColor)
+ .frame(maxWidth: .infinity)
}
}
@@ -1390,6 +1594,7 @@ struct NoteView: View {
struct IntegrationCardView: View {
let task: AgentTask
@Binding var showingDetail: Bool
+ var onDiffTap: ((Int) -> Void)? = nil
@ObservedObject private var appState = AppState.shared
private var isConfigured: Bool {
@@ -1637,7 +1842,7 @@ struct IntegrationCardView: View {
.padding(.leading, 108)
.padding(.trailing, 36)
- TickerView(task: task)
+ TickerView(task: task, onDiffTap: onDiffTap)
.frame(height: 44)
.padding(.top, 6)
.padding(.leading, 108)
@@ -2648,6 +2853,7 @@ struct N8nDetailView: View {
struct TickerView: View {
let task: AgentTask?
+ var onDiffTap: ((Int) -> Void)? = nil
@State private var rowA: String = "…" // completed (above, left-shifted)
@State private var rowB: String = "…" // current (below) → animates diagonally up-left
@@ -2671,22 +2877,26 @@ struct TickerView: View {
}
var body: some View {
+ let isActive = task?.state == .thinking || task?.state == .working
+ let rowADiffTap: (() -> Void)? = rowA.parseDiffStep().map { dp in { onDiffTap?(dp.diffId) } }
+ let rowBDiffTap: (() -> Void)? = rowB.parseDiffStep().map { dp in { onDiffTap?(dp.diffId) } }
+
ZStack(alignment: .topLeading) {
Color.clear
// Row A: completed row — always rendered at phase=1 + completedScale
- TickerRowView(text: rowA, phase: 1.0)
+ TickerRowView(text: rowA, phase: 1.0, isActive: isActive, onDiffTap: rowADiffTap)
.scaleEffect(completedScale, anchor: .leading)
.offset(x: -10, y: rowAOffset)
.opacity(rowAOpacity)
// Row B: current step → animates diagonally up-left, phase 0→1, scale 1→completedScale
- TickerRowView(text: rowB, phase: rowBPhase)
+ TickerRowView(text: rowB, phase: rowBPhase, isActive: isActive, onDiffTap: rowBDiffTap)
.scaleEffect(1 - rowBPhase * (1 - completedScale), anchor: .leading)
.offset(x: -rowBPhase * 10, y: rowBOffset)
// Row C: incoming new step — slides in from below at phase=0
- TickerRowView(text: rowC, phase: 0.0)
+ TickerRowView(text: rowC, phase: 0.0, isActive: isActive)
.offset(y: rowCOffset)
.opacity(rowCOpacity)
}
@@ -2765,35 +2975,87 @@ struct TickerView: View {
struct TickerRowView: View {
let text: String
let phase: Double // 0 = current (shimmer, large), 1 = completed (dim, scaled down by caller)
+ var isActive: Bool = true
+ var onDiffTap: (() -> Void)? = nil
var body: some View {
- HStack(spacing: 6) {
- // Icon: chevron fades out first half, checkmark fades in second half
- ZStack {
- Image(systemName: "chevron.right")
- .font(.system(size: 9, weight: .medium))
- .foregroundColor(Color(hex: "#8E939C"))
- .opacity(max(0, 1 - phase * 2))
- Image(systemName: "checkmark")
- .font(.system(size: 8, weight: .regular))
- .foregroundColor(Color(hex: "#454850"))
- .opacity(max(0, phase * 2 - 1))
- }
- .frame(width: 12, alignment: .center)
-
- // Text: shimmer fades out, dim completed text fades in (overlapping cross-fade)
- ZStack(alignment: .leading) {
- TickerShimmerText(text: text)
- .opacity(max(0, 1 - phase * 1.6))
- Text(text)
- .font(.system(size: 13, weight: .medium))
- .foregroundColor(Color(hex: "#6B7079"))
- .lineLimit(1).truncationMode(.tail)
- .opacity(min(1, max(0, phase * 2 - 0.4)))
+ let chevronOpacity: Double = isActive ? max(0, 1 - phase * 2) : 0
+ let checkmarkOpacity: Double = isActive ? max(0, phase * 2 - 1) : 1
+ let shimmerOpacity: Double = isActive ? max(0, 1 - phase * 1.6) : 0
+ let staticOpacity: Double = isActive ? min(1, max(0, phase * 2 - 0.4)) : 1
+ let staticColor = (!isActive && phase < 0.5) ? Color(hex: "#C9CDD4") : Color(hex: "#6B7079")
+
+ if let dp = text.parseDiffStep() {
+ HStack(spacing: 6) {
+ ZStack {
+ Image(systemName: "chevron.right")
+ .font(.system(size: 9, weight: .medium))
+ .foregroundColor(Color(hex: "#8E939C"))
+ .opacity(chevronOpacity)
+ Image(systemName: "checkmark")
+ .font(.system(size: 8, weight: .regular))
+ .foregroundColor(Color(hex: "#454850"))
+ .opacity(checkmarkOpacity)
+ }
+ .frame(width: 12, alignment: .center)
+ // Filename + counts
+ HStack(spacing: 0) {
+ ZStack(alignment: .leading) {
+ TickerShimmerText(text: dp.filename)
+ .opacity(shimmerOpacity)
+ Text(dp.filename)
+ .font(.system(size: 13, weight: .medium))
+ .foregroundColor(staticColor)
+ .lineLimit(1).truncationMode(.tail)
+ .opacity(staticOpacity)
+ }
+ if dp.added > 0 {
+ Text(" +\(dp.added)")
+ .font(.system(size: 10, weight: .medium).monospaced())
+ .foregroundColor(Color(hex: "#22C55E"))
+ .fixedSize()
+ }
+ if dp.removed > 0 {
+ Text(" −\(dp.removed)")
+ .font(.system(size: 10, weight: .medium).monospaced())
+ .foregroundColor(Color(hex: "#F4505E"))
+ .fixedSize()
+ }
+ }
+ }
+ .frame(height: 22, alignment: .leading)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .contentShape(Rectangle())
+ .onTapGesture { onDiffTap?() }
+ } else {
+ HStack(spacing: 6) {
+ // Icon: chevron fades out first half, checkmark fades in second half
+ ZStack {
+ Image(systemName: "chevron.right")
+ .font(.system(size: 9, weight: .medium))
+ .foregroundColor(Color(hex: "#8E939C"))
+ .opacity(chevronOpacity)
+ Image(systemName: "checkmark")
+ .font(.system(size: 8, weight: .regular))
+ .foregroundColor(Color(hex: "#454850"))
+ .opacity(checkmarkOpacity)
+ }
+ .frame(width: 12, alignment: .center)
+
+ // Text: shimmer fades out, dim completed text fades in (overlapping cross-fade)
+ ZStack(alignment: .leading) {
+ TickerShimmerText(text: text)
+ .opacity(shimmerOpacity)
+ Text(text)
+ .font(.system(size: 13, weight: .medium))
+ .foregroundColor(staticColor)
+ .lineLimit(1).truncationMode(.tail)
+ .opacity(staticOpacity)
+ }
}
+ .frame(height: 22, alignment: .leading)
+ .frame(maxWidth: .infinity, alignment: .leading)
}
- .frame(height: 22, alignment: .leading)
- .frame(maxWidth: .infinity, alignment: .leading)
}
}
diff --git a/README.md b/README.md
index 59d88d36..4ccd8070 100644
--- a/README.md
+++ b/README.md
@@ -33,6 +33,7 @@ Meet **Mochi**: a soft little squircle with big eyes that pops out of your notch
## Features
- 🤖 **Claude Code, Cursor, Codex, Gemini CLI, Antigravity and other agents, live** — see every session in your notch: what it reads, edits and runs, step by step. Tag a hook payload with `coucou_agent` to give any agent its own pill (see [`docs/AGENTS.md`](docs/AGENTS.md)). Finished? Mochi does a happy little jump.
+- See what Claude is editing, live in the notch: each file modification shows the file name and +N −M counts in the ticker, tap to read the full diff
- ✅ **Approve and answer from the notch** — Claude Code permission requests show up with **Allow / Deny / Always**; `AskUserQuestion` prompts show the choices right in the notch (single or multi-select, up to 4 questions). One click, or "Reply in terminal" to fall back to the CLI. Codex also gets Allow / Deny.
- 🧑‍💻 **Jump to the right terminal** — open the exact terminal window of a session *(macOS)*.
- 💬 **Chat with Claude, Gemini, OpenAI, or a local model (Ollama / LM Studio)** — click the model name above the chat box to switch provider and pick a model. Cloud providers use your own API key; local providers connect to a server running on your Mac. *(Gemini, OpenAI and local models: macOS)*
diff --git a/docs/INTEGRATIONS.md b/docs/INTEGRATIONS.md
index 4b1e58f5..8eed56de 100644
--- a/docs/INTEGRATIONS.md
+++ b/docs/INTEGRATIONS.md
@@ -114,6 +114,29 @@ Réglages → Agents → Plan usage → **Uninstall relay**. Remet l'objet `stat
---
+## 1ter. Diff en direct (live diff)
+
+Sur `PostToolUse` pour `Edit`, `MultiEdit` et `Write` (Claude Code, Cursor), l'app calcule un diff ligne à ligne et l'affiche dans le fil de l'île.
+
+**Données**
+- `Edit` : `old_string → new_string`
+- `MultiEdit` : liste `edits`, chaque entrée `old_string → new_string`
+- `Write` : `content` — tout le contenu est compté en ajout (on ne lit jamais le fichier sur le disque)
+- Le diff est calculé localement (Foundation, jamais de lecture sur le disque).
+- Limite : 200 Ko de texte combiné ou 4 000 lignes combinées → bilan seul, "Diff too large".
+- Mémoire : 50 diffs max par session, les plus anciens sont oubliés ; tout effacé à la fin de la session (`SessionEnd`) ou après une heure sans activité.
+
+**Fil (TickerView)** — les étapes de modification affichent le nom du fichier, `+N` en vert `#22C55E` et `−M` en rouge `#F4505E`, petits et monospacés.
+
+**Carte diff** — un clic sur une étape de modification ouvre la carte diff dans la vue principale :
+- En-tête : nom du fichier + bilan + bouton ↗ (ouvre dans VS Code via `code -g fichier:ligne`, sinon `NSWorkspace`)
+- Lignes en monospace 10,5 pt, fond vert ou rouge à 12 %, symbole +/− en marge, 3 lignes de contexte
+- Défilement vertical ; Échap ou clic sur l'en-tête pour revenir au fil
+
+**Vue Terminé (FinishedView)** — liste les fichiers touchés (nom + bilan, 4 au plus, puis "+ N more"). Un clic affiche la carte diff du dernier diff connu pour ce fichier.
+
+---
+
## 2. n8n (workflows de Louis)
- Réglages : URL de l'instance (probablement `https://n8nlouis.dcsys.tech`, **à confirmer avec Louis**) et clé API n8n (Trousseau). La clé se crée dans n8n : Settings → n8n API.
diff --git a/docs/SPEC.md b/docs/SPEC.md
index 3a0a41dd..b35fd8b2 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -88,6 +88,10 @@ Centre vertical du bonhomme : 36 + (hauteur − 46) / 2, sauf `result` (y = 86).
- Toutes les 2,8 s, si la tâche en focus travaille : tout monte de 30 pt en 450 ms `cubic-bezier(.3,.9,.3,1)`.
- Dans l'app réelle, les lignes = les dernières actions de la session (outil + cible : « Edit Invoice.swift », « Bash npm test ») ou les nœuds n8n.
+### Diff en direct
+
+Quand une étape du fil est une modification de fichier (préfixe interne `\u{E001}`), elle s'affiche avec le nom du fichier et le bilan `+N −M` en couleur. Un clic sur la ligne courante ou la ligne précédente ouvre la carte diff (voir DiffCardView) dans la carte gauche de la vue principale, en remplacement du fil — que la pastille soit intégrée (integration_claude, agent_cursor…) ou non. Échap ou le bouton ← de l'en-tête ferme la carte. La vue Terminé liste les fichiers touchés. En fin de tâche (Stop), la ligne courante du fil passe en texte statique (couleur `#C9CDD4`, sans brillance) tant que la tâche n'est pas relancée ; elle est construite à partir du dernier message de l'assistant (champ `last_assistant_message` de l'événement Stop, nettoyé du Markdown par `DiffEngine.toOneLine`).
+
### Pastilles (overview)
- 132 × 34, rayon 17, fond couleur de l'agent à 13 %, bord à 32 %, mini-bonhomme Ø 24 centré à 17 pt du bord gauche, libellé 12 pt couleur de l'agent éclaircie de 25 %. Deux colonnes, écart 8, centrées verticalement dans la carte droite (qui commence à x = 342).
diff --git a/docs/privacy.html b/docs/privacy.html
index 980b37fd..e47b1e3d 100644
--- a/docs/privacy.html
+++ b/docs/privacy.html
@@ -20,7 +20,7 @@
<tr><td>API keys and tokens you enter (Anthropic, Google AI, OpenAI, Stripe, GitHub, Vercel, Resend, Notion, Cal.com, n8n)</td><td>macOS Keychain, Windows Credential Manager, or the Secret Service on Linux (GNOME Keyring, KWallet)</td><td>To call these services on your behalf</td></tr>
<tr><td>Preferences (sound, delays, active pill selection, chat provider and model, shortcut)</td><td>App preferences on your Mac, or <code>%APPDATA%\Coucou</code> on Windows; <code>~/.config/coucou</code> on Linux</td><td>To remember your settings</td></tr>
<tr><td>Files you drop on the notch</td><td>A copy in the app’s own folder (on Windows: <code>%LOCALAPPDATA%\Coucou</code>; on Linux: <code>~/.local/share/coucou</code>)</td><td>So you can ask a question about them or attach them to an email</td></tr>
-<tr><td>Claude Code session events (project name, current step, permission requests)</td><td>In memory only</td><td>To show them in the notch</td></tr>
+<tr><td>Claude Code session events (project name, current step, permission requests, file edits received from hooks)</td><td>In memory only</td><td>To show them in the notch</td></tr>
<tr><td>Diagnostic log (event and tool names, project names, HTTP status codes — no commands, content or API keys)</td><td><code>~/Library/Logs/NotchBuddy</code> on Mac (App Store: same path inside the container); <code>%LOCALAPPDATA%\Coucou\coucou.log</code> on Windows; <code>~/.local/share/coucou/coucou.log</code> on Linux. Capped at 1 MB. Never leaves your computer.</td><td>To help diagnose connection issues between Claude Code and Coucou</td></tr>
</table>
<p>You can delete all of this at any time by removing your keys in Settings, then deleting the app and its folder in <code>~/Library/Application Support/NotchBuddy</code> (or the app’s container for the App Store version). On Windows: uninstall Coucou from Settings → Apps, then delete <code>%APPDATA%\Coucou</code> and <code>%LOCALAPPDATA%\Coucou</code>. On Linux: remove the package (<code>sudo apt remove coucou</code> or <code>sudo dnf remove coucou</code>) or delete the AppImage, then delete <code>~/.config/coucou</code>, <code>~/.local/share/coucou</code>, <code>~/.local/share/fr.louisraille.coucou</code> and <code>~/.cache/coucou</code>.</p>
@@ -37,7 +37,7 @@
<p>We have no access to these requests or their responses.</p>
<h2>5. Claude Code, Gemini CLI, Antigravity and Codex hooks</h2>
-<p>If you install the Claude Code hooks, Claude Code sends session events to Coucou through a local connection on your computer. If you install the Gemini CLI, Antigravity or Codex hooks, those agents send their session events the same way. These events never leave your computer through Coucou. If you install the Plan usage status line, Claude Code also passes the percentage used and the reset times of your plan windows to Coucou through the same local connection; nothing leaves your computer. Before changing any settings file (<code>~/.claude/settings.json</code>, <code>~/.gemini/settings.json</code>, <code>~/.gemini/config/hooks.json</code>, <code>~/.codex/hooks.json</code>), Coucou makes a dated backup and shows you the changes.</p>
+<p>If you install the Claude Code hooks, Claude Code sends session events to Coucou through a local connection on your computer. If you install the Gemini CLI, Antigravity or Codex hooks, those agents send their session events the same way. These events never leave your computer through Coucou. If you install the Plan usage status line, Claude Code also passes the percentage used and the reset times of your plan windows to Coucou through the same local connection; nothing leaves your computer. Before changing any settings file (<code>~/.claude/settings.json</code>, <code>~/.gemini/settings.json</code>, <code>~/.gemini/config/hooks.json</code>, <code>~/.codex/hooks.json</code>), Coucou makes a dated backup and shows you the changes. File edits (the old and new text received from Edit, MultiEdit and Write hooks) are kept in memory for the duration of the session and deleted when the session ends or after one hour of inactivity; they never leave your computer.</p>
<h2>6. Apple Music</h2>
<p>If you activate the Apple Music pill <i>(macOS, GitHub build)</i>, Coucou reads the current track (title, artist, album) from Music on your Mac to display it in the notch, and only sends play, pause or skip commands to Music when you click. Nothing leaves your computer.</p>
@@ -93,7 +93,7 @@
<p>Le développeur n’a accès ni à ces requêtes ni à leurs réponses.</p>
<h2>5. Claude Code, Gemini CLI, Antigravity et Codex</h2>
-<p>Si tu installes les hooks Claude Code, Claude Code envoie les événements de session à Coucou par une connexion locale sur ton ordinateur. Si tu installes les hooks Gemini CLI, Antigravity ou Codex, ces agents envoient leurs événements de la même façon. Coucou ne les fait jamais sortir de ton ordinateur. Si tu installes le relais de jauge de forfait (Plan usage), Claude Code transmet aussi à Coucou, par la même connexion locale, les pourcentages utilisés et les heures de remise à zéro de tes fenêtres de forfait ; rien ne quitte ton ordinateur. Avant de modifier un fichier de configuration (<code>~/.claude/settings.json</code>, <code>~/.gemini/settings.json</code>, <code>~/.gemini/config/hooks.json</code>, <code>~/.codex/hooks.json</code>), Coucou en fait une sauvegarde datée et te montre les changements.</p>
+<p>Si tu installes les hooks Claude Code, Claude Code envoie les événements de session à Coucou par une connexion locale sur ton ordinateur. Si tu installes les hooks Gemini CLI, Antigravity ou Codex, ces agents envoient leurs événements de la même façon. Coucou ne les fait jamais sortir de ton ordinateur. Si tu installes le relais de jauge de forfait (Plan usage), Claude Code transmet aussi à Coucou, par la même connexion locale, les pourcentages utilisés et les heures de remise à zéro de tes fenêtres de forfait ; rien ne quitte ton ordinateur. Avant de modifier un fichier de configuration (<code>~/.claude/settings.json</code>, <code>~/.gemini/settings.json</code>, <code>~/.gemini/config/hooks.json</code>, <code>~/.codex/hooks.json</code>), Coucou en fait une sauvegarde datée et te montre les changements. Les modifications de fichiers (l'ancien et le nouveau texte reçus via les hooks Edit, MultiEdit et Write) sont conservées en mémoire pendant la durée de la session et supprimées à la fin de la session ou après une heure d'inactivité ; elles ne quittent jamais ton ordinateur.</p>
<h2>6. Apple Music</h2>
<p>Si tu actives la pastille Apple Music <i>(macOS, version GitHub)</i>, Coucou lit le morceau en cours (titre, artiste, album) depuis l’app Musique de ton Mac pour l’afficher dans le notch, et n’envoie lecture, pause ou morceau suivant à Musique que quand tu cliques. Rien ne quitte ton ordinateur.</p>
diff --git a/scripts/test-diff-engine.sh b/scripts/test-diff-engine.sh
new file mode 100755
index 00000000..e2493478
--- /dev/null
+++ b/scripts/test-diff-engine.sh
@@ -0,0 +1,8 @@
+#!/usr/bin/env bash
+set -euo pipefail
+cd "$(dirname "$0")/.."
+TEST_DIR="$(mktemp -d "${TMPDIR:-/tmp}/coucou-diff-engine.XXXXXX")"
+trap 'rm -rf "$TEST_DIR"' EXIT
+swiftc NotchBuddy/Sources/App/DiffEngine.swift \
+ tests/DiffEngineTests.swift -o "$TEST_DIR/diff-engine-tests"
+"$TEST_DIR/diff-engine-tests"
diff --git a/tests/DiffEngineTests.swift b/tests/DiffEngineTests.swift
new file mode 100644
index 00000000..d5cb223f
--- /dev/null
+++ b/tests/DiffEngineTests.swift
@@ -0,0 +1,189 @@
+import Foundation
+
+@main
+enum DiffEngineTests {
+
+ static var failures = 0
+
+ static func checkTrue(_ label: String, _ value: Bool) {
+ if value { print(" ✓ \(label)") }
+ else { print(" ✗ \(label)"); failures += 1 }
+ }
+
+ static func checkInt(_ label: String, _ got: Int, _ expected: Int) {
+ if got == expected { print(" ✓ \(label)") }
+ else { print(" ✗ \(label) got: \(got) expected: \(expected)"); failures += 1 }
+ }
+
+ static func main() {
+
+ // ── DiffEngine.fromEdit — additions ───────────────────────────────────
+ print("DiffEngine.fromEdit — additions")
+ do {
+ let d = DiffEngine.fromEdit(old: "", new: "hello\nworld\n", path: "/a/b.swift")
+ checkInt("added == 2", d.added, 2)
+ checkInt("removed == 0", d.removed, 0)
+ checkTrue("!tooLarge", !d.tooLarge)
+ checkTrue("1 hunk", d.hunks.count == 1)
+ checkTrue("name == b.swift", d.name == "b.swift")
+ }
+
+ // ── DiffEngine.fromEdit — removals ────────────────────────────────────
+ print("DiffEngine.fromEdit — removals")
+ do {
+ let d = DiffEngine.fromEdit(old: "hello\nworld\n", new: "", path: "/x.py")
+ checkInt("added == 0", d.added, 0)
+ checkInt("removed == 2", d.removed, 2)
+ checkTrue("1 hunk", d.hunks.count == 1)
+ }
+
+ // ── DiffEngine.fromEdit — replacement ─────────────────────────────────
+ print("DiffEngine.fromEdit — replacement")
+ do {
+ let d = DiffEngine.fromEdit(old: "foo\nbar\nbaz\n",
+ new: "foo\nqux\nbaz\n",
+ path: "/f.ts")
+ checkInt("added == 1", d.added, 1)
+ checkInt("removed == 1", d.removed, 1)
+ checkTrue("has context lines",
+ d.hunks.first?.lines.contains(where: { $0.kind == .context }) == true)
+ }
+
+ // ── DiffEngine.fromNew — new file ──────────────────────────────────────
+ print("DiffEngine.fromNew — new file")
+ do {
+ let d = DiffEngine.fromNew(content: "line1\nline2\nline3\n", path: "/new.rs")
+ checkInt("added == 3", d.added, 3)
+ checkInt("removed == 0", d.removed, 0)
+ checkTrue("all lines .added",
+ d.hunks.flatMap { $0.lines }.allSatisfy { $0.kind == .added })
+ }
+
+ // ── DiffEngine.fromEdit — MultiEdit (two edits) ────────────────────────
+ print("DiffEngine.fromEdit — MultiEdit (two edits)")
+ do {
+ let d1 = DiffEngine.fromEdit(old: "aaa\n", new: "bbb\n", path: "/m.kt")
+ let d2 = DiffEngine.fromEdit(old: "ccc\n", new: "ddd\n", path: "/m.kt")
+ checkInt("d1 added == 1", d1.added, 1)
+ checkInt("d1 removed == 1", d1.removed, 1)
+ checkInt("d2 added == 1", d2.added, 1)
+ checkInt("d2 removed == 1", d2.removed, 1)
+ }
+
+ // ── DiffEngine — tooLarge ──────────────────────────────────────────────
+ print("DiffEngine — tooLarge")
+ do {
+ // Generate > 200 KB combined content
+ let bigOld = String(repeating: "x", count: 150 * 1024)
+ let bigNew = String(repeating: "y", count: 60 * 1024)
+ let d = DiffEngine.fromEdit(old: bigOld, new: bigNew, path: "/big.swift")
+ checkTrue("tooLarge == true", d.tooLarge)
+ checkTrue("hunks.isEmpty", d.hunks.isEmpty)
+ }
+
+ // ── DiffEngine — CRLF ─────────────────────────────────────────────────
+ print("DiffEngine — CRLF")
+ do {
+ let d = DiffEngine.fromEdit(old: "a\r\nb\r\n", new: "a\r\nc\r\n", path: "/win.txt")
+ checkInt("added == 1", d.added, 1)
+ checkInt("removed == 1", d.removed, 1)
+ }
+
+ // ── DiffEngine — no trailing newline ──────────────────────────────────
+ print("DiffEngine — no trailing newline")
+ do {
+ let d = DiffEngine.fromEdit(old: "hello", new: "hello\nworld", path: "/t.txt")
+ checkInt("added == 1", d.added, 1)
+ checkInt("removed == 0", d.removed, 0)
+ }
+
+ // ── DiffEngine — 3-line context ───────────────────────────────────────
+ print("DiffEngine — 3-line context")
+ do {
+ // 10-line file, change line 5
+ let oldContent = (1...10).map { "line\($0)" }.joined(separator: "\n") + "\n"
+ let newContent = (1...10).map { $0 == 5 ? "changed" : "line\($0)" }.joined(separator: "\n") + "\n"
+ let d = DiffEngine.fromEdit(old: oldContent, new: newContent, path: "/ctx.swift")
+ checkInt("added == 1", d.added, 1)
+ checkInt("removed == 1", d.removed, 1)
+ checkTrue("1 hunk", d.hunks.count == 1)
+ let hunk = d.hunks[0]
+ let contextLines = hunk.lines.filter { $0.kind == .context }
+ checkTrue("has context before change", contextLines.count >= 3)
+ }
+
+ // ── DiffEngine — m*n > 1_000_000 → tooLarge ─────────────────────────
+ print("DiffEngine — m*n > 1_000_000 → tooLarge")
+ do {
+ // 1001 old lines × 1001 new lines = > 1M
+ let many = (0..<1001).map { "line\($0)" }.joined(separator: "\n")
+ let d = DiffEngine.fromEdit(old: many, new: many + "\nextra", path: "/big.swift")
+ checkTrue("tooLarge when m*n > 1M", d.tooLarge)
+ checkTrue("hunks empty", d.hunks.isEmpty)
+ }
+
+ // ── DiffEngine.fromNew — too large ────────────────────────────────────
+ print("DiffEngine.fromNew — too large")
+ do {
+ let bigContent = String(repeating: "x\n", count: FileDiff.maxLines + 1)
+ let d = DiffEngine.fromNew(content: bigContent, path: "/new.swift")
+ checkTrue("fromNew tooLarge", d.tooLarge)
+ checkTrue("fromNew isNewFile", d.isNewFile)
+ checkTrue("fromNew hunks empty", d.hunks.isEmpty)
+ checkTrue("fromNew added > 0", d.added > 0)
+ }
+
+ // ── String.makeDiffStep / parseDiffStep ───────────────────────────────
+ print("String.makeDiffStep / parseDiffStep")
+ do {
+ let s = String.makeDiffStep(filename: "foo.swift", added: 3, removed: 1, diffId: 7)
+ checkTrue("isDiffStep", s.isDiffStep)
+ let parsed = s.parseDiffStep()
+ checkTrue("parsed != nil", parsed != nil)
+ checkTrue("filename round-trips", parsed?.filename == "foo.swift")
+ checkTrue("added round-trips", parsed?.added == 3)
+ checkTrue("removed round-trips", parsed?.removed == 1)
+ checkTrue("diffId round-trips", parsed?.diffId == 7)
+
+ // id > 9 (multi-digit) round-trips correctly
+ let s2 = String.makeDiffStep(filename: "bar.ts", added: 0, removed: 2, diffId: 42)
+ checkTrue("diffId 42 round-trips", s2.parseDiffStep()?.diffId == 42)
+
+ // Non-diff step should not parse
+ checkTrue("normal step !isDiffStep", !"Edit foo.swift".isDiffStep)
+ checkTrue("normal step parseDiffStep == nil", "Edit foo.swift".parseDiffStep() == nil)
+ }
+
+ // ── DiffEngine.toOneLine ──────────────────────────────────────────────
+ print("DiffEngine.toOneLine")
+ do {
+ // multi-line joined with space
+ checkTrue("multi-line joined",
+ DiffEngine.toOneLine("line one\nline two\nline three") == "line one line two line three")
+
+ // bold stripped
+ checkTrue("bold stripped",
+ DiffEngine.toOneLine("**hello** world") == "hello world")
+
+ // heading stripped
+ checkTrue("heading stripped",
+ DiffEngine.toOneLine("## My Title\nsome text") == "My Title some text")
+
+ // empty input → empty
+ checkTrue("empty → empty", DiffEngine.toOneLine("").isEmpty)
+
+ // truncation
+ let long = DiffEngine.toOneLine(String(repeating: "x ", count: 200), maxChars: 10)
+ checkTrue("truncated to maxChars", long.count <= 10)
+ }
+
+ // ── finish ─────────────────────────────────────────────────────────────
+ if failures == 0 {
+ print("\nAll tests passed.")
+ exit(0)
+ } else {
+ print("\n\(failures) test(s) failed.")
+ exit(1)
+ }
+ }
+}