Compare commits

..
Author SHA1 Message Date
陈大猫 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
陈大猫 3a913b8fc2 feat(plugins): forward pointer and wheel events through host-drawn views (#4556)
Host-drawn Remote DOM surfaces now translate pointerdown, pointermove,
pointerup, pointercancel, and wheel into HostDrawnViewEvent so plugin
HTML canvases can drag, pan, and zoom in the real workbench. The official
SDK dispatches PointerEvent and WheelEvent with surface-relative
coordinates.

Includes host-side pointer capture after pointerdown, move coalescing
with acknowledgedEvent backpressure, pointercancel on surface teardown,
a non-passive wheel listener on the shadow host, and native scrolling
when a scrollable ancestor or host-owned popover panel can consume the
gesture.
2026-11-29 20:14:06 +08:00
陈大猫 8cae6c5784 fix(tray): preload hidden tray panel so first right-click is not delayed (#4558)
Fixes #4557
2026-11-29 18:14:18 +08:00
陈大猫 3c4f561beb fix(rdp): send local clipboard images to the remote desktop (#4552)
* fix(rdp): send local clipboard images to the remote desktop

Fixes #4551

* fix(rdp): invalidate clipboard echo guards on format replacement

Fixes the Codex P2 on PR #4552: a later text-only or image-only clipboard must replace the remote clipboard even when one format matches a stale guard from the previous snapshot.

* fix(rdp): write mixed remote clipboard text and PNG locally

Addresses the Codex P2 on PR #4552: write mixed remote snapshots locally as both text/plain and image/png so the echo guard does not wipe remote text on refocus. Fall back to PNG, then text, if the mixed write fails.
2026-11-29 17:25:37 +08:00
25 changed files with 1727 additions and 74 deletions

No files matched your search

+2
View File
@@ -1330,6 +1330,8 @@ Highlight the focused split pane:
"plugins.sidebar.selectTerminal": "Select an open terminal first.",
"plugins.sidebar.loading": "Loading extension page…",
"plugins.vault.loading": "Loading plugin page…",
"plugins.vault.viewError": "The plugin page failed to render.",
"plugins.vault.retry": "Retry",
"plugins.interaction.title": "Plugin request",
"plugins.interaction.openUrlTitle": "Open external link?",
"plugins.interaction.openUrlNote": "This plugin wants to open the following HTTPS URL in your default browser:",
+2
View File
@@ -1330,6 +1330,8 @@ Resalta el panel dividido enfocado:
"plugins.sidebar.selectTerminal": "Selecciona primero un terminal abierto.",
"plugins.sidebar.loading": "Cargando página de extensión…",
"plugins.vault.loading": "Cargando página del plugin…",
"plugins.vault.viewError": "No se pudo renderizar la página del plugin.",
"plugins.vault.retry": "Reintentar",
"plugins.interaction.title": "Solicitud de complemento",
"plugins.interaction.openUrlTitle": "¿Abrir enlace externo?",
"plugins.interaction.openUrlNote": "Este complemento solicita abrir la siguiente URL HTTPS en tu navegador predeterminado:",
+2
View File
@@ -1271,6 +1271,8 @@ export const ruCoreMessages: Messages = {
"plugins.sidebar.selectTerminal": "Сначала выберите открытый терминал.",
"plugins.sidebar.loading": "Загрузка страницы расширения…",
"plugins.vault.loading": "Загрузка страницы плагина…",
"plugins.vault.viewError": "Не удалось отобразить страницу плагина.",
"plugins.vault.retry": "Повторить",
"plugins.interaction.title": "Запрос плагина",
"plugins.interaction.openUrlTitle": "Открыть внешнюю ссылку?",
"plugins.interaction.openUrlNote": "Этот плагин запрашивает открытие следующего HTTPS-адреса в браузере по умолчанию:",
+2
View File
@@ -1247,6 +1247,8 @@ Vaults 标签保持扁平,不使用这块背景。
"plugins.sidebar.selectTerminal": "请先选择已打开的终端。",
"plugins.sidebar.loading": "正在加载扩展页面…",
"plugins.vault.loading": "正在加载插件页面…",
"plugins.vault.viewError": "插件页面渲染失败。",
"plugins.vault.retry": "重试",
"plugins.interaction.title": "插件请求",
"plugins.interaction.openUrlTitle": "打开外部链接?",
"plugins.interaction.openUrlNote": "此插件请求在默认浏览器中打开以下 HTTPS 链接:",
+2
View File
@@ -1248,6 +1248,8 @@ Vaults 分頁維持扁平,不使用這塊背景。
"plugins.sidebar.selectTerminal": "請先選擇已開啟的終端。",
"plugins.sidebar.loading": "正在載入擴充功能頁面…",
"plugins.vault.loading": "正在載入擴充功能頁面…",
"plugins.vault.viewError": "擴充功能頁面無法顯示。",
"plugins.vault.retry": "重試",
"plugins.interaction.title": "外掛請求",
"plugins.interaction.openUrlTitle": "開啟外部連結?",
"plugins.interaction.openUrlNote": "此外掛請求在預設瀏覽器中開啟以下 HTTPS 連結:",
+406
View File
@@ -65,3 +65,409 @@ test('inserting a child into an existing void element fails the view', async ()
assert.equal(tree.isFailed(), true);
assert.deepEqual(tree.snapshot(), { children: [] });
});
test('duplicate insert of an existing id applies as a move or replace and keeps follow-up updates in sync', async () => {
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
const tree = createPluginRemoteTree();
tree.apply([[0, '~', { id: 'a', type: 1, element: 'div', attributes: { class: 'first' }, children: [] }, 0]]);
// Inserting an existing id at a later sibling index replaces the existing node in place.
const replaced = tree.apply([
[3, 'a', 'class', 'stale'],
[0, '~', { id: 'a', type: 1, element: 'span', attributes: { class: 'replaced' }, children: [] }, 1],
]);
assert.equal(tree.isFailed(), false);
assert.deepEqual(replaced, {
children: [{ id: 'a', type: 1, element: 'span', attributes: { class: 'replaced' }, children: [] }],
});
// Follow-up mutations must apply against the replaced live node (desync gate).
const afterFollowUp = tree.apply([
[3, 'a', 'class', 'after-sort'],
[0, '~', { id: 'b', type: 1, element: 'div', attributes: {}, children: [{ id: 'b-text', type: 3, data: 'second' }] }, 1],
]);
assert.deepEqual(afterFollowUp, {
children: [
{ id: 'a', type: 1, element: 'span', attributes: { class: 'after-sort' }, children: [] },
{ id: 'b', type: 1, element: 'div', attributes: {}, children: [{ id: 'b-text', type: 3, data: 'second' }] },
],
});
// Moving an existing sibling forward adjusts the insert index after detaching the old slot.
const movedForward = tree.apply([
[0, '~', { id: 'a', type: 1, element: 'span', attributes: { class: 'moved-end' }, children: [] }, 2],
]);
assert.deepEqual(movedForward.children.map((node) => node.id), ['b', 'a']);
assert.deepEqual(movedForward.children[1], { id: 'a', type: 1, element: 'span', attributes: { class: 'moved-end' }, children: [] });
// Moving an existing sibling backward preserves index 0 and keeps subsequent updates working.
const movedBack = tree.apply([
[0, '~', { id: 'a', type: 1, element: 'span', attributes: { class: 'moved-start' }, children: [] }, 0],
]);
assert.deepEqual(movedBack.children.map((node) => node.id), ['a', 'b']);
const postMoveAttr = tree.apply([[2, 'b-text', 'updated-second'], [3, 'a', 'class', 'synced']]);
assert.deepEqual(postMoveAttr, {
children: [
{ id: 'a', type: 1, element: 'span', attributes: { class: 'synced' }, children: [] },
{ id: 'b', type: 1, element: 'div', attributes: {}, children: [{ id: 'b-text', type: 3, data: 'updated-second' }] },
],
});
});
test('inserting a parent whose subtree re-includes an already-present child detaches the child and preserves later updates', async () => {
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
const tree = createPluginRemoteTree();
tree.apply([
[0, '~', {
id: 'old-parent',
type: 1,
element: 'div',
attributes: {},
children: [{
id: 'cell-1',
type: 1,
element: 'span',
attributes: { class: 'unsorted' },
children: [{ id: 'cell-text', type: 3, data: 'alpha' }],
}],
}, 0],
]);
// Parent insertion repeats already-attached descendant IDs without a preceding remove.
const reparented = tree.apply([
[0, '~', {
id: 'new-parent',
type: 1,
element: 'section',
attributes: {},
children: [{
id: 'cell-1',
type: 1,
element: 'span',
attributes: { class: 'sorted-asc' },
children: [{ id: 'cell-text', type: 3, data: 'alpha' }],
}],
}, 1],
]);
assert.equal(tree.isFailed(), false);
assert.deepEqual(reparented, {
children: [
{ id: 'old-parent', type: 1, element: 'div', attributes: {}, children: [] },
{
id: 'new-parent',
type: 1,
element: 'section',
attributes: {},
children: [{
id: 'cell-1',
type: 1,
element: 'span',
attributes: { class: 'sorted-asc' },
children: [{ id: 'cell-text', type: 3, data: 'alpha' }],
}],
},
],
});
// A subsequent sort-like incremental update on the moved child applies cleanly.
const secondSort = tree.apply([
[3, 'cell-1', 'class', 'sorted-desc'],
[2, 'cell-text', 'omega'],
]);
assert.deepEqual(secondSort.children[1], {
id: 'new-parent',
type: 1,
element: 'section',
attributes: {},
children: [{
id: 'cell-1',
type: 1,
element: 'span',
attributes: { class: 'sorted-desc' },
children: [{ id: 'cell-text', type: 3, data: 'omega' }],
}],
});
// Same-batch case: descendant inserted first, then a new parent serializing that descendant.
const sameBatch = tree.apply([
[0, 'old-parent', { id: 'child-2', type: 1, element: 'span', attributes: {}, children: [{ id: 'child-2-text', type: 3, data: 'one' }] }, 0],
[0, '~', {
id: 'wrapper',
type: 1,
element: 'div',
attributes: {},
children: [{ id: 'child-2', type: 1, element: 'span', attributes: {}, children: [{ id: 'child-2-text', type: 3, data: 'one' }] }],
}, 2],
]);
assert.equal(tree.isFailed(), false);
assert.deepEqual(sameBatch.children[0], { id: 'old-parent', type: 1, element: 'div', attributes: {}, children: [] });
assert.deepEqual(sameBatch.children[2], {
id: 'wrapper',
type: 1,
element: 'div',
attributes: {},
children: [{ id: 'child-2', type: 1, element: 'span', attributes: {}, children: [{ id: 'child-2-text', type: 3, data: 'one' }] }],
});
const afterSameBatch = tree.apply([[2, 'child-2-text', 'two']]);
assert.deepEqual(afterSameBatch.children[2], {
id: 'wrapper',
type: 1,
element: 'div',
attributes: {},
children: [{ id: 'child-2', type: 1, element: 'span', attributes: {}, children: [{ id: 'child-2-text', type: 3, data: 'two' }] }],
});
});
test('unrecoverable self-nesting duplicate throws without failing the tree or corrupting later updates', async () => {
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
const tree = createPluginRemoteTree();
tree.apply([[0, '~', { id: 'a', type: 1, element: 'div', attributes: { class: 'first' }, children: [] }, 0]]);
assert.throws(
() => tree.apply([
[3, 'a', 'class', 'rejected'],
[0, 'a', { id: 'a', type: 1, element: 'span', attributes: {}, children: [] }, 0],
]),
/Duplicate view node/,
);
assert.equal(tree.isFailed(), false);
assert.deepEqual(tree.snapshot(), {
children: [{ id: 'a', type: 1, element: 'div', attributes: { class: 'first' }, children: [] }],
});
const updated = tree.apply([[0, '~', { id: 'b', type: 3, data: 'second' }, 1]]);
assert.deepEqual(updated, {
children: [
{ id: 'a', type: 1, element: 'div', attributes: { class: 'first' }, children: [] },
{ id: 'b', type: 3, data: 'second' },
],
});
});
test('a duplicate id combined with a forbidden mutation still hard-fails the view', async () => {
const { createPluginRemoteTree, isDuplicatePluginViewNodeError, assertDuplicateOnlyPluginRemoteTree } = await import('./pluginRemoteTree');
const tree = createPluginRemoteTree();
tree.apply([[0, '~', { id: 'input', type: 1, element: 'input', attributes: { type: 'text' }, children: [] }, 0]]);
// Mutation order matters for RemoteReceiver: the void-element child is applied first so the
// projected tree actually contains both the policy violation and a later duplicate id.
assert.throws(
() => tree.apply([
[0, 'input', { id: 'child', type: 3, data: 'invalid' }, 0],
[0, '~', { id: 'input', type: 1, element: 'div', attributes: {}, children: [] }, 1],
]),
/Void view elements/,
);
assert.equal(tree.isFailed(), true);
assert.deepEqual(tree.snapshot(), { children: [] });
// Even when the duplicate node appears earlier in root order than the void-element violation,
// unique-id revalidation must still hard-fail instead of rewriting the batch.
const duplicateFirstTree = createPluginRemoteTree();
duplicateFirstTree.apply([[0, '~', { id: 'input', type: 1, element: 'input', attributes: { type: 'text' }, children: [] }, 0]]);
assert.throws(
() => duplicateFirstTree.apply([
[0, 'input', { id: 'child', type: 3, data: 'invalid' }, 0],
[0, '~', { id: 'input', type: 1, element: 'div', attributes: {}, children: [] }, 0],
]),
/Void view elements/,
);
assert.equal(duplicateFirstTree.isFailed(), true);
assert.deepEqual(duplicateFirstTree.snapshot(), { children: [] });
// Defense in depth: if a projected tree already has both issues, unique-id revalidation
// must still surface the void-element violation instead of treating it as recoverable.
const mixed = {
children: [
{ id: 'input', type: 1 as const, element: 'input', attributes: { type: 'text' }, children: [{ id: 'child', type: 3 as const, data: 'invalid' }] },
{ id: 'input', type: 1 as const, element: 'div', attributes: {}, children: [] },
],
};
assert.equal(isDuplicatePluginViewNodeError(new TypeError('Duplicate view node')), true);
assert.throws(() => assertDuplicateOnlyPluginRemoteTree(mixed), /Void view elements/);
});
test('RemoteMutationObserver wrapping a sibling preserves kept siblings and follow-up text updates', async () => {
const dom = new JSDOM('<!doctype html><div id="remote"></div>', { url: 'http://localhost', pretendToBeVisual: true });
const saved = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'MutationObserver', 'Event', 'MouseEvent']) {
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window] });
}
const { RemoteMutationObserver } = await import('@remote-dom/core/elements');
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
const staged = createPluginRemoteTree();
const batches: unknown[][][] = [];
const observer = new RemoteMutationObserver({
mutate(records) {
const cloned = JSON.parse(JSON.stringify(records)) as unknown[][];
batches.push(cloned);
staged.apply(cloned);
},
call() { throw new Error('Host method calls are unavailable'); },
});
const container = document.getElementById('remote')!;
observer.observe(container);
const flush = () => new Promise((resolve) => setTimeout(resolve, 10));
try {
const a = document.createElement('div');
a.id = 'a';
const aText = document.createTextNode('Alpha');
a.appendChild(aText);
const b = document.createElement('div');
b.id = 'b';
b.appendChild(document.createTextNode('Beta'));
container.appendChild(a);
container.appendChild(b);
await flush();
assert.equal(staged.isFailed(), false);
assert.equal(staged.snapshot().children.length, 2);
// Same-tick wrap: append wrapper and move b into it.
const wrapper = document.createElement('section');
wrapper.id = 'wrapper';
container.appendChild(wrapper);
wrapper.appendChild(b);
await flush();
assert.equal(staged.isFailed(), false);
const afterWrap = staged.snapshot();
assert.deepEqual(
afterWrap.children.map((node) => (node.type === 1 ? node.attributes.id : null)),
['a', 'wrapper'],
);
const [aNode, wrapperNode] = afterWrap.children;
assert.ok(aNode && aNode.type === 1, 'Expected sibling a first in host tree');
assert.ok(wrapperNode && wrapperNode.type === 1, 'Expected wrapper second in host tree');
assert.equal(aNode.children[0]?.type === 3 ? aNode.children[0].data : null, 'Alpha');
assert.deepEqual(
wrapperNode.children.map((node) => (node.type === 1 ? node.attributes.id : null)),
['b'],
);
const bNode = wrapperNode.children[0];
assert.ok(bNode && bNode.type === 1, 'Expected b inside wrapper');
assert.equal(bNode.children[0]?.type === 3 ? bNode.children[0].data : null, 'Beta');
// Desync gate: a subsequent text update to a must apply cleanly.
aText.data = 'Alpha updated';
await flush();
assert.equal(staged.isFailed(), false);
const afterText = staged.snapshot();
assert.deepEqual(
afterText.children.map((node) => (node.type === 1 ? node.attributes.id : null)),
['a', 'wrapper'],
);
const updatedANode = afterText.children[0];
assert.ok(updatedANode && updatedANode.type === 1);
assert.equal(updatedANode.children[0]?.type === 3 ? updatedANode.children[0].data : null, 'Alpha updated');
// Later turn: removing wrapper at index 1 must keep a and leave a updatable.
wrapper.remove();
await flush();
assert.equal(staged.isFailed(), false);
const afterRemove = staged.snapshot();
assert.deepEqual(
afterRemove.children.map((node) => (node.type === 1 ? node.attributes.id : null)),
['a'],
);
aText.data = 'Alpha after remove';
await flush();
assert.equal(staged.isFailed(), false);
const afterRemoveText = staged.snapshot();
const survivingANode = afterRemoveText.children[0];
assert.ok(survivingANode && survivingANode.type === 1);
assert.equal(survivingANode.children[0]?.type === 3 ? survivingANode.children[0].data : null, 'Alpha after remove');
assert.ok(batches.length >= 5);
} finally {
observer.disconnect();
for (const [key, value] of saved) {
if (value) Object.defineProperty(globalThis, key, value);
else Reflect.deleteProperty(globalThis, key);
}
dom.window.close();
}
});
test('rewriteDuplicateInsertBatch skips matched detaches and remaps subsequent producer removals', async () => {
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
const tree = createPluginRemoteTree();
tree.apply([
[0, '~', { id: '0', type: 1, element: 'div', attributes: { id: 'a' }, children: [{ id: '1', type: 3, data: 'Alpha' }] }, 0],
[0, '~', { id: '2', type: 1, element: 'div', attributes: { id: 'b' }, children: [{ id: '3', type: 3, data: 'Beta' }] }, 1],
]);
// Exact mutation batch from RemoteMutationObserver when appending wrapper and moving b into it.
const wrapped = tree.apply([
[0, '~', {
id: '4',
type: 1,
element: 'section',
attributes: { id: 'wrapper' },
children: [{ id: '2', type: 1, element: 'div', attributes: { id: 'b' }, children: [{ id: '3', type: 3, data: 'Beta' }] }],
}, 0],
[1, '~', 1],
]);
assert.equal(tree.isFailed(), false);
assert.deepEqual(wrapped.children.map((node) => node.id), ['0', '4']);
const wrapperNode = wrapped.children[1];
assert.equal(wrapperNode.type, 1);
if (wrapperNode.type === 1) {
assert.deepEqual(wrapperNode.children.map((node) => node.id), ['2']);
}
// Subsequent text update to a must still apply.
const updated = tree.apply([[2, '1', 'Alpha updated']]);
assert.equal(tree.isFailed(), false);
assert.deepEqual(updated.children[0], {
id: '0',
type: 1,
element: 'div',
attributes: { id: 'a' },
children: [{ id: '1', type: 3, data: 'Alpha updated' }],
});
// Later producer remove of wrapper at index 1 must remove wrapper and keep a alive.
const afterRemove = tree.apply([[1, '~', 1]]);
assert.equal(tree.isFailed(), false);
assert.deepEqual(afterRemove.children.map((node) => node.id), ['0']);
const afterRemoveUpdate = tree.apply([[2, '1', 'Alpha after remove']]);
assert.equal(tree.isFailed(), false);
assert.deepEqual(afterRemoveUpdate, {
children: [{
id: '0',
type: 1,
element: 'div',
attributes: { id: 'a' },
children: [{ id: '1', type: 3, data: 'Alpha after remove' }],
}],
});
// Producer remove at a larger index after a rewrite detach at a smaller index remaps to the right sibling.
const remapTree = createPluginRemoteTree();
remapTree.apply([
[0, '~', { id: 'a', type: 1, element: 'div', attributes: {}, children: [] }, 0],
[0, '~', { id: 'b', type: 1, element: 'div', attributes: {}, children: [{ id: 'b-text', type: 3, data: 'keep' }] }, 1],
[0, '~', { id: 'c', type: 1, element: 'div', attributes: {}, children: [] }, 2],
]);
const remapped = remapTree.apply([
[0, '~', { id: 'wrap', type: 1, element: 'section', attributes: {}, children: [{ id: 'a', type: 1, element: 'div', attributes: {}, children: [] }] }, 3],
// Producer removes c (original index 2) while a (index 0) was already detached by the rewrite.
[1, '~', 2],
// Producer then removes a at original index 0 (already detached -> skipped).
[1, '~', 0],
]);
assert.equal(remapTree.isFailed(), false);
assert.deepEqual(remapped.children.map((node) => node.id), ['b', 'wrap']);
const followUp = remapTree.apply([[2, 'b-text', 'still-alive']]);
assert.deepEqual(followUp.children[0], {
id: 'b',
type: 1,
element: 'div',
attributes: {},
children: [{ id: 'b-text', type: 3, data: 'still-alive' }],
});
});
+203 -6
View File
@@ -12,6 +12,174 @@ 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();
@@ -23,6 +191,16 @@ export function createPluginRemoteTree() {
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');
@@ -31,16 +209,35 @@ export function createPluginRemoteTree() {
// 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);
receiver.connection.mutate(batch as unknown as Parameters<typeof receiver.connection.mutate>[0]);
const next = { children: receiver.root.children.map(project) };
validatePluginRemoteTree(next);
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) {
failed = true;
current = { children: [] };
validatedTrees.add(current);
if (!isDuplicatePluginViewNodeError(error)) {
failed = true;
current = { children: [] };
validatedTrees.add(current);
}
throw error;
}
},
+277
View File
@@ -60,3 +60,280 @@ test('empty first update holds loading briefly to prevent blank-frame flash then
assert.equal(view.getSnapshot().loading, false, 'truly empty view finishes loading after grace window');
store.dispose();
});
test('update and event failures warn concisely with error message before disposing without logging event payloads', async () => {
const warns: unknown[][] = [];
const originalWarn = console.warn;
console.warn = (...args: unknown[]) => { warns.push(args); };
try {
const f1 = fixture();
const store = new PluginViewSessions();
const view1 = store.acquire('bad-seq', f1.bridge, request);
f1.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: f1.opened[0].instanceId, sequence: 99, css: '', mutations: [] });
assert.equal(view1.getSnapshot().error, true);
assert.equal(warns.length, 1);
assert.match(String(warns[0][0]), /Invalid plugin update order/);
assert.ok(warns[0][1] instanceof Error);
const f2 = fixture();
f2.bridge.sendHostDrawnPluginViewEvent = async () => { throw new Error('IPC channel closed'); };
const view2 = store.acquire('bad-send', f2.bridge, request);
view2.send({ type: 'input', nodeId: 'field', value: 'secret@example.com' });
await Promise.resolve();
assert.equal(view2.getSnapshot().error, true);
assert.equal(warns.length, 2);
assert.match(String(warns[1][0]), /IPC channel closed/);
assert.doesNotMatch(warns[1].map(String).join(' '), /secret@example\.com/);
store.dispose();
} finally {
console.warn = originalWarn;
}
});
test('recoverable duplicate node update applies as a move and publishes the new tree without warning', () => {
const warns: unknown[][] = [];
const originalWarn = console.warn;
console.warn = (...args: unknown[]) => { warns.push(args); };
try {
const f = fixture();
const store = new PluginViewSessions();
const view = store.acquire('dup-move', f.bridge, request);
const id = f.opened[0].instanceId;
const initialNode = {
id: 'row-1',
type: 1 as const,
element: 'div',
attributes: { class: 'row' },
children: [{ id: 'cell-1', type: 3 as const, data: 'alpha' }],
};
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.row{display:flex}', mutations: [[0, '~', initialNode, 0]] });
assert.equal(view.getSnapshot().loading, false);
assert.equal(view.getSnapshot().error, false);
assert.deepEqual(view.getSnapshot().tree.children, [initialNode]);
// Re-inserting an existing node (or wrapping it in a new parent without a remove)
// is normalized as a move and published immediately with zero warnings.
const movedNode = {
id: 'group-1',
type: 1 as const,
element: 'section',
attributes: { class: 'sorted' },
children: [{
id: 'row-1',
type: 1 as const,
element: 'div',
attributes: { class: 'row' },
children: [{ id: 'cell-1', type: 3 as const, data: 'alpha' }],
}],
};
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 2,
css: '.sorted{color:blue}',
mutations: [[0, '~', movedNode, 1]],
} as Update);
assert.equal(warns.length, 0);
assert.equal(view.getSnapshot().error, false);
assert.equal(view.getSnapshot().css.includes('blue'), true);
assert.deepEqual(view.getSnapshot().tree.children, [movedNode]);
assert.equal(f.closes.length, 0);
assert.equal(store.peek('dup-move'), view);
// A subsequent incremental update applies cleanly against the moved nodes.
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 3,
css: '',
cssUnchanged: true,
mutations: [
[2, 'cell-1', 'beta'],
[0, '~', { id: 'row-2', type: 3, data: 'second' }, 1],
],
} as Update);
assert.equal(warns.length, 0);
assert.equal(view.getSnapshot().error, false);
assert.deepEqual(view.getSnapshot().tree.children, [
{
...movedNode,
children: [{ ...initialNode, children: [{ id: 'cell-1', type: 3, data: 'beta' }] }],
},
{ id: 'row-2', type: 3, data: 'second' },
]);
// Forbidden mutations still dispose the session.
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 4,
css: '',
cssUnchanged: true,
mutations: [[3, 'row-1', 'onclick', 'attack()']],
} as Update);
assert.equal(view.getSnapshot().error, true);
assert.deepEqual(view.getSnapshot().tree.children, []);
store.dispose();
} finally {
console.warn = originalWarn;
}
});
test('unrecoverable duplicate node update warns without failing the session and accepts subsequent valid updates', () => {
const warns: unknown[][] = [];
const originalWarn = console.warn;
console.warn = (...args: unknown[]) => { warns.push(args); };
try {
const f = fixture();
const store = new PluginViewSessions();
const view = store.acquire('dup-recovery', f.bridge, request);
const id = f.opened[0].instanceId;
const initialNode = {
id: 'row-1',
type: 1 as const,
element: 'div',
attributes: { class: 'row' },
children: [{ id: 'cell-1', type: 3 as const, data: 'alpha' }],
};
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.row{display:flex}', mutations: [[0, '~', initialNode, 0]] });
assert.equal(view.getSnapshot().loading, false);
assert.equal(view.getSnapshot().error, false);
assert.deepEqual(view.getSnapshot().tree.children, [initialNode]);
// Self-nesting cycle cannot be rewritten as a move; last-resort fallback preserves last good tree.
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 2,
css: '',
cssUnchanged: true,
mutations: [[0, 'row-1', { id: 'row-1', type: 1, element: 'div', attributes: {}, children: [] }, 0]],
} as Update);
assert.equal(warns.length, 1);
assert.match(String(warns[0][0]), /Duplicate view node/);
assert.equal(view.getSnapshot().error, false);
assert.deepEqual(view.getSnapshot().tree.children, [initialNode]);
assert.equal(f.closes.length, 0);
assert.equal(store.peek('dup-recovery'), view);
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 3,
css: '',
cssUnchanged: true,
mutations: [
[2, 'cell-1', 'beta'],
[0, '~', { id: 'row-2', type: 3, data: 'second' }, 1],
],
} as Update);
assert.equal(view.getSnapshot().error, false);
assert.deepEqual(view.getSnapshot().tree.children, [
{ ...initialNode, children: [{ id: 'cell-1', type: 3, data: 'beta' }] },
{ id: 'row-2', type: 3, data: 'second' },
]);
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 4,
css: '',
cssUnchanged: true,
mutations: [[3, 'row-1', 'onclick', 'attack()']],
} as Update);
assert.equal(view.getSnapshot().error, true);
assert.deepEqual(view.getSnapshot().tree.children, []);
store.dispose();
} finally {
console.warn = originalWarn;
}
});
test('pending CSS from a rejected unrecoverable duplicate update is published on the next accepted update', () => {
const originalWarn = console.warn;
console.warn = () => {};
try {
const f = fixture();
const store = new PluginViewSessions();
const view = store.acquire('css-pending', f.bridge, request);
const id = f.opened[0].instanceId;
const node = { id: 'row-1', type: 1 as const, element: 'div', attributes: { class: 'row' }, children: [] };
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.row{color:red}', mutations: [[0, '~', node, 0]] });
assert.equal(view.getSnapshot().css.includes('red'), true);
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 2,
css: '.row{color:blue}',
mutations: [[0, 'row-1', { id: 'row-1', type: 1, element: 'span', attributes: {}, children: [] }, 0]],
} as Update);
assert.equal(view.getSnapshot().error, false);
assert.equal(view.getSnapshot().css.includes('red'), true, 'rejected update does not publish CSS immediately');
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 3,
css: '',
cssUnchanged: true,
mutations: [[3, 'row-1', 'class', 'ready']],
} as Update);
assert.equal(view.getSnapshot().error, false);
assert.equal(view.getSnapshot().css.includes('blue'), true, 'next accepted update publishes the stashed CSS');
store.dispose();
} finally {
console.warn = originalWarn;
}
});
test('explicit CSS matching the last committed value supersedes pending CSS', () => {
const originalWarn = console.warn;
console.warn = () => {};
try {
const f = fixture();
const store = new PluginViewSessions();
const view = store.acquire('css-supersede', f.bridge, request);
const id = f.opened[0].instanceId;
const node = { id: 'row-1', type: 1 as const, element: 'div', attributes: { class: 'row' }, children: [] };
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.row{color:red}', mutations: [[0, '~', node, 0]] });
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 2,
css: '.row{color:blue}',
mutations: [[0, 'row-1', { id: 'row-1', type: 1, element: 'span', attributes: {}, children: [] }, 0]],
} as Update);
assert.equal(view.getSnapshot().css.includes('red'), true);
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 3,
css: '.row{color:red}',
mutations: [[3, 'row-1', 'class', 'ready']],
} as Update);
assert.equal(view.getSnapshot().error, false);
assert.equal(view.getSnapshot().css.includes('blue'), false);
assert.equal(view.getSnapshot().css.includes('red'), true, 'explicit red supersedes pending blue');
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 4,
css: '',
cssUnchanged: true,
mutations: [[3, 'row-1', 'class', 'again']],
} as Update);
assert.equal(view.getSnapshot().css.includes('red'), true);
assert.equal(view.getSnapshot().css.includes('blue'), false);
store.dispose();
} finally {
console.warn = originalWarn;
}
});
+39 -8
View File
@@ -1,4 +1,4 @@
import { createPluginRemoteTree } from './pluginRemoteTree';
import { createPluginRemoteTree, isDuplicatePluginViewNodeError } from './pluginRemoteTree';
import { registerLoadedPluginViewSessions } from './pluginViewSessionRegistry';
import { validatePluginStylesheet } from '@/domain/pluginViewStylePolicy.cjs';
import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
@@ -27,6 +27,8 @@ export class PluginViewSessions {
const tree = createPluginRemoteTree();
let state = empty(); let sequence = 1; let eventId = 0; let disposed = false; let users = 0;
let lastRawCss: string | null = null;
let pendingCss: string | null = null;
let pendingRawCss: string | null = null;
let timer: ReturnType<typeof setTimeout> | undefined;
let emptyFrameTimer: ReturnType<typeof setTimeout> | undefined;
const listeners = new Set<() => void>();
@@ -42,14 +44,26 @@ export class PluginViewSessions {
if (!bridge.openHostDrawnPluginView || !bridge.onHostDrawnPluginViewUpdate || !bridge.onPluginViewClosed) throw new Error('Plugin views unavailable');
cleanup.push(bridge.onHostDrawnPluginViewUpdate((update) => {
if (disposed || update.kind !== 'host-ui.update' || update.instanceId !== id || update.viewId !== request.viewId) return;
let stagedCss: string | null = null;
let stagedRawCss: string | null = null;
try {
if (update.sequence !== sequence++) throw new Error('Invalid plugin update order');
const nextCss = update.cssUnchanged
? state.css
: (lastRawCss !== null && update.css === lastRawCss)
? state.css
: ((lastRawCss = update.css), validatePluginStylesheet(update.css));
if (update.cssUnchanged) {
// keep pending CSS, if any, for the nextCss fallback below
} else if (lastRawCss !== null && update.css === lastRawCss) {
// Explicit CSS equal to the last committed raw CSS supersedes any pending stylesheet.
pendingCss = null;
pendingRawCss = null;
} else {
stagedCss = validatePluginStylesheet(update.css);
stagedRawCss = update.css;
}
const nextCss = stagedCss ?? pendingCss ?? state.css;
const nextTree = tree.apply(update.mutations);
if (stagedRawCss !== null) lastRawCss = stagedRawCss;
else if (pendingRawCss !== null) lastRawCss = pendingRawCss;
pendingCss = null;
pendingRawCss = null;
const settled = (update.acknowledgedEvent ?? 0) >= eventId;
if (state.loading && !hasRenderableTreeContent(nextTree)) {
// Hold the host loading surface briefly while an older SDK flushes its
@@ -68,7 +82,20 @@ export class PluginViewSessions {
emptyFrameTimer = undefined;
}
publish({ tree: nextTree, css: nextCss, loading: false, error: false, settled });
} catch { dispose(true); }
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.warn(`[PluginViewSession] Failed to apply update for ${request.viewId}: ${message}`, error);
// Recoverable duplicate-only batches are normalized as moves in
// createPluginRemoteTree(); only unrecoverable duplicates reach here.
if (isDuplicatePluginViewNodeError(error)) {
if (stagedCss !== null && stagedRawCss !== null) {
pendingCss = stagedCss;
pendingRawCss = stagedRawCss;
}
return;
}
dispose(true);
}
}));
cleanup.push(bridge.onPluginViewClosed((event) => { if (event.instanceId === id) dispose(true); }));
void bridge.openHostDrawnPluginView({ ...request, instanceId: id }).then(() => {
@@ -100,7 +127,11 @@ export class PluginViewSessions {
send: (event: HostDrawnViewEvent) => {
if (disposed || users === 0) return;
publish({ ...state, settled: false });
void bridge.sendHostDrawnPluginViewEvent?.(id, { ...event, eventId: ++eventId }).catch(() => dispose(true));
void bridge.sendHostDrawnPluginViewEvent?.(id, { ...event, eventId: ++eventId }).catch((error) => {
const message = error instanceof Error ? error.message : String(error);
console.warn(`[PluginViewSession] Failed to send event for ${request.viewId}: ${message}`);
dispose(true);
});
},
dispose,
};
+15 -1
View File
@@ -16,5 +16,19 @@ export const useClipboardBackend = () => {
return await bridge.writeClipboardText(text) === true;
}, []);
return { readClipboardText, writeClipboardText };
const readClipboardImagePng = useCallback(async (): Promise<Uint8Array | null> => {
const bridge = netcattyBridge.get();
if (bridge?.readClipboardImagePng) return await bridge.readClipboardImagePng();
// Browser fallback when the native clipboard bridge is unavailable.
const items = await navigator.clipboard?.read();
for (const item of items ?? []) {
if (!item.types.includes("image/png")) continue;
const blob = await item.getType("image/png");
return new Uint8Array(await blob.arrayBuffer());
}
return null;
}, []);
return { readClipboardText, writeClipboardText, readClipboardImagePng };
};
+8 -2
View File
@@ -39,7 +39,11 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
try {
const session = pluginViewSessions.acquire(JSON.stringify([resolvedScopeId, key]), bridge, { viewId, scopeId: resolvedScopeId, context: JSON.parse(contextKey) });
sessionRef.current = { key, send: session.send, image: session.image };
const update = () => { const snapshot = session.getSnapshot(); setState({ key, snapshot, image: session.image }); if (snapshot.error) unavailableRef.current(); };
const update = () => {
const snapshot = session.getSnapshot();
if (snapshot.error) sessionRef.current = null;
setState({ key, snapshot, image: session.image });
};
const stop = session.subscribe(update); update(); setHidden(false);
const stopHidden = subscribeHidden(() => { sessionRef.current = null; setHidden(true); });
return () => { sessionRef.current = null; stopHidden(); stop(); session.release(); };
@@ -49,7 +53,9 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
const session = sessionRef.current;
return active && session?.key === key ? session.image(path) : Promise.reject(new Error('Plugin view unavailable'));
}, [active, key]);
const hasCurrentState = active && state.key === key && cachedSession !== null && state.image === cachedSession.image;
const hasCurrentState = active
&& state.key === key
&& (cachedSession !== null ? state.image === cachedSession.image : state.snapshot.error);
const resolvedSnapshot = hasCurrentState
? state.snapshot
: cachedSession
+88
View File
@@ -82,3 +82,91 @@ test('Vault navigation mounts a real content slot, yields to host dialogs, and w
for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); }
}
});
test('Failed host-drawn view session stays on the plugin vault page with error and retry instead of falling back to Hosts', async () => {
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', { pretendToBeVisual: true, url: 'http://localhost' });
const previous = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'MutationObserver', 'CustomEvent', 'Event']) {
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: key === 'window' ? dom.window : dom.window[key as keyof Window] });
}
for (const [key, value] of Object.entries({ getComputedStyle: dom.window.getComputedStyle.bind(dom.window),
requestAnimationFrame: dom.window.requestAnimationFrame.bind(dom.window), cancelAnimationFrame: dom.window.cancelAnimationFrame.bind(dom.window), IS_REACT_ACT_ENVIRONMENT: true })) {
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key)); Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
}
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({ x: 200, y: 100, width: 640, height: 480, top: 100, left: 200, right: 840, bottom: 580, toJSON() {} });
const { act, useState } = await import('react');
const { createRoot } = await import('react-dom/client');
const { usePluginVaultPages } = await import('../application/state/usePluginVaultPages');
const { PluginVaultNavigation, PluginVaultPage } = await import('./plugins/PluginVaultPages');
const { activeTabStore } = await import('../application/state/activeTabStore');
const { I18nProvider } = await import('../application/i18n/I18nProvider');
const page = { id: 'com.example.page.main', title: 'Synthetic page', location: 'vault-page', visible: true };
let snapshot = { locale: 'en', plugins: [{ id: 'com.example.page', version: '1.0.0', displayName: 'Synthetic plugin', commands: [], keybindings: [], menus: [], settings: [], views: [page] }] };
let changed: (() => void) | undefined;
const listeners = new Set<(event: NetcattyPluginViewClosedEvent) => void>();
const opens: NetcattyPluginViewOpenRequest[] = [], closes: string[] = [];
Object.assign(dom.window, { netcatty: {
async getPluginRuntimeStatus() { return { available: true }; },
async getPluginContributions() { return snapshot; },
onPluginContributionsChanged(fn: () => void) { changed = fn; return () => { changed = undefined; }; },
onPluginViewClosed(fn: (event: NetcattyPluginViewClosedEvent) => void) { listeners.add(fn); return () => { listeners.delete(fn); }; },
onHostDrawnPluginViewUpdate() { return () => {}; },
async openHostDrawnPluginView(payload: NetcattyPluginViewOpenRequest) { opens.push(payload); return { instanceId: payload.instanceId! }; },
async closeHostDrawnPluginView(id: string) { closes.push(id); },
} });
function Fixture() {
const [section, select] = useState<'hosts' | `plugin-vault:${string}`>('hosts');
const model = usePluginVaultPages({ locale: 'en', section, select });
return <><aside><button data-plugin-vault-fallback onClick={() => select('hosts')}>Hosts</button><PluginVaultNavigation model={model} collapsed={false} /></aside>
<main data-section="vault-main">{model.selected ? <PluginVaultPage key={model.selected.key} model={model} /> : <p>Built-in hosts</p>}</main></>;
}
const root = createRoot(document.getElementById('root')!);
const settle = () => new Promise((resolve) => setTimeout(resolve, 35));
try {
activeTabStore.setActiveTabId('vault');
await act(async () => { root.render(<I18nProvider locale="en"><Fixture /></I18nProvider>); await settle(); });
await act(async () => {
document.querySelector<HTMLButtonElement>('button[aria-label="Synthetic page — Synthetic plugin"]')!.click();
await import('./plugins/PluginHostDrawnPage');
await settle();
});
assert.equal(opens.length, 1);
assert.ok(document.querySelector('[data-plugin-vault-page]'));
// Session fails while plugin contribution remains active.
await act(async () => {
for (const listener of listeners) {
listener({ instanceId: opens[0].instanceId!, viewId: page.id, pluginId: 'com.example.page', reason: 'view-error' });
}
await settle();
});
assert.ok(document.querySelector('[data-plugin-vault-page]'), 'stays on the plugin vault page');
assert.doesNotMatch(document.querySelector('main')!.textContent!, /Built-in hosts/);
assert.equal(document.querySelector('[data-plugin-remote-surface]'), null, 'does not render an empty remote surface');
const alert = document.querySelector('[data-plugin-vault-page] [role="alert"]');
assert.ok(alert, 'renders in-page error alert');
assert.equal(alert!.textContent, 'The plugin page failed to render.');
const retryButton = [...document.querySelectorAll<HTMLButtonElement>('[data-plugin-vault-page] button')]
.find((btn) => btn.textContent === 'Retry');
assert.ok(retryButton, 'renders Retry control');
await act(async () => {
retryButton!.click();
await settle();
});
assert.equal(opens.length, 2, 'clicking Retry opens a new host-drawn plugin view session');
assert.notEqual(opens[1].instanceId, opens[0].instanceId);
assert.equal(document.querySelector('[data-plugin-vault-page] [role="alert"]'), null);
// Removing the contribution still falls back to Hosts.
await act(async () => { snapshot = { ...snapshot, plugins: [] }; changed?.(); await settle(); });
await act(async () => { await settle(); });
assert.equal(document.querySelector('[data-plugin-vault-page]'), null);
assert.match(document.querySelector('main')!.textContent!, /Built-in hosts/);
} finally {
await act(async () => { root.unmount(); (await import('../application/state/pluginViewSession')).pluginViewSessions.dispose(); await settle(); }); dom.window.close();
for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); }
}
});
+35 -3
View File
@@ -1,4 +1,7 @@
import { useCallback, useState } from 'react';
import { useI18n } from '../../application/i18n/I18nProvider';
import { useHostDrawnPluginView } from '../../application/state/useHostDrawnPluginView';
import { Button } from '../ui/button';
import { PluginViewLoadingSurface } from './LazyPluginHostDrawnPage';
import { PluginSettingsEntry } from './PluginSettingsEntry';
import { PluginRemoteSurface } from './PluginRemoteSurface';
@@ -30,12 +33,33 @@ function hasFullBleedChrome(tree: unknown): boolean {
return check(children, 0);
}
export function PluginHostDrawnPage(props: PluginHostDrawnPageProps) {
function PluginHostDrawnPageSession({
onRetry,
...props
}: PluginHostDrawnPageProps & { onRetry: () => void }) {
const { t } = useI18n();
const view = useHostDrawnPluginView(props);
if (!view.visible) return null;
if (view.loading) return <PluginViewLoadingSurface slot={props.slot.split(':')[0]} loadingLabel={props.loadingLabel} />;
const slotName = props.slot.split(':')[0];
if (view.loading) return <PluginViewLoadingSurface slot={slotName} loadingLabel={props.loadingLabel} />;
if (view.error) {
return (
<div
className="relative isolate flex h-full min-h-0 w-full flex-1 flex-col items-center justify-center gap-3 bg-background p-6 text-center"
data-plugin-view-slot={slotName}
data-plugin-view-error=""
>
<p role="alert" className="text-sm text-destructive">
{t('plugins.vault.viewError')}
</p>
<Button type="button" variant="outline" size="sm" onClick={onRetry}>
{t('plugins.vault.retry')}
</Button>
</div>
);
}
const fullBleed = hasFullBleedChrome(view.tree);
return <div className="relative isolate h-full min-h-0 w-full flex-1" data-plugin-view-slot={props.slot.split(':')[0]} data-plugin-chrome={fullBleed ? 'full-bleed' : undefined}>
return <div className="relative isolate h-full min-h-0 w-full flex-1" data-plugin-view-slot={slotName} data-plugin-chrome={fullBleed ? 'full-bleed' : undefined}>
<PluginRemoteSurface key={`${props.viewId}:${props.version}:${props.slot}`} tree={view.tree} css={view.css} settled={view.settled} loadImage={view.loadImage} onEvent={view.sendEvent} />
{!fullBleed && (
<div className="absolute right-3 top-3 z-10" data-plugin-settings-entry="">
@@ -44,3 +68,11 @@ export function PluginHostDrawnPage(props: PluginHostDrawnPageProps) {
)}
</div>;
}
export function PluginHostDrawnPage(props: PluginHostDrawnPageProps) {
const [generation, setGeneration] = useState(0);
const handleRetry = useCallback(() => {
setGeneration((n) => n + 1);
}, []);
return <PluginHostDrawnPageSession key={generation} {...props} onRetry={handleRetry} />;
}
@@ -0,0 +1,184 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { JSDOM } from 'jsdom';
function installDom() {
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', {
pretendToBeVisual: true,
url: 'http://localhost',
});
const previous = new Map<string, PropertyDescriptor | undefined>();
const install = (key: string, value: unknown) => {
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
};
for (const key of [
'window',
'document',
'navigator',
'HTMLElement',
'HTMLButtonElement',
'HTMLInputElement',
'Element',
'SVGElement',
'Node',
'NodeFilter',
'MutationObserver',
'CustomEvent',
'Event',
'KeyboardEvent',
'MouseEvent',
]) {
install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]);
}
class MockResizeObserver {
private cb: (entries: unknown[]) => void;
constructor(cb: (entries: unknown[]) => void) {
this.cb = cb;
}
observe(target: Element) {
this.cb([
{
target,
borderBoxSize: [{ inlineSize: 960, blockSize: 420 }],
contentRect: { width: 960, height: 420 },
},
]);
}
unobserve() {}
disconnect() {}
}
Object.assign(dom.window, {
PointerEvent: dom.window.MouseEvent,
ResizeObserver: MockResizeObserver,
});
install('PointerEvent', dom.window.MouseEvent);
install('ResizeObserver', MockResizeObserver);
install('getComputedStyle', dom.window.getComputedStyle.bind(dom.window));
install('requestAnimationFrame', dom.window.requestAnimationFrame.bind(dom.window));
install('cancelAnimationFrame', dom.window.cancelAnimationFrame.bind(dom.window));
install('IS_REACT_ACT_ENVIRONMENT', true);
dom.window.HTMLElement.prototype.getBoundingClientRect = () => new dom.window.DOMRect(0, 0, 960, 420);
return {
dom,
cleanup() {
dom.window.close();
for (const [key, descriptor] of previous) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
},
};
}
test('PluginDataGrid header clicks toggle sort on single clicks, ignore double-click second click, and skip non-sortable columns', async () => {
const env = installDom();
const { act, useState } = await import('react');
const { createRoot } = await import('react-dom/client');
const { PluginDataGrid, SORT_CLICK_DEBOUNCE_MS } = await import('./PluginDataGrid');
type SortState = { column: string; direction: 'asc' | 'desc' } | null;
const events: Array<{ name: string; detail?: Record<string, unknown> }> = [];
let resetSort!: () => void;
function ControlledGrid() {
const [sort, setSort] = useState<SortState>(null);
resetSort = () => setSort(null);
return (
<PluginDataGrid
columns={[
{ name: 'email', type: 'varchar' },
{ name: 'payload', type: 'jsonb', sortable: false },
]}
rows={[
{ email: 'alice@example.com', payload: '{}' },
{ email: 'bob@example.com', payload: '{}' },
]}
sort={sort}
onWidgetEvent={(name, detail) => {
events.push({ name, detail });
if (name === 'sortChange' && detail) {
setSort({
column: String(detail.column),
direction: detail.direction === 'desc' ? 'desc' : 'asc',
});
}
}}
/>
);
}
const root = createRoot(document.getElementById('root')!);
try {
await act(async () => {
root.render(<ControlledGrid />);
});
const emailBtn = document.querySelector<HTMLButtonElement>('[role="columnheader"][data-col-name="email"] button');
const payloadBtn = document.querySelector<HTMLButtonElement>('[role="columnheader"][data-col-name="payload"] button');
assert.ok(emailBtn, 'sortable email header button mounted');
assert.ok(payloadBtn, 'non-sortable payload header button mounted');
assert.equal(payloadBtn.disabled, true);
// 1. Single click (detail 1) -> asc; immediate second detail=1 click is debounced
await act(async () => {
emailBtn.dispatchEvent(new env.dom.window.MouseEvent('click', { bubbles: true, cancelable: true, detail: 1 }));
});
assert.deepEqual(events, [
{ name: 'sortChange', detail: { column: 'email', direction: 'asc' } },
]);
await act(async () => {
emailBtn.dispatchEvent(new env.dom.window.MouseEvent('click', { bubbles: true, cancelable: true, detail: 1 }));
});
assert.deepEqual(events, [
{ name: 'sortChange', detail: { column: 'email', direction: 'asc' } },
]);
// 2. Genuine later single click after debounce window (detail 1) -> desc
await new Promise((resolve) => setTimeout(resolve, SORT_CLICK_DEBOUNCE_MS + 30));
await act(async () => {
emailBtn.dispatchEvent(new env.dom.window.MouseEvent('click', { bubbles: true, cancelable: true, detail: 1 }));
});
assert.deepEqual(events, [
{ name: 'sortChange', detail: { column: 'email', direction: 'asc' } },
{ name: 'sortChange', detail: { column: 'email', direction: 'desc' } },
]);
// 3. Double-click sequence: click (detail 1), click (detail 2), dblclick -> only one sortChange total
await new Promise((resolve) => setTimeout(resolve, SORT_CLICK_DEBOUNCE_MS + 30));
events.length = 0;
await act(async () => {
resetSort();
});
let dblClickBubbled = false;
document.body.addEventListener('dblclick', () => {
dblClickBubbled = true;
}, { once: true });
const dblClickEvent = new env.dom.window.MouseEvent('dblclick', { bubbles: true, cancelable: true, detail: 2 });
await act(async () => {
emailBtn.dispatchEvent(new env.dom.window.MouseEvent('click', { bubbles: true, cancelable: true, detail: 1 }));
emailBtn.dispatchEvent(new env.dom.window.MouseEvent('click', { bubbles: true, cancelable: true, detail: 2 }));
emailBtn.dispatchEvent(dblClickEvent);
});
assert.deepEqual(events, [
{ name: 'sortChange', detail: { column: 'email', direction: 'asc' } },
]);
assert.equal(dblClickEvent.defaultPrevented, true, 'header dblclick should preventDefault');
assert.equal(dblClickBubbled, false, 'header dblclick should not bubble out');
// 4. Non-sortable column emits nothing
events.length = 0;
await act(async () => {
payloadBtn.click();
payloadBtn.dispatchEvent(new env.dom.window.MouseEvent('click', { bubbles: true, cancelable: true, detail: 1 }));
});
assert.deepEqual(events, []);
} finally {
await act(async () => {
root.unmount();
});
env.cleanup();
}
});
@@ -15,6 +15,7 @@ const GUTTER_WIDTH = 64;
const DEFAULT_COL_WIDTH = 156;
const MIN_COL_WIDTH = 68;
const MAX_COL_WIDTH = 640;
export const SORT_CLICK_DEBOUNCE_MS = 500;
export interface PluginDataGridProps extends PluginDataGridWidgetProps {
onWidgetEvent: PluginWidgetEventCallback;
@@ -60,6 +61,7 @@ export function PluginDataGrid({
const scrollRef = useRef<HTMLDivElement>(null);
const editInputRef = useRef<HTMLInputElement>(null);
const blurTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const lastSortClickAtRef = useRef<number | null>(null);
const [colWidths, setColWidths] = useState<Record<string, number>>({});
const [activeCell, setActiveCell] = useState<{ rowIndex: number; colIndex: number } | null>(null);
@@ -223,8 +225,18 @@ export function PluginDataGrid({
onWidgetEvent('rowSelect', { selectedRowIndices: next });
}, [totalRows, selectedSet.size, onWidgetEvent]);
const handleSortClick = useCallback((col: PluginDataGridColumn) => {
const handleSortClick = useCallback((col: PluginDataGridColumn, event?: React.MouseEvent<HTMLButtonElement>) => {
if (col.sortable === false) return;
if (event && event.detail > 1) return;
const now = Date.now();
if (
lastSortClickAtRef.current !== null &&
now >= lastSortClickAtRef.current &&
now - lastSortClickAtRef.current < SORT_CLICK_DEBOUNCE_MS
) {
return;
}
lastSortClickAtRef.current = now;
const nextDirection = sort?.column === col.name && sort.direction === 'asc' ? 'desc' : 'asc';
onWidgetEvent('sortChange', { column: col.name, direction: nextDirection });
}, [sort, onWidgetEvent]);
@@ -452,7 +464,11 @@ export function PluginDataGrid({
<button
type="button"
disabled={!sortable}
onClick={() => handleSortClick(col)}
onClick={(event) => handleSortClick(col, event)}
onDoubleClick={(event) => {
event.preventDefault();
event.stopPropagation();
}}
className={`flex min-w-0 flex-1 items-center gap-1.5 text-left ${sortable ? 'cursor-pointer hover:text-primary' : 'cursor-default'}`}
title={col.foreignKey
? `${col.name}${col.type ? ` (${col.type})` : ''} -> ${col.foreignKey.schema ? `${col.foreignKey.schema}.` : ''}${col.foreignKey.table}.${col.foreignKey.column}`
+37 -20
View File
@@ -9,6 +9,8 @@ import React, {
} from 'react';
import { AlertCircle, UploadCloud } from 'lucide-react';
import { useI18n } from '../../application/i18n/I18nProvider';
import { useClipboardBackend } from '../../application/state/useClipboardBackend';
import { buildRdpClipboardItemData, nextRdpClipboardGuardState, selectRdpClipboardData } from '../../domain/rdpClipboard';
import {
computeMonitorVirtualBounds,
mapViewportToVirtualDesktopCoords,
@@ -186,6 +188,7 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
ref,
) {
const { t } = useI18n();
const { readClipboardImagePng } = useClipboardBackend();
const containerRef = useRef<HTMLDivElement | null>(null);
const viewportRef = useRef<HTMLDivElement | null>(null);
const canvasRef = useRef<HTMLCanvasElement | null>(null);
@@ -199,7 +202,9 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
const modRef = useRef<IronRdpModule | null>(null);
const audioPlayerRef = useRef<RdpAudioPlayer | null>(null);
const lastAltRightUpRef = useRef(0);
const lastRemoteClipboardTextRef = useRef('');
const lastClipboardGuardStateRef = useRef<ReturnType<typeof nextRdpClipboardGuardState>>({
lastText: '', lastPngFingerprint: null,
});
const uploadedFilesRef = useRef<File[]>([]);
const uploadTransferIdRef = useRef<string>('');
const uploadedHighWaterByIndexRef = useRef<Map<number, number>>(new Map());
@@ -601,21 +606,31 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
const mod = modRef.current;
if (!session || !mod) return;
try {
const text = await navigator.clipboard?.readText();
if (text && (force || text !== lastRemoteClipboardTextRef.current)) {
lastRemoteClipboardTextRef.current = text;
const data = new mod.ClipboardData();
try {
data.addText('text/plain', text);
await session.onClipboardPaste(data);
} finally {
try { data.free(); } catch { /* ignore */ }
}
// A denied or unsupported read of one format must not block the other.
const [textResult, pngResult] = await Promise.allSettled([
Promise.resolve().then(() => navigator.clipboard?.readText()),
readClipboardImagePng(),
]);
const { text, pngBytes } = selectRdpClipboardData({
text: textResult.status === 'fulfilled' ? textResult.value : null,
pngBytes: pngResult.status === 'fulfilled' ? pngResult.value : null,
...lastClipboardGuardStateRef.current,
force,
});
if (!text && !pngBytes) return;
const data = new mod.ClipboardData();
try {
if (text) data.addText('text/plain', text);
if (pngBytes) data.addBinary('image/png', pngBytes);
await session.onClipboardPaste(data);
lastClipboardGuardStateRef.current = nextRdpClipboardGuardState({ text, pngBytes });
} finally {
try { data.free(); } catch { /* ignore */ }
}
} catch {
// Clipboard permission or empty
}
}, []);
}, [readClipboardImagePng]);
const syncClipboardNow = useCallback(() => syncLocalClipboardToRdp(true), [syncLocalClipboardToRdp]);
@@ -1168,18 +1183,20 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
pngBytes = val;
}
}
lastClipboardGuardStateRef.current = nextRdpClipboardGuardState({ text: plainText, pngBytes });
if (pngBytes && typeof ClipboardItem !== 'undefined' && navigator.clipboard?.write) {
const pngCopy = new Uint8Array(pngBytes.byteLength);
pngCopy.set(pngBytes);
const blob = new Blob([pngCopy], { type: 'image/png' });
void navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]).catch(() => {
if (plainText) {
lastRemoteClipboardTextRef.current = plainText;
void navigator.clipboard?.writeText(plainText).catch(() => {});
const data = buildRdpClipboardItemData({ text: plainText, pngBytes });
void navigator.clipboard.write([new ClipboardItem(data)]).catch(async () => {
if (plainText !== null) {
// Some clipboards reject mixed formats; keep the PNG if possible.
try {
await navigator.clipboard.write([new ClipboardItem({ 'image/png': data['image/png'] })]);
} catch {
await navigator.clipboard?.writeText(plainText).catch(() => {});
}
}
});
} else if (plainText !== null) {
lastRemoteClipboardTextRef.current = plainText;
void navigator.clipboard?.writeText(plainText).catch(() => {});
}
} catch {
+157
View File
@@ -0,0 +1,157 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { buildRdpClipboardItemData, fingerprintRdpClipboardPng, nextRdpClipboardGuardState, selectRdpClipboardData } from './rdpClipboard';
const pngBytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47]);
const emptyState = { lastText: '', lastPngFingerprint: null };
test('mixed remote clipboard data preserves both local formats and does not echo on refocus', async () => {
const snapshot = { text: 'caption', pngBytes };
const data = buildRdpClipboardItemData(snapshot);
assert.deepEqual(Object.keys(data).sort(), ['image/png', 'text/plain']);
assert.equal(data['image/png'].type, 'image/png');
assert.equal(data['text/plain'].type, 'text/plain');
const localSnapshot = {
text: await data['text/plain'].text(),
pngBytes: new Uint8Array(await data['image/png'].arrayBuffer()),
};
assert.deepEqual(localSnapshot, snapshot);
assert.deepEqual(selectRdpClipboardData({
...nextRdpClipboardGuardState(snapshot),
...localSnapshot,
}), { text: null, pngBytes: null, pngFingerprint: null });
});
test('local clipboard item data preserves image-only, text-only and empty text formats', async () => {
const imageData = buildRdpClipboardItemData({ text: null, pngBytes });
assert.deepEqual(Object.keys(imageData), ['image/png']);
assert.deepEqual(new Uint8Array(await imageData['image/png'].arrayBuffer()), pngBytes);
for (const text of ['hello', '']) {
const textData = buildRdpClipboardItemData({ text, pngBytes: null });
assert.deepEqual(Object.keys(textData), ['text/plain']);
assert.equal(await textData['text/plain'].text(), text);
}
});
test('image-only RDP clipboard data is sent', () => {
assert.deepEqual(selectRdpClipboardData({ ...emptyState, text: '', pngBytes }), {
text: null,
pngBytes,
pngFingerprint: fingerprintRdpClipboardPng(pngBytes),
});
});
test('the last pushed or received PNG is skipped unless forced', () => {
const input = {
...emptyState,
text: null,
pngBytes: new Uint8Array(pngBytes),
lastPngFingerprint: fingerprintRdpClipboardPng(pngBytes),
};
assert.equal(selectRdpClipboardData(input).pngBytes, null);
assert.deepEqual(selectRdpClipboardData({ ...input, force: true }).pngBytes, pngBytes);
assert.notEqual(fingerprintRdpClipboardPng(new Uint8Array([1, 2, 3, 4])), input.lastPngFingerprint);
});
test('text-only RDP clipboard behavior is unchanged', () => {
const input = { ...emptyState, text: 'hello', pngBytes: null };
assert.equal(selectRdpClipboardData(input).text, 'hello');
assert.equal(selectRdpClipboardData({ ...input, lastText: 'hello' }).text, null);
assert.equal(selectRdpClipboardData({ ...input, lastText: 'hello', force: true }).text, 'hello');
});
test('text and PNG are selected together', () => {
const result = selectRdpClipboardData({ ...emptyState, text: 'caption', pngBytes });
assert.equal(result.text, 'caption');
assert.equal(result.pngBytes, pngBytes);
});
test('a changed clipboard snapshot sends every present format', () => {
const result = selectRdpClipboardData({
...emptyState,
text: 'new text',
pngBytes,
lastPngFingerprint: fingerprintRdpClipboardPng(pngBytes),
});
assert.equal(result.text, 'new text');
assert.equal(result.pngBytes, pngBytes);
const imageResult = selectRdpClipboardData({
...emptyState,
text: 'same text',
lastText: 'same text',
pngBytes,
});
assert.equal(imageResult.text, 'same text');
assert.equal(imageResult.pngBytes, pngBytes);
});
test('text then image then the same text replaces each clipboard snapshot', () => {
const imageResult = selectRdpClipboardData({
lastText: 'B', lastPngFingerprint: null, text: null, pngBytes,
});
const pngFingerprint = fingerprintRdpClipboardPng(pngBytes);
assert.deepEqual(imageResult, { text: null, pngBytes, pngFingerprint });
const imageState = nextRdpClipboardGuardState(imageResult);
assert.deepEqual(imageState, { lastText: '', lastPngFingerprint: pngFingerprint });
const textResult = selectRdpClipboardData({ ...imageState, text: 'B', pngBytes: null });
assert.deepEqual(textResult, { text: 'B', pngBytes: null, pngFingerprint: null });
const textState = nextRdpClipboardGuardState(textResult);
assert.deepEqual(textState, { lastText: 'B', lastPngFingerprint: null });
assert.deepEqual(selectRdpClipboardData({ ...textState, text: null, pngBytes }), imageResult);
});
test('text-only replacement sends unchanged text when the previous snapshot included a PNG', () => {
assert.deepEqual(selectRdpClipboardData({
lastText: 'B',
lastPngFingerprint: fingerprintRdpClipboardPng(pngBytes),
text: 'B',
pngBytes: null,
}), { text: 'B', pngBytes: null, pngFingerprint: null });
});
test('image-only replacement sends the same PNG when the previous snapshot included text', () => {
const pngFingerprint = fingerprintRdpClipboardPng(pngBytes);
assert.deepEqual(selectRdpClipboardData({
lastText: 'B',
lastPngFingerprint: pngFingerprint,
text: null,
pngBytes,
}), { text: null, pngBytes, pngFingerprint });
});
test('an identical text and PNG snapshot is skipped unless forced', () => {
const pngFingerprint = fingerprintRdpClipboardPng(pngBytes);
const input = {
lastText: 'B',
lastPngFingerprint: pngFingerprint,
text: 'B',
pngBytes: new Uint8Array(pngBytes),
};
assert.deepEqual(selectRdpClipboardData(input), {
text: null, pngBytes: null, pngFingerprint: null,
});
assert.deepEqual(selectRdpClipboardData({ ...input, force: true }), {
text: 'B', pngBytes, pngFingerprint,
});
assert.deepEqual(nextRdpClipboardGuardState(input), {
lastText: 'B', lastPngFingerprint: pngFingerprint,
});
});
test('an empty clipboard snapshot clears both guard fields and sends nothing', () => {
const input = { text: undefined, pngBytes: new Uint8Array() };
assert.deepEqual(nextRdpClipboardGuardState(input), emptyState);
assert.deepEqual(selectRdpClipboardData({ ...emptyState, ...input }), {
text: null, pngBytes: null, pngFingerprint: null,
});
});
test('empty clipboard formats are ignored even when forced', () => {
assert.deepEqual(selectRdpClipboardData({
...emptyState,
text: undefined,
pngBytes: new Uint8Array(),
force: true,
}), { text: null, pngBytes: null, pngFingerprint: null });
});
+58
View File
@@ -0,0 +1,58 @@
export function buildRdpClipboardItemData({ text, pngBytes }: {
text: string | null;
pngBytes: Uint8Array | null;
}): Record<string, Blob> {
const data: Record<string, Blob> = {};
if (pngBytes) {
const pngCopy = new Uint8Array(pngBytes.byteLength);
pngCopy.set(pngBytes);
data['image/png'] = new Blob([pngCopy], { type: 'image/png' });
}
if (text !== null) {
data['text/plain'] = new Blob([text], { type: 'text/plain' });
}
return data;
}
export function fingerprintRdpClipboardPng(bytes: Uint8Array): string {
// FNV-1a plus the byte length is sufficient for clipboard echo detection.
let hash = 0x811c9dc5;
for (const byte of bytes) {
hash = Math.imul(hash ^ byte, 0x01000193);
}
return `${bytes.length}:${(hash >>> 0).toString(16)}`;
}
export function nextRdpClipboardGuardState({ text, pngBytes }: {
text: string | null | undefined;
pngBytes: Uint8Array | null;
}) {
return {
lastText: text || '',
lastPngFingerprint: pngBytes?.length ? fingerprintRdpClipboardPng(pngBytes) : null,
};
}
export function selectRdpClipboardData({
text,
pngBytes,
lastText,
lastPngFingerprint,
force = false,
}: {
text: string | null | undefined;
pngBytes: Uint8Array | null;
lastText: string;
lastPngFingerprint: string | null;
force?: boolean;
}) {
const current = nextRdpClipboardGuardState({ text, pngBytes });
if (!force && current.lastText === lastText && current.lastPngFingerprint === lastPngFingerprint) {
return { text: null, pngBytes: null, pngFingerprint: null };
}
return {
text: current.lastText || null,
pngBytes: current.lastPngFingerprint !== null ? pngBytes : null,
pngFingerprint: current.lastPngFingerprint,
};
}
+20 -7
View File
@@ -237,16 +237,11 @@ function createClipboardImageFileName(date = new Date()) {
return `netcatty-paste-${formatClipboardImageTimestamp(date)}.png`;
}
async function readClipboardImage({
async function readClipboardImagePngBytes({
clipboard,
fsImpl = fs,
tempDirBridge,
nativeImageImpl = null,
now = () => new Date(),
} = {}) {
if (!clipboard || !tempDirBridge?.getTempFilePath) {
return null;
}
if (!clipboard) return null;
try {
let content = null;
@@ -297,7 +292,24 @@ async function readClipboardImage({
}
if (!Buffer.isBuffer(content) || content.length === 0) return null;
return content;
} catch {
return null;
}
}
async function readClipboardImage({
clipboard,
fsImpl = fs,
tempDirBridge,
nativeImageImpl = null,
now = () => new Date(),
} = {}) {
if (!clipboard || !tempDirBridge?.getTempFilePath) return null;
try {
const content = await readClipboardImagePngBytes({ clipboard, nativeImageImpl });
if (!content) return null;
const name = createClipboardImageFileName(now());
const imagePath = tempDirBridge.getTempFilePath(name);
await fsImpl.promises.writeFile(imagePath, content);
@@ -381,4 +393,5 @@ module.exports = {
parseClipboardTextFilePaths,
readClipboardFiles,
readClipboardImage,
readClipboardImagePngBytes,
};
+55
View File
@@ -11,6 +11,7 @@ const {
parseClipboardTextFilePaths,
readClipboardFiles,
readClipboardImage,
readClipboardImagePngBytes,
} = require("./clipboardFiles.cjs");
const createFs = (entries) => ({
@@ -158,6 +159,59 @@ test("creates stable clipboard image file names", () => {
);
});
test("reads native clipboard PNG bytes without a temp directory", async () => {
const content = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
const result = await readClipboardImagePngBytes({
clipboard: {
readImage: () => ({ isEmpty: () => false, toPNG: () => content }),
read: () => assert.fail("native image read should take precedence"),
},
});
assert.deepEqual(result, content);
});
test("PNG bytes helper returns null for empty native images or PNG buffers", async () => {
assert.equal(await readClipboardImagePngBytes({
clipboard: {
readImage: () => ({
isEmpty: () => true,
toPNG: () => assert.fail("empty image must not be encoded"),
}),
},
}), null);
assert.equal(await readClipboardImagePngBytes({
clipboard: { readImage: () => ({ toPNG: () => Buffer.alloc(0) }) },
}), null);
});
test("PNG bytes helper returns null for missing or failing clipboard reads", async () => {
assert.equal(await readClipboardImagePngBytes(), null);
assert.equal(await readClipboardImagePngBytes({
clipboard: { readImage: () => { throw new Error("clipboard unavailable"); } },
}), null);
});
test("PNG bytes helper converts async clipboard images through nativeImage", async () => {
const rawBytes = Buffer.from("jpeg");
const pngBytes = Buffer.from("png");
const result = await readClipboardImagePngBytes({
clipboard: {
read: async () => [{
types: ["image/jpeg"],
getType: async () => new Blob([rawBytes], { type: "image/jpeg" }),
}],
},
nativeImageImpl: {
createFromBuffer: (bytes) => {
assert.deepEqual(bytes, rawBytes);
return { isEmpty: () => false, toPNG: () => pngBytes };
},
},
});
assert.deepEqual(result, pngBytes);
});
test("writes clipboard image to Netcatty temp directory", async () => {
const writes = [];
const content = Buffer.from([1, 2, 3]);
@@ -346,6 +400,7 @@ test("readClipboardImage and hasClipboardImage support Electron 44+ async W3C cl
};
assert.equal(await hasClipboardImage({ clipboard }), true);
assert.deepEqual(await readClipboardImagePngBytes({ clipboard }), pngBytes);
const saved = await readClipboardImage({
clipboard,
fsImpl: {
@@ -556,6 +556,9 @@ function scheduleTrayPanelIdleDestroy(panelWin) {
&& !trayPanelShowWhenReady
) {
panelWin.destroy();
if (panelWin.isDestroyed() && tray) {
ensureTrayPanelWindow();
}
}
} catch {
// ignore
@@ -1151,6 +1154,9 @@ function createTray() {
});
}
// Load the hidden panel before the first click needs it.
ensureTrayPanelWindow();
console.log("[GlobalShortcut] System tray created");
} catch (err) {
console.error("[GlobalShortcut] Error creating tray:", err);
+102 -24
View File
@@ -83,18 +83,13 @@ function createElectronStub() {
}
}
return {
const electronModule = {
Tray: FakeTray,
Menu: {
buildFromTemplate(template) {
return { template };
},
},
BrowserWindow: {
getAllWindows() {
return [];
},
},
globalShortcut: {
register() {
return true;
@@ -128,6 +123,8 @@ function createElectronStub() {
quit() {},
},
};
installFakeTrayPanelWindow(electronModule);
return electronModule;
}
function createAppLockControllerStub(initialState = { locked: false, reason: null }) {
@@ -795,14 +792,8 @@ test("tray icon event registration is platform-dependent", async () => {
const win = new FakeWindow();
win.minimized = true;
const initializedElectronModule = {
...createElectronStub(),
BrowserWindow: {
getAllWindows() {
return [win];
},
},
};
const initializedElectronModule = createElectronStub();
initializedElectronModule.BrowserWindow.getAllWindows = () => [win];
bridge.init({
electronModule: initializedElectronModule,
getMainWindow: () => win,
@@ -838,14 +829,8 @@ test("tray icon event registration is platform-dependent", async () => {
const appLockController = createAppLockControllerStub();
const win = new FakeWindow();
win.minimized = true;
const initializedElectronModule = {
...createElectronStub(),
BrowserWindow: {
getAllWindows() {
return [win];
},
},
};
const initializedElectronModule = createElectronStub();
initializedElectronModule.BrowserWindow.getAllWindows = () => [win];
bridge.init({
electronModule: initializedElectronModule,
getMainWindow: () => win,
@@ -1363,6 +1348,7 @@ test("tray menu updates refresh an already open tray panel", async () => {
class FakePanelWindow extends FakeWindow {
constructor() {
super();
this.visible = false;
const webContents = new EventEmitter();
webContents.send = (channel, ...args) => {
sentMessages.push([channel, ...args]);
@@ -1537,6 +1523,9 @@ function installFakeTrayPanelWindow(electronModule, { getBoundsSize } = {}) {
height: opts.height,
};
this.setBoundsCalls = [];
this.loadURLCalls = [];
this.showCalls = 0;
this.focusCalls = 0;
this.destroyed = false;
this.visible = false;
const webContents = new EventEmitter();
@@ -1544,7 +1533,9 @@ function installFakeTrayPanelWindow(electronModule, { getBoundsSize } = {}) {
this.webContents = webContents;
}
async loadURL() {}
async loadURL(url) {
this.loadURLCalls.push(url);
}
getBounds() {
if (getBoundsSize) return { ...this.bounds, ...getBoundsSize };
return { ...this.bounds };
@@ -1556,15 +1547,24 @@ function installFakeTrayPanelWindow(electronModule, { getBoundsSize } = {}) {
isDestroyed() {
return this.destroyed;
}
isVisible() {
return this.visible;
}
show() {
this.showCalls += 1;
this.visible = true;
this.emit("show");
}
hide() {
this.visible = false;
this.emit("hide");
}
focus() {
this.focusCalls += 1;
}
focus() {}
destroy() {
this.destroyed = true;
this.emit("closed");
}
}
@@ -1574,6 +1574,84 @@ function installFakeTrayPanelWindow(electronModule, { getBoundsSize } = {}) {
return FakePanelWindow;
}
test("createTray preloads the hidden panel without showing, focusing, or positioning it", async () => {
await withPlatform("win32", async () => {
const bridge = loadBridge();
const electronModule = createElectronStub();
const FakePanelWindow = electronModule.BrowserWindow;
bridge.init({ electronModule, getMainWindow: () => null });
try {
bridge.createTray();
assert.ok(bridge.getTray());
assert.equal(FakePanelWindow.instances.length, 1);
const panelWin = FakePanelWindow.instances[0];
assert.equal(bridge.getTrayPanelWindow(), panelWin);
assert.equal(panelWin.opts.show, false);
assert.equal(panelWin.opts.skipTaskbar, true);
assert.equal(panelWin.loadURLCalls.length, 1);
assert.match(panelWin.loadURLCalls[0], /#\/tray$/);
panelWin.webContents.emit("did-finish-load");
assert.equal(panelWin.isVisible(), false);
assert.equal(panelWin.showCalls, 0);
assert.equal(panelWin.focusCalls, 0);
assert.deepEqual(panelWin.setBoundsCalls, []);
} finally {
bridge.cleanup();
}
});
});
test("idle destroy rewarms the hidden tray panel for the next click", async () => {
await withPatchedTimers(async ({ flushNextTimer, getPendingTimerCount }) => {
await withPlatform("win32", async () => {
const bridge = loadBridge();
const electronModule = createElectronStub();
const FakePanelWindow = electronModule.BrowserWindow;
const eventBounds = { x: 1200, y: 860, width: 24, height: 24 };
electronModule.screen = {
getDisplayNearestPoint: () => ({ workArea: { x: 0, y: 0, width: 1440, height: 860 } }),
};
try {
await enableCloseToTray(bridge, electronModule);
const rightClick = bridge.getTray().handlers.get("right-click");
const firstWin = FakePanelWindow.instances[0];
firstWin.webContents.emit("did-finish-load");
rightClick(null, eventBounds);
assert.equal(firstWin.showCalls, 1);
rightClick(null, eventBounds);
assert.equal(firstWin.isVisible(), false);
assert.equal(getPendingTimerCount(), 1);
assert.equal(flushNextTimer(), true);
assert.equal(firstWin.isDestroyed(), true);
assert.equal(FakePanelWindow.instances.length, 2);
const secondWin = FakePanelWindow.instances[1];
assert.equal(bridge.getTrayPanelWindow(), secondWin);
assert.equal(secondWin.opts.show, false);
assert.equal(secondWin.opts.skipTaskbar, true);
assert.deepEqual(secondWin.loadURLCalls, firstWin.loadURLCalls);
assert.equal(secondWin.showCalls, 0);
assert.equal(secondWin.focusCalls, 0);
assert.deepEqual(secondWin.setBoundsCalls, []);
secondWin.webContents.emit("did-finish-load");
assert.equal(secondWin.isVisible(), false);
assert.equal(secondWin.showCalls, 0);
assert.equal(getPendingTimerCount(), 0);
rightClick(null, eventBounds);
assert.equal(FakePanelWindow.instances.length, 2);
assert.equal(secondWin.showCalls, 1);
assert.equal(secondWin.focusCalls, 1);
} finally {
bridge.cleanup();
}
});
});
});
test("Windows right-click places the designed panel above the taskbar from event bounds", async () => {
await withPlatform("win32", async () => {
const { placeTrayPanel } = require("./trayPanelBounds.cjs");
+5 -1
View File
@@ -2,7 +2,7 @@
let cloudSyncSessionPassword = null;
const perfTrace = require("../perfTrace.cjs");
const { readClipboardFiles, readClipboardImage, hasClipboardImage } = require("../bridges/clipboardFiles.cjs");
const { readClipboardFiles, readClipboardImage, readClipboardImagePngBytes, hasClipboardImage } = require("../bridges/clipboardFiles.cjs");
const { registerSystemNotificationHandlers } = require("../bridges/systemNotification.cjs");
const {
installWindowAttention,
@@ -1207,6 +1207,10 @@ function createBridgeRegistrar(context) {
return await readClipboardImage({ clipboard, fsImpl: fs, tempDirBridge });
});
ipcMain.handle("netcatty:clipboard:readImagePng", async () => {
return await readClipboardImagePngBytes({ clipboard });
});
ipcMain.handle("netcatty:clipboard:hasImage", async () => {
return await hasClipboardImage({ clipboard });
});
+3
View File
@@ -2047,6 +2047,9 @@ function createPreloadApi(ctx) {
readClipboardImage: async () => {
return ipcRenderer.invoke("netcatty:clipboard:readImage");
},
readClipboardImagePng: async () => {
return ipcRenderer.invoke("netcatty:clipboard:readImagePng");
},
hasClipboardImage: async () => {
return ipcRenderer.invoke("netcatty:clipboard:hasImage");
},
+1
View File
@@ -170,6 +170,7 @@ declare global {
writeClipboardText?(text: string): Promise<boolean>;
readClipboardFiles?(): Promise<Array<{ path: string; name: string; isDirectory: boolean; size?: number }>>;
readClipboardImage?(): Promise<{ path: string; name: string; mediaType: string; size?: number } | null>;
readClipboardImagePng?(): Promise<Uint8Array | null>;
hasClipboardImage?(): Promise<boolean>;
// Credential encryption (field-level safeStorage for sensitive data at rest)