Skip to content

Superseded By #357 — Do Not Merge - #353

Closed
jaywedgeworth22 wants to merge 12 commits into
mainfrom
codex/cc-205-plugin-alert-controls
Closed

jaywedgeworth22 wants to merge 12 commits into
mainfrom
codex/cc-205-plugin-alert-controls

Conversation

@jaywedgeworth22

@jaywedgeworth22 jaywedgeworth22 commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

Fixes CC-205

This pull request fixes reset-alert false positives and adds Muse monitoring, optional provider controls, and opt-in SMS delivery. It also updates quit behavior, provider artwork, and Mac version planning.

Resets: the tracker rebaselines when a reused window ID changes cadence and requires a quota rise before treating a pre-end timestamp correction as a reset. Scheduled rollovers and demonstrated restores keep their existing alert rules. Quit now offers Close Window And Keep Running, Quit CodeCaps, and Cancel. The keep-running choice preserves menu-bar access for quota checks and alerts, including Dock-only mode, while confirmed quit retains the snapshot-write drain. System shutdown, restart, logout, quit-all, and an active automatic Sparkle install bypass the prompt.

Providers and plugins: Kimi and Z.ai / ZCode become optional local readers behind a typed LocalQuotaReaderRegistry extension point with per-device preferences. Sources & Fleet adds separate quota-check switches; disabling a provider skips reader construction and credential access, removes its cached rows, and invalidates in-flight refreshes. New code adds a Plugins section with deterministic Mac-local Muse session monitoring, including 60/90-minute burn totals, contributor share display, per-model split, tunable 90-minute burn threshold, bridge controls, and centralized alert fan-out. The burn rule fires only above threshold with a currently observed standard-model session, and standard-session detection fires once on first sight or contributor-to-standard switch, re-arms on return to contributor, ignores missing models, and persists across relaunch. An optional Usage Monitor bridge posts only positive per-session deltas with replay-safe event IDs and checkpointed baselines.

SMS: Alerts & Alarms adds independent SMS for Muse Standard Sessions, Muse Burn, and Quota Exhaustion. SMS ships off for every kind, requires the alert kind to stay enabled, and remains available when notification and popup are off. Setup uses a build-scoped Keychain record plus UserDefaults configuration, saves no message on save, preserves a matching saved secret on blank entry, and exposes explicit re-authorize and forget actions. Delivery reserves a persistent hashed event ID before submission to avoid duplicate paid messages, uses a fixed Twilio endpoint with redirects rejected and no automatic retry, and reports acceptance without claiming handset delivery.

Operational and packaging: adds Keychain services for Muse ingest and Twilio SMS, new UserDefaults preferences and checkpoint state, new Kimi and Z.ai marks with companion and widget mappings, and Mac version planning based on Chicago merge-timestamp shared builds with fail-closed release behavior. No live SMS sending is represented in the changes, and unverified runtime behavior remains unverified.

Tests added: reset-plan and tracker correction cases, quit-confirmation policy cases, registry non-invocation and merge-order cases, Muse reader aggregation and filesystem cases, burn gating and status cases, standard-session detector transition and persistence cases, bridge safety and replay cases, plugin alert-routing cases, SMS coordinator deduplication and capacity cases, SMS controller routing and cancellation cases, Twilio client encoding and receipt cases, credential-store isolation cases, logo and companion-catalog coverage, and Mac version-planner contract tests. The rollout note instructs running swift build and swift test on macOS. No run results, approvals, or deployment verification are included in the changes.

Open review findings, not resolved here: critical — Sources/QuotaCore/TwilioSMSClient.swift:154, SMS form encoding force-unwrap can crash delivery. High — Sources/CodeCaps/MonitorModel.swift:3240, burn persistence failure skips standard-session alerts.


Summary

This pull request fixes Muse alert persistence and refines quota and notification handling. It keeps burn cooldowns and session-detector state retryable when persistence fails rather than consuming them, and it adjusts Muse usage aggregation, Kimi credential selection, cancellation handling, and SMS encoding. Runtime verification status is unverified.

