mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-27 03:10:47 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
17fa55bedc | ||
|
|
6236f5bb95 | ||
|
|
db433c4c19 | ||
|
|
93c74cb068 | ||
|
|
a0f7a376db |
No files matched your search
@@ -331,6 +331,26 @@ export function handleGlobalHotkeyKeyDownImpl(getCtx: AppContextGetter, e: Keybo
|
||||
if (binding.category === 'sftp') {
|
||||
continue;
|
||||
}
|
||||
if (binding.action === 'commandPalette') {
|
||||
const hasOpenHostModal = Array.from(
|
||||
document.querySelectorAll<HTMLElement>('[role="dialog"][aria-modal="true"]:not([data-plugin-dialog])'),
|
||||
).some((el) => {
|
||||
const r = el.getBoundingClientRect();
|
||||
return r.width > 0 && r.height > 0;
|
||||
});
|
||||
if (!hasOpenHostModal) {
|
||||
const inPluginSurface = Boolean(target?.closest?.('[data-plugin-remote-surface]'));
|
||||
const activeFullBleedSurface = inPluginSurface || Array.from(
|
||||
document.querySelectorAll<HTMLElement>('[data-plugin-chrome="full-bleed"] [data-plugin-remote-surface]'),
|
||||
).some((el) => {
|
||||
const r = el.getBoundingClientRect();
|
||||
return r.width > 0 && r.height > 0;
|
||||
});
|
||||
if (activeFullBleedSurface) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (TERMINAL_PASSTHROUGH_ACTIONS.has(binding.action)) {
|
||||
if (isTerminalElement) {
|
||||
return;
|
||||
|
||||
@@ -281,7 +281,7 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
handleEndSessionDrag, handleFollowAppTerminalThemeChange, handleHostConnectWithProtocolCheck, handleHotkeyAction, handleKeyboardInteractiveCancel, handleKeyboardInteractiveSubmit,
|
||||
handleOpenHostFromVaultNote, handleOpenQuickSwitcher, handleOpenSettings, handleOpenVaultHostFromChat, handleOpenVaultNoteFromChat, handleOpenVaultSectionFromChat, handleOpenVaultSnippetFromChat, handleRootContextMenu, handlePassphraseCancel, handlePassphraseSkip, handlePassphraseSubmit, handleFidoPromptSubmit, handleFidoPromptCancel, handleProtocolSelect,
|
||||
handleRequestCloseEditorTabRef, handleSessionStatusChange, handleSyncNowManual, handleTerminalDataCapture, handleUpdateHostFromTerminal,
|
||||
hostById, hosts, terminalHosts, updateTerminalHosts, hotkeyScheme, identities, importOrReuseKey, isBroadcastEnabled, isComposeSendToAll, onToggleComposeSendTarget, isGlobalBroadcastEnabled, isGlobalComposeSendToAll, onToggleGlobalBroadcast, onToggleGlobalComposeSendTarget, canUseGlobalBroadcast, isCreateWorkspaceOpen, isMacClient, isQuickSwitcherOpen,
|
||||
hostById, hosts, terminalHosts, updateTerminalHosts, hotkeyScheme, identities, importOrReuseKey, isVaultInitialized, isBroadcastEnabled, isComposeSendToAll, onToggleComposeSendTarget, isGlobalBroadcastEnabled, isGlobalComposeSendToAll, onToggleGlobalBroadcast, onToggleGlobalComposeSendTarget, canUseGlobalBroadcast, isCreateWorkspaceOpen, isMacClient, isQuickSwitcherOpen,
|
||||
keyBindings, keyboardInteractiveQueue, keys, logViews, managedSources, navigateToSection, openLogView, openNoteRequest, orderedTabsWithEditors, orphanSessions,
|
||||
passphraseQueue, fidoPromptQueue, protocolSelectHost, proxyProfiles, portForwardingRules, removeSessionFromWorkspace, reorderWorkTabs, reorderWorkspaceSessions,
|
||||
resolveEmptyVaultConflict, resolveSessionAppearance, runSnippet, sessionLogsDir, sessionLogsEnabled, sessionLogsFormat, sessionLogsTimestampsEnabled, sessionRenameTarget, sshDebugLogsEnabled,
|
||||
@@ -734,6 +734,7 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
/>
|
||||
|
||||
<TerminalLayerMount
|
||||
isVaultInitialized={isVaultInitialized}
|
||||
hosts={terminalHosts}
|
||||
portForwardingRules={portForwardingRules}
|
||||
customGroups={customGroups}
|
||||
|
||||
@@ -55,6 +55,7 @@ export function VaultHost() {
|
||||
hosts: vault.hosts,
|
||||
identities: vault.identities,
|
||||
importOrReuseKey: actions?.importOrReuseKey,
|
||||
isVaultInitialized: vault.isVaultInitialized,
|
||||
keys: vault.keys,
|
||||
managedSources: vault.managedSources,
|
||||
navigateToSection: local.navigateToSection,
|
||||
@@ -90,6 +91,7 @@ export function VaultHost() {
|
||||
vault.groupConfigs,
|
||||
vault.hosts,
|
||||
vault.identities,
|
||||
vault.isVaultInitialized,
|
||||
vault.keys,
|
||||
vault.managedSources,
|
||||
vault.proxyProfiles,
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import React, { useEffect, useLayoutEffect } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { JSDOM } from 'jsdom';
|
||||
|
||||
import {
|
||||
EMPTY_VAULT_SNAPSHOT,
|
||||
publishVaultSnapshot,
|
||||
useVaultSnapshot,
|
||||
useVaultSnapshotField,
|
||||
} from '../state/vaultSnapshotStore.ts';
|
||||
import {
|
||||
publishAppShellDomainSlice,
|
||||
useAppShellProps,
|
||||
} from './appShellPropsStore.ts';
|
||||
import { registerAppHandlers } from './appHandlersBridge.ts';
|
||||
import { resolveTerminalVaultInitialized } from '../../components/terminal/restoredSessionGate.ts';
|
||||
import { terminalLayerAreEqual } from '../../components/terminalLayerMemo.ts';
|
||||
import {
|
||||
terminalLayerViewCtxEqual,
|
||||
terminalLayerWorkspaceCtxEqual,
|
||||
} from '../../components/terminalLayer/terminalLayerViewMemo.ts';
|
||||
import type { Host, Identity, SSHKey } from '../../domain/models.ts';
|
||||
|
||||
const storageBacking = new Map<string, string>();
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
configurable: true,
|
||||
value: {
|
||||
getItem: (key: string) => storageBacking.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => {
|
||||
storageBacking.set(key, value);
|
||||
},
|
||||
removeItem: (key: string) => {
|
||||
storageBacking.delete(key);
|
||||
},
|
||||
clear: () => {
|
||||
storageBacking.clear();
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const { VaultHost } = await import('./hosts/VaultHost.tsx');
|
||||
|
||||
test('VaultHost keeps isVaultInitialized synchronized with hydrated hosts, keys, and identities for Terminal boot (#4428)', async () => {
|
||||
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>');
|
||||
const prevWindow = globalThis.window;
|
||||
const prevDocument = globalThis.document;
|
||||
const prevActEnv = (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT;
|
||||
|
||||
(globalThis as Record<string, unknown>).window = dom.window;
|
||||
(globalThis as Record<string, unknown>).document = dom.window.document;
|
||||
(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
const host: Host = {
|
||||
id: 'host-1',
|
||||
label: 'test-myhost',
|
||||
hostname: '10.243.2.249',
|
||||
port: 22,
|
||||
username: 'user1',
|
||||
authMethod: 'key',
|
||||
identityFileId: 'key-1',
|
||||
tags: [],
|
||||
createdAt: 0,
|
||||
};
|
||||
const key: SSHKey = {
|
||||
id: 'key-1',
|
||||
label: 'Imported Key',
|
||||
type: 'ED25519',
|
||||
privateKey: '-----BEGIN OPENSSH PRIVATE KEY-----\ntest\n-----END OPENSSH PRIVATE KEY-----',
|
||||
publicKey: 'ssh-ed25519 AAAA test',
|
||||
passphrase: 'secret',
|
||||
source: 'imported',
|
||||
category: 'key',
|
||||
created: 0,
|
||||
};
|
||||
const identity: Identity = {
|
||||
id: 'id-1',
|
||||
label: 'User Identity',
|
||||
username: 'user1',
|
||||
authMethod: 'key',
|
||||
keyId: 'key-1',
|
||||
createdAt: 0,
|
||||
};
|
||||
|
||||
publishVaultSnapshot(EMPTY_VAULT_SNAPSHOT);
|
||||
registerAppHandlers({} as never);
|
||||
|
||||
// Mirror TerminalHost's layout-effect slice publication order (sibling after VaultHost).
|
||||
function TerminalHostMirror() {
|
||||
const vault = useVaultSnapshot();
|
||||
useLayoutEffect(() => {
|
||||
publishAppShellDomainSlice('terminal', { terminalHosts: vault.hosts });
|
||||
}, [vault.hosts]);
|
||||
return null;
|
||||
}
|
||||
|
||||
const syncedBoots: Array<{
|
||||
hostCount: number;
|
||||
keyCount: number;
|
||||
identityCount: number;
|
||||
hasPrivateKey: boolean;
|
||||
}> = [];
|
||||
|
||||
function SyncedTerminal({
|
||||
vaultInitializedOverride,
|
||||
hosts,
|
||||
keys,
|
||||
identities,
|
||||
}: {
|
||||
vaultInitializedOverride: boolean;
|
||||
hosts: readonly Host[];
|
||||
keys: readonly SSHKey[];
|
||||
identities: readonly Identity[];
|
||||
}) {
|
||||
const sharedVaultInitialized = useVaultSnapshotField('isVaultInitialized');
|
||||
const vaultInitialized = resolveTerminalVaultInitialized(
|
||||
sharedVaultInitialized,
|
||||
vaultInitializedOverride,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!vaultInitialized) return;
|
||||
syncedBoots.push({
|
||||
hostCount: hosts.length,
|
||||
keyCount: keys.length,
|
||||
identityCount: identities.length,
|
||||
hasPrivateKey: Boolean(keys[0]?.privateKey),
|
||||
});
|
||||
// Intentionally matches useTerminalEffects' boot effect dep shape (gated on vaultInitialized, not keys).
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [vaultInitialized]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function ShellHarness() {
|
||||
const { domains } = useAppShellProps();
|
||||
const vaultDomain = domains?.vault as
|
||||
| { isVaultInitialized?: boolean; keys?: readonly SSHKey[]; identities?: readonly Identity[] }
|
||||
| undefined;
|
||||
const terminalDomain = domains?.terminal as
|
||||
| { terminalHosts?: readonly Host[] }
|
||||
| undefined;
|
||||
|
||||
return React.createElement(
|
||||
React.Fragment,
|
||||
null,
|
||||
React.createElement(VaultHost),
|
||||
React.createElement(TerminalHostMirror),
|
||||
vaultDomain && terminalDomain
|
||||
? React.createElement(SyncedTerminal, {
|
||||
vaultInitializedOverride: vaultDomain.isVaultInitialized ?? false,
|
||||
hosts: terminalDomain.terminalHosts ?? [],
|
||||
keys: vaultDomain.keys ?? [],
|
||||
identities: vaultDomain.identities ?? [],
|
||||
})
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
const root = createRoot(dom.window.document.getElementById('root')!);
|
||||
try {
|
||||
await React.act(async () => {
|
||||
root.render(React.createElement(ShellHarness));
|
||||
});
|
||||
assert.equal(syncedBoots.length, 0, 'restored terminal must not boot before vault hydration');
|
||||
|
||||
// Publish hydrated hosts, keys, identities, and isVaultInitialized together.
|
||||
await React.act(async () => {
|
||||
publishVaultSnapshot({
|
||||
...EMPTY_VAULT_SNAPSHOT,
|
||||
isVaultInitialized: true,
|
||||
hosts: [host],
|
||||
keys: [key],
|
||||
identities: [identity],
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepEqual(syncedBoots, [
|
||||
{
|
||||
hostCount: 1,
|
||||
keyCount: 1,
|
||||
identityCount: 1,
|
||||
hasPrivateKey: true,
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
await React.act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
publishVaultSnapshot(EMPTY_VAULT_SNAPSHOT);
|
||||
registerAppHandlers(null);
|
||||
(globalThis as Record<string, unknown>).window = prevWindow;
|
||||
(globalThis as Record<string, unknown>).document = prevDocument;
|
||||
(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = prevActEnv;
|
||||
}
|
||||
});
|
||||
|
||||
test('terminal layer memo comparators propagate isVaultInitialized changes', () => {
|
||||
const baseLayerProps = {
|
||||
isVaultInitialized: false,
|
||||
hosts: [],
|
||||
sessions: [],
|
||||
};
|
||||
assert.equal(
|
||||
terminalLayerAreEqual(baseLayerProps, { ...baseLayerProps, isVaultInitialized: true }),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
terminalLayerWorkspaceCtxEqual(
|
||||
{ isVaultInitialized: false },
|
||||
{ isVaultInitialized: true },
|
||||
),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
terminalLayerViewCtxEqual(
|
||||
{ isVaultInitialized: false },
|
||||
{ isVaultInitialized: true },
|
||||
),
|
||||
false,
|
||||
);
|
||||
|
||||
const appViewSource = readFileSync(new URL('./AppView.tsx', import.meta.url), 'utf8');
|
||||
const supportSource = readFileSync(
|
||||
new URL('../../components/terminalLayer/TerminalLayerSupport.tsx', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
assert.match(appViewSource, /<TerminalLayerMount[\s\S]*?isVaultInitialized=\{isVaultInitialized\}/);
|
||||
assert.match(supportSource, /vaultInitializedOverride=\{isVaultInitialized\}/);
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import { createPromptHostnameSessionSignalController } from './promptHostnameSessionSignalController.ts';
|
||||
import { extractTerminalPromptHostname } from '../../domain/terminalPromptSecurity';
|
||||
|
||||
type Change = readonly [sessionId: string, hostname: string | null];
|
||||
|
||||
@@ -20,10 +21,34 @@ function createHarness() {
|
||||
return { changes, controller };
|
||||
}
|
||||
|
||||
test('prompt host controller ignores the initial jumpserver prompt', () => {
|
||||
test('prompt observations are independent of IP, alias, and matching connection addresses', () => {
|
||||
const prompt = '[root@vm-prod ~]# ';
|
||||
const observedHost = extractTerminalPromptHostname(prompt)!;
|
||||
for (const hostname of ['203.0.113.10', 'alias.example.test', observedHost]) {
|
||||
const changes: Change[] = [];
|
||||
const controller = createPromptHostnameSessionSignalController({
|
||||
getSession: () => ({ protocol: 'ssh', hostname }),
|
||||
onChange: (sessionId, host) => changes.push([sessionId, host]),
|
||||
});
|
||||
controller.handleTerminalOutput('ssh-1', prompt);
|
||||
assert.deepEqual(changes, [['ssh-1', observedHost]], hostname);
|
||||
}
|
||||
});
|
||||
|
||||
test('forgetting a session permits the first matching-host prompt to publish again', () => {
|
||||
const { changes, controller } = createHarness();
|
||||
const prompt = '[root@jump.example.com ~]# ';
|
||||
const observedHost = extractTerminalPromptHostname(prompt)!;
|
||||
controller.handleTerminalOutput('ssh-1', prompt);
|
||||
controller.forgetSession('ssh-1');
|
||||
controller.handleTerminalOutput('ssh-1', prompt);
|
||||
assert.deepEqual(changes, [['ssh-1', observedHost], ['ssh-1', observedHost]]);
|
||||
});
|
||||
|
||||
test('prompt host controller observes the initial jumpserver prompt', () => {
|
||||
const { changes, controller } = createHarness();
|
||||
controller.handleTerminalOutput('ssh-1', 'Last login\r\n[root@jump.example.com ~]# ');
|
||||
assert.deepEqual(changes, []);
|
||||
assert.deepEqual(changes, [['ssh-1', getSession('ssh-1').hostname]]);
|
||||
});
|
||||
|
||||
test('prompt host controller publishes a nested target and de-duplicates it', () => {
|
||||
@@ -31,17 +56,18 @@ test('prompt host controller publishes a nested target and de-duplicates it', ()
|
||||
controller.handleTerminalOutput('ssh-1', '[root@jump.example.com ~]# ');
|
||||
controller.handleTerminalOutput('ssh-1', 'ssh root@10.1.64.1\r\n[root@10.1.64.1 ~]# ');
|
||||
controller.handleTerminalOutput('ssh-1', '\r\n[root@10.1.64.1 ~]# ');
|
||||
assert.deepEqual(changes, [['ssh-1', '10.1.64.1']]);
|
||||
assert.deepEqual(changes, [['ssh-1', getSession('ssh-1').hostname], ['ssh-1', '10.1.64.1']]);
|
||||
});
|
||||
|
||||
test('prompt host controller clears the override when returning to the jumpserver', () => {
|
||||
test('prompt host controller observes the original host when returning from a target', () => {
|
||||
const { changes, controller } = createHarness();
|
||||
controller.handleTerminalOutput('ssh-1', '[root@jump.example.com ~]# ');
|
||||
controller.handleTerminalOutput('ssh-1', '\r\n[root@10.1.64.1 ~]# ');
|
||||
controller.handleTerminalOutput('ssh-1', 'exit\r\n[root@jump.example.com ~]# ');
|
||||
assert.deepEqual(changes, [
|
||||
['ssh-1', getSession('ssh-1').hostname],
|
||||
['ssh-1', '10.1.64.1'],
|
||||
['ssh-1', null],
|
||||
['ssh-1', getSession('ssh-1').hostname],
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -50,26 +76,28 @@ test('prompt host controller detects an identity split across output chunks', ()
|
||||
controller.handleTerminalOutput('ssh-1', '[root@jump.example.com ~]# ');
|
||||
controller.handleTerminalOutput('ssh-1', 'ssh target\r\n[root@10.1.');
|
||||
controller.handleTerminalOutput('ssh-1', '64.1 ~]# ');
|
||||
assert.deepEqual(changes, [['ssh-1', '10.1.64.1']]);
|
||||
assert.deepEqual(changes, [['ssh-1', getSession('ssh-1').hostname], ['ssh-1', '10.1.64.1']]);
|
||||
});
|
||||
|
||||
test('prompt host controller ignores ambiguous, sensitive, and local output', () => {
|
||||
const { changes, controller } = createHarness();
|
||||
controller.handleTerminalOutput('ssh-1', '[root@jump.example.com ~]# ');
|
||||
const initialChanges = changes.slice();
|
||||
controller.handleTerminalOutput('ssh-1', 'Password:\n# ');
|
||||
controller.handleTerminalOutput('ssh-1', 'copied output\n# ');
|
||||
controller.handleTerminalOutput('local-1', '[root@10.1.64.1 ~]# ');
|
||||
assert.deepEqual(changes, []);
|
||||
assert.deepEqual(changes, initialChanges);
|
||||
});
|
||||
|
||||
test('prompt host controller ignores host-like text embedded in copied output', () => {
|
||||
const { changes, controller } = createHarness();
|
||||
controller.handleTerminalOutput('ssh-1', '[root@jump.example.com ~]# ');
|
||||
const initialChanges = changes.slice();
|
||||
controller.handleTerminalOutput('ssh-1', 'see [root@prod] logs\n# ');
|
||||
controller.handleTerminalOutput('ssh-1', '[root@prod] copied output\n# ');
|
||||
controller.handleTerminalOutput('ssh-1', 'root@prod output\n# ');
|
||||
controller.handleTerminalOutput('ssh-1', '[root@prod] version = 1.2\n# ');
|
||||
assert.deepEqual(changes, []);
|
||||
assert.deepEqual(changes, initialChanges);
|
||||
});
|
||||
|
||||
test('prompt host controller publishes common zsh, Alpine, and macOS root prompt hosts', () => {
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
} from '../../domain/terminalPromptSecurity';
|
||||
|
||||
type PromptHostnameSessionSignalOptions = {
|
||||
getSession: (sessionId: string) => Pick<TerminalSession, 'protocol' | 'hostname'> | undefined;
|
||||
getSession: (sessionId: string) => Pick<TerminalSession, 'protocol'> | undefined;
|
||||
onChange: (sessionId: string, hostname: string | null) => void;
|
||||
maxTailChars?: number;
|
||||
};
|
||||
@@ -22,20 +22,18 @@ export function createPromptHostnameSessionSignalController({
|
||||
maxTailChars = DEFAULT_MAX_TAIL_CHARS,
|
||||
}: PromptHostnameSessionSignalOptions) {
|
||||
const tails = new Map<string, string>();
|
||||
const baselines = new Map<string, string>();
|
||||
const published = new Map<string, string>();
|
||||
const tailLimit = Math.max(256, maxTailChars);
|
||||
|
||||
const forgetSession = (sessionId: string): void => {
|
||||
tails.delete(sessionId);
|
||||
baselines.delete(sessionId);
|
||||
published.delete(sessionId);
|
||||
};
|
||||
|
||||
return {
|
||||
forgetSession,
|
||||
pruneSessions(validSessionIds: ReadonlySet<string>): void {
|
||||
for (const sessionId of [...tails.keys(), ...baselines.keys(), ...published.keys()]) {
|
||||
for (const sessionId of [...tails.keys(), ...published.keys()]) {
|
||||
if (!validSessionIds.has(sessionId)) {
|
||||
forgetSession(sessionId);
|
||||
}
|
||||
@@ -65,19 +63,8 @@ export function createPromptHostnameSessionSignalController({
|
||||
const detectedKey = normalizedHostname(detected);
|
||||
if (!detectedKey) return;
|
||||
|
||||
let baseline = baselines.get(sessionId);
|
||||
if (baseline === undefined) {
|
||||
baseline = normalizedHostname(session.hostname) || detectedKey;
|
||||
baselines.set(sessionId, baseline);
|
||||
}
|
||||
|
||||
if (detectedKey === baseline) {
|
||||
if (!published.has(sessionId)) return;
|
||||
published.delete(sessionId);
|
||||
onChange(sessionId, null);
|
||||
return;
|
||||
}
|
||||
|
||||
// Observe the prompt, not whether its hostname matches an IP or DNS alias.
|
||||
// The domain title policy decides if this presentation is shown.
|
||||
if (published.get(sessionId) === detectedKey) return;
|
||||
published.set(sessionId, detectedKey);
|
||||
onChange(sessionId, detected);
|
||||
|
||||
@@ -192,6 +192,7 @@ function buildScriptSessionMeta(
|
||||
}
|
||||
|
||||
const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
isVaultInitialized,
|
||||
hosts,
|
||||
portForwardingRules = [],
|
||||
customGroups,
|
||||
@@ -2802,6 +2803,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
onToggleGlobalComposeSendTarget,
|
||||
canUseGlobalBroadcast,
|
||||
isComposeBarOpen,
|
||||
isVaultInitialized,
|
||||
keyBindings,
|
||||
keys,
|
||||
knownHosts,
|
||||
|
||||
@@ -80,7 +80,7 @@ test("host tree tab gutter style animates only when host tree transitions and yi
|
||||
});
|
||||
});
|
||||
|
||||
test("workspace tabs resolve generated labels from live prompt hosts", () => {
|
||||
test("workspace tabs resolve generated labels from live prompt hosts in all mode", () => {
|
||||
const sessions = [
|
||||
topTabSession("s1", "h1", { customName: "", promptHostname: "" }),
|
||||
topTabSession("s2", "h2", { customName: "", promptHostname: "" }),
|
||||
@@ -95,7 +95,7 @@ test("workspace tabs resolve generated labels from live prompt hosts", () => {
|
||||
publishSessionPromptHost("s1", "target-a");
|
||||
publishSessionPromptHost("s2", "target-b");
|
||||
assert.equal(
|
||||
resolveWorkspaceTopTabLabel(workspace, sessions),
|
||||
resolveWorkspaceTopTabLabel(workspace, sessions, "all"),
|
||||
"target-a/target-b",
|
||||
);
|
||||
|
||||
@@ -103,6 +103,30 @@ test("workspace tabs resolve generated labels from live prompt hosts", () => {
|
||||
sessionPresentationStore.clearSession("s2");
|
||||
});
|
||||
|
||||
test("generated workspace tabs keep saved names in disabled and agent-only modes", (t) => {
|
||||
const sessions = [
|
||||
topTabSession("mode-s1", "h1", { hostLabel: "Production" }),
|
||||
topTabSession("mode-s2", "h2", { hostLabel: "Database" }),
|
||||
];
|
||||
t.after(() => sessions.forEach((session) => sessionPresentationStore.clearSession(session.id)));
|
||||
const savedTitle = sessions.map((session) => session.hostLabel).join("/");
|
||||
const workspace = { title: savedTitle, autoTitle: false, generatedTitle: true, focusedSessionId: "mode-s1" };
|
||||
publishSessionPromptHost("mode-s1", "vm-prod");
|
||||
publishSessionPromptHost("mode-s2", "db-prod");
|
||||
for (const mode of [undefined, "off", "agent"] as const) {
|
||||
assert.equal(resolveWorkspaceTopTabLabel(workspace, sessions, mode), savedTitle, String(mode));
|
||||
}
|
||||
});
|
||||
|
||||
test("auto workspace tabs apply presentation with the current mode", (t) => {
|
||||
const session = topTabSession("auto-mode", "h1", { hostLabel: "Production" });
|
||||
t.after(() => sessionPresentationStore.clearSession(session.id));
|
||||
const workspace = { title: "Workspace", autoTitle: true, focusedSessionId: session.id };
|
||||
publishSessionPromptHost(session.id, "vm-prod");
|
||||
assert.equal(resolveWorkspaceTopTabLabel(workspace, [session], "off"), session.hostLabel);
|
||||
assert.equal(resolveWorkspaceTopTabLabel(workspace, [session], "all"), "vm-prod");
|
||||
});
|
||||
|
||||
test("workspace tabs keep explicit names ahead of live prompt hosts", () => {
|
||||
const sessions = [
|
||||
topTabSession("s1", "h1", { customName: "", promptHostname: "" }),
|
||||
|
||||
@@ -470,3 +470,180 @@ test('PluginRemoteSurface forwards dblclick, contextmenu, throttled scroll, curs
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
}
|
||||
});
|
||||
|
||||
test('PluginDataGrid FK jump, hiddenColumns, keyboard shortcuts, and PluginErCanvas double-click + SVG export', 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', 'KeyboardEvent', '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: 0, y: 0, width: 800, height: 600, top: 0, left: 0, right: 800, bottom: 600, 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 { act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { PluginRemoteSurface } = await import('./PluginRemoteSurface');
|
||||
|
||||
const events: Array<Record<string, unknown>> = [];
|
||||
const gridProps = {
|
||||
columns: [
|
||||
{ name: 'id', type: 'int4', primaryKey: true },
|
||||
{ name: 'customer_id', type: 'int4', foreignKey: { table: 'customers', column: 'id', schema: 'public' } },
|
||||
{ name: 'secret_col', type: 'text' },
|
||||
],
|
||||
hiddenColumns: ['secret_col'],
|
||||
rows: [[10, 42, 'hidden-val']],
|
||||
editable: true,
|
||||
};
|
||||
const roGridProps = {
|
||||
columns: [{ name: 'id', type: 'int4' }],
|
||||
rows: [{ id: 99 }],
|
||||
editable: false,
|
||||
};
|
||||
const erProps = {
|
||||
tables: [
|
||||
{ name: 'customers', schema: 'public', columns: [{ name: 'id', type: 'integer', isPk: true }, { name: 'created_at', type: 'timestamp with time zone' }] },
|
||||
{ name: 'orders', schema: 'public', columns: [{ name: 'id', type: 'integer', isPk: true }, { name: 'customer_id', type: 'integer', isFk: true }] },
|
||||
],
|
||||
relations: [{ fromTable: 'public.orders', fromColumn: 'customer_id', toTable: 'public.customers', toColumn: 'id', onDelete: 'CASCADE' }],
|
||||
};
|
||||
const tree = {
|
||||
children: [
|
||||
{ id: 'surface-btn', type: 1, element: 'button', attributes: { type: 'button' }, children: [{ id: 'sbt', type: 3, data: 'Btn' }] },
|
||||
{ id: 'grid', type: 1, element: 'div', attributes: { 'data-plugin-widget': 'data-grid', 'data-plugin-widget-props': JSON.stringify(gridProps) }, children: [] },
|
||||
{ id: 'ro-grid', type: 1, element: 'div', attributes: { 'data-plugin-widget': 'data-grid', 'data-plugin-widget-props': JSON.stringify(roGridProps) }, children: [] },
|
||||
{ id: 'er', type: 1, element: 'div', attributes: { 'data-plugin-widget': 'er-canvas', 'data-plugin-widget-props': JSON.stringify(erProps) }, children: [] },
|
||||
],
|
||||
};
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
try {
|
||||
await act(async () => {
|
||||
root.render(<PluginRemoteSurface tree={tree} css="" onEvent={(e) => events.push(e as unknown as Record<string, unknown>)} />);
|
||||
});
|
||||
|
||||
// Shadow surface prevents default on Cmd+K / Cmd+S
|
||||
const btn = shadows[0].querySelector('button')!;
|
||||
const modK = new dom.window.KeyboardEvent('keydown', { key: 'k', metaKey: true, bubbles: true, cancelable: true });
|
||||
await act(async () => { btn.dispatchEvent(modK); });
|
||||
assert.equal(modK.defaultPrevented, true, 'Cmd+K inside shadow surface must preventDefault');
|
||||
|
||||
// DataGrid: hiddenColumns excludes secret_col while preserving values
|
||||
const gridHost = document.querySelector('[data-plugin-widget-node="grid"]') as HTMLElement;
|
||||
assert.equal(gridHost.querySelector('[data-col-name="secret_col"]'), null, 'hidden column must not render');
|
||||
const fkCell = gridHost.querySelector('[role="gridcell"][data-row-index="0"][data-col-name="customer_id"]') as HTMLElement;
|
||||
assert.ok(fkCell, 'customer_id FK cell rendered');
|
||||
const jumpBtn = fkCell.querySelector('[data-fk-jump]') as HTMLButtonElement;
|
||||
assert.ok(jumpBtn, 'FK jump button rendered');
|
||||
await act(async () => { jumpBtn.click(); });
|
||||
assert.deepEqual(
|
||||
events.find((e) => e.nodeId === 'grid' && e.widgetEvent === 'fkJump'),
|
||||
{ nodeId: 'grid', type: 'widget', widgetEvent: 'fkJump', detail: { rowIndex: 0, colName: 'customer_id', value: 42, targetTable: 'customers', targetColumn: 'id', targetSchema: 'public' } },
|
||||
);
|
||||
|
||||
// Select FK cell then press Cmd+C -> cellCopy, Delete -> cellEdit NULL, Cmd+Z -> shortcut mod+z
|
||||
await act(async () => { fkCell.click(); });
|
||||
const gridRoot = gridHost.querySelector('[data-plugin-data-grid]') as HTMLElement;
|
||||
await act(async () => {
|
||||
gridRoot.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'c', metaKey: true, bubbles: true, cancelable: true }));
|
||||
gridRoot.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'Delete', bubbles: true, cancelable: true }));
|
||||
gridRoot.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'z', metaKey: true, bubbles: true, cancelable: true }));
|
||||
});
|
||||
assert.deepEqual(
|
||||
events.find((e) => e.nodeId === 'grid' && e.widgetEvent === 'cellCopy'),
|
||||
{ nodeId: 'grid', type: 'widget', widgetEvent: 'cellCopy', detail: { text: '42', rowIndex: 0, colName: 'customer_id', rowIndices: [0] } },
|
||||
);
|
||||
assert.deepEqual(
|
||||
events.find((e) => e.nodeId === 'grid' && e.widgetEvent === 'cellEdit'),
|
||||
{ nodeId: 'grid', type: 'widget', widgetEvent: 'cellEdit', detail: { rowIndex: 0, colName: 'customer_id', value: null, isNull: true } },
|
||||
);
|
||||
assert.deepEqual(
|
||||
events.find((e) => e.nodeId === 'grid' && e.widgetEvent === 'shortcut'),
|
||||
{ nodeId: 'grid', type: 'widget', widgetEvent: 'shortcut', detail: { shortcut: 'mod+z' } },
|
||||
);
|
||||
|
||||
// Non-editable grid double-click emits cellDoubleClick
|
||||
const roHost = document.querySelector('[data-plugin-widget-node="ro-grid"]') as HTMLElement;
|
||||
const roCell = roHost.querySelector('[role="gridcell"][data-row-index="0"][data-col-name="id"]') as HTMLElement;
|
||||
await act(async () => { roCell.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true })); });
|
||||
assert.deepEqual(
|
||||
events.find((e) => e.nodeId === 'ro-grid' && e.widgetEvent === 'cellDoubleClick'),
|
||||
{ nodeId: 'ro-grid', type: 'widget', widgetEvent: 'cellDoubleClick', detail: { rowIndex: 0, colName: 'id', value: 99 } },
|
||||
);
|
||||
|
||||
// ER Canvas: abbreviated type, tableDoubleClick, Export SVG
|
||||
const erHost = document.querySelector('[data-plugin-widget-node="er"]') as HTMLElement;
|
||||
assert.ok(erHost.textContent?.includes('timestamptz'), 'verbose PG timestamp abbreviated to timestamptz');
|
||||
const ordersCard = erHost.querySelector('[data-er-table="orders"]') as Element;
|
||||
await act(async () => { ordersCard.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true })); });
|
||||
assert.deepEqual(
|
||||
events.find((e) => e.nodeId === 'er' && e.widgetEvent === 'tableDoubleClick'),
|
||||
{ nodeId: 'er', type: 'widget', widgetEvent: 'tableDoubleClick', detail: { table: 'orders', schema: 'public' } },
|
||||
);
|
||||
const exportBtn = erHost.querySelector('[data-er-export-svg]') as HTMLButtonElement;
|
||||
await act(async () => { exportBtn.click(); });
|
||||
const exportEvt = events.find((e) => e.nodeId === 'er' && e.widgetEvent === 'exportSvg');
|
||||
assert.ok(exportEvt, 'exportSvg event emitted');
|
||||
assert.match(String((exportEvt!.detail as { svg: string }).svg), /^<svg xmlns="http:\/\/www\.w3\.org\/2000\/svg"/);
|
||||
|
||||
// Host global hotkey handler yields Cmd+K (commandPalette) to active plugin surface while keeping Cmd+J (quickSwitch)
|
||||
const { handleGlobalHotkeyKeyDownImpl } = await import('../../application/app/AppHandlers');
|
||||
const { matchesKeyBinding } = await import('../../domain/models');
|
||||
const { DEFAULT_KEY_BINDINGS } = await import('../../domain/models/keyBindings');
|
||||
const hostActions: string[] = [];
|
||||
const onGlobalKey = (event: KeyboardEvent) => handleGlobalHotkeyKeyDownImpl(() => ({
|
||||
HOTKEY_DEBUG: false,
|
||||
closeTabKeyStr: '⌘ + W',
|
||||
hotkeyScheme: 'mac',
|
||||
keyBindings: DEFAULT_KEY_BINDINGS,
|
||||
matchesKeyBinding,
|
||||
executeHotkeyAction: (action: string) => hostActions.push(action),
|
||||
}), event);
|
||||
dom.window.addEventListener('keydown', onGlobalKey as unknown as EventListener, true);
|
||||
try {
|
||||
await act(async () => {
|
||||
gridRoot.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'k', code: 'KeyK', metaKey: true, bubbles: true, cancelable: true }));
|
||||
});
|
||||
assert.deepEqual(hostActions, [], 'host commandPalette must not hijack Cmd+K inside plugin surface');
|
||||
assert.ok(
|
||||
events.some((e) => e.nodeId === 'grid' && e.widgetEvent === 'shortcut' && (e.detail as { shortcut?: string })?.shortcut === 'mod+k'),
|
||||
'Cmd+K reaches plugin DataGrid as mod+k shortcut',
|
||||
);
|
||||
await act(async () => {
|
||||
gridRoot.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'j', code: 'KeyJ', metaKey: true, bubbles: true, cancelable: true }));
|
||||
});
|
||||
assert.deepEqual(hostActions, ['quickSwitch'], 'Cmd+J still opens Netcatty Quick Switcher');
|
||||
} finally {
|
||||
dom.window.removeEventListener('keydown', onGlobalKey as unknown as EventListener, true);
|
||||
}
|
||||
} 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');
|
||||
}
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { LazyLoadBoundary } from '../ui/lazy-load-boundary';
|
||||
import { PluginViewPopover } from './PluginViewPopover';
|
||||
import { PluginSplitPane } from './primitives/PluginSplitPane';
|
||||
import { parseWidgetPropsJson, PluginSlottedWidget, type SlottedWidgetKind } from './primitives/PluginWidgetRenderer';
|
||||
import { matchWorkbenchShortcut } from './primitives/shortcuts';
|
||||
import type { PluginSplitPaneWidgetProps } from './primitives/types';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { validatePluginRemoteTree } from '@/domain/pluginRemoteTreePolicy.cjs';
|
||||
@@ -407,8 +408,15 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
|
||||
|
||||
if (event.type === 'submit') event.preventDefault();
|
||||
if (event.type === 'contextmenu') event.preventDefault();
|
||||
if (event.type === 'keydown' && event instanceof view.KeyboardEvent) {
|
||||
const sc = matchWorkbenchShortcut(event, { includeUndoRedo: false });
|
||||
if (sc === 'mod+k' || sc === 'mod+s') {
|
||||
event.preventDefault();
|
||||
}
|
||||
}
|
||||
|
||||
const nodeId = target.dataset.netcattyRemoteNode;
|
||||
const nodeId = target.dataset.netcattyRemoteNode
|
||||
?? (event.type === 'keydown' ? (shadow.querySelector('[data-netcatty-remote-node]') as HTMLElement | null)?.dataset.netcattyRemoteNode : undefined);
|
||||
if (!nodeId) return;
|
||||
|
||||
if (event.type === 'scroll') {
|
||||
@@ -464,13 +472,55 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
|
||||
};
|
||||
|
||||
for (const event of SURFACE_EVENTS) shadow.addEventListener(event, listener, true);
|
||||
|
||||
// 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;
|
||||
if (!surfaceEl || !surfaceEl.closest('[data-plugin-chrome="full-bleed"]')) return;
|
||||
const rect = surfaceEl.getBoundingClientRect();
|
||||
if (rect.width <= 0 || rect.height <= 0) return;
|
||||
const doc = surfaceEl.ownerDocument;
|
||||
const hasHostModal = [...doc.querySelectorAll('[role=dialog][aria-modal=true]:not([data-plugin-dialog])')].some((dialog) => {
|
||||
const r = dialog.getBoundingClientRect();
|
||||
return r.width > 0 && r.height > 0;
|
||||
});
|
||||
if (hasHostModal) return;
|
||||
const active = doc.activeElement;
|
||||
const focusInsideHostChrome = active
|
||||
&& active !== doc.body
|
||||
&& active !== doc.documentElement
|
||||
&& !surfaceEl.contains(active)
|
||||
&& !active.closest?.('[data-plugin-view-slot]');
|
||||
if (focusInsideHostChrome) return;
|
||||
const sc = matchWorkbenchShortcut(event, { includeUndoRedo: false });
|
||||
if (sc !== 'mod+k' && sc !== 'mod+s') return;
|
||||
const rootNodeId = (shadow.querySelector('[data-netcatty-remote-node]') as HTMLElement | null)?.dataset.netcattyRemoteNode;
|
||||
if (!rootNodeId) return;
|
||||
event.preventDefault();
|
||||
onEventRef.current({
|
||||
nodeId: rootNodeId,
|
||||
type: 'keydown',
|
||||
key: event.key,
|
||||
ctrlKey: event.ctrlKey,
|
||||
metaKey: event.metaKey,
|
||||
altKey: event.altKey,
|
||||
shiftKey: event.shiftKey,
|
||||
});
|
||||
};
|
||||
view?.addEventListener('keydown', onWindowKeyDown, false);
|
||||
|
||||
return () => {
|
||||
view?.removeEventListener('keydown', onWindowKeyDown, false);
|
||||
for (const timer of scrollTimers.values()) clearTimeout(timer);
|
||||
scrollTimers.clear();
|
||||
pendingScroll.clear();
|
||||
for (const event of SURFACE_EVENTS) shadow.removeEventListener(event, listener, true);
|
||||
};
|
||||
}, [shadow]);
|
||||
}, [shadow, depth]);
|
||||
|
||||
return (
|
||||
<SurfaceContext.Provider value={surfaceContextValue}>
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
readClipboardTextWithFallbacks,
|
||||
} from '@/infrastructure/monaco/monacoClipboardPaste';
|
||||
import { useNetcattyMonacoTheme } from '@/infrastructure/monaco/useNetcattyMonacoTheme';
|
||||
import { matchWorkbenchShortcut } from './shortcuts';
|
||||
import { extractCurrentSqlStatement, extractSqlTableAliases } from './sqlStatement';
|
||||
import type {
|
||||
PluginCodeEditorCompletionSchema,
|
||||
@@ -62,8 +63,10 @@ export default function PluginCodeEditorInner({
|
||||
const editorId = useId();
|
||||
const modelPath = `inmemory://netcatty-plugin-editor/${editorId.replace(/[^a-zA-Z0-9_-]/g, '_')}.${language}`;
|
||||
|
||||
const wrapperRef = useRef<HTMLDivElement>(null);
|
||||
const editorRef = useRef<Parameters<OnMount>[0] | null>(null);
|
||||
const monacoRef = useRef<Monaco | null>(null);
|
||||
const handledKeyEventsRef = useRef<WeakSet<Event>>(new WeakSet());
|
||||
const disposablesRef = useRef<Array<{ dispose(): void }>>([]);
|
||||
const onWidgetEventRef = useRef(onWidgetEvent);
|
||||
onWidgetEventRef.current = onWidgetEvent;
|
||||
@@ -316,6 +319,26 @@ export default function PluginCodeEditorInner({
|
||||
],
|
||||
run: emitFormat,
|
||||
}),
|
||||
editor.onKeyDown((monacoKeyEvent) => {
|
||||
const nativeEvent = monacoKeyEvent.browserEvent;
|
||||
if (handledKeyEventsRef.current.has(nativeEvent)) return;
|
||||
const shortcut = matchWorkbenchShortcut(nativeEvent, { includeUndoRedo: false });
|
||||
if (!shortcut) return;
|
||||
if (shortcut === 'escape') {
|
||||
const target = nativeEvent.target as Element | null;
|
||||
if (target?.closest?.('.suggest-widget, .find-widget, .parameter-hints-widget')) return;
|
||||
handledKeyEventsRef.current.add(nativeEvent);
|
||||
onWidgetEventRef.current('shortcut', { shortcut });
|
||||
return;
|
||||
}
|
||||
handledKeyEventsRef.current.add(nativeEvent);
|
||||
monacoKeyEvent.preventDefault();
|
||||
monacoKeyEvent.stopPropagation();
|
||||
nativeEvent.preventDefault();
|
||||
nativeEvent.stopImmediatePropagation?.();
|
||||
nativeEvent.stopPropagation();
|
||||
onWidgetEventRef.current('shortcut', { shortcut });
|
||||
}),
|
||||
editor.addAction({
|
||||
id: 'netcatty.pluginCodeEditor.paste',
|
||||
label: 'Paste',
|
||||
@@ -354,10 +377,38 @@ export default function PluginCodeEditorInner({
|
||||
}, 80);
|
||||
}, []);
|
||||
|
||||
// Native capture listener runs BEFORE Monaco's textarea / chord-prefix handler
|
||||
// so Cmd/Ctrl+K never enters Monaco's chord state and always reaches the plugin once.
|
||||
useEffect(() => {
|
||||
const el = wrapperRef.current;
|
||||
if (!el) return;
|
||||
const onNativeKeyDownCapture = (event: KeyboardEvent) => {
|
||||
if (handledKeyEventsRef.current.has(event)) return;
|
||||
// Keep Monaco's native Cmd/Ctrl+Z undo/redo intact while forwarding global workbench shortcuts.
|
||||
const shortcut = matchWorkbenchShortcut(event, { includeUndoRedo: false });
|
||||
if (!shortcut) return;
|
||||
if (shortcut === 'escape') {
|
||||
const target = event.target as Element | null;
|
||||
if (target?.closest?.('.suggest-widget, .find-widget, .parameter-hints-widget')) return;
|
||||
handledKeyEventsRef.current.add(event);
|
||||
onWidgetEventRef.current('shortcut', { shortcut });
|
||||
return;
|
||||
}
|
||||
handledKeyEventsRef.current.add(event);
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
event.stopPropagation();
|
||||
onWidgetEventRef.current('shortcut', { shortcut });
|
||||
};
|
||||
el.addEventListener('keydown', onNativeKeyDownCapture, true);
|
||||
return () => el.removeEventListener('keydown', onNativeKeyDownCapture, true);
|
||||
}, []);
|
||||
|
||||
const resolvedHeight = typeof height === 'number' ? `${height}px` : height;
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={wrapperRef}
|
||||
className="relative h-full w-full min-h-0 min-w-0 overflow-hidden bg-background"
|
||||
style={resolvedHeight !== '100%' ? { height: resolvedHeight } : undefined}
|
||||
data-plugin-code-editor=""
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useVirtualizer } from '@tanstack/react-virtual';
|
||||
import { ArrowDown, ArrowUp, ArrowUpDown, KeyRound, Loader2 } from 'lucide-react';
|
||||
import { ArrowDown, ArrowUp, ArrowUpDown, ArrowUpRight, KeyRound, Link2, Loader2 } from 'lucide-react';
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { matchWorkbenchShortcut } from './shortcuts';
|
||||
import type {
|
||||
PluginDataGridColumn,
|
||||
PluginDataGridRow,
|
||||
@@ -45,6 +46,7 @@ function isNumericColumn(col: PluginDataGridColumn, value: unknown): boolean {
|
||||
export function PluginDataGrid({
|
||||
columns = [],
|
||||
rows = [],
|
||||
hiddenColumns,
|
||||
dirtyCells,
|
||||
deletedRowIndices,
|
||||
insertedRows = [],
|
||||
@@ -70,6 +72,11 @@ export function PluginDataGrid({
|
||||
|
||||
const deletedSet = useMemo(() => new Set(deletedRowIndices ?? []), [deletedRowIndices]);
|
||||
const selectedSet = useMemo(() => new Set(selectedRowIndices ?? []), [selectedRowIndices]);
|
||||
const hiddenSet = useMemo(() => new Set(hiddenColumns ?? []), [hiddenColumns]);
|
||||
const visibleCols = useMemo(
|
||||
() => columns.map((col, origIndex) => ({ col, origIndex })).filter(({ col }) => !hiddenSet.has(col.name)),
|
||||
[columns, hiddenSet],
|
||||
);
|
||||
const totalRows = rows.length + insertedRows.length;
|
||||
|
||||
const getColWidth = useCallback((col: PluginDataGridColumn): number => {
|
||||
@@ -91,16 +98,16 @@ export function PluginDataGrid({
|
||||
|
||||
const colVirtualizer = useVirtualizer({
|
||||
horizontal: true,
|
||||
count: columns.length,
|
||||
count: visibleCols.length,
|
||||
getScrollElement: () => scrollRef.current,
|
||||
estimateSize: (index) => (columns[index] ? getColWidth(columns[index]) : DEFAULT_COL_WIDTH),
|
||||
estimateSize: (index) => (visibleCols[index] ? getColWidth(visibleCols[index].col) : DEFAULT_COL_WIDTH),
|
||||
overscan: 4,
|
||||
initialRect: { width: 960, height: 420 },
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
colVirtualizer.measure();
|
||||
}, [colWidths, columns, colVirtualizer]);
|
||||
}, [colWidths, visibleCols, colVirtualizer]);
|
||||
|
||||
useEffect(() => {
|
||||
if (editingCell) {
|
||||
@@ -125,11 +132,11 @@ export function PluginDataGrid({
|
||||
return null;
|
||||
}, [rows, insertedRows]);
|
||||
|
||||
const getEffectiveValue = useCallback((rowIndex: number, col: PluginDataGridColumn, colIndex: number) => {
|
||||
const getEffectiveValue = useCallback((rowIndex: number, col: PluginDataGridColumn, origColIndex: number) => {
|
||||
const dirtyKey = `${rowIndex}:${col.name}`;
|
||||
const isDirty = Boolean(dirtyCells && Object.prototype.hasOwnProperty.call(dirtyCells, dirtyKey));
|
||||
const entry = getRowAt(rowIndex);
|
||||
const rawValue = entry ? readCellValue(entry.row, col, colIndex) : undefined;
|
||||
const rawValue = entry ? readCellValue(entry.row, col, origColIndex) : undefined;
|
||||
return {
|
||||
value: isDirty ? dirtyCells![dirtyKey] : rawValue,
|
||||
isDirty,
|
||||
@@ -147,19 +154,19 @@ export function PluginDataGrid({
|
||||
});
|
||||
}, [onWidgetEvent]);
|
||||
|
||||
const beginEdit = useCallback((rowIndex: number, colIndex: number) => {
|
||||
const beginEdit = useCallback((rowIndex: number, visibleColIndex: number) => {
|
||||
if (!editable || deletedSet.has(rowIndex)) return;
|
||||
const col = columns[colIndex];
|
||||
if (!col) return;
|
||||
const { value } = getEffectiveValue(rowIndex, col, colIndex);
|
||||
setActiveCell({ rowIndex, colIndex });
|
||||
const entry = visibleCols[visibleColIndex];
|
||||
if (!entry) return;
|
||||
const { value } = getEffectiveValue(rowIndex, entry.col, entry.origIndex);
|
||||
setActiveCell({ rowIndex, colIndex: visibleColIndex });
|
||||
setEditingCell({
|
||||
rowIndex,
|
||||
colIndex,
|
||||
colName: col.name,
|
||||
colIndex: visibleColIndex,
|
||||
colName: entry.col.name,
|
||||
draft: value === null || value === undefined ? '' : formatCellDisplay(value),
|
||||
});
|
||||
}, [editable, deletedSet, columns, getEffectiveValue]);
|
||||
}, [editable, deletedSet, visibleCols, getEffectiveValue]);
|
||||
|
||||
const toggleRowSelection = useCallback((rowIndex: number, shiftKey: boolean) => {
|
||||
const next = new Set(selectedSet);
|
||||
@@ -225,9 +232,78 @@ export function PluginDataGrid({
|
||||
onWidgetEvent('cellContextMenu', { rowIndex, colName, x, y });
|
||||
}, [onWidgetEvent]);
|
||||
|
||||
const copySelectionOrActiveCell = useCallback(() => {
|
||||
const selectedIndices = [...selectedSet].sort((a, b) => a - b);
|
||||
if (selectedIndices.length > 0 && visibleCols.length > 0) {
|
||||
const text = selectedIndices
|
||||
.map((rowIdx) => visibleCols.map(({ col, origIndex }) => {
|
||||
const { value } = getEffectiveValue(rowIdx, col, origIndex);
|
||||
return value === null || value === undefined ? 'NULL' : formatCellDisplay(value);
|
||||
}).join('\t'))
|
||||
.join('\n');
|
||||
try { void navigator.clipboard?.writeText?.(text)?.catch?.(() => {}); } catch {}
|
||||
onWidgetEvent('cellCopy', {
|
||||
text,
|
||||
rowIndex: activeCell?.rowIndex ?? selectedIndices[0],
|
||||
colName: activeCell ? visibleCols[activeCell.colIndex]?.col.name ?? null : null,
|
||||
rowIndices: selectedIndices,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
if (activeCell) {
|
||||
const entry = visibleCols[activeCell.colIndex];
|
||||
if (!entry) return false;
|
||||
const { value } = getEffectiveValue(activeCell.rowIndex, entry.col, entry.origIndex);
|
||||
const text = value === null || value === undefined ? 'NULL' : formatCellDisplay(value);
|
||||
try { void navigator.clipboard?.writeText?.(text)?.catch?.(() => {}); } catch {}
|
||||
onWidgetEvent('cellCopy', {
|
||||
text,
|
||||
rowIndex: activeCell.rowIndex,
|
||||
colName: entry.col.name,
|
||||
rowIndices: [activeCell.rowIndex],
|
||||
});
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}, [selectedSet, visibleCols, activeCell, getEffectiveValue, onWidgetEvent]);
|
||||
|
||||
const handleGridKeyDown = useCallback((event: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
if (editingCell || !activeCell || columns.length === 0 || totalRows === 0) return;
|
||||
const mod = event.metaKey || event.ctrlKey;
|
||||
|
||||
// While editing an inline cell input, only forward Cmd/Ctrl+K and Cmd/Ctrl+S.
|
||||
if (editingCell) {
|
||||
const shortcut = matchWorkbenchShortcut(event, { includeUndoRedo: false });
|
||||
if (shortcut === 'mod+k' || shortcut === 'mod+s') {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
onWidgetEvent('shortcut', { shortcut });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Global workbench shortcuts + grid Undo/Redo
|
||||
const shortcut = matchWorkbenchShortcut(event, { includeUndoRedo: true });
|
||||
if (shortcut) {
|
||||
if (shortcut !== 'escape') {
|
||||
event.preventDefault();
|
||||
}
|
||||
event.stopPropagation();
|
||||
onWidgetEvent('shortcut', { shortcut });
|
||||
return;
|
||||
}
|
||||
|
||||
// Cmd/Ctrl+C copies active cell or selected rows
|
||||
if (mod && !event.altKey && !event.shiftKey && event.key.toLowerCase() === 'c') {
|
||||
if (copySelectionOrActiveCell()) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!activeCell || visibleCols.length === 0 || totalRows === 0) return;
|
||||
const { rowIndex, colIndex } = activeCell;
|
||||
|
||||
if (event.key === 'ArrowDown' && rowIndex + 1 < totalRows) {
|
||||
event.preventDefault();
|
||||
setActiveCell({ rowIndex: rowIndex + 1, colIndex });
|
||||
@@ -236,7 +312,7 @@ export function PluginDataGrid({
|
||||
event.preventDefault();
|
||||
setActiveCell({ rowIndex: rowIndex - 1, colIndex });
|
||||
rowVirtualizer.scrollToIndex(rowIndex - 1);
|
||||
} else if (event.key === 'ArrowRight' && colIndex + 1 < columns.length) {
|
||||
} else if (event.key === 'ArrowRight' && colIndex + 1 < visibleCols.length) {
|
||||
event.preventDefault();
|
||||
setActiveCell({ rowIndex, colIndex: colIndex + 1 });
|
||||
colVirtualizer.scrollToIndex(colIndex + 1);
|
||||
@@ -244,11 +320,34 @@ export function PluginDataGrid({
|
||||
event.preventDefault();
|
||||
setActiveCell({ rowIndex, colIndex: colIndex - 1 });
|
||||
colVirtualizer.scrollToIndex(colIndex - 1);
|
||||
} else if (event.key === 'Enter' && editable) {
|
||||
} else if ((event.key === 'Enter' || event.key === 'F2') && editable) {
|
||||
event.preventDefault();
|
||||
beginEdit(rowIndex, colIndex);
|
||||
} else if ((event.key === 'Delete' || event.key === 'Backspace') && editable && !deletedSet.has(rowIndex)) {
|
||||
const entry = visibleCols[colIndex];
|
||||
if (entry && entry.col.nullable !== false) {
|
||||
event.preventDefault();
|
||||
onWidgetEvent('cellEdit', {
|
||||
rowIndex,
|
||||
colName: entry.col.name,
|
||||
value: null,
|
||||
isNull: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
}, [editingCell, activeCell, columns.length, totalRows, rowVirtualizer, colVirtualizer, editable, beginEdit]);
|
||||
}, [
|
||||
editingCell,
|
||||
activeCell,
|
||||
visibleCols,
|
||||
totalRows,
|
||||
rowVirtualizer,
|
||||
colVirtualizer,
|
||||
editable,
|
||||
deletedSet,
|
||||
beginEdit,
|
||||
copySelectionOrActiveCell,
|
||||
onWidgetEvent,
|
||||
]);
|
||||
|
||||
const virtualRows = rowVirtualizer.getVirtualItems();
|
||||
const virtualCols = colVirtualizer.getVirtualItems();
|
||||
@@ -272,11 +371,8 @@ export function PluginDataGrid({
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div
|
||||
ref={scrollRef}
|
||||
className="relative h-full w-full min-h-0 flex-1 overflow-auto [&::-webkit-scrollbar]:w-1.5 [&::-webkit-scrollbar]:h-1.5 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-corner]:bg-transparent [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-muted-foreground/20 hover:[&::-webkit-scrollbar-thumb]:bg-muted-foreground/40"
|
||||
>
|
||||
{columns.length === 0 ? (
|
||||
<div ref={scrollRef} className="relative h-full w-full min-h-0 flex-1 overflow-auto">
|
||||
{visibleCols.length === 0 ? (
|
||||
<div className="flex h-full w-full items-center justify-center p-6 text-xs text-muted-foreground">
|
||||
{emptyMessage}
|
||||
</div>
|
||||
@@ -304,8 +400,9 @@ export function PluginDataGrid({
|
||||
|
||||
<div className="relative flex-1" style={{ height: HEADER_HEIGHT }}>
|
||||
{virtualCols.map((vCol) => {
|
||||
const col = columns[vCol.index];
|
||||
if (!col) return null;
|
||||
const colEntry = visibleCols[vCol.index];
|
||||
if (!colEntry) return null;
|
||||
const { col } = colEntry;
|
||||
const isSorted = sort?.column === col.name;
|
||||
const sortable = col.sortable !== false;
|
||||
return (
|
||||
@@ -324,11 +421,16 @@ export function PluginDataGrid({
|
||||
disabled={!sortable}
|
||||
onClick={() => handleSortClick(col)}
|
||||
className={`flex min-w-0 flex-1 items-center gap-1.5 text-left ${sortable ? 'cursor-pointer hover:text-primary' : 'cursor-default'}`}
|
||||
title={col.type ? `${col.name} (${col.type})` : col.name}
|
||||
title={col.foreignKey
|
||||
? `${col.name}${col.type ? ` (${col.type})` : ''} -> ${col.foreignKey.schema ? `${col.foreignKey.schema}.` : ''}${col.foreignKey.table}.${col.foreignKey.column}`
|
||||
: col.type ? `${col.name} (${col.type})` : col.name}
|
||||
>
|
||||
{col.primaryKey && (
|
||||
<KeyRound size={11} className="shrink-0 text-amber-500" aria-label="Primary key" />
|
||||
)}
|
||||
{col.foreignKey && (
|
||||
<Link2 size={11} className="shrink-0 text-blue-500" aria-label="Foreign key" />
|
||||
)}
|
||||
<span className="truncate font-medium">{col.name}</span>
|
||||
{col.type && (
|
||||
<span className="truncate font-mono text-[10px] font-normal text-muted-foreground">
|
||||
@@ -399,7 +501,7 @@ export function PluginDataGrid({
|
||||
<div
|
||||
className="sticky left-0 z-10 flex shrink-0 items-center justify-between border-r border-border/70 bg-background px-2 font-mono text-[10px] tabular-nums text-muted-foreground"
|
||||
style={{ width: GUTTER_WIDTH, height: ROW_HEIGHT }}
|
||||
onContextMenu={(e) => handleCellContextMenu(e, rowIndex, columns[0]?.name ?? '')}
|
||||
onContextMenu={(e) => handleCellContextMenu(e, rowIndex, visibleCols[0]?.col.name ?? '')}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
@@ -420,14 +522,16 @@ export function PluginDataGrid({
|
||||
{/* Virtualized Cells */}
|
||||
<div className="relative z-0 flex-1 overflow-hidden" style={{ height: ROW_HEIGHT }}>
|
||||
{virtualCols.map((vCol) => {
|
||||
const colIndex = vCol.index;
|
||||
const col = columns[colIndex];
|
||||
if (!col) return null;
|
||||
const { value, isDirty } = getEffectiveValue(rowIndex, col, colIndex);
|
||||
const isEditing = editingCell?.rowIndex === rowIndex && editingCell?.colIndex === colIndex;
|
||||
const isActive = activeCell?.rowIndex === rowIndex && activeCell?.colIndex === colIndex;
|
||||
const visibleColIndex = vCol.index;
|
||||
const colEntry = visibleCols[visibleColIndex];
|
||||
if (!colEntry) return null;
|
||||
const { col, origIndex } = colEntry;
|
||||
const { value, isDirty } = getEffectiveValue(rowIndex, col, origIndex);
|
||||
const isEditing = editingCell?.rowIndex === rowIndex && editingCell?.colIndex === visibleColIndex;
|
||||
const isActive = activeCell?.rowIndex === rowIndex && activeCell?.colIndex === visibleColIndex;
|
||||
const isNull = value === null || value === undefined;
|
||||
const numeric = !isNull && isNumericColumn(col, value);
|
||||
const fk = col.foreignKey;
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -436,21 +540,31 @@ export function PluginDataGrid({
|
||||
data-row-index={rowIndex}
|
||||
data-col-name={col.name}
|
||||
data-dirty={isDirty ? 'true' : undefined}
|
||||
className={`absolute top-0 bottom-0 flex items-center border-r border-border/50 px-2.5 font-mono text-[12px] tabular-nums overflow-hidden ${
|
||||
className={`group/cell absolute top-0 bottom-0 flex items-center gap-1 border-r border-border/50 px-2.5 font-mono text-[12px] tabular-nums overflow-hidden ${
|
||||
isDirty ? 'bg-amber-500/15 ring-1 ring-inset ring-amber-500/50' : ''
|
||||
} ${isActive ? 'ring-2 ring-inset ring-primary z-[5]' : ''} ${
|
||||
numeric ? 'justify-end' : 'justify-start'
|
||||
}`}
|
||||
style={{ left: vCol.start, width: vCol.size }}
|
||||
onClick={() => {
|
||||
setActiveCell({ rowIndex, colIndex });
|
||||
setActiveCell({ rowIndex, colIndex: visibleColIndex });
|
||||
onWidgetEvent('cellSelect', {
|
||||
rowIndex,
|
||||
colName: col.name,
|
||||
value: value === undefined ? null : value,
|
||||
});
|
||||
}}
|
||||
onDoubleClick={() => beginEdit(rowIndex, colIndex)}
|
||||
onDoubleClick={() => {
|
||||
if (editable && !isDeleted) {
|
||||
beginEdit(rowIndex, visibleColIndex);
|
||||
} else {
|
||||
onWidgetEvent('cellDoubleClick', {
|
||||
rowIndex,
|
||||
colName: col.name,
|
||||
value: value === undefined ? null : value,
|
||||
});
|
||||
}
|
||||
}}
|
||||
onContextMenu={(e) => handleCellContextMenu(e, rowIndex, col.name)}
|
||||
>
|
||||
{isEditing ? (
|
||||
@@ -465,6 +579,13 @@ export function PluginDataGrid({
|
||||
value={editingCell.draft}
|
||||
onChange={(e) => setEditingCell({ ...editingCell, draft: e.target.value })}
|
||||
onKeyDown={(e) => {
|
||||
const sc = matchWorkbenchShortcut(e, { includeUndoRedo: false });
|
||||
if (sc === 'mod+k' || sc === 'mod+s') {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
onWidgetEvent('shortcut', { shortcut: sc });
|
||||
return;
|
||||
}
|
||||
e.stopPropagation();
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
@@ -475,14 +596,13 @@ export function PluginDataGrid({
|
||||
} else if (e.key === 'Tab') {
|
||||
e.preventDefault();
|
||||
commitEdit(editingCell, false);
|
||||
const nextCol = e.shiftKey ? colIndex - 1 : colIndex + 1;
|
||||
if (nextCol >= 0 && nextCol < columns.length) {
|
||||
const nextCol = e.shiftKey ? visibleColIndex - 1 : visibleColIndex + 1;
|
||||
if (nextCol >= 0 && nextCol < visibleCols.length) {
|
||||
beginEdit(rowIndex, nextCol);
|
||||
}
|
||||
}
|
||||
}}
|
||||
onBlur={() => {
|
||||
// Delay slightly so clicking the inline NULL button wins over blur.
|
||||
const snapshot = editingCell;
|
||||
setTimeout(() => {
|
||||
setEditingCell((curr) => {
|
||||
@@ -534,6 +654,28 @@ export function PluginDataGrid({
|
||||
{formatCellDisplay(value)}
|
||||
</span>
|
||||
)}
|
||||
{!isEditing && !isNull && fk && (
|
||||
<button
|
||||
type="button"
|
||||
data-fk-jump=""
|
||||
aria-label={`Jump to ${fk.schema ? `${fk.schema}.` : ''}${fk.table}.${fk.column}`}
|
||||
title={`Jump to ${fk.schema ? `${fk.schema}.` : ''}${fk.table}.${fk.column} = ${formatCellDisplay(value)}`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onWidgetEvent('fkJump', {
|
||||
rowIndex,
|
||||
colName: col.name,
|
||||
value,
|
||||
targetTable: fk.table,
|
||||
targetColumn: fk.column,
|
||||
...(fk.schema ? { targetSchema: fk.schema } : {}),
|
||||
});
|
||||
}}
|
||||
className="ml-auto shrink-0 inline-flex h-4 w-4 items-center justify-center rounded text-blue-500 opacity-0 transition-opacity hover:bg-blue-500/15 group-hover/cell:opacity-100 focus:opacity-100"
|
||||
>
|
||||
<ArrowUpRight size={11} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
import { Maximize2, RotateCcw, ZoomIn, ZoomOut } from 'lucide-react';
|
||||
import { Download, Maximize2, RotateCcw, ZoomIn, ZoomOut } from 'lucide-react';
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
abbreviateSqlType,
|
||||
buildStandaloneErSvg,
|
||||
ER_CARD_HEADER_HEIGHT,
|
||||
ER_CARD_ROW_HEIGHT,
|
||||
ER_CARD_WIDTH,
|
||||
erCardHeight,
|
||||
erTableKey,
|
||||
} from './erFormat';
|
||||
import { matchWorkbenchShortcut } from './shortcuts';
|
||||
import type {
|
||||
PluginErCanvasWidgetProps,
|
||||
PluginErTable,
|
||||
PluginWidgetEventCallback,
|
||||
} from './types';
|
||||
|
||||
const CARD_WIDTH = 236;
|
||||
const CARD_HEADER_HEIGHT = 34;
|
||||
const CARD_ROW_HEIGHT = 24;
|
||||
const CARD_FOOTER_PADDING = 8;
|
||||
const GRID_GAP_X = 76;
|
||||
const GRID_GAP_X = 80;
|
||||
const GRID_GAP_Y = 56;
|
||||
const MIN_ZOOM = 0.25;
|
||||
const MAX_ZOOM = 2.5;
|
||||
@@ -19,35 +25,45 @@ export interface PluginErCanvasProps extends PluginErCanvasWidgetProps {
|
||||
onWidgetEvent: PluginWidgetEventCallback;
|
||||
}
|
||||
|
||||
function tableKey(table: Pick<PluginErTable, 'name' | 'schema'>): string {
|
||||
return table.schema ? `${table.schema}.${table.name}` : table.name;
|
||||
}
|
||||
|
||||
function cardHeight(table: PluginErTable): number {
|
||||
return CARD_HEADER_HEIGHT + Math.max(1, table.columns.length) * CARD_ROW_HEIGHT + CARD_FOOTER_PADDING;
|
||||
}
|
||||
|
||||
function computeInitialPositions(tables: PluginErTable[]): 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);
|
||||
|
||||
tables.forEach((table, index) => {
|
||||
const key = tableKey(table);
|
||||
const key = erTableKey(table);
|
||||
if (typeof table.x === 'number' && Number.isFinite(table.x) && typeof table.y === 'number' && Number.isFinite(table.y)) {
|
||||
result[key] = { x: table.x, y: table.y };
|
||||
return;
|
||||
}
|
||||
const colIdx = index % colsPerRow;
|
||||
const x = 40 + colIdx * (CARD_WIDTH + GRID_GAP_X);
|
||||
const x = 40 + colIdx * (ER_CARD_WIDTH + GRID_GAP_X);
|
||||
const y = colY[colIdx];
|
||||
result[key] = { x, y };
|
||||
colY[colIdx] = y + cardHeight(table) + GRID_GAP_Y;
|
||||
colY[colIdx] = y + erCardHeight(table) + GRID_GAP_Y;
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function resolveCanvasPalette(el: HTMLElement | null) {
|
||||
const isDark = typeof document !== 'undefined' && document.documentElement.classList.contains('dark');
|
||||
const readVar = (name: string, fallback: string) => {
|
||||
if (!el || typeof window === 'undefined' || typeof window.getComputedStyle !== 'function') return fallback;
|
||||
const val = window.getComputedStyle(el).getPropertyValue(name).trim();
|
||||
return val ? `hsl(${val})` : fallback;
|
||||
};
|
||||
return {
|
||||
background: readVar('--background', isDark ? '#0f1117' : '#ffffff'),
|
||||
card: readVar('--card', isDark ? '#161922' : '#ffffff'),
|
||||
cardForeground: readVar('--card-foreground', isDark ? '#f1f5f9' : '#0f172a'),
|
||||
muted: readVar('--muted', isDark ? '#1e2230' : '#f1f5f9'),
|
||||
mutedForeground: readVar('--muted-foreground', isDark ? '#94a3b8' : '#64748b'),
|
||||
border: readVar('--border', isDark ? '#2a3040' : '#e2e8f0'),
|
||||
primary: readVar('--primary', isDark ? '#38bdf8' : '#2563eb'),
|
||||
};
|
||||
}
|
||||
|
||||
export function PluginErCanvas({
|
||||
tables = [],
|
||||
relations = [],
|
||||
@@ -61,7 +77,7 @@ export function PluginErCanvas({
|
||||
const [panning, setPanning] = useState(false);
|
||||
|
||||
const tableSignature = useMemo(
|
||||
() => tables.map((t) => `${tableKey(t)}:${t.x ?? ''}:${t.y ?? ''}`).join('|'),
|
||||
() => tables.map((t) => `${erTableKey(t)}:${t.x ?? ''}:${t.y ?? ''}`).join('|'),
|
||||
[tables],
|
||||
);
|
||||
|
||||
@@ -70,7 +86,7 @@ export function PluginErCanvas({
|
||||
const defaults = computeInitialPositions(tables);
|
||||
const next: Record<string, { x: number; y: number }> = {};
|
||||
for (const tbl of tables) {
|
||||
const key = tableKey(tbl);
|
||||
const key = erTableKey(tbl);
|
||||
next[key] = prev[key] ?? defaults[key];
|
||||
}
|
||||
return next;
|
||||
@@ -81,7 +97,7 @@ export function PluginErCanvas({
|
||||
const byKey = new Map<string, PluginErTable>();
|
||||
const byName = new Map<string, PluginErTable>();
|
||||
for (const tbl of tables) {
|
||||
byKey.set(tableKey(tbl), tbl);
|
||||
byKey.set(erTableKey(tbl), tbl);
|
||||
if (!byName.has(tbl.name)) byName.set(tbl.name, tbl);
|
||||
}
|
||||
return { byKey, byName };
|
||||
@@ -104,11 +120,11 @@ export function PluginErCanvas({
|
||||
let maxX = -Infinity;
|
||||
let maxY = -Infinity;
|
||||
for (const tbl of tables) {
|
||||
const pos = positions[tableKey(tbl)] ?? { x: 0, y: 0 };
|
||||
const pos = positions[erTableKey(tbl)] ?? { x: 0, y: 0 };
|
||||
minX = Math.min(minX, pos.x);
|
||||
minY = Math.min(minY, pos.y);
|
||||
maxX = Math.max(maxX, pos.x + CARD_WIDTH);
|
||||
maxY = Math.max(maxY, pos.y + cardHeight(tbl));
|
||||
maxX = Math.max(maxX, pos.x + ER_CARD_WIDTH);
|
||||
maxY = Math.max(maxY, pos.y + erCardHeight(tbl));
|
||||
}
|
||||
const contentW = Math.max(1, maxX - minX);
|
||||
const contentH = Math.max(1, maxY - minY);
|
||||
@@ -154,6 +170,7 @@ export function PluginErCanvas({
|
||||
if (event.button !== 0) return;
|
||||
if ((event.target as Element).closest?.('[data-er-table]')) return;
|
||||
event.preventDefault();
|
||||
containerRef.current?.focus();
|
||||
const startX = event.clientX;
|
||||
const startY = event.clientY;
|
||||
const initialX = viewport.x;
|
||||
@@ -180,7 +197,8 @@ export function PluginErCanvas({
|
||||
const startCardDrag = useCallback((event: React.PointerEvent<SVGGElement>, table: PluginErTable) => {
|
||||
if (event.button !== 0) return;
|
||||
event.stopPropagation();
|
||||
const key = tableKey(table);
|
||||
containerRef.current?.focus();
|
||||
const key = erTableKey(table);
|
||||
const startX = event.clientX;
|
||||
const startY = event.clientY;
|
||||
const origin = positions[key] ?? { x: 0, y: 0 };
|
||||
@@ -216,6 +234,14 @@ export function PluginErCanvas({
|
||||
window.addEventListener('pointercancel', onUp);
|
||||
}, [positions, viewport.zoom, onWidgetEvent]);
|
||||
|
||||
const handleCardDoubleClick = useCallback((event: React.MouseEvent<SVGGElement>, table: PluginErTable) => {
|
||||
event.stopPropagation();
|
||||
onWidgetEvent('tableDoubleClick', {
|
||||
table: table.name,
|
||||
...(table.schema ? { schema: table.schema } : {}),
|
||||
});
|
||||
}, [onWidgetEvent]);
|
||||
|
||||
const zoomBy = useCallback((factor: number) => {
|
||||
const el = containerRef.current;
|
||||
const rect = el?.getBoundingClientRect();
|
||||
@@ -234,15 +260,35 @@ export function PluginErCanvas({
|
||||
|
||||
const resetLayout = useCallback(() => {
|
||||
setPositions(computeInitialPositions(tables));
|
||||
requestAnimationFrame(fitToView);
|
||||
if (typeof requestAnimationFrame === 'function') {
|
||||
requestAnimationFrame(fitToView);
|
||||
} else {
|
||||
fitToView();
|
||||
}
|
||||
}, [tables, fitToView]);
|
||||
|
||||
const handleExportSvg = useCallback(() => {
|
||||
const palette = resolveCanvasPalette(containerRef.current);
|
||||
const svg = buildStandaloneErSvg(tables, relations, positions, palette);
|
||||
onWidgetEvent('exportSvg', { svg });
|
||||
}, [tables, relations, positions, onWidgetEvent]);
|
||||
|
||||
const handleKeyDown = useCallback((event: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
const shortcut = matchWorkbenchShortcut(event, { includeUndoRedo: true });
|
||||
if (!shortcut) return;
|
||||
if (shortcut !== 'escape') event.preventDefault();
|
||||
event.stopPropagation();
|
||||
onWidgetEvent('shortcut', { shortcut });
|
||||
}, [onWidgetEvent]);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
data-plugin-er-canvas=""
|
||||
tabIndex={0}
|
||||
onWheel={handleWheel}
|
||||
className="relative h-full w-full min-h-0 min-w-0 overflow-hidden bg-background text-foreground select-none"
|
||||
onKeyDown={handleKeyDown}
|
||||
className="relative h-full w-full min-h-0 min-w-0 overflow-hidden bg-background text-foreground select-none outline-none"
|
||||
>
|
||||
{/* Floating Canvas Controls */}
|
||||
<div className="absolute right-3 top-3 z-20 flex items-center gap-1 rounded-lg border border-border bg-background/95 p-1 shadow-sm backdrop-blur-sm">
|
||||
@@ -251,7 +297,7 @@ export function PluginErCanvas({
|
||||
onClick={() => zoomBy(1.2)}
|
||||
aria-label="Zoom in"
|
||||
title="Zoom in"
|
||||
className="inline-flex h-6 w-6 items-center justify-center rounded hover:bg-accent text-muted-foreground hover:text-foreground"
|
||||
className="inline-flex h-6 w-6 items-center justify-center rounded hover:bg-muted text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<ZoomIn size={13} />
|
||||
</button>
|
||||
@@ -263,7 +309,7 @@ export function PluginErCanvas({
|
||||
onClick={() => zoomBy(1 / 1.2)}
|
||||
aria-label="Zoom out"
|
||||
title="Zoom out"
|
||||
className="inline-flex h-6 w-6 items-center justify-center rounded hover:bg-accent text-muted-foreground hover:text-foreground"
|
||||
className="inline-flex h-6 w-6 items-center justify-center rounded hover:bg-muted text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<ZoomOut size={13} />
|
||||
</button>
|
||||
@@ -273,7 +319,7 @@ export function PluginErCanvas({
|
||||
onClick={fitToView}
|
||||
aria-label="Fit to view"
|
||||
title="Fit to view"
|
||||
className="inline-flex h-6 items-center gap-1 rounded px-1.5 text-[11px] text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
className="inline-flex h-6 items-center gap-1 rounded px-1.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||
>
|
||||
<Maximize2 size={12} />
|
||||
Fit
|
||||
@@ -283,10 +329,22 @@ export function PluginErCanvas({
|
||||
onClick={resetLayout}
|
||||
aria-label="Reset layout"
|
||||
title="Reset layout"
|
||||
className="inline-flex h-6 w-6 items-center justify-center rounded hover:bg-accent text-muted-foreground hover:text-foreground"
|
||||
className="inline-flex h-6 w-6 items-center justify-center rounded hover:bg-muted text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<RotateCcw size={12} />
|
||||
</button>
|
||||
<div className="mx-0.5 h-4 w-px bg-border" />
|
||||
<button
|
||||
type="button"
|
||||
data-er-export-svg=""
|
||||
onClick={handleExportSvg}
|
||||
aria-label="Export SVG"
|
||||
title="Export SVG"
|
||||
className="inline-flex h-6 items-center gap-1 rounded px-1.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||
>
|
||||
<Download size={12} />
|
||||
Export SVG
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{tables.length === 0 ? (
|
||||
@@ -314,28 +372,34 @@ export function PluginErCanvas({
|
||||
const fromTable = resolveTable(rel.fromTable);
|
||||
const toTable = resolveTable(rel.toTable);
|
||||
if (!fromTable || !toTable) return null;
|
||||
const fromKey = tableKey(fromTable);
|
||||
const toKey = tableKey(toTable);
|
||||
const fromKey = erTableKey(fromTable);
|
||||
const toKey = erTableKey(toTable);
|
||||
const fromPos = positions[fromKey] ?? { x: 0, y: 0 };
|
||||
const toPos = positions[toKey] ?? { x: 0, y: 0 };
|
||||
const fromColIdx = Math.max(0, fromTable.columns.findIndex((c) => c.name === rel.fromColumn));
|
||||
const toColIdx = Math.max(0, toTable.columns.findIndex((c) => c.name === rel.toColumn));
|
||||
const y1 = fromPos.y + CARD_HEADER_HEIGHT + fromColIdx * CARD_ROW_HEIGHT + CARD_ROW_HEIGHT / 2;
|
||||
const y2 = toPos.y + CARD_HEADER_HEIGHT + toColIdx * CARD_ROW_HEIGHT + CARD_ROW_HEIGHT / 2;
|
||||
const fromCenter = fromPos.x + CARD_WIDTH / 2;
|
||||
const toCenter = toPos.x + CARD_WIDTH / 2;
|
||||
const y1 = fromPos.y + ER_CARD_HEADER_HEIGHT + fromColIdx * ER_CARD_ROW_HEIGHT + ER_CARD_ROW_HEIGHT / 2;
|
||||
const y2 = toPos.y + ER_CARD_HEADER_HEIGHT + toColIdx * ER_CARD_ROW_HEIGHT + ER_CARD_ROW_HEIGHT / 2;
|
||||
const fromCenter = fromPos.x + ER_CARD_WIDTH / 2;
|
||||
const toCenter = toPos.x + ER_CARD_WIDTH / 2;
|
||||
const goRight = toCenter >= fromCenter;
|
||||
const x1 = goRight ? fromPos.x + CARD_WIDTH : fromPos.x;
|
||||
const x2 = goRight ? toPos.x : toPos.x + CARD_WIDTH;
|
||||
const x1 = goRight ? fromPos.x + ER_CARD_WIDTH : fromPos.x;
|
||||
const x2 = goRight ? toPos.x : toPos.x + ER_CARD_WIDTH;
|
||||
const dx = Math.max(48, Math.abs(x2 - x1) * 0.45);
|
||||
const c1x = goRight ? x1 + dx : x1 - dx;
|
||||
const c2x = goRight ? x2 - dx : x2 + dx;
|
||||
const highlighted = hoveredRelation === idx || selectedTable === fromKey || selectedTable === toKey;
|
||||
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}`}
|
||||
onPointerEnter={() => setHoveredRelation(idx)}
|
||||
onPointerLeave={() => setHoveredRelation(null)}
|
||||
>
|
||||
@@ -343,7 +407,7 @@ export function PluginErCanvas({
|
||||
d={`M ${x1} ${y1} C ${c1x} ${y1}, ${c2x} ${y2}, ${x2} ${y2}`}
|
||||
fill="none"
|
||||
stroke="transparent"
|
||||
strokeWidth={12}
|
||||
strokeWidth={14}
|
||||
/>
|
||||
<path
|
||||
d={`M ${x1} ${y1} C ${c1x} ${y1}, ${c2x} ${y2}, ${x2} ${y2}`}
|
||||
@@ -354,17 +418,27 @@ 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} />
|
||||
{rel.name && highlighted && (
|
||||
<text
|
||||
x={(x1 + x2) / 2}
|
||||
y={(y1 + y2) / 2 - 6}
|
||||
textAnchor="middle"
|
||||
fontSize={10}
|
||||
fontFamily="var(--font-mono)"
|
||||
fill="hsl(var(--primary))"
|
||||
>
|
||||
{rel.name}
|
||||
</text>
|
||||
{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>
|
||||
);
|
||||
@@ -372,9 +446,9 @@ export function PluginErCanvas({
|
||||
|
||||
{/* Table Cards */}
|
||||
{tables.map((table) => {
|
||||
const key = tableKey(table);
|
||||
const key = erTableKey(table);
|
||||
const pos = positions[key] ?? { x: 0, y: 0 };
|
||||
const height = cardHeight(table);
|
||||
const height = erCardHeight(table);
|
||||
const isSelected = selectedTable === key;
|
||||
|
||||
return (
|
||||
@@ -383,11 +457,12 @@ export function PluginErCanvas({
|
||||
data-er-table={table.name}
|
||||
transform={`translate(${pos.x}, ${pos.y})`}
|
||||
onPointerDown={(e) => startCardDrag(e, table)}
|
||||
onDoubleClick={(e) => handleCardDoubleClick(e, table)}
|
||||
className="cursor-pointer"
|
||||
filter="url(#nc-er-shadow)"
|
||||
>
|
||||
<rect
|
||||
width={CARD_WIDTH}
|
||||
width={ER_CARD_WIDTH}
|
||||
height={height}
|
||||
rx={8}
|
||||
fill="hsl(var(--card))"
|
||||
@@ -396,14 +471,14 @@ export function PluginErCanvas({
|
||||
/>
|
||||
{/* Header band */}
|
||||
<path
|
||||
d={`M 0 8 Q 0 0 8 0 L ${CARD_WIDTH - 8} 0 Q ${CARD_WIDTH} 0 ${CARD_WIDTH} 8 L ${CARD_WIDTH} ${CARD_HEADER_HEIGHT} L 0 ${CARD_HEADER_HEIGHT} Z`}
|
||||
d={`M 0 8 Q 0 0 8 0 L ${ER_CARD_WIDTH - 8} 0 Q ${ER_CARD_WIDTH} 0 ${ER_CARD_WIDTH} 8 L ${ER_CARD_WIDTH} ${ER_CARD_HEADER_HEIGHT} L 0 ${ER_CARD_HEADER_HEIGHT} Z`}
|
||||
fill="hsl(var(--muted))"
|
||||
/>
|
||||
<line
|
||||
x1={0}
|
||||
y1={CARD_HEADER_HEIGHT}
|
||||
x2={CARD_WIDTH}
|
||||
y2={CARD_HEADER_HEIGHT}
|
||||
y1={ER_CARD_HEADER_HEIGHT}
|
||||
x2={ER_CARD_WIDTH}
|
||||
y2={ER_CARD_HEADER_HEIGHT}
|
||||
stroke="hsl(var(--border))"
|
||||
strokeWidth={1}
|
||||
/>
|
||||
@@ -420,15 +495,19 @@ export function PluginErCanvas({
|
||||
|
||||
{/* Columns */}
|
||||
{table.columns.map((col, colIdx) => {
|
||||
const rowY = CARD_HEADER_HEIGHT + colIdx * CARD_ROW_HEIGHT;
|
||||
const rowY = ER_CARD_HEADER_HEIGHT + colIdx * ER_CARD_ROW_HEIGHT;
|
||||
const badgeOffset = (col.isPk ? 26 : 0) + (col.isFk ? 26 : 0);
|
||||
const maxNameChars = badgeOffset >= 52 ? 12 : badgeOffset >= 26 ? 15 : 19;
|
||||
const displayName = col.name.length > maxNameChars ? `${col.name.slice(0, maxNameChars - 1)}…` : col.name;
|
||||
const displayType = `${abbreviateSqlType(col.type)}${col.nullable ? '?' : ''}`;
|
||||
return (
|
||||
<g key={col.name} transform={`translate(0, ${rowY})`}>
|
||||
<title>{`${col.name}: ${col.type}${col.nullable ? ' NULL' : ' NOT NULL'}`}</title>
|
||||
{colIdx > 0 && (
|
||||
<line
|
||||
x1={8}
|
||||
y1={0}
|
||||
x2={CARD_WIDTH - 8}
|
||||
x2={ER_CARD_WIDTH - 8}
|
||||
y2={0}
|
||||
stroke="hsl(var(--border))"
|
||||
strokeOpacity={0.45}
|
||||
@@ -458,17 +537,17 @@ export function PluginErCanvas({
|
||||
fontFamily="var(--font-mono)"
|
||||
fill="hsl(var(--card-foreground))"
|
||||
>
|
||||
{col.name.length > 18 ? `${col.name.slice(0, 17)}…` : col.name}
|
||||
{displayName}
|
||||
</text>
|
||||
<text
|
||||
x={CARD_WIDTH - 10}
|
||||
x={ER_CARD_WIDTH - 10}
|
||||
y={16}
|
||||
textAnchor="end"
|
||||
fontSize={10}
|
||||
fontFamily="var(--font-mono)"
|
||||
fill="hsl(var(--muted-foreground))"
|
||||
>
|
||||
{`${col.type}${col.nullable ? '?' : ''}`.slice(0, 14)}
|
||||
{displayType}
|
||||
</text>
|
||||
</g>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { abbreviateSqlType, buildStandaloneErSvg } from './erFormat';
|
||||
import { matchWorkbenchShortcut } from './shortcuts';
|
||||
|
||||
test('abbreviateSqlType shortens verbose SQL catalog types cleanly without mid-word clipping', () => {
|
||||
assert.equal(abbreviateSqlType('character varying(180)'), 'varchar(180)');
|
||||
assert.equal(abbreviateSqlType('timestamp with time zone'), 'timestamptz');
|
||||
assert.equal(abbreviateSqlType('timestamp without time zone'), 'timestamp');
|
||||
assert.equal(abbreviateSqlType('double precision'), 'float8');
|
||||
assert.equal(abbreviateSqlType('integer'), 'int4');
|
||||
assert.equal(abbreviateSqlType('boolean'), 'bool');
|
||||
assert.equal(abbreviateSqlType('numeric(10,2)'), 'numeric(10,2)');
|
||||
});
|
||||
|
||||
test('buildStandaloneErSvg generates valid self-contained SVG markup with tables, PK/FK pills, and Bezier relations', () => {
|
||||
const svg = buildStandaloneErSvg(
|
||||
[
|
||||
{ name: 'customers', schema: 'public', columns: [{ name: 'id', type: 'integer', isPk: true }, { name: 'email', type: 'character varying(180)', nullable: false }] },
|
||||
{ name: 'orders', schema: 'public', columns: [{ name: 'id', type: 'integer', isPk: true }, { name: 'customer_id', type: 'integer', isFk: true }] },
|
||||
],
|
||||
[{ fromTable: 'public.orders', fromColumn: 'customer_id', toTable: 'public.customers', toColumn: 'id', onDelete: 'CASCADE' }],
|
||||
{ 'public.customers': { x: 40, y: 40 }, 'public.orders': { x: 380, y: 40 } },
|
||||
{
|
||||
background: '#0f1117',
|
||||
card: '#161922',
|
||||
cardForeground: '#f1f5f9',
|
||||
muted: '#1e2230',
|
||||
mutedForeground: '#94a3b8',
|
||||
border: '#2a3040',
|
||||
primary: '#38bdf8',
|
||||
},
|
||||
);
|
||||
assert.match(svg, /^<svg xmlns="http:\/\/www\.w3\.org\/2000\/svg"/);
|
||||
assert.match(svg, /<\/svg>$/);
|
||||
assert.match(svg, /public\.customers/);
|
||||
assert.match(svg, /varchar\(180\)/);
|
||||
assert.match(svg, />PK</);
|
||||
assert.match(svg, />FK</);
|
||||
assert.match(svg, /<path d="M /);
|
||||
});
|
||||
|
||||
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');
|
||||
assert.equal(matchWorkbenchShortcut({ key: 's', metaKey: true }), 'mod+s');
|
||||
assert.equal(matchWorkbenchShortcut({ key: 't', ctrlKey: true }), 'mod+t');
|
||||
assert.equal(matchWorkbenchShortcut({ key: 'w', metaKey: true }), 'mod+w');
|
||||
assert.equal(matchWorkbenchShortcut({ key: 'z', metaKey: true }), 'mod+z');
|
||||
assert.equal(matchWorkbenchShortcut({ key: 'Z', metaKey: true, shiftKey: true }), 'mod+shift+z');
|
||||
assert.equal(matchWorkbenchShortcut({ key: 'y', ctrlKey: true }), 'mod+shift+z');
|
||||
assert.equal(matchWorkbenchShortcut({ key: 'Escape' }), 'escape');
|
||||
assert.equal(matchWorkbenchShortcut({ key: 'z', metaKey: true }, { includeUndoRedo: false }), null);
|
||||
assert.equal(matchWorkbenchShortcut({ key: 'c', metaKey: true }), null);
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
import type { PluginErRelation, PluginErTable } from './types';
|
||||
|
||||
export const ER_CARD_WIDTH = 252;
|
||||
export const ER_CARD_HEADER_HEIGHT = 34;
|
||||
export const ER_CARD_ROW_HEIGHT = 24;
|
||||
export const ER_CARD_FOOTER_PADDING = 8;
|
||||
|
||||
/** Abbreviate verbose SQL types (especially PostgreSQL catalog names) so ER cards never clip mid-word. */
|
||||
export function abbreviateSqlType(rawType: string): string {
|
||||
const trimmed = rawType.trim();
|
||||
if (!trimmed) return '';
|
||||
let out = trimmed
|
||||
.replace(/\bcharacter\s+varying\b/gi, 'varchar')
|
||||
.replace(/\bcharacter\b(?=\s*\()/gi, 'char')
|
||||
.replace(/\btimestamp\s*(?:\(\d+\)\s*)?with\s+time\s+zone\b/gi, 'timestamptz')
|
||||
.replace(/\btimestamp\s*(?:\(\d+\)\s*)?without\s+time\s+zone\b/gi, 'timestamp')
|
||||
.replace(/\btime\s*(?:\(\d+\)\s*)?with\s+time\s+zone\b/gi, 'timetz')
|
||||
.replace(/\btime\s*(?:\(\d+\)\s*)?without\s+time\s+zone\b/gi, 'time')
|
||||
.replace(/\bdouble\s+precision\b/gi, 'float8')
|
||||
.replace(/\bboolean\b/gi, 'bool')
|
||||
.replace(/\binteger\b/gi, 'int4')
|
||||
.replace(/\bsmallint\b/gi, 'int2')
|
||||
.replace(/\bbigint\b/gi, 'int8')
|
||||
.replace(/\s+/g, ' ');
|
||||
if (out.length > 18) {
|
||||
out = `${out.slice(0, 17)}…`;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function erTableKey(table: Pick<PluginErTable, 'name' | 'schema'>): string {
|
||||
return table.schema ? `${table.schema}.${table.name}` : table.name;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
function escapeXml(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
export interface ErSvgPalette {
|
||||
background: string;
|
||||
card: string;
|
||||
cardForeground: string;
|
||||
muted: string;
|
||||
mutedForeground: string;
|
||||
border: string;
|
||||
primary: string;
|
||||
}
|
||||
|
||||
export function buildStandaloneErSvg(
|
||||
tables: PluginErTable[],
|
||||
relations: PluginErRelation[],
|
||||
positions: Record<string, { x: number; y: number }>,
|
||||
palette: ErSvgPalette,
|
||||
): string {
|
||||
const byKey = new Map<string, PluginErTable>();
|
||||
const byName = new Map<string, PluginErTable>();
|
||||
for (const tbl of tables) {
|
||||
byKey.set(erTableKey(tbl), tbl);
|
||||
if (!byName.has(tbl.name)) byName.set(tbl.name, tbl);
|
||||
}
|
||||
const resolveTable = (ref: string) => byKey.get(ref) ?? byName.get(ref);
|
||||
|
||||
let minX = Infinity;
|
||||
let minY = Infinity;
|
||||
let maxX = -Infinity;
|
||||
let maxY = -Infinity;
|
||||
for (const tbl of tables) {
|
||||
const pos = positions[erTableKey(tbl)] ?? { x: 40, y: 40 };
|
||||
minX = Math.min(minX, pos.x);
|
||||
minY = Math.min(minY, pos.y);
|
||||
maxX = Math.max(maxX, pos.x + ER_CARD_WIDTH);
|
||||
maxY = Math.max(maxY, pos.y + erCardHeight(tbl));
|
||||
}
|
||||
if (!Number.isFinite(minX)) {
|
||||
minX = 0; minY = 0; maxX = 400; maxY = 240;
|
||||
}
|
||||
const pad = 40;
|
||||
const vbX = Math.floor(minX - pad);
|
||||
const vbY = Math.floor(minY - pad);
|
||||
const vbW = Math.max(200, Math.ceil(maxX - minX + pad * 2));
|
||||
const vbH = Math.max(160, Math.ceil(maxY - minY + pad * 2));
|
||||
|
||||
const lines: string[] = [
|
||||
`<svg xmlns="http://www.w3.org/2000/svg" width="${vbW}" height="${vbH}" viewBox="${vbX} ${vbY} ${vbW} ${vbH}">`,
|
||||
`<rect x="${vbX}" y="${vbY}" width="${vbW}" height="${vbH}" fill="${escapeXml(palette.background)}" />`,
|
||||
];
|
||||
|
||||
for (const rel of relations) {
|
||||
const fromTable = resolveTable(rel.fromTable);
|
||||
const toTable = resolveTable(rel.toTable);
|
||||
if (!fromTable || !toTable) continue;
|
||||
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((c) => c.name === rel.fromColumn));
|
||||
const toColIdx = Math.max(0, toTable.columns.findIndex((c) => c.name === rel.toColumn));
|
||||
const y1 = fromPos.y + ER_CARD_HEADER_HEIGHT + fromColIdx * ER_CARD_ROW_HEIGHT + ER_CARD_ROW_HEIGHT / 2;
|
||||
const y2 = toPos.y + ER_CARD_HEADER_HEIGHT + toColIdx * ER_CARD_ROW_HEIGHT + ER_CARD_ROW_HEIGHT / 2;
|
||||
const goRight = (toPos.x + ER_CARD_WIDTH / 2) >= (fromPos.x + ER_CARD_WIDTH / 2);
|
||||
const x1 = goRight ? fromPos.x + ER_CARD_WIDTH : fromPos.x;
|
||||
const x2 = goRight ? toPos.x : toPos.x + ER_CARD_WIDTH;
|
||||
const dx = Math.max(48, Math.abs(x2 - x1) * 0.45);
|
||||
const c1x = goRight ? x1 + dx : x1 - dx;
|
||||
const c2x = goRight ? x2 - dx : x2 + dx;
|
||||
lines.push(
|
||||
`<path d="M ${x1} ${y1} C ${c1x} ${y1}, ${c2x} ${y2}, ${x2} ${y2}" fill="none" stroke="${escapeXml(palette.mutedForeground)}" stroke-width="1.5" stroke-opacity="0.75" />`,
|
||||
`<circle cx="${x1}" cy="${y1}" r="3.5" fill="${escapeXml(palette.mutedForeground)}" />`,
|
||||
`<circle cx="${x2}" cy="${y2}" r="3.5" fill="${escapeXml(palette.background)}" stroke="${escapeXml(palette.mutedForeground)}" stroke-width="1.8" />`,
|
||||
);
|
||||
}
|
||||
|
||||
for (const tbl of tables) {
|
||||
const pos = positions[erTableKey(tbl)] ?? { x: 0, y: 0 };
|
||||
const h = erCardHeight(tbl);
|
||||
const title = tbl.schema ? `${tbl.schema}.${tbl.name}` : tbl.name;
|
||||
lines.push(`<g transform="translate(${pos.x}, ${pos.y})">`);
|
||||
lines.push(`<rect width="${ER_CARD_WIDTH}" height="${h}" rx="8" fill="${escapeXml(palette.card)}" stroke="${escapeXml(palette.border)}" stroke-width="1" />`);
|
||||
lines.push(`<path d="M 0 8 Q 0 0 8 0 L ${ER_CARD_WIDTH - 8} 0 Q ${ER_CARD_WIDTH} 0 ${ER_CARD_WIDTH} 8 L ${ER_CARD_WIDTH} ${ER_CARD_HEADER_HEIGHT} L 0 ${ER_CARD_HEADER_HEIGHT} Z" fill="${escapeXml(palette.muted)}" />`);
|
||||
lines.push(`<line x1="0" y1="${ER_CARD_HEADER_HEIGHT}" x2="${ER_CARD_WIDTH}" y2="${ER_CARD_HEADER_HEIGHT}" stroke="${escapeXml(palette.border)}" stroke-width="1" />`);
|
||||
lines.push(`<text x="12" y="21" font-size="12" font-weight="600" font-family="system-ui, -apple-system, sans-serif" fill="${escapeXml(palette.cardForeground)}">${escapeXml(title)}</text>`);
|
||||
|
||||
tbl.columns.forEach((col, colIdx) => {
|
||||
const rowY = ER_CARD_HEADER_HEIGHT + colIdx * ER_CARD_ROW_HEIGHT;
|
||||
const badgeOffset = (col.isPk ? 26 : 0) + (col.isFk ? 26 : 0);
|
||||
const shortType = `${abbreviateSqlType(col.type)}${col.nullable ? '?' : ''}`;
|
||||
const colLabel = col.name.length > 18 ? `${col.name.slice(0, 17)}…` : col.name;
|
||||
lines.push(`<g transform="translate(0, ${rowY})">`);
|
||||
if (colIdx > 0) {
|
||||
lines.push(`<line x1="8" y1="0" x2="${ER_CARD_WIDTH - 8}" y2="0" stroke="${escapeXml(palette.border)}" stroke-opacity="0.45" stroke-width="0.75" />`);
|
||||
}
|
||||
if (col.isPk) {
|
||||
lines.push(`<rect x="8" y="5" width="22" height="14" rx="3" fill="#f59e0b" fill-opacity="0.2" /><text x="19" y="15.5" text-anchor="middle" font-size="9" font-weight="700" font-family="system-ui, sans-serif" fill="#d97706">PK</text>`);
|
||||
}
|
||||
if (col.isFk) {
|
||||
const fkX = col.isPk ? 34 : 8;
|
||||
lines.push(`<rect x="${fkX}" y="5" width="22" height="14" rx="3" fill="#3b82f6" fill-opacity="0.2" /><text x="${fkX + 11}" y="15.5" text-anchor="middle" font-size="9" font-weight="700" font-family="system-ui, sans-serif" fill="#2563eb">FK</text>`);
|
||||
}
|
||||
lines.push(`<text x="${10 + badgeOffset}" y="16" font-size="11" font-family="ui-monospace, monospace" fill="${escapeXml(palette.cardForeground)}">${escapeXml(colLabel)}</text>`);
|
||||
lines.push(`<text x="${ER_CARD_WIDTH - 10}" y="16" text-anchor="end" font-size="10" font-family="ui-monospace, monospace" fill="${escapeXml(palette.mutedForeground)}">${escapeXml(shortType)}</text>`);
|
||||
lines.push('</g>');
|
||||
});
|
||||
lines.push('</g>');
|
||||
}
|
||||
|
||||
lines.push('</svg>');
|
||||
return lines.join('\n');
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { PluginWorkbenchShortcut } from './types';
|
||||
|
||||
export interface KeyboardShortcutLike {
|
||||
key: string;
|
||||
metaKey?: boolean;
|
||||
ctrlKey?: boolean;
|
||||
altKey?: boolean;
|
||||
shiftKey?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize global workbench shortcuts pressed inside plugin views/widgets.
|
||||
* Returns null for unrecognized key combinations.
|
||||
*/
|
||||
export function matchWorkbenchShortcut(
|
||||
event: KeyboardShortcutLike,
|
||||
options?: { includeUndoRedo?: boolean },
|
||||
): PluginWorkbenchShortcut | null {
|
||||
const includeUndoRedo = options?.includeUndoRedo ?? true;
|
||||
if (event.key === 'Escape' && !event.metaKey && !event.ctrlKey && !event.altKey) {
|
||||
return 'escape';
|
||||
}
|
||||
const mod = Boolean(event.metaKey || event.ctrlKey);
|
||||
if (!mod || event.altKey) return null;
|
||||
const key = event.key.toLowerCase();
|
||||
if (key === 'k' && !event.shiftKey) return 'mod+k';
|
||||
if (key === 's' && !event.shiftKey) return 'mod+s';
|
||||
if (key === 't' && !event.shiftKey) return 'mod+t';
|
||||
if (key === 'w' && !event.shiftKey) return 'mod+w';
|
||||
if (includeUndoRedo) {
|
||||
if (key === 'z' && event.shiftKey) return 'mod+shift+z';
|
||||
if (key === 'z' && !event.shiftKey) return 'mod+z';
|
||||
if (key === 'y' && event.ctrlKey && !event.metaKey && !event.shiftKey) return 'mod+shift+z';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -3,6 +3,15 @@ export type PluginWidgetEventCallback = (
|
||||
detail?: Record<string, unknown>,
|
||||
) => void;
|
||||
|
||||
export type PluginWorkbenchShortcut =
|
||||
| 'mod+k'
|
||||
| 'mod+s'
|
||||
| 'mod+t'
|
||||
| 'mod+w'
|
||||
| 'mod+z'
|
||||
| 'mod+shift+z'
|
||||
| 'escape';
|
||||
|
||||
export interface PluginCodeEditorCompletionColumn {
|
||||
name: string;
|
||||
type?: string;
|
||||
@@ -48,6 +57,12 @@ export interface PluginCodeEditorWidgetProps {
|
||||
height?: number | string;
|
||||
}
|
||||
|
||||
export interface PluginDataGridForeignKey {
|
||||
table: string;
|
||||
column: string;
|
||||
schema?: string;
|
||||
}
|
||||
|
||||
export interface PluginDataGridColumn {
|
||||
name: string;
|
||||
type?: string;
|
||||
@@ -55,6 +70,7 @@ export interface PluginDataGridColumn {
|
||||
nullable?: boolean;
|
||||
width?: number;
|
||||
sortable?: boolean;
|
||||
foreignKey?: PluginDataGridForeignKey;
|
||||
}
|
||||
|
||||
export interface PluginDataGridSort {
|
||||
@@ -67,6 +83,7 @@ export type PluginDataGridRow = Record<string, unknown> | unknown[];
|
||||
export interface PluginDataGridWidgetProps {
|
||||
columns?: PluginDataGridColumn[];
|
||||
rows?: PluginDataGridRow[];
|
||||
hiddenColumns?: string[];
|
||||
rowKeyField?: string;
|
||||
dirtyCells?: Record<string, unknown>;
|
||||
deletedRowIndices?: number[];
|
||||
@@ -109,6 +126,8 @@ export interface PluginErRelation {
|
||||
toTable: string;
|
||||
toColumn: string;
|
||||
name?: string;
|
||||
onDelete?: string;
|
||||
onUpdate?: string;
|
||||
}
|
||||
|
||||
export interface PluginErCanvasWidgetProps {
|
||||
|
||||
@@ -683,6 +683,7 @@ export const AIChatPanelsHost = memo(AIChatPanelsHostInner, aiChatPanelsHostAreE
|
||||
AIChatPanelsHost.displayName = 'AIChatPanelsHost';
|
||||
|
||||
export interface TerminalLayerProps {
|
||||
isVaultInitialized?: boolean;
|
||||
hosts: Host[];
|
||||
portForwardingRules?: import('../../domain/models').PortForwardingRule[];
|
||||
customGroups: string[];
|
||||
@@ -822,6 +823,7 @@ interface TerminalPaneProps {
|
||||
splitVerticalHandlersRef: React.MutableRefObject<Map<string, () => void>>;
|
||||
resolveSessionAppearance: (hostScope: TerminalAppearanceHostScope) => ResolvedAppearance;
|
||||
hostMap: Map<string, Host>;
|
||||
isVaultInitialized?: boolean;
|
||||
keys: SSHKey[];
|
||||
identities: Identity[];
|
||||
snippets: Snippet[];
|
||||
@@ -961,6 +963,7 @@ const terminalPanePropsAreEqual = (
|
||||
prev.splitHorizontalHandlersRef === next.splitHorizontalHandlersRef &&
|
||||
prev.splitVerticalHandlersRef === next.splitVerticalHandlersRef &&
|
||||
getPaneAppearanceThemeId(prev) === getPaneAppearanceThemeId(next) &&
|
||||
prev.isVaultInitialized === next.isVaultInitialized &&
|
||||
prev.keys === next.keys &&
|
||||
prev.identities === next.identities &&
|
||||
prev.snippets === next.snippets &&
|
||||
@@ -1253,6 +1256,7 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
|
||||
splitVerticalHandlersRef,
|
||||
resolveSessionAppearance,
|
||||
hostMap,
|
||||
isVaultInitialized,
|
||||
keys,
|
||||
identities,
|
||||
snippets,
|
||||
@@ -1643,12 +1647,12 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
|
||||
"absolute bg-background",
|
||||
inActiveWorkspace && "workspace-pane",
|
||||
isVisible && "z-10",
|
||||
isMagnified && magnifiedSurfaceBounds && "overflow-hidden rounded-md border shadow-2xl",
|
||||
magnifiedSurfaceBounds && "overflow-hidden rounded-md border shadow-2xl",
|
||||
)}
|
||||
style={{
|
||||
...style,
|
||||
borderColor: isMagnified && magnifiedSurfaceBounds ? sessionAppearanceTheme.colors.cursor : undefined,
|
||||
borderWidth: isMagnified && magnifiedSurfaceBounds
|
||||
borderColor: magnifiedSurfaceBounds ? sessionAppearanceTheme.colors.cursor : undefined,
|
||||
borderWidth: magnifiedSurfaceBounds
|
||||
? resolveMagnifiedChromeBorderWidth(magnifiedDevicePixelRatio)
|
||||
: undefined,
|
||||
}}
|
||||
@@ -1680,6 +1684,7 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
|
||||
sessionId={session.id}
|
||||
workspaceId={session.workspaceId}
|
||||
restoreState={session.restoreState}
|
||||
vaultInitializedOverride={isVaultInitialized}
|
||||
pendingInitialCwd={session.pendingInitialCwd}
|
||||
shellType={session.shellType}
|
||||
lastCwd={session.lastCwd}
|
||||
@@ -1776,6 +1781,7 @@ interface TerminalPanesHostProps {
|
||||
splitVerticalHandlersRef: React.MutableRefObject<Map<string, () => void>>;
|
||||
resolveSessionAppearance: (hostScope: TerminalAppearanceHostScope) => ResolvedAppearance;
|
||||
hostMap: Map<string, Host>;
|
||||
isVaultInitialized?: boolean;
|
||||
keys: SSHKey[];
|
||||
identities: Identity[];
|
||||
snippets: Snippet[];
|
||||
@@ -1871,6 +1877,7 @@ const terminalPanesHostPropsAreEqual = (
|
||||
if (prev.splitVerticalHandlersRef !== next.splitVerticalHandlersRef) return false;
|
||||
if (prev.resolveSessionAppearance !== next.resolveSessionAppearance) return false;
|
||||
if (prev.hostMap !== next.hostMap) return false;
|
||||
if (prev.isVaultInitialized !== next.isVaultInitialized) return false;
|
||||
if (prev.keys !== next.keys) return false;
|
||||
if (prev.identities !== next.identities) return false;
|
||||
if (prev.snippets !== next.snippets) return false;
|
||||
|
||||
@@ -5,18 +5,45 @@ import React from "react";
|
||||
import { act, create } from "react-test-renderer";
|
||||
import { sidePanelLiveStore, SIDE_PANEL_INACTIVE_LIVE_SNAPSHOT } from "../../application/state/sidePanelLiveStore.ts";
|
||||
import { createEmptyWorkspaceRoot } from "../../domain/workspace.ts";
|
||||
import { resolveMagnifiedChromeBorderWidth } from "../../domain/paneMagnification.ts";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
import { TerminalLayerWorkspaceSection } from "./TerminalLayerWorkspaceSection.tsx";
|
||||
|
||||
test("magnified terminal panes use the resolved terminal accent for border chrome", () => {
|
||||
test("terminal pane chrome follows retained surface bounds through restore", () => {
|
||||
const source = readFileSync(new URL("./TerminalLayerSupport.tsx", import.meta.url), "utf8");
|
||||
const paneSource = source.slice(source.indexOf('data-section="terminal-split-pane"'), source.indexOf("<Terminal\n"));
|
||||
|
||||
assert.match(paneSource, /isMagnified && magnifiedSurfaceBounds && "overflow-hidden rounded-md border shadow-2xl"/);
|
||||
assert.match(paneSource, /borderColor: isMagnified && magnifiedSurfaceBounds \? sessionAppearanceTheme\.colors\.cursor : undefined/);
|
||||
assert.match(paneSource, /borderWidth: isMagnified && magnifiedSurfaceBounds/);
|
||||
assert.match(paneSource, /resolveMagnifiedChromeBorderWidth\(magnifiedDevicePixelRatio\)/);
|
||||
assert.match(paneSource, /^\s*magnifiedSurfaceBounds && "overflow-hidden rounded-md border shadow-2xl",$/m);
|
||||
assert.match(paneSource, /borderColor: magnifiedSurfaceBounds \? sessionAppearanceTheme\.colors\.cursor : undefined/);
|
||||
assert.match(paneSource, /borderWidth: magnifiedSurfaceBounds\s*\? resolveMagnifiedChromeBorderWidth\(magnifiedDevicePixelRatio\)\s*: undefined/);
|
||||
});
|
||||
|
||||
test("restoring terminal chrome keeps its width and color until surface bounds clear", () => {
|
||||
const source = readFileSync(new URL("./TerminalLayerSupport.tsx", import.meta.url), "utf8");
|
||||
const paneSource = source.slice(source.indexOf('data-section="terminal-split-pane"'), source.indexOf("<Terminal\n"));
|
||||
const styleSource = paneSource.match(/style=\{\{([\s\S]*?)\}\}/);
|
||||
assert.ok(styleSource);
|
||||
const resolveStyle = new Function(
|
||||
"style", "isMagnified", "magnifiedSurfaceBounds", "sessionAppearanceTheme",
|
||||
"magnifiedDevicePixelRatio", "resolveMagnifiedChromeBorderWidth",
|
||||
`return ({${styleSource[1]}});`,
|
||||
);
|
||||
const bounds = { left: 0, top: 80, width: 1200, height: 800 };
|
||||
const theme = { colors: { cursor: "#0088ff" } };
|
||||
|
||||
for (const dpr of [1, 2]) {
|
||||
const magnified = resolveStyle({}, true, bounds, theme, dpr, resolveMagnifiedChromeBorderWidth);
|
||||
const restoring = resolveStyle({}, false, bounds, theme, dpr, resolveMagnifiedChromeBorderWidth);
|
||||
assert.deepEqual(restoring, magnified);
|
||||
assert.equal(restoring.borderColor, theme.colors.cursor);
|
||||
assert.equal(restoring.borderWidth, dpr === 1 ? 2 : 1);
|
||||
for (const isMagnified of [false, true]) {
|
||||
const cleared = resolveStyle({}, isMagnified, null, theme, dpr, resolveMagnifiedChromeBorderWidth);
|
||||
assert.equal(cleared.borderColor, undefined);
|
||||
assert.equal(cleared.borderWidth, undefined);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("magnified terminal panes snap overlay bounds to the device-pixel grid", () => {
|
||||
|
||||
@@ -62,6 +62,7 @@ function TerminalLayerWorkspaceSectionInner({ ctx }: { ctx: WorkspaceContext })
|
||||
splitVerticalHandlersRef,
|
||||
resolveSessionAppearance,
|
||||
hostMap,
|
||||
isVaultInitialized,
|
||||
keys,
|
||||
identities,
|
||||
snippets,
|
||||
@@ -230,6 +231,7 @@ function TerminalLayerWorkspaceSectionInner({ ctx }: { ctx: WorkspaceContext })
|
||||
splitVerticalHandlersRef={splitVerticalHandlersRef}
|
||||
resolveSessionAppearance={resolveSessionAppearance}
|
||||
hostMap={hostMap}
|
||||
isVaultInitialized={isVaultInitialized}
|
||||
keys={keys}
|
||||
identities={identities}
|
||||
snippets={snippets}
|
||||
|
||||
@@ -383,6 +383,7 @@ const WORKSPACE_CTX_KEYS = [
|
||||
'splitVerticalHandlersRef',
|
||||
'resolveSessionAppearance',
|
||||
'hostMap',
|
||||
'isVaultInitialized',
|
||||
'keys',
|
||||
'identities',
|
||||
'snippets',
|
||||
|
||||
@@ -4,6 +4,7 @@ export const terminalLayerAreEqual = (
|
||||
prev: Record<string, unknown>,
|
||||
next: Record<string, unknown>,
|
||||
): boolean => (
|
||||
prev.isVaultInitialized === next.isVaultInitialized &&
|
||||
prev.hosts === next.hosts &&
|
||||
prev.customGroups === next.customGroups &&
|
||||
prev.groupConfigs === next.groupConfigs &&
|
||||
|
||||
@@ -26,8 +26,6 @@ import { resolveSessionCodingCliProvider } from '../../domain/codingCliProviderM
|
||||
import type { CodingCliProvider } from '../../domain/codingCliProviders';
|
||||
import { resolveCodingCliActivityPhase, type CodingCliActivityPhase } from '../../domain/codingCliTitleParse';
|
||||
import {
|
||||
buildMergedWorkspaceTitleFromSessions,
|
||||
DEFAULT_WORKSPACE_TITLE,
|
||||
resolveSessionTabTitle,
|
||||
resolveWorkspaceTabLabel,
|
||||
} from '../../domain/sessionTabTitle';
|
||||
@@ -261,24 +259,15 @@ export const formatSessionTopTabLabel = (
|
||||
|
||||
type WorkspaceTopTabLabelWorkspace = Pick<
|
||||
Workspace,
|
||||
'title' | 'focusedSessionId' | 'autoTitle'
|
||||
> & {
|
||||
generatedTitle?: boolean;
|
||||
};
|
||||
'title' | 'focusedSessionId' | 'autoTitle' | 'generatedTitle'
|
||||
>;
|
||||
|
||||
export const resolveWorkspaceTopTabLabel = (
|
||||
workspace: WorkspaceTopTabLabelWorkspace,
|
||||
sessions: readonly TerminalSession[],
|
||||
dynamicTabTitleMode?: DynamicTabTitleMode,
|
||||
): string => {
|
||||
const presentedSessions = sessions.map(applySessionPresentation);
|
||||
const resolvedWorkspace = workspace.generatedTitle
|
||||
? {
|
||||
...workspace,
|
||||
title: buildMergedWorkspaceTitleFromSessions(presentedSessions) ?? DEFAULT_WORKSPACE_TITLE,
|
||||
autoTitle: false,
|
||||
}
|
||||
: workspace;
|
||||
return resolveWorkspaceTabLabel(resolvedWorkspace, presentedSessions);
|
||||
return resolveWorkspaceTabLabel(workspace, sessions.map(applySessionPresentation), dynamicTabTitleMode);
|
||||
};
|
||||
|
||||
export const createTopTabCopyDoubleClickHandler = (
|
||||
@@ -1106,7 +1095,7 @@ export const WorkspaceTopTab: React.FC<WorkspaceTopTabProps> = memo(({
|
||||
[onCopyWorkspace, workspace.id, tabDoubleClickBehavior],
|
||||
);
|
||||
const detachSessions = workspaceSessions ?? [];
|
||||
const tabLabel = resolveWorkspaceTopTabLabel(workspace, detachSessions);
|
||||
const tabLabel = resolveWorkspaceTopTabLabel(workspace, detachSessions, dynamicTabTitleMode);
|
||||
|
||||
return (
|
||||
<ContextMenu>
|
||||
|
||||
@@ -22,6 +22,68 @@ test('getSessionConnectionLabel prefers customName over hostLabel', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('connection identity ignores live prompt hostnames', () => {
|
||||
const session = { hostLabel: 'Production', promptHostname: 'vm-prod' };
|
||||
assert.equal(getSessionConnectionLabel(session), session.hostLabel);
|
||||
});
|
||||
|
||||
test('ordinary SSH prompt hostnames do not replace configured names by default', () => {
|
||||
const session = { hostLabel: 'Production', promptHostname: 'vm-prod' };
|
||||
for (const mode of [undefined, 'off', 'agent'] as const) {
|
||||
assert.equal(resolveSessionTabTitle(session, mode), session.hostLabel, String(mode));
|
||||
}
|
||||
});
|
||||
|
||||
test('agent mode does not use a prompt hostname when the agent has no title', () => {
|
||||
const session = {
|
||||
hostLabel: 'Production', promptHostname: 'vm-prod', codingCliProviderId: 'claude' as const,
|
||||
};
|
||||
assert.equal(resolveSessionTabTitle(session, 'agent'), session.hostLabel);
|
||||
});
|
||||
|
||||
test('persisted merged workspace identities ignore live hostnames', () => {
|
||||
const sessions = [
|
||||
{ id: 'a', hostId: 'h1', hostLabel: 'Production', promptHostname: 'vm-prod' },
|
||||
{ id: 'b', hostId: 'h2', hostLabel: 'Database', promptHostname: 'db-prod' },
|
||||
];
|
||||
assert.equal(
|
||||
buildMergedWorkspaceTitleFromSessions(sessions),
|
||||
buildMergedWorkspaceTitle(sessions[0].hostLabel, sessions[1].hostLabel),
|
||||
);
|
||||
});
|
||||
|
||||
test('auto workspace labels honor disabled and agent-only modes', () => {
|
||||
const session = { id: 'a', hostId: 'h1', hostLabel: 'Production', promptHostname: 'vm-prod' };
|
||||
const workspace = { title: DEFAULT_WORKSPACE_TITLE, autoTitle: true, focusedSessionId: session.id };
|
||||
for (const mode of [undefined, 'off', 'agent'] as const) {
|
||||
assert.equal(resolveWorkspaceTabLabel(workspace, [session], mode), session.hostLabel, String(mode));
|
||||
}
|
||||
});
|
||||
|
||||
test('auto workspace labels use the same agent title policy as session tabs', () => {
|
||||
const session = {
|
||||
id: 'a', hostId: 'h1', hostLabel: 'Production', promptHostname: 'vm-prod',
|
||||
dynamicTitle: 'claude: deploy', codingCliProviderId: 'claude' as const,
|
||||
};
|
||||
const workspace = { title: DEFAULT_WORKSPACE_TITLE, autoTitle: true, focusedSessionId: session.id };
|
||||
assert.equal(resolveWorkspaceTabLabel(workspace, [session], 'agent'), session.dynamicTitle);
|
||||
});
|
||||
|
||||
test('generated workspace display titles honor mode without changing their saved identity', () => {
|
||||
const sessions = [
|
||||
{ id: 'a', hostId: 'h1', hostLabel: 'Production', promptHostname: 'vm-prod' },
|
||||
{ id: 'b', hostId: 'h2', hostLabel: 'Database', promptHostname: 'db-prod' },
|
||||
];
|
||||
const savedTitle = buildMergedWorkspaceTitle(sessions[0].hostLabel, sessions[1].hostLabel)!;
|
||||
const workspace = { title: savedTitle, autoTitle: false, generatedTitle: true, focusedSessionId: 'a' };
|
||||
assert.equal(resolveWorkspaceTabLabel(workspace, sessions, 'off'), savedTitle);
|
||||
assert.equal(
|
||||
resolveWorkspaceTabLabel(workspace, sessions, 'all'),
|
||||
buildMergedWorkspaceTitle(sessions[0].promptHostname, sessions[1].promptHostname),
|
||||
);
|
||||
assert.equal(workspace.title, savedTitle);
|
||||
});
|
||||
|
||||
test('resolveSessionTabTitle ignores dynamic title for non-agent sessions', () => {
|
||||
assert.equal(
|
||||
resolveSessionTabTitle(
|
||||
@@ -85,12 +147,12 @@ test('resolveSessionTabTitle strips agent spinner prefixes from dynamic titles',
|
||||
);
|
||||
});
|
||||
|
||||
test('resolveSessionTabTitle uses a detected prompt host ahead of hostLabel', () => {
|
||||
test('resolveSessionTabTitle uses a detected prompt host in all mode', () => {
|
||||
assert.equal(
|
||||
resolveSessionTabTitle({
|
||||
hostLabel: 'jumpserver',
|
||||
promptHostname: '10.1.64.1',
|
||||
}),
|
||||
}, 'all'),
|
||||
'10.1.64.1',
|
||||
);
|
||||
});
|
||||
@@ -300,3 +362,183 @@ test('buildMergedWorkspaceTitleFromSessions recomputes from live membership', ()
|
||||
'01/02',
|
||||
);
|
||||
});
|
||||
|
||||
// External review examples: the expected field is part of the contract, not
|
||||
// computed by resolveSessionTabTitle or another display-title helper.
|
||||
const reviewedAllTitleCases = [
|
||||
{
|
||||
name: 'same-host shell title retains username and cwd',
|
||||
session: { hostLabel: 'Production', promptHostname: 'web01', dynamicTitle: 'ubuntu@web01: ~/app' },
|
||||
expectedField: 'dynamicTitle',
|
||||
},
|
||||
{
|
||||
name: 'old shell host gives way to the current prompt host',
|
||||
session: { hostLabel: 'Database entry', promptHostname: 'db02', dynamicTitle: 'ubuntu@web01: ~/app' },
|
||||
expectedField: 'promptHostname',
|
||||
},
|
||||
{
|
||||
name: 'JumpServer transport title gives way to the target prompt host',
|
||||
session: { hostLabel: 'Jump fleet', promptHostname: 'target-01', dynamicTitle: 'user@jumpssh:2222' },
|
||||
expectedField: 'promptHostname',
|
||||
},
|
||||
{
|
||||
name: 'program title retains its document context',
|
||||
session: { hostLabel: 'Editor server', promptHostname: 'web01', dynamicTitle: 'vim README.md' },
|
||||
expectedField: 'dynamicTitle',
|
||||
},
|
||||
] as const;
|
||||
|
||||
for (const { name, session, expectedField } of reviewedAllTitleCases) {
|
||||
test(`all title policy review: ${name}`, () => {
|
||||
assert.equal(resolveSessionTabTitle(session, 'all'), session[expectedField]);
|
||||
});
|
||||
}
|
||||
|
||||
test('all title policy compares shell hostnames case-insensitively without rewriting the title', () => {
|
||||
const session = { hostLabel: 'Production', promptHostname: 'web01', dynamicTitle: 'ubuntu@WEB01: ~/app' };
|
||||
assert.equal(resolveSessionTabTitle(session, 'all'), session.dynamicTitle);
|
||||
});
|
||||
|
||||
test('all title policy ignores one FQDN trailing dot only when comparing host identity', () => {
|
||||
for (const session of [
|
||||
{ hostLabel: 'Production', promptHostname: 'WEB01.EXAMPLE.TEST', dynamicTitle: 'ubuntu@web01.example.test.: ~/app' },
|
||||
{ hostLabel: 'Production', promptHostname: 'web01.example.test.', dynamicTitle: 'ubuntu@WEB01.EXAMPLE.TEST: /srv' },
|
||||
]) {
|
||||
assert.equal(resolveSessionTabTitle(session, 'all'), session.dynamicTitle);
|
||||
}
|
||||
});
|
||||
|
||||
test('all title policy equates bracketed IPv6 title hosts with the same literal prompt address', () => {
|
||||
const session = {
|
||||
hostLabel: 'IPv6 production', promptHostname: '2001:DB8::A', dynamicTitle: 'root@[2001:db8::a]: ~/app',
|
||||
};
|
||||
assert.equal(resolveSessionTabTitle(session, 'all'), session.dynamicTitle);
|
||||
});
|
||||
|
||||
test('all title policy rejects a clearly different bracketed IPv6 title host', () => {
|
||||
const session = {
|
||||
hostLabel: 'IPv6 production', promptHostname: '2001:db8::b', dynamicTitle: 'root@[2001:db8::a]: /srv',
|
||||
};
|
||||
assert.equal(resolveSessionTabTitle(session, 'all'), session.promptHostname);
|
||||
});
|
||||
|
||||
test('all title policy does not treat embedded email or URI text as a shell host report', () => {
|
||||
for (const dynamicTitle of [
|
||||
'vim maintainer@old.example.test:notes.txt',
|
||||
'Issue for maintainer@old.example.test',
|
||||
'https://maintainer@old.example.test/docs',
|
||||
'mailto:maintainer@old.example.test',
|
||||
]) {
|
||||
const session = { hostLabel: 'Production', promptHostname: 'web01', dynamicTitle };
|
||||
assert.equal(resolveSessionTabTitle(session, 'all'), session.dynamicTitle);
|
||||
}
|
||||
});
|
||||
|
||||
test('reviewed shell and program titles remain disabled in default off and agent modes', () => {
|
||||
for (const { session } of reviewedAllTitleCases) {
|
||||
for (const mode of [undefined, 'off', 'agent'] as const) {
|
||||
assert.equal(resolveSessionTabTitle(session, mode), session.hostLabel);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('manual names stay authoritative for every reviewed title and mode', () => {
|
||||
for (const example of reviewedAllTitleCases) {
|
||||
const session = { ...example.session, customName: 'Operator production tab' };
|
||||
for (const mode of [undefined, 'off', 'agent', 'all'] as const) {
|
||||
assert.equal(resolveSessionTabTitle(session, mode), session.customName);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('active Agent titles retain priority over reviewed prompt identities only in enabled modes', () => {
|
||||
for (const example of reviewedAllTitleCases) {
|
||||
const session = { ...example.session, codingCliProviderId: 'claude' as const, dynamicTitle: 'claude: deploy' };
|
||||
for (const mode of [undefined, 'agent', 'all'] as const) {
|
||||
assert.equal(resolveSessionTabTitle(session, mode), session.dynamicTitle);
|
||||
}
|
||||
assert.equal(resolveSessionTabTitle(session, 'off'), session.hostLabel);
|
||||
}
|
||||
});
|
||||
|
||||
const reviewedWorkspaceSessions = reviewedAllTitleCases.map(({ session }, index) => ({
|
||||
...session, id: `review-pane-${index}`, hostId: `review-host-${index}`,
|
||||
}));
|
||||
const reviewedWorkspaceLabels = reviewedAllTitleCases.map(({ session, expectedField }) => session[expectedField]);
|
||||
|
||||
test('auto workspace titles apply the reviewed all policy to the focused pane', () => {
|
||||
for (let index = 0; index < reviewedWorkspaceSessions.length; index += 1) {
|
||||
const session = reviewedWorkspaceSessions[index];
|
||||
const workspace = { title: DEFAULT_WORKSPACE_TITLE, autoTitle: true, focusedSessionId: session.id };
|
||||
assert.equal(
|
||||
resolveWorkspaceTabLabel(workspace, reviewedWorkspaceSessions, 'all'),
|
||||
`${reviewedWorkspaceLabels[index]} +${reviewedWorkspaceSessions.length - 1}`,
|
||||
);
|
||||
for (const mode of [undefined, 'off', 'agent'] as const) {
|
||||
assert.equal(
|
||||
resolveWorkspaceTabLabel(workspace, reviewedWorkspaceSessions, mode),
|
||||
`${session.hostLabel} +${reviewedWorkspaceSessions.length - 1}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('generated workspace display titles apply the reviewed policy without changing stored names', () => {
|
||||
const workspace = {
|
||||
title: reviewedWorkspaceSessions.map(session => session.hostLabel).join('/'),
|
||||
autoTitle: false, generatedTitle: true, focusedSessionId: reviewedWorkspaceSessions[0].id,
|
||||
};
|
||||
const storedTitle = workspace.title;
|
||||
assert.equal(
|
||||
resolveWorkspaceTabLabel(workspace, reviewedWorkspaceSessions, 'all'),
|
||||
reviewedWorkspaceLabels.join('/'),
|
||||
);
|
||||
for (const mode of [undefined, 'off', 'agent'] as const) {
|
||||
assert.equal(resolveWorkspaceTabLabel(workspace, reviewedWorkspaceSessions, mode), storedTitle);
|
||||
}
|
||||
assert.equal(workspace.title, storedTitle);
|
||||
});
|
||||
|
||||
test('all title policy preserves bare emails and suffixes without shell or port evidence', () => {
|
||||
for (const dynamicTitle of [
|
||||
'maintainer@old.example.test',
|
||||
'ubuntu@old.example.test: notes.txt',
|
||||
'ubuntu@old.example.test:0',
|
||||
'ubuntu@old.example.test:65536',
|
||||
'ubuntu@old.example.test:999999',
|
||||
'ubuntu@old.example.test:22garbage',
|
||||
]) {
|
||||
const session = { hostLabel: 'Production', promptHostname: 'web01', dynamicTitle };
|
||||
assert.equal(resolveSessionTabTitle(session, 'all'), session.dynamicTitle);
|
||||
}
|
||||
});
|
||||
|
||||
test('all title policy recognizes legal endpoint port boundaries', () => {
|
||||
for (const port of [1, 65_535]) {
|
||||
const session = { hostLabel: 'Jump fleet', promptHostname: 'target', dynamicTitle: `ubuntu@jump:${port}` };
|
||||
assert.equal(resolveSessionTabTitle(session, 'all'), session.promptHostname);
|
||||
}
|
||||
});
|
||||
|
||||
test('all title policy does not infer short names or matching first labels as aliases', () => {
|
||||
for (const reportedHost of ['web', 'web.dev.example']) {
|
||||
const session = {
|
||||
hostLabel: 'Production', promptHostname: 'web.prod.example', dynamicTitle: `root@${reportedHost}: /srv`,
|
||||
};
|
||||
assert.equal(resolveSessionTabTitle(session, 'all'), session.promptHostname);
|
||||
}
|
||||
});
|
||||
|
||||
test('all title policy preserves titles with invalid bracketed host addresses', () => {
|
||||
for (const reportedHost of ['not-ip', '2001:db8:::1']) {
|
||||
const session = { hostLabel: 'Production', promptHostname: 'web01', dynamicTitle: `root@[${reportedHost}]: ~/app` };
|
||||
assert.equal(resolveSessionTabTitle(session, 'all'), session.dynamicTitle);
|
||||
}
|
||||
});
|
||||
|
||||
test('explicit workspace names ignore all reviewed live title shapes', () => {
|
||||
const workspace = { title: 'Operator layout', autoTitle: false, generatedTitle: false };
|
||||
for (const mode of [undefined, 'off', 'agent', 'all'] as const) {
|
||||
assert.equal(resolveWorkspaceTabLabel(workspace, reviewedWorkspaceSessions, mode), workspace.title);
|
||||
}
|
||||
});
|
||||
+74
-50
@@ -3,11 +3,21 @@ import type { CodingCliProviderId } from './codingCliProviders';
|
||||
import { normalizeCodingCliTitle } from './codingCliTitleParse';
|
||||
import type { DynamicTabTitleMode } from './models/terminal';
|
||||
|
||||
/** Connection label: user rename, live prompt host, then configured host label. */
|
||||
/** Configured connection label, independent of live terminal presentation. */
|
||||
export const getSessionConnectionLabel = (
|
||||
session: Pick<TerminalSession, 'customName' | 'hostLabel' | 'promptHostname'>,
|
||||
session: Pick<TerminalSession, 'customName' | 'hostLabel'>,
|
||||
): string => {
|
||||
return session.customName || session.promptHostname || session.hostLabel || '';
|
||||
return session.customName || session.hostLabel || '';
|
||||
};
|
||||
|
||||
type SessionTabLabelSession = Pick<
|
||||
TerminalSession,
|
||||
'customName' | 'hostLabel' | 'promptHostname' | 'dynamicTitle' | 'codingCliProviderId'
|
||||
>;
|
||||
|
||||
const joinWorkspaceLabels = (labels: readonly string[]): string | null => {
|
||||
const uniqueLabels = [...new Set(labels.map((label) => label.trim()).filter(Boolean))];
|
||||
return uniqueLabels.length > 0 ? uniqueLabels.join('/') : null;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -31,18 +41,10 @@ export const buildMergedWorkspaceTitle = (
|
||||
baseLabel: string,
|
||||
joiningLabel: string,
|
||||
): string | null => {
|
||||
const base = baseLabel.trim();
|
||||
const joining = joiningLabel.trim();
|
||||
if (!base && !joining) return null;
|
||||
if (!base) return joining;
|
||||
if (!joining || joining === base) return base;
|
||||
return `${base}/${joining}`;
|
||||
return joinWorkspaceLabels([baseLabel, joiningLabel]);
|
||||
};
|
||||
|
||||
type WorkspaceTabLabelSession = Pick<
|
||||
TerminalSession,
|
||||
'id' | 'customName' | 'hostLabel' | 'hostId' | 'promptHostname'
|
||||
>;
|
||||
type WorkspaceTabLabelSession = Pick<TerminalSession, 'id' | 'hostId'> & SessionTabLabelSession;
|
||||
|
||||
/**
|
||||
* Recompute a merged workspace's composed title from its *current* member
|
||||
@@ -57,14 +59,7 @@ type WorkspaceTabLabelSession = Pick<
|
||||
export const buildMergedWorkspaceTitleFromSessions = (
|
||||
sessions: readonly WorkspaceTabLabelSession[],
|
||||
): string | null => {
|
||||
const labels: string[] = [];
|
||||
for (const session of sessions) {
|
||||
const label = getSessionConnectionLabel(session).trim();
|
||||
if (!label || labels.includes(label)) continue;
|
||||
labels.push(label);
|
||||
}
|
||||
if (labels.length === 0) return null;
|
||||
return labels.join('/');
|
||||
return joinWorkspaceLabels(sessions.map(getSessionConnectionLabel));
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -75,17 +70,26 @@ export const buildMergedWorkspaceTitleFromSessions = (
|
||||
* workspace holds sessions for more than one distinct host, the focused host is
|
||||
* shown with a "+N" suffix for the others.
|
||||
*
|
||||
* Uses the stable connection label (rename / host label) rather than the
|
||||
* dynamic shell/agent title: those live titles are published only to the
|
||||
* session presentation store (not the plain session records passed here), and
|
||||
* they can differ per-pane on a single host — counting them would both go stale
|
||||
* and produce a bogus "+N". The host identity is what this tab is about.
|
||||
* Presented sessions use the same title policy as individual tabs. Generated
|
||||
* merge titles are display-only compositions; their persisted identity is built
|
||||
* separately by buildMergedWorkspaceTitleFromSessions. Host counts always use
|
||||
* hostId, never a dynamic title or per-pane rename.
|
||||
*/
|
||||
export const resolveWorkspaceTabLabel = (
|
||||
workspace: { title?: string; focusedSessionId?: string | null; autoTitle?: boolean },
|
||||
workspace: {
|
||||
title?: string;
|
||||
focusedSessionId?: string | null;
|
||||
autoTitle?: boolean;
|
||||
generatedTitle?: boolean;
|
||||
},
|
||||
sessions: readonly WorkspaceTabLabelSession[],
|
||||
dynamicTabTitleMode: DynamicTabTitleMode = 'agent',
|
||||
): string => {
|
||||
const title = workspace.title?.trim();
|
||||
if (workspace.generatedTitle) {
|
||||
return joinWorkspaceLabels(sessions.map((session) => resolveSessionTabTitle(session, dynamicTabTitleMode)))
|
||||
?? DEFAULT_WORKSPACE_TITLE;
|
||||
}
|
||||
// Derive a host label only for an auto-titled workspace. The `autoTitle` flag
|
||||
// is authoritative when present (so a workspace a user explicitly named
|
||||
// "Workspace" is kept, not overwritten); legacy workspaces without the flag
|
||||
@@ -98,7 +102,7 @@ export const resolveWorkspaceTabLabel = (
|
||||
return title || DEFAULT_WORKSPACE_TITLE;
|
||||
}
|
||||
const focused = sessions.find((s) => s.id === workspace.focusedSessionId) ?? sessions[0];
|
||||
const primary = getSessionConnectionLabel(focused);
|
||||
const primary = resolveSessionTabTitle(focused, dynamicTabTitleMode);
|
||||
// Count distinct HOSTS by hostId, the only stable host identity: a rename
|
||||
// rewrites both customName and hostLabel (useSessionState.submitSessionRename),
|
||||
// so neither is safe to count by — a renamed pane on the same host would add a
|
||||
@@ -130,38 +134,58 @@ export const resolveCodingCliProviderIconUpdate = ({
|
||||
return nextProviderId;
|
||||
};
|
||||
|
||||
const shellTitleHostname = (title: string): string | undefined => {
|
||||
// A title is not a prompt: require an anchored identity plus cwd/port evidence,
|
||||
// so program titles, email addresses, and URIs do not become host reports.
|
||||
const match = /^[a-z0-9_.+-]+@(\[[^\]\s]+\]|[a-z0-9][a-z0-9_.-]*):\s*(.*)$/iu.exec(title);
|
||||
if (!match) return undefined;
|
||||
const [, hostname, suffix] = match;
|
||||
const isPath = /^(?:~(?:\/|$)|\/)/u.test(suffix);
|
||||
const isPort = /^\d{1,5}$/u.test(suffix) && Number(suffix) > 0 && Number(suffix) <= 65_535;
|
||||
if (!isPath && !isPort) return undefined;
|
||||
if (hostname.startsWith('[')) {
|
||||
try {
|
||||
// Validate IPv6 brackets only; do not use URL canonicalization to infer
|
||||
// aliases or compressed/expanded address equivalence.
|
||||
new URL(`http://${hostname}/`);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
return hostname;
|
||||
};
|
||||
|
||||
const titleHostnameKey = (hostname: string): string =>
|
||||
hostname.replace(/^\[(.*)\]$/u, '$1').replace(/\.$/u, '').toLowerCase();
|
||||
|
||||
/**
|
||||
* Resolve the label shown on session tabs and pane headers.
|
||||
* Uses the shell-reported title according to the global dynamic title mode.
|
||||
* Live prompt and Shell titles require all mode; agent mode permits Agent titles only.
|
||||
*/
|
||||
export const resolveSessionTabTitle = (
|
||||
session: Pick<
|
||||
TerminalSession,
|
||||
'customName' | 'hostLabel' | 'promptHostname' | 'dynamicTitle' | 'codingCliProviderId'
|
||||
>,
|
||||
session: SessionTabLabelSession,
|
||||
dynamicTabTitleMode: DynamicTabTitleMode = 'agent',
|
||||
): string => {
|
||||
const connectionLabel = getSessionConnectionLabel(session);
|
||||
if (session.customName) {
|
||||
return session.customName;
|
||||
if (session.customName || dynamicTabTitleMode === 'off') {
|
||||
return connectionLabel;
|
||||
}
|
||||
if (dynamicTabTitleMode !== 'off' && session.codingCliProviderId) {
|
||||
const agentTitle = session.dynamicTitle?.trim();
|
||||
if (agentTitle) return normalizeCodingCliTitle(agentTitle) || agentTitle;
|
||||
|
||||
const rawTitle = session.dynamicTitle?.trim();
|
||||
const dynamicTitle = rawTitle ? normalizeCodingCliTitle(rawTitle) || rawTitle : undefined;
|
||||
if (session.codingCliProviderId && dynamicTitle) {
|
||||
return dynamicTitle;
|
||||
}
|
||||
if (dynamicTabTitleMode !== 'all') {
|
||||
return connectionLabel;
|
||||
}
|
||||
const promptHostname = session.promptHostname?.trim();
|
||||
if (!dynamicTitle) return promptHostname || connectionLabel;
|
||||
if (promptHostname) {
|
||||
return promptHostname;
|
||||
const reportedHost = shellTitleHostname(dynamicTitle);
|
||||
if (reportedHost && titleHostnameKey(reportedHost) !== titleHostnameKey(promptHostname)) {
|
||||
return promptHostname;
|
||||
}
|
||||
}
|
||||
if (dynamicTabTitleMode === 'off') {
|
||||
return connectionLabel;
|
||||
}
|
||||
if (dynamicTabTitleMode === 'agent' && !session.codingCliProviderId) {
|
||||
return connectionLabel;
|
||||
}
|
||||
const dynamicTitle = session.dynamicTitle?.trim();
|
||||
if (!dynamicTitle) {
|
||||
return connectionLabel;
|
||||
}
|
||||
return normalizeCodingCliTitle(dynamicTitle) || dynamicTitle;
|
||||
return dynamicTitle;
|
||||
};
|
||||
@@ -1,6 +1,7 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { describe, it } from 'node:test';
|
||||
import type { Host, ManagedSource, ProxyProfile } from './models';
|
||||
import { applyGroupDefaults, resolveGroupDefaults } from './groupConfig';
|
||||
import { deleteGroup, upsertGroup } from './vaultGroupAgentOps';
|
||||
|
||||
const hosts: Host[] = [
|
||||
@@ -25,6 +26,27 @@ describe('vaultGroupAgentOps', () => {
|
||||
assert.equal(result.config?.username, 'deploy');
|
||||
});
|
||||
|
||||
it('clearing a child group proxy lets the parent group proxy apply, like Group Details', () => {
|
||||
const result = upsertGroup({
|
||||
groups: ['prod', 'prod/web'],
|
||||
configs: [
|
||||
{ path: 'prod', proxyConfig: { type: 'http', host: 'parent-gw.test', port: 3128 } },
|
||||
{ path: 'prod/web', proxyProfileId: 'proxy-1' },
|
||||
],
|
||||
hosts,
|
||||
managedSources: [],
|
||||
}, 'prod/web', '{"proxyProfileId":""}', [], proxyProfiles);
|
||||
assert.equal(result.ok, true);
|
||||
if (!result.ok) return;
|
||||
assert.equal(result.config?.proxyProfileId, undefined);
|
||||
assert.equal(result.config?.proxyConfig, undefined);
|
||||
const proxyOptions = { validProxyProfileIds: new Set(['proxy-1']), globalProxyProfileId: '' };
|
||||
const effective = applyGroupDefaults(
|
||||
hosts[0], resolveGroupDefaults('prod/web', result.state.configs, proxyOptions), proxyOptions,
|
||||
);
|
||||
assert.equal(effective.proxyConfig?.host, 'parent-gw.test');
|
||||
});
|
||||
|
||||
it('rejects missing identities, proxy profiles, and jump hosts', () => {
|
||||
const state = { groups: ['prod'], configs: [], hosts, managedSources: [] };
|
||||
assert.equal(upsertGroup(state, 'prod', '{"identityId":"missing"}', [], proxyProfiles).ok, false);
|
||||
|
||||
@@ -149,7 +149,9 @@ export function patchGroupConfig(
|
||||
if (proxyProfileId && !proxyProfiles.some((profile) => profile.id === proxyProfileId)) {
|
||||
return { ok: false, error: `Proxy profile "${proxyProfileId}" was not found.` };
|
||||
}
|
||||
next.proxyProfileId = proxyProfileId;
|
||||
// Like Group Details: an empty value removes the group proxy so a parent
|
||||
// group proxy (or the global default) applies, instead of blocking it.
|
||||
next.proxyProfileId = proxyProfileId || undefined;
|
||||
next.proxyConfig = undefined;
|
||||
}
|
||||
if (Object.hasOwn(defaults, 'jumpHostIds')) {
|
||||
|
||||
@@ -643,7 +643,7 @@ test('applyVaultHostUpdate applies and clears advanced connection settings', ()
|
||||
assert.equal(cleared.ok, true);
|
||||
if (!cleared.ok) return;
|
||||
assert.deepEqual(cleared.updatedHost.hostChain, { hostIds: [] });
|
||||
assert.equal(cleared.updatedHost.proxyProfileId, '');
|
||||
assert.equal(cleared.updatedHost.proxyProfileId, undefined);
|
||||
assert.equal(cleared.updatedHost.startupCommand, '');
|
||||
assert.equal(cleared.updatedHost.startupCommandRunMode, undefined);
|
||||
assert.deepEqual(cleared.updatedHost.environmentVariables, []);
|
||||
@@ -652,6 +652,49 @@ test('applyVaultHostUpdate applies and clears advanced connection settings', ()
|
||||
assert.equal(cleared.updatedHost.etEnabled, false);
|
||||
});
|
||||
|
||||
const proxyUpdateProfile: ProxyProfile = {
|
||||
id: 'proxy-1', label: 'proxy', config: { type: 'socks5', host: '127.0.0.1', port: 1080 }, createdAt: 1,
|
||||
};
|
||||
const proxyUpdateHost = (overrides: Partial<Host> = {}): Host => ({
|
||||
id: 'host-1', label: 'host', hostname: 'host.example.com', username: 'root', tags: [], os: 'linux',
|
||||
...overrides,
|
||||
});
|
||||
const updateProxy = (host: Host, patch: VaultHostUpdatePatch) => applyVaultHostUpdate(
|
||||
[host], [], host.id, patch, { proxyProfiles: [proxyUpdateProfile] },
|
||||
);
|
||||
const proxyOptions = { validProxyProfileIds: new Set([proxyUpdateProfile.id]), globalProxyProfileId: '' };
|
||||
|
||||
test('applyVaultHostUpdate selecting a proxy profile replaces an explicit direct choice', () => {
|
||||
const result = updateProxy(
|
||||
proxyUpdateHost({ directProxy: true }),
|
||||
{ proxyProfileId: proxyUpdateProfile.id },
|
||||
);
|
||||
assert.equal(result.ok, true);
|
||||
if (!result.ok) return;
|
||||
assert.equal(result.updatedHost.proxyProfileId, proxyUpdateProfile.id);
|
||||
assert.equal(result.updatedHost.directProxy, undefined);
|
||||
assert.equal(result.updatedHost.proxyConfig, undefined);
|
||||
assert.equal(applyGroupDefaults(result.updatedHost, {}, proxyOptions).proxyProfileId, proxyUpdateProfile.id);
|
||||
});
|
||||
|
||||
test('applyVaultHostUpdate clearing the proxy removes every host proxy setting so group proxies apply', () => {
|
||||
const groupProxyConfig = { type: 'http' as const, host: 'group-proxy.example.com', port: 3128 };
|
||||
for (const current of [
|
||||
proxyUpdateHost({ proxyProfileId: proxyUpdateProfile.id }),
|
||||
proxyUpdateHost({ proxyConfig: { type: 'http', host: 'host-proxy.example.com', port: 8080 } }),
|
||||
proxyUpdateHost({ directProxy: true }),
|
||||
]) {
|
||||
const result = updateProxy(current, { proxyProfileId: '' });
|
||||
assert.equal(result.ok, true, JSON.stringify(current));
|
||||
if (!result.ok) continue;
|
||||
assert.equal(result.updatedHost.proxyProfileId, undefined);
|
||||
assert.equal(result.updatedHost.proxyConfig, undefined);
|
||||
assert.equal(result.updatedHost.directProxy, undefined);
|
||||
const effective = applyGroupDefaults(result.updatedHost, { proxyConfig: groupProxyConfig }, proxyOptions);
|
||||
assert.deepEqual(effective.proxyConfig, groupProxyConfig);
|
||||
}
|
||||
});
|
||||
|
||||
test('applyVaultHostUpdate rejects malformed advanced connection settings', () => {
|
||||
const host: Host = {
|
||||
id: 'host-1', label: 'host', hostname: 'host.example.com', username: 'root', tags: [], os: 'linux',
|
||||
|
||||
@@ -514,8 +514,12 @@ export function applyVaultHostUpdate(
|
||||
if (nextProxyProfileId && !options.proxyProfiles?.some((profile) => profile.id === nextProxyProfileId)) {
|
||||
return { ok: false, error: `Proxy profile "${nextProxyProfileId}" was not found.` };
|
||||
}
|
||||
updated.proxyProfileId = nextProxyProfileId;
|
||||
// Mirror the Host Details proxy panel: a selected profile replaces any
|
||||
// one-off proxy and the explicit direct choice; an empty value removes
|
||||
// every host proxy setting so the group and global default apply again.
|
||||
updated.proxyProfileId = nextProxyProfileId || undefined;
|
||||
updated.proxyConfig = undefined;
|
||||
updated.directProxy = undefined;
|
||||
}
|
||||
if (startupCommand.provided) {
|
||||
if (typeof startupCommand.value !== 'string') return { ok: false, error: 'startupCommand must be a string.' };
|
||||
|
||||
@@ -145,7 +145,7 @@ const TOOL_INPUT_FIELDS = Object.freeze({
|
||||
os: { type: "string", optional: true, description: "Operating system override: auto (default), linux, windows, macos, freebsd, or unknown. Use auto to use detected system information; network device mode is separate." },
|
||||
identityId: { type: "string", optional: true, description: "Reusable identity ID from vault_identities_list. Empty string detaches the identity." },
|
||||
jumpHostIds: { type: "string", optional: true, description: "JSON array of vault host IDs in jump order. Empty array clears the chain." },
|
||||
proxyProfileId: { type: "string", optional: true, description: "Reusable proxy ID from vault_proxy_profiles_list. Empty string clears it." },
|
||||
proxyProfileId: { type: "string", optional: true, description: "Reusable proxy ID from vault_proxy_profiles_list. Empty string removes it so the group or global default applies." },
|
||||
startupCommand: { type: "string", optional: true, description: "Command to run after connecting. Empty string clears it." },
|
||||
startupCommandRunMode: { type: "string", optional: true, description: "paste or lineDelay." },
|
||||
environmentVariables: { type: "string", optional: true, description: "JSON object or array of {name,value} entries. Empty object clears them." },
|
||||
|
||||
@@ -759,7 +759,7 @@
|
||||
"proxyProfileId": {
|
||||
"type": "string",
|
||||
"optional": true,
|
||||
"description": "Reusable proxy ID from vault_proxy_profiles_list. Empty string clears it."
|
||||
"description": "Reusable proxy ID from vault_proxy_profiles_list. Empty string removes it so the group or global default applies."
|
||||
},
|
||||
"startupCommand": {
|
||||
"type": "string",
|
||||
|
||||
@@ -817,7 +817,7 @@
|
||||
"proxyProfileId": {
|
||||
"type": "string",
|
||||
"optional": true,
|
||||
"description": "Reusable proxy ID from vault_proxy_profiles_list. Empty string clears it."
|
||||
"description": "Reusable proxy ID from vault_proxy_profiles_list. Empty string removes it so the group or global default applies."
|
||||
},
|
||||
"startupCommand": {
|
||||
"type": "string",
|
||||
|
||||
@@ -107,6 +107,24 @@ function subscribeControlPropertyMutations(container: HTMLElement, onMutation: (
|
||||
const MAX_PLUGIN_CSS_LENGTH = 131072;
|
||||
const MAX_PLUGIN_EVENT_VALUE_LENGTH = 131072;
|
||||
|
||||
function matchShortcutFromKeyEvent(event: HostDrawnViewEvent, isTextControl: boolean): string | null {
|
||||
const key = event.key ?? '';
|
||||
if (key === 'Escape' && !event.metaKey && !event.ctrlKey && !event.altKey) return 'escape';
|
||||
const mod = Boolean(event.metaKey || event.ctrlKey);
|
||||
if (!mod || event.altKey) return null;
|
||||
const lower = key.toLowerCase();
|
||||
if (lower === 'k' && !event.shiftKey) return 'mod+k';
|
||||
if (lower === 's' && !event.shiftKey) return 'mod+s';
|
||||
if (lower === 't' && !event.shiftKey) return 'mod+t';
|
||||
if (lower === 'w' && !event.shiftKey) return 'mod+w';
|
||||
if (!isTextControl) {
|
||||
if (lower === 'z' && event.shiftKey) return 'mod+shift+z';
|
||||
if (lower === 'z' && !event.shiftKey) return 'mod+z';
|
||||
if (lower === 'y' && event.ctrlKey && !event.metaKey && !event.shiftKey) return 'mod+shift+z';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Build ordinary DOM in the isolated runtime; only validated data reaches the visible host. */
|
||||
export function registerHostDomView(views: PluginViews, viewId: string, mount: (container: HTMLElement, stateScope: string) => (() => void) | void, css = ''): Disposable {
|
||||
if (css.length > MAX_PLUGIN_CSS_LENGTH) throw new TypeError('Plugin CSS exceeds the view limit');
|
||||
@@ -148,10 +166,18 @@ export function registerHostDomView(views: PluginViews, viewId: string, mount: (
|
||||
const eventType = event.type;
|
||||
if (eventType === 'dismiss') { element.dispatchEvent(new Event('netcatty-dismiss')); return; }
|
||||
if (eventType === 'widget') {
|
||||
element.dispatchEvent(new CustomEvent('netcatty-widget-event', {
|
||||
const widgetEvent = new CustomEvent('netcatty-widget-event', {
|
||||
bubbles: false,
|
||||
cancelable: true,
|
||||
detail: { widgetEvent: event.widgetEvent, detail: event.detail },
|
||||
}));
|
||||
});
|
||||
element.dispatchEvent(widgetEvent);
|
||||
if (!widgetEvent.defaultPrevented && event.widgetEvent === 'shortcut' && event.detail && typeof event.detail === 'object' && !Array.isArray(event.detail)) {
|
||||
const shortcut = (event.detail as Record<string, unknown>).shortcut;
|
||||
if (typeof shortcut === 'string') {
|
||||
element.dispatchEvent(new CustomEvent('netcatty-shortcut', { bubbles: true, detail: { shortcut } }));
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (eventType === 'dblclick') {
|
||||
@@ -209,11 +235,18 @@ export function registerHostDomView(views: PluginViews, viewId: string, mount: (
|
||||
if (eventType === 'reset' && element instanceof HTMLFormElement) { element.reset(); return; }
|
||||
if (eventType === 'submit') { const action = new Event(eventType, { bubbles: true, cancelable: true }); action.preventDefault(); element.dispatchEvent(action); return; }
|
||||
if (eventType === 'keydown' || eventType === 'keyup') {
|
||||
if ((element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement)
|
||||
&& typeof event.selectionStart === 'number' && typeof event.selectionEnd === 'number') {
|
||||
const isTextControl = element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement;
|
||||
if (isTextControl && typeof event.selectionStart === 'number' && typeof event.selectionEnd === 'number') {
|
||||
try { element.setSelectionRange(event.selectionStart, event.selectionEnd); } catch {}
|
||||
}
|
||||
element.dispatchEvent(new KeyboardEvent(eventType, { key: event.key ?? '', ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey, bubbles: true, cancelable: true })); return;
|
||||
element.dispatchEvent(new KeyboardEvent(eventType, { key: event.key ?? '', ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey, bubbles: true, cancelable: true }));
|
||||
if (eventType === 'keydown') {
|
||||
const shortcut = matchShortcutFromKeyEvent(event, isTextControl);
|
||||
if (shortcut) {
|
||||
element.dispatchEvent(new CustomEvent('netcatty-shortcut', { bubbles: true, detail: { shortcut } }));
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (eventType.startsWith('composition')) { element.dispatchEvent(new CompositionEvent(eventType, { data: event.data ?? '', bubbles: true })); return; }
|
||||
if (eventType === 'focusin' || eventType === 'focusout') { element.dispatchEvent(new FocusEvent(eventType, { bubbles: true })); return; }
|
||||
|
||||
@@ -426,7 +426,7 @@ test('hostDom syncs valueAsNumber, valueAsDate, stepUp, stepDown, and setRangeTe
|
||||
test('hostReact widgets and extended surface events round-trip cleanly through hostDom', async () => {
|
||||
const dom = new JSDOM('<!doctype html><body></body>', { 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', 'CustomEvent', 'MouseEvent']) {
|
||||
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'HTMLInputElement', 'HTMLTextAreaElement', 'HTMLSelectElement', 'HTMLOptionElement', 'HTMLFormElement', 'Node', 'MutationObserver', 'Event', 'CustomEvent', 'MouseEvent', 'KeyboardEvent']) {
|
||||
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] });
|
||||
}
|
||||
@@ -436,6 +436,7 @@ test('hostReact widgets and extended surface events round-trip cleanly through h
|
||||
const { remoteId } = await import('@remote-dom/core/elements');
|
||||
const {
|
||||
registerHostReactView,
|
||||
usePluginShortcuts,
|
||||
PluginPopover,
|
||||
PluginCodeEditor,
|
||||
PluginDataGrid,
|
||||
@@ -453,7 +454,9 @@ test('hostReact widgets and extended surface events round-trip cleanly through h
|
||||
};
|
||||
|
||||
const received: Record<string, unknown> = {};
|
||||
const globalShortcuts: string[] = [];
|
||||
function IdeView() {
|
||||
usePluginShortcuts((sc) => { globalShortcuts.push(sc); });
|
||||
return (
|
||||
<div data-plugin-chrome="full-bleed">
|
||||
<button
|
||||
@@ -467,18 +470,24 @@ test('hostReact widgets and extended surface events round-trip cleanly through h
|
||||
<span>Action</span>
|
||||
</PluginPopover>
|
||||
<PluginSplitPane direction="horizontal" initialSize={260} onResizeEnd={(d) => { received.resizeEnd = d; }}>
|
||||
<PluginCodeEditor value="SELECT 1;" language="sql" onExecute={(d) => { received.execute = d; }} />
|
||||
<PluginCodeEditor value="SELECT 1;" language="sql" onExecute={(d) => { received.execute = d; }} onShortcut={(d) => { received.editorShortcut = d; }} />
|
||||
<PluginDataGrid
|
||||
columns={[{ name: 'id', primaryKey: true }]}
|
||||
columns={[{ name: 'id', primaryKey: true, foreignKey: { table: 'users', column: 'id' } }]}
|
||||
hiddenColumns={[]}
|
||||
rows={[{ id: 1 }]}
|
||||
editable
|
||||
onCellEdit={(d) => { received.cellEdit = d; }}
|
||||
onFkJump={(d) => { received.fkJump = d; }}
|
||||
onCellCopy={(d) => { received.cellCopy = d; }}
|
||||
onCellDoubleClick={(d) => { received.cellDoubleClick = d; }}
|
||||
/>
|
||||
</PluginSplitPane>
|
||||
<PluginErCanvas
|
||||
tables={[{ name: 'users', columns: [{ name: 'id', type: 'int', isPk: true }] }]}
|
||||
relations={[]}
|
||||
onTableClick={(d) => { received.tableClick = d; }}
|
||||
onTableDoubleClick={(d) => { received.tableDoubleClick = d; }}
|
||||
onExportSvg={(d) => { received.exportSvg = d; }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
@@ -506,18 +515,35 @@ test('hostReact widgets and extended surface events round-trip cleanly through h
|
||||
await act(async () => {
|
||||
receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'dblclick', nodeId: remoteId(btn), x: 12, y: 34 } });
|
||||
receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'contextmenu', nodeId: remoteId(btn), x: 56, y: 78 } });
|
||||
receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'keydown', nodeId: remoteId(btn), key: 'k', metaKey: true } });
|
||||
receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(editorEl), widgetEvent: 'execute', detail: { value: 'SELECT 1;', selectedText: '', currentStatement: 'SELECT 1' } } });
|
||||
receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(editorEl), widgetEvent: 'shortcut', detail: { shortcut: 'mod+s' } } });
|
||||
receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(gridEl), widgetEvent: 'shortcut', detail: { shortcut: 'mod+z' } } });
|
||||
receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(gridEl), widgetEvent: 'cellEdit', detail: { rowIndex: 0, colName: 'id', value: '2', isNull: false } } });
|
||||
receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(gridEl), widgetEvent: 'fkJump', detail: { rowIndex: 0, colName: 'id', value: 1, targetTable: 'users', targetColumn: 'id' } } });
|
||||
receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(gridEl), widgetEvent: 'cellCopy', detail: { text: '1', rowIndex: 0, colName: 'id', rowIndices: [0] } } });
|
||||
receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(gridEl), widgetEvent: 'cellDoubleClick', detail: { rowIndex: 0, colName: 'id', value: 1 } } });
|
||||
receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(splitEl), widgetEvent: 'resizeEnd', detail: { size: 320, collapsed: false } } });
|
||||
receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(erEl), widgetEvent: 'tableClick', detail: { table: 'users' } } });
|
||||
receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(erEl), widgetEvent: 'tableDoubleClick', detail: { table: 'users' } } });
|
||||
receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(erEl), widgetEvent: 'exportSvg', detail: { svg: '<svg/>' } } });
|
||||
});
|
||||
|
||||
assert.deepEqual(received.dblclick, { x: 12, y: 34 });
|
||||
assert.deepEqual(received.contextmenu, { x: 56, y: 78 });
|
||||
assert.deepEqual(received.execute, { value: 'SELECT 1;', selectedText: '', currentStatement: 'SELECT 1' });
|
||||
assert.deepEqual(received.editorShortcut, { shortcut: 'mod+s' });
|
||||
// editorEl consumed mod+s via onShortcut (must NOT double-fire usePluginShortcuts);
|
||||
// btn (Shadow DOM) and gridEl (no onShortcut) bubble to usePluginShortcuts once each.
|
||||
assert.deepEqual(globalShortcuts, ['mod+k', 'mod+z']);
|
||||
assert.deepEqual(received.cellEdit, { rowIndex: 0, colName: 'id', value: '2', isNull: false });
|
||||
assert.deepEqual(received.fkJump, { rowIndex: 0, colName: 'id', value: 1, targetTable: 'users', targetColumn: 'id' });
|
||||
assert.deepEqual(received.cellCopy, { text: '1', rowIndex: 0, colName: 'id', rowIndices: [0] });
|
||||
assert.deepEqual(received.cellDoubleClick, { rowIndex: 0, colName: 'id', value: 1 });
|
||||
assert.deepEqual(received.resizeEnd, { size: 320, collapsed: false });
|
||||
assert.deepEqual(received.tableClick, { table: 'users' });
|
||||
assert.deepEqual(received.tableDoubleClick, { table: 'users' });
|
||||
assert.deepEqual(received.exportSvg, { svg: '<svg/>' });
|
||||
await act(async () => { receive({ kind: 'host-ui.close', instanceId: 'ide-1' }); });
|
||||
} finally {
|
||||
await act(async () => { registration.dispose(); });
|
||||
|
||||
@@ -10,6 +10,34 @@ export function registerHostReactView(views: PluginViews, viewId: string, render
|
||||
}, css);
|
||||
}
|
||||
|
||||
export type PluginWorkbenchShortcut =
|
||||
| 'mod+k'
|
||||
| 'mod+s'
|
||||
| 'mod+t'
|
||||
| 'mod+w'
|
||||
| 'mod+z'
|
||||
| 'mod+shift+z'
|
||||
| 'escape';
|
||||
|
||||
/**
|
||||
* Subscribe to normalized global workbench shortcuts forwarded from both the
|
||||
* Shadow DOM surface and slotted host-rendered widgets (CodeEditor, DataGrid, ErCanvas).
|
||||
*/
|
||||
export function usePluginShortcuts(handler: (shortcut: PluginWorkbenchShortcut) => void): void {
|
||||
const handlerRef = useRef(handler);
|
||||
handlerRef.current = handler;
|
||||
useEffect(() => {
|
||||
const listener = (event: Event) => {
|
||||
const shortcut = (event as CustomEvent<{ shortcut?: PluginWorkbenchShortcut }>).detail?.shortcut;
|
||||
if (typeof shortcut === 'string') {
|
||||
handlerRef.current(shortcut);
|
||||
}
|
||||
};
|
||||
document.addEventListener('netcatty-shortcut', listener);
|
||||
return () => document.removeEventListener('netcatty-shortcut', listener);
|
||||
}, []);
|
||||
}
|
||||
|
||||
export interface PluginPopoverProps {
|
||||
anchor?: string;
|
||||
anchorX?: number;
|
||||
@@ -58,7 +86,7 @@ type WidgetEventDetail = { widgetEvent?: string; detail?: Record<string, unknown
|
||||
|
||||
function useWidgetEventBridge(
|
||||
ref: React.RefObject<HTMLElement | null>,
|
||||
handler: (widgetEvent: string, detail: Record<string, unknown>) => void,
|
||||
handler: (widgetEvent: string, detail: Record<string, unknown>) => boolean | void,
|
||||
) {
|
||||
const handlerRef = useRef(handler);
|
||||
handlerRef.current = handler;
|
||||
@@ -68,7 +96,9 @@ function useWidgetEventBridge(
|
||||
const listener = (event: Event) => {
|
||||
const payload = (event as CustomEvent<WidgetEventDetail>).detail;
|
||||
if (!payload || typeof payload.widgetEvent !== 'string') return;
|
||||
handlerRef.current(payload.widgetEvent, payload.detail ?? {});
|
||||
if (handlerRef.current(payload.widgetEvent, payload.detail ?? {}) === true) {
|
||||
event.preventDefault();
|
||||
}
|
||||
};
|
||||
node.addEventListener('netcatty-widget-event', listener);
|
||||
return () => node.removeEventListener('netcatty-widget-event', listener);
|
||||
@@ -124,6 +154,7 @@ export interface PluginCodeEditorProps {
|
||||
onSelection?: (detail: { selectionStart: number; selectionEnd: number; selectedText: string }) => void;
|
||||
onExecute?: (detail: { value: string; selectedText: string; currentStatement: string }) => void;
|
||||
onFormat?: (detail: { value: string }) => void;
|
||||
onShortcut?: (detail: { shortcut: PluginWorkbenchShortcut }) => void;
|
||||
}
|
||||
|
||||
/** Host-rendered Monaco code editor with local zero-IPC schema completion. */
|
||||
@@ -144,6 +175,7 @@ export function PluginCodeEditor({
|
||||
onSelection,
|
||||
onExecute,
|
||||
onFormat,
|
||||
onShortcut,
|
||||
}: PluginCodeEditorProps) {
|
||||
const ref = useRef<HTMLElement>(null);
|
||||
useWidgetEventBridge(ref, (eventName, detail) => {
|
||||
@@ -151,6 +183,7 @@ export function PluginCodeEditor({
|
||||
else if (eventName === 'selection') onSelection?.(detail as { selectionStart: number; selectionEnd: number; selectedText: string });
|
||||
else if (eventName === 'execute') onExecute?.(detail as { value: string; selectedText: string; currentStatement: string });
|
||||
else if (eventName === 'format') onFormat?.(detail as { value: string });
|
||||
else if (eventName === 'shortcut' && onShortcut) { onShortcut(detail as { shortcut: PluginWorkbenchShortcut }); return true; }
|
||||
});
|
||||
const serialized = useMemo(
|
||||
() => JSON.stringify({
|
||||
@@ -176,6 +209,12 @@ export function PluginCodeEditor({
|
||||
});
|
||||
}
|
||||
|
||||
export interface PluginDataGridForeignKey {
|
||||
table: string;
|
||||
column: string;
|
||||
schema?: string;
|
||||
}
|
||||
|
||||
export interface PluginDataGridColumn {
|
||||
name: string;
|
||||
type?: string;
|
||||
@@ -183,6 +222,7 @@ export interface PluginDataGridColumn {
|
||||
nullable?: boolean;
|
||||
width?: number;
|
||||
sortable?: boolean;
|
||||
foreignKey?: PluginDataGridForeignKey;
|
||||
}
|
||||
|
||||
export interface PluginDataGridSort {
|
||||
@@ -195,6 +235,7 @@ export type PluginDataGridRow = Record<string, unknown> | unknown[];
|
||||
export interface PluginDataGridProps {
|
||||
columns: PluginDataGridColumn[];
|
||||
rows: PluginDataGridRow[];
|
||||
hiddenColumns?: string[];
|
||||
rowKeyField?: string;
|
||||
dirtyCells?: Record<string, unknown>;
|
||||
deletedRowIndices?: number[];
|
||||
@@ -207,16 +248,21 @@ export interface PluginDataGridProps {
|
||||
className?: string;
|
||||
style?: CSSProperties;
|
||||
onCellSelect?: (detail: { rowIndex: number; colName: string; value: unknown }) => void;
|
||||
onCellDoubleClick?: (detail: { rowIndex: number; colName: string; value: unknown }) => void;
|
||||
onCellEdit?: (detail: { rowIndex: number; colName: string; value: unknown; isNull: boolean }) => void;
|
||||
onCellContextMenu?: (detail: { rowIndex: number; colName: string; x: number; y: number }) => void;
|
||||
onCellCopy?: (detail: { text: string; rowIndex: number | null; colName: string | null; rowIndices: number[] }) => void;
|
||||
onFkJump?: (detail: { rowIndex: number; colName: string; value: unknown; targetTable: string; targetColumn: string; targetSchema?: string }) => void;
|
||||
onSortChange?: (detail: { column: string; direction: 'asc' | 'desc' }) => void;
|
||||
onRowSelect?: (detail: { selectedRowIndices: number[] }) => void;
|
||||
onShortcut?: (detail: { shortcut: PluginWorkbenchShortcut }) => void;
|
||||
}
|
||||
|
||||
/** Host-rendered virtualized editable data grid powered by @tanstack/react-virtual. */
|
||||
export function PluginDataGrid({
|
||||
columns,
|
||||
rows,
|
||||
hiddenColumns,
|
||||
rowKeyField,
|
||||
dirtyCells,
|
||||
deletedRowIndices,
|
||||
@@ -229,23 +275,32 @@ export function PluginDataGrid({
|
||||
className,
|
||||
style,
|
||||
onCellSelect,
|
||||
onCellDoubleClick,
|
||||
onCellEdit,
|
||||
onCellContextMenu,
|
||||
onCellCopy,
|
||||
onFkJump,
|
||||
onSortChange,
|
||||
onRowSelect,
|
||||
onShortcut,
|
||||
}: PluginDataGridProps) {
|
||||
const ref = useRef<HTMLElement>(null);
|
||||
useWidgetEventBridge(ref, (eventName, detail) => {
|
||||
if (eventName === 'cellSelect') onCellSelect?.(detail as { rowIndex: number; colName: string; value: unknown });
|
||||
else if (eventName === 'cellDoubleClick') onCellDoubleClick?.(detail as { rowIndex: number; colName: string; value: unknown });
|
||||
else if (eventName === 'cellEdit') onCellEdit?.(detail as { rowIndex: number; colName: string; value: unknown; isNull: boolean });
|
||||
else if (eventName === 'cellContextMenu') onCellContextMenu?.(detail as { rowIndex: number; colName: string; x: number; y: number });
|
||||
else if (eventName === 'cellCopy') onCellCopy?.(detail as { text: string; rowIndex: number | null; colName: string | null; rowIndices: number[] });
|
||||
else if (eventName === 'fkJump') onFkJump?.(detail as { rowIndex: number; colName: string; value: unknown; targetTable: string; targetColumn: string; targetSchema?: string });
|
||||
else if (eventName === 'sortChange') onSortChange?.(detail as { column: string; direction: 'asc' | 'desc' });
|
||||
else if (eventName === 'rowSelect') onRowSelect?.(detail as { selectedRowIndices: number[] });
|
||||
else if (eventName === 'shortcut' && onShortcut) { onShortcut(detail as { shortcut: PluginWorkbenchShortcut }); return true; }
|
||||
});
|
||||
const serialized = useMemo(
|
||||
() => JSON.stringify({
|
||||
columns,
|
||||
rows,
|
||||
...(hiddenColumns !== undefined ? { hiddenColumns } : {}),
|
||||
...(rowKeyField !== undefined ? { rowKeyField } : {}),
|
||||
...(dirtyCells !== undefined ? { dirtyCells } : {}),
|
||||
...(deletedRowIndices !== undefined ? { deletedRowIndices } : {}),
|
||||
@@ -256,7 +311,7 @@ export function PluginDataGrid({
|
||||
...(loading !== undefined ? { loading } : {}),
|
||||
...(emptyMessage !== undefined ? { emptyMessage } : {}),
|
||||
}),
|
||||
[columns, rows, rowKeyField, dirtyCells, deletedRowIndices, insertedRows, selectedRowIndices, sort, editable, loading, emptyMessage],
|
||||
[columns, rows, hiddenColumns, rowKeyField, dirtyCells, deletedRowIndices, insertedRows, selectedRowIndices, sort, editable, loading, emptyMessage],
|
||||
);
|
||||
return createElement('div', {
|
||||
ref,
|
||||
@@ -343,6 +398,8 @@ export interface PluginErRelation {
|
||||
toTable: string;
|
||||
toColumn: string;
|
||||
name?: string;
|
||||
onDelete?: string;
|
||||
onUpdate?: string;
|
||||
}
|
||||
|
||||
export interface PluginErCanvasProps {
|
||||
@@ -351,6 +408,9 @@ export interface PluginErCanvasProps {
|
||||
className?: string;
|
||||
style?: CSSProperties;
|
||||
onTableClick?: (detail: { table: string; schema?: string }) => void;
|
||||
onTableDoubleClick?: (detail: { table: string; schema?: string }) => void;
|
||||
onExportSvg?: (detail: { svg: string }) => void;
|
||||
onShortcut?: (detail: { shortcut: PluginWorkbenchShortcut }) => void;
|
||||
}
|
||||
|
||||
/** Host-rendered interactive pan/zoom SVG ER diagram canvas. */
|
||||
@@ -360,10 +420,16 @@ export function PluginErCanvas({
|
||||
className,
|
||||
style,
|
||||
onTableClick,
|
||||
onTableDoubleClick,
|
||||
onExportSvg,
|
||||
onShortcut,
|
||||
}: PluginErCanvasProps) {
|
||||
const ref = useRef<HTMLElement>(null);
|
||||
useWidgetEventBridge(ref, (eventName, detail) => {
|
||||
if (eventName === 'tableClick') onTableClick?.(detail as { table: string; schema?: string });
|
||||
else if (eventName === 'tableDoubleClick') onTableDoubleClick?.(detail as { table: string; schema?: string });
|
||||
else if (eventName === 'exportSvg') onExportSvg?.(detail as { svg: string });
|
||||
else if (eventName === 'shortcut' && onShortcut) { onShortcut(detail as { shortcut: PluginWorkbenchShortcut }); return true; }
|
||||
});
|
||||
const serialized = useMemo(
|
||||
() => JSON.stringify({ tables, relations }),
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
import React, { useState } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { flushSync } from "react-dom";
|
||||
import { useSessionState } from "../../application/state/useSessionState";
|
||||
import { createPromptHostnameSessionSignalController } from "../../application/state/promptHostnameSessionSignalController";
|
||||
import { sessionPresentationStore } from "../../application/state/sessionPresentationStore";
|
||||
import { extractTerminalPromptHostname } from "../../domain/terminalPromptSecurity";
|
||||
import type { DynamicTabTitleMode, Host, TerminalSession, Workspace } from "../../domain/models";
|
||||
import { SessionTopTab, WorkspaceTopTab } from "../../components/top-tabs/TopTabItems";
|
||||
import { TooltipProvider } from "../../components/ui/tooltip";
|
||||
|
||||
const hosts: Host[] = [
|
||||
{ id: "production", label: "\u751f\u4ea7", hostname: "203.0.113.10", username: "fixture", port: 22, protocol: "ssh", os: "linux", tags: [] },
|
||||
{ id: "database", label: "Database", hostname: "198.51.100.20", username: "fixture", port: 22, protocol: "ssh", os: "linux", tags: [] },
|
||||
{ id: "jump", label: "Jump fleet", hostname: "jump.example.test", username: "fixture", port: 22, protocol: "ssh", os: "linux", tags: [] },
|
||||
];
|
||||
const noop = () => {};
|
||||
type SessionState = ReturnType<typeof useSessionState>;
|
||||
let state: SessionState;
|
||||
let setMode: React.Dispatch<React.SetStateAction<DynamicTabTitleMode | undefined>>;
|
||||
let setRevision: React.Dispatch<React.SetStateAction<number>>;
|
||||
let revision = 0;
|
||||
let fixtureRenderCount = 0;
|
||||
|
||||
function workspace(id: string, sessions: TerminalSession[], title: string, autoTitle: boolean, generatedTitle = false): Workspace {
|
||||
return {
|
||||
id, title, autoTitle, generatedTitle, focusedSessionId: sessions[0].id,
|
||||
root: { id: `${id}-root`, type: "split", direction: "vertical", children: sessions.map(session => ({ id: `${id}-${session.id}`, type: "pane", sessionId: session.id })) },
|
||||
};
|
||||
}
|
||||
|
||||
function Fixture() {
|
||||
fixtureRenderCount += 1;
|
||||
state = useSessionState({ persistSessionRestore: false });
|
||||
const [mode, updateMode] = useState<DynamicTabTitleMode>();
|
||||
const [commit, updateRevision] = useState(0);
|
||||
setMode = updateMode;
|
||||
setRevision = updateRevision;
|
||||
const members = state.sessions.slice(0, 2);
|
||||
const shared = {
|
||||
isBeingDragged: false, isDraggingForReorder: false, shiftStyle: {},
|
||||
showDropIndicatorBefore: false, showDropIndicatorAfter: false,
|
||||
onTabDragStart: noop, onTabDragEnd: noop, onTabDragOver: noop, onTabDragLeave: noop, onTabDrop: noop,
|
||||
tabDoubleClickBehavior: "disabled" as const, dynamicTabTitleMode: mode,
|
||||
renderBulkCloseItems: () => null, t: (key: string) => key,
|
||||
};
|
||||
const workspaces = members.length === 2 ? [
|
||||
workspace("auto", members, "Workspace", true),
|
||||
workspace("generated", members, members.map(session => session.hostLabel).join("/"), false, true),
|
||||
workspace("explicit", members, "My Cluster", false),
|
||||
] : [];
|
||||
return <TooltipProvider>
|
||||
<main data-fixture-commit={commit}>
|
||||
<h1>Production SSH tab title policy</h1>
|
||||
<section aria-label="Session tabs" style={{ display: "flex", gap: 8 }}>
|
||||
{state.sessions.map(session => <SessionTopTab key={session.id} {...shared}
|
||||
session={session} host={hosts.find(host => host.id === session.hostId)}
|
||||
onCloseSession={noop} onRenameSession={state.startSessionRename}
|
||||
onCopySession={noop} onCopySessionToNewWindow={noop} />)}
|
||||
</section>
|
||||
<section aria-label="Workspace tabs" style={{ display: "flex", gap: 8, marginTop: 16 }}>
|
||||
{workspaces.map(item => <WorkspaceTopTab key={item.id} {...shared}
|
||||
workspace={item} workspaceSessions={members} workspaceSessionIds={members.map(session => session.id)}
|
||||
paneCount={members.length} isHostDropTarget={false}
|
||||
onRenameWorkspace={noop} onCopyWorkspace={noop} onCloseWorkspace={noop} />)}
|
||||
</section>
|
||||
</main>
|
||||
</TooltipProvider>;
|
||||
}
|
||||
|
||||
function waitForCommit(expected: number): Promise<void> {
|
||||
const ready = () => document.querySelector(`[data-fixture-commit="${expected}"]`) !== null;
|
||||
if (ready()) return Promise.resolve();
|
||||
return new Promise((resolve, reject) => {
|
||||
const observer = new MutationObserver(() => {
|
||||
if (!ready()) return;
|
||||
observer.disconnect();
|
||||
clearTimeout(timeout);
|
||||
resolve();
|
||||
});
|
||||
const timeout = setTimeout(() => {
|
||||
observer.disconnect();
|
||||
reject(new Error(`React commit ${expected} was not observed within 60 seconds`));
|
||||
}, 60_000);
|
||||
observer.observe(document.body, { attributes: true, childList: true, subtree: true });
|
||||
});
|
||||
}
|
||||
|
||||
async function change(action: () => void): Promise<void> {
|
||||
revision += 1;
|
||||
flushSync(() => { action(); setRevision(revision); });
|
||||
await waitForCommit(revision);
|
||||
}
|
||||
|
||||
export type TitleMeasurement = { scenario: string; tabId: string; actual: string; expected: string };
|
||||
|
||||
function titleSpan(tabId: string): Element {
|
||||
const span = document.querySelector(`[data-tab-id="${tabId}"] span.truncate.leading-5`);
|
||||
if (!span) throw new Error(`Missing production title span for ${tabId}`);
|
||||
return span;
|
||||
}
|
||||
|
||||
function title(tabId: string): string {
|
||||
return titleSpan(tabId).textContent ?? "";
|
||||
}
|
||||
|
||||
function waitForTitleMutation(tabId: string, action: () => void): Promise<void> {
|
||||
const span = titleSpan(tabId);
|
||||
const before = span.textContent;
|
||||
return new Promise((resolve, reject) => {
|
||||
const observer = new MutationObserver(() => {
|
||||
if (span.textContent === before) return;
|
||||
observer.disconnect();
|
||||
clearTimeout(timeout);
|
||||
resolve();
|
||||
});
|
||||
const timeout = setTimeout(() => {
|
||||
observer.disconnect();
|
||||
reject(new Error(`Production title ${tabId} did not mutate after a store-only update within 60 seconds`));
|
||||
}, 60_000);
|
||||
observer.observe(span, { characterData: true, childList: true, subtree: true });
|
||||
try { action(); } catch (error) {
|
||||
observer.disconnect();
|
||||
clearTimeout(timeout);
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function promptHost(prompt: string): string {
|
||||
const hostname = extractTerminalPromptHostname(prompt);
|
||||
if (!hostname) throw new Error(`Fixture prompt was not parsed: ${JSON.stringify(prompt)}`);
|
||||
return hostname;
|
||||
}
|
||||
|
||||
export async function runSshTabTitlePolicy(): Promise<{ rows: TitleMeasurement[]; promptOnlyParentRenders: number }> {
|
||||
const node = document.getElementById("root");
|
||||
if (!node) throw new Error("Missing fixture root");
|
||||
const root = createRoot(node);
|
||||
const rows: TitleMeasurement[] = [];
|
||||
const record = (scenario: string, tabId: string, expected: string) => {
|
||||
rows.push({ scenario, tabId, actual: title(tabId), expected });
|
||||
};
|
||||
const controller = createPromptHostnameSessionSignalController({
|
||||
getSession: id => state.sessions.find(session => session.id === id),
|
||||
onChange: (id, hostname) => state.updateSessionPromptHost(id, hostname),
|
||||
});
|
||||
let first = "";
|
||||
let second = "";
|
||||
let jump = "";
|
||||
try {
|
||||
flushSync(() => root.render(<Fixture />));
|
||||
await waitForCommit(0);
|
||||
await change(() => {
|
||||
first = state.connectToHost(hosts[0]);
|
||||
second = state.connectToHost(hosts[1]);
|
||||
});
|
||||
await change(() => {
|
||||
state.updateSessionStatus(first, "connected");
|
||||
state.updateSessionStatus(second, "connected");
|
||||
});
|
||||
record("initial saved host name", first, hosts[0].label);
|
||||
const firstPrompt = "[fixture@VM-0-8-centos ~]# ";
|
||||
const secondPrompt = "[fixture@db-target ~]# ";
|
||||
const firstObserved = promptHost(firstPrompt);
|
||||
const secondObserved = promptHost(secondPrompt);
|
||||
await change(() => {
|
||||
controller.handleTerminalOutput(first, firstPrompt);
|
||||
controller.handleTerminalOutput(second, secondPrompt);
|
||||
});
|
||||
// Do not call the title resolver for expectations: names come from the
|
||||
// saved host entities; dynamic hostnames come from the prompt parser.
|
||||
const recordGroup = (scenario: string, firstName: string, secondName: string) => {
|
||||
record(scenario, first, firstName);
|
||||
record(scenario, second, secondName);
|
||||
record(scenario, "auto", `${firstName} +1`);
|
||||
record(scenario, "generated", `${firstName}/${secondName}`);
|
||||
record(scenario, "explicit", "My Cluster");
|
||||
};
|
||||
for (const mode of [undefined, "off", "agent", "all"] as const) {
|
||||
await change(() => setMode(mode));
|
||||
recordGroup(`ordinary SSH mode=${mode ?? "default"}`,
|
||||
mode === "all" ? firstObserved : hosts[0].label,
|
||||
mode === "all" ? secondObserved : hosts[1].label);
|
||||
}
|
||||
const updatedPrompt = "[fixture@production-next ~]# ";
|
||||
const parentRendersBefore = fixtureRenderCount;
|
||||
// This action deliberately bypasses change(), setRevision and flushSync:
|
||||
// only the production store subscriptions may update these mounted tabs.
|
||||
await waitForTitleMutation(first, () => controller.handleTerminalOutput(first, `\r\n${updatedPrompt}`));
|
||||
const promptOnlyParentRenders = fixtureRenderCount - parentRendersBefore;
|
||||
recordGroup("all-mode prompt-only store subscription", promptHost(updatedPrompt), secondObserved);
|
||||
const agentTitle = "claude: deploy";
|
||||
await change(() => {
|
||||
state.updateSessionCodingCliProvider(first, "claude");
|
||||
state.updateSessionDynamicTitle(first, agentTitle);
|
||||
});
|
||||
for (const mode of ["off", "agent", "all"] as const) {
|
||||
await change(() => setMode(mode));
|
||||
recordGroup(`Agent title mode=${mode}`, mode === "off" ? hosts[0].label : agentTitle,
|
||||
mode === "all" ? secondObserved : hosts[1].label);
|
||||
}
|
||||
const manualName = "Manual production";
|
||||
await change(() => state.submitSessionRename(first, manualName));
|
||||
for (const mode of ["off", "agent", "all"] as const) {
|
||||
await change(() => setMode(mode));
|
||||
const renamed = state.sessions.find(session => session.id === first);
|
||||
if (!renamed?.customName) throw new Error("Production rename hook did not set customName");
|
||||
recordGroup(`manual title mode=${mode}`, renamed.customName,
|
||||
mode === "all" ? secondObserved : hosts[1].label);
|
||||
}
|
||||
await change(() => { jump = state.connectToHost(hosts[2]); setMode("all"); });
|
||||
await change(() => state.updateSessionStatus(jump, "connected"));
|
||||
const targetPrompt = "[fixture@app-target ~]# ";
|
||||
const targetObserved = promptHost(targetPrompt);
|
||||
await change(() => controller.handleTerminalOutput(jump, targetPrompt));
|
||||
record("JumpServer first output is target", jump, targetObserved);
|
||||
for (const mode of ["off", "agent", "all"] as const) {
|
||||
await change(() => setMode(mode));
|
||||
record(`JumpServer direct target mode=${mode}`, jump, mode === "all" ? targetObserved : hosts[2].label);
|
||||
}
|
||||
for (const menu of ["Opt> ", "[Host]> ", "\x1b[32mOpt> \x1b[0m"]) {
|
||||
await change(() => controller.handleTerminalOutput(jump, `\r\nlogout\r\n${menu}`));
|
||||
record(`JumpServer return to menu ${JSON.stringify(menu)}`, jump, hosts[2].label);
|
||||
await change(() => controller.handleTerminalOutput(jump, `\r\n${targetPrompt}`));
|
||||
record("JumpServer re-enter target", jump, targetObserved);
|
||||
}
|
||||
await change(() => controller.handleTerminalOutput(jump, "\r\nOpt> "));
|
||||
await change(() => state.updateSessionStatus(jump, "disconnected"));
|
||||
await change(() => { state.updateSessionStatus(jump, "connecting"); setMode("off"); });
|
||||
record("same-session reconnect preserves saved name in off", jump, hosts[2].label);
|
||||
await change(() => { state.updateSessionStatus(jump, "connected"); setMode("all"); });
|
||||
await change(() => controller.handleTerminalOutput(jump, `\r\n${targetPrompt}`));
|
||||
record("first target after reconnect is observed again", jump, targetObserved);
|
||||
return { rows, promptOnlyParentRenders };
|
||||
} finally {
|
||||
flushSync(() => root.unmount());
|
||||
for (const id of [first, second, jump]) {
|
||||
if (id) { controller.forgetSession(id); sessionPresentationStore.clearSession(id); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
"use strict";
|
||||
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const esbuild = require("esbuild");
|
||||
const root = path.resolve(__dirname, "..");
|
||||
|
||||
function launchFromNode() {
|
||||
const { spawnSync } = require("node:child_process");
|
||||
const { applyElectronLaunchEnv } = require("../electron/launchEnv.cjs");
|
||||
const temp = require("../electron/bridges/tempDirBridge.cjs");
|
||||
const prefix = `${temp.getTempFilePath("ssh-tab-title-policy")}-`;
|
||||
const userData = fs.mkdtempSync(prefix);
|
||||
let code = 1;
|
||||
try {
|
||||
const result = spawnSync(require("electron"), [__filename], {
|
||||
cwd: root, stdio: "inherit", timeout: 65_000,
|
||||
env: { ...applyElectronLaunchEnv(process.env), NETCATTY_SSH_TITLE_USER_DATA: userData },
|
||||
});
|
||||
if (result.error) throw result.error;
|
||||
code = result.status ?? 1;
|
||||
} finally {
|
||||
// Chromium owns profile files until the child exits, especially on Windows.
|
||||
const target = path.resolve(userData);
|
||||
console.log("SSH_TAB_TITLE_CLEANUP", target);
|
||||
assert.equal(path.dirname(target), path.dirname(path.resolve(prefix)));
|
||||
assert.ok(path.basename(target).startsWith(path.basename(prefix)));
|
||||
const stat = fs.lstatSync(target);
|
||||
assert.ok(stat.isDirectory() && !stat.isSymbolicLink());
|
||||
fs.rmSync(target, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
|
||||
}
|
||||
process.exit(code);
|
||||
}
|
||||
|
||||
function fixtureResponse(request) {
|
||||
const url = new URL(request.url);
|
||||
if (url.hostname !== "fixture") return new Response("Not found", { status: 404 });
|
||||
if (url.pathname === "/index.html") return new Response("<body><div id='root'></div>", {
|
||||
headers: { "Content-Type": "text/html; charset=utf-8" },
|
||||
});
|
||||
let pathname;
|
||||
try { pathname = decodeURIComponent(url.pathname); } catch {
|
||||
return new Response("Invalid resource path", { status: 400 });
|
||||
}
|
||||
const publicRoot = path.join(root, "public");
|
||||
const file = path.resolve(publicRoot, `.${pathname}`);
|
||||
const relative = path.relative(publicRoot, file);
|
||||
if (relative.startsWith("..") || path.isAbsolute(relative)) return new Response("Not found", { status: 404 });
|
||||
if (!fs.existsSync(file) || !fs.statSync(file).isFile()) return new Response("Not found", { status: 404 });
|
||||
const mime = {
|
||||
".svg": "image/svg+xml", ".png": "image/png", ".ico": "image/x-icon",
|
||||
".css": "text/css", ".js": "text/javascript", ".woff2": "font/woff2",
|
||||
}[path.extname(file)] ?? "application/octet-stream";
|
||||
return new Response(fs.readFileSync(file), { headers: { "Content-Type": mime } });
|
||||
}
|
||||
|
||||
function runInElectron() {
|
||||
const { app, BrowserWindow, protocol } = require("electron");
|
||||
assert.ok(process.env.NETCATTY_SSH_TITLE_USER_DATA,
|
||||
"Launch with node scripts/ssh-tab-title-policy.live.test.cjs so profile cleanup runs after Electron exits.");
|
||||
protocol.registerSchemesAsPrivileged([{
|
||||
scheme: "ssh-title-test", privileges: { standard: true, secure: true, supportFetchAPI: true },
|
||||
}]);
|
||||
app.setPath("userData", process.env.NETCATTY_SSH_TITLE_USER_DATA);
|
||||
app.on("window-all-closed", () => {});
|
||||
let win;
|
||||
let finished = false;
|
||||
const finish = code => {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
clearTimeout(watchdog);
|
||||
win?.destroy();
|
||||
app.exit(code);
|
||||
};
|
||||
const watchdog = setTimeout(() => {
|
||||
console.error("SSH_TAB_TITLE_FAILED: real component verification exceeded 60 seconds");
|
||||
finish(1);
|
||||
}, 60_000);
|
||||
|
||||
void app.whenReady().then(async () => {
|
||||
const bundle = esbuild.buildSync({
|
||||
entryPoints: [path.join(__dirname, "fixtures/ssh-tab-title-policy.tsx")],
|
||||
bundle: true, format: "cjs", 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": "{}",
|
||||
"process.env.NODE_ENV": '"production"',
|
||||
},
|
||||
}).outputFiles[0].text;
|
||||
win = new BrowserWindow({
|
||||
show: process.env.NETCATTY_SSH_TITLE_SHOW_WINDOW === "1", width: 1280, height: 800,
|
||||
webPreferences: { contextIsolation: true, nodeIntegration: false, backgroundThrottling: false },
|
||||
});
|
||||
const consoleErrors = [];
|
||||
win.webContents.on("console-message", details => {
|
||||
if (details.level === "error") consoleErrors.push(details.message);
|
||||
});
|
||||
protocol.handle("ssh-title-test", fixtureResponse);
|
||||
await win.loadURL("ssh-title-test://fixture/index.html");
|
||||
const { rows, promptOnlyParentRenders } = await win.webContents.executeJavaScript(`(async () => {
|
||||
const loaded = { exports: {} };
|
||||
((module, exports) => { ${bundle} })(loaded, loaded.exports);
|
||||
return loaded.exports.runSshTabTitlePolicy();
|
||||
})()`);
|
||||
assert.ok(rows.length > 0, "The real component fixture must produce assertions");
|
||||
for (const row of rows) {
|
||||
assert.equal(row.actual, row.expected, `${row.scenario}; production tab=${row.tabId}`);
|
||||
}
|
||||
console.log("SSH_TAB_TITLE_BROWSER_CONSOLE_ERRORS", JSON.stringify(consoleErrors));
|
||||
assert.equal(consoleErrors.length, 0, "The real production components must not log browser errors");
|
||||
assert.equal(promptOnlyParentRenders, 0, "Prompt-only store updates must not force the fixture parent to render");
|
||||
console.log("SSH_TAB_TITLE_POLICY_OK", JSON.stringify({ assertions: rows.length, consoleErrors: consoleErrors.length, promptOnlyParentRenders }));
|
||||
finish(0);
|
||||
}).catch(error => {
|
||||
console.error("SSH_TAB_TITLE_POLICY_FAILED", error);
|
||||
finish(1);
|
||||
});
|
||||
}
|
||||
|
||||
if (process.versions.electron) runInElectron();
|
||||
else launchFromNode();
|
||||
Reference in new issue
Block a user