Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(home): request AI models inside the user's plan (#8214)

teo99c37e7023f3
diff --git a/.agents/rules/web/data.md b/.agents/rules/web/data.md
index a0d304192a..71709f184d 100644
--- a/.agents/rules/web/data.md
+++ b/.agents/rules/web/data.md
@@ -28,6 +28,12 @@ Queries, caching, and where data is fetched.
- **FE-07** Don't hardcode backend-owned config in the frontend (e.g. system bot
config) — fetch it dynamically or generate types from the backend source of
truth.
+- **FE-57** Never hardcode a `provider/model` id. Pick AI models from
+ `@core/component/AI/constant` by plan: `FREE_DEFAULT_MODEL` for AI every plan
+ runs, `defaultModelForPlan`/`modelsForPlan` for user choices. `FREE_MODELS`
+ is generated from the backend's `FreeTierModel` schema, and the backend 403s
+ anything outside the user's plan. Enforced by ast-grep
+ `ts-no-hardcoded-model-id` + `tsx-no-hardcoded-model-id`, error.
- **FE-29** Every new query call site (`useQuery`/`useInfiniteQuery` or a hook
from `src/lib/queries/**`) needs a deliberate `Suspense` boundary: reading
`query.data` suspends to the *nearest ancestor* boundary. When reviewing, walk
diff --git a/apps/web/src/features/home/components/home-suggestions.test.tsx b/apps/web/src/features/home/components/home-suggestions.test.tsx
index c24057000b..3264fb8f05 100644
--- a/apps/web/src/features/home/components/home-suggestions.test.tsx
+++ b/apps/web/src/features/home/components/home-suggestions.test.tsx
@@ -45,4 +45,37 @@ describe('HomeSuggestions', () => {
expect(onOpen).toHaveBeenCalledExactlyOnceWith(items[1]);
expect(onSelect).toHaveBeenCalledTimes(1);
});
+
+ it('offers Try again for a retryable failure', () => {
+ const onRetry = vi.fn();
+ const view = render(() => (
+ <HomeSuggestions
+ view={{ kind: 'error', retryable: true }}
+ onSelect={vi.fn()}
+ onOpen={vi.fn()}
+ onRetry={onRetry}
+ onConnect={vi.fn()}
+ />
+ ));
+
+ fireEvent.click(view.getByRole('button', { name: 'Try again' }));
+ expect(onRetry).toHaveBeenCalledOnce();
+ });
+
+ it('offers no Try again when the plan refused the request', () => {
+ const view = render(() => (
+ <HomeSuggestions
+ view={{ kind: 'error', retryable: false }}
+ onSelect={vi.fn()}
+ onOpen={vi.fn()}
+ onRetry={vi.fn()}
+ onConnect={vi.fn()}
+ />
+ ));
+
+ expect(
+ view.getByText('Suggestions are unavailable right now.')
+ ).toBeTruthy();
+ expect(view.queryByRole('button', { name: 'Try again' })).toBeNull();
+ });
});
diff --git a/apps/web/src/features/home/components/home-suggestions.tsx b/apps/web/src/features/home/components/home-suggestions.tsx
index 2a1545b583..540bf08b9a 100644
--- a/apps/web/src/features/home/components/home-suggestions.tsx
+++ b/apps/web/src/features/home/components/home-suggestions.tsx
@@ -10,7 +10,7 @@ import {
type RecommendedItem,
type RecommendedView,
} from '@queries/ai/homeRecommendations';
-import { For, Match, Switch } from 'solid-js';
+import { For, Match, Show, Switch } from 'solid-js';
import { Dynamic } from 'solid-js/web';
import { match } from 'ts-pattern';
@@ -88,13 +88,15 @@ export function HomeSuggestions(props: {
<Match when={props.view.kind === 'error'}>
<div class="flex flex-wrap items-center justify-between gap-3 px-4 py-3 text-sm text-ink-muted">
<span>Suggestions are unavailable right now.</span>
- <button
- type="button"
- class="rounded-lg px-2 py-1 text-accent hover:bg-hover"
- onClick={props.onRetry}
- >
- Try again
- </button>
+ <Show when={props.view.kind === 'error' && props.view.retryable}>
+ <button
+ type="button"
+ class="rounded-lg px-2 py-1 text-accent hover:bg-hover"
+ onClick={props.onRetry}
+ >
+ Try again
+ </button>
+ </Show>
</div>
</Match>
<Match when={props.view.kind === 'connect-inbox'}>
diff --git a/apps/web/src/features/home/use-home-recommendations.ts b/apps/web/src/features/home/use-home-recommendations.ts
index c0be0dccdc..b5a229e618 100644
--- a/apps/web/src/features/home/use-home-recommendations.ts
+++ b/apps/web/src/features/home/use-home-recommendations.ts
@@ -45,6 +45,7 @@ export function useHomeRecommendations() {
failed:
(emailLinks.isError && emailLinks.data === undefined) ||
recommendations.hasError(),
+ retryable: recommendations.canRetry(),
items: recommendations.items(),
emailLinked:
emailLinks.isSuccess && (emailLinks.data?.links.length ?? 0) > 0,
diff --git a/apps/web/src/features/routines/routine-creator.test.tsx b/apps/web/src/features/routines/routine-creator.test.tsx
index d0ee647739..f1f8843822 100644
--- a/apps/web/src/features/routines/routine-creator.test.tsx
+++ b/apps/web/src/features/routines/routine-creator.test.tsx
@@ -51,6 +51,7 @@ vi.mock('@core/constant/SettingsState', () => ({
vi.mock('../agents-view/primitives/open-page', () => ({
openAgentsPage: vi.fn(),
}));
+vi.mock('@core/auth/license', () => ({ useHasPaidAccess: () => () => true }));
vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));
vi.mock('@core/mobile/isTouchDevice', () => ({ isTouchDevice: () => false }));
vi.mock('@core/mobile/virtualKeyboard', () => ({
diff --git a/apps/web/src/features/routines/routine-creator.tsx b/apps/web/src/features/routines/routine-creator.tsx
index 45d86bb395..1a8d8012dd 100644
--- a/apps/web/src/features/routines/routine-creator.tsx
+++ b/apps/web/src/features/routines/routine-creator.tsx
@@ -1,7 +1,8 @@
import { openAgentsPage } from '@app/features/agents-view/primitives/open-page';
import { useSplitLayout } from '@components/app/split-layout/layout';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
-import { DEFAULT_MODEL } from '@core/component/AI/constant';
+import { useHasPaidAccess } from '@core/auth/license';
+import { defaultModelForPlan } from '@core/component/AI/constant';
import {
clearRoutineComposerDraft,
loadRoutineComposerDraft,
@@ -20,10 +21,11 @@ export function RoutineCreator(
const panel = useSplitPanelOrThrow();
const layout = useSplitLayout();
const source = createRoutineCreatorSource();
+ const hasPaidAccess = useHasPaidAccess();
return (
<RoutineCreatorView
source={source}
- defaultModel={DEFAULT_MODEL}
+ defaultModel={defaultModelForPlan(hasPaidAccess())}
storage={{
load: loadRoutineComposerDraft,
save: saveRoutineComposerDraft,
diff --git a/apps/web/src/features/routines/routine-detail.test.tsx b/apps/web/src/features/routines/routine-detail.test.tsx
index c2e9a41b02..f6ee612d49 100644
--- a/apps/web/src/features/routines/routine-detail.test.tsx
+++ b/apps/web/src/features/routines/routine-detail.test.tsx
@@ -72,8 +72,9 @@ vi.mock('./routine-triggers', () => ({
}));
vi.mock('@core/block', () => ({ useBlockId: () => 'routine-id' }));
vi.mock('@core/component/AI/constant', () => ({
- DEFAULT_MODEL: 'claude-sonnet-4-6',
+ defaultModelForPlan: () => 'claude-sonnet-4-6',
}));
+vi.mock('@core/auth/license', () => ({ useHasPaidAccess: () => () => true }));
vi.mock('@core/constant/allBlocks', () => ({
blockNameToDefaultFile: () => 'New routine',
}));
diff --git a/apps/web/src/features/routines/routine-detail.tsx b/apps/web/src/features/routines/routine-detail.tsx
index c553c4734f..c3accce693 100644
--- a/apps/web/src/features/routines/routine-detail.tsx
+++ b/apps/web/src/features/routines/routine-detail.tsx
@@ -2,8 +2,9 @@ import { openAgentsPage } from '@app/features/agents-view/primitives/open-page';
import { openBulkEditModal } from '@app/features/entity/bulk-edit/BulkEditEntityModal';
import { useSplitLayout } from '@components/app/split-layout/layout';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
+import { useHasPaidAccess } from '@core/auth/license';
import { useBlockId } from '@core/block';
-import { DEFAULT_MODEL } from '@core/component/AI/constant';
+import { defaultModelForPlan } from '@core/component/AI/constant';
import { toast } from '@core/component/Toast/Toast';
import { useUserId } from '@core/context/user';
import { writeClipboardData } from '@core/util/dataTransfer';
@@ -44,6 +45,7 @@ export function RoutineDetail(props: {
const layout = useSplitLayout();
const panel = useSplitPanelOrThrow();
const userId = useUserId();
+ const hasPaidAccess = useHasPaidAccess();
const back = () =>
props.onBack ? props.onBack() : openAgentsPage(layout, 'routines');
const open = (id: string) =>
@@ -75,7 +77,7 @@ export function RoutineDetail(props: {
<RoutineDetailView
source={source}
userId={userId}
- defaultModel={DEFAULT_MODEL}
+ defaultModel={defaultModelForPlan(hasPaidAccess())}
initialTab={props.initialTab}
onBack={back}
onDelete={remove}
diff --git a/apps/web/src/lib/core/component/AI/constant/model.ts b/apps/web/src/lib/core/component/AI/constant/model.ts
index 9c8dd41388..af0fdcb3b7 100644
--- a/apps/web/src/lib/core/component/AI/constant/model.ts
+++ b/apps/web/src/lib/core/component/AI/constant/model.ts
@@ -1,6 +1,7 @@
import OpenAiIcon from '@core/component/AI/assets/openai.svg';
import ClaudeIcon from '@icon/wide-claude.svg';
import GoogleIcon from '@phosphor-fill/google-logo-fill.svg';
+import { FreeTierModel } from '@service-cognition/generated/schemas/freeTierModel';
/**
* Frontend-owned set of model ids. These are the `provider/model` ids the
@@ -59,10 +60,18 @@ export const MODEL_PROVIDER_ICON: ExhaustiveMap = {
export const DEFAULT_MODEL: TModel = Model.sonnet55;
/**
- * Default model for free users. Free users aren't entitled to the premium
- * models (which the backend rejects with a 403), so they start on Gemini Flash.
+ * Models a free user may select, generated from the backend's free tier
+ * (`chat::domain::models::FREE_MODEL`). Every other model is paid-only: the
+ * backend rejects it with a 403, and the selector shows it locked, where
+ * selecting one opens the paywall.
*/
-export const FREE_DEFAULT_MODEL: TModel = Model.gemini38Flash;
+export const FREE_MODELS: readonly TModel[] = Object.values(FreeTierModel);
+
+/**
+ * Default model for free users, and the model for AI that runs for every plan
+ * without a model choice (e.g. Home suggestions).
+ */
+export const FREE_DEFAULT_MODEL: TModel = FREE_MODELS[0];
/** Models a paid user may select. */
export const PAID_MODELS: readonly TModel[] = Object.values(Model);
@@ -71,15 +80,7 @@ export const PAID_MODELS: readonly TModel[] = Object.values(Model);
* Model for database AI: question answering, the database assistant, and chats
* opened from a database. Available on both free and paid plans.
*/
-export const DATABASE_MODEL: TModel = Model.gemini38Flash;
-
-/**
- * Models a free user may select. Free users only get Gemini Flash
- * (`FREE_DEFAULT_MODEL`); every other model is paid-only and shows locked in
- * the selector, where selecting one opens the paywall instead of being sent
- * and rejected by the backend.
- */
-export const FREE_MODELS: readonly TModel[] = [FREE_DEFAULT_MODEL];
+export const DATABASE_MODEL: TModel = FREE_DEFAULT_MODEL;
/** The default model for a user given their paid entitlement. */
export function defaultModelForPlan(hasPaidAccess: boolean): TModel {
diff --git a/apps/web/src/lib/queries/ai/createHomeRecommendations.ts b/apps/web/src/lib/queries/ai/createHomeRecommendations.ts
index c6a6acb575..4b48b1b9ae 100644
--- a/apps/web/src/lib/queries/ai/createHomeRecommendations.ts
+++ b/apps/web/src/lib/queries/ai/createHomeRecommendations.ts
@@ -1,3 +1,4 @@
+import { FREE_DEFAULT_MODEL } from '@core/component/AI/constant';
import { PERMISSION_IDS } from '@core/constant/permissions';
import { useHasPermission } from '@core/context/user';
import {
@@ -15,20 +16,16 @@ import {
} from './homeRecommendations';
import { createAIProjection } from './projection';
-// `provider/model` id routed by the projection generator. Must stay in the
-// backend's free-tier allowlist (ai_projections FREE_TIER_MODELS). The smart
-// projection omits the model and uses the server default (the smart tier).
-const FAST_MODEL = 'anthropic/claude-haiku-4-5';
-
/**
* Fast + smart recommendation projections. The static prompt instructs the
* agent to gather non-email items through ListNotifications and emails through
* ListEntities, which preserves each entity type's canonical inbox semantics.
*
* Two projections share one prompt and schema and differ only in model: the
- * fast one (Haiku, free tier) generates inline for immediate paint; the smart
- * one (server default, premium-gated) replaces it when it lands, and is
- * skipped entirely for users without professional features.
+ * fast one (the free-tier model, available on every plan) generates inline for
+ * immediate paint; the smart one (server default, premium-gated) replaces it
+ * when it lands, and is skipped entirely for users without professional
+ * features.
*
* Result selection is pure and lives in `homeRecommendations.ts`; this hook
* only wires it to the projections.
@@ -45,7 +42,7 @@ export function createHomeRecommendations(
id: 'home/recommended-fast',
prompt: buildRecommendationPrompt(),
schema: recommendationSchema,
- model: FAST_MODEL,
+ model: FREE_DEFAULT_MODEL,
awaitGeneration: true,
refreshCadence: 'high',
expiry: 'day',
@@ -83,8 +80,10 @@ export function createHomeRecommendations(
})
);
+ const canRetry = () => !fast.isForbidden();
+
const retry = async () => {
- if (!enabled()) return;
+ if (!enabled() || !canRetry()) return;
setAttempt((value) => value + 1);
const requests = [fast.refresh()];
if (smartEnabled()) requests.push(smart.refresh());
@@ -104,6 +103,8 @@ export function createHomeRecommendations(
(timedOut() ||
(fast.error() !== undefined &&
(!smartEnabled() || smart.error() !== undefined))),
+ /** False when the plan refused the request, so retrying would fail again. */
+ canRetry,
retry,
};
}
diff --git a/apps/web/src/lib/queries/ai/homeRecommendations.ts b/apps/web/src/lib/queries/ai/homeRecommendations.ts
index c420aa4a6b..ce3e236a8a 100644
--- a/apps/web/src/lib/queries/ai/homeRecommendations.ts
+++ b/apps/web/src/lib/queries/ai/homeRecommendations.ts
@@ -135,7 +135,7 @@ export function pickRecommendations(
/** What the Recommended section should render. */
export type RecommendedView =
| { kind: 'loading' }
- | { kind: 'error' }
+ | { kind: 'error'; retryable: boolean }
| { kind: 'items'; items: RecommendedItem[] }
| { kind: 'connect-inbox' }
| { kind: 'caught-up' };
@@ -148,6 +148,8 @@ export type RecommendedView =
export function deriveRecommendedView(input: {
loading: boolean;
failed: boolean;
+ /** False when the failure would repeat on retry (the plan refused it). */
+ retryable: boolean;
items: RecommendedItem[] | undefined;
emailLinked: boolean;
}): RecommendedView {
@@ -155,7 +157,9 @@ export function deriveRecommendedView(input: {
return { kind: 'items', items: input.items };
}
if (input.loading && input.items === undefined) return { kind: 'loading' };
- if (input.failed && input.items === undefined) return { kind: 'error' };
+ if (input.failed && input.items === undefined) {
+ return { kind: 'error', retryable: input.retryable };
+ }
if (!input.emailLinked) return { kind: 'connect-inbox' };
return { kind: 'caught-up' };
}
diff --git a/apps/web/src/lib/queries/ai/projection.ts b/apps/web/src/lib/queries/ai/projection.ts
index 33213bde2d..72a98ce2c3 100644
--- a/apps/web/src/lib/queries/ai/projection.ts
+++ b/apps/web/src/lib/queries/ai/projection.ts
@@ -1,4 +1,4 @@
-import { throwOnErr } from '@core/util/result';
+import { thrownResultErrorHasCode, throwOnErr } from '@core/util/result';
import { cognitionApiServiceClient } from '@service-cognition/client';
import type { Expiry } from '@service-cognition/generated/schemas/expiry';
import type { ProjectionStateResponse } from '@service-cognition/generated/schemas/projectionStateResponse';
@@ -8,7 +8,7 @@ import type { TargetType } from '@service-cognition/generated/schemas/targetType
import type { UpsertProjectionRequest } from '@service-cognition/generated/schemas/upsertProjectionRequest';
import { createConnectionWebsocketEffect } from '@service-connection/websocket';
import { queryOptions, useQuery, useQueryClient } from '@tanstack/solid-query';
-import { type Accessor, createMemo } from 'solid-js';
+import { type Accessor, createMemo, createSignal } from 'solid-js';
import { z } from 'zod';
const AI_PROJECTION_UPDATED_MESSAGE_TYPE = 'ai_projection_updated';
@@ -44,8 +44,9 @@ export type CreateAIProjectionOptions<Schema extends z.ZodType = z.ZodType> = {
* generated as schema-conforming JSON (prompted, non-strict — works across
* providers) and `data` returns the parsed, validated object. */
schema?: Schema;
- /** Optional `provider/model` id (e.g. `cerebras/llama-3.3-70b`,
- * `anthropic/claude-haiku-4-5`). Defaults to the server's default model. */
+ /** Optional `provider/model` id from `@core/component/AI/constant`.
+ * Defaults to the server's default model, which is premium-only. A free
+ * user's request must name a model in `FREE_MODELS`. */
model?: string;
/** Whether the projection targets the user or their team. Default `user`. */
targetType?: TargetType;
@@ -148,7 +149,7 @@ function toProjectionState(
* id: 'inbox/important',
* prompt: 'Summarize my most important unread emails.',
* schema: z.object({ items: z.array(z.string()) }),
- * model: 'cerebras/llama-3.3-70b',
+ * model: FREE_DEFAULT_MODEL,
* awaitGeneration: true,
* enabled: inboxOpen(),
* }));
@@ -196,16 +197,23 @@ export function createAIProjection<Schema extends z.ZodType>(
/** Re-triggers generation even when a cached result exists. Resolves with
* the post-trigger state (`refreshing`, or the finished result when
* `awaitGeneration` is set). */
+ const [refreshError, setRefreshError] = createSignal<unknown>();
const refresh = async (): Promise<ProjectionStateResponse> => {
const key = queryKey();
- const state = await throwOnErr(
- async () =>
- await cognitionApiServiceClient.upsertAiProjection(
- buildProjectionRequest(options(), { regenerate: true })
- )
- );
- queryClient.setQueryData(key, state);
- return state;
+ try {
+ const state = await throwOnErr(
+ async () =>
+ await cognitionApiServiceClient.upsertAiProjection(
+ buildProjectionRequest(options(), { regenerate: true })
+ )
+ );
+ setRefreshError(undefined);
+ queryClient.setQueryData(key, state);
+ return state;
+ } catch (error) {
+ setRefreshError(error);
+ throw error;
+ }
};
// Do not suspend callers while the request is pending: they own the loading
@@ -271,6 +279,11 @@ export function createAIProjection<Schema extends z.ZodType>(
query.error?.message ??
parsedResult().error ??
undefined,
+ /** The server refused the request for the user's plan (403). Repeating
+ * the same request fails the same way. */
+ isForbidden: () =>
+ thrownResultErrorHasCode(query.error, 'FORBIDDEN') ||
+ thrownResultErrorHasCode(refreshError(), 'FORBIDDEN'),
/** Re-trigger generation, keeping stale data visible meanwhile. */
refresh,
/** The underlying tanstack query, for advanced use. */
diff --git a/apps/web/src/lib/queries/ai/tests/createHomeRecommendations.test.ts b/apps/web/src/lib/queries/ai/tests/createHomeRecommendations.test.ts
index 43a3d58261..23a21e9e47 100644
--- a/apps/web/src/lib/queries/ai/tests/createHomeRecommendations.test.ts
+++ b/apps/web/src/lib/queries/ai/tests/createHomeRecommendations.test.ts
@@ -1,13 +1,19 @@
+import { FreeTierModel } from '@service-cognition/generated/schemas/freeTierModel';
import { createRoot, createSignal } from 'solid-js';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createHomeRecommendations } from '../createHomeRecommendations';
import type { HomeRecommendations } from '../homeRecommendations';
import { createAIProjection } from '../projection';
-vi.mock('@core/context/user', () => ({ useHasPermission: () => () => true }));
+const plan = vi.hoisted(() => ({ premium: true }));
+
+vi.mock('@core/context/user', () => ({
+ useHasPermission: () => () => plan.premium,
+}));
vi.mock('../projection', () => ({ createAIProjection: vi.fn() }));
afterEach(() => {
+ plan.premium = true;
vi.useRealTimers();
vi.clearAllMocks();
});
@@ -22,6 +28,7 @@ describe('Home recommendation loading', () => {
data: () => undefined,
isGenerating: () => ['cold', 'loading', 'refreshing'].includes(status()),
error: () => undefined,
+ isForbidden: () => false,
refresh: vi.fn().mockResolvedValue(undefined),
} as unknown as ReturnType<typeof createAIProjection>);
@@ -60,6 +67,7 @@ describe('Home recommendation loading', () => {
data,
isGenerating: () => true,
error: () => undefined,
+ isForbidden: () => false,
refresh,
} as unknown as ReturnType<typeof createAIProjection>);
@@ -103,3 +111,56 @@ describe('Home recommendation loading', () => {
expect(vi.getTimerCount()).toBe(0);
});
});
+
+describe('Home recommendation entitlement', () => {
+ it('requests only backend free-tier models for a free user', () => {
+ plan.premium = false;
+ vi.mocked(createAIProjection).mockReturnValue({
+ data: () => undefined,
+ isGenerating: () => true,
+ error: () => undefined,
+ isForbidden: () => false,
+ refresh: vi.fn().mockResolvedValue(undefined),
+ } as unknown as ReturnType<typeof createAIProjection>);
+
+ createRoot((dispose) => {
+ createHomeRecommendations();
+ dispose();
+ });
+
+ const requests = vi
+ .mocked(createAIProjection)
+ .mock.calls.map(([options]) => options())
+ .filter((options) => options.enabled);
+ expect(requests.map((options) => options.id)).toEqual([
+ 'home/recommended-fast',
+ ]);
+ expect(Object.values(FreeTierModel)).toContain(requests[0].model);
+ });
+
+ it('does not offer or send a retry the plan refused', async () => {
+ plan.premium = false;
+ const refresh = vi.fn().mockResolvedValue(undefined);
+ vi.mocked(createAIProjection).mockReturnValue({
+ data: () => undefined,
+ isGenerating: () => false,
+ error: () => 'Forbidden',
+ isForbidden: () => true,
+ refresh,
+ } as unknown as ReturnType<typeof createAIProjection>);
+
+ let dispose!: () => void;
+ const recommendations = createRoot((cleanup) => {
+ dispose = cleanup;
+ return createHomeRecommendations();
+ });
+ try {
+ expect(recommendations.hasError()).toBe(true);
+ expect(recommendations.canRetry()).toBe(false);
+ await recommendations.retry();
+ expect(refresh).not.toHaveBeenCalled();
+ } finally {
+ dispose();
+ }
+ });
+});
diff --git a/apps/web/src/lib/queries/ai/tests/homeRecommendations.test.ts b/apps/web/src/lib/queries/ai/tests/homeRecommendations.test.ts
index adede208f9..1006f6e1c6 100644
--- a/apps/web/src/lib/queries/ai/tests/homeRecommendations.test.ts
+++ b/apps/web/src/lib/queries/ai/tests/homeRecommendations.test.ts
@@ -192,6 +192,7 @@ describe('deriveRecommendedView', () => {
const base = {
loading: false,
failed: false,
+ retryable: true,
items: undefined,
emailLinked: true,
};
@@ -209,7 +210,12 @@ describe('deriveRecommendedView', () => {
check(
'shows an explicit error — never claims caught-up on failure',
{ ...base, failed: true },
- { kind: 'error' }
+ { kind: 'error', retryable: true }
+ );
+ check(
+ 'a plan refusal is an error that offers no retry',
+ { ...base, failed: true, retryable: false },
+ { kind: 'error', retryable: false }
);
check(
'connect CTA when no inbox is linked',
diff --git a/apps/web/src/lib/queries/ai/tests/projection.test.ts b/apps/web/src/lib/queries/ai/tests/projection.test.ts
new file mode 100644
index 0000000000..c495584685
--- /dev/null
+++ b/apps/web/src/lib/queries/ai/tests/projection.test.ts
@@ -0,0 +1,61 @@
+import { cognitionApiServiceClient } from '@service-cognition/client';
+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import { err } from 'neverthrow';
+import { createRoot } from 'solid-js';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createAIProjection } from '../projection';
+
+vi.mock('@service-cognition/client', () => ({
+ cognitionApiServiceClient: { upsertAiProjection: vi.fn() },
+}));
+vi.mock('@service-connection/websocket', () => ({
+ createConnectionWebsocketEffect: vi.fn(),
+}));
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+function mountProjection() {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ let projection!: ReturnType<typeof createAIProjection>;
+ const dispose = createRoot((cleanup) => {
+ QueryClientProvider({
+ client: queryClient,
+ get children() {
+ projection = createAIProjection(() => ({
+ id: 'test/projection',
+ prompt: 'Summarize.',
+ }));
+ return null;
+ },
+ });
+ return cleanup;
+ });
+ return { projection, dispose };
+}
+
+describe('createAIProjection isForbidden', () => {
+ it('reports a 403 that only a refresh received', async () => {
+ vi.mocked(cognitionApiServiceClient.upsertAiProjection)
+ .mockResolvedValueOnce(err([{ code: 'SERVER_ERROR', message: 'boom' }]))
+ .mockResolvedValueOnce(
+ err([{ code: 'FORBIDDEN', message: 'professional features required' }])
+ );
+
+ const { projection, dispose } = mountProjection();
+ try {
+ await vi.waitFor(() => expect(projection.error()).toBe('boom'));
+ expect(projection.isForbidden()).toBe(false);
+
+ await expect(projection.refresh()).rejects.toThrow(
+ 'professional features required'
+ );
+ expect(projection.isForbidden()).toBe(true);
+ } finally {
+ dispose();
+ }
+ });
+});
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/freeTierModel.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/freeTierModel.ts
new file mode 100644
index 0000000000..662bfcd962
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/freeTierModel.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * A `provider/model` id every user may request without professional features.
+ */
+export type FreeTierModel = (typeof FreeTierModel)[keyof typeof FreeTierModel];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const FreeTierModel = {
+ 'google/gemini-38-flash': 'google/gemini-3.8-flash',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts
index ece6e4d11c..90541935bb 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts
@@ -123,6 +123,7 @@ export * from './errorResponse';
export * from './expiry';
export * from './featureUsage';
export * from './fileType';
+export * from './freeTierModel';
export * from './genericErrorResponse';
export * from './getBatchPreviewRequest';
export * from './getBatchPreviewResponse';
diff --git a/apps/web/src/lib/service-clients/service-cognition/openapi.json b/apps/web/src/lib/service-clients/service-cognition/openapi.json
index 952c7004ed..eb6a220fba 100644
--- a/apps/web/src/lib/service-clients/service-cognition/openapi.json
+++ b/apps/web/src/lib/service-clients/service-cognition/openapi.json
@@ -3805,6 +3805,11 @@
"swf"
]
},
+ "FreeTierModel": {
+ "type": "string",
+ "description": "A `provider/model` id every user may request without professional features.",
+ "enum": ["google/gemini-3.8-flash"]
+ },
"GenericErrorResponse": {
"type": "object",
"required": ["error", "message"],
diff --git a/crates/ai_projections/src/domain/ai_projection_service.rs b/crates/ai_projections/src/domain/ai_projection_service.rs
index 579671ab7f..f3111cda18 100644
--- a/crates/ai_projections/src/domain/ai_projection_service.rs
+++ b/crates/ai_projections/src/domain/ai_projection_service.rs
@@ -24,6 +24,10 @@ pub const READ_PROFESSIONAL_FEATURES: &str = "read:professional_features";
/// `provider/model` ids that any user may request, without professional
/// features. Everything else — including an absent model, which resolves to
/// the server default (the smart tier) — requires the permission.
+///
+/// Must equal the chat free tier (`chat::domain::models::FREE_MODEL`), which
+/// the web client generates from the published `FreeTierModel` schema;
+/// `document_cognition_service` tests the two together.
pub const FREE_TIER_MODELS: &[&str] = &["google/gemini-3.8-flash"];
/// Whether a requested projection model requires the
diff --git a/crates/chat/AGENTS.md b/crates/chat/AGENTS.md
index 52091fab01..e8e83d8ea7 100644
--- a/crates/chat/AGENTS.md
+++ b/crates/chat/AGENTS.md
@@ -47,6 +47,11 @@ adapters, and lifecycle events. See `README.md` for the Kafka event schema.
`null`, and `project_id: ""` means "removed from its project" (see `README.md`).
- Sharing a chat with a team is gated through `SharePermission.team_share_*` and
only the persisted owner may set `teamShareAccessLevel`.
+- `FREE_MODEL` is published as the `FreeTierModel` OpenAPI schema; the web
+ client's free tier is generated from it. After changing it, run
+ `bun run gen-api document-cognition` in `apps/web`, update the web model
+ catalog if the id is new, and keep `ai_projections::FREE_TIER_MODELS` equal
+ (`document_cognition_service` tests both).
## Related
diff --git a/crates/chat/src/domain/models/mod.rs b/crates/chat/src/domain/models/mod.rs
index e179aec9ae..392a3b4625 100644
--- a/crates/chat/src/domain/models/mod.rs
+++ b/crates/chat/src/domain/models/mod.rs
@@ -10,4 +10,4 @@ pub use chat::{
};
pub use error::{ChatErr, Result};
pub use message::{PatchChatMessageArgs, ResolvedMessageContent, WebCitation};
-pub use model_access::{CHAT_MODELS, FREE_MODEL, PAID_DEFAULT_MODEL};
+pub use model_access::{CHAT_MODELS, FREE_MODEL, FreeTierModel, PAID_DEFAULT_MODEL};
diff --git a/crates/chat/src/domain/models/model_access.rs b/crates/chat/src/domain/models/model_access.rs
index bcffc425bc..db196ed4d1 100644
--- a/crates/chat/src/domain/models/model_access.rs
+++ b/crates/chat/src/domain/models/model_access.rs
@@ -25,3 +25,26 @@ pub const PAID_DEFAULT_MODEL: &str = "anthropic/claude-sonnet-5-5";
/// The only model available to free (non-professional) users.
pub const FREE_MODEL: &str = "google/gemini-3.8-flash";
+
+/// OpenAPI schema publishing [`FREE_MODEL`] as a string enum, so the web
+/// client generates its free-tier model list from this crate instead of
+/// copying the id.
+pub struct FreeTierModel;
+
+impl utoipa::ToSchema for FreeTierModel {
+ fn name() -> std::borrow::Cow<'static, str> {
+ std::borrow::Cow::Borrowed("FreeTierModel")
+ }
+}
+
+impl utoipa::PartialSchema for FreeTierModel {
+ fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
+ utoipa::openapi::schema::ObjectBuilder::new()
+ .schema_type(utoipa::openapi::schema::Type::String)
+ .enum_values(Some([FREE_MODEL]))
+ .description(Some(
+ "A `provider/model` id every user may request without professional features.",
+ ))
+ .into()
+ }
+}
diff --git a/docs/agent-guide/home.md b/docs/agent-guide/home.md
index 80bbd00f57..16d71a1b2e 100644
--- a/docs/agent-guide/home.md
+++ b/docs/agent-guide/home.md
@@ -136,7 +136,9 @@ for tasks, skills, snippets, and other documents. Suggestion loading/errors
are isolated from the input. If generation stalls for 45 seconds, the shimmer
is replaced with a retry action; a late result still appears automatically.
Generation status updates do not extend that deadline. Retry starts a fresh
-45-second wait. Shift+Enter adds a line. Selecting a Home row replaces
+45-second wait. Free users get suggestions from the free-tier model; if the
+plan refuses the request (403), the row says suggestions are unavailable and
+offers no retry. Shift+Enter adds a line. Selecting a Home row replaces
the composer with its preview. Home uses the shared 256px sidebar and collapses
navigation below 720px. The hamburger or `Cmd+.` opens the full feed as a
slide-over. Activating a row or **New chat** closes that overlay to show content;
diff --git a/packages/sdk-docs/reference/generated/cognition/types.gen/README.md b/packages/sdk-docs/reference/generated/cognition/types.gen/README.md
index 51e49fa198..58efc86462 100644
--- a/packages/sdk-docs/reference/generated/cognition/types.gen/README.md
+++ b/packages/sdk-docs/reference/generated/cognition/types.gen/README.md
@@ -112,6 +112,7 @@
- [Expiry](type-aliases/Expiry.md)
- [FeatureUsage](type-aliases/FeatureUsage.md)
- [FileType](type-aliases/FileType.md)
+- [FreeTierModel](type-aliases/FreeTierModel.md)
- [GenericErrorResponse](type-aliases/GenericErrorResponse.md)
- [GetBatchPreviewData](type-aliases/GetBatchPreviewData.md)
- [GetBatchPreviewError](type-aliases/GetBatchPreviewError.md)
diff --git a/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/FreeTierModel.md b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/FreeTierModel.md
new file mode 100644
index 0000000000..f45903d132
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/FreeTierModel.md
@@ -0,0 +1,5 @@
+# Type Alias: FreeTierModel
+
+> **FreeTierModel** = `"google/gemini-3.8-flash"`
+
+A `provider/model` id every user may request without professional features.
diff --git a/packages/sdk/generated/cognition/index.ts b/packages/sdk/generated/cognition/index.ts
index b920fdc3cf..160421c271 100644
--- a/packages/sdk/generated/cognition/index.ts
+++ b/packages/sdk/generated/cognition/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AccessLevel, AddMcpServerData, AddMcpServerError, AddMcpServerErrors, AddMcpServerResponse, AddMcpServerResponses, AddServerRequest, AiAdmissionErrorBody, AiFeature, AssistantMessagePart, AttachmentMetadata, AttachmentType, BrowsePipedreamMcpCatalogData, BrowsePipedreamMcpCatalogError, BrowsePipedreamMcpCatalogErrors, BrowsePipedreamMcpCatalogResponse, BrowsePipedreamMcpCatalogResponses, CallToolData, CallToolError, CallToolErrors, CallToolRequest, CallToolResponse, CallToolResponse2, CallToolResponses, ChannelSharePermission, ChannelType, Chat, ChatAttachment, ChatHistory, ChatHistoryBatchMessagesRequest, ChatMessage, ChatMessageContent, ChatMessageError, ChatMessageWithAttachments, ChatPreview, ChatPreviewData, ChatResponse, ChatStream, ClientOptions, CompleteHandlerData, CompleteHandlerErrors, CompleteHandlerResponse, CompleteHandlerResponses, CompleteOnboardingRequest, CompletePipedreamMcpConnectionData, CompletePipedreamMcpConnectionError, CompletePipedreamMcpConnectionErrors, CompletePipedreamMcpConnectionResponse, CompletePipedreamMcpConnectionResponses, CompletionUsage, ConnectedServer, ConversationRecord, CopyChatData, CopyChatError, CopyChatErrors, CopyChatResponse, CopyChatResponses, CreateChatData, CreateChatError, CreateChatErrors, CreateChatRequest, CreateChatResponse, CreateChatResponses, CreatePipedreamMcpTokenData, CreatePipedreamMcpTokenError, CreatePipedreamMcpTokenErrors, CreatePipedreamMcpTokenResponse, CreatePipedreamMcpTokenResponses, DatabaseChange, DecisionErrorBody, DecisionRequest, DecisionResponse, DecisionsData, DecisionsError, DecisionsErrors, DecisionsResponse, DecisionsResponses, DeleteChatData, DeleteChatError, DeleteChatErrors, DeleteChatResponses, DeleteMcpServerData, DeleteMcpServerError, DeleteMcpServerErrors, DeleteMcpServerResponse, DeleteMcpServerResponses, DeletePipedreamMcpConnectionData, DeletePipedreamMcpConnectionError, DeletePipedreamMcpConnectionErrors, DeletePipedreamMcpConnectionResponse, DeletePipedreamMcpConnectionResponses, DiscoverHandlerData, DiscoverHandlerErrors, DiscoverHandlerResponse, DiscoverHandlerResponses, DismissRunHandlerData, DismissRunHandlerErrors, DismissRunHandlerResponse, DismissRunHandlerResponses, DocumentCognitionServiceApiVersion, DocumentReference, DocumentTextPart, DynamicSchema, Entity, EntityType, ErrorBody, ErrorResponse, Expiry, FeatureUsage, FileType, GenericErrorResponse, GetBatchPreviewData, GetBatchPreviewError, GetBatchPreviewErrors, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchPreviewResponse2, GetBatchPreviewResponses, GetChatData, GetChatError, GetChatErrors, GetChatHistoryBatchMessagesHandlerData, GetChatHistoryBatchMessagesHandlerError, GetChatHistoryBatchMessagesHandlerErrors, GetChatHistoryBatchMessagesHandlerResponse, GetChatHistoryBatchMessagesHandlerResponses, GetChatHistoryHandlerData, GetChatHistoryHandlerError, GetChatHistoryHandlerErrors, GetChatHistoryHandlerResponse, GetChatHistoryHandlerResponses, GetChatPermissionsData, GetChatPermissionsError, GetChatPermissionsErrors, GetChatPermissionsResponse, GetChatPermissionsResponse2, GetChatPermissionsResponses, GetChatResponse, GetChatResponse2, GetChatResponses, GetChatsForAttachmentHandlerData, GetChatsForAttachmentHandlerError, GetChatsForAttachmentHandlerErrors, GetChatsForAttachmentHandlerResponse, GetChatsForAttachmentHandlerResponses, GetChatsForAttachmentResponse, GetCitationHandlerData, GetCitationHandlerError, GetCitationHandlerErrors, GetCitationHandlerResponse, GetCitationHandlerResponses, GetMemoryHandlerData, GetMemoryHandlerError, GetMemoryHandlerErrors, GetMemoryHandlerResponse, GetMemoryHandlerResponses, GetStateHandler2Data, GetStateHandler2Errors, GetStateHandler2Response, GetStateHandler2Responses, GetStateHandlerData, GetStateHandlerErrors, GetStateHandlerResponse, GetStateHandlerResponses, GetUsageHandlerData, GetUsageHandlerError, GetUsageHandlerErrors, GetUsageHandlerResponse, GetUsageHandlerResponses, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HttpSendChatMessageRequest, ImportEntity, ImportRun, ImportSource, ImportState, ImportStatus, Initiator, JwtPayload, LinearIssueMeta, LinkShare, ListMcpServersData, ListMcpServersError, ListMcpServersErrors, ListMcpServersResponse, ListMcpServersResponses, ListPipedreamMcpConnectionsData, ListPipedreamMcpConnectionsError, ListPipedreamMcpConnectionsErrors, ListPipedreamMcpConnectionsResponse, ListPipedreamMcpConnectionsResponses, MacroUserIdStr, McpAuthCallbackData, McpAuthCallbackError, McpAuthCallbackErrors, McpAuthCallbackResponses, McpOauthClientMetadataData, McpOauthClientMetadataResponses, MemoryErrorBody, MemoryResponse, MessageWithAttachments, ModelSpeed, NewAttachment, NewChatMessage, NewMessageAttachment, NotionDocMeta, OnboardingRow, OnboardingState, OnboardingStatus, PatchChatData, PatchChatError, PatchChatErrors, PatchChatRequest, PatchChatResponses, PermanentlyDeleteChatData, PermanentlyDeleteChatError, PermanentlyDeleteChatErrors, PermanentlyDeleteChatResponses, PipedreamCatalogEntryResponse, PipedreamCatalogResponse, PipedreamCompleteRequest, PipedreamConnectionResponse, PipedreamTokenResponse, PipedreamUpdateRequest, Price, ProjectionStateResponse, ProjectionStatus, RefreshCadence, RejectToolCallData, RejectToolCallError, RejectToolCallErrors, RejectToolCallRequest, RejectToolCallResponses, RetryGatherHandlerData, RetryGatherHandlerError, RetryGatherHandlerErrors, RetryGatherHandlerResponse, RetryGatherHandlerResponses, RevertDeleteChatData, RevertDeleteChatError, RevertDeleteChatErrors, RevertDeleteChatResponses, Role, RunImportHandlerData, RunImportHandlerErrors, RunImportHandlerResponse, RunImportHandlerResponses, RunImportOutcome, RunImportRequest, RunStatus, SendChatMessageData, SendChatMessageError, SendChatMessageErrors, SendChatMessagePayload, SendChatMessageResponse, SendChatMessageResponse2, SendChatMessageResponses, ServerResponse, SetPricingHandlerData, SetPricingHandlerError, SetPricingHandlerErrors, SetPricingHandlerResponses, SetPricingRequest, SharePermissionV2, SlackChannelMeta, SlackParticipant, StartAuthRequest, StartAuthResponse, StartMcpAuthData, StartMcpAuthError, StartMcpAuthErrors, StartMcpAuthResponse, StartMcpAuthResponses, StopChatStreamData, StopChatStreamError, StopChatStreamError2, StopChatStreamErrors, StopChatStreamRequest, StopChatStreamResponse, StopChatStreamResponse2, StopChatStreamResponses, StreamError, StringIdResponse, StructuredCompletionData, StructuredCompletionError, StructuredCompletionError2, StructuredCompletionErrors, StructuredCompletionOutcome, StructuredCompletionRequest, StructuredCompletionResponse, StructuredCompletionResponse2, StructuredCompletionResponses, StructuredToolActivity, TargetType, ToolOutcome, ToolSet, UpdateChannelSharePermission, UpdateMcpServerData, UpdateMcpServerError, UpdateMcpServerErrors, UpdateMcpServerResponse, UpdateMcpServerResponses, UpdateOperation, UpdatePipedreamMcpConnectionData, UpdatePipedreamMcpConnectionError, UpdatePipedreamMcpConnectionErrors, UpdatePipedreamMcpConnectionResponse, UpdatePipedreamMcpConnectionResponses, UpdateServerRequest, UpdateSharePermissionRequestV2, UpdateToolCallData, UpdateToolCallError, UpdateToolCallErrors, UpdateToolCallRequest, UpdateToolCallResponses, UpdateToolResponseData, UpdateToolResponseError, UpdateToolResponseErrors, UpdateToolResponseRequest, UpdateToolResponseResponses, UpsertAiProjectionData, UpsertAiProjectionError, UpsertAiProjectionErrors, UpsertAiProjectionResponse, UpsertAiProjectionResponses, UpsertProjectionRequest, Usage, UsageRequest, UsageSummary, UserPdfRect, UserToolResponseValue, WebCitation, WithChatId } from './types.gen';
+export type { AccessLevel, AddMcpServerData, AddMcpServerError, AddMcpServerErrors, AddMcpServerResponse, AddMcpServerResponses, AddServerRequest, AiAdmissionErrorBody, AiFeature, AssistantMessagePart, AttachmentMetadata, AttachmentType, BrowsePipedreamMcpCatalogData, BrowsePipedreamMcpCatalogError, BrowsePipedreamMcpCatalogErrors, BrowsePipedreamMcpCatalogResponse, BrowsePipedreamMcpCatalogResponses, CallToolData, CallToolError, CallToolErrors, CallToolRequest, CallToolResponse, CallToolResponse2, CallToolResponses, ChannelSharePermission, ChannelType, Chat, ChatAttachment, ChatHistory, ChatHistoryBatchMessagesRequest, ChatMessage, ChatMessageContent, ChatMessageError, ChatMessageWithAttachments, ChatPreview, ChatPreviewData, ChatResponse, ChatStream, ClientOptions, CompleteHandlerData, CompleteHandlerErrors, CompleteHandlerResponse, CompleteHandlerResponses, CompleteOnboardingRequest, CompletePipedreamMcpConnectionData, CompletePipedreamMcpConnectionError, CompletePipedreamMcpConnectionErrors, CompletePipedreamMcpConnectionResponse, CompletePipedreamMcpConnectionResponses, CompletionUsage, ConnectedServer, ConversationRecord, CopyChatData, CopyChatError, CopyChatErrors, CopyChatResponse, CopyChatResponses, CreateChatData, CreateChatError, CreateChatErrors, CreateChatRequest, CreateChatResponse, CreateChatResponses, CreatePipedreamMcpTokenData, CreatePipedreamMcpTokenError, CreatePipedreamMcpTokenErrors, CreatePipedreamMcpTokenResponse, CreatePipedreamMcpTokenResponses, DatabaseChange, DecisionErrorBody, DecisionRequest, DecisionResponse, DecisionsData, DecisionsError, DecisionsErrors, DecisionsResponse, DecisionsResponses, DeleteChatData, DeleteChatError, DeleteChatErrors, DeleteChatResponses, DeleteMcpServerData, DeleteMcpServerError, DeleteMcpServerErrors, DeleteMcpServerResponse, DeleteMcpServerResponses, DeletePipedreamMcpConnectionData, DeletePipedreamMcpConnectionError, DeletePipedreamMcpConnectionErrors, DeletePipedreamMcpConnectionResponse, DeletePipedreamMcpConnectionResponses, DiscoverHandlerData, DiscoverHandlerErrors, DiscoverHandlerResponse, DiscoverHandlerResponses, DismissRunHandlerData, DismissRunHandlerErrors, DismissRunHandlerResponse, DismissRunHandlerResponses, DocumentCognitionServiceApiVersion, DocumentReference, DocumentTextPart, DynamicSchema, Entity, EntityType, ErrorBody, ErrorResponse, Expiry, FeatureUsage, FileType, FreeTierModel, GenericErrorResponse, GetBatchPreviewData, GetBatchPreviewError, GetBatchPreviewErrors, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchPreviewResponse2, GetBatchPreviewResponses, GetChatData, GetChatError, GetChatErrors, GetChatHistoryBatchMessagesHandlerData, GetChatHistoryBatchMessagesHandlerError, GetChatHistoryBatchMessagesHandlerErrors, GetChatHistoryBatchMessagesHandlerResponse, GetChatHistoryBatchMessagesHandlerResponses, GetChatHistoryHandlerData, GetChatHistoryHandlerError, GetChatHistoryHandlerErrors, GetChatHistoryHandlerResponse, GetChatHistoryHandlerResponses, GetChatPermissionsData, GetChatPermissionsError, GetChatPermissionsErrors, GetChatPermissionsResponse, GetChatPermissionsResponse2, GetChatPermissionsResponses, GetChatResponse, GetChatResponse2, GetChatResponses, GetChatsForAttachmentHandlerData, GetChatsForAttachmentHandlerError, GetChatsForAttachmentHandlerErrors, GetChatsForAttachmentHandlerResponse, GetChatsForAttachmentHandlerResponses, GetChatsForAttachmentResponse, GetCitationHandlerData, GetCitationHandlerError, GetCitationHandlerErrors, GetCitationHandlerResponse, GetCitationHandlerResponses, GetMemoryHandlerData, GetMemoryHandlerError, GetMemoryHandlerErrors, GetMemoryHandlerResponse, GetMemoryHandlerResponses, GetStateHandler2Data, GetStateHandler2Errors, GetStateHandler2Response, GetStateHandler2Responses, GetStateHandlerData, GetStateHandlerErrors, GetStateHandlerResponse, GetStateHandlerResponses, GetUsageHandlerData, GetUsageHandlerError, GetUsageHandlerErrors, GetUsageHandlerResponse, GetUsageHandlerResponses, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HttpSendChatMessageRequest, ImportEntity, ImportRun, ImportSource, ImportState, ImportStatus, Initiator, JwtPayload, LinearIssueMeta, LinkShare, ListMcpServersData, ListMcpServersError, ListMcpServersErrors, ListMcpServersResponse, ListMcpServersResponses, ListPipedreamMcpConnectionsData, ListPipedreamMcpConnectionsError, ListPipedreamMcpConnectionsErrors, ListPipedreamMcpConnectionsResponse, ListPipedreamMcpConnectionsResponses, MacroUserIdStr, McpAuthCallbackData, McpAuthCallbackError, McpAuthCallbackErrors, McpAuthCallbackResponses, McpOauthClientMetadataData, McpOauthClientMetadataResponses, MemoryErrorBody, MemoryResponse, MessageWithAttachments, ModelSpeed, NewAttachment, NewChatMessage, NewMessageAttachment, NotionDocMeta, OnboardingRow, OnboardingState, OnboardingStatus, PatchChatData, PatchChatError, PatchChatErrors, PatchChatRequest, PatchChatResponses, PermanentlyDeleteChatData, PermanentlyDeleteChatError, PermanentlyDeleteChatErrors, PermanentlyDeleteChatResponses, PipedreamCatalogEntryResponse, PipedreamCatalogResponse, PipedreamCompleteRequest, PipedreamConnectionResponse, PipedreamTokenResponse, PipedreamUpdateRequest, Price, ProjectionStateResponse, ProjectionStatus, RefreshCadence, RejectToolCallData, RejectToolCallError, RejectToolCallErrors, RejectToolCallRequest, RejectToolCallResponses, RetryGatherHandlerData, RetryGatherHandlerError, RetryGatherHandlerErrors, RetryGatherHandlerResponse, RetryGatherHandlerResponses, RevertDeleteChatData, RevertDeleteChatError, RevertDeleteChatErrors, RevertDeleteChatResponses, Role, RunImportHandlerData, RunImportHandlerErrors, RunImportHandlerResponse, RunImportHandlerResponses, RunImportOutcome, RunImportRequest, RunStatus, SendChatMessageData, SendChatMessageError, SendChatMessageErrors, SendChatMessagePayload, SendChatMessageResponse, SendChatMessageResponse2, SendChatMessageResponses, ServerResponse, SetPricingHandlerData, SetPricingHandlerError, SetPricingHandlerErrors, SetPricingHandlerResponses, SetPricingRequest, SharePermissionV2, SlackChannelMeta, SlackParticipant, StartAuthRequest, StartAuthResponse, StartMcpAuthData, StartMcpAuthError, StartMcpAuthErrors, StartMcpAuthResponse, StartMcpAuthResponses, StopChatStreamData, StopChatStreamError, StopChatStreamError2, StopChatStreamErrors, StopChatStreamRequest, StopChatStreamResponse, StopChatStreamResponse2, StopChatStreamResponses, StreamError, StringIdResponse, StructuredCompletionData, StructuredCompletionError, StructuredCompletionError2, StructuredCompletionErrors, StructuredCompletionOutcome, StructuredCompletionRequest, StructuredCompletionResponse, StructuredCompletionResponse2, StructuredCompletionResponses, StructuredToolActivity, TargetType, ToolOutcome, ToolSet, UpdateChannelSharePermission, UpdateMcpServerData, UpdateMcpServerError, UpdateMcpServerErrors, UpdateMcpServerResponse, UpdateMcpServerResponses, UpdateOperation, UpdatePipedreamMcpConnectionData, UpdatePipedreamMcpConnectionError, UpdatePipedreamMcpConnectionErrors, UpdatePipedreamMcpConnectionResponse, UpdatePipedreamMcpConnectionResponses, UpdateServerRequest, UpdateSharePermissionRequestV2, UpdateToolCallData, UpdateToolCallError, UpdateToolCallErrors, UpdateToolCallRequest, UpdateToolCallResponses, UpdateToolResponseData, UpdateToolResponseError, UpdateToolResponseErrors, UpdateToolResponseRequest, UpdateToolResponseResponses, UpsertAiProjectionData, UpsertAiProjectionError, UpsertAiProjectionErrors, UpsertAiProjectionResponse, UpsertAiProjectionResponses, UpsertProjectionRequest, Usage, UsageRequest, UsageSummary, UserPdfRect, UserToolResponseValue, WebCitation, WithChatId } from './types.gen';
diff --git a/packages/sdk/generated/cognition/types.gen.ts b/packages/sdk/generated/cognition/types.gen.ts
index 6523938429..bc8d287059 100644
--- a/packages/sdk/generated/cognition/types.gen.ts
+++ b/packages/sdk/generated/cognition/types.gen.ts
@@ -645,6 +645,11 @@ export type FeatureUsage = {
*/
export type FileType = 'docx' | 'pdf' | 'md' | 'spreadsheet' | 'canvas' | 'coffee' | 'cson' | 'iced' | 'c' | 'i' | 'cpp' | 'cppm' | 'cc' | 'ccm' | 'cxx' | 'cxxm' | 'cplusplus' | 'cplusplusm' | 'hpp' | 'hh' | 'hxx' | 'hplusplus' | 'h' | 'ii' | 'ino' | 'inl' | 'ipp' | 'ixx' | 'tpp' | 'txx' | 'hppin' | 'hin' | 'cu' | 'cuh' | 'cs' | 'csx' | 'cake' | 'css' | 'dart' | 'diff' | 'patch' | 'rej' | 'dockerfile' | 'containerfile' | 'go' | 'handlebars' | 'hbs' | 'hjs' | 'hlsl' | 'hlsli' | 'fx' | 'fxh' | 'vsh' | 'psh' | 'cginc' | 'compute' | 'html' | 'htm' | 'shtml' | 'xhtml' | 'xht' | 'mdoc' | 'jsp' | 'asp' | 'aspx' | 'jshtm' | 'volt' | 'ejs' | 'rhtml' | 'ini' | 'conf' | 'properties' | 'cfg' | 'directory' | 'gitattributes' | 'gitconfig' | 'gitmodules' | 'editorconfig' | 'repo' | 'java' | 'jav' | 'jsx' | 'js' | 'es6' | 'mjs' | 'cjs' | 'pac' | 'json' | 'bowerrc' | 'jscsrc' | 'webmanifest' | 'jsmap' | 'cssmap' | 'tsmap' | 'har' | 'jslintrc' | 'jsonld' | 'geojson' | 'ipynb' | 'vuerc' | 'jsonc' | 'eslintrc' | 'eslintrcjson' | 'jsfmtrc' | 'jshintrc' | 'swcrc' | 'hintrc' | 'babelrc' | 'jsonl' | 'ndjson' | 'codesnippets' | 'jl' | 'jmd' | 'sty' | 'cls' | 'bbx' | 'cbx' | 'tex' | 'ltx' | 'ctx' | 'bib' | 'less' | 'log' | 'lua' | 'mak' | 'mk' | 'mkd' | 'mdwn' | 'mdown' | 'markdown' | 'markdn' | 'mdtxt' | 'mdtext' | 'workbook' | 'm' | 'mm' | 'pl' | 'pm' | 'pod' | 't' | 'psgi' | 'raku' | 'rakumod' | 'rakutest' | 'rakudoc' | 'nqp' | 'p6' | 'pl6' | 'pm6' | 'php' | 'php4' | 'php5' | 'phtml' | 'ctp' | 'ps1' | 'psm1' | 'psd1' | 'pssc' | 'psrc' | 'py' | 'rpy' | 'pyw' | 'cpy' | 'gyp' | 'gypi' | 'pyi' | 'ipy' | 'pyt' | 'r' | 'rhistory' | 'rprofile' | 'rt' | 'cshtml' | 'razor' | 'rb' | 'rbx' | 'rjs' | 'gemspec' | 'rake' | 'ru' | 'erb' | 'podspec' | 'rbi' | 'rs' | 'scss' | 'sass' | 'shader' | 'sh' | 'bash' | 'bashrc' | 'bashaliases' | 'bashprofile' | 'bashlogin' | 'ebuild' | 'eclass' | 'profile' | 'bashlogout' | 'xprofile' | 'xsession' | 'xsessionrc' | 'zsh' | 'zshrc' | 'zprofile' | 'zlogin' | 'zlogout' | 'zshenv' | 'zshtheme' | 'fish' | 'ksh' | 'csh' | 'cshrc' | 'tcshrc' | 'yashrc' | 'yashprofile' | 'sql' | 'dsql' | 'swift' | 'ts' | 'cts' | 'mts' | 'tsx' | 'tsbuildinfo' | 'xml' | 'xsd' | 'ascx' | 'atom' | 'axml' | 'axaml' | 'bpmn' | 'cpt' | 'csl' | 'csproj' | 'csprojuser' | 'dita' | 'ditamap' | 'dtd' | 'ent' | 'mod' | 'dtml' | 'fsproj' | 'fxml' | 'iml' | 'isml' | 'jmx' | 'launch' | 'menu' | 'mxml' | 'nuspec' | 'opml' | 'owl' | 'proj' | 'props' | 'pt' | 'publishsettings' | 'pubxml' | 'pubxmluser' | 'rbxlx' | 'rbxmx' | 'rdf' | 'rng' | 'rss' | 'shproj' | 'storyboard' | 'targets' | 'tld' | 'tmx' | 'vbproj' | 'vbprojuser' | 'vcxproj' | 'vcxprojfilters' | 'wsdl' | 'wxi' | 'wxl' | 'wxs' | 'xaml' | 'xbl' | 'xib' | 'xlf' | 'xliff' | 'xpdl' | 'xul' | 'xoml' | 'xsl' | 'xslt' | 'yaml' | 'yml' | 'eyaml' | 'eyml' | 'cff' | 'yamltmlanguage' | 'yamltmpreferences' | 'yamltmtheme' | 'winget' | 'txt' | 'csv' | 'tsv' | 'jpeg' | 'jpg' | 'png' | 'gif' | 'svg' | 'webp' | 'avif' | 'bmp' | 'ico' | 'tiff' | 'tif' | 'heic' | 'heif' | 'tar' | 'targz' | 'tgz' | 'gz' | 'bz2' | 'tarbz2' | 'tbz2' | 'z' | 'tarz' | 'lz' | 'tarlz' | 'xz' | 'tarxz' | 'txz' | 'lzma' | 'tarlzma' | 'rar' | 'sevenz' | 'zst' | 'tarzst' | 'tzst' | 'zip' | 'exe' | 'msi' | 'dll' | 'bat' | 'cmd' | 'com' | 'appimage' | 'app' | 'bin' | 'deb' | 'rpm' | 'apk' | 'dmg' | 'pkg' | 'crx' | 'xpi' | 'mp3' | 'wav' | 'ogg' | 'flac' | 'aac' | 'm4a' | 'wma' | 'mid' | 'midi' | 'mp4' | 'mkv' | 'webm' | 'avi' | 'mov' | 'wmv' | 'mpg' | 'mpeg' | 'm4v' | 'flv' | 'f4v' | 'threegp' | 'ttf' | 'otf' | 'woff' | 'woff2' | 'eot' | 'rtf' | 'odt' | 'ods' | 'odp' | 'odg' | 'odf' | 'epub' | 'mobi' | 'azw' | 'azw3' | 'djvu' | 'xls' | 'xlsm' | 'ppt' | 'doc' | 'pptx' | 'xlsx' | 'db' | 'sqlite' | 'sqlite3' | 'mdb' | 'accdb' | 'dbf' | 'plist' | 'toml' | 'env' | 'dot' | 'gv' | 'torrent' | 'ics' | 'vcf' | 'ai' | 'eps' | 'ps' | 'dxf' | 'dwg' | 'fig' | 'psd' | 'psb' | 'stl' | 'obj' | 'fbx' | 'blend' | 'dae' | 'threeds' | 'gltf' | 'glb' | 'vhd' | 'vhdx' | 'vmdk' | 'ova' | 'ovf' | 'iso' | 'img' | 'swf';
+/**
+ * A `provider/model` id every user may request without professional features.
+ */
+export type FreeTierModel = 'google/gemini-3.8-flash';
+
export type GenericErrorResponse = {
/**
* Indicates if an error occurred
diff --git a/packages/sdk/specs/cognition.json b/packages/sdk/specs/cognition.json
index 952c7004ed..eb6a220fba 100644
--- a/packages/sdk/specs/cognition.json
+++ b/packages/sdk/specs/cognition.json
@@ -3805,6 +3805,11 @@
"swf"
]
},
+ "FreeTierModel": {
+ "type": "string",
+ "description": "A `provider/model` id every user may request without professional features.",
+ "enum": ["google/gemini-3.8-flash"]
+ },
"GenericErrorResponse": {
"type": "object",
"required": ["error", "message"],
diff --git a/rules/ast-grep/ts-no-hardcoded-model-id.yml b/rules/ast-grep/ts-no-hardcoded-model-id.yml
new file mode 100644
index 0000000000..633fe875de
--- /dev/null
+++ b/rules/ast-grep/ts-no-hardcoded-model-id.yml
@@ -0,0 +1,29 @@
+id: ts-no-hardcoded-model-id
+language: typescript
+# Twin of tsx-no-hardcoded-model-id — ast-grep rules are single-language, and
+# `tsx` only scans .tsx files.
+severity: error
+message: Don't hardcode a `provider/model` id. Pick the model from `@core/component/AI/constant` by plan (`FREE_DEFAULT_MODEL`, `defaultModelForPlan`, `modelsForPlan`).
+note: |-
+ Rule FE-57 in .agents/rules/web/data.md. The backend rejects any model outside
+ the user's plan with a 403, and its free tier changes independently of the
+ frontend: Home suggestions hardcoded Claude Haiku, then the free tier became
+ Gemini Flash only, and every free user's request failed. `FREE_MODELS` is
+ generated from the backend's `FreeTierModel` schema, so selecting through the
+ plan helpers keeps requests inside the user's tier. A new model id goes in the
+ catalog in `apps/web/src/lib/core/component/AI/constant/model.ts`.
+files:
+ - apps/web/src/**
+ignores:
+ - apps/web/src/lib/core/component/AI/constant/model.ts
+ # Developer tools that deliberately exercise arbitrary models.
+ - '**/debug/**'
+ - '**/generated/**'
+ - '**/*.test.ts'
+ - '**/*.test.tsx'
+ - '**/test/**'
+ - '**/tests/**'
+ - '**/browser-test/**'
+rule:
+ kind: string_fragment
+ regex: ^(anthropic|openai|google|cerebras|fireworks)/[A-Za-z0-9][\w.:-]*$
diff --git a/rules/ast-grep/tsx-no-hardcoded-model-id.yml b/rules/ast-grep/tsx-no-hardcoded-model-id.yml
new file mode 100644
index 0000000000..eb2c83bded
--- /dev/null
+++ b/rules/ast-grep/tsx-no-hardcoded-model-id.yml
@@ -0,0 +1,21 @@
+id: tsx-no-hardcoded-model-id
+language: tsx
+# Twin of ts-no-hardcoded-model-id — ast-grep rules are single-language.
+severity: error
+message: Don't hardcode a `provider/model` id. Pick the model from `@core/component/AI/constant` by plan (`FREE_DEFAULT_MODEL`, `defaultModelForPlan`, `modelsForPlan`).
+note: |-
+ Rule FE-57 in .agents/rules/web/data.md. See ts-no-hardcoded-model-id for the
+ rationale: the backend 403s models outside the user's plan, and `FREE_MODELS`
+ is generated from its `FreeTierModel` schema.
+files:
+ - apps/web/src/**
+ignores:
+ # Developer tools that deliberately exercise arbitrary models.
+ - '**/debug/**'
+ - '**/*.test.tsx'
+ - '**/test/**'
+ - '**/tests/**'
+ - '**/browser-test/**'
+rule:
+ kind: string_fragment
+ regex: ^(anthropic|openai|google|cerebras|fireworks)/[A-Za-z0-9][\w.:-]*$
diff --git a/services/document_cognition_service/src/api/swagger.rs b/services/document_cognition_service/src/api/swagger.rs
index 11bb43aa9c..2c710ac1d6 100644
--- a/services/document_cognition_service/src/api/swagger.rs
+++ b/services/document_cognition_service/src/api/swagger.rs
@@ -37,7 +37,7 @@ use pipedream_mcp::inbound::axum_router::{
use crate::api::preview::get_batch_preview::{GetBatchPreviewRequest, GetBatchPreviewResponse};
-use chat::domain::models::{ChatResponse, GetChatResponse, WebCitation};
+use chat::domain::models::{ChatResponse, FreeTierModel, GetChatResponse, WebCitation};
use chat::inbound::http::router::{
self as chat_router, CallToolRequest, CallToolResponse, CreateChatRequest,
GetChatPermissionsResponse, PatchChatRequest, RejectToolCallRequest, UpdateToolCallRequest,
@@ -186,6 +186,7 @@ use utoipa::OpenApi;
StopChatStreamError,
StreamError,
ToolSet,
+ FreeTierModel,
StructuredCompletionRequest,
StructuredCompletionResponse,
StructuredCompletionError,
@@ -261,3 +262,6 @@ use utoipa::OpenApi;
)
)]
pub struct ApiDoc;
+
+#[cfg(test)]
+mod test;
diff --git a/services/document_cognition_service/src/api/swagger/test.rs b/services/document_cognition_service/src/api/swagger/test.rs
new file mode 100644
index 0000000000..50614df0a7
--- /dev/null
+++ b/services/document_cognition_service/src/api/swagger/test.rs
@@ -0,0 +1,22 @@
+use ai_projections::domain::ai_projection_service::{
+ FREE_TIER_MODELS, requires_professional_features,
+};
+use chat::domain::models::FREE_MODEL;
+use utoipa::OpenApi;
+
+#[test]
+fn openapi_publishes_the_chat_free_tier_model() {
+ let doc = serde_json::to_value(super::ApiDoc::openapi()).unwrap();
+ assert_eq!(
+ doc["components"]["schemas"]["FreeTierModel"]["enum"],
+ serde_json::json!([FREE_MODEL])
+ );
+}
+
+// The web client sends the published free-tier model to both chat and AI
+// projections, so projections must allow exactly that model for free users.
+#[test]
+fn projection_free_tier_matches_the_published_free_tier() {
+ assert_eq!(FREE_TIER_MODELS, [FREE_MODEL]);
+ assert!(!requires_professional_features(Some(FREE_MODEL)));
+}