Skip to content

feat(flare-proxy): request-optimization short-circuits for CLI bookkeeping calls - #355

Merged
getappz merged 3 commits into
masterfrom
task/212
Jul 28, 2026
Merged

feat(flare-proxy): request-optimization short-circuits for CLI bookkeeping calls#355
getappz merged 3 commits into
masterfrom
task/212

Conversation

@getappz

@getappz getappz commented Jul 28, 2026

Copy link
Copy Markdown
Owner

Summary

  • Ports 5 short-circuit categories from free-claude-code (quota-check mock, prefix detection, title-generation skip, suggestion-mode skip, filepath-extraction mock) so Claude-Code-CLI internal bookkeeping requests are intercepted locally instead of burning free-tier quota. Task 2 of feat(pm): PM skill pack v1 — /pm:standup /pm:groom /pm:plan /pm:health #212.
  • Fix (review finding, item fix(work): supervisor-dispatched jobs can claim their own assigned item #393): the port originally answered short-circuits with an SSE stream, but the reference always returns a plain non-streaming Anthropic Messages JSON body for these categories, and the CLI doesn't send stream: true for them — an SSE reply would have broken CLI parsing. Replaced the SSE builders with one build_message() JSON helper and switched the handler to axum::Json(..).into_response().
  • Also fixes a pre-existing clippy -D warnings failure (Iterator::last on a DoubleEndedIterator).

Test plan

  • cargo fmt --all -- --check
  • cargo clippy -p flare-proxy --all-features --all-targets -- -D warnings
  • cargo test -p flare-proxy --all-features (46 passed)
  • cargo build --workspace --all-features

Summary by CodeRabbit

  • New Features
    • Added a request short-circuiting layer for supported internal message patterns, returning immediate non-streaming assistant responses.
    • Enabled faster handling for quota-check, command-prefix, title-generation skipping, suggestion-mode skipping, and filepath-extraction requests.
    • Added configuration flags (via environment settings) to enable or disable each shortcut behavior.
  • Bug Fixes
    • Non-matching requests continue through the existing upstream forwarding flow unchanged.
  • Tests
    • Added unit coverage for pattern detection, configuration behavior, and response formatting.

…eping calls

Ports the 5 short-circuit categories from free-claude-code (quota-check mock,
prefix detection, title-generation skip, suggestion-mode skip, filepath
extraction mock) so Claude-Code-CLI internal bookkeeping requests are
intercepted locally instead of burning free-tier quota.

Returns a non-streaming Messages JSON body (matching the reference's
response shape) rather than an SSE stream -- these CLI-internal calls are
not sent with stream:true and expect a plain JSON response; the rest of
this proxy is unconditionally SSE, so this is a deliberate exception.
@coderabbitai

coderabbitai Bot commented Jul 28, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a configurable short-circuit module for selected Anthropic-style message requests. Matching quota, command, title, suggestion, and filepath requests receive generated JSON responses; unmatched requests continue through existing upstream forwarding.

Changes

Short-circuit request handling

Layer / File(s) Summary
Short-circuit contracts and dispatch
crates/flare-proxy/src/shortcircuit.rs
Defines environment-backed feature flags, match outcomes, dispatch ordering, response payloads, text normalization, and ID generation.
Request detection and parsing
crates/flare-proxy/src/shortcircuit.rs
Detects quota, command-prefix, title-generation, suggestion-mode, and filepath-extraction patterns, including command and filepath parsing.
Router integration and validation
crates/flare-proxy/src/lib.rs, crates/flare-proxy/src/shortcircuit.rs
Exports the module, stores configuration in AppState, short-circuits matched requests before forwarding, and tests detection and response behavior.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant v1_messages_handler
  participant try_short_circuit
  participant UpstreamProxy
  Client->>v1_messages_handler: JSON message request
  v1_messages_handler->>try_short_circuit: Body and configured flags
  alt Match
    try_short_circuit-->>v1_messages_handler: Generated JSON response
    v1_messages_handler-->>Client: Short-circuited response
  else NoMatch
    try_short_circuit-->>v1_messages_handler: NoMatch
    v1_messages_handler->>UpstreamProxy: Existing proxy request
    UpstreamProxy-->>Client: Upstream response
  end
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change: local short-circuit optimization for CLI bookkeeping calls.
Description check ✅ Passed The description covers the summary and test plan well; only the reviewer notes/backwards-compatibility section from the template is missing.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch task/212

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai 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.

🧹 Nitpick comments (3)
crates/flare-proxy/src/shortcircuit.rs (2)

145-196: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Redundant <filepaths> check and duplicate to_lowercase() call.

"<filepaths>" is always a substring of "filepaths"'s match target once lowercased, so content.to_lowercase().contains("<filepaths>") can never be true when the first check is false ("<filepaths>" itself contains "filepaths") — the second condition is dead. It also allocates a second lowercase copy of content unnecessarily, on a path reached by every user message shaped like Command:/Output:.

♻️ Proposed cleanup
-    let user_has_filepaths = content.to_lowercase().contains("filepaths")
-        || content.to_lowercase().contains("<filepaths>");
+    let content_lower = content.to_lowercase();
+    let user_has_filepaths = content_lower.contains("filepaths");
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/flare-proxy/src/shortcircuit.rs` around lines 145 - 196, In
detect_filepath_extraction, compute content.to_lowercase() once and reuse it for
the filepath detection. Remove the redundant "<filepaths>" condition, leaving
the check for the "filepaths" substring while preserving the existing gating
behavior.

507-552: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add dispatch-level tests for the remaining try_short_circuit branches.

Only the "all disabled" and "quota enabled" cases exercise try_short_circuit directly; the prefix/title/suggestion/filepath branches are only tested via their standalone detector functions, not through the actual dispatcher (config flag gating + build_message shape together). Since this dispatcher gates quota-bypassing behavior, end-to-end coverage of each branch would catch future regressions where a flag check or return value is wired incorrectly.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/flare-proxy/src/shortcircuit.rs` around lines 507 - 552, Add
dispatch-level tests alongside test_short_circuit_all_disabled and
test_short_circuit_quota_mock_enabled for the fast-prefix, title-generation,
suggestion-mode, and filepath-extraction branches of try_short_circuit. Enable
only the corresponding ShortCircuitConfig flag in each test, provide a body that
triggers that detector, and assert the returned Match payload from
build_message, including its distinguishing content and metadata.
crates/flare-proxy/src/lib.rs (1)

57-58: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider caching ShortCircuitConfig in AppState instead of reloading per request.

ProviderConfig is computed once in router() and stored in AppState, but ShortCircuitConfig::from_env() is re-read from the environment on every request here. Not a functional bug (env vars are static at runtime), but it's an inconsistent pattern with the existing config-loading approach in this same handler.

♻️ Proposed refactor
-    let sc_config = shortcircuit::ShortCircuitConfig::from_env();
-    match shortcircuit::try_short_circuit(&body, &sc_config) {
+    match shortcircuit::try_short_circuit(&body, &state.sc_config) {

This requires adding the field to AppState and populating it in router():

struct AppState {
    config: ProviderConfig,
    client: reqwest::Client,
    sc_config: shortcircuit::ShortCircuitConfig,
}
.with_state(AppState {
    config: ProviderConfig::from_env(),
    client,
    sc_config: shortcircuit::ShortCircuitConfig::from_env(),
})
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/flare-proxy/src/lib.rs` around lines 57 - 58, Cache ShortCircuitConfig
in AppState alongside ProviderConfig and initialize it once in router() with
ShortCircuitConfig::from_env(). Update the request handler’s
shortcircuit::try_short_circuit call to use the state-held configuration instead
of reloading the environment per request.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@crates/flare-proxy/src/lib.rs`:
- Around line 57-58: Cache ShortCircuitConfig in AppState alongside
ProviderConfig and initialize it once in router() with
ShortCircuitConfig::from_env(). Update the request handler’s
shortcircuit::try_short_circuit call to use the state-held configuration instead
of reloading the environment per request.

In `@crates/flare-proxy/src/shortcircuit.rs`:
- Around line 145-196: In detect_filepath_extraction, compute
content.to_lowercase() once and reuse it for the filepath detection. Remove the
redundant "<filepaths>" condition, leaving the check for the "filepaths"
substring while preserving the existing gating behavior.
- Around line 507-552: Add dispatch-level tests alongside
test_short_circuit_all_disabled and test_short_circuit_quota_mock_enabled for
the fast-prefix, title-generation, suggestion-mode, and filepath-extraction
branches of try_short_circuit. Enable only the corresponding ShortCircuitConfig
flag in each test, provide a body that triggers that detector, and assert the
returned Match payload from build_message, including its distinguishing content
and metadata.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 3d87bb52-b733-43ac-b4b2-2f50c47c9b6a

📥 Commits

Reviewing files that changed from the base of the PR and between 8f7534b and b52faa5.

📒 Files selected for processing (2)
  • crates/flare-proxy/src/lib.rs
  • crates/flare-proxy/src/shortcircuit.rs

getappz added 2 commits July 28, 2026 12:15
- drop redundant <filepaths> substring check (always implied by filepaths)
- cache ShortCircuitConfig in AppState instead of reading env per request
- add try_short_circuit dispatch coverage for prefix/title/suggestion/filepath
@getappz
getappz merged commit 952b09d into master Jul 28, 2026
15 checks passed
@getappz
getappz deleted the task/212 branch July 28, 2026 06:57
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