style(workspace): align browsing with the approved concept (#219)

* style(workspace): align approved shell and visual fixtures

* test(workflows): preserve evidence across browser projects

* style(workspace): match approved image browsing geometry

* style(workspace): match natural library card layout

* fix(workspace): retain wheel motion during row correction

* fix(workspace): contain zoomed controls and image metadata (#215)
This commit is contained in:
Vito
2026-10-18 02:53:26 -07:00
committed by GitHub
parent 4ef236aaf7
commit e7cfcc2bfb
25 changed files with 1749 additions and 180 deletions
+20 -1
View File
@@ -190,7 +190,7 @@ test('responsive gallery defers observed size writes and still fits the new view
await expect(page.locator('.image-card')).toHaveCount(4);
await page.setViewportSize({width:390,height:844});
await expect.poll(()=>page.locator('.image-card').first().evaluate(node=>node.getBoundingClientRect().width)).toBeLessThan(390);
await expect.poll(()=>page.locator('.image-grid').evaluate(node=>Number.parseFloat(node.style.height))).toBeGreaterThan(900);
await expect.poll(()=>page.locator('.image-grid').evaluate(node=>Number.parseFloat(node.style.height))).toBeCloseTo(383.75,0);
expect(await page.evaluate(()=>window.inlineResizeWrites)).toBe(0);
});
@@ -203,3 +203,22 @@ test('unverified saved associations explain uncertainty and cannot be sent',asyn
await expect(role(details(page),'Positive')).toContainText('cannot be verified against this file');
await expect(details(page).getByRole('button',{name:/^Send /})).toHaveCount(0);
});
test('prompt role headings contain compact real actions and honest source evidence',async({page})=>{
await page.goto(workspace);await select(page,'0:shared/same.png');
for (const name of ['Positive','Negative']) {
const block=role(details(page),name),heading=block.locator('.prompt-block-heading');
await expect(heading.getByRole('heading',{name:`${name} prompt`,exact:true})).toBeVisible();
await expect(heading.getByRole('button',{name:`Copy ${name.toLowerCase()} prompt`,exact:true})).toBeVisible();
await expect(heading.getByRole('button',{name:`Send ${name.toLowerCase()} prompt`,exact:true})).toBeVisible();
await expect(heading.locator('[data-copy-role] svg')).toHaveCount(1);
expect(await heading.evaluate(node=>node.nextElementSibling.classList.contains('prompt-source'))).toBe(true);
}
await expect(role(details(page),'Positive').locator('.prompt-source')).toHaveText('Inferred from the saved workflow');
await select(page,'0:empty-negative.png');
await expect(role(details(page),'Negative')).toContainText('Empty negative prompt');
await expect(role(details(page),'Negative').locator('.prompt-block-heading [data-copy-role]')).toHaveCount(1);
await select(page,'0:uncertain.png');await expect(details(page).locator('[data-copy-role]')).toHaveCount(0);
await expect(details(page)).toContainText('Not recorded in this file.');
});
+22 -1
View File
@@ -14,6 +14,8 @@ from aiohttp import web
from PIL import Image
from PIL.PngImagePlugin import PngInfo
from tests.browser.workspace_visual_fixture import seed_workspace_visual
class TestModel:
default_prompt = "Describe the image"
@@ -223,6 +225,7 @@ def create_app(root: Path) -> web.Application:
@routes.post("/__test__/reset")
async def reset(request: web.Request) -> web.Response:
data = await request.json() if request.can_read_body else {}
workspace_visual = data.get("workspace_visual", False)
extra = data.get("extra_images", 0)
include_video = data.get("include_video", False)
prompt_inspector = data.get("prompt_inspector", False)
@@ -230,7 +233,22 @@ def create_app(root: Path) -> web.Application:
extra_prompts = data.get("extra_prompts", 0)
extra_variants = data.get("extra_variants", 0)
if (
isinstance(extra, bool)
not isinstance(workspace_visual, bool)
or (
workspace_visual
and any(
key in data
for key in (
"extra_images",
"include_video",
"prompt_inspector",
"native_library",
"extra_prompts",
"extra_variants",
)
)
)
or isinstance(extra, bool)
or not isinstance(extra, int)
or not 0 <= extra <= 200
or not isinstance(include_video, bool)
@@ -244,6 +262,9 @@ def create_app(root: Path) -> web.Application:
or not 0 <= extra_variants <= 200
):
raise web.HTTPBadRequest()
if workspace_visual:
await api._run_in_executor(seed_workspace_visual, api, root)
return web.json_response({"success": True})
await api._run_in_executor(
seed,
extra,
+77 -1
View File
@@ -17,7 +17,13 @@ test.afterEach(async ({ page, browserName }) => {
expect(page.imageErrors).toEqual([]);
});
test('native Images keeps colliding filenames distinct and inspects the selected source', async ({ page, request }) => {
test('native Images keeps colliding filenames distinct and inspects the selected source', async ({ page, request }, testInfo) => {
await page.setViewportSize({width:1600,height:1100});
async function capture(name) {
await page.evaluate(async()=>{await document.fonts.ready;await Promise.all([...document.images].map(image=>image.decode().catch(()=>{})));});
const path=testInfo.outputPath(`${name}.png`);await page.screenshot({path});
await testInfo.attach(name,{path,contentType:'image/png'});
}
const snapshot = await (await request.get('/prompt_manager/stats')).json();
await page.goto(workspace);
await expect(cards(page)).toHaveCount(2);
@@ -29,8 +35,17 @@ test('native Images keeps colliding filenames distinct and inspects the selected
await expect(details(page)).toContainText('same.png');
await expect(details(page)).toContainText('shared/same.png');
await expect(details(page)).toContainText(/input/i);
await capture('after-images-source-collision-input-1600');
await cards(page).first().getByRole('button', { name: 'Open same.png', exact: true }).click();
await expect(details(page)).toContainText(/output/i);
await capture('after-images-source-collision-output-1600');
await page.setViewportSize({width:390,height:844});
for (const [index,source] of [[1,'input'],[0,'output']]) {
await cards(page).nth(index).getByRole('button',{name:'Open same.png',exact:true}).click();
await expect(details(page)).toContainText(new RegExp(source,'i'));
await details(page).scrollIntoViewIfNeeded();
await capture(`after-images-source-collision-${source}-390`);
}
expect((await (await request.get('/prompt_manager/stats')).json()).stats).toEqual(snapshot.stats);
});
@@ -480,3 +495,64 @@ test('leaving during Refresh cancels it without replacing the next workspace', a
await expect(page.getByRole('heading', { name: 'Continue creating', exact: true })).toBeVisible();
await expect(page.getByText('Images could not be refreshed. Try Refresh again.', { exact: true })).toHaveCount(0);
});
test('Images uses approved geometry while keeping real controls', async ({page,request}) => {
await request.post('/__test__/reset',{data:{workspace_visual:true}});
await page.setViewportSize({width:1600,height:1100});
await page.goto(workspace);
await expect(cards(page)).toHaveCount(24);
await expect(page.locator('.workspace-heading-copy > .intro')).toHaveCount(1);
await expect(details(page)).toHaveCSS('width','310px');
await expect(page.locator('.image-workspace')).toHaveCSS('column-gap','22px');
for (const label of ['Source','Folder','Media','Sort','Thumbnail size']) await expect(page.getByRole('combobox',{name:label,exact:true})).toBeVisible();
await expect(page.getByRole('searchbox',{name:'Search filenames',exact:true})).toHaveAttribute('placeholder',/filename or folder/);
await expect(page.getByRole('link',{name:'Group by positive prompt',exact:true})).toHaveAttribute('href','#/library');
const geometry = await cards(page).evaluateAll(nodes=>nodes.slice(0,4).map(node=>{
const box=node.getBoundingClientRect(),media=node.querySelector('.image-open').getBoundingClientRect();
return {x:box.x,y:box.y,right:box.right,bottom:box.bottom,width:box.width,mediaWidth:media.width,mediaHeight:media.height};
}));
expect(geometry[1].x-geometry[0].right).toBeCloseTo(13,0);
expect(geometry[3].y-geometry[0].bottom).toBeCloseTo(13,0);
expect(geometry[3].x).toBeCloseTo(geometry[0].x,0);
expect(geometry[0].mediaWidth/geometry[0].mediaHeight).toBeCloseTo(4/3,2);
expect((await page.locator('.image-toolbar').boundingBox()).y).toBeLessThan(geometry[0].y);
await expect(cards(page).first()).toHaveCSS('outline-style','solid');
const cover=details(page).locator(':scope > img');
await expect(cover).toHaveCSS('height','150px');
expect(await details(page).evaluate(node=>node.firstElementChild.tagName)).toBe('IMG');
await page.setViewportSize({width:390,height:844});
await expect.poll(()=>cards(page).nth(1).evaluate(node=>node.offsetTop)).toBe(0);
await expect.poll(()=>cards(page).nth(2).evaluate(node=>node.offsetTop)).toBeGreaterThan(0);
expect(await page.evaluate(()=>document.documentElement.scrollWidth-document.documentElement.clientWidth)).toBeLessThanOrEqual(1);
});
test('density changes and resize preserve identity focus and selection', async ({page,request}) => {
await request.post('/__test__/reset',{data:{workspace_visual:true}});
await page.setViewportSize({width:1600,height:1100});await page.goto(workspace);
await expect(cards(page)).toHaveCount(24);
const first=cards(page).first();await first.evaluate(node=>{window.originalImageCard=node;});
await first.getByRole('button',{name:/^Open /}).click();
const key=await first.getAttribute('data-image-key');
let imageReads=0;page.on('request',request=>{if(request.url().includes('/images/output?')) imageReads++;});
for (const layout of ['Grid','List','Masonry']) for (const [density,columns] of [['comfortable',3],['large',2],['compact',4]]) {
await page.getByRole('button',{name:layout,exact:true}).click();
await page.getByRole('combobox',{name:'Thumbnail size',exact:true}).selectOption(density);
await first.getByRole('button',{name:/^Open /}).focus();await page.keyboard.press('ArrowDown');
await expect(cards(page).nth(layout==='List'?1:columns).getByRole('button',{name:/^Open /})).toBeFocused();
await expect(first).toHaveClass(/selected/);
expect(await first.evaluate(node=>node===window.originalImageCard)).toBe(true);
}
expect(imageReads).toBe(0);
await page.evaluate(()=>{location.hash='#/overview';});await expect(page.locator('h1')).toHaveText('Overview');
await page.evaluate(()=>{location.hash='#/images';});await expect(page.getByRole('combobox',{name:'Thumbnail size',exact:true})).toHaveValue('compact');
await expect(page.locator(`article[data-image-key="${key}"]`)).toHaveClass(/selected/);
await page.getByRole('button',{name:'Grid',exact:true}).click();
for (const [width,columns] of [[951,3],[950,3],[700,2],[390,2]]) {
await page.setViewportSize({width,height:844});
await expect.poll(()=>cards(page).nth(columns).evaluate(node=>node.offsetLeft)).toBe(0);
await first.getByRole('button',{name:/^Open /}).focus();await page.keyboard.press('ArrowDown');
await expect(cards(page).nth(columns).getByRole('button',{name:/^Open /})).toBeFocused();
expect(await page.evaluate(()=>document.documentElement.scrollWidth-document.documentElement.clientWidth)).toBeLessThanOrEqual(1);
}
});
+257
View File
@@ -97,6 +97,25 @@ test('failed library reads retry while late search responses cannot overwrite ne
await expect(cards(page)).toHaveCount(1);await expect(cards(page).first()).toContainText('Dog landscape');release();await expect(cards(page).first()).toContainText('Dog landscape');
});
test('refresh atomically discards old row geometry and renders changed parent data',async({page,request})=>{
await page.goto(route);await expect(cards(page)).toHaveCount(3);
const card=cards(page).filter({has:page.getByText('Dog landscape',{exact:true})});const id=await card.getAttribute('data-prompt-id');
await expect(await request.put(`/prompt_manager/prompts/${id}`,{data:{text:'Revised dog landscape'}})).toBeOK();
await expect(await request.put(`/prompt_manager/prompts/${id}/rating`,{data:{rating:5}})).toBeOK();
await page.evaluate(()=>{
const native=requestAnimationFrame;const held=[];let paused=true;window.releaseLibraryFrames=()=>{paused=false;window.requestAnimationFrame=native;for(const callback of held)callback();};
window.requestAnimationFrame=callback=>native(time=>{if(paused)held.push(()=>callback(time));else callback(time);});
});
try {
await page.getByRole('button',{name:'Refresh library',exact:true}).click();
await expect(page.locator('.library-status')).not.toHaveText('Loading prompt library…');
} finally {await page.evaluate(()=>window.releaseLibraryFrames());}
await expect(cards(page)).toHaveCount(3);
const changed=page.locator(`article[data-prompt-id="${id}"]`);await expect(changed).toContainText('Revised dog landscape');
await expect(changed.getByRole('img',{name:'Rated 5 out of 5',exact:true})).toHaveCount(1);
await expect(page.getByRole('button',{name:'Retry prompt library',exact:true})).toBeHidden();
});
test('returning from history restores library context and mobile content stays inside the viewport',async({page})=>{
await page.setViewportSize({width:390,height:844});await page.goto(route);
await page.getByRole('combobox',{name:'Category',exact:true}).selectOption('Animals');
@@ -110,6 +129,29 @@ test('returning from history restores library context and mobile content stays i
await expect(history(page)).toHaveCount(0);await expect(page.locator('dialog[open]')).toHaveCount(0);
});
test('empty shelf visits restore saved scroll without inventing a parent anchor',async({page})=>{
await page.setViewportSize({width:1600,height:300});await page.goto(route);
await page.getByRole('searchbox',{name:'Search prompts',exact:true}).fill('No matching saved positive');
await expect(cards(page)).toHaveCount(0);await expect(page.locator('.library-status')).toContainText('No matching prompts.');
await page.evaluate(()=>scrollTo(0,document.documentElement.scrollHeight));
await expect.poll(()=>page.evaluate(()=>scrollY)).toBeGreaterThan(0);
const position=await page.evaluate(()=>scrollY);
await page.getByRole('navigation',{name:'Workspace',exact:true}).getByRole('link',{name:'Overview',exact:true}).evaluate(node=>node.click());
await expect(page.locator('#workspace-main h1')).toHaveText('Overview');
await page.getByRole('navigation',{name:'Workspace',exact:true}).getByRole('link',{name:'Prompt library',exact:true}).evaluate(node=>node.click());
await expect(page.getByRole('searchbox',{name:'Search prompts',exact:true})).toHaveValue('No matching saved positive');
await expect(cards(page)).toHaveCount(0);
await expect.poll(()=>page.evaluate(expected=>Math.abs(scrollY-expected),position)).toBeLessThanOrEqual(1);
const search=page.getByRole('searchbox',{name:'Search prompts',exact:true});await search.focus();await search.fill('Dog landscape');
await expect(cards(page)).toHaveCount(1);await expect(search).toBeFocused();
await page.evaluate(()=>scrollTo(0,0));await page.getByRole('button',{name:'Refresh library',exact:true}).click();await expect(cards(page)).toHaveCount(1);
expect(await page.evaluate(()=>scrollY)).toBe(0);
const anchor=await firstVisibleParent(page);expect(anchor).not.toBeNull();
await cards(page).getByRole('link',{name:'Explore history',exact:true}).evaluate(node=>node.click());await expect(history(page)).toBeVisible();
await page.setViewportSize({width:390,height:844});await page.getByRole('link',{name:'Back to library',exact:true}).click();
await retainedParent(page,anchor);await expect(page.getByRole('searchbox',{name:'Search prompts',exact:true})).toHaveValue('Dog landscape');
});
test('history detail failures retry and returning to the list ignores late detail responses',async({page})=>{
let fail=true;let release;const hold=new Promise(resolve=>{release=resolve;});
await page.route(/\/prompt_manager\/library\/\d+(?:\?|$)/,async route=>{
@@ -168,3 +210,218 @@ test('large variant histories append bounded pages without replacing the selecte
await expect(history(page).getByRole('button',{name:'Select negative variant 1',exact:true})).toHaveAttribute('aria-pressed','true');
await expect(saved(page).getByRole('region',{name:'Negative prompt',exact:true}).locator('pre')).toHaveText(chosenNegative);
});
async function observeLibrary(page, hold=false) {
await page.addInitScript(({hold})=>{
const NativeResizeObserver=window.ResizeObserver;
const records=[];let holding=hold;
const raf=window.requestAnimationFrame.bind(window),cancel=window.cancelAnimationFrame.bind(window);
const pending=new Set(),heldFrames=new Map();let requested=0,mutations=0,unmounted=0,holdingFrames=false;
window.requestAnimationFrame=callback=>{requested++;const id=raf(time=>{const deliver=()=>{pending.delete(id);callback(time);};if(holdingFrames)heldFrames.set(id,deliver);else deliver();});pending.add(id);return id;};
window.cancelAnimationFrame=id=>{pending.delete(id);heldFrames.delete(id);cancel(id);};
window.ResizeObserver=class {
constructor(callback) {
const record={callback,targets:new Set(),entries:new Map(),latest:new Map(),disconnected:false};
record.native=new NativeResizeObserver(entries=>{
const ready=[];
for(const entry of entries) {
if(entry.target.matches('.library-card')) {
if(!entry.target.isConnected)unmounted++;
record.latest.set(entry.target,entry);
if(holding) {record.entries.set(entry.target,entry);continue;}
}
ready.push(entry);
}
if(ready.length)callback(ready,this);
});records.push(record);this.record=record;
}
observe(target,options){this.record.targets.add(target);this.record.native.observe(target,options);}
unobserve(target){this.record.targets.delete(target);this.record.entries.delete(target);this.record.latest.delete(target);this.record.native.unobserve(target);}
disconnect(){this.record.disconnected=true;this.record.targets.clear();this.record.entries.clear();this.record.native.disconnect();}
};
new MutationObserver(entries=>{mutations+=entries.filter(entry=>entry.target.matches('.library-card,.library-row,.library-row-spacer')).length;}).observe(document,{subtree:true,attributes:true,attributeFilter:['style']});
window.libraryObservation={
hold(){holding=true;},
release(){holding=false;for(const record of records){const entries=[...record.entries.values()].filter(entry=>record.targets.has(entry.target));record.entries.clear();if(entries.length)record.callback(entries,record.native);}},
holdFrames(){holdingFrames=true;},
releaseFrames(){holdingFrames=false;const callbacks=[...heldFrames.values()];heldFrames.clear();for(const callback of callbacks)callback();},
equal(){for(const record of records){const entries=[...record.latest.values()].filter(entry=>record.targets.has(entry.target));if(entries.length)record.callback(entries,record.native);}},
stats(){return {requested,pending:pending.size,heldFrames:heldFrames.size,measurements:records.reduce((sum,record)=>sum+record.entries.size,0),mutations,unmounted,targets:records.reduce((sum,record)=>sum+record.targets.size,0)};},
};
},{hold});
}
async function settleLibrary(page) {
await expect.poll(async()=>page.evaluate(()=>window.libraryObservation.stats().pending)).toBe(0);
await page.evaluate(()=>new Promise(resolve=>setTimeout(resolve,60)));
await expect.poll(async()=>page.evaluate(()=>window.libraryObservation.stats().pending)).toBe(0);
}
async function firstVisibleParent(page) {
return cards(page).evaluateAll(nodes=>{
const card=nodes.find(node=>{const box=node.getBoundingClientRect();return box.bottom>0&&box.top<innerHeight;});
return card?{id:card.dataset.promptId,offset:card.getBoundingClientRect().top}:null;
});
}
async function retainedParent(page, anchor) {
const card=page.locator(`article[data-prompt-id="${anchor.id}"]`);
await expect(card).toHaveCount(1);
await expect.poll(async()=>Math.abs(await card.evaluate(node=>node.getBoundingClientRect().top)-anchor.offset)).toBeLessThanOrEqual(2);
}
test('Library natural rows retain long prompt content without overflow',async({page,request})=>{
await request.post('/__test__/reset',{data:{workspace_visual:true}});
const data=await(await request.get('/prompt_manager/library')).json();
for(const [width,height] of [[1600,1100],[390,844]]) {
await page.setViewportSize({width,height});await page.goto(route);await expect(cards(page)).toHaveCount(6);
expect(await cards(page).filter({hasText:'A study in very long creative context'}).evaluate(node=>node.getBoundingClientRect().height)).toBeGreaterThan(560);
await expect(page.locator('.workspace-heading-copy > .intro')).toContainText('One positive.');
await expect(page.locator('.library-shelf > .intro')).toHaveCount(0);
for(const theme of ['dark','light']) {
await page.getByRole('combobox',{name:'Appearance',exact:true}).selectOption(theme);
await expect(page.locator('.prompt-positive h3').first()).toHaveCSS('color',theme==='dark'?'rgb(115, 221, 169)':'rgb(23, 107, 70)');
}
await expect(page.locator('.library-card-art').first()).toHaveCSS('height',width===1600?'170px':'150px');
await expect(page.locator('.library-card-content').first()).toHaveCSS('padding',width===1600?'18px':'15px');
await expect(page.locator('.library-grid')).toHaveCSS('gap','18px');
const long=cards(page).filter({hasText:'A study in very long creative context'});
const prompt=long.locator('.prompt-text');expect((await prompt.textContent()).length).toBeGreaterThan(1500);
expect(await long.evaluate(node=>node.getBoundingClientRect().height)).toBeGreaterThan(560);
for(const selector of ['.library-card-title','.library-card-prompts','.prompt-text','.library-card-content > .library-tags']) {
expect(await long.locator(selector).evaluate(node=>node.scrollHeight<=node.clientHeight+1)).toBe(true);
}
await prompt.focus();await expect(prompt).toBeFocused();
await long.getByRole('link',{name:'Explore history',exact:true}).scrollIntoViewIfNeeded();
await expect(long.getByRole('link',{name:'Explore history',exact:true})).toBeVisible();
for(const item of data.items) {
const card=page.locator(`article[data-prompt-id="${item.id}"]`);
await expect(card.getByRole('img',{name:item.rating?`Rated ${item.rating} out of 5`:'Unrated',exact:true})).toHaveCount(1);
await expect(card.locator('.library-card-content > .library-tags .library-chip')).toHaveText(item.tags);
}
expect(await page.evaluate(()=>document.documentElement.scrollWidth-document.documentElement.clientWidth)).toBeLessThanOrEqual(1);
await expect(page.locator('.library-shelf')).not.toContainText(/\b\d+ (?:tracked )?runs\b|Used today/i);
const boxes=await cards(page).evaluateAll(nodes=>nodes.map(node=>{const b=node.getBoundingClientRect();return {x:b.x,y:b.y,right:b.right,bottom:b.bottom};}));
for(let i=0;i<boxes.length;i++) for(const b of boxes.slice(i+1)) {const a=boxes[i];expect(a.right<=b.x+1||b.right<=a.x+1||a.bottom<=b.y+1||b.bottom<=a.y+1).toBe(true);}
}
});
test('row measurement preserves anchor after width invalidation and append',async({page,request})=>{
await request.post('/__test__/reset',{data:{native_library:true,extra_prompts:200}});
await observeLibrary(page,true);await page.addInitScript(()=>{window.IntersectionObserver=undefined;});
let release;const held=new Promise(resolve=>{release=resolve;});
await page.route('**/images/serve/**',async route=>{await held;await route.continue().catch(()=>{});});
try {
await page.setViewportSize({width:1600,height:1100});await page.goto(route);
const more=page.getByRole('button',{name:'Load more prompts',exact:true});
for(const count of [40,80,120]) {await expect(page.locator('.library-caption')).toContainText(`${count} of 203`);await more.evaluate(node=>node.click());}
await expect(page.locator('.library-caption')).toContainText('160 of 203');
await page.evaluate(()=>scrollTo(0,document.querySelector('.library-grid').getBoundingClientRect().top+scrollY+40*486+25));
await settleLibrary(page);const anchor=await firstVisibleParent(page);expect(anchor).not.toBeNull();
const pinned=cards(page).first();const pinnedId=await pinned.getAttribute('data-prompt-id');await pinned.locator('a').first().evaluate(node=>node.focus({preventScroll:true}));
await page.evaluate(()=>window.libraryObservation.release());await settleLibrary(page);await retainedParent(page,anchor);
expect(await cards(page).count()).toBeLessThan(80);await expect(page.locator(`article[data-prompt-id="${pinnedId}"] a`).first()).toBeFocused();
const after=await firstVisibleParent(page);release();await page.evaluate(async()=>{await Promise.all([...document.querySelectorAll('.library-card img')].map(image=>image.decode().catch(()=>{})));});await settleLibrary(page);await retainedParent(page,after);
await more.evaluate(node=>node.click());await expect(page.locator('.library-caption')).toContainText('200 of 203');await settleLibrary(page);await retainedParent(page,after);
await expect(page.locator(`article[data-prompt-id="${pinnedId}"] a`).first()).toBeFocused();
await page.setViewportSize({width:390,height:844});await settleLibrary(page);await retainedParent(page,after);
await expect(page.locator(`article[data-prompt-id="${pinnedId}"] a`).first()).toBeFocused();
expect(await cards(page).count()).toBeLessThan(80);
const ids=await cards(page).evaluateAll(nodes=>nodes.map(node=>node.dataset.promptId));expect(new Set(ids).size).toBe(ids.length);
for(const changedWidth of [false,true]) {
const before=await firstVisibleParent(page);
await page.locator(`article[data-prompt-id="${before.id}"] .library-history-link`).evaluate(node=>node.click());await expect(history(page)).toBeVisible();
if(changedWidth)await page.setViewportSize({width:1600,height:1100});
await page.getByRole('link',{name:'Back to library',exact:true}).click();await settleLibrary(page);await retainedParent(page,before);
expect(await cards(page).count()).toBeLessThan(80);
}
expect((await page.evaluate(()=>window.libraryObservation.stats())).unmounted).toBe(0);
} finally {release();}
});
test('queued row growth preserves newer native wheel movement and correction events',async({page,request},testInfo)=>{
await request.post('/__test__/reset',{data:{native_library:true,extra_prompts:200}});
await observeLibrary(page);await page.addInitScript(()=>{window.IntersectionObserver=undefined;});
await page.setViewportSize({width:1600,height:1100});await page.goto(route);
const more=page.getByRole('button',{name:'Load more prompts',exact:true});
for(const count of [40,80,120]) {await expect(page.locator('.library-caption')).toContainText(`${count} of 203`);await more.evaluate(node=>node.click());}
await expect(page.locator('.library-caption')).toContainText('160 of 203');
await page.evaluate(()=>scrollTo(0,document.querySelector('.library-grid').getBoundingClientRect().top+scrollY+20*486+25));
await settleLibrary(page);await page.mouse.move(1100,550);
const pinned=cards(page).first(),pinnedId=await pinned.getAttribute('data-prompt-id');await pinned.locator('a').first().evaluate(node=>node.focus({preventScroll:true}));
try {
// The same queued-frame wheel sequence is stable without changed measurements.
const control=await firstVisibleParent(page),controlY=await page.evaluate(()=>scrollY);
await page.evaluate(()=>window.libraryObservation.holdFrames());await page.mouse.wheel(0,160);
await expect.poll(()=>page.evaluate(()=>scrollY)).toBe(controlY+160);
await expect.poll(()=>page.evaluate(()=>window.libraryObservation.stats().heldFrames)).toBeGreaterThan(0);
await page.evaluate(()=>window.libraryObservation.releaseFrames());await settleLibrary(page);
expect(await page.evaluate(()=>scrollY)).toBe(controlY+160);await retainedParent(page,{...control,offset:control.offset-160});
const before=await firstVisibleParent(page),beforeY=await page.evaluate(()=>scrollY);
await page.evaluate(()=>{window.libraryObservation.hold();for(const content of document.querySelectorAll('.library-card-content'))content.style.paddingBlockEnd='45px';});
await expect.poll(()=>page.evaluate(()=>window.libraryObservation.stats().measurements)).toBeGreaterThan(0);
const parent=page.locator(`article[data-prompt-id="${before.id}"]`);
const growth=await parent.evaluate(node=>node.getBoundingClientRect().top)-before.offset;
expect(growth).toBeGreaterThan(0);expect(await page.evaluate(()=>scrollY)).toBe(beforeY);
await page.evaluate(()=>{window.libraryObservation.holdFrames();window.libraryObservation.release();});
await expect.poll(()=>page.evaluate(()=>window.libraryObservation.stats().heldFrames)).toBeGreaterThan(0);
await page.mouse.wheel(0,160);await expect.poll(()=>page.evaluate(()=>scrollY)).toBe(beforeY+160);
expect(await page.evaluate(()=>document.documentElement.scrollHeight-innerHeight-scrollY)).toBeGreaterThan(1000);
await page.evaluate(()=>window.libraryObservation.releaseFrames());await settleLibrary(page);
await testInfo.attach('queued-growth-wheel-geometry',{body:JSON.stringify({beforeY,offset:before.offset,growth,wheel:160,finalY:await page.evaluate(()=>scrollY),finalOffset:await parent.evaluate(node=>node.getBoundingClientRect().top)}),contentType:'application/json'});
await retainedParent(page,{...before,offset:before.offset-160});
expect(Math.abs(await page.evaluate(()=>scrollY)-(beforeY+160+growth))).toBeLessThanOrEqual(2);
// The correction's own native scroll event must not become new user motion.
const corrected=await firstVisibleParent(page);
await page.evaluate(()=>{window.libraryObservation.hold();for(const content of document.querySelectorAll('.library-card-content'))content.style.paddingBlockEnd='65px';});
await expect.poll(()=>page.evaluate(()=>window.libraryObservation.stats().measurements)).toBeGreaterThan(0);
await page.evaluate(()=>window.libraryObservation.release());await settleLibrary(page);await retainedParent(page,corrected);
await expect(page.locator(`article[data-prompt-id="${pinnedId}"] a`).first()).toBeFocused();
const ids=await cards(page).evaluateAll(nodes=>nodes.map(node=>node.dataset.promptId));expect(ids.length).toBeLessThan(80);expect(new Set(ids).size).toBe(ids.length);
await page.evaluate(()=>window.libraryObservation.holdFrames());await page.mouse.wheel(0,160);
await expect.poll(()=>page.evaluate(()=>window.libraryObservation.stats().heldFrames)).toBeGreaterThan(0);
await page.evaluate(()=>{location.hash='#/overview';});await expect(cards(page)).toHaveCount(0);
expect((await page.evaluate(()=>window.libraryObservation.stats())).targets).toBe(0);
expect((await page.evaluate(()=>window.libraryObservation.stats())).pending).toBe(0);
expect((await page.evaluate(()=>window.libraryObservation.stats())).heldFrames).toBe(0);
expect((await page.evaluate(()=>window.libraryObservation.stats())).unmounted).toBe(0);
} finally {await page.evaluate(()=>{window.libraryObservation.release();window.libraryObservation.releaseFrames();});}
});
test('unchanged row observations settle without resize feedback',async({page,request,browserName})=>{
await request.post('/__test__/reset',{data:{native_library:true,extra_prompts:200}});
await observeLibrary(page);await page.addInitScript(()=>{window.IntersectionObserver=undefined;});
let session,breakpoint;
try {
if(browserName==='chromium') {
session=await page.context().newCDPSession(page);await session.send('Debugger.enable');
await page.addInitScript(()=>{window.libraryLayoutCalls=0;});
const scripts=[];session.on('Debugger.scriptParsed',script=>scripts.push(script));
await page.goto(route);await expect(cards(page).first()).toBeVisible();await settleLibrary(page);
const script=scripts.find(script=>script.url.endsWith('/workspace/library-layout.mjs'));expect(script).toBeTruthy();
const {scriptSource}=await session.send('Debugger.getScriptSource',{scriptId:script.scriptId});
const lines=scriptSource.split('\n');const start=lines.findIndex(line=>line.includes('export function layoutLibraryRows('));expect(start).toBeGreaterThanOrEqual(0);
const possible=await session.send('Debugger.getPossibleBreakpoints',{start:{scriptId:script.scriptId,lineNumber:start},end:{scriptId:script.scriptId,lineNumber:start+3},restrictToFunction:false});
const location=possible.locations.find(location=>location.lineNumber>start);expect(location).toBeTruthy();
breakpoint=(await session.send('Debugger.setBreakpoint',{location,condition:'(window.libraryLayoutCalls++, false)'})).breakpointId;
} else {await page.goto(route);await expect(cards(page).first()).toBeVisible();await settleLibrary(page);}
const more=page.getByRole('button',{name:'Load more prompts',exact:true});
for(const count of [40,80,120]) {await expect(page.locator('.library-caption')).toContainText(`${count} of 203`);await more.evaluate(node=>node.click());}
await expect(page.locator('.library-caption')).toContainText('160 of 203');await settleLibrary(page);
if(session)expect(await page.evaluate(()=>window.libraryLayoutCalls)).toBeGreaterThan(0);
const before=await page.evaluate(()=>({stats:window.libraryObservation.stats(),calls:window.libraryLayoutCalls}));
await page.evaluate(()=>{for(let i=0;i<12;i++){window.libraryObservation.equal();dispatchEvent(new Event('scroll'));}});await settleLibrary(page);
const after=await page.evaluate(()=>({stats:window.libraryObservation.stats(),calls:window.libraryLayoutCalls}));
expect(after.stats.requested-before.stats.requested).toBeLessThanOrEqual(1);expect(after.stats.mutations).toBe(before.stats.mutations);if(session)expect(after.calls).toBe(before.calls);
for(let i=0;i<3;i++) {await page.evaluate(()=>scrollBy(0,1));await settleLibrary(page);}
if(session)expect(await page.evaluate(()=>window.libraryLayoutCalls)).toBe(after.calls);
const equalBefore=await page.evaluate(()=>window.libraryObservation.stats().requested);await page.evaluate(()=>{for(let i=0;i<12;i++)window.libraryObservation.equal();});await settleLibrary(page);
expect((await page.evaluate(()=>window.libraryObservation.stats())).requested).toBe(equalBefore);
await page.evaluate(()=>{window.libraryObservation.hold();for(const content of document.querySelectorAll('.library-card-content'))content.style.paddingBlockEnd='35px';});await settleLibrary(page);
const calls=await page.evaluate(()=>window.libraryLayoutCalls);await page.evaluate(()=>window.libraryObservation.release());await settleLibrary(page);
if(session)expect(await page.evaluate(()=>window.libraryLayoutCalls)-calls).toBe(1);
await page.evaluate(()=>{dispatchEvent(new Event('scroll'));location.hash='#/overview';});await expect(cards(page)).toHaveCount(0);await settleLibrary(page);
expect((await page.evaluate(()=>window.libraryObservation.stats())).targets).toBe(0);
expect((await page.evaluate(()=>window.libraryObservation.stats())).pending).toBe(0);
expect((await page.evaluate(()=>window.libraryObservation.stats())).unmounted).toBe(0);
} finally {if(breakpoint)await session.send('Debugger.removeBreakpoint',{breakpointId:breakpoint});if(session)await session.detach();}
});
+513
View File
@@ -0,0 +1,513 @@
import { writeFile } from 'node:fs/promises';
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
import { test, expect } from '../../tools/vendor/node_modules/@playwright/test/index.mjs';
test.use({ locale: 'en-US', timezoneId: 'UTC', reducedMotion: 'reduce' });
const workspace = '/prompt_manager/workspace';
const primary = ['images', 'library', 'tags', 'inspect'];
const tools = ['overview', 'system'];
async function noOverflow(page) {
expect(await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth)).toBeLessThanOrEqual(1);
}
async function groupedNavigation(page) {
for (const [group, routes] of [['primary', primary], ['tools', tools]]) {
const region = page.locator(`.workspace-nav-${group}`);
await expect(region).toHaveCount(1);
expect(await region.locator('[data-route]').evaluateAll(nodes => nodes.map(node => node.dataset.route))).toEqual(routes);
}
}
async function attachEvidence(page, testInfo, name, fullPage = true) {
await page.evaluate(async () => {
await document.fonts.ready;
for (const image of document.images) image.loading = 'eager';
await Promise.all([...document.images].map(image => image.decode().catch(() => {})));
});
const screenshotPath = testInfo.outputPath(`${name}.png`);
await page.screenshot({ path: screenshotPath, fullPage });
await testInfo.attach(name, { path: screenshotPath, contentType: 'image/png' });
const geometry = await page.evaluate(() => Object.fromEntries(['.sidebar', '.topbar', '#workspace-main', '.workspace-heading', 'h1', '.image-workspace', '.image-grid', '.image-card', '.image-details', '.prompt-block-heading', '.library-toolbar', '.library-grid', '.library-card', '.library-card-art', '.library-card-content'].map(selector => {
const node = document.querySelector(selector);
if (!node) return [selector, null];
const box = node.getBoundingClientRect(), style = getComputedStyle(node);
return [selector, { x: box.x, y: box.y, width: box.width, height: box.height, padding: style.padding, fontSize: style.fontSize }];
})));
const geometryPath = testInfo.outputPath(`${name}-geometry.json`);
await writeFile(geometryPath, JSON.stringify(geometry, null, 2));
await testInfo.attach(`${name}-geometry`, { path: geometryPath, contentType: 'application/json' });
}
test.beforeEach(async ({ page, request, browserName }) => {
await startCoverage(page, browserName);
await expect(await request.post('/__test__/reset')).toBeOK();
});
test.afterEach(async ({ page, browserName }) => { await saveCoverage(page, browserName); });
test('visual fixture exposes real stable media and library records', async ({ request }) => {
expect((await request.post('/__test__/reset', { data: { workspace_visual: 'true' } })).status()).toBe(400);
for (const option of ['extra_images', 'include_video', 'prompt_inspector', 'native_library', 'extra_prompts', 'extra_variants']) {
expect((await request.post('/__test__/reset', { data: { workspace_visual: true, [option]: option.startsWith('extra') ? 1 : true } })).status()).toBe(400);
}
await expect(await request.post('/__test__/reset', { data: { workspace_visual: true } })).toBeOK();
const images = await (await request.get('/prompt_manager/images/output?limit=40')).json();
expect(images.total).toBe(24);
expect(new Set(images.images.map(image => image.root_index))).toEqual(new Set([0, 1]));
const image = images.images[0];
await expect(await request.get(image.url)).toBeOK();
const thumbnail = await request.get(image.thumbnail_url);
await expect(thumbnail).toBeOK();
expect(thumbnail.headers()['content-type']).toBe('image/png');
const inspection = await (await request.get(`/prompt_manager/images/inspect/${encodeURIComponent(image.path)}?root=${image.root_index}`)).json();
expect(inspection.success).toBe(true);
expect(inspection.image.path).toBe(image.path);
expect(inspection.prompts.positive.text).toContain('Amber geometry');
expect(inspection.prompts.negative.text).toBe('blurred edges, watermark');
expect(new Set(images.images.map(image => image.modified_time)).size).toBe(24);
const library = await (await request.get('/prompt_manager/library')).json();
expect(library.total).toBe(6);
expect(library.items.reduce((sum, item) => sum + item.variant_count, 0)).toBe(10);
const recipes = await Promise.all(library.items.map(async item => (await request.get(`/prompt_manager/library/${item.id}`)).json()));
expect(recipes.flatMap(recipe => recipe.variants).some(variant => variant.negative_text === '')).toBe(true);
const options = await (await request.get('/prompt_manager/library/options')).json();
expect(options.success).toBe(true);
await request.post('/__test__/reset', { data: { workspace_visual: true } });
const repeated = await (await request.get('/prompt_manager/images/output?limit=40')).json();
const identity = items => items.map(({root_index, path, modified_time}) => ({root_index, path, modified_time}));
expect(identity(repeated.images)).toEqual(identity(images.images));
await expect(await request.post('/__test__/reset')).toBeOK();
expect((await (await request.get('/prompt_manager/stats')).json()).stats.total_prompts).toBe(2);
});
test('shell matches approved stable geometry in both themes', async ({ page, request }, testInfo) => {
await request.post('/__test__/reset', { data: { workspace_visual: true } });
for (const [width, height] of [[1600, 1100], [390, 844]]) {
await page.setViewportSize({ width, height });
for (const route of ['images', 'library']) {
await page.goto(`${workspace}#/${route}`);
if (width === 1600) await expect(page.locator('.sidebar')).toHaveCSS('width', '218px');
await expect(page.locator('.workspace-heading > .workspace-heading-copy > h1')).toBeVisible();
await groupedNavigation(page);
await expect(page.locator(route === 'images' ? 'article[data-image-key]' : 'article[data-prompt-id]').first()).toBeVisible();
await expect(page.locator('.brand')).toHaveAttribute('href', '#/images');
await expect(page.locator('#workspace-main > .eyebrow')).toHaveCount(0);
for (const [theme, active] of [['dark', 'rgb(20, 54, 77)'], ['light', 'rgb(228, 241, 251)']]) {
await page.getByRole('combobox', { name: 'Appearance', exact: true }).selectOption(theme);
await expect(page.locator('nav [aria-current="page"]')).toHaveCSS('background-color', active);
await expect(page.locator('h1')).toHaveCSS('font-weight', '620');
await expect(page.locator('h1')).toHaveCSS('letter-spacing', '-0.7px');
await expect(page.locator('.workspace-heading')).toHaveCSS('margin-block-end', '22px');
await expect(page.locator('h1')).toHaveCSS('font-size', width === 1600 ? '28px' : '25px');
await expect(page.locator('.workspace-heading-copy > .intro')).toHaveCSS('line-height', '18px');
await expect(page.locator('#workspace-main')).toHaveCSS('padding-inline-start', width === 1600 ? '30px' : '14px');
if (width === 1600) {
await expect(page.locator('.sidebar')).toHaveCSS('width', '218px');
await expect(page.locator('.topbar')).toHaveCSS('height', '68px');
} else {
await expect(page.locator('.sidebar')).toHaveCSS('position', 'static');
expect(await page.locator('.workspace-shell').evaluate(node => getComputedStyle(node).gridTemplateColumns.split(' ').length)).toBe(1);
}
await noOverflow(page);
await attachEvidence(page, testInfo, `${route}-${width}-${theme}`);
}
}
}
});
test('long content and zoom keep grouped navigation reachable', async ({ page, request }) => {
await request.post('/__test__/reset', { data: { workspace_visual: true } });
await page.setViewportSize({ width: 1600, height: 1100 });
await page.goto(`${workspace}#/library`);
await expect(page.locator('article[data-prompt-id]')).toHaveCount(6);
await page.evaluate(() => { document.documentElement.style.zoom = '2'; });
await groupedNavigation(page);
for (const route of [...primary, ...tools]) {
const link = page.locator(`nav [data-route="${route}"]`);
await link.focus(); await expect(link).toBeFocused();
}
await page.getByRole('combobox', { name: 'Appearance', exact: true }).focus();
await expect(page.getByRole('combobox', { name: 'Appearance', exact: true })).toBeFocused();
const text = page.locator('.prompt-text').filter({ hasText: 'A study in very long creative context' });
await text.scrollIntoViewIfNeeded();
expect((await text.textContent()).length).toBeGreaterThan(1500);
await text.focus(); await expect(text).toBeFocused();
expect(await text.evaluate(node => {
const scroller = node.closest('.library-card-prompts');
return scroller.scrollHeight <= scroller.clientHeight + 1 && node.scrollHeight <= node.clientHeight + 1;
})).toBe(true);
await noOverflow(page);
await page.evaluate(() => { document.documentElement.style.zoom = ''; });
for (const width of [1251, 1250, 951, 950, 780, 700]) {
await page.setViewportSize({ width, height: 1100 });
await expect(page.locator('.sidebar')).toHaveCSS('position', width > 950 ? 'sticky' : 'static');
if (width > 950) await expect(page.locator('.sidebar')).toHaveCSS('width', width > 1250 ? '218px' : '185px');
await expect(page.locator('#workspace-main')).toHaveCSS('padding-inline-start', width > 1250 ? '30px' : width > 700 ? '24px' : '14px');
await noOverflow(page);
}
});
test('Appearance label and control fit the narrow shell at 200 percent zoom', async ({ page, request }, testInfo) => {
await request.post('/__test__/reset', { data: { workspace_visual: true } });
await page.setViewportSize({ width: 390, height: 844 });
await page.goto(`${workspace}#/images`);
await expect(page.locator('article[data-image-key]')).toHaveCount(24);
await page.evaluate(() => { document.documentElement.style.zoom = '2'; });
const preference = page.getByRole('combobox', { name: 'Appearance', exact: true });
const bounds = await preference.evaluate(select => {
const field = select.closest('label');
return { intendedWrapper: field.classList.contains('workspace-appearance'),
boxes: [field, field.querySelector('.ca-field-label'), select].map(node => {
const box = node.getBoundingClientRect(); return { left: box.left, right: box.right, width: box.width };
}), width: document.documentElement.clientWidth };
});
for (const box of bounds.boxes) {
expect(box.width).toBeGreaterThan(0);
expect(box.left).toBeGreaterThanOrEqual(-1);
expect(box.right).toBeLessThanOrEqual(bounds.width + 1);
}
expect(bounds.intendedWrapper).toBe(true);
for (const theme of ['follow', 'light', 'dark']) {
await preference.selectOption(theme); await expect(preference).toHaveValue(theme);
}
await preference.focus(); await expect(preference).toBeFocused();
await noOverflow(page);
await attachEvidence(page, testInfo, 'zoom-shell-390', false);
});
async function containedImageContent(page) {
return page.locator('article[data-image-key]').evaluateAll(nodes => {
const failures = [];
for (const card of nodes) {
const outer = card.getBoundingClientRect();
for (const selector of ['.image-card-footer', 'strong', 'small', '.image-card-footer button']) {
const node = card.querySelector(selector), box = node.getBoundingClientRect();
if (box.width <= 0 || box.height <= 0 || box.left < outer.left - 1 || box.right > outer.right + 1 ||
box.top < outer.top - 1 || box.bottom > outer.bottom + 1 ||
(selector === 'small' && node.scrollHeight > node.clientHeight + 1)) {
failures.push({ key: card.dataset.imageKey, selector,
card: { left: outer.left, right: outer.right, top: outer.top, bottom: outer.bottom },
content: { left: box.left, right: box.right, top: box.top, bottom: box.bottom } });
}
}
const action = card.querySelector('.image-card-footer button').getBoundingClientRect();
const range = document.createRange(); range.selectNodeContents(card.querySelector('small'));
for (const text of range.getClientRects()) {
if (Math.min(text.right, action.right) - Math.max(text.left, action.left) > .5 &&
Math.min(text.bottom, action.bottom) - Math.max(text.top, action.top) > .5) {
failures.push({ key: card.dataset.imageKey, selector: 'facts/action overlap',
text: { left: text.left, right: text.right, top: text.top, bottom: text.bottom },
action: { left: action.left, right: action.right, top: action.top, bottom: action.bottom } });
}
}
}
return failures;
});
}
for (const [width, height] of [[390, 844], [1600, 1100]]) for (const layout of ['Grid', 'List', 'Masonry']) {
test(`${layout} contains real card text and keyboard actions at ${width}px with 200 percent zoom`, async ({ page, request }, testInfo) => {
await request.post('/__test__/reset', { data: { workspace_visual: true } });
await page.setViewportSize({ width, height }); await page.goto(`${workspace}#/images`);
const cards = page.locator('article[data-image-key]');
await expect(cards).toHaveCount(24);
await page.getByRole('button', { name: layout, exact: true }).click();
const firstKey = await cards.first().getAttribute('data-image-key');
for (const zoom of [1, 2]) {
await page.evaluate(zoom => { document.documentElement.style.zoom = String(zoom); }, zoom);
for (const density of ['comfortable', 'large', 'compact']) {
await page.getByRole('combobox', { name: 'Thumbnail size', exact: true }).selectOption(density);
await expect.poll(() => containedImageContent(page)).toEqual([]);
await orderedMedia(page);
const columns = await cards.evaluateAll(nodes => {
const top = nodes[0].getBoundingClientRect().top;
return nodes.filter(node => Math.abs(node.getBoundingClientRect().top - top) < 1).length;
});
if (zoom === 1) expect(columns).toBe(layout === 'List' ? 1 : width === 390 || density === 'large' ? 2 : density === 'compact' ? 4 : 3);
else expect(columns).toBe(layout === 'List' || width === 390 ? 1 : density === 'large' ? 2 : density === 'compact' ? 4 : 3);
if (zoom === 1 && layout === 'List') await expect(cards.first()).toHaveCSS('height', '97px');
await cards.first().locator('.image-open').focus(); await page.keyboard.press('ArrowDown');
await expect(cards.nth(columns).locator('.image-open')).toBeFocused();
await page.keyboard.press('ArrowUp'); await expect(cards.first().locator('.image-open')).toBeFocused();
expect(await cards.first().getAttribute('data-image-key')).toBe(firstKey);
}
const longCard = cards.filter({ hasText: 'a-very-long-geometric-composition-' });
const filename = await longCard.locator('strong').textContent();
expect(filename).toMatch(/layered-context-.*\.png/);
await longCard.locator('.image-open').focus(); await page.keyboard.press('Enter');
await expect(page.locator('.image-details h2')).toHaveText(filename);
const fullPreview = page.getByRole('button', { name: 'Open full preview', exact: true });
await fullPreview.focus(); await expect(fullPreview).toBeFocused(); await page.keyboard.press('Enter');
await expect(page.getByRole('dialog', { name: 'Image preview', exact: true })).toBeVisible();
await expect(page.locator('.image-preview > header h2')).toHaveText(filename);
await page.keyboard.press('Escape');
await longCard.locator('.image-open').focus(); await page.keyboard.press('Tab');
await expect(longCard.getByRole('button', { name: `Preview ${filename}`, exact: true })).toBeFocused();
await page.keyboard.press('Enter'); await expect(page.locator('dialog[open]')).toHaveCount(1);
await page.keyboard.press('Escape');
await expect.poll(() => containedImageContent(page)).toEqual([]);
await orderedMedia(page);
await page.evaluate(() => scrollTo(0, 0));
await attachEvidence(page, testInfo, `zoom-${layout.toLowerCase()}-${width}-${zoom}`, false);
}
});
}
test('zoomed virtual Images keeps the visible real media mounted during native scrolling', async ({ page, request }) => {
await page.addInitScript(() => { window.IntersectionObserver = undefined; });
await request.post('/__test__/reset', { data: { extra_images: 200 } });
await page.setViewportSize({ width: 390, height: 844 }); await page.goto(`${workspace}#/images`);
const cards = page.locator('article[data-image-key]');
await expect(cards).toHaveCount(40);
await page.evaluate(() => { document.documentElement.style.zoom = '2'; });
await expect.poll(() => cards.nth(1).evaluate(node => node.offsetLeft)).toBe(0);
const stride = await cards.first().evaluate(node => node.getBoundingClientRect().height + 26);
const more = page.getByRole('button', { name: 'Load more images', exact: true });
for (const loaded of [80, 120, 160, 200, 202]) {
await more.click(); await expect(page.locator('.image-toolbar')).toContainText(`${loaded} of 202 images`);
}
await expect.poll(() => cards.count()).toBeLessThan(120);
await page.evaluate(stride => {
const grid = document.querySelector('.image-grid');
scrollTo(0, grid.getBoundingClientRect().top + scrollY + stride * 100 - 120);
}, stride);
await expect(page.locator('article[data-index="100"]')).toBeVisible();
await expect(page.locator('article[data-index="101"]')).toHaveCount(1);
const visible = page.locator('article[data-index="100"]');
await visible.locator('.image-open').focus(); await page.keyboard.press('ArrowDown');
await expect(page.locator('article[data-index="101"] .image-open')).toBeFocused();
await page.keyboard.press('ArrowUp'); await expect(visible.locator('.image-open')).toBeFocused();
await expect(visible).toBeInViewport();
await expect.poll(() => containedImageContent(page)).toEqual([]);
await orderedMedia(page);
await expect.poll(() => cards.count()).toBeLessThan(120);
});
test('supplemental extreme zoom grows real footers preserves the visible anchor and resets reservations', async ({ page, request }) => {
await request.post('/__test__/reset', { data: { workspace_visual: true } });
await page.setViewportSize({ width: 390, height: 844 }); await page.goto(`${workspace}#/images`);
const cards = page.locator('article[data-image-key]'), grid = page.locator('.image-grid');
await expect(cards).toHaveCount(24);
await page.evaluate(() => { document.documentElement.style.zoom = '2'; });
await expect.poll(() => cards.nth(1).evaluate(node => node.offsetLeft)).toBe(0);
const selected = cards.nth(16), key = await selected.getAttribute('data-image-key');
await selected.locator('.image-open').click(); await selected.locator('.image-open').focus();
const filename = await selected.locator('strong').textContent();
await selected.evaluate(node => scrollBy(0, node.getBoundingClientRect().top - 120));
await page.evaluate(() => {
const grid = document.querySelector('.image-grid'), footers = [...grid.querySelectorAll('.image-card-footer')];
const nativeHeight = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetHeight').get;
const descriptors = footers.map(node => [node, Object.getOwnPropertyDescriptor(node, 'offsetHeight')]);
const restore = () => { for (const [node, descriptor] of descriptors) {
if (descriptor) Object.defineProperty(node, 'offsetHeight', descriptor); else delete node.offsetHeight;
} };
window.footerMeasurementProbe = { before: null, restore };
for (const footer of footers) Object.defineProperty(footer, 'offsetHeight', { configurable: true, get() {
const height = nativeHeight.call(this);
if (document.documentElement.style.zoom === '4' && grid.style.getPropertyValue('--image-footer-height') === '54px' &&
Math.abs(Number.parseFloat(this.closest('.image-card').style.width) - Number.parseFloat(getComputedStyle(grid).width)) < .01) {
const top = visualViewport?.offsetTop || 0, bottom = top + (visualViewport?.height || innerHeight);
const first = [...grid.children].find(node => { const box = node.getBoundingClientRect(); return box.bottom > top && box.top < bottom; });
window.footerMeasurementProbe.before = first ? { index: Number(first.dataset.index), key: first.dataset.imageKey,
top: first.getBoundingClientRect().top - top } : null;
restore();
}
return height;
} });
document.documentElement.style.zoom = '4';
const box = grid.getBoundingClientRect();
// The approved initial reservation is 54px with 4:3 media and a 13px row gap.
const stride = (box.width / 4 - 2) * .75 + 54 + 2 + 13;
// Place row eight inside the 52px scaled gap so the preceding row is not visible.
const index = 8;
scrollTo(0, box.top + scrollY + index * stride * 4 - 16);
});
try {
await expect.poll(() => page.evaluate(() => window.footerMeasurementProbe.before?.index)).toBe(8);
const anchor = await page.evaluate(() => window.footerMeasurementProbe.before);
await expect.poll(() => grid.evaluate(node => Number.parseFloat(node.style.getPropertyValue('--image-footer-height')))).toBeGreaterThan(54);
await expect.poll(() => containedImageContent(page)).toEqual([]);
const visibleAnchor = page.locator(`article[data-index="${anchor.index}"]`);
const anchorTop = await visibleAnchor.evaluate(node => node.getBoundingClientRect().top - (visualViewport?.offsetTop || 0));
expect(Math.abs(anchorTop - anchor.top)).toBeLessThanOrEqual(2);
await expect(page.locator(`article[data-image-key="${key}"]`)).toHaveClass(/selected/);
await expect(selected.locator('.image-open')).toBeFocused();
await expect(page.locator('.image-details h2')).toHaveText(filename);
const mutations = await grid.evaluate(async node => {
let changes = 0;
const observer = new MutationObserver(records => { changes += records.length; });
observer.observe(node, { subtree: true, attributes: true, attributeFilter: ['style'] });
for (let frame = 0; frame < 6; frame++) await new Promise(requestAnimationFrame);
observer.disconnect(); return changes;
});
expect(mutations).toBe(0);
await page.getByRole('button', { name: 'List', exact: true }).click();
await expect.poll(() => containedImageContent(page)).toEqual([]);
expect(await cards.first().evaluate(node => node.offsetHeight)).toBeGreaterThan(97);
await page.getByRole('searchbox', { name: 'Search filenames', exact: true }).fill('no-real-media-match');
await expect(cards).toHaveCount(0);
expect(await grid.evaluate(node => Number.parseFloat(node.style.getPropertyValue('--image-footer-height')))).toBe(54);
await page.getByRole('searchbox', { name: 'Search filenames', exact: true }).fill('');
await expect(cards).toHaveCount(24);
await expect.poll(() => grid.evaluate(node => Number.parseFloat(node.style.getPropertyValue('--image-footer-height')))).toBeGreaterThan(54);
const extremeFooter = await grid.evaluate(node => Number.parseFloat(node.style.getPropertyValue('--image-footer-height')));
await page.evaluate(() => { document.documentElement.style.zoom = '2'; });
await expect.poll(() => grid.evaluate(node => Number.parseFloat(node.style.getPropertyValue('--image-footer-height')))).toBeLessThan(extremeFooter);
await expect(cards.first()).toHaveCSS('height', '97px');
await expect.poll(() => containedImageContent(page)).toEqual([]);
await page.getByRole('button', { name: 'Grid', exact: true }).click();
await expect.poll(() => grid.evaluate(node => Number.parseFloat(node.style.getPropertyValue('--image-footer-height')))).toBe(54);
await orderedMedia(page);
} finally { await page.evaluate(() => {
window.footerMeasurementProbe?.restore(); delete window.footerMeasurementProbe;
}); }
});
test('supplemental wrapped real footer reservation survives append without moving the visible card', async ({ page, request }) => {
await page.addInitScript(() => { window.IntersectionObserver = undefined; });
await request.post('/__test__/reset', { data: { extra_images: 200 } });
await page.setViewportSize({ width: 390, height: 844 }); await page.goto(`${workspace}#/images`);
const cards = page.locator('article[data-image-key]'), grid = page.locator('.image-grid');
await expect(cards).toHaveCount(40);
await cards.first().locator('.image-open').click();
const selectedKey = await cards.first().getAttribute('data-image-key');
await page.evaluate(() => { document.documentElement.style.zoom = '4'; });
await expect.poll(() => grid.evaluate(node => Number.parseFloat(node.style.getPropertyValue('--image-footer-height')))).toBeGreaterThan(54);
let release, pending = false;
const held = new Promise(resolve => { release = resolve; });
await page.route('**/images/output?**', async route => {
if (new URL(route.request().url()).searchParams.has('cursor')) { pending = true; await held; }
await route.continue();
});
try {
const more = page.getByRole('button', { name: 'Load more images', exact: true });
await more.click(); await expect.poll(() => pending).toBe(true);
const anchor = await cards.evaluateAll(nodes => {
const top = visualViewport?.offsetTop || 0, bottom = top + (visualViewport?.height || innerHeight);
const node = nodes.find(node => { const box = node.getBoundingClientRect(); return box.bottom > top && box.top < bottom; });
return node ? { key: node.dataset.imageKey, top: node.getBoundingClientRect().top - top } : null;
});
expect(anchor).not.toBeNull();
release(); await expect(page.locator('.image-toolbar')).toContainText('80 of 202 images');
await expect(cards).toHaveCount(80);
await expect.poll(async () => Math.abs(await page.locator(`article[data-image-key="${anchor.key}"]`).evaluate(node => node.getBoundingClientRect().top - (visualViewport?.offsetTop || 0)) - anchor.top)).toBeLessThanOrEqual(1);
await expect(page.locator(`article[data-image-key="${selectedKey}"]`)).toHaveClass(/selected/);
await expect(more).toBeFocused();
await expect.poll(() => containedImageContent(page)).toEqual([]);
} finally { release(); }
});
test('Library visual evidence keeps natural cards and returns from real history in both themes',async({browser,browserName,request},testInfo)=>{
await request.post('/__test__/reset',{data:{workspace_visual:true}});
for(const [width,height] of [[1600,1100],[390,844]]) for(const theme of ['dark','light']) {
const context=await browser.newContext({viewport:{width,height},locale:'en-US',timezoneId:'UTC',reducedMotion:'reduce'});
const page=await context.newPage();const errors=[];page.on('pageerror',error=>errors.push(error.message));await startCoverage(page,browserName);
try {
await page.goto(`${workspace}#/library`);await expect(page.locator('article[data-prompt-id]')).toHaveCount(6);
await page.getByRole('combobox',{name:'Appearance',exact:true}).selectOption(theme);
await attachEvidence(page,testInfo,`after-library-${width}-${theme}`,false);
await noOverflow(page);
await page.getByRole('link',{name:'Explore history',exact:true}).first().click();
await expect(page.getByRole('region',{name:'Prompt history',exact:true})).toBeVisible();
await expect(page.locator('.library-history > div > .intro')).toHaveCount(1);
await page.getByRole('link',{name:'Back to library',exact:true}).click();
await expect(page.locator('article[data-prompt-id]')).toHaveCount(6);
await expect(page.locator('.workspace-heading-copy > .intro')).toHaveCount(1);
expect(errors).toEqual([]);
} finally {await saveCoverage(page,browserName);await context.close();}
}
});
test('approved icons are decorative safe SVGs and reject unknown vocabulary', async ({ page }) => {
await page.goto(`${workspace}#/images`);
const icons = await page.evaluate(async () => {
const { createWorkspaceIcon } = await import('/prompt_manager/js/workspace/icons.mjs');
const names = ['images', 'library', 'tags', 'upload', 'overview', 'settings', 'grid', 'list', 'masonry', 'search', 'info', 'copy', 'branch'];
const otherDocument = document.implementation.createHTMLDocument();
const rendered = names.map(name => {
const icon = createWorkspaceIcon(name, otherDocument);
return { name, svg: icon instanceof SVGSVGElement, owner: icon.ownerDocument === otherDocument,
viewBox: icon.getAttribute('viewBox'), hidden: icon.getAttribute('aria-hidden'), focusable: icon.getAttribute('focusable'),
fill: icon.getAttribute('fill'), stroke: icon.getAttribute('stroke'), width: icon.getAttribute('stroke-width'),
path: icon.querySelector('path').getAttribute('d'), children: icon.childElementCount };
});
const unknown = ['missing', '__proto__', '', null, 1].map(name => {
try { createWorkspaceIcon(name); return false; } catch (error) { return error instanceof TypeError; }
});
return { rendered, unknown };
});
expect(icons.unknown).toEqual([true, true, true, true, true]);
for (const icon of icons.rendered) {
expect(icon).toMatchObject({ svg: true, owner: true, viewBox: '0 0 24 24', hidden: 'true', focusable: 'false', fill: 'none', stroke: 'currentColor', width: '1.65', children: 1 });
expect(icon.path.length).toBeGreaterThan(10);
}
expect(icons.rendered.find(icon => icon.name === 'overview').path).toBe('M3 12h4l3-8 4 16 3-8h4');
});
async function orderedMedia(page) {
const boxes=await page.locator('article[data-image-key]').evaluateAll(nodes=>nodes.map(node=>{
const box=node.getBoundingClientRect();return {x:box.x,y:box.y,right:box.right,bottom:box.bottom};
}));
for (let index=0;index<boxes.length;index++) for (const other of boxes.slice(index+1)) {
const box=boxes[index];
expect(box.right<=other.x+1||other.right<=box.x+1||box.bottom<=other.y+1||other.bottom<=box.y+1).toBe(true);
}
await noOverflow(page);
}
test('Images visual layouts retain real delayed media long filenames and loaded scroll',async({page,request},testInfo)=>{
await request.post('/__test__/reset',{data:{workspace_visual:true}});
let release, mediaRequests=0;const held=new Promise(resolve=>{release=resolve;});
await page.route('**/images/serve/**',async route=>{mediaRequests++;await held;await route.continue().catch(()=>{});});
try {
await page.setViewportSize({width:1600,height:1100});await page.goto(`${workspace}#/images`,{waitUntil:'domcontentloaded'});
await expect(page.locator('article[data-image-key]')).toHaveCount(24);
await expect.poll(()=>mediaRequests).toBeGreaterThan(0);
expect(await page.locator('.image-card img').first().evaluate(image=>image.complete)).toBe(false);
await expect(page.locator('.image-card').first()).toHaveCSS('border-radius','7px');
await orderedMedia(page);
} finally {release();}
for (const [width,height] of [[1600,1100],[390,844]]) {
await page.setViewportSize({width,height});
for (const theme of ['dark','light']) {
await page.getByRole('combobox',{name:'Appearance',exact:true}).selectOption(theme);
await page.locator('.image-card .image-open').first().click();
await expect(page.locator('.image-details h2')).toHaveText('study-01.png');
for (const layout of ['Grid','List','Masonry']) {
await page.getByRole('button',{name:layout,exact:true}).click();await page.evaluate(()=>scrollTo(0,0));
if(layout==='List') await expect(page.locator('.image-card').first()).toHaveCSS('height','97px');
await orderedMedia(page);
await attachEvidence(page,testInfo,`after-images-${layout.toLowerCase()}-${width}-${theme}`,false);
}
await page.locator('article[data-image-key]').last().scrollIntoViewIfNeeded();
const longCard=page.locator('article[data-image-key]').filter({hasText:'a-very-long-geometric-composition-'});
await expect(longCard.locator('strong')).toHaveText(/layered-context-.*\.png/);
await longCard.locator('.image-open').click();
await expect(page.locator('.image-details h2')).toHaveText(await longCard.locator('strong').textContent());
await orderedMedia(page);
await attachEvidence(page,testInfo,`after-images-loaded-scroll-${width}-${theme}`,false);
}
}
await page.evaluate(()=>{location.hash='#/overview';});
await expect(page.locator('.image-card,.image-details,.viewer-container,dialog[open]')).toHaveCount(0);
});
test('embedded history gallery keeps the history heading and disposes its layouts',async({page,request},testInfo)=>{
await request.post('/__test__/reset',{data:{workspace_visual:true}});
for (const width of [1600,390]) {
await page.setViewportSize({width,height:width===1600?1100:844});await page.goto(`${workspace}#/library`);
await page.getByRole('link',{name:'Explore history',exact:true}).first().click();
await expect(page.getByRole('region',{name:'Prompt history',exact:true})).toBeVisible();
await expect(page.locator('h1')).not.toHaveText('Prompt library');
const title=await page.locator('h1').textContent();expect(title).not.toBe('Images');
await expect(page.locator('article[data-image-key]').first()).toBeVisible();
for (const layout of ['List','Masonry','Grid']) {
await page.getByRole('button',{name:layout,exact:true}).click();await orderedMedia(page);
await expect(page.locator('h1')).toHaveText(title);
await expect(page.locator('.workspace-heading-copy > .intro')).toHaveCount(0);
}
await attachEvidence(page,testInfo,`after-images-embedded-history-${width}`,false);
await page.getByRole('link',{name:'Back to library',exact:true}).click();
await expect(page.locator('.image-card,.image-details,dialog[open]')).toHaveCount(0);
}
});
+22
View File
@@ -13,6 +13,17 @@ const routes = [
['system', 'System', '/prompt_manager/admin'],
];
async function countAppearanceWrites(page) {
await page.evaluate(() => {
window.__appearanceChanges = 0;
const original = Storage.prototype.setItem;
Storage.prototype.setItem = function (...args) {
if (args[0] === 'pm_workspace_theme') window.__appearanceChanges++;
return original.apply(this, args);
};
});
}
test.beforeEach(async ({ page, request, browserName }) => {
await startCoverage(page, browserName);
await expect(await request.post('/__test__/reset')).toBeOK();
@@ -191,7 +202,13 @@ test('leaving a loading overview prevents its delayed result from replacing the
await finished;
await expect(page.locator('#workspace-main h1')).toHaveText('Images');
await expect(page.locator('#workspace-main')).not.toContainText('999');
await expect(page.locator('.workspace-nav-primary')).toHaveCount(1);
await expect(page.locator('.workspace-nav-tools')).toHaveCount(1);
await expect(page.getByRole('combobox', { name: 'Appearance', exact: true })).toHaveCount(1);
await expect(page.locator('#workspace-main a[href="/prompt_manager/gallery"]')).toBeVisible();
await countAppearanceWrites(page);
await page.getByRole('combobox', { name: 'Appearance', exact: true }).selectOption('light');
expect(await page.evaluate(() => window.__appearanceChanges)).toBe(1);
});
test('cached-page restoration remounts one working shell and refreshes its data', async ({ page }) => {
@@ -211,8 +228,13 @@ test('cached-page restoration remounts one working shell and refreshes its data'
expect(reads).toBe(3);
const navigation = page.getByRole('navigation', { name: 'Workspace', exact: true });
await expect(navigation.getByRole('link')).toHaveCount(routes.length);
await expect(page.locator('.workspace-nav-primary')).toHaveCount(1);
await expect(page.locator('.workspace-nav-tools')).toHaveCount(1);
await expect(page.getByRole('combobox', { name: 'Appearance', exact: true })).toHaveCount(1);
await countAppearanceWrites(page);
await navigation.getByRole('link', { name: 'Images', exact: true }).click();
await expect(page.locator('#workspace-main h1')).toHaveText('Images');
await page.getByRole('combobox', { name: 'Appearance' }).selectOption('light');
await expect(page.locator('body')).toHaveAttribute('data-ca-theme', 'light');
expect(await page.evaluate(() => window.__appearanceChanges)).toBe(1);
});
+161
View File
@@ -0,0 +1,161 @@
"""Deterministic original artwork and saved prompts for workspace visual checks."""
from __future__ import annotations
import json
import os
from pathlib import Path
import shutil
from typing import TYPE_CHECKING
from PIL import Image, ImageDraw
from PIL.PngImagePlugin import PngInfo
from utils.hashing import generate_prompt_hash
if TYPE_CHECKING:
from py.api import PromptManagerAPI
_POSITIVES = (
(
"Amber geometry\nLayered sandstone arches, warm afternoon light, "
"precise silhouettes."
),
(
"Tidal observatory\nCobalt circles over a quiet sea, "
"a pale horizon and measured reflections."
),
(
"Forest atlas\nOverlapping emerald triangles, paper textures "
"and a soft misty background."
),
(
"Rose pavilion\nCoral blocks and floating windows, "
"balanced shadows on a terracotta plaza."
),
"Violet orbit\nConcentric rings, lavender haze and a tiny silver moon.",
"A study in very long creative context\n"
+ "Preserve every geometric detail, layered color relationship and quiet edge. "
* 18
+ "unbroken-"
+ "context" * 40,
)
_NEGATIVES = (
("blurred edges, watermark", "flat lighting, clipped highlights", ""),
("low contrast, noise", "distorted horizon"),
("oversaturated foliage", "soft geometry"),
("unbalanced composition",),
("banding, harsh gradients",),
("cropped details, illegible marks",),
)
def _write_art(path: Path, index: int, positive: str, negative: str) -> None:
sizes = ((720, 480), (480, 720), (560, 560), (900, 400))
palettes = (
("#252c46", "#e0a75e", "#b76445"),
("#153b57", "#64bfc6", "#dfdba8"),
("#1d4947", "#71ac83", "#d5d8aa"),
("#523547", "#ef9c87", "#bc6764"),
("#342b59", "#a79bd6", "#e5c0bf"),
("#303d4d", "#b1c4c5", "#d6a05f"),
)
width, height = sizes[index % len(sizes)]
background, accent, highlight = palettes[index // 4]
graph = {
"1": {"class_type": "CLIPTextEncode", "inputs": {"text": positive}},
"2": {"class_type": "CLIPTextEncode", "inputs": {"text": negative}},
"3": {
"class_type": "KSampler",
"inputs": {"positive": ["1", 0], "negative": ["2", 0]},
},
"4": {"class_type": "SaveImage", "inputs": {"images": ["3", 0]}},
}
info = PngInfo()
info.add_text("prompt", json.dumps(graph))
path.parent.mkdir(parents=True, exist_ok=True)
with Image.new("RGB", (width, height), background) as image:
draw = ImageDraw.Draw(image)
draw.rectangle((0, height * 3 // 4, width, height), fill=highlight)
radius = min(width, height) // 3
center_x, center_y = width // 2 + (index % 3 - 1) * 25, height // 2
draw.ellipse(
(
center_x - radius,
center_y - radius,
center_x + radius,
center_y + radius,
),
fill=accent,
)
draw.polygon(
(
(width // 8, height * 7 // 8),
(width // 2, height // 4),
(width * 7 // 8, height * 7 // 8),
),
outline=highlight,
width=8,
)
draw.line(
(width // 6, height // 3, width * 5 // 6, height // 3),
fill=highlight,
width=4,
)
image.save(path, pnginfo=info)
stamp = 1_760_000_000 - index * 60
os.utime(path, (stamp, stamp))
def seed_workspace_visual(api: PromptManagerAPI, root: Path) -> None:
"""Replace only the owned browser harness records and media roots."""
with api.db.model.get_connection() as conn:
for table in (
"image_prompt_pairs",
"prompt_pair_tags",
"prompt_pairs",
"generated_images",
"prompt_tags",
"tags",
"prompts",
):
conn.execute(f"DELETE FROM {table}")
for name in ("output", "input"):
shutil.rmtree(root / name)
(root / name).mkdir()
for parent_index, (positive, negatives) in enumerate(zip(_POSITIVES, _NEGATIVES)):
category = ("Architecture", "Landscape", "Abstract")[parent_index % 3]
tags = ["geometric", ("warm", "cool")[parent_index % 2]]
if parent_index == 5:
tags.append("long-context-" + "detail" * 28)
prompt_id = api.db.save_prompt(
positive,
category=category,
tags=tags,
prompt_hash=generate_prompt_hash(positive),
rating=parent_index if parent_index else None,
)
for variant_index, negative in enumerate(negatives):
api.db.save_prompt_pair(
positive,
negative,
title=f"Composition {variant_index + 1}",
category=category,
tags=tags,
)
for offset in range(4):
index = parent_index * 4 + offset
directory = ("output", "input")[offset % 2]
filename = f"study-{index + 1:02}.png"
if index == 23:
filename = (
"a-very-long-geometric-composition-"
+ "layered-context-" * 9
+ ".png"
)
path = root / directory / category.lower() / filename
_write_art(path, index, positive, negatives[offset % len(negatives)])
api.db.link_image_to_prompt(prompt_id, str(path))
api._generate_gallery_thumbnails_sync(api._get_all_output_dirs(), (150, 150))
api.invalidate_gallery_cache()
+58 -1
View File
@@ -75,6 +75,63 @@ test('binary-searched windows handle boundaries, empty collections and focus wit
test('reported maximum height keeps unusually tall custom layouts inside the virtual window',async()=>{
const {layoutImages,visibleImages}=await source;
const geometry=layoutImages([{}, {}, {}],10000,'grid',20000);
assert.equal(geometry.maxHeight,7572);
assert.equal(geometry.maxHeight,7554.5);
assert.deepEqual(visibleImages(geometry.positions,6000,200,-1,geometry.maxHeight),[0]);
});
test('approved workspace densities share viewport metrics and reject unknown values', async () => {
const {workspaceImageMetrics, layoutImages} = await source;
assert.equal(typeof workspaceImageMetrics, 'function', 'workspace density metrics must be exported');
for (const [width, expected] of [[1600,[3,2,4]], [1250,[2,2,3]], [950,[2,2,3]], [700,[2,2,2]], [390,[2,2,2]], [1700,[4,2,5]]]) {
assert.deepEqual(['comfortable','large','compact'].map(density => workspaceImageMetrics(width,density).columns), expected);
for (const density of ['comfortable','large','compact']) {
const metrics = workspaceImageMetrics(width,density);
assert.deepEqual(metrics, {columns: expected[['comfortable','large','compact'].indexOf(density)], gap:13, footerHeight:54, listHeight:97});
assert.equal(layoutImages([{},{}],990,'list',240,metrics).positions[1].x,0);
}
}
assert.throws(() => workspaceImageMetrics(1600,'unknown'), TypeError);
assert.deepEqual(workspaceImageMetrics(1600),workspaceImageMetrics(1600,'comfortable'));
});
test('approved grid uses inner media at four to three and explicit columns with thirteen pixel gaps', async () => {
const {workspaceImageMetrics,layoutImages} = await source;
assert.equal(typeof workspaceImageMetrics,'function');
const metrics = workspaceImageMetrics(1600);
const {positions} = layoutImages(Array(4).fill({}),990,'grid',240,metrics);
assert.equal(positions[1].x-positions[0].width,13);
assert.equal(positions[3].x,0);
assert.equal(positions[3].y-positions[0].height,13);
assert.equal(positions[0].height-54-2,(positions[0].width-2)*.75);
assert.equal(layoutImages([{}],990,'list',240,metrics).height,97);
const custom=layoutImages([{}],990,'grid',240,{columns:2,gap:20,footerHeight:60,listHeight:100});
assert.equal(custom.positions[0].width,485);
assert.equal(custom.height,(485-2)*.75+62);
assert.equal(layoutImages([{}],990,'list',240,{listHeight:100}).height,100);
});
test('masonry uses real finite proportions and falls back for invalid dimensions', async () => {
const {layoutImages}=await source;
const images=[{width:100,height:1000},{width:1000,height:100},{width:Infinity,height:10},{width:10,height:NaN}];
const {positions}=layoutImages(images,990,'masonry',240,{columns:3});
assert.equal(positions[0].height,(positions[0].width-2)*10+56);
assert.equal(positions[1].height,(positions[1].width-2)/10+56);
for (const position of positions) assert.ok(Number.isFinite(position.height));
});
test('gallery width limits density columns without changing ordinary workspace geometry', async () => {
const {workspaceImageMetrics, layoutImages} = await source;
for (const [viewport, width, density, columns] of [
[1600,990,'comfortable',3], [1600,990,'compact',4],
[951,428,'compact',3], [390,362,'comfortable',2],
[1600,190,'comfortable',1], [1600,190,'compact',1],
[390,167,'large',1], [390,167,'compact',1], [390,69.5,'comfortable',1], [390,0,'comfortable',1],
]) {
const metrics = workspaceImageMetrics(viewport,density,width);
assert.equal(metrics.columns,columns,`${viewport}/${width}/${density}`);
const {positions} = layoutImages(Array(8).fill({}),width,'grid',240,metrics);
assert.equal(positions[columns].x,0);
assert.ok(positions[columns].y > 0);
}
});
+56
View File
@@ -0,0 +1,56 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const source = import('../../web/js/workspace/library-layout.mjs');
test('natural Library rows use the tallest measured card and estimate only missing heights', async () => {
const {layoutLibraryRows} = await source;
const heights = Object.freeze([300, 470, 600, 250, null]);
const layout = layoutLibraryRows(heights, 2);
assert.deepEqual(layout.rows, [
{first: 0, last: 1, top: 0, height: 470},
{first: 2, last: 3, top: 488, height: 600},
{first: 4, last: 4, top: 1106, height: 468},
]);
assert.equal(layout.height, 1574);
assert.deepEqual(layoutLibraryRows([300, 470], 1), {
rows: [{first: 0, last: 0, top: 0, height: 300}, {first: 1, last: 1, top: 318, height: 470}], height: 788,
});
assert.deepEqual(layoutLibraryRows([], 2), {rows: [], height: 0});
});
test('row measurements validate geometry and invalid heights reserve the configured estimate', async () => {
const {layoutLibraryRows} = await source;
assert.deepEqual(layoutLibraryRows([0, -1, NaN, Infinity, undefined, '300'], 2, {estimate: 448, gap: 0}).rows.map(row => row.height), [448, 448, 448]);
for (const columns of [0, -1, 1.5, Infinity, NaN, '2']) assert.throws(() => layoutLibraryRows([], columns), TypeError);
for (const estimate of [0, -1, NaN, Infinity]) assert.throws(() => layoutLibraryRows([], 2, {estimate}), TypeError);
for (const gap of [-1, NaN, Infinity]) assert.throws(() => layoutLibraryRows([], 2, {gap}), TypeError);
const before = layoutLibraryRows([300, 470, 600], 2);
const appended = layoutLibraryRows([300, 470, 600, 250, 310], 2);
assert.deepEqual(appended.rows[0], before.rows[0]);
assert.deepEqual(appended.rows[1], {first: 2, last: 3, top: 488, height: 600});
assert.equal(appended.height, 1416);
});
test('measured windows add two overscan rows and pin distant focus in ascending DOM order', async () => {
const {layoutLibraryRows, visibleLibraryRows} = await source;
const {rows} = layoutLibraryRows(Array(40).fill(100), 2, {gap: 10});
for (const row of rows) Object.freeze(row);
Object.freeze(rows);
assert.deepEqual(visibleLibraryRows(rows, 550, 100, 0), [0, 3, 4, 5, 6, 7]);
assert.deepEqual(visibleLibraryRows(rows, 550, 100, 39), [3, 4, 5, 6, 7, 19]);
assert.deepEqual(visibleLibraryRows(rows, 550, 100, 40), [3, 4, 5, 6, 7]);
assert.deepEqual(visibleLibraryRows(rows, 550, 100, -1), [3, 4, 5, 6, 7]);
assert.deepEqual(visibleLibraryRows([], 0, 900), []);
assert.deepEqual(visibleLibraryRows(rows, NaN, Infinity), [0, 1, 2]);
});
test('measured-window lookup binary searches a 50000-row shelf without walking it', async () => {
const {visibleLibraryRows} = await source;
let reads = 0;
const rows = new Proxy({length: 50000}, {get(target, key) {
if (/^\d+$/.test(String(key))) { reads++; const index = Number(key); return {first: index * 2, last: index * 2 + 1, top: index * 118, height: 100}; }
return Reflect.get(target, key);
}});
assert.deepEqual(visibleLibraryRows(rows, 1180000, 100, 0), [0, 9998, 9999, 10000, 10001, 10002]);
assert.ok(reads < 500, `${reads} numeric row reads`);
});
+6
View File
@@ -42,6 +42,12 @@ test('parent shelf window bounds DOM and pins focused rows without changing logi
const {libraryWindow}=await source;const first=libraryWindow(500,2,0,900);assert.equal(first[0],0);assert.ok(first.length<24);
const middle=libraryWindow(500,2,50000,900,0);assert.equal(middle[0],0);assert.ok(middle.some(index=>index>150));assert.ok(middle.length<24);assert.deepEqual(middle,[...middle].sort((a,b)=>a-b));assert.deepEqual(libraryWindow(3,2,0,900),[0,1,2]);
});
test('uniform compatibility window handles huge counts without collection allocation',async()=>{
const {libraryWindow}=await source;const original=Array.from;const lengths=[];
Array.from=function(value,...args){lengths.push(value.length);assert.ok(!Number.isFinite(value.length)||value.length<32,'collection-sized allocation');return original.call(this,value,...args);};
try {const indexes=libraryWindow(Number.MAX_SAFE_INTEGER,2,50000,900,0);assert.ok(indexes.length<32);assert.ok(indexes.includes(0));assert.ok(indexes.includes(2*Math.floor(50000/578)));assert.deepEqual(indexes,[...new Set(indexes)].sort((a,b)=>a-b));assert.ok(lengths.every(length=>length<32));}
finally {Array.from=original;}
});
test('negative variants append continuously without losing selected identity, and failures retry same cursor',async()=>{
const {createLibraryDetail}=await source;const calls=[];let count=0;const v=id=>({id,negative_text:id===9?'':'bad',explicit_empty:id===9});
const loader=createLibraryDetail({api:{get:async url=>{calls.push(url);count++;if(count===2)throw Error('offline');return {positive:item(1),variants:count===1?[v(9)]:[v(9),v(10)],variant_total:2,variants_has_more:count===1,variants_next_cursor:count===1?'next':null,unassigned_image_count:0};}},onChange:()=>{}});
+70
View File
@@ -0,0 +1,70 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';
import { execFileSync } from 'node:child_process';
import { tmpdir } from 'node:os';
import { isAbsolute, join, relative, resolve, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
import workflowConfig from '../../tools/vendor/playwright.workflows.config.mjs';
const configUrl = new URL('../../tools/vendor/playwright.workflows.config.mjs', import.meta.url);
const runner = fileURLToPath(new URL('../../tools/vendor/node_modules/@playwright/test/cli.js', import.meta.url));
const testModule = new URL('../../tools/vendor/node_modules/@playwright/test/index.mjs', import.meta.url).href;
async function evidenceFiles(directory) {
const files = [];
for (const entry of await readdir(directory, { withFileTypes: true })) {
const path = join(directory, entry.name);
if (entry.isDirectory()) files.push(...await evidenceFiles(path));
else if (entry.name === 'evidence.json') files.push(path);
}
return files;
}
test('sequential workflow project runs retain all four project evidence sets', async t => {
const root = await mkdtemp(join(tmpdir(), 'pm-workflow-artifacts-'));
t.after(() => rm(root, { recursive: true, force: true }));
const uploadedAncestor = resolve(root, 'test-results/workflows');
const isolateOutput = value => {
assert.equal(typeof value, 'string');
assert.equal(isAbsolute(value), false, 'configured output must remain relative');
const output = resolve(root, value);
assert.ok(output.startsWith(root + sep), 'runner output must stay inside its owned temporary root');
const uploadedRelative = relative(uploadedAncestor, output);
assert.ok(uploadedRelative === '' || (!uploadedRelative.startsWith('..') && !isAbsolute(uploadedRelative)),
'project evidence must remain beneath the uploaded workflow ancestor');
return output;
};
// Validate every output before launching a runner that removes output directories.
const outputDir = isolateOutput(workflowConfig.outputDir);
const projects = workflowConfig.projects.map(project => ({
...project, outputDir: isolateOutput(project.outputDir ?? workflowConfig.outputDir),
}));
const testDir = join(root, 'specs');
await mkdir(testDir);
await writeFile(join(testDir, 'evidence-retention.spec.mjs'), `
import { test } from ${JSON.stringify(testModule)};
import { writeFile } from 'node:fs/promises';
test('writes project evidence without a browser or host', async ({}, testInfo) => {
await writeFile(testInfo.outputPath('evidence.json'), JSON.stringify({ project: testInfo.project.name }));
});
`);
const configPath = join(root, 'playwright.config.mjs');
await writeFile(configPath, `
import config from ${JSON.stringify(configUrl.href)};
export default { ...config, testDir: ${JSON.stringify(testDir)}, webServer: undefined,
outputDir: ${JSON.stringify(outputDir)}, projects: ${JSON.stringify(projects)} };
`);
const run = names => execFileSync(process.execPath, [runner, 'test', '--config', configPath,
...names.flatMap(name => ['--project', name])], {
cwd: root, encoding: 'utf8', timeout: 30_000,
env: { ...process.env, PM_JS_COVERAGE: '', NODE_V8_COVERAGE: '' },
});
assert.match(run(['chromium', 'touch']), /2 passed/);
const first = new Map(await Promise.all((await evidenceFiles(uploadedAncestor)).map(async path => [path, await readFile(path, 'utf8')])));
assert.deepEqual([...first.values()].map(value => JSON.parse(value).project).sort(), ['chromium', 'touch']);
assert.match(run(['firefox', 'webkit']), /2 passed/);
const retained = new Map(await Promise.all((await evidenceFiles(uploadedAncestor)).map(async path => [path, await readFile(path, 'utf8')])));
assert.deepEqual([...retained.values()].map(value => JSON.parse(value).project).sort(), ['chromium', 'firefox', 'touch', 'webkit']);
for (const [path, contents] of first) assert.equal(retained.get(path), contents, 'later runs preserve earlier evidence bytes and paths');
});