@mastra/react 1.15.1-alpha.3 → 1.15.1-alpha.5

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.
@@ -2,9 +2,10 @@ import { n as useMastraClient } from "../../mastra-client-context-DQ5z_ze9.js";
2
2
  import { t as useInView } from "../../use-in-view-ChEDWwE1.js";
3
3
  import { t as getOrCreate } from "../../map-5-4U5rwA.js";
4
4
  import { n as is403ForbiddenError } from "../../query-utils-DvMERIwf.js";
5
- import { t as getFeedbackRefetchInterval } from "../../feedback-refetch-interval-C12Nzb2r.js";
5
+ import { t as getFeedbackRefetchInterval } from "../../feedback-refetch-interval-D7vqhO1C.js";
6
6
  import { MastraClient, MastraClientError } from "@mastra/client-js";
7
- import { useEffect, useMemo, useRef, useState } from "react";
7
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
8
+ import { v4 } from "@lukeed/uuid";
8
9
  import { keepPreviousData, queryOptions, skipToken, useInfiniteQuery, useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
9
10
  import { EntityType } from "@mastra/core/observability";
10
11
  // src/hooks/traces/discovery-cache.ts
@@ -1219,33 +1220,173 @@ const useTraces = ({ filters, listMode = "traces", polling = {}, enabled = true,
1219
1220
  recentlyAddedKeys
1220
1221
  };
1221
1222
  };
1223
+ // src/hooks/feedback/optimistic-feedback.ts
1224
+ /** How long a pending comment stays visible if the server never returns it (e.g. a lost write). */
1225
+ const OPTIMISTIC_FEEDBACK_TTL_MS = 6e4;
1226
+ const NO_PENDING = [];
1227
+ const pendingFeedbackKey = (traceId, spanId) => [
1228
+ "feedback-optimistic",
1229
+ traceId,
1230
+ spanId || null
1231
+ ];
1232
+ function removePendingFeedback(queryClient, traceId, spanId, shouldRemove) {
1233
+ queryClient.setQueryData(pendingFeedbackKey(traceId, spanId), (entries) => {
1234
+ if (!entries) return entries;
1235
+ const kept = entries.filter((entry) => !shouldRemove(entry));
1236
+ return kept.length === entries.length ? entries : kept;
1237
+ });
1238
+ }
1239
+ function addPendingFeedback(queryClient, { traceId, spanId, item }) {
1240
+ queryClient.setQueryData(pendingFeedbackKey(traceId, spanId), (entries = []) => [...entries.filter((entry) => entry.item.feedbackId !== item.feedbackId), {
1241
+ item,
1242
+ expiresAt: Date.now() + OPTIMISTIC_FEEDBACK_TTL_MS
1243
+ }]);
1244
+ }
1245
+ function discardPendingFeedback(queryClient, { traceId, spanId, feedbackId }) {
1246
+ removePendingFeedback(queryClient, traceId, spanId, (entry) => entry.item.feedbackId === feedbackId);
1247
+ }
1248
+ const timeOf = (item) => new Date(item.timestamp).getTime();
1249
+ /**
1250
+ * Prepends pending comments the server does not return yet (newest first, flagged `isPending`)
1251
+ * and counts them in the total.
1252
+ */
1253
+ function mergePendingFeedback(data, pending) {
1254
+ if (pending.length === 0) return data;
1255
+ const serverIds = new Set(data.feedback.map((item) => item.feedbackId));
1256
+ const missing = pending.filter((item) => !serverIds.has(item.feedbackId)).sort((a, b) => timeOf(b) - timeOf(a)).map((item) => ({
1257
+ ...item,
1258
+ isPending: true
1259
+ }));
1260
+ if (missing.length === 0) return data;
1261
+ return {
1262
+ ...data,
1263
+ feedback: [...missing, ...data.feedback],
1264
+ ...data.pagination ? { pagination: {
1265
+ ...data.pagination,
1266
+ total: data.pagination.total + missing.length
1267
+ } } : {}
1268
+ };
1269
+ }
1270
+ /** Stops tracking pending comments once a fetched first page returns them. */
1271
+ function settlePendingFeedback(queryClient, { traceId, spanId }, data) {
1272
+ const serverIds = new Set(data.feedback.map((item) => item.feedbackId));
1273
+ removePendingFeedback(queryClient, traceId, spanId, (entry) => serverIds.has(entry.item.feedbackId));
1274
+ }
1275
+ /** Pending comments for a trace (no `spanId`) or a span, to merge into the first page of its list. */
1276
+ function usePendingFeedback({ traceId, spanId, enabled }) {
1277
+ const queryClient = useQueryClient();
1278
+ const queryKey = pendingFeedbackKey(traceId, spanId);
1279
+ const { data: entries } = useQuery({
1280
+ queryKey,
1281
+ queryFn: () => queryClient.getQueryData(queryKey) ?? [],
1282
+ enabled: false,
1283
+ staleTime: Infinity,
1284
+ gcTime: OPTIMISTIC_FEEDBACK_TTL_MS
1285
+ });
1286
+ useEffect(() => {
1287
+ if (!entries?.length) return;
1288
+ const nextExpiry = Math.min(...entries.map((entry) => entry.expiresAt));
1289
+ const timer = setTimeout(() => removePendingFeedback(queryClient, traceId, spanId, (entry) => entry.expiresAt <= Date.now()), Math.max(0, nextExpiry - Date.now()));
1290
+ return () => clearTimeout(timer);
1291
+ }, [
1292
+ entries,
1293
+ queryClient,
1294
+ traceId,
1295
+ spanId
1296
+ ]);
1297
+ return useMemo(() => enabled && entries?.length ? entries.map((entry) => entry.item) : NO_PENDING, [enabled, entries]);
1298
+ }
1222
1299
  // src/hooks/traces/use-create-feedback.tsx
1223
1300
  /**
1224
- * Submits a free-text comment as a feedback record, scoped to the trace or to a
1225
- * single span, then invalidates the matching feedback list so it refreshes.
1301
+ * Identity generated per submit, so the optimistic comment (added in onMutate) and the posted
1302
+ * record (sent in mutationFn) share one feedbackId. TanStack passes the same variables object
1303
+ * to every callback and retry of a mutation run; `mutate` copies the caller's variables so a
1304
+ * reused object still gets a fresh identity on each submit.
1305
+ *
1306
+ * The timestamp comes from the client clock, so a skewed clock can order a pending comment
1307
+ * differently from how the server later sorts the stored one.
1308
+ */
1309
+ const identities = /* @__PURE__ */ new WeakMap();
1310
+ function identityFor(variables) {
1311
+ let identity = identities.get(variables);
1312
+ if (!identity) {
1313
+ identity = {
1314
+ feedbackId: v4(),
1315
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1316
+ };
1317
+ identities.set(variables, identity);
1318
+ }
1319
+ return identity;
1320
+ }
1321
+ /**
1322
+ * Submits a free-text comment as a feedback record, scoped to the trace or to a single span.
1323
+ * The comment shows up right away in `useTraceFeedback` / `useSpanFeedback`, is removed again
1324
+ * if the submit fails, and the matching feedback list is invalidated on success.
1325
+ *
1326
+ * Caller `onMutate`, `onError` and `onSuccess` run in addition to this behavior, not instead of it.
1226
1327
  */
1227
1328
  const useCreateFeedback = ({ traceId, spanId, contextMode, feedbackUserId, queryOptions }) => {
1228
1329
  const client = useMastraClient();
1229
1330
  const queryClient = useQueryClient();
1230
- return useMutation({
1231
- mutationFn: ({ text }) => client.createFeedback({
1331
+ const mutation = useMutation({
1332
+ mutationFn: (variables) => client.createFeedback({
1232
1333
  ...contextMode !== void 0 ? { contextMode } : {},
1233
1334
  feedback: {
1335
+ ...identityFor(variables),
1234
1336
  traceId,
1235
1337
  ...spanId ? { spanId } : {},
1236
1338
  ...feedbackUserId !== void 0 ? { feedbackUserId } : {},
1237
1339
  feedbackType: "comment",
1238
1340
  feedbackSource: "user",
1239
- value: text
1341
+ value: variables.text
1240
1342
  }
1241
1343
  }),
1242
- onSuccess: () => queryClient.invalidateQueries({ queryKey: spanId ? [
1243
- "span-feedback",
1244
- traceId,
1245
- spanId
1246
- ] : ["trace-feedback", traceId] }),
1247
- ...queryOptions
1344
+ ...queryOptions,
1345
+ onMutate: (...args) => {
1346
+ const [variables] = args;
1347
+ const { feedbackId, timestamp } = identityFor(variables);
1348
+ addPendingFeedback(queryClient, {
1349
+ traceId,
1350
+ spanId,
1351
+ item: {
1352
+ feedbackId,
1353
+ timestamp,
1354
+ traceId,
1355
+ ...spanId ? { spanId } : {},
1356
+ ...feedbackUserId !== void 0 ? { feedbackUserId } : {},
1357
+ feedbackType: "comment",
1358
+ feedbackSource: "user",
1359
+ value: variables.text,
1360
+ reviewStatus: "needs-review"
1361
+ }
1362
+ });
1363
+ return queryOptions?.onMutate?.(...args);
1364
+ },
1365
+ onError: (...args) => {
1366
+ const [, variables] = args;
1367
+ discardPendingFeedback(queryClient, {
1368
+ traceId,
1369
+ spanId,
1370
+ feedbackId: identityFor(variables).feedbackId
1371
+ });
1372
+ return queryOptions?.onError?.(...args);
1373
+ },
1374
+ onSuccess: async (...args) => {
1375
+ await Promise.all([queryClient.invalidateQueries({ queryKey: spanId ? [
1376
+ "span-feedback",
1377
+ traceId,
1378
+ spanId
1379
+ ] : ["trace-feedback", traceId] }), queryOptions?.onSuccess?.(...args)]);
1380
+ }
1248
1381
  });
1382
+ const { mutate: mutateRun, mutateAsync: mutateAsyncRun } = mutation;
1383
+ const mutate = useCallback((variables, options) => mutateRun({ ...variables }, options), [mutateRun]);
1384
+ const mutateAsync = useCallback((variables, options) => mutateAsyncRun({ ...variables }, options), [mutateAsyncRun]);
1385
+ return {
1386
+ ...mutation,
1387
+ mutate,
1388
+ mutateAsync
1389
+ };
1249
1390
  };
1250
1391
  // src/hooks/traces/use-delete-feedback.tsx
1251
1392
  /**
@@ -1269,12 +1410,25 @@ const useDeleteFeedback = ({ traceId, spanId, queryOptions }) => {
1269
1410
  /**
1270
1411
  * Feedback scoped to a single span. Both identifiers are required: without a `spanId`
1271
1412
  * the query stays disabled rather than falling back to trace-wide feedback.
1413
+ * The first page also shows comments submitted through `useCreateFeedback` that the server
1414
+ * does not return yet (feedback writes are eventually consistent on Mastra Platform).
1272
1415
  *
1273
1416
  * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.
1274
1417
  */
1275
1418
  const useSpanFeedback = ({ traceId = "", spanId = "", page, queryOptions }) => {
1276
1419
  const client = useMastraClient();
1420
+ const queryClient = useQueryClient();
1277
1421
  const pageNumber = page ?? 0;
1422
+ const pending = usePendingFeedback({
1423
+ traceId,
1424
+ spanId,
1425
+ enabled: pageNumber === 0
1426
+ });
1427
+ const { select: callerSelect, ...restQueryOptions } = queryOptions ?? {};
1428
+ const select = useCallback((data) => {
1429
+ const merged = mergePendingFeedback(data, pending);
1430
+ return callerSelect ? callerSelect(merged) : merged;
1431
+ }, [pending, callerSelect]);
1278
1432
  return useQuery({
1279
1433
  queryKey: [
1280
1434
  "span-feedback",
@@ -1282,62 +1436,85 @@ const useSpanFeedback = ({ traceId = "", spanId = "", page, queryOptions }) => {
1282
1436
  spanId,
1283
1437
  pageNumber
1284
1438
  ],
1285
- queryFn: () => client.listFeedback({
1286
- filters: {
1439
+ queryFn: async ({ signal }) => {
1440
+ const data = await client.listFeedback({
1441
+ filters: {
1442
+ traceId,
1443
+ spanId
1444
+ },
1445
+ pagination: {
1446
+ page: pageNumber,
1447
+ perPage: 10
1448
+ }
1449
+ });
1450
+ if (pageNumber === 0 && !signal.aborted) settlePendingFeedback(queryClient, {
1287
1451
  traceId,
1288
1452
  spanId
1289
- },
1290
- pagination: {
1291
- page: pageNumber,
1292
- perPage: 10
1293
- }
1294
- }),
1295
- refetchInterval: getFeedbackRefetchInterval,
1453
+ }, data);
1454
+ return data;
1455
+ },
1456
+ select,
1457
+ refetchInterval: (query) => getFeedbackRefetchInterval(query, pending.length > 0),
1296
1458
  gcTime: 0,
1297
1459
  staleTime: 0,
1298
- ...queryOptions
1460
+ ...restQueryOptions
1299
1461
  });
1300
1462
  };
1301
1463
  // src/hooks/traces/use-trace-feedback.tsx
1302
- /** Loads a page of trace-level feedback and stops polling when storage cannot serve feedback. */
1303
1464
  /**
1465
+ * Loads a page of trace-level feedback and stops polling when storage cannot serve feedback.
1466
+ * The first page also shows comments submitted through `useCreateFeedback` that the server
1467
+ * does not return yet (feedback writes are eventually consistent on Mastra Platform).
1468
+ *
1304
1469
  * Does not guard on empty ids; pass `queryOptions: { enabled }` to skip the fetch.
1305
1470
  */
1306
1471
  const useTraceFeedback = ({ traceId = "", page, queryOptions }) => {
1307
1472
  const client = useMastraClient();
1473
+ const queryClient = useQueryClient();
1308
1474
  const pageNumber = page ?? 0;
1475
+ const pending = usePendingFeedback({
1476
+ traceId,
1477
+ enabled: pageNumber === 0
1478
+ });
1479
+ const { select: callerSelect, ...restQueryOptions } = queryOptions ?? {};
1480
+ const select = useCallback((data) => {
1481
+ const merged = mergePendingFeedback(data, pending);
1482
+ const feedback = merged.feedback.filter((item) => !item.spanId);
1483
+ const traceLevel = merged.pagination ? {
1484
+ ...merged,
1485
+ feedback,
1486
+ pagination: {
1487
+ ...merged.pagination,
1488
+ total: feedback.length
1489
+ }
1490
+ } : {
1491
+ ...merged,
1492
+ feedback
1493
+ };
1494
+ return callerSelect ? callerSelect(traceLevel) : traceLevel;
1495
+ }, [pending, callerSelect]);
1309
1496
  return useQuery({
1310
1497
  queryKey: [
1311
1498
  "trace-feedback",
1312
1499
  traceId,
1313
1500
  pageNumber
1314
1501
  ],
1315
- queryFn: () => client.listFeedback({
1316
- filters: { traceId },
1317
- pagination: {
1318
- page: pageNumber,
1319
- perPage: 10
1320
- }
1321
- }),
1322
- select: (data) => {
1323
- const feedback = data.feedback.filter((item) => !item.spanId);
1324
- if (!data.pagination) return {
1325
- ...data,
1326
- feedback
1327
- };
1328
- return {
1329
- ...data,
1330
- feedback,
1502
+ queryFn: async ({ signal }) => {
1503
+ const data = await client.listFeedback({
1504
+ filters: { traceId },
1331
1505
  pagination: {
1332
- ...data.pagination,
1333
- total: feedback.length
1506
+ page: pageNumber,
1507
+ perPage: 10
1334
1508
  }
1335
- };
1509
+ });
1510
+ if (pageNumber === 0 && !signal.aborted) settlePendingFeedback(queryClient, { traceId }, data);
1511
+ return data;
1336
1512
  },
1337
- refetchInterval: getFeedbackRefetchInterval,
1513
+ select,
1514
+ refetchInterval: (query) => getFeedbackRefetchInterval(query, pending.length > 0),
1338
1515
  gcTime: 0,
1339
1516
  staleTime: 0,
1340
- ...queryOptions
1517
+ ...restQueryOptions
1341
1518
  });
1342
1519
  };
1343
1520
  // src/hooks/traces/use-trace-metadata-filter-fields.ts