@mastra/react 1.12.0 → 1.13.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/{accumulator-CgLQ_3q3.cjs → accumulator-BmD8-x9I.cjs} +52 -3
  2. package/dist/accumulator-BmD8-x9I.cjs.map +1 -0
  3. package/dist/{accumulator-BfvVnXJr.js → accumulator-D9jAph99.js} +52 -3
  4. package/dist/accumulator-D9jAph99.js.map +1 -0
  5. package/dist/chat/index.cjs +1 -1
  6. package/dist/chat/index.js +1 -1
  7. package/dist/hooks/capabilities/index.cjs +42 -0
  8. package/dist/hooks/capabilities/index.cjs.map +1 -1
  9. package/dist/hooks/capabilities/index.d.ts +3 -0
  10. package/dist/hooks/capabilities/index.d.ts.map +1 -1
  11. package/dist/hooks/capabilities/index.js +40 -1
  12. package/dist/hooks/capabilities/index.js.map +1 -1
  13. package/dist/hooks/capabilities/use-span-aggregate-available.d.ts +9 -0
  14. package/dist/hooks/capabilities/use-span-aggregate-available.d.ts.map +1 -0
  15. package/dist/hooks/capabilities/use-span-query-available.d.ts +9 -0
  16. package/dist/hooks/capabilities/use-span-query-available.d.ts.map +1 -0
  17. package/dist/hooks/capabilities/use-thread-query-available.d.ts +9 -0
  18. package/dist/hooks/capabilities/use-thread-query-available.d.ts.map +1 -0
  19. package/dist/hooks/templates/index.cjs.map +1 -1
  20. package/dist/hooks/templates/index.js.map +1 -1
  21. package/dist/hooks/templates/use-templates.d.ts.map +1 -1
  22. package/dist/hooks/traces/index.cjs +109 -1
  23. package/dist/hooks/traces/index.cjs.map +1 -1
  24. package/dist/hooks/traces/index.d.ts +2 -0
  25. package/dist/hooks/traces/index.d.ts.map +1 -1
  26. package/dist/hooks/traces/index.js +106 -2
  27. package/dist/hooks/traces/index.js.map +1 -1
  28. package/dist/hooks/traces/use-query-spans.d.ts +27 -0
  29. package/dist/hooks/traces/use-query-spans.d.ts.map +1 -0
  30. package/dist/hooks/traces/use-query-threads.d.ts +30 -0
  31. package/dist/hooks/traces/use-query-threads.d.ts.map +1 -0
  32. package/dist/hooks/traces/use-traces.d.ts +37 -37
  33. package/dist/hooks/workflows/index.cjs +1 -1
  34. package/dist/hooks/workflows/index.js +1 -1
  35. package/dist/{hooks-B1i-oHae.cjs → hooks-C6CJtoOR.cjs} +2 -2
  36. package/dist/{hooks-B1i-oHae.cjs.map → hooks-C6CJtoOR.cjs.map} +1 -1
  37. package/dist/{hooks-NaZLZreZ.js → hooks-DG-Y1KFe.js} +2 -2
  38. package/dist/{hooks-NaZLZreZ.js.map → hooks-DG-Y1KFe.js.map} +1 -1
  39. package/dist/{hooks-CLfMO5cH.js → hooks-DvLSZtUd.js} +2 -2
  40. package/dist/{hooks-CLfMO5cH.js.map → hooks-DvLSZtUd.js.map} +1 -1
  41. package/dist/{hooks-D8nOYPUd.cjs → hooks-XYsmqFCz.cjs} +2 -2
  42. package/dist/{hooks-D8nOYPUd.cjs.map → hooks-XYsmqFCz.cjs.map} +1 -1
  43. package/dist/index.cjs +3 -3
  44. package/dist/index.js +3 -3
  45. package/dist/lib/mastra-db/accumulator.d.ts +0 -6
  46. package/dist/lib/mastra-db/accumulator.d.ts.map +1 -1
  47. package/package.json +6 -6
  48. package/dist/accumulator-BfvVnXJr.js.map +0 -1
  49. package/dist/accumulator-CgLQ_3q3.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-span-query-available.d.ts","sourceRoot":"","sources":["../../../src/hooks/capabilities/use-span-query-available.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,eAAO,MAAM,qBAAqB,QAAO;IAAE,SAAS,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAO9E,CAAC"}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * `enabled` stays false while capabilities load. Servers without the
3
+ * capabilities endpoint predate thread rows, so they fall back to `false`.
4
+ */
5
+ export declare const useThreadQueryAvailable: () => {
6
+ isLoading: boolean;
7
+ enabled: boolean;
8
+ };
9
+ //# sourceMappingURL=use-thread-query-available.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-thread-query-available.d.ts","sourceRoot":"","sources":["../../../src/hooks/capabilities/use-thread-query-available.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,eAAO,MAAM,uBAAuB,QAAO;IAAE,SAAS,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAOhF,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["useQuery","useMastraClient","useMutation","useState","RequestContext"],"sources":["../../../src/hooks/templates/use-templates.ts"],"sourcesContent":["import type { MastraClient, TemplateInstallationRequest } from '@mastra/client-js';\nimport { RequestContext } from '@mastra/core/request-context';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery, useMutation } from '@tanstack/react-query';\nimport { useState } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions, MastraQueryOptions } from '../shared/query-options';\n\nexport interface Template {\n slug: string;\n title: string;\n description: string;\n longDescription: string;\n githubUrl: string;\n tags: string[];\n imageURL?: string;\n codeExample?: string;\n agents?: string[];\n tools?: string[];\n workflows?: string[];\n mcp?: string[];\n networks?: string[];\n videoURL?: string;\n useCase: string;\n supportedProviders: string[];\n}\n\nasync function getMastraTemplateRepos(): Promise<{ templates: Template[]; tags: string[]; providers: string[] }> {\n const response = await fetch('https://mastra.ai/api/templates.json');\n if (!response.ok) {\n throw new Error(`Failed to fetch templates: ${response.statusText}`);\n }\n const templates = await response.json();\n const allTemplates = [\n {\n title: 'Weather Agent',\n slug: 'weather-agent',\n githubUrl: 'https://github.com/mastra-ai/weather-agent',\n description: 'Get weather information of any city.',\n longDescription: 'One Agent, one Workflow and one Tool to bring you the weather in your city.',\n imageURL: '',\n tags: ['Agent', 'Workflow', 'Tool'],\n useCase: '',\n supportedProviders: ['openai', 'anthropic', 'google', 'groq'],\n agents: ['weatherAgent'],\n tools: ['weatherTool'],\n workflows: ['weatherWorkflow'],\n },\n ...templates,\n ];\n\n const allTags = Array.from(new Set(allTemplates.flatMap(t => t.tags)));\n const allProviders = Array.from(new Set(allTemplates.flatMap(t => t.supportedProviders)));\n\n return {\n templates: allTemplates,\n tags: allTags,\n providers: allProviders,\n };\n}\n\nasync function getTemplateRepoByRepoName({ repo, owner }: { repo: string; owner: string }): Promise<Template> {\n const response = await fetch(`https://api.github.com/repos/${owner}/${repo}`);\n if (!response.ok) {\n throw new Error(`Failed to fetch template: ${response.statusText}`);\n }\n const repoInfo = await response.json();\n if (!repoInfo.is_template) {\n throw new Error('Repo is not a template, please update the repo settings to make it a template');\n }\n\n return {\n title: repoInfo.name,\n slug: repoInfo.name,\n description: repoInfo.description ?? '',\n imageURL: '',\n tags: [],\n useCase: '',\n longDescription: repoInfo.description ?? '',\n githubUrl: repoInfo.html_url,\n supportedProviders: [],\n };\n}\n\nasync function getTemplateRepo({ repoOrSlug, owner }: { repoOrSlug: string; owner: string }): Promise<Template> {\n const { templates } = await getMastraTemplateRepos();\n const template = templates.find(t => t.slug === repoOrSlug);\n\n if (!template) {\n if (owner === 'mastra-ai' && repoOrSlug.startsWith('template-')) {\n const templateRepo = templates.find(template => `template-${template.slug}` === repoOrSlug);\n if (templateRepo) {\n return templateRepo;\n }\n }\n\n const templateRepo = await getTemplateRepoByRepoName({ repo: repoOrSlug, owner });\n\n if (templateRepo) {\n return templateRepo;\n }\n\n throw new Error(`Template ${repoOrSlug} not found`);\n }\n\n return template;\n}\n\nasync function getTemplateRepoEnvVars({\n repo,\n owner,\n branch,\n}: {\n repo: string;\n owner: string;\n branch: string;\n}): Promise<Record<string, string>> {\n const envUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${branch}/.env.example`;\n const envResponse = await fetch(envUrl);\n\n if (envResponse.ok) {\n const envContent = await envResponse.text();\n const envVars = envContent.split('\\n').reduce(\n (acc, line) => {\n if (!line || line.startsWith('#')) return acc; // Skip empty lines and comments\n\n const [key, value] = line.split('=');\n\n if (key) {\n acc[key] = value?.split('')?.every(item => item === '*') ? '' : value?.replaceAll('\"', '');\n }\n return acc;\n },\n {} as Record<string, string>,\n );\n\n return envVars;\n }\n\n return {};\n}\n\ntype MastraTemplateRepos = Awaited<ReturnType<typeof getMastraTemplateRepos>>;\ntype TemplateRepo = Awaited<ReturnType<typeof getTemplateRepo>>;\ntype TemplateRepoEnvVars = Awaited<ReturnType<typeof getTemplateRepoEnvVars>>;\ntype AgentBuilderWorkflowDetails = Awaited<ReturnType<ReturnType<MastraClient['getAgentBuilderAction']>['details']>>;\ntype TemplateInstallRun = Awaited<ReturnType<ReturnType<MastraClient['getAgentBuilderAction']>['createRun']>>;\ntype TemplateInstallRunById = Awaited<ReturnType<ReturnType<MastraClient['getAgentBuilderAction']>['runById']>>;\ntype StreamTemplateInstallVariables = {\n inputData: TemplateInstallationRequest;\n selectedModel: { provider: string; modelId: string };\n runId: string;\n};\n\nexport const useMastraTemplates = <TData = MastraTemplateRepos>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<MastraTemplateRepos, TData> } = {}): UseQueryResult<TData, Error> => {\n return useQuery<MastraTemplateRepos, Error, TData>({\n queryKey: ['mastra-templates'],\n queryFn: getMastraTemplateRepos,\n ...queryOptions,\n });\n};\n\nexport const useTemplateRepo = <TData = TemplateRepo>({\n repoOrSlug,\n owner,\n queryOptions,\n}: {\n repoOrSlug: string;\n owner: string;\n queryOptions?: MastraQueryOptions<TemplateRepo, TData>;\n}): UseQueryResult<TData, Error> => {\n return useQuery<TemplateRepo, Error, TData>({\n queryKey: ['template-repo', repoOrSlug, owner],\n queryFn: () => getTemplateRepo({ repoOrSlug, owner }),\n ...queryOptions,\n });\n};\n\nexport const useTemplateRepoEnvVars = <TData = TemplateRepoEnvVars>({\n repo,\n owner,\n branch,\n queryOptions,\n}: {\n repo: string;\n owner: string;\n branch: string;\n queryOptions?: MastraQueryOptions<TemplateRepoEnvVars, TData>;\n}): UseQueryResult<TData, Error> => {\n return useQuery<TemplateRepoEnvVars, Error, TData>({\n queryKey: ['template-repo-env-vars', repo, owner, branch],\n queryFn: () => getTemplateRepoEnvVars({ repo, owner, branch }),\n ...queryOptions,\n });\n};\n\nexport const useAgentBuilderWorkflow = <TData = AgentBuilderWorkflowDetails>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<AgentBuilderWorkflowDetails, TData> } = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n return useQuery<AgentBuilderWorkflowDetails, Error, TData>({\n queryKey: ['agent-builder-workflow'],\n queryFn: async () => {\n return await client.getAgentBuilderAction('merge-template').details();\n },\n ...queryOptions,\n });\n};\n\nexport const useCreateTemplateInstallRun = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<TemplateInstallRun, { runId?: string }> } = {}) => {\n const client = useMastraClient();\n return useMutation({\n mutationFn: async ({ runId }: { runId?: string }) => {\n return await client.getAgentBuilderAction('merge-template').createRun({ runId });\n },\n ...queryOptions,\n });\n};\n\nexport const useGetTemplateInstallRun = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<TemplateInstallRunById, { runId: string }> } = {}) => {\n const client = useMastraClient();\n return useMutation({\n mutationFn: async ({ runId }: { runId: string }) => {\n return await client.getAgentBuilderAction('merge-template').runById(runId);\n },\n ...queryOptions,\n });\n};\n\nconst normalizeError = (error: unknown): string => {\n if (typeof error === 'string') return error;\n if (error == null) return 'Unknown error';\n if (error instanceof Error)\n return typeof error.message === 'string' && error.message.length > 0 ? error.message : 'Unknown error';\n if (typeof error === 'object') {\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n }\n return String(error);\n};\n\n// Helper function to process template installation records (like workflows' sanitizeWorkflowWatchResult)\nconst processTemplateInstallRecord = (\n record: { type: string; payload: any; runId?: string; eventTimestamp?: string },\n currentState: any,\n workflowInfo?: any,\n): { newState: any } => {\n let newState = { ...currentState };\n\n // Initialize steps if not present or empty\n const hasSteps =\n newState.payload?.workflowState?.steps && Object.keys(newState.payload.workflowState.steps).length > 0;\n if (!hasSteps && workflowInfo?.allSteps) {\n newState.payload = {\n ...newState.payload,\n workflowState: {\n ...newState.payload?.workflowState,\n steps: Object.keys(workflowInfo.allSteps).reduce((acc, stepId) => {\n acc[stepId] = {\n id: stepId,\n description: workflowInfo.allSteps[stepId].description,\n status: 'pending',\n };\n return acc;\n }, {} as any),\n },\n };\n }\n\n // Handle different event types\n // Support both legacy ('start') and VNext ('workflow-start') formats\n if (record.type === 'start' || record.type === 'workflow-start') {\n // Pre-populate all workflow steps from workflowInfo if available\n const initialSteps: any = {};\n if (workflowInfo?.allSteps) {\n Object.entries(workflowInfo.allSteps).forEach(([stepId, stepData]: [string, any]) => {\n initialSteps[stepId] = {\n id: stepData.id,\n description: stepData.description,\n status: 'pending',\n };\n });\n }\n\n const runId = record.runId || record.payload?.runId;\n\n newState = {\n ...newState,\n runId,\n eventTimestamp: new Date().toISOString(),\n status: 'running',\n phase: 'initializing',\n payload: {\n workflowState: {\n status: 'running',\n steps: initialSteps,\n },\n currentStep: null,\n },\n };\n }\n\n // Support both legacy ('step-start') and VNext ('workflow-step-start') formats\n if (record.type === 'step-start' || record.type === 'workflow-step-start') {\n const stepId = record.payload.id;\n newState = {\n ...newState,\n phase: 'processing',\n payload: {\n ...newState.payload,\n currentStep: {\n id: stepId,\n status: 'running',\n startTime: new Date(),\n ...record.payload,\n },\n workflowState: {\n ...newState.payload.workflowState,\n steps: {\n ...newState.payload.workflowState.steps,\n [stepId]: {\n ...newState.payload.workflowState.steps[stepId],\n status: 'running',\n startTime: new Date(),\n ...record.payload,\n },\n },\n },\n },\n };\n }\n\n // Support both legacy ('step-result') and VNext ('workflow-step-result') formats\n if (record.type === 'step-result' || record.type === 'workflow-step-result') {\n const stepId = record.payload.id;\n const status = record.payload.status;\n const hasError = record.payload.error;\n newState = {\n ...newState,\n payload: {\n ...newState.payload,\n currentStep: {\n ...newState.payload.currentStep,\n status: record.payload.status,\n output: record.payload.output,\n error: record.payload.error,\n endTime: new Date(),\n },\n workflowState: {\n ...newState.payload.workflowState,\n steps: {\n ...newState.payload.workflowState.steps,\n [stepId]: {\n ...newState.payload.workflowState.steps[stepId],\n status: record.payload.status,\n output: record.payload.output,\n error: record.payload.error,\n endTime: new Date(),\n },\n },\n },\n },\n };\n\n // If this step failed, also set workflow-level error state\n if (status === 'failed' && hasError) {\n const errorString = normalizeError(hasError);\n newState = {\n ...newState,\n status: 'failed',\n error: errorString,\n phase: 'error',\n failedStep: {\n id: stepId,\n error: errorString,\n description: record.payload.description || stepId,\n },\n payload: {\n ...newState.payload,\n workflowState: {\n ...newState.payload.workflowState,\n status: 'failed',\n },\n },\n errorTimestamp: new Date(),\n };\n }\n }\n\n // Support both legacy ('step-finish') and VNext ('workflow-step-finish') formats\n if (record.type === 'step-finish' || record.type === 'workflow-step-finish') {\n newState = {\n ...newState,\n payload: {\n ...newState.payload,\n currentStep: null,\n },\n };\n }\n\n // Support both legacy ('finish') and VNext ('workflow-finish') formats\n if (record.type === 'finish' || record.type === 'workflow-finish') {\n // Don't override error states - if we're already in error phase, stay there\n if (newState.phase === 'error' || newState.status === 'failed') {\n newState = {\n ...newState,\n // Keep existing status, phase, error, failedStep\n completedAt: new Date(),\n };\n } else {\n // Normal completion flow\n newState = {\n ...newState,\n status: record.payload.status || 'completed',\n phase: 'completed',\n payload: {\n ...newState.payload,\n currentStep: null,\n workflowState: {\n ...newState.payload.workflowState,\n status: record.payload.status || 'completed',\n },\n },\n completedAt: new Date(),\n };\n }\n }\n\n if (record.type === 'error') {\n const errorStr = normalizeError(record.payload.error);\n newState = {\n ...newState,\n status: 'failed',\n error: errorStr,\n phase: 'error',\n payload: {\n ...newState.payload,\n workflowState: {\n ...newState.payload.workflowState,\n status: 'failed',\n },\n },\n errorTimestamp: new Date(),\n };\n }\n\n return { newState };\n};\n\n// Shared localStorage helpers for template installation state\nconst saveTemplateStateToLocalStorage = (runId: string, state: any) => {\n try {\n localStorage.setItem(\n `template-install-${runId}`,\n JSON.stringify({\n state,\n timestamp: Date.now(),\n }),\n );\n } catch (error) {\n console.warn('Failed to save template state to localStorage:', error);\n }\n};\n\n// Shared helper for processing template installation streams (streamlined)\nconst useTemplateStreamProcessor = (workflowInfo?: any, runId?: string) => {\n const [streamResult, setStreamResult] = useState<any>({});\n const [isStreaming, setIsStreaming] = useState(false);\n\n const processStream = async (stream: any, initialRunId?: string) => {\n setIsStreaming(true);\n setStreamResult({});\n\n if (!stream) throw new Error('No stream returned');\n\n const reader = stream.getReader();\n\n // Initialize minimal state - don't set immediately, let events drive the state\n let currentState: any = {\n runId: initialRunId || runId,\n eventTimestamp: new Date().toISOString(),\n phase: 'running',\n payload: {\n workflowState: {\n steps: {},\n },\n currentStep: null,\n },\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n const { newState } = processTemplateInstallRecord(value, currentState, workflowInfo);\n\n currentState = newState;\n setStreamResult(newState);\n\n // Save to localStorage for refresh recovery (same as watch)\n if (value.runId || initialRunId || runId) {\n const effectiveRunId = value.runId || initialRunId || runId;\n saveTemplateStateToLocalStorage(effectiveRunId, newState);\n }\n }\n } catch (error) {\n console.error('💥 [processStream] Error processing template installation stream:', error);\n\n // Use the helper for error handling too\n const { newState } = processTemplateInstallRecord(\n { type: 'error', payload: { error: error instanceof Error ? error.message : 'Unknown error' } },\n currentState,\n workflowInfo,\n );\n\n setStreamResult(newState);\n } finally {\n setIsStreaming(false);\n reader.releaseLock();\n }\n };\n\n return {\n streamResult,\n isStreaming,\n processStream,\n };\n};\n\nexport const useStreamTemplateInstall = ({\n workflowInfo,\n queryOptions,\n}: {\n workflowInfo?: any;\n queryOptions?: { streamInstall?: MastraMutationOptions<void, StreamTemplateInstallVariables> };\n} = {}) => {\n const client = useMastraClient();\n const { streamResult, isStreaming, processStream } = useTemplateStreamProcessor(workflowInfo);\n\n const streamInstall = useMutation({\n mutationFn: async ({ inputData, selectedModel, runId }: StreamTemplateInstallVariables) => {\n const maxRetries = 3;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n const template = client.getAgentBuilderAction('merge-template');\n const requestContext = new RequestContext();\n requestContext.set('selectedModel', selectedModel);\n const stream = await template.stream({ inputData, requestContext }, runId);\n await processStream(stream, runId);\n\n // If we get here, the stream completed successfully\n return;\n } catch (error: any) {\n console.error(`💥 [streamInstall] Attempt ${attempt} failed:`, error);\n const isNetworkError =\n error?.message?.includes('Failed to fetch') ||\n error?.message?.includes('NetworkError') ||\n error?.message?.includes('network error') ||\n error?.message?.includes('fetch') ||\n error?.code === 'NETWORK_ERROR' ||\n error?.name === 'TypeError';\n\n console.warn(`Stream attempt ${attempt}/${maxRetries} failed:`, error);\n\n if (isNetworkError) {\n // For stream network errors, provide helpful message since switching context is complex\n const errorMessage = runId\n ? `Network error during template installation (likely hot reload). Please refresh the page to resume from where you left off using runId: ${runId}`\n : 'Network error during template installation (likely hot reload). Please try again.';\n\n console.error('🔌 Stream network error:', errorMessage);\n throw new Error(errorMessage);\n }\n\n // If it's not a network error or we've exhausted retries, throw\n console.error('❌ [streamInstall] Non-network error or max retries reached, throwing:', error);\n throw error;\n }\n }\n },\n ...queryOptions?.streamInstall,\n });\n\n return {\n streamInstall,\n streamResult,\n isStreaming,\n };\n};\n\n/**\n * Hook for observing template installation with full replay capability.\n * Uses observeStream() which replays cached execution from beginning, then continues live.\n */\nexport const useObserveStreamTemplateInstall = ({\n workflowInfo,\n queryOptions,\n}: {\n workflowInfo?: any;\n queryOptions?: { observeInstall?: MastraMutationOptions<void, { runId: string }> };\n} = {}) => {\n const client = useMastraClient();\n const { streamResult, isStreaming, processStream } = useTemplateStreamProcessor(workflowInfo);\n\n const observeInstall = useMutation({\n mutationFn: async ({ runId }: { runId: string }) => {\n const maxRetries = 3;\n const retryDelay = 2000; // 2 seconds\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n // Initialize state - but observeStream will replay full history\n // so we don't need to rely on localStorage as fallback\n const template = client.getAgentBuilderAction('merge-template');\n\n // Use observeStream to get full replay + live updates\n const stream = await template.observeStream({ runId });\n await processStream(stream, runId);\n\n // If we get here, the observe stream completed successfully\n return;\n } catch (error: any) {\n console.error(`💥 [observeInstall] Attempt ${attempt} failed:`, error);\n const isNetworkError =\n error?.message?.includes('Failed to fetch') ||\n error?.message?.includes('NetworkError') ||\n error?.message?.includes('network error') ||\n error?.message?.includes('fetch') ||\n error?.code === 'NETWORK_ERROR' ||\n error?.name === 'TypeError';\n\n console.warn(`ObserveStream attempt ${attempt}/${maxRetries} failed:`, error);\n\n if (isNetworkError && attempt < maxRetries) {\n console.info(\n `🔄 ObserveStream network error detected (likely hot reload), retrying in ${retryDelay}ms... (attempt ${attempt + 1}/${maxRetries})`,\n );\n await new Promise(resolve => setTimeout(resolve, retryDelay));\n continue; // Retry\n }\n\n // If it's not a network error or we've exhausted retries, throw\n console.error('❌ [observeInstall] Non-network error or max retries reached, throwing:', error);\n throw error;\n }\n }\n },\n ...queryOptions?.observeInstall,\n });\n\n return {\n observeInstall,\n streamResult,\n isStreaming,\n };\n};\n"],"mappings":";;;;;;AA2BA,eAAe,yBAAkG;CAC/G,MAAM,WAAW,MAAM,MAAM,sCAAsC;CACnE,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,8BAA8B,SAAS,YAAY;CAGrE,MAAM,eAAe,CACnB;EACE,OAAO;EACP,MAAM;EACN,WAAW;EACX,aAAa;EACb,iBAAiB;EACjB,UAAU;EACV,MAAM;GAAC;GAAS;GAAY;EAAM;EAClC,SAAS;EACT,oBAAoB;GAAC;GAAU;GAAa;GAAU;EAAM;EAC5D,QAAQ,CAAC,cAAc;EACvB,OAAO,CAAC,aAAa;EACrB,WAAW,CAAC,iBAAiB;CAC/B,GACA,GAAG,MAhBmB,SAAS,KAAK,CAiBtC;CAKA,OAAO;EACL,WAAW;EACX,MALc,MAAM,KAAK,IAAI,IAAI,aAAa,SAAQ,MAAK,EAAE,IAAI,CAAC,CAKtD;EACZ,WALmB,MAAM,KAAK,IAA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CAAC,MAAM;CACT,MAAM,SAASH,8BAAAA,gBAAgB;CAC/B,MAAM,EAAE,cAAc,aAAa,kBAAkB,2BAA2B,YAAY;CAgD5F,OAAO;EACL,iBAAA,GA/CqBC,sBAAAA,YAAAA,CAAY;GACjC,YAAY,OAAO,EAAE,YAA+B;IAClD,MAAM,aAAa;IACnB,MAAM,aAAa;IAEnB,KAAK,IAAI,UAAU,GAAG,WAAW,YAAY,WAC3C,IAAI;KAMF,MAAM,SAAS,MAHE,OAAO,sBAAsB,gBAGlB,CAAC,CAAC,cAAc,EAAE,MAAM,CAAC;KACrD,MAAM,cAAc,QAAQ,KAAK;KAGjC;IACF,SAAS,OAAY;KACnB,QAAQ,MAAM,+BAA+B,QAAQ,WAAW,KAAK;KACrE,MAAM,iBACJ,OAAO,SAAS,SAAS,iBAAiB,KAC1C,OAAO,SAAS,SAAS,cAAc,KACvC,OAAO,SAAS,SAAS,eAAe,KACxC,OAAO,SAAS,SAAS,OAAO,KAChC,OAAO,SAAS,mBAChB,OAAO,SAAS;KAElB,QAAQ,KAAK,yBAAyB,QAAQ,GAAG,WAAW,WAAW,KAAK;KAE5E,IAAI,kBAAkB,UAAU,YAAY;MAC1C,QAAQ,KACN,4EAA4E,WAAW,iBAAiB,UAAU,EAAE,GAAG,WAAW,EACpI;MACA,MAAM,IAAI,SAAQ,YAAW,WAAW,SAAS,UAAU,CAAC;MAC5D;KACF;KAGA,QAAQ,MAAM,0EAA0E,KAAK;KAC7F,MAAM;IACR;GAEJ;GACA,GAAG,cAAc;EACnB,CAGe;EACb;EACA;CACF;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["useQuery","useMastraClient","useMutation","useState","RequestContext"],"sources":["../../../src/hooks/templates/use-templates.ts"],"sourcesContent":["import type { MastraClient, TemplateInstallationRequest } from '@mastra/client-js';\nimport { RequestContext } from '@mastra/core/request-context';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery, useMutation } from '@tanstack/react-query';\nimport { useState } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions, MastraQueryOptions } from '../shared/query-options';\n\nexport interface Template {\n slug: string;\n title: string;\n description: string;\n longDescription: string;\n githubUrl: string;\n tags: string[];\n imageURL?: string;\n codeExample?: string;\n agents?: string[];\n tools?: string[];\n workflows?: string[];\n mcp?: string[];\n networks?: string[];\n videoURL?: string;\n useCase: string;\n supportedProviders: string[];\n}\n\nasync function getMastraTemplateRepos(): Promise<{ templates: Template[]; tags: string[]; providers: string[] }> {\n const response = await fetch('https://mastra.ai/api/templates.json');\n if (!response.ok) {\n throw new Error(`Failed to fetch templates: ${response.statusText}`);\n }\n const templates = await response.json();\n const allTemplates = [\n {\n title: 'Weather Agent',\n slug: 'weather-agent',\n githubUrl: 'https://github.com/mastra-ai/weather-agent',\n description: 'Get weather information of any city.',\n longDescription: 'One Agent, one Workflow and one Tool to bring you the weather in your city.',\n imageURL: '',\n tags: ['Agent', 'Workflow', 'Tool'],\n useCase: '',\n supportedProviders: ['openai', 'anthropic', 'google', 'groq'],\n agents: ['weatherAgent'],\n tools: ['weatherTool'],\n workflows: ['weatherWorkflow'],\n },\n ...templates,\n ];\n\n const allTags = Array.from(new Set(allTemplates.flatMap(t => t.tags)));\n const allProviders = Array.from(new Set(allTemplates.flatMap(t => t.supportedProviders)));\n\n return {\n templates: allTemplates,\n tags: allTags,\n providers: allProviders,\n };\n}\n\nasync function getTemplateRepoByRepoName({ repo, owner }: { repo: string; owner: string }): Promise<Template> {\n const response = await fetch(`https://api.github.com/repos/${owner}/${repo}`);\n if (!response.ok) {\n throw new Error(`Failed to fetch template: ${response.statusText}`);\n }\n const repoInfo = await response.json();\n if (!repoInfo.is_template) {\n throw new Error('Repo is not a template, please update the repo settings to make it a template');\n }\n\n return {\n title: repoInfo.name,\n slug: repoInfo.name,\n description: repoInfo.description ?? '',\n imageURL: '',\n tags: [],\n useCase: '',\n longDescription: repoInfo.description ?? '',\n githubUrl: repoInfo.html_url,\n supportedProviders: [],\n };\n}\n\nasync function getTemplateRepo({ repoOrSlug, owner }: { repoOrSlug: string; owner: string }): Promise<Template> {\n const { templates } = await getMastraTemplateRepos();\n const template = templates.find(t => t.slug === repoOrSlug);\n\n if (!template) {\n if (owner === 'mastra-ai' && repoOrSlug.startsWith('template-')) {\n const templateRepo = templates.find(template => `template-${template.slug}` === repoOrSlug);\n if (templateRepo) {\n return templateRepo;\n }\n }\n\n const templateRepo = await getTemplateRepoByRepoName({ repo: repoOrSlug, owner });\n\n if (templateRepo) {\n return templateRepo;\n }\n\n throw new Error(`Template ${repoOrSlug} not found`);\n }\n\n return template;\n}\n\nasync function getTemplateRepoEnvVars({\n repo,\n owner,\n branch,\n}: {\n repo: string;\n owner: string;\n branch: string;\n}): Promise<Record<string, string>> {\n const envUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${branch}/.env.example`;\n const envResponse = await fetch(envUrl);\n\n if (envResponse.ok) {\n const envContent = await envResponse.text();\n const envVars = envContent.split('\\n').reduce<Record<string, string>>((acc, line) => {\n if (!line || line.startsWith('#')) return acc; // Skip empty lines and comments\n\n const [key, value] = line.split('=');\n\n if (key) {\n acc[key] = value?.split('')?.every(item => item === '*') ? '' : value?.replaceAll('\"', '');\n }\n return acc;\n }, {});\n\n return envVars;\n }\n\n return {};\n}\n\ntype MastraTemplateRepos = Awaited<ReturnType<typeof getMastraTemplateRepos>>;\ntype TemplateRepo = Awaited<ReturnType<typeof getTemplateRepo>>;\ntype TemplateRepoEnvVars = Awaited<ReturnType<typeof getTemplateRepoEnvVars>>;\ntype AgentBuilderWorkflowDetails = Awaited<ReturnType<ReturnType<MastraClient['getAgentBuilderAction']>['details']>>;\ntype TemplateInstallRun = Awaited<ReturnType<ReturnType<MastraClient['getAgentBuilderAction']>['createRun']>>;\ntype TemplateInstallRunById = Awaited<ReturnType<ReturnType<MastraClient['getAgentBuilderAction']>['runById']>>;\ntype StreamTemplateInstallVariables = {\n inputData: TemplateInstallationRequest;\n selectedModel: { provider: string; modelId: string };\n runId: string;\n};\n\nexport const useMastraTemplates = <TData = MastraTemplateRepos>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<MastraTemplateRepos, TData> } = {}): UseQueryResult<TData, Error> => {\n return useQuery<MastraTemplateRepos, Error, TData>({\n queryKey: ['mastra-templates'],\n queryFn: getMastraTemplateRepos,\n ...queryOptions,\n });\n};\n\nexport const useTemplateRepo = <TData = TemplateRepo>({\n repoOrSlug,\n owner,\n queryOptions,\n}: {\n repoOrSlug: string;\n owner: string;\n queryOptions?: MastraQueryOptions<TemplateRepo, TData>;\n}): UseQueryResult<TData, Error> => {\n return useQuery<TemplateRepo, Error, TData>({\n queryKey: ['template-repo', repoOrSlug, owner],\n queryFn: () => getTemplateRepo({ repoOrSlug, owner }),\n ...queryOptions,\n });\n};\n\nexport const useTemplateRepoEnvVars = <TData = TemplateRepoEnvVars>({\n repo,\n owner,\n branch,\n queryOptions,\n}: {\n repo: string;\n owner: string;\n branch: string;\n queryOptions?: MastraQueryOptions<TemplateRepoEnvVars, TData>;\n}): UseQueryResult<TData, Error> => {\n return useQuery<TemplateRepoEnvVars, Error, TData>({\n queryKey: ['template-repo-env-vars', repo, owner, branch],\n queryFn: () => getTemplateRepoEnvVars({ repo, owner, branch }),\n ...queryOptions,\n });\n};\n\nexport const useAgentBuilderWorkflow = <TData = AgentBuilderWorkflowDetails>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<AgentBuilderWorkflowDetails, TData> } = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n return useQuery<AgentBuilderWorkflowDetails, Error, TData>({\n queryKey: ['agent-builder-workflow'],\n queryFn: async () => {\n return await client.getAgentBuilderAction('merge-template').details();\n },\n ...queryOptions,\n });\n};\n\nexport const useCreateTemplateInstallRun = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<TemplateInstallRun, { runId?: string }> } = {}) => {\n const client = useMastraClient();\n return useMutation({\n mutationFn: async ({ runId }: { runId?: string }) => {\n return await client.getAgentBuilderAction('merge-template').createRun({ runId });\n },\n ...queryOptions,\n });\n};\n\nexport const useGetTemplateInstallRun = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<TemplateInstallRunById, { runId: string }> } = {}) => {\n const client = useMastraClient();\n return useMutation({\n mutationFn: async ({ runId }: { runId: string }) => {\n return await client.getAgentBuilderAction('merge-template').runById(runId);\n },\n ...queryOptions,\n });\n};\n\nconst normalizeError = (error: unknown): string => {\n if (typeof error === 'string') return error;\n if (error == null) return 'Unknown error';\n if (error instanceof Error)\n return typeof error.message === 'string' && error.message.length > 0 ? error.message : 'Unknown error';\n if (typeof error === 'object') {\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n }\n return String(error);\n};\n\n// Helper function to process template installation records (like workflows' sanitizeWorkflowWatchResult)\nconst processTemplateInstallRecord = (\n record: { type: string; payload: any; runId?: string; eventTimestamp?: string },\n currentState: any,\n workflowInfo?: any,\n): { newState: any } => {\n let newState = { ...currentState };\n\n // Initialize steps if not present or empty\n const hasSteps =\n newState.payload?.workflowState?.steps && Object.keys(newState.payload.workflowState.steps).length > 0;\n if (!hasSteps && workflowInfo?.allSteps) {\n newState.payload = {\n ...newState.payload,\n workflowState: {\n ...newState.payload?.workflowState,\n steps: Object.keys(workflowInfo.allSteps).reduce<any>((acc, stepId) => {\n acc[stepId] = {\n id: stepId,\n description: workflowInfo.allSteps[stepId].description,\n status: 'pending',\n };\n return acc;\n }, {}),\n },\n };\n }\n\n // Handle different event types\n // Support both legacy ('start') and VNext ('workflow-start') formats\n if (record.type === 'start' || record.type === 'workflow-start') {\n // Pre-populate all workflow steps from workflowInfo if available\n const initialSteps: any = {};\n if (workflowInfo?.allSteps) {\n Object.entries(workflowInfo.allSteps).forEach(([stepId, stepData]: [string, any]) => {\n initialSteps[stepId] = {\n id: stepData.id,\n description: stepData.description,\n status: 'pending',\n };\n });\n }\n\n const runId = record.runId || record.payload?.runId;\n\n newState = {\n ...newState,\n runId,\n eventTimestamp: new Date().toISOString(),\n status: 'running',\n phase: 'initializing',\n payload: {\n workflowState: {\n status: 'running',\n steps: initialSteps,\n },\n currentStep: null,\n },\n };\n }\n\n // Support both legacy ('step-start') and VNext ('workflow-step-start') formats\n if (record.type === 'step-start' || record.type === 'workflow-step-start') {\n const stepId = record.payload.id;\n newState = {\n ...newState,\n phase: 'processing',\n payload: {\n ...newState.payload,\n currentStep: {\n id: stepId,\n status: 'running',\n startTime: new Date(),\n ...record.payload,\n },\n workflowState: {\n ...newState.payload.workflowState,\n steps: {\n ...newState.payload.workflowState.steps,\n [stepId]: {\n ...newState.payload.workflowState.steps[stepId],\n status: 'running',\n startTime: new Date(),\n ...record.payload,\n },\n },\n },\n },\n };\n }\n\n // Support both legacy ('step-result') and VNext ('workflow-step-result') formats\n if (record.type === 'step-result' || record.type === 'workflow-step-result') {\n const stepId = record.payload.id;\n const status = record.payload.status;\n const hasError = record.payload.error;\n newState = {\n ...newState,\n payload: {\n ...newState.payload,\n currentStep: {\n ...newState.payload.currentStep,\n status: record.payload.status,\n output: record.payload.output,\n error: record.payload.error,\n endTime: new Date(),\n },\n workflowState: {\n ...newState.payload.workflowState,\n steps: {\n ...newState.payload.workflowState.steps,\n [stepId]: {\n ...newState.payload.workflowState.steps[stepId],\n status: record.payload.status,\n output: record.payload.output,\n error: record.payload.error,\n endTime: new Date(),\n },\n },\n },\n },\n };\n\n // If this step failed, also set workflow-level error state\n if (status === 'failed' && hasError) {\n const errorString = normalizeError(hasError);\n newState = {\n ...newState,\n status: 'failed',\n error: errorString,\n phase: 'error',\n failedStep: {\n id: stepId,\n error: errorString,\n description: record.payload.description || stepId,\n },\n payload: {\n ...newState.payload,\n workflowState: {\n ...newState.payload.workflowState,\n status: 'failed',\n },\n },\n errorTimestamp: new Date(),\n };\n }\n }\n\n // Support both legacy ('step-finish') and VNext ('workflow-step-finish') formats\n if (record.type === 'step-finish' || record.type === 'workflow-step-finish') {\n newState = {\n ...newState,\n payload: {\n ...newState.payload,\n currentStep: null,\n },\n };\n }\n\n // Support both legacy ('finish') and VNext ('workflow-finish') formats\n if (record.type === 'finish' || record.type === 'workflow-finish') {\n // Don't override error states - if we're already in error phase, stay there\n if (newState.phase === 'error' || newState.status === 'failed') {\n newState = {\n ...newState,\n // Keep existing status, phase, error, failedStep\n completedAt: new Date(),\n };\n } else {\n // Normal completion flow\n newState = {\n ...newState,\n status: record.payload.status || 'completed',\n phase: 'completed',\n payload: {\n ...newState.payload,\n currentStep: null,\n workflowState: {\n ...newState.payload.workflowState,\n status: record.payload.status || 'completed',\n },\n },\n completedAt: new Date(),\n };\n }\n }\n\n if (record.type === 'error') {\n const errorStr = normalizeError(record.payload.error);\n newState = {\n ...newState,\n status: 'failed',\n error: errorStr,\n phase: 'error',\n payload: {\n ...newState.payload,\n workflowState: {\n ...newState.payload.workflowState,\n status: 'failed',\n },\n },\n errorTimestamp: new Date(),\n };\n }\n\n return { newState };\n};\n\n// Shared localStorage helpers for template installation state\nconst saveTemplateStateToLocalStorage = (runId: string, state: any) => {\n try {\n localStorage.setItem(\n `template-install-${runId}`,\n JSON.stringify({\n state,\n timestamp: Date.now(),\n }),\n );\n } catch (error) {\n console.warn('Failed to save template state to localStorage:', error);\n }\n};\n\n// Shared helper for processing template installation streams (streamlined)\nconst useTemplateStreamProcessor = (workflowInfo?: any, runId?: string) => {\n const [streamResult, setStreamResult] = useState<any>({});\n const [isStreaming, setIsStreaming] = useState(false);\n\n const processStream = async (stream: any, initialRunId?: string) => {\n setIsStreaming(true);\n setStreamResult({});\n\n if (!stream) throw new Error('No stream returned');\n\n const reader = stream.getReader();\n\n // Initialize minimal state - don't set immediately, let events drive the state\n let currentState: any = {\n runId: initialRunId || runId,\n eventTimestamp: new Date().toISOString(),\n phase: 'running',\n payload: {\n workflowState: {\n steps: {},\n },\n currentStep: null,\n },\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n const { newState } = processTemplateInstallRecord(value, currentState, workflowInfo);\n\n currentState = newState;\n setStreamResult(newState);\n\n // Save to localStorage for refresh recovery (same as watch)\n if (value.runId || initialRunId || runId) {\n const effectiveRunId = value.runId || initialRunId || runId;\n saveTemplateStateToLocalStorage(effectiveRunId, newState);\n }\n }\n } catch (error) {\n console.error('💥 [processStream] Error processing template installation stream:', error);\n\n // Use the helper for error handling too\n const { newState } = processTemplateInstallRecord(\n { type: 'error', payload: { error: error instanceof Error ? error.message : 'Unknown error' } },\n currentState,\n workflowInfo,\n );\n\n setStreamResult(newState);\n } finally {\n setIsStreaming(false);\n reader.releaseLock();\n }\n };\n\n return {\n streamResult,\n isStreaming,\n processStream,\n };\n};\n\nexport const useStreamTemplateInstall = ({\n workflowInfo,\n queryOptions,\n}: {\n workflowInfo?: any;\n queryOptions?: { streamInstall?: MastraMutationOptions<void, StreamTemplateInstallVariables> };\n} = {}) => {\n const client = useMastraClient();\n const { streamResult, isStreaming, processStream } = useTemplateStreamProcessor(workflowInfo);\n\n const streamInstall = useMutation({\n mutationFn: async ({ inputData, selectedModel, runId }: StreamTemplateInstallVariables) => {\n const maxRetries = 3;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n const template = client.getAgentBuilderAction('merge-template');\n const requestContext = new RequestContext();\n requestContext.set('selectedModel', selectedModel);\n const stream = await template.stream({ inputData, requestContext }, runId);\n await processStream(stream, runId);\n\n // If we get here, the stream completed successfully\n return;\n } catch (error: any) {\n console.error(`💥 [streamInstall] Attempt ${attempt} failed:`, error);\n const isNetworkError =\n error?.message?.includes('Failed to fetch') ||\n error?.message?.includes('NetworkError') ||\n error?.message?.includes('network error') ||\n error?.message?.includes('fetch') ||\n error?.code === 'NETWORK_ERROR' ||\n error?.name === 'TypeError';\n\n console.warn(`Stream attempt ${attempt}/${maxRetries} failed:`, error);\n\n if (isNetworkError) {\n // For stream network errors, provide helpful message since switching context is complex\n const errorMessage = runId\n ? `Network error during template installation (likely hot reload). Please refresh the page to resume from where you left off using runId: ${runId}`\n : 'Network error during template installation (likely hot reload). Please try again.';\n\n console.error('🔌 Stream network error:', errorMessage);\n throw new Error(errorMessage);\n }\n\n // If it's not a network error or we've exhausted retries, throw\n console.error('❌ [streamInstall] Non-network error or max retries reached, throwing:', error);\n throw error;\n }\n }\n },\n ...queryOptions?.streamInstall,\n });\n\n return {\n streamInstall,\n streamResult,\n isStreaming,\n };\n};\n\n/**\n * Hook for observing template installation with full replay capability.\n * Uses observeStream() which replays cached execution from beginning, then continues live.\n */\nexport const useObserveStreamTemplateInstall = ({\n workflowInfo,\n queryOptions,\n}: {\n workflowInfo?: any;\n queryOptions?: { observeInstall?: MastraMutationOptions<void, { runId: string }> };\n} = {}) => {\n const client = useMastraClient();\n const { streamResult, isStreaming, processStream } = useTemplateStreamProcessor(workflowInfo);\n\n const observeInstall = useMutation({\n mutationFn: async ({ runId }: { runId: string }) => {\n const maxRetries = 3;\n const retryDelay = 2000; // 2 seconds\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n // Initialize state - but observeStream will replay full history\n // so we don't need to rely on localStorage as fallback\n const template = client.getAgentBuilderAction('merge-template');\n\n // Use observeStream to get full replay + live updates\n const stream = await template.observeStream({ runId });\n await processStream(stream, runId);\n\n // If we get here, the observe stream completed successfully\n return;\n } catch (error: any) {\n console.error(`💥 [observeInstall] Attempt ${attempt} failed:`, error);\n const isNetworkError =\n error?.message?.includes('Failed to fetch') ||\n error?.message?.includes('NetworkError') ||\n error?.message?.includes('network error') ||\n error?.message?.includes('fetch') ||\n error?.code === 'NETWORK_ERROR' ||\n error?.name === 'TypeError';\n\n console.warn(`ObserveStream attempt ${attempt}/${maxRetries} failed:`, error);\n\n if (isNetworkError && attempt < maxRetries) {\n console.info(\n `🔄 ObserveStream network error detected (likely hot reload), retrying in ${retryDelay}ms... (attempt ${attempt + 1}/${maxRetries})`,\n );\n await new Promise(resolve => setTimeout(resolve, retryDelay));\n continue; // Retry\n }\n\n // If it's not a network error or we've exhausted retries, throw\n console.error('❌ [observeInstall] Non-network error or max retries reached, throwing:', error);\n throw error;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,KACxC,OAAO,SAAS,SAAS,OAAO,KAChC,OAAO,SAAS,mBAChB,OAAO,SAAS;KAElB,QAAQ,KAAK,yBAAyB,QAAQ,GAAG,WAAW,WAAW,KAAK;KAE5E,IAAI,kBAAkB,UAAU,YAAY;MAC1C,QAAQ,KACN,4EAA4E,WAAW,iBAAiB,UAAU,EAAE,GAAG,WAAW,EACpI;MACA,MAAM,IAAI,SAAQ,YAAW,WAAW,SAAS,UAAU,CAAC;MAC5D;KACF;KAGA,QAAQ,MAAM,0EAA0E,KAAK;KAC7F,MAAM;IACR;GAEJ;GACA,GAAG,cAAc;EACnB,CAGe;EACb;EACA;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/hooks/templates/use-templates.ts"],"sourcesContent":["import type { MastraClient, TemplateInstallationRequest } from '@mastra/client-js';\nimport { RequestContext } from '@mastra/core/request-context';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery, useMutation } from '@tanstack/react-query';\nimport { useState } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions, MastraQueryOptions } from '../shared/query-options';\n\nexport interface Template {\n slug: string;\n title: string;\n description: string;\n longDescription: string;\n githubUrl: string;\n tags: string[];\n imageURL?: string;\n codeExample?: string;\n agents?: string[];\n tools?: string[];\n workflows?: string[];\n mcp?: string[];\n networks?: string[];\n videoURL?: string;\n useCase: string;\n supportedProviders: string[];\n}\n\nasync function getMastraTemplateRepos(): Promise<{ templates: Template[]; tags: string[]; providers: string[] }> {\n const response = await fetch('https://mastra.ai/api/templates.json');\n if (!response.ok) {\n throw new Error(`Failed to fetch templates: ${response.statusText}`);\n }\n const templates = await response.json();\n const allTemplates = [\n {\n title: 'Weather Agent',\n slug: 'weather-agent',\n githubUrl: 'https://github.com/mastra-ai/weather-agent',\n description: 'Get weather information of any city.',\n longDescription: 'One Agent, one Workflow and one Tool to bring you the weather in your city.',\n imageURL: '',\n tags: ['Agent', 'Workflow', 'Tool'],\n useCase: '',\n supportedProviders: ['openai', 'anthropic', 'google', 'groq'],\n agents: ['weatherAgent'],\n tools: ['weatherTool'],\n workflows: ['weatherWorkflow'],\n },\n ...templates,\n ];\n\n const allTags = Array.from(new Set(allTemplates.flatMap(t => t.tags)));\n const allProviders = Array.from(new Set(allTemplates.flatMap(t => t.supportedProviders)));\n\n return {\n templates: allTemplates,\n tags: allTags,\n providers: allProviders,\n };\n}\n\nasync function getTemplateRepoByRepoName({ repo, owner }: { repo: string; owner: string }): Promise<Template> {\n const response = await fetch(`https://api.github.com/repos/${owner}/${repo}`);\n if (!response.ok) {\n throw new Error(`Failed to fetch template: ${response.statusText}`);\n }\n const repoInfo = await response.json();\n if (!repoInfo.is_template) {\n throw new Error('Repo is not a template, please update the repo settings to make it a template');\n }\n\n return {\n title: repoInfo.name,\n slug: repoInfo.name,\n description: repoInfo.description ?? '',\n imageURL: '',\n tags: [],\n useCase: '',\n longDescription: repoInfo.description ?? '',\n githubUrl: repoInfo.html_url,\n supportedProviders: [],\n };\n}\n\nasync function getTemplateRepo({ repoOrSlug, owner }: { repoOrSlug: string; owner: string }): Promise<Template> {\n const { templates } = await getMastraTemplateRepos();\n const template = templates.find(t => t.slug === repoOrSlug);\n\n if (!template) {\n if (owner === 'mastra-ai' && repoOrSlug.startsWith('template-')) {\n const templateRepo = templates.find(template => `template-${template.slug}` === repoOrSlug);\n if (templateRepo) {\n return templateRepo;\n }\n }\n\n const templateRepo = await getTemplateRepoByRepoName({ repo: repoOrSlug, owner });\n\n if (templateRepo) {\n return templateRepo;\n }\n\n throw new Error(`Template ${repoOrSlug} not found`);\n }\n\n return template;\n}\n\nasync function getTemplateRepoEnvVars({\n repo,\n owner,\n branch,\n}: {\n repo: string;\n owner: string;\n branch: string;\n}): Promise<Record<string, string>> {\n const envUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${branch}/.env.example`;\n const envResponse = await fetch(envUrl);\n\n if (envResponse.ok) {\n const envContent = await envResponse.text();\n const envVars = envContent.split('\\n').reduce(\n (acc, line) => {\n if (!line || line.startsWith('#')) return acc; // Skip empty lines and comments\n\n const [key, value] = line.split('=');\n\n if (key) {\n acc[key] = value?.split('')?.every(item => item === '*') ? '' : value?.replaceAll('\"', '');\n }\n return acc;\n },\n {} as Record<string, string>,\n );\n\n return envVars;\n }\n\n return {};\n}\n\ntype MastraTemplateRepos = Awaited<ReturnType<typeof getMastraTemplateRepos>>;\ntype TemplateRepo = Awaited<ReturnType<typeof getTemplateRepo>>;\ntype TemplateRepoEnvVars = Awaited<ReturnType<typeof getTemplateRepoEnvVars>>;\ntype AgentBuilderWorkflowDetails = Awaited<ReturnType<ReturnType<MastraClient['getAgentBuilderAction']>['details']>>;\ntype TemplateInstallRun = Awaited<ReturnType<ReturnType<MastraClient['getAgentBuilderAction']>['createRun']>>;\ntype TemplateInstallRunById = Awaited<ReturnType<ReturnType<MastraClient['getAgentBuilderAction']>['runById']>>;\ntype StreamTemplateInstallVariables = {\n inputData: TemplateInstallationRequest;\n selectedModel: { provider: string; modelId: string };\n runId: string;\n};\n\nexport const useMastraTemplates = <TData = MastraTemplateRepos>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<MastraTemplateRepos, TData> } = {}): UseQueryResult<TData, Error> => {\n return useQuery<MastraTemplateRepos, Error, TData>({\n queryKey: ['mastra-templates'],\n queryFn: getMastraTemplateRepos,\n ...queryOptions,\n });\n};\n\nexport const useTemplateRepo = <TData = TemplateRepo>({\n repoOrSlug,\n owner,\n queryOptions,\n}: {\n repoOrSlug: string;\n owner: string;\n queryOptions?: MastraQueryOptions<TemplateRepo, TData>;\n}): UseQueryResult<TData, Error> => {\n return useQuery<TemplateRepo, Error, TData>({\n queryKey: ['template-repo', repoOrSlug, owner],\n queryFn: () => getTemplateRepo({ repoOrSlug, owner }),\n ...queryOptions,\n });\n};\n\nexport const useTemplateRepoEnvVars = <TData = TemplateRepoEnvVars>({\n repo,\n owner,\n branch,\n queryOptions,\n}: {\n repo: string;\n owner: string;\n branch: string;\n queryOptions?: MastraQueryOptions<TemplateRepoEnvVars, TData>;\n}): UseQueryResult<TData, Error> => {\n return useQuery<TemplateRepoEnvVars, Error, TData>({\n queryKey: ['template-repo-env-vars', repo, owner, branch],\n queryFn: () => getTemplateRepoEnvVars({ repo, owner, branch }),\n ...queryOptions,\n });\n};\n\nexport const useAgentBuilderWorkflow = <TData = AgentBuilderWorkflowDetails>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<AgentBuilderWorkflowDetails, TData> } = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n return useQuery<AgentBuilderWorkflowDetails, Error, TData>({\n queryKey: ['agent-builder-workflow'],\n queryFn: async () => {\n return await client.getAgentBuilderAction('merge-template').details();\n },\n ...queryOptions,\n });\n};\n\nexport const useCreateTemplateInstallRun = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<TemplateInstallRun, { runId?: string }> } = {}) => {\n const client = useMastraClient();\n return useMutation({\n mutationFn: async ({ runId }: { runId?: string }) => {\n return await client.getAgentBuilderAction('merge-template').createRun({ runId });\n },\n ...queryOptions,\n });\n};\n\nexport const useGetTemplateInstallRun = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<TemplateInstallRunById, { runId: string }> } = {}) => {\n const client = useMastraClient();\n return useMutation({\n mutationFn: async ({ runId }: { runId: string }) => {\n return await client.getAgentBuilderAction('merge-template').runById(runId);\n },\n ...queryOptions,\n });\n};\n\nconst normalizeError = (error: unknown): string => {\n if (typeof error === 'string') return error;\n if (error == null) return 'Unknown error';\n if (error instanceof Error)\n return typeof error.message === 'string' && error.message.length > 0 ? error.message : 'Unknown error';\n if (typeof error === 'object') {\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n }\n return String(error);\n};\n\n// Helper function to process template installation records (like workflows' sanitizeWorkflowWatchResult)\nconst processTemplateInstallRecord = (\n record: { type: string; payload: any; runId?: string; eventTimestamp?: string },\n currentState: any,\n workflowInfo?: any,\n): { newState: any } => {\n let newState = { ...currentState };\n\n // Initialize steps if not present or empty\n const hasSteps =\n newState.payload?.workflowState?.steps && Object.keys(newState.payload.workflowState.steps).length > 0;\n if (!hasSteps && workflowInfo?.allSteps) {\n newState.payload = {\n ...newState.payload,\n workflowState: {\n ...newState.payload?.workflowState,\n steps: Object.keys(workflowInfo.allSteps).reduce((acc, stepId) => {\n acc[stepId] = {\n id: stepId,\n description: workflowInfo.allSteps[stepId].description,\n status: 'pending',\n };\n return acc;\n }, {} as any),\n },\n };\n }\n\n // Handle different event types\n // Support both legacy ('start') and VNext ('workflow-start') formats\n if (record.type === 'start' || record.type === 'workflow-start') {\n // Pre-populate all workflow steps from workflowInfo if available\n const initialSteps: any = {};\n if (workflowInfo?.allSteps) {\n Object.entries(workflowInfo.allSteps).forEach(([stepId, stepData]: [string, any]) => {\n initialSteps[stepId] = {\n id: stepData.id,\n description: stepData.description,\n status: 'pending',\n };\n });\n }\n\n const runId = record.runId || record.payload?.runId;\n\n newState = {\n ...newState,\n runId,\n eventTimestamp: new Date().toISOString(),\n status: 'running',\n phase: 'initializing',\n payload: {\n workflowState: {\n status: 'running',\n steps: initialSteps,\n },\n currentStep: null,\n },\n };\n }\n\n // Support both legacy ('step-start') and VNext ('workflow-step-start') formats\n if (record.type === 'step-start' || record.type === 'workflow-step-start') {\n const stepId = record.payload.id;\n newState = {\n ...newState,\n phase: 'processing',\n payload: {\n ...newState.payload,\n currentStep: {\n id: stepId,\n status: 'running',\n startTime: new Date(),\n ...record.payload,\n },\n workflowState: {\n ...newState.payload.workflowState,\n steps: {\n ...newState.payload.workflowState.steps,\n [stepId]: {\n ...newState.payload.workflowState.steps[stepId],\n status: 'running',\n startTime: new Date(),\n ...record.payload,\n },\n },\n },\n },\n };\n }\n\n // Support both legacy ('step-result') and VNext ('workflow-step-result') formats\n if (record.type === 'step-result' || record.type === 'workflow-step-result') {\n const stepId = record.payload.id;\n const status = record.payload.status;\n const hasError = record.payload.error;\n newState = {\n ...newState,\n payload: {\n ...newState.payload,\n currentStep: {\n ...newState.payload.currentStep,\n status: record.payload.status,\n output: record.payload.output,\n error: record.payload.error,\n endTime: new Date(),\n },\n workflowState: {\n ...newState.payload.workflowState,\n steps: {\n ...newState.payload.workflowState.steps,\n [stepId]: {\n ...newState.payload.workflowState.steps[stepId],\n status: record.payload.status,\n output: record.payload.output,\n error: record.payload.error,\n endTime: new Date(),\n },\n },\n },\n },\n };\n\n // If this step failed, also set workflow-level error state\n if (status === 'failed' && hasError) {\n const errorString = normalizeError(hasError);\n newState = {\n ...newState,\n status: 'failed',\n error: errorString,\n phase: 'error',\n failedStep: {\n id: stepId,\n error: errorString,\n description: record.payload.description || stepId,\n },\n payload: {\n ...newState.payload,\n workflowState: {\n ...newState.payload.workflowState,\n status: 'failed',\n },\n },\n errorTimestamp: new Date(),\n };\n }\n }\n\n // Support both legacy ('step-finish') and VNext ('workflow-step-finish') formats\n if (record.type === 'step-finish' || record.type === 'workflow-step-finish') {\n newState = {\n ...newState,\n payload: {\n ...newState.payload,\n currentStep: null,\n },\n };\n }\n\n // Support both legacy ('finish') and VNext ('workflow-finish') formats\n if (record.type === 'finish' || record.type === 'workflow-finish') {\n // Don't override error states - if we're already in error phase, stay there\n if (newState.phase === 'error' || newState.status === 'failed') {\n newState = {\n ...newState,\n // Keep existing status, phase, error, failedStep\n completedAt: new Date(),\n };\n } else {\n // Normal completion flow\n newState = {\n ...newState,\n status: record.payload.status || 'completed',\n phase: 'completed',\n payload: {\n ...newState.payload,\n currentStep: null,\n workflowState: {\n ...newState.payload.workflowState,\n status: record.payload.status || 'completed',\n },\n },\n completedAt: new Date(),\n };\n }\n }\n\n if (record.type === 'error') {\n const errorStr = normalizeError(record.payload.error);\n newState = {\n ...newState,\n status: 'failed',\n error: errorStr,\n phase: 'error',\n payload: {\n ...newState.payload,\n workflowState: {\n ...newState.payload.workflowState,\n status: 'failed',\n },\n },\n errorTimestamp: new Date(),\n };\n }\n\n return { newState };\n};\n\n// Shared localStorage helpers for template installation state\nconst saveTemplateStateToLocalStorage = (runId: string, state: any) => {\n try {\n localStorage.setItem(\n `template-install-${runId}`,\n JSON.stringify({\n state,\n timestamp: Date.now(),\n }),\n );\n } catch (error) {\n console.warn('Failed to save template state to localStorage:', error);\n }\n};\n\n// Shared helper for processing template installation streams (streamlined)\nconst useTemplateStreamProcessor = (workflowInfo?: any, runId?: string) => {\n const [streamResult, setStreamResult] = useState<any>({});\n const [isStreaming, setIsStreaming] = useState(false);\n\n const processStream = async (stream: any, initialRunId?: string) => {\n setIsStreaming(true);\n setStreamResult({});\n\n if (!stream) throw new Error('No stream returned');\n\n const reader = stream.getReader();\n\n // Initialize minimal state - don't set immediately, let events drive the state\n let currentState: any = {\n runId: initialRunId || runId,\n eventTimestamp: new Date().toISOString(),\n phase: 'running',\n payload: {\n workflowState: {\n steps: {},\n },\n currentStep: null,\n },\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n const { newState } = processTemplateInstallRecord(value, currentState, workflowInfo);\n\n currentState = newState;\n setStreamResult(newState);\n\n // Save to localStorage for refresh recovery (same as watch)\n if (value.runId || initialRunId || runId) {\n const effectiveRunId = value.runId || initialRunId || runId;\n saveTemplateStateToLocalStorage(effectiveRunId, newState);\n }\n }\n } catch (error) {\n console.error('💥 [processStream] Error processing template installation stream:', error);\n\n // Use the helper for error handling too\n const { newState } = processTemplateInstallRecord(\n { type: 'error', payload: { error: error instanceof Error ? error.message : 'Unknown error' } },\n currentState,\n workflowInfo,\n );\n\n setStreamResult(newState);\n } finally {\n setIsStreaming(false);\n reader.releaseLock();\n }\n };\n\n return {\n streamResult,\n isStreaming,\n processStream,\n };\n};\n\nexport const useStreamTemplateInstall = ({\n workflowInfo,\n queryOptions,\n}: {\n workflowInfo?: any;\n queryOptions?: { streamInstall?: MastraMutationOptions<void, StreamTemplateInstallVariables> };\n} = {}) => {\n const client = useMastraClient();\n const { streamResult, isStreaming, processStream } = useTemplateStreamProcessor(workflowInfo);\n\n const streamInstall = useMutation({\n mutationFn: async ({ inputData, selectedModel, runId }: StreamTemplateInstallVariables) => {\n const maxRetries = 3;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n const template = client.getAgentBuilderAction('merge-template');\n const requestContext = new RequestContext();\n requestContext.set('selectedModel', selectedModel);\n const stream = await template.stream({ inputData, requestContext }, runId);\n await processStream(stream, runId);\n\n // If we get here, the stream completed successfully\n return;\n } catch (error: any) {\n console.error(`💥 [streamInstall] Attempt ${attempt} failed:`, error);\n const isNetworkError =\n error?.message?.includes('Failed to fetch') ||\n error?.message?.includes('NetworkError') ||\n error?.message?.includes('network error') ||\n error?.message?.includes('fetch') ||\n error?.code === 'NETWORK_ERROR' ||\n error?.name === 'TypeError';\n\n console.warn(`Stream attempt ${attempt}/${maxRetries} failed:`, error);\n\n if (isNetworkError) {\n // For stream network errors, provide helpful message since switching context is complex\n const errorMessage = runId\n ? `Network error during template installation (likely hot reload). Please refresh the page to resume from where you left off using runId: ${runId}`\n : 'Network error during template installation (likely hot reload). Please try again.';\n\n console.error('🔌 Stream network error:', errorMessage);\n throw new Error(errorMessage);\n }\n\n // If it's not a network error or we've exhausted retries, throw\n console.error('❌ [streamInstall] Non-network error or max retries reached, throwing:', error);\n throw error;\n }\n }\n },\n ...queryOptions?.streamInstall,\n });\n\n return {\n streamInstall,\n streamResult,\n isStreaming,\n };\n};\n\n/**\n * Hook for observing template installation with full replay capability.\n * Uses observeStream() which replays cached execution from beginning, then continues live.\n */\nexport const useObserveStreamTemplateInstall = ({\n workflowInfo,\n queryOptions,\n}: {\n workflowInfo?: any;\n queryOptions?: { observeInstall?: MastraMutationOptions<void, { runId: string }> };\n} = {}) => {\n const client = useMastraClient();\n const { streamResult, isStreaming, processStream } = useTemplateStreamProcessor(workflowInfo);\n\n const observeInstall = useMutation({\n mutationFn: async ({ runId }: { runId: string }) => {\n const maxRetries = 3;\n const retryDelay = 2000; // 2 seconds\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n // Initialize state - but observeStream will replay full history\n // so we don't need to rely on localStorage as fallback\n const template = client.getAgentBuilderAction('merge-template');\n\n // Use observeStream to get full replay + live updates\n const stream = await template.observeStream({ runId });\n await processStream(stream, runId);\n\n // If we get here, the observe stream completed successfully\n return;\n } catch (error: any) {\n console.error(`💥 [observeInstall] Attempt ${attempt} failed:`, error);\n const isNetworkError =\n error?.message?.includes('Failed to fetch') ||\n error?.message?.includes('NetworkError') ||\n error?.message?.includes('network error') ||\n error?.message?.includes('fetch') ||\n error?.code === 'NETWORK_ERROR' ||\n error?.name === 'TypeError';\n\n console.warn(`ObserveStream attempt ${attempt}/${maxRetries} failed:`, error);\n\n if (isNetworkError && attempt < maxRetries) {\n console.info(\n `🔄 ObserveStream network error detected (likely hot reload), retrying in ${retryDelay}ms... (attempt ${attempt + 1}/${maxRetries})`,\n );\n await new Promise(resolve => setTimeout(resolve, retryDelay));\n continue; // Retry\n }\n\n // If it's not a network error or we've exhausted retries, throw\n console.error('❌ [observeInstall] Non-network error or max retries reached, throwing:', error);\n throw error;\n }\n }\n },\n ...queryOptions?.observeInstall,\n });\n\n return {\n observeInstall,\n streamResult,\n isStreaming,\n };\n};\n"],"mappings":";;;;;AA2BA,eAAe,yBAAkG;CAC/G,MAAM,WAAW,MAAM,MAAM,sCAAsC;CACnE,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,8BAA8B,SAAS,YAAY;CAGrE,MAAM,eAAe,CACnB;EACE,OAAO;EACP,MAAM;EACN,WAAW;EACX,aAAa;EACb,iBAAiB;EACjB,UAAU;EACV,MAAM;GAAC;GAAS;GAAY;EAAM;EAClC,SAAS;EACT,oBAAoB;GAAC;GAAU;GAAa;GAAU;EAAM;EAC5D,QAAQ,CAAC,cAAc;EACvB,OAAO,CAAC,aAAa;EACrB,WAAW,CAAC,iBAAiB;CAC/B,GACA,GAAG,MAhBmB,SAAS,KAAK,CAiBtC;CAKA,OAAO;EACL,WAAW;EACX,MALc,MAAM,KAAK,IAAI,IAA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a;IACnB,MAAM,aAAa;IAEnB,KAAK,IAAI,UAAU,GAAG,WAAW,YAAY,WAC3C,IAAI;KAMF,MAAM,SAAS,MAHE,OAAO,sBAAsB,gBAGlB,CAAC,CAAC,cAAc,EAAE,MAAM,CAAC;KACrD,MAAM,cAAc,QAAQ,KAAK;KAGjC;IACF,SAAS,OAAY;KACnB,QAAQ,MAAM,+BAA+B,QAAQ,WAAW,KAAK;KACrE,MAAM,iBACJ,OAAO,SAAS,SAAS,iBAAiB,KAC1C,OAAO,SAAS,SAAS,cAAc,KACvC,OAAO,SAAS,SAAS,eAAe,KACxC,OAAO,SAAS,SAAS,OAAO,KAChC,OAAO,SAAS,mBAChB,OAAO,SAAS;KAElB,QAAQ,KAAK,yBAAyB,QAAQ,GAAG,WAAW,WAAW,KAAK;KAE5E,IAAI,kBAAkB,UAAU,YAAY;MAC1C,QAAQ,KACN,4EAA4E,WAAW,iBAAiB,UAAU,EAAE,GAAG,WAAW,EACpI;MACA,MAAM,IAAI,SAAQ,YAAW,WAAW,SAAS,UAAU,CAAC;MAC5D;KACF;KAGA,QAAQ,MAAM,0EAA0E,KAAK;KAC7F,MAAM;IACR;GAEJ;GACA,GAAG,cAAc;EACnB,CAGe;EACb;EACA;CACF;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/hooks/templates/use-templates.ts"],"sourcesContent":["import type { MastraClient, TemplateInstallationRequest } from '@mastra/client-js';\nimport { RequestContext } from '@mastra/core/request-context';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery, useMutation } from '@tanstack/react-query';\nimport { useState } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions, MastraQueryOptions } from '../shared/query-options';\n\nexport interface Template {\n slug: string;\n title: string;\n description: string;\n longDescription: string;\n githubUrl: string;\n tags: string[];\n imageURL?: string;\n codeExample?: string;\n agents?: string[];\n tools?: string[];\n workflows?: string[];\n mcp?: string[];\n networks?: string[];\n videoURL?: string;\n useCase: string;\n supportedProviders: string[];\n}\n\nasync function getMastraTemplateRepos(): Promise<{ templates: Template[]; tags: string[]; providers: string[] }> {\n const response = await fetch('https://mastra.ai/api/templates.json');\n if (!response.ok) {\n throw new Error(`Failed to fetch templates: ${response.statusText}`);\n }\n const templates = await response.json();\n const allTemplates = [\n {\n title: 'Weather Agent',\n slug: 'weather-agent',\n githubUrl: 'https://github.com/mastra-ai/weather-agent',\n description: 'Get weather information of any city.',\n longDescription: 'One Agent, one Workflow and one Tool to bring you the weather in your city.',\n imageURL: '',\n tags: ['Agent', 'Workflow', 'Tool'],\n useCase: '',\n supportedProviders: ['openai', 'anthropic', 'google', 'groq'],\n agents: ['weatherAgent'],\n tools: ['weatherTool'],\n workflows: ['weatherWorkflow'],\n },\n ...templates,\n ];\n\n const allTags = Array.from(new Set(allTemplates.flatMap(t => t.tags)));\n const allProviders = Array.from(new Set(allTemplates.flatMap(t => t.supportedProviders)));\n\n return {\n templates: allTemplates,\n tags: allTags,\n providers: allProviders,\n };\n}\n\nasync function getTemplateRepoByRepoName({ repo, owner }: { repo: string; owner: string }): Promise<Template> {\n const response = await fetch(`https://api.github.com/repos/${owner}/${repo}`);\n if (!response.ok) {\n throw new Error(`Failed to fetch template: ${response.statusText}`);\n }\n const repoInfo = await response.json();\n if (!repoInfo.is_template) {\n throw new Error('Repo is not a template, please update the repo settings to make it a template');\n }\n\n return {\n title: repoInfo.name,\n slug: repoInfo.name,\n description: repoInfo.description ?? '',\n imageURL: '',\n tags: [],\n useCase: '',\n longDescription: repoInfo.description ?? '',\n githubUrl: repoInfo.html_url,\n supportedProviders: [],\n };\n}\n\nasync function getTemplateRepo({ repoOrSlug, owner }: { repoOrSlug: string; owner: string }): Promise<Template> {\n const { templates } = await getMastraTemplateRepos();\n const template = templates.find(t => t.slug === repoOrSlug);\n\n if (!template) {\n if (owner === 'mastra-ai' && repoOrSlug.startsWith('template-')) {\n const templateRepo = templates.find(template => `template-${template.slug}` === repoOrSlug);\n if (templateRepo) {\n return templateRepo;\n }\n }\n\n const templateRepo = await getTemplateRepoByRepoName({ repo: repoOrSlug, owner });\n\n if (templateRepo) {\n return templateRepo;\n }\n\n throw new Error(`Template ${repoOrSlug} not found`);\n }\n\n return template;\n}\n\nasync function getTemplateRepoEnvVars({\n repo,\n owner,\n branch,\n}: {\n repo: string;\n owner: string;\n branch: string;\n}): Promise<Record<string, string>> {\n const envUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${branch}/.env.example`;\n const envResponse = await fetch(envUrl);\n\n if (envResponse.ok) {\n const envContent = await envResponse.text();\n const envVars = envContent.split('\\n').reduce<Record<string, string>>((acc, line) => {\n if (!line || line.startsWith('#')) return acc; // Skip empty lines and comments\n\n const [key, value] = line.split('=');\n\n if (key) {\n acc[key] = value?.split('')?.every(item => item === '*') ? '' : value?.replaceAll('\"', '');\n }\n return acc;\n }, {});\n\n return envVars;\n }\n\n return {};\n}\n\ntype MastraTemplateRepos = Awaited<ReturnType<typeof getMastraTemplateRepos>>;\ntype TemplateRepo = Awaited<ReturnType<typeof getTemplateRepo>>;\ntype TemplateRepoEnvVars = Awaited<ReturnType<typeof getTemplateRepoEnvVars>>;\ntype AgentBuilderWorkflowDetails = Awaited<ReturnType<ReturnType<MastraClient['getAgentBuilderAction']>['details']>>;\ntype TemplateInstallRun = Awaited<ReturnType<ReturnType<MastraClient['getAgentBuilderAction']>['createRun']>>;\ntype TemplateInstallRunById = Awaited<ReturnType<ReturnType<MastraClient['getAgentBuilderAction']>['runById']>>;\ntype StreamTemplateInstallVariables = {\n inputData: TemplateInstallationRequest;\n selectedModel: { provider: string; modelId: string };\n runId: string;\n};\n\nexport const useMastraTemplates = <TData = MastraTemplateRepos>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<MastraTemplateRepos, TData> } = {}): UseQueryResult<TData, Error> => {\n return useQuery<MastraTemplateRepos, Error, TData>({\n queryKey: ['mastra-templates'],\n queryFn: getMastraTemplateRepos,\n ...queryOptions,\n });\n};\n\nexport const useTemplateRepo = <TData = TemplateRepo>({\n repoOrSlug,\n owner,\n queryOptions,\n}: {\n repoOrSlug: string;\n owner: string;\n queryOptions?: MastraQueryOptions<TemplateRepo, TData>;\n}): UseQueryResult<TData, Error> => {\n return useQuery<TemplateRepo, Error, TData>({\n queryKey: ['template-repo', repoOrSlug, owner],\n queryFn: () => getTemplateRepo({ repoOrSlug, owner }),\n ...queryOptions,\n });\n};\n\nexport const useTemplateRepoEnvVars = <TData = TemplateRepoEnvVars>({\n repo,\n owner,\n branch,\n queryOptions,\n}: {\n repo: string;\n owner: string;\n branch: string;\n queryOptions?: MastraQueryOptions<TemplateRepoEnvVars, TData>;\n}): UseQueryResult<TData, Error> => {\n return useQuery<TemplateRepoEnvVars, Error, TData>({\n queryKey: ['template-repo-env-vars', repo, owner, branch],\n queryFn: () => getTemplateRepoEnvVars({ repo, owner, branch }),\n ...queryOptions,\n });\n};\n\nexport const useAgentBuilderWorkflow = <TData = AgentBuilderWorkflowDetails>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<AgentBuilderWorkflowDetails, TData> } = {}): UseQueryResult<TData, Error> => {\n const client = useMastraClient();\n return useQuery<AgentBuilderWorkflowDetails, Error, TData>({\n queryKey: ['agent-builder-workflow'],\n queryFn: async () => {\n return await client.getAgentBuilderAction('merge-template').details();\n },\n ...queryOptions,\n });\n};\n\nexport const useCreateTemplateInstallRun = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<TemplateInstallRun, { runId?: string }> } = {}) => {\n const client = useMastraClient();\n return useMutation({\n mutationFn: async ({ runId }: { runId?: string }) => {\n return await client.getAgentBuilderAction('merge-template').createRun({ runId });\n },\n ...queryOptions,\n });\n};\n\nexport const useGetTemplateInstallRun = ({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<TemplateInstallRunById, { runId: string }> } = {}) => {\n const client = useMastraClient();\n return useMutation({\n mutationFn: async ({ runId }: { runId: string }) => {\n return await client.getAgentBuilderAction('merge-template').runById(runId);\n },\n ...queryOptions,\n });\n};\n\nconst normalizeError = (error: unknown): string => {\n if (typeof error === 'string') return error;\n if (error == null) return 'Unknown error';\n if (error instanceof Error)\n return typeof error.message === 'string' && error.message.length > 0 ? error.message : 'Unknown error';\n if (typeof error === 'object') {\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n }\n return String(error);\n};\n\n// Helper function to process template installation records (like workflows' sanitizeWorkflowWatchResult)\nconst processTemplateInstallRecord = (\n record: { type: string; payload: any; runId?: string; eventTimestamp?: string },\n currentState: any,\n workflowInfo?: any,\n): { newState: any } => {\n let newState = { ...currentState };\n\n // Initialize steps if not present or empty\n const hasSteps =\n newState.payload?.workflowState?.steps && Object.keys(newState.payload.workflowState.steps).length > 0;\n if (!hasSteps && workflowInfo?.allSteps) {\n newState.payload = {\n ...newState.payload,\n workflowState: {\n ...newState.payload?.workflowState,\n steps: Object.keys(workflowInfo.allSteps).reduce<any>((acc, stepId) => {\n acc[stepId] = {\n id: stepId,\n description: workflowInfo.allSteps[stepId].description,\n status: 'pending',\n };\n return acc;\n }, {}),\n },\n };\n }\n\n // Handle different event types\n // Support both legacy ('start') and VNext ('workflow-start') formats\n if (record.type === 'start' || record.type === 'workflow-start') {\n // Pre-populate all workflow steps from workflowInfo if available\n const initialSteps: any = {};\n if (workflowInfo?.allSteps) {\n Object.entries(workflowInfo.allSteps).forEach(([stepId, stepData]: [string, any]) => {\n initialSteps[stepId] = {\n id: stepData.id,\n description: stepData.description,\n status: 'pending',\n };\n });\n }\n\n const runId = record.runId || record.payload?.runId;\n\n newState = {\n ...newState,\n runId,\n eventTimestamp: new Date().toISOString(),\n status: 'running',\n phase: 'initializing',\n payload: {\n workflowState: {\n status: 'running',\n steps: initialSteps,\n },\n currentStep: null,\n },\n };\n }\n\n // Support both legacy ('step-start') and VNext ('workflow-step-start') formats\n if (record.type === 'step-start' || record.type === 'workflow-step-start') {\n const stepId = record.payload.id;\n newState = {\n ...newState,\n phase: 'processing',\n payload: {\n ...newState.payload,\n currentStep: {\n id: stepId,\n status: 'running',\n startTime: new Date(),\n ...record.payload,\n },\n workflowState: {\n ...newState.payload.workflowState,\n steps: {\n ...newState.payload.workflowState.steps,\n [stepId]: {\n ...newState.payload.workflowState.steps[stepId],\n status: 'running',\n startTime: new Date(),\n ...record.payload,\n },\n },\n },\n },\n };\n }\n\n // Support both legacy ('step-result') and VNext ('workflow-step-result') formats\n if (record.type === 'step-result' || record.type === 'workflow-step-result') {\n const stepId = record.payload.id;\n const status = record.payload.status;\n const hasError = record.payload.error;\n newState = {\n ...newState,\n payload: {\n ...newState.payload,\n currentStep: {\n ...newState.payload.currentStep,\n status: record.payload.status,\n output: record.payload.output,\n error: record.payload.error,\n endTime: new Date(),\n },\n workflowState: {\n ...newState.payload.workflowState,\n steps: {\n ...newState.payload.workflowState.steps,\n [stepId]: {\n ...newState.payload.workflowState.steps[stepId],\n status: record.payload.status,\n output: record.payload.output,\n error: record.payload.error,\n endTime: new Date(),\n },\n },\n },\n },\n };\n\n // If this step failed, also set workflow-level error state\n if (status === 'failed' && hasError) {\n const errorString = normalizeError(hasError);\n newState = {\n ...newState,\n status: 'failed',\n error: errorString,\n phase: 'error',\n failedStep: {\n id: stepId,\n error: errorString,\n description: record.payload.description || stepId,\n },\n payload: {\n ...newState.payload,\n workflowState: {\n ...newState.payload.workflowState,\n status: 'failed',\n },\n },\n errorTimestamp: new Date(),\n };\n }\n }\n\n // Support both legacy ('step-finish') and VNext ('workflow-step-finish') formats\n if (record.type === 'step-finish' || record.type === 'workflow-step-finish') {\n newState = {\n ...newState,\n payload: {\n ...newState.payload,\n currentStep: null,\n },\n };\n }\n\n // Support both legacy ('finish') and VNext ('workflow-finish') formats\n if (record.type === 'finish' || record.type === 'workflow-finish') {\n // Don't override error states - if we're already in error phase, stay there\n if (newState.phase === 'error' || newState.status === 'failed') {\n newState = {\n ...newState,\n // Keep existing status, phase, error, failedStep\n completedAt: new Date(),\n };\n } else {\n // Normal completion flow\n newState = {\n ...newState,\n status: record.payload.status || 'completed',\n phase: 'completed',\n payload: {\n ...newState.payload,\n currentStep: null,\n workflowState: {\n ...newState.payload.workflowState,\n status: record.payload.status || 'completed',\n },\n },\n completedAt: new Date(),\n };\n }\n }\n\n if (record.type === 'error') {\n const errorStr = normalizeError(record.payload.error);\n newState = {\n ...newState,\n status: 'failed',\n error: errorStr,\n phase: 'error',\n payload: {\n ...newState.payload,\n workflowState: {\n ...newState.payload.workflowState,\n status: 'failed',\n },\n },\n errorTimestamp: new Date(),\n };\n }\n\n return { newState };\n};\n\n// Shared localStorage helpers for template installation state\nconst saveTemplateStateToLocalStorage = (runId: string, state: any) => {\n try {\n localStorage.setItem(\n `template-install-${runId}`,\n JSON.stringify({\n state,\n timestamp: Date.now(),\n }),\n );\n } catch (error) {\n console.warn('Failed to save template state to localStorage:', error);\n }\n};\n\n// Shared helper for processing template installation streams (streamlined)\nconst useTemplateStreamProcessor = (workflowInfo?: any, runId?: string) => {\n const [streamResult, setStreamResult] = useState<any>({});\n const [isStreaming, setIsStreaming] = useState(false);\n\n const processStream = async (stream: any, initialRunId?: string) => {\n setIsStreaming(true);\n setStreamResult({});\n\n if (!stream) throw new Error('No stream returned');\n\n const reader = stream.getReader();\n\n // Initialize minimal state - don't set immediately, let events drive the state\n let currentState: any = {\n runId: initialRunId || runId,\n eventTimestamp: new Date().toISOString(),\n phase: 'running',\n payload: {\n workflowState: {\n steps: {},\n },\n currentStep: null,\n },\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n const { newState } = processTemplateInstallRecord(value, currentState, workflowInfo);\n\n currentState = newState;\n setStreamResult(newState);\n\n // Save to localStorage for refresh recovery (same as watch)\n if (value.runId || initialRunId || runId) {\n const effectiveRunId = value.runId || initialRunId || runId;\n saveTemplateStateToLocalStorage(effectiveRunId, newState);\n }\n }\n } catch (error) {\n console.error('💥 [processStream] Error processing template installation stream:', error);\n\n // Use the helper for error handling too\n const { newState } = processTemplateInstallRecord(\n { type: 'error', payload: { error: error instanceof Error ? error.message : 'Unknown error' } },\n currentState,\n workflowInfo,\n );\n\n setStreamResult(newState);\n } finally {\n setIsStreaming(false);\n reader.releaseLock();\n }\n };\n\n return {\n streamResult,\n isStreaming,\n processStream,\n };\n};\n\nexport const useStreamTemplateInstall = ({\n workflowInfo,\n queryOptions,\n}: {\n workflowInfo?: any;\n queryOptions?: { streamInstall?: MastraMutationOptions<void, StreamTemplateInstallVariables> };\n} = {}) => {\n const client = useMastraClient();\n const { streamResult, isStreaming, processStream } = useTemplateStreamProcessor(workflowInfo);\n\n const streamInstall = useMutation({\n mutationFn: async ({ inputData, selectedModel, runId }: StreamTemplateInstallVariables) => {\n const maxRetries = 3;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n const template = client.getAgentBuilderAction('merge-template');\n const requestContext = new RequestContext();\n requestContext.set('selectedModel', selectedModel);\n const stream = await template.stream({ inputData, requestContext }, runId);\n await processStream(stream, runId);\n\n // If we get here, the stream completed successfully\n return;\n } catch (error: any) {\n console.error(`💥 [streamInstall] Attempt ${attempt} failed:`, error);\n const isNetworkError =\n error?.message?.includes('Failed to fetch') ||\n error?.message?.includes('NetworkError') ||\n error?.message?.includes('network error') ||\n error?.message?.includes('fetch') ||\n error?.code === 'NETWORK_ERROR' ||\n error?.name === 'TypeError';\n\n console.warn(`Stream attempt ${attempt}/${maxRetries} failed:`, error);\n\n if (isNetworkError) {\n // For stream network errors, provide helpful message since switching context is complex\n const errorMessage = runId\n ? `Network error during template installation (likely hot reload). Please refresh the page to resume from where you left off using runId: ${runId}`\n : 'Network error during template installation (likely hot reload). Please try again.';\n\n console.error('🔌 Stream network error:', errorMessage);\n throw new Error(errorMessage);\n }\n\n // If it's not a network error or we've exhausted retries, throw\n console.error('❌ [streamInstall] Non-network error or max retries reached, throwing:', error);\n throw error;\n }\n }\n },\n ...queryOptions?.streamInstall,\n });\n\n return {\n streamInstall,\n streamResult,\n isStreaming,\n };\n};\n\n/**\n * Hook for observing template installation with full replay capability.\n * Uses observeStream() which replays cached execution from beginning, then continues live.\n */\nexport const useObserveStreamTemplateInstall = ({\n workflowInfo,\n queryOptions,\n}: {\n workflowInfo?: any;\n queryOptions?: { observeInstall?: MastraMutationOptions<void, { runId: string }> };\n} = {}) => {\n const client = useMastraClient();\n const { streamResult, isStreaming, processStream } = useTemplateStreamProcessor(workflowInfo);\n\n const observeInstall = useMutation({\n mutationFn: async ({ runId }: { runId: string }) => {\n const maxRetries = 3;\n const retryDelay = 2000; // 2 seconds\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n // Initialize state - but observeStream will replay full history\n // so we don't need to rely on localStorage as fallback\n const template = client.getAgentBuilderAction('merge-template');\n\n // Use observeStream to get full replay + live updates\n const stream = await template.observeStream({ runId });\n await processStream(stream, runId);\n\n // If we get here, the observe stream completed successfully\n return;\n } catch (error: any) {\n console.error(`💥 [observeInstall] Attempt ${attempt} failed:`, error);\n const isNetworkError =\n error?.message?.includes('Failed to fetch') ||\n error?.message?.includes('NetworkError') ||\n error?.message?.includes('network error') ||\n error?.message?.includes('fetch') ||\n error?.code === 'NETWORK_ERROR' ||\n error?.name === 'TypeError';\n\n console.warn(`ObserveStream attempt ${attempt}/${maxRetries} failed:`, error);\n\n if (isNetworkError && attempt < maxRetries) {\n console.info(\n `🔄 ObserveStream network error detected (likely hot reload), retrying in ${retryDelay}ms... (attempt ${attempt + 1}/${maxRetries})`,\n );\n await new Promise(resolve => setTimeout(resolve, retryDelay));\n continue; // Retry\n }\n\n // If it's not a network error or we've exhausted retries, throw\n console.error('❌ [observeInstall] Non-network error or max retries reached, throwing:', error);\n throw error;\n }\n }\n },\n ...queryOptions?.observeInstall,\n });\n\n return {\n observeInstall,\n streamResult,\n isStreaming,\n };\n};\n"],"mappings":";;;;;AA2BA,eAAe,yBAAkG;CAC/G,MAAM,WAAW,MAAM,MAAM,sCAAsC;CACnE,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,8BAA8B,SAAS,YAAY;CAGrE,MAAM,e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CAAA;KAAE,CAAC,CAAA;CAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;WAG3C,MAAM;WAKhD,CAAC;AAiTF,eAAO,MAAM,wBAAwB,qCAGlC;IACD,YAAY,CAAC,EAAE,GAAG,CAAC;IACnB,YAAY,CAAC,EAAE;QAAE,aAAa,CAAC,EAAE,qBAAqB,CAAC,IAAI,EAAE,8BAA8B,CAAC,CAAA;KAAE,CAAC;CAChG;;;;CAsDA,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,+BAA+B,qCAGzC;IACD,YAAY,CAAC,EAAE,GAAG,CAAC;IACnB,YAAY,CAAC,EAAE;QAAE,cAAc,CAAC,EAAE,qBAAqB,CAAC,IAAI,EAAE;YAAE,KAAK,EAAE,MAAM,CAAA;SAAE,CAAC,CAAA;KAAE,CAAC;CACpF;;eAK0C,MAAM;;;;CAkDhD,CAAC"}
@@ -1,9 +1,9 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_mastra_client_context = require("../../mastra-client-context-DzX3f0RF.cjs");
3
3
  const require_use_in_view = require("../../use-in-view-B6eJO9Zi.cjs");
4
+ const require_map = require("../../map-wjmL1y5O.cjs");
4
5
  const require_query_utils = require("../../query-utils-CcrChYgz.cjs");
5
6
  const require_feedback_refetch_interval = require("../../feedback-refetch-interval-XD5FVc2k.cjs");
6
- const require_map = require("../../map-wjmL1y5O.cjs");
7
7
  let _mastra_client_js = require("@mastra/client-js");
8
8
  let react = require("react");
9
9
  let _tanstack_react_query = require("@tanstack/react-query");
@@ -628,6 +628,110 @@ function useTraceQueryLatest({ query, limit = 25, enabled = true, refetchInterva
628
628
  });
629
629
  }
630
630
  //#endregion
631
+ //#region src/hooks/traces/use-query-spans.ts
632
+ const SPAN_QUERY_PER_PAGE = 25;
633
+ const selectSpans = (data) => data.pages.flatMap((page) => page.spans);
634
+ /** Queries completed spans with cursor pagination and viewport-driven loading. */
635
+ function useQuerySpans({ query, limit = 25, enabled = true, queryOptions }) {
636
+ const client = require_mastra_client_context.useMastraClient();
637
+ const { inView, setRef: setEndOfListElement } = require_use_in_view.useInView();
638
+ const { data, hasNextPage, isFetchingNextPage, fetchNextPage, isLoading, isFetching, isError, error, refetch, isFetchNextPageError } = (0, _tanstack_react_query.useInfiniteQuery)({
639
+ queryKey: [
640
+ "span-query",
641
+ query,
642
+ limit
643
+ ],
644
+ queryFn: query ? ({ pageParam }) => client.querySpans({
645
+ ...query,
646
+ page: pageParam ? {
647
+ limit,
648
+ after: pageParam
649
+ } : { limit }
650
+ }) : _tanstack_react_query.skipToken,
651
+ initialPageParam: void 0,
652
+ getNextPageParam: (lastPage) => lastPage.page.next ?? void 0,
653
+ select: selectSpans,
654
+ retry: false,
655
+ placeholderData: _tanstack_react_query.keepPreviousData,
656
+ enabled,
657
+ ...queryOptions
658
+ });
659
+ (0, react.useEffect)(() => {
660
+ if (enabled && inView && hasNextPage && !isFetching && !isFetchNextPageError) fetchNextPage();
661
+ }, [
662
+ enabled,
663
+ inView,
664
+ hasNextPage,
665
+ isFetching,
666
+ isFetchNextPageError,
667
+ fetchNextPage
668
+ ]);
669
+ return {
670
+ spans: data,
671
+ hasNextPage,
672
+ isFetchingNextPage,
673
+ fetchNextPage: () => void fetchNextPage(),
674
+ setEndOfListElement,
675
+ isLoading,
676
+ isFetching,
677
+ isError,
678
+ error,
679
+ refetch: () => void refetch()
680
+ };
681
+ }
682
+ //#endregion
683
+ //#region src/hooks/traces/use-query-threads.ts
684
+ const THREAD_QUERY_PER_PAGE = 25;
685
+ const selectThreads = (data) => data.pages.flatMap((page) => page.threads);
686
+ /** Queries thread rows with cursor pagination and viewport-driven loading. */
687
+ function useQueryThreads({ query, limit = 25, enabled = true, queryOptions }) {
688
+ const client = require_mastra_client_context.useMastraClient();
689
+ const { inView, setRef: setEndOfListElement } = require_use_in_view.useInView();
690
+ const { data, hasNextPage, isFetchingNextPage, fetchNextPage, isLoading, isFetching, isError, error, refetch, isFetchNextPageError } = (0, _tanstack_react_query.useInfiniteQuery)({
691
+ queryKey: [
692
+ "thread-query",
693
+ query,
694
+ limit
695
+ ],
696
+ queryFn: query ? ({ pageParam }) => client.queryTraceThreads({
697
+ ...query,
698
+ page: pageParam ? {
699
+ limit,
700
+ after: pageParam
701
+ } : { limit }
702
+ }) : _tanstack_react_query.skipToken,
703
+ initialPageParam: void 0,
704
+ getNextPageParam: (lastPage) => lastPage.page.next ?? void 0,
705
+ select: selectThreads,
706
+ retry: false,
707
+ placeholderData: _tanstack_react_query.keepPreviousData,
708
+ enabled,
709
+ ...queryOptions
710
+ });
711
+ (0, react.useEffect)(() => {
712
+ if (enabled && inView && hasNextPage && !isFetching && !isFetchNextPageError) fetchNextPage();
713
+ }, [
714
+ enabled,
715
+ inView,
716
+ hasNextPage,
717
+ isFetching,
718
+ isFetchNextPageError,
719
+ fetchNextPage
720
+ ]);
721
+ return {
722
+ threads: data,
723
+ hasNextPage,
724
+ isFetchingNextPage,
725
+ fetchNextPage: () => void fetchNextPage(),
726
+ setEndOfListElement,
727
+ isLoading,
728
+ isFetching,
729
+ isError,
730
+ error,
731
+ refetch: () => void refetch()
732
+ };
733
+ }
734
+ //#endregion
631
735
  //#region src/hooks/traces/use-trace-usage.ts
