# Run a Long Task in the Background in a Reflex App

Yes. An agent moves a slow Reflex event handler to a background task with an async client and a stop button, tests it in a browser against a stub, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-background-tasks/reflex/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the state class to find what actually blocks. In an app like reflex-dev/reflex-chat, `chat/state.py` defines `State` with a private `_chats` dictionary, `current_chat` and a `processing` flag, and the form in `chat/components/chat.py` submits to `State.process_question`. That handler delegates to `openai_process_question`, an `async` generator that appends the question, sets `processing`, and then creates a streaming completion with the synchronous `OpenAI()` client and walks it in a plain `for` loop, yielding after each chunk. Two things follow. The loop waits on the network inside an `async` function without awaiting, so the server's event loop is held between chunks for every connected user. And because the handler is an ordinary event, the user's other events, `set_chat`, `delete_chat` and `create_chat` from `chat/components/navbar.py`, queue behind it until the answer finishes. The Send button is already bound to `processing` for `loading` and `disabled`. `requirements.txt` asks for `reflex>=0.7.11` and `openai>=1.78.1`.

The change keeps the form and moves the work. `process_question` stays the form's target and validates the input; the streaming handler becomes a background task, declared with `@rx.event(background=True)`. A background task does not hold the state lock while it waits, so every read or write of state goes inside an `async with self:` block: one block to append the question and set `processing`, one short block per chunk to extend the last answer, one at the end to clear the flag. The agent captures the chat name inside the first block and writes to that chat afterwards, since `current_chat` can now change while an answer streams and the current code indexes `self._chats[self.current_chat]` on every chunk. The client becomes `AsyncOpenAI` with `await` on the create call and `async for` over the stream, which is what frees the event loop.

With the lock released, cancelling becomes possible, so the agent adds it. A `stop` event sets `processing` to false, the loop checks the flag inside its per-chunk block and breaks, and the action bar shows a Stop button in place of Send while an answer is streaming. Deleting a chat mid-answer is handled the same way: the loop checks that its chat still exists before writing. A `try` and `finally` around the stream clears `processing` if the request fails, so an error from the API cannot leave the Send button disabled, which the present code would do.

It tests against a stand-in, not a paid API. In its sandbox the agent starts a small local server that speaks the streaming chat completions format slowly, one word every half second, and points the client at it with `OPENAI_BASE_URL`; the app only requires that `OPENAI_API_KEY` is set to something. It runs `reflex run`, opens the app in a browser, asks a question, and while the answer is still arriving creates a second chat and switches to it, switches back, presses Stop, and deletes a chat mid-stream, taking a screenshot at each step. It runs the three jobs `.github/workflows/ci.yml` defines, `pyright .`, Ruff and `reflex export`, and reports each result.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "The Linear issue after this prompt asks for the chat to stay usable while an answer is streaming. Read rxconfig.py, requirements.txt, chat/chat.py, chat/state.py, chat/components/chat.py, chat/components/navbar.py and .github/workflows/ci.yml first. Turn the streaming handler in chat/state.py into a Reflex background task declared with rx.event(background=True), with every state read and write inside an async with self block, and keep process_question as the form's target. Capture the chat name at the start and write to that chat, so switching chats mid-answer does not move the text. Replace the synchronous OpenAI client with AsyncOpenAI and iterate the stream with async for. Add a stop event and a Stop button shown while processing, make the loop stop when the flag clears or its chat is deleted, and clear processing in a finally block. Do not call the real API: start a local stub that streams a chat completion slowly and point OPENAI_BASE_URL at it. Run the app, and in a browser ask a question, then during the answer create and switch chats, switch back, press Stop, and delete a chat, with a screenshot of each. Run pyright, Ruff and reflex export as CI does. Open a pull request with the screenshots, the stub's request log and the check results.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

A pull request that changes `chat/state.py` and the action bar in `chat/components/chat.py`. The description walks through the browser session with screenshots: the answer still growing in its own chat while a second chat is open, the Stop button ending a stream partway, and a chat deleted mid-answer without an error. It includes the stub's log of the one request each question produced and the output of `pyright .`, Ruff and `reflex export`.

A reviewer checks that no state access sits outside an `async with self:` block, that the lock is held only for the append and never across an `await` on the network, and that the stopped answer is kept as partial text and not discarded. They try it once with a real key before merging, since the stub proves the concurrency and not the provider's behaviour.

## Run it on every Linear issue labelled ux

Create an automation in the Project that holds the app's repository, with this prompt and a `linear` trigger whose `labels` name the label your team puts on interface complaints. When a member of your Rush org adds it to an issue, a run starts with the issue appended after the prompt. The prompt names the files and the checks; the issue supplies the symptom. The automation's runner needs a Linear connection, made in the console under Settings → Connections.

Each labelled issue starts its own run in its own sandbox, up to the automation's `max_runs_per_hour`, and an issue past that waits as a `queued` run. A state trigger in `plan` mode is the cautious variant: it starts a read-only run that posts its plan as a comment on the issue, and a person moves the issue on when the plan looks right.

## Why run it on Rush?

Concurrency changes are the ones a diff cannot vouch for. Whether the interface stays responsive during a stream, and whether text lands in the right chat after a switch, is only visible with a slow answer in flight and a second action on top of it. The agent sets that up in its own sandbox with a stub it controls, drives a real browser, and keeps the screenshots, the server log and the stub's log in the run's record.

No model key is spent and none is needed in the Project, because the stub stands in for the provider. The same request applies to any slow handler in a Reflex app, such as a report export or a long database job: each run reads that handler, finds what it holds while it waits, and moves only that.

## Frequently asked questions

### Why does the interface freeze while the answer streams?

Two reasons in this app. The handler iterates a synchronous client's stream inside an `async` function, which holds the server's event loop between chunks, and an ordinary event handler keeps the user's state locked until it finishes, so other clicks queue. A background task with an async client removes both.

### What is different about a background task in Reflex?

It is an `async` event handler declared with `background=True` that runs without holding the state lock. In exchange, state may only be changed inside `async with self:`, a read outside it may be stale, and each block should be short. The pull request keeps one block per chunk for that reason.

### Can several questions run at once after this?

Not by default. The Send button stays disabled while `processing` is true, so one answer streams per user at a time. What changes is that everything else keeps working during it. Allowing one stream per chat is a follow-up that needs a flag per chat.

### Does the test call OpenAI?

No. The run points the client at a local stub through `OPENAI_BASE_URL` and sets a placeholder key, so it can make the answer as slow as the test needs and spend nothing. The pull request says so and suggests one manual try with a real key before merging.

## More Reflex jobs

- [Add Chat Export to a Reflex Chat App](https://getrush.ai/run/add-chat-export/reflex/)
- [Add Dark Mode to a Reflex App](https://getrush.ai/run/add-dark-mode/reflex/)
- [Add Dependabot to a Reflex App](https://getrush.ai/run/add-dependabot/reflex/)

## More jobs like this: Turn a Linear label into a PR

- [Add Biometric Login to an Expo App from a Linear Issue](https://getrush.ai/run/add-biometric-auth/expo/)
- [Add Fingerprint and Face ID Login to a Flutter App](https://getrush.ai/run/add-biometric-auth/flutter/)
- [Add Biometric Login to a React Native App](https://getrush.ai/run/add-biometric-auth/react-native/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
