All jobs

Add Optimistic Updates to a tRPC and Next.js App

Yes. An agent makes a tRPC mutation write into the infinite query cache before the server answers, roll back on error, and opens a PR with a Playwright test.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent reads the mutation and the query it should update before it writes an onMutate. In an app shaped like trpc/examples-next-prisma-starter, package.json pins @trpc/client, @trpc/next, @trpc/react-query and @trpc/server to the canary tag beside @tanstack/react-query ^5.105.0, next ^15.5.25, react ^19.1.0, @prisma/client ^6.7.0, superjson ^1.12.4 and zod ^4.2.1, with vitest ^5.0.0 and @playwright/test ^1.50.1 for tests and pnpm as the package manager. src/server/routers/post.ts has three procedures: list, an infinite query over prisma.post.findMany that takes limit and a cursor, fetches limit + 1 rows ordered by createdAt descending, pops the extra row into nextCursor and returns items.reverse(); byId; and add, whose zod input is id: z.string().uuid().optional(), title of 1 to 32 characters and text of at least 1. src/pages/index.tsx renders PostsCard, which calls trpc.post.list.useInfiniteQuery({ limit: 5 }, { getNextPageParam }) and flattens pages into PostItems, and AddPostCard, whose trpc.post.add.useMutation has only an onSuccess that calls utils.post.list.invalidate(), so a new post appears only after the round trip and the refetch. The form disables both fields and the button while addPost.status === 'pending' and resets itself after mutateAsync resolves. src/utils/trpc.ts builds the client with createTRPCNext, httpBatchStreamLink, the superjson transformer and ssr: false.

Two details of this app shape the optimistic write. First, add accepts an optional id that must be a UUID, so the client can generate one with crypto.randomUUID() and send it, and the optimistic row and the row the server returns share an id; there is no placeholder to swap and no key change to make React remount the item. Second, the query is infinite and each page is { items, nextCursor } with items in ascending order after the server's reverse(), so the new post belongs at the end of the first page's items, not at the head of a flat list. The agent writes onMutate to call utils.post.list.cancel({ limit: 5 }), read the current pages with utils.post.list.getInfiniteData({ limit: 5 }), write a copy with the new post appended to the first page through utils.post.list.setInfiniteData, and return the previous pages as context; onError writes that context back; onSettled calls utils.post.list.invalidate() so the server's createdAt and updatedAt replace the client's new Date(). The limit: 5 input is pulled into one constant shared by the query and the helpers, because the cache key includes the input and a mismatch makes the optimistic write land on a key nothing renders.

The form changes to match. mutateAsync becomes mutate, the fields and button stop being disabled during the request, and the form resets in onMutate rather than after the answer, since that is the point of the change. A failed add already renders the existing Alert from addPost.error.message; the agent keeps it and makes sure the rolled-back list and the alert appear together. The PostItem for a post whose createdAt came from the client shows the same formatDate output as the server's would, because both use the day in UTC, so nothing flickers when the invalidation lands. The Load more footer is left alone: the optimistic write only touches pages[0], so hasNextPage and fetchNextPage keep working from the unchanged nextCursor.

