Files
Netcatty/application/state/pluginRemoteTree.ts
T
陈大猫 549f58c653 fix(plugins): keep vault plugin pages on header double-click and view errors (#4548)
* fix(plugins): keep vault pages on view errors and ignore header double-clicks

Double-clicking a PluginDataGrid column header fired two sortChange events.
A failed host-drawn view session then called the vault unavailable fallback,
which selected Hosts and kicked the user out of the plugin workbench.

Ignore the second click of a header double-click, and when a started view
session fails, stay on the plugin page with an in-page error and Retry
instead of navigating to Hosts. Missing vault-page contributions still
fall back to Hosts.

Related: binaricat/netcatty-database-plugin#6

* fix(plugins): debounce PluginDataGrid header sort clicks

event.detail > 1 was not enough: CDP/Electron double-clicks can still
deliver two detail=1 clicks about 40ms apart, and overlapping
host-ui.update payloads disposed the view session. Ignore a second
sort click within 500ms, and warn with the dispose reason when an
update or event send fails.

Related: binaricat/netcatty-database-plugin#6

* fix(plugins): keep the last good tree on duplicate view-node updates

A PluginDataGrid header double-click can produce a host-ui.update whose
projected tree has duplicate node IDs. apply() previously mutated the
live receiver first, then hard-failed the view. Stage the batch on a
scratch receiver, reject Duplicate view node without closing the
session, and keep the last good snapshot. Forbidden mutations still
fail the view.

Related: binaricat/netcatty-database-plugin#6

* fix(plugins): hard-fail mixed policy violations and stash rejected CSS

Duplicate view-node recovery now re-validates the projected tree with
unique IDs so a batch that also contains a forbidden mutation still
closes the view. Validated CSS from a rejected duplicate update is
stashed and published on the next accepted update.

Related: binaricat/netcatty-database-plugin#6

* fix(plugins): let explicit CSS supersede a stashed pending stylesheet

If a rejected duplicate update stashed CSS, an later accepted update
that explicitly resends the last committed CSS must drop the pending
stylesheet instead of publishing it.

Related: binaricat/netcatty-database-plugin#6

* fix(plugins): apply duplicate view-node inserts as moves

RemoteReceiver leaves a stale copy when a host-ui.update inserts an
already-attached id, or a parent that re-serializes one. Rejecting the
batch kept the last good grid but desynced the producer, so a later
PluginDataGrid sort did not visually apply.

Normalize duplicate-only batches by detaching those ids first, then
apply the rewritten batch to both the scratch projection and the live
receiver. Mixed policy violations still hard-fail.

* fix(plugins): remap producer removals after rewrite detaches

rewriteDuplicateInsertBatch already detached already-attached IDs
before inserting a wrapper, but then replayed the producer's original
removal index. That index could now point at a sibling the producer
kept, so a same-tick wrap of b dropped a and later updates to a were
ignored.

Skip producer removals whose slot was already detached by the rewrite,
and shift later indices down accordingly.

* fix(plugins): remap wrap insert index after descendant detaches

RemoteMutationObserver can encode insert-at-0 when the previous sibling
was moved into the inserted wrapper. After detaching that descendant
from the same parent, honoring the stale 0 put wrapper before a, so a
later remove of wrapper at index 1 deleted a.

Bump the insert index to the hole left by a same-parent descendant
detach. Do not bump when the detached id is the insert root itself, so
ordinary moves stay intact.
2026-11-29 21:01:48 +08:00

248 lines
9.3 KiB
TypeScript

import { RemoteReceiver } from '@remote-dom/core/receivers';
import { validatePluginMutationBatch, validatePluginRemoteTree } from '@/domain/pluginRemoteTreePolicy.cjs';
type WireNode = { id: string; type: 3 | 8; data: string } | {
id: string; type: 1; element: string; attributes: Record<string, string>; children: WireNode[];
};
type WireTree = { children: WireNode[] };
const validatedTrees = new WeakSet<object>();
export function isValidatedPluginRemoteTree(tree: unknown): boolean {
return Boolean(tree && typeof tree === 'object' && validatedTrees.has(tree));
}
export function isDuplicatePluginViewNodeError(error: unknown): error is TypeError {
return error instanceof TypeError && error.message === 'Duplicate view node';
}
function withUniqueViewIds(tree: WireTree): WireTree {
let n = 0;
const rewrite = (node: WireNode): WireNode => {
const id = `n${n++}`;
if (node.type === 3 || node.type === 8) return { id, type: node.type, data: node.data };
return { id, type: 1, element: node.element, attributes: node.attributes, children: node.children.map(rewrite) };
};
return { children: tree.children.map(rewrite) };
}
/** If a projected tree has duplicate IDs, still hard-fail when other policy violations exist. */
export function assertDuplicateOnlyPluginRemoteTree(tree: WireTree): void {
validatePluginRemoteTree(withUniqueViewIds(tree));
}
type WorkingNode = {
id: string;
parentId: string | null;
children: WorkingNode[];
};
type RewriteDetach = {
parentId: string;
index: number;
id: string;
};
function collectSubtreeIds(node: WireNode, out: string[] = []): string[] {
out.push(node.id);
if (node.type === 1) {
for (const child of node.children) collectSubtreeIds(child, out);
}
return out;
}
function buildWorkingNode(node: WireNode, parentId: string, nodes: Map<string, WorkingNode>): WorkingNode {
const working: WorkingNode = { id: node.id, parentId, children: [] };
nodes.set(node.id, working);
if (node.type === 1) {
for (const child of node.children) {
working.children.push(buildWorkingNode(child, node.id, nodes));
}
}
return working;
}
function detachWorkingSubtree(node: WorkingNode, nodes: Map<string, WorkingNode>): void {
nodes.delete(node.id);
node.parentId = null;
for (const child of node.children) detachWorkingSubtree(child, nodes);
}
function hasAncestorInSet(startId: string, ids: Set<string>, nodes: Map<string, WorkingNode>): boolean {
let cursor: string | null = startId;
while (cursor !== null) {
if (ids.has(cursor)) return true;
cursor = nodes.get(cursor)?.parentId ?? null;
}
return false;
}
/**
* Normalizes a duplicate-only mutation batch so inserts referencing IDs already
* attached in the tree first emit explicit removals from their previous parents.
* Returns null if an insert would detach its own destination parent (cycle).
*/
function rewriteDuplicateInsertBatch(current: WireTree, batch: unknown[][]): unknown[][] | null {
const root: WorkingNode = { id: '~', parentId: null, children: [] };
const nodes = new Map<string, WorkingNode>([['~', root]]);
for (const child of current.children) {
root.children.push(buildWorkingNode(child, '~', nodes));
}
const rewritten: unknown[][] = [];
const rewriteDetaches: RewriteDetach[] = [];
for (const record of batch) {
const type = record[0];
if (type === 0) {
const parentId = record[1] as string;
const node = record[2] as WireNode;
let insertIndex = record[3] as number;
const parent = nodes.get(parentId);
if (!parent) {
// Detached parent: RemoteReceiver drops this insert as a no-op.
rewritten.push(record);
continue;
}
const subtreeIds = collectSubtreeIds(node);
if (hasAncestorInSet(parentId, new Set(subtreeIds), nodes)) {
return null;
}
for (const existingId of subtreeIds) {
const existing = nodes.get(existingId);
if (!existing || existing.parentId === null) continue;
const oldParent = nodes.get(existing.parentId);
if (!oldParent) continue;
const oldIndex = oldParent.children.indexOf(existing);
if (oldIndex < 0) continue;
rewritten.push([1, oldParent.id, oldIndex]);
rewriteDetaches.push({ parentId: oldParent.id, index: oldIndex, id: existing.id });
oldParent.children.splice(oldIndex, 1);
detachWorkingSubtree(existing, nodes);
if (oldParent.id === parentId) {
if (oldIndex < insertIndex) {
insertIndex -= 1;
} else if (existing.id !== node.id && oldIndex > insertIndex) {
insertIndex = oldIndex;
}
}
}
rewritten.push(insertIndex === record[3] ? record : [0, parentId, node, insertIndex]);
const inserted = buildWorkingNode(node, parentId, nodes);
if (insertIndex >= parent.children.length) {
parent.children.push(inserted);
} else {
parent.children.splice(insertIndex, 0, inserted);
}
} else if (type === 1) {
const parentId = record[1] as string;
const removeIndex = record[2] as number;
const exactMatchIndex = rewriteDetaches.findIndex(
(detach) => detach.parentId === parentId && detach.index === removeIndex,
);
if (exactMatchIndex !== -1) {
rewriteDetaches.splice(exactMatchIndex, 1);
continue;
}
let smallerCount = 0;
for (const detach of rewriteDetaches) {
if (detach.parentId === parentId && detach.index < removeIndex) {
smallerCount += 1;
}
}
const remappedIndex = removeIndex - smallerCount;
const parent = nodes.get(parentId);
if (!parent) {
if (smallerCount === 0) rewritten.push(record);
continue;
}
if (remappedIndex < 0 || remappedIndex >= parent.children.length) {
continue;
}
rewritten.push(remappedIndex === removeIndex ? record : [1, parentId, remappedIndex]);
const [removed] = parent.children.splice(remappedIndex, 1);
if (removed) detachWorkingSubtree(removed, nodes);
for (const detach of rewriteDetaches) {
if (detach.parentId === parentId && detach.index > removeIndex) {
detach.index -= 1;
}
}
} else {
rewritten.push(record);
}
}
return rewritten;
}
/** Data-only staging area: untrusted changes are never applied directly to the host DOM. */
export function createPluginRemoteTree() {
const receiver = new RemoteReceiver();
let current: WireTree = { children: [] };
validatedTrees.add(current);
let failed = false;
const project = (node: unknown): WireNode => {
const value = node as { id: string; type: number; data?: string; element?: string; attributes?: Record<string, string>; children?: unknown[] };
if (value.type === 3 || value.type === 8) return { id: value.id, type: value.type, data: value.data ?? '' };
return { id: value.id, type: 1, element: value.element ?? '', attributes: Object.fromEntries(Object.entries(value.attributes ?? {}).filter(([, attribute]) => attribute !== null)), children: (value.children ?? []).map(project) };
};
const applyToScratch = (records: unknown[][]): WireTree => {
const scratch = new RemoteReceiver();
if (current.children.length > 0) {
scratch.connection.mutate(
current.children.map((child, index) => [0, '~', child, index]) as unknown as Parameters<typeof scratch.connection.mutate>[0],
);
}
scratch.connection.mutate(records as unknown as Parameters<typeof scratch.connection.mutate>[0]);
return { children: scratch.root.children.map(project) };
};
return {
apply(input: unknown): WireTree {
if (failed) throw new Error('Plugin view has been closed after an invalid update');
try {
validatePluginMutationBatch(input);
// Ordinary DOM attribute mutations do not specify a channel. RemoteReceiver
// defaults those to properties, so explicitly mark them as attributes.
const batch = (input as unknown[][]).map((record) => record[0] === 3 && record.length === 4 ? [...record, 2] : record);
let appliedBatch = batch;
let next = applyToScratch(batch);
try {
validatePluginRemoteTree(next);
} catch (error) {
if (!isDuplicatePluginViewNodeError(error)) throw error;
assertDuplicateOnlyPluginRemoteTree(next);
const rewritten = rewriteDuplicateInsertBatch(current, batch);
if (!rewritten) throw error;
const rewrittenNext = applyToScratch(rewritten);
try {
validatePluginRemoteTree(rewrittenNext);
} catch (rewrittenError) {
if (isDuplicatePluginViewNodeError(rewrittenError)) assertDuplicateOnlyPluginRemoteTree(rewrittenNext);
throw rewrittenError;
}
appliedBatch = rewritten;
next = rewrittenNext;
}
receiver.connection.mutate(appliedBatch as unknown as Parameters<typeof receiver.connection.mutate>[0]);
validatedTrees.add(next);
current = next;
return next;
} catch (error) {
if (!isDuplicatePluginViewNodeError(error)) {
failed = true;
current = { children: [] };
validatedTrees.add(current);
}
throw error;
}
},
snapshot(): WireTree { return current; },
isFailed(): boolean { return failed; },
};
}