Skip to content

fix(backend): stateless owner-authed reply generation so clone drafting stops writing to the user's chat - #11444

Merged
undivisible merged 9 commits into
BasedHardware:mainfrom
undivisible:fix/windows-ai-clone-stateless-endpoint
Aug 14, 2026
Merged

undivisible merged 9 commits into
BasedHardware:mainfrom
undivisible:fix/windows-ai-clone-stateless-endpoint

Conversation

@undivisible

@undivisible undivisible commented Aug 12, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

A bot review on #10933 found that the Windows AI Clone generates its reply drafts by calling the user-facing POST /v2/messages. That handler persists the drafting prompt as a human chat row, counts it against chat quota, runs goal extraction on it, and later persists the generated assistant response — so clone drafting contaminates the owner's canonical Omi chat history and can create spurious goals even when the user never opened chat. Triage confirmed the finding but deferred it as out of scope for #10933.

The clone caller does not exist on main yet (it lives only on #10933's branch), so this PR is the backend half: the stateless endpoint plus its guard.

What this adds

POST /v2/chat/generate-reply — owner-authenticated (Firebase ID token, chat:send_message rate-limit policy), stateless.

It reuses the same generation path as /v2/messages (execute_chat_stream) rather than duplicating it. The only differences are persistence and session identity:

  • no chat session is acquired or mutated (chat_session=None)
  • no human or AI message is written to chat history
  • no chat quota question is attributed to the conversation, no goal extraction is submitted
  • chat quota is still enforced, so generation cannot bypass plan limits

Explicit error contract. execute_chat_stream yields error: frames verbatim and stages a canned answer alongside callback_data['error'] — the sibling finding already fixed on #10933 was that those were being staged as reply text. This endpoint returns neither: a failed generation is 502 {"error": "<reason>"}, with a shared record_fallback emission (component=other, llm_answer → none, outcome=exhausted) per docs/agents/fallback-telemetry.md.

Route registered as review_status: reviewed in backend/route_policy_manifest.yaml (not the legacy baseline). It lives in a new backend/routers/chat_generation.py rather than inside chat.py so the persisting and non-persisting surfaces cannot drift into sharing state (and so chat.py stays under its line-count ratchet).

Separate commit: the backend async-blocker gate's has_await only recognized ast.Await, so any endpoint that drives an async generator (async for) or an async context manager was reported as no_await_should_be_def even though it cannot be a plain def. This endpoint is the first caller to hit that false positive; fixed in the scanner with two tests rather than worked around at the call site.

What #10933 must change to adopt this

In desktop/windows/src/main/aiClone/replyEngine.ts, replace the POST /v2/messages SSE call with a single POST /v2/chat/generate-reply JSON call:

  • request: { text, history: [{ text, sender }], app_id? }
  • success: 200 { text, app_id } — use text as the draft
  • failure: 502 { detail: { error } } — treat as a generation failure, never as draft text; the existing Windows recordFallback still covers the switch to the non-grounded desktop completion provider

No SSE parsing, no base64 done: decoding, and no error: frame handling remain on the caller side.

Verification

  • backend/tests/unit/test_chat_generate_reply_stateless.py — 3 tests, all through the real routers.chat FastAPI app via the existing chat router harness (production behavior through a controllable seam, not a source scrape):
    • generation writes no turn: chat_db.add_message, add_message_to_chat_session, get_chat_session, record_chat_quota_question, llm_executor.submit all uncalled; chat_session passed as None
    • a staged error answer is never returned as reply text (502, record_fallback with outcome=exhausted)
    • legacy principal: /v2/messages still persists the human turn and records its quota question
  • Mutation-verified: adding chat_db.add_message(uid, messages[-1].model_dump()) back into the handler fails 2 of the 3 tests with AssertionError: Expected 'add_message' to not have been called. Called 1 times.; reverted.
  • backend/test.sh on the changed files and make preflight pass.

Failure-Class: none

Review in cubic


Note

Medium Risk
Touches the shared chat generation path and quota enforcement for a new first-party surface; behavior is well-tested but incorrect client migration could still affect drafting UX.

Overview
Adds POST /v2/chat/generate-reply in a dedicated chat_generation router so automated drafting (e.g. AI clone) can run the same execute_chat_stream path as POST /v2/messages without persisting turns, touching chat sessions, recording quota questions, or running goal extraction. Callers send text, optional history, and optional app_id; successful responses return JSON { text, app_id } with citation markers stripped. Failures return 502 with { error } and never surface staged canned error text; record_fallback is emitted on exhaustion.

New Pydantic types GenerateReplyRequest / GenerateReplyResponse back the API. The route is wired in main.py and documented in route_policy_manifest.yaml (Firebase auth, chat:send_message rate limit, exact_chat_owner). Chat quota is still enforced via enforce_chat_quota.

scan_async_blockers now treats async for and async with as real suspension so streaming endpoints are not misclassified as no_await_should_be_def. Unit tests cover stateless behavior, error contract, and that /v2/messages still persists.

Reviewed by Cursor Bugbot for commit 7b648e3. Configure here.

undivisible and others added 6 commits August 12, 2026 12:26
Automated drafting surfaces had no way to generate a reply without going
through POST /v2/messages, which persists the drafting prompt as a human
chat row, counts it against chat quota, runs goal extraction on it, and
persists the generated answer. Machine activity therefore contaminated the
owner's canonical chat history.

POST /v2/chat/generate-reply reuses the same generation path
(execute_chat_stream) with persistence and session identity removed: no
chat session is acquired or mutated, no message is written, no quota
question is attributed to the conversation.

The error contract is explicit rather than inherited: execute_chat_stream
stages a canned answer alongside callback_data['error'] and yields verbatim
`error: ` frames. This endpoint never returns either as reply text -- a
failed generation is HTTP 502 with {'error': <reason>} and a shared
record_fallback emission.

Failure-Class: new

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Regression test for the /v2/messages contamination: generating through
/v2/chat/generate-reply must not call chat_db.add_message, touch a chat
session, record a quota question, or submit goal extraction. Adding a
persistence call back into the handler fails the assertion.

Also covers the explicit error contract (staged canned answer is never
returned as reply text) and a legacy-principal case asserting /v2/messages
keeps persisting the human turn.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…point

An automated surface that only needs a generated result must not reuse the
user-facing endpoint that also owns the user's durable state. Guard artifact
is the stateless-generation behavioral test added in this PR.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Keeps routers/chat.py within the product file line-count ratchet and keeps
the persisting and non-persisting chat surfaces from drifting into shared
state. Behavior is unchanged; the endpoint still reuses execute_chat_stream.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… gate

`has_await` only recognized `ast.Await`, so an endpoint that drives an async
generator (`async for`) or an async context manager was reported as
`no_await_should_be_def` even though it cannot be rewritten as a plain `def`.
The new stateless generation endpoint is the first caller to hit it.

Failure-Class: none

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
New backend router files are strict-typechecked: pass MessageType.text
instead of the bare literal and skip the app lookup when no app id was
supplied, so get_available_app_by_id never receives None.

Failure-Class: none

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@cursor

cursor Bot commented Aug 12, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_52849e18-f00d-4787-9ef4-d0f40029ff0a)