Then it tests both paths where the app already has tests. playwright/smoke.test.ts fills the title and text with a random nonce, clicks submit, waits for networkidle, reloads and waits for the text; the agent adds a test that asserts the nonce is visible before any network response, by routing **/api/trpc/** through page.route with a delayed fulfilment, and a test that fulfils the post.add call with a tRPC error body and asserts the item disappears and the alert renders. src/server/routers/post.test.ts stays as it is, since the server did not change. In its own sandbox the agent installs Postgres, sets DATABASE_URL and DIRECT_URL as .env expects, runs pnpm prebuild to generate the Prisma client and migrate, pnpm build, pnpm test-e2e and pnpm typecheck, and keeps the output. oxlint, which pnpm lint runs over src, is run too, because the vitest.config.mts and lint setup are what the Testing workflow checks on push.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Add optimistic updates to the add-post mutation in this tRPC and Next.js app. Read package.json, src/server/routers/post.ts, src/pages/index.tsx, src/utils/trpc.ts, playwright/smoke.test.ts and .github/workflows first. Generate the post id on the client since the add procedure accepts an optional UUID id, so the optimistic row and the saved row share a key. In onMutate cancel the list query, read the infinite data, append the new post to the first page in the order the server returns items, and return the previous pages; roll back in onError; invalidate in onSettled. Share the list input between the query and the cache helpers in one constant. Stop disabling the form during the request and reset it when the mutation starts, keeping the existing error alert. Add Playwright tests that prove the post appears before the server answers and disappears with the alert when the server fails, using page.route. Install Postgres in the sandbox, set DATABASE_URL and DIRECT_URL, run pnpm prebuild, pnpm build, pnpm test-e2e, pnpm typecheck and pnpm lint, and open a pull request with each command's output and a note on what still waits for the server.",
  "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 src/pages/index.tsx and playwright/smoke.test.ts and nothing under src/server/. The description walks through onMutate, onError and onSettled against the shape of post.list's pages, says why the id is generated on the client, and quotes pnpm test-e2e with the two new tests, pnpm typecheck and pnpm lint, so a reviewer can see the slow-network and failure paths pass without running a browser.

The repository's Testing workflow runs on push, with the Build + E2E tests and Unit tests + typecheck jobs against a Postgres service, so the new Playwright tests become checks on the pull request. A reviewer reads them, then decides whether the optimistic row should carry a visual pending state, which the pull request leaves out on purpose so the saved post and the pending post look the same.

Run it on every Linear issue labelled agent

A product team files the slow-feeling form as a Linear issue and labels it. In the console, an automation in the Project with the repository has a linear trigger on linear.issue.labeled with that label in labels, or on linear.issue.state_changed with the team's in-progress state mapped to exec in states, and the prompt above, so adding the label or moving the issue starts a run that reads the issue after the prompt, does the work and opens the pull request linked to it. The trigger fires only for changes made by a member of your Rush org, and the automation's max_runs_per_hour keeps a batch of relabelled issues from starting all at once.

From your own server, the same request is a POST /o/{org}/sessions with the issue URL in resources beside the repository, so the issue text sits in front of the agent, and a request_id that is a UUID v5 of the issue id so a retried webhook delivery does not start a second run.

The use case this job follows, with its automation and trigger: Turn a Linear label into a PR.

Why run it on Rush?

Optimistic updates fail in the paths nobody clicks by hand: the error path, where a stale cache or a wrong key leaves a ghost post in the list, and the infinite-query path, where writing to a flat array breaks getNextPageParam. The agent reads the page shape and the cache key from the code, writes the update against them, and proves both the fast path and the rollback with Playwright in its own sandbox with a real Postgres behind the app, so the pull request carries the test output rather than a screen recording.

The same run fits every mutation in the app, because each reads the query it should update before writing a line. A team can start one run per form from a server or from Linear, each in its own sandbox with its own record, and read the pull requests back through GET /o/{org}/sessions when they finish.

Frequently asked questions

Why generate the id on the client?

Because post.add already accepts an optional UUID id, the client can choose one and send it, so the optimistic row and the row the server returns share a key. React keeps the same element when the invalidation lands, and there is no placeholder id to replace or duplicate to filter out.

What happens when the server rejects the post?

onError writes back the pages captured in onMutate, so the list returns to what it was, and the existing destructive Alert renders the error message from the server, such as the zod message for a title over 32 characters. The Playwright test fulfils the tRPC call with an error body and asserts both.

Does this change the server or the database?

No. src/server/routers/post.ts, the Prisma schema and the migrations are untouched, and post.test.ts runs as before. Only the page component and the Playwright tests change.

Will the Load more button still work?

Yes. The optimistic write appends to the first page's items and leaves every nextCursor as it was, so hasNextPage and fetchNextPage read the same cursors. onSettled then invalidates the whole infinite query, which refetches from the first page as it does today.

More tRPC jobs

The same job on other stacks

Keep reading