Compare commits

...
11 changed files with 412 additions and 12 deletions

No files matched your search

+4
View File
@@ -1048,6 +1048,10 @@ Highlight the focused split pane:
'vault.groups.deleteDialogTitle': 'Delete Group',
'vault.groups.deleteDialog.desc': 'This will permanently delete the group and move all hosts to the root level.',
'vault.groups.deleteDialog.managedDesc': 'This is a managed SSH config group. Deleting it will also delete all hosts and unlink from the source file.',
'vault.groups.deleteDialog.mixedDesc': 'This group contains hosts imported from a linked SSH config file. Every host under its managed subgroup will be deleted, even hosts not managed by that file. All other hosts will move to the root level unless you also delete them below.',
'vault.groups.deleteDialog.managedWarning': 'Deleting this group will also clear its entries from the linked SSH config file. Entries that came from that file may be lost for other apps that use it. Back up the file before continuing.',
'vault.groups.deleteDialog.sourcesChanged': 'The managed files affected by this deletion have changed. Review the files and confirm again.',
'vault.groups.deleteDialog.managedFile': 'Linked file: {file}',
'vault.groups.deleteDialog.deleteHosts': 'Also delete all hosts in this group',
'vault.groups.deleteDialog.bulkTitle': 'Delete Selected Groups',
'vault.groups.deleteDialog.bulkDesc': 'This will permanently delete the selected groups and move their hosts to the root level.',
+4
View File
@@ -1006,6 +1006,10 @@ Resalta el panel dividido enfocado:
'vault.groups.deleteDialogTitle': 'Eliminar grupo',
'vault.groups.deleteDialog.desc': 'Esto eliminará permanentemente el grupo y moverá todos los hosts al nivel raíz.',
'vault.groups.deleteDialog.managedDesc': 'Este es un grupo administrado de configuración SSH. Eliminarlo también eliminará todos los hosts y lo desvinculará del archivo de origen.',
'vault.groups.deleteDialog.mixedDesc': 'Este grupo contiene hosts importados de un archivo de configuración SSH vinculado. Todos los hosts bajo su subgrupo administrado se eliminarán, incluso los hosts no administrados por ese archivo. Los demás hosts se moverán al nivel raíz a menos que también los elimine abajo.',
'vault.groups.deleteDialog.managedWarning': 'Al eliminar este grupo también se borrarán sus entradas del archivo de configuración SSH vinculado. Las entradas provenientes de ese archivo pueden perderse y también afectará a otras aplicaciones que lo usen. Haz una copia de seguridad del archivo antes de continuar.',
'vault.groups.deleteDialog.sourcesChanged': 'Los archivos administrados afectados por esta eliminación han cambiado. Revisa los archivos y vuelve a confirmar.',
'vault.groups.deleteDialog.managedFile': 'Archivo vinculado: {file}',
'vault.groups.deleteDialog.deleteHosts': 'También eliminar todos los hosts de este grupo',
'vault.groups.deleteDialog.bulkTitle': 'Eliminar grupos seleccionados',
'vault.groups.deleteDialog.bulkDesc': 'Esto eliminará permanentemente los grupos seleccionados y moverá sus hosts al nivel raíz.',
+4
View File
@@ -1030,6 +1030,10 @@ export const ruCoreMessages: Messages = {
'vault.groups.deleteDialogTitle': 'Удалить группу',
'vault.groups.deleteDialog.desc': 'Группа будет безвозвратно удалена, а все хосты будут перемещены в корень.',
'vault.groups.deleteDialog.managedDesc': 'Это управляемая группа SSH-конфига. При её удалении также будут удалены все хосты и снята связь с исходным файлом.',
'vault.groups.deleteDialog.mixedDesc': 'Эта группа содержит хосты, импортированные из связанного SSH-конфига. Все хосты под управляемой подгруппой будут удалены, включая хосты, не управляемые этим файлом. Остальные хосты будут перемещены в корень, если вы также не удалите их ниже.',
'vault.groups.deleteDialog.managedWarning': 'При удалении этой группы её записи также будут удалены из связанного файла конфигурации SSH. Записи, импортированные из этого файла, могут быть утеряны, это затронет и другие приложения, использующие файл. Сделайте резервную копию файла перед продолжением.',
'vault.groups.deleteDialog.sourcesChanged': 'Управляемые файлы, затрагиваемые этим удалением, изменились. Проверьте файлы и подтвердите удаление снова.',
'vault.groups.deleteDialog.managedFile': 'Связанный файл: {file}',
'vault.groups.deleteDialog.deleteHosts': 'Также удалить все хосты в этой группе',
'vault.groups.deleteDialog.bulkTitle': 'Удалить выбранные группы',
'vault.groups.deleteDialog.bulkDesc': 'Выбранные группы будут безвозвратно удалены, а их хосты перемещены в корень.',
@@ -0,0 +1,48 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import en from './en.ts';
import ru from './ru.ts';
import es from './es.ts';
import zhCN from './zh-CN.ts';
import zhTW from './zh-TW.ts';
const KEYS = [
'vault.groups.deleteDialog.managedDesc',
'vault.groups.deleteDialog.mixedDesc',
'vault.groups.deleteDialog.managedWarning',
'vault.groups.deleteDialog.managedFile',
] as const;
test('managed group delete warning copy exists in every locale', () => {
for (const [locale, messages] of Object.entries({ en, ru, es, zhCN, zhTW })) {
const missing = KEYS.filter((key) => !messages[key]);
assert.deepEqual(missing, [], `${locale} is missing managed group delete copy`);
}
});
test('managed group delete warning mentions data loss in every locale', () => {
const MARKERS = ['备份', '備份', 'copia de seguridad', 'резервную копию', 'Back up'];
for (const [locale, messages] of Object.entries({ en, ru, es, zhCN, zhTW })) {
const text = messages['vault.groups.deleteDialog.managedWarning'];
assert.match(
text ?? '',
/SSH/,
`${locale} warning should reference the SSH config file`,
);
assert.ok(
MARKERS.some((marker) => text?.includes(marker)),
`${locale} warning should tell the user to back up the file`,
);
}
});
test('linked file line interpolates the file path', () => {
for (const messages of [en, ru, es, zhCN, zhTW]) {
assert.match(
messages['vault.groups.deleteDialog.managedFile'] ?? '',
/\{file\}/,
'managedFile copy should include the {file} placeholder',
);
}
});
+4
View File
@@ -678,6 +678,10 @@ export const zhCNCoreMessages: Messages = {
'vault.groups.deleteDialogTitle': '删除分组',
'vault.groups.deleteDialog.desc': '这将永久删除该分组并将所有主机移动到根级别。',
'vault.groups.deleteDialog.managedDesc': '这是一个托管的 SSH config 分组。删除后将同时删除所有主机并断开与源文件的连接。',
'vault.groups.deleteDialog.mixedDesc': '该分组包含从关联 SSH config 文件导入的主机。其托管子分组下的所有主机都将被删除,包括不受该文件管理的主机;其余主机将移动到根级别,除非您在下方选择同时删除。',
'vault.groups.deleteDialog.managedWarning': '删除该分组会同时清空关联 SSH config 文件中的对应条目,从该文件导入的配置可能会丢失,其他使用该文件的应用也会受到影响。请先备份文件再继续。',
'vault.groups.deleteDialog.sourcesChanged': '此次删除涉及的托管文件已发生变化。请检查文件并重新确认。',
'vault.groups.deleteDialog.managedFile': '关联文件:{file}',
'vault.groups.deleteDialog.deleteHosts': '同时删除该分组下的所有主机',
'vault.groups.deleteDialog.bulkTitle': '删除所选分组',
'vault.groups.deleteDialog.bulkDesc': '这将永久删除所选分组,并把其中的主机移动到根级别。',
+4
View File
@@ -680,6 +680,10 @@ export const zhTWCoreMessages: Messages = {
'vault.groups.deleteDialogTitle': '刪除群組',
'vault.groups.deleteDialog.desc': '這將永久刪除該群組並將所有主機移動到根層級。',
'vault.groups.deleteDialog.managedDesc': '這是一個託管的 SSH config 群組。刪除後將同時刪除所有主機並斷開與原始檔的連線。',
'vault.groups.deleteDialog.mixedDesc': '該群組包含從關聯 SSH config 檔案匯入的主機。其受管理子群組下的所有主機都將被刪除,包括不受該檔案管理的主機;其餘主機將移動到根層級,除非您在下方選擇同時刪除。',
'vault.groups.deleteDialog.managedWarning': '刪除該群組會同時清空關聯 SSH config 檔案中的對應條目,從該檔案匯入的設定可能會遺失,其他使用該檔案的應用也會受到影響。請先備份檔案再繼續。',
'vault.groups.deleteDialog.sourcesChanged': '此次刪除涉及的受管理檔案已發生變化。請檢查檔案並重新確認。',
'vault.groups.deleteDialog.managedFile': '關聯檔案:{file}',
'vault.groups.deleteDialog.deleteHosts': '同時刪除該群組下的所有主機',
'vault.groups.deleteDialog.bulkTitle': '刪除所選群組',
'vault.groups.deleteDialog.bulkDesc': '這將永久刪除所選群組,並把其中的主機移動到根層級。',
@@ -4,7 +4,7 @@ import React from "react";
import { act, create, type ReactTestRenderer } from "react-test-renderer";
import type { GroupConfig, ManagedSource } from "../../domain/models.ts";
import { useVaultGroupDeletion } from "./useVaultGroupDeletion.ts";
import { useVaultGroupDeletion, VaultGroupDeletionConfirmationChangedError } from "./useVaultGroupDeletion.ts";
test("group deletion removes saved settings in the same Vault transaction", async () => {
const actEnvironment = globalThis as typeof globalThis & {
@@ -132,7 +132,7 @@ test("group deletion restores managed files when the persisted Vault cannot be r
assert.equal(commitCount, 0);
});
test("group deletion retries file clearing when another managed source enters the group", async () => {
test("group deletion rejects retry when another managed source enters the group", async () => {
const actEnvironment = globalThis as typeof globalThis & {
IS_REACT_ACT_ENVIRONMENT?: boolean;
};
@@ -198,7 +198,7 @@ test("group deletion retries file clearing when another managed source enters th
renderer = create(React.createElement(Probe));
});
await act(async () => {
await deleteGroups?.(["Production"]);
await assert.rejects(deleteGroups!(["Production"]), VaultGroupDeletionConfirmationChangedError);
});
} finally {
await act(async () => {
@@ -209,10 +209,9 @@ test("group deletion retries file clearing when another managed source enters th
assert.deepEqual(clearedSourceIds, [
["managed-first"],
["managed-concurrent", "managed-first"],
]);
assert.equal(restoreCount, 1);
assert.equal(commitCount, 1);
assert.equal(commitCount, 0);
});
test("group deletion restores managed files and does not report success when commit fails", async () => {
@@ -278,3 +277,209 @@ test("group deletion restores managed files and does not report success when com
assert.equal(restoreCount, 1);
assert.equal(reportedCount, 0);
});
const confirmedSource: ManagedSource = {
id: "managed-production",
type: "ssh_config",
filePath: "/tmp/managed-production.conf",
groupName: "Production",
lastSyncedAt: 1,
};
async function withDeletionProbe(
options: Partial<Parameters<typeof useVaultGroupDeletion>[0]>,
run: (getDelete: () => ReturnType<typeof useVaultGroupDeletion>, rerender: (sources: ManagedSource[]) => Promise<void>) => Promise<void>,
) {
const environment = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
const previous = environment.IS_REACT_ACT_ENVIRONMENT;
environment.IS_REACT_ACT_ENVIRONMENT = true;
let renderer: ReactTestRenderer | undefined;
let deleteGroups!: ReturnType<typeof useVaultGroupDeletion>;
const defaults: Parameters<typeof useVaultGroupDeletion>[0] = {
customGroups: ["Production"], hosts: [], groupConfigs: [],
managedSources: [confirmedSource],
onReadPersistedHosts: async () => [],
onReadPersistedManagedSources: () => [confirmedSource],
onCommitVaultGroupMutation: async (mutate) => mutate({
groups: ["Production"], configs: [], hosts: [],
managedSources: [confirmedSource], snippets: [],
}),
...options,
};
const Probe = ({ sources }: { sources: ManagedSource[] }) => {
deleteGroups = useVaultGroupDeletion({ ...defaults, managedSources: sources });
return null;
};
try {
await act(async () => {
renderer = create(<Probe sources={defaults.managedSources} />);
});
await run(() => deleteGroups, async (sources) => {
await act(async () => { renderer!.update(<Probe sources={sources} />); });
});
} finally {
await act(async () => { renderer?.unmount(); });
environment.IS_REACT_ACT_ENVIRONMENT = previous;
}
}
for (const [name, rendered, persisted] of [
["changed file path", [confirmedSource], [{ ...confirmedSource, filePath: "/tmp/other.conf" }]],
["changed source id", [confirmedSource], [{ ...confirmedSource, id: "replacement" }]],
["added source", [confirmedSource], [confirmedSource, { ...confirmedSource, id: "added", filePath: "/tmp/added.conf" }]],
["first source", [], [confirmedSource]],
["source moved up within selection", [{ ...confirmedSource, groupName: "Production/Sub" }], [confirmedSource]],
["source moved into selection", [{ ...confirmedSource, groupName: "Staging" }], [confirmedSource]],
] as const) {
test(`group deletion rejects initially persisted ${name} before clearing files`, async () => {
let clearCount = 0;
let commitCount = 0;
let reportedCount = 0;
await withDeletionProbe({
managedSources: [...rendered],
onReadPersistedManagedSources: () => [...persisted],
onClearAndRemoveManagedSources: async () => {
clearCount += 1;
return async () => {};
},
onCommitVaultGroupMutation: async () => {
commitCount += 1;
throw new Error("unexpected commit");
},
onDeletedPaths: () => { reportedCount += 1; },
}, async (getDelete) => {
// A failed attempt refreshes latestRef without refreshing the warning.
for (let attempt = 0; attempt < 2; attempt += 1) {
await assert.rejects(getDelete()(["Production"]), VaultGroupDeletionConfirmationChangedError);
}
});
assert.equal(clearCount, 0);
assert.equal(commitCount, 0);
assert.equal(reportedCount, 0);
});
}
test("group deletion keeps old callbacks bound to their rendered confirmation", async () => {
const changed = { ...confirmedSource, filePath: "/tmp/changed.conf" };
const cleared: string[] = [];
await withDeletionProbe({
onReadPersistedManagedSources: () => [changed],
onClearAndRemoveManagedSources: async (sources) => {
cleared.push(...sources.map((source) => source.filePath));
return async () => {};
},
onCommitVaultGroupMutation: async (mutate) => mutate({
groups: ["Production"], configs: [], hosts: [], managedSources: [changed], snippets: [],
}),
}, async (getDelete, rerender) => {
const staleDelete = getDelete();
await rerender([changed]);
assert.notEqual(getDelete(), staleDelete);
await assert.rejects(staleDelete(["Production"]), VaultGroupDeletionConfirmationChangedError);
assert.deepEqual(cleared, []);
await getDelete()(["Production"]);
});
assert.deepEqual(cleared, [changed.filePath]);
});
for (const retry of ["snapshot", "commit", "superseded"] as const) {
test(`group deletion retains safe ${retry} retries for the same confirmed file`, async () => {
const updated = { ...confirmedSource, lastSyncedAt: 2 };
let reads = 0;
let commits = 0;
let restores = 0;
let reported = 0;
const cleared: string[] = [];
await withDeletionProbe({
onReadPersistedManagedSources: () => {
reads += 1;
return [retry === "snapshot" && reads > 1 ? updated : confirmedSource];
},
onClearAndRemoveManagedSources: async (sources) => {
cleared.push(...sources.map((source) => source.filePath));
return async () => { restores += 1; };
},
onCommitVaultGroupMutation: async (mutate) => {
commits += 1;
if (retry === "superseded" && commits === 1) return { ok: false, superseded: true };
return mutate({
groups: ["Production"], configs: [], hosts: [], snippets: [],
managedSources: [retry === "snapshot" || (retry === "commit" && commits === 1) ? updated : confirmedSource],
});
},
onDeletedPaths: () => { reported += 1; },
}, async (getDelete) => { await getDelete()(["Production"]); });
assert.deepEqual(cleared, [confirmedSource.filePath, confirmedSource.filePath]);
assert.equal(restores, 1);
assert.equal(commits, retry === "snapshot" ? 1 : 2);
assert.equal(reported, 1);
});
}
for (const retry of ["commit", "superseded"] as const) {
test(`group deletion rejects new files after a ${retry} retry`, async () => {
const added = { ...confirmedSource, id: "added", filePath: "/tmp/added.conf" };
let persisted = [confirmedSource];
let commits = 0;
let restores = 0;
let reported = 0;
const cleared: string[] = [];
await withDeletionProbe({
onReadPersistedManagedSources: () => persisted,
onClearAndRemoveManagedSources: async (sources) => {
cleared.push(...sources.map((source) => source.filePath));
return async () => { restores += 1; };
},
onCommitVaultGroupMutation: async (mutate) => {
commits += 1;
persisted = [confirmedSource, added];
if (retry === "superseded") return { ok: false, superseded: true };
return mutate({
groups: ["Production"], configs: [], hosts: [], snippets: [], managedSources: persisted,
});
},
onDeletedPaths: () => { reported += 1; },
}, async (getDelete) => {
await assert.rejects(getDelete()(["Production"]), VaultGroupDeletionConfirmationChangedError);
});
assert.deepEqual(cleared, [confirmedSource.filePath]);
assert.equal(restores, 1);
assert.equal(commits, 1);
assert.equal(reported, 0);
});
}
for (const phase of ["snapshot", "commit"] as const) {
test(`group deletion rejects a managed subgroup moved to its parent during ${phase}`, async () => {
const subgroup = { ...confirmedSource, groupName: "Production/Sub" };
let persisted = [subgroup];
let reads = 0;
let restores = 0;
let commits = 0;
const cleared: string[] = [];
await withDeletionProbe({
managedSources: [subgroup],
onReadPersistedManagedSources: () => {
if (phase === "snapshot" && ++reads > 1) persisted = [confirmedSource];
return persisted;
},
onClearAndRemoveManagedSources: async (sources) => {
cleared.push(...sources.map((source) => source.groupName));
return async () => { restores += 1; };
},
onCommitVaultGroupMutation: async (mutate) => {
commits += 1;
persisted = [confirmedSource];
return mutate({
groups: ["Production", "Production/Sub"], configs: [], hosts: [],
managedSources: persisted, snippets: [],
});
},
}, async (getDelete) => {
await assert.rejects(getDelete()(["Production"]), VaultGroupDeletionConfirmationChangedError);
});
assert.deepEqual(cleared, ["Production/Sub"]);
assert.equal(restores, 1);
assert.equal(commits, phase === "snapshot" ? 0 : 1);
});
}
@@ -14,6 +14,17 @@ import {
const RETRY_VAULT_GROUP_DELETION = Symbol("retry-vault-group-deletion");
export class VaultGroupDeletionConfirmationChangedError extends Error {
constructor() {
super("The managed files affected by this deletion have changed. Review the files and confirm again.");
this.name = "VaultGroupDeletionConfirmationChangedError";
}
}
const managedSourceDeletionIdentity = (source: ManagedSource): string => (
JSON.stringify([source.id, source.type, source.filePath, source.groupName])
);
const managedSourceSnapshotsMatch = (
left: ManagedSource[],
right: ManagedSource[],
@@ -59,6 +70,14 @@ export function useVaultGroupDeletion({
additionallyDeletedHostIds: ReadonlySet<string> = new Set(),
) => {
const selectedPaths = [...paths];
// Bind confirmation to the sources rendered with this callback, not the
// latest persisted snapshot (which reads and retries update independently).
const confirmedFiles = new Set(buildVaultGroupDeletion({
...latestRef.current,
selectedPaths,
deleteHosts,
managedSources,
}).sourcesToRemove.map(managedSourceDeletionIdentity));
let deletedRoots: string[] = [];
while (true) {
let restoreManagedFiles: (() => Promise<void>) | undefined;
@@ -82,6 +101,12 @@ export function useVaultGroupDeletion({
return { status: "empty" as const };
}
if (deletion.sourcesToRemove.some((source) => (
!confirmedFiles.has(managedSourceDeletionIdentity(source))
))) {
throw new VaultGroupDeletionConfirmationChangedError();
}
if (deletion.sourcesToRemove.length > 0) {
if (onClearAndRemoveManagedSources) {
restoreManagedFiles = await onClearAndRemoveManagedSources(deletion.sourcesToRemove);
@@ -194,6 +219,7 @@ export function useVaultGroupDeletion({
}
onDeletedPaths?.(deletedRoots);
}, [
managedSources,
onClearAndRemoveManagedSource,
onClearAndRemoveManagedSources,
onCommitVaultGroupMutation,
+16
View File
@@ -1289,6 +1289,21 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
t,
});
const managedFilesByGroupPath = useMemo(() => {
const map = new Map<string, string[]>();
for (const source of managedSources) {
if (source.filePath) {
const files = map.get(source.groupName);
if (files) {
files.push(source.filePath);
} else {
map.set(source.groupName, [source.filePath]);
}
}
}
return map;
}, [managedSources]);
const {
startInlineNewGroup,
startInlineRenameGroup,
@@ -1380,6 +1395,7 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
<>
<HostTreeGroupDeleteDialog
managedGroupPaths={managedGroupPaths}
managedFilesByGroupPath={managedFilesByGroupPath}
onConfirmDelete={deleteGroupPath}
/>
<VaultViewLayout
+54 -6
View File
@@ -5,6 +5,8 @@ import {
hostTreeInlineGroupDeleteStore,
useHostTreeInlineGroupDeleteTarget,
} from '../../application/state/hostTreeInlineGroupDeleteStore';
import { VaultGroupDeletionConfirmationChangedError } from '../../application/state/useVaultGroupDeletion';
import { toast } from '../ui/toast';
import { Button } from '../ui/button';
import {
Dialog,
@@ -17,11 +19,13 @@ import {
type HostTreeGroupDeleteDialogProps = {
managedGroupPaths?: Set<string>;
managedFilesByGroupPath?: Map<string, string[]>;
onConfirmDelete: (groupPath: string, deleteHosts: boolean) => void | Promise<void>;
};
export const HostTreeGroupDeleteDialog: React.FC<HostTreeGroupDeleteDialogProps> = ({
managedGroupPaths,
managedFilesByGroupPath,
onConfirmDelete,
}) => {
const { t } = useI18n();
@@ -29,6 +33,23 @@ export const HostTreeGroupDeleteDialog: React.FC<HostTreeGroupDeleteDialogProps>
const [deleteHosts, setDeleteHosts] = useState(false);
const isOpen = Boolean(targetPath);
const isManaged = Boolean(targetPath && managedGroupPaths?.has(targetPath));
const descendantManagedFiles: string[] = [];
if (targetPath && managedFilesByGroupPath) {
for (const [groupPath, files] of managedFilesByGroupPath) {
if (
(groupPath === targetPath || groupPath.startsWith(`${targetPath}/`))
) {
for (const filePath of files) {
if (
filePath
&& !descendantManagedFiles.includes(filePath)
) {
descendantManagedFiles.push(filePath);
}
}
}
}
}
useEffect(() => {
if (!isOpen) {
@@ -49,7 +70,9 @@ export const HostTreeGroupDeleteDialog: React.FC<HostTreeGroupDeleteDialogProps>
<DialogDescription className="break-words [overflow-wrap:anywhere]">
{isManaged
? t('vault.groups.deleteDialog.managedDesc')
: t('vault.groups.deleteDialog.desc')}
: descendantManagedFiles.length > 0
? t('vault.groups.deleteDialog.mixedDesc')
: t('vault.groups.deleteDialog.desc')}
</DialogDescription>
</DialogHeader>
<div className="min-w-0 space-y-4 py-4">
@@ -59,6 +82,25 @@ export const HostTreeGroupDeleteDialog: React.FC<HostTreeGroupDeleteDialogProps>
{t('vault.groups.pathLabel')}:{' '}
<span className="font-mono">{targetPath}</span>
</p>
{descendantManagedFiles.length > 0 && (
<div className="space-y-1 rounded-md border border-destructive/40 bg-destructive/10 p-3">
<p className="text-sm text-destructive">
{t('vault.groups.deleteDialog.managedWarning')}
</p>
{descendantManagedFiles.length > 0 && (
<div className="max-h-40 space-y-1 overflow-y-auto">
{descendantManagedFiles.map((filePath) => (
<p
key={filePath}
className="break-all font-mono text-xs text-muted-foreground"
>
{t('vault.groups.deleteDialog.managedFile', { file: filePath })}
</p>
))}
</div>
)}
</div>
)}
{!isManaged && (
<label className="flex items-center gap-2 text-sm cursor-pointer">
<input
@@ -79,12 +121,18 @@ export const HostTreeGroupDeleteDialog: React.FC<HostTreeGroupDeleteDialogProps>
</Button>
<Button
variant="destructive"
onClick={() => {
onClick={async () => {
if (!targetPath) return;
void Promise.resolve(onConfirmDelete(targetPath, isManaged || deleteHosts)).finally(() => {
hostTreeInlineGroupDeleteStore.close();
setDeleteHosts(false);
});
try {
await onConfirmDelete(targetPath, isManaged || deleteHosts);
} catch (error) {
toast.error(error instanceof VaultGroupDeletionConfirmationChangedError
? t('vault.groups.deleteDialog.sourcesChanged')
: error instanceof Error ? error.message : t('common.error'));
return;
}
hostTreeInlineGroupDeleteStore.close();
setDeleteHosts(false);
}}
>
{t('common.delete')}
+38 -1
View File
@@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useCallback } from "react";
import { deleteVaultKey } from "../../application/defaultKeyPassphrases";
import { VaultGroupDeletionConfirmationChangedError } from "../../application/state/useVaultGroupDeletion";
import { usePluginImporterCommit } from "../../application/state/usePluginImporterCommit";
import { preserveConcurrentHostLineTimestampUpdate } from "../../domain/host";
import {
@@ -390,6 +391,19 @@ export function VaultViewLayout({ ctx }: { ctx: VaultViewLayoutContext }) {
source.groupName === path || source.groupName.startsWith(path + "/"),
),
);
const pendingDeleteManagedFiles: string[] = [];
for (const source of managedSources) {
if (
source.filePath
&& !pendingDeleteManagedFiles.includes(source.filePath)
&& pendingDeleteGroupPaths.some(
(path) =>
source.groupName === path || source.groupName.startsWith(path + "/"),
)
) {
pendingDeleteManagedFiles.push(source.filePath);
}
}
const handleNotesOpenHost = useCallback((host: any, source?: { noteId?: string }) => {
if (source?.noteId && onOpenHostFromNote) {
onOpenHostFromNote(host, source);
@@ -1654,6 +1668,27 @@ export function VaultViewLayout({ ctx }: { ctx: VaultViewLayoutContext }) {
})
)}
</p>
{pendingDeleteHasManagedGroups && (
<div className="space-y-1 rounded-md border border-destructive/40 bg-destructive/10 p-3">
<p className="text-sm text-destructive">
{t("vault.groups.deleteDialog.managedWarning")}
</p>
{pendingDeleteManagedFiles.length > 0 && (
<div className="max-h-40 space-y-1 overflow-y-auto">
{pendingDeleteManagedFiles.map((filePath) => (
<p
key={filePath}
className="break-all font-mono text-xs text-muted-foreground"
>
{t("vault.groups.deleteDialog.managedFile", {
file: filePath,
})}
</p>
))}
</div>
)}
</div>
)}
{!pendingDeleteHasManagedGroups && (
<label className="flex items-center gap-2 text-sm cursor-pointer">
<input
@@ -1692,7 +1727,9 @@ export function VaultViewLayout({ ctx }: { ctx: VaultViewLayoutContext }) {
isBulkDelete ? selectedHostIds : new Set<string>(),
);
} catch (error) {
toast.error(error instanceof Error ? error.message : t("common.error"));
toast.error(error instanceof VaultGroupDeletionConfirmationChangedError
? t("vault.groups.deleteDialog.sourcesChanged")
: error instanceof Error ? error.message : t("common.error"));
return;
}
if (isBulkDelete) {