Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 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
244 changes: 244 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,244 @@
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 page = new URL(request.url).searchParams.get("page") ?? "1"
historyRequests.push(new URL(request.url).search)
return HttpResponse.json({
repository,
prototype,
builds: page === "1" ? builds : [build(1, "successful")],
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).toEqual([""])
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("link", { name: "Older Builds" }))
expect(await screen.findByRole("link", { name: "Build 1" })).toBeVisible()
expect(historyRequests).toEqual(["", "?page=2"])
expect(screen.queryByRole("link", { name: "Older Builds" })).not.toBeInTheDocument()
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: /v2/ })).toHaveAttribute(
"aria-disabled",
"true",
)
expect(within(picker).getByRole("menuitem", { name: /v4/ })).toHaveAttribute(
"aria-disabled",
"true",
)
fireEvent.keyDown(picker, { key: "Escape" })
fireEvent.click(screen.getByRole("link", { name: "Newest Builds" }))
expect(await screen.findByRole("link", { name: "Build 3" })).toBeVisible()
expect(historyRequests).toEqual(["", "?page=2", ""])
}, 15_000)
})
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ describe("real prototype index", () => {
"https://github.com/mona",
)

expect(screen.queryByRole("button", { name: "More actions" })).not.toBeInTheDocument()
expect(screen.getByRole("button", { name: "More actions" })).toBeVisible()
expect(document.querySelector('form[action="/api/auth/session/sign-out"]')).not.toBeNull()
expect(document.querySelector('form[action="/session"]')).toBeNull()

Expand Down Expand Up @@ -539,7 +539,7 @@ describe("real prototype index", () => {
expect(screen.queryByRole("link", { name: "Create" })).not.toBeInTheDocument()
expect(screen.queryByRole("button", { name: "Branch from here" })).not.toBeInTheDocument()
expect(screen.queryByRole("link", { name: "Edit prototype listings" })).not.toBeInTheDocument()
expect(screen.queryByRole("button", { name: "More actions" })).not.toBeInTheDocument()
expect(screen.getByRole("button", { name: "More actions" })).toBeVisible()
fireEvent.click(await screen.findByRole("button", { name: "Edit details" }))
const editor = screen.getByRole("dialog", { name: "Edit prototype details" })
fireEvent.change(within(editor).getByRole("textbox", { name: "Name" }), {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,13 @@ export function BuildHistoryScreen({
data: BuildHistoryResponse
}) {
const location = useLocation()
const mock = import.meta.env.DEV && import.meta.env.MODE === "mock"

return (
<BuildsIndexPage
data={buildHistoryData(workspace, data, new URLSearchParams(location.search))}
data={buildHistoryData(workspace, data, new URLSearchParams(location.search), {
real: !mock,
})}
/>
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,28 @@ export function buildHistoryData(
workspace: WorkspaceResponse,
data: BuildHistoryResponse,
search: URLSearchParams,
options: { real?: boolean } = {},
): BuildsIndexPageData {
const prototypePath = `/repositories/${data.repository.id}/prototypes/${data.prototype.id}`
const path = `${prototypePath}/builds`
const selectedBuild =
data.prototype.builds.find((build) => String(build.number) === search.get("build")) ?? null
data.prototype.builds.find(
(build) => build.state === "successful" && String(build.number) === search.get("build"),
) ?? null
const selectedNumber = selectedBuild?.number ?? null
const workspaceData = prototypeWorkspace({
workspace,
repository: data.repository,
prototype: data.prototype,
selectedBuild,
search,
surface: "history",
real: options.real,
})

return {
...prototypeWorkspace({
workspace,
repository: data.repository,
prototype: data.prototype,
selectedBuild,
search,
surface: "history",
}),
...workspaceData,
shareLinksPath: options.real ? undefined : workspaceData.shareLinksPath,
builds: data.builds.map((build) => {
const githubAuthor =
build.commitAuthorProvider === undefined || build.commitAuthorProvider === "github"
Expand Down Expand Up @@ -53,7 +59,7 @@ export function buildHistoryData(
: "Commit unavailable",
commitSha: build.commitSha,
createdAt: build.createdAt,
createdLabel: `Created ${formatBuildTime(build.createdAt)}`,
createdLabel: `Added to Hub ${formatBuildTime(build.createdAt)}`,
number: build.number,
numberLabel: `Build ${build.number}`,
path:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { describe, expect, it, vi } from "vitest"

import { formatBuildTime } from "."

describe("formatBuildTime()", () => {
it("shows the viewer's timezone for the Build date", () => {
vi.stubEnv("TZ", "America/Los_Angeles")

expect(formatBuildTime("2026-01-15T12:00:00Z")).toBe("Jan 15, 2026, 4:00 AM PST")
expect(formatBuildTime("2026-07-15T12:00:00Z")).toBe("Jul 15, 2026, 5:00 AM PDT")
})
})
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
/** Names the viewer's timezone so Build times are unambiguous. */
export function formatBuildTime(timestamp: string) {
return new Intl.DateTimeFormat("en", {
dateStyle: "medium",
timeStyle: "short",
year: "numeric",
month: "short",
day: "numeric",
hour: "numeric",
minute: "2-digit",
timeZoneName: "short",
}).format(new Date(timestamp))
Comment thread
nshki marked this conversation as resolved.
Resolved
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ export function prototypeShowData(

return {
...workspaceData,
historyPath: options.real ? undefined : workspaceData.historyPath,
shareLinksPath: options.real ? undefined : workspaceData.shareLinksPath,
buildPinned: search.has("build"),
controlsIdentity: data.controlsIdentity,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export function prototypeWorkspace({
: null,
},
branchName: prototype.branchName,
branchPath: resourcePath(path, search),
branchPath: resourcePath(path, search, { build: pinnedBuild }),
prototypeName: prototype.name,
buildOptions: builds.map((build) => ({
number: build.number,
Expand Down
Loading
Loading