Skip to content

fix(workspace): thread titles authenticate as the agent, not as the instance (#2766) - #2768

Merged
vybe merged 1 commit into
devfrom
fix/2766-title-auth-follows-agent
Sep 14, 2026
Merged

vybe merged 1 commit into
devfrom
fix/2766-title-auth-follows-agent

Conversation

@dolho

@dolho dolho commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

Fixes #2766

The defect

_resolve_title_auth preferred the instance-wide Anthropic API key outright and only fell back to the agent's subscription. On a fleet where every agent runs on a Claude subscription, thread titles were billed to — and gated on — a console account no agent was assigned. An unfunded or revoked instance key then broke a Workspace feature for agents that were otherwise completely healthy.

Same class as #2114 (a stale ANTHROPIC_API_KEY shadowing CLAUDE_CODE_OAUTH_TOKEN on the agent side), one layer up on the backend.

The change

The credential now follows the agent, matching how its chat is already billed. The mode comes from subscription_service.derive_auth_mode — the platform's one auth-mode derivation (#471) — rather than a second answer to "what is this agent authenticated as":

mode credential
subscription the agent's own OAuth token (Messages-API beta header)
api_key the instance key
not_configured none — the derived title stands

A subscription-mode agent whose token cannot be read returns None rather than falling through to the instance key. Falling through is precisely the shadowing this fixes: a key the agent was never assigned is not a credential it holds, so a missing token means "no credential for this agent", not "use someone else's".

Second half of the issue — a non-200 now records the upstream reason instead of the bare status:

before:  HTTP 400
after:   HTTP 400 · invalid_request_error · Your credit balance is too low...

HTTP 400 alone reads as a transport fault and sends the operator after the wrong thing. Only the API's own error.type and error.message are used — never the raw body — and the phrase is scrubbed for credential-shaped text before it reaches the operator-visible health record.

Validated on a live instance

Probed the real resolver in-container against real DB state, on an instance with one subscription-mode agent and one api_key-mode agent. Repro step 1 from the issue — storing an unfunded instance key — then flipping only the code:

instance key stored: True        (unchanged across both probes)

                     BEFORE (dev)                AFTER (this branch)
analyst-demo    ->   INSTANCE KEY (x-api-key)    SUBSCRIPTION (Bearer)
trinity-system  ->   INSTANCE KEY (x-api-key)    INSTANCE KEY (x-api-key)

analyst-demo has a subscription with a present token and was still resolving to the unfunded instance key — the reported defect, reproduced. trinity-system has no subscription, so it is genuinely api_key-mode and is unchanged, which is the half that must not regress.

Instance restored afterwards: test key deleted, patched file reverted byte-for-byte, backend restarted on original code, /health green.

Unit tests

11 tests. Reverting only the precedence (keeping the new helper defined so the module still imports) fails exactly the two behavioural regressions plus the derivation guard, and leaves the other eight green — including the api_key-mode path:

FAILED test_a_subscription_agent_uses_its_own_subscription_even_when_an_instance_key_exists
FAILED test_a_subscription_agent_with_an_unreadable_token_does_not_borrow_the_instance_key
FAILED test_the_mode_comes_from_the_platforms_one_derivation
3 failed, 8 passed        ->  with the fix: 11 passed

Note on an unrelated flaky suite

test_2638_subscription_switch_on_turn.py is flaky on origin/dev independently of this change. The same -k selection gives 3 / 3 / 0 failures across three runs with this branch's code entirely absent, and 3 / 0 / 10 / 5 with it; it passes standalone (54/54) both ways. I nearly attributed it to this change on a single-run comparison — filing it separately rather than papering over it here.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Q19uRCksdn4DiRAJ55rfpZ

…nstance (#2766)

`_resolve_title_auth` preferred the instance-wide Anthropic API key outright
and only fell back to the agent's subscription. On a fleet where every agent
runs on a Claude subscription, thread titles were therefore billed to — and
gated on — a console account no agent was assigned, so an unfunded or revoked
instance key broke a Workspace feature for agents that were otherwise
completely healthy. The reported symptom is HTTP 400 "credit balance is too
low" on every attempt, the generator latching to `failing`, and every new chat
keeping its first-message fallback title.

The credential now FOLLOWS THE AGENT, matching how its chat is already billed.
The mode comes from `subscription_service.derive_auth_mode` — the platform's
one auth-mode derivation (#471) — rather than a second answer to "what is this
agent authenticated as": subscription -> its own OAuth token; api_key -> the
instance key; not_configured -> no credential and the derived title stands.

A subscription-mode agent whose token cannot be read returns None rather than
falling through to the instance key. Falling through is precisely the
shadowing this fixes: a key the agent was never assigned is not a credential it
holds, so a missing token means "no credential for this agent", not "use
someone else's". Same class as #2114 on the agent side, one layer up.

Second half of the issue: a non-200 now records the upstream reason rather than
the bare status. `HTTP 400` alone reads as a transport fault and sends the
operator after the wrong thing; `HTTP 400 · invalid_request_error · Your credit
balance is too low...` points at billing. Only the API's own `error.type` and
`error.message` are used, never the raw body, and the phrase is scrubbed for
credential-shaped text before it reaches the operator-visible health record.

Verified: reverting ONLY the precedence (keeping the new helper defined so the
module still imports) fails exactly the two behavioural regressions plus the
derivation guard, and leaves the other eight green — including the api_key-mode
path, which must keep working unchanged.

Note on the suite: `test_2638_subscription_switch_on_turn.py` is flaky on
`origin/dev` independently of this change — the same selection gives 3/3/0
failures across three runs with this branch's code entirely absent, and 3/0/10/5
with it. It passes standalone both ways. Filed separately; not addressed here.

Fixes #2766

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Q19uRCksdn4DiRAJ55rfpZ
@dolho

dolho commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

Review: /review + /validate-pr

Self-review, so the goal was to find what I got wrong. Three informational findings, two of which I only found by running the code rather than reading it. No critical. Recommendation: APPROVE, with [I1] worth fixing since it silently truncates the thing this PR adds.

/validate-pr — Lane B

Category Status Notes
Lane B client_portal/service.py + a test
Base branch ✅ dev
Closing keyword ✅ Fixes #2766 — same-repo, promotion fires
Size ✅ 2 files, +210/−15
Security greps ✅ clean
Docs ➖ bug fix → descriptive commit only
Test adequacy ✅ 11 tests; reverting only the precedence fails exactly the 2 regressions + the derivation guard, leaving 8 green
Merge gate 🟡 MERGEABLE / BLOCKED — needs a review, no failing checks

/review — structural

Critical: none.

Verified:

  • derive_auth_mode is the platform's one derivation (feat: Subscription usage observability — 5h/7d usage dashboard, per-agent breakdown, and rate-limit event history #471), so this path cannot become a second answer to "what is this agent authenticated as". Pinned by a source guard.
  • The api_key branch is genuinely unchanged — an agent with no subscription still gets x-api-key, tested.
  • The fall-through is closed: a subscription-mode agent with an unreadable token returns None rather than borrowing the instance key, which is the shadowing the PR exists to fix.
  • Live-verified on a dev instance with one subscription agent and one api_key agent: before/after flipped exactly the subscription agent, left the api_key agent alone.

[I1] The failure detail can exceed the health-record cap and be truncated mid-message (Confidence: 9/10)

_record_title_outcome truncates to _TITLE_HEALTH_DETAIL_CHARS = 120. My builder can produce more than that:

"HTTP 400" (8) + " · " (3) + type[:40] + " · " (3) + message[:80]  =  up to 134

Measured worst case 134 chars against a 120 cap — so the tail of error.message is cut. The whole point of this half of the PR is that HTTP 400 · invalid_request_error · Your credit balance is too low… tells the operator it is a billing problem; losing the end of that sentence is a partial loss of the fix.

The real payload from the issue survives (invalid_request_error is 21 chars, so the message gets ~88 of its 120), but a longer upstream type eats into it. Cheapest fix is to size the message slice against the remaining budget rather than a fixed 80, or to trim the type harder — the type is the machine-readable half and the message is the human half, so the message should win the space.

[I2] The second alternative in the scrub regex is dead (Confidence: 10/10)

re.sub(r"(sk-[A-Za-z0-9_\-]{8,}|sk-ant-[A-Za-z0-9_\-]{8,})", "[redacted]", text)

sk-[A-Za-z0-9_\-]{8,} already matches every sk-ant-… string, because ant-… is alnum-plus-dash. I checked for any string the second branch catches and the first does not: none. Alternation is ordered, so branch 1 always wins.

Harmless — the scrubbing works, and sk-ant-oat01-… subscription tokens are redacted (verified). But a reader will assume the second branch exists because something needs it. It should be one pattern, or the second branch should be the one that is actually narrower.

Worth noting what the regex does not cover: a bare oat-… token with no sk- prefix. Trinity's stored OAuth tokens are sk-ant-oat01-, so they are covered — but the redaction is prefix-shaped, not exhaustive, and that is the honest description of it.

[I3] The api_key path now makes a DB read it did not before (Confidence: 8/10)

Inverting the precedence means db.get_agent_subscription_id(agent_name) runs first, always — including on an install where every agent is api_key-mode and the old code returned after one settings read with no DB access at all.

One indexed lookup per title generation, on a path that is about to make an HTTPS call to Anthropic, so the cost is noise. Naming it because it is a real behavioural change that the commit message does not mention, and because it is the mirror of the same observation on #2764: both fixes moved work onto a path that previously had none.

Cross-PR note

[I3] here and [I1] on #2764 are the same shape — a correctness fix that quietly adds a call to a hot-ish path. Neither matters at current scale. Worth knowing they both landed in the same week if anyone later profiles sync or title generation.

🤖 Generated with Claude Code · https://claude.ai/code/session_01Q19uRCksdn4DiRAJ55rfpZ

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

merge-train: batch validated on train/20260914-1332

@vybe
vybe merged commit 27282ed into dev Sep 14, 2026
25 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants