@mastra/playground-ui 71.0.0-alpha.7 → 71.0.0-alpha.9
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.
- package/dist/domains/agents/chat/stream-error-message.cjs.js +13 -6
- package/dist/domains/agents/chat/stream-error-message.cjs.js.map +1 -1
- package/dist/domains/agents/chat/stream-error-message.es.js +13 -6
- package/dist/domains/agents/chat/stream-error-message.es.js.map +1 -1
- package/dist/domains/agents/chat/use-chat-send-handler.cjs.js +4 -1
- package/dist/domains/agents/chat/use-chat-send-handler.cjs.js.map +1 -1
- package/dist/domains/agents/chat/use-chat-send-handler.es.js +4 -1
- package/dist/domains/agents/chat/use-chat-send-handler.es.js.map +1 -1
- package/dist/domains/dashboards/components/stateless-widget.cjs.js.map +1 -1
- package/dist/domains/dashboards/components/stateless-widget.es.js.map +1 -1
- package/dist/domains/dashboards/components/view-tabs.cjs.js +30 -0
- package/dist/domains/dashboards/components/view-tabs.cjs.js.map +1 -0
- package/dist/domains/dashboards/components/view-tabs.d.ts +1 -0
- package/dist/domains/dashboards/components/view-tabs.es.js +29 -0
- package/dist/domains/dashboards/components/view-tabs.es.js.map +1 -0
- package/dist/domains/dashboards/hooks/use-widget-views.cjs.js +24 -5
- package/dist/domains/dashboards/hooks/use-widget-views.cjs.js.map +1 -1
- package/dist/domains/dashboards/hooks/use-widget-views.es.js +24 -6
- package/dist/domains/dashboards/hooks/use-widget-views.es.js.map +1 -1
- package/dist/domains/dashboards/kinds/scores/scores-widget.cjs.js +2 -2
- package/dist/domains/dashboards/kinds/scores/scores-widget.cjs.js.map +1 -1
- package/dist/domains/dashboards/kinds/scores/scores-widget.es.js +1 -1
- package/dist/domains/dashboards/kinds/scores/scores-widget.es.js.map +1 -1
- package/dist/domains/dashboards/kinds/table/table-tabs.cjs.js +0 -11
- package/dist/domains/dashboards/kinds/table/table-tabs.cjs.js.map +1 -1
- package/dist/domains/dashboards/kinds/table/table-tabs.es.js +0 -11
- package/dist/domains/dashboards/kinds/table/table-tabs.es.js.map +1 -1
- package/dist/domains/dashboards/kinds/table/table-widget.cjs.js.map +1 -1
- package/dist/domains/dashboards/kinds/table/table-widget.es.js.map +1 -1
- package/dist/domains/dashboards/kinds/timeseries/timeseries-widget.cjs.js +1 -1
- package/dist/domains/dashboards/kinds/timeseries/timeseries-widget.cjs.js.map +1 -1
- package/dist/domains/dashboards/kinds/timeseries/timeseries-widget.es.js +1 -1
- package/dist/domains/dashboards/kinds/timeseries/timeseries-widget.es.js.map +1 -1
- package/dist/domains/dashboards/lib/chrome.cjs.js +1 -23
- package/dist/domains/dashboards/lib/chrome.cjs.js.map +1 -1
- package/dist/domains/dashboards/lib/chrome.es.js +2 -23
- package/dist/domains/dashboards/lib/chrome.es.js.map +1 -1
- package/dist/domains/dashboards/lib/view-labels.cjs.js +9 -7
- package/dist/domains/dashboards/lib/view-labels.cjs.js.map +1 -1
- package/dist/domains/dashboards/lib/view-labels.es.js +9 -7
- package/dist/domains/dashboards/lib/view-labels.es.js.map +1 -1
- package/dist/domains/dashboards/metrics-dashboard.cjs.js +1 -1
- package/dist/domains/dashboards/metrics-dashboard.cjs.js.map +1 -1
- package/dist/domains/dashboards/metrics-dashboard.es.js +1 -1
- package/dist/domains/dashboards/metrics-dashboard.es.js.map +1 -1
- package/dist/domains/dashboards/widget-kind.cjs.js.map +1 -1
- package/dist/domains/dashboards/widget-kind.es.js.map +1 -1
- package/dist/domains/dashboards.cjs.js +1 -1
- package/dist/domains/dashboards.es.js +1 -1
- package/dist/domains/metrics/components/breakdown/breakdown-table.cjs.js +2 -2
- package/dist/domains/metrics/components/breakdown/breakdown-table.cjs.js.map +1 -1
- package/dist/domains/metrics/components/breakdown/breakdown-table.es.js +2 -2
- package/dist/domains/metrics/components/breakdown/breakdown-table.es.js.map +1 -1
- package/dist/domains/metrics/components/distinct-ids/distinct-ids-chart.cjs.js +4 -2
- package/dist/domains/metrics/components/distinct-ids/distinct-ids-chart.cjs.js.map +1 -1
- package/dist/domains/metrics/components/distinct-ids/distinct-ids-chart.es.js +4 -2
- package/dist/domains/metrics/components/distinct-ids/distinct-ids-chart.es.js.map +1 -1
- package/dist/src/domains/agents/chat/stream-error-message.d.ts +16 -11
- package/dist/src/domains/dashboards/components/stateless-widget.d.ts +1 -2
- package/dist/src/domains/dashboards/components/view-tabs.d.ts +13 -0
- package/dist/src/domains/dashboards/hooks/use-widget-views.d.ts +11 -5
- package/dist/src/domains/dashboards/lib/chrome.d.ts +4 -13
- package/dist/src/domains/dashboards/lib/view-labels.d.ts +3 -3
- package/dist/src/domains/dashboards/widget-kind.d.ts +2 -3
- package/package.json +12 -11
- package/dist/domains/dashboards/kinds/table/table-view-tabs.cjs.js +0 -32
- package/dist/domains/dashboards/kinds/table/table-view-tabs.cjs.js.map +0 -1
- package/dist/domains/dashboards/kinds/table/table-view-tabs.d.ts +0 -1
- package/dist/domains/dashboards/kinds/table/table-view-tabs.es.js +0 -31
- package/dist/domains/dashboards/kinds/table/table-view-tabs.es.js.map +0 -1
- package/dist/src/domains/dashboards/kinds/table/table-view-tabs.d.ts +0 -14
|
@@ -1,15 +1,22 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
// src/domains/agents/chat/stream-error-message.ts
|
|
3
|
-
var MAX_STEPS_FINISH_REASON = "tool-calls";
|
|
4
3
|
var getMaxStepsErrorText = (maxSteps) => {
|
|
5
4
|
return `Agent stopped because it reached maxSteps${typeof maxSteps === "number" ? ` (${maxSteps})` : ""} while tool calls were still pending. Increase maxSteps in advanced settings and try again.`;
|
|
6
5
|
};
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
6
|
+
/**
|
|
7
|
+
* True when a run stopped because it used its whole step budget while the model
|
|
8
|
+
* still wanted to call tools. A `'tool-calls'` finish reason alone only says the
|
|
9
|
+
* last step called a tool: a `stopWhen` match, a client tool or an
|
|
10
|
+
* `onIterationComplete` stop end a run the same way, even on the last allowed
|
|
11
|
+
* step (#29612). Core reports why its loop stopped as `stopCause`, on both the
|
|
12
|
+
* agent stream and thread subscription copies. When `stopCause` is absent (for
|
|
13
|
+
* example from an older `@mastra/core` server), do not infer exhaustion from
|
|
14
|
+
* step count, because intentional boundary stops look identical.
|
|
15
|
+
*/
|
|
16
|
+
var isMaxStepsFinishChunk = ({ chunk }) => {
|
|
17
|
+
if (chunk.type !== "finish" || chunk.payload.stepResult?.reason !== "tool-calls") return false;
|
|
18
|
+
return chunk.payload.stopCause === "max_steps";
|
|
11
19
|
};
|
|
12
|
-
var isMaxStepsFinishChunk = (chunk) => getFinishReason(chunk) === MAX_STEPS_FINISH_REASON;
|
|
13
20
|
/**
|
|
14
21
|
* Build a `MastraDBMessage` representing a stream `error` chunk so it can be
|
|
15
22
|
* rendered by `error-aware-text`. Prefer the human-readable `message` field on
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream-error-message.cjs.js","names":[],"sources":["../../../../src/domains/agents/chat/stream-error-message.ts"],"sourcesContent":["import type { MastraDBMessage } from '@mastra/core/agent/message-list';\
|
|
1
|
+
{"version":3,"file":"stream-error-message.cjs.js","names":[],"sources":["../../../../src/domains/agents/chat/stream-error-message.ts"],"sourcesContent":["import type { MastraDBMessage } from '@mastra/core/agent/message-list';\nimport type { ChunkType } from '@mastra/core/stream';\n\ntype StreamErrorChunk = {\n runId?: string;\n payload?: {\n error?: unknown;\n };\n};\n\nconst getMaxStepsErrorText = (maxSteps?: number) => {\n const limit = typeof maxSteps === 'number' ? ` (${maxSteps})` : '';\n return `Agent stopped because it reached maxSteps${limit} while tool calls were still pending. Increase maxSteps in advanced settings and try again.`;\n};\n\n/**\n * True when a run stopped because it used its whole step budget while the model\n * still wanted to call tools. A `'tool-calls'` finish reason alone only says the\n * last step called a tool: a `stopWhen` match, a client tool or an\n * `onIterationComplete` stop end a run the same way, even on the last allowed\n * step (#29612). Core reports why its loop stopped as `stopCause`, on both the\n * agent stream and thread subscription copies. When `stopCause` is absent (for\n * example from an older `@mastra/core` server), do not infer exhaustion from\n * step count, because intentional boundary stops look identical.\n */\nexport const isMaxStepsFinishChunk = ({ chunk }: { chunk: ChunkType; maxSteps?: number | undefined }) => {\n if (chunk.type !== 'finish' || chunk.payload.stepResult?.reason !== 'tool-calls') return false;\n return chunk.payload.stopCause === 'max_steps';\n};\n\n/**\n * Build a `MastraDBMessage` representing a stream `error` chunk so it can be\n * rendered by `error-aware-text`. Prefer the human-readable `message` field on\n * the error payload when present, falling back to a JSON dump so we never\n * silently swallow an error.\n */\nexport const buildStreamErrorMessage = (chunk: StreamErrorChunk): MastraDBMessage => {\n const errorValue = chunk.payload?.error;\n let text: string;\n if (typeof errorValue === 'string') {\n text = errorValue;\n } else if (errorValue instanceof Error) {\n text = errorValue.message;\n } else if (\n errorValue &&\n typeof errorValue === 'object' &&\n typeof (errorValue as { message?: unknown }).message === 'string'\n ) {\n text = (errorValue as { message: string }).message;\n } else if (errorValue == null) {\n text = 'Unknown error';\n } else {\n try {\n text = JSON.stringify(errorValue) ?? String(errorValue);\n } catch {\n try {\n text = String(errorValue);\n } catch {\n text = 'Unknown error';\n }\n }\n }\n return {\n id: `error-${chunk.runId ?? 'unknown'}-${Date.now()}`,\n role: 'assistant',\n createdAt: new Date(),\n content: {\n format: 2,\n parts: [{ type: 'text', text }],\n metadata: { status: 'error' },\n },\n };\n};\n\nexport const buildMaxStepsStreamErrorMessage = (chunk: Pick<ChunkType, 'runId'>, maxSteps?: number) =>\n buildStreamErrorMessage({\n runId: chunk.runId,\n payload: { error: getMaxStepsErrorText(maxSteps) },\n });\n"],"mappings":";;AAUA,IAAM,wBAAwB,aAAsB;CAElD,OAAO,4CADO,OAAO,aAAa,WAAW,KAAK,SAAS,KAAK,GACP;AAC3D;;;;;;;;;;;AAYA,IAAa,yBAAyB,EAAE,YAAiE;CACvG,IAAI,MAAM,SAAS,YAAY,MAAM,QAAQ,YAAY,WAAW,cAAc,OAAO;CACzF,OAAO,MAAM,QAAQ,cAAc;AACrC;;;;;;;AAQA,IAAa,2BAA2B,UAA6C;CACnF,MAAM,aAAa,MAAM,SAAS;CAClC,IAAI;CACJ,IAAI,OAAO,eAAe,UACxB,OAAO;MACF,IAAI,sBAAsB,OAC/B,OAAO,WAAW;MACb,IACL,cACA,OAAO,eAAe,YACtB,OAAQ,WAAqC,YAAY,UAEzD,OAAQ,WAAmC;MACtC,IAAI,cAAc,MACvB,OAAO;MAEP,IAAI;EACF,OAAO,KAAK,UAAU,UAAU,KAAK,OAAO,UAAU;CACxD,QAAQ;EACN,IAAI;GACF,OAAO,OAAO,UAAU;EAC1B,QAAQ;GACN,OAAO;EACT;CACF;CAEF,OAAO;EACL,IAAI,SAAS,MAAM,SAAS,UAAU,GAAG,KAAK,IAAI;EAClD,MAAM;EACN,2BAAW,IAAI,KAAK;EACpB,SAAS;GACP,QAAQ;GACR,OAAO,CAAC;IAAE,MAAM;IAAQ;GAAK,CAAC;GAC9B,UAAU,EAAE,QAAQ,QAAQ;EAC9B;CACF;AACF;AAEA,IAAa,mCAAmC,OAAiC,aAC/E,wBAAwB;CACtB,OAAO,MAAM;CACb,SAAS,EAAE,OAAO,qBAAqB,QAAQ,EAAE;AACnD,CAAC"}
|
|
@@ -1,14 +1,21 @@
|
|
|
1
1
|
// src/domains/agents/chat/stream-error-message.ts
|
|
2
|
-
var MAX_STEPS_FINISH_REASON = "tool-calls";
|
|
3
2
|
var getMaxStepsErrorText = (maxSteps) => {
|
|
4
3
|
return `Agent stopped because it reached maxSteps${typeof maxSteps === "number" ? ` (${maxSteps})` : ""} while tool calls were still pending. Increase maxSteps in advanced settings and try again.`;
|
|
5
4
|
};
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
5
|
+
/**
|
|
6
|
+
* True when a run stopped because it used its whole step budget while the model
|
|
7
|
+
* still wanted to call tools. A `'tool-calls'` finish reason alone only says the
|
|
8
|
+
* last step called a tool: a `stopWhen` match, a client tool or an
|
|
9
|
+
* `onIterationComplete` stop end a run the same way, even on the last allowed
|
|
10
|
+
* step (#29612). Core reports why its loop stopped as `stopCause`, on both the
|
|
11
|
+
* agent stream and thread subscription copies. When `stopCause` is absent (for
|
|
12
|
+
* example from an older `@mastra/core` server), do not infer exhaustion from
|
|
13
|
+
* step count, because intentional boundary stops look identical.
|
|
14
|
+
*/
|
|
15
|
+
var isMaxStepsFinishChunk = ({ chunk }) => {
|
|
16
|
+
if (chunk.type !== "finish" || chunk.payload.stepResult?.reason !== "tool-calls") return false;
|
|
17
|
+
return chunk.payload.stopCause === "max_steps";
|
|
10
18
|
};
|
|
11
|
-
var isMaxStepsFinishChunk = (chunk) => getFinishReason(chunk) === MAX_STEPS_FINISH_REASON;
|
|
12
19
|
/**
|
|
13
20
|
* Build a `MastraDBMessage` representing a stream `error` chunk so it can be
|
|
14
21
|
* rendered by `error-aware-text`. Prefer the human-readable `message` field on
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream-error-message.es.js","names":[],"sources":["../../../../src/domains/agents/chat/stream-error-message.ts"],"sourcesContent":["import type { MastraDBMessage } from '@mastra/core/agent/message-list';\
|
|
1
|
+
{"version":3,"file":"stream-error-message.es.js","names":[],"sources":["../../../../src/domains/agents/chat/stream-error-message.ts"],"sourcesContent":["import type { MastraDBMessage } from '@mastra/core/agent/message-list';\nimport type { ChunkType } from '@mastra/core/stream';\n\ntype StreamErrorChunk = {\n runId?: string;\n payload?: {\n error?: unknown;\n };\n};\n\nconst getMaxStepsErrorText = (maxSteps?: number) => {\n const limit = typeof maxSteps === 'number' ? ` (${maxSteps})` : '';\n return `Agent stopped because it reached maxSteps${limit} while tool calls were still pending. Increase maxSteps in advanced settings and try again.`;\n};\n\n/**\n * True when a run stopped because it used its whole step budget while the model\n * still wanted to call tools. A `'tool-calls'` finish reason alone only says the\n * last step called a tool: a `stopWhen` match, a client tool or an\n * `onIterationComplete` stop end a run the same way, even on the last allowed\n * step (#29612). Core reports why its loop stopped as `stopCause`, on both the\n * agent stream and thread subscription copies. When `stopCause` is absent (for\n * example from an older `@mastra/core` server), do not infer exhaustion from\n * step count, because intentional boundary stops look identical.\n */\nexport const isMaxStepsFinishChunk = ({ chunk }: { chunk: ChunkType; maxSteps?: number | undefined }) => {\n if (chunk.type !== 'finish' || chunk.payload.stepResult?.reason !== 'tool-calls') return false;\n return chunk.payload.stopCause === 'max_steps';\n};\n\n/**\n * Build a `MastraDBMessage` representing a stream `error` chunk so it can be\n * rendered by `error-aware-text`. Prefer the human-readable `message` field on\n * the error payload when present, falling back to a JSON dump so we never\n * silently swallow an error.\n */\nexport const buildStreamErrorMessage = (chunk: StreamErrorChunk): MastraDBMessage => {\n const errorValue = chunk.payload?.error;\n let text: string;\n if (typeof errorValue === 'string') {\n text = errorValue;\n } else if (errorValue instanceof Error) {\n text = errorValue.message;\n } else if (\n errorValue &&\n typeof errorValue === 'object' &&\n typeof (errorValue as { message?: unknown }).message === 'string'\n ) {\n text = (errorValue as { message: string }).message;\n } else if (errorValue == null) {\n text = 'Unknown error';\n } else {\n try {\n text = JSON.stringify(errorValue) ?? String(errorValue);\n } catch {\n try {\n text = String(errorValue);\n } catch {\n text = 'Unknown error';\n }\n }\n }\n return {\n id: `error-${chunk.runId ?? 'unknown'}-${Date.now()}`,\n role: 'assistant',\n createdAt: new Date(),\n content: {\n format: 2,\n parts: [{ type: 'text', text }],\n metadata: { status: 'error' },\n },\n };\n};\n\nexport const buildMaxStepsStreamErrorMessage = (chunk: Pick<ChunkType, 'runId'>, maxSteps?: number) =>\n buildStreamErrorMessage({\n runId: chunk.runId,\n payload: { error: getMaxStepsErrorText(maxSteps) },\n });\n"],"mappings":";AAUA,IAAM,wBAAwB,aAAsB;CAElD,OAAO,4CADO,OAAO,aAAa,WAAW,KAAK,SAAS,KAAK,GACP;AAC3D;;;;;;;;;;;AAYA,IAAa,yBAAyB,EAAE,YAAiE;CACvG,IAAI,MAAM,SAAS,YAAY,MAAM,QAAQ,YAAY,WAAW,cAAc,OAAO;CACzF,OAAO,MAAM,QAAQ,cAAc;AACrC;;;;;;;AAQA,IAAa,2BAA2B,UAA6C;CACnF,MAAM,aAAa,MAAM,SAAS;CAClC,IAAI;CACJ,IAAI,OAAO,eAAe,UACxB,OAAO;MACF,IAAI,sBAAsB,OAC/B,OAAO,WAAW;MACb,IACL,cACA,OAAO,eAAe,YACtB,OAAQ,WAAqC,YAAY,UAEzD,OAAQ,WAAmC;MACtC,IAAI,cAAc,MACvB,OAAO;MAEP,IAAI;EACF,OAAO,KAAK,UAAU,UAAU,KAAK,OAAO,UAAU;CACxD,QAAQ;EACN,IAAI;GACF,OAAO,OAAO,UAAU;EAC1B,QAAQ;GACN,OAAO;EACT;CACF;CAEF,OAAO;EACL,IAAI,SAAS,MAAM,SAAS,UAAU,GAAG,KAAK,IAAI;EAClD,MAAM;EACN,2BAAW,IAAI,KAAK;EACpB,SAAS;GACP,QAAQ;GACR,OAAO,CAAC;IAAE,MAAM;IAAQ;GAAK,CAAC;GAC9B,UAAU,EAAE,QAAQ,QAAQ;EAC9B;CACF;AACF;AAEA,IAAa,mCAAmC,OAAiC,aAC/E,wBAAwB;CACtB,OAAO,MAAM;CACb,SAAS,EAAE,OAAO,qBAAqB,QAAQ,EAAE;AACnD,CAAC"}
|
|
@@ -183,7 +183,10 @@ var useChatSendHandler = ({ agentId, requestContext, agentVersionId, threadId, m
|
|
|
183
183
|
onChunk: async (chunk) => {
|
|
184
184
|
delivered = true;
|
|
185
185
|
if (chunk.type === "finish") {
|
|
186
|
-
if (require_domains_agents_chat_stream_error_message.isMaxStepsFinishChunk(
|
|
186
|
+
if (require_domains_agents_chat_stream_error_message.isMaxStepsFinishChunk({
|
|
187
|
+
chunk,
|
|
188
|
+
maxSteps: deps.maxSteps
|
|
189
|
+
})) setStreamErrors((prev) => [...prev, require_domains_agents_chat_stream_error_message.buildMaxStepsStreamErrorMessage(chunk, deps.maxSteps)]);
|
|
187
190
|
await refreshThreadList?.();
|
|
188
191
|
refreshTimelinePanel(deps.threadId);
|
|
189
192
|
completeObservationalMemoryBuffering(deps.threadId);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-chat-send-handler.cjs.js","names":["RequestContext","useMastraClient","useQueryClient","useRef","useCallback","observationalMemoryQueryKey","memoryThreadMessagesQueryKey","memoryStatusQueryKey","injectBufferingEnds","buildStreamErrorMessage","toUntrustedAppContext","isMaxStepsFinishChunk","buildMaxStepsStreamErrorMessage"],"sources":["../../../../src/domains/agents/chat/use-chat-send-handler.ts"],"sourcesContent":["import type { MastraDBMessage } from '@mastra/core/agent/message-list';\nimport { RequestContext } from '@mastra/core/di';\nimport { useMastraClient } from '@mastra/react';\nimport {\n memoryStatusQueryKey,\n memoryThreadMessagesQueryKey,\n observationalMemoryQueryKey,\n} from '@mastra/react/hooks/memory';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useCallback, useRef } from 'react';\nimport type { Dispatch, SetStateAction } from 'react';\nimport {\n buildMaxStepsStreamErrorMessage,\n buildStreamErrorMessage,\n isMaxStepsFinishChunk,\n} from './stream-error-message';\nimport type { ChatSendArgs } from '@/domains/chat/context/chat-context';\nimport { injectBufferingEnds } from '@/domains/chat/om/om-parts-converter';\n\nimport { toUntrustedAppContext } from '@/utils/mcp-app-context';\n\n/**\n * The OM/error stream chunks this hook reacts to are not part of the typed\n * `useChat` chunk union, so we narrow them at the stream boundary.\n */\ntype OmStreamChunk =\n | { type: 'data-om-observation-start'; data?: { operationType?: string } }\n | { type: 'data-om-observation-end'; data?: { operationType?: string } }\n | { type: 'data-om-observation-failed'; data?: { operationType?: string } }\n | {\n type: 'data-om-status';\n data?: {\n windows?: unknown;\n recordId?: string;\n threadId?: string;\n stepNumber?: number;\n generationCount?: number;\n };\n }\n | { type: 'data-om-activation'; data?: { operationType?: string; cycleId?: string } };\n\ntype ErrorStreamChunk = { type: 'error'; runId?: string; payload?: { error?: unknown } };\ntype HandledStreamChunk = OmStreamChunk | ErrorStreamChunk;\n\nconst asHandledStreamChunk = (chunk: unknown): HandledStreamChunk | undefined => {\n const type = (chunk as { type?: unknown }).type;\n if (\n type === 'error' ||\n type === 'data-om-observation-start' ||\n type === 'data-om-observation-end' ||\n type === 'data-om-observation-failed' ||\n type === 'data-om-status' ||\n type === 'data-om-activation'\n ) {\n return chunk as HandledStreamChunk;\n }\n return undefined;\n};\n\ninterface SendDeps {\n model?: string;\n requestContext?: Record<string, any>;\n agentVersionId?: string;\n threadId?: string;\n modelSettingsArgs: Record<string, unknown>;\n chatWithNetwork?: boolean;\n chatWithGenerate?: boolean;\n maxSteps?: number;\n isOMEnabled: boolean;\n tracingOptions?: unknown;\n}\n\ninterface UseChatSendHandlerArgs {\n agentId: string;\n requestContext?: Record<string, any>;\n agentVersionId?: string;\n threadId?: string;\n modelSettingsArgs: Record<string, unknown>;\n model?: string;\n chatWithNetwork?: boolean;\n chatWithGenerate?: boolean;\n maxSteps?: number;\n isOMEnabled: boolean;\n tracingOptions?: unknown;\n threadSignalsUnsupportedRef: { current: boolean };\n isRunningStream: boolean;\n sendMessage: (args: any) => Promise<void>;\n cancelRun?: () => void;\n setMessages: Dispatch<SetStateAction<MastraDBMessage[]>>;\n setStreamErrors: Dispatch<SetStateAction<MastraDBMessage[]>>;\n refreshThreadList?: () => void | Promise<void>;\n refreshWorkingMemory?: () => void | Promise<unknown>;\n handleObservationStart: (operationType?: string) => void;\n handleProgressUpdate: (data: any) => void;\n refreshObservationalMemory: (operationType?: string) => void;\n handleActivation: (data: any) => void;\n resetObservationalMemoryStreamState: () => void;\n /** Signal the memory timeline panel to refetch (mirrors left OM sidebar freshness). */\n signalTimelineRefresh: () => void;\n}\n\nconst buildRequestContext = (deps: SendDeps, turnContext?: Record<string, unknown>) => {\n const requestContextInstance = new RequestContext();\n Object.entries({ ...deps.requestContext, ...turnContext }).forEach(([key, value]) => {\n requestContextInstance.set(key, value);\n });\n if (deps.agentVersionId) {\n requestContextInstance.set('agentVersionId', deps.agentVersionId);\n }\n return requestContextInstance;\n};\n\n/**\n * A server error (5xx) can come after the agent ran and stored the turn, as in generate mode where no\n * chunk arrives first: putting the message back in the composer would invite sending it twice. A\n * request that got no response, or that the server refused (4xx, such as a body too large), left\n * nothing behind.\n */\nconst mayHaveBeenStored = (error: unknown) => {\n const status = (error as { status?: unknown } | null)?.status;\n return typeof status === 'number' && status >= 500;\n};\n\nconst didUpdateWorkingMemory = (chunk: any) => {\n const result = chunk.payload?.result;\n return (\n (chunk.type === 'tool-result' || chunk.type === 'tool-execution-end') &&\n chunk.payload?.toolName === 'updateWorkingMemory' &&\n typeof result === 'object' &&\n result !== null &&\n 'success' in result &&\n result.success\n );\n};\n\nexport const useChatSendHandler = ({\n agentId,\n requestContext,\n agentVersionId,\n threadId,\n modelSettingsArgs,\n model,\n chatWithNetwork,\n chatWithGenerate,\n maxSteps,\n isOMEnabled,\n tracingOptions,\n threadSignalsUnsupportedRef,\n isRunningStream,\n sendMessage,\n cancelRun,\n setMessages,\n setStreamErrors,\n refreshThreadList,\n refreshWorkingMemory,\n handleObservationStart,\n handleProgressUpdate,\n refreshObservationalMemory,\n handleActivation,\n resetObservationalMemoryStreamState,\n signalTimelineRefresh,\n}: UseChatSendHandlerArgs) => {\n const baseClient = useMastraClient();\n const queryClient = useQueryClient();\n const abortControllerRef = useRef<AbortController | null>(null);\n // Latest context per source (an MCP App's tool call, for instance), carried by the next send only.\n const modelContextRef = useRef(new Map<string, string>());\n const setModelContext = useCallback((sourceId: string, context: string | undefined) => {\n if (context) {\n modelContextRef.current.set(sourceId, context);\n } else {\n modelContextRef.current.delete(sourceId);\n }\n }, []);\n const sendDepsRef = useRef<SendDeps>({\n requestContext,\n agentVersionId,\n threadId,\n modelSettingsArgs,\n model,\n chatWithNetwork,\n chatWithGenerate,\n maxSteps,\n isOMEnabled,\n tracingOptions,\n });\n sendDepsRef.current = {\n requestContext,\n agentVersionId,\n threadId,\n modelSettingsArgs,\n model,\n chatWithNetwork,\n chatWithGenerate,\n maxSteps,\n isOMEnabled,\n tracingOptions,\n };\n\n // Force an immediate refetch of the memory timeline panel (playground-ui\n // ['memory', ...] keys), scoped to the given thread, so the panel shows live\n // data right away. Runs on every chat completion regardless of whether\n // observational memory is enabled, so the thread messages and memory status\n // shown in the panel are never stale after a stream finishes.\n const refreshTimelinePanel = useCallback(\n (currentThreadId?: string) => {\n if (!currentThreadId) return;\n void queryClient.refetchQueries({ queryKey: observationalMemoryQueryKey(agentId, currentThreadId) });\n void queryClient.refetchQueries({ queryKey: memoryThreadMessagesQueryKey(currentThreadId) });\n void queryClient.refetchQueries({ queryKey: memoryStatusQueryKey(agentId, currentThreadId) });\n // Also poke the timeline panel directly. The panel resolves its own thread id\n // from the route, so it stays correct even for brand-new threads where\n // `deps.threadId` is still undefined at send time and the keyed refetch above\n // cannot target the real thread yet.\n signalTimelineRefresh();\n },\n [agentId, queryClient, signalTimelineRefresh],\n );\n\n const completeObservationalMemoryBuffering = useCallback(\n (currentThreadId?: string) => {\n if (!currentThreadId || !sendDepsRef.current.isOMEnabled) return;\n baseClient\n .awaitBufferStatus({ agentId, resourceId: agentId, threadId: currentThreadId })\n .then(result => {\n setMessages(prev => injectBufferingEnds(prev, result?.record));\n void queryClient.invalidateQueries({ queryKey: ['observational-memory', agentId] });\n void queryClient.invalidateQueries({ queryKey: ['memory-status', agentId] });\n // Refetch the panel again once buffering completes, so any records that\n // only landed after awaitBufferStatus resolved are reflected immediately.\n refreshTimelinePanel(currentThreadId);\n void refreshWorkingMemory?.();\n })\n .catch(() => {});\n },\n [agentId, baseClient, queryClient, refreshTimelinePanel, refreshWorkingMemory, setMessages],\n );\n\n const handleHandledChunk = useCallback(\n (handled: HandledStreamChunk | undefined) => {\n if (handled?.type === 'error') {\n setStreamErrors(prev => [...prev, buildStreamErrorMessage(handled)]);\n }\n if (handled?.type === 'data-om-observation-start') {\n handleObservationStart(handled.data?.operationType);\n }\n if (handled?.type === 'data-om-status') {\n handleProgressUpdate(handled.data);\n }\n if (\n handled?.type === 'data-om-observation-end' ||\n handled?.type === 'data-om-observation-failed' ||\n handled?.type === 'data-om-activation'\n ) {\n refreshObservationalMemory(handled.data?.operationType);\n }\n if (handled?.type === 'data-om-observation-end') {\n void refreshWorkingMemory?.();\n }\n if (handled?.type === 'data-om-activation') {\n handleActivation(handled.data);\n }\n },\n [\n handleActivation,\n handleObservationStart,\n handleProgressUpdate,\n refreshObservationalMemory,\n refreshWorkingMemory,\n setStreamErrors,\n ],\n );\n\n const send = useCallback(\n async ({ message, attachments = [], requestContext: turnContext }: ChatSendArgs): Promise<boolean> => {\n const deps = sendDepsRef.current;\n if (threadSignalsUnsupportedRef.current && (isRunningStream || abortControllerRef.current)) return false;\n\n setStreamErrors([]);\n const controller = new AbortController();\n abortControllerRef.current = controller;\n const requestContextInstance = buildRequestContext(deps, turnContext);\n const heldContext = new Map(modelContextRef.current);\n modelContextRef.current.clear();\n // MCP App context is third-party content: it goes in the user turn as delimited data, never in the system prompt.\n const appContext = heldContext.size\n ? [\n {\n role: 'user' as const,\n content: [{ type: 'text' as const, text: toUntrustedAppContext(heldContext.values()) }],\n },\n ]\n : [];\n const coreUserMessages = [...attachments, ...appContext];\n // An error can still be thrown once the server has the message, by a chunk handler or a refresh.\n // Those must not put the message back in the composer.\n let delivered = false;\n\n try {\n if (deps.chatWithNetwork) {\n await sendMessage({\n message,\n mode: 'network',\n coreUserMessages,\n requestContext: requestContextInstance,\n threadId: deps.threadId,\n modelSettings: deps.modelSettingsArgs,\n model: deps.model,\n signal: controller.signal,\n tracingOptions: deps.tracingOptions,\n onNetworkChunk: async (chunk: any) => {\n delivered = true;\n if (didUpdateWorkingMemory(chunk)) {\n void refreshWorkingMemory?.();\n }\n if (chunk.type === 'network-execution-event-step-finish') {\n void refreshThreadList?.();\n }\n handleHandledChunk(asHandledStreamChunk(chunk));\n },\n });\n } else if (deps.chatWithGenerate) {\n await sendMessage({\n message,\n mode: 'generate',\n coreUserMessages,\n requestContext: requestContextInstance,\n threadId: deps.threadId,\n modelSettings: deps.modelSettingsArgs,\n model: deps.model,\n signal: controller.signal,\n tracingOptions: deps.tracingOptions,\n });\n delivered = true;\n await refreshThreadList?.();\n refreshTimelinePanel(deps.threadId);\n return true;\n } else {\n await sendMessage({\n message,\n mode: 'stream',\n coreUserMessages,\n requestContext: requestContextInstance,\n threadId: deps.threadId,\n modelSettings: deps.modelSettingsArgs,\n model: deps.model,\n tracingOptions: deps.tracingOptions,\n onChunk: async (chunk: any) => {\n delivered = true;\n if (chunk.type === 'finish') {\n if (isMaxStepsFinishChunk(chunk)) {\n setStreamErrors(prev => [...prev, buildMaxStepsStreamErrorMessage(chunk, deps.maxSteps)]);\n }\n await refreshThreadList?.();\n refreshTimelinePanel(deps.threadId);\n completeObservationalMemoryBuffering(deps.threadId);\n }\n if (didUpdateWorkingMemory(chunk)) {\n void refreshWorkingMemory?.();\n }\n handleHandledChunk(asHandledStreamChunk(chunk));\n },\n signal: controller.signal,\n });\n\n return true;\n }\n\n delivered = true;\n setTimeout(() => {\n void refreshThreadList?.();\n }, 500);\n refreshTimelinePanel(deps.threadId);\n completeObservationalMemoryBuffering(deps.threadId);\n return true;\n } catch (error: any) {\n console.error('Error occurred in ChatProvider', error);\n if (error.name === 'AbortError') {\n return true;\n }\n setStreamErrors(prev => [...prev, buildStreamErrorMessage({ runId: 'thrown', payload: { error } })]);\n resetObservationalMemoryStreamState();\n const stored = delivered || mayHaveBeenStored(error);\n if (!stored) {\n // The message goes back to the composer, so its context waits for the retry.\n heldContext.forEach((context, sourceId) => {\n if (!modelContextRef.current.has(sourceId)) modelContextRef.current.set(sourceId, context);\n });\n }\n return stored;\n } finally {\n abortControllerRef.current = null;\n }\n },\n [\n completeObservationalMemoryBuffering,\n handleHandledChunk,\n isRunningStream,\n refreshThreadList,\n refreshTimelinePanel,\n refreshWorkingMemory,\n resetObservationalMemoryStreamState,\n sendMessage,\n setStreamErrors,\n threadSignalsUnsupportedRef,\n ],\n );\n\n const cancel = useCallback(async () => {\n abortControllerRef.current?.abort();\n abortControllerRef.current = null;\n resetObservationalMemoryStreamState();\n cancelRun?.();\n completeObservationalMemoryBuffering(sendDepsRef.current.threadId);\n }, [cancelRun, completeObservationalMemoryBuffering, resetObservationalMemoryStreamState]);\n\n return { send, cancel, setModelContext };\n};\n"],"mappings":";;;;;;;;;;AA4CA,IAAM,wBAAwB,UAAmD;CAC/E,MAAM,OAAQ,MAA6B;CAC3C,IACE,SAAS,WACT,SAAS,+BACT,SAAS,6BACT,SAAS,gCACT,SAAS,oBACT,SAAS,sBAET,OAAO;AAGX;AA4CA,IAAM,uBAAuB,MAAgB,gBAA0C;CACrF,MAAM,yBAAyB,IAAIA,gBAAAA,eAAe;CAClD,OAAO,QAAQ;EAAE,GAAG,KAAK;EAAgB,GAAG;CAAY,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK,WAAW;EACnF,uBAAuB,IAAI,KAAK,KAAK;CACvC,CAAC;CACD,IAAI,KAAK,gBACP,uBAAuB,IAAI,kBAAkB,KAAK,cAAc;CAElE,OAAO;AACT;;;;;;;AAQA,IAAM,qBAAqB,UAAmB;CAC5C,MAAM,SAAU,OAAuC;CACvD,OAAO,OAAO,WAAW,YAAY,UAAU;AACjD;AAEA,IAAM,0BAA0B,UAAe;CAC7C,MAAM,SAAS,MAAM,SAAS;CAC9B,QACG,MAAM,SAAS,iBAAiB,MAAM,SAAS,yBAChD,MAAM,SAAS,aAAa,yBAC5B,OAAO,WAAW,YAClB,WAAW,QACX,aAAa,UACb,OAAO;AAEX;AAEA,IAAa,sBAAsB,EACjC,SACA,gBACA,gBACA,UACA,mBACA,OACA,iBACA,kBACA,UACA,aACA,gBACA,6BACA,iBACA,aACA,WACA,aACA,iBACA,mBACA,sBACA,wBACA,sBACA,4BACA,kBACA,qCACA,4BAC4B;CAC5B,MAAM,cAAA,GAAaC,cAAAA,gBAAAA,CAAgB;CACnC,MAAM,eAAA,GAAcC,sBAAAA,eAAAA,CAAe;CACnC,MAAM,sBAAA,GAAqBC,MAAAA,OAAAA,CAA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N,qBAAqB,KAAK,QAAQ;IAClC,qCAAqC,KAAK,QAAQ;IAClD,OAAO;GACT,SAAS,OAAY;IACnB,QAAQ,MAAM,kCAAkC,KAAK;IACrD,IAAI,MAAM,SAAS,cACjB,OAAO;IAET,iBAAgB,SAAQ,CAAC,GAAG,MAAMH,iDAAAA,wBAAwB;KAAE,OAAO;KAAU,SAAS,EAAE,MAAM;IAAE,CAAC,CAAC,CAAC;IACnG,oCAAoC;IACpC,MAAM,SAAS,aAAa,kBAAkB,KAAK;IACnD,IAAI,CAAC,QAEH,YAAY,SAAS,SAAS,aAAa;KACzC,IAAI,CAAC,gBAAgB,QAAQ,IAAI,QAAQ,GAAG,gBAAgB,QAAQ,IAAI,UAAU,OAAO;IAC3F,CAAC;IAEH,OAAO;GACT,UAAU;IACR,mBAAmB,UAAU;GAC/B;EACF,GACA;GACE;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF,CAWO;EAAM,SAAA,GARAL,MAAAA,YAAAA,CAAY,YAAY;GACrC,mBAAmB,SAAS,MAAM;GAClC,mBAAmB,UAAU;GAC7B,oCAAoC;GACpC,YAAY;GACZ,qCAAqC,YAAY,QAAQ,QAAQ;EACnE,GAAG;GAAC;GAAW;GAAsC;EAAmC,CAEzE;EAAQ;CAAgB;AACzC"}
|
|
1
|
+
{"version":3,"file":"use-chat-send-handler.cjs.js","names":["RequestContext","useMastraClient","useQueryClient","useRef","useCallback","observationalMemoryQueryKey","memoryThreadMessagesQueryKey","memoryStatusQueryKey","injectBufferingEnds","buildStreamErrorMessage","toUntrustedAppContext","isMaxStepsFinishChunk","buildMaxStepsStreamErrorMessage"],"sources":["../../../../src/domains/agents/chat/use-chat-send-handler.ts"],"sourcesContent":["import type { MastraDBMessage } from '@mastra/core/agent/message-list';\nimport { RequestContext } from '@mastra/core/di';\nimport { useMastraClient } from '@mastra/react';\nimport {\n memoryStatusQueryKey,\n memoryThreadMessagesQueryKey,\n observationalMemoryQueryKey,\n} from '@mastra/react/hooks/memory';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useCallback, useRef } from 'react';\nimport type { Dispatch, SetStateAction } from 'react';\nimport {\n buildMaxStepsStreamErrorMessage,\n buildStreamErrorMessage,\n isMaxStepsFinishChunk,\n} from './stream-error-message';\nimport type { ChatSendArgs } from '@/domains/chat/context/chat-context';\nimport { injectBufferingEnds } from '@/domains/chat/om/om-parts-converter';\n\nimport { toUntrustedAppContext } from '@/utils/mcp-app-context';\n\n/**\n * The OM/error stream chunks this hook reacts to are not part of the typed\n * `useChat` chunk union, so we narrow them at the stream boundary.\n */\ntype OmStreamChunk =\n | { type: 'data-om-observation-start'; data?: { operationType?: string } }\n | { type: 'data-om-observation-end'; data?: { operationType?: string } }\n | { type: 'data-om-observation-failed'; data?: { operationType?: string } }\n | {\n type: 'data-om-status';\n data?: {\n windows?: unknown;\n recordId?: string;\n threadId?: string;\n stepNumber?: number;\n generationCount?: number;\n };\n }\n | { type: 'data-om-activation'; data?: { operationType?: string; cycleId?: string } };\n\ntype ErrorStreamChunk = { type: 'error'; runId?: string; payload?: { error?: unknown } };\ntype HandledStreamChunk = OmStreamChunk | ErrorStreamChunk;\n\nconst asHandledStreamChunk = (chunk: unknown): HandledStreamChunk | undefined => {\n const type = (chunk as { type?: unknown }).type;\n if (\n type === 'error' ||\n type === 'data-om-observation-start' ||\n type === 'data-om-observation-end' ||\n type === 'data-om-observation-failed' ||\n type === 'data-om-status' ||\n type === 'data-om-activation'\n ) {\n return chunk as HandledStreamChunk;\n }\n return undefined;\n};\n\ninterface SendDeps {\n model?: string;\n requestContext?: Record<string, any>;\n agentVersionId?: string;\n threadId?: string;\n modelSettingsArgs: Record<string, unknown>;\n chatWithNetwork?: boolean;\n chatWithGenerate?: boolean;\n maxSteps?: number;\n isOMEnabled: boolean;\n tracingOptions?: unknown;\n}\n\ninterface UseChatSendHandlerArgs {\n agentId: string;\n requestContext?: Record<string, any>;\n agentVersionId?: string;\n threadId?: string;\n modelSettingsArgs: Record<string, unknown>;\n model?: string;\n chatWithNetwork?: boolean;\n chatWithGenerate?: boolean;\n maxSteps?: number;\n isOMEnabled: boolean;\n tracingOptions?: unknown;\n threadSignalsUnsupportedRef: { current: boolean };\n isRunningStream: boolean;\n sendMessage: (args: any) => Promise<void>;\n cancelRun?: () => void;\n setMessages: Dispatch<SetStateAction<MastraDBMessage[]>>;\n setStreamErrors: Dispatch<SetStateAction<MastraDBMessage[]>>;\n refreshThreadList?: () => void | Promise<void>;\n refreshWorkingMemory?: () => void | Promise<unknown>;\n handleObservationStart: (operationType?: string) => void;\n handleProgressUpdate: (data: any) => void;\n refreshObservationalMemory: (operationType?: string) => void;\n handleActivation: (data: any) => void;\n resetObservationalMemoryStreamState: () => void;\n /** Signal the memory timeline panel to refetch (mirrors left OM sidebar freshness). */\n signalTimelineRefresh: () => void;\n}\n\nconst buildRequestContext = (deps: SendDeps, turnContext?: Record<string, unknown>) => {\n const requestContextInstance = new RequestContext();\n Object.entries({ ...deps.requestContext, ...turnContext }).forEach(([key, value]) => {\n requestContextInstance.set(key, value);\n });\n if (deps.agentVersionId) {\n requestContextInstance.set('agentVersionId', deps.agentVersionId);\n }\n return requestContextInstance;\n};\n\n/**\n * A server error (5xx) can come after the agent ran and stored the turn, as in generate mode where no\n * chunk arrives first: putting the message back in the composer would invite sending it twice. A\n * request that got no response, or that the server refused (4xx, such as a body too large), left\n * nothing behind.\n */\nconst mayHaveBeenStored = (error: unknown) => {\n const status = (error as { status?: unknown } | null)?.status;\n return typeof status === 'number' && status >= 500;\n};\n\nconst didUpdateWorkingMemory = (chunk: any) => {\n const result = chunk.payload?.result;\n return (\n (chunk.type === 'tool-result' || chunk.type === 'tool-execution-end') &&\n chunk.payload?.toolName === 'updateWorkingMemory' &&\n typeof result === 'object' &&\n result !== null &&\n 'success' in result &&\n result.success\n );\n};\n\nexport const useChatSendHandler = ({\n agentId,\n requestContext,\n agentVersionId,\n threadId,\n modelSettingsArgs,\n model,\n chatWithNetwork,\n chatWithGenerate,\n maxSteps,\n isOMEnabled,\n tracingOptions,\n threadSignalsUnsupportedRef,\n isRunningStream,\n sendMessage,\n cancelRun,\n setMessages,\n setStreamErrors,\n refreshThreadList,\n refreshWorkingMemory,\n handleObservationStart,\n handleProgressUpdate,\n refreshObservationalMemory,\n handleActivation,\n resetObservationalMemoryStreamState,\n signalTimelineRefresh,\n}: UseChatSendHandlerArgs) => {\n const baseClient = useMastraClient();\n const queryClient = useQueryClient();\n const abortControllerRef = useRef<AbortController | null>(null);\n // Latest context per source (an MCP App's tool call, for instance), carried by the next send only.\n const modelContextRef = useRef(new Map<string, string>());\n const setModelContext = useCallback((sourceId: string, context: string | undefined) => {\n if (context) {\n modelContextRef.current.set(sourceId, context);\n } else {\n modelContextRef.current.delete(sourceId);\n }\n }, []);\n const sendDepsRef = useRef<SendDeps>({\n requestContext,\n agentVersionId,\n threadId,\n modelSettingsArgs,\n model,\n chatWithNetwork,\n chatWithGenerate,\n maxSteps,\n isOMEnabled,\n tracingOptions,\n });\n sendDepsRef.current = {\n requestContext,\n agentVersionId,\n threadId,\n modelSettingsArgs,\n model,\n chatWithNetwork,\n chatWithGenerate,\n maxSteps,\n isOMEnabled,\n tracingOptions,\n };\n\n // Force an immediate refetch of the memory timeline panel (playground-ui\n // ['memory', ...] keys), scoped to the given thread, so the panel shows live\n // data right away. Runs on every chat completion regardless of whether\n // observational memory is enabled, so the thread messages and memory status\n // shown in the panel are never stale after a stream finishes.\n const refreshTimelinePanel = useCallback(\n (currentThreadId?: string) => {\n if (!currentThreadId) return;\n void queryClient.refetchQueries({ queryKey: observationalMemoryQueryKey(agentId, currentThreadId) });\n void queryClient.refetchQueries({ queryKey: memoryThreadMessagesQueryKey(currentThreadId) });\n void queryClient.refetchQueries({ queryKey: memoryStatusQueryKey(agentId, currentThreadId) });\n // Also poke the timeline panel directly. The panel resolves its own thread id\n // from the route, so it stays correct even for brand-new threads where\n // `deps.threadId` is still undefined at send time and the keyed refetch above\n // cannot target the real thread yet.\n signalTimelineRefresh();\n },\n [agentId, queryClient, signalTimelineRefresh],\n );\n\n const completeObservationalMemoryBuffering = useCallback(\n (currentThreadId?: string) => {\n if (!currentThreadId || !sendDepsRef.current.isOMEnabled) return;\n baseClient\n .awaitBufferStatus({ agentId, resourceId: agentId, threadId: currentThreadId })\n .then(result => {\n setMessages(prev => injectBufferingEnds(prev, result?.record));\n void queryClient.invalidateQueries({ queryKey: ['observational-memory', agentId] });\n void queryClient.invalidateQueries({ queryKey: ['memory-status', agentId] });\n // Refetch the panel again once buffering completes, so any records that\n // only landed after awaitBufferStatus resolved are reflected immediately.\n refreshTimelinePanel(currentThreadId);\n void refreshWorkingMemory?.();\n })\n .catch(() => {});\n },\n [agentId, baseClient, queryClient, refreshTimelinePanel, refreshWorkingMemory, setMessages],\n );\n\n const handleHandledChunk = useCallback(\n (handled: HandledStreamChunk | undefined) => {\n if (handled?.type === 'error') {\n setStreamErrors(prev => [...prev, buildStreamErrorMessage(handled)]);\n }\n if (handled?.type === 'data-om-observation-start') {\n handleObservationStart(handled.data?.operationType);\n }\n if (handled?.type === 'data-om-status') {\n handleProgressUpdate(handled.data);\n }\n if (\n handled?.type === 'data-om-observation-end' ||\n handled?.type === 'data-om-observation-failed' ||\n handled?.type === 'data-om-activation'\n ) {\n refreshObservationalMemory(handled.data?.operationType);\n }\n if (handled?.type === 'data-om-observation-end') {\n void refreshWorkingMemory?.();\n }\n if (handled?.type === 'data-om-activation') {\n handleActivation(handled.data);\n }\n },\n [\n handleActivation,\n handleObservationStart,\n handleProgressUpdate,\n refreshObservationalMemory,\n refreshWorkingMemory,\n setStreamErrors,\n ],\n );\n\n const send = useCallback(\n async ({ message, attachments = [], requestContext: turnContext }: ChatSendArgs): Promise<boolean> => {\n const deps = sendDepsRef.current;\n if (threadSignalsUnsupportedRef.current && (isRunningStream || abortControllerRef.current)) return false;\n\n setStreamErrors([]);\n const controller = new AbortController();\n abortControllerRef.current = controller;\n const requestContextInstance = buildRequestContext(deps, turnContext);\n const heldContext = new Map(modelContextRef.current);\n modelContextRef.current.clear();\n // MCP App context is third-party content: it goes in the user turn as delimited data, never in the system prompt.\n const appContext = heldContext.size\n ? [\n {\n role: 'user' as const,\n content: [{ type: 'text' as const, text: toUntrustedAppContext(heldContext.values()) }],\n },\n ]\n : [];\n const coreUserMessages = [...attachments, ...appContext];\n // An error can still be thrown once the server has the message, by a chunk handler or a refresh.\n // Those must not put the message back in the composer.\n let delivered = false;\n\n try {\n if (deps.chatWithNetwork) {\n await sendMessage({\n message,\n mode: 'network',\n coreUserMessages,\n requestContext: requestContextInstance,\n threadId: deps.threadId,\n modelSettings: deps.modelSettingsArgs,\n model: deps.model,\n signal: controller.signal,\n tracingOptions: deps.tracingOptions,\n onNetworkChunk: async (chunk: any) => {\n delivered = true;\n if (didUpdateWorkingMemory(chunk)) {\n void refreshWorkingMemory?.();\n }\n if (chunk.type === 'network-execution-event-step-finish') {\n void refreshThreadList?.();\n }\n handleHandledChunk(asHandledStreamChunk(chunk));\n },\n });\n } else if (deps.chatWithGenerate) {\n await sendMessage({\n message,\n mode: 'generate',\n coreUserMessages,\n requestContext: requestContextInstance,\n threadId: deps.threadId,\n modelSettings: deps.modelSettingsArgs,\n model: deps.model,\n signal: controller.signal,\n tracingOptions: deps.tracingOptions,\n });\n delivered = true;\n await refreshThreadList?.();\n refreshTimelinePanel(deps.threadId);\n return true;\n } else {\n await sendMessage({\n message,\n mode: 'stream',\n coreUserMessages,\n requestContext: requestContextInstance,\n threadId: deps.threadId,\n modelSettings: deps.modelSettingsArgs,\n model: deps.model,\n tracingOptions: deps.tracingOptions,\n onChunk: async (chunk: any) => {\n delivered = true;\n if (chunk.type === 'finish') {\n if (isMaxStepsFinishChunk({ chunk, maxSteps: deps.maxSteps })) {\n setStreamErrors(prev => [...prev, buildMaxStepsStreamErrorMessage(chunk, deps.maxSteps)]);\n }\n await refreshThreadList?.();\n refreshTimelinePanel(deps.threadId);\n completeObservationalMemoryBuffering(deps.threadId);\n }\n if (didUpdateWorkingMemory(chunk)) {\n void refreshWorkingMemory?.();\n }\n handleHandledChunk(asHandledStreamChunk(chunk));\n },\n signal: controller.signal,\n });\n\n return true;\n }\n\n delivered = true;\n setTimeout(() => {\n void refreshThreadList?.();\n }, 500);\n refreshTimelinePanel(deps.threadId);\n completeObservationalMemoryBuffering(deps.threadId);\n return true;\n } catch (error: any) {\n console.error('Error occurred in ChatProvider', error);\n if (error.name === 'AbortError') {\n return true;\n }\n setStreamErrors(prev => [...prev, buildStreamErrorMessage({ runId: 'thrown', payload: { error } })]);\n resetObservationalMemoryStreamState();\n const stored = delivered || mayHaveBeenStored(error);\n if (!stored) {\n // The message goes back to the composer, so its context waits for the retry.\n heldContext.forEach((context, sourceId) => {\n if (!modelContextRef.current.has(sourceId)) modelContextRef.current.set(sourceId, context);\n });\n }\n return stored;\n } finally {\n abortControllerRef.current = null;\n }\n },\n [\n completeObservationalMemoryBuffering,\n handleHandledChunk,\n isRunningStream,\n refreshThreadList,\n refreshTimelinePanel,\n refreshWorkingMemory,\n resetObservationalMemoryStreamState,\n sendMessage,\n setStreamErrors,\n threadSignalsUnsupportedRef,\n ],\n );\n\n const cancel = useCallback(async () => {\n abortControllerRef.current?.abort();\n abortControllerRef.current = null;\n resetObservationalMemoryStreamState();\n cancelRun?.();\n completeObservationalMemoryBuffering(sendDepsRef.current.threadId);\n }, [cancelRun, completeObservationalMemoryBuffering, resetObservationalMemoryStreamState]);\n\n return { send, cancel, setModelContext };\n};\n"],"mappings":";;;;;;;;;;AA4CA,IAAM,wBAAwB,UAAmD;CAC/E,MAAM,OAAQ,MAA6B;CAC3C,IACE,SAAS,WACT,SAAS,+BACT,SAAS,6BACT,SAAS,gCACT,SAAS,oBACT,SAAS,sBAET,OAAO;AAGX;AA4CA,IAAM,uBAAuB,MAAgB,gBAA0C;CACrF,MAAM,yBAAyB,IAAIA,gBAAAA,eAAe;CAClD,OAAO,QAAQ;EAAE,GAAG,KAAK;EAAgB,GAAG;CAAY,CAAC,CAAC,CA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O;IAC3F,CAAC;IAEH,OAAO;GACT,UAAU;IACR,mBAAmB,UAAU;GAC/B;EACF,GACA;GACE;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF,CAWO;EAAM,SAAA,GARAL,MAAAA,YAAAA,CAAY,YAAY;GACrC,mBAAmB,SAAS,MAAM;GAClC,mBAAmB,UAAU;GAC7B,oCAAoC;GACpC,YAAY;GACZ,qCAAqC,YAAY,QAAQ,QAAQ;EACnE,GAAG;GAAC;GAAW;GAAsC;EAAmC,CAEzE;EAAQ;CAAgB;AACzC"}
|
|
@@ -182,7 +182,10 @@ var useChatSendHandler = ({ agentId, requestContext, agentVersionId, threadId, m
|
|
|
182
182
|
onChunk: async (chunk) => {
|
|
183
183
|
delivered = true;
|
|
184
184
|
if (chunk.type === "finish") {
|
|
185
|
-
if (isMaxStepsFinishChunk(
|
|
185
|
+
if (isMaxStepsFinishChunk({
|
|
186
|
+
chunk,
|
|
187
|
+
maxSteps: deps.maxSteps
|
|
188
|
+
})) setStreamErrors((prev) => [...prev, buildMaxStepsStreamErrorMessage(chunk, deps.maxSteps)]);
|
|
186
189
|
await refreshThreadList?.();
|
|
187
190
|
refreshTimelinePanel(deps.threadId);
|
|
188
191
|
completeObservationalMemoryBuffering(deps.threadId);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-chat-send-handler.es.js","names":[],"sources":["../../../../src/domains/agents/chat/use-chat-send-handler.ts"],"sourcesContent":["import type { MastraDBMessage } from '@mastra/core/agent/message-list';\nimport { RequestContext } from '@mastra/core/di';\nimport { useMastraClient } from '@mastra/react';\nimport {\n memoryStatusQueryKey,\n memoryThreadMessagesQueryKey,\n observationalMemoryQueryKey,\n} from '@mastra/react/hooks/memory';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useCallback, useRef } from 'react';\nimport type { Dispatch, SetStateAction } from 'react';\nimport {\n buildMaxStepsStreamErrorMessage,\n buildStreamErrorMessage,\n isMaxStepsFinishChunk,\n} from './stream-error-message';\nimport type { ChatSendArgs } from '@/domains/chat/context/chat-context';\nimport { injectBufferingEnds } from '@/domains/chat/om/om-parts-converter';\n\nimport { toUntrustedAppContext } from '@/utils/mcp-app-context';\n\n/**\n * The OM/error stream chunks this hook reacts to are not part of the typed\n * `useChat` chunk union, so we narrow them at the stream boundary.\n */\ntype OmStreamChunk =\n | { type: 'data-om-observation-start'; data?: { operationType?: string } }\n | { type: 'data-om-observation-end'; data?: { operationType?: string } }\n | { type: 'data-om-observation-failed'; data?: { operationType?: string } }\n | {\n type: 'data-om-status';\n data?: {\n windows?: unknown;\n recordId?: string;\n threadId?: string;\n stepNumber?: number;\n generationCount?: number;\n };\n }\n | { type: 'data-om-activation'; data?: { operationType?: string; cycleId?: string } };\n\ntype ErrorStreamChunk = { type: 'error'; runId?: string; payload?: { error?: unknown } };\ntype HandledStreamChunk = OmStreamChunk | ErrorStreamChunk;\n\nconst asHandledStreamChunk = (chunk: unknown): HandledStreamChunk | undefined => {\n const type = (chunk as { type?: unknown }).type;\n if (\n type === 'error' ||\n type === 'data-om-observation-start' ||\n type === 'data-om-observation-end' ||\n type === 'data-om-observation-failed' ||\n type === 'data-om-status' ||\n type === 'data-om-activation'\n ) {\n return chunk as HandledStreamChunk;\n }\n return undefined;\n};\n\ninterface SendDeps {\n model?: string;\n requestContext?: Record<string, any>;\n agentVersionId?: string;\n threadId?: string;\n modelSettingsArgs: Record<string, unknown>;\n chatWithNetwork?: boolean;\n chatWithGenerate?: boolean;\n maxSteps?: number;\n isOMEnabled: boolean;\n tracingOptions?: unknown;\n}\n\ninterface UseChatSendHandlerArgs {\n agentId: string;\n requestContext?: Record<string, any>;\n agentVersionId?: string;\n threadId?: string;\n modelSettingsArgs: Record<string, unknown>;\n model?: string;\n chatWithNetwork?: boolean;\n chatWithGenerate?: boolean;\n maxSteps?: number;\n isOMEnabled: boolean;\n tracingOptions?: unknown;\n threadSignalsUnsupportedRef: { current: boolean };\n isRunningStream: boolean;\n sendMessage: (args: any) => Promise<void>;\n cancelRun?: () => void;\n setMessages: Dispatch<SetStateAction<MastraDBMessage[]>>;\n setStreamErrors: Dispatch<SetStateAction<MastraDBMessage[]>>;\n refreshThreadList?: () => void | Promise<void>;\n refreshWorkingMemory?: () => void | Promise<unknown>;\n handleObservationStart: (operationType?: string) => void;\n handleProgressUpdate: (data: any) => void;\n refreshObservationalMemory: (operationType?: string) => void;\n handleActivation: (data: any) => void;\n resetObservationalMemoryStreamState: () => void;\n /** Signal the memory timeline panel to refetch (mirrors left OM sidebar freshness). */\n signalTimelineRefresh: () => void;\n}\n\nconst buildRequestContext = (deps: SendDeps, turnContext?: Record<string, unknown>) => {\n const requestContextInstance = new RequestContext();\n Object.entries({ ...deps.requestContext, ...turnContext }).forEach(([key, value]) => {\n requestContextInstance.set(key, value);\n });\n if (deps.agentVersionId) {\n requestContextInstance.set('agentVersionId', deps.agentVersionId);\n }\n return requestContextInstance;\n};\n\n/**\n * A server error (5xx) can come after the agent ran and stored the turn, as in generate mode where no\n * chunk arrives first: putting the message back in the composer would invite sending it twice. A\n * request that got no response, or that the server refused (4xx, such as a body too large), left\n * nothing behind.\n */\nconst mayHaveBeenStored = (error: unknown) => {\n const status = (error as { status?: unknown } | null)?.status;\n return typeof status === 'number' && status >= 500;\n};\n\nconst didUpdateWorkingMemory = (chunk: any) => {\n const result = chunk.payload?.result;\n return (\n (chunk.type === 'tool-result' || chunk.type === 'tool-execution-end') &&\n chunk.payload?.toolName === 'updateWorkingMemory' &&\n typeof result === 'object' &&\n result !== null &&\n 'success' in result &&\n result.success\n );\n};\n\nexport const useChatSendHandler = ({\n agentId,\n requestContext,\n agentVersionId,\n threadId,\n modelSettingsArgs,\n model,\n chatWithNetwork,\n chatWithGenerate,\n maxSteps,\n isOMEnabled,\n tracingOptions,\n threadSignalsUnsupportedRef,\n isRunningStream,\n sendMessage,\n cancelRun,\n setMessages,\n setStreamErrors,\n refreshThreadList,\n refreshWorkingMemory,\n handleObservationStart,\n handleProgressUpdate,\n refreshObservationalMemory,\n handleActivation,\n resetObservationalMemoryStreamState,\n signalTimelineRefresh,\n}: UseChatSendHandlerArgs) => {\n const baseClient = useMastraClient();\n const queryClient = useQueryClient();\n const abortControllerRef = useRef<AbortController | null>(null);\n // Latest context per source (an MCP App's tool call, for instance), carried by the next send only.\n const modelContextRef = useRef(new Map<string, string>());\n const setModelContext = useCallback((sourceId: string, context: string | undefined) => {\n if (context) {\n modelContextRef.current.set(sourceId, context);\n } else {\n modelContextRef.current.delete(sourceId);\n }\n }, []);\n const sendDepsRef = useRef<SendDeps>({\n requestContext,\n agentVersionId,\n threadId,\n modelSettingsArgs,\n model,\n chatWithNetwork,\n chatWithGenerate,\n maxSteps,\n isOMEnabled,\n tracingOptions,\n });\n sendDepsRef.current = {\n requestContext,\n agentVersionId,\n threadId,\n modelSettingsArgs,\n model,\n chatWithNetwork,\n chatWithGenerate,\n maxSteps,\n isOMEnabled,\n tracingOptions,\n };\n\n // Force an immediate refetch of the memory timeline panel (playground-ui\n // ['memory', ...] keys), scoped to the given thread, so the panel shows live\n // data right away. Runs on every chat completion regardless of whether\n // observational memory is enabled, so the thread messages and memory status\n // shown in the panel are never stale after a stream finishes.\n const refreshTimelinePanel = useCallback(\n (currentThreadId?: string) => {\n if (!currentThreadId) return;\n void queryClient.refetchQueries({ queryKey: observationalMemoryQueryKey(agentId, currentThreadId) });\n void queryClient.refetchQueries({ queryKey: memoryThreadMessagesQueryKey(currentThreadId) });\n void queryClient.refetchQueries({ queryKey: memoryStatusQueryKey(agentId, currentThreadId) });\n // Also poke the timeline panel directly. The panel resolves its own thread id\n // from the route, so it stays correct even for brand-new threads where\n // `deps.threadId` is still undefined at send time and the keyed refetch above\n // cannot target the real thread yet.\n signalTimelineRefresh();\n },\n [agentId, queryClient, signalTimelineRefresh],\n );\n\n const completeObservationalMemoryBuffering = useCallback(\n (currentThreadId?: string) => {\n if (!currentThreadId || !sendDepsRef.current.isOMEnabled) return;\n baseClient\n .awaitBufferStatus({ agentId, resourceId: agentId, threadId: currentThreadId })\n .then(result => {\n setMessages(prev => injectBufferingEnds(prev, result?.record));\n void queryClient.invalidateQueries({ queryKey: ['observational-memory', agentId] });\n void queryClient.invalidateQueries({ queryKey: ['memory-status', agentId] });\n // Refetch the panel again once buffering completes, so any records that\n // only landed after awaitBufferStatus resolved are reflected immediately.\n refreshTimelinePanel(currentThreadId);\n void refreshWorkingMemory?.();\n })\n .catch(() => {});\n },\n [agentId, baseClient, queryClient, refreshTimelinePanel, refreshWorkingMemory, setMessages],\n );\n\n const handleHandledChunk = useCallback(\n (handled: HandledStreamChunk | undefined) => {\n if (handled?.type === 'error') {\n setStreamErrors(prev => [...prev, buildStreamErrorMessage(handled)]);\n }\n if (handled?.type === 'data-om-observation-start') {\n handleObservationStart(handled.data?.operationType);\n }\n if (handled?.type === 'data-om-status') {\n handleProgressUpdate(handled.data);\n }\n if (\n handled?.type === 'data-om-observation-end' ||\n handled?.type === 'data-om-observation-failed' ||\n handled?.type === 'data-om-activation'\n ) {\n refreshObservationalMemory(handled.data?.operationType);\n }\n if (handled?.type === 'data-om-observation-end') {\n void refreshWorkingMemory?.();\n }\n if (handled?.type === 'data-om-activation') {\n handleActivation(handled.data);\n }\n },\n [\n handleActivation,\n handleObservationStart,\n handleProgressUpdate,\n refreshObservationalMemory,\n refreshWorkingMemory,\n setStreamErrors,\n ],\n );\n\n const send = useCallback(\n async ({ message, attachments = [], requestContext: turnContext }: ChatSendArgs): Promise<boolean> => {\n const deps = sendDepsRef.current;\n if (threadSignalsUnsupportedRef.current && (isRunningStream || abortControllerRef.current)) return false;\n\n setStreamErrors([]);\n const controller = new AbortController();\n abortControllerRef.current = controller;\n const requestContextInstance = buildRequestContext(deps, turnContext);\n const heldContext = new Map(modelContextRef.current);\n modelContextRef.current.clear();\n // MCP App context is third-party content: it goes in the user turn as delimited data, never in the system prompt.\n const appContext = heldContext.size\n ? [\n {\n role: 'user' as const,\n content: [{ type: 'text' as const, text: toUntrustedAppContext(heldContext.values()) }],\n },\n ]\n : [];\n const coreUserMessages = [...attachments, ...appContext];\n // An error can still be thrown once the server has the message, by a chunk handler or a refresh.\n // Those must not put the message back in the composer.\n let delivered = false;\n\n try {\n if (deps.chatWithNetwork) {\n await sendMessage({\n message,\n mode: 'network',\n coreUserMessages,\n requestContext: requestContextInstance,\n threadId: deps.threadId,\n modelSettings: deps.modelSettingsArgs,\n model: deps.model,\n signal: controller.signal,\n tracingOptions: deps.tracingOptions,\n onNetworkChunk: async (chunk: any) => {\n delivered = true;\n if (didUpdateWorkingMemory(chunk)) {\n void refreshWorkingMemory?.();\n }\n if (chunk.type === 'network-execution-event-step-finish') {\n void refreshThreadList?.();\n }\n handleHandledChunk(asHandledStreamChunk(chunk));\n },\n });\n } else if (deps.chatWithGenerate) {\n await sendMessage({\n message,\n mode: 'generate',\n coreUserMessages,\n requestContext: requestContextInstance,\n threadId: deps.threadId,\n modelSettings: deps.modelSettingsArgs,\n model: deps.model,\n signal: controller.signal,\n tracingOptions: deps.tracingOptions,\n });\n delivered = true;\n await refreshThreadList?.();\n refreshTimelinePanel(deps.threadId);\n return true;\n } else {\n await sendMessage({\n message,\n mode: 'stream',\n coreUserMessages,\n requestContext: requestContextInstance,\n threadId: deps.threadId,\n modelSettings: deps.modelSettingsArgs,\n model: deps.model,\n tracingOptions: deps.tracingOptions,\n onChunk: async (chunk: any) => {\n delivered = true;\n if (chunk.type === 'finish') {\n if (isMaxStepsFinishChunk(chunk)) {\n setStreamErrors(prev => [...prev, buildMaxStepsStreamErrorMessage(chunk, deps.maxSteps)]);\n }\n await refreshThreadList?.();\n refreshTimelinePanel(deps.threadId);\n completeObservationalMemoryBuffering(deps.threadId);\n }\n if (didUpdateWorkingMemory(chunk)) {\n void refreshWorkingMemory?.();\n }\n handleHandledChunk(asHandledStreamChunk(chunk));\n },\n signal: controller.signal,\n });\n\n return true;\n }\n\n delivered = true;\n setTimeout(() => {\n void refreshThreadList?.();\n }, 500);\n refreshTimelinePanel(deps.threadId);\n completeObservationalMemoryBuffering(deps.threadId);\n return true;\n } catch (error: any) {\n console.error('Error occurred in ChatProvider', error);\n if (error.name === 'AbortError') {\n return true;\n }\n setStreamErrors(prev => [...prev, buildStreamErrorMessage({ runId: 'thrown', payload: { error } })]);\n resetObservationalMemoryStreamState();\n const stored = delivered || mayHaveBeenStored(error);\n if (!stored) {\n // The message goes back to the composer, so its context waits for the retry.\n heldContext.forEach((context, sourceId) => {\n if (!modelContextRef.current.has(sourceId)) modelContextRef.current.set(sourceId, context);\n });\n }\n return stored;\n } finally {\n abortControllerRef.current = null;\n }\n },\n [\n completeObservationalMemoryBuffering,\n handleHandledChunk,\n isRunningStream,\n refreshThreadList,\n refreshTimelinePanel,\n refreshWorkingMemory,\n resetObservationalMemoryStreamState,\n sendMessage,\n setStreamErrors,\n threadSignalsUnsupportedRef,\n ],\n );\n\n const cancel = useCallback(async () => {\n abortControllerRef.current?.abort();\n abortControllerRef.current = null;\n resetObservationalMemoryStreamState();\n cancelRun?.();\n completeObservationalMemoryBuffering(sendDepsRef.current.threadId);\n }, [cancelRun, completeObservationalMemoryBuffering, resetObservationalMemoryStreamState]);\n\n return { send, cancel, setModelContext };\n};\n"],"mappings":";;;;;;;;;AA4CA,IAAM,wBAAwB,UAAmD;CAC/E,MAAM,OAAQ,MAA6B;CAC3C,IACE,SAAS,WACT,SAAS,+BACT,SAAS,6BACT,SAAS,gCACT,SAAS,oBACT,SAAS,sBAET,OAAO;AAGX;AA4CA,IAAM,uBAAuB,MAAgB,gBAA0C;CACrF,MAAM,yBAAyB,IAAI,eAAe;CAClD,OAAO,QAAQ;EAAE,GAAG,KAAK;EAAgB,GAAG;CAAY,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK,WAAW;EACnF,uBAAuB,IAAI,KAAK,KAAK;CACvC,CAAC;CACD,IAAI,KAAK,gBACP,uBAAuB,IAAI,kBAAkB,KAAK,cAAc;CAElE,OAAO;AACT;;;;;;;AAQA,IAAM,qBAAqB,UAAmB;CAC5C,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;QAClC,qCAAqC,KAAK,QAAQ;OACpD;OACA,IAAI,uBAAuB,KAAK,GAC9B,uBAA4B;OAE9B,mBAAmB,qBAAqB,KAAK,CAAC;MAChD;MACA,QAAQ,WAAW;KACrB,CAAC;KAED,OAAO;IACT;IAEA,YAAY;IACZ,iBAAiB;KACf,oBAAyB;IAC3B,GAAG,GAAG;IACN,qBAAqB,KAAK,QAAQ;IAClC,qCAAqC,KAAK,QAAQ;IAClD,OAAO;GACT,SAAS,OAAY;IACnB,QAAQ,MAAM,kCAAkC,KAAK;IACrD,IAAI,MAAM,SAAS,cACjB,OAAO;IAET,iBAAgB,SAAQ,CAAC,GAAG,MAAM,wBAAwB;KAAE,OAAO;KAAU,SAAS,EAAE,MAAM;IAAE,CAAC,CAAC,CAAC;IACnG,oCAAoC;IACpC,MAAM,SAAS,aAAa,kBAAkB,KAAK;IACnD,IAAI,CAAC,QAEH,YAAY,SAAS,SAAS,aAAa;KACzC,IAAI,CAAC,gBAAgB,QAAQ,IAAI,QAAQ,GAAG,gBAAgB,QAAQ,IAAI,UAAU,OAAO;IAC3F,CAAC;IAEH,OAAO;GACT,UAAU;IACR,mBAAmB,UAAU;GAC/B;EACF,GACA;GACE;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF,CAWO;EAAM,QARA,YAAY,YAAY;GACrC,mBAAmB,SAAS,MAAM;GAClC,mBAAmB,UAAU;GAC7B,oCAAoC;GACpC,YAAY;GACZ,qCAAqC,YAAY,QAAQ,QAAQ;EACnE,GAAG;GAAC;GAAW;GAAsC;EAAmC,CAEzE;EAAQ;CAAgB;AACzC"}
|
|
1
|
+
{"version":3,"file":"use-chat-send-handler.es.js","names":[],"sources":["../../../../src/domains/agents/chat/use-chat-send-handler.ts"],"sourcesContent":["import type { MastraDBMessage } from '@mastra/core/agent/message-list';\nimport { RequestContext } from '@mastra/core/di';\nimport { useMastraClient } from '@mastra/react';\nimport {\n memoryStatusQueryKey,\n memoryThreadMessagesQueryKey,\n observationalMemoryQueryKey,\n} from '@mastra/react/hooks/memory';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useCallback, useRef } from 'react';\nimport type { Dispatch, SetStateAction } from 'react';\nimport {\n buildMaxStepsStreamErrorMessage,\n buildStreamErrorMessage,\n isMaxStepsFinishChunk,\n} from './stream-error-message';\nimport type { ChatSendArgs } from '@/domains/chat/context/chat-context';\nimport { injectBufferingEnds } from '@/domains/chat/om/om-parts-converter';\n\nimport { toUntrustedAppContext } from '@/utils/mcp-app-context';\n\n/**\n * The OM/error stream chunks this hook reacts to are not part of the typed\n * `useChat` chunk union, so we narrow them at the stream boundary.\n */\ntype OmStreamChunk =\n | { type: 'data-om-observation-start'; data?: { operationType?: string } }\n | { type: 'data-om-observation-end'; data?: { operationType?: string } }\n | { type: 'data-om-observation-failed'; data?: { operationType?: string } }\n | {\n type: 'data-om-status';\n data?: {\n windows?: unknown;\n recordId?: string;\n threadId?: string;\n stepNumber?: number;\n generationCount?: number;\n };\n }\n | { type: 'data-om-activation'; data?: { operationType?: string; cycleId?: string } };\n\ntype ErrorStreamChunk = { type: 'error'; runId?: string; payload?: { error?: unknown } };\ntype HandledStreamChunk = OmStreamChunk | ErrorStreamChunk;\n\nconst asHandledStreamChunk = (chunk: unknown): HandledStreamChunk | undefined => {\n const type = (chunk as { type?: unknown }).type;\n if (\n type === 'error' ||\n type === 'data-om-observation-start' ||\n type === 'data-om-observation-end' ||\n type === 'data-om-observation-failed' ||\n type === 'data-om-status' ||\n type === 'data-om-activation'\n ) {\n return chunk as HandledStreamChunk;\n }\n return undefined;\n};\n\ninterface SendDeps {\n model?: string;\n requestContext?: Record<string, any>;\n agentVersionId?: string;\n threadId?: string;\n modelSettingsArgs: Record<string, unknown>;\n chatWithNetwork?: boolean;\n chatWithGenerate?: boolean;\n maxSteps?: number;\n isOMEnabled: boolean;\n tracingOptions?: unknown;\n}\n\ninterface UseChatSendHandlerArgs {\n agentId: string;\n requestContext?: Record<string, any>;\n agentVersionId?: string;\n threadId?: string;\n modelSettingsArgs: Record<string, unknown>;\n model?: string;\n chatWithNetwork?: boolean;\n chatWithGenerate?: boolean;\n maxSteps?: number;\n isOMEnabled: boolean;\n tracingOptions?: unknown;\n threadSignalsUnsupportedRef: { current: boolean };\n isRunningStream: boolean;\n sendMessage: (args: any) => Promise<void>;\n cancelRun?: () => void;\n setMessages: Dispatch<SetStateAction<MastraDBMessage[]>>;\n setStreamErrors: Dispatch<SetStateAction<MastraDBMessage[]>>;\n refreshThreadList?: () => void | Promise<void>;\n refreshWorkingMemory?: () => void | Promise<unknown>;\n handleObservationStart: (operationType?: string) => void;\n handleProgressUpdate: (data: any) => void;\n refreshObservationalMemory: (operationType?: string) => void;\n handleActivation: (data: any) => void;\n resetObservationalMemoryStreamState: () => void;\n /** Signal the memory timeline panel to refetch (mirrors left OM sidebar freshness). */\n signalTimelineRefresh: () => void;\n}\n\nconst buildRequestContext = (deps: SendDeps, turnContext?: Record<string, unknown>) => {\n const requestContextInstance = new RequestContext();\n Object.entries({ ...deps.requestContext, ...turnContext }).forEach(([key, value]) => {\n requestContextInstance.set(key, value);\n });\n if (deps.agentVersionId) {\n requestContextInstance.set('agentVersionId', deps.agentVersionId);\n }\n return requestContextInstance;\n};\n\n/**\n * A server error (5xx) can come after the agent ran and stored the turn, as in generate mode where no\n * chunk arrives first: putting the message back in the composer would invite sending it twice. A\n * request that got no response, or that the server refused (4xx, such as a body too large), left\n * nothing behind.\n */\nconst mayHaveBeenStored = (error: unknown) => {\n const status = (error as { status?: unknown } | null)?.status;\n return typeof status === 'number' && status >= 500;\n};\n\nconst didUpdateWorkingMemory = (chunk: any) => {\n const result = chunk.payload?.result;\n return (\n (chunk.type === 'tool-result' || chunk.type === 'tool-execution-end') &&\n chunk.payload?.toolName === 'updateWorkingMemory' &&\n typeof result === 'object' &&\n result !== null &&\n 'success' in result &&\n result.success\n );\n};\n\nexport const useChatSendHandler = ({\n agentId,\n requestContext,\n agentVersionId,\n threadId,\n modelSettingsArgs,\n model,\n chatWithNetwork,\n chatWithGenerate,\n maxSteps,\n isOMEnabled,\n tracingOptions,\n threadSignalsUnsupportedRef,\n isRunningStream,\n sendMessage,\n cancelRun,\n setMessages,\n setStreamErrors,\n refreshThreadList,\n refreshWorkingMemory,\n handleObservationStart,\n handleProgressUpdate,\n refreshObservationalMemory,\n handleActivation,\n resetObservationalMemoryStreamState,\n signalTimelineRefresh,\n}: UseChatSendHandlerArgs) => {\n const baseClient = useMastraClient();\n const queryClient = useQueryClient();\n const abortControllerRef = useRef<AbortController | null>(null);\n // Latest context per source (an MCP App's tool call, for instance), carried by the next send only.\n const modelContextRef = useRef(new Map<string, string>());\n const setModelContext = useCallback((sourceId: string, context: string | undefined) => {\n if (context) {\n modelContextRef.current.set(sourceId, context);\n } else {\n modelContextRef.current.delete(sourceId);\n }\n }, []);\n const sendDepsRef = useRef<SendDeps>({\n requestContext,\n agentVersionId,\n threadId,\n modelSettingsArgs,\n model,\n chatWithNetwork,\n chatWithGenerate,\n maxSteps,\n isOMEnabled,\n tracingOptions,\n });\n sendDepsRef.current = {\n requestContext,\n agentVersionId,\n threadId,\n modelSettingsArgs,\n model,\n chatWithNetwork,\n chatWithGenerate,\n maxSteps,\n isOMEnabled,\n tracingOptions,\n };\n\n // Force an immediate refetch of the memory timeline panel (playground-ui\n // ['memory', ...] keys), scoped to the given thread, so the panel shows live\n // data right away. Runs on every chat completion regardless of whether\n // observational memory is enabled, so the thread messages and memory status\n // shown in the panel are never stale after a stream finishes.\n const refreshTimelinePanel = useCallback(\n (currentThreadId?: string) => {\n if (!currentThreadId) return;\n void queryClient.refetchQueries({ queryKey: observationalMemoryQueryKey(agentId, currentThreadId) });\n void queryClient.refetchQueries({ queryKey: memoryThreadMessagesQueryKey(currentThreadId) });\n void queryClient.refetchQueries({ queryKey: memoryStatusQueryKey(agentId, currentThreadId) });\n // Also poke the timeline panel directly. The panel resolves its own thread id\n // from the route, so it stays correct even for brand-new threads where\n // `deps.threadId` is still undefined at send time and the keyed refetch above\n // cannot target the real thread yet.\n signalTimelineRefresh();\n },\n [agentId, queryClient, signalTimelineRefresh],\n );\n\n const completeObservationalMemoryBuffering = useCallback(\n (currentThreadId?: string) => {\n if (!currentThreadId || !sendDepsRef.current.isOMEnabled) return;\n baseClient\n .awaitBufferStatus({ agentId, resourceId: agentId, threadId: currentThreadId })\n .then(result => {\n setMessages(prev => injectBufferingEnds(prev, result?.record));\n void queryClient.invalidateQueries({ queryKey: ['observational-memory', agentId] });\n void queryClient.invalidateQueries({ queryKey: ['memory-status', agentId] });\n // Refetch the panel again once buffering completes, so any records that\n // only landed after awaitBufferStatus resolved are reflected immediately.\n refreshTimelinePanel(currentThreadId);\n void refreshWorkingMemory?.();\n })\n .catch(() => {});\n },\n [agentId, baseClient, queryClient, refreshTimelinePanel, refreshWorkingMemory, setMessages],\n );\n\n const handleHandledChunk = useCallback(\n (handled: HandledStreamChunk | undefined) => {\n if (handled?.type === 'error') {\n setStreamErrors(prev => [...prev, buildStreamErrorMessage(handled)]);\n }\n if (handled?.type === 'data-om-observation-start') {\n handleObservationStart(handled.data?.operationType);\n }\n if (handled?.type === 'data-om-status') {\n handleProgressUpdate(handled.data);\n }\n if (\n handled?.type === 'data-om-observation-end' ||\n handled?.type === 'data-om-observation-failed' ||\n handled?.type === 'data-om-activation'\n ) {\n refreshObservationalMemory(handled.data?.operationType);\n }\n if (handled?.type === 'data-om-observation-end') {\n void refreshWorkingMemory?.();\n }\n if (handled?.type === 'data-om-activation') {\n handleActivation(handled.data);\n }\n },\n [\n handleActivation,\n handleObservationStart,\n handleProgressUpdate,\n refreshObservationalMemory,\n refreshWorkingMemory,\n setStreamErrors,\n ],\n );\n\n const send = useCallback(\n async ({ message, attachments = [], requestContext: turnContext }: ChatSendArgs): Promise<boolean> => {\n const deps = sendDepsRef.current;\n if (threadSignalsUnsupportedRef.current && (isRunningStream || abortControllerRef.current)) return false;\n\n setStreamErrors([]);\n const controller = new AbortController();\n abortControllerRef.current = controller;\n const requestContextInstance = buildRequestContext(deps, turnContext);\n const heldContext = new Map(modelContextRef.current);\n modelContextRef.current.clear();\n // MCP App context is third-party content: it goes in the user turn as delimited data, never in the system prompt.\n const appContext = heldContext.size\n ? [\n {\n role: 'user' as const,\n content: [{ type: 'text' as const, text: toUntrustedAppContext(heldContext.values()) }],\n },\n ]\n : [];\n const coreUserMessages = [...attachments, ...appContext];\n // An error can still be thrown once the server has the message, by a chunk handler or a refresh.\n // Those must not put the message back in the composer.\n let delivered = false;\n\n try {\n if (deps.chatWithNetwork) {\n await sendMessage({\n message,\n mode: 'network',\n coreUserMessages,\n requestContext: requestContextInstance,\n threadId: deps.threadId,\n modelSettings: deps.modelSettingsArgs,\n model: deps.model,\n signal: controller.signal,\n tracingOptions: deps.tracingOptions,\n onNetworkChunk: async (chunk: any) => {\n delivered = true;\n if (didUpdateWorkingMemory(chunk)) {\n void refreshWorkingMemory?.();\n }\n if (chunk.type === 'network-execution-event-step-finish') {\n void refreshThreadList?.();\n }\n handleHandledChunk(asHandledStreamChunk(chunk));\n },\n });\n } else if (deps.chatWithGenerate) {\n await sendMessage({\n message,\n mode: 'generate',\n coreUserMessages,\n requestContext: requestContextInstance,\n threadId: deps.threadId,\n modelSettings: deps.modelSettingsArgs,\n model: deps.model,\n signal: controller.signal,\n tracingOptions: deps.tracingOptions,\n });\n delivered = true;\n await refreshThreadList?.();\n refreshTimelinePanel(deps.threadId);\n return true;\n } else {\n await sendMessage({\n message,\n mode: 'stream',\n coreUserMessages,\n requestContext: requestContextInstance,\n threadId: deps.threadId,\n modelSettings: deps.modelSettingsArgs,\n model: deps.model,\n tracingOptions: deps.tracingOptions,\n onChunk: async (chunk: any) => {\n delivered = true;\n if (chunk.type === 'finish') {\n if (isMaxStepsFinishChunk({ chunk, maxSteps: deps.maxSteps })) {\n setStreamErrors(prev => [...prev, buildMaxStepsStreamErrorMessage(chunk, deps.maxSteps)]);\n }\n await refreshThreadList?.();\n refreshTimelinePanel(deps.threadId);\n completeObservationalMemoryBuffering(deps.threadId);\n }\n if (didUpdateWorkingMemory(chunk)) {\n void refreshWorkingMemory?.();\n }\n handleHandledChunk(asHandledStreamChunk(chunk));\n },\n signal: controller.signal,\n });\n\n return true;\n }\n\n delivered = true;\n setTimeout(() => {\n void refreshThreadList?.();\n }, 500);\n refreshTimelinePanel(deps.threadId);\n completeObservationalMemoryBuffering(deps.threadId);\n return true;\n } catch (error: any) {\n console.error('Error occurred in ChatProvider', error);\n if (error.name === 'AbortError') {\n return true;\n }\n setStreamErrors(prev => [...prev, buildStreamErrorMessage({ runId: 'thrown', payload: { error } })]);\n resetObservationalMemoryStreamState();\n const stored = delivered || mayHaveBeenStored(error);\n if (!stored) {\n // The message goes back to the composer, so its context waits for the retry.\n heldContext.forEach((context, sourceId) => {\n if (!modelContextRef.current.has(sourceId)) modelContextRef.current.set(sourceId, context);\n });\n }\n return stored;\n } finally {\n abortControllerRef.current = null;\n }\n },\n [\n completeObservationalMemoryBuffering,\n handleHandledChunk,\n isRunningStream,\n refreshThreadList,\n refreshTimelinePanel,\n refreshWorkingMemory,\n resetObservationalMemoryStreamState,\n sendMessage,\n setStreamErrors,\n threadSignalsUnsupportedRef,\n ],\n );\n\n const cancel = useCallback(async () => {\n abortControllerRef.current?.abort();\n abortControllerRef.current = null;\n resetObservationalMemoryStreamState();\n cancelRun?.();\n completeObservationalMemoryBuffering(sendDepsRef.current.threadId);\n }, [cancelRun, completeObservationalMemoryBuffering, resetObservationalMemoryStreamState]);\n\n return { send, cancel, setModelContext };\n};\n"],"mappings":";;;;;;;;;AA4CA,IAAM,wBAAwB,UAAmD;CAC/E,MAAM,OAAQ,MAA6B;CAC3C,IACE,SAAS,WACT,SAAS,+BACT,SAAS,6BACT,SAAS,gCACT,SAAS,oBACT,SAAS,sBAET,OAAO;AAGX;AA4CA,IAAM,uBAAuB,MAAgB,gBAA0C;CACrF,MAAM,yBAAyB,IAAI,eAAe;CAClD,OAAO,QAAQ;EAAE,GAAG,KAAK;EAAgB,GAAG;CA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ACzC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stateless-widget.cjs.js","names":["preparedGate"],"sources":["../../../../src/domains/dashboards/components/stateless-widget.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\nimport type { DashboardScope, OnDashboardDrilldown } from '../lib/definition';\nimport type { DashboardEnvironment } from '../lib/gate';\nimport { preparedGate } from '../lib/plan-widget';\nimport type { ReadyPreparedWidget } from '../lib/plan-widget';\nimport type { DashboardResult } from '../lib/requests';\nimport type { DashboardAlert, DashboardExpand, WidgetState } from '../widget-kind';\nimport type { MetricsCardDragHandleProps } from '@/ds/components/MetricsCard';\n\nexport type StatelessWidgetProps = {\n /** The widget as `prepareWidget` parsed it. */\n prepared: ReadyPreparedWidget;\n /** The page's window, filters and aggregate gates. */\n env: DashboardEnvironment;\n /** What the user picked on the widget; `{}` for its defaults. */\n state: WidgetState;\n onStateChange: (next: WidgetState) => void;\n /** Answers to `planWidget`'s `discover` requests, in order; missing ones are still loading. */\n discovered?: (DashboardResult | undefined)[];\n /** Answers to `planWidget`'s `requests`, in order; missing ones are still loading. */\n results?: (DashboardResult | undefined)[];\n /** Asks the host to send the failed requests again. */\n onRetry: () => void;\n scope: DashboardScope;\n onDrilldown?: OnDashboardDrilldown;\n expand?: DashboardExpand;\n dragHandle?: MetricsCardDragHandleProps;\n /**\n * Makes the card's title editable in place, and is called with the trimmed new title when the\n * user changes it (Enter or blur; Escape reverts). The host stores it and passes the widget back\n * with its new `title`.
|
|
1
|
+
{"version":3,"file":"stateless-widget.cjs.js","names":["preparedGate"],"sources":["../../../../src/domains/dashboards/components/stateless-widget.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\nimport type { DashboardScope, OnDashboardDrilldown } from '../lib/definition';\nimport type { DashboardEnvironment } from '../lib/gate';\nimport { preparedGate } from '../lib/plan-widget';\nimport type { ReadyPreparedWidget } from '../lib/plan-widget';\nimport type { DashboardResult } from '../lib/requests';\nimport type { DashboardAlert, DashboardExpand, WidgetState } from '../widget-kind';\nimport type { MetricsCardDragHandleProps } from '@/ds/components/MetricsCard';\n\nexport type StatelessWidgetProps = {\n /** The widget as `prepareWidget` parsed it. */\n prepared: ReadyPreparedWidget;\n /** The page's window, filters and aggregate gates. */\n env: DashboardEnvironment;\n /** What the user picked on the widget; `{}` for its defaults. */\n state: WidgetState;\n onStateChange: (next: WidgetState) => void;\n /** Answers to `planWidget`'s `discover` requests, in order; missing ones are still loading. */\n discovered?: (DashboardResult | undefined)[];\n /** Answers to `planWidget`'s `requests`, in order; missing ones are still loading. */\n results?: (DashboardResult | undefined)[];\n /** Asks the host to send the failed requests again. */\n onRetry: () => void;\n scope: DashboardScope;\n onDrilldown?: OnDashboardDrilldown;\n expand?: DashboardExpand;\n dragHandle?: MetricsCardDragHandleProps;\n /**\n * Makes the card's title editable in place, and is called with the trimmed new title when the\n * user changes it (Enter or blur; Escape reverts). The host stores it and passes the widget back\n * with its new `title`. KPI groups have no title.\n */\n onTitleChange?: (title: string) => void;\n /** The card's Create alert button; see `DashboardAlert`. */\n alert?: DashboardAlert;\n /**\n * The host's buttons on the card, after its own: `MetricsCard.Action`s, each deciding whether it\n * waits for the card's hover (e.g. `onCardHover`) or stays in view.\n */\n actions?: ReactNode;\n};\n\n/**\n * One widget drawn from what it is given: it holds no state, fetches nothing and has no effects.\n * The host plans its requests with `planWidget`, sends them however it can, and passes the answers\n * back; picks on the widget come back through `onStateChange`.\n */\nexport function StatelessWidget({ prepared, env, discovered = [], results = [], ...props }: StatelessWidgetProps) {\n const gate = preparedGate(prepared, env, props.state);\n if (gate.status === 'hidden') return null;\n return (\n <prepared.kind.component\n {...props}\n widget={prepared.widget}\n views={prepared.views}\n gate={gate}\n comparisonLabel={env.comparisonLabel}\n projectLabel={env.projectLabel}\n discovered={discovered}\n results={results}\n />\n );\n}\n"],"mappings":";;;;;;;;;AA+CA,SAAgB,gBAAgB,EAAE,UAAU,KAAK,aAAa,CAAC,GAAG,UAAU,CAAC,GAAG,GAAG,SAA+B;CAChH,MAAM,OAAOA,2CAAAA,aAAa,UAAU,KAAK,MAAM,KAAK;CACpD,IAAI,KAAK,WAAW,UAAU,OAAO;CACrC,OACE,iBAAA,GAAA,kBAAA,IAAA,CAAC,SAAS,KAAK,WAAf;EACE,GAAI;EACJ,QAAQ,SAAS;EACjB,OAAO,SAAS;EACV;EACN,iBAAiB,IAAI;EACrB,cAAc,IAAI;EACN;EACH;CACV,CAAA;AAEL"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stateless-widget.es.js","names":[],"sources":["../../../../src/domains/dashboards/components/stateless-widget.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\nimport type { DashboardScope, OnDashboardDrilldown } from '../lib/definition';\nimport type { DashboardEnvironment } from '../lib/gate';\nimport { preparedGate } from '../lib/plan-widget';\nimport type { ReadyPreparedWidget } from '../lib/plan-widget';\nimport type { DashboardResult } from '../lib/requests';\nimport type { DashboardAlert, DashboardExpand, WidgetState } from '../widget-kind';\nimport type { MetricsCardDragHandleProps } from '@/ds/components/MetricsCard';\n\nexport type StatelessWidgetProps = {\n /** The widget as `prepareWidget` parsed it. */\n prepared: ReadyPreparedWidget;\n /** The page's window, filters and aggregate gates. */\n env: DashboardEnvironment;\n /** What the user picked on the widget; `{}` for its defaults. */\n state: WidgetState;\n onStateChange: (next: WidgetState) => void;\n /** Answers to `planWidget`'s `discover` requests, in order; missing ones are still loading. */\n discovered?: (DashboardResult | undefined)[];\n /** Answers to `planWidget`'s `requests`, in order; missing ones are still loading. */\n results?: (DashboardResult | undefined)[];\n /** Asks the host to send the failed requests again. */\n onRetry: () => void;\n scope: DashboardScope;\n onDrilldown?: OnDashboardDrilldown;\n expand?: DashboardExpand;\n dragHandle?: MetricsCardDragHandleProps;\n /**\n * Makes the card's title editable in place, and is called with the trimmed new title when the\n * user changes it (Enter or blur; Escape reverts). The host stores it and passes the widget back\n * with its new `title`.
|
|
1
|
+
{"version":3,"file":"stateless-widget.es.js","names":[],"sources":["../../../../src/domains/dashboards/components/stateless-widget.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\nimport type { DashboardScope, OnDashboardDrilldown } from '../lib/definition';\nimport type { DashboardEnvironment } from '../lib/gate';\nimport { preparedGate } from '../lib/plan-widget';\nimport type { ReadyPreparedWidget } from '../lib/plan-widget';\nimport type { DashboardResult } from '../lib/requests';\nimport type { DashboardAlert, DashboardExpand, WidgetState } from '../widget-kind';\nimport type { MetricsCardDragHandleProps } from '@/ds/components/MetricsCard';\n\nexport type StatelessWidgetProps = {\n /** The widget as `prepareWidget` parsed it. */\n prepared: ReadyPreparedWidget;\n /** The page's window, filters and aggregate gates. */\n env: DashboardEnvironment;\n /** What the user picked on the widget; `{}` for its defaults. */\n state: WidgetState;\n onStateChange: (next: WidgetState) => void;\n /** Answers to `planWidget`'s `discover` requests, in order; missing ones are still loading. */\n discovered?: (DashboardResult | undefined)[];\n /** Answers to `planWidget`'s `requests`, in order; missing ones are still loading. */\n results?: (DashboardResult | undefined)[];\n /** Asks the host to send the failed requests again. */\n onRetry: () => void;\n scope: DashboardScope;\n onDrilldown?: OnDashboardDrilldown;\n expand?: DashboardExpand;\n dragHandle?: MetricsCardDragHandleProps;\n /**\n * Makes the card's title editable in place, and is called with the trimmed new title when the\n * user changes it (Enter or blur; Escape reverts). The host stores it and passes the widget back\n * with its new `title`. KPI groups have no title.\n */\n onTitleChange?: (title: string) => void;\n /** The card's Create alert button; see `DashboardAlert`. */\n alert?: DashboardAlert;\n /**\n * The host's buttons on the card, after its own: `MetricsCard.Action`s, each deciding whether it\n * waits for the card's hover (e.g. `onCardHover`) or stays in view.\n */\n actions?: ReactNode;\n};\n\n/**\n * One widget drawn from what it is given: it holds no state, fetches nothing and has no effects.\n * The host plans its requests with `planWidget`, sends them however it can, and passes the answers\n * back; picks on the widget come back through `onStateChange`.\n */\nexport function StatelessWidget({ prepared, env, discovered = [], results = [], ...props }: StatelessWidgetProps) {\n const gate = preparedGate(prepared, env, props.state);\n if (gate.status === 'hidden') return null;\n return (\n <prepared.kind.component\n {...props}\n widget={prepared.widget}\n views={prepared.views}\n gate={gate}\n comparisonLabel={env.comparisonLabel}\n projectLabel={env.projectLabel}\n discovered={discovered}\n results={results}\n />\n );\n}\n"],"mappings":";;;;;;;;AA+CA,SAAgB,gBAAgB,EAAE,UAAU,KAAK,aAAa,CAAC,GAAG,UAAU,CAAC,GAAG,GAAG,SAA+B;CAChH,MAAM,OAAO,aAAa,UAAU,KAAK,MAAM,KAAK;CACpD,IAAI,KAAK,WAAW,UAAU,OAAO;CACrC,OACE,oBAAC,SAAS,KAAK,WAAf;EACE,GAAI;EACJ,QAAQ,SAAS;EACjB,OAAO,SAAS;EACV;EACN,iBAAiB,IAAI;EACrB,cAAc,IAAI;EACN;EACH;CACV,CAAA;AAEL"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_domains_dashboards_lib_view_labels = require("../lib/view-labels.cjs.js");
|
|
3
|
+
const require_tabs_tab = require("../../../tabs-tab-DX3gEvH2.cjs");
|
|
4
|
+
let react_jsx_runtime = require("react/jsx-runtime");
|
|
5
|
+
// src/domains/dashboards/components/view-tabs.tsx
|
|
6
|
+
/**
|
|
7
|
+
* A widget's views as pill tabs under its title, each one click away; what doesn't fit folds into a
|
|
8
|
+
* "+N" menu. Picking one swaps at once: the pill doesn't slide, as the body under it doesn't fade.
|
|
9
|
+
*/
|
|
10
|
+
function ViewTabs({ labels, index, onChoose }) {
|
|
11
|
+
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_tabs_tab.Tabs, {
|
|
12
|
+
value: String(index),
|
|
13
|
+
defaultTab: String(index),
|
|
14
|
+
onValueChange: (value) => onChoose(Number(value)),
|
|
15
|
+
className: "min-w-0 grow overflow-visible",
|
|
16
|
+
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_tabs_tab.TabList, {
|
|
17
|
+
variant: "pill",
|
|
18
|
+
size: "sm",
|
|
19
|
+
overflow: "menu",
|
|
20
|
+
className: "[&_[data-slot=tabs-indicator]]:transition-none",
|
|
21
|
+
children: require_domains_dashboards_lib_view_labels.shortViewLabels(labels).map((label, i) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_tabs_tab.Tab, {
|
|
22
|
+
value: String(i),
|
|
23
|
+
children: label
|
|
24
|
+
}, i))
|
|
25
|
+
})
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
exports.ViewTabs = ViewTabs;
|
|
29
|
+
|
|
30
|
+
//# sourceMappingURL=view-tabs.cjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"view-tabs.cjs.js","names":["Tabs","TabList","shortViewLabels","Tab"],"sources":["../../../../src/domains/dashboards/components/view-tabs.tsx"],"sourcesContent":["import { shortViewLabels } from '../lib/view-labels';\nimport { Tab, TabList, Tabs } from '@/ds/components/Tabs';\n\ntype ViewTabsProps = {\n /** Every view's full name, in order; the tabs show them without their shared words. */\n labels: readonly string[];\n /** The open view. */\n index: number;\n onChoose: (index: number) => void;\n};\n\n/**\n * A widget's views as pill tabs under its title, each one click away; what doesn't fit folds into a\n * \"+N\" menu. Picking one swaps at once: the pill doesn't slide, as the body under it doesn't fade.\n */\nexport function ViewTabs({ labels, index, onChoose }: ViewTabsProps) {\n return (\n <Tabs\n value={String(index)}\n defaultTab={String(index)}\n onValueChange={value => onChoose(Number(value))}\n // Grows into the toolbar's free space, so folding measures the room beside a legend.\n className=\"min-w-0 grow overflow-visible\"\n >\n <TabList variant=\"pill\" size=\"sm\" overflow=\"menu\" className=\"[&_[data-slot=tabs-indicator]]:transition-none\">\n {shortViewLabels(labels).map((label, i) => (\n <Tab key={i} value={String(i)}>\n {label}\n </Tab>\n ))}\n </TabList>\n </Tabs>\n );\n}\n"],"mappings":";;;;;;;;;AAeA,SAAgB,SAAS,EAAE,QAAQ,OAAO,YAA2B;CACnE,OACE,iBAAA,GAAA,kBAAA,IAAA,CAACA,iBAAAA,MAAD;EACE,OAAO,OAAO,KAAK;EACnB,YAAY,OAAO,KAAK;EACxB,gBAAe,UAAS,SAAS,OAAO,KAAK,CAAC;EAE9C,WAAU;EAEV,UAAA,iBAAA,GAAA,kBAAA,IAAA,CAACC,iBAAAA,SAAD;GAAS,SAAQ;GAAO,MAAK;GAAK,UAAS;GAAO,WAAU;GACzD,UAAAC,2CAAAA,gBAAgB,MAAM,CAAC,CAAC,KAAK,OAAO,MACnC,iBAAA,GAAA,kBAAA,IAAA,CAACC,iBAAAA,KAAD;IAAa,OAAO,OAAO,CAAC;IACzB,UAAA;GACE,GAFK,CAEL,CACN;EACM,CAAA;CACL,CAAA;AAEV"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from '../../../src/domains/dashboards/components/view-tabs';
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { shortViewLabels } from "../lib/view-labels.es.js";
|
|
2
|
+
import { n as Tabs, r as TabList, t as Tab } from "../../../tabs-tab-BbkJy1dq.js";
|
|
3
|
+
import { jsx } from "react/jsx-runtime";
|
|
4
|
+
// src/domains/dashboards/components/view-tabs.tsx
|
|
5
|
+
/**
|
|
6
|
+
* A widget's views as pill tabs under its title, each one click away; what doesn't fit folds into a
|
|
7
|
+
* "+N" menu. Picking one swaps at once: the pill doesn't slide, as the body under it doesn't fade.
|
|
8
|
+
*/
|
|
9
|
+
function ViewTabs({ labels, index, onChoose }) {
|
|
10
|
+
return /* @__PURE__ */ jsx(Tabs, {
|
|
11
|
+
value: String(index),
|
|
12
|
+
defaultTab: String(index),
|
|
13
|
+
onValueChange: (value) => onChoose(Number(value)),
|
|
14
|
+
className: "min-w-0 grow overflow-visible",
|
|
15
|
+
children: /* @__PURE__ */ jsx(TabList, {
|
|
16
|
+
variant: "pill",
|
|
17
|
+
size: "sm",
|
|
18
|
+
overflow: "menu",
|
|
19
|
+
className: "[&_[data-slot=tabs-indicator]]:transition-none",
|
|
20
|
+
children: shortViewLabels(labels).map((label, i) => /* @__PURE__ */ jsx(Tab, {
|
|
21
|
+
value: String(i),
|
|
22
|
+
children: label
|
|
23
|
+
}, i))
|
|
24
|
+
})
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
export { ViewTabs };
|
|
28
|
+
|
|
29
|
+
//# sourceMappingURL=view-tabs.es.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"view-tabs.es.js","names":[],"sources":["../../../../src/domains/dashboards/components/view-tabs.tsx"],"sourcesContent":["import { shortViewLabels } from '../lib/view-labels';\nimport { Tab, TabList, Tabs } from '@/ds/components/Tabs';\n\ntype ViewTabsProps = {\n /** Every view's full name, in order; the tabs show them without their shared words. */\n labels: readonly string[];\n /** The open view. */\n index: number;\n onChoose: (index: number) => void;\n};\n\n/**\n * A widget's views as pill tabs under its title, each one click away; what doesn't fit folds into a\n * \"+N\" menu. Picking one swaps at once: the pill doesn't slide, as the body under it doesn't fade.\n */\nexport function ViewTabs({ labels, index, onChoose }: ViewTabsProps) {\n return (\n <Tabs\n value={String(index)}\n defaultTab={String(index)}\n onValueChange={value => onChoose(Number(value))}\n // Grows into the toolbar's free space, so folding measures the room beside a legend.\n className=\"min-w-0 grow overflow-visible\"\n >\n <TabList variant=\"pill\" size=\"sm\" overflow=\"menu\" className=\"[&_[data-slot=tabs-indicator]]:transition-none\">\n {shortViewLabels(labels).map((label, i) => (\n <Tab key={i} value={String(i)}>\n {label}\n </Tab>\n ))}\n </TabList>\n </Tabs>\n );\n}\n"],"mappings":";;;;;;;;AAeA,SAAgB,SAAS,EAAE,QAAQ,OAAO,YAA2B;CACnE,OACE,oBAAC,MAAD;EACE,OAAO,OAAO,KAAK;EACnB,YAAY,OAAO,KAAK;EACxB,gBAAe,UAAS,SAAS,OAAO,KAAK,CAAC;EAE9C,WAAU;EAEV,UAAA,oBAAC,SAAD;GAAS,SAAQ;GAAO,MAAK;GAAK,UAAS;GAAO,WAAU;GACzD,UAAA,gBAAgB,MAAM,CAAC,CAAC,KAAK,OAAO,MACnC,oBAAC,KAAD;IAAa,OAAO,OAAO,CAAC;IACzB,UAAA;GACE,GAFK,CAEL,CACN;EACM,CAAA;CACL,CAAA;AAEV"}
|
|
@@ -1,19 +1,37 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_domains_dashboards_components_view_tabs = require("../components/view-tabs.cjs.js");
|
|
2
3
|
const require_domains_dashboards_lib_chrome = require("../lib/chrome.cjs.js");
|
|
3
4
|
const require_domains_dashboards_lib_definition = require("../lib/definition.cjs.js");
|
|
4
5
|
let react = require("react");
|
|
5
|
-
|
|
6
|
+
let react_jsx_runtime = require("react/jsx-runtime");
|
|
7
|
+
// src/domains/dashboards/hooks/use-widget-views.tsx
|
|
6
8
|
/**
|
|
7
|
-
* The
|
|
8
|
-
* (`
|
|
9
|
-
|
|
9
|
+
* The card heading for the open view: the widget's title, with several views as tabs under it
|
|
10
|
+
* (`toolbar`). With somewhere to expand to, the title stays alone instead, and `ExpandAction` links there.
|
|
11
|
+
*/
|
|
12
|
+
function viewTitle(widget, views, index, onChoose, expand) {
|
|
13
|
+
if (expand?.href(widget)) return { title: widget.title?.trim() ? widget.title : require_domains_dashboards_lib_chrome.viewLabel(views[0]?.label, 0) };
|
|
14
|
+
if (views.length < 2) return { title: widget.title ?? "" };
|
|
15
|
+
return {
|
|
16
|
+
title: widget.title ?? "",
|
|
17
|
+
toolbar: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_domains_dashboards_components_view_tabs.ViewTabs, {
|
|
18
|
+
labels: views.map((v, i) => require_domains_dashboards_lib_chrome.viewLabel(v.label, i)),
|
|
19
|
+
index,
|
|
20
|
+
onChoose
|
|
21
|
+
})
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The open view of a widget, `wanted` when it has one (else the first), and the card heading for it
|
|
26
|
+
* (`title`, and with several views their tabs as `toolbar`, unless the widget has somewhere to
|
|
27
|
+
* `expand` to) to spread into `ChartCard`; picking a view calls `onChoose`.
|
|
10
28
|
*/
|
|
11
29
|
function viewMenu(widget, views, wanted, onChoose, expand) {
|
|
12
30
|
const index = views[wanted] ? wanted : 0;
|
|
13
31
|
return {
|
|
14
32
|
view: views[index] ?? views[0],
|
|
15
33
|
index,
|
|
16
|
-
heading:
|
|
34
|
+
heading: viewTitle(widget, views, index, onChoose, expand)
|
|
17
35
|
};
|
|
18
36
|
}
|
|
19
37
|
/** `viewMenu` with the open view held here: `defaultIndex` until one is picked. */
|
|
@@ -36,5 +54,6 @@ exports.hasDrilldownAction = hasDrilldownAction;
|
|
|
36
54
|
exports.useDrilldown = useDrilldown;
|
|
37
55
|
exports.useViewMenu = useViewMenu;
|
|
38
56
|
exports.viewMenu = viewMenu;
|
|
57
|
+
exports.viewTitle = viewTitle;
|
|
39
58
|
|
|
40
59
|
//# sourceMappingURL=use-widget-views.cjs.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-widget-views.cjs.js","names":["
|
|
1
|
+
{"version":3,"file":"use-widget-views.cjs.js","names":["viewLabel","ViewTabs","useState","viewDrilldown","targetScope"],"sources":["../../../../src/domains/dashboards/hooks/use-widget-views.tsx"],"sourcesContent":["import type { DashboardWidget, DashboardWidgetView } from '@mastra/client-js';\nimport { useState } from 'react';\nimport type { DrilldownScope } from '../../metrics/drilldown';\nimport { ViewTabs } from '../components/view-tabs';\nimport { viewLabel } from '../lib/chrome';\nimport type { ViewHeading } from '../lib/chrome';\nimport { viewDrilldown, targetScope } from '../lib/definition';\nimport type { OnDashboardDrilldown } from '../lib/definition';\nimport type { DashboardExpand, ResolvedView } from '../widget-kind';\n\n/**\n * The card heading for the open view: the widget's title, with several views as tabs under it\n * (`toolbar`). With somewhere to expand to, the title stays alone instead, and `ExpandAction` links there.\n */\nexport function viewTitle(\n widget: DashboardWidget,\n views: readonly DashboardWidgetView[],\n index: number,\n onChoose: (index: number) => void,\n expand?: DashboardExpand,\n): ViewHeading {\n if (expand?.href(widget)) {\n // The card and its expand link need a name: a blank title falls back to the first view's label.\n return { title: widget.title?.trim() ? widget.title : viewLabel(views[0]?.label, 0) };\n }\n if (views.length < 2) return { title: widget.title ?? '' };\n return {\n title: widget.title ?? '',\n toolbar: <ViewTabs labels={views.map((v, i) => viewLabel(v.label, i))} index={index} onChoose={onChoose} />,\n };\n}\n\nexport type Views<Options> = readonly [ResolvedView<Options>, ...ResolvedView<Options>[]];\n\n/**\n * The open view of a widget, `wanted` when it has one (else the first), and the card heading for it\n * (`title`, and with several views their tabs as `toolbar`, unless the widget has somewhere to\n * `expand` to) to spread into `ChartCard`; picking a view calls `onChoose`.\n */\nexport function viewMenu<Options>(\n widget: DashboardWidget,\n views: Views<Options>,\n wanted: number,\n onChoose: (index: number) => void,\n expand?: DashboardExpand,\n) {\n const index = views[wanted] ? wanted : 0;\n return { view: views[index] ?? views[0], index, heading: viewTitle(widget, views, index, onChoose, expand) };\n}\n\n/** `viewMenu` with the open view held here: `defaultIndex` until one is picked. */\nexport function useViewMenu<Options>(\n widget: DashboardWidget,\n views: Views<Options>,\n defaultIndex = 0,\n expand?: DashboardExpand,\n) {\n const [chosen, choose] = useState<number>();\n return viewMenu(widget, views, chosen ?? defaultIndex, choose, expand);\n}\n\n/** What clicking a bucket or row opens, with what was clicked; `undefined` when the view has no click target. */\nexport function useDrilldown(\n widget: DashboardWidget,\n view: DashboardWidgetView,\n onDrilldown: OnDashboardDrilldown | undefined,\n) {\n const { click } = viewDrilldown(widget, view);\n if (!onDrilldown || !click) return undefined;\n return (clicked: DrilldownScope) => onDrilldown(click.page, { ...targetScope(click), ...clicked });\n}\n\n/** Whether the view has an action button to show (`DrilldownAction`). */\nexport const hasDrilldownAction = (\n widget: DashboardWidget,\n view: DashboardWidgetView,\n onDrilldown: OnDashboardDrilldown | undefined,\n) => onDrilldown !== undefined && viewDrilldown(widget, view).action !== undefined;\n"],"mappings":";;;;;;;;;;;AAcA,SAAgB,U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.es.js";
|
|
2
|
+
import { viewLabel } from "../lib/chrome.es.js";
|
|
2
3
|
import { targetScope, viewDrilldown } from "../lib/definition.es.js";
|
|
3
4
|
import { useState } from "react";
|
|
4
|
-
|
|
5
|
+
import { jsx } from "react/jsx-runtime";
|
|
6
|
+
// src/domains/dashboards/hooks/use-widget-views.tsx
|
|
5
7
|
/**
|
|
6
|
-
* The
|
|
7
|
-
* (`
|
|
8
|
-
|
|
8
|
+
* The card heading for the open view: the widget's title, with several views as tabs under it
|
|
9
|
+
* (`toolbar`). With somewhere to expand to, the title stays alone instead, and `ExpandAction` links there.
|
|
10
|
+
*/
|
|
11
|
+
function viewTitle(widget, views, index, onChoose, expand) {
|
|
12
|
+
if (expand?.href(widget)) return { title: widget.title?.trim() ? widget.title : viewLabel(views[0]?.label, 0) };
|
|
13
|
+
if (views.length < 2) return { title: widget.title ?? "" };
|
|
14
|
+
return {
|
|
15
|
+
title: widget.title ?? "",
|
|
16
|
+
toolbar: /* @__PURE__ */ jsx(ViewTabs, {
|
|
17
|
+
labels: views.map((v, i) => viewLabel(v.label, i)),
|
|
18
|
+
index,
|
|
19
|
+
onChoose
|
|
20
|
+
})
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* The open view of a widget, `wanted` when it has one (else the first), and the card heading for it
|
|
25
|
+
* (`title`, and with several views their tabs as `toolbar`, unless the widget has somewhere to
|
|
26
|
+
* `expand` to) to spread into `ChartCard`; picking a view calls `onChoose`.
|
|
9
27
|
*/
|
|
10
28
|
function viewMenu(widget, views, wanted, onChoose, expand) {
|
|
11
29
|
const index = views[wanted] ? wanted : 0;
|
|
@@ -31,6 +49,6 @@ function useDrilldown(widget, view, onDrilldown) {
|
|
|
31
49
|
}
|
|
32
50
|
/** Whether the view has an action button to show (`DrilldownAction`). */
|
|
33
51
|
var hasDrilldownAction = (widget, view, onDrilldown) => onDrilldown !== void 0 && viewDrilldown(widget, view).action !== void 0;
|
|
34
|
-
export { hasDrilldownAction, useDrilldown, useViewMenu, viewMenu };
|
|
52
|
+
export { hasDrilldownAction, useDrilldown, useViewMenu, viewMenu, viewTitle };
|
|
35
53
|
|
|
36
54
|
//# sourceMappingURL=use-widget-views.es.js.map
|