{"slug": "build-a-multi-agent-research-app-in-react-with-tanstack-ai", "title": "Build a multi-agent research app in React with TanStack AI", "summary": "TanStack released TanStack AI 1.0, the first stable version of its AI library, adding subagents, tool approvals and chat compaction plus 23 provider adapters for OpenAI, Anthropic, Gemini and OpenRouter. In a side-by-side build of a two-agent \"Library Scout\" research app, the TanStack version took 272 lines of code versus 229 for Vercel's AI SDK 7 (ai 7.0.162), with the author installing @tanstack/ai 1.1.0 and running the openai/gpt-6-luna model through OpenRouter. The author reported that setting maxCompletionTokens to 300 let gpt-6-luna spend all 300 tokens on hidden reasoning and return no answer, so every call sets reasoning: 'off'.", "body_md": "[TanStack AI 1.0](https://tanstack.com/blog/tanstack-ai-1-0) is out, and it is the first stable version of TanStack’s AI library. The release also brings a few big features. Subagents let one chat hand work to other agents, tool approvals make the app ask you before a tool runs, and compaction trims long chats so they stay within the model’s limit. It also has 23 provider adapters, so the same code can talk to OpenAI, Anthropic, Gemini, OpenRouter, and others.\n\nTo see if these features are valid, I built an app called [Library Scout](https://github.com/marvelken/Multi-Agent-Research-TanStack). It answers a question every React developer asks too often: which library should I use? Normally that means googling, opening npm, checking downloads, checking React support, checking the size, and then picking the one with the nicest logo anyway. Library Scout does the boring part for you.\n\nThe first Agent researcher pulls real numbers from npm, and a second agent, the writer, reads them and recommends one library. You stay in charge because the app asks for your permission before it searches.\n\nI also built the same app with Vercel’s AI SDK 7, so we can compare them side by side. TanStack did not save me code, because it took 272 lines against 229 for the AI SDK. But it gave me features the AI SDK could not match, and I will show you what worked and what broke. The full code for both apps is in this [GitHub repo](https://github.com/marvelken/Multi-Agent-Research-TanStack), so you can check any file as we go.\n\nYou do not need a fancy setup to follow along. Here is what I used:\n\nFirst, let us create a new React app. The [TanStack](https://blog.logrocket.com/tanstack-markdown-vs-react-markdown/) CLI sets up the project for us, and then we add the AI packages the app needs. Run these in your terminal:\n\n```\nnpx @tanstack/cli@latest create library-scout --framework React --package-manager pnpm --blank\ncd library-scout\npnpm add --save-exact @tanstack/ai @tanstack/ai-react @tanstack/ai-client @tanstack/ai-openrouter zod\n```\n\nPut your key in a `.env` file as `OPENROUTER_API_KEY`. These commands installed `@tanstack/ai` 1.1.0 for me, and the AI SDK version used `ai` 7.0.162. Both apps use the `openai/gpt-6-luna` model through OpenRouter.\n\nTo keep costs favorable, I gave every model call a limit on how long its reply can be, using `maxCompletionTokens`. The problem is that `gpt-6-luna` likes to think quietly before it answers, and that hidden thinking counts toward the same limit. In one test, I set the limit to 300 tokens, and the model spent all 300 thinking. It thought very hard and then said nothing at all. That is why every call in this app also sets `reasoning: 'off'`, which you will see in the code below.\n\nOur agents need two tools that call free npm endpoints. `searchNpm` finds packages, and `getPackageStats` gets the numbers for one package. The two functions that call npm live in `src/lib/npm.ts`, which you can copy from the repo.\n\nIn the file `src/lib/tools.ts`, I define the tools there. This file has no server code, so the browser can use it too. Here is the search tool, the only one that needs your approval, and `getPackageStatsDef` sits below it in the same file:\n\n``` js\nexport const searchNpmDef = toolDefinition({\n  name: 'searchNpm',\n  description: 'Search the npm registry. Returns package names, versions and descriptions.',\n  inputSchema: z.object({ query: z.string().describe('Search words, for example \"react toast\"') }),\n  needsApproval: true,\n})\n```\n\nNext, I created `src/lib/tools.server.ts`. This file connects each tool to the function that does the work on the server:\n\n``` js\nexport const searchNpmTool = searchNpmDef.server(searchNpm)\n```\n\nI went ahead to create `src/routes/api.chat.ts`. This is the server route the chat talks to. It sends the messages to the model and streams the reply back to the browser:\n\n``` js\nPOST: async ({ request }) => {\n  const params = await chatParamsFromRequest(request)\n  const stream = chat({\n    adapter: openRouterText(MODEL_MAIN),\n    modelOptions: { maxCompletionTokens: 800 },\n    reasoning: 'off',\n    messages: params.messages,\n    threadId: params.threadId,\n    runId: params.runId,\n  })\n  return toServerSentEventsResponse(stream)\n},\n```\n\nNow for the fun part. Each subagent has two pieces, and each piece gets its own file. I created `src/lib/agents.ts` for the first piece, a plain description of each agent’s name, job, tools, and input. It has no server code, so the browser can import it. The writer sits below the researcher in the same file:\n\n``` js\nexport const researcher = {\n  name: 'researcher',\n  description: 'Researches npm packages for one focused task and returns findings with package names and real numbers.',\n  inputSchema: z.object({\n    task: z.string().describe('What to research. The researcher sees only this text.'),\n  }),\n  tools: [searchNpmDef, getPackageStatsDef],\n} as const\n```\n\nThen I created `src/lib/agents.server.ts` for the second piece. Here, `defineAgent()` adds a `run` function that calls the model on the server. The writer gets the same treatment in this file, and the prompts are in the repo:\n\n``` js\nexport const researcherAgent = defineAgent({\n  ...researcher,\n  run: (ctx) =>\n    chat({\n      adapter: openRouterText(MODEL_MAIN),\n      modelOptions: { maxCompletionTokens: 1000 },\n      reasoning: 'off',\n      systemPrompts: [RESEARCHER_PROMPT],\n      // On a resume, ctx.messages holds the child's own paused tool call. Without it the resume fails.\n      messages: ctx.resume ? ctx.messages : [{ role: 'user', content: ctx.input.task }],\n      tools: [searchNpmTool, getPackageStatsTool],\n      ...ctx.forward, // threadId, runId, parentRunId, subagentRunId, resume, abortController\n    }),\n})\n```\n\nThe lead does not need its own file, because it is just the `chat()` call in our route. Open `src/routes/api.chat.ts` to see where I added the subagents and some limits to that `chat()` call:\n\n```\nsubagents: {\n  agents: [researcherAgent, writerAgent],\n  limits: { maxDepth: 1, maxConcurrent: 2, maxCalls: 4, timeoutMs: 120_000 },\n},\n```\n\nThe `limits` line lets the lead go one level deep, run two subagents at once, make four subagent calls per request, and give each one two minutes. I also checked the final browser bundle, and none of the prompts or server code leaked into it.\n\nThat one line is my favorite thing in TanStack AI. Here is what I wrote by hand for a smaller version in the AI SDK app. All of its agent code lives in one file, `baseline-ai-sdk/src/lib/agents.server.ts` in the repo, and each tool must also call `countChildCall()`:\n\n``` js\nlet childCalls = 0\nconst countChildCall = () => {\n  if (++childCalls > 4) throw new Error('child limit reached (4 per request)')\n}\n// ...\nstopWhen: stepCountIs(6),\n// ...\nfunction withChildLimits(abortSignal: AbortSignal | undefined) {\n  const timeout = AbortSignal.timeout(120_000)\n  return abortSignal ? AbortSignal.any([abortSignal, timeout]) : timeout\n}\n```\n\nThe AI SDK has no separate subagent API, so you call an agent from inside a tool, and `streamChild` is another helper I wrote:\n\n``` js\nconst researcherTool = tool({\n  description:\n    'Researches npm packages for one focused task and returns findings with package names and real numbers.',\n  inputSchema: z.object({ task: z.string().describe('What to research. The researcher sees only this text.') }),\n  execute: async function* ({ task }, { abortSignal }) {\n    countChildCall()\n    yield* streamChild(researcher, task, abortSignal)\n  },\n  toModelOutput: ({ output }) => ({ type: 'text', value: lastText(output) }),\n})\n```\n\nSo did it work? Yes. When I asked which toast library suits a small dashboard, the lead called the researcher and then the writer in every completed run, and every download number in the answers matched npm.\n\nOn the browser side, `useChat` does most of the work. I created `src/routes/chat.$chatId.tsx`, where `$chatId` puts the chat ID in the URL. That ID becomes the `threadId`, so each conversation keeps its own history, and the agent descriptions give us types. Each subagent arrives as a message part with the type `'subagent'`, and we render a card for it:\n\n```\nconst { messages, sendMessage, isLoading, stop, subagents, interrupts, resuming } = useChat({\n  connection: fetchServerSentEvents('/api/chat'),\n  threadId: chatId,\n  subagents: scoutAgents, // declarations only: used for types, never run in the browser\n  tools: [searchNpmDef], // types the approval interrupt for the child's searchNpm call\n})\n// ...\nif (part.type === 'text') return <p key={index}>{part.content}</p>\nif (part.type === 'subagent') return <SubagentCard key={part.subagent.id} subagent={part.subagent} />\n```\n\nThen create `src/components/SubagentCard.tsx` for the card itself:\n\n```\nexport function SubagentCard({ subagent }: { subagent: SubagentHandle }) {\n  return (\n    <section className={`card ${subagent.status}`} data-name={subagent.name} data-status={subagent.status}>\n      <header>\n        <strong>{subagent.name}</strong>\n        <span className=\"status\">{subagent.status}</span>\n        {subagent.status === 'running' && (\n          <button type=\"button\" className=\"stop\" onClick={() => subagent.stop?.()}>\n            Stop\n          </button>\n        )}\n      </header>\n      {subagent.error && <p className=\"error\">{subagent.error.message}</p>}\n      {subagent.messages.flatMap((message) =>\n        message.parts.map((part, index) => {\n          const key = `${message.id}-${index}`\n          if (part.type === 'text') return <p key={key}>{part.content}</p>\n          if (part.type === 'tool-call') {\n            return (\n              <div key={key} className=\"tool-call\">\n                <code>\n                  {part.name}({part.arguments})\n                </code>{' '}\n                <em>{part.state}</em>\n              </div>\n            )\n          }\n          return null\n        }),\n      )}\n    </section>\n  )\n}\n```\n\nThe card shows the agent’s name, status, text, and tool calls, plus a Stop button that does not do what you think. We will get to that.\n\nWhen I asked for one researcher per library, two cards started together and updated on their own, which looked great. Then the logs showed that both researchers had researched both libraries, so the work was done twice, very quickly.\n\nThe AI SDK streams progress too, but I had to write each agent’s status myself, and it resends the whole agent message on every update. For the same question, the browser downloaded 1,447,308 bytes from it against 169,803 from TanStack.\n\nWhen the researcher wants to run `searchNpm`, it pauses until you click Approve or Reject. The easy part to miss is that pausing ends the request, and clicking Approve sends a new one that must pick up where the old one stopped:\n\nI learned this the hard way. My researcher copied the example in the [subagents docs](https://tanstack.com/ai/latest/docs/chat/subagents.md), which only sends the task text, and my very first Approve gave me this:\n\n```\nInterruptResumeValidationError: Resume entry references unknown interrupt approval_call_FINpuMRRhwDGfgE5fkMrQ1Hu. Resume entries must resolve or cancel the complete interrupt batch. One or more interrupt resolutions are invalid.\n```\n\nThe researcher crashed, and the writer politely reported that it had nothing to recommend. The fix is the `ctx.resume` line in the researcher code. After your approval, the researcher needs its old messages, because they hold the search it was waiting to run, and the docs example leaves them out.\n\nThe server route also has to pass two values from the request to the lead. Open `src/routes/api.chat.ts` and add these to the lead’s `chat()` call:\n\n```\n...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),\n...(params.resume ? { resume: params.resume } : {}),\n```\n\nForget `parentRunId` , and you get a clear error. Forget `resume` and you get no error at all, because the researcher just pauses again and you can click Approve forever.\n\n```\nOver 200k developers use LogRocket to create better digital experiences\nLearn more →\n```\n\nWhen the researcher asked for three searches at once, the docs buttons stayed clickable after I answered, and nothing was sent until all three had answers. Checking each request’s status fixed it. I added this to `src/routes/chat.$chatId.tsx`, below the messages:\n\n``` js\n{interrupts.map((interrupt) =>\n  interrupt.kind === 'tool-approval' ? (\n    <div key={interrupt.id} className=\"approval\" data-status={interrupt.status}>\n      <span>\n        Run <code>{interrupt.toolName}</code> with <code>{JSON.stringify(interrupt.originalArgs)}</code>?\n      </span>\n      <button\n        disabled={!interrupt.canResolve || resuming || interrupt.status !== 'pending'}\n        onClick={() => interrupt.resolveInterrupt(true)}\n      >\n        Approve\n      </button>\n      {/* The Reject button is the same, with resolveInterrupt(false) */}\n    </div>\n  ) : null,\n)}\n```\n\nA page reload normally loses a waiting search. Adding `withPersistence(memoryPersistence())` took about 10 lines and brought it back after a reload, though a server restart still wipes it. With persistence on, 2 of my 20 resumes failed with `Resume entry references non-pending interrupt`, and I could not find out why.\n\nThe AI SDK cannot ask for approval inside a subagent, and its docs say so. When I tried anyway, the researcher stopped, the lead carried on as if all was fine, and `searchNpm` never ran. My workaround asks before the researcher starts:\n\n```\ntoolApproval: { researcher: 'user-approval' },\n```\n\nThat took 15 lines against 27 in TanStack, but you approve a general task, not the exact search.\n\nI expected a card’s Stop button to stop that one agent, but it stops the whole run, so the lead never answers. The server does not even hear about it by default, and my stopped researcher kept working for five more seconds, made two more model calls, and finished an answer nobody would see.\n\nThis line makes the server stop when the browser does. Add it to the POST handler in `src/routes/api.chat.ts`, and pass the same `abortController` to `chat()`, as the repo does:\n\n``` js\nrequest.signal.addEventListener('abort', () => abortController.abort(), { once: true })\n```\n\nNow it stops everything, including the other researcher you did not touch, whose card keeps saying `running` anyway. There is also a `cancelUrl` option that I only found in the source code. It only works with the chat’s main Stop button, and you write the cancel route yourself, which is why my stop code took 38 lines in TanStack and 10 in the AI SDK.\n\nNeither library lets you stop one agent and keep the lead going. After a stop, my TanStack writer said it had no evidence, and the lead ignored it and replied, “Sonner would be my pick.” At least it was confident.\n\nLong chats get expensive, because the model rereads the whole conversation every time. Compaction cuts what the model reads, while your screen still shows everything. I ran one five-message chat four times, with a 2,000-token limit per strategy. The first message said my project needs React 18 and a toast library under 5 KB, and the last one asked for those facts back:\n\n| Setup | Tokens sent to the model | Cost | Remembered the first message? | \n|---|---|---|---|\n| No compaction | 17,055 | $0.00084 | Yes | \n| `evictOldest` | 6,587 | $0.00079 | No | \n| `clearToolResults` | 10,348 | $0.00086 | Yes | \n| `summarizeOldest` | 6,789 | $0.00163 | No | \n\n`summarizeOldest` cost the most and then told me I “haven’t specified” either requirement, which is a bold thing to say to the person who specified them. `clearToolResults` kept the facts, so it went into the app, with 16 lines that include a small UI note. Add this near the top of `src/routes/api.chat.ts`, then put `compaction` in the lead’s `middleware` list:\n\n``` js\nconst compaction = withCompaction({\n  maxTokens: 1500,\n  strategy: clearToolResults({ keepRecentToolResults: 2 }),\n  onCompact: (info) =>\n    console.log(\n      `[compaction] ${info.before} -> ${info.after} tokens, ${info.messagesBefore} -> ${info.messagesAfter} messages`,\n    ),\n})\n```\n\nAfter five questions, every old card was still on screen and the model remembered my first message. But the last compaction only went from 3,353 tokens to 2,558, well over the 1,500 limit, so it slows the growth without stopping it.\n\nSubagents need their own setup too. Compacting the lead did nothing for a subagent that reads the whole chat (2,888 tokens against 2,896), while giving a subagent its own `withCompaction` cut its last call from 3,819 tokens to 1,358.\n\nI tried four kinds of switch. Most of the extra work came from the reply limit and reasoning level on every call:\n\n| What I changed | Lines changed | What happened | \n|---|---|---|\n| The model, from `gpt-6-luna` to`anthropic/claude-haiku-5.5` | 1 | 6 type errors, but it ran | \n| The adapter, from `openRouterText` to`openaiCompatible` | 26 added, 22 removed | It ran with OpenRouter’s own option names | \n| The direct Anthropic, OpenAI, and Gemini adapters | 16 to 22 added, 20 to 26 removed | Type checks only, because I only had an OpenRouter key | \n| The lead’s model in the middle of a chat | 10 added, 2 removed | It worked | \n\nThe one-line change caused the most trouble. Haiku’s tool arguments came back broken five times across two runs, one run crashed, and the finished run cost 8.9 to 11 times more than `gpt-6-luna`. The same change in the AI SDK app had no type errors and passed its one run, so test a new model even when the change is tiny.\n\nThe `openaiCompatible` switch is sneakier. It accepts `maxCompletionTokens` and ignores it, so a reply limited to 16 tokens came back with 2,775. You need OpenRouter’s own option names. To try this switch, create `src/lib/provider.server.ts`:\n\n``` js\nexport const openrouter = openaiCompatible({\n  name: 'openrouter',\n  baseURL: 'https://openrouter.ai/api/v1',\n  apiKey: process.env.OPENROUTER_API_KEY!,\n  models: [MODEL_MAIN],\n})\n```\n\nThen change these two lines in every `chat()` call:\n\n```\nadapter: openrouter(MODEL_MAIN),\nmodelOptions: { max_tokens: 1000, reasoning: { effort: 'none' } }, // raw OpenRouter keys: maxCompletionTokens is ignored here\n```\n\nThe TanStack and [AI SDK](https://blog.logrocket.com/unified-ai-interfaces-vercel-sdk/) columns come from my builds unless a cell says docs only. I did not build Mastra, so its column comes from its [docs](https://mastra.ai/docs/subagents.md), and I cannot say how it feels to use:\n\n| Feature | TanStack AI | AI SDK 7 | Mastra (docs only) | \n|---|---|---|---|\n| Approval inside a subagent | Built in | Not available | Built in | \n| Status for each agent in the UI | Built in | Written by hand | Not confirmed | \n| Stop one agent while the lead continues | No | No | Not documented | \n| Limits | Built in, 1 line | Written by hand, 9 lines | Built in | \n| Compaction | Built in | A helper plus your own code (docs only) | Built in | \n| Saving chats | Built in | Your own code (docs only) | Built in | \n| Lines for the same app | 272 | 229 | Not built | \n| Gzipped browser JavaScript | 190,442 bytes | 155,678 bytes | Not built | \n\nThe last two rows are not a fair fight, because TanStack’s numbers include extras like approving each search. So does TanStack AI cut boilerplate? Not in line count for this app, but it cuts the number of features you build yourself.\n\nTanStack is known for strong types and good docs. The types hold up. I made the same five mistakes in both apps, and each caught four before running. TanStack caught the fifth, a wrong subagent input sent through a router, while running, but the AI SDK let an unsupported `temperature` setting through with no warning at all.\n\nThe docs fall short. The approval example breaks on resume, the button example breaks with several approvals, and `cancelUrl` is missing. The AI SDK docs have mistakes too, such as using `messages` where the code expects `uiMessages`. And on lock-in, you are not stuck with one provider, but leaving one still takes work.\n\nSo my answer is yes on types and features, but not yet on docs or on how reliably approvals resume.\n\nPick TanStack AI when a person must approve what a subagent does, or when you want agent status, limits, compaction, and saved chats without building them yourself. Pick the AI SDK when your subagents only need to report back, when you switch models often, or when you want fewer lines and a smaller bundle right now.\n\nThese results come from about 30 TanStack runs and 3 AI SDK runs, mostly on one model, so test your own app before you decide.\n\nTanStack AI 1.0 really does turn subagents into a library feature, and watching two researchers work side by side with so little code is fun. Just test three things before you trust them: what Stop stops, whether compaction holds its limit, and whether that one-line model switch is really one line.\n\n            Install LogRocket via npm or script tag. `LogRocket.init()` must be called client-side, not\n            server-side\n            \n\n``` python\n$ npm i --save logrocket \n\n// Code:\n\nimport LogRocket from 'logrocket'; \nLogRocket.init('app/id');\n// Add to your HTML:\n\n<script src=\"https://cdn.lr-ingest.com/LogRocket.min.js\"></script>\n<script>window.LogRocket && window.LogRocket.init('app/id');</script>\nStop guessing about your digital experience with LogRocket\nGet started for free\n```\n\nLearn key lessons from real-world code migrations using AI coding agents.\n\nCompare the top AI development tools and models of November 2026. View updated rankings, feature breakdowns, and find the best fit for you.\n\nAI coding assistants can generate UI quite quickly, but they don’t know your design system. Here’s how you can teach them the ins and outs.\n\nBuild a 3D hero with GPU Style Sheets and compare its code, bundle size, and rendering costs with Three.js.\n\nWould you be interested in joining LogRocket's developer community?\n\nJoin LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.", "url": "https://wpnews.pro/news/build-a-multi-agent-research-app-in-react-with-tanstack-ai", "canonical_source": "https://blog.logrocket.com/react-tanstack-ai-research-assistant/", "published_at": "2026-11-16 16:59:10+00:00", "updated_at": "2026-11-20 14:42:01.981639+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "developer-tools", "large-language-models"], "entities": ["TanStack", "TanStack AI 1.0", "Vercel", "AI SDK 7", "OpenRouter", "OpenAI", "Anthropic", "Gemini"], "also_reported_by": [], "takeaway": "TanStack AI 1.0 ships subagents, needsApproval tool gating and compaction across 23 provider adapters, but the author's build cost 272 lines versus 229 for Vercel AI SDK 7, and reasoning tokens count against maxCompletionTokens, so set reasoning: 'off' to avoid a 300-token cap being spent entirely o", "recommendation": null, "alternates": {"html": "https://wpnews.pro/news/build-a-multi-agent-research-app-in-react-with-tanstack-ai", "markdown": "https://wpnews.pro/news/build-a-multi-agent-research-app-in-react-with-tanstack-ai.md", "text": "https://wpnews.pro/news/build-a-multi-agent-research-app-in-react-with-tanstack-ai.txt", "jsonld": "https://wpnews.pro/news/build-a-multi-agent-research-app-in-react-with-tanstack-ai.jsonld"}}