Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions app/base/e2e/global-setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* Warm the dev server's SSR routes before the suite runs. `vite dev` compiles
* each route on first request, and the first navigation (`/` → `/setup`) under
* CI load could exceed the test timeout, leaving the owner-setup form not yet
* rendered. The webServer readiness check only hits `/api/cms/v1/health` (the
* API), so the SSR routes stay cold. Here we poll health, then GET the routes
* the suite starts on so their first real navigation is warm.
*/
const BASE = 'http://127.0.0.1:3035'
const WARM_ROUTES = ['/', '/setup', '/login']

async function waitForHealth(deadline: number): Promise<void> {
while (Date.now() < deadline) {
try {
const res = await fetch(`${BASE}/api/cms/v1/health`)
if (res.ok) return
} catch {
// server not up yet
}
await new Promise((r) => setTimeout(r, 500))
}
throw new Error('e2e warm-up: server health never became ready')
}

export default async function globalSetup(): Promise<void> {
await waitForHealth(Date.now() + 120_000)
for (const route of WARM_ROUTES) {
try {
await fetch(`${BASE}${route}`, { redirect: 'manual' })
} catch {
// A warm-up miss is non-fatal; the test will still navigate.
}
}
}
6 changes: 5 additions & 1 deletion app/base/playwright.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,14 @@ export default defineConfig({
workers: 1,
fullyParallel: false,
forbidOnly: !!process.env.CI,
retries: 0,
// On CI the first cold `vite dev` route compile can still flake under load;
// a retry runs against the now-warm server. Local runs stay at 0.
retries: process.env.CI ? 2 : 0,
timeout: 90000,
expect: { timeout: 15000 },
reporter: 'list',
// Warm the SSR routes (health-gated) so the first navigation isn't a cold compile.
globalSetup: './e2e/global-setup.ts',
use: { baseURL: 'http://127.0.0.1:3035', trace: 'retain-on-failure' },
projects: [
{
Expand Down
17 changes: 13 additions & 4 deletions app/base/src/cms.config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { createServerOnlyFn } from '@tanstack/react-start'
import { defineCms, interfaceScheduleHandlers } from '@tanstack/cms-core'
import { aiRuntime } from '@tanstack/cms-core/ai'
import { quickjsInterfaceRuntime } from '@tanstack/cms-core/interfaces-quickjs'
import { createPgliteStorage } from '@tanstack/cms-store-postgres/pglite'
import { seed } from './seed'
import { baseOps } from './operations'
Expand All @@ -16,7 +14,14 @@ export const cms = defineCms(definition, {
ops: baseOps,
interfaces: {
collection: 'interfaces',
runtime: quickjsInterfaceRuntime(),
// Server-only: a dynamic import keeps the QuickJS/code-mode (and its
// transitive @tanstack/ai) packages out of the client bundle.
runtime: createServerOnlyFn(
async () =>
(
await import('@tanstack/cms-core/interfaces-quickjs')
).quickjsInterfaceRuntime(),
),
scheduleSession: createServerOnlyFn(async (userId: string) =>
(await import('./auth.server')).scheduleSession(userId),
),
Expand All @@ -40,7 +45,11 @@ export const cms = defineCms(definition, {
events: { dispatch: 'manual' },
security: { trustForwardedHost: true },
ai: {
runtime: aiRuntime(),
// Server-only: a dynamic import keeps `@tanstack/ai` out of the client
// bundle this isomorphic config is also pulled into.
runtime: createServerOnlyFn(
async () => (await import('@tanstack/cms-core/ai')).aiRuntime(),
),
textAdapter: createServerOnlyFn(async () =>
(await import('./ai.server')).textAdapter(),
),
Expand Down
5 changes: 3 additions & 2 deletions app/prm/src/cms.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
*/
import { createServerOnlyFn } from '@tanstack/react-start'
import { defineCms, PERMISSIONS } from '@tanstack/cms-core'
import { aiRuntime } from '@tanstack/cms-core/ai'
import { createPgliteStorage } from '@tanstack/cms-store-postgres/pglite'
import { seed } from './seed'
import { importPeopleOp } from './ops/import-people'
Expand Down Expand Up @@ -112,7 +111,9 @@ export const cms = defineCms(definition, {
],
},
ai: {
runtime: aiRuntime(),
// Server-only: dynamic import keeps @tanstack/ai out of the client bundle
// this isomorphic config is pulled into (see textAdapter below).
runtime: async () => (await import('@tanstack/cms-core/ai')).aiRuntime(),
textAdapter: async () => {
if (!process.env.ANTHROPIC_API_KEY) return null
const { anthropicText } = await import('@tanstack/ai-anthropic')
Expand Down
20 changes: 16 additions & 4 deletions packages/core/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ import type {
OpInputOf,
OpOutputOf,
} from './ops'
import type { InterfaceRuntime } from './interfaces'
import type { InterfaceRuntimeInput } from './interfaces'
import type { CmsEventsConfig, EventHandlerDefinition } from './events'
import type { AnyDocumentStateStrategy } from './document-state'
import type { PublishingStrategy } from './publishing'
Expand Down Expand Up @@ -148,13 +148,25 @@ export interface CmsAiRuntime {
toolDefinition: unknown
}

/**
* A `CmsAiRuntime`, or a (server-only) provider that returns one. Use the
* provider form in an app whose config is imported on the client (e.g. a
* TanStack Start admin) so `@tanstack/ai` stays out of the client bundle:
* `runtime: createServerOnlyFn(async () => (await import('@tanstack/cms-core/ai')).aiRuntime())`.
* A headless/server-only config can pass `aiRuntime()` directly.
*/
export type CmsAiRuntimeInput =
| CmsAiRuntime
| (() => CmsAiRuntime | Promise<CmsAiRuntime>)

export interface CmsAiConfig {
/**
* The `@tanstack/ai` runtime used to build agent tools (required for agent
* tools / MCP / the content agent). Supply with `aiRuntime()` from
* `@tanstack/cms-core/ai`. Text/image generation live in `@tanstack/cms-api`.
* `@tanstack/cms-core/ai` — directly in a server-only config, or behind a
* server-only provider when the config is also imported on the client.
*/
runtime?: CmsAiRuntime
runtime?: CmsAiRuntimeInput
/** A `@tanstack/ai` text adapter (OpenAI, Anthropic, Gemini, Ollama, …). */
textAdapter?: () => unknown
/** A `@tanstack/ai` image adapter; it must accept an input image to support edits. */
Expand Down Expand Up @@ -317,7 +329,7 @@ export interface CmsConfig {
* `import { quickjsInterfaceRuntime } from '@tanstack/cms-core/interfaces-quickjs'`
* then `runtime: quickjsInterfaceRuntime()`.
*/
runtime: InterfaceRuntime
runtime: InterfaceRuntimeInput
/** Resolve the schedule owner's CURRENT access; null suspends execution. Server-only. */
scheduleSession?: (
userId: string,
Expand Down
10 changes: 10 additions & 0 deletions packages/core/src/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,16 @@ export interface InterfaceRuntime {
createDriver: () => Promise<IsolateDriver> | IsolateDriver
stripTypeScript: (code: string) => Promise<string>
}

/**
* An `InterfaceRuntime`, or a (server-only) provider that returns one. Use the
* provider form when the config is also imported on the client (e.g. a TanStack
* Start admin) so the QuickJS/code-mode packages stay out of the client bundle:
* `runtime: createServerOnlyFn(async () => (await import('@tanstack/cms-core/interfaces-quickjs')).quickjsInterfaceRuntime())`.
*/
export type InterfaceRuntimeInput =
| InterfaceRuntime
| (() => InterfaceRuntime | Promise<InterfaceRuntime>)
export const interfaceInputSchema = z
.object({
id: z.string().regex(/^[a-z][a-z0-9-]{0,99}$/),
Expand Down
6 changes: 4 additions & 2 deletions packages/core/src/server/cms-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,15 +63,17 @@ function callAccess(toolCtx: unknown): AccessContext | undefined {
}

export async function cmsTools(actor: string, options?: CmsToolsOptions) {
const runtime = getCmsConfig().ai?.runtime
if (!runtime) {
const provided = getCmsConfig().ai?.runtime
if (!provided) {
throw new CmsError(
'Agent tools need an AI runtime. Add: ' +
"import { aiRuntime } from '@tanstack/cms-core/ai'" +
' then `defineCms({ ai: { runtime: aiRuntime(), ... } })`.',
'NOT_CONFIGURED',
)
}
// The provider form (server-only) keeps `@tanstack/ai` out of a client bundle.
const runtime = typeof provided === 'function' ? await provided() : provided
// A type-only `import()` keeps the precise `@tanstack/ai` type without a
// value import (which would pull it into core's bundle).
// oxlint-disable-next-line typescript/consistent-type-imports
Expand Down
16 changes: 9 additions & 7 deletions packages/core/src/server/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,21 +117,23 @@ export function createInterfaceQuery(
}
}
/** The injected interface runtime, or a `NOT_CONFIGURED` error naming the fix. */
function interfaceRuntime(): InterfaceRuntime {
const runtime = getCmsConfig().interfaces?.runtime
if (!runtime) {
async function interfaceRuntime(): Promise<InterfaceRuntime> {
const provided = getCmsConfig().interfaces?.runtime
if (!provided) {
throw new CmsError(
'Code-mode interfaces need a runtime. Add: ' +
"import { quickjsInterfaceRuntime } from '@tanstack/cms-core/interfaces-quickjs'" +
' then `defineCms({ interfaces: { collection, runtime: quickjsInterfaceRuntime() } })`.',
'NOT_CONFIGURED',
)
}
return runtime
// The provider form (server-only) keeps the QuickJS/code-mode packages out of
// a client bundle the isomorphic config is also pulled into.
return typeof provided === 'function' ? await provided() : provided
}

export async function interfaceDriver(): Promise<IsolateDriver> {
return interfaceRuntime().createDriver()
return (await interfaceRuntime()).createDriver()
}
const jsonResult = z.record(z.string(), z.json())
/** Every run uses fresh isolates; persistence is the stored code, not a shared VM. */
Expand Down Expand Up @@ -185,7 +187,7 @@ export async function executeInterface(
return { result, evidence }
}
async function validateHandlerSyntax(code: string) {
const runtime = interfaceRuntime()
const runtime = await interfaceRuntime()
const { stripTypeScript } = runtime
const sandbox = await (
await runtime.createDriver()
Expand All @@ -210,7 +212,7 @@ async function executeCode(
event?: JsonValue,
stageWrites = true,
) {
const runtime = interfaceRuntime()
const runtime = await interfaceRuntime()
const { stripTypeScript } = runtime
const driver = await runtime.createDriver()
let bindingError: unknown
Expand Down
Loading