mirror of
https://github.com/mastra-ai/mastra.git
synced 2026-11-17 08:44:46 +00:00
14,225 commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
d929736435 |
fix(core): use one stream bus for durable agents (#30229)
Durable agents now use the wrapped Agent's stream bus instead of
constructing a second one. An Agent-level pubsub carries both run frames
and thread events, including after registration and forks; evented
execution still uses Mastra's shared transport. Standalone durable
agents remain observable, and plain-run records and abort checks stay
separate from durable execution.
Previously, observing across replicas required repeating the pubsub on
the durable wrapper. This now works with the Agent configuration alone:
```ts
const agent = createDurableAgent({
agent: new Agent({ id: 'assistant', name: 'Assistant', instructions, model, pubsub }),
});
```
Inngest explicitly exposes its detached-streaming capability without
migrating its bus. The server retains the `isDurableAgentLike` fallback
in `hasResumableStreams` for compatibility with older Inngest wrappers:
their proxy can inherit `false` from a plain Agent or lack the method
entirely. Server and Inngest versions are not coupled, so removing the
fallback would silently turn HTTP disconnects into run cancellation on
supported mixed-version installs. This is a deliberate, user-approved
exception to the ticket's shortcut-removal bullet; no peer-dependency
bump is needed while the fallback remains. Regression coverage exercises
capability `true`, `false`, and missing; the latter two fail without the
fallback.
Server branch audit (`packages/server/src/server/handlers/agents.ts`):
`validateDurableToolCallAccess` (line 298) remains because approvals
need durable workflow snapshots; `authorizeRunAccess` (2676) remains
because durable ownership uses workflow rows/local and replay owners
rather than plain run records (COR-1542). The two abort-route branches
(2724 and 2742) retain durable cancellation support and its
missing/finished-run acknowledgement semantics, not separate transports.
The observe-route branch (3141) remains for generation-fenced
`__subscribeToRunStream` and the Inngest adapter's `pubsub` fallback;
consolidating observation is COR-1541, and migrating Inngest's bus is
COR-1539. The recover-route guard (3746) remains because only durable
execution has recoverable workflow snapshots. None of these remaining
branches requires a second stream bus on core DurableAgent.
The Mastra-fallback regression also runs through a fork created after
registration, both with and without resolving the bus before
registration. Another replica must receive replay plus live tail through
finish, and the terminal frame must be published on Mastra's transport.
The latest targeted rerun passed 33 tests, including cache-policy
warnings and plain-publisher isolation across both durable storage
variants; core typecheck, targeted lint, formatting and diff checks
passed.
Verified with 1,643 core durable/stream tests, 78 AIMock parity tests,
292 server handler tests (including the mixed-version capability cases),
119 Inngest tests, and six real Redis cross-server cases covering live
observation, thread events and HTTP Stop. Typechecks, lint and
formatting pass. The Agent-pubsub regression failed before the fix; a
built-package red/green demo also confirms the transport change. An
earlier approval-resume timing failure passed in isolation and on the
final full rerun.
Fixes COR-1540
## Transport precedence and upgrade scope
Default-engine durable run transport precedence is now: explicit
`createDurableAgent` pubsub → wrapped Agent pubsub → Mastra pubsub.
Evented runs retain Mastra's shared transport. Mastra-only
configurations are unchanged.
If the wrapped Agent already specifies a different transport from Mastra
and the wrapper has no override, this fix changes the effective
run-frame and remote Stop transport. To preserve routing across an
upgrade, explicitly pass the previous transport to `createDurableAgent`
or align the Agent and Mastra transports. The wrapper configures the
shared stream bus, so its override also affects resumable streams from
direct calls on the wrapped Agent. The core changeset includes this
upgrade note.
A local investigation used separately built pre-change main
(`
|
||
|
|
da04116579 |
feat(factory): let a person's reply wake a card's session while automated runs hold every slot (#30307)
## What
When a trusted collaborator comments on or reviews a card's GitHub pull
request or issue, Factory wakes the card's session even while automated
runs hold every run slot. Before, those replies were
`sendMessage`/`signalActivity` decisions that counted against the single
automated cap (`dispatcher.maxInFlight`, default 10), so a reply could
sit behind multi-hour triage runs.
## How
- **Provenance.** GitHub rule actors gain `human: true` when the webhook
`sender.type` is `User`. Bots, and Factory's synthetic reconciler events
(no `sender.type`), get `human: false`.
- **Classification** (`isInteractiveDecision`, `rules/dispatcher.ts`): a
decision is a reply only if it's `sendMessage` or `signalActivity`,
would wake the session (`idleBehavior` isn't `persist`), has an empty
causal chain (no rule passed it along, e.g. not a transition's message),
and its actor is a GitHub human who is trusted and not Factory.
Everything else stays automated. GitLab, Linear, Jira and incident.io
activity stays automated because those sources give no reliable
bot/human signal.
- **Lane.** Each process keeps a reserve of reply slots
(`dispatcher.maxInteractiveInFlight` /
`MASTRACODE_DISPATCH_MAX_INTERACTIVE_IN_FLIGHT`, default `2`, `0`
allowed). Claim order per tick: pending manual starts → replies (reserve
first, then borrowing free automated slots) → automated runs. The claim
filter now receives the row's `actor` and `causalChain` as well as the
decision payload, so no schema change.
- **Honest bounds.** The caps limit dispatcher slot occupancy, not total
running agents: `signalActivity` frees its slot once the session accepts
it, and UI/Slack messages plus approval notices to following sessions go
to the session directly and never wait for a slot. The README says so.
- **Run-queue API (additive).** Entries gain `lane`; the response gains
`queuedByLane`, and `slots` gains `interactive: { inUse, cap }`.
Existing fields keep their meaning. `position` now counts within a lane.
The board's queue menu lists waiting replies first, with a reply-slot
footer.
## Testing
- Dispatcher (LibSQL + throwaway Postgres): with automated cap 1 held by
a hanging run, a trusted person's PR reply (`sendMessage`) and issue
comment (`signalActivity`) are claimed and delivered. Automated runs,
bot replies, untrusted replies, Factory-authored replies, actors with no
`human` flag, rule-passed messages and `persist` activity all stay
pending. Other cases: the reserve caps at its size, replies borrow a
free automated slot ahead of automated runs, and the default reserve is
2. Red proof: disabling the classification fails 3 of the 4 lane tests.
- GitHub rules: `issue_comment` and `pull_request_review` from a User →
`human: true`; from a Bot or without `sender.type` → `human: false`.
- Approval notice to a following session commits nothing to the run
queue.
- MSW: queue menu groups replies apart from automated runs and shows
both slot footers.
- Gates: factory `check`, oxlint and oxfmt clean. Factory suites on
LibSQL: 942 passed. factory-ui typecheck and lint clean; unit tests 696
passed. The full MSW suite has 21 failures, the same as on main
(AppStartup, OMSection, MemorySettings, NewSessionStarters,
ThreadPageTeammateSession, TranscriptMessageMeta). `mastracode/web`
index.test.ts has 2 failures that are also on main. Postgres runs of the
full dispatcher suite at `--maxWorkers=3` show the timing flakes main
already has; every test that failed passes on its own.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
**ELI5:** When a trusted person replies to a GitHub issue or pull
request, that reply gets its own reserved run slots. It no longer waits
behind routine automated runs.
## Overview
This change adds an interactive lane to the Factory decision dispatcher.
Trusted GitHub human replies can wake a card's session while automated
runs hold the automated slots. The run-queue API changes are additive.
## Classification
`isInteractiveDecision` in `mastracode/factory/src/rules/dispatcher.ts`
marks a decision as interactive only when all of these hold:
- The decision is `sendMessage` or `signalActivity`.
- The decision wakes the session.
- The causal chain is empty.
- The decision does not persist.
- The actor is a trusted GitHub human.
- The actor is not Factory-authored.
All other decisions use the automated lane. This includes bot actors,
untrusted actors, Factory events, and activity from GitLab, Linear,
Jira, and incident.io.
## GitHub actor changes
- `mastracode/factory/src/rules/types.ts` adds optional `human?:
boolean` to the GitHub variant of `FactoryRuleActor`.
- `mastracode/factory/src/integrations/github/rules.ts` sets `human` to
`true` only when the webhook sender type is exactly `User`.
- Trust lookup and its failure handling are unchanged. A lookup error
still marks the actor untrusted.
## Dispatcher behavior
- The default interactive reserve is 2 slots per process.
- `dispatcher.maxInteractiveInFlight` in
`mastracode/factory/src/factory.ts` and
`MASTRACODE_DISPATCH_MAX_INTERACTIVE_IN_FLIGHT` in
`mastracode/web/src/mastra/index.ts` set the reserve.
- A value of `0` disables the reserve. Invalid values use the default of
2.
- Each tick claims in this order: pending manual starts, then
interactive decisions, then automated deferred runs.
- Interactive decisions can use free automated slots.
- `runSlots()` returns overall `inUse` and `cap`, plus `interactive: {
inUse, cap }`.
- The caps limit dispatcher-held slots. They do not limit all running
agents.
- Pull-request activity releases its slot when the session accepts it.
- Direct session messages and approval notices do not wait for a slot.
## Storage
- `FactoryDeferredDecisionClaimInput.decisionFilter` receives a second
argument, `provenance`.
- The new `FactoryDecisionProvenance` type contains `actor` and
`causalChain`.
- No schema change is made. Invalid stored actor JSON parses to `null`.
Invalid causal-chain JSON parses to an empty array.
## Run-queue API (additive)
- `runQueueResponseSchema` in
`mastracode/factory/src/routes/contracts.ts` adds:
- `slots.interactive: { inUse, cap }`
- `queuedByLane: { automated, interactive }`
- Each queue entry has a `lane` field with the value `automated` or
`interactive`.
- `position` counts within a lane.
- The listing limit of 50 entries is unchanged. Waiting replies are
listed before automated runs.
- The `runSlots` types in `routes/surface.ts` and `routes/work-items.ts`
include the interactive pool.
## Board UI
- `RunQueueIndicator.tsx` lists waiting replies before automated runs.
- Each nonempty group has a label.
- The menu shows reply-slot usage next to overall slot usage.
- The tooltip fallback reads "Runs waiting for a run slot."
- `msw-server.ts` and `BoardPageRunQueue.msw.test.tsx` add lane fixtures
and a test for a waiting reply.
## Documentation and release notes
- `mastracode/factory/README.md`,
`docs/src/mastra-code/configuration.mdx`, and two changesets describe
the reserve, its default, the `0` behavior, the queue fields, and the
board ordering.
- The `mastra` changeset is a patch. The `@mastra/factory` changeset is
a minor release.
## Tests
Added or updated tests cover:
- GitHub actor `human` classification for issue comments and PR reviews,
for `User`, `Bot`, and missing sender types.
- Dispatcher reserve use, interactive cap overflow, borrowing of free
automated slots, and exclusions. Exclusions include automated, bot,
untrusted, Factory-authored, untyped, causally moved, and persisted
messages.
- The default interactive cap of 2.
- The polling-loop claim count, which changes from two to three per
tick.
- Factory config forwarding in
`mastracode/web/src/mastra/index.test.ts`, which now expects
`maxInteractiveInFlight: 0` when the environment variable is `0`.
- Clearing `MASTRACODE_DISPATCH_MAX_INTERACTIVE_IN_FLIGHT` in
sandbox-provider tests.
- No deferred decisions recorded after approval-notification delivery,
in `approval-answer-resume.test.ts`.
## Validation (author-reported)
The PR objectives report the following results. They were not checked
against completed CI checks on the current head.
- Dispatcher tests were run on LibSQL and throwaway Postgres. Full
Postgres dispatcher runs at `--maxWorkers=3` showed timing flakes. The
author reports that each failing test passes when run alone.
- Factory suites on LibSQL report 942 passing tests.
- Factory `check`, oxlint, and oxfmt are reported clean.
- factory-ui unit tests report 696 passing tests.
- The author reports 21 full MSW suite failures and 2 `mastracode/web`
`index.test.ts` failures. The author states these also occur on `main`.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
|
||
|
|
7517474b39 |
fix(studio): load Gateway v2 models and skip v1 memory calls (#29445)
## Why Studio currently shows Gateway models from a bundled registry and sends memory requests to the Gateway v1 API whenever a Gateway key exists. A deployed project using Gateway v2 can therefore offer unsupported models and receive 404s from the v1-only memory endpoints. ## Design When the deployment sets `MASTRA_GATEWAY_VERSION=v2`, fetch the authenticated `/v1/models` catalog from the configured Gateway and offer only models with a chat endpoint through Mastra's chat model selector. If catalog loading fails, do not fall back to the v1 model list. Treat the Gateway memory client as unavailable in v2 mode so memory handlers use the agent's own memory configuration. V1 behavior remains unchanged. The Platform runtime signal is introduced by [platform#4329](https://github.com/mastra-ai/platform/pull/4329); deploying that PR alone will not change Studio until these Mastra packages are released and the project is redeployed. ## Validation - Focused core Gateway tests: 9 passed, including live model filtering and catalog failure behavior. - Focused server Gateway memory test: 1 passed. - `git diff --check` passed. - A live deployed Studio smoke test is still needed after the updated packages are published and deployed. Full package typechecks were unavailable in the isolated worktree because its linked local dependency builds are older than this checkout. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 When Gateway v2 is on, Studio lists only the chat models from the live Gateway catalog. It also stops calling the Gateway v1 memory API. A resolved agent without memory now shows no memory data, not shared-storage data. ## Changes - In v2 mode, `MastraGateway.fetchProviders()` requests `/v1/models` with authentication and a 10-second timeout. It keeps only models that have a string `id` and a `chat` endpoint. - If the catalog request fails or returns an invalid response, the call throws. It does not fall back to the v1 model list. - The provider list skips the bundled `mastra` registry entry in v2 mode. This prevents stale model IDs from appearing. - Other Gateway versions keep the OpenRouter model list. - In v2 mode, `getGatewayClient()` returns `null`. Memory handlers then use the agent's own memory configuration. - For a resolved v2 Gateway agent without memory: - Thread listing returns "Memory is not initialized". - Message listing returns empty `messages` and `uiMessages` arrays. - Unresolved agents keep the storage fallback. - v2 detection uses `isGatewayV2()`. It returns true when any of these conditions holds: - `MASTRA_GATEWAY_VERSION` is `v2`. - The API key starts with `msk-gateway-` or `mskv2_`. - A registered `mastra` gateway instance reports `isV2()` as true. `MastraGateway.isV2()` is a new public method. This check covers gateways configured with a v2 key and no matching environment variables. - Added patch changesets for `@mastra/core` and `@mastra/server`. ## Testing and rollout - Completed CI results are not available for this review. - The author reports that focused core Gateway tests, a focused server memory test, and `git diff --check` passed. These results were not verified here. - Full package typechecks were not run in the author's isolated worktree. - A deployed Studio smoke test is still needed. It requires the updated Mastra packages to be published and the project to be redeployed. - The Platform runtime signal depends on platform#4329. Deploying that change alone does not affect Studio. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Taofeeq Oluder <oluderutaofeeq@gmail.com> Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
92f3c5ba4f |
fix(cli): keep the key id of a Gateway v2 key from create-mastra (#30457) | ||
|
|
88f94f237a |
chore(deps): use the latest @ai-sdk/provider-utils and @ai-sdk/provider patch in each major (#30518)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
a5859ee2b9 |
chore: version packages (alpha) (#30430)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
cd2a326988 |
fix(libsql): stop background task writes stalling shutdown, and fix backend timing flakes (#30504)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
b739dd45db |
test(playground): stop jsdom teardown leaks from failing whole test shards (#30502)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
4809a81ba5 |
test(ui): fix main-red autosave test and flaky UI Retry/theme tests (#30500)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
8759d3ab63 |
test: keep real network calls out of unit test projects (#30498)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
88b4a97042 |
refactor(factory): skip legacy migration tables on new databases (#30488)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
6c647e6fae |
refactor(factory): stop creating columns and tables nothing reads (#30495)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
e8ef0c928f |
fix(factory-ui): tidy sidebar actions, the locked model picker and branch copying (#30471)
**─────── TLDR ───────**
> Five small fixes to controls in Factory's sidebar, composer and
session panel.
Four of them had their own styling instead of reusing the control beside
them. They reuse it now, and the two components that only existed for
the locked model control are gone. The fifth lets a card's description
show more before you expand it.
### Behavior changed
Hovering a board row in the sidebar
├─ **was** — the configure link was a ghost icon button with
its own hover reveal
└─ **now** — the same row action as every other sidebar row
The sidebar command header
├─ **was** — its buttons stopped 6px short of the nav rows'
right edge
└─ **now** — flush with the rows' right edge
Steering a teammate's session, the composer's model control
├─ **was** — a separate model + thinking button pair, styled
unlike the picker
└─ **now** — the usual picker trigger, disabled; hover says
who can change it
Copying a session's branch in the workspace panel
├─ **was** — a separate copy icon button after the branch
name
└─ **now** — click the branch icon or name; a copy icon
shows on hover
A card's description in the session panel overview
├─ **was** — clipped at 72px, with Show more on its own row
below
└─ **now** — clipped at 100px, Show more floats centered
over the fade
### Decisions
- **copy icon keeps a reserved slot at the end of the name** —
overlaying it would hide the end of a truncated branch; one class away
- **no tooltip on the branch button** — the hover icon and the toast
already say it copies; a truncated name is no longer readable on hover
- **`unavailableReason` is a minor bump** — new optional prop, same name
and role as `ThinkingLevelPicker`'s
### Shape changed
| | | |
|---|---|---|
| **−** | `LockedModelButton` | the locked state is now the shared
picker, disabled |
| **−** | `ModelThinkingGroup` | the thinking level now lives in the
disabled trigger's accessible name |
| **~** | `Button` rendered as a link | drops `type`, the configure link
was rendering `<a type="button">` |
new on `@mastra/playground-ui`
`ModelPicker` `unavailableReason?: string`
One test in `ThreadPageTeammateSession` ("says a teammate when the owner
has no profile") fails locally on `main` too when the whole file runs,
and passes alone. `EmptyThreadState` shows the owner's `userId` as the
resource ID. I left it out of this PR.
### Not verified
- [ ] the five changes in a running browser; the layout is from reading
the classes
---
> ██████████████████ **source** `+160 −105` — net +55, two components
deleted
> ███ **changeset** `+21`
> █ **tests** `+12 −5`
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
**ELI5:** This change fixes several small Factory UI details. Sidebar
buttons line up with their rows, a locked model shows a disabled picker
with a reason tooltip, and a session branch copies when clicked. Session
descriptions also show more text before they are clipped.
## Overview
The change updates 15 files. It adds 193 lines and removes 110. It
changes two packages:
- `@mastra/playground-ui`: adds the `unavailableReason` prop to
`ModelPicker`, changes `Button` link rendering, and adjusts sidebar
command-header padding.
- `mastracode/factory-ui`: removes two session model-status components
and updates the board, workspace, session-description, and model-status
UI.
## Changes
### Playground UI package
- **`ModelPicker`
(`packages/playground-ui/src/domains/llm/model-picker.tsx`):** Adds
optional `unavailableReason?: string` to `ModelPickerProps`. When set,
the trigger renders disabled and shows the reason in a tooltip.
Otherwise, the popover or drawer picker renders as before.
- **`Button`
(`packages/playground-ui/src/ds/components/Button/Button.tsx`):** When a
button renders as a link, the cloned element sets `type` to `undefined`.
Link-rendered buttons no longer put `type` on the anchor. This allows
`Sidebar.NavAction` links to render a valid `<a>`.
- **`SidebarCommandHeader`
(`packages/playground-ui/src/ds/components/Sidebar/header/sidebar-command-header.tsx`):**
Uses `pr-0.5` instead of `pr-2` when the sidebar is not collapsed. The
collapsed padding stays `px-3`.
- **Changesets:** A minor changeset documents `unavailableReason`. A
patch changeset documents the `Sidebar.CommandHeader` alignment and the
`Button` link fix.
### Factory UI: model status
- **Removed:** `LockedModelButton.tsx` and `ModelThinkingGroup.tsx`.
- **`ModelPicker.tsx`:** `ModelMenuProps` accepts `unavailableReason?:
string`, and `ModelMenu` passes it to the shared picker. A new
`LockedModelMenu` renders the session owner's credential and the shared
model menu. Its trigger is disabled and shows the locked reason. Its
accessible label includes the thinking summary. When a session has a
locked model and a selected model ID, `ModelPicker` uses this menu. The
regular menu reuses the shared trigger content.
- **`SessionThinkingSettings.tsx` and `useSessionThinking.ts`:**
`useSessionThinking` returns a `summary` string. The summary is
`loading` or `unavailable` for those states. Otherwise, it is the label
that matches the effective level, or the level value if no label
matches. `SessionThinkingSettings` uses this summary in the group's
accessible label.
### Factory UI: board and sessions
- **`FactorySection.tsx`:** Board configuration actions use
`Sidebar.NavAction` instead of `Button`. The hover and focus group
selectors are updated. `FactoryLink` no longer adds the `group/board`
class when an action is present.
- **`CardDescription.tsx`:** Raises the collapsed height cap from 4.5rem
to 6.25rem. The description container is centered. The collapsed mask
starts at 50% instead of 30%. The "Show more" / "Show less" button
changes from `ghost` to `default` styling. While collapsed, the button
sits over the bottom center of the description. When expanded, that
positioning is removed.
### Factory UI: workspace branch
- **`WorkspaceSection.tsx`:** Replaces `CopyButton` with a local
`BranchCopyButton`. Clicking the branch icon or name copies the branch
name. The button shows a checkmark after copying. The copy icon appears
on hover or keyboard focus. The loading and unavailable states are
unchanged.
## Tests
- **`WorkspaceFiles.msw.test.tsx`:** The focus assertion in "opens the
overview immediately" now expects the `Copy branch factory/issue-1`
button instead of `Copy branch name`.
- **`ThreadPageTeammateSession.msw.test.tsx`:** The disabled model
button's accessible name now includes the thinking level. The test
checks that the session owner's OpenAI credential is shown. It keeps the
locked-reason tooltip check and asserts that clicking the model button
does not open a dialog. It no longer asserts that the thinking-level
control is disabled.
## Known issues and limits
- The author reports that the test "says a teammate when the owner has
no profile" fails when the full `ThreadPageTeammateSession` file runs on
`main`. It passes when run alone. This PR does not address that failure.
- The author did not verify the five UI changes in a running browser.
- CI and test results: not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
|
||
|
|
9b9240047b |
feat(factory-ui): add a stage bar, dock the session panel, and find any workspace file (#30388)
**─────── TLDR ───────**
> Card session pages now show the card's stage in the header and its
links, changes and files in a panel docked beside the conversation.
Before, a review session listed its pull requests twice, and each
surface judged a pull request's status its own way. Now each fact has
one home, and the panel gives way before the conversation does.
### Behavior changed
a card session's header
├─ **was** — a breadcrumb: board, card, then the session's
context
└─ **now** — a stage bar: arrows move the card, or say why
they can't
the session panel as the window narrows
├─ **was** — under the header, the conversation squeezed
beside it
└─ **now** — beside the header; narrows, then folds in step
with the sidebar
Go to file in a session
├─ **was** — no search: a file was reached by opening its
folders one by one
└─ **now** — typing a name finds any workspace file,
multi-repo roots included, changed first
a pull request's status icon on the board, in the sidebar and the panel
├─ **was** — each surface read the state its own way
└─ **now** — one rule: merged sticks, a close holds until
the card reopens
a pull request closed, then reopened
├─ **was** — on GitHub every card holding it stayed closed;
on GitLab, its own card
└─ **now** — every card that holds it reads open again
### Shape changed
| | | |
|---|---|---|
| **−** | `WorkspaceOverview`, `WorkspaceFilesSurface` | replaced by
`WorkspaceSection` and the docked card |
| **−** | `FactoryReviewPullRequestLinks`, `PullRequestLinks` | the
links live in the panel overview |
| **−** | `GlobalSearchButton` | search lives in the sidebar |
| **−** | `useWorkspacePullRequestStatuses` | its 5-second poll goes;
`useSessionPullRequestSubscriptions` reads on the feed |
| **~** | `usePullRequestSubscriptions` | split into
`useThreadSubscriptions` and `useRefreshThreadSubscriptions` |
new surface the panel relies on
`GET /web/workspace/files?workspacePath=`
returns `{ workspacePath, available, paths, truncated }` · `updatedAt`
on GitHub and GitLab subscriptions · `CodeDiff` paints on the card
surface, Studio included · the dock is an `aside` landmark named Session
panel
### Decisions
- **no breadcrumb** — the sidebar, panel and stage bar each name one
part; one component to restore it
- **search only in the sidebar, phones included** — the header button
duplicated it; Cmd/Ctrl+K still opens it
- **the client still picks between card and subscription state** —
either can lag today; I move that to the server next
### Tradeoff
The sidebar stops asking for each visible session's pull request status
every 5 seconds. The board's live feed now triggers that read, and a
re-read every 60 seconds is the floor. For ten visible sessions with an
open pull request and nothing happening, that is about 10 reads a minute
where main made 120 (computed from the intervals, not measured). A busy
board refreshes at most every 5 seconds, so it never reads more often
than main's poll, and like that poll it re-reads only a pull request
whose subscription is open. The price: a status that changes without a
card write can show up to 60 seconds late, against 5 on main. With the
stream down, it reads every 5 seconds as before.
### Not verified
- [ ] the panel folding and unfolding in Safari and Firefox — checked in
Chromium only
- [ ] the file index on busybox sandboxes — its script relies on `grep
-z` and `xargs -0`
- [ ] a pull request reopened on a real GitHub or GitLab repository —
the reopen sync ran against test storage only
- [ ] the file index refusing a symlinked checkout on a Linux sandbox —
it ran on a macOS host only, and a single-repository workdir that is
itself a symlink is not checked
- [ ] the `mastra-studio-preview` build on Vercel — it fails generating
`@mastra/connect` provider docs (`oxfmt-mdx` not found), in files this
PR does not touch
- [ ] `CodeDiff` in Studio's memory observations — it shares the
component, and I only looked at it in Factory
- [ ] a sidebar toggle that leaves the conversation within 10px of the
dock threshold — the fold starts about 70ms after the sidebar there
---
> ██████████████████ **ui source** `+3583 −1446`
> █████████████ **ui tests** `+2586 −611` — with e2e and server tests,
49% of the additions
> ████ **e2e** `+777 −2` — a 556-line heavy-session fixture
> ██ **server tests** `+401 −22`
> ██ **server source** `+352 −16` — the file index route and the reopen
sync on GitHub and GitLab
> █ **changesets** `+46`
> █ **design system** `+4` — `CodeDiff` on the card surface
---------
Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local>
Co-authored-by: Damien Schneider <damienschneider@mac.lan>
|
||
|
|
a1c11c5b11 |
chore(deps): update better-auth monorepo to v1.7.22 (#30464)
This PR contains the following updates: | Package | Type | Update | Change | Pending | |---|---|---|---|---| | [@better-auth/drizzle-adapter@<1.7.7](https://www.better-auth.com/docs/adapters/drizzle) ([source](https://redirect.github.com/better-auth/better-auth/tree/HEAD/packages/drizzle-adapter)) | pnpm-workspace.overrides | patch | [`1.7.18` → `1.7.22`](https://renovatebot.com/diffs/npm/@better-auth%2fdrizzle-adapter/1.7.18/1.7.22) | `1.7.25` (+2) | | [better-auth](https://better-auth.com) ([source](https://redirect.github.com/better-auth/better-auth/tree/HEAD/packages/better-auth)) | pnpm-workspace.overrides | patch | [`^1.7.18` → `^1.7.22`](https://renovatebot.com/diffs/npm/better-auth/1.7.18/1.7.22) | `1.7.25` (+2) | | [better-auth](https://better-auth.com) ([source](https://redirect.github.com/better-auth/better-auth/tree/HEAD/packages/better-auth)) | dependencies | patch | [`^1.7.18` → `^1.7.22`](https://renovatebot.com/diffs/npm/better-auth/1.7.18/1.7.22) | `1.7.25` (+2) | --- > [!WARNING] > Some dependencies could not be looked up. Check the [Dependency Dashboard](../issues/9505) for more information. --- ### Release Notes <details> <summary>better-auth/better-auth (@​better-auth/drizzle-adapter@<1.7.7)</summary> ### [`v1.7.22`](https://redirect.github.com/better-auth/better-auth/blob/HEAD/packages/drizzle-adapter/CHANGELOG.md#1722) [Compare Source](https://redirect.github.com/better-auth/better-auth/compare/v1.7.21...v1.7.22) ##### Patch Changes - [#​12333](https://redirect.github.com/better-auth/better-auth/pull/12333) [`6536174`]( |
||
|
|
12f79652cf |
feat(playground-ui): pick every remaining interface icon from Central Icons (#30438) | ||
|
|
adc0a70bf8 |
fix(memory, couchbase): check semantic recall scope in Memory and warn on ignored Couchbase filters (#30446) | ||
|
|
d1d736db29 |
test(memory): pin attachment token counts in the #29851 image test (#30415) | ||
|
|
c8a35ac624 |
fix(memory): keep Observational Memory local when the gateway has no memory API (#30414)
> Opened by @abhiaiyer91 > Opened by @factory-project:7d5175c3-3a20-42ac-aba9-756f183136f4 ## Summary Keep Observational Memory local for agents using `mastra/<provider>/<model>` with gateway organization keys (`msk-gateway-*` and `mskv2_*`), because those keys do not provide gateway-managed memory. Gateway project keys (`msk_*`) continue to use gateway-managed memory. Finish an open local turn before switching to gateway-managed memory. Credential ownership checks report local memory only for models that are not on the Mastra gateway. A credential the gateway cannot resolve — including one it reports as missing — is thrown instead of read as local ownership: guessing local ownership can cause both the gateway and local store to persist the same thread, because the model call resolves the same credential again. The Observational Memory processor also propagates ownership-check errors. Older models that cannot report gateway memory ownership retain their previous behavior. Docs explain the gateway-key distinction and the paired `@mastra/core` and `@mastra/memory` upgrade. Project keys routed BYOK or with gateway memory disabled remain outside this change's scope. ## Verification (head ` |
||
|
|
cac6299ae0 |
feat(playground-ui): reveal the mobile sidebar from under the page (#30440)
**─────── TLDR ───────** > On phones, the page now slides aside to reveal the sidebar underneath it. `takeover`, the default mobile mode of `Sidebar`, was a drawer covering the page. Now the `AppShell` content is the layer that moves, and the sidebar stays fixed below it, scaling up from 95% as it shows. It all lives in playground-ui, so Studio and Factory get it through `AppShell` with no change on their side. ### Behavior changed Opening navigation on a phone ├─ **was** — a drawer slid over the page, with a floating close button └─ **now** — the page slides right and the sidebar shows underneath Swiping the page ├─ **was** — only the open drawer could be swiped shut └─ **now** — right opens, left closes, the page tracks the finger both ways Letting go mid-swipe └─ **new** — finishes the way you last moved; under 40px it springs back Navigation open ├─ **new** — a tinted, framed strip of page: tap it, swipe it, or press <kbd>Esc</kbd> └─ **new** — <kbd>Tab</kbd> and <kbd>Shift</kbd>+<kbd>Tab</kbd> cycle inside the sidebar; the page and toasts are out of reach until it closes Resizing the sidebar on desktop └─ **unchanged** — same widths; the live value is now set on the panel ### Decisions - **drag progress in non-inherited properties on the three moving layers** — a scope variable restyled the whole page per touchmove, 2.16ms against 0.21ms - **live `--sidebar-width` on the panel, not the scope** — same restyle cost per desktop resize frame; every reader in this repo sits inside the panel - **past 40px, release follows the last direction moved, not "past halfway or a fast flick"** — halfway sent a slow close bouncing back open; one line in `release` to revert - **the open reveal makes everything outside itself inert, not `AppShell` its own content** — also covers toasts and portals mounted outside `AppShell`, and removing the sidebar while it's open can't leave the page stuck inert ### Watch > [!WARNING] > The gesture only moves elements marked as reveal layers, and only `AppShell` marks the page. <mark>A `takeover` sidebar outside `AppShell` has no page to slide</mark>: wrap it in `AppShell` or pass `mobileMode="drawer"`, like the agent builder does. The changeset spells this out. ### Not verified - [ ] real iOS Safari and Android Chrome, including iOS's edge back-swipe against swipe-to-open: checked only in Chromium and WebKit with synthetic touches, and in DevTools touch emulation - [ ] the platform app: not in this repo, so I couldn't check it renders the sidebar inside `AppShell` - [ ] one emulator run right after page load lost `touchend` and left the page mid-drag; two reruns didn't reproduce it --- > ███████████████████ **source** `+493 −42` — half of it the gesture hook > ████████████ **tests** `+322 −7` > █ **changeset** `+21` > █ **stories** `+10 −2` <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> **ELI5:** On a phone, the menu now slides out from under the page, like pulling a drawer out from behind a curtain. You swipe or tap to open it, and you swipe, tap, or press Escape to close it. ## Summary This PR changes the default mobile and tablet `takeover` sidebar in `@mastra/playground-ui`. The `AppShell` page content slides aside to reveal the sidebar underneath. The reveal uses a scale and fade effect. - Swipe right opens the sidebar. Swipe left closes it. - On release, movement beyond 40px follows the last gesture direction. Shorter movements spring back to the starting state. - When open, a strip of the page stays visible. Tapping or swiping the strip closes the sidebar. Escape also closes it. - While open, focus stays in the sidebar. Tab and Shift+Tab cycle between the sidebar's first control and its close strip. The page and toasts are set to `inert` until the sidebar closes. - Desktop sidebar widths do not change. The live `--sidebar-width` value is set on the sidebar panel. - A `takeover` sidebar outside `AppShell` has no page to slide. Wrap the page in `AppShell`, or set `mobileMode="drawer"` on the sidebar. ## Changes by file - **`.changeset/rich-bats-hide.md`**: Adds a minor release note for `@mastra/playground-ui`. It describes the page-sliding and swipe behavior, focus handling, gesture exclusions, reduced-motion behavior, and the `AppShell` requirement. - **`sidebar-reveal.tsx`** (new): Adds the `SidebarReveal` component. It applies reveal styling, connects gestures to drawer state, and makes the panel a modal dialog while open. It focuses the panel on open and handles Escape. On cleanup, it removes inert marks and restores focus to the mobile trigger if focus was lost. While closed, the drawer is inert and hidden from accessibility APIs. A scrim click closes the drawer. - **`use-reveal-gesture.ts`** (new): Adds `useRevealGesture` and the exported `REVEAL_EASE` constant. The hook tracks one touch. It claims horizontal movement after an 8px threshold. It ignores gestures owned by a nested horizontal swipe. Release duration is velocity-matched and clamped to 120–400ms. Cancelled touches use zero velocity. Cleanup removes listeners and temporary CSS variables. - **`sidebar-reveal.css`** (new): Defines non-inherited custom properties for drag, duration, progress, and motion. Progress rests at 0 when closed and at 1 when open. The settle duration is 320ms closed and 400ms open. Reduced-motion preferences set layer motion to 0ms. The panel scales and fades, and the scrim translates and fades. When a mobile sidebar is present, the page is clipped, styled, and translated. - **`sidebar-panel.tsx`**: Renders mobile takeover mode through `SidebarReveal`. The mobile drawer always uses drawer mode, fixed drawer sizing, and `px-3` padding. The takeover-specific close button and conditional takeover styling are removed. The desktop panel applies its computed width through `SidebarPanelStyle` and attaches `panelRef`. - **`sidebar-provider.tsx`**: Adds a panel ref and exposes it through context. Writes the live `--sidebar-width` value to the panel, not the scope. Adds `data-sidebar-mobile-open`, set to `'true'` or `'false'` by drawer state. - **`sidebar-context.ts`**: Adds `scopeRef` and `panelRef` to `SidebarContextValue`. - **`sidebar-mobile-trigger.tsx`**: Removes the selector that hid the trigger when `data-sidebar-mobile-present="true"`. The selector for `data-sidebar-mobile="false"` remains. - **`app-shell.tsx`**: Adds `data-sidebar-reveal-layer="page"` to the content wrapper. Slot and layout classes are unchanged. - **`app-shell.css`**: Sets `overflow-x: clip` when a mobile sidebar is present and reveal state is active. - **`app-shell.stories.tsx`**: Adds a Storybook description of the mobile interactions to the `Mobile` story. - **`sidebar-layout.stories.tsx`**: Sets `mobileMode="drawer"` on the `Mobile` story's sidebar. - **`sidebar-reveal.test.tsx`** (new, 313 lines added): Tests opening by a rightward drag past halfway or by a fast flick. Tests that short or reversed drags stay closed. Tests that vertical scrolls and drags in horizontal scrollers do not open the sidebar. Tests closing by leftward swipe or Escape. Tests that Escape in a nested menu closes only that menu. Tests focus restoration, focus cycling, and inert behavior for the page and an outside toast. Tests that removing the sidebar while open leaves the page usable. - **`sidebar-root.test.tsx`**: Adds an `Element.prototype.getAnimations` fallback when the method is missing. The `widthOf` helper reads `--sidebar-width` from the panel. The mobile close test queries the button named "Close navigation menu". ## Public API changes - Added: `SidebarReveal` component. - Added: `useRevealGesture` hook and `REVEAL_EASE` constant. - Changed: `SidebarContextValue` gains `scopeRef` and `panelRef`. - Behavior change: The default mobile `takeover` sidebar slides the page. The previous takeover rendering is removed. ## Testing and verification - The author reports synthetic touch tests in Chromium and WebKit, and DevTools touch emulation. - Real iOS Safari and Android Chrome were not verified. iOS edge back-swipe behavior was not verified. - The platform app was not checked. - One emulator run lost `touchend` after page load and left the page mid-drag. Two reruns did not reproduce it. - CI results for this head: not available. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Damien Schneider <damienschneider@mac.lan> |
||
|
|
a48d697b35 |
feat(e2b): run commands as another OS user, and choose the owner of S3/GCS mounts (#30433)
> Opened by @factory-project:7d5175c3-3a20-42ac-aba9-756f183136f4
## Description
E2B sandboxes ran every agent command as the template's default OS user,
and S3/GCS FUSE mounts were always owned by that same user. That user
has to be privileged — mounting FUSE filesystems needs `sudo`, and the
staged s3fs credentials file (`/tmp/.passwd-s3fs-*`, mode 600) is only
readable by it — so an agent running shell commands as that user could
read bucket credentials or become root.
Two opt-in options fix that:
- **`E2BSandbox({ user })`** — every command the sandbox runs on the
agent's behalf runs as that OS user: `executeCommand`, background
processes, and the tree-kill script that takes their descendants down
(another user cannot signal them). Mounting still runs as the default
user, because it needs `sudo`.
- **`S3Filesystem({ owner })` / `GCSFilesystem({ owner })`** — `{ uid,
gid }` naming the owner of the files inside the FUSE mount, replacing
the `id -u && id -g` probe. This is what gives the command user read and
write access to the mount.
Both are additive and default to today's behavior. `owner` lives on the
filesystem options rather than the sandbox because the mount config is
produced by `filesystem.getMountConfig()`, which is what E2B's `mount()`
reads; `E2BSandboxOptions.user` reaches the provider through the shared
`CommandsApiProcessManager`, and the key is left off entirely when unset
so the SDK's own default user still applies. `owner` is validated as
non-negative integers before it is interpolated into a mount command.
The `user` must already exist in the sandbox template.
## Related issue(s)
Fixes #30349
## 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)
- [x] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] 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)
- [ ] I have addressed all Coderabbit comments on this PR
## Test plan
All checks run on this head (`dec4e6ec`):
- `packages/_internals/workspace`: 160 tests, including a new test that
the spawn and the kill script both carry the configured user, and one
that the key stays unset without a user.
- `@mastra/e2b` unit suite: 367 passed, 9 skipped (`validateOwner`
cases; S3 and GCS mounts using an explicit owner skip the `id -u && id
-g` probe and emit `uid=`/`gid=` and `--uid=`/`--gid=`; mounts without
an owner still probe).
- `@mastra/s3` 150 passed, `@mastra/gcs` 91 passed, including
`getMountConfig()` carrying `owner` when set and omitting it when not.
- Typecheck (e2b, s3, gcs, platform-workspace) clean; lint 0 warnings /
0 errors and builds clean for e2b, s3 and gcs.
- Each new test fails against the base source without the change (10 in
e2b, 1 internal, 1 s3, 1 gcs).
- Integration coverage: `index.integration.test.ts` gained a case
asserting an explicit owner yields `1234:1234` from `stat -c %u:%g`. It
needs `E2B_API_KEY`, so it does not run in CI — a manual run on a real
sandbox is the remaining gap.
## Follow-ups (not part of this change)
1. File-API writes (`sandbox.files`, `FilesApiFilesystem`) and code-mode
staging under `/home/user` still run as the default user, so with `user`
set, files written through file tools are not owned by the command user.
2. `E2BProviderConfig.configSchema` does not list `user` (it already
omits `workingDirectory`, `reattach` and `lifecycle`), so the Studio
provider form does not offer it even though the runtime forwards it.
3. `commands.list()` scope relative to the configured user is unverified
without an API key; tracked handles still surface.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
**ELI5:** Agent commands in an E2B sandbox used to run as the same user
that mounts cloud storage. This PR lets you pick a separate,
less-privileged user for agent commands, and lets you set the file owner
for S3 and GCS mounts. Both options are off by default.
## Summary
This PR adds two opt-in E2B options, as described in issue `#30349`:
- **Command user.** `E2BSandbox({ user })` runs agent commands,
background processes, and descendant cleanup as the named OS user.
Mounting still uses the default user. The user must already exist in the
sandbox template.
- **Mount owner.** `S3Filesystem({ owner })` and `GCSFilesystem({ owner
})` accept `{ uid, gid }`. When set, the mount uses these IDs. When
unset, the existing `id -u && id -g` probe runs.
### Changes by area
- **Workspace process manager**
(`packages/_internals/workspace/src/commands-api-process-manager.ts`):
`CommandsApi.run` and `CommandsApiProcessManagerOptions` accept an
optional `user`. Spawned commands and descendant cleanup in `kill()` use
it.
- **E2B provider** (`workspaces/e2b/src/sandbox/`):
- `index.ts` adds `user?: string` to `E2BSandboxOptions`.
- `process-manager.ts` forwards `user` to the base class.
- `mounts/types.ts` adds `MountOwner` and `validateOwner`. Validation
requires non-negative integers for `uid` and `gid`.
- `mounts/s3.ts` and `mounts/gcs.ts` use a supplied owner. Otherwise,
they probe the default user.
- `index.ts` re-exports `MountOwner`.
- **S3 and GCS filesystems** (`workspaces/s3/src/filesystem/index.ts`,
`workspaces/gcs/src/filesystem/index.ts`): add `MountOwner`, an optional
`owner` option, and a `readonly owner` property. `getMountConfig()`
copies `uid` and `gid` into a plain object only when an owner is set.
This copy also handles owners whose fields are prototype getters. Both
packages re-export `MountOwner`.
- **Docs and changeset:** document both options. The changeset sets
minor releases for `@mastra/e2b`, `@mastra/s3`, and `@mastra/gcs`.
### Tests
- Workspace tests check that a configured user reaches spawned commands
and their kill commands. They also check that an unset user is passed as
`undefined`.
- E2B unit tests check owner validation and mount behavior with and
without an owner.
- S3 and GCS tests check `getMountConfig()` with and without an owner.
They also check that later changes to the input owner do not change the
config.
- An E2B integration test checks that an explicit owner of `1234` mounts
with ownership `1234:1234`. This test requires `E2B_API_KEY` and was not
run in CI.
The author reports passing workspace, E2B, S3, and GCS tests. The author
also reports clean typecheck, lint, and build results. These results are
not tied to a completed CI run on the current head. A manual run against
a real E2B sandbox is outstanding.
### Out of scope (per PR description)
- File-API writes and code-mode staging still use the default user.
- The Studio configuration schema does not expose `user`.
- The scope of `commands.list()` relative to the configured user is not
verified.
<!-- 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>
|
||
|
|
82c98f9f1c |
fix(rag): keep long JSON string content when chunking JSON documents (#30407)
> Opened by @factory-project:7d5175c3-3a20-42ac-aba9-756f183136f4
JSON chunking (`MDocument.chunk({ strategy: 'json' })`) silently
discarded most of a long string value whenever the field's serialized
path was longer than 13 characters, or the value contained characters
that JSON escapes. The splitter budgeted a fixed 20-character overhead
regardless of the real field name, and then dropped every piece that
still exceeded `maxSize`. The result was silent data loss with no error,
no warning, and no config that avoided it — a 3000-character value under
a 16-character key kept 120 characters at `maxSize` 500, and a
14-character key at `maxSize` 21 produced zero chunks.
The fix sizes each piece from the value it is about to emit: it measures
the serialized envelope of the candidate piece and its full field path,
cuts only at code-point boundaries so astral characters are never split,
and never discards a completed piece. When a field path alone leaves no
room for a single character, the remainder is emitted as one oversized
chunk instead of being dropped.
**Result:** Approved — `
|
||
|
|
0170d700a4 |
feat(mcp): let MCPServer set maxRequestBodySize for HTTP requests (#30411)
> Opened by @factory-project:7d5175c3-3a20-42ac-aba9-756f183136f4
## Description
Every MCP HTTP request served by a Mastra `MCPServer` was capped at the
MCP SDK's fixed 4 MiB default. A client sending a larger `tools/call`
body received
```json
{"jsonrpc":"2.0","error":{"code":-32000,"message":"Payload Too Large: Request body must not exceed 4194304 bytes"},"id":null}
```
before the tool ever ran, with no way to raise the bound. That breaks
legitimate payloads — for example a Claude connector MCP App intake form
that submits a signed PDF and a photo of an ID in a single `tools/call`.
`MCPServer` now accepts an optional `maxRequestBodySize` (bytes) in its
config, next to `legacy`:
```typescript
const server = new MCPServer({
name: 'intake',
version: '1.0.0',
maxRequestBodySize: 16 * 1024 * 1024,
tools: { submitIntake },
});
```
The option is forwarded to both SDK layers that enforce the cap:
`createMcpHandler(...)` owns the handler's bound, and
`toNodeHandler(...)` owns an adapter-level bound —
`@modelcontextprotocol/node` buffers the Node request stream itself
before the handler sees it, and per its
`ToNodeHandlerOptions.maxRequestBodySize` docs "the adapter's bound
applies first". Passing it to only one layer leaves the other's 4 MiB
default in force.
Leaving the option unset keeps the SDK default of `4194304` (4 MiB), so
existing servers behave exactly as before, and an over-limit body is
still rejected with the same `413` before it is parsed. The option
applies to `startHTTP` only; `stdio` has no request bodies. Documented
in the `MCPServer` configuration table of
`docs/src/content/en/reference/tools/mcp-server.mdx`.
## Test plan
New `packages/mcp/src/server/server-http-body-size.test.ts` drives the
real `startHTTP` path through the shared harness:
- default server rejects a 5 MiB body with `413`, `-32000`, and the
default byte count in the message, without running the tool;
- `maxRequestBodySize: 8 MiB` accepts a 5 MiB body and the tool runs;
- `maxRequestBodySize: 1024` rejects a 2 KiB body with `413` naming the
configured limit;
- a body under the configured limit is accepted.
## Verification
| Category | Command | Result |
| --- | --- | --- |
| Package tests | `pnpm exec vitest run --project unit:packages/mcp
src/server` | ✅ 36 files, 669 passed, 8 skipped |
| Package tests | `pnpm exec vitest run --project unit:packages/mcp
src/client` | ✅ 34 files, 627 passed |
| Type check / build | `pnpm --filter @mastra/mcp build:lib` | ✅ Passed;
emits `maxRequestBodySize?: number` in `dist/server/server.d.ts` |
| Lint | `npx oxlint --type-aware <changed .ts>` | ✅ 0 warnings, 0
errors |
| Format | `npx oxfmt --check <changed .ts>` | ✅ Passed |
| New tests on base code | new tests against the pre-change `server.ts`
| ✅ 2 of 4 fail on base (`expected 413, received 200`), 4 of 4 pass on
head |
| Docs checks | `run-checks.sh --docs
docs/src/content/en/reference/tools/mcp-server.mdx` | ✅ format, remark,
validate pass |
| Public surface | scratch script importing the built `@mastra/mcp` | ✅
default → `413`, raised limit passes the size gate |
| Not run | Vale prose check | ⚠️ binary not installed, so prose was not
linted |
One full-suite run failed on `server-events.test.ts` (stdio events). The
same test also fails at the base commit under the same full-suite load
and passes on re-run and in isolation, so it is a pre-existing flake
rather than a regression; this change does not touch the `serveStdio`
path.
## Follow-ups (non-blocking)
- A non-positive or non-finite `maxRequestBodySize` is not validated at
construction; the SDK's `RangeError` surfaces on the first HTTP request
as a `500`. Constructor-time validation would fail faster.
- The built-in `/api/mcp` endpoint (`server.mcp` / `ServerMCPConfig`)
and adapter-level `MCPOptions` still expose no body-size option; this
change deliberately scopes to a user-instantiated `MCPServer`.
Fixes #30207
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
ELI5: MCP servers reject requests bigger than 4 MB. This PR lets a
developer set a bigger limit for one server, so large uploads can reach
the tool.
## Summary
This PR adds an optional `maxRequestBodySize` setting to
`MCPServerConfig`. `MCPServer` stores the value and passes it to both
`createMcpHandler(...)` and `toNodeHandler(...)`. When the setting is
unset, the SDK default of 4 MiB (4194304 bytes) applies.
## Changes
- `packages/mcp/src/server/server.ts`: Adds `maxRequestBodySize?:
number` to `MCPServerConfig`. Adds a private readonly field and assigns
it from config. Passes the value to both HTTP handler layers. Adds 12
lines.
- `packages/mcp/src/server/server-http-body-size.test.ts`: Adds 109
lines and 4 test cases:
- A body over the default 4 MiB limit returns `413`, and the tool does
not run.
- A body larger than 4 MiB succeeds when `maxRequestBodySize` raises the
limit.
- A body over a lowered limit returns `413`, and the message includes
the configured limit.
- A body under the configured limit succeeds.
- `docs/src/content/en/reference/tools/mcp-server.mdx`: Documents the
option in the configuration table. Adds 7 lines.
- `.changeset/olive-pandas-carry.md`: Adds a minor release note for
`@mastra/mcp`. Adds 20 lines.
## Behavior
- The limit is in bytes.
- The documentation states that the value must be positive. The diff
does not validate this. The code stores any value it receives.
- An oversized body receives a `413` JSON-RPC error before it is parsed.
No tool runs.
- The limit applies only to bodies the server reads from the request
stream. When body-parsing middleware supplies the parsed body, the limit
does not apply. The documentation tells the user to set the limit on
that parser too.
- The setting does not apply to `stdio`.
## Scope
- The PR does not add constructor-time validation for non-positive or
non-finite values.
- The PR does not add body-size options to the built-in `/api/mcp`
endpoint or to adapter-level `MCPOptions`.
## Diff
4 files changed, 148 lines added, 0 removed.
## Verification
The PR author reports these results. This review did not run them.
- `vitest run --project unit:packages/mcp src/server`: 36 files, 669
passed, 8 skipped.
- `vitest run --project unit:packages/mcp src/client`: 34 files, 627
passed.
- `pnpm --filter @mastra/mcp build:lib`: passed.
- Vale prose check: not run. The binary was unavailable.
- One full-suite failure in `server-events.test.ts`. The author reports
the same failure on the base commit under full-suite load. The author
reports that it passes on rerun and in isolation.
## Linked issue
Issue `#30207` requests a per-server `maxRequestBodySize` on
`MCPServer`, passed to `createMcpHandler`. The PR adds the constructor
option and forwards it to both handler layers. The diff and test names
cover the requested behavior: the default is kept when unset, a `413` is
returned above the limit, and the setting applies per server.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
|
||
|
|
1072f7c626 |
fix(memory): reuse message embeddings across saves (#30429)
## Summary Saving messages with semantic recall embeds each message's text and writes a vector row for it. Since the message write path moved onto the shared row builder, Memory stopped reusing embeddings for text it had already embedded. The same text saved again (a repeated reply, a re-saved message, a cloned thread) went back to the embedder every time: three saves of the same 50 texts made 150 embedding calls instead of 50. This restores bounded reuse on the write path without changing how rows are written: - Vectors are cached per Memory instance in a bounded LRU, keyed by each message's exact prepared chunks, so chunk-size limits still apply and a different chunking is a miss. - The cache is emptied when the embedder or its options change. - Failed calls, and responses without exactly one embedding per chunk, are never kept. Concurrent writes of the same chunks share one call. - Reused vectors are not counted again in reported embedding usage. - Only vectors are cached. Every message still gets its own row with its own id and metadata, so there are no duplicate recall rows. The memory performance benchmark previously timed recalls without checking that anything had been indexed, so a writer that skipped embedding would pass it. It now checks that every message has a vector row and that each thread's semantic recall returns its own messages before timing. ## Test plan - New `semantic-recall-embedding-reuse.test.ts` (10 tests): repeated text, re-saved ids, usage on reuse, long-text reuse, invalid responses and changed embedder options fail before this change. Edited text, failed embeds, embedder swaps and raw-string content are covered as controls. - `@mastra/memory` unit suite: 2,689 pass + 1 todo. Typecheck, lint and format clean. - Real file-backed LibSQL, 3 saves × 50 messages: repeated text 150 → 50 embedding calls, re-saved ids 150 → 50. Stored rows unchanged (151 / 51 / 451 for long chunked text). Unique, raw-string and long-text call counts unchanged. - LibSQL performance benchmark (2,500 messages, FastEmbed) passes with the new check. The check fails when vector writes are disabled or recall returns nothing. - Local FastEmbed: repeated text ~7.6s → ~2.6s; unique text unchanged. Ref #29826 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ELI5: When a message is saved, Memory turns its text into numbers (an embedding). If the same text was already turned into numbers, this change reuses them instead of asking the embedding service again. Each message still gets its own stored row. ## Overview This change adds a bounded cache of message-chunk embeddings to `Memory`. The cache applies only to the message-vector write path. The change also adds checks to the LibSQL performance test, a patch changeset for `@mastra/memory`, and a new test file. Diff scope: 4 files changed, 350 lines added, 11 removed. ## Changes **`packages/memory/src/index.ts`** (+55 / -11) - Adds `chunkEmbeddingCache`, an LRU cache bounded by `DEFAULT_EMBEDDING_CACHE_MAX_SIZE`. It holds promises of vectors only. Keys are a hash of `JSON.stringify(chunks)`. - Adds `chunkEmbeddingCacheOwner`. It records the embedder and options that produced the cached vectors. - Adds `embedMessageChunks(chunks)`, which: - Snapshots `this.embedder` and `this.embedderOptions` before hashing. - Calls `embedValues` with the snapshot and skips the cache if the embedder or options change during hashing. - Clears the cache when the owner record differs from the snapshot. The clear happens at the next miss, not when the embedder changes. - Returns cached vectors on a hit. A hit returns no usage data. - On a miss, calls `embedValues` and stores the pending promise. Concurrent writes with the same chunks share that promise. - Evicts the entry when the call fails or returns a number of embeddings that differs from the number of chunks. - Returns usage only for the call that reached the embedder. - Changes `embedValues` to accept an optional `{ embedder, embedderOptions }` argument. The default is `this`, so other callers keep the current behavior. - Changes the message-vector row builder to call `embedMessageChunks` instead of `embedValues`. The diff for this file shows no change to the query or content embedding paths. **`packages/memory/src/semantic-recall-embedding-reuse.test.ts`** (+267) - Adds a new test file. It covers reuse across saves, one row per message on resave, re-embedding of edited or distinct text, usage counting, non-reuse of failed or mis-sized results, invalidation on embedder or option change, an embedder change during an in-flight save, raw-string content, and chunking within the embedder input limit. - The number of tests in this file is not verified from the diff. The PR reports 10. **`packages/memory/integration-tests/src/performance-testing/performance-tests.ts`** (+23) - Imports the `MastraVector` type. - Before timing, checks that indexed vector rows are at least `threadCount * messagesPerThread`. - Before timing, runs a thread-scoped semantic recall for each thread. Checks that results are nonempty and belong to that thread. - The timed query measurements and p95 threshold are not changed. **`.changeset/quiet-owls-reuse.md`** (+5) - Adds a patch changeset for `@mastra/memory`. It describes reuse of vectors for repeated or re-saved text and the exclusion of reused vectors from reported usage. ## Reported results These results come from the PR description. They are not verified by completed checks on the current head. - Three saves of 50 messages with repeated text: embedding calls fell from 150 to 50. Stored row counts are reported unchanged. - Repeated-text FastEmbed time: about 7.6 s before, 2.6 s after. - Unique, raw-string, and long-text call counts: reported unchanged. - `@mastra/memory` unit tests: 2,689 passing, 1 todo. - Typecheck, lint, and format: reported clean. - LibSQL benchmark with 2,500 messages: reported passing. ## Not verified - Test, typecheck, lint, format, and benchmark results. No completed check on the current head was available. - The test count in the new test file. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com> |
||
|
|
1100a41fb7 |
feat(playground-ui): switch interface icons to Central Icons (#29934) | ||
|
|
33eaa293e2 |
fix(core): give unnamed sleeps the same step id in every process (#30397)
## Description
A `.sleep()` or `.sleepUntil()` declared without an `id` now gets the
same step ID in every process: `sleep_<workflowId>_<n>`, where `n`
starts at the number of sleeps declared before this one and moves up
past any ID already in use.
### Why
Each process generated a random ID for an unnamed sleep when it built
the workflow, and that ID is the key of the sleep's result in the stored
run. A process that restarts or time travels a run stored by another
process looked the sleep up under its own ID, found nothing, and the
step after the sleep got no input. On the evented engine a restart
failed the run with an input validation error (the step received
`undefined`). Time travel on either engine ran the step with `{}`.
Scheduled workflows were affected too: the schedule's definition hash
covers the serialized step graph, which includes the sleep IDs, so every
instance computed a different hash and the instances that hadn't
registered the schedule last refused to fire it.
### What changed
`packages/core/src/workflows/workflow.ts` uses the rule unnamed `.map()`
steps have used since #21222: a deterministic ID from the workflow ID
and an ordinal, unless the workflow is already registered with a Mastra
instance that has a custom ID generator when the sleep is declared, in
which case that generator still produces the part after `sleep_`.
`sleep` and `sleepUntil` share one count, since both use the `sleep_`
prefix. An ID already taken by an explicit one is skipped. An explicit
`id` is unchanged.
```ts
// before: sleep_3f2c9e1a-... (different in every process)
// after: sleep_my-workflow_0
createWorkflow({ id: 'my-workflow', ... }).then(a).sleep(5000).then(b).commit();
```
The `sleep` and `sleepUntil` reference pages now describe the default
ID.
### Known limits
- Adding or removing a sleep shifts the default IDs of later unnamed
sleeps. Pass `{ id }` to pin one.
- Runs stored before the upgrade keep their random sleep IDs and still
won't match after a restart or time travel, as before.
- A custom ID generator that returns random IDs still gives a different
ID per process.
### Tests
- New `packages/core/src/workflows/sleep-id-determinism.test.ts`: two
builds of the same workflow give the same IDs with one ordinal over
`sleep` and `sleepUntil` (without the fix: random `sleep_<uuid>` IDs);
an explicit ID that claims a default name is skipped (without the fix: a
random ID); a default-engine time travel past a sleep after the workflow
is rebuilt, on `InMemoryStore`, hands the next step its recorded input
(without the fix: the run ends `failed` with "Step input validation
failed", because the step got `{}`).
- `packages/core/src/workflows/evented/sleep-restart.test.ts`: the sleep
and `sleepUntil` restart cases now build the workflow once per runtime,
as a real restart does, and assert the step after the sleep receives its
input (without the fix: the run ends `failed` with
`WORKFLOW_STEP_INPUT_VALIDATION_FAILED`, input `undefined`).
## Related issue(s)
None
## 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
- [ ] 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)
- [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:** When a workflow waits, it gives that wait a name. Before this
change, the name was random each time the code ran. Another process
could not find the saved wait, so a restarted or time-traveled run lost
its data. Now each unnamed wait gets a name based on its position in the
workflow, so every process uses the same name.
## Summary
Unnamed `.sleep()` and `.sleepUntil()` steps now get a deterministic ID.
The ID has the form `sleep_<workflowId>_<n>`. Both sleep types share one
counter. The counter skips IDs that already exist in the workflow's
steps. Explicit `{ id }` values are unchanged.
## Changes
- **`packages/core/src/workflows/workflow.ts`:** Adds a private
`#defaultSleepId(stepType)` helper. `sleep()` and `sleepUntil()` call it
when no explicit ID is given.
- With no custom ID generator on the Mastra instance, `n` equals the
number of earlier `sleep` and `sleepUntil` entries in `stepFlow`. The
helper increments `n` while `sleep_<workflowId>_<n>` already exists in
`steps`.
- With a custom ID generator, the helper calls `generateId` with the
workflow ID and the step type. It then prefixes the result with
`sleep_`. The generator supplies the suffix.
- The `crypto.randomUUID()` fallback is removed from both methods.
- **`.changeset/curly-pillows-argue.md`:** Adds a `@mastra/core` patch
changeset. It describes the fix and states these limits:
- Runs stored before this change keep their random IDs. They do not
match after a restart or time travel.
- Scheduled workflows with unnamed sleeps get the same definition hash
on each instance.
- Adding or removing a sleep changes the IDs of later unnamed sleeps.
Pass `{ id }` to keep an ID fixed.
## Documentation and tests
- The raw summary reports that the `sleep` and `sleepUntil` reference
pages describe the ID format, the counter, and the custom ID generator
behavior.
- The raw summary reports a new
`packages/core/src/workflows/sleep-id-determinism.test.ts`. It covers
stable IDs, the shared counter, explicit-ID collisions, and a
rebuild-and-time-travel case.
- The raw summary reports that `sleep-restart.test.ts` now creates a
separate workflow object for each runtime. It asserts that the
`afterSleep` step receives `{ value: 'persist me' }`.
- Verification status: the doc pages and test files were not inspected.
Test results are not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
|
||
|
|
15dc07c51d |
chore: version packages (alpha) (#30394)
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/core@1.84.0-alpha.2 ### Minor Changes - Added run metadata to background process callbacks. ([#30161](https://github.com/mastra-ai/mastra/pull/30161)) `backgroundProcesses` callbacks on `execute_command` now receive, when available, the `agentId`, `threadId`, `resourceId`, and `runId` of the call that started the process, so hosts can route exit notices to the right conversation. `onExit` also receives `killedByAbort`, which is `true` when the abort signal fired (the run's signal by default) and killed the process. ```ts backgroundProcesses: { onExit: ({ pid, exitCode, threadId, killedByAbort }) => { if (!killedByAbort) notifyThread(threadId, `Process ${pid} exited with code ${exitCode}`); }, }, ``` `truncateOutput` and `DEFAULT_TAIL_LINES` are now exported from `@mastra/core/workspace`, so hosts can trim process output the same way `execute_command` does. ### Patch Changes - Fixed retries in `dountil` and `dowhile` loops on the evented engine. Each iteration of a loop body now starts at `retryCount` 0 and gets the step's full `retries`, as on the default engine. Before, the count carried over from earlier iterations, so a body that failed once in a later iteration could run out of retries and fail the run. ([#30383](https://github.com/mastra-ai/mastra/pull/30383)) If your step code reads `retryCount` inside a loop body, it now gets the attempt within the current iteration. The loop condition receives the iteration number as `iterationCount`. To use it inside the body, pass it through the step's output or workflow state. - Fixed durable agent runs failing with `DURABLE_AGENT_EXECUTION_UNVERIFIED` when an ownership check took longer than the lease TTL (15 seconds by default) while the same process still held the run. These runs used to fail and lose their saved snapshots. They now keep running, and a step stops only when an ownership check fails, the claim can't be renewed before it expires, or another execution takes over the run. ([#30386](https://github.com/mastra-ai/mastra/pull/30386)) - Fixed workflow recovery restarting a run that is still executing, which ran its steps twice. `startAsync()` now takes the run's lease before it saves the first snapshot, so it resolves after the lease is taken and rejects if taking it fails. Runs of workflows whose `shouldPersistSnapshot` saves `waiting` but not `running` now hold a lease too, so recovery no longer restarts them while they execute or sleep. ([#30384](https://github.com/mastra-ai/mastra/pull/30384)) - `processToolResult` now sees and can rewrite a tool's `toModelOutput` result. Previously, when a tool mapped its result with `toModelOutput` (for example a file viewer returning images), output processors only saw and changed the raw result, and the mapped output, images included, still reached the next model call and stored history unchanged. ([#30401](https://github.com/mastra-ai/mastra/pull/30401)) The hook now receives `modelOutput`. To replace it, commit a `result`-state part that carries the new value in `providerMetadata.mastra.modelOutput`: ```ts processToolResult({ messageList, toolCallId, toolName, args, result, modelOutput }) { messageList.updateToolInvocation({ type: 'tool-invocation', toolInvocation: { state: 'result', toolCallId, toolName, args, result }, providerMetadata: { mastra: { modelOutput: shrinkImages(modelOutput) } }, }); } ``` A processor that replaces only `result`, or edits it in place, now has the new value mapped through `toModelOutput` again, so the model reads the mapping of the processed result rather than of the original. With several processors, each one receives the `modelOutput` the processor before it committed, so a later processor can't bring back an image an earlier one removed. This applies to both regular and durable agents. In durable agents, a `processToolResult` that throws now also keeps the unprocessed mapped output from the model, not only the raw result. ## @mastra/client-js@1.60.1-alpha.2 ### Patch Changes - Updated dependencies [[`7277766`]( |
||
|
|
9eae9680d2 |
fix(memory): serialize tool results half as often in long Observational Memory runs (#30400) | ||
|
|
5b7f130224 |
test(core): cover a child scope added to an existing Knowledge scope's declaration (#29925)
## Description Adds a test for the condition that sends a held Knowledge scope back to the store when its declaration lists a child scope that doesn't exist yet. Since #29775, a write run skips the store call for a held scope that already exists, whose parent hasn't changed, whose declaration has no template pages, and whose declared child scopes all exist (`#materialize` in `packages/core/src/knowledge/scope-runtime.ts`). Existing tests in `write-start-scopes.test.ts` fail when the parent or template-page condition is replaced with `true`. Replacing the child-scope condition with `true` leaves all 9 passing, so nothing in that file would catch a write run that stops creating a child scope added to an existing scope's declaration. The new test materializes `team:t1` with no children and checks that `team:t1/internal` doesn't exist. It then runs a write start with `children: [{ name: 'internal' }]` and checks that `team:t1/internal` now exists under `team:t1`. ## Testing - `pnpm --filter @mastra/core exec vitest run src/knowledge/__tests__/write-start-scopes.test.ts`: 10 passed (9 existing, 1 new). - With the child-scope condition replaced by `true`, the new test fails (`expected undefined to be defined`) and the other 9 pass. - `oxlint` and `prettier --check` are clean on the file. ### Postgres check of #29775 I also ran #29775 against Postgres 16 (`pgvector/pgvector:0.8.4-pg16`). That script imports the scope runtime from core source, so it isn't part of this PR. - Compared with the per-scope loop from before #29775, each in its own schema, the batched start produced the same scope trees (parent, declaration, name, description, template pages), warnings and errors. The start sequences covered a conflicting held parent, an unplaced scope getting linked once its parent is held, ambiguous parents, template-child principals, `belongsTo` cycles, and 2,301 held scopes. A template page deleted outside Knowledge was recreated the same way by both. - On the batched start only: a child scope added to an existing scope's declaration was created, and a `belongsTo` added to an existing scope's declaration set its parent. - 8 concurrent cold batched starts over the same 201 scopes all succeeded. All 201 scopes existed afterwards, every project was under the org, and no address appeared on more than one scope row. - `materializeScope` calls for 2,301 held scopes: a first write went from 4,601 (the old loop materialized the shared parent again for each project) to 2,301 plus one batched lookup, and a repeat write from 2,301 to 0. In one local run on Docker for macOS, the repeat write took 11 ms against 7.0 s before. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 This PR adds a test for a team that already exists when its declaration gains a child scope. The test checks that the next materialization creates the new child. ## Changes - Added a test in `packages/core/src/knowledge/__tests__/write-start-scopes.test.ts`. - The test first materializes `team:t1` without children and confirms `team:t1/internal` is absent. - It then materializes `team:t1` with `children: [{ name: 'internal' }]` and checks that the child scope exists. ## Checks - Test, lint, and formatting results: not available. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Jamie Lee Nichols <10267569+CodingButter@users.noreply.github.com> Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
2f4a9ed771 |
feat(connect): share the headless connect helpers (#30336)
## Summary
Studio and the platform dashboard both connect integrations headlessly:
they render their own credential form and drive the Nango frontend SDK
instead of sending users to Nango's hosted Connect UI. Each had its own
copy of the helpers, and the copies drifted. This makes
`@mastra/playground-ui/domains/connect` the single implementation, and
the dashboard will import it (follow-up platform PR).
**Shared, richer field model**
- `headlessAuthFields` now returns a fully resolved `HeadlessAuthField`
(label, description, default value, format, pattern, options,
prefix/suffix, docs URL, warnings, `visibleWhen`, secret, required,
order). The wire type `UserConnectAuthField` gains these as optional
props, and sparse data (e.g. older servers) gets defaults.
- New `isHeadlessAuthFieldVisible`. `splitHeadlessAuthValues` skips
fields hidden by `visibleWhen`.
**More providers connect headlessly**
- `OAUTH2_CC`: built-in Client ID / Client secret fields. The SDK
submits them to Nango's `/oauth2/auth` with no popup.
- `NONE`: calls `nango.create()` (`/auth/unauthenticated`) instead of
`nango.auth()`, which would have opened an OAuth popup.
- Built-in credential fields (API key, Basic, client credentials) are
now appended when the catalog lists only connection params. Before, a
Basic provider with just a `subdomain` field got a form with no username
or password.
Still on the hosted UI: `TBA`, `JWT`, `BILL`, `SIGNATURE`, `AWS_SIGV4`
(these need per-type SDK discriminators) and `INSTALL_PLUGIN` (the SDK
has no headless path).
## Test plan
- [x] New `domains/connect/__tests__/headless-connect.test.ts` (31
tests): supported auth types, field normalization, built-in field
merging, `visibleWhen` visibility and splitting, `NONE` → `create()`,
`OAUTH2_CC` → `auth()` with credentials
- [x] Existing connect and Studio connections tests pass
- [x] `playground-ui` and `playground` typecheck clean; oxlint clean
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## ELI5
This change moves the code that connects third-party apps into one
shared place. A future platform dashboard can reuse that code instead of
keeping its own copy.
## Overview
This PR makes `packages/playground-ui/src/domains/connect` the shared
implementation of headless connect helpers. Studio uses these helpers
now. The platform dashboard import is planned for a follow-up PR.
The change:
- Adds optional metadata to connect auth fields.
- Adds headless support for `NONE` and `OAUTH2_CC`.
- Adds built-in credential fields when the catalog lists only connection
parameters.
- Adds conditional field visibility through `visibleWhen`.
- Updates the Studio connect dialog to display and validate only visible
fields.
The PR description says these auth types stay on the hosted UI: `TBA`,
`JWT`, `BILL`, `SIGNATURE`, `AWS_SIGV4`, and `INSTALL_PLUGIN`.
## Changes by file
- `.changeset/headless-connect-client-credentials.md`: Adds a patch
changeset for `@mastra/playground-ui`. It describes:
- `OAUTH2_CC` requests a Client ID and Client secret in the connect
dialog.
- `NONE` connects without an OAuth popup.
- Built-in credential fields are added when the catalog lists only
connection parameters.
- Headless connect helpers are exported and support `visibleWhen`.
- `packages/playground-ui/src/domains/connect/types.ts` (+13): Adds
optional fields to `UserConnectAuthField`:
- `defaultValue`, `format`, `pattern`, `options`, `prefix`, `suffix`,
`documentationUrl`, `warnings`
- `visibleWhen?: { field: string; equals: string } | null`
- `packages/playground-ui/src/domains/connect/headless-connect.ts`
(+166/-70): Main logic changes.
- Adds `NONE` to headless support. It calls `nango.create()` instead of
`nango.auth()`.
- Adds built-in credential fields for API key, Basic, and `OAUTH2_CC`
flows. For `OAUTH2_CC`, these fields are Client ID and Client secret.
- Normalizes catalog fields into resolved `HeadlessAuthField` values.
- Appends built-in credentials only when catalog fields contain no
credentials.
- Keeps `TWO_STEP` supported only when catalog fields include
credentials.
- Applies `visibleWhen` to field visibility. `splitHeadlessAuthValues`
omits hidden fields.
- Moves the auth request options into a helper.
-
`packages/playground-ui/src/domains/connect/__tests__/headless-connect.test.ts`
(+219): Adds Vitest coverage for:
- Headless auth support classification
- Normalization of catalog fields and built-in credentials
- Separation of credentials and parameters
- `visibleWhen` filtering
- `startHeadlessAuth` calls for OAuth client credentials,
unauthenticated connections, and OAuth popup handling
-
`packages/playground/src/pages/connections/__tests__/fixtures/user-connect.ts`
(+27): Adds the exported `regionalProvidersResponse` fixture. It has one
API-key provider. The required `region` parameter comes before a
required `apiKey` credential. The `apiKey` credential is visible only
when `region` equals `eu`.
- `packages/playground/src/pages/connections/__tests__/index.test.tsx`
(+47): Adds a `ConnectionsPage` test that uses
`regionalProvidersResponse`. The API key is hidden and not required when
`region` is unset or `us`. When `region` is `eu`, the API key is shown,
and Connect stays disabled until a key is entered.
-
`packages/playground/src/pages/connections/components/add-connection-dialog.tsx`
(+3/-1): Imports `isHeadlessAuthFieldVisible`. The dialog displays only
visible fields. Required-field validation checks only the displayed
fields.
## API changes
- Added interface `HeadlessAuthField`.
- Added type `HeadlessAuthFieldFormat = 'hostname' | 'uri' | 'uuid' |
'email'`.
- Added interface `HeadlessAuthProvider { authType?: string | null;
authFields?: readonly UserConnectAuthField[] | null }`.
- Changed `headlessAuthFields` to accept `HeadlessAuthProvider` and
return `HeadlessAuthField[]`.
- Changed `headlessAuthRequiresForm` to accept `HeadlessAuthProvider`.
- Added `isHeadlessAuthFieldVisible(fields, field, values): boolean`.
- Changed `splitHeadlessAuthValues` to accept `readonly
UserConnectAuthField[]`.
## Verification
- Diff size: 7 files changed, 506 lines added, 71 lines removed.
- The PR description reports 31 tests in `headless-connect.test.ts`. It
also reports passing connect and Studio connection tests. These results
are not verified here.
- The PR description reports clean `playground-ui` and `playground`
typechecks and oxlint runs. These results are not verified here.
- CI results for the current head: not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
|
||
|
|
547600d004 |
fix(core): let processToolResult see and rewrite toModelOutput results (#30401)
## What Output processors can now see and rewrite what the model actually receives from a tool that uses `toModelOutput`. Before this change, `processToolResult` only received the tool's raw `result`. When a tool mapped that result with `toModelOutput` (for example a file viewer that returns screenshots as images), the mapping had already been computed, so a processor could change the raw result while the mapped output, images included, went to the next model call and into stored history unchanged. A processor that shrinks or removes oversized images had no way to reach them, and memory processors counted and observed the originals. ## How - `processToolResult` now receives `modelOutput`, the tool's mapped output. - A processor replaces it by committing a `result`-state part with the new value in `providerMetadata.mastra.modelOutput` (via `messageList.updateToolInvocation`). Setting it to `null` drops the mapping. - A processor that changes only the raw `result` gets it re-mapped through `toModelOutput`, so the model reads the mapping of the processed result. - Works on both regular and durable agents. In durable agents, a `processToolResult` that throws now also withholds the unprocessed mapped output from the model, not only the raw result. ## Tests `tool-result-model-output-processors.test.ts` (9 tests, regular and durable engines): replacing mapped images by tiling or with a note, re-mapping after a raw-result rewrite, leaving output alone when a processor doesn't touch it, and durable fail-closed behavior. All 9 fail on main and pass here. Related processor, agentic-execution and model-output suites pass; the durable suite's 8 lease/claim timing failures also occur on main. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> **ELI5:** Some tools give the AI model a special version of their output, such as an image. Before this change, a processor could change only the raw tool result. It could not see or change that special version. Now a processor can read it, replace it, or clear it. The model then gets the updated version. ## Overview This change lets `processToolResult` processors read and rewrite a tool's mapped `modelOutput`. The mapped output comes from the tool's `toModelOutput` mapping. The change applies to regular agents and durable agents. ## Behavior - A processor receives the current mapped output as `ProcessToolResultArgs.modelOutput`. - To replace the mapped output, a processor commits a `result`-state tool-invocation part. The part sets the new value in `providerMetadata.mastra.modelOutput`. - A processor sets `providerMetadata.mastra.modelOutput` to `null` to remove the mapping. - A processor changes only the raw `result`. The system runs `toModelOutput` again on the processed result. The new mapped output replaces the old one. - A processor makes no changes. The existing mapped output stays. - A durable agent processor throws. The unprocessed mapped output is not sent to the model. The fallback result is an error placeholder. - Each processor receives the mapped output committed by the preceding processor. If that processor cleared the mapping, the next processor receives no mapped output. ## Changes by area - **Core commit logic** (`loop/shared/steps/tool-result-commit-core.ts`, +130): Adds `readModelOutput` to read `mastra.modelOutput` from provider metadata. Adds `resolveModelOutputAfterToolResultProcessors` to reconcile processor output with the committed result. It remaps when the raw result changed. It detects in-place edits by comparing a content snapshot taken before processing. It also adds a reverse-search helper that finds the matching assistant tool-invocation part in `result` state. - **Agentic execution** (`loop/workflows/agentic-execution/llm-mapping-step.ts`, +95/−42): Passes `modelOutput` from the chunk's provider metadata into tool-result processing. Both successful-result paths use a shared helper. After processors run, the helper re-resolves the mapped output. It updates the chunk metadata only when the value changed. Tool lookup moves into `resolveMappingTool`. That function checks dynamically scoped step tools before static tools. - **Durable tool-call step** (`agent/durable/workflows/steps/tool-call.ts`, +47/−1): Passes the current mapped output to processors. On processor failure, it replaces the result with an error placeholder and removes the mapped output derived from the unprocessed result. On success, it resolves the mapped output again from the processed result. Mapping failures use the existing mapping-failure path. - **Processor types and schema** (`processors/index.ts`, `processors/step-schema.ts`): Adds optional `modelOutput?: unknown` to `ProcessToolResultArgs`, `ProcessorToolResultPhaseType`, and `ProcessorStepOutputType`. - **Processor runner and workflows** (`processors/runner.ts`, `workflows/workflow.ts`, `workflows/evented/workflow.ts`): `runProcessToolResult` accepts an optional `modelOutput`. Before each output processor runs, the runner reads the latest processed mapped output for the tool call. It uses the supplied value as the fallback. Workflow processors receive the value as `modelOutput`. Legacy processors receive it with the existing arguments. Both workflow implementations pass the value through chained processor steps. - **Tests** (`agent/__tests__/tool-result-model-output-processors.test.ts`, +335): Adds tests for these cases: - processors receive mapped output - a replacement reaches the next prompt, stored history, and streamed tool result - a raw-result change triggers remapping - unchanged output is preserved - processor ordering and clearing behave as specified - a durable agent excludes the original image after a processor throws - **Changeset** (`.changeset/tool-result-model-output-processors.md`, +19): Documents the new behavior. ## Public API - Added: `modelOutput?: unknown` on `ProcessToolResultArgs`, `ProcessorToolResultPhaseType`, and `ProcessorStepOutputType`. - Changed: `ProcessorRunner.runProcessToolResult` accepts an optional `modelOutput`. - Added in `tool-result-commit-core.ts`: `readModelOutput`, `hasToolResultProcessor`, `snapshotToolResult`, `latestProcessedModelOutput`, and `resolveModelOutputAfterToolResultProcessors`. ## Notes - The changeset says the unprocessed mapped output is "retained alongside the raw result" when a durable processor throws. The code and the PR objectives say the output is withheld. This summary follows the code. The changeset wording needs review. - The PR author reports that all 9 tests in `tool-result-model-output-processors.test.ts` fail on `main` and pass on the branch. The author also reports 8 lease/claim timing failures in the durable suite that also occur on `main`. These results come from the author. They were not checked against completed CI on the current head. ## Diff size 10 files changed, +663 / −43 lines. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com> |
||
|
|
951a18b085 |
feat(core): background process exit metadata (#30161)
Ignore the rest of the stack, just this one is open for review for now
because it will help me on workflow-chaos
---
## Description
`execute_command` runs a background process and returns its PID right
away, and `backgroundProcesses` callbacks let a host watch it. Until now
those callbacks only got the `pid` and `toolCallId`, so a host had no
way to tell which conversation started the process or why it stopped.
The callbacks now also get `agentId`, `threadId`, `resourceId` and
`runId` when they're available, and `onExit` gets `killedByAbort`, which
is `true` when the abort signal fired (the run's signal by default) and
killed the process. A host can send an exit notice to the right thread
and skip processes the abort killed:
```ts
const workspace = new Workspace({
sandbox,
tools: {
[WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND]: {
backgroundProcesses: {
onExit: ({ pid, exitCode, threadId, killedByAbort }) => {
if (!killedByAbort) notifyThread(threadId, `Process ${pid} exited with code ${exitCode}`);
},
},
},
},
})
```
`truncateOutput` and `DEFAULT_TAIL_LINES` are now exported from
`@mastra/core/workspace` so a host can trim the output in that notice
the same way `execute_command` does.
Tests run real `LocalSandbox` processes and cover an abort kill, a
normal exit, `kill_process`, an agent with no id, and a direct
`execute()` call that passes the ids at the top level.
## Related issue(s)
First PR of a stack for background shells. There's no tracking issue.
Next in the stack is #30176.
## 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)
- [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)
- [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:** Background commands can now tell their callbacks which agent,
chat thread, user resource, and run started them. The exit callback also
says whether the run's abort signal stopped the command. Other code can
now reuse the output-trimming helper.
## Summary
This change adds origin metadata to `backgroundProcesses` callbacks for
background `execute_command` processes. It adds an exit flag that shows
abort-signal termination. It also exports two workspace helpers for host
code.
## Changes by file
- `packages/core/src/workspace/tools/types.ts`: Adds optional `agentId`,
`threadId`, `resourceId`, and `runId` to `BackgroundProcessMeta`. Adds
optional `killedByAbort` to `BackgroundProcessExitMeta`.
- `packages/core/src/workspace/tools/execute-command.ts`: Passes
`agentId`, `threadId`, `resourceId`, and `runId` to stdout, stderr, and
exit callbacks. Empty or missing IDs become `undefined`. Thread and
resource IDs fall back from `context.agent` to the top-level context.
- `packages/core/src/workspace/index.ts`: Exports `truncateOutput` and
`DEFAULT_TAIL_LINES` from `./tools`.
- `packages/core/src/workspace/tools/__tests__/sandbox-tools.test.ts`:
Adds tests for callback metadata, including a context with no agent ID.
Adds tests that expect `killedByAbort: true` when the spawning run's
abort kills the process. Adds tests that expect `false` for normal exits
and for `kill_process`. The tests use a Node-based long-running command
for cross-platform runs.
- `.changeset/six-mugs-lead.md`: Declares a minor `@mastra/core` release
that describes the new metadata and exports.
- `docs/src/content/en/docs/sandbox/overview.mdx`: Documents that
lifecycle callbacks receive `pid` and, when available, `toolCallId`,
`agentId`, `threadId`, `resourceId`, and `runId`. Documents
`killedByAbort` on `onExit`.
- `docs/src/content/en/reference/workspace/workspace-class.mdx`:
Documents stdout and stderr metadata. Documents exit metadata, including
`killedByAbort`.
## Public API changes
- `BackgroundProcessMeta` gains optional `agentId`, `threadId`,
`resourceId`, and `runId`.
- `BackgroundProcessExitMeta` gains optional `killedByAbort`.
- `@mastra/core/workspace` exports `truncateOutput` and
`DEFAULT_TAIL_LINES`.
## Review and verification status
- Review comments: The author requested CodeRabbit reviews three times.
The bot responses report completed reviews and contain no review
findings. Review severity counts: not available.
- CI and test results on the current head: not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
|
||
|
|
7277766d6c |
fix(core): reset retryCount on each evented loop iteration (#30383)
## Description On the evented engine, each iteration of a `dountil`/`dowhile` loop whose body is a step now starts with `retryCount` 0 and gets the step's full `retries`, as on the default engine. ### Why The evented engine carried `retryCount` from one iteration into the next, so iteration N started at N-1 plus every retry earlier iterations had used. A body with `retries` ran out of budget on a later iteration: with `retries: 1`, a single failure in iteration 3 failed the run instead of being retried. Step code reading `retryCount` also saw that inflated number. The default engine has counted retries per iteration since #23593. ```ts const body = createStep({ id: 'body', retries: 1, execute: async ({ retryCount }) => { /* ... */ } }); workflow.dountil(body, async ({ iterationCount }) => iterationCount >= 4).commit(); // retryCount seen by the body when iteration 3 fails once // before: 0, 1, 2 and the run fails // after: 0, 0, 0, 1, 0 and the run succeeds ``` ### Behavior change - Step code that reads `retryCount` inside an evented loop body now gets the attempt within the current iteration. The iteration number is available to the loop condition as `iterationCount`. - The loop condition's `retryCount` is now the body's attempt in the current iteration on every path. One path used to pass attempt + 1. The default engine passes -1 to the condition; that difference is left as is. ### Not affected `foreach` loops, and loops whose body is a nested workflow (those already started each iteration at 0). ### Tests New case in the shared workflow suite (`workflows/_test-utils/src/domains/run-count.ts`): a `dountil` body with `retries: 1` that throws once in iteration 3. It runs on the default and evented engines and is skipped on Inngest with the other `retryCount` cases. Without the fix it fails on the evented engine with `expected [ 0, 1, 2 ] to deeply equal [ 0, 0, 0, 1, 0 ]`. ## Related issue(s) Linear PLTFRM-3202. No GitHub issue. ## 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 - [ ] 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: When a loop step fails and retries, the retry count from earlier loop passes was carried into later passes. This could use up the retry limit early. This change resets the count so each loop pass gets its full retry limit. ## Summary This pull request changes how the evented workflow engine tracks `retryCount` for `dountil` and `dowhile` loops whose body is a step. ## Changes - `packages/core/src/workflows/evented/workflow-event-processor/loop.ts`: When a loop iteration runs again, `processWorkflowLoop` passes `retryCount: 0` instead of the current retry count. Each iteration starts with the body's full retry budget. - `packages/core/src/workflows/evented/workflow-event-processor/index.ts`: In `runLeafStep`, the loop-condition path passes `retryCount` to `#processLoop` without adding 1. - `.changeset/bright-terms-crash.md`: Adds a patch changeset for `@mastra/core`. It documents that `dountil` and `dowhile` body retries start at 0 on each iteration. It also states that `retryCount` is scoped to the current iteration. - `workflows/_test-utils/src/domains/run-count.ts`: Adds `createRunCountWorkflows` and `createRunCountTests`. The new workflow is a loop whose body allows one retry and throws once on the third iteration. The test asserts that the run succeeds with recorded retry counts `[0, 0, 0, 1, 0]` and final output `4`. Diff size: 4 files, 63 lines added, 2 lines removed. ## Not changed - The default engine's behavior is unchanged. - `foreach` loops and loops with nested workflow bodies are not affected by the diff shown. ## Verification - The shared test case runs on the default and evented engines. It is skipped on Inngest with the other `retryCount` cases. - The author reports that, without the fix, the evented case fails with `expected [ 0, 1, 2 ] to deeply equal [ 0, 0, 0, 1, 0 ]`. The author reports this result. This review did not run the tests. - CI results: not available. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
f4458eea7f |
fix(core): stop failing durable runs on a slow local ownership read (#30386)
### Description A durable agent step whose process holds the run's claim no longer puts a lease TTL deadline on its ownership checks. Such a step now stops only when the claim itself is lost: a renewal fails or comes back superseded, an ownership check fails, or another execution takes over the run. Steps that only observe another process's claim (evented workers following a claim held elsewhere) keep the deadline. The change is in `ExecutionOwnershipGuard` (`packages/core/src/agent/durable/execution-ownership-guard.ts`): the deadline is armed only for remote guards, and the per-check re-arm for local guards is gone. The "Stop work after ownership loss" passage in `docs/src/content/en/docs/harness/durable-agents.mdx` is updated to match. ### Why Each fenced durable loop step checks ownership before and after it runs. For a local guard, that check armed a timer of one lease TTL (15 s by default, `MASTRA_AGENT_THREAD_LEASE_TTL_MS`) and then read the claim with `getRunOwnership`. When that read took longer than the TTL, the timer fired and the step threw `DURABLE_AGENT_EXECUTION_UNVERIFIED`, a non-retryable error. The fence was never lost and the heartbeat kept renewing the claim. Settlement then read ownership again, found this execution still the owner, and settled the run as `owned`. It published `DURABLE_AGENT_EXECUTION_UNVERIFIED` to the caller, deleted the run's snapshots and released the claim. No other execution ever owned the run. A local claim already has its own bound. The heartbeat renews it every 5 s by default (a third of the TTL) and marks the fence lost when renewals fail past the lease deadline or come back superseded. The guard hears about that loss through its `subscribe` listener. A check that throws already marks the fence lost. So the local deadline only ever acted on a read that was slow but would have answered "still yours". ### Known limits - A cancelled run ends a pending check: `withExecutionFence` always starts the ownership read but stops waiting for it when the run's abort signal fires (or has already fired), and the step handles the abort as it does elsewhere. A takeover that read finds still marks the fence lost. Without a cancellation, a check read that never returns while renewals keep succeeding still leaves the step waiting at that check, holding a live claim. Before this change the step ended at one TTL with `DURABLE_AGENT_EXECUTION_UNVERIFIED`, which failed the run and deleted its snapshots. - After a real takeover, the old execution is now stopped by its heartbeat. The heartbeat checks on ticks, so on storage-backed claims that is at most 2 x TTL plus one renewal interval after the last confirmed renewal (about 35 s with defaults). On lease-backed claims it is within one TTL plus one interval (about 20 s). Before, a step stopped one TTL after its check started. Storage writes stay fenced by generation; side effects outside Mastra don't. - Claims on `NoopLeaseProvider` have no heartbeat and were never fenced. Unchanged. - `participateInDurableExecution` awaits `fence.verify()` before every evented participant step (`packages/core/src/agent/durable/evented-execution.ts:128`) with no deadline and no abort race, so cancellation doesn't end a hanging read there. Unchanged by this PR. - On an evented worker's first fenced step of a run there is no registry entry yet, so a remote cancel doesn't end a pre-check ownership read that never returns. Losing the claim still does, and that worker's earlier `fence.verify()` (`evented-execution.ts:128`) waits on the same store with no deadline either. - Remote guards are unchanged: they still stop after one TTL without a successful check, even while verification is queued. That item stays open in #28934. - `settleEventedDurableExecution` (`packages/core/src/agent/durable/evented-execution.ts:196`) still returns early for fence errors, without emitting an error event, deleting snapshots or releasing the claim. A local guard can now only fail with `DURABLE_AGENT_EXECUTION_UNVERIFIED` when its fence is lost, and for the coordinator's fence `watchExecutionLoss` then rejects the waiting caller. Remote guards and participant fences in another process can still reach that early return with a loss that `watchExecutionLoss` doesn't report. ### Tests - `packages/core/src/agent/durable/__tests__/execution-ownership-guard.test.ts`, "leaves a slow local read to the fence instead of a deadline": a local guard whose read never returns is still not lost after 2 x TTL, and its check is still pending. Firing the fence's loss listener then rejects the check with that loss. Without the fix, the guard is already lost at 2 x TTL. - `packages/core/src/agent/durable/execution-fence.test.ts`, "finishes a step whose ownership read outlasts the lease TTL while the claim keeps renewing": a storage-backed `ExecutionFence` on `InMemoryStore` with real renewals under fake timers, and a `withExecutionFence` step whose first `getRunOwnership` resolves after TTL + 1 s. The step returns its output, the fence is not lost, the owner record keeps the same owner and generation, and the run settles as `owned`. Without the fix, the step rejects with `DURABLE_AGENT_EXECUTION_UNVERIFIED`. - `packages/core/src/agent/durable/execution-fence.test.ts`, "ends a cancelled step whose ownership read before/after its work never returns": on the same storage-backed setup, the run's registry abort signal fires while the pre-check or post-check read hangs, and the step returns its abort output (pre-check) or its finished output (post-check) with the fence not lost and the owner record unchanged. Without the cancellation handling, the step call stays pending after the abort. - `packages/core/src/agent/durable/execution-fence.test.ts`, "a step of an already-cancelled run": the step returns its abort output without waiting, the ownership read was still started, and a takeover that read finds marks the fence lost before any heartbeat. "ends a cancelled post-check on a worker whose step created the run registry entry": there is no registry entry at the pre-check, the step creates it with `ensureRemoteAbortListener` as the durable steps do, the post-check read never returns, and a published abort request ends the step with its output. The whole `packages/core/src/agent/durable` suite passes. ### Related issue(s) Related to #28934 ### 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) - [x] Documentation update - [ ] Code refactoring - [ ] Performance improvement - [ ] 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: A durable agent run checks that it still owns its work. A slow check used to make the run fail. Now a local run keeps going while its claim stays valid, and it stops when the claim is lost, a check fails, or another execution takes over. ## Overview This change updates `ExecutionOwnershipGuard` in `packages/core/src/agent/durable/execution-ownership-guard.ts`. Local guards no longer apply a lease-TTL deadline to ownership checks. Remote guards, which observe a claim held by another process, keep the deadline. The change also adds a cancellation race in `execution-fence.ts`, updates the durable agents documentation, and adds a patch changeset. ## Changes - **`execution-ownership-guard.ts`** (+2/-3): The guard arms a lease deadline at construction only for remote observers. Local claims rely on subscription notifications to report ownership loss. Local periodic checks no longer arm a deadline before they run. They also no longer clear a deadline after a successful observation. - **`execution-fence.ts`** (+26/-2): Adds `checkUnlessAborted`. This helper races an ownership check against an abort signal and removes its abort listener afterward. It still throws if the guard recorded ownership loss. `withExecutionFence` gets the signal from the run registry, with `params.abortSignal` as fallback. It uses the helper before and after each step. - **`.changeset/thick-baboons-drum.md`** (+5): Adds a patch release note for `@mastra/core`. Durable agent runs no longer fail with `DURABLE_AGENT_EXECUTION_UNVERIFIED` and lose saved snapshots when an ownership check exceeds the default 15-second lease TTL in the process that holds the run. - **`docs/src/content/en/docs/harness/durable-agents.mdx`** (+1/-1): The "Stop work after ownership loss" section separates two cases: - Steps in the process that holds the claim stop when an ownership check fails or a renewal misses the lease expiry. - Steps that only observe another process's claim stop when no check succeeds within one lease TTL (15 seconds by default). - **`execution-ownership-guard.test.ts`** (+25): Adds a test. A `check()` that waits on a never-settling local ownership read stays pending after 2× the lease TTL and does not mark ownership lost. When the subscription reports supersession, the pending check completes with the superseded error. - **`execution-fence.test.ts`** (+188/-1): Adds storage-backed `withExecutionFence` tests. They cover these cases: - A step whose ownership read exceeds the lease TTL, while the claim keeps renewing, returns its output. The run settles as owned. - A step blocked before or after its work ends when the run is cancelled. The fence stays intact. - A step of an already-cancelled run returns without waiting for a pending read. - A cancelled post-check ends on a worker whose step created the run registry entry. ## Known limits - A local check that never returns stays pending while renewals succeed. Cancellation ends the pending check through the abort race. Without cancellation, the run waits for fence loss. - Takeover detection depends on heartbeat timing. - Remote guards keep their TTL deadline. - Evented participant checks have no deadline or abort race. - Storage writes stay fenced by generation. External side effects are not fenced. ## Verification The author reports that the `packages/core/src/agent/durable` test suite passes. This summary does not independently confirm that result. Check status on the current head is not available. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
a3b4ef9ecd |
fix(core): claim the run lease before a startAsync run's first snapshot (#30384)
## Description A default-engine run started with `startAsync()` now takes its run lease before it saves its first `waiting` snapshot, and runs of workflows that save `waiting` but not `running` now take a lease too. Before this, workflow recovery on another instance could restart such a run while it was still executing, and its steps ran twice. ### Changes - `Run._start()` claims the lease before the `startAsync()` path writes the initial `waiting` snapshot, releases it if anything fails before the run is handed to the execution, and hands it to the execution, which releases it when the run settles. Plain `start()` already claimed first. - `#claimOwnership()` claims when the workflow saves `running` or `waiting`. Before, it only claimed when the workflow saved `running`. Internal workflows such as background tasks are excluded: recovery never lists them, so a lease would cost writes and protect nothing. ### Cause `startAsync()` saved a `waiting` snapshot and claimed the lease afterwards. A recovery pass on another instance that ran between the two listed the run, found no lease, and restarted it once the grace period had passed. The original execution then took its lease by force and kept going, so both executions ran the steps. A workflow whose `shouldPersistSnapshot` saves `waiting` but not `running` never took a lease at all. Every `startAsync()` run of it that lasted longer than the grace period was restarted while it ran, and so was every `start()` run that reached a sleep step, since the sleep saves `waiting`. Both cases are older than the recovery loop from #30281. They show up now because that loop runs this rule on every tick instead of once at boot. ### Behavior changes and cost - `startAsync()` resolves after the lease is taken, and rejects if taking it fails. - Workflows that save `waiting` but not `running` pay for a lease on each run: one claim, one renewal every TTL/3 while the run executes, and one release. - `restart()` of such a run is now refused while another process holds its lease, as it already is for workflows that save `running`. ### Not affected Evented runs (they have their own `start()` and `startAsync()`, and hold no run lease), agent `stream()`, the agentic, network and durable agent loops, and internal workflows such as background tasks. ### Known limits - Resume and time travel still mark the run `running` first and claim the lease afterwards. Recovery on another instance can restart a run in that window. - The grace period compares the writing process's clock with the clock of the instance running recovery. A clock gap larger than the grace (2 s by default) can still restart a run that was just written. - If taking the lease throws, `startAsync()` rejects and the workflow span stays open, as `start()` already behaves. ### Tests Three cases in `packages/core/src/mastra/restart-active-runs-rule.test.ts`, each with two `Mastra` instances on one `InMemoryStore`. Instance B runs a recovery pass with a grace of 0 while instance A executes the run, and the step must run once. Without the fix each case runs it twice (`expected [ 'run-1', 'run-1' ] to deeply equal [ 'run-1' ]`). - `startAsync()` on A while the store holds A's first lease claim back. B's pass runs while the claim is pending. - `startAsync()` of a workflow that saves `waiting` but not `running`. B's pass runs while A's step executes. - `start()` of the same kind of workflow with a sleep step before the step. B's pass runs once the sleep saved `waiting`. A fourth case covers the lease on failure: when `shouldPersistSnapshot` throws for `waiting`, `startAsync()` rejects with that error and the run's ownership record is no longer live (without the release it stays live, because it keeps renewing). ## Related issue(s) Related to #28060 ## 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 - [ ] 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:** A workflow run can start on one server. Another server might restart that run by mistake, because it does not see that the first server is already running it. This change makes the first server claim a lease on the run before it saves the first snapshot. ## Summary This change fixes a race in workflow recovery for default-engine `startAsync()` runs. Recovery can find a `waiting` run that has no lease and restart it while its original execution still runs. The change claims the run lease before the initial `waiting` snapshot is written. ## Changes - **`packages/core/src/workflows/workflow.ts`** (+84/−67): - `Run._start` claims recovery ownership before it writes the initial `waiting` snapshot. - `_start` passes the held claim to `#executeOwned`. Execution releases the lease when the run settles. - If snapshot creation or dispatch setup fails, `_start` releases a releasable claim. - If the snapshot write fails, the workflow span ends with the error. - `#claimOwnership` claims recoverable runs when the persistence predicate accepts `running`. It also claims them when the predicate accepts `waiting` for a non-internal workflow. - `#executeOwned` accepts either an ownership lease or an owner record as its held value. - **`packages/core/src/mastra/restart-active-runs-rule.test.ts`** (+97/−3): - `startBlockingReplica` accepts snapshot-persistence options and an optional sleep before the first step. - New tests cover: - Recovery during a pending run-ownership claim. Recovery must not start a duplicate run. - Live `startAsync` runs and sleeping runs whose workflows persist `waiting` but not `running`. Recovery must not restart them. - A `startAsync` failure while the predicate decides whether to persist `waiting`. The failed start must release its lease and must not run the workflow. - **`.changeset/thin-moose-know.md`** (+5/−0): Adds a patch changeset for `@mastra/core`. It documents the recovery and lease behavior. Diff size: 3 files, +186 lines, −70 lines. ## Behavior - `startAsync()` resolves after the lease is claimed. It rejects if the claim fails. - A run that holds a lease renews it every TTL/3 while it executes. It releases the lease when it settles. - `restart()` is refused while another process holds the run lease. - Affected workflows add one lease claim, periodic renewals, and one release. - Internal workflows do not claim a lease only because they persist `waiting` snapshots. ## Not changed - Evented runs, agent `stream()`, agentic, network, and durable agent loops are not affected. - Resume and time-travel lease timing remains a stated limit. - Clock skew larger than the grace period can still let recovery restart a recently written run. - If a lease claim fails, the workflow span stays open. This matches `start()`. ## Verification - The PR description reports that each added recovery case runs its step twice without the fix. This is the author's report. It is not confirmed here. - CI and test results for the current head are not available. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
1c52fdd034 |
chore: version packages (alpha) (#30261)
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/factory@0.29.0-alpha.1 ## @mastra/core@1.84.0-alpha.1 ## @mastra/playground-ui@69.1.0-alpha.1 ## @mastra/client-js@1.60.1-alpha.1 ## @mastra/react@1.15.1-alpha.1 ## @mastra/deployer-cloud@1.84.0-alpha.1 ## @mastra/longmemeval@1.1.43-alpha.1 ## @mastra/opencode@0.1.43-alpha.1 ## create-factory@0.4.4-alpha.1 ## @mastra/code-sdk@1.19.1-alpha.1 ## mastracode@0.50.1-alpha.1 ## @mastra/arize@1.3.31-alpha.0 ## @mastra/arthur@0.4.31-alpha.0 ## @mastra/braintrust@1.3.28-alpha.0 ## @mastra/datadog@1.4.23-alpha.0 ## @mastra/deepeval@0.1.25-alpha.0 ## @mastra/laminar@1.3.33-alpha.0 ## @mastra/langfuse@1.6.7-alpha.0 ## @mastra/langsmith@1.4.4-alpha.0 ## @mastra/observability@1.24.1-alpha.0 ## @mastra/otel-bridge@1.5.23-alpha.0 ## @mastra/otel-exporter@1.5.3-alpha.0 ## @mastra/posthog@1.4.8-alpha.0 ## @mastra/sentry@1.2.33-alpha.0 ## @mastra/agent-builder@1.2.2-alpha.0 ## mastra@1.39.1-alpha.1 ## @mastra/connect@1.4.1-alpha.0 ## @mastra/deployer@1.84.0-alpha.1 ## @mastra/editor@0.17.2-alpha.0 ## @mastra/mcp-docs-server@1.3.14-alpha.1 ## @mastra/memory@1.41.2-alpha.0 ## @mastra/server@1.84.0-alpha.1 ## @mastra/google-cloud-pubsub@1.1.8-alpha.0 ## @mastra/redis-streams@0.8.2-alpha.0 ## @mastra/valkey-streams@0.6.3-alpha.0 ## @mastra/elysia@0.1.24-alpha.1 ## @mastra/express@1.5.28-alpha.1 ## @mastra/fastify@1.5.28-alpha.1 ## @mastra/hono@1.7.26-alpha.1 ## @mastra/koa@1.7.28-alpha.1 ## @mastra/nestjs@0.3.1-alpha.1 ## @mastra/next@0.2.42-alpha.1 ## @mastra/tanstack-start@0.2.42-alpha.1 ## @mastra/clickhouse@1.30.1-alpha.0 ## @mastra/cloudflare@1.8.1-alpha.0 ## @mastra/cloudflare-d1@1.5.1-alpha.0 ## @mastra/convex@1.9.1-alpha.0 ## @mastra/dsql@1.5.8-alpha.0 ## @mastra/dynamodb@1.5.2-alpha.0 ## @mastra/libsql@1.30.1-alpha.0 ## @mastra/mongodb@1.27.1-alpha.0 ## @mastra/mssql@1.11.2-alpha.0 ## @mastra/mysql@0.17.1-alpha.0 ## @mastra/oracledb@0.5.7-alpha.0 ## @mastra/pg@1.36.1-alpha.0 ## @mastra/redis@1.4.14-alpha.0 ## @mastra/spanner@1.12.1-alpha.0 ## @mastra/turso@0.1.22-alpha.0 ## @mastra/upstash@1.6.2-alpha.0 ## @mastra/valkey@0.2.10-alpha.0 ## @mastra/temporal@0.6.1-alpha.1 ## @mastra/daytona@0.11.6-alpha.0 ## create-mastra@1.39.1-alpha.1 ## @internal/playground@1.39.1-alpha.1 Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
8acea4cc5b |
fix(core): background task timeout 0 means none (#30381)
## Description
Setting a background task timeout to `0` killed the task right away: the
worker armed `setTimeout(abort, 0)`, so the task ended as `timed_out`
before it did any work.
Now `0` means no timeout. The task runs until it finishes or is
cancelled. This works on the tool config, the agent's per-tool config,
the enqueue payload, and the manager's `defaultTimeoutMs`. Other values
behave as before.
```ts
const longJob = createTool({
id: 'long-job',
// ...
background: {
enabled: true,
// before: the task timed out immediately
// after: the task has no timeout
timeoutMs: 0,
},
})
```
Also documents `0` on the related types and on the background tasks and
configuration docs pages.
## Related issue(s)
None. Standalone fix, independent of any other PR.
## 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)
- [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)
- [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:** A background task can have a time limit. Before this change, a
limit of `0` stopped the task right away. After this change, `0` means
the task has no time limit, so it runs until it finishes or is
cancelled.
## Summary
This change makes a background task timeout of `0` mean "no timeout."
Other timeout values keep their existing behavior. The `0` rule applies
in four places:
- Tool configuration
- Agent per-tool configuration
- The enqueue payload
- The background task manager's `defaultTimeoutMs`
The change also alters how an `AbortError` from a tool is classified. A
tool that throws its own `AbortError` no longer counts as a timeout. The
task fails with the tool's own error. Retries apply if they are
configured.
The task's own signal aborts for these cases: timer expiry,
cancellation, workflow cancellation, shutdown, and ownership loss.
Executors receive that signal.
## Changes by file
- `packages/core/src/background-tasks/workflow.ts`: Does not create the
timeout timer when `task.timeoutMs` is `0`. For other values, the timer
still aborts the task after the configured duration. Timeout
classification now requires an aborted signal or the matching timeout
message. An `AbortError` name or the `"Task cancelled"` message alone no
longer counts as a timeout.
- `packages/core/src/background-tasks/types.ts`: Documentation comments
state that `0` means no timeout for task payloads, manager defaults, and
per-tool overrides. No runtime types changed.
- `packages/core/src/background-tasks/manager.test.ts`: Adds tests. One
test checks that `timeoutMs: 0` prevents a timeout after fake timers
advance 600 seconds, and that the task completes after its executor is
released. Another test checks that an executor's `AbortError` with
`timeoutMs: 0` results in status `failed` with the original error
message.
- `.changeset/wet-geckos-work.md`: Adds a patch changeset for
`@mastra/core`. It documents the `0` behavior and the `AbortError`
behavior.
- `docs/src/content/en/docs/harness/background-tasks.mdx`: The timeout
resolution order states that `0` means no timeout at the tool,
agent-tool, or manager-default level.
- `docs/src/content/en/reference/configuration.mdx`: The
`backgroundTasks.defaultTimeoutMs` entry states that `0` means no
timeout.
- `docs/src/content/en/reference/core/mastra-class.mdx`: The
`backgroundTasks.defaultTimeoutMs` description states that `0` means no
timeout.
## Public API
No exported declarations changed.
## Diff size
- 7 files changed
- 73 lines added, 11 lines removed
## Test and CI results
Not available. The new tests appear in the diff, but no completed test
or CI run results were supplied.
## Review status
Review finding counts are not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
|
||
|
|
37ddff38e5 |
test(core): run the claimed owner's runs on the runtime that registers them (#30389)
## Description Builds the claimed owner in the caller request context tests of `signals-claimed-ownership.test.ts` on the shared `agentThreadStreamRuntime`, the runtime `Agent.stream` registers its runs on. The sender stays on its own `AgentThreadStreamRuntime` and still plays the other process. Test-only change, four lines. "runs a plain wake that arrives during owner discovery with its own caller tenant" fails every time on current `main` (`Timed out waiting for the second owner run`). It breaks "Unit and E2E Tests / Affected UNIT Test (3/3)" on every PR that runs core tests. ### Cause The test built the owner on a separate `AgentThreadStreamRuntime`, while `Agent.stream` registers runs on the shared one. The owner therefore saw its own run as remote: it marked the thread busy with that run's id when it started it, and only learned the run's stream id from `run-registered` if a lease check still found the run live. #29148 removed the 1 ms pause after memory saves. The run now releases its lease before that check resolves, so the stream id is never recorded. The second wake is queued behind a run the owner has no record of, `run-completed` can't clear the busy marker because the stream id doesn't match, and the wake is acknowledged but never started. #29447 added the test and #29148 removed the pause. Neither PR's CI ran both. ### Why the fix is in the test Production uses one runtime per process. `Agent.claimThreadOwnership` and `Agent.subscribeToThread` go through `agentThreadStreamRuntime` (`agent/agent.ts`), every `registerRun` call is on it (`agent/agent.ts`, `agent/durable/durable-agent.ts`), and only that instance is exported (`agent/durable/index.ts`), not the class. A run the owner starts is registered in the owner's own state, so a wake queued behind it is drained by that run's completion watcher. Several tests in this file already use the shared runtime for the owner. The other tests in this block that #29447 added get the same one-line change so the block models the same setup. ### Verification - The whole file passes 10 out of 10 runs with `npx vitest run --project unit:packages/core src/agent/__tests__/signals-claimed-ownership.test.ts`. Before the change it failed 10 out of 10. - With the change, removing #29447's request-context argument from the during-discovery delivery in `thread-stream-runtime.ts` fails only this test, on `expect(Promise.all([first.accepted, second.accepted])).resolves` with `tenant missing from request context`. The test still covers that fix. - `src/agent/__tests__` passes (200 files), and `tsc --noEmit -p tsconfig.build.json` and oxfmt are clean. ## Related issue(s) None. ## 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) - [ ] 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) - [ ] 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 The test setup had the wrong runtime for the claimed owner. This change makes the test owner use the same shared runtime that the agent uses to run streams. This lets the owner track its own run and handle queued wakes correctly. ## Summary The change updates test setup in `packages/core/src/agent/__tests__/signals-claimed-ownership.test.ts`. The diff adds 4 lines and removes 4 lines in one file. Four claimed-owner context tests now use the process-wide `agentThreadStreamRuntime`. Before the change, each test created a separate owner runtime. The affected tests cover: - Caller tenant propagation. - Transformed tool context. - Wakes that arrive during owner discovery. - Owner-versus-caller session identity. The sender stays on its own `AgentThreadStreamRuntime`. This represents the other process. ## Rationale The owner and `Agent.stream` must use the same runtime. With the same runtime, the owner can track the run that `Agent.stream` registers. The owner can then drain a wake that is queued behind that run when the run completes. With separate runtimes, a queued wake could be acknowledged without starting. ## Verification The following results are reported by the PR author. They were not re-run for this summary: - `signals-claimed-ownership.test.ts` passed 10 of 10 runs after the change. It failed 10 of 10 runs before the change. - `src/agent/__tests__` passed (200 files). - `tsc --noEmit -p tsconfig.build.json` and oxfmt were clean. No public or exported declarations changed. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
3a91e29455 |
fix(playground-ui): let page scroll continue past a DataList (#30333)
## Description Scrolling the page with the cursor over a DataList did nothing. The viewport scrolls on both axes and had `overscroll-none`, so a wheel over a list with nothing left to scroll never reached the page. Now only the x axis keeps overscroll off, so a sideways flick still can't trigger browser back. A list that does overflow scrolls first, then hands off to the page at its end. No visual change, so no screenshots. Safari may now rubber-band a list that overflows, which is what `overscroll-none` was guarding against. Verified: playground-ui tests (546 files) and typecheck pass. The new test fails on the old code. Ran real wheel events in Chrome on the admin portal Connect page, against this build, with short and overflowing lists, scrolling down and back up. ## Related issue(s) Fixes PLTFRM-3615 ## 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 - [ ] 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: When your mouse is over a data table, scrolling down past the end of the table now moves the whole page. Before this change, the page stopped scrolling there. ## Summary This change lets page scrolling continue when the cursor is over a `DataList`. The list scrolls first. When the list reaches its scroll limit, vertical scroll passes to the page. ## Changes - `packages/playground-ui/src/ds/components/DataList/data-list-root.tsx`: The `ScrollAreaViewport` class changes from `overscroll-none` to `overscroll-x-none`. Overscroll is now disabled only on the horizontal axis. Vertical overscroll is no longer disabled by this class. - `packages/playground-ui/src/ds/components/DataList/data-list-root.test.tsx`: Adds a test. The test checks that the viewport class includes `overscroll-x-none` and does not include `overscroll-none`, `overscroll-y-none`, or `overscroll-y-contain`. - `.changeset/warm-garlics-lick.md`: Adds a patch changeset for `@mastra/playground-ui`. ## Behavior notes - Horizontal overscroll stays disabled. This prevents a sideways gesture from triggering browser history navigation. - The code comment that explained why overscroll was off is removed. That comment said a vertical bounce would drag the sticky header and expose the panel behind the content. The diff does not add a replacement note. The sticky header behavior under vertical bounce is therefore not documented in the code. - The PR description says Safari can rubber-band overflowing lists. This is not verified by the diff. ## Verification - The diff confirms the class change, the comment removal, and the new test and changeset. - The PR description reports that the playground-ui tests and typecheck pass, and that manual wheel testing in Chrome passed. These results are author-reported. They were not checked against completed CI runs for this head. - No public API declarations changed. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
eb57671973 |
fix(connect): default OpenAI create-image tool to gpt-image-2.5-sunburst (#30364)
> Opened by @arthurfiorette The OpenAI create-image tool in `@mastra/connect` defaulted to `gpt-image-1`, which OpenAI retired on October 23, 2026. Calls that omitted `model` failed. This changes the default (and the schema description) to `gpt-image-2.5-sunburst`, OpenAI's recommended replacement, so those calls work again. A changeset is included. Test plan: not run locally. The change replaces one string default and the matching description text. Fixes #30329 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> **ELI5:** The tool that makes images used an old AI model when the caller did not name one. OpenAI turned that model off, so those calls failed. This change makes the tool use a newer model by default, and it keeps that default when the provider code is regenerated. ## Overview This change updates the default model of the OpenAI create-image tool in `@mastra/connect`. The default changes from `gpt-image-1` to `gpt-image-2.5-sunburst`. OpenAI retired `gpt-image-1` on October 23, 2026. Calls that omit `model` failed after that date. This change addresses those calls. The generator script also changes. Without this change, regenerating the OpenAI provider would restore the old default. The generator now applies the same default. It uses `replaceOnce` and throws if an expected template pattern does not occur exactly once. ## Changes - `packages/connect/src/providers/openai/tools/create-image.ts`: Changes the fallback model used when `input.model` is omitted. Changes the matching schema description to name the new default. Explicitly passed models are unchanged. - `packages/connect/scripts/generate-provider.ts`: Adds an OpenAI `create-image` override. The override changes the generated model-default description and the execution fallback to `gpt-image-2.5-sunburst`. `applyProviderActionOverrides` applies this override for the OpenAI create-image action. - `packages/connect/src/__tests__/provider-commands.test.ts`: The OpenAI image action fixture accepts an optional `model` and sends it with the prompt. The fixture defaults to `gpt-image-1` when `model` is omitted. A new test asserts that generated OpenAI tools default to `gpt-image-2.5-sunburst`, document that default, and do not reference `gpt-image-1`. - `packages/connect/src/providers/openai/.manifest.json`: Updates the SHA-256 value for `tools/create-image.ts`. - `.changeset/connect-image-default-sunburst.md`: Adds a patch changeset for `@mastra/connect`. The changeset documents the default model change. ## Scope - 5 files changed. - 55 lines added and 5 lines removed. - No exported or public declarations changed. ## Verification - The author states that tests were not run locally. - No completed CI or test results were available for review. ## Linked issue - Issue `#30329` reports the retired default model. It names `gpt-image-2.5-sunburst` and `gpt-image-2.5-flare` as replacement options. This change uses `gpt-image-2.5-sunburst`. <!-- 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> |
||
|
|
d6cb408779 |
ci(mcp): keep the version-packages compat check working on branches behind a release (#30280)
## Problem The **E2E MCP compatibility** job's last step simulates a version-packages PR. It runs `changeset version` on a scratch changeset and requires the bumped versions of `@mastra/core`'s workspace dependencies to be unpublished on npmjs. On a branch that is behind main's latest alpha release, the bump lands on a version main has already published. For example, `@mastra/schema-compat` 1.4.0-alpha.1 bumps to alpha.2, which is already on npm. The step then exits before running the compat consumers: ``` @mastra/schema-compat@1.4.0-alpha.2 is not an unpublished version on npmjs (HTTP 200), so this does not reproduce a version-packages PR ``` After every alpha release this fails the job on unrelated PRs until each one merges main. ## Change `packages/mcp/integration-tests/version-packages-regression.mjs` now runs the same `changeset version` again, with a fresh uniquely named changeset, while any bumped dependency is still on npmjs. It stops after 10 rounds. The step always reaches the unpublished state it is meant to reproduce. Unexpected npmjs responses now fail with their own message instead of being treated as "published". ## Testing Run in a disposable checkout of a branch that is behind the 1.4.0-alpha.2 release (schema-compat 1.4.0-alpha.1, pre mode): - Old script: fails with the error above. - New script: `1.4.0-alpha.2 is already on npmjs; versioning again`, then `1.4.0-alpha.1 -> 1.4.0-alpha.3 (not on npmjs)`. - `compat.sh` in that bumped state, against the CI E2E registry snapshot: `MCP COMPAT PASS`. - Covered by unit-level probes: bound exhaustion, HTTP 403/429/500 and network errors failing closed, and a no-progress bump being rejected. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ELI5: The test script that checks MCP compatibility used to stop when a new package version was already public. Now it keeps creating new version bumps until each bumped package version is not yet public, so the test can run. Summary: Scope: One file changed, `packages/mcp/integration-tests/version-packages-regression.mjs` (+40/-15). Behavior change: - The script no longer requires every bumped workspace dependency to be unpublished after one `changeset version` run. - It runs `changeset version` in rounds. Each round writes a new patch changeset for the dependencies that are still published. - For each dependency, it checks `https://registry.npmjs.org/<name>/<version>`: - HTTP 404: the version is unpublished. The dependency leaves the list. - Other successful (2xx) response: the version is published. The dependency stays in the list for another round. - Any other status, or a network error: the script throws an error that names the package, version and HTTP status. - If a dependency's version does not change after a round, the script throws an error. - The limit is 10 rounds (`MAX_ROUNDS`). If dependencies are still published after 10 rounds, the script throws an error that lists them. - Changeset file names include a round number, so each round creates a unique file name. - The header comment now describes rerunning versioning when a bumped version is already published. It no longer says the script checks that versions are absent before versioning. Reason: A branch behind the latest release can bump a workspace dependency to a version already published on npmjs. The old script failed in that case before it ran the compatibility checks. Verification: The PR author reports a manual run on a checkout behind the 1.4.0-alpha.2 release. The old script failed. The new script advanced `@mastra/schema-compat` from 1.4.0-alpha.1 to alpha.3. The author also reports `compat.sh` passed (`MCP COMPAT PASS`) against the CI E2E registry snapshot. The author reports unit-level probes for round-limit exhaustion, HTTP 403/429/500 responses and network errors, and rejection of a bump that makes no progress. CI results for this head are not available from the supplied evidence. Public API: No declarations of exported or public entities changed. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com> |
||
|
|
94fd1f0a5f |
test(core): catch bracket-form env writes and Windows paths in the isolation check (#30368)
## Summary A follow-up to #30308 (isolate core tests that set env before their imports). That PR added a check that fails when a core unit test sets `process.env` before its imports but isn't in the isolated list. Review found two gaps in it: - **Bracket form missed.** The check matched `process.env.X = …` but not `process.env['X'] = …` (or the `"X"` and backtick forms). A test written that way could stay in the shared lane and leak its env into other files, the same way `thread-lease-loss-parked` broke main. The pattern now matches dot and bracket writes, at top level and inside `vi.hoisted`. `===` comparisons still don't match. - **Windows paths.** `relative()` returns backslash paths on Windows, which never match the forward-slash isolated list, so every isolated file would be reported missing. Paths are now converted to `/` before the comparison. ## Test plan - New test in `packages/core/src/isolated-tests-list.test.ts` covers five matched forms and three ignored ones. It fails with the old pattern (bracket case) and passes with the fix, 2/2 twice. - Path conversion checked with `path.win32` (not run on a Windows machine). - Core type check, oxlint and oxfmt are clean. Test-only change, no changeset. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> **ELI5:** The test checks that unit test files which change environment settings before their imports are listed as isolated. This change makes the check catch more ways of writing those settings, and makes it work on Windows paths too. ## Summary of changes This change updates one file: `packages/core/src/isolated-tests-list.test.ts` (+26, -3). **Path normalization** - `unitTestFiles` converts each discovered path to use `/` as the separator. It calls `.split(sep).join('/')` on the result of `relative()`. This lets the paths match the isolated-file list on Windows. **Environment-write pattern** - The pattern `envBeforeImports` is now built from a shared `envWrite` fragment. It matches: - Dot notation: `process.env.NAME =` - Bracket notation with single quotes, double quotes, or backticks: `process.env['NAME'] =`, `process.env["NAME"] =`, and the backtick form - The fragment ends with `=(?!=)`, so equality comparisons (`===`) do not match. - Matches count at the start of a line (top level) or inside a `vi.hoisted(() => { ... })` block. **New test case** - `recognizes env writes before imports in dot and bracket form` is added. - It asserts five forms that match: dot, single-quoted bracket, double-quoted bracket, and the dot and single-quoted bracket forms inside `vi.hoisted`. - It asserts three forms that do not match: a single-quoted bracket write inside `beforeEach`, an `===` comparison, and a read. - The test builds `process.env` at runtime so that the file's own source does not match the pattern. - The backtick bracket form is in the regex but has no test case. **Not verified in this review** - The author reports that the test passed 2/2 twice, that Windows path handling was checked with `path.win32`, and that the type check, oxlint, and oxfmt pass. I did not run these checks. - The PR has no changeset. The author states it is test-only. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com> |
||
|
|
2087fdccb8 |
fix(server): limit built-in MCP memory tools to reads and add working-memory inspection (#30245)
## Summary The built-in MCP server (added in #29931, built-in MCP memory tools) gives connected MCP clients a set of memory tools. Two of them did more than an outside client should: `save_messages` wrote raw messages straight into a thread, and `search_memory` ran a broad semantic-recall search. There was also no way to read an agent's working memory through MCP. This PR narrows the built-in MCP memory toolset to inspection: - **Removed `save_messages` and `search_memory` from the built-in MCP toolset.** Their HTTP endpoints are unchanged; only MCP exposure is removed. - **Added read-only `get_working_memory`** for a thread or a resource. It never writes stored state and works in read-only mode. - With a thread (the request's reserved context thread takes precedence over a `threadId` argument), it uses the existing thread working-memory route and its ownership checks. - Without a thread, it uses a new `GET /memory/working-memory` route that reads resource-scoped working memory for the caller's effective resource. When fine-grained authorization (FGA) is configured, the route requires an authenticated user and checks `memory:read` on that resource; a grant on a single thread does not authorize the whole resource. - Regenerated client route types and CLI route metadata for the new route. ## Test plan - New regression tests with real `Memory` + `InMemoryStore`, `Agent` and `Mastra`, through the MCP catalogue and route handlers: tool list, thread and resource reads, FGA allow/deny, missing user, spoofed resource, thread grant vs resource grant, Studio/server FGA provider selection, reserved context thread precedence, and no storage mutation. - These tests fail on the code before the fix (8 failed / 25 passed) and pass after. - Focused MCP/memory/FGA-provider suites: 140/140. - Full server suite: 128 files, 3,552 passed, 3 skipped, 1 todo. - `pnpm build:server`, server TypeScript, lint, formatting, and `generate:permissions` / `check:permissions` pass. - Live loopback MCP SDK client check of `tools/list` and `tools/call`: removed tools are absent, caller identity is enforced, nothing is written. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 This change makes the built-in MCP memory tools read-only. It removes the tools that save messages or search memory. It adds one tool that reads working memory for a thread or a resource. ## Summary This change limits the built-in MCP memory toolset to inspection. It removes the `save_messages` and `search_memory` tools from MCP. Their HTTP endpoints remain unchanged. It adds a read-only `get_working_memory` MCP tool. ### Behavior - **Thread reads:** The tool uses the reserved context thread ID when one exists. Otherwise, it uses the `threadId` argument. Thread reads use the existing thread working-memory route. The existing ownership checks apply. - **Resource reads:** When no thread ID is available, the tool calls the new route `GET /memory/working-memory`. The route reads working memory for the effective resource ID. When the tool call omits the resource ID, the tool uses the value from the request context. - **Fine-grained authorization (FGA):** When an FGA provider is configured, the resource route requires an authenticated user and `memory:read` permission on the effective resource. The FGA check passes request context. A grant on one thread does not authorize resource-wide access. - **Memory unavailable:** The resource route returns null working memory when memory is unavailable. - **Thread-scoped requests on the resource route:** The resource route rejects thread-scoped working memory. ### Changed files - `packages/server/src/server/handlers/memory.ts`: Adds MCP metadata to `GET_WORKING_MEMORY_ROUTE`. Adds `GET_RESOURCE_WORKING_MEMORY_ROUTE`. Removes MCP tool metadata from `SAVE_MESSAGES_ROUTE` and `SEARCH_MEMORY_ROUTE`. - `packages/server/src/server/mcp/toolsets/memory.ts`: Adds working-memory retrieval for threads and resources. Removes the search and message-saving operations. - `packages/server/src/server/server-adapter/routes/memory.ts`: Adds the new route to the exported `MEMORY_ROUTES`. - `packages/server/src/server/server-adapter/routes/fga-manifest.ts`: Registers `/memory/working-memory` as a resource route. The resource ID comes from the request context, or from the `resourceId` parameter. - `packages/server/src/server/server-adapter/index.test.ts`: Adds FGA tests for the resource working-memory endpoint. - `packages/server/src/server/mcp/toolsets.test.ts`: Adds tests for FGA provider selection, fail-closed behavior, resource and thread permissions, reserved-context precedence, and read-only inspection. Updates the expected tool list. - `server-adapters/server-adapters-test-suite/src/builtin-mcp-parity-test-suite.ts`: Removes `save_messages` and `search_memory` from the expected tool list. - `server-adapters/server-adapters-test-suite/src/builtin-mcp-toolsets-test-suite.ts`: Adds `get_working_memory` to the parity and read-only cases. Asserts that `save_messages` is not offered to a non-owner and that the HTTP write returns 403. - `server-adapters/server-adapters-test-suite/src/route-test-utils.ts`: Sets a default `resourceId` for `GET /memory/working-memory`. - `.changeset/red-pets-throw.md`: Declares patch releases for `@mastra/client-js`, `@mastra/server`, and `mastra`. The PR also regenerates client route types and CLI route metadata. The diff changes 12 files, with 558 lines added and 57 removed. ### Public API - New route: `GET_RESOURCE_WORKING_MEMORY_ROUTE` at `GET /memory/working-memory`. - Changed export: `MEMORY_ROUTES` includes the new route. - MCP tool surface: `save_messages` and `search_memory` are removed from MCP. `get_working_memory` is added. The HTTP endpoints for the removed tools are unchanged. ### Verification The author reports these results. This summary did not run them: - 140 of 140 focused MCP, memory, and FGA-provider tests pass. - 128 server test files pass, with 3,552 tests passed, 3 skipped, and 1 todo. - Server build, TypeScript, lint, formatting, and permission-generation checks pass. - A live loopback MCP SDK check of `tools/list` and `tools/call` passes. - The author reports that the new regression tests failed before the change (8 failed, 25 passed) and pass after it. CI status on the current head: not available. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com> |
||
|
|
174f81a1c9 |
feat(playground-ui): add no-alerts and no-destinations empty-state drawings (#30354)
## Description Adds two empty-state drawings to `EmptyStateIllustration`: `no-alerts`, a warning beacon whose rays light up on hover, and `no-destinations`, a letter dropping into a mail slot. Platform's Alerts page uses them on the empty Alerts and Destinations tabs. | Dark | Light | | --- | --- | |  |  | Verified: EmptyState tests, oxlint and prettier pass; checked both drawings at 300px in Storybook in dark and light, on hover, and with reduced motion (the rays stay off). ## Related issue(s) PLTFRM-3618 ## Type of change - [x] New feature (non-breaking change that adds functionality) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> **ELI5:** This change adds two new empty-state pictures to the playground UI. One picture shows a warning beacon for alerts. The other shows a letter going into a mail slot for destinations. When the user hovers over a picture, the alert rays fade in, and the letter moves. ## Overview This change adds two SVG illustrations to the `EmptyStateIllustration` component in `@mastra/playground-ui`: - `no-alerts`: a warning beacon. - `no-destinations`: a letter that drops into a mail slot. The diff touches 5 files. It adds 102 lines and removes 0. ## Changes - **`illustrations/no-alerts-art.tsx`** (new, 41 lines): exports `NoAlertsArt()`. It renders a stroked SVG group with a beacon shape. A child group holds the six ray lines. That group has `opacity-0` by default. On `empty-state` group hover, it changes to `opacity-100`. The opacity transition applies only inside `motion-safe:` variants. - **`illustrations/no-destinations-art.tsx`** (new, 48 lines): exports `NoDestinationsArt({ id })`. It renders a stroked SVG group with a mail slot and a letter. The letter is clipped by a mask. The mask ID comes from the `id` prop, so each instance has a unique mask ID. A `hoverStyle` object sets `--hover-shift` to `0px 16.89px`. On `empty-state` group hover, the letter group applies `translate: var(--hover-shift)`. The transition applies only inside `motion-safe:` variants. - **`empty-state-illustration.tsx`** (+6): imports both components. It adds `'no-alerts'` and `'no-destinations'` to the `EmptyStateIllustrationName` union. It also maps both names to their components. - **`empty-state.stories.tsx`** (+2): adds `no-alerts` labeled "Alerts" and `no-destinations` labeled "Destinations" to the `AllIllustrations` story. - **`.changeset/shy-files-relate.md`** (new, +5): declares a patch release for `@mastra/playground-ui`. It describes the two illustrations and shows the usage `<EmptyStateIllustration name="no-alerts" />`. ## Not verified - The PR author reports that EmptyState tests, oxlint, and prettier pass. The diff does not show these results, so they are not available from this review. - The author reports visual checks in Storybook's "All illustrations" view in dark and light themes. This is not available from this review. - The PR description says Platform's Alerts page uses these illustrations. This repository does not contain that page, so this is not available from this review. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
8ac88228d6 |
fix(core): remove the 10 ms pause after memory saves and keep same-millisecond turns in order (#29148)
## What Removes the 10 ms pause `MessageHistory` waited after every memory save, and fixes the ordering bug that pause had been hiding. Stacked on #29142 (keep a forwarded queued message until the owning run accepts it). Retarget to `main` once that merges. ## Why The pause was added so the next message's timestamp would always land after the saved one. Without it, a new turn's input can be stamped in the same millisecond as the previous turn's stored answer. Sorting on equal timestamps then puts the stored answer last, and the new turn's response merges into that old answer. Under load, `signals-pending-cancellation` "answers the follow-up after upstream/thread cancellation" failed 2 of 12 runs this way. Every memory-backed call also paid at least 10 ms per save. ## How - `message-history.ts`: drop the post-save `setTimeout`. Stored history is now added in a single `add(array, 'memory')` call, as semantic recall already does. - `MessageList`: after a memory add, any live message whose timestamp equals a stored one moves 1 ms later, skipping other stored times, and its signal `createdAt` is kept in sync. Live messages that tie only with each other keep their timestamps. The pass runs once per add, in O(n log n). ## Test changes (setup only, no assertion changes) - New `input-after-stored-history-tie.test.ts`: a tied new turn stays after the stored answer (fails without the fix), and same-ms live messages with no stored tie are left untouched. - `signals-pending-cancellation` lease-loss test now waits for the follow-up run to register before it vanishes. Without the pause, the run could vanish before registering, and the message was delayed past the test window. The test still fails against a runtime without the lease watch. - `provider-history-compat` fixture: explicit ascending `createdAt` values in place of four `new Date()` calls that landed in the same ms. - `background-task-call-id-reuse` scenario: waits for the last background result instead of relying on the pause. ## Testing - Full core unit lane (`--project unit:packages/core`, Node 24, 5 CPUs): 1,560/1,560 files, 25,295 passed, 0 failed. - Signals, message-list and call-id-reuse suites: 3 repeated runs, 1,169 passed each. - `tsc --noEmit` and oxlint are clean. Not verified: real multi-process pubsub (Unix socket/Redis), and stores other than core's in-memory and test stores. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> **ELI5:** When a chat app saves a reply, it used to wait 10 ms. Two messages could also get the same timestamp and sort in the wrong order. This change removes the wait and keeps messages in the correct order, even when timestamps match. ## Overview This change removes the 10 ms pause after each memory save in `MessageHistory`. It also changes how `MessageList` orders live messages whose timestamps match stored history. Without this change, a new turn's response could merge into the previous turn's stored answer. The change also covers a forwarded-idle case, where a run can start after another process's lease disappears. The runtime clears the forwarded run's active IDs only when the stream ID and run ID still match the values it read before the lease check. ## Changes by area **Memory save path** - `packages/core/src/processors/memory/message-history.ts`: `processInput` adds all chronological history in one `add(array, 'memory')` call. It previously added each message separately. `processOutputResult` no longer waits 10 ms after it persists messages. **Message ordering** - `packages/core/src/agent/message-list/message-list.ts`: `MessageList.add` runs `moveLiveMessagesPastStoredTies` after it processes inputs. The pass runs once per add. - When memory messages exist, the pass marks them as stored. - It moves live messages that share a stored timestamp. It also moves live messages that would no longer follow a moved live message. - It skips other stored times when it chooses new timestamps. - It orders placements by each message's own timestamp and arrival order. - It preserves anchored signals. It updates matching signal `createdAt` values and the ordering watermark. - It re-queues moved persisted messages, so the moved timestamps are saved again. - It sorts the list only when a message moved. - Live messages that tie only with each other keep their timestamps. **Remote run forwarding** - `packages/core/src/agent/thread-stream-runtime.ts`: The forwarded idle-signal lease checker snapshots the active stream ID before it reads the lease. - After consecutive checks show that the target run no longer holds the lease, and its unadmitted signals are requeued, the runtime clears that run's active run ID and stream ID. - It clears them only when the run has no local record, the active stream ID is unchanged from the snapshot, and the active run ID still matches. - It then drains pending idle signals. **Tests** - `packages/core/src/agent/__tests__/signals-pending-cancellation.test.ts`: Adds and updates coverage for follower idle messages. The cases cover runs that end, are superseded, or lose their lease before delivery. The vanished-owner tests wait for the follow-up run's registration to reach subscribers before they end the run. A new test checks that a follower with queued work does not start local execution after it unsubscribes and sees the lease disappear. Another test checks that a run that takes the thread during an in-flight lease read stays active. A further test checks that a remote run that starts and ends during that read does not block the drain of queued work. - `packages/core/src/agent/message-list/tests/input-after-stored-history-tie.test.ts` (new): Covers ties between stored history and live input, response, and context. It checks reminder placement, deduplication under turn sources, and turn order when stored history arrives in batches. A save test checks that a moved input is returned for saving with its updated timestamp. - `packages/core/src/loop/test-utils/aimock/scenarios/background-task-call-id-reuse.scenario.test.ts`: Waits after each turn until that turn's background result appears in recalled memory. - `packages/core/src/processors/provider-history-compat.test.ts`: Gives transcript messages explicit, sequential timestamps. The test still checks that API-error repair removes the earlier empty signed block. - `packages/memory/src/processors/observational-memory/__tests__/message-utils.test.ts`: Gives stored messages timestamps earlier than the live input. It expects observable order `memory-1`, `input-1`, `response-1`. It still checks that the synthetic continuation is excluded from observable messages. **Release notes** - `.changeset/memory-save-no-pause.md`: Adds a patch changeset for `@mastra/core`. It documents the removed pause, the same-millisecond ordering fix, and the queued-message case. ## Public API No exported or public declarations change. ## Scope 9 files changed. 571 lines added and 26 removed. ## Validation The PR author reports these results. This summary does not verify them. - Core unit lane (`--project unit:packages/core`, Node 24, 5 CPUs): 1,560 files and 25,295 tests passed. - Signals, message-list, and call-ID-reuse suites: 1,169 tests each passed across three runs. - `tsc --noEmit` and oxlint: clean. - Not verified: real multi-process pubsub (Unix socket or Redis), and stores other than core's in-memory and test stores. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com> Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
2788a6d959 |
feat(core): recover stopped workflow runs from a loop with one leader (#30281)
## Description
Restarts a default-engine workflow run whose instance crashed without
waiting for another instance to boot. `startWorkers()` now starts a
recovery loop on an instance that runs the orchestration worker, and one
instance among those that share a store runs its passes.
### The loop
Each pass applies the rule `restartAllActiveWorkflowRuns()` already uses
for default-engine runs: restart a `running` or `waiting` run once no
instance holds its run lease and `recovery.workflowGraceMs` passed since
the run or its lease last changed. The loop replaces the per-run recheck
timers the previous PR kept (`#scheduleWorkflowRecoveryRecheck`,
`#recheckWorkflowRun`); the durable-agent rechecks are unchanged.
The loop never touches evented runs. A redelivering broker recovers
them, and on other pubsubs the explicit `restartAllActiveWorkflowRuns()`
restarts them in the caller, as before. That call no longer joins a loop
pass for its evented part, so `startWorkers()` followed by the explicit
call still restarts evented runs on `EventEmitterPubSub`
(`evented/sleep-restart.test.ts` passes).
### Leader
One row, `::recovery-leader`, in the run-owners table, which gates the
loop's ticks only. Each tick of an instance tries a non-forced claim
until it gets the row, then keeps it: the lease helper renews it every
renew interval until `stopWorkers()` or `shutdown()` releases it. Only
the holder's loop lists runs; another instance's tick costs one refused
claim. When the leader dies, the row lapses after the lease TTL and the
next tick elsewhere takes it.
The leader saves listing cost only. Two restarts of one run are still
prevented by the run lease (`restart()` claims non-forced and throws
`WORKFLOW_RESTART_RUN_OWNED`).
An explicit `restartAllActiveWorkflowRuns()` never looks at the row. As
in the previous PR, each booting instance restarts its own stopped
default-engine runs (joining its own pass in flight), so another app's
workflows on the same store are recovered at its boot, and runs
recovered after a redeploy spread over the booting instances. Without
run fencing there is no leader and no loop, and the call restarts every
active run as before.
A failed probe, `getStore` or claim skips that tick and the loop keeps
going. A probe that answers "no fencing" stops the loop for good.
### Timings
- Interval: `recovery.workflowScanIntervalMs`, 60 s by default, each
wait up to 20 % shorter or longer, capped at 2^31 - 1 ms.
- A pass that saw a run in its grace period (and not live) moves the
next pass to that run's due time, no sooner than 1 s later and up to 20
% past it.
- A crashed instance's run is restarted about
`MASTRA_AGENT_THREAD_LEASE_TTL_MS` (15 s) plus `workflowGraceMs` (2 s)
after the crash, plus up to one interval for the next pass. When the
crashed instance was the leader, add up to one more interval for a
follower to take the row.
- `shutdown()` stops the loop when it starts, waits within
`drainTimeout` for the pass in flight and the restarts it handed out,
and releases the row in `stopWorkers()`.
### Config
```ts
const mastra = new Mastra({
recovery: { workflowScanIntervalMs: 30_000 },
});
```
`recovery.workflows: 'off'` turns the loop off. `workers: false`, or a
`MASTRA_WORKERS` filter without `orchestration`, runs no loop. An
instance that registers no default-engine workflow to recover never
claims the leader row.
### LibSQL thread state writes
`@mastra/libsql` thread state writes (`setState`, `deleteState`) now
take the client write lock the store's other writes take. Without it, on
a local database file, a thread state write that ran while the same
store held a write transaction open (a lease claim or renewal) failed
with `SQLITE_BUSY`; the leader's renewals made that much more likely.
### Known limits
- A process that calls `restartAllActiveWorkflowRuns()` but never
`startWorkers()` runs no loop and doesn't recheck the runs it left
alone. A run its boot call found live or in its grace period is left to
the loop of another instance, if any.
- A leader whose renewals fail for longer than the lease TTL can run
passes alongside the new leader for up to one renew interval after the
store answers again. The run lease still prevents a run from being
restarted twice.
- Between boots, the loop recovers only the workflows the leader
registers. Instances that register different workflows on one store get
loop recovery for the leader's workflows only, and the others' runs at
their next boot.
- A run the loop restarts executes on the leader.
- A `mastra worker` process calls `stopWorkers()` on `SIGTERM` and exits
without `shutdown()`, so its default-engine runs wait as long as a
crashed instance's.
- A run that another instance won between the pass's lease read and
`restart()` is looked at again only at the next pass, up to one interval
later.
- Rolling deploys are out of scope for this stack.
### Tests
New `recovery-loop.test.ts` (in-memory store, 600 ms lease TTL):
- a crashed leader's run is restarted by the follower with no boot,
within TTL + 2 intervals + 1.2 s
- instances started together run passes on one of them, and the leader
keeps the row while passes are further apart than the lease TTL
- the leader's `stopWorkers()` releases the row and the follower takes
over
- a tick that `stopWorkers()` overtook (on the first tick's store read,
or on a later tick's probe) claims no row, so another instance can lead
- a stopped run of a workflow only another app registers is restarted by
that app's boot call while a different instance leads, and the leader's
loop never lists that workflow
- next-pass timing table (no run, live run, run in grace, grace ending
within 1 s), timers unref'd
- no listing after `stopWorkers()`; `shutdown()` waits for a pass in
flight
- a loop on `startWorkers('orchestration')`
- the loop keeps going after a failed probe, leader claim, listing or
restart
- no listing and no claim with `workflows: 'off'` or without run fencing
The recheck cases of `restart-active-runs-ownership.test.ts` and
`restart-active-runs-rule.test.ts` are gone with the rechecks: the crash
case covers a crashed owner, the failure table covers transient errors,
and the existing shutdown and limiter cases cover draining and
`workflowConcurrency`. The LibSQL cross-process cases and the MCP
survivor cases boot like a server (`startWorkers()`, then the explicit
call) and recover through the loop.
Checks: core `src/workflows src/mastra src/agent/durable src/events`
(only the two `scheduler.test.ts` retry cases that fail outside UTC),
core typecheck, LibSQL cross-process, Postgres and LibSQL
`recovery-pass.test.ts`, MCP `server-tasks-background`.
## Related issue(s)
Part of #28712. Stack 4 of 4, on top of the recovery pass PR.
## 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)
- [x] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [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: Sometimes a workflow run stops when its server crashes. This
change adds a background check. One server regularly looks for stopped
runs and restarts them, so the work can finish without a manual restart.
## Overview
This change adds a workflow recovery loop to `@mastra/core`.
`startWorkers()` starts the loop. Among instances that share a store,
only the leader runs default-engine passes. A pass restarts
default-engine runs in `running` or `waiting` status when:
- no instance holds the run lease, and
- the configured grace period has elapsed.
The loop excludes evented runs. Explicit
`restartAllActiveWorkflowRuns()` calls handle evented runs and are not
leader-gated.
The change also updates LibSQL thread-state writes. `setState` and
`deleteState` now run through `withClientWriteLock`.
## Key changes
- `packages/core/src/mastra/index.ts`
- Adds `workflowScanIntervalMs` to `MastraRecoveryConfig`. The default
is 60000 ms. Values are capped at `2 ** 31 - 1`. A value of `-1`
resolves to the default.
- `startWorkers()` starts the loop when the selected workers handle
workflow events and recovery is enabled.
- When workflows use run fencing, the loop elects a leader through a
renewable lease. If fencing is unsupported, the loop stops.
- A pass records the earliest due time for runs still in their grace
period. The loop can then scan sooner.
- Failed lease reads leave runs for a later pass. Restart failures are
tracked per engine.
- Per-run recheck, retry, and backoff logic is removed.
- `stopWorkers()` stops the loop and releases the leader lease. Shutdown
waits for an in-flight pass.
- Explicit `restartAllActiveWorkflowRuns()` calls share an in-flight
default-engine pass. Broker-redelivered evented runs stay broker-owned,
except process-local scheduled runs.
- `packages/core/src/workflows/run-ownership.ts`
- `repeatAfterSettled` accepts a function for the delay and an optional
`immediately` flag.
- Signature changes from `(tick, intervalMs: number)` to `(tick,
intervalMs: number | (() => number), options?)`.
- `stores/libsql/src/storage/domains/thread-state/index.ts`
- `setState` and `deleteState` use `withClientWriteLock`. SQL,
arguments, and error handling are unchanged.
- Tests
- Adds `packages/core/src/mastra/recovery-loop.test.ts`. It covers
leadership, scheduling, shutdown, and failure handling. The file is
added to `vitest.isolated-tests.ts`.
- Removes three tests from `restart-active-runs-ownership.test.ts`.
- In `restart-active-runs-rule.test.ts`, removes one test and rewrites
the lease-read failure test to use the loop.
- Updates the recovery-defaults test, the MCP background server test,
and two LibSQL cross-process tests for the new scan interval.
- Adds a LibSQL thread-state test. It holds a write transaction open
during `setState` and `deleteState`.
- Documentation and changesets
- Updates the workers, server-adapter, workflow overview, and
`mastra-class` reference pages. Adds a "Recovery loop" section to the
workflow overview.
- Corrects the crash-recovery text in the workers page.
- Adds changesets for `@mastra/core` and `@mastra/libsql`.
## Public API changes
- Adds `workflowScanIntervalMs?: number` to `MastraRecoveryConfig`.
- Changes the signature of `repeatAfterSettled` in `run-ownership.ts`.
## Scope
- 19 files changed. 1028 lines added and 379 removed.
## Verification status
- Review findings: not available. No current review findings were
supplied.
- Author-reported checks: the PR objectives list core tests, core
typecheck, LibSQL cross-process tests, Postgres and LibSQL
`recovery-pass.test.ts`, and MCP `server-tasks-background`. These are
author reports. Results on the current head were not available for this
summary.
- Known failures: the author reports that two `scheduler.test.ts` retry
cases fail outside UTC.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
|
||
|
|
6d14d0edc4 |
feat(core): recover an agent resume whose process died (#30330)
## Description
`approveToolCall()`, `declineToolCall()`, and `resumeStream()` kept the
decision in the memory of the process handling the resume. If that
process died after claiming the run and before the run finished, the
decision was gone: the run stayed claimed, nothing in storage could
finish it, and the thread kept showing the approval as pending.
Every resume claim now writes `resumeClaimIntent` (the resume data and
the targeted `toolCallId`) in the same compare-and-set that stamps
`resumeClaimedAt`. The new `agent.recoverResume({ runId })` reads that
intent and finishes the run through the existing takeover rules, so it
only takes over an abandoned claim (judged by claim age or lease expiry,
as for any takeover).
- The replay keeps the original target. A resume without a `toolCallId`
resumes every parked call, so storing the data alone would apply one
answer to sibling calls.
- A recovery only takes over the exact claim whose intent it read. If a
newer resume claimed the run in between, the recovery rejects with
`AGENT_RESUME_ALREADY_CLAIMED`, so a stale decision never overrides a
newer one.
- `resumeStream(undefined, ...)` keeps its meaning. Recovery is opt-in
through `recoverResume()`, which rejects with
`AGENT_RESUME_NOTHING_TO_RECOVER` when no resume claimed the run.
- No adapter changes: every adapter merges `updateWorkflowState` options
into the stored run, the same way `resumeClaimedAt` is stored.
`DurableAgent` has its own claim and is not covered here.
Supersedes #30321, which stored the data without its target and applied
a recovered answer to every parked tool call.
## Related issue(s)
Fixes #30285
## Type of change
- [x] 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
- [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:** When a program stops during a user's approval, the approval
can be lost. This change saves the user's answer with the run. A new
recovery method can then finish the run without asking the user again.
## Overview
This change adds `agent.recoverResume({ runId })`. It replays a resume
that was claimed but not finished, for example after the process that
handled it stops.
## Behavior
- A resume claim stores `toolCallId` and `resumeData` in
`resumeClaimIntent`, together with `claimedAt`.
- The claim write sets `resumeClaimedAt` and `resumeClaimIntent` in one
update object. The code confirms that both fields are written together.
The storage layer's atomicity is not verified in this change.
- `recoverResume()` reads the stored intent. It takes over only the
claim whose `claimedAt` matches the snapshot's current
`resumeClaimedAt`.
- Recovery re-reads the run after it hands the run back. If the run no
longer carries the claim that recovery read, recovery fails with
`AGENT_RESUME_ALREADY_CLAIMED`. A newer pending claim can still be
displaced by the hand-back. That claim then fails in `start()`, and the
older decision does not run.
- If no resume has claimed the run, `recoverResume()` fails with
`AGENT_RESUME_NOTHING_TO_RECOVER`.
- `resumeStream(undefined, ...)` keeps its existing meaning. Recovery
runs only when a caller calls `recoverResume()`.
- The stored `toolCallId` targets one call. A recovered answer applies
only to that call, not to sibling parked calls.
- Recovery supports storage without run fencing for claims that never
started. This matches other takeovers.
## Documented takeover rules
The documentation states that recovery takes over a claim when either
condition holds:
- The claim was not started for 60 seconds.
- The run-fencing lease was not renewed for 60 seconds.
The documentation also notes that the resumed tool call runs again and
can repeat side effects.
## Changes by area
- **Core agent (`packages/core/src/agent/agent.ts`):** Adds
`recoverResume()`. Stores resume intent on each claim write. Passes
resume data into claim creation from `resumeStream()` and
`resumeGenerate()`. Adds the recovery path to the shared stream-resume
flow.
- **Until-idle helper
(`packages/core/src/agent/stream-until-idle.ts`):**
`runResumeStreamUntilIdle` accepts an optional `resume` callback for the
first turn. Without it, the function calls `agent.resumeStream` as
before. Continuation behavior is unchanged.
- **Types (`packages/core/src/workflows/types.ts`,
`packages/core/src/storage/types.ts`):** `WorkflowRunState` gains an
optional `resumeClaimIntent` with `claimedAt`, `toolCallId?`, and
`resumeData?`. `UpdateWorkflowStateOptions` accepts `resumeClaimIntent`.
- **Tests
(`packages/core/src/loop/test-utils/aimock/scenarios/resume-claim-after-crash.scenario.test.ts`):**
Adds parallel suspended tool-call support. Adds recovery tests for:
- Replaying a dead claimant's decision.
- Targeting only the answered call.
- Keeping a newer decision when recovery runs late.
- Refusing to recover a live claim.
- Returning `AGENT_RESUME_NOTHING_TO_RECOVER` when no decision exists.
- **Documentation and changeset:** Adds a section on recovering a
decision after a crash. The changeset declares a minor release for
`@mastra/core`.
## Scope and limits
- `DurableAgent` is not covered.
- No storage adapter changes are required.
- Public API addition: `recoverResume()` on `Agent`.
## Relation to linked issue
The linked issue asks that approval decisions survive a crash after a
claim. This change persists the decision with the claim and replays it
through `recoverResume()`. It does not add a separate
`getPendingResume(runId)` helper.
## Verification
- CI and test results: not available. No completed check results were
supplied for the current head.
- Review severity counts: not available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
|
||
|
|
7fd6830a26 |
fix(core): carry request context to a wake started by a claimed owner on another server (#29447)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
558b8b997c |
Simplify mastra factory dev startup output (#30344)
> Opened by @DSchau ## What The first `mastra factory dev` boot of a hello-world Factory printed about 20 lines before the ready banner: 8 `[factory:timing]` phase lines, 3 "Platform X integration initialized" lines with JSON, and 6 poller/reconcile "started" lines. Together they read as if every integration was loading, even with nothing connected. Under `mastra factory dev`, startup now looks like this: ``` ◇ Starting Mastra dev server... mastra 1.39.0 ready in 24050 ms │ Factory UI: http://localhost:4111 │ API: http://localhost:4111/api │ Deploy: mastra deploy ◯ watching for file changes... ◇ Intake: GitHub connected · Jira, Linear, GitLab, incident.io available ``` ## Changes - **Boot timing**: `timedPhase` and the `boot` total are off when `MASTRA_FACTORY_DEV=true`, unless `FACTORY_TIMING` or the new `MASTRA_FACTORY_DEBUG` is set. Deployed Factories still log them by default. - **Intake summary**: integrations get an optional `hasActiveConnections()`. Jira, GitLab and incident.io already had one. GitHub now checks for usable installations and Linear for connected workspaces. After finalize, factory dev prints a single connected/available line labelled "Intake" to match the Factory UI. The checks run in parallel and don't block boot, and a failed check shows as "status unknown". - **Init logs**: the "integration initialized" lines go through `logPlatformBootInfo`, which only prints when boot diagnostics are on. - **Worker logs**: the five poller/reconcile "started" logs moved from info to debug. - **CLI**: - `mastra factory dev --debug` passes `MASTRA_FACTORY_DEBUG=true` to the server, which brings back the timings and init details. - In factory mode the banner labels the root URL "Factory UI" instead of "Studio". ## Caveat The worker "started" logs go through the project's Mastra logger, which is INFO by default in dev. `--debug` doesn't change that logger's level, so those lines only come back if the project configures a debug-level logger. ## Test plan - [x] `timing.test.ts` checks that boot timing is on by default, quiet under factory dev, and back on with debug - [x] `startup-summary.test.ts` covers four cases: connected/available, none connected, failed check and no checkable integrations - [x] `dev.test.ts` checks that `MASTRA_FACTORY_DEBUG` is set only with `--debug` - [x] `dev-logger.test.ts` checks the Factory UI banner and that the Studio banner is unchanged - [x] Factory platform/worker/sandbox suites: 462 passed - [x] `tsc --noEmit` passes for factory and cli <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> **ELI5:** When you start a local Factory project, the terminal used to print many timing and setup messages. Those messages made it look like integrations were connected when they were not. Now the terminal shows only a short list of which integrations are connected. Detailed messages appear when you turn on debug mode. ## Overview This change reduces startup output for local `mastra factory dev`. Deployed Factories still log boot timing. The change also adds one integration connection summary at startup. The factory-mode banner now labels the root URL "Factory UI" instead of "Studio." ## Changes by area **Boot diagnostics gating** - `mastracode/factory/src/timing.ts` adds `bootDiagnosticsEnabled`. Diagnostics are enabled when any of these is true: - `FACTORY_TIMING` is `1`, `true`, or `yes`. - `MASTRA_FACTORY_DEV` is not `true`. This is the deployed case. - `MASTRA_FACTORY_DEBUG` is `1` or `true`. - `timedPhase` runs its callback without logging when diagnostics are disabled. The function signature is unchanged. - `mastracode/factory/src/factory.ts` logs boot timing in `finalize()` only when diagnostics are enabled and a start time exists. - `mastracode/factory/src/integrations/github/sandbox.ts` gates command-attempt timing on diagnostics in addition to the existing phase check. **Log level changes** - The worker "started" messages move from info to debug in: - `github/reconcile-worker.ts` - `issue-reconcile-worker.ts` - `platform/github/event-worker.ts` - `platform/gitlab/event-worker.ts` - `platform/linear/event-worker.ts` - These messages appear only when the project logger runs at debug level. The `--debug` flag does not change the logger level. **Platform boot logging** - `platform/api-client.ts` adds `logPlatformBootInfo`. It writes an info-level log only when diagnostics are enabled. - The GitHub, Jira, and Linear platform integrations use `logPlatformBootInfo` for initialization messages. **Connection checks and integration summary** - `integrations/base.ts` adds an optional `hasActiveConnections(): Promise<boolean>` to `FactoryIntegration`. - `platform/github/integration.ts` implements `hasActiveConnections()`. It returns `true` when at least one installation is usable and not suspended. - `platform/linear/integration.ts` implements `hasActiveConnections()`. It returns `true` when at least one connected Linear workspace is listed. - Jira, GitLab, and incident.io already had connection checks. This change does not modify them. - `integrations/startup-summary.ts` is new. It adds: - `describeIntegrations()`. It checks only integrations with `hasActiveConnections`, runs the checks concurrently, and sorts each result into connected, available, or status unknown. A check that throws is reported as status unknown. It returns `undefined` when no integration can report connections. - `logIntegrationSummary()`. It logs the summary only when `describeIntegrations()` returns a value. - `factory.ts` calls `logIntegrationSummary` in `finalize()` only when `MASTRA_FACTORY_DEV` is `true`. - A follow-up commit renames the summary label to "Intake" to match Factory UI terms. **CLI** - `packages/cli/src/commands/dev/dev.ts` adds `debug` to `StartOptions`. When both `factory` and `debug` are set, the child server receives `MASTRA_FACTORY_DEBUG=true`. The ready logger also receives the `factory` flag. - `packages/cli/src/utils/dev-logger.ts` adds an optional `factory` parameter to `DevLogger.ready`. In factory mode, the root URL is labeled "Factory UI:" and the Studio entry is omitted. The API and Deploy entries remain. Rows align to the widest label. **Changeset** - `.changeset/quiet-factory-boot.md` adds patch releases for `@mastra/factory` and `mastra`. It describes the new startup output and the `--debug` behavior. ## Tests The new or updated tests cover: - `timing.test.ts`: default, factory-dev, and debug timing behavior. - `startup-summary.test.ts`: four connection-summary cases. These are connected and available providers, no connected provider, a failed check reported as unknown, and no report when no integration can report connections. - `dev.test.ts`: `MASTRA_FACTORY_DEBUG` behavior in factory mode. - `dev-logger.test.ts`: Factory UI and Studio banners. The author reports these results. This summary does not verify them: - Factory platform, worker, and sandbox suites: 462 passed. - `tsc --noEmit` passes for factory and CLI. ## Scope 21 files changed. 232 lines added and 19 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> |
||
|
|
70f3eba5ec |
docs: fix inaccurate examples and defaults across workflows, processors, Studio, workers, sandbox, observability, channels and Next.js guide (#30331) |