Repository navigation
fix(backend): stateless owner-authed reply generation so clone drafting stops writing to the user's chat - #11444
Conversation
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]>
Bugbot couldn't run - usage limit reachedBugbot 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) |
There was a problem hiding this comment.
All reported issues were addressed across 8 files
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
There was a problem hiding this comment.
💡 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".
| callback_data: dict[str, Any] = {} | ||
| usage_token = set_usage_context(uid, Features.CHAT) | ||
| try: | ||
| async for _chunk in execute_chat_stream( |
There was a problem hiding this comment.
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 👍 / 👎.
| 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) |
There was a problem hiding this comment.
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 👍 / 👎.
| 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 |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| uid, | ||
| messages, | ||
| app, | ||
| cited=False, |
There was a problem hiding this comment.
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 👍 / 👎.
| app.include_router(focus_sessions.router) | ||
| app.include_router(advice.router) | ||
| app.include_router(chat_sessions.router) | ||
| app.include_router(chat_generation.router) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
/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.
| 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 |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.jsoncaptures 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.pyregisterschat_generation.router, so the new route is actually exposed through the FastAPI app.backend/models/chat.pyadds bounded request models (textand history turn text capped, history length capped), which is important for this generation-only API.backend/route_policy_manifest.yamldeclares/v2/chat/generate-replywith Firebase auth,exact_chat_owner, fail-closedchat:send_messagerate limiting, anddata_domain: chat; that matches the sensitive surface.backend/routers/chat_generation.pyavoids the stateful chat writes I was looking for: it builds transientMessageobjects, callsexecute_chat_stream(..., chat_session=None), does not callchat_db.add_message, does not record a quota question, and treatscallback_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 isasyncbut 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.pycorrectly treatsasync forandasync withas real suspension points, avoiding a false “should be def” finding for streaming consumers like this endpoint.backend/tests/unit/test_chat_generate_reply_stateless.pyexercises the important behavioral contract: generation succeeds without chat-state writes, staged error answers are not returned as successful text, and/v2/messagesstill persists as before.backend/tests/unit/test_scan_async_blockers.pyadds focused coverage for theasync for/async withscanner 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
left a comment
There was a problem hiding this comment.
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
Bugbot couldn't run - usage limit reachedBugbot 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
There was a problem hiding this comment.
💡 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".
| async for _chunk in execute_chat_stream( | ||
| uid, | ||
| messages, | ||
| app, | ||
| cited=False, |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| for child in _walk_body(node): | ||
| if isinstance(child, ast.Await): | ||
| if isinstance(child, (ast.Await, ast.AsyncFor, ast.AsyncWith)): | ||
| return True |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| record_fallback( | ||
| component='other', | ||
| from_mode='llm_answer', | ||
| to_mode='none', | ||
| reason='other', | ||
| outcome='exhausted', | ||
| ) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
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
mainyet (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_messagerate-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:chat_session=None)Explicit error contract.
execute_chat_streamyieldserror:frames verbatim and stages a canned answer alongsidecallback_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 is502 {"error": "<reason>"}, with a sharedrecord_fallbackemission (component=other,llm_answer → none,outcome=exhausted) perdocs/agents/fallback-telemetry.md.Route registered as
review_status: reviewedinbackend/route_policy_manifest.yaml(not the legacy baseline). It lives in a newbackend/routers/chat_generation.pyrather than insidechat.pyso the persisting and non-persisting surfaces cannot drift into sharing state (and sochat.pystays under its line-count ratchet).Separate commit: the backend async-blocker gate's
has_awaitonly recognizedast.Await, so any endpoint that drives an async generator (async for) or an async context manager was reported asno_await_should_be_defeven though it cannot be a plaindef. 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 thePOST /v2/messagesSSE call with a singlePOST /v2/chat/generate-replyJSON call:{ text, history: [{ text, sender }], app_id? }200 { text, app_id }— usetextas the draft502 { detail: { error } }— treat as a generation failure, never as draft text; the existing WindowsrecordFallbackstill covers the switch to the non-grounded desktop completion providerNo SSE parsing, no base64
done:decoding, and noerror:frame handling remain on the caller side.Verification
backend/tests/unit/test_chat_generate_reply_stateless.py— 3 tests, all through the realrouters.chatFastAPI app via the existing chat router harness (production behavior through a controllable seam, not a source scrape):chat_db.add_message,add_message_to_chat_session,get_chat_session,record_chat_quota_question,llm_executor.submitall uncalled;chat_sessionpassed asNonerecord_fallbackwithoutcome=exhausted)/v2/messagesstill persists the human turn and records its quota questionchat_db.add_message(uid, messages[-1].model_dump())back into the handler fails 2 of the 3 tests withAssertionError: Expected 'add_message' to not have been called. Called 1 times.; reverted.backend/test.shon the changed files andmake preflightpass.Failure-Class: none
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-replyin a dedicatedchat_generationrouter so automated drafting (e.g. AI clone) can run the sameexecute_chat_streampath asPOST /v2/messageswithout persisting turns, touching chat sessions, recording quota questions, or running goal extraction. Callers sendtext, optionalhistory, and optionalapp_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_fallbackis emitted on exhaustion.New Pydantic types
GenerateReplyRequest/GenerateReplyResponseback the API. The route is wired inmain.pyand documented inroute_policy_manifest.yaml(Firebase auth,chat:send_messagerate limit,exact_chat_owner). Chat quota is still enforced viaenforce_chat_quota.scan_async_blockersnow treatsasync forandasync withas real suspension so streaming endpoints are not misclassified asno_await_should_be_def. Unit tests cover stateless behavior, error contract, and that/v2/messagesstill persists.Reviewed by Cursor Bugbot for commit 7b648e3. Configure here.