Repository navigation
fix(backend): admit the shipped task-extraction prompt into settings sync (#11481) - #11580
RatnamOjha wants to merge 2 commits into
Conversation
…sync `TaskAssistantSettings.analysis_prompt` was bounded at 10,000 code points while the desktop client's shipped default task prompt is 13,120, so that prompt has never synced. The mismatch is silent by construction: `SettingsSyncManager. promptForSync` omits an oversized prompt from the PATCH to preserve partial semantics, so the server never 422s — the field simply never arrives, for every user still on the default. Give task its own bound (20,000) rather than raising the shared one. Task is the only shipped default that outgrew 10k; focus, advice and memory ship 0, 3,576 and 6,262 code points respectively and stay on the shared bound. This mirrors the client, which already carries a task-specific `TaskAssistantSettings.maximumSyncedAnalysisPromptLength`. Backend-only on purpose. Raising the client constant first would make every user on the default start sending a 13.1k `analysis_prompt`, which the deployed backend would 422, breaking assistant-settings sync wholesale for that build. The order is: this change -> prod backend deploy -> client constant raised in a desktop release. The desktop tests that pin the client at 10k stay green here. The regression test that would have caught it: the existing backend test named "accepts_shipped_default_size" only compared the bound against itself, so it passed at any value. `test_backend_bounds_admit_every_shipped_desktop_prompt` now parses each assistant's real `defaultAnalysisPrompt` literal out of the Swift sources and validates it through the real `UpdateAssistantSettingsRequest` model. Verification: cd backend && python -m pytest tests/routers/test_users.py -q -> 25 passed With the bound reverted to 10000, the new test fails on task only: "String should have at most 10000 characters [type=string_too_long]" (advice and memory still pass), confirming it catches the reported defect. Refs: BasedHardware#11481 Failure-Class: none
Focus, advice and memory repeated the literal `10000` while task referenced a named constant. That duplication is what let the task bound drift out of sync with the prompt the client actually ships without anything naming the contract. Behavior is unchanged: focus, advice and memory still validate at 10,000 and only task carries the raised bound. Verified by reading `model_fields` off each model after the change: FocusAssistantSettings max_length=10000 TaskAssistantSettings max_length=20000 AdviceAssistantSettings max_length=10000 MemoryAssistantSettings max_length=10000 The constants moved above `FocusAssistantSettings` so the first consumer is declared after them. `docs/api-reference/app-client-openapi.json` carries the one exported bound that changed. It was hand-patched rather than regenerated: `scripts/export_openapi.py` on this machine also rewrites `format: binary` to `contentMediaType` and adds `ctx`/`input` to `ValidationError`, which is local pydantic/fastapi version drift unrelated to this change. Refs: BasedHardware#11481
There was a problem hiding this comment.
1 issue found across 3 files
Confidence score: 4/5
- In
backend/tests/routers/test_users.py, the Swift prompt parsing logic assumes string literals never contain escape sequences or\(...)interpolation, so a future default prompt change could make the Python parser misread content and produce brittle or misleading test results; add an explicit guard/assertion for unsupported Swift string features or switch to a parser that handles escapes/interpolation safely.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="backend/tests/routers/test_users.py">
<violation number="1" location="backend/tests/routers/test_users.py:461">
P2: The test parsing Swift prompts silently assumes the literals contain no `\(...)` interpolation or escape sequences, but nothing enforces that. If a future Desktop default gains `\n`, `\"`, or interpolation, Python includes the literal backslash/escape text so the parsed length no longer matches the real synced prompt, and the guard either validates a wrong size or fails spuriously. Add a loud assertion (e.g. no `\` in the reconstructed content, with a message to rework the parser) so the contract can't degrade quietly.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| closing = next(i for i in range(opening + 1, len(lines)) if lines[i].strip() == '"""') | ||
| indent = len(lines[closing]) - len(lines[closing].lstrip()) | ||
|
|
||
| return '\n'.join(line[indent:] if len(line) >= indent else line.lstrip() for line in lines[opening + 1 : closing]) |
There was a problem hiding this comment.
P2: The test parsing Swift prompts silently assumes the literals contain no \(...) interpolation or escape sequences, but nothing enforces that. If a future Desktop default gains \n, \", or interpolation, Python includes the literal backslash/escape text so the parsed length no longer matches the real synced prompt, and the guard either validates a wrong size or fails spuriously. Add a loud assertion (e.g. no \ in the reconstructed content, with a message to rework the parser) so the contract can't degrade quietly.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/tests/routers/test_users.py, line 461:
<comment>The test parsing Swift prompts silently assumes the literals contain no `\(...)` interpolation or escape sequences, but nothing enforces that. If a future Desktop default gains `\n`, `\"`, or interpolation, Python includes the literal backslash/escape text so the parsed length no longer matches the real synced prompt, and the guard either validates a wrong size or fails spuriously. Add a loud assertion (e.g. no `\` in the reconstructed content, with a message to rework the parser) so the contract can't degrade quietly.</comment>
<file context>
@@ -430,23 +444,54 @@ def _failing_iter(_uid, *, include_archive=True):
+ closing = next(i for i in range(opening + 1, len(lines)) if lines[i].strip() == '"""')
+ indent = len(lines[closing]) - len(lines[closing].lstrip())
+
+ return '\n'.join(line[indent:] if len(line) >= indent else line.lstrip() for line in lines[opening + 1 : closing])
+
+
</file context>
|
Marking this draft:
That is The reason it cannot be worked around by splitting request and response models:
So there is no non-breaking way to let the server return more than it promised. That leaves the two paths the gate itself names, and both are maintainer calls rather than something I should pick:
Everything else in the PR stands and is independent of which path you choose:
Happy to redo this as either path — say which and I will push it. Leaving it draft rather than green-by-force. |
|
Verified this independently before it waits on a maintainer call — the analysis holds up end to end. Measurements reproduced exactly. I re-extracted each The structural blocker is real. The failing contract gate is correct, not a false positive. Widening a released response bound means the server can now return something released clients were promised it would not — that is a genuine breaking change under any sane compatibility rule, and the hand-edited The new test is the real regression guard. What is needed now is a product/release decision between the two options already laid out: (1) trim by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with |
… hydration (#11481) (#11678) * fix(desktop): distinguish shipped default from oversized user prompts The oversized-prompt protection could not tell text the user wrote from text every install ships, so it defended the shipped default as though it were unsynced user data — and that defence blocks the account's real prompt forever. The shipped task default is 13,120 code points against a 10,000 bound, so on the first settings push `promptForSync` omits it (correct: it cannot be sent) and stamps `unsyncedOversizedOwner.task`. `applyRemotePrompt` then sees "oversized and owned by me" and refuses every remote prompt. A task prompt customised on one Mac can therefore never hydrate onto a Mac still sitting on the default — which is every fresh install, since the getter falls back to the default when nothing is stored. Both functions now take the assistant's `shippedDefault` and use it as the discriminator: oversized + == shipped default -> omit from sync, do NOT claim ownership oversized + != shipped default -> omit from sync, claim ownership (unchanged) and hydration preserves a local prompt only when it is oversized, owner-matched, *and* not the shipped default. The parameter is explicit rather than an assistant-name -> default dictionary so the compiler forces all six call sites to name their default; a lookup table would fail open — straight back to this bug — for an assistant nobody registered. Passing it for insight and memory too means the same defect cannot reappear if either default outgrows its bound; both are well under it today (3,576 and 6,262 code points). Reset semantics, chosen deliberately: "Reset to Default" means this device has no custom local opinion, so account state may hydrate again. That matters because the reset path re-stamps ownership — `TaskPromptEditorView.resetToDefault()` clears the stored prompt, then assigns the editor's `@State`, which fires `.onChange` and writes the default straight back through the setter, calling `recordLocalPromptOwner`. Comparing against the shipped default survives that; "is the UserDefaults key set?" would not, because after a UI reset the key is present and the stamp restored. Client-only. It needs nothing from the backend: the oversized default is still omitted from the PATCH exactly as before. It neither fixes nor depends on the backend bound mismatch tracked in #11580. Existing test call sites take the new argument; no assertion changed. The `testEachAssistantPromptUsesItsBackendBound` table became a tuple array so the per-assistant default is read without a force unwrap. Verification: xcrun swift build -c debug --package-path Desktop -> Build complete! xcrun swift test --filter APIClientAssistantSettingsTests -> 10 tests, 0 failures swiftlint-wrapper.sh lint -> 0 violations in 1287 files Refs: #11481 Failure-Class: none * test(desktop): cover task prompt sync ownership cases Three cases over the two decisions that were conflated: whether a prompt claims unsynced ownership on push, and whether hydration may overwrite it on pull. fresh install on the shipped default testShippedDefaultIsOmittedFromSyncWithout... reset to default testRemoteHydrationAppliesAfterResetToDefault reset as the editor performs it testRemoteHydrationAppliesAfterTheResetPath... Ownership is asserted through its observable consequence — whether a later pull is allowed to hydrate — rather than by reading the bookkeeping key. That keeps these tests on sync behaviour instead of internals, and avoids inline UserDefaults key literals, which `omi_inline_userdefaults_key` rightly rejects. The remaining matrix rows were already covered and are deliberately not duplicated: a small custom prompt staying server-authoritative (testRemoteHydrationRemainsServerAuthoritativeForSyncableTaskPrompt), an oversized prompt owned by another account still being replaced (testRemoteHydrationReplacesOversizedPromptOwnedByAnotherAccount), and a genuinely user-authored oversized prompt staying protected (testRemoteHydrationPreservesOversizedUnsyncedLocalTaskPrompt). Those three passed before and after and were not touched — they are the guard proving the protection was narrowed, not removed. The editor-path case earns its place beside the direct reset because it exercises the `.onChange` write that re-stamps ownership over the shipped default, which is exactly why the discriminator has to be the prompt text rather than the presence of the UserDefaults key. Red baseline: with the two new conditions removed from SettingsSyncManager (the `shippedDefault` parameter kept so the suite still compiles), these three fail and the other ten pass: testShippedDefaultIsOmittedFromSyncWithoutBlockingLaterHydration testRemoteHydrationAppliesAfterResetToDefault testRemoteHydrationAppliesAfterTheResetPathTheEditorPerforms -> Executed 13 tests, with 3 failures Each restores the stored prompt and auth owner, and runs under a distinct owner id so it cannot inherit a stamp from a sibling test. Verification: xcrun swift test --filter APIClientAssistantSettingsTests -> 13 tests, 0 failures Refs: #11481 * fix(desktop): preserve ownership semantics when restoring prompt test state `withTaskPromptState` restored state in the wrong order. The `defer` assigned `analysisPrompt = originalPrompt` before restoring `authUserId`, and the `analysisPrompt` setter calls `SettingsSyncManager.recordLocalPromptOwner`, which reads `currentOwnerID` — still the test's synthetic owner at that point. Every test using the helper therefore left `assistantPrompt.unsyncedOversizedOwner.task` pointing at "owner-fresh-install", "owner-reset" or "owner-editor-reset" instead of the value it started with, leaking into the app's real UserDefaults and into whichever test ran next. Restoring `authUserId` first means the setter stamps the original owner, which is the state the helper promised to put back. Reported by cubic on #11678. Verification: xcrun swift test --filter APIClientAssistantSettingsTests -> 13 tests, 0 failures Refs: #11481 Failure-Class: none * fix(desktop): remember historically shipped prompt defaults Comparing against the current shipped default only recognises the default this build ships. The reset path persists the default it saw, so once the app ships a new one that stored text stops matching, is reclassified as user-authored, has ownership claimed on the next push, and blocks the account's prompt again — the same defect this PR set out to fix, resurfacing across a version boundary. The classification is now recorded where it is actually known. Every write of a prompt already computes `isCustom`, so `recordLocalPromptOwner` takes that answer and persists it alongside the ownership stamp; `isShippedDefault` then treats a prompt as shipped when the text matches *or* the marker says it did when written. Writing a shipped default also releases any claim the previous value held, since there is no longer unsynced user text to protect. An absent marker means a build older than this one wrote the value, and the bool default of `false` leaves those installs on the text comparison exactly as before — the fallback is the previous behaviour, not a new one. The parameter is required rather than defaulted so all three assistants state their answer at the call site, matching the `shippedDefault` argument already threaded through the sync seams. Scope note: the marker is only consulted for the oversized path, which is where ownership is claimed. Insight and memory ship well under the bound today, so this changes nothing for them until a default grows past it — which is precisely the case it exists to survive. Red baseline — with only the marker consultation removed (text comparison alone, so the change is isolated from the parameter plumbing): testPersistedPreviousShippedDefaultStillHydrates -> Executed 15 tests, with 1 failure The test drives the real order: an older build's write, then this build's push — the push is what re-claims ownership, so a version of the test that skipped it passed either way and proved nothing. It failed to reproduce until that step was added. Reported by cubic on #11678. Verification: xcrun swift test --filter APIClientAssistantSettingsTests -> 15 tests, 0 failures ... plus 3 sibling SettingsSyncManager suites -> 41 tests, 0 failures swiftlint-wrapper.sh lint -> 0 violations, 1287 files Refs: #11481 Failure-Class: none
aryanorastar
left a comment
There was a problem hiding this comment.
Verified on af61b0c (draft).
Raising the task analysis_prompt bound so the shipped TaskAssistant default actually syncs is the right production hole. Do not do it by bumping the unversioned OpenAPI maxLength 10000 → 20000 on GET/PATCH analysis_prompt. Public Developer API contract is red on this SHA for that break.
Please keep the unversioned contract at 10k or version the schema; admit the Swift default without a silent unversioned maxLength change. I am not merging this draft.
What
TaskAssistantSettings.analysis_promptwas bounded at 10,000 code points while the desktop client's shipped default task prompt is 13,120. That prompt has therefore never synced — and never will on any deployed build — because the mismatch is silent by construction.This is the backend half of #11481, and backend-only on purpose.
Why it is silent
An oversized prompt does not 422.
SettingsSyncManager.promptForSyncomits it from the settings PATCH to preserve partial-update semantics, so the field simply never arrives:For every user still on the default task prompt, the server has held no
analysis_promptat all since at least 2026-06.Why task gets its own bound
Task is the only shipped default that outgrew 10k. Measured at
66fe4673ceby extracting eachdefaultAnalysisPromptliteral and counting code points:advice)This mirrors the client, which already carries a task-specific
TaskAssistantSettings.maximumSyncedAnalysisPromptLength. The headroom above 13,120 is for user edits, which write the same field.Sequencing
Order matters and this PR is deliberately step 1 of 3:
Raising the client constant first would make every user on the default start sending a 13.1k
analysis_promptthat the deployed backend still 422s, breaking assistant-settings sync wholesale for that build. The desktop tests that pin the client at 10k (testShippedTaskPromptExceedsBackendBoundAndIsOmittedFromSync,testEachAssistantPromptUsesItsBackendBound) are untouched and stay green.Raising a
max_lengthis backward compatible: every payload valid before is still valid.The regression test
The existing backend test was named
..._accepts_shipped_default_size_...but only compared the bound against itself, so it passed at any value — which is why the defect survived. Each side asserted against its own constant and nothing asserted the contract between them.test_backend_bounds_admit_every_shipped_desktop_promptnow parses each assistant's realdefaultAnalysisPromptliteral out of the Swift sources and validates it through the realUpdateAssistantSettingsRequestmodel. It is behavioral — real Pydantic validation on the real shipped text — not a source scrape.Verification
Proof the new test catches the reported defect — with the bound reverted to 10000, it fails on task only:
Effective bounds read off
model_fieldsafter the change, confirming the other three are untouched:Note on the OpenAPI spec
docs/api-reference/app-client-openapi.jsoncarries the single exported bound that changed. It was hand-patched rather than regenerated:scripts/export_openapi.pyon this machine also rewritesformat: binarytocontentMediaTypeand addsctx/inputtoValidationError, which is local pydantic/fastapi version drift unrelated to this change. Worth a maintainer regenerating on the pinned toolchain if you'd rather have the generated artifact.Line-Count-Exception: backend/routers/users.py | 2174 -> 2180 | two named bounds replacing a duplicated literal, plus the contract comment explaining why a bound may not sit under its assistant's shipped default
Refs: #11481
Failure-Class: none