Functional Changes

  • Alert persistence in MonitorModel: saves burn timestamps and detector state through a guarded helper that restores the previous defaults value when synchronize fails. Failed burn persistence no longer blocks the standard session alert or consumes the burn cooldown, and failed detector persistence leaves the standard event eligible on a later poll. Adds a test hook for synchronize behavior.
  • Muse session aggregation in MuseCodeSessionReader: changes segment identity to exact source range and model, with total treated as high-water rather than identity when both boundaries exist. Aggregation keeps only the high-water total per segment and uses deterministic ordering, so repeated cumulative snapshots do not sum and stale snapshots do not replace newer high-water values.
  • Kimi quota reader: limits OAuth credential discovery to the designated Kimi Code credential file with newest-file precedence and injectable environment for lookup. Adds explicit Kimi provider validation requiring approved coding base URLs, narrow TOML provider-table parsing with quoted scalars, and JSON provider selection including legacy provider form. Fixes long OAuth token handling by bypassing the display-length cap, accepts numeric-string counters with finite non-negative guards, clears the physical quota unit for provider counters, and propagates cancellation without trying fallback hosts.
  • Z-Code quota reader and Kimi reader: check cancellation before credential and network work and map URL cancellation to a cancelled result without trying alternate auth forms, accounts, or hosts.
  • Twilio SMS client: replaces form encoding with byte-level UTF-8 percent-encoding to correctly escape Unicode content.
  • Repository hygiene: adds a scoped gitleaks exception for the Twilio secret-validation line.

User-Visible / Operational Impact

  • Missed Muse burn or standard-session alerts due to failed local persistence become retryable on subsequent polls instead of lost. Muse 5-hour and contributor-share totals reflect high-water de-duplication rather than double-counting repeated snapshots.
  • Kimi absent versus misconfigured states are more precise: unrelated provider or service keys are ignored and never sent to Kimi transport, while only explicitly identified Kimi coding providers are used. Quota windows support string-encoded counters from the provider API.
  • SMS notifications preserve non-ASCII titles and bodies through correct encoding. Cancellation of quota refreshes is reported as cancelled without extra network attempts.

Tests Added

New automated tests were added in the diff; no run results were provided so outcomes are unverified. Added tests cover failed burn persistence not blocking standard alerts, failed detector persistence remaining eligible without repeating burn, persistence failure not consuming contributor-to-standard rearm across recreation, long and oversized OAuth credential handling, TOML and JSON provider selection and rejection including unapproved bases and unscoped keys, numeric-string counters and guards, cancellation without fallback for Kimi and Z-Code, high-water aggregation and distinct-range summation for Muse sessions, Unicode SMS form encoding, and Kimi logo color preservation with revised pixel scanning.

Unresolved Risks

  • Automated review reports one high finding that remains open: Sources/QuotaCore/KimiQuotaReader.swift:341 — CRLF config.toml handling may reject a valid Kimi key as missing credential. Behavior for affected configurations is unverified.

@linear-code

linear-code Bot commented Nov 3, 2026

Copy link
Copy Markdown

CC-205

@kody-ai

This comment has been minimized.

Comment thread Sources/CodeCaps/MonitorModel.swift Resolved
Comment thread Sources/QuotaCore/TwilioSMSClient.swift Resolved

@kody-ai kody-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Found critical issues please review the requested changes

@swu-codex

swu-codex Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

@kody start-review

35761ac fixes all three initial findings, the CI compiler-expression failure, and the exact gitleaks false positive.  It also preserves PR #352's long Kimi OAuth token fix and restricts shared-config fallback to explicitly identified Kimi coding providers.  Provider parsing/cancellation tests passed 33/33; Muse plugin tests 16/16; Twilio tests 8/8.  Additional explicit Z.ai key setup is being integrated after first-party source confirmed its OAuth token is not the coding-plan quota credential.

@kody-ai

kody-ai Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Code Review Completed! 🔥

The code review was successfully completed based on your current configurations.

Kody Guide: Usage and Configuration
Interacting with Kody
  • Request a Review: Ask Kody to review your PR manually by adding a comment with the @kody start-review command at the root of your PR.

  • Validate Business Logic: Ask Kody to validate your code against business rules by adding a comment with the @kody -v business-logic command.

  • Provide Feedback: Help Kody learn and improve by reacting to its comments with a 👍 for helpful suggestions or a 👎 if improvements are needed.

Current Kody Configuration
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ✅

Access your configuration settings here.

​

Comment thread Sources/QuotaCore/KimiQuotaReader.swift Resolved
@swu-codex

swu-codex Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

