Files
Netcatty/components/vault/useVaultImportHandlers.ts
T
陈大猫andCursor 9aed2c41d4 feat(ai): unify capability registry, harness tools, and agent runtime (#1685)
* feat(ai): unify capability registry, harness tools, and agent runtime

Centralize MCP/CLI/Catty tool surfaces in the capability catalog with codegen,
move Catty-only harness tools into catalog with local execution, converge
mcpServerBridge builtin dispatch via registry, and wire AgentRuntime with
vault bridge, permission grants, and Round 2 catalog parity.

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(ai): vault host tools, artifact cards, and external agent vault guidance

Unify vault host create/import with capability RPC routing, add chat artifact cards with Vault navigation, and align external MCP agents with Catty rules so host creation never falls back to Vault Notes.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(ai): address Bugbot findings for streaming, vault bridge, and grants

Clear Catty streaming by chat sessionId, read latest vault state via getters on agent mutations, and stack grant persisters so unmounting one AI panel does not break others.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(vault): clear pending openNoteId after chat navigation focus

NotesManager notifies VaultView once the one-shot openNoteId request is applied so the id does not stick for the rest of the session.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(vault): serialize vault agent IPC mutations to prevent lost writes

Queue vault agent bridge handlers so concurrent hosts.create or note.create tool calls cannot overwrite each other via stale read-modify-write snapshots.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(vault): keep synchronous vault snapshot for agent IPC reads

Mirror hosts, notes, and groups in a ref updated immediately on agent writes so serialized mutations see the latest state before React re-renders.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(ai): sync Catty MCP sessions and defer runtime cleanup on delete

Register terminal sessions with the main process before Catty tool calls, and clear ToolOutputStore only after stopping an active turn when deleting a chat session.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(ai): avoid deleting a newer abort controller on late stop

Only remove the session abort-controller entry when stop finishes if it still refers to the controller that was stopped.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(ai): sync vault snapshot on render and await active turn on stop

Refresh vault agent reads when React props change without clobbering in-flight agent writes, and wait for runTurn to finish before clearing ToolOutputStore on session delete.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(ai): reload permission grants from storage before auto-approve

Re-read persisted grant rules on each approval check so revocations in Settings take effect without requiring a chat hook remount.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(ai): sync permission grants to main process immediately on write

Push MCP permissionGrantsSnapshot as soon as Always allow persists a rule so the next tool call in the same agent turn sees the grant without waiting for useEffect.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-26 00:08:39 +08:00

226 lines
8.5 KiB
TypeScript

import { useCallback } from "react";
import { sanitizeHost } from "../../domain/host";
import { readTextFile } from "../../lib/readTextFile";
import { applyVaultHostImport, importVaultHostsFromText, type VaultImportFormat } from "../../domain/vaultImport";
import type { Host, ManagedSource } from "../../types";
import type { ImportOptions } from "./ImportVaultDialog";
import { toast } from "../ui/toast";
interface UseVaultImportHandlersOptions {
customGroups: string[];
hosts: Host[];
managedSources: ManagedSource[];
onUpdateCustomGroups: (groups: string[]) => void;
onUpdateHosts: (hosts: Host[]) => void;
onUpdateManagedSources: (sources: ManagedSource[]) => void;
setIsImportOpen: (open: boolean) => void;
t: (key: string, values?: Record<string, unknown>) => string;
}
export function useVaultImportHandlers({
customGroups,
hosts,
managedSources,
onUpdateCustomGroups,
onUpdateHosts,
onUpdateManagedSources,
setIsImportOpen,
t,
}: UseVaultImportHandlersOptions) {
const handleImportFileSelected = useCallback(
async (format: VaultImportFormat, file: File, options?: ImportOptions) => {
setIsImportOpen(false);
try {
const formatLabel =
format === "putty"
? "PuTTY"
: format === "mobaxterm"
? "MobaXterm"
: format === "csv"
? "CSV"
: format === "securecrt"
? "SecureCRT"
: "ssh_config";
toast.info(t("vault.import.toast.start", { format: formatLabel }));
const text = await readTextFile(file);
const result = importVaultHostsFromText(format, text, {
fileName: file.name,
});
const isManaged = format === "ssh_config" && options?.managed === true;
const fileBaseName = file.name.replace(/\.[^/.]+$/, "");
// Generate unique managed group name (check for conflicts with existing sources,
// custom groups, and host groups to avoid accidentally merging unrelated hosts)
let managedGroupName = `${fileBaseName} - Managed`;
if (isManaged) {
const existingGroupNames = new Set([
...managedSources.map(s => s.groupName),
...customGroups,
...hosts.map(h => h.group).filter((g): g is string => !!g),
]);
let suffix = 1;
while (existingGroupNames.has(managedGroupName)) {
managedGroupName = `${fileBaseName} - Managed (${suffix})`;
suffix++;
}
}
// Check if this file is already managed
const bridge = (window as unknown as { netcatty?: { getPathForFile?: (file: File) => string | undefined } }).netcatty;
// Try bridge.getPathForFile first, then fall back to file.path (Electron legacy)
const filePath = bridge?.getPathForFile?.(file) || (file as File & { path?: string }).path;
if (isManaged && !filePath) {
// Cannot proceed with managed import without a valid file path
toast.error(
t("vault.import.sshConfig.noFilePathDesc"),
t("vault.import.sshConfig.noFilePath"),
);
return;
}
if (isManaged) {
const existingSource = managedSources.find(s => s.filePath === filePath);
if (existingSource) {
toast.error(
t("vault.import.sshConfig.alreadyManagedDesc", { group: existingSource.groupName }),
t("vault.import.sshConfig.alreadyManaged"),
);
return;
}
}
const makeKey = (h: Host) =>
`${(h.protocol ?? "ssh").toLowerCase()}|${h.hostname.toLowerCase()}|${h.port}|${(h.username ?? "").toLowerCase()}`;
const existingKeys = new Set(hosts.map(makeKey));
// Filter out duplicates for both managed and non-managed imports
let newHosts = result.hosts.filter((h) => !existingKeys.has(makeKey(h)));
// For managed imports, also update existing hosts to be managed
let updatedExistingHosts: Host[] = [];
if (isManaged) {
const importedKeys = new Set(result.hosts.map(makeKey));
updatedExistingHosts = hosts.filter((h) => importedKeys.has(makeKey(h)));
}
if (isManaged && (newHosts.length > 0 || updatedExistingHosts.length > 0)) {
const sourceId = crypto.randomUUID();
const newSource: ManagedSource = {
id: sourceId,
type: "ssh_config",
filePath: filePath,
groupName: managedGroupName,
lastSyncedAt: Date.now(),
};
newHosts = newHosts.map((h) => ({
...h,
group: managedGroupName,
// Only SSH hosts can be managed (SSH config only supports SSH)
managedSourceId: (!h.protocol || h.protocol === "ssh") ? sourceId : undefined,
}));
// Update existing hosts to be managed (move to managed group)
const existingHostIds = new Set(updatedExistingHosts.map(h => h.id));
const updatedHosts = hosts.map((h) => {
if (!existingHostIds.has(h.id)) return h;
const canBeManaged = !h.protocol || h.protocol === "ssh";
return {
...h,
group: managedGroupName,
managedSourceId: canBeManaged ? sourceId : undefined,
// Sanitize label for managed hosts
label: canBeManaged && h.label ? h.label.replace(/\s/g, '') : h.label,
};
});
onUpdateManagedSources([...managedSources, newSource]);
onUpdateHosts([...updatedHosts, ...newHosts].map(sanitizeHost));
const nextGroups = Array.from(
new Set([
...customGroups,
...result.groups,
managedGroupName,
...newHosts.map((h) => h.group).filter(Boolean),
]),
) as string[];
onUpdateCustomGroups(nextGroups);
} else if (newHosts.length > 0) {
const merged = applyVaultHostImport(hosts, customGroups, result, { skipDuplicates: true });
onUpdateHosts(merged.hosts);
onUpdateCustomGroups(merged.customGroups);
}
// Count total hosts affected (new + converted to managed)
const totalAffected = newHosts.length + (isManaged ? updatedExistingHosts.length : 0);
const skipped = result.stats.skipped;
const duplicates = result.stats.duplicates;
const hasWarnings = skipped > 0 || duplicates > 0 || result.issues.length > 0;
if (result.stats.parsed === 0 && totalAffected === 0) {
toast.error(
t("vault.import.toast.noEntries", { format: formatLabel }),
t("vault.import.toast.failedTitle"),
);
return;
}
if (totalAffected === 0) {
toast.warning(
t("vault.import.toast.noNewHosts", { format: formatLabel }),
t("vault.import.toast.completedTitle"),
);
return;
}
if (isManaged) {
toast.success(
t("vault.import.sshConfig.managedSuccess", { count: totalAffected }),
t("vault.import.toast.completedTitle"),
);
} else {
const details = t("vault.import.toast.summary", {
count: totalAffected,
skipped,
duplicates,
});
if (hasWarnings) {
const firstIssue = result.issues[0]?.message;
toast.warning(
firstIssue ? `${details} ${t("vault.import.toast.firstIssue", { issue: firstIssue })}` : details,
t("vault.import.toast.completedTitle"),
);
} else {
toast.success(details, t("vault.import.toast.completedTitle"));
}
}
} catch (err) {
const message =
err instanceof Error ? err.message : t("common.unknownError");
toast.error(message, t("vault.import.toast.failedTitle"));
}
},
[
customGroups,
hosts,
managedSources,
onUpdateCustomGroups,
onUpdateHosts,
onUpdateManagedSources,
setIsImportOpen,
t,
],
);
return { handleImportFileSelected };
}