Compare commits

...
Author SHA1 Message Date
bincxz 1c1be0b3c8 fix(plugins): preserve plugin tabs on overlay close and harden host surface controls 2026-11-21 19:08:52 +08:00
陈大猫 519c463048 Merge pull request #4291 from binaricat/fix/4275-retain-configured-default-agent
fix(ai): retain the configured default agent when its probe fails
2026-11-21 17:56:30 +08:00
陈大猫 14767f6a48 Merge pull request #4264 from binaricat/fix/4017-isolate-unpackaged-profile
fix(electron): isolate unpackaged app profiles
2026-11-21 17:46:00 +08:00
陈大猫 e185306e50 Merge pull request #4265 from binaricat/fix/3570-folder-partial-pause
fix(sftp): show folder pause failures without resuming siblings
2026-11-21 17:41:32 +08:00
陈大猫 b864bf55b6 fix(ai): retain configured default agent during failed discovery 2026-11-21 17:38:41 +08:00
陈大猫 9c49a07e16 Merge pull request #4290 from binaricat/fix/4262-compose-right-click
fix(terminal): keep composer right-click out of the live terminal
2026-11-21 17:04:47 +08:00
陈大猫 c5a855d885 Merge pull request #4289 from binaricat/fix/4261-rtl-pane-guard-8e86279
fix(terminal): render RTL text without destabilizing WebGL (#4261)
2026-11-21 16:52:50 +08:00
陈大猫 a2e04556b7 Merge pull request #4216 from binaricat/fix/4214-codebuddy-empty-tools
fix(ai): do not pass empty CodeBuddy tools whitelist that hides MCP tools
2026-11-21 16:51:55 +08:00
陈大猫 0fbf1cdc14 fix(terminal): fit wide RTL runs without clipping glyphs 2026-11-21 16:08:53 +08:00
陈大猫 7bbff7ce6e fix(terminal): preserve RTL DOM cell widths and detect astral RTL 2026-11-21 15:49:45 +08:00
陈大猫 57227dfe1b Merge pull request #4288 from binaricat/fix/release-hide-plugin-platform
fix(release): temporarily hide the plugin platform
2026-11-21 15:35:43 +08:00
陈大猫 470628b1a3 fix(terminal): keep composer right-click out of the live terminal
Address the unintended paste described in #4262.
2026-11-21 13:55:51 +08:00
陈大猫 ef99e0daf7 Merge pull request #4182 from binaricat/fix/4181-mcp-session-reconnect-discoverability
fix(mcp): advertise sessions reconnect tools to agents
2026-11-21 13:41:12 +08:00
陈大猫 18a9000278 Merge pull request #4225 from binaricat/fix/4224-max-iteration-visible-continue
fix(ai): surface max-iteration stop with a Continue action (Fixes #4224)
2026-11-21 13:41:06 +08:00
陈大猫 19ff28528d fix(ai): keep CodeBuddy MCP discovery isolated 2026-11-21 12:17:23 +08:00
陈大猫 8e862798e4 fix(terminal): keep RTL shaping off the WebGL atlas
Preserve the original RTL implementation and keep affected panes on the DOM renderer to avoid an oversized WebGL glyph allocation. Unchanged ASCII panes retain their renderer.
2026-11-21 11:02:05 +08:00
陈大猫 5b9d5351d7 fix(release): hide the plugin platform by default 2026-11-21 10:31:43 +08:00
Serag AhmedandClaude Opus 5.5 112bab7292 fix(terminal): draw RTL text in display order with joined letters
xterm.js has no bidi support and draws every cell on its own, so Arabic,
Persian and Hebrew words came out reversed and Arabic letters unjoined
(#4261).

Register a character joiner that marks the parts of each line the Unicode
Bidirectional Algorithm (bidi-js) puts at a right-to-left or number level
in a left-to-right paragraph. Both the WebGL and DOM renderers draw a
joined range as one string through the browser's text engine, which
orders it, shapes the letters and mirrors brackets. The buffer is
unchanged, so selection, copy, search and cursor positions still use the
logical text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 13:50:08 +03:00
陈大猫 ed9da31034 fix(terminal): keep Shift+Insert as paste when Kitty keyboard is active
Related #4279

When a TUI such as Claude Code enables the Kitty keyboard protocol, Shift+Insert was encoded as an Insert key (CSI 2;2~) instead of pasting. Netcatty always constructs xterm with Kitty support, so this happened even with the user Kitty setting off.

This claims bare Shift+Insert as clipboard paste (the same onPaste path as the paste keybinding) after user/snippet shortcuts and before Kitty/Win32 encoding.

This does not change right-click / context-menu behavior while mouse tracking is active.
2026-11-20 15:53:40 +08:00
陈大猫 3d302e2456 fix(ai): recognize bracket prompts with a time field as idle (#4277)
Fixes #4276
2026-11-20 12:47:23 +08:00
GOUKI9999 f987341bf2 fix(ai): preserve saved harness paths on failed probes 2026-11-19 16:20:43 +08:00
陈大猫 5e4195bf7f fix(ui): snap and thicken magnified pane chrome on low-DPR displays (#4270)
Related #4168

On ~1–1.2× displays the 1px rounded accent border around a magnified
pane drops out at the corners, and a box that is not aligned to the
device-pixel grid turns the stroke into a faint, doubled hairline.

Snap the magnified terminal overlay (after the 12px inset) to integer
device pixels, and use a 2px accent stroke when devicePixelRatio is
below 1.5 on both the terminal and side-panel chrome. Higher-DPR
displays keep the existing 1px stroke.
2026-11-18 23:23:21 +08:00
陈大猫 9c292460e3 fix(ai): treat models-list 404 as a warning and send Anthropic Bearer auth (#4269)
* fix(ai): treat models-list 404 as a warning and send Anthropic Bearer on custom bases

Custom OpenAI-compatible gateways that omit a /models listing were
shown as a hard detect failure on HTTP 404. Treat 404 as a warning.
Official Anthropic stays on x-api-key only; custom Anthropic-compat
bases also send Authorization: Bearer so Agent Plan and similar
proxies authenticate.

* fix(ai): use the versioned Ark Agent Plan messages endpoint
2026-11-18 19:21:16 +08:00
陈大猫 5e1bdd85d8 fix(sftp): preserve settled folder pause failure on stale owner publish 2026-11-18 15:18:54 +08:00
陈大猫 450d1df2e7 fix(sftp): keep partial pause feedback consistent across transfer views 2026-11-18 15:07:28 +08:00
陈大猫 3ed22954db fix(sftp): preserve partial folder pause results 2026-11-18 14:44:35 +08:00
陈大猫 3260bf4206 fix(electron): isolate unpackaged app profiles 2026-11-18 14:05:02 +08:00
陈大猫 17d53152ec merge(main): pick up plugin-contract CI hang fix from #4240 2026-11-14 20:42:36 +08:00
陈大猫 f05ea0c9b7 fix(ai): surface max-iteration stop with a Continue action (Fixes #4224) 2026-11-13 12:04:16 +08:00
陈大猫 bb81b72ff0 fix(ai): avoid empty CodeBuddy tools whitelist that hides MCP tools (#4214)
Omit tools in MCP mode and explicitly disallow CodeBuddy built-ins, preserving injected MCP visibility and the skills-mode Bash whitelist.

Fixes #4214
2026-11-12 14:13:14 +08:00
陈大猫 d0fffac598 chore: retrigger CI after plugin-contract runner cancel 2026-11-08 09:48:34 +08:00
陈大猫 106e39a797 chore: retrigger CI after lint-and-test runner shutdown (exit 143) 2026-11-08 09:23:48 +08:00
陈大猫 3bf4c9df1a fix(mcp): advertise sessions reconnect tools to agents 2026-11-08 01:06:02 +08:00
83 changed files with 1955 additions and 195 deletions

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']);
});
}
+3
View File
@@ -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',
@@ -333,6 +335,7 @@ export const enAiMessages: Messages = {
'ai.defaultAgent': 'Default Agent',
'ai.defaultAgent.description': 'Agent to use when starting a new AI session',
'ai.defaultAgent.catty': 'Catty (Built-in)',
'ai.defaultAgent.unavailable': 'Unavailable',
'ai.toolAccess.title': 'Tool Access',
'ai.toolAccess.mode': 'Netcatty Access Mode',
'ai.toolAccess.description': 'Choose how external agents access Netcatty sessions. MCP exposes the built-in server, while Skills + CLI points agents to the local Netcatty skill and CLI commands.',
+3
View File
@@ -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',
@@ -333,6 +335,7 @@ export const esAiMessages: Messages = {
'ai.defaultAgent': 'Agente predeterminado',
'ai.defaultAgent.description': 'Agente que se usará al iniciar una nueva sesión de IA',
'ai.defaultAgent.catty': 'Catty (Integrado)',
'ai.defaultAgent.unavailable': 'No disponible',
'ai.toolAccess.title': 'Acceso a herramientas',
'ai.toolAccess.mode': 'Modo de acceso de Netcatty',
'ai.toolAccess.description': 'Elige cómo acceden los agentes externos a las sesiones de Netcatty. MCP expone el servidor integrado, mientras que Habilidades + CLI apunta a los agentes hacia las habilidades locales de Netcatty y los comandos de CLI.',
+3
View File
@@ -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
@@ -273,6 +275,7 @@ export const ruAiMessages: Messages = {
'ai.defaultAgent': 'Агент по умолчанию',
'ai.defaultAgent.description': 'Агент, который будет использоваться при запуске новой AI-сессии',
'ai.defaultAgent.catty': 'Catty (встроенный)',
'ai.defaultAgent.unavailable': 'Недоступен',
'ai.toolAccess.title': 'Доступ к инструментам',
'ai.toolAccess.mode': 'Режим доступа Netcatty',
'ai.toolAccess.description': 'Выберите, как внешние агенты получают доступ к сессиям Netcatty. MCP предоставляет встроенный сервер, а Skills + CLI указывает агентам на локальный skill Netcatty и команды CLI.',
+3
View File
@@ -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 设置',
@@ -333,6 +335,7 @@ export const zhCNAiMessages: Messages = {
'ai.defaultAgent': '默认 Agent',
'ai.defaultAgent.description': '创建新 AI 会话时使用的 Agent',
'ai.defaultAgent.catty': 'Catty(内置)',
'ai.defaultAgent.unavailable': '暂不可用',
'ai.toolAccess.title': '工具接入',
'ai.toolAccess.mode': 'Netcatty 接入模式',
'ai.toolAccess.description': '选择外部 Agent 访问 Netcatty 会话的方式。MCP 会暴露内置服务器,Skills + CLI 会引导 Agent 读取本地 Skill 并调用 Netcatty CLI。',
+3
View File
@@ -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 設定',
@@ -333,6 +335,7 @@ export const zhTWAiMessages: Messages = {
'ai.defaultAgent': '預設 Agent',
'ai.defaultAgent.description': '建立新 AI 工作階段時使用的 Agent',
'ai.defaultAgent.catty': 'Catty(內建)',
'ai.defaultAgent.unavailable': '暫時無法使用',
'ai.toolAccess.title': '工具介接',
'ai.toolAccess.mode': 'Netcatty 介接模式',
'ai.toolAccess.description': '選擇外部 Agent 存取 Netcatty 工作階段的方式。MCP 會公開內建伺服器,Skills + CLI 會引導 Agent 讀取本機 Skill 並呼叫 Netcatty CLI。',
@@ -541,3 +541,98 @@ test("late pause acknowledgement cannot restart a cancelling stream before settl
await pause;
assert.equal(resumes, 0);
});
for (const rejected of [false, true]) {
test(`folder pause retains successful children without claiming failed children paused: rejected=${rejected}`, async (t) => {
t.after(resetTransferPauseLatchesForTests);
let fail = true;
let resumes = 0;
const id = `partial-folder-${rejected}`;
const { host, getTasks } = createHost([
{ ...makeTask(id), isDirectory: true },
{ ...makeTask(`${id}-ok`), parentTaskId: id },
{ ...makeTask(`${id}-bad`), parentTaskId: id },
], () => ({
pauseTransfer: async (childId) => {
if (fail && childId.endsWith('-bad')) {
if (rejected) throw new Error('pause IPC unavailable');
return { success: false, reason: 'This transfer cannot be paused safely' };
}
return { success: true, checkpointBytes: 10 };
},
resumeTransfer: async () => { resumes++; return { success: true }; },
}));
await softPauseTransfer(host, id);
await new Promise<void>(resolve => setImmediate(resolve));
assert.equal(getTasks()[0].status, 'pausing');
assert.match(getTasks()[0].pauseUnavailableReason || '', /pause/i);
assert.equal(getTasks()[1].status, 'paused');
assert.equal(getTasks()[2].status, 'transferring');
assert.equal(isTransferPauseLatched(id), true);
assert.equal(resumes, 0, 'failed pause must not resume successful siblings');
fail = false;
await softPauseTransfer(host, id);
await new Promise<void>(resolve => setImmediate(resolve));
assert.ok(getTasks().every(row => row.status === 'paused'));
assert.equal(getTasks()[0].pauseUnavailableReason, undefined);
});
}
test('folder pause does not claim success while acknowledgements are pending or retry budget expires', async (t) => {
t.after(resetTransferPauseLatchesForTests);
const id = 'slow-start-folder';
let calls = 0;
const { host, getTasks } = createHost([
{ ...makeTask(id), isDirectory: true },
{ ...makeTask(`${id}-child`), parentTaskId: id },
], () => ({ pauseTransfer: async () => {
calls++;
return { success: false, reason: 'This transfer cannot be paused yet' };
} }));
assert.equal(await softPauseTransfer(host, id), 'pausing');
assert.equal(getTasks()[0].status, 'pausing');
// Wait for the bounded startup retry budget (four 40ms delays).
await new Promise(resolve => setTimeout(resolve, 220));
assert.equal(calls, 5);
assert.equal(getTasks()[0].status, 'pausing');
assert.match(getTasks()[0].pauseUnavailableReason || '', /cannot be paused yet/);
assert.equal(getTasks()[1].status, 'transferring');
});
test('explicit resume after partial folder pause releases successful siblings and walk latch', async (t) => {
t.after(resetTransferPauseLatchesForTests);
const id = 'resume-partial-folder';
const resumed: string[] = [];
const { host, getTasks } = createHost([
{ ...makeTask(id), isDirectory: true },
{ ...makeTask(`${id}-ok`), parentTaskId: id },
{ ...makeTask(`${id}-bad`), parentTaskId: id },
], () => ({
pauseTransfer: async childId => childId.endsWith('-ok')
? { success: true } : { success: false, reason: 'Pause rejected' },
resumeTransfer: async childId => { resumed.push(childId); return { success: true }; },
}));
await softPauseTransfer(host, id);
await new Promise<void>(resolve => setImmediate(resolve));
assert.equal((await softResumeTransfer(host, id)).handled, true);
assert.equal(isTransferPauseLatched(id), false);
assert.ok(getTasks().every(row => row.status === 'transferring'));
assert.deepEqual(resumed.sort(), [`${id}-bad`, `${id}-ok`]);
});
test('child completion during a rejected folder pause does not leave a false failure', async (t) => {
t.after(resetTransferPauseLatchesForTests);
const id = 'completed-during-folder-pause';
let finish!: (result: { success: boolean; reason: string }) => void;
const { host, getTasks } = createHost([
{ ...makeTask(id), isDirectory: true },
{ ...makeTask(`${id}-child`), parentTaskId: id },
], () => ({ pauseTransfer: () => new Promise(resolve => { finish = resolve; }) }));
await softPauseTransfer(host, id);
host.setTasks(getTasks().map(row => row.parentTaskId ? { ...row, status: 'completed' } : row));
finish({ success: false, reason: 'Pause rejected' });
await new Promise<void>(resolve => setImmediate(resolve));
assert.equal(getTasks()[0].status, 'paused');
assert.equal(getTasks()[0].pauseUnavailableReason, undefined);
assert.equal(getTasks()[1].status, 'completed');
});
@@ -184,7 +184,7 @@ export async function softPauseTransfer(
try { globalSftpTransferScheduler.pause(id); } catch { /* best-effort */ }
}
const immediateStatus = task.isDirectory ? "paused" as const : "pausing" as const;
const immediateStatus = "pausing" as const;
// Freeze via latch/status; leave lifecycleEpoch alone until bridge responds.
host.setTasks(paintTreeStatus(
host.getTasks(),
@@ -271,7 +271,11 @@ export async function softPauseTransfer(
if (!pauseStillCurrent()) {
return { id, result: { success: false, reason: "Pause superseded by resume" } };
}
const result = await pauseOne(id);
// A rejected IPC is a failed acknowledgement, not proof of pause.
const result: Awaited<ReturnType<NonNullable<TransferControlBridge["pauseTransfer"]>>> = await pauseOne(id).catch((error: unknown) => ({
success: false,
reason: error instanceof Error ? error.message : "Could not pause transfer",
}));
if (wasSuperseded(result)) return { id, result };
const live = host.getTasks().find((candidate) => candidate.id === taskId);
const userResumed = !pauseStillCurrent()
@@ -293,16 +297,26 @@ export async function softPauseTransfer(
if (after.status !== "paused" && after.status !== "pausing") return;
const byId = new Map(pauseResults.map((row) => [row.id, row.result]));
const bridgeEpoch = maxBridgeLifecycleEpoch(pauseResults.map((row) => row.result));
// Final directory paint: parent + unfinished children all go paused (do not
// leave children stuck on transferring under a paused parent).
const liveTasks = host.getTasks();
const failed = pauseResults.filter(({ id, result }) => {
const live = liveTasks.find((candidate) => candidate.id === id);
return live && !["completed", "cancelled", "failed"].includes(live.status)
&& !result.success && !isBenignPauseMiss(result.reason);
});
// Keep acknowledged children paused and retain the walk latch. Never
// auto-resume siblings to roll back a partial pause. Failed children may
// still be streaming; expose that truth and allow an explicit retry.
const pauseFailure = failed.length > 0
? (failed[0].result.reason || "Could not pause all folder transfers")
: undefined;
host.setTasks(host.getTasks().map((candidate) => {
if (candidate.id === taskId) {
return {
...candidate,
status: "paused" as const,
status: pauseFailure ? "pausing" as const : "paused" as const,
speed: 0,
checkpointBytes: candidate.transferredBytes,
pauseUnavailableReason: undefined,
pauseUnavailableReason: pauseFailure,
phase: undefined,
// Bridge epoch only — control-plane pauseEpoch must not poison ingest.
...(bridgeEpoch !== undefined ? { lifecycleEpoch: bridgeEpoch } : null),
@@ -311,24 +325,25 @@ export async function softPauseTransfer(
if (candidate.parentTaskId !== taskId && !backendIds.includes(candidate.id)) return candidate;
if (["completed", "cancelled", "failed"].includes(candidate.status)) return candidate;
const result = byId.get(candidate.id);
const childFailed = result && !result.success && !isBenignPauseMiss(result.reason);
const childEpoch = Number.isFinite(result?.lifecycleEpoch)
? (result!.lifecycleEpoch as number)
: bridgeEpoch;
: childFailed ? undefined : bridgeEpoch;
return {
...candidate,
status: "paused" as const,
status: childFailed ? "transferring" as const : "paused" as const,
speed: 0,
checkpointBytes: result?.checkpointBytes ?? candidate.checkpointBytes ?? candidate.transferredBytes,
resumeStage: result?.resumeStage ?? candidate.resumeStage,
downloadCheckpointBytes: result?.downloadCheckpointBytes ?? candidate.downloadCheckpointBytes,
uploadCheckpointBytes: result?.uploadCheckpointBytes ?? candidate.uploadCheckpointBytes,
sourceFingerprint: result?.sourceFingerprint ?? candidate.sourceFingerprint,
pauseUnavailableReason: undefined,
pauseUnavailableReason: childFailed ? (result.reason || "Could not pause transfer") : undefined,
...(childEpoch !== undefined ? { lifecycleEpoch: childEpoch } : null),
};
}));
})().catch(() => { /* best-effort */ });
return "paused";
return "pausing";
}
// Single-file: await soft-drain with supersede guards.
@@ -122,8 +122,11 @@ test("runtime soft-resumes live walk after owner teardown simulation (no dedicat
resetGlobals();
const resumeCalls: string[] = [];
let dedicatedHandlerCalls = 0;
let acknowledgePause!: () => void;
installBridge(t, {
pauseTransfer: async () => ({ success: true, checkpointBytes: 5 }),
pauseTransfer: () => new Promise((resolve) => {
acknowledgePause = () => resolve({ success: true, checkpointBytes: 5 });
}),
resumeTransfer: async (id) => {
resumeCalls.push(id);
return { success: true };
@@ -151,6 +154,9 @@ test("runtime soft-resumes live walk after owner teardown simulation (no dedicat
]);
await runtime.pause("folder");
assert.equal(runtime.getTask("folder")?.status, "pausing");
acknowledgePause();
await new Promise<void>((resolve) => setImmediate(resolve));
assert.equal(runtime.getTask("folder")?.status, "paused");
assert.equal(isTransferPauseLatched("folder"), true);
assert.equal(isTransferWalkInFlight("folder"), true);
@@ -1505,6 +1505,7 @@ test("pause after terminal close works without any React owner", async () => {
await store.pause("stale-dir");
await new Promise<void>((resolve) => setImmediate(resolve));
assert.equal(store.getSnapshot().tasks.find((row) => row.id === "stale-dir")?.status, "paused");
assert.equal(isTransferPauseLatched("stale-dir"), true);
assert.ok(pauseCalls.includes("stale-child"));
@@ -2413,6 +2414,7 @@ test("dedicated directory resume after soft-pause winds down then startFresh (no
// Soft-pause paints paused under dedicated-resume.
await store.pause("dir");
await new Promise<void>((resolve) => setImmediate(resolve));
assert.equal(store.getSnapshot().tasks.find((task) => task.id === "dir")?.status, "paused");
// Resume must cancel soft-paused children, clear sticky latches, await wind-down, then startFresh.
@@ -2621,7 +2623,7 @@ test("async folder soft-drain does not re-pause after immediate resume", async (
// Pause returns immediately (async soft-drain).
await store.pause("dir-race");
assert.equal(store.getSnapshot().tasks.find((row) => row.id === "dir-race")?.status, "paused");
assert.equal(store.getSnapshot().tasks.find((row) => row.id === "dir-race")?.status, "pausing");
// User hits resume before soft-drain finishes — full store resume (bumps epoch
// + releases latch tree), which is what the UI does.
@@ -2690,21 +2692,33 @@ test("orphan directory pause stays latched even when some children hard-miss pau
await store.pause("dir");
// Folder pause is async: UI is paused immediately; soft-drain may still be running.
// Folder pause stays pending until the child acknowledgements settle.
const dir = store.getSnapshot().tasks.find((task) => task.id === "dir");
assert.equal(dir?.status, "paused", "folder parent must paint paused without waiting on children");
assert.equal(store.getSnapshot().tasks.find((task) => task.id === "c-ok")?.status, "paused");
assert.equal(store.getSnapshot().tasks.find((task) => task.id === "c-fail")?.status, "paused");
// Soft-drain is fire-and-forget — give it a tick to hit the bridge.
await new Promise((resolve) => setTimeout(resolve, 20));
assert.equal(dir?.status, "pausing");
const ownerSnapshotDuringDrain = store.getSnapshot().tasks.map((row) => ({ ...row }));
await new Promise<void>((resolve) => setImmediate(resolve));
assert.equal(store.getTask("c-ok")?.status, "paused");
assert.equal(store.getTask("c-fail")?.status, "transferring");
assert.deepEqual(pauseCalls.sort(), ["c-fail", "c-ok"]);
// Latch-first: do not bridge-resume partial successes (that re-opened the queue).
assert.deepEqual(resumeCalls, []);
assert.equal(
store.getSnapshot().tasks.find((task) => task.id === "dir")?.status,
"paused",
"hard-miss soft-drain must not demote folder out of paused",
"pausing",
"hard miss keeps the folder latched without claiming a successful pause",
);
assert.equal(store.getTask("dir")?.pauseUnavailableReason, "This transfer cannot be paused safely");
store.publishOwner("dedicated-resume", ownerSnapshotDuringDrain);
assert.equal(store.getTask("dir")?.status, "pausing");
assert.equal(store.getTask("dir")?.pauseUnavailableReason, "This transfer cannot be paused safely");
assert.equal(store.getTask("c-ok")?.status, "paused");
assert.equal(store.getTask("c-fail")?.status, "transferring");
store.ingestBackgroundEvent({ type: "progress", transferId: "c-fail", transferred: 25, speed: 10 });
assert.equal(store.getTask("c-fail")?.status, "transferring");
assert.equal(store.getTask("c-fail")?.transferredBytes, 25);
store.patchTask("c-fail", { transferredBytes: 50, speed: 10 });
assert.equal(store.getTask("c-fail")?.status, "transferring");
assert.equal(store.getTask("c-fail")?.transferredBytes, 50);
});
test("dedicated resume source-changed marks attention and can reset checkpoint", async () => {
+27 -11
View File
@@ -353,7 +353,22 @@ export function mergeOwnerPublishedTask(
// Only a strictly newer lifecycle epoch may re-open transferring (resume).
const incomingPaused = incoming.status === "paused" || incoming.status === "pausing";
const existingPaused = existing.status === "paused" || existing.status === "pausing";
if (incomingPaused && incomingLifecycleEpoch >= existingLifecycleEpoch) {
// The panel can publish a snapshot from before the child acknowledgements
// arrived. Only a newer control decision may clear the folder's failure.
const rejectedFolderPause = existing.isDirectory && !existing.parentTaskId
&& existing.status === "pausing" && !!existing.pauseUnavailableReason
&& incomingLifecycleEpoch <= existingLifecycleEpoch
&& isTransferPauseLatched(existing.id);
const rejectedChildPause = parentStatus === "pausing"
&& !!existing.parentTaskId && existing.status === "transferring" && !!existing.pauseUnavailableReason;
if (rejectedFolderPause) {
merged.status = "pausing";
merged.speed = 0;
merged.pauseUnavailableReason = existing.pauseUnavailableReason;
} else if (rejectedChildPause && incomingLifecycleEpoch <= existingLifecycleEpoch) {
merged.status = "transferring";
merged.pauseUnavailableReason = existing.pauseUnavailableReason;
} else if (incomingPaused && incomingLifecycleEpoch >= existingLifecycleEpoch) {
merged.status = incoming.status;
merged.speed = 0;
// Pin the visible bar while paused/latched. Soft-drain must not keep
@@ -392,6 +407,7 @@ export function mergeOwnerPublishedTask(
const parentHoldsPause = parentStatus === "paused" || parentStatus === "pausing";
if (
parentHoldsPause
&& !rejectedChildPause
&& !["completed", "cancelled", "failed"].includes(merged.status)
&& (merged.status === "transferring" || merged.status === "pending" || merged.status === "queued")
) {
@@ -1722,17 +1738,15 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
// Soft-drain / walk progress must not move the visible bar after Pause.
// Latch or paused/pausing freezes transferredBytes/speed unless this patch
// is an explicit resume (transferring + epoch, or dedicated-resume).
const pauseHeld = isTransferOrRootPauseLatched(task.parentTaskId ?? task.id, task.id)
const parent = task.parentTaskId ? tasks.find((candidate) => candidate.id === task.parentTaskId) : undefined;
const rejectedChildPause = parent?.status === "pausing" && !!parent.pauseUnavailableReason
&& task.status === "transferring" && !!task.pauseUnavailableReason;
const pauseHeld = !rejectedChildPause && (isTransferOrRootPauseLatched(task.parentTaskId ?? task.id, task.id)
|| isTransferPauseLatched(task.id)
|| task.status === "paused"
|| task.status === "pausing"
|| (!!task.parentTaskId && (
isTransferPauseLatched(task.parentTaskId)
|| (() => {
const parent = tasks.find((candidate) => candidate.id === task.parentTaskId);
return parent?.status === "paused" || parent?.status === "pausing";
})()
));
|| parent?.status === "paused"
|| parent?.status === "pausing");
if (pauseHeld && !explicitResume) {
// Keep lifecycle at paused/pausing; allow checkpoint metadata only.
if (task.status === "pausing" || task.status === "paused") {
@@ -2451,10 +2465,12 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
task.parentTaskId ?? task.id,
task.id,
) || isTransferPauseLatched(task.id);
const uiPauseLatched = task.status === "paused"
const rejectedChildPause = parentRow?.status === "pausing" && !!parentRow.pauseUnavailableReason
&& task.status === "transferring" && !!task.pauseUnavailableReason;
const uiPauseLatched = !rejectedChildPause && (task.status === "paused"
|| task.status === "pausing"
|| parentHoldsPause
|| selfLatched;
|| selfLatched);
const explicitResume = lifecycleStatus === "transferring"
&& event.lifecycleEpoch !== undefined
&& incomingEpoch > currentEpoch;
@@ -0,0 +1,62 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { JSDOM } from 'jsdom';
test('closing plugin overlays preserves the underlying plugin tab and closing that tab still removes it', async () => {
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost', pretendToBeVisual: true });
const previous = new Map<string, PropertyDescriptor | undefined>();
const install = (name: string, value: unknown) => {
previous.set(name, Object.getOwnPropertyDescriptor(globalThis, name));
Object.defineProperty(globalThis, name, { configurable: true, writable: true, value });
};
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'CustomEvent', 'MutationObserver']) {
install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]);
}
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);
Object.assign(dom.window, { matchMedia: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }), netcatty: {
async getPluginRuntimeStatus() { return { available: true }; },
async getPluginContributions() { return { locale: 'en', plugins: [{ id: 'example.plugin', version: '1.0.0', displayName: 'Example',
commands: [], keybindings: [], menus: [], settings: [], views: ['tab', 'modal', 'aside', 'panel'].map(location => ({
id: `example.plugin.${location}`, title: location, location, visible: true,
})) }] }; },
onPluginContributionsChanged() { return () => {}; },
async setPluginEnvironment() {},
} });
const { default: React, act } = await import('react');
const { createRoot } = await import('react-dom/client');
const { usePluginViewLifecycle, requestOpenPluginView } = await import('./usePluginViewLifecycle');
const { pluginViewTabStore } = await import('./pluginViewTabStore');
const { activeTabStore } = await import('./activeTabStore');
const context = { 'netcatty.surface': 'keybinding' };
let model!: ReturnType<typeof usePluginViewLifecycle>;
function Fixture() {
model = usePluginViewLifecycle({ locale: 'en', theme: 'dark', keybindingContext: context });
return React.createElement('button', { onClick: () => void model.close() }, model.activeView?.view.id ?? 'none');
}
const root = createRoot(document.getElementById('root')!);
const settle = () => new Promise(resolve => setTimeout(resolve, 30));
const perform = async (action: () => void) => act(async () => { action(); await settle(); });
try {
activeTabStore.setActiveTabId('vault');
const tab = pluginViewTabStore.open({ pluginId: 'example.plugin', pluginName: 'Example', viewId: 'example.plugin.tab', title: 'Tab' });
await perform(() => root.render(React.createElement(Fixture)));
assert.equal(model.activeView?.view.id, tab.viewId);
for (const location of ['modal', 'aside', 'panel']) {
await perform(() => requestOpenPluginView({ viewId: `example.plugin.${location}` }));
assert.equal(model.activeView?.view.location, location);
await perform(() => document.querySelector('button')!.click());
assert.equal(activeTabStore.getActiveTabId(), tab.id, `closing ${location} preserves the active tab`);
assert.equal(pluginViewTabStore.getTabs()[0]?.id, tab.id);
assert.equal(model.activeView?.view.id, tab.viewId, `closing ${location} returns to the underlying view`);
}
await perform(() => document.querySelector('button')!.click());
assert.equal(pluginViewTabStore.getTabs().length, 0, 'closing the tab itself still removes it');
} finally {
await act(async () => root.unmount());
pluginViewTabStore.retain(new Set()); activeTabStore.setActiveTabId('vault'); dom.window.close();
for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); }
}
});
+5 -1
View File
@@ -144,7 +144,11 @@ export function usePluginViewLifecycle({
const close = useCallback(async () => {
setRequested(null);
if (activeView) pluginViewSessions.closeView(activeView.view.id);
if (activePluginTab) pluginViewTabStore.close(activePluginTab.id);
// An overlay can be requested while a different plugin tab stays active.
// Dismissing that overlay must not close the tab underneath it.
if (activeView?.view.location === 'tab' && activePluginTab?.viewId === activeView.view.id) {
pluginViewTabStore.close(activePluginTab.id);
}
}, [activePluginTab, activeView]);
useEffect(() => {
+3 -1
View File
@@ -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}
+10 -10
View File
@@ -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);
+8 -5
View File
@@ -436,7 +436,7 @@ function TransferRow({
task: TransferTask;
children: TransferTask[];
} | null>(null);
if (task.status === "pausing") {
if (task.status === "pausing" && !task.pauseUnavailableReason) {
if (!pausingSnapshotRef.current) {
pausingSnapshotRef.current = {
task: { ...task },
@@ -464,20 +464,23 @@ function TransferRow({
&& !task.error;
const sharedResuming = useSftpTransferResuming(task.id);
const isResuming = sharedResuming || storeResuming;
const canPause = task.resumable !== false && task.status === "transferring" && canControl && !isResuming;
const pauseFailed = task.status === "pausing" && !!task.pauseUnavailableReason;
const canPause = task.resumable !== false && (task.status === "transferring" || pauseFailed) && canControl && !isResuming;
// Orphaned tasks after app restart (interrupted / attention / paused without a
// live panel owner) must still expose resume/cancel from the global center.
// Conflict rows must use resolveConflict — Resume would overwrite blindly.
// Non-resumable attention rows (e.g. duplicate-destination refusals) are
// terminal: resuming them would start a second writer on the same path.
// Do not show Resume during soft-drain "pausing" — play + spinner together
// makes the row twitch as buttons appear/disappear mid-drain.
// makes the row twitch as buttons appear/disappear mid-drain. A settled
// partial failure is different: offer Retry Pause and explicit Resume.
const canResume = !isResuming && !task.conflict && (
["paused", "interrupted"].includes(task.status)
|| (pauseFailed && task.resumable !== false)
|| (task.status === "attention" && task.resumable !== false)
|| (task.status === "failed" && task.resumable !== false && (task.checkpointBytes ?? 0) > 0)
) && canControl;
const isPausing = task.status === "pausing";
const isPausing = task.status === "pausing" && !pauseFailed;
const canCancel = ["pending", "queued", "transferring", "pausing", "paused", "interrupted", "attention"].includes(task.status) && canControl;
const canRetry = task.status === "failed" && task.retryable !== false && canControl;
const isTerminal = ["completed", "failed", "cancelled"].includes(task.status);
@@ -577,7 +580,7 @@ function TransferRow({
<Pause size={13} />
</TransferAction>
)}
{task.status === "pausing" && (
{task.status === "pausing" && !pauseFailed && (
<div className="flex h-8 w-8 items-center justify-center" role="status" aria-label={t("sftp.transferCenter.status.pausing")}>
<Loader2 size={13} className="animate-spin text-amber-500" />
</div>
+1
View File
@@ -550,6 +550,7 @@ const SettingsPageContent: React.FC<{ settings: SettingsState; appLock?: AppLock
{mountedTabs.has("appearance") && (
<SettingsLazyTab value="appearance">
<LazySettingsAppearanceTab
pluginRuntimeAvailable={pluginRuntimeAvailable}
theme={settings.theme}
resolvedTheme={settings.resolvedTheme}
setTheme={settings.setTheme}
+17
View File
@@ -206,6 +206,23 @@ test("surfaces pause unavailable reason on a transferring row", () => {
assert.match(markup, /This transfer cannot be paused yet/);
});
test("shows a settled folder pause failure with retry and resume instead of a spinner", () => {
const markup = renderTransferItem({
...baseTask,
isDirectory: true,
status: "pausing",
error: undefined,
speed: 0,
resumable: true,
pauseUnavailableReason: "This transfer cannot be paused yet",
}, { onPause: () => {}, onResume: () => {} });
assert.match(markup, /This transfer cannot be paused yet/);
assert.match(markup, /aria-label="Pause: archive\.tar\.gz"/);
assert.match(markup, /aria-label="Resume: archive\.tar\.gz"/);
assert.doesNotMatch(markup, /aria-busy="true"|aria-label="Pausing:/);
});
test("renders child resize handle as a keyboard-reachable separator", () => {
const markup = renderTransferItem(
{
+62
View File
@@ -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(); });
});
+16
View File
@@ -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 ||
+24
View File
@@ -71,6 +71,30 @@ test('buildManagedAgentState keeps unrelated defaults when removing stale manage
assert.equal(state.defaultAgentId, 'custom-agent');
});
test('a failed saved-path probe keeps the override, preferences, and default until recovery', () => {
const agent: ExternalAgentConfig = {
id: 'discovered_copilot',
name: 'GitHub Copilot CLI',
command: 'C:/npm/copilot.cmd',
commandSource: 'manual',
sdkBackend: 'copilot',
enabled: false,
available: true,
};
const unavailable = buildManagedAgentState([agent], agent.id, 'copilot', null, 'manual');
assert.deepEqual(unavailable.agents, [{ ...agent, available: false }]);
assert.equal(unavailable.defaultAgentId, agent.id);
assert.equal(getInitialManagedAgentPaths(unavailable.agents).copilot, agent.command);
const recovered = buildManagedAgentState(unavailable.agents, agent.id, 'copilot', {
path: agent.command, version: '1.0.106', available: true,
}, 'manual');
assert.equal(recovered.agents[0].available, true);
assert.equal(recovered.agents[0].enabled, false);
assert.equal(recovered.defaultAgentId, agent.id);
assert.deepEqual(buildManagedAgentState(recovered.agents, agent.id, 'copilot', null, 'auto').agents, []);
});
test('buildManagedAgentState stores the system Claude executable for SDK runs', () => {
const state = buildManagedAgentState(
[],
@@ -36,9 +36,30 @@ test('plugin surface forwards its own input and contains malformed updates and r
assert.equal(events.length, 2);
await act(async () => { root.render(<PluginRemoteSurface tree={tree} css="@import 'https://bad.example/x';" onEvent={() => {}} />); });
assert.equal(document.querySelector('[role=alert]')?.textContent, 'Unable to display plugin view.');
const optionA = { id: 'a', type: 1, element: 'option', attributes: { selected: '' }, children: [{ id: 'at', type: 3, data: ' First\n option ' }] };
const optionB = { id: 'b', type: 1, element: 'option', attributes: {}, children: [{ id: 'bt', type: 3, data: 'Second' }] };
const controls = { children: [
{ id: 'select', type: 1, element: 'select', attributes: { multiple: '' }, children: [optionA, optionB] },
{ id: 'textarea', type: 1, element: 'textarea', attributes: {}, children: [{ id: 'ta', type: 3, data: 'Hello' }, { id: 'tb', type: 3, data: ' world' }] },
] };
const renderControls = async () => act(async () => root.render(<PluginRemoteSurface tree={{ ...controls }} css="" onEvent={(event) => events.push(event)} />));
await renderControls();
const select = captured!.querySelector('select')!;
assert.deepEqual([...select.selectedOptions].map((option) => option.value), ['First option']);
assert.equal(captured!.querySelector('textarea')!.value, 'Hello world');
await act(async () => {
select.options[0].selected = false; select.options[1].selected = true;
select.dispatchEvent(new dom.window.Event('change', { bubbles: true }));
});
assert.deepEqual(events.at(-1), { nodeId: 'select', type: 'change', value: 'Second', values: ['Second'] });
optionA.attributes = {} as typeof optionA.attributes;
optionB.attributes = { selected: '' };
await renderControls();
assert.deepEqual([...select.selectedOptions].map((option) => option.value), ['Second'], 'acknowledgement keeps native option text values selected');
let clicks = 0;
const renderView = async (nextTree: unknown) => act(async () => root.render(<>
<PluginRemoteSurface key="view" tree={nextTree} css="" onEvent={() => {}} />
const renderView = async (nextTree: unknown, viewKey = 'view') => act(async () => root.render(<>
<PluginRemoteSurface key={viewKey} tree={nextTree} css="" onEvent={() => {}} />
<button id="canary" onClick={() => clicks++}>Host canary</button>
<PluginRemoteSurface key="sibling" tree={tree} css="" onEvent={() => {}} />
</>));
@@ -48,15 +69,17 @@ test('plugin surface forwards its own input and contains malformed updates and r
assert.ok(document.querySelector('[role=alert]'));
await act(async () => document.getElementById('canary')!.click());
assert.equal(clicks, 1);
// Validated data can still hit a React rendering constraint. Contain that
// descendant throw too, independently of the policy rejection above.
// Unexpected rendering failures stay within this plugin, including layout effects.
const originalError = console.error;
const prevAttach = dom.window.Element.prototype.attachShadow;
try {
console.error = () => {};
await renderView({ children: [{ id: 'bad', type: 1, element: 'textarea', attributes: {}, children: [
{ id: 'a', type: 3, data: 'one' }, { id: 'b', type: 3, data: 'two' },
] }] });
} finally { console.error = originalError; }
dom.window.Element.prototype.attachShadow = () => { throw new Error('Synthetic surface failure'); };
await renderView(tree, 'broken-surface');
} finally {
dom.window.Element.prototype.attachShadow = prevAttach;
console.error = originalError;
}
assert.equal(document.querySelectorAll('[data-plugin-remote-surface]').length, 1);
assert.ok(document.querySelector('[role=alert]'));
await act(async () => document.getElementById('canary')!.click());
+10 -3
View File
@@ -13,6 +13,10 @@ const ATTRIBUTE_NAMES: Record<string, string> = { class: 'className', for: 'html
const BOOLEAN_ATTRIBUTES = new Set(['checked', 'disabled', 'readonly', 'required', 'multiple', 'selected', 'open']);
const SurfaceContext = createContext<{ css: string; onEvent(event: PluginSurfaceEvent): void; depth: number }>({ css: '', onEvent: () => {}, depth: 0 });
function remoteText(nodes: RemoteNode[]): string {
return nodes.map((node) => (node.type === 3 ? node.data : node.type === 1 ? remoteText(node.children) : '')).join('');
}
const ResourceLoader = createContext<((path: string) => Promise<string>) | undefined>(undefined);
function RemoteElement({ node, settled }: { node: RemoteNode; settled: boolean }): React.ReactNode {
@@ -27,10 +31,10 @@ function RemoteElement({ node, settled }: { node: RemoteNode; settled: boolean }
return () => { cancelled = true; };
}, [imagePath, loadImage]);
const remoteSelection = JSON.stringify(node.type === 1 && node.element === 'select'
? node.children.filter((child) => child.type === 1 && child.element === 'option' && Object.hasOwn(child.attributes, 'selected')).map((child) => child.type === 1 ? child.attributes.value ?? '' : '') : []);
? node.children.filter((child) => child.type === 1 && child.element === 'option' && Object.hasOwn(child.attributes, 'selected')).map((child) => child.type === 1 ? child.attributes.value ?? remoteText(child.children).replace(/[\t\n\f\r ]+/g, ' ').trim() : '') : []);
const [localSelection, setLocalSelection] = useState<string[]>(() => JSON.parse(remoteSelection));
useEffect(() => { if (settled) setLocalSelection(JSON.parse(remoteSelection)); }, [remoteSelection, settled]);
const remoteValue = attrs.value;
const remoteValue = attrs.value ?? (node.type === 1 && node.element === 'textarea' ? remoteText(node.children) : undefined);
const remoteChecked = Object.hasOwn(attrs, 'checked');
const [localValue, setLocalValue] = useState(remoteValue ?? '');
const [localChecked, setLocalChecked] = useState(remoteChecked);
@@ -62,7 +66,10 @@ function RemoteElement({ node, settled }: { node: RemoteNode; settled: boolean }
if (event.currentTarget instanceof event.currentTarget.ownerDocument.defaultView!.HTMLInputElement) setLocalChecked(event.currentTarget.checked);
};
}
return React.createElement(node.element, props, ...(node.element === 'textarea' && remoteValue !== undefined ? [] : node.children).map((child) => <RemoteElement key={child.id} node={child} settled={settled} />));
// React treats textarea/option text specially; do not wrap it in components.
if (node.element === 'textarea') return React.createElement(node.element, props);
if (node.element === 'option') return React.createElement(node.element, props, remoteText(node.children));
return React.createElement(node.element, props, ...node.children.map((child) => <RemoteElement key={child.id} node={child} settled={settled} />));
}
/** Host-owned DOM, kept inside a closed shadow root and a clipped stacking context. */
+2 -1
View File
@@ -36,7 +36,7 @@ export const Toggle: React.FC<ToggleProps> = ({ checked, onChange, disabled, ari
interface SelectProps {
value: string;
options: { value: string; label: string; icon?: React.ReactNode }[];
options: { value: string; label: string; icon?: React.ReactNode; disabled?: boolean }[];
onChange: (value: string) => void;
className?: string;
disabled?: boolean;
@@ -87,6 +87,7 @@ export const Select: React.FC<SelectProps> = ({
<SelectPrimitive.Item
key={opt.value}
value={opt.value}
disabled={opt.disabled}
className="relative flex w-full min-w-0 cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
@@ -2,9 +2,12 @@ import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import vm from "node:vm";
import React, { useCallback, useEffect, useRef, useState } from "react";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import TestRenderer, { act } from "react-test-renderer";
import ts from "typescript";
import { canSendWithAgent } from "../../ai/agentSendEligibility";
import { buildManagedAgentState, getUnavailablePreferredHarness } from "./ai/managedAgentState";
import type { ExternalAgentConfig } from "../../../infrastructure/ai/types";
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -94,3 +97,61 @@ test("an older AI detection result cannot replace or finish the newer request",
assert.equal(h.state.busy, false);
} finally { await act(async () => h.root.unmount()); }
});
// Mount the same option computation and normalization effect that the
// Settings tab runs after a probe has updated the actual saved agent state.
const pickerStart = source.indexOf(" // Agent options for default agent");
const pickerEnd = source.indexOf("\n useEffect(() => {\n const bridge", pickerStart);
assert.ok(pickerStart >= 0 && pickerEnd > pickerStart);
const runDefaultPicker = vm.runInNewContext(ts.transpile(`(function(ctx) {
const { useMemo, useEffect, externalAgents, defaultAgentId, setDefaultAgentId, t,
canSendWithAgent, getUnavailablePreferredHarness, React, AgentIconBadge } = ctx;
${source.slice(pickerStart, pickerEnd)}
return agentOptions;
})`, { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React }), { console }) as
(ctx: Record<string, unknown>) => { value: string; disabled?: boolean }[];
test("Settings retains the unavailable saved default, blocks sends and restores the same choice", async () => {
const agent: ExternalAgentConfig = {
id: "discovered_copilot",
name: "GitHub Copilot CLI",
command: "/fixture/copilot",
commandSource: "manual",
sdkBackend: "copilot",
enabled: true,
available: true,
};
let options: ReturnType<typeof runDefaultPicker> = [];
let choice = "";
function Harness({ agents }: { agents: ExternalAgentConfig[] }) {
const [defaultAgentId, setDefaultAgentId] = useState(agent.id);
options = runDefaultPicker({
useMemo, useEffect, externalAgents: agents, defaultAgentId, setDefaultAgentId,
t: (key: string) => key, canSendWithAgent, getUnavailablePreferredHarness, React,
AgentIconBadge: () => null,
});
choice = defaultAgentId;
return null;
}
const failed = buildManagedAgentState([agent], agent.id, "copilot", null, "manual");
const recovered = buildManagedAgentState(failed.agents, agent.id, "copilot", {
path: agent.command, available: true, version: "1.0.106",
}, "manual");
let root!: TestRenderer.ReactTestRenderer;
const render = (agents: ExternalAgentConfig[]) => React.createElement(Harness, { agents });
try {
await act(async () => { root = TestRenderer.create(render([agent])); });
await act(async () => { root.update(render(failed.agents)); });
assert.equal(choice, agent.id);
assert.equal(options.find(option => option.value === agent.id)?.disabled, true);
assert.equal(canSendWithAgent(choice, failed.agents), false);
await act(async () => { root.update(render(recovered.agents)); });
assert.equal(choice, agent.id);
assert.equal(options.find(option => option.value === agent.id)?.disabled, undefined);
assert.equal(canSendWithAgent(choice, recovered.agents), true);
const reset = buildManagedAgentState(recovered.agents, agent.id, "copilot", null, "auto");
await act(async () => { root.update(render(reset.agents)); });
assert.equal(choice, "catty");
} finally { await act(async () => root.unmount()); }
});
+31 -12
View File
@@ -68,6 +68,7 @@ import {
areExternalAgentListsEqual,
buildManagedAgentState,
getInitialManagedAgentPaths,
getUnavailablePreferredHarness,
updateCodebuddyManagedEnv,
updateCodebuddyManagedOptions,
} from "./ai/managedAgentState";
@@ -392,6 +393,10 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
: setMimoPathInfo;
setInfo(result);
const savedPaths = initialManagedPathsRef.current;
if (savedPaths && (commandSource === "auto" || (result?.available && result.path))) {
savedPaths[agentKey] = commandSource === "manual" ? result?.path ?? "" : "";
}
let nextDefaultId: string | null = null;
setExternalAgents((prev) => {
@@ -414,7 +419,7 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
apiKeyPresent?: boolean;
refreshShellEnv?: boolean;
commandSource?: "manual" | "auto";
removeUnavailableManualPath?: boolean;
recheckSavedPath?: boolean;
},
) => {
const bridge = getBridge();
@@ -461,7 +466,7 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
options?.commandSource === "manual"
&& customPath.trim()
&& !result?.available
&& !options.removeUnavailableManualPath
&& !options.recheckSavedPath
) {
const setInfo = agentKey === "codex"
? setCodexPathInfo
@@ -525,9 +530,14 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
void resolveAgentPath(task.key, task.path, {
...task.options,
commandSource: task.path ? "manual" : "auto",
removeUnavailableManualPath: Boolean(task.path),
}).finally(() => {
autoResolvedAgentStateRef.current[task.key] = "done";
recheckSavedPath: Boolean(task.path),
}).then((result) => {
if (result?.available) {
autoResolvedAgentStateRef.current[task.key] = "done";
} else {
// Retry a failed check on the next visit to the Agents tab.
delete autoResolvedAgentStateRef.current[task.key];
}
});
}, task.delayMs));
return () => {
@@ -646,13 +656,22 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
[removeProvider, editingProviderId, removeProviderConfirm],
);
// Agent options for default agent
const agentOptions = useMemo(() => [
{ value: "catty", label: t('ai.defaultAgent.catty'), icon: <AgentIconBadge agent={{ id: "catty", type: "builtin" }} size="xs" variant="plain" /> },
...externalAgents
.filter((a) => canSendWithAgent(a.id, externalAgents))
.map((a) => ({ value: a.id, label: a.name, icon: <AgentIconBadge agent={a} size="xs" variant="plain" /> })),
], [externalAgents, t]);
// Agent options for default agent. Include a saved default that is temporarily offline as a disabled option.
// This preserves the setting without offering that harness for new selections.
const agentOptions = useMemo(() => {
const unavailable = getUnavailablePreferredHarness(externalAgents, defaultAgentId);
return [
{ value: "catty", label: t('ai.defaultAgent.catty'), icon: <AgentIconBadge agent={{ id: "catty", type: "builtin" }} size="xs" variant="plain" /> },
...externalAgents
.filter((a) => a === unavailable || canSendWithAgent(a.id, externalAgents))
.map((a) => ({
value: a.id,
label: a === unavailable ? `${a.name} (${t('ai.defaultAgent.unavailable')})` : a.name,
icon: <AgentIconBadge agent={a} size="xs" variant="plain" />,
disabled: a === unavailable ? true : undefined,
})),
];
}, [externalAgents, defaultAgentId, t]);
useEffect(() => {
if (!agentOptions.some((option) => option.value === defaultAgentId)) {
@@ -40,6 +40,7 @@ const CUSTOM_CSS_HELP_PROSE_CLASS =
"text-xs text-foreground/90 leading-relaxed [&>*:first-child]:mt-0 [&>*:last-child]:mb-0";
function SettingsAppearanceTab(props: {
pluginRuntimeAvailable: boolean;
theme: "dark" | "light" | "system";
resolvedTheme: "dark" | "light";
setTheme: (theme: "dark" | "light" | "system") => void;
@@ -366,7 +367,9 @@ function SettingsAppearanceTab(props: {
{renderThemeSwatches(visibleUiThemes, visibleUiThemeId, setVisibleUiThemeId)}
</div>
</SettingsAnchor>
<PluginThemePicker mode={resolvedTheme} onRestore={() => (resolvedTheme === "dark" ? setDarkUiThemeId : setLightUiThemeId)(resolvedTheme === "dark" ? "midnight" : "snow")} />
{props.pluginRuntimeAvailable && (
<PluginThemePicker mode={resolvedTheme} onRestore={() => (resolvedTheme === "dark" ? setDarkUiThemeId : setLightUiThemeId)(resolvedTheme === "dark" ? "midnight" : "snow")} />
)}
{pluginThemeError && <p role="alert" className="text-xs text-destructive">{pluginThemeError}</p>}
<SettingRow
anchorId="appearance-accent-mode"
@@ -154,7 +154,7 @@ export const ModelSelector: React.FC<{
await bridge.aiAllowlistAddHost(baseURL);
}
const url = buildProviderProbeUrl(baseURL, effectiveModelsEndpoint);
const headers = buildModelDiscoveryHeaders(resolvedStyle, apiKey, customHeaders);
const headers = buildModelDiscoveryHeaders(resolvedStyle, apiKey, customHeaders, baseURL);
const result = await bridge.aiFetch(url, "GET", headers, undefined, undefined, undefined, undefined, skipTLSVerify);
if (!result.ok) {
if (discoveryKeyRef.current !== requestKey) return;
@@ -1,12 +1,26 @@
import type { ExternalAgentConfig } from "../../../../infrastructure/ai/types";
import {
type ManagedAgentKey,
getExternalAgentSdkBackend,
isPathLikeCommand,
} from "../../../../infrastructure/ai/managedAgents";
import type { AgentPathInfo } from "./types";
import { AGENT_DEFAULTS, isCursorAvailableForMode } from "./types";
import { buildCodebuddyEnv } from "./codebuddyConfigEnv";
/** A saved, enabled harness can remain preferred while its version probe fails. */
export function getUnavailablePreferredHarness(
agents: ExternalAgentConfig[],
defaultAgentId: string,
): ExternalAgentConfig | undefined {
return agents.find((agent) =>
agent.id === defaultAgentId &&
Object.keys(AGENT_DEFAULTS).some((key) => agent.id === `discovered_${key}`) &&
agent.enabled && agent.available === false &&
agent.commandSource !== "auto" && isPathLikeCommand(agent.command) &&
Boolean(getExternalAgentSdkBackend(agent)));
}
function getAutoManagedAgentStoredPath(
agents: ExternalAgentConfig[],
agentKey: ManagedAgentKey,
@@ -34,9 +48,17 @@ export function buildManagedAgentState(
const managedId = `discovered_${agentKey}`;
const managedAgents = prevAgents.filter((agent) => agent.id === managedId);
const otherAgents = prevAgents.filter((agent) => agent.id !== managedId);
const existingManaged = managedAgents[0];
const savedManualPath = commandSource === "manual" && existingManaged?.commandSource !== "auto"
&& isPathLikeCommand(existingManaged?.command);
if (!pathInfo?.available || !pathInfo.path) {
const existingManaged = managedAgents.find((agent) => agent.id === managedId);
if (savedManualPath && existingManaged) {
return {
agents: prevAgents.map((agent) => agent.id === managedId ? { ...agent, available: false } : agent),
defaultAgentId,
};
}
if (agentKey === "cursor" && (existingManaged?.apiKey || existingManaged?.cursorAuthMode === "cli-login")) {
const defaults = AGENT_DEFAULTS[agentKey];
const {
@@ -97,7 +119,6 @@ export function buildManagedAgentState(
};
}
const existingManaged = managedAgents.find((agent) => agent.id === managedId);
const {
acpCommand: _legacyCommand,
acpArgs: _legacyArgs,
@@ -139,7 +160,9 @@ export function buildManagedAgentState(
available: cursorModeAvailable,
// Do not force-disable when only the current auth mode is temporarily
// unavailable (user may switch modes). Send paths already require available.
enabled: managedAgents.length === 0
enabled: savedManualPath && existingManaged
? existingManaged.enabled
: managedAgents.length === 0
|| (agentKey === "codebuddy" && existingManaged && !isPathLikeCommand(existingManaged.command))
? true
: managedAgents.some((agent) => agent.enabled) || managedAgents.every((agent) => agent.available === false),
+10 -6
View File
@@ -139,6 +139,8 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
// panel setTransfersState for every tick — that re-rendered the whole SFTP
// tree and pegged the renderer during large copies.
const task = useSftpTransferTask(propsTask.id, propsTask);
const pauseFailed = task.status === 'pausing' && !!task.pauseUnavailableReason;
const isPausing = task.status === 'pausing' && !pauseFailed;
// Same progress model as the global transfer center (done · found for folders).
const isDirParent = isDirectoryParentTask(task);
@@ -196,7 +198,7 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
? (fileCountDisplay
? `${t('sftp.transferCenter.phase.scanning')} · ${fileCountDisplay}`
: t('sftp.transferCenter.phase.scanning'))
: task.status === 'pausing'
: isPausing
? pausingLabel
: isDirParent
? (fileCountDisplay
@@ -227,7 +229,9 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
const statusIcon = isResuming
? <Loader2 size={12} className="animate-spin text-primary" />
: task.status === 'pausing'
: pauseFailed
? <Pause size={12} className="text-amber-500" />
: isPausing
? <Loader2 size={12} className="animate-spin text-amber-500" />
: task.status === 'transferring'
? <Loader2 size={12} className="animate-spin text-primary" />
@@ -290,7 +294,7 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
// Surface hard pause misses (e.g. "cannot be paused yet") so the panel
// pause button never looks dead when the backend refuses.
const showPauseUnavailable = !!task.pauseUnavailableReason
&& (task.status === 'transferring' || task.status === 'queued' || task.status === 'pending');
&& (pauseFailed || task.status === 'transferring' || task.status === 'queued' || task.status === 'pending');
const showWarning = task.status === 'completed' && !!task.warning;
const hasFooterContent = showTransferSizeCalculation || showFailedError || showPauseUnavailable || showWarning || childWarningCount > 0;
const retryActionLabel = t('sftp.transfers.retryAction');
@@ -352,7 +356,7 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
</Button>
</IconButtonWithTooltip>
)}
{task.status === 'transferring' && task.resumable !== false && onPause && !isResuming && (
{(task.status === 'transferring' || pauseFailed) && task.resumable !== false && onPause && !isResuming && (
<IconButtonWithTooltip label={pauseActionLabel}>
<Button
type="button"
@@ -367,7 +371,7 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
</Button>
</IconButtonWithTooltip>
)}
{task.status === 'pausing' && (
{isPausing && (
<IconButtonWithTooltip label={pausingLabel}>
<Button
type="button"
@@ -397,7 +401,7 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
</Button>
</IconButtonWithTooltip>
)}
{(task.status === 'paused' || task.status === 'interrupted') && onResume && !isResuming && (
{(task.status === 'paused' || task.status === 'interrupted' || (pauseFailed && task.resumable !== false)) && onResume && !isResuming && (
<IconButtonWithTooltip label={resumeActionLabel}>
<Button
type="button"
@@ -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');
});
+3 -1
View File
@@ -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,
@@ -110,6 +110,7 @@ import {
createTerminalLigatureController,
terminalFontLigaturesEnabled,
} from "./terminalFontLigatures";
import { createPaneBidiJoiner, findRightToLeftRuns } from "./terminalBidiJoiner";
import { createWebglRendererController } from "./webglRendererController";
import { getSharedWebglContextBudget } from "./webglContextBudget";
import {
@@ -1074,6 +1075,22 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
term.loadAddon(unicodeGraphemes);
term.unicode.activeVersion = '15-graphemes';
// Draw Arabic, Persian and Hebrew runs in display order with joined letters.
// Display only: the buffer, selection and copy keep the logical text.
term.registerCharacterJoiner(performanceConfig.useWebGLAddon
? createPaneBidiJoiner(
() => webglController.getAddon() !== null,
() => {
if (runtimeDisposed) return;
// The pinned WebGL addon allocates a maximum-size atlas page for a
// wide joined glyph. Prevent attach/recovery again for just this pane.
webglController.dispose();
logger.info("[XTerm] Using DOM renderer for right-to-left text in this pane");
repaintTerminal();
},
)
: findRightToLeftRuns);
trackRenderer();
const appLevelActions = getAppLevelActions();
@@ -2601,6 +2618,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 +2805,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(() => {
@@ -0,0 +1,128 @@
import assert from "node:assert/strict";
import test from "node:test";
import { createPaneBidiJoiner, findRightToLeftRuns, mightContainRightToLeft } from "./terminalBidiJoiner";
const slice = (text: string, ranges: [number, number][]) =>
ranges.map(([start, end]) => text.slice(start, end));
test("pure left-to-right text is left alone", () => {
assert.deepEqual(findRightToLeftRuns("ls -la /var/log 2>&1 | grep error"), []);
assert.deepEqual(findRightToLeftRuns("10.0.0.138 (eth0) 100%"), []);
assert.deepEqual(findRightToLeftRuns(""), []);
});
test("the cheap detection gate rejects the ASCII and unrelated astral characters", () => {
assert.equal(mightContainRightToLeft(String.raw`update DEPLOY 0 2 3 \uD802`), false);
assert.equal(mightContainRightToLeft("shell 🛠️ 👍"), false);
assert.equal(mightContainRightToLeft("𞤀𞤤"), true);
});
test("supplementary RTL stays whole and returns xterm UTF-16 offsets", () => {
const adlam = "𞤀𞤤";
const text = `🛠 ${adlam} x`;
assert.deepEqual(findRightToLeftRuns(text), [[3, 7]]);
assert.deepEqual(findRightToLeftRuns(`${adlam} 123`), [[0, 8]]);
});
test("Persian prose is one run so the browser can order and join it", () => {
const text = "سلام دنیا";
assert.deepEqual(findRightToLeftRuns(text), [[0, text.length]]);
});
test("Arabic prose keeps its interior spaces and drops trailing ones", () => {
const text = "مرحبا بالعالم ";
assert.deepEqual(slice(text, findRightToLeftRuns(text)), ["مرحبا بالعالم"]);
});
test("a Persian word typed after a shell command is its own run", () => {
const text = 'echo "سلام"';
assert.deepEqual(slice(text, findRightToLeftRuns(text)), ["سلام"]);
});
test("numbers inside Persian text stay in the run", () => {
const text = "قیمت 100 تومان";
assert.deepEqual(findRightToLeftRuns(text), [[0, text.length]]);
});
test("an IP address after Arabic text belongs to the Arabic run", () => {
const text = "العنوان 10.0.0.138";
assert.deepEqual(findRightToLeftRuns(text), [[0, text.length]]);
});
test("Persian digits inside Persian text stay in the run", () => {
const text = "تعداد ۵۰ فایل";
assert.deepEqual(findRightToLeftRuns(text), [[0, text.length]]);
});
test("mixed Persian and English splits at the English words", () => {
const text = "فایل config.yaml پیدا نشد";
assert.deepEqual(slice(text, findRightToLeftRuns(text)), ["فایل", "پیدا نشد"]);
});
test("English with a Persian phrase in the middle only joins the phrase", () => {
const text = "Error: فایل پیدا نشد (code 2)";
assert.deepEqual(slice(text, findRightToLeftRuns(text)), ["فایل پیدا نشد"]);
});
test("brackets around RTL text inside an RTL run are kept with it", () => {
const text = "مثال (نص) هنا";
assert.deepEqual(findRightToLeftRuns(text), [[0, text.length]]);
});
test("Hebrew is handled like Arabic", () => {
const text = "ls שלום עולם";
assert.deepEqual(slice(text, findRightToLeftRuns(text)), ["שלום עולם"]);
});
test("a single right-to-left character is not worth joining", () => {
assert.deepEqual(findRightToLeftRuns("a ب c"), []);
});
test("ranges are sorted and do not overlap", () => {
const text = "الف abc باء def جيم";
const ranges = findRightToLeftRuns(text);
assert.deepEqual(slice(text, ranges), ["الف", "باء", "جيم"]);
for (let i = 1; i < ranges.length; i++) {
assert.ok(ranges[i][0] >= ranges[i - 1][1]);
}
});
test("ASCII output never requests a DOM-only renderer", async () => {
let switches = 0;
const join = createPaneBidiJoiner(() => true, () => { switches++; });
assert.deepEqual(join("192.0.2.1: ready"), []);
assert.deepEqual(join("100 lines of output"), []);
await Promise.resolve();
assert.equal(switches, 0);
});
test("RTL joins are withheld from WebGL until the pane switches once to DOM", async () => {
let webgl = true;
let switches = 0;
const join = createPaneBidiJoiner(() => webgl, () => {
switches++;
webgl = false;
});
const short = "سلام دنیا";
const long = "این یک جمله فارسی معمولی برای بررسی خوانایی متن در یک پنجره عریض است";
assert.deepEqual(join(short), []);
assert.deepEqual(join(long), []);
assert.equal(switches, 0);
await Promise.resolve();
assert.equal(switches, 1);
assert.deepEqual(join(short), [[0, short.length]]);
assert.deepEqual(join(long), [[0, long.length]]);
await Promise.resolve();
assert.equal(switches, 1);
});
test("RTL received before deferred WebGL activation keeps the pane on DOM", async () => {
let switches = 0;
const text = "سلام";
const join = createPaneBidiJoiner(() => false, () => { switches++; });
assert.deepEqual(join(text), [[0, text.length]]);
await Promise.resolve();
assert.equal(switches, 1);
});
@@ -0,0 +1,91 @@
import bidiFactory from "bidi-js";
import rtlCharacterPattern from "../../../lib/terminalRtlCharacter.json";
/**
* Display-only right-to-left support for xterm.js (issue #4261).
*
* xterm.js draws every cell on its own and in buffer (logical) order, so
* Arabic, Persian and Hebrew words come out reversed, and Arabic letters are
* drawn in their isolated forms. xterm.js has no bidi support of its own
* (xtermjs/xterm.js#701).
*
* The DOM renderer draws joined ranges as one string, allowing the browser to
* reorder and shape Arabic letters and mirror brackets. The WebGL addon also
* supports joiners, but long joined RTL runs can exhaust its glyph texture,
* so a pane that needs RTL shaping stays on DOM. The buffer is never changed, so selection, copy, search
* and cursor positions keep working on the logical text. xterm.js also draws
* a range cell by cell again while the cursor is inside it or a selection
* only partly covers it, so editing an RTL word shows the logical cells.
*
* This joiner returns the parts of a line that the Unicode Bidirectional
* Algorithm puts at a right-to-left (or number) embedding level when the
* paragraph direction is left-to-right, which is the default for terminals
* (https://terminal-wg.pages.freedesktop.org/bidi/). Runs separated by
* left-to-right text therefore keep their left-to-right order, and lines are
* not right-aligned.
*/
// RTL scripts and directional controls in the BMP and supplementary planes.
// The Unicode flag makes the supplementary bounds code points, not UTF-16
// lead surrogates (which would also match unrelated non-RTL characters).
const RTL_CHARACTER = new RegExp(rtlCharacterPattern, "u");
const SURROGATE_PAIR = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
// bidi-js 1.0.3 looks up string[i] rather than a full code point. Project
// astral characters to BMP characters of the same bidi class for this
// calculation only. Two copies retain the original UTF-16 offsets expected
// by xterm; the actual glyphs (and terminal buffer) are never replaced.
const BIDI_CLASS_PROXY: Readonly<Record<string, string>> = {
L: "a", R: "א", AL: "ا", EN: "0", AN: "٠", NSM: "\u0301",
ON: "!", BN: "\u00ad", ET: "$", CS: ",", ES: "+",
};
let bidi: ReturnType<typeof bidiFactory> | null = null;
export function mightContainRightToLeft(text: string): boolean {
return RTL_CHARACTER.test(text);
}
export function findRightToLeftRuns(text: string): [number, number][] {
if (!mightContainRightToLeft(text)) return [];
bidi ??= bidiFactory();
const classifier = bidi;
const projected = text.replace(SURROGATE_PAIR, (character) =>
(BIDI_CLASS_PROXY[classifier.getBidiCharTypeName(character)] ?? "!").repeat(2),
);
const { levels } = classifier.getEmbeddingLevels(projected, "ltr");
const ranges: [number, number][] = [];
let start = -1;
for (let i = 0; i <= text.length; i++) {
const inRun = i < text.length && levels[i] > 0;
if (inRun && start < 0) {
start = i;
} else if (!inRun && start >= 0) {
// A single cell looks the same joined or not.
if (i - start > 1) ranges.push([start, i]);
start = -1;
}
}
return ranges;
}
/** Keep wide RTL glyphs out of the WebGL atlas, without changing other panes. */
export function createPaneBidiJoiner(
isWebglActive: () => boolean,
stayOnDom: () => void,
): typeof findRightToLeftRuns {
let requestedDom = false;
return (text) => {
const ranges = findRightToLeftRuns(text);
if (ranges.length === 0) return ranges;
if (!requestedDom) {
requestedDom = true;
// Do not dispose the current renderer from inside its render callback.
queueMicrotask(stayOnDom);
}
return isWebglActive() ? [] : ranges;
};
}
@@ -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", () => {
+49
View File
@@ -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,
+37 -4
View File
@@ -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,
};
}
+1
View File
@@ -44,6 +44,7 @@ function validatePluginRemoteTree(root) {
|| !Array.isArray(node.children) || !record(node.attributes)
|| Object.keys(node).some((key) => !["id", "type", "element", "attributes", "children"].includes(key))) throw new TypeError("Forbidden view element");
if (VOID_ELEMENTS.has(node.element) && node.children.length) throw new TypeError("Void view elements cannot have children");
if (node.element === "textarea" && node.children.some((child) => !record(child) || ![3, 8].includes(child.type))) throw new TypeError("Textarea only accepts text");
const attributes = Object.entries(node.attributes);
if (attributes.length > 64) throw new TypeError("Too many view attributes");
for (const [name, value] of attributes) {
+2
View File
@@ -43,4 +43,6 @@ test("void children are rejected in snapshots and mutation insertions", () => {
assert.throws(() => validatePluginRemoteTree({ children: [node] }), /Void view elements/);
assert.throws(() => validatePluginMutationBatch([[0, "~", node, 0]]), /Void view elements/);
}
assert.throws(() => validatePluginRemoteTree({ children: [element("a", "textarea", {}, [element("b", "div")])] }), /Textarea/);
assert.equal(validatePluginRemoteTree({ children: [element("a", "textarea", {}, [text("b", "Hello"), text("c", " world")])] }), true);
});
+13
View File
@@ -0,0 +1,13 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import type { TransferTask } from './models';
import { getGlobalTransferBatchEligibility, listGloballyPausableTransferIds } from './sftpTransferActions';
test('a partially failed folder pause can be retried or explicitly resumed', () => {
const task = { id: 'folder', status: 'pausing', isDirectory: true, resumable: true,
pauseUnavailableReason: 'This transfer cannot be paused yet' } as TransferTask;
assert.equal(getGlobalTransferBatchEligibility([task]).pausableCount, 1);
assert.equal(getGlobalTransferBatchEligibility([task]).resumableCount, 1);
assert.deepEqual(listGloballyPausableTransferIds([task]), ['folder']);
assert.equal(getGlobalTransferBatchEligibility([{ ...task, pauseUnavailableReason: undefined }]).pausableCount, 0);
});
+2 -1
View File
@@ -5,7 +5,8 @@ export function getGlobalTransferBatchEligibility(tasks: readonly TransferTask[]
return {
cancellableCount: listGloballyCancellableTransferIds(tasks).length,
pausableCount: topLevel.filter((task) => (
["pending", "queued", "transferring"].includes(task.status)
(["pending", "queued", "transferring"].includes(task.status)
|| (task.status === "pausing" && !!task.pauseUnavailableReason))
&& task.resumable !== false
&& !(task.ownerId === "dedicated-resume" && task.reconnectRequired)
)).length,
+20
View File
@@ -0,0 +1,20 @@
const fs = require("node:fs");
const path = require("node:path");
function configureAppProfile(app, devServerUrl) {
const unpackaged = !app.isPackaged;
const isDev = unpackaged && Boolean(devServerUrl);
if (unpackaged) {
// Keep the existing development profile path for both Vite and dist.
app.setName("Netcatty Dev");
const devProfile = path.join(app.getPath("userData"), "dev");
fs.mkdirSync(devProfile, { recursive: true });
app.setPath("userData", devProfile);
// Chromium's Local Storage, IndexedDB and other session state must
// follow the profile even if Electron has already resolved sessionData.
app.setPath("sessionData", devProfile);
}
return { isDev, effectiveDevServerUrl: isDev ? devServerUrl : undefined };
}
module.exports = { configureAppProfile };
+51
View File
@@ -0,0 +1,51 @@
const assert = require("node:assert/strict");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { test } = require("node:test");
const { configureAppProfile } = require("./appProfile.cjs");
function fakeApp(t, isPackaged) {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-profile-"));
t.after(() => fs.rmSync(tmp, { recursive: true, force: true }));
const production = path.join(tmp, "netcatty");
const paths = { userData: production, sessionData: production };
const app = {
isPackaged,
name: "Netcatty",
setName(name) { this.name = name; },
getPath(name) { return paths[name]; },
setPath(name, value) {
assert.ok(fs.statSync(value).isDirectory());
paths[name] = value;
},
};
return { app, paths, production };
}
test("unpackaged dist launches isolate both application and Chromium state", (t) => {
const { app, paths, production } = fakeApp(t, false);
assert.deepEqual(configureAppProfile(app, undefined), {
isDev: false, effectiveDevServerUrl: undefined,
});
const dev = path.join(production, "dev");
assert.deepEqual(paths, { userData: dev, sessionData: dev });
assert.equal(app.name, "Netcatty Dev");
});
test("Vite launches keep the development profile and URL", (t) => {
const { app, paths, production } = fakeApp(t, false);
const url = "http://localhost:5173";
assert.deepEqual(configureAppProfile(app, url), { isDev: true, effectiveDevServerUrl: url });
const dev = path.join(production, "dev");
assert.deepEqual(paths, { userData: dev, sessionData: dev });
});
test("packaged launches keep their data paths and ignore a Vite URL", (t) => {
const { app, paths, production } = fakeApp(t, true);
assert.deepEqual(configureAppProfile(app, "http://localhost:5173"), {
isDev: false, effectiveDevServerUrl: undefined,
});
assert.deepEqual(paths, { userData: production, sessionData: production });
assert.equal(app.name, "Netcatty");
});
+5
View File
@@ -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) ||
+39
View File
@@ -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
@@ -254,19 +254,25 @@ function buildCodebuddyQueryOptions({
elicitation, canUseTool,
}) {
const builtinTools = codebuddyBuiltinTools(toolIntegrationMode);
const mcpMode = builtinTools.length === 0;
const mcpServers = toSdkMcpServers(injectedMcpServers);
if (mcpMode) {
// These are only the app-managed servers. Show their tools directly without
// enabling the CLI’s general-purpose discovery tools.
for (const server of Object.values(mcpServers)) {
if (server.type !== "sdk") server.defer_loading = false;
}
}
const options = {
cwd,
includePartialMessages: true,
permissionMode: "bypassPermissions",
allowDangerouslySkipPermissions: true,
extraArgs: { "dangerously-skip-permissions": null },
mcpServers: toSdkMcpServers(injectedMcpServers),
mcpServers,
...(mcpMode ? { strictMcpConfig: true } : {}),
// Keep unrelated CLI built-ins disabled by default, including future tools.
tools: builtinTools,
// `tools` is the built-in tool whitelist. In mcp mode it is [], so CodeBuddy
// built-ins stay disabled while injected Netcatty MCP tools remain visible.
// Do not mirror that empty list into allowedTools: the SDK treats
// allowedTools as an auto-approval list, and allowedTools: [] prevents MCP
// tool calls from running under bypassPermissions.
disallowedTools: [...UI_DISALLOWED_TOOLS],
// Keep the SDK isolated from user/project settings so local hooks, plugins,
// or extra MCP servers cannot expand Netcatty's controlled tool boundary.
@@ -60,14 +60,38 @@ test("buildCodebuddyQueryOptions wires SDK options in isolated mode", () => {
assert.equal(opts.abortController, ac);
assert.equal(opts.resume, "sess-1");
assert.deepEqual(opts.tools, []);
// allowedTools must stay unset in mcp mode: tools:[] disables built-ins, while
// allowedTools:[] would prevent injected Netcatty MCP tools from running.
assert.ok(!("allowedTools" in opts));
assert.equal(opts.strictMcpConfig, true);
assert.equal(opts.mcpServers["netcatty-remote-hosts"].defer_loading, false);
assert.ok(opts.disallowedTools.includes("AskUserQuestion"));
assert.equal(opts.mcpServers["netcatty-remote-hosts"].type, "stdio");
assert.deepEqual(opts.mcpServers["netcatty-remote-hosts"].env, { NETCATTY_MCP_PORT: "1" });
});
test("mcp and default mode allow only the app-managed MCP configuration", () => {
for (const toolIntegrationMode of ["mcp", undefined]) {
const opts = buildCodebuddyQueryOptions({
toolIntegrationMode,
injectedMcpServers: [{ name: "netcatty", command: "/abs/electron" }],
});
assert.deepEqual(opts.tools, []);
assert.ok(!("allowedTools" in opts));
assert.deepEqual(opts.settingSources, []);
assert.equal(opts.strictMcpConfig, true);
assert.equal(opts.mcpServers.netcatty.command, "/abs/electron");
assert.equal(opts.mcpServers.netcatty.defer_loading, false);
}
});
test("skills mode keeps the Bash whitelist and UI exclusions", () => {
const opts = buildCodebuddyQueryOptions({ toolIntegrationMode: "skills" });
assert.deepEqual(opts.tools, ["Bash"]);
assert.deepEqual(opts.disallowedTools, ["AskUserQuestion"]);
assert.ok(!opts.disallowedTools.includes("Bash"));
assert.ok(!("allowedTools" in opts));
});
test("built-in tools are mode-aware", () => {
assert.deepEqual(codebuddyBuiltinTools("mcp"), []);
assert.deepEqual(codebuddyBuiltinTools(undefined), []);
+4 -9
View File
@@ -88,6 +88,10 @@ const path = require("node:path");
const os = require("node:os");
const fs = require("node:fs");
const { execFile } = require("node:child_process");
// Separate profile selection from renderer loading. In particular, source
// builds serving dist/ still need a non-production profile.
const { configureAppProfile } = require("./appProfile.cjs");
const { isDev, effectiveDevServerUrl } = configureAppProfile(app, process.env.VITE_DEV_SERVER_URL);
const { getCliDiscoveryFilePath } = require("./cli/discoveryPath.cjs");
const {
SSH_DEEP_LINK_CHANNEL,
@@ -291,15 +295,6 @@ app.on("web-contents-created", (_event, contents) => {
});
});
// Application configuration
const devServerUrl = process.env.VITE_DEV_SERVER_URL;
// Never treat a packaged app as "dev" even if the user has VITE_DEV_SERVER_URL set globally.
const isDev = !app.isPackaged && !!devServerUrl;
const effectiveDevServerUrl = isDev ? devServerUrl : undefined;
if (isDev) {
app.setName("Netcatty Dev");
app.setPath("userData", path.join(app.getPath("userData"), "dev"));
}
const { applyPortableDataDirectory } = require("./portableData.cjs");
const portableData = applyPortableDataDirectory({ app });
if (portableData) {
+1 -1
View File
@@ -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", () => {
+6
View File
@@ -1,6 +1,12 @@
"use strict";
const { isPluginDevelopmentEnabled } = require("./constants.cjs");
function startPluginHost(options) {
// The plugin platform is not shipping in this release. Keep its data
// untouched and allow existing developer workflows to opt in as before.
if (!isPluginDevelopmentEnabled(options.env)) return null;
const reportFailure = (message, error) => {
try { options.logger?.error?.(message, error); } catch {}
};
+7 -8
View File
@@ -5,16 +5,15 @@ const test = require("node:test");
const { startPluginHost } = require("./hostBootstrap.cjs");
test("normal release constructs the browser plugin host without a developer flag", async () => {
let created = 0;
const service = { manager: { async initialize() {}, async shutdown() {} } };
test("default startup leaves the plugin host and stored plugin data untouched", () => {
const effects = [];
assert.equal(startPluginHost({
env: {},
createService() { created += 1; return service; },
registerShutdown() {},
logger: { error() {} },
}), service);
assert.equal(created, 1);
createService() { effects.push("create"); },
registerShutdown() { effects.push("register"); },
logger: { error() { effects.push("error"); } },
}), null);
assert.deepEqual(effects, []);
});
test("synchronous plugin host construction failure leaves Netcatty available", () => {
+1 -1
View File
@@ -804,7 +804,7 @@ function registerPluginBridge(ipcMain, options) {
if (!options.interactionService) throw new Error("Host interactions unavailable");
return options.interactionService.setTerminalTarget(event.sender, target);
});
handle(CHANNELS.themeCatalog, async () => {
handlePassive(CHANNELS.themeCatalog, null, async () => {
if (!options.themeService) throw new Error("Plugin themes are unavailable");
return options.themeService.catalog();
});
+1
View File
@@ -53,6 +53,7 @@ test("disabled plugin runtime keeps passive host integration channels quiet", as
assert.deepEqual(await ipcMain.handlers.get(CHANNELS.terminalProviders)({}, {}), []);
assert.deepEqual(await ipcMain.handlers.get(CHANNELS.terminalSessionEvent)({}, {}), []);
assert.deepEqual(await ipcMain.handlers.get(CHANNELS.extensionProviders)({}, {}), []);
assert.equal(await ipcMain.handlers.get(CHANNELS.themeCatalog)({}), null);
assert.equal(await ipcMain.handlers.get(CHANNELS.credentialCatalogUpdate)({}, { entries: [] }), 0);
assert.equal(await ipcMain.handlers.get(CHANNELS.setScopeCatalog)({}, {}), null);
assert.deepEqual(await ipcMain.handlers.get(CHANNELS.getScopeCatalog)({}, {}), {
+15 -2
View File
@@ -3,6 +3,19 @@ export function mount(root, context, viewId) {
const onDispose = (stop) => cleanup.push(stop);
const subscribeMessage = (listener) => { const sub = context.views.onDidReceiveMessage(viewId, listener); cleanup.push(() => sub.dispose()); return sub; };
const element = (id) => root.querySelector("#" + id);
// Keep the newest output visible within the host's per-node and total limits.
// Chunking avoids closing a healthy view when an ordinary response exceeds 8 KB.
let outputText = ''; let outputTruncated = false;
function showOutput(text, append = false) {
const combined = append ? outputText + text : text;
outputTruncated = (append && outputTruncated) || combined.length > 32768;
outputText = combined.slice(-32768);
const nodes = [];
if (outputTruncated) nodes.push(root.ownerDocument.createTextNode('[Earlier output omitted; showing the latest 32,768 characters.]\n\n'));
for (let offset = 0; offset < outputText.length; offset += 4096) nodes.push(root.ownerDocument.createTextNode(outputText.slice(offset, offset + 4096)));
element('response').replaceChildren(...nodes);
}
const invoke = (operation, params = {}) => context.commands.executeCommand(`com.netcatty.assistant.${operation}`, params);
let chat;
let turn;
@@ -90,7 +103,7 @@ element('compose').addEventListener('submit', async (event) => {
}
const run = ++generation;
busy(true); element('status').textContent = 'Streaming...';
element('response').textContent = ''; element('usage').textContent = '';
showOutput(''); element('usage').textContent = '';
try {
// No inference has been requested yet, so an expired session can be
// replaced before this explicit Send. Never retry a failed send/read.
@@ -103,7 +116,7 @@ element('compose').addEventListener('submit', async (event) => {
const chunk = await invoke('read', { turnHandle: turn });
if (run !== generation) return;
if (chunk.kind === 'end') break;
if (chunk.kind === 'text') element('response').textContent += chunk.text;
if (chunk.kind === 'text') showOutput(chunk.text, true);
if (chunk.kind === 'usage') element('usage').textContent = `${chunk.inputTokens ?? '?'} input tokens · ${chunk.outputTokens ?? '?'} output tokens`;
}
element('status').textContent = 'Complete';
+17 -3
View File
@@ -3,6 +3,19 @@ export function mount(root, context, viewId) {
const onDispose = (stop) => cleanup.push(stop);
const subscribeMessage = (listener) => { const sub = context.views.onDidReceiveMessage(viewId, listener); cleanup.push(() => sub.dispose()); return sub; };
const element = (id) => root.querySelector("#" + id);
// Keep the newest output visible within the host's per-node and total limits.
// Chunking avoids closing a healthy view when an ordinary response exceeds 8 KB.
let outputText = ''; let outputTruncated = false;
function showOutput(text, append = false) {
const combined = append ? outputText + text : text;
outputTruncated = (append && outputTruncated) || combined.length > 32768;
outputText = combined.slice(-32768);
const nodes = [];
if (outputTruncated) nodes.push(root.ownerDocument.createTextNode('[Earlier output omitted; showing the latest 32,768 characters.]\n\n'));
for (let offset = 0; offset < outputText.length; offset += 4096) nodes.push(root.ownerDocument.createTextNode(outputText.slice(offset, offset + 4096)));
element('transcript').replaceChildren(...nodes);
}
const invoke = (name, params = {}) => context.commands.executeCommand(`com.netcatty.globalagent.${name}`, params);
let chat; let selection; let turn; let busy = false; let generation = 0; let closed = false;
const option = (value, text) => { const item = root.ownerDocument.createElement('option'); item.value = value; item.textContent = text; return item; };
@@ -53,7 +66,7 @@ element('open').addEventListener('click', async () => {
if (closed || run !== generation) { await invoke('close', { chatHandle: result.chatHandle }).catch(() => {}); return; }
chat = result; const history = await invoke('history', { chatHandle: chat.chatHandle });
if (closed || run !== generation) return;
element('transcript').textContent = history.items.map((item) => `${item.role}: ${item.text}`).join('\n\n');
showOutput(history.items.map((item) => `${item.role}: ${item.text}`).join('\n\n'));
element('usage').textContent = ''; element('activity').textContent = '';
status(`Ready · ${result.backendLabel}`);
} catch { await closeChat(); if (!closed && run === generation) status('Conversation unavailable. Refresh backends or choose terminals again; your draft is kept.'); }
@@ -62,8 +75,9 @@ element('open').addEventListener('click', async () => {
element('compose').addEventListener('submit', async (event) => {
event.preventDefault(); if (busy || !chat || !element('prompt').value.trim()) return;
if (chat.expiresAt <= Date.now()) { status('Conversation targets expired. Choose terminals and reopen; your draft is kept.'); return; }
if (element('prompt').value.length > 8192) { status('Message is too long. Limit it to 8,192 characters before sending.'); return; }
const run = ++generation; controls(true); status('Running…'); element('usage').textContent = ''; element('activity').textContent = '';
const text = element('prompt').value; element('transcript').textContent += `\n\nuser: ${text}\n\nassistant: `;
const text = element('prompt').value; showOutput(`\n\nuser: ${text}\n\nassistant: `, true);
try {
const result = await invoke('send', { chatHandle: chat.chatHandle, text });
if (closed || run !== generation) { await invoke('stop', { turnHandle: result.turnHandle }).catch(() => {}); return; }
@@ -71,7 +85,7 @@ element('compose').addEventListener('submit', async (event) => {
for (;;) {
const item = await invoke('read', { turnHandle: turn }); if (closed || run !== generation) return;
if (item.kind === 'end') { status(item.reason === 'completed' ? 'Complete' : `Ended: ${item.reason}`); break; }
if (item.kind === 'text') element('transcript').textContent += item.text;
if (item.kind === 'text') showOutput(item.text, true);
if (item.kind === 'activity') element('activity').textContent = `${item.capabilityId}: ${item.state}`;
if (item.kind === 'usage') element('usage').textContent = `${item.inputTokens} input tokens · ${item.outputTokens} output tokens`;
}
+1 -1
View File
@@ -3,5 +3,5 @@
<div><label for="conversation">Owned conversation</label><select id="conversation"><option value="">New conversation</option></select></div>
<div class="actions"><button id="refresh" type="button">Refresh backends</button><button id="targets" type="button">Choose terminals</button><button id="open" type="button" disabled>Open conversation</button></div><p id="selection" class="hint">No targets selected yet.</p></section>
<section class="card response"><pre id="transcript" aria-live="polite"></pre><p id="usage" class="hint"></p><p id="activity" class="hint"></p></section>
<form id="compose"><label for="prompt">Message</label><textarea id="prompt" maxlength="16384" placeholder="Ask about the selected terminals"></textarea><div class="actions"><button id="send" type="submit" disabled>Send</button><button id="stop" type="button" disabled>Stop</button><span id="status" role="status">Loading configured backends…</span></div></form>
<form id="compose"><label for="prompt">Message</label><textarea id="prompt" maxlength="8192" placeholder="Ask about the selected terminals"></textarea><div class="actions"><button id="send" type="submit" disabled>Send</button><button id="stop" type="button" disabled>Stop</button><span id="status" role="status">Loading configured backends…</span></div></form>
<footer>Actions follow this plugin's Allow / Ask / Deny setting.</footer></main></div>
@@ -71,3 +71,19 @@ test("normalizeAnthropicSdkBaseURL preserves custom non-/v1 path prefixes", () =
"https://gateway.example/api/v1",
);
});
test("normalizes the official Ark Agent Plan Anthropic prefix only", () => {
const base = "https://ark.cn-beijing.volces.com/api/plan";
for (const input of [base, base + "/", " " + base + " ", base + "/v1", base + "/v1/"]) {
assert.equal(normalizeAnthropicSdkBaseURL(input), base + "/v1");
}
for (const input of [
base.replace("https:", "http:"),
base.replace(".com", ".com.example"),
base.replace(".com", ".com:8443"),
base + "/custom",
"https://gateway.example/api/plan",
]) {
assert.equal(normalizeAnthropicSdkBaseURL(input), input);
}
});
@@ -39,6 +39,7 @@ export function isBareOriginBaseURL(baseURL: string): boolean {
* Normalize a stored Anthropic-compat Base URL for @ai-sdk/anthropic.
* - Bare hosts gain a /v1 suffix (Claude Code style → SDK style).
* - Bases that already end in /v1 are left unchanged.
* - The official Ark Agent Plan /api/plan prefix gains a /v1 suffix.
* - Other path prefixes (custom proxies) are left unchanged so chat keeps
* requesting `{prefix}/messages` rather than `{prefix}/v1/messages`.
*/
@@ -46,6 +47,9 @@ export function normalizeAnthropicSdkBaseURL(baseURL: string): string {
const trimmed = stripTrailingSlashes(baseURL);
if (!trimmed) return trimmed;
if (anthropicBaseIncludesV1(trimmed)) return trimmed;
// Claude Code appends /v1/messages to the documented Ark Agent Plan base.
// The Anthropic SDK appends only /messages, so supply the missing /v1.
if (trimmed === "https://ark.cn-beijing.volces.com/api/plan") return `${trimmed}/v1`;
if (!isBareOriginBaseURL(trimmed)) return trimmed;
return `${trimmed}/v1`;
}
+6 -1
View File
@@ -142,7 +142,12 @@ export async function fetchProviderModelCatalog(
await bridge.aiAllowlistAddHost(baseURL);
}
const url = buildProviderProbeUrl(baseURL, endpoint);
const headers = buildModelDiscoveryHeaders(style, apiKey, await decryptProviderHeaders(provider.customHeaders));
const headers = buildModelDiscoveryHeaders(
style,
apiKey,
await decryptProviderHeaders(provider.customHeaders),
baseURL,
);
const result = await bridge.aiFetch(
url,
'GET',
@@ -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) {
@@ -1,13 +1,34 @@
import assert from "node:assert/strict";
import test from "node:test";
import { buildModelDiscoveryHeaders, resolveModelsDiscoveryEndpoint } from "./modelDiscoveryHeaders";
import {
buildModelDiscoveryHeaders,
isCustomAnthropicBaseURL,
resolveModelsDiscoveryEndpoint,
} from "./modelDiscoveryHeaders";
test("buildModelDiscoveryHeaders uses x-api-key+anthropic-version for the anthropic family", () => {
assert.deepEqual(buildModelDiscoveryHeaders("anthropic", "sk-test"), {
"x-api-key": "sk-test",
"anthropic-version": "2023-06-01",
});
test("buildModelDiscoveryHeaders uses x-api-key+anthropic-version only on official anthropic host", () => {
for (const baseURL of [undefined, "", "https://api.anthropic.com", "https://api.anthropic.com/v1"]) {
assert.deepEqual(buildModelDiscoveryHeaders("anthropic", "sk-test", {}, baseURL), {
"x-api-key": "sk-test",
"anthropic-version": "2023-06-01",
});
assert.equal(isCustomAnthropicBaseURL(baseURL), false);
}
});
test("buildModelDiscoveryHeaders sends both x-api-key and Bearer auth on custom anthropic bases", () => {
for (const baseURL of [
"https://ark.cn-beijing.volces.com/api/plan",
"https://gateway.example/v1",
]) {
assert.equal(isCustomAnthropicBaseURL(baseURL), true);
assert.deepEqual(buildModelDiscoveryHeaders("anthropic", "sk-test", {}, baseURL), {
"x-api-key": "sk-test",
Authorization: "Bearer sk-test",
"anthropic-version": "2023-06-01",
});
}
});
test("buildModelDiscoveryHeaders uses Bearer auth for the openai-compatible family", () => {
@@ -65,4 +86,16 @@ test('custom discovery headers override default auth regardless of case', () =>
assert.equal(Object.keys(headers).filter(key => key.toLowerCase() === name.toLowerCase()).length, 1);
assert.equal(headers['X-Tenant'], 'tenant');
}
const customAnthropicAuth = buildModelDiscoveryHeaders(
'anthropic',
'default-key',
{ authorization: 'Bearer custom-token' },
'https://ark.cn-beijing.volces.com/api/plan',
);
assert.deepEqual(customAnthropicAuth, {
'x-api-key': 'default-key',
'anthropic-version': '2023-06-01',
authorization: 'Bearer custom-token',
});
});
+23 -2
View File
@@ -27,11 +27,27 @@ export function resolveModelsDiscoveryEndpoint(
return STYLE_DEFAULT_MODELS_ENDPOINT[style] ?? presetEndpoint;
}
/**
* True when `baseURL` is a valid URL whose host is not the official
* `api.anthropic.com` endpoint. Omitted or blank values default to the
* official host and return `false`.
*/
export function isCustomAnthropicBaseURL(baseURL?: string): boolean {
const trimmed = baseURL?.trim();
if (!trimmed) return false;
try {
return new URL(trimmed).hostname.toLowerCase() !== "api.anthropic.com";
} catch {
return false;
}
}
/**
* Pick auth headers for a provider's `/models` discovery endpoint.
*
* Each wire-protocol family uses its own auth dialect:
* - `anthropic`: `x-api-key` + `anthropic-version`
* - `anthropic`: `x-api-key` + `anthropic-version` on official `api.anthropic.com`;
* custom Anthropic-compatible gateways also receive `Authorization: Bearer ...`
* - `google`: `x-goog-api-key` (Google Generative AI rejects Bearer)
* - `openai`: `Authorization: Bearer …` (also the OpenAI-compat default)
*
@@ -41,12 +57,16 @@ export function resolveModelsDiscoveryEndpoint(
function buildDefaultModelDiscoveryHeaders(
style: ProviderStyle,
apiKey: string | undefined,
baseURL?: string,
): Record<string, string> {
if (!apiKey) return {};
switch (style) {
case "anthropic":
return {
"x-api-key": apiKey,
...(isCustomAnthropicBaseURL(baseURL)
? { Authorization: `Bearer ${apiKey}` }
: {}),
"anthropic-version": "2023-06-01",
};
case "google":
@@ -61,8 +81,9 @@ export function buildModelDiscoveryHeaders(
style: ProviderStyle,
apiKey: string | undefined,
customHeaders: Record<string, string> = {},
baseURL?: string,
): Record<string, string> {
const headers = buildDefaultModelDiscoveryHeaders(style, apiKey);
const headers = buildDefaultModelDiscoveryHeaders(style, apiKey, baseURL);
const overridden = new Set(Object.keys(customHeaders).map((name) => name.toLowerCase()));
return Object.fromEntries([
...Object.entries(headers).filter(([name]) => !overridden.has(name.toLowerCase())),
@@ -59,17 +59,38 @@ test("validateProviderProbeInputs requires base URL and API key except for ollam
);
});
test("classifyProviderProbeResponse marks auth and transport failures as error", () => {
test("classifyProviderProbeResponse marks auth, permission, server, and transport failures as error", () => {
assert.equal(
classifyProviderProbeResponse({ ok: false, status: 401, latencyMs: 120, error: "Unauthorized" }).health,
"error",
);
assert.equal(
classifyProviderProbeResponse({ ok: false, status: 403, latencyMs: 90 }).health,
"error",
);
assert.equal(
classifyProviderProbeResponse({ ok: false, status: 502, latencyMs: 200 }).health,
"error",
);
assert.equal(
classifyProviderProbeResponse({ ok: false, status: 0, latencyMs: 30, error: "Request timeout" }).health,
"error",
);
});
test("classifyProviderProbeResponse downgrades HTTP 404 models-list probe to warn", () => {
const result = classifyProviderProbeResponse({
ok: false,
status: 404,
latencyMs: 95,
data: "404 page not found",
});
assert.equal(result.health, "warn");
assert.equal(result.statusCode, 404);
assert.equal(result.latencyMs, 95);
assert.ok(result.error && result.error.includes("404"));
});
test("classifyProviderProbeResponse marks 2xx with models payload as ok", () => {
const result = classifyProviderProbeResponse({
ok: true,
@@ -188,11 +209,11 @@ test("probeProviderConnection returns typed failures before fetch", async () =>
});
test("probeProviderConnection does not double /v1 for Anthropic AI SDK style bases", async () => {
const calls: string[] = [];
const calls: Array<{ url: string; headers?: Record<string, string> }> = [];
const run = await probeProviderConnection({
bridge: {
aiFetch: async (url) => {
calls.push(url);
aiFetch: async (url, _method, headers) => {
calls.push({ url, headers });
return {
ok: true,
status: 200,
@@ -205,6 +226,90 @@ test("probeProviderConnection does not double /v1 for Anthropic AI SDK style bas
providerId: "custom",
style: "anthropic",
});
assert.deepEqual(calls, ["https://gateway.example/v1/models"]);
assert.deepEqual(calls, [
{
url: "https://gateway.example/v1/models",
headers: {
"x-api-key": "sk-test",
Authorization: "Bearer sk-test",
"anthropic-version": "2023-06-01",
},
},
]);
assert.equal(run.ok, true);
});
test("probeProviderConnection keeps official Anthropic free of Bearer while custom gateways get Bearer and 404 warns", async () => {
const calls: Array<{ url: string; headers?: Record<string, string> }> = [];
const official = await probeProviderConnection({
bridge: {
aiFetch: async (url, _method, headers) => {
calls.push({ url, headers });
return {
ok: true,
status: 200,
data: JSON.stringify({ data: [{ id: "claude-sonnet-4-5" }] }),
};
},
},
baseURL: "https://api.anthropic.com",
apiKey: "sk-ant-test",
providerId: "anthropic",
style: "anthropic",
});
assert.equal(official.ok, true);
assert.deepEqual(calls[0], {
url: "https://api.anthropic.com/v1/models",
headers: {
"x-api-key": "sk-ant-test",
"anthropic-version": "2023-06-01",
},
});
const agentPlanOpenAI = await probeProviderConnection({
bridge: {
aiFetch: async (url, _method, headers) => {
calls.push({ url, headers });
return { ok: false, status: 404, data: "404 page not found" };
},
},
baseURL: "https://ark.cn-beijing.volces.com/api/plan/v3",
apiKey: "ark-key",
providerId: "custom",
style: "openai",
});
assert.equal(agentPlanOpenAI.ok, true);
if (!agentPlanOpenAI.ok) throw new Error("expected probe result");
assert.equal(agentPlanOpenAI.classification.health, "warn");
assert.equal(agentPlanOpenAI.classification.statusCode, 404);
assert.deepEqual(calls[1], {
url: "https://ark.cn-beijing.volces.com/api/plan/v3/models",
headers: { Authorization: "Bearer ark-key" },
});
const agentPlanAnthropic = await probeProviderConnection({
bridge: {
aiFetch: async (url, _method, headers) => {
calls.push({ url, headers });
return { ok: false, status: 404, data: "404 page not found" };
},
},
baseURL: "https://ark.cn-beijing.volces.com/api/plan",
apiKey: "ark-key",
providerId: "custom",
style: "anthropic",
});
assert.equal(agentPlanAnthropic.ok, true);
if (!agentPlanAnthropic.ok) throw new Error("expected probe result");
assert.equal(agentPlanAnthropic.classification.health, "warn");
assert.equal(agentPlanAnthropic.classification.statusCode, 404);
assert.deepEqual(calls[2], {
url: "https://ark.cn-beijing.volces.com/api/plan/v1/models",
headers: {
"x-api-key": "ark-key",
Authorization: "Bearer ark-key",
"anthropic-version": "2023-06-01",
},
});
});
+16 -2
View File
@@ -98,7 +98,8 @@ function countModelsInPayload(data: string | undefined): number | undefined {
/**
* Map a lightweight `/models` (or equivalent) probe response to green / yellow / red.
* Yellow covers slow-but-successful replies and empty model catalogs.
* Yellow covers slow-but-successful replies, empty model catalogs, and HTTP 404
* (gateways that work for chat without exposing a models listing route).
*/
export function classifyProviderProbeResponse(input: {
ok: boolean;
@@ -115,6 +116,14 @@ export function classifyProviderProbeResponse(input: {
...(input.error ? { error: input.error } : {}),
};
if (input.status === 404) {
return {
...base,
health: "warn",
error: input.error || "Model list not available (HTTP 404)",
};
}
if (!input.ok || input.status < 200 || input.status >= 300) {
return {
...base,
@@ -182,7 +191,12 @@ export async function probeProviderConnection(input: {
await bridge.aiAllowlistAddHost(baseURL);
}
const url = buildProviderProbeUrl(baseURL, endpoint);
const headers = buildModelDiscoveryHeaders(input.style, input.apiKey, input.customHeaders);
const headers = buildModelDiscoveryHeaders(
input.style,
input.apiKey,
input.customHeaders,
baseURL,
);
const result = await bridge.aiFetch(
url,
"GET",
+16 -3
View File
@@ -5,6 +5,7 @@ import { wrapLanguageModel, type LanguageModelMiddleware } from 'ai';
import type { ProviderConfig, ProviderStyle } from '../types';
import { resolveOpenAIApi, resolveProviderStyle } from '../types';
import { normalizeAnthropicSdkBaseURL } from '../anthropicCompatBaseUrl';
import { isCustomAnthropicBaseURL } from '../modelDiscoveryHeaders';
import { buildSdkRequestHeaders } from '../providerRequestHeaders';
import { normalizeOllamaSdkBaseURL } from '../ollamaCompatBaseUrl';
import { normalizeOpenAIChatCacheUsage } from '../openAIChatCacheUsage';
@@ -774,13 +775,25 @@ function createProviderModel(
: openai.chat(modelId);
}
case 'anthropic':
case 'anthropic': {
// Official api.anthropic.com keeps x-api-key only. Custom Anthropic-compat
// gateways (e.g. Volcengine Ark Agent Plan, Claude Code proxies) may require
// Authorization: Bearer (ANTHROPIC_AUTH_TOKEN) or x-api-key, so send both.
// @ai-sdk/anthropic rejects passing apiKey and authToken together, so pass
// authToken for Bearer and retain x-api-key in headers unless overridden.
const useCustomBearer = Boolean(apiKey && isCustomAnthropicBaseURL(baseURL));
const hasCustomXApiKey = Object.keys(sdkHeaders).some(
(key) => key.toLowerCase() === 'x-api-key',
);
return createAnthropic({
apiKey,
...(useCustomBearer ? { authToken: apiKey } : { apiKey }),
baseURL,
fetch: customFetch,
headers: sdkHeaders,
headers: useCustomBearer && !hasCustomXApiKey
? { 'x-api-key': apiKey!, ...sdkHeaders }
: sdkHeaders,
})(modelId);
}
case 'google':
return createGoogle({
+72
View File
@@ -323,3 +323,75 @@ test("OpenAI Chat sends inline image attachments as data URLs through the bridge
}
assert.equal(requests.length, 4);
});
test("Anthropic SDK sends x-api-key only on official host and adds Bearer on custom bases", async (t) => {
const browserGlobal = globalThis as typeof globalThis & { window?: unknown };
const originalWindow = browserGlobal.window;
t.after(() => { browserGlobal.window = originalWindow; });
const requests: Array<{ url: string; headers: Headers }> = [];
Reflect.set(globalThis, "window", {
netcatty: {
aiFetch: async (url: string, _method: string, headers: Record<string, string>) => {
requests.push({ url, headers: new Headers(headers) });
return { ok: false, status: 400, data: '{"error":{"message":"captured anthropic request"}}' };
},
},
});
const prompt = [{ role: "user" as const, content: [{ type: "text" as const, text: "hello" }] }];
for (const baseURL of [undefined, "https://api.anthropic.com", "https://api.anthropic.com/v1"]) {
const model = createModelFromConfig(makeConfig({
providerId: "anthropic",
style: "anthropic",
apiKey: "test-key",
baseURL,
}));
await assert.rejects(async () => await model.doGenerate({ prompt }));
const request = requests.at(-1)!;
assert.equal(request.headers.get("x-api-key"), "__IPC_SECURED__");
assert.equal(request.headers.get("authorization"), null);
assert.equal(request.headers.get("anthropic-version"), "2023-06-01");
}
for (const baseURL of [
"https://ark.cn-beijing.volces.com/api/plan",
"https://gateway.example/v1",
]) {
const model = createModelFromConfig(makeConfig({
style: "anthropic",
apiKey: "test-key",
baseURL,
}));
await assert.rejects(async () => await model.doGenerate({ prompt }));
const request = requests.at(-1)!;
assert.equal(request.url, baseURL.endsWith("/api/plan")
? baseURL + "/v1/messages"
: baseURL + "/messages");
assert.equal(request.headers.get("x-api-key"), "__IPC_SECURED__");
assert.equal(request.headers.get("authorization"), "Bearer __IPC_SECURED__");
assert.equal(request.headers.get("anthropic-version"), "2023-06-01");
}
const overridden = createModelFromConfig(makeConfig({
style: "anthropic",
apiKey: "test-key",
baseURL: "https://ark.cn-beijing.volces.com/api/plan",
customHeaders: { Authorization: "Bearer custom-override" },
}));
await assert.rejects(async () => await overridden.doGenerate({ prompt }));
const overriddenReq = requests.at(-1)!;
assert.equal(overriddenReq.headers.get("x-api-key"), "__IPC_SECURED__");
assert.equal(overriddenReq.headers.get("authorization"), "Bearer custom-override");
const overriddenApiKey = createModelFromConfig(makeConfig({
style: "anthropic",
apiKey: "test-key",
baseURL: "https://ark.cn-beijing.volces.com/api/plan",
customHeaders: { "X-API-Key": "custom-x-api-key" },
}));
await assert.rejects(async () => await overriddenApiKey.doGenerate({ prompt }));
const overriddenApiKeyReq = requests.at(-1)!;
assert.equal(overriddenApiKeyReq.headers.get("x-api-key"), "custom-x-api-key");
assert.equal(overriddenApiKeyReq.headers.get("authorization"), "Bearer __IPC_SECURED__");
});
+2
View File
@@ -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;
+1
View File
@@ -0,0 +1 @@
"[\\u0590-\\u08ff\\u200f\\u202b\\u202e\\u2067\\ufb1d-\\ufdff\\ufe70-\\ufefc\\u{10800}-\\u{10fff}\\u{1e800}-\\u{1eeff}]"
+1 -1
View File
@@ -27,6 +27,7 @@
"@withfig/autocomplete": "^2.692.3",
"ajv": "8.18.0",
"ajv-formats": "3.0.1",
"bidi-js": "1.0.3",
"css-tree": "^3.2.1",
"electron-updater": "^6.8.3",
"http-proxy-agent": "^7.0.2",
@@ -10231,7 +10232,6 @@
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz",
"integrity": "sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==",
"dev": true,
"license": "MIT",
"dependencies": {
"require-from-string": "^2.0.2"
+2 -1
View File
@@ -42,7 +42,7 @@
"pack:linux": "npm run build && cross-env NODE_OPTIONS=--disable-warning=DEP0190 electron-builder --config electron-builder.config.cjs --linux --publish=never",
"pack:linux-x64": "npm run build && cross-env npm_config_arch=x64 NODE_OPTIONS=--disable-warning=DEP0190 electron-builder --config electron-builder.config.cjs --linux --x64 --publish=never",
"pack:linux-arm64": "npm run build && cross-env npm_config_arch=arm64 NODE_OPTIONS=--disable-warning=DEP0190 electron-builder --config electron-builder.config.cjs --linux --arm64 --publish=never",
"postinstall": "patch-package && node scripts/patch-xterm-macos-column-selection.cjs && node scripts/patch-xterm-foreground-intense.cjs && node scripts/patch-xterm-ligatures-font-cache.cjs && node scripts/patch-xterm-image-tile-stride.cjs && node scripts/patch-xterm-image-iip-type.cjs && electron-builder install-app-deps && node scripts/rebuildPatchedNodePty.cjs && node scripts/patch-xterm-webgl-atlas.cjs",
"postinstall": "patch-package && node scripts/patch-xterm-macos-column-selection.cjs && node scripts/patch-xterm-foreground-intense.cjs && node scripts/patch-xterm-joined-width.cjs && node scripts/patch-xterm-ligatures-font-cache.cjs && node scripts/patch-xterm-image-tile-stride.cjs && node scripts/patch-xterm-image-iip-type.cjs && electron-builder install-app-deps && node scripts/rebuildPatchedNodePty.cjs && node scripts/patch-xterm-webgl-atlas.cjs",
"rebuild": "electron-builder install-app-deps",
"tool:cli": "node electron/cli/netcatty-tool-cli.cjs",
"generate:capability-tools": "node scripts/generate-capability-tools.cjs",
@@ -97,6 +97,7 @@
"@withfig/autocomplete": "^2.692.3",
"ajv": "8.18.0",
"ajv-formats": "3.0.1",
"bidi-js": "1.0.3",
"css-tree": "^3.2.1",
"electron-updater": "^6.8.3",
"http-proxy-agent": "^7.0.2",
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env node
/* global console, process */
"use strict";
const fs = require("node:fs");
const path = require("node:path");
// xterm 6.1 beta applies a joined run's *total* width correction as
// letter-spacing, which Chromium can apply once per glyph. Joined cells are
// already sized in terminal columns; use that width instead of changing the
// text spacing (which can also interfere with contextual shaping).
const VERSION = "6.1.0-beta.292";
// Share the terminalBidiJoiner gate. Scope this fix to the new RTL
// shaping path; leave the existing ASCII font-ligature renderer unchanged.
const rtl = new RegExp(require("../lib/terminalRtlCharacter.json"), "u");
// Keep the outer span exactly on the grid. When wider fallback glyphs would
// extend into the next cell, compress the complete shaped text horizontally
// in an inner span. Keep the untouched text together for browser bidi/shaping,
// and avoid measuring DOM layout during rendering: xterm's existing spacing
// calculation already supplies the difference from the cached natural width.
const patches = [
{ file: "xterm.js", joined: "H", chars: "$", span: "w", width: "y*_", spacing: "k", rows: "m" },
{ file: "xterm.mjs", joined: "fi", chars: "_i", span: "I", width: "Rr*h", spacing: "Ot", rows: "p" },
].map(({ file, joined, chars, span, width, spacing, rows }) => {
const defaultSpacing = `${spacing}!==this.defaultSpacing&&(${span}.style.letterSpacing=\`\${${spacing}}px\`)`;
const original = `,${defaultSpacing},${rows}.push(${span}),`;
const replacement = [
`;if(${joined}&&${rtl}.test(${chars})){`,
`const allocated=${width};${span}.style.width=allocated+"px";${span}.style.letterSpacing="0px";`,
`if(${spacing}<0&&allocated>0){`,
'const run=this._document.createElement("span");',
`run.textContent=${span}.textContent;`,
'run.style.transformOrigin="left center";',
`run.style.transform="scaleX("+allocated/(allocated-${spacing})+")";`,
`${span}.replaceChildren(run);`,
`}}else{${defaultSpacing}}${rows}.push(${span}),`,
].join("");
return [file, original, replacement];
});
function patchJoinedWidth(source, original, replacement) {
if (source.split(replacement).length === 2 && !source.replace(replacement, "").includes(original)) return source;
if (source.split(original).length !== 2) throw new Error("unexpected xterm joined-width patch anchor");
return source.replace(original, replacement);
}
function patchInstalledXterm(root = process.cwd()) {
const base = path.resolve(root, "node_modules/@xterm/xterm");
const version = JSON.parse(fs.readFileSync(path.join(base, "package.json"), "utf8")).version;
if (version !== VERSION) throw new Error(`unsupported @xterm/xterm ${version}; expected ${VERSION}`);
const files = patches.map(([file, original, replacement]) => {
const filename = path.join(base, "lib", file);
const source = fs.readFileSync(filename, "utf8");
return [filename, source, patchJoinedWidth(source, original, replacement)];
});
for (const [filename, source, patched] of files) {
if (source !== patched) fs.writeFileSync(filename, patched);
}
if (files.some(([, source, patched]) => source !== patched)) {
fs.rmSync(path.resolve(root, "node_modules/.vite"), { recursive: true, force: true });
}
}
if (require.main === module) {
try { patchInstalledXterm(); }
catch (error) { console.error(error.message); process.exitCode = 1; }
}
module.exports = { patchInstalledXterm };
+85
View File
@@ -0,0 +1,85 @@
"use strict";
/* global process, __dirname, console */
if (!process.versions.electron) {
require("node:test")("RTL DOM cell geometry", { skip: "run with Electron" }, () => {});
} else {
const { app, BrowserWindow } = require("electron");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { buildSync } = require("esbuild");
const profile = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-rtl-width-"));
app.setPath("userData", profile);
app.on("window-all-closed", () => {});
const bundle = buildSync({
stdin: {
contents: 'export { Terminal } from "@xterm/xterm"; export { findRightToLeftRuns } from "./components/terminal/runtime/terminalBidiJoiner";',
resolveDir: path.resolve(__dirname, ".."),
},
bundle: true, format: "iife", globalName: "rtlTest", platform: "browser", write: false,
}).outputFiles[0].text;
let win;
function finish(code) {
win?.destroy();
app.exit(code);
}
void app.whenReady().then(async () => {
win = new BrowserWindow({ show: true, width: 600, height: 320 });
await win.loadURL("data:text/html,<div id='terminal' style='width:500px;height:260px'></div>");
await win.webContents.insertCSS(fs.readFileSync(require.resolve("@xterm/xterm/css/xterm.css"), "utf8"));
const measurement = await win.webContents.executeJavaScript(`(async () => {
${bundle}
const fontFamily = '"Noto Sans Mono", "DejaVu Sans", monospace';
const term = new rtlTest.Terminal({cols: 30, rows: 8, fontSize: 24, fontFamily, allowProposedApi: true});
term.open(document.querySelector("#terminal"));
term.registerCharacterJoiner(text => text.startsWith("ffi") ? [[0, 3]] : rtlTest.findRightToLeftRuns(text));
const a = "יייייייי", b = "שששששששש";
const ctx = document.createElement("canvas").getContext("2d");
ctx.font = "24px " + fontFamily;
await new Promise(resolve => term.write(a + " Z\\r\\n" + b + " Z\\r\\n01234567 Z\\r\\nffi Z\\r\\n", resolve));
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
const rows = [...document.querySelectorAll(".xterm-rows > div")].slice(0, 4);
const geometry = rows.map(row => {
const spans = [...row.children];
const suffix = spans.find(span => span.textContent.includes("Z"));
const content = spans[0].firstElementChild ?? spans[0];
const range = document.createRange();
range.selectNodeContents(content);
const glyphs = range.getBoundingClientRect();
const cellBox = spans[0].getBoundingClientRect();
return {
glyphWidth: glyphs.width,
glyphRight: glyphs.right - cellBox.left,
transform: content.style.transform,
marker: suffix.getBoundingClientRect().right - row.getBoundingClientRect().left,
joinedWidth: spans[0].getBoundingClientRect().width,
text: row.textContent,
first: spans[0].textContent,
widthStyle: spans[0].style.width,
overflow: spans[0].style.overflow,
};
});
return { geometry, cell: term._core._renderService.dimensions.css.cell.width, natural: [ctx.measureText(a).width, ctx.measureText(b).width] };
})()`);
console.log(JSON.stringify(measurement));
const [thin, wide, ascii, ligature] = measurement.geometry;
assert.equal(ligature.first, "ffi");
assert.equal(ligature.widthStyle, "", "ASCII ligatures must keep their existing layout");
assert.equal(ligature.overflow, "", "ASCII ligature overhang must not be clipped");
// Ensure the fixture actually exercises unequal font metrics rather than
// passing accidentally on a monospace/fallback-only test environment.
assert.ok(Math.abs(measurement.natural[0] - measurement.natural[1]) > 8);
assert.ok(measurement.natural[1] > measurement.cell * 8 + 8, "wide fallback must exceed its cell allocation");
assert.notEqual(wide.transform, "", "nominally oversized RTL glyphs must actually fit, not just clip");
assert.equal(wide.overflow, "", "RTL text must not be hidden by overflow clipping");
assert.ok(wide.glyphRight <= wide.joinedWidth + 1, JSON.stringify(measurement));
assert.equal(thin.transform, "", "narrow RTL text must not be unnecessarily rescaled");
for (const row of [thin, wide]) {
assert.match(row.text, / Z/);
assert.ok(Math.abs(row.joinedWidth - measurement.cell * 8) <= 1, JSON.stringify(measurement));
assert.ok(Math.abs(row.marker - ascii.marker) <= 1, JSON.stringify(measurement));
}
finish(0);
}).catch(error => { console.error(error); finish(1); });
}
+2 -1
View File
@@ -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.
+19
View File
@@ -0,0 +1,19 @@
declare module "bidi-js" {
interface BidiParagraph {
start: number;
end: number;
level: number;
}
interface BidiEmbeddingLevels {
levels: Uint8Array;
paragraphs: BidiParagraph[];
}
interface Bidi {
getBidiCharTypeName(char: string): string;
getEmbeddingLevels(text: string, baseDirection?: "ltr" | "rtl"): BidiEmbeddingLevels;
}
export default function bidiFactory(): Bidi;
}