mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-29 22:00:10 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
547ab339fe | ||
|
|
4b05b03776 | ||
|
|
5d5c5b0940 | ||
|
|
549f58c653 | ||
|
|
3a913b8fc2 | ||
|
|
8cae6c5784 | ||
|
|
3c4f561beb |
No files matched your search
@@ -46,6 +46,8 @@
|
||||
<a href="./README.md">English</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.zh-TW.md">繁體中文</a> · <a href="./README.ja-JP.md">日本語</a>
|
||||
</p>
|
||||
|
||||
> **お知らせ:** プラグインシステムおよび現在の公式プラグイン(Netcatty Database、Netcatty Monitor)は、まだ不安定な段階にあります。ご利用の際はご注意ください。問題があればいつでも [Issue を作成](https://github.com/binaricat/Netcatty/issues)してください。できるだけ早く対応します。詳しくは[お知らせ](https://github.com/binaricat/Netcatty/discussions/4554)をご覧ください。
|
||||
|
||||
---
|
||||
|
||||
<img width="3358" height="1984" alt="image" src="docs/assets/readme/overview.webp" />
|
||||
@@ -84,6 +86,8 @@ Catty Agent にサーバーの健全性チェックを依頼すると、適切
|
||||
<a name="plugin-system"></a>
|
||||
# 🧩 プラグインシステム — Netcatty を安全に拡張
|
||||
|
||||
> **お知らせ:** プラグインシステムおよび現在の公式プラグイン(Netcatty Database、Netcatty Monitor)は、まだ不安定な段階にあります。ご利用の際はご注意ください。問題があればいつでも [Issue を作成](https://github.com/binaricat/Netcatty/issues)してください。できるだけ早く対応します。詳しくは[お知らせ](https://github.com/binaricat/Netcatty/discussions/4554)をご覧ください。
|
||||
|
||||
> **SSH 鍵やホストレンダラーを公開することなく機能を追加できます。** Netcatty のセキュリティ優先プラグイン基盤は、通常プラグインをオフラインのサンドボックス内で実行し、**ホストレンダリング UI**(Closed Shadow DOM + ネイティブ Monaco、DataGrid、BI/メトリクスチャート、Vault SSH トンネルプロキシ)のみで画面を描画します。
|
||||
|
||||
### ✨ 主な特徴
|
||||
|
||||
@@ -46,6 +46,8 @@
|
||||
<a href="./README.md">English</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.zh-TW.md">繁體中文</a> · <a href="./README.ja-JP.md">日本語</a>
|
||||
</p>
|
||||
|
||||
> **Notice:** The plugin system and the current official plugins (Netcatty Database and Netcatty Monitor) are still in an unstable stage. Please keep that in mind while using them. If you run into a problem, feel free to [open an Issue](https://github.com/binaricat/Netcatty/issues) — I'll fix it as soon as I can. See the [announcement](https://github.com/binaricat/Netcatty/discussions/4554).
|
||||
|
||||
---
|
||||
|
||||
<img width="3358" height="1984" alt="image" src="docs/assets/readme/overview.webp" />
|
||||
@@ -86,6 +88,8 @@ Watch Catty Agent orchestrate a Docker Swarm cluster across two servers in one c
|
||||
<a name="plugin-system"></a>
|
||||
# 🧩 Plugin System — Extend Netcatty Safely
|
||||
|
||||
> **Notice:** The plugin system and the current official plugins (Netcatty Database and Netcatty Monitor) are still in an unstable stage. Please keep that in mind while using them. If you run into a problem, feel free to [open an Issue](https://github.com/binaricat/Netcatty/issues) — I'll fix it as soon as I can. See the [announcement](https://github.com/binaricat/Netcatty/discussions/4554).
|
||||
|
||||
> **Build and install rich extensions without exposing your SSH keys or host renderer.** Netcatty's security-first plugin platform runs ordinary extensions inside an offline, sandboxed runtime and renders custom views exclusively through **Host-Rendered UI** (closed Shadow DOM + native Monaco, DataGrid, BI/Metric charts, and Vault SSH tunnel brokers).
|
||||
|
||||
### ✨ Highlights
|
||||
|
||||
@@ -46,6 +46,8 @@
|
||||
<a href="./README.md">English</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.zh-TW.md">繁體中文</a> · <a href="./README.ja-JP.md">日本語</a>
|
||||
</p>
|
||||
|
||||
> **说明:** 插件系统和现有的官方插件(Netcatty 数据库、Netcatty 监控)目前仍处于不稳定阶段,使用时请多加留意。如果你遇到问题,欢迎随时[提交 Issue](https://github.com/binaricat/Netcatty/issues),我会尽快修复。详见[公告](https://github.com/binaricat/Netcatty/discussions/4554)。
|
||||
|
||||
---
|
||||
|
||||
<img width="3358" height="1984" alt="image" src="docs/assets/readme/overview.webp" />
|
||||
@@ -84,6 +86,8 @@
|
||||
<a name="plugin-system"></a>
|
||||
# 🧩 插件系统 — 安全扩展你的工作台
|
||||
|
||||
> **说明:** 插件系统和现有的官方插件(Netcatty 数据库、Netcatty 监控)目前仍处于不稳定阶段,使用时请多加留意。如果你遇到问题,欢迎随时[提交 Issue](https://github.com/binaricat/Netcatty/issues),我会尽快修复。详见[公告](https://github.com/binaricat/Netcatty/discussions/4554)。
|
||||
|
||||
> **在不暴露 SSH 密钥与主进程渲染器的前提下自由扩展 Netcatty。** Netcatty 的安全优先插件平台将普通插件隔离在离线沙箱中运行,并通过**宿主渲染 UI**(Closed Shadow DOM + 原生 Monaco 编辑器、虚拟化数据网格、实时监控/BI 图表与 Vault SSH 隧道代理)呈现原生手感界面。
|
||||
|
||||
### ✨ 核心亮点
|
||||
|
||||
@@ -46,6 +46,8 @@
|
||||
<a href="./README.md">English</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.zh-TW.md">繁體中文</a> · <a href="./README.ja-JP.md">日本語</a>
|
||||
</p>
|
||||
|
||||
> **說明:** 外掛系統與現有的官方外掛(Netcatty 資料庫、Netcatty 監控)目前仍處於不穩定階段,使用時請多加留意。若遇到問題,歡迎隨時[提交 Issue](https://github.com/binaricat/Netcatty/issues),我會盡快修復。詳見[公告](https://github.com/binaricat/Netcatty/discussions/4554)。
|
||||
|
||||
---
|
||||
|
||||
<img width="3358" height="1984" alt="image" src="docs/assets/readme/overview.webp" />
|
||||
@@ -84,6 +86,8 @@
|
||||
<a name="plugin-system"></a>
|
||||
# 🧩 外掛系統 —— 安全擴充你的工作台
|
||||
|
||||
> **說明:** 外掛系統與現有的官方外掛(Netcatty 資料庫、Netcatty 監控)目前仍處於不穩定階段,使用時請多加留意。若遇到問題,歡迎隨時[提交 Issue](https://github.com/binaricat/Netcatty/issues),我會盡快修復。詳見[公告](https://github.com/binaricat/Netcatty/discussions/4554)。
|
||||
|
||||
> **在不暴露 SSH 金鑰與宿主渲染器的前提下自由擴充 Netcatty。** Netcatty 的安全優先外掛平台將一般外掛隔離於離線沙箱中執行,並透過**宿主渲染 UI**(Closed Shadow DOM + 原生 Monaco 編輯器、虛擬化資料格、即時監控/BI 圖表與 Vault SSH 通道代理)呈現原生體驗。
|
||||
|
||||
### ✨ 核心亮點
|
||||
|
||||
@@ -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:",
|
||||
|
||||
@@ -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:",
|
||||
|
||||
@@ -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-адреса в браузере по умолчанию:",
|
||||
|
||||
@@ -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 链接:",
|
||||
|
||||
@@ -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 連結:",
|
||||
|
||||
@@ -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' }],
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
},
|
||||
|
||||
@@ -218,3 +218,52 @@ test('portForward.start surfaces live error status and message when tunnel start
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('views.open resolves visible contribution, triggers open without polluting context, and rejects missing/hidden views', async () => {
|
||||
const opened: Array<{ viewId: string; context?: Record<string, unknown>; params?: unknown }> = [];
|
||||
const queries: unknown[] = [];
|
||||
const ctx: PluginVaultDataContext = {
|
||||
...makeContext({}),
|
||||
viewOpenRuntime: {
|
||||
getPluginContributions: async (query) => {
|
||||
queries.push(query);
|
||||
return {
|
||||
locale: 'en',
|
||||
plugins: [{
|
||||
id: 'com.example.db',
|
||||
version: '1.0.0',
|
||||
displayName: 'Database',
|
||||
commands: [],
|
||||
keybindings: [],
|
||||
menus: [],
|
||||
settings: [],
|
||||
views: [
|
||||
{ id: 'com.example.db.workbench', title: 'Database', location: 'vault-page', visible: true },
|
||||
{ id: 'com.example.db.hidden', title: 'Hidden', location: 'vault-page', visible: false },
|
||||
],
|
||||
}],
|
||||
};
|
||||
},
|
||||
requestOpenPluginView: (detail) => { opened.push(detail); },
|
||||
},
|
||||
};
|
||||
|
||||
const result = await handlePluginVaultDataRequest(
|
||||
'views.open',
|
||||
{ viewId: 'com.example.db.workbench', location: 'vault-page' },
|
||||
ctx,
|
||||
);
|
||||
assert.deepEqual(result, { opened: true, focused: true, location: 'vault-page' });
|
||||
assert.deepEqual(queries[0], { context: { 'netcatty.surface': 'vault-page' } });
|
||||
assert.deepEqual(opened, [{ viewId: 'com.example.db.workbench' }]);
|
||||
|
||||
await assert.rejects(
|
||||
() => handlePluginVaultDataRequest('views.open', { viewId: 'com.example.db.hidden', location: 'vault-page' }, ctx),
|
||||
/not available/,
|
||||
);
|
||||
await assert.rejects(
|
||||
() => handlePluginVaultDataRequest('views.open', { viewId: 'com.example.db.missing', location: 'vault-page' }, ctx),
|
||||
/not available/,
|
||||
);
|
||||
assert.equal(opened.length, 1);
|
||||
});
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
applyPortForwardingRuntimeStatus,
|
||||
getPortForwardingRuntimeRules,
|
||||
} from './usePortForwardingState';
|
||||
import { requestOpenPluginView } from './usePluginViewLifecycle';
|
||||
|
||||
export interface PluginPortForwardRuntimeDeps {
|
||||
startPortForward?: typeof startPortForward;
|
||||
@@ -36,10 +37,16 @@ export interface PluginPortForwardRuntimeDeps {
|
||||
applyRuntimeStatus?: typeof applyPortForwardingRuntimeStatus;
|
||||
}
|
||||
|
||||
export interface PluginViewOpenRuntimeDeps {
|
||||
getPluginContributions?: NonNullable<ReturnType<typeof netcattyBridge.get>>['getPluginContributions'];
|
||||
requestOpenPluginView?: typeof requestOpenPluginView;
|
||||
}
|
||||
|
||||
export type PluginVaultDataContext = {
|
||||
getVault: () => AppVaultRuntime & ReturnType<AppVaultRuntime['readCurrentHostActionState']>;
|
||||
resources: PluginHostActionResources;
|
||||
portForwardRuntime?: PluginPortForwardRuntimeDeps;
|
||||
viewOpenRuntime?: PluginViewOpenRuntimeDeps;
|
||||
};
|
||||
|
||||
type PortForwardSummaryStatus = 'inactive' | 'connecting' | 'active' | 'error';
|
||||
@@ -472,6 +479,42 @@ export async function handlePluginVaultDataRequest(
|
||||
return { focused: true };
|
||||
}
|
||||
|
||||
case 'views.open': {
|
||||
const viewId = typeof payload.viewId === 'string' ? payload.viewId : '';
|
||||
const location = typeof payload.location === 'string' ? payload.location : '';
|
||||
if (!viewId) throw new Error('Plugin view ID is required');
|
||||
const queryContext = location === 'vault-page'
|
||||
? { 'netcatty.surface': 'vault-page' }
|
||||
: location === 'terminal-sidebar'
|
||||
? { 'netcatty.surface': 'terminal-sidebar' }
|
||||
: { 'netcatty.surface': 'view' };
|
||||
const getContributions = ctx.viewOpenRuntime?.getPluginContributions ?? netcattyBridge.get()?.getPluginContributions;
|
||||
if (!getContributions) {
|
||||
throw new Error('Plugin contributions are unavailable');
|
||||
}
|
||||
const snapshot = await getContributions({ context: queryContext });
|
||||
const resolved = snapshot.plugins
|
||||
.flatMap((plugin) => plugin.views)
|
||||
.find((view) => view.id === viewId && view.visible);
|
||||
if (!resolved) {
|
||||
throw new Error(`Plugin view is not available: ${viewId}`);
|
||||
}
|
||||
if (resolved.location === 'terminal-sidebar') {
|
||||
const sessionRuntime = getAppSessionRuntime();
|
||||
const activeTabId = activeTabStore.getActiveTabId();
|
||||
const isTerminalTab = Boolean(
|
||||
sessionRuntime?.sessions.some((s) => s.id === activeTabId)
|
||||
|| sessionRuntime?.workspaces.some((w) => w.id === activeTabId),
|
||||
);
|
||||
if (!isTerminalTab) {
|
||||
throw new Error('An active terminal tab is required to open a terminal sidebar view');
|
||||
}
|
||||
}
|
||||
const openView = ctx.viewOpenRuntime?.requestOpenPluginView ?? requestOpenPluginView;
|
||||
openView({ viewId: resolved.id });
|
||||
return { opened: true, focused: true, location: resolved.location };
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`Unsupported Vault data request: ${kind}`);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
});
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
@@ -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 };
|
||||
};
|
||||
@@ -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
|
||||
|
||||
@@ -26,6 +26,7 @@ export const OPEN_PLUGIN_VIEW_EVENT = 'netcatty:open-plugin-view';
|
||||
export interface OpenPluginViewDetail {
|
||||
viewId: string;
|
||||
context?: Record<string, unknown>;
|
||||
params?: unknown;
|
||||
}
|
||||
|
||||
export type ResolvedPluginView = {
|
||||
|
||||
@@ -73,8 +73,12 @@ test('Vault navigation mounts a real content slot, yields to host dialogs, and w
|
||||
await act(async () => { selectSection('plugin-vault:missing'); await settle(); });
|
||||
assert.match(document.querySelector('main')!.textContent!, /Built-in hosts/);
|
||||
await act(async () => { snapshot = { ...snapshot, plugins: [{ id: 'com.example.page', version: '1.0.0', displayName: 'Synthetic plugin', commands: [], keybindings: [], menus: [], settings: [], views: [page] }] }; changed?.(); await settle(); });
|
||||
await act(async () => { requestOpenPluginView({ viewId: page.id }); await settle(); });
|
||||
await act(async () => { activeTabStore.setActiveTabId('terminal:synthetic'); await settle(); });
|
||||
assert.equal(activeTabStore.getActiveTabId(), 'terminal:synthetic');
|
||||
await act(async () => { requestOpenPluginView({ viewId: page.id, params: { connectionId: 'db-1' } }); await settle(); });
|
||||
assert.equal(activeTabStore.getActiveTabId(), 'vault', 'opening a vault-page switches the active tab to vault');
|
||||
assert.equal(opens.length, 2);
|
||||
assert.deepEqual(opens[1].context, { 'netcatty.surface': 'vault-page' }, 'activation params must not be merged into contribution context');
|
||||
await act(async () => { selectSection('hosts'); await settle(); });
|
||||
assert.equal(document.querySelector('[data-plugin-vault-page]'), null);
|
||||
} finally {
|
||||
@@ -82,3 +86,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); }
|
||||
}
|
||||
});
|
||||
@@ -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}`
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -13,7 +13,7 @@ mean complete. Existing APIs remain available.
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| Authorization management | Engine `listGrants`, `revokeAll`, database audit | Manager shows declarations only | Host-only grant list, bounded audit summary, disable and revoke | Paths, session IDs, grant metadata are sensitive | Exact plugin ID, trusted app sender | Serialized manager mutation, disable before revoke, runtime teardown, retained audit | Batch 1 limited acceptance complete on ff3734d: independent review fixes, host/manager/UI tests, exact test/packaging CI, parent native own-views Application grant/revoke/disable/runtime-stop check. Visible view was manually closed beforehand. No plugin RPC for managing grants |
|
||||
| Network and credential leases | `network.request`, `credentials.createLease`, single-use host redemption | SDK request omits lease and authorization fields | Canonical request types matching broker | Network mutation and credentials | Exact origin plus secret reference and operation | Existing timeout, redirects, byte quotas, runtime checks, lease TTL | Batch 1 contract/SDK consistency complete: canonical types, synthetic fixture/lease tests, feature discovery and exact CI. No live network or credential acceptance claimed. No plaintext secret API |
|
||||
| Commands, menus, toolbar, status bar, views | `commands.execute`, settings, context keys, view state and messages, UI contributions | No editor or SFTP menu slots | Existing contribution system | Plugin text and arguments may be sensitive | Namespaced contributions and permissions | Existing lifecycle, rate and message limits | Existing tests. New context menu slots planned with bounded context DTOs |
|
||||
| Commands, menus, toolbar, status bar, views | `commands.execute`, settings, context keys, view state and messages, `views.open` (own contributed view + `host-ui.activate`), UI contributions | No editor or SFTP menu slots | Existing contribution system and capability-gated `views.open` for own views | Plugin text and arguments may be sensitive | Namespaced contributions and permissions | Existing lifecycle, rate and message limits; 16 KiB UTF-8 cap on `views.open` params | Existing tests plus unit tests for `views.open` (no live Electron/CI acceptance claimed). New context menu slots planned with bounded context DTOs |
|
||||
| Terminal providers | Decorations, links, completion, snapshots through provider requests | Session change delivery follows prior provider request and non-once grant | Preserve providers. Standalone selected-session watch planned | Hostnames, session state, endpoint identity | Host-selected session, runtime identity | Session-close and revoke cleanup, bounded event rate | Existing provider tests. Ordinary views cannot independently subscribe today |
|
||||
| Current context and host picker | Host context keys are boolean state | `vault.metadata` enumeration is not generic SDK | Selected host/session DTO from an explicit whitelist | Labels and endpoint metadata are sensitive | Host-owned user-action context, selected host/session | TTL, runtime and session invalidation, redacted audit | Planned. Never reuse agent `sanitizeHostForAgent` as plugin DTO |
|
||||
| Terminal selection and input draft | Provider-supplied snapshots, completion suggestions | No explicit selection-share or draft API | User shares selection, plugin proposes a visible editable draft | Terminal plaintext, accidental execution | Host action token plus exact live session/endpoint | Single-use token, size cap, no plaintext audit, active identity before commit | Planned. Reject Enter/control characters for draft insertion. No full history or direct shell |
|
||||
|
||||
@@ -87,6 +87,17 @@ stores only the plugin's own data, not host records or credentials. State scopes
|
||||
separate placements and terminal sessions but are not an authorization boundary
|
||||
against other code in the same plugin.
|
||||
|
||||
A plugin can open or focus one of its own contributed views with
|
||||
`context.views.open({ viewId, params? })` (permission `views`; gated by
|
||||
`views.vault-pages` for `vault-page`, `views.terminal-sidebar` for
|
||||
`terminal-sidebar`, and `views.host-drawn` for `tab`, `aside`, `panel`, and
|
||||
`modal`). Once the view is visible and focused in the main window, the host
|
||||
delivers `{ kind: "host-ui.activate", instanceId, params? }` over
|
||||
`context.views.onDidReceiveMessage(viewId, listener)` for both newly created
|
||||
and retained instances without remounting an existing view. `params` is
|
||||
optional plugin-defined JSON (at most 16 KiB UTF-8 serialized), never host
|
||||
records or credentials, and is not merged into contribution `context`.
|
||||
|
||||
The main process binds each instance to its actual owner window and exact
|
||||
plugin/runtime version. Close during activation, owner navigation/crash, plugin
|
||||
disable/replacement/uninstall, runtime failure and App Lock invalidate it.
|
||||
|
||||
@@ -10,6 +10,13 @@ normal stacking. The plugin receives only the `netcatty.surface: vault-page`
|
||||
context and its own interactions. Selection shares no Vault or session records.
|
||||
|
||||
Leaving and returning retains the view within the bounded lifecycle policy.
|
||||
A plugin with `views` and negotiated `views.vault-pages` may also open or focus
|
||||
its own `vault-page` via `context.views.open({ viewId, params? })`, switching
|
||||
to the Vault tab and selecting that page while delivering
|
||||
`{ kind: "host-ui.activate", instanceId, params? }` to the live instance
|
||||
(retained or newly mounted). Listing still does not auto-activate pages, and
|
||||
`params` is bounded plugin-defined JSON (not host records, credentials, or
|
||||
contribution `context`).
|
||||
Missing/disabled entries, invalid context or failed activation return to Hosts.
|
||||
Late failure from an older selection cannot replace a newer page. App Lock,
|
||||
disable and runtime termination clear the associated content and authority.
|
||||
|
||||
@@ -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 });
|
||||
});
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -21,6 +21,10 @@ test("AI privacy IPC validates sender and shares semantic transforms", async ()
|
||||
assert.equal(masked.ok, true);
|
||||
assert.doesNotMatch(JSON.stringify(masked.value), /synthetic-secret|192\.0\.2\.1/);
|
||||
assert.deepEqual(transform({ trusted: true }, { ...request, operation: "restore", value: masked.value }).value, request.value);
|
||||
assert.deepEqual(transform({ trusted: true }, { ...request, operation: "restoreStrict", value: masked.value }).value, request.value);
|
||||
const unknown = { ...request, value: "[NC_unknown_IP_1]" };
|
||||
assert.equal(transform({ trusted: true }, { ...unknown, operation: "restore" }).value, unknown.value);
|
||||
assert.equal(transform({ trusted: true }, { ...unknown, operation: "restoreStrict" }).ok, false);
|
||||
handlers.get("netcatty:ai:privacy:clear")({ trusted: true }, request.chatSessionId);
|
||||
assert.equal(transform({ trusted: true }, { ...request, operation: "restore", value: masked.value }).ok, false);
|
||||
service.invalidateConfiguration();
|
||||
|
||||
@@ -21,7 +21,7 @@ function registerPrivacyHandlers({ ipcMain, validateSender, aiPrivacyService })
|
||||
ipcMain.handle("netcatty:ai:privacy:transform", (event, request = {}) => {
|
||||
if (!validateSender(event)) return { ok: false, error: "Unauthorized" };
|
||||
try {
|
||||
if (request.operation !== "redact" && request.operation !== "restore") {
|
||||
if (request.operation !== "redact" && request.operation !== "restore" && request.operation !== "restoreStrict") {
|
||||
throw new Error("Invalid AI privacy operation.");
|
||||
}
|
||||
return {
|
||||
|
||||
@@ -21,7 +21,13 @@
|
||||
*/
|
||||
function createStreamEmitter({ safeSend, sender, requestId, restoreValue }) {
|
||||
const pending = { "text-delta": "", "reasoning-delta": "" };
|
||||
const restore = typeof restoreValue === "function" ? restoreValue : (value) => value;
|
||||
const restoreStrict = typeof restoreValue === "function" ? restoreValue : (value) => value;
|
||||
const restore = (value) => {
|
||||
try { return restoreStrict(value); } catch {
|
||||
// #4562: an unresolvable display fragment must not abort the turn.
|
||||
return value;
|
||||
}
|
||||
};
|
||||
const streamFields = { "text-delta": "textDelta", "reasoning-delta": "delta" };
|
||||
const displayFields = {
|
||||
"tool-call": ["args", "input"],
|
||||
@@ -58,7 +64,6 @@ function createStreamEmitter({ safeSend, sender, requestId, restoreValue }) {
|
||||
const suffix = text.slice(start);
|
||||
if ("[NC_".startsWith(suffix)
|
||||
|| (suffix.startsWith("[NC_") && !suffix.includes("]"))) {
|
||||
if (suffix.length > 128) throw new Error("AI privacy could not restore an incomplete response token.");
|
||||
end = start;
|
||||
}
|
||||
}
|
||||
@@ -108,7 +113,7 @@ function createStreamEmitter({ safeSend, sender, requestId, restoreValue }) {
|
||||
pending["text-delta"] = "";
|
||||
pending["reasoning-delta"] = "";
|
||||
let restored;
|
||||
try { restored = restore(error); } catch {
|
||||
try { restored = restoreStrict(error); } catch {
|
||||
restored = "AI privacy could not restore the response. Start a new conversation.";
|
||||
}
|
||||
safeSend(sender, "netcatty:ai:sdk-agent:error", { requestId, error: restored });
|
||||
|
||||
@@ -127,14 +127,80 @@ test("privacy restoration restores activity fields and never emits an unfinished
|
||||
assert.match(JSON.stringify(calls), /private-original/);
|
||||
});
|
||||
|
||||
test("privacy restoration fails closed on unknown complete tokens and incomplete final tokens", () => {
|
||||
test("privacy restoration passes through unknown complete tokens and incomplete final tokens", () => {
|
||||
const { calls, safeSend } = recordingSend();
|
||||
const emitter = createStreamEmitter({
|
||||
safeSend, sender: {}, requestId: "private", restoreValue: restoreTestValue,
|
||||
});
|
||||
assert.doesNotThrow(() => emitter.text("[NC_other_SECRET_1]"));
|
||||
emitter.text(" after ");
|
||||
emitter.text("[NC_incomplete");
|
||||
assert.doesNotThrow(() => emitter.emitDone());
|
||||
assert.deepEqual(calls.map((entry) => entry.channel), [
|
||||
"netcatty:ai:sdk-agent:event", "netcatty:ai:sdk-agent:event",
|
||||
"netcatty:ai:sdk-agent:event", "netcatty:ai:sdk-agent:done",
|
||||
]);
|
||||
assert.equal(calls.map((entry) => entry.payload.event?.textDelta || "").join(""),
|
||||
"[NC_other_SECRET_1] after [NC_incomplete");
|
||||
});
|
||||
|
||||
test("unknown reasoning tokens allow later text and reasoning-end events to continue", () => {
|
||||
const { calls, safeSend } = recordingSend();
|
||||
const emitter = createStreamEmitter({
|
||||
safeSend, sender: {}, requestId: "private", restoreValue: restoreTestValue,
|
||||
});
|
||||
emitter.reasoning("Note IPs are redacted as [NC_other_");
|
||||
assert.doesNotThrow(() => emitter.emitEvent({ type: "reasoning-delta", delta: "SECRET_1]" }));
|
||||
emitter.text(`Answer ${PRIVATE_TOKEN}`);
|
||||
emitter.reasoning(" then [NC_incomplete");
|
||||
assert.doesNotThrow(() => emitter.reasoningEnd());
|
||||
emitter.emitDone();
|
||||
const events = calls.filter((entry) => entry.payload.event).map((entry) => entry.payload.event);
|
||||
assert.equal(events.filter((event) => event.type === "reasoning-delta").map((event) => event.delta).join(""),
|
||||
"Note IPs are redacted as [NC_other_SECRET_1] then [NC_incomplete");
|
||||
assert.equal(events.find((event) => event.type === "text-delta").textDelta, "Answer private-original");
|
||||
assert.equal(events.at(-1).type, "reasoning-end");
|
||||
assert.equal(calls.at(-1).channel, "netcatty:ai:sdk-agent:done");
|
||||
assert.equal(calls.some((entry) => entry.channel === "netcatty:ai:sdk-agent:error"), false);
|
||||
});
|
||||
|
||||
test("long incomplete privacy tokens remain buffered until the final flush", () => {
|
||||
const { calls, safeSend } = recordingSend();
|
||||
const emitter = createStreamEmitter({
|
||||
safeSend, sender: {}, requestId: "private", restoreValue: restoreTestValue,
|
||||
});
|
||||
const incomplete = `[NC_${"x".repeat(128)}`;
|
||||
assert.doesNotThrow(() => emitter.text(`Before ${incomplete}`));
|
||||
assert.equal(calls[0].payload.event.textDelta, "Before ");
|
||||
assert.doesNotThrow(() => emitter.emitDone());
|
||||
assert.equal(calls[1].payload.event.textDelta, incomplete);
|
||||
assert.equal(calls[2].channel, "netcatty:ai:sdk-agent:done");
|
||||
});
|
||||
|
||||
test("activity restoration failures preserve opaque values and allow the stream to finish", () => {
|
||||
const { calls, safeSend } = recordingSend();
|
||||
const emitter = createStreamEmitter({
|
||||
safeSend, sender: {}, requestId: "private", restoreValue: restoreTestValue,
|
||||
});
|
||||
const output = { text: "[NC_other_SECRET_1]" };
|
||||
assert.doesNotThrow(() => emitter.toolResult("tool-1", output, "tool"));
|
||||
emitter.text("Still working");
|
||||
emitter.reasoning("[NC_incomplete");
|
||||
assert.doesNotThrow(() => emitter.emitDone());
|
||||
assert.deepEqual(calls.map((entry) => entry.payload.event || entry.channel), [
|
||||
{ type: "tool-result", toolCallId: "tool-1", output, toolName: "tool" },
|
||||
{ type: "text-delta", textDelta: "Still working" },
|
||||
{ type: "reasoning-delta", delta: "[NC_incomplete" },
|
||||
"netcatty:ai:sdk-agent:done",
|
||||
]);
|
||||
});
|
||||
|
||||
test("privacy restoration failure in an error retains the generic fallback", () => {
|
||||
const { calls, safeSend } = recordingSend();
|
||||
const emitter = createStreamEmitter({
|
||||
safeSend, sender: {}, requestId: "private", restoreValue: restoreTestValue,
|
||||
});
|
||||
assert.throws(() => emitter.text("[NC_other_SECRET_1]"), /Unknown privacy token/);
|
||||
emitter.text("[NC_incomplete");
|
||||
assert.throws(() => emitter.emitDone(), /Unknown privacy token/);
|
||||
emitter.emitError("[NC_other_SECRET_1]");
|
||||
assert.equal(calls.length, 1);
|
||||
assert.match(calls[0].payload.error, /Start a new conversation/);
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
@@ -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);
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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 });
|
||||
});
|
||||
|
||||
@@ -19,6 +19,7 @@ const MAX_NODES = 100000;
|
||||
const MAX_DEPTH = 100;
|
||||
const CONFIG_KEYS = new Set(["enabled", "redactPrivateIps", "cidrs", "patterns"]);
|
||||
const RESERVED_TOKEN = /\[NC_[^\]\r\n]*(?:\]|(?=[\r\n]|$))/g;
|
||||
const PLACEHOLDER_TOKEN = /^\[NC_[a-f0-9]{12}_(?:IP|HOST|SECRET)_\d+\]$/;
|
||||
|
||||
function plainObject(value) {
|
||||
return value !== null && typeof value === "object"
|
||||
@@ -112,7 +113,7 @@ function escapedLiteral(value) {
|
||||
* Session-local reversible pseudonyms. No reverse map leaves this closure.
|
||||
* Operate on parsed JSON, never on an RPC envelope or an encoded attachment.
|
||||
*/
|
||||
function createRedactionSession(input) {
|
||||
function createRedactionSession(input, { passthroughUnknownTokens = false } = {}) {
|
||||
const config = normalizeRedactionConfig(input);
|
||||
if (!config.enabled) return Object.freeze({ redact: (value) => value, restore: (value) => value });
|
||||
|
||||
@@ -166,7 +167,11 @@ function createRedactionSession(input) {
|
||||
const aliases = [];
|
||||
if (acceptExistingTokens) {
|
||||
value = source.replace(RESERVED_TOKEN, (token, start) => {
|
||||
if (!originals.has(token)) throw new Error(TOKEN_ERROR);
|
||||
if (!originals.has(token)) {
|
||||
if (!passthroughUnknownTokens) throw new Error(TOKEN_ERROR);
|
||||
// Loose or unclosed reserved text must still be scanned for secrets.
|
||||
if (!PLACEHOLDER_TOKEN.test(token)) return token;
|
||||
}
|
||||
if (++budget.ranges > MAX_NODES) throw new Error(VALUE_ERROR);
|
||||
aliases.push({ start, end: start + token.length, token });
|
||||
// Keep offsets and credential context around aliases. In particular,
|
||||
@@ -210,8 +215,10 @@ function createRedactionSession(input) {
|
||||
|
||||
// Source text that resembles a token must survive a one-pass round trip.
|
||||
// Do not remember these literals as credentials or scan replacement tokens.
|
||||
for (const match of value.matchAll(RESERVED_TOKEN)) {
|
||||
add(match.index, match.index + match[0].length, "SECRET", false);
|
||||
if (!acceptExistingTokens) {
|
||||
for (const match of value.matchAll(RESERVED_TOKEN)) {
|
||||
add(match.index, match.index + match[0].length, "SECRET", false);
|
||||
}
|
||||
}
|
||||
if (value && (inheritedSecret || secretKey(key))) add(0, value.length);
|
||||
matches(/-----BEGIN ([A-Z0-9 ]*PRIVATE KEY)-----[\s\S]*?-----END \1-----/gd, () => 0);
|
||||
@@ -391,11 +398,18 @@ function createRedactionSession(input) {
|
||||
), "", false, state(preserveRootKeys));
|
||||
}
|
||||
|
||||
function restore(value) {
|
||||
function restore(value, { strict = false } = {}) {
|
||||
return walk(value, (text) => {
|
||||
if (originals.has(text)) return originals.get(text);
|
||||
return text.replace(RESERVED_TOKEN, (token) => {
|
||||
if (!originals.has(token)) throw new Error(TOKEN_ERROR);
|
||||
if (!originals.has(token)) {
|
||||
if (passthroughUnknownTokens && !strict) {
|
||||
// A malformed prefix can swallow an issued alias up to its closing bracket.
|
||||
return token.replace(/\[NC_[a-f0-9]{12}_(?:IP|HOST|SECRET)_\d+\]/g,
|
||||
(alias) => originals.has(alias) ? String(originals.get(alias)) : alias);
|
||||
}
|
||||
throw new Error(TOKEN_ERROR);
|
||||
}
|
||||
// A replacement is not scanned again, including a source token literal.
|
||||
return String(originals.get(token));
|
||||
});
|
||||
@@ -414,7 +428,7 @@ function createRedactionSession(input) {
|
||||
}
|
||||
return Object.freeze({
|
||||
redact: (value, options) => safeTransform(redact, value, options),
|
||||
restore: (value) => safeTransform(restore, value),
|
||||
restore: (value, options) => safeTransform(restore, value, options),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -256,6 +256,47 @@ test("managed aliases stay intact alongside new secrets and do not become learne
|
||||
assert.equal(session.redact(token, { acceptExistingTokens: true }), token);
|
||||
});
|
||||
|
||||
test("AI opt-in keeps unknown aliases opaque alongside known tokens and new secrets", () => {
|
||||
const session = createRedactionSession({ enabled: true }, { passthroughUnknownTokens: true });
|
||||
const known = session.redact("8.8.8.8");
|
||||
const foreign = enabledSession().redact("1.1.1.1");
|
||||
for (const unknown of [foreign, "[NC_unknown]", "[NC_unclosed", known.replace("_IP_", "_HOST_")]) {
|
||||
const source = { [unknown]: [`${known} ${unknown}`, unknown] };
|
||||
assert.deepEqual(session.restore(source), { [unknown]: [`8.8.8.8 ${unknown}`, unknown] });
|
||||
assert.equal(session.restore(`[NC_x ${known} ${unknown}]`), `[NC_x 8.8.8.8 ${unknown}]`);
|
||||
assert.equal(session.restore(`[NC_x ${unknown} ${known}]`), `[NC_x ${unknown} 8.8.8.8]`);
|
||||
assert.deepEqual(session.redact(source, { acceptExistingTokens: true }), source);
|
||||
const masked = session.redact({ password: `raw-prefix${unknown}` }, { acceptExistingTokens: true });
|
||||
// Malformed literals inside a password value are credential text too.
|
||||
if (TOKEN.test(unknown)) assert.equal(masked.password.includes(unknown), true);
|
||||
else assert.match(masked.password, TOKEN);
|
||||
assert.equal(masked.password.includes("raw-prefix"), false);
|
||||
assert.deepEqual(session.restore(masked), { password: `raw-prefix${unknown}` });
|
||||
}
|
||||
});
|
||||
|
||||
test("AI opt-in scans credentials, IPs and custom patterns inside malformed token spans", () => {
|
||||
for (const prefix of ["[NC_unclosed", "[NC_x"]) {
|
||||
for (const address of ["8.8.8.8", "10.0.0.8"]) {
|
||||
const session = createRedactionSession({
|
||||
enabled: true, redactPrivateIps: true, patterns: ["ACCOUNT-[0-9]+"],
|
||||
}, { passthroughUnknownTokens: true });
|
||||
const suffix = prefix === "[NC_x" ? "]" : "";
|
||||
const source = `${prefix} password=hunter2 host=${address} ACCOUNT-123${suffix}`;
|
||||
const masked = session.redact(source, { acceptExistingTokens: true });
|
||||
assert.equal(masked.startsWith(`${prefix} password=`), true);
|
||||
assert.equal(masked.includes("hunter2"), false);
|
||||
assert.equal(masked.includes(address), false);
|
||||
assert.equal(masked.includes("ACCOUNT-123"), false);
|
||||
assert.match(masked, /password=\[NC_[a-f0-9]{12}_SECRET_\d+\]/);
|
||||
assert.match(masked, /host=\[NC_[a-f0-9]{12}_IP_\d+\]/);
|
||||
assert.equal(session.restore(masked), source);
|
||||
assert.throws(() => enabledSession().redact(source, { acceptExistingTokens: true }),
|
||||
/Unknown External MCP redaction token/);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("managed aliases do not break credential or custom-pattern context around raw fragments", () => {
|
||||
const session = enabledSession({ patterns: ["SENSITIVE-BEGIN[\\s\\S]*?SENSITIVE-END"] });
|
||||
const token = session.redact("8.8.8.8");
|
||||
@@ -325,6 +366,7 @@ test("unknown, modified, cross-session tokens and tokens in object keys fail clo
|
||||
const issued = session.redact("8.8.8.8");
|
||||
for (const unknown of [
|
||||
"[NC_unknown_IP_1]", "[NC_unclosed", issued.replace("_IP_", "_HOST_"), `${issued.slice(0, -1)}0]`,
|
||||
`[NC_x ${issued}]`, `[NC_unclosed ${issued}`,
|
||||
]) {
|
||||
assert.throws(() => session.restore(`ping ${unknown}`), /Unknown External MCP redaction token/);
|
||||
assert.throws(() => session.restore({ [unknown]: "test" }), /Unknown External MCP redaction token/);
|
||||
|
||||
@@ -4078,6 +4078,45 @@
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"ViewOpenLimits": {
|
||||
"const": {
|
||||
"maxParamsBytes": 16384
|
||||
}
|
||||
},
|
||||
"ViewOpenParams": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"viewId"
|
||||
],
|
||||
"properties": {
|
||||
"viewId": {
|
||||
"$ref": "#/$defs/ContributionId"
|
||||
},
|
||||
"params": {
|
||||
"$ref": "#/$defs/JsonValue"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"ViewOpenResult": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"opened",
|
||||
"focused"
|
||||
],
|
||||
"properties": {
|
||||
"opened": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"focused": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"location": {
|
||||
"$ref": "#/$defs/ViewLocation"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"PluginViewBadge": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
@@ -4261,6 +4300,27 @@
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"required": [
|
||||
"kind",
|
||||
"instanceId"
|
||||
],
|
||||
"properties": {
|
||||
"kind": {
|
||||
"const": "host-ui.activate"
|
||||
},
|
||||
"instanceId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 128
|
||||
},
|
||||
"params": {
|
||||
"$ref": "#/$defs/JsonValue"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
@@ -17,7 +17,7 @@ class HostDrawnViewHost {
|
||||
this.permissionEngine = permissionEngine ?? null;
|
||||
this.runtimePool = runtimePool ?? null;
|
||||
this.electron = electron; this.contributions = contributionService; this.isLocked = isLocked;
|
||||
this.instances = new Map(); this.opening = new Map(); this.closed = false;
|
||||
this.instances = new Map(); this.opening = new Map(); this.activationWaiters = new Set(); this.closed = false;
|
||||
this.messageSubscription = contributionService.onDidPostViewMessage((event) => this.receive(event));
|
||||
this.changeSubscription = contributionService.onDidChange?.((event) => {
|
||||
for (const instance of [...this.instances.values()]) {
|
||||
@@ -31,6 +31,7 @@ class HostDrawnViewHost {
|
||||
});
|
||||
this.unsubscribeLock = subscribeLock?.((state) => {
|
||||
if (!state.locked) return;
|
||||
this.#rejectActivationWaiters(new Error("Application is locked"));
|
||||
for (const opening of this.opening.values()) opening.cancelled = true;
|
||||
for (const id of [...this.instances.keys()]) void this.close(id, undefined, "app-locked");
|
||||
});
|
||||
@@ -68,7 +69,7 @@ class HostDrawnViewHost {
|
||||
const activation = { pluginId: plugin.id, pluginVersion: plugin.activeVersion, viewId: view.id, runtimeId: identity.runtimeId };
|
||||
this.contributions.assertViewActivationCurrent(activation, { context: payload.context });
|
||||
const instance = { id, sender, owner, pluginId: plugin.id, viewId: view.id, activation,
|
||||
context: structuredClone(payload.context ?? {}), identity, sequence: 0, lastRawCss: null, lastCanonicalCss: "", rateStart: Date.now(), rateCount: 0, ownerClosed: () => { void this.close(id, undefined, "owner-closed"); },
|
||||
context: structuredClone(payload.context ?? {}), identity, ready: false, sequence: 0, lastRawCss: null, lastCanonicalCss: "", rateStart: Date.now(), rateCount: 0, ownerClosed: () => { void this.close(id, undefined, "owner-closed"); },
|
||||
rendererGone: () => { void this.close(id, undefined, "renderer-gone"); }, navigating: null };
|
||||
instance.navigating = (details, _url, isInPlace, isMainFrame) => {
|
||||
if ((details?.isMainFrame ?? isMainFrame) !== false && (details?.isSameDocument ?? isInPlace) !== true) instance.rendererGone();
|
||||
@@ -80,6 +81,8 @@ class HostDrawnViewHost {
|
||||
ensure();
|
||||
this.contributions.assertViewActivationCurrent(activation, { context: payload.context });
|
||||
if (this.instances.get(id) !== instance) throw new Error("Plugin view opening was cancelled");
|
||||
instance.ready = true;
|
||||
this.#notifyInstanceReady(instance);
|
||||
return { instanceId: id };
|
||||
} catch (error) {
|
||||
await this.close(id, undefined, "open-failed");
|
||||
@@ -200,8 +203,92 @@ class HostDrawnViewHost {
|
||||
message: { kind: "host-ui.close", instanceId: id } }, { expectedIdentity: instance.identity });
|
||||
} catch { /* runtime may already have stopped */ }
|
||||
}
|
||||
#notifyInstanceReady(instance) {
|
||||
for (const waiter of [...this.activationWaiters]) {
|
||||
if (
|
||||
waiter.pluginId === instance.pluginId
|
||||
&& waiter.viewId === instance.viewId
|
||||
&& (!waiter.sender || waiter.sender === instance.sender)
|
||||
) {
|
||||
waiter.finish(null, instance);
|
||||
}
|
||||
}
|
||||
}
|
||||
#rejectActivationWaiters(error) {
|
||||
for (const waiter of [...this.activationWaiters]) {
|
||||
waiter.finish(error);
|
||||
}
|
||||
}
|
||||
#waitForInstanceReady({ pluginId, viewId, sender, timeoutMs, signal }) {
|
||||
if (this.closed || this.isLocked()) return Promise.reject(new Error("Plugin view host is unavailable"));
|
||||
if (signal?.aborted) return Promise.reject(signal.reason ?? new Error("Plugin view activation was cancelled"));
|
||||
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return Promise.resolve(null);
|
||||
return new Promise((resolve, reject) => {
|
||||
const waiter = {
|
||||
pluginId,
|
||||
viewId,
|
||||
sender,
|
||||
timer: null,
|
||||
onAbort: null,
|
||||
finish(error, value) {
|
||||
if (!this.active) return;
|
||||
this.active = false;
|
||||
if (this.timer) clearTimeout(this.timer);
|
||||
if (this.onAbort) signal?.removeEventListener("abort", this.onAbort);
|
||||
host.activationWaiters.delete(this);
|
||||
if (error) reject(error);
|
||||
else resolve(value);
|
||||
},
|
||||
active: true,
|
||||
};
|
||||
const host = this;
|
||||
waiter.onAbort = () => waiter.finish(signal?.reason ?? new Error("Plugin view activation was cancelled"));
|
||||
signal?.addEventListener("abort", waiter.onAbort, { once: true });
|
||||
waiter.timer = setTimeout(() => waiter.finish(null, null), timeoutMs);
|
||||
this.activationWaiters.add(waiter);
|
||||
});
|
||||
}
|
||||
async activateViewInstances({ pluginId, viewId, sender = null, params, hasParams = false, timeoutMs = 10_000, signal } = {}) {
|
||||
if (this.closed || this.isLocked()) throw new Error("Plugin view host is unavailable");
|
||||
if (typeof pluginId !== "string" || typeof viewId !== "string" || !viewId.startsWith(`${pluginId}.`)) {
|
||||
throw new TypeError("Invalid plugin view activation target");
|
||||
}
|
||||
const matchingReady = () => [...this.instances.values()].filter((instance) => (
|
||||
instance.ready
|
||||
&& instance.pluginId === pluginId
|
||||
&& instance.viewId === viewId
|
||||
&& (!sender || instance.sender === sender)
|
||||
));
|
||||
let targets = matchingReady();
|
||||
if (targets.length === 0) {
|
||||
const instance = await this.#waitForInstanceReady({ pluginId, viewId, sender, timeoutMs, signal });
|
||||
if (instance) targets = [instance];
|
||||
}
|
||||
if (targets.length === 0) return { activated: 0 };
|
||||
let activated = 0;
|
||||
for (const instance of targets) {
|
||||
if (this.closed || this.isLocked() || this.instances.get(instance.id) !== instance) continue;
|
||||
this.contributions.assertViewActivationCurrent(instance.activation, { context: instance.context });
|
||||
const message = {
|
||||
kind: "host-ui.activate",
|
||||
instanceId: instance.id,
|
||||
...(hasParams ? { params: structuredClone(params) } : {}),
|
||||
};
|
||||
if (!validateMessage(message)) throw new TypeError("Invalid plugin view activate message");
|
||||
await this.contributions.runtimeSupervisor.notify(
|
||||
instance.pluginId,
|
||||
"plugin.view.message",
|
||||
{ viewId: instance.viewId, message },
|
||||
{ expectedIdentity: instance.identity },
|
||||
);
|
||||
activated += 1;
|
||||
}
|
||||
return { activated };
|
||||
}
|
||||
async shutdown() {
|
||||
this.closed = true; for (const opening of this.opening.values()) opening.cancelled = true;
|
||||
this.closed = true;
|
||||
this.#rejectActivationWaiters(new Error("Plugin view host shutting down"));
|
||||
for (const opening of this.opening.values()) opening.cancelled = true;
|
||||
await Promise.all([...this.instances.keys()].map((id) => this.close(id, undefined, "shutdown")));
|
||||
this.messageSubscription?.dispose(); this.changeSubscription?.dispose(); this.unsubscribeLock?.();
|
||||
this.resources?.dispose?.();
|
||||
|
||||
@@ -239,3 +239,69 @@ test("transient resource decode failures are evicted so retries can succeed", as
|
||||
assert.equal(calls, 2);
|
||||
await f.host.shutdown();
|
||||
});
|
||||
|
||||
test("activateViewInstances delivers host-ui.activate to reused and newly created instances without changing host-ui.open", async () => {
|
||||
// 1. Existing retained instance receives host-ui.activate with and without params
|
||||
const f1 = fixture();
|
||||
await open(f1);
|
||||
assert.equal(f1.notifications.length, 1);
|
||||
assert.equal(f1.notifications[0][2].message.kind, "host-ui.open");
|
||||
assert.equal("params" in f1.notifications[0][2].message, false);
|
||||
|
||||
const reusedWithParams = await f1.host.activateViewInstances({
|
||||
pluginId: "com.test.plugin",
|
||||
viewId: "com.test.plugin.view",
|
||||
sender: f1.sender,
|
||||
hasParams: true,
|
||||
params: { connectionId: "db-1" },
|
||||
});
|
||||
assert.deepEqual(reusedWithParams, { activated: 1 });
|
||||
assert.deepEqual(f1.notifications.at(-1)[2], {
|
||||
viewId: "com.test.plugin.view",
|
||||
message: { kind: "host-ui.activate", instanceId: "instance-1", params: { connectionId: "db-1" } },
|
||||
});
|
||||
|
||||
const reusedWithoutParams = await f1.host.activateViewInstances({
|
||||
pluginId: "com.test.plugin",
|
||||
viewId: "com.test.plugin.view",
|
||||
sender: f1.sender,
|
||||
hasParams: false,
|
||||
});
|
||||
assert.deepEqual(reusedWithoutParams, { activated: 1 });
|
||||
assert.deepEqual(f1.notifications.at(-1)[2], {
|
||||
viewId: "com.test.plugin.view",
|
||||
message: { kind: "host-ui.activate", instanceId: "instance-1" },
|
||||
});
|
||||
|
||||
// Wrong window sender receives 0 activations after bounded wait
|
||||
const wrongWindow = await f1.host.activateViewInstances({
|
||||
pluginId: "com.test.plugin",
|
||||
viewId: "com.test.plugin.view",
|
||||
sender: f1.other,
|
||||
hasParams: false,
|
||||
timeoutMs: 20,
|
||||
});
|
||||
assert.deepEqual(wrongWindow, { activated: 0 });
|
||||
await f1.host.shutdown();
|
||||
|
||||
// 2. Newly created instance opened asynchronously receives host-ui.open followed by host-ui.activate
|
||||
const f2 = fixture();
|
||||
const pendingActivation = f2.host.activateViewInstances({
|
||||
pluginId: "com.test.plugin",
|
||||
viewId: "com.test.plugin.view",
|
||||
sender: f2.sender,
|
||||
hasParams: true,
|
||||
params: { connectionId: "db-2" },
|
||||
timeoutMs: 500,
|
||||
});
|
||||
setTimeout(() => { void open(f2); }, 15);
|
||||
const freshResult = await pendingActivation;
|
||||
assert.deepEqual(freshResult, { activated: 1 });
|
||||
assert.equal(f2.notifications.length, 2);
|
||||
assert.equal(f2.notifications[0][2].message.kind, "host-ui.open");
|
||||
assert.deepEqual(f2.notifications[1][2], {
|
||||
viewId: "com.test.plugin.view",
|
||||
message: { kind: "host-ui.activate", instanceId: "instance-1", params: { connectionId: "db-2" } },
|
||||
});
|
||||
await f2.host.shutdown();
|
||||
});
|
||||
@@ -17,6 +17,7 @@ const { PluginCredentialBroker, assertLeaseParams } = require("./credentialBroke
|
||||
const { PluginCredentialCatalog } = require("./credentialCatalog.cjs");
|
||||
const { PluginContributionService } = require("./contributionService.cjs");
|
||||
const { PluginViewBadgeService } = require("./viewBadgeService.cjs");
|
||||
const { PluginViewOpenService } = require("./viewOpenService.cjs");
|
||||
const { PluginViewResources } = require("./viewResourceService.cjs");
|
||||
const { HostDrawnViewHost } = require("./hostDrawnViewHost.cjs");
|
||||
const { createPooledContributionIconRasterizer } = require("./contributionIconRasterizer.cjs");
|
||||
@@ -137,6 +138,7 @@ function createPluginHostService(options) {
|
||||
let permissionDecisionHost;
|
||||
let browserRuntimePool;
|
||||
let viewBadgeService;
|
||||
let viewOpenService;
|
||||
let aiSidebarService;
|
||||
let manager;
|
||||
const logService = new PluginLogService({ paths, electron: options.electron, resolveProvenance: options.resolvePluginProvenance ?? createPluginLogProvenanceResolver(database) });
|
||||
@@ -604,6 +606,14 @@ function createPluginHostService(options) {
|
||||
subscribeLock: options.subscribeAppLock,
|
||||
})
|
||||
: null;
|
||||
viewOpenService = new PluginViewOpenService({
|
||||
vaultDataBridge,
|
||||
hostDrawnViewHost,
|
||||
supportedFeatures,
|
||||
getWindow: options.getInteractionWindow,
|
||||
isLocked: options.isAppLocked,
|
||||
});
|
||||
viewOpenService.registerRpcCapabilities(rpcRegistry);
|
||||
const themeService = new PluginThemeService({database,packageStore,contributionService});
|
||||
manager = new PluginManager({
|
||||
secretStore,
|
||||
@@ -615,6 +625,7 @@ function createPluginHostService(options) {
|
||||
beforeClose: async () => {
|
||||
try {
|
||||
viewBadgeService?.shutdown();
|
||||
viewOpenService?.shutdown();
|
||||
aiSidebarService?.shutdown();
|
||||
themeService.shutdown();
|
||||
capabilitiesService?.shutdown();
|
||||
@@ -682,10 +693,12 @@ function createPluginHostService(options) {
|
||||
terminalDataPipelineService,
|
||||
hostDrawnViewHost,
|
||||
viewBadgeService,
|
||||
viewOpenService,
|
||||
aiSidebarService,
|
||||
};
|
||||
} catch (error) {
|
||||
try { viewBadgeService?.shutdown(); } catch {}
|
||||
try { viewOpenService?.shutdown(); } catch {}
|
||||
try { aiSidebarService?.shutdown(); } catch {}
|
||||
try { browserRuntimePool?.dispose(); } catch {}
|
||||
try { permissionDecisionHost?.shutdown(); } catch {}
|
||||
|
||||
@@ -35,6 +35,7 @@ const ALLOWED_KINDS = new Set([
|
||||
"terminals.openLocal",
|
||||
"workspace.listTabs",
|
||||
"workspace.focusTab",
|
||||
"views.open",
|
||||
]);
|
||||
|
||||
/**
|
||||
|
||||
@@ -349,6 +349,12 @@ function createEmitter() {
|
||||
|
||||
const FILE_CHUNK_BYTES = 2 * 1024 * 1024;
|
||||
const FILE_DIALOG_DEADLINE_MS = 300_000;
|
||||
const VIEW_OPEN_FEATURES = Object.freeze([
|
||||
"views.host-drawn",
|
||||
"views.vault-pages",
|
||||
"views.terminal-sidebar",
|
||||
]);
|
||||
const VIEW_OPEN_MAX_PARAMS_BYTES = 16_384;
|
||||
|
||||
function bytesToBase64(bytes) {
|
||||
if (typeof Buffer === "function") return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
|
||||
@@ -912,6 +918,43 @@ function createPluginContext(config, client, runtimeApi) {
|
||||
}
|
||||
return client.request("views.setBadge", params).then(() => undefined);
|
||||
},
|
||||
async open(options) {
|
||||
if (!VIEW_OPEN_FEATURES.some((feature) => config.enabledFeatures?.includes(feature))) {
|
||||
throw new PluginError(
|
||||
"unsupported",
|
||||
"Required view feature is not enabled: views.host-drawn, views.vault-pages, or views.terminal-sidebar",
|
||||
);
|
||||
}
|
||||
if (!options || typeof options !== "object" || Array.isArray(options)) {
|
||||
throw new PluginError("invalid_argument", "Plugin view open parameters must be an object");
|
||||
}
|
||||
for (const key of Object.keys(options)) {
|
||||
if (key !== "viewId" && key !== "params") {
|
||||
throw new PluginError("invalid_argument", `Unknown plugin view open parameter: ${key}`);
|
||||
}
|
||||
}
|
||||
const viewId = assertOwnedContributionId(config.pluginId, options.viewId, "Plugin view");
|
||||
const hasParams = Object.hasOwn(options, "params") && options.params !== undefined;
|
||||
if (hasParams) {
|
||||
let serialized;
|
||||
try {
|
||||
serialized = JSON.stringify(options.params);
|
||||
} catch {
|
||||
throw new PluginError("invalid_argument", "Plugin view open params must be valid JSON");
|
||||
}
|
||||
if (serialized === undefined) {
|
||||
throw new PluginError("invalid_argument", "Plugin view open params must be valid JSON");
|
||||
}
|
||||
if (new TextEncoder().encode(serialized).byteLength > VIEW_OPEN_MAX_PARAMS_BYTES) {
|
||||
throw new PluginError("invalid_argument", `Plugin view open params exceed ${VIEW_OPEN_MAX_PARAMS_BYTES} bytes`);
|
||||
}
|
||||
}
|
||||
const result = await client.request("views.open", {
|
||||
viewId,
|
||||
...(hasParams ? { params: options.params } : {}),
|
||||
});
|
||||
return Object.freeze(result);
|
||||
},
|
||||
};
|
||||
const providers = {
|
||||
register(providerId, kind, handler) {
|
||||
|
||||
@@ -645,3 +645,102 @@ test("actual SDK directory call rejects an unnegotiated feature without sending
|
||||
await host.request("plugin.activate", {});
|
||||
assert.equal(requests, 0);
|
||||
});
|
||||
|
||||
test("runtime peer views.open enforces view feature gating, ownership, and payload bounds", async (context) => {
|
||||
const { startPluginRuntime } = await import("./runtime/runtimePeer.mjs");
|
||||
|
||||
// 1. Rejects when no view location feature is enabled without sending host RPC
|
||||
{
|
||||
const { port1, port2 } = new MessageChannel();
|
||||
let rpcCalls = 0;
|
||||
const host = new PluginRpcRouter({
|
||||
pluginId: "com.example.db",
|
||||
send: (message) => port1.postMessage(message),
|
||||
handlers: {
|
||||
"views.open": async () => { rpcCalls += 1; return { opened: true, focused: true, location: "vault-page" }; },
|
||||
},
|
||||
});
|
||||
port1.on("message", (message) => host.accept(message));
|
||||
const peer = await startPluginRuntime({
|
||||
port: port2,
|
||||
config: { pluginId: "com.example.db", pluginVersion: "1.0.0", netcattyVersion: "1.0.0", apiVersion: "0.1.0-internal", enabledFeatures: [] },
|
||||
async loadPlugin() {
|
||||
return {
|
||||
default: {
|
||||
async activate(pluginContext) {
|
||||
await assert.rejects(
|
||||
() => pluginContext.views.open({ viewId: "com.example.db.workbench" }),
|
||||
(error) => error?.code === "unsupported" && /views\./.test(error.message),
|
||||
);
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
context.after(async () => { await peer.dispose(); host.close(); port1.close(); port2.close(); });
|
||||
await host.request("plugin.initialize", { netcattyVersion: "1.0.0", apiVersion: "0.1.0-internal", supportedFeatures: [] });
|
||||
await host.request("plugin.activate", {});
|
||||
assert.equal(rpcCalls, 0);
|
||||
}
|
||||
|
||||
// 2. Happy path forwards params, rejects foreign view ids and oversize payloads
|
||||
{
|
||||
const { port1, port2 } = new MessageChannel();
|
||||
const received = [];
|
||||
const host = new PluginRpcRouter({
|
||||
pluginId: "com.example.db",
|
||||
send: (message) => port1.postMessage(message),
|
||||
handlers: {
|
||||
"views.open": async (params) => {
|
||||
received.push(params);
|
||||
return { opened: true, focused: true, location: "vault-page" };
|
||||
},
|
||||
},
|
||||
});
|
||||
port1.on("message", (message) => host.accept(message));
|
||||
const peer = await startPluginRuntime({
|
||||
port: port2,
|
||||
config: {
|
||||
pluginId: "com.example.db",
|
||||
pluginVersion: "1.0.0",
|
||||
netcattyVersion: "1.0.0",
|
||||
apiVersion: "0.1.0-internal",
|
||||
enabledFeatures: ["views.vault-pages"],
|
||||
},
|
||||
async loadPlugin() {
|
||||
return {
|
||||
default: {
|
||||
async activate(pluginContext) {
|
||||
const result = await pluginContext.views.open({
|
||||
viewId: "com.example.db.workbench",
|
||||
params: { connectionId: "conn-42", autoConnect: true },
|
||||
});
|
||||
assert.deepEqual(result, { opened: true, focused: true, location: "vault-page" });
|
||||
assert.equal(Object.isFrozen(result), true);
|
||||
|
||||
await assert.rejects(
|
||||
() => pluginContext.views.open({ viewId: "com.other.db.workbench" }),
|
||||
(error) => error?.code === "invalid_argument",
|
||||
);
|
||||
await assert.rejects(
|
||||
() => pluginContext.views.open({ viewId: "com.example.db.workbench", params: { blob: "x".repeat(17_000) } }),
|
||||
(error) => error?.code === "invalid_argument",
|
||||
);
|
||||
await assert.rejects(
|
||||
() => pluginContext.views.open({ viewId: "com.example.db.workbench", unknownKey: 1 }),
|
||||
(error) => error?.code === "invalid_argument",
|
||||
);
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
context.after(async () => { await peer.dispose(); host.close(); port1.close(); port2.close(); });
|
||||
await host.request("plugin.initialize", { netcattyVersion: "1.0.0", apiVersion: "0.1.0-internal", supportedFeatures: ["views.vault-pages"] });
|
||||
await host.request("plugin.activate", {});
|
||||
assert.deepEqual(received, [{
|
||||
viewId: "com.example.db.workbench",
|
||||
params: { connectionId: "conn-42", autoConnect: true },
|
||||
}]);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,214 @@
|
||||
"use strict";
|
||||
|
||||
const contractSchema = require("./generated/plugin-contract.schema.json");
|
||||
const { createDefinitionValidator } = require("./contractValidator.cjs");
|
||||
const { assertPluginJsonValue } = require("./jsonBoundary.cjs");
|
||||
const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs");
|
||||
const { invalidArgument, freezeJson } = require("./validationUtils.cjs");
|
||||
|
||||
const VIEW_OPEN_MAX_PARAMS_BYTES = contractSchema.$defs.ViewOpenLimits.const.maxParamsBytes;
|
||||
const VAULT_PAGES_FEATURE = contractSchema.$defs.VaultPagesFeature.const;
|
||||
const TERMINAL_SIDEBAR_FEATURE = contractSchema.$defs.TerminalSidebarFeature.const;
|
||||
const HOST_DRAWN_VIEWS_FEATURE = contractSchema.$defs.HostDrawnViewsFeature.const;
|
||||
const HOST_DRAWN_LOCATIONS = new Set(["tab", "aside", "panel", "modal"]);
|
||||
const DEFAULT_ACTIVATE_TIMEOUT_MS = 10_000;
|
||||
const MAX_ACTIVATE_TIMEOUT_MS = 15_000;
|
||||
|
||||
const validateViewOpenParamsSchema = createDefinitionValidator("ViewOpenParams");
|
||||
|
||||
function isPlainObject(value) {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
||||
const proto = Object.getPrototypeOf(value);
|
||||
return proto === Object.prototype || proto === null;
|
||||
}
|
||||
|
||||
function requiredFeatureForViewLocation(location) {
|
||||
if (location === "vault-page") return VAULT_PAGES_FEATURE;
|
||||
if (location === "terminal-sidebar") return TERMINAL_SIDEBAR_FEATURE;
|
||||
if (HOST_DRAWN_LOCATIONS.has(location)) return HOST_DRAWN_VIEWS_FEATURE;
|
||||
return null;
|
||||
}
|
||||
|
||||
function validateViewOpenParams(rawParams) {
|
||||
if (!isPlainObject(rawParams)) {
|
||||
throw invalidArgument("Plugin view open parameters must be an object");
|
||||
}
|
||||
if (!validateViewOpenParamsSchema(rawParams)) {
|
||||
throw invalidArgument("Invalid parameters for ViewOpenParams");
|
||||
}
|
||||
const hasParams = Object.hasOwn(rawParams, "params") && rawParams.params !== undefined;
|
||||
if (hasParams) {
|
||||
try {
|
||||
assertPluginJsonValue(rawParams.params, { maxBytes: VIEW_OPEN_MAX_PARAMS_BYTES });
|
||||
} catch (error) {
|
||||
throw invalidArgument(
|
||||
error instanceof Error && error.message
|
||||
? error.message
|
||||
: `Plugin view open params exceed ${VIEW_OPEN_MAX_PARAMS_BYTES} bytes`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return Object.freeze({
|
||||
viewId: rawParams.viewId,
|
||||
...(hasParams ? { params: freezeJson(rawParams.params) } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function resolveOwnedView(manifest, viewId, pluginId) {
|
||||
if (typeof viewId !== "string" || !viewId.startsWith(`${pluginId}.`) || viewId.length > 256) {
|
||||
throw new PluginRpcError(RPC_ERRORS.notFound, `Plugin view contribution was not found: ${viewId}`);
|
||||
}
|
||||
const view = manifest?.contributes?.views?.find((item) => item?.id === viewId) ?? null;
|
||||
if (!view) {
|
||||
throw new PluginRpcError(RPC_ERRORS.notFound, `Plugin view contribution was not found: ${viewId}`);
|
||||
}
|
||||
return view;
|
||||
}
|
||||
|
||||
class PluginViewOpenService {
|
||||
constructor(options = {}) {
|
||||
this.getVaultDataBridge = typeof options.getVaultDataBridge === "function"
|
||||
? options.getVaultDataBridge
|
||||
: () => options.vaultDataBridge ?? null;
|
||||
this.getHostDrawnViewHost = typeof options.getHostDrawnViewHost === "function"
|
||||
? options.getHostDrawnViewHost
|
||||
: () => options.hostDrawnViewHost ?? null;
|
||||
this.getWindow = options.getWindow ?? null;
|
||||
this.supportedFeatures = Array.isArray(options.supportedFeatures)
|
||||
? [...options.supportedFeatures]
|
||||
: null;
|
||||
this.isLocked = options.isLocked ?? (() => false);
|
||||
this.activateTimeoutMs = Math.min(
|
||||
Math.max(1, options.activateTimeoutMs ?? DEFAULT_ACTIVATE_TIMEOUT_MS),
|
||||
MAX_ACTIVATE_TIMEOUT_MS,
|
||||
);
|
||||
this.closed = false;
|
||||
}
|
||||
|
||||
#requireFeature(context, feature) {
|
||||
const required = context?.manifest?.features?.required;
|
||||
const optional = context?.manifest?.features?.optional;
|
||||
const declared = (Array.isArray(required) && required.includes(feature))
|
||||
|| (Array.isArray(optional) && optional.includes(feature));
|
||||
if (!declared || (this.supportedFeatures && !this.supportedFeatures.includes(feature))) {
|
||||
throw new PluginRpcError(RPC_ERRORS.unsupported, `Required feature was not negotiated: ${feature}`);
|
||||
}
|
||||
}
|
||||
|
||||
registerRpcCapabilities(registry) {
|
||||
registry.registerRequest("views.open", (params, context) => this.open(params, context), {
|
||||
metadata: { capability: "views", mutating: true, permission: "views" },
|
||||
validateParams: (params) => validateViewOpenParams(params),
|
||||
authorization: (params, context) => {
|
||||
if (this.isLocked()) {
|
||||
throw new PluginRpcError(RPC_ERRORS.failedPrecondition, "Application is locked");
|
||||
}
|
||||
const view = resolveOwnedView(context.manifest, params.viewId, context.pluginId);
|
||||
const feature = requiredFeatureForViewLocation(view.location);
|
||||
if (!feature) {
|
||||
throw new PluginRpcError(RPC_ERRORS.unsupported, `Unsupported plugin view location: ${String(view.location)}`);
|
||||
}
|
||||
this.#requireFeature(context, feature);
|
||||
return {
|
||||
permission: "views",
|
||||
resources: ["*"],
|
||||
reason: "Open and focus a plugin view",
|
||||
operationId: "views.open",
|
||||
};
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async open(params, context) {
|
||||
await context?.assertActive?.();
|
||||
if (this.closed) {
|
||||
throw new PluginRpcError(RPC_ERRORS.unavailable, "Plugin view open service is closed");
|
||||
}
|
||||
if (this.isLocked()) {
|
||||
throw new PluginRpcError(RPC_ERRORS.failedPrecondition, "Application is locked");
|
||||
}
|
||||
const validated = validateViewOpenParams(params);
|
||||
const view = resolveOwnedView(context?.manifest, validated.viewId, context?.pluginId);
|
||||
const feature = requiredFeatureForViewLocation(view.location);
|
||||
if (!feature) {
|
||||
throw new PluginRpcError(RPC_ERRORS.unsupported, `Unsupported plugin view location: ${String(view.location)}`);
|
||||
}
|
||||
this.#requireFeature(context, feature);
|
||||
|
||||
const vaultDataBridge = this.getVaultDataBridge();
|
||||
const hostDrawnViewHost = this.getHostDrawnViewHost();
|
||||
if (!vaultDataBridge || !hostDrawnViewHost) {
|
||||
throw new PluginRpcError(RPC_ERRORS.unavailable, "Plugin view host is unavailable");
|
||||
}
|
||||
|
||||
const shown = await vaultDataBridge.request(
|
||||
"views.open",
|
||||
{ viewId: view.id, location: view.location },
|
||||
context?.signal,
|
||||
);
|
||||
await context?.assertActive?.();
|
||||
if (this.isLocked()) {
|
||||
throw new PluginRpcError(RPC_ERRORS.failedPrecondition, "Application is locked");
|
||||
}
|
||||
if (!shown || shown.opened !== true || shown.focused !== true) {
|
||||
throw new PluginRpcError(RPC_ERRORS.unavailable, `Plugin view could not be opened: ${view.id}`);
|
||||
}
|
||||
|
||||
const ownerWindow = this.getWindow?.() ?? vaultDataBridge.getWindow?.() ?? null;
|
||||
const sender = ownerWindow && !ownerWindow.isDestroyed?.()
|
||||
? (ownerWindow.webContents ?? null)
|
||||
: (vaultDataBridge.owner ?? null);
|
||||
const hasParams = Object.hasOwn(validated, "params") && validated.params !== undefined;
|
||||
|
||||
let activation;
|
||||
try {
|
||||
activation = await hostDrawnViewHost.activateViewInstances({
|
||||
pluginId: context.pluginId,
|
||||
viewId: view.id,
|
||||
sender,
|
||||
hasParams,
|
||||
...(hasParams ? { params: validated.params } : {}),
|
||||
timeoutMs: this.activateTimeoutMs,
|
||||
signal: context?.signal,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof PluginRpcError) throw error;
|
||||
if (context?.signal?.aborted) {
|
||||
throw new PluginRpcError(RPC_ERRORS.cancelled, "Plugin view open was cancelled");
|
||||
}
|
||||
if (this.isLocked()) {
|
||||
throw new PluginRpcError(RPC_ERRORS.failedPrecondition, "Application is locked");
|
||||
}
|
||||
throw new PluginRpcError(
|
||||
RPC_ERRORS.unavailable,
|
||||
error instanceof Error && error.message
|
||||
? error.message.slice(0, 256)
|
||||
: `Plugin view could not be activated: ${view.id}`,
|
||||
);
|
||||
}
|
||||
await context?.assertActive?.();
|
||||
if (!activation || !(activation.activated >= 1)) {
|
||||
throw new PluginRpcError(RPC_ERRORS.unavailable, `Plugin view did not open in the main window: ${view.id}`);
|
||||
}
|
||||
|
||||
return Object.freeze({
|
||||
opened: true,
|
||||
focused: true,
|
||||
location: view.location,
|
||||
});
|
||||
}
|
||||
|
||||
shutdown() {
|
||||
this.closed = true;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_ACTIVATE_TIMEOUT_MS,
|
||||
HOST_DRAWN_LOCATIONS,
|
||||
PluginViewOpenService,
|
||||
VIEW_OPEN_MAX_PARAMS_BYTES,
|
||||
requiredFeatureForViewLocation,
|
||||
resolveOwnedView,
|
||||
validateViewOpenParams,
|
||||
};
|
||||
@@ -0,0 +1,217 @@
|
||||
"use strict";
|
||||
|
||||
const assert = require("node:assert/strict");
|
||||
const test = require("node:test");
|
||||
|
||||
const { PluginHostRpcRegistry } = require("./hostRpcRegistry.cjs");
|
||||
const { PluginViewOpenService, VIEW_OPEN_MAX_PARAMS_BYTES } = require("./viewOpenService.cjs");
|
||||
const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs");
|
||||
|
||||
function makeContext(overrides = {}) {
|
||||
const pluginId = overrides.pluginId ?? "com.example.database";
|
||||
return {
|
||||
pluginId,
|
||||
pluginVersion: "1.0.0",
|
||||
runtimeId: overrides.runtimeId ?? "runtime-1",
|
||||
signal: overrides.signal,
|
||||
assertActive: overrides.assertActive ?? (async () => {}),
|
||||
manifest: overrides.manifest ?? {
|
||||
id: pluginId,
|
||||
features: {
|
||||
required: overrides.requiredFeatures ?? ["views.host-drawn", "views.vault-pages", "views.terminal-sidebar"],
|
||||
optional: overrides.optionalFeatures ?? [],
|
||||
},
|
||||
contributes: {
|
||||
views: [
|
||||
{ id: `${pluginId}.workbench`, title: "Database", location: "vault-page" },
|
||||
{ id: `${pluginId}.connection`, title: "Connection", location: "modal" },
|
||||
{ id: `${pluginId}.sidebar`, title: "Sidebar", location: "terminal-sidebar" },
|
||||
{ id: `${pluginId}.tab`, title: "Tab", location: "tab" },
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function makeHarness(options = {}) {
|
||||
const bridgeCalls = [];
|
||||
const activateCalls = [];
|
||||
let locked = Boolean(options.locked);
|
||||
const sender = { isDestroyed: () => false };
|
||||
const win = { webContents: sender, isDestroyed: () => false };
|
||||
const vaultDataBridge = options.vaultDataBridge ?? {
|
||||
owner: sender,
|
||||
getWindow: () => win,
|
||||
async request(kind, payload) {
|
||||
bridgeCalls.push({ kind, payload });
|
||||
if (options.bridgeError) throw options.bridgeError;
|
||||
return options.bridgeResult ?? { opened: true, focused: true, location: payload.location };
|
||||
},
|
||||
};
|
||||
const hostDrawnViewHost = options.hostDrawnViewHost ?? {
|
||||
async activateViewInstances(call) {
|
||||
activateCalls.push(call);
|
||||
if (options.activateError) throw options.activateError;
|
||||
return options.activateResult ?? { activated: 1 };
|
||||
},
|
||||
};
|
||||
const service = new PluginViewOpenService({
|
||||
vaultDataBridge,
|
||||
hostDrawnViewHost,
|
||||
supportedFeatures: options.supportedFeatures ?? ["views.host-drawn", "views.vault-pages", "views.terminal-sidebar"],
|
||||
getWindow: () => win,
|
||||
isLocked: () => locked,
|
||||
activateTimeoutMs: options.activateTimeoutMs ?? 50,
|
||||
});
|
||||
return {
|
||||
service,
|
||||
bridgeCalls,
|
||||
activateCalls,
|
||||
sender,
|
||||
setLocked(next) { locked = next; },
|
||||
};
|
||||
}
|
||||
|
||||
test("PluginViewOpenService opens own vault-page, delivers activation params, and returns honest result", async () => {
|
||||
const h = makeHarness();
|
||||
const ctx = makeContext();
|
||||
|
||||
const withParams = await h.service.open({
|
||||
viewId: "com.example.database.workbench",
|
||||
params: { connectionId: "conn-1", action: "connect" },
|
||||
}, ctx);
|
||||
assert.deepEqual(withParams, { opened: true, focused: true, location: "vault-page" });
|
||||
assert.deepEqual(h.bridgeCalls, [
|
||||
{ kind: "views.open", payload: { viewId: "com.example.database.workbench", location: "vault-page" } },
|
||||
]);
|
||||
assert.equal(h.activateCalls.length, 1);
|
||||
assert.equal(h.activateCalls[0].pluginId, "com.example.database");
|
||||
assert.equal(h.activateCalls[0].viewId, "com.example.database.workbench");
|
||||
assert.equal(h.activateCalls[0].sender, h.sender);
|
||||
assert.equal(h.activateCalls[0].hasParams, true);
|
||||
assert.deepEqual(h.activateCalls[0].params, { connectionId: "conn-1", action: "connect" });
|
||||
|
||||
// Omitting params sets hasParams=false and still delivers host-ui.activate
|
||||
const withoutParams = await h.service.open({ viewId: "com.example.database.connection" }, ctx);
|
||||
assert.deepEqual(withoutParams, { opened: true, focused: true, location: "modal" });
|
||||
assert.equal(h.activateCalls[1].hasParams, false);
|
||||
assert.equal("params" in h.activateCalls[1], false);
|
||||
});
|
||||
|
||||
test("PluginViewOpenService rejects other plugin's view and undeclared own view with notFound", async () => {
|
||||
const h = makeHarness();
|
||||
const ctx = makeContext();
|
||||
|
||||
await assert.rejects(
|
||||
() => h.service.open({ viewId: "com.other.plugin.workbench" }, ctx),
|
||||
(err) => err?.code === RPC_ERRORS.notFound,
|
||||
);
|
||||
await assert.rejects(
|
||||
() => h.service.open({ viewId: "com.example.database.nonexistent" }, ctx),
|
||||
(err) => err?.code === RPC_ERRORS.notFound,
|
||||
);
|
||||
assert.equal(h.bridgeCalls.length, 0);
|
||||
assert.equal(h.activateCalls.length, 0);
|
||||
});
|
||||
|
||||
test("PluginViewOpenService enforces location-specific feature negotiation", async () => {
|
||||
const h = makeHarness();
|
||||
|
||||
// vault-page requires views.vault-pages
|
||||
await assert.rejects(
|
||||
() => h.service.open({ viewId: "com.example.database.workbench" }, makeContext({ requiredFeatures: ["views.host-drawn"] })),
|
||||
(err) => err?.code === RPC_ERRORS.unsupported && err.message.includes("views.vault-pages"),
|
||||
);
|
||||
|
||||
// terminal-sidebar requires views.terminal-sidebar
|
||||
await assert.rejects(
|
||||
() => h.service.open({ viewId: "com.example.database.sidebar" }, makeContext({ requiredFeatures: ["views.host-drawn", "views.vault-pages"] })),
|
||||
(err) => err?.code === RPC_ERRORS.unsupported && err.message.includes("views.terminal-sidebar"),
|
||||
);
|
||||
|
||||
// modal / tab require views.host-drawn
|
||||
await assert.rejects(
|
||||
() => h.service.open({ viewId: "com.example.database.connection" }, makeContext({ requiredFeatures: ["views.vault-pages"] })),
|
||||
(err) => err?.code === RPC_ERRORS.unsupported && err.message.includes("views.host-drawn"),
|
||||
);
|
||||
|
||||
// Host without views.vault-pages supported also rejects even if manifest lists it as optional
|
||||
const unsupportedHost = makeHarness({ supportedFeatures: ["views.host-drawn"] });
|
||||
await assert.rejects(
|
||||
() => unsupportedHost.service.open(
|
||||
{ viewId: "com.example.database.workbench" },
|
||||
makeContext({ requiredFeatures: ["views.host-drawn"], optionalFeatures: ["views.vault-pages"] }),
|
||||
),
|
||||
(err) => err?.code === RPC_ERRORS.unsupported && err.message.includes("views.vault-pages"),
|
||||
);
|
||||
assert.equal(h.bridgeCalls.length, 0);
|
||||
});
|
||||
|
||||
test("PluginViewOpenService rejects locked app with failedPrecondition and malformed/oversize params with invalidArgument", async () => {
|
||||
const h = makeHarness({ locked: true });
|
||||
const ctx = makeContext();
|
||||
|
||||
await assert.rejects(
|
||||
() => h.service.open({ viewId: "com.example.database.workbench" }, ctx),
|
||||
(err) => err?.code === RPC_ERRORS.failedPrecondition && /locked/i.test(err.message),
|
||||
);
|
||||
|
||||
h.setLocked(false);
|
||||
for (const invalid of [
|
||||
null,
|
||||
{},
|
||||
{ viewId: "" },
|
||||
{ viewId: "com.example.database.workbench", extra: true },
|
||||
{ viewId: "com.example.database.workbench", params: { blob: "x".repeat(VIEW_OPEN_MAX_PARAMS_BYTES + 1) } },
|
||||
]) {
|
||||
await assert.rejects(
|
||||
() => h.service.open(invalid, ctx),
|
||||
(err) => err?.code === RPC_ERRORS.invalidArgument,
|
||||
);
|
||||
}
|
||||
assert.equal(h.bridgeCalls.length, 0);
|
||||
});
|
||||
|
||||
test("PluginViewOpenService fails honestly with unavailable when surface or live instance does not appear", async () => {
|
||||
const noInstance = makeHarness({ activateResult: { activated: 0 } });
|
||||
await assert.rejects(
|
||||
() => noInstance.service.open({ viewId: "com.example.database.workbench" }, makeContext()),
|
||||
(err) => err?.code === RPC_ERRORS.unavailable,
|
||||
);
|
||||
|
||||
const bridgeFailed = makeHarness({
|
||||
bridgeError: new PluginRpcError(RPC_ERRORS.unavailable, "Vault data host is unavailable"),
|
||||
});
|
||||
await assert.rejects(
|
||||
() => bridgeFailed.service.open({ viewId: "com.example.database.workbench" }, makeContext()),
|
||||
(err) => err?.code === RPC_ERRORS.unavailable,
|
||||
);
|
||||
});
|
||||
|
||||
test("PluginViewOpenService registers views.open under views permission without requiring workspace permissions", async () => {
|
||||
const h = makeHarness();
|
||||
const registry = new PluginHostRpcRegistry();
|
||||
const authRequests = [];
|
||||
registry.use(async (ctx, next) => {
|
||||
authRequests.push(ctx.authorization);
|
||||
return next();
|
||||
});
|
||||
h.service.registerRpcCapabilities(registry);
|
||||
|
||||
const ctx = makeContext({ requiredFeatures: ["views.vault-pages"] });
|
||||
const routes = registry.createRoutes({
|
||||
pluginId: ctx.pluginId,
|
||||
pluginVersion: ctx.pluginVersion,
|
||||
runtimeId: ctx.runtimeId,
|
||||
runtimeKind: "browser",
|
||||
manifest: ctx.manifest,
|
||||
});
|
||||
|
||||
const result = await routes.requestHandlers["views.open"](
|
||||
{ viewId: "com.example.database.workbench", params: { connectionId: "db-1" } },
|
||||
{},
|
||||
);
|
||||
assert.deepEqual(result, { opened: true, focused: true, location: "vault-page" });
|
||||
assert.equal(authRequests.length, 1);
|
||||
assert.equal(authRequests[0].permission, "views");
|
||||
});
|
||||
@@ -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");
|
||||
},
|
||||
|
||||
@@ -11,7 +11,6 @@ const SESSION_ERROR = "AI privacy session is unavailable or its settings changed
|
||||
const SESSION_ID_ERROR = "AI privacy requires a valid chat session";
|
||||
const LIMIT_ERROR = "AI privacy session limit reached; close a chat and try again";
|
||||
const VALUE_ERROR = "AI privacy could not safely process this value";
|
||||
const TOKEN_ERROR = "Unknown AI privacy token; start a new chat";
|
||||
const VALUE_LIMIT_ERROR = "AI privacy session limit reached; start a new chat";
|
||||
|
||||
/**
|
||||
@@ -129,7 +128,8 @@ function createAiPrivacyService({ maxSessions = 64, initialized = true } = {}) {
|
||||
if (existing) return existing;
|
||||
if (!create) throw new Error(SESSION_ERROR);
|
||||
if (sessions.size >= maxSessions) throw new Error(LIMIT_ERROR);
|
||||
const entry = { redactor: createRedactionSession(config) };
|
||||
// #4562: stale aliases remain opaque; only this chat's known tokens resolve.
|
||||
const entry = { redactor: createRedactionSession(config, { passthroughUnknownTokens: true }) };
|
||||
sessions.set(chatSessionId, entry);
|
||||
return entry;
|
||||
}
|
||||
@@ -143,15 +143,13 @@ function createAiPrivacyService({ maxSessions = 64, initialized = true } = {}) {
|
||||
if (!redactor) return value;
|
||||
try {
|
||||
if (operation === "restore") return redactor.restore(value);
|
||||
// Also validate aliases in preserved root keys. Do not use this restored
|
||||
if (operation === "restoreStrict") return redactor.restore(value, { strict: true });
|
||||
// Also validate preserved root keys. Do not use this restored
|
||||
// value for redaction: whole-string numeric/boolean aliases must keep
|
||||
// their token and type when they cross another model boundary.
|
||||
redactor.restore(value);
|
||||
return redactor.redact(value, { preserveRootKeys: true, acceptExistingTokens: true });
|
||||
} catch (error) {
|
||||
if (error?.message === "Unknown External MCP redaction token; reconnect the client") {
|
||||
throw new Error(TOKEN_ERROR);
|
||||
}
|
||||
if (error?.message === "External MCP redaction session limit reached; reconnect the client") {
|
||||
throw new Error(VALUE_LIMIT_ERROR);
|
||||
}
|
||||
@@ -176,6 +174,8 @@ function createAiPrivacyService({ maxSessions = 64, initialized = true } = {}) {
|
||||
checkSession,
|
||||
redact: (chatSessionId, value) => transform("redact", chatSessionId, value),
|
||||
restore: (chatSessionId, value) => transform("restore", chatSessionId, value),
|
||||
// Execution boundaries must reject aliases that this chat does not own.
|
||||
restoreStrict: (chatSessionId, value) => transform("restoreStrict", chatSessionId, value),
|
||||
clearSession,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -87,11 +87,12 @@ test("maps are isolated per stable chat identity and per service instance", () =
|
||||
assert.notEqual(one, two);
|
||||
assert.equal(service.redact("chat-one", "8.8.8.8"), one);
|
||||
assert.equal(service.restore("chat-one", one), "8.8.8.8");
|
||||
assert.throws(() => service.restore("chat-two", one), /Unknown AI privacy token/);
|
||||
assert.throws(() => service.redact("chat-two", one), /Unknown AI privacy token/);
|
||||
assert.equal(service.restore("chat-two", one), one);
|
||||
assert.equal(service.redact("chat-two", one), one);
|
||||
const other = enabledService();
|
||||
other.checkSession("chat-one");
|
||||
assert.throws(() => other.restore("chat-one", one), /Unknown AI privacy token/);
|
||||
assert.equal(other.restore("chat-one", one), one);
|
||||
assert.equal(other.redact("chat-one", one), one);
|
||||
assert.notEqual(other.redact("chat-one", "8.8.8.8"), one);
|
||||
});
|
||||
|
||||
@@ -113,20 +114,65 @@ test("multiple model boundaries preserve existing aliases, including numeric and
|
||||
assert.equal(service.restore("chat", later), "synthetic.example.test with synthetic-secret and 1.1.1.1");
|
||||
});
|
||||
|
||||
test("unknown, malformed, cross-chat and modified aliases fail closed, including preserved keys", () => {
|
||||
test("unknown, malformed, cross-chat and modified aliases stay opaque, including preserved keys", () => {
|
||||
const service = enabledService();
|
||||
const token = service.redact("chat", "8.8.8.8");
|
||||
const foreign = service.redact("other-chat", "1.1.1.1");
|
||||
for (const value of [
|
||||
"[NC_literal]", "[NC_unclosed", token.replace("_IP_", "_HOST_"),
|
||||
"[NC_literal]", "[NC_unclosed", foreign, token.replace("_IP_", "_HOST_"),
|
||||
`${token.slice(0, -1)}0]`,
|
||||
{ "[NC_unknown]": "ordinary" }, { text: "[NC_unknown]" },
|
||||
{ nested: { "[NC_unknown]": [foreign, "[NC_unclosed"] } },
|
||||
]) {
|
||||
assert.throws(() => service.redact("chat", value), { message: "Unknown AI privacy token; start a new chat" });
|
||||
assert.throws(() => service.restore("chat", value), { message: "Unknown AI privacy token; start a new chat" });
|
||||
assert.deepEqual(service.redact("chat", value), value);
|
||||
assert.deepEqual(service.restore("chat", value), value);
|
||||
}
|
||||
const mixed = `${foreign} before ${token} after [NC_unclosed`;
|
||||
assert.equal(service.restore("chat", mixed), `${foreign} before 8.8.8.8 after [NC_unclosed`);
|
||||
assert.equal(service.restore("chat", `[NC_x ${token} ${foreign}]`), `[NC_x 8.8.8.8 ${foreign}]`);
|
||||
assert.equal(service.restore("chat", `[NC_x ${foreign} ${token}]`), `[NC_x ${foreign} 8.8.8.8]`);
|
||||
assert.equal(service.redact("chat", mixed), mixed);
|
||||
assert.equal(service.restore("chat", token), "8.8.8.8");
|
||||
assert.throws(() => service.restore("unseen", token), NEW_CHAT);
|
||||
assert.equal(service.hasSession("unseen"), false);
|
||||
});
|
||||
|
||||
test("strict execution restore shares the chat map but rejects unknown aliases", () => {
|
||||
const service = enabledService();
|
||||
const source = { host: "8.8.8.8", token: 123456, secret: false };
|
||||
const masked = service.redact("chat", source);
|
||||
const foreign = service.redact("other-chat", "1.1.1.1");
|
||||
assert.deepEqual(service.restoreStrict("chat", masked), source);
|
||||
for (const value of [
|
||||
"[NC_unknown_IP_1]", foreign, { nested: [foreign] },
|
||||
{ [foreign]: "ordinary" }, `[NC_x ${masked.host}]`,
|
||||
]) {
|
||||
assert.throws(() => service.restoreStrict("chat", value), /could not safely process/);
|
||||
}
|
||||
assert.equal(service.restore("chat", foreign), foreign);
|
||||
assert.equal(service.redact("chat", foreign), foreign);
|
||||
assert.throws(() => service.restoreStrict("unseen", masked), NEW_CHAT);
|
||||
assert.equal(service.hasSession("unseen"), false);
|
||||
});
|
||||
|
||||
test("outbound privacy scans passwords and addresses inside malformed token spans", () => {
|
||||
const service = enabledService({ redactPrivateIps: true });
|
||||
for (const source of [
|
||||
"[NC_unclosed password=hunter2 host=8.8.8.8",
|
||||
"[NC_x password=hunter2 host=8.8.8.8]",
|
||||
"[NC_unclosed password=hunter2 host=10.0.0.8",
|
||||
"[NC_x password=hunter2 host=10.0.0.8]",
|
||||
]) {
|
||||
const masked = service.redact("chat", source);
|
||||
assert.equal(masked.includes("hunter2"), false);
|
||||
assert.equal(masked.includes("8.8.8.8"), false);
|
||||
assert.equal(masked.includes("10.0.0.8"), false);
|
||||
assert.match(masked, /password=\[NC_[a-f0-9]{12}_SECRET_\d+\]/);
|
||||
assert.match(masked, /host=\[NC_[a-f0-9]{12}_IP_\d+\]/);
|
||||
assert.equal(service.restore("chat", masked), source);
|
||||
}
|
||||
});
|
||||
|
||||
test("semantic root control keys stay intact while nested user-data keys are protected", () => {
|
||||
const service = enabledService();
|
||||
const source = {
|
||||
|
||||
@@ -13,7 +13,7 @@ function createManagedPrivacyBoundary(dispatch, privacyService) {
|
||||
} });
|
||||
}
|
||||
const enabled = privacyService.checkSession(chatSessionId);
|
||||
const restored = enabled ? privacyService.restore(chatSessionId, params) : params;
|
||||
const restored = enabled ? privacyService.restoreStrict(chatSessionId, params) : params;
|
||||
let result;
|
||||
try {
|
||||
result = await dispatch(method, restored, {
|
||||
|
||||
@@ -208,6 +208,36 @@ test('stream restores tokens split at every character and flushes an ordinary br
|
||||
assert.equal(text, `host=${ADDRESS}; [`);
|
||||
});
|
||||
|
||||
test('unknown placeholders stay opaque in outgoing prompts and generated or streamed text', async (t) => {
|
||||
const { privacy } = await fixture(t);
|
||||
const token = await privacy.transform('redact', ADDRESS);
|
||||
const text = `[NC_unknown_IP_1] then ${token}`;
|
||||
const expected = `[NC_unknown_IP_1] then ${ADDRESS}`;
|
||||
const model = new MockLanguageModelV4({
|
||||
doGenerate: {
|
||||
content: [{ type: 'text', text }],
|
||||
finishReason: { unified: 'stop', raw: undefined }, usage, warnings: [],
|
||||
},
|
||||
doStream: stream([
|
||||
{ type: 'text-start', id: 'text-1' },
|
||||
...[...text].map(delta => ({ type: 'text-delta' as const, id: 'text-1', delta })),
|
||||
{ type: 'text-end', id: 'text-1' },
|
||||
]),
|
||||
});
|
||||
const protectedModel = protectModel(model, privacy);
|
||||
const params: LanguageModelV4CallOptions = {
|
||||
prompt: [{ role: 'user', content: [{ type: 'text', text }] }],
|
||||
};
|
||||
const generated = await protectedModel.doGenerate(params);
|
||||
assert.deepEqual(generated.content, [{ type: 'text', text: expected }]);
|
||||
const response = await protectedModel.doStream(params);
|
||||
const chunks = await drain(response.stream);
|
||||
assert.equal(chunks.filter(chunk => chunk.type === 'text-delta').map(chunk => chunk.delta).join(''), expected);
|
||||
for (const call of [...model.doGenerateCalls, ...model.doStreamCalls]) {
|
||||
assert.deepEqual(call.prompt, params.prompt);
|
||||
}
|
||||
});
|
||||
|
||||
test('stream preserves reasoning bytes and provider continuation metadata', async (t) => {
|
||||
const { privacy } = await fixture(t);
|
||||
const token = await privacy.transform('redact', ADDRESS);
|
||||
@@ -452,6 +482,33 @@ test('unknown tool tokens cannot reach execution', async (t) => {
|
||||
assert.equal(executed, false);
|
||||
});
|
||||
|
||||
test('unknown streamed tool tokens cannot reach execution', async (t) => {
|
||||
const { privacy } = await fixture(t);
|
||||
const model = new MockLanguageModelV4({
|
||||
doStream: stream([
|
||||
{ type: 'tool-call', toolCallId: 'call-1', toolName: 'inspect', input: '{"target":"[NC_unknown_IP_1]"}' },
|
||||
]),
|
||||
});
|
||||
let executed = false;
|
||||
const result = streamText({
|
||||
model: protectModel(model, privacy),
|
||||
messages: [{ role: 'user', content: ADDRESS }],
|
||||
tools: {
|
||||
inspect: tool({
|
||||
inputSchema: z.object({ target: z.string() }),
|
||||
execute: async () => { executed = true; return 'unsafe'; },
|
||||
}),
|
||||
},
|
||||
maxRetries: 0,
|
||||
});
|
||||
await assert.rejects(async () => {
|
||||
for await (const chunk of result.stream) {
|
||||
if (chunk.type === 'error') throw chunk.error;
|
||||
}
|
||||
}, /privacy protection is unavailable/);
|
||||
assert.equal(executed, false);
|
||||
});
|
||||
|
||||
test('OpenAI-compatible reasoning injected after model conversion is still protected', async (t) => {
|
||||
const { privacy } = await fixture(t);
|
||||
const mockGlobal = globalThis as unknown as { window?: unknown };
|
||||
|
||||
@@ -13,14 +13,14 @@ export interface ModelPrivacyBridge {
|
||||
aiPrivacyStatus?: () => Promise<{ ok?: boolean; enabled?: boolean; error?: string }>;
|
||||
aiPrivacyTransform?: (input: {
|
||||
chatSessionId: string;
|
||||
operation: 'redact' | 'restore';
|
||||
operation: 'redact' | 'restore' | 'restoreStrict';
|
||||
value: unknown;
|
||||
}) => Promise<{ ok: boolean; value?: unknown; error?: string }>;
|
||||
}
|
||||
|
||||
export interface ModelPrivacy {
|
||||
enabled: boolean;
|
||||
transform<T>(operation: 'redact' | 'restore', value: T): Promise<T>;
|
||||
transform<T>(operation: 'redact' | 'restore' | 'restoreStrict', value: T): Promise<T>;
|
||||
}
|
||||
|
||||
export interface ModelPrivacyContext {
|
||||
@@ -67,7 +67,7 @@ export async function initializeModelPrivacy(
|
||||
if (!bridge.aiPrivacyTransform) throw new Error(PRIVACY_ERROR);
|
||||
const privacy: ModelPrivacy = {
|
||||
enabled: status.enabled,
|
||||
async transform<T>(operation: 'redact' | 'restore', value: T): Promise<T> {
|
||||
async transform<T>(operation: 'redact' | 'restore' | 'restoreStrict', value: T): Promise<T> {
|
||||
let result;
|
||||
try {
|
||||
result = await bridge.aiPrivacyTransform!({ chatSessionId, operation, value });
|
||||
@@ -250,7 +250,7 @@ async function restoreToolCall(
|
||||
// Let the SDK report malformed JSON. It cannot execute this tool call.
|
||||
return call;
|
||||
}
|
||||
const restored = await privacy.transform('restore', input);
|
||||
const restored = await privacy.transform('restoreStrict', input);
|
||||
return { ...call, input: JSON.stringify(restored) };
|
||||
}
|
||||
|
||||
|
||||
@@ -3475,6 +3475,45 @@
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"ViewOpenLimits": {
|
||||
"const": {
|
||||
"maxParamsBytes": 16384
|
||||
}
|
||||
},
|
||||
"ViewOpenParams": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"viewId"
|
||||
],
|
||||
"properties": {
|
||||
"viewId": {
|
||||
"$ref": "#/$defs/ContributionId"
|
||||
},
|
||||
"params": {
|
||||
"$ref": "#/$defs/JsonValue"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"ViewOpenResult": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"opened",
|
||||
"focused"
|
||||
],
|
||||
"properties": {
|
||||
"opened": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"focused": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"location": {
|
||||
"$ref": "#/$defs/ViewLocation"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"PluginViewBadge": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
@@ -3658,6 +3697,27 @@
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"required": [
|
||||
"kind",
|
||||
"instanceId"
|
||||
],
|
||||
"properties": {
|
||||
"kind": {
|
||||
"const": "host-ui.activate"
|
||||
},
|
||||
"instanceId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 128
|
||||
},
|
||||
"params": {
|
||||
"$ref": "#/$defs/JsonValue"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
@@ -1515,3 +1515,67 @@ test("HostDrawnViewEvent accepts pointer and wheel fields while rejecting out-of
|
||||
assert.equal(validate(invalid), false, JSON.stringify(invalid));
|
||||
}
|
||||
});
|
||||
|
||||
test("ViewOpenParams, ViewOpenResult, and HostDrawnViewMessage host-ui.activate schemas enforce bounds and reject unknown keys", async () => {
|
||||
const { PLUGIN_VIEW_OPEN_MAX_PARAMS_BYTES, serializeJsonValue } = await import("./index.ts");
|
||||
assert.equal(PLUGIN_VIEW_OPEN_MAX_PARAMS_BYTES, 16384);
|
||||
|
||||
const validateOpenParams = validator("ViewOpenParams");
|
||||
for (const valid of [
|
||||
{ viewId: "com.example.db.workbench" },
|
||||
{ viewId: "com.example.db.workbench", params: { connectionId: "conn-1", focus: true } },
|
||||
{ viewId: "com.example.db.workbench", params: null },
|
||||
]) {
|
||||
assert.equal(validateOpenParams(valid), true, JSON.stringify(validateOpenParams.errors));
|
||||
}
|
||||
for (const invalid of [
|
||||
{},
|
||||
{ viewId: "" },
|
||||
{ viewId: "bad" },
|
||||
{ viewId: "com.example.db.workbench", extra: true },
|
||||
{ viewId: "com.example.db.workbench", context: { "netcatty.surface": "vault-page" } },
|
||||
]) {
|
||||
assert.equal(validateOpenParams(invalid), false, JSON.stringify(invalid));
|
||||
}
|
||||
const atLimit = { payload: "a".repeat(PLUGIN_VIEW_OPEN_MAX_PARAMS_BYTES - 14) };
|
||||
assert.equal(Buffer.byteLength(serializeJsonValue(atLimit), "utf8"), PLUGIN_VIEW_OPEN_MAX_PARAMS_BYTES);
|
||||
const overLimit = { payload: "a".repeat(PLUGIN_VIEW_OPEN_MAX_PARAMS_BYTES) };
|
||||
assert.ok(Buffer.byteLength(serializeJsonValue(overLimit), "utf8") > PLUGIN_VIEW_OPEN_MAX_PARAMS_BYTES);
|
||||
|
||||
const validateOpenResult = validator("ViewOpenResult");
|
||||
for (const valid of [
|
||||
{ opened: true, focused: true },
|
||||
{ opened: true, focused: true, location: "vault-page" },
|
||||
{ opened: true, focused: true, location: "terminal-sidebar" },
|
||||
{ opened: true, focused: true, location: "modal" },
|
||||
]) {
|
||||
assert.equal(validateOpenResult(valid), true, JSON.stringify(validateOpenResult.errors));
|
||||
}
|
||||
for (const invalid of [
|
||||
{ opened: true },
|
||||
{ focused: true },
|
||||
{ opened: true, focused: true, location: "settings" },
|
||||
{ opened: true, focused: true, location: "vault-page", extra: 1 },
|
||||
]) {
|
||||
assert.equal(validateOpenResult(invalid), false, JSON.stringify(invalid));
|
||||
}
|
||||
|
||||
const validateViewMessage = validator("HostDrawnViewMessage");
|
||||
for (const valid of [
|
||||
{ kind: "host-ui.open", instanceId: "inst-1" },
|
||||
{ kind: "host-ui.open", instanceId: "inst-1", stateScope: "scope-hash" },
|
||||
{ kind: "host-ui.activate", instanceId: "inst-1" },
|
||||
{ kind: "host-ui.activate", instanceId: "inst-1", params: { connectionId: "conn-1" } },
|
||||
{ kind: "host-ui.activate", instanceId: "inst-1", params: null },
|
||||
]) {
|
||||
assert.equal(validateViewMessage(valid), true, JSON.stringify(validateViewMessage.errors));
|
||||
}
|
||||
for (const invalid of [
|
||||
{ kind: "host-ui.activate" },
|
||||
{ kind: "host-ui.activate", instanceId: "" },
|
||||
{ kind: "host-ui.activate", instanceId: "inst-1", extra: true },
|
||||
{ kind: "host-ui.open", instanceId: "inst-1", extra: true },
|
||||
]) {
|
||||
assert.equal(validateViewMessage(invalid), false, JSON.stringify(invalid));
|
||||
}
|
||||
});
|
||||
@@ -25,3 +25,4 @@ export const PLUGIN_SYNC_MAX_OBJECT_BYTES = 67108864 as const;
|
||||
export const PLUGIN_SYNC_MAX_OBJECT_KEY_LENGTH = 1024 as const;
|
||||
export const PLUGIN_SYNC_MAX_REVISION_LENGTH = 256 as const;
|
||||
export const PLUGIN_SYNC_INLINE_OBJECT_BYTES = 92160 as const;
|
||||
export const PLUGIN_VIEW_OPEN_MAX_PARAMS_BYTES = 16384 as const;
|
||||
@@ -320,6 +320,10 @@ export type HostDrawnViewMessage = ({
|
||||
kind: "host-ui.event";
|
||||
instanceId: string;
|
||||
event: HostDrawnViewEvent;
|
||||
}) | ({
|
||||
kind: "host-ui.activate";
|
||||
instanceId: string;
|
||||
params?: JsonValue;
|
||||
});
|
||||
|
||||
export type HostDrawnViewOpenRequest = {
|
||||
@@ -2336,6 +2340,19 @@ export type ViewContribution = {
|
||||
|
||||
export type ViewLocation = "aside" | "panel" | "tab" | "modal" | "vault-page" | "terminal-sidebar";
|
||||
|
||||
export type ViewOpenLimits = {"maxParamsBytes":16384};
|
||||
|
||||
export type ViewOpenParams = {
|
||||
viewId: ContributionId;
|
||||
params?: JsonValue;
|
||||
};
|
||||
|
||||
export type ViewOpenResult = {
|
||||
opened: boolean;
|
||||
focused: boolean;
|
||||
location?: ViewLocation;
|
||||
};
|
||||
|
||||
export type WireIntegerLimits = {"maxSafeInteger":9007199254740991};
|
||||
|
||||
export type WorkspaceFocusTabParams = {
|
||||
|
||||
@@ -24,6 +24,7 @@ export {
|
||||
PLUGIN_SYNC_MAX_REVISION_LENGTH,
|
||||
PLUGIN_TERMINAL_INTERCEPTOR_MAX_CHUNK_BYTES,
|
||||
PLUGIN_TERMINAL_INTERCEPTOR_MAX_WINDOW_BYTES,
|
||||
PLUGIN_VIEW_OPEN_MAX_PARAMS_BYTES,
|
||||
PLUGIN_WIRE_MAX_SAFE_INTEGER,
|
||||
} from "./generated/plugin-contract-limits.js";
|
||||
export {
|
||||
|
||||
@@ -865,3 +865,78 @@ test('hostDom dispatches pointer drag, pan, cancel, and wheel zoom events into a
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('registerHostReactView ignores host-ui.activate without remounting or dropping the mounted view', async () => {
|
||||
const dom = new JSDOM('<!doctype html><body></body>', { url: 'http://localhost', pretendToBeVisual: true });
|
||||
const saved = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'HTMLInputElement', 'HTMLTextAreaElement', 'HTMLSelectElement', 'HTMLFormElement', '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] });
|
||||
}
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
|
||||
const { act, useEffect, useState } = await import('react');
|
||||
const { registerHostReactView } = await import('./hostReact.js');
|
||||
|
||||
const listeners = new Set<(value: JsonValue) => void>();
|
||||
const messages: Array<Extract<HostDrawnViewMessage, { kind: 'host-ui.update' }>> = [];
|
||||
const views = {
|
||||
onDidReceiveMessage(_id: string, listener: (value: JsonValue) => void) {
|
||||
listeners.add(listener);
|
||||
return { dispose() { listeners.delete(listener); } };
|
||||
},
|
||||
postMessage(_id: string, value: JsonValue) {
|
||||
messages.push(value as unknown as Extract<HostDrawnViewMessage, { kind: 'host-ui.update' }>);
|
||||
},
|
||||
getState: async () => undefined,
|
||||
setState: async () => {},
|
||||
setBadge: async () => {},
|
||||
open: async () => ({ opened: true, focused: true }),
|
||||
};
|
||||
const deliver = (value: JsonValue) => { for (const listener of listeners) listener(value); };
|
||||
|
||||
let mountCount = 0;
|
||||
let unmountCount = 0;
|
||||
const activatedPayloads: JsonValue[] = [];
|
||||
const pluginListener = views.onDidReceiveMessage('com.example.workbench', (msg) => {
|
||||
if (msg && typeof msg === 'object' && !Array.isArray(msg) && msg.kind === 'host-ui.activate') {
|
||||
activatedPayloads.push(msg);
|
||||
}
|
||||
});
|
||||
|
||||
function Workbench() {
|
||||
const [count] = useState(() => ++mountCount);
|
||||
useEffect(() => () => { unmountCount += 1; }, []);
|
||||
return <div id="workbench-root">Mount #{count}</div>;
|
||||
}
|
||||
|
||||
const registration = registerHostReactView(views, 'com.example.workbench', () => <Workbench />);
|
||||
try {
|
||||
await act(async () => {
|
||||
deliver({ kind: 'host-ui.open', instanceId: 'wb-1' });
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
});
|
||||
assert.equal(mountCount, 1);
|
||||
assert.equal(unmountCount, 0);
|
||||
assert.equal(document.querySelectorAll('#workbench-root').length, 1);
|
||||
assert.equal(document.getElementById('workbench-root')?.textContent, 'Mount #1');
|
||||
|
||||
// Sending host-ui.activate must neither remount nor drop the existing view.
|
||||
await act(async () => {
|
||||
deliver({ kind: 'host-ui.activate', instanceId: 'wb-1', params: { connectionId: 'db-42' } });
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
});
|
||||
assert.equal(mountCount, 1, 'host-ui.activate must not remount the view');
|
||||
assert.equal(unmountCount, 0, 'host-ui.activate must not unmount the view');
|
||||
assert.equal(document.querySelectorAll('#workbench-root').length, 1, 'host-ui.activate must not create a second instance');
|
||||
assert.deepEqual(activatedPayloads, [{ kind: 'host-ui.activate', instanceId: 'wb-1', params: { connectionId: 'db-42' } }]);
|
||||
|
||||
await act(async () => { deliver({ kind: 'host-ui.close', instanceId: 'wb-1' }); });
|
||||
assert.equal(unmountCount, 1);
|
||||
} finally {
|
||||
pluginListener.dispose();
|
||||
await act(async () => { registration.dispose(); });
|
||||
for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
@@ -38,6 +38,15 @@ test("byte streams and AI/context clients expose only canonical requests", () =>
|
||||
await context.ai.readTurn({ turnHandle: turn.turnHandle });
|
||||
const selected = await context.selectedContext.list({});
|
||||
await context.selectedContext.read({ handle: selected.items[0].handle, version: selected.items[0].version });
|
||||
const opened = await context.views.open({ viewId: "com.example.plugin.workbench", params: { connectionId: "db-1" } });
|
||||
const _openedFlag: boolean = opened.opened;
|
||||
const _focusedFlag: boolean = opened.focused;
|
||||
void _openedFlag;
|
||||
void _focusedFlag;
|
||||
// @ts-expect-error views.open result is readonly
|
||||
opened.focused = false;
|
||||
// @ts-expect-error views.open rejects unknown properties
|
||||
await context.views.open({ viewId: "com.example.plugin.workbench", context: {} });
|
||||
// @ts-expect-error source identity is host-owned
|
||||
await context.network.connect({ endpoint: "tcp://example.test:22", sourceOwner: "spoofed" });
|
||||
// @ts-expect-error TLS validation cannot be disabled
|
||||
@@ -72,9 +81,13 @@ function assertSdkTypeChecks(source: string) {
|
||||
const fixturePath = join(sdkDirectory, "__provider-overload-fixture.ts");
|
||||
const compilerOptions: ts.CompilerOptions = {
|
||||
allowImportingTsExtensions: true,
|
||||
baseUrl: sdkDirectory,
|
||||
module: ts.ModuleKind.NodeNext,
|
||||
moduleResolution: ts.ModuleResolutionKind.NodeNext,
|
||||
noEmit: true,
|
||||
paths: {
|
||||
"@netcatty/plugin-contract": ["../../plugin-contract/src/index.ts"],
|
||||
},
|
||||
skipLibCheck: true,
|
||||
strict: true,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
|
||||
@@ -256,6 +256,8 @@ export interface PluginViews {
|
||||
/** Sets or clears a notification badge on one of this plugin's declared vault-page or terminal-sidebar views. */
|
||||
setBadge(badge: import("@netcatty/plugin-contract").ViewBadgeParams): Promise<void>;
|
||||
setBadge(viewId: string, badge: Omit<import("@netcatty/plugin-contract").ViewBadgeParams, "viewId"> | null): Promise<void>;
|
||||
/** Opens or focuses one of this plugin's contributed views and delivers an optional activation payload. */
|
||||
open(params: import("@netcatty/plugin-contract").ViewOpenParams): Promise<Readonly<import("@netcatty/plugin-contract").ViewOpenResult>>;
|
||||
}
|
||||
|
||||
export interface PluginProviderInvocation<TPayload extends JsonValue = JsonValue> {
|
||||
|
||||
@@ -308,12 +308,16 @@ function schemaTypeToTs(node, level = 0) {
|
||||
|
||||
const hostInteractionLimits = schema.$defs.HostInteractionLimits?.const;
|
||||
const byteStreamLimits = schema.$defs.ByteStreamLimits?.const;
|
||||
const viewOpenLimits = schema.$defs.ViewOpenLimits?.const;
|
||||
if (!byteStreamLimits || Object.values(byteStreamLimits).some((value) => !Number.isSafeInteger(value) || value < 1)) {
|
||||
throw new Error("ByteStreamLimits must contain positive bounded integers");
|
||||
}
|
||||
if (!hostInteractionLimits || Object.values(hostInteractionLimits).some((value) => !Number.isSafeInteger(value) || value < 1)) {
|
||||
throw new Error("HostInteractionLimits must contain positive bounded integers");
|
||||
}
|
||||
if (!Number.isSafeInteger(viewOpenLimits?.maxParamsBytes) || viewOpenLimits.maxParamsBytes < 1) {
|
||||
throw new Error("ViewOpenLimits.maxParamsBytes must be a positive safe integer");
|
||||
}
|
||||
|
||||
const definitionNames = Object.keys(schema.$defs).sort((left, right) =>
|
||||
left.localeCompare(right, "en"),
|
||||
@@ -356,6 +360,7 @@ const generatedLimits = [
|
||||
`export const PLUGIN_SYNC_MAX_OBJECT_KEY_LENGTH = ${syncLimits.maxObjectKeyLength} as const;`,
|
||||
`export const PLUGIN_SYNC_MAX_REVISION_LENGTH = ${syncLimits.maxRevisionLength} as const;`,
|
||||
`export const PLUGIN_SYNC_INLINE_OBJECT_BYTES = ${syncLimits.inlineObjectBytes} as const;`,
|
||||
`export const PLUGIN_VIEW_OPEN_MAX_PARAMS_BYTES = ${viewOpenLimits.maxParamsBytes} as const;`,
|
||||
"",
|
||||
].join("\n");
|
||||
const normalizedSchema = `${JSON.stringify(schema, null, 2)}\n`;
|
||||
|
||||
Vendored
+1
-1
@@ -4,7 +4,7 @@ declare global {
|
||||
interface NetcattyBridge {
|
||||
// AI / external agents
|
||||
aiPrivacyStatus?(): Promise<{ ok: boolean; enabled?: boolean; error?: string }>;
|
||||
aiPrivacyTransform?(request: { chatSessionId: string; operation: 'redact' | 'restore'; value: unknown }): Promise<{ ok: boolean; value?: unknown; error?: string }>;
|
||||
aiPrivacyTransform?(request: { chatSessionId: string; operation: 'redact' | 'restore' | 'restoreStrict'; value: unknown }): Promise<{ ok: boolean; value?: unknown; error?: string }>;
|
||||
aiPrivacyClearSession?(chatSessionId: string): Promise<{ ok: boolean; error?: string }>;
|
||||
aiSyncProviders?(providers: Array<{ id: string; providerId: string; apiKey?: string; baseURL?: string; enabled: boolean }>): Promise<{ ok: boolean }>;
|
||||
aiChatStream?(requestId: string, url: string, headers?: Record<string, string>, body?: string, providerId?: string, idleTimeoutMs?: number): Promise<{ ok: boolean; statusCode?: number; statusText?: string; error?: string; aborted?: boolean }>;
|
||||
|
||||
+1
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user