Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): send app locale with server requests (#787)

Kmnyb8297e693dd0
diff --git a/apps/desktop/src/main/__tests__/serverApiClient.test.ts b/apps/desktop/src/main/__tests__/serverApiClient.test.ts
index eb3ad20de2..bc3f682173 100644
--- a/apps/desktop/src/main/__tests__/serverApiClient.test.ts
+++ b/apps/desktop/src/main/__tests__/serverApiClient.test.ts
@@ -22,6 +22,9 @@ vi.mock('../authManager', () => ({
refresh: mocks.refresh,
invalidateSession: mocks.invalidateSession,
}));
+vi.mock('../i18n.js', () => ({
+ getResolvedMainLocale: () => 'zh-CN',
+}));
vi.mock('../logger', () => ({
createLogger: () => mocks.logger,
}));
@@ -66,7 +69,10 @@ describe('serverApiFetch', () => {
1,
'https://github-api.example.com/api/github/issues',
expect.objectContaining({
- headers: expect.objectContaining({ Authorization: 'Bearer token-a' }),
+ headers: expect.objectContaining({
+ 'Accept-Language': 'zh-CN',
+ Authorization: 'Bearer token-a',
+ }),
body: JSON.stringify({ userName: 'Account A' }),
}),
);
@@ -74,7 +80,10 @@ describe('serverApiFetch', () => {
2,
'https://github-api.example.com/api/github/issues',
expect.objectContaining({
- headers: expect.objectContaining({ Authorization: 'Bearer token-b' }),
+ headers: expect.objectContaining({
+ 'Accept-Language': 'zh-CN',
+ Authorization: 'Bearer token-b',
+ }),
body: JSON.stringify({ userName: 'Account B' }),
}),
);
diff --git a/apps/desktop/src/main/serverApiClient.ts b/apps/desktop/src/main/serverApiClient.ts
index 7849916b5e..19424ee785 100644
--- a/apps/desktop/src/main/serverApiClient.ts
+++ b/apps/desktop/src/main/serverApiClient.ts
@@ -11,6 +11,7 @@
import { net } from 'electron';
import * as authManager from './authManager';
+import { getResolvedMainLocale } from './i18n.js';
import { createLogger } from './logger';
@@ -69,6 +70,7 @@ async function rawFetch<T>(apiPath: string, opts: ApiFetchOptions): Promise<RawR
const method = opts.method ?? 'GET';
const headers: Record<string, string> = {
'Content-Type': 'application/json',
+ 'Accept-Language': getResolvedMainLocale(),
...(opts.headers ?? {}),
};
const token = opts.token !== undefined ? opts.token : authManager.getAccessToken();
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
index 6db962585c..0a9d93c359 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
@@ -39,6 +39,7 @@ import { cn } from '@/lib/utils';
import { Switch } from '@/components/ui/switch';
import { getLastWorkingDir, subscribeToLastWorkingDir } from '@/state/lastWorkingDir';
import { findSplitChildByPanelKind } from '../../../shared/layoutTree';
+import { resolveSystemLocale } from '../../../shared/locale';
import {
diffGhostPermissionItems,
ghostPanelKind,
@@ -78,6 +79,7 @@ import {
import { pluginMarketErrorKey } from './lib/pluginMarketErrorKey';
import { usePluginIconRefresh } from './lib/usePluginIconRefresh';
import { usePluginMarketForegroundRefresh } from './lib/usePluginMarketForegroundRefresh';
+import { usePluginMarketLocaleRefresh } from './lib/usePluginMarketLocaleRefresh';
import './plugin-motion.css';
const MAX_VISIBLE_INSTALLED_GHOSTS = 5;
@@ -105,7 +107,8 @@ const PRESENTATION_FILTERS: readonly PluginPresentationFilter[] = [
* interaction shape, while every displayed field comes from InstalledGhost.
*/
export function GhostPluginPage() {
- const { t } = useTranslation();
+ const { i18n, t } = useTranslation();
+ const marketLocale = resolveSystemLocale(i18n.resolvedLanguage ?? i18n.language);
const navigate = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
const { confirm, confirmWithCheckbox } = useConfirmDialog();
@@ -691,6 +694,14 @@ export function GhostPluginPage() {
if (requestId === marketDetailRequestRef.current) throw error;
}
}, []);
+ usePluginMarketLocaleRefresh(
+ marketLocale,
+ async () => {
+ await window.electronAPI.setApplicationMenuLocale(marketLocale);
+ },
+ () => refreshMarket(true),
+ marketDetail?.pluginId ? () => refreshVisibleMarketDetail(marketDetail.pluginId) : undefined,
+ );
const visibleMarketIcons = useMemo(
() => [...marketItems.map((item) => item.icon), marketDetail?.icon],
[marketDetail?.icon, marketItems],
diff --git a/apps/desktop/src/renderer/features/plugin/lib/__tests__/usePluginMarketLocaleRefresh.test.tsx b/apps/desktop/src/renderer/features/plugin/lib/__tests__/usePluginMarketLocaleRefresh.test.tsx
new file mode 100644
index 0000000000..db7e068280
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/lib/__tests__/usePluginMarketLocaleRefresh.test.tsx
@@ -0,0 +1,108 @@
+/**
+ * Regression coverage for locale-sensitive market refreshes.
+ * @vitest-environment jsdom
+ */
+
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { usePluginMarketLocaleRefresh } from '../usePluginMarketLocaleRefresh';
+
+describe('usePluginMarketLocaleRefresh', () => {
+ it('waits for the initial main-locale sync before correcting the market load', async () => {
+ let finishSync: (() => void) | undefined;
+ const syncLocale = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ finishSync = resolve;
+ }),
+ );
+ const refreshMarket = vi.fn();
+ const refreshDetail = vi.fn();
+
+ renderHook(
+ ({ locale }) =>
+ usePluginMarketLocaleRefresh(locale, syncLocale, refreshMarket, refreshDetail),
+ {
+ initialProps: { locale: 'en' },
+ },
+ );
+
+ await waitFor(() => {
+ expect(syncLocale).toHaveBeenCalledWith('en');
+ });
+ expect(refreshMarket).not.toHaveBeenCalled();
+ expect(refreshDetail).not.toHaveBeenCalled();
+
+ await act(async () => {
+ finishSync?.();
+ });
+
+ await waitFor(() => {
+ expect(refreshMarket).toHaveBeenCalledTimes(1);
+ expect(refreshDetail).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ it('waits for main to accept a changed locale before refreshing market data', async () => {
+ const syncLocale = vi.fn().mockResolvedValue(undefined);
+ const refreshMarket = vi.fn();
+ const refreshDetail = vi.fn();
+ const { rerender } = renderHook(
+ ({ locale }) =>
+ usePluginMarketLocaleRefresh(locale, syncLocale, refreshMarket, refreshDetail),
+ { initialProps: { locale: 'en' } },
+ );
+
+ await waitFor(() => {
+ expect(refreshMarket).toHaveBeenCalledTimes(1);
+ expect(refreshDetail).toHaveBeenCalledTimes(1);
+ });
+ syncLocale.mockClear();
+ refreshMarket.mockClear();
+ refreshDetail.mockClear();
+
+ await act(async () => {
+ rerender({ locale: 'zh-CN' });
+ });
+
+ await waitFor(() => {
+ expect(syncLocale).toHaveBeenCalledWith('zh-CN');
+ expect(refreshMarket).toHaveBeenCalledTimes(1);
+ expect(refreshDetail).toHaveBeenCalledTimes(1);
+ });
+ expect(syncLocale.mock.invocationCallOrder[0]).toBeLessThan(
+ refreshMarket.mock.invocationCallOrder[0],
+ );
+ expect(syncLocale.mock.invocationCallOrder[0]).toBeLessThan(
+ refreshDetail.mock.invocationCallOrder[0],
+ );
+ });
+
+ it('swallows refresh failures from either market request', async () => {
+ const syncLocale = vi.fn().mockResolvedValue(undefined);
+ const refreshMarket = vi.fn().mockRejectedValue(new Error('market unavailable'));
+ const refreshDetail = vi.fn().mockRejectedValue(new Error('detail unavailable'));
+ const { rerender } = renderHook(
+ ({ locale }) =>
+ usePluginMarketLocaleRefresh(locale, syncLocale, refreshMarket, refreshDetail),
+ { initialProps: { locale: 'en' } },
+ );
+
+ await waitFor(() => {
+ expect(refreshMarket).toHaveBeenCalledTimes(1);
+ expect(refreshDetail).toHaveBeenCalledTimes(1);
+ });
+ refreshMarket.mockClear();
+ refreshDetail.mockClear();
+
+ await act(async () => {
+ rerender({ locale: 'ja' });
+ });
+
+ await waitFor(() => {
+ expect(refreshMarket).toHaveBeenCalledTimes(1);
+ expect(refreshDetail).toHaveBeenCalledTimes(1);
+ });
+ });
+});
diff --git a/apps/desktop/src/renderer/features/plugin/lib/usePluginMarketLocaleRefresh.ts b/apps/desktop/src/renderer/features/plugin/lib/usePluginMarketLocaleRefresh.ts
new file mode 100644
index 0000000000..b43c8f0e94
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/lib/usePluginMarketLocaleRefresh.ts
@@ -0,0 +1,49 @@
+import { useEffect, useRef } from 'react';
+
+type Refresh = () => void | Promise<void>;
+type SyncLocale = (locale: string) => void | Promise<void>;
+
+/**
+ * Re-fetches locale-sensitive market data after main confirms the host locale.
+ *
+ * Main initially falls back to the OS locale until Renderer synchronizes the
+ * stored preference. The mount-time refresh is therefore intentional: it
+ * corrects any catalog request that raced ahead of that first synchronization.
+ */
+export function usePluginMarketLocaleRefresh(
+ locale: string | undefined,
+ syncLocale: SyncLocale,
+ refreshMarket: Refresh,
+ refreshDetail?: Refresh,
+): void {
+ const syncLocaleRef = useRef(syncLocale);
+ const refreshMarketRef = useRef(refreshMarket);
+ const refreshDetailRef = useRef(refreshDetail);
+ syncLocaleRef.current = syncLocale;
+ refreshMarketRef.current = refreshMarket;
+ refreshDetailRef.current = refreshDetail;
+
+ useEffect(() => {
+ if (!locale) return;
+ let cancelled = false;
+
+ void Promise.resolve()
+ .then(() => syncLocaleRef.current(locale))
+ .then(() => {
+ if (cancelled) return;
+ const refreshes: Promise<void>[] = [
+ Promise.resolve().then(() => refreshMarketRef.current()),
+ ];
+ const refreshDetail = refreshDetailRef.current;
+ if (refreshDetail) {
+ refreshes.push(Promise.resolve().then(() => refreshDetail()));
+ }
+ return Promise.allSettled(refreshes);
+ })
+ .catch(() => undefined);
+
+ return () => {
+ cancelled = true;
+ };
+ }, [locale]);
+}