Add preact integration #180
main fromrefs/pull/180/head·merged by AlemTuzlak View on GitHub🎯 Changes#
This adds a preact-integration, this is largely adapted from the react tests and implementation. I was considering adding a signals based one as well but wanted to see whether the appeal is there from a maintenance standpoint.
The minimum version of preact is 10.11 as useId was introduced there https://github.com/preactjs/preact/releases/tag/10.11.0
I will add the ai-preact-ui in a follow up PR.
Note
The PR template calls out to follow https://github.com/TanStack/ai/blob/main/CONTRIBUTING.md but this does not exist.
✅ Checklist#
- I have tested this code locally with
pnpm run test:pr.
🚀 Release Impact#
- This change affects published code, and I have generated a changeset.
Summary by CodeRabbit#
New Features
- Initial release of @tanstack/ai-preact: a Preact hook for AI chats with streaming, message lifecycle controls, tool call workflows, loading/error state, and public types.
Documentation
- Added README, API docs, and CHANGELOG with examples and integration guidance; updated docs navigation.
Tests
- Comprehensive test suite and test utilities covering hook behavior, streaming, tools, lifecycle, and edge cases.
Chores / Build
- Package manifest, TypeScript, and test/build configuration for the new package.
- 1
Actionable comments posted: 2
🧹 Nitpick comments (8)
packages/typescript/ai-preact/package.json (1)
46-52: Missingvitestin devDependencies.The test script uses
vitest run, butvitestis not listed in devDependencies. While it may be hoisted from the workspace root, explicitly declaring it ensures the package is self-contained.🔎 Proposed fix
"devDependencies": { "@testing-library/preact": "^3.2.4", "@vitest/coverage-v8": "4.0.14", "jsdom": "^27.2.0", "preact": "^10.26.9", - "vite": "^7.2.7" + "vite": "^7.2.7", + "vitest": "^4.0.0" },packages/typescript/ai-preact/vite.config.ts (1)
5-27: Clarify the role of this config vsvitest.config.ts.This file sets
environment: 'node', whilevitest.config.tssetsenvironment: 'jsdom'. When runningvitest, the dedicatedvitest.config.tstakes precedence, making the test configuration here potentially unused or confusing.Consider either:
- Removing the
testblock from this file (keeping it build-only), or - Consolidating test configuration into a single location.
packages/typescript/ai-preact/tests/test-utils.ts (1)
25-29: Type assertion bypasses type safety for required options.The default parameter
{} as UseChatOptionsuses a type assertion to cast an empty object. IfUseChatOptionshas required properties (likeconnection), this could lead to runtime errors whenrenderUseChat()is called without arguments.Consider making the parameter truly optional or requiring the caller to always provide options:
🔎 Option A: Make parameter required (safer)
export function renderUseChat( - options: UseChatOptions = {} as UseChatOptions, + options: UseChatOptions, ): RenderHookResult<UseChatReturn, UseChatOptions> { return renderHook(() => useChat(options)) }🔎 Option B: Use Partial type (if truly optional)
export function renderUseChat( - options: UseChatOptions = {} as UseChatOptions, + options: Partial<UseChatOptions> = {}, ): RenderHookResult<UseChatReturn, UseChatOptions> { - return renderHook(() => useChat(options)) + return renderHook(() => useChat(options as UseChatOptions)) }packages/typescript/ai-preact/src/use-chat.ts (3)
48-58: Inconsistent options access pattern.Most options are accessed via
optionsRef.current(lines 49-57), butstreamProcessoron line 58 is accessed directly fromoptions. This inconsistency could lead to subtle bugs if the component re-renders with new options while the client is being created.🔎 Proposed fix
onError: optionsRef.current.onError, tools: optionsRef.current.tools, - streamProcessor: options.streamProcessor, + streamProcessor: optionsRef.current.streamProcessor, onMessagesChange: (newMessages: Array<UIMessage<TTools>>) => {
74-78: Consider adding ESLint disable comment for intentional empty dependencies.The empty dependency array is intentional for mount-only behavior (as documented in lines 71-73), but linters will flag this. Adding an explicit disable comment would clarify the intent and prevent accidental "fixes."
🔎 Proposed change
// Sync initial messages on mount only // Note: initialMessages are passed to ChatClient constructor, but we also // set them here to ensure Preact state is in sync useEffect(() => { if (options.initialMessages && options.initialMessages.length && !messages.length) { client.setMessagesManually(options.initialMessages) } + // eslint-disable-next-line react-hooks/exhaustive-deps -- Intentional mount-only effect }, [])
100-105: Missing generic type parameter onUIMessage.The
appendcallback usesUIMessagewithout the<TTools>parameter, which could cause type inconsistencies sinceUIMessageis generic.🔎 Proposed fix
const append = useCallback( - async (message: ModelMessage | UIMessage) => { + async (message: ModelMessage | UIMessage<TTools>) => { await client.append(message) }, [client], )packages/typescript/ai-preact/tests/use-chat.test.ts (2)
376-425: Test logic may not be verifying the intended behavior.The
adapter2created on line 395 is passed torerenderon line 410, but since theclientIddoesn't change (noidprop change), theuseMemowon't recreate the client. The client will continue using the original adapter. TheonConnectcallback approach also appears unused sincecallCountincrements but the returned chunks aren't utilized by the mock adapter's typical flow.Consider simplifying this test or clarifying what reload behavior it's actually validating:
🔎 Simplified reload test
it('should reload the last assistant message', async () => { - const chunks1 = createTextChunks('First response') - const chunks2 = createTextChunks('Second response') - let callCount = 0 - - const adapter = createMockConnectionAdapter({ - chunks: chunks1, - onConnect: () => { - callCount++ - // Return different chunks on second call - if (callCount === 2) { - return chunks2 - } - return undefined - }, - }) - - // Create a new adapter for the second call - const adapter2 = createMockConnectionAdapter({ chunks: chunks2 }) - const { result, rerender } = renderUseChat({ connection: adapter }) + const chunks = createTextChunks('Response') + const adapter = createMockConnectionAdapter({ chunks }) + const { result } = renderUseChat({ connection: adapter }) await act(async () => { await result.current.sendMessage('Hello') }) await waitFor(() => { const assistantMessage = result.current.messages.find( (m) => m.role === 'assistant', ) expect(assistantMessage).toBeDefined() }) - // Reload with new adapter - rerender({ connection: adapter2 }) + // Reload should resend the last user message await act(async () => { await result.current.reload() }) await waitFor(() => { const assistantMessage = result.current.messages.find( (m) => m.role === 'assistant', ) expect(assistantMessage).toBeDefined() }) - // Should have reloaded (though content might be same if adapter doesn't change) const messagesAfterReload = result.current.messages expect(messagesAfterReload.length).toBeGreaterThan(0) })
1053-1084: Test assertion doesn't verify error is cleared.The test "should clear error on successful operation" (line 1053) doesn't assert that
errorbecomesundefinedafter the successful operation. Additionally, since the client isn't recreated on rerender (sameclientId), theworkingAdapterwon't be used.🔎 Suggested improvement
// Switch to working adapter const workingAdapter = createMockConnectionAdapter({ chunks: createTextChunks('Success'), }) rerender({ connection: workingAdapter }) await act(async () => { await result.current.sendMessage('Test') }) await waitFor(() => { // Error should be cleared on success - expect(result.current.messages.length).toBeGreaterThan(0) + expect(result.current.error).toBeUndefined() }) + expect(result.current.messages.length).toBeGreaterThan(0)Note: This test may also need a different approach since rerendering with a new adapter doesn't recreate the
ChatClient(theclientIdremains unchanged). Consider whether this test accurately reflects the intended behavior.📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 29466c10a435bc9386a8d261d6c8254985d24b16 and 9e87162bf2164ab3b9301bcbd25ccd7e82c6e2f7.
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (12)
.changeset/tired-years-stick.mdpackages/typescript/ai-preact/CHANGELOG.mdpackages/typescript/ai-preact/README.mdpackages/typescript/ai-preact/package.jsonpackages/typescript/ai-preact/src/index.tspackages/typescript/ai-preact/src/types.tspackages/typescript/ai-preact/src/use-chat.tspackages/typescript/ai-preact/tests/test-utils.tspackages/typescript/ai-preact/tests/use-chat.test.tspackages/typescript/ai-preact/tsconfig.jsonpackages/typescript/ai-preact/vite.config.tspackages/typescript/ai-preact/vitest.config.ts
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.{ts,tsx}: Use tree-shakeable adapter architecture for provider implementations - export specialized adapters (text, embedding, summarize, image) as separate imports from/adapterssubpath rather than monolithic adapters Use Zod for runtime schema validation and type inference, particularly for tool input/output definitions withtoolDefinition()and Zod schema inference Implement isomorphic tool system usingtoolDefinition()with.server()and.client()implementations for dual-environment execution Use type-safe per-model configuration with provider options typed based on selected model to ensure compile-time safety Implement stream processing with StreamProcessor for handling chunked responses and support partial JSON parsing for streaming AI responsesFiles:
packages/typescript/ai-preact/src/index.tspackages/typescript/ai-preact/tests/test-utils.tspackages/typescript/ai-preact/vitest.config.tspackages/typescript/ai-preact/src/types.tspackages/typescript/ai-preact/src/use-chat.tspackages/typescript/ai-preact/tests/use-chat.test.tspackages/typescript/ai-preact/vite.config.ts
packages/typescript/*/src/index.ts
📄 CodeRabbit inference engine (CLAUDE.md)
Export tree-shakeable adapters with clear subpath exports in package.json (e.g.,
@tanstack/ai/adapters,@tanstack/ai-openai/adapters) to minimize bundle sizeFiles:
packages/typescript/ai-preact/src/index.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (CLAUDE.md)
Use camelCase for function and variable names throughout the codebase
Files:
packages/typescript/ai-preact/src/index.tspackages/typescript/ai-preact/tests/test-utils.tspackages/typescript/ai-preact/vitest.config.tspackages/typescript/ai-preact/src/types.tspackages/typescript/ai-preact/src/use-chat.tspackages/typescript/ai-preact/tests/use-chat.test.tspackages/typescript/ai-preact/vite.config.ts
**/*.test.ts
📄 CodeRabbit inference engine (CLAUDE.md)
Write unit tests using Vitest alongside source files with
.test.tsnaming conventionFiles:
packages/typescript/ai-preact/tests/use-chat.test.ts
🧠 Learnings (12)
📓 Common learnings
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Implement framework integrations using the headless `tanstack/ai-client` for state management with framework-specific hooks (useChat) on top📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/index.ts : Export tree-shakeable adapters with clear subpath exports in package.json (e.g., `tanstack/ai/adapters`, `tanstack/ai-openai/adapters`) to minimize bundle sizeApplied to files:
packages/typescript/ai-preact/tsconfig.jsonpackages/typescript/ai-preact/README.mdpackages/typescript/ai-preact/src/index.tspackages/typescript/ai-preact/vitest.config.tspackages/typescript/ai-preact/vite.config.tspackages/typescript/ai-preact/CHANGELOG.mdpackages/typescript/ai-preact/package.json
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/adapters/*.ts : Create individual adapter implementations for each provider capability (text, embed, summarize, image) with separate exports to enable tree-shakingApplied to files:
packages/typescript/ai-preact/tsconfig.jsonpackages/typescript/ai-preact/README.mdpackages/typescript/ai-preact/src/index.tspackages/typescript/ai-preact/tests/test-utils.tspackages/typescript/ai-preact/package.json
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Use tree-shakeable adapter architecture for provider implementations - export specialized adapters (text, embedding, summarize, image) as separate imports from `/adapters` subpath rather than monolithic adaptersApplied to files:
packages/typescript/ai-preact/tsconfig.jsonpackages/typescript/ai-preact/README.mdpackages/typescript/ai-preact/src/index.tspackages/typescript/ai-preact/tests/test-utils.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Use Zod for runtime schema validation and type inference, particularly for tool input/output definitions with `toolDefinition()` and Zod schema inferenceApplied to files:
packages/typescript/ai-preact/tsconfig.json
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/model-meta.ts : Maintain model metadata files that define provider options and capabilities per model for per-model type safetyApplied to files:
packages/typescript/ai-preact/tsconfig.jsonpackages/typescript/ai-preact/package.json
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to .eslintrc* : Use ESLint with custom TanStack config for linting all TypeScript and JavaScript filesApplied to files:
packages/typescript/ai-preact/tsconfig.jsonpackages/typescript/ai-preact/vitest.config.tspackages/typescript/ai-preact/vite.config.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to .prettierrc* : Use Prettier for code formatting with project-configured rulesApplied to files:
packages/typescript/ai-preact/tsconfig.json
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.test.ts : Write unit tests using Vitest alongside source files with `.test.ts` naming conventionApplied to files:
packages/typescript/ai-preact/tsconfig.jsonpackages/typescript/ai-preact/vitest.config.tspackages/typescript/ai-preact/vite.config.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Implement framework integrations using the headless `tanstack/ai-client` for state management with framework-specific hooks (useChat) on topApplied to files:
packages/typescript/ai-preact/README.mdpackages/typescript/ai-preact/src/index.tspackages/typescript/ai-preact/tests/test-utils.tspackages/typescript/ai-preact/src/types.tspackages/typescript/ai-preact/src/use-chat.tspackages/typescript/ai-preact/tests/use-chat.test.tspackages/typescript/ai-preact/CHANGELOG.mdpackages/typescript/ai-preact/package.json
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Create changesets with `pnpm changeset` before making changes to prepare for release version bumping and publishingApplied to files:
.changeset/tired-years-stick.md
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/*/package.json : Use `workspace:*` protocol for internal package dependencies in package.json (e.g., `"tanstack/ai": "workspace:*"`)Applied to files:
packages/typescript/ai-preact/package.json
🧬 Code graph analysis (1)
packages/typescript/ai-preact/src/use-chat.ts (2)
packages/typescript/ai-preact/src/types.ts (3)
UseChatOptions(26-30)UseChatReturn(32-98)UIMessage(9-9)
packages/typescript/ai-client/src/chat-client.ts (6)
append(265-285)reload(336-354)stop(359-366)setMessagesManually(509-511)addToolResult(380-408)addToolApprovalResponse(413-450)
🪛 markdownlint-cli2 (0.18.1)
packages/typescript/ai-preact/README.md
2-2: Images should have alternate text (alt text)
(MD045, no-alt-text)
12-12: Hard tabs Column: 1
(MD010, no-hard-tabs)
23-23: Hard tabs Column: 1
(MD010, no-hard-tabs)
24-24: Hard tabs Column: 1
(MD010, no-hard-tabs)
25-25: Hard tabs Column: 1
(MD010, no-hard-tabs)
49-49: Heading levels should only increment by one level at a time Expected: h2; Actual: h3
(MD001, heading-increment)
🔇 Additional comments (8)
packages/typescript/ai-preact/CHANGELOG.md (1)
1-1: LGTM!Standard changelog placeholder for the new package. Entries will be auto-generated by changesets.
.changeset/tired-years-stick.md (1)
1-5: LGTM!Changeset is correctly formatted with appropriate minor version bump for the initial release.
packages/typescript/ai-preact/tsconfig.json (1)
1-11: LGTM!TypeScript configuration is correctly set up for Preact with the automatic JSX runtime (
react-jsx+jsxImportSource: "preact").packages/typescript/ai-preact/src/types.ts (1)
1-98: LGTM!Well-structured type definitions that correctly extend the headless
@tanstack/ai-clientwhile omitting callbacks managed internally by Preact state. The JSDoc documentation clearly explains the design rationale. Based on learnings, this follows the recommended pattern for framework integrations.packages/typescript/ai-preact/src/index.ts (1)
1-17: LGTM! Clean public API surface.The exports are well-organized, following the pattern of framework integrations using the headless
@tanstack/ai-clientfor state management with a framework-specific hook on top. The re-exports from@tanstack/ai-clientprovide convenient access to commonly needed utilities. Based on learnings, this aligns with the expected architecture.packages/typescript/ai-preact/src/use-chat.ts (1)
14-16: Well-structured hook implementation.The hook correctly implements the framework integration pattern: using the headless
ChatClientfrom@tanstack/ai-clientfor state management while providing Preact-specific state bindings. The cleanup on unmount, callback memoization, and ref-based message preservation across client recreations are all properly implemented.Also applies to: 146-158
packages/typescript/ai-preact/tests/use-chat.test.ts (2)
1-11: Comprehensive test suite with good coverage.The test suite thoroughly covers initialization, state management, message operations, lifecycle behaviors, error handling, concurrency scenarios, and tool workflows. Uses Vitest with
.test.tsnaming convention as per coding guidelines.
1216-1321: Good defensive testing for tool operations.The tool operation tests properly use conditional checks (
if (toolCallPart)) to handle cases where tool calls may not be present in the response. This defensive approach prevents false positives while still exercising the API surface.@@ -0,0 +1,2 @@1+<div align="center">2+ <img src="./media/header_ai.png" >⚠️ Potential issue | 🟡 Minor
Add alt text to the header image for accessibility.
The header image is missing the
altattribute, which is flagged by static analysis (MD045).🔎 Proposed fix
- <img src="./media/header_ai.png" > + <img src="./media/header_ai.png" alt="TanStack AI" />📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change2- <img src="./media/header_ai.png" >2+ <img src="./media/header_ai.png" alt="TanStack AI" />🧰 Tools
🪛 markdownlint-cli2 (0.18.1)
2-2: Images should have alternate text (alt text)
(MD045, no-alt-text)
🤖 Prompt for AI Agents
In packages/typescript/ai-preact/README.md around line 2, the header image tag <img src="./media/header_ai.png"> is missing an alt attribute which triggers MD045; add a concise, meaningful alt attribute (e.g., alt="AI Preact header" or a short description of the image) to the img tag so the markup becomes <img src="./media/header_ai.png" alt="..."> to satisfy accessibility and static analysis.packages/typescript/ai-preact/README.md lines 81 to 83OutdatedResolvedby JoviDeCroock(GitHub profile, opens in a new tab)@@ -0,0 +63,21 @@63+ adapter: textAdapter,64+ model: 'gpt-4o',65+ messages: [{ role: 'user', content: [{ type: 'text', content: 'Hello!' }] }],66+})67+68+for await (const chunk of result) {69+ console.log(chunk)70+}71+```72+73+Available adapters: `openaiText`, `openaiEmbed`, `openaiSummarize`, `anthropicText`, `geminiText`, `ollamaText`, and more.74+75+## Bonus: TanStack Start Integration76+77+TanStack AI works with **any** framework (Next.js, Express, Remix, etc.).78+79+**With TanStack Start**, you get a bonus: share implementations between AI tools and server functions with `createServerFnTool`:80+81+```typescript82+import { createServerFnTool } from '@tanstack/ai-preact'83+⚠️ Potential issue | 🟡 Minor
🧩 Analysis chain
🏁 Script executed:
rg -n "createServerFnTool" --type=ts --type=tsx -g '!node_modules' -g '!dist' -A 2 -B 2Repository: TanStack/ai
Length of output: 166
🏁 Script executed:
# Check the index.ts file in ai-preact package to see what's actually exported find . -path "*/ai-preact/index.ts" -o -path "*/ai-preact/src/index.ts" | head -20Repository: TanStack/ai
Length of output: 166
🏁 Script executed:
# Search for export statements of createServerFnTool rg "export.*createServerFnTool" --type=ts --type=tsx -g '!node_modules' -g '!dist'Repository: TanStack/ai
Length of output: 166
🌐 Web query:
TanStack ai createServerFnTool export package @tanstack/ai-preact💡 Result:
Short answer: import createServerFnTool from @tanstack/ai-react — it isn’t exported from an @tanstack/ai-preact package (TanStack docs and repo show the helper under the React bindings). [1][2]
Example: import { createServerFnTool } from "@tanstack/ai-react";
const getProducts = createServerFnTool({ name: "getProducts", inputSchema: z.object({ query: z.string() }), execute: async ({ query }) => db.products.search(query), });
References: [1] TanStack AI repo (createServerFnTool example in README). [2] @tanstack/ai-react docs (API & examples).
Change import source to
@tanstack/ai-react.The example imports
createServerFnToolfrom@tanstack/ai-preact, but this function is exported from@tanstack/ai-react. Update to:import { createServerFnTool } from '@tanstack/ai-react'🤖 Prompt for AI Agents
In packages/typescript/ai-preact/README.md around lines 81 to 83, the example imports createServerFnTool from @tanstack/ai-preact but that export lives in @tanstack/ai-react; update the import to use @tanstack/ai-react (i.e. replace the module specifier in the import statement) so the example imports createServerFnTool from the correct package.- Removing the
Actionable comments posted: 3
♻️ Duplicate comments (1)
packages/typescript/ai-preact/README.md (1)
2-2: Add alt text to the header image for accessibility.The image is missing an
altattribute (MD045). This is a duplicate of a previously flagged issue.🔎 Proposed fix
- <img src="./media/header_ai.png" > + <img src="./media/header_ai.png" alt="TanStack AI Preact" />📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 8c8fbbd40447aae363d54a1f72cb86eb277852bc and 3e685ee9959846ff27c0d56c1d6f6f1a7ff3aa62.
📒 Files selected for processing (1)
packages/typescript/ai-preact/README.md
🧰 Additional context used
🧠 Learnings (6)
📓 Common learnings
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Implement framework integrations using the headless `tanstack/ai-client` for state management with framework-specific hooks (useChat) on top📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/index.ts : Export tree-shakeable adapters with clear subpath exports in package.json (e.g., `tanstack/ai/adapters`, `tanstack/ai-openai/adapters`) to minimize bundle sizeApplied to files:
packages/typescript/ai-preact/README.md
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/adapters/*.ts : Create individual adapter implementations for each provider capability (text, embed, summarize, image) with separate exports to enable tree-shakingApplied to files:
packages/typescript/ai-preact/README.md
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Use tree-shakeable adapter architecture for provider implementations - export specialized adapters (text, embedding, summarize, image) as separate imports from `/adapters` subpath rather than monolithic adaptersApplied to files:
packages/typescript/ai-preact/README.md
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Implement isomorphic tool system using `toolDefinition()` with `.server()` and `.client()` implementations for dual-environment executionApplied to files:
packages/typescript/ai-preact/README.md
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Implement framework integrations using the headless `tanstack/ai-client` for state management with framework-specific hooks (useChat) on topApplied to files:
packages/typescript/ai-preact/README.md
🪛 markdownlint-cli2 (0.18.1)
packages/typescript/ai-preact/README.md
2-2: Images should have alternate text (alt text)
(MD045, no-alt-text)
12-12: Hard tabs Column: 1
(MD010, no-hard-tabs)
23-23: Hard tabs Column: 1
(MD010, no-hard-tabs)
24-24: Hard tabs Column: 1
(MD010, no-hard-tabs)
25-25: Hard tabs Column: 1
(MD010, no-hard-tabs)
49-49: Heading levels should only increment by one level at a time Expected: h2; Actual: h3
(MD001, heading-increment)
@@ -0,0 +1,12 @@1+<div align="center">2+ <img src="./media/header_ai.png" >3+</div>4+5+<br />6+7+<div align="center">8+<a href="https://npmjs.com/package/@tanstack/ai" target="\_parent">9+ <img alt="" src="https://img.shields.io/npm/dm/@tanstack/ai.svg" />10+</a>11+<a href="https://github.com/TanStack/ai" target="\_parent">12+ <img alt="" src="https://img.shields.io/github/stars/TanStack/ai.svg?style=social&label=Star" alt="GitHub stars" />⚠️ Potential issue | 🟡 Minor
Replace hard tabs with spaces for consistent indentation.
Lines 12, 23, 24, and 25 use hard tabs instead of spaces, which violates MD010. Standardize to spaces.
🔎 Proposed fix
<a href="https://github.com/TanStack/ai" target="\_parent"> - <img alt="" src="https://img.shields.io/github/stars/TanStack/ai.svg?style=social&label=Star" alt="GitHub stars" /> + <img alt="" src="https://img.shields.io/github/stars/TanStack/ai.svg?style=social&label=Star" alt="GitHub stars" /> </a> <a href="https://bundlephobia.com/result?p=@tanstack/ai@latest" target="\_parent"> <img alt="" src="https://badgen.net/bundlephobia/minzip/@tanstack/ai@latest" /> </a> </div> <div align="center"> <a href="#badge"> <img alt="semantic-release" src="https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg"> </a> - <a href="#badge"> - <img src="https://img.shields.io/github/v/release/tanstack/ai" alt="Release"/> - </a> + <a href="#badge"> + <img src="https://img.shields.io/github/v/release/tanstack/ai" alt="Release"/> + </a> <a href="https://twitter.com/tan_stack"> <img src="https://img.shields.io/twitter/follow/tan_stack.svg?style=social" alt="Follow @TanStack"/> </a>Also applies to: 23-25
🧰 Tools
🪛 markdownlint-cli2 (0.18.1)
12-12: Hard tabs Column: 1
(MD010, no-hard-tabs)
🤖 Prompt for AI Agents
In packages/typescript/ai-preact/README.md around lines 12 and 23-25, several lines use hard tabs for indentation which violates MD010; replace each hard tab character with spaces (use the repository/project standard for Markdown indentation — e.g., two spaces per tab) so indentation is consistent with the rest of the file and no tabs remain on those lines.@@ -0,0 +29,21 @@29+</div>30+31+<div align="center">32+33+### [Become a Sponsor!](https://github.com/sponsors/tannerlinsley/)34+</div>35+36+# TanStack AI37+38+A powerful, type-safe AI SDK for building AI-powered applications.39+40+- Provider-agnostic adapters (OpenAI, Anthropic, Gemini, Ollama, etc.)41+- **Tree-shakeable adapters** - Import only what you need for smaller bundles42+- **Multimodal content support** - Send images, audio, video, and documents43+- **Image generation** - Generate images with OpenAI DALL-E/GPT-Image and Gemini Imagen44+- Chat completion, streaming, and agent loop strategies45+- Headless chat state management with adapters (SSE, HTTP stream, custom)46+- Isomorphic type-safe tools with server/client execution47+- **Enhanced integration with TanStack Start** - Share implementations between AI tools and server functions48+49+### <a href="https://tanstack.com/ai">Read the docs →</b></a>⚠️ Potential issue | 🟡 Minor
Fix heading level hierarchy.
Line 49 uses
###(h3) but should use##(h2) to maintain proper heading increments per MD001.🔎 Proposed fix
-### <a href="https://tanstack.com/ai">Read the docs →</b></a> +## <a href="https://tanstack.com/ai">Read the docs →</b></a>📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change49-### <a href="https://tanstack.com/ai">Read the docs →</b></a>49+## <a href="https://tanstack.com/ai">Read the docs →</b></a>🧰 Tools
🪛 markdownlint-cli2 (0.18.1)
49-49: Heading levels should only increment by one level at a time Expected: h2; Actual: h3
(MD001, heading-increment)
🤖 Prompt for AI Agents
In packages/typescript/ai-preact/README.md around line 49, the heading currently uses `###` (h3) but should be `##` (h2) to preserve proper heading hierarchy per MD001; change the leading hashes from `###` to `##` on that line so the section increments correctly and re-run the linter to verify the MD001 warning is resolved.packages/typescript/ai-preact/README.md line 80OutdatedResolvedby JoviDeCroock(GitHub profile, opens in a new tab)@@ -0,0 +60,21 @@60+const textAdapter = openaiText()61+62+const result = generate({63+ adapter: textAdapter,64+ model: 'gpt-4o',65+ messages: [{ role: 'user', content: [{ type: 'text', content: 'Hello!' }] }],66+})67+68+for await (const chunk of result) {69+ console.log(chunk)70+}71+```72+73+Available adapters: `openaiText`, `openaiEmbed`, `openaiSummarize`, `anthropicText`, `geminiText`, `ollamaText`, and more.74+75+## Get Involved76+77+- We welcome issues and pull requests!78+- Participate in [GitHub discussions](https://github.com/TanStack/ai/discussions)79+- Chat with the community on [Discord](https://discord.com/invite/WrRKjPJ)80+- See [CONTRIBUTING.md](./CONTRIBUTING.md) for setup instructions⚠️ Potential issue | 🟡 Minor
🧩 Analysis chain
🏁 Script executed:
# Search for all CONTRIBUTING.md files in the repository fd -i "contributing.md" -t f # Check the structure of the packages/typescript/ai-preact directory ls -la packages/typescript/ai-preact/ 2>/dev/null | head -20Repository: TanStack/ai
Length of output: 660
🏁 Script executed:
# Find all CONTRIBUTING.md files with full paths fd -i "contributing.md" -t f | head -50 # Check if CONTRIBUTING.md exists at repository root ls -la CONTRIBUTING.md 2>&1 # List root directory files ls -la | grep -i contributingRepository: TanStack/ai
Length of output: 117
🏁 Script executed:
# Search for any CONTRIBUTING file (case-insensitive) find . -iname "*contributing*" -type f 2>/dev/null # Also search for files that might contain contribution guidelines find . -iname "*contribution*" -type f 2>/dev/null # Check git to see if CONTRIBUTING.md was tracked git ls-files | grep -i contributingRepository: TanStack/ai
Length of output: 37
🏁 Script executed:
# Read the README.md file around line 80 to see the exact context sed -n '75,85p' packages/typescript/ai-preact/README.md # Check for any documentation in .github directory find .github -name "*CONTRIBUTING*" -o -name "*contrib*" 2>/dev/null | head -10 # Check the root level for any documentation files ls -la *.md 2>/dev/nullRepository: TanStack/ai
Length of output: 629
🏁 Script executed:
# Final verification: search entire repo for any CONTRIBUTING content rg -i "CONTRIBUTING" --type md | head -20Repository: TanStack/ai
Length of output: 1829
Remove or fix broken CONTRIBUTING.md reference.
Line 80 references
./CONTRIBUTING.md, but this file does not exist in the repository. Either remove the reference or provide the correct path to setup instructions.🤖 Prompt for AI Agents
In packages/typescript/ai-preact/README.md around line 80, the README references ./CONTRIBUTING.md which does not exist; update the reference to point to the correct contributing or setup document (for example ../CONTRIBUTING.md or the repo-level CONTRIBUTING.md path) or remove the link entirely; ensure the link text and path are valid and relative to this file so the setup instructions resolve correctly.✅ Addressed in commit f6fe950
Actionable comments posted: 1
♻️ Duplicate comments (3)
packages/typescript/ai-preact/README.md (3)
2-2: Add alt text to the header image for accessibility.The header image is missing the
altattribute, which is required for accessibility.🔎 Proposed fix
- <img src="./media/header_ai.png" > + <img src="./media/header_ai.png" alt="TanStack AI Preact" />
12-12: Replace hard tabs with spaces for consistent indentation.Lines 12, 23-25 use hard tabs instead of spaces. Standardize to spaces for consistent formatting.
🔎 Proposed fix
<a href="https://github.com/TanStack/ai" target="\_parent"> - <img alt="" src="https://img.shields.io/github/stars/TanStack/ai.svg?style=social&label=Star" alt="GitHub stars" /> + <img alt="" src="https://img.shields.io/github/stars/TanStack/ai.svg?style=social&label=Star" alt="GitHub stars" /> </a>- <a href="#badge"> - <img src="https://img.shields.io/github/v/release/tanstack/ai" alt="Release"/> - </a> + <a href="#badge"> + <img src="https://img.shields.io/github/v/release/tanstack/ai" alt="Release"/> + </a>Also applies to: 23-25
49-49: Fix heading level hierarchy.Line 49 uses
###(h3) but should use##(h2) to maintain proper heading increments.🔎 Proposed fix
-### <a href="https://tanstack.com/ai">Read the docs →</b></a> +## <a href="https://tanstack.com/ai">Read the docs →</b></a>📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 3e685ee9959846ff27c0d56c1d6f6f1a7ff3aa62 and 38487993275ce0375a4b9ca4ff3aa97aba881a3c.
📒 Files selected for processing (3)
docs/api/ai-preact.mddocs/config.jsonpackages/typescript/ai-preact/README.md
✅ Files skipped from review due to trivial changes (1)
- docs/api/ai-preact.md
🧰 Additional context used
🧠 Learnings (7)
📓 Common learnings
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Implement framework integrations using the headless `tanstack/ai-client` for state management with framework-specific hooks (useChat) on topLearnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/index.ts : Export tree-shakeable adapters with clear subpath exports in package.json (e.g., `tanstack/ai/adapters`, `tanstack/ai-openai/adapters`) to minimize bundle size📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/*/package.json : Use `workspace:*` protocol for internal package dependencies in package.json (e.g., `"tanstack/ai": "workspace:*"`)Applied to files:
docs/config.json
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/index.ts : Export tree-shakeable adapters with clear subpath exports in package.json (e.g., `tanstack/ai/adapters`, `tanstack/ai-openai/adapters`) to minimize bundle sizeApplied to files:
packages/typescript/ai-preact/README.md
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/adapters/*.ts : Create individual adapter implementations for each provider capability (text, embed, summarize, image) with separate exports to enable tree-shakingApplied to files:
packages/typescript/ai-preact/README.md
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Use tree-shakeable adapter architecture for provider implementations - export specialized adapters (text, embedding, summarize, image) as separate imports from `/adapters` subpath rather than monolithic adaptersApplied to files:
packages/typescript/ai-preact/README.md
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Implement isomorphic tool system using `toolDefinition()` with `.server()` and `.client()` implementations for dual-environment executionApplied to files:
packages/typescript/ai-preact/README.md
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Implement framework integrations using the headless `tanstack/ai-client` for state management with framework-specific hooks (useChat) on topApplied to files:
packages/typescript/ai-preact/README.md
🪛 markdownlint-cli2 (0.18.1)
packages/typescript/ai-preact/README.md
2-2: Images should have alternate text (alt text)
(MD045, no-alt-text)
12-12: Hard tabs Column: 1
(MD010, no-hard-tabs)
23-23: Hard tabs Column: 1
(MD010, no-hard-tabs)
24-24: Hard tabs Column: 1
(MD010, no-hard-tabs)
25-25: Hard tabs Column: 1
(MD010, no-hard-tabs)
49-49: Heading levels should only increment by one level at a time Expected: h2; Actual: h3
(MD001, heading-increment)
🔇 Additional comments (1)
docs/config.json (1)
122-125: LGTM!The navigation entry for
@tanstack/ai-preactis properly structured and positioned alphabetically within the API section.@@ -0,0 +53,21 @@53+Import only the functionality you need for smaller bundle sizes:54+55+```typescript56+// Only chat functionality - no summarization code bundled57+import { openaiText } from '@tanstack/ai-openai/adapters'58+import { generate } from '@tanstack/ai'59+60+const textAdapter = openaiText()61+62+const result = generate({63+ adapter: textAdapter,64+ model: 'gpt-4o',65+ messages: [{ role: 'user', content: [{ type: 'text', content: 'Hello!' }] }],66+})67+68+for await (const chunk of result) {69+ console.log(chunk)70+}71+```72+73+Available adapters: `openaiText`, `openaiEmbed`, `openaiSummarize`, `anthropicText`, `geminiText`, `ollamaText`, and more.⚠️ Potential issue | 🟠 Major
Add Preact-specific documentation and usage examples.
The README contains generic TanStack AI content but lacks Preact-specific documentation. Users need to see:
- Installation instructions for
@tanstack/ai-preact - Preact-specific imports (e.g.,
import { useChat } from '@tanstack/ai-preact') - Preact component examples using the
useChathook - Minimum version requirements (Preact >= 10.11.0, per PR objectives)
- Quick start example showing a complete Preact chat component
The current tree-shakeable adapters example (lines 55-71) uses generic
@tanstack/aiimports and doesn't demonstrate the Preact integration at all.💡 Suggested structure
Consider adding a "Quick Start" section after the feature list with a Preact-specific example:
## Quick Start ### Installation \`\`\`bash npm install @tanstack/ai-preact @tanstack/ai-client \`\`\` **Requirements:** Preact >= 10.11.0 ### Basic Usage \`\`\`tsx import { useChat } from '@tanstack/ai-preact' import { ChatClient } from '@tanstack/ai-client' import { openaiText } from '@tanstack/ai-openai/adapters' const chatClient = new ChatClient({ adapter: openaiText(), model: 'gpt-4o', }) function ChatComponent() { const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({ client: chatClient, }) return ( <div> <div> {messages.map((message) => ( <div key={message.id}> <strong>{message.role}:</strong> {message.content} </div> ))} </div> <form onSubmit={handleSubmit}> <input value={input} onChange={handleInputChange} disabled={isLoading} /> <button type="submit" disabled={isLoading}> Send </button> </form> </div> ) } \`\`\`🧰 Tools
🪛 markdownlint-cli2 (0.18.1)
49-49: Heading levels should only increment by one level at a time Expected: h2; Actual: h3
(MD001, heading-increment)
🤖 Prompt for AI Agents
In packages/typescript/ai-preact/README.md around lines 36 to 73, the README is generic TanStack AI content and lacks Preact-specific docs; add a "Quick Start" section that includes installation instructions for @tanstack/ai-preact and @tanstack/ai-client, state the minimum Preact version requirement (Preact >= 10.11.0), show Preact-specific imports (e.g., import { useChat } from '@tanstack/ai-preact' and ChatClient usage), and include a concise Preact component example demonstrating useChat with messages, input handling, submit flow and loading state so users can copy-paste a complete working chat component.AlemTuzlak approved these changes
would you be down for implementing the devtools as well?
View your CI Pipeline Execution ↗ for commit 42d16a25b47cc0fe6fe0f89cd1d53f9fafa54717
Command Status Duration Result nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded 1m 16s View ↗ nx run-many --targets=build --exclude=examples/**✅ Succeeded 36s View ↗
☁️ Nx Cloud last updated this comment at
2026-01-05 10:56:12UTC@tanstack/ai
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai@180@tanstack/ai-anthropic
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-anthropic@180@tanstack/ai-client
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-client@180@tanstack/ai-devtools-core
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-devtools-core@180@tanstack/ai-gemini
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-gemini@180@tanstack/ai-ollama
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-ollama@180@tanstack/ai-openai
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-openai@180@tanstack/ai-preact
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-preact@180@tanstack/ai-react
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-react@180@tanstack/ai-react-ui
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-react-ui@180@tanstack/ai-solid
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-solid@180@tanstack/ai-solid-ui
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-solid-ui@180@tanstack/ai-svelte
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-svelte@180@tanstack/ai-vue
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-vue@180@tanstack/ai-vue-ui
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-vue-ui@180@tanstack/react-ai-devtools
npm i https://pkg.pr.new/TanStack/ai/@tanstack/react-ai-devtools@180@tanstack/solid-ai-devtools
npm i https://pkg.pr.new/TanStack/ai/@tanstack/solid-ai-devtools@180commit:
42d16a2@AlemTuzlak Yes, I would be open to implementing devtools, it will probably be a weekend kinda thing though
@JoviDeCroock no worries, we already provide preact utils from our devtools package so should be easy to do!
Actionable comments posted: 1
Fix all issues with AI Agents 🤖
In @packages/typescript/ai-preact/src/use-chat.ts: - Line 57: The object is incorrectly using the stale options reference for streamProcessor by reading options.streamProcessor instead of the live ref; update the assignment to use optionsRef.current.streamProcessor (matching the other properties that use optionsRef.current) so streamProcessor reflects updates across renders (e.g., replace the streamProcessor: options.streamProcessor line with streamProcessor: optionsRef.current.streamProcessor in useChat).🧹 Nitpick comments (1)
packages/typescript/ai-preact/src/use-chat.ts (1)
70-81: Consider simplifying: This effect may be redundant.The state is already initialized with
options.initialMessageson lines 20-22, and the ChatClient constructor receivesinitialMessages(line 50), which should triggeronMessagesChangeduring initialization. The condition!messages.lengthon line 77 would typically be false since the state was initialized withinitialMessages.This effect might be handling a specific edge case that's not immediately apparent. If the ChatClient doesn't synchronously call
onMessagesChangeduring construction, this becomes necessary. Otherwise, consider whether this synchronization is still needed.📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 38487993275ce0375a4b9ca4ff3aa97aba881a3c and 42d16a25b47cc0fe6fe0f89cd1d53f9fafa54717.
📒 Files selected for processing (2)
packages/typescript/ai-preact/src/use-chat.tspackages/typescript/ai-preact/tests/test-utils.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/typescript/ai-preact/tests/test-utils.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.{ts,tsx}: Use tree-shakeable adapter architecture for provider implementations - export specialized adapters (text, embedding, summarize, image) as separate imports from/adapterssubpath rather than monolithic adapters Use Zod for runtime schema validation and type inference, particularly for tool input/output definitions withtoolDefinition()and Zod schema inference Implement isomorphic tool system usingtoolDefinition()with.server()and.client()implementations for dual-environment execution Use type-safe per-model configuration with provider options typed based on selected model to ensure compile-time safety Implement stream processing with StreamProcessor for handling chunked responses and support partial JSON parsing for streaming AI responsesFiles:
packages/typescript/ai-preact/src/use-chat.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (CLAUDE.md)
Use camelCase for function and variable names throughout the codebase
Files:
packages/typescript/ai-preact/src/use-chat.ts
🧠 Learnings (2)
📓 Common learnings
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Implement framework integrations using the headless `tanstack/ai-client` for state management with framework-specific hooks (useChat) on topLearnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/index.ts : Export tree-shakeable adapters with clear subpath exports in package.json (e.g., `tanstack/ai/adapters`, `tanstack/ai-openai/adapters`) to minimize bundle size📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Implement framework integrations using the headless `tanstack/ai-client` for state management with framework-specific hooks (useChat) on topApplied to files:
packages/typescript/ai-preact/src/use-chat.ts
🧬 Code graph analysis (1)
packages/typescript/ai-preact/src/use-chat.ts (2)
packages/typescript/ai-preact/src/types.ts (3)
UseChatOptions(26-30)UseChatReturn(32-98)UIMessage(9-9)
packages/typescript/ai-client/src/chat-client.ts (8)
setIsLoading(181-185)setError(187-191)append(265-285)reload(336-354)stop(359-366)setMessagesManually(509-511)addToolResult(380-408)addToolApprovalResponse(413-450)
🔇 Additional comments (4)
packages/typescript/ai-preact/src/use-chat.ts (4)
1-12: LGTM! Clean imports following the headless client pattern.The imports correctly separate Preact-specific hooks from the headless ChatClient, aligning with the framework integration pattern.
Based on learnings, this follows the established pattern of building framework-specific hooks on top of the headless
@tanstack/ai-client.
83-91: LGTM! Proper cleanup with clear dependency reasoning.The cleanup effect correctly stops in-flight requests when the component unmounts or the client changes. The inline comment usefully explains why
isLoadingis deliberately excluded from dependencies to avoid aborting continuation requests.
96-161: LGTM! Callback methods and return object correctly implemented.All methods are properly memoized with
useCallbackand depend on[client]to ensure stable references while responding to client changes. The return object correctly exposes the complete API surface defined inUseChatReturn, with each method appropriately delegating to the underlying ChatClient.
39-68: The connection adapter design supports lazy evaluation—no client recreation needed for dynamic connection values.The architecture intentionally uses function-based parameters in connection adapters (like
fetchServerSentEvents(url: string | (() => string), options: ... | (() => ...))) which are evaluated lazily on each request. This allows dynamic behavior (changing URLs, headers, credentials) without recreating the ChatClient instance.If connection values need to change dynamically (URL, headers, etc.), pass functions to the adapter at creation time rather than replacing the adapter reference itself. The comment on lines 93–95 correctly states that replacing the connection adapter requires client recreation, but this is intentional—the design expects you to use lazy-evaluated functions within the adapter instead.
Likely an incorrect or invalid review comment.
@@ -0,0 +37,21 @@37+ }, [messages])38+39+ const client = useMemo(() => {40+ // On first mount, use initialMessages. On subsequent recreations, preserve existing messages.41+ const messagesToUse = isFirstMountRef.current42+ ? options.initialMessages || []43+ : messagesRef.current44+45+ isFirstMountRef.current = false46+47+ return new ChatClient({48+ connection: optionsRef.current.connection,49+ id: clientId,50+ initialMessages: messagesToUse,51+ body: optionsRef.current.body,52+ onResponse: optionsRef.current.onResponse,53+ onChunk: optionsRef.current.onChunk,54+ onFinish: optionsRef.current.onFinish,55+ onError: optionsRef.current.onError,56+ tools: optionsRef.current.tools,57+ streamProcessor: options.streamProcessor,⚠️ Potential issue | 🔴 Critical
Critical: Inconsistent options reference for
streamProcessor.Line 57 uses
options.streamProcessordirectly, while all other option properties (lines 48-56) correctly useoptionsRef.current. This inconsistency meansstreamProcessorwill capture the stale value from the initial render, while other options update correctly.🔎 Proposed fix
- streamProcessor: options.streamProcessor, + streamProcessor: optionsRef.current.streamProcessor,📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change57- streamProcessor: options.streamProcessor,57+ streamProcessor: optionsRef.current.streamProcessor,🤖 Prompt for AI Agents
In @packages/typescript/ai-preact/src/use-chat.ts around line 57, The object is incorrectly using the stale options reference for streamProcessor by reading options.streamProcessor instead of the live ref; update the assignment to use optionsRef.current.streamProcessor (matching the other properties that use optionsRef.current) so streamProcessor reflects updates across renders (e.g., replace the streamProcessor: options.streamProcessor line with streamProcessor: optionsRef.current.streamProcessor in useChat).AlemTuzlak merged this5692609
AlemTuzlak closed this
Sign in to join this conversation.
📝 Walkthrough
Walkthrough#
Adds a new
@tanstack/ai-preactpackage: package metadata, TypeScript types, a PreactuseChathook with ChatClient lifecycle/actions, Vite/Vitest configs, docs, tests, and a changeset/CHANGELOG.Changes#
\.changeset/tired-years-stick.md,packages/typescript/ai-preact/CHANGELOG.md,packages/typescript/ai-preact/README.md,docs/api/ai-preact.md,docs/config.json@tanstack/ai-preact.Package manifest & config,
packages/typescript/ai-preact/package.json,packages/typescript/ai-preact/tsconfig.json,packages/typescript/ai-preact/vite.config.ts,packages/typescript/ai-preact/vitest.config.tspackages/typescript/ai-preact/src/index.tsuseChat, local type exports, and re-exports utilities/types from@tanstack/ai-client.packages/typescript/ai-preact/src/types.tsUseChatOptionsandUseChatReturntypes and re-exportsUIMessage/ChatRequestBody.packages/typescript/ai-preact/src/use-chat.tsuseChathook: manages messages, loading/error, preserves messages across client reconstructions, creates/stops ChatClient, and exposes control methods (sendMessage, append, reload, stop, clear, addToolResult, addToolApprovalResponse).packages/typescript/ai-preact/tests/test-utils.ts,packages/typescript/ai-preact/tests/use-chat.test.tsSequence Diagram(s)#
Estimated code review effort#
🎯 4 (Complex) | ⏱️ ~45 minutes
Suggested reviewers#
Poem#
Pre-merge checks and finishing touches#
❌ Failed checks (1 warning)
@coderabbitai generate docstringsto improve docstring coverage.✅ Passed checks (2 passed)
✨ Finishing touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share