Merge remote-tracking branch 'origin/main' into fix/inspect-video-settle-followups
# Conflicts: # TESTING.md # web/js/workspace/inspect.mjs
This commit is contained in:
+13
-3
@@ -1180,6 +1180,11 @@
|
||||
`Done — ${data.imported} imported, ${data.skipped} skipped`;
|
||||
this.loadStatistics();
|
||||
setTimeout(() => this.hideModal("loraImportModal"), 2000);
|
||||
} else if (data.type === "error") {
|
||||
// A refusal (another job runs) or a failed import: name it and close the modal.
|
||||
document.getElementById("loraImportStatus").textContent = `Error: ${data.message}`;
|
||||
this.showNotification(`LoRA import failed: ${data.message}`, "error");
|
||||
setTimeout(() => this.hideModal("loraImportModal"), 3000);
|
||||
}
|
||||
} catch (e) { /* skip malformed SSE */ }
|
||||
}
|
||||
@@ -1231,10 +1236,13 @@
|
||||
}
|
||||
this.hideModal("settingsModal");
|
||||
} else {
|
||||
throw new Error("Failed to save settings");
|
||||
// A refusal names its reason (a corrupt config.json, a changed file): show it.
|
||||
const data = await response.json().catch(() => ({}));
|
||||
throw new Error(data.error ? `Failed to save settings: ${data.error}` : "Failed to save settings");
|
||||
}
|
||||
} catch (error) {
|
||||
this.showNotification("Failed to save settings", "error");
|
||||
const reason = error.message.startsWith("Failed to save settings:") ? error.message : "Failed to save settings";
|
||||
this.showNotification(reason, "error");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1848,7 +1856,9 @@
|
||||
throw new Error(data.error || 'Maintenance failed');
|
||||
}
|
||||
} else {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
// A refusal names the job that runs ("Scan for metadata already running").
|
||||
const data = await response.json().catch(() => ({}));
|
||||
throw new Error(data.error || `HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Maintenance error:', error);
|
||||
|
||||
+17
-3
@@ -17,6 +17,14 @@
|
||||
this.dupResults = null;
|
||||
|
||||
this.api = ApiClient.createApiClient();
|
||||
// The page's lifetime ends when it starts to leave: WebKit fails a fetch a leaving page starts
|
||||
// ("Fetch API cannot load … due to access control checks.") and logs it as a page error.
|
||||
this.pageLifetime = new AbortController();
|
||||
window.addEventListener("beforeunload", () => this.pageLifetime.abort());
|
||||
window.addEventListener("pagehide", () => this.pageLifetime.abort());
|
||||
window.addEventListener("pageshow", (e) => {
|
||||
if (e.persisted && this.pageLifetime.signal.aborted) this.pageLifetime = new AbortController();
|
||||
});
|
||||
// Only the newest page request may update the grid
|
||||
this.imagesRequest = ApiClient.latestOnly();
|
||||
|
||||
@@ -2129,8 +2137,11 @@ Seed: ${this.currentMetadata.seed || 'Unknown'}`;
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
if (!response.ok) {
|
||||
// Refused (a running job holds the thumbnails): say why and claim nothing.
|
||||
const data = await response.json().catch(() => ({}));
|
||||
this.showNotification(`Thumbnails were not cleared: ${data.error || `HTTP ${response.status}`}`, 'error');
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('Could not clear server thumbnails:', e);
|
||||
@@ -2531,8 +2542,11 @@ Seed: ${this.currentMetadata.seed || 'Unknown'}`;
|
||||
return;
|
||||
}
|
||||
|
||||
// A leaving page starts no read, and one it aborts is not reported.
|
||||
const signal = this.pageLifetime?.signal;
|
||||
if (signal?.aborted) return;
|
||||
try {
|
||||
const data = await this.api.get('/prompt_manager/images/thumbnails/status');
|
||||
const data = await this.api.get('/prompt_manager/images/thumbnails/status', { signal });
|
||||
const total = data.total_images;
|
||||
const pending = data.pending;
|
||||
if (!data.success || !Number.isSafeInteger(total) ||
|
||||
|
||||
@@ -274,7 +274,8 @@ export function mountActivityJobView(main, { store, scope, api, jobId }) {
|
||||
const lost = job.state === 'lost';
|
||||
if (lost && document.activeElement === download) parts.h1.focus();
|
||||
download.disabled = lost;
|
||||
if (job.state === 'running') {
|
||||
// Truth rule: a job that cannot be cancelled (a held legacy-page job) shows no Cancel.
|
||||
if (job.state === 'running' && job.cancellable) {
|
||||
if (!cancel.isConnected) parts.actions.append(cancel);
|
||||
} else if (cancel.isConnected) {
|
||||
// A focused Cancel that goes away hands its focus to the job's heading, never to the page body.
|
||||
|
||||
@@ -103,6 +103,8 @@ export function parseJob(raw) {
|
||||
scope: plainObject(raw.scope) ? { ...raw.scope } : {},
|
||||
listed,
|
||||
log_length: count(raw.log_length),
|
||||
// A held legacy-page job cannot be cancelled; an older server sends no key (cancellable then).
|
||||
cancellable: raw.cancellable !== false,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -153,11 +153,15 @@ function itemFor(job, scope) {
|
||||
progress.textContent = `${next.progress}%`;
|
||||
progress.setAttribute('aria-label', `${next.title} progress`);
|
||||
if (!progress.isConnected) item.insertBefore(progress, actions.isConnected ? actions : null);
|
||||
if (!actions.isConnected) item.append(actions);
|
||||
} else {
|
||||
progress.remove();
|
||||
}
|
||||
// Truth rule: a job that cannot be cancelled (a held legacy-page job) shows no Cancel job.
|
||||
if (running && next.cancellable) {
|
||||
if (!actions.isConnected) item.append(actions);
|
||||
} else if (actions.isConnected) {
|
||||
// A focused Cancel job that goes away hands its focus to the item's title link, never to the page body.
|
||||
if (actions.contains(document.activeElement)) link.focus();
|
||||
progress.remove();
|
||||
actions.remove();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -5,6 +5,7 @@ import { createSendButton } from './prompt-sender.mjs';
|
||||
import { createWorkspaceIcon } from './icons.mjs';
|
||||
import { navigateTo } from './state.mjs';
|
||||
import { showWorkspaceToast } from './toast.mjs';
|
||||
import { openCopyFallback } from './workspace-dialogs.mjs';
|
||||
|
||||
const RAW_KEYS = ['prompt', 'workflow', 'parameters', 'comfyassets_prompt_pairs'];
|
||||
const RAW_LIMIT = 'Raw metadata exceeds the response limit. Download the original file to inspect it externally.';
|
||||
@@ -26,6 +27,26 @@ const REVEAL_BUSY = 'The folder is already opening.';
|
||||
const REVEAL_FAILED = 'The folder could not be opened. Try again.';
|
||||
const FACTS = [['seed', 'Seed'], ['steps', 'Steps'], ['cfg', 'CFG'], ['sampler', 'Sampler'], ['scheduler', 'Scheduler'], ['model', 'Model']];
|
||||
|
||||
// D117 (LI-4): the legacy metadata page's COPY ALL (web/metadata.html copyAllData), its lines and placeholders.
|
||||
const SUMMARY_LINES = [['Checkpoint', 'model'], ['Positive Prompt', 'positive'], ['Negative Prompt', 'negative'], ['Steps', 'steps'],
|
||||
['CFG Scale', 'cfg'], ['Sampler', 'sampler'], ['Seed', 'seed']];
|
||||
const SUMMARY_MISSING = {positive:'No prompt found', negative:'No negative prompt found'};
|
||||
|
||||
/**
|
||||
* The one-click settings summary (D117): the legacy COPY ALL text for what this inspector shows. A confirmed prompt
|
||||
* and a known fact are copied verbatim; anything else, an explicitly empty prompt included, takes the legacy page's
|
||||
* placeholder, as its parse does (`hasValue` treats '' as absent).
|
||||
*/
|
||||
export function settingsSummary(record) {
|
||||
const roles = promptRoles(record?.prompts);
|
||||
const value = key => {
|
||||
if (Object.hasOwn(SUMMARY_MISSING, key)) return roles[key] ? roles[key] : SUMMARY_MISSING[key];
|
||||
const fact = record?.generation?.[key];
|
||||
return fact?.status === 'known' && typeof fact.value === 'string' && fact.value !== '' ? fact.value : 'Unknown';
|
||||
};
|
||||
return SUMMARY_LINES.map(([label, key]) => `${label}: ${value(key)}`).join('\n');
|
||||
}
|
||||
|
||||
function safeFilename(value) {
|
||||
return String(value || 'file').replace(/[\\/\x00-\x1f\x7f<>:"|?*]/g, '_').replace(/^\.+|[. ]+$/g, '') || 'file';
|
||||
}
|
||||
@@ -175,7 +196,7 @@ function prefixedChip(prefix, text) {
|
||||
* `variant: 'full'` (the viewer's `#viewer-details`, imageDetails(i, true)) leaves out the cover and adds "File &
|
||||
* provenance" and "Workflow & raw metadata" with the downloads. `inline: true` means `panel`; neither means `full`.
|
||||
*/
|
||||
export function mountFileInspector(container, {api, sender, parentScope, variant, inline = false, promptContext = '', onTagFilter, onRetry, onRefresh, onInteraction = () => {}}) {
|
||||
export function mountFileInspector(container, {api, sender, parentScope, variant, inline = false, promptContext = '', onTagFilter, onRetry, onRefresh, onInteraction = () => {}, copyFallback = openCopyFallback}) {
|
||||
if (parentScope.signal.aborted) return {setState() {}, dispose() {}};
|
||||
const scope = childScope(parentScope);
|
||||
let contentScope;
|
||||
@@ -184,7 +205,7 @@ export function mountFileInspector(container, {api, sender, parentScope, variant
|
||||
scope.listen(container, 'keydown', onInteraction);
|
||||
scope.listen(container, 'click', onInteraction);
|
||||
scope.listen(container, 'wheel', onInteraction, {passive:true});
|
||||
scope.cleanup(() => {contentScope?.dispose(); container.replaceChildren(); container.classList.remove('file-inspector');});
|
||||
scope.cleanup(() => {contentScope?.dispose(); container.replaceChildren(); container.classList.remove('file-inspector'); container.removeAttribute('aria-busy');});
|
||||
|
||||
const full = (variant ?? (inline ? 'panel' : 'full')) === 'full';
|
||||
function statusView(state, parent) {
|
||||
@@ -203,6 +224,8 @@ export function mountFileInspector(container, {api, sender, parentScope, variant
|
||||
if (scope.signal.aborted) return;
|
||||
contentScope?.dispose(); contentScope = childScope(scope);
|
||||
container.replaceChildren();
|
||||
// A local read resolves on this thread in bounded steps; the busy state stays until its answer lands.
|
||||
if (state.loading) container.setAttribute('aria-busy', 'true'); else container.removeAttribute('aria-busy');
|
||||
render(state);
|
||||
}
|
||||
/**
|
||||
@@ -244,7 +267,7 @@ export function mountFileInspector(container, {api, sender, parentScope, variant
|
||||
inner.append(tags);
|
||||
}
|
||||
inner.append(...generationFacts(record, 'meta-grid', 'small'));
|
||||
if (full) inner.append(provenance(record, badge), rawMetadata(record));
|
||||
if (full) inner.append(summaryButton(record), provenance(record, badge), rawMetadata(record));
|
||||
const footer = full ? container : el('div', undefined, 'detail-footer'), roles = promptRoles(record.prompts);
|
||||
if (Object.hasOwn(roles, 'positive') && Object.hasOwn(roles, 'negative')) {
|
||||
const pair = createButton('', 'send');
|
||||
@@ -264,6 +287,23 @@ export function mountFileInspector(container, {api, sender, parentScope, variant
|
||||
}
|
||||
if (!full && footer.childNodes.length) container.append(footer);
|
||||
}
|
||||
/**
|
||||
* D117 (LI-4): "Copy settings summary" after the six facts, the legacy COPY ALL. It copies as the concept's prompt
|
||||
* copy does: the shared toast, or the select-to-copy dialog where the clipboard is unavailable or refused.
|
||||
*/
|
||||
function summaryButton(record) {
|
||||
const button = createButton('Copy settings summary', 'settings-summary'), text = settingsSummary(record);
|
||||
contentScope.listen(button, 'click', async () => {
|
||||
try {
|
||||
if (!navigator.clipboard) throw new Error('Clipboard requires a secure context');
|
||||
await navigator.clipboard.writeText(text);
|
||||
if (!contentScope.signal.aborted) showWorkspaceToast('Settings summary copied.');
|
||||
} catch {
|
||||
if (!contentScope.signal.aborted) copyFallback(text, {scope:contentScope, trigger:button, title:'Copy settings summary'});
|
||||
}
|
||||
});
|
||||
return button;
|
||||
}
|
||||
/** The concept's plain cover; the card image opens the viewer (D19). Video keeps its own element. */
|
||||
function cover(record) {
|
||||
const {file} = record, video = file?.media_type === 'video';
|
||||
|
||||
@@ -7,6 +7,7 @@ import { pageHeading } from './heading.mjs';
|
||||
import { createWorkspaceIcon } from './icons.mjs';
|
||||
import { createLocalSession, LOCAL_SESSION_MESSAGES } from './local-session.mjs';
|
||||
import { localFileAdapter } from './local-inspection.mjs';
|
||||
import { loadInspectionSemantics } from './local-semantics.mjs';
|
||||
import { createMediaViewer } from './media-viewer.mjs';
|
||||
import { showWorkspaceToast, TOAST_MS } from './toast.mjs';
|
||||
|
||||
@@ -74,6 +75,8 @@ export function mountInspect(main, { parentScope, api, sender }) {
|
||||
if (parentScope.signal.aborted) { scope.dispose(); return { dispose }; }
|
||||
parentScope.signal.addEventListener('abort', dispose, { once: true });
|
||||
scope.cleanup(() => parentScope.signal.removeEventListener('abort', dispose));
|
||||
// The node table the local roles resolve with, read before any file is chosen (one request per page).
|
||||
loadInspectionSemantics();
|
||||
|
||||
// The concept DOM: section.surface > h2, p; div.file-drop.spaced-20 > icon, label, input, span.small; #local-preview.
|
||||
const surface = element('section', 'surface');
|
||||
|
||||
@@ -6,12 +6,11 @@
|
||||
import { readVideoTags, selectVideoCarrier } from './local-video.mjs';
|
||||
import { projectMetadata, fitInspectionPayload, MAX_RESPONSE_BYTES } from './local-projection.mjs';
|
||||
import { projectInspectionPayload } from './inspection-state.mjs';
|
||||
import { resolveLocalEvidence, unreadableEvidence } from './local-resolver.mjs';
|
||||
import { loadInspectionSemantics } from './local-semantics.mjs';
|
||||
|
||||
export const LOCAL_OBSERVATION = 'selected-local-file';
|
||||
export const LOCAL_SOURCE_LABEL = 'Selected local file';
|
||||
// Interim roles until PR L3 ports the inspection resolver: every role is open, and
|
||||
// the legacy fill in projectInspectionPayload shows what the legacy pages show.
|
||||
const LOCAL_RESOLUTION_REASON = 'Resolved in this browser from the workflow.';
|
||||
const LOCAL_LIBRARY = Object.freeze({ status: 'unavailable', scope: 'saved-library', tags: [], category_scope: null, tags_scope: null });
|
||||
const LOCAL_SCOPE = 'local';
|
||||
const PREFIX_BYTES = 32;
|
||||
@@ -19,6 +18,24 @@ const MAX_FILENAME_CHARS = 255;
|
||||
const MEDIA_TYPES = new Set(['image', 'video']);
|
||||
|
||||
const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
const abortError = () => new DOMException('The local selection ended', 'AbortError');
|
||||
|
||||
/** `promise`, or an AbortError as soon as `signal` aborts (the work behind `promise` is shared and keeps going). */
|
||||
function untilAborted(promise, signal) {
|
||||
if (!signal) return promise;
|
||||
if (signal.aborted) return Promise.reject(abortError());
|
||||
return new Promise((resolve, reject) => {
|
||||
const onAbort = () => reject(abortError());
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
promise.then(value => { signal.removeEventListener('abort', onAbort); resolve(value); },
|
||||
error => { signal.removeEventListener('abort', onAbort); reject(error); });
|
||||
});
|
||||
}
|
||||
|
||||
/** One turn of the event loop between bounded steps, so the busy state paints and input is handled. */
|
||||
function nextTurn(signal) {
|
||||
return untilAborted(new Promise(resolve => setTimeout(resolve, 0)), signal);
|
||||
}
|
||||
const pngReader = () => globalThis.PngMetadata || globalThis.window?.PngMetadata;
|
||||
|
||||
/** A display name with no path separators or control characters; never empty. */
|
||||
@@ -88,8 +105,19 @@ export function toInspectionRead(classification, result) {
|
||||
|
||||
const dimension = value => Number.isSafeInteger(value) && value > 0 ? value : null;
|
||||
|
||||
/** The `inspection_version: 1` wire for one local read, before the response budget. */
|
||||
export function buildLocalPayload({ read, file, classification }) {
|
||||
/** The roles for one local read (`{prompts, resolution}`): the bounded parse and resolution step of buildLocalPayload. */
|
||||
export function localEvidence(read, classification, semantics = null) {
|
||||
const inspection = toInspectionRead(classificationOf(classification), read);
|
||||
return inspection.read === null ? unreadableEvidence() : resolveLocalEvidence(inspection.read.records, semantics);
|
||||
}
|
||||
|
||||
/**
|
||||
* The `inspection_version: 1` wire for one local read, before the response budget. Its roles are the server
|
||||
* inspector's for the same records (local-resolver.mjs with `semantics`, the compiled node table; null answers
|
||||
* "unavailable" as the server does), so the legacy fill in projectInspectionPayload applies exactly where it does
|
||||
* for Images.
|
||||
*/
|
||||
export function buildLocalPayload({ read, file, classification, semantics = null, evidence = localEvidence(read, classification, semantics) }) {
|
||||
const classified = classificationOf(classification);
|
||||
const inspection = toInspectionRead(classified, read);
|
||||
const filename = sanitizeLocalFilename(file?.name);
|
||||
@@ -101,8 +129,8 @@ export function buildLocalPayload({ read, file, classification }) {
|
||||
observation: LOCAL_OBSERVATION, source_label: LOCAL_SOURCE_LABEL, media_type: classified.media, extension: localExtension(filename),
|
||||
format: inspection.format, size, width: dimension(inspection.width), height: dimension(inspection.height), modified_time: modified,
|
||||
},
|
||||
prompts: { positive: { status: 'unresolved' }, negative: { status: 'unresolved' } },
|
||||
resolution: { state: 'unresolved', sampler_id: null, reason: LOCAL_RESOLUTION_REASON, reason_code: null, node: null },
|
||||
prompts: evidence.prompts,
|
||||
resolution: evidence.resolution,
|
||||
metadata: projectMetadata(inspection.read),
|
||||
library: { ...LOCAL_LIBRARY, tags: [] },
|
||||
};
|
||||
@@ -166,7 +194,12 @@ export const localFileAdapter = Object.freeze({
|
||||
scope(handle) { owned(handle); return LOCAL_SCOPE; },
|
||||
// An inert sentinel: the controller's same-key check works and no URL is ever built.
|
||||
inspectionPath(handle) { return `local-file:${owned(handle).key}`; },
|
||||
async read(handle, { signal } = {}) {
|
||||
/**
|
||||
* Reads, resolves and projects one selection on the page's thread in bounded steps (each bound by the 2 MiB role
|
||||
* and 4 MiB workflow budgets and the resolver's work limits) with a turn of the event loop between them, so the
|
||||
* inspector's busy state paints. Every wait ends with the selection's `signal`; `yieldControl` is for tests.
|
||||
*/
|
||||
async read(handle, { signal, yieldControl = nextTurn } = {}) {
|
||||
const secret = owned(handle);
|
||||
let result = null;
|
||||
try {
|
||||
@@ -176,7 +209,14 @@ export const localFileAdapter = Object.freeze({
|
||||
// MetadataReadError, an unreadable record. Abort and programming errors still reject.
|
||||
if (!(error instanceof DOMException) || error.name === 'AbortError' || signal?.aborted) throw error;
|
||||
}
|
||||
return fitLocalPayload(buildLocalPayload({ read: result, file: { name: secret.filename, size: secret.file.size, lastModified: secret.file.lastModified }, classification: secret.classification }), MAX_RESPONSE_BYTES, { signal });
|
||||
const semantics = await untilAborted(loadInspectionSemantics(), signal);
|
||||
await yieldControl(signal);
|
||||
const evidence = localEvidence(result, secret.classification, semantics);
|
||||
await yieldControl(signal);
|
||||
const file = { name: secret.filename, size: secret.file.size, lastModified: secret.file.lastModified };
|
||||
const payload = buildLocalPayload({ read: result, file, classification: secret.classification, semantics, evidence });
|
||||
await yieldControl(signal);
|
||||
return fitLocalPayload(payload, MAX_RESPONSE_BYTES, { signal });
|
||||
},
|
||||
toRecord(result, handle, extractFacts) {
|
||||
const secret = owned(handle);
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
// A1111 `parameters` for local-resolver.mjs (#249 local Inspect, PR L3 Task 9): a port of
|
||||
// utils/prompt_pair_resolver.py `_parameters`, `_footer` and `_trailer_lines` for the inspection profile.
|
||||
// Python's `re` differs from JavaScript's in three ways that matter here, so the patterns spell them out:
|
||||
// multiline `^`/`$` break only at "\n" (not "\r", U+2028 or U+2029), `\s` is the `str.isspace()` set and `\d`
|
||||
// is any Unicode decimal digit (Nd). Lengths count code points. No DOM.
|
||||
import { PY_SPACE, pyLen, pyStrip } from './py-json.mjs';
|
||||
import { EMPTY_POSITIVE_REASON, result } from './local-resolver-support.mjs';
|
||||
|
||||
const START = '(?<=^|\\n)', END = '(?=\\n|$)', SPACE = `[${PY_SPACE}]*`;
|
||||
// `_FOOTER` and `_BARE_FOOTER` (inspection reads a bare `Steps: N` when there is no full footer).
|
||||
const FOOTER = new RegExp(`${START}Steps:${SPACE}\\p{Nd}+${SPACE},[^\\n]*${END}`, 'gu');
|
||||
const BARE_FOOTER = new RegExp(`${START}Steps:${SPACE}\\p{Nd}+${SPACE}${END}`, 'gu');
|
||||
const TRAILERS = ['Template:', 'Negative Template:'];
|
||||
const DELIMITER = '\nNegative prompt:';
|
||||
|
||||
/** `_trailer_lines`: empty, or at most one `Template:` line then at most one `Negative Template:` line. */
|
||||
function trailerLines(text) {
|
||||
const stripped = pyStrip(text);
|
||||
const lines = stripped ? stripped.split(/\r?\n|\r/) : [];
|
||||
const prefixes = lines.map(line => {
|
||||
const index = TRAILERS.findIndex(name => line.startsWith(name));
|
||||
return index === -1 ? null : index;
|
||||
});
|
||||
return !prefixes.includes(null) && prefixes.every((prefix, index) => index === 0 || prefix > prefixes[index - 1]);
|
||||
}
|
||||
|
||||
/** `_footer(value, inspection=True)`: the unique settings footer match, or null. */
|
||||
function footer(value) {
|
||||
let footers = [...value.matchAll(FOOTER)];
|
||||
if (!footers.length) footers = [...value.matchAll(BARE_FOOTER)];
|
||||
if (footers.length !== 1) return null;
|
||||
const [match] = footers;
|
||||
return trailerLines(value.slice(match.index + match[0].length)) ? match : null;
|
||||
}
|
||||
|
||||
const rstripLineBreaks = text => text.replace(/[\r\n]+$/, '');
|
||||
|
||||
/** `_parameters(value, max_text_length, inspection=True)`. */
|
||||
export function parameters(value, maxTextLength) {
|
||||
if (typeof value !== 'string' || !value) return result('absent', { reason: 'No A1111 parameters' });
|
||||
if (pyLen(value) > maxTextLength) return result('unresolved', { reason: 'Parameters exceed the length limit', reasonCode: 'text-limit' });
|
||||
const match = footer(value);
|
||||
if (match === null) return result('unresolved', { reason: 'A1111 settings footer is not unique', reasonCode: 'malformed' });
|
||||
// R4: text that starts with the delimiter has an empty positive (#165).
|
||||
const body = `\n${rstripLineBreaks(value.slice(0, match.index))}`;
|
||||
const parts = body.split(DELIMITER);
|
||||
if (parts.length > 2) return result('ambiguous', { reason: 'Multiple negative prompt delimiters' });
|
||||
const positive = pyStrip(parts[0]);
|
||||
if (!positive) return result('unresolved', { reason: EMPTY_POSITIVE_REASON });
|
||||
const provenance = { format: 'a1111', field: 'parameters', text_source: 'embedded-parameters' };
|
||||
const side = (text, role) => ({ text, storage_text: text, provenance: { ...provenance, role } });
|
||||
if (parts.length === 1) return result('absent', { positive: side(positive, 'positive'), reason: 'Negative prompt delimiter is absent' });
|
||||
const negative = pyStrip(parts[1]);
|
||||
return result('resolved', { positive: side(positive, 'positive'), negative: side(negative, 'negative') });
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
// Candidate selection for local-resolver.mjs (#249 local Inspect, PR L3 Task 9): ports of
|
||||
// utils/prompt_pair_resolver.py `_GraphResolver` `stage`, `upstream_stages`, `final_stages`, `file_stages`,
|
||||
// `non_file_outputs`, `producers_of`, `consumers`, `reaches_output`, plus `_outcome_key`, `_recipe_key` and
|
||||
// `_shared_pair` (#270). Each function takes the resolver whose budgets and caches it spends, so the order of
|
||||
// work, and with it every limit, is the server's. No DOM.
|
||||
import { isDict, pyGet, pyStr } from './py-json.mjs';
|
||||
import { DETAILER, IDENTICAL_BRANCHES_REASON, Unresolved, isLink, result } from './local-resolver-support.mjs';
|
||||
|
||||
const roleText = side => side !== null && typeof side === 'object' ? side.text : null;
|
||||
const storageText = side => side !== null && typeof side === 'object' ? side.storage_text : null;
|
||||
/** `_outcome_key`: what a reader sees of a result, the state and the two role texts. */
|
||||
export const outcomeKey = item => JSON.stringify([item.state, roleText(item.positive), roleText(item.negative)]);
|
||||
/** `_recipe_key`: the outcome plus each side's stored recipe. */
|
||||
const recipeKey = item => JSON.stringify([item.state, roleText(item.positive), roleText(item.negative), storageText(item.positive), storageText(item.negative)]);
|
||||
|
||||
/** `_shared_pair`: the one pair every sampler branch resolved to, or null (#270). */
|
||||
export function sharedPair(candidates) {
|
||||
const first = candidates[0];
|
||||
if (first.state !== 'resolved') return null;
|
||||
if (new Set(candidates.map(recipeKey)).size !== 1) return null;
|
||||
return result('resolved', { positive: first.positive, negative: first.negative, reason: IDENTICAL_BRANCHES_REASON, candidates });
|
||||
}
|
||||
|
||||
/** `stage`: one sampler's result; a detailer is compared with its upstream stages. */
|
||||
export function stage(resolver, samplerId, later) {
|
||||
if (later.size >= resolver.maxDepth) return result('unresolved', { samplerId, reason: 'Resolution depth limit reached', reasonCode: 'depth-limit' });
|
||||
const own = resolver.sides(samplerId);
|
||||
if (own.state === 'unresolved') return own;
|
||||
const [name, inputs] = resolver.node(samplerId);
|
||||
const entry = resolver.semantics.samplers.get(name);
|
||||
if (entry === undefined || entry.strategy !== DETAILER) return own;
|
||||
let upstream;
|
||||
try {
|
||||
upstream = upstreamStages(resolver, samplerId, pyGet(inputs, entry.image_stage));
|
||||
if (upstream.some(nodeId => later.has(nodeId))) throw new Unresolved('Cyclic sampler stage ancestry', 'malformed');
|
||||
} catch (error) {
|
||||
if (!(error instanceof Unresolved)) throw error;
|
||||
return result('unresolved', { samplerId, reason: error.message, reasonCode: error.code, node: error.node });
|
||||
}
|
||||
if (!upstream.length) return own;
|
||||
const deeper = new Set([...later, samplerId]);
|
||||
const stages = upstream.map(nodeId => stage(resolver, nodeId, deeper));
|
||||
const blocked = stages.find(item => item.state === 'unresolved');
|
||||
// A stage that cannot be read cannot be compared: never pick one.
|
||||
if (blocked !== undefined) return result('unresolved', { samplerId, reason: blocked.reason, reasonCode: blocked.reason_code, node: blocked.node });
|
||||
const flat = [];
|
||||
for (const item of [own, ...stages]) flat.push(...(item.state === 'ambiguous' ? item.candidates : [item]));
|
||||
if (new Set(flat.map(outcomeKey)).size === 1) return own;
|
||||
return result('ambiguous', { samplerId, reason: 'Sampler stages have different prompts', candidates: flat, reasonCode: 'multistage-differs' });
|
||||
}
|
||||
|
||||
/** `upstream_stages`: samplers reached from a detailer's image input, breadth first; each node draws a visit. */
|
||||
function upstreamStages(resolver, origin, value) {
|
||||
if (!isLink(value)) throw new Unresolved('Expected an image link', 'malformed');
|
||||
const found = [], start = String(value[0]), queue = [[start, 0]], queued = new Set([start]);
|
||||
for (let head = 0; head < queue.length; head++) {
|
||||
const [nodeId, depth] = queue[head];
|
||||
if (nodeId === origin) throw new Unresolved('Cyclic sampler stage ancestry', 'malformed');
|
||||
if (depth >= resolver.maxDepth) throw new Unresolved('Resolution depth limit reached', 'depth-limit');
|
||||
resolver.budget.spend();
|
||||
const [name, inputs] = resolver.node(nodeId);
|
||||
if (resolver.stageClasses.has(name)) { found.push(nodeId); continue; }
|
||||
if (resolver.stageShaped(name, inputs)) throw resolver.unsupported('Unsupported sampler stage ancestry', nodeId);
|
||||
resolver.enqueue(queue, queued, inputs, depth + 1);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
const strategyOf = (resolver, nodeId) => resolver.semantics.samplers.get(resolver.graph.get(nodeId).get('class_type')).strategy;
|
||||
|
||||
/** `final_stages`: drop samplers that only feed detailers (each is judged in that chain). */
|
||||
export function finalStages(resolver, samplerIds) {
|
||||
samplerIds = fileStages(resolver, samplerIds);
|
||||
const detailers = samplerIds.filter(nodeId => strategyOf(resolver, nodeId) === DETAILER);
|
||||
if (!detailers.length) return samplerIds;
|
||||
let reverse;
|
||||
try { reverse = consumers(resolver); } catch (error) {
|
||||
if (!(error instanceof Unresolved)) throw error;
|
||||
return samplerIds;
|
||||
}
|
||||
const absorbed = new Set();
|
||||
for (const detailer of detailers) {
|
||||
resolver.budget.reset(resolver.perCandidateVisits);
|
||||
try {
|
||||
const [name, inputs] = resolver.node(detailer);
|
||||
const image = pyGet(inputs, resolver.semantics.samplers.get(name).image_stage);
|
||||
for (const nodeId of upstreamStages(resolver, detailer, image)) {
|
||||
if (!reachesOutput(resolver, nodeId, reverse)) absorbed.add(nodeId);
|
||||
}
|
||||
} catch (error) {
|
||||
if (!(error instanceof Unresolved)) throw error;
|
||||
}
|
||||
}
|
||||
const kept = samplerIds.filter(nodeId => !absorbed.has(nodeId));
|
||||
return kept.length ? kept : samplerIds;
|
||||
}
|
||||
|
||||
/** `file_stages`: stages not proven preview-only; all of them when every one is. */
|
||||
function fileStages(resolver, samplerIds) {
|
||||
if (samplerIds.length < 2) return samplerIds;
|
||||
let toFile, toPreview;
|
||||
try {
|
||||
const reverse = consumers(resolver), previews = nonFileOutputs(resolver);
|
||||
const terminals = [...resolver.graph].filter(([nodeId, node]) => isDict(node) && !previews.has(nodeId) && !reverse.get(nodeId)?.length).map(([nodeId]) => nodeId);
|
||||
toFile = producersOf(resolver, terminals, previews);
|
||||
toPreview = producersOf(resolver, [...previews], previews);
|
||||
} catch (error) {
|
||||
if (!(error instanceof Unresolved)) throw error;
|
||||
return samplerIds;
|
||||
}
|
||||
const kept = samplerIds.filter(nodeId => toFile.has(nodeId) || !toPreview.has(nodeId));
|
||||
return kept.length ? kept : samplerIds;
|
||||
}
|
||||
|
||||
function nonFileOutputs(resolver) {
|
||||
const names = resolver.semantics.nonFileOutputs, found = new Set();
|
||||
for (const [nodeId, node] of resolver.graph) {
|
||||
// `node.get("class_type") in names`: only a string can be a listed class.
|
||||
if (isDict(node) && names.has(pyGet(node, 'class_type'))) found.add(nodeId);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** `producers_of`: nodes whose output reaches one of `starts`, never through a preview. */
|
||||
function producersOf(resolver, starts, previews) {
|
||||
const found = new Set(starts), queue = [...starts];
|
||||
for (let head = 0; head < queue.length; head++) {
|
||||
const inputs = pyGet(resolver.graph.get(queue[head]), 'inputs');
|
||||
if (!isDict(inputs)) continue;
|
||||
resolver.scan(inputs.size);
|
||||
for (const value of inputs.values()) {
|
||||
if (!isLink(value)) continue;
|
||||
const producer = String(value[0]);
|
||||
if (found.has(producer) || previews.has(producer) || !isDict(pyGet(resolver.graph, producer))) continue;
|
||||
found.add(producer);
|
||||
queue.push(producer);
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** `consumers`: reverse links, node ID to the IDs of nodes reading one of its outputs. */
|
||||
function consumers(resolver) {
|
||||
const reverse = new Map();
|
||||
for (const [nodeId, node] of resolver.graph) {
|
||||
if (!isDict(node) || !isDict(pyGet(node, 'inputs'))) continue;
|
||||
const inputs = node.get('inputs');
|
||||
resolver.scan(inputs.size);
|
||||
for (const value of inputs.values()) {
|
||||
if (!isLink(value)) continue;
|
||||
const producer = String(value[0]);
|
||||
if (!reverse.has(producer)) reverse.set(producer, []);
|
||||
reverse.get(producer).push(nodeId);
|
||||
}
|
||||
}
|
||||
return reverse;
|
||||
}
|
||||
|
||||
/** `reaches_output`: whether a sampler's output reaches a terminal node besides later stages. */
|
||||
function reachesOutput(resolver, nodeId, reverse) {
|
||||
const seen = new Set([nodeId]), queue = [nodeId];
|
||||
for (let head = 0; head < queue.length; head++) {
|
||||
for (const consumer of reverse.get(queue[head]) ?? []) {
|
||||
if (seen.has(consumer)) continue;
|
||||
seen.add(consumer);
|
||||
resolver.budget.spend();
|
||||
const name = pyStr(pyGet(resolver.graph.get(consumer), 'class_type', ''));
|
||||
if (resolver.stageClasses.has(name) || resolver.semantics.nonFileOutputs.has(name)) continue;
|
||||
if (!reverse.get(consumer)?.length) return true;
|
||||
queue.push(consumer);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
// Tables, evidence reader, bounds and outcome lines for local-resolver.mjs (#249 local Inspect, PR L3 Tasks 8-9):
|
||||
// the constants of utils/prompt_pair_resolver.py and utils/inspection_outcomes.py, utils/pair_execution.py
|
||||
// `read_pair_execution` and the semantics table check of utils/inspection_semantics.py. No DOM.
|
||||
import { PyFloat, PyValueError, isDict, isList, isInt, pyJsonLoads, pyLen, pySlice, pyStrip, pyTruthy, pyEqualsOne, pyStr, pyGet } from './py-json.mjs';
|
||||
|
||||
/** The semantics table is unusable: the server's `SemanticsError`. */
|
||||
export class SemanticsError extends Error {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
this.name = 'SemanticsError';
|
||||
}
|
||||
}
|
||||
|
||||
// INSPECTION_PROFILE (prompt_pair_resolver.py 152-166); its drop_preview_only_stages is always on here.
|
||||
export const PROFILE = Object.freeze({
|
||||
perCandidateVisits: 2000, totalVisits: 20000, maxDepth: 64, maxTextLength: 100000, nodeCeiling: 20000,
|
||||
maxPathEntries: 64 * 20000, maxBuiltChars: 16 * 100000, maxScannedUnits: 8000000,
|
||||
});
|
||||
export const EXECUTION_KEY = 'comfyassets_prompt_pairs';
|
||||
export const ROLE_METADATA_KEYS = new Set(['prompt', 'parameters', EXECUTION_KEY]);
|
||||
// pair_execution.py
|
||||
export const MAX_EXECUTION_RECORDS = 16, MAX_EXECUTION_NODES = 64, MAX_EXECUTION_TEXT = 100000, MAX_EXECUTION_JSON = 500000;
|
||||
export const EXECUTION_FIELDS = ['text', 'negative_text', 'positive_text', 'negative_effective_text', 'prepend_text', 'append_text'];
|
||||
|
||||
export const CANDIDATE_STRATEGIES = new Set(['ksampler', 'custom-advanced', 'detailer-stage']);
|
||||
export const DETAILER = 'detailer-stage';
|
||||
export const GUIDER_ABSENT_REASON = 'Guider has no negative input';
|
||||
export const ZEROED_SOURCE = 'zeroed-conditioning';
|
||||
export const MAX_BRANCH_CANDIDATES = 32;
|
||||
export const RUNTIME_REASON = 'Text is decided at run time';
|
||||
export const EMPTY_POSITIVE_REASON = 'Positive prompt is empty';
|
||||
export const IDENTICAL_BRANCHES_REASON = 'Every sampler branch uses the same prompt pair';
|
||||
export const MULTISTAGE_UNATTRIBUTED_REASON = 'Multistage sampler ancestry is ambiguous';
|
||||
export const MALFORMED_EVIDENCE_REASON = 'Prompt evidence is malformed';
|
||||
export const UNREADABLE_METADATA_REASON = 'Media metadata could not be read';
|
||||
export const SEMANTICS_UNAVAILABLE_REASON = 'Inspection node semantics are unavailable';
|
||||
export const INCOMPATIBLE_SLOT = 'Output slot has an incompatible type';
|
||||
export const OVERWRITTEN_PROMPT_REASON = 'Saved PromptManager text was overwritten by another node';
|
||||
export const UNVERIFIABLE_CODES = new Set(['unsupported-node', 'runtime-value']);
|
||||
export const MAX_JOIN_INPUTS = 1000;
|
||||
export const SAMPLER_LIKE_INPUTS = ['latent_image', 'guider', 'positive', 'negative'];
|
||||
export const NO_SAMPLER_NAMES = 3;
|
||||
export const CLASS_NAME_LENGTH = 64;
|
||||
export const MAX_SUBGRAPH_DEPTH = 8, MAX_WORKFLOW_NODES = 100000;
|
||||
|
||||
// inspection_outcomes.py
|
||||
export const OUTCOME_NAME_LENGTH = 200;
|
||||
export const LIMIT_CODES = ['work-limit', 'depth-limit', 'text-limit', 'graph-ceiling'];
|
||||
export const NAMED_LINES = {
|
||||
'unsupported-node': 'Prompt uses a node the inspector does not support',
|
||||
'runtime-value': 'Prompt is chosen at run time',
|
||||
composite: 'Prompt combines several texts',
|
||||
};
|
||||
export const CODED_LINES = {
|
||||
...Object.fromEntries(LIMIT_CODES.map(code => [code, 'Prompt exceeds inspection limits.'])),
|
||||
'no-sampler': 'No supported sampler was found.',
|
||||
malformed: 'Prompt metadata in this file is malformed.',
|
||||
'multistage-differs': 'Sampler stages have different prompts.',
|
||||
};
|
||||
export const UNCODED_LINES = {
|
||||
[EMPTY_POSITIVE_REASON]: 'Positive prompt is empty.',
|
||||
[MULTISTAGE_UNATTRIBUTED_REASON]: 'Several sampler stages were found; their prompts were not compared.',
|
||||
[SEMANTICS_UNAVAILABLE_REASON]: "The inspector's node table is unavailable.",
|
||||
[UNREADABLE_METADATA_REASON]: 'Metadata in this file could not be read.',
|
||||
};
|
||||
|
||||
// Output adapters (prompt_pair_resolver.py 44-105): [inputName, kind, {compose, storageInput, comma, strip, default}].
|
||||
export const adapter = (inputName, kind, options = {}) => Object.freeze({ inputName, kind, compose: false, storageInput: false, comma: false, strip: false, default: null, ...options });
|
||||
export const slotKey = (name, slot) => `${name}\u0000${String(slot)}`;
|
||||
export const ADAPTERS = new Map();
|
||||
for (const name of ['PromptManager', 'PromptManagerFocused', 'PromptManagerSplit']) {
|
||||
ADAPTERS.set(slotKey(name, 0), adapter('text', 'conditioning', { compose: true }));
|
||||
ADAPTERS.set(slotKey(name, 1), adapter('text', 'string', { compose: true }));
|
||||
}
|
||||
ADAPTERS.set(slotKey('PromptManagerPair', 0), adapter('text', 'conditioning', { compose: true }));
|
||||
ADAPTERS.set(slotKey('PromptManagerPair', 2), adapter('text', 'string', { compose: true }));
|
||||
ADAPTERS.set(slotKey('PromptManagerPair', 1), adapter('negative_text', 'conditioning', { storageInput: true }));
|
||||
ADAPTERS.set(slotKey('PromptManagerPair', 3), adapter('negative_text', 'string', { storageInput: true }));
|
||||
ADAPTERS.set(slotKey('PromptManagerText', 0), adapter('text', 'string', { compose: true }));
|
||||
ADAPTERS.set(slotKey('CLIPTextEncode', 0), adapter('text', 'conditioning'));
|
||||
for (const name of ['PrimitiveString', 'PrimitiveStringMultiline']) ADAPTERS.set(slotKey(name, 0), adapter('value', 'string'));
|
||||
for (const name of ['Text Multiline', 'String Literal', 'ShowText|pysssss']) ADAPTERS.set(slotKey(name, 0), adapter('text', 'string'));
|
||||
// Historical PromptManager classes (inspection only).
|
||||
export const COMMA = { comma: true }, NEGATIVE = { strip: true, default: '' };
|
||||
const historical = [
|
||||
['PromptManagerV2', 0, 'text', 'conditioning', COMMA], ['PromptManagerV2', 1, 'negative_text', 'conditioning', NEGATIVE],
|
||||
['PromptManagerV2', 2, 'text', 'string', COMMA], ['PromptManagerV2', 3, 'negative_text', 'string', NEGATIVE],
|
||||
['PromptManagerV2Text', 0, 'text', 'string', COMMA], ['PromptManagerV2Text', 1, 'negative_text', 'string', NEGATIVE],
|
||||
['PromptManagerNegative', 0, 'text', 'conditioning', { strip: true }], ['PromptManagerNegative', 1, 'text', 'string', { strip: true }],
|
||||
['PromptManagerPositiveText', 0, 'text', 'string', COMMA], ['PromptManagerNegativeText', 0, 'text', 'string', COMMA],
|
||||
];
|
||||
for (const name of ['PromptManagerPositive', 'PromptManagerDetailer']) historical.push([name, 0, 'text', 'conditioning', COMMA], [name, 1, 'text', 'string', COMMA]);
|
||||
for (const [name, slot, input, kind, options] of historical) ADAPTERS.set(slotKey(name, slot), adapter(input, kind, options));
|
||||
// `known_slots` in execution_record: every adapter slot per class.
|
||||
export const ADAPTER_SLOTS = new Map();
|
||||
for (const key of ADAPTERS.keys()) {
|
||||
const [name, slot] = key.split('\u0000');
|
||||
if (!ADAPTER_SLOTS.has(name)) ADAPTER_SLOTS.set(name, new Set());
|
||||
ADAPTER_SLOTS.get(name).add(slot);
|
||||
}
|
||||
|
||||
export class Unresolved extends Error {
|
||||
constructor(message, code = null, node = null) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
this.node = node;
|
||||
}
|
||||
}
|
||||
export class Diverging extends Error {
|
||||
constructor(key) {
|
||||
super('diverging');
|
||||
this.key = key;
|
||||
}
|
||||
}
|
||||
|
||||
/** `_link`: a two-item list of (str or int) and a non-negative int, never a bool. */
|
||||
export function isLink(value) {
|
||||
if (!isList(value) || value.length !== 2) return false;
|
||||
const [source, slot] = value;
|
||||
return (typeof source === 'string' || isInt(source)) && isInt(slot) && (typeof slot === 'bigint' ? slot >= 0n : slot >= 0);
|
||||
}
|
||||
export const nodeRef = (nodeId, classType) => ({ id: pySlice(nodeId, CLASS_NAME_LENGTH), class_type: typeof classType === 'string' ? pySlice(classType, CLASS_NAME_LENGTH) : null });
|
||||
|
||||
export function result(state, { positive = null, negative = null, samplerId = null, reason = '', candidates = [], reasonCode = null, node = null } = {}) {
|
||||
return { state, positive, negative, sampler_id: samplerId, reason, candidates, reason_code: reasonCode, node };
|
||||
}
|
||||
|
||||
export class Budget {
|
||||
constructor(total) {
|
||||
this.total = total;
|
||||
this.allowance = total;
|
||||
}
|
||||
reset(allowance) { this.allowance = allowance; }
|
||||
spend() {
|
||||
if (this.total <= 0 || this.allowance <= 0) throw new Unresolved('Resolution visit limit reached', 'work-limit');
|
||||
this.total -= 1;
|
||||
this.allowance -= 1;
|
||||
}
|
||||
charge(cost) {
|
||||
if (cost > this.allowance) throw new Unresolved('Resolution visit limit reached', 'work-limit');
|
||||
this.allowance -= cost;
|
||||
}
|
||||
}
|
||||
|
||||
/** `read_pair_execution`: one distinct record for a traced node, or null; malformed evidence throws `Unresolved`. */
|
||||
export function readPairExecution(metadata, nodeId) {
|
||||
const evidence = message => new Unresolved(message, 'malformed');
|
||||
if (!isDict(metadata) || !metadata.has(EXECUTION_KEY)) return null;
|
||||
let envelope = metadata.get(EXECUTION_KEY);
|
||||
if (typeof envelope === 'string') {
|
||||
if (pyLen(envelope) > MAX_EXECUTION_JSON) throw evidence('Execution evidence exceeds the size limit');
|
||||
try { envelope = pyJsonLoads(envelope); } catch (error) {
|
||||
if (error instanceof PyValueError) throw evidence('Malformed execution evidence JSON');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
if (!isDict(envelope) || !pyEqualsOne(pyGet(envelope, 'version'))) throw evidence('Unsupported execution evidence format');
|
||||
const nodes = pyGet(envelope, 'nodes');
|
||||
if (pyTruthy(pyGet(envelope, 'truncated')) || !isDict(nodes) || nodes.size > MAX_EXECUTION_NODES) throw evidence('Truncated or malformed execution evidence');
|
||||
if (!nodes.has(nodeId)) return null;
|
||||
const node = nodes.get(nodeId);
|
||||
if (!isDict(node) || pyTruthy(pyGet(node, 'truncated'))) throw evidence('Truncated or malformed node execution evidence');
|
||||
const records = pyGet(node, 'records');
|
||||
if (!isList(records) || !records.length || records.length > MAX_EXECUTION_RECORDS) throw evidence('Malformed node execution records');
|
||||
const unique = new Map();
|
||||
for (const record of records) {
|
||||
if (!isDict(record) || EXECUTION_FIELDS.some(key => typeof pyGet(record, key) !== 'string' || pyLen(record.get(key)) > MAX_EXECUTION_TEXT)) {
|
||||
throw evidence('Malformed execution text values');
|
||||
}
|
||||
const clean = Object.fromEntries(EXECUTION_FIELDS.map(key => [key, record.get(key)]));
|
||||
if (clean.negative_effective_text !== clean.negative_text) throw evidence('Negative execution text must be unchanged');
|
||||
unique.set(JSON.stringify(EXECUTION_FIELDS.map(key => clean[key])), clean);
|
||||
}
|
||||
if (unique.size !== 1) throw evidence('Multiple distinct executions have no image anchor');
|
||||
return [...unique.values()][0];
|
||||
}
|
||||
|
||||
/**
|
||||
* The validated semantics table (utils/inspection_semantics.py), from the parsed JSON document. Throws
|
||||
* `SemanticsError` for any shape the server rejects; the caller then answers "semantics unavailable".
|
||||
*/
|
||||
export function compileSemantics(doc) {
|
||||
const fail = message => { throw new SemanticsError(message); };
|
||||
const plain = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
if (!plain(doc) || doc.schema !== 1) fail('unsupported semantics table');
|
||||
const owners = new Map();
|
||||
const claim = (name, category) => {
|
||||
if (owners.has(name) && owners.get(name) !== category) fail(`duplicate class ${name}`);
|
||||
owners.set(name, category);
|
||||
};
|
||||
const byClass = category => {
|
||||
if (!plain(doc[category])) fail(`category ${category} must be an object`);
|
||||
const table = new Map();
|
||||
for (const [name, entry] of Object.entries(doc[category])) {
|
||||
if (!plain(entry) || typeof entry.strategy !== 'string') fail(`${category}[${name}]`);
|
||||
claim(name, category);
|
||||
table.set(name, entry);
|
||||
}
|
||||
return table;
|
||||
};
|
||||
const bySlot = category => {
|
||||
if (!Array.isArray(doc[category])) fail(`category ${category} must be a list`);
|
||||
const table = new Map();
|
||||
for (const row of doc[category]) {
|
||||
if (!plain(row) || typeof row.class !== 'string' || !Number.isInteger(row.slot) || row.slot < 0 || row.slot > 255) fail(`${category} row`);
|
||||
const key = slotKey(row.class, row.slot);
|
||||
if (table.has(key)) fail(`${category}: duplicate output key`);
|
||||
claim(row.class, category);
|
||||
const { class: _name, slot: _slot, ...entry } = row;
|
||||
table.set(key, entry);
|
||||
}
|
||||
return table;
|
||||
};
|
||||
const bySet = category => {
|
||||
if (!Array.isArray(doc[category])) fail(`category ${category} must be a list`);
|
||||
const set = new Set();
|
||||
for (const name of doc[category]) {
|
||||
if (typeof name !== 'string' || set.has(name)) fail(`${category}: duplicate class`);
|
||||
claim(name, category);
|
||||
set.add(name);
|
||||
}
|
||||
return set;
|
||||
};
|
||||
const samplers = byClass('samplers'), guiders = byClass('guiders'), selectors = byClass('selectors');
|
||||
const composites = byClass('composites'), savers = byClass('savers');
|
||||
const conditioning = bySlot('conditioning'), encoders = bySlot('encoders'), strings = bySlot('strings');
|
||||
const runtime = bySet('runtime'), nonFileOutputs = bySet('non_file_outputs');
|
||||
const stageInputs = doc.stage_inputs;
|
||||
if (!plain(stageInputs) || !Array.isArray(stageInputs.shaped) || !Array.isArray(stageInputs.with_model)) fail('stage_inputs');
|
||||
return Object.freeze({
|
||||
samplers, guiders, selectors, composites, savers, conditioning, encoders, strings, runtime, nonFileOutputs,
|
||||
stageInputs: { shaped: [...stageInputs.shaped], withModel: [...stageInputs.with_model] }, allClasses: new Set(owners.keys()),
|
||||
});
|
||||
}
|
||||
|
||||
/** `outcome_message`: one line for an unresolved outcome, or null to keep the status copy. */
|
||||
export function outcomeMessage(resolution) {
|
||||
if (resolution?.state !== 'unresolved') return null;
|
||||
const code = typeof resolution.reason_code === 'string' ? resolution.reason_code : null;
|
||||
if (Object.hasOwn(NAMED_LINES, code)) {
|
||||
const node = resolution.node, raw = node !== null && typeof node === 'object' ? node.class_type : null;
|
||||
const name = typeof raw === 'string' && raw ? pySlice(raw, OUTCOME_NAME_LENGTH) : null;
|
||||
return name ? `${NAMED_LINES[code]} (${name}).` : `${NAMED_LINES[code]}.`;
|
||||
}
|
||||
if (code === null) return Object.hasOwn(UNCODED_LINES, resolution.reason) ? UNCODED_LINES[resolution.reason] : null;
|
||||
return Object.hasOwn(CODED_LINES, code) ? CODED_LINES[code] : null;
|
||||
}
|
||||
|
||||
export const sideOf = (status, text = null, source = null) => ({ status, text, source });
|
||||
export function explained(prompts, resolution) {
|
||||
const message = outcomeMessage(resolution);
|
||||
if (message === null) return prompts;
|
||||
return Object.fromEntries(Object.entries(prompts).map(([role, side]) => [role, side.status === 'unresolved' && !Object.hasOwn(side, 'message') ? { ...side, message } : side]));
|
||||
}
|
||||
export const EMPTY_POSITIVE = outcomeMessage({ state: 'unresolved', reason: EMPTY_POSITIVE_REASON });
|
||||
@@ -0,0 +1,772 @@
|
||||
// The server's inspection resolver in this browser (#249 local Inspect, PR L3 Task 8, decision LI-1): a port of
|
||||
// utils/prompt_inspector.py `inspect_prompt_evidence` with utils/prompt_pair_resolver.py (INSPECTION_PROFILE) and
|
||||
// utils/pair_execution.py `read_pair_execution`, driven by web/js/inspection-semantics.json. Python is the oracle:
|
||||
// tests/test_local_inspect_parity.py compares every answer with the server's on the same records. Values follow
|
||||
// Python's model (py-json.mjs): dict order, int versus float, code-point lengths, `str.strip()`.
|
||||
//
|
||||
// Task 8 ported execution evidence and graph tracing for one sampler; Task 9 adds candidate selection among several
|
||||
// samplers and detailer stages (local-resolver-stages.mjs) and A1111 `parameters` (local-parameters.mjs). No DOM.
|
||||
import { PyValueError, isDict, isList, isInt, pyJsonLoads, pyLen, pySlice, pyStrip, pyStr, pyGet } from './py-json.mjs';
|
||||
import {
|
||||
ADAPTERS,
|
||||
ADAPTER_SLOTS,
|
||||
Budget,
|
||||
CANDIDATE_STRATEGIES,
|
||||
CLASS_NAME_LENGTH,
|
||||
Diverging,
|
||||
EMPTY_POSITIVE,
|
||||
EMPTY_POSITIVE_REASON,
|
||||
GUIDER_ABSENT_REASON,
|
||||
INCOMPATIBLE_SLOT,
|
||||
MALFORMED_EVIDENCE_REASON,
|
||||
MAX_BRANCH_CANDIDATES,
|
||||
MAX_JOIN_INPUTS,
|
||||
MAX_SUBGRAPH_DEPTH,
|
||||
MAX_WORKFLOW_NODES,
|
||||
MULTISTAGE_UNATTRIBUTED_REASON,
|
||||
NO_SAMPLER_NAMES,
|
||||
OVERWRITTEN_PROMPT_REASON,
|
||||
PROFILE,
|
||||
ROLE_METADATA_KEYS,
|
||||
RUNTIME_REASON,
|
||||
SAMPLER_LIKE_INPUTS,
|
||||
SEMANTICS_UNAVAILABLE_REASON,
|
||||
UNREADABLE_METADATA_REASON,
|
||||
UNVERIFIABLE_CODES,
|
||||
Unresolved,
|
||||
ZEROED_SOURCE,
|
||||
compileSemantics,
|
||||
explained,
|
||||
isLink,
|
||||
nodeRef,
|
||||
readPairExecution,
|
||||
result,
|
||||
sideOf,
|
||||
slotKey,
|
||||
} from './local-resolver-support.mjs';
|
||||
import { finalStages, outcomeKey, sharedPair, stage } from './local-resolver-stages.mjs';
|
||||
import { parameters } from './local-parameters.mjs';
|
||||
|
||||
export { SemanticsError, compileSemantics, readPairExecution, outcomeMessage, isLink } from './local-resolver-support.mjs';
|
||||
|
||||
class GraphResolver {
|
||||
constructor(graph, metadata, semantics, overwritten) {
|
||||
this.graph = graph;
|
||||
this.overwritten = overwritten;
|
||||
this.perCandidateVisits = PROFILE.perCandidateVisits;
|
||||
this.budget = new Budget(PROFILE.totalVisits);
|
||||
this.budget.reset(PROFILE.perCandidateVisits);
|
||||
this.pathEntries = PROFILE.maxPathEntries;
|
||||
this.builtChars = PROFILE.maxBuiltChars;
|
||||
this.scanned = PROFILE.maxScannedUnits;
|
||||
this.checked = new Map();
|
||||
this.costs = new Map();
|
||||
this.heights = new Map();
|
||||
this.deepest = 0;
|
||||
this.maxDepth = PROFILE.maxDepth;
|
||||
this.maxTextLength = PROFILE.maxTextLength;
|
||||
this.memo = new Map();
|
||||
this.active = new Set();
|
||||
this.metadata = metadata ?? new Map();
|
||||
this.textSources = new Map();
|
||||
this.choices = new Map();
|
||||
this.tainted = false;
|
||||
this.latentWalks = new Map();
|
||||
this.latentCharged = new Set();
|
||||
this.semantics = semantics;
|
||||
this.samplerClasses = new Set([...semantics.samplers].filter(([, entry]) => CANDIDATE_STRATEGIES.has(entry.strategy)).map(([name]) => name));
|
||||
this.stageClasses = new Set(semantics.samplers.keys());
|
||||
}
|
||||
|
||||
node(nodeId) {
|
||||
if (!this.checked.has(nodeId)) {
|
||||
try {
|
||||
this.checked.set(nodeId, this.checkedNode(nodeId));
|
||||
} catch (error) {
|
||||
if (!(error instanceof Unresolved) || error.code === 'work-limit') throw error;
|
||||
this.checked.set(nodeId, error);
|
||||
}
|
||||
}
|
||||
const checked = this.checked.get(nodeId);
|
||||
if (checked instanceof Unresolved) throw new Unresolved(checked.message, checked.code, checked.node);
|
||||
return checked;
|
||||
}
|
||||
checkedNode(nodeId) {
|
||||
const node = pyGet(this.graph, nodeId);
|
||||
if (!isDict(node) || !isDict(pyGet(node, 'inputs'))) throw new Unresolved('Missing or malformed graph node', 'malformed');
|
||||
const inputs = node.get('inputs');
|
||||
this.scan(inputs.size);
|
||||
return [pyStr(pyGet(node, 'class_type', '')), inputs];
|
||||
}
|
||||
scan(units) {
|
||||
if (units > this.scanned) {
|
||||
this.scanned = -1;
|
||||
throw new Unresolved('Resolution work limit reached', 'work-limit');
|
||||
}
|
||||
this.scanned -= units;
|
||||
}
|
||||
unsupported(message, nodeId) { return this.named(message, 'unsupported-node', nodeId); }
|
||||
named(message, code, nodeId) {
|
||||
const node = pyGet(this.graph, nodeId);
|
||||
const classType = isDict(node) ? pyGet(node, 'class_type') : null;
|
||||
return new Unresolved(message, code, nodeRef(nodeId, classType));
|
||||
}
|
||||
bounded(text) {
|
||||
if (pyLen(text) > this.maxTextLength) throw new Unresolved('Resolved text exceeds the length limit', 'text-limit');
|
||||
return text;
|
||||
}
|
||||
built(text) {
|
||||
this.builtChars -= pyLen(text);
|
||||
if (this.builtChars < 0) throw new Unresolved('Resolution work limit reached', 'work-limit');
|
||||
return text;
|
||||
}
|
||||
|
||||
/** `text`: [text, path, storageText] for a string value or a typed link. */
|
||||
text(value, kind, depth = 0) {
|
||||
this.deepest = Math.max(this.deepest, depth);
|
||||
if (depth >= this.maxDepth) throw new Unresolved('Resolution depth limit reached', 'depth-limit');
|
||||
if (typeof value === 'string' && kind === 'string') return [this.bounded(value), [], value];
|
||||
if (!isLink(value)) throw new Unresolved('Expected a typed graph link or text input', 'malformed');
|
||||
const nodeId = String(value[0]), slot = value[1];
|
||||
const key = `${slotKey(nodeId, slot)}\u0000${kind}`;
|
||||
if (this.active.has(key)) throw new Unresolved('Cyclic prompt graph', 'malformed');
|
||||
if (this.memo.has(key)) {
|
||||
const height = this.heights.get(key);
|
||||
if (depth + height >= this.maxDepth) throw new Unresolved('Resolution depth limit reached', 'depth-limit');
|
||||
this.budget.charge(this.costs.get(key));
|
||||
this.deepest = Math.max(this.deepest, depth + height);
|
||||
return this.memo.get(key);
|
||||
}
|
||||
const allowance = this.budget.allowance, outerDeepest = this.deepest, outerTainted = this.tainted;
|
||||
this.tainted = false;
|
||||
this.deepest = depth;
|
||||
try {
|
||||
this.budget.spend();
|
||||
const [name, inputs] = this.node(nodeId);
|
||||
this.scan(inputs.size);
|
||||
if (this.overwritten.has(nodeId)) throw new Unresolved(OVERWRITTEN_PROMPT_REASON, 'malformed');
|
||||
this.active.add(key);
|
||||
let text, path, storageText;
|
||||
const adapted = ADAPTERS.get(slotKey(name, slot));
|
||||
if (name === 'Reroute' && slot === 0) {
|
||||
const keys = ['value', 'input', 'in'].filter(item => inputs.has(item));
|
||||
if (keys.length !== 1) throw new Unresolved('Reroute input is not uniquely identifiable', 'malformed');
|
||||
[text, path, storageText] = this.text(inputs.get(keys[0]), kind, depth + 1);
|
||||
this.inheritSource(nodeId, slot, [path]);
|
||||
} else if (adapted) {
|
||||
if (adapted.kind !== kind) throw new Unresolved(INCOMPATIBLE_SLOT, 'malformed');
|
||||
const evidence = name === 'PromptManagerPair' ? this.executionRecord(nodeId, inputs) : null;
|
||||
if (evidence !== null) {
|
||||
text = evidence[adapted.inputName === 'text' ? 'positive_text' : 'negative_effective_text'];
|
||||
storageText = evidence[adapted.inputName];
|
||||
path = [];
|
||||
this.textSources.set(slotKey(nodeId, slot), 'execution');
|
||||
} else if (adapted.comma || adapted.strip) {
|
||||
[text, path, storageText] = this.historical(adapted, inputs, depth);
|
||||
} else {
|
||||
[text, path, storageText] = this.text(pyGet(inputs, adapted.inputName), 'string', depth + 1);
|
||||
if (adapted.compose || adapted.storageInput) storageText = text;
|
||||
if (adapted.compose) {
|
||||
const [before, beforePath] = this.text(pyGet(inputs, 'prepend_text', ''), 'string', depth + 1);
|
||||
const [after, afterPath] = this.text(pyGet(inputs, 'append_text', ''), 'string', depth + 1);
|
||||
this.scan(pyLen(before) + pyLen(after) + beforePath.length + path.length + afterPath.length);
|
||||
text = this.built(this.bounded([pyStrip(before), text, pyStrip(after)].filter(part => part).join(' ')));
|
||||
path = [...beforePath, ...path, ...afterPath];
|
||||
}
|
||||
}
|
||||
} else if ((name === 'StringConcatenate' || name === 'Text Concatenate') && slot === 0 && kind === 'string') {
|
||||
[text, path] = this.concatenate(name, inputs, depth);
|
||||
storageText = text;
|
||||
} else if (this.follows(name, slot, kind)) {
|
||||
[text, path, storageText] = this.semantic(nodeId, name, slot, kind, inputs, depth);
|
||||
} else {
|
||||
throw this.unsupported('Unsupported node semantics or output slot', nodeId);
|
||||
}
|
||||
this.scan(path.length + 1);
|
||||
path = [{ node_id: nodeId, output_slot: slot }, ...path];
|
||||
const pathLimit = this.maxDepth * Math.max(1, this.perCandidateVisits);
|
||||
this.pathEntries -= path.length;
|
||||
if (path.length > pathLimit || this.pathEntries < 0) throw new Unresolved('Provenance path limit reached', 'work-limit');
|
||||
const traced = [text, path, storageText];
|
||||
if (!this.tainted) {
|
||||
this.memo.set(key, traced);
|
||||
this.costs.set(key, allowance - this.budget.allowance);
|
||||
this.heights.set(key, this.deepest - depth);
|
||||
}
|
||||
return traced;
|
||||
} finally {
|
||||
this.deepest = Math.max(outerDeepest, this.deepest);
|
||||
this.tainted = outerTainted || this.tainted;
|
||||
this.active.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
/** `StringConcatenate` / `Text Concatenate` (the `text` branch). */
|
||||
concatenate(name, inputs, depth) {
|
||||
let keys, delimiter, clean;
|
||||
if (name === 'StringConcatenate') {
|
||||
keys = ['string_a', 'string_b'];
|
||||
delimiter = pyGet(inputs, 'delimiter', '');
|
||||
clean = false;
|
||||
} else {
|
||||
keys = [...inputs.keys()].filter(item => /^text_[a-z]$/.test(item)).sort();
|
||||
delimiter = pyGet(inputs, 'delimiter', ' ');
|
||||
clean = pyStr(pyGet(inputs, 'clean_whitespace', 'true')).toLowerCase() === 'true';
|
||||
}
|
||||
if (!keys.length || typeof delimiter !== 'string') throw new Unresolved('Malformed concatenation', 'malformed');
|
||||
const parts = [], path = [];
|
||||
let size = 0;
|
||||
for (const inputName of keys) {
|
||||
let [part, followed] = this.text(pyGet(inputs, inputName, ''), 'string', depth + 1);
|
||||
this.scan(pyLen(part) + followed.length);
|
||||
if (clean) part = pyStrip(part);
|
||||
path.push(...followed);
|
||||
if (part || name === 'StringConcatenate') {
|
||||
size += pyLen(part) + (parts.length ? pyLen(delimiter) : 0);
|
||||
if (size > this.maxTextLength) throw new Unresolved('Resolved text exceeds the length limit', 'text-limit');
|
||||
parts.push(part);
|
||||
}
|
||||
}
|
||||
return [this.built(parts.join(delimiter)), path];
|
||||
}
|
||||
|
||||
/** `prompt_manager_*.py` at 07a5af3: strip, then join with ", ". */
|
||||
historical(adapted, inputs, depth) {
|
||||
let [text, path] = this.text(pyGet(inputs, adapted.inputName, adapted.default), 'string', depth + 1);
|
||||
this.scan(pyLen(text));
|
||||
text = pyStrip(text);
|
||||
const storageText = text;
|
||||
if (adapted.comma) {
|
||||
let [before, beforePath] = this.text(pyGet(inputs, 'prepend_text') ?? '', 'string', depth + 1);
|
||||
let [after, afterPath] = this.text(pyGet(inputs, 'append_text') ?? '', 'string', depth + 1);
|
||||
this.scan(pyLen(before) + pyLen(after) + beforePath.length + afterPath.length);
|
||||
before = pyStrip(before); after = pyStrip(after);
|
||||
if (before) text = `${before}${text && !before.endsWith(',') ? ', ' : ''}${text}`;
|
||||
if (after) text = `${text}${text && !text.endsWith(',') ? ', ' : ''}${after}`;
|
||||
text = this.built(this.bounded(text));
|
||||
path = [...beforePath, ...path, ...afterPath];
|
||||
}
|
||||
return [text, path, storageText];
|
||||
}
|
||||
|
||||
follows(name, slot, kind) {
|
||||
const semantics = this.semantics, key = slotKey(name, slot);
|
||||
if (semantics.runtime.has(name)) return true;
|
||||
if (semantics.encoders.has(key) || semantics.strings.has(key)) return true;
|
||||
if (slot === 0 && semantics.selectors.has(name)) return true;
|
||||
return kind === 'conditioning' && (semantics.conditioning.has(key) || (slot === 0 && semantics.composites.has(name)));
|
||||
}
|
||||
|
||||
semantic(nodeId, name, slot, kind, inputs, depth) {
|
||||
const semantics = this.semantics, key = slotKey(name, slot);
|
||||
if (semantics.runtime.has(name)) throw this.named(RUNTIME_REASON, 'runtime-value', nodeId);
|
||||
for (const [table, expected, build] of [[semantics.encoders, 'conditioning', 'encoded'], [semantics.strings, 'string', 'stringed']]) {
|
||||
const listed = table.get(key);
|
||||
if (listed !== undefined) {
|
||||
if (kind !== expected) throw new Unresolved(INCOMPATIBLE_SLOT, 'malformed');
|
||||
return this[build](nodeId, listed, inputs, depth);
|
||||
}
|
||||
}
|
||||
const entry = kind === 'conditioning' ? semantics.conditioning.get(key) : undefined;
|
||||
if (entry !== undefined && entry.strategy === 'zeroed') {
|
||||
this.textSources.set(slotKey(nodeId, slot), ZEROED_SOURCE);
|
||||
return ['', [], ''];
|
||||
}
|
||||
if (entry !== undefined) {
|
||||
const traced = this.text(pyGet(inputs, entry.input), kind, depth + 1);
|
||||
this.inheritSource(nodeId, slot, [traced[1]]);
|
||||
return traced;
|
||||
}
|
||||
if (semantics.selectors.has(name)) return this.select(nodeId, semantics.selectors.get(name), inputs, kind, depth);
|
||||
const parts = semantics.composites.get(name).inputs.map(inputName => this.text(pyGet(inputs, inputName), kind, depth + 1));
|
||||
if (new Set(parts.map(part => part[0])).size !== 1) throw this.named('Combined conditioning has different texts', 'composite', nodeId);
|
||||
return this.merged(nodeId, slot, parts);
|
||||
}
|
||||
|
||||
select(nodeId, entry, inputs, kind, depth) {
|
||||
const condition = pyGet(inputs, entry.condition), branches = entry.branches;
|
||||
let choice;
|
||||
if (typeof condition === 'boolean') choice = condition;
|
||||
else if (!isLink(condition)) throw new Unresolved('Malformed selector condition', 'malformed');
|
||||
else if (this.choices.has(slotKey(String(condition[0]), condition[1]))) {
|
||||
choice = this.choices.get(slotKey(String(condition[0]), condition[1]));
|
||||
this.tainted = true;
|
||||
} else choice = null;
|
||||
if (choice !== null) {
|
||||
const traced = this.text(pyGet(inputs, branches[choice ? 'true' : 'false']), kind, depth + 1);
|
||||
this.inheritSource(nodeId, 0, [traced[1]]);
|
||||
return traced;
|
||||
}
|
||||
const parts = ['true', 'false'].map(label => this.text(pyGet(inputs, branches[label]), kind, depth + 1));
|
||||
if (parts[0][0] !== parts[1][0]) throw new Diverging(slotKey(String(condition[0]), condition[1]));
|
||||
return this.merged(nodeId, 0, parts);
|
||||
}
|
||||
|
||||
merged(nodeId, slot, parts) {
|
||||
const traced = this.joinedPaths(parts, parts);
|
||||
this.inheritSource(nodeId, slot, parts.map(part => part[1]));
|
||||
return traced;
|
||||
}
|
||||
|
||||
joinedPaths(chosen, parts) {
|
||||
const text = chosen[0][0];
|
||||
const storages = new Set(chosen.map(part => part[2]));
|
||||
const storageText = storages.size === 1 ? chosen[0][2] : text;
|
||||
const paths = parts.map(part => part[1]);
|
||||
this.scan(paths.reduce((sum, path) => sum + path.length, 0));
|
||||
const merged = [], seen = new Set();
|
||||
for (const path of paths) {
|
||||
for (const step of path) {
|
||||
const identity = slotKey(step.node_id, step.output_slot);
|
||||
if (!seen.has(identity)) { seen.add(identity); merged.push(step); }
|
||||
}
|
||||
}
|
||||
return [text, merged, storageText];
|
||||
}
|
||||
|
||||
encoded(nodeId, entry, inputs, depth) {
|
||||
const names = entry.inputs;
|
||||
if (entry.strategy === 'single') return this.text(pyGet(inputs, names[0]), 'string', depth + 1);
|
||||
if (entry.strategy === 'flag-parts') return this.flagged(nodeId, entry, inputs, depth);
|
||||
if (entry.strategy !== 'parts-equal') throw this.unsupported('Unsupported encoder strategy', nodeId);
|
||||
const parts = names.map(name => this.text(pyGet(inputs, name), 'string', depth + 1));
|
||||
this.scan(parts.reduce((sum, part) => sum + pyLen(part[0]), 0));
|
||||
if (new Set(parts.map(part => part[0])).size === 1) return this.joinedPaths(parts, parts);
|
||||
const filled = parts.filter(part => part[0] !== '');
|
||||
if (filled.length === 1) return this.joinedPaths(filled, parts);
|
||||
throw this.named('Encoder parts have different texts', 'composite', nodeId);
|
||||
}
|
||||
|
||||
flagged(nodeId, entry, inputs, depth) {
|
||||
const names = entry.inputs;
|
||||
if (!this.setting(nodeId, inputs, entry.params.flag, 'bool')) return this.text(pyGet(inputs, names[0]), 'string', depth + 1);
|
||||
const parts = names.map(name => this.text(pyGet(inputs, name), 'string', depth + 1));
|
||||
this.scan(parts.reduce((sum, part) => sum + pyLen(part[0]), 0));
|
||||
if (new Set(parts.map(part => part[0])).size === 1) return this.joinedPaths(parts, parts);
|
||||
throw this.named(RUNTIME_REASON, 'runtime-value', nodeId);
|
||||
}
|
||||
|
||||
stringed(nodeId, entry, inputs, depth) {
|
||||
const strategy = entry.strategy, source = entry.inputs[0];
|
||||
if (strategy === 'literal') return this.text(pyGet(inputs, source), 'string', depth + 1);
|
||||
if (strategy === 'strip-newlines') {
|
||||
const flag = this.setting(nodeId, inputs, entry.params.flag, 'bool');
|
||||
const traced = this.text(pyGet(inputs, source), 'string', depth + 1);
|
||||
if (!flag) return traced;
|
||||
this.scan(pyLen(traced[0]));
|
||||
const text = this.built(this.bounded(pyStrip(traced[0].replaceAll('\n', ''))));
|
||||
return [text, traced[1], text];
|
||||
}
|
||||
if (strategy === 'join-multi') return this.joinMulti(nodeId, entry, inputs, depth);
|
||||
throw this.unsupported('Unsupported string strategy', nodeId);
|
||||
}
|
||||
|
||||
/** A literal node setting of exactly `type(value) is kind`; linked is `unsupported-node`, else malformed. */
|
||||
setting(nodeId, inputs, name, kind) {
|
||||
if (!inputs.has(name)) throw new Unresolved('Missing string node setting', 'malformed');
|
||||
const value = inputs.get(name);
|
||||
if (isLink(value)) throw this.unsupported('Linked string node setting', nodeId);
|
||||
const typed = { bool: typeof value === 'boolean', int: isInt(value), str: typeof value === 'string' }[kind];
|
||||
if (!typed) throw new Unresolved('Malformed string node setting', 'malformed');
|
||||
return value;
|
||||
}
|
||||
|
||||
joinMulti(nodeId, entry, inputs, depth) {
|
||||
const params = entry.params, flag = params.list_flag;
|
||||
if (!inputs.has(flag)) throw new Unresolved('Missing string node setting', 'malformed');
|
||||
if (isLink(inputs.get(flag)) || inputs.get(flag) === true) throw this.named(RUNTIME_REASON, 'runtime-value', nodeId);
|
||||
if (inputs.get(flag) !== false) throw new Unresolved('Malformed string node setting', 'malformed');
|
||||
const count = this.setting(nodeId, inputs, params.count, 'int');
|
||||
const delimiter = this.setting(nodeId, inputs, params.delimiter, 'str');
|
||||
if (!(count >= 1 && count <= MAX_JOIN_INPUTS)) throw new Unresolved('Malformed string node setting', 'malformed');
|
||||
const total = Number(count);
|
||||
this.scan(total);
|
||||
const names = [entry.inputs[0]];
|
||||
for (let index = 2; index <= total; index++) names.push(`${params.input_prefix}${index}`);
|
||||
const parts = [], path = [], seen = new Set();
|
||||
let size = 0;
|
||||
names.forEach((inputName, position) => {
|
||||
if (position && !inputs.has(inputName)) return;
|
||||
const [part, followed] = this.text(pyGet(inputs, inputName), 'string', depth + 1);
|
||||
this.scan(pyLen(part) + followed.length);
|
||||
for (const step of followed) {
|
||||
const identity = slotKey(step.node_id, step.output_slot);
|
||||
if (!seen.has(identity)) { seen.add(identity); path.push(step); }
|
||||
}
|
||||
if (position && !part) return;
|
||||
size += pyLen(part) + (parts.length ? pyLen(delimiter) : 0);
|
||||
if (size > this.maxTextLength) throw new Unresolved('Resolved text exceeds the length limit', 'text-limit');
|
||||
parts.push(part);
|
||||
});
|
||||
const text = this.built(parts.join(delimiter));
|
||||
return [text, path, text];
|
||||
}
|
||||
|
||||
sourceOf(path) {
|
||||
if (!path.length) return 'graph-inferred';
|
||||
return this.textSources.get(slotKey(path[0].node_id, path[0].output_slot)) ?? 'graph-inferred';
|
||||
}
|
||||
inheritSource(nodeId, slot, paths) {
|
||||
const sources = new Set(paths.map(path => this.sourceOf(path)));
|
||||
if (sources.size === 1) this.textSources.set(slotKey(nodeId, slot), [...sources][0]);
|
||||
else this.textSources.delete(slotKey(nodeId, slot));
|
||||
}
|
||||
unverifiable(error) { return UNVERIFIABLE_CODES.has(error.code); }
|
||||
|
||||
executionRecord(nodeId, inputs) {
|
||||
const record = readPairExecution(this.metadata, nodeId);
|
||||
if (record === null) return null;
|
||||
for (const name of ['text', 'negative_text', 'prepend_text', 'append_text']) {
|
||||
let expected;
|
||||
try {
|
||||
expected = this.text(pyGet(inputs, name, ''), 'string')[0];
|
||||
} catch (error) {
|
||||
if (error instanceof Unresolved && this.unverifiable(error)) {
|
||||
const value = pyGet(inputs, name);
|
||||
if (isLink(value)) {
|
||||
const [sourceName] = this.node(String(value[0]));
|
||||
const known = ADAPTER_SLOTS.get(sourceName);
|
||||
if (known && !known.has(String(value[1]))) throw error;
|
||||
if (['StringConcatenate', 'Text Concatenate', 'Reroute'].includes(sourceName) && value[1] !== 0) throw error;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (name === 'prepend_text' || name === 'append_text') expected = pyStrip(expected);
|
||||
if (expected !== record[name]) throw new Unresolved('Execution evidence does not match recorded node inputs', 'malformed');
|
||||
}
|
||||
return record;
|
||||
}
|
||||
|
||||
side(value, samplerId, guiderId = null, depth = 0) {
|
||||
const [text, path, storageText] = this.text(value, 'conditioning', depth);
|
||||
const origin = path[0];
|
||||
const provenance = {
|
||||
format: 'comfyui', sampler_id: samplerId, ...origin, path,
|
||||
text_source: this.textSources.get(slotKey(origin.node_id, origin.output_slot)) ?? 'graph-inferred',
|
||||
};
|
||||
if (guiderId !== null) provenance.guider_id = guiderId;
|
||||
return { text, storage_text: storageText, provenance };
|
||||
}
|
||||
|
||||
guider(value) {
|
||||
const seen = new Set();
|
||||
let depth = 0;
|
||||
for (;;) {
|
||||
if (depth >= this.maxDepth) throw new Unresolved('Resolution depth limit reached', 'depth-limit');
|
||||
if (!isLink(value)) throw new Unresolved('Expected a guider link', 'malformed');
|
||||
const nodeId = String(value[0]), slot = value[1];
|
||||
if (seen.has(nodeId)) throw new Unresolved('Cyclic guider ancestry', 'malformed');
|
||||
seen.add(nodeId);
|
||||
this.budget.spend();
|
||||
const [name, inputs] = this.node(nodeId);
|
||||
this.scan(inputs.size);
|
||||
depth += 1;
|
||||
if (name === 'Reroute' && slot === 0) {
|
||||
const keys = ['value', 'input', 'in'].filter(item => inputs.has(item));
|
||||
if (keys.length !== 1) throw new Unresolved('Reroute input is not uniquely identifiable', 'malformed');
|
||||
value = inputs.get(keys[0]);
|
||||
continue;
|
||||
}
|
||||
const entry = this.semantics.guiders.get(name);
|
||||
if (entry === undefined || slot !== 0) throw this.unsupported('Unsupported guider', nodeId);
|
||||
return [nodeId, inputs, { positive: entry.positive, negative: entry.negative ?? null }, entry.absent_reason ?? GUIDER_ABSENT_REASON, depth];
|
||||
}
|
||||
}
|
||||
|
||||
pair(samplerId) {
|
||||
this.budget.reset(this.perCandidateVisits);
|
||||
this.latentCharged = new Set();
|
||||
if (this.budget.total <= 0) return result('unresolved', { samplerId, reason: 'Resolution visit limit reached', reasonCode: 'work-limit' });
|
||||
return this.branches(samplerId);
|
||||
}
|
||||
|
||||
branches(samplerId) {
|
||||
const pending = [new Map()], results = [];
|
||||
try {
|
||||
while (pending.length) {
|
||||
this.choices = pending.shift();
|
||||
try {
|
||||
results.push(stage(this, samplerId, new Set()));
|
||||
} catch (error) {
|
||||
if (!(error instanceof Diverging)) throw error;
|
||||
if (results.length + pending.length + 2 > MAX_BRANCH_CANDIDATES) throw new Unresolved('Too many selector branches', 'work-limit');
|
||||
for (const choice of [true, false]) pending.push(new Map([...this.choices, [error.key, choice]]));
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (!(error instanceof Unresolved)) throw error;
|
||||
return result('unresolved', { samplerId, reason: error.message, reasonCode: error.code, node: error.node });
|
||||
} finally {
|
||||
this.choices = new Map();
|
||||
}
|
||||
if (results.every(item => item.state === 'unresolved')) return results[0];
|
||||
if (new Set(results.map(outcomeKey)).size === 1) return results[0];
|
||||
return result('ambiguous', { samplerId, reason: 'Selector branches have different prompts', candidates: results });
|
||||
}
|
||||
|
||||
sides(samplerId) {
|
||||
let positive = null, negative = null;
|
||||
try {
|
||||
let [name, inputs] = this.node(samplerId);
|
||||
const entry = this.semantics.samplers.get(name);
|
||||
this.checkOverrides(samplerId, entry, inputs);
|
||||
const latent = entry.latent;
|
||||
if (latent !== undefined && latent !== null && inputs.has(latent)) this.latentChecked(samplerId, inputs.get(latent));
|
||||
let guiderId = null, depth = 0, conditioning = entry.conditioning, absentReason = 'Negative input is absent';
|
||||
if (entry.strategy === 'custom-advanced') {
|
||||
let guiderReason;
|
||||
[guiderId, inputs, conditioning, guiderReason, depth] = this.guider(pyGet(inputs, conditioning.guider));
|
||||
if (conditioning.negative === null) absentReason = guiderReason;
|
||||
}
|
||||
positive = this.side(pyGet(inputs, conditioning.positive), samplerId, guiderId, depth);
|
||||
if (!pyStrip(positive.text)) throw new Unresolved(EMPTY_POSITIVE_REASON);
|
||||
const negativeName = conditioning.negative;
|
||||
if (negativeName === null || negativeName === undefined || !inputs.has(negativeName)) {
|
||||
return result('absent', { positive, samplerId, reason: absentReason });
|
||||
}
|
||||
negative = this.side(inputs.get(negativeName), samplerId, guiderId, depth);
|
||||
return result('resolved', { positive, negative, samplerId });
|
||||
} catch (error) {
|
||||
if (!(error instanceof Unresolved)) throw error;
|
||||
return result('unresolved', { positive, negative, samplerId, reason: error.message, reasonCode: error.code, node: error.node });
|
||||
}
|
||||
}
|
||||
|
||||
checkOverrides(samplerId, entry, inputs) {
|
||||
for (const name of entry.prompt_overrides ?? []) {
|
||||
const value = pyGet(inputs, name);
|
||||
if (value === null || value === '') continue;
|
||||
if (isLink(value)) throw this.unsupported('Unsupported prompt override', String(value[0]));
|
||||
throw this.named(RUNTIME_REASON, 'runtime-value', samplerId);
|
||||
}
|
||||
}
|
||||
|
||||
latentChecked(samplerId, value) {
|
||||
let error;
|
||||
if (this.latentWalks.has(samplerId)) {
|
||||
const [walked, cost] = this.latentWalks.get(samplerId);
|
||||
error = walked;
|
||||
if (!this.latentCharged.has(samplerId)) {
|
||||
this.budget.charge(cost);
|
||||
this.latentCharged.add(samplerId);
|
||||
}
|
||||
} else {
|
||||
const before = this.budget.allowance;
|
||||
try {
|
||||
this.latentStages(samplerId, value);
|
||||
error = null;
|
||||
} catch (raised) {
|
||||
if (!(raised instanceof Unresolved) || raised.code === 'work-limit') throw raised;
|
||||
error = raised;
|
||||
}
|
||||
this.latentWalks.set(samplerId, [error, before - this.budget.allowance]);
|
||||
this.latentCharged.add(samplerId);
|
||||
}
|
||||
if (error !== null) throw new Unresolved(error.message, error.code, error.node === null ? null : { ...error.node });
|
||||
}
|
||||
|
||||
enqueue(queue, queued, inputs, depth) {
|
||||
this.scan(inputs.size);
|
||||
for (const item of inputs.values()) {
|
||||
if (!isLink(item)) continue;
|
||||
const key = String(item[0]);
|
||||
if (!queued.has(key)) { queued.add(key); queue.push([key, depth]); }
|
||||
}
|
||||
}
|
||||
|
||||
stageShaped(name, inputs) {
|
||||
if (this.semantics.allClasses.has(name)) return false;
|
||||
const { shaped, withModel } = this.semantics.stageInputs;
|
||||
if (shaped.some(key => isLink(pyGet(inputs, key)))) return true;
|
||||
return isLink(pyGet(inputs, 'model')) && withModel.some(key => isLink(pyGet(inputs, key)));
|
||||
}
|
||||
|
||||
latentStages(origin, value) {
|
||||
if (!isLink(value)) throw new Unresolved('Unknown latent ancestry', 'malformed');
|
||||
const start = String(value[0]), queue = [[start, 0]], queued = new Set([start]);
|
||||
for (let head = 0; head < queue.length; head++) {
|
||||
const [nodeId, depth] = queue[head];
|
||||
if (nodeId === origin) throw new Unresolved('Cyclic latent ancestry', 'malformed');
|
||||
if (depth >= this.maxDepth) throw new Unresolved('Resolution depth limit reached', 'depth-limit');
|
||||
this.budget.spend();
|
||||
const [name, inputs] = this.node(nodeId);
|
||||
if (this.stageClasses.has(name)) throw new Unresolved(MULTISTAGE_UNATTRIBUTED_REASON);
|
||||
if (this.stageShaped(name, inputs)) throw this.unsupported('Unsupported latent ancestry', nodeId);
|
||||
this.enqueue(queue, queued, inputs, depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/** `_sampler_like_classes`: distinct classes, in graph order, of nodes shaped like samplers or guiders. */
|
||||
function samplerLikeClasses(graph) {
|
||||
const names = [];
|
||||
for (const node of graph.values()) {
|
||||
if (!isDict(node) || !isDict(pyGet(node, 'inputs'))) continue;
|
||||
const name = pyGet(node, 'class_type');
|
||||
if (typeof name !== 'string' || !name || names.includes(name)) continue;
|
||||
if (SAMPLER_LIKE_INPUTS.some(key => isLink(pyGet(node.get('inputs'), key)))) {
|
||||
names.push(pySlice(name, CLASS_NAME_LENGTH));
|
||||
if (names.length === NO_SAMPLER_NAMES) break;
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
function noSampler(graph) {
|
||||
const seen = samplerLikeClasses(graph);
|
||||
const reason = `No supported sampler pair found${seen.length ? ` (saw ${seen.join(', ')})` : ''}`;
|
||||
return result('unresolved', { reason, reasonCode: 'no-sampler' });
|
||||
}
|
||||
|
||||
/** `_prompt_manager_widgets`: API node ID to widget text for every PromptManager node that runs. */
|
||||
function promptManagerWidgets(workflow) {
|
||||
const nodes = isDict(workflow) ? pyGet(workflow, 'nodes') : null;
|
||||
if (!isList(nodes)) return new Map();
|
||||
const definitions = pyGet(workflow, 'definitions');
|
||||
const listed = isDict(definitions) ? pyGet(definitions, 'subgraphs') : null;
|
||||
const subgraphs = new Map();
|
||||
for (const subgraph of isList(listed) ? listed : []) {
|
||||
if (isDict(subgraph) && typeof pyGet(subgraph, 'id') === 'string' && isList(pyGet(subgraph, 'nodes'))) subgraphs.set(subgraph.get('id'), subgraph.get('nodes'));
|
||||
}
|
||||
const widgets = new Map(), stack = [[nodes, '', 0]];
|
||||
let visited = 0;
|
||||
while (stack.length) {
|
||||
const [members, prefix, depth] = stack.pop();
|
||||
for (const node of members) {
|
||||
visited += 1;
|
||||
if (visited > MAX_WORKFLOW_NODES) return widgets;
|
||||
if (!isDict(node)) continue;
|
||||
const kind = pyGet(node, 'type'), nodeId = pyGet(node, 'id');
|
||||
if (!(typeof nodeId === 'string' || isInt(nodeId))) continue;
|
||||
const apiId = `${prefix}${String(nodeId)}`;
|
||||
// A list or object `type` is neither a subgraph instance nor a PromptManager node (#286).
|
||||
if (isList(kind) || isDict(kind)) continue;
|
||||
if (typeof kind === 'string' && subgraphs.has(kind) && depth < MAX_SUBGRAPH_DEPTH) {
|
||||
stack.push([subgraphs.get(kind), `${apiId}:`, depth + 1]);
|
||||
continue;
|
||||
}
|
||||
const values = pyGet(node, 'widgets_values');
|
||||
const text = isList(values) && values.length && typeof values[0] === 'string' ? values[0] :
|
||||
isDict(values) && typeof pyGet(values, 'text') === 'string' ? values.get('text') : null;
|
||||
if (typeof kind === 'string' && kind !== 'PromptManagerPair' && kind.toLowerCase().includes('promptmanager') && text !== null) widgets.set(apiId, text);
|
||||
}
|
||||
}
|
||||
return widgets;
|
||||
}
|
||||
|
||||
/** `_overwritten_prompt_nodes` (R1). */
|
||||
function overwrittenPromptNodes(workflow, graph) {
|
||||
const widgets = promptManagerWidgets(workflow), byText = new Map();
|
||||
for (const [nodeId] of widgets) {
|
||||
const node = pyGet(graph, nodeId);
|
||||
const inputs = isDict(node) ? pyGet(node, 'inputs') : null;
|
||||
const text = isDict(inputs) ? pyGet(inputs, 'text') : null;
|
||||
if (typeof text === 'string') {
|
||||
if (!byText.has(text)) byText.set(text, []);
|
||||
byText.get(text).push(nodeId);
|
||||
}
|
||||
}
|
||||
const found = new Set();
|
||||
for (const ids of byText.values()) {
|
||||
if (ids.length > 1 && new Set(ids.map(id => widgets.get(id))).size > 1) ids.forEach(id => found.add(id));
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** `_resolve` for an unanchored inspection (output_node_id None). */
|
||||
function resolve(metadata, semantics) {
|
||||
if (!isDict(metadata) || !metadata.size) return result('absent', { reason: 'No parsed prompt metadata' });
|
||||
let graph;
|
||||
if (metadata.has('prompt')) graph = metadata.get('prompt');
|
||||
else if (metadata.has('parameters')) return parameters(metadata.get('parameters'), PROFILE.maxTextLength);
|
||||
else graph = metadata;
|
||||
if (!isDict(graph) || !graph.size) return result('unresolved', { reason: 'API graph is missing or malformed', reasonCode: 'malformed' });
|
||||
if (graph.size > PROFILE.nodeCeiling) return result('unresolved', { reason: 'Prompt graph exceeds the inspection node ceiling', reasonCode: 'graph-ceiling' });
|
||||
if (semantics === null) return result('unresolved', { reason: SEMANTICS_UNAVAILABLE_REASON });
|
||||
let overwritten = new Set();
|
||||
if (metadata.has('prompt')) {
|
||||
overwritten = overwrittenPromptNodes(pyGet(metadata, 'workflow'), graph);
|
||||
}
|
||||
const resolver = new GraphResolver(graph, metadata.has('prompt') ? metadata : null, semantics, overwritten);
|
||||
const samplerIds = finalStages(resolver, [...graph].filter(([, node]) => isDict(node) && typeof pyGet(node, 'class_type') === 'string' &&
|
||||
resolver.samplerClasses.has(node.get('class_type'))).map(([id]) => id));
|
||||
if (!samplerIds.length) return noSampler(graph);
|
||||
if (samplerIds.length > 1) {
|
||||
const candidates = samplerIds.map(id => resolver.pair(id));
|
||||
return sharedPair(candidates) ?? result('ambiguous', { reason: 'Multiple sampler branches', candidates });
|
||||
}
|
||||
return resolver.pair(samplerIds[0]);
|
||||
}
|
||||
|
||||
|
||||
/** `_may_hold_prompt_manager`. */
|
||||
function mayHoldPromptManager(canonical) {
|
||||
const graph = pyGet(canonical, 'prompt');
|
||||
if (!isDict(graph)) return false;
|
||||
for (const node of graph.values()) {
|
||||
if (!isDict(node)) continue;
|
||||
const name = pyGet(node, 'class_type'), inputs = pyGet(node, 'inputs');
|
||||
if (typeof name === 'string' && name.toLowerCase().includes('promptmanager')) return true;
|
||||
if (isDict(inputs) && inputs.has('search_text')) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** `_parsed_workflow`: the UI workflow as a dict, or null. */
|
||||
function parsedWorkflow(value) {
|
||||
if (typeof value === 'string') {
|
||||
try { value = pyJsonLoads(value); } catch (error) {
|
||||
if (error instanceof PyValueError) return null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
return isDict(value) ? value : null;
|
||||
}
|
||||
|
||||
/** `unreadable_evidence`: both roles when the file's metadata could not be read at all. */
|
||||
export function unreadableEvidence() {
|
||||
const resolution = { state: 'unresolved', sampler_id: null, reason: UNREADABLE_METADATA_REASON, reason_code: null, node: null };
|
||||
return { prompts: explained({ positive: sideOf('unresolved'), negative: sideOf('unresolved') }, resolution), resolution };
|
||||
}
|
||||
|
||||
/**
|
||||
* `inspect_prompt_evidence(records, None, profile=INSPECTION_PROFILE)`: `{prompts, resolution}` for the records a
|
||||
* local read found (`{prompt, workflow, parameters, comfyassets_prompt_pairs}` texts). `semantics` is
|
||||
* `compileSemantics(...)`'s table, or null when it could not be loaded.
|
||||
*/
|
||||
export function resolveLocalEvidence(records, semantics) {
|
||||
const source = records !== null && typeof records === 'object' ? records : {};
|
||||
const metadata = new Map(Object.entries(source).filter(([key]) => ROLE_METADATA_KEYS.has(key)));
|
||||
const malformedResolution = { state: 'unresolved', sampler_id: null, reason: MALFORMED_EVIDENCE_REASON, reason_code: 'malformed', node: null };
|
||||
if (!metadata.size) {
|
||||
return {
|
||||
prompts: { positive: sideOf('absent'), negative: sideOf('absent') },
|
||||
resolution: { state: 'absent', sampler_id: null, reason: 'No parsed prompt metadata', reason_code: null, node: null },
|
||||
};
|
||||
}
|
||||
const malformed = { prompts: explained({ positive: sideOf('unresolved'), negative: sideOf('unresolved') }, malformedResolution), resolution: malformedResolution };
|
||||
if (!metadata.has('prompt') && !metadata.has('parameters')) return malformed;
|
||||
if (typeof metadata.get('prompt') === 'string') {
|
||||
try { metadata.set('prompt', pyJsonLoads(metadata.get('prompt'))); } catch (error) {
|
||||
if (error instanceof PyValueError) return malformed;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
const workflow = mayHoldPromptManager(metadata) ? parsedWorkflow(source.workflow ?? null) : null;
|
||||
if (workflow !== null && metadata.has('prompt')) metadata.set('workflow', workflow);
|
||||
const resolved = resolve(metadata, semantics);
|
||||
const state = resolved.state, prompts = {};
|
||||
for (const role of ['positive', 'negative']) {
|
||||
const side = resolved[role];
|
||||
const present = side !== null && typeof side === 'object';
|
||||
if (state !== 'ambiguous' && present && (role === 'negative' || pyStrip(side.text))) prompts[role] = sideOf('resolved', side.text, side.provenance.text_source);
|
||||
else if (state === 'resolved' && present) prompts[role] = { ...sideOf('unresolved'), message: EMPTY_POSITIVE };
|
||||
else prompts[role] = sideOf(state !== 'resolved' ? state : 'unresolved');
|
||||
}
|
||||
const resolution = { state, sampler_id: resolved.sampler_id, reason: resolved.reason, reason_code: resolved.reason_code, node: resolved.node };
|
||||
return { prompts: explained(prompts, resolution), resolution };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
// The node table local Inspect resolves with (#249 local Inspect, PR L3 Task 10): web/js/inspection-semantics.json,
|
||||
// the very table the server's inspector reads, fetched once per page through the API client (the proxy-mount rule).
|
||||
// The Inspect page asks for it as it mounts, before any file is chosen; it is the only static file Inspect fetches,
|
||||
// and the request carries nothing about a selection. A table that cannot be fetched or used is null: the roles then
|
||||
// answer as the server does when its table is unusable, and a later selection asks again.
|
||||
import { compileSemantics } from './local-resolver.mjs';
|
||||
|
||||
export const SEMANTICS_PATH = '/prompt_manager/js/inspection-semantics.json';
|
||||
let pending = null;
|
||||
|
||||
async function fetchSemantics() {
|
||||
const client = globalThis.window?.ApiClient;
|
||||
if (typeof client?.resolveUrl !== 'function' || typeof globalThis.fetch !== 'function') return null;
|
||||
const response = await globalThis.fetch(client.resolveUrl(SEMANTICS_PATH), { credentials: 'same-origin' });
|
||||
if (!response.ok) throw new Error(`Inspection node table request failed (${response.status})`);
|
||||
return compileSemantics(await response.json());
|
||||
}
|
||||
|
||||
/** The compiled table (one request per page), or null when it is unavailable. */
|
||||
export function loadInspectionSemantics() {
|
||||
if (pending !== null) return pending;
|
||||
const current = pending = fetchSemantics().catch(() => null).then(table => {
|
||||
if (table === null && pending === current) pending = null;
|
||||
return table;
|
||||
});
|
||||
return current;
|
||||
}
|
||||
@@ -17,6 +17,7 @@
|
||||
// server folds them.
|
||||
|
||||
import { INT_MAX_STR_DIGITS } from "./local-projection.mjs";
|
||||
import { JSON_MAX_DEPTH } from "./py-json.mjs";
|
||||
|
||||
// Role records (prompt, parameters, the pair execution record) share one budget:
|
||||
// past it the read fails. A workflow has its own budget; past it only the workflow
|
||||
@@ -40,7 +41,6 @@ const MAX_NAME_BYTES = 64; // the longest carrier name is 24 bytes; longer names
|
||||
export const VIDEO_READ_CEILING = MAX_VIDEO_ELEMENTS * (MAX_HEADER_BYTES + MAX_NAME_BYTES) + VIDEO_TAG_READ_BYTES;
|
||||
const PREFIX_BYTES = 32;
|
||||
const YIELD_INTERVAL_MS = 8;
|
||||
const JSON_MAX_DEPTH = 1000; // Python's default recursion limit
|
||||
|
||||
const ROLE_KEYS = ["prompt", "parameters", "comfyassets_prompt_pairs"];
|
||||
const METADATA_KEYS = ["prompt", "workflow", "parameters", "comfyassets_prompt_pairs"];
|
||||
@@ -826,8 +826,9 @@ export function pythonJsonLoads(text) {
|
||||
}
|
||||
}
|
||||
function value(depth) {
|
||||
if (depth > JSON_MAX_DEPTH) throw new PythonJsonError("Maximum recursion depth exceeded", true);
|
||||
const char = text[pos];
|
||||
// The shared cap (py-json.mjs): `depth` containers enclose this value, and it would be one more.
|
||||
if ((char === "{" || char === "[") && depth >= JSON_MAX_DEPTH) throw new PythonJsonError("Maximum recursion depth exceeded", true);
|
||||
if (char === '"') return string();
|
||||
if (char === "{") {
|
||||
pos += 1;
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
// Python's value model for the local inspection resolver (#249 local Inspect, PR L3): the server's resolver
|
||||
// (utils/prompt_pair_resolver.py) runs on `json.loads` output, so the browser port reads the same text the same way.
|
||||
// Objects are `Map`s (insertion order, a repeated key keeps its first position and its last value, as a dict does),
|
||||
// integers are numbers (or BigInt past 2^53 - 1), floats are `PyFloat`, None is null. Strings are measured, sliced and
|
||||
// stripped as Python's `str` is: by code point, with `str.isspace()` whitespace. No DOM.
|
||||
|
||||
/** A Python float: distinct from an int (`1.0` is not a link slot, `type(x) is int` is false). */
|
||||
export class PyFloat {
|
||||
constructor(value) {
|
||||
this.value = value;
|
||||
Object.freeze(this);
|
||||
}
|
||||
}
|
||||
|
||||
/** `ValueError` from `json.loads` (malformed text, or an integer past `sys.int_info.str_digits_check_threshold`). */
|
||||
export class PyValueError extends Error {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
this.name = 'PyValueError';
|
||||
}
|
||||
}
|
||||
|
||||
// CPython's default int max str digits (PEP 651 / gh-95778).
|
||||
const INT_MAX_STR_DIGITS = 4300;
|
||||
/**
|
||||
* The nesting both browser CPython-JSON parsers accept (this one and local-video.mjs's): every array or object counts,
|
||||
* an empty one too, as CPython's scanner enters a recursion level for each. Past it `json.loads` raises RecursionError,
|
||||
* which the server treats as invalid JSON; its real limit depends on the Python (TESTING.md, "Deep JSON").
|
||||
*/
|
||||
export const JSON_MAX_DEPTH = 1000;
|
||||
const MAX_SAFE_DIGITS = '9007199254740991';
|
||||
const NUMBER = /-?(?:0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?/y;
|
||||
const STRING_STOP = /["\\\u0000-\u001f]/g;
|
||||
const HEX4 = /^[0-9a-fA-F]{4}$/;
|
||||
const ESCAPES = { '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t' };
|
||||
// The C scanner's constants, in its order of checks.
|
||||
const CONSTANTS = [['null', null], ['true', true], ['false', false], ['NaN', new PyFloat(NaN)],
|
||||
['Infinity', new PyFloat(Infinity)], ['-Infinity', new PyFloat(-Infinity)]];
|
||||
|
||||
export const isDict = value => value instanceof Map;
|
||||
export const isList = value => Array.isArray(value);
|
||||
/** `isinstance(value, int) and not isinstance(value, bool)`. */
|
||||
export const isInt = value => (typeof value === 'number' && Number.isInteger(value)) || typeof value === 'bigint';
|
||||
|
||||
function numberValue(match) {
|
||||
const [literal, fraction, exponent] = match;
|
||||
if (fraction || exponent) return new PyFloat(Number(literal));
|
||||
const digits = literal[0] === '-' ? literal.slice(1) : literal;
|
||||
if (digits.length > INT_MAX_STR_DIGITS) throw new PyValueError('Exceeds the limit for integer string conversion');
|
||||
if (digits.length > MAX_SAFE_DIGITS.length || (digits.length === MAX_SAFE_DIGITS.length && digits > MAX_SAFE_DIGITS)) return BigInt(literal);
|
||||
// `-0` is the int 0.
|
||||
return Number(literal) || 0;
|
||||
}
|
||||
|
||||
/** `json.loads(text)` with Python's defaults (C scanner): NaN/Infinity accepted, a repeated key's last value wins. */
|
||||
export function pyJsonLoads(text) {
|
||||
if (typeof text !== 'string') throw new TypeError('JSON text must be a string');
|
||||
if (text.startsWith('')) throw new PyValueError('Unexpected UTF-8 BOM (decode using utf-8-sig)');
|
||||
let pos = 0;
|
||||
const fail = message => new PyValueError(`${message}: char ${pos}`);
|
||||
const skip = () => {
|
||||
while (pos < text.length) {
|
||||
const c = text.charCodeAt(pos);
|
||||
if (c !== 0x20 && c !== 0x09 && c !== 0x0a && c !== 0x0d) break;
|
||||
pos++;
|
||||
}
|
||||
};
|
||||
function string() {
|
||||
pos++;
|
||||
let out = '';
|
||||
for (;;) {
|
||||
STRING_STOP.lastIndex = pos;
|
||||
const stop = STRING_STOP.exec(text);
|
||||
if (!stop) throw fail('Unterminated string starting at');
|
||||
out += text.slice(pos, stop.index);
|
||||
pos = stop.index + 1;
|
||||
if (stop[0] === '"') return out;
|
||||
if (stop[0] !== '\\') throw fail('Invalid control character at');
|
||||
const escape = text[pos];
|
||||
if (escape === 'u') {
|
||||
const hex = text.slice(pos + 1, pos + 5);
|
||||
if (!HEX4.test(hex)) throw fail('Invalid \\uXXXX escape');
|
||||
pos += 5;
|
||||
const code = parseInt(hex, 16);
|
||||
if (code >= 0xd800 && code <= 0xdbff && text[pos] === '\\' && text[pos + 1] === 'u') {
|
||||
const low = text.slice(pos + 2, pos + 6);
|
||||
if (!HEX4.test(low)) throw fail('Invalid \\uXXXX escape');
|
||||
const lowCode = parseInt(low, 16);
|
||||
if (lowCode >= 0xdc00 && lowCode <= 0xdfff) {
|
||||
out += String.fromCharCode(code, lowCode);
|
||||
pos += 6;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out += String.fromCharCode(code);
|
||||
} else if (Object.hasOwn(ESCAPES, escape)) {
|
||||
out += ESCAPES[escape];
|
||||
pos++;
|
||||
} else throw fail('Invalid \\escape');
|
||||
}
|
||||
}
|
||||
function key() {
|
||||
if (text[pos] !== '"') throw fail('Expecting property name enclosed in double quotes');
|
||||
const name = string();
|
||||
skip();
|
||||
if (text[pos] !== ':') throw fail("Expecting ':' delimiter");
|
||||
pos++;
|
||||
skip();
|
||||
return name;
|
||||
}
|
||||
function scalar() {
|
||||
if (text[pos] === '"') return string();
|
||||
for (const [literal, value] of CONSTANTS) {
|
||||
if (text.startsWith(literal, pos)) {
|
||||
pos += literal.length;
|
||||
return value;
|
||||
}
|
||||
}
|
||||
NUMBER.lastIndex = pos;
|
||||
const match = NUMBER.exec(text);
|
||||
if (!match) throw fail('Expecting value');
|
||||
pos += match[0].length;
|
||||
return numberValue(match);
|
||||
}
|
||||
skip();
|
||||
const stack = [];
|
||||
const enter = () => {
|
||||
if (stack.length >= JSON_MAX_DEPTH) throw fail('Maximum JSON nesting depth exceeded');
|
||||
pos++; skip();
|
||||
};
|
||||
let result;
|
||||
for (;;) {
|
||||
let value;
|
||||
if (text[pos] === '{') {
|
||||
enter();
|
||||
const frame = { value: new Map(), object: true, key: null };
|
||||
if (text[pos] === '}') pos++;
|
||||
else { frame.key = key(); stack.push(frame); continue; }
|
||||
value = frame.value;
|
||||
} else if (text[pos] === '[') {
|
||||
enter();
|
||||
const frame = { value: [], object: false };
|
||||
if (text[pos] === ']') pos++;
|
||||
else { stack.push(frame); continue; }
|
||||
value = frame.value;
|
||||
} else value = scalar();
|
||||
for (;;) {
|
||||
if (!stack.length) { result = value; break; }
|
||||
const frame = stack[stack.length - 1];
|
||||
if (frame.object) frame.value.set(frame.key, value);
|
||||
else frame.value.push(value);
|
||||
skip();
|
||||
if (text[pos] === ',') {
|
||||
pos++; skip();
|
||||
if (frame.object) frame.key = key();
|
||||
break;
|
||||
}
|
||||
if (text[pos] !== (frame.object ? '}' : ']')) throw fail("Expecting ',' delimiter");
|
||||
pos++;
|
||||
stack.pop();
|
||||
value = frame.value;
|
||||
}
|
||||
if (!stack.length) break;
|
||||
}
|
||||
skip();
|
||||
if (pos !== text.length) throw fail('Extra data');
|
||||
return result;
|
||||
}
|
||||
|
||||
/** `len(text)`: code points (a lone surrogate counts once). */
|
||||
export function pyLen(text) {
|
||||
let pairs = 0;
|
||||
for (let index = 0; index < text.length - 1; index++) {
|
||||
const code = text.charCodeAt(index);
|
||||
if (code >= 0xd800 && code <= 0xdbff) {
|
||||
const next = text.charCodeAt(index + 1);
|
||||
if (next >= 0xdc00 && next <= 0xdfff) { pairs++; index++; }
|
||||
}
|
||||
}
|
||||
return text.length - pairs;
|
||||
}
|
||||
|
||||
/** `text[:count]` by code points. */
|
||||
export function pySlice(text, count) {
|
||||
if (text.length <= count) return text;
|
||||
let end = 0;
|
||||
for (let taken = 0; taken < count && end < text.length; taken++) {
|
||||
const code = text.charCodeAt(end);
|
||||
const next = text.charCodeAt(end + 1);
|
||||
end += code >= 0xd800 && code <= 0xdbff && next >= 0xdc00 && next <= 0xdfff ? 2 : 1;
|
||||
}
|
||||
return text.slice(0, end);
|
||||
}
|
||||
|
||||
// `str.isspace()`: Unicode Zs plus the bidi classes B, S and WS (not U+FEFF, unlike `trim()`).
|
||||
export const PY_SPACE = '\\t\\n\\x0b\\x0c\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000';
|
||||
const LEADING = new RegExp(`^[${PY_SPACE}]+`), TRAILING = new RegExp(`[${PY_SPACE}]+$`);
|
||||
/** `text.strip()`. */
|
||||
export const pyStrip = text => text.replace(LEADING, '').replace(TRAILING, '');
|
||||
|
||||
/** `bool(value)`. */
|
||||
export function pyTruthy(value) {
|
||||
if (value === null || value === undefined || value === false) return false;
|
||||
if (value === true) return true;
|
||||
if (typeof value === 'number') return value !== 0;
|
||||
if (typeof value === 'bigint') return value !== 0n;
|
||||
if (value instanceof PyFloat) return value.value !== 0;
|
||||
if (typeof value === 'string' || isList(value)) return value.length > 0;
|
||||
if (isDict(value)) return value.size > 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** `value == 1` (True and 1.0 equal it too). */
|
||||
export const pyEqualsOne = value => value === 1 || value === 1n || value === true || (value instanceof PyFloat && value.value === 1);
|
||||
|
||||
/** `repr(float)`: the shortest round-trip digits, fixed for exponents -4..15, else `d.ddde+XX`. */
|
||||
export function pyFloatRepr(value) {
|
||||
if (Number.isNaN(value)) return 'nan';
|
||||
if (!Number.isFinite(value)) return value > 0 ? 'inf' : '-inf';
|
||||
if (value === 0) return Object.is(value, -0) ? '-0.0' : '0.0';
|
||||
const [mantissa, exponentText] = value.toExponential().split('e');
|
||||
const exponent = Number(exponentText);
|
||||
const sign = mantissa.startsWith('-') ? '-' : '';
|
||||
const digits = mantissa.replace(/^-/, '').replace('.', '');
|
||||
if (exponent < -4 || exponent >= 16) {
|
||||
const rest = digits.slice(1);
|
||||
return `${sign}${digits[0]}${rest ? `.${rest}` : ''}e${exponent < 0 ? '-' : '+'}${String(Math.abs(exponent)).padStart(2, '0')}`;
|
||||
}
|
||||
if (exponent < 0) return `${sign}0.${'0'.repeat(-exponent - 1)}${digits}`;
|
||||
const whole = digits.slice(0, exponent + 1).padEnd(exponent + 1, '0'), fraction = digits.slice(exponent + 1);
|
||||
return `${sign}${whole}.${fraction || '0'}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* `str(value)` where the resolver compares the result with node class names (`str(node.get("class_type", ""))`).
|
||||
* A container's text never equals a class name, so it is a marker only.
|
||||
*/
|
||||
export function pyStr(value) {
|
||||
if (typeof value === 'string') return value;
|
||||
if (value === null || value === undefined) return 'None';
|
||||
if (value === true) return 'True';
|
||||
if (value === false) return 'False';
|
||||
if (typeof value === 'number' || typeof value === 'bigint') return String(value);
|
||||
if (value instanceof PyFloat) return pyFloatRepr(value.value);
|
||||
return '\u0000container';
|
||||
}
|
||||
|
||||
/** `mapping.get(key, fallback)`. */
|
||||
export const pyGet = (mapping, key, fallback = null) => mapping.has(key) ? mapping.get(key) : fallback;
|
||||
@@ -286,14 +286,17 @@ export function openImportDialog({ scope, onInspect, onRescan, onMetadataScan =
|
||||
return { setRescanBusy };
|
||||
}
|
||||
|
||||
/** "Copy prompt": the text in a readonly, pre-selected textarea for a manual copy. */
|
||||
export function openCopyFallback(text, { scope, trigger = null } = {}) {
|
||||
/**
|
||||
* "Copy prompt": the text in a readonly, pre-selected textarea for a manual copy. `title` names another copy's dialog
|
||||
* (D117 "Copy settings summary").
|
||||
*/
|
||||
export function openCopyFallback(text, { scope, trigger = null, title = 'Copy prompt' } = {}) {
|
||||
requireScope(scope);
|
||||
if (typeof text !== 'string') throw new TypeError('Copy text must be a string');
|
||||
const area = el('textarea');
|
||||
area.readOnly = true;
|
||||
area.value = text;
|
||||
show('Copy prompt', [
|
||||
show(title, [
|
||||
field('Select and copy this text', area, 'copy-text'),
|
||||
el('p', 'Automatic clipboard access requires a secure browser context.', 'small'),
|
||||
], { scope, trigger, focusTarget: area });
|
||||
|
||||
@@ -212,6 +212,8 @@ main:focus-visible { outline: 2px solid var(--ca-focus); outline-offset: 4px; }
|
||||
/* #249 D20: the viewer details' pair send and history buttons wrap inside the narrow rail at 200% zoom with wider fonts,
|
||||
where the toolkit's `nowrap` would push them past its edge. */
|
||||
.ca-tools #viewer-details > button { white-space: normal; /* D20 */ }
|
||||
/* LI-4: "Copy settings summary" after the facts wraps the same way in the narrow rail. */
|
||||
.ca-tools #viewer-details .settings-summary { white-space: normal; /* D117 */ }
|
||||
/* The Images page narrows to one column inside a narrow container (the Library-embedded gallery). */
|
||||
.images-main { container: images-page / inline-size; }
|
||||
@container images-page (inline-size < 600px) {
|
||||
|
||||
Reference in New Issue
Block a user