# Warn Before Closing or Leaving a Form With Unsaved Changes

Yes. An agent reads isDirty from React Hook Form, asks before a dirty drawer closes, blocks route changes and tab close while dirty, tests it and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-unsaved-changes-warning/react-hook-form/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads how forms are built and closed. In a React and Vite app laid out like alan2207/bulletproof-react's `apps/react-vite`, `src/components/ui/form/form.tsx` exports a `Form` that calls `useForm({ ...options, resolver: zodResolver(schema) })` and renders `children(form)`, so a feature component sees `register` and `formState` but nothing outside the render function does. `src/components/ui/form/form-drawer.tsx` wraps a Radix dialog from `src/components/ui/drawer/drawer.tsx`: `useDisclosure` holds `isOpen`, `onOpenChange` calls `close()` whenever Radix asks, which is on the overlay click, the Escape key and the `X` button `DrawerContent` renders, and an effect closes the drawer when `isDone` turns true. Four features use that drawer, `create-discussion.tsx`, `update-discussion.tsx`, `create-comment.tsx` and `update-profile.tsx`, and `update-discussion.tsx` loads `defaultValues` from `useDiscussion`. A person who types a body and clicks outside loses it with no question.

The change starts in `Form`. It gains an optional `onDirtyChange` callback that an effect calls with `form.formState.isDirty` whenever it changes, and nothing else about the component moves, so the eight files that render it compile unchanged. `FormDrawer` gains an optional `isDirty` prop: when `onOpenChange` is asked to close while `isDirty` is true, it opens a confirmation instead, built from the existing `ConfirmationDialog` in `src/components/ui/dialog/confirmation-dialog/`, with the title "Discard changes?", a danger icon and a confirm button that calls `close()`. Cancel returns to the drawer with the typed values intact, because the drawer stays mounted; and `isDone` still closes it with no question, since the submit just succeeded. Each of the four feature components keeps a `dirty` state fed by `onDirtyChange` and passes it to `FormDrawer`, which is the only edit they need.

Leaving the page gets the same treatment through a hook, `src/hooks/use-unsaved-changes.ts`, that takes a boolean. While it is true the hook registers a `beforeunload` listener that calls `preventDefault` so the browser shows its own leave dialog on tab close or reload, and calls `useBlocker` from `react-router`, which `src/app/router.tsx` enables by building the app with `createBrowserRouter`, so an in-app navigation while the drawer is dirty is held until the person confirms in the same dialog. `FormDrawer` calls the hook with its `isDirty` prop, so a feature component gets both protections by passing one boolean.

Tests go next to the existing ones in `src/components/ui/form/__tests__/form.test.tsx`, which already render a `Form` with `rtlRender` and drive it with `userEvent`. The agent adds a test that types into the field, presses Escape, expects the "Discard changes?" dialog and that `handleSubmit` was not called, and a second that confirms the discard and expects the drawer gone. For the route guard it uses `renderApp` from `src/testing/test-utils.tsx`, which builds a memory router, renders the drawer beside a link, types, clicks the link and expects the dialog rather than the new route. In the sandbox it runs `yarn install`, `yarn test`, `yarn lint`, `yarn check-types` and `yarn build`, and opens the app with API mocking on, as `.env.example` sets it, to walk through the drawer, the overlay click and a reload in its browser.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Warn before closing or leaving a form with unsaved changes in apps/react-vite. Read src/components/ui/form/form.tsx, src/components/ui/form/form-drawer.tsx, src/components/ui/drawer/drawer.tsx, src/components/ui/dialog/confirmation-dialog/confirmation-dialog.tsx, src/hooks/use-disclosure.ts, src/app/router.tsx and the four components that use FormDrawer first. Give Form an optional onDirtyChange callback driven by formState.isDirty. Give FormDrawer an optional isDirty prop: when it is true and Radix asks to close, show a Discard changes confirmation built from ConfirmationDialog instead; isDone still closes without asking. Add a useUnsavedChanges hook that registers beforeunload and calls useBlocker from react-router while dirty, and call it from FormDrawer. Wire the four feature components. Add tests beside form.test.tsx for the dialog, the discard and the blocked navigation. Run yarn test, yarn lint, yarn check-types and yarn build, quote the results and open a pull request.",
  "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

