ODS V3 Pre-Release: Public testing and refinement ahead of the official V3 launch. Turn your PC, Mac, or Linux box into a private AI server.
Python ai-agentsamdcomfyuidockerllama-cppllmlocal-ain8nnvidiaopen-webuiragself-hostedspeech-to-textstrix-halotext-to-speechworkflow-automation
// Conversation/review state tests isolate the asynchronous origin handshake.
// Its real transport, timeout and stale-receipt behavior is covered in previewOrigin.test.jsx.
vi.mock('../lib/useVerifiedPreview',()=>({default:(_preview,access)=>access}))
import { fireEvent, screen, waitFor, within } from '@testing-library/react'
import { render } from '../test/test-utils'
import { act } from '@testing-library/react'
import {saveProfile} from '../lib/localProfile'
import {saveConversation,readConversations,DELETE_EVENT} from '../lib/pixelConversations'
import { StrictMode } from 'react'
import {previewManifestResponse} from '../test/previewFixtures'
const previewManifests=new Map()
// The repository's base ESLint profile does not mark JSX identifiers as uses.
// eslint-disable-next-line no-unused-vars
import Pixel, {
NO_REPLY_NOTICE,
OperationsApprovalCard,
formatElapsed,
isCleanContextRecoveryFrame,
parseApprovalReceipt,
parseVerifiedPreviewFrame,
resolvePreviewAccess,
latestProjectPublication,
} from './Pixel'
const response = (body, status = 200) => ({
ok: status >= 200 && status < 300,
status,
json: async () => body,
})
// The calm line a reply ends with once the server proved its turn is over.
const CUT_OFF = (_content, node) => node?.tagName === 'EM' && node.textContent === NO_REPLY_NOTICE
it('resolves old cards to the latest verified version of their own project',()=>{
const publication=(letter,directory)=>{
const sha256=letter.repeat(64),siteId=`site-${sha256.slice(0,24)}`
return {schemaVersion:1,kind:'ods-pixel-workspace-preview',relativeDirectory:directory,siteId,port:9437,url:`http://${siteId}.localhost:9437/${siteId}/`,files:2,bytes:100,sha256,entrySha256:sha256}
}
const old=publication('a','pacman-game'),current=publication('b','pacman-game'),other=publication('c','Playground/weather')
const messages=[old,current,other].map(p=>({role:'assistant',content:'Ready',publication:p}))
messages.push({role:'assistant',content:'Unverified',publication:{...current,url:'https://elsewhere.example/'}})
expect(latestProjectPublication(old,messages)).toEqual(current)
expect(latestProjectPublication(other,messages)).toEqual(other)
expect(messages[0].publication).toEqual(old)
})
// Build a fake fetch Response with streaming SSE body
const sseResponse = (frames, { status = 200, chunks } = {}) => {
const encoder = new TextEncoder()
const frameBytes = frames.map(f => encoder.encode(`data: ${f}\n\n`))
const concatFrames = (group) => {
const totalLen = group.reduce((acc, i) => acc + frameBytes[i].byteLength, 0)
const out = new Uint8Array(totalLen)
let offset = 0
for (const i of group) {
out.set(frameBytes[i], offset)
offset += frameBytes[i].byteLength
}
return out
}
const chunkGroups = chunks
? chunks.map(group => concatFrames(group))
: frameBytes
let idx = 0
const reader = {
read: async () => {
if (idx >= chunkGroups.length) return { done: true, value: undefined }
return { done: false, value: chunkGroups[idx++] }
},
releaseLock: () => {},
}
return {
ok: status >= 200 && status < 300,
status,
body: { getReader: () => reader },
headers: new Map([['content-type', 'text/event-stream']]),
}
}
describe('Pixel', () => {
beforeEach(() => {
previewManifests.clear()
// Stream fixtures are independent of background context reads. The full
// context lifecycle is exercised in PixelCompaction.test.jsx; retain all
// network observations here without consuming the next SSE fixture.
const responses=vi.fn()
const fetchMock=vi.fn((url,...args)=>previewManifests.has(url)?Promise.resolve(previewManifestResponse(previewManifests.get(url))):url==='/api/pixel/chat/context'
? Promise.resolve(response({schemaVersion:1,status:'missing',sessionRevision:null,context:null,model:null,
compaction:{status:'idle',count:0},history:{revision:null,acknowledgedMessages:0}}))
: responses(url,...args))
for(const method of ['mockResolvedValue','mockResolvedValueOnce','mockRejectedValue','mockRejectedValueOnce','mockImplementation','mockImplementationOnce']) {
fetchMock[method]=(...args)=>{responses[method](...args);return fetchMock}
}
globalThis.fetch = fetchMock
globalThis.localStorage.clear()
})
afterEach(() => {
vi.useRealTimers()
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
it('formats short and long owner-agent turn durations', () => {
expect(formatElapsed(0)).toBe('0:00')
expect(formatElapsed(71)).toBe('1:11')
expect(formatElapsed(3671)).toBe('1:01:11')
})
it('bypasses cached availability and runtime identity on status reads', async () => {
globalThis.fetch.mockResolvedValue(response({available:true}))
render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
const calls = globalThis.fetch.mock.calls.filter(([url]) => url === '/api/pixel/status')
expect(calls).toHaveLength(1)
expect(calls[0][1]).toEqual(expect.objectContaining({cache:'no-store', signal:expect.anything()}))
})
it('opens working local chat when Portal was never enabled', async () => {
globalThis.fetch.mockResolvedValue(response({available:false, detail:'Portal is not enabled'}))
render(<Pixel systemStatus={{services:[
{id:'open-webui-preview', name:'Open WebUI Preview', status:'healthy', public_url:'https://preview.example.test'},
{id:'open-webui', name:'Open WebUI (Chat)', status:'healthy', port:8080, external_port:3000},
]}} />)
const chat = await screen.findByRole('link', {name:'Open local chat'})
expect(chat).toHaveAttribute('href', 'http://localhost:3000')
expect(screen.getByText(/Portal's owner agent is not enabled/)).toBeVisible()
expect(screen.queryByText('Your local ODS owner agent')).toBeNull()
expect(screen.queryByRole('textbox', {name:'Portal is unavailable'})).toBeNull()
})
it('does not offer a dead chat link while native Core chat is unhealthy', async () => {
globalThis.fetch.mockResolvedValue(response({available:false, detail:'Portal is not enabled'}))
render(<Pixel systemStatus={{services:[{
id:'open-webui', status:'unhealthy', port:8080, external_port:3000,
}]}} />)
expect(await screen.findByText(/Local chat is not ready yet/)).toBeVisible()
expect(screen.queryByRole('link', {name:'Open local chat'})).toBeNull()
expect(screen.getByRole('link', {name:'View Dashboard'})).toBeVisible()
})
it('does not treat a temporary Portal outage as an uninstalled agent', async () => {
globalThis.fetch.mockResolvedValue(response({available:false, detail:'Portal service is unavailable'}))
render(<Pixel systemStatus={{services:[{
id:'open-webui', status:'healthy', port:8080, external_port:3000,
}]}} />)
await waitFor(() => expect(screen.getByText('Degraded')).toBeInTheDocument())
expect(screen.queryByRole('link', {name:'Open local chat'})).toBeNull()
expect(screen.getByText('Your local ODS owner agent')).toBeVisible()
})
it('keeps prompts clean without copy/reuse controls or inline tool-call summaries',async()=>{
localStorage.setItem('ods.pixel.chat.v1',JSON.stringify({schema:1,chatId:'clean-chat',messages:[
{role:'user',content:'A clean prompt'},
{role:'assistant',content:'A clean response',task:{schemaVersion:1,runId:'chatcmpl_12345678-1234-1234-1234-123456789012',startedAt:'2026-09-10T12:00:00.000Z',finishedAt:'2026-09-10T12:00:01.000Z',state:'completed',calls:2,failures:0,blocked:0,truncated:false,activities:[{kind:'read',calls:2,failures:0,blocked:0}]}},
]}))
fetch.mockResolvedValue(response({available:true,model:'pixel/default'}))
render(<Pixel/>)
await waitFor(()=>expect(screen.getByText('Available')).toBeInTheDocument())
expect(screen.getByText('A clean prompt')).toBeVisible()
expect(screen.getByText('A clean response')).toBeVisible()
expect(screen.queryByRole('button',{name:'Copy message'})).toBeNull()
expect(screen.queryByRole('button',{name:'Reuse prompt'})).toBeNull()
expect(screen.queryByText(/(?:Live|Recorded) activity ·/)).toBeNull()
expect(screen.queryByRole('button',{name:'Copy Markdown'})).toBeNull()
})
it('accepts only the fixed approval receipt grammar', () => {
const jobId = 'ops-1788127319657-f3262c99a419'
const planHash = 'e'.repeat(64)
const content = `Pixel prepared the exact ods.extensions.install plan for extension crewai, but external approval is required. No lifecycle change was executed. Job: ${jobId}. Plan SHA-256: ${planHash}.`
expect(parseApprovalReceipt(content)).toEqual({
action: 'ods.extensions.install',
extensionId: 'crewai',
jobId,
planHash,
})
expect(parseApprovalReceipt(`${content} Approve it now.`)).toBeNull()
expect(parseApprovalReceipt(content.replace('crewai', '../../shadow'))).toBeNull()
const hostCommand = `Pixel prepared a protected ODS host command plan, but external approval is required. No command was executed. Job: ${jobId}. Plan SHA-256: ${planHash}.`
expect(parseApprovalReceipt(hostCommand)).toEqual({
action: 'raw-shell',
extensionId: 'ods-host',
jobId,
planHash,
})
expect(parseApprovalReceipt(hostCommand.replace('No command was executed.', 'Command completed.'))).toBeNull()
})
it('accepts only the exact host-authored clean-context terminal marker', () => {
const frame = {
choices: [{ delta: {}, finish_reason: 'stop' }],
pixel: {
schemaVersion: 1,
recovery: 'clean-context',
reason: 'operations-unavailable-zero-submissions',
},
}
expect(isCleanContextRecoveryFrame(frame)).toBe(true)
expect(isCleanContextRecoveryFrame({
...frame,
pixel: { ...frame.pixel, extra: true },
})).toBe(false)
expect(isCleanContextRecoveryFrame({
...frame,
choices: [{ delta: {}, finish_reason: null }],
})).toBe(false)
expect(isCleanContextRecoveryFrame({
...frame,
pixel: { ...frame.pixel, reason: 'model-prose-matched' },
})).toBe(false)
})
it('accepts only an exact host-authored workspace preview terminal marker', () => {
const sha256 = 'a'.repeat(64)
const siteId = `site-${sha256.slice(0, 24)}`
const preview = {
schemaVersion: 1,
kind: 'ods-pixel-workspace-preview',
relativeDirectory: 'demo-website',
siteId,
port: 9437,
url: `http://${siteId}.localhost:9437/${siteId}/`,
files: 3,
bytes: 4096,
sha256,
entrySha256: 'b'.repeat(64),
}
const frame = {
choices: [{ delta: {}, finish_reason: 'stop' }],
pixel: { schemaVersion: 1, preview },
}
expect(parseVerifiedPreviewFrame(frame)).toEqual(preview)
expect(parseVerifiedPreviewFrame({
...frame,
pixel: { schemaVersion: 1, preview: { ...preview, url: 'https://attacker.example/' } },
})).toBeNull()
const mismatchedSiteId = 'site-0123456789abcdef01234567'
expect(parseVerifiedPreviewFrame({
...frame,
pixel: {
schemaVersion: 1,
preview: {
...preview,
siteId: mismatchedSiteId,
url: `http://${mismatchedSiteId}.localhost:9437/${mismatchedSiteId}/`,
},
},
})).toBeNull()
expect(parseVerifiedPreviewFrame({
...frame,
pixel: { schemaVersion: 1, preview, extra: true },
})).toBeNull()
})
it('restores the verified preview after reload and preserves an explicit close', async () => {
// Persistence and navigation do not depend on reveal animation timing.
// PortalStreamingText.test.jsx exercises the animated response lifecycle.
const matchMedia = globalThis.matchMedia
vi.stubGlobal('matchMedia', query => query === '(prefers-reduced-motion: reduce)'
? { matches: true, addEventListener: vi.fn(), removeEventListener: vi.fn() }
: matchMedia?.(query) ?? { matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() })
const sha256 = 'a'.repeat(64)
const siteId = `site-${sha256.slice(0, 24)}`
const preview = {
schemaVersion: 1,
kind: 'ods-pixel-workspace-preview',
relativeDirectory: 'demo-website',
siteId,
port: 9437,
url: `http://${siteId}.localhost:9437/${siteId}/`,
files: 3,
bytes: 4096,
sha256,
entrySha256: 'b'.repeat(64),
}
previewManifests.set(`/pixel-preview/${siteId}/__ods_manifest__.json`,preview)
globalThis.fetch.mockResolvedValueOnce(
response({ available: true, model: 'pixel/default', detail: 'local' })
)
globalThis.fetch.mockResolvedValueOnce(sseResponse([
JSON.stringify({ choices: [{ delta: { content: `[Open the verified preview](${preview.url})\n\n[Documentation](https://example.com/docs)\n\n[Other host](http://${siteId}.localhost.example.com:9437/${siteId}/)` } }] }),
JSON.stringify({
choices: [{ delta: {}, finish_reason: 'stop' }],
pixel: { schemaVersion: 1, preview },
}),
'[DONE]',
]))
const original = render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), {
target: { value: 'Build and show me a demo website.' },
})
fireEvent.click(screen.getByTitle('Send'))
const frame = await screen.findByTitle('Interactive Portal preview')
expect(frame).toHaveAttribute('src', `/pixel-preview/${siteId}/__ods_view__.html`)
expect(frame).toHaveAttribute('sandbox', 'allow-scripts allow-forms allow-downloads')
expect(screen.queryByLabelText('Snapshot details')).not.toBeInTheDocument()
expect(screen.queryByText('Info', {exact:true})).not.toBeInTheDocument()
expect(screen.getByRole('button', {name:'Browse files',exact:true})).toBeInTheDocument()
fireEvent.click(screen.getByRole('button',{name:'Workspace options'}))
expect(screen.getByRole('link',{name:'Open preview in a new tab'})).toHaveAttribute('href', `/pixel-preview/${siteId}/`)
expect(await screen.findByRole('link', { name: 'Open the verified preview' })).toHaveAttribute('href', `/pixel-preview/${siteId}/`)
expect(await screen.findByRole('link', { name: 'Documentation' })).toHaveAttribute('href', 'https://example.com/docs')
expect(await screen.findByRole('link', { name: 'Other host' },{timeout:2000})).toHaveAttribute('href', `http://${siteId}.localhost.example.com:9437/${siteId}/`)
await waitFor(() => expect(
JSON.parse(globalThis.localStorage.getItem('ods.pixel.chat.v1')).preview
).toEqual(preview))
original.unmount()
globalThis.fetch.mockResolvedValue(response({ available: true }))
const restored = render(<Pixel />)
expect(await screen.findByTitle('Interactive Portal preview')).toHaveAttribute('src', `/pixel-preview/${siteId}/__ods_view__.html`)
expect(globalThis.fetch.mock.calls.filter(([url]) => url === '/api/pixel/chat/stream')).toHaveLength(1)
fireEvent.click(screen.getByTitle('Close preview'))
expect(screen.queryByTitle('Interactive Portal preview')).not.toBeInTheDocument()
await waitFor(() => expect(
JSON.parse(globalThis.localStorage.getItem('ods.pixel.chat.v1')).workspaceOpen
).toBe(false))
expect(JSON.parse(globalThis.localStorage.getItem('ods.pixel.chat.v1')).preview).toEqual(preview)
restored.unmount()
render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
expect(screen.queryByTitle('Interactive Portal preview')).not.toBeInTheDocument()
expect(screen.getByRole('link', { name: 'Open the verified preview' })).toHaveAttribute('href', `/pixel-preview/${siteId}/`)
fireEvent.click(screen.getByRole('button',{name:'Workspace',exact:true}))
expect(await screen.findByTitle('Interactive Portal preview')).toHaveAttribute('src', `/pixel-preview/${siteId}/__ods_view__.html`)
})
it('opens the workspace without a preview and only drafts a publication request', async () => {
globalThis.fetch.mockResolvedValue(response({available:true}))
render(<Pixel />)
await screen.findByText('Available')
fireEvent.click(screen.getByRole('button',{name:'Workspace',exact:true}))
fireEvent.click(screen.getByRole('tab',{name:'Preview',exact:true}))
expect(screen.getByText('No files to show yet')).toBeVisible()
expect(screen.queryByTitle('Interactive Portal preview')).toBeNull()
fireEvent.click(screen.getByRole('button',{name:'Expand workspace'}))
expect(document.querySelector('.pixel-chat-preview-layout')).toHaveClass('is-workspace-expanded')
fireEvent.click(screen.getByRole('button',{name:'Ask Portal to publish'}))
expect(document.querySelector('.pixel-chat-preview-layout')).not.toHaveClass('is-workspace-expanded')
expect(screen.getByPlaceholderText('Message Portal...').value).toBe('Publish the site you created in this conversation to the ODS preview. Inspect the existing files, preserve the project, and use pixel_ods_workspace_preview for the folder that contains index.html.')
expect(globalThis.fetch.mock.calls.some(([url]) => url === '/api/pixel/chat/stream')).toBe(false)
fireEvent.click(screen.getByTitle('Close preview'))
expect(screen.queryByText('No files to show yet')).toBeNull()
fireEvent.click(screen.getByRole('button',{name:'Workspace',exact:true}))
fireEvent.click(screen.getByRole('tab',{name:'Preview',exact:true}))
expect(screen.getByText('No files to show yet')).toBeVisible()
})
it('deletes the selected idle chat and starts an empty one without resurrecting it', async () => {
saveConversation({schema:1,chatId:'delete-current',messages:[{role:'user',content:'Disposable current chat'}]})
globalThis.fetch.mockImplementation(url=>Promise.resolve(response(url==='/api/pixel/images/delete-current'?{schemaVersion:1,deleted:true}:{available:true,model:'pixel/default'})))
render(<Pixel/>)
await waitFor(()=>expect(screen.getByText('Available')).toBeInTheDocument())
expect(screen.getByText('Disposable current chat')).toBeVisible()
const complete=vi.fn()
act(()=>window.dispatchEvent(new CustomEvent(DELETE_EVENT,{detail:{chatId:'delete-current',complete}})))
await waitFor(()=>expect(complete).toHaveBeenCalledWith(''))
await waitFor(()=>expect(screen.queryByText('Disposable current chat')).not.toBeInTheDocument())
expect(readConversations().some(chat=>chat.chatId==='delete-current')).toBe(false)
expect(JSON.parse(localStorage.getItem('ods.pixel.chat.v1')).chatId).not.toBe('delete-current')
})
it('shows the local profile photo beside user messages without including it in model requests',async()=>{
const photo='data:image/webp;base64,YWJj'
saveProfile({name:'Gabriel',photo})
globalThis.fetch.mockResolvedValueOnce(response({available:true}))
globalThis.fetch.mockResolvedValueOnce(sseResponse([JSON.stringify({choices:[{delta:{content:'Hello'}}]}),'[DONE]']))
render(<Pixel/>)
await screen.findByText('Available')
fireEvent.change(screen.getByPlaceholderText('Message Portal...'),{target:{value:'Hi'}})
fireEvent.click(screen.getByTitle('Send'))
expect(await screen.findByRole('img',{name:'Gabriel profile photo'})).toHaveAttribute('src',photo)
expect(screen.getByRole('img',{name:'Gabriel profile photo'}).parentElement).toHaveClass('pixel-user-character')
const post=globalThis.fetch.mock.calls.find(([,options])=>options?.method==='POST')
expect(post[1].body).not.toContain(photo)
await act(async()=>saveProfile({name:'Gabriel',photo:''}))
expect(screen.queryByRole('img',{name:'Gabriel profile photo'})).toBeNull()
expect(screen.getByRole('img',{name:'Gabriel avatar'})).toBeVisible()
})
it('keeps the chat toolbar inside its column beside the full-height workspace', async () => {
globalThis.fetch.mockResolvedValue(response({available:true,model:'pixel/default'}))
render(<Pixel />)
await screen.findByText('Available')
fireEvent.click(screen.getByRole('button',{name:'Workspace',exact:true}))
const panel = screen.getByRole('complementary',{name:'Preview panel'})
const column = screen.getByPlaceholderText('Message Portal...').closest('.pixel-chat-column')
expect(column.parentElement).toBe(panel.parentElement)
expect(column).toContainElement(screen.getByRole('button',{name:'Workspace',exact:true}))
expect(column).toContainElement(screen.getByRole('button',{name:'Model unverified'}))
expect(column).toContainElement(screen.getByRole('button',{name:'Search Portal'}))
expect(panel).not.toContainElement(screen.getByRole('heading',{name:'Portal',exact:true}))
fireEvent.click(screen.getByTitle('Collapse preview'))
expect(panel).toHaveClass('is-collapsed')
fireEvent.click(screen.getByTitle('Expand preview'))
expect(panel).not.toHaveClass('is-collapsed')
})
it('saves terminal activity with the reply and never sends telemetry to the model', async () => {
const task={schemaVersion:1,runId:'chatcmpl_11111111-2222-4333-8444-555555555555',startedAt:'2026-09-08T20:00:00.000Z',finishedAt:'2026-09-08T20:00:02.000Z',state:'completed',calls:1,failures:0,blocked:0,truncated:false,activities:[{kind:'read',calls:1,failures:0,blocked:0}]}
globalThis.fetch.mockResolvedValueOnce(response({available:true}))
globalThis.fetch.mockResolvedValueOnce(sseResponse([
JSON.stringify({choices:[{delta:{content:'Read the file.'}}]}),
JSON.stringify({id:task.runId,pixel_task:task,choices:[{delta:{},finish_reason:'stop'}]}),'[DONE]']))
const first=render(<Pixel />)
await screen.findByText('Available')
fireEvent.change(screen.getByPlaceholderText('Message Portal...'),{target:{value:'Read the file'}})
fireEvent.click(screen.getByTitle('Send'))
await waitFor(()=>expect(JSON.parse(localStorage.getItem('ods.pixel.chat.v1')).messages.at(-1).task).toEqual(task))
first.unmount()
globalThis.fetch.mockResolvedValueOnce(response({available:true}))
render(<Pixel />)
await screen.findByText('Available')
const activity=screen.getByRole('region',{name:'Agent activity'})
fireEvent.click(within(activity).getByRole('button',{name:'Worked for 2s'}))
expect(within(activity).getByText('Reading files')).toBeVisible()
globalThis.fetch.mockResolvedValueOnce(sseResponse([JSON.stringify({choices:[{delta:{content:'OK'}}]}),'[DONE]']))
fireEvent.change(screen.getByPlaceholderText('Message Portal...'),{target:{value:'Continue'}})
fireEvent.click(screen.getByTitle('Send'))
await screen.findByText('OK')
const calls=globalThis.fetch.mock.calls.filter(([url])=>url==='/api/pixel/chat/stream')
expect(JSON.parse(calls.at(-1)[1].body).messages.every(message=>Object.keys(message).sort().join(',')==='content,role')).toBe(true)
})
it('restores pending questions and choices then continues the same conversation without UI metadata', async () => {
const questions=[{id:'style',question:'Qual estilo?',options:['Clean','Colorido']}]
fetch.mockResolvedValueOnce(response({available:true}))
fetch.mockResolvedValueOnce(sseResponse([
JSON.stringify({choices:[{delta:{content:'Qual estilo?'}}]}),
JSON.stringify({pixel_questions:{schemaVersion:1,questions},choices:[{delta:{},finish_reason:'stop'}]}),'[DONE]']))
const first=render(<Pixel/>)
await screen.findByText('Available')
fireEvent.change(screen.getByPlaceholderText('Message Portal...'),{target:{value:'Pergunte antes de criar'}})
fireEvent.click(screen.getByTitle('Send'))
const clean=await screen.findByRole('radio',{name:/Clean/})
fireEvent.click(clean)
await waitFor(()=>expect(JSON.parse(localStorage.getItem('ods.pixel.chat.v1')).messages.at(-1).questionDraft.style).toBe('Clean'))
const chatId=JSON.parse(localStorage.getItem('ods.pixel.chat.v1')).chatId
first.unmount()
fetch.mockResolvedValueOnce(response({available:true}))
render(<Pixel/>)
await screen.findByText('Available')
expect(screen.getByRole('radio',{name:/Clean/})).toBeChecked()
fetch.mockResolvedValueOnce(sseResponse([JSON.stringify({choices:[{delta:{content:'Escolha recebida.'}}]}),'[DONE]']))
fireEvent.click(screen.getByRole('button',{name:'Continue',exact:true}))
await screen.findByText('Escolha recebida.')
const calls=fetch.mock.calls.filter(([url])=>url==='/api/pixel/chat/stream')
expect(calls).toHaveLength(2)
const request=JSON.parse(calls.at(-1)[1].body)
expect(request.chat_id).toBe(chatId)
expect(request.messages.at(-1)).toEqual({role:'user',content:'Qual estilo?\nClean'})
expect(request.messages.every(message=>Object.keys(message).sort().join(',')==='content,role')).toBe(true)
expect(screen.queryByRole('button',{name:'Continue',exact:true})).toBeNull()
expect(screen.getByRole('region',{name:'Your answers'})).toHaveTextContent('Clean')
expect(screen.queryByText('Qual estilo?\nClean')).toBeNull()
})
it('renders agent tables and task lists while keeping unsafe content inert', async () => {
const content = [
'**Files in log-lab:**',
'| File | Size | Description |',
'|------|-----:|-------------|',
'| `log_analyzer.py` | 7263 B | Unicode 世界 |',
'| [unsafe](javascript:alert%281%29) | 0 | <img src=x onerror="alert(1)"> |',
'',
'- [x] Export completed',
'- [ ] Review output',
'',
'```python',
'print("hello")',
'```',
].join('\n')
globalThis.localStorage.setItem('ods.pixel.chat.v1', JSON.stringify({
schema: 1,
chatId: 'table-regression',
messages: [{ role: 'assistant', content }],
}))
globalThis.fetch.mockResolvedValue(response({ available: true, model: 'pixel/default' }))
const { container } = render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
const table = screen.getByRole('table')
expect(within(table).getByRole('columnheader', { name: 'File' })).toBeInTheDocument()
expect(within(table).getByRole('cell', { name: '7263 B' })).toBeInTheDocument()
expect(within(table).getByText('log_analyzer.py').tagName).toBe('CODE')
expect(within(table).getByText('Unicode 世界')).toBeInTheDocument()
expect(within(table).queryByRole('link', { name: 'unsafe' })).not.toBeInTheDocument()
expect(container.querySelector('img[src="x"]')).toBeNull()
const checkboxes = screen.getAllByRole('checkbox')
expect(checkboxes).toHaveLength(2)
expect(checkboxes[0]).toBeChecked()
expect(checkboxes[1]).not.toBeChecked()
checkboxes.forEach(checkbox => expect(checkbox).toBeDisabled())
expect(container.querySelector('pre code')).toHaveTextContent('print("hello")')
})
it.each([
{ url: 'https://attacker.example/' },
{ sha256: 42 },
{ relativeDirectory: '../outside' },
{ siteId: 'site-0123456789abcdef01234567' },
])('keeps the conversation but rejects damaged cached preview metadata: %j', async (changed) => {
const sha256 = 'a'.repeat(64)
const siteId = `site-${sha256.slice(0, 24)}`
globalThis.localStorage.setItem('ods.pixel.chat.v1', JSON.stringify({
schema: 1,
chatId: 'saved_preview',
messages: [{ role: 'user', content: 'Keep my work visible' }],
preview: {
schemaVersion: 1, kind: 'ods-pixel-workspace-preview',
relativeDirectory: 'demo', siteId, port: 9437,
url: `http://${siteId}.localhost:9437/${siteId}/`,
files: 1, bytes: 2048, sha256, entrySha256: 'b'.repeat(64),
...changed,
},
}))
globalThis.fetch.mockResolvedValue(response({ available: true }))
render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
expect(screen.getByText('Keep my work visible')).toBeInTheDocument()
expect(screen.queryByTitle('Interactive Portal preview')).not.toBeInTheDocument()
})
it('clears the stored preview when starting a new conversation', async () => {
const sha256 = 'a'.repeat(64)
const siteId = `site-${sha256.slice(0, 24)}`
globalThis.localStorage.setItem('ods.pixel.chat.v1', JSON.stringify({
schema: 1, chatId: 'saved_preview', messages: [{ role: 'user', content: 'Old project' }],
preview: {
schemaVersion: 1, kind: 'ods-pixel-workspace-preview',
relativeDirectory: 'demo', siteId, port: 9437,
url: `http://${siteId}.localhost:9437/${siteId}/`,
files: 1, bytes: 2048, sha256, entrySha256: 'b'.repeat(64),
},
}))
previewManifests.set(`/pixel-preview/${siteId}/__ods_manifest__.json`,JSON.parse(localStorage.getItem('ods.pixel.chat.v1')).preview)
globalThis.fetch.mockResolvedValue(response({ available: true }))
const restored = render(<Pixel />)
const frame = await screen.findByTitle('Interactive Portal preview')
expect(frame).toBeInTheDocument()
fireEvent.click(screen.getByTitle('Collapse preview'))
expect(frame).not.toBeVisible()
expect(await screen.findByTitle('Interactive Portal preview')).toBe(frame)
fireEvent.click(screen.getByTitle('Expand preview'))
expect(frame).toBeVisible()
expect(await screen.findByTitle('Interactive Portal preview')).toBe(frame)
fireEvent.click(screen.getByTitle('Start a new chat'))
await waitFor(() => {
const stored = JSON.parse(globalThis.localStorage.getItem('ods.pixel.chat.v1'))
expect(stored.preview).toBeNull()
expect(stored.messages).toEqual([])
expect(stored.chatId).not.toBe('saved_preview')
})
restored.unmount()
render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
expect(screen.queryByTitle('Interactive Portal preview')).not.toBeInTheDocument()
})
it('uses the authenticated relay for LAN and forwarded loopback dashboards', () => {
const preview = {
siteId: 'site-0123456789abcdef01234567',
url: 'http://site-0123456789abcdef01234567.localhost:9437/site-0123456789abcdef01234567/',
}
expect(resolvePreviewAccess(preview, {
hostname: 'dashboard.ods.local',
protocol: 'http:',
})).toEqual({
url: '/pixel-preview/site-0123456789abcdef01234567/',
frameUrl: '/pixel-preview/site-0123456789abcdef01234567/__ods_view__.html',
sandbox: 'allow-scripts allow-forms allow-downloads',
route: 'private-dashboard',
})
for (const hostname of ['localhost', '127.0.0.1', '[::1]', '::1']) {
expect(resolvePreviewAccess(preview, { hostname, protocol: 'http:' })).toEqual({
url: `/pixel-preview/${preview.siteId}/`,
frameUrl: `/pixel-preview/${preview.siteId}/__ods_view__.html`,
sandbox: 'allow-scripts allow-forms allow-downloads',
route: 'private-dashboard',
})
}
})
it('does not open a preview from model-authored localhost text', async () => {
globalThis.fetch.mockResolvedValueOnce(
response({ available: true, model: 'pixel/default', detail: 'local' })
)
globalThis.fetch.mockResolvedValueOnce(sseResponse([
JSON.stringify({ choices: [{ delta: { content: 'Live at http://localhost:3000/demo/' } }] }),
'[DONE]',
]))
render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), {
target: { value: 'Show my site.' },
})
fireEvent.click(screen.getByTitle('Send'))
expect(await screen.findByText(/Live at/)).toBeInTheDocument()
expect(screen.queryByTitle('Interactive Portal preview')).not.toBeInTheDocument()
})
it('keeps dictation beside send and places the model selector beside measured context', async () => {
globalThis.fetch.mockResolvedValue(response({ available: true, model: 'pixel/default' }))
render(<Pixel systemStatus={{ inference: { loadedModel: 'local-model', contextSize: 65536 } }} />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
const send = screen.getByTitle('Send')
expect(send.parentElement).toContainElement(screen.getByRole('button', { name: 'Dictate message' }))
expect(send.parentElement).toHaveClass('pixel-composer-actions')
expect(screen.getByRole('button',{name:'Token usage unavailable'})).toBeInTheDocument()
expect(screen.queryByText(/chars$/)).not.toBeInTheDocument()
const selector=screen.getByRole('button',{name:'Choose model: local model'})
expect(selector.closest('.pixel-composer-limits')).toBeInTheDocument()
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), { target: { value: 'Olá' } })
expect(selector).toBeInTheDocument()
expect(screen.getByRole('button',{name:'Token usage unavailable'})).toBeInTheDocument()
const field = screen.getByPlaceholderText('Message Portal...')
expect(field).toHaveClass('pixel-composer-input')
expect(field.className).not.toContain('focus:ring')
fireEvent.keyDown(field,{key:'Enter',shiftKey:true})
fireEvent.change(field,{target:{value:'Olá\nsegunda linha\nterceira linha'}})
expect(field).toHaveValue('Olá\nsegunda linha\nterceira linha')
expect(send.parentElement.parentElement).toHaveClass('pixel-composer-row')
expect(send.parentElement).toContainElement(screen.getByRole('button',{name:'Dictate message'}))
expect(globalThis.fetch.mock.calls.filter(([url])=>url!=='/api/pixel/chat/context').every(([,options]) => options?.method !== 'POST')).toBe(true)
expect(selector.closest('.pixel-composer-limits').lastElementChild).toContainElement(screen.getByRole('button',{name:'Token usage unavailable'}))
})
it('highlights fenced code while keeping unknown languages and HTML inert', async () => {
const content = '```js\nconst value = "Pixel";\n```\n\n```unknown-language\n<video onerror="alert(1)">\n```'
globalThis.fetch.mockResolvedValueOnce(response({ available: true }))
globalThis.fetch.mockResolvedValueOnce(sseResponse([
JSON.stringify({ choices: [{ delta: { content } }] }), '[DONE]',
]))
const { container } = render(<Pixel />)
await screen.findByText('Available')
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), { target: { value: 'Show code' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(container.querySelector('.hljs-keyword')).toHaveTextContent('const'))
await waitFor(() => expect(container.querySelector('.hljs-string')).toHaveTextContent('"Pixel"'))
await waitFor(() => expect(container.querySelector('.language-unknown-language')).toHaveTextContent('<video onerror="alert(1)">'))
expect(container.querySelector('video')).toBeNull()
})
it('renders a host-verified approval card without approving in the browser', async () => {
const jobId = 'ops-1788127319657-f3262c99a419'
const planHash = 'e'.repeat(64)
const command = `/opt/ods/bin/ods-pixel-approve ${jobId} ${planHash} --confirm`
const content = `Pixel prepared the exact ods.extensions.install plan for extension crewai, but external approval is required. No lifecycle change was executed. Job: ${jobId}. Plan SHA-256: ${planHash}.`
const clipboard = { writeText: vi.fn().mockResolvedValue(undefined) }
Object.defineProperty(globalThis.navigator, 'clipboard', {
configurable: true,
value: clipboard,
})
globalThis.fetch.mockImplementation(async (url) => {
if (url === '/api/pixel/status') {
return response({ available: true, model: 'pixel/default', detail: 'local' })
}
if (url === '/api/pixel/chat/stream') {
return sseResponse([
JSON.stringify({ choices: [{ delta: { content } }] }),
'[DONE]',
])
}
if (url === `/api/pixel/ops/${jobId}?plan_hash=${planHash}`) {
return response({
schemaVersion: 1,
kind: 'ods-pixel-operations-status',
jobId,
planHash,
status: 'awaiting-approval',
riskTier: 'managed',
approvalRequired: true,
updatedAt: '2026-08-30T22:01:59Z',
approvalCommand: command,
})
}
throw new Error(`unexpected fetch ${url}`)
})
render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), {
target: { value: 'Install the ODS extension crewai.' },
})
fireEvent.click(screen.getByTitle('Send'))
expect(await screen.findByText('Owner approval required')).toBeInTheDocument()
expect(screen.getByText('managed')).toBeInTheDocument()
const copy = screen.getByRole('button', { name: 'Copy secure approval command' })
fireEvent.click(copy)
await waitFor(() => expect(clipboard.writeText).toHaveBeenCalledWith(command))
expect(globalThis.fetch.mock.calls.some(([url]) => url.includes('/api/pixel/ops/'))).toBe(true)
expect(globalThis.fetch.mock.calls.some(([, options]) => options?.method === 'POST' && options?.body?.includes('approve'))).toBe(false)
})
it('renders the same independently verified approval UX for a protected host command', async () => {
const jobId = 'ops-1788127319657-f3262c99a419'
const planHash = 'f'.repeat(64)
const command = `/opt/ods/bin/ods-pixel-approve ${jobId} ${planHash} --confirm`
const content = `Pixel prepared a protected ODS host command plan, but external approval is required. No command was executed. Job: ${jobId}. Plan SHA-256: ${planHash}.`
globalThis.fetch.mockResolvedValue(response({
schemaVersion: 1,
kind: 'ods-pixel-operations-status',
jobId,
planHash,
status: 'awaiting-approval',
riskTier: 'break-glass',
approvalRequired: true,
updatedAt: '2026-09-03T02:00:00Z',
approvalCommand: command,
}))
render(<OperationsApprovalCard content={content} />)
expect(await screen.findByText('Owner approval required')).toBeInTheDocument()
expect(screen.getByText('raw-shell · ods-host')).toBeInTheDocument()
expect(screen.getByText('break-glass')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Copy secure approval command' })).toBeInTheDocument()
expect(globalThis.fetch).toHaveBeenCalledWith(
`/api/pixel/ops/${jobId}?plan_hash=${planHash}`,
expect.any(Object),
)
})
it('recovers an approval card after a transient status projection failure', async () => {
vi.useFakeTimers()
const jobId = 'ops-1788127319657-f3262c99a419'
const planHash = 'e'.repeat(64)
const content = `Pixel prepared the exact ods.extensions.install plan for extension crewai, but external approval is required. No lifecycle change was executed. Job: ${jobId}. Plan SHA-256: ${planHash}.`
globalThis.fetch
.mockRejectedValueOnce(new Error('temporary restart'))
.mockResolvedValueOnce(response({
schemaVersion: 1,
kind: 'ods-pixel-operations-status',
jobId,
planHash,
status: 'succeeded',
riskTier: 'managed',
approvalRequired: true,
updatedAt: '2026-08-30T22:01:59Z',
approvalCommand: null,
}))
render(<OperationsApprovalCard content={content} />)
await act(async () => {})
expect(screen.getByRole('alert')).toHaveTextContent(
'This approval receipt could not be independently verified. Do not approve it.'
)
await act(async () => {
await vi.advanceTimersByTimeAsync(3000)
})
expect(screen.getByText('Protected operation completed')).toBeInTheDocument()
expect(globalThis.fetch).toHaveBeenCalledTimes(2)
})
it('shows unavailable state when status fails', async () => {
globalThis.fetch.mockResolvedValue(response({ available: false, detail: 'Edge unreachable' }))
render(<Pixel />)
await waitFor(() => {
expect(screen.getByText('Degraded')).toBeInTheDocument()
})
expect(screen.getAllByText(/Edge unreachable/).length).toBeGreaterThan(0)
})
it.each(['request', 'body'])('recovers after a stalled status %s without accepting its late response', async phase => {
vi.useFakeTimers()
let finishStalled, stalledSignal
let calls = 0
globalThis.fetch.mockImplementation((url, options) => {
if (url !== '/api/pixel/status') return Promise.resolve(response({}))
calls += 1
if (calls === 1) return Promise.resolve(response({available:false}))
if (calls === 2) {
stalledSignal = options.signal
const pending = new Promise(resolve => { finishStalled = resolve })
return phase === 'request' ? pending : Promise.resolve({ok:true,json:()=>pending})
}
return Promise.resolve(response({available:true,runtime:{source:'remote-provider',model:'cloud-model',contextLength:32768,maxTokens:4096,reasoning:false}}))
})
render(<Pixel />)
await act(async () => { await vi.advanceTimersByTimeAsync(3000) })
expect(screen.getByText('Degraded')).toBeInTheDocument()
expect(calls).toBe(2)
await act(async () => { await vi.advanceTimersByTimeAsync(15000) })
expect(stalledSignal.aborted).toBe(true)
expect(screen.getByText('Degraded')).toBeInTheDocument()
await act(async () => { await vi.advanceTimersByTimeAsync(3000) })
expect(screen.getByText('Available')).toBeInTheDocument()
expect(screen.getByRole('button',{name:'Choose model: cloud model'})).toBeInTheDocument()
await act(async () => { finishStalled(phase === 'request' ? response({available:false}) : {available:false}) })
expect(screen.getByText('Available')).toBeInTheDocument()
})
it('recovers confirmed cloud after a stalled status body and first selector opening during the outage without local model requests', async () => {
vi.useFakeTimers()
let finishStalled, stalledSignal
let statusCalls = 0
const cloud = {available:true,runtime:{source:'remote-provider',model:'cloud-model',contextLength:32768,maxTokens:4096,reasoning:false}}
globalThis.fetch.mockImplementation((url, options) => {
if (url !== '/api/pixel/status') return Promise.resolve(response({},503))
statusCalls += 1
if (statusCalls === 2) {
stalledSignal = options.signal
return Promise.resolve({ok:true,json:()=>new Promise(resolve => { finishStalled = resolve })})
}
return Promise.resolve(response(cloud))
})
const localRequests = () => fetch.mock.calls.filter(([url])=>url.startsWith('/api/models'))
render(<Pixel />)
await act(async()=>{})
expect(screen.getByText('Available')).toBeInTheDocument()
expect(screen.getByRole('button',{name:'Choose model: cloud model'})).toHaveTextContent('cloud model')
fireEvent.change(screen.getByRole('textbox'),{target:{value:'Keep this cloud draft'}})
expect(localRequests()).toHaveLength(0)
await act(async()=>{await vi.advanceTimersByTimeAsync(3000)})
expect(statusCalls).toBe(2)
await act(async()=>{await vi.advanceTimersByTimeAsync(15000)})
expect(stalledSignal.aborted).toBe(true)
expect(screen.getByText('Degraded')).toBeInTheDocument()
expect(screen.getByRole('textbox')).toBeDisabled()
fireEvent.click(screen.getByRole('button',{name:'Last confirmed model: cloud model; Portal unavailable'}))
await act(async()=>{})
expect(screen.getByText('The conversation’s model source is not confirmed.')).toBeVisible()
expect(screen.queryByRole('button',{name:'Switch model',exact:true})).toBeNull()
expect(localRequests()).toHaveLength(0)
await act(async()=>{await vi.advanceTimersByTimeAsync(3000)})
expect(screen.getByText('Available')).toBeInTheDocument()
expect(screen.getByRole('button',{name:'Choose model: cloud model'})).toHaveTextContent('cloud model')
expect(screen.getByRole('link',{name:'Provider settings'})).toBeVisible()
expect(screen.getByRole('textbox')).toBeEnabled()
expect(screen.getByRole('textbox')).toHaveValue('Keep this cloud draft')
await act(async()=>{finishStalled({available:false})})
await act(async()=>{await vi.advanceTimersByTimeAsync(60000)})
fireEvent.click(screen.getByRole('button',{name:'Choose model: cloud model'}))
fireEvent.click(screen.getByRole('button',{name:'Choose model: cloud model'}))
await act(async()=>{})
expect(screen.getByText('Available')).toBeInTheDocument()
expect(screen.getByRole('textbox')).toBeEnabled()
expect(localRequests()).toHaveLength(0)
})
it('restores the cloud composer despite an unavailable local activation catalog', async () => {
vi.useFakeTimers()
let available = true, catalogFailed = false, remote = false
globalThis.fetch.mockImplementation(async url => {
if (url === '/api/pixel/status') return response({available,runtime:available ? remote ? {source:'remote-provider',model:'cloud-model',contextLength:32768,maxTokens:4096,reasoning:false} : {source:'local-switchboard',model:'local-model',contextLength:32768} : undefined})
if (url === '/api/models') return catalogFailed ? response({},503) : response({models:[],modelLifecycle:{active:true,operation:'model_activation',modelId:'local-model'}})
if (url === '/api/models/recovery') return response({pending:false,phase:'idle'})
return response({})
})
render(<Pixel />)
await act(async()=>{})
fireEvent.click(screen.getByRole('button',{name:'Choose model: local model'}))
await act(async()=>{})
available = false
catalogFailed = true
await act(async()=>{await vi.advanceTimersByTimeAsync(3000)})
expect(screen.getByRole('textbox')).toBeDisabled()
available = true
remote = true
await act(async()=>{await vi.advanceTimersByTimeAsync(3000)})
expect(screen.getByRole('alert')).toHaveTextContent('Failed to fetch models')
expect(screen.getByText('Available')).toBeInTheDocument()
expect(screen.getByRole('button',{name:'Choose model: cloud model'})).toBeInTheDocument()
expect(screen.getByRole('textbox')).toBeEnabled()
})
it('recovers cloud after opening the selector during an initial backend outage and stops local reads', async () => {
vi.useFakeTimers()
let recovered = false
globalThis.fetch.mockImplementation(async url => {
if (url === '/api/pixel/status') return recovered
? response({available:true,runtime:{source:'remote-provider',model:'cloud-model',contextLength:32768,maxTokens:4096,reasoning:false}})
: response({},503)
if (url.startsWith('/api/models')) return response({},503)
return response({})
})
render(<Pixel />)
await act(async()=>{})
expect(screen.getByText('Degraded')).toBeInTheDocument()
expect(screen.getByRole('textbox')).toBeDisabled()
fireEvent.click(screen.getByRole('button',{name:'Model unavailable'}))
await act(async()=>{})
const localReads = () => fetch.mock.calls.filter(([url])=>url.startsWith('/api/models')).length
expect(localReads()).toBeGreaterThan(0)
expect(screen.getByText('The conversation’s model source is not confirmed.')).toBeVisible()
expect(screen.queryByRole('button',{name:'Switch model',exact:true})).toBeNull()
recovered = true
await act(async()=>{await vi.advanceTimersByTimeAsync(3000)})
expect(screen.getByText('Available')).toBeInTheDocument()
expect(screen.getByRole('textbox')).toBeEnabled()
expect(screen.getByRole('button',{name:'Choose model: cloud model'})).toBeInTheDocument()
expect(screen.getByRole('link',{name:'Provider settings'})).toBeVisible()
// A genuine catalog error can remain visible without blocking cloud chat.
expect(screen.getByRole('alert')).toHaveTextContent('Failed to fetch models')
const readsAtRecovery = localReads()
await act(async()=>{await vi.advanceTimersByTimeAsync(60000)})
fireEvent.click(screen.getByRole('button',{name:'Choose model: cloud model'}))
fireEvent.click(screen.getByRole('button',{name:'Choose model: cloud model'}))
await act(async()=>{})
expect(localReads()).toBe(readsAtRecovery)
expect(screen.getByRole('textbox')).toBeEnabled()
expect(fetch.mock.calls.filter(([url,options])=>url.startsWith('/api/models') && options?.method === 'POST')).toHaveLength(0)
})
it('shows available state when status succeeds', async () => {
globalThis.fetch.mockResolvedValue(response({ available: true, model: 'pixel/default', detail: 'local' }))
render(<Pixel />)
await waitFor(() => {
expect(screen.getByText('Available')).toBeInTheDocument()
})
})
it('shows a model-switching state and keeps the composer disabled', async () => {
globalThis.fetch.mockResolvedValue(response({
available: false,
model: null,
state: 'model_switching',
detail: 'Model switch in progress; Pixel will be ready when activation completes',
}))
render(<Pixel />)
await waitFor(() => expect(screen.getByText('Switching model...')).toBeInTheDocument())
expect(screen.getByLabelText('Model activation')).toHaveTextContent('Model change has not finished')
expect(screen.getByPlaceholderText('Waiting for model switch...')).toBeDisabled()
})
it('keeps an unqualified model available with a visible capability advisory, not an admission gate', async () => {
globalThis.fetch.mockResolvedValue(response({
available: true,
model: 'pixel/default',
detail: 'Owner agent ready',
modelSupport: {
tier: 'adaptive',
detail: 'Pixel is ready and adapts its tool flow for this model.',
},
}))
render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
expect(screen.getByText('Available')).toHaveAttribute(
'title',
'The active model is recorded as not agent-qualified. Tool-driven tasks may be unreliable; chat and experiments remain available.'
)
expect(screen.getByRole('status', { name: 'Model capability' })).toBeVisible()
expect(screen.getByRole('status', { name: 'Model capability' })).toHaveTextContent('not agent-qualified')
expect(screen.getByRole('status', { name: 'Model capability' })).toHaveTextContent('Tool-driven tasks may be unreliable')
expect(screen.queryByText(/ready and adapts/)).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Model unverified' })).toBeInTheDocument()
expect(screen.queryByRole('link', { name: 'Change model' })).not.toBeInTheDocument()
expect(screen.getByPlaceholderText('Message Portal...')).toBeEnabled()
})
it.each([null, undefined, {}, { tier: 'qualified', detail: 'Qualified' },
{ tier: 'unknown', detail: 'Unknown' }, { tier: 'adaptive', detail: null }])(
'does not infer a qualification warning from absent, qualified or unknown support: %j', async modelSupport => {
globalThis.fetch.mockResolvedValue(response({ available: true, model: 'pixel/default', modelSupport }))
render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
expect(screen.queryByRole('status', { name: 'Model capability' })).not.toBeInTheDocument()
expect(screen.getByText('Available')).not.toHaveAttribute('title')
expect(screen.getByPlaceholderText('Message Portal...')).toBeEnabled()
}
)
const MODEL_ADVISORY_TEXT = {
'context-too-small': 'This model runs with less than 16K tokens of context, too small for Portal tasks. Set its context to 16K or more in Models, or switch model.',
'tools-unavailable': 'This model failed the tool-call check, so Portal tasks that use tools will likely fail. Chat still works.',
'not-profiled': 'ODS has not checked this model yet, so Portal tasks may not work. To check it, choose Check again on the running model in Models.',
'thinking-always-on': 'This model always thinks before it answers, so Portal tasks are slower and use more of its context.',
}
it.each(Object.entries(MODEL_ADVISORY_TEXT))(
'shows the fixed %s advisory with a switch link and help, above the conversation before the first task', async (reason, text) => {
globalThis.fetch.mockResolvedValue(response({
available: true, model: 'pixel/default',
modelSupport: { tier: 'adaptive', detail: 'Server wording that is never shown.', reason },
}))
render(<Pixel />)
const banner = await screen.findByRole('status', { name: 'Model capability' })
expect(banner).toHaveTextContent(text)
expect(screen.queryByText(/Server wording/)).not.toBeInTheDocument()
expect(screen.getByText('Available')).toHaveAttribute('title', text)
expect(within(banner).getByRole('link', { name: 'Switch model' })).toHaveAttribute('href', '/models')
expect(within(banner).getByRole('link', { name: 'Get help on Discord' })).toHaveAttribute('href', 'https://discord.gg/4ntNp9MAwC')
expect(screen.getByText('What do you want to work on?')).toBeVisible()
const conversation = screen.getByRole('region', { name: 'Conversation messages' })
expect(banner.compareDocumentPosition(conversation) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
expect(screen.getByPlaceholderText('Message Portal...')).toBeEnabled()
}
)
it('never disables sending while a model advisory is shown', async () => {
globalThis.fetch.mockImplementation(async url => url === '/api/pixel/chat/stream'
? sseResponse([JSON.stringify({ choices: [{ delta: { content: 'Chat still answers' } }] }), '[DONE]'])
: response({
available: true, model: 'pixel/default',
modelSupport: { tier: 'adaptive', detail: 'Tools failed.', reason: 'tools-unavailable' },
}))
render(<Pixel />)
await screen.findByRole('status', { name: 'Model capability' })
const composer = screen.getByPlaceholderText('Message Portal...')
expect(composer).toBeEnabled()
fireEvent.change(composer, { target: { value: 'run a task anyway' } })
expect(screen.getByTitle('Send')).toBeEnabled()
fireEvent.click(screen.getByTitle('Send'))
expect(await screen.findByText('Chat still answers')).toBeInTheDocument()
const sends = globalThis.fetch.mock.calls.filter(([url]) => url === '/api/pixel/chat/stream')
expect(sends).toHaveLength(1)
expect(JSON.parse(sends[0][1].body).messages.at(-1).content).toBe('run a task anyway')
expect(screen.getByRole('status', { name: 'Model capability' })).toHaveTextContent(MODEL_ADVISORY_TEXT['tools-unavailable'])
})
it('keeps a specific advisory when an older model gate refuses a send', async () => {
globalThis.fetch.mockImplementation(async url => url === '/api/pixel/chat/stream'
? response({ detail: 'Pixel is ready and adapts its tool flow for this model.' }, 412)
: response({
available: true, model: 'pixel/default',
modelSupport: { tier: 'adaptive', detail: 'Not checked.', reason: 'not-profiled' },
}))
render(<Pixel />)
await screen.findByRole('status', { name: 'Model capability' })
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), { target: { value: 'keep this request' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(globalThis.fetch.mock.calls.some(([url]) => url === '/api/pixel/chat/stream')).toBe(true))
await waitFor(() => expect(screen.getByPlaceholderText('Message Portal...')).toHaveValue('keep this request'))
expect(screen.getByPlaceholderText('Message Portal...')).toBeEnabled()
expect(screen.getByRole('status', { name: 'Model capability' })).toHaveTextContent(MODEL_ADVISORY_TEXT['not-profiled'])
expect(screen.getByRole('status', { name: 'Model capability' })).not.toHaveTextContent('not agent-qualified')
})
it('renders a legacy advisory exactly as before, without the switch link or help', async () => {
globalThis.fetch.mockResolvedValue(response({
available: true, model: 'pixel/default',
modelSupport: { tier: 'adaptive', detail: 'Pixel is ready and adapts its tool flow for this model.' },
}))
render(<Pixel />)
const banner = await screen.findByRole('status', { name: 'Model capability' })
expect(banner.textContent).toBe('The active model is recorded as not agent-qualified. Tool-driven tasks may be unreliable; chat and experiments remain available.')
expect(within(banner).queryByRole('link')).not.toBeInTheDocument()
expect(screen.queryByRole('link', { name: 'Switch model' })).not.toBeInTheDocument()
})
it.each([
{ tier: 'adaptive', detail: 'Shown?', reason: 'unknown-reason' },
{ tier: 'adaptive', detail: 'Shown?', reason: 'toString' },
{ tier: 'adaptive', detail: 'Shown?', reason: null },
{ tier: 'adaptive', detail: 'Shown?', reason: ['tools-unavailable'] },
{ tier: 'adaptive', detail: 'Shown?', reason: 'tools-unavailable', extra: true },
{ tier: 'qualified', detail: 'Shown?', reason: 'tools-unavailable' },
{ tier: 'adaptive', detail: '', reason: 'tools-unavailable' },
{ tier: 'adaptive', detail: 'x'.repeat(513), reason: 'tools-unavailable' },
{ tier: 'adaptive', reason: 'tools-unavailable' },
])('rejects a malformed or unknown advisory reason like any other bad answer: %j', async modelSupport => {
globalThis.fetch.mockResolvedValue(response({ available: true, model: 'pixel/default', modelSupport }))
render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
expect(screen.queryByRole('status', { name: 'Model capability' })).not.toBeInTheDocument()
expect(screen.getByText('Available')).not.toHaveAttribute('title')
expect(screen.queryByRole('link', { name: 'Switch model' })).not.toBeInTheDocument()
expect(screen.getByPlaceholderText('Message Portal...')).toBeEnabled()
})
it('preserves a draft when model viability changes before stream acceptance', async () => {
globalThis.fetch
.mockResolvedValueOnce(response({ available: true, model: 'pixel/default', detail: 'local' }))
.mockResolvedValueOnce(response({
detail: 'Pixel is ready and adapts its tool flow for this model.',
}, 412))
render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
const composer = screen.getByPlaceholderText('Message Portal...')
fireEvent.change(composer, { target: { value: 'keep this owner request' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
expect(screen.getByPlaceholderText('Message Portal...')).toBeEnabled()
expect(screen.getByPlaceholderText('Message Portal...')).toHaveValue(
'keep this owner request'
)
await waitFor(() => expect(screen.getByRole('status', { name: 'Model capability' })).toHaveTextContent('not agent-qualified'))
expect(screen.getByRole('status', { name: 'Model capability' })).not.toHaveTextContent('ready and adapts')
})
it('maps the legacy incompatible status to a usable adaptive status', async () => {
globalThis.localStorage.setItem('ods.pixel.chat.v1', JSON.stringify({
schema: 1,
chatId: 'stored_chat',
messages: [
{ role: 'user', content: 'old request' },
{ role: 'assistant', content: 'old response' },
],
}))
globalThis.fetch.mockResolvedValue(response({
available: false,
model: null,
state: 'model_incompatible',
detail: 'This model failed Pixel tool qualification.',
}))
render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
expect(screen.getByText('Available')).toHaveAttribute(
'title',
'The active model is recorded as not agent-qualified. Tool-driven tasks may be unreliable; chat and experiments remain available.'
)
expect(screen.getByRole('status', { name: 'Model capability' })).toBeVisible()
expect(screen.getByRole('button', { name: 'Model unverified' })).toBeInTheDocument()
expect(screen.queryByRole('link', { name: 'Change model' })).not.toBeInTheDocument()
expect(screen.getByPlaceholderText('Message Portal...')).toBeEnabled()
})
it('restores an unsent draft when model activation wins the chat race', async () => {
globalThis.fetch.mockResolvedValueOnce(
response({ available: true, model: 'pixel/default', detail: 'local' })
)
globalThis.fetch.mockResolvedValueOnce(response({
detail: 'Model switch in progress; Pixel will be ready when activation completes',
}, 409))
render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
const textarea = screen.getByPlaceholderText('Message Portal...')
fireEvent.change(textarea, { target: { value: 'keep this exact draft' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(screen.getByText('Switching model...')).toBeInTheDocument())
expect(textarea).toHaveValue('keep this exact draft')
expect(screen.queryByText('Request failed')).not.toBeInTheDocument()
expect(JSON.parse(globalThis.localStorage.getItem('ods.pixel.chat.v1')).messages).toEqual([])
})
it('keeps send disabled until the draft has non-whitespace content', async () => {
globalThis.fetch.mockResolvedValue(
response({ available: true, model: 'pixel/default', detail: 'local' })
)
render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
const textarea = screen.getByPlaceholderText('Message Portal...')
const send = screen.getByTitle('Send')
expect(send).toBeDisabled()
fireEvent.change(textarea, { target: { value: ' ' } })
expect(send).toBeDisabled()
fireEvent.change(textarea, { target: { value: 'ready' } })
expect(send).toBeEnabled()
})
// RTX Spark Elf of Doom: a failed preview check keeps the agent's own
// explanation, and (2026-10-25) Portal's line after it is one calm, muted
// sentence above a preview that works, never error-looking text.
it('renders a kept agent explanation as Markdown, then Portal\'s muted line, with the preview card', async () => {
const matchMedia = globalThis.matchMedia
vi.stubGlobal('matchMedia', query => query === '(prefers-reduced-motion: reduce)'
? { matches: true, addEventListener: vi.fn(), removeEventListener: vi.fn() }
: matchMedia?.(query) ?? { matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() })
const sha256 = 'c'.repeat(64)
const siteId = `site-${sha256.slice(0, 24)}`
const preview = {schemaVersion: 1, kind: 'ods-pixel-workspace-preview', relativeDirectory: 'elf-of-doom', siteId, port: 9437,
url: `http://${siteId}.localhost:9437/${siteId}/`, files: 3, bytes: 4096, sha256, entrySha256: 'd'.repeat(64)}
previewManifests.set(`/pixel-preview/${siteId}/__ods_manifest__.json`, preview)
const note = "Portal couldn't test every control automatically. Try it, and tell Portal if something isn't right."
const content = 'The cause is `ui.js:748`: a canvas is not a valid `fillStyle`, so the previous colour stays set.\n\n' +
'- The last full-viewport fill covers the arena.\n\n' +
`${note}\n\n` +
`Your preview is ready.\n\n[Open preview](${preview.url})\n\nPublished from your workspace.`
globalThis.fetch.mockResolvedValueOnce(response({ available: true, model: 'pixel/default', detail: 'local' }))
globalThis.fetch.mockResolvedValueOnce(sseResponse([
JSON.stringify({ choices: [{ delta: { content } }] }),
JSON.stringify({ choices: [{ delta: {}, finish_reason: 'stop' }], pixel: { schemaVersion: 1, preview },
pixel_outcome: { schemaVersion: 1, status: 'failed' } }),
'[DONE]',
]))
const {container} = render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), { target: { value: 'Fix the arena, then look at the preview.' } })
fireEvent.click(screen.getByTitle('Send'))
const line = await screen.findByText(note)
expect(line.closest('p')).toHaveClass('portal-delivery-note')
expect(screen.getByText('ui.js:748').closest('code')).not.toBeNull()
expect(screen.getByText('The last full-viewport fill covers the arena.').closest('li')).not.toBeNull()
expect(screen.getByText(/^The cause is/).closest('p')).not.toHaveClass('portal-delivery-note')
const reply = line.closest('[data-pixel-response]')
expect(reply.textContent).not.toMatch(/failed|did not pass|not verified|unverified|error|Portal check/i)
expect(within(reply).queryByRole('alert')).toBeNull()
expect(reply.querySelector('[class*="red-"]')).toBeNull()
expect(screen.queryByText('Your preview is ready.')).toBeNull()
expect(screen.queryByText(/Published from your workspace/)).toBeNull()
expect(screen.queryByRole('link', { name: 'Open preview' })).toBeNull()
expect(within(reply).getByRole('button', { name: /Web preview/ })).toBeVisible()
expect(await screen.findByTitle('Interactive Portal preview')).toHaveAttribute('src', `/pixel-preview/${siteId}/__ods_view__.html`)
expect(container.querySelector('.portal-embed-note')).toBeNull()
// The stored reply and the model's history keep the full delivered text.
await waitFor(() => expect(JSON.parse(globalThis.localStorage.getItem('ods.pixel.chat.v1')).messages.at(-1))
.toMatchObject({ role: 'assistant', content, publication: preview }))
})
// RTX Spark, 2026-10-25: "Draw me a picture of a dragon" published an SVG
// site that the preview card showed, and the reply ended with the model's
// own embed of that site. Portal said it could not display it.
it.each([
['after the reply', "Here's your dragon, curled around a mountain peak.\n\n"],
['as the whole reply', ''],
])('leaves out the embed of the preview its card shows, %s, and copies the original text', async (_name, prose) => {
const matchMedia = globalThis.matchMedia
vi.stubGlobal('matchMedia', query => query === '(prefers-reduced-motion: reduce)'
? { matches: true, addEventListener: vi.fn(), removeEventListener: vi.fn() }
: matchMedia?.(query) ?? { matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() })
const sha256 = 'fca81965eeec4e16e761822a' + 'b'.repeat(40)
const siteId = `site-${sha256.slice(0, 24)}`
const preview = {schemaVersion: 1, kind: 'ods-pixel-workspace-preview', relativeDirectory: 'Playground/dragon', siteId, port: 9437,
url: `http://${siteId}.localhost:9437/${siteId}/`, files: 1, bytes: 2048, sha256, entrySha256: 'e'.repeat(64)}
previewManifests.set(`/pixel-preview/${siteId}/__ods_manifest__.json`, preview)
const content = `${prose}[embed ref="${siteId}" title="Dragon" height="560" /]\n\n` +
`Your preview is ready.\n\n[Open preview](${preview.url})\n\nCreated by Portal.\n` +
'Publication scope: this receipt verifies the published snapshot, not functional behavior or completion of other requested work.'
const writeText = vi.fn().mockResolvedValue(undefined)
const clipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard')
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } })
try {
globalThis.fetch.mockResolvedValueOnce(response({ available: true, model: 'pixel/default', detail: 'local' }))
globalThis.fetch.mockResolvedValueOnce(sseResponse([
JSON.stringify({ choices: [{ delta: { content } }] }),
JSON.stringify({ choices: [{ delta: {}, finish_reason: 'stop' }], pixel: { schemaVersion: 1, preview },
pixel_outcome: { schemaVersion: 1, status: 'passed' } }),
'[DONE]',
]))
const {container} = render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), { target: { value: 'Draw me a picture of a dragon' } })
fireEvent.click(screen.getByTitle('Send'))
expect(await screen.findByTitle('Interactive Portal preview')).toHaveAttribute('src', `/pixel-preview/${siteId}/__ods_view__.html`)
const reply = [...container.querySelectorAll('[data-pixel-response]')].at(-1)
expect(await within(reply).findByRole('button', { name: /Web preview/ })).toBeVisible()
if (prose) expect(await within(reply).findByText("Here's your dragon, curled around a mountain peak.")).toBeVisible()
await waitFor(() => expect(within(reply).getByRole('button', { name: 'Copy response' })).toBeVisible())
expect(reply.textContent).not.toMatch(/\[embed|embedded view|can’t display|Your preview is ready/)
expect(container.querySelector('.portal-embed-note')).toBeNull()
fireEvent.click(within(reply).getByRole('button', { name: 'Copy response' }))
await waitFor(() => expect(writeText).toHaveBeenCalledOnce())
expect(writeText.mock.calls[0][0]).toContain(`[embed ref="${siteId}" title="Dragon" height="560" /]`)
await waitFor(() => expect(JSON.parse(globalThis.localStorage.getItem('ods.pixel.chat.v1')).messages.at(-1))
.toMatchObject({ role: 'assistant', content, publication: preview }))
} finally {
if (clipboard) Object.defineProperty(navigator, 'clipboard', clipboard)
else delete navigator.clipboard
}
})
it('shows nothing, not a note, for a later reply of only an embed of a preview the chat already shows', async () => {
// Reveal replies at once, so a note would already show.
const matchMedia = globalThis.matchMedia
vi.stubGlobal('matchMedia', query => query === '(prefers-reduced-motion: reduce)'
? { matches: true, addEventListener: vi.fn(), removeEventListener: vi.fn() }
: matchMedia?.(query) ?? { matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() })
const sha256 = 'fca81965eeec4e16e761822a' + 'b'.repeat(40)
const siteId = `site-${sha256.slice(0, 24)}`
const preview = {schemaVersion: 1, kind: 'ods-pixel-workspace-preview', relativeDirectory: 'Playground/dragon', siteId, port: 9437,
url: `http://${siteId}.localhost:9437/${siteId}/`, files: 1, bytes: 2048, sha256, entrySha256: 'e'.repeat(64)}
const embed = `[embed ref="${siteId}" title="Dragon" height="560" /]`
globalThis.localStorage.setItem('ods.pixel.chat.v1', JSON.stringify({schema: 1, chatId: 'dragon-chat', messages: [
{role: 'user', content: 'Draw me a picture of a dragon'},
{role: 'assistant', content: `Here's your dragon.\n\nYour preview is ready.\n\n[Open preview](${preview.url})\n\nCreated by Portal.`,
publication: preview},
]}))
globalThis.fetch.mockImplementation(async url => url === '/api/pixel/chat/stream'
? sseResponse([JSON.stringify({choices: [{delta: {content: embed}}]}),
JSON.stringify({choices: [{delta: {}, finish_reason: 'stop'}], pixel_outcome: {schemaVersion: 1, status: 'none'}}), '[DONE]'])
: response({available: true, model: 'pixel/default'}))
const {container} = render(<Pixel />)
await screen.findByText('Available')
expect(screen.getByText("Here's your dragon.")).toBeVisible()
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), {target: {value: 'Show it to me again'}})
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(JSON.parse(globalThis.localStorage.getItem('ods.pixel.chat.v1')).messages.at(-1))
.toMatchObject({role: 'assistant', content: embed}))
await waitFor(() => expect(within([...container.querySelectorAll('[data-pixel-response]')].at(-1))
.getByRole('button', {name: 'Copy response'})).toBeVisible())
expect(container.textContent).not.toMatch(/embedded view|can’t display|\[embed/)
})
// Seen live: "what is 12 squared?" was answered exactly "144.", which
// Markdown reads as an ordered list that starts at 144 with one empty item.
// Without its start number the reply showed an empty "1." and lost the answer.
it.each([
['what is 12 squared?', '144.', '144', ['']],
['what is left?', 'Steps 1 and 2 are done.\n\n3. Run the tests\n4. Open the pull request', '3', ['Run the tests', 'Open the pull request']],
])('keeps the ordered-list start number in the reply to %j', async (question, content, start, items) => {
globalThis.fetch.mockResolvedValueOnce(response({available:true}))
globalThis.fetch.mockResolvedValueOnce(sseResponse([JSON.stringify({choices:[{delta:{content}}]}),'[DONE]']))
const {container}=render(<Pixel />)
await screen.findByText('Available')
fireEvent.change(screen.getByPlaceholderText('Message Portal...'),{target:{value:question}})
fireEvent.click(screen.getByTitle('Send'))
// Read the list once the whole reply is revealed. The reveal animation can
// outlast the default one-second DOM wait on Windows CI.
await waitFor(()=>expect(container.querySelector('.portal-streaming-text')).toHaveAttribute('aria-busy','false'),{timeout:5000})
const list=container.querySelector('.portal-streaming-text ol')
expect(list).toHaveAttribute('start',start)
expect(within(list).getAllByRole('listitem').map(item=>item.textContent)).toEqual(items)
})
it('preserves earlier file changes across another message and reload without sending UI metadata to the model', async () => {
const publication = letter => {
const sha256 = letter.repeat(64)
const siteId = `site-${sha256.slice(0, 24)}`
return {schemaVersion: 1, kind: 'ods-pixel-workspace-preview', relativeDirectory: 'demo', siteId, port: 9437, url: `http://${siteId}.localhost:9437/${siteId}/`, files: 1, bytes: 100, sha256, entrySha256: sha256}
}
const before = publication('a')
const after = publication('b')
const originalContent = `Game updated\n\nYour preview is ready.\n\n[Open preview](${after.url})\n\nPublished from your workspace.\nPublication scope: this receipt verifies the published snapshot, not functional behavior or completion of other requested work.`
const changes = {schemaVersion: 1, scope: 'published-snapshots', siteId: after.siteId, sha256: after.sha256, beforeSiteId: before.siteId, beforeSha256: before.sha256, changes: [{path: 'index.html', change: 'modified', additions: 22, deletions: 9, truncated: true, diff: []}]}
globalThis.localStorage.setItem('ods.pixel.chat.v1', JSON.stringify({schema: 1, chatId: 'diff-history', messages: [
{role: 'user', content: 'edit the game'},
{role: 'assistant', content: originalContent, publication: after, beforePublication: before},
]}))
globalThis.fetch.mockImplementation(async (url) => {
if (url.includes('__ods_changes__')) return {ok: true, headers: new Map(), arrayBuffer: async () => new TextEncoder().encode(JSON.stringify(changes)).buffer}
if (url === '/api/pixel/chat/stream') return sseResponse([JSON.stringify({choices: [{delta: {content: 'Second answer'}}]}), '[DONE]'])
return response({available: true, model: 'pixel/default'})
})
const view = render(<Pixel />)
expect(await screen.findByRole('button',{name:/index\.html/})).toBeVisible()
expect(screen.getByText('Game updated')).toBeVisible()
expect(screen.queryByRole('link',{name:/Open preview/})).toBeNull()
expect(screen.queryByText(/Published from your workspace/)).toBeNull()
expect(screen.queryByText(/Publication scope:/)).toBeNull()
expect(screen.getByRole('button',{name:'Copy response'})).toBeVisible()
await screen.findByText('Available')
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), {target: {value: 'another message'}})
fireEvent.click(screen.getByTitle('Send'))
expect(screen.getByRole('button',{name:/index\.html/})).toBeVisible()
expect(await screen.findByText('Second answer')).toBeVisible()
expect(screen.getByRole('button',{name:/index\.html/})).toBeVisible()
expect(screen.getAllByLabelText('22 lines added, 9 lines removed')).toHaveLength(2)
const call = globalThis.fetch.mock.calls.find(([url]) => url === '/api/pixel/chat/stream')
expect(JSON.parse(call[1].body).messages).toEqual([
{role: 'user', content: 'edit the game'}, {role: 'assistant', content: originalContent}, {role: 'user', content: 'another message'},
])
const stored = JSON.parse(localStorage.getItem('ods.pixel.chat.v1'))
expect(stored.messages[1]).toMatchObject({content:originalContent, publication: after, beforePublication: before})
view.unmount()
render(<Pixel />)
expect(await screen.findByRole('button',{name:/index\.html/})).toBeVisible()
expect(screen.getByText('Second answer')).toBeVisible()
})
it('keeps visible history beyond the model request limit after send and reload', async () => {
const messages = Array.from({length: 60}, (_, index) => ({role: index % 2 ? 'assistant' : 'user', content: `History item ${index}`}))
localStorage.setItem('ods.pixel.chat.v1', JSON.stringify({schema: 1, chatId: 'long-history', messages}))
globalThis.fetch.mockImplementation(async url => url === '/api/pixel/chat/stream'
? sseResponse([JSON.stringify({choices: [{delta: {content: 'Latest answer'}}]}), '[DONE]'])
: response({available: true, model: 'pixel/default'}))
const view = render(<Pixel />)
await screen.findByText('Available')
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), {target: {value: 'continue'}})
fireEvent.click(screen.getByTitle('Send'))
// Rendering sixty Markdown messages plus animated text can exceed the
// default one-second DOM wait on Windows CI. Keep the same visible/persisted contract.
await screen.findByText('Latest answer', {}, {timeout: 5000})
expect(screen.getByText('History item 0')).toBeVisible()
const call = globalThis.fetch.mock.calls.find(([url]) => url === '/api/pixel/chat/stream')
expect(JSON.parse(call[1].body).messages.length).toBeLessThanOrEqual(50)
await waitFor(() => expect(JSON.parse(localStorage.getItem('ods.pixel.chat.v1')).messages).toHaveLength(62))
view.unmount()
render(<Pixel />)
expect(screen.getByText('History item 0')).toBeVisible()
expect(screen.getByText('Latest answer')).toBeVisible()
})
it('restores the bounded local chat and reuses its opaque session after reload', async () => {
globalThis.localStorage.setItem('ods.pixel.chat.v1', JSON.stringify({
schema: 1,
chatId: 'persisted-chat-42',
messages: [
{ role: 'user', content: 'remember this' },
{ role: 'assistant', content: 'remembered' },
],
}))
globalThis.fetch.mockResolvedValueOnce(
response({ available: true, model: 'pixel/default', detail: 'local' })
)
globalThis.fetch.mockResolvedValueOnce(sseResponse([
JSON.stringify({ choices: [{ delta: { content: 'still remembered' } }] }),
'[DONE]',
]))
render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
expect(screen.getByText('remembered')).toBeInTheDocument()
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), {
target: { value: 'what did I say?' },
})
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(screen.getByText('still remembered')).toBeInTheDocument())
const chatCall = globalThis.fetch.mock.calls.find(call => call[0] === '/api/pixel/chat/stream')
const body = JSON.parse(chatCall[1].body)
expect(body.chat_id).toBe('persisted-chat-42')
expect(body.messages).toEqual([
{ role: 'user', content: 'remember this' },
{ role: 'assistant', content: 'remembered' },
{ role: 'user', content: 'what did I say?' },
])
})
it('keeps new chats clear of sample tasks while preserving runtime identity', async () => {
globalThis.fetch.mockResolvedValue(
response({ available: true, model: 'pixel/default', detail: 'Owner agent ready' })
)
render(<Pixel systemStatus={{
inference: {
loadedModel: 'Qwen3.5-9B-Q4_K_M.gguf',
contextSize: 32768,
},
}} />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
expect(screen.getByText('What do you want to work on?')).toBeInTheDocument()
expect(screen.getByRole('button',{name:'Choose model: Qwen 3.5 9B'})).toBeInTheDocument()
expect(screen.getByRole('button',{name:'Token usage unavailable'})).toBeInTheDocument()
for (const name of ['Check ODS health','Build in my workspace','Research with sources','Plan a multi-step task']) expect(screen.queryByRole('button',{name:new RegExp(name)})).toBeNull()
expect(screen.getByPlaceholderText('Message Portal...')).toHaveValue('')
expect(globalThis.fetch.mock.calls.filter(([url])=>url==='/api/pixel/status')).toHaveLength(1)
})
it('shows the active remote Pixel runtime instead of the local rollback model', async () => {
globalThis.fetch.mockResolvedValue(
response({
available: true,
model: 'pixel/default',
detail: 'Owner agent ready',
runtime: {
source: 'remote-provider',
model: 'remote-owner-model',
contextLength: 131072,
maxTokens: 16384,
reasoning: false,
},
})
)
render(<Pixel systemStatus={{
inference: {
loadedModel: 'Qwen3.5-9B-Q4_K_M.gguf',
contextSize: 32768,
},
}} />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
expect(screen.getByRole('button',{name:'Choose model: remote owner model'})).toBeInTheDocument()
expect(screen.getByRole('button',{name:/Token usage unavailable.*131,072 token capacity/})).toBeInTheDocument()
expect(screen.queryByText('Qwen3.5-9B-Q4_K_M.gguf')).not.toBeInTheDocument()
})
it.each(['unknown', 'supported', 'unsupported'])('keeps the selected model label with %s image capability', async imageInput => {
globalThis.fetch.mockResolvedValue(response({
available: true, model: 'pixel/default',
runtime: {source: 'remote-provider', model: 'deepseek-v4.1-flash',
contextLength: 131072, maxTokens: 8192, reasoning: false,
routeFingerprint: 'a'.repeat(64), imageInput},
}))
render(<Pixel />)
await waitFor(() => expect(screen.getByRole('button', {name: /Choose model: deepseek/i})).toBeInTheDocument())
expect(screen.queryByText('Model unverified')).not.toBeInTheDocument()
})
it.each([
{imageInput: true}, {imageInput: 'vision'}, {imageInput: 'unknown\n'},
{imageInput: 'unknown', endpoint: 'https://foreign.example'},
{imageInput: 'unknown', routeFingerprint: 'a'.repeat(64) + '\n'},
])('does not confirm malformed extended model metadata %j', async invalid => {
globalThis.fetch.mockResolvedValue(response({
available: true, model: 'pixel/default',
runtime: {source: 'remote-provider', model: 'untrusted-runtime-name',
contextLength: 131072, maxTokens: 8192, reasoning: false,
routeFingerprint: 'a'.repeat(64), ...invalid},
}))
render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
expect(screen.queryByRole('button', {name: /Choose model: untrusted/i})).not.toBeInTheDocument()
})
it('shows a callable 8K remote model without imposing a larger context floor', async () => {
globalThis.fetch.mockResolvedValue(
response({
available: true,
model: 'pixel/default',
detail: 'Owner agent ready',
runtime: {
source: 'remote-provider',
model: 'small-owner-model',
contextLength: 8192,
maxTokens: 1024,
reasoning: false,
},
modelSupport: {
tier: 'adaptive',
detail: 'Pixel is ready and adapts its tool flow for this model.',
},
})
)
render(<Pixel systemStatus={{
inference: {
loadedModel: 'Qwen3.5-9B-Q4_K_M.gguf',
contextSize: 32768,
},
}} />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
expect(screen.getByRole('button',{name:'Choose model: small owner model'})).toBeInTheDocument()
expect(screen.getByRole('button',{name:/Token usage unavailable.*8,192 token capacity/})).toBeInTheDocument()
expect(screen.queryByText('Qwen3.5-9B-Q4_K_M.gguf')).not.toBeInTheDocument()
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
expect(screen.getByPlaceholderText('Message Portal...')).toBeEnabled()
})
it('shows the verified local runtime instead of stale installer model metadata', async () => {
globalThis.fetch.mockResolvedValue(response({
available: true,
runtime: { source: 'local-switchboard', model: 'Qwen3.6-35B-A3B-GGUF', contextLength: 65536 },
modelSupport: { tier: 'adaptive', detail: 'Pixel adapts its tools to this model.' },
}))
render(<Pixel systemStatus={{ inference: { loadedModel: 'qwen3.5-9b', contextSize: 32768 } }} />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
expect(screen.getByRole('button',{name:'Choose model: Qwen 3.6 35B'})).toBeInTheDocument()
expect(screen.getByRole('button',{name:/Token usage unavailable.*65,536 token capacity/})).toBeInTheDocument()
expect(screen.queryByText('qwen3.5-9b')).not.toBeInTheDocument()
expect(screen.getByPlaceholderText('Message Portal...')).toBeEnabled()
})
it('shows a verified fixed external-host model without inventing a context window', async () => {
globalThis.fetch.mockResolvedValue(response({
available: true,
model: 'pixel/default',
runtime: { source: 'external-host', model: 'Qwen3.5-9B-Q4_K_M.gguf' },
}))
render(<Pixel systemStatus={{ inference: { loadedModel: 'stale-local-model', contextSize: 32768 } }} />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
expect(screen.getByRole('button',{name:'Choose model: Qwen 3.5 9B'})).toBeInTheDocument()
expect(screen.getByRole('button',{name:'Token usage unavailable'})).toBeInTheDocument()
expect(screen.queryByText('stale-local-model')).not.toBeInTheDocument()
})
it('ignores an unknown runtime source and keeps the fallback local identity', async () => {
globalThis.fetch.mockResolvedValue(
response({
available: true,
model: 'pixel/default',
detail: 'Owner agent ready',
runtime: {
source: 'local',
model: 'forged-runtime',
contextLength: 131072,
maxTokens: 16384,
reasoning: false,
},
})
)
render(<Pixel systemStatus={{
inference: {
loadedModel: 'Qwen3.5-9B-Q4_K_M.gguf',
contextSize: 32768,
},
}} />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
expect(screen.getByRole('button',{name:'Choose model: Qwen 3.5 9B'})).toBeInTheDocument()
expect(screen.getByRole('button',{name:'Token usage unavailable'})).toBeInTheDocument()
expect(screen.queryByText('forged-runtime')).not.toBeInTheDocument()
})
it.each([200, 409, 'rejected-stream'])('starts catalog installation only after an accepted owner chat command (%s)', async status => {
const plan = {schemaVersion: 1, extensionId: 'demo', steps: [{extensionId: 'demo', action: 'none',
status: 'enabled', missingConfiguration: [], configuration: []}]}
globalThis.fetch.mockImplementation(async url => {
if (url === '/api/pixel/status') return response({available: true, model: 'pixel/default', detail: 'local'})
if (url === '/api/pixel/chat/stream') return status === 200
? sseResponse([JSON.stringify({choices: [{delta: {content: 'Checking extension.'}}]}), '[DONE]'])
: status === 'rejected-stream' ? sseResponse([JSON.stringify({error:{type:'pixel_dashboard_error',code:'transition_in_progress'}}),'[DONE]'])
: response({detail: 'Model switch pending'}, 409)
if (url === '/api/extensions/demo/install-next') return response({schemaVersion: 1, extensionId: 'demo',
state: 'succeeded', dispatched: false, plan})
if (url === '/api/extensions/demo/install-plan') return response(plan)
return response({extensions: []})
})
render(<Pixel />)
await screen.findByText('Available')
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), {target: {value: '/extensions @demo '}})
fireEvent.click(screen.getByTitle('Send'))
if (status === 200) await screen.findByText('Checking extension.')
else await waitFor(() => expect(screen.getByRole('textbox')).toHaveValue('/extensions @demo'))
const installs = globalThis.fetch.mock.calls.filter(([url]) => url === '/api/extensions/demo/install-next')
expect(installs).toHaveLength(status === 200 ? 1 : 0)
})
it('does not create a GitHub extension request for a rejected admission', async () => {
const command = '/extensions https://github.com/owner/repo'
globalThis.fetch.mockImplementation(async url => url === '/api/pixel/chat/stream'
? sseResponse([JSON.stringify({error:{type:'pixel_dashboard_error',code:'transition_in_progress'}}),'[DONE]'])
: response({available:true}))
render(<Pixel />)
await screen.findByText('Available')
fireEvent.change(screen.getByRole('textbox'), {target:{value:command}})
fireEvent.click(screen.getByTitle('Send'))
await screen.findByText(/This message was not started/)
expect(screen.getByRole('textbox')).toHaveValue(command)
expect(fetch.mock.calls.filter(([url])=>url.startsWith('/api/extensions/github/requests'))).toHaveLength(0)
})
it.each([null,{active:false,outcome:'rolled_back',failureCode:'runtime_load_failed'}])('shows a retained model hold and keeps model recovery evidence (%j)', async modelActivation => {
const detail = 'A model transition is holding new messages. Check model update progress. If it has stopped, restore Sandbox in Portal permissions.'
globalThis.fetch.mockResolvedValue(response({available:false,model:null,state:'model_transition_pending',detail,modelActivation}))
render(<Pixel />)
expect(await screen.findByText('Model transition pending')).toBeVisible()
expect(screen.getByText(detail)).toBeVisible()
expect(screen.getByRole('textbox')).toBeDisabled()
expect(screen.queryByText('Portal is switching models')).toBeNull()
if (modelActivation) expect(screen.getByText('Model switch failed; previous model restored')).toBeVisible()
expect(fetch.mock.calls.filter(([url])=>url==='/api/pixel/chat/stream')).toHaveLength(0)
})
it('sends exact body to stream endpoint', async () => {
globalThis.fetch.mockResolvedValueOnce(
response({ available: true, model: 'pixel/default', detail: 'local' })
)
render(<Pixel />)
await waitFor(() => {
expect(screen.getByText('Available')).toBeInTheDocument()
})
// Prepare stream response
const streamFrames = [
JSON.stringify({ choices: [{ delta: { content: 'Hello' } }] }),
'[DONE]',
]
globalThis.fetch.mockResolvedValueOnce(sseResponse(streamFrames))
const textarea = screen.getByPlaceholderText('Message Portal...')
fireEvent.change(textarea, { target: { value: 'hi there' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => {
expect(globalThis.fetch).toHaveBeenCalledWith(
'/api/pixel/chat/stream',
expect.objectContaining({
method: 'POST',
headers: { 'Content-Type': 'application/json' },
})
)
})
const call = globalThis.fetch.mock.calls.find(
c => c[0] === '/api/pixel/chat/stream'
)
const body = JSON.parse(call[1].body)
expect(body.messages).toHaveLength(1)
expect(body.messages[0].role).toBe('user')
expect(body.messages[0].content).toBe('hi there')
expect(body.chat_id).toBeDefined()
expect(body.request_id).toEqual(expect.any(String))
expect(call[1].headers).toEqual({ 'Content-Type': 'application/json' })
expect(call[1].headers.Authorization).toBeUndefined()
})
it('sends only role and content on later turns', async () => {
globalThis.fetch.mockResolvedValueOnce(
response({ available: true, model: 'pixel/default', detail: 'local' })
)
globalThis.fetch.mockResolvedValueOnce(sseResponse([
JSON.stringify({ choices: [{ delta: { content: 'First answer' } }] }),
'[DONE]',
]))
globalThis.fetch.mockResolvedValueOnce(sseResponse([
JSON.stringify({ choices: [{ delta: { content: 'Second answer' } }] }),
'[DONE]',
]))
render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
const textarea = screen.getByPlaceholderText('Message Portal...')
fireEvent.change(textarea, { target: { value: 'first turn' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(screen.getByText('First answer')).toBeInTheDocument())
fireEvent.change(textarea, { target: { value: 'second turn' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(screen.getByText('Second answer')).toBeInTheDocument())
const chatCalls = globalThis.fetch.mock.calls.filter(
call => call[0] === '/api/pixel/chat/stream'
)
expect(chatCalls).toHaveLength(2)
const body = JSON.parse(chatCalls[1][1].body)
expect(body.messages).toEqual([
{ role: 'user', content: 'first turn' },
{ role: 'assistant', content: 'First answer' },
{ role: 'user', content: 'second turn' },
])
expect(body.messages.every(message => Object.keys(message).sort().join(',') === 'content,role')).toBe(true)
expect(body.history_snapshot).toEqual({schemaVersion:1,messages:body.messages})
})
it.each([0,2])('recovers once from a zero-submission marker while preserving history from contextStart=%s', async contextStart => {
globalThis.localStorage.setItem('ods.pixel.chat.v1', JSON.stringify({
schema: 1,
chatId: 'long-running-chat',
contextStart,
messages: [
...(contextStart ? [{role:'user',content:'Excluded earlier request'},{role:'assistant',content:'Excluded earlier answer'}] : []),
{ role: 'user', content: 'old context' },
{ role: 'assistant', content: 'old answer' },
],
}))
const marker = JSON.stringify({
choices: [{ delta: {}, finish_reason: 'stop' }],
pixel: {
schemaVersion: 1,
recovery: 'clean-context',
reason: 'operations-unavailable-zero-submissions',
},
})
globalThis.fetch.mockResolvedValueOnce(
response({ available: true, model: 'pixel/default', detail: 'local' })
)
globalThis.fetch.mockResolvedValueOnce(sseResponse([
JSON.stringify({ choices: [{ delta: { content: 'unverified model prose' } }] }),
marker,
'[DONE]',
]))
globalThis.fetch.mockResolvedValueOnce(sseResponse([
JSON.stringify({ choices: [{ delta: { content: 'Verified recovery result' } }] }),
'[DONE]',
]))
globalThis.fetch.mockResolvedValueOnce(sseResponse([
JSON.stringify({ choices: [{ delta: { content: 'Follow-up result' } }] }),
'[DONE]',
]))
render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
const textarea = screen.getByPlaceholderText('Message Portal...')
fireEvent.change(textarea, { target: { value: 'Inspect the installed extension.' } })
fireEvent.click(screen.getByTitle('Send'))
expect(await screen.findByText('Verified recovery result')).toBeInTheDocument()
expect(screen.getByText('Recovered with a clean context')).toBeInTheDocument()
expect(screen.queryByText('unverified model prose')).not.toBeInTheDocument()
const firstTwo = globalThis.fetch.mock.calls.filter(call => call[0] === '/api/pixel/chat/stream')
expect(firstTwo).toHaveLength(2)
const firstBody = JSON.parse(firstTwo[0][1].body)
const retryBody = JSON.parse(firstTwo[1][1].body)
expect(retryBody.chat_id).not.toBe(firstBody.chat_id)
expect(retryBody.messages).toEqual([
{ role: 'user', content: 'Inspect the installed extension.' },
])
expect(retryBody.history_snapshot).toEqual(firstBody.history_snapshot)
expect(retryBody.history_snapshot.messages).toEqual([
{ role: 'user', content: 'old context' },
{ role: 'assistant', content: 'old answer' },
...retryBody.messages,
])
const savedRecovery = JSON.parse(localStorage.getItem('ods.pixel.chat.v1'))
expect(savedRecovery.contextStart).toBe(contextStart)
expect(savedRecovery.messages[contextStart].content).toBe('old context')
expect(screen.getByText('old answer')).toBeVisible()
// Text can render before the stream's final cleanup enables the composer.
await waitFor(() => expect(textarea).not.toBeDisabled())
fireEvent.change(textarea, { target: { value: 'Continue from that verified result.' } })
await waitFor(() => expect(screen.getByTitle('Send')).not.toBeDisabled())
fireEvent.click(screen.getByTitle('Send'))
expect(await screen.findByText('Follow-up result')).toBeInTheDocument()
const chatCalls = globalThis.fetch.mock.calls.filter(call => call[0] === '/api/pixel/chat/stream')
expect(chatCalls).toHaveLength(3)
expect(JSON.parse(chatCalls[2][1].body)).toEqual({
chat_id: retryBody.chat_id,
request_id: expect.any(String),
history_snapshot:{schemaVersion:1,messages:[
{ role: 'user', content: 'old context' },
{ role: 'assistant', content: 'old answer' },
{ role: 'user', content: 'Inspect the installed extension.' },
{ role: 'assistant', content: 'Verified recovery result' },
{ role: 'user', content: 'Continue from that verified result.' },
]},
messages: [
{ role: 'user', content: 'old context' },
{ role: 'assistant', content: 'old answer' },
{ role: 'user', content: 'Inspect the installed extension.' },
{ role: 'assistant', content: 'Verified recovery result' },
{ role: 'user', content: 'Continue from that verified result.' },
],
})
})
it.each([409,412])('preserves the original history boundary when recovery is rejected with %s',async rejection=>{
const messages=[{role:'user',content:'Excluded request'},{role:'assistant',content:'Excluded answer'},
{role:'user',content:'The project is Cedar'},{role:'assistant',content:'I will remember Cedar'}]
localStorage.setItem('ods.pixel.chat.v1',JSON.stringify({schema:1,chatId:'retry-history-chat',contextStart:2,messages}))
const marker=JSON.stringify({choices:[{delta:{},finish_reason:'stop'}],pixel:{schemaVersion:1,recovery:'clean-context',reason:'operations-unavailable-zero-submissions'}})
let attempts=0
fetch.mockImplementation(async url=>{
if(url==='/api/pixel/chat/stream')return ++attempts===1?sseResponse([marker,'[DONE]']):response({detail:'Model preparation in progress'},rejection)
if(url==='/api/pixel/chat/context')return response({schemaVersion:1,status:'missing',sessionRevision:null,context:null,model:null,compaction:{status:'idle',count:0},history:{revision:null,acknowledgedMessages:0}})
return response({available:true})
})
render(<Pixel/>);await screen.findByText('Available')
const textarea=screen.getByPlaceholderText('Message Portal...')
fireEvent.change(textarea,{target:{value:'Continue Cedar'}})
fireEvent.click(screen.getByTitle('Send'))
await waitFor(()=>expect(textarea).toHaveValue('Continue Cedar'))
const calls=fetch.mock.calls.filter(([url])=>url==='/api/pixel/chat/stream')
expect(calls).toHaveLength(2)
expect(JSON.parse(calls[1][1].body).history_snapshot.messages).toEqual([...messages.slice(2),{role:'user',content:'Continue Cedar'}])
expect(JSON.parse(localStorage.getItem('ods.pixel.chat.v1'))).toMatchObject({contextStart:2,messages,draft:'Continue Cedar'})
})
it('stops honestly after a second host-authoritative zero-submission marker', async () => {
const marker = JSON.stringify({
choices: [{ delta: {}, finish_reason: 'stop' }],
pixel: {
schemaVersion: 1,
recovery: 'clean-context',
reason: 'operations-unavailable-zero-submissions',
},
})
globalThis.fetch.mockResolvedValueOnce(
response({ available: true, model: 'pixel/default', detail: 'local' })
)
globalThis.fetch.mockResolvedValueOnce(sseResponse([marker, '[DONE]']))
globalThis.fetch.mockResolvedValueOnce(sseResponse([marker, '[DONE]']))
render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), {
target: { value: 'Inspect ODS through Operations.' },
})
fireEvent.click(screen.getByTitle('Send'))
expect(await screen.findByText(/Automatic recovery was attempted once/)).toBeInTheDocument()
expect(globalThis.fetch.mock.calls.filter(call => call[0] === '/api/pixel/chat/stream')).toHaveLength(2)
expect(screen.queryByText('Recovered with a clean context')).not.toBeInTheDocument()
})
it('never retries from matching model prose without the structured host marker', async () => {
const prose = 'Pixel did not submit the requested host or Operations work through the isolated Operations Broker.'
globalThis.fetch.mockResolvedValueOnce(
response({ available: true, model: 'pixel/default', detail: 'local' })
)
globalThis.fetch.mockResolvedValueOnce(sseResponse([
JSON.stringify({ choices: [{ delta: { content: prose } }] }),
'[DONE]',
]))
render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), {
target: { value: 'Discuss the fallback wording.' },
})
fireEvent.click(screen.getByTitle('Send'))
expect(await screen.findByText(prose, {}, { timeout: 3000 })).toBeInTheDocument()
expect(globalThis.fetch.mock.calls.filter(call => call[0] === '/api/pixel/chat/stream')).toHaveLength(1)
})
it('starts a clean conversation with a new opaque chat id', async () => {
globalThis.fetch.mockResolvedValueOnce(
response({ available: true, model: 'pixel/default', detail: 'local' })
)
globalThis.fetch.mockResolvedValueOnce(sseResponse([
JSON.stringify({ choices: [{ delta: { content: 'First answer' } }] }),
'[DONE]',
]))
globalThis.fetch.mockResolvedValueOnce(sseResponse([
JSON.stringify({ choices: [{ delta: { content: 'Second answer' } }] }),
'[DONE]',
]))
render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
const textarea = screen.getByPlaceholderText('Message Portal...')
fireEvent.change(textarea, { target: { value: 'first turn' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(screen.getByText('First answer')).toBeInTheDocument())
const firstCall = globalThis.fetch.mock.calls.find(call => call[0] === '/api/pixel/chat/stream')
const firstChatId = JSON.parse(firstCall[1].body).chat_id
fireEvent.click(screen.getByTitle('Start a new chat'))
expect(screen.queryByText('First answer')).not.toBeInTheDocument()
expect(screen.getByText('What do you want to work on?')).toBeInTheDocument()
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), { target: { value: 'second turn' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(screen.getByText('Second answer')).toBeInTheDocument())
const chatCalls = globalThis.fetch.mock.calls.filter(call => call[0] === '/api/pixel/chat/stream')
const secondChatId = JSON.parse(chatCalls[1][1].body).chat_id
expect(secondChatId).not.toBe(firstChatId)
})
it('parses SSE chunks and displays content', async () => {
globalThis.fetch.mockResolvedValueOnce(
response({ available: true, model: 'pixel/default', detail: 'local' })
)
render(<Pixel />)
await waitFor(() => {
expect(screen.getByText('Available')).toBeInTheDocument()
})
const frames = [
JSON.stringify({ choices: [{ delta: { content: 'Hello' } }] }),
JSON.stringify({ choices: [{ delta: { content: ' world' } }] }),
'[DONE]',
]
globalThis.fetch.mockResolvedValueOnce(sseResponse(frames))
const textarea = screen.getByPlaceholderText('Message Portal...')
fireEvent.change(textarea, { target: { value: 'hello' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => {
expect(screen.getByText((_,node)=>node.tagName==='P' && node.textContent==='Hello world')).toBeInTheDocument()
})
})
it('parses chunks across arbitrary boundaries', async () => {
globalThis.fetch.mockResolvedValueOnce(
response({ available: true, model: 'pixel/default', detail: 'local' })
)
render(<Pixel />)
await waitFor(() => {
expect(screen.getByText('Available')).toBeInTheDocument()
})
// Split the JSON across two reader.read() calls
const frames = [
JSON.stringify({ choices: [{ delta: { content: 'Split' } }] }),
JSON.stringify({ choices: [{ delta: { content: ' test' } }] }),
'[DONE]',
]
// First chunk has only partial first frame, second has rest
const encoder = new TextEncoder()
const full = frames.map(f => encoder.encode(`data: ${f}\n\n`))
const firstFrame = full[0]
const mid = Math.floor(firstFrame.length / 2)
let idx = 0
const chunks = [firstFrame.slice(0, mid), firstFrame.slice(mid), full[1], full[2]]
globalThis.fetch.mockResolvedValueOnce({
ok: true,
status: 200,
body: {
getReader: () => ({
read: async () => {
if (idx >= chunks.length) return { done: true, value: undefined }
return { done: false, value: chunks[idx++] }
},
releaseLock: () => {},
}),
},
headers: new Map([['content-type', 'text/event-stream']]),
})
const textarea = screen.getByPlaceholderText('Message Portal...')
fireEvent.change(textarea, { target: { value: 'boundaries' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => {
expect(screen.getByText((_,node)=>node.tagName==='P' && node.textContent==='Split test')).toBeInTheDocument()
})
})
it('preserves an in-flight request and partial answer across repeated reloads without replay', async () => {
let releasePendingRead
let reads = 0
globalThis.fetch.mockImplementation(async (url, options) => {
if (url === '/api/pixel/status') return response({ available: true })
if (url === '/api/pixel/chat/activity') return response({ state: 'unknown' })
if (url !== '/api/pixel/chat/stream') throw new Error(`unexpected request: ${url}`)
const pendingRead = new Promise(resolve => { releasePendingRead = resolve })
options.signal.addEventListener('abort', () => releasePendingRead({ done: true }), { once: true })
return {
ok: true,
headers: new Map([['content-type', 'text/event-stream']]),
body: { getReader: () => ({
read: async () => reads++ === 0
? { done: false, value: new TextEncoder().encode('data: {"choices":[{"delta":{"content":"Created report.md; checking its contents."}}]}\n\n') }
: pendingRead,
releaseLock: () => {},
}) },
}
})
const first = render(<Pixel />)
await screen.findByText('Available')
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), { target: { value: 'Create a report, then verify it.' } })
fireEvent.click(screen.getByTitle('Send'))
await screen.findByText('Created report.md; checking its contents.')
const request = JSON.parse(globalThis.fetch.mock.calls.find(([url]) => url === '/api/pixel/chat/stream')[1].body)
await waitFor(() => {
const saved = JSON.parse(globalThis.localStorage.getItem('ods.pixel.chat.v1'))
expect(saved.chatId).toBe(request.chat_id)
expect(saved.inFlight).toBe(true)
expect(saved.messages).toEqual([
{ role: 'user', content: 'Create a report, then verify it.' },
{ role: 'assistant', content: 'Created report.md; checking its contents.' },
])
})
first.unmount()
await act(async () => {})
for (let reload = 0; reload < 2; reload += 1) {
const restored = render(<Pixel />)
await screen.findByText('Portal can’t confirm your last request has finished.')
expect(screen.getByRole('button', { name: 'Continue in this chat' })).toBeEnabled()
expect(screen.getByText('Create a report, then verify it.')).toBeInTheDocument()
expect(screen.getByText('Created report.md; checking its contents.')).toBeInTheDocument()
expect(screen.queryByText(/Activity unknown|Completion was not confirmed/)).not.toBeInTheDocument()
expect(screen.queryByText(/Stopped by you/)).not.toBeInTheDocument()
expect(screen.queryByTitle('Stop')).not.toBeInTheDocument()
expect(globalThis.fetch.mock.calls.filter(([url]) => url === '/api/pixel/chat/stream')).toHaveLength(1)
restored.unmount()
}
})
it('recovers a completed answer after closing the original stream without resubmitting in StrictMode', async () => {
const siteId = 'site-' + 'a'.repeat(24)
const preview = {schemaVersion:1,kind:'ods-pixel-workspace-preview',relativeDirectory:'recovery-demo',siteId,port:9437,
url:`http://${siteId}.localhost:9437/${siteId}/`,files:2,bytes:4096,
sha256:'a'.repeat(64),entrySha256:'b'.repeat(64)}
globalThis.localStorage.setItem('ods.pixel.chat.v1', JSON.stringify({
schema:1, chatId:'durable-chat', requestId:'durable-attempt', inFlight:true,
messages:[{role:'user',content:'Make my preview'},{role:'assistant',content:'Partial answer'}],
}))
previewManifests.set(`/pixel-preview/${siteId}/__ods_manifest__.json`,preview)
globalThis.fetch.mockImplementation(async (url, options) => {
if (url === '/api/pixel/status') return response({available:true})
if (url === '/api/pixel/chat/result') {
expect(JSON.parse(options.body)).toEqual({chat_id:'durable-chat',request_id:'durable-attempt'})
return response({state:'complete',events:[
'data: '+JSON.stringify({choices:[{delta:{content:'Recovered final answer'}}]}),
'data: '+JSON.stringify({choices:[{finish_reason:'stop'}],pixel:{schemaVersion:1,preview}}),
'data: [DONE]', '',
].join('\n')})
}
throw new Error(`Unexpected request ${url}`)
})
const first = render(<StrictMode><Pixel /></StrictMode>)
expect(await screen.findByText('Recovered final answer')).toBeVisible()
expect(await screen.findByTitle('Interactive Portal preview')).toHaveAttribute('src',`/pixel-preview/${siteId}/__ods_view__.html`)
expect(screen.queryByText('Partial answer')).toBeNull()
expect(globalThis.fetch.mock.calls.some(([url]) => url === '/api/pixel/chat/stream')).toBe(false)
await waitFor(() => expect(JSON.parse(localStorage.getItem('ods.pixel.chat.v1')).inFlight).toBe(false))
first.unmount()
render(<Pixel />)
expect(await screen.findByText('Recovered final answer')).toBeVisible()
expect(screen.getAllByText('Recovered final answer')).toHaveLength(1)
})
it('recovers an exact pre-submission 503 receipt and sends the next turn with a new identity', async () => {
const rejection = 'Portal did not start this attempt. Restore its connection and send your message again.'
const attempts = []
globalThis.fetch.mockImplementation(async (url, options) => {
if (url === '/api/pixel/status') return response({available:true})
if (url === '/api/pixel/chat/stream') {
const attempt = JSON.parse(options.body)
attempts.push(attempt)
if (attempts.length === 1) return response({detail:'Could not confirm the assistant name. Please retry.'}, 503)
return sseResponse([JSON.stringify({choices:[{delta:{content:'Connected again'}}]}), '[DONE]'])
}
if (url === '/api/pixel/chat/result') {
expect(JSON.parse(options.body)).toEqual({chat_id:attempts[0].chat_id,request_id:attempts[0].request_id})
return response({state:'interrupted',events:[
'data: '+JSON.stringify({choices:[{delta:{content:rejection}}]}),
'data: '+JSON.stringify({error:{message:rejection,type:'pixel_dashboard_error'}}),
'data: [DONE]', '',
].join('\n')})
}
if (url === '/api/pixel/chat/activity') return response({state:'unknown'})
throw new Error(`Unexpected request ${url}`)
})
render(<Pixel />)
await screen.findByText('Available')
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), {target:{value:'Check my files'}})
fireEvent.click(screen.getByTitle('Send'))
expect(await screen.findByText(rejection)).toBeVisible()
expect(screen.queryByText('Activity unknown')).not.toBeInTheDocument()
expect(screen.queryByTitle('Stop')).not.toBeInTheDocument()
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), {target:{value:'Try again'}})
fireEvent.click(screen.getByTitle('Send'))
expect(await screen.findByText('Connected again')).toBeVisible()
expect(attempts).toHaveLength(2)
expect(attempts[1].chat_id).toBe(attempts[0].chat_id)
expect(attempts[1].request_id).not.toBe(attempts[0].request_id)
})
it('does not call a retained zero-submission receipt completed or resubmit it on reload', async () => {
localStorage.setItem('ods.pixel.chat.v1', JSON.stringify({schema:1,chatId:'not-started-chat',requestId:'not-started-attempt',inFlight:true,
messages:[{role:'user',content:'Do my task'},{role:'assistant',content:''}]}))
const frame = {choices:[{delta:{},finish_reason:'stop'}],pixel:{schemaVersion:1,recovery:'clean-context',reason:'operations-unavailable-zero-submissions'}}
globalThis.fetch.mockImplementation(async url => {
if (url === '/api/pixel/status') return response({available:true})
if (url === '/api/pixel/chat/result') return response({state:'complete',events:'data: '+JSON.stringify(frame)+'\n\ndata: [DONE]\n\n'})
throw new Error(`Unexpected request ${url}`)
})
render(<Pixel />)
expect(await screen.findByText('Portal did not start this attempt. Send your message again to continue.')).toBeVisible()
expect(screen.queryByText('Completed without a text response.')).toBeNull()
expect(globalThis.fetch.mock.calls.some(([url]) => url === '/api/pixel/chat/stream')).toBe(false)
})
it('commits its recovery identity before starting a request', async () => {
globalThis.fetch.mockImplementation(async (url, options) => {
if (url === '/api/pixel/status') return response({available:true})
if (url === '/api/pixel/chat/stream') {
const sent = JSON.parse(options.body)
const saved = JSON.parse(localStorage.getItem('ods.pixel.chat.v1'))
expect(saved.requestId).toBe(sent.request_id)
expect(saved.chatId).toBe(sent.chat_id)
expect(saved.inFlight).toBe(true)
expect(saved.messages).toEqual([{role:'user',content:'Retain this task'},{role:'assistant',content:''}])
return sseResponse([JSON.stringify({choices:[{delta:{content:'Stored'}}]}),'[DONE]'])
}
throw new Error(`Unexpected request ${url}`)
})
render(<Pixel />); await screen.findByText('Available')
fireEvent.change(screen.getByPlaceholderText('Message Portal...'),{target:{value:'Retain this task'}})
fireEvent.click(screen.getByTitle('Send'))
expect(await screen.findByText('Stored')).toBeVisible()
})
it('does not start orphaned work when the attempt identity cannot be saved', async () => {
globalThis.fetch.mockResolvedValue(response({available:true}))
render(<Pixel />); await screen.findByText('Available')
vi.spyOn(window.Storage.prototype,'setItem').mockImplementation(() => { throw new Error('quota') })
fireEvent.change(screen.getByPlaceholderText('Message Portal...'),{target:{value:'Keep my draft'}})
fireEvent.click(screen.getByTitle('Send'))
expect(await screen.findByText(/No task was started/)).toBeVisible()
expect(screen.getByPlaceholderText('Message Portal...')).toHaveValue('Keep my draft')
expect(globalThis.fetch.mock.calls.some(([url]) => url === '/api/pixel/chat/stream')).toBe(false)
})
function saveInterruptedChat() {
globalThis.localStorage.setItem('ods.pixel.chat.v1', JSON.stringify({
schema: 1, chatId: 'restored_opaque_chat', inFlight: true,
messages: [{ role: 'user', content: 'Inspect my project' }, { role: 'assistant', content: 'Saved partial result' }],
}))
}
it.each([false, true])('bounds a stalled recovery lookup and permits a fresh inspection (receipt=%s)', async retained => {
saveInterruptedChat()
if (retained) {
const saved = JSON.parse(localStorage.getItem('ods.pixel.chat.v1'))
localStorage.setItem('ods.pixel.chat.v1', JSON.stringify({...saved, requestId:'retained-attempt'}))
}
const signals = []
const endpoint = retained ? '/api/pixel/chat/result' : '/api/pixel/chat/activity'
globalThis.fetch.mockImplementation(async (url, options) => {
if (url === '/api/pixel/status') return response({available:true})
expect(url).toBe(endpoint)
expect(options.signal.aborted).toBe(false)
signals.push(options.signal)
if (signals.length === 1) return new Promise((resolve, reject) => {
options.signal.addEventListener('abort', () => reject(new globalThis.DOMException('aborted','AbortError')), {once:true})
})
return response(retained ? {state:'complete',events:'data: {"choices":[{"delta":{"content":"Recovered after timeout"}}]}\n\ndata: [DONE]\n\n'} : {state:'terminal'})
})
vi.useFakeTimers()
await act(async () => { render(<Pixel />) })
expect(signals).toHaveLength(1)
await act(async () => { await vi.advanceTimersByTimeAsync(15000) })
expect(signals[0].aborted).toBe(true)
expect(screen.getByRole('button',{name:'Continue in this chat'})).toBeEnabled()
expect(screen.getByText('Saved partial result')).toBeVisible()
// The next check starts by itself, with a fresh deadline.
await act(async () => { await vi.advanceTimersByTimeAsync(1000) })
expect(signals).toHaveLength(2)
expect(signals[1]).not.toBe(signals[0])
expect(screen.getByPlaceholderText('Message Portal...')).toBeEnabled()
expect(screen.getByText(retained ? 'Recovered after timeout' : 'Saved partial result')).toBeVisible()
expect(globalThis.fetch.mock.calls.some(([url]) => url === '/api/pixel/chat/stream')).toBe(false)
})
it('restored activity tracks this chat from active to terminal without replay or stopped claims', async () => {
saveInterruptedChat()
let state = 'active'
globalThis.fetch.mockImplementation(async (url, options) => {
if (url === '/api/pixel/status') return response({ available: true })
expect(url).toBe('/api/pixel/chat/activity')
expect(JSON.parse(options.body)).toEqual({ chat_id: 'restored_opaque_chat' })
return response({ state })
})
render(<Pixel />)
await screen.findByText('Working in this chat')
expect(screen.getByTitle('Stop')).toBeEnabled()
// The draft stays editable; only sending and New chat wait, with a reason.
expect(screen.getByPlaceholderText('Message Portal...')).toBeEnabled()
expect(screen.queryByTitle('Send')).toBeNull()
expect(screen.getByRole('button', {name:'New chat'})).toHaveAttribute('aria-disabled', 'true')
expect(screen.getByRole('button', {name:'New chat'})).toHaveAttribute('title', expect.stringContaining('Portal is finishing the current task'))
expect(screen.getByText('Saved partial result')).toBeInTheDocument()
// No receipt brings this turn's answer back here, so the line never promises it.
expect(screen.getByText('Portal is still working on your last request. When it’s done, ask Portal what it did. You can stop it.')).toBeVisible()
expect(screen.queryByRole('button', {name:'Continue in this chat'})).not.toBeInTheDocument()
state = 'terminal'
// The server proved the turn is over: the reply settles calmly, it is
// never claimed as the owner's Stop, and the composer is free again.
await screen.findByText(CUT_OFF, {}, { timeout: 3000 })
expect(screen.queryByTitle('Stop')).not.toBeInTheDocument()
expect(screen.queryByText(/Stopped by you|no longer active|was not recovered/)).not.toBeInTheDocument()
expect(screen.getByText('Saved partial result')).toBeInTheDocument()
expect(screen.queryByRole('status', { name: 'Last message' })).not.toBeInTheDocument()
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), { target: { value: 'What did you change?' } })
expect(screen.getByTitle('Send')).toBeEnabled()
expect(globalThis.fetch.mock.calls.some(([url]) => url === '/api/pixel/chat/stream')).toBe(false)
})
it('rechecks the selected interrupted chat even when the previous interrupted chat is terminal', async () => {
saveConversation({schema:1,chatId:'second_interrupted',interrupted:true,messages:[{role:'user',content:'Another task'}]})
saveInterruptedChat()
globalThis.fetch.mockImplementation(async (url, options) => {
if (url === '/api/pixel/status') return response({available:true})
expect(url).toBe('/api/pixel/chat/activity')
const {chat_id} = JSON.parse(options.body)
return response({state:chat_id === 'second_interrupted' ? 'active' : 'terminal'})
})
render(<Pixel />)
await screen.findByText(CUT_OFF)
act(()=>window.dispatchEvent(new CustomEvent('ods:pixel-select-conversation',{detail:'second_interrupted'})))
await screen.findByText('Working in this chat')
expect(fetch).toHaveBeenCalledWith('/api/pixel/chat/activity',expect.objectContaining({body:JSON.stringify({chat_id:'second_interrupted'})}))
expect(screen.getByPlaceholderText('Message Portal...')).toBeEnabled()
expect(screen.queryByTitle('Send')).toBeNull()
expect(screen.getByTitle('Stop')).toBeEnabled()
})
it('restored activity recovers from unknown and only exact cancellation marks this chat stopped', async () => {
saveInterruptedChat()
let state = 'unknown'
let aborted = false
globalThis.fetch.mockImplementation(async (url, options) => {
if (url === '/api/pixel/status') return response({ available: false, switching: true })
expect(JSON.parse(options.body)).toEqual({ chat_id: 'restored_opaque_chat' })
if (url === '/api/pixel/chat/activity') return response({ state })
expect(url).toBe('/api/pixel/chat/cancel')
return response({ aborted })
})
render(<Pixel />)
await screen.findByText('Portal can’t confirm your last request has finished.')
expect(screen.queryByTitle('Stop')).not.toBeInTheDocument()
state = 'active'
// The next check, on a growing interval, finds the work still running.
await screen.findByText('Working in this chat', {}, { timeout: 3000 })
expect(screen.getByRole('textbox')).toBeDisabled()
fireEvent.click(screen.getByTitle('Stop'))
await screen.findByRole('alert')
expect(screen.queryByText('Response stopped')).not.toBeInTheDocument()
expect(screen.getByText('Saved partial result')).toBeInTheDocument()
aborted = true
fireEvent.click(screen.getByTitle('Stop'))
await screen.findByText('Response stopped')
expect(screen.getByText('Saved partial result')).toBeInTheDocument()
expect(globalThis.fetch.mock.calls.some(([url]) => url === '/api/pixel/chat/stream')).toBe(false)
})
it('restored activity terminal observation wins a pending cancellation race', async () => {
saveInterruptedChat()
let state = 'active'
let finishCancel
globalThis.fetch.mockImplementation(async (url) => {
if (url === '/api/pixel/status') return response({ available: true })
if (url === '/api/pixel/chat/activity') return response({ state })
if (url === '/api/pixel/chat/cancel') return new Promise(resolve => { finishCancel = resolve })
throw new Error('unexpected replay')
})
render(<Pixel />)
await screen.findByTitle('Stop')
fireEvent.click(screen.getByTitle('Stop'))
state = 'terminal'
await screen.findByText(CUT_OFF, {}, { timeout: 3000 })
await act(async () => { finishCancel(response({ aborted: true })) })
// The late acknowledgement never rewrites the settled reply as a Stop.
expect(screen.queryByText(/Stopped by you/)).not.toBeInTheDocument()
expect(screen.getByText(CUT_OFF)).toBeInTheDocument()
expect(screen.getByText('Saved partial result')).toBeInTheDocument()
expect(screen.queryByTitle('Stop')).not.toBeInTheDocument()
})
it('restored activity rejects unrelated global activity and allows a failed lookup retry', async () => {
saveInterruptedChat()
let calls = 0
globalThis.fetch.mockImplementation(async (url) => {
if (url === '/api/pixel/status') return response({ available: true })
expect(url).toBe('/api/pixel/chat/activity')
calls += 1
if (calls === 1) throw new Error('offline')
if (calls === 2) return response({ active: true, streams: 1 })
return response({ state: 'active' })
})
render(<Pixel />)
await screen.findByText('Portal can’t confirm your last request has finished.')
// Neither a failed lookup nor global activity counts as this chat's work.
await waitFor(() => expect(calls).toBe(2), { timeout: 3000 })
expect(screen.getByText('Portal can’t confirm your last request has finished.')).toBeVisible()
expect(screen.queryByTitle('Stop')).not.toBeInTheDocument()
await screen.findByText('Working in this chat', {}, { timeout: 4000 })
})
it('restored unknown activity permits an explicit exact-chat Continue without replay, and says stopped only once confirmed', async () => {
saveInterruptedChat()
let aborted = false
globalThis.fetch.mockImplementation(async (url, options) => {
if (url === '/api/pixel/status') return response({ available: true })
expect(JSON.parse(options.body)).toEqual({ chat_id: 'restored_opaque_chat' })
if (url === '/api/pixel/chat/activity') return response({ state: 'unknown' })
expect(url).toBe('/api/pixel/chat/cancel')
return response({ aborted })
})
render(<Pixel />)
await screen.findByText('Portal can’t confirm your last request has finished.')
expect(globalThis.fetch.mock.calls.some(([url]) => url === '/api/pixel/chat/cancel')).toBe(false)
fireEvent.click(screen.getByRole('button', { name: 'Continue in this chat' }))
await screen.findByText('Portal could not confirm this chat is free yet. Try again in a moment.')
expect(screen.queryByText('Response stopped')).not.toBeInTheDocument()
expect(screen.getByText('Saved partial result')).toBeInTheDocument()
aborted = true
fireEvent.click(screen.getByRole('button', { name: 'Continue in this chat' }))
// Continue stops anything left over: only its confirmation says stopped,
// and the reply never claims Portal finished.
await screen.findByText('Response stopped')
expect(screen.getByText(/Stopped by you/)).toBeInTheDocument()
expect(screen.queryByText(CUT_OFF)).not.toBeInTheDocument()
expect(screen.getByText('Saved partial result')).toBeInTheDocument()
expect(globalThis.fetch.mock.calls.some(([url]) => url === '/api/pixel/chat/stream')).toBe(false)
})
it('disables send while streaming', async () => {
globalThis.fetch.mockResolvedValueOnce(
response({ available: true, model: 'pixel/default', detail: 'local' })
)
// Stream that holds open
const holdReader = {
read: async () => new Promise(() => {}),
releaseLock: () => {},
}
globalThis.fetch.mockResolvedValueOnce({
ok: true,
status: 200,
body: { getReader: () => holdReader },
headers: new Map([['content-type', 'text/event-stream']]),
})
render(<Pixel />)
await waitFor(() => {
expect(screen.getByText('Available')).toBeInTheDocument()
})
const textarea = screen.getByPlaceholderText('Message Portal...')
fireEvent.change(textarea, { target: { value: 'test' } })
fireEvent.click(screen.getByTitle('Send'))
// During streaming the Send button is replaced by a Stop button;
// the textarea stays editable for the next message.
await waitFor(() => {
expect(screen.queryByTitle('Send')).not.toBeInTheDocument()
const ta = screen.getByPlaceholderText('Message Portal...')
expect(ta).toBeEnabled()
expect(screen.getByText('Working')).toBeInTheDocument()
expect(screen.getAllByText(/0:00 elapsed/).length).toBeGreaterThan(0)
expect(screen.getByText('Thinking…')).toBeInTheDocument()
const reply = screen.getByText('Thinking…').closest('[data-pixel-response]')
expect(reply.querySelectorAll('.pixel-character')).toHaveLength(1)
expect(reply.querySelector('.pixel-reply-character')).not.toBeNull()
expect(screen.queryByText('Available')).not.toBeInTheDocument()
})
})
it('renders an owner-stopped response as a neutral terminal state', async () => {
globalThis.fetch.mockResolvedValueOnce(
response({ available: true, model: 'pixel/default', detail: 'local' })
)
globalThis.fetch.mockResolvedValueOnce({
ok: true,
status: 200,
body: {
getReader: () => ({
read: async () => new Promise(() => {}),
releaseLock: () => {},
}),
},
headers: new Map([['content-type', 'text/event-stream']]),
})
globalThis.fetch.mockResolvedValueOnce(response({ aborted: true }))
render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), {
target: { value: 'long task' },
})
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(screen.getByTitle('Stop')).toBeInTheDocument())
fireEvent.click(screen.getByTitle('Stop'))
const stopped = await screen.findByText('Response stopped')
expect(globalThis.fetch).toHaveBeenCalledWith('/api/pixel/chat/cancel', expect.objectContaining({
method: 'POST',
}))
expect(stopped.parentElement).toHaveClass('pixel-stopped-response', 'bg-transparent')
expect(stopped.parentElement).not.toHaveClass('bg-theme-text-secondary/10', 'border-theme-border')
expect(stopped.parentElement).not.toHaveClass('bg-red-500/10')
expect(screen.getByText('Stopped by you. Workspace changes completed before cancellation were preserved.')).toBeInTheDocument()
expect(screen.getByText('Available')).toBeInTheDocument()
expect(screen.getByTitle('Send')).toBeDisabled()
})
it('keeps partial output but marks it durably when the owner stops a response', async () => {
globalThis.fetch.mockResolvedValueOnce(
response({ available: true, model: 'pixel/default', detail: 'local' })
)
const encoder = new TextEncoder()
let reads = 0
let closeReader
globalThis.fetch.mockResolvedValueOnce({
ok: true,
status: 200,
body: {
getReader: () => ({
read: async () => {
reads += 1
if (reads === 1) {
return {
done: false,
value: encoder.encode('data: {"choices":[{"delta":{"content":"Partial verified work"}}]}\n\n'),
}
}
return new Promise(resolve => { closeReader = resolve })
},
releaseLock: () => {},
}),
},
headers: new Map([['content-type', 'text/event-stream']]),
})
globalThis.fetch.mockResolvedValueOnce(response({ aborted: true }))
render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), {
target: { value: 'long task with partial output' },
})
fireEvent.click(screen.getByTitle('Send'))
await screen.findByText('Partial verified work')
fireEvent.click(screen.getByTitle('Stop'))
expect(await screen.findByText('Response stopped')).toBeInTheDocument()
await act(async () => { closeReader({ done: true }) })
expect(screen.queryByText(/Completion was not confirmed/)).not.toBeInTheDocument()
expect(screen.getByText('Response stopped')).toBeInTheDocument()
expect(screen.getByText('Partial verified work')).toBeInTheDocument()
expect(screen.getByText('Stopped by you. Workspace changes completed before cancellation were preserved.')).toBeInTheDocument()
await waitFor(() => {
const stored = JSON.parse(globalThis.localStorage.getItem('ods.pixel.chat.v1'))
expect(stored.messages.at(-1).content).toContain('Stopped by you.')
expect(stored.interrupted).toBe(false)
expect(stored.inFlight).toBe(false)
})
})
it.each(['delta', 'error', 'eof'])('isolates a new reply from a stopped reader that delivers a late %s', async late => {
const pending = []
let requests = 0
globalThis.fetch.mockImplementation(async url => {
if (url === '/api/pixel/status') return response({available:true})
if (url === '/api/pixel/chat/cancel') return response({aborted:true})
if (url !== '/api/pixel/chat/stream') throw new Error('Unexpected request')
const index = requests++
return {ok:true, status:200, body:{getReader:()=>({
read:()=>new Promise((resolve,reject)=>{pending[index]={resolve,reject}}),
releaseLock:()=>{},
})}}
})
render(<Pixel />)
await screen.findByText('Available')
const send = text => {
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), {target:{value:text}})
fireEvent.click(screen.getByTitle('Send'))
}
send('First task')
await waitFor(()=>expect(pending[0]).toBeDefined())
fireEvent.click(screen.getByTitle('Stop'))
await screen.findByText('Response stopped')
send('Second task')
await waitFor(()=>expect(pending[1]).toBeDefined())
await act(async()=>{
if (late === 'error') pending[0].reject(new Error('Late network failure'))
else pending[0].resolve(late === 'eof' ? {done:true} : {
done:false,value:new TextEncoder().encode('data: {"choices":[{"delta":{"content":"Old reply leaking"}}]}\n\ndata: [DONE]\n\n'),
})
})
expect(screen.queryByText('Old reply leaking')).not.toBeInTheDocument()
expect(screen.getByTitle('Stop')).toBeInTheDocument()
expect(JSON.parse(localStorage.getItem('ods.pixel.chat.v1')).inFlight).toBe(true)
await act(async()=>pending[1].resolve({done:false,value:new TextEncoder().encode('data: {"choices":[{"delta":{"content":"Second reply correct"}}]}\n\ndata: [DONE]\n\n')}))
await screen.findByText('Second reply correct')
expect(screen.getByText('Response stopped')).toBeInTheDocument()
expect(screen.getByText('Available')).toBeInTheDocument()
})
it('keeps the live stream attached and Stop retryable without an exact acknowledgement', async () => {
globalThis.fetch.mockResolvedValueOnce(
response({ available: true, model: 'pixel/default', detail: 'local' })
)
globalThis.fetch.mockResolvedValueOnce({
ok: true,
status: 200,
body: {
getReader: () => ({
read: async () => new Promise(() => {}),
releaseLock: () => {},
}),
},
headers: new Map([['content-type', 'text/event-stream']]),
})
globalThis.fetch.mockResolvedValueOnce(response({ aborted: false }))
globalThis.fetch.mockResolvedValueOnce(response({ aborted: true }))
render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), {
target: { value: 'long task' },
})
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(screen.getByTitle('Stop')).toBeInTheDocument())
fireEvent.click(screen.getByTitle('Stop'))
expect(await screen.findByRole('alert')).toHaveTextContent(
'Stop was not confirmed. Portal is still connected; retry Stop.'
)
expect(screen.queryByText('Response stopped')).not.toBeInTheDocument()
fireEvent.click(screen.getByTitle('Stop'))
expect(await screen.findByText('Response stopped')).toBeInTheDocument()
})
it('enforces input limit', async () => {
globalThis.fetch.mockResolvedValueOnce(
response({ available: true, model: 'pixel/default', detail: 'local' })
)
render(<Pixel />)
await waitFor(() => {
expect(screen.getByText('Available')).toBeInTheDocument()
})
const textarea = screen.getByPlaceholderText('Message Portal...')
const longText = 'a'.repeat(16 * 1024 + 1)
fireEvent.change(textarea, { target: { value: longText } })
await waitFor(() => {
expect(screen.getByText(/too long/)).toBeInTheDocument()
})
const sendBtn = screen.getByTitle('Send')
expect(sendBtn).toBeDisabled()
})
it('shows only a generic message for an upstream error frame', async () => {
globalThis.fetch.mockResolvedValueOnce(
response({ available: true, model: 'pixel/default', detail: 'local' })
)
globalThis.fetch.mockResolvedValueOnce(sseResponse([
JSON.stringify({ error: 'upstream-secret-value' }),
'[DONE]',
]))
render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), { target: { value: 'test' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => {
expect(screen.getByText('Portal could not complete the response.')).toBeInTheDocument()
})
expect(screen.queryByText(/upstream-secret-value/)).not.toBeInTheDocument()
})
it.each([false, true])('explains rate limits without leaking details or replaying work (restored=%s)', async restored => {
const error = {type:'pixel_ingress_error',code:'provider_rate_limited',message:'private-upstream-secret'}
const frames = [
JSON.stringify({choices:[{delta:{content:'Saved edits'}}]}),
JSON.stringify({error}),
JSON.stringify({choices:[{delta:{content:'False success'}}]}),
'[DONE]',
]
if (restored) localStorage.setItem('ods.pixel.chat.v1', JSON.stringify({
schema:1,chatId:'limited-chat',requestId:'limited-attempt',inFlight:true,
messages:[{role:'user',content:'Continue editing'},{role:'assistant',content:''}],
}))
globalThis.fetch.mockImplementation(async url => {
if (url === '/api/pixel/chat/stream') return sseResponse(frames)
if (url === '/api/pixel/chat/result') return response({state:'interrupted',events:frames.map(frame=>'data: '+frame+'\n\n').join('')})
return response({available:true})
})
render(<Pixel />)
await screen.findByText('Available')
if (!restored) {
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), {target:{value:'Continue editing'}})
fireEvent.click(screen.getByTitle('Send'))
}
expect(await screen.findByText(/The model provider reached its rate limit/)).toBeVisible()
expect(screen.getByText('Saved edits')).toBeVisible()
expect(screen.queryByText(/private-upstream-secret|False success/)).toBeNull()
await waitFor(()=>expect(JSON.parse(localStorage.getItem('ods.pixel.chat.v1')).messages.at(-1).status).toBe('error'))
expect(fetch.mock.calls.filter(([url])=>url==='/api/pixel/chat/stream')).toHaveLength(restored ? 0 : 1)
})
it.each(['transition_in_progress','gateway_connect_refused'].flatMap(code =>
[{restored:false}, {restored:true}, {restored:true,draft:'A newer draft'}].map(item => ({...item,code}))))('restores a rejected draft without resuming execution (%j)', async ({restored,draft,code}) => {
const frames = [JSON.stringify({error:{type:'pixel_dashboard_error',code,message:'private-secret'}}),'[DONE]']
if (restored) localStorage.setItem('ods.pixel.chat.v1', JSON.stringify({
schema:1,chatId:'rejected-chat',requestId:'rejected-attempt',inFlight:true,draft,
messages:[{role:'user',content:'Keep this request'},{role:'assistant',content:''}],
}))
globalThis.fetch.mockImplementation(async url => {
if (url === '/api/pixel/chat/stream') return sseResponse(frames)
if (url === '/api/pixel/chat/result') return response({state:'rejected',events:frames.map(frame=>'data: '+frame+'\n\n').join('')})
return response({available:true})
})
render(<Pixel />)
await screen.findByText('Available')
if (!restored) {
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), {target:{value:'Keep this request'}})
fireEvent.click(screen.getByTitle('Send'))
}
await waitFor(()=>expect(screen.getByRole('textbox').value).toBe(draft || 'Keep this request'))
await waitFor(()=>{
const saved=JSON.parse(localStorage.getItem('ods.pixel.chat.v1'))
expect(saved.requestId).toBeFalsy()
expect(saved.interrupted).toBe(false)
expect(saved.inFlight).toBe(false)
expect(saved.messages[0]).toMatchObject({role:'user',content:'Keep this request'})
expect(saved.messages.at(-1).content).toContain(code === 'gateway_connect_refused'
? 'Portal did not start this attempt because its gateway was unavailable.' : 'This message was not started.')
})
expect(screen.queryByText(/could not complete|Check saved work|private-secret/)).toBeNull()
expect(fetch.mock.calls.filter(([url])=>url==='/api/pixel/chat/stream')).toHaveLength(restored ? 0 : 1)
})
it.each([
['partial text', 'Saved edits', 'Saved edits'],
['no text', '', 'Portal could not complete the response. Check saved work before continuing.'],
])('keeps the previous wording for a recovered generic failure (%s)', async (_name, partial, expected) => {
const frames = [
...(partial ? [JSON.stringify({choices:[{delta:{content:partial}}]})] : []),
JSON.stringify({error:{message:'private-upstream-secret'}}),
'[DONE]',
]
localStorage.setItem('ods.pixel.chat.v1', JSON.stringify({
schema:1,chatId:'generic-chat',requestId:'generic-attempt',inFlight:true,
messages:[{role:'user',content:'Continue editing'},{role:'assistant',content:''}],
}))
globalThis.fetch.mockImplementation(async url => {
if (url === '/api/pixel/chat/result') return response({state:'interrupted',events:frames.map(frame=>'data: '+frame+'\n\n').join('')})
return response({available:true})
})
render(<Pixel />)
await screen.findByText('Available')
await waitFor(()=>expect(JSON.parse(localStorage.getItem('ods.pixel.chat.v1')).messages.at(-1).content).toBe(expected))
expect(screen.queryByText(/private-upstream-secret/)).toBeNull()
})
it('keeps a stream that closes without DONE calm and checks it instead of calling it failed', async () => {
globalThis.fetch.mockResolvedValueOnce(
response({ available: true, model: 'pixel/default', detail: 'local' })
)
globalThis.fetch.mockResolvedValueOnce(sseResponse([
JSON.stringify({ choices: [{ delta: { content: 'Partial answer' } }] }),
]))
render(<Pixel />)
await waitFor(() => expect(screen.getByText('Available')).toBeInTheDocument())
fireEvent.change(screen.getByPlaceholderText('Message Portal...'), { target: { value: 'test' } })
fireEvent.click(screen.getByTitle('Send'))
expect(await screen.findByRole('status', { name: 'Last message' })).toBeVisible()
expect(screen.getByText('Partial answer')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Continue in this chat' })).toBeEnabled()
expect(screen.queryByText(/Response interrupted|Connection interrupted|could not be received|Ended early/)).not.toBeInTheDocument()
await waitFor(() => expect(JSON.parse(localStorage.getItem('ods.pixel.chat.v1'))).toMatchObject({ interrupted: true }))
expect(JSON.parse(localStorage.getItem('ods.pixel.chat.v1')).messages.at(-1).status).toBeUndefined()
})
it('preserves partial answers and ignores late content after an upstream error', async () => {
globalThis.fetch.mockResolvedValueOnce(response({available:true}))
globalThis.fetch.mockResolvedValueOnce(sseResponse([
JSON.stringify({choices:[{delta:{content:'Work already explained'}}]}),
JSON.stringify({error:'private-upstream-error'}),
JSON.stringify({choices:[{delta:{content:'False late success'}}]}),
'[DONE]',
]))
const view=render(<Pixel />)
await screen.findByText('Available')
fireEvent.change(screen.getByPlaceholderText('Message Portal...'),{target:{value:'test'}})
fireEvent.click(screen.getByTitle('Send'))
await screen.findByText('Portal could not complete the response.')
expect(screen.getByText('Work already explained')).toBeInTheDocument()
expect(screen.queryByText(/False late success|private-upstream-error/)).toBeNull()
await waitFor(()=>{
const saved=JSON.parse(localStorage.getItem('ods.pixel.chat.v1'))
expect(saved.messages.at(-1).status).toBe('error')
expect(saved.inFlight).toBe(false)
})
view.unmount()
globalThis.fetch.mockResolvedValue(response({available:true}))
render(<Pixel />)
expect(screen.getByText('Work already explained')).toBeInTheDocument()
expect(JSON.parse(localStorage.getItem('ods.pixel.chat.v1')).messages.at(-1).status).toBe('error')
})
it('restores long assistant replies without losing the chat and bounds only their API copy',async()=>{
const longReply='Long explanation '+ 'x'.repeat(20000)
localStorage.setItem('ods.pixel.chat.v1',JSON.stringify({schema:1,chatId:'long_reply',messages:[{role:'user',content:'Original task'},{role:'assistant',content:longReply,status:'done'}]}))
globalThis.fetch.mockImplementation(async url=>url==='/api/pixel/chat/stream' ? sseResponse([JSON.stringify({choices:[{delta:{content:'Follow-up answer'}}]}),'[DONE]']) : response({available:true}))
render(<Pixel />)
await screen.findByText('Available')
expect(screen.getByText(longReply)).toBeInTheDocument()
fireEvent.change(screen.getByPlaceholderText('Message Portal...'),{target:{value:'Continue'}})
fireEvent.click(screen.getByTitle('Send'))
await screen.findByText('Follow-up answer')
const body=JSON.parse(fetch.mock.calls.find(([url])=>url==='/api/pixel/chat/stream')[1].body)
expect(body.chat_id).toBe('long_reply')
expect(body.messages.every(message=>message.content.length<=16384)).toBe(true)
expect(body.messages[1].content).toContain('shortened for model context')
expect(screen.getByText(longReply)).toBeInTheDocument()
expect(JSON.parse(localStorage.getItem('ods.pixel.chat.v1')).messages[1].content).toBe(longReply)
})
it.each(['Files','Review'])('reloads the active %s inspector after a failed fetch',async tab=>{
const sha256='a'.repeat(64),siteId=`site-${sha256.slice(0,24)}`
localStorage.setItem('ods.pixel.chat.v1',JSON.stringify({schema:1,chatId:'reload_inspector',messages:[{role:'user',content:'Inspect project'}],preview:{schemaVersion:1,kind:'ods-pixel-workspace-preview',relativeDirectory:'demo',siteId,port:9437,url:`http://${siteId}.localhost:9437/${siteId}/`,files:1,bytes:100,sha256,entrySha256:'b'.repeat(64)}}))
let failed=true
const preview=JSON.parse(localStorage.getItem('ods.pixel.chat.v1')).preview
globalThis.fetch.mockImplementation(async url=>{
if(url==='/api/pixel/status')return response({available:true})
if(!failed && url.includes('__ods_manifest__'))return previewManifestResponse(preview)
return {ok:false}
})
render(<Pixel />)
await screen.findByText('Available')
fireEvent.click(tab==='Files' ? screen.getByRole('button',{name:'Browse files'}) : screen.getByRole('tab',{name:'Review'}))
await screen.findByText(tab==='Files' ? 'Files unavailable.' : /File comparison unavailable/)
const inspector=tab==='Files' ? '__ods_manifest__' : '__ods_changes__'
const requests=()=>fetch.mock.calls.filter(([url])=>url.startsWith('/pixel-preview/') && url.includes(inspector)).length
const before=requests()
fireEvent.click(screen.getByTitle('Reload preview'))
await waitFor(()=>expect(requests()).toBe(before+1))
if(tab==='Files') expect(screen.getByRole('button',{name:'Browse files'})).toHaveAttribute('aria-pressed','true')
expect(screen.getByRole('tab',{name:tab==='Files'?'Preview':'Review'})).toHaveAttribute('aria-selected','true')
expect(screen.queryByTitle('Interactive Portal preview')).toBeNull()
if(tab==='Files') fireEvent.click(screen.getByRole('button',{name:'Browse files'}))
else fireEvent.click(screen.getByRole('tab',{name:'Preview'}))
expect(screen.queryByTitle('Interactive Portal preview')).toBeNull()
failed=false
fireEvent.click(screen.getByTitle('Reload preview'))
expect(await screen.findByTitle('Interactive Portal preview')).toBeVisible()
expect(screen.getByRole('tabpanel',{name:'Preview'})).toBeVisible()
expect(screen.queryByRole('tabpanel',{name:'Review'})).toBeNull()
expect(screen.queryByText('Files unavailable.')).toBeNull()
})
it('renders assistant HTML as inert text', async () => {
const maliciousFrames = [
JSON.stringify({ choices: [{ delta: { content: '<script>alert(1)</script>' } }] }),
'[DONE]',
]
globalThis.fetch.mockResolvedValueOnce(
response({ available: true, model: 'pixel/default', detail: 'local' })
)
globalThis.fetch.mockResolvedValueOnce(sseResponse(maliciousFrames))
render(<Pixel />)
await waitFor(() => {
expect(screen.getByText('Available')).toBeInTheDocument()
})
const textarea = screen.getByPlaceholderText('Message Portal...')
fireEvent.change(textarea, { target: { value: 'test' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => {
const el = screen.getByText('<script>alert(1)</script>')
expect(el.tagName.toLowerCase()).not.toBe('script')
})
})
})
// Fix the numeric locale for English accessibility fixtures on every host OS.
beforeEach(()=>{vi.spyOn(Number.prototype,'toLocaleString').mockImplementation(function(locales,options){
return new Intl.NumberFormat(locales || 'en-US',options).format(this.valueOf())
})})