mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-21 23:50:45 +00:00
Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
470628b1a3 | ||
|
|
ef99e0daf7 | ||
|
|
18a9000278 | ||
|
|
ed9da31034 | ||
|
|
3d302e2456 | ||
|
|
5e4195bf7f | ||
|
|
9c292460e3 | ||
|
|
17d53152ec | ||
|
|
f05ea0c9b7 | ||
|
|
d0fffac598 | ||
|
|
106e39a797 | ||
|
|
3bf4c9df1a |
No files matched your search
@@ -0,0 +1,18 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { enAiMessages } from './en/ai';
|
||||
import { esAiMessages } from './es/ai';
|
||||
import { ruAiMessages } from './ru/ai';
|
||||
import { zhCNAiMessages } from './zh-CN/ai';
|
||||
import { zhTWAiMessages } from './zh-TW/ai';
|
||||
|
||||
for (const [locale, messages] of Object.entries({
|
||||
en: enAiMessages, es: esAiMessages, ru: ruAiMessages,
|
||||
'zh-CN': zhCNAiMessages, 'zh-TW': zhTWAiMessages,
|
||||
})) {
|
||||
test(`${locale} translates the Catty iteration limit notice and Continue action`, () => {
|
||||
assert.ok(messages['ai.chat.iterationLimitReached']);
|
||||
assert.match(messages['ai.chat.iterationLimitReached'], /\{limit\}/);
|
||||
assert.ok(messages['ai.chat.continue']);
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const enAiMessages: Messages = {
|
||||
'ai.chat.iterationLimitReached': 'Tool-loop limit ({limit} iterations) reached. You can continue in this chat. Running terminal jobs are not stopped.',
|
||||
'ai.chat.continue': 'Continue',
|
||||
'ai.chat.attachmentContentUnavailable': 'Content not available on this device',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Agent Settings',
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const esAiMessages: Messages = {
|
||||
'ai.chat.iterationLimitReached': 'Se alcanzó el límite del bucle de herramientas ({limit} iteraciones). Puedes continuar en este chat. Las tareas de terminal en ejecución no se detienen.',
|
||||
'ai.chat.continue': 'Continuar',
|
||||
'ai.chat.attachmentContentUnavailable': 'Contenido no disponible en este dispositivo',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Configuración del agente',
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const ruAiMessages: Messages = {
|
||||
'ai.chat.iterationLimitReached': 'Достигнут лимит цикла инструментов ({limit} итераций). Можно продолжить в этом чате. Запущенные задачи терминала не останавливаются.',
|
||||
'ai.chat.continue': 'Продолжить',
|
||||
'ai.chat.attachmentContentUnavailable': 'Содержимое недоступно на этом устройстве',
|
||||
'ai.chat.contextUsage': 'Контекст: {used} / {max} токенов',
|
||||
// AI Settings
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const zhCNAiMessages: Messages = {
|
||||
'ai.chat.iterationLimitReached': '已达到工具循环上限({limit} 次迭代)。你可以在此对话中继续,正在运行的终端任务不会停止。',
|
||||
'ai.chat.continue': '继续',
|
||||
'ai.chat.attachmentContentUnavailable': '附件内容未保留在此设备',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Agent 设置',
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const zhTWAiMessages: Messages = {
|
||||
'ai.chat.iterationLimitReached': '已達到工具迴圈上限({limit} 次迭代)。你可以在此對話中繼續,正在執行的終端工作不會停止。',
|
||||
'ai.chat.continue': '繼續',
|
||||
'ai.chat.attachmentContentUnavailable': '附件內容未保留在此裝置',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Agent 設定',
|
||||
|
||||
@@ -55,7 +55,7 @@ interface AIChatPanelContentProps {
|
||||
contextUsage?: import('../application/state/useAgentCompactionUi').AgentContextUsage | null;
|
||||
inputValue: string;
|
||||
setInputValue: (value: string) => void;
|
||||
handleSend: () => void;
|
||||
handleSend: (textOverride?: string) => void;
|
||||
handleCompact: () => void;
|
||||
/** Rename a chat by id (history drawer edit affordance). Panel action, never agent content. */
|
||||
onRenameSession?: (sessionId: string, title: string) => void;
|
||||
@@ -211,6 +211,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
parked = false,
|
||||
sending = false,
|
||||
}) => {
|
||||
const handleContinue = React.useCallback(() => handleSend(t('ai.chat.continue')), [handleSend, t]);
|
||||
const mentionHosts = React.useMemo(
|
||||
() => terminalSessions.map((session) => ({
|
||||
sessionId: session.sessionId,
|
||||
@@ -345,6 +346,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
<ChatMessageList
|
||||
messages={messages}
|
||||
isStreaming={isStreaming}
|
||||
onContinue={handleContinue}
|
||||
activeSessionId={activeSessionId}
|
||||
activeCompaction={activeCompaction}
|
||||
contextCompaction={activeSession?.contextCompaction}
|
||||
|
||||
@@ -1610,14 +1610,14 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
}, [currentAgentId, enterScopeDraftMode, updateScopeDraft]);
|
||||
|
||||
|
||||
const handleSend = useCallback(async () => {
|
||||
const handleSend = useCallback(async (textOverride?: string) => {
|
||||
const draft = currentDraftRef.current;
|
||||
const currentPanelView = panelViewRef.current;
|
||||
const currentSessionView = activeSessionRef.current;
|
||||
if (!validateNoteMentions(draft?.attachments ?? [])) return;
|
||||
const trimmed = draft?.text.trim() ?? '';
|
||||
if (textOverride === undefined && !validateNoteMentions(draft?.attachments ?? [])) return;
|
||||
const trimmed = (textOverride ?? draft?.text ?? '').trim();
|
||||
const sendScopeKey = scopeKey;
|
||||
const attachments = (draft?.attachments ?? []).map((file) => ({
|
||||
const attachments = (textOverride === undefined ? draft?.attachments ?? [] : []).map((file) => ({
|
||||
base64Data: file.base64Data,
|
||||
mediaType: file.mediaType,
|
||||
filename: file.filename,
|
||||
@@ -1645,12 +1645,12 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
const agentConfig = sendAgentId !== 'catty' ? findEnabledExternalAgent(externalAgents, sendAgentId) : undefined;
|
||||
if (sendAgentId !== 'catty' && !agentConfig) return;
|
||||
|
||||
const selectedSkillSlugs = draft?.selectedUserSkillSlugs ?? [];
|
||||
const selectedSkillSlugs = textOverride === undefined ? draft?.selectedUserSkillSlugs ?? [] : [];
|
||||
const modelPrompt = buildPromptWithTerminalSelectionAttachments(trimmed, attachments);
|
||||
const modelAttachments = attachments.filter((attachment) => !isInlineTextAttachment(attachment));
|
||||
const isDraftMode = currentPanelView.mode === 'draft';
|
||||
|
||||
flushDraftText();
|
||||
if (textOverride === undefined) flushDraftText();
|
||||
const submittedText = draft?.text ?? '';
|
||||
const keepPendingAfterSend = () => {
|
||||
const pending = pendingComposerTextRef.current;
|
||||
@@ -1739,7 +1739,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
const createdSession = createSession(scope, sendAgentId);
|
||||
sessionId = createdSession.id;
|
||||
currentSession = createdSession;
|
||||
clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
if (textOverride === undefined) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
showScopeSessionView(createdSession.id);
|
||||
setActiveSessionId(createdSession.id);
|
||||
sessionSendGateKey = sessionId;
|
||||
@@ -1770,7 +1770,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
});
|
||||
addMessageToSession(sessionId, { id: generateId(), role: 'assistant', content: t('ai.chat.noProvider'), timestamp: Date.now() });
|
||||
if (currentPanelView.mode === 'session') {
|
||||
clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
if (textOverride === undefined) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
showScopeSessionView(sessionId);
|
||||
}
|
||||
return;
|
||||
@@ -1785,7 +1785,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
});
|
||||
addMessageToSession(sessionId, { id: generateId(), role: 'assistant', content: t('ai.chat.noProviderModel'), timestamp: Date.now() });
|
||||
if (currentPanelView.mode === 'session') {
|
||||
clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
if (textOverride === undefined) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
showScopeSessionView(sessionId);
|
||||
}
|
||||
return;
|
||||
@@ -1798,7 +1798,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
...(selectedSkillSlugs.length > 0 ? { selectedUserSkillSlugs: selectedSkillSlugs } : {}),
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
if (textOverride === undefined) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
showScopeSessionView(sessionId);
|
||||
setActiveSessionId(sessionId);
|
||||
setStreamingForScope(sessionId, true);
|
||||
|
||||
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import React from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { act, create, type ReactTestRenderer } from "react-test-renderer";
|
||||
|
||||
import { I18nProvider } from "../../application/i18n/I18nProvider.tsx";
|
||||
import type { ChatMessage } from "../../infrastructure/ai/types.ts";
|
||||
@@ -644,3 +645,64 @@ test('fork is offered only for safe completed replies and hidden while streaming
|
||||
assert.equal((render(false).match(/Fork from here/g) ?? []).length, 1);
|
||||
assert.equal((render(true).match(/Fork from here/g) ?? []).length, 0);
|
||||
});
|
||||
|
||||
test('ChatMessageList renders a non-error iteration limit notice with a Continue action', () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ id: 'poll', role: 'tool', content: '', timestamp: 1,
|
||||
toolResults: [{ toolCallId: 'poll-1', content: '{"jobId":"job-1","status":"running"}' }] },
|
||||
{ id: 'limit', role: 'assistant', content: '', timestamp: 2, iterationLimit: 20 },
|
||||
];
|
||||
const render = (isStreaming: boolean) => renderToStaticMarkup(
|
||||
<I18nProvider locale="en">
|
||||
<TooltipProvider>
|
||||
<ChatMessageList messages={messages} isStreaming={isStreaming} onContinue={() => {}} />
|
||||
</TooltipProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
const markup = render(false);
|
||||
assert.match(markup, /Tool-loop limit \(20 iterations\) reached/);
|
||||
assert.match(markup, /<button[^>]*>Continue<\/button>/);
|
||||
assert.doesNotMatch(markup, /bg-destructive/);
|
||||
assert.match(render(true), /<button[^>]*disabled=""[^>]*>Continue<\/button>/);
|
||||
|
||||
const source = readFileSync(new URL('./ChatMessageList.tsx', import.meta.url), 'utf8');
|
||||
const panel = readFileSync(new URL('../AIChatPanelContent.tsx', import.meta.url), 'utf8');
|
||||
const sidePanel = readFileSync(new URL('../AIChatSidePanel.tsx', import.meta.url), 'utf8');
|
||||
assert.match(source, /onClick=\{onContinue\}/);
|
||||
assert.match(panel, /onContinue=\{handleContinue\}/);
|
||||
assert.match(panel, /handleContinue = React.useCallback\(\(\) => handleSend\(t\('ai.chat.continue'\)\)/);
|
||||
assert.match(sidePanel, /const handleSend = useCallback\(async \(textOverride\?: string\)/);
|
||||
assert.match(sidePanel, /const trimmed = \(textOverride \?\? draft\?\.text \?\? ''\)\.trim\(\)/);
|
||||
});
|
||||
|
||||
test('iteration limit Continue button invokes the provided send callback', async t => {
|
||||
const previousWindow = globalThis.window;
|
||||
const actGlobal = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
|
||||
const previousActEnvironment = actGlobal.IS_REACT_ACT_ENVIRONMENT;
|
||||
globalThis.window = { setTimeout, clearTimeout } as unknown as Window & typeof globalThis;
|
||||
actGlobal.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
t.after(() => {
|
||||
globalThis.window = previousWindow;
|
||||
actGlobal.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment;
|
||||
});
|
||||
let continued = 0;
|
||||
let renderer: ReactTestRenderer;
|
||||
await act(async () => {
|
||||
renderer = create(
|
||||
<I18nProvider locale="en">
|
||||
<TooltipProvider>
|
||||
<ChatMessageList
|
||||
messages={[{ id: 'limit', role: 'assistant', content: '', timestamp: 1, iterationLimit: 20 }]}
|
||||
onContinue={() => { continued += 1; }}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
});
|
||||
const button = renderer!.root.findAllByType('button').find(node => node.children.includes('Continue'));
|
||||
assert.ok(button);
|
||||
assert.equal(button.props.disabled, false);
|
||||
await act(async () => { button.props.onClick(); });
|
||||
assert.equal(continued, 1);
|
||||
await act(async () => { renderer!.unmount(); });
|
||||
});
|
||||
@@ -90,6 +90,7 @@ import ChatJumpNav from './ChatJumpNav';
|
||||
interface ChatMessageListProps {
|
||||
messages: ChatMessage[];
|
||||
isStreaming?: boolean;
|
||||
onContinue?: () => void;
|
||||
/** Active chat session ID — used to filter standalone MCP approval blocks */
|
||||
activeSessionId?: string | null;
|
||||
activeCompaction?: ActiveCompactionUi | null;
|
||||
@@ -185,6 +186,7 @@ export function pruneResolvedApprovals(
|
||||
const ChatMessageList: React.FC<ChatMessageListProps> = ({
|
||||
messages,
|
||||
isStreaming,
|
||||
onContinue,
|
||||
activeSessionId,
|
||||
activeCompaction = null,
|
||||
contextCompaction,
|
||||
@@ -813,6 +815,18 @@ const ChatMessageList: React.FC<ChatMessageListProps> = ({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{message.iterationLimit != null && (
|
||||
<div role="status" className="rounded-md border border-border/60 bg-muted/30 px-3 py-2 text-sm">
|
||||
<p>{t('ai.chat.iterationLimitReached', { limit: message.iterationLimit })}</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onContinue}
|
||||
disabled={!!isStreaming || !onContinue}
|
||||
className="mt-2 rounded-md border border-border px-2 py-1 text-xs font-medium hover:bg-muted disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>{t('ai.chat.continue')}</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error info */}
|
||||
{message.errorInfo && (
|
||||
<div className="flex items-start gap-2 px-3 py-2 rounded-md bg-destructive/10 border border-destructive/20 text-sm">
|
||||
@@ -1079,6 +1093,7 @@ const ChatMessageList: React.FC<ChatMessageListProps> = ({
|
||||
|
||||
function areMessagesEqual(prev: ChatMessageListProps, next: ChatMessageListProps): boolean {
|
||||
if (prev.isStreaming !== next.isStreaming) return false;
|
||||
if (prev.onContinue !== next.onContinue) return false;
|
||||
if (prev.activeSessionId !== next.activeSessionId) return false;
|
||||
if (prev.notes !== next.notes) return false;
|
||||
if (prev.hosts !== next.hosts) return false;
|
||||
@@ -1107,6 +1122,7 @@ function areMessagesEqual(prev: ChatMessageListProps, next: ChatMessageListProps
|
||||
p.statusText !== n.statusText ||
|
||||
p.executionStatus !== n.executionStatus ||
|
||||
p.errorInfo !== n.errorInfo ||
|
||||
p.iterationLimit !== n.iterationLimit ||
|
||||
p.toolCalls !== n.toolCalls ||
|
||||
p.toolResults !== n.toolResults ||
|
||||
p.agentActivities !== n.agentActivities ||
|
||||
|
||||
@@ -2,9 +2,11 @@ import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import React from 'react';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
|
||||
import { I18nProvider } from '../../application/i18n/I18nProvider';
|
||||
import { TerminalComposeBar } from './TerminalComposeBar';
|
||||
import { TerminalContextMenu } from './TerminalContextMenu';
|
||||
import { TooltipProvider } from '../ui/tooltip';
|
||||
import { getComposeBarHistory, pruneComposeBarHistory, recordComposeBarHistory } from '../../application/state/composeBarHistoryStore';
|
||||
import { terminalReconnectRegistry } from '../../application/state/terminalReconnectRegistry';
|
||||
@@ -303,3 +305,54 @@ test('compose send target toggle shows all vs active without looking like broadc
|
||||
assert.equal(stillPulsing.length, 0);
|
||||
await act(async () => { root.unmount(); });
|
||||
});
|
||||
|
||||
|
||||
test('compose right-click never pastes into the terminal behind it', async (t) => {
|
||||
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', { url: 'http://localhost' });
|
||||
const globals = ['window', 'document', 'localStorage', 'Element', 'HTMLElement', 'Node'] as const;
|
||||
const originals = globals.map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)] as const);
|
||||
for (const name of globals) {
|
||||
Object.defineProperty(globalThis, name, { configurable: true, value: dom.window[name] });
|
||||
}
|
||||
const rootElement = dom.window.document.querySelector('#root')!;
|
||||
const root = createRoot(rootElement);
|
||||
t.after(async () => {
|
||||
await act(async () => root.unmount());
|
||||
dom.window.close();
|
||||
for (const [name, descriptor] of originals) {
|
||||
if (descriptor) Object.defineProperty(globalThis, name, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, name);
|
||||
}
|
||||
});
|
||||
let pasteCount = 0;
|
||||
const render = (broadcast: boolean) => (
|
||||
<I18nProvider locale="en"><TooltipProvider>
|
||||
<TerminalContextMenu sessionId="right-click-test" status="connected" rightClickBehavior="paste" onPaste={() => { pasteCount++; }}>
|
||||
<div>
|
||||
<div data-terminal-cell />
|
||||
<TerminalComposeBar sessionId="right-click-test" isBroadcastEnabled={broadcast} onSend={() => true} onClose={() => {}} />
|
||||
</div>
|
||||
</TerminalContextMenu>
|
||||
</TooltipProvider></I18nProvider>
|
||||
);
|
||||
const rightClick = async (target: string) => {
|
||||
const element = rootElement.querySelector(target);
|
||||
assert.ok(element, target);
|
||||
await act(async () => {
|
||||
element.dispatchEvent(new dom.window.MouseEvent('contextmenu', { bubbles: true, cancelable: true, button: 2 }));
|
||||
});
|
||||
};
|
||||
|
||||
await act(async () => root.render(render(false)));
|
||||
await rightClick('textarea');
|
||||
assert.equal(pasteCount, 0, 'the solo composer must not paste into the PTY');
|
||||
await rightClick('[data-terminal-cell]');
|
||||
assert.equal(pasteCount, 1, 'ordinary terminal right-click paste still works');
|
||||
|
||||
await act(async () => root.render(render(true)));
|
||||
await rightClick('textarea');
|
||||
assert.equal(pasteCount, 1, 'broadcast compose opens only its own menu');
|
||||
assert.ok(rootElement.querySelector('[data-compose-broadcast-menu]'));
|
||||
await rightClick('[data-compose-broadcast-menu]');
|
||||
assert.equal(pasteCount, 1, 'right-click on the compose menu must not paste into the PTY');
|
||||
});
|
||||
@@ -360,9 +360,11 @@ export const TerminalComposeBar: React.FC<TerminalComposeBarProps> = ({
|
||||
|
||||
const sendToAll = composeSendToAll ?? Boolean(isBroadcastEnabled);
|
||||
const handleBroadcastContextMenu = useCallback((event: React.MouseEvent) => {
|
||||
// A solo composer is inside the terminal's context-menu trigger, but this
|
||||
// gesture must never run a terminal action (such as paste into the PTY).
|
||||
event.stopPropagation();
|
||||
if (!isBroadcastEnabled && !sendToAll) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
setBroadcastMenuAnchor({
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
|
||||
@@ -2601,6 +2601,18 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
|
||||
}
|
||||
}
|
||||
|
||||
// Claim Shift+Insert as clipboard paste before Kitty/Win32 or xterm can
|
||||
// encode it as an Insert key, while preserving user shortcut precedence.
|
||||
if (
|
||||
e.key === "Insert" && e.shiftKey
|
||||
&& !e.ctrlKey && !e.altKey && !e.metaKey
|
||||
) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
void ctx.terminalContextActionsRef?.current?.onPaste?.();
|
||||
return false;
|
||||
}
|
||||
|
||||
// Sogou/macOS CJK punctuation: keydown still reports ASCII "," while the
|
||||
// full-width "," arrives on insertText. Returning false (without
|
||||
// preventDefault) stops xterm/Kitty from sending the half-width key so the
|
||||
@@ -2776,15 +2788,6 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
|
||||
};
|
||||
return true;
|
||||
}
|
||||
// xterm leaves Shift+Insert to the browser's native paste handler. Fan out
|
||||
// the clipboard data from onData instead of encoding an Insert key for
|
||||
// peers or treating the paste as that key's pending legacy data (#4142).
|
||||
if (
|
||||
e.key === "Insert" && e.shiftKey
|
||||
&& !e.ctrlKey && !e.altKey && !e.metaKey
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (!shouldDeferKittyKeyEvent(normalizedKittyEvent)) {
|
||||
const identity = kittyKeyIdentity(e);
|
||||
if (
|
||||
|
||||
@@ -65,3 +65,24 @@ test('disabled or mouse-owned gestures retain the full original event sequence',
|
||||
dispose();
|
||||
dom.window.close();
|
||||
});
|
||||
|
||||
|
||||
test('right-click in the compose bar is never captured or replayed as terminal paste', (t) => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
const dom = new JSDOM('<div id="root"><div data-section="terminal-compose-bar"><textarea></textarea></div></div>');
|
||||
const root = dom.window.document.querySelector<HTMLElement>('#root')!;
|
||||
const compose = root.querySelector('textarea')!;
|
||||
const dispose = installRightClickLongPress(root, () => true);
|
||||
const seen: EventTarget[] = [];
|
||||
root.addEventListener('contextmenu', (event) => seen.push(event.target!));
|
||||
const fire = (type: string) => compose.dispatchEvent(new dom.window.MouseEvent(type, {
|
||||
bubbles: true, cancelable: true, button: 2, buttons: type === 'mouseup' ? 0 : 2,
|
||||
}));
|
||||
fire('mousedown');
|
||||
fire('contextmenu');
|
||||
t.mock.timers.tick(RIGHT_CLICK_LONG_PRESS_MS);
|
||||
fire('mouseup');
|
||||
assert.deepEqual(seen, [compose], 'only the original composer event should be delivered');
|
||||
dispose();
|
||||
dom.window.close();
|
||||
});
|
||||
@@ -37,7 +37,7 @@ export function installRightClickLongPress(
|
||||
suppressContextMenu = false;
|
||||
if (event.button !== 2 || event.shiftKey || event.ctrlKey || event.altKey || event.metaKey
|
||||
|| !canStart()
|
||||
|| (event.target as Element | null)?.closest('[data-terminal-history-preview]')) return;
|
||||
|| (event.target as Element | null)?.closest('[data-terminal-history-preview], [data-section="terminal-compose-bar"]')) return;
|
||||
press = event;
|
||||
suppressContextMenu = true;
|
||||
timer = setTimeout(() => {
|
||||
|
||||
@@ -7,7 +7,7 @@ import { buildSync } from "esbuild";
|
||||
import { JSDOM } from "jsdom";
|
||||
import ts from "typescript";
|
||||
|
||||
test("native Shift+Insert broadcasts clipboard bytes once without an Insert key", async () => {
|
||||
test("Shift+Insert uses onPaste and broadcasts clipboard bytes once across keyboard modes", async () => {
|
||||
const root = fileURLToPath(new URL("../../..", import.meta.url));
|
||||
const layer = readFileSync(new URL("../../TerminalLayer.tsx", import.meta.url), "utf8");
|
||||
const start = layer.indexOf(" const handleBroadcastInput = useCallback(");
|
||||
@@ -21,6 +21,8 @@ test("native Shift+Insert broadcasts clipboard bytes once without an Insert key"
|
||||
contents: `
|
||||
export { createXTermRuntime } from "./components/terminal/runtime/createXTermRuntime";
|
||||
export { DEFAULT_TERMINAL_SETTINGS } from "./domain/models/terminal";
|
||||
export { DEFAULT_KEY_BINDINGS } from "./domain/models/keyBindings";
|
||||
export { pasteTextIntoTerminal } from "./components/terminal/runtime/terminalUserPaste";
|
||||
export { resolveTerminalBroadcastTargetIds } from "./domain/terminalBroadcast";
|
||||
export { dispatchKittyKeyboardBroadcastInput } from "./components/terminal/runtime/kittyKeyboardBroadcast";
|
||||
export * from "./components/terminal/runtime/terminalPacedBroadcast";
|
||||
@@ -50,7 +52,8 @@ test("native Shift+Insert broadcasts clipboard bytes once without an Insert key"
|
||||
`);
|
||||
dom.window.eval(bundle);
|
||||
const results = await dom.window.eval(`(async () => {
|
||||
const {createXTermRuntime, DEFAULT_TERMINAL_SETTINGS, resolveTerminalBroadcastTargetIds,
|
||||
const {createXTermRuntime, DEFAULT_TERMINAL_SETTINGS, DEFAULT_KEY_BINDINGS,
|
||||
pasteTextIntoTerminal, resolveTerminalBroadcastTargetIds,
|
||||
dispatchKittyKeyboardBroadcastInput, markTerminalBroadcastUserInput,
|
||||
captureTerminalBroadcastInput, isTerminalBroadcastInputCurrent} = runtimeTest;
|
||||
const ref = current => ({current});
|
||||
@@ -60,71 +63,123 @@ test("native Shift+Insert broadcasts clipboard bytes once without an Insert key"
|
||||
const canUseDirectSessionWriteFallback = () => true;
|
||||
const isTerminalSensitiveInputActive = () => false;
|
||||
const wires = new Map();
|
||||
const pasteCalls = new Map();
|
||||
const terminalBackend = {
|
||||
writeToSession:(id,data)=>wires.get(id).push(data), resizeSession(){}, openExternalAvailable:false,
|
||||
};
|
||||
${dispatcher}
|
||||
const make = (id, kittyKeyboardProtocolEnabled) => {
|
||||
const make = (id, kittyKeyboardProtocolEnabled, options = {}) => {
|
||||
const container = document.createElement('div'); document.body.appendChild(container);
|
||||
wires.set(id, []);
|
||||
pasteCalls.set(id, 0);
|
||||
const terminalContextActionsRef = ref({});
|
||||
const host = {id,label:id,hostname:'localhost',protocol:'ssh',sshInputCompatibility:false};
|
||||
return createXTermRuntime({
|
||||
const runtime = createXTermRuntime({
|
||||
container, host, getHost:()=>host, sessionId:id, sessionRef:ref(id), statusRef:ref('connected'),
|
||||
fontFamilyId:'jetbrains-mono',resolvedFontFamily:'monospace',fontSize:14,
|
||||
terminalTheme:{colors:{background:'#111111',foreground:'#eeeeee',cursor:'#ffffff',selection:'#444444'}},
|
||||
terminalSettingsRef:ref({...DEFAULT_TERMINAL_SETTINGS,rendererType:'dom',fontLigatures:false,cursorBlink:false}),
|
||||
terminalBackend,hotkeySchemeRef:ref('disabled'),keyBindingsRef:ref([]),onHotkeyActionRef:ref(undefined),
|
||||
terminalBackend,hotkeySchemeRef:ref('pc'),
|
||||
keyBindingsRef:ref(options.bindings ?? DEFAULT_KEY_BINDINGS),onHotkeyActionRef:ref(undefined),
|
||||
terminalContextActionsRef, snippetsRef:ref(options.snippets ?? []),
|
||||
onSnippetShortkeyRef:ref(options.onSnippet),
|
||||
isBroadcastEnabledRef:ref(true),onBroadcastInputRef:ref(handleBroadcastInput),
|
||||
commandBufferRef:ref(''),requestSearchFocus(){},kittyKeyboardProtocolEnabled,
|
||||
commandBufferRef:ref(''),requestSearchFocus:options.onSearch ?? (()=>{}),kittyKeyboardProtocolEnabled,
|
||||
});
|
||||
terminalContextActionsRef.current.onPaste = async () => {
|
||||
pasteCalls.set(id, pasteCalls.get(id) + 1);
|
||||
if (options.delayed) await new Promise(resolve=>setTimeout(resolve,10));
|
||||
pasteTextIntoTerminal(runtime.term, 'clipboard', {scrollOnPaste:false});
|
||||
};
|
||||
return runtime;
|
||||
};
|
||||
const results = [];
|
||||
for (const bracketed of [false,true]) {
|
||||
for (const delayed of [true,false]) {
|
||||
for (const peerKitty of [false,true]) {
|
||||
const source = make('source', false), peer = make('peer', peerKitty);
|
||||
try {
|
||||
sessionsRef.current = ['source','peer'].map(id=>({id,protocol:'ssh',workspaceId:'workspace'}));
|
||||
if (peerKitty) await new Promise(resolve=>peer.term.write('\\x1b[>8u',resolve));
|
||||
if (bracketed) await new Promise(resolve=>source.term.write('\\x1b[?2004h',resolve));
|
||||
const key = new KeyboardEvent('keydown', {
|
||||
bubbles:true,cancelable:true,key:'Insert',code:'Insert',keyCode:45,shiftKey:true,
|
||||
});
|
||||
source.term.textarea.dispatchEvent(key);
|
||||
const beforePaste = [...wires.get('peer')];
|
||||
if (delayed) await new Promise(resolve=>setTimeout(resolve,10));
|
||||
// Supply the native clipboard event which Chromium emits for this chord.
|
||||
const paste = new Event('paste', {bubbles:true,cancelable:true});
|
||||
Object.defineProperty(paste,'clipboardData',{value:{getData:()=> 'clipboard'}});
|
||||
source.term.textarea.dispatchEvent(paste);
|
||||
source.term.textarea.dispatchEvent(new KeyboardEvent('keyup', {
|
||||
bubbles:true,key:'Insert',code:'Insert',keyCode:45,shiftKey:true,
|
||||
}));
|
||||
results.push({bracketed,delayed,peerKitty,beforePaste,
|
||||
prevented:key.defaultPrevented,source:[...wires.get('source')],peer:[...wires.get('peer')]});
|
||||
// Ordinary Insert still uses the physical-key broadcast path.
|
||||
if (!peerKitty) {
|
||||
wires.get('source').length=0; wires.get('peer').length=0;
|
||||
source.term.textarea.dispatchEvent(new KeyboardEvent('keydown', {
|
||||
bubbles:true,cancelable:true,key:'Insert',code:'Insert',keyCode:45,
|
||||
const modes = [
|
||||
{name:'legacy',kitty:false,setup:''},
|
||||
{name:'native-kitty',kitty:false,setup:'\\x1b[>1u'},
|
||||
{name:'native-kitty-all-keys',kitty:false,setup:'\\x1b[>8u'},
|
||||
{name:'netcatty-kitty',kitty:true,setup:'\\x1b[>1u'},
|
||||
{name:'win32',kitty:false,setup:'\\x1b[?9001h'},
|
||||
];
|
||||
for (const mode of modes) {
|
||||
for (const bracketed of [false,true]) {
|
||||
for (const delayed of [true,false]) {
|
||||
for (const peerKitty of [false,true]) {
|
||||
const source = make('source', mode.kitty, {delayed}), peer = make('peer', peerKitty);
|
||||
try {
|
||||
sessionsRef.current = ['source','peer'].map(id=>({id,protocol:'ssh',workspaceId:'workspace'}));
|
||||
if (mode.setup) await new Promise(resolve=>source.term.write(mode.setup,resolve));
|
||||
if (peerKitty) await new Promise(resolve=>peer.term.write('\\x1b[>8u',resolve));
|
||||
if (bracketed) await new Promise(resolve=>source.term.write('\\x1b[?2004h',resolve));
|
||||
const key = new KeyboardEvent('keydown', {
|
||||
bubbles:true,cancelable:true,key:'Insert',code:'Insert',keyCode:45,shiftKey:true,
|
||||
});
|
||||
source.term.textarea.dispatchEvent(key);
|
||||
if (delayed) await new Promise(resolve=>setTimeout(resolve,20));
|
||||
source.term.textarea.dispatchEvent(new KeyboardEvent('keyup', {
|
||||
bubbles:true,key:'Insert',code:'Insert',keyCode:45,shiftKey:true,
|
||||
}));
|
||||
results.push({plainInsert:true,source:[...wires.get('source')],peer:[...wires.get('peer')]});
|
||||
}
|
||||
} finally { source.dispose(); peer.dispose(); }
|
||||
results.push({mode:mode.name,bracketed,delayed,peerKitty,pasteCalls:pasteCalls.get('source'),
|
||||
prevented:key.defaultPrevented,source:[...wires.get('source')],peer:[...wires.get('peer')]});
|
||||
// Ordinary Insert still uses the physical-key broadcast path.
|
||||
if (!peerKitty && mode.name !== 'win32') {
|
||||
wires.get('source').length=0; wires.get('peer').length=0;
|
||||
source.term.textarea.dispatchEvent(new KeyboardEvent('keydown', {
|
||||
bubbles:true,cancelable:true,key:'Insert',code:'Insert',keyCode:45,
|
||||
}));
|
||||
results.push({plainInsert:true,mode:mode.name,pasteCalls:pasteCalls.get('source'),
|
||||
source:[...wires.get('source')],peer:[...wires.get('peer')]});
|
||||
}
|
||||
wires.get('source').length=0; wires.get('peer').length=0;
|
||||
const pasteShortcut = new KeyboardEvent('keydown', {
|
||||
bubbles:true,cancelable:true,key:'V',code:'KeyV',keyCode:86,ctrlKey:true,shiftKey:true,
|
||||
});
|
||||
source.term.textarea.dispatchEvent(pasteShortcut);
|
||||
if (delayed) await new Promise(resolve=>setTimeout(resolve,20));
|
||||
source.term.textarea.dispatchEvent(new KeyboardEvent('keyup', {
|
||||
bubbles:true,key:'V',code:'KeyV',keyCode:86,ctrlKey:true,shiftKey:true,
|
||||
}));
|
||||
results.push({configuredPaste:true,mode:mode.name,bracketed,pasteCalls:pasteCalls.get('source'),
|
||||
prevented:pasteShortcut.defaultPrevented,source:[...wires.get('source')],peer:[...wires.get('peer')]});
|
||||
} finally { source.dispose(); peer.dispose(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const shortcut of ['binding','snippet']) {
|
||||
let searchCalls = 0, snippetCalls = 0;
|
||||
const source = make('source', true, shortcut === 'binding'
|
||||
? {onSearch:()=>searchCalls++,bindings:DEFAULT_KEY_BINDINGS.map(binding=>binding.action === 'searchTerminal'
|
||||
? {...binding,pc:'Shift + Insert'} : binding)}
|
||||
: {snippets:[{id:'snippet',shortkey:'Shift + Insert'}],onSnippet:()=>snippetCalls++});
|
||||
try {
|
||||
await new Promise(resolve=>source.term.write('\\x1b[>1u',resolve));
|
||||
source.term.textarea.dispatchEvent(new KeyboardEvent('keydown', {
|
||||
bubbles:true,cancelable:true,key:'Insert',code:'Insert',keyCode:45,shiftKey:true,
|
||||
}));
|
||||
results.push({shortcut,pasteCalls:pasteCalls.get('source'),snippetCalls,searchCalls,
|
||||
source:[...wires.get('source')]});
|
||||
} finally { source.dispose(); }
|
||||
}
|
||||
return JSON.stringify(results);
|
||||
})()`);
|
||||
for (const result of JSON.parse(results)) {
|
||||
if (result.plainInsert) {
|
||||
assert.equal(result.pasteCalls, 1);
|
||||
assert.deepEqual(result.source, ["\x1b[2~"]);
|
||||
assert.deepEqual(result.peer, ["\x1b[2~"]);
|
||||
continue;
|
||||
}
|
||||
if (result.shortcut) {
|
||||
assert.equal(result.pasteCalls, 0, result.shortcut);
|
||||
assert.equal(result.snippetCalls, result.shortcut === 'snippet' ? 1 : 0);
|
||||
assert.equal(result.searchCalls, result.shortcut === 'binding' ? 1 : 0);
|
||||
assert.deepEqual(result.source, []);
|
||||
continue;
|
||||
}
|
||||
const label = JSON.stringify(result);
|
||||
assert.deepEqual(result.beforePaste, [], label);
|
||||
assert.equal(result.prevented, false, "native paste must remain enabled: " + label);
|
||||
assert.equal(result.pasteCalls, result.configuredPaste ? 2 : 1, label);
|
||||
assert.equal(result.prevented, true, label);
|
||||
const expected = result.bracketed ? "\x1b[200~clipboard\x1b[201~" : "clipboard";
|
||||
assert.deepEqual(result.source, [expected], label);
|
||||
assert.deepEqual(result.peer, [expected], label);
|
||||
|
||||
@@ -374,3 +374,14 @@ test('side panel close button stays visible at every panel width', () => {
|
||||
assert.match(closeSlice, /className="h-7 w-7 shrink-0 rounded-md p-0 hover:bg-transparent"/);
|
||||
assert.doesNotMatch(closeSlice, /\bhidden\b|max-(sm|md|lg|xl):/);
|
||||
});
|
||||
|
||||
test('magnified side-panel chrome thickens the accent stroke on low-DPR displays', () => {
|
||||
const source = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8');
|
||||
const overlay = source.slice(
|
||||
source.indexOf('data-section="pane-magnification-overlay"'),
|
||||
source.indexOf('data-section="pane-magnification-content"'),
|
||||
);
|
||||
assert.match(overlay, /overflow-hidden rounded-md border bg-background shadow-2xl/);
|
||||
assert.match(overlay, /borderColor: sidePanelTheme\.accent,/);
|
||||
assert.match(overlay, /resolveMagnifiedChromeBorderWidth\(/);
|
||||
});
|
||||
@@ -64,7 +64,7 @@ import { PersistentSidePanelPortal, SidePanelMountedContent } from './terminalLa
|
||||
import { usePluginTerminalSidebar } from '../../application/state/usePluginTerminalSidebar';
|
||||
import { PluginTerminalSidebarPageHost } from '../plugins/PluginTerminalSidebar';
|
||||
import { PluginContributionIcon } from '../plugins/PluginContributionIcon';
|
||||
import { getPaneMagnificationShortcutLabel } from '../../domain/paneMagnification';
|
||||
import { getPaneMagnificationShortcutLabel, resolveMagnifiedChromeBorderWidth } from '../../domain/paneMagnification';
|
||||
|
||||
const MemoizedSidePanelMountedContent = memo(
|
||||
SidePanelMountedContent,
|
||||
@@ -1545,6 +1545,9 @@ function TerminalLayerSidePanelInner({ ctx, pluginSidebar }: { ctx: SidePanelCon
|
||||
className="absolute inset-3 flex flex-col overflow-hidden rounded-md border bg-background shadow-2xl animate-in fade-in zoom-in-95 duration-150"
|
||||
style={{
|
||||
borderColor: sidePanelTheme.accent,
|
||||
borderWidth: resolveMagnifiedChromeBorderWidth(
|
||||
typeof window === 'undefined' ? 1 : (window.devicePixelRatio || 1),
|
||||
),
|
||||
backgroundColor: sidePanelTheme.termBg,
|
||||
color: sidePanelTheme.termFg,
|
||||
}}
|
||||
|
||||
@@ -52,6 +52,7 @@ import type { ResolvedAppearance, TerminalAppearanceHostScope } from '../../doma
|
||||
import type { TerminalSidePanelAutoOpenTab } from '../../domain/terminalSidePanelAutoOpen';
|
||||
import type { SidePanelTool } from '../../domain/sidePanelLayout';
|
||||
import {
|
||||
resolveMagnifiedChromeBorderWidth,
|
||||
resolvePaneMagnificationStyle,
|
||||
type PaneMagnificationController,
|
||||
type PaneMagnificationTarget,
|
||||
@@ -1439,10 +1440,12 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
|
||||
observer.observe(surface);
|
||||
return () => observer.disconnect();
|
||||
}, [isMagnified]);
|
||||
const magnifiedDevicePixelRatio = typeof window === 'undefined' ? 1 : (window.devicePixelRatio || 1);
|
||||
const style: React.CSSProperties = resolvePaneMagnificationStyle(
|
||||
layoutStyle,
|
||||
isMagnified && !!magnifiedSurfaceBounds,
|
||||
magnifiedSurfaceBounds,
|
||||
magnifiedDevicePixelRatio,
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
@@ -1605,6 +1608,9 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
|
||||
style={{
|
||||
...style,
|
||||
borderColor: isMagnified && magnifiedSurfaceBounds ? sessionAppearanceTheme.colors.cursor : undefined,
|
||||
borderWidth: isMagnified && magnifiedSurfaceBounds
|
||||
? resolveMagnifiedChromeBorderWidth(magnifiedDevicePixelRatio)
|
||||
: undefined,
|
||||
}}
|
||||
tabIndex={-1}
|
||||
onClick={handlePaneClick}
|
||||
|
||||
@@ -15,6 +15,14 @@ test("magnified terminal panes use the resolved terminal accent for border chrom
|
||||
|
||||
assert.match(paneSource, /isMagnified && magnifiedSurfaceBounds && "overflow-hidden rounded-md border shadow-2xl /);
|
||||
assert.match(paneSource, /borderColor: isMagnified && magnifiedSurfaceBounds \? sessionAppearanceTheme\.colors\.cursor : undefined/);
|
||||
assert.match(paneSource, /borderWidth: isMagnified && magnifiedSurfaceBounds/);
|
||||
assert.match(paneSource, /resolveMagnifiedChromeBorderWidth\(magnifiedDevicePixelRatio\)/);
|
||||
});
|
||||
|
||||
test("magnified terminal panes snap overlay bounds to the device-pixel grid", () => {
|
||||
const source = readFileSync(new URL("./TerminalLayerSupport.tsx", import.meta.url), "utf8");
|
||||
assert.match(source, /resolvePaneMagnificationStyle\(\s*layoutStyle,\s*isMagnified && !!magnifiedSurfaceBounds,\s*magnifiedSurfaceBounds,\s*magnifiedDevicePixelRatio,\s*\)/);
|
||||
assert.match(source, /const magnifiedDevicePixelRatio = typeof window === 'undefined' \? 1 : \(window\.devicePixelRatio \|\| 1\)/);
|
||||
});
|
||||
|
||||
test("terminal keyboard focus updates the pane selected for magnification", () => {
|
||||
|
||||
@@ -7,7 +7,9 @@ import {
|
||||
isPaneMagnificationSelectionValid,
|
||||
resolvePaneMagnificationCandidate,
|
||||
resolvePaneMagnificationStyle,
|
||||
resolveMagnifiedChromeBorderWidth,
|
||||
resolveTwoPaneMagnificationStyle,
|
||||
snapCssRectToDevicePixels,
|
||||
type PaneMagnificationController,
|
||||
} from './paneMagnification.ts';
|
||||
|
||||
@@ -90,6 +92,53 @@ test('magnification overlays the original layout without changing its rect', ()
|
||||
});
|
||||
});
|
||||
|
||||
test('magnified chrome uses a 2px accent stroke only below 1.5 device pixels', () => {
|
||||
assert.equal(resolveMagnifiedChromeBorderWidth(1), 2);
|
||||
assert.equal(resolveMagnifiedChromeBorderWidth(1.2), 2);
|
||||
assert.equal(resolveMagnifiedChromeBorderWidth(1.49), 2);
|
||||
assert.equal(resolveMagnifiedChromeBorderWidth(1.5), 1);
|
||||
assert.equal(resolveMagnifiedChromeBorderWidth(2), 1);
|
||||
assert.equal(resolveMagnifiedChromeBorderWidth(0), 1);
|
||||
});
|
||||
|
||||
test('magnified surface bounds snap to the device-pixel grid after the 12px inset', () => {
|
||||
const original = { left: '0px', top: '0px', width: '100px', height: '100px' };
|
||||
// Integer CSS pixels at 1x stay unchanged (existing contract).
|
||||
assert.deepEqual(resolvePaneMagnificationStyle(original, true, {
|
||||
left: 120,
|
||||
top: 80,
|
||||
width: 1400,
|
||||
height: 900,
|
||||
}, 1), {
|
||||
position: 'fixed',
|
||||
left: '132px',
|
||||
top: '92px',
|
||||
width: '1376px',
|
||||
height: '876px',
|
||||
zIndex: 50,
|
||||
});
|
||||
|
||||
// 120.4+12=132.4 at 2x -> 264.8 rounds to 265 -> 132.5
|
||||
// right: 120.4+1400-12=1508.4 at 2x -> 3016.8 rounds to 3017 -> 1508.5
|
||||
const snapped = resolvePaneMagnificationStyle(original, true, {
|
||||
left: 120.4,
|
||||
top: 80.4,
|
||||
width: 1400,
|
||||
height: 900,
|
||||
}, 2);
|
||||
assert.deepEqual(snapped, {
|
||||
position: 'fixed',
|
||||
left: '132.5px',
|
||||
top: '92.5px',
|
||||
width: '1376px',
|
||||
height: '876px',
|
||||
zIndex: 50,
|
||||
});
|
||||
|
||||
const rect = snapCssRectToDevicePixels(10.2, 20.2, 110.2, 80.2, 2);
|
||||
assert.deepEqual(rect, { left: 10, top: 20, width: 100, height: 60 });
|
||||
});
|
||||
|
||||
test('two-pane magnification keeps the dormant pane geometry unchanged', () => {
|
||||
assert.deepEqual(resolveTwoPaneMagnificationStyle('left', true, true), {
|
||||
left: '12px', top: '12px', width: 'calc(100% - 24px)', height: 'calc(100% - 24px)', zIndex: 50,
|
||||
|
||||
@@ -92,19 +92,52 @@ export function getPaneMagnificationShortcutLabel(
|
||||
return (hotkeyScheme === 'mac' ? binding?.mac : binding?.pc)?.replace(/ \+ /g, '+') ?? '';
|
||||
}
|
||||
|
||||
export function resolveMagnifiedChromeBorderWidth(devicePixelRatio = 1): number {
|
||||
return devicePixelRatio > 0 && devicePixelRatio < 1.5 ? 2 : 1;
|
||||
}
|
||||
|
||||
export function snapCssRectToDevicePixels(
|
||||
left: number,
|
||||
top: number,
|
||||
right: number,
|
||||
bottom: number,
|
||||
devicePixelRatio = 1,
|
||||
): { left: number; top: number; width: number; height: number } {
|
||||
const dpr = devicePixelRatio > 0 ? devicePixelRatio : 1;
|
||||
const snap = (value: number) => Math.round(value * dpr) / dpr;
|
||||
const snappedLeft = snap(left);
|
||||
const snappedTop = snap(top);
|
||||
const snappedRight = snap(right);
|
||||
const snappedBottom = snap(bottom);
|
||||
return {
|
||||
left: snappedLeft,
|
||||
top: snappedTop,
|
||||
width: Math.max(0, snappedRight - snappedLeft),
|
||||
height: Math.max(0, snappedBottom - snappedTop),
|
||||
};
|
||||
}
|
||||
|
||||
export function resolvePaneMagnificationStyle(
|
||||
original: React.CSSProperties,
|
||||
magnified: boolean,
|
||||
surfaceBounds?: { left: number; top: number; width: number; height: number } | null,
|
||||
devicePixelRatio = 1,
|
||||
): React.CSSProperties {
|
||||
if (!magnified) return original;
|
||||
if (surfaceBounds) {
|
||||
const snapped = snapCssRectToDevicePixels(
|
||||
surfaceBounds.left + 12,
|
||||
surfaceBounds.top + 12,
|
||||
surfaceBounds.left + surfaceBounds.width - 12,
|
||||
surfaceBounds.top + surfaceBounds.height - 12,
|
||||
devicePixelRatio,
|
||||
);
|
||||
return {
|
||||
position: 'fixed',
|
||||
left: `${surfaceBounds.left + 12}px`,
|
||||
top: `${surfaceBounds.top + 12}px`,
|
||||
width: `${Math.max(0, surfaceBounds.width - 24)}px`,
|
||||
height: `${Math.max(0, surfaceBounds.height - 24)}px`,
|
||||
left: `${snapped.left}px`,
|
||||
top: `${snapped.top}px`,
|
||||
width: `${snapped.width}px`,
|
||||
height: `${snapped.height}px`,
|
||||
zIndex: 50,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -70,6 +70,10 @@ const CMD_PROMPT_PATTERN = /^[A-Za-z]:(?:\\[^<>"|]*)?>$/;
|
||||
// the final `]` before `$`/`#` is the delimiter.
|
||||
const POSIX_PROMPT_PATTERN = /^(?:[^\s@]+@[^\s:]+(?::[^\n\r]*)?|\[[^\s@\]]+@[^\s\]:]+(?:\s+[^\n\r]+)?\])[#$]$/;
|
||||
|
||||
// Bracket PS1 without @host, with bash `\t` time: `[\u \t \w]$` -> `[root 12:04:23 ~]$` (#4276).
|
||||
// Require HH:MM:SS so loose `[word]$` output cannot count as idle.
|
||||
const BRACKET_TIME_POSIX_PROMPT_PATTERN = /^\[[^\s@\]]+\s+\d{2}:\d{2}:\d{2}(?:\s+[^\n\r\]]+)?\][#$]$/;
|
||||
|
||||
// Space-separated bash PS1 `\u@\h \w $ ` renders as `user@host ~ $`.
|
||||
// macOS ships zsh with `%n@%m %1~ %#`, which renders as
|
||||
// `user@host ~ %` / `user@host My Project %`; privileged shells end in `#`.
|
||||
@@ -137,6 +141,7 @@ function isDefaultPosixPromptLine(line) {
|
||||
const withoutEnvPrefix = normalized.replace(/^\([^()\n\r]+\)\s+/, "");
|
||||
return (
|
||||
POSIX_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||||
BRACKET_TIME_POSIX_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||||
PAREN_POSIX_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||||
ALPINE_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||||
ZSH_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||||
|
||||
@@ -192,6 +192,30 @@ test("isDefaultPosixPromptLine matches classic user@host prompts", () => {
|
||||
assert.equal(isDefaultPosixPromptLine(""), false);
|
||||
});
|
||||
|
||||
test("recognizes bracketed time prompts without a hostname and preserves trailing space", () => {
|
||||
for (const prompt of [
|
||||
"[root 12:04:23 ~]$",
|
||||
"[root 12:04:23 ~]$ ",
|
||||
"[alice 00:00:00 /var/log]# ",
|
||||
"[alice-admin 23:59:59 ~/src]$ ",
|
||||
]) {
|
||||
assert.equal(isDefaultPosixPromptLine(prompt), true, prompt);
|
||||
assert.equal(extractTrailingIdlePrompt(`welcome\r\n${prompt}`), prompt, prompt);
|
||||
}
|
||||
});
|
||||
|
||||
test("bracketed time prompt recognition rejects pending input and prompts without time", () => {
|
||||
for (const line of [
|
||||
"[root 12:04:23 ~]$ hostname",
|
||||
"[root 12:04:23 ~]$ echo $",
|
||||
"[root ~]$",
|
||||
"[word]$",
|
||||
]) {
|
||||
assert.equal(isDefaultPosixPromptLine(line), false, line);
|
||||
assert.equal(extractTrailingIdlePrompt(`welcome\r\n${line}`), "", line);
|
||||
}
|
||||
});
|
||||
|
||||
test("recognizes space-separated Bash idle prompts and preserves trailing whitespace", () => {
|
||||
for (const prompt of [
|
||||
"root@VM-Q7L4M8P2 ~ $",
|
||||
@@ -488,6 +512,13 @@ test("extracts a trailing RHEL-family bracketed idle prompt", () => {
|
||||
assert.equal(extractTrailingIdlePrompt("welcome\r\nroot@host ~#"), "");
|
||||
});
|
||||
|
||||
test("extractTrailingIdlePrompt recognizes an ANSI-colored bracketed time prompt", () => {
|
||||
assert.equal(
|
||||
extractTrailingIdlePrompt("welcome\r\n[\x1b[1;34mroot \x1b[1;36m12:04:23 \x1b[1;32m~\x1b[0m]$ "),
|
||||
"[root 12:04:23 ~]$ ",
|
||||
);
|
||||
});
|
||||
|
||||
test("extractTrailingIdlePrompt recognizes a two-line user@host then bare $/# PS1", () => {
|
||||
// export PS1="\u@\h: \w\n$ " paints the host line, then a lone "$ ".
|
||||
// The cached prompt must keep both lines so a lone "$" cannot satisfy endsWith.
|
||||
@@ -1233,6 +1264,14 @@ test("trackSessionIdlePrompt and getFreshIdlePrompt accept an Oracle/RHEL bracke
|
||||
assert.equal(getFreshIdlePrompt(bracketedPath), "[user@host My [Project]]$ ");
|
||||
});
|
||||
|
||||
test("trackSessionIdlePrompt and getFreshIdlePrompt accept a bracketed time prompt", () => {
|
||||
const session = {};
|
||||
const prompt = "[root 12:04:23 ~]$ ";
|
||||
assert.equal(trackSessionIdlePrompt(session, `Last login...\r\n${prompt}`), prompt);
|
||||
assert.equal(session.lastIdlePrompt, prompt);
|
||||
assert.equal(getFreshIdlePrompt(session), prompt);
|
||||
});
|
||||
|
||||
test("visible idle prompt survives a PSReadLine erase that leaves the raw tail dirty", () => {
|
||||
// PSReadLine echoes the pending-input clear prefix (`ggd2147483647d` / `i`),
|
||||
// then homes the cursor and erases those keys with CSI. stripAnsi drops the
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const NETCATTY_MCP_SERVER_INSTRUCTIONS =
|
||||
"Use Netcatty tools for terminals, hosts, SFTP, vault, snippets/scripts, and port forwards. For terminal work, call get_environment first; select by label or hostname and pass sessionId to terminal_execute/terminal_start. Never use the local shell for Netcatty session commands. If none matches, use vault_hosts_list and host_open. 15 core tools start loaded. For attachments, advanced SFTP, vault/notes, snippets, scripts, or port forwards, call load_netcatty_tools with a toolset; use all for every tool.";
|
||||
"Call get_environment first; select by label or hostname and pass sessionId to terminal tools. Never use the local shell for Netcatty session commands. If none matches, use vault_hosts_list and host_open. 15 core tools start loaded. Use load_netcatty_tools: sessions, attachments, sftp_advanced, vault_hosts, vault_notes, snippets, scripts, portforward, or all. For disconnected in-scope sessions, load sessions; use session_reconnect/session_recover instead of host_open (creates a new tab).";
|
||||
|
||||
module.exports = { NETCATTY_MCP_SERVER_INSTRUCTIONS };
|
||||
@@ -18,6 +18,9 @@ test("MCP server instructions route Netcatty terminal work through environment d
|
||||
assert.match(NETCATTY_MCP_SERVER_INSTRUCTIONS, /vault_hosts_list and host_open/);
|
||||
assert.match(NETCATTY_MCP_SERVER_INSTRUCTIONS, /load_netcatty_tools/);
|
||||
assert.match(NETCATTY_MCP_SERVER_INSTRUCTIONS, /15 core tools/);
|
||||
assert.match(NETCATTY_MCP_SERVER_INSTRUCTIONS, /load_netcatty_tools: sessions,/);
|
||||
assert.match(NETCATTY_MCP_SERVER_INSTRUCTIONS, /disconnected in-scope sessions, load sessions/);
|
||||
assert.match(NETCATTY_MCP_SERVER_INSTRUCTIONS, /session_reconnect\/session_recover instead of host_open \(creates a new tab\)/);
|
||||
});
|
||||
|
||||
test("stdio MCP server publishes the routing instructions during initialization", () => {
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { jsonSchema, tool } from 'ai';
|
||||
import { MockLanguageModelV4, simulateReadableStream } from 'ai/test';
|
||||
import { processCattyStream, shouldEmitAgentEventsForStreamChunk } from './turnDrivers/cattyStreamProcessor';
|
||||
import type { CattyToolsBundle } from './capabilityTools';
|
||||
import { createInitialCattyRuntimeContext } from './cattyRuntimeContext';
|
||||
import type { ChatMessage } from '../types';
|
||||
|
||||
@@ -111,3 +113,100 @@ describe('processCattyStream reasoning continuation', () => {
|
||||
assert.match(continuation?.reasoningParts?.map(part => part.text).join('') ?? '', /thinking/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('processCattyStream iteration limit', () => {
|
||||
const usage = {
|
||||
inputTokens: { total: 1, noCache: 1, cacheRead: undefined, cacheWrite: undefined },
|
||||
outputTokens: { total: 1, text: 1, reasoning: undefined },
|
||||
};
|
||||
|
||||
async function run(t: import('node:test').TestContext, replies: ('poll' | 'summary')[], maxIterations: number) {
|
||||
const originalRaf = globalThis.requestAnimationFrame;
|
||||
const originalCancelRaf = globalThis.cancelAnimationFrame;
|
||||
t.after(() => {
|
||||
globalThis.requestAnimationFrame = originalRaf;
|
||||
globalThis.cancelAnimationFrame = originalCancelRaf;
|
||||
});
|
||||
globalThis.requestAnimationFrame = callback => setTimeout(() => callback(0), 0) as unknown as number;
|
||||
globalThis.cancelAnimationFrame = id => clearTimeout(id);
|
||||
|
||||
const messages: ChatMessage[] = [{ id: 'assistant-1', role: 'assistant', content: '', timestamp: 0 }];
|
||||
let calls = 0;
|
||||
const model = new MockLanguageModelV4({
|
||||
doStream: async () => {
|
||||
const reply = replies[calls++];
|
||||
assert.ok(reply, 'unexpected extra model step');
|
||||
return {
|
||||
stream: simulateReadableStream({ chunks: [
|
||||
{ type: 'stream-start', warnings: [] },
|
||||
...(reply === 'poll' ? [{
|
||||
type: 'tool-call' as const,
|
||||
toolCallId: `poll-${calls}`,
|
||||
toolName: 'terminal_poll',
|
||||
input: '{"jobId":"job-1"}',
|
||||
}] : [
|
||||
{ type: 'text-start' as const, id: 'summary' },
|
||||
{ type: 'text-delta' as const, id: 'summary', delta: 'The job completed.' },
|
||||
{ type: 'text-end' as const, id: 'summary' },
|
||||
]),
|
||||
{ type: 'finish', finishReason: { unified: reply === 'poll' ? 'tool-calls' : 'stop', raw: undefined }, usage },
|
||||
] }),
|
||||
};
|
||||
},
|
||||
});
|
||||
await processCattyStream({
|
||||
streamSessionId: 'session-1', model, systemPrompt: 'test',
|
||||
toolsBundle: {
|
||||
tools: {
|
||||
terminal_poll: tool({
|
||||
inputSchema: jsonSchema<{ jobId: string }>({
|
||||
type: 'object', properties: { jobId: { type: 'string' } }, required: ['jobId'],
|
||||
}),
|
||||
execute: async ({ jobId }) => ({ jobId, status: 'running', output: 'buffered output' }),
|
||||
}),
|
||||
} as unknown as CattyToolsBundle['tools'],
|
||||
toolsContext: {},
|
||||
},
|
||||
sdkMessages: [{ role: 'user', content: 'Check the job' }],
|
||||
signal: new AbortController().signal,
|
||||
currentAssistantMsgId: 'assistant-1', maxIterations,
|
||||
runtimeContext: createInitialCattyRuntimeContext({
|
||||
chatSessionId: 'session-1', turnId: 'turn-1', permissionMode: 'auto', scopeType: 'terminal',
|
||||
}),
|
||||
ui: {
|
||||
addMessageToSession: (sessionId, message) => {
|
||||
assert.equal(sessionId, 'session-1');
|
||||
messages.push(message);
|
||||
},
|
||||
updateMessageById: (_sessionId, id, updater) => {
|
||||
const index = messages.findIndex(message => message.id === id);
|
||||
if (index >= 0) messages[index] = updater(messages[index]);
|
||||
},
|
||||
},
|
||||
});
|
||||
return { messages, calls };
|
||||
}
|
||||
|
||||
it('adds a non-error assistant notice after terminal_poll exhausts the step cap', async t => {
|
||||
const { messages, calls } = await run(t, ['poll', 'poll'], 2);
|
||||
assert.equal(calls, 2);
|
||||
assert.equal(messages.at(-2)?.role, 'tool');
|
||||
assert.match(messages.at(-2)?.toolResults?.[0].content ?? '', /job-1/);
|
||||
const notice = messages.at(-1)!;
|
||||
assert.equal(notice.role, 'assistant');
|
||||
assert.equal(notice.iterationLimit, 2);
|
||||
assert.equal(notice.errorInfo, undefined);
|
||||
});
|
||||
|
||||
for (const [name, replies, maxIterations] of [
|
||||
['natural stop before the cap', ['summary'], 2],
|
||||
['natural stop on the last allowed step', ['summary'], 1],
|
||||
['post-tool summary on the last allowed step', ['poll', 'summary'], 2],
|
||||
] as const) {
|
||||
it(`does not add a limit notice for ${name}`, async t => {
|
||||
const { messages } = await run(t, [...replies], maxIterations);
|
||||
assert.equal(messages.at(-1)?.content, 'The job completed.');
|
||||
assert.ok(messages.every(message => message.iterationLimit === undefined));
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -141,6 +141,8 @@ export async function processCattyStream(input: ProcessCattyStreamInput): Promis
|
||||
: undefined;
|
||||
const promptCache = createCattyPromptCache(systemPrompt, model.provider, endpoint);
|
||||
|
||||
let reachedIterationLimit = false;
|
||||
const stopAtIterationLimit = isStepCount(maxIterations);
|
||||
const result = streamText({
|
||||
model,
|
||||
messages: promptCache.prepareMessages(sdkMessages),
|
||||
@@ -152,7 +154,12 @@ export async function processCattyStream(input: ProcessCattyStreamInput): Promis
|
||||
permissionMode: runtimeContext.permissionMode,
|
||||
chatSessionId: runtimeContext.chatSessionId,
|
||||
}),
|
||||
stopWhen: isStepCount(maxIterations),
|
||||
// The SDK evaluates stopWhen only when tool work would allow another
|
||||
// step. A natural final reply (even on the last allowed step) bypasses it.
|
||||
stopWhen: async (options) => {
|
||||
reachedIterationLimit = await stopAtIterationLimit(options);
|
||||
return reachedIterationLimit;
|
||||
},
|
||||
abortSignal: signal,
|
||||
include: { rawChunks: true },
|
||||
timeout: buildCattyStreamTimeouts({
|
||||
@@ -580,6 +587,16 @@ export async function processCattyStream(input: ProcessCattyStreamInput): Promis
|
||||
const usage = await result.usage;
|
||||
const finalStep = await result.finalStep;
|
||||
const performance = finalStep?.performance;
|
||||
if (reachedIterationLimit && !signal.aborted) {
|
||||
clearCompactionStatusFromAssistant(activeMsgId);
|
||||
ui.addMessageToSession(streamSessionId, {
|
||||
id: generateId(),
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
timestamp: Date.now(),
|
||||
iterationLimit: maxIterations,
|
||||
});
|
||||
}
|
||||
// onEnd can run before this consumer flushes its final text and creates the
|
||||
// post-tool assistant message. Attach turn totals only after that flush.
|
||||
if (usage) {
|
||||
|
||||
@@ -171,6 +171,8 @@ export interface ChatMessage {
|
||||
timestamp: number;
|
||||
model?: string;
|
||||
providerId?: AIProviderId;
|
||||
/** Catty stopped at its tool-loop cap; rendered as a non-error notice. */
|
||||
iterationLimit?: number;
|
||||
errorInfo?: {
|
||||
type: 'network' | 'auth' | 'timeout' | 'provider' | 'agent' | 'unknown';
|
||||
message: string;
|
||||
|
||||
@@ -11,7 +11,8 @@ Use the Netcatty MCP tools whenever the task targets Netcatty or a remote sessio
|
||||
|
||||
- For terminal work, call `get_environment` first. Select the current target by its label or hostname and pass its `sessionId` to terminal tools.
|
||||
- Never use the local shell for commands intended for a Netcatty session.
|
||||
- If a required specialized tool is not visible, call `load_netcatty_tools` with `attachments`, `sftp_advanced`, `vault_hosts`, `vault_notes`, `snippets`, `scripts`, or `portforward`. Use `all` only when several categories are needed.
|
||||
- If a required specialized tool is not visible, call `load_netcatty_tools` with `sessions`, `attachments`, `sftp_advanced`, `vault_hosts`, `vault_notes`, `snippets`, `scripts`, or `portforward`. Use `all` only when several categories are needed.
|
||||
- For disconnected sessions already in scope, load `sessions` and use `session_reconnect` / `session_recover` instead of `host_open`, which creates a new tab.
|
||||
- If no live session matches, use `vault_hosts_list` and `host_open`. A newly opened tab lands in your own bound workspace by default (workspace chat → that workspace; terminal chat → that terminal's workspace); only pass `workspaceId` when the user asks for a different target. Close only sessions opened for the current task when they are no longer needed.
|
||||
- Use `terminal_execute` for short commands. Use `terminal_start`, `terminal_poll`, and `terminal_stop` for long-running or streaming commands.
|
||||
- Treat Netcatty permission denials and tool errors as authoritative. Do not bypass them with local commands or alternate connection tools.
|
||||
Reference in new issue
Block a user