The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
// @vitest-environment jsdom
/*
* Copyright 2026 BoxLite AI
* SPDX-License-Identifier: AGPL-3.0
*/
import { BoxliteError } from '@/api/errors'
import React, { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { MemoryRouter } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { RegistriesPanel } from './RegistriesPanel'
// Drive a React controlled input the way a user typing would.
function typeInto(el: HTMLInputElement, value: string) {
const desc = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')
desc?.set?.call(el, value)
el.dispatchEvent(new Event('input', { bubbles: true }))
}
const PASSWORD = 'ghp_not-a-real-token'
const state = vi.hoisted(() => ({
credentials: [] as unknown[],
listError: null as unknown,
byId: new Map<string, unknown>(),
canWrite: true,
loading: false,
cached: false,
}))
const mocks = vi.hoisted(() => ({
refetch: vi.fn(),
create: vi.fn(),
update: vi.fn(),
resetUpdate: vi.fn(),
remove: vi.fn(),
reset: vi.fn(),
handleApiError: vi.fn(),
toastError: vi.fn(),
toastSuccess: vi.fn(),
}))
vi.mock('@/lib/error-handling', () => ({ handleApiError: mocks.handleApiError }))
vi.mock('sonner', () => ({ toast: { error: mocks.toastError, success: mocks.toastSuccess } }))
vi.mock('@/hooks/queries/useRegistriesQuery', () => ({
useRegistriesQuery: () => ({
data: state.loading || (state.listError && !state.cached) ? undefined : state.credentials,
error: state.listError,
isLoading: state.loading,
isFetching: state.loading,
refetch: mocks.refetch,
}),
}))
vi.mock('@/hooks/queries/useBoxesByImageQuery', () => ({
useBoxesByImageQuery: () => ({ byId: state.byId }),
}))
vi.mock('@/hooks/mutations/useRegistryMutations', () => ({
useCreateRegistryMutation: () => ({ mutateAsync: mocks.create, reset: mocks.reset, isPending: false }),
useUpdateRegistryMutation: () => ({ mutateAsync: mocks.update, reset: mocks.resetUpdate, isPending: false }),
useDeleteRegistryMutation: () => ({ mutateAsync: mocks.remove, isPending: false }),
}))
vi.mock('@/hooks/useSelectedOrganization', () => ({
useSelectedOrganization: () => ({
selectedOrganization: { id: 'org-1' },
organizationMembers: [{ userId: 'user-1', name: 'Chen Ming', email: '[email protected]' }],
authenticatedUserHasPermission: (permission: string) => permission !== 'write:registries' || state.canWrite,
}),
}))
const CREDENTIAL = {
id: 'credential-1',
kind: 'basic',
registryHost: 'ghcr.io',
repositoryPrefix: 'acme/',
username: 'acme-bot',
createdBy: 'user-1',
createdAt: '2026-01-01T00:00:00.000Z',
}
let root: Root | null = null
let host: HTMLDivElement
async function renderPanel(entry = '/dashboard/images/registries') {
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
await act(async () =>
root?.render(React.createElement(MemoryRouter, { initialEntries: [entry] }, React.createElement(RegistriesPanel))),
)
}
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
Element.prototype.scrollIntoView = vi.fn()
state.credentials = [CREDENTIAL]
state.listError = null
state.byId = new Map()
state.canWrite = true
state.cached = false
state.loading = false
vi.resetAllMocks()
mocks.create.mockResolvedValue({})
mocks.update.mockResolvedValue({})
mocks.remove.mockResolvedValue(undefined)
})
afterEach(() => {
act(() => root?.unmount())
root = null
document.body.innerHTML = ''
})
const button = (text: string) => [...document.querySelectorAll('button')].find((b) => b.textContent === text)
const field = (id: string) => document.getElementById(id) as HTMLInputElement
const open = () => act(() => button('Connect a registry')?.click())
async function fillAndSubmit(values: { prefix?: string; username?: string; password?: string }) {
act(() => {
if (values.prefix !== undefined) typeInto(field('registry-prefix'), values.prefix)
typeInto(field('registry-username'), values.username ?? 'acme-bot')
typeInto(field('registry-password'), values.password ?? PASSWORD)
})
await act(async () => field('registry-password').form?.requestSubmit())
}
describe('the credential list', () => {
it.each([
['', 'every repository'],
['acme/', 'acme/*'],
])('matches the displayed Covers label for %s', async (repositoryPrefix, query) => {
state.credentials = [{ ...CREDENTIAL, repositoryPrefix }]
await renderPanel()
const input = document.querySelector<HTMLInputElement>('[aria-label="Filter registries"]')!
act(() => typeInto(input, query))
expect(document.querySelectorAll('.resource-list-row')).toHaveLength(1)
expect(document.body.textContent).not.toContain('No registries match')
})
it('shows pending credentials as loading with an unknown count', async () => {
state.credentials = []
state.loading = true
await renderPanel()
expect(document.querySelector('[role="status"]')?.textContent).toContain('Loading registries')
expect(document.querySelector('.resource-filter')?.textContent).toBe('—')
expect(document.body.textContent).not.toContain('No private registries connected')
})
it.each(['GHCR', 'acme/', 'acme-bot'])(
'filters visible credentials by %s and recovers from no matches',
async (query) => {
await renderPanel()
const input = document.querySelector<HTMLInputElement>('[aria-label="Filter registries"]')
expect(input).not.toBeNull()
act(() => typeInto(input!, query))
expect(document.querySelectorAll('.resource-list-row')).toHaveLength(1)
act(() => typeInto(input!, 'no-such-registry'))
expect(document.querySelectorAll('.resource-list-row')).toHaveLength(0)
expect(document.body.textContent).toContain('No registries match')
expect(document.body.textContent).not.toContain('No private registries connected')
await act(async () => button('Clear filter')?.click())
expect(input!.value).toBe('')
expect(document.querySelectorAll('.resource-list-row')).toHaveLength(1)
expect(mocks.create).not.toHaveBeenCalled()
expect(mocks.update).not.toHaveBeenCalled()
expect(mocks.remove).not.toHaveBeenCalled()
},
)
it('keeps one connection action in an empty credential list', async () => {
state.credentials = []
await renderPanel()
const actions = [...host.querySelectorAll('button')].filter((button) => button.textContent === 'Connect a registry')
expect(actions).toHaveLength(1)
await act(async () => actions[0].click())
expect(document.querySelector('[role="dialog"]')).not.toBeNull()
})
it('lists a credential by what it covers, who it pulls as, and who added it', async () => {
await renderPanel()
expect(host.textContent).toContain('ghcr.io')
expect(host.textContent).toContain('acme/*')
expect(host.textContent).toContain('acme-bot')
expect(host.textContent).toContain('by Chen Ming')
})
it('reports a list that failed rather than showing an empty one', async () => {
const failure = new Error('403')
state.credentials = []
state.listError = failure
await renderPanel()
expect(mocks.handleApiError).not.toHaveBeenCalled()
expect(document.querySelector<HTMLInputElement>('[aria-label="Filter registries"]')?.disabled).toBe(true)
expect(document.querySelector('[role="alert"] h2')?.textContent).toBe('Could not load private registries')
expect(host.textContent).not.toContain('No private registry connected')
})
// A deploy without a secret store answers 501. That is a state of the
// environment, not a failure, and there is nothing to connect.
it('says private registries are off where the deploy does not support them', async () => {
state.credentials = []
state.listError = new BoxliteError('Registry credentials are not configured for this deployment')
await renderPanel()
expect(host.textContent).toContain('not enabled in this environment')
expect(button('Connect a registry')).toBeUndefined()
expect(mocks.handleApiError).not.toHaveBeenCalled()
})
})
describe('updating a credential', () => {
it('preloads the username, fixes its scope, and submits only the replacement login', async () => {
await renderPanel()
act(() => button('Update')?.click())
expect(field('registry-username').value).toBe(CREDENTIAL.username)
expect(field('registry-prefix').disabled).toBe(true)
expect(field('registry-host').hasAttribute('disabled')).toBe(true)
expect(field('registry-password').type).toBe('password')
expect(field('registry-password').value).toBe('')
expect(field('registry-password').required).toBe(true)
await fillAndSubmit({ username: 'new-bot' })
expect(mocks.update).toHaveBeenCalledWith({
id: CREDENTIAL.id,
organizationId: 'org-1',
credential: { username: 'new-bot', password: PASSWORD },
})
expect(mocks.create).not.toHaveBeenCalled()
expect(mocks.remove).not.toHaveBeenCalled()
expect(mocks.toastSuccess).toHaveBeenCalledWith('Credential updated', expect.anything())
expect(mocks.resetUpdate).toHaveBeenCalled()
expect(document.getElementById('registry-password')).toBeNull()
})
it('reports update failure and retains the entered login for retry', async () => {
const refusal = new BoxliteError('Registry credential is in use by another request; retry update')
mocks.update.mockRejectedValue(refusal)
await renderPanel()
act(() => button('Update')?.click())
await fillAndSubmit({})
expect(mocks.handleApiError).toHaveBeenCalledWith(refusal, 'Could not update the credential for ghcr.io')
expect(field('registry-password').value).toBe(PASSWORD)
expect(mocks.resetUpdate).not.toHaveBeenCalled()
})
it('clears the replacement secret on cancel', async () => {
await renderPanel()
act(() => button('Update')?.click())
act(() => typeInto(field('registry-password'), PASSWORD))
act(() => button('Cancel')?.click())
act(() => button('Update')?.click())
expect(field('registry-password').value).toBe('')
expect(mocks.resetUpdate).toHaveBeenCalled()
})
it('keeps update actions disabled after closing an in-flight update', async () => {
let complete!: () => void
mocks.update.mockReturnValueOnce(new Promise<void>((resolve) => (complete = resolve)))
await renderPanel()
act(() => button('Update')?.click())
await fillAndSubmit({})
try {
act(() => button('Cancel')?.click())
expect(mocks.resetUpdate).toHaveBeenCalled()
expect(button('Update')?.disabled).toBe(true)
open()
expect(button('Connect')?.disabled).toBe(true)
} finally {
await act(async () => complete())
}
expect(button('Update')?.disabled).toBe(false)
})
it.each(['create', 'update'] as const)('keeps a newer form open when an earlier %s completes', async (operation) => {
let complete!: () => void
mocks[operation].mockReturnValueOnce(new Promise<void>((resolve) => (complete = resolve)))
await renderPanel()
if (operation === 'create') open()
else act(() => button('Update')?.click())
await fillAndSubmit({})
act(() => button('Cancel')?.click())
open()
act(() => {
typeInto(field('registry-username'), 'next-bot')
typeInto(field('registry-password'), 'next-token')
})
await act(async () => complete())
expect(document.getElementById('registry-username')).not.toBeNull()
expect(field('registry-username').value).toBe('next-bot')
expect(field('registry-password').value).toBe('next-token')
expect(button('Connect')?.disabled).toBe(false)
})
it('hides update without write permission', async () => {
state.canWrite = false
await renderPanel()
expect(button('Update')).toBeUndefined()
})
})
describe('connecting a registry', () => {
it('connects the first registry from the empty-list action', async () => {
state.credentials = []
await renderPanel()
const actions = [...document.querySelectorAll('button')].filter((item) => item.textContent === 'Connect a registry')
act(() => actions.at(-1)?.click())
await fillAndSubmit({ prefix: 'acme/' })
expect(mocks.create).toHaveBeenCalledWith({
organizationId: 'org-1',
credential: { registryHost: 'ghcr.io', repositoryPrefix: 'acme/', username: 'acme-bot', password: PASSWORD },
})
expect(document.getElementById('registry-password')).toBeNull()
})
it('takes the secret in a masked field, and sends it only in the create', async () => {
await renderPanel()
open()
expect(field('registry-password').type).toBe('password')
await fillAndSubmit({})
expect(mocks.create).toHaveBeenCalledWith({
credential: { registryHost: 'ghcr.io', repositoryPrefix: '', username: 'acme-bot', password: PASSWORD },
organizationId: 'org-1',
})
expect(document.getElementById('registry-password')).toBeNull()
expect(mocks.reset).toHaveBeenCalled()
})
it('submits a custom registry typed into the hostname field', async () => {
await renderPanel()
open()
const registry = field('registry-host')
expect(registry).toBeInstanceOf(HTMLInputElement)
act(() => typeInto(registry, ' Registry.Example.com '))
expect(document.querySelector('label[for="registry-password"]')?.textContent).toBe('Password or access token')
await fillAndSubmit({ prefix: 'team/' })
expect(mocks.create).toHaveBeenCalledWith({
credential: {
registryHost: 'registry.example.com',
repositoryPrefix: 'team/',
username: 'acme-bot',
password: PASSWORD,
},
organizationId: 'org-1',
})
})
it('fills the editable hostname from the existing presets', async () => {
await renderPanel()
open()
const presets = document.querySelector('[aria-label="Registry presets"]')
expect(presets).not.toBeNull()
await act(async () => presets?.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })))
const gcr = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find(
(option) => option.textContent?.trim() === 'Google Container Registry (gcr.io)',
)
expect(gcr).toBeDefined()
await act(async () => gcr?.click())
expect(field('registry-host').value).toBe('gcr.io')
expect(document.body.textContent).toContain('oauth2accesstoken')
})
// The API takes whole path segments ending in a slash; one left off is
// completed rather than refused.
it('completes a repository prefix typed without its trailing slash', async () => {
await renderPanel()
open()
act(() => typeInto(field('registry-prefix'), 'acme'))
expect(host.ownerDocument.body.textContent).toContain('ghcr.io/acme/*')
await fillAndSubmit({})
expect(mocks.create).toHaveBeenCalledWith(
expect.objectContaining({ credential: expect.objectContaining({ repositoryPrefix: 'acme/' }) }),
)
})
it('forgets a typed secret when the dialog is closed without saving', async () => {
await renderPanel()
open()
act(() => typeInto(field('registry-password'), PASSWORD))
act(() => button('Cancel')?.click())
open()
expect(field('registry-password').value).toBe('')
})
it('says which credential is in the way of a duplicate, and keeps the form', async () => {
mocks.create.mockRejectedValue(
new BoxliteError('A credential for ghcr.io/acme/ already exists; update it to replace the login'),
)
await renderPanel()
open()
await fillAndSubmit({ prefix: 'acme/' })
expect(mocks.toastError).toHaveBeenCalledWith('ghcr.io/acme/* already has a credential', expect.anything())
expect(field('registry-prefix').value).toBe('acme/')
expect(mocks.reset).not.toHaveBeenCalled()
})
it('reports any other failure with the API’s reason', async () => {
const refusal = new BoxliteError('registry host not allowed')
mocks.create.mockRejectedValue(refusal)
await renderPanel()
open()
await fillAndSubmit({})
expect(mocks.handleApiError).toHaveBeenCalledWith(refusal, 'Could not connect ghcr.io')
})
// A box whose private pull was refused links here with the registry named,
// so the form opens on it with that registry's instructions.
it('opens on the registry a link names, with that registry’s instructions', async () => {
await renderPanel('/dashboard/images/registries?connect=gcr.io')
expect(field('registry-username')).not.toBeNull()
expect(field('registry-host').value).toBe('gcr.io')
expect(document.body.textContent).toContain('oauth2accesstoken')
})
it('opens a connect link for a custom registry with the hostname prefilled', async () => {
await renderPanel('/dashboard/images/registries?connect=registry.example.com')
expect(field('registry-host')?.value).toBe('registry.example.com')
expect(document.body.textContent).toContain('Bearer token endpoint on the same host')
})
it('ignores a connect link containing a URL instead of a hostname', async () => {
await renderPanel('/dashboard/images/registries?connect=https%3A%2F%2Fregistry.example.com')
expect(document.getElementById('registry-username')).toBeNull()
})
})
describe('removing a credential', () => {
it('removes a confirmed credential and closes the confirmation', async () => {
await renderPanel()
act(() =>
(document.querySelector('button[title="Remove the credential for ghcr.io"]') as HTMLButtonElement).click(),
)
await act(async () => button('Remove')?.click())
expect(mocks.remove).toHaveBeenCalledWith({ id: 'credential-1', organizationId: 'org-1' })
expect(document.querySelector('[role="alertdialog"]')).toBeNull()
})
// The API refuses while boxes pull through the credential and lists them by
// id; the reader is told which boxes, by name.
it('names the boxes a refusal lists', async () => {
state.byId = new Map([['a1b2c3', { id: 'a1b2c3', name: 'agile-otter' }]])
mocks.remove.mockRejectedValue(
new BoxliteError('Registry credential credential-1 cannot be removed while 1 box(es) pull through it: a1b2c3'),
)
await renderPanel()
act(() =>
(document.querySelector('button[title="Remove the credential for ghcr.io"]') as HTMLButtonElement).click(),
)
await act(async () => button('Remove')?.click())
expect(mocks.toastError).toHaveBeenCalledWith(
'Still in use',
expect.objectContaining({ description: expect.stringContaining('agile-otter') }),
)
})
})
it('retries an initial registry failure without displaying transport details or an empty inventory', async () => {
state.listError = new Error('Cannot GET /private-internal-route')
await renderPanel()
expect(button('Retry')).toBeDefined()
expect(document.querySelector('[role="alert"]')?.textContent).toContain('Could not load private registries')
expect(document.body.textContent).not.toContain('/private-internal-route')
expect(document.body.textContent).not.toContain('No private registries connected')
await act(async () => button('Retry')?.click())
expect(mocks.refetch).toHaveBeenCalledTimes(1)
})
it('preserves cached registry records and offers recovery after a refresh fails', async () => {
state.cached = true
state.listError = new Error('Connection lost')
await renderPanel()
expect(document.querySelectorAll('.resource-list-row')).toHaveLength(1)
expect(button('Retry')).toBeDefined()
expect(document.querySelector('[role="alert"]')?.textContent).toContain('Showing previously loaded data')
expect(document.body.textContent).toContain('acme-bot')
await act(async () => button('Retry')?.click())
expect(mocks.refetch).toHaveBeenCalledTimes(1)
})