mirror of
https://github.com/mastra-ai/mastra.git
synced 2026-11-17 08:44:46 +00:00
23,235 commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
d60ba71be0 | chore: version - exit prerelease mode @mastra/agent-builder@1.2.1 @mastra/ai-sdk@1.12.0 @mastra/arize@1.3.30 @mastra/arthur@0.4.30 @mastra/auth-cloud@1.2.9 @mastra/auth-neon@0.3.6 @mastra/auth-okta@0.3.0 @mastra/auth-studio@1.4.0 @mastra/auth-supabase@1.2.0 @mastra/auth-workos@1.6.9 @mastra/auth@1.2.0 @mastra/braintrust@1.3.27 @mastra/clickhouse@1.30.0 @mastra/client-js@1.60.0 @mastra/code-sdk@1.19.0 @mastra/connect@1.4.0 @mastra/convex@1.9.0 @mastra/core@1.83.0 @mastra/datadog@1.4.22 @mastra/deepeval@0.1.24 @mastra/deployer-cloud@1.83.0 @mastra/deployer-cloudflare@1.2.42 @mastra/deployer-netlify@1.2.42 @mastra/deployer-sandbox@0.3.27 @mastra/deployer-vercel@1.2.42 @mastra/deployer@1.83.0 @mastra/discord@1.3.4 @mastra/docker@0.14.0 @mastra/dsql@1.5.7 @mastra/duckdb@1.19.0 @mastra/dynamodb@1.5.1 @mastra/e2b-desktop@0.1.13 @mastra/e2b@0.17.0 @mastra/editor@0.17.1 @mastra/elysia@0.1.23 @mastra/express@1.5.27 @mastra/factory@0.28.0 @mastra/fastembed@1.3.7 @mastra/fastify@1.5.27 @mastra/gcs@0.3.6 @mastra/hono@1.7.25 @mastra/inngest@1.11.2 @mastra/koa@1.7.27 @mastra/laminar@1.3.32 @mastra/lance@1.6.1 @mastra/langfuse@1.6.6 @mastra/langsmith@1.4.3 @mastra/libsql@1.30.0 @mastra/longmemeval@1.1.42 @mastra/mcp-apps-components@0.1.0 @mastra/mcp-docs-server@1.3.13 @mastra/mcp@2.9.0 @mastra/memory@1.41.1 @mastra/mongodb@1.27.0 @mastra/mysql@0.17.0 @mastra/nestjs@0.3.0 @mastra/next@0.2.41 @mastra/observability@1.24.0 @mastra/opencode@0.1.42 @mastra/otel-bridge@1.5.22 @mastra/otel-exporter@1.5.2 @mastra/pg@1.36.0 @mastra/platform-workspace@1.13.0 @mastra/playground-ui@69.0.0 @mastra/posthog@1.4.7 @mastra/rag@2.8.0 @mastra/react@1.15.0 @mastra/redis-streams@0.8.1 @mastra/redis@1.4.13 @mastra/schema-compat@1.4.0 @mastra/sentry@1.2.32 @mastra/server-adapters-test-suite@0.3.0 @mastra/server@1.83.0 @mastra/slack@1.9.0 @mastra/spanner@1.12.0 @mastra/tanstack-start@0.2.41 @mastra/teams@0.1.5 @mastra/temporal@0.6.0 @mastra/turso@0.1.21 @mastra/upstash@1.6.1 @mastra/valkey-streams@0.6.2 @mastra/valkey@0.2.9 @mastra/vectorize@1.1.5 @mastra/voice-deepgram@0.13.4 @mastra/voice-google-gemini-live@0.14.19 @mastra/voice-openai-realtime@0.14.9 @mastra/voice-xai-realtime@0.2.18 create-factory@0.4.3 create-mastra@1.39.0 mastra@1.39.0 mastracode@0.50.0 @mastra/auth-auth0@1.3.0 @mastra/auth-better-auth@1.1.11 @mastra/auth-clerk@1.4.0 | ||
|
|
5c87442ed7 |
chore: version packages (alpha) (#30203)
This PR was opened by the [Changesets release](https://github.com/changesets/action) GitHub action. When you're ready to do a release, you can merge this and publish to npm yourself or [setup this action to publish automatically](https://github.com/changesets/action#with-publishing). If you're not ready to do a release yet, that's fine, whenever you add more changesets to main, this PR will be updated. ⚠️⚠️⚠️⚠️⚠️⚠️ `main` is currently in **pre mode** so this branch has prereleases rather than normal releases. If you want to exit prereleases, run `changeset pre exit` on `main`. ⚠️⚠️⚠️⚠️⚠️⚠️ # Releases > The changelog information of each package has been omitted from this message, as the content exceeds the size limit. ## @mastra/auth-auth0@1.3.0-alpha.0 ## @mastra/auth-clerk@1.4.0-alpha.0 ## @mastra/auth-okta@0.3.0-alpha.0 ## @mastra/auth-supabase@1.2.0-alpha.0 ## @mastra/client-js@1.60.0-alpha.13 ## @mastra/auth@1.2.0-alpha.0 ## @mastra/core@1.83.0-alpha.13 ## @mastra/playground-ui@69.0.0-alpha.15 ## @mastra/rag@2.8.0-alpha.3 ## @mastra/server@1.83.0-alpha.13 ## @mastra/server-adapters-test-suite@0.3.0-alpha.5 ## @mastra/auth-better-auth@1.1.11-alpha.2 ## @mastra/auth-cloud@1.2.9-alpha.0 ## @mastra/auth-neon@0.3.6-alpha.1 ## @mastra/auth-workos@1.6.9-alpha.0 ## @mastra/discord@1.3.4-alpha.0 ## @mastra/react@1.15.0-alpha.13 ## @mastra/deployer-cloud@1.83.0-alpha.13 ## @mastra/deployer-cloudflare@1.2.42-alpha.3 ## @mastra/deployer-netlify@1.2.42-alpha.1 ## @mastra/deployer-sandbox@0.3.27-alpha.1 ## @mastra/deployer-vercel@1.2.42-alpha.1 ## @mastra/longmemeval@1.1.42-alpha.13 ## @mastra/opencode@0.1.42-alpha.13 ## @mastra/factory@0.28.0-alpha.15 ## create-factory@0.4.3-alpha.15 ## @mastra/code-sdk@1.19.0-alpha.15 ## mastracode@0.50.0-alpha.14 ## @mastra/agent-builder@1.2.1-alpha.5 ## mastra@1.39.0-alpha.15 ## @mastra/connect@1.4.0-alpha.6 ## @mastra/deployer@1.83.0-alpha.13 ## @mastra/editor@0.17.1-alpha.7 ## @mastra/mcp@2.9.0-alpha.5 ## @mastra/mcp-docs-server@1.3.13-alpha.17 ## @mastra/memory@1.41.1-alpha.5 ## @mastra/schema-compat@1.4.0-alpha.2 ## @mastra/elysia@0.1.23-alpha.13 ## @mastra/express@1.5.27-alpha.13 ## @mastra/fastify@1.5.27-alpha.13 ## @mastra/hono@1.7.25-alpha.13 ## @mastra/koa@1.7.27-alpha.13 ## @mastra/nestjs@0.3.0-alpha.13 ## @mastra/next@0.2.41-alpha.13 ## @mastra/tanstack-start@0.2.41-alpha.13 ## @mastra/voice-google-gemini-live@0.14.19-alpha.2 ## @mastra/voice-openai-realtime@0.14.9-alpha.3 ## @mastra/voice-xai-realtime@0.2.18-alpha.2 ## @mastra/inngest@1.11.2-alpha.9 ## @mastra/temporal@0.6.0-alpha.13 ## create-mastra@1.39.0-alpha.15 ## @internal/playground@1.39.0-alpha.15 Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
ef2c03fc12 |
test(factory): fix Triage switch-credentials test (#30234)
## Summary
`dispatcher-switch-credentials.scenario.test.ts > moves a card by intake
route after switching its bound session as the session owner` fails on
every full `UNIT Test (Shard 1)` run on `main`. This PR points the
test's setup at a Work board that has a Triage column. Only the test
changes.
## Root cause
- [#29901](https://github.com/mastra-ai/mastra/pull/29901) (merged Nov
10, 22:12 UTC) removed Triage from the default Work board. The default
phases are now `intake, planning, execute, pr-review, done, canceled`.
Tests that need Triage use `createTriageWorkRegistry()` from
`boards/test-utils.ts`.
- [#30179](https://github.com/mastra-ai/mastra/pull/30179) added this
scenario on a branch based on `
|
||
|
|
4cc8167698 |
feat(factory-ui): one-page onboarding that explains every dead end (#30173)
**─────── TLDR ───────** > Factory onboarding becomes one page with Codebase, Work, Accounts and Model sections, and every dead end along the way now says why and offers a way out — including the GitHub App installed on a personal account shared by a team. ## Behavior **Setup flow** ├─ **was** a multi-step wizard with a separate review step └─ **now** one page; finished sections collapse to a summary with Change, Accounts asks who pays for model usage, Model shows the accounts that answer needs, Create factory sits under the cards **GitHub App on a personal account, org with 2+ members** ├─ **was** "GitHub App installed" success toast, then the same Connect button again, forever └─ **now** warning in Codebase: "Factory can’t use this GitHub installation", explains personal accounts only work for one-member orgs (pending invitations count), offers Choose another account and Refresh, can't be dismissed; driven by Platform's `hiddenPersonalInstallReason`, now passed through `/web/github/status` as `reason: 'personal_install_hidden'`, so it shows on every visit, not only right after the install. Another usable installation still reports `ready` Related: #28624 adds Share with this factory for this case. That needs mastra-ai/platform#3953 and #3983, both still open, so it stays a draft and rebases onto this PR. **Install refused by Platform** ├─ **was** generic "GitHub connection failed" toast └─ **now** inline reason with its real fix: preexisting install → the organization's Settings → General page in Platform (`/orgs/:orgId/settings/general`), where an admin chooses Refresh accounts, then Refresh; Mastra account linked to another GitHub user, or not signed in to Platform → Platform, then Connect GitHub again; Factory account that isn't a Mastra account → Sign out; already-used link → info notice with Refresh; other refusals → Connect GitHub again **GitHub callback while GitLab is connected or drafted** ├─ **was** landed on the GitLab tab with a GitHub notice above GitLab repos, and dismissing the notice or clicking Connect flipped the tab to GitLab └─ **now** the opening tab is decided once: GitHub for a callback, else the drafted repo's host, else the connected one; it doesn't move until the user switches. Choosing a repository clears the GitHub result, so Change codebase reopens on the chosen repo's host (before, a GitLab pick reopened on GitHub with Continue disabled) **Install reported, status finds nothing usable** ├─ **was** always blamed a personal account, even when status itself failed (5xx/401) └─ **now** neutral "Factory can’t see this GitHub installation yet" only when status really says `not_connected`; a failed status shows Retry instead **GitHub status request fails / session expired** ├─ **was** looked like "not connected" and offered a Connect that would fail └─ **now** "Couldn't load GitHub status." with Retry; a 401 offers Sign in, which returns to `/onboarding`; Retry shows a spinner while it runs **Back from GitHub without finishing** ├─ **was** Connect stayed stuck on "Redirecting…" (bfcache restore) └─ **now** button resets on pageshow **No repositories / refresh fails** ├─ **was** empty list blamed repository access even when the load failed; refresh errors were silent └─ **now** empty list points to Manage access, load and refresh failures show their error with Retry, a pending approval request stays up until new repos appear **Create factory disabled** ├─ **was** greyed out with no reason └─ **now** a line above it names, per account, whether a provider or a model is missing ("Connect your account for sessions to create your factory."), linked with aria-describedby; on mobile it lives in the pinned bar **Cancelled API key or sign-in dialog** ├─ **was** the cancelled provider stayed selected, dropping the working one and disabling Create └─ **now** a provider is selected only once its key or sign-in succeeds **Saved provider no longer usable** ├─ **was** a saved provider without a model, or one deleted from the list, reopened as a blank picker └─ **now** says the connection changed, or that the provider is no longer available, and asks to choose another **Member locked to personal accounts adds a custom provider** ├─ **was** the new provider unlocked the company account and the answer silently flipped to Company account └─ **now** the personal-accounts answer is saved with the choice; disabled providers say only an admin can connect them **Member, gateway offered, company provider already connected** ├─ **was** opened on a gateway they can't connect └─ **new** opens on Your own provider; the gateway button explains only an admin can connect it **Sign out from onboarding** └─ **new** account menu (themes + Sign out) and the `person_not_platform_user` recovery share one sign-out that clears the saved onboarding draft **Personal default still loading** ├─ **was** the personal catalog could arrive first, so Create offered a fallback model and would overwrite the saved personal default └─ **now** no model is suggested, and Create stays off, until the personal default answers **Account answer changed during a personal gateway connect** ├─ **was** switching to hybrid mid-connect let the late result select the gateway on a lane that can't use it └─ **now** the account answer is locked until the connection settles **Linear status down** ├─ **was** the Work summary said "Set up later" └─ **now** it says "Couldn't check connections" **Hybrid Model summary** ├─ **was** the collapsed row showed only the company model └─ **now** shows both, work then sessions ## Decisions 1. **Personal-account warning is status-driven.** Platform reports why it withheld a personal install, so the notice keys off `reason: 'personal_install_hidden'` and persists across visits; the post-install guess uses neutral copy because `connected: false` alone doesn't prove the cause. 2. **Onboarding shows GitHub results inline, never as toasts.** The callback is read once into page state (`callbackResult`), so the notice survives re-renders and has room for a reason plus an action. A usable install gets no message: the repository list is the feedback. Settings keeps its toasts. 3. **Select a provider only after its credential succeeds.** Cancelling must never cost the user a provider that already worked. ## Not verified - [ ] The Slack thread about shared personal accounts couldn't be read; the scenario was reconstructed from Platform's `github-app.ts` - [ ] The `/orgs/:orgId/settings/general` link: Platform's main routes it to `General`, which shows Refresh accounts to writers outside customer cloud; not clicked through live - [ ] Real Platform round trip for each `github_app_error` code (verified with mocked callbacks only) - [ ] Direct GitHub mode: it never reads `?github=error`, so refusals there still show nothing (server follow-up) - [ ] GitLab / Jira / incident.io connect failures remain toast-only (follow-up) - [ ] A pending approval request notice is lost on reload (the callback is read from the URL once) - [ ] Create errors still use client strings like "Failed to create Factory (403)"; server message not surfaced (follow-up) ## Diff - **source** ████████████████████ +3315 −1802 - **tests** ██████████████ +2268 −1083 - **changeset** █ +17 −0 - **docs** █ +9 −5 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ELI5: Factory setup used to be a multi-step wizard. Now it is one page with four sections: Codebase, Work, Accounts, and Model. Each section explains what is wrong when setup cannot continue, and it offers a fix. ## Summary This pull request replaces the multi-step Factory onboarding wizard with a single page. The page has four sections: Codebase, Work, Accounts, and Model. **Onboarding page and flow** - `OnboardingPage` reads the GitHub callback result once and renders `GitHubAppCallbackHandler` in inline mode. It passes the result to `EmptyFactoryState`. - `FactoryOnboarding` renders the single-page flow. It restores a persisted step and draft, and it forces factory model scope for local setups. - `onboardingSteps.ts` defines the section model. Steps are `vcs`, `project-management`, and `model`. Several step helpers are removed. - `onboardingFlow.ts` changes the draft shape. It adds `workConfirmed`, adds `onboardingCreateReadiness`, and renames `OnboardingModelChoice` to `OnboardingDraftModel`. - `createBlockedReason.ts` returns the reason that creation is blocked. **Removed components** - The wizard steps are deleted: `InitialFactoryStep`, `MastraGatewayOption`, `ModelProviderFactoryStep`, `ModelProviderPicker`, `PersonalProviderFactoryStep`, `OnboardingProgress`, `OnboardingReviewRow`, `OnboardingReviewStep`, `OnboardingSetupStep`, and `OnboardingWorkReviewRow`. - Their MSW test file `ModelProviderFactoryStep.msw.test.tsx` is deleted. **GitHub callback handling** - `GitHubAppCallbackHandler.tsx` exports `GitHubAppCallbackResult` and `callbackResult`. It has an `inline` mode that suppresses toasts. - `githubCallbackRecovery.ts` maps callback codes to a Platform page and a next action. It also reports whether the callback awaits access. **New onboarding components** (under `onboarding/`) - Layout and rows: `OnboardingStepCard`, `OnboardingStepRow`, `OnboardingCodebaseRow`, `OnboardingWorkRow`, `OnboardingWorkDoneRow`, `OnboardingModelRow`, `OnboardingAccountsRow`, `OnboardingInset`, `OnboardingPageAction`, `OnboardingSlot`, `OnboardingSearchInset`. - Account and model: `OnboardingModelSection`, `OnboardingAccountLanes`, `OnboardingAccountLane`, `OnboardingAccountHeading`, `OnboardingLaneProvider`, `OnboardingLaneStatus`, `OnboardingProviderPicker`, `OnboardingProviderOptions`, `OnboardingProviderOption`, `OnboardingProviderSummary`, `OnboardingScopeChoice`, `OnboardingConnectGatewayButton`, `OnboardingGatewaySummary`. - Source control: `OnboardingGithubHostRow`, `OnboardingGitlabHostRow`, `OnboardingHostRecoveryAction`, `OnboardingGithubNotice`, `OnboardingRepositoryRows`, `OnboardingRepositoryError`. - Other: `OnboardingCreateNotice`, `OnboardingAccountMenu`, `OnboardingAccountsPreview` (now takes `showModels`). **Hooks and services** - `useAccountSource`, `useOnboardingModelLane`, and `useOnboardingModelSetup` manage account source, model lanes, and the combined setup. - `useProviderConnection` adds `selectedProviderId`, `retrying`, and a selection-change callback. `closeKeyDialog` now receives `saved`. - `useProviderModels` adds `retrying` and gates queries on connection state. - `useWorkSourceConnectionsStatus` adds `isPending` and `isError`. - `sourceControlHosts.ts` adds host types and unavailable-reason helpers. - `onboardingSignOut.ts` adds `signOutOfOnboarding`. - `accountName.ts` adds `accountName`. `SidebarSettingsLink` uses it. **Settings and other UI** - `AddApiKeyDialog` and `ProviderConnectionDialogs` pass `saved: boolean` to `onClose`. - `VcsFactoryStep` adds GitHub callback props and a GitHub/GitLab segmented control. It adds repository refresh and retry handling. - `ProjectManagementFactoryStep` uses the new step card. - `FactoryDefaultModelForm` takes `scope` and `lane` props. - `OnboardingConnectionRow` replaces `connected` and `compact` with `tone`. - `onboarding.css` adds fold and card animation. `onboarding-preview.css` removes the mobile responsive layout. **Platform personal-install status (`mastracode/factory`)** - `integration.ts` adds the `personal_install_hidden` status. It reads `hiddenPersonalInstallReason` from Platform and treats `null` as absent. - Status is `personal_install_hidden` when no usable installation exists and Platform reports a hidden personal installation. A usable installation yields `ready`. - `integration.test.ts` adds parameterized tests for both cases. - The changeset `factory-github-personal-install-status.md` documents this as a patch release for `@mastra/factory`. - The changeset `factory-onboarding-one-page.md` documents the one-page onboarding as a `mastra` patch. **Tests** - New `OnboardingModelSection.msw.test.tsx` (1060 lines) covers provider, gateway, custom-provider, and admin cases. - `EmptyFactoryState.msw.test.tsx`, `VcsFactoryStep.msw.test.tsx`, and `GitHubAppCallbackHandler.msw.test.tsx` are rewritten for the new flow. - Shared fixture `modelSection.tsx` adds `renderModelSection` and provider helpers. - New `onboardingSteps.test.ts` covers step selection and restoration. **Not verified** - The PR description lists these items as not verified or deferred: - Live Platform round trips for each `github_app_error` code. - Direct GitHub mode refusals. - Failures for other integrations. - Approval notices after reload. - Server messages for create errors. - The Settings link to the Refresh accounts button was not tested live. The author cites Platform routing as the basis for the link. **Author-reported checks** - The author reports factory-ui typecheck and lint as clean. - The author reports 671/671 unit tests passing, and 628/628 for workspaces, settings, and root-route MSW tests. - These results come from the PR comments. This summary did not run them. **Review scope** - 96 files changed. 5609 lines added and 2890 removed, from the pull request diff. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local> |
||
|
|
18168d518c |
feat(playground): show the built-in MCP server in Studio (#29932)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
cac0f555ff |
fix(factory-ui): explain failed board loads and type the sidebar's status rows (#29983)
## Description **─────── TLDR ───────** > When the board list can't load, the sidebar now shows a properly typed error row with a Retry button instead of a big unstyled sentence. The page shows the design system's error illustration for what actually went wrong, plus a way to recover. The Boards and Phases sidebar sections rendered "Unable to load boards." and "Unable to load phases." as bare `<li>`/`<p>` text with no text role, so they fell back to the browser's default 16px type. The board pages showed a lone ⊘ with no reason and no action. The app's query client also sets `retry: false` and `refetchOnWindowFocus: false`, so a single failed request (a 500, a deploy restart, a dropped connection) stayed on screen until a full reload. ### Before / after **Board page, catalog request returns 500** | Before | After | |---|---| |  |  | **Board settings, board request returns 500** | Before | After | |---|---| |  |  | **Each failure gets its own illustration and next step** (unreachable · 404 · 401 · 429)  <details><summary>Light theme, and the empty catalog</summary>   </details> ### Behavior changed the Boards and Phases sidebar sections when loading fails ├─ **was** — "Unable to load boards." in the browser's default type, nothing to click └─ **now** — "Couldn’t load boards" in the nav-row type, aligned under the section header, with a Retry icon in the header-action column the board page, the board landing page and board settings when loading fails ├─ **was** — ⊘ and "Unable to load boards.", only a reload helps └─ **now** — the `EmptyState` illustration for the failure, one sentence about it, and Try again (Sign in for an expired session) which illustration └─ **new** — server unreachable → `disconnected` · 401 → `locked` + Sign in · 403/404 → `not-a-member` · 429 → `rate-limited` · anything else → `server-error` "No boards installed." ├─ **was** — bare text in the sidebar and at the top of the landing page └─ **now** — a muted nav-row note in the sidebar, a centered `EmptyState` on the page the Sessions section's error and empty rows └─ **now** — the same shared rows: `meta` → `label` type, Retry as an icon, aligned with the header; still no alert role ### Decisions - **the "Loading…" in the default face**: nothing visible renders that way today. Every sidebar loading state is `SidebarNavigationSkeleton`, and the remaining "Loading…" strings already use `Txt`. The bare-text rows were the error and empty states, and this PR fixes all of them (boards, phases, landing). - **no lint rule for bare text**: a rule can't tell a bare `<li>Unable…</li>` apart from a `<span>` that a Button or menu item styles. `SidebarLoadError` and `SidebarEmptyNote` are the guard instead. - **art chosen by HTTP status**: follows the pairings in the `EmptyState` "error illustrations" story. - **404 → `not-a-member`**: the catalog only returns 404 when the factory isn't in the caller's organization, and there is no "not found" illustration. - **Retry is an icon in the sidebar**: a labelled button truncated "Couldn’t load boa…" at the default sidebar width. The icon matches the section header's `+` and filter buttons, and the accessible name stays "Retry". - **the server's message isn't shown**: 5xx bodies are "Internal Server Error" or machine codes, so the copy is written per failure kind instead. - **Sessions keeps failing quietly**: Boards and Phases already rendered their failure as `role="alert"`, and they keep it. Sessions never did, so the shared row takes `announce={false}` there instead of adding an alert to every page. ### Shape changed new in `@internal/factory-ui` (`src/ui/ui/LoadErrorState.tsx`) `LoadErrorState` · `SidebarLoadError` · `SidebarEmptyNote` · `describeLoadFailure` ### Verified - screenshots are from the real app on Vite in Chromium, with Playwright fulfilling the API and forcing the board catalog to fail - the 8 new MSW tests fail against `main` and pass here; they cover retry recovery in the sidebar and on the page, plus each failure kind's copy, art and action - `typecheck`, `oxlint` and `prettier` pass on the changed files - full factory-ui MSW suite: all green except 9 tests in `AppStartup.msw.test.tsx` (8) and `ThreadPageTeammateSession.msw.test.tsx` (1), which fail the same way on `main` in the same environment and aren't touched here ### Not verified - [ ] the 401 → `/signin` round trip with web auth enabled (screens and tests run with auth off) ## Related issue(s) No issue. Found from a screenshot of the sidebar's "Unable to load boards." state. ## Type of change - [x] Bug fix (non-breaking change that fixes an issue) - [ ] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update - [ ] Code refactoring - [ ] Performance improvement - [x] Test update ## Checklist - [ ] I have linked the related issue(s) in the description above - [ ] I have made corresponding changes to the documentation (if applicable) - [x] I have added tests that prove my fix is effective or that my feature works - [ ] I have addressed all Coderabbit comments on this PR --- _Generated by [Claude Code](https://claude.ai/code/session_01D9qJ4NKnF4weVgHKMV6zja)_ --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local> |
||
|
|
4ba2bdef89 |
feat(server): memory, observability and agent builder MCP toolsets (#29931)
## Description Adds four toolsets to the built-in MCP server at `/api/mcp`: - `memory`: threads, messages, memory search, and Observational Memory. `get_observations` can wait for pending Observational Memory work, for example right after `call_agent`. - `observability`: trace and span queries, logs, and trace trajectories. - `observability_analytics`: `analyze_metrics`, `analyze_scores`, and `analyze_feedback`, plus metric name and label lookups. - `stored_agents`: list allowed models, and create, read, and update stored agents. With these, an MCP client such as Claude Code can create an agent, talk to it, read what it remembered, and explain a slow trace. ### Behavior - **On by default, shown only when supported.** Each toolset appears only when the app has the matching capability (a memory-enabled agent, an observability store that supports the queries, an editor for stored agents). Apps that don't set `server.mcp.toolsets` get these tools on upgrade, including write tools. Set `toolsets` to keep the previous set, or `readOnly: true` to drop writes. The changeset says this. - **Same checks as HTTP.** Every tool dispatches through its HTTP route, so authentication, RBAC, FGA, thread ownership, and agent visibility apply unchanged. No MCP caller gets more access than the same caller over HTTP. - **Observability isn't scoped per user.** Anyone with `observability:read` sees all traces, as over HTTP. The docs show how to leave those toolsets out. - **Builder model policy.** When the agent builder restricts models, `create_stored_agent` and `update_stored_agent` check the model the agent runs (`provider` and `name`, in every conditional variant; other keys on `model` are rejected), models named in `defaultOptions` such as `structuredOutput.model`, enabled fallback models (`modelList`), memory models, input and output processor models, and the defaults they fall back to. Anything the policy can't check is rejected. The HTTP stored-agent routes don't apply this check. Agents created or updated over MCP are published immediately (`update_stored_agent` defaults `autoPublish` to `true`). - **Results fit MCP client limits.** `get_trace` returns light span records with every span id, and `get_span` returns one span in full. Long lists are cut to fit, with a note on how to get the rest, and a single oversized item has its long values shortened (ids are never cut). - **Errors.** Bad `analyze_*` and `list_metric_names` arguments return 400. A failed observability store lookup is retried on the next request instead of hiding the observability tools until restart. Stacked on #29930. ## Test plan - `@mastra/server`: unit tests for the toolsets, capability detection, result sizing, and schemas. - Shared adapter suite (`builtin-mcp-toolsets-test-suite`) on Hono, Express, Fastify, Koa, Elysia, and NestJS: memory ownership compared with HTTP on the same request, read-only mode, analytics dispatch, and argument errors. Hono also runs observability tests against in-memory, LibSQL, and DuckDB stores. - `@mastra/editor` integration tests for the builder model policy across `model` (static and conditional), `defaultOptions`, fallback models, memory, and processors. They need no provider API keys. - Run end to end with two users over MCP and HTTP, and with Claude Code. --------- Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
27705673f2 |
feat(server): OAuth discovery and audience checks for the built-in MCP endpoint (#29930)
## Description
Lets MCP clients such as Claude Code sign in to the built-in `/api/mcp`
endpoint with OAuth instead of a pasted token. The endpoint tells
clients where to sign in (RFC 9728 protected-resource metadata) and can
reject tokens issued for a different API (audience check).
```ts
new Mastra({
server: {
auth: new MastraJwtAuth({
jwksUri: 'https://auth.example.com/.well-known/jwks.json',
issuer: 'https://auth.example.com/',
}),
mcp: { oauth: { resource: 'https://my-app.example.com/api/mcp' } },
},
});
```
### Behavior changes
**OAuth discovery for `/api/mcp`** (`@mastra/server`, every server
adapter including NestJS)
- When `server.auth` is set and the built-in MCP server is on, a `401`
from `/api/mcp` carries `WWW-Authenticate: Bearer
resource_metadata="…"`. `error="invalid_token"` is added only when a
token was sent (RFC 6750 §3).
- Metadata is served publicly at
`/.well-known/oauth-protected-resource/api/mcp` and
`/.well-known/oauth-protected-resource`, with `Cache-Control: no-store`.
- The document lists `resource`, `authorization_servers`, optional
`scopes_supported`, and `bearer_methods_supported: ['header']`. Without
`oauth.resource`, `resource` is derived from the request origin.
- The challenge, metadata routes and audience check apply only to
`/api/mcp`. Other routes are unaffected.
**Audience check** (`server.mcp.oauth.resource`)
- When set, the token audience must include this exact value, or the
request gets 401.
- An invalid value (non-URL, or a non-loopback `http://` URL) turns
discovery off and logs an error, but the audience check still runs
against it. Requests fail closed until the value is fixed.
- A provider that can't check audience (no `verifyAudience`, for example
`SimpleAuth` API keys) is accepted by default. The server logs a startup
warning on adapters built on `MastraServer`, not on NestJS.
- `requireAudience: true` (opt-in, only valid together with `resource`)
rejects those requests on `/api/mcp` with 401 `invalid_token`. Inside
`CompositeAuth`, only requests accepted by such providers are rejected.
Without `resource`, nothing changes.
**Config and provider hooks** (`@mastra/core`)
- New `server.mcp.oauth` config: `resource`, `requireAudience`,
`authorizationServers`, `scopesSupported`.
- Two new optional auth-provider methods:
- `getOAuthMetadata()` advertises the provider's authorization server.
- `verifyAudience()` checks the token audience.
- `CompositeAuth` combines the authorization servers of its providers.
It checks the audience with the provider that accepted the token, and
rejects when that provider can't be determined. The new
`getAuthenticatedProvider(user)` returns that provider.
**Providers**
| Provider | Advertises its authorization server | Checks audience
against `oauth.resource` |
|---|---|---|
| `MastraJwtAuth` | Yes, its `issuer` | Yes |
| Auth0 | Yes, the tenant | Yes |
| Clerk | Yes, the Frontend API | No |
| Okta | Yes, the issuer | No: Okta already enforces its own `audience`
(`OKTA_AUDIENCE`) |
| Supabase | Yes, `<url>/auth/v1` (requires Supabase's OAuth 2.1 server)
| No |
`MastraJwtAuth` gains `jwksUri` and `issuer` options
(`JWT_AUTH_JWKS_URI`, `JWT_AUTH_ISSUER`), so it can verify tokens signed
by an identity provider. JWKS keys are restricted to their key type, so
HMAC tokens forged with the public key are rejected.
**JWT subject as user id** (`@mastra/auth`, Auth0, Clerk)
- When a token has no `id` claim, the user's `id` is now set to `sub`.
Existing `id` claims are kept.
- Standard OIDC access tokens only carry `sub`. Before this change, RBAC
never loaded roles for these users, so every protected route returned
`403 Missing required permission`.
- Unless `mapUserToResourceId` is set, this also scopes data for these
users:
- **Owned records** (stored agents, skills, workspaces and other owned
records): each user sees their own records plus public ones. Admin
permissions keep the full list.
- **Tool-provider connections:** per-author connections move from the
shared `default` owner to the user's `sub`. Existing connections need
reconnecting, or set `mapUserToResourceId: () => 'default'` to keep the
old shared behavior.
- **Feedback:** recorded with `sub` as the user id.
- The changeset describes all of these effects.
**Test suite** (`@mastra/server-adapters-test-suite`)
- New `createBuiltinMCPOAuthTestSuite`.
- The package now has `@mastra/auth` and `jose` as peer dependencies.
Stacked on #29929.
## Test plan
- `packages/server`: `src/server/mcp/oauth.test.ts` and
`oauth-without-mcp.test.ts`. They cover metadata, the challenge format,
resource validation, failing closed on an invalid `resource`, and
discovery working without `@mastra/mcp` installed.
- `packages/auth` `jwt.test.ts`:
- JWKS and issuer validation
- string and array `aud`
- an algorithm-confusion token that is HS256-signed with the real RSA
public key PEM and must be rejected
- `sub` used as `id`
- `packages/core` `composite-auth.test.ts`: per-provider audience
delegation, rejection when the authenticating provider is unknown, and
`getAuthenticatedProvider`.
- `auth/auth0`, `auth/clerk`, `auth/okta`, `auth/supabase` unit tests.
- `createBuiltinMCPOAuthTestSuite` on Hono, Express, Fastify, Koa and
Elysia, plus the NestJS equivalent. It checks:
- the challenge, and fetching the advertised metadata URL
- audience accept and reject, including for an invalid `resource`
- `requireAudience`:
- `SimpleAuth` + `resource`: 200 by default, 401 in strict mode
- a JWT with a matching audience: 200 in strict mode
- a mixed `CompositeAuth`: only the API key is rejected
- RBAC with a token that carries only `sub`
- that a `sub`-only user can't list another user's private stored agent
- `tsc --noEmit` and `oxlint` on the touched packages, plus docs `pnpm
check` and Vale.
- Manual run end to end with Claude Code against a local identity
provider: discovery, client registration, PKCE login, and two users with
different roles.
---------
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
|
||
|
|
4fcc168fa1 |
fix(core): honor agent pubsub for durable thread coordination (#30215)
DurableAgent currently falls back to the Mastra pubsub for thread
coordination even when its wrapped Agent has a custom bus. Replicas
sharing only the Agent bus cannot consistently discover active runs,
receive thread updates, coordinate leases, or send Stop requests.
Delegate coordination pubsub resolution to the wrapped Agent and retain
injected coordination buses on Agent forks, without treating a
Mastra-inherited bus as owned configuration. The durable-option bus
remains independently configured for run-frame transport. For example,
`createDurableAgent({ agent: new Agent({ ...config, pubsub: sharedBus })
})` now uses `sharedBus` for thread coordination before and after
registration and forking.
Added regression coverage using independent Mastra instances and a
shared Agent bus for run visibility, subscriptions, leases and release,
remote Stop, fork behavior, and bus precedence. Updated the existing
queued-cancellation fixture to wait for visible output so it tests
queued cancellation rather than silent-model interruption. Includes an
@mastra/core patch changeset.
Verification: 110 tests passed across 11 Vitest project/file executions
covering seven source test files. Core `tsc --noEmit`, type-aware oxlint
(zero warnings/errors), formatting, and `git diff --check` passed.
Timing-sensitive coordination and cancellation cases passed 20
consecutive runs. Negative control: temporarily removing both production
fixes caused six of nine shared-bus regression tests to fail; both fixes
were restored before the final passing run.
Fixes #29882
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## ELI5
When an agent runs on several servers, the servers must share one
message bus for thread updates. Before this change, a durable agent used
a local bus for thread updates, so servers did not see each other's runs
or Stop requests. This change makes the durable agent use the agent's
own shared bus for thread updates.
## Overview
This change makes a `DurableAgent` use the wrapped Agent's pubsub for
durable thread coordination. Thread coordination covers run discovery,
thread subscriptions, thread leases, Stop requests, and notification
signals. Before this change, these operations called `getPubSub()` on
the durable wrapper. The wrapper did not override that method, so it
fell back to `mastra.pubsub`. That bus is in-process when no
Mastra-level pubsub is set.
Durable run frames still use `DurableAgentConfig.pubsub`. This change
does not alter that path.
## Changes
- `packages/core/src/agent/durable/durable-agent.ts`:
`DurableAgent.getPubSub()` now returns the wrapped agent's pubsub. The
setter documentation no longer states that the inherited `getPubSub()`
returns the wrapper's own stored pubsub. Memory and workspace setters
still forward to both instances.
- `packages/core/src/agent/agent.ts`: `Agent.__fork()` copies the source
agent's inherited pubsub reference to the fork. A fork keeps an injected
coordination bus.
-
`packages/core/src/agent/streams/__tests__/durable-shared-bus.test.ts`:
Adds parameterized tests for thread-run coordination, leases,
subscriptions, and Stop across agent buses. The tests run with and
without shared stream frames and forks. The tests also cover owned,
injected, and Mastra-provided coordination buses for plain and durable
agent forks. The `setup` helper gives Mastra instance B a separate bus
when an agent pubsub is supplied.
-
`packages/core/src/agent/durable/__tests__/durable-agent-abort.test.ts`:
`createAbortableModel` accepts optional response text and emits it as a
`text-delta` before it waits for abort. The remote-cancellation test
waits for that output before it queues and cancels input. This separates
queued cancellation from interruption of a silent model.
- `.changeset/big-zoos-call.md`: Adds a patch changeset for
`@mastra/core`.
## Scope
- 5 files changed, 115 lines added, 8 lines removed.
- No exported or public declarations changed.
## Verification
- The PR description reports 110 passing tests across 11 Vitest
executions. It also reports passing Core `tsc --noEmit`, type-aware
oxlint, formatting, and `git diff --check`. These results come from the
author's report. They were not confirmed from completed checks on the
current head.
- The author reports that a negative control with both production fixes
removed made six of nine shared-bus regression tests fail.
- Review severity counts: not available. No current review findings were
supplied.
## Linked issue
Issue `#29882` reports that thread topics stay in-process when a durable
Agent has a shared cross-process pubsub. This change addresses the issue
by making `DurableAgent.getPubSub()` delegate to the wrapped agent and
by preserving injected buses on `__fork()`. The issue also asks that
durable run frames stay separate from thread coordination. The diff
keeps `DurableAgentConfig.pubsub` for run frames. The change does not
add the internal `registered.__setPubSub(T)` workaround that the issue
rejects.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
|
||
|
|
e58a7d5cd6 |
fix(core): keep a forwarded queued message until the owning run accepts it (#29142)
## What was broken When a process drains a queued message (`queueMessage`) while a run in another process holds the thread lease, it forwards the message to that run as `signal-enqueued` and forgets about it. If that run has already finished locally, the owner drops the forward at the `answersTo(runId)` check. No run picks the message up, and the caller has already been told it was queued, so the message is lost without any error. A 10 ms pause after every memory save in `MessageHistory` has been hiding this race. With that pause shortened to 0–1 ms, three `signals-pending-cancellation` cases lose the queued message on every run. ## What this changes - The follower now keeps a forwarded user message until the owning run admits it. The owner already announces admission as a `pending` user-message presentation, so there is no wire change. - If the run it was forwarded to completes, fails or is discarded without admitting it, the message goes back to the front of the idle queue and is drained again, taking the lease over from the ended run. - If the owner disappears without publishing a run-end event, the follower reads the lease every renewal interval while anything is held. After two consecutive checks in which the lease no longer names that run, it requeues the message. - Held messages count toward the queued-message count, and thread-level and by-id cancels clear them, so a cancelled message can't come back after the owner ends. - A stopped (aborted) run is deliberately not requeued: it still admits until its stream ends, and requeueing there ran the message twice. - Entries are keyed by the run id the owner resolves the address to (`forwardedSignalRunId`), so legacy retake lease tokens match. - Non-user signals keep the old forward-only behaviour. The 10 ms pause stays in this PR. Removing it exposes a separate createdAt tie, which a follow-up PR will fix. ## Known limits - If the owner admits the message but its `pending` presentation is lost and the run then ends, the message can run twice. - A crashed owner's forwarded message runs about two lease renewal intervals after the lease expires. ## Tests - `signals-pending-cancellation.test.ts`, new describe "follower idle message forwarded to a run that has already ended". It covers: requeue when the run ends without admitting; a stopped run runs the message exactly once; cancel while held; lease lost without a run-end event. - `signals-drain-handoff.test.ts` "removes observed messages after lease acquisition failure" pinned the bug: it asserted the message never ran. It now expects the message to run once after the lease is released. ## Test plan - [x] With main's runtime and the new tests: 2 of 123 fail on every run (3 runs). With this fix: 123/123 on all 3 runs. - [x] Full `@mastra/core` unit run: 26,439 tests, 0 failed. - [x] `tsc --noEmit` for core: 0 errors. oxlint clean. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 A message sent to a run in another process should not disappear if that run cannot accept it. This change keeps the message queued and tries again if the run ends before accepting it. ## Summary - Keep forwarded user messages until the owning run accepts them. - If the run ends, fails, or is discarded before admission, return the message to the front of the idle queue. With a lease provider, requeue after two consecutive checks show that the lease no longer names the target run. - Count held messages in the queue total and support cancellation while they are held. - Do not requeue messages when the owning run stops. Keep non-user signals on their existing forwarding path. - During a takeover, keep messages held for lease checks when the follower did not register the successor. This avoids immediate requeueing that could cause duplicate execution. - Update tests for run endings, lease loss, cancellation, queue counts, and lease handoff. The author reports two limits: a message may run twice if its pending presentation is lost before the run ends, and recovery after an owner crash may take about two lease-renewal intervals. The 10 ms pause after memory saves remains because removing it exposes a separate `createdAt` tie. ## Tests The author reports that 123/123 targeted tests passed on each of three runs, 26,439 `@mastra/core` unit tests passed with no failures, `tsc --noEmit` reported no errors, and oxlint was clean. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com> |
||
|
|
4d8a09ed37 |
fix(factory): switch bound sessions onto card threads as the session owner (#30179)
## Summary
When Factory sends work to a bound session that is on a different
thread, the dispatcher switches the session onto the card's thread
first. That switch ran before the dispatcher built the owner's request
context, so the thread subscription loaded memory with no user, and the
tenant credential gate failed with:
`Tenant model credential policy could not be resolved: the request has
no authenticated user` (`reason: 'missing-user-context'`, `hasUser:
false`)
Shipyard logs show this on the `Agent.getMemory → subscribeToThread →
#switch → prepareCredentialTenant` stack for board-driven cards.
The dispatcher now passes the binding's owner (`startedBy`, `orgId` from
Factory's own rows, not client-writable thread metadata) into the
switch, the same identity the turn already runs as. Credential checks
are unchanged.
## Not covered
- The webhook subscription-session switch
(`integrations/subscription-session.ts`) makes the same context-less
switch.
- Cold `resumeStream` resumes without a user are a separate bug.
## Test plan
- New `dispatcher-switch-credentials.scenario.test.ts`: real dispatcher,
controller, session and user-requiring credential resolver. Fails on
main with the exact production diagnostic, passes with the fix.
- `dispatcher.test.ts` now requires the switch to carry the owner user.
- `src/rules`: 770/770 pass. oxlint/oxfmt clean.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
**ELI5:** When a Factory card starts work in a chat session, the system
must act as the user who started that work. This change makes the
session switch to the card's thread run as that user. Before, the switch
ran with no user, so the thread's memory could not load and the card
never started.
## Summary
This change makes `FactoryDecisionDispatcher` switch a bound session to
its card thread with the session owner's identity. The owner is
`startedBy` and `orgId` from the Factory binding record, not from
client-writable thread metadata.
### Changes
- **`mastracode/factory/src/rules/dispatcher.ts`** (+27/-17 in the raw
summary; the diff shows 44 changed lines)
- Replaces `ThreadSwitchSession` with `SessionOwner` (`userId`,
`orgId`).
- `#requireSession(binding, owner)` requires an owner. It passes the
owner to `#findSession`, which passes it to `#switchThread`.
- `#switchThread` takes a `BoundDispatcherSession`. When an owner is
given, it builds a request context with `factoryRequestContext`. It then
calls `thread.switch({ threadId, requestContext })`. Without an owner,
it sends `requestContext: undefined`.
- The skill, message, notification, activity, and pending-start dispatch
paths pass `{ userId: startedBy, orgId: record.orgId }` to
`#requireSession`. The path that calls `#switchThread` directly also
passes the owner.
- `#primeCredentials` calls are unchanged.
- **`mastracode/factory/src/rules/dispatcher.test.ts`** (+6/-2)
- The session stub's `thread.switch` input type accepts an optional
`RequestContext`.
- The session-recovery test now asserts that `thread.switch` receives
`requestContext`. It also asserts that the context user is `{ workosId:
'user-1', organizationId: 'org-1' }`.
- **`.changeset/dispatcher-switch-owner-context.md`** (+5)
- Adds a patch changeset for `@mastra/factory`.
-
**`mastracode/factory/src/rules/dispatcher-switch-credentials.scenario.test.ts`**
(new, +160)
- Registers the tenant credential resolver and wraps the agent memory
with credential preparation. The memory wrapper records the request
context user.
- The raw summary describes assertions that the deferred decision
succeeds, the session returns to the card thread, and memory receives
the session owner. I read only the first 80 lines of this file, so I did
not verify those assertions.
### Not covered
- The context-less switch in `integrations/subscription-session.ts` is
not changed.
- Cold `resumeStream` resumes without a user are not changed.
### Verification
- Diff stats confirm 4 files changed, 198 insertions, and 19 deletions.
- The author reports that the new scenario test fails on `main` and
passes with this change. I did not run it.
- The author reports that `src/rules` passes 770 of 770 tests and that
oxlint and oxfmt are clean. I did not run these checks.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
|
||
|
|
171e27355f |
fix(code-sdk): fire SessionStart again when a session binds a different thread (#30223)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
392c7b69d5 |
feat(server): built-in MCP endpoint for agents, workflows and tools (#29929)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
25ba8bae0e |
docs(memory): rewrite the Observational Memory guide (#30213)
Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com> Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com> Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
d05afc4a90 |
refactor(server): shared route authorization and in-process dispatchRoute across adapters (#29928)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
834b0d2828 |
fix(server): enforce stored-agent visibility on every route that resolves an agent (#29927)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
649ac25a61 |
docs(studio): remove outdated Studio overview and deployment details (#30220) | ||
|
|
6dbc650bed |
fix(factory): only return Jira issues from the project in the issue reference (#29326)
`GET /web/jira/issues/:identifier` checks that the project encoded in `issueRef` is bound to the Factory project, then fetches the issue by key. It never checked that the issue actually lives in that project. A hand-built `issueRef` pairing a bound project ID with an issue key from an unbound project returned that issue's title, description and comments. `#findIssue` now treats an issue whose `fields.project.id` doesn't match the referenced project (from the issue reference or the source ID) as not found. The route already turns that into a 404. Added an integration test for both the encoded-reference and sourceId paths. Factory Jira tests pass (63), and `tsc` and lint are clean. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 The Jira endpoint could return an issue from a project outside the source’s scope. This change checks that the issue belongs to the expected project and rejects references that conflict with the source. ## Changes - `#findIssue` returns `null` when an issue reference conflicts with the source connection or project. - `#findIssue` returns `null` when the fetched issue’s project ID does not match the project in the issue reference or `sourceId`. - Added tests for mismatched projects and conflicting references. - Added a patch changeset for `@mastra/factory`. Test, type-check, and lint results were not available. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
5ff479a34b |
fix(inngest): stop steps on every worker at the total deadline (#29002)
## Checks on ` |
||
|
|
c0d3bfdc43 |
feat: pass the authenticated user to DynamicArgument callbacks (#28612)
Dynamic agent config callbacks now get the authenticated end user as an
optional `user` argument, so you can personalize an agent without
digging auth keys out of `requestContext` yourself. It works in any
`DynamicArgument` callback: instructions, model, tools, memory,
workspace, processors, scorers, and so on.
```ts
import { Agent } from '@mastra/core/agent';
const supportAgent = new Agent({
id: 'support-agent',
instructions: ({ user }) =>
user ? `You are helping ${user.name ?? user.id}.` : 'You are a helpful assistant.',
model: ({ user }) => (user?.role === 'admin' ? 'openai/gpt-5' : 'openai/gpt-5-mini'),
tools: ({ user }) => (user ? { accountTool, ...(user.role === 'admin' ? { adminTool } : {}) } : {}),
memory: ({ user }) => (user ? userMemory : undefined),
});
```
`user` always has the same `MastraUser` shape, no matter which auth
provider you use, and it's `undefined` for unauthenticated requests:
```ts
import type { MastraUser } from '@mastra/core/types';
// { id: string; name?: string; email?: string; avatarUrl?: string; role?: string }
```
The server auth middleware builds it through a new overridable
`toMastraUser()` on `MastraAuthProvider`. The default handles common
shapes (`id`/`sub`/`userId`, `name`, `email`, `avatarUrl`/`picture`,
`role`), and JWT, Cloud, Supabase, Neon and Better Auth ship overrides
for their user objects. Custom providers can map their own shape:
```ts
import { MastraAuthProvider } from '@mastra/core/server';
import type { MastraUser } from '@mastra/core/types';
class MyAuth extends MastraAuthProvider<MyUser> {
async authenticateToken(token: string) { /* ... */ }
async authorizeUser(user: MyUser) { return true; }
toMastraUser(user: MyUser): MastraUser {
return { id: user.accountId, name: user.profile.displayName, role: user.permissions.primaryRole };
}
}
```
Inline auth configs can pass `toMastraUser` too. If the provider user
has no role and an RBAC provider is configured, the primary RBAC role
fills it in, so `user.role` also works with WorkOS, Okta, Google and
Neon. The raw provider user is still available when you need
provider-specific fields, and the new context key is reserved, so
clients can't spoof it through the request body:
```ts
instructions: ({ requestContext }) => {
const rawUser = requestContext.get('mastra__user'); // provider-specific object, unchanged
// ...
},
```
Dynamic `vectorStore` resolvers on RAG tools get `user` as well:
```ts
createVectorQueryTool({
indexName: 'docs',
model: embedder,
vectorStore: ({ user }) => (user ? tenantStores.get(user.id)! : sharedStore),
});
```
Inside core, every place that invoked a `DynamicArgument` callback
inline now goes through a single `resolveDynamicArgument` helper, which
reads the user from `requestContext` at call time. This is non-breaking:
callbacks get an extra optional field, providers get a method with a
working default. Requests served through an `MCPServer` don't get `user`
yet, since MCP builds its own request context; that's documented.
Tested with unit tests for the helper, normalization and each provider
override, middleware tests (inline config, provider role, RBAC role,
CompositeAuth ordering, unauthenticated), regression tests for the
migrated call sites, and an end-to-end test where an agent behind a fake
auth provider gets personalized instructions. Core, server, rag and the
touched auth packages typecheck clean, and their suites pass.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## ELI5
When a signed-in user makes a request, configuration callbacks can now
use a standard set of details about that user. When a workflow resumes,
it uses the new request’s user details instead of restoring them from
the earlier run.
## Summary
- Added optional `user` data to `DynamicArgument` callbacks and RAG
vector-store resolvers. Callbacks can also use `getRequestUser()` to
read the normalized user from request context.
- Added the `MastraUser` type and `toMastraUser()` normalization hooks
for auth providers and inline auth configs. The server stores the
normalized user in a reserved request-context key and uses the primary
RBAC role when the user has no role.
- Updated core dynamic configuration paths to use the shared resolver.
Added user support to agent scopes and migrated A2A memory resolution.
- Added `withoutLiveRequestKeys()` to remove live authentication and
authorization data from saved context during workflow resume, restart,
and time travel. Saved non-authentication context, such as tenant data,
remains available.
- Added documentation and changesets. Raised relevant `@mastra/core`
peer dependency minimums to 1.81.0. MCPServer requests do not receive
the normalized `user`.
## Validation
The author reports passing typechecks and test suites across core,
server, RAG, and several auth packages. The author also reports three
failing Inngest tests and earlier failures in evented workflow and
scheduler tests, which reportedly fail the same way on comparison
sources. These results are author-reported and have not been
independently verified.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
|
||
|
|
9a0c3e05ff |
perf(factory): skip the card read for workers nobody follows (#29992)
**─────── TLDR ───────** > Board-started workers that nobody follows no longer load their work item card on every agent step, cutting that step's storage cost by about a third. The sessions state processor runs on every agent step. For a worker session it loaded the card first, then counted followers, and returned nothing when there were none — the usual case for board-started workers. It now counts followers first and only reads the card when it has a line to show. ### Behavior changed a worker step, nobody follows its item ├─ **was** — binding, card (board item + work item + sources), subscribers read └─ **now** — binding and subscribers read; no card read, still no signal a worker step, someone follows its item └─ **unchanged** — same reads, same "Working on #7 as work…" line ### Gain Local benchmark: 2,200 cards, 150 bound workers with no followers, 2,000 steps through `computeStateSignal`. > ██████████████████ **Postgres before** `1217µs wall · 327µs cpu` > █████████████ **Postgres after** `872µs wall · 223µs cpu` > ██████ **LibSQL before** `413µs wall · 421µs cpu` > ████ **LibSQL after** `281µs wall · 287µs cpu` ### Decisions - **no cross-step cache of binding or subscribers** — another server process can follow or revoke without telling this one; a cache would show stale lines - **scope resolution left alone** — it is shared auth code and still reads session, run binding and project each step; that is most of the remaining cost ### Not verified - [ ] the gain in production — the 16% self time on `#workerLine` in the Shipyard profile is far above this ~0.3ms per step, so this PR is a part of the stall at most - [ ] the 11% LibSQL row iteration in that profile — Shipyard's factory storage is Postgres, and no LibSQL path in factory is hit at runtime with `DATABASE_URL` set - [ ] the 9% spawn — the closest candidate is the per-run `git rev-parse` and binary probe in the SDK's dynamic instructions, outside this package --- > ██████████████████ **tests** `+15` — 68% of the additions > ██████ **changeset** `+5` > ██ **source** `+2 −2` — reordered, net 0 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ELI5: When a worker runs for a board item that nobody follows, the system used to load the item card and then discard it. Now it checks for followers first and skips that read when none exist. The output stays the same. ## Summary This PR changes `FactorySessionsStateProcessor` in `@mastra/factory` so that it checks for work-item followers before it loads the work item card. Workers with no followers now return `null` without reading the card. Workers with followers still load the card and produce the "Working on ... as ... Reports go to N following sessions" line. ## Changes - `mastracode/factory/src/tools/sessions-state-processor.ts` (+2/-2): In `#workerLine`, the `listWorkItemSubscribers` call and the follower count now run before `workItems.getForProject`. The `getForProject` call moves below the `following === 0` early return. The comment is updated to say the card read is skipped. - `mastracode/factory/src/tools/sessions-state-processor.test.ts` (+15): Adds a test for a worker with a bound item and no followers. The test spies on storage `findOne` and `findMany` calls. It checks that the step emits no signal and that neither query reads the board-item collection. The test imports `FACTORY_BOARD_ITEMS_SCHEMA`. - `.changeset/full-dogs-try.md` (+5): Adds a patch changeset for `@mastra/factory`. The note says per-step database reads drop for board-started sessions with no followers, by about a third. ## Diff size 3 files changed, 22 lines added, 2 lines removed. ## Benchmarks The author reports local results for 2,200 cards, 150 bound workers without followers, and 2,000 `computeStateSignal` steps: - Postgres: 1217 µs wall / 327 µs CPU before, 872 µs wall / 223 µs CPU after. - LibSQL: 413 µs wall / 421 µs CPU before, 281 µs wall / 287 µs CPU after. The author did not verify production gains, the Shipyard profile's LibSQL row iteration, or spawn cost. The description says factory storage uses Postgres in Shipyard, and the closest spawn candidate lies outside this package. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local> Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
0b24f9cdb0 |
perf(core): read only stored run status when checking parked runs (#30175)
## Summary
Thread subscribers decide whether a remote or replayed run is still
parked by reading its stored status. They used `getWorkflowRunById`,
which loads the whole run snapshot (often 1–40 MB) into Node just to
read `status`. They now use `loadWorkflowRunStatus`, which returns only
the status for v1 and v2 rows.
On Shipyard, pg_stat_statements showed ~18.4k of these full-run reads
(~576 kB avg, 865 s DB time) since the last stats reset, contributing to
GC pressure and event-loop lag.
## Test plan
- New test in `thread-stream-stored-run-state.test.ts` asserts
status-only reads; fails on main, passes here
- `src/agent/__tests__`: 2414 passed
- agent-controller + thread-stream suites: 1064 passed
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
**ELI5:** When the system checks whether a paused agent run is still
waiting, it now reads only the run's status. Before, it loaded the whole
saved run record, which could be several megabytes. Each check now uses
less database work and less memory.
## Summary
This change reduces the data read when a thread subscriber checks
whether a remote or replayed run is parked. In
`AgentThreadStreamRuntime.#readStoredRunStatus`
(`packages/core/src/agent/thread-stream-runtime.ts`), the method now
calls `workflowsStore.loadWorkflowRunStatus({ runId, workflowName })`
instead of `workflowsStore.getWorkflowRunById`. The full run snapshot is
no longer fetched or parsed.
### Behavior changes in `#readStoredRunStatus`
- The method checks the same workflow names in the same order.
- It returns the first string status it finds.
- If no workflow name returns a string status, it returns `'missing'`.
- The `catch` block is unchanged. The diff does not show what it
returns.
- Before, the first run found returned its snapshot status immediately,
even when that status was not a string. Now the loop moves to the next
workflow name when the status is not a string. This changes the return
value when no name yields a string status: the method returns
`'missing'`.
### Other changes
- `.changeset/stored-run-status-only.md` is a new file. It adds a
`patch` entry for `@mastra/core`. The entry states that memory use and
garbage-collection pauses drop for thread subscribers on adapters that
support a status-only read. Adapters without that read still load the
snapshot.
-
`packages/core/src/agent/__tests__/thread-stream-stored-run-state.test.ts`
adds one test, "reads only the stored run status, not the whole run
snapshot". It spies on `loadWorkflowRunStatus` and `getWorkflowRunById`
during a lease-lapse scenario. It asserts that the status method is
called and that the full-run method is not.
### Diff size
- 3 files changed, 23 lines added, 4 lines removed.
### Not verified
- The PR objectives report production figures: about 18.4k full-run
reads, a 576 kB average, and 865 seconds of database time. The diff does
not check these.
- The PR objectives report test results: the new test fails on `main`,
2,414 tests pass in `src/agent/__tests__`, and 1,064 tests pass across
the agent-controller and thread-stream suites. No test run output is
available, so these results are not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
|
||
|
|
8d4abc4f88 |
chore(deps): Vanta 2026-11-12 — raise undici to 8.12.4 / 7.30.2 (#30205) | ||
|
|
731b66498c |
docs(mcp): remove prebuilt Mastra apps section (#30209)
## Description Removes the "Use prebuilt Mastra apps" section from `docs/connections/mcp`, along with `@mastra/mcp-apps-components` in the page's `packages` frontmatter. The package exists to support Playground UI MCP App components and shouldn't be documented as a user-facing package yet. ## Related issue(s) None. Requested internally in Slack (#growth-pmm). ## Type of change - [ ] Bug fix (non-breaking change that fixes an issue) - [ ] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [x] Documentation update - [ ] Code refactoring - [ ] Performance improvement - [ ] Test update ## Checklist - [ ] I have linked the related issue(s) in the description above - [x] I have made corresponding changes to the documentation (if applicable) - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] I have addressed all Coderabbit comments on this PR Link to Devin session: https://app.devin.ai/sessions/e41299f3bd58441b9d227362b56641e1 Open in Devin Desktop: https://app.devin.ai/desktop/session/e41299f3bd58441b9d227362b56641e1?variant=devin <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> **ELI5:** The docs page for MCP no longer talks about a ready-made app package. That package is still being built for internal use, so it should not appear in public docs yet. ## Summary This change removes user-facing documentation for `@mastra/mcp-apps-components` from the MCP docs page. ## Changes - `docs/src/content/en/docs/connections/mcp.mdx`: Removes the "Use prebuilt Mastra apps" section. This section explained how to install and use the package's prebuilt greeting app. Removes `@mastra/mcp-apps-components` from the page's `packages` frontmatter. ## Scope - Files changed: 1 - Lines added: 0 - Lines removed: 46 - The rest of the MCP Apps documentation is unchanged. ## Rationale The package supports Playground UI MCP App components. The team does not yet want to document it as a user-facing package. ## Public API No exported or public declarations change. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: paul <paul@mastra.ai> |
||
|
|
79ff445aca |
fix(rag): reject JSON chunk sizes that stall string splitting (#30186)
## Summary - Require JSON chunk `maxSize` of at least 21 in strategy validation and direct transformer construction, preventing zero-length string splits from stalling chunking. - Add regressions for invalid integer and fractional limits and verify long strings reconstruct at the supported boundary. - Include a patch changeset for `@mastra/rag`. ## Test plan - `cd packages/rag && ./node_modules/.bin/vitest run src/document/document.test.ts --reporter=dot` (167 passed) - `./node_modules/.bin/tsc --noEmit -p packages/rag/tsconfig.json` - Type-aware oxlint for changed files; Prettier check; `git diff --check` Fixes #30166 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> **ELI5:** The JSON text splitter could get stuck in an endless loop when a user set a small chunk size. This change rejects those small sizes with a clear error, so the splitter never hangs. ## Summary This change stops JSON chunking from hanging when `maxSize` is too small. The splitter subtracts a fixed overhead of 20 from `maxSize` and floors the result. At `maxSize` 20, the split point is zero. The splitter then never consumes input. Fractional values between 20 and 21 have the same problem. The change sets a minimum JSON `maxSize` of 21. It applies this minimum in two places: - **Option validation** (`packages/rag/src/document/validation.ts`): The JSON chunk options schema adds an optional `maxSize` field. It accepts the field only when the value is at least 21. - **Transformer constructor** (`packages/rag/src/document/transformers/json.ts`): `RecursiveJsonTransformer` throws a `RangeError` when `maxSize` is not finite or is below 21. Other chunking strategies keep their existing size rules. ### Documentation - `docs/src/content/en/reference/rag/chunk.mdx` states that the JSON strategy's `maxSize` is a target maximum for each chunk. It must be at least 21. Long values nested in objects can exceed it. - A patch changeset for `@mastra/rag` describes the new minimum. ### Tests (`packages/rag/src/document/document.test.ts`) - Adds cases that expect `maxSize` values `0.5`, `20`, and `20.9` to be rejected. The cases cover both `MDocument.chunk` and direct transformer construction. The expected error matches `maxSize.*21`. - Adds a case that splits a 100-character JSON string with `maxSize: 21`. The test checks that the output has multiple chunks. It also checks that the parsed string values rejoin to the original text. ### Behavior change Callers that pass a JSON `maxSize` below 21 now receive a configuration error. Before this change, those calls were accepted and could hang. Default JSON chunking remains valid. ### Reported validation (not verified in this summary) The PR description reports these checks: - `vitest run src/document/document.test.ts`: 167 passed. - `tsc --noEmit` for `packages/rag`. - Type-aware oxlint on changed files, Prettier check, and `git diff --check`. Diff size: 5 files changed, 38 lines added, 1 line removed. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com> Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
da717f489c |
Fix GraphRAG leaking documents across reused tool requests (#30185)
## Summary - Rebuild the GraphRAG graph from each request’s retrieval results so tenant-specific indexes cannot reuse a previous request’s documents. - Return empty context and sources when retrieval yields no candidates. - Add a real LibSQL and embedding-server regression covering sequential, empty, and concurrent requests, plus a patch changeset. ## Test plan - `pnpm build:rag` - `pnpm test:rag` (454 tests) - `pnpm exec tsc --noEmit -p packages/rag/tsconfig.json` - `pnpm --filter ./packages/rag lint` - `pnpm exec prettier --check packages/rag/src/tools/graph-rag.ts packages/rag/src/tools/graph-rag-isolation.test.ts .changeset/graph-rag-request-isolation.md` Fixes #30168 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> **ELI5:** A search helper that is reused can return a document from an earlier user's search. This change makes the helper build its answer only from the current search. Each request now gets results for its own search. ## Summary This change fixes a data-isolation defect in the GraphRAG tool that `createGraphRAGTool` creates in `@mastra/rag`. Linked issue `#30168` reports the defect. The tool kept one `GraphRAG` instance and an `isInitialized` flag across executions. Later requests that selected a different index could still receive documents from the first execution. ## Changes - `packages/rag/src/tools/graph-rag.ts` (+32/-37): - Removes the `GraphRAG` instance and the initialization flag that persisted across executions. - Returns empty context and sources when vector search finds no candidates. - Otherwise, builds a new graph from that execution's retrieved chunks and embeddings, then traverses it. - Keeps graph-build logging, tracing, and error propagation. - `packages/rag/src/tools/graph-rag-isolation.test.ts` (+84/-0): Adds a Vitest integration test. The test uses tenant-specific and empty vector indexes. It serves an `LLMock` through a local HTTP proxy. It checks that: - A request returns only the document from its selected index. - An empty index returns empty results. - Concurrent requests stay isolated. - `.changeset/graph-rag-request-isolation.md` (+5/-0): Declares a patch release for `@mastra/rag`. - `docs/src/content/en/reference/rag/graph-rag-guide.mdx` (+1/-1): States that each graph query tool execution builds its graph from that request's retrieved chunks. The guide no longer says that later queries reuse the first execution's graph. No exported or public declarations change. ## Tradeoff Each execution now builds a graph. The linked issue states that this adds work per request. The request-specific candidates require this work. A future cache would need correct candidate and scope keys. ## Verification Not available. The PR lists planned checks: `pnpm build:rag`, `pnpm test:rag`, a TypeScript check, lint, and a Prettier check. No completed results for these checks were supplied. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com> Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
e1a20364af |
Fix OpenAPI request schemas for defaulted and transformed fields (#30187)
## Summary - Generate request path, query, and body JSON Schemas from input types while retaining output types for responses. - Pass input/output mode through the Zod v4 adapter to represent defaults and transformations accurately. - Add regressions for OpenAPI documents, API schema manifests, and Zod v4 conversion, plus patch changesets for both packages. ## Test plan - `pnpm exec vitest run` in `packages/schema-compat` (1089 passed, 9 skipped) - `pnpm exec vitest run` in `packages/server` (3406 passed, 3 skipped, 1 todo) - `pnpm exec tsc --noEmit -p tsconfig.json` in both packages - `pnpm exec oxlint --type-aware` on modified files; `pnpm exec prettier --check` on modified files Fixes #30050 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> **ELI5:** Mastra builds an API document that tells client programs what data to send. Before this change, the document described the cleaned-up data the server produces, not the data the client sends. This change makes the document describe what clients send for requests, and keeps the cleaned-up form for responses. ## Summary This pull request changes how OpenAPI documents describe request and response schemas for Zod schemas. It addresses issue `#30050`. ### Problem The OpenAPI conversion used the Zod output side for all schemas. Request data needs the input side. This caused two errors: - Fields with `.default()` appeared as required in request bodies. - Parameters with `.transform()` appeared as `{}` in path and query schemas. On Zod versions before 4.2, and through the 3.25 v4 compatibility layer, the `@mastra/schema-compat` Zod v4 adapter also dropped the input/output mode. ### Changes - **`packages/server/src/server/server-adapter/openapi-utils.ts`:** `schemaToJsonSchema` accepts an optional `io` argument (`'input' | 'output'`, default `'output'`) and passes it to `standardSchemaToJSONSchema`. Path parameters, query parameters, and request bodies use `'input'`. Response schemas keep the default `'output'`. - **`packages/server/src/server/server-adapter/api-schema-manifest.ts`:** `convertSchema` accepts a direction and passes it to `schemaToJsonSchema`. The manifest builder converts response schemas as output. It converts path, query, and body schemas as input. - **`packages/schema-compat/src/standard-schema/adapters/zod-v4.ts`:** `convertToJsonSchema` accepts a direction and passes it to Zod's `toJSONSchema` options. The `input` converter uses `'input'`. The `output` converter uses `'output'`. - **Generated CLI schemas:** `packages/cli/src/commands/api/feedback-score-schemas.generated.ts` and `route-metadata.generated.ts` are regenerated to match the OpenAPI request-schema change. - **Changeset:** Adds patch releases for `@mastra/schema-compat` and `@mastra/server`. ### Tests - `openapi-utils.test.ts`: Adds a test for a `createRoute` POST route. It checks that transformed path and query inputs use string schemas, that the defaulted query parameter is optional, and that only non-defaulted body and response fields are required. - `api-schema-manifest.test.ts`: Adds a test that checks property schemas and required fields for path, query, body, and response schemas with defaults and transforms. - `zod-v4.test.ts`: Changes the input/output comparison. It now checks that properties and required fields match for a schema without defaults or transforms. It adds a test for a defaulted, transformed field through the routed adapter. ### Scope - 9 files changed, 155 lines added, 62 lines removed (from `git diff --stat` against the merge base). - Two of the nine files are generated CLI schema files. - No exported declarations changed except the `schemaToJsonSchema` signature, which gained an optional parameter. ### Verification The PR objectives report these local checks by the author: `schema-compat` and `server` Vitest runs, `tsc --noEmit` in both packages, and `oxlint` and `prettier --check` on modified files. These results come from the PR description. CI results on the current head are not available. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com> Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
5251e7199e |
Fix atomic pubsub replay writes on Redis Cluster (#30174)
> Opened by @abhiaiyer91
## Summary
- Preserve existing `CachingPubSub` replay keys by default, so upgrading
does not make in-flight logs unreadable for other cache backends or
Redis standalone.
- Add `keyFormat: 'redis-cluster'` as an explicit option for new Redis
Cluster deployments. It encodes the topic into a hash tag shared by the
replay list and counter, allowing the atomic Redis Lua append instead of
the `CROSSSLOT` fallback. PubSub topic names remain unchanged.
- Retain the Redis cache fallback for callers that still supply untagged
keys; add coverage for both key formats and edge-case topics.
## Usage
Pass `{ keyFormat: 'redis-cluster' }` as the third argument to `new
CachingPubSub(innerPubSub, redisServerCache, options)` on **all workers
sharing the same cache**. Roll it out for new logs, or after existing
replay logs expire. The default remains the original
`${keyPrefix}${topic}` format; opt-in keys use
`${keyPrefix}{${encodeURIComponent(topic)}}` (with `%EMPTY` for an empty
topic).
## Test plan
- Seven focused core suites: 169 tests passed, with no type errors; core
build/type generation and targeted oxlint passed.
- Convex cache suite: 21 tests passed with original key expectations.
- Redis Docker Compose integration: 14 tests passed.
- Real slot-assigned Redis Cluster: confirmed untagged two-key `EVAL`
fails with `CROSSSLOT`; opted-in replay successfully publishes and reads
indexes 0–2.
Fixes #30149
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
ELI5: Redis Cluster sometimes refuses to run one command that touches
two related cache keys. This PR puts those keys in the same place, so
the command works and event indexes stay in order.
## Summary
This PR changes `CachingPubSub` so that a topic's replay list and its
index counter share a Redis Cluster hash tag.
`RedisServerCache.listPushIndexed` can then run its Lua script on both
keys without a `CROSSSLOT` error.
## Changes
- **`packages/core/src/events/caching-pubsub.ts`**
- Adds an optional `keyFormat?: 'redis-cluster'` option. The default is
`'legacy'`.
- Legacy mode keeps the list key as `keyPrefix + topic`.
- `redis-cluster` mode builds the list key as `keyPrefix + {tag}`. The
tag is `encodeURIComponent(topic)`, or `%EMPTY` when that value is
empty.
- The counter key is now `<list key>:counter`. In `redis-cluster` mode,
it uses the same hash tag as the list key.
- **`stores/redis/src/cache.ts`**
- Updates the comment on the `CROSSSLOT` fallback. The fallback logic is
unchanged. Untagged keys can still trigger `CROSSSLOT`, so the fallback
remains for callers that do not use tagged keys.
- **`.changeset/redis-cluster-atomic-pubsub-replay.md`**
- Adds a patch changeset for `@mastra/core`.
## Behavior and compatibility
- Topic names used for publishing are unchanged.
- The default `legacy` format keeps existing replay keys. Existing logs
stay readable with the default setting.
- Opting into `keyFormat: 'redis-cluster'` changes replay key names.
Workers that use the new format cannot read logs written under the old
names until those logs expire by TTL.
## Scope limits
- The change co-locates only the replay list and counter for each topic.
It does not co-locate those keys with transport streams or other keys
for the same run.
- The change does not add a new default for `keyFormat`.
## Tests and checks
- The diff adds no test file. The PR objectives report test runs, but
this summary does not verify them.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
|
||
|
|
6ad8e7eb9d |
feat(ui): one settings layout across Studio, Factory and Platform (#29400)
## Description Settings pages in Studio, Factory and Platform each had their own layout: different widths, section headers with buttons, add rows at the bottom of lists, fields starting at different x positions. This gives all three one layout, built from reusable Playground UI components: - A 640px page column with the title above the sections. - Each section is a dimmed title above one borderless card. The card owns all row spacing (14px padding, inset hairlines), so rows carry no padding of their own. - Settings rows: label and description on the left, control on the right. Text fields share one width, selects hug their value up to that width, switches and buttons keep their size. - Lists: a count and the list's action in a header row at the top of the card, one empty row (text plus the same action) when there's nothing in it, and `SettingsItem` rows with one icon tile size, so every list lines up. - Input, InputGroup and select values use the regular-weight `text-body-sm`, like Textarea. This is the Playground UI, Studio and Factory half. The Platform half, mastra-ai/platform#4174, pins a snapshot of this branch. ## Before / After Every settings page in Studio and Factory, `origin/main` on the left and this branch on the right (1440×1800, dark). Platform's pages are in mastra-ai/platform#4174. | Before | After | | --- | --- | | <br>Studio · Settings | <br>Studio · Settings | | <br>Factory · My account | <br>Factory · My account | | <br>Factory · Preferences | <br>Factory · Preferences | | <br>Factory · Connections | <br>Factory · Connections | | <br>Factory · Models | <br>Factory · Models | | <br>Factory · Memory | <br>Factory · Memory | | <br>Factory · Skills | <br>Factory · Skills | | <br>Factory · Tools | <br>Factory · Tools | | <br>Factory · Behavior | <br>Factory · Behavior | | <br>Factory · Repositories | <br>Factory · Repositories | | <br>Factory · Work Intake | <br>Factory · Work Intake | | <br>Factory · Work board | <br>Factory · Work board | | <br>Factory · Manage Factory | <br>Factory · Manage Factory | One loading state everywhere (`SettingsSkeleton`, New/Settings Loading story), built from the real rows and list items:  ## What changed Playground UI (`@mastra/playground-ui/new/settings`): - `SettingsLayout`: the page column and title (`header` for an app's own header). - `SettingsTitle`: dimmed, inset to the card; `info` keeps a section description as a tooltip. - `SettingsContainer`: the card, owning row spacing. Rows with nothing in them take no space, so a list can always render its notice row. - `SettingsRow` / `SettingsFieldsetRow`: control column with shared field width; selects hug (`fieldTriggerWidthStyle` reads `--field-max-width`). With `controlPlacement="below"` the control fills the row. - New `SettingsListHeader`, `SettingsEmptyRow` (now takes an `action`), `SettingsItem`, `SettingsItemIcon`. `SettingsNoticeRow` stays. - New `SettingsSkeleton`: the one loading state for settings, placeholder rows (`variant="row"`) or list items (`variant="item"`) inside the same card. - Removed `SettingsAddRow` and `SettingsContainer`'s `variant`. `Section`'s deprecated rows keep their old look on their own code. Studio: the settings page uses `SettingsLayout` with its title in the column. URL, API prefix and request headers are one "Mastra connection" card. They only work as a set, so edits stay a draft: an "Unsaved changes · Discard · Save changes" row shows up once something changed, and saving applies all of it at once. This replaces "Save configuration", which sat under the headers and read as saving only them. The first-run connect screen keeps its own form. `@mastra/react`: `useAuthCapabilities` and `usePermissionPatterns` keep their last result while a new client loads (`keepPreviousData`). Before, every connection change gave them a new query key, and the auth and permission guards showed a full-page spinner until it answered, so the page went blank on each save. Factory: every settings page is on the shared components. Section stacks are fragments under `SettingsLayout`, lists with an action use the header or empty row (repositories, custom providers, speech-to-text keys, Connect, intake pickers), and logo and icon rows are `SettingsItem`s. Factory's own `SettingsAddRow`, `SettingsActionRow`, `SettingsSectionHeader` and `SettingsRowsSkeleton` are gone. Every settings loading state is `SettingsSkeleton` (Skills used to show plain "Loading skills…" text). Models keeps its routing diagram; its lane and defaults cards use the borderless settings surface. Work board keeps its form layout. Memory is split into Personal memory and Factory memory, and Build history is its own section. ## Testing 1. `mdev up storybook`: New/Settings, Page, Controls and Loading stories. 2. `mdev up studio`, open Settings: change the URL, prefix or a header and the unsaved row appears; Discard restores; Save applies everything without the page going blank. Change the theme. 3. Factory settings: every section, especially Models. Playground UI, Studio and Factory typecheck clean; the settings, Studio connection, Factory settings and Models tests pass, and CI is green. Not seen locally: a loading state on screen (they resolve too fast), Models with providers connected, and Factory's Memory form (no models in the local org). ## Related issue(s) Fixes PLTFRM-3135 ## Type of change - [ ] Bug fix (non-breaking change that fixes an issue) - [x] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update - [ ] Code refactoring - [ ] Performance improvement - [ ] Test update ## Checklist - [x] I have linked the related issue(s) in the description above - [ ] I have made corresponding changes to the documentation (if applicable) - [x] I have added tests that prove my fix is effective or that my feature works - [ ] I have addressed all Coderabbit comments on this PR <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 This PR makes settings pages in Playground UI, Studio, and Factory use a more consistent layout. It adds shared building blocks so settings and lists are easier to organize and read. ## Summary - Add shared settings components in Playground UI, including a centered 640px layout, consistent containers and rows, list headers, empty and notice rows, and settings items. - Update the Playground settings page and Studio connection form to use the shared layout. Add `CopyInput` for read-only values with a copy action. - Update Factory settings, workspace, and connection views to use the shared components. Separate Personal memory and Factory memory, and give Build history its own section. - Remove older layout helpers, including `SettingsAddRow`, `SettingsSectionHeader`, and the settings container variant. - Add or update component tests and Storybook examples for the new settings patterns. **Checks:** not available. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
7cefe1623e |
fix(factory): let a board use the key review (#29903)
Factory refused every write to a board under the key `review`, because
that key belonged to the retired Review board. No key is reserved now,
so `review` works like any other, and the unique index on a project's
board keys is what stops a duplicate.
```ts
// before: 409 reserved_board
// after: 201, listed in the catalog, and a second create is 409 board_exists
await fetch(`/web/factory/projects/${id}/boards`, {
method: 'POST',
body: JSON.stringify({ key: 'review', name: 'Review', phases }),
});
// before: threw "board id 'review' is reserved for the retired Review board"
new MastraFactory({ boards: [defineBoard({ id: 'review', ... })] });
```
A board a project stores under `review`, or one an app passes in
`boards`, is served in place of the retired Review board, and the cards
put on it are its own cards in their stored phases, never read as Work
cards. The retired board is still the fallback for a project that has no
board of its own under the key.
The cards the retired board left stored on `review` do not become the
new board's. The write that gives a project its board (a create,
`factory.upsertBoard()`, or a `PATCH` of the seeded row below) stores
their Work placement in the same transaction, the way an ordinary write
to such a card already does, so they stay on Work and the new board
starts empty. While one of those cards is still open the write is
refused with `409 board_in_use`, since the retired board is still in use
there. This is the one place Factory rewrites those rows together,
scoped to one project's cards on `review`.
Projects from earlier releases can hold the `review` row Factory seeded
back then. While nobody has edited it, it stays hidden and the
retired-board behaviour applies, as before. An edited row used to be
reported as a catalog problem and is now served as the project's board.
Creating over the untouched seed is a `409 board_exists` since the row
is there; a `PATCH` or delete gets past it.
An app board with id `review` owns its cards in a project from when its
row is stored there, not from the moment the app defines it. Storing the
row moves every card the retired board left on `review` to Work, open
ones included, because a deploy can't be refused. Where the old seeded
row is still there, Factory rewrites it to the app's definition on the
next load, in the same transaction as the card move.
The card store asks on each read of a `review` card whether the project
has its own `review` board (the board row and its phases, read through
the caller's connection), because a project can create or delete it at
any time.
Tests run on LibSQL and Postgres: finished old cards stay on Work and
the new board is empty (and can be deleted again), an open old card
refuses the create, the upsert and the seed edit, an app board is served
with its own cards and none of the old ones in a project with and
without the seeded row, a second create is `board_exists`, and the
untouched seed stays hidden. They fail without the card rewrite.
`src/boards`, `src/routes`, the boards and work-items storage suites and
the intake-routes rules pass on both stores, except three Postgres
timeouts in `projects-concurrency.test.ts` that fail the same way on
main, and one Postgres timeout in `intake-routes.test.ts` that comes and
goes. No error code is added, so the CLI route metadata is unchanged.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## ELI5
Projects and apps can now use a board named `review`. When they do,
cards left on the old Review board move to Work, so they do not get
mixed with cards on the new board.
## Summary
- Removed the restriction on using `review` as a board key.
- Served stored `review` boards as regular boards. Untouched legacy seed
rows remain hidden until edited, replaced, or adopted by an app board.
- When a project creates, edits, or upserts a board under `review`, the
system moves legacy Review cards to Work in the same transaction. If
open cards remain, the write returns `409 board_in_use`.
- App-board seeding moves legacy Review cards to Work, including open
cards.
- Added safeguards that use the current card state during release to
handle concurrent changes.
- Updated documentation and tests for board ownership, duplicate
creation, legacy seeds, card migration, and open-card refusals.
**Test and CI results:** not available from completed checks on the
current head.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
|
||
|
|
05a6931471 |
chore: version packages (alpha) (#30172)
This PR was opened by the [Changesets release](https://github.com/changesets/action) GitHub action. When you're ready to do a release, you can merge this and publish to npm yourself or [setup this action to publish automatically](https://github.com/changesets/action#with-publishing). If you're not ready to do a release yet, that's fine, whenever you add more changesets to main, this PR will be updated. ⚠️⚠️⚠️⚠️⚠️⚠️ `main` is currently in **pre mode** so this branch has prereleases rather than normal releases. If you want to exit prereleases, run `changeset pre exit` on `main`. ⚠️⚠️⚠️⚠️⚠️⚠️ # Releases ## @mastra/client-js@1.60.0-alpha.12 ### Minor Changes - Allow `querySpans()` to sort by `model` or `provider`. ([#30096](https://github.com/mastra-ai/mastra/pull/30096)) ```ts orderBy: [{ field: 'model', direction: 'asc' }]; ``` ### Patch Changes - The generated route types for scores now include the `SCORER` and `PROCESSOR` entity types, matching the entity types experiments can emit. ([#30145](https://github.com/mastra-ai/mastra/pull/30145)) - Add span-local error counts. ([#30088](https://github.com/mastra-ai/mastra/pull/30088)) - Updated dependencies [[`56f654f`]( |
||
|
|
72abae68eb |
feat(observability): export span-local originating error counts (#30088)
## Description Export `errorCount` as failures originating directly on each span. Child failures forwarded through a model step, workflow or agent add no parent count; independent parent failures do. Failed retries remain counted after recovery, and replay does not create new occurrences. No parent/child totals or suspend/resume rollup are maintained. Attribution stays in a WeakMap without modifying user errors. Explicit internal serializers and Inngest memoized operations preserve provenance across boundaries; public workflow results and stored workflow state omit transport metadata. Failures before child execution count on their actual originating span. Excluded spans preserve attribution so their failures cannot be misassigned to visible parents, but excluded failures are absent from exported totals. Retry context stays in the server-only context module, while shared origin utilities use global crypto. Guarded cross-package calls preserve mixed-version startup compatibility. Unsupported accounting and older snapshots remain unknown. Error-free spans do not allocate occurrence sets. Validation: 117 focused observability/workflow/compatibility tests, 23 real Inngest error/retry scenarios and 37 Inngest engine/nested-result checks pass. New regressions reproduced resolver undercounting, excluded-child misattribution and public transport-field leakage before the fixes. Real Inngest tests cover an empty execution graph, unavailable remote child, instrumented child errors, nested propagation, retries, public responses and stored state. Core/observability build, Inngest typecheck, changed-file type-aware lint and CI formatting checks pass. The preceding merge also passed 167 core checks and redaction integration coverage. Playground production builds were verified on Node 24. Docs checks with Vale report no errors (three warnings on unchanged API headings); the CI Vale configuration passes. Standalone observability `tsc` previously reported generic union-call errors in untouched `workflow-control-flow-suite.ts`; package builds and focused tests pass. No production rollout or query-table changes. CI reruns on the new head. ## Related issue(s) Fixes https://linear.app/kepler-crm/issue/OBS-901 Follow-ups: https://linear.app/kepler-crm/issue/OBS-902 and https://linear.app/kepler-crm/issue/OBS-903 Nonblocking review follow-up: https://linear.app/kepler-crm/issue/OBS-905 tracks explicit propagated classification on previously untagged errors and reuse of one Error object across separate foreach iterations. Changesets intentionally remain single sentences per maintainer direction. ## Type of change - [x] New feature (non-breaking change that adds functionality) - [x] Documentation update - [x] Test update ## Checklist - [x] I have linked the related issue(s) in the description above - [x] I have made corresponding changes to the documentation (if applicable) - [x] I have added tests that prove my fix is effective or that my feature works - [ ] I have addressed all Coderabbit comments on this PR <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 This change counts each error on the span where it first happened. It keeps the count correct when errors are wrapped, retried, or rebuilt, so one failure is not counted twice. ## Summary - Adds span-local `errorCount` to exported spans. The count covers failures that start directly on that span. - Adds `claimSpanError`, `BaseSpan.recordError`, and `BaseSpan.restoreErrorCount`. Each claim records one occurrence ID on the span. - Ignores propagated failures on the receiving span. Propagated failures count only on their origin span. - Keeps error origin through cause chains, durable tool serialization, and event codecs. - Stores origin metadata in a `WeakMap` for live errors and formatted results. Omits it from public workflow JSON. - Stores occurrence IDs in span snapshots. Rebuilt spans restore them, so replayed attempts are not counted again. - Records failed attempts for default, evented, and Inngest workflow retries. Each attempt uses an attempt-scoped occurrence ID. - Reports `errorCount` as unknown when the runtime lacks the claim API or when an older snapshot has no accounting history. - Updates tracing types, the span record schema description, the span reference documentation, and changesets for `@mastra/core`, `@mastra/observability`, `@mastra/client-js`, and `@mastra/inngest`. - Adds tests for repeated reports, retry scopes, concurrent async spans, excluded children, cause-linked errors, tool and agent spans, rebuilt and legacy snapshots, codecs, durable serialization, workflow retries, and ESM/CJS compatibility with an older core build. ## Scope - Parent and child totals are not computed. - Suspend and resume rollups are not computed. - Query-time summation, display, filtering, sorting, and aggregate-table integration are not included. These are tracked in [OBS-902](https://linear.app/kepler-crm/issue/OBS-902) and [OBS-903](https://linear.app/kepler-crm/issue/OBS-903). - Counts reflect observed exported failures only. Filtering, sampling, or loss before export can leave counts incomplete. ## Change size - 32 files changed - 862 lines added - 161 lines removed ## Validation - Completed checks on the current head: not available from the supplied evidence. - Author-reported results, not verified here: - Focused observability tests, codec and durable-serialization checks, and engine and Inngest retry scenarios. - Node 24 builds, 167 core checks, 125 observability and redaction tests, and 19 real Inngest scenarios. - Type-aware lint and `lint:format`. - Known limitations: - A prior monorepo E2E attempt did not run application assertions. Fixture dependency installation failed with a pnpm store ENOENT error. - Earlier runtime tests ran on Node 23.11.0, which is outside the supported engine range. - Standalone observability `tsc` reports errors in an untouched test utility. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
46ce164dde |
fix(factory): recover stuck environment builds and rebuild on saved changes (#30148)
Environment templates could stop rebuilding for good, and changing a
setup command never rebuilt them.
When a build start isn't recorded (for example the process restarts
mid-start), Factory marks the start uncertain and asks the provider for
its build list before building again. Mastra Platform has no build list,
so that mark could never clear: every Build now, schedule and push run
skipped with `unresolved` forever and sessions kept booting an old
template. Now an uncertain start ages out 30 minutes (the build wait
ceiling) after its lease lapsed, Factory logs once that it gave up on
it, and the next trigger builds. A new `build_start_uncertain_since`
column records when the mark started; rows already stuck get stamped on
their next read and recover 30 minutes later.
Saving a template input (setup commands, working directory, settings,
environment repositories, Build variables) also never started a build,
so each new sandbox reran the changed setup command. Saves now start a
build once the project has a template, only when the inputs actually
differ from the last build. Repeated saves don't double-build, and a
change saved during a build is built when that build ends.
Before: a project stuck on `unresolved` stayed on its Oct 28 template,
and a new setup command reran for 40s in every sandbox. After: the stuck
project builds on its next trigger after 30 minutes, and saving the
setup command rebuilds the template.
Tested with red/green tests on LibSQL and Postgres 16 using real storage
and a fake clock, plus route tests for every save path.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
**ELI5:** Sometimes the system got stuck while it prepared a project's
build environment, and it did not try again for a long time. Also,
saving changes to the project's setup did not start a new build. This
change fixes both problems. Stuck builds now recover, and saved changes
now start a new build when they affect the template.
## Overview
This change fixes two problems in Factory environment template builds.
1. **Stuck build starts.** A build start can stay `unresolved` for a
long time when the provider cannot list builds.
2. **Missing rebuild on save.** Saving changed template inputs did not
start a build.
Diff base: `main` at merge base
`
|
||
|
|
4e378c3e26 |
feat(factory-ui): let an intake route join a pull request to its issue's card (#30197)
An intake route can put a pull request on the card of the issue it
closes instead of giving it a card of its own, but only the route
Factory seeds ("Pull requests that close a waiting issue join its card")
could do it. The Add route form in Settings → Work Intake always saved
`joinClosedIssue: false`, and a saved route had no control for it, so an
admin could not make a second joining route or get one back after
deleting the seeded one.
Routes now carry a "Join the issue's card instead" switch. It is offered
on a new route, and on a saved new-card route, once the conditions
include "Source kind is Pull request" and "Pull request closes an issue
is Yes". Turning it on changes the outcome label from "Send to" to "Join
the issue's card, move to" and offers every unfinished phase, since the
card is already on the board. A line under the switch says only trusted
authors' pull requests join and others get their own card.
```ts
// before: every route the form made
target: { boardKey: 'work', phaseKey: 'intake' }
// after, with the switch on
target: { boardKey: 'work', phaseKey: 'building', joinClosedIssue: true }
```
A route that already joins keeps the switch even if its conditions no
longer qualify, so it can still be turned off. Turning it off on a route
parked in a phase new cards cannot land in moves it back to the board's
first phase. Card moves and the catch-all never show it, and the "send
new cards to" logic ignores joining routes as before.
Tested with MSW against the real client: creating a joining route sends
`joinClosedIssue: true`, the switch stays hidden without both conditions
and goes away when they are narrowed, and toggling a saved route PATCHes
its target at the revision it was read at. The first and third fail on
main, the second fails if the switch is always offered. Also run by hand
on a local Factory with its own throwaway Postgres; screenshots are in
`.pr-review/` locally. The full MSW suite was not rerun, only the
settings and board config folders, where the ten failures are the memory
settings ones that fail on main.
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
|
||
|
|
f0710446e0 |
feat(observability): sort spans by model and provider (#30096)
Adds ascending/descending `model` and `provider` ordering to
`querySpans()` across Core, server, Client JS, PostgreSQL, DuckDB and
ClickHouse. No schema changes or backfill.
```ts
orderBy: [{ field: 'model', direction: 'asc' }]
```
Sorting uses the dedicated columns before pagination, with
case-sensitive UTF-8 ordering, missing values last, and identity
tie-breakers. String cursors preserve their values and remain bound to
the query and trusted scope. Legacy attribute-based display values
remain available without changing cursor boundaries. Trace/thread sort
fields stay unchanged. The server advertises
`spanQueryModelProviderSort` and rejects unsupported stores.
This PR is API-only. Studio sorting controls and live-refresh changes
are tracked in
[OBS-906](https://linear.app/kepler-crm/issue/OBS-906/add-model-and-provider-sorting-to-spans-explorer).
Enabling those controls needs raw model/provider sorting values
available to the existing head-row merge, including when polls are
ordered by end time; using display values can disagree with database
ordering. The PR has no remaining Playground UI changes or release
entry.
Validation: Core/server tests, real storage conformance across
PostgreSQL, DuckDB and ClickHouse, mixed-core checks, and
Core/server/adapter typechecks passed for the API implementation. After
removing the UI changes, both existing span component/hook suites pass
(52 tests). Changed-file lint and docs checks including CI Vale pass.
A bounded local ClickHouse 26.6.8.7 comparison used 180,000 synthetic
rows, 10,000 matches per tenant, distinct tenants across cases, both
directions and continuation pages, and disabled query/condition caches.
Median CPU was 21.9 ms for start time, 19.4 ms for model, and 21.4 ms
for provider; median query memory was about 4.6 MiB for each (maximum
6.8/8.4/7.2 MiB). These are selection-query measurements on synthetic
OSS data, not a production benchmark.
Part of OBS-896. Platform API support and package pins follow this OSS
merge and snapshot publication. UI enablement is tracked separately in
OBS-906.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
**ELI5:** Trace spans can now be sorted by their model name and provider
name, in both directions. The database does the sorting, so users can
page through the results in the right order.
## Overview
This change adds `model` and `provider` as sort fields for span queries.
It applies to the Core API, the server handlers, and the PostgreSQL,
DuckDB, and ClickHouse stores. The diff has 31 changed files, with 320
lines added and 43 removed.
## Core changes
- `SPAN_QUERY_ORDER_FIELDS` now includes `model` and `provider`.
- `SpanQueryPlanOptions` adds `allowSpanModelProviderOrdering?:
boolean`. Ordering by these fields requires this option.
- Trace and thread queries do not support these fields.
- Cursor validation accepts string or null values for `model` and
`provider`. Timestamp normalization applies only to `startedAt` and
`endedAt`.
- `SpanQuerySelectedRow` adds an optional `cursorSortValue`. Response
construction removes this field from returned spans. It uses the value
for the next-page cursor, and falls back to the row's ordering field
when the value is absent.
- The base storage feature union adds `span-query-model-provider-sort`.
## Server changes
- `assertObservabilitySpanModelProviderSortSupported` returns HTTP 501
with `SPAN_QUERY_UNSUPPORTED` when a store does not declare
`span-query-model-provider-sort`. The check runs before `querySpans` is
called.
- `ObservabilityStorageCapabilities` and its empty default add
`spanQueryModelProviderSort`, which defaults to `false`.
- The capability is reported as supported only when span queries are
supported, the core order fields include both `model` and `provider`,
and the store declares the feature.
- The system capabilities schema adds `spanQueryModelProviderSort:
z.boolean().default(false)`.
- The route handler permits model and provider ordering and performs the
capability check.
## Store changes
- **PostgreSQL:** Sorts by `model` and `provider` use `COLLATE "C"`. The
cursor bounds cast sort values to `text COLLATE "C"` when `stringSort`
is enabled. The feature is advertised only when the core order fields
include both fields.
- **DuckDB:** Sorts by `model` and `provider` use `"C"` collation.
Cursor values cast as strings with the same collation. The feature is
advertised only when the core order fields include both fields.
- **ClickHouse:** `afterCursor` treats `model` and `provider` as
strings. Null rows are included after the cursor for numeric and string
sorts. The feature is advertised only when the core order fields include
both fields.
- Returned `model` and `provider` values may still come from span
attributes. The code comments state that these fallback values are not
used for filtering or sorting.
## Tests and conformance
- Core tests cover ordering gating, rejection in trace and thread
queries, string and null cursor values, and rejection of cursors when
the order, filters, authorization, or scope change.
- Server tests cover the 501 rejection for `durationMs`, `model`, and
`provider` on older stores. They also cover capability parsing and the
capability flag in the system endpoint.
- Shared conformance tests in `stores/_test-utils` cover ascending and
descending pagination at page sizes 1, 2, and 3. They cover empty
strings, missing values, case and Unicode ordering, ties, and filter
exclusion. They also check that missing values sort last and that legacy
attribute values are not treated as dedicated fields.
- Store feature-list tests for ClickHouse, DuckDB, and PostgreSQL expect
the new feature flag.
## Changesets and documentation
- Changesets add minor release notes for `@mastra/core`,
`@mastra/server`, `@mastra/client-js`, `@mastra/duckdb`,
`@mastra/clickhouse`, and `@mastra/pg`.
- The advanced query reference adds the `spanQueryModelProviderSort`
capability row. It documents `model` and `provider` ordering. It states
that the comparison is case-sensitive and that missing values sort last
in both directions.
## Scope and limits
- This diff does not include Studio UI changes. The commit history says
UI enablement is deferred to a separate issue because it needs raw model
and provider values for head-row merging.
- This diff does not include client-js source changes. Its client-js
changeset documents the new sort fields.
- The diff does not include schema changes or backfill.
- The PR description reports these results, which this review did not
run or verify:
- Core and server tests, and real shared-storage conformance and
mixed-core checks, pass.
- Core, server, and adapter typechecks pass. Staged-file lint and docs
checks, including CI Vale, pass.
- 58 Studio and MSW tests pass.
- The full Playground UI typecheck reports four unrelated chart and form
errors, and the library declaration build fails.
- A local ClickHouse 26.6.8.7 comparison with 180,000 synthetic rows
measured median CPU of 21.9 ms for start time, 19.4 ms for model, and
21.4 ms for provider. Median query memory was about 4.6 MiB for each.
These figures are not production measurements.
- Platform backend and UI wiring, and package pins, remain under
OBS-896.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
|
||
|
|
ba2529c209 |
docs(models): explain when to use custom gateways and the base class (#30066)
## Description The custom gateways guide showed a plain-object gateway and a `MastraModelGateway` subclass. It didn't explain when to use a custom gateway or why you'd extend the class. Changes: - `docs/src/content/en/models/gateways/custom-gateways.mdx` - New "When to use custom gateways" section, which replaces the "Create custom gateways to support" list. - It describes a custom gateway as the way to connect Mastra to open-weight models you run yourself, such as gpt-oss, Llama, Gemma, Mistral, Qwen, or DeepSeek. - It lists when self-hosting fits: compliance rules on sending data to third parties, per-token pricing that costs more than running your own GPUs, fine-tuned models, model versions that only change when you upgrade, and offline, air-gapped, or edge deployments. - It notes what the gateway adds: typed model IDs and a Studio model picker, per-call credential resolution, and Studio filtering with `AUTO_BLOCK_EXTERNAL_PROVIDERS`. - For a single OpenAI-compatible endpoint, it points to `url` in the model config instead. It also says to set `apiKey` there, because Mastra doesn't read environment-variable keys for `url` models. - New "Choose a plain object or a class" subsection. Both forms behave the same at runtime, because the base class defaults for `getId()`, `shouldEnable()`, `handlesModel()`, and `serializeForSpan()` match the fallbacks in `gateway-helpers.ts`. A class makes sense when you need constructor options, private state, or several instances. - Replaced the class example with one that takes optional `id`, `baseURL`, and `apiKey` constructor options. Added a two-instance example with distinct IDs, because `GatewayManager` deduplicates gateways by ID. Both examples now forward `headers` in `resolveLanguageModel()`. - "Showing only custom gateways in Studio" now says the filter also applies to `GET /agents/providers`. It only changes which providers are listed, and doesn't stop agents from calling other providers in code. - `docs/src/content/en/docs/studio/overview.mdx`: the model picker section now mentions `AUTO_BLOCK_EXTERNAL_PROVIDERS` and links to the custom gateways section. ## Related issue(s) Docs follow-up from a Slack question about `MastraModelGateway`. ## Type of change - [ ] Bug fix (non-breaking change that fixes an issue) - [ ] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [x] Documentation update - [ ] Code refactoring - [ ] Performance improvement - [ ] Test update ## Checklist - [ ] I have linked the related issue(s) in the description above - [x] I have made corresponding changes to the documentation (if applicable) - [ ] I have added tests that prove my fix is effective or that my feature works - [x] I have addressed all Coderabbit comments on this PR Link to Devin session: https://app.devin.ai/sessions/922f1f27155a4c858ce0e76079f78b2f Open in Devin Desktop: https://app.devin.ai/desktop/session/922f1f27155a4c858ce0e76079f78b2f?variant=devin --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: paul <paul@mastra.ai> |
||
|
|
43d1e9c16d |
fix(ui): fix hover highlight not covering the corner (#30047)
Hovering a card (the credits card in Platform's sidebar, project cards, any clickable `Card`) tinted a second rounded shape 1-2px inside the card, so a thin untinted ring showed along the edge, widest at the corners. Now the hover tint is the surface's own background, so it covers the whole surface and follows any corner radius exactly. The fix is in the shared `state-layer` utility, so every surface that uses it changes. ## Before / After Hovered, dark, zoomed 4x on the bottom-left corner. Look for the darker crescent at the corner in "Before". | | Before | After | | --- | --- | --- | | Platform project card | <img src="https://github.com/user-attachments/assets/7ed1f23b-c0f0-45b0-8313-f1b3ff39058c" width="300" alt="Before project"> | <img src="https://github.com/user-attachments/assets/bb3a627a-668a-4002-9392-57dc8f5f3520" width="300" alt="After project"> | | Platform credits card | <img src="https://github.com/user-attachments/assets/88896a43-4a0f-451f-950f-865d8917b2cf" width="300" alt="Before credits"> | <img src="https://github.com/user-attachments/assets/04700558-04ee-4ece-a240-428964035c48" width="300" alt="After credits"> | | `CardLink` | <img src="https://github.com/user-attachments/assets/00675559-99de-4ccf-ac54-d87c53ac74b9" width="300" alt="Before card"> | <img src="https://github.com/user-attachments/assets/bbe15805-fd38-4282-88da-3ca12efc94fd" width="300" alt="After card"> | | Composer attachment | <img src="https://github.com/user-attachments/assets/6bdf4093-2dad-4a83-85be-003dcdc93a7d" width="300" alt="Before attachment"> | <img src="https://github.com/user-attachments/assets/d325d318-7eea-4554-b489-12b7f7c011b7" width="300" alt="After attachment"> | | Workflow edge Data button | <img src="https://github.com/user-attachments/assets/580d836d-6cc0-4f78-87bb-f559d9c614d7" width="300" alt="Before edge"> | <img src="https://github.com/user-attachments/assets/a0c68b78-0e34-43e4-b102-eb1d81dd8c15" width="300" alt="After edge"> | | Ask-user option | <img src="https://github.com/user-attachments/assets/7611683d-9b2c-453a-a674-a3f9b5950272" width="300" alt="Before ask"> | <img src="https://github.com/user-attachments/assets/105ad584-4a9c-4f18-b10b-f3cf553ef00b" width="300" alt="After ask"> | ## What changed - `state-layer` paints its hover/press tint as a flat `background-image` over the element's fill, instead of a `::before` overlay inset by 1px. The browser clips it to the element's own shape, borders and inset-shadow rims draw over it, and `position`, `isolation` and the negative z-index are gone. `surfaceGroupStateLayerStyle` does the same. - Two consumers painted on the old layer and move to the new one: the composer attachment's dark fill goes to `--surface-tint`, and the edge Data button's selected fill becomes the same `--fill` image the utility uses for press. - 14 files only re-sort the `state-layer` class (the formatter orders it with the background utilities now). ## Why The overlay existed to keep the tint layered over an opaque fill (swapping `background-color` for a translucent rung makes the surface see-through) and to let it fade. It was shrunk 1px so it wouldn't cover the inset rim, which is what made the second shape. A background image keeps the layering and needs no shrinking. It can't fade, so these hovers are now instant, in line with the other instant-hover changes. ## Testing 1. Platform home: hover a project card. The tint reaches the edge, no darker crescent at the corner. Same for the sidebar Credits card. 2. Storybook, Layout/Card "Interactive links", AI/Composer attachments, Workflows/Edge data, AI/Ask user: hover each. Same result. 3. Workflows/Edge data "External inspector": click Data, move the pointer away. It keeps the selected fill. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 This PR makes hover and press highlights cover the full shape of cards and buttons. Highlights now follow rounded corners, remain below borders and inner shadows, and switch instantly. ## Summary - Replaced the inset `::before` state layer with clipped `background-image` fills. - Updated grouped surfaces to use the same highlight approach. - Moved composer attachment fills to `--surface-tint`. - Preserved the selected fill for the workflow edge Data button. - Updated state-layer documentation and the theme export test. - Reordered `state-layer` classes in affected consumers. - Added a patch changeset for `@mastra/playground-ui`. **Scope:** 21 files changed; 48 insertions and 63 deletions. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
f9088d8510 |
feat(mcp-apps-components): accept the editor's widget shapes in chat-authored dashboards (#30192)
Dashboards authored in chat rejected several widgets the dashboard
editor can build, so a model couldn't recreate what a user had in the
editor. This widens the shared option schemas in `@mastra/playground-ui`
and the renderers behind them, and the chat authoring schema in
`@mastra/mcp-apps-components` picks the changes up.
KPIs can now combine values (`ratio`, `minus`, `max`, `coalesce`), read
score, trace and span aggregates, and use the `duration`, `percent` and
`score` formats. Percentiles come through trace/span measures, which
give one whole-range value (metric percentiles are always bucketed, so
they can't make a single KPI figure). KPIs now also request the previous
window, so combined values show a change:
```ts
{
label: 'Error rate',
format: 'percent',
value: {
ratio: {
of: { traceAggregate: { measure: 'errorCount', compare: 'previousWindow' } },
over: { traceAggregate: { measure: 'count', compare: 'previousWindow' } },
},
},
}
// p95 latency
{ label: 'p95 latency', format: 'duration', value: { traceAggregate: { measure: 'duration.p95', compare: 'previousWindow' } } }
```
Line charts can plot `scoreTimeSeries`, and charts accept `blue`,
`orange`, `pink`, `yellow`, `red` and `purple`, all mapped to existing
data-viz tokens. KPI `icon` and `detail`, series `color` and table
`emptyMessage` are now optional: series without a color take one from a
palette by position, and tables without a message show "No data". Metric
types in the discovery API (counter vs. histogram) are not part of this
PR.
Tested with new widget tests that open dashboards through the real tool:
p95 latency and error-rate KPIs compared with the previous window, plus
a score line chart and a table that set no colors or empty message. The
KPI test fails against the old KPI request plan. Typecheck, lint and the
existing suites pass in both packages.
---------
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
|
||
|
|
e1753c7199 |
feat(factory): stop a card's sandbox as soon as its context is done (#29981)
## What Each Factory card context (Triage, Work, Review, or a custom board's `runner.context`) runs in its own session with its own sandbox, so one card can hold three VMs. Until now only terminal phases released them, and only on the process that had opened the sandbox. A card that left Triage kept its triage VM until the provider's idle timeout, and a card finished on another replica (or after a restart) stopped nothing. This PR stops a card's sandbox as soon as the card is done with that context. - **Leaving a context.** When a committed move takes a card out of the last phase of a context into a phase that runs in another context, Factory stops that context's sandbox. Triage → Planning stops the triage sandbox. Planning → Building stops nothing, because both run in `work`. - **Finishing.** Done/Canceled stop every sandbox the card holds. When this process never opened a sandbox, it stops it by identity through the configured provider, the same way session deletion already destroys by identity. It stops, it does not destroy. There is no TTL sweep. - **Coming back.** A stop keeps the session row, branch and files, so PR review → Triage resumes the same sandbox: E2B resumes the paused VM by its metadata tag, Docker restarts the container by name, and local reuses its directory. Platform `stop()` sends nothing remotely; that VM idles out under its environment policy, and the next run reattaches by session id. ## How - `FactoryTransitionService` gets an `onContextLeft` hook beside `onTerminalStage`. It fires only for accepted moves where `roleForPhase(from) !== roleForPhase(to)` and the new phase is not terminal. Both hooks share one bounded, best-effort runner (`#bounded`): a committed move never fails or hangs on cleanup. - `sandbox/context-sandboxes.ts`: - `createContextSandboxStops` re-reads the card and skips if the revision moved (the same stale guard as terminal cleanup). It also skips if the card is back in the context or holds the same session under its new context. - **Run in flight:** if a run is active on the left session in this process (the agent whose own tool call made the move, or a person chatting), the stop waits for that run's `agent_end` and then re-checks only that the card has not come back. The run isn't awaited inside the hook, because it may be the very tool call waiting on this transition. I picked this over the `initiatingBindingId` skip because it covers both the initiating agent and a person in the session, and still stops the sandbox afterwards instead of leaving it to the terminal path. - `createTerminalSandboxStops` is the existing terminal retirement moved out of `factory.ts`. - `SessionRetirementCoordinator.stopSessionSandbox` stops a session's sandbox without teardown and invalidates its workspace. A detached sandbox is reached through the new `stopDetachedSessionSandbox`. Retirement without deletion now also stops a detached materialized sandbox by identity; before, it left it to the provider. ## Known limits - A run live on **another** replica is not seen by the in-flight check, because there is no shared signal for human chat. Leaving a context from replica A while a run streams on replica B can pause that E2B VM under it. Terminal retirement has never had a human-chat guard, so the terminal path behaves as before, except that it now reaches detached sandboxes. - The local provider persists no physical sandbox id, so a local sandbox opened on another process can't be stopped by identity. Local has no remote VM, so nothing keeps billing. ## Test plan New `src/sandbox/context-sandboxes.test.ts`, real storage on LibSQL and Postgres (`FACTORY_TEST_POSTGRES_URL`, throwaway container), with the real `LocalFactorySandbox`: - Triage → Planning stops the triage sandbox only; the work sandbox stays running. - Planning → Building stops nothing. - Back to Triage resumes a new instance on the same directory, and a file written before the stop is still there. - A run in flight on the triage session holds the stop until it ends; a card back in Triage by then keeps its sandbox. - Done on a second Factory over the same database (a process that never opened the sandboxes) stops all three by identity. - The move still commits when the stop throws. Red: with the transition/retirement changes reverted, 4 of 7 fail. Mutation-checked the come-back guard. `session-retirement.test.ts`: the case that pinned "retire without delete never touches a detached sandbox" was flipped to the new contract. `factory.test.ts` asserts the hook is wired when a sandbox is configured (red without the wiring). Gates: `check` 0, `lint` 0/0, `build:lib` ok. `src/sandbox src/rules factory.test sandbox-release source-control-sessions` on LibSQL+PG: 1114 passed. The only failures are 2 `board-phase-runtime` "custom phase that runs an app skill" cases, which fail the same way on main (a third fails only under load). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 When a card leaves a work context, this change stops the sandbox that context used. It keeps the session and its files, so the card can resume that sandbox if it returns. When a card reaches Done or Canceled, the change stops every sandbox the card holds. ## Changes - Adds `onContextLeft` to `FactoryTransitionService`. The hook runs after an accepted move that leaves the last phase of a context for a different context or for no context. Moves between phases in the same context do not stop a sandbox. - Adds `controllerRunInFlight`. If a run is active in the current process, the context-leave stop waits for `agent_end`. After the run ends, the stop checks whether the card returned to that context. If it did, the sandbox keeps running. - Adds `createContextSandboxStops`. It checks the card revision and skips missing cards or sessions. It keeps the sandbox if the card returned to the left context or still holds that session. - Adds `createTerminalSandboxStops`. It deduplicates the session IDs on a finished card and retires each sandbox without deleting its session. `MastraFactory` uses it for terminal work-item cleanup in place of the previous inline logic. - Adds `SessionRetirementCoordinator.stopSessionSandbox`. It serializes the stop, verifies the session and organization, and stops the attached sandbox. For a detached sandbox, it stops the sandbox by identity through the configured provider. It invalidates the session in a `finally` block. - Changes detached-sandbox cleanup in `session-retirement.ts`. When `deleteSession` is false, cleanup stops a materialized sandbox. When `deleteSession` is true, cleanup destroys it. Sessions without a persisted sandbox ID or configured sandbox are skipped. - Adds `stopDetachedSessionSandbox` in `sandbox-release.ts`. It creates a provider sandbox from the session ID and optional sandbox ID, with repository access disabled, and calls plain `stop()`. - Keeps cleanup bounded and best-effort. The transition service awaits each hook with the terminal-cleanup timeout. Errors are swallowed. If the timeout expires, cleanup continues in the background. A failed stop does not fail or roll back a committed move. - Stopping preserves the session row, branch, and files. Session deletion still destroys the sandbox. - Adds docs: a `@mastra/factory` changeset and a "Card sandboxes" section in the factory README. - Adds tests in `context-sandboxes.test.ts` for LibSQL and, when `FACTORY_TEST_POSTGRES_URL` is set, PostgreSQL. The tests cover context-leave stops, same-context preservation, resumption on return, in-flight runs with a real controller, terminal cleanup of persisted sandboxes, accepted moves when a stop fails, and idle versus active sessions. Also adds a `MastraFactory.prepare` test and updates the session-retirement test fake to record `stop` calls. ## Known limits - An in-flight run on another replica is not detected. The stop does not wait for that run. - A local sandbox opened by another process cannot be stopped by identity. ## Validation Completed test and CI results are not available for the current head. The PR objectives report `check`, `lint`, `build:lib`, and test results, but these are author-reported and not confirmed as completed checks on this head. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
686c178917 |
fix(voice): replace retired default OpenAI Realtime model (#30183)
## Summary - Default new OpenAI Realtime voice connections to `gpt-realtime-2.1-mini` instead of the retired preview model. - Align the constructor examples, README, and voice integration documentation with the new default. - Cover default and explicit model selection with a real local WebSocket handshake regression test and a patch changeset. ## Test plan - `pnpm turbo build --filter="@mastra/voice-openai-realtime^..."` - `pnpm --dir voice/openai-realtime-api test` (70 tests) - `pnpm --dir voice/openai-realtime-api exec tsc --noEmit --project tsconfig.json` - `pnpm --dir voice/openai-realtime-api lint` - `pnpm --dir voice/openai-realtime-api build` Fixes #29722 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> **ELI5:** The OpenAI voice connector picked an old model by default, and OpenAI has shut that model down. This change makes the connector pick a current model by default. Users who set their own model still get that model. **Overview** This change replaces the default OpenAI Realtime model in `@mastra/voice-openai-realtime` with `gpt-realtime-2.1-mini`. The previous default was `gpt-4o-mini-realtime-preview-2024-12-17`. Linked issue `#29722` reports that OpenAI lists this snapshot as shut down. **Changes by file (5 files, +36/-8 lines)** - `voice/openai-realtime-api/src/index.ts` (+4/-4): Sets the default realtime model to `gpt-realtime-2.1-mini`. Updates the class example, the model-option documentation, and the constructor example. - `voice/openai-realtime-api/src/connection.integration.test.ts` (+24/-1): Adds a local WebSocket handshake test. The `setup` helper accepts an optional model and types the connection callback with the WebSocket and `IncomingMessage`. Parameterized tests check the model in the connection URL for two cases: no model configured (expects `gpt-realtime-2.1-mini`) and an explicit model (expects that model). - `voice/openai-realtime-api/README.md` (+1/-1): Usage example uses `gpt-realtime-2.1-mini`. - `docs/src/content/en/integrations/voice/openai.mdx` (+2/-2): Realtime usage example and constructor options use `gpt-realtime-2.1-mini`. - `.changeset/realtime-mini-default.md` (+5/-0): Patch changeset for `@mastra/voice-openai-realtime`. **Behavior** - Without a `model` option, the connection URL requests `gpt-realtime-2.1-mini`. - With a `model` option, the connection URL requests the configured model. - No exported or public declarations change. **Validation** The author reports these commands. This summary does not confirm their results: - `pnpm turbo build --filter="@mastra/voice-openai-realtime^..."` - `pnpm --dir voice/openai-realtime-api test` (70 tests) - `pnpm --dir voice/openai-realtime-api exec tsc --noEmit --project tsconfig.json` - `pnpm --dir voice/openai-realtime-api lint` - `pnpm --dir voice/openai-realtime-api build` **Scope limits** The linked issue also mentions future shutdowns for `whisper-1` and `tts-1`. This change does not alter those defaults. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com> Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
6023a04173 |
Add release changeset for the Mastra Code settings crash fix (#30184)
## Summary - Add a `mastracode` patch changeset for the fix already merged in #30180. ## Test plan - `pnpm exec prettier --check .changeset/mastracode-legacy-mouse-settings.md` - `pnpm exec changeset status --output /tmp/mastracode-changeset-status.json` Ref #30109 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ELI5: Some saved settings files do not include a mouse option. When that happens, the `/settings` command in mastracode crashed. This change adds a release note for the fix. With the fix, a missing mouse option uses Off. ## Summary of changes This PR adds one changeset file: `.changeset/mastracode-legacy-mouse-settings.md` (new file, +5 lines, 0 removed). The changeset: - Marks the `mastracode` package for a `patch` release. - Describes the fix: `/settings` no longer crashes when saved settings lack mouse preferences. The missing setting defaults to Off. The PR does not change any source code. The fix itself was merged earlier in `#30180`. This changeset tracks that fix for the next `mastracode` release. ## Review notes - Scope: documentation-only change to release metadata. - Code impact: none in this diff. - Checks: the PR lists `prettier --check` and `changeset status` as test steps. Their results are not available from the supplied evidence. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com> Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
56f654fc0d |
fix(core): name the agent in the memory missing-storage error (#30164)
Co-authored-by: Abhi Aiyer <abhiaiyer91@gmail.com> |
||
|
|
993c85892c |
Prevent /settings from crashing on missing mouse preferences (#30180) | ||
|
|
1fbc69aa9a |
feat(factory): count the new session page's starters and activity on the server (#30097)
**─────── TLDR ───────** > The new session page now gets its starter counts and activity dates from two small server reads instead of downloading every card of the project. To show a handful of numbers, the page read the whole board: 1,505 KB gzipped on the 8,078-card board measured in #28915. The rules that decide which cards a starter counts now run on the server, and the browser keeps the wording and the layout. Since #30099 a tab that already holds the board only reads the cards that moved. What this PR removes is the first download, and the board the tab had to keep to count on it. Fifth step of removing whole-board reads, after #30080, #30083, #30087 and #30081 (⌘K). The board page comes next. ### Behavior changed opening a new session page ├─ **was** — every card of the project downloaded, then counted in the browser └─ **now** — two reads: the starter counts, and the instants of the period a card changes while the page is open ├─ **was** — the cards that moved, merged into the board the tab kept └─ **now** — the two reads asked again; the instants come back only when one was added or removed, a `304` otherwise choosing "This month" in the activity band ├─ **was** — recounted at once on the board the tab kept └─ **now** — one more read; the band stays up on the week's instants until it answers the live session counts in the activity band ├─ **was** — read off the whole board └─ **now** — read off the sidebar's cards holding a session, already loaded a pull request card whose source reports no state ├─ **was** — finished only in a phase named `done` or `canceled` └─ **now** — finished in any terminal phase of the default board the page served by a Factory server without the two routes └─ **new** — starters and activity band stay hidden, the rest of the page works; feed frames do not ask the two routes again ### Shape changed | | | | |---|---|---| | **+** | `routes/work-item-starters.ts` | the starter rules, moved here from the browser; they read the cards as storage holds them | | **+** | `routes/work-item-activity.ts` | the instants one period needs | | **+** | `hashedBody()` in `routes/board-snapshot.ts` | a computed answer and the `ETag` naming it | | **~** | `starterPrompts.ts` | words the counts, no longer reads cards | | **+** | `queryKeys.boardFacts(id)` | answers computed from the board, refreshed with it | | **+** | `activityDepth(period)` | one home for "Today reads the week's answer" | | **−** | draft page in `pageLoadsBoard` | it no longer reads the board | | **−** | `doneAt` in `boardItems.ts` | its only caller moved to the server | what callers can now ask `GET …/work-items/starters` · `GET …/work-items/activity?since=<instant>` (answers `304` to `If-None-Match`) · `mastra api factory work-item starters` · `mastra api factory work-item activity` ### Decisions - **counted on the server, not from a smaller card list** — the page needs eight numbers, not cards; a new starter now takes a server rule plus its wording - **instants, not buckets** — the browser buckets in the viewer's time zone and Today reuses the week's answer; bucket on the server if the list ever weighs - **no whole-board fallback on an older server** — the two blocks hide until the server is deployed; one `catch` away if you disagree - **counted on stored cards, not on their wire copy** — copying every card per request was three quarters of the read's time; the rules merge the work item's facts with the card's where they read them - **recounted on every request, no memo per board** — a memo would have to expire with the clock (stale pull requests), the board registry and the decisions; the count costs 1 to 5 ms - **`ETag` on the instants, none on the counts** — the counts weigh about 150 bytes; the page asks the instants from the top of the hour so the address repeats and the browser can revalidate - **the other depth stands in while a period loads** — two observers, one enabled; a placeholder would set the band's clock to zero ### Gain Opening the page on 2,500 cards with ~2 KB descriptions: the whole board, 1.2 MB gzipped, becomes about 150 bytes of counts plus 27 bytes per card created or completed in the period. That is 1.9 KB when the cards were filed over 400 days, 67.9 KB when all 2,500 fall in the week (sent uncompressed: instants gzip about 3.5×). Once the page is open, this branch does not beat `main`, it costs a little more. One refresh of one open tab, at most every 5 s: | one refresh of an open tab | 2,500 cards | 10,000 cards | |---|---|---| | `main`, nothing changed | 0.5 ms · 124 B | 1.4 ms · 122 B | | here, nothing changed | 2.4 ms · 154 B | 7.7 ms · 156 B | | `main`, one card filed | 860 B | 868 B | | here, one card filed | 2,030 B | 5,921 B | "here" adds up the three reads the page makes: cards holding a session (`304`), starters, instants. Cards filed over 400 days, medians of 10 rounds in the in-memory route harness. When every card falls in the week the two counts take 0.98 + 1.15 ms at 2,500 cards and 4.27 + 4.60 ms at 10,000. Counting on stored cards took the starters function from 1.11 to 0.29 ms at 2,500 cards and from 4.61 to 1.15 ms at 10,000. ### Watch > [!WARNING] > The starter rules moved from the browser to the server together with their scenario tests. <mark>A porting mistake would show as a wrong number on a starter button</mark> and nowhere else, so compare a few buttons with the board after deploy. on merge: nothing to do. `main` with #30153 is merged into this branch and the CLI route metadata check passes. ### Not verified - [ ] against a real board or Postgres — the timings come from the in-memory route harness - [ ] the `304` in the signed-in app — the route is tested, and headless Chromium revalidated a stand-in answer with the same headers, but the real page was not watched against a real server --- > ████████████████████ **tests** `+1077 −431` — 58% of the additions > ███████████ **source** `+572 −222` > ███ **generated** `+177` > █ **changeset** `+24` > █ **docs** `+2` --------- Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local> |
||
|
|
4f301a45b4 |
feat(factory): let sessions query the Factory audit trail (#30165)
> Opened by @user_01KN2T7F5T2WYEMHY58VJGPZ8R ## What Adds `factory_list_audit_events`, a read-only tool that Factory user sessions and MCP clients can use to ask who did what in a Factory: which work item, run, branch or setting changed, who changed it, and when. Filters: - `actor`: `me`, a user id, or `agent:<threadId>`. Add `includeAgentRuns` to also get the agent runs that person started. - `namespace` (e.g. `work_item`, `run`, `agent`) and/or exact `actions` - `workItem` (id or `#123`) - `since` / `until` (ISO times) - `cursor` / `limit` (newest first, max 50 per page) ## Privacy The audit table covers the whole org and nothing limits who can read it. It also stores request context and actor profiles. So this tool trims what it returns: - **Only this Factory's events.** Results are scoped to the caller's org and Factory project. - **No request context.** Client IP and user agent are never returned. - **No actor emails.** Actor display names are returned unless the stored name is an email (the fallback for people with no name), in which case it's left out. The private `__actorProfile` metadata is never returned. - **No event metadata.** Branches, PR URLs, stage details, env var names and model IDs stay out. The tool returns only action, time, actor, `startedBy` for agent events, and targets. - **Private sessions stay private.** An event that names a session (a session target or the session it recorded acting in, e.g. ownership transfers, git pushes, run approvals, signals) is shown only if every such session is in this Factory and shared, or private and owned by the caller. An agent event is also shown only if: - the caller started the run (`startedBy`), or - its thread belongs to a work-item run binding in this Factory (those runs are already on the board), or - its thread resolves to a session in this Factory that is shared, or private and owned by the caller. Anything that can't be resolved stays hidden. Each call reads at most 5 pages of 200 events. Narrow filters therefore return a `nextCursor` and never scan the whole trail in one call. ## Test plan - [x] New `audit-events-tool.test.ts` runs against a real in-memory `AuditStorage` (LibSQL). It covers project/org scoping; stripping of IP, user agent, email and metadata; actor, namespace, action, work-item and time-window filters; cursor paging and rejecting bad cursors; agent visibility across runs, shared, private and own-private sessions plus unresolvable threads; human and agent events naming another person's private session (ownership transfer, git push, signal) or an unknown session; and `includeAgentRuns`. - [x] Tool-list and approval-allowlist tests updated (`work-item-tools`, `messaging-tools`, `factory.test.ts`) - [x] `vitest run src/tools src/factory.test.ts src/mcp`: plus `src/routes/source-control-sessions.test.ts`: 534 passed - [x] `tsc --noEmit`, `oxlint --type-aware`, `prettier --check` clean <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> **ELI5:** This change lets Factory users and MCP clients look up a history of audit events. They can filter the history and page through it. The tool shows only events that the caller is allowed to see. ## Summary This change adds the read-only tool `factory_list_audit_events` to `@mastra/factory`. The tool lists audit events for the caller's Factory organization and project. Results are newest first. ### Filters The tool accepts these optional inputs: - Actor - Agent run started by a person - Namespace or exact actions - Work item - Time range (`since` and `until`) - Cursor - Limit ### Behavior - The default result count is 25. The maximum is `MAX_LIST`, which the PR objectives describe as 50. - The tool reads pages of 200 events. It reads up to five pages per call. - If the result limit or scan budget is reached, the tool returns a continuation cursor. - The tool rejects: - An invalid cursor. - `since` greater than or equal to `until`. - `includeAgentRuns` when the actor is not a person. - An unknown work item returns an error. - An action filter with no matches returns an empty list. ### Output Each result includes: - Action - Time - Actor - An optional display name and starter, without email addresses - Up to ten targets, with truncated text The output omits request context and event metadata. The only exception is who started an agent run. ### Visibility rules - Agent events are visible when the caller started the run or when the run thread is visible. Other agent actors are hidden. - Work-item run threads are visible to Factory members. - Other threads must resolve to a session in the same organization and project. The session must be shared or owned by the caller. - Any session named by an event must pass the same session check. - Missing lookup data and lookup failures deny visibility. Per the PR objectives, two follow-up commits change the following: - Ownership-transfer audit targets stay on the session row ID. This matches the existing session hover-card lookup. - Agent stage moves recorded under run-binding IDs are included. Factory board runs are recognized by binding ID as well as by thread. Unresolved agent IDs stay hidden. ### Interface changes - Added `FactoryAuditToolDependencies` in `mastracode/factory/src/tools/audit-events-tool.ts`. - Added `createAuditEventsTool(scope: FactoryToolScope, deps: FactoryAuditToolDependencies)` in the same file. - `FactoryToolDependencies` in `mastracode/factory/src/tools/index.ts` now includes `FactoryAuditToolDependencies`. - For user scopes, `createFactoryTools` adds the new tool. Non-user scopes still return only messaging tools. ### Other changes - `permissions.ts`: adds the tool to `FACTORY_TOOLS_WITHOUT_APPROVAL`. - `annotations.ts`: adds the tool to `FACTORY_TOOL_ANNOTATIONS` with read-only annotations and the title "List audit events." - `.changeset/factory-audit-events-tool.md`: adds a patch changeset for `@mastra/factory`. - `mastracode/factory/README.md`: documents the tool in the Factory tools table. - Tests: - `audit-events-tool.test.ts` (new, +331 lines) uses in-memory LibSQL audit storage. It covers scoping, privacy, filters, pagination, and visibility. - `factory.test.ts`, `messaging-tools.test.ts`, and `work-item-tools.test.ts` add the new tool to their expected tool lists. ### Diff size 10 files changed, +608 lines and −19 lines. ### Verification - Author-reported: `vitest run src/tools src/factory.test.ts src/mcp` and `src/routes/source-control-sessions.test.ts` passed, 534 tests total. `tsc --noEmit`, `oxlint --type-aware`, and `prettier --check` were clean. - Not independently verified in this review. No completed checks on the current head were inspected. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com> Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com> Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local> Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> |
||
|
|
d97d3c5fd8 |
chore: version packages (alpha) (#30167)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
987566e882 |
fix(core): persist scores for scorer-target experiments (#30145)
Co-authored-by: Abhi Aiyer <abhiaiyer91@gmail.com> |
||
|
|
2742d51576 |
fix(cli): pass filters and lists to Factory list commands (#30153)
**─────── TLDR ───────** > `mastra api factory work-item list` now accepts its filters, and a list of values given to a Factory command reaches the server in the form it reads. Copilot found this on #30081 after it merged. That PR's changeset says `mastra api` can pass the list route's new filters (`started`, `q`, `limit`, `source`). It could not: the command was registered without input, so the JSON was dropped and the whole board came back. This makes that sentence true before it ships. ### Behavior changed `mastra api factory work-item list <project-id> '{"started":"false","q":"login flow"}'` ├─ **was** — the JSON input dropped without a word, every card of the project listed └─ **now** — the filters are sent a list in the input of a Factory command, such as `{"kind":["automation-failed","agent-waiting"]}` on `attention list` ├─ **was** — sent as one JSON string: answered 400, or read as one literal value that matches nothing └─ **now** — one query parameter per value, the form Factory routes read ### Shape changed | | | | |---|---|---| | **~** | `factory work-item list` | takes optional JSON input, like `attention list` and `decision list` | | **~** | `buildUrl(…, route)` | fifth parameter is `{ apiPrefix, repeatLists }`, no longer the prefix alone | ### Decisions - **only on Factory routes** — Mastra API routes parse object-typed query values from JSON, and a single-element `tags` on `trace list`, `log list`, `score list` and `feedback list` only parses in that form; repeating values there would break them - **an empty list and a list of objects keep the JSON form** — an empty list sent as no parameter at all would turn `{"source":[]}` into a request for the whole board ### Watch > [!WARNING] > <mark>A script that already passed a list to a Factory command now sends a different query string.</mark> The old form was answered 400 or matched nothing, so no call that worked changes. on merge: nothing to do. ### Not verified - [ ] against a running Factory server — the tests assert the URL the CLI requests, not the server's answer - [ ] list filters on Mastra API commands (`datasetIds`, `scorerId`, `feedbackType`, `level`) — reading their schemas suggests some are refused in the JSON form the CLI sends today; not run, and not touched here --- > ██████████████████ **tests** `+101 −6` — 77% of the additions > ████ **source** `+24 −4` > █ **changeset** `+7` --------- Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local> |
||
|
|
a4258a989c |
chore: version packages (alpha) (#30127)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
8e93f532c6 |
fix(factory-ui): label search sessions by the phase they run (#30142)
> Opened by @roaminro ## Summary A Factory work item can have one session per context (triage, work, review), and all of them run on the item's branch. Factory search (Cmd/Ctrl+K) showed one row per session, but each row only had the item title, "Work session", the branch, and the issue number. Two sessions on the same item therefore looked like duplicate results. This PR labels each session row with its context. The label comes from `contextLabel()`, the same helper the session page breadcrumb uses, so it shows the board's phase name when only one phase runs in that context and the well-known context name otherwise. Rows now read, for example, `Triage · factory/issue-30123-…` and `Work · current · factory/issue-30123-…`. - The session for the card's current phase is tagged `current` and sorted first within the item. - The context label is searchable, so typing `triage 30123` finds the triage session. - Sessions with no work item keep the existing `Work session` / `Review session` context. - The search dialog already loaded the board catalog; it is now passed into `createSessionSearchGroups`. ## Test plan - [x] New MSW test: a card holding `triage` and `work` sessions on one branch renders two distinguishable rows, with Work marked current and listed first, and `triage 321` narrows to the triage row. The test fails without this change. - [x] `vitest run src/ui/domains/search`: 59 passed - [x] `tsc --noEmit -p src/ui/tsconfig.json` and oxlint pass <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 Factory search showed sessions for the same work item and branch that looked alike. This change gives each session a clear label, such as its phase or context name. The session for the current phase now appears first, so users can tell the sessions apart and find them faster. ## Overview This change makes Factory search sessions distinguishable. Sessions that share a work item and branch now show a context label. The label is searchable. ## Changes - **Search result service** (`services/searchResults.ts`): - `createSessionSearchGroups` accepts an optional `boards?: readonly BoardInfo[]` input. - Work items link to context-specific card sessions. The previous logic linked each stored session reference. - Board phase data feeds the lookup. - Each session result uses its context label and current status to build its context and search value. - The context thread ID sets the result path. If the thread ID is absent, the factory session ID is used. - Results with the same update time sort current-context sessions first. Other results stay sorted newest first. - **Search content component** (`components/FactoryGlobalSearchContent.tsx`): passes `catalog.data` as `boards` to `createSessionSearchGroups`. - **Tests** (`__tests__/GlobalSearch.msw.test.tsx`): - `stubSearchApi` accepts per-repository `FactoryUserSession[]` fixtures. It falls back to `sessionsByRepository` when an entry is missing. - A new test covers a work item with a current Work session and a historical Triage session. It checks that both appear as searchable results, that the Work result is marked current, and that a Triage query returns only the Triage result. - **Changeset** (`.changeset/factory-search-session-phase.md`): adds a `mastra` patch changeset for phase labels, the current marker, and phase-name search. ## Behavior - A context label uses the board phase name when only one phase runs in that context. Otherwise it uses the context name. This matches the session page breadcrumb (per the PR description). - The session for the card's current phase is marked `current` and sorts first within its work item. - Sessions without a work item keep the existing `Work session` or `Review session` context. ## Verification - The author reports that `vitest run src/ui/domains/search` passes 59 tests. The author also reports that `tsc --noEmit -p src/ui/tsconfig.json` and oxlint pass. These results were not re-run for this summary. ## Diff size - 4 files changed, 87 lines added, 13 lines removed. - Exported signature change: `createSessionSearchGroups` gains an optional `boards` input. No other exported declarations changed. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com> Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com> |