Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 更新 banner 新增「查看更新公告」入口 (#954)
guyong-zapob34e44855de7
diff --git a/apps/desktop/src/renderer/__tests__/updateBannerReleaseNotesLink.test.tsx b/apps/desktop/src/renderer/__tests__/updateBannerReleaseNotesLink.test.tsxnew file mode 100644index 0000000000..794f2118d8--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/updateBannerReleaseNotesLink.test.tsx@@ -0,0 +1,122 @@+// @vitest-environment jsdom++/**+ * UpdateBanner「查看更新公告」文字链 —— 方案 A。+ *+ * 覆盖入口的四条判定:CDN 有公告才显示、点击带的是待装版本号、confirming 两步确认期+ * 让位、superseding 态不给入口(那时的 version 指向上一个已就绪补丁,不是正在下的新版)。+ */++import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { UpdateBanner } from '@/components/sidebar/UpdateBanner';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, opts?: Record<string, unknown>) =>+ opts?.version ? `${key}:${String(opts.version)}` : key,+ }),+}));++const updateStatus = vi.hoisted(() => ({+ current: { status: 'ready', version: '1.4.2' } as {+ status: string;+ version?: string;+ errorCode?: string;+ },+}));++vi.mock('@/hooks/useUpdateStatus', () => ({+ useUpdateStatus: () => updateStatus.current,+}));++const fetchReleaseNotes = vi.hoisted(() => vi.fn());+vi.mock('@/release-notes', () => ({ fetchReleaseNotes }));++const NOTES = { version: '1.4.2', date: '2026-07-28', contributors: [], sections: [], topics: [] };++const LINK = 'update.banner.viewNotes';++beforeEach(() => {+ updateStatus.current = { status: 'ready', version: '1.4.2' };+ fetchReleaseNotes.mockReset();+ fetchReleaseNotes.mockResolvedValue(NOTES);+});++afterEach(() => {+ cleanup();+});++describe('UpdateBanner release-notes link', () => {+ it('shows the link once the pending version has notes on CDN, and opens that version', async () => {+ const onOpenVersionNotice = vi.fn();+ render(<UpdateBanner isCollapsed={false} onOpenVersionNotice={onOpenVersionNotice} />);++ const link = await screen.findByText(LINK);+ expect(fetchReleaseNotes).toHaveBeenCalledWith('1.4.2');++ fireEvent.click(link);+ expect(onOpenVersionNotice).toHaveBeenCalledWith('1.4.2');+ });++ it('hides the link when the CDN has no renderable notes for that version', async () => {+ fetchReleaseNotes.mockResolvedValue(null);+ render(<UpdateBanner isCollapsed={false} onOpenVersionNotice={vi.fn()} />);++ await waitFor(() => expect(fetchReleaseNotes).toHaveBeenCalled());+ expect(screen.queryByText(LINK)).toBeNull();+ });++ it('hides the link while the two-step relaunch confirmation is showing', async () => {+ render(<UpdateBanner isCollapsed={false} onOpenVersionNotice={vi.fn()} />);+ await screen.findByText(LINK);++ fireEvent.click(screen.getByText('update.banner.button'));++ expect(screen.getByText('update.banner.confirmButton')).toBeTruthy();+ expect(screen.queryByText(LINK)).toBeNull();+ });++ it('does not probe or show the link while a newer version is superseding', async () => {+ updateStatus.current = { status: 'superseding', version: '1.4.2' };+ render(<UpdateBanner isCollapsed={false} onOpenVersionNotice={vi.fn()} />);++ await screen.findByText('update.banner.preparingButton');+ expect(fetchReleaseNotes).not.toHaveBeenCalled();+ expect(screen.queryByText(LINK)).toBeNull();+ });++ it('does not probe at all while the sidebar is collapsed / rail', async () => {+ render(<UpdateBanner isCollapsed onOpenVersionNotice={vi.fn()} />);++ // 收起态压根不渲染文字链,那就不该为它打一次 CDN 请求。+ await screen.findByRole('button');+ expect(fetchReleaseNotes).not.toHaveBeenCalled();+ expect(screen.queryByText(LINK)).toBeNull();+ });++ it('probes once the sidebar expands, without re-probing on callback identity churn', async () => {+ const { rerender } = render(+ <UpdateBanner isCollapsed onOpenVersionNotice={vi.fn()} />,+ );+ expect(fetchReleaseNotes).not.toHaveBeenCalled();++ rerender(<UpdateBanner isCollapsed={false} onOpenVersionNotice={vi.fn()} />);+ await screen.findByText(LINK);+ expect(fetchReleaseNotes).toHaveBeenCalledTimes(1);++ // useUpdateNotice 的回调带 `open` 依赖,弹窗开关会换掉它的 identity;探测不该跟着重跑。+ rerender(<UpdateBanner isCollapsed={false} onOpenVersionNotice={vi.fn()} />);+ rerender(<UpdateBanner isCollapsed={false} onOpenVersionNotice={vi.fn()} />);+ expect(fetchReleaseNotes).toHaveBeenCalledTimes(1);+ });++ it('renders no link when the host provides no open-notice callback', async () => {+ render(<UpdateBanner isCollapsed={false} />);++ await screen.findByText('update.banner.button');+ expect(fetchReleaseNotes).not.toHaveBeenCalled();+ expect(screen.queryByText(LINK)).toBeNull();+ });+});diff --git a/apps/desktop/src/renderer/__tests__/updateNoticeDialogAutoLayout.test.tsx b/apps/desktop/src/renderer/__tests__/updateNoticeDialogAutoLayout.test.tsxnew file mode 100644index 0000000000..e35359a555--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/updateNoticeDialogAutoLayout.test.tsx@@ -0,0 +1,101 @@+// @vitest-environment jsdom++/**+ * UpdateNoticeDialog 的 auto 布局契约。+ *+ * 装完后的自动公告走这条布局,UpdateBanner 的「装前预览」也刻意复用它(见 useUpdateNotice+ * 的 onOpenVersion)。所以这个文件既是既有行为的回归护栏,也是新入口渲染形态的说明:+ * - 单版本:右上角是该版本日期,徽标 v<版本>+ * - 跨版本:右上角是版本数,徽标 v<旧> → v<新>+ * 两种情况都没有版本跳转器、没有懒加载占位块。+ *+ * 弹窗本身在本次改动里一行未改;这里锁住的是「预览入口依赖的那部分不能被顺手清理掉」。+ */++import { cleanup, render, screen } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { UpdateNoticeDialog } from '@/components/UpdateNoticeDialog';+import type { ReleaseNotes } from '@/release-notes';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, opts?: Record<string, unknown>) => {+ if (!opts) return key;+ const args = Object.entries(opts).map(([k, v]) => `${k}=${String(v)}`).join(',');+ return `${key}(${args})`;+ },+ i18n: { language: 'zh-CN' },+ }),+}));++function notesFor(version: string, date: string): ReleaseNotes {+ return {+ version,+ date,+ contributors: [],+ sections: [],+ topics: [{ title: `条目 ${version}`, text: '正文。', contributors: [] }],+ };+}++const NEWEST = notesFor('0.1.21', '2026-07-29');+const OLDER = notesFor('0.1.20', '2026-07-20');++beforeEach(() => {+ // jsdom 没有 IntersectionObserver;弹窗内部的懒加载与 sticky 表头都依赖它。+ vi.stubGlobal('IntersectionObserver', class {+ observe() {}+ unobserve() {}+ disconnect() {}+ takeRecords() { return []; }+ });+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++function renderAuto(releaseNotes: ReleaseNotes[]) {+ return render(+ <UpdateNoticeDialog+ open+ mode="auto"+ releaseNotes={releaseNotes}+ allVersions={null}+ loadVersion={vi.fn().mockResolvedValue(null)}+ onDismiss={vi.fn()}+ />,+ );+}++describe('UpdateNoticeDialog auto layout', () => {+ it('single version: date on the right, plain version badge, single-version aria', () => {+ renderAuto([NEWEST]);++ expect(screen.queryByText(/update\.notice\.versionsSpan/)).toBeNull();+ expect(screen.getAllByText(/2026/).length).toBeGreaterThan(0);+ expect(screen.getByText('v0.1.21')).toBeTruthy();+ expect(+ screen.getByText('update.notice.ariaDescription(version=0.1.21)'),+ ).toBeTruthy();+ });++ it('multiple versions: version count on the right, range badge, span aria', () => {+ renderAuto([NEWEST, OLDER]);++ expect(screen.getByText('update.notice.versionsSpan(count=2)')).toBeTruthy();+ expect(screen.getByText('v0.1.20 → v0.1.21')).toBeTruthy();+ expect(+ screen.getByText('update.notice.ariaDescriptionSpan(from=0.1.20,count=2)'),+ ).toBeTruthy();+ });++ it('renders one content block per aggregated version', () => {+ renderAuto([NEWEST, OLDER]);++ expect(screen.getByText('条目 0.1.21')).toBeTruthy();+ expect(screen.getByText('条目 0.1.20')).toBeTruthy();+ });+});diff --git a/apps/desktop/src/renderer/__tests__/useUpdateNoticeUpdatePreview.test.tsx b/apps/desktop/src/renderer/__tests__/useUpdateNoticeUpdatePreview.test.tsxnew file mode 100644index 0000000000..ad0c228d59--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/useUpdateNoticeUpdatePreview.test.tsx@@ -0,0 +1,226 @@+// @vitest-environment jsdom++/**+ * useUpdateNotice().onOpenVersion —— UpdateBanner 的「装前预览」入口。+ *+ * 契约:聚合 `(已装版本, 待装版本]` 这个区间 —— 跨了几版就显示几块,普通单版本升级就一块;+ * 不带已装版本本身,也不带它之前的历史(那是火焰按钮的活)。复用 auto 的布局契约(整段预加载、+ * 无懒加载历史、无版本跳转器),但 dismiss 不推进 lastReadVersion —— 否则重启装完后真正的+ * 自动公告就再也不弹了。+ *+ * 同时钉住:火焰按钮的完整历史路径不受本次改动影响。+ */++import { act, renderHook, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { useUpdateNotice } from '@/hooks/useUpdateNotice';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++const mocks = vi.hoisted(() => ({+ fetchReleaseNotes: vi.fn(),+ fetchReleaseNotesIndex: vi.fn(),+ toastError: vi.fn(),+}));++vi.mock('@/release-notes', () => ({+ fetchReleaseNotes: mocks.fetchReleaseNotes,+ fetchReleaseNotesIndex: mocks.fetchReleaseNotesIndex,+}));++vi.mock('@/lib/toast', () => ({ toast: { error: mocks.toastError } }));++const STORAGE_KEY = 'xdt-maker:lastReadVersion';++function notesFor(version: string) {+ return {+ version,+ date: '2026-07-28',+ contributors: [],+ sections: [],+ topics: [{ title: `t-${version}`, text: 'x', contributors: [] }],+ };+}++/** 设定「已装版本」,并让自动弹窗路径静默(lastRead === appVersion 时 effect 直接 return)。 */+function setInstalled(version: string) {+ (window as unknown as { electronAPI: unknown }).electronAPI = { appVersion: version };+ localStorage.setItem(STORAGE_KEY, version);+}++beforeEach(() => {+ 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));+ setInstalled('1.4.1');+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('useUpdateNotice onOpenVersion — pre-install preview', () => {+ it('shows one block for a plain one-version bump', async () => {+ const { result } = renderHook(() => useUpdateNotice());++ act(() => { result.current.onOpenVersion('1.4.2'); });++ await waitFor(() => expect(result.current.open).toBe(true));+ expect(result.current.mode).toBe('auto');+ expect(result.current.releaseNotes?.map((n) => n.version)).toEqual(['1.4.2']);+ // auto 布局契约:没有懒加载历史列表,也就没有版本跳转器。+ expect(result.current.allVersions).toBeNull();+ });++ it('aggregates every version the restart jumps over, newest first', async () => {+ setInstalled('1.3.9');+ const { result } = renderHook(() => useUpdateNotice());++ act(() => { result.current.onOpenVersion('1.4.2'); });++ await waitFor(() => expect(result.current.open).toBe(true));+ expect(result.current.releaseNotes?.map((n) => n.version)).toEqual([+ '1.4.2', '1.4.1', '1.4.0',+ ]);+ });++ it('excludes the installed version and everything older than it', async () => {+ setInstalled('1.4.0');+ const { result } = renderHook(() => useUpdateNotice());++ act(() => { result.current.onOpenVersion('1.4.2'); });++ await waitFor(() => expect(result.current.open).toBe(true));+ const shown = result.current.releaseNotes?.map((n) => n.version) ?? [];+ 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');+ });++ it('caps the aggregated range at 5 versions', async () => {+ setInstalled('1.0.0');+ mocks.fetchReleaseNotesIndex.mockResolvedValue(+ Array.from({ length: 9 }, (_, i) => `1.1.${i + 1}`),+ );+ const { result } = renderHook(() => useUpdateNotice());++ act(() => { result.current.onOpenVersion('1.1.9'); });++ await waitFor(() => expect(result.current.open).toBe(true));+ expect(result.current.releaseNotes?.map((n) => n.version)).toEqual([+ '1.1.9', '1.1.8', '1.1.7', '1.1.6', '1.1.5',+ ]);+ });++ 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)));+ const { result } = renderHook(() => useUpdateNotice());++ act(() => { result.current.onOpenVersion('1.4.2'); });++ await waitFor(() => expect(result.current.open).toBe(true));+ expect(result.current.releaseNotes?.map((n) => n.version)).toEqual(['1.4.2', '1.4.0']);+ });++ it('falls back to the pending version alone when the index is unreachable', async () => {+ setInstalled('1.3.9');+ mocks.fetchReleaseNotesIndex.mockResolvedValue(null);+ const { result } = renderHook(() => useUpdateNotice());++ act(() => { result.current.onOpenVersion('1.4.2'); });++ await waitFor(() => expect(result.current.open).toBe(true));+ expect(result.current.releaseNotes?.map((n) => n.version)).toEqual(['1.4.2']);+ });++ it('includes the pending version even when the CDN index lags behind it', async () => {+ mocks.fetchReleaseNotesIndex.mockResolvedValue(['1.3.9', '1.4.0', '1.4.1']);+ const { result } = renderHook(() => useUpdateNotice());++ act(() => { result.current.onOpenVersion('1.4.2'); });++ await waitFor(() => expect(result.current.open).toBe(true));+ expect(result.current.releaseNotes?.map((n) => n.version)).toEqual(['1.4.2']);+ });++ 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)));+ const { result } = renderHook(() => useUpdateNotice());++ act(() => { result.current.onOpenVersion('1.4.2'); });++ await waitFor(() => expect(mocks.toastError).toHaveBeenCalled());+ expect(result.current.open).toBe(false);+ expect(result.current.releaseNotes).toBeNull();+ });++ it('dedupes a double click before the dialog has opened', async () => {+ const { result } = renderHook(() => useUpdateNotice());++ // 同一 tick 两次点击:`open` 还是 false,只有同步 ref 拦得住第二次。+ act(() => {+ result.current.onOpenVersion('1.4.2');+ result.current.onOpenVersion('1.4.2');+ });++ await waitFor(() => expect(result.current.open).toBe(true));+ expect(mocks.fetchReleaseNotesIndex).toHaveBeenCalledTimes(1);+ expect(mocks.fetchReleaseNotes).toHaveBeenCalledTimes(1);+ });++ it('opens with the pending version alone when the index hangs past its budget', async () => {+ setInstalled('1.3.9');+ // index 永不 resolve —— 模拟 CDN 挂住(真实链路要等满 15s 超时)。+ mocks.fetchReleaseNotesIndex.mockReturnValue(new Promise(() => {}));+ vi.useFakeTimers();+ try {+ const { result } = renderHook(() => useUpdateNotice());++ act(() => { result.current.onOpenVersion('1.4.2'); });++ // 预算到点前不该开:in-between 版本还有希望赶上。+ await act(async () => { await vi.advanceTimersByTimeAsync(2999); });+ expect(result.current.open).toBe(false);++ await act(async () => { await vi.advanceTimersByTimeAsync(1); });+ await vi.waitFor(() => expect(result.current.open).toBe(true));+ expect(result.current.releaseNotes?.map((n) => n.version)).toEqual(['1.4.2']);+ } finally {+ vi.useRealTimers();+ }+ });++ it('leaves lastReadVersion untouched on dismiss, so the post-restart popup still fires', async () => {+ const { result } = renderHook(() => useUpdateNotice());++ act(() => { result.current.onOpenVersion('1.4.2'); });+ await waitFor(() => expect(result.current.open).toBe(true));+ act(() => { result.current.dismiss(); });++ expect(localStorage.getItem(STORAGE_KEY)).toBe('1.4.1');+ });+});++describe('useUpdateNotice onOpen — flame-icon history is unchanged', () => {+ it('still seeds appVersion and lists the full <= appVersion history', async () => {+ const { result } = renderHook(() => useUpdateNotice());++ act(() => { result.current.onOpen(); });++ await waitFor(() => expect(result.current.open).toBe(true));+ 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']);+ });+});diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsxindex e34884f8c4..a7acd30081 100644--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx@@ -355,6 +355,7 @@ export function MainLayout() {loadVersion: noticeLoadVersion,dismiss: dismissNotice,onOpen: openNotice,+ onOpenVersion: openVersionNotice,} = useUpdateNotice();const navigate = useNavigate();const location = useLocation();@@ -1172,6 +1173,7 @@ export function MainLayout() {onDragStart={handleDragStart}onResetWidth={resetWidth}onOpenUpdateNotice={openNotice}+ onOpenVersionNotice={openVersionNotice}peekState={sidebarPeek.isPeekVisible ? sidebarPeek.peekState : null}peekDrawerProps={sidebarPeek.drawerProps}/>diff --git a/apps/desktop/src/renderer/components/sidebar/Sidebar.tsx b/apps/desktop/src/renderer/components/sidebar/Sidebar.tsxindex 47142d9341..02da13e3e8 100644--- a/apps/desktop/src/renderer/components/sidebar/Sidebar.tsx+++ b/apps/desktop/src/renderer/components/sidebar/Sidebar.tsx@@ -50,6 +50,12 @@ interface SidebarProps {onResetWidth?: () => void;/** Open the update notice dialog to review release notes. */onOpenUpdateNotice?: () => void;+ /**+ * Open the update notice dialog pinned to one version — used by UpdateBanner+ * to preview the notes of the downloaded-but-not-yet-installed update, which+ * `onOpenUpdateNotice`'s history range (`<= appVersion`) cannot reach.+ */+ onOpenVersionNotice?: (version: string) => void;/*** 完全隐藏态 hover 临时浮出(peek)——非 null 时以 fixed overlay 抽屉渲染* (useSidebarPeek 驱动,MainLayout 只在 peek 可见期传入):@@ -69,6 +75,7 @@ export function Sidebar({onDragStart,onResetWidth,onOpenUpdateNotice,+ onOpenVersionNotice,peekState = null,peekDrawerProps,}: SidebarProps) {@@ -215,7 +222,10 @@ export function Sidebar({{/* Update banner: shown only when a verified update is readypeek 抽屉视同展开(否则横幅在抽屉里消失,与「预览完整列表」语义相悖)。 */}- <UpdateBanner isCollapsed={(isCollapsed && !isPeek) || isRail} />+ <UpdateBanner+ isCollapsed={(isCollapsed && !isPeek) || isRail}+ onOpenVersionNotice={onOpenVersionNotice}+ />{/* Bottom: User info (Shell-level, shared across all features)isCollapsed 在这里表达"窄布局"(rail 居中头像);完全隐藏态 w-0 整体裁掉。 */}diff --git a/apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx b/apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsxindex f56072144f..ed09de6a9e 100644--- a/apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx+++ b/apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx@@ -11,7 +11,19 @@* 「取消」置于其下(次级、需刻意移动),从而在保持左下角、减少视线/鼠标移动的同时,* 用两步显式点击防止误更新。*- * - Expanded ready: Flame 36px → "Updated to {v}" → "Relaunch to apply" → Relaunch pill+ * 「查看更新公告」文字链:ready 态在副标题下给一条 ghost 文字链,点开 UpdateNoticeDialog+ * 预览**待安装版本**的公告,让用户在「现在重启 vs 稍后」之间有据可依(装完后的自动弹窗+ * 只解决装完之后的事)。跨版本时会把「已装版本 → 待装版本」之间跳过的每一版聚合进同一个+ * 弹窗(useUpdateNotice 的 onOpenVersion),普通单版本升级就只有一块。三条刻意的边界:+ * - 只在 ready 态出现。superseding 态顶部刻意不显示版本号(新版还在下),没有可信的+ * 版本可查,confirming 态则要保持两步确认的干净,两者都不给入口。+ * - CDN 上没有该版本公告(或内容不可渲染)时不显示入口 —— 用挂载时的 fetch 探测,+ * 宁可没有入口,也不给一个点了报错的链接。探测结果被 release-notes 双层缓存复用,+ * 真正点开时不会再打一次网。+ * - 收起 / rail 态放不下文字链,因此**没有入口**;那两态里 UserInfoSection 的火焰按钮+ * 也只能看 <= 当前已装版本的历史,看不到待装版本。这是本方案已知的取舍。+ *+ * - Expanded ready: Flame 36px → "Updated to {v}" → "Relaunch to apply" → notes link → Relaunch pill* - Expanded confirming: Flame 36px → "Restart to update?" → hint → Confirm pill / Cancel (下方,ghost)* - Expanded superseding: Loader2 36px (spin) → "Newer version found" → "Updating…" → disabled pill with spinner* - Collapsed ready: Flame 20px, click → confirming(就地展开 ✓ / ✕)@@ -31,15 +43,21 @@ import { useUpdateStatus } from '@/hooks/useUpdateStatus';import { useUpdateBannerDismiss } from '@/hooks/useUpdateBannerDismiss';import { ConfirmDialog } from '@/components/ui/confirm-dialog';import { Tip } from '@/components/ui/tooltip';+import { fetchReleaseNotes } from '@/release-notes';// 运行期端点清单(dev/packaged 都在启动阻断后有真值,烘焙兜底已退役)const websiteUrl = () => window.electronAPI.clientEndpoints.websiteUrl;interface UpdateBannerProps {isCollapsed: boolean;+ /**+ * 打开指定版本的更新公告(UpdateNoticeDialog)。由 MainLayout 的 useUpdateNotice+ * 提供;未传时文字链整体不渲染。+ */+ onOpenVersionNotice?: (version: string) => void;}-export function UpdateBanner({ isCollapsed }: UpdateBannerProps) {+export function UpdateBanner({ isCollapsed, onOpenVersionNotice }: UpdateBannerProps) {const { status, version, errorCode } = useUpdateStatus();// 用户主动关闭态(仅本次进程内存,由 UserInfoSection 的火焰按钮唤回)。// status/version 变化时下面 effect 会自动 restore,新一版更新到达时 banner@@ -62,6 +80,8 @@ export function UpdateBanner({ isCollapsed }: UpdateBannerProps) {const { t } = useTranslation();const [showSpawnFailedDialog, setShowSpawnFailedDialog] = useState(false);+ // 待安装版本的公告在 CDN 上是否可用 —— 决定文字链是否渲染。+ const [hasNotes, setHasNotes] = useState(false);// Show the translocated fallback dialog when the main process reports// the app is running from a read-only App Translocation path.@@ -104,6 +124,30 @@ export function UpdateBanner({ isCollapsed }: UpdateBannerProps) {}}, [confirming]);+ // 公告可用性探测。只对 ready 态的具体版本做 —— superseding 时的 version 指向的是+ // 上一个已就绪补丁,不是正在下载的新版,拿它探测会给出错版本的入口。+ // fetchReleaseNotes 在 renderer + main 两层都有缓存,所以这次探测同时也是预热:+ // 用户真点开时命中缓存,不会再打一次 CDN。+ //+ // 两条刻意的收窄:+ // - 收起 / rail 态不渲染文字链,那就别探测;展开时 isCollapsed 变化会让 effect+ // 重跑,该探测的时候一定会探测到。+ // - 依赖里用 canOpenNotice 这个布尔量而不是回调本身 —— 回调来自 useUpdateNotice+ // 的 useCallback([t, open]),弹窗每次开关都会换掉它的 identity,直接依赖函数会+ // 让探测跟着弹窗开关反复重跑。+ const canOpenNotice = Boolean(onOpenVersionNotice);+ useEffect(() => {+ if (status !== 'ready' || !version || !canOpenNotice || isCollapsed) {+ setHasNotes(false);+ return;+ }+ let cancelled = false;+ fetchReleaseNotes(version)+ .then((notes) => { if (!cancelled) setHasNotes(notes !== null); })+ .catch(() => { if (!cancelled) setHasNotes(false); });+ return () => { cancelled = true; };+ }, [status, version, canOpenNotice, isCollapsed]);+// 取消:先打标记再复位,让上面的 effect 在入口按钮重新挂载后把焦点还回去。const handleCancelConfirm = () => {restoreFocusRef.current = true;@@ -149,6 +193,12 @@ export function UpdateBanner({ isCollapsed }: UpdateBannerProps) {window.open(websiteUrl(), '_blank');};+ // 文字链要显示的版本 —— undefined 即不显示。ready 态之外(superseding / error)没有+ // 可信版本号,confirming 态则刻意让位给两步确认。hasNotes 已经蕴含「ready + 该版本+ // 公告可渲染」,这里再显式列出条件,读代码时不必回溯 effect。+ const notesVersion =+ status === 'ready' && !confirming && hasNotes && version ? version : undefined;+const versionSuffix = version ? ` (v${version})` : '';const versionForAria = version ?? 'latest';@@ -297,14 +347,30 @@ export function UpdateBanner({ isCollapsed }: UpdateBannerProps) {: t('update.banner.title', { version: version ?? '…' })}</p>- {/* Subtitle */}- <p className="text-xs text-sidebar-muted">- {isPreparing- ? t('update.banner.preparingSubtitle')- : confirming- ? t('update.banner.confirmHint')- : t('update.banner.subtitle')}- </p>+ {/* Subtitle + 「查看更新公告」文字链 —— 同一视觉组(gap-1),所以链接读作副标题的+ 延伸而不是第三段独立文案;没有链接时这个 wrapper 只有一个子元素,布局与+ 加链接前完全一致。 */}+ <div className="flex flex-col items-center gap-1">+ <p className="text-xs text-sidebar-muted">+ {isPreparing+ ? t('update.banner.preparingSubtitle')+ : confirming+ ? t('update.banner.confirmHint')+ : t('update.banner.subtitle')}+ </p>+ {notesVersion && (+ <button+ onClick={() => onOpenVersionNotice?.(notesVersion)}+ aria-label={t('update.banner.viewNotesAria', { version: notesVersion })}+ className={cn(+ 'rounded-full text-xs underline underline-offset-2',+ 'text-sidebar-muted transition-colors hover:text-foreground',+ )}+ >+ {t('update.banner.viewNotes')}+ </button>+ )}+ </div>{/* Actions.- superseding: disabled pill + spinner.diff --git a/apps/desktop/src/renderer/hooks/useUpdateNotice.ts b/apps/desktop/src/renderer/hooks/useUpdateNotice.tsindex c43808b80d..96d87195b1 100644--- a/apps/desktop/src/renderer/hooks/useUpdateNotice.ts+++ b/apps/desktop/src/renderer/hooks/useUpdateNotice.ts@@ -22,6 +22,15 @@ const STORAGE_KEY = 'xdt-maker:lastReadVersion';*/const MAX_AGGREGATED_VERSIONS = 5;+/**+ * How long the pre-install preview waits for the version index before opening+ * with the pending version alone. The index contributes only the *in-between*+ * blocks of a multi-version jump; a slow or unreachable CDN must not turn the+ * banner's link into a dead click for the full request timeout (15s in+ * `releaseNotesService`).+ */+const PREVIEW_INDEX_BUDGET_MS = 3000;+/** Numeric semver comparison. Returns >0 if a > b, <0 if a < b, 0 if equal. */function cmpVersion(a: string, b: string): number {const pa = a.split('.').map(Number);@@ -47,6 +56,22 @@ function cmpVersion(a: string, b: string): number {* visible version + doubles as a dropdown to jump to any version.* Dismissal does NOT touch lastReadVersion (manual look-back* must not suppress the next real upgrade popup).+ *+ * `onOpenVersion(pending)` is a third entry point — the sidebar UpdateBanner+ * previewing an update that is downloaded but **not installed yet**. It reuses+ * the `auto` layout contract verbatim (pre-loaded blocks, `v旧 → v新` badge,+ * version count, no lazy history, no version jumper) because it carries the+ * same shape of payload: an aggregated diff range. The only difference is which+ * range — auto covers `(lastRead, appVersion]`, preview covers+ * `(appVersion, pending]`, so a user who skipped several releases sees every+ * version the restart will jump over, and a plain one-version bump sees one+ * block.+ *+ * Two things it deliberately does NOT do: attach the installed version or its+ * back-catalogue (that's the flame icon's job — `onOpen`), and advance+ * `lastReadVersion` on dismiss (that would swallow the real popup after the+ * restart). The read-marker, not `mode`, is what governs the latter — see+ * `readMarkerRef`.*/export type UpdateNoticeMode = 'auto' | 'manual';@@ -80,6 +105,17 @@ export interface UseUpdateNoticeReturn {dismiss: () => void;/** Manually open the dialog for a lazy full-history review. */onOpen: () => void;+ /**+ * Open the dialog as a pre-install preview of `pendingVersion`: that version+ * plus every version between it and the installed one, aggregated in the+ * `auto` layout. Dismissal does not touch `lastReadVersion`.+ *+ * No fallback to a different version: if `pendingVersion`'s own notes can't+ * be fetched we toast and stay closed rather than answering a question the+ * user didn't ask. Callers should gate their entry point on a successful+ * `fetchReleaseNotes` probe so this stays an edge case.+ */+ onOpenVersion: (pendingVersion: string) => void;}/**@@ -112,6 +148,36 @@ function versionsToFetch(return index.slice(lastIdx + 1, curIdx + 1);}+/**+ * Build the pre-install preview range for `onOpenVersion`: every version the+ * user is about to jump over, i.e. index entries in `(appVersion, pending]`,+ * ascending, plus `pending` itself.+ *+ * Deliberately excludes `appVersion` and everything older — the question is+ * "what do I get by restarting", not "what has ever shipped". Skipping several+ * releases therefore yields several blocks; a normal one-version bump yields+ * exactly one.+ *+ * - Index unreachable → just `[pending]`; the dialog still opens with the one+ * block that matters.+ * - `pending` not in the index yet (CDN publishes the notice and the index+ * separately, so there is a window) → appended anyway. It is the version the+ * caller already probed successfully.+ * - Capped to the newest `MAX_AGGREGATED_VERSIONS` for the same reason auto+ * mode is: nobody reads 30 blocks, and each one is a CDN round-trip.+ */+function versionsToPreview(+ index: string[] | null,+ appVersion: string,+ pending: string,+): string[] {+ const inRange = (index ?? []).filter(+ (v) => cmpVersion(v, appVersion) > 0 && cmpVersion(v, pending) <= 0,+ );+ if (!inRange.includes(pending)) inRange.push(pending);+ return inRange.slice(-MAX_AGGREGATED_VERSIONS);+}+/*** Build the manual-mode full-history list: everything in the CDN index up to* (and including) appVersion, reversed to newest-first for UI convenience.@@ -302,10 +368,81 @@ export function useUpdateNotice(): UseUpdateNoticeReturn {});}, [t, open]);+ const onOpenVersion = useCallback((pendingVersion: string) => {+ // `open` is state, so two clicks in the same tick both read `false` and both+ // fan out to the CDN. `dialogOpenedRef` is set synchronously below and stays+ // true until dismiss (or a failed attempt), so it is the re-entrancy guard+ // that actually holds for a double-clicked text link.+ if (open || dialogOpenedRef.current) return;+ if (dismissTimerRef.current !== null) {+ clearTimeout(dismissTimerRef.current);+ dismissTimerRef.current = null;+ }+ dialogOpenedRef.current = true;+ const appVersion = window.electronAPI.appVersion;++ (async () => {+ // 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);+ // 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 —+ // the same degradation `versionsToPreview` already does for a null index.+ const index = await Promise.race([+ fetchReleaseNotesIndex(),+ new Promise<null>((resolve) => {+ setTimeout(() => resolve(null), PREVIEW_INDEX_BUDGET_MS);+ }),+ ]);+ const targets = versionsToPreview(index, appVersion, pendingVersion);+ const results = await Promise.all(+ targets.map((v) => (v === pendingVersion ? pendingNotes : fetchReleaseNotes(v))),+ );+ const notes = results.filter((n): n is ReleaseNotes => n !== null);++ // The pending version's own notes are the point of this dialog — if only+ // the in-between ones loaded, we'd be answering a question the user+ // didn't ask. Bail (the banner's probe makes this a rare CDN race).+ if (!notes.some((n) => n.version === pendingVersion)) {+ dialogOpenedRef.current = false;+ toast.error(t('logic.toasts.fetchUpdateNoticeFailed'));+ return;+ }++ // Same race guard as onOpen: never clobber an auto popup that has already+ // claimed the dialog with a real read-marker.+ if (readMarkerRef.current !== null) return;++ notes.reverse();+ setMode('auto');+ setReleaseNotes(notes);+ setAllVersions(null);+ // Stays null: dismissing a pre-install preview must NOT advance+ // lastReadVersion, or the real popup after the restart never fires.+ readMarkerRef.current = null;+ setOpen(true);+ })().catch((err) => {+ dialogOpenedRef.current = false;+ log.warn('preview-fetch threw:', err);+ toast.error(t('logic.toasts.fetchUpdateNoticeFailed'));+ });+ }, [t, open]);+const loadVersion = useCallback((version: string) => fetchReleaseNotes(version),[],);- return { open, mode, releaseNotes, allVersions, loadVersion, dismiss, onOpen };+ return {+ open,+ mode,+ releaseNotes,+ allVersions,+ loadVersion,+ dismiss,+ onOpen,+ onOpenVersion,+ };}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex c8a98eb7bf..6adc153181 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -3850,6 +3850,8 @@"banner": {"title": "Updated to {{version}}","subtitle": "Relaunch to apply",+ "viewNotes": "See What's New",+ "viewNotesAria": "See what's new in {{version}}","button": "Relaunch","tooltipReady": "Update ready – click to relaunch{{versionSuffix}}","ariaCollapsed": "Update ready, click to relaunch to version {{version}}",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 7ad5af3030..6d2dc99102 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -3849,6 +3849,8 @@"banner": {"title": "{{version}} に更新済み","subtitle": "再起動して適用",+ "viewNotes": "更新情報を見る",+ "viewNotesAria": "{{version}} の更新情報を見る","button": "再起動","tooltipReady": "更新準備完了 — クリックで再起動{{versionSuffix}}","ariaCollapsed": "更新準備完了、クリックでバージョン {{version}} に再起動",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex c0c454cc7d..63c3adcfc1 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -3849,6 +3849,8 @@"banner": {"title": "{{version}}로 업데이트됨","subtitle": "재시작해 적용",+ "viewNotes": "업데이트 소식 보기",+ "viewNotesAria": "{{version}} 업데이트 소식 보기","button": "재시작","tooltipReady": "업데이트 준비됨 — 클릭해 재시작{{versionSuffix}}","ariaCollapsed": "업데이트 준비됨, 클릭해 버전 {{version}}로 재시작",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex b997982fa0..e208b765fc 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -3849,6 +3849,8 @@"banner": {"title": "已更新到 {{version}}","subtitle": "重启以应用更新",+ "viewNotes": "查看更新公告",+ "viewNotesAria": "查看 {{version}} 的更新公告","button": "立即重启","tooltipReady": "更新已就绪 — 点击重启{{versionSuffix}}","ariaCollapsed": "更新已就绪,点击重启到版本 {{version}}",