From 0ebe929567ccf5dd0173d6caf7457ae1599f9b60 Mon Sep 17 00:00:00 2001 From: Dawid Buszta <344369893+MF-DEEV@users.noreply.github.com> Date: Thu, 22 Oct 2026 18:24:12 +0200 Subject: [PATCH 1/6] feat(sessions): give every session and subagent a clawd in its own costume Each session draws a pixel Clawd costume (shell, hat, eyewear, extra) by lot from its id, the same on every launch. Subagents draw their own and wear the color their definition gives them. The Clawd waddles, types, hops for a permission, cheers when work ends and dozes when quiet; Reduce Motion keeps one pose. Clicking it on a session's page opens a wardrobe in the island, and the choice is kept for that session. --- Sources/Vorssaint/Core/Defaults.swift | 7 + .../Core/NotchClaudeSessionStrings.swift | 46 +- .../ClaudeSessions/ClaudeAgentColors.swift | 166 ++++++ .../ClaudeSessions/ClaudeSessionModels.swift | 2 + .../ClaudeSessions/ClaudeSessionService.swift | 50 +- .../ClaudeSessions/ClawdCostume.swift | 195 +++++++ .../Notch/NotchClaudeSessionsSupport.swift | 77 ++- .../Services/Notch/NotchService.swift | 2 + .../UI/Notch/NotchCapsuleViews.swift | 9 + .../Notch/NotchClaudeSessionDetailView.swift | 14 +- .../Notch/NotchClaudeSessionLargeView.swift | 11 +- .../UI/Notch/NotchClaudeSessionsView.swift | 27 +- .../Vorssaint/UI/Notch/NotchClawdBuddy.swift | 165 ++++++ .../Vorssaint/UI/Notch/NotchClawdSprite.swift | 533 ++++++++++++++++++ .../Vorssaint/UI/Notch/NotchClawdView.swift | 162 ++++++ .../UI/Notch/NotchClawdWardrobeView.swift | 264 +++++++++ .../UI/Notch/NotchDecorativeClock.swift | 11 +- .../Vorssaint/UI/Notch/NotchNoticeView.swift | 5 + .../NotchClaudeSessionsSettingsControls.swift | 33 ++ Tests/ClaudeAgentColorTests.swift | 129 +++++ Tests/ClawdCostumeTests.swift | 178 ++++++ Tests/MetricsTests.swift | 4 + Tests/NotchClawdSpriteTests.swift | 182 ++++++ Tests/NotchClawdViewTests.swift | 124 ++++ build.sh | 4 + 25 files changed, 2375 insertions(+), 25 deletions(-) create mode 100644 Sources/Vorssaint/Services/ClaudeSessions/ClaudeAgentColors.swift create mode 100644 Sources/Vorssaint/Services/ClaudeSessions/ClawdCostume.swift create mode 100644 Sources/Vorssaint/UI/Notch/NotchClawdBuddy.swift create mode 100644 Sources/Vorssaint/UI/Notch/NotchClawdSprite.swift create mode 100644 Sources/Vorssaint/UI/Notch/NotchClawdView.swift create mode 100644 Sources/Vorssaint/UI/Notch/NotchClawdWardrobeView.swift create mode 100644 Tests/ClaudeAgentColorTests.swift create mode 100644 Tests/ClawdCostumeTests.swift create mode 100644 Tests/NotchClawdSpriteTests.swift create mode 100644 Tests/NotchClawdViewTests.swift diff --git a/Sources/Vorssaint/Core/Defaults.swift b/Sources/Vorssaint/Core/Defaults.swift index 62901972f..aa1cd58aa 100644 --- a/Sources/Vorssaint/Core/Defaults.swift +++ b/Sources/Vorssaint/Core/Defaults.swift @@ -896,6 +896,12 @@ enum DefaultsKey { static let notchSessionsContentPreview = "notchSessionsContentPreview" /// Names given to Claude Code sessions in the island, by session. static let notchSessionsNames = "notchSessionsNames" + /// Each session and subagent shows a Clawd in a costume of its own. + static let notchSessionsBuddies = "notchSessionsBuddies" + /// Costumes the person dressed sessions in, by session, as + /// `ClawdCostume.code`. Session ids belong to this Mac, so like the names + /// they stay out of settings backups. + static let notchSessionsCostumes = "notchSessionsCostumes" /// Whether an enlarged session page keeps its details folded away. static let notchSessionsSidebarHidden = "notchSessionsSidebarHidden" /// The text size of a session's page with the island grown around it. @@ -1495,6 +1501,7 @@ enum Defaults { DefaultsKey.notchSessionsContentPreview: false, DefaultsKey.notchSessionsLargeTextSize: 15.0, DefaultsKey.notchSessionsSidebarHidden: false, + DefaultsKey.notchSessionsBuddies: true, DefaultsKey.notchLyricsEnabled: true, DefaultsKey.notchLyricsOnline: false, DefaultsKey.notchBrowserCovers: false, diff --git a/Sources/Vorssaint/Core/NotchClaudeSessionStrings.swift b/Sources/Vorssaint/Core/NotchClaudeSessionStrings.swift index c5f3fcbca..cb90198a8 100644 --- a/Sources/Vorssaint/Core/NotchClaudeSessionStrings.swift +++ b/Sources/Vorssaint/Core/NotchClaudeSessionStrings.swift @@ -86,6 +86,23 @@ struct NotchClaudeSessionStrings { let bridgeRefused: String let openFailed: String let background: String + let buddies: String + let buddiesHint: String + let wardrobe: String + let dressUp: String + let dressUpFormat: String + let surpriseMe: String + let ownOutfit: String + let goToSession: String + let shellTitle: String + let hatTitle: String + let eyewearTitle: String + let extrasTitle: String + let nothing: String + let shells: [ClawdShell: String] + let hats: [ClawdHat: String] + let eyewears: [ClawdEyewear: String] + let extras: [ClawdExtra: String] func phase(_ phase: ClaudeSessionPhase) -> String { switch phase { @@ -105,6 +122,12 @@ struct NotchClaudeSessionStrings { func leftRunning(_ count: Int) -> String { String(format: leftRunningFormat, count) } func finishedAfter(_ duration: String) -> String { String(format: finishedAfterFormat, duration) } func hooksFailed(_ reason: String) -> String { String(format: hooksFailedFormat, reason) } + func dressUp(_ name: String) -> String { String(format: dressUpFormat, name) } + + func name(_ shell: ClawdShell) -> String { shells[shell] ?? shell.rawValue } + func name(_ hat: ClawdHat) -> String { hat == .none ? nothing : hats[hat] ?? hat.rawValue } + func name(_ eyewear: ClawdEyewear) -> String { eyewear == .none ? nothing : eyewears[eyewear] ?? eyewear.rawValue } + func name(_ extra: ClawdExtra) -> String { extra == .none ? nothing : extras[extra] ?? extra.rawValue } } extension FeatureStrings { @@ -200,5 +223,26 @@ extension NotchClaudeSessionStrings { bridgePackageFailed: "Couldn’t package the extension", bridgeRefused: "Antigravity refused the extension", openFailed: "Couldn’t find that window", - background: "In background") + background: "In background", + buddies: "A Clawd for every session", + buddiesHint: "Each session and subagent gets its own Clawd, dressed at random. Click one on its session’s page to change the outfit.", + wardrobe: "Wardrobe", + dressUp: "Change outfit", + dressUpFormat: "Change %@’s outfit", + surpriseMe: "Surprise me", + ownOutfit: "Back to the first outfit", + goToSession: "Go to it", + shellTitle: "Shell", + hatTitle: "Hat", + eyewearTitle: "Eyewear", + extrasTitle: "Extras", + nothing: "None", + shells: [.clay: "Clay", .coral: "Coral", .amber: "Amber", .moss: "Moss", .mint: "Mint", .teal: "Teal", + .sky: "Sky", .iris: "Iris", .orchid: "Orchid", .rose: "Rose"], + hats: [.beanie: "Beanie", .cap: "Cap", .beret: "Beret", .topHat: "Top hat", .crown: "Crown", + .party: "Party hat", .propeller: "Propeller cap", .chef: "Chef’s hat"], + eyewears: [.glasses: "Glasses", .shades: "Sunglasses", .round: "Round glasses", .monocle: "Monocle", + .anaglyph: "3D glasses"], + extras: [.bow: "Bow", .scarf: "Scarf", .bowTie: "Bow tie", .flower: "Flower", .headphones: "Headphones", + .coffee: "Coffee"]) } diff --git a/Sources/Vorssaint/Services/ClaudeSessions/ClaudeAgentColors.swift b/Sources/Vorssaint/Services/ClaudeSessions/ClaudeAgentColors.swift new file mode 100644 index 000000000..121023ded --- /dev/null +++ b/Sources/Vorssaint/Services/ClaudeSessions/ClaudeAgentColors.swift @@ -0,0 +1,166 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Vorssaint + +import Foundation + +/// The color Claude Code gives a subagent, from the `color:` line its +/// definition may start with, so the subagent's Clawd wears that shell. Only +/// the head of a definition is read, and only its name and color are kept. +enum ClaudeAgentDefinitions { + /// How much of a definition is read: its frontmatter comes first. + static let headLimit = 4096 + /// Definitions looked at in one folder, at most. + static let filesLimit = 200 + + /// The `name:` and `color:` of a definition's frontmatter, the block + /// between its first two `---` lines. + static func frontmatter(_ data: Data) -> (name: String?, color: String?) { + let head = String(decoding: data.prefix(headLimit), as: UTF8.self) + var lines = head.split(separator: "\n", omittingEmptySubsequences: false).makeIterator() + guard lines.next()?.trimmingCharacters(in: .whitespaces) == "---" else { return (nil, nil) } + var name: String?, color: String? + while let line = lines.next() { + let text = line.trimmingCharacters(in: .whitespaces) + if text == "---" { return (name, color) } + guard let colon = text.firstIndex(of: ":") else { continue } + let key = text[..= 2, let first = value.first, first == value.last, first == "\"" || first == "'" { + value = String(value.dropFirst().dropLast()) + } + guard !value.isEmpty else { continue } + if key == "name" { name = value } else if key == "color" { color = value } + } + // No closing line: what was read was not frontmatter. + return (nil, nil) + } + + /// Where an agent called `type` may be defined, in the order Claude Code + /// prefers: a plugin's agent by its `plugin:agent` name; otherwise the + /// project's own agents, from its folder up, then the person's. + static func folders(type: String, cwd: String, home: URL, plugins: Data?, readsProtected: Bool) -> [URL] { + if let colon = type.firstIndex(of: ":") { + let plugin = String(type[.. Bool { + let homePath = home.standardizedFileURL.path + let guarded = ["Desktop", "Documents", "Downloads", "Library/Mobile Documents", "Pictures", "Movies", "Music"] + .map { homePath + "/" + $0 } + return guarded.contains { path == $0 || path.hasPrefix($0 + "/") } || path == "/Volumes" || path.hasPrefix("/Volumes/") + } + + /// The agent folders of an installed plugin, from Claude Code's + /// `installed_plugins.json`: `{"plugins": {"name@marketplace": [{"installPath": …}]}}`. + static func pluginFolders(_ data: Data?, plugin: String) -> [URL] { + guard let data, data.count < 1 << 20, + let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + let plugins = json["plugins"] as? [String: Any] else { return [] } + var folders: [URL] = [] + for (key, value) in plugins.sorted(by: { $0.key < $1.key }) { + guard key.split(separator: "@", maxSplits: 1).first.map(String.init) == plugin, + let installs = value as? [[String: Any]] else { continue } + for install in installs { + guard let path = install["installPath"] as? String, !path.isEmpty else { continue } + folders.append(URL(fileURLWithPath: path, isDirectory: true).appending(path: "agents", directoryHint: .isDirectory)) + } + } + return folders + } + + /// The name an agent goes by in `type`: a plugin's agent drops the plugin. + static func agentName(_ type: String) -> String { + guard let colon = type.firstIndex(of: ":") else { return type } + return String(type[type.index(after: colon)...]) + } +} + +/// Looks agents' colors up and remembers them for a while, so a definition +/// changed in the meantime is picked up. Used only on the sessions queue. +final class ClaudeAgentColors { + /// How long an answer is kept before the definitions are read again. + static let keptFor: TimeInterval = 30 + + private let home: URL + private var known: [String: (color: String?, at: Date)] = [:] + /// Whether the app may read inside folders macOS guards, which it may + /// only with Full Disk Access. + var readsProtected = false + + init(home: URL = FileManager.default.homeDirectoryForCurrentUser) { + self.home = home + } + + func reset() { known = [:] } + + /// The color an agent of `type` working in `cwd` is given, if any. + func color(type: String, cwd: String, now: Date) -> String? { + guard !type.isEmpty, type != ClaudeSubagent.untyped else { return nil } + let key = type + "|" + cwd + (readsProtected ? "|all" : "") + if let entry = known[key], now.timeIntervalSince(entry.at) < Self.keptFor, entry.at <= now { return entry.color } + let color = lookUp(type: type, cwd: cwd) + if known.count > 500 { known = [:] } + known[key] = (color, now) + return color + } + + /// The session with each subagent's color filled in. + func decorate(_ session: ClaudeSession, now: Date) -> ClaudeSession { + guard !session.subagents.isEmpty else { return session } + var session = session + for index in session.subagents.indices { + session.subagents[index].color = color(type: session.subagents[index].type, cwd: session.cwd, now: now) + } + return session + } + + private func lookUp(type: String, cwd: String) -> String? { + let plugins = type.contains(":") + ? ClaudeSessionRegistryReader.homes(home).lazy.compactMap { + FileManager.default.contents(atPath: $0.appending(path: "plugins/installed_plugins.json").path) + }.first + : nil + let name = ClaudeAgentDefinitions.agentName(type) + for folder in ClaudeAgentDefinitions.folders(type: type, cwd: cwd, home: home, plugins: plugins, + readsProtected: readsProtected) { + if let found = definition(named: name, in: folder) { return found.color } + } + return nil + } + + /// The definition called `name` in `folder`: by its own `name:` line, or + /// failing that by its file name. + private func definition(named name: String, in folder: URL) -> (name: String, color: String?)? { + guard let files = try? FileManager.default.contentsOfDirectory(atPath: folder.path) else { return nil } + var byFile: (name: String, color: String?)? + for file in files.filter({ $0.hasSuffix(".md") }).sorted().prefix(ClaudeAgentDefinitions.filesLimit) { + let path = folder.appending(path: file).path + guard let handle = FileHandle(forReadingAtPath: path) else { continue } + let data = (try? handle.read(upToCount: ClaudeAgentDefinitions.headLimit)) ?? Data() + try? handle.close() + let head = ClaudeAgentDefinitions.frontmatter(data) + if head.name == name { return (name, head.color) } + if head.name == nil, (file as NSString).deletingPathExtension == name { byFile = (name, head.color) } + } + return byFile + } +} diff --git a/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionModels.swift b/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionModels.swift index 969fa88e8..089a28c2b 100644 --- a/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionModels.swift +++ b/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionModels.swift @@ -181,6 +181,8 @@ struct ClaudeSubagent: Equatable, Identifiable { var description: String? var started: Date var finished: Date? + /// The color its definition gives it in Claude Code, as written there. + var color: String? = nil var isRunning: Bool { finished == nil } } diff --git a/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionService.swift b/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionService.swift index 9d5e5751b..9941ca060 100644 --- a/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionService.swift +++ b/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionService.swift @@ -29,6 +29,13 @@ final class ClaudeSessionService: ObservableObject { /// app's own preferences, never in Claude Code's files. @Published private(set) var names: [String: String] = UserDefaults.standard.dictionary(forKey: DefaultsKey.notchSessionsNames) as? [String: String] ?? [:] + /// Costumes the person dressed sessions' Clawds in, by session, as + /// `ClawdCostume.code`; a session missing here wears its own lot. + @Published private(set) var costumes: [String: String] = + UserDefaults.standard.dictionary(forKey: DefaultsKey.notchSessionsCostumes) as? [String: String] ?? [:] + /// The session whose Clawd is being dressed. Its page stays focused + /// under the wardrobe, so an enlarged island keeps its size. + @Published private(set) var dressingID: String? /// The permission each session shows and since when. Main thread. private var shownRequests: [String: (request: String, at: Date)] = [:] let events = PassthroughSubject() @@ -56,6 +63,7 @@ final class ClaudeSessionService: ObservableObject { // Main thread. private(set) var running = false + private var permissionWatch: AnyCancellable? // Queue. private let engine = ClaudeSessionEngine() @@ -69,6 +77,7 @@ final class ClaudeSessionService: ObservableObject { private var hosts: [Int32: ClaudeSessionHost] = [:] private var published: [ClaudeSession] = [] private var lastRecords: [Int32: ClaudeSessionRecord] = [:] + private let agentColors = ClaudeAgentColors() private var server: ClaudeHookServer? /// Permission requests whose hook waits for the island's answer. private var pending: [String: (connection: ClaudeHookServer.Connection, session: String, suggestions: Any?, @@ -101,6 +110,11 @@ final class ClaudeSessionService: ObservableObject { } guard !running else { return } running = true + // Agents defined inside folders macOS guards are read only with Full + // Disk Access, which spares the person a prompt out of nowhere. + permissionWatch = Permissions.shared.$fullDiskAccess.removeDuplicates().sink { [weak self] granted in + self?.queue.async { self?.agentColors.readsProtected = granted } + } let socket = Self.socketPath(home: home) queue.async { [self] in startServer(at: socket) @@ -123,6 +137,8 @@ final class ClaudeSessionService: ObservableObject { guard running else { return } running = false focusedID = nil + dressingID = nil + permissionWatch = nil sessions = [] counts = ClaudeSessionCounts() queue.async { [self] in @@ -140,6 +156,7 @@ final class ClaudeSessionService: ObservableObject { pending = [:] server?.stop() server = nil + agentColors.reset() engine.ingest(records: [], now: Date.distantFuture) } } @@ -180,9 +197,35 @@ final class ClaudeSessionService: ObservableObject { func focus(_ id: String?) { focusedID = id + dressingID = nil if let id { acknowledge(id) } } + /// What a session's Clawd wears. + func costume(for session: ClaudeSession) -> ClawdCostume { + ClawdCostume.resolved(key: session.id, kept: costumes[session.id]) + } + + /// What a subagent's Clawd wears: its own lot, in the color its + /// definition gives it. + func costume(for agent: ClaudeSubagent, in session: ClaudeSession) -> ClawdCostume { + ClawdCostume.seeded(NotchClaudeSessionsSupport.costumeKey(agent, in: session), agentColor: agent.color) + } + + /// Dresses a session's Clawd, or with nil gives it its own costume back. + func setCostume(_ costume: ClawdCostume?, for id: String) { + costumes = NotchClaudeSessionsSupport.kept(costumes, id: id, value: ClawdCostume.kept(costume, key: id), + live: Set(sessions.map(\.id))) + UserDefaults.standard.set(costumes, forKey: DefaultsKey.notchSessionsCostumes) + } + + /// Opens the wardrobe of the session whose page is open, or with nil + /// goes back to the page. + func dress(_ id: String?) { + guard id == nil || id == focusedID else { return } + dressingID = id + } + func acknowledge(_ id: String) { queue.async { [self] in engine.acknowledge(id, now: Date()) @@ -514,7 +557,7 @@ final class ClaudeSessionService: ObservableObject { private func publish(now: Date) { let snapshot = engine.snapshot(now: now) - let sorted = NotchClaudeSessionsSupport.sorted(snapshot.sessions) + let sorted = NotchClaudeSessionsSupport.sorted(snapshot.sessions.map { agentColors.decorate($0, now: now) }) let changed = sorted != published published = sorted guard changed || !snapshot.events.isEmpty else { return } @@ -529,7 +572,10 @@ final class ClaudeSessionService: ObservableObject { shownRequests[session.id] = request.map { (request: $0, at: Date()) } } } - if let focusedID, !sorted.contains(where: { $0.id == focusedID }) { self.focusedID = nil } + if let focusedID, !sorted.contains(where: { $0.id == focusedID }) { + self.focusedID = nil + dressingID = nil + } } snapshot.events.forEach(events.send) } diff --git a/Sources/Vorssaint/Services/ClaudeSessions/ClawdCostume.swift b/Sources/Vorssaint/Services/ClaudeSessions/ClawdCostume.swift new file mode 100644 index 000000000..adc1cd7eb --- /dev/null +++ b/Sources/Vorssaint/Services/ClaudeSessions/ClawdCostume.swift @@ -0,0 +1,195 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Vorssaint + +import Foundation + +// Every Claude Code session in the island has a Clawd of its own, the little +// pixel crab Claude Code greets with, dressed in a costume drawn by lot from +// the session's id. The same session always draws the same costume, so it is +// known by it from one launch to the next; the person may dress it otherwise. + +/// The color of a Clawd's shell. +enum ClawdShell: String, CaseIterable, Identifiable { + case clay, coral, amber, moss, mint, teal, sky, iris, orchid, rose + + var id: String { rawValue } + + /// sRGB components out of 255, so the model needs no graphics framework. + var rgb: (red: Int, green: Int, blue: Int) { + switch self { + // Claude Code's own `clawd_body`. + case .clay: return (215, 119, 87) + case .coral: return (226, 86, 72) + case .amber: return (230, 166, 58) + case .moss: return (112, 168, 70) + case .mint: return (72, 184, 146) + case .teal: return (40, 160, 170) + case .sky: return (68, 146, 224) + case .iris: return (116, 112, 226) + case .orchid: return (178, 98, 214) + case .rose: return (230, 112, 156) + } + } + + /// The shell Claude Code's color for a subagent stands for, as an agent's + /// definition names it in its `color:` line. + init?(agentColor: String) { + switch agentColor.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() { + case "red": self = .coral + case "orange": self = .clay + case "yellow": self = .amber + case "green": self = .moss + case "cyan": self = .teal + case "blue": self = .sky + case "purple": self = .iris + case "pink": self = .rose + default: return nil + } + } +} + +enum ClawdHat: String, CaseIterable, Identifiable { + case none, beanie, cap, beret, topHat, crown, party, propeller, chef + + var id: String { rawValue } +} + +enum ClawdEyewear: String, CaseIterable, Identifiable { + case none, glasses, shades, round, monocle, anaglyph + + var id: String { rawValue } +} + +enum ClawdExtra: String, CaseIterable, Identifiable { + case none, bow, scarf, bowTie, flower, headphones, coffee + + var id: String { rawValue } +} + +struct ClawdCostume: Hashable { + var shell: ClawdShell + var hat: ClawdHat + var eyewear: ClawdEyewear + var extra: ClawdExtra + + /// Clawd as Claude Code draws it. + static let classic = ClawdCostume(shell: .clay, hat: .none, eyewear: .none, extra: .none) + + /// How often a lot draws something rather than nothing. + static let hatChance = 0.7 + static let eyewearChance = 0.4 + static let extraChance = 0.45 + /// Claude's own color comes up this many times as often as any other. + static let clayWeight = 3 + + /// A number for `key` that stays the same from one launch to the next: + /// FNV-1a over its bytes. Swift's `Hasher` is seeded anew each launch. + static func seed(_ key: String) -> UInt64 { + var hash: UInt64 = 0xcbf2_9ce4_8422_2325 + for byte in key.utf8 { + hash ^= UInt64(byte) + hash = hash &* 0x0000_0100_0000_01b3 + } + return hash + } + + /// The costume `key` draws, the same each time. + static func seeded(_ key: String) -> ClawdCostume { + var generator = ClawdRandom(seed: seed(key)) + return drawn(using: &generator) + } + + /// A subagent's costume: drawn from its own key, in the shell of the + /// color its definition gives it, if it gives one. + static func seeded(_ key: String, agentColor: String?) -> ClawdCostume { + var costume = seeded(key) + if let shell = agentColor.flatMap(ClawdShell.init(agentColor:)) { costume.shell = shell } + return costume + } + + /// A costume by lot, other than `current`, for "Surprise me". + static func random(excluding current: ClawdCostume?) -> ClawdCostume { + var generator = SystemRandomNumberGenerator() + var costume = drawn(using: &generator) + // Ten draws alike in a row are as good as impossible; give up then. + for _ in 0..<10 where costume == current { costume = drawn(using: &generator) } + return costume + } + + /// One part after another from the same lot, so each is its own draw. + static func drawn(using generator: inout Generator) -> ClawdCostume { + let shells = ClawdShell.allCases + let weights = shells.map { $0 == .clay ? clayWeight : 1 } + var ticket = Int(generator.next() % UInt64(weights.reduce(0, +))) + var shell = ClawdShell.clay + for (candidate, weight) in zip(shells, weights) { + if ticket < weight { shell = candidate; break } + ticket -= weight + } + return ClawdCostume(shell: shell, + hat: pick(ClawdHat.allCases, chance: hatChance, using: &generator), + eyewear: pick(ClawdEyewear.allCases, chance: eyewearChance, using: &generator), + extra: pick(ClawdExtra.allCases, chance: extraChance, using: &generator)) + } + + /// Nothing, the first case, with the chance left over; otherwise one of + /// the rest, each as likely. + private static func pick(_ parts: [Part], chance: Double, + using generator: inout Generator) -> Part { + let roll = Double(generator.next() >> 11) / Double(1 << 53) + let index = Int(generator.next() % UInt64(max(1, parts.count - 1))) + return roll < chance && parts.count > 1 ? parts[1 + index] : parts[0] + } +} + +// The memberwise initializer stays because the one that reads a kept costume +// lives out here. +extension ClawdCostume { + private static let version = "v1:" + + /// The costume as kept in the preferences. + var code: String { + Self.version + [shell.rawValue, hat.rawValue, eyewear.rawValue, extra.rawValue].joined(separator: ".") + } + + /// Reads a kept costume. A part this version does not know comes from + /// `fallback`; anything else unreadable is nil. + init?(code: String, fallback: ClawdCostume) { + guard code.hasPrefix(Self.version), code.count <= 80 else { return nil } + let parts = code.dropFirst(Self.version.count).split(separator: ".", omittingEmptySubsequences: false).map(String.init) + guard parts.count == 4 else { return nil } + self.init(shell: ClawdShell(rawValue: parts[0]) ?? fallback.shell, + hat: ClawdHat(rawValue: parts[1]) ?? fallback.hat, + eyewear: ClawdEyewear(rawValue: parts[2]) ?? fallback.eyewear, + extra: ClawdExtra(rawValue: parts[3]) ?? fallback.extra) + } + + /// What a session wears: what the person chose for it, or its own lot. + static func resolved(key: String, kept: String?, agentColor: String? = nil) -> ClawdCostume { + let own = seeded(key, agentColor: agentColor) + return kept.flatMap { ClawdCostume(code: $0, fallback: own) } ?? own + } + + /// What to keep for a session dressed in `costume`: nothing when it is + /// the session's own lot, so the choice follows the lot if it changes. + static func kept(_ costume: ClawdCostume?, key: String) -> String? { + guard let costume, costume != seeded(key) else { return nil } + return costume.code + } +} + +/// SplitMix64: a small generator that gives the same numbers for the same +/// seed on every Mac and every launch. +struct ClawdRandom: RandomNumberGenerator { + private var state: UInt64 + + init(seed: UInt64) { state = seed } + + mutating func next() -> UInt64 { + state = state &+ 0x9e37_79b9_7f4a_7c15 + var value = state + value = (value ^ (value >> 30)) &* 0xbf58_476d_1ce4_e5b9 + value = (value ^ (value >> 27)) &* 0x94d0_49bb_1331_11eb + return value ^ (value >> 31) + } +} diff --git a/Sources/Vorssaint/Services/Notch/NotchClaudeSessionsSupport.swift b/Sources/Vorssaint/Services/Notch/NotchClaudeSessionsSupport.swift index 97b7556a5..ebd868705 100644 --- a/Sources/Vorssaint/Services/Notch/NotchClaudeSessionsSupport.swift +++ b/Sources/Vorssaint/Services/Notch/NotchClaudeSessionsSupport.swift @@ -24,6 +24,10 @@ enum NotchClaudeSessionsSupport { ClaudeContentPolicy(previews: defaults.bool(forKey: DefaultsKey.notchSessionsContentPreview)) } + static func showsBuddies(in defaults: UserDefaults = .standard) -> Bool { + defaults.object(forKey: DefaultsKey.notchSessionsBuddies) as? Bool ?? true + } + // MARK: Order /// Sessions that wait on the person come first, then the ones at work, @@ -156,17 +160,82 @@ enum NotchClaudeSessionsSupport { /// The names with one changed. Names of sessions no longer running go /// first once there are too many. static func renamed(_ names: [String: String], id: String, to name: String, live: Set) -> [String: String] { - var result = names let trimmed = String(name.trimmingCharacters(in: .whitespacesAndNewlines).prefix(nameLimit)) - result[id] = trimmed.isEmpty ? nil : trimmed - if result.count > namesKept { - for key in result.keys.sorted() where !live.contains(key) && key != id && result.count > namesKept { + return kept(names, id: id, value: trimmed.isEmpty ? nil : trimmed, live: live) + } + + /// What the island keeps by session, with one value changed or, with + /// nil, removed. Values of sessions no longer running go first once + /// there are more than `limit`. + static func kept(_ values: [String: String], id: String, value: String?, live: Set, + limit: Int = namesKept) -> [String: String] { + var result = values + result[id] = value + if result.count > limit { + for key in result.keys.sorted() where !live.contains(key) && key != id && result.count > limit { result[key] = nil } } return result } + // MARK: Clawds + + /// A quiet session dozes off once it has done nothing this long; before + /// that it stays awake, as after the person reads what it did. + static let dozeAfter: TimeInterval = 5 * 60 + + /// What a session's Clawd does in its phase. + static func motion(_ session: ClaudeSession, now: Date) -> NotchClawdMotion { + switch session.phase { + case .generating: return .think + case .runningTool: return .work + case .background: return .slow + case .waitingPermission: return .alert + case .waitingInput: return .ask + case .finished: return .content + case .idle: + let quiet = now.timeIntervalSince(session.lastActive ?? session.phaseSince) + return quiet < dozeAfter ? .rest : .doze + } + } + + /// When the session's work ended, which its Clawd hops for. Counted from + /// the phase's own start, so every Clawd of the session on screen hops + /// as one, and one drawn once the hop is over does not hop again. + static func cheer(_ session: ClaudeSession) -> Date? { + session.phase == .finished ? session.phaseSince : nil + } + + /// What a session's Clawd does in a notice: the notice's own symbol says + /// what happened, so the Clawd matches its words. + static func noticeMotion(symbol: String) -> NotchClawdMotion { + switch symbol { + case self.symbol(.finished): return .content + case self.symbol(.waitingInput): return .ask + default: return .alert + } + } + + /// A subagent works while it runs and rests, done, after. + static func motion(_ agent: ClaudeSubagent) -> NotchClawdMotion { + agent.isRunning ? .work : .done + } + + /// The key a subagent's costume is drawn from. + static func costumeKey(_ agent: ClaudeSubagent, in session: ClaudeSession) -> String { + session.id + "/" + agent.id + } + + /// What Escape closes on the Sessions page: the wardrobe, then a + /// session's page, and with neither open, the island itself. + enum PageLayer: Equatable { case wardrobe, session } + + static func pageLayer(focused: String?, dressing: String?) -> PageLayer? { + if dressing != nil, dressing == focused { return .wardrobe } + return focused == nil ? nil : .session + } + /// What the conversation says Claude is doing while a turn runs, picked /// once per turn as Claude Code's own spinner does. static let thinkingWords = [ diff --git a/Sources/Vorssaint/Services/Notch/NotchService.swift b/Sources/Vorssaint/Services/Notch/NotchService.swift index 8d9bfb76e..6d3b52c91 100644 --- a/Sources/Vorssaint/Services/Notch/NotchService.swift +++ b/Sources/Vorssaint/Services/Notch/NotchService.swift @@ -1884,6 +1884,8 @@ final class NotchService: ObservableObject { commandOnly: event.modifierFlags.intersection([.command, .control, .option, .shift]) == .command) else { return false } let sessions = ClaudeSessionService.shared + // The wardrobe covers the request: a key must not answer what is not on screen. + guard sessions.dressingID == nil else { return false } let focused = sessions.focusedID.flatMap { id in sessions.sessions.first { $0.id == id } } guard let target = focused ?? sessions.sessions.first(where: { $0.permission.map { !$0.asksQuestions } ?? false }), let permission = target.permission, diff --git a/Sources/Vorssaint/UI/Notch/NotchCapsuleViews.swift b/Sources/Vorssaint/UI/Notch/NotchCapsuleViews.swift index 2f533ee46..bda90fe3c 100644 --- a/Sources/Vorssaint/UI/Notch/NotchCapsuleViews.swift +++ b/Sources/Vorssaint/UI/Notch/NotchCapsuleViews.swift @@ -152,6 +152,15 @@ struct NotchCapsuleNoticeView: View { .frame(width: CapsuleLayout.symbolWidth, height: side) } else if notice.event == .agents, let agent = notice.agent, notice.symbol == agent.symbol { NotchAgentMark(provider: agent, size: CapsuleLayout.symbolSize).frame(width: CapsuleLayout.symbolWidth) + } else if notice.event == .sessions, let id = notice.sessionID, NotchClaudeSessionsSupport.showsBuddies() { + // Two points wider than the slot, half a point past each side: at + // the slot's own width a pixel would be too small to read. + NotchClaudeNoticeClawd(sessionID: id, symbol: notice.symbol, + size: CGSize(width: CapsuleLayout.symbolWidth + 2, + height: min(CapsuleLayout.symbolWidth, CapsuleLayout.artworkSide(geometry)))) + .frame(width: CapsuleLayout.symbolWidth) + .id("\(id)|\(notice.symbol)") + .transition(.identity) } else if notice.event == .track { NotchCapsuleTrackArtwork(side: min(CapsuleLayout.symbolWidth, CapsuleLayout.artworkSide(geometry))) .frame(width: CapsuleLayout.symbolWidth) diff --git a/Sources/Vorssaint/UI/Notch/NotchClaudeSessionDetailView.swift b/Sources/Vorssaint/UI/Notch/NotchClaudeSessionDetailView.swift index 7a45f685e..0f48a160e 100644 --- a/Sources/Vorssaint/UI/Notch/NotchClaudeSessionDetailView.swift +++ b/Sources/Vorssaint/UI/Notch/NotchClaudeSessionDetailView.swift @@ -78,7 +78,7 @@ struct NotchClaudeSessionDetailView: View { private func header(now: Date) -> some View { HStack(spacing: 10) { - NotchClaudeSessionBadge(phase: session.phase, size: 30) + NotchClawdDressButton(session: session, name: service.displayName(session), text: text) VStack(alignment: .leading, spacing: 2) { HStack(spacing: 6) { Text(text.phase(session.phase)) @@ -104,9 +104,9 @@ struct NotchClaudeSessionDetailView: View { .truncationMode(.middle) } } + .accessibilityElement(children: .combine) Spacer(minLength: 0) } - .accessibilityElement(children: .combine) } private var details: String { @@ -265,10 +265,12 @@ struct NotchClaudeSessionDetailView: View { sectionTitle(text.subagents) ForEach(session.subagents.prefix(Self.shownSubagents)) { agent in HStack(spacing: 6) { - Image(systemName: agent.isRunning ? "arrow.triangle.branch" : "checkmark") - .font(.system(size: 9, weight: .semibold)) - .foregroundStyle(agent.isRunning ? AgentProvider.claude.tint : .white.opacity(0.45)) - .frame(width: 12) + NotchClaudeSubagentAvatar(agent: agent, session: session) { + Image(systemName: agent.isRunning ? "arrow.triangle.branch" : "checkmark") + .font(.system(size: 9, weight: .semibold)) + .foregroundStyle(agent.isRunning ? AgentProvider.claude.tint : .white.opacity(0.45)) + .frame(width: 12) + } Text(agent.type).font(.system(size: 11, weight: .medium)).foregroundStyle(.white.opacity(0.85)) if let description = agent.description { Text(description).font(.system(size: 10.5)).foregroundStyle(.secondary).lineLimit(1) diff --git a/Sources/Vorssaint/UI/Notch/NotchClaudeSessionLargeView.swift b/Sources/Vorssaint/UI/Notch/NotchClaudeSessionLargeView.swift index 1d8fec265..26edb9f58 100644 --- a/Sources/Vorssaint/UI/Notch/NotchClaudeSessionLargeView.swift +++ b/Sources/Vorssaint/UI/Notch/NotchClaudeSessionLargeView.swift @@ -139,7 +139,8 @@ struct NotchClaudeSessionLargeView: View { private func header(now: Date) -> some View { HStack(alignment: .center, spacing: 12) { - NotchClaudeSessionBadge(phase: session.phase, size: 34) + NotchClawdDressButton(session: session, name: ClaudeSessionService.shared.displayName(session), text: text, + size: CGSize(width: 48, height: 42), badge: 34) VStack(alignment: .leading, spacing: 3) { HStack(spacing: 8) { Text(text.phase(session.phase)) @@ -382,9 +383,11 @@ struct NotchClaudeSessionLargeView: View { private func agentRow(_ agent: ClaudeSubagent, now: Date) -> some View { HStack(alignment: .firstTextBaseline, spacing: 6) { - Image(systemName: agent.isRunning ? "arrow.triangle.branch" : "checkmark") - .font(.system(size: 10, weight: .semibold)) - .foregroundStyle(agent.isRunning ? AgentProvider.claude.tint : .white.opacity(0.4)) + NotchClaudeSubagentAvatar(agent: agent, session: session, size: CGSize(width: 22, height: 17)) { + Image(systemName: agent.isRunning ? "arrow.triangle.branch" : "checkmark") + .font(.system(size: 10, weight: .semibold)) + .foregroundStyle(agent.isRunning ? AgentProvider.claude.tint : .white.opacity(0.4)) + } VStack(alignment: .leading, spacing: 1) { Text(agent.type).font(.system(size: 12, weight: .semibold)).foregroundStyle(.white.opacity(0.9)) if let description = agent.description { diff --git a/Sources/Vorssaint/UI/Notch/NotchClaudeSessionsView.swift b/Sources/Vorssaint/UI/Notch/NotchClaudeSessionsView.swift index a1feb305c..ed18fd6c4 100644 --- a/Sources/Vorssaint/UI/Notch/NotchClaudeSessionsView.swift +++ b/Sources/Vorssaint/UI/Notch/NotchClaudeSessionsView.swift @@ -19,9 +19,18 @@ struct NotchClaudeSessionsView: View { return service.sessions.first { $0.id == id } } + /// The session whose Clawd is being dressed, over its own page. + private var dressing: ClaudeSession? { + guard let focused, service.dressingID == focused.id else { return nil } + return focused + } + var body: some View { Group { - if let focused { + if let dressing { + NotchClawdWardrobeView(session: dressing, size: size) + .transition(reduceMotion ? .opacity : .move(edge: .trailing).combined(with: .opacity)) + } else if let focused { NotchClaudeSessionDetailView(session: focused, size: size) .transition(reduceMotion ? .opacity : .move(edge: .trailing).combined(with: .opacity)) } else if service.sessions.isEmpty { @@ -31,12 +40,20 @@ struct NotchClaudeSessionsView: View { } } .animation(reduceMotion ? nil : .spring(response: 0.32, dampingFraction: 0.86), value: focused?.id) + .animation(reduceMotion ? nil : .spring(response: 0.32, dampingFraction: 0.86), value: dressing?.id) .frame(width: size.width, height: size.height, alignment: .top) .environment(\.locale, l10n.language.formattingLocale()) - .onChange(of: focused?.id, initial: true) { _, id in + .onChange(of: [focused?.id, dressing?.id], initial: true) { _, _ in guard !preview else { return } - // Escape steps back to the list before it closes the island. - NotchService.shared.setPageLayer(.sessions, close: id == nil ? nil : { service.focus(nil) }) + // Escape steps back from the wardrobe to the page, and from the + // page to the list, before it closes the island. + let close: (() -> Void)? + switch NotchClaudeSessionsSupport.pageLayer(focused: focused?.id, dressing: dressing?.id) { + case .wardrobe: close = { service.dress(nil) } + case .session: close = { service.focus(nil) } + case nil: close = nil + } + NotchService.shared.setPageLayer(.sessions, close: close) } .onDisappear { guard !preview else { return } @@ -106,7 +123,7 @@ struct NotchClaudeSessionRow: View { HStack(spacing: 6) { Button(action: open) { HStack(spacing: 10) { - NotchClaudeSessionBadge(phase: session.phase) + NotchClaudeSessionAvatar(session: session) summary if !quickDecision { Image(systemName: "chevron.right") diff --git a/Sources/Vorssaint/UI/Notch/NotchClawdBuddy.swift b/Sources/Vorssaint/UI/Notch/NotchClawdBuddy.swift new file mode 100644 index 000000000..01d84c704 --- /dev/null +++ b/Sources/Vorssaint/UI/Notch/NotchClawdBuddy.swift @@ -0,0 +1,165 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Vorssaint + +import SwiftUI + +/// A Clawd fitted to a box, moving unless Reduce Motion is on. It is +/// decoration: what it stands for is said by the text beside it. +struct NotchClawd: View { + let costume: ClawdCostume + var motion = NotchClawdMotion.rest + var seed: UInt64 = 0 + var cheer: Date? = nil + var bubbles = true + let size: CGSize + @Environment(\.accessibilityReduceMotion) private var reduceMotion + + var body: some View { + NotchClawdBridge(costume: costume, motion: motion, seed: seed, cheer: cheer, still: reduceMotion, bubbles: bubbles) + .frame(width: size.width, height: size.height) + .accessibilityHidden(true) + .allowsHitTesting(false) + } +} + +private struct NotchClawdBridge: NSViewRepresentable { + let costume: ClawdCostume + let motion: NotchClawdMotion + let seed: UInt64 + let cheer: Date? + let still: Bool + let bubbles: Bool + + func makeNSView(context: Context) -> NotchClawdView { NotchClawdView() } + func updateNSView(_ view: NotchClawdView, context: Context) { + view.configure(costume: costume, motion: motion, seed: seed, cheer: cheer, still: still, bubbles: bubbles) + } + static func dismantleNSView(_ view: NotchClawdView, coordinator: ()) { view.stop() } +} + +/// A Clawd standing still, drawn as a picture: the wardrobe's tiles show +/// dozens at once and none of them moves. +struct NotchClawdPicture: View { + let costume: ClawdCostume + var pose = NotchClawdPose() + let size: CGSize + @Environment(\.displayScale) private var displayScale + + var body: some View { + let fit = NotchClawdSprite.layout(box: size, scale: displayScale) + ZStack(alignment: .topLeading) { + if let image = NotchClawdSprite.image(costume, pose) { + Image(decorative: image, scale: 1) + .resizable() + .interpolation(.none) + .frame(width: CGFloat(NotchClawdSprite.width) * fit.pixel, + height: CGFloat(NotchClawdSprite.height) * fit.pixel) + .offset(x: fit.origin.x, y: fit.origin.y) + } + } + .frame(width: size.width, height: size.height, alignment: .topLeading) + .accessibilityHidden(true) + } +} + +/// A session's Clawd in the costume it wears, doing what the session does. +/// With Clawds turned off, the phase's badge takes its place. +struct NotchClaudeSessionAvatar: View { + let session: ClaudeSession + var size = CGSize(width: 32, height: 30) + /// The badge's size when Clawds are off. + var badge: CGFloat = 26 + @ObservedObject private var service = ClaudeSessionService.shared + @AppStorage(DefaultsKey.notchSessionsBuddies) private var buddies = true + + var body: some View { + if buddies { + NotchClawd(costume: service.costume(for: session), + motion: NotchClaudeSessionsSupport.motion(session, now: Date()), + seed: ClawdCostume.seed(session.id), cheer: NotchClaudeSessionsSupport.cheer(session), size: size) + } else { + NotchClaudeSessionBadge(phase: session.phase, size: badge) + } + } +} + +/// A subagent's Clawd: at work while it runs, faded and smiling once done. +/// With Clawds turned off, `fallback` shows instead. +struct NotchClaudeSubagentAvatar: View { + let agent: ClaudeSubagent + let session: ClaudeSession + var size = CGSize(width: 18, height: 14) + @ViewBuilder let fallback: () -> Fallback + @ObservedObject private var service = ClaudeSessionService.shared + @AppStorage(DefaultsKey.notchSessionsBuddies) private var buddies = true + + var body: some View { + if buddies { + NotchClawd(costume: service.costume(for: agent, in: session), + motion: NotchClaudeSessionsSupport.motion(agent), + seed: ClawdCostume.seed(NotchClaudeSessionsSupport.costumeKey(agent, in: session)), size: size) + .opacity(agent.isRunning ? 1 : 0.5) + } else { + fallback() + } + } +} + +/// A session's Clawd as a button that opens its wardrobe. A small shirt +/// shows on it under the pointer, so it is found without a word on screen. +/// With Clawds turned off, the phase's badge stays as it was. +struct NotchClawdDressButton: View { + let session: ClaudeSession + let name: String + let text: NotchClaudeSessionStrings + var size = CGSize(width: 40, height: 36) + var badge: CGFloat = 30 + @AppStorage(DefaultsKey.notchSessionsBuddies) private var buddies = true + @Environment(\.accessibilityReduceMotion) private var reduceMotion + @State private var hovered = false + + var body: some View { + if buddies { + Button { ClaudeSessionService.shared.dress(session.id) } label: { + NotchClaudeSessionAvatar(session: session, size: size, badge: badge) + .overlay(alignment: .bottomTrailing) { + Image(systemName: "tshirt.fill") + .font(.system(size: 7.5, weight: .bold)) + .foregroundStyle(.black.opacity(0.85)) + .frame(width: 15, height: 15) + .background(.white.opacity(0.92), in: Circle()) + .offset(x: 4, y: 3) + .opacity(hovered ? 1 : 0) + .scaleEffect(hovered || reduceMotion ? 1 : 0.6, anchor: .bottomTrailing) + } + .contentShape(Rectangle()) + } + // No lift: a pixel drawing scaled by a fraction loses its edges. + .buttonStyle(NotchButtonStyle(cornerRadius: 10, lifts: false)) + .onHover { hovering in + withAnimation(reduceMotion ? nil : .spring(response: 0.25, dampingFraction: 0.7)) { hovered = hovering } + } + .help(text.dressUp) + .accessibilityLabel(text.dressUp(name)) + } else { + NotchClaudeSessionBadge(phase: session.phase, size: badge) + } + } +} + +/// A session's Clawd in a notice about it: hopping while the session waits, +/// cheering once its work is done. The strip has no room above it, so no +/// bubble shows; the notice's words say what it wants. +struct NotchClaudeNoticeClawd: View { + let sessionID: String + let symbol: String + let size: CGSize + @ObservedObject private var service = ClaudeSessionService.shared + + var body: some View { + let session = service.sessions.first { $0.id == sessionID } + NotchClawd(costume: ClawdCostume.resolved(key: sessionID, kept: service.costumes[sessionID]), + motion: NotchClaudeSessionsSupport.noticeMotion(symbol: symbol), seed: ClawdCostume.seed(sessionID), + cheer: session.flatMap(NotchClaudeSessionsSupport.cheer), bubbles: false, size: size) + } +} diff --git a/Sources/Vorssaint/UI/Notch/NotchClawdSprite.swift b/Sources/Vorssaint/UI/Notch/NotchClawdSprite.swift new file mode 100644 index 000000000..2e2664a55 --- /dev/null +++ b/Sources/Vorssaint/UI/Notch/NotchClawdSprite.swift @@ -0,0 +1,533 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Vorssaint + +import CoreGraphics +import Foundation + +/// What a Clawd does for as long as it is shown. +enum NotchClawdMotion: Equatable { + /// Awake and at ease: it breathes, blinks and looks about. + case rest + /// Its work is done: smiling eyes. + case content + /// Long quiet: eyes shut and a "z" rising now and then. + case doze + /// Claude writes: busy hands, eyes going to and fro. + case think + /// A tool runs: it waddles on the spot. + case work + /// Work in the background: busy hands, at half the pace. + case slow + /// It waits for a permission: hops, waves and shows "!". + case alert + /// It waits for an answer: the same, with "?". + case ask + /// A subagent that finished: still, with smiling eyes. + case done +} + +/// One drawing of a Clawd. Equal poses draw the same image, so they key the +/// cache, and a new image is set only when the pose changes. +struct NotchClawdPose: Hashable { + enum Arms: String { case down, up, typeLeft, typeRight, waveUp, waveOut } + enum Legs: String { case stand, stepLeft, stepRight } + enum Eyes: String { case open, closed, happy, left, right } + enum Bubble: Hashable { case alert, question, sleep(Int) } + + var arms = Arms.down + var legs = Legs.stand + var eyes = Eyes.open + var bubble: Bubble? + /// How far the body rises over its legs, which stretch to stay on the ground. + var rise = 0 + /// How far it is off the ground, legs tucked. + var jump = 0 + /// Every other step, for what turns or steams on its own. + var tick = 0 + + var key: String { + let bubbleKey: String + switch bubble { + case nil: bubbleKey = "-" + case .alert: bubbleKey = "!" + case .question: bubbleKey = "?" + case .sleep(let phase): bubbleKey = "z\(phase)" + } + return "\(arms.rawValue).\(legs.rawValue).\(eyes.rawValue).\(bubbleKey).\(rise).\(jump).\(tick)" + } +} + +/// Clawd drawn in pixels, after the sprite Claude Code cooks with: a body 13 +/// pixels wide and 8 tall, eyes a pixel wide and two tall, arms that stick +/// out two pixels on each side and four short legs. Each costume part is a +/// small drawing laid over it. Everything here is plain data and pure +/// functions; the views only put the images on screen. +enum NotchClawdSprite { + // MARK: Canvas + + static let width = 24 + static let height = 22 + /// Where the body's top left pixel sits on the canvas. + static let bodyX = 5 + static let bodyY = 12 + /// The part of the canvas the figure is fitted by: the body with its + /// arms and legs and a little room for a hat. It is the same for every + /// costume, so every Clawd is drawn at the same size; tall hats, a raised + /// arm and the bubbles reach past it. + static let frameColumns = 3..<20 + static let frameRows = 8..<22 + + /// Steps a second while it moves. + static let rate: Float = 12 + + // MARK: Fitting + + /// How big a canvas pixel is, in points, and where the canvas's top left + /// corner goes in a box measured from its top left: as many whole device + /// pixels per canvas pixel as fit the frame in `box`, at least one, with + /// the frame centred and every edge on a device pixel. + static func layout(box: CGSize, scale: CGFloat) -> (pixel: CGFloat, origin: CGPoint) { + let scale = max(1, scale.isFinite ? scale : 1) + let across = max(0, box.width) * scale / CGFloat(frameColumns.count) + let down = max(0, box.height) * scale / CGFloat(frameRows.count) + let devicePixels = max(1, floor(min(across, down))) + let pixel = devicePixels / scale + let frameMidX = CGFloat(frameColumns.lowerBound) + CGFloat(frameColumns.count) / 2 + let frameMidY = CGFloat(frameRows.lowerBound) + CGFloat(frameRows.count) / 2 + let x = (box.width / 2 - frameMidX * pixel) * scale + let y = (box.height / 2 - frameMidY * pixel) * scale + return (pixel, CGPoint(x: x.rounded() / scale, y: y.rounded() / scale)) + } + + // MARK: Motion + + /// How long the hop a Clawd gives at the end of its work lasts. + static let cheerLength: TimeInterval = 1.4 + + /// The pose `motion` has reached `elapsed` seconds in. `seed` sets the + /// Clawd's own rhythm, so a row of them never blinks as one. `cheer` is + /// how long ago its work ended, while the hop for it plays. `still` is + /// Reduce Motion: one pose that says the same without moving. Without + /// `bubbles`, as in a notice with no room above, no "!", "?" or "z" shows. + static func pose(_ motion: NotchClawdMotion, at elapsed: TimeInterval, seed: UInt64, + cheer: TimeInterval? = nil, still: Bool = false, bubbles: Bool = true) -> NotchClawdPose { + var pose = posed(motion, at: elapsed, seed: seed, cheer: cheer, still: still) + if !bubbles { pose.bubble = nil } + return pose + } + + private static func posed(_ motion: NotchClawdMotion, at elapsed: TimeInterval, seed: UInt64, + cheer: TimeInterval?, still: Bool) -> NotchClawdPose { + if still { return stillPose(motion) } + let time = elapsed.isFinite ? max(0, elapsed) : 0 + if let cheer, cheer >= 0, cheer < cheerLength { return cheerPose(at: cheer) } + let step = Int(time * Double(rate)) + var pose = NotchClawdPose() + pose.tick = (step / 3) % 2 + switch motion { + case .rest: + pose.eyes = blinks(time, seed: seed) ? .closed : glance(time, seed: seed) + pose.rise = breath(time, period: 2.4) + case .content: + pose.eyes = .happy + pose.rise = breath(time, period: 2.4) + case .doze: + pose.eyes = .closed + pose.rise = breath(time, period: 3.2) + pose.bubble = .sleep(Int(time / 0.7) % 3) + case .think: + pose.arms = (step / 2) % 2 == 0 ? .typeLeft : .typeRight + let look = Int(time / 0.8) % 4 + pose.eyes = blinks(time, seed: seed) ? .closed : look == 1 ? .left : look == 3 ? .right : .open + case .slow: + pose.arms = (step / 4) % 2 == 0 ? .typeLeft : .typeRight + pose.eyes = blinks(time, seed: seed) ? .closed : .open + case .work: + switch (step / 2) % 4 { + case 0: pose.legs = .stepLeft + case 2: pose.legs = .stepRight + default: pose.rise = 1 + } + pose.eyes = blinks(time, seed: seed) ? .closed : .open + case .alert, .ask: + pose.bubble = motion == .alert ? .alert : .question + let cycle = time.truncatingRemainder(dividingBy: 1.6) + if cycle < 0.5 { + pose.jump = [0, 2, 3, 3, 2, 0][min(5, Int(cycle * Double(rate)))] + pose.arms = pose.jump > 0 ? .up : .down + } else if cycle < 1.1 { + pose.arms = Int((cycle - 0.5) / 0.15) % 2 == 0 ? .waveUp : .waveOut + } + pose.eyes = .open + case .done: + pose.eyes = .happy + pose.tick = 0 + } + return pose + } + + private static func stillPose(_ motion: NotchClawdMotion) -> NotchClawdPose { + var pose = NotchClawdPose() + switch motion { + case .rest: break + case .content, .done: pose.eyes = .happy + case .doze: pose.eyes = .closed; pose.bubble = .sleep(1) + case .think, .slow: pose.arms = .typeLeft + case .work: pose.legs = .stepLeft + case .alert: pose.bubble = .alert; pose.arms = .waveUp + case .ask: pose.bubble = .question; pose.arms = .waveUp + } + return pose + } + + /// A crouch, a jump with both arms up, and a landing with smiling eyes. + private static func cheerPose(at age: TimeInterval) -> NotchClawdPose { + var pose = NotchClawdPose() + pose.eyes = .happy + let step = Int(age * Double(rate)) + let arc = [0, 0, 2, 4, 5, 5, 4, 2, 0] + if step < arc.count { + pose.jump = arc[step] + pose.arms = step < 2 ? .down : .up + } else { + pose.arms = .up + } + return pose + } + + /// Eyes shut for two steps every few seconds, at the Clawd's own pace. + static func blinks(_ time: TimeInterval, seed: UInt64) -> Bool { + let period = 3.4 + Double(seed % 23) / 10 + let offset = Double((seed >> 8) % 1000) / 1000 * period + return (time + offset).truncatingRemainder(dividingBy: period) < 2 / Double(rate) + } + + /// Now and then it looks to one side for a moment. + private static func glance(_ time: TimeInterval, seed: UInt64) -> NotchClawdPose.Eyes { + let period = 6.1 + Double((seed >> 16) % 31) / 10 + let offset = Double((seed >> 24) % 1000) / 1000 * period + let shifted = time + offset + guard shifted.truncatingRemainder(dividingBy: period) < 0.8 else { return .open } + return Int(shifted / period) % 2 == 0 ? .left : .right + } + + /// Up a pixel for the second half of each breath. + private static func breath(_ time: TimeInterval, period: TimeInterval) -> Int { + time.truncatingRemainder(dividingBy: period) < period / 2 ? 0 : 1 + } + + // MARK: Drawing + + /// A small drawing, its letters standing for colors, placed by its top + /// left corner in the body's own pixels: the body's top left is 0, 0. + struct Stamp { + let x: Int + let y: Int + let rows: [String] + } + + /// The costume in `pose`, as one letter per canvas pixel, nil where + /// nothing is drawn. Rows run from the top. + static func letters(_ costume: ClawdCostume, _ pose: NotchClawdPose) -> [Character?] { + compose(costume, pose).canvas + } + + /// How many pixels of the costume in `pose` fall off the canvas: none, + /// for a drawing that fits. + static func clippedPixels(_ costume: ClawdCostume, _ pose: NotchClawdPose) -> Int { + compose(costume, pose).clipped + } + + private static func compose(_ costume: ClawdCostume, _ pose: NotchClawdPose) -> (canvas: [Character?], clipped: Int) { + var canvas = [Character?](repeating: nil, count: width * height) + var clipped = 0 + let lift = pose.rise + pose.jump + func put(_ stamp: Stamp, dy: Int = -lift) { + for (row, line) in stamp.rows.enumerated() { + for (column, letter) in line.enumerated() where letter != "." { + let x = bodyX + stamp.x + column, y = bodyY + stamp.y + row + dy + guard x >= 0, x < width, y >= 0, y < height else { clipped += 1; continue } + canvas[y * width + x] = letter + } + } + } + // Legs reach the ground under a rising body, and tuck in off it. + let feet = [(0, true), (2, true), (10, false), (12, false)] + for (x, left) in feet { + let lifted = (pose.legs == .stepLeft && left) || (pose.legs == .stepRight && !left) + let top = 8 - pose.rise, bottom = pose.jump > 0 || lifted ? 8 : 9 + put(Stamp(x: x, y: top, rows: Array(repeating: "C", count: max(1, bottom - top + 1))), dy: -pose.jump) + } + put(Stamp(x: 0, y: 0, rows: Array(repeating: String(repeating: "C", count: 13), count: 8))) + arms(pose.arms).forEach { put($0) } + put(eyes(pose.eyes, column: 3)) + put(eyes(pose.eyes, column: 9)) + if let stamp = eyewear(costume.eyewear) { put(stamp) } + hat(costume.hat, tick: pose.tick).forEach { put($0) } + extra(costume.extra, arms: pose.arms, tick: pose.tick).forEach { put($0) } + if let bubble = pose.bubble { bubbleStamps(bubble).forEach { put($0) } } + return (canvas, clipped) + } + + private static func arms(_ arms: NotchClawdPose.Arms) -> [Stamp] { + let downLeft = Stamp(x: -2, y: 4, rows: ["CC", "CC"]) + let downRight = Stamp(x: 13, y: 4, rows: ["CC", "CC"]) + let upLeft = Stamp(x: -3, y: 0, rows: ["CC.", "CC.", ".CC", ".CC", "..C"]) + let upRight = Stamp(x: 13, y: 0, rows: [".CC", ".CC", "CC.", "CC.", "C.."]) + switch arms { + case .down: return [downLeft, downRight] + case .up: return [upLeft, upRight] + case .typeLeft: return [Stamp(x: -2, y: 5, rows: ["CC", "CC"]), downRight] + case .typeRight: return [downLeft, Stamp(x: 13, y: 5, rows: ["CC", "CC"])] + case .waveUp: return [downLeft, upRight] + case .waveOut: return [downLeft, Stamp(x: 13, y: 2, rows: ["..C", ".CC", "CC.", "C.."])] + } + } + + private static func eyes(_ eyes: NotchClawdPose.Eyes, column x: Int) -> Stamp { + switch eyes { + case .open: return Stamp(x: x, y: 2, rows: ["E", "E"]) + case .closed: return Stamp(x: x - 1, y: 3, rows: ["EEE"]) + case .happy: return Stamp(x: x - 1, y: 2, rows: [".E.", "E.E"]) + case .left: return Stamp(x: x - 1, y: 2, rows: ["E", "E"]) + case .right: return Stamp(x: x + 1, y: 2, rows: ["E", "E"]) + } + } + + private static func eyewear(_ eyewear: ClawdEyewear) -> Stamp? { + switch eyewear { + case .none: return nil + case .glasses: + return Stamp(x: 0, y: 1, rows: [".KKKKK.KKKKK.", + "KK...KKK...KK", + ".K...K.K...K.", + ".KKKKK.KKKKK."]) + case .shades: + return Stamp(x: 0, y: 1, rows: ["KKKKKKKKKKKKK", + ".LlLLL.LlLLL.", + ".LLLLL.LLLLL.", + "..LLL...LLL.."]) + case .round: + return Stamp(x: 1, y: 1, rows: [".KKK...KKK.", + "K...KKK...K", + "K...K.K...K", + ".KKK...KKK."]) + case .monocle: + return Stamp(x: 7, y: 1, rows: [".YYY.", + "Y...Y", + "Y...Y", + ".YYY.", + "....y", + "...y.", + "...y."]) + case .anaglyph: + return Stamp(x: 0, y: 1, rows: ["WWWWWWWWWWWWW", + "WRRRRRWTTTTTW", + "WRRRRRWTTTTTW", + ".WWWWW.WWWWW."]) + } + } + + private static func hat(_ hat: ClawdHat, tick: Int) -> [Stamp] { + switch hat { + case .none: return [] + case .beanie: + return [Stamp(x: 0, y: -4, rows: [".....WWW.....", + "...AAAAAAA...", + ".AAAAAAAAAAA.", + "AAAAAAAAAAAAA", + "aAaAaAaAaAaAa"])] + case .cap: + return [Stamp(x: 0, y: -3, rows: ["...AAAAAAA......", + ".AAAAAWAAAAA....", + "AAAAAAAAAAAAaaaa"])] + case .beret: + return [Stamp(x: -1, y: -4, rows: [".........a....", + "...AAAAAAAAA..", + ".AAAAAAAAAAAAA", + "AAAAAAAAAAAAAA", + ".aaaaaaaaaaa.."])] + case .topHat: + return [Stamp(x: 1, y: -6, rows: ["..DDDDDDD..", + "..DdDDDDD..", + "..DdDDDDD..", + "..RRRRRRR..", + "..DDDDDDD..", + "DDDDDDDDDDD"])] + case .crown: + return [Stamp(x: 1, y: -4, rows: ["Y....Y....Y", + "YY..YYY..YY", + "YYYYYRYYYYY", + "yyyyyyyyyyy"])] + case .party: + return [Stamp(x: 3, y: -7, rows: ["...Y...", + "...A...", + "..WWW..", + "..AAA..", + ".WWWWW.", + ".AAAAA.", + "WWWWWWW"])] + case .propeller: + let blades = tick == 0 ? "RRRR.s.BBBB" : "..RR.s.BB.." + return [Stamp(x: 1, y: -5, rows: [blades, + ".....s.....", + "...RRYBB...", + ".RRRRYBBBB.", + "RRRRRYBBBBB"])] + case .chef: + return [Stamp(x: 1, y: -6, rows: ["..WWW.WWW..", + ".WWWWWWWWW.", + "WWWWWWWWWWW", + ".WWWWWWWWW.", + "..WWWWWWW..", + "..wwwwwww.."])] + } + } + + /// Where the right hand is in each pose, for what it holds. + private static func rightHand(_ arms: NotchClawdPose.Arms) -> (x: Int, y: Int) { + switch arms { + case .down, .typeLeft: return (15, 3) + case .typeRight: return (15, 4) + case .up, .waveUp: return (15, -2) + case .waveOut: return (16, 0) + } + } + + private static func extra(_ extra: ClawdExtra, arms: NotchClawdPose.Arms, tick: Int) -> [Stamp] { + switch extra { + case .none: return [] + case .bow: + return [Stamp(x: 9, y: -2, rows: ["AA.AA", "AAaAA", "AA.AA"])] + case .scarf: + return [Stamp(x: 0, y: 4, rows: ["AAAAAAAAAAAAA", + "aaaaaaaaaaaaa", + ".........AA..", + ".........aA.."])] + case .bowTie: + return [Stamp(x: 4, y: 4, rows: ["KK.KK", "KKsKK", "KK.KK"])] + case .flower: + return [Stamp(x: -1, y: -2, rows: [".W.", "WYW", ".W."])] + case .headphones: + return [Stamp(x: -2, y: -3, rows: ["....SSSSSSSSS....", + "..SS.........SS..", + ".S.............S.", + ".S.............S.", + "AA.............AA", + "AA.............AA", + "AA.............AA"])] + case .coffee: + let hand = rightHand(arms) + let steam = tick == 0 ? [".w.", "w.."] : ["w..", ".w."] + return [Stamp(x: hand.x, y: hand.y - 2, rows: steam + ["NNN", "WWW", "WWW"])] + } + } + + private static func bubbleStamps(_ bubble: NotchClawdPose.Bubble) -> [Stamp] { + switch bubble { + case .alert: + return [Stamp(x: 15, y: -7, rows: ["XX", "XX", "XX", "..", "XX"])] + case .question: + return [Stamp(x: 15, y: -7, rows: ["XXX", "..X", ".X.", "...", ".X."])] + case .sleep(let phase): + let small = ["ZZZZ", "..Z.", ".Z..", "ZZZZ"], large = ["ZZZZZ", "...Z.", "..Z..", ".Z...", "ZZZZZ"] + switch phase % 3 { + case 0: return [Stamp(x: 13, y: -3, rows: small)] + case 1: return [Stamp(x: 13, y: -3, rows: small), Stamp(x: 14, y: -9, rows: large)] + default: return [Stamp(x: 14, y: -9, rows: large)] + } + } + } + + // MARK: Colors + + /// sRGB out of 255 for each letter; the shell and accent letters come + /// from the costume. + static func color(_ letter: Character, costume: ClawdCostume) -> (red: Int, green: Int, blue: Int)? { + let shell = costume.shell.rgb, accent = accent(for: costume.shell).rgb + switch letter { + case "C": return shell + case "c": return shaded(shell) + case "A": return accent + case "a": return shaded(accent) + case "E": return (24, 22, 26) + case "K": return (32, 32, 38) + case "D": return (66, 66, 78) + case "d": return (108, 108, 124) + case "L": return (30, 30, 40) + case "l": return (150, 170, 205) + case "W": return (246, 244, 238) + case "w": return (196, 200, 210) + case "R": return (226, 64, 64) + case "Y": return (247, 198, 70) + case "y": return (196, 142, 44) + case "T": return (64, 204, 232) + case "N": return (124, 76, 44) + case "B": return (72, 132, 232) + case "S": return (156, 158, 170) + case "s": return (98, 100, 112) + case "X": return (255, 199, 71) + case "Z": return (196, 206, 236) + default: return nil + } + } + + /// The color hats, scarves and headphones come in on each shell: one + /// far enough from it to stand out. + static func accent(for shell: ClawdShell) -> ClawdShell { + switch shell { + case .clay: return .sky + case .coral: return .teal + case .amber: return .iris + case .moss: return .coral + case .mint: return .orchid + case .teal: return .amber + case .sky: return .coral + case .iris: return .amber + case .orchid: return .mint + case .rose: return .sky + } + } + + private static func shaded(_ color: (red: Int, green: Int, blue: Int)) -> (red: Int, green: Int, blue: Int) { + (color.red * 78 / 100, color.green * 78 / 100, color.blue * 78 / 100) + } + + /// Straight RGBA bytes for the canvas, transparent where nothing is drawn. + static func pixels(_ costume: ClawdCostume, _ pose: NotchClawdPose) -> [UInt8] { + var bytes = [UInt8](repeating: 0, count: width * height * 4) + for (index, letter) in letters(costume, pose).enumerated() { + guard let letter, let color = color(letter, costume: costume) else { continue } + bytes[index * 4] = UInt8(clamping: color.red) + bytes[index * 4 + 1] = UInt8(clamping: color.green) + bytes[index * 4 + 2] = UInt8(clamping: color.blue) + bytes[index * 4 + 3] = 255 + } + return bytes + } + + // MARK: Images + + private static let cache: NSCache = { + let cache = NSCache() + cache.countLimit = 512 + return cache + }() + + /// The canvas as an image, a pixel per canvas pixel, made once per + /// costume and pose. Every pixel is either opaque or clear. + static func image(_ costume: ClawdCostume, _ pose: NotchClawdPose) -> CGImage? { + let key = "\(costume.code)|\(pose.key)" as NSString + if let image = cache.object(forKey: key) { return image } + let data = Data(pixels(costume, pose)) + guard let provider = CGDataProvider(data: data as CFData), + let space = CGColorSpace(name: CGColorSpace.sRGB), + let image = CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, + bytesPerRow: width * 4, space: space, + bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue), + provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent) + else { return nil } + cache.setObject(image, forKey: key) + return image + } +} diff --git a/Sources/Vorssaint/UI/Notch/NotchClawdView.swift b/Sources/Vorssaint/UI/Notch/NotchClawdView.swift new file mode 100644 index 000000000..60f46869d --- /dev/null +++ b/Sources/Vorssaint/UI/Notch/NotchClawdView.swift @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Vorssaint + +import AppKit +import QuartzCore + +/// A Clawd on screen: one layer showing the image of its pose, scaled up a +/// whole number of device pixels per canvas pixel with no smoothing, so its +/// edges stay sharp. A clock steps it a dozen times a second while it can be +/// seen, and the layer changes only when the pose does. Settings keeps its +/// views when it closes, so the window's visibility is watched as well. +final class NotchClawdView: NSView { + private let sprite = CALayer() + private(set) var costume = ClawdCostume.classic + private(set) var motion = NotchClawdMotion.rest + private var seed: UInt64 = 0 + private var still = false + private var bubbles = true + /// When the hop for finished work began, on the media clock. + private var cheerStart: CFTimeInterval? + private var cheerSince: Date? + private var configured = false + private(set) var pose: NotchClawdPose? + private var visibilityObserver: NSObjectProtocol? + /// When the motion under way began, on the media clock. Updates that + /// change nothing keep it, so the motion never jumps back. + private(set) var motionStart: CFTimeInterval = 0 + private var clock: NotchDecorativeClock? + + override init(frame frameRect: NSRect) { + super.init(frame: frameRect) + wantsLayer = true + layer?.masksToBounds = false + sprite.magnificationFilter = .nearest + sprite.minificationFilter = .nearest + sprite.contentsGravity = .resize + sprite.actions = ["contents": NSNull(), "bounds": NSNull(), "position": NSNull(), "frame": NSNull(), + "contentsScale": NSNull()] + layer?.addSublayer(sprite) + setAccessibilityElement(false) + } + + required init?(coder: NSCoder) { nil } + + deinit { + if let visibilityObserver { NotificationCenter.default.removeObserver(visibilityObserver) } + } + + override var isFlipped: Bool { true } + override func hitTest(_ point: NSPoint) -> NSView? { nil } + + /// Shows `costume` doing `motion`. `seed` is the Clawd's own rhythm. + /// `cheer` is when the work it hops for ended. `still` is Reduce Motion. + func configure(costume: ClawdCostume, motion: NotchClawdMotion, seed: UInt64, cheer: Date? = nil, + still: Bool, bubbles: Bool = true) { + let restart = !configured || motion != self.motion + guard restart || costume != self.costume || seed != self.seed || still != self.still || cheer != cheerSince + || bubbles != self.bubbles + else { return } + configured = true + self.costume = costume + self.motion = motion + self.seed = seed + self.still = still + self.bubbles = bubbles + let now = CACurrentMediaTime() + if restart { motionStart = now } + if cheer != cheerSince { + cheerSince = cheer + cheerStart = cheer.map { now - Date().timeIntervalSince($0) } + } + pose = nil + updateLayers() + } + + func stop() { + still = true + updateLayers() + if let visibilityObserver { NotificationCenter.default.removeObserver(visibilityObserver) } + visibilityObserver = nil + } + + override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + if let visibilityObserver { NotificationCenter.default.removeObserver(visibilityObserver) } + visibilityObserver = window.map { window in + NotificationCenter.default.addObserver(forName: NSWindow.didChangeOcclusionStateNotification, + object: window, queue: .main) { [weak self] _ in + self?.updateLayers() + } + } + updateLayers() + } + + override func viewDidChangeBackingProperties() { + super.viewDidChangeBackingProperties() + placeSprite() + } + + override func viewDidHide() { super.viewDidHide(); updateLayers() } + override func viewDidUnhide() { super.viewDidUnhide(); updateLayers() } + override func layout() { super.layout(); placeSprite() } + + override func setFrameSize(_ newSize: NSSize) { + super.setFrameSize(newSize) + placeSprite() + } + + var isMoving: Bool { clock?.isRunning == true } + + private var backingScale: CGFloat { window?.backingScaleFactor ?? NSScreen.main?.backingScaleFactor ?? 2 } + + /// The canvas fitted to the view, on whole device pixels. + private func placeSprite() { + let fit = NotchClawdSprite.layout(box: bounds.size, scale: backingScale) + let frame = CGRect(x: fit.origin.x, y: fit.origin.y, + width: CGFloat(NotchClawdSprite.width) * fit.pixel, + height: CGFloat(NotchClawdSprite.height) * fit.pixel) + CATransaction.begin() + CATransaction.setDisableActions(true) + if sprite.frame != frame { sprite.frame = frame } + sprite.contentsScale = backingScale + CATransaction.commit() + } + + private func updateLayers() { + let moving = !still && configured && !isHiddenOrHasHiddenAncestor + && window?.isVisible == true && window?.occlusionState.contains(.visible) == true + placeSprite() + show(at: CACurrentMediaTime()) + if moving { + // Low Power Mode halves the steps; the poses keep their timing. + let rate = ProcessInfo.processInfo.isLowPowerModeEnabled ? NotchClawdSprite.rate / 2 : NotchClawdSprite.rate + if clock?.stepsPerSecond != rate { + clock?.stop() + clock = NotchDecorativeClock(rate: rate) { [weak self] time in self?.step(at: time) } + } + if let clock, let window, !clock.isRunning, window.contentView != nil { clock.start(in: self) } + } else { + clock?.stop() + } + } + + /// The pose for `time` on the media clock, set on the layer when it + /// differs from the one shown. + private func show(at time: CFTimeInterval) { + guard configured else { return } + let next = NotchClawdSprite.pose(motion, at: time - motionStart, seed: seed, + cheer: cheerStart.map { time - $0 }, still: still, bubbles: bubbles) + guard next != pose else { return } + pose = next + CATransaction.begin() + CATransaction.setDisableActions(true) + sprite.contents = NotchClawdSprite.image(costume, next) + CATransaction.commit() + } + + func step(at time: CFTimeInterval) { + guard isMoving else { return } + show(at: time) + } +} diff --git a/Sources/Vorssaint/UI/Notch/NotchClawdWardrobeView.swift b/Sources/Vorssaint/UI/Notch/NotchClawdWardrobeView.swift new file mode 100644 index 000000000..627b3e31a --- /dev/null +++ b/Sources/Vorssaint/UI/Notch/NotchClawdWardrobeView.swift @@ -0,0 +1,264 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Vorssaint + +import SwiftUI + +/// Where a session's Clawd is dressed: the Clawd itself on the left, doing +/// what its session does, and on the right a row for each part of its +/// costume. A choice dresses it at once, and it hops for it. +struct NotchClawdWardrobeView: View { + let session: ClaudeSession + let size: CGSize + @ObservedObject private var service = ClaudeSessionService.shared + @ObservedObject private var l10n = L10n.shared + @Environment(\.accessibilityReduceMotion) private var reduceMotion + /// When the costume last changed here, which the Clawd hops for. + @State private var changed: Date? + + private var text: NotchClaudeSessionStrings { FeatureStrings.notchClaudeSessions(l10n.language) } + private var costume: ClawdCostume { service.costume(for: session) } + private var dressedByHand: Bool { service.costumes[session.id] != nil } + /// The stage grows with an enlarged island, up to a point. + private var stageWidth: CGFloat { min(230, max(150, size.width * 0.3)) } + + var body: some View { + VStack(spacing: 8) { + if session.phase.isWaiting { waitingBar } + HStack(alignment: .top, spacing: 14) { + stage + ScrollView { + VStack(alignment: .leading, spacing: 12) { + shells + part(text.hatTitle, chosen: text.name(costume.hat), parts: ClawdHat.allCases, + name: text.name, selected: costume.hat) { dressed(\.hat, $0) } + part(text.eyewearTitle, chosen: text.name(costume.eyewear), parts: ClawdEyewear.allCases, + name: text.name, selected: costume.eyewear) { dressed(\.eyewear, $0) } + part(text.extrasTitle, chosen: text.name(costume.extra), parts: ClawdExtra.allCases, + name: text.name, selected: costume.extra) { dressed(\.extra, $0) } + } + .padding(.bottom, 8) + .frame(maxWidth: .infinity, alignment: .leading) + } + .scrollIndicators(.automatic) + } + } + .notchBand(leading: { + NotchBandBackButton(title: text.wardrobe) { service.dress(nil) } + }, trailing: { + HStack(spacing: 2) { + surpriseButton + resetButton + } + }) + } + + // MARK: Stage + + private var stage: some View { + VStack(spacing: 8) { + ZStack(alignment: .bottom) { + // The floor it stands on, a soft light under its feet. + Ellipse() + .fill(.white.opacity(0.07)) + .frame(width: stageWidth * 0.62, height: 10) + .offset(y: -10) + NotchClawd(costume: costume, motion: NotchClaudeSessionsSupport.motion(session, now: Date()), + seed: ClawdCostume.seed(session.id), cheer: changed ?? NotchClaudeSessionsSupport.cheer(session), + size: CGSize(width: stageWidth - 24, height: stageWidth * 0.78)) + .padding(.bottom, 14) + } + .frame(width: stageWidth, height: stageWidth * 0.78 + 24) + .modifier(NotchControlSurface(cornerRadius: 18, interactive: false)) + .accessibilityElement() + .accessibilityLabel(outfit) + Text(service.displayName(session)) + .font(.system(size: 13, weight: .semibold)) + .foregroundStyle(.white.opacity(0.95)) + .lineLimit(1) + .truncationMode(.tail) + NotchClaudeProjectTag(project: session.project) + } + .frame(width: stageWidth) + } + + /// The costume read aloud, part by part. + private var outfit: String { + [text.name(costume.shell), costume.hat == .none ? nil : text.name(costume.hat), + costume.eyewear == .none ? nil : text.name(costume.eyewear), + costume.extra == .none ? nil : text.name(costume.extra)] + .compactMap { $0 }.joined(separator: ", ") + } + + /// The session asked for something while it was being dressed. + private var waitingBar: some View { + Button { service.dress(nil) } label: { + HStack(spacing: 6) { + Image(systemName: NotchClaudeSessionsSupport.symbol(session.phase)) + .font(.system(size: 11, weight: .semibold)) + Text(text.phase(session.phase)) + .font(.system(size: 12, weight: .semibold)) + Spacer(minLength: 6) + Text(text.goToSession) + .font(.system(size: 12, weight: .medium)) + Image(systemName: "chevron.right") + .font(.system(size: 9, weight: .bold)) + } + .foregroundStyle(session.phase.tint) + .padding(.horizontal, 12) + .frame(height: 30) + .background(session.phase.tint.opacity(0.14), in: Capsule()) + .contentShape(Capsule()) + } + .buttonStyle(NotchButtonStyle(cornerRadius: 15, lifts: false)) + .transition(.opacity) + } + + // MARK: Parts + + private var shells: some View { + VStack(alignment: .leading, spacing: 6) { + heading(text.shellTitle, chosen: text.name(costume.shell)) + LazyVGrid(columns: [GridItem(.adaptive(minimum: 26, maximum: 30), spacing: 3)], alignment: .leading, spacing: 3) { + ForEach(ClawdShell.allCases) { shell in + let selected = shell == costume.shell + let color = shell.rgb + Button { dressed(\.shell, shell) } label: { + Circle() + .fill(Color(.sRGB, red: Double(color.red) / 255, green: Double(color.green) / 255, + blue: Double(color.blue) / 255)) + .frame(width: 20, height: 20) + .padding(3) + .overlay { Circle().strokeBorder(.white.opacity(selected ? 0.9 : 0), lineWidth: 2) } + .frame(width: 28, height: 28) + .contentShape(Circle()) + } + .buttonStyle(.plain) + .help(text.name(shell)) + .accessibilityLabel(text.name(shell)) + .accessibilityAddTraits(selected ? .isSelected : []) + .animation(reduceMotion ? nil : .easeOut(duration: 0.15), value: selected) + } + } + } + .accessibilityElement(children: .contain) + .accessibilityLabel(text.shellTitle) + } + + /// A row of tiles for one part: nothing, then each piece on a Clawd in + /// the shell it wears, with nothing else on, so the piece reads. + private func part(_ title: String, chosen: String, parts: [Part], + name: @escaping (Part) -> String, selected: Part, + choose: @escaping (Part) -> Void) -> some View { + VStack(alignment: .leading, spacing: 6) { + heading(title, chosen: chosen) + LazyVGrid(columns: [GridItem(.adaptive(minimum: 46, maximum: 54), spacing: 6)], alignment: .leading, spacing: 6) { + ForEach(parts) { piece in + tile(piece, isSelected: piece == selected, name: name(piece)) { choose(piece) } + } + } + } + .accessibilityElement(children: .contain) + .accessibilityLabel(title) + } + + private func tile(_ piece: Part, isSelected: Bool, name: String, action: @escaping () -> Void) -> some View { + Button(action: action) { + ZStack { + RoundedRectangle(cornerRadius: 10, style: .continuous) + .fill(.white.opacity(isSelected ? 0.13 : 0.05)) + if let outfit = wearing(piece) { + NotchClawdPicture(costume: outfit, size: CGSize(width: 34, height: 30)) + .offset(y: 3) + } else { + Image(systemName: "line.diagonal") + .font(.system(size: 15, weight: .regular)) + .foregroundStyle(.white.opacity(0.4)) + } + } + .frame(height: 44) + .overlay { + RoundedRectangle(cornerRadius: 10, style: .continuous) + .strokeBorder(.white.opacity(isSelected ? 0.85 : 0.07), lineWidth: isSelected ? 1.5 : 1) + } + .contentShape(RoundedRectangle(cornerRadius: 10, style: .continuous)) + } + .buttonStyle(NotchButtonStyle(cornerRadius: 10, lifts: false)) + .help(name) + .accessibilityLabel(name) + .accessibilityAddTraits(isSelected ? .isSelected : []) + .animation(reduceMotion ? nil : .easeOut(duration: 0.15), value: isSelected) + } + + /// The Clawd a tile shows: in this session's shell, wearing only the + /// piece; nil for the tile that takes the part off. + private func wearing(_ piece: Part) -> ClawdCostume? { + var outfit = ClawdCostume(shell: costume.shell, hat: .none, eyewear: .none, extra: .none) + switch piece { + case let hat as ClawdHat where hat != .none: outfit.hat = hat + case let eyewear as ClawdEyewear where eyewear != .none: outfit.eyewear = eyewear + case let extra as ClawdExtra where extra != .none: outfit.extra = extra + default: return nil + } + return outfit + } + + private func heading(_ title: String, chosen: String) -> some View { + HStack(alignment: .firstTextBaseline) { + Text(title) + .font(.system(size: 11, weight: .semibold)) + .foregroundStyle(.white.opacity(0.85)) + Spacer(minLength: 8) + Text(chosen) + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .lineLimit(1) + } + .padding(.trailing, 4) + } + + // MARK: Changing + + private func dressed(_ part: WritableKeyPath, _ value: Value) { + var next = costume + next[keyPath: part] = value + guard next != costume else { return } + wear(next) + } + + private func wear(_ next: ClawdCostume?) { + service.setCostume(next, for: session.id) + changed = Date() + } + + private var surpriseButton: some View { + Button { wear(ClawdCostume.random(excluding: costume)) } label: { + HStack(spacing: 5) { + Image(systemName: "dice") + .font(.system(size: 11, weight: .semibold)) + Text(text.surpriseMe) + .font(.system(size: 12, weight: .medium)) + .lineLimit(1) + } + .foregroundStyle(.white.opacity(0.9)) + .padding(.horizontal, 9) + .frame(height: 28) + .contentShape(RoundedRectangle(cornerRadius: 9, style: .continuous)) + } + .buttonStyle(NotchButtonStyle(cornerRadius: 9)) + .help(text.surpriseMe) + } + + private var resetButton: some View { + Button { wear(nil) } label: { + Image(systemName: "arrow.uturn.backward") + .font(.system(size: 11, weight: .semibold)) + .foregroundStyle(.white.opacity(0.9)) + .frame(width: 28, height: 28) + .contentShape(RoundedRectangle(cornerRadius: 9, style: .continuous)) + } + .buttonStyle(NotchButtonStyle(cornerRadius: 9)) + .disabled(!dressedByHand) + .help(text.ownOutfit) + .accessibilityLabel(text.ownOutfit) + } +} diff --git a/Sources/Vorssaint/UI/Notch/NotchDecorativeClock.swift b/Sources/Vorssaint/UI/Notch/NotchDecorativeClock.swift index 88f06c019..77d586d37 100644 --- a/Sources/Vorssaint/UI/Notch/NotchDecorativeClock.swift +++ b/Sources/Vorssaint/UI/Notch/NotchDecorativeClock.swift @@ -17,9 +17,14 @@ final class NotchDecorativeClock { private let step: (CFTimeInterval) -> Void private var link: CADisplayLink? + /// The most steps a second this clock takes. + let stepsPerSecond: Float /// `step` receives the time the frame being prepared will show at. - init(step: @escaping (CFTimeInterval) -> Void) { + /// Pixel art steps more slowly than `rate`, as its frames change only + /// a dozen times a second. + init(rate: Float = NotchDecorativeClock.rate, step: @escaping (CFTimeInterval) -> Void) { + self.stepsPerSecond = max(1, min(rate, Self.rate)) self.step = step } @@ -33,8 +38,8 @@ final class NotchDecorativeClock { func start(in view: NSView) { guard link == nil else { return } let link = view.displayLink(target: Target(clock: self), selector: #selector(Target.fire(_:))) - link.preferredFrameRateRange = CAFrameRateRange(minimum: Self.rate / 2, maximum: Self.rate, - preferred: Self.rate) + link.preferredFrameRateRange = CAFrameRateRange(minimum: stepsPerSecond / 2, maximum: stepsPerSecond, + preferred: stepsPerSecond) link.add(to: .main, forMode: .common) self.link = link } diff --git a/Sources/Vorssaint/UI/Notch/NotchNoticeView.swift b/Sources/Vorssaint/UI/Notch/NotchNoticeView.swift index 716d9d008..6b3165d2b 100644 --- a/Sources/Vorssaint/UI/Notch/NotchNoticeView.swift +++ b/Sources/Vorssaint/UI/Notch/NotchNoticeView.swift @@ -95,6 +95,11 @@ struct NotchNoticeView: View { .animation(nil, value: hidesMascot) } else if notice.event == .agents, let agent = notice.agent, notice.symbol == agent.symbol { NotchAgentMark(provider: agent, size: 13) + } else if notice.event == .sessions, let id = notice.sessionID, NotchClaudeSessionsSupport.showsBuddies() { + // The session's own Clawd, so the notice says which one it is. + NotchClaudeNoticeClawd(sessionID: id, symbol: notice.symbol, size: CGSize(width: 18, height: 18)) + .id("\(id)|\(notice.symbol)") + .transition(.identity) } else if notice.event == .track { NotchTrackArtwork(size: min(18, geometry.stripHeight - 6)) } else { diff --git a/Sources/Vorssaint/UI/Settings/NotchClaudeSessionsSettingsControls.swift b/Sources/Vorssaint/UI/Settings/NotchClaudeSessionsSettingsControls.swift index 0679e29d0..a0f50f11a 100644 --- a/Sources/Vorssaint/UI/Settings/NotchClaudeSessionsSettingsControls.swift +++ b/Sources/Vorssaint/UI/Settings/NotchClaudeSessionsSettingsControls.swift @@ -10,6 +10,7 @@ struct NotchClaudeSessionsSettingsControls: View { @AppStorage(DefaultsKey.notchSessionsLiveActivity) private var liveActivity = true @AppStorage(DefaultsKey.notchSessionsAutoExpand) private var autoExpand = true @AppStorage(DefaultsKey.notchSessionsContentPreview) private var previews = false + @AppStorage(DefaultsKey.notchSessionsBuddies) private var buddies = true private var text: NotchClaudeSessionStrings { FeatureStrings.notchClaudeSessions(l10n.language) } @@ -22,6 +23,7 @@ struct NotchClaudeSessionsSettingsControls: View { switchRow("waveform.path.ecg", text.liveActivity, isOn: $liveActivity) switchRow("rectangle.expand.vertical", text.autoExpand, caption: text.autoExpandHint, isOn: $autoExpand) switchRow("text.bubble", text.contentPreview, caption: text.contentPreviewHint, isOn: $previews) + buddiesRow Divider() hooks bridge @@ -32,6 +34,37 @@ struct NotchClaudeSessionsSettingsControls: View { } } + /// A few Clawds in their costumes beside the words, so the switch shows + /// what it is about even with no session running. + private var buddiesRow: some View { + VStack(alignment: .leading, spacing: 4) { + SettingsRow(symbol: "tshirt", title: text.buddies) { + Toggle(text.buddies, isOn: $buddies).labelsHidden().toggleStyle(.switch) + } + HStack(alignment: .center, spacing: 12) { + Text(text.buddiesHint) + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + Spacer(minLength: 0) + HStack(spacing: 4) { + ForEach(Self.samples, id: \.self) { costume in + NotchClawdPicture(costume: costume, size: CGSize(width: 30, height: 28)) + } + } + .opacity(buddies ? 1 : 0.35) + .accessibilityHidden(true) + } + .padding(.leading, settingsRowTextInset) + } + } + + private static let samples = [ + ClawdCostume.classic, + ClawdCostume(shell: .sky, hat: .cap, eyewear: .none, extra: .bow), + ClawdCostume(shell: .moss, hat: .topHat, eyewear: .shades, extra: .none), + ] + private var bridge: some View { VStack(alignment: .leading, spacing: 6) { SettingsRow(symbol: "terminal", title: text.bridgeTitle, diff --git a/Tests/ClaudeAgentColorTests.swift b/Tests/ClaudeAgentColorTests.swift new file mode 100644 index 000000000..9dffca108 --- /dev/null +++ b/Tests/ClaudeAgentColorTests.swift @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Vorssaint + +import Foundation + +enum ClaudeAgentColorTests { + static func run(_ suite: TestSuite) { + suite.run("agent definitions") { definitions(suite) } + suite.run("agent colors") { colors(suite) } + } + + static func data(_ text: String) -> Data { Data(text.utf8) } + + static func definitions(_ suite: TestSuite) { + let head = ClaudeAgentDefinitions.frontmatter(data(""" + --- + name: code-reviewer + description: "Reviews: code, for bugs" + color: 'green' + tools: Read, Grep + --- + You review code. color: red + """)) + suite.expect(head.name == "code-reviewer" && head.color == "green", + "an agent's name and color come from its frontmatter, quotes and all: \(head)") + let plain = ClaudeAgentDefinitions.frontmatter(data("name: x\ncolor: red\n")) + suite.expect(plain.name == nil && plain.color == nil, "text that does not open with --- is not frontmatter") + suite.expect(ClaudeAgentDefinitions.frontmatter(data("---\nname: x\ncolor: red\n")).name == nil, + "nor is a block that never closes") + suite.expect(ClaudeAgentDefinitions.frontmatter(data("---\nname: x\n---\n")).color == nil, + "an agent without a color has none") + let long = "---\nname: far\n" + String(repeating: "# filler\n", count: 600) + "color: red\n---\n" + suite.expect(ClaudeAgentDefinitions.frontmatter(data(long)).color == nil, + "only the head of a definition is read") + suite.expect(ClaudeAgentDefinitions.frontmatter(Data([0xff, 0xfe, 0x00])).name == nil, "nor is garbage") + + let home = URL(fileURLWithPath: "/Users/me") + let project = ClaudeAgentDefinitions.folders(type: "reviewer", cwd: "/Users/me/code/app/src", home: home, + plugins: nil, readsProtected: false).map(\.path) + suite.expect(project == ["/Users/me/code/app/src/.claude/agents", "/Users/me/code/app/.claude/agents", + "/Users/me/code/.claude/agents", "/Users/me/.claude/agents", "/Users/me/.config/claude/agents"], + "a project's agents are looked for from its folder up, then the person's: \(project)") + let guarded = ClaudeAgentDefinitions.folders(type: "reviewer", cwd: "/Users/me/Desktop/app", home: home, + plugins: nil, readsProtected: false).map(\.path) + suite.expect(guarded == ["/Users/me/.claude/agents", "/Users/me/.config/claude/agents"], + "folders macOS guards with a prompt are left alone: \(guarded)") + let allowed = ClaudeAgentDefinitions.folders(type: "reviewer", cwd: "/Users/me/Desktop/app", home: home, + plugins: nil, readsProtected: true).map(\.path) + suite.expect(allowed.first == "/Users/me/Desktop/app/.claude/agents" && allowed.count == 4, + "unless the app has Full Disk Access: \(allowed)") + for path in ["/Users/me/Documents/x", "/Users/me/Downloads", "/Users/me/Library/Mobile Documents/com~apple~CloudDocs/a", + "/Volumes/Work/repo"] { + suite.expect(ClaudeAgentDefinitions.isProtected(path, home: home), "\(path) is guarded") + } + for path in ["/Users/me/code", "/Users/me/Desktopper", "/tmp/vs-spike", "/Users/me/.claude"] { + suite.expect(!ClaudeAgentDefinitions.isProtected(path, home: home), "\(path) is not") + } + let outside = ClaudeAgentDefinitions.folders(type: "reviewer", cwd: "/tmp/vs-spike", home: home, plugins: nil, + readsProtected: false).map(\.path) + suite.expect(outside.first == "/tmp/vs-spike/.claude/agents" && outside.contains("/tmp/.claude/agents") + && !outside.contains("/.claude/agents"), + "outside home, the search stops short of the disk's top: \(outside)") + suite.expect(ClaudeAgentDefinitions.folders(type: "reviewer", cwd: "", home: home, plugins: nil, readsProtected: true) + .map(\.path) == ["/Users/me/.claude/agents", "/Users/me/.config/claude/agents"], + "with no folder, only the person's own agents") + + let plugins = data(""" + {"version":2,"plugins":{"feature-dev@official":[{"scope":"user","installPath":"/p/feature-dev/1.0"}], + "feature-devtools@other":[{"installPath":"/p/tools"}],"broken@x":"nope"}} + """) + suite.expect(ClaudeAgentDefinitions.folders(type: "feature-dev:code-reviewer", cwd: "/Users/me/code", home: home, + plugins: plugins, readsProtected: false).map(\.path) + == ["/p/feature-dev/1.0/agents"], + "a plugin's agent is looked for only in that plugin's folder") + suite.expect(ClaudeAgentDefinitions.pluginFolders(data("[]"), plugin: "x").isEmpty + && ClaudeAgentDefinitions.pluginFolders(nil, plugin: "x").isEmpty, + "an unreadable plugin list names no folder") + suite.expect(ClaudeAgentDefinitions.agentName("feature-dev:code-reviewer") == "code-reviewer" + && ClaudeAgentDefinitions.agentName("Explore") == "Explore", "an agent is called without its plugin") + } + + static func colors(_ suite: TestSuite) { + let home = FileManager.default.temporaryDirectory.appending(path: "claude-agents-\(UUID().uuidString)") + defer { try? FileManager.default.removeItem(at: home) } + let project = home.appending(path: "code/app") + func write(_ text: String, to folder: URL, _ name: String) { + try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + try? data(text).write(to: folder.appending(path: name)) + } + write("---\nname: reviewer\ncolor: blue\n---\n", to: home.appending(path: ".claude/agents"), "reviewer.md") + write("---\nname: tester\ncolor: pink\n---\n", to: home.appending(path: ".claude/agents"), "a.md") + write("---\nname: reviewer\ncolor: green\n---\n", to: project.appending(path: ".claude/agents"), "mine.md") + write("no frontmatter here", to: project.appending(path: ".claude/agents"), "plain.md") + let plugin = home.appending(path: "plugin-install") + write("---\nname: architect\ncolor: purple\n---\n", to: plugin.appending(path: "agents"), "architect.md") + write("{\"plugins\":{\"feature-dev@m\":[{\"installPath\":\"\(plugin.path)\"}]}}", + to: home.appending(path: ".claude/plugins"), "installed_plugins.json") + + let colors = ClaudeAgentColors(home: home) + let now = Date() + suite.expect(colors.color(type: "reviewer", cwd: project.path, now: now) == "green", + "the project's own agent wins over the person's of the same name") + suite.expect(colors.color(type: "reviewer", cwd: home.appending(path: "elsewhere").path, now: now) == "blue", + "elsewhere the person's agent counts") + suite.expect(colors.color(type: "tester", cwd: project.path, now: now) == "pink", + "an agent is found by its own name, whatever its file is called") + suite.expect(colors.color(type: "plain", cwd: project.path, now: now) == nil, + "a definition without frontmatter has no color") + suite.expect(colors.color(type: "feature-dev:architect", cwd: project.path, now: now) == "purple", + "a plugin's agent has its plugin's color") + suite.expect(colors.color(type: ClaudeSubagent.untyped, cwd: project.path, now: now) == nil + && colors.color(type: "general-purpose", cwd: project.path, now: now) == nil, + "a subagent of unknown or built-in type has no color") + + write("---\nname: reviewer\ncolor: red\n---\n", to: project.appending(path: ".claude/agents"), "mine.md") + suite.expect(colors.color(type: "reviewer", cwd: project.path, now: now.addingTimeInterval(5)) == "green", + "an answer is kept for a while, so definitions are not read on every tick") + suite.expect(colors.color(type: "reviewer", cwd: project.path, now: now.addingTimeInterval(ClaudeAgentColors.keptFor + 1)) + == "red", "and a changed definition is picked up after that") + + var session = ClaudeSession(id: "s", pid: 1, cwd: project.path, project: "app", name: "app", host: .unknown, phase: .generating, + phaseSince: now, timeline: [], subagents: [ + ClaudeSubagent(id: "a1", type: "tester", started: now), + ClaudeSubagent(id: "a2", type: "Explore", started: now), + ], tokens: AgentTokens(), cost: 0, hooked: false) + session = colors.decorate(session, now: now) + suite.expect(session.subagents.map(\.color) == ["pink", nil], "each subagent of a session gets its color") + } +} diff --git a/Tests/ClawdCostumeTests.swift b/Tests/ClawdCostumeTests.swift new file mode 100644 index 000000000..9d6b4aeb5 --- /dev/null +++ b/Tests/ClawdCostumeTests.swift @@ -0,0 +1,178 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Vorssaint + +import Foundation + +enum ClawdCostumeTests { + static func run(_ suite: TestSuite) { + suite.run("clawd costume lot") { lot(suite) } + suite.run("clawd costume keeping") { keeping(suite) } + suite.run("clawd motions and pages") { motions(suite) } + suite.run("clawd strings") { strings(suite) } + } + + static func lot(_ suite: TestSuite) { + // FNV-1a, not Swift's Hasher, which is seeded anew every launch. + suite.expect(ClawdCostume.seed("") == 0xcbf2_9ce4_8422_2325 && ClawdCostume.seed("a") == 0xaf63_dc4c_8601_ec8c, + "a session's number is FNV-1a over its id, the same on every launch") + let id = "99c35831-5f0b-4c3e-9d0a-0f3c2a7b8e11" + suite.expect(ClawdCostume.seeded(id) == ClawdCostume.seeded(id), "a session always draws the same costume") + var generator = ClawdRandom(seed: 42) + let first = (0..<4).map { _ in generator.next() } + generator = ClawdRandom(seed: 42) + suite.expect(first == (0..<4).map { _ in generator.next() } && Set(first).count == 4, + "the lot gives the same numbers for the same seed, and not the same number twice") + + let costumes = (0..<600).map { ClawdCostume.seeded("session-\($0)") } + suite.expect(Set(costumes.map(\.shell)) == Set(ClawdShell.allCases), "every shell comes up") + suite.expect(Set(costumes.map(\.hat)) == Set(ClawdHat.allCases) + && Set(costumes.map(\.eyewear)) == Set(ClawdEyewear.allCases) + && Set(costumes.map(\.extra)) == Set(ClawdExtra.allCases), + "every hat, pair of eyewear and extra comes up, and so does nothing") + func share(_ count: Int) -> Double { Double(count) / Double(costumes.count) } + let bare = (hat: share(costumes.filter { $0.hat == .none }.count), + eyewear: share(costumes.filter { $0.eyewear == .none }.count), + extra: share(costumes.filter { $0.extra == .none }.count)) + suite.expect(abs(bare.hat - (1 - ClawdCostume.hatChance)) < 0.08 + && abs(bare.eyewear - (1 - ClawdCostume.eyewearChance)) < 0.08 + && abs(bare.extra - (1 - ClawdCostume.extraChance)) < 0.08, + "each part is left off about as often as meant: \(bare)") + let clay = share(costumes.filter { $0.shell == .clay }.count) + let other = share(costumes.filter { $0.shell == .sky }.count) + suite.expect(clay > other * 1.8, "Claude's own color comes up more often than any other: \(clay) to \(other)") + suite.expect(Set(costumes).count > 400, "sessions are told apart by their costumes: \(Set(costumes).count) of 600") + + let current = ClawdCostume.seeded(id) + suite.expect((0..<30).allSatisfy { _ in ClawdCostume.random(excluding: current) != current }, + "Surprise me always changes something") + + let colors = ["red", "orange", "yellow", "green", "cyan", "blue", "purple", "pink"] + let shells = colors.compactMap(ClawdShell.init(agentColor:)) + suite.expect(shells == [.coral, .clay, .amber, .moss, .teal, .sky, .iris, .rose], + "Claude Code's eight agent colors each have their shell: \(shells)") + suite.expect(ClawdShell(agentColor: " Blue\n") == .sky && ClawdShell(agentColor: "teal") == nil + && ClawdShell(agentColor: "") == nil, + "a color is read whatever its case and spacing, and one Claude Code does not offer is not") + let agent = ClawdCostume.seeded("s/a1", agentColor: "green") + var drawn = ClawdCostume.seeded("s/a1") + drawn.shell = .moss + suite.expect(agent == drawn, "a subagent keeps its own lot and only takes its color's shell") + suite.expect(ClawdCostume.seeded("s/a1", agentColor: nil) == ClawdCostume.seeded("s/a1") + && ClawdCostume.seeded("s/a1", agentColor: "mauve") == ClawdCostume.seeded("s/a1"), + "without a color it Claude Code knows, the lot decides the shell too") + } + + static func keeping(_ suite: TestSuite) { + let costume = ClawdCostume(shell: .sky, hat: .topHat, eyewear: .shades, extra: .bowTie) + suite.expect(costume.code == "v1:sky.topHat.shades.bowTie", "a costume keeps as a short versioned line: \(costume.code)") + suite.expect(ClawdCostume(code: costume.code, fallback: .classic) == costume, "and reads back the same") + for costume in [ClawdCostume.classic] + (0..<50).map({ ClawdCostume.seeded("k\($0)") }) { + suite.expect(ClawdCostume(code: costume.code, fallback: .classic) == costume, "\(costume.code) round trips") + } + let fallback = ClawdCostume(shell: .rose, hat: .crown, eyewear: .monocle, extra: .coffee) + suite.expect(ClawdCostume(code: "v1:sky.sombrero.shades.cape", fallback: fallback) + == ClawdCostume(shell: .sky, hat: .crown, eyewear: .shades, extra: .coffee), + "a part a later version added comes from the session's own lot, the rest stays") + for garbage in ["", "sky.cap.none.none", "v2:sky.cap.none.none", "v1:sky.cap.none", "v1:sky.cap.none.none.bow", + "v1:" + String(repeating: "x", count: 200)] { + suite.expect(ClawdCostume(code: garbage, fallback: fallback) == nil, "unreadable \(garbage.prefix(20)) is ignored") + } + let id = "session-1" + suite.expect(ClawdCostume.resolved(key: id, kept: nil) == ClawdCostume.seeded(id) + && ClawdCostume.resolved(key: id, kept: "nonsense") == ClawdCostume.seeded(id) + && ClawdCostume.resolved(key: id, kept: costume.code) == costume, + "a session wears what the person chose for it, or else its own lot") + suite.expect(ClawdCostume.kept(ClawdCostume.seeded(id), key: id) == nil && ClawdCostume.kept(nil, key: id) == nil, + "dressing a session in its own lot keeps nothing") + let other = ClawdCostume.random(excluding: ClawdCostume.seeded(id)) + suite.expect(ClawdCostume.kept(other, key: id) == other.code, "anything else is kept") + + var kept = NotchClaudeSessionsSupport.kept([:], id: "a", value: "v1:sky.cap.none.none", live: ["a"]) + suite.expect(kept == ["a": "v1:sky.cap.none.none"], "a choice is kept by session") + kept = NotchClaudeSessionsSupport.kept(kept, id: "a", value: nil, live: ["a"]) + suite.expect(kept.isEmpty, "and going back to its own lot removes it") + let many = Dictionary(uniqueKeysWithValues: (0.. ClaudeSession { + var session = ClaudeSession(id: "s", pid: 1, cwd: "/x/p", project: "p", name: "p", host: .unknown, phase: phase, + phaseSince: ClaudeSessionEngineTests.at(since), timeline: [], subagents: [], + tokens: AgentTokens(), cost: 0, hooked: false) + session.lastActive = active.map(ClaudeSessionEngineTests.at) + return session + } + let pairs: [(ClaudeSessionPhase, NotchClawdMotion)] = [ + (.generating, .think), (.runningTool, .work), (.background, .slow), (.waitingPermission, .alert), + (.waitingInput, .ask), (.finished, .content), + ] + for (phase, motion) in pairs { + suite.expect(NotchClaudeSessionsSupport.motion(session(phase), now: now) == motion, "\(phase) is \(motion)") + } + suite.expect(NotchClaudeSessionsSupport.motion(session(.idle, since: 990, active: 900), now: now) == .rest, + "a session quiet for a few minutes, as one just read, stays awake") + suite.expect(NotchClaudeSessionsSupport.motion(session(.idle, since: 0, active: 1000 - NotchClaudeSessionsSupport.dozeAfter - 1), + now: now) == .doze, + "a session quiet for long dozes off") + suite.expect(NotchClaudeSessionsSupport.motion(session(.idle, since: 0), now: now) == .doze, + "without a time it last worked, how long it has been idle counts") + suite.expect(NotchClaudeSessionsSupport.cheer(session(.finished, since: 995)) == ClaudeSessionEngineTests.at(995) + && NotchClaudeSessionsSupport.cheer(session(.idle)) == nil, + "a session's Clawd hops from when its work ended, and only then") + let running = ClaudeSubagent(id: "a1", type: "Explore", started: now) + var done = running + done.finished = now + suite.expect(NotchClaudeSessionsSupport.motion(running) == .work && NotchClaudeSessionsSupport.motion(done) == .done, + "a subagent works while it runs and rests once done") + suite.expect(NotchClaudeSessionsSupport.costumeKey(running, in: session(.idle)) == "s/a1", + "a subagent draws its costume from its session and its own id") + suite.expect(NotchClaudeSessionsSupport.noticeMotion(symbol: NotchClaudeSessionsSupport.symbol(.finished)) == .content + && NotchClaudeSessionsSupport.noticeMotion(symbol: NotchClaudeSessionsSupport.symbol(.waitingInput)) == .ask + && NotchClaudeSessionsSupport.noticeMotion(symbol: NotchClaudeSessionsSupport.symbol(.waitingPermission)) == .alert, + "a notice's Clawd matches what the notice says") + + typealias Layer = NotchClaudeSessionsSupport.PageLayer + suite.expect(NotchClaudeSessionsSupport.pageLayer(focused: nil, dressing: nil) == nil + && NotchClaudeSessionsSupport.pageLayer(focused: "a", dressing: nil) == Layer.session + && NotchClaudeSessionsSupport.pageLayer(focused: "a", dressing: "a") == Layer.wardrobe + && NotchClaudeSessionsSupport.pageLayer(focused: "b", dressing: "a") == Layer.session + && NotchClaudeSessionsSupport.pageLayer(focused: nil, dressing: "a") == nil, + "Escape closes the wardrobe, then the page, then the island; a wardrobe left over from another page does not count") + } + + static func strings(_ suite: TestSuite) { + let text = FeatureStrings.notchClaudeSessions(.enUS) + let shells = ClawdShell.allCases.map(text.name) + let hats = ClawdHat.allCases.map(text.name) + let eyewear = ClawdEyewear.allCases.map(text.name) + let extras = ClawdExtra.allCases.map(text.name) + for names in [shells, hats, eyewear, extras] { + suite.expect(names.allSatisfy { !$0.isEmpty } && Set(names).count == names.count, + "every part has a name of its own: \(names)") + } + suite.expect(Set(shells).isDisjoint(with: ClawdShell.allCases.map(\.rawValue)) + && hats.dropFirst().allSatisfy { name in !ClawdHat.allCases.map(\.rawValue).contains(name) }, + "names are words for people, not the keys they are stored by") + suite.expect(hats.first == text.nothing && eyewear.first == text.nothing && extras.first == text.nothing, + "taking a part off is called the same in every row") + suite.expect(text.dressUp("vorsaint") == "Change vorsaint’s outfit", "the Clawd's button names its session") + } +} diff --git a/Tests/MetricsTests.swift b/Tests/MetricsTests.swift index d73a3fbfc..706657264 100644 --- a/Tests/MetricsTests.swift +++ b/Tests/MetricsTests.swift @@ -123,6 +123,10 @@ struct MetricsTests { ClaudeSessionEngineTests.run(suite) ClaudeSessionReaderTests.run(suite) ClaudeHookTests.run(suite) + ClawdCostumeTests.run(suite) + NotchClawdSpriteTests.run(suite) + NotchClawdViewTests.run(suite) + ClaudeAgentColorTests.run(suite) }), ("features", { FeatureCatalogTests.run(suite) diff --git a/Tests/NotchClawdSpriteTests.swift b/Tests/NotchClawdSpriteTests.swift new file mode 100644 index 000000000..4c0153aae --- /dev/null +++ b/Tests/NotchClawdSpriteTests.swift @@ -0,0 +1,182 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Vorssaint + +import CoreGraphics +import Foundation + +enum NotchClawdSpriteTests { + static func run(_ suite: TestSuite) { + suite.run("clawd drawing") { drawing(suite) } + suite.run("clawd poses") { poses(suite) } + suite.run("clawd fitting") { fitting(suite) } + } + + static var everyCostume: [ClawdCostume] { + ClawdShell.allCases.flatMap { shell in + ClawdHat.allCases.flatMap { hat in + ClawdEyewear.allCases.flatMap { eyewear in + ClawdExtra.allCases.map { ClawdCostume(shell: shell, hat: hat, eyewear: eyewear, extra: $0) } + } + } + } + } + + static let motions: [NotchClawdMotion] = [.rest, .content, .doze, .think, .work, .slow, .alert, .ask, .done] + + /// Every pose a Clawd is ever drawn in: each motion over ten seconds, + /// the jump for finished work, and the still poses of Reduce Motion. + static var reachingPoses: [NotchClawdPose] { + var poses = Set() + for motion in motions { + for step in 0..<120 { + let time = Double(step) / 12 + poses.insert(NotchClawdSprite.pose(motion, at: time, seed: 7)) + poses.insert(NotchClawdSprite.pose(motion, at: time, seed: 7, cheer: time)) + poses.insert(NotchClawdSprite.pose(motion, at: time, seed: 7, still: true)) + } + } + return Array(poses) + } + + static func drawing(_ suite: TestSuite) { + suite.expect(everyCostume.count == 10 * 9 * 6 * 7, "a Clawd can be dressed \(everyCostume.count) ways") + // Each part is drawn on its own, so each part checked on its own + // stands for every costume it is part of; the tallest hat with the + // widest extra checks that they fit together too. + let bare = ClawdCostume.classic + var costumes = ClawdShell.allCases.map { ClawdCostume(shell: $0, hat: .party, eyewear: .anaglyph, extra: .coffee) } + costumes += ClawdHat.allCases.map { ClawdCostume(shell: .clay, hat: $0, eyewear: .none, extra: .headphones) } + costumes += ClawdEyewear.allCases.map { ClawdCostume(shell: .clay, hat: .topHat, eyewear: $0, extra: .none) } + costumes += ClawdExtra.allCases.map { ClawdCostume(shell: .clay, hat: .chef, eyewear: .none, extra: $0) } + var clipped: [String] = [], unpainted: Set = [] + for costume in costumes + [bare] { + for pose in reachingPoses { + if NotchClawdSprite.clippedPixels(costume, pose) > 0 { clipped.append("\(costume.code) \(pose.key)") } + for letter in NotchClawdSprite.letters(costume, pose).compactMap({ $0 }) + where NotchClawdSprite.color(letter, costume: costume) == nil { unpainted.insert(letter) } + } + } + suite.expect(clipped.isEmpty, "every costume fits the canvas in every pose: \(clipped.prefix(5))") + suite.expect(unpainted.isEmpty, "every letter drawn has a color: \(unpainted)") + + let width = NotchClawdSprite.width, x = NotchClawdSprite.bodyX, y = NotchClawdSprite.bodyY + func letter(_ costume: ClawdCostume, column: Int, row: Int) -> Character? { + NotchClawdSprite.letters(costume, NotchClawdPose())[(y + row) * width + x + column] + } + suite.expect(letter(bare, column: 3, row: 2) == "E" && letter(bare, column: 9, row: 3) == "E" + && letter(bare, column: 6, row: 0) == "C" && letter(bare, column: 0, row: 9) == "C", + "Clawd has two eyes, a body and legs where Claude Code draws them") + for eyewear in ClawdEyewear.allCases { + let worn = ClawdCostume(shell: .clay, hat: .none, eyewear: eyewear, extra: .none) + let eyes = [(3, 2), (3, 3), (9, 2), (9, 3)].map { letter(worn, column: $0.0, row: $0.1) } + let covers = eyewear == .shades || eyewear == .anaglyph + suite.expect(covers ? !eyes.contains("E") : eyes.allSatisfy { $0 == "E" }, + "\(eyewear) \(covers ? "covers" : "shows") the eyes: \(eyes)") + } + for shell in ClawdShell.allCases { + suite.expect(NotchClawdSprite.accent(for: shell) != shell, "a hat on \(shell) is told from the shell") + } + suite.expect(Set(ClawdShell.allCases.map { "\($0.rgb)" }).count == ClawdShell.allCases.count, + "every shell has its own color") + suite.expect(ClawdShell.clay.rgb == (215, 119, 87), "the classic shell is Claude Code's own clawd_body") + + let image = NotchClawdSprite.image(bare, NotchClawdPose()) + suite.expect(image?.width == width && image?.height == NotchClawdSprite.height, + "an image has a pixel per canvas pixel") + suite.expect(NotchClawdSprite.image(bare, NotchClawdPose()) === image, "an image is made once per costume and pose") + let bytes = NotchClawdSprite.pixels(bare, NotchClawdPose()) + suite.expect(stride(from: 3, to: bytes.count, by: 4).allSatisfy { bytes[$0] == 0 || bytes[$0] == 255 }, + "every pixel is opaque or clear, so scaling without smoothing keeps its edges") + var propeller = ClawdCostume.classic + propeller.hat = .propeller + suite.expect(NotchClawdSprite.letters(propeller, NotchClawdPose(tick: 0)) + != NotchClawdSprite.letters(propeller, NotchClawdPose(tick: 1)), + "a propeller turns from one step to the next") + } + + static func poses(_ suite: TestSuite) { + let seed = ClawdCostume.seed("session") + func poses(_ motion: NotchClawdMotion, over seconds: Double = 8) -> [NotchClawdPose] { + stride(from: 0.0, to: seconds, by: 1 / 12).map { NotchClawdSprite.pose(motion, at: $0, seed: seed) } + } + let rest = poses(.rest) + suite.expect(rest.contains { $0.eyes == .closed } && rest.contains { $0.rise == 1 } && rest.contains { $0.rise == 0 }, + "at rest it blinks and breathes") + suite.expect(rest.filter { $0.eyes == .closed }.count <= 2 * Int(8 / 3.4 + 1), + "a blink lasts two steps") + suite.expect(poses(.doze).allSatisfy { $0.eyes == .closed } + && Set(poses(.doze).compactMap(\.bubble)).count == 3, "dozing, its eyes stay shut and the z's rise") + suite.expect(Set(poses(.think).map(\.arms)) == [.typeLeft, .typeRight], "thinking, its hands are busy") + suite.expect(Set(poses(.work).map(\.legs)) == [.stand, .stepLeft, .stepRight], "at work it waddles") + let alert = poses(.alert) + suite.expect(alert.allSatisfy { $0.bubble == .alert } && alert.contains { $0.jump > 0 } + && alert.contains { $0.arms == .waveUp } && alert.allSatisfy { $0.jump == 0 || $0.legs == .stand }, + "waiting on a permission, it hops and waves under a !") + suite.expect(poses(.ask).allSatisfy { $0.bubble == .question }, "waiting on an answer, it shows a ?") + suite.expect(poses(.content).allSatisfy { $0.eyes == .happy } && Set(poses(.done)).count == 1, + "done, it smiles, and a subagent that finished keeps still") + let other = ClawdCostume.seed("another session") + let blinks = stride(from: 0.0, to: 20, by: 1 / 12).map { NotchClawdSprite.blinks($0, seed: seed) } + let otherBlinks = stride(from: 0.0, to: 20, by: 1 / 12).map { NotchClawdSprite.blinks($0, seed: other) } + suite.expect(blinks != otherBlinks, "two Clawds side by side do not blink as one") + + for motion in [NotchClawdMotion.rest, .content, .doze, .think, .work, .slow, .alert, .ask, .done] { + let still = stride(from: 0.0, to: 6, by: 0.25).map { + NotchClawdSprite.pose(motion, at: $0, seed: seed, cheer: 0.5, still: true) + } + suite.expect(Set(still).count == 1 && still[0].jump == 0 && still[0].rise == 0, + "with Reduce Motion, \(motion) is one pose that does not move") + } + let still = { (motion: NotchClawdMotion) in NotchClawdSprite.pose(motion, at: 0, seed: seed, still: true) } + suite.expect(still(.alert).bubble == .alert && still(.ask).bubble == .question && still(.doze).eyes == .closed + && still(.content).eyes == .happy && still(.think).arms == .typeLeft, + "and each still pose says what the motion says") + + let cheer = stride(from: 0.0, to: NotchClawdSprite.cheerLength, by: 1 / 12).map { + NotchClawdSprite.pose(.content, at: 30, seed: seed, cheer: $0) + } + suite.expect(cheer.contains { $0.jump >= 4 && $0.arms == .up } && cheer.allSatisfy { $0.eyes == .happy }, + "when its work ends it jumps with both arms up") + suite.expect(NotchClawdSprite.pose(.content, at: 30, seed: seed, cheer: NotchClawdSprite.cheerLength) + == NotchClawdSprite.pose(.content, at: 30, seed: seed), + "and once the jump is over, a Clawd drawn later does not jump again") + suite.expect(NotchClawdSprite.pose(.alert, at: 0.2, seed: seed, bubbles: false).bubble == nil + && NotchClawdSprite.pose(.doze, at: 1, seed: seed, bubbles: false).bubble == nil, + "where there is no room above, no bubble shows") + suite.expect(NotchClawdSprite.pose(.rest, at: .nan, seed: seed) == NotchClawdSprite.pose(.rest, at: 0, seed: seed) + && NotchClawdSprite.pose(.rest, at: -5, seed: seed) == NotchClawdSprite.pose(.rest, at: 0, seed: seed), + "a time that makes no sense counts as the start") + suite.expect(Set(rest.map(\.key)).count == Set(rest).count, "each pose has a key of its own") + } + + static func fitting(_ suite: TestSuite) { + for (box, scale) in [(CGSize(width: 32, height: 30), 2.0), (CGSize(width: 40, height: 36), 2.0), + (CGSize(width: 18, height: 18), 2.0), (CGSize(width: 32, height: 30), 1.0), + (CGSize(width: 48, height: 42), 3.0), (CGSize(width: 130, height: 110), 2.0)] { + let fit = NotchClawdSprite.layout(box: box, scale: scale) + let devicePixels = fit.pixel * scale + let frameWidth = CGFloat(NotchClawdSprite.frameColumns.count) * fit.pixel + let frameHeight = CGFloat(NotchClawdSprite.frameRows.count) * fit.pixel + let frameLeft = fit.origin.x + CGFloat(NotchClawdSprite.frameColumns.lowerBound) * fit.pixel + let frameTop = fit.origin.y + CGFloat(NotchClawdSprite.frameRows.lowerBound) * fit.pixel + suite.expect(devicePixels == devicePixels.rounded() && devicePixels >= 1, + "\(box) at \(scale)x: a canvas pixel is a whole number of device pixels: \(devicePixels)") + suite.expect(frameWidth <= box.width + 0.001 && frameHeight <= box.height + 0.001, + "\(box) at \(scale)x: the figure fits its box") + suite.expect(abs(frameLeft + frameWidth / 2 - box.width / 2) <= 0.5 / scale + 0.001 + && abs(frameTop + frameHeight / 2 - box.height / 2) <= 0.5 / scale + 0.001, + "\(box) at \(scale)x: the figure is centred") + suite.expect((fit.origin.x * scale).rounded() == fit.origin.x * scale + && (fit.origin.y * scale).rounded() == fit.origin.y * scale, + "\(box) at \(scale)x: the canvas starts on a device pixel") + } + suite.expect(NotchClawdSprite.layout(box: CGSize(width: 32, height: 30), scale: 2).pixel == 1.5, + "a Clawd in a list row gets three device pixels a canvas pixel") + suite.expect(NotchClawdSprite.layout(box: .zero, scale: 2).pixel == 0.5 + && NotchClawdSprite.layout(box: CGSize(width: 40, height: 40), scale: .nan).pixel > 0, + "an empty box or a scale that makes no sense still draws something") + // Every costume is the same size: a hat reaches above the frame instead. + suite.expect(NotchClawdSprite.frameColumns.count == 17 && NotchClawdSprite.frameRows.upperBound == NotchClawdSprite.height, + "the frame is the body with its arms, standing on the canvas's bottom") + } +} diff --git a/Tests/NotchClawdViewTests.swift b/Tests/NotchClawdViewTests.swift new file mode 100644 index 000000000..045899672 --- /dev/null +++ b/Tests/NotchClawdViewTests.swift @@ -0,0 +1,124 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Vorssaint + +import AppKit +import QuartzCore + +enum NotchClawdViewTests { + private final class Window: NSWindow { + var shown = true + var exposed = true + override var isVisible: Bool { shown } + override var occlusionState: NSWindow.OcclusionState { exposed ? [.visible] : [] } + func notifyVisibility() { + NotificationCenter.default.post(name: NSWindow.didChangeOcclusionStateNotification, object: self) + } + } + + static func run(_ suite: TestSuite) { + suite.run("clawd view") { view(suite) } + } + + static func view(_ suite: TestSuite) { + let window = Window(contentRect: CGRect(x: 0, y: 0, width: 80, height: 80), + styleMask: .borderless, backing: .buffered, defer: false) + window.isReleasedWhenClosed = false + let container = NSView(frame: window.frame) + window.contentView = container + let costume = ClawdCostume(shell: .sky, hat: .cap, eyewear: .none, extra: .none) + let view = NotchClawdView(frame: CGRect(x: 0, y: 0, width: 32, height: 30)) + func animationCount(_ layer: CALayer? = nil) -> Int { + guard let layer = layer ?? view.layer else { return 0 } + return (layer.animationKeys() ?? []).count + (layer.sublayers ?? []).reduce(0) { $0 + animationCount($1) } + } + func sprite() -> CALayer? { view.layer?.sublayers?.first } + + view.configure(costume: costume, motion: .work, seed: 7, still: false) + suite.expect(!view.isMoving, "a Clawd not on screen does not move") + container.addSubview(view) + suite.expect(view.isMoving, "on screen it moves") + suite.expect(animationCount() == 0, "it leaves no repeating animation for the window server to draw at the display's rate") + suite.expect(sprite()?.contents != nil && sprite()?.magnificationFilter == .nearest + && sprite()?.minificationFilter == .nearest, "its image is scaled without smoothing") + let frame = sprite()?.frame ?? .zero + let scale = window.backingScaleFactor + suite.expect(abs(frame.width * scale - (frame.width * scale).rounded()) < 0.001 + && abs(frame.width / CGFloat(NotchClawdSprite.width) * scale + - (frame.width / CGFloat(NotchClawdSprite.width) * scale).rounded()) < 0.001, + "each canvas pixel covers whole device pixels: \(frame)") + + let started = view.motionStart + view.configure(costume: costume, motion: .work, seed: 7, still: false) + suite.expect(view.motionStart == started, "an update that changes nothing keeps the motion where it is") + let poses = stride(from: 0.0, to: 2, by: 1 / 12).map { time -> NotchClawdPose? in + view.step(at: started + time) + return view.pose + } + suite.expect(Set(poses.compactMap { $0 }).count > 1, "stepping the clock moves it from pose to pose") + view.step(at: started + 0.5) + let shown = sprite()?.contents as AnyObject? + view.step(at: started + 0.5) + suite.expect(sprite()?.contents as AnyObject? === shown, "the same pose keeps the same image") + + view.configure(costume: costume, motion: .alert, seed: 7, still: false) + suite.expect(view.motionStart > started, "a new motion starts from its beginning") + view.configure(costume: costume, motion: .alert, seed: 7, still: true) + suite.expect(!view.isMoving && view.pose?.bubble == .alert, "Reduce Motion stops it in a pose that says the same") + view.configure(costume: costume, motion: .alert, seed: 7, still: false) + view.configure(costume: costume, motion: .alert, seed: 7, still: false, bubbles: false) + suite.expect(view.pose?.bubble == nil, "a Clawd in a notice shows no bubble") + view.configure(costume: costume, motion: .content, seed: 7, cheer: Date().addingTimeInterval(-0.3), still: false) + view.step(at: CACurrentMediaTime()) + suite.expect((view.pose?.jump ?? 0) > 0 || view.pose?.arms == .up, "work that just ended makes it jump") + view.configure(costume: costume, motion: .content, seed: 7, cheer: Date().addingTimeInterval(-60), still: false) + view.step(at: CACurrentMediaTime()) + suite.expect(view.pose?.jump == 0, "work that ended long ago does not") + + window.exposed = false + window.notifyVisibility() + suite.expect(!view.isMoving, "a covered island stops it") + window.exposed = true + window.notifyVisibility() + suite.expect(view.isMoving, "and uncovering it starts it again") + window.shown = false + window.notifyVisibility() + suite.expect(!view.isMoving, "closed Settings keep it still") + window.shown = true + window.notifyVisibility() + container.isHidden = true + suite.expect(!view.isMoving, "a hidden page stops it") + container.isHidden = false + suite.expect(view.isMoving, "and showing the page starts it") + suite.expect(view.hitTest(.zero) == nil && !view.isAccessibilityElement(), + "a Clawd takes no clicks and is not read out on its own") + view.removeFromSuperview() + suite.expect(!view.isMoving, "taking it off screen stops it") + container.addSubview(view) + view.stop() + window.notifyVisibility() + suite.expect(!view.isMoving, "and a dismantled Clawd stays still") + view.removeFromSuperview() + + let clock = NotchDecorativeClock(rate: NotchClawdSprite.rate) { _ in } + let host = NSView(frame: container.bounds) + container.addSubview(host) + clock.start(in: host) + let range = clock.displayLink?.preferredFrameRateRange + suite.expect(range?.maximum == NotchClawdSprite.rate && NotchClawdSprite.rate <= 12, + "a Clawd steps at most a dozen times a second: \(String(describing: range))") + clock.stop() + suite.expect(NotchDecorativeClock(rate: 120) { _ in }.stepsPerSecond == NotchDecorativeClock.rate + && NotchDecorativeClock { _ in }.stepsPerSecond == NotchDecorativeClock.rate, + "no clock steps faster than the decorations' own rate") + + weak var released: NotchClawdView? + autoreleasepool { + let view = NotchClawdView(frame: .zero) + released = view + view.configure(costume: costume, motion: .think, seed: 1, still: false) + container.addSubview(view) + view.removeFromSuperview() + } + suite.expect(released == nil, "watching the window does not keep a discarded Clawd alive") + } +} diff --git a/build.sh b/build.sh index 6efe752cf..69dd3d693 100755 --- a/build.sh +++ b/build.sh @@ -295,6 +295,8 @@ if (( TEST )); then Sources/Vorssaint/Services/ClaudeSessions/ClaudeHookMessage.swift Sources/Vorssaint/Services/ClaudeSessions/ClaudeHookServer.swift Sources/Vorssaint/Services/ClaudeSessions/ClaudeHookInstaller.swift + Sources/Vorssaint/Services/ClaudeSessions/ClawdCostume.swift + Sources/Vorssaint/Services/ClaudeSessions/ClaudeAgentColors.swift Sources/Vorssaint/Core/NotchLockScreenStrings.swift Sources/Vorssaint/Services/Notch/NotchLockScreenSupport.swift Sources/Vorssaint/Services/AgentUsage/AgentUsageModels.swift @@ -332,6 +334,8 @@ if (( TEST )); then Sources/Vorssaint/UI/Notch/NotchEqualizerBars.swift Sources/Vorssaint/UI/Notch/NotchScrollEdgeFade.swift Sources/Vorssaint/UI/Notch/NotchAgentAnimationView.swift + Sources/Vorssaint/UI/Notch/NotchClawdSprite.swift + Sources/Vorssaint/UI/Notch/NotchClawdView.swift Sources/Vorssaint/UI/WindowVisibilityReader.swift Sources/Vorssaint/Services/Notch/NotchMusicAutomationSupport.swift Sources/Vorssaint/Services/Notch/NotchMusicAutomation.swift From d333c373b5b9f7d66ce89c972e945aa3606faf05 Mon Sep 17 00:00:00 2001 From: Dawid Buszta <344369893+MF-DEEV@users.noreply.github.com> Date: Thu, 22 Oct 2026 18:36:54 +0200 Subject: [PATCH 2/6] fix(sessions): keep the dressed clawd inside its card and describe what clawds read The wardrobe fits the whole canvas in its card, so a cup held out or the highest jump no longer spills over the top row. The session page leaves room for a tall hat to hop. Privacy and permission notes say that outfits are kept by session id and that agent colors come from the head of agent definitions, read in guarded folders only with Full Disk Access. --- README.md | 2 +- .../Core/NotchClaudeSessionStrings.swift | 2 +- .../Notch/NotchClaudeSessionDetailView.swift | 2 ++ .../UI/Notch/NotchClawdWardrobeView.swift | 20 +++++++++++++------ docs/PERMISSIONS.md | 6 +++--- docs/PRIVACY.md | 2 +- 6 files changed, 22 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index f044bf4ed..d8ac8950c 100644 --- a/README.md +++ b/README.md @@ -135,7 +135,7 @@ Reorder or hide panel sections, choose a compact layout, and export settings to - **Dynamic Island.** Keep music, notifications, calendars, timers, downloads and everyday controls around the camera cutout, or a simulated one on other Macs. Customize sections and shortcuts, with optional lyrics, a live equalizer, camera preview and file tools. - **AI agents.** Follow Claude, Codex, OpenCode and GitHub Copilot in the Dynamic Island: plan limits and when they reset where available, tokens, API value, models, projects and live work, with a notice when a long task finishes. Codex's banked resets can be used from there too, and each extra Codex account (`CODEX_HOME`) can have a limits card of its own. Copilot uses local CLI/app session logs; its token totals update when shutdown metrics arrive, and aggregate API-value estimates use base rates. -- **Claude Code sessions.** See every Claude Code session running on your Mac in the Dynamic Island: its folder and branch, whether it works, runs a tool, waits on you or is done, its latest tools, tasks, subagents and cost. Answer its permission prompts with the whole command in view, pick an answer to the questions Claude asks, or write your own, jump to its Terminal tab or Antigravity window, and type a reply that reaches it as if typed there. Enlarge a session's page to read the whole conversation at a text size you pick and write a longer reply. Permission prompts and questions use opt-in Claude Code hooks; prompts and replies stay unread unless you turn on previews. +- **Claude Code sessions.** See every Claude Code session running on your Mac in the Dynamic Island: its folder and branch, whether it works, runs a tool, waits on you or is done, its latest tools, tasks, subagents and cost. Answer its permission prompts with the whole command in view, pick an answer to the questions Claude asks, or write your own, jump to its Terminal tab or Antigravity window, and type a reply that reaches it as if typed there. Enlarge a session's page to read the whole conversation at a text size you pick and write a longer reply. Each session and subagent shows a pixel Clawd in an outfit drawn at random, which you can change from the session's page. Permission prompts and questions use opt-in Claude Code hooks; prompts and replies stay unread unless you turn on previews. - **Command Bar.** Search apps, windows, files, clipboard history, snippets and app menu commands from one field. Calculate, convert units, find emoji or run saved scripts. - **Quick panel.** Open a floating palette of favorite tools with ⌃⌘V. - **Quick toggles.** Switch appearance, hide desktop icons, eject disks, empty the Trash, lock the screen and more. diff --git a/Sources/Vorssaint/Core/NotchClaudeSessionStrings.swift b/Sources/Vorssaint/Core/NotchClaudeSessionStrings.swift index cb90198a8..8bbd8ab27 100644 --- a/Sources/Vorssaint/Core/NotchClaudeSessionStrings.swift +++ b/Sources/Vorssaint/Core/NotchClaudeSessionStrings.swift @@ -230,7 +230,7 @@ extension NotchClaudeSessionStrings { dressUp: "Change outfit", dressUpFormat: "Change %@’s outfit", surpriseMe: "Surprise me", - ownOutfit: "Back to the first outfit", + ownOutfit: "Back to the original outfit", goToSession: "Go to it", shellTitle: "Shell", hatTitle: "Hat", diff --git a/Sources/Vorssaint/UI/Notch/NotchClaudeSessionDetailView.swift b/Sources/Vorssaint/UI/Notch/NotchClaudeSessionDetailView.swift index 0f48a160e..252ee264a 100644 --- a/Sources/Vorssaint/UI/Notch/NotchClaudeSessionDetailView.swift +++ b/Sources/Vorssaint/UI/Notch/NotchClaudeSessionDetailView.swift @@ -79,6 +79,8 @@ struct NotchClaudeSessionDetailView: View { private func header(now: Date) -> some View { HStack(spacing: 10) { NotchClawdDressButton(session: session, name: service.displayName(session), text: text) + // Room for a tall hat to hop in at the top of the scrolling page. + .padding(.top, 6) VStack(alignment: .leading, spacing: 2) { HStack(spacing: 6) { Text(text.phase(session.phase)) diff --git a/Sources/Vorssaint/UI/Notch/NotchClawdWardrobeView.swift b/Sources/Vorssaint/UI/Notch/NotchClawdWardrobeView.swift index 627b3e31a..94f659d9f 100644 --- a/Sources/Vorssaint/UI/Notch/NotchClawdWardrobeView.swift +++ b/Sources/Vorssaint/UI/Notch/NotchClawdWardrobeView.swift @@ -20,6 +20,7 @@ struct NotchClawdWardrobeView: View { private var dressedByHand: Bool { service.costumes[session.id] != nil } /// The stage grows with an enlarged island, up to a point. private var stageWidth: CGFloat { min(230, max(150, size.width * 0.3)) } + private var stageHeight: CGFloat { stageWidth * 0.92 } var body: some View { VStack(spacing: 8) { @@ -55,19 +56,26 @@ struct NotchClawdWardrobeView: View { // MARK: Stage private var stage: some View { - VStack(spacing: 8) { + // The whole canvas fits the card, so a tall hat, a raised arm, a cup + // held out and the highest jump all stay inside it. + let margin: CGFloat = 10 + let pixel = min((stageWidth - margin * 2) / CGFloat(NotchClawdSprite.width), + (stageHeight - margin * 2) / CGFloat(NotchClawdSprite.height)) + let figure = CGSize(width: pixel * CGFloat(NotchClawdSprite.frameColumns.count), + height: pixel * CGFloat(NotchClawdSprite.frameRows.count)) + return VStack(spacing: 8) { ZStack(alignment: .bottom) { // The floor it stands on, a soft light under its feet. Ellipse() .fill(.white.opacity(0.07)) - .frame(width: stageWidth * 0.62, height: 10) - .offset(y: -10) + .frame(width: figure.width * 0.9, height: pixel * 2) + .offset(y: pixel) NotchClawd(costume: costume, motion: NotchClaudeSessionsSupport.motion(session, now: Date()), seed: ClawdCostume.seed(session.id), cheer: changed ?? NotchClaudeSessionsSupport.cheer(session), - size: CGSize(width: stageWidth - 24, height: stageWidth * 0.78)) - .padding(.bottom, 14) + size: figure) } - .frame(width: stageWidth, height: stageWidth * 0.78 + 24) + .padding(.bottom, margin + pixel) + .frame(width: stageWidth, height: stageHeight, alignment: .bottom) .modifier(NotchControlSurface(cornerRadius: 18, interactive: false)) .accessibilityElement() .accessibilityLabel(outfit) diff --git a/docs/PERMISSIONS.md b/docs/PERMISSIONS.md index 5e2e3e442..26fc36ec8 100644 --- a/docs/PERMISSIONS.md +++ b/docs/PERMISSIONS.md @@ -15,7 +15,7 @@ You can review or change every grant in System Settings, under Privacy and Secur | Bluetooth | Yes | Accessory battery levels in Monitor, optional accessory alerts in the notch and Bluetooth on sleep | | Files and Folders | Yes | Monitoring downloads in a folder you choose | | Notifications | Yes | Keep awake, battery, Monitor and update alerts | -| Full Disk Access | Yes | A deeper uninstaller scan | +| Full Disk Access | Yes | A deeper uninstaller scan; agent colors from projects in protected folders | | Administrator (one time) | Yes | Password free closed lid toggling | | Automation | Yes | Finder actions, Homebrew Terminal handoff, replies to Claude Code sessions in Terminal and supported music playback controls | | App Management | Yes | App installs, updates and removal | @@ -129,9 +129,9 @@ Download monitoring watches only the folder you choose in the system picker. Fol **Why it comes up.** The uninstaller hunts down the files an app leaves behind, like caches, preferences and logs. Some of those spots are protected by macOS and only open up with Full Disk Access. -**What uses it.** The uninstaller, for a deeper scan. +**What uses it.** The uninstaller, for a deeper scan. When it is already granted, Dynamic Island Sessions also looks for agent definitions inside projects in protected folders such as Desktop or Documents, to give a subagent's Clawd its agent's color. It never asks for the permission. -**If you say no.** The uninstaller still works and scans the places it can reach. It just might not surface files tucked away in protected folders. +**If you say no.** The uninstaller still works and scans the places it can reach. It just might not surface files tucked away in protected folders. A subagent from a project in a protected folder keeps the color its Clawd drew at random. **Optional.** Yes. There is no pop up for Full Disk Access. You add Vorssaint in System Settings, under Privacy and Security, Full Disk Access, and Vorssaint opens that pane for you when the feature calls for it. diff --git a/docs/PRIVACY.md b/docs/PRIVACY.md index b7e4aca43..7f27df9e6 100644 --- a/docs/PRIVACY.md +++ b/docs/PRIVACY.md @@ -39,7 +39,7 @@ The live equalizer is off until you turn it on. When on, it reads the audio outp On new setups, AI Agents stays off until you enable it. Updates preserve your existing setting. While it is on, it reads the session logs Claude Code and Codex already keep in your home folder, under `~/.claude/projects` (or `~/.config/claude/projects`) and `~/.codex`, where they are, as they grow, the event log GitHub Copilot keeps for each session under `~/.copilot/session-state`, and the OpenCode database at `~/.local/share/opencode/opencode.db` and its write-ahead log, opened read-only whether or not OpenCode is running and from thirteen weeks back at most. Only token counts, model names, times, session identifiers, recorded costs and the name of the folder each agent worked in are taken from them; prompts, replies, tool output and files are never decoded into anything that is kept. From OpenCode's database the query itself takes out only those values, with each message's role, how it ended and whether it failed, and of the parts that hold its message content only each part's type and state are checked, inside the query, so that content never reaches the app. The plan name comes from the account profile Claude Code caches in `~/.claude.json`, which is parsed in memory and of which only the plan fields and the organization it signs in to are kept. While a Claude Code task shows as working, the section also looks at the small records Claude Code keeps in `~/.claude/sessions` for each running session, and reads only the process and the session each one belongs to, to tell when that session has ended. The section also asks macOS whether the Mac is online, which sends nothing, so a Claude Code task that cannot reach its server stops showing as working once the Mac has been offline for about 20 seconds. A task waiting on a shell command keeps showing, so the identifier Claude Code gives each shell command still running is held in memory until its result appears, and is never saved. Claude's plan limits come from Claude Code when it can check them, as the network list below describes, and otherwise from the history the Claude app keeps in `~/Library/Application Support/Claude/plan-usage-history.json`, of which only the time, the account each reading belongs to and the percentage used of each window are kept. Vorssaint itself never uses a sign-in, keychain item or token. With Claude turned on, the section's settings also read that history to show when the Claude app last saved its limits, even before the section is turned on, and keep only that time. An agent turned off in the section's settings is not read at all. Those values are held in memory and kept while the display sleeps or the Mac is locked. So that a launch reads only what the agents wrote since, they are also saved to a file in the app's cache folder that only your account can read, with the path of each log, how far it was read and a checksum that tells when it changed. Those paths include your home folder and, for Claude Code, the full path of the folder each session worked in, since Claude Code names its log folders after it. Nothing from OpenCode's database goes into that file. What it gives stays in memory only, and the database is read again at each launch. Time Machine leaves the cache folder out of backups. An app update or a damaged file sets the saved file aside and the logs are read from their start again. Turning the section off drops what is in memory and deletes that file. Costs are computed on your Mac from a public price list that ships with the app and can be kept current, as described below. For an OpenCode model that list does not price, the cost OpenCode recorded is shown. -The Sessions page is off until you turn it on, and it rides on AI Agents being installed. While it is on, it reads the small records Claude Code keeps in `~/.claude/sessions` (or `~/.config/claude/sessions`) for each running session: the process, the session, the folder it works in, its name and whether it is busy or waiting on you. It checks that each record's process is the one that wrote it, then reads the new lines of that session's transcript under `~/.claude/projects`, its subagents' transcripts and the small description Claude Code keeps beside each, and the task list Claude Code keeps under `~/.claude/tasks`. From these it keeps, in memory only, times, tool names and the identifiers of tool calls, the git branch, the model, token counts and the cost computed as AI Agents computes it, how many tasks are done, and each subagent's type. Prompts, replies, titles, tool arguments, task names and what subagents were asked are not decoded unless you turn on Show previews, which is off by default; with it on they are kept in memory only, shortened (the conversation an enlarged page shows keeps a session's latest 150 prompts and replies), and cleared as soon as you turn it off. To tell which app shows a session, Vorssaint reads that session's terminal device and two variables of its environment, the bundle identifier of the app that started it and the port of the IDE connection, and keeps nothing else from that environment. For a session in Antigravity it also reads the folders the IDE's lock file under `~/.claude/ide` says that window has open, to bring the right window forward. Nothing the page reads is saved or sent. An image you paste or drop into a reply is used where it lies when it is a PNG, JPEG, GIF or WebP file; any other image is saved as a PNG in a folder of the app's own under the system's temporary folder, readable only by your account, so Claude Code can read it, and copies a day old are deleted. When an Antigravity window still runs an extension from before images, until it reloads, the reply names each image's file instead, and a copy goes into the folder Claude Code keeps for that session under `/private/tmp/claude-/`, where Claude reads it without asking. The app keeps an extension you added current by itself. +The Sessions page is off until you turn it on, and it rides on AI Agents being installed. While it is on, it reads the small records Claude Code keeps in `~/.claude/sessions` (or `~/.config/claude/sessions`) for each running session: the process, the session, the folder it works in, its name and whether it is busy or waiting on you. It checks that each record's process is the one that wrote it, then reads the new lines of that session's transcript under `~/.claude/projects`, its subagents' transcripts and the small description Claude Code keeps beside each, and the task list Claude Code keeps under `~/.claude/tasks`. From these it keeps, in memory only, times, tool names and the identifiers of tool calls, the git branch, the model, token counts and the cost computed as AI Agents computes it, how many tasks are done, and each subagent's type. Prompts, replies, titles, tool arguments, task names and what subagents were asked are not decoded unless you turn on Show previews, which is off by default; with it on they are kept in memory only, shortened (the conversation an enlarged page shows keeps a session's latest 150 prompts and replies), and cleared as soon as you turn it off. To tell which app shows a session, Vorssaint reads that session's terminal device and two variables of its environment, the bundle identifier of the app that started it and the port of the IDE connection, and keeps nothing else from that environment. For a session in Antigravity it also reads the folders the IDE's lock file under `~/.claude/ide` says that window has open, to bring the right window forward. To give a subagent's Clawd the color Claude Code gives that agent, it reads the first few kilobytes of the agent definitions in `~/.claude/agents`, in `.claude/agents` of the session's folder and the folders above it, and in the plugins `~/.claude/plugins/installed_plugins.json` lists, and keeps only each agent's name and color, in memory. A project under Desktop, Documents, Downloads, iCloud Drive or an external volume is looked in only when Vorssaint has Full Disk Access, so macOS never asks on its behalf. Nothing the page reads is sent. The names you give sessions and the outfits you choose for their Clawds are saved in the app's preferences by session id; they stay out of settings backups and go when the app is uninstalled. An image you paste or drop into a reply is used where it lies when it is a PNG, JPEG, GIF or WebP file; any other image is saved as a PNG in a folder of the app's own under the system's temporary folder, readable only by your account, so Claude Code can read it, and copies a day old are deleted. When an Antigravity window still runs an extension from before images, until it reloads, the reply names each image's file instead, and a copy goes into the folder Claude Code keeps for that session under `/private/tmp/claude-/`, where Claude reads it without asking. The app keeps an extension you added current by itself. Permission prompts and live tool activity reach the page through Claude Code hooks, which are added only when you press Install Hooks. They go into `~/.claude/settings.json` next to your own entries, marked as Vorssaint's, after the file is copied aside as `settings.json.vorssaint-