Merge remote-tracking branch 'origin/main' into fix/test-reset-stall
This commit is contained in:
@@ -78,6 +78,17 @@ export async function seedConcept(request,data={}) {
|
||||
return response.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* Seed the concept fixture and fix the browser's clock at the fixture's own instant (`manifest.now`), so the page and
|
||||
* the fixture read one "now": a prompt used now reads "Used today" and the caption names the fixture's day even when
|
||||
* the run crosses midnight between seeding and rendering. Timers keep running; only `Date` stands still.
|
||||
*/
|
||||
export async function seedConceptAt(page,request,data={}) {
|
||||
const manifest=await seedConcept(request,data);
|
||||
await page.clock.setFixedTime(new Date(manifest.now*1000));
|
||||
return manifest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save `tags` as the current image tag set of the listed file at `path` (root 0) through the real observe and tag
|
||||
* routes (#249 PR C), releasing the capture afterwards; returns the receipt's saved names.
|
||||
|
||||
@@ -237,9 +237,12 @@ const viewerStructure=details=>details.evaluate(node=>{
|
||||
test('viewer details hold provenance, raw records and downloads',async({page,request})=>{
|
||||
await page.setViewportSize({width:1600,height:1100});const reads=await patchInspection(page);
|
||||
await fullFixture(page,request);let details=await viewerDetails(page,'complete.png');
|
||||
// The panel content without the cover, then the two disclosures, then the pair send and history buttons (D20).
|
||||
// The panel content without the cover, D117's Copy settings summary after the facts, then the two disclosures,
|
||||
// then the pair send and history buttons (D20).
|
||||
expect(await viewerStructure(details)).toEqual({outer:['div','button.send','button'],
|
||||
inner:['div.panel-heading','p.small','div.tags','section.prompt-section.positive','section.prompt-section.negative','div.tags','dl.meta-grid','details','details']});
|
||||
inner:['div.panel-heading','p.small','div.tags','section.prompt-section.positive','section.prompt-section.negative','div.tags','dl.meta-grid','button.settings-summary','details','details']});
|
||||
await expect(details.locator(':scope > div > button')).toHaveText('Copy settings summary');
|
||||
await expect(details.locator(':scope > div > button.settings-summary')).toHaveCSS('white-space','normal');
|
||||
await expect(details.locator('.detail-cover,.detail-inner,.detail-footer')).toHaveCount(0);
|
||||
await expect(details.locator('.panel-heading h2')).toHaveText(POSITIVE_TITLE);await expect(details.locator('.panel-heading .chip')).toHaveText('PNG');
|
||||
await expect(details.locator(':scope > div > p.small')).toHaveText('complete.png');
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {writeFile} from 'node:fs/promises';
|
||||
import {test,expect} from './fixtures.mjs';
|
||||
import {captureCanonicalState} from './history-canonical-comparison.mjs';
|
||||
import {SIZES,THEMES,MOTIONS,seedConcept,openConcept,openProduction,inventoryOf,diffInventory,mutate,stripExact,countCopy,reflow,withoutItems} from './concept-inventory.mjs';
|
||||
import {SIZES,THEMES,MOTIONS,seedConceptAt,openConcept,openProduction,inventoryOf,diffInventory,mutate,stripExact,countCopy,reflow,withoutItems} from './concept-inventory.mjs';
|
||||
|
||||
// Task C7 of #249: the production Images page against the immutable concept, on the concept-shaped real fixture (24
|
||||
// images of the concept's six prompts, its seeds, sizes and favorites). Heading, toolbar, filter row, caption, grid,
|
||||
@@ -85,7 +85,7 @@ function listInfo(card,actionsWidth) {
|
||||
/** Recorded Images deviations only (spec §8); everything else in the concept inventory must equal production. */
|
||||
const nocase=(a,b)=>{const x=a.toLowerCase(),y=b.toLowerCase();return x<y?-1:x>y?1:a<b?-1:a>b?1:0;};
|
||||
|
||||
export function mapImagesConcept(reference,{manifest,now=new Date()}) {
|
||||
export function mapImagesConcept(reference,{manifest,now=new Date(manifest.now*1000)}) {
|
||||
const paths=new Map(manifest.images.map(image=>[image.filename,image.path]));
|
||||
// D14: the sort appends production's two sorts. Save view is the concept's own (saved views, #249 D16 retired).
|
||||
const toolbar={...reference.toolbar};
|
||||
@@ -318,7 +318,7 @@ async function behaviorsOf(page,scope) {
|
||||
return {hover,opened,viewerTitle,focusAfterViewer,selected,layouts,search,single};
|
||||
}
|
||||
|
||||
test.beforeEach(async({request},testInfo)=>{testInfo.manifest=await seedConcept(request);});
|
||||
test.beforeEach(async({page,request},testInfo)=>{testInfo.manifest=await seedConceptAt(page,request);});
|
||||
|
||||
for(const [width,height] of SIZES)for(const theme of THEMES)test(`images page geometry, tokens, controls and behaviors match the concept ${width}x${height} ${theme}`,async({page,request},testInfo)=>{
|
||||
test.setTimeout(240_000);
|
||||
@@ -348,7 +348,7 @@ for(const [width,height] of SIZES)for(const theme of THEMES)test(`images page ge
|
||||
importDiff:diffInventory(mapImportConcept(referenceImport),actualImport),referenceBehaviors,actualBehaviors};
|
||||
}
|
||||
// Load more in production: a fixture past one listing page appends one batch and shows the concept's toast.
|
||||
testInfo.manifest=await seedConcept(request,{extra_images:LOAD_MORE_EXTRA});
|
||||
testInfo.manifest=await seedConceptAt(page,request,{extra_images:LOAD_MORE_EXTRA});
|
||||
for(const motion of MOTIONS) {
|
||||
const total=FIXTURE_IMAGES+LOAD_MORE_EXTRA;
|
||||
await openProductionLoaded(page,theme,motion,total);
|
||||
@@ -514,7 +514,7 @@ test('one appended image reads in the singular',async({page,request})=>{
|
||||
test.setTimeout(120_000);
|
||||
await page.setViewportSize({width:1600,height:1100});
|
||||
const total=PRODUCTION_BATCH+1;
|
||||
await seedConcept(request,{extra_images:total-FIXTURE_IMAGES});
|
||||
await seedConceptAt(page,request,{extra_images:total-FIXTURE_IMAGES});
|
||||
await openProductionLoaded(page,'dark','no-preference',total);
|
||||
await expect(page.locator('.infinite-continuation > p').first()).toHaveText(countCopy(`${PRODUCTION_BATCH} of ${total} images · more load as you scroll`));
|
||||
// A dispatched press: scrolling the button into view lets the page's own observer load the one image first.
|
||||
@@ -530,7 +530,7 @@ test('one image appended by scrolling reads in the singular',async({page,request
|
||||
test.setTimeout(120_000);
|
||||
await page.setViewportSize({width:1600,height:1100});
|
||||
const total=PRODUCTION_BATCH+1;
|
||||
await seedConcept(request,{extra_images:total-FIXTURE_IMAGES});
|
||||
await seedConceptAt(page,request,{extra_images:total-FIXTURE_IMAGES});
|
||||
await openProductionLoaded(page,'dark','no-preference',total);
|
||||
await expect(page.locator('#result-count')).toHaveText(new RegExp(`^${PRODUCTION_BATCH} of ${total} images`));
|
||||
await page.locator('.infinite-continuation').scrollIntoViewIfNeeded();
|
||||
@@ -551,7 +551,7 @@ test('one footer height for the collection (D3)',async({page,request})=>{
|
||||
const reference=await inventoryOf(page,'#main');
|
||||
expect(reference.grid.columns).toBe(2);
|
||||
expect(reference.cards.every(card=>card.info.p.height>parseFloat(card.info.p.lineHeight))).toBe(true);
|
||||
const manifest=await seedConcept(request,{seedless_images:2,short_seedless:true});
|
||||
const manifest=await seedConceptAt(page,request,{seedless_images:2,short_seedless:true});
|
||||
await openProductionLoaded(page,'dark','no-preference',FIXTURE_IMAGES+2);
|
||||
const actual=await inventoryOf(page,'#workspace-main');
|
||||
const box=card=>({left:card.left,top:card.top,width:card.width,height:card.height});
|
||||
|
||||
@@ -117,7 +117,7 @@ function measureViewer() {
|
||||
['dl.meta-grid', node => node.closest('details') ? null : 'facts'],
|
||||
['details > summary', node => text(node)],
|
||||
['button.send', node => node.closest('.prompt-section') ? `send ${node.closest('.prompt-section').matches('.positive') ? 'positive' : 'negative'}` : 'send pair'],
|
||||
['button', node => /Prompt history/.test(node.textContent) ? 'Prompt history' : null],
|
||||
['button', node => /Prompt history/.test(node.textContent) ? 'Prompt history' : text(node) === 'Copy settings summary' ? 'settings summary' : null],
|
||||
];
|
||||
const sections = [...rail.querySelectorAll('*')].map(node => {
|
||||
for (const [selector, label] of SECTIONS) if (node.matches(selector)) return label(node);
|
||||
@@ -158,13 +158,18 @@ async function withProductionCopy(page) {
|
||||
}, { COPY, ACCEPT });
|
||||
}
|
||||
|
||||
/** D66: the viewer of a local file is titled by its filename and has no tag chips and no Prompt history. */
|
||||
/**
|
||||
* D66: the viewer of a local file is titled by its filename and has no tag chips and no Prompt history. D117 (LI-4):
|
||||
* "Copy settings summary" follows the six facts.
|
||||
*/
|
||||
function mapViewerConcept(reference) {
|
||||
const sections = reference.sections.filter(section => section !== 'tag chips' && section !== 'Prompt history');
|
||||
const facts = sections.indexOf('facts');
|
||||
return {
|
||||
...reference,
|
||||
title: FILE,
|
||||
railTitle: FILE,
|
||||
sections: reference.sections.filter(section => section !== 'tag chips' && section !== 'Prompt history'),
|
||||
sections: [...sections.slice(0, facts + 1), 'settings summary', ...sections.slice(facts + 1)],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -269,9 +274,9 @@ for (const [width, height] of SIZES) for (const theme of THEMES) {
|
||||
// The chooser names the chosen file after a real setInputFiles, as the concept's does.
|
||||
expect(production.initial.chosen).toEqual({ name: '', files: [] });
|
||||
expect(production.selected.chosen).toEqual({ name: FILE, files: [FILE] });
|
||||
// D66 in the rail: no tag chips and no Prompt history; the title is the filename.
|
||||
// D66 in the rail: no tag chips and no Prompt history; the title is the filename. D117 follows the facts.
|
||||
expect(production.viewer.sections).toEqual(['heading', 'filename', 'badges', 'positive', 'send positive', 'negative',
|
||||
'send negative', 'facts', 'File & provenance', 'Workflow & raw metadata', 'send pair']);
|
||||
'send negative', 'facts', 'settings summary', 'File & provenance', 'Workflow & raw metadata', 'send pair']);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -45,10 +45,10 @@ function withCategoryScope(inventory) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Recorded inspector deviations only (spec §8, TESTING.md D3, D20–D22, D34 and D38); everything else must equal
|
||||
* production. `reference.viewerPlain` is the concept's own full details
|
||||
* with its tag chips made plain (D20) and, under a coarse pointer, D34's targets, both at runtime: the browser lays out
|
||||
* what follows them, as the Images spec's removed toolbar items do.
|
||||
* Recorded inspector deviations only (spec §8, TESTING.md D3, D20–D22, D34, D38 and D117); everything else must
|
||||
* equal production. `reference.viewerPlain` is the concept's own full details
|
||||
* with its tag chips made plain (D20), D117's summary button added and, under a coarse pointer, D34's targets, all at
|
||||
* runtime: the browser lays out what follows them, as the Images spec's removed toolbar items do.
|
||||
*/
|
||||
export function mapInspectorConcept(reference,{viewport}) {
|
||||
const {panel,viewerPlain,fileControls}=reference;
|
||||
@@ -105,7 +105,11 @@ async function openProductionPanel(page,theme) {
|
||||
await settle(page);
|
||||
}
|
||||
|
||||
/** The concept's tag chips in the open viewer as plain `span.chip`s (D20) and D34's coarse targets; returns an undo. */
|
||||
/**
|
||||
* The concept's tag chips in the open viewer as plain `span.chip`s (D20), D34's coarse targets and D117's "Copy
|
||||
* settings summary" after the six facts (LI-4), drawn as the concept's own plain button (its "Download sample JSON",
|
||||
* without its action); returns an undo.
|
||||
*/
|
||||
async function plainViewerChips(page) {
|
||||
const restoreTargets=await mutate(page,{css:D34_COARSE_TARGETS});
|
||||
await page.evaluate(()=>{
|
||||
@@ -113,10 +117,15 @@ async function plainViewerChips(page) {
|
||||
const span=document.createElement('span');span.className='chip';span.textContent=button.textContent;
|
||||
button.replaceWith(span);return [span,button];
|
||||
});
|
||||
const summary=document.querySelector('#viewer-details [data-action="download-workflow"]').cloneNode(false);
|
||||
for(const key of Object.keys(summary.dataset))delete summary.dataset[key];
|
||||
summary.textContent='Copy settings summary';summary.classList.add('settings-summary');
|
||||
document.querySelector('#viewer-details > div > dl.meta-grid').after(summary);window.__summaryButton=summary;
|
||||
});
|
||||
await settle(page);
|
||||
return async()=>{
|
||||
await page.evaluate(()=>{for(const [span,button] of window.__plainChips)span.replaceWith(button);delete window.__plainChips;});
|
||||
await page.evaluate(()=>{for(const [span,button] of window.__plainChips)span.replaceWith(button);delete window.__plainChips;
|
||||
window.__summaryButton.remove();delete window.__summaryButton;});
|
||||
await restoreTargets();
|
||||
};
|
||||
}
|
||||
@@ -342,7 +351,7 @@ for(const [width,height] of SIZES)test(`image tags saved on the concept image ke
|
||||
|
||||
// The comparison is only worth something if it notices a change (spec §7 mutation check): on the panel one CSS
|
||||
// mutation (the role label's letter spacing) and one DOM mutation (the footer removed); in the viewer (final review m5)
|
||||
// its pair actions removed and D38's Show in folder removed; each applied after an exact match.
|
||||
// its pair actions removed, D38's Show in folder removed and D117's summary removed; each applied after an exact match.
|
||||
test('inspector comparison detects mutations',async({page})=>{
|
||||
test.setTimeout(120_000);
|
||||
const viewport={width:1600,height:1100};
|
||||
@@ -366,6 +375,9 @@ test('inspector comparison detects mutations',async({page})=>{
|
||||
expect(()=>assertInspectorMatch(reference,withoutActions,viewport)).toThrow(/viewerDetails\.actions/);
|
||||
const withoutReveal=await viewerMutated({remove:['#viewer-details button[aria-label$=" in folder"]']});
|
||||
expect(()=>assertInspectorMatch(reference,withoutReveal,viewport)).toThrow(/fileControls/);
|
||||
// D117: the summary action after the facts is part of the mapped concept, so losing it is a difference.
|
||||
const withoutSummary=await viewerMutated({remove:['#viewer-details > div > button']});
|
||||
expect(()=>assertInspectorMatch(reference,withoutSummary,viewport)).toThrow(/viewerDetails\.structure\.inner/);
|
||||
assertInspectorMatch(reference,await viewerMutated(),viewport);
|
||||
|
||||
await mutate(page,{remove:['#image-inspector > .detail-footer']});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {writeFile} from 'node:fs/promises';
|
||||
import {test,expect} from './fixtures.mjs';
|
||||
import {captureCanonicalState} from './history-canonical-comparison.mjs';
|
||||
import {SIZES,THEMES,MOTIONS,seedConcept,openConcept,openProduction,inventoryOf,diffInventory,mutate,stripExact,countCopy,reflow} from './concept-inventory.mjs';
|
||||
import {SIZES,THEMES,MOTIONS,seedConceptAt,openConcept,openProduction,inventoryOf,diffInventory,mutate,stripExact,countCopy,reflow} from './concept-inventory.mjs';
|
||||
|
||||
// Task E3 of #249: the production Prompt library shelf against the immutable concept (app.js renderLibrary a572–586,
|
||||
// style.css s648–708), on the concept-shaped real fixture (the concept's six prompts with their negatives, categories,
|
||||
@@ -37,7 +37,8 @@ export function mapLibraryConcept(reference) {
|
||||
// D43: tag chips come in the store's alphabetical order; the row flows again from the concept's own chips.
|
||||
tags:sortedTags(card.tags),
|
||||
// D23: the stars are aria-hidden, with a visually hidden "Rated N out of 5" spoken in their place. The fixture's
|
||||
// run_count (4) and last_used_at (now) give the concept's own "4 runs" and "Used today". The two-line clamp is
|
||||
// run_count (4) and last_used_at (its own "now", where the page's clock stands) give the concept's own "4 runs"
|
||||
// and "Used today". The two-line clamp is
|
||||
// applied below through `clampedCards`, measured on the concept with `CLAMP_CSS` (its samples wrap at 390px).
|
||||
footer:{...card.footer,facts:{...card.footer.facts,spoken:card.footer.facts.spoken.replace(/^(★+)/,stars=>`Rated ${stars.length} out of 5`)}}}));
|
||||
return {...reference,library:{...library,toolbar,
|
||||
@@ -238,7 +239,8 @@ async function openHost(context) {
|
||||
}
|
||||
|
||||
test.beforeEach(async({page,request},testInfo)=>{
|
||||
testInfo.manifest=await seedConcept(request);
|
||||
// The page's clock stands at the fixture's own "now", so its last use reads "Used today" on either side of midnight.
|
||||
testInfo.manifest=await seedConceptAt(page,request);
|
||||
// Both documents copy through the clipboard; the stub records what they wrote.
|
||||
await page.addInitScript(()=>{window.copied=[];Object.defineProperty(navigator,'clipboard',{configurable:true,value:{writeText:async text=>{window.copied.push(text);}}});});
|
||||
});
|
||||
@@ -322,6 +324,27 @@ for(const theme of THEMES)test(`library grid and cards match the concept 1800x11
|
||||
expect(compare(reference,actual,{sections:['library'],library:['grid','cards','trailing']})).toEqual([]);
|
||||
});
|
||||
|
||||
// PR #284's CI run: the fixture recorded the last use at 23:59:5x UTC and the shelf rendered at 00:00:05, so production
|
||||
// read "Used yesterday" against the concept's "Used today". Here the browser's wall clock starts at 23:59:58 UTC, the
|
||||
// fixture records its use at that instant, and midnight passes before either document opens.
|
||||
const BEFORE_MIDNIGHT=Date.UTC(2026,9,22,23,59,58);
|
||||
const PAST_MIDNIGHT_MS=5_000;
|
||||
test('a run that crosses midnight still reads the concept fixture\'s day',async({page,request})=>{
|
||||
await page.setViewportSize({width:1800,height:1100});
|
||||
await page.clock.install({time:BEFORE_MIDNIGHT});
|
||||
const manifest=await seedConceptAt(page,request,{now:BEFORE_MIDNIGHT/1000});
|
||||
expect(manifest.now*1000,'the fixture\'s now').toBe(BEFORE_MIDNIGHT);
|
||||
const used=(await (await request.get('/prompt_manager/library')).json()).items.map(item=>Date.parse(item.last_used_at));
|
||||
expect(used,'every last use at the fixture\'s now').toEqual(Array(CONCEPT_PROMPTS).fill(BEFORE_MIDNIGHT));
|
||||
await page.clock.fastForward(PAST_MIDNIGHT_MS);
|
||||
await openConceptLibrary(page,'dark','no-preference');
|
||||
const reference=await conceptInventory(page);
|
||||
await openProductionLibrary(page,'dark','no-preference');
|
||||
const actual=await inventoryOf(page,'#workspace-main');
|
||||
expect(actual.library.cards.map(card=>card.footer.facts.text.replace(/^★+ · /,''))).toEqual(Array(CONCEPT_PROMPTS).fill('Used today'));
|
||||
expect(compare(reference,actual,{sections:['library'],library:['grid','cards','trailing']})).toEqual([]);
|
||||
});
|
||||
|
||||
// The comparison is only worth something if it notices a change (spec §7 mutation check): one CSS mutation (the footer
|
||||
// padding) and one DOM mutation (the negative-variants chip removed), each applied after an exact match.
|
||||
test('library comparison detects mutations',async({page})=>{
|
||||
|
||||
+12
-1
@@ -24,6 +24,7 @@ from tests.browser.workspace_activity_fixture import register_activity_commands
|
||||
from tests.browser.workspace_concept_fixture import (
|
||||
MAX_EXTRA_IMAGES as CONCEPT_MAX_EXTRA_IMAGES,
|
||||
MAX_SEEDLESS_IMAGES as CONCEPT_MAX_SEEDLESS_IMAGES,
|
||||
MAX_EPOCH_SECONDS as CONCEPT_MAX_EPOCH_SECONDS,
|
||||
seed_workspace_concept,
|
||||
)
|
||||
from tests.browser.workspace_visual_fixture import seed_workspace_visual
|
||||
@@ -491,8 +492,17 @@ def create_app(root: Path) -> web.Application:
|
||||
if (
|
||||
request.query
|
||||
or not isinstance(data, dict)
|
||||
or set(data) - set(limits) - {"short_seedless"}
|
||||
or set(data) - set(limits) - {"short_seedless", "now"}
|
||||
or not isinstance(data.get("short_seedless", False), bool)
|
||||
# A chosen "now" (epoch seconds) pins every time the fixture writes.
|
||||
or (
|
||||
"now" in data
|
||||
and (
|
||||
isinstance(data["now"], bool)
|
||||
or not isinstance(data["now"], (int, float))
|
||||
or not 0 < data["now"] < CONCEPT_MAX_EPOCH_SECONDS
|
||||
)
|
||||
)
|
||||
or any(
|
||||
isinstance(data.get(key, 0), bool)
|
||||
or not isinstance(data.get(key, 0), int)
|
||||
@@ -512,6 +522,7 @@ def create_app(root: Path) -> web.Application:
|
||||
extra_images=data.get("extra_images", 0),
|
||||
seedless_images=data.get("seedless_images", 0),
|
||||
short_seedless=data.get("short_seedless", False),
|
||||
now=data.get("now"),
|
||||
)
|
||||
)
|
||||
return web.json_response({"success": True, **manifest})
|
||||
|
||||
@@ -178,27 +178,28 @@ async function captureFooter(page,testInfo,name) {
|
||||
|
||||
test.beforeEach(async({request})=>{await seedConcept(request);});
|
||||
|
||||
for(const [width,height] of SIZES)for(const theme of THEMES)test(`shell geometry, tokens and controls match the concept ${width}x${height} ${theme}`,async({page},testInfo)=>{
|
||||
// One test per route, size, theme and motion. All of them in one test per size and theme (12 page loads, 12 captures,
|
||||
// 36 hovers) steadily took 22 s median and up to 33 s on CI WebKit, past the 30 s budget with no step stalled; one
|
||||
// route in one motion is a sixth of that work under the same budget.
|
||||
for(const [route,breadcrumb] of ROUTES)for(const [width,height] of SIZES)for(const theme of THEMES)for(const motion of MOTIONS)test(`shell geometry, tokens and controls match the concept on ${route} ${width}x${height} ${theme} ${motion}`,async({page},testInfo)=>{
|
||||
await page.setViewportSize({width,height});const result={};
|
||||
for(const motion of MOTIONS)for(const [route,breadcrumb] of ROUTES) {
|
||||
await openConcept(page,route,theme,motion);await page.mouse.move(0,0);
|
||||
const reference=await inventoryOf(page,'#main');
|
||||
if(motion==='no-preference')await captureCanonicalState(page,testInfo,`concept-shell-${route}-${width}-${theme}`);
|
||||
const referenceRings=FULL_HEADING.has(route)?await ringsOf(page,'#main'):null;
|
||||
const referenceHovers=await hoversOf(page);
|
||||
if(motion==='no-preference')await captureFooter(page,testInfo,`concept-footer-${route}-${width}-${theme}`);
|
||||
await openProduction(page,route,theme,motion);await page.mouse.move(0,0);
|
||||
const actual=await inventoryOf(page,'#workspace-main');
|
||||
if(motion==='no-preference')await captureCanonicalState(page,testInfo,`production-shell-${route}-${width}-${theme}`);
|
||||
const actualRings=FULL_HEADING.has(route)?await ringsOf(page,'#workspace-main'):null;
|
||||
const actualHovers=await hoversOf(page);
|
||||
if(motion==='no-preference')await captureFooter(page,testInfo,`production-footer-${route}-${width}-${theme}`);
|
||||
result[`${motion} ${route}`]={route,breadcrumb,reference,actual,diff:compare(route,reference,actual),referenceRings,actualRings,
|
||||
referenceHovers,actualHovers};
|
||||
}
|
||||
const path=testInfo.outputPath('shell-geometry.json');await writeFile(path,JSON.stringify(result,null,2));
|
||||
await testInfo.attach('shell-geometry',{path,contentType:'application/json'});
|
||||
for(const [key,{route,breadcrumb,reference,actual,diff,referenceRings,actualRings,referenceHovers,actualHovers}] of Object.entries(result)) {
|
||||
await openConcept(page,route,theme,motion);await page.mouse.move(0,0);
|
||||
const reference=await inventoryOf(page,'#main');
|
||||
if(motion==='no-preference')await captureCanonicalState(page,testInfo,`concept-shell-${route}-${width}-${theme}`);
|
||||
const referenceRings=FULL_HEADING.has(route)?await ringsOf(page,'#main'):null;
|
||||
const referenceHovers=await hoversOf(page);
|
||||
if(motion==='no-preference')await captureFooter(page,testInfo,`concept-footer-${route}-${width}-${theme}`);
|
||||
await openProduction(page,route,theme,motion);await page.mouse.move(0,0);
|
||||
const actual=await inventoryOf(page,'#workspace-main');
|
||||
if(motion==='no-preference')await captureCanonicalState(page,testInfo,`production-shell-${route}-${width}-${theme}`);
|
||||
const actualRings=FULL_HEADING.has(route)?await ringsOf(page,'#workspace-main'):null;
|
||||
const actualHovers=await hoversOf(page);
|
||||
if(motion==='no-preference')await captureFooter(page,testInfo,`production-footer-${route}-${width}-${theme}`);
|
||||
result[`${motion} ${route}`]={reference,actual,diff:compare(route,reference,actual),referenceRings,actualRings,
|
||||
referenceHovers,actualHovers};
|
||||
const path=testInfo.outputPath(`shell-geometry-${route}-${motion}.json`);await writeFile(path,JSON.stringify(result,null,2));
|
||||
await testInfo.attach(`shell-geometry-${route}-${motion}`,{path,contentType:'application/json'});
|
||||
for(const [key,{reference,actual,diff,referenceRings,actualRings,referenceHovers,actualHovers}] of Object.entries(result)) {
|
||||
// The concept itself is what this comparison assumes: its sample counts and its shell controls.
|
||||
expect.soft(reference.chrome.navs[0].rows.map(row=>[row.text,row.count?.text??null]),`${key} concept WORKSPACE rows`)
|
||||
.toEqual([['Images','24'],['Prompt library','6'],['Tags & categories','15'],['Inspect a file',null]]);
|
||||
|
||||
@@ -2,6 +2,13 @@ import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage
|
||||
import { test, expect } from './fixtures.mjs';
|
||||
import { seedConcept, openConcept, openProduction } from './concept-inventory.mjs';
|
||||
|
||||
// The Activity store's periodic list read (activity-store.mjs POLL_MS) and the detail view's read throttle
|
||||
// (activity-job-view.mjs DETAIL_INTERVAL_MS).
|
||||
const POLL_MS = 15_000;
|
||||
const DETAIL_INTERVAL_MS = 1_000;
|
||||
// A request is reported to the test a little after the browser sends it; that delay is not a shorter wait.
|
||||
const REPORT_SLACK_MS = 100;
|
||||
|
||||
// Activity (#249 Activity-1): the concept's Activity page (app.js renderActivity 732–738), its top-bar button
|
||||
// (index.html 51–52) and sidebar row (app.js ~341), with the recorded D52 (counts of running jobs), D53 (the progress
|
||||
// pill) and D54 (real job items). Fake jobs come from tests/browser/workspace_activity_fixture.py.
|
||||
@@ -278,6 +285,8 @@ test('reload during a scan reattaches to the running job', async ({ page, reques
|
||||
});
|
||||
|
||||
test('lost server clears the pill and marks jobs ended', async ({ page, request }) => {
|
||||
// A poll interval after the restart, then failed re-reads backing off for 1 + 2 + 4 s.
|
||||
test.setTimeout(90_000);
|
||||
await page.setViewportSize({ width: 1600, height: 1100 });
|
||||
const job = await startJob(request);
|
||||
await step(request, job.id, { processed: 4000 });
|
||||
@@ -294,9 +303,12 @@ test('lost server clears the pill and marks jobs ended', async ({ page, request
|
||||
await expect(items(page).first().locator('p')).toHaveText(LOST);
|
||||
await expect(items(page).first().locator('progress, .row-actions')).toHaveCount(0);
|
||||
await expect(navRow(page).locator('.nav-count')).toHaveCount(0);
|
||||
// One re-read found the restart; there is no retry storm and no finish toast for a job that only vanished.
|
||||
await page.waitForTimeout(2500);
|
||||
expect(reads.length).toBeLessThanOrEqual(2);
|
||||
// One re-read found the restart; there is no retry storm and no finish toast for a job that only vanished. The
|
||||
// read after it is the periodic one, a whole poll interval later: any extra read lands in that gap and fails it.
|
||||
const found = reads.length;
|
||||
expect(found, 'reads that found the restart').toBeGreaterThanOrEqual(1);
|
||||
await expect.poll(() => reads.length, { timeout: POLL_MS + 10_000 }).toBeGreaterThan(found);
|
||||
expect(reads[found] - reads[found - 1], 'the next read waits for the poll').toBeGreaterThanOrEqual(POLL_MS - REPORT_SLACK_MS);
|
||||
await expect(toast(page)).toHaveText('');
|
||||
|
||||
// A server that cannot be read at all also ends the running job, then is read again with a growing backoff.
|
||||
@@ -308,9 +320,12 @@ test('lost server clears the pill and marks jobs ended', async ({ page, request
|
||||
await expect(await request.post('/__test__/jobs/restart')).toBeOK();
|
||||
await expect(pill(page)).toBeHidden();
|
||||
await expect(items(page).filter({ hasText: LOST })).toHaveCount(1);
|
||||
await page.waitForTimeout(3500);
|
||||
// 1 s, then 2 s: at most two re-reads in 3.5 s.
|
||||
expect(failed.length).toBeLessThanOrEqual(2);
|
||||
// 1 s, then 2 s, then 4 s: each failed re-read waits twice as long as the one before. The gaps between the
|
||||
// reads themselves are the evidence, so a slow runner noticing the ended job late cannot add a read to a window.
|
||||
await expect.poll(() => failed.length, { timeout: 20_000 }).toBeGreaterThanOrEqual(3);
|
||||
const gaps = failed.slice(1, 3).map((at, index) => at - failed[index]);
|
||||
expect(gaps[0]).toBeGreaterThanOrEqual(2000 - REPORT_SLACK_MS);
|
||||
expect(gaps[1]).toBeGreaterThanOrEqual(4000 - REPORT_SLACK_MS);
|
||||
await page.unroute('**/prompt_manager/jobs**');
|
||||
expect(second.id).not.toBe(job.id);
|
||||
});
|
||||
@@ -607,6 +622,8 @@ test('filter narrows the selected outcome', async ({ page, request }) => {
|
||||
|
||||
test('job view renders 200-row cap note', async ({ page, request }) => {
|
||||
await page.setViewportSize({ width: 1600, height: 1100 });
|
||||
// The page's timers are Playwright's, running at real speed, so the M12 check below can run a read throttle out.
|
||||
await page.clock.install();
|
||||
const job = await startJob(request);
|
||||
await step(request, job.id, { processed: 260, bulk: { group: 'added', count: 250 }, records: [
|
||||
...Array.from({ length: 10 }, (_, index) => ({ group: 'no_metadata', path: `misc/plain_${index}.png`, detail: 'No prompt metadata in the file' })),
|
||||
@@ -646,11 +663,15 @@ test('job view renders 200-row cap note', async ({ page, request }) => {
|
||||
page.on('request', item => { if (new URL(item.url()).pathname === `/prompt_manager/jobs/${job.id}`) reads.push(Date.now()); });
|
||||
await step(request, job.id, { processed: 300, bulk: { group: 'added', count: 40 } });
|
||||
await expect(tiles(page).first().locator('dd')).toHaveText('290');
|
||||
await page.waitForTimeout(1500);
|
||||
// Every read the counter update could have scheduled is due within one throttle interval: run it out, so any such
|
||||
// read is sent before the log opens. Requests reach the test in the order they were sent, so once the log's read
|
||||
// has answered, a read sent before it would already be listed.
|
||||
await page.clock.runFor(DETAIL_INTERVAL_MS);
|
||||
expect(reads).toEqual([]);
|
||||
await scanLog(page).locator('summary').click();
|
||||
await expect.poll(() => reads.length).toBe(1);
|
||||
await expect(scanLog(page).locator('pre')).toContainText('bulk/file_00039.png');
|
||||
expect(reads, 'only the log\'s own read').toHaveLength(1);
|
||||
});
|
||||
|
||||
test('cancel scan ends cancelled with partial counts', async ({ page, request }) => {
|
||||
@@ -705,14 +726,17 @@ test('a held legacy job shows no Cancel in the list or its view', async ({ page,
|
||||
|
||||
test('busy start names the running job', async ({ page, request }) => {
|
||||
await page.setViewportSize({ width: 1600, height: 1100 });
|
||||
// The page's timers are Playwright's, so the toast's lifetime below is run out rather than waited for.
|
||||
await page.clock.install();
|
||||
const running = await startJob(request, { title: 'Database maintenance', kind: 'maintenance' });
|
||||
await startFromImport(page);
|
||||
await expect(toast(page)).toHaveText('Another job is running: Database maintenance.');
|
||||
await expect(toast(page).getByRole('link', { name: 'Database maintenance', exact: true })).toHaveAttribute('href', `#/activity/${running.id}`);
|
||||
await expect(page).toHaveURL(/#\/images$/);
|
||||
expect((await listed(request)).map(item => item.id)).toEqual([running.id]);
|
||||
// Review M14: a toast with a link outlasts the plain 6.5 s, so the link stays reachable.
|
||||
await page.waitForTimeout(7000);
|
||||
// Review M14: a toast with a link outlasts the plain 6.5 s, so the link stays reachable. Running the page's timers
|
||||
// 7 s on fires a 6.5 s clear for certain, however slowly this runner reached this line.
|
||||
await page.clock.runFor(7000);
|
||||
await expect(toast(page).getByRole('link', { name: 'Database maintenance', exact: true })).toBeVisible();
|
||||
await toast(page).getByRole('link', { name: 'Database maintenance', exact: true }).click();
|
||||
await expect(heading(page).locator('h1')).toHaveText('Database maintenance');
|
||||
|
||||
@@ -494,6 +494,23 @@ test('the inline current file names its prompts apart from the frozen run fields
|
||||
expect(await exact(dialog(page).getByRole('region',{name:'Positive prompt',exact:true}).locator('p.prompt-text'))).toBe(before);
|
||||
});
|
||||
|
||||
// LI-4 (D117): the recorded history's current-file viewer is the shared full inspector, so it copies the legacy summary.
|
||||
test('the current file viewer copies its settings summary',async({page})=>{
|
||||
await page.addInitScript(()=>{window.__copied=[];Object.defineProperty(navigator,'clipboard',{configurable:true,value:{writeText:async text=>{window.__copied.push(text);}}});});
|
||||
await page.route(url=>url.pathname.endsWith('/inspection'),async route=>{const response=await route.fetch();const body=await response.json();
|
||||
body.prompts={positive:{status:'resolved',text:'current file positive',source:'graph-inferred'},negative:{status:'resolved',text:'current file negative',source:'graph-inferred'}};
|
||||
await route.fulfill({response,json:body});});
|
||||
await open(page,page.fixture.detail_id);await marker(page,page.fixture.runs.shared).click();await expect(dialog(page).locator('[data-receipt]')).toHaveCount(5);
|
||||
await dialog(page).locator('[data-receipt]').first().getByRole('button',{name:'View current file',exact:true}).click();
|
||||
const details=page.locator('dialog#viewer-dialog #viewer-details');await expect(details.locator('.panel-heading')).toBeVisible();
|
||||
const facts=await details.locator(':scope > div > dl.meta-grid dd').allTextContents();
|
||||
await details.getByRole('button',{name:'Copy settings summary',exact:true}).click();
|
||||
await expect(page.locator('#workspace-toast')).toHaveText('Settings summary copied.');
|
||||
const [seed,steps,cfg,sampler,,model]=facts;
|
||||
expect(await page.evaluate(()=>window.__copied)).toEqual([[`Checkpoint: ${model}`,'Positive Prompt: current file positive','Negative Prompt: current file negative',
|
||||
`Steps: ${steps}`,`CFG Scale: ${cfg}`,`Sampler: ${sampler}`,`Seed: ${seed}`].join('\n').replace(/: (Not recorded|Unresolved|Ambiguous|Unavailable within inspection limits)(?=\n|$)/g,': Unknown')]);
|
||||
});
|
||||
|
||||
test('the recorded run dialog with a resolved current file has no duplicate button or region names',async({page})=>{
|
||||
await page.route(url=>url.pathname.endsWith('/inspection'),async route=>{const response=await route.fetch();const body=await response.json();
|
||||
body.prompts={positive:{status:'resolved',text:'current file positive',source:'graph-inferred'},negative:{status:'resolved',text:'current file negative',source:'graph-inferred'}};
|
||||
|
||||
@@ -907,6 +907,10 @@ test('browser Back closes the open Images dialog and leaves the next page usable
|
||||
|
||||
test('count line shows images and positive prompts', async ({ page, request }) => {
|
||||
await page.addInitScript(() => { window.IntersectionObserver = undefined; });
|
||||
// D17's "Today" is the newest file's day: the page's clock stands at that file's mtime, so the fixture's day and
|
||||
// the page's agree on either side of midnight.
|
||||
const { images } = await (await request.get('/prompt_manager/images/output?mode=workspace&limit=40')).json();
|
||||
await page.clock.setFixedTime(new Date(Math.max(...images.map(image => image.modified_time)) * 1000));
|
||||
await page.goto(workspace);
|
||||
await expect(cards(page)).toHaveCount(2);
|
||||
await expect(caption(page).locator('#result-count')).toHaveText('2 of 2 images · 2 positive prompts');
|
||||
|
||||
@@ -207,6 +207,40 @@ test('chooser opens the shared full inspector without a second read', async ({ p
|
||||
expect(await page.evaluate(() => window.__slices)).toBe(0);
|
||||
});
|
||||
|
||||
// PR L3 Task 10: local roles are the server inspector's (local-resolver.mjs), so for every parity PNG the rail shows the
|
||||
// prompts, their status lines and the facts Images shows for the same bytes in the output folder.
|
||||
const PARITY_PNGS = ['f01b', 'f02', 'f03', 'f06a', 'f06b', 'f06c', 'f06d', 'f06e', 'f07a', 'f07b', 'f08', 'f09', 'f10', 'f11', 'f12',
|
||||
'f14', 'f15', 'f16', 'f17', 'f19', 'f20', 'f21', 'f22', 'f23', 'f24'];
|
||||
const roleSections = locator => locator.evaluate(node => [...node.querySelectorAll('.prompt-section')].map(item => item.textContent));
|
||||
|
||||
test('chooser shows the Images roles and resolution for every parity PNG', async ({ page, request }) => {
|
||||
test.slow();
|
||||
for (const name of PARITY_PNGS) {
|
||||
await expect(await request.post('/__test__/add-local-inspect-file', { data: { name: `${name}.png` } })).toBeOK();
|
||||
}
|
||||
const served = {};
|
||||
await page.goto(`${workspace}#/images`);
|
||||
for (const name of PARITY_PNGS) {
|
||||
await page.locator(`article[data-image-key="0:local-inspect/${name}.png"] .image-open`).click();
|
||||
await expect(viewer(page).locator('#viewer-title')).toHaveText(`${name}.png`);
|
||||
await expect(rail(page).locator('.panel-heading')).toBeVisible();
|
||||
await expect(rail(page).locator('.prompt-section')).not.toHaveCount(0);
|
||||
served[name] = { content: await railContent(rail(page)), roles: await roleSections(rail(page)) };
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(viewer(page)).toHaveCount(0);
|
||||
}
|
||||
await openInspect(page);
|
||||
for (const name of PARITY_PNGS) {
|
||||
await choose(page, parityPng(`${name}.png`));
|
||||
await openViewer(page);
|
||||
await expect(viewer(page).locator('#viewer-title')).toHaveText(`${name}.png`);
|
||||
await expect(rail(page).locator('.prompt-section')).not.toHaveCount(0);
|
||||
expect({ content: await railContent(rail(page)), roles: await roleSections(rail(page)) }, name).toEqual(served[name]);
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(viewer(page)).toHaveCount(0);
|
||||
}
|
||||
});
|
||||
|
||||
test('Import → Inspect a local image lands here', async ({ page }) => {
|
||||
await page.goto(`${workspace}#/images`);
|
||||
await page.getByRole('button', { name: 'Import', exact: true }).click();
|
||||
@@ -481,15 +515,13 @@ test('replacing a video that just started loading never blocks the page', async
|
||||
});
|
||||
|
||||
test('a video replaced while still starting is reset once it settles', async ({ context, browserName }) => {
|
||||
// A WebKit (GStreamer) video released exactly at its `loadstart` sometimes blocks the page, with or without any
|
||||
// reset and also with the code before the deferred reset (2 of 24 runs); tracked in TESTING.md (D62). WebKit's
|
||||
// no-hang guard is `replacing a video that just started loading never blocks the page`.
|
||||
test.skip(browserName === 'webkit', 'WebKit release at loadstart is a tracked follow-up (D62)');
|
||||
test.setTimeout(120000);
|
||||
// The video is replaced from its own `loadstart` (readyState HAVE_NOTHING). It leaves the page with no src before
|
||||
// its URL is revoked, and is reset (load() with no src, which frees its decoder) only once it reports metadata or
|
||||
// an error, so the page never blocks. Fresh pages share one browser process.
|
||||
for (let attempt = 0; attempt < 5; attempt++) {
|
||||
test.setTimeout(180000);
|
||||
// The video is replaced from its own `loadstart` (readyState HAVE_NOTHING), or a few milliseconds after it. On
|
||||
// WebKit (GStreamer) a video that left the page or the viewport before its pipeline had started deadlocked the
|
||||
// page (TESTING.md D62), so it stays in place, inert and still playing its URL, with the new preview after it.
|
||||
// Once it reports metadata or an error it is paused, loses its src, is reset (load() with no src, which frees its
|
||||
// decoder) and leaves the page, and only then is its URL revoked. Fresh pages share one browser process.
|
||||
for (let attempt = 0; attempt < 15; attempt++) {
|
||||
const page = await context.newPage();
|
||||
try {
|
||||
if (attempt === 0) await startCoverage(page, browserName);
|
||||
@@ -510,10 +542,12 @@ test('a video replaced while still starting is reset once it settles', async ({
|
||||
const video = slot.querySelector('video');
|
||||
if (!video) return;
|
||||
observer.disconnect();
|
||||
video.addEventListener('loadstart', () => {
|
||||
const replace = () => {
|
||||
window.__starting = { node: video, url: video.getAttribute('src'), readyState: video.readyState };
|
||||
input.files = window.__pngFiles; input.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
}, { once: true });
|
||||
window.__starting.replaced = { connected: video.isConnected, src: video.hasAttribute('src'), inert: video.inert, resets: video.__resets ?? 0 };
|
||||
};
|
||||
video.addEventListener('loadstart', () => { if (window.__delay) setTimeout(replace, window.__delay); else replace(); }, { once: true });
|
||||
}).observe(slot, { childList: true });
|
||||
});
|
||||
const png = parityPng('f02.png');
|
||||
@@ -522,13 +556,17 @@ test('a video replaced while still starting is reset once it settles', async ({
|
||||
transfer.items.add(new File([new Uint8Array(bytes)], 'f02.png', { type: 'image/png' }));
|
||||
window.__pngFiles = transfer.files;
|
||||
}, [...png.buffer]);
|
||||
await page.evaluate(delay => { window.__delay = delay; }, attempt % 5);
|
||||
await choose(page, localFixture('core-tags.webm', 'video/webm'));
|
||||
await expect(preview(page).locator('img.local-file-preview')).toBeVisible({ timeout: 8000 });
|
||||
await expect(preview(page).locator('video')).toHaveCount(0);
|
||||
// Released while starting, and never reset synchronously: the URL went once the node had no src.
|
||||
expect(await page.evaluate(() => ({ readyState: window.__starting.readyState, revoked: window.__starting.revoked })))
|
||||
.toEqual({ readyState: 0, revoked: { src: false, connected: false, resets: 0 } });
|
||||
await expect.poll(() => page.evaluate(() => window.__starting.node.__resets ?? 0), { timeout: 15000 }).toBe(1);
|
||||
// Replaced while starting (always so at `loadstart` itself): kept in place and untouched. A video that had
|
||||
// settled is released at once. Either way it is reset once, and its URL goes last.
|
||||
await expect.poll(() => page.evaluate(() => window.__starting.revoked ?? null)).toEqual({ src: false, connected: false, resets: 1 });
|
||||
const { readyState, replaced } = await page.evaluate(() => ({ readyState: window.__starting.readyState, replaced: window.__starting.replaced }));
|
||||
if (attempt % 5 === 0) expect(readyState).toBe(0);
|
||||
expect(replaced).toEqual(readyState === 0 ? { connected: true, src: true, inert: true, resets: 0 } : { connected: false, src: false, inert: false, resets: 1 });
|
||||
expect(await page.evaluate(() => window.__starting.node.__resets)).toBe(1);
|
||||
// The page still answers.
|
||||
await chooser(page).setInputFiles(parityPng('f02.png', 'after.png'), { timeout: 8000 });
|
||||
await expect(preview(page).locator('img.local-file-preview')).toBeVisible({ timeout: 8000 });
|
||||
@@ -652,13 +690,19 @@ test('local roles send exactly', async ({ page, context }) => {
|
||||
|
||||
test('local inspection makes no content request or storage write', async ({ page }) => {
|
||||
await instrument(page);
|
||||
await openInspect(page);
|
||||
// The shell's own reads (counts, Activity) settle before the baseline.
|
||||
await expect(page.locator('aside.sidebar nav [data-route="images"] .nav-count')).toBeAttached();
|
||||
const baseline = (await urls(page)).writes.length;
|
||||
const requests = [];
|
||||
page.on('request', request => requests.push({ url: request.url(), method: request.method(), body: request.postData() }));
|
||||
page.on('websocket', socket => requests.push({ url: socket.url(), method: 'WS', body: null }));
|
||||
const table = /\/prompt_manager\/js\/inspection-semantics\.json$/;
|
||||
const tableRead = page.waitForResponse(response => table.test(response.url()));
|
||||
await openInspect(page);
|
||||
// The one static file Inspect reads, its node table, is fetched as the page mounts: before any selection.
|
||||
expect((await tableRead).ok()).toBe(true);
|
||||
// The shell's own reads (counts, Activity) settle before the baseline.
|
||||
await expect(page.locator('aside.sidebar nav [data-route="images"] .nav-count')).toBeAttached();
|
||||
const baseline = (await urls(page)).writes.length;
|
||||
const before = requests.length;
|
||||
expect(requests.filter(entry => table.test(entry.url))).toHaveLength(1);
|
||||
for (const file of [sendablePng('private-name.png'), localFixture('core-tags.webm', 'video/webm', 'private-clip.webm')]) {
|
||||
await choose(page, file);
|
||||
await openViewer(page);
|
||||
@@ -666,7 +710,8 @@ test('local inspection makes no content request or storage write', async ({ page
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(viewer(page)).toHaveCount(0);
|
||||
}
|
||||
const network = requests.filter(entry => !entry.url.startsWith('blob:') && !entry.url.startsWith('data:'));
|
||||
const network = requests.slice(before).filter(entry => !entry.url.startsWith('blob:') && !entry.url.startsWith('data:'));
|
||||
expect(requests.filter(entry => table.test(entry.url)), 'the table is read once per page').toHaveLength(1);
|
||||
expect(network.filter(entry => /private|lighthouse|fox/.test(`${entry.url} ${entry.body ?? ''}`))).toEqual([]);
|
||||
expect(network.filter(entry => entry.method !== 'GET')).toEqual([]);
|
||||
expect(network.filter(entry => !/\/prompt_manager\/(activity|images\/output|library|vocabulary)/.test(entry.url))).toEqual([]);
|
||||
@@ -685,3 +730,80 @@ test('touch layout at 390 has no horizontal overflow at 200% zoom', async ({ pag
|
||||
expect(area).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
// LI-4 (D117): "Copy settings summary" after the six facts is the legacy metadata page's COPY ALL, in the shared full
|
||||
// inspector, so a file served in Images and the same bytes chosen here copy the same summary of what the rail shows.
|
||||
/** Records clipboard writes in the page, or (`clipboard: false`) leaves the page without a clipboard. */
|
||||
async function stubClipboard(page, { clipboard = true } = {}) {
|
||||
await page.addInitScript(available => {
|
||||
window.__copied = [];
|
||||
Object.defineProperty(navigator, 'clipboard', { configurable: true,
|
||||
value: available ? { writeText: async text => { window.__copied.push(text); } } : undefined });
|
||||
}, clipboard);
|
||||
}
|
||||
/** The summary the rail's own prompts and facts make, in the legacy COPY ALL lines and placeholders. */
|
||||
const expectedSummary = locator => locator.evaluate(node => {
|
||||
const facts = Object.fromEntries([...node.querySelectorAll(':scope .meta-grid:not(details .meta-grid) > div')]
|
||||
.map(item => [item.querySelector('dt').textContent, item.querySelector('dd').textContent]));
|
||||
// A confirmed prompt has its Copy action; an explicitly empty one takes the legacy placeholder too.
|
||||
const prompt = role => {
|
||||
const text = node.querySelector(`.prompt-section.${role} [data-copy-role]`) ? node.querySelector(`.prompt-section.${role} p.prompt-text`).textContent : null;
|
||||
return text === `No ${role} prompt (explicitly empty)` ? null : text;
|
||||
};
|
||||
return [`Checkpoint: ${facts.Model}`, `Positive Prompt: ${prompt('positive') ?? 'No prompt found'}`,
|
||||
`Negative Prompt: ${prompt('negative') ?? 'No negative prompt found'}`, `Steps: ${facts.Steps}`, `CFG Scale: ${facts.CFG}`,
|
||||
`Sampler: ${facts.Sampler}`, `Seed: ${facts.Seed}`].join('\n');
|
||||
});
|
||||
async function copySummary(page) {
|
||||
const button = rail(page).getByRole('button', { name: 'Copy settings summary', exact: true });
|
||||
// It follows the six facts, before "File & provenance".
|
||||
expect(await button.evaluate(node => [node.previousElementSibling?.localName, node.nextElementSibling?.localName])).toEqual(['dl', 'details']);
|
||||
await button.click();
|
||||
}
|
||||
|
||||
test('Copy settings summary copies the same legacy summary in Images and Inspect', async ({ page, request }) => {
|
||||
await stubClipboard(page);
|
||||
await expect(await request.post('/__test__/add-local-inspect-file', { data: { name: 'f02.png' } })).toBeOK();
|
||||
await page.goto(`${workspace}#/images`);
|
||||
await page.locator('article[data-image-key="0:local-inspect/f02.png"] .image-open').click();
|
||||
await expect(rail(page).locator('.prompt-section.positive p.prompt-text')).toBeVisible();
|
||||
const served = await expectedSummary(rail(page));
|
||||
expect(served).toMatch(/^Checkpoint: .+\nPositive Prompt: [\s\S]+\nNegative Prompt: [\s\S]+\nSteps: .+\nCFG Scale: .+\nSampler: .+\nSeed: .+$/);
|
||||
expect(served).not.toContain('Unknown');
|
||||
await copySummary(page);
|
||||
await expect(page.locator('#workspace-toast')).toHaveText('Settings summary copied.');
|
||||
expect(await page.evaluate(() => window.__copied)).toEqual([served]);
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(viewer(page)).toHaveCount(0);
|
||||
|
||||
await openInspect(page);
|
||||
await choose(page, parityPng('f02.png'));
|
||||
await openViewer(page);
|
||||
expect(await expectedSummary(rail(page))).toBe(served);
|
||||
await copySummary(page);
|
||||
await expect.poll(() => page.evaluate(() => window.__copied)).toEqual([served, served]);
|
||||
// The panel variant (the Images side panel) keeps the concept's footer: no summary action there.
|
||||
await page.keyboard.press('Escape');
|
||||
await page.goto(`${workspace}#/images`);
|
||||
await expect(page.locator('#image-inspector .panel-heading')).toBeVisible();
|
||||
await expect(page.locator('#image-inspector').getByRole('button', { name: 'Copy settings summary', exact: true })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('Copy settings summary without a clipboard opens the select-to-copy dialog', async ({ page }) => {
|
||||
await stubClipboard(page, { clipboard: false });
|
||||
await openInspect(page);
|
||||
await choose(page, sendablePng());
|
||||
await openViewer(page);
|
||||
const summary = await expectedSummary(rail(page));
|
||||
expect(summary).toContain(`Positive Prompt: ${POSITIVE_LINES}`);
|
||||
await copySummary(page);
|
||||
const fallback = page.getByRole('dialog', { name: 'Copy settings summary', exact: true });
|
||||
await expect(fallback).toBeVisible();
|
||||
await expect(fallback.getByRole('textbox', { name: 'Select and copy this text', exact: true })).toHaveValue(summary);
|
||||
await expect(fallback.getByRole('textbox', { name: 'Select and copy this text', exact: true })).toBeFocused();
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(fallback).toHaveCount(0);
|
||||
// Escape closes only the copy dialog; focus returns to the action in the still-open viewer.
|
||||
await expect(viewer(page)).toBeVisible();
|
||||
await expect(rail(page).getByRole('button', { name: 'Copy settings summary', exact: true })).toBeFocused();
|
||||
});
|
||||
|
||||
@@ -610,7 +610,9 @@ test('card matches the concept and never wraps the category mid-word',async({pag
|
||||
await expect(await request.post('/prompt_manager/bulk/category',{data:{prompt_ids:[dual.id],category:''}})).toBeOK();
|
||||
// A long saved title fills the title row, so only the chip's own min-content keeps "Uncategorized" and "asian" whole.
|
||||
const wide='A remarkably long saved positive prompt title that fills the whole card title row';
|
||||
await patchShelf(page,item=>item.id===cat.id?{run_count:4,last_used_at:new Date().toISOString(),rating:5}:item.id===dual.id||item.id===dog.id?{title:wide,run_count:1,last_used_at:null,rating:null}:{});
|
||||
// One "now" for the patched last use and the page's clock, so it reads "Used today" on either side of midnight.
|
||||
const usedAt=new Date();await page.clock.setFixedTime(usedAt);
|
||||
await patchShelf(page,item=>item.id===cat.id?{run_count:4,last_used_at:usedAt.toISOString(),rating:5}:item.id===dual.id||item.id===dog.id?{title:wide,run_count:1,last_used_at:null,rating:null}:{});
|
||||
for(const [width,height] of [[1600,1100],[390,844]]) {
|
||||
await page.setViewportSize({width,height});await page.goto(route);await expect(cards(page)).toHaveCount(3);
|
||||
const card=page.locator(`article[data-prompt-id="${cat.id}"]`);
|
||||
|
||||
@@ -340,6 +340,9 @@ test('Tag opens the dialog without selecting the card', async ({ page }) => {
|
||||
const panel = page.getByRole('complementary', { name: 'Selected image details', exact: true });
|
||||
await page.goto(images);
|
||||
await expect(card(page, FIRST)).toHaveClass(/\bselected\b/);
|
||||
// Capture the panel once it shows the first card's details, not while it is still reading them.
|
||||
await expect(panel.getByRole('heading', { level: 2 })).toBeVisible();
|
||||
await expect(panel).not.toContainText('Loading file details');
|
||||
const before = await panel.innerText();
|
||||
await openTag(page, SECOND, { goto: false });
|
||||
await page.keyboard.press('Escape');
|
||||
|
||||
@@ -11,6 +11,7 @@ the same sidebar counts (24 images, 6 prompts, 15 tags). Nothing is mocked.
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import datetime
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
@@ -157,6 +158,8 @@ CONCEPT_MODEL = "illustrative-model.safetensors"
|
||||
MAX_EXTRA_IMAGES = 120
|
||||
# Unlinked, seedless images (D11 "W × H · PNG") newer than the concept's, for D3 checks.
|
||||
MAX_SEEDLESS_IMAGES = 2
|
||||
# A test's chosen "now" (epoch seconds) stays before the year 3000.
|
||||
MAX_EPOCH_SECONDS = 32_503_680_000
|
||||
SEEDLESS_SIZE = (1536, 1152)
|
||||
# The same 4:3 shape with a short "96 × 72 · PNG" subtitle that stays on one line at
|
||||
# 390px beside the card's Info and Tag (the D3 footer check).
|
||||
@@ -342,6 +345,17 @@ def _bounded(name: str, value: int, maximum: int) -> None:
|
||||
raise ValueError(f"{name} is out of range")
|
||||
|
||||
|
||||
def _instant(now: float | None) -> float:
|
||||
"""The fixture's one "now": ``now`` itself, or the wall clock when omitted."""
|
||||
if now is None:
|
||||
return time.time()
|
||||
if isinstance(now, bool) or not isinstance(now, (int, float)):
|
||||
raise TypeError("now must be a number of epoch seconds")
|
||||
if not 0 < now < MAX_EPOCH_SECONDS:
|
||||
raise ValueError("now is out of range")
|
||||
return float(now)
|
||||
|
||||
|
||||
def seed_workspace_concept(
|
||||
api: PromptManagerAPI,
|
||||
root: Path,
|
||||
@@ -349,9 +363,16 @@ def seed_workspace_concept(
|
||||
extra_images: int = 0,
|
||||
seedless_images: int = 0,
|
||||
short_seedless: bool = False,
|
||||
now: float | None = None,
|
||||
) -> dict:
|
||||
"""Replace this server's disposable rows and files with the concept's data.
|
||||
|
||||
Every relative time the fixture writes (the prompts' last use, the files'
|
||||
mtimes, the runs' observation times) is taken from one instant, ``now``
|
||||
(epoch seconds, the wall clock when omitted), returned as ``manifest["now"]``.
|
||||
A browser whose clock is fixed at that instant reads the concept's "Used
|
||||
today" and caption day however close to midnight the run starts.
|
||||
|
||||
``extra_images`` continues the concept's rounds (same prompts, dimensions and
|
||||
seed rule) after its 24 images, for bounded-rendering and Load more checks.
|
||||
``seedless_images`` adds unlinked PNGs without metadata, newest of all;
|
||||
@@ -361,6 +382,10 @@ def seed_workspace_concept(
|
||||
raise TypeError("short_seedless must be a boolean")
|
||||
_bounded("extra_images", extra_images, MAX_EXTRA_IMAGES)
|
||||
_bounded("seedless_images", seedless_images, MAX_SEEDLESS_IMAGES)
|
||||
now = _instant(now)
|
||||
used_at = datetime.datetime.fromtimestamp(now, datetime.timezone.utc).isoformat(
|
||||
timespec="microseconds"
|
||||
)
|
||||
_clear(api, root)
|
||||
db = api.db
|
||||
epoch = db.get_execution_epoch()
|
||||
@@ -385,8 +410,15 @@ def seed_workspace_concept(
|
||||
db.update_prompt_pair_metadata(pair_ids[0], title=first_name)
|
||||
for name, text in prompt.negatives[1:]:
|
||||
pair_ids.append(db.save_prompt_pair(prompt.positive, text, title=name))
|
||||
# Real queue-hook counting (D23): four runs, the last one now.
|
||||
# Real queue-hook counting (D23): four runs, the last one now, at the
|
||||
# fixture's own instant rather than the database's later wall clock.
|
||||
db.record_prompt_use(positive_id, times=CONCEPT_RUN_COUNT)
|
||||
with db.model.get_connection() as conn:
|
||||
conn.execute(
|
||||
"UPDATE prompts SET last_used_at = ? WHERE id = ?",
|
||||
(used_at, positive_id),
|
||||
)
|
||||
conn.commit()
|
||||
prompts.insert(
|
||||
0, {"id": prompt.id, "positive_id": positive_id, "pair_ids": pair_ids}
|
||||
)
|
||||
@@ -400,7 +432,6 @@ def seed_workspace_concept(
|
||||
favorite_root = _favorite_root_key(list(api._get_all_output_dirs())[0])
|
||||
total = len(CONCEPT_PROMPTS) * CONCEPT_IMAGE_ROUNDS + extra_images
|
||||
rounds = math.ceil(total / len(CONCEPT_PROMPTS))
|
||||
now = time.time()
|
||||
images, runs = [], []
|
||||
slots = [
|
||||
(round_index, prompt_index, prompt)
|
||||
@@ -484,6 +515,8 @@ def seed_workspace_concept(
|
||||
api.invalidate_gallery_cache()
|
||||
return {
|
||||
"epoch": epoch,
|
||||
# The fixture's "now" (epoch seconds), for the browser's fixed clock.
|
||||
"now": now,
|
||||
# The newest file's mtime (epoch seconds), for the D17 caption date.
|
||||
"newest_modified": now - 10 if seedless_images else now - 60,
|
||||
"seedless": seedless,
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -14,6 +14,11 @@
|
||||
// the carrier rule alone, as the server selects from ffprobe's tag map.
|
||||
// A {records} entry (records null = an unreadable file) answers
|
||||
// {classified: null, result: null, metadata} for the projection alone.
|
||||
// A {mode: 'resolve'} entry (PR L3) answers {evidence}: resolveLocalEvidence of its {records} texts
|
||||
// with the repository semantics table. With a {path} it reads the file locally and also answers
|
||||
// {facts} (and {unreadable: true} with the server's unreadable evidence when nothing could be read):
|
||||
// extractGenerationFacts on the local payload through projectInspectionPayload, exactly as
|
||||
// tests/js/support/inspection-parity-facts.mjs reads the server's response for vectors.json.
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { createRequire } from 'node:module';
|
||||
@@ -28,6 +33,22 @@ const web = path.join(here, '..', '..', '..', 'web', 'js', 'workspace');
|
||||
const { selectVideoCarrier } = await import(moduleUrl(path.join(web, 'local-video.mjs')));
|
||||
const { projectMetadata } = await import(moduleUrl(path.join(web, 'local-projection.mjs')));
|
||||
const { readLocalFile, toInspectionRead } = await import(moduleUrl(path.join(web, 'local-inspection.mjs')));
|
||||
const { resolveLocalEvidence, compileSemantics, unreadableEvidence } = await import(moduleUrl(path.join(web, 'local-resolver.mjs')));
|
||||
const { buildLocalPayload } = await import(moduleUrl(path.join(web, 'local-inspection.mjs')));
|
||||
const { projectInspectionPayload } = await import(moduleUrl(path.join(web, 'inspection-state.mjs')));
|
||||
const semantics = compileSemantics(JSON.parse(fs.readFileSync(path.join(here, '..', '..', '..', 'web', 'js', 'inspection-semantics.json'), 'utf8')));
|
||||
const { extractGenerationFacts } = require(path.join(here, '..', '..', '..', 'web', 'js', 'comfy-metadata.js'));
|
||||
|
||||
/** The local evidence for one set of record texts. */
|
||||
const resolved = records => ({ evidence: resolveLocalEvidence(records, semantics) });
|
||||
|
||||
/** The local wire's evidence and six facts for one read (no legacy fill, as in the vectors' own harness). */
|
||||
function localPayload(read, file, classification) {
|
||||
const payload = buildLocalPayload({ read, file, classification, semantics });
|
||||
const record = projectInspectionPayload(payload, { kind: 'local-file', key: 'local:1', path: file.name }, null, extractGenerationFacts);
|
||||
const facts = Object.fromEntries(Object.entries(record.generation).map(([field, fact]) => [field, { status: fact.status, value: fact.value }]));
|
||||
return { evidence: { prompts: payload.prompts, resolution: payload.resolution }, facts };
|
||||
}
|
||||
|
||||
const selectionRead = (selection) => selection.status === 'complete' ?
|
||||
{ records: selection.records, record_formats: selection.record_formats, carrierText: selection.carrierText, limited: selection.limited } : null;
|
||||
@@ -37,6 +58,19 @@ for await (const chunk of process.stdin) chunks.push(chunk);
|
||||
const output = {};
|
||||
for (const entry of JSON.parse(Buffer.concat(chunks).toString('utf8'))) {
|
||||
const { name } = entry;
|
||||
if (entry.mode === 'resolve') {
|
||||
if (entry.records !== undefined) { output[name] = resolved(entry.records); continue; }
|
||||
const blob = await fs.openAsBlob(entry.path);
|
||||
const { classification, result } = await readLocalFile(blob, { pngMetadata });
|
||||
const read = classification === null ? null : toInspectionRead(classification, result).read;
|
||||
if (classification === null) { output[name] = { unreadable: true }; continue; }
|
||||
// The evidence is the local wire's own (buildLocalPayload), and it equals resolveLocalEvidence of the records.
|
||||
const local = localPayload(result, { name: path.basename(entry.path), size: blob.size }, classification);
|
||||
const direct = read === null ? unreadableEvidence() : resolved(read.records).evidence;
|
||||
if (JSON.stringify(direct) !== JSON.stringify(local.evidence)) throw new Error(`${name}: the wire's roles are not the resolver's`);
|
||||
output[name] = read === null ? { unreadable: true, ...local } : local;
|
||||
continue;
|
||||
}
|
||||
if (entry.records !== undefined) {
|
||||
const read = entry.records === null ? null : {
|
||||
records: entry.records,
|
||||
|
||||
@@ -215,3 +215,151 @@ test('none and unavailable render no image chips', async () => {
|
||||
assert.deepEqual(inspectorTagChips(tagged({state, tags:[]}, {status:'none', tags:[], tags_scope:null}), {filterable:true}), []);
|
||||
}
|
||||
});
|
||||
|
||||
// LI-4 (D117): "Copy settings summary" after the six facts of the full inspector consolidates the legacy metadata
|
||||
// page's COPY ALL (web/metadata.html copyAllData). The legacy template is read from that page itself and run on the
|
||||
// legacy parse, so the summary's text is the legacy page's, line for line, wherever the two agree on the values.
|
||||
const METADATA_PAGE = fs.readFileSync(new URL('../../web/metadata.html', import.meta.url), 'utf8');
|
||||
function legacyCopyAll(params) {
|
||||
const template = METADATA_PAGE.match(/const allData = `([\s\S]*?)`;/)[1];
|
||||
return new Function('currentWorkflowData', `return \`${template}\`;`)(params);
|
||||
}
|
||||
const legacyParams = record => ComfyMetadata.extractGenerationParams({prompt:record.metadata.prompt_graph.status === 'parsed' ? record.metadata.prompt_graph.value : null,
|
||||
workflow:record.metadata.workflow_graph.status === 'parsed' ? record.metadata.workflow_graph.value : null});
|
||||
|
||||
/**
|
||||
* Each summary line against the legacy page's, allowing only the recorded differences (D117): a number keeps the
|
||||
* inspector's (the server's) spelling ("8.0" where the legacy page wrote 8); a fact the legacy parse left "Unknown" may
|
||||
* be known; and a negative the #249 ZeroOut guard zeroed reads "No negative prompt found" where the legacy parse read
|
||||
* the positive's text through the zero-out.
|
||||
*/
|
||||
function assertLegacySummary(summary, legacy, record) {
|
||||
const lines = summary.split('\n'), expected = legacy.split('\n');
|
||||
assert.deepEqual(lines.map(line => line.split(':')[0]), expected.map(line => line.split(':')[0]), 'the legacy labels, in order');
|
||||
lines.forEach((line, index) => {
|
||||
if (line === expected[index]) return;
|
||||
const [label, value] = [line.slice(0, line.indexOf(': ')), line.slice(line.indexOf(': ') + 2)];
|
||||
const old = expected[index].slice(label.length + 2);
|
||||
if (label === 'Negative Prompt' && record.prompts.negative?.source === 'zeroed-conditioning' && value === 'No negative prompt found') return;
|
||||
if (old === 'Unknown' && !/Prompt$/.test(label)) return;
|
||||
assert.ok(value.trim() !== '' && Number(value) === Number(old), `${label}: "${value}" differs from the legacy "${old}"`);
|
||||
});
|
||||
}
|
||||
|
||||
test('settings summary is the legacy COPY ALL text for a local file', async () => {
|
||||
const {settingsSummary} = await load();
|
||||
assert.equal(typeof settingsSummary, 'function', 'settingsSummary is exported');
|
||||
const record = await localRecord(localPng('fox.png'));
|
||||
assertLegacySummary(settingsSummary(record), legacyCopyAll(legacyParams(record)), record);
|
||||
assert.equal(settingsSummary(record), ['Checkpoint: synthetic-v1.safetensors', 'Positive Prompt: a red fox in snow, detailed fur',
|
||||
'Negative Prompt: blurry, lowres', 'Steps: 20', 'CFG Scale: 8.0', 'Sampler: euler', 'Seed: 7'].join('\n'));
|
||||
// Every parity PNG read in this browser: the legacy page's text but for the recorded differences, and exactly the
|
||||
// legacy text for most of them (f09 among them: the server is ambiguous, so the record shows the legacy fill).
|
||||
const exact = [];
|
||||
for (const name of fs.readdirSync(PARITY).filter(item => item.endsWith('.png')).sort()) {
|
||||
const parity = await localRecord(new File([fs.readFileSync(new URL(name, PARITY))], name));
|
||||
const summary = settingsSummary(parity), legacy = legacyCopyAll(legacyParams(parity));
|
||||
assertLegacySummary(summary, legacy, parity);
|
||||
if (summary === legacy) exact.push(name);
|
||||
}
|
||||
assert.ok(exact.includes('f09.png'));
|
||||
assert.deepEqual(fs.readdirSync(PARITY).filter(item => item.endsWith('.png') && !exact.includes(item)).sort(), ['f01b.png', 'f17.png', 'f23.png']);
|
||||
});
|
||||
|
||||
test('settings summary uses the legacy placeholders for what the record does not know', async () => {
|
||||
const {settingsSummary} = await load();
|
||||
const unknown = {...record(), prompts:{positive:{status:'unresolved'}, negative:{status:'ambiguous'}}, generation:{}};
|
||||
assert.equal(settingsSummary(unknown), legacyCopyAll({}).replace('Positive Prompt: undefined', 'Positive Prompt: No prompt found')
|
||||
.replace('Negative Prompt: undefined', 'Negative Prompt: No negative prompt found'));
|
||||
assert.equal(settingsSummary(unknown), ['Checkpoint: Unknown', 'Positive Prompt: No prompt found', 'Negative Prompt: No negative prompt found',
|
||||
'Steps: Unknown', 'CFG Scale: Unknown', 'Sampler: Unknown', 'Seed: Unknown'].join('\n'));
|
||||
// A server answer is shown as the inspector shows it: known facts verbatim, every other state the legacy "Unknown".
|
||||
const server = {...record(), prompts:{positive:{status:'resolved', text:'a\n猫'}, negative:{status:'resolved', text:''}}, generation:{
|
||||
model:{status:'known', value:'m.safetensors'}, steps:{status:'not-recorded', value:null}, cfg:{status:'known', value:'6.50'},
|
||||
sampler:{status:'ambiguous', value:null}, seed:{status:'known', value:'9007199254740993'}, scheduler:{status:'known', value:'karras'}}};
|
||||
assert.equal(settingsSummary(server), ['Checkpoint: m.safetensors', 'Positive Prompt: a\n猫', 'Negative Prompt: No negative prompt found',
|
||||
'Steps: Unknown', 'CFG Scale: 6.50', 'Sampler: Unknown', 'Seed: 9007199254740993'].join('\n'));
|
||||
});
|
||||
|
||||
/** The full inspector with a toast node and `clipboard` as `navigator.clipboard`; returns the summary button. */
|
||||
function renderSummary(record, {variant = 'full', clipboard} = {}) {
|
||||
const f = mountedDom(), scope = createScope(), fallbacks = [], toast = new f.Node('div');
|
||||
f.doc.getElementById = id => id === 'workspace-toast' ? toast : null;
|
||||
const previous = Object.getOwnPropertyDescriptor(globalThis, 'navigator');
|
||||
Object.defineProperty(globalThis, 'navigator', {configurable:true, value:clipboard === undefined ? {} : {clipboard}});
|
||||
const view = mountFileInspector(f.container, {sender:{open() {}}, parentScope:scope, variant, copyFallback:(text, options) => fallbacks.push({text, ...options})});
|
||||
view.setState({loading:false, error:false, record});
|
||||
const button = f.walk(f.container, n => n.tagName === 'button' && n.textContent === 'Copy settings summary')[0] ?? null;
|
||||
return {f, button, toast, fallbacks, scope, done() {
|
||||
view.dispose(); scope.dispose(); f.restore();
|
||||
if (previous) Object.defineProperty(globalThis, 'navigator', previous); else delete globalThis.navigator;
|
||||
}};
|
||||
}
|
||||
|
||||
test('Copy settings summary follows the facts in the full inspector only', async () => {
|
||||
const full = renderSummary(record());
|
||||
try {
|
||||
assert.ok(full.button, 'the full inspector offers Copy settings summary');
|
||||
const inner = full.button.parent, index = inner.children.indexOf(full.button);
|
||||
assert.equal(inner.children[index - 1].tagName, 'dl', 'it follows the six facts');
|
||||
assert.equal(inner.children[index + 1].tagName, 'details', 'File & provenance follows it');
|
||||
// M7: the D117 wrap rule targets this button by its class, never any button of a details block.
|
||||
assert.equal(full.button.className, 'settings-summary');
|
||||
} finally { full.done(); }
|
||||
const panel = renderSummary(record(), {variant:'panel'});
|
||||
try { assert.equal(panel.button, null, 'the Images side panel keeps the concept footer'); } finally { panel.done(); }
|
||||
});
|
||||
|
||||
test('Copy settings summary copies the summary and shows the shared toast', async () => {
|
||||
const {settingsSummary} = await load(), copied = [];
|
||||
const view = renderSummary(record(), {clipboard:{writeText:async text => {copied.push(text);}}});
|
||||
try {
|
||||
await view.button.listeners.get('click')[0].callback({target:view.button});
|
||||
assert.deepEqual(copied, [settingsSummary(record())]);
|
||||
assert.equal(view.toast.textContent, 'Settings summary copied.');
|
||||
assert.equal(view.fallbacks.length, 0);
|
||||
} finally { view.done(); }
|
||||
});
|
||||
|
||||
test('Copy settings summary without a clipboard opens the select-to-copy fallback', async () => {
|
||||
const {settingsSummary} = await load();
|
||||
for (const clipboard of [undefined, {writeText:async () => {throw new Error('Denied');}}]) {
|
||||
const view = renderSummary(record(), {clipboard});
|
||||
try {
|
||||
await view.button.listeners.get('click')[0].callback({target:view.button});
|
||||
assert.equal(view.fallbacks.length, 1);
|
||||
assert.equal(view.fallbacks[0].text, settingsSummary(record()));
|
||||
assert.equal(view.fallbacks[0].title, 'Copy settings summary');
|
||||
assert.equal(view.fallbacks[0].trigger, view.button);
|
||||
assert.notEqual(view.toast.textContent, 'Settings summary copied.');
|
||||
} finally { view.done(); }
|
||||
}
|
||||
});
|
||||
|
||||
test('the inspector is busy while a read is loading, then not', async () => {
|
||||
const f = mountedDom(), scope = createScope();
|
||||
const view = mountFileInspector(f.container, {sender:{open() {}}, parentScope:scope, variant:'full'});
|
||||
try {
|
||||
view.setState({loading:true, error:false, record:null});
|
||||
assert.equal(f.container.getAttribute('aria-busy'), 'true');
|
||||
assert.ok(f.walk(f.container, n => n.textContent === 'Loading file details…').length);
|
||||
view.setState({loading:false, error:false, record:record()});
|
||||
assert.equal(f.container.getAttribute('aria-busy'), null);
|
||||
view.setState({loading:true, error:false, record:null});
|
||||
view.setState({loading:false, error:true, record:null});
|
||||
assert.equal(f.container.getAttribute('aria-busy'), null);
|
||||
view.setState({loading:true, error:false, record:null});
|
||||
} finally {
|
||||
view.dispose();
|
||||
assert.equal(f.container.getAttribute('aria-busy'), null, 'dispose clears the busy state');
|
||||
scope.dispose(); f.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('the D117 wrap rule targets only the settings summary button', async () => {
|
||||
const fs = await import('node:fs');
|
||||
const css = fs.readFileSync(new URL('../../web/js/workspace/workspace.css', import.meta.url), 'utf8');
|
||||
const rules = css.split('\n').filter(line => line.includes('D117'));
|
||||
assert.deepEqual(rules.map(line => line.trim()), ['.ca-tools #viewer-details .settings-summary { white-space: normal; /* D117 */ }']);
|
||||
assert.doesNotMatch(css, /#viewer-details > div > button/);
|
||||
});
|
||||
|
||||
@@ -20,6 +20,16 @@ const { extractGenerationFacts } = ComfyMetadata;
|
||||
// The page loads both as scripts; the legacy fill and the PNG reader find them on the global.
|
||||
globalThis.PngMetadata = PngMetadata;
|
||||
globalThis.ComfyMetadata = ComfyMetadata;
|
||||
// The page's API client and the node table it serves (local-semantics.mjs fetches it once).
|
||||
const SEMANTICS = fs.readFileSync(path.join(here, "..", "..", "web", "js", "inspection-semantics.json"), "utf8");
|
||||
globalThis.window = { ApiClient: { resolveUrl: (value) => value } };
|
||||
// A test can hold the table request (`tableGate`) to stand for a slow or stalled proxy.
|
||||
let tableGate = null;
|
||||
globalThis.fetch = async (url) => {
|
||||
if (url !== "/prompt_manager/js/inspection-semantics.json") throw new Error(`unexpected request ${url}`);
|
||||
if (tableGate) await tableGate;
|
||||
return new Response(SEMANTICS, { status: 200 });
|
||||
};
|
||||
const m = await import("../../web/js/workspace/local-inspection.mjs").catch((error) => {
|
||||
if (error.code !== "ERR_MODULE_NOT_FOUND") throw error;
|
||||
return {};
|
||||
@@ -59,6 +69,37 @@ test("contract", () => {
|
||||
assert.ok(Object.isFrozen(m.localFileAdapter));
|
||||
});
|
||||
|
||||
// M3: the first read waits for the page's one table request; an aborted, replaced or cleared selection must not.
|
||||
test("a read waiting for the node table ends with its selection", async () => {
|
||||
let release;
|
||||
tableGate = new Promise((resolve) => { release = resolve; });
|
||||
try {
|
||||
const file = pngFile("slow.png", [tEXt("prompt", PROMPT)]);
|
||||
const aborted = new AbortController();
|
||||
const reading = m.localFileAdapter.read(await handleFor(file), { signal: aborted.signal });
|
||||
const settled = (promise) => Promise.race([promise.then(() => "resolved", (error) => error.name), new Promise((resolve) => setTimeout(() => resolve("pending"), 200))]);
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
aborted.abort();
|
||||
assert.equal(await settled(reading), "AbortError");
|
||||
// Through the controller: clearing the selection ends its read; nothing is published for it.
|
||||
const controller = createInspectionController({ api: null, adapter: m.localFileAdapter, extractFacts: extractGenerationFacts });
|
||||
const states = [];
|
||||
controller.subscribe((state) => states.push(state));
|
||||
const selected = controller.select(await handleFor(file));
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
controller.clear();
|
||||
assert.equal(await settled(selected), "resolved");
|
||||
assert.ok(states.every((state) => state.record === null && state.error === false), "no record or error for a cleared selection");
|
||||
controller.dispose();
|
||||
} finally {
|
||||
tableGate = null;
|
||||
release();
|
||||
}
|
||||
// The shared request still lands for the next selection.
|
||||
const { wire } = await recordFor(pngFile("next.png", [tEXt("prompt", PROMPT)]));
|
||||
assert.equal(wire.resolution.state, "resolved");
|
||||
});
|
||||
|
||||
test("a PNG File becomes the server-shaped wire with local provenance", async () => {
|
||||
const file = pngFile("Fox Render.PNG", [tEXt("prompt", PROMPT), tEXt("workflow", WORKFLOW)]);
|
||||
const { wire, record, handle } = await recordFor(file);
|
||||
@@ -66,8 +107,12 @@ test("a PNG File becomes the server-shaped wire with local provenance", async ()
|
||||
size: file.size, width: 640, height: 480, modified_time: 1_700_000_000.123 });
|
||||
assert.equal(wire.success, true);
|
||||
assert.equal(wire.inspection_version, 1);
|
||||
assert.deepEqual(wire.prompts, { positive: { status: "unresolved" }, negative: { status: "unresolved" } });
|
||||
assert.deepEqual(wire.resolution, { state: "unresolved", sampler_id: null, reason: "Resolved in this browser from the workflow.", reason_code: null, node: null });
|
||||
// The roles the server's inspector resolves for the same records (local-resolver.mjs).
|
||||
assert.deepEqual(wire.prompts, {
|
||||
positive: { status: "resolved", text: "a red fox in snow, detailed fur", source: "graph-inferred" },
|
||||
negative: { status: "resolved", text: "blurry, lowres", source: "graph-inferred" },
|
||||
});
|
||||
assert.deepEqual(wire.resolution, { state: "resolved", sampler_id: "3", reason: "", reason_code: null, node: null });
|
||||
assert.deepEqual(wire.library, { status: "unavailable", scope: "saved-library", tags: [], category_scope: null, tags_scope: null });
|
||||
assert.equal(wire.metadata.status, "available");
|
||||
assert.deepEqual(wire.metadata.raw, { prompt: PROMPT, workflow: WORKFLOW });
|
||||
@@ -96,6 +141,33 @@ test("a PNG File becomes the server-shaped wire with local provenance", async ()
|
||||
assert.equal(exported.file.source_label, "Selected local file");
|
||||
});
|
||||
|
||||
test("roles answer as the server's inspector: unreadable, unavailable table, ambiguous", async () => {
|
||||
const png = { media: "image", kind: "png" };
|
||||
const unreadable = m.buildLocalPayload({ read: null, file: { name: "a.png" }, classification: png });
|
||||
assert.deepEqual(unreadable.resolution, { state: "unresolved", sampler_id: null, reason: "Media metadata could not be read", reason_code: null, node: null });
|
||||
assert.equal(unreadable.prompts.positive.message, "Metadata in this file could not be read.");
|
||||
const records = { prompt: PROMPT };
|
||||
const read = { status: "complete", records, limited: [], width: 2, height: 3 };
|
||||
// Without a table (it could not be fetched) the roles stay open, with the server's own line.
|
||||
const missing = m.buildLocalPayload({ read, file: { name: "a.png" }, classification: png });
|
||||
assert.equal(missing.resolution.reason, "Inspection node semantics are unavailable");
|
||||
assert.equal(missing.prompts.positive.message, "The inspector's node table is unavailable.");
|
||||
const semantics = await (await import("../../web/js/workspace/local-semantics.mjs")).loadInspectionSemantics();
|
||||
const graph = JSON.parse(PROMPT);
|
||||
graph["9"] = { ...graph["3"], inputs: { ...graph["3"].inputs, positive: ["8", 0] } };
|
||||
graph["8"] = { class_type: "CLIPTextEncode", inputs: { text: "a cat", clip: ["4", 1] } };
|
||||
const several = m.buildLocalPayload({ read: { ...read, records: { prompt: JSON.stringify(graph) } }, file: { name: "a.png" }, classification: png, semantics });
|
||||
assert.equal(several.resolution.reason, "Multiple sampler branches");
|
||||
assert.deepEqual(several.prompts.positive, { status: "ambiguous", text: null, source: null });
|
||||
// The legacy fill then applies exactly as it does to the server's answer for the same bytes in Images.
|
||||
const handle = await handleFor(pngFile("grid.png", [tEXt("prompt", JSON.stringify(graph))]));
|
||||
const local = m.localFileAdapter.toRecord(several, handle, extractGenerationFacts);
|
||||
const asServed = { ...several, file: { ...several.file, observation: "current-file", source_label: "output" } };
|
||||
const served = projectInspectionPayload(asServed, { kind: "rooted-file", key: "0:grid.png", root_index: 0, path: "grid.png", root_scope: null }, null, extractGenerationFacts);
|
||||
assert.deepEqual(local.prompts, served.prompts);
|
||||
assert.deepEqual(local.generation, served.generation);
|
||||
});
|
||||
|
||||
test("file facts follow the server: extension like Path.suffix, null when unknown", async () => {
|
||||
const cases = [["a.b.PnG", ".png"], [".hidden", ""], ["noext", ""], ["dot.", ""], ["x.tar.gz", ".gz"]];
|
||||
for (const [name, extension] of cases) {
|
||||
@@ -307,3 +379,89 @@ test("the parity corpus PNGs read into renderable records", async () => {
|
||||
assert.ok(["parsed", "limited", "malformed"].includes(wire.metadata.prompt_graph.status));
|
||||
}
|
||||
});
|
||||
|
||||
// M4: resolution runs on the page's main thread, so a read yields between its bounded steps (the busy state paints
|
||||
// and input is handled) and no step may exceed a budget on the largest record the readers keep (2 MiB of roles).
|
||||
const ROLE_BYTES = 2 * 1024 * 1024;
|
||||
// Generous for a shared CI runner: a desktop resolves these in 130-455 ms.
|
||||
const STEP_BUDGET_MS = 2500;
|
||||
const ENCODE = (text) => ({ class_type: "CLIPTextEncode", inputs: { text, clip: ["4", 1] } });
|
||||
const KSAMPLER = (positive, negative, latent) => ({ class_type: "KSampler", inputs: { seed: 1, steps: 20, cfg: 8.0, sampler_name: "euler", scheduler: "normal",
|
||||
denoise: 1.0, model: ["4", 0], positive, negative, latent_image: latent } });
|
||||
const LOADERS = { "4": { class_type: "CheckpointLoaderSimple", inputs: { ckpt_name: "m.safetensors" } }, "5": { class_type: "EmptyLatentImage", inputs: { width: 64, height: 64, batch_size: 1 } } };
|
||||
/** The largest graph of this shape whose JSON fits the role budget. */
|
||||
function maximal(build, high) {
|
||||
let low = 1;
|
||||
while (low < high) {
|
||||
const middle = (low + high + 1) >> 1;
|
||||
if (Buffer.byteLength(JSON.stringify(build(middle)), "utf8") <= ROLE_BYTES) low = middle;
|
||||
else high = middle - 1;
|
||||
}
|
||||
return JSON.stringify(build(low));
|
||||
}
|
||||
const MAXIMAL_GRAPHS = {
|
||||
// Many candidates: every sampler is a final stage with its own pair.
|
||||
independent: maximal((count) => {
|
||||
const graph = { ...LOADERS };
|
||||
for (let index = 0; index < count; index++) {
|
||||
graph[`s${index}`] = KSAMPLER([`p${index}`, 0], [`n${index}`, 0], ["5", 0]);
|
||||
graph[`p${index}`] = ENCODE(`fox ${index}`);
|
||||
graph[`n${index}`] = ENCODE(`blur ${index}`);
|
||||
}
|
||||
return graph;
|
||||
}, 6666),
|
||||
// One long stage chain through the latent: the deepest stage walk.
|
||||
chain: maximal((count) => {
|
||||
const graph = { ...LOADERS, "6": ENCODE("fox"), "7": ENCODE("blur") };
|
||||
for (let index = 0; index < count; index++) graph[`s${index}`] = KSAMPLER(["6", 0], ["7", 0], index ? [`s${index - 1}`, 0] : ["5", 0]);
|
||||
return graph;
|
||||
}, 19996),
|
||||
};
|
||||
|
||||
test("resolution of a maximal 2 MiB graph stays within the step budget", async () => {
|
||||
const { resolveLocalEvidence } = await import("../../web/js/workspace/local-resolver.mjs");
|
||||
const semantics = await (await import("../../web/js/workspace/local-semantics.mjs")).loadInspectionSemantics();
|
||||
for (const [name, prompt] of Object.entries(MAXIMAL_GRAPHS)) {
|
||||
assert.ok(Buffer.byteLength(prompt, "utf8") > ROLE_BYTES - 1024, `${name} fills the role budget`);
|
||||
const started = performance.now();
|
||||
const evidence = resolveLocalEvidence({ prompt }, semantics);
|
||||
const elapsed = performance.now() - started;
|
||||
assert.ok(elapsed < STEP_BUDGET_MS, `${name}: ${Math.round(elapsed)} ms`);
|
||||
assert.notEqual(evidence.resolution.reason_code, "malformed", name);
|
||||
}
|
||||
});
|
||||
|
||||
test("a read yields between bounded steps and answers byte for byte as one synchronous build", async () => {
|
||||
const semantics = await (await import("../../web/js/workspace/local-semantics.mjs")).loadInspectionSemantics();
|
||||
const file = pngFile("maximal.png", [tEXt("prompt", MAXIMAL_GRAPHS.independent)]);
|
||||
const handle = await handleFor(file);
|
||||
const marks = [];
|
||||
const yieldControl = async (signal) => {
|
||||
signal?.throwIfAborted();
|
||||
marks.push(performance.now());
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
};
|
||||
const started = performance.now();
|
||||
const wire = await m.localFileAdapter.read(handle, { signal: new AbortController().signal, yieldControl });
|
||||
marks.push(performance.now());
|
||||
// Resolution and the projection each run in a turn of their own after the table is in.
|
||||
assert.ok(marks.length >= 3, `yields: ${marks.length - 1}`);
|
||||
const gaps = marks.map((mark, index) => mark - (index ? marks[index - 1] : started));
|
||||
assert.ok(Math.max(...gaps) < STEP_BUDGET_MS, `longest step ${Math.round(Math.max(...gaps))} ms`);
|
||||
const { result } = await m.readLocalFile(file, { classification: handle.classification });
|
||||
const direct = await m.fitLocalPayload(m.buildLocalPayload({ read: result, file: { name: handle.filename, size: file.size, lastModified: file.lastModified },
|
||||
classification: handle.classification, semantics }));
|
||||
assert.equal(JSON.stringify(wire), JSON.stringify(direct));
|
||||
assert.equal(wire.resolution.state, "ambiguous");
|
||||
// An abort at any yield ends the read there.
|
||||
for (let stop = 0; stop < marks.length - 1; stop++) {
|
||||
const controller = new AbortController();
|
||||
let seen = 0;
|
||||
const stopping = async (signal) => {
|
||||
if (seen++ === stop) controller.abort();
|
||||
signal.throwIfAborted();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
};
|
||||
await assert.rejects(m.localFileAdapter.read(handle, { signal: controller.signal, yieldControl: stopping }), { name: "AbortError" }, `yield ${stop}`);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
// PR L3 Tasks 8-9: the server's inspection resolver in this browser. The values below are what CPython answers
|
||||
// (json.loads, len, str.strip, repr, utils/prompt_inspector.inspect_prompt_evidence); the full comparison with the
|
||||
// server runs in tests/test_local_inspect_parity.py through tests/js/support/local-inspect-oracle.mjs.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
|
||||
const py = await import('../../web/js/workspace/py-json.mjs');
|
||||
const resolver = await import('../../web/js/workspace/local-resolver.mjs');
|
||||
const semantics = resolver.compileSemantics(JSON.parse(fs.readFileSync(new URL('../../web/js/inspection-semantics.json', import.meta.url), 'utf8')));
|
||||
|
||||
test('json.loads keeps Python value kinds and dict order', () => {
|
||||
const value = py.pyJsonLoads('{"9": 1, "10": 1.0, "a": NaN, "9": [true, -0, 9007199254740993, -Infinity]}');
|
||||
assert.ok(value instanceof Map);
|
||||
// A repeated key keeps its first position and takes its last value; integer-like keys keep text order.
|
||||
assert.deepEqual([...value.keys()], ['9', '10', 'a']);
|
||||
const [flag, zero, big, negative] = value.get('9');
|
||||
assert.equal(flag, true); assert.equal(zero, 0); assert.equal(big, 9007199254740993n);
|
||||
assert.ok(negative instanceof py.PyFloat); assert.equal(negative.value, -Infinity);
|
||||
assert.ok(value.get('10') instanceof py.PyFloat, '1.0 is a float, not an int');
|
||||
assert.ok(Number.isNaN(value.get('a').value));
|
||||
assert.equal(py.isInt(value.get('10')), false);
|
||||
assert.equal(py.pyJsonLoads('"\\ud83d\\ude00\\ud800"'), '\u{1f600}\ud800');
|
||||
for (const bad of ['{}', '{"a":1,}', '[01]', '{"a" 1}', '"\u0001"', '"\\x"', '1 2', '-', `${'9'.repeat(4301)}`, '"\\ud800\\uzzzz"']) {
|
||||
assert.throws(() => py.pyJsonLoads(bad), py.PyValueError, bad);
|
||||
}
|
||||
assert.equal(py.pyJsonLoads(` ${'9'.repeat(4300)}\n`), BigInt('9'.repeat(4300)));
|
||||
});
|
||||
|
||||
// One depth cap for both browser CPython-JSON parsers (py-json.mjs here, local-video.mjs for video envelopes): every
|
||||
// array or object counts, an empty one too, as CPython's scanner enters recursion for each; past the cap it refuses.
|
||||
test('json.loads refuses nesting past the shared depth cap, counting every container', () => {
|
||||
const video = import('../../web/js/workspace/local-video.mjs');
|
||||
assert.equal(py.JSON_MAX_DEPTH, 1000);
|
||||
const nest = (depth, inner = '') => '['.repeat(depth) + inner + ']'.repeat(depth);
|
||||
const objects = (depth, inner) => '{"a":'.repeat(depth) + inner + '}'.repeat(depth);
|
||||
for (const text of [nest(1000), nest(1000, '1'), nest(999, '{}'), objects(1000, '1'), objects(999, '[]')]) assert.doesNotThrow(() => py.pyJsonLoads(text));
|
||||
for (const text of [nest(1001), nest(1001, '1'), nest(1000, '{}'), objects(1001, '1'), objects(1000, '[]')]) {
|
||||
assert.throws(() => py.pyJsonLoads(text), py.PyValueError);
|
||||
}
|
||||
return video.then(({ pythonJsonLoads, PythonJsonError }) => {
|
||||
for (const text of [nest(1000), nest(1000, '1'), objects(999, '[]')]) assert.doesNotThrow(() => pythonJsonLoads(text));
|
||||
for (const text of [nest(1001), nest(1001, '1'), objects(1000, '[]')]) {
|
||||
assert.throws(() => pythonJsonLoads(text), error => error instanceof PythonJsonError && error.recursion === true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test('str helpers measure, slice and strip as CPython', () => {
|
||||
assert.equal(py.pyLen('a\u{1f600}\ud800'), 3);
|
||||
assert.equal(py.pySlice('\u{1f600}\u{1f600}x', 2), '\u{1f600}\u{1f600}');
|
||||
// str.isspace() includes \x1c-\x1f and \x85 and excludes , unlike String.prototype.trim.
|
||||
assert.equal(py.pyStrip('\x1c\x85 a b \x1f'), 'a b');
|
||||
assert.equal(py.pyStrip('a'), 'a');
|
||||
assert.deepEqual([1.0, 0.0001, 1e-5, 1e16, 123456789012345.6, -2.5, 1e22].map(py.pyFloatRepr),
|
||||
['1.0', '0.0001', '1e-05', '1e+16', '123456789012345.6', '-2.5', '1e+22']);
|
||||
assert.deepEqual([null, true, 0, 1n, new py.PyFloat(2), '', [], new Map()].map(py.pyTruthy), [false, true, false, true, true, false, false, false]);
|
||||
assert.deepEqual([1, 1n, true, new py.PyFloat(1), '1', 2].map(py.pyEqualsOne), [true, true, true, true, false, false]);
|
||||
});
|
||||
|
||||
const encode = text => ({class_type: 'CLIPTextEncode', inputs: {text, clip: ['4', 1]}});
|
||||
const sampler = (extra = {}) => ({class_type: 'KSampler', inputs: {seed: 1, positive: ['6', 0], negative: ['7', 0], latent_image: ['5', 0], model: ['4', 0], ...extra}});
|
||||
const base = (nodes = {}) => ({'3': sampler(), '4': {class_type: 'CheckpointLoaderSimple', inputs: {ckpt_name: 'm.safetensors'}},
|
||||
'5': {class_type: 'EmptyLatentImage', inputs: {width: 64, height: 64, batch_size: 1}}, '6': encode('a fox'), '7': encode('blurry'), ...nodes});
|
||||
|
||||
test('a single chain resolves both roles with their sources', () => {
|
||||
const evidence = resolver.resolveLocalEvidence({prompt: JSON.stringify(base())}, semantics);
|
||||
assert.deepEqual(evidence, {
|
||||
prompts: {positive: {status: 'resolved', text: 'a fox', source: 'graph-inferred'}, negative: {status: 'resolved', text: 'blurry', source: 'graph-inferred'}},
|
||||
resolution: {state: 'resolved', sampler_id: '3', reason: '', reason_code: null, node: null},
|
||||
});
|
||||
});
|
||||
|
||||
test('records without roles, malformed text and a missing sampler answer as the server', () => {
|
||||
assert.deepEqual(resolver.resolveLocalEvidence({workflow: '{}'}, semantics).resolution,
|
||||
{state: 'absent', sampler_id: null, reason: 'No parsed prompt metadata', reason_code: null, node: null});
|
||||
const malformed = resolver.resolveLocalEvidence({prompt: '{broken'}, semantics);
|
||||
assert.equal(malformed.resolution.reason, 'Prompt evidence is malformed');
|
||||
assert.equal(malformed.prompts.positive.message, 'Prompt metadata in this file is malformed.');
|
||||
const none = resolver.resolveLocalEvidence({prompt: JSON.stringify({'1': encode('x'), '2': {class_type: 'MySampler', inputs: {positive: ['1', 0]}}})}, semantics);
|
||||
assert.deepEqual(none.resolution, {state: 'unresolved', sampler_id: null, reason: 'No supported sampler pair found (saw MySampler)', reason_code: 'no-sampler', node: null});
|
||||
assert.equal(none.prompts.negative.message, 'No supported sampler was found.');
|
||||
assert.equal(resolver.resolveLocalEvidence({prompt: JSON.stringify(base()), parameters: 'x'}, null).resolution.reason, 'Inspection node semantics are unavailable');
|
||||
});
|
||||
|
||||
test('a float output slot is not a link, and a runtime node is named', () => {
|
||||
const floatSlot = resolver.resolveLocalEvidence({prompt: JSON.stringify(base()).replace('"positive":["6",0]', '"positive":["6",0.0]')}, semantics);
|
||||
assert.deepEqual(floatSlot.resolution, {state: 'unresolved', sampler_id: '3', reason: 'Expected a typed graph link or text input', reason_code: 'malformed', node: null});
|
||||
const runtime = resolver.resolveLocalEvidence({prompt: JSON.stringify(base({'6': {class_type: 'PromptSearchList', inputs: {}}}))}, semantics);
|
||||
assert.deepEqual(runtime.resolution.node, {id: '6', class_type: 'PromptSearchList'});
|
||||
assert.equal(runtime.prompts.positive.message, 'Prompt is chosen at run time (PromptSearchList).');
|
||||
});
|
||||
|
||||
test('execution evidence replaces a PromptManagerPair text when it matches the node inputs', () => {
|
||||
const pair = {class_type: 'PromptManagerPair', inputs: {text: 'fox', negative_text: 'blur', prepend_text: '', append_text: ''}};
|
||||
const record = {text: 'fox', negative_text: 'blur', positive_text: 'fox, executed', negative_effective_text: 'blur', prepend_text: '', append_text: ''};
|
||||
const graph = base({'3': sampler({positive: ['8', 0], negative: ['8', 1]}), '8': pair});
|
||||
const evidence = resolver.resolveLocalEvidence({prompt: JSON.stringify(graph), comfyassets_prompt_pairs: JSON.stringify({version: 1, nodes: {'8': {records: [record]}}})}, semantics);
|
||||
assert.deepEqual(evidence.prompts.positive, {status: 'resolved', text: 'fox, executed', source: 'execution'});
|
||||
const stale = resolver.resolveLocalEvidence({prompt: JSON.stringify(graph), comfyassets_prompt_pairs: JSON.stringify({version: 1, nodes: {'8': {records: [{...record, text: 'other'}]}}})}, semantics);
|
||||
assert.equal(stale.resolution.reason, 'Execution evidence does not match recorded node inputs');
|
||||
});
|
||||
|
||||
test('identical sampler branches resolve to their shared pair, differing ones stay ambiguous (#270)', () => {
|
||||
const shared = resolver.resolveLocalEvidence({prompt: JSON.stringify(base({'9': sampler()}))}, semantics);
|
||||
assert.deepEqual(shared.resolution, {state: 'resolved', sampler_id: null, reason: 'Every sampler branch uses the same prompt pair', reason_code: null, node: null});
|
||||
assert.equal(shared.prompts.positive.text, 'a fox');
|
||||
const differ = resolver.resolveLocalEvidence({prompt: JSON.stringify(base({'9': sampler({positive: ['8', 0]}), '8': encode('a cat')}))}, semantics);
|
||||
assert.deepEqual(differ.resolution, {state: 'ambiguous', sampler_id: null, reason: 'Multiple sampler branches', reason_code: null, node: null});
|
||||
assert.equal(differ.prompts.positive.status, 'ambiguous');
|
||||
});
|
||||
|
||||
test('a detailer stage is compared with the sampler in its image ancestry', () => {
|
||||
const graph = base({'10': {class_type: 'VAEDecode', inputs: {samples: ['3', 0]}}, '8': encode('a cat'), '12': {class_type: 'SaveImage', inputs: {images: ['11', 0]}},
|
||||
'11': {class_type: 'FaceDetailer', inputs: {image: ['10', 0], model: ['4', 0], positive: ['8', 0], negative: ['7', 0]}}});
|
||||
const evidence = resolver.resolveLocalEvidence({prompt: JSON.stringify(graph)}, semantics);
|
||||
assert.deepEqual(evidence.resolution, {state: 'ambiguous', sampler_id: '11', reason: 'Sampler stages have different prompts', reason_code: 'multistage-differs', node: null});
|
||||
assert.equal(evidence.prompts.positive.message, undefined);
|
||||
});
|
||||
|
||||
test('A1111 parameters split on the unique settings footer as Python does', () => {
|
||||
const read = text => resolver.resolveLocalEvidence({parameters: text}, semantics);
|
||||
assert.deepEqual(read('a fox\nNegative prompt: blur\nSteps: 20, Sampler: euler').prompts, {
|
||||
positive: {status: 'resolved', text: 'a fox', source: 'embedded-parameters'}, negative: {status: 'resolved', text: 'blur', source: 'embedded-parameters'},
|
||||
});
|
||||
// Python's multiline ^ and $ break only at \n: a U+2028 or a lone \r never starts the footer line.
|
||||
for (const text of ['a fox\u2028Steps: 20, x', 'a fox\rSteps: 20, x']) assert.equal(read(text).resolution.reason, 'A1111 settings footer is not unique');
|
||||
// \d is any Unicode decimal digit and \s spans line breaks, as in Python's re.
|
||||
assert.equal(read('a fox\nSteps: \u0662\u0660, x').resolution.reason, 'Negative prompt delimiter is absent');
|
||||
assert.equal(read('a fox\nSteps:\n 20 \n, x').resolution.state, 'absent');
|
||||
assert.equal(read('a fox\nSteps: 1, x\nNegative Template: n\nTemplate: t').resolution.reason_code, 'malformed');
|
||||
assert.equal(read('\u{1f600}'.repeat(60000) + '\nSteps: 1, x').resolution.state, 'absent', 'the length limit counts code points');
|
||||
});
|
||||
|
||||
test('an unusable semantics table is refused', () => {
|
||||
for (const doc of [null, {schema: 2}, {schema: 1, samplers: []}]) assert.throws(() => resolver.compileSemantics(doc), resolver.SemanticsError);
|
||||
});
|
||||
|
||||
// The committed server answers (tests/fixtures/local-inspect/resolver-vectors.json, written by
|
||||
// `python3 -m tests.local_resolver_cases --write` and checked current by the Python suite).
|
||||
test('committed server answers equal the local evidence', () => {
|
||||
const {vectors} = JSON.parse(fs.readFileSync(new URL('../fixtures/local-inspect/resolver-vectors.json', import.meta.url), 'utf8'));
|
||||
const canonical = value => Array.isArray(value) ? value.map(canonical) :
|
||||
value !== null && typeof value === 'object' ? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])])) : value;
|
||||
let compared = 0;
|
||||
for (const {name, records, evidence} of vectors) {
|
||||
assert.deepEqual(canonical(resolver.resolveLocalEvidence(records, semantics)), canonical(evidence), name);
|
||||
compared++;
|
||||
}
|
||||
assert.ok(compared > 280, `compared ${compared}`);
|
||||
});
|
||||
|
||||
test('a list or object workflow node type is skipped, as on the server (#286)', () => {
|
||||
const graph = base({'6': {class_type: 'PromptManager', inputs: {text: 'a fox', clip: ['4', 1]}}});
|
||||
for (const type of [['PromptManager'], {name: 'PromptManager'}]) {
|
||||
const evidence = resolver.resolveLocalEvidence({prompt: JSON.stringify(graph), workflow: JSON.stringify({nodes: [{id: 6, type, widgets_values: ['x']}]})}, semantics);
|
||||
assert.equal(evidence.resolution.state, 'resolved');
|
||||
assert.equal(evidence.prompts.positive.status, 'resolved');
|
||||
assert.equal(evidence.prompts.positive.text, 'a fox');
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
// web/js/workspace/local-semantics.mjs (#249 local Inspect, PR L3 Task 10): the node table local Inspect resolves
|
||||
// with is the server's own web/js/inspection-semantics.json, fetched once through the API client before a file is
|
||||
// chosen. A table that cannot be fetched or used answers as the server does when its table is unusable.
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
|
||||
const TABLE = fs.readFileSync(new URL("../../web/js/inspection-semantics.json", import.meta.url), "utf8");
|
||||
let instance = 0;
|
||||
/** A fresh module instance (its cache is per page) with `fetch` and the API client stubbed. */
|
||||
async function load(respond) {
|
||||
const calls = [];
|
||||
globalThis.window = { ApiClient: { resolveUrl: (path) => `/proxy${path}` } };
|
||||
globalThis.fetch = async (url, init) => { calls.push([url, init]); return respond(); };
|
||||
const module = await import(`../../web/js/workspace/local-semantics.mjs?instance=${++instance}`);
|
||||
return { module, calls };
|
||||
}
|
||||
test.after(() => { delete globalThis.window; delete globalThis.fetch; });
|
||||
|
||||
test("the table is fetched once through the API client and compiled", async () => {
|
||||
const { module, calls } = await load(() => new Response(TABLE, { status: 200 }));
|
||||
const [first, second] = await Promise.all([module.loadInspectionSemantics(), module.loadInspectionSemantics()]);
|
||||
assert.equal(first, second);
|
||||
assert.ok(first.samplers.has("KSampler"));
|
||||
assert.equal(await module.loadInspectionSemantics(), first);
|
||||
assert.deepEqual(calls, [["/proxy/prompt_manager/js/inspection-semantics.json", { credentials: "same-origin" }]]);
|
||||
});
|
||||
|
||||
test("a failed or unusable table is null, and a later selection asks again", async () => {
|
||||
for (const respond of [() => new Response("nope", { status: 404 }), () => new Response("{\"schema\": 2}", { status: 200 }), () => { throw new TypeError("offline"); }]) {
|
||||
const { module, calls } = await load(respond);
|
||||
assert.equal(await module.loadInspectionSemantics(), null);
|
||||
assert.equal(await module.loadInspectionSemantics(), null);
|
||||
assert.equal(calls.length, 2);
|
||||
}
|
||||
});
|
||||
|
||||
test("without the API client nothing is fetched", async () => {
|
||||
const { module, calls } = await load(() => new Response(TABLE));
|
||||
delete globalThis.window;
|
||||
assert.equal(await module.loadInspectionSemantics(), null);
|
||||
assert.deepEqual(calls, []);
|
||||
});
|
||||
@@ -193,8 +193,8 @@ test("unclassified input creates no object URL", async () => {
|
||||
// declares a supported type it opens the inspector's unreadable state, with no preview and no URL (ledger ruling).
|
||||
const gone = pngFile("gone.png", "fox", { gate: () => Promise.reject(new DOMException("The file was removed", "NotReadableError")) });
|
||||
assert.equal(value.select([gone]), "accepted");
|
||||
await settle();
|
||||
const unreadable = value.controller.state;
|
||||
// The read yields between its steps (local-inspection.mjs): wait for the answer, not a fixed number of turns.
|
||||
const unreadable = await recorded(value.controller);
|
||||
assert.ok(unreadable.record, "the unreadable record is published");
|
||||
assert.deepEqual([value.state.phase, value.state.message, value.state.preview], ["ready", m.LOCAL_SESSION_MESSAGES.unreadable, null]);
|
||||
assert.equal(m.LOCAL_SESSION_MESSAGES.unreadable, "Embedded metadata could not be read.");
|
||||
|
||||
@@ -521,6 +521,10 @@ test('copy fallback selects the text', async () => {
|
||||
assert.equal(note.className, 'small');
|
||||
assert.equal(note.textContent, 'Automatic clipboard access requires a secure browser context.');
|
||||
assert.throws(() => openCopyFallback(42, { scope }), TypeError);
|
||||
// LI-4 (D117): the settings summary names its own dialog; the select-to-copy body is the same.
|
||||
openCopyFallback('Seed: 7', { scope, title: 'Copy settings summary' });
|
||||
assert.equal(byId(dom, 'modal-title').textContent, 'Copy settings summary');
|
||||
assert.equal(byId(dom, 'copy-text').value, 'Seed: 7');
|
||||
} finally {
|
||||
closeWorkspaceDialog();
|
||||
scope.dispose();
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,574 @@
|
||||
"""Candidate-selection record sets for the local resolver parity test (PR L3 Task 9).
|
||||
|
||||
``local_resolver_cases`` covers one sampler's tracing. These cases reach the
|
||||
rest of ``_resolve``: several sampler candidates and the identical-branch rule
|
||||
(#270), stages that only reach previews, detailer stages and their upstream
|
||||
samplers (multistage), and A1111 ``parameters`` with every footer shape. The
|
||||
server's ``inspect_prompt_evidence`` is the oracle; nothing here states an
|
||||
expected answer. All content is synthetic.
|
||||
"""
|
||||
|
||||
import json
|
||||
import random
|
||||
|
||||
try:
|
||||
from tests.local_resolver_cases import EXECUTION_KEY, SPACES, WORDS, _Builder
|
||||
except ImportError: # pragma: no cover - discover -s tests puts tests/ first
|
||||
from local_resolver_cases import EXECUTION_KEY, SPACES, WORDS, _Builder
|
||||
|
||||
|
||||
def _encode(text):
|
||||
return {"class_type": "CLIPTextEncode", "inputs": {"text": text, "clip": ["4", 1]}}
|
||||
|
||||
|
||||
def _sampler(positive, negative, latent=None, name="KSampler"):
|
||||
inputs = {"seed": 1, "model": ["4", 0], "positive": positive}
|
||||
if negative is not None:
|
||||
inputs["negative"] = negative
|
||||
inputs["latent_image"] = latent or ["5", 0]
|
||||
return {"class_type": name, "inputs": inputs}
|
||||
|
||||
|
||||
def _decode(sampler_id):
|
||||
return {"class_type": "VAEDecode", "inputs": {"samples": [sampler_id, 0]}}
|
||||
|
||||
|
||||
def _save(image, name="SaveImage"):
|
||||
return {"class_type": name, "inputs": {"images": image}}
|
||||
|
||||
|
||||
def _detailer(image, positive, negative, name="FaceDetailer", **extra):
|
||||
inputs = {"image": image, "model": ["4", 0], "positive": positive}
|
||||
inputs["negative"] = negative
|
||||
inputs.update(extra)
|
||||
return {"class_type": name, "inputs": inputs}
|
||||
|
||||
|
||||
def _base(**nodes):
|
||||
graph = {
|
||||
"4": {"class_type": "CheckpointLoaderSimple", "inputs": {"ckpt_name": "m"}},
|
||||
"5": {"class_type": "EmptyLatentImage", "inputs": {"width": 64}},
|
||||
"6": _encode("a fox"),
|
||||
"7": _encode("blurry"),
|
||||
"8": _encode("a cat"),
|
||||
}
|
||||
graph.update(nodes)
|
||||
return graph
|
||||
|
||||
|
||||
def _samplers():
|
||||
"""Several unanchored samplers: identical, differing and mixed branches."""
|
||||
same = _sampler(["6", 0], ["7", 0])
|
||||
cases = {
|
||||
"two-identical": _base(**{"3": same, "9": same}),
|
||||
"two-differ": _base(**{"3": same, "9": _sampler(["8", 0], ["7", 0])}),
|
||||
"two-negative-differs": _base(**{"3": same, "9": _sampler(["6", 0], ["8", 0])}),
|
||||
"identical-without-negative": _base(
|
||||
**{"3": _sampler(["6", 0], None), "9": _sampler(["6", 0], None)}
|
||||
),
|
||||
"one-unresolved": _base(**{"3": same, "9": _sampler(["missing", 0], ["7", 0])}),
|
||||
"both-unresolved": _base(
|
||||
**{"3": _sampler(["x", 0], ["7", 0]), "9": _sampler(["y", 0], ["7", 0])}
|
||||
),
|
||||
"three-identical-one-advanced": _base(
|
||||
**{
|
||||
"3": same,
|
||||
"9": same,
|
||||
"10": _sampler(["6", 0], ["7", 0], name="KSamplerAdvanced"),
|
||||
}
|
||||
),
|
||||
# Equal texts, different recipes: a PromptManager pair against an encoder.
|
||||
"same-text-other-recipe": _base(
|
||||
**{
|
||||
"3": same,
|
||||
"9": _sampler(["11", 0], ["7", 0]),
|
||||
"11": {
|
||||
"class_type": "PromptManager",
|
||||
"inputs": {
|
||||
"text": "fox",
|
||||
"prepend_text": "a",
|
||||
"append_text": "",
|
||||
"clip": ["4", 1],
|
||||
},
|
||||
},
|
||||
}
|
||||
),
|
||||
"multistage-latent": _base(
|
||||
**{"3": same, "9": _sampler(["6", 0], ["7", 0], latent=["3", 0])}
|
||||
),
|
||||
}
|
||||
selector = {
|
||||
"class_type": "easy ifElse",
|
||||
"inputs": {"boolean": ["4", 0], "on_true": ["6", 0], "on_false": ["8", 0]},
|
||||
}
|
||||
cases["selector-and-plain"] = _base(
|
||||
**{"3": same, "9": _sampler(["12", 0], ["7", 0]), "12": selector}
|
||||
)
|
||||
return cases
|
||||
|
||||
|
||||
def _previews():
|
||||
"""Stages whose outputs reach only previews are not the saved file's."""
|
||||
same, other = _sampler(["6", 0], ["7", 0]), _sampler(["8", 0], ["7", 0])
|
||||
return {
|
||||
"preview-dropped": _base(
|
||||
**{
|
||||
"3": same,
|
||||
"9": other,
|
||||
"13": _decode("3"),
|
||||
"14": _decode("9"),
|
||||
"15": _save(["13", 0]),
|
||||
"16": _save(["14", 0], "PreviewImage"),
|
||||
}
|
||||
),
|
||||
"all-previews-kept": _base(
|
||||
**{
|
||||
"3": same,
|
||||
"9": other,
|
||||
"13": _decode("3"),
|
||||
"14": _decode("9"),
|
||||
"15": _save(["13", 0], "PreviewImage"),
|
||||
"16": _save(["14", 0], "Image Comparer (rgthree)"),
|
||||
}
|
||||
),
|
||||
"preview-and-file": _base(
|
||||
**{
|
||||
"3": same,
|
||||
"9": other,
|
||||
"13": _decode("3"),
|
||||
"14": _decode("9"),
|
||||
"15": _save(["13", 0]),
|
||||
"16": _save(["14", 0], "PreviewImage"),
|
||||
"17": _save(["14", 0]),
|
||||
}
|
||||
),
|
||||
"unconsumed-stage-kept": _base(
|
||||
**{
|
||||
"3": same,
|
||||
"9": other,
|
||||
"14": _decode("9"),
|
||||
"16": _save(["14", 0], "PreviewImage"),
|
||||
}
|
||||
),
|
||||
# A list or object class_type is never a preview class (#286).
|
||||
"preview-unhashable-class": _base(
|
||||
**{
|
||||
"3": same,
|
||||
"9": other,
|
||||
"14": _decode("9"),
|
||||
"16": {"class_type": ["PreviewImage"], "inputs": {"images": ["14", 0]}},
|
||||
"17": {"class_type": {"a": 1}, "inputs": {"images": ["3", 0]}},
|
||||
}
|
||||
),
|
||||
"preview-through-bad-node": _base(
|
||||
**{
|
||||
"3": same,
|
||||
"9": other,
|
||||
"13": _decode("3"),
|
||||
"15": _save(["13", 0]),
|
||||
"16": _save(["9", 0], "PreviewImage"),
|
||||
"18": "not a node",
|
||||
"19": {"class_type": "Note", "inputs": {"x": ["18", 0]}},
|
||||
}
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _detailers():
|
||||
"""Detailer stages judged with the samplers in their image ancestry."""
|
||||
same = _sampler(["6", 0], ["7", 0])
|
||||
cases = {
|
||||
"detailer-same-prompt": _base(
|
||||
**{
|
||||
"3": same,
|
||||
"10": _decode("3"),
|
||||
"11": _detailer(["10", 0], ["6", 0], ["7", 0]),
|
||||
"12": _save(["11", 0]),
|
||||
}
|
||||
),
|
||||
"detailer-differs": _base(
|
||||
**{
|
||||
"3": same,
|
||||
"10": _decode("3"),
|
||||
"11": _detailer(["10", 0], ["8", 0], ["7", 0]),
|
||||
"12": _save(["11", 0]),
|
||||
}
|
||||
),
|
||||
"detailer-and-own-output": _base(
|
||||
**{
|
||||
"3": same,
|
||||
"10": _decode("3"),
|
||||
"11": _detailer(["10", 0], ["8", 0], ["7", 0]),
|
||||
"12": _save(["11", 0]),
|
||||
"13": _save(["10", 0]),
|
||||
}
|
||||
),
|
||||
"detailer-image-literal": _base(
|
||||
**{
|
||||
"11": _detailer("not a link", ["6", 0], ["7", 0]),
|
||||
"12": _save(["11", 0]),
|
||||
}
|
||||
),
|
||||
"detailer-cycle": _base(
|
||||
**{
|
||||
"11": _detailer(["10", 0], ["6", 0], ["7", 0]),
|
||||
"10": {"class_type": "ImageScale", "inputs": {"image": ["11", 0]}},
|
||||
"12": _save(["11", 0]),
|
||||
}
|
||||
),
|
||||
"detailer-chain": _base(
|
||||
**{
|
||||
"3": same,
|
||||
"10": _decode("3"),
|
||||
"11": _detailer(["10", 0], ["6", 0], ["7", 0]),
|
||||
"21": _detailer(
|
||||
["11", 0], ["8", 0], ["7", 0], name="UltimateSDUpscale"
|
||||
),
|
||||
"12": _save(["21", 0]),
|
||||
}
|
||||
),
|
||||
"detailer-chain-same": _base(
|
||||
**{
|
||||
"3": same,
|
||||
"10": _decode("3"),
|
||||
"11": _detailer(["10", 0], ["6", 0], ["7", 0]),
|
||||
"21": _detailer(["11", 0], ["6", 0], ["7", 0], name="DetailerForEach"),
|
||||
"12": _save(["21", 0]),
|
||||
}
|
||||
),
|
||||
"detailer-two-upstream": _base(
|
||||
**{
|
||||
"3": same,
|
||||
"9": _sampler(["8", 0], ["7", 0]),
|
||||
"10": {
|
||||
"class_type": "ImageBlend",
|
||||
"inputs": {"image1": ["13", 0], "image2": ["14", 0]},
|
||||
},
|
||||
"13": _decode("3"),
|
||||
"14": _decode("9"),
|
||||
"11": _detailer(["10", 0], ["6", 0], ["7", 0]),
|
||||
"12": _save(["11", 0]),
|
||||
}
|
||||
),
|
||||
"detailer-unsupported-stage": _base(
|
||||
**{
|
||||
"10": {
|
||||
"class_type": "MysterySampler",
|
||||
"inputs": {"positive": ["6", 0], "model": ["4", 0]},
|
||||
},
|
||||
"11": _detailer(["10", 0], ["6", 0], ["7", 0]),
|
||||
"12": _save(["11", 0]),
|
||||
}
|
||||
),
|
||||
"detailer-upstream-unresolved": _base(
|
||||
**{
|
||||
"3": _sampler(["gone", 0], ["7", 0]),
|
||||
"10": _decode("3"),
|
||||
"11": _detailer(["10", 0], ["6", 0], ["7", 0]),
|
||||
"12": _save(["11", 0]),
|
||||
}
|
||||
),
|
||||
"detailer-upstream-selector": _base(
|
||||
**{
|
||||
"3": _sampler(["15", 0], ["7", 0]),
|
||||
"15": {
|
||||
"class_type": "easy ifElse",
|
||||
"inputs": {
|
||||
"boolean": ["4", 0],
|
||||
"on_true": ["6", 0],
|
||||
"on_false": ["8", 0],
|
||||
},
|
||||
},
|
||||
"10": _decode("3"),
|
||||
"11": _detailer(["10", 0], ["6", 0], ["7", 0]),
|
||||
"12": _save(["11", 0]),
|
||||
}
|
||||
),
|
||||
"detailer-wildcard": _base(
|
||||
**{
|
||||
"3": same,
|
||||
"10": _decode("3"),
|
||||
"11": _detailer(["10", 0], ["6", 0], ["7", 0], wildcard="[x|y]"),
|
||||
"12": _save(["11", 0]),
|
||||
}
|
||||
),
|
||||
"detailer-no-upscaled-image": _base(
|
||||
**{
|
||||
"3": same,
|
||||
"10": _decode("3"),
|
||||
"11": _detailer(
|
||||
["10", 0], ["6", 0], ["7", 0], name="UltimateSDUpscaleNoUpscale"
|
||||
),
|
||||
"12": _save(["11", 0]),
|
||||
}
|
||||
),
|
||||
"detailer-no-sampler-upstream": _base(
|
||||
**{
|
||||
"10": {"class_type": "LoadImage", "inputs": {"image": "a.png"}},
|
||||
"11": _detailer(["10", 0], ["6", 0], ["7", 0]),
|
||||
"12": _save(["11", 0]),
|
||||
}
|
||||
),
|
||||
}
|
||||
deep = {"3": _sampler(["6", 0], ["7", 0]), "d0": _decode("3")}
|
||||
for index in range(1, 70):
|
||||
deep[f"d{index}"] = {
|
||||
"class_type": "ImageScale",
|
||||
"inputs": {"image": [f"d{index - 1}", 0]},
|
||||
}
|
||||
deep["11"] = _detailer(["d69", 0], ["6", 0], ["7", 0])
|
||||
deep["12"] = _save(["11", 0])
|
||||
cases["detailer-deep-ancestry"] = _base(**deep)
|
||||
# More nested detailer stages than the depth bound.
|
||||
stacked = {"3": _sampler(["6", 0], ["7", 0]), "s0": _decode("3")}
|
||||
previous = "s0"
|
||||
for index in range(1, 67):
|
||||
stacked[f"s{index}"] = _detailer([previous, 0], ["6", 0], ["7", 0])
|
||||
previous = f"s{index}"
|
||||
stacked["12"] = _save([previous, 0])
|
||||
cases["detailer-stacked-past-depth"] = _base(**stacked)
|
||||
# Each detailer walks a wide shared image ancestry: the total visit budget
|
||||
# runs out across stages before any candidate is read.
|
||||
wide = {
|
||||
f"l{index}": {"class_type": "LoadImage", "inputs": {}} for index in range(1500)
|
||||
}
|
||||
wide["hub"] = {
|
||||
"class_type": "ImageBatchMany",
|
||||
"inputs": {f"i{index}": [f"l{index}", 0] for index in range(1500)},
|
||||
}
|
||||
for index in range(15):
|
||||
wide[f"w{index}"] = _detailer(["hub", 0], ["6", 0], ["7", 0])
|
||||
wide[f"o{index}"] = _save([f"w{index}", 0])
|
||||
cases["detailers-exhaust-total-visits"] = _base(**wide)
|
||||
cases["detailer-mutual-cycle"] = _base(
|
||||
**{
|
||||
"11": _detailer(["21", 0], ["6", 0], ["7", 0]),
|
||||
"21": _detailer(["11", 0], ["6", 0], ["7", 0]),
|
||||
"12": _save(["21", 0]),
|
||||
}
|
||||
)
|
||||
# The sampler's output reaches a preview through more nodes than one
|
||||
# detailer's allowance: the walk runs out, so the sampler is not absorbed.
|
||||
long = {"3": _sampler(["6", 0], ["7", 0]), "10": _decode("3")}
|
||||
previous = "10"
|
||||
for index in range(2100):
|
||||
long[f"c{index}"] = {
|
||||
"class_type": "ImageScale",
|
||||
"inputs": {"image": [previous, 0]},
|
||||
}
|
||||
previous = f"c{index}"
|
||||
long["p"] = _save([previous, 0], "PreviewImage")
|
||||
long["11"] = _detailer(["10", 0], ["6", 0], ["7", 0])
|
||||
long["12"] = _save(["11", 0])
|
||||
cases["detailer-output-walk-exhausted"] = _base(**long)
|
||||
# Every detailer's ancestry walk has its own allowance: the first one is
|
||||
# wide, and the second still absorbs the first.
|
||||
chained = {"3": _sampler(["6", 0], ["7", 0]), "10": _decode("3")}
|
||||
chained["h1"] = {
|
||||
"class_type": "ImageBatchMany",
|
||||
"inputs": {
|
||||
"i": ["10", 0],
|
||||
**{f"i{index}": [f"a{index}", 0] for index in range(1500)},
|
||||
},
|
||||
}
|
||||
chained["h2"] = {
|
||||
"class_type": "ImageBatchMany",
|
||||
"inputs": {
|
||||
"i": ["11", 0],
|
||||
**{f"i{index}": [f"b{index}", 0] for index in range(600)},
|
||||
},
|
||||
}
|
||||
for index in range(1500):
|
||||
chained[f"a{index}"] = {"class_type": "LoadImage", "inputs": {}}
|
||||
for index in range(600):
|
||||
chained[f"b{index}"] = {"class_type": "LoadImage", "inputs": {}}
|
||||
chained["11"] = _detailer(["h1", 0], ["6", 0], ["7", 0])
|
||||
chained["21"] = _detailer(["h2", 0], ["6", 0], ["7", 0])
|
||||
chained["12"] = _save(["21", 0])
|
||||
cases["detailers-each-reset"] = _base(**chained)
|
||||
return cases
|
||||
|
||||
|
||||
_FOOTER = "Steps: 20, Sampler: euler, CFG scale: 7"
|
||||
|
||||
|
||||
def _parameters():
|
||||
"""A1111 ``parameters`` texts: every footer shape and delimiter rule."""
|
||||
texts = {
|
||||
"basic": f"a fox\nNegative prompt: blur\n{_FOOTER}",
|
||||
"no-negative": f"a fox\n{_FOOTER}",
|
||||
"two-delimiters": f"a\nNegative prompt: b\nNegative prompt: c\n{_FOOTER}",
|
||||
"leading-delimiter": f"Negative prompt: blur\n{_FOOTER}",
|
||||
"blank-positive": f" \x85\nNegative prompt: blur\n{_FOOTER}",
|
||||
"footer-not-last": f"a fox\n{_FOOTER}\nmore text",
|
||||
"two-footers": f"a\n{_FOOTER}\n{_FOOTER}",
|
||||
"bare-footer": "a fox\nNegative prompt: blur\nSteps: 20",
|
||||
"bare-and-full": f"a fox\nSteps: 5\n{_FOOTER}",
|
||||
"two-bare": "a\nSteps: 1\nSteps: 2",
|
||||
"template": f"a fox\n{_FOOTER}\nTemplate: {{a|b}}",
|
||||
"both-templates": f"a\n{_FOOTER}\nTemplate: x\nNegative Template: y",
|
||||
"templates-reversed": f"a\n{_FOOTER}\nNegative Template: y\nTemplate: x",
|
||||
"two-templates": f"a\n{_FOOTER}\nTemplate: x\nTemplate: y",
|
||||
"template-multiline": f"a\n{_FOOTER}\nTemplate: x\nmore",
|
||||
"crlf": f"a fox\r\nNegative prompt: blur\r\n{_FOOTER}\r\n",
|
||||
"cr-only": f"a fox\rNegative prompt: blur\r{_FOOTER}",
|
||||
"cr-template": f"a\n{_FOOTER}\rTemplate: x",
|
||||
"line-separator": f"a fox
{_FOOTER}",
|
||||
"next-line": f"a fox\x85{_FOOTER}",
|
||||
"spaced-steps": "a fox\nSteps:\n 20 \n, x",
|
||||
"steps-newline-bare": "a fox\nSteps:\n20\n",
|
||||
"arabic-digits": "a fox\nSteps: ٢٠, Sampler: euler",
|
||||
"fullwidth-digits": "a fox\nSteps: 2, x",
|
||||
"no-digits": "a fox\nSteps: , x",
|
||||
"trailing-spaces": f"a fox \nNegative prompt: blur \n{_FOOTER} \n \n",
|
||||
"empty-negative": f"a fox\nNegative prompt:\n{_FOOTER}",
|
||||
"astral-within-limit": "\U0001f600" * 60_000 + f"\n{_FOOTER}",
|
||||
"over-limit": "x" * 100_001,
|
||||
"at-limit": "x" * (100_000 - len(_FOOTER) - 1) + "\n" + _FOOTER,
|
||||
"empty": "",
|
||||
"only-footer": _FOOTER,
|
||||
"lone-surrogate": f"\ud800 fox\nNegative prompt: \udfff\n{_FOOTER}",
|
||||
}
|
||||
cases = {f"parameters-{name}": {"parameters": text} for name, text in texts.items()}
|
||||
cases["parameters-with-execution"] = {
|
||||
"parameters": texts["basic"],
|
||||
EXECUTION_KEY: json.dumps({"version": 1, "nodes": {}}),
|
||||
}
|
||||
return cases
|
||||
|
||||
|
||||
def selection_cases():
|
||||
"""Named record sets for every Task 9 path, each a ``read_inspection_file`` dict."""
|
||||
cases = {}
|
||||
for group in (_samplers(), _previews(), _detailers()):
|
||||
for name, graph in group.items():
|
||||
cases[f"select-{name}"] = {"prompt": json.dumps(graph, ensure_ascii=False)}
|
||||
cases.update(_parameters())
|
||||
return cases
|
||||
|
||||
|
||||
class _Selection(_Builder):
|
||||
"""Random graphs with several samplers, outputs, previews and detailers."""
|
||||
|
||||
def sampler(self):
|
||||
rng = self.rng
|
||||
positive = self.conditioning(0)
|
||||
negative = self.conditioning(0) if rng.random() < 0.85 else None
|
||||
name = rng.choice(["KSampler", "KSampler", "KSamplerAdvanced", "SamplerCustom"])
|
||||
node_id = self.new_id()
|
||||
self.nodes[node_id] = _sampler(positive, negative, name=name)
|
||||
return node_id
|
||||
|
||||
def shared(self, ids):
|
||||
"""A copy of an earlier sampler: an identical branch."""
|
||||
node_id = self.new_id()
|
||||
self.nodes[node_id] = json.loads(json.dumps(self.nodes[self.rng.choice(ids)]))
|
||||
return node_id
|
||||
|
||||
def output(self, image):
|
||||
rng = self.rng
|
||||
choice = rng.randrange(5)
|
||||
if choice == 4:
|
||||
return
|
||||
name = ["SaveImage", "SaveImage", "PreviewImage", "PreviewAny"][choice]
|
||||
self.nodes[self.new_id()] = _save(image, name)
|
||||
|
||||
def detailer(self, image):
|
||||
rng = self.rng
|
||||
node_id = self.new_id()
|
||||
positive = self.conditioning(1) if rng.random() < 0.5 else None
|
||||
name = rng.choice(list(_DETAILER_NAMES))
|
||||
node = _detailer(image, positive, self.conditioning(1), name=name)
|
||||
if positive is None:
|
||||
node["inputs"]["positive"] = self.reuse_positive()
|
||||
if name == "UltimateSDUpscaleNoUpscale":
|
||||
node["inputs"]["upscaled_image"] = node["inputs"].pop("image")
|
||||
if name in ("FaceDetailer", "DetailerForEach") and rng.random() < 0.15:
|
||||
node["inputs"]["wildcard"] = rng.choice(["", "x", ["4", 0]])
|
||||
self.nodes[node_id] = node
|
||||
return node_id
|
||||
|
||||
def reuse_positive(self):
|
||||
samplers = [
|
||||
node
|
||||
for node in self.nodes.values()
|
||||
if node.get("class_type")
|
||||
in ("KSampler", "KSamplerAdvanced", "SamplerCustom")
|
||||
]
|
||||
if samplers:
|
||||
return self.rng.choice(samplers)["inputs"]["positive"]
|
||||
return self.conditioning(1)
|
||||
|
||||
def build(self):
|
||||
rng = self.rng
|
||||
ids = [self.sampler()]
|
||||
for _ in range(rng.randrange(3)):
|
||||
ids.append(self.shared(ids) if rng.random() < 0.4 else self.sampler())
|
||||
for sampler_id in list(ids):
|
||||
decoded = self.new_id()
|
||||
self.nodes[decoded] = _decode(sampler_id)
|
||||
image = [decoded, 0]
|
||||
for _ in range(rng.randrange(3)):
|
||||
if rng.random() < 0.5:
|
||||
image = [self.detailer(image), 0]
|
||||
else:
|
||||
self.output(image)
|
||||
self.output(image)
|
||||
if rng.random() < 0.1:
|
||||
self.nodes[sampler_id]["inputs"]["latent_image"] = [rng.choice(ids), 0]
|
||||
graph = {
|
||||
"4": {"class_type": "CheckpointLoaderSimple", "inputs": {"ckpt_name": "m"}},
|
||||
"5": {"class_type": "EmptyLatentImage", "inputs": {"width": 64}},
|
||||
}
|
||||
graph.update(self.nodes)
|
||||
return graph
|
||||
|
||||
|
||||
_DETAILER_NAMES = (
|
||||
"FaceDetailer",
|
||||
"DetailerForEach",
|
||||
"UltimateSDUpscale",
|
||||
"UltimateSDUpscaleNoUpscale",
|
||||
)
|
||||
_PARAMETER_LINES = [
|
||||
"Negative prompt:",
|
||||
"Negative prompt: blur",
|
||||
"Steps: 20, Sampler: euler",
|
||||
"Steps: 7",
|
||||
"Steps: x",
|
||||
"Template: t",
|
||||
"Negative Template: n",
|
||||
"Steps:٣, a",
|
||||
]
|
||||
|
||||
|
||||
def _parameter_text(rng):
|
||||
parts = []
|
||||
for _ in range(rng.randint(1, 5)):
|
||||
if rng.random() < 0.5:
|
||||
parts.append(rng.choice(_PARAMETER_LINES))
|
||||
else:
|
||||
parts.append(rng.choice(SPACES) + rng.choice(WORDS) + rng.choice(SPACES))
|
||||
joints = ["\n", "\n", "\r\n", "\r", "
", " "]
|
||||
return "".join(part + rng.choice(joints) for part in parts).rstrip(
|
||||
rng.choice(["", "\n", " "])
|
||||
)
|
||||
|
||||
|
||||
def selection_fuzz_cases(seed, count):
|
||||
"""Seeded several-sampler graphs (sometimes corrupted) and parameters texts."""
|
||||
rng = random.Random(seed)
|
||||
cases = {}
|
||||
for index in range(count):
|
||||
if rng.random() < 0.2:
|
||||
cases[f"select-fuzz-{seed}-{index}"] = {"parameters": _parameter_text(rng)}
|
||||
continue
|
||||
builder = _Selection(rng)
|
||||
graph = builder.build()
|
||||
if rng.random() < 0.2:
|
||||
builder.nodes = graph
|
||||
builder.corrupt()
|
||||
records = {"prompt": json.dumps(graph, ensure_ascii=rng.random() < 0.5)}
|
||||
records.update(builder.records)
|
||||
cases[f"select-fuzz-{seed}-{index}"] = records
|
||||
return cases
|
||||
@@ -486,6 +486,30 @@ class TestStaticRoutes(CoreRoutesTestCase):
|
||||
self.assertEqual(resp.status, 200)
|
||||
self.assertIn("application/javascript", resp.headers["Content-Type"])
|
||||
|
||||
async def test_inspection_semantics_table_is_the_one_json_served(self):
|
||||
"""Local Inspect reads the node table the server resolves with (#249 PR L3).
|
||||
|
||||
Only that exact file is served; every other JSON stays forbidden.
|
||||
"""
|
||||
resp = await self.client.request(
|
||||
"GET", "/prompt_manager/js/inspection-semantics.json"
|
||||
)
|
||||
self.assertEqual(resp.status, 200)
|
||||
self.assertIn("application/json", resp.headers["Content-Type"])
|
||||
table = Path(__file__).resolve().parents[1] / "web" / "js"
|
||||
self.assertEqual(
|
||||
await resp.read(), (table / "inspection-semantics.json").read_bytes()
|
||||
)
|
||||
for path in (
|
||||
"js/shared/toolkit/provenance.json",
|
||||
"lib/viewerjs/provenance.json",
|
||||
"lib/inspection-semantics.json",
|
||||
"js/workspace/..%2Finspection-semantics.json",
|
||||
"js/INSPECTION-SEMANTICS.json",
|
||||
):
|
||||
resp = await self.client.request("GET", f"/prompt_manager/{path}")
|
||||
self.assertEqual(resp.status, 403, path)
|
||||
|
||||
async def test_lib_served(self):
|
||||
web_dir = self._fake_root()
|
||||
(web_dir / "lib" / "x.css").write_text("body{}")
|
||||
@@ -578,6 +602,28 @@ class TestStaticRoutes(CoreRoutesTestCase):
|
||||
resp = await self.client.request("GET", "/prompt_manager/lib/link.js")
|
||||
self.assertEqual(resp.status, 403)
|
||||
|
||||
async def test_inspection_semantics_symlink_escaping_web_dir_is_403(self):
|
||||
"""The exact-path JSON gets the same realpath containment as any file."""
|
||||
web_dir = self._fake_root()
|
||||
secret = Path(self.tmpdir) / "secret.json"
|
||||
secret.write_text('{"secret": true}')
|
||||
try:
|
||||
os.symlink(secret, web_dir / "js" / "inspection-semantics.json")
|
||||
except (OSError, NotImplementedError):
|
||||
self.skipTest("symlinks not available")
|
||||
resp = await self.client.request(
|
||||
"GET", "/prompt_manager/js/inspection-semantics.json"
|
||||
)
|
||||
self.assertEqual(resp.status, 403)
|
||||
self.assertNotIn("secret", await resp.text())
|
||||
|
||||
async def test_inspection_semantics_missing_is_404(self):
|
||||
self._fake_root()
|
||||
resp = await self.client.request(
|
||||
"GET", "/prompt_manager/js/inspection-semantics.json"
|
||||
)
|
||||
self.assertEqual(resp.status, 404)
|
||||
|
||||
async def test_empty_path_is_not_served(self):
|
||||
for prefix in ("lib", "js"):
|
||||
resp = await self.client.request("GET", f"/prompt_manager/{prefix}/")
|
||||
|
||||
@@ -1643,6 +1643,62 @@ class TestPromptInspector(ImageAPITestCase):
|
||||
str(path), False, report_ambiguity=True
|
||||
)
|
||||
|
||||
async def test_unhashable_workflow_node_type_is_skipped(self):
|
||||
"""A UI workflow node whose ``type`` is a list or dict is skipped (#286).
|
||||
|
||||
The R1 check looks each node's ``type`` up among subgraph IDs; an
|
||||
unhashable ``type`` used to raise there and the route answered 500.
|
||||
Such a node can be neither a subgraph instance nor a PromptManager
|
||||
node, so the walk skips it and a prompt that resolves still resolves.
|
||||
"""
|
||||
source = graph()
|
||||
source["1"]["class_type"] = "PromptManager"
|
||||
for kind in (["PromptManager"], {"name": "PromptManager"}):
|
||||
with self.subTest(kind=type(kind).__name__):
|
||||
workflow = json.dumps(
|
||||
{"nodes": [{"id": 1, "type": kind, "widgets_values": ["x"]}]}
|
||||
)
|
||||
png(
|
||||
self.output_dir / "image.png",
|
||||
prompt=json.dumps(source),
|
||||
workflow=workflow,
|
||||
)
|
||||
response, result = await self.inspect()
|
||||
self.assertEqual(response.status, 200)
|
||||
self.assertEqual(result["resolution"]["state"], "resolved")
|
||||
self.assertEqual(result["resolution"]["sampler_id"], "3")
|
||||
self.assertEqual(result["prompts"]["positive"]["status"], "resolved")
|
||||
self.assertEqual(result["prompts"]["positive"]["text"], "portrait")
|
||||
self.assertEqual(result["prompts"]["negative"]["text"], "blurry")
|
||||
self.assertNotIn("unhashable", json.dumps(result))
|
||||
|
||||
async def test_unhashable_graph_class_type_is_not_a_preview_output(self):
|
||||
"""A list or object ``class_type`` never names a preview output (#286).
|
||||
|
||||
With several samplers the inspector first drops stages that reach only
|
||||
previews; looking such a ``class_type`` up among the preview classes
|
||||
used to raise, and the route answered 500.
|
||||
"""
|
||||
for kind in (["PreviewImage"], {"name": "PreviewImage"}):
|
||||
with self.subTest(kind=type(kind).__name__):
|
||||
source = graph()
|
||||
source["9"] = {
|
||||
"class_type": "KSampler",
|
||||
"inputs": {"positive": ["8", 0], "negative": ["2", 0]},
|
||||
}
|
||||
source["8"] = {
|
||||
"class_type": "CLIPTextEncode",
|
||||
"inputs": {"text": "cat"},
|
||||
}
|
||||
source["10"] = {"class_type": kind, "inputs": {"images": ["9", 0]}}
|
||||
png(self.output_dir / "image.png", prompt=json.dumps(source))
|
||||
response, result = await self.inspect()
|
||||
self.assertEqual(response.status, 200)
|
||||
self.assertEqual(
|
||||
result["resolution"]["reason"], "Multiple sampler branches"
|
||||
)
|
||||
self.assertEqual(result["resolution"]["state"], "ambiguous")
|
||||
|
||||
|
||||
class TestInspectorImageTags(ImageAPITestCase):
|
||||
"""B3: the inspector envelope's ``image_tags`` facet (spec amendment S1)."""
|
||||
|
||||
@@ -299,45 +299,126 @@ class OutputWriterTests(fixtures.unittest.TestCase):
|
||||
)
|
||||
self.assertEqual(writer.context_budget.charged_bytes, 0)
|
||||
|
||||
def isolated_writer(self) -> HistoryWriter:
|
||||
"""A ready writer whose budget no other writer or test can charge."""
|
||||
writer = HistoryWriter(
|
||||
lambda: self.db, clock=self.clock, context_budget=ContextBudget()
|
||||
)
|
||||
self.writers.append(writer)
|
||||
writer.start()
|
||||
self.wait_for(lambda: writer.status().accepting)
|
||||
return writer
|
||||
|
||||
def rotate_between_transactions(self, writer, start, after, restore, hold=None):
|
||||
"""Wrap ``after`` so a restore or invalidation lands right after it.
|
||||
|
||||
Returns the patch and an event set once that rotation has returned on
|
||||
the worker. A restore is a full verify/migrate/backup/replace cycle, so
|
||||
the handoff waits on this event with the generous ``BLOCK_SECONDS``
|
||||
ceiling instead of the short worker-behavior deadline (TESTING.md,
|
||||
Windows portability preflight).
|
||||
"""
|
||||
backup = os.path.join(self.directory.name, f"restore-{start.run_id}.db")
|
||||
self.assertTrue(self.db.model.backup_database(backup))
|
||||
original = getattr(self.db, after)
|
||||
rotated = threading.Event()
|
||||
|
||||
def write(*args, **kwargs):
|
||||
result = original(*args, **kwargs)
|
||||
try:
|
||||
if hold is not None:
|
||||
entered, release = hold
|
||||
entered.set()
|
||||
release.wait(BLOCK_SECONDS)
|
||||
if restore:
|
||||
self.db.model.restore_from_file(backup)
|
||||
else:
|
||||
writer.invalidate()
|
||||
finally:
|
||||
rotated.set()
|
||||
return result
|
||||
|
||||
return patch.object(self.db, after, write), rotated
|
||||
|
||||
def test_restore_or_generation_rotation_between_transactions_discards_evidence(
|
||||
self,
|
||||
):
|
||||
for after in ("write_execution_finish", "write_execution_contexts_for_finish"):
|
||||
for restore in (False, True):
|
||||
with self.subTest(after=after, restore=restore):
|
||||
writer = self.writer()
|
||||
start = self.start_command(len(self.writers))
|
||||
self.db.write_execution_start(start)
|
||||
backup = os.path.join(self.directory.name, "restore.db")
|
||||
self.assertTrue(self.db.model.backup_database(backup))
|
||||
original = getattr(self.db, after)
|
||||
# Each subtest owns its writer and budget and retires them
|
||||
# before the next starts, so one slow restore cannot leave
|
||||
# in-flight charges or an epoch rotation for the next.
|
||||
writer = self.isolated_writer()
|
||||
try:
|
||||
start = self.start_command(len(self.writers))
|
||||
self.db.write_execution_start(start)
|
||||
rotation, rotated = self.rotate_between_transactions(
|
||||
writer, start, after, restore
|
||||
)
|
||||
with rotation:
|
||||
self.finalization(writer, start)
|
||||
self.assertTrue(rotated.wait(BLOCK_SECONDS))
|
||||
self.wait_for(lambda: writer.status().pending == 0)
|
||||
self.assertEqual(
|
||||
self.db.get_execution_outputs(start.run_id)["state"],
|
||||
"not_captured",
|
||||
)
|
||||
self.assertEqual(
|
||||
self.db.get_execution_contexts(start.run_id)["state"],
|
||||
(
|
||||
"complete"
|
||||
if after == "write_execution_contexts_for_finish"
|
||||
and not restore
|
||||
else "not_captured"
|
||||
),
|
||||
)
|
||||
self.assertEqual(writer.context_budget.charged_bytes, 0)
|
||||
finally:
|
||||
self.assertTrue(writer.close(BLOCK_SECONDS))
|
||||
|
||||
def write(*args, **kwargs):
|
||||
result = original(*args, **kwargs)
|
||||
if restore:
|
||||
self.db.model.restore_from_file(backup)
|
||||
else:
|
||||
writer.invalidate()
|
||||
return result
|
||||
|
||||
with patch.object(self.db, after, write):
|
||||
self.finalization(writer, start)
|
||||
self.wait_for(lambda: writer.status().pending == 0)
|
||||
self.assertEqual(
|
||||
self.db.get_execution_outputs(start.run_id)["state"],
|
||||
"not_captured",
|
||||
)
|
||||
self.assertEqual(
|
||||
self.db.get_execution_contexts(start.run_id)["state"],
|
||||
(
|
||||
"complete"
|
||||
if after == "write_execution_contexts_for_finish"
|
||||
and not restore
|
||||
else "not_captured"
|
||||
),
|
||||
)
|
||||
self.assertEqual(writer.context_budget.charged_bytes, 0)
|
||||
self.assertTrue(writer.close())
|
||||
def test_slow_restore_between_transactions_holds_charge_only_while_in_flight(
|
||||
self,
|
||||
):
|
||||
writer = self.isolated_writer()
|
||||
start = self.start_command()
|
||||
self.db.write_execution_start(start)
|
||||
entered, release = self.block()
|
||||
rotation, rotated = self.rotate_between_transactions(
|
||||
writer, start, "write_execution_finish", True, (entered, release)
|
||||
)
|
||||
with rotation:
|
||||
context = self.sealed(writer)
|
||||
outputs = self.outputs(writer, context.lease.byte_count)
|
||||
charge = writer.context_budget.charged_bytes
|
||||
self.assertGreater(charge, 0)
|
||||
self.assertTrue(
|
||||
writer.submit_finalization(self.finish_command(start), context, outputs)
|
||||
)
|
||||
self.assertTrue(entered.wait(BLOCK_SECONDS))
|
||||
# The worker is between transactions: the payload is owned, not leaked.
|
||||
self.assertEqual(writer.status().pending, 1)
|
||||
self.assertEqual(writer.context_budget.charged_bytes, charge)
|
||||
release.set()
|
||||
self.assertTrue(rotated.wait(BLOCK_SECONDS))
|
||||
self.wait_for(lambda: writer.status().pending == 0)
|
||||
self.assertEqual(writer.context_budget.charged_bytes, 0)
|
||||
self.assertFalse(writer.status().accepting)
|
||||
self.assertEqual(
|
||||
self.db.get_execution_outputs(start.run_id)["state"], "not_captured"
|
||||
)
|
||||
# The restored epoch is probed again and new evidence is accepted.
|
||||
self.clock.advance(5)
|
||||
self.wait_for(lambda: writer.status().accepting)
|
||||
restored = self.start_command(2)
|
||||
self.db.write_execution_start(restored)
|
||||
self.finalization(writer, restored)
|
||||
self.wait_for(lambda: writer.status().pending == 0)
|
||||
self.assertEqual(
|
||||
self.db.get_execution_outputs(restored.run_id)["state"], "complete"
|
||||
)
|
||||
self.assertEqual(writer.context_budget.charged_bytes, 0)
|
||||
self.assertTrue(writer.close(BLOCK_SECONDS))
|
||||
|
||||
def test_invalidation_during_output_preparation_rechecks_actual_commit(self):
|
||||
import database.execution_outputs as outputs_db
|
||||
|
||||
@@ -12,6 +12,7 @@ import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import types
|
||||
import unittest
|
||||
import unittest.mock as mock
|
||||
@@ -368,10 +369,29 @@ class TestConsoleBanner(unittest.TestCase):
|
||||
self.assertIn("Loaded:", banner)
|
||||
|
||||
|
||||
class PriorFileHandler(logging.FileHandler):
|
||||
"""A caller-owned sink that stays closed once its owner closes it.
|
||||
|
||||
``FileHandler.emit`` reopens the file when ``stream`` is None, so a record
|
||||
that selected this handler before ``close()`` would reopen prior.log after
|
||||
it, and Windows then refuses the temp directory cleanup (WinError 32).
|
||||
``Handler.handle`` and ``FileHandler.close`` hold the same handler lock, so
|
||||
checking ``_closed`` in ``emit`` is race free (as in the product's
|
||||
``_OwnedRotatingFileHandler``).
|
||||
"""
|
||||
|
||||
def emit(self, record):
|
||||
if not self._closed:
|
||||
super().emit(record)
|
||||
|
||||
|
||||
class TestPackageLoggerIsolation(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
# Runs after restore_logging, before the cleanup Windows refuses while
|
||||
# prior.log is open; /proc makes Linux fail the same way.
|
||||
self.addCleanup(self.assert_tmp_has_no_open_handles)
|
||||
self.logger = logging.getLogger("prompt_manager")
|
||||
self.previous = (
|
||||
self.logger.handlers[:],
|
||||
@@ -381,7 +401,7 @@ class TestPackageLoggerIsolation(unittest.TestCase):
|
||||
)
|
||||
self.addCleanup(self.restore_logging)
|
||||
self.path = os.path.join(self.tmp.name, "prior.log")
|
||||
self.handler = logging.FileHandler(self.path)
|
||||
self.handler = PriorFileHandler(self.path)
|
||||
self.logger.handlers = [self.handler]
|
||||
self.logger.setLevel(logging.DEBUG)
|
||||
self.logger.propagate = True
|
||||
@@ -398,16 +418,20 @@ class TestPackageLoggerIsolation(unittest.TestCase):
|
||||
self.server.PromptServer.instance.prompt_queue.task_done = lambda *a, **k: None
|
||||
|
||||
def restore_logging(self):
|
||||
for handler in self.logger.handlers:
|
||||
if handler not in self.previous[0]:
|
||||
handler.close()
|
||||
self.handler.close()
|
||||
# Detach before closing, so new records stop selecting these handlers.
|
||||
retired = [h for h in self.logger.handlers if h not in self.previous[0]]
|
||||
(
|
||||
self.logger.handlers,
|
||||
self.logger.level,
|
||||
self.logger.propagate,
|
||||
self.logger.disabled,
|
||||
) = self.previous
|
||||
for handler in retired:
|
||||
handler.close()
|
||||
self.handler.close()
|
||||
|
||||
def assert_tmp_has_no_open_handles(self):
|
||||
self.assertEqual(open_handles_under(self.tmp.name), [])
|
||||
|
||||
def assert_logging_restored(self, handlers, registration):
|
||||
for key, module in self.saved_modules.items():
|
||||
@@ -456,6 +480,49 @@ class TestPackageLoggerIsolation(unittest.TestCase):
|
||||
self.assertEqual(open_at_disposal, [True])
|
||||
self.assert_logging_restored(handlers, registration)
|
||||
|
||||
def test_record_in_flight_at_restore_cannot_reopen_prior_log(self):
|
||||
"""A record that selected prior.log before restore never reopens it.
|
||||
|
||||
Leaked daemon threads of other tests (image workers, watchdog) log
|
||||
under ``prompt_manager.*``. One that reaches the prior handler while
|
||||
restore_logging closes it would, with a plain FileHandler, reopen the
|
||||
file on emit and keep it open through TemporaryDirectory.cleanup().
|
||||
"""
|
||||
message = "record selected before restore_logging"
|
||||
selected = threading.Event()
|
||||
resume = threading.Event()
|
||||
errors = []
|
||||
|
||||
def pause_before_handler_lock(record):
|
||||
if record.getMessage() == message:
|
||||
selected.set()
|
||||
if not resume.wait(5):
|
||||
raise RuntimeError("logging thread was not released")
|
||||
return True
|
||||
|
||||
def log_from_background_thread():
|
||||
try:
|
||||
logging.getLogger("prompt_manager.late_emitter").warning(message)
|
||||
except BaseException as error:
|
||||
errors.append(error)
|
||||
|
||||
self.handler.addFilter(pause_before_handler_lock)
|
||||
worker = threading.Thread(target=log_from_background_thread, daemon=True)
|
||||
worker.start()
|
||||
try:
|
||||
self.assertTrue(selected.wait(5), "record did not select prior.log")
|
||||
self.restore_logging()
|
||||
self.assertIsNone(self.handler.stream)
|
||||
finally:
|
||||
resume.set()
|
||||
worker.join(5)
|
||||
self.assertFalse(worker.is_alive(), "logging thread did not finish")
|
||||
self.assertEqual(errors, [])
|
||||
self.assertIsNone(self.handler.stream)
|
||||
self.assert_tmp_has_no_open_handles()
|
||||
with open(self.path, encoding="utf-8") as log:
|
||||
self.assertNotIn(message, log.read())
|
||||
|
||||
def test_failed_package_import_closes_handlers_and_restores_logging(self):
|
||||
name = "prompt_manager_pkg_logger_failure"
|
||||
captured = {}
|
||||
|
||||
@@ -51,12 +51,19 @@ from utils.prompt_inspector import (
|
||||
read_inspection_file,
|
||||
)
|
||||
|
||||
from utils.prompt_inspector import inspect_prompt_evidence, unreadable_evidence
|
||||
from utils.prompt_pair_resolver import INSPECTION_PROFILE
|
||||
|
||||
try:
|
||||
from tests import inspection_parity as parity
|
||||
from tests import local_resolver_cases as resolver_cases
|
||||
from tests import local_resolver_selection_cases as selection_cases
|
||||
from tests.open_handles import assert_closed
|
||||
from tests.test_utils_video_metadata import HAVE_FFMPEG, write_video
|
||||
except ImportError: # pragma: no cover - discover -s tests puts tests/ first
|
||||
import inspection_parity as parity
|
||||
import local_resolver_cases as resolver_cases
|
||||
import local_resolver_selection_cases as selection_cases
|
||||
from open_handles import assert_closed
|
||||
from test_utils_video_metadata import HAVE_FFMPEG, write_video
|
||||
|
||||
@@ -1111,5 +1118,306 @@ class LocalProjectionParityTests(unittest.TestCase):
|
||||
self.assertTrue({"parsed", "malformed", "limited"} <= seen)
|
||||
|
||||
|
||||
def _server_evidence(records):
|
||||
return inspect_prompt_evidence(records, None, profile=INSPECTION_PROFILE)
|
||||
|
||||
|
||||
class LocalResolverParityTests(unittest.TestCase):
|
||||
"""``resolveLocalEvidence`` answers as ``inspect_prompt_evidence`` (L3 Tasks 8-9).
|
||||
|
||||
Python is the oracle: every expected value is the server's own answer on the
|
||||
same record texts. Task 8 ported one sampler's tracing; Task 9 ports
|
||||
candidate selection (several samplers, the identical-branch rule of #270,
|
||||
preview-only stages, detailer stages) and A1111 ``parameters``, so no
|
||||
record set is left to the server any more.
|
||||
"""
|
||||
|
||||
def setUp(self):
|
||||
temporary = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temporary.cleanup)
|
||||
self.addCleanup(assert_closed, self, temporary.name)
|
||||
self.directory = Path(temporary.name)
|
||||
|
||||
def _compare(self, cases):
|
||||
"""Assert each record set's local evidence equal; return the server answers."""
|
||||
observed = _run_oracle(
|
||||
self,
|
||||
[
|
||||
{"name": name, "mode": "resolve", "records": records}
|
||||
for name, records in cases.items()
|
||||
],
|
||||
)
|
||||
answers = {}
|
||||
for name, records in cases.items():
|
||||
with self.subTest(case=name):
|
||||
local = observed[name]
|
||||
server = _server_evidence(records)
|
||||
answers[name] = server
|
||||
self.assertEqual(
|
||||
_canonical_bytes(local["evidence"]), _canonical_bytes(server)
|
||||
)
|
||||
return answers
|
||||
|
||||
def test_local_roles_match_execution_and_single_chain_vectors(self):
|
||||
files = {}
|
||||
for name in parity.COMMITTED:
|
||||
files[name] = parity.fixture_path(name)
|
||||
for name in parity.TEST_TIME:
|
||||
path = parity.fixture_path(name, self.directory)
|
||||
parity.write_png(path, parity.build(name))
|
||||
files[name] = path
|
||||
observed = _run_oracle(
|
||||
self,
|
||||
[
|
||||
{"name": name, "mode": "resolve", "path": str(path)}
|
||||
for name, path in files.items()
|
||||
],
|
||||
)
|
||||
vectors = {
|
||||
vector["fixture"]: vector
|
||||
for vector in json.loads(parity.VECTORS_PATH.read_text(encoding="utf-8"))
|
||||
if vector["profile"] == "inspection"
|
||||
}
|
||||
compared = 0
|
||||
for name, path in files.items():
|
||||
with self.subTest(fixture=name):
|
||||
local = observed[name]
|
||||
try:
|
||||
records = read_inspection_file(path).metadata
|
||||
except MetadataReadError:
|
||||
self.assertTrue(local["unreadable"])
|
||||
continue
|
||||
# The single-chain subset (Task 8); the rest is Task 9's test below.
|
||||
if not resolver_cases.single_chain(records):
|
||||
continue
|
||||
server = _server_evidence(records)
|
||||
self.assertEqual(
|
||||
_canonical_bytes(local["evidence"]), _canonical_bytes(server)
|
||||
)
|
||||
# The committed vector agrees with the server read here.
|
||||
expect = vectors[name]["expect"]
|
||||
self.assertEqual(server["resolution"]["state"], expect["state"])
|
||||
self.assertEqual(
|
||||
server["resolution"]["reason_code"], expect["reason_code"]
|
||||
)
|
||||
compared += 1
|
||||
self.assertGreaterEqual(compared, 20)
|
||||
|
||||
def test_local_roles_match_inspection_vectors(self):
|
||||
"""Every inspection vector: local prompts, resolution and facts equal Images'.
|
||||
|
||||
The facts are ``extractGenerationFacts`` (with the legacy fill) on the
|
||||
local payload, against the facts the committed vectors pin for the
|
||||
server's response on the same file.
|
||||
"""
|
||||
vectors = [
|
||||
vector
|
||||
for vector in json.loads(parity.VECTORS_PATH.read_text(encoding="utf-8"))
|
||||
if vector["profile"] == "inspection"
|
||||
]
|
||||
files = {}
|
||||
for vector in vectors:
|
||||
name = vector["fixture"]
|
||||
if name in parity.TEST_TIME:
|
||||
path = parity.fixture_path(name, self.directory)
|
||||
parity.write_png(path, parity.build(name))
|
||||
else:
|
||||
path = parity.fixture_path(name)
|
||||
files[name] = path
|
||||
observed = _run_oracle(
|
||||
self,
|
||||
[
|
||||
{"name": name, "mode": "resolve", "path": str(path)}
|
||||
for name, path in files.items()
|
||||
],
|
||||
)
|
||||
for vector in vectors:
|
||||
name = vector["fixture"]
|
||||
with self.subTest(fixture=name):
|
||||
local, expect = observed[name], vector["expect"]
|
||||
try:
|
||||
server = _server_evidence(
|
||||
read_inspection_file(files[name]).metadata
|
||||
)
|
||||
except MetadataReadError:
|
||||
server = unreadable_evidence()
|
||||
self.assertTrue(local["unreadable"])
|
||||
self.assertEqual(
|
||||
_canonical_bytes(local["evidence"]), _canonical_bytes(server)
|
||||
)
|
||||
resolution, prompts = (
|
||||
local["evidence"]["resolution"],
|
||||
local["evidence"]["prompts"],
|
||||
)
|
||||
self.assertEqual(
|
||||
(
|
||||
resolution["state"],
|
||||
resolution["reason"],
|
||||
resolution["reason_code"],
|
||||
),
|
||||
(expect["state"], expect["reason"], expect["reason_code"]),
|
||||
)
|
||||
self.assertEqual(
|
||||
[
|
||||
parity._role_text(
|
||||
prompts[role]["status"], prompts[role]["text"]
|
||||
)
|
||||
for role in ("positive", "negative")
|
||||
],
|
||||
[expect["positive"], expect["negative"]],
|
||||
)
|
||||
self.assertEqual(local["facts"], expect["facts"])
|
||||
self.assertEqual(len(vectors), 28)
|
||||
|
||||
def test_local_roles_match_selection_record_sets(self):
|
||||
answers = self._compare(selection_cases.selection_cases())
|
||||
reasons = {answer["resolution"]["reason"] for answer in answers.values()}
|
||||
self.assertTrue(
|
||||
{
|
||||
"Every sampler branch uses the same prompt pair",
|
||||
"Multiple sampler branches",
|
||||
"Sampler stages have different prompts",
|
||||
"Cyclic sampler stage ancestry",
|
||||
"Expected an image link",
|
||||
"Unsupported sampler stage ancestry",
|
||||
"Resolution depth limit reached",
|
||||
"A1111 settings footer is not unique",
|
||||
"Multiple negative prompt delimiters",
|
||||
"Negative prompt delimiter is absent",
|
||||
"Parameters exceed the length limit",
|
||||
"No A1111 parameters",
|
||||
}
|
||||
<= reasons
|
||||
)
|
||||
# A stage reaching only previews is dropped: one sampler is named.
|
||||
self.assertEqual(
|
||||
answers["select-preview-dropped"]["resolution"]["sampler_id"], "3"
|
||||
)
|
||||
|
||||
def test_local_roles_match_fuzzed_selection_sets(self):
|
||||
cases = {}
|
||||
for seed in range(4):
|
||||
cases.update(selection_cases.selection_fuzz_cases(seed, 150))
|
||||
answers = self._compare(cases)
|
||||
reasons = [answer["resolution"]["reason"] for answer in answers.values()]
|
||||
self.assertGreater(reasons.count("Multiple sampler branches"), 20)
|
||||
self.assertGreater(reasons.count("Sampler stages have different prompts"), 0)
|
||||
self.assertGreater(
|
||||
reasons.count("Every sampler branch uses the same prompt pair"), 0
|
||||
)
|
||||
self.assertGreater(reasons.count("A1111 settings footer is not unique"), 0)
|
||||
|
||||
def test_local_roles_match_golden_record_sets(self):
|
||||
answers = self._compare(resolver_cases.golden_cases())
|
||||
codes = {answer["resolution"]["reason_code"] for answer in answers.values()}
|
||||
self.assertTrue(
|
||||
{
|
||||
"malformed",
|
||||
"unsupported-node",
|
||||
"runtime-value",
|
||||
"composite",
|
||||
"work-limit",
|
||||
"depth-limit",
|
||||
"text-limit",
|
||||
"graph-ceiling",
|
||||
"no-sampler",
|
||||
None,
|
||||
}
|
||||
<= codes
|
||||
)
|
||||
sources = {
|
||||
side["source"]
|
||||
for answer in answers.values()
|
||||
for side in answer["prompts"].values()
|
||||
}
|
||||
self.assertTrue(
|
||||
{"execution", "graph-inferred", "zeroed-conditioning"} <= sources
|
||||
)
|
||||
|
||||
def test_committed_resolver_vectors_are_current(self):
|
||||
"""The Node unit test's committed answers are still the server's."""
|
||||
committed = json.loads(resolver_cases.VECTORS_PATH.read_text(encoding="utf-8"))
|
||||
self.assertEqual(
|
||||
committed,
|
||||
json.loads(json.dumps(resolver_cases.committed_vectors())),
|
||||
"regenerate with: python3 -m tests.local_resolver_cases --write",
|
||||
)
|
||||
|
||||
def test_local_roles_match_at_every_work_bound(self):
|
||||
answers = self._compare(resolver_cases.boundary_cases())
|
||||
for name in ("visits", "depth", "scanned"):
|
||||
self.assertEqual(answers[f"{name}-edge"]["resolution"]["state"], "resolved")
|
||||
self.assertIn(
|
||||
answers[f"{name}-over"]["resolution"]["reason_code"],
|
||||
("work-limit", "depth-limit"),
|
||||
)
|
||||
self.assertEqual(
|
||||
answers["named-astral"]["resolution"]["node"]["class_type"],
|
||||
"\U0001f600" * 64,
|
||||
)
|
||||
|
||||
def test_local_json_depth_cap_at_its_boundary(self):
|
||||
"""Both kinds of deep record at the browser's JSON depth cap (1,000).
|
||||
|
||||
Locally a record nested past the cap is invalid JSON: a prompt is
|
||||
malformed and a workflow is ignored, as the server answers when
|
||||
``json.loads`` raises RecursionError. The server's own limit depends on
|
||||
the Python (TESTING.md, "Deep JSON"): about 990 on 3.10 and 3.11, so it
|
||||
agrees past the cap there; about 10,000 on 3.12 and 3.13 and over
|
||||
50,000 on 3.14, so it agrees up to the cap there and reads deeper.
|
||||
"""
|
||||
cases = resolver_cases.depth_cases()
|
||||
observed = _run_oracle(
|
||||
self,
|
||||
[
|
||||
{"name": name, "mode": "resolve", "records": records}
|
||||
for name, _kind, _depth, records in cases
|
||||
],
|
||||
)
|
||||
newer = sys.version_info >= (3, 12)
|
||||
compared = 0
|
||||
for name, kind, depth, records in cases:
|
||||
with self.subTest(case=name):
|
||||
local = observed[name]["evidence"]["resolution"]
|
||||
within = depth <= resolver_cases.JSON_MAX_DEPTH
|
||||
if kind == "prompt":
|
||||
expected = (
|
||||
("resolved", None) if within else ("unresolved", "malformed")
|
||||
)
|
||||
else:
|
||||
# A workflow that is read finds the overwritten pair (R1).
|
||||
expected = (
|
||||
("unresolved", "malformed") if within else ("resolved", None)
|
||||
)
|
||||
self.assertEqual((local["state"], local["reason_code"]), expected)
|
||||
server = _server_evidence(records)
|
||||
if server["resolution"]["state"] == local["state"]:
|
||||
self.assertEqual(
|
||||
_canonical_bytes(observed[name]["evidence"]),
|
||||
_canonical_bytes(server),
|
||||
)
|
||||
compared += 1
|
||||
else:
|
||||
# The documented divergence only: an older server refuses
|
||||
# a little below the cap, a newer one reads past it.
|
||||
self.assertEqual(within, not newer)
|
||||
self.assertGreaterEqual(compared, 2)
|
||||
|
||||
def test_local_roles_match_fuzzed_record_sets(self):
|
||||
cases = {}
|
||||
for seed in range(4):
|
||||
cases.update(resolver_cases.fuzz_cases(seed, 150))
|
||||
answers = self._compare(cases)
|
||||
states = [answer["resolution"]["state"] for answer in answers.values()]
|
||||
# Coherent graphs reach real results, not only early refusals.
|
||||
self.assertGreater(states.count("resolved"), len(states) // 5)
|
||||
self.assertGreater(states.count("ambiguous"), 0)
|
||||
self.assertGreater(states.count("unresolved"), len(states) // 10)
|
||||
self.assertGreaterEqual(
|
||||
len({answer["resolution"]["reason_code"] for answer in answers.values()}),
|
||||
5,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
"""The concept fixture files carry the concept inspector facts (app.js:400-414)."""
|
||||
|
||||
import json
|
||||
import math
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
@@ -15,6 +17,8 @@ except ImportError: # discovered with tests/ as the top-level directory
|
||||
from tests.browser.workspace_concept_fixture import (
|
||||
CONCEPT_MODEL,
|
||||
CONCEPT_PROMPTS,
|
||||
MAX_EPOCH_SECONDS,
|
||||
_instant,
|
||||
write_concept_png,
|
||||
)
|
||||
from utils.prompt_inspector import inspect_prompt_evidence, read_inspection_file
|
||||
@@ -80,5 +84,29 @@ class TestWorkspaceConceptFixture(unittest.TestCase):
|
||||
self.assertEqual((image["width"], image["height"]), size)
|
||||
|
||||
|
||||
class TestConceptFixtureInstant(unittest.TestCase):
|
||||
"""One "now" for every relative time the fixture writes (PR #284's midnight)."""
|
||||
|
||||
def test_a_chosen_instant_is_kept(self):
|
||||
self.assertEqual(_instant(1_792_713_598), 1_792_713_598.0)
|
||||
self.assertEqual(_instant(1_792_713_598.25), 1_792_713_598.25)
|
||||
|
||||
def test_the_wall_clock_when_omitted(self):
|
||||
before = time.time()
|
||||
now = _instant(None)
|
||||
self.assertLessEqual(before, now)
|
||||
self.assertLessEqual(now, time.time())
|
||||
|
||||
def test_a_non_number_is_refused(self):
|
||||
for value in (True, "1792713598", [1]):
|
||||
with self.subTest(value=value), self.assertRaises(TypeError):
|
||||
_instant(value)
|
||||
|
||||
def test_an_instant_out_of_range_is_refused(self):
|
||||
for value in (0, -1, MAX_EPOCH_SECONDS, math.inf, math.nan):
|
||||
with self.subTest(value=value), self.assertRaises(ValueError):
|
||||
_instant(value)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
Reference in New Issue
Block a user