mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-12-06 19:03:43 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1ed0a7ddd7 | ||
|
|
8583d6a345 |
No files matched your search
@@ -0,0 +1,160 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
import React from 'react';
|
||||
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
|
||||
import { I18nProvider } from '../application/i18n/I18nProvider';
|
||||
import type { Host } from '../domain/models';
|
||||
import HostDetailsPanel from './HostDetailsPanel';
|
||||
import { HostDetailsConnectionSections } from './HostDetailsConnectionSections';
|
||||
import { LocalShellHostDetailsPanel } from './LocalShellHostDetailsPanel';
|
||||
import { SerialHostDetailsPanel } from './SerialHostDetailsPanel';
|
||||
import { installDomEnvironment } from './test-support/renderReactDom';
|
||||
import { AsidePanelFooter } from './ui/aside-panel';
|
||||
import { Button } from './ui/button';
|
||||
import { Combobox } from './ui/combobox';
|
||||
import { Input } from './ui/input';
|
||||
import { TooltipProvider } from './ui/tooltip';
|
||||
|
||||
type PanelKind = 'ssh' | 'local' | 'serial';
|
||||
const host: Host = {
|
||||
id: 'existing', label: 'Web', hostname: 'web.example.com', username: 'root',
|
||||
password: 'test-password', authMethod: 'password', tags: [], os: 'linux',
|
||||
protocol: 'ssh', group: 'prod / web',
|
||||
};
|
||||
|
||||
async function withPanel(
|
||||
kind: PanelKind,
|
||||
initialData: Host | undefined,
|
||||
run: (editor: {
|
||||
renderer: ReactTestRenderer;
|
||||
save: () => Promise<Host>;
|
||||
created: string[];
|
||||
}) => Promise<void>,
|
||||
groups: string[] = [],
|
||||
) {
|
||||
const dom = installDomEnvironment();
|
||||
const previousRaf = globalThis.requestAnimationFrame;
|
||||
const previousCancelRaf = globalThis.cancelAnimationFrame;
|
||||
globalThis.requestAnimationFrame = (callback) => setTimeout(() => callback(0), 0) as unknown as number;
|
||||
globalThis.cancelAnimationFrame = (id) => clearTimeout(id);
|
||||
let renderer: ReactTestRenderer | undefined;
|
||||
let saved: Host | undefined;
|
||||
const created: string[] = [];
|
||||
const common = { onSave: (value: Host) => { saved = value; }, onCancel() {}, groups, layout: 'inline' as const };
|
||||
try {
|
||||
await act(async () => {
|
||||
renderer = create(<I18nProvider locale="en"><TooltipProvider>
|
||||
{kind === 'ssh' ? <HostDetailsPanel {...common} initialData={initialData}
|
||||
availableKeys={[]} identities={[]} terminalThemeId="default" terminalFontSize={14}
|
||||
onCreateGroup={(path) => created.push(path)} />
|
||||
: kind === 'local' ? <LocalShellHostDetailsPanel {...common} initialData={initialData} />
|
||||
: <SerialHostDetailsPanel {...common} initialData={initialData!} />}
|
||||
</TooltipProvider></I18nProvider>);
|
||||
});
|
||||
await run({
|
||||
renderer: renderer!, created,
|
||||
save: async () => {
|
||||
saved = undefined;
|
||||
await act(async () => {
|
||||
const buttons = renderer!.root.findByType(AsidePanelFooter).findAllByType(Button);
|
||||
await buttons[buttons.length - 1].props.onClick();
|
||||
});
|
||||
assert.ok(saved, 'the panel must call onSave');
|
||||
return saved;
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
if (renderer) await act(async () => { renderer!.unmount(); });
|
||||
globalThis.requestAnimationFrame = previousRaf;
|
||||
globalThis.cancelAnimationFrame = previousCancelRaf;
|
||||
dom.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
function groupPicker(renderer: ReactTestRenderer, kind: PanelKind) {
|
||||
return renderer.root.findAllByType(Combobox).find((picker) =>
|
||||
kind === 'ssh' ? picker.props.createText === 'Create Group' : picker.props.placeholder === 'Select Group',
|
||||
)!;
|
||||
}
|
||||
|
||||
for (const kind of ['ssh', 'local', 'serial'] as const) {
|
||||
const initialData = { ...host, protocol: kind, ...(kind === 'serial' ? { hostname: 'COM3' } : {}) };
|
||||
test(`${kind} Host Details keeps the exact stored group on a label-only edit`, async () => {
|
||||
for (const group of ['prod / web', ' prod / web ', ' prod/web ']) {
|
||||
await withPanel(kind, { ...initialData, group }, async ({ renderer, save }) => {
|
||||
await act(async () => {
|
||||
renderer.root.findAllByType(Input).find((input) => input.props.value === host.label)!
|
||||
.props.onChange({ target: { value: 'Updated label' } });
|
||||
});
|
||||
const saved = await save();
|
||||
assert.equal(saved.label, 'Updated label');
|
||||
assert.equal(saved.group, group);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test(`${kind} Host Details normalizes an explicitly selected trimmed-equivalent group`, async () => {
|
||||
for (const group of [' prod/web ', ' prod / web ']) {
|
||||
await withPanel(kind, { ...initialData, group }, async ({ renderer, save }) => {
|
||||
await act(async () => { groupPicker(renderer, kind).props.onValueChange(group.trim()); });
|
||||
assert.equal((await save()).group, 'prod/web');
|
||||
}, [group.trim()]);
|
||||
}
|
||||
});
|
||||
|
||||
test(`${kind} Host Details normalizes a changed group and allows clearing it`, async () => {
|
||||
await withPanel(kind, initialData, async ({ renderer, save }) => {
|
||||
const picker = groupPicker(renderer, kind);
|
||||
await act(async () => { picker.props.onValueChange(host.group); });
|
||||
assert.equal((await save()).group, host.group, 'reselecting the original group preserves it');
|
||||
for (const [value, expected] of [[' stage / / web ', 'stage/web'], ['', '']]) {
|
||||
await act(async () => { picker.props.onValueChange(value); });
|
||||
assert.equal((await save()).group, expected);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
for (const kind of ['ssh', 'local'] as const) {
|
||||
test(`${kind} Host Details normalizes a new host's group`, async () => {
|
||||
await withPanel(kind, undefined, async ({ renderer, save }) => {
|
||||
await act(async () => {
|
||||
if (kind === 'ssh') {
|
||||
const { update } = renderer.root.findByType(HostDetailsConnectionSections).props;
|
||||
update('hostname', 'web.example.com');
|
||||
update('password', 'test-password');
|
||||
}
|
||||
groupPicker(renderer, kind).props.onValueChange('prod / web');
|
||||
});
|
||||
assert.equal((await save()).group, 'prod/web');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test('Create Group normalizes paths before creation and selection, including the Combobox follow-up', async () => {
|
||||
const values = ['prod / web', 'prod//web', 'prod\\web', ' prod / web ', '/ prod / / web //'];
|
||||
for (const groups of [[], ['prod/web']]) {
|
||||
await withPanel('ssh', host, async ({ renderer, save, created }) => {
|
||||
for (const value of values) {
|
||||
const picker = groupPicker(renderer, 'ssh');
|
||||
await act(async () => { picker.props.onCreateNew(value); });
|
||||
assert.equal(groupPicker(renderer, 'ssh').props.value, 'prod/web');
|
||||
// Combobox calls both callbacks with the original input when creating.
|
||||
await act(async () => { picker.props.onValueChange(value); });
|
||||
assert.equal(groupPicker(renderer, 'ssh').props.value, 'prod/web');
|
||||
assert.equal((await save()).group, 'prod/web');
|
||||
}
|
||||
assert.deepEqual(created, groups.length ? [] : values.map(() => 'prod/web'));
|
||||
await act(async () => { groupPicker(renderer, 'ssh').props.onCreateNew(' / / \\ '); });
|
||||
assert.equal(created.length, groups.length ? 0 : values.length);
|
||||
}, groups);
|
||||
}
|
||||
});
|
||||
|
||||
test('new-group sub-panel passes both parent and name through the same creation handler', () => {
|
||||
const source = readFileSync(new URL('./HostDetailsPanel.tsx', import.meta.url), 'utf8');
|
||||
assert.match(source, /createAndSelectGroup\(`\$\{newGroupParent\}\/\$\{newGroupName\}`\)/);
|
||||
assert.match(source, /onSave=\{handleCreateGroup\}/);
|
||||
assert.match(source, /onCreateNew=\{createAndSelectGroup\}/);
|
||||
});
|
||||
@@ -14,6 +14,7 @@ import React, { useEffect, useMemo, useState, useCallback, useRef } from "react"
|
||||
import { useI18n } from "../application/i18n/I18nProvider";
|
||||
import { useApplicationBackend, type SshAgentStatus } from "../application/state/useApplicationBackend";
|
||||
import { applyGroupDefaults, resolveGroupDefaults, resolveGroupTerminalThemeId } from "../domain/groupConfig";
|
||||
import { normalizeGroupTargetPath, resolveHostGroupForSave } from "../domain/hostGroupPathMutations";
|
||||
import {
|
||||
getEffectiveHostDistro,
|
||||
normalizePrimaryTelnetState,
|
||||
@@ -281,6 +282,8 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
}, [form.agentForwarding, form.identityAgent, form.hostname, form.port, form.username, checkSshAgent]);
|
||||
|
||||
const [groupInputValue, setGroupInputValue] = useState(form.group || "");
|
||||
const originalGroupRef = useRef(initialData ? initialData.group || "" : undefined);
|
||||
const createdGroupInputRef = useRef<string | null>(null);
|
||||
|
||||
const initialHostId = initialData?.id;
|
||||
|
||||
@@ -315,6 +318,8 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
}, [initialData, snippets]);
|
||||
|
||||
useEffect(() => {
|
||||
originalGroupRef.current = initialData ? initialData.group || "" : undefined;
|
||||
createdGroupInputRef.current = null;
|
||||
if (!initialData) return;
|
||||
const normalized = normalizePrimaryTelnetState(initialData);
|
||||
setForm(
|
||||
@@ -578,7 +583,11 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
}
|
||||
const normalizedProxyConfig = proxySave.normalizedProxyConfig;
|
||||
let finalLabel = form.label?.trim() || hostname;
|
||||
const finalGroup = groupInputValue.trim() || form.group || "";
|
||||
const finalGroup = resolveHostGroupForSave(
|
||||
groupInputValue.trim() || form.group || "",
|
||||
originalGroupRef.current,
|
||||
groupInputValue !== originalGroupRef.current,
|
||||
);
|
||||
|
||||
const targetManagedSource = managedSources
|
||||
.filter(s => finalGroup === s.groupName || finalGroup.startsWith(s.groupName + "/"))
|
||||
@@ -761,14 +770,18 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateGroup = () => {
|
||||
if (!newGroupName.trim()) return;
|
||||
const fullPath = newGroupParent
|
||||
? `${newGroupParent}/${newGroupName.trim()}`
|
||||
: newGroupName.trim();
|
||||
onCreateGroup?.(fullPath);
|
||||
const createAndSelectGroup = (value: string) => {
|
||||
const fullPath = normalizeGroupTargetPath(value);
|
||||
if (!fullPath) return;
|
||||
createdGroupInputRef.current = value;
|
||||
if (!groups.includes(fullPath)) onCreateGroup?.(fullPath);
|
||||
setGroupInputValue(fullPath);
|
||||
update("group", fullPath);
|
||||
};
|
||||
|
||||
const handleCreateGroup = () => {
|
||||
if (!newGroupName.trim()) return;
|
||||
createAndSelectGroup(`${newGroupParent}/${newGroupName}`);
|
||||
setNewGroupName("");
|
||||
setNewGroupParent("");
|
||||
setActiveSubPanel("none");
|
||||
@@ -1117,16 +1130,18 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
options={groupOptions}
|
||||
value={form.group || ""}
|
||||
onValueChange={(val) => {
|
||||
update("group", val);
|
||||
setGroupInputValue(val);
|
||||
// Creation also calls onValueChange with the raw input. Keep that
|
||||
// path normalized while preserving a reselected legacy group.
|
||||
const groupPath = val === createdGroupInputRef.current
|
||||
? normalizeGroupTargetPath(val)
|
||||
: resolveHostGroupForSave(val, originalGroupRef.current, val !== originalGroupRef.current);
|
||||
createdGroupInputRef.current = null;
|
||||
update("group", groupPath);
|
||||
setGroupInputValue(groupPath);
|
||||
}}
|
||||
placeholder={t("hostDetails.group.placeholder")}
|
||||
allowCreate={true}
|
||||
onCreateNew={(val) => {
|
||||
onCreateGroup?.(val);
|
||||
update("group", val);
|
||||
setGroupInputValue(val);
|
||||
}}
|
||||
onCreateNew={createAndSelectGroup}
|
||||
createText="Create Group"
|
||||
triggerClassName="flex-1 h-10"
|
||||
/>
|
||||
|
||||
@@ -5,12 +5,13 @@
|
||||
* into vault groups next to their SSH hosts (issue #3615).
|
||||
*/
|
||||
import { Save, TerminalSquare, X } from 'lucide-react';
|
||||
import React, { useMemo, useState } from 'react';
|
||||
import React, { useMemo, useRef, useState } from 'react';
|
||||
import { useI18n } from '../application/i18n/I18nProvider';
|
||||
import { useDiscoveredShells } from '../lib/useDiscoveredShells';
|
||||
import { detectLocalOs } from '../lib/localShell';
|
||||
import type { Host } from '../domain/models';
|
||||
import { createLocalShellHost } from '../domain/localShellHost';
|
||||
import { resolveHostGroupForSave } from '../domain/hostGroupPathMutations';
|
||||
|
||||
import { Button } from './ui/button';
|
||||
import { Combobox, ComboboxOption } from './ui/combobox';
|
||||
@@ -68,6 +69,7 @@ export const LocalShellHostDetailsPanel: React.FC<LocalShellHostDetailsPanelProp
|
||||
const [group, setGroup] = useState(
|
||||
initialData ? initialData.group ?? '' : defaultGroup ?? '',
|
||||
);
|
||||
const originalGroupRef = useRef(initialData ? initialData.group ?? '' : undefined);
|
||||
|
||||
const matchedShell = useMemo(
|
||||
() => discoveredShells.find((candidate) => candidate.id === shell),
|
||||
@@ -128,12 +130,12 @@ export const LocalShellHostDetailsPanel: React.FC<LocalShellHostDetailsPanelProp
|
||||
shellIcon: shellMeta?.icon,
|
||||
startDir,
|
||||
startupCommand,
|
||||
// Save the controlled value directly: '' means the user explicitly
|
||||
// cleared the group, which persists at the vault root.
|
||||
group: group,
|
||||
group,
|
||||
tags: initialData?.tags,
|
||||
notes: initialData?.notes,
|
||||
});
|
||||
// Apply after the factory's outer trim to retain unchanged legacy paths exactly.
|
||||
host.group = resolveHostGroupForSave(group, originalGroupRef.current, group !== originalGroupRef.current);
|
||||
// On edits, merge over the existing host so fields this form does not
|
||||
// expose (pinned, lastConnectedAt, order, ...) and the original
|
||||
// creation timestamp survive a save.
|
||||
|
||||
@@ -3,9 +3,10 @@
|
||||
* A dedicated editor for serial port hosts (distinct from SSH HostDetailsPanel)
|
||||
*/
|
||||
import { Eye, EyeOff, Save, Tag, X } from 'lucide-react';
|
||||
import React, { useMemo, useState } from 'react';
|
||||
import React, { useMemo, useRef, useState } from 'react';
|
||||
import { useI18n } from '../application/i18n/I18nProvider';
|
||||
import type { GroupConfig, Host, SerialConfig, SerialFlowControl, SerialParity } from '../domain/models';
|
||||
import { resolveHostGroupForSave } from '../domain/hostGroupPathMutations';
|
||||
import {
|
||||
resolveSerialBackspaceFormValue,
|
||||
resolveSerialBackspaceOverrideOnSave,
|
||||
@@ -97,6 +98,7 @@ export const SerialHostDetailsPanel: React.FC<SerialHostDetailsPanelPropsWithRes
|
||||
const [charset, setCharset] = useState(initialData.charset || 'UTF-8');
|
||||
const [tags, setTags] = useState<string[]>(initialData.tags || []);
|
||||
const [group, setGroup] = useState(initialData.group || '');
|
||||
const originalGroupRef = useRef(initialData.group || '');
|
||||
const [notes, setNotes] = useState(initialData.notes ?? '');
|
||||
|
||||
const handleSave = () => {
|
||||
@@ -136,7 +138,7 @@ export const SerialHostDetailsPanel: React.FC<SerialHostDetailsPanelPropsWithRes
|
||||
? (passwordCleared ? undefined : password)
|
||||
: (initialData.password ?? undefined),
|
||||
tags,
|
||||
group,
|
||||
group: resolveHostGroupForSave(group, originalGroupRef.current, group !== originalGroupRef.current),
|
||||
charset,
|
||||
serialConfig: config,
|
||||
backspaceBehavior: undefined,
|
||||
|
||||
@@ -1,11 +1,45 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
normalizeGroupTargetPath,
|
||||
resolveHostGroupForSave,
|
||||
remapSnippetTargetGroupPaths,
|
||||
removeSnippetTargetGroupPaths,
|
||||
} from './hostGroupPathMutations.ts';
|
||||
import type { Snippet } from './models';
|
||||
|
||||
const dirtyPaths = ['prod / web', 'prod//web', 'prod\\web', ' prod / web ', '/ prod / / web //'];
|
||||
|
||||
test('Host Details normalizes new and changed group paths with the shared rules', () => {
|
||||
for (const value of dirtyPaths) {
|
||||
assert.equal(normalizeGroupTargetPath(value), 'prod/web');
|
||||
assert.equal(resolveHostGroupForSave(value), 'prod/web', 'new host');
|
||||
assert.equal(resolveHostGroupForSave(value, ''), 'prod/web', 'previously ungrouped host');
|
||||
assert.equal(resolveHostGroupForSave(value, 'staging'), 'prod/web', 'changed group');
|
||||
}
|
||||
});
|
||||
|
||||
test('Host Details preserves unchanged stored paths on unrelated edits', () => {
|
||||
for (const storedGroup of [...dirtyPaths, '', ' ']) {
|
||||
const value = storedGroup.trim() || storedGroup || '';
|
||||
assert.equal(resolveHostGroupForSave(value, storedGroup), storedGroup);
|
||||
assert.equal(resolveHostGroupForSave(storedGroup, storedGroup), storedGroup);
|
||||
}
|
||||
});
|
||||
|
||||
test('Host Details normalizes an explicitly changed group equivalent after trimming', () => {
|
||||
for (const storedGroup of [' prod/web ', ' prod / web ']) {
|
||||
assert.equal(resolveHostGroupForSave(storedGroup.trim(), storedGroup, true), 'prod/web');
|
||||
}
|
||||
});
|
||||
|
||||
test('Host Details allows changed paths to normalize to ungrouped', () => {
|
||||
for (const value of ['', ' / / \\ ']) {
|
||||
assert.equal(resolveHostGroupForSave(value, 'prod / web'), '');
|
||||
assert.equal(resolveHostGroupForSave(value), '');
|
||||
}
|
||||
});
|
||||
|
||||
const snippets: Snippet[] = [{
|
||||
id: 'script-a',
|
||||
label: 'A',
|
||||
|
||||
@@ -9,6 +9,16 @@ export function normalizeGroupTargetPath(value: string): string {
|
||||
.join('/');
|
||||
}
|
||||
|
||||
// Undefined means a new host; existing ungrouped hosts use ''. Preserve legacy
|
||||
// paths on unrelated edits so their exact-path connection defaults do not change.
|
||||
// Compare the raw field before save-time trimming to determine groupChanged.
|
||||
export function resolveHostGroupForSave(value: string, originalGroup?: string, groupChanged = false): string {
|
||||
if (!groupChanged && originalGroup !== undefined && (value === originalGroup || value === originalGroup.trim())) {
|
||||
return originalGroup;
|
||||
}
|
||||
return normalizeGroupTargetPath(value);
|
||||
}
|
||||
|
||||
export function normalizeGroupTargetPaths(values: Iterable<string>): string[] {
|
||||
return Array.from(new Set(
|
||||
[...values].map(normalizeGroupTargetPath).filter(Boolean),
|
||||
|
||||
Reference in new issue
Block a user