mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-12-04 00:10:49 +00:00
Compare commits
23
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
57b8ac53e3 | ||
|
|
b0e11af042 | ||
|
|
1851ee39b9 | ||
|
|
a01e58ac77 | ||
|
|
2b766abe6b | ||
|
|
4b65002a78 | ||
|
|
520b434866 | ||
|
|
7cdb07e9ed | ||
|
|
1b15e9773f | ||
|
|
ac1f779323 | ||
|
|
9d579c10ff | ||
|
|
c3cd4850ab | ||
|
|
74a304952b | ||
|
|
db30429344 | ||
|
|
b9d58c2825 | ||
|
|
12a49604d1 | ||
|
|
a06ebcc467 | ||
|
|
4686a945fc | ||
|
|
4b05b03776 | ||
|
|
5d5c5b0940 | ||
|
|
549f58c653 | ||
|
|
3a913b8fc2 | ||
|
|
8cae6c5784 |
No files matched your search
@@ -1137,3 +1137,159 @@ test('executeHotkeyActionImpl reopenClosedTab calls reopenLastClosedTab and reco
|
||||
assert.equal(logs[1].username, 'dev');
|
||||
assert.equal(logs[1].protocol, 'local');
|
||||
});
|
||||
|
||||
for (const scheme of ['pc', 'mac'] as const) {
|
||||
test(`addSessionToWorkspace shortcut ${scheme}: opens append dialog and consumes event only when a workspace is active`, () => {
|
||||
const target = new FakeHTMLElement();
|
||||
|
||||
for (const scenario of [
|
||||
{ name: 'active workspace', activeTabId: 'workspace-1', expectConsume: true },
|
||||
{ name: 'standalone terminal', activeTabId: 'session-1', expectConsume: false },
|
||||
{ name: 'vault tab', activeTabId: 'vault', expectConsume: false },
|
||||
{ name: 'sftp tab', activeTabId: 'sftp', expectConsume: false },
|
||||
{ name: 'editor tab', activeTabId: 'editor:file-1', expectConsume: false },
|
||||
{ name: 'log view tab', activeTabId: 'log-1', expectConsume: false },
|
||||
{ name: 'plugin view tab', activeTabId: 'plugin-view:demo:main', expectConsume: false },
|
||||
]) {
|
||||
const dialogCalls: unknown[] = [];
|
||||
let prevented = 0;
|
||||
let stopped = 0;
|
||||
const event = {
|
||||
key: 'n',
|
||||
code: 'KeyN',
|
||||
ctrlKey: scheme === 'pc',
|
||||
metaKey: scheme === 'mac',
|
||||
altKey: false,
|
||||
shiftKey: false,
|
||||
target,
|
||||
composedPath: () => [target],
|
||||
preventDefault: () => { prevented += 1; },
|
||||
stopPropagation: () => { stopped += 1; },
|
||||
} as unknown as KeyboardEvent;
|
||||
|
||||
const actionCtx = {
|
||||
activeTabStore: { getActiveTabId: () => scenario.activeTabId },
|
||||
editorTabs: [{ id: 'file-1' }],
|
||||
orderedTabs: ['session-1', 'workspace-1'],
|
||||
sessions: [{ id: 'session-1' }, { id: 's-ws', workspaceId: 'workspace-1' }],
|
||||
settings: { showSftpTab: true, shellOnlyTabNumberShortcuts: false },
|
||||
setAddToWorkspaceDialog: (value: unknown) => { dialogCalls.push(value); },
|
||||
toEditorTabId: (id: string) => `editor:${id}`,
|
||||
workspaces: [{ id: 'workspace-1', title: 'Workspace 1' }],
|
||||
};
|
||||
|
||||
handleGlobalHotkeyKeyDownImpl(
|
||||
() => ({
|
||||
HOTKEY_DEBUG: false,
|
||||
closeTabKeyStr: '',
|
||||
hotkeyScheme: scheme,
|
||||
keyBindings: DEFAULT_KEY_BINDINGS,
|
||||
matchesKeyBinding,
|
||||
executeHotkeyAction: (action: string, ev: KeyboardEvent) =>
|
||||
executeHotkeyActionImpl(() => actionCtx, action, ev),
|
||||
}),
|
||||
event,
|
||||
);
|
||||
|
||||
assert.deepEqual(
|
||||
dialogCalls,
|
||||
scenario.expectConsume ? [{ mode: 'append', workspaceId: 'workspace-1' }] : [],
|
||||
`${scheme} / ${scenario.name}: dialog calls`,
|
||||
);
|
||||
assert.equal(
|
||||
prevented,
|
||||
scenario.expectConsume ? 1 : 0,
|
||||
`${scheme} / ${scenario.name}: preventDefault count`,
|
||||
);
|
||||
assert.equal(
|
||||
stopped,
|
||||
scenario.expectConsume ? 1 : 0,
|
||||
`${scheme} / ${scenario.name}: stopPropagation count`,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('addSessionToWorkspace shortcut stays out of form inputs and Monaco even while a workspace is active', () => {
|
||||
for (const [label, target] of [
|
||||
['input', new FakeInputHTMLElement()],
|
||||
['monaco', new FakeMonacoHTMLElement()],
|
||||
] as const) {
|
||||
const dialogCalls: unknown[] = [];
|
||||
let prevented = 0;
|
||||
let stopped = 0;
|
||||
const event = {
|
||||
key: 'n',
|
||||
code: 'KeyN',
|
||||
ctrlKey: true,
|
||||
metaKey: false,
|
||||
altKey: false,
|
||||
shiftKey: false,
|
||||
target,
|
||||
composedPath: () => [target],
|
||||
preventDefault: () => { prevented += 1; },
|
||||
stopPropagation: () => { stopped += 1; },
|
||||
} as unknown as KeyboardEvent;
|
||||
|
||||
handleGlobalHotkeyKeyDownImpl(
|
||||
() => ({
|
||||
HOTKEY_DEBUG: false,
|
||||
closeTabKeyStr: '',
|
||||
hotkeyScheme: 'pc',
|
||||
keyBindings: DEFAULT_KEY_BINDINGS,
|
||||
matchesKeyBinding,
|
||||
executeHotkeyAction: (action: string, ev: KeyboardEvent) =>
|
||||
executeHotkeyActionImpl(() => ({
|
||||
activeTabStore: { getActiveTabId: () => 'workspace-1' },
|
||||
editorTabs: [],
|
||||
orderedTabs: ['workspace-1'],
|
||||
sessions: [],
|
||||
settings: {},
|
||||
setAddToWorkspaceDialog: (value: unknown) => { dialogCalls.push(value); },
|
||||
toEditorTabId: (id: string) => `editor:${id}`,
|
||||
workspaces: [{ id: 'workspace-1', title: 'Workspace 1' }],
|
||||
}), action, ev),
|
||||
}),
|
||||
event,
|
||||
);
|
||||
|
||||
assert.deepEqual(dialogCalls, [], `${label} should not open workspace dialog`);
|
||||
assert.equal(prevented, 0, `${label} should not preventDefault`);
|
||||
assert.equal(stopped, 0, `${label} should not stopPropagation`);
|
||||
}
|
||||
});
|
||||
|
||||
test('executeHotkeyActionImpl addSessionToWorkspace returns boolean availability defensively', () => {
|
||||
const dialogCalls: unknown[] = [];
|
||||
const makeCtx = (overrides: Record<string, unknown> = {}) => ({
|
||||
activeTabStore: { getActiveTabId: () => 'workspace-1' },
|
||||
editorTabs: [],
|
||||
orderedTabs: [],
|
||||
sessions: [],
|
||||
settings: {},
|
||||
setAddToWorkspaceDialog: (value: unknown) => { dialogCalls.push(value); },
|
||||
toEditorTabId: (id: string) => `editor:${id}`,
|
||||
workspaces: [{ id: 'workspace-1', title: 'Workspace 1' }],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
assert.equal(
|
||||
executeHotkeyActionImpl(() => makeCtx({ workspaces: undefined }), 'addSessionToWorkspace', {} as KeyboardEvent),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
executeHotkeyActionImpl(() => makeCtx({ setAddToWorkspaceDialog: undefined }), 'addSessionToWorkspace', {} as KeyboardEvent),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
executeHotkeyActionImpl(() => makeCtx({ activeTabStore: { getActiveTabId: () => 'session-1' } }), 'addSessionToWorkspace', {} as KeyboardEvent),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(dialogCalls, []);
|
||||
|
||||
assert.equal(
|
||||
executeHotkeyActionImpl(() => makeCtx(), 'addSessionToWorkspace', {} as KeyboardEvent),
|
||||
true,
|
||||
);
|
||||
assert.deepEqual(dialogCalls, [{ mode: 'append', workspaceId: 'workspace-1' }]);
|
||||
});
|
||||
@@ -394,8 +394,13 @@ export function handleGlobalHotkeyKeyDownImpl(getCtx: AppContextGetter, e: Keybo
|
||||
|
||||
// An unavailable action must leave the chord to the terminal.
|
||||
// Broadcast keeps Ctrl/Cmd+B for tmux; the host list keeps Ctrl/Cmd+Shift+B
|
||||
// when the sidebar cannot show. Dispatch once before consuming it.
|
||||
if (binding.action === 'broadcast' || binding.action === 'toggleHostTree') {
|
||||
// when the sidebar cannot show; addSessionToWorkspace keeps Ctrl/Cmd+N
|
||||
// when no workspace tab is active. Dispatch once before consuming it.
|
||||
if (
|
||||
binding.action === 'broadcast'
|
||||
|| binding.action === 'toggleHostTree'
|
||||
|| binding.action === 'addSessionToWorkspace'
|
||||
) {
|
||||
if (executeHotkeyAction(binding.action, e) === true) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
@@ -1218,6 +1223,17 @@ export function executeHotkeyActionImpl(getCtx: AppContextGetter, action: string
|
||||
// button, but without having to open QS first.
|
||||
setAddToWorkspaceDialog({ mode: 'create' });
|
||||
break;
|
||||
case 'addSessionToWorkspace': {
|
||||
// Open the same append-mode picker the workspace tab context menu
|
||||
// uses, targeting the currently active workspace. A standalone tab
|
||||
// (or vault/settings) has no workspace to append into, so return false
|
||||
// to leave the chord for the active surface or terminal.
|
||||
const currentId = activeTabStore.getActiveTabId();
|
||||
const activeWs = (workspaces ?? []).find((w) => w.id === currentId);
|
||||
if (!activeWs || typeof setAddToWorkspaceDialog !== 'function') return false;
|
||||
setAddToWorkspaceDialog({ mode: 'append', workspaceId: activeWs.id });
|
||||
return true;
|
||||
}
|
||||
case 'portForwarding':
|
||||
// Navigate to vault and open port forwarding section
|
||||
setActiveTabId('vault');
|
||||
|
||||
@@ -1847,6 +1847,7 @@ export function AppSideEffects() {
|
||||
hostname: result.target.hostname,
|
||||
port: result.target.port,
|
||||
username: result.target.username || undefined,
|
||||
...(result.target.password ? { password: result.target.password } : {}),
|
||||
domain: result.target.domain || undefined,
|
||||
label: result.target.label,
|
||||
rdpContent: result.target.rawRdpFileContent,
|
||||
|
||||
@@ -572,6 +572,7 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
onEditHost={handleEditHostFromOverlay}
|
||||
onRenameWorkspace={startWorkspaceRename}
|
||||
onCopyWorkspace={copyWorkspaceWithCurrentShell}
|
||||
onRequestAddToWorkspace={handleRequestAddToWorkspace}
|
||||
onCloseWorkspace={closeWorkspace}
|
||||
onCloseLogView={closeLogView}
|
||||
onCloseTabsBatch={closeTabsBatch}
|
||||
|
||||
@@ -688,6 +688,15 @@ export const enAiMessages: Messages = {
|
||||
'ai.chatHistory.messageCap': 'Messages kept per chat',
|
||||
'ai.chatHistory.messageCap.description': 'Maximum number of messages stored per chat (50–2000). Lowering it drops the oldest messages from storage on the next write. Larger values increase storage and cloud-sync size.',
|
||||
'ai.chatHistory.messageCap.unit': 'messages',
|
||||
'ai.chatHistory.autoLlmTitle': 'Auto-generate chat titles',
|
||||
'ai.chatHistory.autoLlmTitle.description': 'Use a small one-shot LLM call to write a short title after the first message. Falls back to the first line if unavailable. Local setting only.',
|
||||
'ai.chatHistory.titleModel': 'Title model',
|
||||
'ai.chatHistory.titleModel.description': 'Provider and model used to generate chat titles. Pick a small, cheap model. Defaults to the current Catty model.',
|
||||
'ai.chatHistory.titleModel.none': 'No enabled provider available.',
|
||||
'ai.chatHistory.titleModel.useCurrentCatty': 'Use current Catty model',
|
||||
'ai.chatHistory.titleModel.unavailable': 'Unavailable',
|
||||
'ai.chatHistory.titleModel.providerPlaceholder': 'Select provider',
|
||||
'ai.chatHistory.titleModel.modelPlaceholder': 'Select model',
|
||||
|
||||
// AI Error
|
||||
'ai.codex.bridgeError': 'Codex main-process handlers are not loaded yet. Fully restart Netcatty, or restart the Electron dev process, then try again.',
|
||||
|
||||
@@ -431,6 +431,8 @@ export const enCoreMessages: Messages = {
|
||||
'settings.vault.showSftpTab': 'Show SFTP tab',
|
||||
'settings.vault.showSftpTabDesc': 'Display the standalone SFTP view in the top tab bar. When hidden, use the in-session SFTP side panel instead.',
|
||||
'settings.vault.showHostTreeSidebar': 'Show host list sidebar',
|
||||
'settings.vault.removeTopTabsDragArea': 'Remove the top window-drag area',
|
||||
'settings.vault.removeTopTabsDragAreaDesc': 'When enabled, remove the draggable space above the tabs so the top edge is available for clicks.',
|
||||
'settings.vault.showHostTreeSidebarDesc': 'Display the host list sidebar and its top-bar toggle on terminal and editor tabs.',
|
||||
'settings.vault.autoImportSystemKnownHosts': 'Auto-import system known_hosts',
|
||||
'settings.vault.autoImportSystemKnownHostsDesc': 'When Vault loads, silently import entries from the OpenSSH known_hosts file. Turn this off to keep Netcatty known hosts separate; Scan System still imports on demand.',
|
||||
@@ -1061,6 +1063,7 @@ Highlight the focused split pane:
|
||||
'settings.shortcuts.binding.command-palette': 'Open Command Palette',
|
||||
'settings.shortcuts.binding.quick-switch': 'Quick Switch',
|
||||
'settings.shortcuts.binding.new-workspace': 'New Workspace',
|
||||
'settings.shortcuts.binding.add-session-to-workspace': 'Add Session to Workspace',
|
||||
'settings.shortcuts.binding.snippets': 'Open Snippets',
|
||||
'settings.shortcuts.binding.broadcast': 'Switch the Broadcast Mode',
|
||||
'settings.shortcuts.binding.toggle-side-panel': 'Toggle Side Panel',
|
||||
@@ -1330,6 +1333,8 @@ Highlight the focused split pane:
|
||||
"plugins.sidebar.selectTerminal": "Select an open terminal first.",
|
||||
"plugins.sidebar.loading": "Loading extension page…",
|
||||
"plugins.vault.loading": "Loading plugin page…",
|
||||
"plugins.vault.viewError": "The plugin page failed to render.",
|
||||
"plugins.vault.retry": "Retry",
|
||||
"plugins.interaction.title": "Plugin request",
|
||||
"plugins.interaction.openUrlTitle": "Open external link?",
|
||||
"plugins.interaction.openUrlNote": "This plugin wants to open the following HTTPS URL in your default browser:",
|
||||
|
||||
@@ -16,6 +16,7 @@ export const enTerminalMessages: Messages = {
|
||||
'terminal.directory.cmdIntegrationUnavailable': 'Waiting for a directory report from the original Command Prompt session.',
|
||||
'terminal.directory.gitBashIntegrationUnavailable': 'Waiting for an accessible directory from the original Git Bash session.',
|
||||
'terminal.directory.wslIntegrationUnavailable': 'Waiting for an idle Bash session in the selected WSL distribution.',
|
||||
'terminal.directory.cygwinIntegrationUnavailable': 'Waiting for Cygwin Bash to return to an idle prompt.',
|
||||
'terminal.directory.nonFilesystem': 'The current PowerShell location is not a filesystem directory.',
|
||||
'terminal.directory.busy': 'Wait for an empty shell prompt.',
|
||||
'terminal.directory.readFailed': 'Could not read this directory. Try refreshing.',
|
||||
@@ -619,6 +620,10 @@ export const enTerminalMessages: Messages = {
|
||||
'keychain.export.scriptPlaceholder': 'Export script...',
|
||||
'keychain.export.missingCredentials':
|
||||
'Host has no saved password or key. Please add password credentials to the host first.',
|
||||
'keychain.export.missingPublicKey':
|
||||
'This key has no public key. Open Edit, paste the public key, then try Export and Attach again.',
|
||||
'keychain.export.missingPublicKeyNote':
|
||||
'This key has no public key. Paste it in the key editor before exporting.',
|
||||
'keychain.export.successTitle': 'Export Successful',
|
||||
'keychain.export.successMessage': 'Public key exported and attached to {host}',
|
||||
'keychain.export.failedTitle': 'Export Failed',
|
||||
@@ -695,6 +700,7 @@ export const enTerminalMessages: Messages = {
|
||||
'tabs.logPrefix': 'Log:',
|
||||
'tabs.logLocal': 'Local',
|
||||
'tabs.copyTab': 'Copy Tab',
|
||||
'tabs.addSessionToWorkspace': 'Add Session to Workspace',
|
||||
'tabs.duplicateSession': 'Duplicate Session',
|
||||
'tabs.copyTabToNewWindow': 'Copy Tab to New Window',
|
||||
'tabs.copyTabToNewWindowFailed': 'Failed to open tab in a new window',
|
||||
|
||||
@@ -688,6 +688,15 @@ export const esAiMessages: Messages = {
|
||||
'ai.chatHistory.messageCap': 'Mensajes conservados por chat',
|
||||
'ai.chatHistory.messageCap.description': 'Número máximo de mensajes almacenados por chat (50–2000). Al reducirlo, los mensajes más antiguos se descartan del almacenamiento en la siguiente escritura. Los valores más altos aumentan el almacenamiento y el tamaño de la sincronización en la nube.',
|
||||
'ai.chatHistory.messageCap.unit': 'mensajes',
|
||||
'ai.chatHistory.autoLlmTitle': 'Generar títulos automáticamente',
|
||||
'ai.chatHistory.autoLlmTitle.description': 'Usa una breve llamada LLM para crear un título corto tras el primer mensaje. Si no está disponible, usa la primera línea. Ajuste solo local.',
|
||||
'ai.chatHistory.titleModel': 'Modelo de título',
|
||||
'ai.chatHistory.titleModel.description': 'Proveedor y modelo usados para generar títulos. Elige un modelo pequeño y económico. Por defecto usa el modelo actual de Catty.',
|
||||
'ai.chatHistory.titleModel.none': 'No hay proveedores habilitados.',
|
||||
'ai.chatHistory.titleModel.useCurrentCatty': 'Usar el modelo actual de Catty',
|
||||
'ai.chatHistory.titleModel.unavailable': 'No disponible',
|
||||
'ai.chatHistory.titleModel.providerPlaceholder': 'Seleccionar proveedor',
|
||||
'ai.chatHistory.titleModel.modelPlaceholder': 'Seleccionar modelo',
|
||||
|
||||
// AI Error
|
||||
'ai.codex.bridgeError': 'Los controladores del proceso principal de Codex aún no están cargados. Reinicia Netcatty por completo o reinicia el proceso de desarrollo de Electron y vuelve a intentarlo.',
|
||||
|
||||
@@ -431,6 +431,8 @@ export const esCoreMessages: Messages = {
|
||||
'settings.vault.showSftpTab': 'Mostrar pestaña SFTP',
|
||||
'settings.vault.showSftpTabDesc': 'Muestra la vista SFTP independiente en la barra de pestañas superior. Cuando está oculta, usa el panel lateral SFTP dentro de la sesión.',
|
||||
'settings.vault.showHostTreeSidebar': 'Mostrar barra lateral de lista de hosts',
|
||||
'settings.vault.removeTopTabsDragArea': 'Quitar el área superior para arrastrar la ventana',
|
||||
'settings.vault.removeTopTabsDragAreaDesc': 'Al activarla, quita el espacio de arrastre sobre las pestañas para poder hacer clic en el borde superior.',
|
||||
'settings.vault.showHostTreeSidebarDesc': 'Muestra la barra lateral de lista de hosts y su alternador en la barra superior en las pestañas de terminal y editor.',
|
||||
'settings.vault.autoImportSystemKnownHosts': 'Importar automáticamente known_hosts del sistema',
|
||||
'settings.vault.autoImportSystemKnownHostsDesc': 'Cuando se carga el Vault, importa en silencio las entradas del archivo known_hosts de OpenSSH. Desactívalo para mantener los hosts conocidos de Netcatty separados; Escanear sistema sigue importando a pedido.',
|
||||
@@ -1062,6 +1064,7 @@ Resalta el panel dividido enfocado:
|
||||
'settings.shortcuts.binding.command-palette': 'Abrir paleta de comandos',
|
||||
'settings.shortcuts.binding.quick-switch': 'Cambio rápido',
|
||||
'settings.shortcuts.binding.new-workspace': 'Nuevo espacio de trabajo',
|
||||
'settings.shortcuts.binding.add-session-to-workspace': 'Añadir sesión al espacio de trabajo',
|
||||
'settings.shortcuts.binding.snippets': 'Abrir fragmentos',
|
||||
'settings.shortcuts.binding.broadcast': 'Alternar modo de transmisión',
|
||||
'settings.shortcuts.binding.toggle-opacity': 'Alternar la transparencia de la ventana',
|
||||
@@ -1330,6 +1333,8 @@ Resalta el panel dividido enfocado:
|
||||
"plugins.sidebar.selectTerminal": "Selecciona primero un terminal abierto.",
|
||||
"plugins.sidebar.loading": "Cargando página de extensión…",
|
||||
"plugins.vault.loading": "Cargando página del plugin…",
|
||||
"plugins.vault.viewError": "No se pudo renderizar la página del plugin.",
|
||||
"plugins.vault.retry": "Reintentar",
|
||||
"plugins.interaction.title": "Solicitud de complemento",
|
||||
"plugins.interaction.openUrlTitle": "¿Abrir enlace externo?",
|
||||
"plugins.interaction.openUrlNote": "Este complemento solicita abrir la siguiente URL HTTPS en tu navegador predeterminado:",
|
||||
|
||||
@@ -16,6 +16,7 @@ export const esTerminalMessages: Messages = {
|
||||
'terminal.directory.cmdIntegrationUnavailable': 'Esperando el directorio de la sesión original del símbolo del sistema.',
|
||||
'terminal.directory.gitBashIntegrationUnavailable': 'Esperando un directorio accesible de la sesión original de Git Bash.',
|
||||
'terminal.directory.wslIntegrationUnavailable': 'Esperando una sesión de Bash inactiva en la distribución WSL seleccionada.',
|
||||
'terminal.directory.cygwinIntegrationUnavailable': 'Esperando que Bash de Cygwin vuelva a un indicador inactivo.',
|
||||
'terminal.directory.nonFilesystem': 'La ubicación actual de PowerShell no es un directorio del sistema de archivos.',
|
||||
'terminal.directory.accessDenied': 'Permiso denegado al listar este directorio.',
|
||||
'terminal.directory.busy': 'Espera a que el prompt esté vacío.',
|
||||
@@ -619,6 +620,10 @@ export const esTerminalMessages: Messages = {
|
||||
'keychain.export.scriptPlaceholder': 'Script de exportación...',
|
||||
'keychain.export.missingCredentials':
|
||||
'El host no tiene contraseña ni clave guardadas. Primero agrega credenciales de contraseña al host.',
|
||||
'keychain.export.missingPublicKey':
|
||||
'Esta clave no tiene clave pública. Ábrela en Editar, pega la clave pública y vuelve a intentar Exportar y adjuntar.',
|
||||
'keychain.export.missingPublicKeyNote':
|
||||
'Esta clave no tiene clave pública. Pégala en el editor de claves antes de exportar.',
|
||||
'keychain.export.successTitle': 'Exportación exitosa',
|
||||
'keychain.export.successMessage': 'Clave pública exportada y adjuntada a {host}',
|
||||
'keychain.export.failedTitle': 'Falló la exportación',
|
||||
@@ -697,6 +702,7 @@ export const esTerminalMessages: Messages = {
|
||||
'tabs.logPrefix': 'Registro:',
|
||||
'tabs.logLocal': 'Local',
|
||||
'tabs.copyTab': 'Copiar pestaña',
|
||||
'tabs.addSessionToWorkspace': 'Añadir sesión al espacio de trabajo',
|
||||
'tabs.duplicateSession': 'Duplicar sesión',
|
||||
'tabs.copyTabToNewWindow': 'Copiar pestaña a una nueva ventana',
|
||||
'tabs.copyTabToNewWindowFailed': 'No se pudo abrir la pestaña en una nueva ventana',
|
||||
|
||||
@@ -228,3 +228,25 @@ test("AI tool output limit settings copy is localized across all five locales",
|
||||
assert.match(zhTW["ai.safety.toolOutputMaxChars.description"], /傳回/);
|
||||
assert.equal(zhTW["ai.safety.toolOutputMaxChars.description"].includes("返回"), false);
|
||||
});
|
||||
|
||||
test("LLM chat title settings copy is localized across all five locales", () => {
|
||||
const keys = [
|
||||
"ai.chatHistory.autoLlmTitle",
|
||||
"ai.chatHistory.autoLlmTitle.description",
|
||||
"ai.chatHistory.titleModel",
|
||||
"ai.chatHistory.titleModel.description",
|
||||
"ai.chatHistory.titleModel.none",
|
||||
"ai.chatHistory.titleModel.useCurrentCatty",
|
||||
"ai.chatHistory.titleModel.unavailable",
|
||||
"ai.chatHistory.titleModel.providerPlaceholder",
|
||||
"ai.chatHistory.titleModel.modelPlaceholder",
|
||||
] as const;
|
||||
for (const [locale, messages] of Object.entries(ALL_LOCALES)) {
|
||||
for (const key of keys) {
|
||||
assert.ok(messages[key]?.trim(), `${locale}: missing ${key}`);
|
||||
if (locale !== "en") {
|
||||
assert.notEqual(messages[key], en[key], `${locale}: ${key} should be translated`);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -687,6 +687,15 @@ export const ruAiMessages: Messages = {
|
||||
'ai.chatHistory.messageCap': 'Сообщений, сохраняемых в чате',
|
||||
'ai.chatHistory.messageCap.description': 'Максимальное число сообщений, хранимых для одного чата (50–2000). При уменьшении самые старые сообщения удаляются из хранилища при следующей записи. Большие значения увеличивают объём хранилища и синхронизации с облаком.',
|
||||
'ai.chatHistory.messageCap.unit': 'сообщений',
|
||||
'ai.chatHistory.autoLlmTitle': 'Автосоздание заголовков чатов',
|
||||
'ai.chatHistory.autoLlmTitle.description': 'Короткий запрос к LLM создаёт заголовок после первого сообщения. Если недоступно, используется первая строка. Локальная настройка.',
|
||||
'ai.chatHistory.titleModel': 'Модель для заголовков',
|
||||
'ai.chatHistory.titleModel.description': 'Провайдер и модель для создания заголовков. Выберите небольшую недорогую модель. По умолчанию — текущая модель Catty.',
|
||||
'ai.chatHistory.titleModel.none': 'Нет включённых провайдеров.',
|
||||
'ai.chatHistory.titleModel.useCurrentCatty': 'Использовать текущую модель Catty',
|
||||
'ai.chatHistory.titleModel.unavailable': 'Недоступно',
|
||||
'ai.chatHistory.titleModel.providerPlaceholder': 'Выбрать провайдер',
|
||||
'ai.chatHistory.titleModel.modelPlaceholder': 'Выбрать модель',
|
||||
|
||||
// AI Error
|
||||
'ai.codex.bridgeError': 'Обработчики главного процесса Codex ещё не загружены. Полностью перезапустите Netcatty или dev-процесс Electron и попробуйте снова.',
|
||||
|
||||
@@ -430,6 +430,8 @@ export const ruCoreMessages: Messages = {
|
||||
'settings.vault.showSftpTab': 'Показывать вкладку SFTP',
|
||||
'settings.vault.showSftpTabDesc': 'Показывать отдельный SFTP-вид в верхней панели вкладок. Если скрыто, используйте боковую панель SFTP внутри сессии.',
|
||||
'settings.vault.showHostTreeSidebar': 'Показывать боковую панель хостов',
|
||||
'settings.vault.removeTopTabsDragArea': 'Убрать верхнюю область перетаскивания окна',
|
||||
'settings.vault.removeTopTabsDragAreaDesc': 'При включении удаляется область перетаскивания над вкладками, чтобы по верхнему краю можно было нажимать.',
|
||||
'settings.vault.showHostTreeSidebarDesc': 'Показывать список хостов и кнопку в верхней панели для вкладок терминала и редактора.',
|
||||
'settings.vault.autoImportSystemKnownHosts': 'Автоимпорт системного known_hosts',
|
||||
'settings.vault.autoImportSystemKnownHostsDesc': 'При открытии хранилища тихо импортировать записи из OpenSSH known_hosts. Отключите, чтобы держать известные хосты Netcatty отдельно; кнопка «Сканировать систему» по-прежнему импортирует вручную.',
|
||||
@@ -1046,6 +1048,7 @@ export const ruCoreMessages: Messages = {
|
||||
'settings.shortcuts.binding.command-palette': 'Открыть палитру команд',
|
||||
'settings.shortcuts.binding.quick-switch': 'Быстрое переключение',
|
||||
'settings.shortcuts.binding.new-workspace': 'Новая рабочая область',
|
||||
'settings.shortcuts.binding.add-session-to-workspace': 'Добавить сессию в рабочую область',
|
||||
'settings.shortcuts.binding.snippets': 'Открыть сниппеты',
|
||||
'settings.shortcuts.binding.broadcast': 'Переключить режим трансляции',
|
||||
'settings.shortcuts.binding.toggle-opacity': 'Переключить прозрачность окна',
|
||||
@@ -1271,6 +1274,8 @@ export const ruCoreMessages: Messages = {
|
||||
"plugins.sidebar.selectTerminal": "Сначала выберите открытый терминал.",
|
||||
"plugins.sidebar.loading": "Загрузка страницы расширения…",
|
||||
"plugins.vault.loading": "Загрузка страницы плагина…",
|
||||
"plugins.vault.viewError": "Не удалось отобразить страницу плагина.",
|
||||
"plugins.vault.retry": "Повторить",
|
||||
"plugins.interaction.title": "Запрос плагина",
|
||||
"plugins.interaction.openUrlTitle": "Открыть внешнюю ссылку?",
|
||||
"plugins.interaction.openUrlNote": "Этот плагин запрашивает открытие следующего HTTPS-адреса в браузере по умолчанию:",
|
||||
|
||||
@@ -16,6 +16,7 @@ export const ruTerminalMessages: Messages = {
|
||||
'terminal.directory.cmdIntegrationUnavailable': 'Ожидание данных о каталоге от исходного сеанса командной строки.',
|
||||
'terminal.directory.gitBashIntegrationUnavailable': 'Ожидание доступного каталога исходного сеанса Git Bash.',
|
||||
'terminal.directory.wslIntegrationUnavailable': 'Ожидание готовности Bash в выбранном дистрибутиве WSL.',
|
||||
'terminal.directory.cygwinIntegrationUnavailable': 'Ожидание готовности Bash в Cygwin.',
|
||||
'terminal.directory.nonFilesystem': 'Текущее расположение PowerShell не является каталогом файловой системы.',
|
||||
'terminal.directory.accessDenied': 'Нет разрешения на просмотр содержимого этого каталога.',
|
||||
'terminal.directory.busy': 'Дождитесь пустой командной строки.',
|
||||
@@ -636,6 +637,8 @@ export const ruTerminalMessages: Messages = {
|
||||
'keychain.export.script': 'Скрипт *',
|
||||
'keychain.export.scriptPlaceholder': 'Скрипт экспорта...',
|
||||
'keychain.export.missingCredentials': 'У хоста нет сохранённого пароля или ключа. Сначала добавьте в хост учётные данные с паролем.',
|
||||
'keychain.export.missingPublicKey': 'У этого ключа нет публичного ключа. Откройте «Редактировать», вставьте публичный ключ и снова нажмите «Экспортировать и привязать».',
|
||||
'keychain.export.missingPublicKeyNote': 'У этого ключа нет публичного ключа. Вставьте его в редакторе ключа перед экспортом.',
|
||||
'keychain.export.successTitle': 'Экспорт выполнен успешно',
|
||||
'keychain.export.successMessage': 'Публичный ключ экспортирован и привязан к {host}',
|
||||
'keychain.export.failedTitle': 'Ошибка экспорта',
|
||||
@@ -712,6 +715,7 @@ export const ruTerminalMessages: Messages = {
|
||||
'tabs.logPrefix': 'Журнал:',
|
||||
'tabs.logLocal': 'Локальный',
|
||||
'tabs.copyTab': 'Копировать вкладку',
|
||||
'tabs.addSessionToWorkspace': 'Добавить сессию в эту рабочую область',
|
||||
'tabs.duplicateSession': 'Дублировать сессию',
|
||||
'tabs.copyTabToNewWindow': 'Копировать вкладку в новое окно',
|
||||
'tabs.copyTabToNewWindowFailed': 'Не удалось открыть вкладку в новом окне',
|
||||
|
||||
@@ -688,6 +688,15 @@ export const zhCNAiMessages: Messages = {
|
||||
'ai.chatHistory.messageCap': '每个会话保留的消息数',
|
||||
'ai.chatHistory.messageCap.description': '每个会话最多存储的消息条数(50–2000)。调低后会在下一次写入时从存储中丢弃最旧的消息。数值越大,存储占用和云同步体积也越大。',
|
||||
'ai.chatHistory.messageCap.unit': '条消息',
|
||||
'ai.chatHistory.autoLlmTitle': '自动生成会话标题',
|
||||
'ai.chatHistory.autoLlmTitle.description': '首条消息后用一次轻量 LLM 调用生成简短标题;不可用时回退为首句。仅本机生效。',
|
||||
'ai.chatHistory.titleModel': '标题模型',
|
||||
'ai.chatHistory.titleModel.description': '用于生成会话标题的 provider 和模型,建议选小巧便宜的模型。默认使用当前 Catty 模型。',
|
||||
'ai.chatHistory.titleModel.none': '没有可用的 provider。',
|
||||
'ai.chatHistory.titleModel.useCurrentCatty': '使用当前 Catty 模型',
|
||||
'ai.chatHistory.titleModel.unavailable': '不可用',
|
||||
'ai.chatHistory.titleModel.providerPlaceholder': '选择 provider',
|
||||
'ai.chatHistory.titleModel.modelPlaceholder': '选择模型',
|
||||
|
||||
// AI Error
|
||||
'ai.codex.bridgeError': 'Codex 主进程处理器尚未加载。请完全重启 Netcatty 或重启 Electron 开发进程,然后重试。',
|
||||
|
||||
@@ -438,6 +438,8 @@ export const zhCNCoreMessages: Messages = {
|
||||
'settings.vault.showSftpTab': '显示 SFTP 标签页',
|
||||
'settings.vault.showSftpTabDesc': '在顶部标签栏显示独立的 SFTP 视图。关闭后可改用会话内左侧的 SFTP 侧栏。',
|
||||
'settings.vault.showHostTreeSidebar': '显示主机列表侧栏',
|
||||
'settings.vault.removeTopTabsDragArea': '移除顶部窗口拖动区域',
|
||||
'settings.vault.removeTopTabsDragAreaDesc': '开启后移除标签页上方的拖动空白区域,让顶部可用于点击标签页和窗口按钮。',
|
||||
'settings.vault.showHostTreeSidebarDesc': '在终端和编辑器标签页显示主机列表侧栏及顶部开关。',
|
||||
'settings.vault.autoImportSystemKnownHosts': '自动导入系统 known_hosts',
|
||||
'settings.vault.autoImportSystemKnownHostsDesc': '打开主机库时静默导入 OpenSSH known_hosts 中的记录。关闭后,Netcatty 已知主机与系统信任库保持独立;仍可通过「扫描系统」手动导入。',
|
||||
@@ -1247,6 +1249,8 @@ Vaults 标签保持扁平,不使用这块背景。
|
||||
"plugins.sidebar.selectTerminal": "请先选择已打开的终端。",
|
||||
"plugins.sidebar.loading": "正在加载扩展页面…",
|
||||
"plugins.vault.loading": "正在加载插件页面…",
|
||||
"plugins.vault.viewError": "插件页面渲染失败。",
|
||||
"plugins.vault.retry": "重试",
|
||||
"plugins.interaction.title": "插件请求",
|
||||
"plugins.interaction.openUrlTitle": "打开外部链接?",
|
||||
"plugins.interaction.openUrlNote": "此插件请求在默认浏览器中打开以下 HTTPS 链接:",
|
||||
|
||||
@@ -16,6 +16,7 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'terminal.directory.cmdIntegrationUnavailable': '正在等待原 CMD 会话报告当前目录。',
|
||||
'terminal.directory.gitBashIntegrationUnavailable': '正在等待原 Git Bash 会话中的可访问目录。',
|
||||
'terminal.directory.wslIntegrationUnavailable': '正在等待所选 WSL 发行版中的 Bash 返回空闲提示符。',
|
||||
'terminal.directory.cygwinIntegrationUnavailable': '正在等待 Cygwin Bash 返回空闲提示符。',
|
||||
'terminal.directory.nonFilesystem': '当前 PowerShell 位置不是文件系统目录。',
|
||||
'terminal.directory.accessDenied': '没有权限列出此目录。',
|
||||
'terminal.directory.busy': '请等待终端回到空命令提示符。',
|
||||
@@ -630,6 +631,7 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'settings.shortcuts.binding.command-palette': '打开命令面板',
|
||||
'settings.shortcuts.binding.quick-switch': '快速切换',
|
||||
'settings.shortcuts.binding.new-workspace': '新建工作区',
|
||||
'settings.shortcuts.binding.add-session-to-workspace': '添加会话到工作区',
|
||||
'settings.shortcuts.binding.snippets': '打开代码片段',
|
||||
'settings.shortcuts.binding.broadcast': '切换广播模式',
|
||||
'settings.shortcuts.binding.toggle-opacity': '切换窗口透明度',
|
||||
@@ -719,6 +721,8 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'keychain.export.script': '脚本 *',
|
||||
'keychain.export.scriptPlaceholder': '导出脚本...',
|
||||
'keychain.export.missingCredentials': '主机未保存密码或密钥。请先为该主机添加密码凭据。',
|
||||
'keychain.export.missingPublicKey': '此密钥没有公钥。请先在编辑页粘贴公钥,然后再试「导出并绑定」。',
|
||||
'keychain.export.missingPublicKeyNote': '此密钥没有公钥。请先在密钥编辑页粘贴公钥,然后再导出。',
|
||||
'keychain.export.successTitle': '导出成功',
|
||||
'keychain.export.successMessage': '已导出公钥并绑定到 {host}',
|
||||
'keychain.export.failedTitle': '导出失败',
|
||||
@@ -795,6 +799,7 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'tabs.logPrefix': '日志:',
|
||||
'tabs.logLocal': '本地',
|
||||
'tabs.copyTab': '复制标签页',
|
||||
'tabs.addSessionToWorkspace': '在此工作区添加会话',
|
||||
'tabs.duplicateSession': '复制会话',
|
||||
'tabs.copyTabToNewWindow': '复制标签页到新窗口',
|
||||
'tabs.copyTabToNewWindowFailed': '无法在新窗口打开标签页',
|
||||
|
||||
@@ -687,6 +687,15 @@ export const zhTWAiMessages: Messages = {
|
||||
'ai.chatHistory.messageCap': '每個會話保留的訊息數',
|
||||
'ai.chatHistory.messageCap.description': '每個會話最多儲存的訊息數(50–2000)。調低後會在下一次寫入時從儲存中捨棄最舊的訊息。數值越大,儲存空間與雲端同步體積也越大。',
|
||||
'ai.chatHistory.messageCap.unit': '則訊息',
|
||||
'ai.chatHistory.autoLlmTitle': '自動產生工作階段標題',
|
||||
'ai.chatHistory.autoLlmTitle.description': '首則訊息後以一次輕量 LLM 呼叫產生簡短標題;不可用時退回首行。僅本機生效。',
|
||||
'ai.chatHistory.titleModel': '標題模型',
|
||||
'ai.chatHistory.titleModel.description': '用於產生工作階段標題的 provider 與模型,建議選擇輕巧便宜的模型。預設使用目前的 Catty 模型。',
|
||||
'ai.chatHistory.titleModel.none': '沒有可用的 provider。',
|
||||
'ai.chatHistory.titleModel.useCurrentCatty': '使用目前的 Catty 模型',
|
||||
'ai.chatHistory.titleModel.unavailable': '無法使用',
|
||||
'ai.chatHistory.titleModel.providerPlaceholder': '選擇 provider',
|
||||
'ai.chatHistory.titleModel.modelPlaceholder': '選擇模型',
|
||||
|
||||
// AI Error
|
||||
'ai.codex.bridgeError': 'Codex 主行程處理器尚未載入。請完全重新啟動 Netcatty 或重新啟動 Electron 開發行程,然後重試。',
|
||||
|
||||
@@ -438,6 +438,8 @@ export const zhTWCoreMessages: Messages = {
|
||||
'settings.vault.showSftpTab': '顯示 SFTP 分頁',
|
||||
'settings.vault.showSftpTabDesc': '在頂部分頁列顯示獨立的 SFTP 檢視。關閉後可改用工作階段內左側的 SFTP 側欄。',
|
||||
'settings.vault.showHostTreeSidebar': '顯示主機列表側欄',
|
||||
'settings.vault.removeTopTabsDragArea': '移除頂部視窗拖曳區域',
|
||||
'settings.vault.removeTopTabsDragAreaDesc': '開啟後移除分頁上方的拖曳空白區域,讓頂部可供點擊分頁與視窗按鈕。',
|
||||
'settings.vault.showHostTreeSidebarDesc': '在終端和編輯器分頁顯示主機列表側欄及頂部開關。',
|
||||
'settings.vault.autoImportSystemKnownHosts': '自動匯入系統 known_hosts',
|
||||
'settings.vault.autoImportSystemKnownHostsDesc': '開啟主機庫時靜默匯入 OpenSSH known_hosts 中的記錄。關閉後,Netcatty 已知主機與系統信任庫保持獨立;仍可透過「掃描系統」手動匯入。',
|
||||
@@ -1248,6 +1250,8 @@ Vaults 分頁維持扁平,不使用這塊背景。
|
||||
"plugins.sidebar.selectTerminal": "請先選擇已開啟的終端。",
|
||||
"plugins.sidebar.loading": "正在載入擴充功能頁面…",
|
||||
"plugins.vault.loading": "正在載入擴充功能頁面…",
|
||||
"plugins.vault.viewError": "擴充功能頁面無法顯示。",
|
||||
"plugins.vault.retry": "重試",
|
||||
"plugins.interaction.title": "外掛請求",
|
||||
"plugins.interaction.openUrlTitle": "開啟外部連結?",
|
||||
"plugins.interaction.openUrlNote": "此外掛請求在預設瀏覽器中開啟以下 HTTPS 連結:",
|
||||
|
||||
@@ -16,6 +16,7 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'terminal.directory.cmdIntegrationUnavailable': '正在等待原 CMD 工作階段回報目前目錄。',
|
||||
'terminal.directory.gitBashIntegrationUnavailable': '正在等待原 Git Bash 工作階段中的可存取目錄。',
|
||||
'terminal.directory.wslIntegrationUnavailable': '正在等待所選 WSL 發行版本中的 Bash 返回閒置提示字元。',
|
||||
'terminal.directory.cygwinIntegrationUnavailable': '正在等待 Cygwin Bash 返回閒置提示字元。',
|
||||
'terminal.directory.nonFilesystem': '目前 PowerShell 位置不是檔案系統目錄。',
|
||||
'terminal.directory.accessDenied': '沒有權限列出此目錄。',
|
||||
'terminal.directory.busy': '請等待終端回到空白命令提示字元。',
|
||||
@@ -630,6 +631,7 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'settings.shortcuts.binding.command-palette': '開啟指令面板',
|
||||
'settings.shortcuts.binding.quick-switch': '快速切換',
|
||||
'settings.shortcuts.binding.new-workspace': '新增工作區',
|
||||
'settings.shortcuts.binding.add-session-to-workspace': '新增工作階段至工作區',
|
||||
'settings.shortcuts.binding.snippets': '開啟程式碼片段',
|
||||
'settings.shortcuts.binding.broadcast': '切換廣播模式',
|
||||
'settings.shortcuts.binding.toggle-opacity': '切換視窗透明度',
|
||||
@@ -719,6 +721,8 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'keychain.export.script': '指令碼 *',
|
||||
'keychain.export.scriptPlaceholder': '匯出指令碼...',
|
||||
'keychain.export.missingCredentials': '主機未儲存密碼或金鑰。請先為該主機新增密碼憑證。',
|
||||
'keychain.export.missingPublicKey': '此金鑰沒有公鑰。請先在編輯頁貼上公鑰,然後再試「匯出並繫結」。',
|
||||
'keychain.export.missingPublicKeyNote': '此金鑰沒有公鑰。請先在金鑰編輯頁貼上公鑰,然後再匯出。',
|
||||
'keychain.export.successTitle': '匯出成功',
|
||||
'keychain.export.successMessage': '已匯出公鑰並繫結到 {host}',
|
||||
'keychain.export.failedTitle': '匯出失敗',
|
||||
@@ -795,6 +799,7 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'tabs.logPrefix': '日誌:',
|
||||
'tabs.logLocal': '本機',
|
||||
'tabs.copyTab': '複製分頁',
|
||||
'tabs.addSessionToWorkspace': '新增工作階段至此工作區',
|
||||
'tabs.duplicateSession': '複製工作階段',
|
||||
'tabs.copyTabToNewWindow': '複製分頁到新視窗',
|
||||
'tabs.copyTabToNewWindowFailed': '無法在新視窗開啟分頁',
|
||||
|
||||
@@ -65,3 +65,409 @@ test('inserting a child into an existing void element fails the view', async ()
|
||||
assert.equal(tree.isFailed(), true);
|
||||
assert.deepEqual(tree.snapshot(), { children: [] });
|
||||
});
|
||||
|
||||
test('duplicate insert of an existing id applies as a move or replace and keeps follow-up updates in sync', async () => {
|
||||
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
|
||||
const tree = createPluginRemoteTree();
|
||||
tree.apply([[0, '~', { id: 'a', type: 1, element: 'div', attributes: { class: 'first' }, children: [] }, 0]]);
|
||||
|
||||
// Inserting an existing id at a later sibling index replaces the existing node in place.
|
||||
const replaced = tree.apply([
|
||||
[3, 'a', 'class', 'stale'],
|
||||
[0, '~', { id: 'a', type: 1, element: 'span', attributes: { class: 'replaced' }, children: [] }, 1],
|
||||
]);
|
||||
assert.equal(tree.isFailed(), false);
|
||||
assert.deepEqual(replaced, {
|
||||
children: [{ id: 'a', type: 1, element: 'span', attributes: { class: 'replaced' }, children: [] }],
|
||||
});
|
||||
|
||||
// Follow-up mutations must apply against the replaced live node (desync gate).
|
||||
const afterFollowUp = tree.apply([
|
||||
[3, 'a', 'class', 'after-sort'],
|
||||
[0, '~', { id: 'b', type: 1, element: 'div', attributes: {}, children: [{ id: 'b-text', type: 3, data: 'second' }] }, 1],
|
||||
]);
|
||||
assert.deepEqual(afterFollowUp, {
|
||||
children: [
|
||||
{ id: 'a', type: 1, element: 'span', attributes: { class: 'after-sort' }, children: [] },
|
||||
{ id: 'b', type: 1, element: 'div', attributes: {}, children: [{ id: 'b-text', type: 3, data: 'second' }] },
|
||||
],
|
||||
});
|
||||
|
||||
// Moving an existing sibling forward adjusts the insert index after detaching the old slot.
|
||||
const movedForward = tree.apply([
|
||||
[0, '~', { id: 'a', type: 1, element: 'span', attributes: { class: 'moved-end' }, children: [] }, 2],
|
||||
]);
|
||||
assert.deepEqual(movedForward.children.map((node) => node.id), ['b', 'a']);
|
||||
assert.deepEqual(movedForward.children[1], { id: 'a', type: 1, element: 'span', attributes: { class: 'moved-end' }, children: [] });
|
||||
|
||||
// Moving an existing sibling backward preserves index 0 and keeps subsequent updates working.
|
||||
const movedBack = tree.apply([
|
||||
[0, '~', { id: 'a', type: 1, element: 'span', attributes: { class: 'moved-start' }, children: [] }, 0],
|
||||
]);
|
||||
assert.deepEqual(movedBack.children.map((node) => node.id), ['a', 'b']);
|
||||
const postMoveAttr = tree.apply([[2, 'b-text', 'updated-second'], [3, 'a', 'class', 'synced']]);
|
||||
assert.deepEqual(postMoveAttr, {
|
||||
children: [
|
||||
{ id: 'a', type: 1, element: 'span', attributes: { class: 'synced' }, children: [] },
|
||||
{ id: 'b', type: 1, element: 'div', attributes: {}, children: [{ id: 'b-text', type: 3, data: 'updated-second' }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test('inserting a parent whose subtree re-includes an already-present child detaches the child and preserves later updates', async () => {
|
||||
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
|
||||
const tree = createPluginRemoteTree();
|
||||
tree.apply([
|
||||
[0, '~', {
|
||||
id: 'old-parent',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: {},
|
||||
children: [{
|
||||
id: 'cell-1',
|
||||
type: 1,
|
||||
element: 'span',
|
||||
attributes: { class: 'unsorted' },
|
||||
children: [{ id: 'cell-text', type: 3, data: 'alpha' }],
|
||||
}],
|
||||
}, 0],
|
||||
]);
|
||||
|
||||
// Parent insertion repeats already-attached descendant IDs without a preceding remove.
|
||||
const reparented = tree.apply([
|
||||
[0, '~', {
|
||||
id: 'new-parent',
|
||||
type: 1,
|
||||
element: 'section',
|
||||
attributes: {},
|
||||
children: [{
|
||||
id: 'cell-1',
|
||||
type: 1,
|
||||
element: 'span',
|
||||
attributes: { class: 'sorted-asc' },
|
||||
children: [{ id: 'cell-text', type: 3, data: 'alpha' }],
|
||||
}],
|
||||
}, 1],
|
||||
]);
|
||||
assert.equal(tree.isFailed(), false);
|
||||
assert.deepEqual(reparented, {
|
||||
children: [
|
||||
{ id: 'old-parent', type: 1, element: 'div', attributes: {}, children: [] },
|
||||
{
|
||||
id: 'new-parent',
|
||||
type: 1,
|
||||
element: 'section',
|
||||
attributes: {},
|
||||
children: [{
|
||||
id: 'cell-1',
|
||||
type: 1,
|
||||
element: 'span',
|
||||
attributes: { class: 'sorted-asc' },
|
||||
children: [{ id: 'cell-text', type: 3, data: 'alpha' }],
|
||||
}],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// A subsequent sort-like incremental update on the moved child applies cleanly.
|
||||
const secondSort = tree.apply([
|
||||
[3, 'cell-1', 'class', 'sorted-desc'],
|
||||
[2, 'cell-text', 'omega'],
|
||||
]);
|
||||
assert.deepEqual(secondSort.children[1], {
|
||||
id: 'new-parent',
|
||||
type: 1,
|
||||
element: 'section',
|
||||
attributes: {},
|
||||
children: [{
|
||||
id: 'cell-1',
|
||||
type: 1,
|
||||
element: 'span',
|
||||
attributes: { class: 'sorted-desc' },
|
||||
children: [{ id: 'cell-text', type: 3, data: 'omega' }],
|
||||
}],
|
||||
});
|
||||
|
||||
// Same-batch case: descendant inserted first, then a new parent serializing that descendant.
|
||||
const sameBatch = tree.apply([
|
||||
[0, 'old-parent', { id: 'child-2', type: 1, element: 'span', attributes: {}, children: [{ id: 'child-2-text', type: 3, data: 'one' }] }, 0],
|
||||
[0, '~', {
|
||||
id: 'wrapper',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: {},
|
||||
children: [{ id: 'child-2', type: 1, element: 'span', attributes: {}, children: [{ id: 'child-2-text', type: 3, data: 'one' }] }],
|
||||
}, 2],
|
||||
]);
|
||||
assert.equal(tree.isFailed(), false);
|
||||
assert.deepEqual(sameBatch.children[0], { id: 'old-parent', type: 1, element: 'div', attributes: {}, children: [] });
|
||||
assert.deepEqual(sameBatch.children[2], {
|
||||
id: 'wrapper',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: {},
|
||||
children: [{ id: 'child-2', type: 1, element: 'span', attributes: {}, children: [{ id: 'child-2-text', type: 3, data: 'one' }] }],
|
||||
});
|
||||
const afterSameBatch = tree.apply([[2, 'child-2-text', 'two']]);
|
||||
assert.deepEqual(afterSameBatch.children[2], {
|
||||
id: 'wrapper',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: {},
|
||||
children: [{ id: 'child-2', type: 1, element: 'span', attributes: {}, children: [{ id: 'child-2-text', type: 3, data: 'two' }] }],
|
||||
});
|
||||
});
|
||||
|
||||
test('unrecoverable self-nesting duplicate throws without failing the tree or corrupting later updates', async () => {
|
||||
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
|
||||
const tree = createPluginRemoteTree();
|
||||
tree.apply([[0, '~', { id: 'a', type: 1, element: 'div', attributes: { class: 'first' }, children: [] }, 0]]);
|
||||
assert.throws(
|
||||
() => tree.apply([
|
||||
[3, 'a', 'class', 'rejected'],
|
||||
[0, 'a', { id: 'a', type: 1, element: 'span', attributes: {}, children: [] }, 0],
|
||||
]),
|
||||
/Duplicate view node/,
|
||||
);
|
||||
assert.equal(tree.isFailed(), false);
|
||||
assert.deepEqual(tree.snapshot(), {
|
||||
children: [{ id: 'a', type: 1, element: 'div', attributes: { class: 'first' }, children: [] }],
|
||||
});
|
||||
const updated = tree.apply([[0, '~', { id: 'b', type: 3, data: 'second' }, 1]]);
|
||||
assert.deepEqual(updated, {
|
||||
children: [
|
||||
{ id: 'a', type: 1, element: 'div', attributes: { class: 'first' }, children: [] },
|
||||
{ id: 'b', type: 3, data: 'second' },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test('a duplicate id combined with a forbidden mutation still hard-fails the view', async () => {
|
||||
const { createPluginRemoteTree, isDuplicatePluginViewNodeError, assertDuplicateOnlyPluginRemoteTree } = await import('./pluginRemoteTree');
|
||||
const tree = createPluginRemoteTree();
|
||||
tree.apply([[0, '~', { id: 'input', type: 1, element: 'input', attributes: { type: 'text' }, children: [] }, 0]]);
|
||||
// Mutation order matters for RemoteReceiver: the void-element child is applied first so the
|
||||
// projected tree actually contains both the policy violation and a later duplicate id.
|
||||
assert.throws(
|
||||
() => tree.apply([
|
||||
[0, 'input', { id: 'child', type: 3, data: 'invalid' }, 0],
|
||||
[0, '~', { id: 'input', type: 1, element: 'div', attributes: {}, children: [] }, 1],
|
||||
]),
|
||||
/Void view elements/,
|
||||
);
|
||||
assert.equal(tree.isFailed(), true);
|
||||
assert.deepEqual(tree.snapshot(), { children: [] });
|
||||
|
||||
// Even when the duplicate node appears earlier in root order than the void-element violation,
|
||||
// unique-id revalidation must still hard-fail instead of rewriting the batch.
|
||||
const duplicateFirstTree = createPluginRemoteTree();
|
||||
duplicateFirstTree.apply([[0, '~', { id: 'input', type: 1, element: 'input', attributes: { type: 'text' }, children: [] }, 0]]);
|
||||
assert.throws(
|
||||
() => duplicateFirstTree.apply([
|
||||
[0, 'input', { id: 'child', type: 3, data: 'invalid' }, 0],
|
||||
[0, '~', { id: 'input', type: 1, element: 'div', attributes: {}, children: [] }, 0],
|
||||
]),
|
||||
/Void view elements/,
|
||||
);
|
||||
assert.equal(duplicateFirstTree.isFailed(), true);
|
||||
assert.deepEqual(duplicateFirstTree.snapshot(), { children: [] });
|
||||
|
||||
// Defense in depth: if a projected tree already has both issues, unique-id revalidation
|
||||
// must still surface the void-element violation instead of treating it as recoverable.
|
||||
const mixed = {
|
||||
children: [
|
||||
{ id: 'input', type: 1 as const, element: 'input', attributes: { type: 'text' }, children: [{ id: 'child', type: 3 as const, data: 'invalid' }] },
|
||||
{ id: 'input', type: 1 as const, element: 'div', attributes: {}, children: [] },
|
||||
],
|
||||
};
|
||||
assert.equal(isDuplicatePluginViewNodeError(new TypeError('Duplicate view node')), true);
|
||||
assert.throws(() => assertDuplicateOnlyPluginRemoteTree(mixed), /Void view elements/);
|
||||
});
|
||||
|
||||
test('RemoteMutationObserver wrapping a sibling preserves kept siblings and follow-up text updates', async () => {
|
||||
const dom = new JSDOM('<!doctype html><div id="remote"></div>', { url: 'http://localhost', pretendToBeVisual: true });
|
||||
const saved = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'MutationObserver', 'Event', 'MouseEvent']) {
|
||||
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window] });
|
||||
}
|
||||
const { RemoteMutationObserver } = await import('@remote-dom/core/elements');
|
||||
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
|
||||
const staged = createPluginRemoteTree();
|
||||
const batches: unknown[][][] = [];
|
||||
const observer = new RemoteMutationObserver({
|
||||
mutate(records) {
|
||||
const cloned = JSON.parse(JSON.stringify(records)) as unknown[][];
|
||||
batches.push(cloned);
|
||||
staged.apply(cloned);
|
||||
},
|
||||
call() { throw new Error('Host method calls are unavailable'); },
|
||||
});
|
||||
const container = document.getElementById('remote')!;
|
||||
observer.observe(container);
|
||||
const flush = () => new Promise((resolve) => setTimeout(resolve, 10));
|
||||
|
||||
try {
|
||||
const a = document.createElement('div');
|
||||
a.id = 'a';
|
||||
const aText = document.createTextNode('Alpha');
|
||||
a.appendChild(aText);
|
||||
|
||||
const b = document.createElement('div');
|
||||
b.id = 'b';
|
||||
b.appendChild(document.createTextNode('Beta'));
|
||||
|
||||
container.appendChild(a);
|
||||
container.appendChild(b);
|
||||
await flush();
|
||||
|
||||
assert.equal(staged.isFailed(), false);
|
||||
assert.equal(staged.snapshot().children.length, 2);
|
||||
|
||||
// Same-tick wrap: append wrapper and move b into it.
|
||||
const wrapper = document.createElement('section');
|
||||
wrapper.id = 'wrapper';
|
||||
container.appendChild(wrapper);
|
||||
wrapper.appendChild(b);
|
||||
await flush();
|
||||
|
||||
assert.equal(staged.isFailed(), false);
|
||||
const afterWrap = staged.snapshot();
|
||||
assert.deepEqual(
|
||||
afterWrap.children.map((node) => (node.type === 1 ? node.attributes.id : null)),
|
||||
['a', 'wrapper'],
|
||||
);
|
||||
const [aNode, wrapperNode] = afterWrap.children;
|
||||
assert.ok(aNode && aNode.type === 1, 'Expected sibling a first in host tree');
|
||||
assert.ok(wrapperNode && wrapperNode.type === 1, 'Expected wrapper second in host tree');
|
||||
assert.equal(aNode.children[0]?.type === 3 ? aNode.children[0].data : null, 'Alpha');
|
||||
assert.deepEqual(
|
||||
wrapperNode.children.map((node) => (node.type === 1 ? node.attributes.id : null)),
|
||||
['b'],
|
||||
);
|
||||
const bNode = wrapperNode.children[0];
|
||||
assert.ok(bNode && bNode.type === 1, 'Expected b inside wrapper');
|
||||
assert.equal(bNode.children[0]?.type === 3 ? bNode.children[0].data : null, 'Beta');
|
||||
|
||||
// Desync gate: a subsequent text update to a must apply cleanly.
|
||||
aText.data = 'Alpha updated';
|
||||
await flush();
|
||||
|
||||
assert.equal(staged.isFailed(), false);
|
||||
const afterText = staged.snapshot();
|
||||
assert.deepEqual(
|
||||
afterText.children.map((node) => (node.type === 1 ? node.attributes.id : null)),
|
||||
['a', 'wrapper'],
|
||||
);
|
||||
const updatedANode = afterText.children[0];
|
||||
assert.ok(updatedANode && updatedANode.type === 1);
|
||||
assert.equal(updatedANode.children[0]?.type === 3 ? updatedANode.children[0].data : null, 'Alpha updated');
|
||||
|
||||
// Later turn: removing wrapper at index 1 must keep a and leave a updatable.
|
||||
wrapper.remove();
|
||||
await flush();
|
||||
|
||||
assert.equal(staged.isFailed(), false);
|
||||
const afterRemove = staged.snapshot();
|
||||
assert.deepEqual(
|
||||
afterRemove.children.map((node) => (node.type === 1 ? node.attributes.id : null)),
|
||||
['a'],
|
||||
);
|
||||
aText.data = 'Alpha after remove';
|
||||
await flush();
|
||||
|
||||
assert.equal(staged.isFailed(), false);
|
||||
const afterRemoveText = staged.snapshot();
|
||||
const survivingANode = afterRemoveText.children[0];
|
||||
assert.ok(survivingANode && survivingANode.type === 1);
|
||||
assert.equal(survivingANode.children[0]?.type === 3 ? survivingANode.children[0].data : null, 'Alpha after remove');
|
||||
assert.ok(batches.length >= 5);
|
||||
} finally {
|
||||
observer.disconnect();
|
||||
for (const [key, value] of saved) {
|
||||
if (value) Object.defineProperty(globalThis, key, value);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('rewriteDuplicateInsertBatch skips matched detaches and remaps subsequent producer removals', async () => {
|
||||
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
|
||||
const tree = createPluginRemoteTree();
|
||||
tree.apply([
|
||||
[0, '~', { id: '0', type: 1, element: 'div', attributes: { id: 'a' }, children: [{ id: '1', type: 3, data: 'Alpha' }] }, 0],
|
||||
[0, '~', { id: '2', type: 1, element: 'div', attributes: { id: 'b' }, children: [{ id: '3', type: 3, data: 'Beta' }] }, 1],
|
||||
]);
|
||||
|
||||
// Exact mutation batch from RemoteMutationObserver when appending wrapper and moving b into it.
|
||||
const wrapped = tree.apply([
|
||||
[0, '~', {
|
||||
id: '4',
|
||||
type: 1,
|
||||
element: 'section',
|
||||
attributes: { id: 'wrapper' },
|
||||
children: [{ id: '2', type: 1, element: 'div', attributes: { id: 'b' }, children: [{ id: '3', type: 3, data: 'Beta' }] }],
|
||||
}, 0],
|
||||
[1, '~', 1],
|
||||
]);
|
||||
assert.equal(tree.isFailed(), false);
|
||||
assert.deepEqual(wrapped.children.map((node) => node.id), ['0', '4']);
|
||||
const wrapperNode = wrapped.children[1];
|
||||
assert.equal(wrapperNode.type, 1);
|
||||
if (wrapperNode.type === 1) {
|
||||
assert.deepEqual(wrapperNode.children.map((node) => node.id), ['2']);
|
||||
}
|
||||
|
||||
// Subsequent text update to a must still apply.
|
||||
const updated = tree.apply([[2, '1', 'Alpha updated']]);
|
||||
assert.equal(tree.isFailed(), false);
|
||||
assert.deepEqual(updated.children[0], {
|
||||
id: '0',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: { id: 'a' },
|
||||
children: [{ id: '1', type: 3, data: 'Alpha updated' }],
|
||||
});
|
||||
|
||||
// Later producer remove of wrapper at index 1 must remove wrapper and keep a alive.
|
||||
const afterRemove = tree.apply([[1, '~', 1]]);
|
||||
assert.equal(tree.isFailed(), false);
|
||||
assert.deepEqual(afterRemove.children.map((node) => node.id), ['0']);
|
||||
const afterRemoveUpdate = tree.apply([[2, '1', 'Alpha after remove']]);
|
||||
assert.equal(tree.isFailed(), false);
|
||||
assert.deepEqual(afterRemoveUpdate, {
|
||||
children: [{
|
||||
id: '0',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: { id: 'a' },
|
||||
children: [{ id: '1', type: 3, data: 'Alpha after remove' }],
|
||||
}],
|
||||
});
|
||||
|
||||
// Producer remove at a larger index after a rewrite detach at a smaller index remaps to the right sibling.
|
||||
const remapTree = createPluginRemoteTree();
|
||||
remapTree.apply([
|
||||
[0, '~', { id: 'a', type: 1, element: 'div', attributes: {}, children: [] }, 0],
|
||||
[0, '~', { id: 'b', type: 1, element: 'div', attributes: {}, children: [{ id: 'b-text', type: 3, data: 'keep' }] }, 1],
|
||||
[0, '~', { id: 'c', type: 1, element: 'div', attributes: {}, children: [] }, 2],
|
||||
]);
|
||||
const remapped = remapTree.apply([
|
||||
[0, '~', { id: 'wrap', type: 1, element: 'section', attributes: {}, children: [{ id: 'a', type: 1, element: 'div', attributes: {}, children: [] }] }, 3],
|
||||
// Producer removes c (original index 2) while a (index 0) was already detached by the rewrite.
|
||||
[1, '~', 2],
|
||||
// Producer then removes a at original index 0 (already detached -> skipped).
|
||||
[1, '~', 0],
|
||||
]);
|
||||
assert.equal(remapTree.isFailed(), false);
|
||||
assert.deepEqual(remapped.children.map((node) => node.id), ['b', 'wrap']);
|
||||
const followUp = remapTree.apply([[2, 'b-text', 'still-alive']]);
|
||||
assert.deepEqual(followUp.children[0], {
|
||||
id: 'b',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: {},
|
||||
children: [{ id: 'b-text', type: 3, data: 'still-alive' }],
|
||||
});
|
||||
});
|
||||
@@ -12,6 +12,174 @@ export function isValidatedPluginRemoteTree(tree: unknown): boolean {
|
||||
return Boolean(tree && typeof tree === 'object' && validatedTrees.has(tree));
|
||||
}
|
||||
|
||||
export function isDuplicatePluginViewNodeError(error: unknown): error is TypeError {
|
||||
return error instanceof TypeError && error.message === 'Duplicate view node';
|
||||
}
|
||||
|
||||
function withUniqueViewIds(tree: WireTree): WireTree {
|
||||
let n = 0;
|
||||
const rewrite = (node: WireNode): WireNode => {
|
||||
const id = `n${n++}`;
|
||||
if (node.type === 3 || node.type === 8) return { id, type: node.type, data: node.data };
|
||||
return { id, type: 1, element: node.element, attributes: node.attributes, children: node.children.map(rewrite) };
|
||||
};
|
||||
return { children: tree.children.map(rewrite) };
|
||||
}
|
||||
|
||||
/** If a projected tree has duplicate IDs, still hard-fail when other policy violations exist. */
|
||||
export function assertDuplicateOnlyPluginRemoteTree(tree: WireTree): void {
|
||||
validatePluginRemoteTree(withUniqueViewIds(tree));
|
||||
}
|
||||
|
||||
type WorkingNode = {
|
||||
id: string;
|
||||
parentId: string | null;
|
||||
children: WorkingNode[];
|
||||
};
|
||||
|
||||
type RewriteDetach = {
|
||||
parentId: string;
|
||||
index: number;
|
||||
id: string;
|
||||
};
|
||||
|
||||
function collectSubtreeIds(node: WireNode, out: string[] = []): string[] {
|
||||
out.push(node.id);
|
||||
if (node.type === 1) {
|
||||
for (const child of node.children) collectSubtreeIds(child, out);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function buildWorkingNode(node: WireNode, parentId: string, nodes: Map<string, WorkingNode>): WorkingNode {
|
||||
const working: WorkingNode = { id: node.id, parentId, children: [] };
|
||||
nodes.set(node.id, working);
|
||||
if (node.type === 1) {
|
||||
for (const child of node.children) {
|
||||
working.children.push(buildWorkingNode(child, node.id, nodes));
|
||||
}
|
||||
}
|
||||
return working;
|
||||
}
|
||||
|
||||
function detachWorkingSubtree(node: WorkingNode, nodes: Map<string, WorkingNode>): void {
|
||||
nodes.delete(node.id);
|
||||
node.parentId = null;
|
||||
for (const child of node.children) detachWorkingSubtree(child, nodes);
|
||||
}
|
||||
|
||||
function hasAncestorInSet(startId: string, ids: Set<string>, nodes: Map<string, WorkingNode>): boolean {
|
||||
let cursor: string | null = startId;
|
||||
while (cursor !== null) {
|
||||
if (ids.has(cursor)) return true;
|
||||
cursor = nodes.get(cursor)?.parentId ?? null;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes a duplicate-only mutation batch so inserts referencing IDs already
|
||||
* attached in the tree first emit explicit removals from their previous parents.
|
||||
* Returns null if an insert would detach its own destination parent (cycle).
|
||||
*/
|
||||
function rewriteDuplicateInsertBatch(current: WireTree, batch: unknown[][]): unknown[][] | null {
|
||||
const root: WorkingNode = { id: '~', parentId: null, children: [] };
|
||||
const nodes = new Map<string, WorkingNode>([['~', root]]);
|
||||
for (const child of current.children) {
|
||||
root.children.push(buildWorkingNode(child, '~', nodes));
|
||||
}
|
||||
|
||||
const rewritten: unknown[][] = [];
|
||||
const rewriteDetaches: RewriteDetach[] = [];
|
||||
for (const record of batch) {
|
||||
const type = record[0];
|
||||
if (type === 0) {
|
||||
const parentId = record[1] as string;
|
||||
const node = record[2] as WireNode;
|
||||
let insertIndex = record[3] as number;
|
||||
const parent = nodes.get(parentId);
|
||||
if (!parent) {
|
||||
// Detached parent: RemoteReceiver drops this insert as a no-op.
|
||||
rewritten.push(record);
|
||||
continue;
|
||||
}
|
||||
|
||||
const subtreeIds = collectSubtreeIds(node);
|
||||
if (hasAncestorInSet(parentId, new Set(subtreeIds), nodes)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const existingId of subtreeIds) {
|
||||
const existing = nodes.get(existingId);
|
||||
if (!existing || existing.parentId === null) continue;
|
||||
const oldParent = nodes.get(existing.parentId);
|
||||
if (!oldParent) continue;
|
||||
const oldIndex = oldParent.children.indexOf(existing);
|
||||
if (oldIndex < 0) continue;
|
||||
|
||||
rewritten.push([1, oldParent.id, oldIndex]);
|
||||
rewriteDetaches.push({ parentId: oldParent.id, index: oldIndex, id: existing.id });
|
||||
oldParent.children.splice(oldIndex, 1);
|
||||
detachWorkingSubtree(existing, nodes);
|
||||
|
||||
if (oldParent.id === parentId) {
|
||||
if (oldIndex < insertIndex) {
|
||||
insertIndex -= 1;
|
||||
} else if (existing.id !== node.id && oldIndex > insertIndex) {
|
||||
insertIndex = oldIndex;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rewritten.push(insertIndex === record[3] ? record : [0, parentId, node, insertIndex]);
|
||||
const inserted = buildWorkingNode(node, parentId, nodes);
|
||||
if (insertIndex >= parent.children.length) {
|
||||
parent.children.push(inserted);
|
||||
} else {
|
||||
parent.children.splice(insertIndex, 0, inserted);
|
||||
}
|
||||
} else if (type === 1) {
|
||||
const parentId = record[1] as string;
|
||||
const removeIndex = record[2] as number;
|
||||
const exactMatchIndex = rewriteDetaches.findIndex(
|
||||
(detach) => detach.parentId === parentId && detach.index === removeIndex,
|
||||
);
|
||||
if (exactMatchIndex !== -1) {
|
||||
rewriteDetaches.splice(exactMatchIndex, 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
let smallerCount = 0;
|
||||
for (const detach of rewriteDetaches) {
|
||||
if (detach.parentId === parentId && detach.index < removeIndex) {
|
||||
smallerCount += 1;
|
||||
}
|
||||
}
|
||||
const remappedIndex = removeIndex - smallerCount;
|
||||
const parent = nodes.get(parentId);
|
||||
if (!parent) {
|
||||
if (smallerCount === 0) rewritten.push(record);
|
||||
continue;
|
||||
}
|
||||
if (remappedIndex < 0 || remappedIndex >= parent.children.length) {
|
||||
continue;
|
||||
}
|
||||
rewritten.push(remappedIndex === removeIndex ? record : [1, parentId, remappedIndex]);
|
||||
const [removed] = parent.children.splice(remappedIndex, 1);
|
||||
if (removed) detachWorkingSubtree(removed, nodes);
|
||||
for (const detach of rewriteDetaches) {
|
||||
if (detach.parentId === parentId && detach.index > removeIndex) {
|
||||
detach.index -= 1;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
rewritten.push(record);
|
||||
}
|
||||
}
|
||||
|
||||
return rewritten;
|
||||
}
|
||||
|
||||
/** Data-only staging area: untrusted changes are never applied directly to the host DOM. */
|
||||
export function createPluginRemoteTree() {
|
||||
const receiver = new RemoteReceiver();
|
||||
@@ -23,6 +191,16 @@ export function createPluginRemoteTree() {
|
||||
if (value.type === 3 || value.type === 8) return { id: value.id, type: value.type, data: value.data ?? '' };
|
||||
return { id: value.id, type: 1, element: value.element ?? '', attributes: Object.fromEntries(Object.entries(value.attributes ?? {}).filter(([, attribute]) => attribute !== null)), children: (value.children ?? []).map(project) };
|
||||
};
|
||||
const applyToScratch = (records: unknown[][]): WireTree => {
|
||||
const scratch = new RemoteReceiver();
|
||||
if (current.children.length > 0) {
|
||||
scratch.connection.mutate(
|
||||
current.children.map((child, index) => [0, '~', child, index]) as unknown as Parameters<typeof scratch.connection.mutate>[0],
|
||||
);
|
||||
}
|
||||
scratch.connection.mutate(records as unknown as Parameters<typeof scratch.connection.mutate>[0]);
|
||||
return { children: scratch.root.children.map(project) };
|
||||
};
|
||||
return {
|
||||
apply(input: unknown): WireTree {
|
||||
if (failed) throw new Error('Plugin view has been closed after an invalid update');
|
||||
@@ -31,16 +209,35 @@ export function createPluginRemoteTree() {
|
||||
// Ordinary DOM attribute mutations do not specify a channel. RemoteReceiver
|
||||
// defaults those to properties, so explicitly mark them as attributes.
|
||||
const batch = (input as unknown[][]).map((record) => record[0] === 3 && record.length === 4 ? [...record, 2] : record);
|
||||
receiver.connection.mutate(batch as unknown as Parameters<typeof receiver.connection.mutate>[0]);
|
||||
const next = { children: receiver.root.children.map(project) };
|
||||
validatePluginRemoteTree(next);
|
||||
let appliedBatch = batch;
|
||||
let next = applyToScratch(batch);
|
||||
try {
|
||||
validatePluginRemoteTree(next);
|
||||
} catch (error) {
|
||||
if (!isDuplicatePluginViewNodeError(error)) throw error;
|
||||
assertDuplicateOnlyPluginRemoteTree(next);
|
||||
const rewritten = rewriteDuplicateInsertBatch(current, batch);
|
||||
if (!rewritten) throw error;
|
||||
const rewrittenNext = applyToScratch(rewritten);
|
||||
try {
|
||||
validatePluginRemoteTree(rewrittenNext);
|
||||
} catch (rewrittenError) {
|
||||
if (isDuplicatePluginViewNodeError(rewrittenError)) assertDuplicateOnlyPluginRemoteTree(rewrittenNext);
|
||||
throw rewrittenError;
|
||||
}
|
||||
appliedBatch = rewritten;
|
||||
next = rewrittenNext;
|
||||
}
|
||||
receiver.connection.mutate(appliedBatch as unknown as Parameters<typeof receiver.connection.mutate>[0]);
|
||||
validatedTrees.add(next);
|
||||
current = next;
|
||||
return next;
|
||||
} catch (error) {
|
||||
failed = true;
|
||||
current = { children: [] };
|
||||
validatedTrees.add(current);
|
||||
if (!isDuplicatePluginViewNodeError(error)) {
|
||||
failed = true;
|
||||
current = { children: [] };
|
||||
validatedTrees.add(current);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
@@ -218,3 +218,52 @@ test('portForward.start surfaces live error status and message when tunnel start
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('views.open resolves visible contribution, triggers open without polluting context, and rejects missing/hidden views', async () => {
|
||||
const opened: Array<{ viewId: string; context?: Record<string, unknown>; params?: unknown }> = [];
|
||||
const queries: unknown[] = [];
|
||||
const ctx: PluginVaultDataContext = {
|
||||
...makeContext({}),
|
||||
viewOpenRuntime: {
|
||||
getPluginContributions: async (query) => {
|
||||
queries.push(query);
|
||||
return {
|
||||
locale: 'en',
|
||||
plugins: [{
|
||||
id: 'com.example.db',
|
||||
version: '1.0.0',
|
||||
displayName: 'Database',
|
||||
commands: [],
|
||||
keybindings: [],
|
||||
menus: [],
|
||||
settings: [],
|
||||
views: [
|
||||
{ id: 'com.example.db.workbench', title: 'Database', location: 'vault-page', visible: true },
|
||||
{ id: 'com.example.db.hidden', title: 'Hidden', location: 'vault-page', visible: false },
|
||||
],
|
||||
}],
|
||||
};
|
||||
},
|
||||
requestOpenPluginView: (detail) => { opened.push(detail); },
|
||||
},
|
||||
};
|
||||
|
||||
const result = await handlePluginVaultDataRequest(
|
||||
'views.open',
|
||||
{ viewId: 'com.example.db.workbench', location: 'vault-page' },
|
||||
ctx,
|
||||
);
|
||||
assert.deepEqual(result, { opened: true, focused: true, location: 'vault-page' });
|
||||
assert.deepEqual(queries[0], { context: { 'netcatty.surface': 'vault-page' } });
|
||||
assert.deepEqual(opened, [{ viewId: 'com.example.db.workbench' }]);
|
||||
|
||||
await assert.rejects(
|
||||
() => handlePluginVaultDataRequest('views.open', { viewId: 'com.example.db.hidden', location: 'vault-page' }, ctx),
|
||||
/not available/,
|
||||
);
|
||||
await assert.rejects(
|
||||
() => handlePluginVaultDataRequest('views.open', { viewId: 'com.example.db.missing', location: 'vault-page' }, ctx),
|
||||
/not available/,
|
||||
);
|
||||
assert.equal(opened.length, 1);
|
||||
});
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
applyPortForwardingRuntimeStatus,
|
||||
getPortForwardingRuntimeRules,
|
||||
} from './usePortForwardingState';
|
||||
import { requestOpenPluginView } from './usePluginViewLifecycle';
|
||||
|
||||
export interface PluginPortForwardRuntimeDeps {
|
||||
startPortForward?: typeof startPortForward;
|
||||
@@ -36,10 +37,16 @@ export interface PluginPortForwardRuntimeDeps {
|
||||
applyRuntimeStatus?: typeof applyPortForwardingRuntimeStatus;
|
||||
}
|
||||
|
||||
export interface PluginViewOpenRuntimeDeps {
|
||||
getPluginContributions?: NonNullable<ReturnType<typeof netcattyBridge.get>>['getPluginContributions'];
|
||||
requestOpenPluginView?: typeof requestOpenPluginView;
|
||||
}
|
||||
|
||||
export type PluginVaultDataContext = {
|
||||
getVault: () => AppVaultRuntime & ReturnType<AppVaultRuntime['readCurrentHostActionState']>;
|
||||
resources: PluginHostActionResources;
|
||||
portForwardRuntime?: PluginPortForwardRuntimeDeps;
|
||||
viewOpenRuntime?: PluginViewOpenRuntimeDeps;
|
||||
};
|
||||
|
||||
type PortForwardSummaryStatus = 'inactive' | 'connecting' | 'active' | 'error';
|
||||
@@ -472,6 +479,42 @@ export async function handlePluginVaultDataRequest(
|
||||
return { focused: true };
|
||||
}
|
||||
|
||||
case 'views.open': {
|
||||
const viewId = typeof payload.viewId === 'string' ? payload.viewId : '';
|
||||
const location = typeof payload.location === 'string' ? payload.location : '';
|
||||
if (!viewId) throw new Error('Plugin view ID is required');
|
||||
const queryContext = location === 'vault-page'
|
||||
? { 'netcatty.surface': 'vault-page' }
|
||||
: location === 'terminal-sidebar'
|
||||
? { 'netcatty.surface': 'terminal-sidebar' }
|
||||
: { 'netcatty.surface': 'view' };
|
||||
const getContributions = ctx.viewOpenRuntime?.getPluginContributions ?? netcattyBridge.get()?.getPluginContributions;
|
||||
if (!getContributions) {
|
||||
throw new Error('Plugin contributions are unavailable');
|
||||
}
|
||||
const snapshot = await getContributions({ context: queryContext });
|
||||
const resolved = snapshot.plugins
|
||||
.flatMap((plugin) => plugin.views)
|
||||
.find((view) => view.id === viewId && view.visible);
|
||||
if (!resolved) {
|
||||
throw new Error(`Plugin view is not available: ${viewId}`);
|
||||
}
|
||||
if (resolved.location === 'terminal-sidebar') {
|
||||
const sessionRuntime = getAppSessionRuntime();
|
||||
const activeTabId = activeTabStore.getActiveTabId();
|
||||
const isTerminalTab = Boolean(
|
||||
sessionRuntime?.sessions.some((s) => s.id === activeTabId)
|
||||
|| sessionRuntime?.workspaces.some((w) => w.id === activeTabId),
|
||||
);
|
||||
if (!isTerminalTab) {
|
||||
throw new Error('An active terminal tab is required to open a terminal sidebar view');
|
||||
}
|
||||
}
|
||||
const openView = ctx.viewOpenRuntime?.requestOpenPluginView ?? requestOpenPluginView;
|
||||
openView({ viewId: resolved.id });
|
||||
return { opened: true, focused: true, location: resolved.location };
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`Unsupported Vault data request: ${kind}`);
|
||||
}
|
||||
|
||||
@@ -60,3 +60,280 @@ test('empty first update holds loading briefly to prevent blank-frame flash then
|
||||
assert.equal(view.getSnapshot().loading, false, 'truly empty view finishes loading after grace window');
|
||||
store.dispose();
|
||||
});
|
||||
test('update and event failures warn concisely with error message before disposing without logging event payloads', async () => {
|
||||
const warns: unknown[][] = [];
|
||||
const originalWarn = console.warn;
|
||||
console.warn = (...args: unknown[]) => { warns.push(args); };
|
||||
try {
|
||||
const f1 = fixture();
|
||||
const store = new PluginViewSessions();
|
||||
const view1 = store.acquire('bad-seq', f1.bridge, request);
|
||||
f1.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: f1.opened[0].instanceId, sequence: 99, css: '', mutations: [] });
|
||||
assert.equal(view1.getSnapshot().error, true);
|
||||
assert.equal(warns.length, 1);
|
||||
assert.match(String(warns[0][0]), /Invalid plugin update order/);
|
||||
assert.ok(warns[0][1] instanceof Error);
|
||||
|
||||
const f2 = fixture();
|
||||
f2.bridge.sendHostDrawnPluginViewEvent = async () => { throw new Error('IPC channel closed'); };
|
||||
const view2 = store.acquire('bad-send', f2.bridge, request);
|
||||
view2.send({ type: 'input', nodeId: 'field', value: 'secret@example.com' });
|
||||
await Promise.resolve();
|
||||
assert.equal(view2.getSnapshot().error, true);
|
||||
assert.equal(warns.length, 2);
|
||||
assert.match(String(warns[1][0]), /IPC channel closed/);
|
||||
assert.doesNotMatch(warns[1].map(String).join(' '), /secret@example\.com/);
|
||||
store.dispose();
|
||||
} finally {
|
||||
console.warn = originalWarn;
|
||||
}
|
||||
});
|
||||
test('recoverable duplicate node update applies as a move and publishes the new tree without warning', () => {
|
||||
const warns: unknown[][] = [];
|
||||
const originalWarn = console.warn;
|
||||
console.warn = (...args: unknown[]) => { warns.push(args); };
|
||||
try {
|
||||
const f = fixture();
|
||||
const store = new PluginViewSessions();
|
||||
const view = store.acquire('dup-move', f.bridge, request);
|
||||
const id = f.opened[0].instanceId;
|
||||
const initialNode = {
|
||||
id: 'row-1',
|
||||
type: 1 as const,
|
||||
element: 'div',
|
||||
attributes: { class: 'row' },
|
||||
children: [{ id: 'cell-1', type: 3 as const, data: 'alpha' }],
|
||||
};
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.row{display:flex}', mutations: [[0, '~', initialNode, 0]] });
|
||||
assert.equal(view.getSnapshot().loading, false);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.deepEqual(view.getSnapshot().tree.children, [initialNode]);
|
||||
|
||||
// Re-inserting an existing node (or wrapping it in a new parent without a remove)
|
||||
// is normalized as a move and published immediately with zero warnings.
|
||||
const movedNode = {
|
||||
id: 'group-1',
|
||||
type: 1 as const,
|
||||
element: 'section',
|
||||
attributes: { class: 'sorted' },
|
||||
children: [{
|
||||
id: 'row-1',
|
||||
type: 1 as const,
|
||||
element: 'div',
|
||||
attributes: { class: 'row' },
|
||||
children: [{ id: 'cell-1', type: 3 as const, data: 'alpha' }],
|
||||
}],
|
||||
};
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 2,
|
||||
css: '.sorted{color:blue}',
|
||||
mutations: [[0, '~', movedNode, 1]],
|
||||
} as Update);
|
||||
assert.equal(warns.length, 0);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.equal(view.getSnapshot().css.includes('blue'), true);
|
||||
assert.deepEqual(view.getSnapshot().tree.children, [movedNode]);
|
||||
assert.equal(f.closes.length, 0);
|
||||
assert.equal(store.peek('dup-move'), view);
|
||||
|
||||
// A subsequent incremental update applies cleanly against the moved nodes.
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 3,
|
||||
css: '',
|
||||
cssUnchanged: true,
|
||||
mutations: [
|
||||
[2, 'cell-1', 'beta'],
|
||||
[0, '~', { id: 'row-2', type: 3, data: 'second' }, 1],
|
||||
],
|
||||
} as Update);
|
||||
assert.equal(warns.length, 0);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.deepEqual(view.getSnapshot().tree.children, [
|
||||
{
|
||||
...movedNode,
|
||||
children: [{ ...initialNode, children: [{ id: 'cell-1', type: 3, data: 'beta' }] }],
|
||||
},
|
||||
{ id: 'row-2', type: 3, data: 'second' },
|
||||
]);
|
||||
|
||||
// Forbidden mutations still dispose the session.
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 4,
|
||||
css: '',
|
||||
cssUnchanged: true,
|
||||
mutations: [[3, 'row-1', 'onclick', 'attack()']],
|
||||
} as Update);
|
||||
assert.equal(view.getSnapshot().error, true);
|
||||
assert.deepEqual(view.getSnapshot().tree.children, []);
|
||||
store.dispose();
|
||||
} finally {
|
||||
console.warn = originalWarn;
|
||||
}
|
||||
});
|
||||
|
||||
test('unrecoverable duplicate node update warns without failing the session and accepts subsequent valid updates', () => {
|
||||
const warns: unknown[][] = [];
|
||||
const originalWarn = console.warn;
|
||||
console.warn = (...args: unknown[]) => { warns.push(args); };
|
||||
try {
|
||||
const f = fixture();
|
||||
const store = new PluginViewSessions();
|
||||
const view = store.acquire('dup-recovery', f.bridge, request);
|
||||
const id = f.opened[0].instanceId;
|
||||
const initialNode = {
|
||||
id: 'row-1',
|
||||
type: 1 as const,
|
||||
element: 'div',
|
||||
attributes: { class: 'row' },
|
||||
children: [{ id: 'cell-1', type: 3 as const, data: 'alpha' }],
|
||||
};
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.row{display:flex}', mutations: [[0, '~', initialNode, 0]] });
|
||||
assert.equal(view.getSnapshot().loading, false);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.deepEqual(view.getSnapshot().tree.children, [initialNode]);
|
||||
|
||||
// Self-nesting cycle cannot be rewritten as a move; last-resort fallback preserves last good tree.
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 2,
|
||||
css: '',
|
||||
cssUnchanged: true,
|
||||
mutations: [[0, 'row-1', { id: 'row-1', type: 1, element: 'div', attributes: {}, children: [] }, 0]],
|
||||
} as Update);
|
||||
assert.equal(warns.length, 1);
|
||||
assert.match(String(warns[0][0]), /Duplicate view node/);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.deepEqual(view.getSnapshot().tree.children, [initialNode]);
|
||||
assert.equal(f.closes.length, 0);
|
||||
assert.equal(store.peek('dup-recovery'), view);
|
||||
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 3,
|
||||
css: '',
|
||||
cssUnchanged: true,
|
||||
mutations: [
|
||||
[2, 'cell-1', 'beta'],
|
||||
[0, '~', { id: 'row-2', type: 3, data: 'second' }, 1],
|
||||
],
|
||||
} as Update);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.deepEqual(view.getSnapshot().tree.children, [
|
||||
{ ...initialNode, children: [{ id: 'cell-1', type: 3, data: 'beta' }] },
|
||||
{ id: 'row-2', type: 3, data: 'second' },
|
||||
]);
|
||||
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 4,
|
||||
css: '',
|
||||
cssUnchanged: true,
|
||||
mutations: [[3, 'row-1', 'onclick', 'attack()']],
|
||||
} as Update);
|
||||
assert.equal(view.getSnapshot().error, true);
|
||||
assert.deepEqual(view.getSnapshot().tree.children, []);
|
||||
store.dispose();
|
||||
} finally {
|
||||
console.warn = originalWarn;
|
||||
}
|
||||
});
|
||||
|
||||
test('pending CSS from a rejected unrecoverable duplicate update is published on the next accepted update', () => {
|
||||
const originalWarn = console.warn;
|
||||
console.warn = () => {};
|
||||
try {
|
||||
const f = fixture();
|
||||
const store = new PluginViewSessions();
|
||||
const view = store.acquire('css-pending', f.bridge, request);
|
||||
const id = f.opened[0].instanceId;
|
||||
const node = { id: 'row-1', type: 1 as const, element: 'div', attributes: { class: 'row' }, children: [] };
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.row{color:red}', mutations: [[0, '~', node, 0]] });
|
||||
assert.equal(view.getSnapshot().css.includes('red'), true);
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 2,
|
||||
css: '.row{color:blue}',
|
||||
mutations: [[0, 'row-1', { id: 'row-1', type: 1, element: 'span', attributes: {}, children: [] }, 0]],
|
||||
} as Update);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.equal(view.getSnapshot().css.includes('red'), true, 'rejected update does not publish CSS immediately');
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 3,
|
||||
css: '',
|
||||
cssUnchanged: true,
|
||||
mutations: [[3, 'row-1', 'class', 'ready']],
|
||||
} as Update);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.equal(view.getSnapshot().css.includes('blue'), true, 'next accepted update publishes the stashed CSS');
|
||||
store.dispose();
|
||||
} finally {
|
||||
console.warn = originalWarn;
|
||||
}
|
||||
});
|
||||
|
||||
test('explicit CSS matching the last committed value supersedes pending CSS', () => {
|
||||
const originalWarn = console.warn;
|
||||
console.warn = () => {};
|
||||
try {
|
||||
const f = fixture();
|
||||
const store = new PluginViewSessions();
|
||||
const view = store.acquire('css-supersede', f.bridge, request);
|
||||
const id = f.opened[0].instanceId;
|
||||
const node = { id: 'row-1', type: 1 as const, element: 'div', attributes: { class: 'row' }, children: [] };
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.row{color:red}', mutations: [[0, '~', node, 0]] });
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 2,
|
||||
css: '.row{color:blue}',
|
||||
mutations: [[0, 'row-1', { id: 'row-1', type: 1, element: 'span', attributes: {}, children: [] }, 0]],
|
||||
} as Update);
|
||||
assert.equal(view.getSnapshot().css.includes('red'), true);
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 3,
|
||||
css: '.row{color:red}',
|
||||
mutations: [[3, 'row-1', 'class', 'ready']],
|
||||
} as Update);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.equal(view.getSnapshot().css.includes('blue'), false);
|
||||
assert.equal(view.getSnapshot().css.includes('red'), true, 'explicit red supersedes pending blue');
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 4,
|
||||
css: '',
|
||||
cssUnchanged: true,
|
||||
mutations: [[3, 'row-1', 'class', 'again']],
|
||||
} as Update);
|
||||
assert.equal(view.getSnapshot().css.includes('red'), true);
|
||||
assert.equal(view.getSnapshot().css.includes('blue'), false);
|
||||
store.dispose();
|
||||
} finally {
|
||||
console.warn = originalWarn;
|
||||
}
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createPluginRemoteTree } from './pluginRemoteTree';
|
||||
import { createPluginRemoteTree, isDuplicatePluginViewNodeError } from './pluginRemoteTree';
|
||||
import { registerLoadedPluginViewSessions } from './pluginViewSessionRegistry';
|
||||
import { validatePluginStylesheet } from '@/domain/pluginViewStylePolicy.cjs';
|
||||
import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
|
||||
@@ -27,6 +27,8 @@ export class PluginViewSessions {
|
||||
const tree = createPluginRemoteTree();
|
||||
let state = empty(); let sequence = 1; let eventId = 0; let disposed = false; let users = 0;
|
||||
let lastRawCss: string | null = null;
|
||||
let pendingCss: string | null = null;
|
||||
let pendingRawCss: string | null = null;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let emptyFrameTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const listeners = new Set<() => void>();
|
||||
@@ -42,14 +44,26 @@ export class PluginViewSessions {
|
||||
if (!bridge.openHostDrawnPluginView || !bridge.onHostDrawnPluginViewUpdate || !bridge.onPluginViewClosed) throw new Error('Plugin views unavailable');
|
||||
cleanup.push(bridge.onHostDrawnPluginViewUpdate((update) => {
|
||||
if (disposed || update.kind !== 'host-ui.update' || update.instanceId !== id || update.viewId !== request.viewId) return;
|
||||
let stagedCss: string | null = null;
|
||||
let stagedRawCss: string | null = null;
|
||||
try {
|
||||
if (update.sequence !== sequence++) throw new Error('Invalid plugin update order');
|
||||
const nextCss = update.cssUnchanged
|
||||
? state.css
|
||||
: (lastRawCss !== null && update.css === lastRawCss)
|
||||
? state.css
|
||||
: ((lastRawCss = update.css), validatePluginStylesheet(update.css));
|
||||
if (update.cssUnchanged) {
|
||||
// keep pending CSS, if any, for the nextCss fallback below
|
||||
} else if (lastRawCss !== null && update.css === lastRawCss) {
|
||||
// Explicit CSS equal to the last committed raw CSS supersedes any pending stylesheet.
|
||||
pendingCss = null;
|
||||
pendingRawCss = null;
|
||||
} else {
|
||||
stagedCss = validatePluginStylesheet(update.css);
|
||||
stagedRawCss = update.css;
|
||||
}
|
||||
const nextCss = stagedCss ?? pendingCss ?? state.css;
|
||||
const nextTree = tree.apply(update.mutations);
|
||||
if (stagedRawCss !== null) lastRawCss = stagedRawCss;
|
||||
else if (pendingRawCss !== null) lastRawCss = pendingRawCss;
|
||||
pendingCss = null;
|
||||
pendingRawCss = null;
|
||||
const settled = (update.acknowledgedEvent ?? 0) >= eventId;
|
||||
if (state.loading && !hasRenderableTreeContent(nextTree)) {
|
||||
// Hold the host loading surface briefly while an older SDK flushes its
|
||||
@@ -68,7 +82,20 @@ export class PluginViewSessions {
|
||||
emptyFrameTimer = undefined;
|
||||
}
|
||||
publish({ tree: nextTree, css: nextCss, loading: false, error: false, settled });
|
||||
} catch { dispose(true); }
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.warn(`[PluginViewSession] Failed to apply update for ${request.viewId}: ${message}`, error);
|
||||
// Recoverable duplicate-only batches are normalized as moves in
|
||||
// createPluginRemoteTree(); only unrecoverable duplicates reach here.
|
||||
if (isDuplicatePluginViewNodeError(error)) {
|
||||
if (stagedCss !== null && stagedRawCss !== null) {
|
||||
pendingCss = stagedCss;
|
||||
pendingRawCss = stagedRawCss;
|
||||
}
|
||||
return;
|
||||
}
|
||||
dispose(true);
|
||||
}
|
||||
}));
|
||||
cleanup.push(bridge.onPluginViewClosed((event) => { if (event.instanceId === id) dispose(true); }));
|
||||
void bridge.openHostDrawnPluginView({ ...request, instanceId: id }).then(() => {
|
||||
@@ -100,7 +127,11 @@ export class PluginViewSessions {
|
||||
send: (event: HostDrawnViewEvent) => {
|
||||
if (disposed || users === 0) return;
|
||||
publish({ ...state, settled: false });
|
||||
void bridge.sendHostDrawnPluginViewEvent?.(id, { ...event, eventId: ++eventId }).catch(() => dispose(true));
|
||||
void bridge.sendHostDrawnPluginViewEvent?.(id, { ...event, eventId: ++eventId }).catch((error) => {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.warn(`[PluginViewSession] Failed to send event for ${request.viewId}: ${message}`);
|
||||
dispose(true);
|
||||
});
|
||||
},
|
||||
dispose,
|
||||
};
|
||||
|
||||
@@ -25,6 +25,7 @@ export type SettingsChromeSnapshot = {
|
||||
windowOpacity: number;
|
||||
showSftpTab: boolean;
|
||||
showHostTreeSidebar: boolean;
|
||||
removeTopTabsDragArea: boolean;
|
||||
showRecentHosts: boolean;
|
||||
hostClickBehavior: HostClickBehavior;
|
||||
showOnlyUngroupedHostsInRoot: boolean;
|
||||
@@ -59,6 +60,7 @@ export const DEFAULT_SETTINGS_CHROME_SNAPSHOT: SettingsChromeSnapshot = Object.f
|
||||
windowOpacity: 1,
|
||||
showSftpTab: true,
|
||||
showHostTreeSidebar: true,
|
||||
removeTopTabsDragArea: false,
|
||||
showRecentHosts: true,
|
||||
hostClickBehavior: 'connect',
|
||||
showOnlyUngroupedHostsInRoot: false,
|
||||
@@ -86,6 +88,7 @@ export function settingsChromeSnapshotsEqual(
|
||||
&& a.windowOpacity === b.windowOpacity
|
||||
&& a.showSftpTab === b.showSftpTab
|
||||
&& a.showHostTreeSidebar === b.showHostTreeSidebar
|
||||
&& a.removeTopTabsDragArea === b.removeTopTabsDragArea
|
||||
&& a.showRecentHosts === b.showRecentHosts
|
||||
&& a.hostClickBehavior === b.hostClickBehavior
|
||||
&& a.showOnlyUngroupedHostsInRoot === b.showOnlyUngroupedHostsInRoot
|
||||
|
||||
@@ -137,6 +137,7 @@ export type { HostClickBehavior } from '../../domain/hostClickBehavior';
|
||||
export const DEFAULT_SHOW_ONLY_UNGROUPED_HOSTS_IN_ROOT = false;
|
||||
export const DEFAULT_SHOW_SFTP_TAB = true;
|
||||
export const DEFAULT_SHOW_HOST_TREE_SIDEBAR = true;
|
||||
export const DEFAULT_REMOVE_TOP_TABS_DRAG_AREA = false;
|
||||
export const DEFAULT_SHELL_ONLY_TAB_NUMBER_SHORTCUTS = false;
|
||||
export const DEFAULT_SHOW_TAB_NUMBER_BADGES = true;
|
||||
export const DEFAULT_DISABLE_TERMINAL_FONT_ZOOM = false;
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
STORAGE_KEY_HOST_CLICK_BEHAVIOR,
|
||||
STORAGE_KEY_SHOW_SFTP_TAB,
|
||||
STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR,
|
||||
STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA,
|
||||
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN,
|
||||
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB,
|
||||
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN,
|
||||
@@ -136,6 +137,7 @@ interface UseSettingsStorageSyncParams {
|
||||
showOnlyUngroupedHostsInRoot: boolean;
|
||||
showSftpTab: boolean;
|
||||
showHostTreeSidebar: boolean;
|
||||
removeTopTabsDragArea: boolean;
|
||||
terminalSidePanelAutoOpen: boolean;
|
||||
terminalSidePanelAutoOpenTab: TerminalSidePanelAutoOpenTab;
|
||||
localShellSidePanelAutoOpen: boolean;
|
||||
@@ -194,6 +196,7 @@ interface UseSettingsStorageSyncParams {
|
||||
setShowOnlyUngroupedHostsInRootState: Dispatch<SetStateAction<boolean>>;
|
||||
setShowSftpTabState: Dispatch<SetStateAction<boolean>>;
|
||||
setShowHostTreeSidebarState: Dispatch<SetStateAction<boolean>>;
|
||||
setRemoveTopTabsDragAreaState: Dispatch<SetStateAction<boolean>>;
|
||||
setTerminalSidePanelAutoOpenState: Dispatch<SetStateAction<boolean>>;
|
||||
setTerminalSidePanelAutoOpenTabState: Dispatch<SetStateAction<TerminalSidePanelAutoOpenTab>>;
|
||||
setLocalShellSidePanelAutoOpenState: Dispatch<SetStateAction<boolean>>;
|
||||
@@ -238,7 +241,7 @@ export function useSettingsStorageSync({
|
||||
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
|
||||
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
|
||||
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, removeTopTabsDragArea, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
|
||||
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
|
||||
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
|
||||
@@ -249,7 +252,7 @@ export function useSettingsStorageSync({
|
||||
setFollowAppTerminalThemeState, setTerminalFontFamilyId, setTerminalFontSize,
|
||||
setSftpDoubleClickBehavior, setSftpAutoSync, setSftpShowHiddenFiles,
|
||||
setSftpUseCompressedUpload, setSftpSkipUnchanged, setSftpAutoOpenSidebar, setSftpFollowTerminalCwd, setSftpDefaultViewMode,
|
||||
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
|
||||
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setRemoveTopTabsDragAreaState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
|
||||
setEditorWordWrapState, setSessionLogsEnabled, setSessionLogsDir, setSessionLogsFormat, setSessionLogsTimestampsEnabled,
|
||||
setRemoteDesktopAutoRecordState, setRemoteDesktopRecordingFpsState, setRemoteDesktopRecordingIncludeAudioState, setRemoteDesktopRecordingMaxMbState, setRemoteDesktopRecordingRetentionDaysState,
|
||||
setSshDebugLogsEnabled, setSshDeepLinkEnabledState, setJmsDeepLinkEnabledState, setJumpServerRdpLaunchModeState, setExplorerContextMenuEnabledState,
|
||||
@@ -266,7 +269,7 @@ export function useSettingsStorageSync({
|
||||
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
|
||||
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
|
||||
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, removeTopTabsDragArea, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
|
||||
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
|
||||
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
|
||||
@@ -278,7 +281,7 @@ export function useSettingsStorageSync({
|
||||
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
|
||||
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
|
||||
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, removeTopTabsDragArea, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
|
||||
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
|
||||
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
|
||||
@@ -548,6 +551,12 @@ export function useSettingsStorageSync({
|
||||
setShowHostTreeSidebarState(newValue);
|
||||
}
|
||||
}
|
||||
if (e.key === STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA && e.newValue !== null) {
|
||||
const newValue = e.newValue === 'true';
|
||||
if (newValue !== s.removeTopTabsDragArea) {
|
||||
setRemoveTopTabsDragAreaState(newValue);
|
||||
}
|
||||
}
|
||||
if (e.key === STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN && e.newValue !== null) {
|
||||
const newValue = e.newValue === 'true';
|
||||
if (newValue !== s.terminalSidePanelAutoOpen) {
|
||||
@@ -701,6 +710,7 @@ export function useSettingsStorageSync({
|
||||
setSftpSkipUnchanged,
|
||||
setShowOnlyUngroupedHostsInRootState,
|
||||
setShowHostTreeSidebarState,
|
||||
setRemoveTopTabsDragAreaState,
|
||||
setTerminalSidePanelAutoOpenState,
|
||||
setTerminalSidePanelAutoOpenTabState,
|
||||
setLocalShellSidePanelAutoOpenState,
|
||||
|
||||
@@ -1,21 +1,38 @@
|
||||
import {
|
||||
buildSftpDownloadDialogDirectoryOptions,
|
||||
normalizeSftpDefaultDownloadDirectory,
|
||||
type SftpDownloadDialogDirectoryOptions,
|
||||
} from "../../../domain/sftpDownloadLocation";
|
||||
import { STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR } from "../../../infrastructure/config/storageKeys";
|
||||
import {
|
||||
STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR,
|
||||
STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR,
|
||||
} from "../../../infrastructure/config/storageKeys";
|
||||
import { localStorageAdapter } from "../../../infrastructure/persistence/localStorageAdapter";
|
||||
|
||||
/**
|
||||
* Read the device-local default download folder at call time so every SFTP
|
||||
* Read the device-local download folders at call time so every SFTP
|
||||
* surface (main view, terminal side panel, other windows) sees the latest
|
||||
* value without threading it through props.
|
||||
*/
|
||||
export const getSftpDownloadDialogDirectoryOptions = (): SftpDownloadDialogDirectoryOptions => {
|
||||
let stored: string | null = null;
|
||||
let lastUsed: string | null = null;
|
||||
try {
|
||||
stored = localStorageAdapter.readString(STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR);
|
||||
lastUsed = localStorageAdapter.readString(STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR);
|
||||
} catch {
|
||||
// Storage unavailable (non-browser host); fall back to system Downloads.
|
||||
}
|
||||
return buildSftpDownloadDialogDirectoryOptions(stored);
|
||||
return buildSftpDownloadDialogDirectoryOptions(stored, lastUsed);
|
||||
};
|
||||
|
||||
/** Remember a confirmed download destination without changing the setting. */
|
||||
export const rememberSftpDownloadDirectory = (directory: string): void => {
|
||||
const normalized = normalizeSftpDefaultDownloadDirectory(directory);
|
||||
if (!normalized) return;
|
||||
try {
|
||||
localStorageAdapter.writeString(STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR, normalized);
|
||||
} catch {
|
||||
// Unavailable storage must not interrupt the download.
|
||||
}
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
|
||||
import {
|
||||
STORAGE_KEY_AI_PROVIDERS,
|
||||
@@ -19,6 +19,8 @@ import {
|
||||
STORAGE_KEY_AI_WEB_SEARCH,
|
||||
STORAGE_KEY_AI_QUICK_MESSAGES,
|
||||
STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION,
|
||||
STORAGE_KEY_AI_AUTO_LLM_TITLE,
|
||||
STORAGE_KEY_AI_TITLE_MODEL,
|
||||
} from '../../infrastructure/config/storageKeys';
|
||||
import type { AIQuickMessage } from '../../infrastructure/ai/quickMessages';
|
||||
import { sanitizeQuickMessages } from '../../infrastructure/ai/quickMessages';
|
||||
@@ -46,6 +48,7 @@ import {
|
||||
DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
normalizeAiToolOutputMaxChars,
|
||||
} from '../../domain/aiToolOutputLimit';
|
||||
import type { TitleModelConfig } from '../../domain/aiSessionTitle';
|
||||
import { AI_STATE_CHANGED_EVENT, emitAIStateChanged } from './aiStateEvents';
|
||||
import { getAIBridge } from './aiStateSnapshots';
|
||||
import { useStoredBoolean } from './useStoredBoolean';
|
||||
@@ -54,6 +57,25 @@ import {
|
||||
readCommandBlocklistSetting,
|
||||
} from './commandBlocklistSettings';
|
||||
|
||||
export type { TitleModelConfig };
|
||||
|
||||
function readTitleModelSetting(): TitleModelConfig | null {
|
||||
const stored = localStorageAdapter.read<unknown>(STORAGE_KEY_AI_TITLE_MODEL);
|
||||
if (!stored || typeof stored !== 'object') return null;
|
||||
const providerId = (stored as TitleModelConfig).providerId;
|
||||
const modelId = (stored as TitleModelConfig).modelId;
|
||||
return typeof providerId === 'string' && providerId.trim()
|
||||
&& typeof modelId === 'string' && modelId.trim()
|
||||
? { providerId: providerId.trim(), modelId: modelId.trim() }
|
||||
: null;
|
||||
}
|
||||
|
||||
function readAgentStringMap(key: string): Record<string, string> {
|
||||
const stored = localStorageAdapter.read<unknown>(key);
|
||||
if (!stored || typeof stored !== 'object' || Array.isArray(stored)) return {};
|
||||
return stored as Record<string, string>;
|
||||
}
|
||||
|
||||
function readPermissionMode(): AIPermissionMode {
|
||||
const stored = localStorageAdapter.readString(STORAGE_KEY_AI_PERMISSION_MODE);
|
||||
if (stored === 'observer' || stored === 'confirm' || stored === 'auto') return stored;
|
||||
@@ -150,6 +172,25 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
|
||||
const [quickMessages, setQuickMessagesRaw] = useState<AIQuickMessage[]>(() =>
|
||||
sanitizeQuickMessages(localStorageAdapter.read<unknown>(STORAGE_KEY_AI_QUICK_MESSAGES)),
|
||||
);
|
||||
const [autoLlmTitle, setAutoLlmTitle] = useStoredBoolean(STORAGE_KEY_AI_AUTO_LLM_TITLE, true);
|
||||
const [titleModel, setTitleModelRaw] = useState<TitleModelConfig | null>(() =>
|
||||
readTitleModelSetting(),
|
||||
);
|
||||
const titleModelRef = useRef(titleModel);
|
||||
titleModelRef.current = titleModel;
|
||||
|
||||
const setTitleModel = useCallback((config: TitleModelConfig | null) => {
|
||||
const normalized = config
|
||||
&& typeof config.providerId === 'string' && config.providerId.trim()
|
||||
&& typeof config.modelId === 'string' && config.modelId.trim()
|
||||
? { providerId: config.providerId.trim(), modelId: config.modelId.trim() }
|
||||
: null;
|
||||
titleModelRef.current = normalized;
|
||||
setTitleModelRaw(normalized);
|
||||
if (normalized) localStorageAdapter.write(STORAGE_KEY_AI_TITLE_MODEL, normalized);
|
||||
else localStorageAdapter.remove(STORAGE_KEY_AI_TITLE_MODEL);
|
||||
emitAIStateChanged(STORAGE_KEY_AI_TITLE_MODEL);
|
||||
}, []);
|
||||
|
||||
const setProviders = useCallback((value: ProviderConfig[] | ((prev: ProviderConfig[]) => ProviderConfig[])) => {
|
||||
setProvidersRaw((prev) => {
|
||||
@@ -183,6 +224,9 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
|
||||
localStorageAdapter.writeString(STORAGE_KEY_AI_ACTIVE_PROVIDER, '');
|
||||
return '';
|
||||
});
|
||||
if (titleModelRef.current?.providerId === id) {
|
||||
setTitleModel(null);
|
||||
}
|
||||
|
||||
if (onRemoveProvider) {
|
||||
onRemoveProvider(id);
|
||||
@@ -196,11 +240,13 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
|
||||
const cleanup = removeProviderReferences(id, agentProviderMap, agentModelMap);
|
||||
if (cleanup.providerMapChanged) {
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_AGENT_PROVIDER_MAP, cleanup.agentProviderMap);
|
||||
emitAIStateChanged(STORAGE_KEY_AI_AGENT_PROVIDER_MAP);
|
||||
}
|
||||
if (cleanup.modelMapChanged) {
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_AGENT_MODEL_MAP, cleanup.agentModelMap);
|
||||
emitAIStateChanged(STORAGE_KEY_AI_AGENT_MODEL_MAP);
|
||||
}
|
||||
}, [onRemoveProvider, setProviders]);
|
||||
}, [onRemoveProvider, setProviders, setTitleModel]);
|
||||
|
||||
const setActiveProviderId = useCallback((id: string) => {
|
||||
setActiveProviderIdRaw(id);
|
||||
@@ -375,6 +421,9 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
|
||||
case STORAGE_KEY_AI_QUICK_MESSAGES:
|
||||
setQuickMessagesRaw(sanitizeQuickMessages(localStorageAdapter.read<unknown>(STORAGE_KEY_AI_QUICK_MESSAGES)));
|
||||
break;
|
||||
case STORAGE_KEY_AI_TITLE_MODEL:
|
||||
setTitleModelRaw(readTitleModelSetting());
|
||||
break;
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('[useAISettingsState] Failed to process AI settings storage change', key, err);
|
||||
@@ -438,6 +487,10 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
|
||||
setWebSearchConfig,
|
||||
quickMessages,
|
||||
setQuickMessages,
|
||||
autoLlmTitle,
|
||||
setAutoLlmTitle,
|
||||
titleModel,
|
||||
setTitleModel,
|
||||
}), [
|
||||
providers,
|
||||
setProviders,
|
||||
@@ -471,6 +524,10 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
|
||||
setWebSearchConfig,
|
||||
quickMessages,
|
||||
setQuickMessages,
|
||||
autoLlmTitle,
|
||||
setAutoLlmTitle,
|
||||
titleModel,
|
||||
setTitleModel,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -486,6 +543,12 @@ export function useAISettingsState() {
|
||||
STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION,
|
||||
true,
|
||||
);
|
||||
const [agentProviderMap, setAgentProviderMapRaw] = useState<Record<string, string>>(() =>
|
||||
readAgentStringMap(STORAGE_KEY_AI_AGENT_PROVIDER_MAP),
|
||||
);
|
||||
const [agentModelMap, setAgentModelMapRaw] = useState<Record<string, string>>(() =>
|
||||
readAgentStringMap(STORAGE_KEY_AI_AGENT_MODEL_MAP),
|
||||
);
|
||||
|
||||
const setAiSessionMessageCap = useCallback((value: number) => {
|
||||
const normalizedValue = normalizeAiSessionMessageCap(value);
|
||||
@@ -494,23 +557,32 @@ export function useAISettingsState() {
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const syncMessageCap = (key: string | null) => {
|
||||
if (key !== STORAGE_KEY_AI_SESSION_MESSAGE_CAP) return;
|
||||
const syncSettingsOnlyKey = (key: string | null) => {
|
||||
try {
|
||||
setAiSessionMessageCapRaw(
|
||||
normalizeAiSessionMessageCap(
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_SESSION_MESSAGE_CAP)
|
||||
?? DEFAULT_AI_SESSION_MESSAGE_CAP,
|
||||
),
|
||||
);
|
||||
switch (key) {
|
||||
case STORAGE_KEY_AI_SESSION_MESSAGE_CAP:
|
||||
setAiSessionMessageCapRaw(
|
||||
normalizeAiSessionMessageCap(
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_SESSION_MESSAGE_CAP)
|
||||
?? DEFAULT_AI_SESSION_MESSAGE_CAP,
|
||||
),
|
||||
);
|
||||
break;
|
||||
case STORAGE_KEY_AI_AGENT_PROVIDER_MAP:
|
||||
setAgentProviderMapRaw(readAgentStringMap(STORAGE_KEY_AI_AGENT_PROVIDER_MAP));
|
||||
break;
|
||||
case STORAGE_KEY_AI_AGENT_MODEL_MAP:
|
||||
setAgentModelMapRaw(readAgentStringMap(STORAGE_KEY_AI_AGENT_MODEL_MAP));
|
||||
break;
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('[useAISettingsState] Failed to process AI settings storage change', key, err);
|
||||
}
|
||||
};
|
||||
|
||||
const handleStorage = (event: StorageEvent) => syncMessageCap(event.key);
|
||||
const handleStorage = (event: StorageEvent) => syncSettingsOnlyKey(event.key);
|
||||
const handleLocalStateChanged = (event: Event) => {
|
||||
syncMessageCap((event as CustomEvent<{ key?: string }>).detail?.key ?? null);
|
||||
syncSettingsOnlyKey((event as CustomEvent<{ key?: string }>).detail?.key ?? null);
|
||||
};
|
||||
|
||||
window.addEventListener('storage', handleStorage);
|
||||
@@ -527,11 +599,15 @@ export function useAISettingsState() {
|
||||
setAiSessionMessageCap,
|
||||
showTerminalSelectionAIAction,
|
||||
setShowTerminalSelectionAIAction,
|
||||
agentProviderMap,
|
||||
agentModelMap,
|
||||
}), [
|
||||
shared,
|
||||
aiSessionMessageCap,
|
||||
setAiSessionMessageCap,
|
||||
showTerminalSelectionAIAction,
|
||||
setShowTerminalSelectionAIAction,
|
||||
agentProviderMap,
|
||||
agentModelMap,
|
||||
]);
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import React, { act } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { JSDOM } from 'jsdom';
|
||||
|
||||
import type { AISession, ProviderConfig } from '../../infrastructure/ai/types.ts';
|
||||
import {
|
||||
STORAGE_KEY_AI_ACTIVE_PROVIDER,
|
||||
STORAGE_KEY_AI_AGENT_MODEL_MAP,
|
||||
STORAGE_KEY_AI_AGENT_PROVIDER_MAP,
|
||||
STORAGE_KEY_AI_AUTO_LLM_TITLE,
|
||||
STORAGE_KEY_AI_PROVIDERS,
|
||||
STORAGE_KEY_AI_TITLE_MODEL,
|
||||
} from '../../infrastructure/config/storageKeys.ts';
|
||||
import { useAIState, type UseAIStateOptions } from './useAIState.ts';
|
||||
import { useAISessionsStore } from './aiSessionsStore.ts';
|
||||
import {
|
||||
__resetIdbPersistenceForTests,
|
||||
markAiSessionsHydrationComplete,
|
||||
setLatestAISessionsSnapshot,
|
||||
} from './aiStateSnapshots.ts';
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (reason?: unknown) => void;
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
type Capture = {
|
||||
ai: ReturnType<typeof useAIState> | null;
|
||||
sessions: AISession[];
|
||||
};
|
||||
|
||||
function Harness({
|
||||
capture,
|
||||
options,
|
||||
}: {
|
||||
capture: Capture;
|
||||
options?: UseAIStateOptions;
|
||||
}) {
|
||||
capture.ai = useAIState(options);
|
||||
capture.sessions = useAISessionsStore().sessions as AISession[];
|
||||
return null;
|
||||
}
|
||||
|
||||
async function setupHook(options?: {
|
||||
sessions?: AISession[];
|
||||
providers?: ProviderConfig[];
|
||||
activeProviderId?: string;
|
||||
agentProviderMap?: Record<string, string>;
|
||||
agentModelMap?: Record<string, string>;
|
||||
autoLlmTitle?: boolean;
|
||||
titleModel?: { providerId: string; modelId: string } | null;
|
||||
generateSessionTitle?: UseAIStateOptions['generateSessionTitle'];
|
||||
}) {
|
||||
const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost' });
|
||||
const prevDescriptors = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const [key, value] of [
|
||||
['window', dom.window],
|
||||
['document', dom.window.document],
|
||||
['localStorage', dom.window.localStorage],
|
||||
['CustomEvent', dom.window.CustomEvent],
|
||||
['Event', dom.window.Event],
|
||||
['IS_REACT_ACT_ENVIRONMENT', true],
|
||||
] as const) {
|
||||
prevDescriptors.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, value });
|
||||
}
|
||||
|
||||
__resetIdbPersistenceForTests();
|
||||
markAiSessionsHydrationComplete();
|
||||
|
||||
if (options?.providers) {
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_PROVIDERS, JSON.stringify(options.providers));
|
||||
}
|
||||
if (options?.activeProviderId) {
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_ACTIVE_PROVIDER, options.activeProviderId);
|
||||
}
|
||||
if (options?.agentProviderMap) {
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_AGENT_PROVIDER_MAP, JSON.stringify(options.agentProviderMap));
|
||||
}
|
||||
if (options?.agentModelMap) {
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_AGENT_MODEL_MAP, JSON.stringify(options.agentModelMap));
|
||||
}
|
||||
if (options?.autoLlmTitle !== undefined) {
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_AUTO_LLM_TITLE, String(options.autoLlmTitle));
|
||||
}
|
||||
if (options?.titleModel) {
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_TITLE_MODEL, JSON.stringify(options.titleModel));
|
||||
}
|
||||
|
||||
const initialSessions = options?.sessions ?? [];
|
||||
setLatestAISessionsSnapshot(initialSessions);
|
||||
dom.window.localStorage.setItem('netcatty_ai_sessions_v1', JSON.stringify(initialSessions));
|
||||
|
||||
const container = dom.window.document.createElement('div');
|
||||
dom.window.document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
const capture: Capture = { ai: null, sessions: [] };
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
React.createElement(Harness, {
|
||||
capture,
|
||||
options: { generateSessionTitle: options?.generateSessionTitle },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
capture,
|
||||
cleanup: async () => {
|
||||
await act(async () => root.unmount());
|
||||
container.remove();
|
||||
dom.window.close();
|
||||
__resetIdbPersistenceForTests();
|
||||
for (const [key, desc] of prevDescriptors) {
|
||||
if (desc) Object.defineProperty(globalThis, key, desc);
|
||||
else delete (globalThis as Record<string, unknown>)[key];
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const providerA: ProviderConfig = {
|
||||
id: 'p-catty',
|
||||
providerId: 'openai',
|
||||
name: 'Main OpenAI',
|
||||
enabled: true,
|
||||
defaultModel: 'gpt-5.4',
|
||||
};
|
||||
|
||||
const providerB: ProviderConfig = {
|
||||
id: 'p-title',
|
||||
providerId: 'openai',
|
||||
name: 'Cheap Title',
|
||||
enabled: true,
|
||||
defaultModel: 'gpt-4o-mini',
|
||||
};
|
||||
|
||||
const untitledSession = (id = 's-1'): AISession => ({
|
||||
id,
|
||||
title: 'New Chat',
|
||||
agentId: 'catty',
|
||||
scope: { type: 'terminal', targetId: 'term-1' },
|
||||
messages: [{ id: 'm-1', role: 'user', content: 'Check slow SSH handshake on prod', timestamp: 1 }],
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
});
|
||||
|
||||
test('autoTitleSession preserves a user rename that happens while LLM title generation is pending', async () => {
|
||||
const pending = deferred<string>();
|
||||
let capturedSignal: AbortSignal | undefined;
|
||||
const { capture, cleanup } = await setupHook({
|
||||
sessions: [untitledSession()],
|
||||
providers: [providerA],
|
||||
activeProviderId: providerA.id,
|
||||
generateSessionTitle: async (_source, opts) => {
|
||||
capturedSignal = opts.signal;
|
||||
return pending.promise;
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
let titleTask!: Promise<void>;
|
||||
await act(async () => {
|
||||
titleTask = capture.ai!.autoTitleSession('s-1', 'Check slow SSH handshake on prod');
|
||||
});
|
||||
// Deterministic fallback landed immediately.
|
||||
assert.equal(capture.sessions[0].title, 'Check slow SSH handshake on prod');
|
||||
assert.equal(capturedSignal?.aborted, false);
|
||||
|
||||
// User renames the session (e.g. after closing & reopening the side panel).
|
||||
await act(async () => {
|
||||
capture.ai!.updateSessionTitle('s-1', 'Prod SSH Debug');
|
||||
});
|
||||
assert.equal(capturedSignal?.aborted, true, 'manual rename aborts pending LLM call');
|
||||
assert.equal(capture.sessions[0].title, 'Prod SSH Debug');
|
||||
|
||||
// Even if the LLM promise resolves with a generated title afterwards, it
|
||||
// must not overwrite the user's title.
|
||||
await act(async () => {
|
||||
pending.resolve('Slow SSH Handshake');
|
||||
await titleTask;
|
||||
});
|
||||
assert.equal(capture.sessions[0].title, 'Prod SSH Debug');
|
||||
} finally {
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('autoTitleSession promotes the LLM title when unrenamed and passes Catty or explicit titleModel config', async () => {
|
||||
const seenConfigs: Array<ProviderConfig | null | undefined> = [];
|
||||
const pending = deferred<string>();
|
||||
const { capture, cleanup } = await setupHook({
|
||||
sessions: [untitledSession('s-catty'), untitledSession('s-explicit')],
|
||||
providers: [providerB, providerA],
|
||||
activeProviderId: providerB.id,
|
||||
agentProviderMap: { catty: providerA.id },
|
||||
agentModelMap: { catty: 'gpt-5.4-turbo' },
|
||||
generateSessionTitle: async (_source, opts) => {
|
||||
seenConfigs.push(opts.config);
|
||||
return pending.promise;
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
let task!: Promise<void>;
|
||||
await act(async () => {
|
||||
task = capture.ai!.autoTitleSession('s-catty', 'Check slow SSH handshake on prod');
|
||||
});
|
||||
assert.equal(seenConfigs[0]?.id, providerA.id);
|
||||
assert.equal(seenConfigs[0]?.defaultModel, 'gpt-5.4-turbo');
|
||||
|
||||
await act(async () => {
|
||||
pending.resolve('SSH Handshake Audit');
|
||||
await task;
|
||||
});
|
||||
assert.equal(capture.sessions.find((s) => s.id === 's-catty')?.title, 'SSH Handshake Audit');
|
||||
|
||||
// Explicit titleModel overrides Catty model.
|
||||
await act(async () => {
|
||||
capture.ai!.setTitleModel({ providerId: providerB.id, modelId: 'gpt-4o-mini' });
|
||||
});
|
||||
await act(async () => {
|
||||
await capture.ai!.autoTitleSession('s-explicit', 'Inspect nginx error logs');
|
||||
});
|
||||
assert.equal(seenConfigs[1]?.id, providerB.id);
|
||||
assert.equal(seenConfigs[1]?.defaultModel, 'gpt-4o-mini');
|
||||
assert.equal(capture.sessions.find((s) => s.id === 's-explicit')?.title, 'SSH Handshake Audit');
|
||||
} finally {
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('autoTitleSession aborts and ignores deleted sessions, deduplicates concurrent calls, and skips titled chats', async () => {
|
||||
const pending = deferred<string>();
|
||||
let calls = 0;
|
||||
let signalRef: AbortSignal | undefined;
|
||||
const { capture, cleanup } = await setupHook({
|
||||
sessions: [
|
||||
untitledSession('s-del'),
|
||||
untitledSession('s-dup'),
|
||||
{ ...untitledSession('s-titled'), title: 'Already named' },
|
||||
],
|
||||
providers: [providerA],
|
||||
activeProviderId: providerA.id,
|
||||
generateSessionTitle: async (_source, opts) => {
|
||||
calls += 1;
|
||||
signalRef = opts.signal;
|
||||
return pending.promise;
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
// Titled chat skips both fallback and LLM.
|
||||
await act(async () => {
|
||||
await capture.ai!.autoTitleSession('s-titled', 'New prompt text');
|
||||
});
|
||||
assert.equal(calls, 0);
|
||||
assert.equal(capture.sessions.find((s) => s.id === 's-titled')?.title, 'Already named');
|
||||
|
||||
// Deleting a session aborts in-flight generation and never resurrects it.
|
||||
let delTask!: Promise<void>;
|
||||
await act(async () => {
|
||||
delTask = capture.ai!.autoTitleSession('s-del', 'Delete me mid-flight');
|
||||
});
|
||||
assert.equal(calls, 1);
|
||||
await act(async () => {
|
||||
capture.ai!.deleteSession('s-del');
|
||||
});
|
||||
assert.equal(signalRef?.aborted, true);
|
||||
await act(async () => {
|
||||
pending.resolve('Ghost title');
|
||||
await delTask;
|
||||
});
|
||||
assert.equal(capture.sessions.some((s) => s.id === 's-del'), false);
|
||||
|
||||
// Duplicate concurrent call for the same session only invokes LLM once.
|
||||
const pendingDup = deferred<string>();
|
||||
const dupHarness = await setupHook({
|
||||
sessions: [untitledSession('s-dup2')],
|
||||
providers: [providerA],
|
||||
activeProviderId: providerA.id,
|
||||
generateSessionTitle: async () => {
|
||||
calls += 1;
|
||||
return pendingDup.promise;
|
||||
},
|
||||
});
|
||||
try {
|
||||
let t1!: Promise<void>;
|
||||
let t2!: Promise<void>;
|
||||
await act(async () => {
|
||||
t1 = dupHarness.capture.ai!.autoTitleSession('s-dup2', 'First call');
|
||||
t2 = dupHarness.capture.ai!.autoTitleSession('s-dup2', 'Second call');
|
||||
});
|
||||
assert.equal(calls, 2);
|
||||
await act(async () => {
|
||||
pendingDup.resolve('Single Title');
|
||||
await Promise.all([t1, t2]);
|
||||
});
|
||||
assert.equal(dupHarness.capture.sessions.find((s) => s.id === 's-dup2')?.title, 'Single Title');
|
||||
} finally {
|
||||
await dupHarness.cleanup();
|
||||
}
|
||||
} finally {
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('autoTitleSession respects autoLlmTitle=false and removeProvider clears dangling titleModel', async () => {
|
||||
let calls = 0;
|
||||
const { capture, cleanup } = await setupHook({
|
||||
sessions: [untitledSession('s-off')],
|
||||
providers: [providerA, providerB],
|
||||
activeProviderId: providerA.id,
|
||||
autoLlmTitle: false,
|
||||
titleModel: { providerId: providerB.id, modelId: 'gpt-4o-mini' },
|
||||
generateSessionTitle: async () => {
|
||||
calls += 1;
|
||||
return 'Should not run';
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
await capture.ai!.autoTitleSession('s-off', 'Fallback only please');
|
||||
});
|
||||
assert.equal(calls, 0);
|
||||
assert.equal(capture.sessions[0].title, 'Fallback only please');
|
||||
|
||||
assert.deepEqual(capture.ai!.titleModel, { providerId: providerB.id, modelId: 'gpt-4o-mini' });
|
||||
await act(async () => {
|
||||
capture.ai!.removeProvider(providerB.id);
|
||||
});
|
||||
assert.equal(capture.ai!.titleModel, null);
|
||||
} finally {
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
@@ -98,8 +98,20 @@ import {
|
||||
buildUndoLastTurnBranch,
|
||||
type UndoLastTurnRestoredDraft,
|
||||
} from '../../domain/aiUndoLastTurn';
|
||||
import {
|
||||
applySessionTitleIfCurrent,
|
||||
buildFallbackTitle,
|
||||
canAutoTitleSession,
|
||||
resolveEffectiveTitleModelConfig,
|
||||
} from '../../domain/aiSessionTitle';
|
||||
import type { generateSessionLlmTitle as GenerateSessionLlmTitleFn } from '../../infrastructure/ai/sessionTitleGeneration';
|
||||
|
||||
export function useAIState() {
|
||||
export interface UseAIStateOptions {
|
||||
/** Optional test injection for one-shot LLM title generation. */
|
||||
generateSessionTitle?: typeof GenerateSessionLlmTitleFn;
|
||||
}
|
||||
|
||||
export function useAIState(options?: UseAIStateOptions) {
|
||||
const [hostPermissions, setHostPermissionsRaw] = useState<HostAIPermission[]>(() =>
|
||||
localStorageAdapter.read<HostAIPermission[]>(STORAGE_KEY_AI_HOST_PERMISSIONS) ?? []
|
||||
);
|
||||
@@ -402,11 +414,35 @@ export function useAIState() {
|
||||
setWebSearchConfig,
|
||||
quickMessages,
|
||||
setQuickMessages,
|
||||
autoLlmTitle,
|
||||
setAutoLlmTitle,
|
||||
titleModel,
|
||||
setTitleModel,
|
||||
} = useSharedAISettingsState({
|
||||
ignoreInvalidPermissionModeOnStorage: true,
|
||||
onRemoveProvider: handleRemoveProviderReferences,
|
||||
});
|
||||
|
||||
const providersRef = useRef(providers);
|
||||
providersRef.current = providers;
|
||||
const activeProviderIdRef = useRef(activeProviderId);
|
||||
activeProviderIdRef.current = activeProviderId;
|
||||
const activeModelIdRef = useRef(activeModelId);
|
||||
activeModelIdRef.current = activeModelId;
|
||||
const autoLlmTitleRef = useRef(autoLlmTitle);
|
||||
autoLlmTitleRef.current = autoLlmTitle;
|
||||
const titleModelRef = useRef(titleModel);
|
||||
titleModelRef.current = titleModel;
|
||||
const generateSessionTitleRef = useRef(options?.generateSessionTitle);
|
||||
generateSessionTitleRef.current = options?.generateSessionTitle;
|
||||
const pendingCreatedSessionIdsRef = useRef<Set<string>>(new Set());
|
||||
const titleAbortControllersRef = useRef<Map<string, AbortController>>(new Map());
|
||||
useEffect(() => {
|
||||
for (const session of sessions) {
|
||||
pendingCreatedSessionIdsRef.current.delete(session.id);
|
||||
}
|
||||
}, [sessions]);
|
||||
|
||||
useEffect(() => {
|
||||
setLatestAISessionsSnapshot(sessions);
|
||||
}, [sessions]);
|
||||
@@ -724,6 +760,14 @@ export function useAIState() {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
// Keep the source workspace name when the fork stays in that workspace;
|
||||
// a fork into a different/terminal scope must not inherit a stale name.
|
||||
if (
|
||||
source.workspaceNameSnapshot
|
||||
&& (!viewingScope || (viewingScope.type === 'workspace' && viewingScope.targetId === source.scope.targetId))
|
||||
) {
|
||||
fork.workspaceNameSnapshot = source.workspaceNameSnapshot;
|
||||
}
|
||||
if (plan.contextCompaction) {
|
||||
fork.contextCompaction = plan.contextCompaction;
|
||||
}
|
||||
@@ -739,17 +783,25 @@ export function useAIState() {
|
||||
return fork;
|
||||
}, [persistSessions, setActiveSessionId]);
|
||||
|
||||
const createSession = useCallback((scope: AISessionScope, agentId?: string): AISession => {
|
||||
const createSession = useCallback((
|
||||
scope: AISessionScope,
|
||||
agentId?: string,
|
||||
workspaceNameSnapshot?: string,
|
||||
): AISession => {
|
||||
const now = Date.now();
|
||||
const session: AISession = {
|
||||
id: `ai_${now}_${Math.random().toString(36).slice(2, 8)}`,
|
||||
title: 'New Chat',
|
||||
agentId: agentId || defaultAgentId,
|
||||
scope,
|
||||
...(scope.type === 'workspace' && workspaceNameSnapshot
|
||||
? { workspaceNameSnapshot }
|
||||
: {}),
|
||||
messages: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
pendingCreatedSessionIdsRef.current.add(session.id);
|
||||
setSessionsRaw(prev => {
|
||||
const next = [session, ...prev];
|
||||
setLatestAISessionsSnapshot(next);
|
||||
@@ -796,6 +848,12 @@ export function useAIState() {
|
||||
}, [persistSessions, setActiveSessionId]);
|
||||
|
||||
const deleteSession = useCallback((sessionId: string, scopeKey?: string) => {
|
||||
pendingCreatedSessionIdsRef.current.delete(sessionId);
|
||||
const pendingTitleController = titleAbortControllersRef.current.get(sessionId);
|
||||
if (pendingTitleController) {
|
||||
titleAbortControllersRef.current.delete(sessionId);
|
||||
pendingTitleController.abort();
|
||||
}
|
||||
cleanupDeletedAIChatSessions([sessionId]);
|
||||
if (persistTimerRef.current) {
|
||||
clearTimeout(persistTimerRef.current);
|
||||
@@ -838,6 +896,14 @@ export function useAIState() {
|
||||
const removedSessionIds = sessionsRef.current
|
||||
.filter(s => s.scope.type === scopeType && s.scope.targetId === targetId)
|
||||
.map(s => s.id);
|
||||
for (const removedId of removedSessionIds) {
|
||||
pendingCreatedSessionIdsRef.current.delete(removedId);
|
||||
const pendingTitleController = titleAbortControllersRef.current.get(removedId);
|
||||
if (pendingTitleController) {
|
||||
titleAbortControllersRef.current.delete(removedId);
|
||||
pendingTitleController.abort();
|
||||
}
|
||||
}
|
||||
cleanupDeletedAIChatSessions(removedSessionIds);
|
||||
if (persistTimerRef.current) {
|
||||
clearTimeout(persistTimerRef.current);
|
||||
@@ -865,6 +931,12 @@ export function useAIState() {
|
||||
}, [persistSessions]);
|
||||
|
||||
const updateSessionTitle = useCallback((sessionId: string, title: string) => {
|
||||
// Manual rename supersedes any in-flight automatic title generation.
|
||||
const pendingTitleController = titleAbortControllersRef.current.get(sessionId);
|
||||
if (pendingTitleController) {
|
||||
titleAbortControllersRef.current.delete(sessionId);
|
||||
pendingTitleController.abort();
|
||||
}
|
||||
setSessionsRaw(prev => {
|
||||
const next = prev.map(s => s.id === sessionId ? { ...s, title, updatedAt: Date.now() } : s);
|
||||
setLatestAISessionsSnapshot(next);
|
||||
@@ -873,12 +945,125 @@ export function useAIState() {
|
||||
});
|
||||
}, [persistSessions]);
|
||||
|
||||
/**
|
||||
* Auto-title a session if it still carries the placeholder title. Writes a
|
||||
* deterministic fallback immediately, then (when enabled and a model is
|
||||
* configured) upgrades it with a one-shot LLM summary. Lives in application
|
||||
* state so panel close/reopen cannot break the in-flight lifecycle, and
|
||||
* compares against live state atomically so a user rename always wins.
|
||||
*/
|
||||
const autoTitleSession = useCallback(async (
|
||||
sessionId: string,
|
||||
text: string,
|
||||
callerSignal?: AbortSignal,
|
||||
): Promise<void> => {
|
||||
if (!sessionId) return;
|
||||
if (titleAbortControllersRef.current.has(sessionId)) return;
|
||||
|
||||
const snapshot = latestAISessionsSnapshot ?? sessionsRef.current;
|
||||
const existing = snapshot.find((s) => s.id === sessionId);
|
||||
if (existing && !canAutoTitleSession(existing)) return;
|
||||
if (!existing && !pendingCreatedSessionIdsRef.current.has(sessionId)) return;
|
||||
|
||||
const fallback = buildFallbackTitle(text);
|
||||
|
||||
// Phase 1: Atomically apply the deterministic fallback while still untitled.
|
||||
setSessionsRaw((prev) => {
|
||||
const result = applySessionTitleIfCurrent(prev, sessionId, fallback);
|
||||
if (!result.updated) return prev;
|
||||
setLatestAISessionsSnapshot(result.sessions);
|
||||
persistSessions(result.sessions);
|
||||
return result.sessions;
|
||||
});
|
||||
|
||||
if (!autoLlmTitleRef.current || callerSignal?.aborted) return;
|
||||
|
||||
const resolvedTitleConfig = resolveEffectiveTitleModelConfig({
|
||||
titleModel: titleModelRef.current,
|
||||
providers: providersRef.current,
|
||||
activeProviderId: activeProviderIdRef.current,
|
||||
activeModelId: activeModelIdRef.current,
|
||||
agentProviderMap: agentProviderMapRef.current,
|
||||
agentModelMap: agentModelMapRef.current,
|
||||
});
|
||||
if (!resolvedTitleConfig) return;
|
||||
|
||||
const requestController = new AbortController();
|
||||
titleAbortControllersRef.current.set(sessionId, requestController);
|
||||
const onCallerAbort = () => requestController.abort();
|
||||
if (callerSignal) {
|
||||
callerSignal.addEventListener('abort', onCallerAbort, { once: true });
|
||||
}
|
||||
|
||||
try {
|
||||
const latestBeforeCall = (latestAISessionsSnapshot ?? sessionsRef.current)
|
||||
.find((s) => s.id === sessionId);
|
||||
if (
|
||||
latestBeforeCall
|
||||
&& !canAutoTitleSession(latestBeforeCall)
|
||||
&& latestBeforeCall.title !== fallback
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const sourceMessages = latestBeforeCall?.messages?.length
|
||||
? latestBeforeCall.messages
|
||||
: (text ? [{ role: 'user' as const, content: text }] : []);
|
||||
if (sourceMessages.length === 0) return;
|
||||
|
||||
const generateTitle = generateSessionTitleRef.current
|
||||
?? (await import('../../infrastructure/ai/sessionTitleGeneration')).generateSessionLlmTitle;
|
||||
|
||||
const generated = await generateTitle(
|
||||
{ messages: sourceMessages },
|
||||
{
|
||||
config: resolvedTitleConfig,
|
||||
chatSessionId: sessionId,
|
||||
signal: requestController.signal,
|
||||
},
|
||||
);
|
||||
|
||||
if (requestController.signal.aborted || !generated || generated === fallback) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Phase 2: Atomically promote the LLM title only if the session still
|
||||
// exists and still holds the exact fallback title applied in Phase 1.
|
||||
if (mountedRef.current) {
|
||||
setSessionsRaw((prev) => {
|
||||
const result = applySessionTitleIfCurrent(prev, sessionId, generated, fallback);
|
||||
if (!result.updated) return prev;
|
||||
setLatestAISessionsSnapshot(result.sessions);
|
||||
persistSessions(result.sessions);
|
||||
return result.sessions;
|
||||
});
|
||||
} else {
|
||||
const current = latestAISessionsSnapshot ?? getPersistedAiSessionsSnapshot();
|
||||
const result = applySessionTitleIfCurrent(current, sessionId, generated, fallback);
|
||||
if (result.updated) {
|
||||
setLatestAISessionsSnapshot(result.sessions);
|
||||
persistSessions(result.sessions);
|
||||
emitAIStateChanged(STORAGE_KEY_AI_SESSIONS);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Generation never throws; fallback was already applied above.
|
||||
} finally {
|
||||
if (callerSignal) {
|
||||
callerSignal.removeEventListener('abort', onCallerAbort);
|
||||
}
|
||||
if (titleAbortControllersRef.current.get(sessionId) === requestController) {
|
||||
titleAbortControllersRef.current.delete(sessionId);
|
||||
}
|
||||
}
|
||||
}, [persistSessions]);
|
||||
|
||||
// Issue #4015 R2: rebind a dangling chat to the panel's current scope.
|
||||
// Rewrites `scope`, clears the dangling marker and makes the chat the
|
||||
// active session of its new scope so it shows in the scoped history again.
|
||||
const rebindSessionScope = useCallback((
|
||||
sessionId: string,
|
||||
scope: { type: 'terminal' | 'workspace'; targetId: string; hostIds?: string[] },
|
||||
workspaceNameSnapshot?: string,
|
||||
) => {
|
||||
const scopeKey = `${scope.type}:${scope.targetId}`;
|
||||
// Capture the PRE-rebind active map before rebindActiveSessionMap drops the
|
||||
@@ -903,9 +1088,15 @@ export function useAIState() {
|
||||
if (scope.hostIds && scope.hostIds.length > 0) {
|
||||
nextScope.hostIds = [...scope.hostIds];
|
||||
}
|
||||
// Snapshot follows the binding: keep it only for workspace scopes.
|
||||
// `rest` may still carry a stale snapshot from a previous workspace.
|
||||
const { workspaceNameSnapshot: _staleSnapshot, ...withoutSnapshot } = rest;
|
||||
return {
|
||||
...rest,
|
||||
...withoutSnapshot,
|
||||
scope: nextScope,
|
||||
...(scope.type === 'workspace' && workspaceNameSnapshot
|
||||
? { workspaceNameSnapshot }
|
||||
: {}),
|
||||
updatedAt: Date.now(),
|
||||
} as AISession;
|
||||
});
|
||||
@@ -1453,6 +1644,10 @@ export function useAIState() {
|
||||
setWebSearchConfig,
|
||||
quickMessages,
|
||||
setQuickMessages,
|
||||
autoLlmTitle,
|
||||
setAutoLlmTitle,
|
||||
titleModel,
|
||||
setTitleModel,
|
||||
// sessions / activeSessionIdMap / draftsByScope / panelViewByScope live in
|
||||
// aiSessionsStore so streaming updates do not rebuild this config object.
|
||||
setActiveSessionId,
|
||||
@@ -1468,6 +1663,7 @@ export function useAIState() {
|
||||
deleteSession,
|
||||
deleteSessionsByTarget,
|
||||
updateSessionTitle,
|
||||
autoTitleSession,
|
||||
rebindSessionScope,
|
||||
exportSessionsBackup,
|
||||
importSessionsBackup,
|
||||
@@ -1522,6 +1718,10 @@ export function useAIState() {
|
||||
setWebSearchConfig,
|
||||
quickMessages,
|
||||
setQuickMessages,
|
||||
autoLlmTitle,
|
||||
setAutoLlmTitle,
|
||||
titleModel,
|
||||
setTitleModel,
|
||||
setActiveSessionId,
|
||||
ensureDraftForScope,
|
||||
updateDraft,
|
||||
@@ -1535,6 +1735,7 @@ export function useAIState() {
|
||||
deleteSession,
|
||||
deleteSessionsByTarget,
|
||||
updateSessionTitle,
|
||||
autoTitleSession,
|
||||
rebindSessionScope,
|
||||
exportSessionsBackup,
|
||||
importSessionsBackup,
|
||||
|
||||
@@ -122,7 +122,7 @@ export function useComposeDirectoryPicker(sessionId: string) {
|
||||
const filtered = useMemo(() => filterDirectories(entries, query, showHidden), [entries, query, showHidden]);
|
||||
const cwdError = controller?.getCwdError() ?? null;
|
||||
const waitsForCwd = error === 'unknown' || error === 'integrationUnavailable' || error === 'cmdIntegrationUnavailable'
|
||||
|| error === 'gitBashIntegrationUnavailable' || error === 'wslIntegrationUnavailable' || error === 'nonFilesystem';
|
||||
|| error === 'gitBashIntegrationUnavailable' || error === 'wslIntegrationUnavailable' || error === 'cygwinIntegrationUnavailable' || error === 'nonFilesystem';
|
||||
return { cwd, home, display, pathFlavor, open, setOpen, query, setQuery, showHidden, setShowHidden, entries: filtered,
|
||||
parent: cwd ? directoryParent(cwd, pathFlavor) : null, loading, pending,
|
||||
error: cwdError ?? (cwd && waitsForCwd ? null : error),
|
||||
|
||||
@@ -16,7 +16,10 @@ export const checkAppShortcut = (
|
||||
return null;
|
||||
};
|
||||
|
||||
// Get list of key bindings that should be handled at app level (not by terminal)
|
||||
// Get list of key bindings that should be handled at app level (not by terminal).
|
||||
// Conditional shortcuts that pass through to the terminal when unavailable
|
||||
// (like toggleHostTree and addSessionToWorkspace) stay out so an unconsumed
|
||||
// chord still gets full Kitty/Win32/broadcast handling in xterm.
|
||||
export const getAppLevelActions = (): Set<string> => {
|
||||
return new Set([
|
||||
'switchToTab',
|
||||
|
||||
@@ -39,7 +39,11 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
|
||||
try {
|
||||
const session = pluginViewSessions.acquire(JSON.stringify([resolvedScopeId, key]), bridge, { viewId, scopeId: resolvedScopeId, context: JSON.parse(contextKey) });
|
||||
sessionRef.current = { key, send: session.send, image: session.image };
|
||||
const update = () => { const snapshot = session.getSnapshot(); setState({ key, snapshot, image: session.image }); if (snapshot.error) unavailableRef.current(); };
|
||||
const update = () => {
|
||||
const snapshot = session.getSnapshot();
|
||||
if (snapshot.error) sessionRef.current = null;
|
||||
setState({ key, snapshot, image: session.image });
|
||||
};
|
||||
const stop = session.subscribe(update); update(); setHidden(false);
|
||||
const stopHidden = subscribeHidden(() => { sessionRef.current = null; setHidden(true); });
|
||||
return () => { sessionRef.current = null; stopHidden(); stop(); session.release(); };
|
||||
@@ -49,7 +53,9 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
|
||||
const session = sessionRef.current;
|
||||
return active && session?.key === key ? session.image(path) : Promise.reject(new Error('Plugin view unavailable'));
|
||||
}, [active, key]);
|
||||
const hasCurrentState = active && state.key === key && cachedSession !== null && state.image === cachedSession.image;
|
||||
const hasCurrentState = active
|
||||
&& state.key === key
|
||||
&& (cachedSession !== null ? state.image === cachedSession.image : state.snapshot.error);
|
||||
const resolvedSnapshot = hasCurrentState
|
||||
? state.snapshot
|
||||
: cachedSession
|
||||
|
||||
@@ -26,6 +26,7 @@ export const OPEN_PLUGIN_VIEW_EVENT = 'netcatty:open-plugin-view';
|
||||
export interface OpenPluginViewDetail {
|
||||
viewId: string;
|
||||
context?: Record<string, unknown>;
|
||||
params?: unknown;
|
||||
}
|
||||
|
||||
export type ResolvedPluginView = {
|
||||
|
||||
@@ -88,6 +88,7 @@ import {
|
||||
STORAGE_KEY_SHOW_ONLY_UNGROUPED_HOSTS_IN_ROOT,
|
||||
STORAGE_KEY_SHOW_SFTP_TAB,
|
||||
STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR,
|
||||
STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA,
|
||||
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN,
|
||||
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB,
|
||||
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN,
|
||||
@@ -145,6 +146,7 @@ import {
|
||||
DEFAULT_HOST_CLICK_BEHAVIOR,
|
||||
DEFAULT_SHOW_SFTP_TAB,
|
||||
DEFAULT_SHOW_HOST_TREE_SIDEBAR,
|
||||
DEFAULT_REMOVE_TOP_TABS_DRAG_AREA,
|
||||
DEFAULT_SHELL_ONLY_TAB_NUMBER_SHORTCUTS,
|
||||
DEFAULT_SHOW_TAB_NUMBER_BADGES,
|
||||
DEFAULT_DISABLE_TERMINAL_FONT_ZOOM,
|
||||
@@ -472,6 +474,10 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
const stored = localStorageAdapter.readBoolean(STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR);
|
||||
return stored ?? DEFAULT_SHOW_HOST_TREE_SIDEBAR;
|
||||
});
|
||||
const [removeTopTabsDragArea, setRemoveTopTabsDragAreaState] = useState<boolean>(() => {
|
||||
const stored = localStorageAdapter.readBoolean(STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA);
|
||||
return stored ?? DEFAULT_REMOVE_TOP_TABS_DRAG_AREA;
|
||||
});
|
||||
const [terminalSidePanelAutoOpen, setTerminalSidePanelAutoOpenState] = useState<boolean>(() => {
|
||||
const stored = localStorageAdapter.readBoolean(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN);
|
||||
return stored ?? DEFAULT_TERMINAL_SIDE_PANEL_AUTO_OPEN_ENABLED;
|
||||
@@ -1186,6 +1192,8 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
setShowSftpTabState(storedShowSftpTab ?? DEFAULT_SHOW_SFTP_TAB);
|
||||
const storedShowHostTreeSidebar = localStorageAdapter.readBoolean(STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR);
|
||||
setShowHostTreeSidebarState(storedShowHostTreeSidebar ?? DEFAULT_SHOW_HOST_TREE_SIDEBAR);
|
||||
const storedRemoveTopTabsDragArea = localStorageAdapter.readBoolean(STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA);
|
||||
setRemoveTopTabsDragAreaState(storedRemoveTopTabsDragArea ?? DEFAULT_REMOVE_TOP_TABS_DRAG_AREA);
|
||||
const storedTerminalSidePanelAutoOpen = localStorageAdapter.readBoolean(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN);
|
||||
setTerminalSidePanelAutoOpenState(storedTerminalSidePanelAutoOpen ?? DEFAULT_TERMINAL_SIDE_PANEL_AUTO_OPEN_ENABLED);
|
||||
const storedTerminalSidePanelAutoOpenTab = readStoredString(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB);
|
||||
@@ -1489,7 +1497,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
|
||||
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
|
||||
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, removeTopTabsDragArea, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
|
||||
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
|
||||
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
|
||||
@@ -1501,7 +1509,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
setFollowAppTerminalThemeState, setTerminalFontFamilyId, setTerminalFontSize: applyIncomingTerminalFontSize,
|
||||
setSftpDoubleClickBehavior, setSftpAutoSync, setSftpShowHiddenFiles,
|
||||
setSftpUseCompressedUpload, setSftpSkipUnchanged, setSftpAutoOpenSidebar, setSftpFollowTerminalCwd, setSftpDefaultViewMode,
|
||||
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
|
||||
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setRemoveTopTabsDragAreaState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
|
||||
setEditorWordWrapState, setSessionLogsEnabled, setSessionLogsDir, setSessionLogsFormat, setSessionLogsTimestampsEnabled,
|
||||
setRemoteDesktopAutoRecordState, setRemoteDesktopRecordingFpsState, setRemoteDesktopRecordingIncludeAudioState, setRemoteDesktopRecordingMaxMbState, setRemoteDesktopRecordingRetentionDaysState,
|
||||
setSshDebugLogsEnabled, setSshDeepLinkEnabledState: applyIncomingSshDeepLinkEnabled, setJmsDeepLinkEnabledState: applyIncomingJmsDeepLinkEnabled, setJumpServerRdpLaunchModeState, setExplorerContextMenuEnabledState: applyIncomingExplorerContextMenuEnabled,
|
||||
@@ -1647,6 +1655,13 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
notifySettingsChanged(STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR, enabled);
|
||||
}, [notifySettingsChanged]);
|
||||
|
||||
const setRemoveTopTabsDragArea = useCallback((enabled: boolean) => {
|
||||
setRemoveTopTabsDragAreaState(enabled);
|
||||
localStorageAdapter.writeBoolean(STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA, enabled);
|
||||
if (!persistMountedRef.current) return;
|
||||
notifySettingsChanged(STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA, enabled);
|
||||
}, [notifySettingsChanged]);
|
||||
|
||||
const setTerminalSidePanelAutoOpen = useCallback((enabled: boolean) => {
|
||||
setTerminalSidePanelAutoOpenState(enabled);
|
||||
localStorageAdapter.writeBoolean(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN, enabled);
|
||||
@@ -2181,6 +2196,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
windowOpacity,
|
||||
showSftpTab,
|
||||
showHostTreeSidebar,
|
||||
removeTopTabsDragArea,
|
||||
showRecentHosts,
|
||||
hostClickBehavior,
|
||||
showOnlyUngroupedHostsInRoot,
|
||||
@@ -2205,6 +2221,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
restoreTerminalCwd,
|
||||
shellOnlyTabNumberShortcuts,
|
||||
showHostTreeSidebar,
|
||||
removeTopTabsDragArea,
|
||||
showOnlyUngroupedHostsInRoot,
|
||||
showRecentHosts,
|
||||
showSftpTab,
|
||||
@@ -2385,6 +2402,8 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
setShowSftpTab,
|
||||
showHostTreeSidebar,
|
||||
setShowHostTreeSidebar,
|
||||
removeTopTabsDragArea,
|
||||
setRemoveTopTabsDragArea,
|
||||
terminalSidePanelAutoOpen,
|
||||
setTerminalSidePanelAutoOpen,
|
||||
terminalSidePanelAutoOpenTab,
|
||||
|
||||
@@ -11,11 +11,11 @@ type SessionProps = Parameters<typeof useTerminalDirectorySession>[0];
|
||||
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
|
||||
|
||||
function installBridge(t: TestContext, getAppInfo?: NetcattyBridge['getAppInfo']) {
|
||||
function installBridge(t: TestContext, getAppInfo?: NetcattyBridge['getAppInfo'], discoverShells?: NetcattyBridge['discoverShells']) {
|
||||
const previous = Object.getOwnPropertyDescriptor(globalThis, 'window');
|
||||
let probes = 0; let lists = 0;
|
||||
Object.defineProperty(globalThis, 'window', { configurable: true, value: { netcatty: {
|
||||
getAppInfo,
|
||||
getAppInfo, discoverShells,
|
||||
getSessionPwd: async () => { probes++; return { success: true, cwd: '/actual' }; },
|
||||
listLocalDir: async () => { lists++; return []; },
|
||||
} } });
|
||||
@@ -55,6 +55,19 @@ for (const wrapper of ['wsl-Ubuntu', 'git-bash', 'cygwin']) {
|
||||
});
|
||||
}
|
||||
|
||||
test('a discovered Cygwin terminal registers its own POSIX directory controller', async t => {
|
||||
installBridge(t, async () => ({ name: 'Netcatty', version: 'test', platform: 'win32' }), async () => [
|
||||
{ id: 'cygwin', name: 'Cygwin', command: 'C:/cygwin64/bin/bash.exe', args: ['--login', '-i'], icon: 'cygwin' },
|
||||
]);
|
||||
const props = options('cygwin-tab');
|
||||
props.host = { ...props.host, localShell: 'cygwin' };
|
||||
function Harness() { useTerminalDirectorySession(props); return null; }
|
||||
let root!: ReactTestRenderer;
|
||||
await act(async () => { root = create(React.createElement(Harness)); });
|
||||
t.after(async () => { await act(async () => { root.unmount(); }); });
|
||||
assert.deepEqual(getTerminalDirectory(props.sessionId)?.target, { authority: 'cygwin:cygwin-tab', pathFlavor: 'posix' });
|
||||
});
|
||||
|
||||
for (const platform of ['linux', 'darwin']) {
|
||||
test(`local POSIX directory controller registers on ${platform}`, async t => {
|
||||
installBridge(t, async () => ({ name: 'Netcatty', version: 'test', platform }));
|
||||
|
||||
@@ -7,7 +7,7 @@ import { createTerminalDirectoryController } from './terminalDirectoryController
|
||||
import { registerTerminalDirectory } from './terminalDirectoryRegistry';
|
||||
import { directoryChangeCommand, COMPLETE_DIRECTORY_CAPABILITIES, type WindowsDirectoryShell } from '../../domain/directoryPicker';
|
||||
import type { DirectoryPathFlavor } from '../../domain/directoryPath';
|
||||
import { isDiscoveredGitBash } from '../../lib/localShell';
|
||||
import { isDiscoveredCygwin, isDiscoveredGitBash } from '../../lib/localShell';
|
||||
|
||||
export function useTerminalDirectorySession(options: {
|
||||
sessionId: string;
|
||||
@@ -36,6 +36,7 @@ export function useTerminalDirectorySession(options: {
|
||||
let unregister = () => {};
|
||||
const register = (pathFlavor: DirectoryPathFlavor = 'posix', integration?: WindowsDirectoryShell) => {
|
||||
if (!isCurrent()) return;
|
||||
const sessionFilesystem = integration === 'wsl' || integration === 'cygwin';
|
||||
const controller = createTerminalDirectoryController({
|
||||
sessionId,
|
||||
io: createTerminalDirectoryIO(bridge, backendId, {
|
||||
@@ -44,8 +45,8 @@ export function useTerminalDirectorySession(options: {
|
||||
pathFlavor,
|
||||
windowsShell: integration,
|
||||
}, isCurrent),
|
||||
target: { authority: `${integration === 'wsl' ? 'wsl' : local ? 'local' : 'ssh'}:${backendId}`, pathFlavor },
|
||||
trustOsc7: integration !== 'wsl',
|
||||
target: { authority: `${sessionFilesystem ? integration : local ? 'local' : 'ssh'}:${backendId}`, pathFlavor },
|
||||
trustOsc7: !sessionFilesystem,
|
||||
capabilities: COMPLETE_DIRECTORY_CAPABILITIES,
|
||||
buildChangeCommand: path => directoryChangeCommand(path, integration ?? 'posix', pathFlavor),
|
||||
isCurrent,
|
||||
@@ -67,6 +68,8 @@ export function useTerminalDirectorySession(options: {
|
||||
register('posix', 'wsl');
|
||||
} else if (isDiscoveredGitBash(host.localShell, shells?.find(item => item.id === 'git-bash')?.command)) {
|
||||
register('win32', 'git-bash');
|
||||
} else if (isDiscoveredCygwin(host.localShell, shells?.find(item => item.id === 'cygwin')?.command)) {
|
||||
register('posix', 'cygwin');
|
||||
}
|
||||
}
|
||||
}).catch(() => {});
|
||||
|
||||
@@ -4,6 +4,8 @@ import { JSDOM } from 'jsdom';
|
||||
|
||||
const DB_PLUGIN = 'plugin-vault:com.binaricat.netcatty-database.main' as const;
|
||||
const MONITOR_PLUGIN = 'plugin-vault:com.binaricat.netcatty-monitor.main' as const;
|
||||
const OFFICIAL_DB_PLUGIN = 'plugin-vault:com.binaricat.netcatty-database.workbench' as const;
|
||||
const OFFICIAL_MONITOR_PLUGIN = 'plugin-vault:com.binaricat.netcatty-monitor.workbench' as const;
|
||||
|
||||
test('useVaultNavConfig persists order & visibility, survives cold-start loading, prunes uninstalled plugins, and resets cleanly', async () => {
|
||||
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost' });
|
||||
@@ -30,9 +32,10 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
|
||||
let model!: ReturnType<typeof useVaultNavConfig>;
|
||||
let activePluginIds: (typeof DB_PLUGIN | typeof MONITOR_PLUGIN)[] = [DB_PLUGIN, MONITOR_PLUGIN];
|
||||
let pluginsLoading = false;
|
||||
let pluginsAvailable = true;
|
||||
|
||||
function Fixture() {
|
||||
model = useVaultNavConfig({ activePluginIds, pluginsLoading });
|
||||
model = useVaultNavConfig({ activePluginIds, pluginsLoading, pluginsAvailable });
|
||||
return <div />;
|
||||
}
|
||||
|
||||
@@ -83,6 +86,7 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
|
||||
const coldRoot = createRoot(document.getElementById('root')!);
|
||||
activePluginIds = [];
|
||||
pluginsLoading = true;
|
||||
pluginsAvailable = false;
|
||||
await act(async () => {
|
||||
coldRoot.render(<Fixture />);
|
||||
});
|
||||
@@ -93,6 +97,7 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
|
||||
// Plugins finish loading, but DB_PLUGIN was uninstalled.
|
||||
activePluginIds = [MONITOR_PLUGIN];
|
||||
pluginsLoading = false;
|
||||
pluginsAvailable = true;
|
||||
await act(async () => {
|
||||
coldRoot.render(<Fixture />);
|
||||
});
|
||||
@@ -122,3 +127,125 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('useVaultNavConfig preserves saved plugin order when settled with pluginsAvailable=false and restores slots once plugins become available', async () => {
|
||||
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost' });
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const key of ['window', 'document', 'navigator', 'localStorage', 'StorageEvent', 'CustomEvent', 'Event']) {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window],
|
||||
});
|
||||
}
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: true,
|
||||
});
|
||||
|
||||
const { default: React, act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { useVaultNavConfig } = await import('./useVaultNavConfig');
|
||||
const { STORAGE_KEY_VAULT_NAV_CONFIG } = await import('../../infrastructure/config/storageKeys');
|
||||
|
||||
let model!: ReturnType<typeof useVaultNavConfig>;
|
||||
let activePluginIds: (typeof OFFICIAL_DB_PLUGIN | typeof OFFICIAL_MONITOR_PLUGIN)[] = [
|
||||
OFFICIAL_DB_PLUGIN,
|
||||
OFFICIAL_MONITOR_PLUGIN,
|
||||
];
|
||||
let pluginsLoading = false;
|
||||
let pluginsAvailable: boolean | undefined = true;
|
||||
|
||||
function Fixture() {
|
||||
model = useVaultNavConfig({ activePluginIds, pluginsLoading, pluginsAvailable });
|
||||
return <div />;
|
||||
}
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<Fixture />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
model.reorder(OFFICIAL_MONITOR_PLUGIN, 'hosts', 'after');
|
||||
model.setVisible('logs', false);
|
||||
});
|
||||
assert.equal(model.visibleIds[1], OFFICIAL_MONITOR_PLUGIN);
|
||||
assert.equal(model.isHidden('logs'), true);
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
|
||||
const restartedRoot = createRoot(document.getElementById('root')!);
|
||||
activePluginIds = [];
|
||||
pluginsLoading = false;
|
||||
pluginsAvailable = false;
|
||||
await act(async () => {
|
||||
restartedRoot.render(
|
||||
<React.StrictMode>
|
||||
<Fixture />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
});
|
||||
|
||||
assert.equal(model.visibleIds.includes(OFFICIAL_MONITOR_PLUGIN), false);
|
||||
assert.equal(model.visibleIds.includes(OFFICIAL_DB_PLUGIN), false);
|
||||
assert.equal(model.config.order[1], OFFICIAL_MONITOR_PLUGIN);
|
||||
assert.equal(model.config.order.includes(OFFICIAL_DB_PLUGIN), true);
|
||||
|
||||
const persistedUnavailable = JSON.parse(
|
||||
dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}',
|
||||
);
|
||||
assert.equal(persistedUnavailable.order[1], OFFICIAL_MONITOR_PLUGIN);
|
||||
assert.equal(persistedUnavailable.order.includes(OFFICIAL_DB_PLUGIN), true);
|
||||
assert.deepEqual(persistedUnavailable.hidden, ['logs']);
|
||||
|
||||
pluginsAvailable = undefined;
|
||||
await act(async () => {
|
||||
restartedRoot.render(
|
||||
<React.StrictMode>
|
||||
<Fixture />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
});
|
||||
const persistedDefault = JSON.parse(
|
||||
dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}',
|
||||
);
|
||||
assert.equal(persistedDefault.order[1], OFFICIAL_MONITOR_PLUGIN);
|
||||
assert.equal(persistedDefault.order.includes(OFFICIAL_DB_PLUGIN), true);
|
||||
|
||||
activePluginIds = [OFFICIAL_DB_PLUGIN, OFFICIAL_MONITOR_PLUGIN];
|
||||
pluginsLoading = false;
|
||||
pluginsAvailable = true;
|
||||
await act(async () => {
|
||||
restartedRoot.render(
|
||||
<React.StrictMode>
|
||||
<Fixture />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
});
|
||||
assert.equal(model.visibleIds[1], OFFICIAL_MONITOR_PLUGIN);
|
||||
assert.equal(model.visibleIds.includes(OFFICIAL_DB_PLUGIN), true);
|
||||
assert.equal(model.isHidden('logs'), true);
|
||||
|
||||
await act(async () => {
|
||||
restartedRoot.unmount();
|
||||
});
|
||||
} finally {
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
@@ -28,6 +28,8 @@ export interface UseVaultNavConfigOptions {
|
||||
activePluginIds: readonly PluginVaultNavId[];
|
||||
/** Pass true while plugin contributions are still loading on cold start. */
|
||||
pluginsLoading?: boolean;
|
||||
/** Pass true once plugin contributions are available from the plugin runtime. */
|
||||
pluginsAvailable?: boolean;
|
||||
}
|
||||
|
||||
export interface UseVaultNavConfigResult {
|
||||
@@ -76,13 +78,14 @@ function writeStoredVaultNavConfig(config: VaultNavConfig): void {
|
||||
export function useVaultNavConfig({
|
||||
activePluginIds,
|
||||
pluginsLoading = false,
|
||||
pluginsAvailable = false,
|
||||
}: UseVaultNavConfigOptions): UseVaultNavConfigResult {
|
||||
const pluginKey = activePluginIds.join('\0');
|
||||
const stablePluginIds = useMemo<PluginVaultNavId[]>(
|
||||
() => (pluginKey ? (pluginKey.split('\0') as PluginVaultNavId[]) : []),
|
||||
[pluginKey],
|
||||
);
|
||||
const pruneMissingPlugins = !pluginsLoading;
|
||||
const pruneMissingPlugins = !pluginsLoading && pluginsAvailable;
|
||||
|
||||
const [config, setConfig] = useState<VaultNavConfig>(() =>
|
||||
readStoredVaultNavConfig(stablePluginIds, pruneMissingPlugins),
|
||||
|
||||
@@ -440,3 +440,43 @@ test('changed remote transcript resets the local native SDK thread before contin
|
||||
assert.equal(getAISessionsSnapshot().sessions[0].messages.at(-1)?.content, 'Added on another device');
|
||||
delete (window as unknown as { netcatty?: unknown }).netcatty;
|
||||
});
|
||||
|
||||
test('cloud apply keeps receiver workspaceNameSnapshot when workspace binding is unchanged and drops it on rebind', async () => {
|
||||
const local: AISession = {
|
||||
...session(),
|
||||
id: 'ws-chat',
|
||||
scope: { type: 'workspace', targetId: 'ws-1', hostIds: ['h-1'] },
|
||||
workspaceNameSnapshot: 'Prod Cluster (this Mac)',
|
||||
updatedAt: 10,
|
||||
};
|
||||
save([local]);
|
||||
|
||||
// Never uploaded to cloud.
|
||||
const uploaded = await buildCloudSyncPayload(vault, [], { collectPluginSidecars: () => undefined });
|
||||
assert.equal(Object.hasOwn(uploaded.aiSessions?.[0] ?? {}, 'workspaceNameSnapshot'), false);
|
||||
|
||||
// Newer remote update on the same workspace (stripped by remote device, or even
|
||||
// carrying a foreign snapshot that must be stripped on apply) keeps local name.
|
||||
const remoteSameWs: AISession = {
|
||||
...local,
|
||||
updatedAt: 20,
|
||||
title: 'Updated title from peer',
|
||||
workspaceNameSnapshot: 'Peer stale name',
|
||||
};
|
||||
await applySyncPayload({ ...vault, aiSessions: [remoteSameWs], syncedAt: 20 }, { importVaultData: () => undefined });
|
||||
const afterSameWs = getAISessionsSnapshot().sessions.find((s) => s.id === 'ws-chat');
|
||||
assert.equal(afterSameWs?.title, 'Updated title from peer');
|
||||
assert.equal(afterSameWs?.workspaceNameSnapshot, 'Prod Cluster (this Mac)');
|
||||
|
||||
// Newer remote update that rebinds to another workspace drops the old local name.
|
||||
const remoteRebound: AISession = {
|
||||
...local,
|
||||
updatedAt: 30,
|
||||
scope: { type: 'workspace', targetId: 'ws-2', hostIds: ['h-2'] },
|
||||
workspaceNameSnapshot: undefined,
|
||||
};
|
||||
await applySyncPayload({ ...vault, aiSessions: [remoteRebound], syncedAt: 30 }, { importVaultData: () => undefined });
|
||||
const afterRebound = getAISessionsSnapshot().sessions.find((s) => s.id === 'ws-chat');
|
||||
assert.equal(afterRebound?.scope.targetId, 'ws-2');
|
||||
assert.equal(afterRebound?.workspaceNameSnapshot, undefined);
|
||||
});
|
||||
@@ -2422,13 +2422,17 @@ test('sync prepares header encryption once before importing and leaves input unc
|
||||
assert.deepEqual(JSON.parse(localStorage.getItem(storageKeys.STORAGE_KEY_AI_PROVIDERS)!)[0].customHeaders, { 'X-Tenant': sealed });
|
||||
});
|
||||
|
||||
test("SFTP default download folder stays device-local and is never synced", async () => {
|
||||
const key = storageKeys.STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR;
|
||||
assert.equal((SYNCABLE_SETTING_STORAGE_KEYS as readonly string[]).includes(key), false);
|
||||
localStorage.clear();
|
||||
localStorage.setItem(key, "/Users/me/server-files");
|
||||
const payload = buildSyncPayload(vault());
|
||||
assert.equal(JSON.stringify(payload).includes("/Users/me/server-files"), false);
|
||||
await applySyncPayload(payload, { importVaultData: () => {} });
|
||||
assert.equal(localStorage.getItem(key), "/Users/me/server-files");
|
||||
});
|
||||
for (const key of [
|
||||
storageKeys.STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR,
|
||||
storageKeys.STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR,
|
||||
]) {
|
||||
test(`SFTP download folder ${key} stays device-local and is never synced`, async () => {
|
||||
assert.equal((SYNCABLE_SETTING_STORAGE_KEYS as readonly string[]).includes(key), false);
|
||||
localStorage.clear();
|
||||
localStorage.setItem(key, "/Users/me/server-files");
|
||||
const payload = buildSyncPayload(vault());
|
||||
assert.equal(JSON.stringify(payload).includes("/Users/me/server-files"), false);
|
||||
await applySyncPayload(payload, { importVaultData: () => {} });
|
||||
assert.equal(localStorage.getItem(key), "/Users/me/server-files");
|
||||
});
|
||||
}
|
||||
@@ -14,6 +14,11 @@ import type {
|
||||
ExternalAgentConfig,
|
||||
} from '../infrastructure/ai/types';
|
||||
import type { VaultNote } from '../domain/models';
|
||||
import {
|
||||
buildFallbackTitle,
|
||||
canAutoTitleSession,
|
||||
resolveCattyEffectiveModel,
|
||||
} from '../domain/aiSessionTitle';
|
||||
import type { ExecutorContext } from '../infrastructure/ai/cattyAgent/executor';
|
||||
import {
|
||||
DEFAULT_MAX_ITERATIONS,
|
||||
@@ -294,6 +299,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
undoLastTurnInSession,
|
||||
deleteSession,
|
||||
updateSessionTitle,
|
||||
autoTitleSession,
|
||||
rebindSessionScope,
|
||||
exportSessionsBackup,
|
||||
importSessionsBackup,
|
||||
@@ -1038,26 +1044,16 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
[providers, activeProviderId],
|
||||
);
|
||||
|
||||
const cattyAgentProvider = useMemo(() => {
|
||||
const overrideId = agentProviderMap['catty'];
|
||||
if (overrideId) {
|
||||
const p = providers.find((cfg) => cfg.id === overrideId);
|
||||
if (p) return p;
|
||||
}
|
||||
return activeProvider;
|
||||
}, [agentProviderMap, providers, activeProvider]);
|
||||
|
||||
const cattyAgentModelId = useMemo(() => {
|
||||
const trim = (s: string | undefined | null): string => (s ?? '').trim();
|
||||
const overrideId = agentProviderMap['catty'];
|
||||
const overrideProvider = overrideId
|
||||
? providers.find((cfg) => cfg.id === overrideId)
|
||||
: undefined;
|
||||
if (overrideProvider) {
|
||||
return trim(agentModelMap['catty']) || trim(overrideProvider.defaultModel);
|
||||
}
|
||||
return trim(cattyAgentProvider?.defaultModel) || trim(activeModelId);
|
||||
}, [agentModelMap, agentProviderMap, providers, cattyAgentProvider, activeModelId]);
|
||||
const { provider: cattyAgentProvider, modelId: cattyAgentModelId } = useMemo(
|
||||
() => resolveCattyEffectiveModel({
|
||||
providers,
|
||||
activeProviderId,
|
||||
activeModelId,
|
||||
agentProviderMap,
|
||||
agentModelMap,
|
||||
}),
|
||||
[providers, activeProviderId, activeModelId, agentProviderMap, agentModelMap],
|
||||
);
|
||||
|
||||
const effectiveActiveProvider = currentAgentId === 'catty' ? cattyAgentProvider : activeProvider;
|
||||
const effectiveActiveModelId = currentAgentId === 'catty' ? cattyAgentModelId : activeModelId;
|
||||
@@ -1680,18 +1676,10 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
}, [openSettingsWindow]);
|
||||
|
||||
|
||||
/** Ref to always access latest sessions (avoids stale closure in autoTitleSession). */
|
||||
/** Ref to always access latest sessions inside async send callbacks. */
|
||||
const sessionsRef = useRef(sessions);
|
||||
sessionsRef.current = sessions;
|
||||
|
||||
/** Auto-title a session from the first user message if untitled. */
|
||||
const autoTitleSession = useCallback((sessionId: string, text: string) => {
|
||||
const s = sessionsRef.current.find(x => x.id === sessionId);
|
||||
if (s && (!s.title || s.title === 'New Chat')) {
|
||||
updateSessionTitle(sessionId, text.length > 50 ? text.slice(0, 50) + '...' : text);
|
||||
}
|
||||
}, [updateSessionTitle]);
|
||||
|
||||
const buildExecutorContextForScope = useCallback((scope: {
|
||||
type: 'terminal' | 'workspace' | 'global';
|
||||
targetId?: string;
|
||||
@@ -1875,7 +1863,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
let currentSession = currentSessionView ?? null;
|
||||
if (isDraftMode) {
|
||||
const scope: AISessionScope = { type: scopeType, targetId: scopeTargetId, hostIds: scopeHostIds };
|
||||
const createdSession = createSession(scope, sendAgentId);
|
||||
const createdSession = createSession(scope, sendAgentId, scopeLabel);
|
||||
sessionId = createdSession.id;
|
||||
currentSession = createdSession;
|
||||
if (useDraftAttachments) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
@@ -1983,7 +1971,6 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
updateLastMessage(sessionId, msg => msg.statusText ? { ...msg, statusText: '' } : msg);
|
||||
setStreamingForScope(sessionId, false);
|
||||
abortControllersRef.current.delete(sessionId);
|
||||
autoTitleSession(sessionId, titleText);
|
||||
} else {
|
||||
const toolScope = {
|
||||
type: scopeType,
|
||||
@@ -2005,12 +1992,23 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
terminalSessions,
|
||||
webSearchConfig,
|
||||
getExecutorContext: () => buildExecutorContextForScope(toolScope),
|
||||
autoTitleSession,
|
||||
// Title generation is triggered once, below, for both agent branches.
|
||||
autoTitleSession: () => {},
|
||||
selectedUserSkillSlugs: selectedSkillSlugs,
|
||||
titleText,
|
||||
pluginContext,
|
||||
}, modelAttachments.length > 0 ? modelAttachments : undefined);
|
||||
}
|
||||
// Single title-generation trigger for both agent branches. Pass the
|
||||
// signal explicitly: sendToCattyAgent's finally removes its controller.
|
||||
if (autoTitleSession) {
|
||||
void autoTitleSession(sessionId, titleText, abortController.signal);
|
||||
} else {
|
||||
const current = sessionsRef.current.find((s) => s.id === sessionId);
|
||||
if (canAutoTitleSession(current)) {
|
||||
updateSessionTitle(sessionId, buildFallbackTitle(titleText));
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
setIsSending(false);
|
||||
endSendForKey(sendGateKey);
|
||||
@@ -2022,7 +2020,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
validateNoteMentions, loadCodexConfigModel,
|
||||
isStreaming, isUndoingLastTurn, activeProvider, effectiveActiveProvider, effectiveActiveModelId, selectedCattyThinking, scopeKey, currentAgentId,
|
||||
activeModelId, externalAgents,
|
||||
createSession, addMessageToSession, updateMessageById, updateLastMessage,
|
||||
createSession, addMessageToSession, updateMessageById, updateLastMessage, updateSessionTitle,
|
||||
setStreamingForScope,
|
||||
sendToExternalAgent, sendToCattyAgent, reportStreamError, autoTitleSession, t,
|
||||
abortControllersRef, terminalSessions, defaultTargetSession, providers, selectedAgentModel, updateSessionExternalSessionId,
|
||||
@@ -2666,6 +2664,7 @@ const AI_CHAT_SIDE_PANEL_AI_STATE_KEYS = [
|
||||
'createSession',
|
||||
'deleteSession',
|
||||
'updateSessionTitle',
|
||||
'autoTitleSession',
|
||||
'rebindSessionScope',
|
||||
'exportSessionsBackup',
|
||||
'importSessionsBackup',
|
||||
|
||||
@@ -36,7 +36,7 @@ export interface AIChatSidePanelProps {
|
||||
clearDraftForScope: (scopeKey: string) => void;
|
||||
addDraftFiles: (scopeKey: string, fallbackAgentId: string, inputFiles: File[]) => Promise<void>;
|
||||
removeDraftFile: (scopeKey: string, fallbackAgentId: string, fileId: string) => void;
|
||||
createSession: (scope: AISessionScope, agentId?: string) => AISession;
|
||||
createSession: (scope: AISessionScope, agentId?: string, workspaceNameSnapshot?: string) => AISession;
|
||||
/** Non-destructively branch before the last user turn; returns the branch id + restored composer content. */
|
||||
undoLastTurnInSession?: (
|
||||
sessionId: string,
|
||||
@@ -44,6 +44,7 @@ export interface AIChatSidePanelProps {
|
||||
) => Promise<{ sessionId: string; restored: { text: string; attachments: import('../infrastructure/ai/types').UploadedFile[]; selectedUserSkillSlugs: string[] } } | null>;
|
||||
deleteSession: (sessionId: string, scopeKey?: string) => void;
|
||||
updateSessionTitle: (sessionId: string, title: string) => void;
|
||||
autoTitleSession?: (sessionId: string, text: string, signal?: AbortSignal) => void | Promise<void>;
|
||||
/** Issue #4015 R2: rebind a dangling chat to this panel's scope (panel action, never agent content). */
|
||||
rebindSessionScope?: (sessionId: string, scope: { type: 'terminal' | 'workspace'; targetId: string; hostIds?: string[] }) => void;
|
||||
/** Manual durability escape hatch: export the store to a JSON file (returns the path, '' when fixed-path). With `sessionIds`, exports only those chats. */
|
||||
|
||||
@@ -2,6 +2,11 @@ import React from "react";
|
||||
import { ChevronRight, Info } from "lucide-react";
|
||||
import { applyGroupDefaults, resolveGroupDefaults } from "../domain/groupConfig";
|
||||
import { sanitizeCredentialValue } from "../domain/credentials";
|
||||
import {
|
||||
getExportablePublicKey,
|
||||
hasExportablePublicKey,
|
||||
isKeychainExportDisabled,
|
||||
} from "../domain/keychainExport";
|
||||
import { hasBridgeSshCredentials, resolveBridgeKeyAuth, resolveBridgeSshAgentAuth, resolveHostAuth } from "../domain/sshAuth";
|
||||
import { resolveHostSshConnectionTimeouts } from "../domain/sshConnectionTimeouts";
|
||||
import { connectionTotpFields } from "../domain/totpConfig";
|
||||
@@ -41,6 +46,15 @@ export const KeychainExportPanel: React.FC<KeychainExportPanelProps> = ({
|
||||
onSaveHost,
|
||||
closePanel,
|
||||
}) => {
|
||||
const hasPublicKey = hasExportablePublicKey(panel.key?.publicKey);
|
||||
const exportDisabled = isKeychainExportDisabled({
|
||||
exportHost,
|
||||
exportLocation,
|
||||
exportFilename,
|
||||
publicKey: panel.key?.publicKey,
|
||||
isExporting,
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Key info card */}
|
||||
@@ -159,17 +173,32 @@ export const KeychainExportPanel: React.FC<KeychainExportPanelProps> = ({
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
|
||||
{!hasPublicKey && (
|
||||
<div className="flex items-start gap-2 p-3 bg-muted/50 border border-border/60 rounded-lg">
|
||||
<Info
|
||||
size={14}
|
||||
className="mt-0.5 text-muted-foreground shrink-0"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("keychain.export.missingPublicKeyNote")}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Export button */}
|
||||
<Button
|
||||
className="w-full h-11"
|
||||
disabled={
|
||||
!exportHost ||
|
||||
!exportLocation ||
|
||||
!exportFilename ||
|
||||
isExporting
|
||||
}
|
||||
disabled={exportDisabled}
|
||||
onClick={async () => {
|
||||
if (!exportHost || !panel.key.publicKey) return;
|
||||
if (!exportHost) return;
|
||||
const publicKey = getExportablePublicKey(panel.key?.publicKey);
|
||||
if (!publicKey) {
|
||||
toast.error(
|
||||
t("keychain.export.missingPublicKey"),
|
||||
t("keychain.export.failedTitle"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsExporting(true);
|
||||
|
||||
@@ -216,7 +245,7 @@ export const KeychainExportPanel: React.FC<KeychainExportPanelProps> = ({
|
||||
}
|
||||
|
||||
// Escape the public key for shell (single quotes, escape existing quotes)
|
||||
const escapedPublicKey = panel.key.publicKey.replace(
|
||||
const escapedPublicKey = publicKey.replace(
|
||||
/'/g,
|
||||
"'\\''",
|
||||
);
|
||||
|
||||
@@ -73,8 +73,12 @@ test('Vault navigation mounts a real content slot, yields to host dialogs, and w
|
||||
await act(async () => { selectSection('plugin-vault:missing'); await settle(); });
|
||||
assert.match(document.querySelector('main')!.textContent!, /Built-in hosts/);
|
||||
await act(async () => { snapshot = { ...snapshot, plugins: [{ id: 'com.example.page', version: '1.0.0', displayName: 'Synthetic plugin', commands: [], keybindings: [], menus: [], settings: [], views: [page] }] }; changed?.(); await settle(); });
|
||||
await act(async () => { requestOpenPluginView({ viewId: page.id }); await settle(); });
|
||||
await act(async () => { activeTabStore.setActiveTabId('terminal:synthetic'); await settle(); });
|
||||
assert.equal(activeTabStore.getActiveTabId(), 'terminal:synthetic');
|
||||
await act(async () => { requestOpenPluginView({ viewId: page.id, params: { connectionId: 'db-1' } }); await settle(); });
|
||||
assert.equal(activeTabStore.getActiveTabId(), 'vault', 'opening a vault-page switches the active tab to vault');
|
||||
assert.equal(opens.length, 2);
|
||||
assert.deepEqual(opens[1].context, { 'netcatty.surface': 'vault-page' }, 'activation params must not be merged into contribution context');
|
||||
await act(async () => { selectSection('hosts'); await settle(); });
|
||||
assert.equal(document.querySelector('[data-plugin-vault-page]'), null);
|
||||
} finally {
|
||||
@@ -82,3 +86,91 @@ test('Vault navigation mounts a real content slot, yields to host dialogs, and w
|
||||
for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); }
|
||||
}
|
||||
});
|
||||
|
||||
test('Failed host-drawn view session stays on the plugin vault page with error and retry instead of falling back to Hosts', async () => {
|
||||
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', { pretendToBeVisual: true, url: 'http://localhost' });
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'MutationObserver', 'CustomEvent', 'Event']) {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: key === 'window' ? dom.window : dom.window[key as keyof Window] });
|
||||
}
|
||||
for (const [key, value] of Object.entries({ getComputedStyle: dom.window.getComputedStyle.bind(dom.window),
|
||||
requestAnimationFrame: dom.window.requestAnimationFrame.bind(dom.window), cancelAnimationFrame: dom.window.cancelAnimationFrame.bind(dom.window), IS_REACT_ACT_ENVIRONMENT: true })) {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key)); Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
}
|
||||
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({ x: 200, y: 100, width: 640, height: 480, top: 100, left: 200, right: 840, bottom: 580, toJSON() {} });
|
||||
const { act, useState } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { usePluginVaultPages } = await import('../application/state/usePluginVaultPages');
|
||||
const { PluginVaultNavigation, PluginVaultPage } = await import('./plugins/PluginVaultPages');
|
||||
const { activeTabStore } = await import('../application/state/activeTabStore');
|
||||
const { I18nProvider } = await import('../application/i18n/I18nProvider');
|
||||
const page = { id: 'com.example.page.main', title: 'Synthetic page', location: 'vault-page', visible: true };
|
||||
let snapshot = { locale: 'en', plugins: [{ id: 'com.example.page', version: '1.0.0', displayName: 'Synthetic plugin', commands: [], keybindings: [], menus: [], settings: [], views: [page] }] };
|
||||
let changed: (() => void) | undefined;
|
||||
const listeners = new Set<(event: NetcattyPluginViewClosedEvent) => void>();
|
||||
const opens: NetcattyPluginViewOpenRequest[] = [], closes: string[] = [];
|
||||
Object.assign(dom.window, { netcatty: {
|
||||
async getPluginRuntimeStatus() { return { available: true }; },
|
||||
async getPluginContributions() { return snapshot; },
|
||||
onPluginContributionsChanged(fn: () => void) { changed = fn; return () => { changed = undefined; }; },
|
||||
onPluginViewClosed(fn: (event: NetcattyPluginViewClosedEvent) => void) { listeners.add(fn); return () => { listeners.delete(fn); }; },
|
||||
onHostDrawnPluginViewUpdate() { return () => {}; },
|
||||
async openHostDrawnPluginView(payload: NetcattyPluginViewOpenRequest) { opens.push(payload); return { instanceId: payload.instanceId! }; },
|
||||
async closeHostDrawnPluginView(id: string) { closes.push(id); },
|
||||
} });
|
||||
function Fixture() {
|
||||
const [section, select] = useState<'hosts' | `plugin-vault:${string}`>('hosts');
|
||||
const model = usePluginVaultPages({ locale: 'en', section, select });
|
||||
return <><aside><button data-plugin-vault-fallback onClick={() => select('hosts')}>Hosts</button><PluginVaultNavigation model={model} collapsed={false} /></aside>
|
||||
<main data-section="vault-main">{model.selected ? <PluginVaultPage key={model.selected.key} model={model} /> : <p>Built-in hosts</p>}</main></>;
|
||||
}
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 35));
|
||||
try {
|
||||
activeTabStore.setActiveTabId('vault');
|
||||
await act(async () => { root.render(<I18nProvider locale="en"><Fixture /></I18nProvider>); await settle(); });
|
||||
await act(async () => {
|
||||
document.querySelector<HTMLButtonElement>('button[aria-label="Synthetic page — Synthetic plugin"]')!.click();
|
||||
await import('./plugins/PluginHostDrawnPage');
|
||||
await settle();
|
||||
});
|
||||
assert.equal(opens.length, 1);
|
||||
assert.ok(document.querySelector('[data-plugin-vault-page]'));
|
||||
|
||||
// Session fails while plugin contribution remains active.
|
||||
await act(async () => {
|
||||
for (const listener of listeners) {
|
||||
listener({ instanceId: opens[0].instanceId!, viewId: page.id, pluginId: 'com.example.page', reason: 'view-error' });
|
||||
}
|
||||
await settle();
|
||||
});
|
||||
assert.ok(document.querySelector('[data-plugin-vault-page]'), 'stays on the plugin vault page');
|
||||
assert.doesNotMatch(document.querySelector('main')!.textContent!, /Built-in hosts/);
|
||||
assert.equal(document.querySelector('[data-plugin-remote-surface]'), null, 'does not render an empty remote surface');
|
||||
const alert = document.querySelector('[data-plugin-vault-page] [role="alert"]');
|
||||
assert.ok(alert, 'renders in-page error alert');
|
||||
assert.equal(alert!.textContent, 'The plugin page failed to render.');
|
||||
|
||||
const retryButton = [...document.querySelectorAll<HTMLButtonElement>('[data-plugin-vault-page] button')]
|
||||
.find((btn) => btn.textContent === 'Retry');
|
||||
assert.ok(retryButton, 'renders Retry control');
|
||||
|
||||
await act(async () => {
|
||||
retryButton!.click();
|
||||
await settle();
|
||||
});
|
||||
assert.equal(opens.length, 2, 'clicking Retry opens a new host-drawn plugin view session');
|
||||
assert.notEqual(opens[1].instanceId, opens[0].instanceId);
|
||||
assert.equal(document.querySelector('[data-plugin-vault-page] [role="alert"]'), null);
|
||||
|
||||
// Removing the contribution still falls back to Hosts.
|
||||
await act(async () => { snapshot = { ...snapshot, plugins: [] }; changed?.(); await settle(); });
|
||||
await act(async () => { await settle(); });
|
||||
assert.equal(document.querySelector('[data-plugin-vault-page]'), null);
|
||||
assert.match(document.querySelector('main')!.textContent!, /Built-in hosts/);
|
||||
} finally {
|
||||
await act(async () => { root.unmount(); (await import('../application/state/pluginViewSession')).pluginViewSessions.dispose(); await settle(); }); dom.window.close();
|
||||
for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); }
|
||||
}
|
||||
});
|
||||
@@ -258,6 +258,12 @@ const SettingsAITabContainer: React.FC = () => {
|
||||
setQuickMessages={aiState.setQuickMessages}
|
||||
showTerminalSelectionAIAction={aiState.showTerminalSelectionAIAction}
|
||||
setShowTerminalSelectionAIAction={aiState.setShowTerminalSelectionAIAction}
|
||||
autoLlmTitle={aiState.autoLlmTitle}
|
||||
setAutoLlmTitle={aiState.setAutoLlmTitle}
|
||||
titleModel={aiState.titleModel}
|
||||
setTitleModel={aiState.setTitleModel}
|
||||
agentProviderMap={aiState.agentProviderMap}
|
||||
agentModelMap={aiState.agentModelMap}
|
||||
/>
|
||||
</AITabErrorBoundary>
|
||||
);
|
||||
@@ -581,6 +587,8 @@ const SettingsPageContent: React.FC<{ settings: SettingsState; appLock?: AppLock
|
||||
setShowSftpTab={settings.setShowSftpTab}
|
||||
showHostTreeSidebar={settings.showHostTreeSidebar}
|
||||
setShowHostTreeSidebar={settings.setShowHostTreeSidebar}
|
||||
removeTopTabsDragArea={settings.removeTopTabsDragArea}
|
||||
setRemoveTopTabsDragArea={settings.setRemoveTopTabsDragArea}
|
||||
windowOpacity={settings.windowOpacity}
|
||||
setWindowOpacity={settings.setWindowOpacity}
|
||||
windowBackgroundBlur={settings.windowBackgroundBlur}
|
||||
|
||||
@@ -1497,6 +1497,9 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
if (!shouldProbeCommandCwd({
|
||||
restoreTerminalCwd,
|
||||
visibleSftpHost,
|
||||
latestVisibleSftpHost: visibleSftpHost
|
||||
? hostsRef.current.find((host) => host.id === visibleSftpHost.id)
|
||||
: undefined,
|
||||
sessionHost,
|
||||
globalSftpFollowTerminalCwd: sftpFollowTerminalCwdRef.current,
|
||||
restrictExtraSshChannels: hostRestrictsExtraSshChannels(sessionHost),
|
||||
|
||||
+10
-2
@@ -217,6 +217,7 @@ interface TopTabsProps {
|
||||
tabInsertionTarget?: { tabId: string; position: 'before' | 'after'; additionalTabIds?: readonly string[] },
|
||||
) => void;
|
||||
onAppendHostToWorkspace?: (workspaceId: string, hostId: string) => void;
|
||||
onRequestAddToWorkspace?: (workspaceId: string) => void;
|
||||
showSftpTab: boolean;
|
||||
showHostTreeSidebar: boolean;
|
||||
switchTabKeyBinding: Pick<KeyBinding, 'mac' | 'pc'> | null;
|
||||
@@ -270,6 +271,7 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
onReorderTabs,
|
||||
onRemoveSessionFromWorkspace,
|
||||
onAppendHostToWorkspace,
|
||||
onRequestAddToWorkspace,
|
||||
showSftpTab,
|
||||
showHostTreeSidebar,
|
||||
switchTabKeyBinding,
|
||||
@@ -288,6 +290,7 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
const {
|
||||
hotkeyScheme,
|
||||
showTabNumberBadges,
|
||||
removeTopTabsDragArea,
|
||||
shellOnlyTabNumberShortcuts,
|
||||
} = useSettingsChromeStore();
|
||||
const switchTabKey = hotkeyScheme === 'mac'
|
||||
@@ -1031,6 +1034,7 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
onTabDrop={handleTabDrop}
|
||||
onRenameWorkspace={onRenameWorkspace}
|
||||
onCopyWorkspace={onCopyWorkspace}
|
||||
onRequestAddToWorkspace={onRequestAddToWorkspace}
|
||||
onCloseWorkspace={onCloseWorkspace}
|
||||
onDetachSessionFromWorkspace={handleDetachSessionFromWorkspace}
|
||||
renderBulkCloseItems={renderBulkCloseItems}
|
||||
@@ -1087,6 +1091,7 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
<div
|
||||
data-top-tabs-root
|
||||
data-section="top-tabs"
|
||||
data-remove-top-tabs-drag-area={removeTopTabsDragArea ? 'true' : undefined}
|
||||
className="relative w-full bg-secondary app-drag"
|
||||
style={{
|
||||
...dragRegionNoSelect,
|
||||
@@ -1099,9 +1104,11 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
tabsContainerRef={tabsContainerRef}
|
||||
updateScrollState={updateScrollState}
|
||||
/>
|
||||
{/* Always-on drag stripe so the window can be moved even when tabs fill the bar */}
|
||||
<div className="absolute inset-x-0 top-0 h-1 app-drag pointer-events-auto z-10" style={dragRegionStyle} aria-hidden />
|
||||
{!removeTopTabsDragArea && (
|
||||
<div className="absolute inset-x-0 top-0 h-1 app-drag pointer-events-auto z-10" style={dragRegionStyle} aria-hidden />
|
||||
)}
|
||||
<div
|
||||
data-section="top-tabs-toolbar-row"
|
||||
className="h-9 flex items-end gap-0 app-drag overflow-visible"
|
||||
style={{
|
||||
...dragRegionStyle,
|
||||
@@ -1387,6 +1394,7 @@ export const topTabsAreEqual = (prev: TopTabsProps, next: TopTabsProps): boolean
|
||||
prev.onMoveSessionToNewWindow === next.onMoveSessionToNewWindow &&
|
||||
prev.onEditHost === next.onEditHost &&
|
||||
prev.onAppendHostToWorkspace === next.onAppendHostToWorkspace &&
|
||||
prev.onRequestAddToWorkspace === next.onRequestAddToWorkspace &&
|
||||
prev.onCopyWorkspace === next.onCopyWorkspace &&
|
||||
prev.onOpenSettings === next.onOpenSettings &&
|
||||
prev.onLockApp === next.onLockApp &&
|
||||
|
||||
@@ -394,6 +394,7 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
const vaultNavConfig = useVaultNavConfig({
|
||||
activePluginIds: activePluginNavIds,
|
||||
pluginsLoading: pluginVault.contributions.loading,
|
||||
pluginsAvailable: pluginVault.contributions.available,
|
||||
});
|
||||
const previousHiddenNavRef = useRef<ReadonlySet<VaultNavItemId>>(vaultNavConfig.hiddenSet);
|
||||
useEffect(() => {
|
||||
|
||||
@@ -542,3 +542,24 @@ test("clicking an active-elsewhere chat falls back to opening locally when focus
|
||||
dom.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("subtitle styling keeps agent label emphasized and message count normal when scopeLabel is empty", async () => {
|
||||
const dom = installDomEnvironment();
|
||||
try {
|
||||
const props = baseProps();
|
||||
props.sessions = [
|
||||
makeSession({ id: "no-scope-label", title: "Orphan chat", scope: { type: "terminal", targetId: "t-gone" } }),
|
||||
];
|
||||
const renderer = await renderManager(dom, props);
|
||||
const row = rows(renderer)[0];
|
||||
const spans = Array.from(row.querySelectorAll("span")).filter((el) => !el.getAttribute("aria-hidden"));
|
||||
const agentSpan = spans.find((el) => el.textContent === "Catty Agent");
|
||||
const countSpan = spans.find((el) => (el.textContent ?? "").includes("1"));
|
||||
assert.ok(agentSpan?.className.includes("font-medium"));
|
||||
assert.ok(!agentSpan?.className.includes("truncate"));
|
||||
assert.ok(countSpan);
|
||||
assert.ok(!countSpan.className.includes("font-medium"));
|
||||
} finally {
|
||||
dom.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -260,13 +260,17 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
const canMoveElsewhere = otherMoveTargets.length > 0;
|
||||
const isRenaming = renamingSessionId === row.session.id;
|
||||
const isMenuOpen = openMenuSessionId === row.session.id;
|
||||
const subtitleParts: string[] = [];
|
||||
if (row.scopeLabel) subtitleParts.push(row.scopeLabel);
|
||||
if (showAgentMeta) subtitleParts.push(row.agentLabel);
|
||||
const subtitleParts: Array<{ text: string; bold: boolean; truncate: boolean }> = [];
|
||||
if (row.scopeLabel) {
|
||||
subtitleParts.push({ text: row.scopeLabel, bold: true, truncate: true });
|
||||
}
|
||||
subtitleParts.push({ text: row.agentLabel, bold: true, truncate: false });
|
||||
if (row.messageCount > 0) {
|
||||
subtitleParts.push(
|
||||
t('ai.chat.managerMessagesCount').replace('{n}', String(row.messageCount)),
|
||||
);
|
||||
subtitleParts.push({
|
||||
text: t('ai.chat.managerMessagesCount').replace('{n}', String(row.messageCount)),
|
||||
bold: false,
|
||||
truncate: false,
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -336,12 +340,15 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
)}
|
||||
</div>
|
||||
{subtitleParts.length > 0 && (
|
||||
<div className="mt-0.5 flex items-center gap-1.5 text-[11px] text-muted-foreground/50 min-w-0">
|
||||
<div className="mt-0.5 flex items-center gap-1.5 text-[11px] text-muted-foreground/70 min-w-0">
|
||||
{subtitleParts.map((part, index) => (
|
||||
<React.Fragment key={`${row.session.id}-meta-${index}`}>
|
||||
{index > 0 && <span aria-hidden>·</span>}
|
||||
<span className={index === 0 ? 'truncate' : 'shrink-0'}>
|
||||
{part}
|
||||
<span className={cn(
|
||||
part.truncate ? 'truncate' : 'shrink-0',
|
||||
part.bold && 'font-medium',
|
||||
)}>
|
||||
{part.text}
|
||||
</span>
|
||||
</React.Fragment>
|
||||
))}
|
||||
|
||||
@@ -96,6 +96,39 @@ test("global rows cover every scope: live terminal, other terminal, workspace, c
|
||||
assert.equal(byId.get("s-global")!.scopeLabel, t("ai.chat.chatsScopeGlobal"));
|
||||
});
|
||||
|
||||
test("workspace name snapshot is the fallback for a dangling workspace, but live title wins", () => {
|
||||
const input = {
|
||||
...baseInput(),
|
||||
hosts: [{ id: "h-old", label: "old-host", hostname: "10.0.0.5" }],
|
||||
};
|
||||
input.sessions = [
|
||||
// Workspace gone: the captured name wins over the host fallback.
|
||||
baseSession({
|
||||
id: "s-snap",
|
||||
scope: { type: "workspace", targetId: "w-gone", hostIds: ["h-old"] },
|
||||
workspaceNameSnapshot: "Prod (old)",
|
||||
}),
|
||||
// Workspace still live: the live title wins even if a stale snapshot exists.
|
||||
baseSession({
|
||||
id: "s-live",
|
||||
scope: { type: "workspace", targetId: "w-1" },
|
||||
workspaceNameSnapshot: "Stale name",
|
||||
}),
|
||||
// Dangling flag with a live workspace present still falls back to the snapshot.
|
||||
baseSession({
|
||||
id: "s-flagged",
|
||||
scope: { type: "workspace", targetId: "w-1" },
|
||||
scopeDangling: true,
|
||||
workspaceNameSnapshot: "Prod (archived)",
|
||||
}),
|
||||
];
|
||||
const byId = new Map(buildGlobalManagerRows(input).map((row) => [row.session.id, row]));
|
||||
assert.equal(byId.get("s-snap")!.scopeLabel, "Prod (old)");
|
||||
assert.equal(byId.get("s-snap")!.scopeState, "dangling");
|
||||
assert.equal(byId.get("s-live")!.scopeLabel, "Prod");
|
||||
assert.equal(byId.get("s-flagged")!.scopeLabel, "Prod (archived)");
|
||||
});
|
||||
|
||||
test("active marker distinguishes current panel active chat vs active elsewhere", () => {
|
||||
const input = baseInput();
|
||||
input.sessions = [
|
||||
|
||||
@@ -165,10 +165,14 @@ export function buildGlobalManagerRows(input: BuildGlobalManagerRowsInput): Glob
|
||||
if (session.scope.type === 'workspace') {
|
||||
const title = workspaceTitles.get(session.scope.targetId ?? '');
|
||||
if (title != null && !session.scopeDangling) {
|
||||
// Live title wins so a rename is reflected immediately.
|
||||
scopeLabel = title;
|
||||
isDangling = false;
|
||||
} else {
|
||||
scopeLabel = resolveHistoricalHostLabel(session.scope.hostIds, hostNamesById);
|
||||
// Workspace is gone/dangling: prefer the name captured at bind time,
|
||||
// then fall back to the historical host labels.
|
||||
scopeLabel = session.workspaceNameSnapshot
|
||||
|| resolveHistoricalHostLabel(session.scope.hostIds, hostNamesById);
|
||||
isDangling = true;
|
||||
}
|
||||
} else if (session.scope.type === 'terminal') {
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
import { useHostDrawnPluginView } from '../../application/state/useHostDrawnPluginView';
|
||||
import { Button } from '../ui/button';
|
||||
import { PluginViewLoadingSurface } from './LazyPluginHostDrawnPage';
|
||||
import { PluginSettingsEntry } from './PluginSettingsEntry';
|
||||
import { PluginRemoteSurface } from './PluginRemoteSurface';
|
||||
@@ -30,12 +33,33 @@ function hasFullBleedChrome(tree: unknown): boolean {
|
||||
return check(children, 0);
|
||||
}
|
||||
|
||||
export function PluginHostDrawnPage(props: PluginHostDrawnPageProps) {
|
||||
function PluginHostDrawnPageSession({
|
||||
onRetry,
|
||||
...props
|
||||
}: PluginHostDrawnPageProps & { onRetry: () => void }) {
|
||||
const { t } = useI18n();
|
||||
const view = useHostDrawnPluginView(props);
|
||||
if (!view.visible) return null;
|
||||
if (view.loading) return <PluginViewLoadingSurface slot={props.slot.split(':')[0]} loadingLabel={props.loadingLabel} />;
|
||||
const slotName = props.slot.split(':')[0];
|
||||
if (view.loading) return <PluginViewLoadingSurface slot={slotName} loadingLabel={props.loadingLabel} />;
|
||||
if (view.error) {
|
||||
return (
|
||||
<div
|
||||
className="relative isolate flex h-full min-h-0 w-full flex-1 flex-col items-center justify-center gap-3 bg-background p-6 text-center"
|
||||
data-plugin-view-slot={slotName}
|
||||
data-plugin-view-error=""
|
||||
>
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{t('plugins.vault.viewError')}
|
||||
</p>
|
||||
<Button type="button" variant="outline" size="sm" onClick={onRetry}>
|
||||
{t('plugins.vault.retry')}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const fullBleed = hasFullBleedChrome(view.tree);
|
||||
return <div className="relative isolate h-full min-h-0 w-full flex-1" data-plugin-view-slot={props.slot.split(':')[0]} data-plugin-chrome={fullBleed ? 'full-bleed' : undefined}>
|
||||
return <div className="relative isolate h-full min-h-0 w-full flex-1" data-plugin-view-slot={slotName} data-plugin-chrome={fullBleed ? 'full-bleed' : undefined}>
|
||||
<PluginRemoteSurface key={`${props.viewId}:${props.version}:${props.slot}`} tree={view.tree} css={view.css} settled={view.settled} loadImage={view.loadImage} onEvent={view.sendEvent} />
|
||||
{!fullBleed && (
|
||||
<div className="absolute right-3 top-3 z-10" data-plugin-settings-entry="">
|
||||
@@ -44,3 +68,11 @@ export function PluginHostDrawnPage(props: PluginHostDrawnPageProps) {
|
||||
)}
|
||||
</div>;
|
||||
}
|
||||
|
||||
export function PluginHostDrawnPage(props: PluginHostDrawnPageProps) {
|
||||
const [generation, setGeneration] = useState(0);
|
||||
const handleRetry = useCallback(() => {
|
||||
setGeneration((n) => n + 1);
|
||||
}, []);
|
||||
return <PluginHostDrawnPageSession key={generation} {...props} onRetry={handleRetry} />;
|
||||
}
|
||||
@@ -808,3 +808,793 @@ test('PluginDataGrid clears stale editingCell and pending blur timer when insert
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
}
|
||||
});
|
||||
|
||||
test('PluginRemoteSurface forwards pointer gestures with capture/coalescing and wheel zoom without breaking scroll or widgets', async () => {
|
||||
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost', pretendToBeVisual: true });
|
||||
const saved = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'WheelEvent', 'PointerEvent', 'ShadowRoot']) {
|
||||
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
const val = key === 'window' ? dom.window : key === 'PointerEvent' ? dom.window.MouseEvent : dom.window[key as keyof typeof dom.window];
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: val });
|
||||
}
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
|
||||
Object.assign(dom.window, {
|
||||
ResizeObserver: class {
|
||||
private cb: (entries: unknown[]) => void;
|
||||
constructor(cb: (entries: unknown[]) => void) { this.cb = cb; }
|
||||
observe(target: Element) {
|
||||
this.cb([{ target, borderBoxSize: [{ inlineSize: 800, blockSize: 600 }], contentRect: { width: 800, height: 600 } }]);
|
||||
}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
},
|
||||
PointerEvent: dom.window.MouseEvent,
|
||||
});
|
||||
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({
|
||||
x: 100, y: 50, width: 800, height: 600, top: 50, left: 100, right: 900, bottom: 650, toJSON() {},
|
||||
});
|
||||
|
||||
const capturedPointers: Array<{ target: Element; pointerId: number }> = [];
|
||||
const releasedPointers: Array<{ target: Element; pointerId: number }> = [];
|
||||
dom.window.HTMLElement.prototype.setPointerCapture = function (pointerId: number) {
|
||||
capturedPointers.push({ target: this, pointerId });
|
||||
};
|
||||
dom.window.HTMLElement.prototype.releasePointerCapture = function (pointerId: number) {
|
||||
releasedPointers.push({ target: this, pointerId });
|
||||
};
|
||||
|
||||
const shadows: ShadowRoot[] = [];
|
||||
const nativeAttach = dom.window.Element.prototype.attachShadow;
|
||||
dom.window.Element.prototype.attachShadow = function (options) {
|
||||
const s = nativeAttach.call(this, options);
|
||||
shadows.push(s as unknown as ShadowRoot);
|
||||
return s;
|
||||
};
|
||||
|
||||
const makePointerEvent = (
|
||||
type: string,
|
||||
opts: { clientX: number; clientY: number; pointerId?: number; button?: number; buttons?: number; pointerType?: string; shiftKey?: boolean; composed?: boolean },
|
||||
) => {
|
||||
const evt = new dom.window.MouseEvent(type, {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
composed: opts.composed ?? true,
|
||||
clientX: opts.clientX,
|
||||
clientY: opts.clientY,
|
||||
button: opts.button ?? 0,
|
||||
buttons: opts.buttons ?? 0,
|
||||
shiftKey: opts.shiftKey ?? false,
|
||||
});
|
||||
if (opts.pointerId !== undefined) Object.defineProperty(evt, 'pointerId', { value: opts.pointerId });
|
||||
if (opts.pointerType !== undefined) Object.defineProperty(evt, 'pointerType', { value: opts.pointerType });
|
||||
return evt;
|
||||
};
|
||||
|
||||
const { act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { PluginRemoteSurface } = await import('./PluginRemoteSurface');
|
||||
const { createDefinitionValidator } = await import('../../electron/plugins/contractValidator.cjs');
|
||||
const validateEvent = createDefinitionValidator('HostDrawnViewEvent');
|
||||
|
||||
const events: Array<Record<string, unknown>> = [];
|
||||
const gridProps = {
|
||||
columns: [{ name: 'id', type: 'int4', primaryKey: true }],
|
||||
rows: [{ id: 1 }],
|
||||
editable: false,
|
||||
};
|
||||
const tree = {
|
||||
children: [
|
||||
{
|
||||
id: 'stage',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: { class: 'graph-stage', style: 'overflow:hidden;touch-action:none' },
|
||||
children: [
|
||||
{
|
||||
id: 'node-1',
|
||||
type: 1,
|
||||
element: 'button',
|
||||
attributes: { type: 'button', class: 'graph-node', style: 'touch-action:none' },
|
||||
children: [{ id: 'n1t', type: 3, data: 'Alpha' }],
|
||||
},
|
||||
{
|
||||
id: 'plain-btn',
|
||||
type: 1,
|
||||
element: 'button',
|
||||
attributes: { type: 'button', class: 'plain-btn' },
|
||||
children: [{ id: 'pbt', type: 3, data: 'Click me' }],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'scroll-box',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: { class: 'scroll-box', style: 'overflow-y:auto;height:120px' },
|
||||
children: [
|
||||
{ id: 'scroll-row', type: 1, element: 'div', attributes: { class: 'scroll-row' }, children: [{ id: 'srt', type: 3, data: 'Item' }] },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'fit-box',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: { class: 'fit-box', style: 'overflow-y:auto;height:120px' },
|
||||
children: [
|
||||
{ id: 'fit-row', type: 1, element: 'div', attributes: { class: 'fit-row' }, children: [{ id: 'frt', type: 3, data: 'Short' }] },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'split',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: {
|
||||
'data-plugin-widget': 'split-pane',
|
||||
'data-plugin-widget-props': JSON.stringify({ direction: 'horizontal', initialSize: 200, minSize: 100, maxSize: 400 }),
|
||||
},
|
||||
children: [
|
||||
{ id: 'pane-node', type: 1, element: 'div', attributes: { class: 'pane-node' }, children: [{ id: 'pn', type: 3, data: 'Pane' }] },
|
||||
{ id: 'pane-b', type: 1, element: 'div', attributes: {}, children: [{ id: 'pb', type: 3, data: 'Right' }] },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'grid',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: { 'data-plugin-widget': 'data-grid', 'data-plugin-widget-props': JSON.stringify(gridProps) },
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
const renderSurface = async (settled = true) => {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<PluginRemoteSurface
|
||||
tree={tree}
|
||||
css=""
|
||||
settled={settled}
|
||||
onEvent={(e) => {
|
||||
assert.equal(validateEvent(e), true, `Emitted event must satisfy contract schema: ${JSON.stringify(e)} -> ${JSON.stringify(validateEvent.errors)}`);
|
||||
events.push(e as unknown as Record<string, unknown>);
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
try {
|
||||
await renderSurface(true);
|
||||
const mainShadow = shadows[0]!;
|
||||
const stage = mainShadow.querySelector('.graph-stage') as HTMLElement;
|
||||
const nodeBtn = mainShadow.querySelector('.graph-node') as HTMLElement;
|
||||
const plainBtn = mainShadow.querySelector('.plain-btn') as HTMLElement;
|
||||
const scrollBox = mainShadow.querySelector('.scroll-box') as HTMLElement;
|
||||
const scrollRow = mainShadow.querySelector('.scroll-row') as HTMLElement;
|
||||
const fitBox = mainShadow.querySelector('.fit-box') as HTMLElement;
|
||||
const fitRow = mainShadow.querySelector('.fit-row') as HTMLElement;
|
||||
const paneNode = mainShadow.querySelector('.pane-node') as HTMLElement;
|
||||
const splitHandle = mainShadow.querySelector('[data-split-handle]') as HTMLElement;
|
||||
|
||||
// 1. Hover pointermove before any pointerdown must NOT forward
|
||||
await act(async () => {
|
||||
nodeBtn.dispatchEvent(makePointerEvent('pointermove', { clientX: 150, clientY: 90, pointerId: 3, button: -1, buttons: 0 }));
|
||||
});
|
||||
assert.equal(events.length, 0, 'idle hover pointermove must not flood plugin IPC');
|
||||
|
||||
// 2. pointerdown -> move (including outside node/surface) -> coalesce -> flush before pointerup
|
||||
const downEvt = makePointerEvent('pointerdown', { clientX: 140, clientY: 90, pointerId: 7, button: 0, buttons: 1, pointerType: 'mouse' });
|
||||
await act(async () => {
|
||||
nodeBtn.dispatchEvent(downEvt);
|
||||
});
|
||||
assert.equal(downEvt.defaultPrevented, false, 'pointerdown must not preventDefault so focus/click/text-selection remain intact');
|
||||
assert.deepEqual(capturedPointers, [{ target: nodeBtn, pointerId: 7 }], 'touch-action:none node engages host pointer capture');
|
||||
assert.deepEqual(events.at(-1), {
|
||||
nodeId: 'node-1',
|
||||
type: 'pointerdown',
|
||||
x: 40,
|
||||
y: 40,
|
||||
pointerId: 7,
|
||||
button: 0,
|
||||
buttons: 1,
|
||||
pointerType: 'mouse',
|
||||
});
|
||||
|
||||
// Unchanged coordinate move is skipped; first changed move forwards immediately (leading edge)
|
||||
// and rapid subsequent moves outside the surface coalesce and flush right before pointerup.
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 140, clientY: 90, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse' }));
|
||||
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 200, clientY: 130, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse', shiftKey: true }));
|
||||
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 215, clientY: 140, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse' }));
|
||||
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 80, clientY: 20, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse' }));
|
||||
dom.window.dispatchEvent(makePointerEvent('pointerup', { clientX: 80, clientY: 20, pointerId: 7, button: 0, buttons: 0, pointerType: 'mouse' }));
|
||||
});
|
||||
assert.deepEqual(releasedPointers, [{ target: nodeBtn, pointerId: 7 }], 'pointer capture released on pointerup');
|
||||
assert.deepEqual(events.slice(1), [
|
||||
{ nodeId: 'node-1', type: 'pointermove', x: 100, y: 80, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse', shiftKey: true },
|
||||
{ nodeId: 'node-1', type: 'pointermove', x: -20, y: -30, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse' },
|
||||
{ nodeId: 'node-1', type: 'pointerup', x: -20, y: -30, pointerId: 7, button: 0, buttons: 0, pointerType: 'mouse' },
|
||||
]);
|
||||
|
||||
// Moves after pointerup are ignored
|
||||
const countAfterUp = events.length;
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 300, clientY: 300, pointerId: 7, button: -1, buttons: 0 }));
|
||||
});
|
||||
assert.equal(events.length, countAfterUp);
|
||||
|
||||
// 3. Backpressure via settled={false} holds coalesced pointermove until settled flips true
|
||||
events.length = 0;
|
||||
await renderSurface(false);
|
||||
await act(async () => {
|
||||
nodeBtn.dispatchEvent(makePointerEvent('pointerdown', { clientX: 150, clientY: 100, pointerId: 9, button: 0, buttons: 1 }));
|
||||
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 190, clientY: 120, pointerId: 9, button: -1, buttons: 1 }));
|
||||
});
|
||||
assert.deepEqual(events.map((e) => e.type), ['pointerdown'], 'unsettled move waits for acknowledgement');
|
||||
await renderSurface(true);
|
||||
assert.deepEqual(events.map((e) => ({ type: e.type, x: e.x, y: e.y })), [
|
||||
{ type: 'pointerdown', x: 50, y: 50 },
|
||||
{ type: 'pointermove', x: 90, y: 70 },
|
||||
], 'move flushes immediately once settled becomes true');
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(makePointerEvent('pointercancel', { clientX: 95, clientY: 75, pointerId: 9, button: -1, buttons: 0 }));
|
||||
});
|
||||
assert.equal(events.at(-1)?.type, 'pointercancel');
|
||||
assert.equal(events.at(-1)?.nodeId, 'node-1');
|
||||
|
||||
// 4. Plain button does not engage setPointerCapture and still forwards normal click
|
||||
events.length = 0;
|
||||
const captureCountBeforePlain = capturedPointers.length;
|
||||
await act(async () => {
|
||||
plainBtn.dispatchEvent(makePointerEvent('pointerdown', { clientX: 120, clientY: 70, pointerId: 11, button: 0, buttons: 1 }));
|
||||
plainBtn.dispatchEvent(makePointerEvent('pointerup', { clientX: 120, clientY: 70, pointerId: 11, button: 0, buttons: 0 }));
|
||||
plainBtn.click();
|
||||
});
|
||||
assert.equal(capturedPointers.length, captureCountBeforePlain, 'plain button without touch-action:none skips setPointerCapture');
|
||||
assert.deepEqual(events.map((e) => e.type), ['pointerdown', 'pointerup', 'click']);
|
||||
|
||||
// 5. Wheel over non-scrollable remote node prevents default and forwards deltas; rapid ticks coalesce by summing deltas
|
||||
events.length = 0;
|
||||
const wheel1 = new dom.window.WheelEvent('wheel', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
clientX: 260,
|
||||
clientY: 190,
|
||||
deltaX: 0,
|
||||
deltaY: -120,
|
||||
deltaMode: 0,
|
||||
ctrlKey: true,
|
||||
});
|
||||
const wheel2 = new dom.window.WheelEvent('wheel', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
clientX: 265,
|
||||
clientY: 195,
|
||||
deltaX: 4,
|
||||
deltaY: -60,
|
||||
deltaMode: 0,
|
||||
ctrlKey: true,
|
||||
});
|
||||
const wheel3 = new dom.window.WheelEvent('wheel', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
clientX: 270,
|
||||
clientY: 200,
|
||||
deltaX: 6,
|
||||
deltaY: -40,
|
||||
deltaMode: 0,
|
||||
ctrlKey: true,
|
||||
});
|
||||
await act(async () => {
|
||||
stage.dispatchEvent(wheel1);
|
||||
stage.dispatchEvent(wheel2);
|
||||
stage.dispatchEvent(wheel3);
|
||||
});
|
||||
assert.equal(wheel1.defaultPrevented, true, 'non-scrollable wheel must preventDefault');
|
||||
assert.equal(wheel2.defaultPrevented, true, 'coalesced wheel tick must also preventDefault');
|
||||
assert.equal(wheel3.defaultPrevented, true, 'coalesced wheel tick must also preventDefault');
|
||||
assert.deepEqual([...events], [
|
||||
{ nodeId: 'stage', type: 'wheel', x: 160, y: 140, deltaX: 0, deltaY: -120, deltaMode: 0, ctrlKey: true },
|
||||
]);
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
});
|
||||
assert.deepEqual(events.at(-1), {
|
||||
nodeId: 'stage',
|
||||
type: 'wheel',
|
||||
x: 170,
|
||||
y: 150,
|
||||
deltaX: 10,
|
||||
deltaY: -100,
|
||||
deltaMode: 0,
|
||||
ctrlKey: true,
|
||||
});
|
||||
|
||||
// 6. Wheel over scrollable overflow container allows native scroll (no preventDefault, no wheel event)
|
||||
events.length = 0;
|
||||
Object.defineProperty(scrollBox, 'scrollHeight', { value: 600, configurable: true });
|
||||
Object.defineProperty(scrollBox, 'clientHeight', { value: 120, configurable: true });
|
||||
const scrollWheel = new dom.window.WheelEvent('wheel', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
clientX: 200,
|
||||
clientY: 150,
|
||||
deltaX: 0,
|
||||
deltaY: 100,
|
||||
deltaMode: 0,
|
||||
});
|
||||
await act(async () => {
|
||||
scrollRow.dispatchEvent(scrollWheel);
|
||||
});
|
||||
assert.equal(scrollWheel.defaultPrevented, false, 'scrollable overflow ancestor must keep native wheel scrolling');
|
||||
assert.equal(events.length, 0, 'wheel over scrollable overflow ancestor must not forward wheel');
|
||||
|
||||
// Non-overflowing overflow:auto container still forwards wheel
|
||||
Object.defineProperty(fitBox, 'scrollHeight', { value: 120, configurable: true });
|
||||
Object.defineProperty(fitBox, 'clientHeight', { value: 120, configurable: true });
|
||||
const fitWheel = new dom.window.WheelEvent('wheel', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
clientX: 200,
|
||||
clientY: 150,
|
||||
deltaX: 0,
|
||||
deltaY: -80,
|
||||
deltaMode: 0,
|
||||
});
|
||||
await act(async () => {
|
||||
fitRow.dispatchEvent(fitWheel);
|
||||
await new Promise((resolve) => setTimeout(resolve, 35));
|
||||
});
|
||||
assert.equal(fitWheel.defaultPrevented, true, 'non-overflowing overflow:auto box forwards wheel');
|
||||
assert.equal(events.length, 1);
|
||||
assert.equal(events[0].nodeId, 'fit-row');
|
||||
assert.equal(events[0].type, 'wheel');
|
||||
|
||||
// 7. touch-action:none canvas inside a scrollable surface host still claims wheel zoom
|
||||
events.length = 0;
|
||||
const hostDiv = mainShadow.host as HTMLElement;
|
||||
hostDiv.style.overflowY = 'auto';
|
||||
Object.defineProperty(hostDiv, 'scrollHeight', { value: 1400, configurable: true });
|
||||
Object.defineProperty(hostDiv, 'clientHeight', { value: 600, configurable: true });
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 35));
|
||||
});
|
||||
const stageWheelInScrollableHost = new dom.window.WheelEvent('wheel', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
clientX: 220,
|
||||
clientY: 160,
|
||||
deltaX: 0,
|
||||
deltaY: -90,
|
||||
deltaMode: 0,
|
||||
});
|
||||
await act(async () => {
|
||||
nodeBtn.dispatchEvent(stageWheelInScrollableHost);
|
||||
});
|
||||
assert.equal(stageWheelInScrollableHost.defaultPrevented, true, 'touch-action:none graph node claims wheel even when outer host is scrollable');
|
||||
assert.equal(events.at(-1)?.type, 'wheel');
|
||||
assert.equal(events.at(-1)?.nodeId, 'node-1');
|
||||
|
||||
// 8. Slotted widget pointer & wheel events are never forwarded as generic plugin events
|
||||
events.length = 0;
|
||||
const gridHost = document.querySelector('[data-plugin-widget-host="data-grid"]') as HTMLElement;
|
||||
const gridCell = gridHost.querySelector('[role="gridcell"]') as HTMLElement;
|
||||
const widgetWheel = new dom.window.WheelEvent('wheel', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
composed: true,
|
||||
clientX: 200,
|
||||
clientY: 150,
|
||||
deltaX: 0,
|
||||
deltaY: 120,
|
||||
deltaMode: 0,
|
||||
});
|
||||
await act(async () => {
|
||||
gridCell.dispatchEvent(makePointerEvent('pointerdown', { clientX: 200, clientY: 150, pointerId: 21, button: 0, buttons: 1 }));
|
||||
gridCell.dispatchEvent(makePointerEvent('pointermove', { clientX: 240, clientY: 170, pointerId: 21, button: -1, buttons: 1 }));
|
||||
gridCell.dispatchEvent(makePointerEvent('pointerup', { clientX: 240, clientY: 170, pointerId: 21, button: 0, buttons: 0 }));
|
||||
gridCell.dispatchEvent(widgetWheel);
|
||||
});
|
||||
assert.equal(widgetWheel.defaultPrevented, false, 'slotted widget wheel must not be intercepted by surface');
|
||||
assert.equal(
|
||||
events.some((e) => ['pointerdown', 'pointermove', 'pointerup', 'wheel'].includes(String(e.type))),
|
||||
false,
|
||||
'slotted widget pointer and wheel events must not forward as generic surface events',
|
||||
);
|
||||
|
||||
// 9. SplitPane handle drag does not forward generic pointer events, while remote nodes inside its panes do
|
||||
events.length = 0;
|
||||
await act(async () => {
|
||||
splitHandle.dispatchEvent(makePointerEvent('pointerdown', { clientX: 200, clientY: 100, pointerId: 31, button: 0, buttons: 1 }));
|
||||
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 250, clientY: 100, pointerId: 31, button: -1, buttons: 1 }));
|
||||
dom.window.dispatchEvent(makePointerEvent('pointerup', { clientX: 250, clientY: 100, pointerId: 31, button: 0, buttons: 0 }));
|
||||
});
|
||||
assert.equal(
|
||||
events.some((e) => ['pointerdown', 'pointermove', 'pointerup'].includes(String(e.type))),
|
||||
false,
|
||||
'split-pane handle must not forward generic pointer events',
|
||||
);
|
||||
assert.ok(events.some((e) => e.nodeId === 'split' && e.widgetEvent === 'resizeEnd'), 'split-pane resize still works');
|
||||
|
||||
events.length = 0;
|
||||
await act(async () => {
|
||||
paneNode.dispatchEvent(makePointerEvent('pointerdown', { clientX: 160, clientY: 110, pointerId: 32, button: 0, buttons: 1 }));
|
||||
dom.window.dispatchEvent(makePointerEvent('pointerup', { clientX: 160, clientY: 110, pointerId: 32, button: 0, buttons: 0 }));
|
||||
});
|
||||
assert.deepEqual(events.map((e) => ({ nodeId: e.nodeId, type: e.type, x: e.x, y: e.y })), [
|
||||
{ nodeId: 'pane-node', type: 'pointerdown', x: 60, y: 60 },
|
||||
{ nodeId: 'pane-node', type: 'pointerup', x: 60, y: 60 },
|
||||
]);
|
||||
|
||||
// 10. Unmounting the surface mid-drag emits pointercancel so a retained plugin session does not stay in a drag.
|
||||
events.length = 0;
|
||||
await act(async () => {
|
||||
nodeBtn.dispatchEvent(makePointerEvent('pointerdown', { clientX: 160, clientY: 110, pointerId: 41, button: 0, buttons: 1, pointerType: 'mouse' }));
|
||||
});
|
||||
assert.equal(events[0]?.type, 'pointerdown');
|
||||
assert.equal(events[0]?.pointerId, 41);
|
||||
await act(async () => { root.unmount(); });
|
||||
assert.deepEqual(events.at(-1), {
|
||||
nodeId: 'node-1',
|
||||
type: 'pointercancel',
|
||||
x: 60,
|
||||
y: 60,
|
||||
pointerId: 41,
|
||||
button: -1,
|
||||
buttons: 0,
|
||||
});
|
||||
} finally {
|
||||
await act(async () => root.unmount());
|
||||
dom.window.close();
|
||||
for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
}
|
||||
});
|
||||
|
||||
test('PluginRemoteSurface leaves wheel to a scrollable host-owned popover panel', async () => {
|
||||
const { JSDOM } = await import('jsdom');
|
||||
const { act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { PluginRemoteSurface } = await import('./PluginRemoteSurface');
|
||||
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost', pretendToBeVisual: true });
|
||||
const saved = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'WheelEvent', 'ShadowRoot']) {
|
||||
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
const val = key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window];
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: val });
|
||||
}
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
|
||||
Object.assign(dom.window, {
|
||||
ResizeObserver: class {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
},
|
||||
});
|
||||
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({
|
||||
x: 100, y: 50, width: 800, height: 600, top: 50, left: 100, right: 900, bottom: 650, toJSON() {},
|
||||
});
|
||||
const shadows: ShadowRoot[] = [];
|
||||
const nativeAttach = dom.window.Element.prototype.attachShadow;
|
||||
dom.window.Element.prototype.attachShadow = function (options) {
|
||||
const s = nativeAttach.call(this, options);
|
||||
shadows.push(s as unknown as ShadowRoot);
|
||||
return s;
|
||||
};
|
||||
|
||||
const events: Array<Record<string, unknown>> = [];
|
||||
const root = createRoot(dom.window.document.getElementById('root')!);
|
||||
try {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<PluginRemoteSurface
|
||||
tree={{
|
||||
children: [
|
||||
{
|
||||
id: 'menu',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: {
|
||||
'data-plugin-popover': 'true',
|
||||
'data-plugin-anchor-x': '40',
|
||||
'data-plugin-anchor-y': '20',
|
||||
'data-plugin-popover-width': '240',
|
||||
'data-plugin-popover-max-height': '160',
|
||||
open: '',
|
||||
},
|
||||
children: [
|
||||
{
|
||||
id: 'row',
|
||||
type: 1,
|
||||
element: 'button',
|
||||
attributes: { type: 'button' },
|
||||
children: [{ id: 'row-t', type: 3, data: 'A tall menu item' }],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}}
|
||||
css=""
|
||||
settled={true}
|
||||
onEvent={(e) => { events.push(e as unknown as Record<string, unknown>); }}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const popover = dom.window.document.querySelector('[data-plugin-view-popover]') as HTMLElement | null;
|
||||
assert.ok(popover, 'host-owned popover panel is present');
|
||||
popover!.style.overflow = 'auto';
|
||||
Object.defineProperty(popover!, 'scrollHeight', { configurable: true, value: 400 });
|
||||
Object.defineProperty(popover!, 'clientHeight', { configurable: true, value: 160 });
|
||||
|
||||
const popoverShadow = shadows.find((s) => popover!.contains((s as ShadowRoot).host)) ?? shadows.at(-1);
|
||||
const row = popoverShadow!.querySelector('button') as HTMLElement;
|
||||
assert.ok(row, 'popover row is present');
|
||||
const wheel = new dom.window.WheelEvent('wheel', { bubbles: true, cancelable: true, deltaX: 0, deltaY: 80, deltaMode: 0, clientX: 120, clientY: 80 });
|
||||
await act(async () => { row.dispatchEvent(wheel); });
|
||||
assert.equal(wheel.defaultPrevented, false, 'scrollable popover panel must keep native wheel scrolling');
|
||||
assert.equal(events.some((e) => e.type === 'wheel'), false, 'wheel over a scrollable popover panel must not be forwarded');
|
||||
} finally {
|
||||
await act(async () => root.unmount());
|
||||
dom.window.close();
|
||||
for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
}
|
||||
});
|
||||
|
||||
test('PluginRemoteSurface + hostDom end-to-end round-trip supports node drag, incident edge tracking, background pan, and wheel zoom', async () => {
|
||||
const dom = new JSDOM('<!doctype html><div id="host-root"></div>', { url: 'http://localhost', pretendToBeVisual: true });
|
||||
const saved = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'HTMLInputElement', 'HTMLTextAreaElement', 'HTMLSelectElement', 'HTMLOptionElement', 'HTMLFormElement', 'Node', 'MutationObserver', 'Event', 'MouseEvent', 'WheelEvent', 'PointerEvent', 'CustomEvent', 'ShadowRoot']) {
|
||||
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
const val = key === 'window' ? dom.window : key === 'PointerEvent' ? dom.window.MouseEvent : dom.window[key as keyof typeof dom.window];
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: val });
|
||||
}
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
|
||||
Object.assign(dom.window, { PointerEvent: dom.window.MouseEvent });
|
||||
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({
|
||||
x: 40, y: 20, width: 600, height: 400, top: 20, left: 40, right: 640, bottom: 420, toJSON() {},
|
||||
});
|
||||
|
||||
// In Electron the visible host renderer and hidden plugin runtime run in separate
|
||||
// BrowserWindows. Guard host window capture listeners while forwarding into hostDom
|
||||
// so plugin-side synthetic dispatches do not loop back into the host in a shared JSDOM.
|
||||
let forwardingToPlugin = false;
|
||||
const origAdd = dom.window.addEventListener.bind(dom.window);
|
||||
const origRemove = dom.window.removeEventListener.bind(dom.window);
|
||||
const wrappedListeners = new WeakMap<EventListenerOrEventListenerObject, EventListener>();
|
||||
dom.window.addEventListener = ((type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions) => {
|
||||
const capture = typeof options === 'boolean' ? options : Boolean(options?.capture);
|
||||
if (type === 'pointermove' || type === 'pointerup' || type === 'pointercancel') {
|
||||
const wrapped: EventListener = (evt) => {
|
||||
if (capture ? forwardingToPlugin : !forwardingToPlugin) return;
|
||||
if (typeof listener === 'function') listener(evt);
|
||||
else listener.handleEvent(evt);
|
||||
};
|
||||
wrappedListeners.set(listener, wrapped);
|
||||
return origAdd(type, wrapped, options);
|
||||
}
|
||||
return origAdd(type, listener, options);
|
||||
}) as typeof dom.window.addEventListener;
|
||||
dom.window.removeEventListener = ((type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions) => {
|
||||
return origRemove(type, wrappedListeners.get(listener) ?? listener, options);
|
||||
}) as typeof dom.window.removeEventListener;
|
||||
|
||||
const shadows: ShadowRoot[] = [];
|
||||
const nativeAttach = dom.window.Element.prototype.attachShadow;
|
||||
dom.window.Element.prototype.attachShadow = function (options) {
|
||||
const s = nativeAttach.call(this, options);
|
||||
shadows.push(s as unknown as ShadowRoot);
|
||||
return s;
|
||||
};
|
||||
|
||||
const { act, useEffect, useRef, useState } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { PluginRemoteSurface } = await import('./PluginRemoteSurface');
|
||||
const { createPluginRemoteTree } = await import('../../application/state/pluginRemoteTree');
|
||||
const { registerHostReactView } = await import('../../packages/plugin-sdk/src/hostReact');
|
||||
const { createDefinitionValidator } = await import('../../electron/plugins/contractValidator.cjs');
|
||||
const validateEvent = createDefinitionValidator('HostDrawnViewEvent');
|
||||
|
||||
const remoteTree = createPluginRemoteTree();
|
||||
const hostRoot = createRoot(document.getElementById('host-root')!);
|
||||
let pluginReceive: (message: unknown) => void = () => {};
|
||||
let latestEventId = 0;
|
||||
let latestAck = 0;
|
||||
|
||||
const renderHostSurface = () => {
|
||||
hostRoot.render(
|
||||
<PluginRemoteSurface
|
||||
tree={remoteTree.snapshot()}
|
||||
css=""
|
||||
settled={latestAck >= latestEventId}
|
||||
onEvent={(event) => {
|
||||
const stamped = { ...event, eventId: ++latestEventId };
|
||||
assert.equal(validateEvent(stamped), true, `Host event failed contract schema: ${JSON.stringify(validateEvent.errors)}`);
|
||||
forwardingToPlugin = true;
|
||||
try {
|
||||
pluginReceive({ kind: 'host-ui.event', instanceId: 'e2e-1', event: stamped });
|
||||
} finally {
|
||||
forwardingToPlugin = false;
|
||||
}
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
};
|
||||
|
||||
const views = {
|
||||
onDidReceiveMessage(_id: string, listener: (value: unknown) => void) {
|
||||
pluginReceive = listener;
|
||||
return { dispose() {} };
|
||||
},
|
||||
postMessage(_id: string, value: unknown) {
|
||||
const msg = value as { kind?: string; mutations?: unknown[]; acknowledgedEvent?: number };
|
||||
if (msg.kind !== 'host-ui.update') return;
|
||||
if (Array.isArray(msg.mutations) && msg.mutations.length > 0) {
|
||||
remoteTree.apply(msg.mutations);
|
||||
}
|
||||
if (typeof msg.acknowledgedEvent === 'number') {
|
||||
latestAck = msg.acknowledgedEvent;
|
||||
}
|
||||
renderHostSurface();
|
||||
},
|
||||
getState: async () => undefined,
|
||||
setState: async () => {},
|
||||
setBadge: async () => {},
|
||||
};
|
||||
|
||||
function MiniGraphCanvas() {
|
||||
const stageRef = useRef<HTMLDivElement | null>(null);
|
||||
const [nodePos, setNodePos] = useState({ x: 80, y: 100 });
|
||||
const fixedPos = { x: 280, y: 100 };
|
||||
const [viewport, setViewport] = useState({ x: 0, y: 0, zoom: 1 });
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const dragRef = useRef<{ kind: 'node' | 'pan'; pointerId: number; startX: number; startY: number; originX: number; originY: number } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const el = stageRef.current;
|
||||
if (!el) return;
|
||||
const onWheel = (event: WheelEvent) => {
|
||||
event.preventDefault();
|
||||
setViewport((prev) => ({
|
||||
...prev,
|
||||
zoom: Math.round(prev.zoom * (event.deltaY < 0 ? 1.2 : 0.8) * 100) / 100,
|
||||
}));
|
||||
};
|
||||
el.addEventListener('wheel', onWheel, { passive: false });
|
||||
return () => el.removeEventListener('wheel', onWheel);
|
||||
}, []);
|
||||
|
||||
// Mirror real canvas window-level drag listeners inside the plugin runtime.
|
||||
useEffect(() => {
|
||||
if (!dragging) return;
|
||||
const onMove = (event: PointerEvent) => {
|
||||
const drag = dragRef.current;
|
||||
if (!drag || drag.pointerId !== event.pointerId) return;
|
||||
if (drag.kind === 'node') {
|
||||
setNodePos({ x: drag.originX + (event.clientX - drag.startX), y: drag.originY + (event.clientY - drag.startY) });
|
||||
} else {
|
||||
setViewport((prev) => ({ ...prev, x: drag.originX + (event.clientX - drag.startX), y: drag.originY + (event.clientY - drag.startY) }));
|
||||
}
|
||||
};
|
||||
const onUp = (event: PointerEvent) => {
|
||||
if (dragRef.current?.pointerId === event.pointerId) {
|
||||
dragRef.current = null;
|
||||
setDragging(false);
|
||||
}
|
||||
};
|
||||
window.addEventListener('pointermove', onMove as unknown as EventListener);
|
||||
window.addEventListener('pointerup', onUp as unknown as EventListener);
|
||||
return () => {
|
||||
window.removeEventListener('pointermove', onMove as unknown as EventListener);
|
||||
window.removeEventListener('pointerup', onUp as unknown as EventListener);
|
||||
};
|
||||
}, [dragging]);
|
||||
|
||||
const edgeLen = Math.round(Math.hypot(fixedPos.x - nodePos.x, fixedPos.y - nodePos.y));
|
||||
|
||||
return (
|
||||
<div
|
||||
className="e2e-stage"
|
||||
ref={stageRef}
|
||||
style={{ overflow: 'hidden', touchAction: 'none' }}
|
||||
onPointerDown={(e) => {
|
||||
if (e.button !== 0) return;
|
||||
dragRef.current = { kind: 'pan', pointerId: e.pointerId, startX: e.clientX, startY: e.clientY, originX: viewport.x, originY: viewport.y };
|
||||
setDragging(true);
|
||||
}}
|
||||
>
|
||||
<div className="e2e-world" style={{ transform: `translate(${viewport.x}px, ${viewport.y}px) scale(${viewport.zoom})` }}>
|
||||
<div className="e2e-edge" style={{ width: `${edgeLen}px`, transform: `translate(${nodePos.x}px, ${nodePos.y}px)` }} />
|
||||
<button
|
||||
type="button"
|
||||
className="e2e-node"
|
||||
style={{ touchAction: 'none', transform: `translate(${nodePos.x}px, ${nodePos.y}px)` }}
|
||||
onPointerDown={(e) => {
|
||||
if (e.button !== 0) return;
|
||||
e.stopPropagation();
|
||||
dragRef.current = { kind: 'node', pointerId: e.pointerId, startX: e.clientX, startY: e.clientY, originX: nodePos.x, originY: nodePos.y };
|
||||
setDragging(true);
|
||||
}}
|
||||
>
|
||||
N1
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const makePointer = (type: string, clientX: number, clientY: number, pointerId: number, button: number, buttons: number) => {
|
||||
const evt = new dom.window.MouseEvent(type, { bubbles: true, cancelable: true, composed: true, clientX, clientY, button, buttons });
|
||||
Object.defineProperty(evt, 'pointerId', { value: pointerId });
|
||||
return evt;
|
||||
};
|
||||
|
||||
const registration = registerHostReactView(views as never, 'com.example.e2e-graph', () => <MiniGraphCanvas />);
|
||||
try {
|
||||
await act(async () => {
|
||||
pluginReceive({ kind: 'host-ui.open', instanceId: 'e2e-1' });
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
});
|
||||
|
||||
const shadow = shadows[0]!;
|
||||
const stageEl = shadow.querySelector('.e2e-stage') as HTMLElement;
|
||||
const worldEl = shadow.querySelector('.e2e-world') as HTMLElement;
|
||||
const edgeEl = shadow.querySelector('.e2e-edge') as HTMLElement;
|
||||
const nodeEl = shadow.querySelector('.e2e-node') as HTMLElement;
|
||||
assert.equal(nodeEl.style.transform, 'translate(80px, 100px)');
|
||||
assert.equal(edgeEl.style.width, '200px');
|
||||
|
||||
// Drag node across the visible host surface (pointermove/up dispatched on host window outside the node)
|
||||
await act(async () => {
|
||||
nodeEl.dispatchEvent(makePointer('pointerdown', 120, 120, 1, 0, 1));
|
||||
await new Promise((resolve) => setTimeout(resolve, 15));
|
||||
});
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(makePointer('pointermove', 170, 160, 1, -1, 1));
|
||||
await new Promise((resolve) => setTimeout(resolve, 15));
|
||||
});
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(makePointer('pointerup', 170, 160, 1, 0, 0));
|
||||
await new Promise((resolve) => setTimeout(resolve, 25));
|
||||
});
|
||||
|
||||
assert.equal(nodeEl.style.transform, 'translate(130px, 140px)', 'visible host shadow DOM node must move by (+50, +40)');
|
||||
assert.equal(edgeEl.style.width, `${Math.round(Math.hypot(280 - 130, 100 - 140))}px`, 'visible host incident edge must follow node');
|
||||
|
||||
// Pan background stage and wheel-zoom
|
||||
await act(async () => {
|
||||
stageEl.dispatchEvent(makePointer('pointerdown', 300, 200, 2, 0, 1));
|
||||
await new Promise((resolve) => setTimeout(resolve, 15));
|
||||
});
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(makePointer('pointermove', 340, 230, 2, -1, 1));
|
||||
await new Promise((resolve) => setTimeout(resolve, 15));
|
||||
});
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(makePointer('pointerup', 340, 230, 2, 0, 0));
|
||||
await new Promise((resolve) => setTimeout(resolve, 25));
|
||||
});
|
||||
const wheelEvt = new dom.window.WheelEvent('wheel', { bubbles: true, cancelable: true, clientX: 250, clientY: 180, deltaX: 0, deltaY: -120, deltaMode: 0 });
|
||||
await act(async () => {
|
||||
stageEl.dispatchEvent(wheelEvt);
|
||||
await new Promise((resolve) => setTimeout(resolve, 25));
|
||||
});
|
||||
|
||||
assert.equal(wheelEvt.defaultPrevented, true);
|
||||
assert.equal(worldEl.style.transform, 'translate(40px, 30px) scale(1.2)', 'visible host shadow DOM world must pan and wheel-zoom');
|
||||
|
||||
await act(async () => {
|
||||
pluginReceive({ kind: 'host-ui.close', instanceId: 'e2e-1' });
|
||||
});
|
||||
} finally {
|
||||
await act(async () => {
|
||||
registration.dispose();
|
||||
hostRoot.unmount();
|
||||
});
|
||||
dom.window.close();
|
||||
for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
}
|
||||
});
|
||||
@@ -19,8 +19,13 @@ export type PluginSurfaceEvent = import('@netcatty/plugin-contract').HostDrawnVi
|
||||
|
||||
const MAX_EVENT_VALUE_LENGTH = 131072;
|
||||
const SCROLL_THROTTLE_MS = 60;
|
||||
const POINTER_MOVE_THROTTLE_MS = 24;
|
||||
const POINTER_MOVE_BACKPRESSURE_MAX_MS = 96;
|
||||
const WHEEL_THROTTLE_MS = 24;
|
||||
const SURFACE_EVENTS = [
|
||||
'click', 'dblclick', 'contextmenu',
|
||||
'pointerdown', 'pointermove', 'pointerup', 'pointercancel',
|
||||
'wheel',
|
||||
'input', 'change',
|
||||
'keydown', 'keyup',
|
||||
'focusin', 'focusout',
|
||||
@@ -337,6 +342,163 @@ function readSelectionRange(
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function readSurfacePoint(
|
||||
event: MouseEvent,
|
||||
surfaceEl: HTMLElement | null,
|
||||
): { x: number; y: number } {
|
||||
const rect = surfaceEl?.getBoundingClientRect();
|
||||
const rawX = rect ? event.clientX - rect.left : event.clientX;
|
||||
const rawY = rect ? event.clientY - rect.top : event.clientY;
|
||||
return {
|
||||
x: Number.isFinite(rawX) ? Math.round(rawX) : 0,
|
||||
y: Number.isFinite(rawY) ? Math.round(rawY) : 0,
|
||||
};
|
||||
}
|
||||
|
||||
function readModifierKeys(event: MouseEvent | WheelEvent): {
|
||||
ctrlKey?: true;
|
||||
metaKey?: true;
|
||||
altKey?: true;
|
||||
shiftKey?: true;
|
||||
} {
|
||||
return {
|
||||
...(event.ctrlKey ? { ctrlKey: true as const } : {}),
|
||||
...(event.metaKey ? { metaKey: true as const } : {}),
|
||||
...(event.altKey ? { altKey: true as const } : {}),
|
||||
...(event.shiftKey ? { shiftKey: true as const } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function readPointerId(event: Event): number {
|
||||
const raw = (event as PointerEvent).pointerId;
|
||||
if (typeof raw === 'number' && Number.isFinite(raw)) {
|
||||
return Math.max(-2147483648, Math.min(2147483647, Math.trunc(raw)));
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
function readPointerType(event: Event): 'mouse' | 'pen' | 'touch' | undefined {
|
||||
const raw = (event as PointerEvent).pointerType;
|
||||
return raw === 'mouse' || raw === 'pen' || raw === 'touch' ? raw : undefined;
|
||||
}
|
||||
|
||||
function readPointerButton(event: MouseEvent): number {
|
||||
return typeof event.button === 'number' && Number.isFinite(event.button)
|
||||
? Math.max(-1, Math.min(32, Math.trunc(event.button)))
|
||||
: 0;
|
||||
}
|
||||
|
||||
function readPointerButtons(event: MouseEvent): number {
|
||||
return typeof event.buttons === 'number' && Number.isFinite(event.buttons)
|
||||
? Math.max(0, Math.min(65535, Math.trunc(event.buttons)))
|
||||
: 0;
|
||||
}
|
||||
|
||||
function roundWheelDelta(value: number): number {
|
||||
return Number.isFinite(value) ? Math.round(value * 100) / 100 : 0;
|
||||
}
|
||||
|
||||
function isScrollableOverflowValue(value: string | undefined): boolean {
|
||||
return value === 'auto' || value === 'scroll' || value === 'overlay';
|
||||
}
|
||||
|
||||
function readOverflowToken(value: string | undefined, axis: 'x' | 'y'): string | undefined {
|
||||
if (!value) return undefined;
|
||||
const parts = value.trim().split(/\s+/);
|
||||
return axis === 'y' ? (parts[1] ?? parts[0]) : parts[0];
|
||||
}
|
||||
|
||||
function readAxisOverflow(
|
||||
el: HTMLElement,
|
||||
style: CSSStyleDeclaration | undefined,
|
||||
axis: 'x' | 'y',
|
||||
): string | undefined {
|
||||
// Prefer a scrollable value from computed or inline styles. Some test DOMs
|
||||
// report the initial `visible` computed overflow even when the element has
|
||||
// an inline `overflow: auto` shorthand.
|
||||
const candidates = [
|
||||
axis === 'y' ? style?.overflowY : style?.overflowX,
|
||||
axis === 'y' ? el.style.overflowY : el.style.overflowX,
|
||||
readOverflowToken(style?.overflow, axis),
|
||||
readOverflowToken(el.style.overflow, axis),
|
||||
];
|
||||
for (const value of candidates) {
|
||||
if (isScrollableOverflowValue(value)) return value;
|
||||
}
|
||||
return candidates.find((value) => value && value !== 'visible') ?? candidates[0];
|
||||
}
|
||||
|
||||
function canElementScrollForWheel(
|
||||
el: HTMLElement,
|
||||
view: Window & typeof globalThis,
|
||||
deltaX: number,
|
||||
deltaY: number,
|
||||
): boolean {
|
||||
const style = view.getComputedStyle?.(el);
|
||||
const canScrollY = deltaY !== 0
|
||||
&& isScrollableOverflowValue(readAxisOverflow(el, style, 'y'))
|
||||
&& el.scrollHeight > el.clientHeight + 1;
|
||||
const canScrollX = deltaX !== 0
|
||||
&& isScrollableOverflowValue(readAxisOverflow(el, style, 'x'))
|
||||
&& el.scrollWidth > el.clientWidth + 1;
|
||||
return canScrollY || canScrollX;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wheel vs native scroll rule:
|
||||
* Walk ancestors inside the shadow root (and then the surface's own scroll host
|
||||
* unless a non-scrollable element declares `touch-action: none` to claim canvas
|
||||
* gestures). If an ancestor has `overflow: auto|scroll|overlay` with actual
|
||||
* overflow along the wheel axis, leave the event to native scrolling (existing
|
||||
* throttled `scroll` events still forward). Otherwise `preventDefault()` so the
|
||||
* surrounding workbench does not steal the gesture, and forward coalesced `wheel`.
|
||||
*/
|
||||
function hasScrollableAncestorForWheel(
|
||||
target: HTMLElement,
|
||||
shadow: ShadowRoot,
|
||||
host: HTMLElement | null,
|
||||
view: Window & typeof globalThis,
|
||||
deltaX: number,
|
||||
deltaY: number,
|
||||
): boolean {
|
||||
let current: HTMLElement | null = target;
|
||||
let hitGestureBoundary = false;
|
||||
while (current) {
|
||||
if (canElementScrollForWheel(current, view, deltaX, deltaY)) return true;
|
||||
const touchAction = view.getComputedStyle?.(current)?.touchAction || current.style.touchAction;
|
||||
if (touchAction === 'none') {
|
||||
hitGestureBoundary = true;
|
||||
break;
|
||||
}
|
||||
const parent = current.parentElement;
|
||||
if (!parent || parent.getRootNode() !== shadow) break;
|
||||
current = parent;
|
||||
}
|
||||
if (!hitGestureBoundary && host && canElementScrollForWheel(host, view, deltaX, deltaY)) {
|
||||
return true;
|
||||
}
|
||||
// Nested popover surfaces live in a portaled PluginViewPopover panel. That
|
||||
// panel (not the inner overflow-auto host) is often the only element with a
|
||||
// bounded max-height, so include it when deciding who owns the wheel.
|
||||
if (!hitGestureBoundary) {
|
||||
const popover = (host ?? target).closest?.('[data-plugin-view-popover]') as HTMLElement | null;
|
||||
if (popover && canElementScrollForWheel(popover, view, deltaX, deltaY)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
type ActivePointerGesture = {
|
||||
nodeId: string;
|
||||
pointerId: number;
|
||||
capturedElement: HTMLElement | null;
|
||||
lastSentX: number;
|
||||
lastSentY: number;
|
||||
lastMoveSentAt: number;
|
||||
pendingMove: PluginSurfaceEvent | null;
|
||||
pendingMoveSince: number;
|
||||
moveTimer: ReturnType<typeof setTimeout> | null;
|
||||
};
|
||||
|
||||
/** Host-owned DOM, kept inside a closed shadow root and a clipped stacking context. */
|
||||
export function PluginRemoteSurface({ tree, css, onEvent, settled = true, loadImage, depth = 0 }: { depth?: number; tree: unknown; css: string; settled?: boolean; loadImage?(path: string): Promise<string>; onEvent(event: PluginSurfaceEvent): void }) {
|
||||
const checkedTree = useMemo(() => {
|
||||
@@ -373,6 +535,8 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
|
||||
const surfaceRef = useRef<HTMLDivElement>(null);
|
||||
const hostRef = useRef<HTMLDivElement>(null);
|
||||
const onEventRef = useRef(onEvent); onEventRef.current = onEvent;
|
||||
const settledRef = useRef(settled); settledRef.current = settled;
|
||||
const flushPendingMovesRef = useRef<(() => void) | null>(null);
|
||||
const shadowRef = useRef<ShadowRoot | null>(null);
|
||||
const [shadow, setShadow] = useState<ShadowRoot | null>(null);
|
||||
const [shadowHost, setShadowHost] = useState<HTMLDivElement | null>(null);
|
||||
@@ -387,6 +551,10 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
|
||||
setShadowHost(host);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (settled) flushPendingMovesRef.current?.();
|
||||
}, [settled]);
|
||||
|
||||
const surfaceContextValue = useMemo(
|
||||
() => ({ css, onEvent, depth, shadowHost }),
|
||||
[css, onEvent, depth, shadowHost],
|
||||
@@ -394,8 +562,15 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
|
||||
|
||||
useEffect(() => {
|
||||
if (!shadow) return;
|
||||
const view = shadow.ownerDocument.defaultView;
|
||||
const scrollTimers = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
const pendingScroll = new Map<string, PluginSurfaceEvent>();
|
||||
const activeGestures = new Map<number, ActivePointerGesture>();
|
||||
const handledPointerEvents = new WeakSet<Event>();
|
||||
let windowPointerListenersAttached = false;
|
||||
let wheelTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let pendingWheel: PluginSurfaceEvent | null = null;
|
||||
let lastWheelSentAt = 0;
|
||||
|
||||
const flushScroll = (nodeId: string) => {
|
||||
scrollTimers.delete(nodeId);
|
||||
@@ -406,10 +581,203 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
|
||||
}
|
||||
};
|
||||
|
||||
const flushWheel = () => {
|
||||
if (wheelTimer !== null) {
|
||||
clearTimeout(wheelTimer);
|
||||
wheelTimer = null;
|
||||
}
|
||||
const evt = pendingWheel;
|
||||
pendingWheel = null;
|
||||
if (!evt || ((evt.deltaX ?? 0) === 0 && (evt.deltaY ?? 0) === 0)) return;
|
||||
lastWheelSentAt = Date.now();
|
||||
onEventRef.current(evt);
|
||||
};
|
||||
|
||||
const emitGestureMove = (gesture: ActivePointerGesture, moveEvent: PluginSurfaceEvent, now: number) => {
|
||||
if (gesture.moveTimer !== null) {
|
||||
clearTimeout(gesture.moveTimer);
|
||||
gesture.moveTimer = null;
|
||||
}
|
||||
gesture.pendingMove = null;
|
||||
gesture.pendingMoveSince = 0;
|
||||
if (moveEvent.x === gesture.lastSentX && moveEvent.y === gesture.lastSentY) return;
|
||||
gesture.lastSentX = moveEvent.x ?? gesture.lastSentX;
|
||||
gesture.lastSentY = moveEvent.y ?? gesture.lastSentY;
|
||||
gesture.lastMoveSentAt = now;
|
||||
onEventRef.current(moveEvent);
|
||||
};
|
||||
|
||||
const scheduleGestureMoveFlush = (gesture: ActivePointerGesture) => {
|
||||
if (gesture.moveTimer !== null || !gesture.pendingMove) return;
|
||||
const now = Date.now();
|
||||
const throttleWait = Math.max(0, POINTER_MOVE_THROTTLE_MS - (now - gesture.lastMoveSentAt));
|
||||
const backpressureWait = settledRef.current
|
||||
? 0
|
||||
: Math.max(0, POINTER_MOVE_BACKPRESSURE_MAX_MS - (now - gesture.pendingMoveSince));
|
||||
const delay = Math.max(1, throttleWait, backpressureWait);
|
||||
gesture.moveTimer = setTimeout(() => {
|
||||
gesture.moveTimer = null;
|
||||
if (activeGestures.get(gesture.pointerId) !== gesture || !gesture.pendingMove) return;
|
||||
const tickNow = Date.now();
|
||||
const elapsed = tickNow - gesture.lastMoveSentAt;
|
||||
const waitedEnough = settledRef.current || tickNow - gesture.pendingMoveSince >= POINTER_MOVE_BACKPRESSURE_MAX_MS;
|
||||
if (elapsed >= POINTER_MOVE_THROTTLE_MS && waitedEnough) {
|
||||
emitGestureMove(gesture, gesture.pendingMove, tickNow);
|
||||
} else {
|
||||
scheduleGestureMoveFlush(gesture);
|
||||
}
|
||||
}, delay);
|
||||
};
|
||||
|
||||
const releaseGesture = (gesture: ActivePointerGesture) => {
|
||||
if (gesture.moveTimer !== null) {
|
||||
clearTimeout(gesture.moveTimer);
|
||||
gesture.moveTimer = null;
|
||||
}
|
||||
gesture.pendingMove = null;
|
||||
gesture.pendingMoveSince = 0;
|
||||
if (gesture.capturedElement) {
|
||||
try {
|
||||
gesture.capturedElement.releasePointerCapture?.(gesture.pointerId);
|
||||
} catch {
|
||||
// Capture may already have been released natively.
|
||||
}
|
||||
gesture.capturedElement = null;
|
||||
}
|
||||
activeGestures.delete(gesture.pointerId);
|
||||
if (activeGestures.size === 0) detachWindowPointerListeners();
|
||||
};
|
||||
|
||||
/**
|
||||
* Active pointer gestures are tracked at the host surface so plugin drags
|
||||
* continue after leaving the originating node or surface (plugin-side
|
||||
* setPointerCapture cannot capture the visible host pointer). Moves skip
|
||||
* unchanged coordinates, coalesce under POINTER_MOVE_THROTTLE_MS, and adapt
|
||||
* to host-ui acknowledgedEvent backpressure via `settled`.
|
||||
*/
|
||||
const onGesturePointerEvent = (event: Event) => {
|
||||
if (!view || activeGestures.size === 0 || handledPointerEvents.has(event)) return;
|
||||
const pointerId = readPointerId(event);
|
||||
const gesture = activeGestures.get(pointerId);
|
||||
if (!gesture) return;
|
||||
handledPointerEvents.add(event);
|
||||
|
||||
const isMouseLike = event instanceof view.MouseEvent;
|
||||
const coords = isMouseLike
|
||||
? readSurfacePoint(event, surfaceRef.current ?? hostRef.current)
|
||||
: { x: gesture.lastSentX, y: gesture.lastSentY };
|
||||
const pointerType = readPointerType(event);
|
||||
const button = isMouseLike ? readPointerButton(event) : -1;
|
||||
const buttons = isMouseLike ? readPointerButtons(event) : 0;
|
||||
const modifiers = isMouseLike ? readModifierKeys(event) : {};
|
||||
|
||||
if (event.type === 'pointermove') {
|
||||
const moveEvent: PluginSurfaceEvent = {
|
||||
nodeId: gesture.nodeId,
|
||||
type: 'pointermove',
|
||||
...coords,
|
||||
pointerId: gesture.pointerId,
|
||||
button,
|
||||
buttons,
|
||||
...(pointerType ? { pointerType } : {}),
|
||||
...modifiers,
|
||||
};
|
||||
if (gesture.pendingMove === null && coords.x === gesture.lastSentX && coords.y === gesture.lastSentY) {
|
||||
return;
|
||||
}
|
||||
const now = Date.now();
|
||||
const elapsed = now - gesture.lastMoveSentAt;
|
||||
const canSendNow =
|
||||
elapsed >= POINTER_MOVE_THROTTLE_MS
|
||||
&& (settledRef.current || (gesture.pendingMoveSince > 0 && now - gesture.pendingMoveSince >= POINTER_MOVE_BACKPRESSURE_MAX_MS));
|
||||
if (canSendNow) {
|
||||
emitGestureMove(gesture, moveEvent, now);
|
||||
} else {
|
||||
gesture.pendingMove = moveEvent;
|
||||
if (gesture.pendingMoveSince === 0) gesture.pendingMoveSince = now;
|
||||
scheduleGestureMoveFlush(gesture);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === 'pointerup' && gesture.pendingMove) {
|
||||
emitGestureMove(gesture, gesture.pendingMove, Date.now());
|
||||
}
|
||||
releaseGesture(gesture);
|
||||
onEventRef.current({
|
||||
nodeId: gesture.nodeId,
|
||||
type: event.type as 'pointerup' | 'pointercancel',
|
||||
...coords,
|
||||
pointerId: gesture.pointerId,
|
||||
button,
|
||||
buttons,
|
||||
...(pointerType ? { pointerType } : {}),
|
||||
...modifiers,
|
||||
});
|
||||
};
|
||||
|
||||
const onWindowBlur = (event: Event) => {
|
||||
if (!view || event.target !== view || activeGestures.size === 0) return;
|
||||
for (const gesture of [...activeGestures.values()]) {
|
||||
const { nodeId, pointerId, lastSentX, lastSentY } = gesture;
|
||||
releaseGesture(gesture);
|
||||
onEventRef.current({
|
||||
nodeId,
|
||||
type: 'pointercancel',
|
||||
x: lastSentX,
|
||||
y: lastSentY,
|
||||
pointerId,
|
||||
button: -1,
|
||||
buttons: 0,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const attachWindowPointerListeners = () => {
|
||||
if (!view || windowPointerListenersAttached) return;
|
||||
windowPointerListenersAttached = true;
|
||||
view.addEventListener('pointermove', onGesturePointerEvent, true);
|
||||
view.addEventListener('pointerup', onGesturePointerEvent, true);
|
||||
view.addEventListener('pointercancel', onGesturePointerEvent, true);
|
||||
view.addEventListener('blur', onWindowBlur, false);
|
||||
};
|
||||
|
||||
const detachWindowPointerListeners = () => {
|
||||
if (!view || !windowPointerListenersAttached) return;
|
||||
windowPointerListenersAttached = false;
|
||||
view.removeEventListener('pointermove', onGesturePointerEvent, true);
|
||||
view.removeEventListener('pointerup', onGesturePointerEvent, true);
|
||||
view.removeEventListener('pointercancel', onGesturePointerEvent, true);
|
||||
view.removeEventListener('blur', onWindowBlur, false);
|
||||
};
|
||||
|
||||
flushPendingMovesRef.current = () => {
|
||||
const now = Date.now();
|
||||
for (const gesture of activeGestures.values()) {
|
||||
if (!gesture.pendingMove) continue;
|
||||
const elapsed = now - gesture.lastMoveSentAt;
|
||||
if (elapsed >= POINTER_MOVE_THROTTLE_MS) {
|
||||
emitGestureMove(gesture, gesture.pendingMove, now);
|
||||
} else {
|
||||
if (gesture.moveTimer !== null) {
|
||||
clearTimeout(gesture.moveTimer);
|
||||
gesture.moveTimer = null;
|
||||
}
|
||||
scheduleGestureMoveFlush(gesture);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const listener = (event: Event) => {
|
||||
if (!view || !SURFACE_EVENT_SET.has(event.type)) return;
|
||||
|
||||
if (event.type === 'pointermove' || event.type === 'pointerup' || event.type === 'pointercancel') {
|
||||
onGesturePointerEvent(event);
|
||||
return;
|
||||
}
|
||||
|
||||
const target = event.target;
|
||||
const view = shadow.ownerDocument.defaultView;
|
||||
if (!view || !(target instanceof view.HTMLElement) || !SURFACE_EVENT_SET.has(event.type)) return;
|
||||
if (!(target instanceof view.HTMLElement)) return;
|
||||
|
||||
// Closed-shadow events hide their editable target from window capture.
|
||||
if (event.type === 'focusin') {
|
||||
@@ -420,8 +788,12 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
|
||||
}
|
||||
if (event.type === 'focusout') hostRef.current?.removeAttribute('data-plugin-editing');
|
||||
|
||||
// Internal events inside slotted host-rendered widgets are handled by the widget itself.
|
||||
if (target.closest('[data-plugin-widget-host]')) return;
|
||||
// Internal events inside slotted host-rendered widgets or split-pane dividers are handled by the widget itself.
|
||||
if (
|
||||
target.closest('[data-plugin-widget-host]')
|
||||
|| target.closest('[data-split-handle]')
|
||||
|| SLOTTED_WIDGET_KINDS.has(target.dataset.pluginWidget ?? '')
|
||||
) return;
|
||||
|
||||
if (event.type === 'submit') event.preventDefault();
|
||||
if (event.type === 'contextmenu') event.preventDefault();
|
||||
@@ -436,6 +808,120 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
|
||||
?? (event.type === 'keydown' ? (shadow.querySelector('[data-netcatty-remote-node]') as HTMLElement | null)?.dataset.netcattyRemoteNode : undefined);
|
||||
if (!nodeId) return;
|
||||
|
||||
if (event.type === 'pointerdown') {
|
||||
if (!(event instanceof view.MouseEvent)) return;
|
||||
const pointerId = readPointerId(event);
|
||||
const existing = activeGestures.get(pointerId);
|
||||
if (existing) releaseGesture(existing);
|
||||
|
||||
const coords = readSurfacePoint(event, surfaceRef.current ?? hostRef.current);
|
||||
const pointerType = readPointerType(event);
|
||||
const button = readPointerButton(event);
|
||||
const buttons = readPointerButtons(event);
|
||||
const modifiers = readModifierKeys(event);
|
||||
|
||||
// Engage native pointer capture only on non-control elements that explicitly
|
||||
// declare `touch-action: none` so text selection, native form controls, and
|
||||
// normal button click cancellation stay intact. Window capture listeners still
|
||||
// sustain cross-node/cross-surface drags for every remote node.
|
||||
let capturedElement: HTMLElement | null = null;
|
||||
if (!target.matches('input, textarea, select, option')) {
|
||||
const touchAction = view.getComputedStyle?.(target)?.touchAction || target.style.touchAction;
|
||||
if (touchAction === 'none') {
|
||||
try {
|
||||
target.setPointerCapture?.(pointerId);
|
||||
capturedElement = target;
|
||||
} catch {
|
||||
// Synthetic or unsupported pointer capture environments rely on window listeners.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
activeGestures.set(pointerId, {
|
||||
nodeId,
|
||||
pointerId,
|
||||
capturedElement,
|
||||
lastSentX: coords.x,
|
||||
lastSentY: coords.y,
|
||||
lastMoveSentAt: 0,
|
||||
pendingMove: null,
|
||||
pendingMoveSince: 0,
|
||||
moveTimer: null,
|
||||
});
|
||||
attachWindowPointerListeners();
|
||||
|
||||
onEventRef.current({
|
||||
nodeId,
|
||||
type: 'pointerdown',
|
||||
...coords,
|
||||
pointerId,
|
||||
button,
|
||||
buttons,
|
||||
...(pointerType ? { pointerType } : {}),
|
||||
...modifiers,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === 'wheel') {
|
||||
const wheel = event as WheelEvent;
|
||||
const deltaX = roundWheelDelta(wheel.deltaX);
|
||||
const deltaY = roundWheelDelta(wheel.deltaY);
|
||||
if (deltaX === 0 && deltaY === 0) return;
|
||||
|
||||
if (hasScrollableAncestorForWheel(target, shadow, hostRef.current, view, deltaX, deltaY)) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
|
||||
const rawMode = wheel.deltaMode;
|
||||
const deltaMode = typeof rawMode === 'number' && Number.isFinite(rawMode)
|
||||
? Math.max(0, Math.min(2, Math.trunc(rawMode)))
|
||||
: 0;
|
||||
const coords = readSurfacePoint(wheel, surfaceRef.current ?? hostRef.current);
|
||||
const modifiers = readModifierKeys(wheel);
|
||||
const nextWheel: PluginSurfaceEvent = {
|
||||
nodeId,
|
||||
type: 'wheel',
|
||||
...coords,
|
||||
deltaX,
|
||||
deltaY,
|
||||
deltaMode,
|
||||
...modifiers,
|
||||
};
|
||||
|
||||
const now = Date.now();
|
||||
if (!pendingWheel && now - lastWheelSentAt >= WHEEL_THROTTLE_MS) {
|
||||
lastWheelSentAt = now;
|
||||
onEventRef.current(nextWheel);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
pendingWheel
|
||||
&& pendingWheel.nodeId === nodeId
|
||||
&& pendingWheel.deltaMode === deltaMode
|
||||
&& Boolean(pendingWheel.ctrlKey) === Boolean(modifiers.ctrlKey)
|
||||
&& Boolean(pendingWheel.metaKey) === Boolean(modifiers.metaKey)
|
||||
&& Boolean(pendingWheel.altKey) === Boolean(modifiers.altKey)
|
||||
&& Boolean(pendingWheel.shiftKey) === Boolean(modifiers.shiftKey)
|
||||
) {
|
||||
pendingWheel = {
|
||||
...pendingWheel,
|
||||
...coords,
|
||||
deltaX: roundWheelDelta((pendingWheel.deltaX ?? 0) + deltaX),
|
||||
deltaY: roundWheelDelta((pendingWheel.deltaY ?? 0) + deltaY),
|
||||
};
|
||||
} else {
|
||||
if (pendingWheel) flushWheel();
|
||||
pendingWheel = nextWheel;
|
||||
}
|
||||
if (wheelTimer === null) {
|
||||
const delay = Math.max(1, WHEEL_THROTTLE_MS - (Date.now() - lastWheelSentAt));
|
||||
wheelTimer = setTimeout(flushWheel, delay);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === 'scroll') {
|
||||
const scrollEvent: PluginSurfaceEvent = {
|
||||
nodeId,
|
||||
@@ -463,11 +949,7 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
|
||||
|
||||
let pointerCoords: { x: number; y: number } | undefined;
|
||||
if ((event.type === 'dblclick' || event.type === 'contextmenu') && event instanceof view.MouseEvent) {
|
||||
const rect = (surfaceRef.current ?? hostRef.current)?.getBoundingClientRect();
|
||||
pointerCoords = {
|
||||
x: Math.round(rect ? event.clientX - rect.left : event.clientX),
|
||||
y: Math.round(rect ? event.clientY - rect.top : event.clientY),
|
||||
};
|
||||
pointerCoords = readSurfacePoint(event, surfaceRef.current ?? hostRef.current);
|
||||
}
|
||||
|
||||
const selection =
|
||||
@@ -488,12 +970,21 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
|
||||
});
|
||||
};
|
||||
|
||||
for (const event of SURFACE_EVENTS) shadow.addEventListener(event, listener, true);
|
||||
for (const event of SURFACE_EVENTS) {
|
||||
shadow.addEventListener(event, listener, event === 'wheel' ? { capture: true, passive: false } : true);
|
||||
}
|
||||
// Chromium only treats wheel as cancelable when a non-passive listener is
|
||||
// registered on a real element. A closed ShadowRoot listener alone can see
|
||||
// `cancelable: false`, so also listen on the shadow host (no-op targeting;
|
||||
// the shadow capture listener still owns forwarding).
|
||||
const shadowHostEl = hostRef.current;
|
||||
const hostWheelOptions: AddEventListenerOptions = { capture: true, passive: false };
|
||||
const hostWheelListener = (_event: Event) => {};
|
||||
shadowHostEl?.addEventListener('wheel', hostWheelListener, hostWheelOptions);
|
||||
|
||||
// When a full-bleed plugin view is visible and focus sits on document.body (e.g.
|
||||
// right after tab switch or drawer close), forward global Cmd/Ctrl+K / Cmd/Ctrl+S
|
||||
// into the plugin so its Command Palette and Save shortcuts work reliably.
|
||||
const view = shadow.ownerDocument.defaultView;
|
||||
const onWindowKeyDown = (event: KeyboardEvent) => {
|
||||
if (depth !== 0 || event.defaultPrevented) return;
|
||||
const surfaceEl = surfaceRef.current;
|
||||
@@ -531,7 +1022,28 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
|
||||
view?.addEventListener('keydown', onWindowKeyDown, false);
|
||||
|
||||
return () => {
|
||||
flushPendingMovesRef.current = null;
|
||||
view?.removeEventListener('keydown', onWindowKeyDown, false);
|
||||
shadowHostEl?.removeEventListener('wheel', hostWheelListener, hostWheelOptions);
|
||||
// The retained plugin session keeps its SDK DOM when this surface unmounts
|
||||
// (tab hide). Send pointercancel so plugin drags do not stay stuck.
|
||||
for (const gesture of [...activeGestures.values()]) {
|
||||
const { nodeId, pointerId, lastSentX, lastSentY } = gesture;
|
||||
releaseGesture(gesture);
|
||||
onEventRef.current({
|
||||
nodeId,
|
||||
type: 'pointercancel',
|
||||
x: lastSentX,
|
||||
y: lastSentY,
|
||||
pointerId,
|
||||
button: -1,
|
||||
buttons: 0,
|
||||
});
|
||||
}
|
||||
detachWindowPointerListeners();
|
||||
if (wheelTimer !== null) clearTimeout(wheelTimer);
|
||||
wheelTimer = null;
|
||||
pendingWheel = null;
|
||||
for (const timer of scrollTimers.values()) clearTimeout(timer);
|
||||
scrollTimers.clear();
|
||||
pendingScroll.clear();
|
||||
|
||||
@@ -141,6 +141,7 @@ export const PluginVaultAISidebar: React.FC<PluginVaultAISidebarProps> = ({
|
||||
undoLastTurnInSession={aiConfig.undoLastTurnInSession}
|
||||
deleteSession={aiConfig.deleteSession}
|
||||
updateSessionTitle={aiConfig.updateSessionTitle}
|
||||
autoTitleSession={aiConfig.autoTitleSession}
|
||||
exportSessionsBackup={aiConfig.exportSessionsBackup}
|
||||
importSessionsBackup={aiConfig.importSessionsBackup}
|
||||
updateSessionExternalSessionId={aiConfig.updateSessionExternalSessionId}
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { JSDOM } from 'jsdom';
|
||||
|
||||
function installDom() {
|
||||
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', {
|
||||
pretendToBeVisual: true,
|
||||
url: 'http://localhost',
|
||||
});
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
const install = (key: string, value: unknown) => {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
};
|
||||
for (const key of [
|
||||
'window',
|
||||
'document',
|
||||
'navigator',
|
||||
'HTMLElement',
|
||||
'HTMLButtonElement',
|
||||
'HTMLInputElement',
|
||||
'Element',
|
||||
'SVGElement',
|
||||
'Node',
|
||||
'NodeFilter',
|
||||
'MutationObserver',
|
||||
'CustomEvent',
|
||||
'Event',
|
||||
'KeyboardEvent',
|
||||
'MouseEvent',
|
||||
]) {
|
||||
install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]);
|
||||
}
|
||||
class MockResizeObserver {
|
||||
private cb: (entries: unknown[]) => void;
|
||||
constructor(cb: (entries: unknown[]) => void) {
|
||||
this.cb = cb;
|
||||
}
|
||||
observe(target: Element) {
|
||||
this.cb([
|
||||
{
|
||||
target,
|
||||
borderBoxSize: [{ inlineSize: 960, blockSize: 420 }],
|
||||
contentRect: { width: 960, height: 420 },
|
||||
},
|
||||
]);
|
||||
}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
}
|
||||
Object.assign(dom.window, {
|
||||
PointerEvent: dom.window.MouseEvent,
|
||||
ResizeObserver: MockResizeObserver,
|
||||
});
|
||||
install('PointerEvent', dom.window.MouseEvent);
|
||||
install('ResizeObserver', MockResizeObserver);
|
||||
install('getComputedStyle', dom.window.getComputedStyle.bind(dom.window));
|
||||
install('requestAnimationFrame', dom.window.requestAnimationFrame.bind(dom.window));
|
||||
install('cancelAnimationFrame', dom.window.cancelAnimationFrame.bind(dom.window));
|
||||
install('IS_REACT_ACT_ENVIRONMENT', true);
|
||||
dom.window.HTMLElement.prototype.getBoundingClientRect = () => new dom.window.DOMRect(0, 0, 960, 420);
|
||||
|
||||
return {
|
||||
dom,
|
||||
cleanup() {
|
||||
dom.window.close();
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('PluginDataGrid header clicks toggle sort on single clicks, ignore double-click second click, and skip non-sortable columns', async () => {
|
||||
const env = installDom();
|
||||
const { act, useState } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { PluginDataGrid, SORT_CLICK_DEBOUNCE_MS } = await import('./PluginDataGrid');
|
||||
type SortState = { column: string; direction: 'asc' | 'desc' } | null;
|
||||
|
||||
const events: Array<{ name: string; detail?: Record<string, unknown> }> = [];
|
||||
let resetSort!: () => void;
|
||||
|
||||
function ControlledGrid() {
|
||||
const [sort, setSort] = useState<SortState>(null);
|
||||
resetSort = () => setSort(null);
|
||||
return (
|
||||
<PluginDataGrid
|
||||
columns={[
|
||||
{ name: 'email', type: 'varchar' },
|
||||
{ name: 'payload', type: 'jsonb', sortable: false },
|
||||
]}
|
||||
rows={[
|
||||
{ email: 'alice@example.com', payload: '{}' },
|
||||
{ email: 'bob@example.com', payload: '{}' },
|
||||
]}
|
||||
sort={sort}
|
||||
onWidgetEvent={(name, detail) => {
|
||||
events.push({ name, detail });
|
||||
if (name === 'sortChange' && detail) {
|
||||
setSort({
|
||||
column: String(detail.column),
|
||||
direction: detail.direction === 'desc' ? 'desc' : 'asc',
|
||||
});
|
||||
}
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
try {
|
||||
await act(async () => {
|
||||
root.render(<ControlledGrid />);
|
||||
});
|
||||
|
||||
const emailBtn = document.querySelector<HTMLButtonElement>('[role="columnheader"][data-col-name="email"] button');
|
||||
const payloadBtn = document.querySelector<HTMLButtonElement>('[role="columnheader"][data-col-name="payload"] button');
|
||||
assert.ok(emailBtn, 'sortable email header button mounted');
|
||||
assert.ok(payloadBtn, 'non-sortable payload header button mounted');
|
||||
assert.equal(payloadBtn.disabled, true);
|
||||
|
||||
// 1. Single click (detail 1) -> asc; immediate second detail=1 click is debounced
|
||||
await act(async () => {
|
||||
emailBtn.dispatchEvent(new env.dom.window.MouseEvent('click', { bubbles: true, cancelable: true, detail: 1 }));
|
||||
});
|
||||
assert.deepEqual(events, [
|
||||
{ name: 'sortChange', detail: { column: 'email', direction: 'asc' } },
|
||||
]);
|
||||
await act(async () => {
|
||||
emailBtn.dispatchEvent(new env.dom.window.MouseEvent('click', { bubbles: true, cancelable: true, detail: 1 }));
|
||||
});
|
||||
assert.deepEqual(events, [
|
||||
{ name: 'sortChange', detail: { column: 'email', direction: 'asc' } },
|
||||
]);
|
||||
|
||||
// 2. Genuine later single click after debounce window (detail 1) -> desc
|
||||
await new Promise((resolve) => setTimeout(resolve, SORT_CLICK_DEBOUNCE_MS + 30));
|
||||
await act(async () => {
|
||||
emailBtn.dispatchEvent(new env.dom.window.MouseEvent('click', { bubbles: true, cancelable: true, detail: 1 }));
|
||||
});
|
||||
assert.deepEqual(events, [
|
||||
{ name: 'sortChange', detail: { column: 'email', direction: 'asc' } },
|
||||
{ name: 'sortChange', detail: { column: 'email', direction: 'desc' } },
|
||||
]);
|
||||
|
||||
// 3. Double-click sequence: click (detail 1), click (detail 2), dblclick -> only one sortChange total
|
||||
await new Promise((resolve) => setTimeout(resolve, SORT_CLICK_DEBOUNCE_MS + 30));
|
||||
events.length = 0;
|
||||
await act(async () => {
|
||||
resetSort();
|
||||
});
|
||||
let dblClickBubbled = false;
|
||||
document.body.addEventListener('dblclick', () => {
|
||||
dblClickBubbled = true;
|
||||
}, { once: true });
|
||||
|
||||
const dblClickEvent = new env.dom.window.MouseEvent('dblclick', { bubbles: true, cancelable: true, detail: 2 });
|
||||
await act(async () => {
|
||||
emailBtn.dispatchEvent(new env.dom.window.MouseEvent('click', { bubbles: true, cancelable: true, detail: 1 }));
|
||||
emailBtn.dispatchEvent(new env.dom.window.MouseEvent('click', { bubbles: true, cancelable: true, detail: 2 }));
|
||||
emailBtn.dispatchEvent(dblClickEvent);
|
||||
});
|
||||
assert.deepEqual(events, [
|
||||
{ name: 'sortChange', detail: { column: 'email', direction: 'asc' } },
|
||||
]);
|
||||
assert.equal(dblClickEvent.defaultPrevented, true, 'header dblclick should preventDefault');
|
||||
assert.equal(dblClickBubbled, false, 'header dblclick should not bubble out');
|
||||
|
||||
// 4. Non-sortable column emits nothing
|
||||
events.length = 0;
|
||||
await act(async () => {
|
||||
payloadBtn.click();
|
||||
payloadBtn.dispatchEvent(new env.dom.window.MouseEvent('click', { bubbles: true, cancelable: true, detail: 1 }));
|
||||
});
|
||||
assert.deepEqual(events, []);
|
||||
} finally {
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -15,6 +15,7 @@ const GUTTER_WIDTH = 64;
|
||||
const DEFAULT_COL_WIDTH = 156;
|
||||
const MIN_COL_WIDTH = 68;
|
||||
const MAX_COL_WIDTH = 640;
|
||||
export const SORT_CLICK_DEBOUNCE_MS = 500;
|
||||
|
||||
export interface PluginDataGridProps extends PluginDataGridWidgetProps {
|
||||
onWidgetEvent: PluginWidgetEventCallback;
|
||||
@@ -60,6 +61,7 @@ export function PluginDataGrid({
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const editInputRef = useRef<HTMLInputElement>(null);
|
||||
const blurTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const lastSortClickAtRef = useRef<number | null>(null);
|
||||
|
||||
const [colWidths, setColWidths] = useState<Record<string, number>>({});
|
||||
const [activeCell, setActiveCell] = useState<{ rowIndex: number; colIndex: number } | null>(null);
|
||||
@@ -223,8 +225,18 @@ export function PluginDataGrid({
|
||||
onWidgetEvent('rowSelect', { selectedRowIndices: next });
|
||||
}, [totalRows, selectedSet.size, onWidgetEvent]);
|
||||
|
||||
const handleSortClick = useCallback((col: PluginDataGridColumn) => {
|
||||
const handleSortClick = useCallback((col: PluginDataGridColumn, event?: React.MouseEvent<HTMLButtonElement>) => {
|
||||
if (col.sortable === false) return;
|
||||
if (event && event.detail > 1) return;
|
||||
const now = Date.now();
|
||||
if (
|
||||
lastSortClickAtRef.current !== null &&
|
||||
now >= lastSortClickAtRef.current &&
|
||||
now - lastSortClickAtRef.current < SORT_CLICK_DEBOUNCE_MS
|
||||
) {
|
||||
return;
|
||||
}
|
||||
lastSortClickAtRef.current = now;
|
||||
const nextDirection = sort?.column === col.name && sort.direction === 'asc' ? 'desc' : 'asc';
|
||||
onWidgetEvent('sortChange', { column: col.name, direction: nextDirection });
|
||||
}, [sort, onWidgetEvent]);
|
||||
@@ -452,7 +464,11 @@ export function PluginDataGrid({
|
||||
<button
|
||||
type="button"
|
||||
disabled={!sortable}
|
||||
onClick={() => handleSortClick(col)}
|
||||
onClick={(event) => handleSortClick(col, event)}
|
||||
onDoubleClick={(event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}}
|
||||
className={`flex min-w-0 flex-1 items-center gap-1.5 text-left ${sortable ? 'cursor-pointer hover:text-primary' : 'cursor-default'}`}
|
||||
title={col.foreignKey
|
||||
? `${col.name}${col.type ? ` (${col.type})` : ''} -> ${col.foreignKey.schema ? `${col.foreignKey.schema}.` : ''}${col.foreignKey.table}.${col.foreignKey.column}`
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import React from 'react';
|
||||
import { ER_CARD_WIDTH, erCardHeight } from './erFormat';
|
||||
import type { ErRect } from './erFormat';
|
||||
import type { PluginErTable } from './types';
|
||||
|
||||
function position(element: Element) {
|
||||
const match = element.getAttribute('transform')?.match(/translate\(([-\d.]+), ([-\d.]+)\)/);
|
||||
assert.ok(match);
|
||||
return { x: Number(match[1]), y: Number(match[2]) };
|
||||
}
|
||||
|
||||
function assertNoOverlap(label: ErRect, cards: ErRect[]) {
|
||||
for (const card of cards) {
|
||||
assert.ok(label.x + label.width < card.x || label.x > card.x + card.width
|
||||
|| label.y + label.height < card.y || label.y > card.y + card.height,
|
||||
`label ${JSON.stringify(label)} overlaps card ${JSON.stringify(card)}`);
|
||||
}
|
||||
}
|
||||
|
||||
test('ER hover labels stay in corridors through drag, zoom, fit, reset, and SVG export', async () => {
|
||||
const dom = new JSDOM('<!doctype html><body><div id="root"></div></body>', { pretendToBeVisual: true });
|
||||
const saved = new Map<string, PropertyDescriptor | undefined>();
|
||||
const install = (key: string, value: unknown) => {
|
||||
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
};
|
||||
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent']) {
|
||||
install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]);
|
||||
}
|
||||
install('requestAnimationFrame', dom.window.requestAnimationFrame.bind(dom.window));
|
||||
install('cancelAnimationFrame', dom.window.cancelAnimationFrame.bind(dom.window));
|
||||
install('IS_REACT_ACT_ENVIRONMENT', true);
|
||||
dom.window.HTMLElement.prototype.getBoundingClientRect = () => new dom.window.DOMRect(0, 0, 1200, 600);
|
||||
const { act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { PluginErCanvas } = await import('./PluginErCanvas');
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
let tables: PluginErTable[] = [
|
||||
{ name: 'customers', schema: 'main', columns: [{ name: 'id', type: 'int4', isPk: true }, { name: 'email', type: 'TEXT' }] },
|
||||
{ name: 'orders', schema: 'main', columns: [{ name: 'id', type: 'int4', isPk: true }, { name: 'customer_id', type: 'int4', isPk: true, isFk: true }] },
|
||||
];
|
||||
const relations = [{ fromTable: 'main.orders', fromColumn: 'customer_id', toTable: 'main.customers', toColumn: 'id', onDelete: 'CASCADE' }];
|
||||
let exported = '';
|
||||
const render = async () => {
|
||||
await act(async () => root.render(<PluginErCanvas tables={tables} relations={relations} onWidgetEvent={(name, detail) => {
|
||||
if (name === 'exportSvg') exported = String(detail?.svg);
|
||||
}} />));
|
||||
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 30)); });
|
||||
};
|
||||
const card = (name: string) => document.querySelector(`[data-er-table="${name}"]`)!;
|
||||
const cards = () => tables.map((table) => ({ ...position(card(table.name)), width: ER_CARD_WIDTH, height: erCardHeight(table) }));
|
||||
const label = () => document.querySelector('[data-er-relation-label]');
|
||||
const assertSafeLabel = () => {
|
||||
const group = label();
|
||||
assert.ok(group);
|
||||
const rect = group.querySelector('rect')!;
|
||||
const bbox = { ...position(group), width: Number(rect.getAttribute('width')), height: Number(rect.getAttribute('height')) };
|
||||
assertNoOverlap(bbox, cards());
|
||||
assert.equal(group.querySelector('svg')?.getAttribute('overflow'), 'hidden');
|
||||
assert.equal(group.getAttribute('pointer-events'), 'none');
|
||||
// Label paints after every card, with all geometry in the same viewport.
|
||||
for (const table of tables) assert.ok(card(table.name).compareDocumentPosition(group) & dom.window.Node.DOCUMENT_POSITION_FOLLOWING);
|
||||
return bbox;
|
||||
};
|
||||
const click = async (name: string) => {
|
||||
await act(async () => document.querySelector(`[aria-label="${name}"]`)!.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true })));
|
||||
};
|
||||
const zoom = () => Number(document.querySelector('[data-er-table]')!.parentElement!.getAttribute('transform')!.match(/scale\(([^)]+)\)/)![1]);
|
||||
const dragTo = async (name: string, x: number, y: number) => {
|
||||
const origin = position(card(name));
|
||||
const scale = zoom();
|
||||
await act(async () => card(name).dispatchEvent(new dom.window.MouseEvent('pointerdown', { bubbles: true, button: 0, clientX: 0, clientY: 0 })));
|
||||
await act(async () => dom.window.dispatchEvent(new dom.window.MouseEvent('pointermove', { clientX: (x - origin.x) * scale, clientY: (y - origin.y) * scale })));
|
||||
await act(async () => dom.window.dispatchEvent(new dom.window.MouseEvent('pointerup')));
|
||||
};
|
||||
try {
|
||||
await render();
|
||||
assert.equal(label(), null);
|
||||
await act(async () => document.querySelector('[data-er-relation] path')!.dispatchEvent(new dom.window.MouseEvent('pointerover', { bubbles: true })));
|
||||
const initial = position(card('orders'));
|
||||
const fullLabel = assertSafeLabel();
|
||||
assert.equal(label()!.textContent, 'customer_id -> id (ON DELETE CASCADE)');
|
||||
assert.ok(initial.x - position(card('customers')).x - ER_CARD_WIDTH > fullLabel.width);
|
||||
|
||||
// The reported three-table layout also keeps a vertical corridor.
|
||||
tables = [...tables, { name: 'products', schema: 'main', columns: [{ name: 'id', type: 'int4', isPk: true }] }];
|
||||
await render();
|
||||
assertSafeLabel();
|
||||
assert.ok(position(card('products')).y - position(card('customers')).y - erCardHeight(tables[0]) >= 80);
|
||||
await click('Zoom in');
|
||||
assertSafeLabel();
|
||||
const left = position(card('customers'));
|
||||
await dragTo('orders', left.x + ER_CARD_WIDTH + 100, left.y);
|
||||
assertSafeLabel();
|
||||
assert.match(label()!.textContent!, /\.\.\.$/);
|
||||
assert.ok(Number(label()!.querySelector('rect')!.getAttribute('width')) < fullLabel.width);
|
||||
await click('Fit to view');
|
||||
assertSafeLabel();
|
||||
await dragTo('orders', left.x + ER_CARD_WIDTH + 40, left.y);
|
||||
assert.equal(label(), null);
|
||||
await dragTo('orders', left.x + 100, left.y);
|
||||
assert.equal(label(), null);
|
||||
|
||||
// The live and exported edge layers exclude every card, including overlaps.
|
||||
const relation = document.querySelector('[data-er-relation]')!;
|
||||
const maskId = relation.getAttribute('mask')!.slice(5, -1);
|
||||
const mask = document.getElementById(maskId)!;
|
||||
assert.equal(mask.querySelectorAll('rect[fill="black"]').length, tables.length);
|
||||
await click('Export SVG');
|
||||
const svg = new dom.window.DOMParser().parseFromString(exported, 'image/svg+xml');
|
||||
assert.equal(svg.querySelector('parsererror'), null);
|
||||
assert.equal(svg.querySelectorAll('mask rect[fill="black"]').length, tables.length);
|
||||
assert.ok(svg.querySelector('g[mask] path'));
|
||||
assert.equal(svg.querySelector('g[mask] text'), null);
|
||||
const exportedCards = [...svg.querySelectorAll('mask rect[fill="black"]')];
|
||||
for (const [index, bounds] of cards().entries()) {
|
||||
for (const key of ['x', 'y', 'width', 'height'] as const) assert.equal(Number(exportedCards[index].getAttribute(key)), bounds[key]);
|
||||
}
|
||||
await click('Reset layout');
|
||||
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 30)); });
|
||||
assert.deepEqual(position(card('orders')), initial);
|
||||
assertSafeLabel();
|
||||
assert.ok(Number.isFinite(zoom()) && zoom() > 0);
|
||||
} finally {
|
||||
await act(async () => root.unmount());
|
||||
dom.window.close();
|
||||
for (const [key, descriptor] of saved) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Download, Maximize2, RotateCcw, ZoomIn, ZoomOut } from 'lucide-react';
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
abbreviateSqlType,
|
||||
buildStandaloneErSvg,
|
||||
@@ -7,7 +7,11 @@ import {
|
||||
ER_CARD_ROW_HEIGHT,
|
||||
ER_CARD_WIDTH,
|
||||
erCardHeight,
|
||||
erCardRects,
|
||||
erRelationLabelText,
|
||||
erRelationLabelWidth,
|
||||
erTableKey,
|
||||
placeErRelationLabel,
|
||||
} from './erFormat';
|
||||
import { matchWorkbenchShortcut } from './shortcuts';
|
||||
import type {
|
||||
@@ -16,8 +20,7 @@ import type {
|
||||
PluginWidgetEventCallback,
|
||||
} from './types';
|
||||
|
||||
const GRID_GAP_X = 80;
|
||||
const GRID_GAP_Y = 56;
|
||||
const GRID_GAP_Y = 80;
|
||||
const MIN_ZOOM = 0.25;
|
||||
const MAX_ZOOM = 2.5;
|
||||
|
||||
@@ -25,7 +28,7 @@ export interface PluginErCanvasProps extends PluginErCanvasWidgetProps {
|
||||
onWidgetEvent: PluginWidgetEventCallback;
|
||||
}
|
||||
|
||||
function computeInitialPositions(tables: PluginErTable[]): Record<string, { x: number; y: number }> {
|
||||
function computeInitialPositions(tables: PluginErTable[], gapX: number): Record<string, { x: number; y: number }> {
|
||||
const result: Record<string, { x: number; y: number }> = {};
|
||||
const colsPerRow = Math.max(1, Math.min(4, Math.ceil(Math.sqrt(tables.length || 1))));
|
||||
const colY = Array.from({ length: colsPerRow }, () => 40);
|
||||
@@ -37,7 +40,7 @@ function computeInitialPositions(tables: PluginErTable[]): Record<string, { x: n
|
||||
return;
|
||||
}
|
||||
const colIdx = index % colsPerRow;
|
||||
const x = 40 + colIdx * (ER_CARD_WIDTH + GRID_GAP_X);
|
||||
const x = 40 + colIdx * (ER_CARD_WIDTH + gapX);
|
||||
const y = colY[colIdx];
|
||||
result[key] = { x, y };
|
||||
colY[colIdx] = y + erCardHeight(table) + GRID_GAP_Y;
|
||||
@@ -69,8 +72,10 @@ export function PluginErCanvas({
|
||||
relations = [],
|
||||
onWidgetEvent,
|
||||
}: PluginErCanvasProps) {
|
||||
const gapX = relations.reduce((gap, rel) => Math.max(gap, erRelationLabelWidth(erRelationLabelText(rel)) + 32), 160);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [positions, setPositions] = useState<Record<string, { x: number; y: number }>>(() => computeInitialPositions(tables));
|
||||
const relationMaskId = useId();
|
||||
const [positions, setPositions] = useState<Record<string, { x: number; y: number }>>(() => computeInitialPositions(tables, gapX));
|
||||
const [viewport, setViewport] = useState({ x: 0, y: 0, zoom: 1 });
|
||||
const [selectedTable, setSelectedTable] = useState<string | null>(null);
|
||||
const [hoveredRelation, setHoveredRelation] = useState<number | null>(null);
|
||||
@@ -83,7 +88,7 @@ export function PluginErCanvas({
|
||||
|
||||
useEffect(() => {
|
||||
setPositions((prev) => {
|
||||
const defaults = computeInitialPositions(tables);
|
||||
const defaults = computeInitialPositions(tables, gapX);
|
||||
const next: Record<string, { x: number; y: number }> = {};
|
||||
for (const tbl of tables) {
|
||||
const key = erTableKey(tbl);
|
||||
@@ -91,7 +96,17 @@ export function PluginErCanvas({
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, [tableSignature, tables]);
|
||||
}, [tableSignature, tables, gapX]);
|
||||
|
||||
const cardRects = useMemo(() => erCardRects(tables, positions), [tables, positions]);
|
||||
const edgeBounds = {
|
||||
x: Math.min(...cardRects.map((card) => card.x)) - 64,
|
||||
y: Math.min(...cardRects.map((card) => card.y)) - 64,
|
||||
width: 0,
|
||||
height: 0,
|
||||
};
|
||||
edgeBounds.width = Math.max(...cardRects.map((card) => card.x + card.width)) - edgeBounds.x + 64;
|
||||
edgeBounds.height = Math.max(...cardRects.map((card) => card.y + card.height)) - edgeBounds.y + 64;
|
||||
|
||||
const tableLookup = useMemo(() => {
|
||||
const byKey = new Map<string, PluginErTable>();
|
||||
@@ -262,13 +277,13 @@ export function PluginErCanvas({
|
||||
}, []);
|
||||
|
||||
const resetLayout = useCallback(() => {
|
||||
setPositions(computeInitialPositions(tables));
|
||||
setPositions(computeInitialPositions(tables, gapX));
|
||||
if (typeof requestAnimationFrame === 'function') {
|
||||
requestAnimationFrame(fitToView);
|
||||
requestAnimationFrame(() => fitToViewRef.current());
|
||||
} else {
|
||||
fitToView();
|
||||
}
|
||||
}, [tables, fitToView]);
|
||||
}, [tables, gapX, fitToView]);
|
||||
|
||||
const handleExportSvg = useCallback(() => {
|
||||
const palette = resolveCanvasPalette(containerRef.current);
|
||||
@@ -360,6 +375,10 @@ export function PluginErCanvas({
|
||||
onPointerDown={handleCanvasPointerDown}
|
||||
>
|
||||
<defs>
|
||||
<mask id={relationMaskId} maskUnits="userSpaceOnUse" {...edgeBounds}>
|
||||
<rect {...edgeBounds} fill="white" />
|
||||
{cardRects.map((card, index) => <rect key={index} {...card} fill="black" />)}
|
||||
</mask>
|
||||
<pattern id="nc-er-dots" width="20" height="20" patternUnits="userSpaceOnUse">
|
||||
<circle cx="1" cy="1" r="1" fill="hsl(var(--border))" opacity="0.55" />
|
||||
</pattern>
|
||||
@@ -394,15 +413,12 @@ export function PluginErCanvas({
|
||||
const isHovered = hoveredRelation === idx;
|
||||
const highlighted = isHovered || selectedTable === fromKey || selectedTable === toKey;
|
||||
const stroke = highlighted ? 'hsl(var(--primary))' : 'hsl(var(--muted-foreground))';
|
||||
const midX = (x1 + x2) / 2;
|
||||
const midY = (y1 + y2) / 2;
|
||||
const edgeLabel = `${rel.fromColumn} -> ${rel.toColumn}${rel.onDelete ? ` (ON DELETE ${rel.onDelete})` : ''}`;
|
||||
const labelWidth = Math.min(260, Math.max(72, edgeLabel.length * 6.2 + 14));
|
||||
|
||||
return (
|
||||
<g
|
||||
key={rel.name ?? `${fromKey}.${rel.fromColumn}->${toKey}.${rel.toColumn}:${idx}`}
|
||||
data-er-relation={`${rel.fromTable}.${rel.fromColumn}->${rel.toTable}.${rel.toColumn}`}
|
||||
mask={`url(#${relationMaskId})`}
|
||||
onPointerEnter={() => setHoveredRelation(idx)}
|
||||
onPointerLeave={() => setHoveredRelation(null)}
|
||||
>
|
||||
@@ -421,28 +437,6 @@ export function PluginErCanvas({
|
||||
/>
|
||||
<circle cx={x1} cy={y1} r={3.5} fill={stroke} />
|
||||
<circle cx={x2} cy={y2} r={3.5} fill="hsl(var(--background))" stroke={stroke} strokeWidth={1.8} />
|
||||
{isHovered && (
|
||||
<g transform={`translate(${midX - labelWidth / 2}, ${midY - 12})`}>
|
||||
<rect
|
||||
width={labelWidth}
|
||||
height={18}
|
||||
rx={4}
|
||||
fill="hsl(var(--popover))"
|
||||
stroke="hsl(var(--primary))"
|
||||
strokeWidth={1}
|
||||
/>
|
||||
<text
|
||||
x={labelWidth / 2}
|
||||
y={12}
|
||||
textAnchor="middle"
|
||||
fontSize={10}
|
||||
fontFamily="var(--font-mono)"
|
||||
fill="hsl(var(--popover-foreground))"
|
||||
>
|
||||
{edgeLabel}
|
||||
</text>
|
||||
</g>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
@@ -558,6 +552,48 @@ export function PluginErCanvas({
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{/* Hover labels stay above cards, but only inside a free corridor. */}
|
||||
{hoveredRelation !== null && (() => {
|
||||
const rel = relations[hoveredRelation];
|
||||
if (!rel) return null;
|
||||
const fromTable = resolveTable(rel.fromTable);
|
||||
const toTable = resolveTable(rel.toTable);
|
||||
if (!fromTable || !toTable) return null;
|
||||
const fromPos = positions[erTableKey(fromTable)] ?? { x: 0, y: 0 };
|
||||
const toPos = positions[erTableKey(toTable)] ?? { x: 0, y: 0 };
|
||||
const fromColIdx = Math.max(0, fromTable.columns.findIndex((col) => col.name === rel.fromColumn));
|
||||
const toColIdx = Math.max(0, toTable.columns.findIndex((col) => col.name === rel.toColumn));
|
||||
const midX = (fromPos.x + toPos.x + ER_CARD_WIDTH) / 2;
|
||||
const midY = (fromPos.y + toPos.y) / 2 + ER_CARD_HEADER_HEIGHT
|
||||
+ (fromColIdx + toColIdx + 1) * ER_CARD_ROW_HEIGHT / 2;
|
||||
const text = erRelationLabelText(rel);
|
||||
const label = placeErRelationLabel(text, midX, midY, cardRects);
|
||||
if (!label) return null;
|
||||
return (
|
||||
<g data-er-relation-label="" transform={`translate(${label.x}, ${label.y})`} pointerEvents="none">
|
||||
<rect
|
||||
width={label.width}
|
||||
height={label.height}
|
||||
rx={4}
|
||||
fill="hsl(var(--popover))"
|
||||
stroke="hsl(var(--primary))"
|
||||
strokeWidth={1}
|
||||
/>
|
||||
<svg x={7} y={0} width={label.width - 14} height={label.height} overflow="hidden">
|
||||
<text
|
||||
x={(label.width - 14) / 2}
|
||||
y={12}
|
||||
textAnchor="middle"
|
||||
fontSize={10}
|
||||
fontFamily="var(--font-mono)"
|
||||
fill="hsl(var(--popover-foreground))"
|
||||
>
|
||||
{label.text}
|
||||
</text>
|
||||
</svg>
|
||||
</g>
|
||||
);
|
||||
})()}
|
||||
</g>
|
||||
</svg>
|
||||
)}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { abbreviateSqlType, buildStandaloneErSvg } from './erFormat';
|
||||
import { abbreviateSqlType, buildStandaloneErSvg, placeErRelationLabel } from './erFormat';
|
||||
import { matchWorkbenchShortcut } from './shortcuts';
|
||||
|
||||
test('abbreviateSqlType shortens verbose SQL catalog types cleanly without mid-word clipping', () => {
|
||||
@@ -40,6 +40,28 @@ test('buildStandaloneErSvg generates valid self-contained SVG markup with tables
|
||||
assert.match(svg, /<path d="M /);
|
||||
});
|
||||
|
||||
test('ER labels avoid unrelated card rectangles and fit vertical corridors', () => {
|
||||
const text = 'customer_id -> id (ON DELETE CASCADE)';
|
||||
const cards = [
|
||||
{ x: 40, y: 40, width: 252, height: 90 },
|
||||
{ x: 584, y: 40, width: 252, height: 90 },
|
||||
];
|
||||
const label = placeErRelationLabel(text, 438, 98, cards);
|
||||
assert.ok(label);
|
||||
assert.equal(label.text, text);
|
||||
assert.ok(label.x > 292 && label.x + label.width < 584);
|
||||
// An unrelated card can block an otherwise wide corridor.
|
||||
assert.equal(placeErRelationLabel(text, 438, 98, [...cards, { x: 400, y: 40, width: 252, height: 90 }]), null);
|
||||
// Vertically aligned tables leave a free label band between the rows.
|
||||
const vertical = placeErRelationLabel(text, 166, 170, [cards[0], { ...cards[0], y: 210 }]);
|
||||
assert.ok(vertical);
|
||||
assert.ok(vertical.y > 130 && vertical.y + vertical.height < 210);
|
||||
const long = placeErRelationLabel('very_long_column_name'.repeat(30), 438, 98, cards);
|
||||
assert.ok(long);
|
||||
assert.ok(long.width <= 260);
|
||||
assert.match(long.text, /\.\.\.$/);
|
||||
});
|
||||
|
||||
test('matchWorkbenchShortcut normalizes mod+k/s/t/w/z/shift+z and escape while respecting includeUndoRedo', () => {
|
||||
assert.equal(matchWorkbenchShortcut({ key: 'k', metaKey: true }), 'mod+k');
|
||||
assert.equal(matchWorkbenchShortcut({ key: 'K', ctrlKey: true }), 'mod+k');
|
||||
|
||||
@@ -36,6 +36,52 @@ export function erCardHeight(table: PluginErTable): number {
|
||||
return ER_CARD_HEADER_HEIGHT + Math.max(1, table.columns.length) * ER_CARD_ROW_HEIGHT + ER_CARD_FOOTER_PADDING;
|
||||
}
|
||||
|
||||
export interface ErRect {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export function erCardRects(tables: PluginErTable[], positions: Record<string, { x: number; y: number }>): ErRect[] {
|
||||
return tables.map((table) => ({
|
||||
...(positions[erTableKey(table)] ?? { x: 0, y: 0 }),
|
||||
width: ER_CARD_WIDTH,
|
||||
height: erCardHeight(table),
|
||||
}));
|
||||
}
|
||||
|
||||
export function erRelationLabelText(rel: PluginErRelation): string {
|
||||
return `${rel.fromColumn} -> ${rel.toColumn}${rel.onDelete ? ` (ON DELETE ${rel.onDelete})` : ''}`;
|
||||
}
|
||||
|
||||
export function erRelationLabelWidth(text: string): number {
|
||||
return Math.min(260, Math.max(72, text.length * 6.2 + 14));
|
||||
}
|
||||
|
||||
/** Fit the hover label into the free horizontal corridor at the edge midpoint. */
|
||||
export function placeErRelationLabel(text: string, midX: number, midY: number, cards: ErRect[]): (ErRect & { text: string }) | null {
|
||||
const y = midY - 12;
|
||||
const height = 18;
|
||||
const clearance = 4;
|
||||
let left = -Infinity;
|
||||
let right = Infinity;
|
||||
for (const card of cards) {
|
||||
if (y + height <= card.y - clearance || y >= card.y + card.height + clearance) continue;
|
||||
const cardLeft = card.x - clearance;
|
||||
const cardRight = card.x + card.width + clearance;
|
||||
// Hide rather than paint inside a card when dragging closes the corridor.
|
||||
if (midX >= cardLeft && midX <= cardRight) return null;
|
||||
if (cardRight < midX) left = Math.max(left, cardRight);
|
||||
if (cardLeft > midX) right = Math.min(right, cardLeft);
|
||||
}
|
||||
const width = Math.min(erRelationLabelWidth(text), right - left);
|
||||
if (width < 72) return null;
|
||||
const x = Math.max(left, Math.min(midX - width / 2, right - width));
|
||||
const maxChars = Math.floor((width - 14) / 6.2 + 1e-6);
|
||||
return { x, y, width, height, text: text.length > maxChars ? `${text.slice(0, maxChars - 3)}...` : text };
|
||||
}
|
||||
|
||||
function escapeXml(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, '&')
|
||||
@@ -94,6 +140,14 @@ export function buildStandaloneErSvg(
|
||||
`<rect x="${vbX}" y="${vbY}" width="${vbW}" height="${vbH}" fill="${escapeXml(palette.background)}" />`,
|
||||
];
|
||||
|
||||
// Cut all edge decorations out of card rectangles, even with translucent fills.
|
||||
lines.push(`<defs><mask id="er-edges" maskUnits="userSpaceOnUse" x="${vbX}" y="${vbY}" width="${vbW}" height="${vbH}">`);
|
||||
lines.push(`<rect x="${vbX}" y="${vbY}" width="${vbW}" height="${vbH}" fill="white" />`);
|
||||
for (const card of erCardRects(tables, positions)) {
|
||||
lines.push(`<rect x="${card.x}" y="${card.y}" width="${card.width}" height="${card.height}" fill="black" />`);
|
||||
}
|
||||
lines.push('</mask></defs><g mask="url(#er-edges)">');
|
||||
|
||||
for (const rel of relations) {
|
||||
const fromTable = resolveTable(rel.fromTable);
|
||||
const toTable = resolveTable(rel.toTable);
|
||||
@@ -116,6 +170,7 @@ export function buildStandaloneErSvg(
|
||||
`<circle cx="${x2}" cy="${y2}" r="3.5" fill="${escapeXml(palette.background)}" stroke="${escapeXml(palette.mutedForeground)}" stroke-width="1.8" />`,
|
||||
);
|
||||
}
|
||||
lines.push('</g>');
|
||||
|
||||
for (const tbl of tables) {
|
||||
const pos = positions[erTableKey(tbl)] ?? { x: 0, y: 0 };
|
||||
|
||||
@@ -10,7 +10,7 @@ import React, {
|
||||
import { AlertCircle, UploadCloud } from 'lucide-react';
|
||||
import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
import { useClipboardBackend } from '../../application/state/useClipboardBackend';
|
||||
import { buildRdpClipboardItemData, nextRdpClipboardGuardState, selectRdpClipboardData } from '../../domain/rdpClipboard';
|
||||
import { buildRdpClipboardItemData, nextRdpClipboardGuardState, selectRdpClipboardData, shouldPushLocalClipboardToRdp } from '../../domain/rdpClipboard';
|
||||
import {
|
||||
computeMonitorVirtualBounds,
|
||||
mapViewportToVirtualDesktopCoords,
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
resolveKeyToRdpScancode,
|
||||
type RemoteDesktopAction,
|
||||
} from '../../domain/remoteDesktopActionCodec';
|
||||
import { buildRdpFileContentsResponse } from '../../infrastructure/remoteDesktop/rdpFileContents';
|
||||
import type { RemoteDesktopSharedFolder } from '../../infrastructure/remoteDesktop/remoteDesktopSharedFolders';
|
||||
import {
|
||||
captureFrameFromCanvas,
|
||||
@@ -468,6 +469,15 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
|
||||
callbacksRef.current.onClipboardFileTransferStatus?.(transfer?.message ?? null);
|
||||
}, []);
|
||||
|
||||
const clearLocalClipboardFiles = useCallback(() => {
|
||||
if (uploadedFilesRef.current.length === 0) return;
|
||||
uploadedFilesRef.current = [];
|
||||
uploadedHighWaterByIndexRef.current.clear();
|
||||
uploadTransferIdRef.current = '';
|
||||
lastUploadProgressEmitRef.current = 0;
|
||||
emitClipboardTransfer(null);
|
||||
}, [emitClipboardTransfer]);
|
||||
|
||||
const downloadRemoteClipboardFile = useCallback(async (fileIndex: number) => {
|
||||
const session = sessionRef.current;
|
||||
const mod = modRef.current;
|
||||
@@ -579,6 +589,10 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
|
||||
});
|
||||
toast.info(stagedMessage);
|
||||
} catch (err) {
|
||||
uploadedFilesRef.current = [];
|
||||
uploadedHighWaterByIndexRef.current.clear();
|
||||
uploadTransferIdRef.current = '';
|
||||
lastUploadProgressEmitRef.current = 0;
|
||||
const errMessage = err instanceof Error ? err.message : 'Server does not support clipboard file transfer';
|
||||
emitClipboardTransfer({
|
||||
id: transferId,
|
||||
@@ -601,7 +615,11 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
|
||||
|
||||
// Sync local clipboard to remote when focused or manually requested
|
||||
const syncLocalClipboardToRdp = useCallback(async (force = false) => {
|
||||
if ((!force && !propsRef.current.clipboardSyncEnabled) || propsRef.current.viewOnly) return;
|
||||
if (!shouldPushLocalClipboardToRdp({
|
||||
...propsRef.current,
|
||||
force,
|
||||
stagedLocalFileCount: uploadedFilesRef.current.length,
|
||||
})) return;
|
||||
const session = sessionRef.current;
|
||||
const mod = modRef.current;
|
||||
if (!session || !mod) return;
|
||||
@@ -611,6 +629,12 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
|
||||
Promise.resolve().then(() => navigator.clipboard?.readText()),
|
||||
readClipboardImagePng(),
|
||||
]);
|
||||
// A file drop or session change can happen while clipboard reads are pending.
|
||||
if (sessionRef.current !== session || !shouldPushLocalClipboardToRdp({
|
||||
...propsRef.current,
|
||||
force,
|
||||
stagedLocalFileCount: uploadedFilesRef.current.length,
|
||||
})) return;
|
||||
const { text, pngBytes } = selectRdpClipboardData({
|
||||
text: textResult.status === 'fulfilled' ? textResult.value : null,
|
||||
pngBytes: pngResult.status === 'fulfilled' ? pngResult.value : null,
|
||||
@@ -622,6 +646,7 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
|
||||
try {
|
||||
if (text) data.addText('text/plain', text);
|
||||
if (pngBytes) data.addBinary('image/png', pngBytes);
|
||||
if (force) clearLocalClipboardFiles();
|
||||
await session.onClipboardPaste(data);
|
||||
lastClipboardGuardStateRef.current = nextRdpClipboardGuardState({ text, pngBytes });
|
||||
} finally {
|
||||
@@ -630,7 +655,7 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
|
||||
} catch {
|
||||
// Clipboard permission or empty
|
||||
}
|
||||
}, [readClipboardImagePng]);
|
||||
}, [clearLocalClipboardFiles, readClipboardImagePng]);
|
||||
|
||||
const syncClipboardNow = useCallback(() => syncLocalClipboardToRdp(true), [syncLocalClipboardToRdp]);
|
||||
|
||||
@@ -1169,7 +1194,7 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
|
||||
|
||||
// Clipboard (text / HTML / PNG)
|
||||
builder.remoteClipboardChangedCallback((clipboardData: IronClipboardData) => {
|
||||
if (disposed || !propsRef.current.clipboardSyncEnabled) return;
|
||||
if (disposed) return;
|
||||
try {
|
||||
const items = clipboardData.items();
|
||||
let plainText: string | null = null;
|
||||
@@ -1183,6 +1208,8 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
|
||||
pngBytes = val;
|
||||
}
|
||||
}
|
||||
if (plainText !== null || pngBytes !== null) clearLocalClipboardFiles();
|
||||
if (!propsRef.current.clipboardSyncEnabled) return;
|
||||
lastClipboardGuardStateRef.current = nextRdpClipboardGuardState({ text: plainText, pngBytes });
|
||||
if (pngBytes && typeof ClipboardItem !== 'undefined' && navigator.clipboard?.write) {
|
||||
const data = buildRdpClipboardItemData({ text: plainText, pngBytes });
|
||||
@@ -1226,6 +1253,7 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
|
||||
isDirectory: Boolean(f?.isDirectory),
|
||||
}),
|
||||
);
|
||||
if (offers.length > 0) clearLocalClipboardFiles();
|
||||
remoteFilesRef.current = { clipDataId, files: offers };
|
||||
callbacksRef.current.onRemoteClipboardFilesChange?.(offers);
|
||||
},
|
||||
@@ -1249,11 +1277,10 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
|
||||
if (!file) {
|
||||
try {
|
||||
session.invokeExtension(
|
||||
new mod.Extension('submit_file_contents', {
|
||||
streamId: req.streamId,
|
||||
isError: true,
|
||||
data: new Uint8Array(0),
|
||||
}),
|
||||
new mod.Extension(
|
||||
'submit_file_contents',
|
||||
buildRdpFileContentsResponse(req.streamId, true, new Uint8Array(0)),
|
||||
),
|
||||
);
|
||||
} catch { /* ignore */ }
|
||||
return;
|
||||
@@ -1268,11 +1295,10 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
|
||||
dv.setUint32(4, high, true);
|
||||
try {
|
||||
session.invokeExtension(
|
||||
new mod.Extension('submit_file_contents', {
|
||||
streamId: req.streamId,
|
||||
isError: false,
|
||||
data: new Uint8Array(sizeBuf),
|
||||
}),
|
||||
new mod.Extension(
|
||||
'submit_file_contents',
|
||||
buildRdpFileContentsResponse(req.streamId, false, new Uint8Array(sizeBuf)),
|
||||
),
|
||||
);
|
||||
} catch { /* ignore */ }
|
||||
return;
|
||||
@@ -1286,11 +1312,10 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
|
||||
.then((ab) => {
|
||||
if (disposed || !sessionRef.current) return;
|
||||
sessionRef.current.invokeExtension(
|
||||
new mod.Extension('submit_file_contents', {
|
||||
streamId: req.streamId,
|
||||
isError: false,
|
||||
data: new Uint8Array(ab),
|
||||
}),
|
||||
new mod.Extension(
|
||||
'submit_file_contents',
|
||||
buildRdpFileContentsResponse(req.streamId, false, new Uint8Array(ab)),
|
||||
),
|
||||
);
|
||||
const prevHighWater = uploadedHighWaterByIndexRef.current.get(req.index) ?? 0;
|
||||
const nextHighWater = Math.max(
|
||||
@@ -1328,11 +1353,10 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
|
||||
if (disposed || !sessionRef.current) return;
|
||||
try {
|
||||
sessionRef.current.invokeExtension(
|
||||
new mod.Extension('submit_file_contents', {
|
||||
streamId: req.streamId,
|
||||
isError: true,
|
||||
data: new Uint8Array(0),
|
||||
}),
|
||||
new mod.Extension(
|
||||
'submit_file_contents',
|
||||
buildRdpFileContentsResponse(req.streamId, true, new Uint8Array(0)),
|
||||
),
|
||||
);
|
||||
} catch { /* ignore */ }
|
||||
const errMessage = err instanceof Error
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
|
||||
const source = readFileSync(new URL('./RemoteDesktopPane.tsx', import.meta.url), 'utf8');
|
||||
|
||||
test('RemoteDesktopPane keeps keyboard grab in visible solo and focus panes and honors split focus', () => {
|
||||
const terminalLayerSource = readFileSync(new URL('../terminalLayer/TerminalLayerSupport.tsx', import.meta.url), 'utf8');
|
||||
const paneProps = terminalLayerSource.match(/<LazyRemoteDesktopPane\b[\s\S]*?\/>/)?.[0];
|
||||
assert.ok(paneProps, 'RemoteDesktopPane must be wired into the terminal layer');
|
||||
assert.match(paneProps, /isVisible=\{isVisible\}/);
|
||||
// Solo and focus modes have no split contention; only split siblings use the focus boolean.
|
||||
assert.match(paneProps, /isFocused=\{paneState.mode === 'split' \? isFocusedPane : true\}/);
|
||||
});
|
||||
|
||||
test('RemoteDesktopPane releases keyboard grab for an unfocused split sibling, hidden, disconnected, or view-only pane', () => {
|
||||
assert.match(
|
||||
source,
|
||||
/useEffect\(\(\) => \{\s*if \(\(!isVisible \|\| !isFocused \|\| status !== 'connected' \|\| viewOnly\) && keyboardGrabActive\) \{\s*releaseKeyboardGrab\(\);\s*\}\s*\}, \[isFocused, isVisible, keyboardGrabActive, releaseKeyboardGrab, status, viewOnly\]\)/,
|
||||
);
|
||||
});
|
||||
|
||||
test('RemoteDesktopPane scopes all pane UI portals to the pane only in session fullscreen', () => {
|
||||
assert.match(source, /import \{ PortalContainerProvider \} from '\.\.\/ui\/portal-container'/);
|
||||
assert.match(source, /const \[portalContainer, setPortalContainer\] = useState<HTMLDivElement \| null>\(null\)/);
|
||||
assert.match(source, /const paneContent = \([\s\S]*<RemoteDesktopToolbar[\s\S]*<RemoteDesktopAuditDialog/);
|
||||
assert.match(
|
||||
source,
|
||||
/<PortalContainerProvider container=\{isFullscreen \? portalContainer : null\}>\s*\{paneContent\}\s*<\/PortalContainerProvider>/,
|
||||
);
|
||||
});
|
||||
|
||||
test('RemoteDesktopPane uses the same root for fullscreen ownership and the portal container', () => {
|
||||
assert.match(
|
||||
source,
|
||||
/const setPaneRoot = useCallback\(\(node: HTMLDivElement \| null\) => \{\s*paneRootRef.current = node;\s*setPortalContainer\(node\);\s*\}, \[\]\)/,
|
||||
);
|
||||
assert.match(source, /const paneContent = \(\s*<div\s+ref=\{setPaneRoot\}/);
|
||||
assert.match(
|
||||
source,
|
||||
/const root = paneRootRef.current;\s*setIsFullscreen\(Boolean\(root && document.fullscreenElement === root\)\)/,
|
||||
);
|
||||
assert.match(source, /document.addEventListener\('fullscreenchange', handleFsChange\)/);
|
||||
assert.match(source, /document.removeEventListener\('fullscreenchange', handleFsChange\)/);
|
||||
assert.match(source, /const root = paneRootRef.current;[\s\S]*root.requestFullscreen\(\)/);
|
||||
});
|
||||
@@ -79,6 +79,7 @@ import {
|
||||
VncProtocolIcon,
|
||||
} from '../icons/RemoteDesktopIcons';
|
||||
import { Button } from '../ui/button';
|
||||
import { PortalContainerProvider } from '../ui/portal-container';
|
||||
import { toast } from '../ui/toast';
|
||||
import {
|
||||
trustKnownRemoteDesktopCert,
|
||||
@@ -208,6 +209,11 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
|
||||
const { t } = useI18n();
|
||||
const isRdp = protocol === 'rdp';
|
||||
const paneRootRef = useRef<HTMLDivElement | null>(null);
|
||||
const [portalContainer, setPortalContainer] = useState<HTMLDivElement | null>(null);
|
||||
const setPaneRoot = useCallback((node: HTMLDivElement | null) => {
|
||||
paneRootRef.current = node;
|
||||
setPortalContainer(node);
|
||||
}, []);
|
||||
const canvasAreaRef = useRef<HTMLDivElement | null>(null);
|
||||
const canvasHandleRef = useRef<RemoteDesktopCanvasHandle | null>(null);
|
||||
const activeBackendSessionIdRef = useRef<string | null>(null);
|
||||
@@ -1161,6 +1167,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
|
||||
keys,
|
||||
identities,
|
||||
knownHosts,
|
||||
credentials,
|
||||
});
|
||||
const res = await rdBridge.openSystemClient(opts);
|
||||
if (!res?.ok) {
|
||||
@@ -1169,7 +1176,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Failed to launch system client');
|
||||
}
|
||||
}, [chainHosts, host, identities, keys, knownHosts, protocol]);
|
||||
}, [chainHosts, credentials, host, identities, keys, knownHosts, protocol]);
|
||||
|
||||
const handleToggleFullscreen = useCallback(() => {
|
||||
const root = paneRootRef.current;
|
||||
@@ -1747,9 +1754,9 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
|
||||
const showRemoteAppNotice =
|
||||
isRdp && Boolean(spec.rdpConfig?.remoteApplicationMode) && !remoteAppBannerDismissed;
|
||||
|
||||
return (
|
||||
const paneContent = (
|
||||
<div
|
||||
ref={paneRootRef}
|
||||
ref={setPaneRoot}
|
||||
className={cn(
|
||||
'relative flex h-full w-full flex-col overflow-hidden bg-black text-foreground select-none',
|
||||
keyboardGrabActive && 'ring-2 ring-inset ring-primary/80',
|
||||
@@ -2309,6 +2316,13 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
// Fullscreen portals must stay inside the pane; windowed menus need to escape its overflow clipping.
|
||||
return (
|
||||
<PortalContainerProvider container={isFullscreen ? portalContainer : null}>
|
||||
{paneContent}
|
||||
</PortalContainerProvider>
|
||||
);
|
||||
});
|
||||
RemoteDesktopPane.displayName = 'RemoteDesktopPane';
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import { selectConnectionLogForTerminalDataCapture } from '../../domain/connecti
|
||||
import type { ConnectionLog } from '../../domain/models';
|
||||
import type { Host, TerminalSession } from '../../types';
|
||||
import {
|
||||
buildSystemRemoteDesktopPayload,
|
||||
canOpenCompanionRemoteDesktopSftp,
|
||||
computeClipboardUploadProgress,
|
||||
formatRecordingDuration,
|
||||
@@ -155,3 +156,77 @@ test('stampRemoteDesktopSessionEndTimes and handleTerminalDataCaptureImpl stamp
|
||||
assert.ok(typeof updates[0].patch.endTime === 'number' && updates[0].patch.endTime > 0);
|
||||
assert.equal('terminalData' in updates[0].patch, false);
|
||||
});
|
||||
|
||||
test('buildSystemRemoteDesktopPayload passes RDP password via payload without embedding it in rdpContent', () => {
|
||||
const rdpHost = {
|
||||
id: 'rdp-1',
|
||||
label: 'Prod Win',
|
||||
hostname: '10.10.0.5',
|
||||
port: 3389,
|
||||
username: 'CORP\\alice',
|
||||
password: 'VaultedPassword123!',
|
||||
group: '',
|
||||
tags: [],
|
||||
os: 'windows',
|
||||
protocol: 'rdp',
|
||||
} as unknown as Host;
|
||||
|
||||
const vaultedPayload = buildSystemRemoteDesktopPayload({
|
||||
host: rdpHost,
|
||||
protocol: 'rdp',
|
||||
keys: [],
|
||||
identities: [],
|
||||
});
|
||||
|
||||
assert.equal(vaultedPayload.protocol, 'rdp');
|
||||
assert.equal(vaultedPayload.username, 'alice');
|
||||
assert.equal(vaultedPayload.domain, 'CORP');
|
||||
assert.equal(vaultedPayload.password, 'VaultedPassword123!');
|
||||
assert.ok(vaultedPayload.rdpContent);
|
||||
assert.equal(vaultedPayload.rdpContent.includes('VaultedPassword123!'), false);
|
||||
assert.match(vaultedPayload.rdpContent, /^prompt for credentials:i:1\r?$/m);
|
||||
|
||||
// Runtime credentials override (typed in auth dialog)
|
||||
const runtimePayload = buildSystemRemoteDesktopPayload({
|
||||
host: rdpHost,
|
||||
protocol: 'rdp',
|
||||
keys: [],
|
||||
identities: [],
|
||||
credentials: {
|
||||
username: 'localadmin',
|
||||
domain: '',
|
||||
password: 'TypedRuntimePassword!',
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(runtimePayload.username, 'localadmin');
|
||||
assert.equal(runtimePayload.domain, undefined);
|
||||
assert.equal(runtimePayload.password, 'TypedRuntimePassword!');
|
||||
assert.ok(runtimePayload.rdpContent);
|
||||
assert.equal(runtimePayload.rdpContent.includes('TypedRuntimePassword!'), false);
|
||||
assert.match(runtimePayload.rdpContent, /^username:s:localadmin\r?$/m);
|
||||
|
||||
// VNC never passes password on the system client payload
|
||||
const vncHost = {
|
||||
...rdpHost,
|
||||
id: 'vnc-1',
|
||||
port: 5900,
|
||||
protocol: 'vnc',
|
||||
} as unknown as Host;
|
||||
|
||||
const vncPayload = buildSystemRemoteDesktopPayload({
|
||||
host: vncHost,
|
||||
protocol: 'vnc',
|
||||
keys: [],
|
||||
identities: [],
|
||||
credentials: {
|
||||
username: 'bob',
|
||||
domain: '',
|
||||
password: 'VncPasswordShouldNotPass',
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(vncPayload.protocol, 'vnc');
|
||||
assert.equal(vncPayload.password, undefined);
|
||||
assert.equal(vncPayload.rdpContent, undefined);
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Host, Identity, KnownHost, SSHKey } from '../../types';
|
||||
import {
|
||||
resolveRemoteDesktopConnectionSpec,
|
||||
splitWindowsUserDomain,
|
||||
type MonitorLayoutSpec,
|
||||
type RemoteDesktopConnectionSpec,
|
||||
type RemoteDesktopProtocol,
|
||||
@@ -447,18 +448,42 @@ export function buildSystemRemoteDesktopPayload(args: {
|
||||
identities: readonly Identity[];
|
||||
knownHosts?: readonly KnownHost[];
|
||||
rawRdpContent?: string;
|
||||
credentials?: {
|
||||
username?: string;
|
||||
password?: string;
|
||||
domain?: string;
|
||||
};
|
||||
}): RemoteDesktopOpenSystemClientOptions {
|
||||
const { host, protocol, chainHosts, keys, identities, knownHosts, rawRdpContent } = args;
|
||||
const { host, protocol, chainHosts, keys, identities, knownHosts, rawRdpContent, credentials } = args;
|
||||
const spec = resolveRemoteDesktopConnectionSpec(host, protocol, identities);
|
||||
const jumpHosts = buildSshJumpHostConfigs(chainHosts, keys, identities);
|
||||
const proxy = toBridgeProxy(host, identities);
|
||||
|
||||
const rawUsername = credentials?.username !== undefined ? credentials.username : spec.username;
|
||||
const rawDomain = protocol === 'rdp'
|
||||
? (credentials?.domain !== undefined ? credentials.domain : spec.domain)
|
||||
: '';
|
||||
const resolvedUserDomain = protocol === 'rdp'
|
||||
? splitWindowsUserDomain(rawUsername, rawDomain)
|
||||
: { username: (rawUsername || '').trim(), domain: '' };
|
||||
const effectiveUsername = resolvedUserDomain.username || undefined;
|
||||
const effectiveDomain = protocol === 'rdp' ? (resolvedUserDomain.domain || undefined) : undefined;
|
||||
const rawPassword = protocol === 'rdp'
|
||||
? (credentials?.password !== undefined && credentials.password.length > 0
|
||||
? credentials.password
|
||||
: spec.password)
|
||||
: undefined;
|
||||
const sanitizedPassword = sanitizeCredentialValue(rawPassword);
|
||||
const effectivePassword = sanitizedPassword && sanitizedPassword.length > 0
|
||||
? sanitizedPassword
|
||||
: undefined;
|
||||
|
||||
const rdpContent = protocol === 'rdp'
|
||||
? (rawRdpContent?.trim() || generateRdpFileContent({
|
||||
hostname: spec.hostname,
|
||||
port: spec.port,
|
||||
username: spec.username || undefined,
|
||||
domain: spec.domain || undefined,
|
||||
username: effectiveUsername,
|
||||
domain: effectiveDomain,
|
||||
width: spec.rdpConfig?.width,
|
||||
height: spec.rdpConfig?.height,
|
||||
colorDepth: spec.rdpConfig?.colorDepth,
|
||||
@@ -479,8 +504,9 @@ export function buildSystemRemoteDesktopPayload(args: {
|
||||
protocol,
|
||||
hostname: spec.hostname,
|
||||
port: spec.port,
|
||||
username: spec.username || undefined,
|
||||
domain: spec.domain || undefined,
|
||||
username: effectiveUsername,
|
||||
...(effectivePassword !== undefined ? { password: effectivePassword } : {}),
|
||||
domain: effectiveDomain,
|
||||
label: spec.label,
|
||||
rdpContent,
|
||||
loadBalanceInfo: spec.rdpConfig?.loadBalanceInfo,
|
||||
|
||||
@@ -18,6 +18,7 @@ import type {
|
||||
ProviderConfig,
|
||||
WebSearchConfig,
|
||||
} from "../../../infrastructure/ai/types";
|
||||
import type { TitleModelConfig } from "../../../application/state/useAISettingsState";
|
||||
import type { ManagedAgentKey } from "../../../infrastructure/ai/managedAgents";
|
||||
import { PROVIDER_PRESETS } from "../../../infrastructure/ai/types";
|
||||
import { withOpencodeGoAutoConfiguredModel, shouldAutoActivateOpencodeGo } from "../../../infrastructure/ai/opencodeGo";
|
||||
@@ -62,6 +63,7 @@ import {
|
||||
} from "../../../domain/aiSessionMessageCap";
|
||||
import { WebSearchSettings } from "./ai/WebSearchSettings";
|
||||
import { QuickMessagesSettings } from "./ai/QuickMessagesSettings";
|
||||
import { TitleModelPicker } from "./ai/TitleModelPicker";
|
||||
import type { AIQuickMessage } from "../../../infrastructure/ai/quickMessages";
|
||||
import { encryptField } from "../../../infrastructure/persistence/secureFieldAdapter";
|
||||
import { CursorSdkCard } from "./ai/CursorSdkCard";
|
||||
@@ -175,6 +177,12 @@ interface SettingsAITabProps {
|
||||
setQuickMessages: (value: AIQuickMessage[] | ((prev: AIQuickMessage[]) => AIQuickMessage[])) => void;
|
||||
showTerminalSelectionAIAction: boolean;
|
||||
setShowTerminalSelectionAIAction: (value: boolean | ((prev: boolean) => boolean)) => void;
|
||||
autoLlmTitle: boolean;
|
||||
setAutoLlmTitle: (value: boolean | ((prev: boolean) => boolean)) => void;
|
||||
titleModel: TitleModelConfig | null;
|
||||
setTitleModel: (config: TitleModelConfig | null) => void;
|
||||
agentProviderMap: Record<string, string>;
|
||||
agentModelMap: Record<string, string>;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -188,7 +196,7 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
removeProvider,
|
||||
activeProviderId,
|
||||
setActiveProviderId,
|
||||
activeModelId: _activeModelId,
|
||||
activeModelId,
|
||||
setActiveModelId,
|
||||
globalPermissionMode,
|
||||
setGlobalPermissionMode,
|
||||
@@ -216,6 +224,12 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
setQuickMessages,
|
||||
showTerminalSelectionAIAction,
|
||||
setShowTerminalSelectionAIAction,
|
||||
autoLlmTitle,
|
||||
setAutoLlmTitle,
|
||||
titleModel,
|
||||
setTitleModel,
|
||||
agentProviderMap,
|
||||
agentModelMap,
|
||||
}) => {
|
||||
const {
|
||||
permissionGrants,
|
||||
@@ -1369,6 +1383,35 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
<span className="text-xs text-muted-foreground">{t('ai.chatHistory.messageCap.unit')}</span>
|
||||
</div>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
anchorId="ai-chat-history-auto-llm-title"
|
||||
label={t('ai.chatHistory.autoLlmTitle')}
|
||||
description={t('ai.chatHistory.autoLlmTitle.description')}
|
||||
>
|
||||
<Toggle
|
||||
checked={autoLlmTitle}
|
||||
onChange={setAutoLlmTitle}
|
||||
ariaLabel={t('ai.chatHistory.autoLlmTitle')}
|
||||
/>
|
||||
</SettingRow>
|
||||
{autoLlmTitle && (
|
||||
<SettingRow
|
||||
anchorId="ai-chat-history-title-model"
|
||||
label={t('ai.chatHistory.titleModel')}
|
||||
description={t('ai.chatHistory.titleModel.description')}
|
||||
>
|
||||
<TitleModelPicker
|
||||
providers={providers}
|
||||
activeProviderId={activeProviderId}
|
||||
activeModelId={activeModelId}
|
||||
agentProviderMap={agentProviderMap}
|
||||
agentModelMap={agentModelMap}
|
||||
value={titleModel}
|
||||
onChange={setTitleModel}
|
||||
t={t}
|
||||
/>
|
||||
</SettingRow>
|
||||
)}
|
||||
</SettingCard>
|
||||
</SettingsSection>
|
||||
|
||||
|
||||
@@ -68,6 +68,8 @@ function SettingsAppearanceTab(props: {
|
||||
setShowSftpTab: (enabled: boolean) => void;
|
||||
showHostTreeSidebar: boolean;
|
||||
setShowHostTreeSidebar: (enabled: boolean) => void;
|
||||
removeTopTabsDragArea: boolean;
|
||||
setRemoveTopTabsDragArea: (enabled: boolean) => void;
|
||||
windowOpacity: number;
|
||||
setWindowOpacity: (opacity: number) => void;
|
||||
windowBackgroundBlur: boolean;
|
||||
@@ -141,6 +143,8 @@ function SettingsAppearanceTab(props: {
|
||||
setShowSftpTab,
|
||||
showHostTreeSidebar,
|
||||
setShowHostTreeSidebar,
|
||||
removeTopTabsDragArea,
|
||||
setRemoveTopTabsDragArea,
|
||||
windowOpacity,
|
||||
setWindowOpacity,
|
||||
windowBackgroundBlur,
|
||||
@@ -525,6 +529,13 @@ function SettingsAppearanceTab(props: {
|
||||
>
|
||||
<Toggle checked={showHostTreeSidebar} onChange={setShowHostTreeSidebar} />
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
anchorId="appearance-vault-remove-top-tabs-drag-area"
|
||||
label={t('settings.vault.removeTopTabsDragArea')}
|
||||
description={t('settings.vault.removeTopTabsDragAreaDesc')}
|
||||
>
|
||||
<Toggle checked={removeTopTabsDragArea} onChange={setRemoveTopTabsDragArea} />
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
anchorId="appearance-vault-auto-import-known-hosts"
|
||||
label={t('settings.vault.autoImportSystemKnownHosts')}
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import React from "react";
|
||||
|
||||
import { getLoadedLocaleMessages, loadLocaleMessages } from "../../../../application/i18n/messages.ts";
|
||||
import type { ProviderConfig } from "../../../../infrastructure/ai/types.ts";
|
||||
import { createDomRenderer, dispatchDomEvent, installDomEnvironment } from "../../../test-support/renderReactDom.tsx";
|
||||
import {
|
||||
buildTitleModelPickerViewModel,
|
||||
TITLE_MODEL_INHERIT_VALUE,
|
||||
} from "./titleModelPickerViewModel.ts";
|
||||
|
||||
await loadLocaleMessages("en");
|
||||
const enMessages = getLoadedLocaleMessages("en")!;
|
||||
const t = (key: string) => {
|
||||
const hit = enMessages[key as keyof typeof enMessages];
|
||||
return typeof hit === "string" ? hit : key;
|
||||
};
|
||||
|
||||
const firstProvider: ProviderConfig = {
|
||||
id: "p-first",
|
||||
providerId: "openai",
|
||||
name: "DeepSeek Cheap",
|
||||
enabled: true,
|
||||
defaultModel: "deepseek-chat",
|
||||
};
|
||||
|
||||
const cattyProvider: ProviderConfig = {
|
||||
id: "p-catty",
|
||||
providerId: "anthropic",
|
||||
name: "Claude Main",
|
||||
enabled: true,
|
||||
defaultModel: "claude-sonnet-4",
|
||||
};
|
||||
|
||||
const disabledProvider: ProviderConfig = {
|
||||
id: "p-off",
|
||||
providerId: "openai",
|
||||
name: "Disabled Provider",
|
||||
enabled: false,
|
||||
defaultModel: "gpt-4o-mini",
|
||||
};
|
||||
|
||||
const customEmptyProvider: ProviderConfig = {
|
||||
id: "p-custom-empty",
|
||||
providerId: "custom",
|
||||
name: "Custom Empty",
|
||||
enabled: true,
|
||||
defaultModel: "",
|
||||
};
|
||||
|
||||
function installRadixGlobals(dom: ReturnType<typeof installDomEnvironment>) {
|
||||
const globalAsRecord = globalThis as Record<string, unknown>;
|
||||
const saved = new Map<string, { existed: boolean; value: unknown }>();
|
||||
const setGlobal = (key: string, value: unknown) => {
|
||||
saved.set(key, { existed: Object.prototype.hasOwnProperty.call(globalAsRecord, key), value: globalAsRecord[key] });
|
||||
globalAsRecord[key] = value;
|
||||
};
|
||||
for (const key of [
|
||||
"MutationObserver", "NodeFilter", "Element", "HTMLElement", "HTMLInputElement",
|
||||
"HTMLTextAreaElement", "HTMLButtonElement", "HTMLAnchorElement", "HTMLSelectElement",
|
||||
"DocumentFragment", "Text", "CharacterData", "ShadowRoot", "SVGElement", "DOMRect",
|
||||
] as const) {
|
||||
const winValue = (dom.window as unknown as Record<string, unknown>)[key];
|
||||
if (globalAsRecord[key] == null && winValue != null) setGlobal(key, winValue);
|
||||
}
|
||||
if (globalAsRecord.PointerEvent == null) setGlobal("PointerEvent", dom.window.MouseEvent);
|
||||
if (globalAsRecord.ResizeObserver == null) {
|
||||
setGlobal("ResizeObserver", class { observe() {} unobserve() {} disconnect() {} });
|
||||
}
|
||||
if (globalAsRecord.requestAnimationFrame == null) {
|
||||
setGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => setTimeout(() => cb(Date.now()), 0));
|
||||
}
|
||||
if (globalAsRecord.cancelAnimationFrame == null) {
|
||||
setGlobal("cancelAnimationFrame", (id: ReturnType<typeof setTimeout>) => clearTimeout(id));
|
||||
}
|
||||
const proto = dom.window.HTMLElement.prototype as unknown as Record<string, unknown>;
|
||||
if (typeof proto.hasPointerCapture !== "function") proto.hasPointerCapture = () => false;
|
||||
if (typeof proto.releasePointerCapture !== "function") proto.releasePointerCapture = () => {};
|
||||
if (typeof proto.setPointerCapture !== "function") proto.setPointerCapture = () => {};
|
||||
if (typeof proto.scrollIntoView !== "function") proto.scrollIntoView = () => {};
|
||||
|
||||
return () => {
|
||||
for (const [key, entry] of saved) {
|
||||
if (entry.existed) globalAsRecord[key] = entry.value;
|
||||
else delete globalAsRecord[key];
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
test("null titleModel represents 'Use current Catty model' and reflects Catty's effective model instead of providers[0]", () => {
|
||||
const vm = buildTitleModelPickerViewModel({
|
||||
providers: [firstProvider, cattyProvider],
|
||||
activeProviderId: firstProvider.id,
|
||||
activeModelId: "deepseek-chat",
|
||||
agentProviderMap: { catty: cattyProvider.id },
|
||||
agentModelMap: { catty: "claude-opus-4" },
|
||||
value: null,
|
||||
t,
|
||||
});
|
||||
|
||||
assert.equal(vm.mode, "inherit");
|
||||
assert.equal(vm.providerSelectValue, TITLE_MODEL_INHERIT_VALUE);
|
||||
assert.equal(vm.providerOptions[0].value, TITLE_MODEL_INHERIT_VALUE);
|
||||
assert.equal(vm.providerOptions[0].label, t("ai.chatHistory.titleModel.useCurrentCatty"));
|
||||
assert.equal(vm.inheritedLabel, "Claude Main · claude-opus-4");
|
||||
});
|
||||
|
||||
test("explicit disabled or missing titleModel stays visible as unavailable rather than pretending to inherit", () => {
|
||||
const vm = buildTitleModelPickerViewModel({
|
||||
providers: [firstProvider, disabledProvider],
|
||||
activeProviderId: firstProvider.id,
|
||||
activeModelId: "deepseek-chat",
|
||||
agentProviderMap: {},
|
||||
agentModelMap: {},
|
||||
value: { providerId: disabledProvider.id, modelId: "gpt-4o-mini" },
|
||||
t,
|
||||
});
|
||||
|
||||
assert.equal(vm.mode, "explicit");
|
||||
assert.equal(vm.providerSelectValue, disabledProvider.id);
|
||||
const unavailable = vm.providerOptions.find((opt) => opt.value === disabledProvider.id);
|
||||
assert.ok(unavailable?.disabled);
|
||||
assert.match(unavailable?.label ?? "", /Unavailable/);
|
||||
});
|
||||
|
||||
test("TitleModelPicker lets user pick providers[0] from inherit mode, revert to null, and avoids saving empty modelId", async () => {
|
||||
const dom = installDomEnvironment();
|
||||
const restoreGlobals = installRadixGlobals(dom);
|
||||
try {
|
||||
const { TitleModelPicker } = await import("./TitleModelPicker.tsx");
|
||||
const changes: Array<{ providerId: string; modelId: string } | null> = [];
|
||||
const renderer = await createDomRenderer(dom.document);
|
||||
|
||||
const renderPicker = async (value: { providerId: string; modelId: string } | null) => {
|
||||
await renderer.render(
|
||||
<TitleModelPicker
|
||||
providers={[firstProvider, cattyProvider, customEmptyProvider]}
|
||||
activeProviderId={cattyProvider.id}
|
||||
activeModelId="claude-sonnet-4"
|
||||
agentProviderMap={{ catty: cattyProvider.id }}
|
||||
agentModelMap={{ catty: "claude-opus-4" }}
|
||||
value={value}
|
||||
onChange={(next) => changes.push(next)}
|
||||
t={t}
|
||||
/>,
|
||||
);
|
||||
};
|
||||
|
||||
await renderPicker(null);
|
||||
const inheritedSummary = renderer.container.querySelector('[data-section="ai-title-model-inherited"]');
|
||||
assert.equal(inheritedSummary?.textContent, "Claude Main · claude-opus-4");
|
||||
|
||||
// Open provider select and choose providers[0] ("DeepSeek Cheap").
|
||||
const triggers = renderer.container.querySelectorAll<HTMLElement>('[role="combobox"]');
|
||||
assert.equal(triggers.length, 1, "model picker hidden while inheriting Catty model");
|
||||
assert.ok((triggers[0].textContent ?? "").includes(t("ai.chatHistory.titleModel.useCurrentCatty")));
|
||||
|
||||
await dispatchDomEvent(triggers[0], new dom.window.KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
const options = Array.from(dom.document.body.querySelectorAll<HTMLElement>('[role="option"]'));
|
||||
const deepseekOption = options.find((el) => (el.textContent ?? "").includes("DeepSeek Cheap"));
|
||||
assert.ok(deepseekOption);
|
||||
await dispatchDomEvent(deepseekOption, new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.deepEqual(changes, [{ providerId: "p-first", modelId: "deepseek-chat" }]);
|
||||
|
||||
// Re-render with an explicit custom modelId not in seed catalog -> still renders its label.
|
||||
await renderPicker({ providerId: "p-first", modelId: "custom-tiny-model" });
|
||||
const triggersExplicit = renderer.container.querySelectorAll<HTMLElement>('[role="combobox"]');
|
||||
assert.equal(triggersExplicit.length, 2);
|
||||
assert.ok((triggersExplicit[1].textContent ?? "").includes("custom-tiny-model"));
|
||||
|
||||
// Selecting a provider with no defaultModel/seed models does not persist empty modelId.
|
||||
await dispatchDomEvent(triggersExplicit[0], new dom.window.KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
const emptyOpt = Array.from(dom.document.body.querySelectorAll<HTMLElement>('[role="option"]'))
|
||||
.find((el) => (el.textContent ?? "").includes("Custom Empty"));
|
||||
assert.ok(emptyOpt);
|
||||
await dispatchDomEvent(emptyOpt, new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(changes.length, 1, "does not persist incomplete { providerId, modelId: '' }");
|
||||
|
||||
// Reverting to "Use current Catty model" emits null.
|
||||
const triggersAfterPending = renderer.container.querySelectorAll<HTMLElement>('[role="combobox"]');
|
||||
await dispatchDomEvent(triggersAfterPending[0], new dom.window.KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
const inheritOpt = Array.from(dom.document.body.querySelectorAll<HTMLElement>('[role="option"]'))
|
||||
.find((el) => (el.textContent ?? "").includes(t("ai.chatHistory.titleModel.useCurrentCatty")));
|
||||
assert.ok(inheritOpt);
|
||||
await dispatchDomEvent(inheritOpt, new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(changes.at(-1), null);
|
||||
} finally {
|
||||
restoreGlobals();
|
||||
dom.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,133 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import type { TitleModelConfig } from "../../../../domain/aiSessionTitle";
|
||||
import { seedProviderModelCatalog } from "../../../../infrastructure/ai/cattyProviderModels";
|
||||
import type { ProviderConfig } from "../../../../infrastructure/ai/types";
|
||||
import { useProviderModelCatalog } from "../../../ai/useProviderModelCatalog";
|
||||
import { Select } from "../../settings-ui";
|
||||
import {
|
||||
buildTitleModelPickerViewModel,
|
||||
TITLE_MODEL_INHERIT_VALUE,
|
||||
} from "./titleModelPickerViewModel";
|
||||
|
||||
export {
|
||||
buildTitleModelPickerViewModel,
|
||||
TITLE_MODEL_INHERIT_VALUE,
|
||||
type TitleModelPickerOption,
|
||||
type TitleModelPickerViewModel,
|
||||
} from "./titleModelPickerViewModel";
|
||||
|
||||
export interface TitleModelPickerProps {
|
||||
providers: ProviderConfig[];
|
||||
activeProviderId: string;
|
||||
activeModelId: string;
|
||||
agentProviderMap: Record<string, string>;
|
||||
agentModelMap: Record<string, string>;
|
||||
value: TitleModelConfig | null;
|
||||
onChange: (config: TitleModelConfig | null) => void;
|
||||
t: (key: string) => string;
|
||||
}
|
||||
|
||||
/** Provider + model pickers for the one-shot title model. */
|
||||
export const TitleModelPicker: React.FC<TitleModelPickerProps> = ({
|
||||
providers,
|
||||
activeProviderId,
|
||||
activeModelId,
|
||||
agentProviderMap,
|
||||
agentModelMap,
|
||||
value,
|
||||
onChange,
|
||||
t,
|
||||
}) => {
|
||||
// Hold a newly chosen provider locally until it has a concrete non-empty
|
||||
// modelId so incomplete configs are never persisted to storage.
|
||||
const [pendingProviderId, setPendingProviderId] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
setPendingProviderId(null);
|
||||
}, [value]);
|
||||
|
||||
const vm = buildTitleModelPickerViewModel({
|
||||
providers,
|
||||
activeProviderId,
|
||||
activeModelId,
|
||||
agentProviderMap,
|
||||
agentModelMap,
|
||||
value,
|
||||
pendingProviderId,
|
||||
t,
|
||||
});
|
||||
|
||||
const catalog = useProviderModelCatalog(
|
||||
vm.selectedEnabledProvider,
|
||||
Boolean(vm.selectedEnabledProvider),
|
||||
);
|
||||
|
||||
if (vm.mode === "none") {
|
||||
return (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{t("ai.chatHistory.titleModel.none")}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
const baseModelOptions = catalog.models.map((model) => ({
|
||||
value: model.id,
|
||||
label: model.name || model.id,
|
||||
}));
|
||||
const modelOptions = vm.activeModelId
|
||||
&& !baseModelOptions.some((option) => option.value === vm.activeModelId)
|
||||
? [{ value: vm.activeModelId, label: vm.activeModelId }, ...baseModelOptions]
|
||||
: baseModelOptions;
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap items-center justify-end gap-2">
|
||||
<Select
|
||||
value={vm.providerSelectValue}
|
||||
options={vm.providerOptions}
|
||||
onChange={(nextValue) => {
|
||||
if (nextValue === TITLE_MODEL_INHERIT_VALUE) {
|
||||
setPendingProviderId(null);
|
||||
onChange(null);
|
||||
return;
|
||||
}
|
||||
const provider = providers.find((item) => item.id === nextValue && Boolean(item.enabled));
|
||||
if (!provider) return;
|
||||
const fallbackModelId = (provider.defaultModel ?? "").trim()
|
||||
|| seedProviderModelCatalog(provider).models[0]?.id
|
||||
|| "";
|
||||
if (fallbackModelId) {
|
||||
setPendingProviderId(null);
|
||||
onChange({ providerId: provider.id, modelId: fallbackModelId });
|
||||
} else {
|
||||
setPendingProviderId(provider.id);
|
||||
}
|
||||
}}
|
||||
className="w-48"
|
||||
placeholder={t("ai.chatHistory.titleModel.providerPlaceholder")}
|
||||
/>
|
||||
{vm.mode === "inherit" ? (
|
||||
vm.inheritedLabel ? (
|
||||
<span
|
||||
data-section="ai-title-model-inherited"
|
||||
className="text-xs text-muted-foreground max-w-48 truncate"
|
||||
title={vm.inheritedLabel}
|
||||
>
|
||||
{vm.inheritedLabel}
|
||||
</span>
|
||||
) : null
|
||||
) : (
|
||||
<Select
|
||||
value={vm.activeModelId}
|
||||
options={modelOptions}
|
||||
onChange={(modelId) => {
|
||||
if (!vm.selectedEnabledProvider || !modelId) return;
|
||||
setPendingProviderId(null);
|
||||
onChange({ providerId: vm.selectedEnabledProvider.id, modelId });
|
||||
}}
|
||||
className="w-48"
|
||||
disabled={!vm.selectedEnabledProvider || (catalog.loading && !catalog.fetched)}
|
||||
placeholder={t("ai.chatHistory.titleModel.modelPlaceholder")}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,114 @@
|
||||
import { resolveCattyEffectiveModel, type TitleModelConfig } from "../../../../domain/aiSessionTitle";
|
||||
import type { ProviderConfig } from "../../../../infrastructure/ai/types";
|
||||
|
||||
export const TITLE_MODEL_INHERIT_VALUE = "__netcatty_inherit_catty__";
|
||||
|
||||
export interface TitleModelPickerOption {
|
||||
value: string;
|
||||
label: string;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export interface TitleModelPickerViewModel {
|
||||
mode: "none" | "inherit" | "explicit";
|
||||
providerSelectValue: string;
|
||||
providerOptions: TitleModelPickerOption[];
|
||||
selectedEnabledProvider: ProviderConfig | undefined;
|
||||
activeModelId: string;
|
||||
inheritedLabel: string | null;
|
||||
}
|
||||
|
||||
/** Pure derivation for TitleModelPicker options and inherited summary. */
|
||||
export function buildTitleModelPickerViewModel(input: {
|
||||
providers: readonly ProviderConfig[];
|
||||
activeProviderId: string;
|
||||
activeModelId: string;
|
||||
agentProviderMap: Readonly<Record<string, string>>;
|
||||
agentModelMap: Readonly<Record<string, string>>;
|
||||
value: TitleModelConfig | null;
|
||||
pendingProviderId?: string | null;
|
||||
t: (key: string) => string;
|
||||
}): TitleModelPickerViewModel {
|
||||
const {
|
||||
providers,
|
||||
activeProviderId,
|
||||
activeModelId,
|
||||
agentProviderMap,
|
||||
agentModelMap,
|
||||
value,
|
||||
pendingProviderId = null,
|
||||
t,
|
||||
} = input;
|
||||
|
||||
const enabledProviders = providers.filter((provider) => Boolean(provider.enabled));
|
||||
const inherited = resolveCattyEffectiveModel({
|
||||
providers,
|
||||
activeProviderId,
|
||||
activeModelId,
|
||||
agentProviderMap,
|
||||
agentModelMap,
|
||||
});
|
||||
const inheritedIsUsable = Boolean(
|
||||
inherited.provider && inherited.provider.enabled && inherited.modelId,
|
||||
);
|
||||
const inheritedLabel = inheritedIsUsable && inherited.provider
|
||||
? `${inherited.provider.name} · ${inherited.modelId}`
|
||||
: null;
|
||||
|
||||
const targetProviderId = pendingProviderId ?? value?.providerId ?? null;
|
||||
if (!targetProviderId && enabledProviders.length === 0) {
|
||||
return {
|
||||
mode: "none",
|
||||
providerSelectValue: TITLE_MODEL_INHERIT_VALUE,
|
||||
providerOptions: [],
|
||||
selectedEnabledProvider: undefined,
|
||||
activeModelId: "",
|
||||
inheritedLabel: null,
|
||||
};
|
||||
}
|
||||
|
||||
const providerOptions: TitleModelPickerOption[] = [
|
||||
{
|
||||
value: TITLE_MODEL_INHERIT_VALUE,
|
||||
label: t("ai.chatHistory.titleModel.useCurrentCatty"),
|
||||
},
|
||||
...enabledProviders.map((provider) => ({
|
||||
value: provider.id,
|
||||
label: provider.name,
|
||||
})),
|
||||
];
|
||||
|
||||
if (!targetProviderId) {
|
||||
return {
|
||||
mode: "inherit",
|
||||
providerSelectValue: TITLE_MODEL_INHERIT_VALUE,
|
||||
providerOptions,
|
||||
selectedEnabledProvider: undefined,
|
||||
activeModelId: "",
|
||||
inheritedLabel,
|
||||
};
|
||||
}
|
||||
|
||||
const selectedEnabledProvider = enabledProviders.find((provider) => provider.id === targetProviderId);
|
||||
if (!selectedEnabledProvider) {
|
||||
const savedProvider = providers.find((provider) => provider.id === targetProviderId);
|
||||
providerOptions.push({
|
||||
value: targetProviderId,
|
||||
label: `${savedProvider?.name ?? targetProviderId} (${t("ai.chatHistory.titleModel.unavailable")})`,
|
||||
disabled: true,
|
||||
});
|
||||
}
|
||||
|
||||
const resolvedModelId = pendingProviderId
|
||||
? ""
|
||||
: (value?.modelId?.trim() || "");
|
||||
|
||||
return {
|
||||
mode: "explicit",
|
||||
providerSelectValue: targetProviderId,
|
||||
providerOptions,
|
||||
selectedEnabledProvider,
|
||||
activeModelId: resolvedModelId,
|
||||
inheritedLabel,
|
||||
};
|
||||
}
|
||||
@@ -12,7 +12,10 @@ import { netcattyBridge } from "../../../infrastructure/services/netcattyBridge"
|
||||
import { getFileExtension, getLanguageId, FileOpenerType, SystemAppInfo } from "../../../lib/sftpFileUtils";
|
||||
import { isNavigableDirectory } from "../utils";
|
||||
import { resolveDownloadSourceSnapshot } from "../../../application/state/sftp/downloadSourceSnapshot";
|
||||
import { getSftpDownloadDialogDirectoryOptions } from "../../../application/state/sftp/downloadLocation";
|
||||
import {
|
||||
getSftpDownloadDialogDirectoryOptions,
|
||||
rememberSftpDownloadDirectory,
|
||||
} from "../../../application/state/sftp/downloadLocation";
|
||||
import { reportSftpUploadResults } from "../reportSftpUploadResults";
|
||||
import { editorTabStore } from "../../../application/state/editorTabStore";
|
||||
import { popOutEditorTab } from "../../../application/state/editorWindowClient";
|
||||
@@ -469,6 +472,7 @@ export const useSftpViewFileOps = ({
|
||||
getSftpDownloadDialogDirectoryOptions(),
|
||||
);
|
||||
if (!destination) return null;
|
||||
rememberSftpDownloadDirectory(destination);
|
||||
localDirectory = destination;
|
||||
continue;
|
||||
}
|
||||
@@ -547,6 +551,7 @@ export const useSftpViewFileOps = ({
|
||||
getSftpDownloadDialogDirectoryOptions(),
|
||||
);
|
||||
if (!selectedDirectory) return;
|
||||
rememberSftpDownloadDirectory(selectedDirectory);
|
||||
|
||||
// The picker may stay open while the remote entry changes again.
|
||||
const selectedSnapshot = await resolveDownloadSourceSnapshot(
|
||||
@@ -601,6 +606,7 @@ export const useSftpViewFileOps = ({
|
||||
getSftpDownloadDialogDirectoryOptions(),
|
||||
);
|
||||
if (!targetPath) return;
|
||||
rememberSftpDownloadDirectory(getParentPath(targetPath));
|
||||
|
||||
const selectedSnapshot = await resolveDownloadSourceSnapshot(
|
||||
statSftp,
|
||||
@@ -793,6 +799,7 @@ export const useSftpViewFileOps = ({
|
||||
getSftpDownloadDialogDirectoryOptions(),
|
||||
);
|
||||
if (!selectedDirectory) return;
|
||||
rememberSftpDownloadDirectory(selectedDirectory);
|
||||
|
||||
if (parents.every((parent) => parent === parents[0]) && files.every((file) => file.type !== "symlink")) {
|
||||
try {
|
||||
|
||||
@@ -5,6 +5,10 @@ import { act, create, type ReactTestRenderer } from "react-test-renderer";
|
||||
import type { SftpFileEntry } from "../../types";
|
||||
import type { SftpStateApi } from "../../application/state/useSftpState";
|
||||
import { useSftpViewFileOps } from "./hooks/useSftpViewFileOps";
|
||||
import {
|
||||
STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR,
|
||||
STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR,
|
||||
} from "../../infrastructure/config/storageKeys";
|
||||
|
||||
const file = (
|
||||
name: string, size: number, type: SftpFileEntry["type"] = "file",
|
||||
@@ -213,7 +217,7 @@ test("duplicate-name downloads keep captured paths and stop when the source conn
|
||||
}
|
||||
});
|
||||
|
||||
test("download dialogs open in the configured default download folder", async () => {
|
||||
test("download dialogs remember confirmed choices without changing settings or remembering uploads", async () => {
|
||||
const globals = globalThis as typeof globalThis & {
|
||||
IS_REACT_ACT_ENVIRONMENT?: boolean;
|
||||
localStorage?: Storage;
|
||||
@@ -221,6 +225,8 @@ test("download dialogs open in the configured default download folder", async ()
|
||||
const previousAct = globals.IS_REACT_ACT_ENVIRONMENT;
|
||||
const hadLocalStorage = Object.prototype.hasOwnProperty.call(globals, "localStorage");
|
||||
const previousLocalStorage = globals.localStorage;
|
||||
const previousWindow = Object.getOwnPropertyDescriptor(globals, "window");
|
||||
Object.defineProperty(globals, "window", { configurable: true, value: { confirm: () => true } });
|
||||
globals.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
const store = new Map<string, string>();
|
||||
Object.defineProperty(globals, "localStorage", {
|
||||
@@ -243,13 +249,24 @@ test("download dialogs open in the configured default download folder", async ()
|
||||
]);
|
||||
const saveOptions: unknown[] = [];
|
||||
const directoryOptions: unknown[] = [];
|
||||
let saveResult: string | null | undefined;
|
||||
let directoryResult: string | null = "/picked-folder";
|
||||
let directoryResults: string[] = [];
|
||||
let packedConflict = false;
|
||||
const connection = { id: "conn-1", hostId: "host-1", hostLabel: "Host", currentPath: "/remote", isLocal: false };
|
||||
const pane = { connection, filenameEncoding: "auto" };
|
||||
const sftpRef = { current: {
|
||||
leftPane: pane, rightPane: pane,
|
||||
joinPath: (parent: string, name: string) => `${parent}/${name}`,
|
||||
tryPackedDownload: async () => "regular",
|
||||
tryPackedDownload: async () => {
|
||||
if (packedConflict) {
|
||||
packedConflict = false;
|
||||
return "conflict";
|
||||
}
|
||||
return "regular";
|
||||
},
|
||||
downloadToLocal: async () => "completed",
|
||||
uploadExternalFolderPath: async () => [],
|
||||
} as unknown as SftpStateApi };
|
||||
let ops: ReturnType<typeof useSftpViewFileOps> | undefined;
|
||||
let renderer: ReactTestRenderer | undefined;
|
||||
@@ -261,8 +278,14 @@ test("download dialogs open in the configured default download folder", async ()
|
||||
getOpenerForFileRef: { current: () => null },
|
||||
setOpenerForExtension: () => undefined,
|
||||
t: (key) => key,
|
||||
showSaveDialog: async (name, _filters, options) => { saveOptions.push(options); return `/picked/${name}`; },
|
||||
selectDirectory: async (_title, _defaultPath, options) => { directoryOptions.push(options); return "/picked"; },
|
||||
showSaveDialog: async (name, _filters, options) => {
|
||||
saveOptions.push(options);
|
||||
return saveResult === undefined ? `/picked/${name}` : saveResult;
|
||||
},
|
||||
selectDirectory: async (_title, _defaultPath, options) => {
|
||||
directoryOptions.push(options);
|
||||
return directoryResults.length ? directoryResults.shift()! : directoryResult;
|
||||
},
|
||||
getSftpIdForConnection: () => "sftp-1",
|
||||
statSftp: async (_id, path) => types.get(path) ?? null as unknown as SftpStatResult,
|
||||
listSftp: async () => [],
|
||||
@@ -278,18 +301,60 @@ test("download dialogs open in the configured default download folder", async ()
|
||||
await act(async () => { await single(file("a.txt", 1)); });
|
||||
assert.deepEqual(saveOptions.at(-1), { fallbackDirectory: "downloads" },
|
||||
"unset preference falls back to the system Downloads folder");
|
||||
assert.equal(store.get(STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR), "/picked", "Save As remembers the parent directory");
|
||||
await act(async () => { await single(file("b.txt", 1)); });
|
||||
assert.deepEqual(saveOptions.at(-1), { preferredDirectory: "/picked", fallbackDirectory: "downloads" },
|
||||
"the next Save As opens in the last chosen folder");
|
||||
|
||||
store.set("netcatty_sftp_default_download_dir_v1", "/home/me/server-files");
|
||||
store.delete(STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR);
|
||||
store.set(STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR, "/home/me/server-files");
|
||||
const configured = { preferredDirectory: "/home/me/server-files", fallbackDirectory: "downloads" };
|
||||
await act(async () => { await single(file("a.txt", 1)); });
|
||||
assert.deepEqual(saveOptions.at(-1), configured, "Save As opens in the configured folder");
|
||||
const remembered = (preferredDirectory: string) => ({
|
||||
preferredDirectory, secondaryDirectory: "/home/me/server-files", fallbackDirectory: "downloads",
|
||||
});
|
||||
await act(async () => { await single(file("dir", 0, "directory")); });
|
||||
assert.deepEqual(directoryOptions.at(-1), configured, "folder downloads use the configured folder");
|
||||
assert.deepEqual(directoryOptions.at(-1), remembered("/picked"), "folder downloads prefer the last Save As folder");
|
||||
assert.equal(store.get(STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR), "/picked-folder");
|
||||
directoryResult = "/picked-batch";
|
||||
await act(async () => { await batch([file("a.txt", 1), file("b.txt", 1)]); });
|
||||
assert.deepEqual(directoryOptions.at(-1), configured, "multi-select downloads use the configured folder");
|
||||
assert.deepEqual(directoryOptions.at(-1), remembered("/picked-folder"), "multi-select prefers the last folder pick");
|
||||
assert.equal(store.get(STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR), "/picked-batch");
|
||||
|
||||
packedConflict = true;
|
||||
directoryResults = ["/initial-retry", "/picked-retry"];
|
||||
await act(async () => { await single(file("dir", 0, "directory")); });
|
||||
assert.deepEqual(directoryOptions.slice(-2), [remembered("/picked-batch"), remembered("/initial-retry")],
|
||||
"packed-download retries see the preceding confirmed folder");
|
||||
assert.equal(store.get(STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR), "/picked-retry");
|
||||
|
||||
for (const cancelled of [null, ""]) {
|
||||
saveResult = cancelled;
|
||||
directoryResult = cancelled;
|
||||
await act(async () => {
|
||||
await single(file("a.txt", 1));
|
||||
await single(file("dir", 0, "directory"));
|
||||
await batch([file("a.txt", 1), file("b.txt", 1)]);
|
||||
});
|
||||
assert.equal(store.get(STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR), "/picked-retry", "cancelled or empty picks preserve memory");
|
||||
}
|
||||
|
||||
directoryResult = "/upload-only";
|
||||
await act(async () => { await ops!.onUploadExternalFolderLeft(); });
|
||||
assert.equal(directoryOptions.at(-1), undefined, "upload picker receives no download directory hints");
|
||||
assert.equal(store.get(STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR), "/picked-retry", "uploads do not change download memory");
|
||||
|
||||
saveResult = "C:\\picked\\a.txt";
|
||||
await act(async () => { await single(file("a.txt", 1)); });
|
||||
assert.deepEqual(saveOptions.at(-1), remembered("/picked-retry"));
|
||||
assert.equal(store.get(STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR), "C:\\picked", "Save As handles Windows parent paths");
|
||||
assert.equal(store.get(STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR), "/home/me/server-files", "the Settings default is preserved");
|
||||
} finally {
|
||||
await act(async () => { renderer?.unmount(); });
|
||||
globals.IS_REACT_ACT_ENVIRONMENT = previousAct;
|
||||
if (previousWindow) Object.defineProperty(globals, "window", previousWindow);
|
||||
else Reflect.deleteProperty(globals, "window");
|
||||
if (hadLocalStorage) {
|
||||
Object.defineProperty(globals, "localStorage", { configurable: true, writable: true, value: previousLocalStorage });
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import path from 'node:path';
|
||||
import test from 'node:test';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { buildSync } from 'esbuild';
|
||||
import { JSDOM } from 'jsdom';
|
||||
|
||||
test('Ctrl+N opens AddToWorkspaceDialog inside a workspace and passes through to standalone PTY across terminal modes', async () => {
|
||||
const root = fileURLToPath(new URL('../../..', import.meta.url));
|
||||
const bundle = buildSync({
|
||||
stdin: {
|
||||
contents: `
|
||||
export { createXTermRuntime } from "./components/terminal/runtime/createXTermRuntime";
|
||||
export { DEFAULT_TERMINAL_SETTINGS } from "./domain/models/terminal";
|
||||
export { DEFAULT_KEY_BINDINGS, matchesKeyBinding } from "./domain/models/keyBindings";
|
||||
export { executeHotkeyActionImpl, handleGlobalHotkeyKeyDownImpl } from "./application/app/AppHandlers";
|
||||
`,
|
||||
loader: 'ts',
|
||||
resolveDir: root,
|
||||
},
|
||||
bundle: true,
|
||||
format: 'iife',
|
||||
globalName: 'runtimeTest',
|
||||
platform: 'browser',
|
||||
write: false,
|
||||
alias: {
|
||||
'node:diagnostics_channel': path.join(root, 'infrastructure/shims/nodeDiagnosticsChannel.ts'),
|
||||
diagnostics_channel: path.join(root, 'infrastructure/shims/nodeDiagnosticsChannel.ts'),
|
||||
},
|
||||
define: { 'import.meta.env.DEV': 'false', 'import.meta.env.PROD': 'true', 'import.meta': '{}' },
|
||||
}).outputFiles[0].text;
|
||||
|
||||
const dom = new JSDOM('<body/>', {
|
||||
url: 'http://localhost',
|
||||
runScripts: 'outside-only',
|
||||
pretendToBeVisual: true,
|
||||
});
|
||||
Object.assign(dom.window, { structuredClone });
|
||||
|
||||
try {
|
||||
dom.window.eval(`
|
||||
Object.defineProperty(navigator, 'platform', { configurable: true, value: 'Win32' });
|
||||
Object.defineProperty(navigator, 'userAgent', {
|
||||
configurable: true,
|
||||
value: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/148.0.0.0 Safari/537.36',
|
||||
});
|
||||
window.matchMedia = () => ({ matches: false, addListener(){}, removeListener(){}, addEventListener(){}, removeEventListener(){} });
|
||||
window.ResizeObserver = window.IntersectionObserver = class { observe(){} unobserve(){} disconnect(){} };
|
||||
HTMLCanvasElement.prototype.getContext = function(type) {
|
||||
if (type !== '2d') return null;
|
||||
return new Proxy(
|
||||
{
|
||||
canvas: this,
|
||||
measureText: () => ({ width: 8, fontBoundingBoxAscent: 12, fontBoundingBoxDescent: 3 }),
|
||||
getImageData: () => ({ data: new Uint8ClampedArray(4) }),
|
||||
createLinearGradient: () => ({ addColorStop(){} }),
|
||||
},
|
||||
{ get: (target, key) => (key in target ? target[key] : () => {}) },
|
||||
);
|
||||
};
|
||||
`);
|
||||
dom.window.eval(bundle);
|
||||
|
||||
const results = await dom.window.eval(`(async () => {
|
||||
const {
|
||||
createXTermRuntime,
|
||||
DEFAULT_TERMINAL_SETTINGS,
|
||||
DEFAULT_KEY_BINDINGS,
|
||||
matchesKeyBinding,
|
||||
executeHotkeyActionImpl,
|
||||
handleGlobalHotkeyKeyDownImpl,
|
||||
} = runtimeTest;
|
||||
const ref = (current) => ({ current });
|
||||
|
||||
let activeTabId = 'session-1';
|
||||
const dialogCalls = [];
|
||||
const workspaces = [{ id: 'workspace-1', title: 'Workspace 1' }];
|
||||
const sessions = [{ id: 'session-1' }, { id: 'ws-sess', workspaceId: 'workspace-1' }];
|
||||
|
||||
const onGlobalKeyDown = (e) => {
|
||||
handleGlobalHotkeyKeyDownImpl(
|
||||
() => ({
|
||||
HOTKEY_DEBUG: false,
|
||||
closeTabKeyStr: 'Ctrl + W',
|
||||
hotkeyScheme: 'pc',
|
||||
keyBindings: DEFAULT_KEY_BINDINGS,
|
||||
matchesKeyBinding,
|
||||
executeHotkeyAction: (action, event) =>
|
||||
executeHotkeyActionImpl(
|
||||
() => ({
|
||||
activeTabStore: { getActiveTabId: () => activeTabId },
|
||||
editorTabs: [],
|
||||
orderedTabs: ['session-1', 'workspace-1'],
|
||||
sessions,
|
||||
settings: { showSftpTab: true, shellOnlyTabNumberShortcuts: false },
|
||||
setAddToWorkspaceDialog: (value) => dialogCalls.push(value),
|
||||
toEditorTabId: (id) => 'editor:' + id,
|
||||
workspaces,
|
||||
}),
|
||||
action,
|
||||
event,
|
||||
),
|
||||
}),
|
||||
e,
|
||||
);
|
||||
};
|
||||
window.addEventListener('keydown', onGlobalKeyDown, true);
|
||||
|
||||
const modes = [
|
||||
{ name: 'legacy', kitty: false, setup: '' },
|
||||
{ name: 'netcatty-kitty', kitty: true, setup: '\\x1b[>1u' },
|
||||
{ name: 'win32', kitty: false, setup: '\\x1b[?9001h' },
|
||||
];
|
||||
|
||||
const modeResults = [];
|
||||
try {
|
||||
for (const mode of modes) {
|
||||
const container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
const writes = [];
|
||||
const host = { id: 'h-' + mode.name, label: mode.name, hostname: 'localhost', protocol: 'local', sshInputCompatibility: false };
|
||||
const runtime = createXTermRuntime({
|
||||
container,
|
||||
host,
|
||||
getHost: () => host,
|
||||
sessionId: 'session-1',
|
||||
sessionRef: ref('session-1'),
|
||||
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: { writeToSession: (_id, data) => writes.push(data), resizeSession(){}, openExternalAvailable: false },
|
||||
hotkeySchemeRef: ref('pc'),
|
||||
keyBindingsRef: ref(DEFAULT_KEY_BINDINGS),
|
||||
onHotkeyActionRef: ref(undefined),
|
||||
terminalContextActionsRef: ref({}),
|
||||
snippetsRef: ref([]),
|
||||
onSnippetShortkeyRef: ref(undefined),
|
||||
isBroadcastEnabledRef: ref(false),
|
||||
onBroadcastInputRef: ref(undefined),
|
||||
commandBufferRef: ref(''),
|
||||
requestSearchFocus: () => {},
|
||||
kittyKeyboardProtocolEnabled: mode.kitty,
|
||||
});
|
||||
try {
|
||||
if (mode.setup) {
|
||||
await new Promise((resolve) => runtime.term.write(mode.setup, resolve));
|
||||
}
|
||||
|
||||
// 1. Standalone terminal: Ctrl+N passes through to the PTY.
|
||||
activeTabId = 'session-1';
|
||||
writes.length = 0;
|
||||
dialogCalls.length = 0;
|
||||
const standaloneEvent = new KeyboardEvent('keydown', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
key: 'n',
|
||||
code: 'KeyN',
|
||||
keyCode: 78,
|
||||
ctrlKey: true,
|
||||
});
|
||||
runtime.term.textarea.dispatchEvent(standaloneEvent);
|
||||
runtime.term.textarea.dispatchEvent(new KeyboardEvent('keyup', {
|
||||
bubbles: true,
|
||||
key: 'n',
|
||||
code: 'KeyN',
|
||||
keyCode: 78,
|
||||
ctrlKey: true,
|
||||
}));
|
||||
const standalone = {
|
||||
dialogCalls: [...dialogCalls],
|
||||
writes: [...writes],
|
||||
};
|
||||
|
||||
// 2. Active workspace: Ctrl+N opens AddToWorkspaceDialog and leaks zero PTY bytes.
|
||||
activeTabId = 'workspace-1';
|
||||
writes.length = 0;
|
||||
dialogCalls.length = 0;
|
||||
const workspaceEvent = new KeyboardEvent('keydown', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
key: 'n',
|
||||
code: 'KeyN',
|
||||
keyCode: 78,
|
||||
ctrlKey: true,
|
||||
});
|
||||
runtime.term.textarea.dispatchEvent(workspaceEvent);
|
||||
const workspace = {
|
||||
prevented: workspaceEvent.defaultPrevented,
|
||||
dialogCalls: [...dialogCalls],
|
||||
writes: [...writes],
|
||||
};
|
||||
|
||||
modeResults.push({ mode: mode.name, standalone, workspace });
|
||||
} finally {
|
||||
runtime.dispose();
|
||||
container.remove();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
window.removeEventListener('keydown', onGlobalKeyDown, true);
|
||||
}
|
||||
return JSON.stringify(modeResults);
|
||||
})()`);
|
||||
|
||||
const parsed = JSON.parse(results);
|
||||
for (const entry of parsed) {
|
||||
assert.deepEqual(entry.standalone.dialogCalls, [], `${entry.mode}: standalone must not open dialog`);
|
||||
if (entry.mode === 'legacy') {
|
||||
assert.deepEqual(entry.standalone.writes, ['\x0e'], 'legacy standalone must emit Ctrl+N (\\x0e)');
|
||||
} else if (entry.mode === 'netcatty-kitty') {
|
||||
assert.deepEqual(entry.standalone.writes, ['\x1b[110;5u'], 'kitty standalone must emit Kitty Ctrl+N');
|
||||
} else if (entry.mode === 'win32') {
|
||||
assert.ok(entry.standalone.writes.length > 0, 'win32 standalone must emit Win32 Ctrl+N record');
|
||||
}
|
||||
|
||||
assert.equal(entry.workspace.prevented, true, `${entry.mode}: workspace Ctrl+N must be prevented`);
|
||||
assert.deepEqual(entry.workspace.dialogCalls, [{ mode: 'append', workspaceId: 'workspace-1' }]);
|
||||
assert.deepEqual(entry.workspace.writes, [], `${entry.mode}: workspace Ctrl+N must emit zero PTY bytes`);
|
||||
}
|
||||
} finally {
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
@@ -620,6 +620,19 @@ const AIChatPanelsHostInner: React.FC<AIChatPanelsHostProps> = ({
|
||||
return next;
|
||||
}, [workspaces, appTerminalSessions]);
|
||||
|
||||
// Rebind resolves the destination workspace title from live state so the
|
||||
// chat's name snapshot always reflects its actual binding.
|
||||
const rebindSessionScopeWithSnapshot = useCallback((
|
||||
sessionId: string,
|
||||
scope: { type: 'terminal' | 'workspace'; targetId: string; hostIds?: string[] },
|
||||
) => aiConfig.rebindSessionScope(
|
||||
sessionId,
|
||||
scope,
|
||||
scope.type === 'workspace'
|
||||
? (workspaces ?? []).find((workspace) => workspace.id === scope.targetId)?.title
|
||||
: undefined,
|
||||
), [aiConfig, workspaces]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!pendingTerminalSelection) return;
|
||||
if (consumedTerminalSelectionRequestIds.has(pendingTerminalSelection.requestId)) {
|
||||
@@ -738,7 +751,8 @@ const AIChatPanelsHostInner: React.FC<AIChatPanelsHostProps> = ({
|
||||
undoLastTurnInSession={aiConfig.undoLastTurnInSession}
|
||||
deleteSession={aiConfig.deleteSession}
|
||||
updateSessionTitle={aiConfig.updateSessionTitle}
|
||||
rebindSessionScope={aiConfig.rebindSessionScope}
|
||||
autoTitleSession={aiConfig.autoTitleSession}
|
||||
rebindSessionScope={rebindSessionScopeWithSnapshot}
|
||||
exportSessionsBackup={aiConfig.exportSessionsBackup}
|
||||
importSessionsBackup={aiConfig.importSessionsBackup}
|
||||
updateSessionExternalSessionId={aiConfig.updateSessionExternalSessionId}
|
||||
@@ -1871,7 +1885,7 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
|
||||
identities={identities}
|
||||
knownHosts={knownHosts}
|
||||
isVisible={isVisible}
|
||||
isFocused={isFocusedPane}
|
||||
isFocused={paneState.mode === 'split' ? isFocusedPane : true}
|
||||
inWorkspace={keepsWorkspacePresentation}
|
||||
onStatusChange={handleRemoteDesktopStatusChange}
|
||||
onCloseSession={onCloseSession}
|
||||
|
||||
@@ -52,6 +52,33 @@ test("visible SFTP host override can disable command cwd probing", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("turning Follow on refreshes a panel host snapshot captured before the toggle", () => {
|
||||
assert.equal(shouldProbeCommandCwd({
|
||||
restoreTerminalCwd: false,
|
||||
visibleSftpHost: { id: 'ssh-host' },
|
||||
latestVisibleSftpHost: { id: 'ssh-host', sftpFollowTerminalCwd: true },
|
||||
globalSftpFollowTerminalCwd: false,
|
||||
}), true);
|
||||
});
|
||||
|
||||
test("turning Follow off overrides an enabled panel host snapshot", () => {
|
||||
assert.equal(shouldProbeCommandCwd({
|
||||
restoreTerminalCwd: false,
|
||||
visibleSftpHost: { id: 'ssh-host', sftpFollowTerminalCwd: true },
|
||||
latestVisibleSftpHost: { id: 'ssh-host', sftpFollowTerminalCwd: false },
|
||||
globalSftpFollowTerminalCwd: true,
|
||||
}), false);
|
||||
});
|
||||
|
||||
test("a different host preference cannot change the visible SFTP target's probe gate", () => {
|
||||
assert.equal(shouldProbeCommandCwd({
|
||||
restoreTerminalCwd: false,
|
||||
visibleSftpHost: { id: 'sftp-host', sftpFollowTerminalCwd: false },
|
||||
latestVisibleSftpHost: { id: 'terminal-host', sftpFollowTerminalCwd: true },
|
||||
globalSftpFollowTerminalCwd: true,
|
||||
}), false);
|
||||
});
|
||||
|
||||
test("schedules the post-command cwd probe for a connected local POSIX shell", () => {
|
||||
assert.equal(
|
||||
canScheduleCommandCwdProbe({ protocol: "local", status: "connected", shellType: "posix" }),
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
import { isTerminalSessionEligibleForSftpReuse } from "../../application/state/terminalConnectionReuse";
|
||||
import type { TerminalSession } from "../../domain/models";
|
||||
import { resolveHostFollowTerminalCwd, resolveSftpFollowTerminalCwdTargetHost } from "../../domain/sftpFollowTerminalCwd";
|
||||
import { mergeLatestFollowTerminalCwdHostSetting, resolveHostFollowTerminalCwd, resolveSftpFollowTerminalCwdTargetHost } from "../../domain/sftpFollowTerminalCwd";
|
||||
|
||||
type FollowTerminalCwdHost = {
|
||||
id?: string;
|
||||
sftpFollowTerminalCwd?: boolean;
|
||||
};
|
||||
|
||||
type ShouldProbeCommandCwdOptions = {
|
||||
restoreTerminalCwd: boolean;
|
||||
visibleSftpHost?: FollowTerminalCwdHost | null;
|
||||
latestVisibleSftpHost?: FollowTerminalCwdHost | null;
|
||||
sessionHost?: FollowTerminalCwdHost | null;
|
||||
globalSftpFollowTerminalCwd: boolean;
|
||||
restrictExtraSshChannels?: boolean;
|
||||
@@ -37,6 +39,7 @@ export const canScheduleCommandCwdProbe = (session: CommandCwdProbeSession): boo
|
||||
export const shouldProbeCommandCwd = ({
|
||||
restoreTerminalCwd,
|
||||
visibleSftpHost,
|
||||
latestVisibleSftpHost,
|
||||
sessionHost,
|
||||
globalSftpFollowTerminalCwd,
|
||||
restrictExtraSshChannels = false,
|
||||
@@ -45,7 +48,12 @@ export const shouldProbeCommandCwd = ({
|
||||
if (restoreTerminalCwd) return true;
|
||||
|
||||
if (!visibleSftpHost) return false;
|
||||
const followHost = resolveSftpFollowTerminalCwdTargetHost(visibleSftpHost, sessionHost);
|
||||
// The panel pins its connected host profile. Follow can change after that
|
||||
// snapshot was captured, so use the latest preference for the same host.
|
||||
const followHost = resolveSftpFollowTerminalCwdTargetHost(
|
||||
mergeLatestFollowTerminalCwdHostSetting(visibleSftpHost, latestVisibleSftpHost),
|
||||
sessionHost,
|
||||
);
|
||||
return resolveHostFollowTerminalCwd(
|
||||
followHost?.sftpFollowTerminalCwd,
|
||||
globalSftpFollowTerminalCwd,
|
||||
|
||||
@@ -1034,6 +1034,7 @@ interface WorkspaceTopTabProps {
|
||||
onTabDrop: (e: React.DragEvent, targetTabId: string) => void;
|
||||
onRenameWorkspace: (workspaceId: string) => void;
|
||||
onCopyWorkspace: (workspaceId: string) => void;
|
||||
onRequestAddToWorkspace?: (workspaceId: string) => void;
|
||||
onCloseWorkspace: (workspaceId: string) => void;
|
||||
onDetachSessionFromWorkspace?: (workspaceId: string, sessionId: string) => void;
|
||||
/** Sessions for Detach menu; each menu item applies live presentation itself. */
|
||||
@@ -1086,6 +1087,7 @@ export const WorkspaceTopTab: React.FC<WorkspaceTopTabProps> = memo(({
|
||||
onTabDrop,
|
||||
onRenameWorkspace,
|
||||
onCopyWorkspace,
|
||||
onRequestAddToWorkspace,
|
||||
onCloseWorkspace,
|
||||
onDetachSessionFromWorkspace,
|
||||
renderBulkCloseItems,
|
||||
@@ -1198,6 +1200,11 @@ export const WorkspaceTopTab: React.FC<WorkspaceTopTabProps> = memo(({
|
||||
<ContextMenuItem onClick={() => onCopyWorkspace(workspace.id)}>
|
||||
{t('tabs.copyTab')}
|
||||
</ContextMenuItem>
|
||||
{onRequestAddToWorkspace && (
|
||||
<ContextMenuItem onClick={() => onRequestAddToWorkspace(workspace.id)}>
|
||||
{t('tabs.addSessionToWorkspace')}
|
||||
</ContextMenuItem>
|
||||
)}
|
||||
{onDetachSessionFromWorkspace && detachSessions.map((session) => (
|
||||
<WorkspaceDetachSessionMenuItem
|
||||
key={session.id}
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
import { JSDOM } from 'jsdom';
|
||||
|
||||
import { loadLocaleMessages } from '../../application/i18n/messages.ts';
|
||||
import type { Workspace } from '../../types';
|
||||
|
||||
test('WorkspaceTopTab context menu invokes onRequestAddToWorkspace for the workspace and omits item when absent', async () => {
|
||||
await loadLocaleMessages('en');
|
||||
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', {
|
||||
pretendToBeVisual: true,
|
||||
url: 'http://localhost',
|
||||
});
|
||||
const window = dom.window;
|
||||
const previousGlobals = new Map<string, PropertyDescriptor | undefined>();
|
||||
const installGlobal = (key: string, value: unknown) => {
|
||||
previousGlobals.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value,
|
||||
});
|
||||
};
|
||||
|
||||
class ResizeObserverStub {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
}
|
||||
|
||||
installGlobal('window', window);
|
||||
installGlobal('document', window.document);
|
||||
installGlobal('navigator', window.navigator);
|
||||
installGlobal('localStorage', window.localStorage);
|
||||
installGlobal('HTMLElement', window.HTMLElement);
|
||||
installGlobal('HTMLInputElement', window.HTMLInputElement);
|
||||
installGlobal('HTMLTextAreaElement', window.HTMLTextAreaElement);
|
||||
installGlobal('Element', window.Element);
|
||||
installGlobal('SVGElement', window.SVGElement);
|
||||
installGlobal('Node', window.Node);
|
||||
installGlobal('NodeFilter', window.NodeFilter);
|
||||
installGlobal('MutationObserver', window.MutationObserver);
|
||||
installGlobal('CustomEvent', window.CustomEvent);
|
||||
installGlobal('DOMRect', window.DOMRect);
|
||||
installGlobal('Event', window.Event);
|
||||
installGlobal('KeyboardEvent', window.KeyboardEvent);
|
||||
installGlobal('MouseEvent', window.MouseEvent);
|
||||
installGlobal('getComputedStyle', window.getComputedStyle.bind(window));
|
||||
installGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => setTimeout(() => cb(Date.now()), 0) as unknown as number);
|
||||
installGlobal('cancelAnimationFrame', (id: number) => clearTimeout(id));
|
||||
installGlobal('ResizeObserver', ResizeObserverStub);
|
||||
installGlobal('IS_REACT_ACT_ENVIRONMENT', true);
|
||||
|
||||
const { default: React, act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { I18nProvider, useI18n } = await import('../../application/i18n/I18nProvider.tsx');
|
||||
const { WorkspaceTopTab } = await import('./TopTabItems.tsx');
|
||||
const { topTabsAreEqual } = await import('../TopTabs.tsx');
|
||||
|
||||
const rootNode = window.document.getElementById('root');
|
||||
assert.ok(rootNode);
|
||||
const root = createRoot(rootNode);
|
||||
|
||||
const workspace: Workspace = {
|
||||
id: 'ws-context-test',
|
||||
title: 'Prod Split',
|
||||
focusedSessionId: 's-1',
|
||||
root: { id: 'p-1', type: 'pane', sessionId: 's-1' },
|
||||
};
|
||||
const requested: string[] = [];
|
||||
const noop = () => {};
|
||||
|
||||
const Harness: React.FC<{ onRequestAddToWorkspace?: (workspaceId: string) => void }> = ({
|
||||
onRequestAddToWorkspace,
|
||||
}) => {
|
||||
const { t } = useI18n();
|
||||
return (
|
||||
<WorkspaceTopTab
|
||||
workspace={workspace}
|
||||
tabDoubleClickBehavior="copy"
|
||||
paneCount={1}
|
||||
workspaceSessionIds={['s-1']}
|
||||
workspaceSessions={[]}
|
||||
isBeingDragged={false}
|
||||
isDraggingForReorder={false}
|
||||
shiftStyle={{}}
|
||||
showDropIndicatorBefore={false}
|
||||
showDropIndicatorAfter={false}
|
||||
isHostDropTarget={false}
|
||||
onTabDragStart={noop}
|
||||
onTabDragEnd={noop}
|
||||
onTabDragOver={noop}
|
||||
onTabDragLeave={noop}
|
||||
onTabDrop={noop}
|
||||
onRenameWorkspace={noop}
|
||||
onCopyWorkspace={noop}
|
||||
onRequestAddToWorkspace={onRequestAddToWorkspace}
|
||||
onCloseWorkspace={noop}
|
||||
renderBulkCloseItems={() => null}
|
||||
t={t}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const openTabMenu = async () => {
|
||||
const tab = window.document.querySelector<HTMLElement>('[data-tab-id="ws-context-test"]');
|
||||
assert.ok(tab, 'workspace tab should render');
|
||||
await act(async () => {
|
||||
tab.dispatchEvent(new window.MouseEvent('contextmenu', {
|
||||
bubbles: true,
|
||||
button: 2,
|
||||
clientX: 20,
|
||||
clientY: 20,
|
||||
}));
|
||||
});
|
||||
};
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<I18nProvider locale="en">
|
||||
<Harness onRequestAddToWorkspace={(id) => requested.push(id)} />
|
||||
</I18nProvider>,
|
||||
);
|
||||
});
|
||||
|
||||
await openTabMenu();
|
||||
const addMenuItem = Array.from(window.document.querySelectorAll('[role="menuitem"]'))
|
||||
.find((item): item is HTMLElement => (item as Element).textContent?.includes('Add Session to Workspace') ?? false);
|
||||
assert.ok(addMenuItem, 'Add Session to Workspace menu item should render');
|
||||
|
||||
await act(async () => {
|
||||
addMenuItem.click();
|
||||
});
|
||||
assert.deepEqual(requested, ['ws-context-test']);
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<I18nProvider locale="en">
|
||||
<Harness />
|
||||
</I18nProvider>,
|
||||
);
|
||||
});
|
||||
|
||||
await openTabMenu();
|
||||
const absentItem = Array.from(window.document.querySelectorAll('[role="menuitem"]'))
|
||||
.find((item) => (item as Element).textContent?.includes('Add Session to Workspace'));
|
||||
assert.equal(absentItem, undefined, 'menu item should be omitted when callback is absent');
|
||||
|
||||
const topTabsSource = readFileSync(new URL('../TopTabs.tsx', import.meta.url), 'utf8');
|
||||
assert.match(topTabsSource, /<WorkspaceTopTab\b[\s\S]*?onRequestAddToWorkspace=\{onRequestAddToWorkspace\}/);
|
||||
const baseProps = {
|
||||
onRequestAddToWorkspace: noop,
|
||||
} as unknown as Parameters<typeof topTabsAreEqual>[0];
|
||||
const nextProps = {
|
||||
onRequestAddToWorkspace: () => {},
|
||||
} as unknown as Parameters<typeof topTabsAreEqual>[1];
|
||||
assert.equal(topTabsAreEqual(baseProps, baseProps), true);
|
||||
assert.equal(topTabsAreEqual(baseProps, nextProps), false);
|
||||
} finally {
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
await new Promise((resolve) => setTimeout(resolve, 25));
|
||||
});
|
||||
dom.window.close();
|
||||
for (const [key, descriptor] of previousGlobals) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else delete (globalThis as Record<string, unknown>)[key];
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
|
||||
const topTabsSource = readFileSync(new URL('./TopTabs.tsx', import.meta.url), 'utf8');
|
||||
const indexCss = readFileSync(new URL('../index.css', import.meta.url), 'utf8');
|
||||
const settingsStateDefaultsSource = readFileSync(new URL('../application/state/settingsStateDefaults.ts', import.meta.url), 'utf8');
|
||||
const settingsChromeStoreSource = readFileSync(new URL('../application/state/settingsChromeStore.ts', import.meta.url), 'utf8');
|
||||
const settingsAppearanceSource = readFileSync(new URL('./settings/tabs/SettingsAppearanceTab.tsx', import.meta.url), 'utf8');
|
||||
const settingsStateSource = readFileSync(new URL('../application/state/useSettingsState.ts', import.meta.url), 'utf8');
|
||||
const settingsStorageSyncSource = readFileSync(new URL('../application/state/settingsStorageSync.ts', import.meta.url), 'utf8');
|
||||
const storageKeysSource = readFileSync(new URL('../infrastructure/config/storageKeys.ts', import.meta.url), 'utf8');
|
||||
|
||||
test('Windows top-tabs keep the original drag area unless the user removes it', () => {
|
||||
assert.match(topTabsSource, /data-remove-top-tabs-drag-area=\{removeTopTabsDragArea \? 'true' : undefined\}/);
|
||||
assert.match(topTabsSource, /\{!removeTopTabsDragArea && \(\s*<div className="absolute inset-x-0 top-0 h-1 app-drag pointer-events-auto z-10" style=\{dragRegionStyle\} aria-hidden \/>/);
|
||||
assert.match(topTabsSource, /className="h-9 flex items-end gap-0 app-drag overflow-visible"/);
|
||||
assert.match(indexCss, /html\.platform-win32 \[data-top-tabs-root\]\[data-remove-top-tabs-drag-area="true"\] \[data-section="top-tabs-toolbar-row"\]\s*\{\s*height:\s*1\.75rem;/);
|
||||
});
|
||||
|
||||
test('removing the top-tabs drag area is off by default', () => {
|
||||
assert.match(settingsStateDefaultsSource, /DEFAULT_REMOVE_TOP_TABS_DRAG_AREA\s*=\s*false/);
|
||||
assert.match(settingsChromeStoreSource, /removeTopTabsDragArea: false/);
|
||||
});
|
||||
|
||||
test('top-tabs drag-area removal is available in Appearance settings', () => {
|
||||
assert.match(settingsAppearanceSource, /appearance-vault-remove-top-tabs-drag-area/);
|
||||
assert.match(settingsAppearanceSource, /settings\.vault\.removeTopTabsDragArea/);
|
||||
assert.match(settingsAppearanceSource, /<Toggle checked=\{removeTopTabsDragArea\} onChange=\{setRemoveTopTabsDragArea\} \/>/);
|
||||
});
|
||||
|
||||
test('top-tabs drag-area removal preference persists and syncs between windows', () => {
|
||||
assert.match(storageKeysSource, /STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA = ['"]netcatty_remove_top_tabs_drag_area_v1['"]/);
|
||||
assert.match(settingsStateSource, /localStorageAdapter\.readBoolean\(STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA\)/);
|
||||
assert.match(settingsStateSource, /localStorageAdapter\.writeBoolean\(STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA, enabled\)/);
|
||||
assert.match(settingsStorageSyncSource, /e\.key === STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA[\s\S]*?setRemoveTopTabsDragAreaState\(newValue\)/);
|
||||
});
|
||||
@@ -121,7 +121,11 @@ test('VaultNavSidebar supports drag-and-drop reorder (expanded + collapsed), sho
|
||||
setCollapsedExternally = setCollapsed;
|
||||
setPluginsExternally = setPluginIds;
|
||||
|
||||
const nav = useVaultNavConfig({ activePluginIds: pluginIds, pluginsLoading: false });
|
||||
const nav = useVaultNavConfig({
|
||||
activePluginIds: pluginIds,
|
||||
pluginsLoading: false,
|
||||
pluginsAvailable: true,
|
||||
});
|
||||
|
||||
const makeDescriptor = (id: VaultNavItemId): VaultNavItemDescriptor => ({
|
||||
id,
|
||||
|
||||
@@ -33,17 +33,17 @@
|
||||
<text x="85" y="85.0" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="end">8K</text>
|
||||
<text x="43" y="271.5" fill="#e6edf3" font-size="17" font-family="Handlee, cursive" font-weight="bold" transform="rotate(-90, 43, 271.5)">GitHub Stars</text>
|
||||
<text x="90.0" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Jan 2026</text>
|
||||
<text x="209.1" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Mar 2026</text>
|
||||
<text x="336.6" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">May 2026</text>
|
||||
<text x="464.1" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Jul 2026</text>
|
||||
<text x="593.6" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Sep 2026</text>
|
||||
<text x="721.1" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Nov 2026</text>
|
||||
<text x="206.6" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Mar 2026</text>
|
||||
<text x="331.4" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">May 2026</text>
|
||||
<text x="456.1" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Jul 2026</text>
|
||||
<text x="583.0" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Sep 2026</text>
|
||||
<text x="707.7" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Nov 2026</text>
|
||||
<text x="50%" y="525" fill="#e6edf3" font-size="17" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Date</text>
|
||||
<line x1="90" y1="80" x2="90" y2="463" stroke="#30363d" stroke-width="2.5" filter="url(#xkcdify)"/>
|
||||
<line x1="90" y1="463" x2="765" y2="463" stroke="#30363d" stroke-width="2.5" filter="url(#xkcdify)"/>
|
||||
<path d="M 90.0,462.3 C 90.3,462.3 91.7,462.0 92.1,461.9 C 92.8,461.8 93.5,461.7 94.2,461.5 C 94.9,461.4 95.6,461.2 96.3,461.1 C 97.0,461.0 97.7,461.1 98.4,461.0 C 99.1,461.0 99.8,461.0 100.4,460.9 C 101.1,460.9 101.8,460.8 102.5,460.8 C 103.2,460.7 103.6,460.7 104.6,460.7 C 105.7,460.6 107.8,460.6 108.8,460.5 C 109.9,460.5 110.2,460.4 110.9,460.4 C 111.6,460.4 112.3,460.4 113.0,460.4 C 113.7,460.4 114.4,460.3 115.1,460.3 C 115.8,460.3 116.5,460.3 117.2,460.3 C 117.9,460.2 118.6,460.2 119.3,460.1 C 120.0,460.1 120.7,460.1 121.3,459.9 C 122.0,459.8 122.7,459.6 123.4,459.3 C 124.1,459.0 124.8,458.3 125.5,458.1 C 126.2,457.8 126.9,458.0 127.6,457.9 C 128.3,457.9 129.0,457.9 129.7,457.8 C 130.4,457.8 130.8,457.8 131.8,457.7 C 132.8,457.7 134.6,457.7 136.0,457.7 C 137.4,457.7 139.1,457.6 140.2,457.6 C 141.2,457.6 141.5,457.5 142.2,457.5 C 142.9,457.5 143.6,457.4 144.3,457.4 C 145.0,457.4 145.7,457.3 146.4,457.3 C 147.1,457.3 147.8,457.3 148.5,457.3 C 149.2,457.2 149.6,457.2 150.6,457.2 C 151.6,457.2 153.0,457.1 154.8,457.1 C 156.5,457.1 159.3,457.1 161.1,457.1 C 162.8,457.0 163.1,457.1 165.2,457.0 C 167.3,457.0 171.8,456.9 173.6,456.8 C 175.3,456.8 174.6,456.8 175.7,456.8 C 176.7,456.8 178.1,456.8 179.9,456.7 C 181.6,456.7 182.6,456.7 186.1,456.6 C 189.6,456.6 198.0,456.5 200.8,456.5 C 203.5,456.5 202.2,456.5 202.8,456.4 C 203.5,456.4 203.9,457.0 204.9,456.4 C 206.0,455.8 208.1,455.3 209.1,452.9 C 210.2,450.4 210.5,443.8 211.2,441.7 C 211.9,439.6 212.6,440.8 213.3,440.5 C 214.0,440.1 214.7,439.9 215.4,439.7 C 216.1,439.5 216.8,439.3 217.5,439.2 C 218.2,439.0 218.9,439.0 219.6,438.9 C 220.3,438.8 221.0,438.7 221.7,438.6 C 222.4,438.6 223.0,438.6 223.7,438.6 C 224.4,438.5 225.1,438.3 225.8,438.2 C 226.5,438.2 227.2,438.2 227.9,438.1 C 228.6,438.0 229.3,437.7 230.0,437.6 C 230.7,437.5 231.4,437.5 232.1,437.4 C 232.8,437.4 233.2,437.2 234.2,437.1 C 235.2,437.0 237.3,437.0 238.4,437.0 C 239.4,436.9 239.8,436.9 240.5,436.8 C 241.2,436.8 241.9,436.8 242.6,436.7 C 243.3,436.6 243.9,436.4 244.6,436.2 C 245.3,436.1 246.0,436.7 246.7,435.9 C 247.4,435.1 248.1,432.3 248.8,431.4 C 249.5,430.5 250.2,430.6 250.9,430.4 C 251.6,430.3 252.3,430.5 253.0,430.4 C 253.7,430.3 254.4,430.0 255.1,429.7 C 255.8,429.5 256.5,429.3 257.2,428.9 C 257.9,428.4 258.6,427.6 259.3,427.1 C 260.0,426.6 260.7,426.1 261.4,425.7 C 262.1,425.3 262.8,425.0 263.5,424.8 C 264.1,424.6 264.8,424.5 265.5,424.4 C 266.2,424.3 266.9,424.3 267.6,424.2 C 268.3,424.1 269.0,423.9 269.7,423.8 C 270.4,423.7 271.1,423.7 271.8,423.7 C 272.5,423.6 273.2,423.6 273.9,423.5 C 274.6,423.4 275.3,423.4 276.0,423.1 C 276.7,422.7 277.4,421.8 278.1,421.3 C 278.8,420.9 279.5,420.8 280.2,420.4 C 280.9,420.1 281.6,420.8 282.3,419.4 C 283.0,418.0 283.7,413.8 284.3,412.2 C 285.0,410.6 285.7,410.3 286.4,409.6 C 287.1,408.9 287.8,408.5 288.5,408.0 C 289.2,407.6 289.9,407.1 290.6,406.7 C 291.3,406.4 292.0,406.1 292.7,405.8 C 293.4,405.6 294.1,405.6 294.8,405.4 C 295.5,405.2 296.2,405.0 296.9,404.7 C 297.6,404.4 298.3,404.0 299.0,403.8 C 299.7,403.6 300.4,403.6 301.1,403.3 C 301.8,403.1 302.5,402.7 303.2,402.4 C 303.9,402.2 304.6,401.9 305.2,401.7 C 305.9,401.5 306.6,401.3 307.3,401.2 C 308.0,401.1 308.7,401.0 309.4,400.9 C 310.1,400.8 310.8,400.6 311.5,400.5 C 312.2,400.3 312.9,400.2 313.6,400.0 C 314.3,399.8 315.0,399.7 315.7,399.4 C 316.4,399.1 317.1,398.6 317.8,398.3 C 318.5,398.1 319.2,398.0 319.9,397.8 C 320.6,397.7 321.3,397.6 322.0,397.5 C 322.7,397.4 323.4,397.3 324.1,397.2 C 324.8,397.1 325.4,397.0 326.1,396.9 C 326.8,396.9 327.5,396.9 328.2,396.8 C 328.9,396.7 329.6,396.5 330.3,396.3 C 331.0,396.1 331.7,395.6 332.4,395.4 C 333.1,395.1 333.8,394.7 334.5,394.5 C 335.2,394.3 335.9,394.3 336.6,394.2 C 337.3,394.1 338.0,394.0 338.7,393.8 C 339.4,393.6 340.1,393.1 340.8,393.0 C 341.5,392.8 342.2,392.8 342.9,392.7 C 343.6,392.6 344.3,392.4 345.0,392.2 C 345.7,392.1 346.3,391.9 347.0,391.8 C 347.7,391.6 348.4,391.4 349.1,391.2 C 349.8,391.1 350.5,391.0 351.2,390.8 C 351.9,390.6 352.6,390.3 353.3,390.1 C 354.0,389.9 354.7,389.8 355.4,389.6 C 356.1,389.4 356.8,389.1 357.5,388.8 C 358.2,388.6 358.9,388.3 359.6,388.1 C 360.3,387.9 361.0,387.9 361.7,387.5 C 362.4,387.2 363.1,386.3 363.8,386.0 C 364.5,385.7 365.2,385.6 365.9,385.5 C 366.5,385.4 367.2,385.4 367.9,385.3 C 368.6,385.3 369.3,385.1 370.0,385.0 C 370.7,384.9 371.4,385.1 372.1,384.8 C 372.8,384.5 373.5,383.5 374.2,383.1 C 374.9,382.8 375.6,382.8 376.3,382.6 C 377.0,382.4 377.7,382.0 378.4,381.8 C 379.1,381.6 379.8,381.7 380.5,381.6 C 381.2,381.4 381.9,380.9 382.6,380.8 C 383.3,380.6 384.0,380.6 384.7,380.5 C 385.4,380.4 386.1,380.5 386.7,380.3 C 387.4,380.1 388.1,379.9 388.8,379.4 C 389.5,379.0 390.2,378.1 390.9,377.6 C 391.6,377.1 392.3,376.9 393.0,376.6 C 393.7,376.3 394.4,376.2 395.1,375.6 C 395.8,374.9 396.5,373.5 397.2,372.8 C 397.9,372.0 398.6,371.7 399.3,371.3 C 400.0,370.9 400.7,370.8 401.4,370.2 C 402.1,369.6 402.8,368.2 403.5,367.5 C 404.2,366.9 404.9,366.8 405.6,366.5 C 406.3,366.1 407.0,365.8 407.6,365.4 C 408.3,365Line truncated
|
||||
<path d="M 90.0,462.3 C 90.3,462.3 91.7,462.0 92.1,461.9 C 92.8,461.8 93.5,461.7 94.2,461.5 C 94.9,461.4 95.6,461.2 96.3,461.1 C 97.0,461.0 97.7,461.1 98.4,461.0 C 99.1,461.0 99.8,461.0 100.4,460.9 C 101.1,460.9 101.8,460.8 102.5,460.8 C 103.2,460.7 103.6,460.7 104.6,460.7 C 105.7,460.6 107.8,460.6 108.8,460.5 C 109.9,460.5 110.2,460.4 110.9,460.4 C 111.6,460.4 112.3,460.4 113.0,460.4 C 113.7,460.4 114.4,460.3 115.1,460.3 C 115.8,460.3 116.5,460.3 117.2,460.3 C 117.9,460.2 118.6,460.2 119.3,460.1 C 120.0,460.1 120.7,460.1 121.3,459.9 C 122.0,459.8 122.7,459.6 123.4,459.3 C 124.1,459.0 124.8,458.3 125.5,458.1 C 126.2,457.8 126.9,458.0 127.6,457.9 C 128.3,457.9 129.0,457.9 129.7,457.8 C 130.4,457.8 130.8,457.8 131.8,457.7 C 132.8,457.7 134.6,457.7 136.0,457.7 C 137.4,457.7 139.1,457.6 140.2,457.6 C 141.2,457.6 141.5,457.5 142.2,457.5 C 142.9,457.5 143.6,457.4 144.3,457.4 C 145.0,457.4 145.7,457.3 146.4,457.3 C 147.1,457.3 147.8,457.3 148.5,457.3 C 149.2,457.2 149.6,457.2 150.6,457.2 C 151.6,457.2 153.0,457.1 154.8,457.1 C 156.5,457.1 159.3,457.1 161.1,457.1 C 162.8,457.0 163.1,457.1 165.2,457.0 C 167.3,457.0 171.8,456.9 173.6,456.8 C 175.3,456.8 174.6,456.8 175.7,456.8 C 176.7,456.8 178.1,456.8 179.9,456.7 C 181.6,456.7 182.6,456.7 186.1,456.6 C 189.6,456.6 198.0,456.5 200.8,456.5 C 203.5,456.5 202.2,456.5 202.8,456.4 C 203.5,456.4 203.9,457.0 204.9,456.4 C 206.0,455.8 208.1,455.3 209.1,452.9 C 210.2,450.4 210.5,443.8 211.2,441.7 C 211.9,439.6 212.6,440.8 213.3,440.5 C 214.0,440.1 214.7,439.9 215.4,439.7 C 216.1,439.5 216.8,439.3 217.5,439.2 C 218.2,439.0 218.9,439.0 219.6,438.9 C 220.3,438.8 221.0,438.7 221.7,438.6 C 222.4,438.6 223.0,438.6 223.7,438.6 C 224.4,438.5 225.1,438.3 225.8,438.2 C 226.5,438.2 227.2,438.2 227.9,438.1 C 228.6,438.0 229.3,437.7 230.0,437.6 C 230.7,437.5 231.4,437.5 232.1,437.4 C 232.8,437.4 233.2,437.2 234.2,437.1 C 235.2,437.0 237.3,437.0 238.4,437.0 C 239.4,436.9 239.8,436.9 240.5,436.8 C 241.2,436.8 241.9,436.8 242.6,436.7 C 243.3,436.6 243.9,436.4 244.6,436.2 C 245.3,436.1 246.0,436.7 246.7,435.9 C 247.4,435.1 248.1,432.3 248.8,431.4 C 249.5,430.5 250.2,430.6 250.9,430.4 C 251.6,430.3 252.3,430.5 253.0,430.4 C 253.7,430.3 254.4,430.0 255.1,429.7 C 255.8,429.5 256.5,429.3 257.2,428.9 C 257.9,428.4 258.6,427.6 259.3,427.1 C 260.0,426.6 260.7,426.1 261.4,425.7 C 262.1,425.3 262.8,425.0 263.5,424.8 C 264.1,424.6 264.8,424.5 265.5,424.4 C 266.2,424.3 266.9,424.3 267.6,424.2 C 268.3,424.1 269.0,423.9 269.7,423.8 C 270.4,423.7 271.1,423.7 271.8,423.7 C 272.5,423.6 273.2,423.6 273.9,423.5 C 274.6,423.4 275.3,423.4 276.0,423.1 C 276.7,422.7 277.4,421.8 278.1,421.3 C 278.8,420.9 279.5,420.8 280.2,420.4 C 280.9,420.1 281.6,420.8 282.3,419.4 C 283.0,418.0 283.7,413.8 284.3,412.2 C 285.0,410.6 285.7,410.3 286.4,409.6 C 287.1,408.9 287.8,408.5 288.5,408.0 C 289.2,407.6 289.9,407.1 290.6,406.7 C 291.3,406.4 292.0,406.1 292.7,405.8 C 293.4,405.6 294.1,405.6 294.8,405.4 C 295.5,405.2 296.2,405.0 296.9,404.7 C 297.6,404.4 298.3,404.0 299.0,403.8 C 299.7,403.6 300.4,403.6 301.1,403.3 C 301.8,403.1 302.5,402.7 303.2,402.4 C 303.9,402.2 304.6,401.9 305.2,401.7 C 305.9,401.5 306.6,401.3 307.3,401.2 C 308.0,401.1 308.7,401.0 309.4,400.9 C 310.1,400.8 310.8,400.6 311.5,400.5 C 312.2,400.3 312.9,400.2 313.6,400.0 C 314.3,399.8 315.0,399.7 315.7,399.4 C 316.4,399.1 317.1,398.6 317.8,398.3 C 318.5,398.1 319.2,398.0 319.9,397.8 C 320.6,397.7 321.3,397.6 322.0,397.5 C 322.7,397.4 323.4,397.3 324.1,397.2 C 324.8,397.1 325.4,397.0 326.1,396.9 C 326.8,396.9 327.5,396.9 328.2,396.8 C 328.9,396.7 329.6,396.5 330.3,396.3 C 331.0,396.1 331.7,395.6 332.4,395.4 C 333.1,395.1 333.8,394.7 334.5,394.5 C 335.2,394.3 335.9,394.3 336.6,394.2 C 337.3,394.1 338.0,394.0 338.7,393.8 C 339.4,393.6 340.1,393.1 340.8,393.0 C 341.5,392.8 342.2,392.8 342.9,392.7 C 343.6,392.6 344.3,392.4 345.0,392.2 C 345.7,392.1 346.3,391.9 347.0,391.8 C 347.7,391.6 348.4,391.4 349.1,391.2 C 349.8,391.1 350.5,391.0 351.2,390.8 C 351.9,390.6 352.6,390.3 353.3,390.1 C 354.0,389.9 354.7,389.8 355.4,389.6 C 356.1,389.4 356.8,389.1 357.5,388.8 C 358.2,388.6 358.9,388.3 359.6,388.1 C 360.3,387.9 361.0,387.9 361.7,387.5 C 362.4,387.2 363.1,386.3 363.8,386.0 C 364.5,385.7 365.2,385.6 365.9,385.5 C 366.5,385.4 367.2,385.4 367.9,385.3 C 368.6,385.3 369.3,385.1 370.0,385.0 C 370.7,384.9 371.4,385.1 372.1,384.8 C 372.8,384.5 373.5,383.5 374.2,383.1 C 374.9,382.8 375.6,382.8 376.3,382.6 C 377.0,382.4 377.7,382.0 378.4,381.8 C 379.1,381.6 379.8,381.7 380.5,381.6 C 381.2,381.4 381.9,380.9 382.6,380.8 C 383.3,380.6 384.0,380.6 384.7,380.5 C 385.4,380.4 386.1,380.5 386.7,380.3 C 387.4,380.1 388.1,379.9 388.8,379.4 C 389.5,379.0 390.2,378.1 390.9,377.6 C 391.6,377.1 392.3,376.9 393.0,376.6 C 393.7,376.3 394.4,376.2 395.1,375.6 C 395.8,374.9 396.5,373.5 397.2,372.8 C 397.9,372.0 398.6,371.7 399.3,371.3 C 400.0,370.9 400.7,370.8 401.4,370.2 C 402.1,369.6 402.8,368.2 403.5,367.5 C 404.2,366.9 404.9,366.8 405.6,366.5 C 406.3,366.1 407.0,365.8 407.6,365.4 C 408.3,365Line truncated
|
||||
<circle cx="765.0" cy="102.2" r="5" fill="#dd4528" stroke="#0d1117" stroke-width="2" filter="url(#xkcdify)"/>
|
||||
<text x="753.0" y="77.0" fill="#dd4528" font-size="18" font-family="Handlee, cursive" font-weight="bold" text-anchor="end">7536</text>
|
||||
<path d="M 90.0,462.3 C 90.3,462.3 91.7,462.0 92.0,461.9 C 92.7,461.8 93.4,461.7 94.1,461.5 C 94.8,461.4 95.5,461.2 96.1,461.1 C 96.8,461.0 97.5,461.1 98.2,461.0 C 98.9,461.0 99.5,461.0 100.2,460.9 C 100.9,460.9 101.6,460.8 102.3,460.8 C 103.0,460.7 103.3,460.7 104.3,460.7 C 105.3,460.6 107.4,460.6 108.4,460.5 C 109.4,460.5 109.8,460.4 110.5,460.4 C 111.1,460.4 111.8,460.4 112.5,460.4 C 113.2,460.4 113.9,460.3 114.5,460.3 C 115.2,460.3 115.9,460.3 116.6,460.3 C 117.3,460.2 118.0,460.2 118.6,460.1 C 119.3,460.1 120.0,460.1 120.7,459.9 C 121.4,459.8 122.0,459.6 122.7,459.3 C 123.4,459.0 124.1,458.3 124.8,458.1 C 125.5,457.8 126.1,458.0 126.8,457.9 C 127.5,457.9 128.2,457.9 128.9,457.8 C 129.5,457.8 129.9,457.8 130.9,457.7 C 131.9,457.7 133.6,457.7 135.0,457.7 C 136.4,457.7 138.1,457.6 139.1,457.6 C 140.1,457.6 140.5,457.5 141.1,457.5 C 141.8,457.5 142.5,457.4 143.2,457.4 C 143.9,457.4 144.5,457.3 145.2,457.3 C 145.9,457.3 146.6,457.3 147.3,457.3 C 148.0,457.2 148.3,457.2 149.3,457.2 C 150.3,457.2 151.7,457.1 153.4,457.1 C 155.1,457.1 157.8,457.1 159.5,457.1 C 161.2,457.0 161.6,457.1 163.6,457.0 C 165.7,457.0 170.1,456.9 171.8,456.8 C 173.5,456.8 172.8,456.8 173.9,456.8 C 174.9,456.8 176.2,456.8 178.0,456.7 C 179.7,456.7 180.7,456.7 184.1,456.6 C 187.5,456.6 195.7,456.5 198.4,456.5 C 201.1,456.5 199.8,456.5 200.5,456.4 C 201.1,456.4 201.5,457.0 202.5,456.4 C 203.5,455.8 205.6,455.4 206.6,452.9 C 207.6,450.5 208.0,443.8 208.6,441.7 C 209.3,439.7 210.0,440.8 210.7,440.5 C 211.4,440.2 212.0,439.9 212.7,439.7 C 213.4,439.5 214.1,439.3 214.8,439.2 C 215.5,439.1 216.1,439.1 216.8,439.0 C 217.5,438.9 218.2,438.7 218.9,438.7 C 219.5,438.6 220.2,438.7 220.9,438.6 C 221.6,438.6 222.3,438.4 223.0,438.3 C 223.6,438.2 224.3,438.3 225.0,438.2 C 225.7,438.0 226.4,437.7 227.0,437.6 C 227.7,437.5 228.4,437.6 229.1,437.5 C 229.8,437.4 230.5,437.2 231.1,437.1 C 231.8,437.1 232.5,437.1 233.2,437.1 C 233.9,437.1 234.5,437.0 235.2,437.0 C 235.9,436.9 236.6,436.9 237.3,436.8 C 238.0,436.8 238.6,436.8 239.3,436.7 C 240.0,436.6 240.7,436.4 241.4,436.2 C 242.0,436.1 242.7,436.7 243.4,435.9 C 244.1,435.1 244.8,432.3 245.5,431.4 C 246.1,430.5 246.8,430.6 247.5,430.4 C 248.2,430.3 248.9,430.5 249.5,430.4 C 250.2,430.3 250.9,430.0 251.6,429.7 C 252.3,429.5 253.0,429.3 253.6,428.9 C 254.3,428.4 255.0,427.6 255.7,427.1 C 256.4,426.6 257.0,426.0 257.7,425.7 C 258.4,425.3 259.1,425.0 259.8,424.7 C 260.5,424.5 261.1,424.4 261.8,424.3 C 262.5,424.2 263.2,424.2 263.9,424.1 C 264.5,424.0 265.2,423.8 265.9,423.7 C 266.6,423.7 267.3,423.7 268.0,423.6 C 268.6,423.6 269.3,423.6 270.0,423.5 C 270.7,423.4 271.4,423.4 272.0,423.0 C 272.7,422.7 273.4,421.7 274.1,421.3 C 274.8,420.9 275.5,420.7 276.1,420.4 C 276.8,420.1 277.5,420.7 278.2,419.3 C 278.9,418.0 279.5,413.8 280.2,412.2 C 280.9,410.5 281.6,410.3 282.3,409.6 C 283.0,408.9 283.6,408.5 284.3,408.0 C 285.0,407.5 285.7,407.1 286.4,406.7 C 287.0,406.3 287.7,406.0 288.4,405.8 C 289.1,405.6 289.8,405.5 290.5,405.3 C 291.1,405.1 291.8,404.9 292.5,404.6 C 293.2,404.4 293.9,404.0 294.5,403.7 C 295.2,403.5 295.9,403.5 296.6,403.3 C 297.3,403.1 298.0,402.7 298.6,402.4 C 299.3,402.1 300.0,401.9 300.7,401.7 C 301.4,401.5 302.0,401.3 302.7,401.1 C 303.4,401.0 304.1,401.0 304.8,400.9 C 305.5,400.7 306.1,400.6 306.8,400.4 C 307.5,400.3 308.2,400.2 308.9,400.0 C 309.5,399.8 310.2,399.7 310.9,399.4 C 311.6,399.1 312.3,398.6 313.0,398.3 C 313.6,398.1 314.3,398.0 315.0,397.9 C 315.7,397.8 316.4,397.7 317.0,397.6 C 317.7,397.5 318.4,397.4 319.1,397.3 C 319.8,397.2 320.5,397.1 321.1,397.0 C 321.8,396.9 322.5,396.9 323.2,396.8 C 323.9,396.7 324.5,396.6 325.2,396.4 C 325.9,396.1 326.6,395.7 327.3,395.4 C 328.0,395.1 328.6,394.8 329.3,394.6 C 330.0,394.4 330.7,394.4 331.4,394.3 C 332.0,394.1 332.7,394.1 333.4,393.9 C 334.1,393.7 334.8,393.2 335.5,393.1 C 336.1,392.9 336.8,392.9 337.5,392.8 C 338.2,392.7 338.9,392.5 339.5,392.3 C 340.2,392.2 340.9,392.0 341.6,391.9 C 342.3,391.7 343.0,391.5 343.6,391.3 C 344.3,391.2 345.0,391.1 345.7,390.9 C 346.4,390.7 347.0,390.4 347.7,390.2 C 348.4,390.0 349.1,389.9 349.8,389.7 C 350.5,389.5 351.1,389.2 351.8,389.0 C 352.5,388.7 353.2,388.5 353.9,388.3 C 354.5,388.0 355.2,388.0 355.9,387.6 C 356.6,387.3 357.3,386.5 358.0,386.2 C 358.6,385.8 359.3,385.8 360.0,385.7 C 360.7,385.6 361.4,385.6 362.0,385.5 C 362.7,385.4 363.4,385.3 364.1,385.2 C 364.8,385.1 365.5,385.2 366.1,384.9 C 366.8,384.6 367.5,383.6 368.2,383.3 C 368.9,382.9 369.5,383.0 370.2,382.8 C 370.9,382.5 371.6,382.1 372.3,381.9 C 373.0,381.8 373.6,381.9 374.3,381.7 C 375.0,381.5 375.7,381.1 376.4,380.9 C 377.0,380.7 377.7,380.7 378.4,380.7 C 379.1,380.6 379.8,380.6 380.5,380.4 C 381.1,380.2 381.8,380.0 382.5,379.6 C 383.2,379.1 383.9,378.2 384.5,377.7 C 385.2,377.3 385.9,377.1 386.6,376.7 C 387.3,376.4 388.0,376.4 388.6,375.7 C 389.3,375.1 390.0,373.6 390.7,372.9 C 391.4,372.2 392.0,371.9 392.7,371.5 C 393.4,371.0 394.1,371.0 394.8,370.4 C 395.5,369.8 396.1,368.4 396.8,367.7 C 397.5,367.1 398.2,367.0 398.9,366.7 C 399.5,366Line truncated
|
||||
<path d="M 90.0,462.3 C 90.3,462.3 91.7,462.0 92.0,461.9 C 92.7,461.8 93.4,461.7 94.1,461.5 C 94.8,461.4 95.5,461.2 96.1,461.1 C 96.8,461.0 97.5,461.1 98.2,461.0 C 98.9,461.0 99.5,461.0 100.2,460.9 C 100.9,460.9 101.6,460.8 102.3,460.8 C 103.0,460.7 103.3,460.7 104.3,460.7 C 105.3,460.6 107.4,460.6 108.4,460.5 C 109.4,460.5 109.8,460.4 110.5,460.4 C 111.1,460.4 111.8,460.4 112.5,460.4 C 113.2,460.4 113.9,460.3 114.5,460.3 C 115.2,460.3 115.9,460.3 116.6,460.3 C 117.3,460.2 118.0,460.2 118.6,460.1 C 119.3,460.1 120.0,460.1 120.7,459.9 C 121.4,459.8 122.0,459.6 122.7,459.3 C 123.4,459.0 124.1,458.3 124.8,458.1 C 125.5,457.8 126.1,458.0 126.8,457.9 C 127.5,457.9 128.2,457.9 128.9,457.8 C 129.5,457.8 129.9,457.8 130.9,457.7 C 131.9,457.7 133.6,457.7 135.0,457.7 C 136.4,457.7 138.1,457.6 139.1,457.6 C 140.1,457.6 140.5,457.5 141.1,457.5 C 141.8,457.5 142.5,457.4 143.2,457.4 C 143.9,457.4 144.5,457.3 145.2,457.3 C 145.9,457.3 146.6,457.3 147.3,457.3 C 148.0,457.2 148.3,457.2 149.3,457.2 C 150.3,457.2 151.7,457.1 153.4,457.1 C 155.1,457.1 157.8,457.1 159.5,457.1 C 161.2,457.0 161.6,457.1 163.6,457.0 C 165.7,457.0 170.1,456.9 171.8,456.8 C 173.5,456.8 172.8,456.8 173.9,456.8 C 174.9,456.8 176.2,456.8 178.0,456.7 C 179.7,456.7 180.7,456.7 184.1,456.6 C 187.5,456.6 195.7,456.5 198.4,456.5 C 201.1,456.5 199.8,456.5 200.5,456.4 C 201.1,456.4 201.5,457.0 202.5,456.4 C 203.5,455.8 205.6,455.4 206.6,452.9 C 207.6,450.5 208.0,443.8 208.6,441.7 C 209.3,439.7 210.0,440.8 210.7,440.5 C 211.4,440.2 212.0,439.9 212.7,439.7 C 213.4,439.5 214.1,439.3 214.8,439.2 C 215.5,439.1 216.1,439.1 216.8,439.0 C 217.5,438.9 218.2,438.7 218.9,438.7 C 219.5,438.6 220.2,438.7 220.9,438.6 C 221.6,438.6 222.3,438.4 223.0,438.3 C 223.6,438.2 224.3,438.3 225.0,438.2 C 225.7,438.0 226.4,437.7 227.0,437.6 C 227.7,437.5 228.4,437.6 229.1,437.5 C 229.8,437.4 230.5,437.2 231.1,437.1 C 231.8,437.1 232.5,437.1 233.2,437.1 C 233.9,437.1 234.5,437.0 235.2,437.0 C 235.9,436.9 236.6,436.9 237.3,436.8 C 238.0,436.8 238.6,436.8 239.3,436.7 C 240.0,436.6 240.7,436.4 241.4,436.2 C 242.0,436.1 242.7,436.7 243.4,435.9 C 244.1,435.1 244.8,432.3 245.5,431.4 C 246.1,430.5 246.8,430.6 247.5,430.4 C 248.2,430.3 248.9,430.5 249.5,430.4 C 250.2,430.3 250.9,430.0 251.6,429.7 C 252.3,429.5 253.0,429.3 253.6,428.9 C 254.3,428.4 255.0,427.6 255.7,427.1 C 256.4,426.6 257.0,426.0 257.7,425.7 C 258.4,425.3 259.1,425.0 259.8,424.7 C 260.5,424.5 261.1,424.4 261.8,424.3 C 262.5,424.2 263.2,424.2 263.9,424.1 C 264.5,424.0 265.2,423.8 265.9,423.7 C 266.6,423.7 267.3,423.7 268.0,423.6 C 268.6,423.6 269.3,423.6 270.0,423.5 C 270.7,423.4 271.4,423.4 272.0,423.0 C 272.7,422.7 273.4,421.7 274.1,421.3 C 274.8,420.9 275.5,420.7 276.1,420.4 C 276.8,420.1 277.5,420.7 278.2,419.3 C 278.9,418.0 279.5,413.8 280.2,412.2 C 280.9,410.5 281.6,410.3 282.3,409.6 C 283.0,408.9 283.6,408.5 284.3,408.0 C 285.0,407.5 285.7,407.1 286.4,406.7 C 287.0,406.3 287.7,406.0 288.4,405.8 C 289.1,405.6 289.8,405.5 290.5,405.3 C 291.1,405.1 291.8,404.9 292.5,404.6 C 293.2,404.4 293.9,404.0 294.5,403.7 C 295.2,403.5 295.9,403.5 296.6,403.3 C 297.3,403.1 298.0,402.7 298.6,402.4 C 299.3,402.1 300.0,401.9 300.7,401.7 C 301.4,401.5 302.0,401.3 302.7,401.1 C 303.4,401.0 304.1,401.0 304.8,400.9 C 305.5,400.7 306.1,400.6 306.8,400.4 C 307.5,400.3 308.2,400.2 308.9,400.0 C 309.5,399.8 310.2,399.7 310.9,399.4 C 311.6,399.1 312.3,398.6 313.0,398.3 C 313.6,398.1 314.3,398.0 315.0,397.9 C 315.7,397.8 316.4,397.7 317.0,397.6 C 317.7,397.5 318.4,397.4 319.1,397.3 C 319.8,397.2 320.5,397.1 321.1,397.0 C 321.8,396.9 322.5,396.9 323.2,396.8 C 323.9,396.7 324.5,396.6 325.2,396.4 C 325.9,396.1 326.6,395.7 327.3,395.4 C 328.0,395.1 328.6,394.8 329.3,394.6 C 330.0,394.4 330.7,394.4 331.4,394.3 C 332.0,394.1 332.7,394.1 333.4,393.9 C 334.1,393.7 334.8,393.2 335.5,393.1 C 336.1,392.9 336.8,392.9 337.5,392.8 C 338.2,392.7 338.9,392.5 339.5,392.3 C 340.2,392.2 340.9,392.0 341.6,391.9 C 342.3,391.7 343.0,391.5 343.6,391.3 C 344.3,391.2 345.0,391.1 345.7,390.9 C 346.4,390.7 347.0,390.4 347.7,390.2 C 348.4,390.0 349.1,389.9 349.8,389.7 C 350.5,389.5 351.1,389.2 351.8,389.0 C 352.5,388.7 353.2,388.5 353.9,388.3 C 354.5,388.0 355.2,388.0 355.9,387.6 C 356.6,387.3 357.3,386.5 358.0,386.2 C 358.6,385.8 359.3,385.8 360.0,385.7 C 360.7,385.6 361.4,385.6 362.0,385.5 C 362.7,385.4 363.4,385.3 364.1,385.2 C 364.8,385.1 365.5,385.2 366.1,384.9 C 366.8,384.6 367.5,383.6 368.2,383.3 C 368.9,382.9 369.5,383.0 370.2,382.8 C 370.9,382.5 371.6,382.1 372.3,381.9 C 373.0,381.8 373.6,381.9 374.3,381.7 C 375.0,381.5 375.7,381.1 376.4,380.9 C 377.0,380.7 377.7,380.7 378.4,380.7 C 379.1,380.6 379.8,380.6 380.5,380.4 C 381.1,380.2 381.8,380.0 382.5,379.6 C 383.2,379.1 383.9,378.2 384.5,377.7 C 385.2,377.3 385.9,377.1 386.6,376.7 C 387.3,376.4 388.0,376.4 388.6,375.7 C 389.3,375.1 390.0,373.6 390.7,372.9 C 391.4,372.2 392.0,371.9 392.7,371.5 C 393.4,371.0 394.1,371.0 394.8,370.4 C 395.5,369.8 396.1,368.4 396.8,367.7 C 397.5,367.1 398.2,367.0 398.9,366.7 C 399.5,366Line truncated
|
||||
<circle cx="765.0" cy="94.3" r="5" fill="#dd4528" stroke="#0d1117" stroke-width="2" filter="url(#xkcdify)"/>
|
||||
<text x="753.0" y="77.0" fill="#dd4528" font-size="18" font-family="Handlee, cursive" font-weight="bold" text-anchor="end">7701</text>
|
||||
<a href="https://github.com/carsteneu/mystarhistory" target="_blank" rel="noopener"><text x="763" y="527" font-size="13" font-family="Handlee, cursive" fill="#fff" text-anchor="end">Made with carsteneu/mystarhistory</text></a>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 38 KiB After Width: | Height: | Size: 39 KiB |
@@ -33,17 +33,17 @@
|
||||
<text x="85" y="85.0" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="end">8K</text>
|
||||
<text x="43" y="271.5" fill="#000" font-size="17" font-family="Handlee, cursive" font-weight="bold" transform="rotate(-90, 43, 271.5)">GitHub Stars</text>
|
||||
<text x="90.0" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Jan 2026</text>
|
||||
<text x="209.1" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Mar 2026</text>
|
||||
<text x="336.6" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">May 2026</text>
|
||||
<text x="464.1" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Jul 2026</text>
|
||||
<text x="593.6" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Sep 2026</text>
|
||||
<text x="721.1" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Nov 2026</text>
|
||||
<text x="206.6" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Mar 2026</text>
|
||||
<text x="331.4" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">May 2026</text>
|
||||
<text x="456.1" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Jul 2026</text>
|
||||
<text x="583.0" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Sep 2026</text>
|
||||
<text x="707.7" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Nov 2026</text>
|
||||
<text x="50%" y="525" fill="#000" font-size="17" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Date</text>
|
||||
<line x1="90" y1="80" x2="90" y2="463" stroke="#222" stroke-width="2.5" filter="url(#xkcdify)"/>
|
||||
<line x1="90" y1="463" x2="765" y2="463" stroke="#222" stroke-width="2.5" filter="url(#xkcdify)"/>
|
||||
<path d="M 90.0,462.3 C 90.3,462.3 91.7,462.0 92.1,461.9 C 92.8,461.8 93.5,461.7 94.2,461.5 C 94.9,461.4 95.6,461.2 96.3,461.1 C 97.0,461.0 97.7,461.1 98.4,461.0 C 99.1,461.0 99.8,461.0 100.4,460.9 C 101.1,460.9 101.8,460.8 102.5,460.8 C 103.2,460.7 103.6,460.7 104.6,460.7 C 105.7,460.6 107.8,460.6 108.8,460.5 C 109.9,460.5 110.2,460.4 110.9,460.4 C 111.6,460.4 112.3,460.4 113.0,460.4 C 113.7,460.4 114.4,460.3 115.1,460.3 C 115.8,460.3 116.5,460.3 117.2,460.3 C 117.9,460.2 118.6,460.2 119.3,460.1 C 120.0,460.1 120.7,460.1 121.3,459.9 C 122.0,459.8 122.7,459.6 123.4,459.3 C 124.1,459.0 124.8,458.3 125.5,458.1 C 126.2,457.8 126.9,458.0 127.6,457.9 C 128.3,457.9 129.0,457.9 129.7,457.8 C 130.4,457.8 130.8,457.8 131.8,457.7 C 132.8,457.7 134.6,457.7 136.0,457.7 C 137.4,457.7 139.1,457.6 140.2,457.6 C 141.2,457.6 141.5,457.5 142.2,457.5 C 142.9,457.5 143.6,457.4 144.3,457.4 C 145.0,457.4 145.7,457.3 146.4,457.3 C 147.1,457.3 147.8,457.3 148.5,457.3 C 149.2,457.2 149.6,457.2 150.6,457.2 C 151.6,457.2 153.0,457.1 154.8,457.1 C 156.5,457.1 159.3,457.1 161.1,457.1 C 162.8,457.0 163.1,457.1 165.2,457.0 C 167.3,457.0 171.8,456.9 173.6,456.8 C 175.3,456.8 174.6,456.8 175.7,456.8 C 176.7,456.8 178.1,456.8 179.9,456.7 C 181.6,456.7 182.6,456.7 186.1,456.6 C 189.6,456.6 198.0,456.5 200.8,456.5 C 203.5,456.5 202.2,456.5 202.8,456.4 C 203.5,456.4 203.9,457.0 204.9,456.4 C 206.0,455.8 208.1,455.3 209.1,452.9 C 210.2,450.4 210.5,443.8 211.2,441.7 C 211.9,439.6 212.6,440.8 213.3,440.5 C 214.0,440.1 214.7,439.9 215.4,439.7 C 216.1,439.5 216.8,439.3 217.5,439.2 C 218.2,439.0 218.9,439.0 219.6,438.9 C 220.3,438.8 221.0,438.7 221.7,438.6 C 222.4,438.6 223.0,438.6 223.7,438.6 C 224.4,438.5 225.1,438.3 225.8,438.2 C 226.5,438.2 227.2,438.2 227.9,438.1 C 228.6,438.0 229.3,437.7 230.0,437.6 C 230.7,437.5 231.4,437.5 232.1,437.4 C 232.8,437.4 233.2,437.2 234.2,437.1 C 235.2,437.0 237.3,437.0 238.4,437.0 C 239.4,436.9 239.8,436.9 240.5,436.8 C 241.2,436.8 241.9,436.8 242.6,436.7 C 243.3,436.6 243.9,436.4 244.6,436.2 C 245.3,436.1 246.0,436.7 246.7,435.9 C 247.4,435.1 248.1,432.3 248.8,431.4 C 249.5,430.5 250.2,430.6 250.9,430.4 C 251.6,430.3 252.3,430.5 253.0,430.4 C 253.7,430.3 254.4,430.0 255.1,429.7 C 255.8,429.5 256.5,429.3 257.2,428.9 C 257.9,428.4 258.6,427.6 259.3,427.1 C 260.0,426.6 260.7,426.1 261.4,425.7 C 262.1,425.3 262.8,425.0 263.5,424.8 C 264.1,424.6 264.8,424.5 265.5,424.4 C 266.2,424.3 266.9,424.3 267.6,424.2 C 268.3,424.1 269.0,423.9 269.7,423.8 C 270.4,423.7 271.1,423.7 271.8,423.7 C 272.5,423.6 273.2,423.6 273.9,423.5 C 274.6,423.4 275.3,423.4 276.0,423.1 C 276.7,422.7 277.4,421.8 278.1,421.3 C 278.8,420.9 279.5,420.8 280.2,420.4 C 280.9,420.1 281.6,420.8 282.3,419.4 C 283.0,418.0 283.7,413.8 284.3,412.2 C 285.0,410.6 285.7,410.3 286.4,409.6 C 287.1,408.9 287.8,408.5 288.5,408.0 C 289.2,407.6 289.9,407.1 290.6,406.7 C 291.3,406.4 292.0,406.1 292.7,405.8 C 293.4,405.6 294.1,405.6 294.8,405.4 C 295.5,405.2 296.2,405.0 296.9,404.7 C 297.6,404.4 298.3,404.0 299.0,403.8 C 299.7,403.6 300.4,403.6 301.1,403.3 C 301.8,403.1 302.5,402.7 303.2,402.4 C 303.9,402.2 304.6,401.9 305.2,401.7 C 305.9,401.5 306.6,401.3 307.3,401.2 C 308.0,401.1 308.7,401.0 309.4,400.9 C 310.1,400.8 310.8,400.6 311.5,400.5 C 312.2,400.3 312.9,400.2 313.6,400.0 C 314.3,399.8 315.0,399.7 315.7,399.4 C 316.4,399.1 317.1,398.6 317.8,398.3 C 318.5,398.1 319.2,398.0 319.9,397.8 C 320.6,397.7 321.3,397.6 322.0,397.5 C 322.7,397.4 323.4,397.3 324.1,397.2 C 324.8,397.1 325.4,397.0 326.1,396.9 C 326.8,396.9 327.5,396.9 328.2,396.8 C 328.9,396.7 329.6,396.5 330.3,396.3 C 331.0,396.1 331.7,395.6 332.4,395.4 C 333.1,395.1 333.8,394.7 334.5,394.5 C 335.2,394.3 335.9,394.3 336.6,394.2 C 337.3,394.1 338.0,394.0 338.7,393.8 C 339.4,393.6 340.1,393.1 340.8,393.0 C 341.5,392.8 342.2,392.8 342.9,392.7 C 343.6,392.6 344.3,392.4 345.0,392.2 C 345.7,392.1 346.3,391.9 347.0,391.8 C 347.7,391.6 348.4,391.4 349.1,391.2 C 349.8,391.1 350.5,391.0 351.2,390.8 C 351.9,390.6 352.6,390.3 353.3,390.1 C 354.0,389.9 354.7,389.8 355.4,389.6 C 356.1,389.4 356.8,389.1 357.5,388.8 C 358.2,388.6 358.9,388.3 359.6,388.1 C 360.3,387.9 361.0,387.9 361.7,387.5 C 362.4,387.2 363.1,386.3 363.8,386.0 C 364.5,385.7 365.2,385.6 365.9,385.5 C 366.5,385.4 367.2,385.4 367.9,385.3 C 368.6,385.3 369.3,385.1 370.0,385.0 C 370.7,384.9 371.4,385.1 372.1,384.8 C 372.8,384.5 373.5,383.5 374.2,383.1 C 374.9,382.8 375.6,382.8 376.3,382.6 C 377.0,382.4 377.7,382.0 378.4,381.8 C 379.1,381.6 379.8,381.7 380.5,381.6 C 381.2,381.4 381.9,380.9 382.6,380.8 C 383.3,380.6 384.0,380.6 384.7,380.5 C 385.4,380.4 386.1,380.5 386.7,380.3 C 387.4,380.1 388.1,379.9 388.8,379.4 C 389.5,379.0 390.2,378.1 390.9,377.6 C 391.6,377.1 392.3,376.9 393.0,376.6 C 393.7,376.3 394.4,376.2 395.1,375.6 C 395.8,374.9 396.5,373.5 397.2,372.8 C 397.9,372.0 398.6,371.7 399.3,371.3 C 400.0,370.9 400.7,370.8 401.4,370.2 C 402.1,369.6 402.8,368.2 403.5,367.5 C 404.2,366.9 404.9,366.8 405.6,366.5 C 406.3,366.1 407.0,365.8 407.6,365.4 C 408.3,365Line truncated
|
||||
<path d="M 90.0,462.3 C 90.3,462.3 91.7,462.0 92.1,461.9 C 92.8,461.8 93.5,461.7 94.2,461.5 C 94.9,461.4 95.6,461.2 96.3,461.1 C 97.0,461.0 97.7,461.1 98.4,461.0 C 99.1,461.0 99.8,461.0 100.4,460.9 C 101.1,460.9 101.8,460.8 102.5,460.8 C 103.2,460.7 103.6,460.7 104.6,460.7 C 105.7,460.6 107.8,460.6 108.8,460.5 C 109.9,460.5 110.2,460.4 110.9,460.4 C 111.6,460.4 112.3,460.4 113.0,460.4 C 113.7,460.4 114.4,460.3 115.1,460.3 C 115.8,460.3 116.5,460.3 117.2,460.3 C 117.9,460.2 118.6,460.2 119.3,460.1 C 120.0,460.1 120.7,460.1 121.3,459.9 C 122.0,459.8 122.7,459.6 123.4,459.3 C 124.1,459.0 124.8,458.3 125.5,458.1 C 126.2,457.8 126.9,458.0 127.6,457.9 C 128.3,457.9 129.0,457.9 129.7,457.8 C 130.4,457.8 130.8,457.8 131.8,457.7 C 132.8,457.7 134.6,457.7 136.0,457.7 C 137.4,457.7 139.1,457.6 140.2,457.6 C 141.2,457.6 141.5,457.5 142.2,457.5 C 142.9,457.5 143.6,457.4 144.3,457.4 C 145.0,457.4 145.7,457.3 146.4,457.3 C 147.1,457.3 147.8,457.3 148.5,457.3 C 149.2,457.2 149.6,457.2 150.6,457.2 C 151.6,457.2 153.0,457.1 154.8,457.1 C 156.5,457.1 159.3,457.1 161.1,457.1 C 162.8,457.0 163.1,457.1 165.2,457.0 C 167.3,457.0 171.8,456.9 173.6,456.8 C 175.3,456.8 174.6,456.8 175.7,456.8 C 176.7,456.8 178.1,456.8 179.9,456.7 C 181.6,456.7 182.6,456.7 186.1,456.6 C 189.6,456.6 198.0,456.5 200.8,456.5 C 203.5,456.5 202.2,456.5 202.8,456.4 C 203.5,456.4 203.9,457.0 204.9,456.4 C 206.0,455.8 208.1,455.3 209.1,452.9 C 210.2,450.4 210.5,443.8 211.2,441.7 C 211.9,439.6 212.6,440.8 213.3,440.5 C 214.0,440.1 214.7,439.9 215.4,439.7 C 216.1,439.5 216.8,439.3 217.5,439.2 C 218.2,439.0 218.9,439.0 219.6,438.9 C 220.3,438.8 221.0,438.7 221.7,438.6 C 222.4,438.6 223.0,438.6 223.7,438.6 C 224.4,438.5 225.1,438.3 225.8,438.2 C 226.5,438.2 227.2,438.2 227.9,438.1 C 228.6,438.0 229.3,437.7 230.0,437.6 C 230.7,437.5 231.4,437.5 232.1,437.4 C 232.8,437.4 233.2,437.2 234.2,437.1 C 235.2,437.0 237.3,437.0 238.4,437.0 C 239.4,436.9 239.8,436.9 240.5,436.8 C 241.2,436.8 241.9,436.8 242.6,436.7 C 243.3,436.6 243.9,436.4 244.6,436.2 C 245.3,436.1 246.0,436.7 246.7,435.9 C 247.4,435.1 248.1,432.3 248.8,431.4 C 249.5,430.5 250.2,430.6 250.9,430.4 C 251.6,430.3 252.3,430.5 253.0,430.4 C 253.7,430.3 254.4,430.0 255.1,429.7 C 255.8,429.5 256.5,429.3 257.2,428.9 C 257.9,428.4 258.6,427.6 259.3,427.1 C 260.0,426.6 260.7,426.1 261.4,425.7 C 262.1,425.3 262.8,425.0 263.5,424.8 C 264.1,424.6 264.8,424.5 265.5,424.4 C 266.2,424.3 266.9,424.3 267.6,424.2 C 268.3,424.1 269.0,423.9 269.7,423.8 C 270.4,423.7 271.1,423.7 271.8,423.7 C 272.5,423.6 273.2,423.6 273.9,423.5 C 274.6,423.4 275.3,423.4 276.0,423.1 C 276.7,422.7 277.4,421.8 278.1,421.3 C 278.8,420.9 279.5,420.8 280.2,420.4 C 280.9,420.1 281.6,420.8 282.3,419.4 C 283.0,418.0 283.7,413.8 284.3,412.2 C 285.0,410.6 285.7,410.3 286.4,409.6 C 287.1,408.9 287.8,408.5 288.5,408.0 C 289.2,407.6 289.9,407.1 290.6,406.7 C 291.3,406.4 292.0,406.1 292.7,405.8 C 293.4,405.6 294.1,405.6 294.8,405.4 C 295.5,405.2 296.2,405.0 296.9,404.7 C 297.6,404.4 298.3,404.0 299.0,403.8 C 299.7,403.6 300.4,403.6 301.1,403.3 C 301.8,403.1 302.5,402.7 303.2,402.4 C 303.9,402.2 304.6,401.9 305.2,401.7 C 305.9,401.5 306.6,401.3 307.3,401.2 C 308.0,401.1 308.7,401.0 309.4,400.9 C 310.1,400.8 310.8,400.6 311.5,400.5 C 312.2,400.3 312.9,400.2 313.6,400.0 C 314.3,399.8 315.0,399.7 315.7,399.4 C 316.4,399.1 317.1,398.6 317.8,398.3 C 318.5,398.1 319.2,398.0 319.9,397.8 C 320.6,397.7 321.3,397.6 322.0,397.5 C 322.7,397.4 323.4,397.3 324.1,397.2 C 324.8,397.1 325.4,397.0 326.1,396.9 C 326.8,396.9 327.5,396.9 328.2,396.8 C 328.9,396.7 329.6,396.5 330.3,396.3 C 331.0,396.1 331.7,395.6 332.4,395.4 C 333.1,395.1 333.8,394.7 334.5,394.5 C 335.2,394.3 335.9,394.3 336.6,394.2 C 337.3,394.1 338.0,394.0 338.7,393.8 C 339.4,393.6 340.1,393.1 340.8,393.0 C 341.5,392.8 342.2,392.8 342.9,392.7 C 343.6,392.6 344.3,392.4 345.0,392.2 C 345.7,392.1 346.3,391.9 347.0,391.8 C 347.7,391.6 348.4,391.4 349.1,391.2 C 349.8,391.1 350.5,391.0 351.2,390.8 C 351.9,390.6 352.6,390.3 353.3,390.1 C 354.0,389.9 354.7,389.8 355.4,389.6 C 356.1,389.4 356.8,389.1 357.5,388.8 C 358.2,388.6 358.9,388.3 359.6,388.1 C 360.3,387.9 361.0,387.9 361.7,387.5 C 362.4,387.2 363.1,386.3 363.8,386.0 C 364.5,385.7 365.2,385.6 365.9,385.5 C 366.5,385.4 367.2,385.4 367.9,385.3 C 368.6,385.3 369.3,385.1 370.0,385.0 C 370.7,384.9 371.4,385.1 372.1,384.8 C 372.8,384.5 373.5,383.5 374.2,383.1 C 374.9,382.8 375.6,382.8 376.3,382.6 C 377.0,382.4 377.7,382.0 378.4,381.8 C 379.1,381.6 379.8,381.7 380.5,381.6 C 381.2,381.4 381.9,380.9 382.6,380.8 C 383.3,380.6 384.0,380.6 384.7,380.5 C 385.4,380.4 386.1,380.5 386.7,380.3 C 387.4,380.1 388.1,379.9 388.8,379.4 C 389.5,379.0 390.2,378.1 390.9,377.6 C 391.6,377.1 392.3,376.9 393.0,376.6 C 393.7,376.3 394.4,376.2 395.1,375.6 C 395.8,374.9 396.5,373.5 397.2,372.8 C 397.9,372.0 398.6,371.7 399.3,371.3 C 400.0,370.9 400.7,370.8 401.4,370.2 C 402.1,369.6 402.8,368.2 403.5,367.5 C 404.2,366.9 404.9,366.8 405.6,366.5 C 406.3,366.1 407.0,365.8 407.6,365.4 C 408.3,365Line truncated
|
||||
<circle cx="765.0" cy="102.2" r="5" fill="#dd4528" stroke="#fff" stroke-width="2" filter="url(#xkcdify)"/>
|
||||
<text x="753.0" y="77.0" fill="#dd4528" font-size="18" font-family="Handlee, cursive" font-weight="bold" text-anchor="end">7536</text>
|
||||
<path d="M 90.0,462.3 C 90.3,462.3 91.7,462.0 92.0,461.9 C 92.7,461.8 93.4,461.7 94.1,461.5 C 94.8,461.4 95.5,461.2 96.1,461.1 C 96.8,461.0 97.5,461.1 98.2,461.0 C 98.9,461.0 99.5,461.0 100.2,460.9 C 100.9,460.9 101.6,460.8 102.3,460.8 C 103.0,460.7 103.3,460.7 104.3,460.7 C 105.3,460.6 107.4,460.6 108.4,460.5 C 109.4,460.5 109.8,460.4 110.5,460.4 C 111.1,460.4 111.8,460.4 112.5,460.4 C 113.2,460.4 113.9,460.3 114.5,460.3 C 115.2,460.3 115.9,460.3 116.6,460.3 C 117.3,460.2 118.0,460.2 118.6,460.1 C 119.3,460.1 120.0,460.1 120.7,459.9 C 121.4,459.8 122.0,459.6 122.7,459.3 C 123.4,459.0 124.1,458.3 124.8,458.1 C 125.5,457.8 126.1,458.0 126.8,457.9 C 127.5,457.9 128.2,457.9 128.9,457.8 C 129.5,457.8 129.9,457.8 130.9,457.7 C 131.9,457.7 133.6,457.7 135.0,457.7 C 136.4,457.7 138.1,457.6 139.1,457.6 C 140.1,457.6 140.5,457.5 141.1,457.5 C 141.8,457.5 142.5,457.4 143.2,457.4 C 143.9,457.4 144.5,457.3 145.2,457.3 C 145.9,457.3 146.6,457.3 147.3,457.3 C 148.0,457.2 148.3,457.2 149.3,457.2 C 150.3,457.2 151.7,457.1 153.4,457.1 C 155.1,457.1 157.8,457.1 159.5,457.1 C 161.2,457.0 161.6,457.1 163.6,457.0 C 165.7,457.0 170.1,456.9 171.8,456.8 C 173.5,456.8 172.8,456.8 173.9,456.8 C 174.9,456.8 176.2,456.8 178.0,456.7 C 179.7,456.7 180.7,456.7 184.1,456.6 C 187.5,456.6 195.7,456.5 198.4,456.5 C 201.1,456.5 199.8,456.5 200.5,456.4 C 201.1,456.4 201.5,457.0 202.5,456.4 C 203.5,455.8 205.6,455.4 206.6,452.9 C 207.6,450.5 208.0,443.8 208.6,441.7 C 209.3,439.7 210.0,440.8 210.7,440.5 C 211.4,440.2 212.0,439.9 212.7,439.7 C 213.4,439.5 214.1,439.3 214.8,439.2 C 215.5,439.1 216.1,439.1 216.8,439.0 C 217.5,438.9 218.2,438.7 218.9,438.7 C 219.5,438.6 220.2,438.7 220.9,438.6 C 221.6,438.6 222.3,438.4 223.0,438.3 C 223.6,438.2 224.3,438.3 225.0,438.2 C 225.7,438.0 226.4,437.7 227.0,437.6 C 227.7,437.5 228.4,437.6 229.1,437.5 C 229.8,437.4 230.5,437.2 231.1,437.1 C 231.8,437.1 232.5,437.1 233.2,437.1 C 233.9,437.1 234.5,437.0 235.2,437.0 C 235.9,436.9 236.6,436.9 237.3,436.8 C 238.0,436.8 238.6,436.8 239.3,436.7 C 240.0,436.6 240.7,436.4 241.4,436.2 C 242.0,436.1 242.7,436.7 243.4,435.9 C 244.1,435.1 244.8,432.3 245.5,431.4 C 246.1,430.5 246.8,430.6 247.5,430.4 C 248.2,430.3 248.9,430.5 249.5,430.4 C 250.2,430.3 250.9,430.0 251.6,429.7 C 252.3,429.5 253.0,429.3 253.6,428.9 C 254.3,428.4 255.0,427.6 255.7,427.1 C 256.4,426.6 257.0,426.0 257.7,425.7 C 258.4,425.3 259.1,425.0 259.8,424.7 C 260.5,424.5 261.1,424.4 261.8,424.3 C 262.5,424.2 263.2,424.2 263.9,424.1 C 264.5,424.0 265.2,423.8 265.9,423.7 C 266.6,423.7 267.3,423.7 268.0,423.6 C 268.6,423.6 269.3,423.6 270.0,423.5 C 270.7,423.4 271.4,423.4 272.0,423.0 C 272.7,422.7 273.4,421.7 274.1,421.3 C 274.8,420.9 275.5,420.7 276.1,420.4 C 276.8,420.1 277.5,420.7 278.2,419.3 C 278.9,418.0 279.5,413.8 280.2,412.2 C 280.9,410.5 281.6,410.3 282.3,409.6 C 283.0,408.9 283.6,408.5 284.3,408.0 C 285.0,407.5 285.7,407.1 286.4,406.7 C 287.0,406.3 287.7,406.0 288.4,405.8 C 289.1,405.6 289.8,405.5 290.5,405.3 C 291.1,405.1 291.8,404.9 292.5,404.6 C 293.2,404.4 293.9,404.0 294.5,403.7 C 295.2,403.5 295.9,403.5 296.6,403.3 C 297.3,403.1 298.0,402.7 298.6,402.4 C 299.3,402.1 300.0,401.9 300.7,401.7 C 301.4,401.5 302.0,401.3 302.7,401.1 C 303.4,401.0 304.1,401.0 304.8,400.9 C 305.5,400.7 306.1,400.6 306.8,400.4 C 307.5,400.3 308.2,400.2 308.9,400.0 C 309.5,399.8 310.2,399.7 310.9,399.4 C 311.6,399.1 312.3,398.6 313.0,398.3 C 313.6,398.1 314.3,398.0 315.0,397.9 C 315.7,397.8 316.4,397.7 317.0,397.6 C 317.7,397.5 318.4,397.4 319.1,397.3 C 319.8,397.2 320.5,397.1 321.1,397.0 C 321.8,396.9 322.5,396.9 323.2,396.8 C 323.9,396.7 324.5,396.6 325.2,396.4 C 325.9,396.1 326.6,395.7 327.3,395.4 C 328.0,395.1 328.6,394.8 329.3,394.6 C 330.0,394.4 330.7,394.4 331.4,394.3 C 332.0,394.1 332.7,394.1 333.4,393.9 C 334.1,393.7 334.8,393.2 335.5,393.1 C 336.1,392.9 336.8,392.9 337.5,392.8 C 338.2,392.7 338.9,392.5 339.5,392.3 C 340.2,392.2 340.9,392.0 341.6,391.9 C 342.3,391.7 343.0,391.5 343.6,391.3 C 344.3,391.2 345.0,391.1 345.7,390.9 C 346.4,390.7 347.0,390.4 347.7,390.2 C 348.4,390.0 349.1,389.9 349.8,389.7 C 350.5,389.5 351.1,389.2 351.8,389.0 C 352.5,388.7 353.2,388.5 353.9,388.3 C 354.5,388.0 355.2,388.0 355.9,387.6 C 356.6,387.3 357.3,386.5 358.0,386.2 C 358.6,385.8 359.3,385.8 360.0,385.7 C 360.7,385.6 361.4,385.6 362.0,385.5 C 362.7,385.4 363.4,385.3 364.1,385.2 C 364.8,385.1 365.5,385.2 366.1,384.9 C 366.8,384.6 367.5,383.6 368.2,383.3 C 368.9,382.9 369.5,383.0 370.2,382.8 C 370.9,382.5 371.6,382.1 372.3,381.9 C 373.0,381.8 373.6,381.9 374.3,381.7 C 375.0,381.5 375.7,381.1 376.4,380.9 C 377.0,380.7 377.7,380.7 378.4,380.7 C 379.1,380.6 379.8,380.6 380.5,380.4 C 381.1,380.2 381.8,380.0 382.5,379.6 C 383.2,379.1 383.9,378.2 384.5,377.7 C 385.2,377.3 385.9,377.1 386.6,376.7 C 387.3,376.4 388.0,376.4 388.6,375.7 C 389.3,375.1 390.0,373.6 390.7,372.9 C 391.4,372.2 392.0,371.9 392.7,371.5 C 393.4,371.0 394.1,371.0 394.8,370.4 C 395.5,369.8 396.1,368.4 396.8,367.7 C 397.5,367.1 398.2,367.0 398.9,366.7 C 399.5,366Line truncated
|
||||
<path d="M 90.0,462.3 C 90.3,462.3 91.7,462.0 92.0,461.9 C 92.7,461.8 93.4,461.7 94.1,461.5 C 94.8,461.4 95.5,461.2 96.1,461.1 C 96.8,461.0 97.5,461.1 98.2,461.0 C 98.9,461.0 99.5,461.0 100.2,460.9 C 100.9,460.9 101.6,460.8 102.3,460.8 C 103.0,460.7 103.3,460.7 104.3,460.7 C 105.3,460.6 107.4,460.6 108.4,460.5 C 109.4,460.5 109.8,460.4 110.5,460.4 C 111.1,460.4 111.8,460.4 112.5,460.4 C 113.2,460.4 113.9,460.3 114.5,460.3 C 115.2,460.3 115.9,460.3 116.6,460.3 C 117.3,460.2 118.0,460.2 118.6,460.1 C 119.3,460.1 120.0,460.1 120.7,459.9 C 121.4,459.8 122.0,459.6 122.7,459.3 C 123.4,459.0 124.1,458.3 124.8,458.1 C 125.5,457.8 126.1,458.0 126.8,457.9 C 127.5,457.9 128.2,457.9 128.9,457.8 C 129.5,457.8 129.9,457.8 130.9,457.7 C 131.9,457.7 133.6,457.7 135.0,457.7 C 136.4,457.7 138.1,457.6 139.1,457.6 C 140.1,457.6 140.5,457.5 141.1,457.5 C 141.8,457.5 142.5,457.4 143.2,457.4 C 143.9,457.4 144.5,457.3 145.2,457.3 C 145.9,457.3 146.6,457.3 147.3,457.3 C 148.0,457.2 148.3,457.2 149.3,457.2 C 150.3,457.2 151.7,457.1 153.4,457.1 C 155.1,457.1 157.8,457.1 159.5,457.1 C 161.2,457.0 161.6,457.1 163.6,457.0 C 165.7,457.0 170.1,456.9 171.8,456.8 C 173.5,456.8 172.8,456.8 173.9,456.8 C 174.9,456.8 176.2,456.8 178.0,456.7 C 179.7,456.7 180.7,456.7 184.1,456.6 C 187.5,456.6 195.7,456.5 198.4,456.5 C 201.1,456.5 199.8,456.5 200.5,456.4 C 201.1,456.4 201.5,457.0 202.5,456.4 C 203.5,455.8 205.6,455.4 206.6,452.9 C 207.6,450.5 208.0,443.8 208.6,441.7 C 209.3,439.7 210.0,440.8 210.7,440.5 C 211.4,440.2 212.0,439.9 212.7,439.7 C 213.4,439.5 214.1,439.3 214.8,439.2 C 215.5,439.1 216.1,439.1 216.8,439.0 C 217.5,438.9 218.2,438.7 218.9,438.7 C 219.5,438.6 220.2,438.7 220.9,438.6 C 221.6,438.6 222.3,438.4 223.0,438.3 C 223.6,438.2 224.3,438.3 225.0,438.2 C 225.7,438.0 226.4,437.7 227.0,437.6 C 227.7,437.5 228.4,437.6 229.1,437.5 C 229.8,437.4 230.5,437.2 231.1,437.1 C 231.8,437.1 232.5,437.1 233.2,437.1 C 233.9,437.1 234.5,437.0 235.2,437.0 C 235.9,436.9 236.6,436.9 237.3,436.8 C 238.0,436.8 238.6,436.8 239.3,436.7 C 240.0,436.6 240.7,436.4 241.4,436.2 C 242.0,436.1 242.7,436.7 243.4,435.9 C 244.1,435.1 244.8,432.3 245.5,431.4 C 246.1,430.5 246.8,430.6 247.5,430.4 C 248.2,430.3 248.9,430.5 249.5,430.4 C 250.2,430.3 250.9,430.0 251.6,429.7 C 252.3,429.5 253.0,429.3 253.6,428.9 C 254.3,428.4 255.0,427.6 255.7,427.1 C 256.4,426.6 257.0,426.0 257.7,425.7 C 258.4,425.3 259.1,425.0 259.8,424.7 C 260.5,424.5 261.1,424.4 261.8,424.3 C 262.5,424.2 263.2,424.2 263.9,424.1 C 264.5,424.0 265.2,423.8 265.9,423.7 C 266.6,423.7 267.3,423.7 268.0,423.6 C 268.6,423.6 269.3,423.6 270.0,423.5 C 270.7,423.4 271.4,423.4 272.0,423.0 C 272.7,422.7 273.4,421.7 274.1,421.3 C 274.8,420.9 275.5,420.7 276.1,420.4 C 276.8,420.1 277.5,420.7 278.2,419.3 C 278.9,418.0 279.5,413.8 280.2,412.2 C 280.9,410.5 281.6,410.3 282.3,409.6 C 283.0,408.9 283.6,408.5 284.3,408.0 C 285.0,407.5 285.7,407.1 286.4,406.7 C 287.0,406.3 287.7,406.0 288.4,405.8 C 289.1,405.6 289.8,405.5 290.5,405.3 C 291.1,405.1 291.8,404.9 292.5,404.6 C 293.2,404.4 293.9,404.0 294.5,403.7 C 295.2,403.5 295.9,403.5 296.6,403.3 C 297.3,403.1 298.0,402.7 298.6,402.4 C 299.3,402.1 300.0,401.9 300.7,401.7 C 301.4,401.5 302.0,401.3 302.7,401.1 C 303.4,401.0 304.1,401.0 304.8,400.9 C 305.5,400.7 306.1,400.6 306.8,400.4 C 307.5,400.3 308.2,400.2 308.9,400.0 C 309.5,399.8 310.2,399.7 310.9,399.4 C 311.6,399.1 312.3,398.6 313.0,398.3 C 313.6,398.1 314.3,398.0 315.0,397.9 C 315.7,397.8 316.4,397.7 317.0,397.6 C 317.7,397.5 318.4,397.4 319.1,397.3 C 319.8,397.2 320.5,397.1 321.1,397.0 C 321.8,396.9 322.5,396.9 323.2,396.8 C 323.9,396.7 324.5,396.6 325.2,396.4 C 325.9,396.1 326.6,395.7 327.3,395.4 C 328.0,395.1 328.6,394.8 329.3,394.6 C 330.0,394.4 330.7,394.4 331.4,394.3 C 332.0,394.1 332.7,394.1 333.4,393.9 C 334.1,393.7 334.8,393.2 335.5,393.1 C 336.1,392.9 336.8,392.9 337.5,392.8 C 338.2,392.7 338.9,392.5 339.5,392.3 C 340.2,392.2 340.9,392.0 341.6,391.9 C 342.3,391.7 343.0,391.5 343.6,391.3 C 344.3,391.2 345.0,391.1 345.7,390.9 C 346.4,390.7 347.0,390.4 347.7,390.2 C 348.4,390.0 349.1,389.9 349.8,389.7 C 350.5,389.5 351.1,389.2 351.8,389.0 C 352.5,388.7 353.2,388.5 353.9,388.3 C 354.5,388.0 355.2,388.0 355.9,387.6 C 356.6,387.3 357.3,386.5 358.0,386.2 C 358.6,385.8 359.3,385.8 360.0,385.7 C 360.7,385.6 361.4,385.6 362.0,385.5 C 362.7,385.4 363.4,385.3 364.1,385.2 C 364.8,385.1 365.5,385.2 366.1,384.9 C 366.8,384.6 367.5,383.6 368.2,383.3 C 368.9,382.9 369.5,383.0 370.2,382.8 C 370.9,382.5 371.6,382.1 372.3,381.9 C 373.0,381.8 373.6,381.9 374.3,381.7 C 375.0,381.5 375.7,381.1 376.4,380.9 C 377.0,380.7 377.7,380.7 378.4,380.7 C 379.1,380.6 379.8,380.6 380.5,380.4 C 381.1,380.2 381.8,380.0 382.5,379.6 C 383.2,379.1 383.9,378.2 384.5,377.7 C 385.2,377.3 385.9,377.1 386.6,376.7 C 387.3,376.4 388.0,376.4 388.6,375.7 C 389.3,375.1 390.0,373.6 390.7,372.9 C 391.4,372.2 392.0,371.9 392.7,371.5 C 393.4,371.0 394.1,371.0 394.8,370.4 C 395.5,369.8 396.1,368.4 396.8,367.7 C 397.5,367.1 398.2,367.0 398.9,366.7 C 399.5,366Line truncated
|
||||
<circle cx="765.0" cy="94.3" r="5" fill="#dd4528" stroke="#fff" stroke-width="2" filter="url(#xkcdify)"/>
|
||||
<text x="753.0" y="77.0" fill="#dd4528" font-size="18" font-family="Handlee, cursive" font-weight="bold" text-anchor="end">7701</text>
|
||||
<a href="https://github.com/carsteneu/mystarhistory" target="_blank" rel="noopener"><text x="763" y="527" font-size="13" font-family="Handlee, cursive" fill="#000" text-anchor="end">Made with carsteneu/mystarhistory</text></a>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 38 KiB After Width: | Height: | Size: 39 KiB |
@@ -13,7 +13,7 @@ mean complete. Existing APIs remain available.
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| Authorization management | Engine `listGrants`, `revokeAll`, database audit | Manager shows declarations only | Host-only grant list, bounded audit summary, disable and revoke | Paths, session IDs, grant metadata are sensitive | Exact plugin ID, trusted app sender | Serialized manager mutation, disable before revoke, runtime teardown, retained audit | Batch 1 limited acceptance complete on ff3734d: independent review fixes, host/manager/UI tests, exact test/packaging CI, parent native own-views Application grant/revoke/disable/runtime-stop check. Visible view was manually closed beforehand. No plugin RPC for managing grants |
|
||||
| Network and credential leases | `network.request`, `credentials.createLease`, single-use host redemption | SDK request omits lease and authorization fields | Canonical request types matching broker | Network mutation and credentials | Exact origin plus secret reference and operation | Existing timeout, redirects, byte quotas, runtime checks, lease TTL | Batch 1 contract/SDK consistency complete: canonical types, synthetic fixture/lease tests, feature discovery and exact CI. No live network or credential acceptance claimed. No plaintext secret API |
|
||||
| Commands, menus, toolbar, status bar, views | `commands.execute`, settings, context keys, view state and messages, UI contributions | No editor or SFTP menu slots | Existing contribution system | Plugin text and arguments may be sensitive | Namespaced contributions and permissions | Existing lifecycle, rate and message limits | Existing tests. New context menu slots planned with bounded context DTOs |
|
||||
| Commands, menus, toolbar, status bar, views | `commands.execute`, settings, context keys, view state and messages, `views.open` (own contributed view + `host-ui.activate`), UI contributions | No editor or SFTP menu slots | Existing contribution system and capability-gated `views.open` for own views | Plugin text and arguments may be sensitive | Namespaced contributions and permissions | Existing lifecycle, rate and message limits; 16 KiB UTF-8 cap on `views.open` params | Existing tests plus unit tests for `views.open` (no live Electron/CI acceptance claimed). New context menu slots planned with bounded context DTOs |
|
||||
| Terminal providers | Decorations, links, completion, snapshots through provider requests | Session change delivery follows prior provider request and non-once grant | Preserve providers. Standalone selected-session watch planned | Hostnames, session state, endpoint identity | Host-selected session, runtime identity | Session-close and revoke cleanup, bounded event rate | Existing provider tests. Ordinary views cannot independently subscribe today |
|
||||
| Current context and host picker | Host context keys are boolean state | `vault.metadata` enumeration is not generic SDK | Selected host/session DTO from an explicit whitelist | Labels and endpoint metadata are sensitive | Host-owned user-action context, selected host/session | TTL, runtime and session invalidation, redacted audit | Planned. Never reuse agent `sanitizeHostForAgent` as plugin DTO |
|
||||
| Terminal selection and input draft | Provider-supplied snapshots, completion suggestions | No explicit selection-share or draft API | User shares selection, plugin proposes a visible editable draft | Terminal plaintext, accidental execution | Host action token plus exact live session/endpoint | Single-use token, size cap, no plaintext audit, active identity before commit | Planned. Reject Enter/control characters for draft insertion. No full history or direct shell |
|
||||
|
||||
@@ -87,6 +87,17 @@ stores only the plugin's own data, not host records or credentials. State scopes
|
||||
separate placements and terminal sessions but are not an authorization boundary
|
||||
against other code in the same plugin.
|
||||
|
||||
A plugin can open or focus one of its own contributed views with
|
||||
`context.views.open({ viewId, params? })` (permission `views`; gated by
|
||||
`views.vault-pages` for `vault-page`, `views.terminal-sidebar` for
|
||||
`terminal-sidebar`, and `views.host-drawn` for `tab`, `aside`, `panel`, and
|
||||
`modal`). Once the view is visible and focused in the main window, the host
|
||||
delivers `{ kind: "host-ui.activate", instanceId, params? }` over
|
||||
`context.views.onDidReceiveMessage(viewId, listener)` for both newly created
|
||||
and retained instances without remounting an existing view. `params` is
|
||||
optional plugin-defined JSON (at most 16 KiB UTF-8 serialized), never host
|
||||
records or credentials, and is not merged into contribution `context`.
|
||||
|
||||
The main process binds each instance to its actual owner window and exact
|
||||
plugin/runtime version. Close during activation, owner navigation/crash, plugin
|
||||
disable/replacement/uninstall, runtime failure and App Lock invalidate it.
|
||||
|
||||
@@ -10,6 +10,13 @@ normal stacking. The plugin receives only the `netcatty.surface: vault-page`
|
||||
context and its own interactions. Selection shares no Vault or session records.
|
||||
|
||||
Leaving and returning retains the view within the bounded lifecycle policy.
|
||||
A plugin with `views` and negotiated `views.vault-pages` may also open or focus
|
||||
its own `vault-page` via `context.views.open({ viewId, params? })`, switching
|
||||
to the Vault tab and selecting that page while delivering
|
||||
`{ kind: "host-ui.activate", instanceId, params? }` to the live instance
|
||||
(retained or newly mounted). Listing still does not auto-activate pages, and
|
||||
`params` is bounded plugin-defined JSON (not host records, credentials, or
|
||||
contribution `context`).
|
||||
Missing/disabled entries, invalid context or failed activation return to Hosts.
|
||||
Late failure from an older selection cannot replace a newer page. App Lock,
|
||||
disable and runtime termination clear the associated content and authority.
|
||||
|
||||
@@ -71,11 +71,15 @@ PSDrive 根的 ProviderPath 可能带尾部反斜杠,因此路径比较按根
|
||||
|
||||
通过 `WSLENV` 为所选发行版的交互会话传递标记。辅助进程在同一发行版和用户下读取 `/proc`,绑定原 Bash 的进程和终端,按 POSIX 路径处理 Linux 目录与挂载盘。检测到同终端的子进程时暂缓导航,原 Bash 恢复后重新读取位置。目录切换使用 Bash 内建 `cd`,以会话 cwd 确认结果。终端换窗口时保留原 shell 类型,目录请求跟随当前显示窗口。枚举目录时,按条目处理读取异常,保留可读的子目录。
|
||||
|
||||
## Cygwin 会话集成
|
||||
|
||||
通过 PTY 的 Windows PID 在同一 Cygwin 安装中定位原 Bash。辅助程序读取 `/proc/<pid>/cwd`,按 Cygwin 路径枚举目录并解析符号链接;切换后以原 Bash 的实际 cwd 确认。会话存在子进程时暂缓操作。WSL 和 Cygwin 共用目录请求与窗口归属检查,分别保留各自的路径解析。
|
||||
|
||||
## 后续设计方向
|
||||
|
||||
- POSIX hook:分别处理 bash 的 PROMPT_COMMAND、zsh 的启动链和 fish 事件,补齐事件上报。
|
||||
- CMD:补充扩展关闭、提示符被启动脚本覆盖、变量展开字符和 UNC 映射场景。
|
||||
- WSL 扩展与 Cygwin:验证各自的发行版或挂载边界,复用目录控制器。
|
||||
- WSL 扩展与 Cygwin:分别覆盖 WSL 2 和其他发行版,以及 Cygwin 自定义挂载前缀和共享路径。
|
||||
- 扩展远程环境:逐项明确活动 shell 与 SFTP/provider 的文件系统对应关系。
|
||||
|
||||
阶段交付与推进顺序统一维护在 [开发计划](directory-picker-follow-up.md)。
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
| C:CMD | 交互 CMD 的 PROMPT 上报;盘符目录读取与 `cd /d` 切换;原进程和新提示符确认 | 复用目录控制器,按 CMD 的变量展开和进程继承划定支持范围 |
|
||||
| D1:Git Bash | 绑定原 Git for Windows Bash,读取 MSYS cwd 并映射为 Windows 盘符路径 | 保留 Bash 启动行为,复用 Windows 文件系统和目录控制器 |
|
||||
| D2:WSL | 从原交互 Bash 读取 POSIX cwd,在同发行版和用户下解析路径、枚举目录并确认切换 | 保留 WSL 启动配置,让 Linux 目录和 Windows 挂载盘共享同一会话身份 |
|
||||
| D3:Cygwin | 在原 Bash 的路径命名空间中读取、枚举和切换目录 | 由同一安装的工具解析盘符挂载和目录符号链接 |
|
||||
| 状态恢复 | provider 切换清空旧目录与列表;恢复 FileSystem 后重新读取;提交输入使旧报告失效 | 让菜单始终对应当前有效的文件系统位置 |
|
||||
| 生命周期 | 单会话请求排序、旧控制器失效、受管脚本清理、终端就绪门控 | 将异步操作与实际会话代次绑定 |
|
||||
|
||||
@@ -20,12 +21,10 @@ Windows CI 使用原生 ConPTY 覆盖 PowerShell 5.1/7 以及 CMD 的特殊字
|
||||
|
||||
| PR 顺序 | 交付范围 |
|
||||
| --- | --- |
|
||||
| 1. WSL | Ubuntu Bash 的 Directory Picker,覆盖 Linux 目录和挂载盘。 |
|
||||
| 2. Cygwin | 识别原 Bash 及其挂载,接入目录枚举、跳转和确认。 |
|
||||
| 3. Git Branch | 识别当前工作树,读取分支并确认切换。见 [Git Branch](git-branch.md)。 |
|
||||
| 4. Git Changes | 复用工作树状态,提供变更统计和详情入口。见 [Git Changes](git-changes.md)。 |
|
||||
| 5. Pull Request | 使用当前工作树和分支关联托管服务。见 [Pull Request](pull-request.md)。 |
|
||||
| 6. Node Version | 独立接入当前 shell 和版本管理器。见 [Node Version](node-version.md)。 |
|
||||
| 1. Git Branch | 识别当前工作树,读取分支并确认切换。见 [Git Branch](git-branch.md)。 |
|
||||
| 2. Git Changes | 复用工作树状态,提供变更统计和详情入口。见 [Git Changes](git-changes.md)。 |
|
||||
| 3. Pull Request | 使用当前工作树和分支关联托管服务。见 [Pull Request](pull-request.md)。 |
|
||||
| 4. Node Version | 独立接入当前 shell 和版本管理器。见 [Node Version](node-version.md)。 |
|
||||
|
||||
### PowerShell 覆盖扩展
|
||||
|
||||
@@ -54,7 +53,7 @@ Windows CI 使用原生 ConPTY 覆盖 PowerShell 5.1/7 以及 CMD 的特殊字
|
||||
|
||||
### D3:Cygwin
|
||||
|
||||
先确认 Cygwin 进程与终端的对应关系,再验证 `/cygdrive`、自定义挂载、符号链接和 Unicode。由同一安装的工具读取 cwd 和目录,保留原路径命名空间。Git Bash 后续扩展共享路径和虚拟挂载。
|
||||
已覆盖 `/cygdrive`、Unicode、目录符号链接与多窗口会话。后续验证自定义挂载前缀和共享路径,再扩展对应的根目录和父级规则。Git Bash 的共享路径和虚拟挂载单独扩展。
|
||||
|
||||
### E:扩展远程与嵌套 shell
|
||||
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import {
|
||||
applySessionTitleIfCurrent,
|
||||
buildFallbackTitle,
|
||||
canAutoTitleSession,
|
||||
resolveCattyEffectiveModel,
|
||||
resolveEffectiveTitleModelConfig,
|
||||
SESSION_TITLE_MAX_CHARS,
|
||||
SESSION_TITLE_PLACEHOLDER,
|
||||
} from './aiSessionTitle.ts';
|
||||
import type { AISession, ProviderConfig } from '../infrastructure/ai/types.ts';
|
||||
|
||||
const makeProvider = (overrides: Partial<ProviderConfig> = {}): ProviderConfig => ({
|
||||
id: 'p-1',
|
||||
providerId: 'openai',
|
||||
name: 'OpenAI',
|
||||
enabled: true,
|
||||
defaultModel: 'gpt-4o',
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const makeSession = (overrides: Partial<AISession> = {}): AISession => ({
|
||||
id: 's-1',
|
||||
title: SESSION_TITLE_PLACEHOLDER,
|
||||
agentId: 'catty',
|
||||
scope: { type: 'global' },
|
||||
messages: [],
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
test('buildFallbackTitle normalizes whitespace and truncates cleanly', () => {
|
||||
assert.equal(buildFallbackTitle(' check\n\tdisk usage '), 'check disk usage');
|
||||
assert.equal(
|
||||
buildFallbackTitle('a'.repeat(SESSION_TITLE_MAX_CHARS + 5)),
|
||||
`${'a'.repeat(SESSION_TITLE_MAX_CHARS)}...`,
|
||||
);
|
||||
// Surrogate pair boundary: 50 emoji should not split mid-surrogate.
|
||||
const emoji = '🚀'.repeat(SESSION_TITLE_MAX_CHARS + 2);
|
||||
assert.equal(buildFallbackTitle(emoji), `${'🚀'.repeat(SESSION_TITLE_MAX_CHARS)}...`);
|
||||
});
|
||||
|
||||
test('canAutoTitleSession accepts empty or placeholder titles only', () => {
|
||||
assert.equal(canAutoTitleSession(undefined), false);
|
||||
assert.equal(canAutoTitleSession(makeSession({ title: '' })), true);
|
||||
assert.equal(canAutoTitleSession(makeSession({ title: SESSION_TITLE_PLACEHOLDER })), true);
|
||||
assert.equal(canAutoTitleSession(makeSession({ title: 'Existing title' })), false);
|
||||
});
|
||||
|
||||
test('applySessionTitleIfCurrent updates atomically only when expected title matches', () => {
|
||||
const initial = [makeSession({ id: 's-1', title: SESSION_TITLE_PLACEHOLDER, updatedAt: 10 })];
|
||||
|
||||
// Phase 1: placeholder -> fallback.
|
||||
const phase1 = applySessionTitleIfCurrent(initial, 's-1', 'Check nginx logs', undefined, 20);
|
||||
assert.equal(phase1.updated, true);
|
||||
assert.equal(phase1.sessions[0].title, 'Check nginx logs');
|
||||
assert.equal(phase1.sessions[0].updatedAt, 20);
|
||||
|
||||
// User renamed before Phase 2 settles -> Phase 2 must NOT overwrite.
|
||||
const renamed = [{ ...phase1.sessions[0], title: 'Prod nginx audit', updatedAt: 30 }];
|
||||
const rejected = applySessionTitleIfCurrent(renamed, 's-1', 'Nginx Log Check', 'Check nginx logs', 40);
|
||||
assert.equal(rejected.updated, false);
|
||||
assert.equal(rejected.sessions, renamed);
|
||||
assert.equal(rejected.sessions[0].title, 'Prod nginx audit');
|
||||
|
||||
// Matching expected title -> Phase 2 succeeds.
|
||||
const promoted = applySessionTitleIfCurrent(phase1.sessions, 's-1', 'Nginx Log Check', 'Check nginx logs', 40);
|
||||
assert.equal(promoted.updated, true);
|
||||
assert.equal(promoted.sessions[0].title, 'Nginx Log Check');
|
||||
assert.equal(promoted.sessions[0].updatedAt, 40);
|
||||
|
||||
// Identical nextTitle is a no-op (does not bump updatedAt).
|
||||
const noop = applySessionTitleIfCurrent(phase1.sessions, 's-1', 'Check nginx logs', 'Check nginx logs', 50);
|
||||
assert.equal(noop.updated, false);
|
||||
assert.equal(noop.sessions[0].updatedAt, 20);
|
||||
});
|
||||
|
||||
test('resolveCattyEffectiveModel and resolveEffectiveTitleModelConfig match Catty inheritance', () => {
|
||||
const cheap = makeProvider({ id: 'p-cheap', name: 'DeepSeek', defaultModel: 'deepseek-chat' });
|
||||
const main = makeProvider({ id: 'p-main', name: 'Anthropic', providerId: 'anthropic', defaultModel: 'claude-sonnet' });
|
||||
const disabled = makeProvider({ id: 'p-off', name: 'Disabled', enabled: false, defaultModel: 'm-off' });
|
||||
const providers = [cheap, main, disabled];
|
||||
|
||||
const catty = resolveCattyEffectiveModel({
|
||||
providers,
|
||||
activeProviderId: 'p-cheap',
|
||||
activeModelId: 'deepseek-chat',
|
||||
agentProviderMap: { catty: 'p-main' },
|
||||
agentModelMap: { catty: 'claude-opus' },
|
||||
});
|
||||
assert.equal(catty.provider?.id, 'p-main');
|
||||
assert.equal(catty.modelId, 'claude-opus');
|
||||
|
||||
// titleModel === null inherits Catty's effective provider/model, NOT providers[0].
|
||||
const inherited = resolveEffectiveTitleModelConfig({
|
||||
titleModel: null,
|
||||
providers,
|
||||
activeProviderId: 'p-cheap',
|
||||
activeModelId: 'deepseek-chat',
|
||||
agentProviderMap: { catty: 'p-main' },
|
||||
agentModelMap: { catty: 'claude-opus' },
|
||||
});
|
||||
assert.equal(inherited?.id, 'p-main');
|
||||
assert.equal(inherited?.defaultModel, 'claude-opus');
|
||||
|
||||
// Explicit titleModel overrides Catty.
|
||||
const explicit = resolveEffectiveTitleModelConfig({
|
||||
titleModel: { providerId: 'p-cheap', modelId: 'deepseek-chat' },
|
||||
providers,
|
||||
activeProviderId: 'p-main',
|
||||
activeModelId: 'claude-opus',
|
||||
agentProviderMap: {},
|
||||
agentModelMap: {},
|
||||
});
|
||||
assert.equal(explicit?.id, 'p-cheap');
|
||||
assert.equal(explicit?.defaultModel, 'deepseek-chat');
|
||||
|
||||
// Incomplete or disabled explicit config never mixes provider/model or falls back silently.
|
||||
assert.equal(
|
||||
resolveEffectiveTitleModelConfig({
|
||||
titleModel: { providerId: 'p-cheap', modelId: '' },
|
||||
providers,
|
||||
activeProviderId: 'p-main',
|
||||
activeModelId: 'claude-opus',
|
||||
agentProviderMap: {},
|
||||
agentModelMap: {},
|
||||
}),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
resolveEffectiveTitleModelConfig({
|
||||
titleModel: { providerId: 'p-off', modelId: 'm-off' },
|
||||
providers,
|
||||
activeProviderId: 'p-main',
|
||||
activeModelId: 'claude-opus',
|
||||
agentProviderMap: {},
|
||||
agentModelMap: {},
|
||||
}),
|
||||
null,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
import type { AISession, ProviderConfig } from '../infrastructure/ai/types';
|
||||
|
||||
export const SESSION_TITLE_PLACEHOLDER = 'New Chat';
|
||||
export const SESSION_TITLE_MAX_CHARS = 50;
|
||||
|
||||
/** Provider + model chosen for one-shot session-title generation. */
|
||||
export interface TitleModelConfig {
|
||||
providerId: string;
|
||||
modelId: string;
|
||||
}
|
||||
|
||||
export interface CattyModelResolutionInput {
|
||||
providers: readonly ProviderConfig[];
|
||||
activeProviderId: string;
|
||||
activeModelId: string;
|
||||
agentProviderMap: Readonly<Record<string, string>>;
|
||||
agentModelMap: Readonly<Record<string, string>>;
|
||||
}
|
||||
|
||||
export interface EffectiveCattyModel {
|
||||
provider: ProviderConfig | undefined;
|
||||
modelId: string;
|
||||
}
|
||||
|
||||
export interface TitleModelResolutionInput extends CattyModelResolutionInput {
|
||||
titleModel: TitleModelConfig | null | undefined;
|
||||
}
|
||||
|
||||
function trimText(value: string | undefined | null): string {
|
||||
return (value ?? '').trim();
|
||||
}
|
||||
|
||||
/** Deterministic fallback: first user message truncated to 50 chars + "...". */
|
||||
export function buildFallbackTitle(text: string): string {
|
||||
const normalized = text.replace(/\s+/g, ' ').trim();
|
||||
const chars = Array.from(normalized);
|
||||
return chars.length > SESSION_TITLE_MAX_CHARS
|
||||
? `${chars.slice(0, SESSION_TITLE_MAX_CHARS).join('')}...`
|
||||
: normalized;
|
||||
}
|
||||
|
||||
/** Whether a session currently carries no user/LLM title and is eligible for auto-titling. */
|
||||
export function canAutoTitleSession(
|
||||
session: Pick<AISession, 'title'> | null | undefined,
|
||||
): boolean {
|
||||
if (!session) return false;
|
||||
return !session.title || session.title === SESSION_TITLE_PLACEHOLDER;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure atomic title update.
|
||||
*
|
||||
* - When `expectedTitle` is omitted, applies `nextTitle` only if the session
|
||||
* still exists and is untitled (`!title || title === SESSION_TITLE_PLACEHOLDER`).
|
||||
* - When `expectedTitle` is provided, applies `nextTitle` only if the session
|
||||
* still exists and its current title equals `expectedTitle` strictly.
|
||||
*/
|
||||
export function applySessionTitleIfCurrent<T extends Pick<AISession, 'id' | 'title' | 'updatedAt'>>(
|
||||
sessions: readonly T[],
|
||||
sessionId: string,
|
||||
nextTitle: string,
|
||||
expectedTitle?: string,
|
||||
now: number = Date.now(),
|
||||
): { sessions: T[]; updated: boolean } {
|
||||
const index = sessions.findIndex((session) => session.id === sessionId);
|
||||
if (index === -1) return { sessions: sessions as T[], updated: false };
|
||||
|
||||
const current = sessions[index];
|
||||
if (expectedTitle === undefined) {
|
||||
if (!canAutoTitleSession(current)) {
|
||||
return { sessions: sessions as T[], updated: false };
|
||||
}
|
||||
} else if (current.title !== expectedTitle) {
|
||||
return { sessions: sessions as T[], updated: false };
|
||||
}
|
||||
|
||||
if (current.title === nextTitle) {
|
||||
return { sessions: sessions as T[], updated: false };
|
||||
}
|
||||
|
||||
const next = sessions.slice();
|
||||
next[index] = {
|
||||
...current,
|
||||
title: nextTitle,
|
||||
updatedAt: now,
|
||||
};
|
||||
return { sessions: next, updated: true };
|
||||
}
|
||||
|
||||
/** Resolve Catty Agent's effective provider and model ID from settings + per-agent overrides. */
|
||||
export function resolveCattyEffectiveModel(
|
||||
input: CattyModelResolutionInput,
|
||||
): EffectiveCattyModel {
|
||||
const activeProvider = input.providers.find((provider) => provider.id === input.activeProviderId);
|
||||
const overrideId = input.agentProviderMap['catty'];
|
||||
const overrideProvider = overrideId
|
||||
? input.providers.find((provider) => provider.id === overrideId)
|
||||
: undefined;
|
||||
const provider = overrideProvider ?? activeProvider;
|
||||
const modelId = overrideProvider
|
||||
? (trimText(input.agentModelMap['catty']) || trimText(overrideProvider.defaultModel))
|
||||
: (trimText(provider?.defaultModel) || trimText(input.activeModelId));
|
||||
return { provider, modelId };
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the effective provider config for one-shot title generation:
|
||||
* an explicit, valid `titleModel` if set, otherwise Catty's current provider/model.
|
||||
* Returns `null` if the resolved provider is missing, disabled, or lacks a model.
|
||||
*/
|
||||
export function resolveEffectiveTitleModelConfig(
|
||||
input: TitleModelResolutionInput,
|
||||
): ProviderConfig | null {
|
||||
const explicitProviderId = trimText(input.titleModel?.providerId);
|
||||
const explicitModelId = trimText(input.titleModel?.modelId);
|
||||
|
||||
if (explicitProviderId || explicitModelId) {
|
||||
if (!explicitProviderId || !explicitModelId) return null;
|
||||
const base = input.providers.find((provider) => provider.id === explicitProviderId);
|
||||
if (!base || !base.enabled) return null;
|
||||
return { ...base, id: explicitProviderId, defaultModel: explicitModelId };
|
||||
}
|
||||
|
||||
const catty = resolveCattyEffectiveModel(input);
|
||||
if (!catty.provider || !catty.provider.enabled || !catty.modelId) return null;
|
||||
return { ...catty.provider, id: catty.provider.id, defaultModel: catty.modelId };
|
||||
}
|
||||
@@ -3,8 +3,8 @@ import { resolveInteractiveTerminalCdIntent } from './sessionRestore';
|
||||
import { isAbsoluteDirectoryPath, joinDirectoryPath, labelDirectoryPath, parentDirectoryPath, type DirectoryPathFlavor } from './directoryPath';
|
||||
|
||||
export type DirectoryEntry = { name: string; path: string; hidden: boolean };
|
||||
export type WindowsDirectoryShell = 'powershell' | 'cmd' | 'git-bash' | 'wsl';
|
||||
export type DirectoryPickerErrorCode = 'unavailable' | 'unknown' | 'busy' | 'readFailed' | 'accessDenied' | 'changeFailed' | 'unsupportedPath' | 'integrationUnavailable' | 'cmdIntegrationUnavailable' | 'gitBashIntegrationUnavailable' | 'wslIntegrationUnavailable' | 'nonFilesystem';
|
||||
export type WindowsDirectoryShell = 'powershell' | 'cmd' | 'git-bash' | 'wsl' | 'cygwin';
|
||||
export type DirectoryPickerErrorCode = 'unavailable' | 'unknown' | 'busy' | 'readFailed' | 'accessDenied' | 'changeFailed' | 'unsupportedPath' | 'integrationUnavailable' | 'cmdIntegrationUnavailable' | 'gitBashIntegrationUnavailable' | 'wslIntegrationUnavailable' | 'cygwinIntegrationUnavailable' | 'nonFilesystem';
|
||||
|
||||
export class DirectoryPickerError extends Error {
|
||||
constructor(public readonly code: DirectoryPickerErrorCode) { super(code); }
|
||||
@@ -55,7 +55,8 @@ export function directoryChangeCommand(path: string, shell: 'posix' | WindowsDir
|
||||
const target = path.replace(/\\/g, '/').replace(/'/g, "'\\''");
|
||||
return `\\builtin cd -- '${target}'`;
|
||||
}
|
||||
if (shell === 'wsl') return flavor === 'posix' ? `\\builtin cd -- '${path.replace(/'/g, "'\\''")}'` : null;
|
||||
if (shell === 'cygwin' && path.startsWith('//')) return null;
|
||||
if (shell === 'wsl' || shell === 'cygwin') return flavor === 'posix' ? `\\builtin cd -- '${path.replace(/'/g, "'\\''")}'` : null;
|
||||
return flavor === 'posix' ? resolveInteractiveTerminalCdIntent(path)?.command ?? null : null;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import en from '../application/i18n/locales/en.ts';
|
||||
import es from '../application/i18n/locales/es.ts';
|
||||
import ru from '../application/i18n/locales/ru.ts';
|
||||
import zhCN from '../application/i18n/locales/zh-CN.ts';
|
||||
import zhTW from '../application/i18n/locales/zh-TW.ts';
|
||||
import {
|
||||
getAppLevelActions,
|
||||
getTerminalPassthroughActions,
|
||||
} from '../application/state/useGlobalHotkeys.ts';
|
||||
import { findActiveSystemShortcutConflict } from './activeKeyBindings.ts';
|
||||
import { resolveKeyBindings } from './customKeyBindings.ts';
|
||||
import { DEFAULT_KEY_BINDINGS, matchesKeyBinding } from './models/keyBindings.ts';
|
||||
|
||||
test('add-session-to-workspace defaults to Cmd+N on macOS and Ctrl+N on PC without conflicts', () => {
|
||||
const binding = DEFAULT_KEY_BINDINGS.find((entry) => entry.id === 'add-session-to-workspace');
|
||||
assert.ok(binding, 'add-session-to-workspace must exist in DEFAULT_KEY_BINDINGS');
|
||||
assert.equal(binding.action, 'addSessionToWorkspace');
|
||||
assert.equal(binding.label, 'Add Session to Workspace');
|
||||
assert.equal(binding.category, 'app');
|
||||
assert.equal(binding.mac, '⌘ + N');
|
||||
assert.equal(binding.pc, 'Ctrl + N');
|
||||
|
||||
assert.deepEqual(
|
||||
DEFAULT_KEY_BINDINGS.filter((entry) => entry.mac === binding.mac).map((entry) => entry.id),
|
||||
['add-session-to-workspace'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
DEFAULT_KEY_BINDINGS.filter((entry) => entry.pc === binding.pc).map((entry) => entry.id),
|
||||
['add-session-to-workspace'],
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
findActiveSystemShortcutConflict('⌘ + N', 'mac', DEFAULT_KEY_BINDINGS)?.id,
|
||||
'add-session-to-workspace',
|
||||
);
|
||||
assert.equal(
|
||||
findActiveSystemShortcutConflict('Ctrl + N', 'pc', DEFAULT_KEY_BINDINGS)?.id,
|
||||
'add-session-to-workspace',
|
||||
);
|
||||
|
||||
// Conditional shortcuts stay out of both fixed terminal passthrough and
|
||||
// unconditional app-level short-circuit sets so unconsumed events keep full
|
||||
// terminal handling (legacy, Kitty, Win32, broadcast).
|
||||
assert.equal(getTerminalPassthroughActions().has('addSessionToWorkspace'), false);
|
||||
assert.equal(getAppLevelActions().has('addSessionToWorkspace'), false);
|
||||
|
||||
assert.equal(
|
||||
matchesKeyBinding(
|
||||
{ key: 'n', code: 'KeyN', metaKey: true, ctrlKey: false, altKey: false, shiftKey: false } as KeyboardEvent,
|
||||
binding.mac,
|
||||
true,
|
||||
),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
matchesKeyBinding(
|
||||
{ key: 'n', code: 'KeyN', metaKey: false, ctrlKey: true, altKey: false, shiftKey: false } as KeyboardEvent,
|
||||
binding.pc,
|
||||
false,
|
||||
),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
matchesKeyBinding(
|
||||
{ key: 'N', code: 'KeyN', metaKey: false, ctrlKey: true, altKey: false, shiftKey: true } as KeyboardEvent,
|
||||
binding.pc,
|
||||
false,
|
||||
),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
matchesKeyBinding(
|
||||
{ key: 'n', code: 'KeyN', metaKey: false, ctrlKey: true, altKey: false, shiftKey: false } as KeyboardEvent,
|
||||
binding.mac,
|
||||
true,
|
||||
),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test('custom app shortcuts evict add-session-to-workspace defaults per scheme while SFTP overrides leave it intact', () => {
|
||||
const pcOverride = resolveKeyBindings(DEFAULT_KEY_BINDINGS, {
|
||||
'open-hosts': { pc: 'Ctrl + N' },
|
||||
});
|
||||
assert.equal(pcOverride.find((entry) => entry.id === 'add-session-to-workspace')?.pc, 'Disabled');
|
||||
assert.equal(pcOverride.find((entry) => entry.id === 'add-session-to-workspace')?.mac, '⌘ + N');
|
||||
|
||||
const sftpOverride = resolveKeyBindings(DEFAULT_KEY_BINDINGS, {
|
||||
'sftp-new-folder': { pc: 'Ctrl + N', mac: '⌘ + N' },
|
||||
});
|
||||
assert.equal(sftpOverride.find((entry) => entry.id === 'add-session-to-workspace')?.pc, 'Ctrl + N');
|
||||
assert.equal(sftpOverride.find((entry) => entry.id === 'add-session-to-workspace')?.mac, '⌘ + N');
|
||||
});
|
||||
|
||||
test('add-session-to-workspace shortcut and workspace tab menu labels are localized across all locales', () => {
|
||||
const locales = [
|
||||
['en', en],
|
||||
['es', es],
|
||||
['ru', ru],
|
||||
['zh-CN', zhCN],
|
||||
['zh-TW', zhTW],
|
||||
] as const;
|
||||
|
||||
for (const [name, messages] of locales) {
|
||||
assert.ok(messages['settings.shortcuts.binding.add-session-to-workspace']?.trim(), `${name} shortcut label`);
|
||||
assert.ok(messages['tabs.addSessionToWorkspace']?.trim(), `${name} tab menu label`);
|
||||
if (name !== 'en') {
|
||||
assert.notEqual(
|
||||
messages['settings.shortcuts.binding.add-session-to-workspace'],
|
||||
en['settings.shortcuts.binding.add-session-to-workspace'],
|
||||
`${name} shortcut label should be localized`,
|
||||
);
|
||||
assert.notEqual(
|
||||
messages['tabs.addSessionToWorkspace'],
|
||||
en['tabs.addSessionToWorkspace'],
|
||||
`${name} tab menu label should be localized`,
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import test from "node:test";
|
||||
|
||||
import {
|
||||
getExportablePublicKey,
|
||||
hasExportablePublicKey,
|
||||
isKeychainExportDisabled,
|
||||
} from "./keychainExport.ts";
|
||||
|
||||
test("getExportablePublicKey trims valid keys and rejects missing or blank values", () => {
|
||||
assert.equal(getExportablePublicKey(undefined), null);
|
||||
assert.equal(getExportablePublicKey(null), null);
|
||||
assert.equal(getExportablePublicKey(""), null);
|
||||
assert.equal(getExportablePublicKey(" \n\t "), null);
|
||||
assert.equal(
|
||||
getExportablePublicKey(" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA \n"),
|
||||
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA",
|
||||
);
|
||||
});
|
||||
|
||||
test("hasExportablePublicKey treats missing and whitespace-only values as missing", () => {
|
||||
assert.equal(hasExportablePublicKey(undefined), false);
|
||||
assert.equal(hasExportablePublicKey(""), false);
|
||||
assert.equal(hasExportablePublicKey(" \t\r\n "), false);
|
||||
assert.equal(hasExportablePublicKey("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA"), true);
|
||||
});
|
||||
|
||||
test("isKeychainExportDisabled disables export when public key is missing or blank", () => {
|
||||
const ready = {
|
||||
exportHost: { id: "host-1" },
|
||||
exportLocation: ".ssh",
|
||||
exportFilename: "authorized_keys",
|
||||
publicKey: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA",
|
||||
isExporting: false,
|
||||
};
|
||||
|
||||
assert.equal(isKeychainExportDisabled(ready), false);
|
||||
assert.equal(isKeychainExportDisabled({ ...ready, publicKey: undefined }), true);
|
||||
assert.equal(isKeychainExportDisabled({ ...ready, publicKey: "" }), true);
|
||||
assert.equal(isKeychainExportDisabled({ ...ready, publicKey: " \n\t " }), true);
|
||||
assert.equal(isKeychainExportDisabled({ ...ready, exportHost: null }), true);
|
||||
assert.equal(isKeychainExportDisabled({ ...ready, exportLocation: "" }), true);
|
||||
assert.equal(isKeychainExportDisabled({ ...ready, exportFilename: "" }), true);
|
||||
assert.equal(isKeychainExportDisabled({ ...ready, isExporting: true }), true);
|
||||
});
|
||||
|
||||
test("KeychainExportPanel wires missing public key disable, hint, and error toast", () => {
|
||||
const source = readFileSync(
|
||||
join(import.meta.dirname, "../components/KeychainExportPanel.tsx"),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
assert.doesNotMatch(source, /if\s*\(\s*!exportHost\s*\|\|\s*!panel\.key\.publicKey\s*\)\s*return;/);
|
||||
assert.match(source, /isKeychainExportDisabled\(/);
|
||||
assert.match(source, /t\("keychain\.export\.missingPublicKeyNote"\)/);
|
||||
assert.match(
|
||||
source,
|
||||
/toast\.error\(\s*t\("keychain\.export\.missingPublicKey"\),\s*t\("keychain\.export\.failedTitle"\),?\s*\)/,
|
||||
);
|
||||
});
|
||||
|
||||
test("all five terminal locale files define missingPublicKey and missingPublicKeyNote", () => {
|
||||
for (const locale of ["en", "zh-CN", "zh-TW", "es", "ru"]) {
|
||||
const source = readFileSync(
|
||||
join(import.meta.dirname, `../application/i18n/locales/${locale}/terminal.ts`),
|
||||
"utf8",
|
||||
);
|
||||
assert.match(source, /'keychain\.export\.missingPublicKey':/, `${locale} missing toast key`);
|
||||
assert.match(source, /'keychain\.export\.missingPublicKeyNote':/, `${locale} missing note key`);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
export function getExportablePublicKey(publicKey?: string | null): string | null {
|
||||
if (typeof publicKey !== "string") return null;
|
||||
const trimmed = publicKey.trim();
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
export function hasExportablePublicKey(publicKey?: string | null): boolean {
|
||||
return getExportablePublicKey(publicKey) !== null;
|
||||
}
|
||||
|
||||
export function isKeychainExportDisabled(params: {
|
||||
exportHost: unknown;
|
||||
exportLocation: string;
|
||||
exportFilename: string;
|
||||
publicKey?: string | null;
|
||||
isExporting: boolean;
|
||||
}): boolean {
|
||||
return (
|
||||
!params.exportHost ||
|
||||
!params.exportLocation ||
|
||||
!params.exportFilename ||
|
||||
!hasExportablePublicKey(params.publicKey) ||
|
||||
params.isExporting
|
||||
);
|
||||
}
|
||||
@@ -271,6 +271,7 @@ export const DEFAULT_KEY_BINDINGS: KeyBinding[] = [
|
||||
{ id: 'command-palette', action: 'commandPalette', label: 'Open Command Palette', mac: '⌘ + K', pc: 'Ctrl + K', category: 'app' },
|
||||
{ id: 'quick-switch', action: 'quickSwitch', label: 'Quick Switch', mac: '⌘ + J', pc: 'Ctrl + J', category: 'app' },
|
||||
{ id: 'new-workspace', action: 'newWorkspace', label: 'New Workspace', mac: '⌘ + Shift + J', pc: 'Ctrl + Shift + J', category: 'app' },
|
||||
{ id: 'add-session-to-workspace', action: 'addSessionToWorkspace', label: 'Add Session to Workspace', mac: '⌘ + N', pc: 'Ctrl + N', category: 'app' },
|
||||
{ id: 'snippets', action: 'snippets', label: 'Open Snippets', mac: '⌘ + Shift + S', pc: 'Ctrl + Shift + S', category: 'app' },
|
||||
{ id: 'broadcast', action: 'broadcast', label: 'Switch the Broadcast Mode', mac: '⌘ + B', pc: 'Ctrl + B', category: 'app' },
|
||||
{ id: 'toggle-side-panel', action: 'toggleSidePanel', label: 'Toggle Side Panel', mac: '⌘ + \\', pc: 'Ctrl + \\', category: 'app' },
|
||||
|
||||
Loaded 100 of 181 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user