Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion hub/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Hub is being rebuilt in TypeScript. Read the [root instructions](../AGENTS.md),
- [Development](docs/development.md) and [testing](docs/testing-and-operations.md) own local and CI commands.
- [Storybook](docs/storybook.md#ui-changes-and-pull-request-evidence) owns presentation coverage, cleanup, and PR screenshots.

Run Node commands from `hub/`, locally or inside the devcontainer. PostgreSQL and Prisma support configured GitHub authentication, administrator enrollment, Hub sessions, and a seeded prototype index with prototype metadata editing and draft registration through the API; see [authentication](docs/authentication.md). Other prototype APIs and repository-specific permissions are not built. Agree on the design before adding more product models, permissions, deployment choices, or product API routes.
Run Node commands from `hub/`, locally or inside the devcontainer. PostgreSQL and Prisma support configured GitHub authentication, administrator enrollment, Hub sessions, Build history, and a seeded prototype index with prototype metadata editing and draft registration through the API; see [authentication](docs/authentication.md). Other prototype APIs and repository-specific permissions are not built. Agree on the design before adding more product models, permissions, deployment choices, or product API routes.

Use `npm run dev:api` to run Hub with local developer sign-in; this is the default choice for trying or testing Hub. Use `npm run dev:api:live` only when the task needs real GitHub or Entra sign-in configured in `.env`. [Development](docs/development.md#start-with-the-real-api) explains both modes.

Expand Down
2 changes: 1 addition & 1 deletion hub/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Hub is being rebuilt on `build/hub/new` using TypeScript, Express, React, Vite, and Vitest. This branch lets contributors start the new app locally. It is not ready to replace the existing Hub.

The API has liveness, readiness, repository index, and prototype detail routes. Signed-in members can edit a visible prototype's name, description, and start page in the interface. React Router also connects the retained frontend pages to local mock data.
The API has liveness, readiness, repository index, prototype detail, and Build history routes. Signed-in members can edit a visible prototype's name, description, and start page in the interface. React Router also connects the retained frontend pages to local mock data.

Contributors can use PostgreSQL and Prisma locally or in the devcontainer. The backend provides:

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,13 @@ export function createMockHandlers(store: MockStore) {
recordIdentifier(params.repositoryId),
recordIdentifier(params.prototypeId),
filters.page,
filters.build,
)
if (scenario === "empty") {
if (filters.page !== 1) throw new MockStoreError(404, "Page not found.")
response.builds = []
response.prototype.builds = []
response.prototype.latestBuild = null
response.pagination = {
page: 1,
pageSize: response.pagination.pageSize,
Expand Down
26 changes: 24 additions & 2 deletions hub/client/application/hub/mocks/create-mock-store/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,13 +253,35 @@ export function createMockStore({ origin, seed = createFixtureSeed() }: Options)
}
},

getBuildHistory(repositoryId: string, prototypeId: string, page = 1): BuildHistoryResponse {
getBuildHistory(
repositoryId: string,
prototypeId: string,
page = 1,
buildNumber?: number,
): BuildHistoryResponse {
session.requireViewer()
const prototype = prototypeRecord(repositoryId, prototypeId)
const selected = paginate(prototype.builds, page, buildHistoryPageSize)
const pinnedBuild = prototype.builds.find(
({ number, state }) => number === buildNumber && state === "successful",
)
const pickerBuilds = [...selected.records]
if (pinnedBuild && !pickerBuilds.some(({ number }) => number === pinnedBuild.number)) {
pickerBuilds.push(pinnedBuild)
}
const latestBuild = prototype.builds[0]
return {
repository: repositoryRecord(repositoryId),
prototype,
prototype: {
...prototype,
builds: pickerBuilds,
latestBuild:
prototype.latestBuild !== undefined
? prototype.latestBuild
: latestBuild
? { number: latestBuild.number, state: latestBuild.state }
: null,
},
builds: selected.records,
pagination: selected.pagination,
}
Expand Down
17 changes: 16 additions & 1 deletion hub/client/application/hub/mocks/pagination.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,15 +90,28 @@ describe("mock collection pagination", () => {
expect(first.pagination.pageSize).toBe(25)
expect(first.pagination.totalCount).toBeGreaterThan(50)
expect(first.builds).toHaveLength(25)
expect(first.prototype.builds.map(({ number }) => number)).toEqual(
first.builds.map(({ number }) => number),
)
const pinnedBuild = first.builds.find(({ state }) => state === "successful")
if (!pinnedBuild) throw new Error("The history requires a successful Build to pin.")
const numbers = first.builds.map(({ number }) => number)
for (let page = 2; page <= first.pagination.pageCount; page += 1) {
const next = await getBuildHistory(new Request(`${url}?page=${page}`), "2001", "1")
const next = await getBuildHistory(
new Request(`${url}?page=${page}&build=${pinnedBuild.number}`),
"2001",
"1",
)
expect(next.pagination).toMatchObject({
page,
pageSize: 25,
totalCount: first.pagination.totalCount,
})
expect(next.builds).toHaveLength(Math.min(25, first.pagination.totalCount - (page - 1) * 25))
expect(next.prototype.builds.map(({ number }) => number).sort((a, b) => b - a)).toEqual(
[pinnedBuild.number, ...next.builds.map(({ number }) => number)].sort((a, b) => b - a),
)
expect(next.prototype.latestBuild).toEqual(first.prototype.latestBuild)
numbers.push(...next.builds.map(({ number }) => number))
}
expect(numbers).toHaveLength(first.pagination.totalCount)
Expand All @@ -110,12 +123,14 @@ describe("mock collection pagination", () => {
"3",
)
expect(empty.builds).toEqual([])
expect(empty.prototype.builds).toEqual([])
expect(empty.pagination.pageSize).toBe(25)
const forcedEmpty = await fetch(`${store.origin}/api/repositories/2001/prototypes/1/builds`, {
headers: { "X-Replica-Mock-Scenario": "empty" },
})
await expect(forcedEmpty.json()).resolves.toMatchObject({
builds: [],
prototype: { builds: [], latestBuild: null },
pagination: { page: 1, pageSize: 25, totalCount: 0, pageCount: 1 },
})
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export function getBuildHistory(request: Request, repositoryId: string, prototyp
request.url,
)
if (query.page > 1) url.searchParams.set("page", String(query.page))
if (query.build) url.searchParams.set("build", String(query.build))

return requestJson(url, buildHistoryResponseSchema, {
signal: request.signal,
Expand Down
271 changes: 271 additions & 0 deletions hub/client/application/hub/routes/real-build-history.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,271 @@
import type { RouteConfigEntry } from "@react-router/dev/routes"
import { act, fireEvent, render, screen, within } from "@testing-library/react"
import { http, HttpResponse } from "msw"
import { setupServer } from "msw/node"
import type { ComponentType } from "react"
import {
createBrowserRouter,
RouterProvider,
useLoaderData,
type ActionFunction,
type LoaderFunction,
type RouteObject,
} from "react-router"
import { describe, expect, it, onTestFinished, vi } from "vitest"

type RouteModule = {
default?: ComponentType<{ loaderData: unknown }>
clientLoader?: LoaderFunction
clientAction?: ActionFunction
ErrorBoundary?: ComponentType
HydrateFallback?: ComponentType
}

const routeModules = import.meta.glob<RouteModule>([
"../root.tsx",
"./**/index.tsx",
"!./fixtures/**",
])

function applicationRoute(entry: RouteConfigEntry): RouteObject {
const modulePath =
entry.file === "root.tsx" ? "../root.tsx" : `./${entry.file.replace(/^routes\//, "")}`
const loadModule = routeModules[modulePath]
if (!loadModule) throw new Error(`Missing application route module: ${entry.file}`)
const common = {
id: entry.id ?? entry.file.replace(/\.tsx$/, ""),
path: entry.path,
lazy: async () => {
const module = await loadModule()
const Page = module.default
return {
loader: module.clientLoader,
action: module.clientAction,
ErrorBoundary: module.ErrorBoundary,
HydrateFallback: module.HydrateFallback,
Component: Page ? () => <Page loaderData={useLoaderData()} /> : undefined,
}
},
}
return entry.index
? { ...common, index: true }
: { ...common, children: entry.children?.map(applicationRoute) }
}

async function renderApplication(path: string) {
const [{ default: routes }, { HubThemeProvider }] = await Promise.all([
import("../routes"),
import("@hooks/use-hub-theme"),
])
window.history.replaceState(null, "", path)
const router = createBrowserRouter(
[applicationRoute({ id: "root", file: "root.tsx", children: routes })],
{ window },
)
onTestFinished(() => router.dispose())
await act(async () => {
await vi.waitFor(() => expect(router.state.initialized).toBe(true), { timeout: 10_000 })
})
render(
<HubThemeProvider>
<RouterProvider router={router} />
</HubThemeProvider>,
)
return router
}

describe("real Build history", () => {
it("opens History from a pinned real Build and keeps that Build selected", async () => {
vi.stubEnv("MODE", "development")
vi.stubEnv("DEV", true)
const repositoryId = "11111111-1111-4111-8111-111111111111"
const prototypeId = "22222222-2222-4222-8222-222222222222"
const userId = "44444444-4444-4444-8444-444444444444"
const prototypePath = `/repositories/${repositoryId}/prototypes/${prototypeId}`
const repository = { id: repositoryId, nameWithOwner: "team/design", defaultBranch: "main" }
function build(number: number, state: string) {
return {
number,
repositoryId,
prototypeId,
state,
commitSha: null,
commitAuthorProvider: null,
commitAuthorIssuer: null,
commitAuthorProviderUserId: null,
commitAuthorLogin: null,
commitAuthorName: null,
commitAuthorAvatarUrl: null,
createdAt: `2026-11-0${number}T12:00:00.000Z`,
startedAt: null,
finishedAt: null,
previewUrl: null,
desktopScreenshotUrl: null,
narrowScreenshotUrl: null,
failureSummary: null,
}
}
const builds = [build(4, "running"), build(3, "successful"), build(2, "failed")]
const prototype = {
id: prototypeId,
repositoryId,
name: "Welcome flow",
branchName: "prototype/welcome",
description: null,
authorProvider: "github",
authorLogin: "mona",
authorName: "Mona",
canEdit: true,
startPage: "/welcome",
latestBuild: { number: 4, state: "running" },
builds: [...builds, build(1, "successful")],
}
const historyRequests: string[] = []
const server = setupServer(
http.get(`${window.location.origin}/api/auth/session`, () =>
HttpResponse.json({
authenticated: true,
membershipId: "55555555-5555-4555-8555-555555555555",
userId,
provider: "github",
login: "octocat",
name: "Octocat",
role: "MEMBER",
}),
),
http.get(`${window.location.origin}/api/session`, () =>
HttpResponse.json({ error: "This endpoint is unavailable in real mode." }, { status: 404 }),
),
http.get(`${window.location.origin}/api/workspace`, () =>
HttpResponse.json({
viewer: {
id: userId,
provider: "github",
login: "octocat",
name: "Octocat",
avatarUrl: null,
},
repositories: [repository],
capabilities: {
createPrototypes: false,
reviewPrototypes: false,
manageSharing: false,
administerHub: false,
},
}),
),
http.get(`${window.location.origin}/api${prototypePath}`, ({ request }) => {
const selected = new URL(request.url).searchParams.get("build") === "3"
return HttpResponse.json({
repository,
prototype,
selectedBuild: selected ? build(3, "successful") : null,
showPrototypeInfo: false,
})
}),
http.get(`${window.location.origin}/api${prototypePath}/review-comments`, () =>
HttpResponse.json({ error: "Not found." }, { status: 404 }),
),
http.get(`${window.location.origin}/api${prototypePath}/builds`, ({ request }) => {
const url = new URL(request.url)
const page = url.searchParams.get("page") ?? "1"
const pageBuilds = page === "1" ? builds : [build(1, "successful")]
const pinned = page === "2" && url.searchParams.get("build") === "3"
historyRequests.push(url.search)
return HttpResponse.json({
repository,
prototype: {
...prototype,
builds: pinned ? [build(3, "successful"), ...pageBuilds] : pageBuilds,
},
builds: pageBuilds,
pagination: { page: Number(page), pageSize: 3, totalCount: 4, pageCount: 2 },
})
}),
)
server.listen({ onUnhandledRequest: "error" })
onTestFinished(() => server.close())
const router = await renderApplication(`${prototypePath}?build=3`)
expect(await screen.findByText("Build 3 has no preview")).toBeVisible()

fireEvent.click(screen.getByRole("button", { name: "More actions" }))
const historyLink = within(screen.getByRole("menuitem", { name: "History" })).getByRole("link")
const historyUrl = new URL(historyLink.getAttribute("href") ?? "", window.location.origin)
expect(historyUrl.pathname).toBe(`${prototypePath}/builds`)
expect(historyUrl.searchParams.get("build")).toBe("3")
fireEvent.click(historyLink)

expect(await screen.findByRole("heading", { name: "History", level: 2 })).toBeVisible()
expect(router.state.location.pathname).toBe(`${prototypePath}/builds`)
expect(historyRequests.map((query) => Object.fromEntries(new URLSearchParams(query)))).toEqual([
{ build: "3" },
])
expect(screen.queryByRole("link", { name: "Analytics" })).not.toBeInTheDocument()
expect(screen.queryByRole("link", { name: "Learnings" })).not.toBeInTheDocument()
expect(document.querySelector('form[action="/api/auth/session/sign-out"]')).not.toBeNull()
expect(document.querySelector('form[action="/session"]')).toBeNull()
const history = screen.getByRole("list", { name: "History" })
const successful = within(history).getByRole("link", { name: "Build 3" })
expect(new URL(successful.getAttribute("href") ?? "", window.location.origin)).toMatchObject({
pathname: prototypePath,
search: "?build=3",
})
expect(within(history).getByText("Build 2").closest("a")).toBeNull()
expect(within(history).getByText("Build 4").closest("a")).toBeNull()
const older = new URL(
screen.getByRole("link", { name: "Older Builds" }).getAttribute("href") ?? "",
window.location.origin,
)
expect(older.pathname).toBe(`${prototypePath}/builds`)
expect(Object.fromEntries(older.searchParams)).toEqual({ page: "2", build: "3" })
const close = new URL(
screen.getByRole("link", { name: "Return to prototype" }).getAttribute("href") ?? "",
window.location.origin,
)
expect(close.pathname).toBe(prototypePath)
expect(close.searchParams.get("build")).toBe("3")
fireEvent.click(screen.getByRole("button", { name: "Choose build, v3" }))
const firstPicker = screen.getByRole("menu")
expect(within(firstPicker).getByRole("menuitem", { name: /v2/ })).toHaveAttribute(
"aria-disabled",
"true",
)
expect(within(firstPicker).getByRole("menuitem", { name: /v4/ })).toHaveAttribute(
"aria-disabled",
"true",
)
fireEvent.keyDown(firstPicker, { key: "Escape" })

fireEvent.click(screen.getByRole("link", { name: "Older Builds" }))
expect(await screen.findByRole("link", { name: "Build 1" })).toBeVisible()
expect(historyRequests.map((query) => Object.fromEntries(new URLSearchParams(query)))).toEqual([
{ build: "3" },
{ page: "2", build: "3" },
])
expect(screen.queryByRole("link", { name: "Older Builds" })).not.toBeInTheDocument()
const olderClose = new URL(
screen.getByRole("link", { name: "Return to prototype" }).getAttribute("href") ?? "",
window.location.origin,
)
expect(olderClose.pathname).toBe(prototypePath)
expect(olderClose.searchParams.get("build")).toBe("3")
fireEvent.click(screen.getByRole("button", { name: "Choose build, v3" }))
const picker = screen.getByRole("menu")
const selectedBuild = within(picker).getByRole("menuitem", { name: /v3/ })
expect(within(selectedBuild).getByRole("link")).toHaveAttribute(
"href",
`${prototypePath}?build=3`,
)
expect(within(picker).getByRole("menuitem", { name: /v1/ })).toBeVisible()
expect(within(picker).queryByRole("menuitem", { name: /v2/ })).not.toBeInTheDocument()
expect(within(picker).queryByRole("menuitem", { name: /v4/ })).not.toBeInTheDocument()
fireEvent.keyDown(picker, { key: "Escape" })
fireEvent.click(screen.getByRole("link", { name: "Newest Builds" }))
expect(await screen.findByRole("link", { name: "Build 3" })).toBeVisible()
expect(historyRequests.map((query) => Object.fromEntries(new URLSearchParams(query)))).toEqual([
{ build: "3" },
{ page: "2", build: "3" },
{ build: "3" },
])
}, 15_000)
})
Loading
Loading