From 7ce928decdfca24c0f81282c7f2e48641d66e15d Mon Sep 17 00:00:00 2001 From: viper1aa <129401103+w0otdev@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:05:56 +0700 Subject: [PATCH 1/4] version bump --- Directory.Build.props | 6 +++--- Tests/packages.lock.json | 6 +++--- V-Notch.csproj | 6 +++--- app.manifest | 2 +- packages.lock.json | 2 +- rust/Cargo.toml | 2 +- rust/crates/vnotch-ffi/src/sys/app_session.rs | 2 +- rust/crates/vnotch-ffi/src/sys/m05/ai_usage.rs | 2 +- rust/crates/vnotch-ffi/src/sys/m05/weather.rs | 2 +- rust/crates/vnotch-uninstall/build.rs | 2 +- 10 files changed, 16 insertions(+), 16 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 5785c823..7c95851f 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -11,9 +11,9 @@ - 2.4.2 - 2.4.2.0 - 2.4.2.0 + 2.5.0 + 2.5.0.0 + 2.5.0.0 latest-recommended true diff --git a/Tests/packages.lock.json b/Tests/packages.lock.json index 5825e79a..c74afebd 100644 --- a/Tests/packages.lock.json +++ b/Tests/packages.lock.json @@ -198,15 +198,15 @@ "Microsoft.Extensions.DependencyInjection": "[8.0.1, )", "Microsoft.ML.OnnxRuntime.DirectML": "[1.24.4, )", "Microsoft.Web.WebView2": "[1.0.4078.44, )", - "VNotch.Application": "[2.4.2, )", - "VNotch.Core": "[2.4.2, )", + "VNotch.Application": "[2.5.0, )", + "VNotch.Core": "[2.5.0, )", "Vortice.Direct3D9": "[3.8.3, )" } }, "vnotch.application": { "type": "Project", "dependencies": { - "VNotch.Core": "[2.4.2, )" + "VNotch.Core": "[2.5.0, )" } }, "vnotch.core": { diff --git a/V-Notch.csproj b/V-Notch.csproj index f109200d..13466ccf 100644 --- a/V-Notch.csproj +++ b/V-Notch.csproj @@ -42,9 +42,9 @@ reflection, COM interop or CPU/GPU translation backends. --> true false - 2.4.2 - 2.4.2.0 - 2.4.2.0 + 2.5.0 + 2.5.0.0 + 2.5.0.0 w0otdev, viper1aa V-Notch V-Notch diff --git a/app.manifest b/app.manifest index 5e4448dd..00aafc3b 100644 --- a/app.manifest +++ b/app.manifest @@ -1,6 +1,6 @@ - + diff --git a/packages.lock.json b/packages.lock.json index 8d4f9ef1..993fc299 100644 --- a/packages.lock.json +++ b/packages.lock.json @@ -134,7 +134,7 @@ "vnotch.application": { "type": "Project", "dependencies": { - "VNotch.Core": "[2.4.2, )" + "VNotch.Core": "[2.5.0, )" } }, "vnotch.core": { diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 1af2d7b7..5d8cb3a5 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -8,7 +8,7 @@ members = [ ] [workspace.package] -version = "2.4.2" +version = "2.5.0" edition = "2024" rust-version = "1.100" license = "MIT" diff --git a/rust/crates/vnotch-ffi/src/sys/app_session.rs b/rust/crates/vnotch-ffi/src/sys/app_session.rs index 8418a528..d9599eee 100644 --- a/rust/crates/vnotch-ffi/src/sys/app_session.rs +++ b/rust/crates/vnotch-ffi/src/sys/app_session.rs @@ -156,7 +156,7 @@ impl AppSession { install_jobs: Arc::new(Mutex::new(HashMap::new())), next_job_id: AtomicU64::new(1), locale_service, - app_version: cfg.app_version.unwrap_or_else(|| "2.4.2".to_owned()), + app_version: cfg.app_version.unwrap_or_else(|| "2.5.0".to_owned()), }) } diff --git a/rust/crates/vnotch-ffi/src/sys/m05/ai_usage.rs b/rust/crates/vnotch-ffi/src/sys/m05/ai_usage.rs index 8fa8bb73..e9428073 100644 --- a/rust/crates/vnotch-ffi/src/sys/m05/ai_usage.rs +++ b/rust/crates/vnotch-ffi/src/sys/m05/ai_usage.rs @@ -719,7 +719,7 @@ async fn exchange_codex_rpc( total_read: &mut usize, now_unix_sec: i64, ) -> Option { - const INIT: &[u8] = b"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"clientInfo\":{\"name\":\"V-Notch\",\"version\":\"2.4.2\"}}}\n"; + const INIT: &[u8] = b"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"clientInfo\":{\"name\":\"V-Notch\",\"version\":\"2.5.0\"}}}\n"; const INITED: &[u8] = b"{\"jsonrpc\":\"2.0\",\"method\":\"initialized\",\"params\":{}}\n"; const ACCT: &[u8] = b"{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"account/read\",\"params\":{}}\n"; diff --git a/rust/crates/vnotch-ffi/src/sys/m05/weather.rs b/rust/crates/vnotch-ffi/src/sys/m05/weather.rs index e142aff6..974a7b00 100644 --- a/rust/crates/vnotch-ffi/src/sys/m05/weather.rs +++ b/rust/crates/vnotch-ffi/src/sys/m05/weather.rs @@ -129,7 +129,7 @@ impl WeatherEngineHost { pub fn for_session(session: i64) -> Self { let client = reqwest::Client::builder() .timeout(WEATHER_HTTP_TIMEOUT) - .user_agent("V-Notch/2.4.2") + .user_agent("V-Notch/2.5.0") .build() .ok(); Self { diff --git a/rust/crates/vnotch-uninstall/build.rs b/rust/crates/vnotch-uninstall/build.rs index 57c7ef7d..416761f2 100644 --- a/rust/crates/vnotch-uninstall/build.rs +++ b/rust/crates/vnotch-uninstall/build.rs @@ -28,7 +28,7 @@ const UNINSTALLER_KEYS: &[&str] = &[ const UNINSTALL_MANIFEST_XML: &str = r#" - + V-Notch Uninstaller From 6059dc9754501cc7c58fdf2f597ae11f38450475 Mon Sep 17 00:00:00 2001 From: viper1aa <129401103+w0otdev@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:20:51 +0700 Subject: [PATCH 2/4] Announcement fetch from GitHub repository --- Interop/RepoAnnouncementsNative.cs | 138 ++++ Models/AppNotificationInfo.cs | 2 + Services/RepoAnnouncementService.cs | 47 ++ Windows/MainWindow.Announcement.cs | 192 ++++++ Windows/MainWindow.AppNotification.cs | 3 +- .../MainWindow.AppNotificationInteraction.cs | 12 +- Windows/MainWindow.xaml.cs | 2 + rust/Cargo.lock | 12 +- rust/Cargo.toml | 11 + .../vnotch-core/src/updater/announcements.rs | 638 ++++++++++++++++++ rust/crates/vnotch-core/src/updater/mod.rs | 8 + .../src/exports/m03/announcements_abi.rs | 91 +++ rust/crates/vnotch-ffi/src/exports/m03/mod.rs | 2 + .../vnotch-ffi/src/sys/m03/announcements.rs | 261 +++++++ rust/crates/vnotch-ffi/src/sys/m03/mod.rs | 6 + scripts/r.ps1 | 29 +- 16 files changed, 1435 insertions(+), 19 deletions(-) create mode 100644 Interop/RepoAnnouncementsNative.cs create mode 100644 Services/RepoAnnouncementService.cs create mode 100644 Windows/MainWindow.Announcement.cs create mode 100644 rust/crates/vnotch-core/src/updater/announcements.rs create mode 100644 rust/crates/vnotch-ffi/src/exports/m03/announcements_abi.rs create mode 100644 rust/crates/vnotch-ffi/src/sys/m03/announcements.rs diff --git a/Interop/RepoAnnouncementsNative.cs b/Interop/RepoAnnouncementsNative.cs new file mode 100644 index 00000000..3b1a206e --- /dev/null +++ b/Interop/RepoAnnouncementsNative.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace VNotch.Interop; + +internal sealed record PinnedAnnouncementDto( + [property: JsonPropertyName("id")] string Id, + [property: JsonPropertyName("number")] ulong Number, + [property: JsonPropertyName("title")] string Title, + [property: JsonPropertyName("summary")] string Summary, + [property: JsonPropertyName("url")] string Url, + [property: JsonPropertyName("category")] string Category); + +internal sealed record FetchAnnouncementsResponseDto( + [property: JsonPropertyName("announcements")] List? Announcements, + [property: JsonPropertyName("totalPinned")] int TotalPinned, + [property: JsonPropertyName("fromCache")] bool FromCache); + +/// +/// Thin ABI 2.2 P/Invoke wrapper for pinned repository announcements in vnotch_rust.dll. +/// +internal static partial class RepoAnnouncementsNative +{ + private static readonly JsonSerializerOptions JsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [LibraryImport(NativeAbi.RustLibraryName)] + private static unsafe partial int vn_announcements_fetch_unseen_utf8( + byte* reqJson, + uint reqLen, + out VnOwnedBytes outJson); + + [LibraryImport(NativeAbi.RustLibraryName)] + private static unsafe partial int vn_announcements_mark_seen_utf8( + byte* reqJson, + uint reqLen, + out uint outCount); + + [LibraryImport(NativeAbi.RustLibraryName)] + private static unsafe partial int vn_announcements_parse_pinned_utf8( + byte* htmlUtf8, + uint htmlLen, + out VnOwnedBytes outJson); + + internal static unsafe FetchAnnouncementsResponseDto FetchUnseen( + string cachePath, + string? url = null, + bool forceRefresh = false) + { + byte[] reqBytes = JsonSerializer.SerializeToUtf8Bytes(new + { + cachePath, + url, + forceRefresh + }); + + VnOwnedBytes owned = default; + try + { + int status; + fixed (byte* ptr = reqBytes) + { + status = vn_announcements_fetch_unseen_utf8(ptr, checked((uint)reqBytes.Length), out owned); + } + + NativeResult.RequireSuccess(status, nameof(vn_announcements_fetch_unseen_utf8)); + ReadOnlySpan span = owned.AsSpan(); + if (span.IsEmpty) + { + return new FetchAnnouncementsResponseDto([], 0, false); + } + + return JsonSerializer.Deserialize(span, JsonOptions) + ?? new FetchAnnouncementsResponseDto([], 0, false); + } + finally + { + owned.Free(); + } + } + + internal static unsafe uint MarkSeen(string cachePath, IReadOnlyList ids) + { + if (ids.Count == 0) + { + return 0; + } + + byte[] reqBytes = JsonSerializer.SerializeToUtf8Bytes(new + { + cachePath, + ids + }); + + int status; + uint count; + fixed (byte* ptr = reqBytes) + { + status = vn_announcements_mark_seen_utf8(ptr, checked((uint)reqBytes.Length), out count); + } + + NativeResult.RequireSuccess(status, nameof(vn_announcements_mark_seen_utf8)); + return count; + } + + internal static unsafe IReadOnlyList ParsePinnedHtml(string html) + { + byte[] htmlBytes = Encoding.UTF8.GetBytes(html ?? string.Empty); + VnOwnedBytes owned = default; + try + { + int status; + fixed (byte* ptr = htmlBytes) + { + status = vn_announcements_parse_pinned_utf8(ptr, checked((uint)htmlBytes.Length), out owned); + } + + NativeResult.RequireSuccess(status, nameof(vn_announcements_parse_pinned_utf8)); + ReadOnlySpan span = owned.AsSpan(); + if (span.IsEmpty) + { + return []; + } + + return JsonSerializer.Deserialize>(span, JsonOptions) ?? []; + } + finally + { + owned.Free(); + } + } +} diff --git a/Models/AppNotificationInfo.cs b/Models/AppNotificationInfo.cs index 0be38d55..29dd8021 100644 --- a/Models/AppNotificationInfo.cs +++ b/Models/AppNotificationInfo.cs @@ -12,4 +12,6 @@ public sealed class AppNotificationInfo public string Body { get; init; } = string.Empty; public ImageSource? AppIcon { get; init; } public DateTimeOffset CreationTime { get; init; } = DateTimeOffset.UtcNow; + public string? ActionUrl { get; init; } + public string? AnnouncementId { get; init; } } diff --git a/Services/RepoAnnouncementService.cs b/Services/RepoAnnouncementService.cs new file mode 100644 index 00000000..c49cdcff --- /dev/null +++ b/Services/RepoAnnouncementService.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using VNotch.Interop; + +namespace VNotch.Services; + +/// +/// Thin async facade over Rust pinned GitHub Discussions announcements fetcher and local seen-state. +/// +internal static class RepoAnnouncementService +{ + private const string CacheFileName = "announcements-cache.json"; + + internal static string DefaultCachePath => Path.Combine(AppPaths.LocalAppDataRoot, CacheFileName); + + internal static Task> FetchUnseenAsync( + bool forceRefresh = false, + CancellationToken cancellationToken = default) + { + return Task.Run>(() => + { + cancellationToken.ThrowIfCancellationRequested(); + var response = RepoAnnouncementsNative.FetchUnseen(DefaultCachePath, url: null, forceRefresh: forceRefresh); + return response.Announcements ?? []; + }, cancellationToken); + } + + internal static void MarkSeen(string announcementId) + { + if (string.IsNullOrWhiteSpace(announcementId)) + { + return; + } + + try + { + _ = RepoAnnouncementsNative.MarkSeen(DefaultCachePath, [announcementId]); + } + catch (Exception ex) + { + RuntimeLog.Warn("ANNOUNCEMENT", $"Failed to record seen announcement '{announcementId}': {ex.Message}"); + } + } +} diff --git a/Windows/MainWindow.Announcement.cs b/Windows/MainWindow.Announcement.cs new file mode 100644 index 00000000..37ac9ebf --- /dev/null +++ b/Windows/MainWindow.Announcement.cs @@ -0,0 +1,192 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Threading; +using VNotch.Interop; +using VNotch.Models; +using VNotch.Services; + +namespace VNotch; + +public partial class MainWindow +{ + private const int AnnouncementInitialDelayMs = 4500; + private const int AnnouncementRetryDelayMs = 3500; + private const int AnnouncementPollHours = 2; + private const int MaxAnnouncementDeferRetries = 20; + + private readonly Queue _pendingAnnouncements = new(); + private readonly HashSet _queuedAnnouncementIds = new(StringComparer.OrdinalIgnoreCase); + private UiScheduledTimer? _announcementInitialTimer; + private UiScheduledTimer? _announcementPollTimer; + private UiScheduledTimer? _announcementFlushTimer; + private CancellationTokenSource? _announcementCts; + private int _announcementDeferRetries; + + private void StartRepoAnnouncementsMonitor() + { + DisposeRepoAnnouncementsMonitor(); + _announcementCts = new CancellationTokenSource(); + + _announcementInitialTimer = new UiScheduledTimer + { + Interval = TimeSpan.FromMilliseconds(AnnouncementInitialDelayMs) + }; + _announcementInitialTimer.Tick += (_, _) => + { + StopAnnouncementTimer(ref _announcementInitialTimer); + CheckRepoAnnouncementsAsync().SafeFireAndForget("ANNOUNCEMENT"); + }; + _announcementInitialTimer.Start(); + + _announcementPollTimer = new UiScheduledTimer + { + Interval = TimeSpan.FromHours(AnnouncementPollHours) + }; + _announcementPollTimer.Tick += (_, _) => + CheckRepoAnnouncementsAsync().SafeFireAndForget("ANNOUNCEMENT"); + _announcementPollTimer.Start(); + } + + private void DisposeRepoAnnouncementsMonitor() + { + StopAnnouncementTimer(ref _announcementInitialTimer); + StopAnnouncementTimer(ref _announcementPollTimer); + StopAnnouncementTimer(ref _announcementFlushTimer); + var cts = Interlocked.Exchange(ref _announcementCts, null); + if (cts != null) + { + try { cts.Cancel(); } catch { } + cts.Dispose(); + } + _pendingAnnouncements.Clear(); + _queuedAnnouncementIds.Clear(); + } + + private async Task CheckRepoAnnouncementsAsync() + { + if (_cleanedUp || _settings.EnableLocalOnlyMode) + { + return; + } + + var cts = _announcementCts; + if (cts == null || cts.IsCancellationRequested) + { + return; + } + + try + { + IReadOnlyList unseen = + await RepoAnnouncementService.FetchUnseenAsync(forceRefresh: false, cts.Token); + if (_cleanedUp || cts.IsCancellationRequested || unseen.Count == 0) + { + return; + } + + await Dispatcher.InvokeAsync(() => + { + if (_cleanedUp) return; + foreach (var item in unseen) + { + if (!string.IsNullOrWhiteSpace(item.Id) && + !string.IsNullOrWhiteSpace(item.Title) && + _queuedAnnouncementIds.Add(item.Id)) + { + _pendingAnnouncements.Enqueue(item); + } + } + + _announcementDeferRetries = 0; + TryPresentNextRepoAnnouncement(); + }, DispatcherPriority.Normal); + } + catch (OperationCanceledException) + { + } + catch (Exception ex) + { + RuntimeLog.Warn("ANNOUNCEMENT", $"Pinned announcements check failed: {ex.Message}"); + } + } + + private void TryPresentNextRepoAnnouncement() + { + if (_cleanedUp || _pendingAnnouncements.Count == 0) + { + StopAnnouncementTimer(ref _announcementFlushTimer); + return; + } + + bool notchBusy = !_isNotchVisible || _isGreetingActive || _isExpanded || _isAnimating || + IsCountdownCompletionVisualActive || _isAppNotificationBannerVisible; + if (notchBusy) + { + if (_announcementDeferRetries++ < MaxAnnouncementDeferRetries) + { + ScheduleAnnouncementFlush(); + } + return; + } + + StopAnnouncementTimer(ref _announcementFlushTimer); + _announcementDeferRetries = 0; + PinnedAnnouncementDto next = _pendingAnnouncements.Dequeue(); + + string body = !string.IsNullOrWhiteSpace(next.Summary) + ? next.Summary + : "Pinned announcement · Click to open on GitHub"; + + var info = new AppNotificationInfo + { + AppName = "V-Notch", + Title = next.Title, + Body = body, + AppIcon = this.Icon, + ActionUrl = next.Url, + AnnouncementId = next.Id + }; + + ShowAppNotification(info); + + if (_isAppNotificationBannerVisible && + string.Equals(_activeAppNotification?.AnnouncementId, next.Id, StringComparison.Ordinal)) + { + string seenId = next.Id; + _ = Task.Run(() => RepoAnnouncementService.MarkSeen(seenId)); + if (_pendingAnnouncements.Count > 0) + { + ScheduleAnnouncementFlush(); + } + } + } + + private void ScheduleAnnouncementFlush() + { + if (_cleanedUp || _announcementFlushTimer != null) + { + return; + } + + _announcementFlushTimer = new UiScheduledTimer + { + Interval = TimeSpan.FromMilliseconds(AnnouncementRetryDelayMs) + }; + _announcementFlushTimer.Tick += (_, _) => + { + StopAnnouncementTimer(ref _announcementFlushTimer); + TryPresentNextRepoAnnouncement(); + }; + _announcementFlushTimer.Start(); + } + + private static void StopAnnouncementTimer(ref UiScheduledTimer? timer) + { + var current = timer; + timer = null; + current?.Stop(); + current?.Dispose(); + } +} diff --git a/Windows/MainWindow.AppNotification.cs b/Windows/MainWindow.AppNotification.cs index 3e54eb38..2e5800ae 100644 --- a/Windows/MainWindow.AppNotification.cs +++ b/Windows/MainWindow.AppNotification.cs @@ -60,7 +60,8 @@ internal void ShowAppNotification(AppNotificationInfo? notification) private void PresentAppNotificationBanner(AppNotificationInfo? notification, bool isQuotaAlert, System.Collections.Generic.IReadOnlyList? quotaAlerts = null) { - if (notification == null || _cleanedUp || (!isQuotaAlert && !_settings.ShowSystemNotifications)) return; + bool isAnnouncement = !string.IsNullOrEmpty(notification?.AnnouncementId); + if (notification == null || _cleanedUp || (!isQuotaAlert && !isAnnouncement && !_settings.ShowSystemNotifications)) return; if (!_isNotchVisible || _isGreetingActive || _isExpanded || _isAnimating || IsCountdownCompletionVisualActive) return; _isAiQuotaNotification = isQuotaAlert; diff --git a/Windows/MainWindow.AppNotificationInteraction.cs b/Windows/MainWindow.AppNotificationInteraction.cs index 847f1e55..3187971b 100644 --- a/Windows/MainWindow.AppNotificationInteraction.cs +++ b/Windows/MainWindow.AppNotificationInteraction.cs @@ -187,7 +187,17 @@ private void ActivateAppNotification(bool keyboard = false) var active = _activeAppNotification; bool activateApp = !_isAiQuotaNotification; BeginAppNotificationDismiss(0, keyboard); - if (activateApp && active != null) _ = AppNotificationService.TryActivateApp(active.AppId, active.AppName); + if (activateApp && active != null) + { + if (!string.IsNullOrWhiteSpace(active.ActionUrl)) + { + _ = SafeLauncher.TryOpenUrl(active.ActionUrl); + } + else + { + _ = AppNotificationService.TryActivateApp(active.AppId, active.AppName); + } + } } private void AppNotificationBanner_KeyDown(object sender, KeyEventArgs e) diff --git a/Windows/MainWindow.xaml.cs b/Windows/MainWindow.xaml.cs index 724ce61e..246826c9 100644 --- a/Windows/MainWindow.xaml.cs +++ b/Windows/MainWindow.xaml.cs @@ -565,6 +565,7 @@ private void MainWindow_Loaded(object sender, RoutedEventArgs e) SetAvailableUpdate(initialUpdate); } CheckForUpdatesAsync().SafeFireAndForget("UPDATE-CHECK"); + StartRepoAnnouncementsMonitor(); PrepareFirstOpenUi(); @@ -753,6 +754,7 @@ private void PerformCleanup() _ownedTrayIcon = null; _updateTimer?.Dispose(); _updateCheckTimer?.Dispose(); + DisposeRepoAnnouncementsMonitor(); _updatePulseTimer?.Dispose(); _updatePulseTimer = null; if (_updateService != null) diff --git a/rust/Cargo.lock b/rust/Cargo.lock index e0bc130c..61951056 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -2023,9 +2023,9 @@ dependencies = [ [[package]] name = "sha2" -version = "0.11.2" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27" +checksum = "820083d430c52864bf834423fc988cbcf61685d6f9d22a765a64e3f6cfe3521c" dependencies = [ "cfg-if", "cpufeatures", @@ -2510,7 +2510,7 @@ checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" [[package]] name = "vnotch-bench" -version = "2.4.2" +version = "2.5.0" dependencies = [ "criterion", "image", @@ -2524,7 +2524,7 @@ dependencies = [ [[package]] name = "vnotch-core" -version = "2.4.2" +version = "2.5.0" dependencies = [ "aes-gcm", "aho-corasick", @@ -2556,7 +2556,7 @@ dependencies = [ [[package]] name = "vnotch-ffi" -version = "2.4.2" +version = "2.5.0" dependencies = [ "crossbeam-channel", "p256", @@ -2577,7 +2577,7 @@ dependencies = [ [[package]] name = "vnotch-uninstall" -version = "2.4.2" +version = "2.5.0" dependencies = [ "serde_json", "vnotch-core", diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 5d8cb3a5..8d674a6e 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -168,3 +168,14 @@ strip = "symbols" opt-level = 3 lto = "thin" codegen-units = 1 + +[profile.dev-fast] +inherits = "dev" +opt-level = 1 +debug = 0 +lto = false +codegen-units = 256 +incremental = true + +[profile.dev-fast.package."*"] +opt-level = 2 diff --git a/rust/crates/vnotch-core/src/updater/announcements.rs b/rust/crates/vnotch-core/src/updater/announcements.rs new file mode 100644 index 00000000..1b1aacbd --- /dev/null +++ b/rust/crates/vnotch-core/src/updater/announcements.rs @@ -0,0 +1,638 @@ +//! Pure-safe parser and seen-state logic for pinned GitHub Discussions announcements. + +use serde::{Deserialize, Serialize}; + +/// Official public GitHub Discussions page for V-Notch. +pub const OFFICIAL_DISCUSSIONS_URL: &str = "https://github.com/w0otdev/V-Notch/discussions"; +/// Maximum HTML response payload accepted when parsing pinned discussions (2 MiB). +pub const MAX_ANNOUNCEMENTS_HTML_BYTES: usize = 2 * 1024 * 1024; +/// Maximum number of pinned discussions returned per check. +pub const MAX_PINNED_ANNOUNCEMENTS: usize = 4; +/// Maximum number of seen announcement IDs retained in local state. +pub const MAX_SEEN_ANNOUNCEMENT_IDS: usize = 64; +/// Schema version for `announcements-cache.json`. +pub const ANNOUNCEMENTS_CACHE_SCHEMA_VERSION: u32 = 1; +/// Default local TTL for pinned announcement checks (30 minutes). +pub const ANNOUNCEMENTS_CACHE_TTL_SECS: i64 = 1800; + +const MAX_PINNED_SECTION_BYTES: usize = 65_536; +const MAX_TITLE_CHARS: usize = 160; +const MAX_SUMMARY_CHARS: usize = 240; +const CARD_CONTEXT_WINDOW_BYTES: usize = 2048; + +const PINNED_START_MARKERS: [&str; 6] = [ + "aria-label=\"pinned discussions\"", + "aria-label=\"pinned\"", + "id=\"pinned-discussions\"", + "data-testid=\"pinned-discussions\"", + "js-pinned-discussions", + "pinned-discussion", +]; + +const PINNED_END_MARKERS: [&str; 5] = [ + "aria-label=\"discussions\"", + "id=\"discussions-list\"", + "data-testid=\"discussions-list\"", + "js-discussions-list", + "action=\"/w0otdev/v-notch/discussions\"", +]; + +/// A pinned announcement parsed from the repository's GitHub Discussions page. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PinnedAnnouncement { + /// Stable identifier (`"discussion:"`). + pub id: String, + /// Numeric GitHub discussion ID. + pub number: u64, + /// Plain-text discussion title. + pub title: String, + /// Short plain-text metadata or summary shown in the notification body. + #[serde(default)] + pub summary: String, + /// Canonical HTTPS URL on `github.com`. + pub url: String, + /// Discussion category label when detected (e.g. `"Announcements"`). + #[serde(default)] + pub category: String, +} + +/// Persistent local cache and seen-state stored in `announcements-cache.json`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct AnnouncementsCache { + /// Cache schema version. + pub schema_version: u32, + /// Last HTTP `ETag` validator returned by GitHub. + pub etag: Option, + /// Unix timestamp (seconds) of the last successful fetch. + pub last_check_unix_s: i64, + /// Last parsed list of pinned announcements. + pub pinned: Vec, + /// Stable announcement IDs already shown or dismissed by the user. + pub seen_ids: Vec, +} + +impl Default for AnnouncementsCache { + fn default() -> Self { + Self { + schema_version: ANNOUNCEMENTS_CACHE_SCHEMA_VERSION, + etag: None, + last_check_unix_s: 0, + pinned: Vec::new(), + seen_ids: Vec::new(), + } + } +} + +impl AnnouncementsCache { + /// Returns `true` when the cached pinned list is still within `ttl_secs`. + #[must_use] + pub const fn is_fresh(&self, now_unix_s: i64, ttl_secs: i64) -> bool { + self.last_check_unix_s > 0 + && now_unix_s >= self.last_check_unix_s + && (now_unix_s - self.last_check_unix_s) < ttl_secs + } +} + +/// Validates that `url` targets the official V-Notch GitHub Discussions listing page. +#[must_use] +pub fn is_official_discussions_page_url(url: &str) -> bool { + let trimmed = url.trim(); + if trimmed.contains('@') || trimmed.contains('?') || trimmed.contains('#') { + return false; + } + let Some(path) = strip_github_origin(trimmed) else { + return false; + }; + let Some(rest) = strip_official_repo_prefix(path) else { + return false; + }; + let rest_trim = rest.trim_end_matches('/'); + rest_trim.eq_ignore_ascii_case("discussions") + || starts_with_ignore_ascii_case(rest_trim, "discussions/categories/") +} + +/// Validates that `url` targets an individual official V-Notch GitHub Discussion. +#[must_use] +pub fn is_official_discussion_url(url: &str) -> bool { + let trimmed = url.trim(); + if trimmed.contains('@') || trimmed.contains('?') || trimmed.contains('#') { + return false; + } + parse_discussion_href(trimmed).is_some() +} + +/// Parses pinned announcements from a GitHub Discussions HTML document. +#[must_use] +pub fn parse_pinned_discussions_html(html: &str) -> Vec { + let bounded = truncate_utf8_bytes(html, MAX_ANNOUNCEMENTS_HTML_BYTES); + let lower = bounded.to_ascii_lowercase(); + if let Some(section) = find_pinned_section(bounded, &lower) { + let items = extract_discussions_from_slice(section); + if !items.is_empty() { + return items; + } + } + extract_discussions_near_pin_markers(bounded, &lower) +} + +/// Filters `pinned` to announcements whose IDs have not yet been recorded in `seen_ids`. +#[must_use] +pub fn select_unseen_announcements( + pinned: &[PinnedAnnouncement], + seen_ids: &[String], +) -> Vec { + pinned + .iter() + .filter(|item| !contains_id_ci(seen_ids, &item.id)) + .cloned() + .collect() +} + +/// Appends newly seen announcement IDs while deduplicating and capping to `max_entries`. +#[must_use] +pub fn merge_seen_announcement_ids( + existing: &[String], + newly_seen: &[String], + max_entries: usize, +) -> Vec { + let cap = max_entries.max(1); + let mut merged: Vec = Vec::with_capacity(existing.len() + newly_seen.len()); + for raw in existing.iter().chain(newly_seen.iter()) { + let id = raw.trim(); + if !id.is_empty() && !contains_id_ci(&merged, id) { + merged.push(id.to_owned()); + } + } + if merged.len() > cap { + let drop_count = merged.len() - cap; + merged.drain(0..drop_count); + } + merged +} + +fn contains_id_ci(list: &[String], target: &str) -> bool { + let needle = target.trim(); + list.iter().any(|item| item.trim().eq_ignore_ascii_case(needle)) +} + +fn strip_github_origin(url: &str) -> Option<&str> { + const PREFIX: &str = "https://github.com/"; + if starts_with_ignore_ascii_case(url, PREFIX) { + url.get(PREFIX.len()..) + } else { + None + } +} + +fn strip_official_repo_prefix(path: &str) -> Option<&str> { + for owner in ["w0otdev/v-notch/", "rainaku/v-notch/"] { + if starts_with_ignore_ascii_case(path, owner) { + return path.get(owner.len()..); + } + } + None +} + +fn parse_discussion_href(href: &str) -> Option<(String, u64)> { + let clean = href.trim().split(['?', '#']).next()?; + let rel = if let Some(after_origin) = strip_github_origin(clean) { + after_origin + } else if let Some(after_slash) = clean.strip_prefix('/') { + after_slash + } else { + return None; + }; + let after_repo = strip_official_repo_prefix(rel)?; + if !starts_with_ignore_ascii_case(after_repo, "discussions/") { + return None; + } + let rest = after_repo.get("discussions/".len()..)?.trim_end_matches('/'); + if rest.is_empty() || !rest.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + let number = rest.parse::().ok()?; + if number == 0 { + return None; + } + Some((format!("{OFFICIAL_DISCUSSIONS_URL}/{number}"), number)) +} + +fn find_pinned_section<'a>(html: &'a str, lower: &str) -> Option<&'a str> { + let start = PINNED_START_MARKERS + .iter() + .filter_map(|marker| lower.find(marker)) + .min()?; + let tail_lower = lower.get(start..)?; + let end_offset = PINNED_END_MARKERS + .iter() + .filter_map(|marker| tail_lower.find(marker)) + .filter(|&offset| offset > 0) + .min() + .unwrap_or(tail_lower.len()) + .min(MAX_PINNED_SECTION_BYTES); + let end = floor_char_boundary(html, start.saturating_add(end_offset)); + html.get(start..end) +} + +fn extract_discussions_from_slice(slice: &str) -> Vec { + let mut results = Vec::new(); + let mut cursor = 0usize; + while cursor < slice.len() && results.len() < MAX_PINNED_ANNOUNCEMENTS { + let Some((next_cursor, item)) = parse_next_anchor(slice, cursor) else { + break; + }; + cursor = next_cursor; + if let Some(ann) = item + && !results.iter().any(|existing: &PinnedAnnouncement| existing.number == ann.number) + { + results.push(ann); + } + } + results +} + +fn extract_discussions_near_pin_markers(html: &str, lower: &str) -> Vec { + let mut results = Vec::new(); + let mut pos = 0usize; + while pos < lower.len() && results.len() < MAX_PINNED_ANNOUNCEMENTS { + let Some(hit) = find_next_pin_marker(lower, pos) else { + break; + }; + let end = floor_char_boundary(html, hit.saturating_add(CARD_CONTEXT_WINDOW_BYTES)); + if let Some(window) = html.get(hit..end) { + for item in extract_discussions_from_slice(window) { + if !results.iter().any(|e| e.number == item.number) { + results.push(item); + break; + } + } + } + pos = ceil_char_boundary(lower, hit.saturating_add(8)); + } + results +} + +fn find_next_pin_marker(lower: &str, from: usize) -> Option { + let tail = lower.get(from..)?; + let a = tail.find("octicon-pin"); + let b = tail.find(">pinned<"); + match (a, b) { + (Some(x), Some(y)) => Some(from + x.min(y)), + (Some(x), None) => Some(from + x), + (None, Some(y)) => Some(from + y), + (None, None) => None, + } +} + +struct AnchorSpan<'a> { + tag_start: usize, + next_cursor: usize, + open_tag: &'a str, + inner: &'a str, +} + +fn find_anchor_span(slice: &str, from: usize) -> Option> { + let tail = slice.get(from..)?; + let open_rel = find_ascii_ci(tail, "' { + return Some(AnchorSpan { + tag_start, + next_cursor: tag_start + 2, + open_tag: "", + inner: "", + }); + } + let tag_end = tag_start + slice.get(tag_start..)?.find('>')?; + let close_pos = tag_end + 1 + find_ascii_ci(slice.get(tag_end + 1..)?, "")?; + Some(AnchorSpan { + tag_start, + next_cursor: close_pos + 4, + open_tag: slice.get(tag_start..=tag_end)?, + inner: slice.get(tag_end + 1..close_pos)?, + }) +} + +fn parse_next_anchor(slice: &str, from: usize) -> Option<(usize, Option)> { + let span = find_anchor_span(slice, from)?; + if span.open_tag.is_empty() { + return Some((span.next_cursor, None)); + } + let Some(href) = extract_attr_value(span.open_tag, "href") else { + return Some((span.next_cursor, None)); + }; + let Some((url, number)) = parse_discussion_href(href) else { + return Some((span.next_cursor, None)); + }; + let title = truncate_chars(&normalize_text(&strip_tags_and_decode(span.inner)), MAX_TITLE_CHARS); + if is_ignored_link_title(&title) { + return Some((span.next_cursor, None)); + } + let context = surrounding_card_window(slice, span.tag_start, span.next_cursor); + let category = extract_nearby_category(context); + let summary = build_summary(context, &category, &title); + Some(( + span.next_cursor, + Some(PinnedAnnouncement { + id: format!("discussion:{number}"), + number, + title, + summary, + url, + category, + }), + )) +} + +fn is_ignored_link_title(title: &str) -> bool { + title.len() < 2 + || title.bytes().all(|b| b.is_ascii_digit() || b == b',' || b == b' ') + || title.eq_ignore_ascii_case("pinned") +} + +fn surrounding_card_window(slice: &str, tag_start: usize, tag_end: usize) -> &str { + let start = floor_char_boundary(slice, tag_start.saturating_sub(512)); + let end = floor_char_boundary(slice, tag_end.saturating_add(1024)); + slice.get(start..end).unwrap_or("") +} + +fn extract_nearby_category(window: &str) -> String { + let Some(pos) = find_ascii_ci(window, "/discussions/categories/") else { + return String::new(); + }; + let Some(after) = window.get(pos..) else { + return String::new(); + }; + let Some(gt) = after.find('>') else { + return String::new(); + }; + let Some(rest) = after.get(gt + 1..) else { + return String::new(); + }; + let Some(close) = find_ascii_ci(rest, "") else { + return String::new(); + }; + let label = normalize_text(&strip_tags_and_decode(rest.get(..close).unwrap_or(""))); + truncate_chars(&label, 48) +} + +fn build_summary(window: &str, category: &str, title: &str) -> String { + if let Some(excerpt) = extract_excerpt_paragraph(window, title) { + return excerpt; + } + if !category.is_empty() { + return category.to_owned(); + } + String::new() +} + +fn extract_excerpt_paragraph(window: &str, title: &str) -> Option { + let p_start = find_ascii_ci(window, "')?; + let body = after_p.get(gt + 1..)?; + let close = find_ascii_ci(body, "

")?; + let text = normalize_text(&strip_tags_and_decode(body.get(..close)?)); + if text.len() < 4 || text.eq_ignore_ascii_case(title) { + return None; + } + Some(truncate_chars(&text, MAX_SUMMARY_CHARS)) +} + +fn extract_attr_value<'a>(tag: &'a str, attr_name: &str) -> Option<&'a str> { + let lower = tag.to_ascii_lowercase(); + let needle = format!("{attr_name}="); + let pos = lower.find(&needle)?; + let after = tag.get(pos + needle.len()..)?.trim_start(); + let first = after.as_bytes().first().copied()?; + if first == b'"' || first == b'\'' { + let rest = after.get(1..)?; + let end = rest.find(char::from(first))?; + rest.get(..end) + } else { + let end = after.find(|c: char| c.is_ascii_whitespace() || c == '>').unwrap_or(after.len()); + after.get(..end) + } +} + +fn strip_tags_and_decode(input: &str) -> String { + let mut no_tags = String::with_capacity(input.len()); + let mut in_tag = false; + for ch in input.chars() { + match ch { + '<' => { + in_tag = true; + no_tags.push(' '); + } + '>' => in_tag = false, + _ if !in_tag => no_tags.push(ch), + _ => {} + } + } + decode_html_entities(&no_tags) +} + +fn decode_html_entities(input: &str) -> String { + let mut out = String::with_capacity(input.len()); + let mut rest = input; + while let Some(amp) = rest.find('&') { + out.push_str(rest.get(..amp).unwrap_or("")); + let after = rest.get(amp + 1..).unwrap_or(""); + if let Some(semi) = after.find(';').filter(|&idx| idx <= 12) { + let entity = after.get(..semi).unwrap_or(""); + if let Some(ch) = decode_single_entity(entity) { + out.push(ch); + rest = after.get(semi + 1..).unwrap_or(""); + continue; + } + } + out.push('&'); + rest = after; + } + out.push_str(rest); + out +} + +fn decode_single_entity(entity: &str) -> Option { + match entity { + "amp" => Some('&'), + "lt" => Some('<'), + "gt" => Some('>'), + "quot" => Some('"'), + "apos" => Some('\''), + "nbsp" => Some(' '), + _ => decode_numeric_entity(entity), + } +} + +fn decode_numeric_entity(entity: &str) -> Option { + let body = entity.strip_prefix('#')?; + let code = if let Some(hex) = body.strip_prefix('x').or_else(|| body.strip_prefix('X')) { + u32::from_str_radix(hex, 16).ok()? + } else { + body.parse::().ok()? + }; + char::from_u32(code).filter(|c| !c.is_control() || *c == '\n' || *c == '\t') +} + +fn normalize_text(input: &str) -> String { + let mut out = String::with_capacity(input.len()); + let mut prev_space = true; + for ch in input.chars() { + if ch.is_whitespace() { + if !prev_space { + out.push(' '); + prev_space = true; + } + } else if !ch.is_control() { + out.push(ch); + prev_space = false; + } + } + if out.ends_with(' ') { + out.pop(); + } + out +} + +fn truncate_chars(input: &str, max_chars: usize) -> String { + if input.chars().count() <= max_chars { + return input.to_owned(); + } + let keep = max_chars.saturating_sub(1); + let mut out: String = input.chars().take(keep).collect(); + out.push('\u{2026}'); + out +} + +fn truncate_utf8_bytes(input: &str, max_bytes: usize) -> &str { + if input.len() <= max_bytes { + return input; + } + let end = floor_char_boundary(input, max_bytes); + input.get(..end).unwrap_or("") +} + +fn floor_char_boundary(s: &str, mut idx: usize) -> usize { + idx = idx.min(s.len()); + while idx > 0 && !s.is_char_boundary(idx) { + idx -= 1; + } + idx +} + +fn ceil_char_boundary(s: &str, mut idx: usize) -> usize { + idx = idx.min(s.len()); + while idx < s.len() && !s.is_char_boundary(idx) { + idx += 1; + } + idx +} + +fn starts_with_ignore_ascii_case(haystack: &str, prefix: &str) -> bool { + haystack + .get(..prefix.len()) + .is_some_and(|head| head.eq_ignore_ascii_case(prefix)) +} + +fn find_ascii_ci(haystack: &str, needle: &str) -> Option { + haystack.to_ascii_lowercase().find(&needle.to_ascii_lowercase()) +} + +#[cfg(test)] +mod tests { + use super::*; + + const SAMPLE_HTML: &str = r#" +
+
+ + V-Notch 2.5 Rust Engine & Native Cutover! + + Announcements +

V-Notch now runs on pure Rust core with lower RAM & faster blur.

+ 12 +
+ +
+ + "#; + + #[test] + fn parses_only_pinned_discussions_and_decodes_entities() { + let items = parse_pinned_discussions_html(SAMPLE_HTML); + assert_eq!(items.len(), 2); + assert_eq!(items[0].id, "discussion:42"); + assert_eq!(items[0].number, 42); + assert_eq!(items[0].title, "V-Notch 2.5 Rust Engine & Native Cutover!"); + assert_eq!(items[0].category, "Announcements"); + assert_eq!( + items[0].summary, + "V-Notch now runs on pure Rust core with lower RAM & faster blur." + ); + assert_eq!(items[0].url, "https://github.com/w0otdev/V-Notch/discussions/42"); + assert_eq!(items[1].id, "discussion:17"); + assert_eq!(items[1].title, "Community Roadmap '26"); + assert_eq!(items[1].summary, "General"); + } + + #[test] + fn fallback_parses_octicon_pin_cards_without_section_label() { + let html = r#" + + "#; + let items = parse_pinned_discussions_html(html); + assert_eq!(items.len(), 1); + assert_eq!(items[0].id, "discussion:88"); + assert_eq!(items[0].title, "Hotfix Notice"); + } + + #[test] + fn filters_seen_and_caps_merged_ids() { + let items = parse_pinned_discussions_html(SAMPLE_HTML); + let unseen = select_unseen_announcements(&items, &["discussion:42".to_owned()]); + assert_eq!(unseen.len(), 1); + assert_eq!(unseen[0].id, "discussion:17"); + + let merged = merge_seen_announcement_ids( + &["discussion:1".to_owned(), "discussion:2".to_owned()], + &["discussion:2".to_owned(), "discussion:3".to_owned()], + 2, + ); + assert_eq!(merged, vec!["discussion:2", "discussion:3"]); + } + + #[test] + fn validates_official_discussion_urls_strictly() { + assert!(is_official_discussions_page_url(OFFICIAL_DISCUSSIONS_URL)); + assert!(is_official_discussion_url( + "https://github.com/w0otdev/V-Notch/discussions/42" + )); + assert!(!is_official_discussion_url( + "https://evil.example/w0otdev/V-Notch/discussions/42" + )); + assert!(!is_official_discussion_url( + "http://github.com/w0otdev/V-Notch/discussions/42" + )); + assert!(!is_official_discussions_page_url( + "https://github.com/w0otdev/V-Notch/discussions?evil=1" + )); + } +} diff --git a/rust/crates/vnotch-core/src/updater/mod.rs b/rust/crates/vnotch-core/src/updater/mod.rs index 6f2bb554..04f2cc2a 100644 --- a/rust/crates/vnotch-core/src/updater/mod.rs +++ b/rust/crates/vnotch-core/src/updater/mod.rs @@ -1,10 +1,18 @@ //! Atom/GitHub release feed parsing, `SemVer` comparison, changelog merging, and signed manifest security. +pub mod announcements; pub mod changelog; pub mod feed; pub mod security; pub mod version; +pub use announcements::{ + ANNOUNCEMENTS_CACHE_SCHEMA_VERSION, ANNOUNCEMENTS_CACHE_TTL_SECS, AnnouncementsCache, + MAX_ANNOUNCEMENTS_HTML_BYTES, MAX_PINNED_ANNOUNCEMENTS, MAX_SEEN_ANNOUNCEMENT_IDS, + OFFICIAL_DISCUSSIONS_URL, PinnedAnnouncement, is_official_discussion_url, + is_official_discussions_page_url, merge_seen_announcement_ids, parse_pinned_discussions_html, + select_unseen_announcements, +}; pub use changelog::{ ChangelogEntry, ChangelogMergeRequest, ChangelogMergeState, ChangelogSnapshot, }; diff --git a/rust/crates/vnotch-ffi/src/exports/m03/announcements_abi.rs b/rust/crates/vnotch-ffi/src/exports/m03/announcements_abi.rs new file mode 100644 index 00000000..540799d2 --- /dev/null +++ b/rust/crates/vnotch-ffi/src/exports/m03/announcements_abi.rs @@ -0,0 +1,91 @@ +//! ABI 2.2 exports for fetching, parsing, and tracking pinned GitHub Discussions announcements. + +use std::ptr; + +use vnotch_core::updater::parse_pinned_discussions_html; + +use super::pods::{read_utf8_slice, write_owned_json}; +use crate::abi::{VnOwnedBytes, VnStatus, ffi_guard}; +use crate::sys::m03::{ + FetchAnnouncementsRequest, MarkAnnouncementsSeenRequest, fetch_unseen_announcements, + mark_announcements_seen, +}; + +/// Fetches unseen pinned GitHub Discussions announcements (`vn_announcements_fetch_unseen_utf8`). +#[unsafe(no_mangle)] +#[allow( + clippy::not_unsafe_ptr_arg_deref, + reason = "C ABI validates `req_json` and `out_json` inside ffi_guard" +)] +pub extern "system" fn vn_announcements_fetch_unseen_utf8( + req_json: *const u8, + req_len: u32, + out_json: *mut VnOwnedBytes, +) -> i32 { + ffi_guard(|| { + if out_json.is_null() { + return Err(VnStatus::InvalidArg); + } + // SAFETY: Caller guarantees `(req_json, req_len)` is valid UTF-8. + let req_str = unsafe { read_utf8_slice(req_json, req_len)? }; + let req: FetchAnnouncementsRequest = if req_str.trim().is_empty() { + FetchAnnouncementsRequest::default() + } else { + serde_json::from_str(req_str).map_err(|_| VnStatus::InvalidArg)? + }; + let resp = fetch_unseen_announcements(&req).map_err(|e| VnStatus::from(&e))?; + // SAFETY: `out_json` verified non-null above. + unsafe { write_owned_json(out_json, &resp) } + }) +} + +/// Marks announcement IDs as seen in local cache (`vn_announcements_mark_seen_utf8`). +#[unsafe(no_mangle)] +#[allow( + clippy::not_unsafe_ptr_arg_deref, + reason = "C ABI validates `req_json` and `out_count` inside ffi_guard" +)] +pub extern "system" fn vn_announcements_mark_seen_utf8( + req_json: *const u8, + req_len: u32, + out_count: *mut u32, +) -> i32 { + ffi_guard(|| { + if out_count.is_null() { + return Err(VnStatus::InvalidArg); + } + // SAFETY: Caller guarantees `(req_json, req_len)` is valid UTF-8. + let req_str = unsafe { read_utf8_slice(req_json, req_len)? }; + let req: MarkAnnouncementsSeenRequest = + serde_json::from_str(req_str).map_err(|_| VnStatus::InvalidArg)?; + let count = mark_announcements_seen(&req).map_err(|e| VnStatus::from(&e))?; + // SAFETY: `out_count` verified non-null above. + unsafe { + ptr::write(out_count, count); + } + Ok(()) + }) +} + +/// Parses pinned announcements from raw GitHub Discussions HTML (`vn_announcements_parse_pinned_utf8`). +#[unsafe(no_mangle)] +#[allow( + clippy::not_unsafe_ptr_arg_deref, + reason = "C ABI validates `html_utf8` and `out_json` inside ffi_guard" +)] +pub extern "system" fn vn_announcements_parse_pinned_utf8( + html_utf8: *const u8, + html_len: u32, + out_json: *mut VnOwnedBytes, +) -> i32 { + ffi_guard(|| { + if out_json.is_null() { + return Err(VnStatus::InvalidArg); + } + // SAFETY: Caller guarantees `(html_utf8, html_len)` is valid UTF-8. + let html = unsafe { read_utf8_slice(html_utf8, html_len)? }; + let items = parse_pinned_discussions_html(html); + // SAFETY: `out_json` verified non-null above. + unsafe { write_owned_json(out_json, &items) } + }) +} diff --git a/rust/crates/vnotch-ffi/src/exports/m03/mod.rs b/rust/crates/vnotch-ffi/src/exports/m03/mod.rs index bb170390..324856d6 100644 --- a/rust/crates/vnotch-ffi/src/exports/m03/mod.rs +++ b/rust/crates/vnotch-ffi/src/exports/m03/mod.rs @@ -1,10 +1,12 @@ //! M03 C ABI 2.2 exports (`SettingsStore`, `PerfMonitor`, `Updater`). +pub mod announcements_abi; pub mod perf_abi; pub mod pods; pub mod settings_abi; pub mod updater_abi; +pub use announcements_abi::*; pub use perf_abi::*; pub use pods::*; pub use settings_abi::*; diff --git a/rust/crates/vnotch-ffi/src/sys/m03/announcements.rs b/rust/crates/vnotch-ffi/src/sys/m03/announcements.rs new file mode 100644 index 00000000..0ae473e5 --- /dev/null +++ b/rust/crates/vnotch-ffi/src/sys/m03/announcements.rs @@ -0,0 +1,261 @@ +//! HTTPS fetcher and atomic local cache for pinned GitHub Discussions announcements. + +use std::fs; +use std::path::Path; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use reqwest::header::{ACCEPT, ETAG, IF_NONE_MATCH}; +use reqwest::redirect::Policy; +use serde::{Deserialize, Serialize}; +use tokio::runtime::Builder; +use vnotch_core::VnCoreError; +use vnotch_core::seam::FileReplacer; +use vnotch_core::updater::{ + ANNOUNCEMENTS_CACHE_SCHEMA_VERSION, ANNOUNCEMENTS_CACHE_TTL_SECS, AnnouncementsCache, + MAX_ANNOUNCEMENTS_HTML_BYTES, MAX_SEEN_ANNOUNCEMENT_IDS, OFFICIAL_DISCUSSIONS_URL, + PinnedAnnouncement, is_official_discussions_page_url, merge_seen_announcement_ids, + parse_pinned_discussions_html, select_unseen_announcements, +}; + +use super::win32::Win32FileReplacer; + +const ANNOUNCEMENTS_USER_AGENT: &str = "V-Notch/2.5.0"; +const FETCH_TIMEOUT_SECS: u64 = 15; +const MAX_REDIRECT_HOPS: usize = 3; + +/// Request payload for [`fetch_unseen_announcements`]. +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct FetchAnnouncementsRequest { + /// Path to `announcements-cache.json`. + pub cache_path: Option, + /// Optional discussions URL override (must pass official URL policy). + pub url: Option, + /// When `true`, bypasses local TTL freshness check (still sends `ETag`). + pub force_refresh: bool, +} + +/// Response payload returned by [`fetch_unseen_announcements`]. +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FetchAnnouncementsResponse { + /// Unseen pinned announcements ready to display in the Notch banner. + pub announcements: Vec, + /// Total pinned announcements currently known (seen + unseen). + pub total_pinned: usize, + /// `true` when served from the local TTL cache or HTTP `304 Not Modified`. + pub from_cache: bool, +} + +/// Request payload for [`mark_announcements_seen`]. +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct MarkAnnouncementsSeenRequest { + /// Path to `announcements-cache.json`. + pub cache_path: String, + /// Stable announcement IDs (`"discussion:"`) to record as seen. + pub ids: Vec, +} + +/// Fetches pinned GitHub Discussions announcements and returns only unseen items. +/// +/// # Errors +/// Returns [`VnCoreError::InvalidArg`] if the target URL fails the official origin check, or +/// [`VnCoreError::Io`] on network/runtime errors. +pub fn fetch_unseen_announcements( + req: &FetchAnnouncementsRequest, +) -> Result { + let url = req + .url + .as_deref() + .map(str::trim) + .filter(|s| !s.is_empty()) + .unwrap_or(OFFICIAL_DISCUSSIONS_URL); + if !is_official_discussions_page_url(url) { + return Err(VnCoreError::InvalidArg("untrusted announcements URL")); + } + let cache_path = req + .cache_path + .as_deref() + .map(str::trim) + .filter(|s| !s.is_empty()); + let mut cache = cache_path.map(load_cache).unwrap_or_default(); + let now_s = current_unix_seconds(); + if !req.force_refresh && cache.is_fresh(now_s, ANNOUNCEMENTS_CACHE_TTL_SECS) { + return Ok(build_response(&cache, true)); + } + let outcome = fetch_discussions_html(url, cache.etag.as_deref())?; + let from_cache = apply_fetch_outcome(&mut cache, outcome, now_s); + if let Some(path) = cache_path { + save_cache(path, &cache)?; + } + Ok(build_response(&cache, from_cache)) +} + +/// Records `req.ids` as seen in `req.cache_path` and returns the total tracked seen count. +/// +/// # Errors +/// Returns [`VnCoreError::InvalidArg`] if `cache_path` is empty, or [`VnCoreError::Io`] on I/O failure. +pub fn mark_announcements_seen(req: &MarkAnnouncementsSeenRequest) -> Result { + let path = req.cache_path.trim(); + if path.is_empty() { + return Err(VnCoreError::InvalidArg("cachePath must not be empty")); + } + let mut cache = load_cache(path); + cache.seen_ids = merge_seen_announcement_ids(&cache.seen_ids, &req.ids, MAX_SEEN_ANNOUNCEMENT_IDS); + cache.schema_version = ANNOUNCEMENTS_CACHE_SCHEMA_VERSION; + save_cache(path, &cache)?; + Ok(u32::try_from(cache.seen_ids.len()).unwrap_or(u32::MAX)) +} + +enum FetchOutcome { + NotModified, + Updated { html: String, etag: Option }, +} + +fn build_response(cache: &AnnouncementsCache, from_cache: bool) -> FetchAnnouncementsResponse { + let announcements = select_unseen_announcements(&cache.pinned, &cache.seen_ids); + FetchAnnouncementsResponse { + announcements, + total_pinned: cache.pinned.len(), + from_cache, + } +} + +fn apply_fetch_outcome( + cache: &mut AnnouncementsCache, + outcome: FetchOutcome, + now_s: i64, +) -> bool { + cache.schema_version = ANNOUNCEMENTS_CACHE_SCHEMA_VERSION; + cache.last_check_unix_s = now_s; + match outcome { + FetchOutcome::NotModified => true, + FetchOutcome::Updated { html, etag } => { + cache.pinned = parse_pinned_discussions_html(&html); + if etag.is_some() { + cache.etag = etag; + } + false + } + } +} + +fn fetch_discussions_html( + url: &str, + cached_etag: Option<&str>, +) -> Result { + let rt = Builder::new_current_thread() + .enable_all() + .build() + .map_err(|_| VnCoreError::Io("failed to start announcements tokio runtime"))?; + rt.block_on(fetch_discussions_html_async(url, cached_etag)) +} + +async fn fetch_discussions_html_async( + url: &str, + cached_etag: Option<&str>, +) -> Result { + let client = build_http_client()?; + let mut builder = client + .get(url) + .header(ACCEPT, "text/html,application/xhtml+xml"); + if let Some(etag) = cached_etag.map(str::trim).filter(|s| !s.is_empty()) { + builder = builder.header(IF_NONE_MATCH, etag); + } + let mut resp = builder + .send() + .await + .map_err(|_| VnCoreError::Io("failed to fetch GitHub Discussions page"))?; + let status = resp.status(); + if status == reqwest::StatusCode::NOT_MODIFIED { + return Ok(FetchOutcome::NotModified); + } + if !status.is_success() { + return Err(VnCoreError::Io("GitHub Discussions returned non-success status")); + } + let etag = resp + .headers() + .get(ETAG) + .and_then(|v| v.to_str().ok()) + .map(str::to_owned); + let html = read_bounded_utf8(&mut resp).await?; + Ok(FetchOutcome::Updated { html, etag }) +} + +fn build_http_client() -> Result { + let policy = Policy::custom(|attempt| { + if attempt.previous().len() >= MAX_REDIRECT_HOPS { + return attempt.error("too many redirects"); + } + if is_official_discussions_page_url(attempt.url().as_str()) { + attempt.follow() + } else { + attempt.error("untrusted redirect target") + } + }); + reqwest::Client::builder() + .https_only(true) + .timeout(Duration::from_secs(FETCH_TIMEOUT_SECS)) + .user_agent(ANNOUNCEMENTS_USER_AGENT) + .redirect(policy) + .build() + .map_err(|_| VnCoreError::Io("failed to build announcements HTTP client")) +} + +async fn read_bounded_utf8(resp: &mut reqwest::Response) -> Result { + let mut bytes = Vec::new(); + while let Some(chunk) = resp + .chunk() + .await + .map_err(|_| VnCoreError::Io("failed reading GitHub Discussions body"))? + { + if bytes.len().saturating_add(chunk.len()) > MAX_ANNOUNCEMENTS_HTML_BYTES { + let remaining = MAX_ANNOUNCEMENTS_HTML_BYTES.saturating_sub(bytes.len()); + if let Some(head) = chunk.get(..remaining) { + bytes.extend_from_slice(head); + } + break; + } + bytes.extend_from_slice(&chunk); + } + Ok(String::from_utf8_lossy(&bytes).into_owned()) +} + +fn load_cache(path: &str) -> AnnouncementsCache { + let Ok(raw) = fs::read_to_string(path) else { + return AnnouncementsCache::default(); + }; + let Ok(parsed) = serde_json::from_str::(&raw) else { + return AnnouncementsCache::default(); + }; + if parsed.schema_version != ANNOUNCEMENTS_CACHE_SCHEMA_VERSION { + return AnnouncementsCache { + seen_ids: parsed.seen_ids, + ..AnnouncementsCache::default() + }; + } + parsed +} + +fn save_cache(path: &str, cache: &AnnouncementsCache) -> Result<(), VnCoreError> { + let target = Path::new(path); + if let Some(parent) = target.parent() + && !parent.as_os_str().is_empty() + { + fs::create_dir_all(parent) + .map_err(|_| VnCoreError::Io("failed creating announcements cache directory"))?; + } + let json = serde_json::to_vec_pretty(cache) + .map_err(|_| VnCoreError::Internal("failed serializing announcements cache"))?; + let replacer = Win32FileReplacer; + replacer.replace_atomic(target, &json) +} + +fn current_unix_seconds() -> i64 { + let secs = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + i64::try_from(secs).unwrap_or(i64::MAX) +} diff --git a/rust/crates/vnotch-ffi/src/sys/m03/mod.rs b/rust/crates/vnotch-ffi/src/sys/m03/mod.rs index 46c107df..c3cf4f8a 100644 --- a/rust/crates/vnotch-ffi/src/sys/m03/mod.rs +++ b/rust/crates/vnotch-ffi/src/sys/m03/mod.rs @@ -1,10 +1,16 @@ //! M03 OS integration modules (`SettingsStore`, `PerfMonitor`, `Updater`, DPAPI, DXGI, PDH, NLS, Authenticode). +pub mod announcements; pub(crate) mod hook_slot; pub mod perf; pub mod updater; pub mod win32; +pub use announcements::{ + FetchAnnouncementsRequest, FetchAnnouncementsResponse, MarkAnnouncementsSeenRequest, + fetch_unseen_announcements, mark_announcements_seen, +}; + pub use perf::{ PdhGpuSampler, PerfMonitorHost, VnSystemMetricsSnapshot, VnSystemMetricsState, find_best_gpu_adapter, legacy_pdh_reset, legacy_pdh_sample, recommend_hardware_tier, diff --git a/scripts/r.ps1 b/scripts/r.ps1 index d0d182ba..78610fe6 100644 --- a/scripts/r.ps1 +++ b/scripts/r.ps1 @@ -1,7 +1,9 @@ param( # Use -Clean to force a full rebuild (e.g. when BAML/animations are suspected stale). # Defaults to a fast incremental build. - [switch]$Clean + [switch]$Clean, + # Use -ReleaseRust to build vnotch_rust.dll with full LTO release profile instead of dev-fast. + [switch]$ReleaseRust ) Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force @@ -202,9 +204,9 @@ Write-TreeSpacer $assetsPath = Join-Path $repoRoot "obj\project.assets.json" $lockFilePath = Join-Path $repoRoot "packages.lock.json" $rustRoot = Join-Path $repoRoot "rust" -$rustManifestPath = Join-Path $rustRoot "Cargo.toml" -$outNativeDllPath = Join-Path $rustRoot "target\release\vnotch_rust.dll" -$tripleNativeDllPath = Join-Path $rustRoot "target\x86_64-pc-windows-msvc\release\vnotch_rust.dll" +$rustProfile = if ($ReleaseRust) { "release" } else { "dev-fast" } +$outNativeDllPath = Join-Path $rustRoot "target\$rustProfile\vnotch_rust.dll" +$tripleNativeDllPath = Join-Path $rustRoot "target\x86_64-pc-windows-msvc\$rustProfile\vnotch_rust.dll" $binManagedDllPath = Join-Path $binPath "V-Notch.dll" $restoreReady = (Test-Path -LiteralPath $assetsPath) -and (-not (Test-Path -LiteralPath $lockFilePath) -or (Get-Item -LiteralPath $assetsPath).LastWriteTimeUtc -ge (Get-Item -LiteralPath $lockFilePath).LastWriteTimeUtc) $useNoRestore = (-not $Clean -and $restoreReady) @@ -350,21 +352,25 @@ if ($buildScope.Rust) { } $rustSw = [System.Diagnostics.Stopwatch]::StartNew() - $prevPriority = [System.Diagnostics.Process]::GetCurrentProcess().PriorityClass $rustOutput = @() $rustExitCode = 0 + $rustArgs = if ($ReleaseRust) { + @("build", "--release", "-p", "vnotch-ffi") + } else { + @("build", "--profile", "dev-fast", "-p", "vnotch-ffi") + } + Push-Location -LiteralPath $rustRoot try { - [System.Diagnostics.Process]::GetCurrentProcess().PriorityClass = [System.Diagnostics.ProcessPriorityClass]::BelowNormal - $rustOutput = & cargo build --release --manifest-path $rustManifestPath -p vnotch-ffi 2>&1 + $rustOutput = & cargo @rustArgs 2>&1 $rustExitCode = $LASTEXITCODE } finally { - [System.Diagnostics.Process]::GetCurrentProcess().PriorityClass = $prevPriority + Pop-Location } $rustSw.Stop() $rustDiagLines = @($rustOutput | ForEach-Object { "$_" } | Where-Object { $_.Trim().Length -gt 0 }) if ($rustExitCode -ne 0) { - Write-TreeItem ("Rust build failed in {0:N2}s (exit code {1}):" -f $rustSw.Elapsed.TotalSeconds, $rustExitCode) -State Error + Write-TreeItem ("Rust build ($rustProfile) failed in {0:N2}s (exit code {1}):" -f $rustSw.Elapsed.TotalSeconds, $rustExitCode) -State Error foreach ($line in $rustDiagLines) { $lineColor = if ($line -match "^error(\[|\:)") { "Red" } elseif ($line -match "^warning(\[|\:)") { "Yellow" } else { "Gray" } Write-Host " $gVert $line" -ForegroundColor $lineColor @@ -385,7 +391,7 @@ if ($buildScope.Rust) { Write-Host " $gBotLeft$lineRule`n" -ForegroundColor DarkCyan exit 1 } - Write-TreeItem ("Built vnotch_rust.dll in {0:N2}s." -f $rustSw.Elapsed.TotalSeconds) -State Success + Write-TreeItem ("Built vnotch_rust.dll ($rustProfile) in {0:N2}s." -f $rustSw.Elapsed.TotalSeconds) -State Success } if (-not $buildScope.Managed) { @@ -398,7 +404,7 @@ if (-not $buildScope.Managed) { } $buildSw.Stop() if ($buildScope.Rust) { - Write-TreeItem ("Staged vnotch_rust.dll; skipped C# build ({0:N2}s total)." -f $buildSw.Elapsed.TotalSeconds) -State Success + Write-TreeItem ("Staged vnotch_rust.dll ($rustProfile); skipped C# build ({0:N2}s total)." -f $buildSw.Elapsed.TotalSeconds) -State Success } else { Write-TreeItem ("No changes detected; skipped build in {0:N2}s." -f $buildSw.Elapsed.TotalSeconds) -State Success } @@ -410,6 +416,7 @@ if (-not $buildScope.Managed) { [System.Diagnostics.Process]::GetCurrentProcess().PriorityClass = [System.Diagnostics.ProcessPriorityClass]::BelowNormal $buildArgs = @( "build", $csprojPath, "-nologo", "-v:q", "-clp:NoSummary", "-m:2", + "-p:VNotchRustArtifactPath=$outNativeDllPath", "-p:RunAnalyzers=false", "-p:EnforceCodeStyleInBuild=false", "-p:EnableNETAnalyzers=false", "-p:CreateHardLinksForCopyFilesToOutputDirectoryIfPossible=true", From 94154036cb51f4ef92cabcecf3db99a7772e2558 Mon Sep 17 00:00:00 2001 From: viper1aa <129401103+w0otdev@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:41:34 +0700 Subject: [PATCH 3/4] Finalizing build --- Models/AppNotificationInfo.cs | 2 - Windows/MainWindow.Announcement.cs | 192 ----------------- Windows/MainWindow.AppNotification.cs | 3 +- .../MainWindow.AppNotificationInteraction.cs | 12 +- Windows/MainWindow.xaml.cs | 2 - Windows/SettingsWindow.Announcements.cs | 195 ++++++++++++++++++ Windows/SettingsWindow.FirstOpen.cs | 1 + Windows/SettingsWindow.GlassSurface.cs | 1 + Windows/SettingsWindow.xaml | 65 ++++++ .../vnotch-core/src/updater/announcements.rs | 6 +- .../vnotch-ffi/src/sys/m03/announcements.rs | 29 ++- 11 files changed, 285 insertions(+), 223 deletions(-) delete mode 100644 Windows/MainWindow.Announcement.cs create mode 100644 Windows/SettingsWindow.Announcements.cs diff --git a/Models/AppNotificationInfo.cs b/Models/AppNotificationInfo.cs index 29dd8021..0be38d55 100644 --- a/Models/AppNotificationInfo.cs +++ b/Models/AppNotificationInfo.cs @@ -12,6 +12,4 @@ public sealed class AppNotificationInfo public string Body { get; init; } = string.Empty; public ImageSource? AppIcon { get; init; } public DateTimeOffset CreationTime { get; init; } = DateTimeOffset.UtcNow; - public string? ActionUrl { get; init; } - public string? AnnouncementId { get; init; } } diff --git a/Windows/MainWindow.Announcement.cs b/Windows/MainWindow.Announcement.cs deleted file mode 100644 index 37ac9ebf..00000000 --- a/Windows/MainWindow.Announcement.cs +++ /dev/null @@ -1,192 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using System.Windows.Threading; -using VNotch.Interop; -using VNotch.Models; -using VNotch.Services; - -namespace VNotch; - -public partial class MainWindow -{ - private const int AnnouncementInitialDelayMs = 4500; - private const int AnnouncementRetryDelayMs = 3500; - private const int AnnouncementPollHours = 2; - private const int MaxAnnouncementDeferRetries = 20; - - private readonly Queue _pendingAnnouncements = new(); - private readonly HashSet _queuedAnnouncementIds = new(StringComparer.OrdinalIgnoreCase); - private UiScheduledTimer? _announcementInitialTimer; - private UiScheduledTimer? _announcementPollTimer; - private UiScheduledTimer? _announcementFlushTimer; - private CancellationTokenSource? _announcementCts; - private int _announcementDeferRetries; - - private void StartRepoAnnouncementsMonitor() - { - DisposeRepoAnnouncementsMonitor(); - _announcementCts = new CancellationTokenSource(); - - _announcementInitialTimer = new UiScheduledTimer - { - Interval = TimeSpan.FromMilliseconds(AnnouncementInitialDelayMs) - }; - _announcementInitialTimer.Tick += (_, _) => - { - StopAnnouncementTimer(ref _announcementInitialTimer); - CheckRepoAnnouncementsAsync().SafeFireAndForget("ANNOUNCEMENT"); - }; - _announcementInitialTimer.Start(); - - _announcementPollTimer = new UiScheduledTimer - { - Interval = TimeSpan.FromHours(AnnouncementPollHours) - }; - _announcementPollTimer.Tick += (_, _) => - CheckRepoAnnouncementsAsync().SafeFireAndForget("ANNOUNCEMENT"); - _announcementPollTimer.Start(); - } - - private void DisposeRepoAnnouncementsMonitor() - { - StopAnnouncementTimer(ref _announcementInitialTimer); - StopAnnouncementTimer(ref _announcementPollTimer); - StopAnnouncementTimer(ref _announcementFlushTimer); - var cts = Interlocked.Exchange(ref _announcementCts, null); - if (cts != null) - { - try { cts.Cancel(); } catch { } - cts.Dispose(); - } - _pendingAnnouncements.Clear(); - _queuedAnnouncementIds.Clear(); - } - - private async Task CheckRepoAnnouncementsAsync() - { - if (_cleanedUp || _settings.EnableLocalOnlyMode) - { - return; - } - - var cts = _announcementCts; - if (cts == null || cts.IsCancellationRequested) - { - return; - } - - try - { - IReadOnlyList unseen = - await RepoAnnouncementService.FetchUnseenAsync(forceRefresh: false, cts.Token); - if (_cleanedUp || cts.IsCancellationRequested || unseen.Count == 0) - { - return; - } - - await Dispatcher.InvokeAsync(() => - { - if (_cleanedUp) return; - foreach (var item in unseen) - { - if (!string.IsNullOrWhiteSpace(item.Id) && - !string.IsNullOrWhiteSpace(item.Title) && - _queuedAnnouncementIds.Add(item.Id)) - { - _pendingAnnouncements.Enqueue(item); - } - } - - _announcementDeferRetries = 0; - TryPresentNextRepoAnnouncement(); - }, DispatcherPriority.Normal); - } - catch (OperationCanceledException) - { - } - catch (Exception ex) - { - RuntimeLog.Warn("ANNOUNCEMENT", $"Pinned announcements check failed: {ex.Message}"); - } - } - - private void TryPresentNextRepoAnnouncement() - { - if (_cleanedUp || _pendingAnnouncements.Count == 0) - { - StopAnnouncementTimer(ref _announcementFlushTimer); - return; - } - - bool notchBusy = !_isNotchVisible || _isGreetingActive || _isExpanded || _isAnimating || - IsCountdownCompletionVisualActive || _isAppNotificationBannerVisible; - if (notchBusy) - { - if (_announcementDeferRetries++ < MaxAnnouncementDeferRetries) - { - ScheduleAnnouncementFlush(); - } - return; - } - - StopAnnouncementTimer(ref _announcementFlushTimer); - _announcementDeferRetries = 0; - PinnedAnnouncementDto next = _pendingAnnouncements.Dequeue(); - - string body = !string.IsNullOrWhiteSpace(next.Summary) - ? next.Summary - : "Pinned announcement · Click to open on GitHub"; - - var info = new AppNotificationInfo - { - AppName = "V-Notch", - Title = next.Title, - Body = body, - AppIcon = this.Icon, - ActionUrl = next.Url, - AnnouncementId = next.Id - }; - - ShowAppNotification(info); - - if (_isAppNotificationBannerVisible && - string.Equals(_activeAppNotification?.AnnouncementId, next.Id, StringComparison.Ordinal)) - { - string seenId = next.Id; - _ = Task.Run(() => RepoAnnouncementService.MarkSeen(seenId)); - if (_pendingAnnouncements.Count > 0) - { - ScheduleAnnouncementFlush(); - } - } - } - - private void ScheduleAnnouncementFlush() - { - if (_cleanedUp || _announcementFlushTimer != null) - { - return; - } - - _announcementFlushTimer = new UiScheduledTimer - { - Interval = TimeSpan.FromMilliseconds(AnnouncementRetryDelayMs) - }; - _announcementFlushTimer.Tick += (_, _) => - { - StopAnnouncementTimer(ref _announcementFlushTimer); - TryPresentNextRepoAnnouncement(); - }; - _announcementFlushTimer.Start(); - } - - private static void StopAnnouncementTimer(ref UiScheduledTimer? timer) - { - var current = timer; - timer = null; - current?.Stop(); - current?.Dispose(); - } -} diff --git a/Windows/MainWindow.AppNotification.cs b/Windows/MainWindow.AppNotification.cs index 2e5800ae..3e54eb38 100644 --- a/Windows/MainWindow.AppNotification.cs +++ b/Windows/MainWindow.AppNotification.cs @@ -60,8 +60,7 @@ internal void ShowAppNotification(AppNotificationInfo? notification) private void PresentAppNotificationBanner(AppNotificationInfo? notification, bool isQuotaAlert, System.Collections.Generic.IReadOnlyList? quotaAlerts = null) { - bool isAnnouncement = !string.IsNullOrEmpty(notification?.AnnouncementId); - if (notification == null || _cleanedUp || (!isQuotaAlert && !isAnnouncement && !_settings.ShowSystemNotifications)) return; + if (notification == null || _cleanedUp || (!isQuotaAlert && !_settings.ShowSystemNotifications)) return; if (!_isNotchVisible || _isGreetingActive || _isExpanded || _isAnimating || IsCountdownCompletionVisualActive) return; _isAiQuotaNotification = isQuotaAlert; diff --git a/Windows/MainWindow.AppNotificationInteraction.cs b/Windows/MainWindow.AppNotificationInteraction.cs index 3187971b..847f1e55 100644 --- a/Windows/MainWindow.AppNotificationInteraction.cs +++ b/Windows/MainWindow.AppNotificationInteraction.cs @@ -187,17 +187,7 @@ private void ActivateAppNotification(bool keyboard = false) var active = _activeAppNotification; bool activateApp = !_isAiQuotaNotification; BeginAppNotificationDismiss(0, keyboard); - if (activateApp && active != null) - { - if (!string.IsNullOrWhiteSpace(active.ActionUrl)) - { - _ = SafeLauncher.TryOpenUrl(active.ActionUrl); - } - else - { - _ = AppNotificationService.TryActivateApp(active.AppId, active.AppName); - } - } + if (activateApp && active != null) _ = AppNotificationService.TryActivateApp(active.AppId, active.AppName); } private void AppNotificationBanner_KeyDown(object sender, KeyEventArgs e) diff --git a/Windows/MainWindow.xaml.cs b/Windows/MainWindow.xaml.cs index 246826c9..724ce61e 100644 --- a/Windows/MainWindow.xaml.cs +++ b/Windows/MainWindow.xaml.cs @@ -565,7 +565,6 @@ private void MainWindow_Loaded(object sender, RoutedEventArgs e) SetAvailableUpdate(initialUpdate); } CheckForUpdatesAsync().SafeFireAndForget("UPDATE-CHECK"); - StartRepoAnnouncementsMonitor(); PrepareFirstOpenUi(); @@ -754,7 +753,6 @@ private void PerformCleanup() _ownedTrayIcon = null; _updateTimer?.Dispose(); _updateCheckTimer?.Dispose(); - DisposeRepoAnnouncementsMonitor(); _updatePulseTimer?.Dispose(); _updatePulseTimer = null; if (_updateService != null) diff --git a/Windows/SettingsWindow.Announcements.cs b/Windows/SettingsWindow.Announcements.cs new file mode 100644 index 00000000..5dc71c0b --- /dev/null +++ b/Windows/SettingsWindow.Announcements.cs @@ -0,0 +1,195 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Media; +using System.Windows.Media.Animation; +using System.Windows.Threading; +using VNotch.Interop; +using VNotch.Services; + +namespace VNotch; + +public partial class SettingsWindow +{ + private readonly Queue _repoAnnouncementsQueue = new(); + private CancellationTokenSource? _repoAnnouncementsCts; + private PinnedAnnouncementDto? _activeRepoAnnouncement; + private bool _isRepoAnnouncementBannerVisible; + private int _repoAnnouncementTotalCount; + private int _repoAnnouncementShownIndex; + + private async Task LoadRepoAnnouncementsAsync() + { + if (_isClosing || _settings.EnableLocalOnlyMode || RepoAnnouncementBanner == null) + { + return; + } + + CancelRepoAnnouncementsFetch(); + var cts = new CancellationTokenSource(); + _repoAnnouncementsCts = cts; + + try + { + IReadOnlyList unseen = + await RepoAnnouncementService.FetchUnseenAsync(forceRefresh: false, cts.Token); + if (_isClosing || cts.IsCancellationRequested || unseen.Count == 0) + { + return; + } + + await Dispatcher.InvokeAsync(() => + { + if (_isClosing || cts.IsCancellationRequested) return; + _repoAnnouncementsQueue.Clear(); + foreach (var item in unseen) + { + if (!string.IsNullOrWhiteSpace(item.Id) && !string.IsNullOrWhiteSpace(item.Title)) + { + _repoAnnouncementsQueue.Enqueue(item); + } + } + + _repoAnnouncementTotalCount = _repoAnnouncementsQueue.Count; + _repoAnnouncementShownIndex = 0; + ShowNextRepoAnnouncement(); + }, DispatcherPriority.Normal); + } + catch (OperationCanceledException) + { + } + catch (Exception ex) + { + RuntimeLog.Warn(LogCategory, $"Failed loading pinned announcements: {ex.Message}"); + } + } + + private void ShowNextRepoAnnouncement() + { + if (RepoAnnouncementBanner == null || _isClosing) + { + return; + } + + if (_repoAnnouncementsQueue.Count == 0) + { + _activeRepoAnnouncement = null; + HideRepoAnnouncementBanner(); + return; + } + + PinnedAnnouncementDto next = _repoAnnouncementsQueue.Dequeue(); + _activeRepoAnnouncement = next; + _repoAnnouncementShownIndex++; + + RepoAnnouncementTitle.Text = next.Title; + RepoAnnouncementMessage.Text = !string.IsNullOrWhiteSpace(next.Summary) + ? next.Summary + : "Pinned announcement on GitHub Discussions."; + RepoAnnouncementDetailsButton.Content = Loc.Get("settings.cpp26Banner.details"); + RepoAnnouncementDismissButton.Content = Loc.Get("settings.cpp26Banner.dismiss"); + + if (_repoAnnouncementTotalCount > 1) + { + RepoAnnouncementBadgeText.Text = $"{_repoAnnouncementShownIndex}/{_repoAnnouncementTotalCount}"; + RepoAnnouncementBadge.Visibility = Visibility.Visible; + } + else + { + RepoAnnouncementBadge.Visibility = Visibility.Collapsed; + } + + if (_isRepoAnnouncementBannerVisible && RepoAnnouncementBanner.Visibility == Visibility.Visible) + { + return; + } + + _isRepoAnnouncementBannerVisible = true; + RepoAnnouncementBanner.Visibility = Visibility.Visible; + + int fps = AnimationConfig.TargetFps; + var ease = new ExponentialEase { EasingMode = EasingMode.EaseOut, Exponent = 6 }; + + RepoAnnouncementBanner.BeginAnimation(OpacityProperty, null); + RepoAnnouncementTranslate.BeginAnimation(TranslateTransform.YProperty, null); + + var fade = new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(350)) { EasingFunction = ease }; + var slide = new DoubleAnimation(20, 0, TimeSpan.FromMilliseconds(350)) { EasingFunction = ease }; + + Timeline.SetDesiredFrameRate(fade, fps); + Timeline.SetDesiredFrameRate(slide, fps); + + RepoAnnouncementBanner.BeginAnimation(OpacityProperty, fade); + RepoAnnouncementTranslate.BeginAnimation(TranslateTransform.YProperty, slide); + } + + private void HideRepoAnnouncementBanner() + { + if (RepoAnnouncementBanner == null || !_isRepoAnnouncementBannerVisible) + { + return; + } + + _isRepoAnnouncementBannerVisible = false; + int fps = AnimationConfig.TargetFps; + var ease = new ExponentialEase { EasingMode = EasingMode.EaseIn, Exponent = 5 }; + + var fade = new DoubleAnimation(RepoAnnouncementBanner.Opacity, 0, TimeSpan.FromMilliseconds(250)) { EasingFunction = ease }; + var slide = new DoubleAnimation(RepoAnnouncementTranslate.Y, 20, TimeSpan.FromMilliseconds(250)) { EasingFunction = ease }; + + Timeline.SetDesiredFrameRate(fade, fps); + Timeline.SetDesiredFrameRate(slide, fps); + + fade.Completed += (_, _) => + { + if (!_isRepoAnnouncementBannerVisible) + { + RepoAnnouncementBanner.BeginAnimation(OpacityProperty, null); + RepoAnnouncementTranslate.BeginAnimation(TranslateTransform.YProperty, null); + RepoAnnouncementBanner.Opacity = 0; + RepoAnnouncementTranslate.Y = 20; + RepoAnnouncementBanner.Visibility = Visibility.Collapsed; + } + }; + + RepoAnnouncementBanner.BeginAnimation(OpacityProperty, fade); + RepoAnnouncementTranslate.BeginAnimation(TranslateTransform.YProperty, slide); + } + + private void RepoAnnouncementDetails_Click(object sender, RoutedEventArgs e) + { + var current = _activeRepoAnnouncement; + if (current != null) + { + string seenId = current.Id; + _ = Task.Run(() => RepoAnnouncementService.MarkSeen(seenId)); + SafeLauncher.TryOpenUrl(current.Url); + } + + ShowNextRepoAnnouncement(); + } + + private void RepoAnnouncementDismiss_Click(object sender, RoutedEventArgs e) + { + var current = _activeRepoAnnouncement; + if (current != null) + { + string seenId = current.Id; + _ = Task.Run(() => RepoAnnouncementService.MarkSeen(seenId)); + } + + ShowNextRepoAnnouncement(); + } + + private void CancelRepoAnnouncementsFetch() + { + var cts = Interlocked.Exchange(ref _repoAnnouncementsCts, null); + if (cts != null) + { + try { cts.Cancel(); } catch { } + cts.Dispose(); + } + } +} diff --git a/Windows/SettingsWindow.FirstOpen.cs b/Windows/SettingsWindow.FirstOpen.cs index 67585494..8d01c680 100644 --- a/Windows/SettingsWindow.FirstOpen.cs +++ b/Windows/SettingsWindow.FirstOpen.cs @@ -151,5 +151,6 @@ private void EnsureBackgroundInitializationStarted() { _updatePresenter.CheckForUpdatesAsync().SafeFireAndForget("SETTINGS-UPDATE-CHECK"); } + LoadRepoAnnouncementsAsync().SafeFireAndForget("SETTINGS-ANNOUNCEMENTS"); } } diff --git a/Windows/SettingsWindow.GlassSurface.cs b/Windows/SettingsWindow.GlassSurface.cs index a38e7705..a86ca1de 100644 --- a/Windows/SettingsWindow.GlassSurface.cs +++ b/Windows/SettingsWindow.GlassSurface.cs @@ -142,6 +142,7 @@ protected override void OnClosed(EventArgs e) StopAndDisposeTagTimer(ImportSettingsButton); StopAndDisposeTagTimer(CheckUpdateButton); _updatePresenter.Dispose(); + CancelRepoAnnouncementsFetch(); Loc.ReleaseTranslationIndex(); _monitorChoicesClosed = true; UnsubscribeDisplaySettingsChanged(); diff --git a/Windows/SettingsWindow.xaml b/Windows/SettingsWindow.xaml index 807374b6..0a9f0bae 100644 --- a/Windows/SettingsWindow.xaml +++ b/Windows/SettingsWindow.xaml @@ -4161,6 +4161,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +