Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

fix: remove chat models calls if not authenticated

Carl-Gerhard Lindesvärd09ae73884505
diff --git a/apps/start/src/components/chat/chat-context.tsx b/apps/start/src/components/chat/chat-context.tsx
index 0746ebf0e..14eeb7602 100644
--- a/apps/start/src/components/chat/chat-context.tsx
+++ b/apps/start/src/components/chat/chat-context.tsx
@@ -1,10 +1,5 @@
-import {
- type ChatModelOption,
- isValidModelId,
- MODEL_STORAGE_KEY,
-} from '@/agents/models';
-import { useTRPC } from '@/integrations/trpc/react';
import { useQuery } from '@tanstack/react-query';
+import { useRouteContext } from '@tanstack/react-router';
import {
createContext,
type ReactNode,
@@ -15,6 +10,12 @@ import {
useState,
} from 'react';
import { newConversationId, useChatUrlState } from './use-chat-open';
+import {
+ type ChatModelOption,
+ isValidModelId,
+ MODEL_STORAGE_KEY,
+} from '@/agents/models';
+import { useTRPC } from '@/integrations/trpc/react';
/**
* Thin global context for chat identifiers. The active conversation
@@ -28,7 +29,7 @@ import { newConversationId, useChatUrlState } from './use-chat-open';
* scoped to it.
*/
-type ChatStateValue = {
+interface ChatStateValue {
/**
* Active conversation id. Mirrors `?chat` in the URL. When the
* drawer is closed this is still populated (the next open uses it),
@@ -92,27 +93,33 @@ type ChatStateValue = {
*/
pendingMessage: string | null;
setPendingMessage: (text: string | null) => void;
-};
+}
const ChatContext = createContext<ChatStateValue | null>(null);
function readStoredAgent(): string | null {
- if (typeof window === 'undefined') return null;
+ if (typeof window === 'undefined') {
+ return null;
+ }
const raw = window.localStorage.getItem(MODEL_STORAGE_KEY);
return isValidModelId(raw) ? raw : null;
}
export function ChatStateProvider({ children }: { children: ReactNode }) {
const trpc = useTRPC();
+ const { session } = useRouteContext({
+ from: '__root__',
+ });
// Single source of truth for "is AI configured on the API" — the
// `chat.models` query already filters by which provider keys are set, so
// an empty `models` array means no OpenAI/Anthropic key and we render the
// setup-instructions empty state. No need to leak env vars to the client.
- const modelsQuery = useQuery({
- ...trpc.chat.models.queryOptions(),
- staleTime: Number.POSITIVE_INFINITY,
- });
+ const modelsQuery = useQuery(
+ trpc.chat.models.queryOptions(undefined, {
+ enabled: !!session?.session,
+ })
+ );
const models = modelsQuery.data?.models ?? [];
const defaultModelId = modelsQuery.data?.defaultModelId ?? null;
const isAiEnabled: boolean | null = modelsQuery.isPending
@@ -130,39 +137,40 @@ export function ChatStateProvider({ children }: { children: ReactNode }) {
// `<ChatRuntimeProvider key={conversationId}>` never sees empty.
// Replaced the moment the user opens the drawer.
const [ghostId] = useState(() => newConversationId());
- const conversationId = chatParam && chatParam.length > 0 ? chatParam : ghostId;
+ const conversationId =
+ chatParam && chatParam.length > 0 ? chatParam : ghostId;
const isOpen = chatParam !== null;
// If the URL says "open with empty id" (e.g. ?chat= from a stale
// link or legacy boolean param), materialize a fresh conversation.
useEffect(() => {
if (chatParam === '') {
- void setChatParam(newConversationId());
+ setChatParam(newConversationId());
}
}, [chatParam, setChatParam]);
const openChatForContext = useCallback(() => {
- void setChatParam(newConversationId());
+ setChatParam(newConversationId());
}, [setChatParam]);
const openNewChat = openChatForContext;
const openChat = useCallback(
(id: string) => {
- void setChatParam(id);
+ setChatParam(id);
},
- [setChatParam],
+ [setChatParam]
);
const closeChat = useCallback(() => {
- void setChatParam(null);
+ setChatParam(null);
}, [setChatParam]);
const switchConversation = useCallback(
(id: string) => {
- void setChatParam(id);
+ setChatParam(id);
},
- [setChatParam],
+ [setChatParam]
);
const newConversation = openNewChat;
@@ -171,17 +179,19 @@ export function ChatStateProvider({ children }: { children: ReactNode }) {
// stored preference (if any); resolves to the server-provided default
// once the models query loads.
const [agentName, setAgentNameState] = useState<string>(
- () => readStoredAgent() ?? '',
+ () => readStoredAgent() ?? ''
);
const setAgent = useCallback(
(id: string) => {
- if (!models.some((m) => m.id === id)) return;
+ if (!models.some((m) => m.id === id)) {
+ return;
+ }
setAgentNameState(id);
if (typeof window !== 'undefined') {
window.localStorage.setItem(MODEL_STORAGE_KEY, id);
}
},
- [models],
+ [models]
);
// Once the models query resolves, make sure `agentName` points at a
@@ -190,8 +200,12 @@ export function ChatStateProvider({ children }: { children: ReactNode }) {
// - stored preference from a provider that's no longer configured
// (e.g. ANTHROPIC_API_KEY was removed) → fall back to default
useEffect(() => {
- if (!defaultModelId) return;
- if (agentName && models.some((m) => m.id === agentName)) return;
+ if (!defaultModelId) {
+ return;
+ }
+ if (agentName && models.some((m) => m.id === agentName)) {
+ return;
+ }
setAgentNameState(defaultModelId);
}, [agentName, defaultModelId, models]);
@@ -245,7 +259,7 @@ export function ChatStateProvider({ children }: { children: ReactNode }) {
isAiEnabled,
streamingTitle,
pendingMessage,
- ],
+ ]
);
return <ChatContext.Provider value={value}>{children}</ChatContext.Provider>;
diff --git a/apps/start/src/hooks/use-session-extension.ts b/apps/start/src/hooks/use-session-extension.ts
index c27163afb..92e74b2e9 100644
--- a/apps/start/src/hooks/use-session-extension.ts
+++ b/apps/start/src/hooks/use-session-extension.ts
@@ -1,19 +1,21 @@
-import { useTRPC } from '@/integrations/trpc/react';
-import { useMutation, useQuery } from '@tanstack/react-query';
-import { useRouteContext, useRouter } from '@tanstack/react-router';
+import { useMutation } from '@tanstack/react-query';
+import { useRouteContext } from '@tanstack/react-router';
import { useEffect, useRef } from 'react';
+import { useTRPC } from '@/integrations/trpc/react';
export function useSessionExtension() {
const trpc = useTRPC();
const context = useRouteContext({
- strict: false,
+ from: '__root__',
});
const extendMutation = useMutation(trpc.auth.extendSession.mutationOptions());
const intervalRef = useRef<NodeJS.Timeout>(null);
const session = context.session?.session;
useEffect(() => {
- if (!session) return;
+ if (!session) {
+ return;
+ }
const extendSessionFn = () => extendMutation.mutate();
@@ -21,7 +23,7 @@ export function useSessionExtension() {
() => {
extendMutation.mutate();
},
- 1000 * 60 * 5,
+ 1000 * 60 * 5
);
// Delay initial call a bit to prioritize other requests
diff --git a/apps/start/src/router.tsx b/apps/start/src/router.tsx
index 47bb2255f..718c0517c 100644
--- a/apps/start/src/router.tsx
+++ b/apps/start/src/router.tsx
@@ -1,7 +1,6 @@
import { createRouter as createTanstackRouter } from '@tanstack/react-router';
import { setupRouterSsrQueryIntegration } from '@tanstack/react-router-ssr-query';
import * as TanstackQuery from './integrations/tanstack-query/root-provider';
-
import { routeTree } from './routeTree.gen';
import { getServerEnvs } from './server/get-envs';
@@ -14,6 +13,11 @@ export const getRouter = async () => {
context: {
...rqContext,
...envs,
+ session: {
+ session: null,
+ user: null,
+ userId: null,
+ },
},
defaultPreload: 'intent',
Wrap: (props: { children: React.ReactNode }) => {
diff --git a/apps/start/src/routes/__root.tsx b/apps/start/src/routes/__root.tsx
index a1c74ff56..4f2b5ace3 100644
--- a/apps/start/src/routes/__root.tsx
+++ b/apps/start/src/routes/__root.tsx
@@ -20,6 +20,7 @@ import { ThemeScriptOnce } from '@/components/theme-provider';
import { LinkButton } from '@/components/ui/button';
import { getCookiesFn } from '@/hooks/use-cookie-store';
import { useSessionExtension } from '@/hooks/use-session-extension';
+import type { RouterOutputs } from '@/trpc/client';
import { op } from '@/utils/op';
if (import.meta.env.VITE_OP_CLIENT_ID) {
@@ -29,6 +30,7 @@ if (import.meta.env.VITE_OP_CLIENT_ID) {
interface MyRouterContext extends ConfigResonse {
queryClient: QueryClient;
trpc: TRPCOptionsProxy<AppRouter>;
+ session: RouterOutputs['auth']['session'];
}
export const Route = createRootRouteWithContext<MyRouterContext>()({