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
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ export function createProductStore(context: MockFlowContext) {
return {
repository: context.repositoryRecord(repositoryId),
templates: templates(repositoryId),
canCreate: session.read().capabilities.createPrototypes,
canCreate: true,
}
},

Expand All @@ -179,7 +179,7 @@ export function createProductStore(context: MockFlowContext) {
return {
repository: context.repositoryRecord(repositoryId),
template,
canCreate: session.read().capabilities.createPrototypes,
canCreate: true,
controlsIdentity: context.controlsIdentity([
"template",
repositoryId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,28 @@ describe("authorizeCopilotHandoff()", () => {
)
vi.stubGlobal("fetch", fetch)

await expect(authorizeCopilotHandoff("2001", { allowCopyFallback: true })).resolves.toBe(false)
await expect(authorizeCopilotHandoff("2001", { allowCopyFallback: true })).resolves.toBe("copy")
await expect(authorizeCopilotHandoff("2001")).rejects.toMatchObject({ status: 503 })
})

it.each([undefined, true])(
"denies a hidden repository even when copy fallback is %s",
async (allowCopyFallback) => {
vi.stubGlobal(
"fetch",
vi
.fn()
.mockResolvedValue(
Response.json({ error: "Repository not found", canCopy: true }, { status: 404 }),
),
)

await expect(authorizeCopilotHandoff("2001", { allowCopyFallback })).resolves.toBe(false)
},
)

it.each([
{ status: 401, canCopy: true },
{ status: 404, canCopy: true },
{ status: 503, canCopy: undefined },
{ status: 503, canCopy: false },
])("rejects a $status with no applicable copy authorization", async ({ status, canCopy }) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,23 @@ const copyFallback = z.object({ canCopy: z.literal(true) })
export async function authorizeCopilotHandoff(
repositoryId: string,
{ allowCopyFallback = false } = {},
) {
): Promise<boolean | "copy"> {
try {
const permission = await requestJson(
new URL(`/api/repositories/${repositoryId}/create/permission`, window.location.origin),
z.object({ canCreate: z.boolean() }),
)
return permission.canCreate
} catch (error) {
// Hub hides repositories the viewer can no longer see behind a 404.
if (error instanceof ApiRequestError && error.status === 404) return false
if (
allowCopyFallback &&
error instanceof ApiRequestError &&
error.status === 503 &&
copyFallback.safeParse(error.body).success
) {
return false
return "copy"
}
throw error
}
Expand Down
29 changes: 21 additions & 8 deletions hub/client/application/hub/routes/expanded-flows.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -237,21 +237,34 @@ describe("Hub expanded frontend flows", () => {
expect(router.state.location.pathname).toBe("/repositories/2001/new")
})

it("keeps prototype creation and management unavailable to a reader", async () => {
it("allows a reader to start a prompt handoff while denying listing writes", async () => {
const store = createMockStore({ origin: window.location.origin })
store.session.select("reader")
const server = setupServer(...createMockHandlers(store))
const router = await renderHubFlow(server, "/repositories/2001", { workspaceRoutes })
expect(screen.queryByRole("link", { name: "Edit prototype listings" })).not.toBeInTheDocument()
expect(screen.queryByRole("link", { name: "Create" })).not.toBeInTheDocument()

await router.settle(() => router.navigate("/repositories/2001/new"))
await router.settle(() => fireEvent.click(screen.getByRole("link", { name: "Create" })))
expect(router.state.location.pathname).toBe("/repositories/2001/new")

expect(screen.getByRole("button", { name: "Create prototype" })).toBeDisabled()
expect(screen.getByRole("main")).toHaveTextContent(/do not have permission to create/i)
expect(
screen.queryByRole("dialog", { name: "Continue in Copilot app" }),
).not.toBeInTheDocument()
fireEvent.change(screen.getByRole("textbox", { name: "What should we create?" }), {
target: { value: "Simplify the settings flow" },
})
await router.settle(() =>
fireEvent.click(screen.getByRole("button", { name: "Create prototype" })),
)
expect(screen.getByRole("dialog", { name: "Continue in Copilot app" })).toBeVisible()
const previousName = store.getPrototype("2001", "1").prototype.name
const write = await fetch(
`${window.location.origin}/api/repositories/2001/prototype-management/1`,
{
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Unauthorized edit", description: null, startPage: "/" }),
},
)
expect(write.status).toBe(403)
expect(store.getPrototype("2001", "1").prototype.name).toBe(previousName)
})

it("shares management edits with the existing preview and repository", async () => {
Expand Down
144 changes: 144 additions & 0 deletions hub/client/application/hub/routes/real-prototype-index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,150 @@ async function renderApplication(path: string) {
}

describe("real prototype index", () => {
it.each(["github", "entra"])(
"starts and copies Default and selected-template sessions for a visible %s member without write capabilities",
async (provider) => {
vi.stubEnv("MODE", "development")
vi.stubEnv("DEV", true)
const repositoryId = "11111111-1111-4111-8111-111111111111"
const repository = {
id: repositoryId,
nameWithOwner: "team/design",
defaultBranch: "main",
capabilities: {
browseTemplates: true,
reviewPrototypes: false,
manageSharing: false,
managePrototypeListings: false,
},
}
const userId = "44444444-4444-4444-8444-444444444444"
const writeText = vi.fn().mockResolvedValue(undefined)
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } })
const permissionChecks = vi.fn()
const writes = vi.fn()
const templateRoute = "/settings?tab=profile#details"
const server = setupServer(
http.get(`${window.location.origin}/api/auth/session`, () =>
HttpResponse.json({
authenticated: true,
membershipId: "55555555-5555-4555-8555-555555555555",
userId,
provider,
login: "member",
name: "Member",
role: "MEMBER",
}),
),
http.get(`${window.location.origin}/api/workspace`, () =>
HttpResponse.json({
viewer: { id: userId, provider, login: "member", name: "Member", avatarUrl: null },
capabilities: {
createPrototypes: false,
reviewPrototypes: false,
manageSharing: false,
administerHub: false,
},
repositories: [repository],
}),
),
http.get(`${window.location.origin}/api/repositories/${repositoryId}/templates`, () =>
HttpResponse.json({
repository,
canCreate: true,
submissionMode: "copilot",
templates: [
{
id: "default",
name: "Default",
description: "Start at home.",
route: "/",
previewUrl: null,
screenshotUrl: null,
buildNumber: null,
},
{
id: "settings",
name: "Settings",
description: "Manage settings.",
route: templateRoute,
previewUrl: null,
screenshotUrl: null,
buildNumber: 1,
},
],
}),
),
http.get(
`${window.location.origin}/api/repositories/${repositoryId}/create/permission`,
() => {
permissionChecks()
return HttpResponse.json({ canCreate: true })
},
),
)
server.events.on("request:start", ({ request }) => {
if (request.method !== "GET" && new URL(request.url).pathname.startsWith("/api/")) writes()
})
server.listen({ onUnhandledRequest: "error" })
onTestFinished(() => server.close())
const router = await renderApplication(`/repositories/${repositoryId}/new`)
const brief = "Make settings easier to use"
fireEvent.change(await screen.findByRole("textbox", { name: "What should we create?" }), {
target: { value: brief },
})

for (const selected of [false, true]) {
if (selected) {
fireEvent.click(screen.getByRole("button", { name: "Template: Default" }))
fireEvent.click(screen.getByRole("option", { name: `Settings ${templateRoute}` }))
}
fireEvent.click(screen.getByRole("button", { name: "Create prototype" }))
const dialog = await screen.findByRole("dialog", { name: "Continue in Copilot app" })
const openApp = within(dialog).getByRole<HTMLAnchorElement>("link", {
name: "Open Copilot App",
})
const launch = new URL(openApp.href)
expect(launch.origin + launch.pathname).toBe("https://github.com/copilot/app/launch")
const session = new URL(launch.searchParams.get("open")!)
expect(session.searchParams.get("repo")).toBe(repository.nameWithOwner)
const prompt = session.searchParams.get("prompt")!
expect(prompt).toContain(brief)
if (selected) {
expect(prompt).toContain(encodeURIComponent(templateRoute))
expect(prompt).toContain("startPage")
} else {
expect(prompt).not.toContain("TEMPLATE_ROUTE_DATA")
}
const open = vi.fn((event: MouseEvent) => event.preventDefault())
openApp.addEventListener("click", open, { once: true })
fireEvent.click(openApp)
expect(open).toHaveBeenCalledOnce()
fireEvent.click(within(dialog).getByRole("button", { name: "Copy prompt" }))
await waitFor(() => expect(writeText).toHaveBeenLastCalledWith(prompt))
fireEvent.click(within(dialog).getByRole("button", { name: "Close Copilot app dialog" }))
}
expect(permissionChecks).toHaveBeenCalledTimes(2)
server.use(
http.get(
`${window.location.origin}/api/repositories/${repositoryId}/create/permission`,
() => HttpResponse.json({ error: "Repository not found." }, { status: 404 }),
),
)
writeText.mockClear()

fireEvent.click(screen.getByRole("button", { name: "Create prototype" }))

expect(await screen.findByRole("alert")).toBeVisible()
expect(screen.getByRole("textbox", { name: "What should we create?" })).toHaveValue(brief)
expect(screen.queryByRole("button", { name: "Copy prompt" })).not.toBeInTheDocument()
expect(screen.queryByRole("link", { name: "Open Copilot App" })).not.toBeInTheDocument()
expect(writeText).not.toHaveBeenCalled()
expect(writes).not.toHaveBeenCalled()
expect(router.state.location.pathname).toBe(`/repositories/${repositoryId}/new`)
},
)

it("opens prototype details from the real index after sign-in", async () => {
vi.stubEnv("MODE", "development")
vi.stubEnv("DEV", true)
Expand Down
4 changes: 2 additions & 2 deletions hub/client/application/hub/routes/session-flow.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ describe("Hub mock session flow", () => {
)
})

it("lets Mona save details without granting creation, sharing or management", async () => {
it("lets Mona branch and save details without granting sharing or management", async () => {
const store = createMockStore({ origin: window.location.origin })
store.session.select("reader")
const server = setupServer(...createMockHandlers(store))
Expand All @@ -109,7 +109,7 @@ describe("Hub mock session flow", () => {

expect(await screen.findByRole("button", { name: "Account menu for @mona" })).toBeVisible()
fireEvent.click(screen.getByRole("button", { name: "View prototype" }))
expect(screen.queryByRole("button", { name: "Branch from here" })).not.toBeInTheDocument()
expect(screen.getByRole("button", { name: "Branch from here" })).toBeVisible()
fireEvent.click(screen.getByRole("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 @@ -179,11 +179,11 @@ describe("Public sharing navigation", () => {
})

it.each([
{ profile: "owner", login: "octocat", canCreate: true },
{ profile: "reader", login: "mona", canCreate: false },
{ profile: "owner", login: "octocat" },
{ profile: "reader", login: "mona" },
] as const)(
"keeps $profile repository permissions but hides Hub administrator entries and sharing controls when access is denied",
async ({ profile, login, canCreate }) => {
async ({ profile, login }) => {
const store = createMockStore({ origin: window.location.origin })
store.session.select(profile)
const server = setupServer(...createMockHandlers(store))
Expand All @@ -197,7 +197,7 @@ describe("Public sharing navigation", () => {
expect(new URL(navigationLink("/notifications").href).searchParams.get("repositoryId")).toBe(
"2002",
)
expect(screen.queryByRole("link", { name: "Create" }) !== null).toBe(canCreate)
expect(screen.getByRole("link", { name: "Create" })).toBeVisible()
expectNoSharingAdministration()
},
)
Expand Down
16 changes: 5 additions & 11 deletions hub/client/application/hub/routes/sidebar-consistency.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -130,12 +130,10 @@ function administrationLinks() {

function expectRepositoryNavigation({
admin,
canCreate = true,
welcomeHidden = false,
unreadCount,
}: {
admin: boolean
canCreate?: boolean
welcomeHidden?: boolean
unreadCount: number
}) {
Expand All @@ -146,7 +144,7 @@ function expectRepositoryNavigation({
const links = navigationLinks()
expect(links.map(linkTarget)).toEqual([
...(welcomeHidden ? [] : ["/welcome?repositoryId=2002"]),
...(canCreate ? ["/repositories/2002/new"] : []),
"/repositories/2002/new",
"/repositories/2002",
"/notifications?repositoryId=2002",
"/repositories/2002/analytics",
Expand Down Expand Up @@ -191,19 +189,16 @@ describe("Hub sidebar consistency", () => {
}
}, 15_000)

it.each([
{ profile: "owner", canCreate: true },
{ profile: "reader", canCreate: false },
] as const)(
it.each([{ profile: "owner" }, { profile: "reader" }] as const)(
"keeps $profile permissions, hidden Welcome and unread counts when moving between repository and settings pages",
async ({ profile, canCreate }) => {
async ({ profile }) => {
const store = createMockStore({ origin: window.location.origin })
store.session.select(profile)
store.settings.mutate({ operation: "welcome-hide" })
const unreadCount = store.getWorkspace().navigation!.notificationsUnreadCount
const server = setupServer(...createMockHandlers(store))
const router = await renderHubFlow(server, "/repositories/2002", { workspaceRoutes })
expectRepositoryNavigation({ admin: false, canCreate, welcomeHidden: true, unreadCount })
expectRepositoryNavigation({ admin: false, welcomeHidden: true, unreadCount })

for (const pathname of [
"/repositories/2002/analytics",
Expand All @@ -214,7 +209,7 @@ describe("Hub sidebar consistency", () => {
const link = navigationLinks().find((item) => new URL(item.href).pathname === pathname)!
await router.settle(() => fireEvent.click(link))
expect(router.state.location.pathname).toBe(pathname)
expectRepositoryNavigation({ admin: false, canCreate, welcomeHidden: true, unreadCount })
expectRepositoryNavigation({ admin: false, welcomeHidden: true, unreadCount })
}
},
)
Expand Down Expand Up @@ -277,7 +272,6 @@ describe("Hub sidebar consistency", () => {

expectRepositoryNavigation({
admin: true,
canCreate: false,
unreadCount: store.getWorkspace().navigation!.notificationsUnreadCount,
})
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,7 @@ export function prototypeShowData(
branchFromLabel: `Branch from: ${data.prototype.name}`,
branchPlaceholder: "What changes would you like to make?",
branchSubmitLabel: "Start from this prototype",
branchSubmissionMode: (options.real ? data.canBranch : workspace.capabilities?.createPrototypes)
? "copilot"
: "disabled",
branchSubmissionMode: !options.real || data.canBranch ? "copilot" : "disabled",
branchInitialRoute: options.real ? (data.prototype.startPage ?? "/") : undefined,
branchInstructions: `BRIEF-END\nStart from the existing \`${data.prototype.branchName}\` prototype branch in this repository. Create a new branch from that branch for the changes above, keeping the existing prototype as the starting point.\nBuild an interactive working UI prototype. Use the repository's \`create-prototype\` skill if it is installed; otherwise follow its own instructions and conventions.\nDo not publish, commit, or push without explicit approval.`,
branchPageInstructions:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export function repositoryWorkspace(
) {
const browseTemplates = real
? workspace.repositories.find(({ id }) => id === repository.id)?.capabilities?.browseTemplates
: workspace.capabilities?.createPrototypes
: true
const canManageAnalytics =
repository.capabilities?.manageAnalytics ||
workspace.repositories.find((entry) => entry.id === repository.id)?.capabilities
Expand Down
Loading
Loading