From f8c0cdca3aea7855fc5b6a119c775703ec4d8960 Mon Sep 17 00:00:00 2001 From: Damien Schneider <74979845+damien-schneider@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:30:01 -0800 Subject: [PATCH 1/3] feat(factory-ui): show a card's session panel before its first session - A card with no session opens on a draft that now has the panel toggle and docked panel: source, pull request, description, linked pull requests and stage moves. - The panel shows whenever the page has an overview, not only when a workspace exists; a thread whose session failed to load still shows none. - Moved the card part of SessionPanelOverview into CardOverview and the panel shell into PanelFrame so the thread and the draft share them. - Dropped the draft's 'New session' header title, matching a card's session page. --- .../factory/components/CardOverview.tsx | 114 ++++++++++++++++++ .../components/SessionPanelOverview.tsx | 101 +++------------- .../components/PanelFrame.tsx | 10 ++ .../components/WorkspaceFilesContent.tsx | 35 ++++-- .../components/WorkspaceFilesToggle.tsx | 4 +- .../components/WorkspacePanelDock.tsx | 6 +- .../components/WorkspaceViewerPanel.tsx | 15 +-- .../context/WorkspaceFilesProvider.tsx | 5 +- .../context/WorkspacePanelContext.ts | 5 +- .../src/ui/domains/workspace-viewer/layout.ts | 2 +- .../factory-ui/src/ui/pages/CardDraftPage.tsx | 77 +++++++++--- .../factory-ui/src/ui/pages/ThreadPage.tsx | 2 +- .../__tests__/CardDraftPage.msw.test.tsx | 50 +++++++- 13 files changed, 295 insertions(+), 131 deletions(-) create mode 100644 mastracode/factory-ui/src/ui/domains/factory/components/CardOverview.tsx create mode 100644 mastracode/factory-ui/src/ui/domains/workspace-viewer/components/PanelFrame.tsx diff --git a/mastracode/factory-ui/src/ui/domains/factory/components/CardOverview.tsx b/mastracode/factory-ui/src/ui/domains/factory/components/CardOverview.tsx new file mode 100644 index 00000000000..d94335e6aa3 --- /dev/null +++ b/mastracode/factory-ui/src/ui/domains/factory/components/CardOverview.tsx @@ -0,0 +1,114 @@ +import { useClock } from '@mastra/playground-ui/hooks/use-clock'; + +import type { InstalledBoardInfo } from '../../../../api/types'; +import { useFactoryQuery } from '../../../../hooks/useFactories'; +import type { WorkspaceSlot } from '../../workspace-viewer/context/WorkspacePanelContext'; +import type { LinkedRepositoryPayload } from '../../workspaces/services/github'; +import { boardOf } from '../boardFlow'; +import { cardProjectRepositoryId } from '../boardRepository'; +import { changeRequestsNoun } from '../changeRequestState'; +import { ownChangeRequest, sessionChangeRequests } from '../sessionChangeRequests'; +import type { PullRequestSubscription } from '../services/githubSubscriptions'; +import { relatedWorkItemIndex } from '../services/relationships'; +import { genericExternalWorkItemUrl } from '../services/workItemPresentation'; +import type { WorkItem } from '../services/workItems'; +import { toMinute } from '../stageStays'; +import { CardDescription } from './CardDescription'; +import { CardSourceRow } from './CardSourceRow'; +import { ChangeRequestLink } from './ChangeRequestLink'; +import { ChangeRequestList } from './ChangeRequestList'; +import { MovesGraph } from './MovesGraph'; +import { RelatedCards } from './RelatedCards'; +import { SectionLoadError } from './SectionLoadError'; + +export const overviewSectionClass = 'flex flex-col gap-3 p-1.5 pb-3'; + +export function CardOverview({ + item, + sessionItems, + factoryId, + boards, + boardsFailed, + repository, + repositoryFailed, + subscriptions, + pullRequestsFailed, + workspace, +}: { + item: WorkItem; + sessionItems: readonly WorkItem[]; + factoryId: string; + boards: readonly InstalledBoardInfo[] | undefined; + boardsFailed: boolean; + repository: LinkedRepositoryPayload | undefined; + repositoryFailed: boolean; + subscriptions: readonly PullRequestSubscription[]; + pullRequestsFailed: boolean; + workspace?: WorkspaceSlot; +}) { + const factoryQuery = useFactoryQuery(factoryId); + const now = useClock(toMinute); + const provider = repository?.provider ?? 'github'; + const related = relatedWorkItemIndex(sessionItems)(item); + const ownRequest = ownChangeRequest(item, repository?.slug, subscriptions); + const ownRequestLink = ownRequest ? ( + + ) : undefined; + const sourceUrl = genericExternalWorkItemUrl(item); + const requests = sessionChangeRequests({ + item, + subscriptions, + provider, + shownElsewhere: [sourceUrl, ownRequest?.url], + }); + const requestsNoun = changeRequestsNoun(repository ? [provider] : requests.map(request => request.provider)); + const moved = item.stageHistory.some(entry => entry.exitedAt); + const showsPhases = related.length > 0 || moved; + + return ( + <> +
+ {workspace ? null : ownRequestLink} + + +
+ {workspace?.({ + repository: repository && { slug: repository.slug, provider }, + changeRequest: ownRequestLink, + })} + {pullRequestsFailed || requests.length > 0 || showsPhases ? ( +
+ + {pullRequestsFailed ? ( + + {requests.length > 0 + ? `Couldn't load the session's ${requestsNoun}, so this list may be out of date.` + : `Couldn't load ${requestsNoun}.`} + + ) : null} + + {boardsFailed && showsPhases ? ( + Couldn't load the board, so phases aren't shown. + ) : moved ? ( + + ) : null} +
+ ) : null} + + ); +} diff --git a/mastracode/factory-ui/src/ui/domains/factory/components/SessionPanelOverview.tsx b/mastracode/factory-ui/src/ui/domains/factory/components/SessionPanelOverview.tsx index cbd635e2e91..cab72d5fe92 100644 --- a/mastracode/factory-ui/src/ui/domains/factory/components/SessionPanelOverview.tsx +++ b/mastracode/factory-ui/src/ui/domains/factory/components/SessionPanelOverview.tsx @@ -1,37 +1,21 @@ -import { useClock } from '@mastra/playground-ui/hooks/use-clock'; -import type { ReactNode } from 'react'; import { useParams } from 'react-router'; import { SkeletonRows } from '../../../ui/SkeletonRows'; -import { useFactoryQuery } from '../../../../hooks/useFactories'; -import type { WorkspaceSectionSlots } from '../../workspace-viewer/context/WorkspacePanelContext'; -import { cardProjectRepositoryId } from '../boardRepository'; +import type { WorkspaceSlot } from '../../workspace-viewer/context/WorkspacePanelContext'; import { changeRequestsHeading, changeRequestsNoun } from '../changeRequestState'; import { useSessionCard } from '../hooks/useSessionCard'; import { useSessionSubscriptions } from '../hooks/useSessionSubscriptions'; -import { ownChangeRequest, sessionChangeRequests } from '../sessionChangeRequests'; -import { relatedWorkItemIndex } from '../services/relationships'; -import { genericExternalWorkItemUrl } from '../services/workItemPresentation'; -import { toMinute } from '../stageStays'; -import { CardDescription } from './CardDescription'; -import { CardSourceRow } from './CardSourceRow'; -import { ChangeRequestLink } from './ChangeRequestLink'; +import { sessionChangeRequests } from '../sessionChangeRequests'; +import { CardOverview, overviewSectionClass } from './CardOverview'; import { ChangeRequestList } from './ChangeRequestList'; -import { MovesGraph } from './MovesGraph'; -import { RelatedCards } from './RelatedCards'; import { SectionLoadError } from './SectionLoadError'; -const sectionClass = 'flex flex-col gap-3 p-1.5 pb-3'; - // Must render inside `ChatSessionBoundary`: the subscriptions follow the chat session. -export function SessionPanelOverview({ workspace }: { workspace: (slots?: WorkspaceSectionSlots) => ReactNode }) { +export function SessionPanelOverview({ workspace }: { workspace: WorkspaceSlot | undefined }) { const { factoryId } = useParams<{ factoryId: string }>(); const { session, links } = useSessionSubscriptions(); const { repository, provider } = session; - const workspaceRepository = repository && { slug: repository.slug, provider }; - const factoryQuery = useFactoryQuery(factoryId); const card = useSessionCard(); - const now = useClock(toMinute); const pullRequestsFailed = session.failed || links.failed; // All at once: a section arriving late would push down the ones under it. @@ -45,13 +29,13 @@ export function SessionPanelOverview({ workspace }: { workspace: (slots?: Worksp return ( <> {card.failed ? ( -
+
Couldn't load the card.
) : null} - {workspace({ repository: workspaceRepository })} + {workspace?.({ repository: repository && { slug: repository.slug, provider } })} {pullRequestsFailed || requests.length > 0 ? ( -
+
{pullRequestsFailed ? ( {`Couldn't load ${changeRequestsNoun(providers)}.`} ) : ( @@ -63,65 +47,18 @@ export function SessionPanelOverview({ workspace }: { workspace: (slots?: Worksp ); } - const item = card.item; - const related = relatedWorkItemIndex(card.sessionItems)(item); - const ownRequest = ownChangeRequest(item, repository?.slug, links.subscriptions); - const sourceUrl = genericExternalWorkItemUrl(item); - const requests = sessionChangeRequests({ - item, - subscriptions: links.subscriptions, - provider, - shownElsewhere: [sourceUrl, ownRequest?.url], - }); - const requestsNoun = changeRequestsNoun(repository ? [provider] : requests.map(request => request.provider)); - const moved = item.stageHistory.some(entry => entry.exitedAt); - const showsPhases = related.length > 0 || moved; - return ( - <> -
- - -
- {workspace({ - repository: workspaceRepository, - changeRequest: ownRequest ? ( - - ) : undefined, - })} - {pullRequestsFailed || requests.length > 0 || showsPhases ? ( -
- - {pullRequestsFailed ? ( - - {requests.length > 0 - ? `Couldn't load the session's ${requestsNoun}, so this list may be out of date.` - : `Couldn't load ${requestsNoun}.`} - - ) : null} - - {card.boardsFailed && showsPhases ? ( - Couldn't load the board, so phases aren't shown. - ) : moved ? ( - - ) : null} -
- ) : null} - + ); } diff --git a/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/PanelFrame.tsx b/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/PanelFrame.tsx new file mode 100644 index 00000000000..ee456db02f5 --- /dev/null +++ b/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/PanelFrame.tsx @@ -0,0 +1,10 @@ +import type { ReactNode } from 'react'; + +export function PanelFrame({ subject, children }: { subject: ReactNode; children: ReactNode }) { + return ( +
+
{subject}
+ {children} +
+ ); +} diff --git a/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/WorkspaceFilesContent.tsx b/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/WorkspaceFilesContent.tsx index a3fb9cd5d71..65e69e6f46b 100644 --- a/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/WorkspaceFilesContent.tsx +++ b/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/WorkspaceFilesContent.tsx @@ -3,7 +3,9 @@ import { useParams } from 'react-router'; import { useRouteSessionId } from '../../../../hooks/useRouteSessionId'; import { workspacePanelKey } from '../context/WorkspacePanelContext'; import { useWorkspacePanel } from '../context/useWorkspacePanel'; +import { overviewClass } from '../layout'; import type { WorkspacePanelSize } from '../layout'; +import { PanelFrame } from './PanelFrame'; import { WorkspaceViewerPanel } from './WorkspaceViewerPanel'; export function WorkspaceFilesContent({ @@ -17,20 +19,27 @@ export function WorkspaceFilesContent({ const { workspacePath, threadId, readsChanges, page } = panel; const { factoryId } = useParams<{ factoryId: string }>(); const sessionId = useRouteSessionId(); - if (!workspacePath || !threadId) return null; + if (workspacePath && threadId) { + return ( +
+ +
+ ); + } + if (!page) return null; return ( -
- -
+ +
{page.overview(undefined)}
+
); } diff --git a/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/WorkspaceFilesToggle.tsx b/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/WorkspaceFilesToggle.tsx index d89f9e7e8aa..db45435c28f 100644 --- a/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/WorkspaceFilesToggle.tsx +++ b/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/WorkspaceFilesToggle.tsx @@ -10,10 +10,10 @@ import { WorkspaceFilesContent } from './WorkspaceFilesContent'; import { IconSidebarSimpleRightWide } from '@mastra/playground-ui/icons/central/IconSidebarSimpleRightWide'; export function WorkspaceFilesToggle() { - const { open, setOpen, workspacePath, canDock } = useWorkspacePanel(); + const { open, setOpen, hasContent, canDock } = useWorkspacePanel(); const [size, setSize] = useState('compact'); - if (!workspacePath) return null; + if (!hasContent) return null; const setPopoverOpen = (next: boolean) => { if (next) setSize('compact'); diff --git a/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/WorkspacePanelDock.tsx b/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/WorkspacePanelDock.tsx index 0960e1554fe..77cdc2b2660 100644 --- a/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/WorkspacePanelDock.tsx +++ b/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/WorkspacePanelDock.tsx @@ -18,11 +18,11 @@ function measureCapsule(capsule: HTMLDivElement) { export function WorkspacePanelDock({ children }: { children: ReactNode }) { const panel = useWorkspacePanel(); - const Dock = panel.workspacePath ? 'aside' : 'div'; + const Dock = panel.hasContent ? 'aside' : 'div'; return ( {children} - {panel.workspacePath && } + {panel.hasContent && } ); } diff --git a/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/WorkspaceViewerPanel.tsx b/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/WorkspaceViewerPanel.tsx index b66aae9dd91..80de1d9e5ca 100644 --- a/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/WorkspaceViewerPanel.tsx +++ b/mastracode/factory-ui/src/ui/domains/workspace-viewer/components/WorkspaceViewerPanel.tsx @@ -1,6 +1,5 @@ import { Button } from '@mastra/playground-ui/components/Button'; import { Tab, TabContent, TabList, Tabs } from '@mastra/playground-ui/components/Tabs'; -import { cn } from '@mastra/playground-ui/utils/cn'; import { memo, useState } from 'react'; import type { ReactNode } from 'react'; import type { UseQueryResult } from '@tanstack/react-query'; @@ -10,9 +9,10 @@ import { useWorkspaceChanges, useWorkspaceFile } from '../../../../hooks/use-fs' import { useFactoryQuery } from '../../../../hooks/useFactories'; import { useUserSessionQuery } from '../../../../hooks/useWorkspaces'; import type { WorkspacePanelPage, WorkspaceSectionSlots } from '../context/WorkspacePanelContext'; -import { overviewScrollClass } from '../layout'; +import { overviewClass } from '../layout'; import type { WorkspacePanelSize } from '../layout'; import type { RepositoryProviders } from './changes/tree/change-tree'; +import { PanelFrame } from './PanelFrame'; import { PanelSubject } from './PanelSubject'; import { RecreateSandboxAction } from './RecreateSandboxAction'; import { WorkspaceChangesPanel } from './WorkspaceChangesPanel'; @@ -151,14 +151,9 @@ export const WorkspaceViewerPanel = memo(function WorkspaceViewerPanel({ ); return ( -
-
- {page ? page.subject(back) : } -
+ }> {view.type === 'overview' ? ( -
- {page ? page.overview(workspace) : workspace()} -
+
{page ? page.overview(workspace) : workspace()}
) : null} {view.type === 'changes' || view.type === 'files' ? (
) : null} - + ); }); diff --git a/mastracode/factory-ui/src/ui/domains/workspace-viewer/context/WorkspaceFilesProvider.tsx b/mastracode/factory-ui/src/ui/domains/workspace-viewer/context/WorkspaceFilesProvider.tsx index 74fef160ee5..8b73e89abd6 100644 --- a/mastracode/factory-ui/src/ui/domains/workspace-viewer/context/WorkspaceFilesProvider.tsx +++ b/mastracode/factory-ui/src/ui/domains/workspace-viewer/context/WorkspaceFilesProvider.tsx @@ -38,13 +38,14 @@ export function WorkspaceFilesProvider({ page, children }: { page?: WorkspacePan const readsChanges = panelToggle?.open === true || (Boolean(workspacePath) && awakeWorkspace === workspacePath); const setOpen = (next: boolean) => setToggled({ layoutRevision, open: next }); - const docked = open && canDock && Boolean(workspacePath); + const hasContent = Boolean(workspacePath) || page !== undefined; + const docked = open && canDock && hasContent; const hasDocked = canDock || layoutRevision > 0; const moved = layoutRevision > 0 || toggled !== undefined; return (
ReactNode; + export interface WorkspacePanelPage { subject: (lead: ReactNode | undefined) => ReactNode; - overview: (workspace: (slots?: WorkspaceSectionSlots) => ReactNode) => ReactNode; + overview: (workspace: WorkspaceSlot | undefined) => ReactNode; } export interface WorkspacePanelApi { open: boolean; setOpen: (open: boolean) => void; + hasContent: boolean; workspacePath?: string; threadId?: string; canDock: boolean; diff --git a/mastracode/factory-ui/src/ui/domains/workspace-viewer/layout.ts b/mastracode/factory-ui/src/ui/domains/workspace-viewer/layout.ts index 433379b5466..4a0d957c97d 100644 --- a/mastracode/factory-ui/src/ui/domains/workspace-viewer/layout.ts +++ b/mastracode/factory-ui/src/ui/domains/workspace-viewer/layout.ts @@ -67,7 +67,7 @@ export const popoverSizeClass: Record = { export const treeRowContainmentClass = '[content-visibility:auto] [contain-intrinsic-size:auto_1.75rem]'; -export const overviewScrollClass = 'flex min-h-0 w-full min-w-0 grow flex-col overflow-y-auto'; +export const overviewClass = 'flex min-h-0 w-full min-w-0 grow flex-col divide-y divide-border overflow-y-auto'; /** Read through descendant selectors: a variable or `group-*` variant on this box would restyle the whole transcript. */ export const panelStateAttributes = (docked: boolean, moved: boolean) => ({ diff --git a/mastracode/factory-ui/src/ui/pages/CardDraftPage.tsx b/mastracode/factory-ui/src/ui/pages/CardDraftPage.tsx index 6f979292ac3..d872efa9f01 100644 --- a/mastracode/factory-ui/src/ui/pages/CardDraftPage.tsx +++ b/mastracode/factory-ui/src/ui/pages/CardDraftPage.tsx @@ -24,6 +24,7 @@ import { useGlobalShortcuts } from '../domains/chat/hooks/useGlobalShortcuts'; import { boardOf } from '../domains/factory/boardFlow'; import { currentItemStage } from '../domains/factory/boardStages'; import { CardDraftActions } from '../domains/factory/components/CardDraftActions'; +import { CardOverview } from '../domains/factory/components/CardOverview'; import { CardStageBar } from '../domains/factory/components/CardStageBar'; import { useCardSessionRepository } from '../domains/factory/hooks/useCardSessionRepository'; import { useStartCardSessionFromDraft } from '../domains/factory/hooks/useStartCardSessionFromDraft'; @@ -31,8 +32,12 @@ import type { WorkItem } from '../domains/factory/services/workItems'; import { settingsSectionPath } from '../domains/settings/settingsSections'; import { factoryHomePath, threadPath } from '../domains/workspaces/services/factoryPaths'; import type { FactoryProject } from '../domains/workspaces/services/github'; - -const DRAFT_TITLE = 'New session'; +import { PanelSubject } from '../domains/workspace-viewer/components/PanelSubject'; +import { WorkspaceFilesToggle } from '../domains/workspace-viewer/components/WorkspaceFilesToggle'; +import { WorkspacePanelDock } from '../domains/workspace-viewer/components/WorkspacePanelDock'; +import { WorkspaceFilesProvider } from '../domains/workspace-viewer/context/WorkspaceFilesProvider'; +import type { WorkspacePanelPage } from '../domains/workspace-viewer/context/WorkspacePanelContext'; +import { SkeletonRows } from '../ui/SkeletonRows'; export function CardDraftPage() { const { @@ -64,7 +69,7 @@ function CardDraftContent({ if (card.isLoadingError) { return ( - +
+
+
@@ -117,17 +122,59 @@ function CardDraftContent({ const session = cardThreadSession(item, board?.phases, currentItemStage(item, board) ?? ''); if (session) return ; + const panel: WorkspacePanelPage = { + subject: lead => , + overview: () => ( + + ), + }; + return ( - } - > - {guards.missingModel || guards.missingCredential ? ( - - ) : ( - - )} - + + } + headerActions={} + dockActions={actions => {actions}} + > + {guards.missingModel || guards.missingCredential ? ( + + ) : ( + + )} + + + ); +} + +function CardDraftOverview({ + factory, + item, + boards, + boardsFailed, +}: { + factory: FactoryProject; + item: WorkItem; + boards: readonly InstalledBoardInfo[] | undefined; + boardsFailed: boolean; +}) { + const lookup = useCardSessionRepository(factory.id, item); + if (lookup.isPending) return ; + + const resolved = lookup.data?.status === 'resolved' ? lookup.data : undefined; + const repository = + resolved && factory.repositories.find(linked => linked.projectRepositoryId === resolved.projectRepositoryId); + return ( + ); } diff --git a/mastracode/factory-ui/src/ui/pages/ThreadPage.tsx b/mastracode/factory-ui/src/ui/pages/ThreadPage.tsx index 09c3064a4be..4f7c560127e 100644 --- a/mastracode/factory-ui/src/ui/pages/ThreadPage.tsx +++ b/mastracode/factory-ui/src/ui/pages/ThreadPage.tsx @@ -57,7 +57,7 @@ export function ThreadPage() { return ( - + diff --git a/mastracode/factory-ui/src/ui/pages/__tests__/CardDraftPage.msw.test.tsx b/mastracode/factory-ui/src/ui/pages/__tests__/CardDraftPage.msw.test.tsx index 217eeb7882a..c46ac1259fb 100644 --- a/mastracode/factory-ui/src/ui/pages/__tests__/CardDraftPage.msw.test.tsx +++ b/mastracode/factory-ui/src/ui/pages/__tests__/CardDraftPage.msw.test.tsx @@ -2,7 +2,7 @@ import { screen, waitFor, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { http, HttpResponse } from 'msw'; import { createMemoryRouter, RouterProvider } from 'react-router'; -import { describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import { server } from '../../../../e2e/ui/msw-server'; import { renderWithProviders, TEST_BASE_URL, waitForMutationsIdle } from '../../../../e2e/ui/render'; @@ -34,6 +34,22 @@ const linearCard = { }, }; +const PULL_REQUEST_NUMBER = 30647; +const PULL_REQUEST_URL = `https://github.com/acme/app/pull/${PULL_REQUEST_NUMBER}`; +const PULL_REQUEST_BODY = 'Stops the unhandled rejection when a stream aborts.'; +const pullRequestCard = { + ...linearCard, + title: 'fix(core): stop the unhandled rejection', + externalSource: { + integrationId: 'github', + type: 'pull-request', + externalId: String(PULL_REQUEST_NUMBER), + url: PULL_REQUEST_URL, + }, + metadata: { githubPullRequestNumber: PULL_REQUEST_NUMBER, number: PULL_REQUEST_NUMBER, state: 'open' }, + workItem: null, +}; + function stubCard(metadata: Record = linearCard.metadata) { const runStarts: unknown[] = []; server.use( @@ -63,13 +79,20 @@ function renderAt(path: string) { return { router, ...renderWithProviders(, createQueryClient()) }; } +function stubPageWidth(width: number) { + vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(() => new DOMRect(0, 0, width, 800)); +} + describe('a card without a session', () => { + afterEach(() => vi.restoreAllMocks()); + it('opens on a draft titled after the card that creates nothing until the first prompt', async () => { const route = stubDraftRoute(); const runStarts = stubCard(); const { router } = renderAt(`/factories/${FACTORY_ID}/cards/${CARD_ID}`); expect(await screen.findByRole('heading', { level: 2, name: linearCard.title })).toBeInTheDocument(); + expect(screen.queryByRole('heading', { level: 1, name: 'New session' })).not.toBeInTheDocument(); expect(router.state.location.pathname).toMatch( new RegExp(`^/factories/${FACTORY_ID}/cards/${CARD_ID}/new/[0-9a-f-]{36}$`), ); @@ -78,6 +101,31 @@ describe('a card without a session', () => { expect(runStarts).toEqual([]); }); + it("shows the card's pull request and description in the session panel before any session exists", async () => { + stubPageWidth(1200); + const route = stubDraftRoute(); + stubCard(); + server.use( + http.get(`${TEST_BASE_URL}/web/factory/projects/${FACTORY_ID}/work-items`, () => + HttpResponse.json({ workItems: [pullRequestCard] }), + ), + http.get(`${TEST_BASE_URL}/web/github/projects/:repository/prs/:number`, ({ params }) => + HttpResponse.json({ number: Number(params.number), description: PULL_REQUEST_BODY }), + ), + ); + renderAt(`/factories/${FACTORY_ID}/cards/${CARD_ID}/new/${DRAFT_SESSION_ID}`); + + const panel = await screen.findByRole('complementary', { name: 'Session panel' }); + const card = await within(panel).findByRole('region', { name: 'Card' }); + expect(await within(card).findByRole('link', { name: `Open PR #${PULL_REQUEST_NUMBER}` })).toHaveAttribute( + 'href', + PULL_REQUEST_URL, + ); + expect(await within(card).findByText(PULL_REQUEST_BODY)).toBeInTheDocument(); + expect(within(panel).queryByRole('region', { name: 'Workspace' })).not.toBeInTheDocument(); + expect(route.createBodies).toEqual([]); + }); + it("offers the card's next step on the draft and moves the card into it", async () => { stubDraftRoute(); const runStarts = stubCard(); From 4deef12c52d11727605239603882fbb563496b3b Mon Sep 17 00:00:00 2001 From: Damien Schneider <74979845+damien-schneider@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:30:14 -0800 Subject: [PATCH 2/3] chore: add changeset for the card draft session panel --- .changeset/factory-card-draft-panel.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/factory-card-draft-panel.md diff --git a/.changeset/factory-card-draft-panel.md b/.changeset/factory-card-draft-panel.md new file mode 100644 index 00000000000..e881d184b80 --- /dev/null +++ b/.changeset/factory-card-draft-panel.md @@ -0,0 +1,5 @@ +--- +'mastra': patch +--- + +Opening a Factory card that has no session yet now shows the session panel, as the card's sessions do. Before you send the first message, it lists the card's source, its pull request, its description, the pull requests it links to and the stages it has moved through. The page also drops its **New session** title, matching a card's session page. From f7e3f3aa3c4b39bc2c114b9df1831336ba09d473 Mon Sep 17 00:00:00 2001 From: Damien Schneider <74979845+damien-schneider@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:26:15 -0800 Subject: [PATCH 3/3] feat(factory-ui): keep the card's header and panel in place when Start opens its thread - Card drafts and threads now sit under one pathless SessionLayout route that renders the frame (header, stage bar, session panel) once; pages render only their chat body. - Start reads the session's cards and pull requests before switching, so the thread opens with its stage bar and panel overview instead of skeletons. - A thread that opens with the draft's prompt skips the composer entrance. - Renamed FactorySessionPage to ThreadFrame and split SessionFrame, CardDraftFrame, CardDraftOverview and SessionNotFound into their own files. --- .changeset/factory-session-layout-route.md | 5 + .../factory-ui/src/hooks/useWorkItems.ts | 14 +- .../chat/components/SessionChatSurface.tsx | 14 +- .../domains/chat/components/SessionFrame.tsx | 31 ++++ .../chat/components/SessionNotFound.tsx | 30 ++++ .../ui/domains/chat/components/chat-enter.css | 4 + .../RelatedFactorySessions.msw.test.tsx | 13 +- .../factory/components/CardDraftFrame.tsx | 47 +++++ .../factory/components/CardDraftOverview.tsx | 38 ++++ ...tedFactorySessions.tsx => ThreadFrame.tsx} | 23 ++- .../hooks/useStartCardSessionFromDraft.ts | 38 ++-- .../UserSessionsRegenerateTitle.msw.test.tsx | 7 +- .../src/ui/layouts/SessionLayout.tsx | 37 ++++ .../factory-ui/src/ui/pages/CardDraftPage.tsx | 162 ++++-------------- .../factory-ui/src/ui/pages/ThreadPage.tsx | 94 +--------- .../__tests__/CardDraftPage.msw.test.tsx | 64 +++++++ mastracode/factory-ui/src/ui/router.tsx | 42 +++-- 17 files changed, 399 insertions(+), 264 deletions(-) create mode 100644 .changeset/factory-session-layout-route.md create mode 100644 mastracode/factory-ui/src/ui/domains/chat/components/SessionFrame.tsx create mode 100644 mastracode/factory-ui/src/ui/domains/chat/components/SessionNotFound.tsx create mode 100644 mastracode/factory-ui/src/ui/domains/factory/components/CardDraftFrame.tsx create mode 100644 mastracode/factory-ui/src/ui/domains/factory/components/CardDraftOverview.tsx rename mastracode/factory-ui/src/ui/domains/factory/components/{RelatedFactorySessions.tsx => ThreadFrame.tsx} (87%) create mode 100644 mastracode/factory-ui/src/ui/layouts/SessionLayout.tsx diff --git a/.changeset/factory-session-layout-route.md b/.changeset/factory-session-layout-route.md new file mode 100644 index 00000000000..78fc3d15287 --- /dev/null +++ b/.changeset/factory-session-layout-route.md @@ -0,0 +1,5 @@ +--- +'mastra': patch +--- + +Sending the first message from a Factory card no longer swaps the page for a new one. The card's header, stage bar and session panel stay in place as the session starts, and the panel shows the card and its pull requests right away instead of loading them again. The composer no longer replays its entrance when the thread opens. diff --git a/mastracode/factory-ui/src/hooks/useWorkItems.ts b/mastracode/factory-ui/src/hooks/useWorkItems.ts index 58c18162432..6063d8e9cd5 100644 --- a/mastracode/factory-ui/src/hooks/useWorkItems.ts +++ b/mastracode/factory-ui/src/hooks/useWorkItems.ts @@ -267,9 +267,12 @@ export function workItemActivityQueryOptions(baseUrl: string, factoryProjectId: * The cards holding one session, with the cards related to them: what a session page reads * instead of the board. */ -export function useSessionWorkItemsQuery(factoryProjectId: string | undefined, sessionId: string | undefined) { - const { baseUrl } = useApiConfig(); - return useQuery({ +export function sessionWorkItemsQueryOptions( + baseUrl: string, + factoryProjectId: string | undefined, + sessionId: string | undefined, +) { + return queryOptions({ queryKey: queryKeys.sessionWorkItems(factoryProjectId, sessionId), queryFn: factoryProjectId && sessionId @@ -281,6 +284,11 @@ export function useSessionWorkItemsQuery(factoryProjectId: string | undefined, s }); } +export function useSessionWorkItemsQuery(factoryProjectId: string | undefined, sessionId: string | undefined) { + const { baseUrl } = useApiConfig(); + return useQuery(sessionWorkItemsQueryOptions(baseUrl, factoryProjectId, sessionId)); +} + /** One card by id, for a page that shows it off the board. */ export function workItemQueryOptions(baseUrl: string, factoryProjectId: string, workItemId: string) { return queryOptions({ diff --git a/mastracode/factory-ui/src/ui/domains/chat/components/SessionChatSurface.tsx b/mastracode/factory-ui/src/ui/domains/chat/components/SessionChatSurface.tsx index 2ef65c7ac99..e8e06495821 100644 --- a/mastracode/factory-ui/src/ui/domains/chat/components/SessionChatSurface.tsx +++ b/mastracode/factory-ui/src/ui/domains/chat/components/SessionChatSurface.tsx @@ -2,6 +2,8 @@ import { TranscriptAnnotations } from '@mastra/playground-ui/components/ai/annot import { ChatShell } from '@mastra/playground-ui/components/ChatShell'; import { cn } from '@mastra/playground-ui/utils/cn'; import type { ReactNode } from 'react'; +import { useState } from 'react'; +import { useLocation } from 'react-router'; import { chatColumnClass, composerColumnClass, reservedSpaceClass } from '../../workspace-viewer/layout'; import { ActivityLine } from './ActivityLine'; @@ -15,6 +17,9 @@ import { TranscriptHistoryLoader } from './TranscriptHistoryLoader'; import { ChatMessageBoundary } from '../context/ChatSessionProvider'; import { useChatMessagePreparation } from '../context/useChatMessagePreparation'; import { useChatTranscript } from '../context/useChatTranscript'; +import { opensWithPrompt } from '../hooks/useHandoffPrompt'; + +import './chat-enter.css'; const PREVIOUS_TURN_PEEK_PX = 64; const activityTail: TranscriptTail = stretchLive => ; @@ -35,6 +40,9 @@ export function SessionChatSurface({ composerStatus, contentOverlay, }: SessionChatSurfaceProps) { + const location = useLocation(); + // Fixed at mount: the thread drops the handoff from its state once it sends. + const [continuesDraft] = useState(() => opensWithPrompt(location.state)); const { busy, loadMore, transcript } = useChatTranscript(); const { historyInitializing, preparing } = useChatMessagePreparation(); const canLoadMore = loadMore.hasMore && !loadMore.isLoading; @@ -42,7 +50,11 @@ export function SessionChatSurface({ return ( + } + dockActions={actions => {actions}} + > + {children} + + + ); +} diff --git a/mastracode/factory-ui/src/ui/domains/chat/components/SessionNotFound.tsx b/mastracode/factory-ui/src/ui/domains/chat/components/SessionNotFound.tsx new file mode 100644 index 00000000000..249e2a57ca0 --- /dev/null +++ b/mastracode/factory-ui/src/ui/domains/chat/components/SessionNotFound.tsx @@ -0,0 +1,30 @@ +import { Button } from '@mastra/playground-ui/components/Button'; +import { EmptyState } from '@mastra/playground-ui/components/EmptyState'; +import { IconChatBubble7Off } from '@mastra/playground-ui/icons/central/IconChatBubble7Off'; +import { useNavigate } from 'react-router'; + +import { newUserSessionPath } from '../../workspaces/services/factoryPaths'; +import { ChatPageLayout } from './ChatPageLayout'; + +export function SessionNotFound({ factoryId }: { factoryId: string | undefined }) { + const navigate = useNavigate(); + return ( + +
+ } + titleSlot="Session not found" + descriptionSlot="This session does not exist, or it is private to another user." + actionSlot={ + factoryId && ( + + ) + } + /> +
+
+ ); +} diff --git a/mastracode/factory-ui/src/ui/domains/chat/components/chat-enter.css b/mastracode/factory-ui/src/ui/domains/chat/components/chat-enter.css index f04b4db533e..869f781e141 100644 --- a/mastracode/factory-ui/src/ui/domains/chat/components/chat-enter.css +++ b/mastracode/factory-ui/src/ui/domains/chat/components/chat-enter.css @@ -68,6 +68,10 @@ composer-fade 180ms linear backwards; } +.chat-surface-continues .composer-enter { + animation: none; +} + .starter-enter { animation: composer-rise 760ms cubic-bezier(0.16, 1, 0.3, 1) backwards, diff --git a/mastracode/factory-ui/src/ui/domains/factory/__tests__/RelatedFactorySessions.msw.test.tsx b/mastracode/factory-ui/src/ui/domains/factory/__tests__/RelatedFactorySessions.msw.test.tsx index b3487c7e548..9784b5b6139 100644 --- a/mastracode/factory-ui/src/ui/domains/factory/__tests__/RelatedFactorySessions.msw.test.tsx +++ b/mastracode/factory-ui/src/ui/domains/factory/__tests__/RelatedFactorySessions.msw.test.tsx @@ -15,8 +15,7 @@ import { sessionCardsWhileBoardLoads } from '../../../../../e2e/ui/session-cards import type { BoardCatalogResponse, InstalledBoardInfo } from '../../../../api/types'; import { ChatSessionTestProvider } from '../../chat/context/ChatSessionTestProvider'; -import { WorkspaceFilesProvider } from '../../workspace-viewer/context/WorkspaceFilesProvider'; -import { FactorySessionPage } from '../components/RelatedFactorySessions'; +import { ThreadFrame } from '../components/ThreadFrame'; import type { FactoryDecisionSummary } from '../services/decisions'; const FACTORY_ID = 'factory-1'; @@ -99,9 +98,7 @@ function renderHeader() { path="/factories/:factoryId/workspaces/:sessionId/threads/:threadId" element={ - - {null} - + {null} } /> @@ -112,7 +109,7 @@ function renderHeader() { ); } -describe('FactorySessionPage', () => { +describe('ThreadFrame', () => { describe('while the board is still loading', () => { it("names the session among the card's others before the board arrives", async () => { const card = workItem(undefined); @@ -411,9 +408,7 @@ describe('FactorySessionPage', () => { path="/factories/:factoryId/workspaces/:sessionId/threads/:threadId" element={ - - {null} - + {null} } /> diff --git a/mastracode/factory-ui/src/ui/domains/factory/components/CardDraftFrame.tsx b/mastracode/factory-ui/src/ui/domains/factory/components/CardDraftFrame.tsx new file mode 100644 index 00000000000..3b0002b3d8e --- /dev/null +++ b/mastracode/factory-ui/src/ui/domains/factory/components/CardDraftFrame.tsx @@ -0,0 +1,47 @@ +import type { ReactNode } from 'react'; +import { useParams } from 'react-router'; + +import { useBoardCatalog } from '../../../../hooks/useBoardCatalog'; +import { useFactoryQuery } from '../../../../hooks/useFactories'; +import { useWorkItemQuery } from '../../../../hooks/useWorkItems'; +import { SessionFrame } from '../../chat/components/SessionFrame'; +import { PanelSubject } from '../../workspace-viewer/components/PanelSubject'; +import { boardOf } from '../boardFlow'; +import { CardDraftOverview } from './CardDraftOverview'; +import { CardStageBar } from './CardStageBar'; + +export function CardDraftFrame({ workItemId, children }: { workItemId: string; children: ReactNode }) { + const { factoryId = '' } = useParams<{ factoryId: string }>(); + const card = useWorkItemQuery(factoryId, workItemId); + const catalog = useBoardCatalog(factoryId); + const factory = useFactoryQuery(factoryId).data; + const item = catalog.isPending ? undefined : (card.data ?? undefined); + const board = item && boardOf(catalog.data, item); + + return ( + , + overview: () => ( + + ), + } + : undefined + } + headerCenter={ + item && board && factory ? ( + + ) : undefined + } + > + {children} + + ); +} diff --git a/mastracode/factory-ui/src/ui/domains/factory/components/CardDraftOverview.tsx b/mastracode/factory-ui/src/ui/domains/factory/components/CardDraftOverview.tsx new file mode 100644 index 00000000000..b85071274a8 --- /dev/null +++ b/mastracode/factory-ui/src/ui/domains/factory/components/CardDraftOverview.tsx @@ -0,0 +1,38 @@ +import type { InstalledBoardInfo } from '../../../../api/types'; +import { SkeletonRows } from '../../../ui/SkeletonRows'; +import type { FactoryProject } from '../../workspaces/services/github'; +import { useCardSessionRepository } from '../hooks/useCardSessionRepository'; +import type { WorkItem } from '../services/workItems'; +import { CardOverview } from './CardOverview'; + +export function CardDraftOverview({ + factory, + item, + boards, + boardsFailed, +}: { + factory: FactoryProject; + item: WorkItem; + boards: readonly InstalledBoardInfo[] | undefined; + boardsFailed: boolean; +}) { + const lookup = useCardSessionRepository(factory.id, item); + if (lookup.isPending) return ; + + const resolved = lookup.data?.status === 'resolved' ? lookup.data : undefined; + const repository = + resolved && factory.repositories.find(linked => linked.projectRepositoryId === resolved.projectRepositoryId); + return ( + + ); +} diff --git a/mastracode/factory-ui/src/ui/domains/factory/components/RelatedFactorySessions.tsx b/mastracode/factory-ui/src/ui/domains/factory/components/ThreadFrame.tsx similarity index 87% rename from mastracode/factory-ui/src/ui/domains/factory/components/RelatedFactorySessions.tsx rename to mastracode/factory-ui/src/ui/domains/factory/components/ThreadFrame.tsx index 992cf7b2f50..feb9bd359e6 100644 --- a/mastracode/factory-ui/src/ui/domains/factory/components/RelatedFactorySessions.tsx +++ b/mastracode/factory-ui/src/ui/domains/factory/components/ThreadFrame.tsx @@ -7,11 +7,11 @@ import { Link, useParams } from 'react-router'; import type { InstalledBoardInfo } from '../../../../api/types'; import { useFactoryQuery } from '../../../../hooks/useFactories'; -import { ChatPageLayout } from '../../chat/components/ChatPageLayout'; +import { SessionFrame } from '../../chat/components/SessionFrame'; import { UserSessionSharing } from '../../workspaces/components/UserSessionSharing'; import { threadPath } from '../../workspaces/services/factoryPaths'; -import { WorkspaceFilesToggle } from '../../workspace-viewer/components/WorkspaceFilesToggle'; -import { WorkspacePanelDock } from '../../workspace-viewer/components/WorkspacePanelDock'; +import type { WorkspacePanelPage } from '../../workspace-viewer/context/WorkspacePanelContext'; +import { useThreadWorkspacePath } from '../../workspace-viewer/hooks/useThreadWorkspacePath'; import { currentItemStage } from '../boardStages'; import { useSessionCard } from '../hooks/useSessionCard'; import { useOpenSession } from '../hooks/useOpenSession'; @@ -19,8 +19,15 @@ import type { WorkItem, WorkItemSessionRef } from '../services/workItems'; import { CardStageBar } from './CardStageBar'; import { CardStageSummary } from './CardStageSummary'; import { SessionContextMenu } from './SessionContextMenu'; +import { SessionPanelOverview } from './SessionPanelOverview'; +import { SessionPanelSubject } from './SessionPanelSubject'; import { ThreadSubscriptionsRefresh } from './ThreadSubscriptionsRefresh'; +const SESSION_PANEL: WorkspacePanelPage = { + subject: lead => , + overview: workspace => , +}; + interface OpenSessionContext { context: string; label: string; @@ -64,9 +71,10 @@ function stageUnavailable( return undefined; } -export function FactorySessionPage({ children }: { children: ReactNode }) { +export function ThreadFrame({ children }: { children: ReactNode }) { const { factoryId, sessionId, threadId } = useParams<{ factoryId: string; sessionId: string; threadId: string }>(); const { session, isUserThread, title: sessionTitle } = useOpenSession(); + const { workspacePath } = useThreadWorkspacePath(); const factoryQuery = useFactoryQuery(factoryId); const factory = factoryQuery.data; const { @@ -86,7 +94,8 @@ export function FactorySessionPage({ children }: { children: ReactNode }) { const stageNote = stageUnavailable(boardEntry, boards, boardsFailed, factoryQuery.isLoadingError); return ( - ) : undefined } - headerActions={} - dockActions={actions => {actions}} > {children} - + ); } diff --git a/mastracode/factory-ui/src/ui/domains/factory/hooks/useStartCardSessionFromDraft.ts b/mastracode/factory-ui/src/ui/domains/factory/hooks/useStartCardSessionFromDraft.ts index 2e9baa6939a..b9562a7a167 100644 --- a/mastracode/factory-ui/src/ui/domains/factory/hooks/useStartCardSessionFromDraft.ts +++ b/mastracode/factory-ui/src/ui/domains/factory/hooks/useStartCardSessionFromDraft.ts @@ -1,9 +1,10 @@ import type { MastraDBMessage } from '@mastra/core/agent-controller'; -import { useMutation, useQueryClient } from '@tanstack/react-query'; -import { useNavigate, useParams } from 'react-router'; +import { noop, useMutation, useQueryClient } from '@tanstack/react-query'; +import { useNavigate } from 'react-router'; import { INITIAL_THREAD_MESSAGE_LIMIT, queryKeys } from '../../../../api/keys'; import type { WorkItemSessionRepository } from '../../../../api/types'; +import { sessionWorkItemsQueryOptions } from '../../../../hooks/useWorkItems'; import { addCachedSession, invalidateSessionQueries } from '../../../../hooks/useWorkspaces'; import type { DraftSessionStart } from '../../chat/context/DraftSessionStartContext'; import { useChatModels } from '../../chat/context/useChatModels'; @@ -13,8 +14,10 @@ import { startPromptHandoff } from '../../chat/hooks/useHandoffPrompt'; import { AGENT_CONTROLLER_ID } from '../../chat/services/constants'; import { stashHandoffFiles } from '../../chat/services/handoffFiles'; import { threadPath } from '../../workspaces/services/factoryPaths'; +import type { FactoryProject } from '../../workspaces/services/github'; import { createUserSession, getUserSession } from '../../workspaces/services/user-sessions'; import { itemSessionSpec } from '../boardItems'; +import { pullRequestSubscriptionsQuery } from '../services/githubSubscriptions'; import { startFactoryRun } from '../services/workItems'; import type { WorkItem } from '../services/workItems'; @@ -22,23 +25,23 @@ type ResolvedRepository = Extract(); const queryClient = useQueryClient(); const navigate = useNavigate(); const resolved = sessionRepository?.status === 'resolved' ? sessionRepository : undefined; const startSession = useMutation({ - mutationFn: async ({ factoryId, repository }: { factoryId: string; repository: ResolvedRepository }) => { + mutationFn: async (repository: ResolvedRepository) => { const metadata = item.workItem ? {} : (item.metadata ?? {}); const { branch, threadTitle } = itemSessionSpec(item); const { sessionId } = await createUserSession(baseUrl, repository.projectRepositoryId, { branch }); - await startFactoryRun(baseUrl, factoryId, { + await startFactoryRun(baseUrl, factory.id, { sessionId, threadTitle, kickoffKey: crypto.randomUUID(), @@ -48,28 +51,35 @@ export function useStartCardSessionFromDraft( input: { source: item.source, sourceKey: item.sourceKey, title: item.title, url: null, metadata }, }, }); - // Read after the start: binding the card decides which memory resource the session works on. - return getUserSession(baseUrl, sessionId); + const provider = + factory.repositories.find(linked => linked.projectRepositoryId === repository.projectRepositoryId)?.provider ?? + 'github'; + // Read after the start, which binds the card, so the thread opens on its resource, cards, and pull requests. + const [session] = await Promise.all([ + getUserSession(baseUrl, sessionId), + queryClient.query(sessionWorkItemsQueryOptions(baseUrl, factory.id, sessionId)).catch(noop), + queryClient.query(pullRequestSubscriptionsQuery(baseUrl, sessionId, sessionId, provider, true)).catch(noop), + ]); + return session; }, - onSettled: (_session, _error, { factoryId }) => - queryClient.invalidateQueries({ queryKey: queryKeys.workItems(factoryId) }), + onSettled: () => queryClient.invalidateQueries({ queryKey: queryKeys.workItems(factory.id) }), }); const start: DraftSessionStart['start'] = async ({ prompt, files }) => { - if (!factoryId || !resolved) { + if (!resolved) { throw new Error('Could not create the session. Reload the page and try again.'); } if (!activeModelId) { throw new Error('Session configuration is not ready. Try again.'); } - const session = await startSession.mutateAsync({ factoryId, repository: resolved }).catch((error: unknown) => { + const session = await startSession.mutateAsync(resolved).catch((error: unknown) => { const message = error instanceof Error ? error.message : 'Session creation failed'; throw new Error(`Could not create the session: ${message}. Try again.`, { cause: error }); }); const { sessionId } = session; queryClient.setQueryData(queryKeys.userSession(sessionId), session); - addCachedSession(queryClient, factoryId, session); - void invalidateSessionQueries(queryClient, factoryId); + addCachedSession(queryClient, factory.id, session); + void invalidateSessionQueries(queryClient, factory.id); // A session that never got a message has no history, so its thread opens on an empty transcript. queryClient.setQueryData( queryKeys.agentControllerThreadMessages(AGENT_CONTROLLER_ID, sessionId, sessionId, INITIAL_THREAD_MESSAGE_LIMIT), @@ -77,7 +87,7 @@ export function useStartCardSessionFromDraft( ); stashHandoffFiles(sessionId, files); const draftKeepsServerDefaults = activeModelId === defaultModelId && !thinkingLevelOverride; - void navigate(threadPath(factoryId, { sessionId, threadId: sessionId }), { + void navigate(threadPath(factory.id, { sessionId, threadId: sessionId }), { replace: true, state: startPromptHandoff(sessionId, prompt, { modelId: draftKeepsServerDefaults ? undefined : activeModelId, diff --git a/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/UserSessionsRegenerateTitle.msw.test.tsx b/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/UserSessionsRegenerateTitle.msw.test.tsx index 868d3c2b386..a5bad8d9c3e 100644 --- a/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/UserSessionsRegenerateTitle.msw.test.tsx +++ b/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/UserSessionsRegenerateTitle.msw.test.tsx @@ -13,8 +13,7 @@ import { TEST_BASE_URL, renderWithProviders, waitForMutationsIdle } from '../../ import type { FactoryUserSession } from '../../services/user-sessions'; import { ChatSessionContext } from '../../../chat/context/ChatSessionContext'; import { ChatSessionTestProvider } from '../../../chat/context/ChatSessionTestProvider'; -import { FactorySessionPage } from '../../../factory/components/RelatedFactorySessions'; -import { WorkspaceFilesProvider } from '../../../workspace-viewer/context/WorkspaceFilesProvider'; +import { ThreadFrame } from '../../../factory/components/ThreadFrame'; import { SessionsSection } from '../SessionsSection'; import { testChatSession } from './fixtures/sessionsSection'; @@ -79,9 +78,7 @@ function renderOpenSession() { element={ - - {null} - + {null} } /> diff --git a/mastracode/factory-ui/src/ui/layouts/SessionLayout.tsx b/mastracode/factory-ui/src/ui/layouts/SessionLayout.tsx new file mode 100644 index 00000000000..4f30108cc1b --- /dev/null +++ b/mastracode/factory-ui/src/ui/layouts/SessionLayout.tsx @@ -0,0 +1,37 @@ +import { Navigate, Outlet, useParams } from 'react-router'; + +import { SessionNotFound } from '../domains/chat/components/SessionNotFound'; +import { ChatSessionBoundary } from '../domains/chat/context/ChatSessionProvider'; +import { failedDraftState } from '../domains/chat/services/handoffFiles'; +import { CardDraftFrame } from '../domains/factory/components/CardDraftFrame'; +import { ThreadFrame } from '../domains/factory/components/ThreadFrame'; +import { useThreadWorkspacePath } from '../domains/workspace-viewer/hooks/useThreadWorkspacePath'; +import { DraftSessionCreateError, isSessionNotFound } from '../domains/workspaces/services/user-sessions'; + +export function SessionLayout() { + const { factoryId, threadId, workItemId } = useParams<{ + factoryId: string; + threadId?: string; + workItemId?: string; + }>(); + const { error } = useThreadWorkspacePath(); + + if (error instanceof DraftSessionCreateError) { + return ; + } + if (error && isSessionNotFound(error)) return ; + + return ( + + {workItemId ? ( + + + + ) : ( + + + + )} + + ); +} diff --git a/mastracode/factory-ui/src/ui/pages/CardDraftPage.tsx b/mastracode/factory-ui/src/ui/pages/CardDraftPage.tsx index d872efa9f01..432b5ab70b0 100644 --- a/mastracode/factory-ui/src/ui/pages/CardDraftPage.tsx +++ b/mastracode/factory-ui/src/ui/pages/CardDraftPage.tsx @@ -12,107 +12,69 @@ import { Link, Navigate, useParams } from 'react-router'; import { useBoardCatalog } from '../../hooks/useBoardCatalog'; import { useWorkItemQuery } from '../../hooks/useWorkItems'; import type { InstalledBoardInfo } from '../../api/types'; -import { ChatPageLayout } from '../domains/chat/components/ChatPageLayout'; import { ConfigurationErrorNotice, DraftStart, draftPageClass } from '../domains/chat/components/DraftStart'; import { emptyThreadClass } from '../domains/chat/components/EmptyThreadState'; import { SessionChatSurface } from '../domains/chat/components/SessionChatSurface'; -import { ChatSessionBoundary } from '../domains/chat/context/ChatSessionProvider'; import { DraftSessionStartContext } from '../domains/chat/context/DraftSessionStartContext'; import { useDraftModelGuards } from '../domains/chat/hooks/useDraftModelGuards'; -import type { DraftModelGuards } from '../domains/chat/hooks/useDraftModelGuards'; import { useGlobalShortcuts } from '../domains/chat/hooks/useGlobalShortcuts'; import { boardOf } from '../domains/factory/boardFlow'; import { currentItemStage } from '../domains/factory/boardStages'; import { CardDraftActions } from '../domains/factory/components/CardDraftActions'; -import { CardOverview } from '../domains/factory/components/CardOverview'; -import { CardStageBar } from '../domains/factory/components/CardStageBar'; import { useCardSessionRepository } from '../domains/factory/hooks/useCardSessionRepository'; import { useStartCardSessionFromDraft } from '../domains/factory/hooks/useStartCardSessionFromDraft'; import type { WorkItem } from '../domains/factory/services/workItems'; import { settingsSectionPath } from '../domains/settings/settingsSections'; import { factoryHomePath, threadPath } from '../domains/workspaces/services/factoryPaths'; import type { FactoryProject } from '../domains/workspaces/services/github'; -import { PanelSubject } from '../domains/workspace-viewer/components/PanelSubject'; -import { WorkspaceFilesToggle } from '../domains/workspace-viewer/components/WorkspaceFilesToggle'; -import { WorkspacePanelDock } from '../domains/workspace-viewer/components/WorkspacePanelDock'; -import { WorkspaceFilesProvider } from '../domains/workspace-viewer/context/WorkspaceFilesProvider'; -import type { WorkspacePanelPage } from '../domains/workspace-viewer/context/WorkspacePanelContext'; -import { SkeletonRows } from '../ui/SkeletonRows'; export function CardDraftPage() { - const { - factoryId = '', - workItemId = '', - draftSessionId, - } = useParams<{ factoryId: string; workItemId: string; draftSessionId: string }>(); + const { factoryId = '', workItemId = '' } = useParams<{ factoryId: string; workItemId: string }>(); const guards = useDraftModelGuards(factoryId, 'factory'); - - return ( - - - - ); -} - -function CardDraftContent({ - factoryId, - workItemId, - guards, -}: { - factoryId: string; - workItemId: string; - guards: DraftModelGuards; -}) { const card = useWorkItemQuery(factoryId, workItemId); const catalog = useBoardCatalog(factoryId); const factory = guards.activeFactory; if (card.isLoadingError) { return ( - -
- } - titleSlot="Could not load this card" - descriptionSlot={card.error.message} - actionSlot={ - - } - /> -
-
+
+ } + titleSlot="Could not load this card" + descriptionSlot={card.error.message} + actionSlot={ + + } + /> +
); } if (card.data === null) { return ( - -
- } - titleSlot="This card no longer exists" - descriptionSlot="It was removed from the board." - actionSlot={ - - Back to the board - - } - /> -
-
+
+ } + titleSlot="This card no longer exists" + descriptionSlot="It was removed from the board." + actionSlot={ + + Back to the board + + } + /> +
); } if (!card.data || catalog.isPending || !factory) { return ( - -
- - -
-
+
+ + +
); } @@ -122,60 +84,8 @@ function CardDraftContent({ const session = cardThreadSession(item, board?.phases, currentItemStage(item, board) ?? ''); if (session) return ; - const panel: WorkspacePanelPage = { - subject: lead => , - overview: () => ( - - ), - }; - - return ( - - } - headerActions={} - dockActions={actions => {actions}} - > - {guards.missingModel || guards.missingCredential ? ( - - ) : ( - - )} - - - ); -} - -function CardDraftOverview({ - factory, - item, - boards, - boardsFailed, -}: { - factory: FactoryProject; - item: WorkItem; - boards: readonly InstalledBoardInfo[] | undefined; - boardsFailed: boolean; -}) { - const lookup = useCardSessionRepository(factory.id, item); - if (lookup.isPending) return ; - - const resolved = lookup.data?.status === 'resolved' ? lookup.data : undefined; - const repository = - resolved && factory.repositories.find(linked => linked.projectRepositoryId === resolved.projectRepositoryId); - return ( - - ); + if (guards.missingModel || guards.missingCredential) return ; + return ; } function CardDraft({ @@ -191,7 +101,11 @@ function CardDraft({ }) { useGlobalShortcuts(); const sessionRepository = useCardSessionRepository(factory.id, item); - const draftStart = useStartCardSessionFromDraft(item, sessionRepository.error ? undefined : sessionRepository.data); + const draftStart = useStartCardSessionFromDraft( + factory, + item, + sessionRepository.error ? undefined : sessionRepository.data, + ); return ( diff --git a/mastracode/factory-ui/src/ui/pages/ThreadPage.tsx b/mastracode/factory-ui/src/ui/pages/ThreadPage.tsx index 4f7c560127e..d55d0ea12e4 100644 --- a/mastracode/factory-ui/src/ui/pages/ThreadPage.tsx +++ b/mastracode/factory-ui/src/ui/pages/ThreadPage.tsx @@ -1,110 +1,34 @@ -import { Button } from '@mastra/playground-ui/components/Button'; -import { EmptyState } from '@mastra/playground-ui/components/EmptyState'; import type { ReactNode } from 'react'; import { useRef } from 'react'; -import { Navigate, useNavigate, useParams } from 'react-router'; import { useRouteThreadSync } from '../../hooks/useRouteThreadSync'; -import { ChatPageLayout } from '../domains/chat/components/ChatPageLayout'; import { EmptyThreadState } from '../domains/chat/components/EmptyThreadState'; import { GoalPanel } from '../domains/chat/components/GoalPanel'; import { PageTitle } from '../domains/chat/components/PageTitle'; import { SessionChatSurface } from '../domains/chat/components/SessionChatSurface'; import { ThreadRailLayer } from '../domains/chat/components/ThreadRailLayer'; import { TeammateSessionLine } from '../domains/chat/components/TeammateSessionLine'; -import { ChatSessionBoundary } from '../domains/chat/context/ChatSessionProvider'; import { useChatTranscript } from '../domains/chat/context/useChatTranscript'; import { useGlobalShortcuts } from '../domains/chat/hooks/useGlobalShortcuts'; -import { DraftSessionCreateError, isSessionNotFound } from '../domains/workspaces/services/user-sessions'; import { useHandoffPrompt } from '../domains/chat/hooks/useHandoffPrompt'; -import { failedDraftState } from '../domains/chat/services/handoffFiles'; -import { FactorySessionPage } from '../domains/factory/components/RelatedFactorySessions'; -import { SessionPanelOverview } from '../domains/factory/components/SessionPanelOverview'; -import { SessionPanelSubject } from '../domains/factory/components/SessionPanelSubject'; -import type { WorkspacePanelPage } from '../domains/workspace-viewer/context/WorkspacePanelContext'; -import { WorkspaceFilesProvider } from '../domains/workspace-viewer/context/WorkspaceFilesProvider'; import { useThreadWorkspacePath } from '../domains/workspace-viewer/hooks/useThreadWorkspacePath'; import { useWiderThan } from '../domains/workspace-viewer/hooks/useWiderThan'; import { RAIL_MIN_REM } from '../domains/workspace-viewer/layout'; import { useInvalidateWorkspaceChangesOnRunCompletion } from '../domains/workspace-viewer/useInvalidateWorkspaceChangesOnRunCompletion'; import { useRefreshWorkspaceFilesOnToolCalls } from '../domains/workspace-viewer/useRefreshWorkspaceFilesOnToolCalls'; -import { newUserSessionPath } from '../domains/workspaces/services/factoryPaths'; - -import '../domains/chat/components/chat-enter.css'; -import { IconChatBubble7Off } from '@mastra/playground-ui/icons/central/IconChatBubble7Off'; - -const SESSION_PANEL: WorkspacePanelPage = { - subject: lead => , - overview: workspace => , -}; export function ThreadPage() { - const { factoryId, threadId } = useParams<{ factoryId: string; threadId?: string }>(); - const workspace = useThreadWorkspacePath(); - - if (workspace.error instanceof DraftSessionCreateError) { - return ( - - ); - } - - if (workspace.error && isSessionNotFound(workspace.error)) return ; - - return ( - - - - - - - ); -} - -function SessionNotFoundMain({ factoryId }: { factoryId: string | undefined }) { - const navigate = useNavigate(); - return ( - -
- } - titleSlot="Session not found" - descriptionSlot="This session does not exist, or it is private to another user." - actionSlot={ - factoryId && ( - - ) - } - /> -
-
- ); -} - -function ThreadPageMain({ - workspacePath, - threadId, -}: { - workspacePath: string | undefined; - threadId: string | undefined; -}) { + const { workspacePath } = useThreadWorkspacePath(); return ( - - } - emptyState={} - composerLabel="Thread composer" - composerStatus={} - contentOverlay={} - /> - + + } + emptyState={} + composerLabel="Thread composer" + composerStatus={} + contentOverlay={} + /> ); } diff --git a/mastracode/factory-ui/src/ui/pages/__tests__/CardDraftPage.msw.test.tsx b/mastracode/factory-ui/src/ui/pages/__tests__/CardDraftPage.msw.test.tsx index c46ac1259fb..39b9025713e 100644 --- a/mastracode/factory-ui/src/ui/pages/__tests__/CardDraftPage.msw.test.tsx +++ b/mastracode/factory-ui/src/ui/pages/__tests__/CardDraftPage.msw.test.tsx @@ -189,6 +189,70 @@ describe('a card without a session', () => { await waitForMutationsIdle(client); }); + it("keeps the card's stage and panel in place when the first prompt opens the thread", async () => { + stubPageWidth(1200); + const route = stubDraftRoute(); + stubCard(); + const user = userEvent.setup(); + const { router, client } = renderAt(`/factories/${FACTORY_ID}/cards/${CARD_ID}`); + const threadPath = `/factories/${FACTORY_ID}/workspaces/${DRAFT_SESSION_ID}/threads/${DRAFT_SESSION_ID}`; + const cardInSession = { + ...linearCard, + sessions: { + chat: { + sessionId: DRAFT_SESSION_ID, + branch: 'factory/linear-eng-42', + threadId: DRAFT_SESSION_ID, + startedBy: 'user-1', + }, + }, + }; + let answerThreadReads = () => {}; + const threadReadsAnswered = new Promise(resolve => { + answerThreadReads = resolve; + }); + server.use( + http.get(`${TEST_BASE_URL}/web/factory/projects/${FACTORY_ID}/work-items`, async ({ request }) => { + if (!new URL(request.url).searchParams.has('sessionId')) return HttpResponse.json({ workItems: [linearCard] }); + if (router.state.location.pathname === threadPath) await threadReadsAnswered; + return HttpResponse.json({ workItems: [cardInSession] }); + }), + http.get(`${TEST_BASE_URL}/web/github/subscriptions`, async () => { + if (router.state.location.pathname === threadPath) await threadReadsAnswered; + return HttpResponse.json({ subscriptions: [] }); + }), + http.get(`${TEST_BASE_URL}/web/linear/issues/:identifier`, () => HttpResponse.json({ description: null })), + http.get(`${TEST_BASE_URL}/web/workspace/changes`, ({ request }) => + HttpResponse.json({ + workspacePath: new URL(request.url).searchParams.get('workspacePath'), + available: true, + additions: 0, + deletions: 0, + changes: [], + }), + ), + http.get( + `${TEST_BASE_URL}/web/factory/projects/${FACTORY_ID}/feed-events`, + () => new HttpResponse(null, { status: 404 }), + ), + ); + + expect(await screen.findByRole('group', { name: 'Card stage' })).toBeInTheDocument(); + await user.type(await screen.findByRole('textbox', { name: 'Message' }), 'repair the facts'); + await user.keyboard('{Enter}'); + + await waitFor(() => expect(route.posted).toEqual(['repair the facts'])); + expect(router.state.location.pathname).toBe(threadPath); + const panel = screen.getByRole('complementary', { name: 'Session panel' }); + expect(within(panel).getByRole('region', { name: 'Workspace' })).toBeInTheDocument(); + expect(within(panel).getByRole('region', { name: 'Card' })).toBeInTheDocument(); + expect(screen.getByRole('group', { name: 'Card stage' })).toBeInTheDocument(); + + answerThreadReads(); + route.finishWorkspace(); + await waitForMutationsIdle(client); + }); + it('keeps the prompt on the draft when the start fails, and the card reopened starts in the session it left', async () => { const route = stubDraftRoute(); const runStarts = stubCard(); diff --git a/mastracode/factory-ui/src/ui/router.tsx b/mastracode/factory-ui/src/ui/router.tsx index c7be5133160..d49fd17e23a 100644 --- a/mastracode/factory-ui/src/ui/router.tsx +++ b/mastracode/factory-ui/src/ui/router.tsx @@ -49,24 +49,31 @@ import { hasResumableFactoryOnboarding } from './domains/workspaces/services/onb // Only the boards ship in the startup bundle; every other page loads on first // visit behind its own loader (see `lazyPage`). -const ThreadPage = lazyPage(() => import('./pages/ThreadPage').then(module => module.ThreadPage), ); +const ThreadPage = lazyPage(() => import('./pages/ThreadPage').then(module => module.ThreadPage)); +// Card drafts and threads share this frame, and a draft's first prompt opens its thread. +const SessionLayout = lazyPage( + () => + import('./layouts/SessionLayout').then(module => { + // A failed preload retries on the visit. + ThreadPage.preload().catch(() => undefined); + return module.SessionLayout; + }), + , +); // A new session opens its thread on the first prompt, so that page loads right after. const NewPage = lazyPage( () => import('./pages/NewPage').then(module => { - // A failed preload retries on the visit. - ThreadPage.preload().catch(() => undefined); + SessionLayout.preload().catch(() => undefined); return module.NewPage; }), , ); -const CardDraftPage = lazyPage( - () => - import('./pages/CardDraftPage').then(module => { - ThreadPage.preload().catch(() => undefined); - return module.CardDraftPage; - }), - , +const CardDraftPage = lazyPage(() => + import('./pages/CardDraftPage').then(module => { + SessionLayout.preload().catch(() => undefined); + return module.CardDraftPage; + }), ); const KnowledgePage = lazyPage( () => import('./pages/KnowledgePage').then(module => module.KnowledgePage), @@ -270,7 +277,7 @@ export function createAppRoutes(services?: RouteLoaderServices): RouteObject[] { { element: , // Load the chat code while its session links appear, before a card or session is clicked. - ...loadOnEntry(prefetchSidebar, ThreadPage), + ...loadOnEntry(prefetchSidebar, SessionLayout), children: [ { // Errors replace only the page, preserving the shell and its providers. @@ -278,17 +285,22 @@ export function createAppRoutes(services?: RouteLoaderServices): RouteObject[] { children: [ { index: true, element: }, { path: 'workspaces/:sessionId', ...lazyRoute(NewPage, prefetchComposer) }, - { path: 'workspaces/:sessionId/threads/:threadId', ...lazyRoute(ThreadPage) }, { path: 'user/new/:draftSessionId', ...lazyRoute(NewPage, prefetchDraft) }, - { path: 'user/threads/:threadId', ...lazyRoute(ThreadPage) }, { path: 'cards/:workItemId', element: , ...loadOnEntry(prefetchCardDraft, CardDraftPage), }, { - path: 'cards/:workItemId/new/:draftSessionId', - ...lazyRoute(CardDraftPage, prefetchCardDraft), + ...lazyRoute(SessionLayout), + children: [ + { path: 'workspaces/:sessionId/threads/:threadId', ...lazyRoute(ThreadPage) }, + { path: 'user/threads/:threadId', ...lazyRoute(ThreadPage) }, + { + path: 'cards/:workItemId/new/:draftSessionId', + ...lazyRoute(CardDraftPage, prefetchCardDraft), + }, + ], }, { path: 'new', ...lazyRoute(NewPage, prefetchComposer) }, { path: 'new-factory', ...lazyRoute(CreateFactoryPage) },