fix(web): keep the native viewport usable after opening a large project
Some checks failed
M6 deployable RC / quick (push) Has been cancelled
M6 deployable RC / chromium (push) Has been cancelled
M6 deployable RC / release (push) Has been cancelled

root cause chain, matching desktop semantics: the desktop runs a file load on
the WM thread, so nothing else is dispatched while it runs. the web port sends
pythonExec/viewportObjectAxis while an 85 s open (and a frame posted before it)
still own the worker; those requests pass the 30 s timeout, the client marks
Main uncertain, and every later frame is rejected with "WebEngine Main 状态待恢复"
until the surface stops. the test helper exposeWebTools() also switches to the
web view, idling the pump and producing the old "needs a wake-up" artefact.

fixes:
- client: timeouts of read-only sync commands no longer mark Main uncertain;
  only commands that may mutate it do.
- canvas: a frame rejected for Main recovery keeps the pump alive with a bounded
  250 ms retry, and the frame carrying a new owner counts as the first
  acknowledged frame so readiness returns one round-trip sooner.
- worker: publish the scene only when Main's revision advanced or the frame
  carried input; publish geometry only with a revision change and let the app
  retain the previous buffers. response payloads drop from 1888 transfers to a
  small snapshot instead of a full SceneIR and geometry projection per frame.

regression case: opening the 238-object fixture inside the native view reaches
readiness with no pointer input and consumes a middle-drag; headed run passes
in ~2.4 minutes. acceptance stays NOT_CLAIMED.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
mes123456
2026-12-06 08:32:19 +08:00
parent 1a2968bbcf
commit 5a21a34c34
7 changed files with 78 additions and 26 deletions

View File