632
736
  const INPUT_TOKEN_METRIC = "mastra_model_total_input_tokens";
633
737
  const OUTPUT_TOKEN_METRIC = "mastra_model_total_output_tokens";
@@ -1303,6 +1407,8 @@ function useTraceColumnPreferencesStorageKey() {
1303
1407
  //#endregion
1304
1408
  exports.DISCOVERY_STALE_TIME = DISCOVERY_STALE_TIME;
1305
1409
  exports.ROOT_ENTITY_TYPES = ROOT_ENTITY_TYPES;
1410
+ exports.SPAN_QUERY_PER_PAGE = SPAN_QUERY_PER_PAGE;
1411
+ exports.THREAD_QUERY_PER_PAGE = THREAD_QUERY_PER_PAGE;
1306
1412
  exports.TRACES_PER_PAGE = TRACES_PER_PAGE;
1307
1413
  exports.TRACE_QUERY_DELTA_LIMIT = TRACE_QUERY_DELTA_LIMIT;
1308
1414
  exports.TRACE_QUERY_PER_PAGE = TRACE_QUERY_PER_PAGE;
@@ -1328,6 +1434,8 @@ exports.useDeleteFeedback = useDeleteFeedback;
1328
1434
  exports.useEntityNames = useEntityNames;
1329
1435
  exports.useEnvironments = useEnvironments;
1330
1436
  exports.useFetchTraceSpans = useFetchTraceSpans;
1437
+ exports.useQuerySpans = useQuerySpans;
1438
+ exports.useQueryThreads = useQueryThreads;
1331
1439
  exports.useServiceNames = useServiceNames;
1332
1440
  exports.useSpanDetail = useSpanDetail;
1333
1441
  exports.useSpanFeedback = useSpanFeedback;