diff --git a/architecture/notes/pebrel_app/gpui_shell/workspace/windowing/2026-10-01-installed-notes-visibility.md b/architecture/notes/pebrel_app/gpui_shell/workspace/windowing/2026-10-01-installed-notes-visibility.md new file mode 100644 index 000000000..6b2fd05f0 --- /dev/null +++ b/architecture/notes/pebrel_app/gpui_shell/workspace/windowing/2026-10-01-installed-notes-visibility.md @@ -0,0 +1,43 @@ +# Installed notes wait for a visible window + +## Status + +Implemented; isolated visibility regression passed on all selected native platforms. + +## Context + +The post-install notice is persistent and shown once. A resident first launch can have only a hidden workspace. + +## Evidence + +The original UpdateInstalled dispatch chose an MRU window without inspecting window_hidden, then persisted release_notes_shown before opening its dialog. Quitting before revealing that hidden window could consume a notice the user never saw. + +## Decision + +The update dialog capability owns one pending installed description in App memory. The process shell event dispatcher chooses a live visible workspace before claiming and opening it. Existing pump ticks retry after reveal; a destroyed handle leaves it pending. Failed persistent claims retry after five seconds. No activation or forced reveal is added. + +The complete process shell event dispatcher lives under windowing/shell_events, separately from window creation, transfer, geometry and snapshot responsibilities. Its existing event behavior is preserved. + +## Rejected alternatives + +- A hidden dialog must not count as a visible notice. +- Forcing a background resident window to the foreground would change startup policy. +- A second persisted notice state would duplicate the existing locked updater authority. + +## Consequences + +Only a successful persistent claim for a visible target consumes the pending notice. Process exit before reveal preserves the existing unclaimed update state. The pending payload is App-owned and does not create another worker or persistence format. + +## Validation + +An isolated GPUI regression sends the real installed event while the workspace is hidden, checks that no persistent acknowledgement exists, reveals it, and checks one acknowledgement. Existing rendered-dialog tests cover content and close/Escape. + +PR head e763523db8ad0bbe3a6d053cd11b1e46ee682adf passed all ten required checks. Its macOS ARM native suite passed 2583 tests (24 existing skips); the visibility regression passed in 3.046 seconds. Later cache changes require their own current-head CI result and do not replace this visibility evidence. + +## Supersedes + +None; refines the installed release-notes lifecycle. + +## Revisit when + +Resident window visibility or updater acknowledgement ownership changes. diff --git a/architecture/notes/pebrel_app/update_check/2026-09-30-installed-release-notes.md b/architecture/notes/pebrel_app/update_check/2026-09-30-installed-release-notes.md new file mode 100644 index 000000000..4c57024b1 --- /dev/null +++ b/architecture/notes/pebrel_app/update_check/2026-09-30-installed-release-notes.md @@ -0,0 +1,90 @@ +# Installed release descriptions + +## Status + +Proposed in this PR. + +## Context + +Users need to read the installed version's GitHub Release description in Settings, +and see it once after an in-app update succeeds. A newer release can appear before +that first launch; checking `/latest` cannot identify the installed description. + +## Evidence + +`update_check.rs` already parses the Release body for checksums but discards it. +`update_download/handoff.rs` records the installer transaction, executable and +result and verifies the running version when recovering the workspace. +`update_state.json` already serializes prompt preferences with process/file locks. +The GPUI component `TextView` already renders selectable Markdown in the product. + +The initial single-file cache could lose a pending release when Settings fetched +the installed version before handoff preparation; an offline first launch then +had no matching snapshot. Concurrent version writes also cannot share a replacing file. + +## Decision + +Retain the Release body as separate updater metadata. Cache it during a successful +update check, then snapshot the matching version in the existing handoff directory +before authorizing installation. This adds no installation authority or helper +protocol field. Missing cached notes do not prevent installation. + +Cache each version in its own atomic file keyed by a SHA-256 digest of the version, +using the existing digest dependency. Version strings cannot escape the updater +directory, and installed-version reads do not evict pending-update metadata. +The old single-file cache remains an exact-version read fallback for compatibility; +new writes use only version-keyed files. Handoff snapshots keep their existing format. + +On startup require a successful result matching the transaction, installation and +running version. Load the snapshot, or fetch that exact version's tag when no +snapshot exists. Failed/offline reads leave the notice pending for a later launch. +Claim the notice with the existing prompt-state process/file locks before showing +it in the selected window. The optional `release_notes_shown` field defaults to +unset for existing state files and is independent of update snooze/skip settings. + +Settings and the dialog share a read-only Markdown view with loading, empty, +failure/retry and external-release states. Remote descriptions are rendered as +content; only HTTP(S) links are opened by the view. Settings remain available on +externally managed distributions; their updates do not create in-app handoffs. + +## Rejected alternatives + +- Inferring success from a changed version: also triggers on fresh installs, + manual installs and failed updates followed by a rollback. +- Showing the latest description: can describe a version not yet installed. +- Using the workspace restore acknowledgement: restoration and reading notes have + independent lifecycles; an offline metadata fetch must not consume the notice. +- A second rich-text renderer or dependency: the existing TextView is sufficient. + +## Consequences + +Release text is stored under the existing updater directory, outside user +settings. No new thread is added; discovery uses the existing startup check and +view-owned background tasks. Automatic installation remains Windows/macOS only; +other distributions can read their installed version's notes in Settings. + +Each cached file retains the existing 2 MiB read limit. Retained metadata grows +with distinct versions rather than requests; pruning must preserve pending update +notes and is separate from correcting version isolation. + +The shown marker gives at-most-once presentation across normal restarts and +concurrent processes. As with existing update prompts, a crash after persisting +that marker but before painting can consume the notice; Settings still exposes it. + +## Validation + +Focused regressions cover exact-version text, persisted snapshots, successful +handoff, duplicate claims, rollback exclusion and existing workspace recovery. +PR evidence records compilation, rendered UI checks and native CI separately. +The cache regression reproduces a pending update followed by an installed-version +Settings read, then verifies an offline handoff snapshot. Compatibility and +untrusted version-path cases exercise the same production cache helpers. + +## Supersedes + +None. + +## Revisit when + +The updater accepts another release source, the handoff protocol changes, or +release notes need a user acknowledgement rather than once-only presentation. diff --git a/pebrel_app/i18n/en-US.json b/pebrel_app/i18n/en-US.json index 7029eef56..309e9a47e 100644 --- a/pebrel_app/i18n/en-US.json +++ b/pebrel_app/i18n/en-US.json @@ -213,7 +213,8 @@ "backup": "backup cloud sync export restore webdav s3 sftp 123 nextcloud synology nas r2 minio snapshots", "agents": "agents agent hook hooks claude codex opencode cursor kimi pi omp copilot grok", "mobile": "mobile phone android ios remote pairing qr lan relay", - "plugins": "plugins plugin extension extensions luau install grant generate" + "plugins": "plugins plugin extension extensions luau install grant generate", + "release_notes": "release notes changelog what is new" } }, "opacity": { @@ -1515,7 +1516,13 @@ "later": "Later", "prepare_failed": "Could not prepare the update: {error}. Pebrel will stay open.", "draft_changed": "A document changed while preparing to exit. Save or discard the latest changes, then retry.", - "in_progress": "This installation is being updated. Wait for the update to finish; Pebrel will reopen automatically." + "in_progress": "This installation is being updated. Wait for the update to finish; Pebrel will reopen automatically.", + "release_notes_title": "Release notes", + "release_notes_loading": "Loading release notes…", + "release_notes_failed": "Could not load release notes: {error}", + "release_notes_retry": "Retry", + "release_notes_empty": "This release has no description.", + "open_release": "Open release" }, "files.filter_placeholder": "Filter files...", "files.match_case": "Match case", diff --git a/pebrel_app/i18n/ja-JP.json b/pebrel_app/i18n/ja-JP.json index 288ebdda3..154f3d7d1 100644 --- a/pebrel_app/i18n/ja-JP.json +++ b/pebrel_app/i18n/ja-JP.json @@ -44,7 +44,8 @@ "advanced": "詳細設定 セッション トレイ 復元 起動 自動起動 ログイン サイレント", "backup": "バックアップ クラウド 同期 ストレージ エクスポート 復元 スナップショット 資格情報 パスワード", "agents": "エージェント フック 連携", - "mobile": "モバイル スマートフォン スマホ リモート ペアリング QRコード ローカルネットワーク リレー ネットワークアダプター 閲覧専用 通知" + "mobile": "モバイル スマートフォン スマホ リモート ペアリング QRコード ローカルネットワーク リレー ネットワークアダプター 閲覧専用 通知", + "release_notes": "リリースノート 更新内容 変更履歴" } }, "opacity": { diff --git a/pebrel_app/i18n/zh-CN.json b/pebrel_app/i18n/zh-CN.json index d984b1849..cd3248d3c 100644 --- a/pebrel_app/i18n/zh-CN.json +++ b/pebrel_app/i18n/zh-CN.json @@ -213,7 +213,8 @@ "backup": "云备份 云同步 云存储 备份 导出 恢复 坚果云 123云盘 群晖 快照", "agents": "智能体 钩子 接入", "mobile": "手机 远程 配对 二维码 局域网 中转 网卡 只看 手机通知", - "plugins": "插件 扩展 安装 授权 生成 plugins plugin luau" + "plugins": "插件 扩展 安装 授权 生成 plugins plugin luau", + "release_notes": "更新内容 更新日志 版本说明" } }, "opacity": { @@ -1515,7 +1516,13 @@ "later": "稍后", "prepare_failed": "更新准备失败:{error}。Pebrel 将保持打开。", "draft_changed": "准备退出期间文档发生了变化。请保存或放弃最新修改后重试。", - "in_progress": "当前安装正在更新,请等待更新完成,Pebrel 随后会自动重新打开。" + "in_progress": "当前安装正在更新,请等待更新完成,Pebrel 随后会自动重新打开。", + "release_notes_title": "更新内容", + "release_notes_loading": "正在加载更新内容…", + "release_notes_failed": "无法加载更新内容:{error}", + "release_notes_retry": "重试", + "release_notes_empty": "此版本未提供更新说明。", + "open_release": "打开发布页" }, "files.filter_placeholder": "过滤文件...", "files.match_case": "区分大小写", diff --git a/pebrel_app/src/gpui_shell/mod.rs b/pebrel_app/src/gpui_shell/mod.rs index a2eff652e..f91edec57 100644 --- a/pebrel_app/src/gpui_shell/mod.rs +++ b/pebrel_app/src/gpui_shell/mod.rs @@ -38,6 +38,7 @@ mod molecule_view; mod motion; pub mod network_settings; pub mod prelude; +mod release_notes; mod scientific_render; pub mod session_restore; #[cfg(all(test, feature = "gpui-test-support"))] @@ -79,6 +80,7 @@ pub(crate) enum GpuiShellEvent { MuxAttach, RuntimeControl(std::sync::Arc), UpdateAvailable(crate::update_check::UpdateCheckResult), + UpdateInstalled(crate::update_check::release_notes::ReleaseNotes), SshPrompt(std::sync::Arc), OpenDirectories(Vec), ElevatedLaunch(std::sync::Arc), diff --git a/pebrel_app/src/gpui_shell/release_notes.rs b/pebrel_app/src/gpui_shell/release_notes.rs new file mode 100644 index 000000000..07f8745f3 --- /dev/null +++ b/pebrel_app/src/gpui_shell/release_notes.rs @@ -0,0 +1,217 @@ +//! One read-only Markdown view for Settings and the post-install notice. +use gpui::{ + App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, + ParentElement as _, Render, Styled as _, Task, Window, div, px, +}; +use gpui_component::text::{TextView, TextViewState}; + +use super::prelude::*; +use crate::i18n::Message; +use crate::update_check::release_notes::ReleaseNotes; + +pub(super) struct ReleaseNotesView { + text: Option>, + error: Option, + empty: bool, + task: Option>, +} + +impl ReleaseNotesView { + pub(super) fn new(notes: Option, cx: &mut Context) -> Self { + let mut view = Self { text: None, error: None, empty: false, task: None }; + if let Some(notes) = notes { + view.set_notes(notes, cx); + } else { + view.load(cx); + } + view + } + + fn set_notes(&mut self, notes: ReleaseNotes, cx: &mut Context) { + self.empty = notes.body.trim().is_empty(); + self.text = Some(cx.new(|cx| TextViewState::markdown(¬es.body, cx))); + self.error = None; + } + + fn load(&mut self, cx: &mut Context) { + let task = + cx.background_executor().spawn(async { crate::update_check::release_notes::current() }); + self.error = None; + self.task = Some(cx.spawn(async move |this, cx| { + let result = task.await; + let _ = this.update(cx, |view, cx| { + view.task = None; + match result { + Ok(notes) => view.set_notes(notes, cx), + Err(error) => view.error = Some(error), + } + cx.notify(); + }); + })); + cx.notify(); + } +} + +impl Render for ReleaseNotesView { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let language = super::config::ui_language(cx); + let mut body = v_flex().w_full().min_w_0().gap_4().child( + h_flex() + .w_full() + .justify_between() + .items_center() + .gap_2() + .child(div().font_semibold().child(format!("v{}", env!("CARGO_PKG_VERSION")))) + .child( + Button::new("release-notes-github") + .icon(IconName::ExternalLink) + .label(language.text(Message::UpdateOpenRelease)) + .ghost() + .small() + .on_click(|_, _, cx| { + cx.open_url(&format!( + "{}/tag/v{}", + crate::update_check::RELEASES_PAGE, + env!("CARGO_PKG_VERSION") + )) + }), + ), + ); + if self.task.is_some() { + body = body.child( + h_flex() + .gap_2() + .child(Spinner::new().small()) + .child(language.text(Message::UpdateReleaseNotesLoading)), + ); + } else if let Some(error) = &self.error { + body = + body.child(div().text_color(cx.theme().danger).child( + language.format(Message::UpdateReleaseNotesFailed, &[("error", error)]), + )) + .child( + Button::new("release-notes-retry") + .label(language.text(Message::UpdateReleaseNotesRetry)) + .on_click(cx.listener(|view, _, _, cx| view.load(cx))), + ); + } else if self.empty { + body = body.child( + div() + .text_color(cx.theme().muted_foreground) + .child(language.text(Message::UpdateReleaseNotesEmpty)), + ); + } else if let Some(text) = &self.text { + body = body.child( + TextView::new(text) + .w_full() + .min_w_0() + .selectable(true) + .scrollable(false) + .on_link_click(|url, _, _, cx| { + if url.starts_with("https://") || url.starts_with("http://") { + cx.open_url(url); + } + }), + ); + } + body + } +} + +pub(super) fn open_dialog(notes: ReleaseNotes, window: &mut Window, cx: &mut App) { + let view = cx.new(|cx| ReleaseNotesView::new(Some(notes), cx)); + window.open_dialog(cx, move |dialog, window, cx| { + let language = super::config::ui_language(cx); + let height = (f32::from(window.viewport_size().height) - 160.0).clamp(120.0, 440.0); + super::prelude::center_modal_dialog(dialog, window, height + 120.0) + .bg(super::theme::settings_panel_bg(cx)) + .title(language.text(Message::UpdateReleaseNotesTitle)) + .close_button(true) + .overlay_closable(true) + .child( + div().w_full().h(px(height)).overflow_y_scrollbar().child( + div() + .w_full() + .debug_selector(|| "release-notes-content".into()) + .child(view.clone()), + ), + ) + .footer( + DialogFooter::new().child( + DialogClose::new().child( + Button::new("release-notes-close") + .debug_selector(|| "release-notes-close".into()) + .primary() + .label(language.text(Message::CommonClose)), + ), + ), + ) + }); +} + +#[cfg(all(test, feature = "gpui-test-support"))] +mod tests { + use super::*; + use gpui::{TestAppContext, size}; + use gpui_component::{Root, Theme, ThemeMode}; + + struct DialogHost; + + impl Render for DialogHost { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + div().size_full().children(Root::render_dialog_layer(window, cx)) + } + } + + #[gpui::test] + fn installed_notes_render_in_the_dialog_and_close_by_click_or_escape(cx: &mut TestAppContext) { + cx.update(|cx| { + gpui_component::init(cx); + cx.set_reduce_motion(true); + }); + let (_, cx) = cx.add_window_view(|window, cx| { + let host = cx.new(|_| DialogHost); + Root::new(host, window, cx) + }); + for (theme, mode) in [ + (pebrel_settings::ThemeName::Nord, ThemeMode::Dark), + (pebrel_settings::ThemeName::LinenLight, ThemeMode::Light), + ] { + cx.update(|window, cx| { + let runtime = pebrel_settings::RuntimeSettings::from_raw( + &pebrel_settings::RawSettings::default(), + ); + cx.set_global(crate::gpui_shell::config::Settings::load_with_runtime( + theme, runtime, + )); + Theme::change(mode, Some(window), cx); + }); + for width in [420.0, 900.0] { + cx.simulate_resize(size(px(width), px(620.0))); + cx.update(|window, cx| open_dialog(ReleaseNotes { + version: env!("CARGO_PKG_VERSION").into(), + body: "# Changes\n\n**Bold**, `inline`, [release](https://github.com/Kuddev/pebrel)\n\n- Item\n\n```sh\npwd\n```\n\n| A | B |\n| - | - |\n| 1 | 2 |\n".repeat(8), + }, window, cx)); + cx.run_until_parked(); + cx.update(|window, cx| { + let _ = window.draw(cx); + }); + let close = cx.debug_bounds("release-notes-close").expect("visible close action"); + let content = cx.debug_bounds("release-notes-content").expect("rendered Markdown"); + assert!(content.size.width > px(0.0)); + assert!(content.size.width <= px(width)); + assert!(close.origin.y >= px(0.0) && close.bottom() <= px(620.0)); + if width == 420.0 { + cx.simulate_click(close.center(), gpui::Modifiers::default()); + } else { + cx.simulate_keystrokes("escape"); + } + cx.run_until_parked(); + cx.update(|window, cx| { + let _ = window.draw(cx); + }); + assert!(cx.debug_bounds("release-notes-content").is_none()); + } + } + } +} diff --git a/pebrel_app/src/gpui_shell/settings_pane.rs b/pebrel_app/src/gpui_shell/settings_pane.rs index 73e5e462a..0232b5e35 100644 --- a/pebrel_app/src/gpui_shell/settings_pane.rs +++ b/pebrel_app/src/gpui_shell/settings_pane.rs @@ -143,6 +143,7 @@ pub struct SettingsPane { about_update: AboutUpdateState, about_update_seq: u64, about_last_checked: Option, + release_notes: Option>, /// 首页「项目与支持」→ 赞助商:独立页面,不是外链行。切换分区时清掉。 about_sponsor_open: bool, settings_search_input: Entity, @@ -1597,6 +1598,12 @@ impl SettingsPane { 10 => self.section_agents(window, cx), MOBILE_SECTION => self.section_mobile(window, cx), PLUGINS_SECTION => self.section_plugins(window, cx), + RELEASE_NOTES_SECTION => { + let view = self.release_notes.get_or_insert_with(|| { + cx.new(|cx| super::release_notes::ReleaseNotesView::new(None, cx)) + }); + div().w_full().child(view.clone()) + }, _ => self.section_backup(window, cx), } .into_any_element() diff --git a/pebrel_app/src/gpui_shell/settings_pane/about.rs b/pebrel_app/src/gpui_shell/settings_pane/about.rs index d82abeff6..c489d3f57 100644 --- a/pebrel_app/src/gpui_shell/settings_pane/about.rs +++ b/pebrel_app/src/gpui_shell/settings_pane/about.rs @@ -301,11 +301,15 @@ impl SettingsPane { REPOSITORY_URL.to_owned(), cx, )) - .child(Self::about_action_row( + .child(Self::about_page_row( "about-releases", IconName::BookOpen, language.text(crate::i18n::Message::SettingsAboutReleaseNotes), - crate::update_check::RELEASES_PAGE.to_owned(), + cx.listener(|this, _, _, cx| { + this.active_section = RELEASE_NOTES_SECTION; + this.about_sponsor_open = false; + cx.notify(); + }), cx, )) .child(Self::about_page_row( diff --git a/pebrel_app/src/gpui_shell/settings_pane/initialization.rs b/pebrel_app/src/gpui_shell/settings_pane/initialization.rs index 2591ce79d..2d4a14eee 100644 --- a/pebrel_app/src/gpui_shell/settings_pane/initialization.rs +++ b/pebrel_app/src/gpui_shell/settings_pane/initialization.rs @@ -703,6 +703,7 @@ impl SettingsPane { about_update: AboutUpdateState::Idle, about_update_seq: 0, about_last_checked: None, + release_notes: None, about_sponsor_open: false, settings_search_input, settings_search_focus: search_header::SearchFocus::default(), diff --git a/pebrel_app/src/gpui_shell/settings_pane/navigation.rs b/pebrel_app/src/gpui_shell/settings_pane/navigation.rs index 9d663ceed..305ce5d53 100644 --- a/pebrel_app/src/gpui_shell/settings_pane/navigation.rs +++ b/pebrel_app/src/gpui_shell/settings_pane/navigation.rs @@ -9,7 +9,8 @@ pub(super) const BUG_REPORT_TEMPLATE: &str = "bug_report.yml"; /// 稳定路由只追加;视觉顺序独立放在 NAV_GROUPS,避免旧入口指向另一页。 pub(super) const MOBILE_SECTION: usize = 11; pub(super) const PLUGINS_SECTION: usize = 12; -pub(super) const SECTION_IDS: [&str; 13] = [ +pub(super) const RELEASE_NOTES_SECTION: usize = 13; +pub(super) const SECTION_IDS: [&str; 14] = [ "application", "appearance", "profiles", @@ -23,11 +24,12 @@ pub(super) const SECTION_IDS: [&str; 13] = [ "agents", "mobile", "plugins", + "release-notes", ]; /// Catalog search aliases for each stable section route. English and Chinese /// remain searchable in every locale alongside the current language. -pub(super) const SECTION_SEARCH_TERMS: [crate::i18n::Message; 13] = [ +pub(super) const SECTION_SEARCH_TERMS: [crate::i18n::Message; 14] = [ crate::i18n::Message::SettingsSearchTermsApplication, crate::i18n::Message::SettingsSearchTermsAppearance, crate::i18n::Message::SettingsSearchTermsProfiles, @@ -41,6 +43,7 @@ pub(super) const SECTION_SEARCH_TERMS: [crate::i18n::Message; 13] = [ crate::i18n::Message::SettingsSearchTermsAgents, crate::i18n::Message::SettingsSearchTermsMobile, crate::i18n::Message::SettingsSearchTermsPlugins, + crate::i18n::Message::SettingsSearchTermsReleaseNotes, ]; /// 保留原来的分组展开顺序,组名不再渲染;数组里仍保存稳定的 [`SECTION_IDS`] @@ -48,7 +51,7 @@ pub(super) const SECTION_SEARCH_TERMS: [crate::i18n::Message; 13] = [ pub(super) const NAV_GROUPS: [(&str, &[usize]); 3] = [ ("workspace", &[0, 1, 2, 10, PLUGINS_SECTION, 6, 7]), ("connections", &[3, 4, 5, MOBILE_SECTION]), - ("system", &[8, 9]), + ("system", &[8, 9, RELEASE_NOTES_SECTION]), ]; pub(super) fn section_label(index: usize, language: crate::display::UiLanguage) -> &'static str { @@ -66,6 +69,7 @@ pub(super) fn section_label(index: usize, language: crate::display::UiLanguage) Some("agents") => language.text(crate::i18n::Message::SettingsSidebarAgents), Some("mobile") => language.text(crate::i18n::Message::MobileTitle), Some("plugins") => language.text(crate::i18n::Message::SettingsSidebarPlugins), + Some("release-notes") => language.text(crate::i18n::Message::UpdateReleaseNotesTitle), _ => "", } } @@ -238,6 +242,7 @@ pub(super) fn section_icon(index: usize) -> SharedString { 10 => IconName::Bot.path(), MOBILE_SECTION => crate::gpui_shell::assets::nav::PHONE.into(), PLUGINS_SECTION => crate::gpui_shell::assets::nav::PUZZLE.into(), + RELEASE_NOTES_SECTION => IconName::BookOpen.path(), _ => IconName::Inbox.path(), } } diff --git a/pebrel_app/src/gpui_shell/settings_pane/search_header.rs b/pebrel_app/src/gpui_shell/settings_pane/search_header.rs index 6a3bb789c..f7d0af412 100644 --- a/pebrel_app/src/gpui_shell/settings_pane/search_header.rs +++ b/pebrel_app/src/gpui_shell/settings_pane/search_header.rs @@ -266,6 +266,8 @@ mod tests { let en = crate::display::UiLanguage::EnUs; let zh = crate::display::UiLanguage::ZhCn; assert_eq!(matching_sections(" FONT ", en), vec![1]); + assert_eq!(matching_sections("release notes", en), vec![RELEASE_NOTES_SECTION]); + assert_eq!(matching_sections("更新内容", zh), vec![RELEASE_NOTES_SECTION]); assert_eq!(matching_sections("字体", zh), vec![1]); assert_eq!(matching_sections("quick terminal", en), vec![7]); assert_eq!(matching_sections("clod backup", en), vec![9]); diff --git a/pebrel_app/src/gpui_shell/settings_pane/tests.rs b/pebrel_app/src/gpui_shell/settings_pane/tests.rs index 88b688f84..24208718b 100644 --- a/pebrel_app/src/gpui_shell/settings_pane/tests.rs +++ b/pebrel_app/src/gpui_shell/settings_pane/tests.rs @@ -511,7 +511,7 @@ fn settings_nav_hides_providers_without_changing_stable_routes() { let visibility: Vec<_> = (0..SECTION_IDS.len()).map(is_nav_section_visible).collect(); assert_eq!( visibility, - vec![true, true, true, false, true, true, true, true, true, true, true, true, true] + vec![true, true, true, false, true, true, true, true, true, true, true, true, true, true] ); assert!(!is_nav_section_visible(SECTION_IDS.len())); assert!(!is_nav_section_visible(usize::MAX)); @@ -531,6 +531,7 @@ fn settings_nav_hides_providers_without_changing_stable_routes() { "agents", "mobile", "plugins", + "release-notes", ] ); } @@ -577,7 +578,7 @@ fn hidden_provider_navigation_keeps_prediction_search_reachable(cx: &mut gpui::T #[test] fn settings_nav_starts_with_application_then_frequent_options() { let visible: Vec<_> = visible_nav_sections().collect(); - assert_eq!(visible, vec![0, 1, 2, 10, PLUGINS_SECTION, 6, 7, 4, 5, 11, 8, 9]); + assert_eq!(visible, vec![0, 1, 2, 10, PLUGINS_SECTION, 6, 7, 4, 5, 11, 8, 9, RELEASE_NOTES_SECTION]); let zh_labels: Vec<_> = visible .iter() .map(|index| section_label(*index, crate::display::UiLanguage::ZhCn)) @@ -596,7 +597,8 @@ fn settings_nav_starts_with_application_then_frequent_options() { "网络", "手机远程", "高级", - "备份" + "备份", + "更新内容" ] ); let en_labels: Vec<_> = visible @@ -618,6 +620,7 @@ fn settings_nav_starts_with_application_then_frequent_options() { "Phone Remote", "Advanced", "Backup", + "Release notes", ] ); } diff --git a/pebrel_app/src/gpui_shell/workspace.rs b/pebrel_app/src/gpui_shell/workspace.rs index f2abc0f11..84ed818d2 100644 --- a/pebrel_app/src/gpui_shell/workspace.rs +++ b/pebrel_app/src/gpui_shell/workspace.rs @@ -105,7 +105,7 @@ mod window_titlebar; pub(crate) mod windowing; // 调用点分散在设置页与窗口层,原样再导出以免拆分波及它们。 -pub(crate) use update_dialog::{open_update_dialog, show_update_notification}; +pub(crate) use update_dialog::open_update_dialog; use tab_drag::{DockTarget, TabDrag, TabDragAxis}; diff --git a/pebrel_app/src/gpui_shell/workspace/residency.rs b/pebrel_app/src/gpui_shell/workspace/residency.rs index 8b8d5d320..646105905 100644 --- a/pebrel_app/src/gpui_shell/workspace/residency.rs +++ b/pebrel_app/src/gpui_shell/workspace/residency.rs @@ -147,6 +147,7 @@ impl NebulaWorkspace { // 更新通知由进程级 windowing dispatcher 选择 MRU 窗口;这个 // 旧的 workspace-local 分发器没有 Window,不能在此打开 Dialog。 GpuiShellEvent::UpdateAvailable(_) + | GpuiShellEvent::UpdateInstalled(_) | GpuiShellEvent::SshPrompt(_) | GpuiShellEvent::OpenDirectories(_) => {}, } diff --git a/pebrel_app/src/gpui_shell/workspace/update_dialog.rs b/pebrel_app/src/gpui_shell/workspace/update_dialog.rs index 4fec14808..01c19ef04 100644 --- a/pebrel_app/src/gpui_shell/workspace/update_dialog.rs +++ b/pebrel_app/src/gpui_shell/workspace/update_dialog.rs @@ -5,6 +5,7 @@ use super::*; +use crate::gpui_shell::GpuiShellEvent; use crate::i18n::Message; use crate::update_download::DownloadStatus; @@ -17,6 +18,51 @@ fn update_dialog_frame(dialog: Dialog, window: &Window, estimated_height: f32, c .bg(crate::gpui_shell::theme::settings_panel_bg(cx)) } +pub(super) fn show_update_event(event: GpuiShellEvent, window: &mut Window, cx: &mut App) { + match event { + GpuiShellEvent::UpdateAvailable(result) => show_update_notification(result, window, cx), + GpuiShellEvent::UpdateInstalled(notes) => queue_installed_notes(notes, cx), + _ => unreachable!(), + } +} + +struct PendingInstalledNotes { + notes: Option, + retry_after: std::time::Instant, +} + +impl gpui::Global for PendingInstalledNotes {} + +pub(super) fn queue_installed_notes( + notes: crate::update_check::release_notes::ReleaseNotes, + cx: &mut App, +) { + cx.set_global(PendingInstalledNotes { + notes: Some(notes), + retry_after: std::time::Instant::now(), + }); +} + +pub(super) fn has_pending_installed_notes(cx: &App) -> bool { + cx.try_global::().is_some_and(|pending| { + pending.notes.is_some() && std::time::Instant::now() >= pending.retry_after + }) +} + +pub(super) fn show_pending_installed_notes(window: &mut Window, cx: &mut App) { + let Some(notes) = cx.global_mut::().notes.take() else { return }; + match crate::update_check::release_notes::claim(¬es.version) { + Ok(true) => crate::gpui_shell::release_notes::open_dialog(notes, window, cx), + Ok(false) => {}, + Err(error) => { + log::warn!("Could not acknowledge installed release notes: {error}"); + let pending = cx.global_mut::(); + pending.notes = Some(notes); + pending.retry_after = std::time::Instant::now() + std::time::Duration::from_secs(5); + }, + } +} + struct UpdateNotification; /// 自动检查只在右下角提示,不抢终端焦点;默认常驻,也遵循通知时长设置。 diff --git a/pebrel_app/src/gpui_shell/workspace/windowing.rs b/pebrel_app/src/gpui_shell/workspace/windowing.rs index c0986a7e8..c5ffc956e 100644 --- a/pebrel_app/src/gpui_shell/workspace/windowing.rs +++ b/pebrel_app/src/gpui_shell/workspace/windowing.rs @@ -208,6 +208,9 @@ fn runtime_window_policy(command: &RuntimeCommand) -> RuntimeWindowPolicy { } } +mod shell_events; +pub(crate) use shell_events::dispatch_shell_events; + pub(crate) struct WindowRegistry { next_window_id: u64, activation_sequence: u64, @@ -774,76 +777,6 @@ fn route_entry(command: &RuntimeCommand, cx: &mut App) -> Result, cx: &mut App) { - for event in events { - match event { - GpuiShellEvent::NotificationFocus(pane_id) => focus_notification(pane_id, cx), - GpuiShellEvent::NotificationChoice { pane_id, request_id, choice } => { - let feedback = entry_with_pane(pane_id, cx).map(|entry| entry.handle); - crate::gpui_shell::toast::reply_to_choice( - pane_id, request_id, choice, feedback, cx, - ); - }, - GpuiShellEvent::TrayFocus(pane_id) => { - let target = - pane_id.and_then(|pane_id| entry_with_pane(pane_id, cx)).or_else(|| { - select_mru_window( - pebrel_settings::RuntimeSettings::load().windowing_behavior, - cx, - ) - }); - if let Some(entry) = target { - focus_entry(&entry, pane_id, cx); - } - }, - GpuiShellEvent::TrayQuit => { - quit_all(cx); - return; - }, - GpuiShellEvent::MuxAttach => { - if let Some(entry) = entries_by_mru(cx).into_iter().next() { - focus_entry(&entry, None, cx); - } - }, - GpuiShellEvent::RuntimeControl(dispatch) => dispatch_runtime(dispatch, cx), - GpuiShellEvent::ElevatedLaunch(request) => elevated_launch::dispatch(request, cx), - GpuiShellEvent::UpdateAvailable(result) => { - let Some(entry) = entries_by_mru(cx).into_iter().next() else { continue }; - let _ = entry.handle.update(cx, move |_, window, cx| { - super::show_update_notification(result, window, cx); - }); - }, - GpuiShellEvent::SshPrompt(request) => { - let Some(entry) = entries_by_mru(cx).into_iter().next() else { - request.respond(crate::ssh_prompt::PromptResponse::Cancel); - continue; - }; - let pending = request.clone(); - if entry - .handle - .update(cx, move |_, window, cx| { - super::ssh_dialog::show(pending, window, cx); - }) - .is_err() - { - request.respond(crate::ssh_prompt::PromptResponse::Cancel); - } - }, - GpuiShellEvent::OpenDirectories(urls) => { - for url in urls { - let Some(path) = crate::file_uri::file_uri_to_local_path(&url) else { - continue; - }; - if let Err(error) = open_new_window(cx, Some(path)) { - log::warn!("Could not open a desktop folder: {error}"); - } - } - }, - } - } - publish_runtime_snapshot(cx); -} - pub(crate) fn dispatch_ai_events(events: Vec, cx: &mut App) { let mut handled = false; for event in crate::ai_hook::reorder_batch(events) { diff --git a/pebrel_app/src/gpui_shell/workspace/windowing/shell_events.rs b/pebrel_app/src/gpui_shell/workspace/windowing/shell_events.rs new file mode 100644 index 000000000..7784b25e7 --- /dev/null +++ b/pebrel_app/src/gpui_shell/workspace/windowing/shell_events.rs @@ -0,0 +1,85 @@ +//! Process-level shell events select live windows and defer installed notes until visible. +use super::super::{ssh_dialog, update_dialog}; +use super::*; + +pub(crate) fn dispatch_shell_events(events: Vec, cx: &mut App) { + for event in events { + match event { + GpuiShellEvent::NotificationFocus(pane_id) => focus_notification(pane_id, cx), + GpuiShellEvent::NotificationChoice { pane_id, request_id, choice } => { + let feedback = entry_with_pane(pane_id, cx).map(|entry| entry.handle); + crate::gpui_shell::toast::reply_to_choice( + pane_id, request_id, choice, feedback, cx, + ); + }, + GpuiShellEvent::TrayFocus(pane_id) => { + let target = + pane_id.and_then(|pane_id| entry_with_pane(pane_id, cx)).or_else(|| { + select_mru_window( + pebrel_settings::RuntimeSettings::load().windowing_behavior, + cx, + ) + }); + if let Some(entry) = target { + focus_entry(&entry, pane_id, cx); + } + }, + GpuiShellEvent::TrayQuit => { + quit_all(cx); + return; + }, + GpuiShellEvent::MuxAttach => { + if let Some(entry) = entries_by_mru(cx).into_iter().next() { + focus_entry(&entry, None, cx); + } + }, + GpuiShellEvent::RuntimeControl(dispatch) => dispatch_runtime(dispatch, cx), + GpuiShellEvent::ElevatedLaunch(request) => elevated_launch::dispatch(request, cx), + GpuiShellEvent::UpdateInstalled(notes) => { + update_dialog::queue_installed_notes(notes, cx); + }, + event @ GpuiShellEvent::UpdateAvailable(_) => { + let Some(entry) = entries_by_mru(cx).into_iter().next() else { continue }; + let _ = entry.handle.update(cx, move |_, window, cx| { + update_dialog::show_update_event(event, window, cx); + }); + }, + GpuiShellEvent::SshPrompt(request) => { + let Some(entry) = entries_by_mru(cx).into_iter().next() else { + request.respond(crate::ssh_prompt::PromptResponse::Cancel); + continue; + }; + let pending = request.clone(); + if entry + .handle + .update(cx, move |_, window, cx| { + ssh_dialog::show(pending, window, cx); + }) + .is_err() + { + request.respond(crate::ssh_prompt::PromptResponse::Cancel); + } + }, + GpuiShellEvent::OpenDirectories(urls) => { + for url in urls { + let Some(path) = crate::file_uri::file_uri_to_local_path(&url) else { + continue; + }; + if let Err(error) = open_new_window(cx, Some(path)) { + log::warn!("Could not open a desktop folder: {error}"); + } + } + }, + } + } + if update_dialog::has_pending_installed_notes(cx) + && let Some(entry) = entries_by_mru(cx).into_iter().find(|entry| { + entry.workspace.upgrade().is_some_and(|workspace| !workspace.read(cx).window_hidden) + }) + { + let _ = entry.handle.update(cx, |_, window, cx| { + update_dialog::show_pending_installed_notes(window, cx); + }); + } + publish_runtime_snapshot(cx); +} diff --git a/pebrel_app/src/gpui_shell/workspace/windowing/transfer_tests.rs b/pebrel_app/src/gpui_shell/workspace/windowing/transfer_tests.rs index 6125ff04c..a0b14b0e4 100644 --- a/pebrel_app/src/gpui_shell/workspace/windowing/transfer_tests.rs +++ b/pebrel_app/src/gpui_shell/workspace/windowing/transfer_tests.rs @@ -112,6 +112,64 @@ fn moving_one_of_two_tabs_preserves_source_and_identity(cx: &mut TestAppContext) }); } +#[gpui::test] +fn installed_notes_wait_for_visible_window(cx: &mut TestAppContext) { + // Isolate persisted once-only state from every other test and real settings. + if std::env::var_os("PEBREL_INSTALLED_NOTES_TEST_CHILD").is_none() { + let root = tempfile::tempdir().unwrap(); + let test_name = format!( + "{}::installed_notes_wait_for_visible_window", + module_path!().split_once("::").unwrap().1 + ); + let result = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", &test_name, "--nocapture"]) + .env("PEBREL_INSTALLED_NOTES_TEST_CHILD", "1") + .env("PEBREL_CONFIG_DIR", root.path()) + .env("NEBULA_CONFIG_DIR", root.path()) + .output() + .unwrap(); + assert!( + result.status.success(), + "{}\n{}", + String::from_utf8_lossy(&result.stdout), + String::from_utf8_lossy(&result.stderr) + ); + assert!(String::from_utf8_lossy(&result.stdout).contains("1 passed")); + return; + } + initialize_test(cx); + let (id, workspace) = cx.update(|cx| open_test_window(cx, 0)); + let state = pebrel_settings::settings_dir().join("update_state.json"); + cx.update(|cx| { + workspace.update(cx, |workspace, _| workspace.window_hidden = true); + dispatch_shell_events( + vec![GpuiShellEvent::UpdateInstalled( + crate::update_check::release_notes::ReleaseNotes { + version: env!("CARGO_PKG_VERSION").into(), + body: "# Installed changes".into(), + }, + )], + cx, + ); + assert!(super::super::update_dialog::has_pending_installed_notes(cx)); + assert!(!state.exists(), "hidden window must not consume persistent notice"); + workspace.update(cx, |workspace, _| workspace.window_hidden = false); + dispatch_shell_events(Vec::new(), cx); + assert!(!super::super::update_dialog::has_pending_installed_notes(cx)); + assert!(entry_by_id(id, cx).is_some()); + }); + cx.run_until_parked(); + let state_after = std::fs::read(&state).unwrap(); + let stored: serde_json::Value = serde_json::from_slice(&state_after).unwrap(); + assert_eq!(stored["release_notes_shown"], env!("CARGO_PKG_VERSION")); + cx.update(|cx| dispatch_shell_events(Vec::new(), cx)); + assert_eq!( + std::fs::read(state).unwrap(), + state_after, + "later pump ticks must not acknowledge again" + ); +} + #[gpui::test] fn busy_tab_confirmation_tracks_its_target_across_removal(cx: &mut TestAppContext) { initialize_test(cx); diff --git a/pebrel_app/src/update_check.rs b/pebrel_app/src/update_check.rs index c5a67c119..8e6e92b50 100644 --- a/pebrel_app/src/update_check.rs +++ b/pebrel_app/src/update_check.rs @@ -24,6 +24,7 @@ const REMIND_LATER_SECS: u64 = 3 * 24 * 60 * 60; pub(crate) mod assets; mod fallback; +pub(crate) mod release_notes; #[cfg(feature = "update-test-source")] pub(crate) mod test_source; @@ -37,6 +38,8 @@ struct UpdatePromptState { last_prompted: Option, remind_after: Option, skipped_version: Option, + #[serde(default)] + release_notes_shown: Option, } impl UpdatePromptState { @@ -154,6 +157,7 @@ struct LatestRelease { version: String, asset: Option, portable_zip_url: Option, + body: Option, } #[derive(Deserialize)] @@ -224,6 +228,9 @@ pub fn spawn_gpui_once(sender: std::sync::mpsc::Sender Result { use crate::platform::distribution::{Distribution, require_release_check}; let distribution = require_release_check()?; - UpdateCheckResult::from_release(fetch_latest_release()?, distribution == Distribution::Portable) + let release = fetch_latest_release()?; + if let Some(body) = &release.body { + release_notes::remember(&release.version, body); + } + UpdateCheckResult::from_release(release, distribution == Distribution::Portable) } fn update_state_path() -> std::path::PathBuf { @@ -303,7 +314,7 @@ fn load_prompt_state() -> UpdatePromptState { } } -fn update_prompt_state(change: impl FnOnce(&mut UpdatePromptState)) -> Result<(), String> { +fn update_prompt_state(change: impl FnOnce(&mut UpdatePromptState) -> T) -> Result { let _guard = UPDATE_STATE_LOCK.lock().unwrap_or_else(|poison| poison.into_inner()); let path = update_state_path(); let Some(_file_lock) = crate::atomic_file::try_lock(&path) @@ -312,11 +323,12 @@ fn update_prompt_state(change: impl FnOnce(&mut UpdatePromptState)) -> Result<() return Err("更新提醒状态正由另一个 Pebrel 进程写入".to_owned()); }; let mut state = load_prompt_state(); - change(&mut state); + let result = change(&mut state); let bytes = serde_json::to_vec_pretty(&state) .map_err(|error| format!("无法序列化更新提醒状态:{error}"))?; crate::atomic_file::write(&path, &bytes) - .map_err(|error| format!("无法保存更新提醒状态:{error}")) + .map_err(|error| format!("无法保存更新提醒状态:{error}"))?; + Ok(result) } pub fn should_prompt(version: &str) -> bool { @@ -410,7 +422,7 @@ fn select_release( let portable_zip_url = windows_arch.and_then(|architecture| { assets::portable_from_assets(&release.tag_name, architecture, &release.assets) }); - LatestRelease { version, asset, portable_zip_url } + LatestRelease { version, asset, portable_zip_url, body: Some(release.body.unwrap_or_default()) } } /// Only a stable, numeric release tag may supply a path component for a link. diff --git a/pebrel_app/src/update_check/fallback.rs b/pebrel_app/src/update_check/fallback.rs index ec39781b1..94e7596b7 100644 --- a/pebrel_app/src/update_check/fallback.rs +++ b/pebrel_app/src/update_check/fallback.rs @@ -78,7 +78,12 @@ fn release_from_uri(uri: &str) -> Option { // Official stable releases use major.minor.patch. Reject login pages, // arbitrary tags, extra path/query/fragment components and preview tags. let version = super::stable_version_from_tag(tag)?; - Some(LatestRelease { version: version.to_owned(), asset: None, portable_zip_url: None }) + Some(LatestRelease { + version: version.to_owned(), + asset: None, + portable_zip_url: None, + body: None, + }) } #[cfg(test)] diff --git a/pebrel_app/src/update_check/release_notes.rs b/pebrel_app/src/update_check/release_notes.rs new file mode 100644 index 000000000..24d89161e --- /dev/null +++ b/pebrel_app/src/update_check/release_notes.rs @@ -0,0 +1,216 @@ +//! Release descriptions are updater metadata, separate from user settings. +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub(crate) struct ReleaseNotes { + pub version: String, + pub body: String, +} + +fn cache_directory() -> PathBuf { + pebrel_settings::settings_dir().join("updates") +} + +fn cache_path(directory: &Path, version: &str) -> PathBuf { + use sha2::{Digest as _, Sha256}; + // Remote version strings must not become filesystem paths. + let key = Sha256::digest(version.as_bytes()) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::(); + directory.join("release-notes").join(format!("{key}.json")) +} + +fn cached(directory: &Path, version: &str) -> Option { + read(&cache_path(directory, version), version) + .or_else(|| read(&directory.join("release-notes.json"), version)) +} + +fn read(path: &Path, version: &str) -> Option { + use std::io::Read as _; + let file = std::fs::File::open(path).ok()?; + let notes: ReleaseNotes = serde_json::from_reader(file.take(2 * 1024 * 1024)).ok()?; + (notes.version == version).then_some(notes) +} + +pub(crate) fn remember(version: &str, body: &str) { + let notes = ReleaseNotes { version: version.to_owned(), body: body.to_owned() }; + if let Err(error) = save(&cache_path(&cache_directory(), version), ¬es) { + log::warn!("Could not cache release notes: {error}"); + } +} + +fn save(path: &Path, notes: &ReleaseNotes) -> Result<(), String> { + let bytes = serde_json::to_vec(notes).map_err(|error| error.to_string())?; + crate::atomic_file::write(path, &bytes).map_err(|error| error.to_string()) +} + +pub(crate) fn snapshot(version: &str, directory: &Path) -> Result<(), String> { + snapshot_from(&cache_directory(), version, directory) +} + +fn snapshot_from(cache: &Path, version: &str, directory: &Path) -> Result<(), String> { + if let Some(notes) = cached(cache, version) { + save(&directory.join("release-notes.json"), ¬es)?; + } + Ok(()) +} + +/// Use the installed tag, never the latest release (which may already be newer). +pub(crate) fn current() -> Result { + let version = env!("CARGO_PKG_VERSION"); + if let Some(directory) = crate::update_download::handoff::completed_update_directory() + && let Some(notes) = read(&directory.join("release-notes.json"), version) + { + return Ok(notes); + } + if let Some(notes) = cached(&cache_directory(), version) { + return Ok(notes); + } + let url = format!("https://api.github.com/repos/Kuddev/pebrel/releases/tags/v{version}"); + #[cfg(feature = "update-test-source")] + if let Some(origin) = super::test_source::origin()? { + return fetch( + &super::test_source::agent(Duration::from_secs(10)), + &format!("{origin}/release.json"), + version, + ); + } + let agent = crate::update_proxy::agent(&url, Duration::from_secs(10)); + let notes = fetch(&agent, &url, version)?; + remember(version, ¬es.body); + Ok(notes) +} + +fn fetch(agent: &ureq::Agent, url: &str, version: &str) -> Result { + let mut response = agent + .get(url) + .header("User-Agent", "pebrel") + .header("Accept", "application/vnd.github+json") + .call() + .map_err(|error| error.to_string())?; + let bytes = response + .body_mut() + .with_config() + .limit(2 * 1024 * 1024) + .read_to_vec() + .map_err(|error| error.to_string())?; + parse(&bytes, version) +} + +fn parse(bytes: &[u8], version: &str) -> Result { + let release: super::GitHubRelease = + serde_json::from_slice(bytes).map_err(|error| error.to_string())?; + if release.tag_name.trim().trim_start_matches(['v', 'V']) != version { + return Err("Release notes do not match the installed version".into()); + } + Ok(ReleaseNotes { version: version.to_owned(), body: release.body.unwrap_or_default() }) +} + +pub(crate) fn pending_installed() -> Option { + crate::update_download::handoff::completed_update_directory()?; + if super::load_prompt_state().release_notes_shown.as_deref() == Some(env!("CARGO_PKG_VERSION")) + { + return None; + } + match current() { + Ok(notes) => Some(notes), + Err(error) => { + // Keep it pending so an offline first launch does not consume the notice. + log::debug!("Could not load installed release notes: {error}"); + None + }, + } +} + +pub(crate) fn claim(version: &str) -> Result { + super::update_prompt_state(|state| { + if state.release_notes_shown.as_deref() == Some(version) { + return false; + } + state.release_notes_shown = Some(version.to_owned()); + true + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn description_preserves_rich_text_and_rejects_another_version() { + let body = "# Changes\n\n**Bold** and [link](https://github.com/Kuddev/pebrel)\n\n```sh\npwd\n```\n\n| A | B |\n| - | - |\n| 1 | 2 |\n"; + let json = + serde_json::to_vec(&serde_json::json!({"tag_name":"v2.0.0", "body":body})).unwrap(); + assert_eq!(parse(&json, "2.0.0").unwrap().body, body); + assert!(parse(&json, "2.1.0").is_err()); + assert!(parse(b"invalid JSON", "2.0.0").is_err()); + assert!(parse(br#"{"tag_name":"v2.0.0","body":null}"#, "2.0.0").unwrap().body.is_empty()); + } + + #[test] + fn release_description_uses_the_update_proxy_and_reports_http_failures() { + use crate::update_proxy::test_support::{Server, response}; + for (status, success) in [("200 OK", true), ("404 Not Found", false)] { + let server = Server::start(vec![response( + status, + "Content-Type: application/json\r\n", + r#"{"tag_name":"v2.0.0","body":"**Changes**"}"#, + )]); + let result = + fetch(&server.agent(&[]), "http://api.update.invalid/tags/v2.0.0", "2.0.0"); + assert_eq!(result.is_ok(), success); + if success { + assert_eq!(result.unwrap().body, "**Changes**"); + } + let requests = server.finish(); + assert!(requests[0].0.starts_with("CONNECT api.update.invalid:80 ")); + assert!(requests[0].1.starts_with("GET /tags/v2.0.0 ")); + } + } + + #[test] + fn snapshot_round_trips_the_exact_release_only() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("release-notes.json"); + let notes = + ReleaseNotes { version: "2.0.0".into(), body: "## 更新\n- **内容**".into() }; + save(&path, ¬es).unwrap(); + assert_eq!(read(&path, "2.0.0").unwrap().body, notes.body); + assert!(read(&path, "2.1.0").is_none()); + } + + #[test] + fn reading_installed_notes_does_not_evict_the_pending_offline_snapshot() { + let cache = tempfile::tempdir().unwrap(); + let handoff = tempfile::tempdir().unwrap(); + let pending = ReleaseNotes { version: "2.1.0".into(), body: "New update notes".into() }; + let installed = ReleaseNotes { version: "2.0.0".into(), body: "Installed notes".into() }; + // The update check caches the pending release before Settings reads the installed one. + save(&cache_path(cache.path(), &pending.version), &pending).unwrap(); + save(&cache_path(cache.path(), &installed.version), &installed).unwrap(); + assert_eq!(cached(cache.path(), &installed.version).unwrap().body, installed.body); + snapshot_from(cache.path(), &pending.version, handoff.path()).unwrap(); + let restored = read(&handoff.path().join("release-notes.json"), &pending.version).unwrap(); + assert_eq!(restored.body, pending.body); + assert!(read(&handoff.path().join("release-notes.json"), &installed.version).is_none()); + } + + #[test] + fn legacy_cache_remains_readable_and_version_keys_cannot_escape_the_cache() { + let cache = tempfile::tempdir().unwrap(); + let legacy = ReleaseNotes { version: "2.0.0".into(), body: "Existing notes".into() }; + save(&cache.path().join("release-notes.json"), &legacy).unwrap(); + assert_eq!(cached(cache.path(), &legacy.version).unwrap().body, legacy.body); + assert!(cached(cache.path(), "2.1.0").is_none()); + let unusual = ReleaseNotes { version: "../../outside".into(), body: "Isolated".into() }; + let path = cache_path(cache.path(), &unusual.version); + assert_eq!(path.parent().unwrap(), cache.path().join("release-notes")); + save(&path, &unusual).unwrap(); + assert_eq!(cached(cache.path(), &unusual.version).unwrap().body, unusual.body); + assert_eq!(cached(cache.path(), &legacy.version).unwrap().body, legacy.body); + } +} diff --git a/pebrel_app/src/update_download/handoff.rs b/pebrel_app/src/update_download/handoff.rs index d2cb69f58..e514c6702 100644 --- a/pebrel_app/src/update_download/handoff.rs +++ b/pebrel_app/src/update_download/handoff.rs @@ -163,6 +163,7 @@ pub(crate) fn prepare(asset: &UpdateAsset) -> Result { guard_path: base.with_extension("nebula-lock"), participants: vec![Participant { pid: std::process::id(), created: created.to_string() }], }; + crate::update_check::release_notes::snapshot(&asset.version, &directory)?; let plan_path = directory.join("plan.json"); crate::atomic_file::write( &plan_path, @@ -306,6 +307,28 @@ pub(crate) fn acknowledge_restore(restored_windows: usize) -> bool { } } +/// A successful helper result must belong to this installation and running version. +pub(crate) fn completed_update_directory() -> Option { + let path: PathBuf = + read_json(&pebrel_settings::settings_dir().join("updates/last-handoff.json"))?; + let path = canonical(&path).ok()?; + let root = canonical(&pebrel_settings::settings_dir().join("updates/handoffs")).ok()?; + if !path.starts_with(root) || path.file_name()? != "plan.json" { + return None; + } + let plan: Plan = read_json(&path)?; + if plan.schema != 1 + || plan.version != env!("CARGO_PKG_VERSION") + || canonical(&plan.executable).ok()? != canonical(&std::env::current_exe().ok()?).ok()? + { + return None; + } + let directory = path.parent()?; + let result: serde_json::Value = read_json(&directory.join("result.json"))?; + (result["success"] == true && result["transaction"] == plan.transaction) + .then(|| directory.to_owned()) +} + pub(super) fn failed_update() -> Option<(UpdateAsset, String)> { let path: PathBuf = read_json(&super::state_directory("").ok()?.join("last-handoff.json"))?; let root = canonical(&super::state_directory("handoffs").ok()?).ok()?; diff --git a/pebrel_app/src/update_download/handoff/tests.rs b/pebrel_app/src/update_download/handoff/tests.rs index 4e382f5ee..5b3c8a739 100644 --- a/pebrel_app/src/update_download/handoff/tests.rs +++ b/pebrel_app/src/update_download/handoff/tests.rs @@ -78,10 +78,27 @@ fn update_restore_tickets_cover_success_rollback_and_acknowledgement() { serde_json::json!({"transaction": "wrong", "success": !recovered, "recovered_original": recovered}), ); assert!(restore_ticket().is_none()); + assert!(completed_update_directory().is_none()); save( "result.json", serde_json::json!({"transaction": plan.transaction, "success": !recovered, "recovered_original": recovered}), ); + assert_eq!(completed_update_directory().is_some(), !recovered); + if !recovered { + crate::update_check::release_notes::remember( + &plan.version, + "# Installed release\n**Changes**", + ); + crate::update_check::release_notes::snapshot(&plan.version, &directory).unwrap(); + let notes = crate::update_check::release_notes::pending_installed().unwrap(); + assert_eq!(notes.body, "# Installed release\n**Changes**"); + assert!(crate::update_check::release_notes::claim(&plan.version).unwrap()); + assert!(!crate::update_check::release_notes::claim(&plan.version).unwrap()); + assert!(crate::update_check::release_notes::pending_installed().is_none()); + assert_eq!(crate::update_check::release_notes::current().unwrap().body, notes.body); + } else { + assert!(crate::update_check::release_notes::pending_installed().is_none()); + } plan.elevated = !plan.elevated; save("plan.json", serde_json::to_value(&plan).unwrap()); assert!(restore_ticket().is_none(), "a ticket cannot cross the actual token scope");