Skip to content
Source
Sign inSign up
TanStack/ai

Add preact integration #180

MergedJoviDeCroock(GitHub profile, opens in a new tab)merged 7 commits intomain fromrefs/pull/180/headmerged 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.
✏️ Tip: You can customize this high-level summary in your review settings.
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      📝 Walkthrough

      Walkthrough

      Adds a new @tanstack/ai-preact package: package metadata, TypeScript types, a Preact useChat hook with ChatClient lifecycle/actions, Vite/Vitest configs, docs, tests, and a changeset/CHANGELOG.

      Changes

      Cohort / File(s)Summary
      Release & docs
      \.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
      New changeset and changelog; package README and API docs added; docs navigation updated to include @tanstack/ai-preact.
      Package config & build
      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.ts
      New package.json, TypeScript project config, Vite and Vitest configs (Vitest includes a path alias). Review build/test config and peerDependencies.
      Public API surface
      packages/typescript/ai-preact/src/index.ts
      Exports useChat, local type exports, and re-exports utilities/types from @tanstack/ai-client.
      Types
      packages/typescript/ai-preact/src/types.ts
      Adds UseChatOptions and UseChatReturn types and re-exports UIMessage / ChatRequestBody.
      Hook implementation
      packages/typescript/ai-preact/src/use-chat.ts
      New useChat hook: manages messages, loading/error, preserves messages across client reconstructions, creates/stops ChatClient, and exposes control methods (sendMessage, append, reload, stop, clear, addToolResult, addToolApprovalResponse).
      Tests & test utils
      packages/typescript/ai-preact/tests/test-utils.ts, packages/typescript/ai-preact/tests/use-chat.test.ts
      Test helpers and an extensive test suite for hook behaviors, state sync, streaming, error paths, tool workflows, and edge cases.

      Sequence Diagram(s)

      sequenceDiagram
        participant UI as Preact UI
        participant Hook as useChat (hook)
        participant Client as ChatClient
        participant Adapter as ConnectionAdapter / Server
      
        rect rgb(243,247,255)
          Note over Hook,Client: Hook creates ChatClient on mount with provided options
          UI->>Hook: mount + options
          Hook->>Client: create/initialize client (initialMessages, callbacks, tools)
          Client->>Adapter: open connection / send request
        end
      
        rect rgb(255,248,225)
          UI->>Hook: sendMessage(content)
          Hook->>Client: sendMessage -> start streaming
          Adapter-->>Client: SSE / chunk events
          Client->>Hook: onChunk / onResponse / onFinish
          Hook->>UI: update messages (isLoading true → false)
        end
      
        rect rgb(255,239,241)
          UI->>Hook: stop()
          Hook->>Client: stop/cancel
          Client->>Adapter: cancel connection
          Hook->>UI: clear loading / finalize state
        end

      Estimated code review effort

      🎯 4 (Complex) | ⏱️ ~45 minutes

      Suggested reviewers

      • jherr
      • AlemTuzlak

      Poem

      "I nibble code in moonlit patch, A new hook springs from carrot scratch. Messages hop, streams softly flow, Tests and docs in tidy row. 🐇🌿"

      Pre-merge checks and finishing touches

      ❌ Failed checks (1 warning)
      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 50.00% which is insufficient. The required threshold is 80.00%.You can run @coderabbitai generate docstrings to improve docstring coverage.
      ✅ Passed checks (2 passed)
      Check nameStatusExplanation
      Title check✅ PassedThe PR title 'Add preact integration' directly and clearly describes the main objective: introducing a new Preact integration to the TanStack AI library. It accurately summarizes the primary change shown across all files.
      Description check✅ PassedThe PR description addresses the required template sections: it provides a clear explanation of changes (Preact integration adapted from React), mentions testing completion, and confirms changeset generation. However, it does not explicitly check the 'Contributing guide' checklist item as required by the template.
      ✨ Finishing touches
      • 📝 Generate docstrings

      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
      Comment `@coderabbitai help` to get the list of available commands and usage tips.
    2. Actionable comments posted: 2

      🧹 Nitpick comments (8)
      packages/typescript/ai-preact/package.json (1)

      46-52: Missing vitest in devDependencies.

      The test script uses vitest run, but vitest is 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 vs vitest.config.ts.

      This file sets environment: 'node', while vitest.config.ts sets environment: 'jsdom'. When running vitest, the dedicated vitest.config.ts takes precedence, making the test configuration here potentially unused or confusing.

      Consider either:

      1. Removing the test block from this file (keeping it build-only), or
      2. 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 UseChatOptions uses a type assertion to cast an empty object. If UseChatOptions has required properties (like connection), this could lead to runtime errors when renderUseChat() 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), but streamProcessor on line 58 is accessed directly from options. 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 on UIMessage.

      The append callback uses UIMessage without the <TTools> parameter, which could cause type inconsistencies since UIMessage is 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 adapter2 created on line 395 is passed to rerender on line 410, but since the clientId doesn't change (no id prop change), the useMemo won't recreate the client. The client will continue using the original adapter. The onConnect callback approach also appears unused since callCount increments 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 error becomes undefined after the successful operation. Additionally, since the client isn't recreated on rerender (same clientId), the workingAdapter won'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 (the clientId remains 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.yaml is excluded by !**/pnpm-lock.yaml
      📒 Files selected for processing (12)
      • .changeset/tired-years-stick.md
      • packages/typescript/ai-preact/CHANGELOG.md
      • packages/typescript/ai-preact/README.md
      • packages/typescript/ai-preact/package.json
      • packages/typescript/ai-preact/src/index.ts
      • packages/typescript/ai-preact/src/types.ts
      • packages/typescript/ai-preact/src/use-chat.ts
      • packages/typescript/ai-preact/tests/test-utils.ts
      • packages/typescript/ai-preact/tests/use-chat.test.ts
      • packages/typescript/ai-preact/tsconfig.json
      • packages/typescript/ai-preact/vite.config.ts
      • packages/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 /adapters subpath rather than monolithic adapters Use Zod for runtime schema validation and type inference, particularly for tool input/output definitions with toolDefinition() and Zod schema inference Implement isomorphic tool system using toolDefinition() 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 responses

      Files:

      • packages/typescript/ai-preact/src/index.ts
      • packages/typescript/ai-preact/tests/test-utils.ts
      • packages/typescript/ai-preact/vitest.config.ts
      • packages/typescript/ai-preact/src/types.ts
      • packages/typescript/ai-preact/src/use-chat.ts
      • packages/typescript/ai-preact/tests/use-chat.test.ts
      • packages/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 size

      Files:

      • 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.ts
      • packages/typescript/ai-preact/tests/test-utils.ts
      • packages/typescript/ai-preact/vitest.config.ts
      • packages/typescript/ai-preact/src/types.ts
      • packages/typescript/ai-preact/src/use-chat.ts
      • packages/typescript/ai-preact/tests/use-chat.test.ts
      • packages/typescript/ai-preact/vite.config.ts
      **/*.test.ts

      📄 CodeRabbit inference engine (CLAUDE.md)

      Write unit tests using Vitest alongside source files with .test.ts naming convention

      Files:

      • 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 size

      Applied to files:

      • packages/typescript/ai-preact/tsconfig.json
      • packages/typescript/ai-preact/README.md
      • packages/typescript/ai-preact/src/index.ts
      • packages/typescript/ai-preact/vitest.config.ts
      • packages/typescript/ai-preact/vite.config.ts
      • packages/typescript/ai-preact/CHANGELOG.md
      • packages/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-shaking

      Applied to files:

      • packages/typescript/ai-preact/tsconfig.json
      • packages/typescript/ai-preact/README.md
      • packages/typescript/ai-preact/src/index.ts
      • packages/typescript/ai-preact/tests/test-utils.ts
      • packages/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 adapters

      Applied to files:

      • packages/typescript/ai-preact/tsconfig.json
      • packages/typescript/ai-preact/README.md
      • packages/typescript/ai-preact/src/index.ts
      • packages/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 inference

      Applied 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 safety

      Applied to files:

      • packages/typescript/ai-preact/tsconfig.json
      • packages/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 files

      Applied to files:

      • packages/typescript/ai-preact/tsconfig.json
      • packages/typescript/ai-preact/vitest.config.ts
      • packages/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 rules

      Applied 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 convention

      Applied to files:

      • packages/typescript/ai-preact/tsconfig.json
      • packages/typescript/ai-preact/vitest.config.ts
      • packages/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 top

      Applied to files:

      • packages/typescript/ai-preact/README.md
      • packages/typescript/ai-preact/src/index.ts
      • packages/typescript/ai-preact/tests/test-utils.ts
      • packages/typescript/ai-preact/src/types.ts
      • packages/typescript/ai-preact/src/use-chat.ts
      • packages/typescript/ai-preact/tests/use-chat.test.ts
      • packages/typescript/ai-preact/CHANGELOG.md
      • packages/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 publishing

      Applied 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-client while 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-client for state management with a framework-specific hook on top. The re-exports from @tanstack/ai-client provide 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 ChatClient from @tanstack/ai-client for 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.ts naming 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" >
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      ⚠️ Potential issue | 🟡 Minor

      Add alt text to the header image for accessibility.

      The header image is missing the alt attribute, 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 change
      2- <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.
    3. 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 alt attribute (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 size

      Applied 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-shaking

      Applied 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 adapters

      Applied 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 execution

      Applied 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 top

      Applied 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" />
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      ⚠️ 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 AI
      37+
      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 bundles
      42+- **Multimodal content support** - Send images, audio, video, and documents
      43+- **Image generation** - Generate images with OpenAI DALL-E/GPT-Image and Gemini Imagen
      44+- Chat completion, streaming, and agent loop strategies
      45+- Headless chat state management with adapters (SSE, HTTP stream, custom)
      46+- Isomorphic type-safe tools with server/client execution
      47+- **Enhanced integration with TanStack Start** - Share implementations between AI tools and server functions
      48+
      49+### <a href="https://tanstack.com/ai">Read the docs →</b></a>
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      ⚠️ 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 change
      49-### <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.
    4. 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 alt attribute, 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.md
      • docs/config.json
      • packages/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 top
      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 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 size

      Applied 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-shaking

      Applied 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 adapters

      Applied 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 execution

      Applied 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 top

      Applied 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-preact is 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+```typescript
      56+// Only chat functionality - no summarization code bundled
      57+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.
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      ⚠️ 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:

      1. Installation instructions for @tanstack/ai-preact
      2. Preact-specific imports (e.g., import { useChat } from '@tanstack/ai-preact')
      3. Preact component examples using the useChat hook
      4. Minimum version requirements (Preact >= 10.11.0, per PR objectives)
      5. Quick start example showing a complete Preact chat component

      The current tree-shakeable adapters example (lines 55-71) uses generic @tanstack/ai imports 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.
    5. AlemTuzlak approved these changes

      would you be down for implementing the devtools as well?

    6. nx-cloud[bot](GitHub profile, opens in a new tab)commented

      View your CI Pipeline Execution ↗ for commit 42d16a25b47cc0fe6fe0f89cd1d53f9fafa54717

      CommandStatusDurationResult
      nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded1m 16sView ↗
      nx run-many --targets=build --exclude=examples/**✅ Succeeded36sView ↗

      ☁️ Nx Cloud last updated this comment at 2026-01-05 10:56:12 UTC

    7. pkg-pr-new[bot](GitHub profile, opens in a new tab)commented

      Open in StackBlitz

      @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@180

      commit: 42d16a2

    8. @AlemTuzlak Yes, I would be open to implementing devtools, it will probably be a weekend kinda thing though

    9. @JoviDeCroock no worries, we already provide preact utils from our devtools package so should be easy to do!

    10. 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.initialMessages on lines 20-22, and the ChatClient constructor receives initialMessages (line 50), which should trigger onMessagesChange during initialization. The condition !messages.length on line 77 would typically be false since the state was initialized with initialMessages.

      This effect might be handling a specific edge case that's not immediately apparent. If the ChatClient doesn't synchronously call onMessagesChange during 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.ts
      • packages/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 /adapters subpath rather than monolithic adapters Use Zod for runtime schema validation and type inference, particularly for tool input/output definitions with toolDefinition() and Zod schema inference Implement isomorphic tool system using toolDefinition() 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 responses

      Files:

      • 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 top
      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 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 top

      Applied 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 isLoading is 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 useCallback and depend on [client] to ensure stable references while responding to client changes. The return object correctly exposes the complete API surface defined in UseChatReturn, 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.current
      42+ ? options.initialMessages || []
      43+ : messagesRef.current
      44+
      45+ isFirstMountRef.current = false
      46+
      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,
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      ⚠️ Potential issue | 🔴 Critical

      Critical: Inconsistent options reference for streamProcessor.

      Line 57 uses options.streamProcessor directly, while all other option properties (lines 48-56) correctly use optionsRef.current. This inconsistency means streamProcessor will 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 change
      57- 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).
    11. AlemTuzlak merged this5692609

    12. AlemTuzlak closed this

Sign in to join this conversation.