Superseded by #357, which contains the same fixed implementation reconciled with current main and #354.  All 106 changed blobs were verified against native-tested source 2da7e69 (1,597 Swift tests, 10 skipped, zero failures; 101 Node contracts passed).  The cumulative-segment, persistence-coupling, SMS-encoding, and CRLF-parser findings were fixed with evidence in their original threads; no finding is being abandoned.  #357 now has a clean merge base and active CI/review.  Runtime installation and scoped credential binding remain tracked under CC-205.

@swu-codex swu-codex Bot changed the title Fix Reset Alerts And Add Muse Monitoring, Optional Providers, And SMS Superseded By #357 — Do Not Merge Nov 3, 2026
@swu-codex

swu-codex Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

This branch is superseded by #357, which carries the same corrected implementation on current main and includes Echo #354.  All four findings from this branch were fixed with replies and evidence; #357 has the complete changes and refreshed CI/review.  Please do not merge this branch.

@jaywedgeworth22
jaywedgeworth22 marked this pull request as draft November 4, 2026 04:58
@swu-wise
swu-wise Bot marked this pull request as ready for review November 6, 2026 03:43
Comment on lines 502 to 512
climbed = reading >= last + ResetAlarmPolicy.earlyResetRiseMargin
}
if jump > required || (jump > ResetAlarmPolicy.resetDriftTolerance && climbed) {
let rose = reading.flatMap { current in
window.lastRemaining.map { current > $0 + ResetAlarmPolicy.riseEpsilon }
} ?? false
let resetHasQuotaEvidence = rose || (hasPassed && reading == nil)
if (jump > required && resetHasQuotaEvidence)
|| (jump > ResetAlarmPolicy.resetDriftTolerance && climbed) {
isReset = true
// When the window had *not* reached its own scheduled end,
// any reset is an early / mid-cycle vendor restore rather than

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: Scheduled quota rollovers fail to trigger isReset when the remaining quota was idle or unchanged across the period boundary.
Severity: MEDIUM

Suggested Fix

Only require resetHasQuotaEvidence when !hasPassed, allowing jump > required to indicate a reset once hasPassed is true even if the reading has not risen.

Prompt for AI Agent
Review the code at the location below. A potential bug has been identified by an AI
agent. Verify if this is a real issue. If it is, propose a fix; if not, explain why it's
not valid.

Location: Sources/QuotaCore/ResetAlarmTracker.swift#L496-L512

Potential issue: In `ResetAlarmTracker.advance`, the reset detection condition requires
`resetHasQuotaEvidence` for scheduled jumps (`jump > required`). Because
`resetHasQuotaEvidence` requires `rose` (`reading > lastRemaining + 1`) or `hasPassed &&
reading == nil`, an idle quota window sitting at 100% remaining will not trigger
`isReset` when its period passes and the reset timestamp advances. The subsequent branch
updates `periodResetAt`, causing the scheduled rollover to be permanently missed for
flat or near-flat windows.

Comment on lines +335 to +341
let total = number(usage["totalTokens"]), total >= 0 else { return nil }
let range = usage["sourceRange"] as? [String: Any]
return MuseCodeTokenSegment(
sessionId: sessionId,
modelId: modelId,
totalTokens: Int(total.rounded()),
promptTokens: number(usage["promptTokens"]).map { Int($0.rounded()) },

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: Converting unbounded floating-point numbers to Int in MuseCodeSessionReader can trigger a runtime trap on large numeric values.
Severity: LOW

Suggested Fix

Enforce maximum and minimum bounds or clamp token values before casting them to Int, or use safe conversion methods that handle overflow without trapping.

Prompt for AI Agent
Review the code at the location below. A potential bug has been identified by an AI
agent. Verify if this is a real issue. If it is, propose a fix; if not, explain why it's
not valid.

Location: Sources/QuotaCore/MuseCodeSessionReader.swift#L335-L341

Potential issue: `MuseCodeSessionReader.number()` accepts any finite `NSNumber`, but
callers in `segment()` convert these values via `Int(total.rounded())` and
`Int($0.rounded())`. Converting floating-point values larger than `Double(Int.max)`
traps at runtime in Swift. An excessively large or corrupted token count in a local
session snapshot file will crash the application during `refreshMuseCodePlugin` and
repeatedly on subsequent launches within the activity window.

@jaywedgeworth22
jaywedgeworth22 marked this pull request as draft November 7, 2026 20:16
@jaywedgeworth22

Copy link
Copy Markdown
Member Author

Closed as fully superseded by #357 (the titles said so), per the owner's standing superseded-PR rule and converted-to-draft earlier today.  Reopen if #357 drops this scope.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant