SPB Git

Repository Public

DesignTests.swift 17.1 KB 380 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Claude Remote / Codex Remote9// File             : Packages/ClaudeRemoteKit/Tests/DesignTests/DesignTests.swift10// Module           : DesignTests11// Repository       : https://git.spboucher.ai/claude-remote-apple12// Project Website  : https://claude.spboucher.ai13// Created          : 2026-11-2914// Last Modified    : 2026-11-2915//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author           : Simon-Pierre Boucher21// Position         : Professor of Finance22// Institution      : Université du Québec en Outaouais (UQO)23// Department       : Département des sciences administratives24// Organization     : SP Boucher25//26// Website          : https://spboucher.ai27// Git              : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General          : info@spboucher.ai34// Professional     : contact@spboucher.ai35// Direct           : simon@spboucher.ai36// Research         : research@spboucher.ai37// Development      : dev@spboucher.ai38// Support          : support@spboucher.ai39// Security/Admin   : admin@spboucher.ai40// Notifications    : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification   : Public67// Distribution     : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License          : None specified (no license file in this repository)81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import ClaudeRemoteDesign89import ClaudeRemoteModels90import Foundation91import SwiftUI92import Testing93#if canImport(AppKit)94import AppKit95#endif9697private func allStyles() -> [(String, StatusStyle)] {98    var out: [(String, StatusStyle)] = []99    out += SessionState.allCases.map { ("SessionState.\($0.rawValue)", $0.statusStyle) }100    out += TaskState.allCases.map { ("TaskState.\($0.rawValue)", $0.statusStyle) }101    out += Health.allCases.map { ("Health.\($0.rawValue)", $0.statusStyle) }102    out += ClusterAppState.allCases.map { ("ClusterAppState.\($0.rawValue)", $0.statusStyle) }103    out += IncidentSeverity.allCases.map { ("IncidentSeverity.\($0.rawValue)", $0.statusStyle) }104    out += McpStatus.allCases.map { ("McpStatus.\($0.rawValue)", $0.statusStyle) }105    out += NotificationKind.allCases.map { ("NotificationKind.\($0.rawValue)", $0.statusStyle) }106    out += DeviceKind.allCases.map { ("DeviceKind.\($0.rawValue)", $0.statusStyle) }107    out.append(("SessionState.unknown", SessionState.unknown("BRAND_NEW").statusStyle))108    out.append(("Health.UNKNOWN", Health.unknownHealth.statusStyle))109    return out110}111112@Suite("Status styles")113struct StatusStyleTests {114    @Test func everyKnownCaseHasLabelAndSymbol() {115        let styles = allStyles()116        #expect(styles.count > 40)117        for (name, style) in styles {118            #expect(!style.label.isEmpty, "\(name) has no label")119            #expect(!style.symbolName.isEmpty, "\(name) has no symbol")120        }121    }122123    @Test func knownCaseCountsMatchTheWireEnums() {124        #expect(SessionState.allCases.count == 9)125        #expect(TaskState.allCases.count == 8)126        #expect(Health.allCases.count == 3)127        #expect(NotificationKind.allCases.count == 7)128        #expect(McpStatus.allCases.count == 4)129    }130131    @Test func unknownValuesFallBackToNeutral() {132        let s = SessionState.unknown("HIBERNATING_NOW").statusStyle133        #expect(s.label == "Hibernating now")134        #expect(s.tone == .neutral)135        #expect(s.symbolName == "questionmark.circle")136        #expect(TaskState.unknown("x").statusStyle.tone == .neutral)137        #expect(McpStatus.unknown("weird").statusStyle.tone == .neutral)138        #expect(NotificationKind.unknown("backup.done").statusStyle.label == "Backup done")139        #expect(StatusStyle.unknown("").label == "Unknown")140    }141142    @Test func toneMappingOfKeyStates() {143        #expect(SessionState.waitingForInput.statusStyle.tone == .warning)144        #expect(SessionState.failed.statusStyle.tone == .error)145        #expect(SessionState.running.statusStyle.tone == .success)146        #expect(SessionState.recoverable.statusStyle.tone == .warning)147        #expect(SessionState.stopped.statusStyle.tone == .neutral)148        #expect(TaskState.failed.statusStyle.tone == .error)149        #expect(TaskState.timedOut.statusStyle.tone == .error)150        #expect(TaskState.succeeded.statusStyle.tone == .success)151        #expect(Health.online.statusStyle.tone == .success)152        #expect(Health.offline.statusStyle.tone == .error)153        #expect(Health.degraded.statusStyle.tone == .warning)154        // Stale / unknown data must never look healthy.155        #expect(Health.unknownHealth.statusStyle.tone == .neutral)156        #expect(Health.unknownHealth.statusStyle.label == "Unknown")157        #expect(McpStatus.notChecked.statusStyle.tone == .neutral)158        #expect(ClusterAppState.down.statusStyle.tone == .error)159        #expect(IncidentSeverity.critical.statusStyle.tone == .error)160        #expect(NotificationKind.sessionWaiting.statusStyle.tone == .warning)161    }162163    @Test func sessionKindPresentation() {164        #expect(SessionKind.agent.label(profile: .claude) == "Claude")165        #expect(SessionKind.agent.label(profile: .codex) == "Codex")166        #expect(SessionKind.shell.label(profile: .codex) == "Shell")167        #expect(SessionKind.shell.symbolName(profile: .claude) == "terminal")168        #expect(SessionKind.agent.symbolName(profile: .codex) == AgentProfile.codex.symbolName)169    }170171    @Test func connectionIndicatorStatuses() {172        typealias S = ConnectionIndicator.Status173        #expect(S.online(latencyMs: 23).detail == "23 ms")174        #expect(S.online(latencyMs: nil).detail == nil)175        #expect(S.online(latencyMs: 23).accessibilityText == "Online, latency 23 ms")176        #expect(S.reconnecting(attempt: 3, nextRetry: nil).label == "Reconnecting (attempt 3)")177        #expect(S.reconnecting(attempt: 1, nextRetry: nil).label == "Reconnecting")178        #expect(S.offline.tone == .error)179        #expect(S.unauthorized.tone == .error)180        #expect(S.online(latencyMs: 1).tone == .success)181        #expect(S.connecting.tone == .info)182    }183184    #if canImport(AppKit)185    @Test func everySymbolExists() {186        var names = Set(allStyles().map(\.1.symbolName))187        typealias S = ConnectionIndicator.Status188        for s in [S.online(latencyMs: nil), .connecting, .reconnecting(attempt: 1, nextRetry: nil), .offline, .unauthorized] {189            names.insert(s.symbolName)190        }191        names.formUnion([AgentProfile.claude.symbolName, AgentProfile.codex.symbolName, "tray", "exclamationmark.triangle.fill",192                         "arrow.up.right", "arrow.down.right", "arrow.right", "questionmark.square.dashed"])193        for name in names {194            #expect(NSImage(systemSymbolName: name, accessibilityDescription: nil) != nil, "missing SF Symbol \(name)")195        }196    }197    #endif198}199200@Suite("Palette and theme")201struct PaletteTests {202    @Test(arguments: [AgentProfile.claude, AgentProfile.codex])203    func textTokensMeetAAOnAppSurfaces(profile: AgentProfile) {204        let theme = CRTheme(profile: profile)205        let texts: [(String, CRColorToken)] = [206            ("text", CRPalette.text), ("text2", CRPalette.text2), ("muted", CRPalette.muted), ("accent", theme.accent),207            ("success", CRPalette.success), ("warning", CRPalette.warning), ("error", CRPalette.error), ("info", CRPalette.info),208            ("warmInk", theme.warmInk),209        ]210        let grounds: [(String, CRColorToken)] = [("bg", CRPalette.bg), ("surface", CRPalette.surface)]211        for scheme in [ColorScheme.light, .dark] {212            for (tn, t) in texts {213                for (gn, g) in grounds {214                    let ratio = t.hex(scheme).contrast(with: g.hex(scheme))215                    #expect(ratio >= 4.5, "\(profile.id.rawValue) \(scheme) \(tn) on \(gn): \(ratio)")216                }217            }218            let onAccent = theme.onAccent.hex(scheme).contrast(with: theme.accent.hex(scheme))219            #expect(onAccent >= 4.5, "\(profile.id.rawValue) \(scheme) onAccent: \(onAccent)")220        }221        #expect(HexColor(0xFFFFFF).contrast(with: theme.ink) >= 7)222    }223224    @Test func themeIsBuiltFromTheProfile() {225        let claude = CRTheme(profile: .claude), codex = CRTheme(profile: .codex)226        #expect(claude.accent.light == HexColor(0x5151E8))227        #expect(claude.accent.dark == HexColor(0x8F8FFF))228        #expect(codex.accent.light == HexColor(0x0B7268))229        #expect(codex.accent.dark == HexColor(0x2DD4BF))230        #expect(claude.gradientStops.count == 3)231        #expect(claude != codex)232        #expect(CRTheme.claude == claude)233        #expect(codex.productName == "Codex Remote")234    }235236    @Test func webTokens() {237        #expect(CRPalette.bg.light.hexString == "#F7F6F3")238        #expect(CRPalette.bg.dark.hexString == "#080B10")239        #expect(CRPalette.surface.dark.hexString == "#10151D")240        #expect(CRPalette.terminalBackground.light.hexString == "#FCFCFA")241        #expect(CRPalette.line.light.alpha < 0.1)242        #expect(CRPalette.bg.hex(.dark) == CRPalette.bg.dark)243        #expect(CRRadius.sm == 10 && CRRadius.md == 16 && CRRadius.lg == 22)244    }245246    #if canImport(AppKit)247    @Test func hexBridging() throws {248        let c = try #require(NSColor(Color(hex: 0x336699)).usingColorSpace(.sRGB))249        #expect(abs(c.redComponent - 0x33 / 255.0) < 0.005)250        #expect(abs(c.greenComponent - 0x66 / 255.0) < 0.005)251        #expect(abs(c.blueComponent - 0x99 / 255.0) < 0.005)252        let a = try #require(NSColor(Color(HexColor(0x000000, alpha: 0.5))).usingColorSpace(.sRGB))253        #expect(abs(a.alphaComponent - 0.5) < 0.005)254        // Dynamic colour resolves per appearance.255        let dyn = NSColor(CRPalette.bg.color)256        var resolved: [NSAppearance.Name: NSColor] = [:]257        for name in [NSAppearance.Name.aqua, .darkAqua] {258            NSAppearance(named: name)?.performAsCurrentDrawingAppearance {259                resolved[name] = dyn.usingColorSpace(.sRGB)260            }261        }262        let light = try #require(resolved[.aqua]), dark = try #require(resolved[.darkAqua])263        #expect(abs(light.redComponent - 0xF7 / 255.0) < 0.01)264        #expect(abs(dark.redComponent - 0x08 / 255.0) < 0.01)265    }266    #endif267}268269@Suite("Tokens, motion, formatters")270struct TokenTests {271    @Test func reduceMotionDisablesEveryAnimation() {272        for kind in CRMotion.Kind.allCases {273            #expect(CRMotion.animation(kind, reduceMotion: true) == nil)274            #expect(CRMotion.animation(kind, reduceMotion: false) != nil)275        }276        #expect(Animation.crStandard(reduceMotion: true) == nil)277        #expect(Animation.crQuick(reduceMotion: true) == nil)278        #expect(Animation.crSpring(reduceMotion: true) == nil)279        #expect(Animation.crStandard(reduceMotion: false) != nil)280    }281282    @Test func terminalFontResolution() {283        #expect(CRTypography.terminalFontCandidates.first == "JetBrains Mono")284        #expect(!CRTypography.isFontAvailable(""))285        #expect(!CRTypography.isFontAvailable("No Such Font 12345"))286        #expect(CRTypography.isFontAvailable("Menlo"))287        #expect(CRTypography.resolvedTerminalFontName(preferred: "No Such Font 12345") != nil) // Menlo at least288        #expect(CRTypography.resolvedTerminalFontName(preferred: "Menlo") == "Menlo")289        #expect(CRTypography.terminalPlatformFont(size: 13, preferred: "No Such Font 12345").pointSize == 13)290    }291292    @Test func bytes() {293        #expect(CRFormat.bytes(nil) == "—")294        #expect(CRFormat.bytes(0) == "0 B")295        #expect(CRFormat.bytes(1023) == "1023 B")296        #expect(CRFormat.bytes(1536) == "1.5 KB")297        #expect(CRFormat.bytes(5 * 1024 * 1024) == "5.0 MB")298        #expect(CRFormat.bytes(200 * 1024 * 1024 * 1024) == "200 GB")299        #expect(CRFormat.megabytes(1536) == "1.5 GB")300    }301302    @Test func durations() {303        #expect(CRFormat.duration(nil) == "—")304        #expect(CRFormat.duration(45) == "45s")305        #expect(CRFormat.duration(185) == "3m 05s")306        #expect(CRFormat.duration(3720) == "1h 02m")307        #expect(CRFormat.duration(2 * 86400 + 4 * 3600 + 5) == "2d 4h")308        #expect(CRFormat.duration(-3) == "0s")309    }310311    @Test func percentLatencyCount() {312        #expect(CRFormat.percent(nil) == "—")313        #expect(CRFormat.percent(42.4) == "42%")314        #expect(CRFormat.percent(42.44, decimals: 1) == "42.4%")315        #expect(CRFormat.latency(ms: nil) == "—")316        #expect(CRFormat.latency(ms: 23.4) == "23 ms")317        #expect(CRFormat.latency(ms: 1234) == "1.2 s")318        #expect(CRFormat.count(999) == "999")319        #expect(CRFormat.count(1234) == "1.2k")320        #expect(CRFormat.count(2_500_000) == "2.5M")321        #expect(CRFormat.count(nil) == "—")322    }323324    @Test func relativeTime() {325        let now = Date(timeIntervalSince1970: 1_800_000_000)326        #expect(CRFormat.relative(now.addingTimeInterval(-10), now: now) == "now")327        #expect(CRFormat.relative(now.addingTimeInterval(-300), now: now) == "5m ago")328        #expect(CRFormat.relative(now.addingTimeInterval(-7200), now: now) == "2h ago")329        #expect(CRFormat.relative(now.addingTimeInterval(-3 * 86400), now: now) == "3d ago")330        #expect(CRFormat.relative(now.addingTimeInterval(600), now: now) == "in 10m")331        #expect(!CRFormat.relative(now.addingTimeInterval(-90 * 86400), now: now).contains("ago"))332    }333334    @Test func progressBarTones() {335        #expect(ProgressBar.tone(for: nil) == .neutral)336        #expect(ProgressBar.tone(for: 0.2) == .accent)337        #expect(ProgressBar.tone(for: 0.8) == .warning)338        #expect(ProgressBar.tone(for: 0.95) == .error)339        #expect(ProgressBar.tone(for: 0.5, warningAt: 0.4, criticalAt: 0.6) == .warning)340    }341342    @Test func tonesHaveColours() {343        for tone in StatusTone.allCases where tone != .accent {344            #expect(tone.textToken != nil)345            #expect(tone.fillToken != nil)346        }347        #expect(StatusTone.accent.textToken == nil)348    }349350    @MainActor @Test func hapticsAreSafeToCallEverywhere() {351        Haptics.isEnabled = true352        Haptics.impact()353        Haptics.selection()354        Haptics.success()355        Haptics.warning()356        Haptics.error()357    }358359    @MainActor @Test func componentsCanBeConstructed() {360        // Smoke test: the view values build on this platform (bodies are evaluated by SwiftUI at run time).361        _ = StatusPill(SessionState.running)362        _ = StatusPill(TaskState.failed, compact: true)363        _ = HealthDot(.online)364        _ = ConnectionIndicator(.online(latencyMs: 12))365        _ = StatTile("Live sessions", value: "3", trend: .up("+1"), symbolName: "terminal", tone: .accent)366        _ = SectionCard("Cluster") { Text("x") }367        _ = EmptyStateView("No sessions")368        _ = LoadingStateView("Loading")369        _ = ErrorStateView(message: "offline") {}370        _ = SkeletonBlock()371        _ = RelativeTimeText(Date())372        _ = KeyValueRow("Host", value: nil)373        _ = TagChip("local")374        _ = ProgressBar(value: 0.4)375        _ = AgentMark()376        _ = Button("Go") {}.buttonStyle(.crPrimary)377        _ = Text("x").crTheme(.codex).crCard().crPanel().crSkeleton(active: true).crAnimation(value: 1)378    }379}380
Files main
Menu

Theme