What comes back is a pull request that changes `form.tsx` and `form-drawer.tsx`, adds `src/hooks/use-unsaved-changes.ts`, edits the four feature components by a few lines each, and extends `form.test.tsx`. No change to the drawer primitive, the dialog primitive or the router, which keep their current API.

The description quotes the Vitest summary with the new tests named, the lint, typecheck and build results, and a short walk through the agent's own browser session: typing in the Update Discussion drawer, clicking the overlay, seeing the dialog, cancelling and finding the text still there. The run's record keeps that session and every command's output.

Before merging, a reviewer decides the wording of the dialog, whether the login and register forms, which do not use `FormDrawer`, should get the route guard as well, and whether a successful submit should also clear the dirty flag through `reset` so a reopened drawer starts clean. The agent leaves the three as they are and names them.

## Run it on every Linear issue labelled ux

In the Project that holds the repository, create an automation with a general version of this page's prompt and a `linear` trigger on `linear.issue.labeled` with `ux` in its `labels`. The trigger puts the issue after the saved prompt and fills nothing in, so the prompt says: read the issue that follows, make the form behaviour change it describes with the existing `Form`, `FormDrawer` and dialog components, test it beside the existing form tests, and open a pull request that links the issue. It needs the runner's Linear connection, made in the console under Settings → Connections, and fires only when someone in your Rush org adds the label.

A support engineer who files "lost my comment when I clicked outside the drawer" and adds the label starts one run; an issue about the profile form starts another, each on its own branch with its own pull request.

## Why run it on Rush?

Proving an unsaved-changes guard means doing the things that lose data, clicking outside, pressing Escape, following a link and reloading, in a running app with mocked data, and then checking the typed text is still there. The sandbox runs the app with API mocking, drives those actions in its own browser, and keeps the session, so the pull request opens with the walkthrough and the tests in it.

The run's record holds the test output and the browser session, so a reviewer watches the dialog appear rather than reading that it does. Across a team's React apps the same request runs at once, one sandbox each, and each pull request names that app's own forms and the components it wired.

## Frequently asked questions

### Why not block on every close, dirty or not?

A dialog on an untouched form trains people to click through it. `formState.isDirty` is true only after a value differs from `defaultValues`, which is exactly the case where closing loses something.

### Does the browser show my dialog on tab close?

No. Browsers show their own generic leave dialog when a `beforeunload` listener calls `preventDefault`, and ignore custom text. The custom "Discard changes?" dialog appears for the drawer close and for in-app navigation, where the app controls the screen.

### What about forms that are not in a drawer?

`LoginForm` and `RegisterForm` render `Form` directly. They can call `useUnsavedChanges` themselves with the same `onDirtyChange` wiring; the agent leaves them out and names them, since losing a half-typed login is a smaller cost than a half-written discussion.

### Will the existing form tests keep passing?

Yes. Both props are optional and the dialog only appears when `isDirty` is passed as true, so the two tests in `form.test.tsx`, which render `Form` without a drawer, run as before. The new tests sit beside them in the same file.

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

- [Add updatedAt Columns That Actually Update to a Drizzle Schema](https://getrush.ai/run/add-updated-at-timestamps/drizzle/)
- [Fix updatedAt Columns That Never Update in a Prisma Schema](https://getrush.ai/run/add-updated-at-timestamps/prisma/)
- [Add updated_at Timestamps to SQLModel Tables](https://getrush.ai/run/add-updated-at-timestamps/sqlmodel/)
- [Add Muting Users to a Rails App from a Linear Issue](https://getrush.ai/run/add-user-mute/rails/)
- [Add a User Profile Page to a Filament Panel](https://getrush.ai/run/add-user-profile-page/filament/)
- [Add User Registration to a Symfony App from a Linear Issue](https://getrush.ai/run/add-user-registration/symfony/)

## 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/)