@@ -7151,7 +7151,7 @@ export function App({localOnly=false,course,teach}:{localOnly?:boolean;course?:A
/* Native only advances its revision for a real Main change, so a cancel or a
* pure focus frame must not manufacture an undo step or an unsaved edit. */
const applyNativeScene = (result: BlendOpenResult, changed = result.snapshot.revision !== snapshot?.revision): void => {
setSnapshot(result.snapshot); setGeometryBuffers(result.geometryBuffers);setNonMeshGeometryBuffers(result.nonMeshGeometryBuffers??[]);
setSnapshot(result.snapshot); setGeometryBuffers(current => result.geometryBuffers ?? current);setNonMeshGeometryBuffers(current => result.nonMeshGeometryBuffers ?? current);
// GPU/WM Outliner gestures return the same Main selection as command edits.
// Keeping only the active object loses recursive/range multi-selection in
// subsequent application actions despite the native tree showing it.

View File

@@ -92,6 +92,7 @@ export function WasmGPUCanvas({ client, active = true, playing = false, onApplie
let frame = 0;
let resizeRetry = 0;
let redrawRetry = 0;
let mainRecoveryWaits = 0;
let selectionRecoveryRetry = 0;
let events: WebEngineGPUInput[] = [];
let invoking = false;
@@ -633,6 +634,7 @@ export function WasmGPUCanvas({ client, active = true, playing = false, onApplie
if (batch.length) canvas.dataset.nativeInputReady = 'false';
try {
const result = await client.gpuUIFrame(session, dimensions.width, dimensions.height, dimensions.pixelRatio, batch, ownerGeneration);
mainRecoveryWaits = 0;
const { scene, error } = result;
if (!disposed && !stopped && typeof result.modalActive === 'boolean') onModalActive?.(result.modalActive);
canvas.dataset.nativeDisplay = result.displayAcknowledged ? 'acknowledged' : 'pending';
@@ -727,8 +729,13 @@ export function WasmGPUCanvas({ client, active = true, playing = false, onApplie
}
// Accept new drops only after the current owner has acknowledged its display and input tail.
if (readyOwnerGeneration !== ownerGeneration) { readyOwnerGeneration = ownerGeneration; readyOwnerFrames = 0; }
const ownerReady = Boolean(result.displayAcknowledged && !ownerChanged && !result.inputDiscarded && !error && attached && !contextLost && !events.length);
readyOwnerFrames = ownerReady ? readyOwnerFrames + 1 : 0;
/* The frame that carries a new owner already proves the display is live. Count it
* as the first acknowledged frame: a large scene pays a full rebuild per frame, so
* waiting for a third round-trip leaves the viewport unready for tens of seconds. */
const ownerStable = Boolean(result.displayAcknowledged && !result.inputDiscarded && !error && attached && !contextLost && !events.length);
const ownerReady = ownerStable && !ownerChanged;
if (ownerChanged && ownerStable) readyOwnerFrames = 1;
else readyOwnerFrames = ownerReady ? readyOwnerFrames + 1 : 0;
canvas.dataset.nativeInputReady = String(Boolean(!disposed && !stopped && ownerReady && readyOwnerFrames >= 2));
if (!readyPublished && canvas.dataset.nativeInputReady === 'true') { readyPublished = true; computeRebinds.current = 0; setReady(true); onReady?.(true); }
const redrawPending = error?.code === 'CAPABILITY_MISSING' && (error.message.includes('Browser region requires redraw') || error.message.includes('Browser region draw buffer is unavailable'));
@@ -875,6 +882,16 @@ export function WasmGPUCanvas({ client, active = true, playing = false, onApplie
? String((reason as { message?: unknown }).message) : String(reason);
const quotaPending = detail.startsWith('NATIVE_FILES_PERSISTENCE_PENDING');
if (quotaPending) { setOperationNotice('原生文件未写入浏览器存储:请重试或先下载备份'); if (!disposed && !stopped) frame = requestAnimationFrame(() => void draw()); return; }
/* The client rejects frames while a timed-out command may still land. Desktop
* Blender's file load owns the event loop, so the same wait is desktop-faithful:
* keep the pump alive until the late responses clear Main authority. */
if (detail.includes('WebEngine Main 状态待恢复')) {
if (mainRecoveryWaits++ < 600) {
setOperationNotice('正在等待原生 Main 恢复…');
if (!disposed && !stopped) frame = window.setTimeout(() => void draw(), 250);
return;
}
}
failSurface(reason);
}
};

View File

@@ -59,6 +59,16 @@ interface PendingRequest {
timedOut?: boolean; timeoutError?: ErrorReport;
}
/* Read-only command set, mirroring the Worker's READ_ONLY_JSON_COMMANDS. Desktop
* Blender runs file loads on the WM thread, so a read queued behind a load can never
* leave Main authority uncertain; a timeout here must not block later frames or edits. */
const READ_ONLY_SYNC_COMMANDS: ReadonlySet<string> = new Set([
"viewportCamera", "viewportFromCamera", "viewportObjectAxis", "history", "snapshot", "delta",
"depsgraph", "memoryStats", "listBlenderOperators", "listBlenderMacros", "listFeatureRoutes",
"listRNADataBlocks", "readRNAProperties", "listRNACollections", "readRNAPropertySchema",
"readRNACollection",
]);
export interface WebEngineClientOptions {
onAudioError?: (message: string) => void;
nativeServices?: boolean;
@@ -1680,7 +1690,9 @@ export class WebEngineClient {
/* A display-frame timeout says nothing about Main authority; treating it as
* uncertain would block every later undo/save after one slow import frame. */
const frameOnly = command.type === "gpuUI" && (command as { op?: string }).op === "frame";
this.mainUncertain = !frameOnly;
const readOnlySync = command.type === "jsonCommand" &&
READ_ONLY_SYNC_COMMANDS.has(String((command as { cmd?: unknown }).cmd ?? ""));
this.mainUncertain = !(frameOnly || readOnlySync);
console.error(`[web-engine] request timed out: ${command.type}${command.type === "jsonCommand" ? `/${(command as { cmd?: string }).cmd}` : ""}${frameOnly ? " (frame; Main remains certain)" : ""}`);
pending.timedOut = true;
pending.timeoutError = this.report("WORKER_TERMINATED", `WebEngine 请求超时: ${command.type}`, true);

View File

@@ -598,12 +598,18 @@ async function handleGPURequest(command: Extract<WebEngineRequest["command"], {
const finish = async (): Promise<WebEngineResult> => {
let sceneResult: Partial<WebEngineResult> = {};
if (mutated) {
const previousRevision = currentSnapshot?.revision;
const scene = await readSnapshotResult().catch((error: unknown) => {
const projection = typeof error === "object" && error !== null && "code" in error ? error as ErrorReport : report("WASM_INIT_FAILED", error instanceof Error ? error.message : "Native scene projection failed");
throw { ...projection, message: `GPU_MAIN_RECOVERY_PENDING: ${projection.message}`, detail: [projection.detail ?? (error instanceof Error ? error.stack : undefined), failure?.message, failure?.detail].filter(Boolean).join("\n") };
});
currentSnapshot = scene.snapshot;
sceneResult = { ...publishFullScene(scene), delta: readDelta() };
/* Geometry buffers dominate the payload (1888 transfers on a 238-mesh scene) and a
* context-only frame cannot change them: a large response may never reach the page.
* Publish them only when the Main revision changed; the editor context still ships. */
sceneResult = scene.snapshot.revision !== previousRevision
? { ...publishFullScene(scene), delta: readDelta() }
: { snapshot: scene.snapshot, delta: readDelta() };
}
// Consume the cursor revision only after the Main projection can be published.
// Recovery may call finish again if that projection throws.
@@ -781,7 +787,16 @@ async function handleGPURequest(command: Extract<WebEngineRequest["command"], {
if (exports.size > 16) exports.delete(exports.keys().next().value!);
}
const inputOwnerChanged = syncGPUInputOwner();
if (nativeFrame?.changed) mutated = true;
if (nativeFrame?.changed) {
/* The native flag compares the serialized editor snapshot, so it is true on almost
* every draw. Publish only when Main advanced or the frame carried input that may
* change the editor context; idle frames then stay cheap instead of projecting the
* whole SceneIR and geometry on a large scene. */
const revision = (nativeFrame as { revision?: unknown }).revision;
mutated = typeof revision === "number"
? revision !== currentSnapshot?.revision || command.events.length > 0
: true;
}
if (nativeFrame?.state === "ERROR" &&
(nativeFrame.error?.startsWith("NATIVE_GPU_SELECTION_CANCELLED:") ||
nativeFrame.error?.startsWith("NATIVE_GPU_DEPTH_CANCELLED:") ||