# Fix RefCell panic in cloud model token counting \(\#54188\) · gitcafe/zed

[View on GitCafe](https://git.cafe/gitcafe/zed/commit/76aab0c35ca9b049fed1ec3d07702b5bbb24faed)

Repository: [gitcafe/zed](https://git.cafe/gitcafe/zed)

Visibility: public

Requested revision: 76aab0c35ca9b049fed1ec3d07702b5bbb24faed

Requested commit: 76aab0c35ca9b049fed1ec3d07702b5bbb24faed

Commit: 76aab0c35ca9b049fed1ec3d07702b5bbb24faed

Tree: 491fa9ec6077ded88045fe645e0caa313e0e1df7

Author: Richard Feldman

Committer: GitHub

## Message

```
Fix RefCell panic in cloud model token counting (#54188)

Fixes #54140

When `RulesLibrary::count_tokens` calls
`CloudLanguageModel::count_tokens` for Google cloud models, it does so
inside a `cx.update` closure, which holds a mutable borrow on the global
`AppCell`. The Google provider branch then called
`token_provider.auth_context(&cx.to_async())`, which created a new
`AsyncApp` handle and tried to take a shared borrow on the same
`RefCell` — causing a "RefCell already mutably borrowed" panic.

This only affects Google models because they are the only provider that
counts tokens server-side via an HTTP request (requiring
authentication). The other providers (Anthropic, OpenAI, xAI) count
tokens locally using tiktoken, so they never call `auth_context` during
`count_tokens`.

The fix makes `CloudLlmTokenProvider::auth_context` generic over `impl
AppContext` instead of requiring `&AsyncApp`. This allows the
`count_tokens` call site to pass `&App` directly (which reads entities
without re-borrowing the `RefCell`), while all other call sites that
already pass `&AsyncApp` (e.g. `stream_completion`, `refresh_models`)
continue to work unchanged.

Release Notes:

- Fixed a crash ("RefCell already mutably borrowed") that could occur
when counting tokens with Google cloud language models.
```

## Parents

- [87b47a4b083c754c54f299d890defa7667863dd3](https://git.cafe/gitcafe/zed/commit/87b47a4b083c754c54f299d890defa7667863dd3?format=markdown)

[Source at this commit](https://git.cafe/gitcafe/zed/tree/76aab0c35ca9b049fed1ec3d07702b5bbb24faed?format=markdown)
