Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions rust/contracts/application-boundary.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
41 changes: 41 additions & 0 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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.
2 changes: 2 additions & 0 deletions rust/crates/core-rules/src/dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -30,6 +31,7 @@ pub fn execute(command: &str, payload: Value) -> Result<Value, RuleError> {
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",
Expand Down
6 changes: 6 additions & 0 deletions rust/crates/core-rules/src/workbench/mod.rs
Original file line number Diff line number Diff line change
@@ -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,
};
124 changes: 124 additions & 0 deletions rust/crates/core-rules/src/workbench/notification_read.rs
Original file line number Diff line number Diff line change
@@ -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<u64>,
}

/// 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<u64>,
/// 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<ReadReduction, RuleError> {
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<Value, RuleError> {
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()))
}
45 changes: 45 additions & 0 deletions rust/crates/core-rules/tests/notification_read_fixture.rs
Original file line number Diff line number Diff line change
@@ -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<u64> = (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);
}
6 changes: 6 additions & 0 deletions rust/crates/core/src/protocol/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)),
Expand Down
5 changes: 5 additions & 0 deletions rust/crates/core/src/runtime/dispatcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<lithe_terminal::ParseLinkTargetsRequest>(parsed.payload)
Expand Down
1 change: 1 addition & 0 deletions rust/crates/core/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
38 changes: 38 additions & 0 deletions rust/crates/core/src/tests/notification_read.rs
Original file line number Diff line number Diff line change
@@ -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"]);
}
}
Loading
Loading