From 7ca9c6a2da739df06d03f1fca8906343ad86a6b7 Mon Sep 17 00:00:00 2001 From: wgw Date: Sun, 15 Nov 2026 15:53:56 +0800 Subject: [PATCH] =?UTF-8?q?fix(workbench):=20=E5=B0=86=E9=80=9A=E7=9F=A5?= =?UTF-8?q?=E5=B7=B2=E8=AF=BB=E8=BF=81=E7=A7=BB=E5=92=8C=E8=AE=A1=E6=95=B0?= =?UTF-8?q?=E8=A7=84=E5=88=99=E7=A7=BB=E5=85=A5=20Core?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rust/contracts/application-boundary.md | 1 + rust/contracts/rust-core-api.md | 41 +++ rust/crates/core-rules/src/dispatch.rs | 2 + rust/crates/core-rules/src/workbench/mod.rs | 6 + .../src/workbench/notification_read.rs | 124 +++++++ .../tests/notification_read_fixture.rs | 45 +++ rust/crates/core/src/protocol/command.rs | 6 + rust/crates/core/src/runtime/dispatcher.rs | 5 + rust/crates/core/src/tests/mod.rs | 1 + .../core/src/tests/notification_read.rs | 38 ++ .../workbench/notification-read-state-v1.json | 326 ++++++++++++++++++ 11 files changed, 595 insertions(+) create mode 100644 rust/crates/core-rules/src/workbench/notification_read.rs create mode 100644 rust/crates/core-rules/tests/notification_read_fixture.rs create mode 100644 rust/crates/core/src/tests/notification_read.rs create mode 100644 rust/fixtures/workbench/notification-read-state-v1.json diff --git a/rust/contracts/application-boundary.md b/rust/contracts/application-boundary.md index 6508fb5c..2c2082f6 100644 --- a/rust/contracts/application-boundary.md +++ b/rust/contracts/application-boundary.md @@ -59,6 +59,7 @@ this lifecycle protection; actual symbol computation remains upstream-owned. | Run/Debug | versioned configuration documents, three-layer resolution, diagnostics, platform-neutral launch plans, DAP framing/state, reverse terminal requests, breakpoint relocation, stepping filters, threads, stacks, variables, and events | project and preference persistence, native edit reporting, adapter discovery, PTY/ConPTY debuggee launch, child processes, sockets, native termination, and UI | | Terminal | input bytes, output bytes, lifecycle; [shell selection semantics](terminal-profiles.md) | PTY/ConPTY, shell discovery, native profile preferences, and environment | | Workbench background | versioned source (`none`, bundled slot `01`–`10`, or `custom`) and opacity | UI, image rendering, bundled-resource packaging, local-image access permission and persistence | +| Notification read state | window-owned unread identities, arrivals/repeats, eviction and mark-all-read transitions, unread count | notification text, history presentation, stable row identities, native toasts and entry-point visibility | | Local History | revision metadata, text content, restore result | persistence location and file operations | | Application logging | fixed module categories, versioned event context, recursive privacy rules, bounded timeline filters and frozen diagnostic preview manifests | background queues, native file rotation/retention, effective directory fallback, crash capture, session selection, viewing and user-selected export destinations | | Modules | stable IDs, manifests, enabled state, lifecycle snapshots, dependencies, capabilities, and contributions | native factories, processes, timers, PTY/ConPTY, watchers, connections, and UI rendering | diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 504143cc..82a34594 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -599,6 +599,7 @@ or removing a command fails until the table changes in the same commit. | `workspace.classifyVisibility` | Classify a batch of workspace-relative paths as hidden or visible. The rule lives in `lithe-core-rules` so the Windows frontend can run it synchronously | | `workspace.visibilityDefaults` | Return the built-in hidden-path lists (from `lithe-core-rules`) | | `workbench.chromeLayout.reduce` | Apply one transition to the rearrangeable workbench chrome: stripe, title bar and status bar button placement, hidden stripe buttons and open tool panels (from `lithe-core-rules`) | +| `workbench.notifications.reduceReadState` | Apply one notification arrival or mark a window's history read; return bounded unread identities and the ready-to-render count (from `lithe-core-rules`) | | `terminal.parseLinkTarget` | Resolve terminal link candidates into file or external targets | | `outputStyle.decode` | Decode one chunk of console output with ANSI escapes into plain lines and styled ranges, carrying the console's state to the next chunk | | `debug.createSession` | Create a transport-neutral DAP session and return its initialize frame | @@ -6414,3 +6415,43 @@ No third-party keymap import or plugin protocol change is introduced. The reduce lives in the pure crate `rust/crates/core-rules`. Executable vectors: `rust/fixtures/editor/ide-essentials-v1.json` (C ABI tests). + +## Notification read state + +`workbench.notifications.reduceReadState` is a pure synchronous reducer owned by +`lithe-core-rules`. A native window holds the returned state and submits it with +its next event. Core retains no global state and performs no I/O. Notification +text, timestamps, toast handles and display rows remain in the host; only read +metadata crosses this boundary, and only when a notification or visibility event +changes it. Painting reads the last returned `unreadCount` without invoking Core. + +Payload: `{ state?: { unreadIds?: [id, ...] }, action }`. Omitted state/identities +mean an empty set. Identities are positive `u64` host-generated stable history +record IDs; a replacing toast must keep the record's original identity. + +- `{ kind: "arrived", id, forgottenId?: id | null, historyVisible: boolean }` + records a new arrival or repeat. When either history entry point is visible, + it marks the whole history read. Otherwise it removes the evicted identity + (if supplied), moves the arriving identity to the front of the unread set and + counts it once. The evicted record may already be read or absent from the set. +- `{ kind: "markAllRead" }` marks every record read, including when the user + explicitly clears the history. Repeated calls are idempotent. + +The response is `{ state: { unreadIds: [...] }, unreadCount }`. The count is the +number of distinct unread records; it does not rely on unread records forming a +prefix in the host's display order. Closing a history entry point changes no +read state. A new arrival after reading may make the same identity unread again. +The state belongs to one window and is discarded when that window closes. + +The wire safety bound is 1024 unread identities; a host may keep a smaller +history and supplies its evicted identity with the next arrival. Zero IDs, +duplicate input IDs, over-limit state or results, unknown fields/actions and +malformed payloads return `invalid_request`, without a replacement state. Hosts +preserve the last valid read projection and record the failure; they do not +reimplement the rules as a fallback. No notification content is included in the +state or diagnostic payload. + +[Shared read-state fixture](../fixtures/workbench/notification-read-state-v1.json) +executes through the rule dispatcher, the Core JSON envelope and the desktop +bridge. It covers repeats, either history entry point, clearing, visible +arrivals, non-prefix display order, read/unread eviction and invalid inputs. diff --git a/rust/crates/core-rules/src/dispatch.rs b/rust/crates/core-rules/src/dispatch.rs index 2bbfe546..4fa7b36e 100644 --- a/rust/crates/core-rules/src/dispatch.rs +++ b/rust/crates/core-rules/src/dispatch.rs @@ -15,6 +15,7 @@ pub const COMMANDS: &[&str] = &[ visibility::CLASSIFY_VISIBILITY, visibility::VISIBILITY_DEFAULTS, workbench::REDUCE_CHROME_LAYOUT, + workbench::REDUCE_NOTIFICATION_READ_STATE, ]; /// Runs one rule on an already decoded payload. @@ -30,6 +31,7 @@ pub fn execute(command: &str, payload: Value) -> Result { visibility::CLASSIFY_VISIBILITY => visibility::classify_visibility_json(payload), visibility::VISIBILITY_DEFAULTS => visibility::visibility_defaults_json(payload), workbench::REDUCE_CHROME_LAYOUT => workbench::reduce_chrome_layout_json(payload), + workbench::REDUCE_NOTIFICATION_READ_STATE => workbench::reduce_read_state_json(payload), _ => Err(RuleError::new( RuleErrorCode::NotSupported, "Unknown rule command", diff --git a/rust/crates/core-rules/src/workbench/mod.rs b/rust/crates/core-rules/src/workbench/mod.rs index 6565883b..a96656f7 100644 --- a/rust/crates/core-rules/src/workbench/mod.rs +++ b/rust/crates/core-rules/src/workbench/mod.rs @@ -1,8 +1,14 @@ //! Workbench chrome rules that a host runs when the user rearranges the window. mod chrome_layout; +mod notification_read; pub use chrome_layout::{ reduce as reduce_chrome_layout, reduce_json as reduce_chrome_layout_json, Action, CatalogItem, Placement, Reduction, State, Surface, Zone, REDUCE_CHROME_LAYOUT, }; + +pub use notification_read::{ + reduce_read_state, reduce_read_state_json, ReadAction, ReadReduction, ReadState, + REDUCE_NOTIFICATION_READ_STATE, +}; diff --git a/rust/crates/core-rules/src/workbench/notification_read.rs b/rust/crates/core-rules/src/workbench/notification_read.rs new file mode 100644 index 00000000..3f71dd96 --- /dev/null +++ b/rust/crates/core-rules/src/workbench/notification_read.rs @@ -0,0 +1,124 @@ +//! Notification read transitions; hosts retain text, toasts and native presentation. + +use crate::{RuleError, RuleErrorCode}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::collections::HashSet; + +/// The Core command for notification read transitions. +pub const REDUCE_NOTIFICATION_READ_STATE: &str = "workbench.notifications.reduceReadState"; + +// A wire safety bound, independent of the host's smaller visible-history limit. +const MAX_UNREAD_IDS: usize = 1024; + +/// Window-owned read metadata, with no notification content or display-order dependency. +#[derive(Debug, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ReadState { + /// Unique positive host identities of unread history records, newest arrival first. + #[serde(default)] + pub unread_ids: Vec, +} + +/// One host event; a repeated record retains its original identity. +#[derive(Debug, Deserialize)] +#[serde( + tag = "kind", + rename_all = "camelCase", + rename_all_fields = "camelCase", + deny_unknown_fields +)] +pub enum ReadAction { + /// A new arrival or repeat, after the host updates its bounded display history. + Arrived { + /// Stable positive history-record identity, not the replacing toast identity. + id: u64, + /// Identity evicted from the display history, whether previously read or unread. + forgotten_id: Option, + /// The host is currently presenting either history entry point to the user. + history_visible: bool, + }, + /// Either history entry point was viewed, or its history was explicitly cleared. + MarkAllRead, +} + +/// The next state and its ready-to-render count; hosts do not recalculate the count. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ReadReduction { + /// Metadata to supply with the next event, scoped to the same native window. + pub state: ReadState, + /// Number of distinct unread records, independent of notification display order. + pub unread_count: usize, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Request { + #[serde(default)] + state: ReadState, + action: ReadAction, +} + +fn invalid() -> RuleError { + RuleError::new( + RuleErrorCode::InvalidRequest, + "Invalid notification read request", + ) +} + +/// Applies an event without clocks or retained global state. +/// +/// Rejects zero or duplicate identities and metadata exceeding the wire bound. +/// Repeated arrivals count once; eviction can remove any unread identity, so no +/// prefix invariant in the host's display list is required. +pub fn reduce_read_state( + mut state: ReadState, + action: ReadAction, +) -> Result { + let mut seen = HashSet::with_capacity(state.unread_ids.len().min(MAX_UNREAD_IDS)); + if state.unread_ids.len() > MAX_UNREAD_IDS + || state + .unread_ids + .iter() + .any(|&id| id == 0 || !seen.insert(id)) + { + return Err(invalid()); + } + match action { + ReadAction::MarkAllRead => state.unread_ids.clear(), + ReadAction::Arrived { + id, + forgotten_id, + history_visible, + } => { + if id == 0 || forgotten_id == Some(0) { + return Err(invalid()); + } + if history_visible { + state.unread_ids.clear(); + } else { + state + .unread_ids + .retain(|&old| old != id && Some(old) != forgotten_id); + if state.unread_ids.len() == MAX_UNREAD_IDS { + return Err(invalid()); + } + state.unread_ids.insert(0, id); + } + } + } + let unread_count = state.unread_ids.len(); + Ok(ReadReduction { + state, + unread_count, + }) +} + +/// Decodes the command payload and returns the deterministic read projection. +pub fn reduce_read_state_json(payload: Value) -> Result { + let request: Request = serde_json::from_value(payload) + .map_err(|error| invalid().with_details(error.to_string()))?; + let reduction = reduce_read_state(request.state, request.action)?; + serde_json::to_value(reduction).map_err(|error| invalid().with_details(error.to_string())) +} diff --git a/rust/crates/core-rules/tests/notification_read_fixture.rs b/rust/crates/core-rules/tests/notification_read_fixture.rs new file mode 100644 index 00000000..b77a2a7d --- /dev/null +++ b/rust/crates/core-rules/tests/notification_read_fixture.rs @@ -0,0 +1,45 @@ +//! Checks shared notification read transitions through the dispatch used by Core. + +use lithe_core_rules::{execute, RuleErrorCode}; +use serde_json::{json, Value}; + +const FIXTURE: &str = include_str!("../../../fixtures/workbench/notification-read-state-v1.json"); +const COMMAND: &str = "workbench.notifications.reduceReadState"; + +#[test] +fn shared_read_transitions_match() { + let fixture: Value = serde_json::from_str(FIXTURE).unwrap(); + assert_eq!(fixture["version"], 1); + for case in fixture["cases"].as_array().unwrap() { + let actual = execute(COMMAND, case["payload"].clone()).unwrap(); + assert_eq!(actual, case["expected"], "{}", case["name"]); + } +} + +#[test] +fn malformed_read_transitions_are_rejected() { + let fixture: Value = serde_json::from_str(FIXTURE).unwrap(); + for case in fixture["errors"].as_array().unwrap() { + let error = execute(COMMAND, case["payload"].clone()).unwrap_err(); + assert_eq!( + error.code, + RuleErrorCode::InvalidRequest, + "{}", + case["name"] + ); + } +} + +#[test] +fn unread_metadata_is_bounded() { + let ids: Vec = (1..=1024).collect(); + let state = json!({"unreadIds": ids}); + let payload = + json!({"state": state, "action": {"kind": "arrived", "id": 1025, "historyVisible": false}}); + assert_eq!( + execute(COMMAND, payload).unwrap_err().code, + RuleErrorCode::InvalidRequest + ); + let payload = json!({"state": state, "action": {"kind": "arrived", "id": 1025, "forgottenId": 4, "historyVisible": false}}); + assert_eq!(execute(COMMAND, payload).unwrap()["unreadCount"], 1024); +} diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index d8660234..44e168cd 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -144,6 +144,9 @@ pub enum CoreCommand { /// button placement, hidden stripe buttons and open tool panels (`workbench.chromeLayout.reduce`), /// from `lithe-core-rules`. WorkbenchChromeLayoutReduce, + /// Applies a notification arrival or marks window-owned history read + /// (`workbench.notifications.reduceReadState`), from `lithe-core-rules`. + WorkbenchNotificationsReduceReadState, /// Resolves terminal link candidates into file or external targets (`terminal.parseLinkTarget`). TerminalParseLinkTarget, /// Decodes one chunk of console output with ANSI escapes into plain lines and styled ranges @@ -1228,6 +1231,9 @@ impl CoreCommand { Some(Self::Workspace(WorkspaceCommand::VisibilityDefaults)) } "workbench.chromeLayout.reduce" => Some(Self::WorkbenchChromeLayoutReduce), + "workbench.notifications.reduceReadState" => { + Some(Self::WorkbenchNotificationsReduceReadState) + } "terminal.parseLinkTarget" => Some(Self::TerminalParseLinkTarget), "outputStyle.decode" => Some(Self::OutputStyleDecode), "debug.createSession" => Some(Self::Debug(DebugCommand::CreateSession)), diff --git a/rust/crates/core/src/runtime/dispatcher.rs b/rust/crates/core/src/runtime/dispatcher.rs index 2a2cd218..deb5bbe5 100644 --- a/rust/crates/core/src/runtime/dispatcher.rs +++ b/rust/crates/core/src/runtime/dispatcher.rs @@ -458,6 +458,11 @@ fn execute_parsed(mut parsed: CoreRequest, document: Option<&str>) -> CoreRespon CoreCommand::WorkbenchChromeLayoutReduce => { rules_response(id, "workbench.chromeLayout.reduce", parsed.payload) } + CoreCommand::WorkbenchNotificationsReduceReadState => rules_response( + id, + "workbench.notifications.reduceReadState", + parsed.payload, + ), CoreCommand::TerminalParseLinkTarget => { let result = serde_json::from_value::(parsed.payload) diff --git a/rust/crates/core/src/tests/mod.rs b/rust/crates/core/src/tests/mod.rs index 6c17ae09..57da99c3 100644 --- a/rust/crates/core/src/tests/mod.rs +++ b/rust/crates/core/src/tests/mod.rs @@ -42,6 +42,7 @@ mod keymap_import; mod language_server_sessions; mod lsp_policy; mod marketplace_plugins; +mod notification_read; mod plugin_editor_resources; mod plugin_run_debug; mod plugin_settings_documents; diff --git a/rust/crates/core/src/tests/notification_read.rs b/rust/crates/core/src/tests/notification_read.rs new file mode 100644 index 00000000..7d7f8ae1 --- /dev/null +++ b/rust/crates/core/src/tests/notification_read.rs @@ -0,0 +1,38 @@ +//! Verifies notification fixtures through the public JSON command envelope. + +use crate::execute_json; +use serde_json::{json, Value}; + +#[test] +fn notification_read_fixture_crosses_the_core_dispatch() { + let fixture: Value = serde_json::from_str(include_str!( + "../../../../fixtures/workbench/notification-read-state-v1.json" + )) + .unwrap(); + for case in fixture["cases"].as_array().unwrap() { + let response: Value = serde_json::from_str(&execute_json( + &json!({ + "id": "notification-read-fixture", + "command": fixture["command"], + "payload": case["payload"] + }) + .to_string(), + )) + .unwrap(); + assert_eq!(response["ok"], true, "{}: {response}", case["name"]); + assert_eq!(response["data"], case["expected"], "{}", case["name"]); + } + for case in fixture["errors"].as_array().unwrap() { + let response: Value = serde_json::from_str(&execute_json( + &json!({ + "id": "notification-read-invalid-fixture", + "command": fixture["command"], + "payload": case["payload"] + }) + .to_string(), + )) + .unwrap(); + assert_eq!(response["ok"], false, "{}", case["name"]); + assert_eq!(response["error"]["code"], case["error"], "{}", case["name"]); + } +} diff --git a/rust/fixtures/workbench/notification-read-state-v1.json b/rust/fixtures/workbench/notification-read-state-v1.json new file mode 100644 index 00000000..633af7ba --- /dev/null +++ b/rust/fixtures/workbench/notification-read-state-v1.json @@ -0,0 +1,326 @@ +{ + "version": 1, + "command": "workbench.notifications.reduceReadState", + "cases": [ + { + "name": "first unread arrival", + "payload": { + "state": { + "unreadIds": [] + }, + "action": { + "kind": "arrived", + "id": 1, + "historyVisible": false + } + }, + "expected": { + "state": { + "unreadIds": [ + 1 + ] + }, + "unreadCount": 1 + } + }, + { + "name": "repeated unread is counted once", + "payload": { + "state": { + "unreadIds": [ + 2, + 1 + ] + }, + "action": { + "kind": "arrived", + "id": 1, + "historyVisible": false + } + }, + "expected": { + "state": { + "unreadIds": [ + 1, + 2 + ] + }, + "unreadCount": 2 + } + }, + { + "name": "read notice becomes unread again", + "payload": { + "state": { + "unreadIds": [ + 2 + ] + }, + "action": { + "kind": "arrived", + "id": 1, + "historyVisible": false + } + }, + "expected": { + "state": { + "unreadIds": [ + 1, + 2 + ] + }, + "unreadCount": 2 + } + }, + { + "name": "viewing either history reads every id", + "payload": { + "state": { + "unreadIds": [ + 7, + 2, + 9 + ] + }, + "action": { + "kind": "markAllRead" + } + }, + "expected": { + "state": { + "unreadIds": [] + }, + "unreadCount": 0 + } + }, + { + "name": "viewing empty history is idempotent", + "payload": { + "state": { + "unreadIds": [] + }, + "action": { + "kind": "markAllRead" + } + }, + "expected": { + "state": { + "unreadIds": [] + }, + "unreadCount": 0 + } + }, + { + "name": "arrival while history is visible reads the history", + "payload": { + "state": { + "unreadIds": [ + 7, + 2, + 9 + ] + }, + "action": { + "kind": "arrived", + "id": 4, + "historyVisible": true + } + }, + "expected": { + "state": { + "unreadIds": [] + }, + "unreadCount": 0 + } + }, + { + "name": "eviction removes its unread id even away from the tail", + "payload": { + "state": { + "unreadIds": [ + 7, + 2, + 9 + ] + }, + "action": { + "kind": "arrived", + "id": 4, + "historyVisible": false, + "forgottenId": 2 + } + }, + "expected": { + "state": { + "unreadIds": [ + 4, + 7, + 9 + ] + }, + "unreadCount": 3 + } + }, + { + "name": "eviction of read notice leaves other unread ids", + "payload": { + "state": { + "unreadIds": [ + 7, + 9 + ] + }, + "action": { + "kind": "arrived", + "id": 4, + "historyVisible": false, + "forgottenId": 2 + } + }, + "expected": { + "state": { + "unreadIds": [ + 4, + 7, + 9 + ] + }, + "unreadCount": 3 + } + }, + { + "name": "visible arrival also expires old id", + "payload": { + "state": { + "unreadIds": [ + 7, + 2 + ] + }, + "action": { + "kind": "arrived", + "id": 4, + "historyVisible": true, + "forgottenId": 2 + } + }, + "expected": { + "state": { + "unreadIds": [] + }, + "unreadCount": 0 + } + }, + { + "name": "unread ids do not depend on display order", + "payload": { + "state": { + "unreadIds": [ + 9, + 3, + 7 + ] + }, + "action": { + "kind": "arrived", + "id": 3, + "historyVisible": false + } + }, + "expected": { + "state": { + "unreadIds": [ + 3, + 9, + 7 + ] + }, + "unreadCount": 3 + } + } + ], + "errors": [ + { + "name": "zero arrival id", + "payload": { + "action": { + "kind": "arrived", + "id": 0, + "historyVisible": false + } + }, + "error": "invalid_request" + }, + { + "name": "duplicate unread ids", + "payload": { + "state": { + "unreadIds": [ + 2, + 2 + ] + }, + "action": { + "kind": "markAllRead" + } + }, + "error": "invalid_request" + }, + { + "name": "zero unread id", + "payload": { + "state": { + "unreadIds": [ + 0 + ] + }, + "action": { + "kind": "markAllRead" + } + }, + "error": "invalid_request" + }, + { + "name": "zero forgotten id", + "payload": { + "action": { + "kind": "arrived", + "id": 2, + "historyVisible": false, + "forgottenId": 0 + } + }, + "error": "invalid_request" + }, + { + "name": "unknown action", + "payload": { + "action": { + "kind": "readPrefix" + } + }, + "error": "invalid_request" + }, + { + "name": "unknown field", + "payload": { + "action": { + "kind": "markAllRead" + }, + "extra": true + }, + "error": "invalid_request" + }, + { + "name": "invalid id type", + "payload": { + "action": { + "kind": "arrived", + "id": "notice", + "historyVisible": false + } + }, + "error": "invalid_request" + } + ] +}