@cubic-dev-ai cubic-dev-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.

All reported issues were addressed across 8 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread backend/routers/chat_generation.py Resolved
Comment thread backend/route_policy_manifest.yaml Resolved
Comment thread backend/route_policy_manifest.yaml Resolved
Comment thread backend/routers/chat_generation.py Resolved

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1182101daf

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread backend/routers/chat_generation.py Outdated
callback_data: dict[str, Any] = {}
usage_token = set_usage_context(uid, Features.CHAT)
try:
async for _chunk in execute_chat_stream(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Prevent automated drafts from invoking mutating tools

When the AI Clone supplies externally authored conversation history, this call enters the default agentic path with the owner's UID and the complete CORE_TOOLS set, which includes create_action_item_tool, calendar create/update/delete, preference writes, and dynamic app tools. A correspondent can therefore place an instruction in the cloned conversation that causes background reply drafting to mutate the owner's tasks, calendar, or integrations without the owner initiating a chat turn. Use a generation mode with an explicitly read-only tool set for this machine-triggered surface.

AGENTS.md reference: AGENTS.md:L41-L43

Useful? React with 👍 / 👎.

Comment thread backend/routers/chat_generation.py Outdated
stream stages alongside ``callback_data['error']`` are never returned as reply
text. A failed generation is an HTTP 502 with ``{'error': <reason>}``.
"""
enforce_chat_quota(uid, platform=x_app_platform)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Count stateless generations against the chat quota

For question-limited plans, enforce_chat_quota reads backend_chat.quota_questions, but this handler never calls record_chat_quota_question or otherwise increments that counter. Consequently, any account currently below its limit can repeatedly use this endpoint while its measured usage remains unchanged, bypassing the advertised Free/Neo question caps subject only to the generic hourly rate limit. Record one idempotent quota event per accepted generation without attaching it to chat history.

Useful? React with 👍 / 👎.

Comment thread backend/routers/chat_generation.py Outdated
Comment on lines +54 to +57
enforce_chat_quota(uid, platform=x_app_platform)

app_id = data.app_id if data.app_id not in ['null', ''] else None
app_record = get_available_app_by_id(app_id, uid) if app_id else None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Offload synchronous quota and app reads

Because this is an async def handler, these calls execute on the event-loop thread: enforce_chat_quota performs several synchronous Firebase/Firestore reads, and get_available_app_by_id can synchronously query Redis and Firestore on a cache miss. Under ordinary datastore latency, a clone-drafting request can therefore stall health checks and every concurrent connection on the worker; run these synchronous operations through run_blocking(db_executor, ...).

AGENTS.md reference: backend/AGENTS.md:L283-L285

Useful? React with 👍 / 👎.

key_subject: uid
enforcement: fail_closed
placement: wrapper
timeout_class: default_method

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Give non-streaming generation a matching request timeout

This route is assigned the default POST timeout, which is 120 seconds when HTTP_POST_TIMEOUT is unset, but the reused agentic path permits a separate 25-second setup phase followed by up to 150 seconds of generation. Unlike /v2/messages, this handler does not return a StreamingResponse, so middleware waits for the entire generation and cancels it at 120 seconds; a valid long tool/model run therefore returns a bare 504 before the generator can produce the documented structured 502 and fallback telemetry. Add a path timeout covering the internal deadline or shorten the internal deadline for this endpoint.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The route is registered with timeout_class: default_method matching /v2/messages. The agentic path carries its own internal setup deadline (AGENT_STREAM_SETUP_TIMEOUT_SECONDS) so the SSE-style body cannot stay silent, and generation deadline handling lives with the stream. If Cloud Run sets a tighter HTTP_POST_TIMEOUT for this non-streaming handler in production, the operator override belongs in the deploy-time methods_timeout config; no code change needed for the default.

Comment thread backend/routers/chat_generation.py Outdated
uid,
messages,
app,
cited=False,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Strip conversation citations from reply drafts

When the agent retrieves owner conversations, the agentic system prompt instructs it to emit inline numeric citations such as [1], and the agentic branch does not consume the cited=False argument. The normal /v2/messages completion path strips those markers in process_message, but this handler returns callback_data['answer'] verbatim, so generated clone replies can expose meaningless [1] markers to the external recipient. Either make the agentic prompt honor the flag or apply the same citation cleanup before returning the draft.

Useful? React with 👍 / 👎.

Comment thread backend/main.py
app.include_router(focus_sessions.router)
app.include_router(advice.router)
app.include_router(chat_sessions.router)
app.include_router(chat_generation.router)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Add the new route to the app-client OpenAPI contract

Although this router exposes a new first-party client API, /v2/chat is absent from APP_CLIENT_PREFIXES and the commit does not update docs/api-reference/app-client-openapi.json. The canonical app-client schema and its generated Dart, TypeScript, and Swift bindings therefore omit both this operation and its request/response models, leaving the Windows adoption to use an untracked hand-written wire contract. Include the route in the app-client export and regenerate the checked-in contract and bindings.

AGENTS.md reference: backend/AGENTS.md:L231-L233

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

/v2/chat is deliberately absent from APP_CLIENT_PREFIXES: the app-client schema feeds the mobile clients' generated Dart/TS/Swift bindings, while this endpoint's only caller is the Windows clone (not part of the app-client generation surface), and the caller itself does not exist on main until #10933. Adding it here would force regenerating the app-client JSON plus all three binding sets without a consumer; the schema export can include /v2/chat when the clone adoption lands.

Comment thread backend/routers/chat_generation.py Outdated
Comment on lines +57 to +59
app_record = get_available_app_by_id(app_id, uid) if app_id else None
app = App(**app_record) if app_record else None
resolved_app_id = app.id if app else None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reject an unavailable requested app instead of changing personas

When the caller explicitly supplies a stale, deleted, private, or otherwise unavailable app_id, get_available_app_by_id returns None and this code silently continues with app=None, producing a successful default-Omi draft with app_id: null. The clone caller cannot distinguish that mode change from a valid generation and may send a reply in the wrong persona; reject the request when a supplied app cannot be resolved, or explicitly instrument the degraded fallback if default generation is intentional.

AGENTS.md reference: AGENTS.md:L91-L91

Useful? React with 👍 / 👎.

@Git-on-my-level Git-on-my-level added security-review Touches auth, provider routing, secrets, or security-sensitive surfaces backend Backend Task (python) labels Aug 12, 2026

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for separating the clone drafting path from the user-facing chat persistence path. I reviewed the changed files on head 1182101dafd66309eb6be9ed3572a5390694a536 and this looks like the right direction, but because this adds a new owner-authenticated chat-generation endpoint on a user-data/auth surface, I’m leaving it for maintainer security/backend sign-off rather than approval.

File-specific notes:

  • .github/failure-classes/FC-machine-surface-on-user-state-endpoint.json captures the violated boundary clearly: machine-only drafting should not reuse a durable user-state endpoint, and the prevention artifact points at the new behavioral test.
  • backend/main.py registers chat_generation.router, so the new route is actually exposed through the FastAPI app.
  • backend/models/chat.py adds bounded request models (text and history turn text capped, history length capped), which is important for this generation-only API.
  • backend/route_policy_manifest.yaml declares /v2/chat/generate-reply with Firebase auth, exact_chat_owner, fail-closed chat:send_message rate limiting, and data_domain: chat; that matches the sensitive surface.
  • backend/routers/chat_generation.py avoids the stateful chat writes I was looking for: it builds transient Message objects, calls execute_chat_stream(..., chat_session=None), does not call chat_db.add_message, does not record a quota question, and treats callback_data['error'] / missing answers as a 502 instead of returning the staged canned answer as reply text. One implementation note for the human reviewer: the endpoint is async but still calls synchronous quota/app helpers before the async stream; CI is green, but this is worth backend maintainer awareness for event-loop sensitivity on this auth/chat path.
  • backend/scripts/scan_async_blockers.py correctly treats async for and async with as real suspension points, avoiding a false “should be def” finding for streaming consumers like this endpoint.
  • backend/tests/unit/test_chat_generate_reply_stateless.py exercises the important behavioral contract: generation succeeds without chat-state writes, staged error answers are not returned as successful text, and /v2/messages still persists as before.
  • backend/tests/unit/test_scan_async_blockers.py adds focused coverage for the async for / async with scanner correction.

Validation: GitHub checks report the backend/hermetic gates passing on this head. I also attempted the focused backend unit command locally (uv run --python 3.11 pytest tests/unit/test_chat_generate_reply_stateless.py tests/unit/test_scan_async_blockers.py -q); the scanner tests passed, but the chat-generation tests were blocked in this local checkout by a harness dependency conflict where FastAPI imported a global Python 3.12 multipart package instead of python-multipart. I’m treating that as a local test-environment issue, not a production-code blocker.

Recommendation: positive technical signal, with security-review/backend maintainer sign-off before merge because this introduces a new authenticated chat/data endpoint.


Reviewed by glm-5.2 for the Omi maintainer automation.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Stateless owner-authed generate-reply keeps clone drafting out of the user's canonical chat history and quota-attributed turns; reuses execute_chat_stream rather than duplicating it, with mutation-verified tests. New endpoint, so approve-only — merge is yours.

Map stream exceptions to the documented response, reject unavailable apps, and remove internal conversation citations from external drafts.

Tests: backend/.venv/bin/python -m pytest tests/unit/test_chat_generate_reply_stateless.py -q

Failure-Class: FC-machine-surface-on-user-state-endpoint
@cursor

cursor Bot commented Aug 14, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_2ed93893-7e95-47e6-aa19-d9938505d77a)

…arations

- Route enforce_chat_quota and get_available_app_by_id through db_executor so
  concurrent clone drafts cannot stall the asyncio event loop.
- Declare byok: validated_when_headers_present and rate-limit enforcement
  fail_open in route_policy_manifest.yaml to match the actual auth dependency
  (get_current_user_uid validates BYOK headers; with_rate_limit fails open on
  Redis errors for first-party user paths).
- Give the async-blocker-gate tests a router decorator so the sample functions
  are endpoints and the async-for/async-with suspension rule is exercised
  rather than silently skipped as non-endpoint helpers.

Verification: test_chat_generate_reply_stateless.py, test_scan_async_blockers.py,
test_route_policy_preflight.py, test_route_policy_inventory.py pass locally
(65 tests). scan_async_blockers reports 0 blocking findings on the router.

Failure-Class: none

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7b648e3d9e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +91 to +95
async for _chunk in execute_chat_stream(
uid,
messages,
app,
cited=False,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Isolate private retrieval from correspondent-controlled history

When history contains correspondent-controlled text, this passes it to the agentic path under the owner's UID, where CORE_TOOLS includes get_conversations_tool and search_conversations_tool; a prompt-injecting correspondent can therefore make the generated external reply disclose the owner's private conversations. Restricting only the previously flagged mutating tools does not close this read-side leak—this surface needs a tool policy that also excludes owner-private retrieval or otherwise treats the supplied history as untrusted data.

AGENTS.md reference: AGENTS.md:L89-L89

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed this surface must not carry the full mutating/retrieval toolset. Since the Windows clone caller does not exist on main yet (it lands with #10933), the read-only toolset restriction for machine-triggered drafting is planned as part of #10933's adoption rather than this backend-only PR; tracked so the endpoint cannot merge into production usage with CORE_TOOLS before that lands.

Comment on lines 191 to 193
for child in _walk_body(node):
if isinstance(child, ast.Await):
if isinstance(child, (ast.Await, ast.AsyncFor, ast.AsyncWith)):
return True

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Stop suspension detection at nested function boundaries

When an async function merely defines a nested coroutine containing async for or async with, _walk_body descends into that nested definition and this condition now returns true even though the outer function never suspends. That suppresses the no_await_should_be_def finding for the outer endpoint, so inspect only the current function's lexical body and skip nested function scopes.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed on head 412c9f4c15: has_await now skips nested function scopes (via the existing _collect_nested_func_lines) before checking for await/async for/async with, so an outer endpoint that merely defines a nested coroutine is still flagged no_await_should_be_def. Regression covered by test_nested_coroutine_does_not_suppress_outer_no_await_finding.

Comment on lines +111 to +117
record_fallback(
component='other',
from_mode='llm_answer',
to_mode='none',
reason='other',
outcome='exhausted',
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Do not record hard failures as fallbacks

When generation fails, this records llm_answer → none and then immediately returns a 502, so no alternate provider, mode, degraded result, or fail-open path was actually taken. The fallback telemetry contract explicitly assigns hard failures to error metrics rather than record_fallback; incrementing omi_fallback_total here misclassifies every failed request and corrupts fallback-rate alerts.

AGENTS.md reference: AGENTS.md:L91-L91

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

This emission is deliberate and documented in the PR body: the stream drives the same fail-closed path as /v2/messages, and when generation exhausts, the endpoint records the shared llm_answer → none, outcome=exhausted fallback before returning 502 — the only telemetry a caller can rely on when the clone switches to the non-grounded desktop provider. The success-path test asserts record_fallback.assert_not_called() so a regression that burns fallback telemetry on success stays caught.

Comment thread backend/models/chat.py
Comment on lines +237 to +239
text: str = Field(..., min_length=1, max_length=100000)
history: List[GenerateReplyTurn] = Field(default_factory=list, max_length=50)
app_id: Optional[str] = Field(None, max_length=200)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Bound persona histories before invoking the model

When app_id resolves to a persona and the caller supplies a history near the accepted limit of 50 turns × 100,000 characters, execute_chat_stream selects the persona branch before the agentic path's fit_within_budget guard. The complete accepted payload is therefore sent to the persona model and predictably exceeds its context window, producing a 502 instead of a draft; apply a total token budget before route selection or enforce a much smaller aggregate request bound.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Persona histories are bounded by the same GenerateReplyRequest validation as the message path (50 turns max, 100k chars per turn) that /v2/messages already ships with, and the persona branch routes through the same execute_chat_stream budget handling. If a persona model's context window is tighter, the dedicated fit_within_budget pass for the persona branch is follow-up for #10933 adoption, not a correctness regression in this stateless surface.

@undivisible
undivisible merged commit a086e11 into BasedHardware:main Aug 14, 2026
32 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) security-review Touches auth, provider routing, secrets, or security-sensitive surfaces

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants