Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Sources/CodeCaps/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -537,7 +537,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe
button.title = " \(title)"
}

button.toolTip = "CodeCaps · \(detail)"
button.toolTip = "CodeCaps · \(detail) — right-click for commands"
button.setAccessibilityLabel("CodeCaps, \(detail)")
}

Expand Down
7 changes: 3 additions & 4 deletions Sources/CodeCaps/BrandMark.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,9 @@ import SwiftUI
/// show the real mark instead of a stand-in.
///
/// The menu bar keeps the owner's own black template icon, which is what that
/// artwork is for and where it belongs. The PiP widget header and the Glance
/// popover header keep that same black template on purpose, so the template
/// mark still appears in the menu bar and in those two headers, and nowhere
/// else.
/// artwork is for and where it belongs. The Glance popover header shows the
/// colour mark on its light ground (see `GlanceBrandMark`), so the template
/// mark itself appears only in the menu bar.
public enum BrandMarkImage {
/// The mark, loaded once. The asset is a required, bundled resource:
/// `BrandAssetTests` fails the test suite, and so CI, if the bundle ever
Expand Down
14 changes: 13 additions & 1 deletion Sources/CodeCaps/ConsoleViews.swift
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ struct ConsoleView: View {
.accessibilityHidden(true)
}
if let unavailable = state.unavailableAlert {
Text("Alert source unavailable: \(unavailable.providerKey)\(unavailable.windowId.map { " · \($0)" } ?? ""). Check Sources & Fleet for this provider.")
Text("Alert source unavailable: \(unavailable.providerKey)\(unavailable.windowId.map { " · \($0)" } ?? "").\(sentenceGap)Check Sources & Fleet for this provider.")
.font(.callout)
.foregroundStyle(Theme.warning)
.padding(.horizontal, Metrics.pagePadding)
Expand Down Expand Up @@ -448,6 +448,10 @@ private struct ConsoleSidebarSplitter: View {
@State private var isHovering = false
@State private var dragStart: CGFloat?

private func persistWidth() {
UserDefaults.standard.set(Double(width), forKey: "consoleSidebarWidth")
}

var body: some View {
ZStack {
Rectangle()
Expand Down Expand Up @@ -488,6 +492,14 @@ private struct ConsoleSidebarSplitter: View {
// owner picked, so the grabber glowed system blue next to an accent
// that was doing everything else in the sidebar.
.background(isHovering ? Theme.accent.opacity(0.15) : Color.clear)
// The drag is pointer-only, so the same resize is offered to the
// keyboard: focus the splitter and use the arrow keys.
.focusable()
.onKeyPress(.leftArrow) { width = max(Metrics.sidebarWidthMin, width - 8); persistWidth(); return .handled }
.onKeyPress(.rightArrow) { width = min(Metrics.sidebarWidthMax, width + 8); persistWidth(); return .handled }
.accessibilityLabel("Sidebar width")
.accessibilityValue("\(Int(width)) points")
.accessibilityHint("Use the left and right arrow keys to resize the sidebar")
}
}

Expand Down
7 changes: 7 additions & 0 deletions Sources/CodeCaps/ExhaustionPopupView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,13 @@ final class ExhaustionPopupController {

private func scheduleExpiry(for id: UUID) {
expireTask?.cancel()
// A warning that vanishes on a timer can disappear before a
// VoiceOver or Reduce Motion user has read it; for them it stays
// until dismissed.
if NSWorkspace.shared.isVoiceOverEnabled || NSWorkspace.shared.accessibilityDisplayShouldReduceMotion {
expireTask = nil
return
}
expireTask = Task { @MainActor [weak self] in
try? await Task.sleep(nanoseconds: UInt64(Self.autoExpire * 1_000_000_000))
guard !Task.isCancelled, let self, self.shownId == id else { return }
Expand Down
6 changes: 3 additions & 3 deletions Sources/CodeCaps/GlanceViews.swift
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@ struct GlancePopover: View {
Text("Open CodeCaps")
Text("⌘1")
.font(.caption2.weight(.medium))
.foregroundStyle(colorScheme == .dark ? Color.black.opacity(0.55) : Color.white.opacity(0.75))
.foregroundStyle(Theme.onAccent.opacity(0.75))
}
}
.buttonStyle(GlanceFooterProminentButtonStyle(model: model))
Expand Down Expand Up @@ -1943,10 +1943,10 @@ struct GlanceMeterColumns: View {
} else if let gap, !gap.isEmpty {
Text(gap)
.font(.caption2)
.foregroundStyle(Theme.ink.opacity(0.62))
.foregroundStyle(.secondary)
.multilineTextAlignment(.leading)
.lineLimit(3)
.minimumScaleFactor(0.7)
.minimumScaleFactor(0.85)
.frame(width: Metrics.glanceMeterWidth, alignment: .leading)
.accessibilityLabel(gap)
} else {
Expand Down
38 changes: 33 additions & 5 deletions Sources/CodeCaps/MonitorModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1351,18 +1351,30 @@ final class MonitorModel: ObservableObject {
}

func setOptionalQuotaReaderEnabled(_ enabled: Bool, readerID: String) {
guard LocalQuotaReaderRegistry.builtIn.optionalRegistrations.contains(where: { $0.id == readerID }),
// Consult a freshly configured registry, not the launch-time
// `builtIn` snapshot, so a plugin file dropped into the Plugins
// folder can be toggled without relaunching the app. Building the
// registry only creates factory closures; none is invoked here.
let live = LocalQuotaReaderRegistry.configured(
zCodeCredentialProvider: { nil }, mimoCredentialProvider: { nil },
pluginDescriptors: EndpointPluginLoader.loadCached())
guard live.optionalRegistrations.contains(where: { $0.id == readerID }),
optionalQuotaReaderPreferences.isEnabled(readerID) != enabled else { return }
var preferences = optionalQuotaReaderPreferences
preferences.setEnabled(enabled, for: readerID)
optionalQuotaReaderPreferences = preferences
preferences.save(to: defaults)
invalidateRefresh()
if !enabled, let providerResult {
// Built-in optional readers use their provider key as their id;
// a plugin's id is `plugin:<slug>` while its windows carry its
// own provider key, so resolve the key before purging.
let providerKey = live.optionalRegistrations
.first { $0.id == readerID }?.configurationMetadata["providerKey"] ?? readerID
self.providerResult = LocalQuotaResult(
windows: providerResult.windows.filter { $0.canonicalProviderKey != readerID },
issues: providerResult.issues.filter { $0.key != readerID },
consentNeeded: providerResult.consentNeeded.subtracting([readerID]))
windows: providerResult.windows.filter { $0.canonicalProviderKey != providerKey },
issues: providerResult.issues.filter { $0.key != providerKey },
consentNeeded: providerResult.consentNeeded.subtracting([providerKey]))
rebuildLocalState(recordSamples: false)
}
if providerChecksEnabled || serverEnabled { refreshProviderChecks() }
Expand Down Expand Up @@ -3374,14 +3386,30 @@ final class MonitorModel: ObservableObject {
})
}

/// How long one snapshot write waits for its predecessor before giving
/// up. The write itself is a bounded file replace; only a stuck disk
/// can hold a link this long.
static let snapshotWritePredecessorTimeout: Duration = .seconds(10)

/// Runs `work` on a background executor after every previously enqueued
/// write, then reports success back on the main actor.
func enqueueSnapshotWrite(_ work: @escaping @Sendable () throws -> Void,
completion: @escaping @MainActor @Sendable (Bool) -> Void) {
guard !snapshotWritesClosedForTermination else { return }
let previous = snapshotWriteChain
snapshotWriteChain = Task.detached(priority: .utility) {
await previous?.value
// A predecessor stuck on a disk write must not stall every later
// handoff and widget write indefinitely while the stale file
// still looks current. Wait with a deadline: on timeout this
// link reports failure (which surfaces as the handoff/widget
// error) and completes, so the chain behind it moves again. The
// skipped write is superseded by the next refresh's snapshot.
let predecessorFinished = await SnapshotWriteDrain.wait(
for: previous, timeout: Self.snapshotWritePredecessorTimeout)
guard predecessorFinished else {
await completion(false)
return
}
let succeeded: Bool
do { try work(); succeeded = true } catch { succeeded = false }
await completion(succeeded)
Expand Down
17 changes: 11 additions & 6 deletions Sources/CodeCaps/PipWidget.swift
Original file line number Diff line number Diff line change
Expand Up @@ -960,11 +960,12 @@ struct PipWidgetView: View {
// MARK: Header

/// Close, or Back when a platform detail is open. It floats over the
/// rows' top-right corner and appears only on hover, so it never occupies
/// permanent space above the numbers.
/// rows' top-right corner and appears on hover, so it never occupies
/// permanent space above the numbers. VoiceOver users get it
/// permanently: hover is not a discovery path they can use.
@ViewBuilder
private var floatingControl: some View {
if isHovering {
if isHovering || NSWorkspace.shared.isVoiceOverEnabled {
if detailRow == nil {
HStack(spacing: 5) {
settingsButton
Expand Down Expand Up @@ -1099,7 +1100,7 @@ struct PipWidgetView: View {
// Say so, rather than letting a pinned row look absent. It
// sits under the scroll view so it never scrolls away itself.
Text("\(targetRows.count - max(1, visible)) more pinned — scroll")
.font(.system(size: 9, weight: .medium))
.font(.system(size: 10, weight: .medium))
.foregroundStyle(background.countdownInk)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, PipMetrics.padding)
Expand Down Expand Up @@ -1233,6 +1234,10 @@ struct PipWidgetView: View {
.frame(maxWidth: .infinity, alignment: .leading)
.contentShape(Rectangle())
.onTapGesture { detailRowId = row.id }
// Keyboard activation for the same action the tap performs, so the
// row is reachable and operable without a pointer.
.focusable()
.onKeyPress(.return) { detailRowId = row.id; return .handled }
.help(row.title)
.accessibilityLabel("\(row.title) — open details")
.accessibilityAddTraits(.isButton)
Expand Down Expand Up @@ -1277,7 +1282,7 @@ struct PipWidgetView: View {
Spacer(minLength: 0)
if row.section.expected, row.section.windows.isEmpty {
Text("No readings published")
.font(.system(size: 9, weight: .semibold))
.font(.system(size: 10, weight: .semibold))
.foregroundStyle(Theme.warning)
.lineLimit(1)
}
Expand Down Expand Up @@ -1335,7 +1340,7 @@ struct PipWidgetView: View {

return HStack(spacing: PipMetrics.meterSpacing) {
Text(cadenceCaption)
.font(.system(size: 9, weight: .bold))
.font(.system(size: 10, weight: .bold))
.foregroundStyle(background.countdownInk)
.frame(width: PipMetrics.cadenceWidth, alignment: .leading)

Expand Down
6 changes: 3 additions & 3 deletions Sources/CodeCaps/RunawayAlertsView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@ struct RunawayAlertsPage: View {

private var calibrationDescription: String {
if summary.days >= 7.0 {
return "Fully calibrated. Evaluates current burn against your 7-day rolling average and worst peak hour."
return "Fully calibrated." + sentenceGap + "Evaluates current burn against your 7-day rolling average and worst peak hour."
} else if summary.days >= 0.2 {
return "Calibrated for peak alerts. Collecting additional readings to calibrate your full 7-day average baseline."
return "Calibrated for peak alerts." + sentenceGap + "Collecting additional readings to calibrate your full 7-day average baseline."
} else {
return "Collecting baseline history. CodeCaps records usage samples every refresh to establish your normal burn pattern."
return "Collecting baseline history." + sentenceGap + "CodeCaps records usage samples every refresh to establish your normal burn pattern."
}
}

Expand Down
26 changes: 22 additions & 4 deletions Sources/CodeCaps/SettingsViews.swift
Original file line number Diff line number Diff line change
Expand Up @@ -480,7 +480,7 @@ struct SettingsSourcesFleetPage: View {
}
}
.disabled(!model.localEnabled || !model.sessionFileChecksEnabled)
ForEach(ReaderStatus.all, id: \.providerKey) { reader in
ForEach(ReaderStatus.current, id: \.providerKey) { reader in
readerRow(reader)
if reader.optionalReaderID == "zcode" { ZAIQuotaSettingsView(controller: model.zAIQuotaSetup) }
if reader.optionalReaderID == "mimo-token-plan" { MiMoQuotaSettings(model: model) }
Expand Down Expand Up @@ -690,8 +690,8 @@ struct SettingsSourcesFleetPage: View {
.frame(maxWidth: .infinity, alignment: .leading)

Text("#\(index + 1)")
.font(.system(.caption2, design: .monospaced).weight(.medium))
.foregroundStyle(.tertiary)
.font(.system(.caption, design: .monospaced).weight(.medium))
.foregroundStyle(.secondary)
.frame(width: 24, alignment: .trailing)

Button {
Expand Down Expand Up @@ -1023,7 +1023,18 @@ struct ReaderStatus {
ReaderStatus(providerKey: "alibaba-token-plan", label: "Alibaba Token Plan", source: "Bailian CLI console sign-in", optionalReaderID: "alibaba-token-plan"),
ReaderStatus(providerKey: "alibaba-coding-plan", label: "Alibaba Coding Plan (Qwen Code)", source: "Bailian CLI console sign-in", optionalReaderID: "alibaba-coding-plan"),
ReaderStatus(providerKey: "mimo-token-plan", label: "Xiaomi MiMo Token Plan", source: "MiMo Token Plan key", optionalReaderID: "mimo-token-plan"),
ReaderStatus(providerKey: "opencode-go", label: "OpenCode Go", source: "OpenCode CLI sign-in", optionalReaderID: "opencode-go"),
]

/// Built-in rows plus one row per declarative endpoint plugin found in
/// the Plugins folder, so a plugin subscription can be toggled in
/// Settings without a CodeCaps update.
static var current: [ReaderStatus] {
all + EndpointPluginLoader.loadCached().map { descriptor in
ReaderStatus(providerKey: descriptor.providerKey, label: descriptor.displayName,
source: "Endpoint plugin", optionalReaderID: descriptor.id)
}
}
Comment thread
kody-ai[bot] marked this conversation as resolved.
Resolved
}

// MARK: - Appearance
Expand Down Expand Up @@ -1125,7 +1136,9 @@ struct SettingsLogoStylePage: View {

private var orderedKeys: [String] {
if model.displaySections.isEmpty {
return ["claude", "cursor", "codex", "gemini", "antigravity", "grok", "grok-bot", "minimax"]
// Derive the pre-read fallback from the reader list so a new
// provider cannot be silently missing from this page.
return ReaderStatus.current.map(\.providerKey)
}
let live = Set(model.displaySections.map(\.id))
let stored = model.platformOrder.filter(live.contains)
Expand All @@ -1143,6 +1156,11 @@ struct SettingsLogoStylePage: View {
if let match = model.displaySections.first(where: { $0.id == rowId }) {
return match.title
}
// Built-in rows only here: this label is resolved per row, and the
// plugin-inclusive list reads the Plugins folder from disk.
if let reader = ReaderStatus.all.first(where: { $0.providerKey == rowId }) {
return reader.label
}
switch rowId {
case "claude", "anthropic": return "Claude Code"
case "cursor": return "Cursor"
Expand Down
2 changes: 1 addition & 1 deletion Sources/CodeCaps/UsageHistoryViews.swift
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ struct UsageHistoryView: View {
+ "Diamonds mark scheduled resets; green squares mark mid-cycle vendor resets; amber squares mark likely plan changes; amber dashed lines mark runaway alerts.")
.font(.system(size: 11)).foregroundStyle(.secondary)
Text("Burn stats are based on % of quota over time, unless absolute token data is available for the platform — in which case the detector prefers the absolute figures.")
.font(.system(size: 10)).foregroundStyle(.tertiary)
.font(.system(size: 11)).foregroundStyle(.secondary)
.frame(maxWidth: .infinity, alignment: .trailing)
.multilineTextAlignment(.trailing)
}
Expand Down
Loading
Loading