Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 支持四语更新公告 (#1935)
guyong-zapof568fcaa0582
diff --git a/apps/desktop/src/main/__tests__/releaseNotesService.test.ts b/apps/desktop/src/main/__tests__/releaseNotesService.test.tsindex 65740889b9..f04d64c165 100644--- a/apps/desktop/src/main/__tests__/releaseNotesService.test.ts+++ b/apps/desktop/src/main/__tests__/releaseNotesService.test.ts@@ -108,6 +108,82 @@ describe('releaseNotesService', () => {expect(requestMock).toHaveBeenCalledTimes(2);});+ it('只有 contentByLocale 的多语言 payload 可加载并继续按 version 缓存', async () => {+ const request = new MockRequest();+ const response = new MockResponse();+ requestMock.mockReturnValueOnce(request);++ const { fetchReleaseNotes } = await import('../releaseNotesService');+ const first = fetchReleaseNotes('0.1.23');+ request.emit('response', response);+ response.emit('data', Buffer.from(JSON.stringify({+ version: '0.1.23',+ date: '2026-08-06',+ githash: '0123456789abcdef0123456789abcdef01234567',+ contentByLocale: {+ en: {+ topics: [{ id: 'voice-input', title: 'Voice input', text: 'More reliable.' }],+ },+ },+ }), 'utf8'));+ response.emit('end');++ const notes = await first;+ expect(notes?.contentByLocale?.en?.topics?.[0]?.id).toBe('voice-input');+ expect(await fetchReleaseNotes('0.1.23')).toBe(notes);+ expect(requestMock).toHaveBeenCalledTimes(1);+ });++ it('同一 version 的并发请求复用同一个在途 CDN 请求', async () => {+ const request = new MockRequest();+ const response = new MockResponse();+ requestMock.mockReturnValueOnce(request);++ const { fetchReleaseNotes } = await import('../releaseNotesService');+ const first = fetchReleaseNotes('0.1.25');+ const second = fetchReleaseNotes('0.1.25');++ expect(requestMock).toHaveBeenCalledTimes(1);+ request.emit('response', response);+ response.emit('data', Buffer.from(JSON.stringify({+ version: '0.1.25',+ date: '2026-08-06',+ topics: [{ title: '并发缓存', text: '只请求一次。' }],+ }), 'utf8'));+ response.emit('end');++ const [firstResult, secondResult] = await Promise.all([first, second]);+ expect(firstResult).toBe(secondResult);+ expect(requestMock).toHaveBeenCalledTimes(1);+ });++ it('localized 内容全部为空或畸形时按失败处理且不缓存', async () => {+ const { fetchReleaseNotes } = await import('../releaseNotesService');+ const payload = JSON.stringify({+ version: '0.1.24',+ date: '2026-08-06',+ contentByLocale: {+ 'zh-CN': { topics: [{ title: ' ', text: '' }] },+ en: { topics: [] },+ },+ });++ const fetchOnce = async () => {+ const request = new MockRequest();+ const response = new MockResponse();+ requestMock.mockReturnValueOnce(request);+ const promise = fetchReleaseNotes('0.1.24');+ request.emit('response', response);+ response.emit('data', Buffer.from(payload, 'utf8'));+ response.emit('end');+ return promise;+ };++ expect(await fetchOnce()).toBeNull();+ expect(await fetchOnce()).toBeNull();+ expect(requestMock).toHaveBeenCalledTimes(2);+ });+it('sections 非空但全部畸形(无任何有效 bullet)同样按失败处理不缓存', async () => {const { fetchReleaseNotes } = await import('../releaseNotesService');diff --git a/apps/desktop/src/main/releaseNotesService.ts b/apps/desktop/src/main/releaseNotesService.tsindex c745654638..a8df0b6426 100644--- a/apps/desktop/src/main/releaseNotesService.ts+++ b/apps/desktop/src/main/releaseNotesService.ts@@ -29,7 +29,10 @@ import { StringDecoder } from 'node:string_decoder';import { net } from 'electron';-import { hasRenderableContent } from '../shared/releaseNotesContent';+import {+ hasRenderableContent,+ type RawReleaseNotes,+} from '../shared/releaseNotesContent';import { getBaseUrl, getPlatformKey } from './manifestService';@@ -39,48 +42,6 @@ const log = createLogger('releaseNotesService');// ── Types ──────────────────────────────────────────────────────────────────-/** Author-grouped item: one block per contributor, with their bullets. */-export interface RawItem {- name: string;- list: string[];-}--export interface RawSection {- title: string;- items: RawItem[];-}--/** Topic-format (v2) block: one user-facing theme with a short narrative. */-export interface RawTopic {- emoji?: string;- title: string;- text: string;- contributors?: string[];-}--export interface RawReleaseNotes {- version: string;- date: string;- /**- * Full main-HEAD commit hash captured when the notice was generated.- * Bookkeeping only — nothing in this service (or the renderer) reads it; it- * exists so a later release can recover the previous version's anchor commit.- * Optional because older notice files predate the field.- */- githash?: string;- /**- * Flat contributor list — collective hall-of-fame on top of per-item `by`.- * Optional: older notice files predate the field (renderer defaults to []).- */- contributors?: string[];- /** Legacy author-grouped sections. Absent on topic-format payloads. */- sections?: RawSection[];- /** Topic-format blocks. Non-empty ⇒ renderer uses the topic layout. */- topics?: RawTopic[];- /** Optional one-line lead above the topics (e.g. PR/commit counts). */- intro?: string;-}-// ── Constants ──────────────────────────────────────────────────────────────const REQUEST_TIMEOUT_MS = 15_000;@@ -88,6 +49,7 @@ const REQUEST_TIMEOUT_MS = 15_000;// ── State ──────────────────────────────────────────────────────────────────const cache = new Map<string, RawReleaseNotes>();+const inFlight = new Map<string, Promise<RawReleaseNotes | null>>();// Sorted ascending list of every version that has a notice JSON on the CDN// for this platform. Cached on success only — a failed fetch falls through so@@ -181,22 +143,34 @@ export async function fetchReleaseNotes(version: string): Promise<RawReleaseNoteconst hit = cache.get(version);if (hit) return hit;- const platform = getPlatformKey();- // Cache-bust to dodge stale CDN edges- const url = `${getBaseUrl()}/notice/${platform}/${version}.json?t=${Date.now()}`;- const json = await fetchCdnJson<RawReleaseNotes>(url);- if (!json) return null;- // A 200 payload with nothing renderable (e.g. a v2 document whose topics- // are all malformed) is treated as a failed fetch and NOT cached — the- // process-lifetime cache would otherwise keep serving the bad document- // even after the CDN is corrected, and the renderer would reject it anyway.- if (!hasRenderableContent(json)) {- log.warn('Payload has no renderable content, treating as failure: version=%s', version);- return null;+ const pending = inFlight.get(version);+ if (pending) return pending;++ const request = (async () => {+ const platform = getPlatformKey();+ // Cache-bust to dodge stale CDN edges+ const url = `${getBaseUrl()}/notice/${platform}/${version}.json?t=${Date.now()}`;+ const json = await fetchCdnJson<RawReleaseNotes>(url);+ if (!json) return null;+ // A 200 payload with nothing renderable (e.g. a v2 document whose topics+ // are all malformed) is treated as a failed fetch and NOT cached — the+ // process-lifetime cache would otherwise keep serving the bad document+ // even after the CDN is corrected, and the renderer would reject it anyway.+ if (!hasRenderableContent(json)) {+ log.warn('Payload has no renderable content, treating as failure: version=%s', version);+ return null;+ }+ cache.set(version, json);+ log.info('Fetched OK: version=%s, sections=%d', json.version, json.sections?.length ?? 0);+ return json;+ })();+ inFlight.set(version, request);++ try {+ return await request;+ } finally {+ if (inFlight.get(version) === request) inFlight.delete(version);}- cache.set(version, json);- log.info('Fetched OK: version=%s, sections=%d', json.version, json.sections?.length ?? 0);- return json;}/**diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 90372940ff..4ccdaaa51b 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -64,6 +64,7 @@ import type {} from '../shared/local-themes';import type { LocalThemeImportResult } from '../shared/theme-import/types';import { DEFAULT_LOCALE, SUPPORTED_LOCALES, type SupportedLocale } from '../shared/locale';+import type { RawReleaseNotes } from '../shared/releaseNotesContent';import {MODEL_ACCESS_STATUS_CHANNEL,type ModelAccessStatus as ModelAccessStatusPayload,@@ -3643,7 +3644,7 @@ contextBridge.exposeInMainWorld('electronAPI', {// Platform is resolved in main via getPlatformKey() to keep the CDN path// axis identical to the hot-update manifest.// Returns null on 404 / network / parse error — caller decides UX.- fetchReleaseNotes: (version: string): Promise<RawReleaseNotesPayload | null> =>+ fetchReleaseNotes: (version: string): Promise<RawReleaseNotes | null> =>ipcRenderer.invoke('release-notes:fetch', version),// Sorted ascending list of every version with a notice on the CDN. Rendererdiff --git a/apps/desktop/src/renderer/__tests__/releaseNotesNormalize.test.ts b/apps/desktop/src/renderer/__tests__/releaseNotesNormalize.test.tsindex 046a0ec595..35dfc16bdc 100644--- a/apps/desktop/src/renderer/__tests__/releaseNotesNormalize.test.ts+++ b/apps/desktop/src/renderer/__tests__/releaseNotesNormalize.test.ts@@ -72,6 +72,155 @@ describe('release-notes normalization', () => {]);});+ it('同一版本按 zh-CN/en/ja/ko 选择对应内容,raw payload 只请求一次', async () => {+ const fetchReleaseNotes = stubFetch({+ version: '0.1.23',+ date: '2026-08-06',+ contributors: ['Lizi'],+ topics: [{ id: 'voice', title: '顶层中文', text: '兼容正文。' }],+ contentByLocale: Object.fromEntries(+ ['zh-CN', 'en', 'ja', 'ko'].map((locale) => [+ locale,+ {+ intro: `intro-${locale}`,+ topics: [{+ id: 'voice',+ emoji: '🎙️',+ title: `title-${locale}`,+ text: `text-${locale}`,+ contributors: ['Lizi'],+ }],+ },+ ]),+ ),+ });+ const mod = await import('@/release-notes');++ for (const locale of ['zh-CN', 'en', 'ja', 'ko'] as const) {+ const notes = await mod.fetchReleaseNotes('0.1.23', locale);+ expect(notes?.intro).toBe(`intro-${locale}`);+ expect(notes?.topics[0]).toMatchObject({+ id: 'voice',+ title: `title-${locale}`,+ text: `text-${locale}`,+ });+ }+ expect(fetchReleaseNotes).toHaveBeenCalledTimes(1);+ });++ it('同一版本并发选择不同语言时也只跨 IPC 请求一次 raw payload', async () => {+ let resolveRaw!: (value: unknown) => void;+ const rawPromise = new Promise<unknown>((resolve) => { resolveRaw = resolve; });+ const fetchReleaseNotes = vi.fn(() => rawPromise);+ vi.stubGlobal('window', { electronAPI: { fetchReleaseNotes } });+ const mod = await import('@/release-notes');++ const english = mod.fetchReleaseNotes('0.1.28', 'en');+ const japanese = mod.fetchReleaseNotes('0.1.28', 'ja');+ expect(fetchReleaseNotes).toHaveBeenCalledTimes(1);++ resolveRaw({+ version: '0.1.28',+ date: '2026-08-06',+ contentByLocale: {+ en: { topics: [{ id: 'same', title: 'English', text: 'English text.' }] },+ ja: { topics: [{ id: 'same', title: '日本語', text: '日本語本文。' }] },+ },+ });++ await expect(english).resolves.toMatchObject({ topics: [{ title: 'English' }] });+ await expect(japanese).resolves.toMatchObject({ topics: [{ title: '日本語' }] });+ expect(fetchReleaseNotes).toHaveBeenCalledTimes(1);+ });++ it('指定语言缺失或畸形时按 en → zh-CN → 顶层旧格式回退', async () => {+ stubFetch({+ version: '0.1.24',+ date: '2026-08-06',+ topics: [{ title: '顶层中文', text: 'legacy-root' }],+ contentByLocale: {+ 'zh-CN': { topics: [{ title: '本地中文', text: 'localized-zh' }] },+ en: { topics: [{ title: 'English', text: 'localized-en' }] },+ ja: { topics: [{ title: ' ', text: '' }] },+ },+ });+ const mod = await import('@/release-notes');++ expect((await mod.fetchReleaseNotes('0.1.24', 'ja'))?.topics[0]?.text)+ .toBe('localized-en');+ expect((await mod.fetchReleaseNotes('0.1.24', 'ko'))?.topics[0]?.text)+ .toBe('localized-en');+ expect((await mod.fetchReleaseNotes('0.1.24', 'zh-CN'))?.topics[0]?.text)+ .toBe('localized-zh');+ });++ it('localized block 为 null 或非对象时按缺失处理并继续 fallback', async () => {+ const fetchReleaseNotes = stubFetch({+ version: '0.1.29',+ date: '2026-08-06',+ contentByLocale: {+ en: { topics: [{ title: 'English', text: 'localized-en' }] },+ ja: null,+ ko: 'not-an-object',+ },+ });+ const mod = await import('@/release-notes');++ expect((await mod.fetchReleaseNotes('0.1.29', 'ja'))?.topics[0]?.text)+ .toBe('localized-en');+ expect((await mod.fetchReleaseNotes('0.1.29', 'ko'))?.topics[0]?.text)+ .toBe('localized-en');+ expect(fetchReleaseNotes).toHaveBeenCalledTimes(1);+ });++ it('英文缺失时回退中文,中文 localized 缺失时直接回退顶层中文', async () => {+ stubFetch({+ version: '0.1.25',+ date: '2026-08-06',+ topics: [{ title: '顶层中文', text: 'legacy-root' }],+ contentByLocale: {+ 'zh-CN': { topics: [{ title: '本地中文', text: 'localized-zh' }] },+ },+ });+ const mod = await import('@/release-notes');++ expect((await mod.fetchReleaseNotes('0.1.25', 'ko'))?.topics[0]?.text)+ .toBe('localized-zh');++ vi.resetModules();+ stubFetch({+ version: '0.1.26',+ date: '2026-08-06',+ topics: [{ title: '顶层中文', text: 'legacy-root' }],+ contentByLocale: {+ en: { topics: [{ title: 'English', text: 'localized-en' }] },+ },+ });+ const zhMod = await import('@/release-notes');+ expect((await zhMod.fetchReleaseNotes('0.1.26', 'zh-CN'))?.topics[0]?.text)+ .toBe('legacy-root');+ });++ it('localized legacy sections 也能被选择和归一化', async () => {+ stubFetch({+ version: '0.1.27',+ date: '2026-08-06',+ contentByLocale: {+ ja: {+ sections: [{+ title: 'Bug Fixes',+ items: [{ name: 'A', list: ['修正しました'] }],+ }],+ },+ },+ });+ const mod = await import('@/release-notes');+ const notes = await mod.fetchReleaseNotes('0.1.27', 'ja');+ expect(notes?.sections).toEqual([+ { title: 'Bug Fixes', items: [{ text: '修正しました', by: 'A' }] },+ ]);+ });+it('畸形 topic 条目被丢弃,合法条目补默认值', async () => {stubFetch({version: '0.1.19',diff --git a/apps/desktop/src/renderer/__tests__/updateBannerRelaunchEntry.test.tsx b/apps/desktop/src/renderer/__tests__/updateBannerRelaunchEntry.test.tsxindex 11f5a251ea..1c7817466b 100644--- a/apps/desktop/src/renderer/__tests__/updateBannerRelaunchEntry.test.tsx+++ b/apps/desktop/src/renderer/__tests__/updateBannerRelaunchEntry.test.tsx@@ -41,6 +41,10 @@ vi.mock('react-i18next', () => ({}),}));+vi.mock('@/hooks/useLocale', () => ({+ useLocale: () => ({ locale: 'en', effectiveLocale: 'en', setLocale: vi.fn() }),+}));+vi.mock('@/hooks/useUpdateStatus', () => ({useUpdateStatus: () => updateStatus.current,}));diff --git a/apps/desktop/src/renderer/__tests__/updateBannerReleaseNotesLink.test.tsx b/apps/desktop/src/renderer/__tests__/updateBannerReleaseNotesLink.test.tsxindex 129cb091f3..94b872a09f 100644--- a/apps/desktop/src/renderer/__tests__/updateBannerReleaseNotesLink.test.tsx+++ b/apps/desktop/src/renderer/__tests__/updateBannerReleaseNotesLink.test.tsx@@ -19,6 +19,10 @@ vi.mock('react-i18next', () => ({}),}));+vi.mock('@/hooks/useLocale', () => ({+ useLocale: () => ({ locale: 'en', effectiveLocale: 'en', setLocale: vi.fn() }),+}));+const updateStatus = vi.hoisted(() => ({current: { status: 'ready', version: '1.4.2' } as {status: string;@@ -72,7 +76,7 @@ describe('UpdateBanner release-notes link', () => {render(<UpdateBanner isCollapsed={false} onOpenVersionNotice={onOpenVersionNotice} />);const link = await screen.findByText(LINK);- expect(fetchReleaseNotes).toHaveBeenCalledWith('1.4.2');+ expect(fetchReleaseNotes).toHaveBeenCalledWith('1.4.2', 'en');fireEvent.click(link);expect(onOpenVersionNotice).toHaveBeenCalledWith('1.4.2');diff --git a/apps/desktop/src/renderer/__tests__/updateNoticeDialogLayout.test.tsx b/apps/desktop/src/renderer/__tests__/updateNoticeDialogLayout.test.tsxindex 0ea66a041d..7038b53925 100644--- a/apps/desktop/src/renderer/__tests__/updateNoticeDialogLayout.test.tsx+++ b/apps/desktop/src/renderer/__tests__/updateNoticeDialogLayout.test.tsx@@ -14,7 +14,7 @@* 4. a version that is merely queued (idle) does not claim to be loading.*/-import { cleanup, render, screen, within } from '@testing-library/react';+import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react';import { afterEach, describe, expect, it, vi } from 'vitest';import '@/i18n';@@ -143,4 +143,56 @@ describe('UpdateNoticeDialog 单栏版式', () => {// 标题栏右侧在单版本 auto 下不再显示日期或版本计数。expect(screen.queryByText(i18n.t('update.notice.versionsSpan', { count: 1 }))).toBeNull();});++ it('手动历史在切换语言后原地刷新所有已加载版本,不重置滚动位置', async () => {+ await act(async () => { await i18n.changeLanguage('en'); });+ vi.stubGlobal('IntersectionObserver', class {+ private readonly callback: IntersectionObserverCallback;+ constructor(callback: IntersectionObserverCallback) {+ this.callback = callback;+ }+ observe = (target: Element) => {+ this.callback([{+ isIntersecting: true,+ target,+ boundingClientRect: { top: 0 },+ } as IntersectionObserverEntry], this as unknown as IntersectionObserver);+ };+ unobserve() {}+ disconnect() {}+ takeRecords() { return []; }+ });++ const localized = (version: string): ReleaseNotes => ({+ ...topicNotes(version, []),+ topics: [{+ title: `${i18n.language}-${version}`,+ text: '正文。',+ contributors: [],+ }],+ });+ const loadVersion = vi.fn(async (version: string) => localized(version));+ render(+ <UpdateNoticeDialog+ open+ mode="manual"+ releaseNotes={[localized('0.1.21')]}+ allVersions={['0.1.21', '0.1.20']}+ loadVersion={loadVersion}+ onDismiss={vi.fn()}+ />,+ );++ const oldLocaleTitle = await screen.findByText('en-0.1.20');+ const scrollBody = oldLocaleTitle.closest('.overflow-y-auto') as HTMLDivElement;+ scrollBody.scrollTop = 123;++ await act(async () => { await i18n.changeLanguage('ja'); });+ await waitFor(() => expect(screen.getByText('ja-0.1.20')).toBeTruthy());+ expect(screen.getByText('ja-0.1.21')).toBeTruthy();+ expect(scrollBody.scrollTop).toBe(123);++ vi.unstubAllGlobals();+ await act(async () => { await i18n.changeLanguage('en'); });+ });});diff --git a/apps/desktop/src/renderer/__tests__/useUpdateNoticeUpdatePreview.test.tsx b/apps/desktop/src/renderer/__tests__/useUpdateNoticeUpdatePreview.test.tsxindex ad0c228d59..d8396a4b57 100644--- a/apps/desktop/src/renderer/__tests__/useUpdateNoticeUpdatePreview.test.tsx+++ b/apps/desktop/src/renderer/__tests__/useUpdateNoticeUpdatePreview.test.tsx@@ -20,6 +20,15 @@ vi.mock('react-i18next', () => ({useTranslation: () => ({ t: (key: string) => key }),}));+const localeState = vi.hoisted(() => ({ current: 'en' as 'zh-CN' | 'en' | 'ja' | 'ko' }));+vi.mock('@/hooks/useLocale', () => ({+ useLocale: () => ({+ locale: localeState.current,+ effectiveLocale: localeState.current,+ setLocale: vi.fn(),+ }),+}));+const mocks = vi.hoisted(() => ({fetchReleaseNotes: vi.fn(),fetchReleaseNotesIndex: vi.fn(),@@ -35,16 +44,22 @@ vi.mock('@/lib/toast', () => ({ toast: { error: mocks.toastError } }));const STORAGE_KEY = 'xdt-maker:lastReadVersion';-function notesFor(version: string) {+function notesFor(version: string, locale = 'en') {return {version,date: '2026-07-28',contributors: [],sections: [],- topics: [{ title: `t-${version}`, text: 'x', contributors: [] }],+ topics: [{ title: `${locale}-${version}`, text: 'x', contributors: [] }],};}+function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((res) => { resolve = res; });+ return { promise, resolve };+}+/** 设定「已装版本」,并让自动弹窗路径静默(lastRead === appVersion 时 effect 直接 return)。 */function setInstalled(version: string) {(window as unknown as { electronAPI: unknown }).electronAPI = { appVersion: version };@@ -52,12 +67,14 @@ function setInstalled(version: string) {}beforeEach(() => {+ localeState.current = 'en';localStorage.clear();mocks.fetchReleaseNotes.mockReset();mocks.fetchReleaseNotesIndex.mockReset();mocks.toastError.mockReset();mocks.fetchReleaseNotesIndex.mockResolvedValue(['1.3.9', '1.4.0', '1.4.1', '1.4.2']);- mocks.fetchReleaseNotes.mockImplementation(async (v: string) => notesFor(v));+ mocks.fetchReleaseNotes.mockImplementation(async (v: string, locale: string) =>+ notesFor(v, locale));setInstalled('1.4.1');});@@ -101,7 +118,7 @@ describe('useUpdateNotice onOpenVersion — pre-install preview', () => {expect(shown).toEqual(['1.4.2', '1.4.1']);expect(shown).not.toContain('1.4.0');expect(shown).not.toContain('1.3.9');- expect(mocks.fetchReleaseNotes).not.toHaveBeenCalledWith('1.3.9');+ expect(mocks.fetchReleaseNotes).not.toHaveBeenCalledWith('1.3.9', 'en');});it('caps the aggregated range at 5 versions', async () => {@@ -121,8 +138,8 @@ describe('useUpdateNotice onOpenVersion — pre-install preview', () => {it('drops an in-between version whose notes are missing, keeps the rest', async () => {setInstalled('1.3.9');- mocks.fetchReleaseNotes.mockImplementation(async (v: string) =>- (v === '1.4.1' ? null : notesFor(v)));+ mocks.fetchReleaseNotes.mockImplementation(async (v: string, locale: string) =>+ (v === '1.4.1' ? null : notesFor(v, locale)));const { result } = renderHook(() => useUpdateNotice());act(() => { result.current.onOpenVersion('1.4.2'); });@@ -154,8 +171,8 @@ describe('useUpdateNotice onOpenVersion — pre-install preview', () => {it('stays closed and toasts when the pending version itself has no notes', async () => {setInstalled('1.3.9');- mocks.fetchReleaseNotes.mockImplementation(async (v: string) =>- (v === '1.4.2' ? null : notesFor(v)));+ mocks.fetchReleaseNotes.mockImplementation(async (v: string, locale: string) =>+ (v === '1.4.2' ? null : notesFor(v, locale)));const { result } = renderHook(() => useUpdateNotice());act(() => { result.current.onOpenVersion('1.4.2'); });@@ -210,6 +227,40 @@ describe('useUpdateNotice onOpenVersion — pre-install preview', () => {expect(localStorage.getItem(STORAGE_KEY)).toBe('1.4.1');});++ it('passes the effective locale and refreshes loaded preview notes after a language switch', async () => {+ const { result, rerender } = renderHook(() => useUpdateNotice());++ act(() => { result.current.onOpenVersion('1.4.2'); });+ await waitFor(() => expect(result.current.open).toBe(true));+ expect(mocks.fetchReleaseNotes).toHaveBeenCalledWith('1.4.2', 'en');+ expect(result.current.releaseNotes?.[0]?.topics[0]?.title).toBe('en-1.4.2');++ localeState.current = 'ja';+ rerender();+ await waitFor(() =>+ expect(result.current.releaseNotes?.[0]?.topics[0]?.title).toBe('ja-1.4.2'));+ expect(mocks.fetchReleaseNotes).toHaveBeenCalledWith('1.4.2', 'ja');+ expect(localStorage.getItem(STORAGE_KEY)).toBe('1.4.1');+ });++ it('finishes opening a preview in the new locale when language changes in flight', async () => {+ const pendingEn = deferred<ReturnType<typeof notesFor>>();+ mocks.fetchReleaseNotes.mockImplementation((version: string, locale: string) => {+ if (version === '1.4.2' && locale === 'en') return pendingEn.promise;+ return Promise.resolve(notesFor(version, locale));+ });+ const { result, rerender } = renderHook(() => useUpdateNotice());++ act(() => { result.current.onOpenVersion('1.4.2'); });+ localeState.current = 'ja';+ rerender();+ await act(async () => { pendingEn.resolve(notesFor('1.4.2', 'en')); });++ await waitFor(() => expect(result.current.open).toBe(true));+ expect(result.current.releaseNotes?.[0]?.topics[0]?.title).toBe('ja-1.4.2');+ expect(mocks.fetchReleaseNotes).toHaveBeenCalledWith('1.4.2', 'ja');+ });});describe('useUpdateNotice onOpen — flame-icon history is unchanged', () => {@@ -222,5 +273,74 @@ describe('useUpdateNotice onOpen — flame-icon history is unchanged', () => {expect(result.current.mode).toBe('manual');expect(result.current.releaseNotes?.map((n) => n.version)).toEqual(['1.4.1']);expect(result.current.allVersions).toEqual(['1.4.1', '1.4.0', '1.3.9']);+ expect(mocks.fetchReleaseNotes).toHaveBeenCalledWith('1.4.1', 'en');+ });++ it('uses the current locale for manual history lazy loads', async () => {+ localeState.current = 'ko';+ const { result } = renderHook(() => useUpdateNotice());++ act(() => { result.current.onOpen(); });+ await waitFor(() => expect(result.current.open).toBe(true));+ await act(async () => { await result.current.loadVersion('1.4.0'); });++ expect(mocks.fetchReleaseNotes).toHaveBeenCalledWith('1.4.1', 'ko');+ expect(mocks.fetchReleaseNotes).toHaveBeenCalledWith('1.4.0', 'ko');+ });++ it('finishes opening manual history in the new locale when language changes in flight', async () => {+ const appEn = deferred<ReturnType<typeof notesFor>>();+ mocks.fetchReleaseNotes.mockImplementation((version: string, locale: string) => {+ if (version === '1.4.1' && locale === 'en') return appEn.promise;+ return Promise.resolve(notesFor(version, locale));+ });+ const { result, rerender } = renderHook(() => useUpdateNotice());++ act(() => { result.current.onOpen(); });+ localeState.current = 'ko';+ rerender();+ await act(async () => { appEn.resolve(notesFor('1.4.1', 'en')); });++ await waitFor(() => expect(result.current.open).toBe(true));+ expect(result.current.mode).toBe('manual');+ expect(result.current.releaseNotes?.[0]?.topics[0]?.title).toBe('ko-1.4.1');+ expect(mocks.fetchReleaseNotes).toHaveBeenCalledWith('1.4.1', 'ko');+ });+});++describe('useUpdateNotice automatic popup', () => {+ it('loads automatic notices with the effective locale', async () => {+ (window as unknown as { electronAPI: unknown }).electronAPI = { appVersion: '1.4.2' };+ localStorage.setItem(STORAGE_KEY, '1.4.1');+ localeState.current = 'ja';++ const { result } = renderHook(() => useUpdateNotice());++ await waitFor(() => expect(result.current.open).toBe(true));+ expect(mocks.fetchReleaseNotes).toHaveBeenCalledWith('1.4.2', 'ja');+ expect(result.current.releaseNotes?.[0]?.topics[0]?.title).toBe('ja-1.4.2');+ });++ it('does not reopen an automatic notice dismissed during a locale refresh', async () => {+ (window as unknown as { electronAPI: unknown }).electronAPI = { appVersion: '1.4.2' };+ localStorage.setItem(STORAGE_KEY, '1.4.1');+ const jaRefresh = deferred<ReturnType<typeof notesFor>>();+ mocks.fetchReleaseNotes.mockImplementation((version: string, locale: string) => {+ if (locale === 'ja') return jaRefresh.promise;+ return Promise.resolve(notesFor(version, locale));+ });+ const { result, rerender } = renderHook(() => useUpdateNotice());++ await waitFor(() => expect(result.current.open).toBe(true));+ localeState.current = 'ja';+ rerender();+ act(() => { result.current.dismiss(); });+ expect(result.current.open).toBe(false);++ await act(async () => { jaRefresh.resolve(notesFor('1.4.2', 'ja')); });+ await act(async () => { await Promise.resolve(); });+ expect(result.current.open).toBe(false);+ expect(localStorage.getItem(STORAGE_KEY)).toBe('1.4.2');+ expect(mocks.fetchReleaseNotes).toHaveBeenCalledTimes(2);});});diff --git a/apps/desktop/src/renderer/components/UpdateNoticeDialog.tsx b/apps/desktop/src/renderer/components/UpdateNoticeDialog.tsxindex 3cb917d034..c3b7cbb9bc 100644--- a/apps/desktop/src/renderer/components/UpdateNoticeDialog.tsx+++ b/apps/desktop/src/renderer/components/UpdateNoticeDialog.tsx@@ -529,7 +529,10 @@ function ManualBody({}return m;});- const inFlightRef = useRef<Set<string>>(new Set());+ const inFlightRef = useRef<Map<string, number>>(new Map());+ const localeGenerationRef = useRef(0);+ const previousLocaleRef = useRef(locale);+ const notesMapRef = useRef(notesMap);// Ref mirror of stateMap so `startLoad` doesn't need it in useCallback deps.// Without this, every setStateMap → new startLoad identity → observer// useEffect re-runs → new observer immediately fires callbacks for still-@@ -537,6 +540,64 @@ function ManualBody({// again → infinite loading↔failed flicker (the bug this refactor fixes).const stateMapRef = useRef(stateMap);useEffect(() => { stateMapRef.current = stateMap; }, [stateMap]);+ useEffect(() => { notesMapRef.current = notesMap; }, [notesMap]);++ // Parent-owned seed notes change when the app locale changes. Merge them+ // into the manual body's local map instead of remounting the scroll area.+ useEffect(() => {+ if (initialLoaded.size === 0) return;+ setNotesMap((prev) => {+ const next = new Map(prev);+ for (const [version, notes] of initialLoaded) next.set(version, notes);+ notesMapRef.current = next;+ return next;+ });+ setStateMap((prev) => {+ const next = new Map(prev);+ for (const version of initialLoaded.keys()) next.set(version, 'loaded');+ stateMapRef.current = next;+ return next;+ });+ }, [initialLoaded]);++ // Refresh every already-loaded history block in place on locale changes.+ // Blocks that have never loaded stay idle and will use the new locale later.+ useEffect(() => {+ if (previousLocaleRef.current === locale) return;+ previousLocaleRef.current = locale;+ const generation = localeGenerationRef.current + 1;+ localeGenerationRef.current = generation;+ inFlightRef.current.clear();+ setStateMap((prev) => {+ const next = new Map(prev);+ for (const [version, state] of next) {+ if (state === 'loading') next.set(version, 'idle');+ }+ stateMapRef.current = next;+ return next;+ });++ const loadedVersions = [...notesMapRef.current.keys()];+ if (loadedVersions.length === 0) return;+ let cancelled = false;+ void Promise.all(loadedVersions.map((version) => loadVersion(version)))+ .then((results) => {+ if (cancelled || localeGenerationRef.current !== generation) return;+ setNotesMap((prev) => {+ const next = new Map(prev);+ results.forEach((notes, index) => {+ if (notes) next.set(loadedVersions[index], notes);+ });+ notesMapRef.current = next;+ return next;+ });+ })+ .catch(() => {+ // Keep the previous-language content visible; individual retry/loading+ // behavior remains unchanged and the next locale change can retry.+ });+ return () => { cancelled = true; };+ }, [locale, loadVersion]);const startLoad = useCallback(async (version: string) => {@@ -546,20 +607,29 @@ function ManualBody({// loading is already in flight (also guarded by inFlightRef), error is// sticky until user hits the retry button (see `retryVersion`).if (current === 'loaded' || current === 'loading' || current === 'error') return;- inFlightRef.current.add(version);+ const generation = localeGenerationRef.current;+ inFlightRef.current.set(version, generation);setStateMap((prev) => new Map(prev).set(version, 'loading'));try {const notes = await loadVersion(version);+ if (localeGenerationRef.current !== generation) return;if (notes) {- setNotesMap((prev) => new Map(prev).set(version, notes));+ setNotesMap((prev) => {+ const next = new Map(prev).set(version, notes);+ notesMapRef.current = next;+ return next;+ });setStateMap((prev) => new Map(prev).set(version, 'loaded'));} else {setStateMap((prev) => new Map(prev).set(version, 'error'));}} catch {+ if (localeGenerationRef.current !== generation) return;setStateMap((prev) => new Map(prev).set(version, 'error'));} finally {- inFlightRef.current.delete(version);+ if (inFlightRef.current.get(version) === generation) {+ inFlightRef.current.delete(version);+ }}},[loadVersion],diff --git a/apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx b/apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsxindex 8b92cf493b..76d6784427 100644--- a/apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx+++ b/apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx@@ -47,6 +47,7 @@ import { cn } from '@/lib/utils';import { Spinner } from '@/components/ui/spinner';import { useUpdateStatus } from '@/hooks/useUpdateStatus';import { useUpdateBannerDismiss } from '@/hooks/useUpdateBannerDismiss';+import { useLocale } from '@/hooks/useLocale';import { ConfirmDialog } from '@/components/ui/confirm-dialog';import { Tip } from '@/components/ui/tooltip';import { fetchReleaseNotes } from '@/release-notes';@@ -65,6 +66,7 @@ interface UpdateBannerProps {export function UpdateBanner({ isCollapsed, onOpenVersionNotice }: UpdateBannerProps) {const { status, version, errorCode } = useUpdateStatus();+ const { effectiveLocale } = useLocale();// 用户主动关闭态(仅本次进程内存,由 UserInfoSection 的火焰按钮唤回)。// status/version 变化时下面 effect 会自动 restore,新一版更新到达时 banner// 重新出现,不会被上一版的 dismiss 状态吞掉。@@ -171,11 +173,11 @@ export function UpdateBanner({ isCollapsed, onOpenVersionNotice }: UpdateBannerPreturn;}let cancelled = false;- fetchReleaseNotes(version)+ fetchReleaseNotes(version, effectiveLocale).then((notes) => { if (!cancelled) setHasNotes(notes !== null); }).catch(() => { if (!cancelled) setHasNotes(false); });return () => { cancelled = true; };- }, [status, version, canOpenNotice, isCollapsed]);+ }, [status, version, canOpenNotice, isCollapsed, effectiveLocale]);// 取消:先打标记再复位,让上面的 effect 在入口按钮重新挂载后把焦点还回去。const handleCancelConfirm = () => {diff --git a/apps/desktop/src/renderer/hooks/useUpdateNotice.ts b/apps/desktop/src/renderer/hooks/useUpdateNotice.tsindex 96d87195b1..7dd09d095b 100644--- a/apps/desktop/src/renderer/hooks/useUpdateNotice.ts+++ b/apps/desktop/src/renderer/hooks/useUpdateNotice.ts@@ -6,6 +6,8 @@ import {fetchReleaseNotesIndex,type ReleaseNotes,} from '@/release-notes';+import { useLocale } from '@/hooks/useLocale';+import type { SupportedLocale } from '@/i18n';import { toast } from '@/lib/toast';import { createLogger } from '@/lib/logger';@@ -199,6 +201,7 @@ function versionsForManual(index: string[] | null, appVersion: string): string[]export function useUpdateNotice(): UseUpdateNoticeReturn {const { t } = useTranslation();+ const { effectiveLocale } = useLocale();const [open, setOpen] = useState(false);const [mode, setMode] = useState<UpdateNoticeMode | null>(null);const [releaseNotes, setReleaseNotes] = useState<ReleaseNotes[] | null>(null);@@ -215,6 +218,46 @@ export function useUpdateNotice(): UseUpdateNoticeReturn {// Stored handle for the dismiss cleanup timer so onOpen can cancel it if// the user re-opens the dialog before the 200ms animation delay fires.const dismissTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ // Async entry points capture a locale. This ref prevents a slower response+ // for the previous locale from replacing newly selected-language content.+ const localeRef = useRef(effectiveLocale);+ localeRef.current = effectiveLocale;+ const previousLocaleRef = useRef(effectiveLocale);++ /**+ * Resolve a whole version set in one stable locale. If the user changes the+ * language while requests are in flight, the raw/version cache makes the+ * retry local and cheap while preventing a mixed-language result set.+ */+ const fetchVersionsForCurrentLocale = useCallback(+ async (+ versions: string[],+ initialRequest?: {+ version: string;+ locale: SupportedLocale;+ promise: Promise<ReleaseNotes | null>;+ },+ ): Promise<(ReleaseNotes | null)[]> => {+ let requestLocale = localeRef.current;+ let canUseInitialRequest = true;+ for (;;) {+ const results = await Promise.all(versions.map((version) => {+ if (+ canUseInitialRequest &&+ initialRequest?.version === version &&+ initialRequest.locale === requestLocale+ ) {+ return initialRequest.promise;+ }+ return fetchReleaseNotes(version, requestLocale);+ }));+ canUseInitialRequest = false;+ if (localeRef.current === requestLocale) return results;+ requestLocale = localeRef.current;+ }+ },+ [],+ );useEffect(() => {const appVersion = window.electronAPI.appVersion;@@ -241,7 +284,7 @@ export function useUpdateNotice(): UseUpdateNoticeReturn {const targets = versionsToFetch(index, lastRead, appVersion).slice(-MAX_AGGREGATED_VERSIONS,);- const results = await Promise.all(targets.map((v) => fetchReleaseNotes(v)));+ const results = await fetchVersionsForCurrentLocale(targets);if (cancelled) return;const notes = results.filter((n): n is ReleaseNotes => n !== null);@@ -281,7 +324,35 @@ export function useUpdateNotice(): UseUpdateNoticeReturn {});return () => { cancelled = true; };- }, []);+ }, [fetchVersionsForCurrentLocale]);++ // Re-select every version currently owned by the hook when the language+ // changes. Renderer raw caching keeps this local: no extra CDN/IPC request.+ useEffect(() => {+ if (previousLocaleRef.current === effectiveLocale) return;+ previousLocaleRef.current = effectiveLocale;+ const versions = releaseNotes?.map((notes) => notes.version) ?? [];+ if (versions.length === 0) return;++ let cancelled = false;+ void Promise.all(versions.map((version) => fetchReleaseNotes(version, effectiveLocale)))+ .then((localized) => {+ if (cancelled || localeRef.current !== effectiveLocale) return;+ const byVersion = new Map(+ localized+ .filter((notes): notes is ReleaseNotes => notes !== null)+ .map((notes) => [notes.version, notes]),+ );+ setReleaseNotes((current) =>+ current?.map((notes) => byVersion.get(notes.version) ?? notes) ?? current,+ );+ })+ .catch((err) => {+ log.warn('locale-refresh threw:', err);+ });++ return () => { cancelled = true; };+ }, [effectiveLocale, releaseNotes]);const dismiss = useCallback(() => {dialogOpenedRef.current = false;@@ -320,10 +391,14 @@ export function useUpdateNotice(): UseUpdateNoticeReturn {// dialog uses to render placeholders for every history entry; the// appVersion notes are what the top block shows immediately so the// dialog isn't blank-until-lazy-load on open.- const [index, appNotes] = await Promise.all([- fetchReleaseNotesIndex(),- fetchReleaseNotes(appVersion),- ]);+ const warmupLocale = localeRef.current;+ const appNotesWarmup = fetchReleaseNotes(appVersion, warmupLocale)+ .catch(() => null);+ const index = await fetchReleaseNotesIndex();+ const [appNotes] = await fetchVersionsForCurrentLocale(+ [appVersion],+ { version: appVersion, locale: warmupLocale, promise: appNotesWarmup },+ );// The dialog needs at least one loaded note as its initial seed.// If appVersion's JSON is temporarily unavailable (CDN lag / 404), try// the most-recent historical version from the index as fallback seed so@@ -335,7 +410,7 @@ export function useUpdateNotice(): UseUpdateNoticeReturn {// so a single bad/lagging CDN file doesn't block the entire history view.for (const fallbackVersion of versionsForManual(index, appVersion)) {if (fallbackVersion === appVersion) continue;- const fallback = (await fetchReleaseNotes(fallbackVersion)) ?? null;+ const [fallback] = await fetchVersionsForCurrentLocale([fallbackVersion]);if (fallback) {seed = fallback;break;@@ -366,7 +441,7 @@ export function useUpdateNotice(): UseUpdateNoticeReturn {log.warn('manual-fetch threw:', err);toast.error(t('logic.toasts.fetchUpdateNoticeFailed'));});- }, [t, open]);+ }, [t, open, fetchVersionsForCurrentLocale]);const onOpenVersion = useCallback((pendingVersion: string) => {// `open` is state, so two clicks in the same tick both read `false` and both@@ -385,7 +460,9 @@ export function useUpdateNotice(): UseUpdateNoticeReturn {// Kick off the pending version's notes immediately — it is the one block// that must be there, and the banner's probe usually leaves it cached, so// this resolves ~instantly and overlaps whatever the index costs.- const pendingNotes = fetchReleaseNotes(pendingVersion);+ const warmupLocale = localeRef.current;+ const pendingNotesWarmup = fetchReleaseNotes(pendingVersion, warmupLocale)+ .catch(() => null);// The index only adds the *in-between* blocks. Waiting out the full CDN// timeout (15s, releaseNotesService) for them would make the link look// dead, so give it a budget and degrade to the pending version alone —@@ -397,8 +474,9 @@ export function useUpdateNotice(): UseUpdateNoticeReturn {}),]);const targets = versionsToPreview(index, appVersion, pendingVersion);- const results = await Promise.all(- targets.map((v) => (v === pendingVersion ? pendingNotes : fetchReleaseNotes(v))),+ const results = await fetchVersionsForCurrentLocale(+ targets,+ { version: pendingVersion, locale: warmupLocale, promise: pendingNotesWarmup },);const notes = results.filter((n): n is ReleaseNotes => n !== null);@@ -428,11 +506,11 @@ export function useUpdateNotice(): UseUpdateNoticeReturn {log.warn('preview-fetch threw:', err);toast.error(t('logic.toasts.fetchUpdateNoticeFailed'));});- }, [t, open]);+ }, [t, open, fetchVersionsForCurrentLocale]);const loadVersion = useCallback(- (version: string) => fetchReleaseNotes(version),- [],+ (version: string) => fetchReleaseNotes(version, effectiveLocale),+ [effectiveLocale],);return {diff --git a/apps/desktop/src/renderer/release-notes/index.ts b/apps/desktop/src/renderer/release-notes/index.tsindex 16e79bf052..375c7c0f0b 100644--- a/apps/desktop/src/renderer/release-notes/index.ts+++ b/apps/desktop/src/renderer/release-notes/index.ts@@ -1,29 +1,22 @@/*** release-notes/index.ts* ---------------------------------------------------------------------------- * Per-version release notes are fetched from CDN by the main process and- * delivered through `window.electronAPI.fetchReleaseNotes`. Platform routing- * happens entirely in main (via getPlatformKey()), so the renderer only ever- * deals with the version string.- *- * Successful results are memoised per version so that dismissing and- * re-opening the dialog from the sidebar does not trigger another fetch.- *- * Two payload generations coexist on the CDN:- *- * Legacy (author-grouped): each section's `items` is an array of author groups- * { "name": "Lizi", "list": ["...", "..."] }- * The dialog flattens these into one bullet per `list` entry under the- * matching author sub-head.- *- * Topic format (v2): the payload carries `topics` instead of `sections` —- * user-facing theme blocks, each a short narrative paragraph:- * { "emoji": "🎙️", "title": "语音输入更稳", "text": "…", "contributors": ["Lizi"] }- * plus an optional top-level `intro` one-liner. Presence of a non-empty- * `topics` array is the discriminator; old payloads never have it.+ * Main fetches one raw JSON per version; renderer selects the requested+ * locale and normalizes it for UpdateNoticeDialog. Raw payloads are cached by+ * version, while normalized results are cached by version + locale so changing+ * the app language never reuses another language's rendered content or causes+ * another CDN request.*/-import { isRenderableTopic } from '../../shared/releaseNotesContent';+import {+ hasRenderableContent,+ isRenderableTopic,+ type NoticeLocale,+ type RawItem,+ type RawLocalizedContent,+ type RawReleaseNotes,+} from '../../shared/releaseNotesContent';+import { DEFAULT_LOCALE } from '../../shared/locale';/** Per-item shape after flattening: one bullet with its author tag. */export interface ReleaseNoteItem {@@ -33,10 +26,7 @@ export interface ReleaseNoteItem {}/** Author-grouped raw item as authored in the JSON. */-export interface RawReleaseNoteItem {- name: string;- list: string[];-}+export type RawReleaseNoteItem = RawItem;export interface ReleaseNoteSection {title: string;@@ -45,6 +35,8 @@ export interface ReleaseNoteSection {/** Topic-format (v2) block: one user-facing theme with a short narrative. */export interface ReleaseNoteTopic {+ /** Stable internal id shared by every localized version of the topic. */+ id?: string;/** Leading emoji for the topic title. Optional — renderer tolerates absence. */emoji?: string;title: string;@@ -63,7 +55,7 @@ export interface ReleaseNotes {sections: ReleaseNoteSection[];/** Topic-format blocks. Non-empty ⇒ dialog renders the topic layout. */topics: ReleaseNoteTopic[];- /** Optional one-line lead above the topics (e.g. PR/commit counts). */+ /** Optional one-line lead above the topics. */intro?: string;}@@ -72,54 +64,60 @@ function expandRawItem(raw: RawReleaseNoteItem): ReleaseNoteItem[] {return raw.list.map((text) => ({ text, by: raw.name }));}-// ── In-memory cache (renderer-side) ────────────────────────────────────────--const cache = new Map<string, ReleaseNotes>();+// Main already caches by version; this renderer raw cache avoids even another+// IPC round-trip when the user switches locale while the dialog is open.+const rawCache = new Map<string, RawReleaseNotes>();+const rawInFlight = new Map<string, Promise<RawReleaseNotes | null>>();+const localizedCache = new Map<string, ReleaseNotes>();// Version-index cache — one shot per session; the app version is immutable// while the process lives, so a successful fetch never needs to repeat.let indexCache: string[] | null = null;-// ── Public API ─────────────────────────────────────────────────────────────+/** Return the legacy/root content in the same shape as a localized block. */+function legacyContentFromRoot(raw: RawReleaseNotes): RawLocalizedContent {+ return {+ intro: raw.intro,+ topics: raw.topics,+ sections: raw.sections,+ };+}-/**- * Fetch the sorted version-index from CDN via main. Used to determine which- * intermediate versions to pull when the user upgrades across releases.- * Returns null on failure — caller should fall back to showing the current- * version only.- */-export async function fetchReleaseNotesIndex(): Promise<string[] | null> {- if (indexCache) return indexCache;- const raw = await window.electronAPI.fetchReleaseNotesIndex();- if (!raw) return null;- indexCache = raw;- return raw;+function hasUsableContent(content: unknown): content is RawLocalizedContent {+ return content !== null && typeof content === 'object' && hasRenderableContent(content);}/**- * Fetch release notes for the given version via the main-process CDN client.- * Returns null when the CDN has no entry for this version on the current- * platform, or when the network/parse fails.- *- * The CDN payload is normalised defensively before caching: missing- * `contributors` / `sections` / `topics` become empty arrays, malformed topic- * entries are dropped, and legacy author-grouped items are flattened.+ * Select one language from a one-file notice. Empty or malformed localized+ * blocks count as missing and continue through the fallback chain.*/-export async function fetchReleaseNotes(- version: string,-): Promise<ReleaseNotes | null> {- const hit = cache.get(version);- if (hit) return hit;+export function selectLocalizedContent(+ raw: RawReleaseNotes,+ locale: NoticeLocale,+): RawLocalizedContent | null {+ const localized = raw.contentByLocale;+ if (locale === 'zh-CN') {+ const zh = localized?.['zh-CN'];+ if (hasUsableContent(zh)) return zh;+ const legacy = legacyContentFromRoot(raw);+ return hasUsableContent(legacy) ? legacy : null;+ }- const raw = await window.electronAPI.fetchReleaseNotes(version);- if (!raw) return null;+ for (const candidate of [locale, 'en', 'zh-CN'] as const) {+ const content = localized?.[candidate];+ if (hasUsableContent(content)) return content;+ }- // Defensive defaults: tolerate older payloads missing `contributors`,- // topic-format payloads missing `sections`, and legacy payloads missing- // `topics`. Malformed entries (topics, sections, author groups, bullets)- // are dropped rather than crashing the dialog on a bad CDN document.- const rawTopics = Array.isArray(raw.topics) ? raw.topics : [];- const rawSections = Array.isArray(raw.sections) ? raw.sections : [];+ const legacy = legacyContentFromRoot(raw);+ return hasUsableContent(legacy) ? legacy : null;+}++function normalizeReleaseNotes(+ raw: RawReleaseNotes,+ content: RawLocalizedContent,+): ReleaseNotes | null {+ const rawTopics = Array.isArray(content.topics) ? content.topics : [];+ const rawSections = Array.isArray(content.sections) ? content.sections : [];const notes: ReleaseNotes = {version: raw.version,date: raw.date,@@ -140,6 +138,7 @@ export async function fetchReleaseNotes(topics: rawTopics.filter((t) => isRenderableTopic(t)).map((t) => ({+ ...(typeof t.id === 'string' ? { id: t.id } : {}),emoji: typeof t.emoji === 'string' ? t.emoji : undefined,title: t.title,text: t.text,@@ -147,16 +146,69 @@ export async function fetchReleaseNotes(? t.contributors.filter((c): c is string => typeof c === 'string'): [],})),- intro: typeof raw.intro === 'string' ? raw.intro : undefined,+ intro: typeof content.intro === 'string' ? content.intro : undefined,};- // A notice with no renderable content (e.g. a payload whose topics or- // section bullets were all malformed and dropped) must count as a failed- // fetch: caching it would open an empty dialog and, worse, advance- // lastReadVersion on dismiss so a corrected CDN payload would never be- // shown again. Bullet-level truth, mirroring shared hasRenderableContent.+const hasContent =notes.topics.length > 0 || notes.sections.some((s) => s.items.length > 0);- if (!hasContent) return null;- cache.set(version, notes);+ return hasContent ? notes : null;+}++async function fetchRawReleaseNotes(version: string): Promise<RawReleaseNotes | null> {+ const hit = rawCache.get(version);+ if (hit) return hit;++ const pending = rawInFlight.get(version);+ if (pending) return pending;++ const request = (async () => {+ const raw = await window.electronAPI.fetchReleaseNotes(version);+ if (!raw || !hasRenderableContent(raw)) return null;+ rawCache.set(version, raw);+ return raw;+ })();+ rawInFlight.set(version, request);++ try {+ return await request;+ } finally {+ if (rawInFlight.get(version) === request) rawInFlight.delete(version);+ }+}++/**+ * Fetch the sorted version-index from CDN via main. Used to determine which+ * intermediate versions to pull when the user upgrades across releases.+ */+export async function fetchReleaseNotesIndex(): Promise<string[] | null> {+ if (indexCache) return indexCache;+ const raw = await window.electronAPI.fetchReleaseNotesIndex();+ if (!raw) return null;+ indexCache = raw;+ return raw;+}++/**+ * Fetch release notes for one version and select the requested locale.+ * CDN/main/preload still receive only the version because every language is+ * carried by the same raw JSON.+ */+export async function fetchReleaseNotes(+ version: string,+ locale: NoticeLocale = DEFAULT_LOCALE,+): Promise<ReleaseNotes | null> {+ const cacheKey = `${version}:${locale}`;+ const hit = localizedCache.get(cacheKey);+ if (hit) return hit;++ const raw = await fetchRawReleaseNotes(version);+ if (!raw) return null;++ const content = selectLocalizedContent(raw, locale);+ if (!content) return null;+ const notes = normalizeReleaseNotes(raw, content);+ if (!notes) return null;++ localizedCache.set(cacheKey, notes);return notes;}diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex d84749ff88..57333f98d6 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -45,6 +45,7 @@ type PendingRemotePrecreatedWorktreeTarget =import('../shared/remotePrecreatedWorktreeLedger').PendingRemotePrecreatedWorktreeTarget;type RemotePrecreatedWorktreeLedgerSnapshot =import('../shared/remotePrecreatedWorktreeLedger').RemotePrecreatedWorktreeLedgerSnapshot;+type RawReleaseNotesPayload = import('../shared/releaseNotesContent').RawReleaseNotes;interface NewMakerWorktreeBranchPreferenceSnapshot {baseRepo: string;@@ -5761,43 +5762,6 @@ interface ElectronAPI {};}-/* ── Release notes raw payload shape from CDN ── */--/** Author-grouped item: one block per contributor, with their bullets. */-interface RawReleaseNotesItem {- name: string;- list: string[];-}--interface RawReleaseNotesSection {- title: string;- items: RawReleaseNotesItem[];-}--/** Topic-format (v2) block: one user-facing theme with a short narrative. */-interface RawReleaseNotesTopic {- emoji?: string;- title: string;- text: string;- contributors?: string[];-}--interface RawReleaseNotesPayload {- version: string;- date: string;- /**- * Flat contributor list — collective hall-of-fame on top of per-item `by`.- * Optional: older notice files predate the field (renderer defaults to []).- */- contributors?: string[];- /** Legacy author-grouped sections. Absent on topic-format payloads. */- sections?: RawReleaseNotesSection[];- /** Topic-format blocks. Non-empty ⇒ renderer uses the topic layout. */- topics?: RawReleaseNotesTopic[];- /** Optional one-line lead above the topics (e.g. PR/commit counts). */- intro?: string;-}-/* ── SkillHub Registry types (v0.6) ──* Mirror of `src/main/skillhub/registry/types.ts`. Renderer uses these* for reading registryEntry on SkillhubSkill; no runtime import needed. */diff --git a/apps/desktop/src/shared/releaseNotesContent.ts b/apps/desktop/src/shared/releaseNotesContent.tsindex 461a07643b..339f7a73ad 100644--- a/apps/desktop/src/shared/releaseNotesContent.ts+++ b/apps/desktop/src/shared/releaseNotesContent.ts@@ -8,6 +8,51 @@* CDN is corrected), and the renderer uses them to filter topic entries.*/+import type { SupportedLocale } from './locale';++export type NoticeLocale = SupportedLocale;++/** Author-grouped item: one block per contributor, with their bullets. */+export interface RawItem {+ name: string;+ list: string[];+}++export interface RawSection {+ title: string;+ items: RawItem[];+}++/** Topic-format (v2) block: one user-facing theme with a short narrative. */+export interface RawTopic {+ id?: string;+ emoji?: string;+ title: string;+ text: string;+ contributors?: string[];+}++export interface RawLocalizedContent {+ intro?: string;+ topics?: RawTopic[];+ sections?: RawSection[];+}++export interface RawReleaseNotes {+ version: string;+ date: string;+ githash?: string;+ contributors?: string[];++ // Legacy/root compatibility fields.+ sections?: RawSection[];+ topics?: RawTopic[];+ intro?: string;++ // New one-file, multi-locale payload.+ contentByLocale?: Partial<Record<NoticeLocale, RawLocalizedContent>>;+}+/** Minimal structural shapes both processes can check without full typing. */interface TopicLike {title?: unknown;@@ -53,15 +98,32 @@ export function isRenderableSection(section: SectionLike | null | undefined): bo}/**- * Whether a raw CDN payload carries anything the dialog can render: at least- * one legacy section with a real bullet, or at least one valid v2 topic.+ * Whether a raw CDN payload carries anything the dialog can render: root+ * legacy/v2 content or at least one renderable localized content block.*/+function hasRenderableLocalizedContent(content: RawLocalizedContent | null | undefined): boolean {+ if (!content) return false;+ if (+ Array.isArray(content.sections) &&+ content.sections.some((s) => isRenderableSection(s as SectionLike))+ ) {+ return true;+ }+ return Array.isArray(content.topics) && content.topics.some((t) => isRenderableTopic(t));+}+export function hasRenderableContent(raw: {sections?: unknown;topics?: unknown;+ contentByLocale?: Partial<Record<NoticeLocale, RawLocalizedContent>>;}): boolean {if (Array.isArray(raw.sections) && raw.sections.some((s) => isRenderableSection(s as SectionLike))) {return true;}- return Array.isArray(raw.topics) && raw.topics.some((t) => isRenderableTopic(t as TopicLike));+ if (Array.isArray(raw.topics) && raw.topics.some((t) => isRenderableTopic(t as TopicLike))) {+ return true;+ }+ return Object.values(raw.contentByLocale ?? {}).some((content) =>+ hasRenderableLocalizedContent(content),+ );}