mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-28 20:50:46 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
621a028791 |
No files matched your search
@@ -0,0 +1,220 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import type { Host, PortForwardingRule } from '../../domain/models';
|
||||
import { STORAGE_KEY_PORT_FORWARDING } from '../../infrastructure/config/storageKeys';
|
||||
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
|
||||
import type { PortForwardingConnection } from '../../infrastructure/services/portForwardingService';
|
||||
import {
|
||||
handlePluginVaultDataRequest,
|
||||
type PluginPortForwardRuntimeDeps,
|
||||
type PluginVaultDataContext,
|
||||
} from './pluginVaultDataHandlers';
|
||||
|
||||
function installMemoryLocalStorage() {
|
||||
const store = new Map<string, string>();
|
||||
const previous = (globalThis as Record<string, unknown>).localStorage;
|
||||
const mockStorage = {
|
||||
get length() { return store.size; },
|
||||
clear() { store.clear(); },
|
||||
getItem(key: string) { return store.has(key) ? store.get(key)! : null; },
|
||||
key(index: number) { return Array.from(store.keys())[index] ?? null; },
|
||||
removeItem(key: string) { store.delete(key); },
|
||||
setItem(key: string, value: string) { store.set(key, String(value)); },
|
||||
};
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
value: mockStorage,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
});
|
||||
return () => {
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
value: previous,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
const sampleHost: Host = {
|
||||
id: 'host-1',
|
||||
label: 'Prod Bastion',
|
||||
hostname: '10.0.0.10',
|
||||
port: 22,
|
||||
username: 'ubuntu',
|
||||
os: 'linux',
|
||||
group: '',
|
||||
tags: [],
|
||||
protocol: 'ssh',
|
||||
};
|
||||
|
||||
const sampleRules: PortForwardingRule[] = [
|
||||
{
|
||||
id: 'rule-active',
|
||||
label: 'DB Tunnel',
|
||||
type: 'local',
|
||||
localPort: 15432,
|
||||
bindAddress: '127.0.0.1',
|
||||
remoteHost: '127.0.0.1',
|
||||
remotePort: 5432,
|
||||
hostId: 'host-1',
|
||||
status: 'inactive',
|
||||
createdAt: 1000,
|
||||
},
|
||||
{
|
||||
id: 'rule-err',
|
||||
label: 'Redis Tunnel',
|
||||
type: 'local',
|
||||
localPort: 16379,
|
||||
bindAddress: '127.0.0.1',
|
||||
remoteHost: '127.0.0.1',
|
||||
remotePort: 6379,
|
||||
hostId: 'host-1',
|
||||
status: 'inactive',
|
||||
createdAt: 2000,
|
||||
},
|
||||
];
|
||||
|
||||
function makeContext(portForwardRuntime: PluginPortForwardRuntimeDeps): PluginVaultDataContext {
|
||||
return {
|
||||
getVault: () => ({
|
||||
hosts: [sampleHost],
|
||||
keys: [],
|
||||
identities: [],
|
||||
knownHosts: [],
|
||||
groupConfigs: [],
|
||||
proxyProfiles: [],
|
||||
snippets: [],
|
||||
customGroups: [],
|
||||
updateHosts: () => {},
|
||||
updateSnippets: () => {},
|
||||
readCurrentHostActionState: () => ({
|
||||
hosts: [sampleHost],
|
||||
keys: [],
|
||||
identities: [],
|
||||
knownHosts: [],
|
||||
groupConfigs: [],
|
||||
proxyProfiles: [],
|
||||
snippets: [],
|
||||
customGroups: [],
|
||||
}),
|
||||
}) as never,
|
||||
resources: {} as never,
|
||||
portForwardRuntime,
|
||||
};
|
||||
}
|
||||
|
||||
test('portForward.list overlays live runtime status and error over persisted inactive rules', async () => {
|
||||
const restore = installMemoryLocalStorage();
|
||||
try {
|
||||
localStorageAdapter.write(STORAGE_KEY_PORT_FORWARDING, sampleRules);
|
||||
const activeConns = new Map<string, PortForwardingConnection>([
|
||||
['rule-active', { ruleId: 'rule-active', tunnelId: 't-1', status: 'active' }],
|
||||
]);
|
||||
const runtimeRules: PortForwardingRule[] = [
|
||||
{ ...sampleRules[0], status: 'active' },
|
||||
{ ...sampleRules[1], status: 'error', error: 'EADDRINUSE: port 16379 busy' },
|
||||
];
|
||||
const ctx = makeContext({
|
||||
getActiveConnection: (id) => activeConns.get(id),
|
||||
getRuntimeRules: () => runtimeRules,
|
||||
});
|
||||
|
||||
const result = await handlePluginVaultDataRequest('portForward.list', {}, ctx) as {
|
||||
rules: Array<{ id: string; status: string; error?: string }>;
|
||||
};
|
||||
const byId = new Map(result.rules.map((r) => [r.id, r]));
|
||||
assert.equal(byId.get('rule-active')?.status, 'active');
|
||||
assert.equal(byId.get('rule-active')?.error, undefined);
|
||||
assert.equal(byId.get('rule-err')?.status, 'error');
|
||||
assert.equal(byId.get('rule-err')?.error, 'EADDRINUSE: port 16379 busy');
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('portForward.start and portForward.stop return live runtime status instead of stripped storage inactive', async () => {
|
||||
const restore = installMemoryLocalStorage();
|
||||
try {
|
||||
localStorageAdapter.write(STORAGE_KEY_PORT_FORWARDING, [sampleRules[0]]);
|
||||
const activeConns = new Map<string, PortForwardingConnection>();
|
||||
const appliedStatuses: Array<{ ruleId: string; status: string; error?: string }> = [];
|
||||
let runtimeRules: PortForwardingRule[] = [{ ...sampleRules[0], status: 'inactive' }];
|
||||
|
||||
const ctx = makeContext({
|
||||
getActiveConnection: (id) => activeConns.get(id),
|
||||
getRuntimeRules: () => runtimeRules,
|
||||
applyRuntimeStatus: (ruleId, status, error) => {
|
||||
appliedStatuses.push({ ruleId, status, error });
|
||||
runtimeRules = runtimeRules.map((r) => (r.id === ruleId ? { ...r, status, error } : r));
|
||||
},
|
||||
startPortForward: async (rule, _host, _hosts, _keys, _ids, onStatusChange) => {
|
||||
onStatusChange?.('connecting');
|
||||
activeConns.set(rule.id, { ruleId: rule.id, tunnelId: 't-live', status: 'active' });
|
||||
onStatusChange?.('active');
|
||||
return { success: true };
|
||||
},
|
||||
stopAndCleanupRule: async (ruleId) => {
|
||||
activeConns.delete(ruleId);
|
||||
return { success: true };
|
||||
},
|
||||
});
|
||||
|
||||
const started = await handlePluginVaultDataRequest(
|
||||
'portForward.start',
|
||||
{ ruleId: 'rule-active' },
|
||||
ctx,
|
||||
) as { ok: boolean; rule: { id: string; status: string; error?: string } };
|
||||
assert.equal(started.ok, true);
|
||||
assert.equal(started.rule.status, 'active');
|
||||
assert.equal(started.rule.error, undefined);
|
||||
assert.ok(appliedStatuses.some((entry) => entry.ruleId === 'rule-active' && entry.status === 'active'));
|
||||
|
||||
// Subsequent list also reports active
|
||||
const listed = await handlePluginVaultDataRequest('portForward.list', {}, ctx) as {
|
||||
rules: Array<{ id: string; status: string }>;
|
||||
};
|
||||
assert.equal(listed.rules[0]?.status, 'active');
|
||||
|
||||
// Stop transitions cleanly back to inactive
|
||||
const stopped = await handlePluginVaultDataRequest(
|
||||
'portForward.stop',
|
||||
{ ruleId: 'rule-active' },
|
||||
ctx,
|
||||
) as { ok: boolean; rule: { id: string; status: string } };
|
||||
assert.equal(stopped.ok, true);
|
||||
assert.equal(stopped.rule.status, 'inactive');
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('portForward.start surfaces live error status and message when tunnel start fails', async () => {
|
||||
const restore = installMemoryLocalStorage();
|
||||
try {
|
||||
localStorageAdapter.write(STORAGE_KEY_PORT_FORWARDING, [sampleRules[1]]);
|
||||
let runtimeRules: PortForwardingRule[] = [{ ...sampleRules[1], status: 'inactive' }];
|
||||
const ctx = makeContext({
|
||||
getActiveConnection: () => undefined,
|
||||
getRuntimeRules: () => runtimeRules,
|
||||
applyRuntimeStatus: (ruleId, status, error) => {
|
||||
runtimeRules = runtimeRules.map((r) => (r.id === ruleId ? { ...r, status, error } : r));
|
||||
},
|
||||
startPortForward: async (_rule, _host, _hosts, _keys, _ids, onStatusChange) => {
|
||||
onStatusChange?.('error', 'Connection refused');
|
||||
return { success: false, error: 'Connection refused' };
|
||||
},
|
||||
});
|
||||
|
||||
const started = await handlePluginVaultDataRequest(
|
||||
'portForward.start',
|
||||
{ ruleId: 'rule-err' },
|
||||
ctx,
|
||||
) as { ok: boolean; rule: { id: string; status: string; error?: string }; error?: string };
|
||||
assert.equal(started.ok, false);
|
||||
assert.equal(started.rule.status, 'error');
|
||||
assert.equal(started.rule.error, 'Connection refused');
|
||||
assert.equal(started.error, 'Connection refused');
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
@@ -10,7 +10,11 @@ import { STORAGE_KEY_PORT_FORWARDING } from '../../infrastructure/config/storage
|
||||
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
import { preparePluginHostStream } from '../../infrastructure/services/pluginHostStreamService';
|
||||
import { startPortForward, stopAndCleanupRule } from '../../infrastructure/services/portForwardingService';
|
||||
import {
|
||||
getActiveConnection,
|
||||
startPortForward,
|
||||
stopAndCleanupRule,
|
||||
} from '../../infrastructure/services/portForwardingService';
|
||||
import { captureScreenSnapshot } from '../../infrastructure/scripts/screenSnapshotRegistry';
|
||||
import { activeTabStore } from './activeTabStore';
|
||||
import {
|
||||
@@ -19,12 +23,64 @@ import {
|
||||
type AppVaultRuntime,
|
||||
} from './appRuntimeBridge';
|
||||
import type { PluginHostActionResources } from './pluginHostActionResources';
|
||||
import {
|
||||
applyPortForwardingRuntimeStatus,
|
||||
getPortForwardingRuntimeRules,
|
||||
} from './usePortForwardingState';
|
||||
|
||||
export interface PluginPortForwardRuntimeDeps {
|
||||
startPortForward?: typeof startPortForward;
|
||||
stopAndCleanupRule?: typeof stopAndCleanupRule;
|
||||
getActiveConnection?: typeof getActiveConnection;
|
||||
getRuntimeRules?: typeof getPortForwardingRuntimeRules;
|
||||
applyRuntimeStatus?: typeof applyPortForwardingRuntimeStatus;
|
||||
}
|
||||
|
||||
export type PluginVaultDataContext = {
|
||||
getVault: () => AppVaultRuntime & ReturnType<AppVaultRuntime['readCurrentHostActionState']>;
|
||||
resources: PluginHostActionResources;
|
||||
portForwardRuntime?: PluginPortForwardRuntimeDeps;
|
||||
};
|
||||
|
||||
type PortForwardSummaryStatus = 'inactive' | 'connecting' | 'active' | 'error';
|
||||
|
||||
function normalizePortForwardSummaryStatus(
|
||||
status: PortForwardingRule['status'] | undefined,
|
||||
): PortForwardSummaryStatus {
|
||||
if (status === 'active' || status === 'connecting' || status === 'error' || status === 'inactive') {
|
||||
return status;
|
||||
}
|
||||
return 'inactive';
|
||||
}
|
||||
|
||||
function overlayPortForwardRuntimeStatus(
|
||||
rule: PortForwardingRule,
|
||||
runtime?: PluginPortForwardRuntimeDeps,
|
||||
): PortForwardingRule {
|
||||
const resolveConnection = runtime?.getActiveConnection ?? getActiveConnection;
|
||||
const liveConn = resolveConnection(rule.id);
|
||||
if (liveConn) {
|
||||
return {
|
||||
...rule,
|
||||
status: normalizePortForwardSummaryStatus(liveConn.status),
|
||||
error: liveConn.error,
|
||||
};
|
||||
}
|
||||
const runtimeRules = (runtime?.getRuntimeRules ?? getPortForwardingRuntimeRules)();
|
||||
const runtimeRule = runtimeRules.find((candidate) => candidate.id === rule.id);
|
||||
if (runtimeRule && (runtimeRule.status === 'active' || runtimeRule.status === 'connecting' || runtimeRule.status === 'error')) {
|
||||
return {
|
||||
...rule,
|
||||
status: runtimeRule.status,
|
||||
error: runtimeRule.error,
|
||||
};
|
||||
}
|
||||
return {
|
||||
...rule,
|
||||
status: normalizePortForwardSummaryStatus(rule.status),
|
||||
};
|
||||
}
|
||||
|
||||
function readPortForwardRules(): PortForwardingRule[] {
|
||||
const raw = localStorageAdapter.read<PortForwardingRule[]>(STORAGE_KEY_PORT_FORWARDING);
|
||||
return migratePortForwardingRulesFromStorage(Array.isArray(raw) ? raw : []);
|
||||
@@ -164,7 +220,9 @@ export async function handlePluginVaultDataRequest(
|
||||
}
|
||||
|
||||
case 'portForward.list': {
|
||||
const rules = readPortForwardRules().slice(0, 500);
|
||||
const rules = readPortForwardRules()
|
||||
.slice(0, 500)
|
||||
.map((rule) => overlayPortForwardRuntimeStatus(rule, ctx.portForwardRuntime));
|
||||
return { rules: rules.map((rule) => summarizePortForwardRule(rule, vault.hosts)) };
|
||||
}
|
||||
|
||||
@@ -199,24 +257,42 @@ export async function handlePluginVaultDataRequest(
|
||||
const settings = getAppSettingsRuntime();
|
||||
const resolvedHost = effectiveHost(rawHost, vault);
|
||||
const resolvedHosts = vault.hosts.map((h) => effectiveHost(h, vault));
|
||||
const res = await startPortForward(
|
||||
const pfStart = ctx.portForwardRuntime?.startPortForward ?? startPortForward;
|
||||
const pfApplyStatus = ctx.portForwardRuntime?.applyRuntimeStatus ?? applyPortForwardingRuntimeStatus;
|
||||
const pfGetConnection = ctx.portForwardRuntime?.getActiveConnection ?? getActiveConnection;
|
||||
let observedStatus: PortForwardingRule['status'] | undefined;
|
||||
let observedError: string | undefined;
|
||||
const res = await pfStart(
|
||||
rule,
|
||||
resolvedHost,
|
||||
resolvedHosts,
|
||||
vault.keys,
|
||||
vault.identities,
|
||||
(status, error) => {
|
||||
const latest = readPortForwardRules();
|
||||
writePortForwardRules(latest.map((item) => (item.id === ruleId ? { ...item, status, error } : item)));
|
||||
observedStatus = status;
|
||||
observedError = error;
|
||||
pfApplyStatus(ruleId, status, error);
|
||||
},
|
||||
false,
|
||||
settings?.terminalSettings,
|
||||
vault.knownHosts,
|
||||
);
|
||||
const updated = readPortForwardRules().find((item) => item.id === ruleId) ?? rule;
|
||||
const liveConn = pfGetConnection(ruleId);
|
||||
const fallbackStatus: PortForwardSummaryStatus = res.success ? 'active' : 'error';
|
||||
const finalStatus = normalizePortForwardSummaryStatus(liveConn?.status ?? observedStatus ?? fallbackStatus);
|
||||
const finalError = finalStatus === 'active'
|
||||
? undefined
|
||||
: (liveConn?.error ?? observedError ?? (res.error ? String(res.error) : undefined));
|
||||
pfApplyStatus(ruleId, finalStatus, finalError);
|
||||
const latestRule = readPortForwardRules().find((item) => item.id === ruleId) ?? rule;
|
||||
const liveRule: PortForwardingRule = {
|
||||
...latestRule,
|
||||
status: finalStatus,
|
||||
error: finalError,
|
||||
};
|
||||
return {
|
||||
ok: Boolean(res.success),
|
||||
rule: summarizePortForwardRule(updated, vault.hosts),
|
||||
rule: summarizePortForwardRule(liveRule, vault.hosts),
|
||||
...(res.error ? { error: String(res.error).slice(0, 512) } : {}),
|
||||
};
|
||||
}
|
||||
@@ -226,11 +302,15 @@ export async function handlePluginVaultDataRequest(
|
||||
const rules = readPortForwardRules();
|
||||
const rule = rules.find((item) => item.id === ruleId);
|
||||
if (!rule) return { ok: false, error: 'Port forwarding rule not found' };
|
||||
await stopAndCleanupRule(ruleId);
|
||||
const pfStop = ctx.portForwardRuntime?.stopAndCleanupRule ?? stopAndCleanupRule;
|
||||
const pfApplyStatus = ctx.portForwardRuntime?.applyRuntimeStatus ?? applyPortForwardingRuntimeStatus;
|
||||
await pfStop(ruleId);
|
||||
pfApplyStatus(ruleId, 'inactive', undefined);
|
||||
const latestRules = readPortForwardRules();
|
||||
const nextRules = latestRules.map((item) => (item.id === ruleId ? { ...item, status: 'inactive' as const, error: undefined } : item));
|
||||
writePortForwardRules(nextRules);
|
||||
const updated = nextRules.find((item) => item.id === ruleId) ?? rule;
|
||||
const updated = overlayPortForwardRuntimeStatus(
|
||||
latestRules.find((item) => item.id === ruleId) ?? { ...rule, status: 'inactive', error: undefined },
|
||||
ctx.portForwardRuntime,
|
||||
);
|
||||
return { ok: true, rule: summarizePortForwardRule(updated, vault.hosts) };
|
||||
}
|
||||
|
||||
@@ -240,7 +320,8 @@ export async function handlePluginVaultDataRequest(
|
||||
if (!rules.some((item) => item.id === ruleId)) {
|
||||
return { ok: false, error: 'Port forwarding rule not found' };
|
||||
}
|
||||
await stopAndCleanupRule(ruleId).catch(() => {});
|
||||
const pfStop = ctx.portForwardRuntime?.stopAndCleanupRule ?? stopAndCleanupRule;
|
||||
await pfStop(ruleId).catch(() => {});
|
||||
const latestRules = readPortForwardRules();
|
||||
writePortForwardRules(latestRules.filter((item) => item.id !== ruleId));
|
||||
return { ok: true };
|
||||
|
||||
@@ -242,6 +242,9 @@ const persistPortForwardingConfig = (rules: PortForwardingRule[]) => {
|
||||
);
|
||||
};
|
||||
|
||||
/** Read-only snapshot of the in-memory runtime port-forwarding rules projection. */
|
||||
export const getPortForwardingRuntimeRules = (): readonly PortForwardingRule[] => globalRules;
|
||||
|
||||
/** Persist configuration only — never write runtime phases to storage. */
|
||||
const setGlobalRules = (newRules: PortForwardingRule[]) => {
|
||||
globalRules = normalizeVaultOrder(newRules);
|
||||
|
||||
@@ -123,7 +123,17 @@ class PluginAISidebarService {
|
||||
}),
|
||||
registry.registerRequest("ai.openSidebar", (params, context) => this.openSidebar(params, context), {
|
||||
metadata: { capability: "plugin-ai-sidebar", mutating: false, permission: "ai.invoke" },
|
||||
authorization: auth("Open the Catty Agent contextual sidebar"),
|
||||
authorization: (params) => {
|
||||
const autoSend = Boolean(params?.autoSend);
|
||||
return {
|
||||
permission: "ai.invoke",
|
||||
resources: ["*"],
|
||||
reason: autoSend
|
||||
? "Automatically send a prompt to the Catty Agent sidebar"
|
||||
: "Open the Catty Agent contextual sidebar",
|
||||
...(autoSend ? {} : { deferDecision: true }),
|
||||
};
|
||||
},
|
||||
}),
|
||||
registry.registerRequest("ai.closeSidebar", (params, context) => this.closeSidebar(params, context), {
|
||||
metadata: { capability: "plugin-ai-sidebar", mutating: false, permission: "ai.invoke" },
|
||||
@@ -282,6 +292,7 @@ class PluginAISidebarService {
|
||||
throw invalidArgument("Plugin has no vault-page or terminal-sidebar view to attach the AI sidebar to");
|
||||
}
|
||||
const prompt = typeof normalizedParams.prompt === "string" ? normalizedParams.prompt.trim() : "";
|
||||
const autoSend = normalizedParams.autoSend === true && prompt.length > 0;
|
||||
if (prompt && CONTROL_CHAR_RE.test(prompt.replace(/[\r\n\t]/g, ""))) {
|
||||
throw invalidArgument("Plugin AI sidebar prompt contains invalid control characters");
|
||||
}
|
||||
@@ -290,7 +301,7 @@ class PluginAISidebarService {
|
||||
pluginId: context.pluginId,
|
||||
viewId,
|
||||
...(prompt ? { prompt } : {}),
|
||||
...(normalizedParams.autoSend === true && prompt ? { autoSend: true } : {}),
|
||||
...(autoSend ? { autoSend: true } : {}),
|
||||
timestamp: this.clock(),
|
||||
}));
|
||||
return null;
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
"use strict";
|
||||
|
||||
const fs = require("node:fs");
|
||||
const os = require("node:os");
|
||||
const path = require("node:path");
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { PluginDatabase } = require("./database.cjs");
|
||||
const { PluginPermissionEngine } = require("./permissionEngine.cjs");
|
||||
const { PluginHostRpcRegistry } = require("./hostRpcRegistry.cjs");
|
||||
const { PluginAISidebarService, buildQualifiedToolName, MAX_TOOLS_PER_PLUGIN } = require("./pluginAiSidebarService.cjs");
|
||||
|
||||
const manifest = Object.freeze({
|
||||
@@ -177,3 +183,95 @@ test("PluginAISidebarService manages context, sidebar commands, lock, and runtim
|
||||
|
||||
service.shutdown();
|
||||
});
|
||||
|
||||
test("ai.openSidebar enforces active ai.invoke approval for autoSend: true while deferring decision for open/prefill", async (t) => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-ai-sidebar-auth-"));
|
||||
const database = new PluginDatabase(path.join(root, "plugins.db"));
|
||||
const authManifest = Object.freeze({
|
||||
...manifest,
|
||||
publisher: "example",
|
||||
permissions: { optional: ["ai.invoke"] },
|
||||
});
|
||||
database.installVersion({
|
||||
pluginId: authManifest.id,
|
||||
version: authManifest.version,
|
||||
manifest: authManifest,
|
||||
archiveSha256: "b".repeat(64),
|
||||
packageRelativePath: "test/pkg",
|
||||
});
|
||||
database.setEnabled(authManifest.id, true);
|
||||
|
||||
let approve = false;
|
||||
const decisionRequests = [];
|
||||
const engine = new PluginPermissionEngine({
|
||||
database,
|
||||
requestDecision: async (request) => {
|
||||
decisionRequests.push(request);
|
||||
return {
|
||||
requestId: request.requestId,
|
||||
decision: approve ? "allow" : "deny",
|
||||
...(approve ? { scope: "once" } : {}),
|
||||
};
|
||||
},
|
||||
});
|
||||
const registry = new PluginHostRpcRegistry();
|
||||
registry.use(engine.createMiddleware());
|
||||
const service = new PluginAISidebarService({ permissionEngine: engine });
|
||||
service.registerRpcCapabilities(registry);
|
||||
const commands = [];
|
||||
service.onDidEmitCommand((cmd) => commands.push(cmd));
|
||||
|
||||
t.after(() => {
|
||||
service.shutdown();
|
||||
engine.shutdown();
|
||||
database.close();
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
engine.setMode({ id: authManifest.id, manifest: authManifest }, "ai.invoke", "ask");
|
||||
const runtimeCtx = {
|
||||
pluginId: authManifest.id,
|
||||
pluginVersion: authManifest.version,
|
||||
runtimeId: "rt-auth",
|
||||
runtimeKind: "browser",
|
||||
manifest: authManifest,
|
||||
};
|
||||
const handlers = registry.createRoutes(runtimeCtx).requestHandlers;
|
||||
|
||||
// 1. Opening/prefilling without autoSend uses deferDecision: true (no Ask prompt)
|
||||
await handlers["ai.openSidebar"]({ prompt: "hello", autoSend: false }, {});
|
||||
assert.equal(decisionRequests.length, 0);
|
||||
assert.equal(commands.length, 1);
|
||||
assert.equal(commands[0].prompt, "hello");
|
||||
assert.equal(commands[0].autoSend, undefined);
|
||||
|
||||
// 2. autoSend: true does NOT defer decision: prompts on Ask and rejects when denied
|
||||
approve = false;
|
||||
await assert.rejects(
|
||||
handlers["ai.openSidebar"]({ prompt: "hello", autoSend: true }, {}),
|
||||
/denied/i,
|
||||
);
|
||||
assert.equal(decisionRequests.length, 1);
|
||||
assert.equal(decisionRequests[0].permission, "ai.invoke");
|
||||
assert.equal(commands.length, 1, "denied autoSend must not emit a sidebar command");
|
||||
|
||||
// 3. When user approves Ask prompt, autoSend: true proceeds
|
||||
approve = true;
|
||||
await handlers["ai.openSidebar"]({ prompt: "run query", autoSend: true }, {});
|
||||
assert.equal(decisionRequests.length, 2);
|
||||
assert.equal(commands.length, 2);
|
||||
assert.equal(commands[1].prompt, "run query");
|
||||
assert.equal(commands[1].autoSend, true);
|
||||
|
||||
// 4. Empty prompt with autoSend: true strips autoSend defensively
|
||||
await handlers["ai.openSidebar"]({ prompt: " ", autoSend: true }, {});
|
||||
assert.equal(commands.length, 3);
|
||||
assert.equal(commands[2].autoSend, undefined);
|
||||
|
||||
// 5. Explicit Deny blocks even non-autoSend openSidebar
|
||||
engine.setMode({ id: authManifest.id, manifest: authManifest }, "ai.invoke", "deny");
|
||||
await assert.rejects(
|
||||
handlers["ai.openSidebar"]({ prompt: "blocked", autoSend: false }, {}),
|
||||
/disabled|denied/i,
|
||||
);
|
||||
});
|
||||
Reference in new issue
Block a user