Skip to content

fix(backend): admit the shipped task-extraction prompt into settings sync (#11481) - #11580

Draft
RatnamOjha wants to merge 2 commits into
BasedHardware:mainfrom
RatnamOjha:fix/task-assistant-prompt-bound
Draft

RatnamOjha wants to merge 2 commits into
BasedHardware:mainfrom
RatnamOjha:fix/task-assistant-prompt-bound

Conversation

@RatnamOjha

@RatnamOjha RatnamOjha commented Aug 14, 2026 •

Copy link
Copy Markdown
Collaborator

What

TaskAssistantSettings.analysis_prompt was 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.promptForSync omits it from the settings PATCH to preserve partial-update semantics, so the field simply never arrives:

// desktop/macos/Desktop/Sources/ProactiveAssistants/Services/SettingsSyncManager.swift:212
let length = prompt.unicodeScalars.count
guard length <= maximumLength else { ... return nil }

For every user still on the default task prompt, the server has held no analysis_prompt at all since at least 2026-06.

Why task gets its own bound

Task is the only shipped default that outgrew 10k. Measured at 66fe4673ce by extracting each defaultAnalysisPrompt literal and counting code points:

assistant shipped default bound
task 13,120 20,000
memory 6,262 10,000
insight (wire key advice) 3,576 10,000
focus ships no default 10,000

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:

  1. this change — backend accepts up to 20k
  2. prod backend deploy
  3. client constant raised in a desktop release

Raising the client constant first would make every user on the default start sending a 13.1k analysis_prompt that 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_length is 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_prompt now parses each assistant's real defaultAnalysisPrompt literal out of the Swift sources and validates it through the real UpdateAssistantSettingsRequest model. It is behavioral — real Pydantic validation on the real shipped text — not a source scrape.

Verification

$ cd backend && python -m pytest tests/routers/test_users.py -q
25 passed

$ python -m pytest tests/unit/test_app_client_openapi_compatibility.py tests/routers/test_users.py -q
45 passed

Proof the new test catches the reported defect — with the bound reverted to 10000, it fails on task only:

E  String should have at most 10000 characters [type=string_too_long,
   input_value='You are a task commitmen...l_system / project_tool']
FAILED tests/routers/test_users.py::test_backend_bounds_admit_every_shipped_desktop_prompt[task-...]
1 failed, 2 passed

Effective bounds read off model_fields after the change, confirming the other three are untouched:

FocusAssistantSettings     max_length=10000
TaskAssistantSettings      max_length=20000
AdviceAssistantSettings    max_length=10000
MemoryAssistantSettings    max_length=10000

Note on the OpenAPI spec

docs/api-reference/app-client-openapi.json carries the single 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. 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

Review in cubic

…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

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

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])

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: 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>

@RatnamOjha

Copy link
Copy Markdown
Collaborator Author

Marking this draft: Public Developer API contract fails, and I do not think it should be forced green. The gate is right and it exposes a constraint the issue did not account for.

check_app_client_openapi_compatibility.py rejects the change on the response side:

BREAKING paths./v1/users/assistant-settings.get.responses.200...properties.task.anyOf[0]
BREAKING paths./v1/users/assistant-settings.patch.responses.200...properties.task.anyOf[0]
Version the endpoint instead of breaking a released app-client contract.

That is _compare_bound doing exactly what it should. For direction == 'response' an upper bound breaks when new_value > old_value: released clients were told analysis_prompt is at most 10,000 characters, and widening it means the server can now return something they were promised it would not.

The reason it cannot be worked around by splitting request and response models:

  • AssistantSettingsResponse extends UpdateAssistantSettingsRequest, so both surfaces share one TaskAssistantSettings schema. Splitting them so only the request widens leaves the response validating at 10,000 — and since the endpoint declares response_model=AssistantSettingsResponse, a stored 13.1k prompt then fails response validation and 500s the GET, which is worse than today's silent non-sync.
  • Dropping maxLength from the response instead also trips the same rule (new_value is None breaks a released response bound).

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:

  1. Trim TaskAssistantSettings.defaultAnalysisPrompt under 10,000 — the alternative Shipped default task prompt (13.7k chars) exceeds the 10k assistant-prompt sync bound, so it never syncs #11481 already mentions. No contract change at all. It is 13,120 code points today, so it needs ~3.2k trimmed, and that is a prompt-behavior change I should not make unilaterally.
  2. Version the endpoint (/v2/users/assistant-settings) and widen the bound there, leaving v1 on 10,000.

Everything else in the PR stands and is independent of which path you choose:

  • test_backend_bounds_admit_every_shipped_desktop_prompt is the missing regression test. The old ..._accepts_shipped_default_size_... compared the bound against itself and passed at any value, which is why this went unnoticed since 2026-06. The new one parses each assistant's real defaultAnalysisPrompt literal out of the Swift sources and validates it through the real request model.
  • Measurements at 66fe4673ce: task 13,120 code points, memory 6,262, insight 3,576, focus ships no default. Task is the only one over.

Happy to redo this as either path — say which and I will push it. Leaving it draft rather than green-by-force.

@RatnamOjha
RatnamOjha marked this pull request as draft August 14, 2026 19:49
@Git-on-my-level

Copy link
Copy Markdown
Member

Verified this independently before it waits on a maintainer call — the analysis holds up end to end.

Measurements reproduced exactly. I re-extracted each defaultAnalysisPrompt literal from the head tree and measured Unicode code points: task 13,120 (TaskExtraction/TaskAssistantSettings.swift), memory 6,262 (MemoryExtraction/MemoryAssistantSettings.swift), insight 3,576 (Insight/InsightAssistantSettings.swift), and confirmed focus ships no default (no Assistants/Focus directory exists). The silent-failure mechanics also check out: SettingsSyncManager.promptForSync returns nil for anything over the bound, and the client pins task at 10_000 (TaskAssistantSettings.swift:119) — so the shipped default has indeed never synced.

The structural blocker is real. AssistantSettingsResponse(UpdateAssistantSettingsRequest) in backend/routers/users.py means request and response share one TaskAssistantSettings schema, so widening only the request side would leave response validation at 10k and 500 the GET for a stored 13.1k prompt. Splitting the models does not avoid the contract break.

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 docs/api-reference/app-client-openapi.json line (single maxLength occurrence in the shared TaskAssistantSettings component) is generator-consistent, so the failure is purely the contract decision, not a spec-editing mistake.

The new test is the real regression guard. test_backend_bounds_admit_every_shipped_desktop_prompt parsing the actual Swift literals closes the gap where the old bound test compared the bound against itself and passed at any value.

What is needed now is a product/release decision between the two options already laid out: (1) trim TaskAssistantSettings.defaultAnalysisPrompt under 10,000, or (2) version the endpoint (/v2/users/assistant-settings) and widen there. Neither is something automation should pick — (1) changes assistant prompt behavior and (2) adds a public API surface — so flagging for human maintainer review on that choice. Thanks for the unusually rigorous draft note; the sequencing rationale (backend bound → deploy → client constant) is exactly right.


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

@Git-on-my-level Git-on-my-level added needs-maintainer-review Needs a human maintainer to sign off before merge backend Backend Task (python) labels Aug 14, 2026
kodjima33 pushed a commit that referenced this pull request Aug 16, 2026
… 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 aryanorastar 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.

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.

This branch has not been deployed

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

Labels

backend Backend Task (python) needs-maintainer-review Needs a human maintainer to sign off before merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants