mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-23 16:42:19 +00:00
fix(ai): order display suppression with terminal output
This commit is contained in:
1 parent
990bb791a7
commit
9c6c99c584
4 files changed
+131
-2
No files matched your search
@@ -2,6 +2,7 @@
|
||||
// Module-level require on purpose: code inside registerCattyExecHandlers
|
||||
// runs under `with (ctx)` where bare `require` resolves to ctx.require
|
||||
// (based in electron/bridges/). Requiring here keeps the path unambiguous.
|
||||
const { emitTerminalSessionData } = require("../emitTerminalSessionData.cjs");
|
||||
const { formatSyntheticEcho } = require("../ai/shellUtils.cjs");
|
||||
const { remoteDisallowsExecChannelProbe, ensureSessionShellKindForExec } = require("../ai/sessionShellKind.cjs");
|
||||
|
||||
@@ -180,11 +181,11 @@ function registerCattyExecHandlers(ctx) {
|
||||
bastionKeystrokes: remoteDisallowsExecChannelProbe(session.remoteSshVersion),
|
||||
onProbeAborted: (marker) => {
|
||||
const contents = electronModule?.webContents?.fromId?.(session.webContentsId);
|
||||
safeSend(contents, "netcatty:data", { sessionId, data: `${marker}_R\n` });
|
||||
emitTerminalSessionData(contents, sessionId, `${marker}_R\n`, { session });
|
||||
},
|
||||
onEchoSuppressionPrime: (marker) => {
|
||||
const contents = electronModule?.webContents?.fromId?.(session.webContentsId);
|
||||
safeSend(contents, "netcatty:data", { sessionId, data: `${marker}_I\n` });
|
||||
emitTerminalSessionData(contents, sessionId, `${marker}_I\n`, { session });
|
||||
},
|
||||
chatSessionId,
|
||||
expectedPrompt: getFreshIdlePrompt(session),
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
const assert = require('node:assert/strict');
|
||||
const { EventEmitter } = require('node:events');
|
||||
const test = require('node:test');
|
||||
const { configureTerminalSessionDataEmitter, emitTerminalSessionData } = require('./emitTerminalSessionData.cjs');
|
||||
const { registerCattyExecHandlers } = require('./aiBridge/cattyExecHandlers.cjs');
|
||||
const { execViaPty } = require('./ai/ptyExec.cjs');
|
||||
const bridge = require('./mcpServerBridge.cjs');
|
||||
|
||||
for (const surface of ['catty', 'mcp-exec', 'mcp-job']) {
|
||||
for (const hasPort of [true, false]) {
|
||||
test(`${surface} primes and resets on the PTY output transport (port=${hasPort})`, async (t) => {
|
||||
const deliveries = [];
|
||||
const pty = new EventEmitter();
|
||||
const session = { protocol: 'local', shellKind: 'posix', pty, webContentsId: 7 };
|
||||
const contents = { isDestroyed: () => false, send: (_channel, payload) => {
|
||||
if (!payload.syntheticEcho) deliveries.push(['ipc', payload.data]);
|
||||
} };
|
||||
const sessions = new Map([['session', session]]);
|
||||
configureTerminalSessionDataEmitter({ getSession: id => sessions.get(id), outputChannel: {
|
||||
send: (_id, data) => {
|
||||
if (!hasPort) return false;
|
||||
deliveries.push(['port', data]);
|
||||
return true;
|
||||
},
|
||||
} });
|
||||
t.after(() => { bridge.cleanup(); configureTerminalSessionDataEmitter(); });
|
||||
const transport = hasPort ? 'port' : 'ipc';
|
||||
let writes = 0;
|
||||
pty.write = data => {
|
||||
if (data === '\x03') return;
|
||||
if (writes++ === 0) {
|
||||
assert.equal(deliveries.length, 1, 'prime arrives before any typed bytes');
|
||||
assert.equal(deliveries[0][0], transport);
|
||||
assert.match(deliveries[0][1], /__NCMCP_.*_I\r?\n$/);
|
||||
emitTerminalSessionData(contents, 'session', 'wrapped echo\r\n', { session });
|
||||
}
|
||||
};
|
||||
const electronModule = { webContents: { fromId: () => contents } };
|
||||
bridge.init({ sessions, electronModule });
|
||||
bridge.setPermissionMode('auto');
|
||||
bridge.updateSessionMetadata([{ sessionId: 'session', protocol: 'local', connected: true }], 'chat');
|
||||
let pending;
|
||||
if (surface === 'catty') {
|
||||
const handlers = new Map();
|
||||
registerCattyExecHandlers({ ipcMain: { handle: (key, fn) => handlers.set(key, fn) },
|
||||
validateSender: () => true, sessions, mcpServerBridge: bridge, electronModule,
|
||||
safeSend: (target, ...args) => target.send(...args), execViaPty, getFreshIdlePrompt: () => '' });
|
||||
pending = handlers.get('netcatty:ai:exec')({ sender: contents }, { sessionId: 'session', command: 'echo test', chatSessionId: 'chat' });
|
||||
} else {
|
||||
pending = bridge.dispatchBuiltinRpc(surface === 'mcp-job' ? 'netcatty/jobStart' : 'netcatty/exec', {
|
||||
sessionId: 'session', command: 'echo test', chatSessionId: 'chat',
|
||||
});
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 30));
|
||||
assert.ok(writes > 0, 'execution must reach the PTY');
|
||||
bridge.cancelAllPtyExecs();
|
||||
pty.emit("close");
|
||||
await pending;
|
||||
assert.equal(deliveries[1][0], transport);
|
||||
assert.equal(deliveries[1][1], 'wrapped echo\r\n');
|
||||
assert.equal(deliveries.at(-1)[0], transport);
|
||||
assert.match(deliveries.at(-1)[1], /__NCMCP_.*_R\r?\n$/);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ const {
|
||||
} = require("./ai/commandSafety.cjs");
|
||||
const { execViaPty, startPtyJob, execViaChannel, execViaRawPty } = require("./ai/ptyExec.cjs");
|
||||
const { safeSend } = require("./ipcUtils.cjs");
|
||||
const { emitTerminalSessionData } = require("./emitTerminalSessionData.cjs");
|
||||
const { getCliDiscoveryFilePath } = require("../cli/discoveryPath.cjs");
|
||||
const { EXTERNAL_MCP_CHAT_SESSION_ID } = require("../cli/externalMcpDiscoveryPath.cjs");
|
||||
const sftpBridge = require("./sftpBridge.cjs");
|
||||
@@ -487,6 +488,10 @@ function shutdownHost({ preserveScopedMetadata = false } = {}) {
|
||||
function echoCommandToSession(session, sessionId, command, { syntheticEcho = true } = {}) {
|
||||
if (!electronModule || !session?.webContentsId || !command) return;
|
||||
const contents = electronModule.webContents?.fromId?.(session.webContentsId);
|
||||
if (!syntheticEcho) {
|
||||
emitTerminalSessionData(contents, sessionId, formatSyntheticEcho(command), { session });
|
||||
return;
|
||||
}
|
||||
safeSend(contents, "netcatty:data", {
|
||||
sessionId,
|
||||
data: formatSyntheticEcho(command),
|
||||
|
||||
@@ -1901,3 +1901,61 @@ test("aborted input releases custom prompts and ignores a late input marker", ()
|
||||
assert.equal(received.join(""), "normal output\nlate prompt\n");
|
||||
} finally { preload.cleanup(); }
|
||||
});
|
||||
|
||||
test('real OpenWrt ash hides wrapped input and preserves output with priming (#3384)', {
|
||||
skip: !process.env.NETCATTY_OPENWRT_SSH_PORT,
|
||||
timeout: 60000,
|
||||
}, async () => {
|
||||
const { Client } = require('ssh2');
|
||||
const { execViaPty } = require('./bridges/ai/ptyExec.cjs');
|
||||
const client = new Client();
|
||||
await new Promise((resolve, reject) => client.once('ready', resolve).once('error', reject).connect({
|
||||
host: '127.0.0.1', port: Number(process.env.NETCATTY_OPENWRT_SSH_PORT), username: 'root', password: '',
|
||||
}));
|
||||
try {
|
||||
for (const cols of [80, 120]) {
|
||||
for (const probeLiveShell of [false, true]) {
|
||||
const preload = loadPreloadWithFakeElectron();
|
||||
const stream = await new Promise((resolve, reject) => client.shell({ term: 'xterm', cols, rows: 30 },
|
||||
(error, value) => error ? reject(error) : resolve(value)));
|
||||
try {
|
||||
await new Promise((resolve, reject) => {
|
||||
let output = '';
|
||||
const timer = setTimeout(() => reject(new Error('OpenWrt prompt missing')), 5000);
|
||||
const onData = data => {
|
||||
output += data;
|
||||
if (output.includes(':~# ')) {
|
||||
clearTimeout(timer);
|
||||
stream.removeListener('data', onData);
|
||||
resolve();
|
||||
}
|
||||
};
|
||||
stream.on('data', onData);
|
||||
});
|
||||
const received = [];
|
||||
const sessionId = `openwrt-${cols}-${probeLiveShell}`;
|
||||
preload.api.onSessionData(sessionId, chunk => received.push(chunk));
|
||||
const deliver = data => preload.handlers.get('netcatty:data')({}, { sessionId, data: String(data) });
|
||||
stream.on('data', deliver);
|
||||
const result = await execViaPty(stream, "printf 'visible-output\\n'", {
|
||||
shellKind: 'posix', probeLiveShell, typedInput: true, timeoutMs: 5000,
|
||||
onEchoSuppressionPrime: marker => deliver(`${marker}_I\n`),
|
||||
onProbeAborted: marker => deliver(`${marker}_R\n`),
|
||||
});
|
||||
await sleep(150);
|
||||
assert.equal(result.ok, true, JSON.stringify(result));
|
||||
assert.equal(result.stdout.trim(), 'visible-output');
|
||||
const display = received.join('');
|
||||
assert.match(display, /visible-output/);
|
||||
assert.doesNotMatch(display, /__nc_|__NCMCP_|printf|eval|unset|_cmd=|_d=/,
|
||||
JSON.stringify({ cols, probeLiveShell, display }));
|
||||
} finally {
|
||||
stream.close();
|
||||
preload.cleanup();
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
client.end();
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user