π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(model-runtime): ensure before* hook errors trigger on*Error handlers (#13496)
YuTengjing297c884b8897
diff --git a/packages/model-runtime/src/core/ModelRuntime.test.ts b/packages/model-runtime/src/core/ModelRuntime.test.tsindex e638aedf02f..bf9d0b51375 100644--- a/packages/model-runtime/src/core/ModelRuntime.test.ts+++ b/packages/model-runtime/src/core/ModelRuntime.test.ts@@ -477,7 +477,7 @@ describe('ModelRuntime', () => {describe('hooks', () => {const createMockRuntime = (hooks?: ModelRuntimeHooks) => {- const mockRuntimeAI = { chat: vi.fn(), generateObject: vi.fn() } as any;+ const mockRuntimeAI = { chat: vi.fn(), embeddings: vi.fn(), generateObject: vi.fn() } as any;return { runtime: new ModelRuntime(mockRuntimeAI, hooks), mockRuntimeAI };};@@ -513,6 +513,20 @@ describe('ModelRuntime', () => {expect(mockRuntimeAI.chat).not.toHaveBeenCalled();});+ it('beforeChat throwing triggers onChatError before re-throwing', async () => {+ const budgetError = { errorType: 'FreePlanLimit', error: { message: 'Budget exceeded' } };+ const beforeChat = vi.fn().mockRejectedValue(budgetError);+ const onChatError = vi.fn();+ const { runtime, mockRuntimeAI } = createMockRuntime({ beforeChat, onChatError });++ await expect(runtime.chat(chatPayload)).rejects.toBe(budgetError);+ expect(mockRuntimeAI.chat).not.toHaveBeenCalled();+ expect(onChatError).toHaveBeenCalledWith(budgetError, {+ options: undefined,+ payload: chatPayload,+ });+ });+it('onChatFinal is injected into callback chain, existing onFinal called first', async () => {const callOrder: string[] = [];const existingOnFinal = vi.fn().mockImplementation(() => callOrder.push('existing'));@@ -591,6 +605,23 @@ describe('ModelRuntime', () => {expect(mockRuntimeAI.generateObject).not.toHaveBeenCalled();});+ it('beforeGenerateObject throwing triggers onGenerateObjectError before re-throwing', async () => {+ const budgetError = { errorType: 'FreePlanLimit', error: { message: 'Budget exceeded' } };+ const beforeGenerateObject = vi.fn().mockRejectedValue(budgetError);+ const onGenerateObjectError = vi.fn();+ const { runtime, mockRuntimeAI } = createMockRuntime({+ beforeGenerateObject,+ onGenerateObjectError,+ });++ await expect(runtime.generateObject(genObjPayload)).rejects.toBe(budgetError);+ expect(mockRuntimeAI.generateObject).not.toHaveBeenCalled();+ expect(onGenerateObjectError).toHaveBeenCalledWith(budgetError, {+ options: undefined,+ payload: genObjPayload,+ });+ });+it('onGenerateObjectFinal wraps onUsage, existing onUsage called first', async () => {const callOrder: string[] = [];const existingOnUsage = vi.fn().mockImplementation(() => callOrder.push('existing'));@@ -630,5 +661,26 @@ describe('ModelRuntime', () => {await expect(runtime.generateObject(genObjPayload)).resolves.toEqual({ result: 'ok' });});});++ describe('embeddings hooks', () => {+ const embeddingsPayload = { model: 'text-embedding-ada-002', input: 'hello' };++ it('beforeEmbeddings throwing triggers onEmbeddingsError before re-throwing', async () => {+ const budgetError = { errorType: 'FreePlanLimit', error: { message: 'Budget exceeded' } };+ const beforeEmbeddings = vi.fn().mockRejectedValue(budgetError);+ const onEmbeddingsError = vi.fn();+ const { runtime, mockRuntimeAI } = createMockRuntime({+ beforeEmbeddings,+ onEmbeddingsError,+ });++ await expect(runtime.embeddings(embeddingsPayload)).rejects.toBe(budgetError);+ expect(mockRuntimeAI.embeddings).not.toHaveBeenCalled();+ expect(onEmbeddingsError).toHaveBeenCalledWith(budgetError, {+ options: undefined,+ payload: embeddingsPayload,+ });+ });+ });});});diff --git a/packages/model-runtime/src/core/ModelRuntime.ts b/packages/model-runtime/src/core/ModelRuntime.tsindex 1d9b28c3c48..27df1ea3d49 100644--- a/packages/model-runtime/src/core/ModelRuntime.ts+++ b/packages/model-runtime/src/core/ModelRuntime.ts@@ -126,9 +126,8 @@ export class ModelRuntime {});}- const finalOptions = await this.applyHooks(payload, options);-try {+ const finalOptions = await this.applyHooks(payload, options);return await this._runtime.chat(payload, finalOptions);} catch (error) {if (this._hooks?.onChatError) {@@ -169,24 +168,24 @@ export class ModelRuntime {}async generateObject(payload: GenerateObjectPayload, options?: GenerateObjectOptions) {- await this._hooks?.beforeGenerateObject?.(payload, options);-- const finalOptions = this._hooks?.onGenerateObjectFinal- ? {- ...options,- onUsage: async (usage: ModelUsage) => {- await options?.onUsage?.(usage);- try {- await this._hooks!.onGenerateObjectFinal!({ usage }, { options, payload });- } catch (e) {- // Hook failures (billing, tracing) must not interfere with response completion- console.error('[ModelRuntime] onGenerateObjectFinal hook error:', e);- }- },- }- : options;-try {+ await this._hooks?.beforeGenerateObject?.(payload, options);++ const finalOptions = this._hooks?.onGenerateObjectFinal+ ? {+ ...options,+ onUsage: async (usage: ModelUsage) => {+ await options?.onUsage?.(usage);+ try {+ await this._hooks!.onGenerateObjectFinal!({ usage }, { options, payload });+ } catch (e) {+ // Hook failures (billing, tracing) must not interfere with response completion+ console.error('[ModelRuntime] onGenerateObjectFinal hook error:', e);+ }+ },+ }+ : options;+return await this._runtime.generateObject!(payload, finalOptions);} catch (error) {if (this._hooks?.onGenerateObjectError) {@@ -216,26 +215,26 @@ export class ModelRuntime {}async embeddings(payload: EmbeddingsPayload, options?: EmbeddingsOptions) {- await this._hooks?.beforeEmbeddings?.(payload, options);-- const startTime = Date.now();-- const finalOptions = this._hooks?.onEmbeddingsFinal- ? {- ...options,- onUsage: async (usage: ModelUsage) => {- await options?.onUsage?.(usage);- try {- const latencyMs = Date.now() - startTime;- await this._hooks!.onEmbeddingsFinal!({ latencyMs, usage }, { options, payload });- } catch (e) {- console.error('[ModelRuntime] onEmbeddingsFinal hook error:', e);- }- },- }- : options;-try {+ await this._hooks?.beforeEmbeddings?.(payload, options);++ const startTime = Date.now();++ const finalOptions = this._hooks?.onEmbeddingsFinal+ ? {+ ...options,+ onUsage: async (usage: ModelUsage) => {+ await options?.onUsage?.(usage);+ try {+ const latencyMs = Date.now() - startTime;+ await this._hooks!.onEmbeddingsFinal!({ latencyMs, usage }, { options, payload });+ } catch (e) {+ console.error('[ModelRuntime] onEmbeddingsFinal hook error:', e);+ }+ },+ }+ : options;+return await this._runtime.embeddings?.(payload, finalOptions);} catch (error) {if (this._hooks?.onEmbeddingsError) {diff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsxindex 93ec128cccb..ea0d1b1ab39 100644--- a/src/features/Conversation/Error/index.tsx+++ b/src/features/Conversation/Error/index.tsx@@ -121,6 +121,7 @@ interface ErrorExtraProps {const ErrorMessageExtra = memo<ErrorExtraProps>(({ error: alertError, data }) => {const error = data.error;const businessChatErrorMessageExtra = useRenderBusinessChatErrorMessageExtra(error, data.id);+if (ENABLE_BUSINESS_FEATURES && businessChatErrorMessageExtra)return businessChatErrorMessageExtra;@@ -139,10 +140,6 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(({ error: alertError, data }) =>return <ExceededContextWindowError id={data.id} />;}- /* β cloud slot β */-- /* β cloud slot β */-case AgentRuntimeErrorType.NoOpenAIAPIKey: {{return <ChatInvalidAPIKey id={data.id} provider={data.error?.body?.provider} />;diff --git a/src/routes/(main)/agent/_layout/index.tsx b/src/routes/(main)/agent/_layout/index.tsxindex 3ed19c1ac76..f4de5f5c51e 100644--- a/src/routes/(main)/agent/_layout/index.tsx+++ b/src/routes/(main)/agent/_layout/index.tsx@@ -20,9 +20,6 @@ const Layout: FC = () => {<Flexbox className={styles.mainContainer} flex={1} height={'100%'}><Outlet /></Flexbox>- {/* β cloud slot β */}-- {/* β cloud slot β */}<RegisterHotkeys />{isDesktop && <ProtocolUrlHandler />}<AgentIdSync />diff --git a/src/routes/(main)/community/_layout/index.tsx b/src/routes/(main)/community/_layout/index.tsxindex e7a47424455..837a3695323 100644--- a/src/routes/(main)/community/_layout/index.tsx+++ b/src/routes/(main)/community/_layout/index.tsx@@ -12,9 +12,6 @@ const Layout: FC = () => {<Flexbox className={styles.mainContainer} flex={1} height={'100%'}><Outlet /></Flexbox>- {/* β cloud slot β */}-- {/* β cloud slot β */}</>);};diff --git a/src/routes/(main)/group/_layout/index.tsx b/src/routes/(main)/group/_layout/index.tsxindex b66e095fe22..e37ac282028 100644--- a/src/routes/(main)/group/_layout/index.tsx+++ b/src/routes/(main)/group/_layout/index.tsx@@ -20,9 +20,6 @@ const Layout: FC = () => {<Flexbox className={styles.mainContainer} flex={1} height={'100%'}><Outlet /></Flexbox>- {/* β cloud slot β */}-- {/* β cloud slot β */}<RegisterHotkeys />{isDesktop && <ProtocolUrlHandler />}<GroupIdSync />diff --git a/src/routes/(main)/settings/provider/detail/default/index.tsx b/src/routes/(main)/settings/provider/detail/default/index.tsxindex af4d0954f29..e0cc14ce6fb 100644--- a/src/routes/(main)/settings/provider/detail/default/index.tsx+++ b/src/routes/(main)/settings/provider/detail/default/index.tsx@@ -23,9 +23,6 @@ const ProviderDetail = memo<ProviderDetailProps>(({ showConfig = true, ...card }return (<Flexbox gap={24} paddingBlock={8}>- {/* β cloud slot β */}-- {/* β cloud slot β */}{showConfig && <ProviderConfig {...card} />}<ModelList id={card.id} {...card.settings} /></Flexbox>diff --git a/src/routes/(mobile)/(home)/_layout/MobileLayout.tsx b/src/routes/(mobile)/(home)/_layout/MobileLayout.tsxindex 9d4653ee88a..a2c3b044bf9 100644--- a/src/routes/(mobile)/(home)/_layout/MobileLayout.tsx+++ b/src/routes/(mobile)/(home)/_layout/MobileLayout.tsx@@ -13,9 +13,6 @@ const MobileLayout = ({ children }: PropsWithChildren) => {<SessionSearchBar mobile /></div>{children}- {/* β cloud slot β */}-- {/* β cloud slot β */}</MobileContentLayout>);};diff --git a/src/routes/(mobile)/me/(home)/features/useCategory.tsx b/src/routes/(mobile)/me/(home)/features/useCategory.tsxindex 624d18b2ebb..814b8209c8d 100644--- a/src/routes/(mobile)/me/(home)/features/useCategory.tsx+++ b/src/routes/(mobile)/me/(home)/features/useCategory.tsx@@ -66,7 +66,6 @@ export const useCategory = (onOpenChangelogModal: () => void) => {},];- /* β cloud slot β */const helps: CellProps[] = [showCloudPromotion && {icon: Cloudy,@@ -100,9 +99,6 @@ export const useCategory = (onOpenChangelogModal: () => void) => {},...(isLoginWithAuth ? profile : []),...(isLoginWithAuth ? settings : []),- /* β cloud slot β */-- /* β cloud slot β */...getDesktopApp,...(!hideDocs ? helps : []),].filter(Boolean) as CellProps[];diff --git a/src/server/sitemap.ts b/src/server/sitemap.tsindex c6a9d2cb23f..54abc4d2c1c 100644--- a/src/server/sitemap.ts+++ b/src/server/sitemap.ts@@ -308,9 +308,6 @@ export class Sitemap {...this._genSitemap('/', { noLocales: true }),...this._genSitemap('/agent', { noLocales: true }),...(!hideDocs ? this._genSitemap('/changelog', { noLocales: true }) : []),- /* β cloud slot β */-- /* β cloud slot β */...this._genSitemap('/community', { changeFrequency: 'daily', priority: 0.7 }),...this._genSitemap('/community/agent', { changeFrequency: 'daily', priority: 0.7 }),...this._genSitemap('/community/mcp', { changeFrequency: 'daily', priority: 0.7 }),