Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix: prevent image/video generation page crash from reused ChatInput action (#17374)

Arvin Xu425e7785fe53
diff --git a/src/features/ChatInput/hooks/useChatInputResourceAccess.test.tsx b/src/features/ChatInput/hooks/useChatInputResourceAccess.test.tsx
new file mode 100644
index 00000000000..b71818552e9
--- /dev/null
+++ b/src/features/ChatInput/hooks/useChatInputResourceAccess.test.tsx
@@ -0,0 +1,65 @@
+import { renderHook } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { createStore, Provider } from '../store';
+import { useChatInputResourceAccess } from './useChatInputResourceAccess';
+
+// Isolate the test to the ChatInput-store access behavior: the peripheral
+// stores/permission hooks are stubbed so the only variable is whether a
+// ChatInput store Provider is present.
+const useResourceAccessMock = vi.fn(() => ({
+ canEditResource: true,
+ canManageResource: true,
+ canUseResource: true,
+ isAccessResolved: true,
+ isLoading: false,
+}));
+
+vi.mock('@/features/ResourcePermission/useResourceAccess', () => ({
+ useResourceAccess: (...args: unknown[]) => useResourceAccessMock(...(args as [])),
+}));
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: () => ({ allowed: true, reason: '' }),
+}));
+
+vi.mock('@/store/agent', () => ({ useAgentStore: () => undefined }));
+vi.mock('@/store/agent/selectors', () => ({
+ builtinAgentSelectors: { inboxAgentId: () => undefined },
+}));
+vi.mock('@/store/agentGroup', () => ({ useAgentGroupStore: () => undefined }));
+vi.mock('@/store/agentGroup/selectors', () => ({
+ agentGroupSelectors: { getGroupById: () => () => undefined },
+}));
+
+describe('useChatInputResourceAccess', () => {
+ afterEach(() => {
+ useResourceAccessMock.mockClear();
+ });
+
+ // Regression: the image/video generation prompt reuses ChatInput's <Action>,
+ // which reaches this hook, without wrapping it in a ChatInput store Provider.
+ // Reading the zustand-utils context store directly threw
+ // "...used zustand provider as an ancestor." and crashed the whole page.
+ it('does not throw when rendered without a ChatInput store Provider', () => {
+ const { result } = renderHook(() => useChatInputResourceAccess());
+
+ expect(result.current.canUseResource).toBe(true);
+ expect(result.current.isGroupContext).toBe(false);
+ // No bound agent to gate when there is no store.
+ expect(useResourceAccessMock).toHaveBeenLastCalledWith('agent', undefined);
+ });
+
+ it('reads the bound agentId from the store when a Provider is present', () => {
+ const store = createStore({ agentId: 'agent-1' });
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <Provider createStore={() => store}>{children}</Provider>
+ );
+
+ const { result } = renderHook(() => useChatInputResourceAccess(), { wrapper });
+
+ expect(result.current.canUseResource).toBe(true);
+ expect(useResourceAccessMock).toHaveBeenLastCalledWith('agent', 'agent-1');
+ });
+});
diff --git a/src/features/ChatInput/hooks/useChatInputResourceAccess.ts b/src/features/ChatInput/hooks/useChatInputResourceAccess.ts
index 6fd5481645a..961803da44e 100644
--- a/src/features/ChatInput/hooks/useChatInputResourceAccess.ts
+++ b/src/features/ChatInput/hooks/useChatInputResourceAccess.ts
@@ -1,5 +1,8 @@
'use client';
+import { useSyncExternalStore } from 'react';
+import type { StoreApi } from 'zustand';
+
import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
@@ -7,7 +10,25 @@ import { builtinAgentSelectors } from '@/store/agent/selectors';
import { useAgentGroupStore } from '@/store/agentGroup';
import { agentGroupSelectors } from '@/store/agentGroup/selectors';
-import { useChatInputStore } from '../store';
+import { type State, useChatInputStoreApiOptional } from '../store';
+
+const EMPTY_SUBSCRIBE = () => () => {};
+
+/**
+ * Reads the bound `agentId` from the ChatInput store, reactively when a store
+ * Provider exists and falling back to `undefined` otherwise. This hook is
+ * reached from the shared <Action> component, which the image/video generation
+ * prompt reuses outside any ChatInput store β€” reading the store directly there
+ * would throw ("...used zustand provider as an ancestor.").
+ */
+const useChatInputAgentId = (): string | undefined => {
+ const storeApi = useChatInputStoreApiOptional() as StoreApi<State> | undefined;
+ return useSyncExternalStore(
+ storeApi ? storeApi.subscribe : EMPTY_SUBSCRIBE,
+ () => storeApi?.getState().agentId,
+ () => undefined,
+ );
+};
/**
* Per-resource General-access gating for the chat input: resolves which
@@ -18,7 +39,7 @@ import { useChatInputStore } from '../store';
* loading defaults permissive β€” the server remains the enforcement point.
*/
export const useChatInputResourceAccess = () => {
- const chatInputAgentId = useChatInputStore((s) => s.agentId);
+ const chatInputAgentId = useChatInputAgentId();
const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
const agentVisibility = useAgentStore((s) =>
chatInputAgentId ? s.agentMap[chatInputAgentId]?.visibility : undefined,
diff --git a/src/features/ChatInput/store/index.ts b/src/features/ChatInput/store/index.ts
index b5cb6b46550..08d218f61dd 100644
--- a/src/features/ChatInput/store/index.ts
+++ b/src/features/ChatInput/store/index.ts
@@ -1,6 +1,13 @@
'use client';
import { type StoreApiWithSelector } from '@lobechat/types';
+import {
+ createContext as createReactContext,
+ createElement,
+ type ReactNode,
+ useContext,
+ useRef,
+} from 'react';
import { subscribeWithSelector } from 'zustand/middleware';
import { shallow } from 'zustand/shallow';
import { createWithEqualityFn } from 'zustand/traditional';
@@ -15,10 +22,49 @@ export type { PublicState, State } from './initialState';
export const createStore = (initState?: Partial<State>) =>
createWithEqualityFn(subscribeWithSelector(store(initState)), shallow);
-export const {
+const {
useStore: useChatInputStore,
useStoreApi,
- Provider,
+ Provider: BaseProvider,
} = createContext<StoreApiWithSelector<Store>>();
+export { useChatInputStore, useStoreApi };
+
+/**
+ * Parallel context that mirrors the ChatInput store api. zustand-utils' own
+ * context throws ("...used zustand provider as an ancestor.") when read without
+ * a Provider, so it cannot answer "is there a store here?". Components reused
+ * outside a chat input β€” e.g. the image/video generation prompt reuses
+ * ChatInput's <Action> β€” read this to degrade gracefully instead of crashing.
+ */
+const ChatInputStoreApiContext = createReactContext<StoreApiWithSelector<Store> | undefined>(
+ undefined,
+);
+
+/** The ChatInput store api, or `undefined` when rendered outside a Provider. */
+export const useChatInputStoreApiOptional = (): StoreApiWithSelector<Store> | undefined =>
+ useContext(ChatInputStoreApiContext);
+
+/**
+ * Wraps zustand-utils' Provider and additionally publishes the same store
+ * instance through {@link ChatInputStoreApiContext} for optional reads. Keeps
+ * the exact `{ createStore, children }` API of the original export.
+ */
+export const Provider = ({
+ createStore: create,
+ children,
+}: {
+ children: ReactNode;
+ createStore: () => StoreApiWithSelector<Store>;
+}) => {
+ const storeRef = useRef<StoreApiWithSelector<Store> | undefined>(undefined);
+ if (!storeRef.current) storeRef.current = create();
+ const storeApi = storeRef.current;
+
+ return createElement(BaseProvider, {
+ children: createElement(ChatInputStoreApiContext.Provider, { children, value: storeApi }),
+ createStore: () => storeApi,
+ });
+};
+
export { selectors } from './selectors';