Compare commits

...
Author SHA1 Message Date
Cursor Agentand陈大猫 078e616ad9 feat(autocomplete): show zh-CN descriptions for common commands
Overlay bundled Fig description strings when the UI locale is zh-CN.
Cached specs stay in English, and missing entries fall back to the original text.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>
2026-10-20 03:04:19 +00:00
7 changed files with 4917 additions and 2 deletions

No files matched your search

+4 -1
View File
@@ -7,6 +7,7 @@ import {
type AutocompleteSettings,
} from "./autocomplete";
import type { Snippet } from "../../domain/models";
import { useI18n } from "../../application/i18n/I18nProvider";
import { usePaneVisible } from "./paneVisibilityStore";
import { getWindowPluginTerminalProviderRegistry } from "../../application/state/pluginTerminalProviderRegistry";
import { provideTerminalCompletions } from "./autocomplete/terminalCompletionProviders";
@@ -95,6 +96,7 @@ export function TerminalAutocomplete({
// flow through (and re-render) the TerminalView ctx. Popup / standalone
// Terminal mounts never publish the store — fall back to the isVisible prop
// (same contract as hibernate).
const { resolvedLocale } = useI18n();
const visible = usePaneVisible(sessionId, isVisible);
const provideCompletions = useCallback(async (
input: string,
@@ -131,8 +133,9 @@ export function TerminalAutocomplete({
historyScope: options.historyScope ?? settings?.historyScope,
signal: options.signal,
onLatePathSuggestions: options.onLatePathSuggestions,
locale: resolvedLocale,
});
}, [allowHostStyleGreaterThanPrompt, hostGroup, hostId, hostOs, isPluginCompletionProviderAvailable, protocol, sensitiveInputActiveRef, sessionId, settings?.historyScope, status, workspaceId]);
}, [allowHostStyleGreaterThanPrompt, hostGroup, hostId, hostOs, isPluginCompletionProviderAvailable, protocol, resolvedLocale, sensitiveInputActiveRef, sessionId, settings?.historyScope, status, workspaceId]);
const autocomplete = useTerminalAutocomplete({
termRef,
containerRef,
@@ -0,0 +1,45 @@
/**
* zh-CN overlay for bundled Fig autocomplete descriptions.
* The dictionary is keyed by the exact English description string.
* Spec objects stay in English; only suggestion copies shown in the popup change.
*/
type DescriptionDictionary = Record<string, string>;
let dictionaryPromise: Promise<DescriptionDictionary> | undefined;
function loadZhCnDescriptions(): Promise<DescriptionDictionary> {
dictionaryPromise ??= import("./descriptions.zh-CN.json").then((mod) => {
const loaded = mod as { default?: DescriptionDictionary };
return loaded.default ?? (mod as unknown as DescriptionDictionary);
});
return dictionaryPromise;
}
/**
* Copy spec-backed suggestions so a zh-CN description overlay cannot leak into
* the cached spec or into a later query in another locale.
*/
export async function localizeSpecSuggestionDescriptions<T extends { description?: string }>(
suggestions: readonly T[],
locale: string | undefined,
): Promise<readonly T[]> {
if (locale !== "zh-CN" || suggestions.length === 0) return suggestions;
let dictionary: DescriptionDictionary;
try {
dictionary = await loadZhCnDescriptions();
} catch {
return suggestions;
}
let changed = false;
const localized = suggestions.map((suggestion) => {
const description = suggestion.description;
if (!description) return suggestion;
const translated = dictionary[description];
if (!translated) return suggestion;
changed = true;
return { ...suggestion, description: translated };
});
return changed ? localized : suggestions;
}
@@ -31,6 +31,7 @@ import {
resolvePathComponents,
} from "./remotePathCompleter";
import { getSnippetSuggestions } from "./snippetCompleter";
import { localizeSpecSuggestionDescriptions } from "./autocompleteDescriptionI18n";
import type { AutocompleteHistoryScope, Snippet } from "../../../domain/models";
import type { AutocompleteCwdSource } from "./terminalAutocompleteLayout";
@@ -272,6 +273,11 @@ export async function getCompletions(
* the shared directory cache for a later keystroke.
*/
onLatePathSuggestions?: (suggestions: CompletionSuggestion[]) => void;
/**
* UI locale. zh-CN overlays bundled spec descriptions; any other locale
* keeps the original English text. Cached specs are not rewritten.
*/
locale?: string;
} = {},
): Promise<CompletionSuggestion[]> {
const { hostId, maxResults = 15, historyScope = "host" } = options;
@@ -368,7 +374,11 @@ export async function getCompletions(
)
: [];
for (const suggestion of specResult.suggestions) {
const specSuggestions = await localizeSpecSuggestionDescriptions(
specResult.suggestions,
options.locale,
);
for (const suggestion of specSuggestions) {
suggestions.push(suggestion);
seenSuggestionTexts.add(suggestion.text);
}
File diff suppressed because it is too large. Load diff
@@ -29,6 +29,8 @@ export interface TerminalCompletionProviderRequest {
* soft budget (cache-bypassed relative SSH cwd).
*/
onLatePathSuggestions?: (suggestions: CompletionSuggestion[]) => void;
/** UI locale forwarded to built-in spec description overlay. */
locale?: string;
}
const DEFAULT_PLUGIN_COMPLETION_RESPONSE_TIMEOUT_MS = 800;
@@ -74,6 +76,7 @@ export async function provideTerminalCompletions(
snippets: request.snippets,
historyScope: request.historyScope,
onLatePathSuggestions: request.onLatePathSuggestions,
locale: request.locale,
});
const pluginRequestController = new AbortController();
const abortPluginRequest = () => pluginRequestController.abort();
@@ -0,0 +1,75 @@
import test from "node:test";
import assert from "node:assert/strict";
import type { FigSpec } from "./autocomplete/figSpecLoader.ts";
const SINCE = "Show logs since timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)";
const SINCE_ZH = "从指定时间起显示日志(例如 2013-01-02T13:23:37Z),也可用相对时间(例如 42m 表示 42 分钟)";
const UNTRANSLATED = "This autocomplete description is intentionally untranslated.";
const dockerSpec: FigSpec = {
name: "docker",
subcommands: [
{
name: "logs",
options: [
{ name: "--since", description: SINCE },
{ name: "--mystery", description: UNTRANSLATED },
],
},
],
};
Object.defineProperty(globalThis, "localStorage", {
value: {
getItem: () => null,
setItem: () => {},
removeItem: () => {},
clear: () => {},
},
configurable: true,
});
Object.defineProperty(globalThis, "window", {
value: {
netcatty: {
listFigSpecs: async () => ["docker"],
loadFigSpec: async (commandName: string) => commandName === "docker" ? dockerSpec : null,
},
},
configurable: true,
});
const { getCompletions } = await import("./autocomplete/completionEngine.ts");
function sinceSuggestion(suggestions: Awaited<ReturnType<typeof getCompletions>>) {
return suggestions.find((suggestion) => suggestion.displayText === "--since");
}
test("zh-CN translates docker logs --since and falls back for unknown descriptions", async () => {
const suggestions = await getCompletions("docker logs --", {
locale: "zh-CN",
skipPathCompletion: true,
maxResults: 20,
});
const since = sinceSuggestion(suggestions);
const mystery = suggestions.find((suggestion) => suggestion.displayText === "--mystery");
assert.equal(since?.displayText, "--since");
assert.equal(since?.description, SINCE_ZH);
assert.equal(mystery?.description, UNTRANSLATED);
assert.equal(dockerSpec.subcommands?.[0].options?.[0].description, SINCE);
});
test("en locale leaves autocomplete descriptions unchanged", async () => {
const suggestions = await getCompletions("docker logs --", {
locale: "en",
skipPathCompletion: true,
maxResults: 20,
});
const since = sinceSuggestion(suggestions);
assert.equal(since?.displayText, "--since");
assert.equal(since?.description, SINCE);
assert.equal(dockerSpec.subcommands?.[0].options?.[0].description, SINCE);
});
@@ -0,0 +1,136 @@
/**
* List description strings for the common-command autocomplete overlay that
* have no zh-CN entry. Maintenance aid for @withfig/autocomplete updates.
* Not a CI check: always exits 0.
*
* Usage: node scripts/list-untranslated-autocomplete-descriptions.mjs
*
* Local specs in electron/specs win over the bundled Fig file, matching
* electron/main/registerBridges.cjs. `docker compose` descriptions come from
* the docker spec; docker-compose.js covers the standalone command.
*/
import fs from "node:fs";
import path from "node:path";
import { pathToFileURL, fileURLToPath } from "node:url";
const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const dictionaryPath = path.join(
rootDir,
"components/terminal/autocomplete/descriptions.zh-CN.json",
);
/** Commands covered by the zh-CN description overlay. */
const COVERED_COMMANDS = [
"git",
"docker",
"docker-compose",
"kubectl",
"npm",
"pnpm",
"yarn",
"pip",
"pip3",
"systemctl",
"journalctl",
"ls",
"cd",
"cp",
"mv",
"rm",
"mkdir",
"chmod",
"chown",
"tar",
"ssh",
"scp",
"rsync",
"curl",
"wget",
"grep",
"find",
"ps",
"kill",
"top",
"apt",
"yum",
"dnf",
"brew",
"sudo",
"cat",
"tail",
"head",
"less",
"df",
"du",
"ip",
"ping",
"netstat",
"ss",
];
function collectDescriptions(node, out, seen) {
if (!node || typeof node !== "object") return;
if (seen.has(node)) return;
seen.add(node);
if (typeof node.description === "string" && node.description.trim()) {
out.add(node.description);
}
for (const value of Object.values(node)) {
if (Array.isArray(value)) {
for (const item of value) collectDescriptions(item, out, seen);
} else if (value && typeof value === "object") {
collectDescriptions(value, out, seen);
}
}
}
function resolveSpecFile(commandName) {
const localFile = path.join(rootDir, "electron/specs", `${commandName}.js`);
if (fs.existsSync(localFile)) return localFile;
const figFile = path.join(
rootDir,
"node_modules/@withfig/autocomplete/build",
`${commandName}.js`,
);
if (fs.existsSync(figFile)) return figFile;
return null;
}
const dictionary = fs.existsSync(dictionaryPath)
? JSON.parse(fs.readFileSync(dictionaryPath, "utf8"))
: {};
const missing = [];
const missingSpecs = [];
for (const commandName of COVERED_COMMANDS) {
const specFile = resolveSpecFile(commandName);
if (!specFile) {
missingSpecs.push(commandName);
continue;
}
const mod = await import(pathToFileURL(specFile).href);
const raw = mod.default?.default ?? mod.default ?? null;
if (!raw) {
missingSpecs.push(commandName);
continue;
}
const spec = JSON.parse(JSON.stringify(raw));
const descriptions = new Set();
collectDescriptions(spec, descriptions, new WeakSet());
for (const description of descriptions) {
if (typeof dictionary[description] !== "string" || dictionary[description].length === 0) {
missing.push({ commandName, description });
}
}
}
if (missingSpecs.length > 0) {
console.log(`NO_SPEC ${missingSpecs.join(" ")}`);
}
const seen = new Set();
for (const entry of missing) {
if (seen.has(entry.description)) continue;
seen.add(entry.description);
console.log(`MISSING ${entry.commandName} ${JSON.stringify(entry.description)}`);
}
console.log(`Untranslated description strings: ${seen.size}`);