mirror of
https://github.com/mastra-ai/mastra.git
synced 2026-11-17 08:44:46 +00:00
2,583 commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
d60ba71be0 | chore: version - exit prerelease mode | ||
|
|
5c87442ed7 |
chore: version packages (alpha) (#30203)
This PR was opened by the [Changesets release](https://github.com/changesets/action) GitHub action. When you're ready to do a release, you can merge this and publish to npm yourself or [setup this action to publish automatically](https://github.com/changesets/action#with-publishing). If you're not ready to do a release yet, that's fine, whenever you add more changesets to main, this PR will be updated. ⚠️⚠️⚠️⚠️⚠️⚠️ `main` is currently in **pre mode** so this branch has prereleases rather than normal releases. If you want to exit prereleases, run `changeset pre exit` on `main`. ⚠️⚠️⚠️⚠️⚠️⚠️ # Releases > The changelog information of each package has been omitted from this message, as the content exceeds the size limit. ## @mastra/auth-auth0@1.3.0-alpha.0 ## @mastra/auth-clerk@1.4.0-alpha.0 ## @mastra/auth-okta@0.3.0-alpha.0 ## @mastra/auth-supabase@1.2.0-alpha.0 ## @mastra/client-js@1.60.0-alpha.13 ## @mastra/auth@1.2.0-alpha.0 ## @mastra/core@1.83.0-alpha.13 ## @mastra/playground-ui@69.0.0-alpha.15 ## @mastra/rag@2.8.0-alpha.3 ## @mastra/server@1.83.0-alpha.13 ## @mastra/server-adapters-test-suite@0.3.0-alpha.5 ## @mastra/auth-better-auth@1.1.11-alpha.2 ## @mastra/auth-cloud@1.2.9-alpha.0 ## @mastra/auth-neon@0.3.6-alpha.1 ## @mastra/auth-workos@1.6.9-alpha.0 ## @mastra/discord@1.3.4-alpha.0 ## @mastra/react@1.15.0-alpha.13 ## @mastra/deployer-cloud@1.83.0-alpha.13 ## @mastra/deployer-cloudflare@1.2.42-alpha.3 ## @mastra/deployer-netlify@1.2.42-alpha.1 ## @mastra/deployer-sandbox@0.3.27-alpha.1 ## @mastra/deployer-vercel@1.2.42-alpha.1 ## @mastra/longmemeval@1.1.42-alpha.13 ## @mastra/opencode@0.1.42-alpha.13 ## @mastra/factory@0.28.0-alpha.15 ## create-factory@0.4.3-alpha.15 ## @mastra/code-sdk@1.19.0-alpha.15 ## mastracode@0.50.0-alpha.14 ## @mastra/agent-builder@1.2.1-alpha.5 ## mastra@1.39.0-alpha.15 ## @mastra/connect@1.4.0-alpha.6 ## @mastra/deployer@1.83.0-alpha.13 ## @mastra/editor@0.17.1-alpha.7 ## @mastra/mcp@2.9.0-alpha.5 ## @mastra/mcp-docs-server@1.3.13-alpha.17 ## @mastra/memory@1.41.1-alpha.5 ## @mastra/schema-compat@1.4.0-alpha.2 ## @mastra/elysia@0.1.23-alpha.13 ## @mastra/express@1.5.27-alpha.13 ## @mastra/fastify@1.5.27-alpha.13 ## @mastra/hono@1.7.25-alpha.13 ## @mastra/koa@1.7.27-alpha.13 ## @mastra/nestjs@0.3.0-alpha.13 ## @mastra/next@0.2.41-alpha.13 ## @mastra/tanstack-start@0.2.41-alpha.13 ## @mastra/voice-google-gemini-live@0.14.19-alpha.2 ## @mastra/voice-openai-realtime@0.14.9-alpha.3 ## @mastra/voice-xai-realtime@0.2.18-alpha.2 ## @mastra/inngest@1.11.2-alpha.9 ## @mastra/temporal@0.6.0-alpha.13 ## create-mastra@1.39.0-alpha.15 ## @internal/playground@1.39.0-alpha.15 Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
ef2c03fc12 |
test(factory): fix Triage switch-credentials test (#30234)
## Summary
`dispatcher-switch-credentials.scenario.test.ts > moves a card by intake
route after switching its bound session as the session owner` fails on
every full `UNIT Test (Shard 1)` run on `main`. This PR points the
test's setup at a Work board that has a Triage column. Only the test
changes.
## Root cause
- [#29901](https://github.com/mastra-ai/mastra/pull/29901) (merged Nov
10, 22:12 UTC) removed Triage from the default Work board. The default
phases are now `intake, planning, execute, pr-review, done, canceled`.
Tests that need Triage use `createTriageWorkRegistry()` from
`boards/test-utils.ts`.
- [#30179](https://github.com/mastra-ai/mastra/pull/30179) added this
scenario on a branch based on `
|
||
|
|
4cc8167698 |
feat(factory-ui): one-page onboarding that explains every dead end (#30173)
**─────── TLDR ───────** > Factory onboarding becomes one page with Codebase, Work, Accounts and Model sections, and every dead end along the way now says why and offers a way out — including the GitHub App installed on a personal account shared by a team. ## Behavior **Setup flow** ├─ **was** a multi-step wizard with a separate review step └─ **now** one page; finished sections collapse to a summary with Change, Accounts asks who pays for model usage, Model shows the accounts that answer needs, Create factory sits under the cards **GitHub App on a personal account, org with 2+ members** ├─ **was** "GitHub App installed" success toast, then the same Connect button again, forever └─ **now** warning in Codebase: "Factory can’t use this GitHub installation", explains personal accounts only work for one-member orgs (pending invitations count), offers Choose another account and Refresh, can't be dismissed; driven by Platform's `hiddenPersonalInstallReason`, now passed through `/web/github/status` as `reason: 'personal_install_hidden'`, so it shows on every visit, not only right after the install. Another usable installation still reports `ready` Related: #28624 adds Share with this factory for this case. That needs mastra-ai/platform#3953 and #3983, both still open, so it stays a draft and rebases onto this PR. **Install refused by Platform** ├─ **was** generic "GitHub connection failed" toast └─ **now** inline reason with its real fix: preexisting install → the organization's Settings → General page in Platform (`/orgs/:orgId/settings/general`), where an admin chooses Refresh accounts, then Refresh; Mastra account linked to another GitHub user, or not signed in to Platform → Platform, then Connect GitHub again; Factory account that isn't a Mastra account → Sign out; already-used link → info notice with Refresh; other refusals → Connect GitHub again **GitHub callback while GitLab is connected or drafted** ├─ **was** landed on the GitLab tab with a GitHub notice above GitLab repos, and dismissing the notice or clicking Connect flipped the tab to GitLab └─ **now** the opening tab is decided once: GitHub for a callback, else the drafted repo's host, else the connected one; it doesn't move until the user switches. Choosing a repository clears the GitHub result, so Change codebase reopens on the chosen repo's host (before, a GitLab pick reopened on GitHub with Continue disabled) **Install reported, status finds nothing usable** ├─ **was** always blamed a personal account, even when status itself failed (5xx/401) └─ **now** neutral "Factory can’t see this GitHub installation yet" only when status really says `not_connected`; a failed status shows Retry instead **GitHub status request fails / session expired** ├─ **was** looked like "not connected" and offered a Connect that would fail └─ **now** "Couldn't load GitHub status." with Retry; a 401 offers Sign in, which returns to `/onboarding`; Retry shows a spinner while it runs **Back from GitHub without finishing** ├─ **was** Connect stayed stuck on "Redirecting…" (bfcache restore) └─ **now** button resets on pageshow **No repositories / refresh fails** ├─ **was** empty list blamed repository access even when the load failed; refresh errors were silent └─ **now** empty list points to Manage access, load and refresh failures show their error with Retry, a pending approval request stays up until new repos appear **Create factory disabled** ├─ **was** greyed out with no reason └─ **now** a line above it names, per account, whether a provider or a model is missing ("Connect your account for sessions to create your factory."), linked with aria-describedby; on mobile it lives in the pinned bar **Cancelled API key or sign-in dialog** ├─ **was** the cancelled provider stayed selected, dropping the working one and disabling Create └─ **now** a provider is selected only once its key or sign-in succeeds **Saved provider no longer usable** ├─ **was** a saved provider without a model, or one deleted from the list, reopened as a blank picker └─ **now** says the connection changed, or that the provider is no longer available, and asks to choose another **Member locked to personal accounts adds a custom provider** ├─ **was** the new provider unlocked the company account and the answer silently flipped to Company account └─ **now** the personal-accounts answer is saved with the choice; disabled providers say only an admin can connect them **Member, gateway offered, company provider already connected** ├─ **was** opened on a gateway they can't connect └─ **new** opens on Your own provider; the gateway button explains only an admin can connect it **Sign out from onboarding** └─ **new** account menu (themes + Sign out) and the `person_not_platform_user` recovery share one sign-out that clears the saved onboarding draft **Personal default still loading** ├─ **was** the personal catalog could arrive first, so Create offered a fallback model and would overwrite the saved personal default └─ **now** no model is suggested, and Create stays off, until the personal default answers **Account answer changed during a personal gateway connect** ├─ **was** switching to hybrid mid-connect let the late result select the gateway on a lane that can't use it └─ **now** the account answer is locked until the connection settles **Linear status down** ├─ **was** the Work summary said "Set up later" └─ **now** it says "Couldn't check connections" **Hybrid Model summary** ├─ **was** the collapsed row showed only the company model └─ **now** shows both, work then sessions ## Decisions 1. **Personal-account warning is status-driven.** Platform reports why it withheld a personal install, so the notice keys off `reason: 'personal_install_hidden'` and persists across visits; the post-install guess uses neutral copy because `connected: false` alone doesn't prove the cause. 2. **Onboarding shows GitHub results inline, never as toasts.** The callback is read once into page state (`callbackResult`), so the notice survives re-renders and has room for a reason plus an action. A usable install gets no message: the repository list is the feedback. Settings keeps its toasts. 3. **Select a provider only after its credential succeeds.** Cancelling must never cost the user a provider that already worked. ## Not verified - [ ] The Slack thread about shared personal accounts couldn't be read; the scenario was reconstructed from Platform's `github-app.ts` - [ ] The `/orgs/:orgId/settings/general` link: Platform's main routes it to `General`, which shows Refresh accounts to writers outside customer cloud; not clicked through live - [ ] Real Platform round trip for each `github_app_error` code (verified with mocked callbacks only) - [ ] Direct GitHub mode: it never reads `?github=error`, so refusals there still show nothing (server follow-up) - [ ] GitLab / Jira / incident.io connect failures remain toast-only (follow-up) - [ ] A pending approval request notice is lost on reload (the callback is read from the URL once) - [ ] Create errors still use client strings like "Failed to create Factory (403)"; server message not surfaced (follow-up) ## Diff - **source** ████████████████████ +3315 −1802 - **tests** ██████████████ +2268 −1083 - **changeset** █ +17 −0 - **docs** █ +9 −5 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ELI5: Factory setup used to be a multi-step wizard. Now it is one page with four sections: Codebase, Work, Accounts, and Model. Each section explains what is wrong when setup cannot continue, and it offers a fix. ## Summary This pull request replaces the multi-step Factory onboarding wizard with a single page. The page has four sections: Codebase, Work, Accounts, and Model. **Onboarding page and flow** - `OnboardingPage` reads the GitHub callback result once and renders `GitHubAppCallbackHandler` in inline mode. It passes the result to `EmptyFactoryState`. - `FactoryOnboarding` renders the single-page flow. It restores a persisted step and draft, and it forces factory model scope for local setups. - `onboardingSteps.ts` defines the section model. Steps are `vcs`, `project-management`, and `model`. Several step helpers are removed. - `onboardingFlow.ts` changes the draft shape. It adds `workConfirmed`, adds `onboardingCreateReadiness`, and renames `OnboardingModelChoice` to `OnboardingDraftModel`. - `createBlockedReason.ts` returns the reason that creation is blocked. **Removed components** - The wizard steps are deleted: `InitialFactoryStep`, `MastraGatewayOption`, `ModelProviderFactoryStep`, `ModelProviderPicker`, `PersonalProviderFactoryStep`, `OnboardingProgress`, `OnboardingReviewRow`, `OnboardingReviewStep`, `OnboardingSetupStep`, and `OnboardingWorkReviewRow`. - Their MSW test file `ModelProviderFactoryStep.msw.test.tsx` is deleted. **GitHub callback handling** - `GitHubAppCallbackHandler.tsx` exports `GitHubAppCallbackResult` and `callbackResult`. It has an `inline` mode that suppresses toasts. - `githubCallbackRecovery.ts` maps callback codes to a Platform page and a next action. It also reports whether the callback awaits access. **New onboarding components** (under `onboarding/`) - Layout and rows: `OnboardingStepCard`, `OnboardingStepRow`, `OnboardingCodebaseRow`, `OnboardingWorkRow`, `OnboardingWorkDoneRow`, `OnboardingModelRow`, `OnboardingAccountsRow`, `OnboardingInset`, `OnboardingPageAction`, `OnboardingSlot`, `OnboardingSearchInset`. - Account and model: `OnboardingModelSection`, `OnboardingAccountLanes`, `OnboardingAccountLane`, `OnboardingAccountHeading`, `OnboardingLaneProvider`, `OnboardingLaneStatus`, `OnboardingProviderPicker`, `OnboardingProviderOptions`, `OnboardingProviderOption`, `OnboardingProviderSummary`, `OnboardingScopeChoice`, `OnboardingConnectGatewayButton`, `OnboardingGatewaySummary`. - Source control: `OnboardingGithubHostRow`, `OnboardingGitlabHostRow`, `OnboardingHostRecoveryAction`, `OnboardingGithubNotice`, `OnboardingRepositoryRows`, `OnboardingRepositoryError`. - Other: `OnboardingCreateNotice`, `OnboardingAccountMenu`, `OnboardingAccountsPreview` (now takes `showModels`). **Hooks and services** - `useAccountSource`, `useOnboardingModelLane`, and `useOnboardingModelSetup` manage account source, model lanes, and the combined setup. - `useProviderConnection` adds `selectedProviderId`, `retrying`, and a selection-change callback. `closeKeyDialog` now receives `saved`. - `useProviderModels` adds `retrying` and gates queries on connection state. - `useWorkSourceConnectionsStatus` adds `isPending` and `isError`. - `sourceControlHosts.ts` adds host types and unavailable-reason helpers. - `onboardingSignOut.ts` adds `signOutOfOnboarding`. - `accountName.ts` adds `accountName`. `SidebarSettingsLink` uses it. **Settings and other UI** - `AddApiKeyDialog` and `ProviderConnectionDialogs` pass `saved: boolean` to `onClose`. - `VcsFactoryStep` adds GitHub callback props and a GitHub/GitLab segmented control. It adds repository refresh and retry handling. - `ProjectManagementFactoryStep` uses the new step card. - `FactoryDefaultModelForm` takes `scope` and `lane` props. - `OnboardingConnectionRow` replaces `connected` and `compact` with `tone`. - `onboarding.css` adds fold and card animation. `onboarding-preview.css` removes the mobile responsive layout. **Platform personal-install status (`mastracode/factory`)** - `integration.ts` adds the `personal_install_hidden` status. It reads `hiddenPersonalInstallReason` from Platform and treats `null` as absent. - Status is `personal_install_hidden` when no usable installation exists and Platform reports a hidden personal installation. A usable installation yields `ready`. - `integration.test.ts` adds parameterized tests for both cases. - The changeset `factory-github-personal-install-status.md` documents this as a patch release for `@mastra/factory`. - The changeset `factory-onboarding-one-page.md` documents the one-page onboarding as a `mastra` patch. **Tests** - New `OnboardingModelSection.msw.test.tsx` (1060 lines) covers provider, gateway, custom-provider, and admin cases. - `EmptyFactoryState.msw.test.tsx`, `VcsFactoryStep.msw.test.tsx`, and `GitHubAppCallbackHandler.msw.test.tsx` are rewritten for the new flow. - Shared fixture `modelSection.tsx` adds `renderModelSection` and provider helpers. - New `onboardingSteps.test.ts` covers step selection and restoration. **Not verified** - The PR description lists these items as not verified or deferred: - Live Platform round trips for each `github_app_error` code. - Direct GitHub mode refusals. - Failures for other integrations. - Approval notices after reload. - Server messages for create errors. - The Settings link to the Refresh accounts button was not tested live. The author cites Platform routing as the basis for the link. **Author-reported checks** - The author reports factory-ui typecheck and lint as clean. - The author reports 671/671 unit tests passing, and 628/628 for workspaces, settings, and root-route MSW tests. - These results come from the PR comments. This summary did not run them. **Review scope** - 96 files changed. 5609 lines added and 2890 removed, from the pull request diff. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local> |
||
|
|
cac0f555ff |
fix(factory-ui): explain failed board loads and type the sidebar's status rows (#29983)
## Description **─────── TLDR ───────** > When the board list can't load, the sidebar now shows a properly typed error row with a Retry button instead of a big unstyled sentence. The page shows the design system's error illustration for what actually went wrong, plus a way to recover. The Boards and Phases sidebar sections rendered "Unable to load boards." and "Unable to load phases." as bare `<li>`/`<p>` text with no text role, so they fell back to the browser's default 16px type. The board pages showed a lone ⊘ with no reason and no action. The app's query client also sets `retry: false` and `refetchOnWindowFocus: false`, so a single failed request (a 500, a deploy restart, a dropped connection) stayed on screen until a full reload. ### Before / after **Board page, catalog request returns 500** | Before | After | |---|---| |  |  | **Board settings, board request returns 500** | Before | After | |---|---| |  |  | **Each failure gets its own illustration and next step** (unreachable · 404 · 401 · 429)  <details><summary>Light theme, and the empty catalog</summary>   </details> ### Behavior changed the Boards and Phases sidebar sections when loading fails ├─ **was** — "Unable to load boards." in the browser's default type, nothing to click └─ **now** — "Couldn’t load boards" in the nav-row type, aligned under the section header, with a Retry icon in the header-action column the board page, the board landing page and board settings when loading fails ├─ **was** — ⊘ and "Unable to load boards.", only a reload helps └─ **now** — the `EmptyState` illustration for the failure, one sentence about it, and Try again (Sign in for an expired session) which illustration └─ **new** — server unreachable → `disconnected` · 401 → `locked` + Sign in · 403/404 → `not-a-member` · 429 → `rate-limited` · anything else → `server-error` "No boards installed." ├─ **was** — bare text in the sidebar and at the top of the landing page └─ **now** — a muted nav-row note in the sidebar, a centered `EmptyState` on the page the Sessions section's error and empty rows └─ **now** — the same shared rows: `meta` → `label` type, Retry as an icon, aligned with the header; still no alert role ### Decisions - **the "Loading…" in the default face**: nothing visible renders that way today. Every sidebar loading state is `SidebarNavigationSkeleton`, and the remaining "Loading…" strings already use `Txt`. The bare-text rows were the error and empty states, and this PR fixes all of them (boards, phases, landing). - **no lint rule for bare text**: a rule can't tell a bare `<li>Unable…</li>` apart from a `<span>` that a Button or menu item styles. `SidebarLoadError` and `SidebarEmptyNote` are the guard instead. - **art chosen by HTTP status**: follows the pairings in the `EmptyState` "error illustrations" story. - **404 → `not-a-member`**: the catalog only returns 404 when the factory isn't in the caller's organization, and there is no "not found" illustration. - **Retry is an icon in the sidebar**: a labelled button truncated "Couldn’t load boa…" at the default sidebar width. The icon matches the section header's `+` and filter buttons, and the accessible name stays "Retry". - **the server's message isn't shown**: 5xx bodies are "Internal Server Error" or machine codes, so the copy is written per failure kind instead. - **Sessions keeps failing quietly**: Boards and Phases already rendered their failure as `role="alert"`, and they keep it. Sessions never did, so the shared row takes `announce={false}` there instead of adding an alert to every page. ### Shape changed new in `@internal/factory-ui` (`src/ui/ui/LoadErrorState.tsx`) `LoadErrorState` · `SidebarLoadError` · `SidebarEmptyNote` · `describeLoadFailure` ### Verified - screenshots are from the real app on Vite in Chromium, with Playwright fulfilling the API and forcing the board catalog to fail - the 8 new MSW tests fail against `main` and pass here; they cover retry recovery in the sidebar and on the page, plus each failure kind's copy, art and action - `typecheck`, `oxlint` and `prettier` pass on the changed files - full factory-ui MSW suite: all green except 9 tests in `AppStartup.msw.test.tsx` (8) and `ThreadPageTeammateSession.msw.test.tsx` (1), which fail the same way on `main` in the same environment and aren't touched here ### Not verified - [ ] the 401 → `/signin` round trip with web auth enabled (screens and tests run with auth off) ## Related issue(s) No issue. Found from a screenshot of the sidebar's "Unable to load boards." state. ## Type of change - [x] Bug fix (non-breaking change that fixes an issue) - [ ] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update - [ ] Code refactoring - [ ] Performance improvement - [x] Test update ## Checklist - [ ] I have linked the related issue(s) in the description above - [ ] I have made corresponding changes to the documentation (if applicable) - [x] I have added tests that prove my fix is effective or that my feature works - [ ] I have addressed all Coderabbit comments on this PR --- _Generated by [Claude Code](https://claude.ai/code/session_01D9qJ4NKnF4weVgHKMV6zja)_ --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local> |
||
|
|
4d8a09ed37 |
fix(factory): switch bound sessions onto card threads as the session owner (#30179)
## Summary
When Factory sends work to a bound session that is on a different
thread, the dispatcher switches the session onto the card's thread
first. That switch ran before the dispatcher built the owner's request
context, so the thread subscription loaded memory with no user, and the
tenant credential gate failed with:
`Tenant model credential policy could not be resolved: the request has
no authenticated user` (`reason: 'missing-user-context'`, `hasUser:
false`)
Shipyard logs show this on the `Agent.getMemory → subscribeToThread →
#switch → prepareCredentialTenant` stack for board-driven cards.
The dispatcher now passes the binding's owner (`startedBy`, `orgId` from
Factory's own rows, not client-writable thread metadata) into the
switch, the same identity the turn already runs as. Credential checks
are unchanged.
## Not covered
- The webhook subscription-session switch
(`integrations/subscription-session.ts`) makes the same context-less
switch.
- Cold `resumeStream` resumes without a user are a separate bug.
## Test plan
- New `dispatcher-switch-credentials.scenario.test.ts`: real dispatcher,
controller, session and user-requiring credential resolver. Fails on
main with the exact production diagnostic, passes with the fix.
- `dispatcher.test.ts` now requires the switch to carry the owner user.
- `src/rules`: 770/770 pass. oxlint/oxfmt clean.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
**ELI5:** When a Factory card starts work in a chat session, the system
must act as the user who started that work. This change makes the
session switch to the card's thread run as that user. Before, the switch
ran with no user, so the thread's memory could not load and the card
never started.
## Summary
This change makes `FactoryDecisionDispatcher` switch a bound session to
its card thread with the session owner's identity. The owner is
`startedBy` and `orgId` from the Factory binding record, not from
client-writable thread metadata.
### Changes
- **`mastracode/factory/src/rules/dispatcher.ts`** (+27/-17 in the raw
summary; the diff shows 44 changed lines)
- Replaces `ThreadSwitchSession` with `SessionOwner` (`userId`,
`orgId`).
- `#requireSession(binding, owner)` requires an owner. It passes the
owner to `#findSession`, which passes it to `#switchThread`.
- `#switchThread` takes a `BoundDispatcherSession`. When an owner is
given, it builds a request context with `factoryRequestContext`. It then
calls `thread.switch({ threadId, requestContext })`. Without an owner,
it sends `requestContext: undefined`.
- The skill, message, notification, activity, and pending-start dispatch
paths pass `{ userId: startedBy, orgId: record.orgId }` to
`#requireSession`. The path that calls `#switchThread` directly also
passes the owner.
- `#primeCredentials` calls are unchanged.
- **`mastracode/factory/src/rules/dispatcher.test.ts`** (+6/-2)
- The session stub's `thread.switch` input type accepts an optional
`RequestContext`.
- The session-recovery test now asserts that `thread.switch` receives
`requestContext`. It also asserts that the context user is `{ workosId:
'user-1', organizationId: 'org-1' }`.
- **`.changeset/dispatcher-switch-owner-context.md`** (+5)
- Adds a patch changeset for `@mastra/factory`.
-
**`mastracode/factory/src/rules/dispatcher-switch-credentials.scenario.test.ts`**
(new, +160)
- Registers the tenant credential resolver and wraps the agent memory
with credential preparation. The memory wrapper records the request
context user.
- The raw summary describes assertions that the deferred decision
succeeds, the session returns to the card thread, and memory receives
the session owner. I read only the first 80 lines of this file, so I did
not verify those assertions.
### Not covered
- The context-less switch in `integrations/subscription-session.ts` is
not changed.
- Cold `resumeStream` resumes without a user are not changed.
### Verification
- Diff stats confirm 4 files changed, 198 insertions, and 19 deletions.
- The author reports that the new scenario test fails on `main` and
passes with this change. I did not run it.
- The author reports that `src/rules` passes 770 of 770 tests and that
oxlint and oxfmt are clean. I did not run these checks.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
|
||
|
|
171e27355f |
fix(code-sdk): fire SessionStart again when a session binds a different thread (#30223)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
6dbc650bed |
fix(factory): only return Jira issues from the project in the issue reference (#29326)
`GET /web/jira/issues/:identifier` checks that the project encoded in `issueRef` is bound to the Factory project, then fetches the issue by key. It never checked that the issue actually lives in that project. A hand-built `issueRef` pairing a bound project ID with an issue key from an unbound project returned that issue's title, description and comments. `#findIssue` now treats an issue whose `fields.project.id` doesn't match the referenced project (from the issue reference or the source ID) as not found. The route already turns that into a 404. Added an integration test for both the encoded-reference and sourceId paths. Factory Jira tests pass (63), and `tsc` and lint are clean. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 The Jira endpoint could return an issue from a project outside the source’s scope. This change checks that the issue belongs to the expected project and rejects references that conflict with the source. ## Changes - `#findIssue` returns `null` when an issue reference conflicts with the source connection or project. - `#findIssue` returns `null` when the fetched issue’s project ID does not match the project in the issue reference or `sourceId`. - Added tests for mismatched projects and conflicting references. - Added a patch changeset for `@mastra/factory`. Test, type-check, and lint results were not available. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
9a0c3e05ff |
perf(factory): skip the card read for workers nobody follows (#29992)
**─────── TLDR ───────** > Board-started workers that nobody follows no longer load their work item card on every agent step, cutting that step's storage cost by about a third. The sessions state processor runs on every agent step. For a worker session it loaded the card first, then counted followers, and returned nothing when there were none — the usual case for board-started workers. It now counts followers first and only reads the card when it has a line to show. ### Behavior changed a worker step, nobody follows its item ├─ **was** — binding, card (board item + work item + sources), subscribers read └─ **now** — binding and subscribers read; no card read, still no signal a worker step, someone follows its item └─ **unchanged** — same reads, same "Working on #7 as work…" line ### Gain Local benchmark: 2,200 cards, 150 bound workers with no followers, 2,000 steps through `computeStateSignal`. > ██████████████████ **Postgres before** `1217µs wall · 327µs cpu` > █████████████ **Postgres after** `872µs wall · 223µs cpu` > ██████ **LibSQL before** `413µs wall · 421µs cpu` > ████ **LibSQL after** `281µs wall · 287µs cpu` ### Decisions - **no cross-step cache of binding or subscribers** — another server process can follow or revoke without telling this one; a cache would show stale lines - **scope resolution left alone** — it is shared auth code and still reads session, run binding and project each step; that is most of the remaining cost ### Not verified - [ ] the gain in production — the 16% self time on `#workerLine` in the Shipyard profile is far above this ~0.3ms per step, so this PR is a part of the stall at most - [ ] the 11% LibSQL row iteration in that profile — Shipyard's factory storage is Postgres, and no LibSQL path in factory is hit at runtime with `DATABASE_URL` set - [ ] the 9% spawn — the closest candidate is the per-run `git rev-parse` and binary probe in the SDK's dynamic instructions, outside this package --- > ██████████████████ **tests** `+15` — 68% of the additions > ██████ **changeset** `+5` > ██ **source** `+2 −2` — reordered, net 0 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ELI5: When a worker runs for a board item that nobody follows, the system used to load the item card and then discard it. Now it checks for followers first and skips that read when none exist. The output stays the same. ## Summary This PR changes `FactorySessionsStateProcessor` in `@mastra/factory` so that it checks for work-item followers before it loads the work item card. Workers with no followers now return `null` without reading the card. Workers with followers still load the card and produce the "Working on ... as ... Reports go to N following sessions" line. ## Changes - `mastracode/factory/src/tools/sessions-state-processor.ts` (+2/-2): In `#workerLine`, the `listWorkItemSubscribers` call and the follower count now run before `workItems.getForProject`. The `getForProject` call moves below the `following === 0` early return. The comment is updated to say the card read is skipped. - `mastracode/factory/src/tools/sessions-state-processor.test.ts` (+15): Adds a test for a worker with a bound item and no followers. The test spies on storage `findOne` and `findMany` calls. It checks that the step emits no signal and that neither query reads the board-item collection. The test imports `FACTORY_BOARD_ITEMS_SCHEMA`. - `.changeset/full-dogs-try.md` (+5): Adds a patch changeset for `@mastra/factory`. The note says per-step database reads drop for board-started sessions with no followers, by about a third. ## Diff size 3 files changed, 22 lines added, 2 lines removed. ## Benchmarks The author reports local results for 2,200 cards, 150 bound workers without followers, and 2,000 `computeStateSignal` steps: - Postgres: 1217 µs wall / 327 µs CPU before, 872 µs wall / 223 µs CPU after. - LibSQL: 413 µs wall / 421 µs CPU before, 281 µs wall / 287 µs CPU after. The author did not verify production gains, the Shipyard profile's LibSQL row iteration, or spawn cost. The description says factory storage uses Postgres in Shipyard, and the closest spawn candidate lies outside this package. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local> Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
8d4abc4f88 |
chore(deps): Vanta 2026-11-12 — raise undici to 8.12.4 / 7.30.2 (#30205) | ||
|
|
6ad8e7eb9d |
feat(ui): one settings layout across Studio, Factory and Platform (#29400)
## Description Settings pages in Studio, Factory and Platform each had their own layout: different widths, section headers with buttons, add rows at the bottom of lists, fields starting at different x positions. This gives all three one layout, built from reusable Playground UI components: - A 640px page column with the title above the sections. - Each section is a dimmed title above one borderless card. The card owns all row spacing (14px padding, inset hairlines), so rows carry no padding of their own. - Settings rows: label and description on the left, control on the right. Text fields share one width, selects hug their value up to that width, switches and buttons keep their size. - Lists: a count and the list's action in a header row at the top of the card, one empty row (text plus the same action) when there's nothing in it, and `SettingsItem` rows with one icon tile size, so every list lines up. - Input, InputGroup and select values use the regular-weight `text-body-sm`, like Textarea. This is the Playground UI, Studio and Factory half. The Platform half, mastra-ai/platform#4174, pins a snapshot of this branch. ## Before / After Every settings page in Studio and Factory, `origin/main` on the left and this branch on the right (1440×1800, dark). Platform's pages are in mastra-ai/platform#4174. | Before | After | | --- | --- | | <br>Studio · Settings | <br>Studio · Settings | | <br>Factory · My account | <br>Factory · My account | | <br>Factory · Preferences | <br>Factory · Preferences | | <br>Factory · Connections | <br>Factory · Connections | | <br>Factory · Models | <br>Factory · Models | | <br>Factory · Memory | <br>Factory · Memory | | <br>Factory · Skills | <br>Factory · Skills | | <br>Factory · Tools | <br>Factory · Tools | | <br>Factory · Behavior | <br>Factory · Behavior | | <br>Factory · Repositories | <br>Factory · Repositories | | <br>Factory · Work Intake | <br>Factory · Work Intake | | <br>Factory · Work board | <br>Factory · Work board | | <br>Factory · Manage Factory | <br>Factory · Manage Factory | One loading state everywhere (`SettingsSkeleton`, New/Settings Loading story), built from the real rows and list items:  ## What changed Playground UI (`@mastra/playground-ui/new/settings`): - `SettingsLayout`: the page column and title (`header` for an app's own header). - `SettingsTitle`: dimmed, inset to the card; `info` keeps a section description as a tooltip. - `SettingsContainer`: the card, owning row spacing. Rows with nothing in them take no space, so a list can always render its notice row. - `SettingsRow` / `SettingsFieldsetRow`: control column with shared field width; selects hug (`fieldTriggerWidthStyle` reads `--field-max-width`). With `controlPlacement="below"` the control fills the row. - New `SettingsListHeader`, `SettingsEmptyRow` (now takes an `action`), `SettingsItem`, `SettingsItemIcon`. `SettingsNoticeRow` stays. - New `SettingsSkeleton`: the one loading state for settings, placeholder rows (`variant="row"`) or list items (`variant="item"`) inside the same card. - Removed `SettingsAddRow` and `SettingsContainer`'s `variant`. `Section`'s deprecated rows keep their old look on their own code. Studio: the settings page uses `SettingsLayout` with its title in the column. URL, API prefix and request headers are one "Mastra connection" card. They only work as a set, so edits stay a draft: an "Unsaved changes · Discard · Save changes" row shows up once something changed, and saving applies all of it at once. This replaces "Save configuration", which sat under the headers and read as saving only them. The first-run connect screen keeps its own form. `@mastra/react`: `useAuthCapabilities` and `usePermissionPatterns` keep their last result while a new client loads (`keepPreviousData`). Before, every connection change gave them a new query key, and the auth and permission guards showed a full-page spinner until it answered, so the page went blank on each save. Factory: every settings page is on the shared components. Section stacks are fragments under `SettingsLayout`, lists with an action use the header or empty row (repositories, custom providers, speech-to-text keys, Connect, intake pickers), and logo and icon rows are `SettingsItem`s. Factory's own `SettingsAddRow`, `SettingsActionRow`, `SettingsSectionHeader` and `SettingsRowsSkeleton` are gone. Every settings loading state is `SettingsSkeleton` (Skills used to show plain "Loading skills…" text). Models keeps its routing diagram; its lane and defaults cards use the borderless settings surface. Work board keeps its form layout. Memory is split into Personal memory and Factory memory, and Build history is its own section. ## Testing 1. `mdev up storybook`: New/Settings, Page, Controls and Loading stories. 2. `mdev up studio`, open Settings: change the URL, prefix or a header and the unsaved row appears; Discard restores; Save applies everything without the page going blank. Change the theme. 3. Factory settings: every section, especially Models. Playground UI, Studio and Factory typecheck clean; the settings, Studio connection, Factory settings and Models tests pass, and CI is green. Not seen locally: a loading state on screen (they resolve too fast), Models with providers connected, and Factory's Memory form (no models in the local org). ## Related issue(s) Fixes PLTFRM-3135 ## Type of change - [ ] Bug fix (non-breaking change that fixes an issue) - [x] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update - [ ] Code refactoring - [ ] Performance improvement - [ ] Test update ## Checklist - [x] I have linked the related issue(s) in the description above - [ ] I have made corresponding changes to the documentation (if applicable) - [x] I have added tests that prove my fix is effective or that my feature works - [ ] I have addressed all Coderabbit comments on this PR <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 This PR makes settings pages in Playground UI, Studio, and Factory use a more consistent layout. It adds shared building blocks so settings and lists are easier to organize and read. ## Summary - Add shared settings components in Playground UI, including a centered 640px layout, consistent containers and rows, list headers, empty and notice rows, and settings items. - Update the Playground settings page and Studio connection form to use the shared layout. Add `CopyInput` for read-only values with a copy action. - Update Factory settings, workspace, and connection views to use the shared components. Separate Personal memory and Factory memory, and give Build history its own section. - Remove older layout helpers, including `SettingsAddRow`, `SettingsSectionHeader`, and the settings container variant. - Add or update component tests and Storybook examples for the new settings patterns. **Checks:** not available. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
7cefe1623e |
fix(factory): let a board use the key review (#29903)
Factory refused every write to a board under the key `review`, because
that key belonged to the retired Review board. No key is reserved now,
so `review` works like any other, and the unique index on a project's
board keys is what stops a duplicate.
```ts
// before: 409 reserved_board
// after: 201, listed in the catalog, and a second create is 409 board_exists
await fetch(`/web/factory/projects/${id}/boards`, {
method: 'POST',
body: JSON.stringify({ key: 'review', name: 'Review', phases }),
});
// before: threw "board id 'review' is reserved for the retired Review board"
new MastraFactory({ boards: [defineBoard({ id: 'review', ... })] });
```
A board a project stores under `review`, or one an app passes in
`boards`, is served in place of the retired Review board, and the cards
put on it are its own cards in their stored phases, never read as Work
cards. The retired board is still the fallback for a project that has no
board of its own under the key.
The cards the retired board left stored on `review` do not become the
new board's. The write that gives a project its board (a create,
`factory.upsertBoard()`, or a `PATCH` of the seeded row below) stores
their Work placement in the same transaction, the way an ordinary write
to such a card already does, so they stay on Work and the new board
starts empty. While one of those cards is still open the write is
refused with `409 board_in_use`, since the retired board is still in use
there. This is the one place Factory rewrites those rows together,
scoped to one project's cards on `review`.
Projects from earlier releases can hold the `review` row Factory seeded
back then. While nobody has edited it, it stays hidden and the
retired-board behaviour applies, as before. An edited row used to be
reported as a catalog problem and is now served as the project's board.
Creating over the untouched seed is a `409 board_exists` since the row
is there; a `PATCH` or delete gets past it.
An app board with id `review` owns its cards in a project from when its
row is stored there, not from the moment the app defines it. Storing the
row moves every card the retired board left on `review` to Work, open
ones included, because a deploy can't be refused. Where the old seeded
row is still there, Factory rewrites it to the app's definition on the
next load, in the same transaction as the card move.
The card store asks on each read of a `review` card whether the project
has its own `review` board (the board row and its phases, read through
the caller's connection), because a project can create or delete it at
any time.
Tests run on LibSQL and Postgres: finished old cards stay on Work and
the new board is empty (and can be deleted again), an open old card
refuses the create, the upsert and the seed edit, an app board is served
with its own cards and none of the old ones in a project with and
without the seeded row, a second create is `board_exists`, and the
untouched seed stays hidden. They fail without the card rewrite.
`src/boards`, `src/routes`, the boards and work-items storage suites and
the intake-routes rules pass on both stores, except three Postgres
timeouts in `projects-concurrency.test.ts` that fail the same way on
main, and one Postgres timeout in `intake-routes.test.ts` that comes and
goes. No error code is added, so the CLI route metadata is unchanged.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## ELI5
Projects and apps can now use a board named `review`. When they do,
cards left on the old Review board move to Work, so they do not get
mixed with cards on the new board.
## Summary
- Removed the restriction on using `review` as a board key.
- Served stored `review` boards as regular boards. Untouched legacy seed
rows remain hidden until edited, replaced, or adopted by an app board.
- When a project creates, edits, or upserts a board under `review`, the
system moves legacy Review cards to Work in the same transaction. If
open cards remain, the write returns `409 board_in_use`.
- App-board seeding moves legacy Review cards to Work, including open
cards.
- Added safeguards that use the current card state during release to
handle concurrent changes.
- Updated documentation and tests for board ownership, duplicate
creation, legacy seeds, card migration, and open-card refusals.
**Test and CI results:** not available from completed checks on the
current head.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
|
||
|
|
05a6931471 |
chore: version packages (alpha) (#30172)
This PR was opened by the [Changesets release](https://github.com/changesets/action) GitHub action. When you're ready to do a release, you can merge this and publish to npm yourself or [setup this action to publish automatically](https://github.com/changesets/action#with-publishing). If you're not ready to do a release yet, that's fine, whenever you add more changesets to main, this PR will be updated. ⚠️⚠️⚠️⚠️⚠️⚠️ `main` is currently in **pre mode** so this branch has prereleases rather than normal releases. If you want to exit prereleases, run `changeset pre exit` on `main`. ⚠️⚠️⚠️⚠️⚠️⚠️ # Releases ## @mastra/client-js@1.60.0-alpha.12 ### Minor Changes - Allow `querySpans()` to sort by `model` or `provider`. ([#30096](https://github.com/mastra-ai/mastra/pull/30096)) ```ts orderBy: [{ field: 'model', direction: 'asc' }]; ``` ### Patch Changes - The generated route types for scores now include the `SCORER` and `PROCESSOR` entity types, matching the entity types experiments can emit. ([#30145](https://github.com/mastra-ai/mastra/pull/30145)) - Add span-local error counts. ([#30088](https://github.com/mastra-ai/mastra/pull/30088)) - Updated dependencies [[`56f654f`]( |
||
|
|
46ce164dde |
fix(factory): recover stuck environment builds and rebuild on saved changes (#30148)
Environment templates could stop rebuilding for good, and changing a
setup command never rebuilt them.
When a build start isn't recorded (for example the process restarts
mid-start), Factory marks the start uncertain and asks the provider for
its build list before building again. Mastra Platform has no build list,
so that mark could never clear: every Build now, schedule and push run
skipped with `unresolved` forever and sessions kept booting an old
template. Now an uncertain start ages out 30 minutes (the build wait
ceiling) after its lease lapsed, Factory logs once that it gave up on
it, and the next trigger builds. A new `build_start_uncertain_since`
column records when the mark started; rows already stuck get stamped on
their next read and recover 30 minutes later.
Saving a template input (setup commands, working directory, settings,
environment repositories, Build variables) also never started a build,
so each new sandbox reran the changed setup command. Saves now start a
build once the project has a template, only when the inputs actually
differ from the last build. Repeated saves don't double-build, and a
change saved during a build is built when that build ends.
Before: a project stuck on `unresolved` stayed on its Oct 28 template,
and a new setup command reran for 40s in every sandbox. After: the stuck
project builds on its next trigger after 30 minutes, and saving the
setup command rebuilds the template.
Tested with red/green tests on LibSQL and Postgres 16 using real storage
and a fake clock, plus route tests for every save path.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
**ELI5:** Sometimes the system got stuck while it prepared a project's
build environment, and it did not try again for a long time. Also,
saving changes to the project's setup did not start a new build. This
change fixes both problems. Stuck builds now recover, and saved changes
now start a new build when they affect the template.
## Overview
This change fixes two problems in Factory environment template builds.
1. **Stuck build starts.** A build start can stay `unresolved` for a
long time when the provider cannot list builds.
2. **Missing rebuild on save.** Saving changed template inputs did not
start a build.
Diff base: `main` at merge base
`
|
||
|
|
4e378c3e26 |
feat(factory-ui): let an intake route join a pull request to its issue's card (#30197)
An intake route can put a pull request on the card of the issue it
closes instead of giving it a card of its own, but only the route
Factory seeds ("Pull requests that close a waiting issue join its card")
could do it. The Add route form in Settings → Work Intake always saved
`joinClosedIssue: false`, and a saved route had no control for it, so an
admin could not make a second joining route or get one back after
deleting the seeded one.
Routes now carry a "Join the issue's card instead" switch. It is offered
on a new route, and on a saved new-card route, once the conditions
include "Source kind is Pull request" and "Pull request closes an issue
is Yes". Turning it on changes the outcome label from "Send to" to "Join
the issue's card, move to" and offers every unfinished phase, since the
card is already on the board. A line under the switch says only trusted
authors' pull requests join and others get their own card.
```ts
// before: every route the form made
target: { boardKey: 'work', phaseKey: 'intake' }
// after, with the switch on
target: { boardKey: 'work', phaseKey: 'building', joinClosedIssue: true }
```
A route that already joins keeps the switch even if its conditions no
longer qualify, so it can still be turned off. Turning it off on a route
parked in a phase new cards cannot land in moves it back to the board's
first phase. Card moves and the catch-all never show it, and the "send
new cards to" logic ignores joining routes as before.
Tested with MSW against the real client: creating a joining route sends
`joinClosedIssue: true`, the switch stays hidden without both conditions
and goes away when they are narrowed, and toggling a saved route PATCHes
its target at the revision it was read at. The first and third fail on
main, the second fails if the switch is always offered. Also run by hand
on a local Factory with its own throwaway Postgres; screenshots are in
`.pr-review/` locally. The full MSW suite was not rerun, only the
settings and board config folders, where the ten failures are the memory
settings ones that fail on main.
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
|
||
|
|
e1753c7199 |
feat(factory): stop a card's sandbox as soon as its context is done (#29981)
## What Each Factory card context (Triage, Work, Review, or a custom board's `runner.context`) runs in its own session with its own sandbox, so one card can hold three VMs. Until now only terminal phases released them, and only on the process that had opened the sandbox. A card that left Triage kept its triage VM until the provider's idle timeout, and a card finished on another replica (or after a restart) stopped nothing. This PR stops a card's sandbox as soon as the card is done with that context. - **Leaving a context.** When a committed move takes a card out of the last phase of a context into a phase that runs in another context, Factory stops that context's sandbox. Triage → Planning stops the triage sandbox. Planning → Building stops nothing, because both run in `work`. - **Finishing.** Done/Canceled stop every sandbox the card holds. When this process never opened a sandbox, it stops it by identity through the configured provider, the same way session deletion already destroys by identity. It stops, it does not destroy. There is no TTL sweep. - **Coming back.** A stop keeps the session row, branch and files, so PR review → Triage resumes the same sandbox: E2B resumes the paused VM by its metadata tag, Docker restarts the container by name, and local reuses its directory. Platform `stop()` sends nothing remotely; that VM idles out under its environment policy, and the next run reattaches by session id. ## How - `FactoryTransitionService` gets an `onContextLeft` hook beside `onTerminalStage`. It fires only for accepted moves where `roleForPhase(from) !== roleForPhase(to)` and the new phase is not terminal. Both hooks share one bounded, best-effort runner (`#bounded`): a committed move never fails or hangs on cleanup. - `sandbox/context-sandboxes.ts`: - `createContextSandboxStops` re-reads the card and skips if the revision moved (the same stale guard as terminal cleanup). It also skips if the card is back in the context or holds the same session under its new context. - **Run in flight:** if a run is active on the left session in this process (the agent whose own tool call made the move, or a person chatting), the stop waits for that run's `agent_end` and then re-checks only that the card has not come back. The run isn't awaited inside the hook, because it may be the very tool call waiting on this transition. I picked this over the `initiatingBindingId` skip because it covers both the initiating agent and a person in the session, and still stops the sandbox afterwards instead of leaving it to the terminal path. - `createTerminalSandboxStops` is the existing terminal retirement moved out of `factory.ts`. - `SessionRetirementCoordinator.stopSessionSandbox` stops a session's sandbox without teardown and invalidates its workspace. A detached sandbox is reached through the new `stopDetachedSessionSandbox`. Retirement without deletion now also stops a detached materialized sandbox by identity; before, it left it to the provider. ## Known limits - A run live on **another** replica is not seen by the in-flight check, because there is no shared signal for human chat. Leaving a context from replica A while a run streams on replica B can pause that E2B VM under it. Terminal retirement has never had a human-chat guard, so the terminal path behaves as before, except that it now reaches detached sandboxes. - The local provider persists no physical sandbox id, so a local sandbox opened on another process can't be stopped by identity. Local has no remote VM, so nothing keeps billing. ## Test plan New `src/sandbox/context-sandboxes.test.ts`, real storage on LibSQL and Postgres (`FACTORY_TEST_POSTGRES_URL`, throwaway container), with the real `LocalFactorySandbox`: - Triage → Planning stops the triage sandbox only; the work sandbox stays running. - Planning → Building stops nothing. - Back to Triage resumes a new instance on the same directory, and a file written before the stop is still there. - A run in flight on the triage session holds the stop until it ends; a card back in Triage by then keeps its sandbox. - Done on a second Factory over the same database (a process that never opened the sandboxes) stops all three by identity. - The move still commits when the stop throws. Red: with the transition/retirement changes reverted, 4 of 7 fail. Mutation-checked the come-back guard. `session-retirement.test.ts`: the case that pinned "retire without delete never touches a detached sandbox" was flipped to the new contract. `factory.test.ts` asserts the hook is wired when a sandbox is configured (red without the wiring). Gates: `check` 0, `lint` 0/0, `build:lib` ok. `src/sandbox src/rules factory.test sandbox-release source-control-sessions` on LibSQL+PG: 1114 passed. The only failures are 2 `board-phase-runtime` "custom phase that runs an app skill" cases, which fail the same way on main (a third fails only under load). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 When a card leaves a work context, this change stops the sandbox that context used. It keeps the session and its files, so the card can resume that sandbox if it returns. When a card reaches Done or Canceled, the change stops every sandbox the card holds. ## Changes - Adds `onContextLeft` to `FactoryTransitionService`. The hook runs after an accepted move that leaves the last phase of a context for a different context or for no context. Moves between phases in the same context do not stop a sandbox. - Adds `controllerRunInFlight`. If a run is active in the current process, the context-leave stop waits for `agent_end`. After the run ends, the stop checks whether the card returned to that context. If it did, the sandbox keeps running. - Adds `createContextSandboxStops`. It checks the card revision and skips missing cards or sessions. It keeps the sandbox if the card returned to the left context or still holds that session. - Adds `createTerminalSandboxStops`. It deduplicates the session IDs on a finished card and retires each sandbox without deleting its session. `MastraFactory` uses it for terminal work-item cleanup in place of the previous inline logic. - Adds `SessionRetirementCoordinator.stopSessionSandbox`. It serializes the stop, verifies the session and organization, and stops the attached sandbox. For a detached sandbox, it stops the sandbox by identity through the configured provider. It invalidates the session in a `finally` block. - Changes detached-sandbox cleanup in `session-retirement.ts`. When `deleteSession` is false, cleanup stops a materialized sandbox. When `deleteSession` is true, cleanup destroys it. Sessions without a persisted sandbox ID or configured sandbox are skipped. - Adds `stopDetachedSessionSandbox` in `sandbox-release.ts`. It creates a provider sandbox from the session ID and optional sandbox ID, with repository access disabled, and calls plain `stop()`. - Keeps cleanup bounded and best-effort. The transition service awaits each hook with the terminal-cleanup timeout. Errors are swallowed. If the timeout expires, cleanup continues in the background. A failed stop does not fail or roll back a committed move. - Stopping preserves the session row, branch, and files. Session deletion still destroys the sandbox. - Adds docs: a `@mastra/factory` changeset and a "Card sandboxes" section in the factory README. - Adds tests in `context-sandboxes.test.ts` for LibSQL and, when `FACTORY_TEST_POSTGRES_URL` is set, PostgreSQL. The tests cover context-leave stops, same-context preservation, resumption on return, in-flight runs with a real controller, terminal cleanup of persisted sandboxes, accepted moves when a stop fails, and idle versus active sessions. Also adds a `MastraFactory.prepare` test and updates the session-retirement test fake to record `stop` calls. ## Known limits - An in-flight run on another replica is not detected. The stop does not wait for that run. - A local sandbox opened by another process cannot be stopped by identity. ## Validation Completed test and CI results are not available for the current head. The PR objectives report `check`, `lint`, `build:lib`, and test results, but these are author-reported and not confirmed as completed checks on this head. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
993c85892c |
Prevent /settings from crashing on missing mouse preferences (#30180) | ||
|
|
1fbc69aa9a |
feat(factory): count the new session page's starters and activity on the server (#30097)
**─────── TLDR ───────** > The new session page now gets its starter counts and activity dates from two small server reads instead of downloading every card of the project. To show a handful of numbers, the page read the whole board: 1,505 KB gzipped on the 8,078-card board measured in #28915. The rules that decide which cards a starter counts now run on the server, and the browser keeps the wording and the layout. Since #30099 a tab that already holds the board only reads the cards that moved. What this PR removes is the first download, and the board the tab had to keep to count on it. Fifth step of removing whole-board reads, after #30080, #30083, #30087 and #30081 (⌘K). The board page comes next. ### Behavior changed opening a new session page ├─ **was** — every card of the project downloaded, then counted in the browser └─ **now** — two reads: the starter counts, and the instants of the period a card changes while the page is open ├─ **was** — the cards that moved, merged into the board the tab kept └─ **now** — the two reads asked again; the instants come back only when one was added or removed, a `304` otherwise choosing "This month" in the activity band ├─ **was** — recounted at once on the board the tab kept └─ **now** — one more read; the band stays up on the week's instants until it answers the live session counts in the activity band ├─ **was** — read off the whole board └─ **now** — read off the sidebar's cards holding a session, already loaded a pull request card whose source reports no state ├─ **was** — finished only in a phase named `done` or `canceled` └─ **now** — finished in any terminal phase of the default board the page served by a Factory server without the two routes └─ **new** — starters and activity band stay hidden, the rest of the page works; feed frames do not ask the two routes again ### Shape changed | | | | |---|---|---| | **+** | `routes/work-item-starters.ts` | the starter rules, moved here from the browser; they read the cards as storage holds them | | **+** | `routes/work-item-activity.ts` | the instants one period needs | | **+** | `hashedBody()` in `routes/board-snapshot.ts` | a computed answer and the `ETag` naming it | | **~** | `starterPrompts.ts` | words the counts, no longer reads cards | | **+** | `queryKeys.boardFacts(id)` | answers computed from the board, refreshed with it | | **+** | `activityDepth(period)` | one home for "Today reads the week's answer" | | **−** | draft page in `pageLoadsBoard` | it no longer reads the board | | **−** | `doneAt` in `boardItems.ts` | its only caller moved to the server | what callers can now ask `GET …/work-items/starters` · `GET …/work-items/activity?since=<instant>` (answers `304` to `If-None-Match`) · `mastra api factory work-item starters` · `mastra api factory work-item activity` ### Decisions - **counted on the server, not from a smaller card list** — the page needs eight numbers, not cards; a new starter now takes a server rule plus its wording - **instants, not buckets** — the browser buckets in the viewer's time zone and Today reuses the week's answer; bucket on the server if the list ever weighs - **no whole-board fallback on an older server** — the two blocks hide until the server is deployed; one `catch` away if you disagree - **counted on stored cards, not on their wire copy** — copying every card per request was three quarters of the read's time; the rules merge the work item's facts with the card's where they read them - **recounted on every request, no memo per board** — a memo would have to expire with the clock (stale pull requests), the board registry and the decisions; the count costs 1 to 5 ms - **`ETag` on the instants, none on the counts** — the counts weigh about 150 bytes; the page asks the instants from the top of the hour so the address repeats and the browser can revalidate - **the other depth stands in while a period loads** — two observers, one enabled; a placeholder would set the band's clock to zero ### Gain Opening the page on 2,500 cards with ~2 KB descriptions: the whole board, 1.2 MB gzipped, becomes about 150 bytes of counts plus 27 bytes per card created or completed in the period. That is 1.9 KB when the cards were filed over 400 days, 67.9 KB when all 2,500 fall in the week (sent uncompressed: instants gzip about 3.5×). Once the page is open, this branch does not beat `main`, it costs a little more. One refresh of one open tab, at most every 5 s: | one refresh of an open tab | 2,500 cards | 10,000 cards | |---|---|---| | `main`, nothing changed | 0.5 ms · 124 B | 1.4 ms · 122 B | | here, nothing changed | 2.4 ms · 154 B | 7.7 ms · 156 B | | `main`, one card filed | 860 B | 868 B | | here, one card filed | 2,030 B | 5,921 B | "here" adds up the three reads the page makes: cards holding a session (`304`), starters, instants. Cards filed over 400 days, medians of 10 rounds in the in-memory route harness. When every card falls in the week the two counts take 0.98 + 1.15 ms at 2,500 cards and 4.27 + 4.60 ms at 10,000. Counting on stored cards took the starters function from 1.11 to 0.29 ms at 2,500 cards and from 4.61 to 1.15 ms at 10,000. ### Watch > [!WARNING] > The starter rules moved from the browser to the server together with their scenario tests. <mark>A porting mistake would show as a wrong number on a starter button</mark> and nowhere else, so compare a few buttons with the board after deploy. on merge: nothing to do. `main` with #30153 is merged into this branch and the CLI route metadata check passes. ### Not verified - [ ] against a real board or Postgres — the timings come from the in-memory route harness - [ ] the `304` in the signed-in app — the route is tested, and headless Chromium revalidated a stand-in answer with the same headers, but the real page was not watched against a real server --- > ████████████████████ **tests** `+1077 −431` — 58% of the additions > ███████████ **source** `+572 −222` > ███ **generated** `+177` > █ **changeset** `+24` > █ **docs** `+2` --------- Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local> |
||
|
|
4f301a45b4 |
feat(factory): let sessions query the Factory audit trail (#30165)
> Opened by @user_01KN2T7F5T2WYEMHY58VJGPZ8R ## What Adds `factory_list_audit_events`, a read-only tool that Factory user sessions and MCP clients can use to ask who did what in a Factory: which work item, run, branch or setting changed, who changed it, and when. Filters: - `actor`: `me`, a user id, or `agent:<threadId>`. Add `includeAgentRuns` to also get the agent runs that person started. - `namespace` (e.g. `work_item`, `run`, `agent`) and/or exact `actions` - `workItem` (id or `#123`) - `since` / `until` (ISO times) - `cursor` / `limit` (newest first, max 50 per page) ## Privacy The audit table covers the whole org and nothing limits who can read it. It also stores request context and actor profiles. So this tool trims what it returns: - **Only this Factory's events.** Results are scoped to the caller's org and Factory project. - **No request context.** Client IP and user agent are never returned. - **No actor emails.** Actor display names are returned unless the stored name is an email (the fallback for people with no name), in which case it's left out. The private `__actorProfile` metadata is never returned. - **No event metadata.** Branches, PR URLs, stage details, env var names and model IDs stay out. The tool returns only action, time, actor, `startedBy` for agent events, and targets. - **Private sessions stay private.** An event that names a session (a session target or the session it recorded acting in, e.g. ownership transfers, git pushes, run approvals, signals) is shown only if every such session is in this Factory and shared, or private and owned by the caller. An agent event is also shown only if: - the caller started the run (`startedBy`), or - its thread belongs to a work-item run binding in this Factory (those runs are already on the board), or - its thread resolves to a session in this Factory that is shared, or private and owned by the caller. Anything that can't be resolved stays hidden. Each call reads at most 5 pages of 200 events. Narrow filters therefore return a `nextCursor` and never scan the whole trail in one call. ## Test plan - [x] New `audit-events-tool.test.ts` runs against a real in-memory `AuditStorage` (LibSQL). It covers project/org scoping; stripping of IP, user agent, email and metadata; actor, namespace, action, work-item and time-window filters; cursor paging and rejecting bad cursors; agent visibility across runs, shared, private and own-private sessions plus unresolvable threads; human and agent events naming another person's private session (ownership transfer, git push, signal) or an unknown session; and `includeAgentRuns`. - [x] Tool-list and approval-allowlist tests updated (`work-item-tools`, `messaging-tools`, `factory.test.ts`) - [x] `vitest run src/tools src/factory.test.ts src/mcp`: plus `src/routes/source-control-sessions.test.ts`: 534 passed - [x] `tsc --noEmit`, `oxlint --type-aware`, `prettier --check` clean <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> **ELI5:** This change lets Factory users and MCP clients look up a history of audit events. They can filter the history and page through it. The tool shows only events that the caller is allowed to see. ## Summary This change adds the read-only tool `factory_list_audit_events` to `@mastra/factory`. The tool lists audit events for the caller's Factory organization and project. Results are newest first. ### Filters The tool accepts these optional inputs: - Actor - Agent run started by a person - Namespace or exact actions - Work item - Time range (`since` and `until`) - Cursor - Limit ### Behavior - The default result count is 25. The maximum is `MAX_LIST`, which the PR objectives describe as 50. - The tool reads pages of 200 events. It reads up to five pages per call. - If the result limit or scan budget is reached, the tool returns a continuation cursor. - The tool rejects: - An invalid cursor. - `since` greater than or equal to `until`. - `includeAgentRuns` when the actor is not a person. - An unknown work item returns an error. - An action filter with no matches returns an empty list. ### Output Each result includes: - Action - Time - Actor - An optional display name and starter, without email addresses - Up to ten targets, with truncated text The output omits request context and event metadata. The only exception is who started an agent run. ### Visibility rules - Agent events are visible when the caller started the run or when the run thread is visible. Other agent actors are hidden. - Work-item run threads are visible to Factory members. - Other threads must resolve to a session in the same organization and project. The session must be shared or owned by the caller. - Any session named by an event must pass the same session check. - Missing lookup data and lookup failures deny visibility. Per the PR objectives, two follow-up commits change the following: - Ownership-transfer audit targets stay on the session row ID. This matches the existing session hover-card lookup. - Agent stage moves recorded under run-binding IDs are included. Factory board runs are recognized by binding ID as well as by thread. Unresolved agent IDs stay hidden. ### Interface changes - Added `FactoryAuditToolDependencies` in `mastracode/factory/src/tools/audit-events-tool.ts`. - Added `createAuditEventsTool(scope: FactoryToolScope, deps: FactoryAuditToolDependencies)` in the same file. - `FactoryToolDependencies` in `mastracode/factory/src/tools/index.ts` now includes `FactoryAuditToolDependencies`. - For user scopes, `createFactoryTools` adds the new tool. Non-user scopes still return only messaging tools. ### Other changes - `permissions.ts`: adds the tool to `FACTORY_TOOLS_WITHOUT_APPROVAL`. - `annotations.ts`: adds the tool to `FACTORY_TOOL_ANNOTATIONS` with read-only annotations and the title "List audit events." - `.changeset/factory-audit-events-tool.md`: adds a patch changeset for `@mastra/factory`. - `mastracode/factory/README.md`: documents the tool in the Factory tools table. - Tests: - `audit-events-tool.test.ts` (new, +331 lines) uses in-memory LibSQL audit storage. It covers scoping, privacy, filters, pagination, and visibility. - `factory.test.ts`, `messaging-tools.test.ts`, and `work-item-tools.test.ts` add the new tool to their expected tool lists. ### Diff size 10 files changed, +608 lines and −19 lines. ### Verification - Author-reported: `vitest run src/tools src/factory.test.ts src/mcp` and `src/routes/source-control-sessions.test.ts` passed, 534 tests total. `tsc --noEmit`, `oxlint --type-aware`, and `prettier --check` were clean. - Not independently verified in this review. No completed checks on the current head were inspected. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com> Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com> Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local> Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> |
||
|
|
d97d3c5fd8 |
chore: version packages (alpha) (#30167)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
a4258a989c |
chore: version packages (alpha) (#30127)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
8e93f532c6 |
fix(factory-ui): label search sessions by the phase they run (#30142)
> Opened by @roaminro ## Summary A Factory work item can have one session per context (triage, work, review), and all of them run on the item's branch. Factory search (Cmd/Ctrl+K) showed one row per session, but each row only had the item title, "Work session", the branch, and the issue number. Two sessions on the same item therefore looked like duplicate results. This PR labels each session row with its context. The label comes from `contextLabel()`, the same helper the session page breadcrumb uses, so it shows the board's phase name when only one phase runs in that context and the well-known context name otherwise. Rows now read, for example, `Triage · factory/issue-30123-…` and `Work · current · factory/issue-30123-…`. - The session for the card's current phase is tagged `current` and sorted first within the item. - The context label is searchable, so typing `triage 30123` finds the triage session. - Sessions with no work item keep the existing `Work session` / `Review session` context. - The search dialog already loaded the board catalog; it is now passed into `createSessionSearchGroups`. ## Test plan - [x] New MSW test: a card holding `triage` and `work` sessions on one branch renders two distinguishable rows, with Work marked current and listed first, and `triage 321` narrows to the triage row. The test fails without this change. - [x] `vitest run src/ui/domains/search`: 59 passed - [x] `tsc --noEmit -p src/ui/tsconfig.json` and oxlint pass <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 Factory search showed sessions for the same work item and branch that looked alike. This change gives each session a clear label, such as its phase or context name. The session for the current phase now appears first, so users can tell the sessions apart and find them faster. ## Overview This change makes Factory search sessions distinguishable. Sessions that share a work item and branch now show a context label. The label is searchable. ## Changes - **Search result service** (`services/searchResults.ts`): - `createSessionSearchGroups` accepts an optional `boards?: readonly BoardInfo[]` input. - Work items link to context-specific card sessions. The previous logic linked each stored session reference. - Board phase data feeds the lookup. - Each session result uses its context label and current status to build its context and search value. - The context thread ID sets the result path. If the thread ID is absent, the factory session ID is used. - Results with the same update time sort current-context sessions first. Other results stay sorted newest first. - **Search content component** (`components/FactoryGlobalSearchContent.tsx`): passes `catalog.data` as `boards` to `createSessionSearchGroups`. - **Tests** (`__tests__/GlobalSearch.msw.test.tsx`): - `stubSearchApi` accepts per-repository `FactoryUserSession[]` fixtures. It falls back to `sessionsByRepository` when an entry is missing. - A new test covers a work item with a current Work session and a historical Triage session. It checks that both appear as searchable results, that the Work result is marked current, and that a Triage query returns only the Triage result. - **Changeset** (`.changeset/factory-search-session-phase.md`): adds a `mastra` patch changeset for phase labels, the current marker, and phase-name search. ## Behavior - A context label uses the board phase name when only one phase runs in that context. Otherwise it uses the context name. This matches the session page breadcrumb (per the PR description). - The session for the card's current phase is marked `current` and sorts first within its work item. - Sessions without a work item keep the existing `Work session` or `Review session` context. ## Verification - The author reports that `vitest run src/ui/domains/search` passes 59 tests. The author also reports that `tsc --noEmit -p src/ui/tsconfig.json` and oxlint pass. These results were not re-run for this summary. ## Diff size - 4 files changed, 87 lines added, 13 lines removed. - Exported signature change: `createSessionSearchGroups` gains an optional `boards` input. No other exported declarations changed. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com> Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
566e2081d3 |
Fix transcript gap ordering when answered suspension prompts are removed (#30163) | ||
|
|
6937417bd4 |
fix(factory): ⌘K reads the clicked card by its id, and three search fixes (#30154)
**─────── TLDR ───────** > ⌘K now reads the card you click by its id before starting it, and three smaller search bugs are fixed. Copilot reviewed #30081 after it merged and left six findings. Four are about the palette and are fixed here, one commit each. The CLI one is #30153, and the sixth was declined on the PR. ### Behavior changed clicking a listed card the search would no longer return, because a more recently updated card took its place among the 20 ├─ **was** — "This card no longer exists", nothing started └─ **now** — the card is read by its id and its session starts Retry after the board cards failed to load, when the intake has no candidate ├─ **was** — the failure notice stayed up for good └─ **now** — only the reads that failed are asked again, and the notice goes typing a source label such as "review" with more than 20 intake items ├─ **was** — the item matching by its label could miss the 20 looked up, and its row never showed └─ **now** — the 20 are ranked on the same text the rows are filtered on typing the number of a card that has no key and no GitHub source ├─ **was** — the server found the card, the palette then hid its row └─ **now** — the row shows the list route asked for `?workItemId=<id>` └─ **new** — the cards with those ids and no other; an id no card has is left out, and a board cursor (`since`) sent with it is ignored, as on the other narrowed lists ### Shape changed | | | | |---|---|---| | **+** | `workItemId` on `workItemListQuerySchema` | repeatable, 100 ids at most, refused with any other filter | | **+** | `cardsWithIds` | beside `cardsFiledFrom` in `work-item-selection.ts` | | **~** | `useBoardRuns({ refetchItems })` | now given the id of the card clicked | | **~** | `useGlobalSearchWorkItems.refetch` | one card by its id, no longer both lists | | **+** | `candidateSearchValue` | one home for the text a candidate row is filtered and ranked on | | **+** | `searchedNumber` | the number the server's search reads, mirrored for the row | what callers can now ask `GET …/work-items?workItemId=<id>` · `mastra api factory work-item list` can pass it once #30153 is in ### Decisions - **a filter on the list route, not `GET /work-items/:id`** — a server older than the filter ignores it and sends the whole board, which still holds the card; a new route would answer 404 there and read as "deleted" - **not the listed copy as a fallback** — starting a run on an id the server no longer has creates the card again (`prepareRunStart`), so a deleted card would come back; the fresh read decides, and a deleted card still gets the toast - **the board page keeps refetching its list on a click** — it moves to the same read with the board page's own PR ### Gain A click in ⌘K asks for one card instead of two lists. ### Watch > [!WARNING] > <mark>Until a server with `workItemId` is deployed, each click on a card in ⌘K downloads the whole board.</mark> It still finds the card there, so the click works, only slower. on merge: `main` with #30099 is merged in and the CLI route metadata regenerated. #30097 regenerates the same file, so whichever merges second runs `pnpm --filter @mastra/factory generate:api-cli-route-metadata` again. ### Not verified - [ ] against a deployed Factory or Postgres — the route tests run on the in-memory harness, the palette tests against stubbed routes - [ ] in a real browser — the palette tests run in jsdom --- > ██████████████████ **tests** `+273 −5` — 65% of the additions > ███████ **source** `+110 −25` > █ **generated** `+18 −2` > █ **changeset** `+16` > █ **docs** `+2 −2` --------- Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local> |
||
|
|
055a8c3b82 | chore: version packages | ||
|
|
b9610409ab |
perf(factory): send an open board only the cards that changed (#30099)
Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local> Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
3dbe6f4314 |
fix(agent-controller): restore stored tool suspensions (#30132)
## Problem
When the server process that parked a run on a tool question (for
example `submit_plan`) goes away, the run stays suspended in storage.
Approving the plan later was rejected with `{ok:false,
reason:"no_pending_suspension"}` because claiming only looked in memory.
The Factory UI treated that 200 as success, so "Approve & build" did
nothing and the card kept offering buttons. Seen in prod on thread
`f82402a7` (plan waiting about 14h).
## Changes
- **core:** `Session.restoreStoredToolSuspension(toolCallId, runId?)`
registers a suspension that exists only in storage. It only does this
when exactly one stored suspended run on the active thread matches the
tool call id, and it skips approval prompts.
- **server:** the tool-suspension route restores the stored suspension
before claiming it. The claim stays synchronous.
- **factory-ui:** reply mutations now reject `ok:false` acks and show an
error toast. The respond mutation refetches the session. The transcript
only resolves a prompt once the reply was actually delivered.
## Tests
- `session-stored-suspension-after-restart.test.ts`: park on one
controller, then approve from a second controller that shares storage.
Fails before the fix. A negative case covers unknown calls and
mismatched runs.
- `useRespondSuspensionRejected.msw.test.tsx`: an `ok:false` ack fails
the mutation. Fails before the fix.
- core agent-controller 1021/1021, server agent-controller 104/104,
factory-ui chat/hooks 616/616, typecheck clean.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
**ELI5:** When an AI agent asks a question and waits for an answer, the
server can restart before the user replies. The reply used to fail
because the server only checked memory. Now the server loads the waiting
question from storage, so the reply works. The user interface also shows
an error when a reply is rejected.
## Overview
This change fixes replies to tool prompts after the process that parked
the run has stopped. Before this change, the claim step checked only
in-memory suspensions. A reply could return `{ ok: false, reason:
"no_pending_suspension" }`. Factory UI treated that response as success,
so the prompt buttons stayed visible.
The change also keeps prompt cards in sync across windows. When a tool
call completes, the matching approval or suspension card clears in every
window.
## Changes
**Core (`packages/core/src/agent-controller/session.ts`)**
- Adds `Session.restoreStoredToolSuspension(toolCallId?: string, runId?:
string): Promise<void>`.
- Returns without a storage lookup when the tool-call ID is missing, the
suspension is already resolvable, or no thread is active.
- Searches suspended runs in storage for the active thread and resource.
It checks each configured agent, reads 100 runs per page, and reads at
most 10 pages per agent.
- Optionally filters by `runId`. Matches only non-approval tool calls
that have the requested ID and a tool name.
- Stops scanning an agent on the no-storage error. Propagates other
lookup errors.
- Registers the suspension and caches its owning agent only when exactly
one match exists and no concurrent restore occurred.
**Server (`packages/server/src/server/handlers/agent-controller.ts`)**
- If `session.restoreStoredToolSuspension` is available, the
tool-suspension route awaits it with `toolCallId` and `runId`. It then
claims the suspension. If the method is not available, the route claims
directly.
- Rejected claims return `{ ok: false, reason }`. Accepted claims are
acknowledged, and the suspension response runs in the background.
**Factory UI**
- `useAgentControllerRunMutations.ts`:
- Validates tool approval and suspension acknowledgments with
`requireAccepted`. A rejected acknowledgment throws the new
`RejectedReplyError`.
- Adds `isEndedPrompt(error: unknown): boolean`. It returns true for
rejections with reason `no_pending_suspension`.
- Both mutations report errors in a toast.
- Suspension-reply errors invalidate the session query. Successful
mutations also invalidate it.
- `Transcript.tsx`: Resolves a prompt after a successful mutation. On
rejection, resolves the prompt only when `isEndedPrompt` returns true.
Otherwise, leaves it unresolved.
- `services/transcript.ts`:
- On a `tool_end` event, updates the tool result. Removes only the
approval or suspension prompt with the matching `toolCallId`.
- Omits persisted prompts for tool calls in terminal states (`result`,
`output-error`, or `output-denied`).
- During server-window reconciliation, removes prompts for terminal tool
calls. Updates matching assistant tool invocations from persisted
terminal parts.
**Changeset (`.changeset/stale-plan-approval.md`)**
- Declares patch releases for `@mastra/core` and `@mastra/server`.
**Channels test
(`packages/core/src/channels/__tests__/agent-controller-channels.test.ts`)**
- The allow/deny policy test sets `deployTool` permission in
`onSessionStart`. It no longer sets the permission on a manually created
session. It reads the session after inbound processing.
**Tests**
-
`packages/core/src/agent-controller/__tests__/session-stored-suspension-after-restart.test.ts`
(new, +169): Covers approval from a second controller that shares
storage. Covers an unknown tool call, a call tied to a different run,
and the 10-page limit.
-
`mastracode/factory-ui/src/hooks/__tests__/useRespondSuspensionRejected.msw.test.tsx`
(new, +45): Mocks a `no_pending_suspension` rejection. Asserts an error
whose message indicates the prompt is no longer waiting. Asserts that
`isEndedPrompt` classifies only that rejection reason as an ended
prompt.
-
`mastracode/factory-ui/src/ui/domains/chat/services/__tests__/transcript.test.ts`
(+57): Covers persisted prompt visibility. A prompt stays visible while
its tool call has no result. It is hidden when a later message or
refetched window includes the result. A `tool_end` event clears only the
prompt with the matching `toolCallId`.
- `mastracode/web/e2e/web/approval-other-window.scenario.test.ts` (new,
+130): End-to-end scenarios for prompts in two windows. After a response
settles, approval, plan-suspension, and `ask_user` cards clear from the
non-answering window. Approval cards clear from the answering window.
Unanswered cards stay in both windows.
- `mastracode/web/e2e/web/fixtures/approval-other-window.json` (new,
+104): Fixture for the end-to-end scenarios. Defines six `gpt-5.4-mini`
interactions: write-file approve and decline, plan approve and revise,
and an `ask_user` prompt.
## Scope
- 12 files changed, 663 lines added, 30 lines removed.
- Added declarations:
- `Session.restoreStoredToolSuspension` (method,
`packages/core/src/agent-controller/session.ts`)
- `RejectedReplyError` (class) and `isEndedPrompt` (function) in
`mastracode/factory-ui/src/hooks/useAgentControllerRunMutations.ts`
## Test results
The author reports these results. This review did not run them:
- Core agent-controller: 1021/1021 passed.
- Server agent-controller: 104/104 passed.
- Factory UI chat and hooks: 616/616 passed.
- Typecheck: clean.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: mastra-platform[bot] <mastra-platform[bot]@users.noreply.github.com>
|
||
|
|
d432f1ea67 |
feat(factory-ui): pick a route's repository, team or project from the project's own (#29982)
## Summary
An intake route with `source.repository equals mastra` never matches. On
GitHub the value is `owner/repo` (`mastra-ai/mastra`), and the route
editor gave no hint of that. Now you pick the value from the project's
own sources:
- **Searchable list of the project's sources.** In Settings › Work
Intake, the value of **Repository, team or project** is a combobox. It
lists the project's linked repositories (`owner/repo` on GitHub,
`group/project` on GitLab), then the team keys of the Linear teams and
projects bound to it, then the keys of its bound Jira projects. All of
this comes from data the UI already loads (`/web/factory/projects`,
`/web/intake/bindings`, `/web/linear/{projects,teams}`,
`/web/jira/projects`), and the Linear and Jira lists are only fetched
when the project has a binding for them. No new endpoint.
- **Narrowed by provider.** When the condition's own AND group, or an
AND group around it, limits `source.integration` or `source.provider`
with **is** or **is any of**, only those providers' values are offered.
A limit in an OR group doesn't count, since a card meets only one
branch. A key two providers share (Linear and Jira `ENG`) shows once.
- **Free typing still works.** The search box offers `Use "<text>"` for
any value not in the list, after the suggestions it matches, so typing
`mastra` and pressing Enter picks `mastra-ai/mastra`; with no match it's
the only option. The control is the same before and after suggestions
load, so a value being typed is kept. Saved values that aren't listed
still show. With **is any of** / **is none of** you can pick several.
The empty trigger reads `owner/repo, ENG, PLAT`. A project with nothing
to suggest gets the same picker with an empty list.
- **Bare-name warning.** When every card a condition tests must come
from GitHub or GitLab (the same AND-group limits as the narrowing, from
one shared helper) and the condition requires a repository with no `/`
(**is**, or any value of **is any of**), the editor shows "GitHub
repositories are owner/repo, such as mastra-ai/mastra." (or the GitLab
equivalent). **contains** / **is not** / **is none of** stay quiet,
since those can still match.
- **README:** the `source.repository` row gives each provider's exact
format and says the comparison ignores case. incident.io items have none
(test `source.provider equals incidentio`), and manual cards have no
`source.*` facts (test `source.kind not_exists`).
`main` replaced the playground-ui `RuleBuilder` in this editor with
factory-ui's own condition rows (#29978). The earlier playground-ui
`examples` placeholder change and its changeset are therefore gone, and
this PR only touches factory-ui and the Factory README.
## Screenshots
<img width="1280" height="900" alt="repository-picker-desktop"
src="https://github.com/user-attachments/assets/60483565-0a47-4ded-88b8-d74f4cfc3da2"
/>
This image predates
|
||
|
|
e60ea1f681 |
fix(factory): rebuild environment templates on push for Platform GitHub (#30135)
Factories connected to GitHub through Mastra Platform never rebuilt
their sandbox template on push, even with build-on-push turned on.
Sessions kept starting from whatever template was built last, so they
spent time fetching and checking out weeks of commits (and
`last_push_build_at` stayed null).
On the Platform lane GitHub events only reach Factory through the
polling event worker. The worker's integration context was built without
the `onRepositoryPush` hook (only the routes context had it), so
`GithubRules` dropped every default-branch push. This passes the hook
into the worker context too:
```ts
// factory.ts, integration worker context
...(this.#environmentBuilds ? { onRepositoryPush: this.#environmentBuilds.onRepositoryPush } : {}),
```
The new test in `event-worker.lifecycle.test.ts` boots a real
`MastraFactory` with `PlatformGithubIntegration`, polls a `push` event
from a stubbed Platform event log, and checks that the build starts,
`lastPushBuildAt` is recorded and the active template is pinned to the
new head. It fails without the fix and passes with it on both LibSQL and
Postgres 16 (`FACTORY_TEST_STORAGE_BACKEND=postgres`).
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
ELI5: When someone pushes new code to a Factory's GitHub repository, the
Factory now rebuilds its sandbox template. New sessions then start from
the latest code, not an old copy.
## Summary
This PR fixes build-on-push for Factories connected to GitHub through
Mastra Platform. Platform GitHub events reach Factory through the
polling event worker. That worker did not receive the `onRepositoryPush`
hook, so default-branch pushes did not trigger an environment build.
## Changes
- `mastracode/factory/src/factory.ts`: When `#environmentBuilds` exists,
`MastraFactory.prepare()` adds `onRepositoryPush` to the integration
context used to build each ready integration's workers. When no
environment build runner exists, the property is omitted. The change is
two added lines, placed beside the existing optional
`sourceControlOwnerId: 'github'` entry.
- `mastracode/factory/src/integrations/platform/github/event-worker.ts`:
Comments only. They now describe default-branch pushes as triggering
environment-template rebuilds, and they name
`GithubRules.onRepositoryPush` as the hand-off. The comments no longer
refer to base-checkpoint rebuilds or `withBaseCheckpointWebhookTrigger`.
No executable behavior changed.
-
`mastracode/factory/src/integrations/platform/github/event-worker.lifecycle.test.ts`:
Adds 143 lines. The test adds PostgreSQL test-storage support and a mock
sandbox that records build starts and returns a ready template. It
configures a project for push builds with a 60-minute debounce, links
its default-branch repository, and polls a stubbed GitHub push event. It
checks that the project is marked as having a push build, that an
environment build starts, and that the resulting template becomes active
with the pushed commit SHA recorded as the repository head. Cleanup
closes storage and stops workers.
- `.changeset/free-horses-grin.md`: Adds a patch changeset for
`@mastra/factory`.
## Test results
The author reports that the new test fails without the change and passes
with it. The author reports this on LibSQL and on Postgres 16 with
`FACTORY_TEST_STORAGE_BACKEND=postgres`. This review did not run the
tests. CI status is not available.
## Diff scope
4 files changed, 153 lines added, 3 lines removed.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
|
||
|
|
ddf1c08cf6 |
perf(factory): ⌘K asks the server for matching cards instead of downloading the board (#30081)
Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local> Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
2d4284603a |
Fix MCP core compatibility, Windows browser paths, and AI SDK tool titles (#30125) | ||
|
|
834c0c5635 |
fix(factory): honor board triage routes and return labeled cards to Intake (#30100) | ||
|
|
9497c2edfb |
test(mastracode): make schedules multi-line e2e scenario independent of the clock (#30128)
## Summary The `schedules-multiline-prompt` TUI e2e scenario failed depending on the time of day. The `/schedules` picker cuts each row off at the dialog width, and the row label's length changes with the clock: the next-fire time includes a date when it falls on another day, and the countdown (`in 5s` vs `in 59m 59s`) changes width. When the label got long enough, the end of the schedule summary was cut off and the "whole summary is visible on one row" check failed. This happened on `main` and on unrelated PRs. The scenario now resizes the terminal to 160 columns, which leaves room for the longest possible label plus the full summary. The test still proves the same things: each schedule takes exactly one row while arrowing through the picker, rows aren't duplicated or wrapped, and the whole summary is visible. A summary with line breaks would still split the row at any width. No product code changes. ## Test plan - [x] Reproduced the failure by running the scenario with `MC_E2E_COLUMNS=114`: the summary was cut off the same way it was in CI. - [x] With the fix, the scenario passes at `MC_E2E_COLUMNS` 80, 114 and 120. - [x] `schedules-multiline-prompt` and `schedules-command` passed 5 runs in a row. - [x] `pnpm --filter ./mastracode/tui lint` and `check` pass, and `oxfmt --check` is clean. Co-authored-by: CalebBarnes <CalebBarnes@users.noreply.github.com> Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
8ea9c0e552 |
fix(factory): surface incomplete working-phase runs instead of marking them successful (#30101) | ||
|
|
9e82af0237 |
chore: version packages (alpha) (#30074)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
4cfa256801 |
feat(coding-agent): link Linear issues with Fixes lines in PR descriptions (#30112) | ||
|
|
0b3514eb8a |
fix(code-sdk): keep schedule summaries on one line (#30108)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
38327de07a |
Avoid Event-Loop Stalls in Instruction Lookup (#30104) | ||
|
|
9efd1ea8df |
fix(factory): report a missing schedule cron as null (#30098)
Schedules can now be one-off runs with no cron expression (#25131), so `schedule.cron` is optional. The Factory environment build schedule view still assigned it to a `string | null` field, which fails the `@mastra/factory` typecheck on `main`. The view now reports a missing cron as `null`, the same as when there is no schedule. ## Test plan - [x] `tsc --noEmit` in `mastracode/factory` passes (fails on `main` at `build-schedule.ts:68`) - [x] `vitest run src/environment`: 61 passed <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 When a schedule has no cron expression, Factory now returns `null` instead of an invalid missing value. This supports one-off schedules and matches the declared output type. ## Changes - Updated `toView` to map an undefined `schedule.cron` to `null`. - Added a patch changeset for `@mastra/factory`. ## Testing Not available. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: CalebBarnes <CalebBarnes@users.noreply.github.com> Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
47dfae5d3a |
fix(factory): mint GitHub tokens ten repositories at a time (#30093)
## Summary A Factory with more than ten repositories asked GitHub for one token per repository every time a session started or an environment built, because one token can name at most ten repositories. Rebuilds and a handful of sessions together ran into the per-installation token limit, and a failed request quietly left that repository unsynced. - Sessions, environment builds and branch-head lookups now request access for each group of up to ten repositories once, and serve every repository in the group from that token. Eleven repositories need two tokens instead of eleven. The group token stays with those callers; a lookup for a single repository still gets a token for that repository only. - Minted access is reused for 20 minutes instead of 5. Sessions replace their `GH_TOKEN` after 30 minutes instead of 45, so a reused token is never close to GitHub's 60-minute expiry. - If a group can't be granted, each repository falls back to its own token as before. ## Test plan - [x] New: the Platform GitHub integration serves an eleven-repository environment from two token requests (twelve without this change) - [x] New: a group mint returns each repository's access under the group token, and a later single-repository lookup still gets a single-repository token - [x] New: `groupedRepositoryAccess` falls back to per-repository tokens when a group can't be granted or the group request fails - [x] Updated token refresh tests for the 30-minute refresh - [x] `@mastra/factory` tests, typecheck, oxlint and oxfmt pass <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 Factory now requests shared GitHub tokens for groups of up to ten repositories. This reduces token requests while preserving individual-token fallback when group access is unavailable. ## Changes - Added grouped repository access with deduplication and shared in-flight requests. - Added a 60-second cooldown after failed or unavailable group requests. - Applied grouped access to environment builds, branch-head resolution, and workspace setup. - Extended the version-control contract for multi-repository access. - Increased repository-access token reuse from 5 to 20 minutes. - Updated session `GH_TOKEN` refresh from 45 to 30 minutes. - Added tests for batching, fallback, cooldowns, cache expiry, and token refresh. - Added a patch changeset for `@mastra/factory`. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: CalebBarnes <CalebBarnes@users.noreply.github.com> Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
e909e9dabc |
fix(factory-ui): refresh a session's cards without waiting for the board read (#30083)
**─────── TLDR ───────** > On a Factory session page, the tab title, breadcrumb and pull request links now keep up with live changes while the board is still downloading. Follow-up to #30080, from [Copilot's review there](https://github.com/mastra-ai/mastra/pull/30080#discussion_r4541053905); that PR merged before this fix was pushed. `FeedEventsProvider` invalidated each board key as one read and kept it in flight until every query under it had answered, so the session's small read, keyed under the board key, could refresh only as often as the whole-board read next to it. It now re-reads each query under a key on its own. ### Behavior changed a second card change arrives while the board read is still in flight ├─ **was** — the session's cards stayed on the first change until the board answered └─ **now** — they show it on the next refresh, the board catches up when it answers two decision lists with different status filters, one of them slow ├─ **was** — the fast one waited for the slow one before its next refresh └─ **now** — each refreshes on its own a card move in flight └─ **unchanged** — no card query is re-read until the move lands, board or session a query still reading when the next frame lands └─ **unchanged** — never cancelled, one more read queued behind it ### Decisions - **no changeset** — the session read is unreleased and #30080's `mastra` entry already describes it; one patch entry away if you want it ### Not verified - [ ] a live session page in a browser — it ran under Vitest with MSW only --- > ██████████████████ **tests** `+51 −1` — 80% of the additions > █████ **source** `+13 −11` — one function in `FeedEventsProvider` <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 Session cards now refresh without waiting for the whole board to finish loading. Each query refreshes independently, so users see card updates sooner. ## Changes - Re-read each cached query under each board key independently. - Track in-flight reads by `query.queryHash`. - Invalidate each query with its exact query key. - Preserve the card-move guard and one-queued-reread behavior. - Add an MSW/Vitest test for repeated session card updates while the board request remains pending. ## Test status Execution result: not available. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local> |
||
|
|
cd30020f7a |
feat(factory): read the sidebar's cards with ?scope=sessions (#30087)
**─────── TLDR ───────** > Away from a board, the Factory sidebar now reads only the cards holding a session, through a new `?scope=sessions`, so a session page no longer downloads the whole board. Step 2 of taking the full-board read out of the UI. After #30080 the sidebar was the last thing on a session page still downloading the board: it uses the cards to mark each session row with its card's source and to say which sessions wait on a person. The list route now takes `scope=sessions` and answers with every card holding a session plus the cards related to them, in the same shape, and the sidebar reads that. On a page that loads the board anyway (the board pages, and the new-session draft, whose starters and activity read it) the sidebar keeps sharing that one read, as it does on main. The board used to arrive on every page through the sidebar's route loader; it now starts from the loaders of those pages. ⌘K still reads the whole board when it opens. Those are the next PRs. ### Behavior changed a session page, Rules, a new session ├─ **was** — the sidebar downloads the whole board to mark its sessions └─ **now** — it asks for the cards holding a session; the board is not requested going from one of those pages to a board ├─ **was** — the board is already loaded, cards show at once └─ **now** — the board loads when its page opens; the sidebar keeps its marks meanwhile going from a board back to one of those pages ├─ **was** — no request └─ **now** — the sidebar asks for the cards holding a session, marked from the board until they answer `GET …/work-items?scope=sessions` └─ **new** — cards holding any session and their related cards, in board order `scope` with any other value, or sent together with `sessionId` └─ **new** — 400 `invalid_scope`, never the whole board a board page, a new-session draft └─ **unchanged** — one board read, shared by the page and the sidebar ⌘K └─ **unchanged** — still reads the whole board ### Shape changed | | | | |---|---|---| | **+** | `allSessionCards(board)` | picks the scope's cards, kept once per board version | | **~** | `sessionCards` | shares `withRelatedCards` with it, same result | | **~** | `scopedSnapshot` | serialized once per card list; its ETag still names the body | | **~** | `listWorkItems(…, only)` | fourth argument takes `{ sessionId }` or `{ scope }` | | **~** | `boardQueryOptions(…, scope)` | third argument `'sessions'` narrows the board to the scope | | **+** | `pageLoadsBoard(pathname)` | names the pages that load the board themselves | | **+** | `useSidebarWorkItemsQuery` | the board on those pages, the scope elsewhere | | **+** | `prefetchDraft` | the draft's loader: the composer's queries plus the board | what the reviewer now lives with `?scope=sessions` on `workItemList` · `workItemListQuerySchema.scope` · error `invalid_scope` · `queryKeys.workItemsWithSessions(projectId)` · `pageLoadsBoard` ### Decisions - **a scope the server resolves, not the sidebar's session ids** — the ids come from another request and have no upper bound; repeated `sessionId` already works if you'd rather not add the param - **which list the sidebar reads is decided from the URL** — `pageLoadsBoard` is a path pattern next to `isSettingsPath`, because the sidebar's loader only gets the URL; a new page that loads the board has to be added to it, or it downloads both lists; `AppStartup` checks the four pages there are today - **between its two lists the sidebar borrows the other one from the cache, not `keepPreviousData`** — the previous data could be another Factory's cards after switching Factory ### Cost Moving from a board to a session page now sends one request where main sent none. A board opened from a session page is no longer already in memory: its columns wait for the read. The sidebar's list takes a write only for a card it already holds, so a card that gains its first session reaches it with the next refetch, not from the mutation's response. The scope also returns cards held only by a teammate's private session, which the sidebar has no row for. On the server the scoped list is picked and serialized once per board version and shared by every tab. ### Watch on deploy: nothing to migrate, and tabs loaded before the deploy keep reading the whole board from the sidebar. Worth a look afterwards: unscoped `GET …/work-items` should drop to board pages, drafts and ⌘K. Also the size of `?scope=sessions` next to the whole board. A card keeps its session until that session is deleted, so the scoped list grows with every card a session has worked: on a board where most cards have been, the two are nearly the same download and the sidebar needs paging instead. ### Not verified - [ ] a real large board — sizes and timings; the tests use a handful of cards - [ ] a live browser — everything ran under Vitest with MSW - [ ] moving between a session page and a board through the real router — the test drives the sidebar alone, behind a plain link - [ ] `AppStartup` on my machine — its 8 route cases fail on a late `GET /web/status`, on main too; with that request masked all 11 pass --- > ██████████████████ **tests** `+216 −40` — 55% of the additions > ████████████ **source** `+142 −54` > █ **changeset** `+16` > █ **generated** `+15` > █ **docs** `+1 −1` <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 The Factory sidebar now loads only cards connected to sessions when it does not need the full board. This reduces unnecessary data loading while keeping session card sources and waiting indicators accurate. ## Changes - Added `scope=sessions` to the Factory work-item list API. - Scoped results include session cards, related cards, and linked pull requests in board order. - Reject invalid scopes and `scope` combined with `sessionId` with `400 invalid_scope`. - Shared related-card selection through `withRelatedCards` and cached `allSessionCards`. - Added scoped ETag and snapshot caching that ignores changes outside the scoped cards. - Added scoped query keys, request handling, and `useSidebarWorkItemsQuery`. - Use the full board on board pages and session-scoped cards elsewhere. - Added placeholder data when switching between the full-board and scoped queries. - Added board and draft prefetching, including immediate board prefetches. - Use a parked-session ID set for sidebar lookups. - Updated API documentation, generated route metadata, and changesets. - Expanded route, startup, sidebar icon, and session filtering tests. ## Validation - Test execution results are not available. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local> |
||
|
|
1c4c4b37f9 |
fix(factory): show source-only card changes on the next board reload (#30042)
## Description **─────── TLDR ───────** > A card whose labels, state or title changed without its own row moving now shows on the next board reload instead of up to a minute later. Since #30041 a board reload rereads only the cards whose `changed_at` moved. Three writes change what a card shows without moving it, so the board kept the old card until the 60 s full read. Each one is a test here that fails on `main`. ### Behavior changed a provider sync changes an issue's labels or state, the card stays where it is ├─ **was** — old labels and state for up to 60 s └─ **now** — shown on the next reload a card that has a source gets a new title ├─ **was** — old title for up to 60 s └─ **now** — shown on the next reload a project's last open Review card closes ├─ **was** — its other Review cards stay on Review for up to 60 s └─ **now** — they read as Work on the next reload ### Decisions - **a source sync locks the card's row before its source** — every card write takes them in that order, and stamping after the source would invert it; one read and one lock per sync - **a board that shows Review cards is reread whole** — one write there moves cards it never touched; only projects still on the retired board pay ### Not verified - [ ] on Postgres: ran on LibSQL only, the lock order comes from reading the pg store --- > ██████████████████ **tests** `+78` — 73% of the additions > █████ **source** `+24 −5` > █ **changeset** `+5` ## Related issue(s) Follow-up to #30041. ## Type of change - [x] Bug fix (non-breaking change that fixes an issue) ## Checklist - [x] I have added tests that prove my fix is effective or that my feature works 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local> Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> |
||
|
|
067314bcb3 |
perf(code-sdk): cache base-branch instruction reads by git object in review sessions (#29551)
**─────── TLDR ───────** > A review session on an untrusted checkout stops running a git process for every instruction file on every model step, which blocked every session in the same process. On an untrusted checkout, `AGENTS.md` and `CLAUDE.md` are read from the base branch with synchronous `git` calls. Each step rebuilt the prompt and ran the reminder check, and the reminder check loaded the instructions again for every file it looked at. Reads are now cached by git object id: each folder's listing by its tree, the content by blob. Ids are content-addressed, so a cached read cannot go stale, and a file the base branch did not touch is not read again when it moves. The cache is shared by every session in the process, so nothing is cached until it matches its id: git checks each folder it lists, and the reader hashes file content itself. The injector also loads the instruction paths it skips once per step instead of once per file. ### Behavior changed each model step of a review session, 8 folders touched ├─ **was** — 107 git processes, each blocking the event loop └─ **now** — 3: the ref lookups; file reads come from the cache the base branch moves during a session └─ **unchanged** — the ref resolves every step, so an edited file is read again a file a blobless clone failed to fetch └─ **unchanged** — retried on the next step; failures are never cached a checkout with a `git replace` ref on an instruction file ├─ **was** — that checkout read the replacement └─ **now** — read as committed, so the cache cannot carry it to other checkouts a checkout whose `.git/objects` holds a rewritten instruction file or folder ├─ **was** — that checkout read the rewritten content └─ **now** — read as absent, so the cache cannot carry it to other checkouts ### Tradeoff Real injector and prompt load on this repo, main → this branch, 8 folders touched: > git calls per settled step — `107 → 3` > git calls until a new session settles — `368 → 114` > first step after the base branch moves a commit — `107 → 20` > first step of a fresh process — `14 → 16` > settled step time in the test harness — `0.4–0.5 s → 0.02 s` The fresh-process step pays for listing each folder on its own, which is what lets git check it. It happens once per process, and its time stayed within noise. ### Decisions - **listings cached per folder, content by blob, successes only, capped at 16 MB** — ids never change, so entries never go stale; a failed fetch retries - **entries checked against their id before caching** — the cache spans checkouts; keying it per checkout is the undo, and loses the sharing - **`getIgnoredInstructionPaths` called once per step, in core** — it ran per candidate file; same set, computed lazily once ### Not verified - [ ] a live Factory review session — measured with the real injector on this repo --- > ██████████████████ **tests** `+200 −1` > █████████ **source** `+100 −37` — net +63 > █ **changeset** `+10` <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 The assistant now reuses verified Git data when it reads instruction files from a branch. This reduces repeated Git work while keeping untrusted checkout content out of the review, and it checks ignored paths only once per processing step. ## Summary - Cache Git tree listings and blob contents by object identity. - Limit cached keys and outputs to 16 MiB with oldest-first eviction. - Cache only successful reads that pass identity checks. - Resolve files from `origin/<ref>` first, then `<ref>`. - Retry failed reads and reread files when the base branch changes. - Use `--no-replace-objects` to isolate checkouts from replace refs. - Load ignored instruction paths once per processor request. - Add tests for caching, cache eviction, ref handling, retries, tampered objects, checkout isolation, and ignored-path loading. **Changes:** 6 files; 310 lines added and 38 removed. **CI, build, and test results:** not available. **Review finding counts:** not available. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local> |
||
|
|
005b6f0247 |
feat(factory): list one session's cards with ?sessionId= (#30080)
**─────── TLDR ───────** > A Factory session page now asks for its own cards with `?sessionId=`, so its tab title, breadcrumb and pull request links stop waiting for the whole board. On a large board the work-item list is the biggest download the UI makes, and three places on a session page read all of it to find one card. The list route now takes an optional, repeatable `sessionId` and answers with the cards holding those sessions plus the cards related to them, in the same shape. `PageTitle`, `StatusLine` and `RelatedFactorySessions` read that instead. This is step 1 of taking the full-board read out of the UI. The sidebar still loads the board on these pages until the next PR, so total bytes on a session page don't drop yet. ### Behavior changed a session page while the board is still downloading ├─ **was** — tab title, breadcrumb and PR links wait for the whole board └─ **now** — they show as soon as the session's own cards arrive `GET …/work-items?sessionId=a&sessionId=b` └─ **new** — cards holding those sessions and their related cards, in board order a card outside that scope changes └─ **new** — the scoped read gets a 304, its ETag hashes the body a `sessionId` that is empty or longer than 512 characters └─ **new** — 400 `invalid_session_id`, never the whole board `GET …/work-items` with no `sessionId` └─ **unchanged** — the whole board, same ETag and gzip path ### Shape changed | | | | |---|---|---| | **+** | `relatedCardIndex(cards, facts)` | extracted from the UI so the server scope uses the same rules | | **~** | `relatedWorkItemIndex` | now a wrapper over it, same signature, callers untouched | | **+** | `scopedSnapshot` | sibling of `boardSnapshot`, with a body-hash ETag | | **+** | `useSessionWorkItemsQuery` | the scoped read, keyed under the board key | what the reviewer now lives with `?sessionId=` on `workItemList` · `workItemListQuerySchema` · `@mastra/factory/work-items/related-cards` · `queryKeys.sessionWorkItems(projectId, sessionId)` ### Decisions - **related cards ride along in the scoped answer** — the header's related links read them; drop the second pass in `sessionCards` to return holders only - **scoped key nested under the board key** — feed invalidation and the board's optimistic writes reach it unchanged; a sibling key would need each wired again - **no cap on repeated `sessionId`** — the sidebar PR knows the real count; one `.max()` on the schema then ### Cost Until the sidebar moves, a session page makes one request more than before: the scoped read, next to the board read the sidebar still makes, and again on each feed event (a 304 when its cards didn't change). The server still loads the cached board to answer it, then stringifies and hashes the picked cards on every request. ### Watch on deploy: nothing to migrate, and tabs loaded before the deploy keep calling the unscoped route. Worth a look afterwards: response size and duration of `GET …/work-items` with and without `sessionId`. The unscoped count per session page stays flat until the sidebar PR. ### Not verified - [ ] a real large board — sizes and timings; the tests use a handful of cards - [ ] a live session page in a browser — the three surfaces ran under Vitest with MSW only --- > ██████████████████ **tests** `+358 −53` — 58% of the additions > ███████████ **source** `+223 −96` — 57 of the removed lines are relation logic leaving the UI > █ **generated** `+18 −2` — CLI route metadata > █ **changeset** `+16` > █ **docs** `+2` <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 A session page can now request only the work-item cards connected to its session. This lets page details load without waiting for the full board request. ## Changes - Added repeatable `sessionId` filtering to the work-item list route. - Returns matching cards and related parents, children, and pull requests in board order. - Returns `400 invalid_session_id` for invalid session IDs. - Added scoped snapshots with body-based weak ETags and conditional `304` responses. - Extracted shared relationship logic into `relatedCardIndex`. - Added session-scoped React Query keys, requests, and cache updates. - Updated page titles, status lines, related sessions, and pull-request links to use scoped cards. - Preserved unscoped board behavior. - Added route, hook, and UI test coverage, documentation, changesets, and generated route metadata. ## Known limitation The sidebar still loads the full board. The scoped request adds another request and still reads the cached board server-side. ## Validation Test execution status: not available. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local> |
||
|
|
ce6ab76fab |
fix(factory): keep Slack statuses under Slack's 50-character limit (#30082)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
7b862c93e7 |
perf(factory): read active runs from the feed stream instead of polling every 5s (#30077)
Co-authored-by: Damien Schneider <damienschneider@damiens-MacBook-Pro.local> Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |
||
|
|
3a6ca42696 |
chore: version packages (alpha) (#30026)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
9ee332c1fd |
feat(ui): rounded squircle favicon for Studio, Factory and docs (#30040)
The tab icon gets rounded corners, matching the rounded style used everywhere else in the UI. Today's tile has a 5% corner radius, which reads as a plain square at 16px. The new tile is a squircle (superellipse, n=7), the smooth corner shape app icons use. The logo is at 80% of the tile width and centered, so it has a little room from the corners. ## Before / After | Before | After | | --- | --- | | <img src="https://github.com/user-attachments/assets/de26b6ac-83db-4212-9a46-a73b36daa714" width="400" alt="Before"> | <img src="https://github.com/user-attachments/assets/d1f885ba-c647-4fa6-9a7d-58e7b72dcf02" width="400" alt="After"> | ## What changed - Studio (`mastra-dark-tile.svg`, green dev variant), Factory (`mastra.svg`, `mastra-dev.svg` and the four session status icons) and the docs `favicon.ico` all come from the same source, so they stay identical. - Factory's status dot still sits on the logo's bottom-left dot. - `mastra studio` now serves `/mastra-dark-tile.svg` as a file. It still checked for the old `/mastra.svg` name, so the tab got the page HTML instead of the icon. ## Scope - Factory's PWA and apple-touch PNGs stay as they are: the OS masks those itself, so a rounded tile inside them would look double-rounded. - Platform and mastra.ai get the same icon in their own PRs. ## Testing 1. Run Studio or Factory: the tab shows the rounded tile (green logo in dev). 2. Factory: open a session, and the colored status dot shows on the same rounded tile. 3. Docs: the tab shows the rounded tile from `favicon.ico`. 4. Run `mastra studio`: the tab shows the rounded tile. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## ELI5 This PR makes the Mastra favicon more rounded across Studio, Factory, and the docs. It also makes Studio serve the correct icon file so browsers display it. ## Changes - Updated Studio, Factory, and Factory session-status SVGs with the rounded tile design. - Replaced the docs `favicon.ico`. - Updated Studio asset handling to serve `/mastra-dark-tile.svg`, including nested paths. - Added a test for serving the Studio favicon instead of the SPA HTML. - Added patch changesets for `mastra` and `@mastra/factory`. ## Validation - Test results: not available. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
32e4bea942 |
perf(factory): reread only changed cards when the board version moves (#30041)
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com> |