From cd5c961b4aa3ecaecd1e61c06ffd4a7f126906b3 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Mon, 23 Nov 2026 19:38:43 +0800 Subject: [PATCH] feat(settings): add built-in file association catalog and plans --- rust/contracts/application-boundary.md | 13 + rust/contracts/rust-core-api.md | 42 ++ rust/crates/core-rules/src/dispatch.rs | 9 +- .../core-rules/src/file_associations.rs | 175 ++++++++ rust/crates/core-rules/src/lib.rs | 1 + .../tests/file_associations_fixture.rs | 44 ++ rust/crates/core/src/protocol/command.rs | 4 + rust/crates/core/src/runtime/dispatcher.rs | 3 + .../application/file-associations-v1.json | 423 ++++++++++++++++++ 9 files changed, 713 insertions(+), 1 deletion(-) create mode 100644 rust/crates/core-rules/src/file_associations.rs create mode 100644 rust/crates/core-rules/tests/file_associations_fixture.rs create mode 100644 rust/fixtures/application/file-associations-v1.json diff --git a/rust/contracts/application-boundary.md b/rust/contracts/application-boundary.md index c64cba64..ca3fefdf 100644 --- a/rust/contracts/application-boundary.md +++ b/rust/contracts/application-boundary.md @@ -621,3 +621,16 @@ never cached authority about an executable. A project may override the global default, while running processes retain their launch environment. Native SDK probing, cancellation and filesystem permissions remain adapter responsibilities; neither these commands nor runtime consumers write into SDKs or installed bundles. + +### System file-association ownership + +Built-in syntax metadata is a host observation; Core owns the bounded text-format +projection, deduplication and conflict-checked explicit selection plan through +`application.fileAssociations.*`. Native adapters read the actual OS defaults and +owned registration, publish only after the user applies the selection, then read +back. They do not maintain a preference that pretends to be the system default. +Windows protected defaults require system user confirmation; native registration +must not write UserChoice. macOS declares alternate editors at build time and +uses Launch Services at runtime without changing bundle resources. OS-opened +regular files enter the same isolated document policy as CLI-opened files, never +implicitly opening or indexing the parent directory. diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 1ea4ef58..bbc52109 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -467,6 +467,8 @@ or removing a command fails until the table changes in the same commit. | Command | Purpose | | --- | --- | +| `application.fileAssociations.catalog` | Project the built-in highlighted text suffixes into native package formats | +| `application.fileAssociations.plan` | Validate an explicit selection against current native association revisions | | `core.ping` | Verify the ABI and protocol version | | `ideHost.control` | Control the native IDE capability broker | | `ai.commitInputBudget` | Budget diff prefixes before crossing the native boundary | @@ -8591,3 +8593,43 @@ permissions and environment-change notification. Inspect is read-only; only an explicit install/remove click publishes. Launcher resources live in user data, never the read-only installation. Removing registration deletes the owned launcher after removing its PATH entry. See [fixtures](../fixtures/application/cli-v1.json). + +## Built-in text file associations + +`application.fileAssociations.catalog` accepts `{languages: [{id, highlighted, +extensions: string[]}]}` observed from the host's built-in syntax catalog. It +returns `{formats: [{extension, language}]}` sorted by extension with first-source +identity winning duplicates. Plugin contributions and filename/prefix-only rules +are not inputs. Languages without a bundled grammar are omitted except +`plaintext`. Only lowercase simple suffixes (a leading dot followed by ASCII +letters or digits, then letters, digits, hyphens, underscores or plus signs) +are registrable; compiled `.rlib` and +compressed `.svgz` are omitted. Compound suffixes are covered by their final simple +suffix when that suffix is declared, rather than claiming OS support for regexes. +At most 128 languages and 512 input suffixes are accepted; suffixes are at most +17 bytes including the leading dot (16 suffix characters), matching the native +package manifest. Language identities are at most 64 ASCII identifier bytes. + +`application.fileAssociations.plan` accepts `{formats, selected: string[], +baseline, current}`. Both observation arrays contain `{extension, defaultId, +registration}`, where registration is an opaque revision of the host-owned native +source. The adapter captures the baseline on read and rereads before an explicit +Apply. Selected extensions must be unique, nonempty, and present in the catalog. +Each selected extension requires one baseline and one current observation. +Changes to default identities or registration revisions produce +`{conflict: true, extensions: []}`. Otherwise the result is +`{conflict: false, extensions: string[]}` in deterministic order. Invalid payloads +fail with `invalid_request`; arrays are bounded to 512 entries, default identities +to 32768 bytes and revision tokens to 128 bytes. Display names are not identity. + +Native hosts own actual Launch Services or per-user Windows registry I/O, +readback, cancellation and partial-failure reporting. Opening settings is +read-only; selecting checkboxes is draft UI state. Applying requests changes only +for selected formats. Windows registers Open With candidates and a context verb +under each owned ProgID, then opens system Default Apps for user confirmation; it +never writes protected UserChoice. The standalone verb appears only for files +associated with that ProgID. macOS registers the signed bundle as an alternate +editor and may explicitly set selected default handlers. macOS associates content +types, so extensions sharing a type may change together. The installed package +stays read-only. No regex or all-files catch-all +registration is permitted. See [fixtures](../fixtures/application/file-associations-v1.json). diff --git a/rust/crates/core-rules/src/dispatch.rs b/rust/crates/core-rules/src/dispatch.rs index a830b766..86c8f055 100644 --- a/rust/crates/core-rules/src/dispatch.rs +++ b/rust/crates/core-rules/src/dispatch.rs @@ -1,11 +1,16 @@ //! Command routing for the rules `lithe-core` forwards to this crate. -use crate::{action_search, cli, editor, keymap, visibility, workbench, RuleError, RuleErrorCode}; +use crate::{ + action_search, cli, editor, file_associations, keymap, visibility, workbench, RuleError, + RuleErrorCode, +}; use serde_json::Value; /// Every command name this crate owns. `lithe-core` routes exactly these names here. pub const COMMANDS: &[&str] = &[ action_search::SEARCH_ACTIONS, + file_associations::CATALOG, + file_associations::PLAN, cli::PLAN_LAUNCH, cli::OPEN_TARGET, cli::EDIT_REGISTRATION, @@ -24,6 +29,8 @@ pub const COMMANDS: &[&str] = &[ /// Runs one rule on an already decoded payload. pub fn execute(command: &str, payload: Value) -> Result { match command { + file_associations::CATALOG => file_associations::catalog_json(payload), + file_associations::PLAN => file_associations::plan_json(payload), cli::PLAN_LAUNCH => cli::plan_launch_json(payload), cli::OPEN_TARGET => cli::open_target_json(payload), cli::EDIT_REGISTRATION => cli::edit_registration_json(payload), diff --git a/rust/crates/core-rules/src/file_associations.rs b/rust/crates/core-rules/src/file_associations.rs new file mode 100644 index 00000000..2c254ca4 --- /dev/null +++ b/rust/crates/core-rules/src/file_associations.rs @@ -0,0 +1,175 @@ +//! File-association catalog and conflict-checked plans; native hosts own registration I/O. + +use crate::{RuleError, RuleErrorCode}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet}; + +/// Projects the host's built-in syntax metadata into registrable text suffixes. +pub const CATALOG: &str = "application.fileAssociations.catalog"; +/// Validates an explicit selection against fresh native observations before publication. +pub const PLAN: &str = "application.fileAssociations.plan"; +const MAX_FORMATS: usize = 512; + +fn invalid(reason: &str) -> RuleError { + RuleError::new(RuleErrorCode::InvalidRequest, reason) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Language { + id: String, + highlighted: bool, + extensions: Vec, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct CatalogRequest { + languages: Vec, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Format { + extension: String, + language: String, +} + +// Viva package declarations accept one suffix of at most 16 ASCII characters. +fn safe_extension(extension: &str) -> bool { + extension.len() > 1 + && extension.len() <= 17 + && extension.starts_with('.') + && extension.as_bytes()[1].is_ascii_alphanumeric() + && extension[1..] + .bytes() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-' || c == b'_' || c == b'+') + // Legacy syntax metadata also recognizes compiled/compressed containers. + // Those are not safe default text-editor associations. + && !matches!(extension, ".rlib" | ".svgz") +} + +fn valid_language(id: &str) -> bool { + !id.is_empty() + && id.len() <= 64 + && id + .bytes() + .all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_') +} + +/// Sorts and deduplicates metadata without loading grammars or inspecting user files. +pub fn catalog_json(payload: Value) -> Result { + let request: CatalogRequest = serde_json::from_value(payload) + .map_err(|_| invalid("Invalid built-in language catalog"))?; + if request.languages.len() > 128 { + return Err(invalid("Too many built-in languages")); + } + let mut formats = BTreeMap::new(); + let mut count = 0; + for language in request.languages { + if !valid_language(&language.id) { + return Err(invalid("Invalid built-in language identity")); + } + count += language.extensions.len(); + if count > MAX_FORMATS { + return Err(invalid("Too many built-in file extensions")); + } + if !language.highlighted && language.id != "plaintext" { + continue; + } + for extension in language.extensions { + if safe_extension(&extension) { + formats + .entry(extension) + .or_insert_with(|| language.id.clone()); + } + } + } + let formats: Vec = formats + .into_iter() + .map(|(extension, language)| Format { + extension, + language, + }) + .collect(); + Ok(json!({"formats": formats})) +} + +/// Display names are excluded: only native identities and owned registration revisions conflict. +#[derive(Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Observation { + extension: String, + default_id: String, + registration: String, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct PlanRequest { + formats: Vec, + selected: Vec, + baseline: Vec, + current: Vec, +} + +/// Refuses stale selections and returns a deterministic additive registration plan. +/// +/// Hosts supply revisions of their owned native registration, re-read before applying the plan. +/// Only selected suffixes enter the plan; native content-type aliases may share defaults. +/// Windows UserChoice is never part of a write plan. +pub fn plan_json(payload: Value) -> Result { + let request: PlanRequest = + serde_json::from_value(payload).map_err(|_| invalid("Invalid file-association plan"))?; + if request.formats.len() > MAX_FORMATS + || request.selected.is_empty() + || request.selected.len() > MAX_FORMATS + || request.baseline.len() > MAX_FORMATS + || request.current.len() > MAX_FORMATS + { + return Err(invalid("File-association plan exceeds its bounds")); + } + let allowed: BTreeSet<&str> = request + .formats + .iter() + .map(|f| f.extension.as_str()) + .collect(); + if allowed.len() != request.formats.len() + || allowed.iter().any(|e| !safe_extension(e)) + || request.formats.iter().any(|f| !valid_language(&f.language)) + { + return Err(invalid("Invalid file-association formats")); + } + let selected: BTreeSet<&str> = request.selected.iter().map(String::as_str).collect(); + if selected.len() != request.selected.len() || !selected.is_subset(&allowed) { + return Err(invalid("Selection is not in the built-in text catalog")); + } + let observations = + |items: Vec| -> Result, RuleError> { + let mut out = BTreeMap::new(); + for item in items { + if !allowed.contains(item.extension.as_str()) + || item.default_id.len() > 32768 + || item.registration.len() > 128 + { + return Err(invalid("Invalid native association observation")); + } + if out.insert(item.extension.clone(), item).is_some() { + return Err(invalid("Duplicate native association observation")); + } + } + Ok(out) + }; + let baseline = observations(request.baseline)?; + let current = observations(request.current)?; + for extension in &selected { + if !baseline.contains_key(*extension) || !current.contains_key(*extension) { + return Err(invalid("Missing native association observation")); + } + if baseline.get(*extension) != current.get(*extension) { + return Ok(json!({"conflict": true, "extensions": []})); + } + } + Ok(json!({"conflict": false, "extensions": selected})) +} diff --git a/rust/crates/core-rules/src/lib.rs b/rust/crates/core-rules/src/lib.rs index 5f04cffc..c7f08c50 100644 --- a/rust/crates/core-rules/src/lib.rs +++ b/rust/crates/core-rules/src/lib.rs @@ -15,6 +15,7 @@ pub mod cli; mod dispatch; pub mod editor; mod error; +pub mod file_associations; pub mod file_names; pub mod keymap; pub mod visibility; diff --git a/rust/crates/core-rules/tests/file_associations_fixture.rs b/rust/crates/core-rules/tests/file_associations_fixture.rs new file mode 100644 index 00000000..69ed40d3 --- /dev/null +++ b/rust/crates/core-rules/tests/file_associations_fixture.rs @@ -0,0 +1,44 @@ +//! Checks the file-association contract without native default-handler mutations. + +use lithe_core_rules::{execute, RuleErrorCode}; +use serde_json::{json, Value}; + +const FIXTURE: &str = include_str!("../../../fixtures/application/file-associations-v1.json"); + +#[test] +fn shared_catalog_and_registration_plans_match() { + let fixture: Value = serde_json::from_str(FIXTURE).unwrap(); + assert_eq!(fixture["version"], 1); + for (section, command) in [ + ("catalog", "application.fileAssociations.catalog"), + ("plans", "application.fileAssociations.plan"), + ] { + for case in fixture[section].as_array().unwrap() { + let actual = execute(command, case["payload"].clone()).unwrap(); + assert_eq!(actual, case["expected"], "{}", case["name"]); + } + } + for case in fixture["errors"].as_array().unwrap() { + let error = + execute(case["command"].as_str().unwrap(), case["payload"].clone()).unwrap_err(); + assert_eq!( + error.code, + RuleErrorCode::InvalidRequest, + "{}", + case["name"] + ); + } +} + +#[test] +fn association_catalog_input_is_bounded() { + let languages: Vec = (0..129) + .map(|_| json!({"id": "text", "highlighted": true, "extensions": []})) + .collect(); + let error = execute( + "application.fileAssociations.catalog", + json!({"languages": languages}), + ) + .unwrap_err(); + assert_eq!(error.code, RuleErrorCode::InvalidRequest); +} diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 34a8611e..01c1b0db 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -53,6 +53,8 @@ pub struct RequestOrigin { pub enum CoreCommand { /// Plans CLI launch and native shell registration (`application.cli.*`). ApplicationCli, + /// Plans built-in text format registration (`application.fileAssociations.*`). + ApplicationFileAssociations, /// Controls the native IDE capability broker (`ideHost.control`). IdeHostControl, /// Reports the Core and protocol versions (`core.ping`). @@ -1126,6 +1128,8 @@ impl CoreCommand { "application.cli.planLaunch" | "application.cli.openTarget" | "application.cli.editRegistration" => Some(Self::ApplicationCli), + "application.fileAssociations.catalog" => Some(Self::ApplicationFileAssociations), + "application.fileAssociations.plan" => Some(Self::ApplicationFileAssociations), "core.ping" => Some(Self::Ping), "ideHost.control" => Some(Self::IdeHostControl), "ai.commitInputBudget" => Some(Self::Ai(AiCommand::CommitInputBudget)), diff --git a/rust/crates/core/src/runtime/dispatcher.rs b/rust/crates/core/src/runtime/dispatcher.rs index 7fe12751..ed3d7792 100644 --- a/rust/crates/core/src/runtime/dispatcher.rs +++ b/rust/crates/core/src/runtime/dispatcher.rs @@ -171,6 +171,9 @@ fn execute_parsed(mut parsed: CoreRequest, document: Option<&str>) -> CoreRespon let preserve_workspace_outcome = matches!(command, CoreCommand::Git(GitCommand::WorkspaceCommitStep)); let response = match command { + CoreCommand::ApplicationFileAssociations => { + rules_response(id, &parsed.command, parsed.payload) + } CoreCommand::ApplicationCli => rules_response(id, &parsed.command, parsed.payload), CoreCommand::IdeHostControl => { let action = parsed.payload["action"].as_str().unwrap_or(""); diff --git a/rust/fixtures/application/file-associations-v1.json b/rust/fixtures/application/file-associations-v1.json new file mode 100644 index 00000000..907ed5a6 --- /dev/null +++ b/rust/fixtures/application/file-associations-v1.json @@ -0,0 +1,423 @@ +{ + "version": 1, + "catalog": [ + { + "name": "only built-in highlighted text and plain text, sorted and deduplicated", + "payload": { + "languages": [ + { + "id": "rust", + "highlighted": true, + "extensions": [ + ".rs", + ".rlib" + ] + }, + { + "id": "xml", + "highlighted": true, + "extensions": [ + ".xml", + ".svgz" + ] + }, + { + "id": "kotlin", + "highlighted": true, + "extensions": [ + ".kts", + ".gradle.kts" + ] + }, + { + "id": "less", + "highlighted": false, + "extensions": [ + ".less" + ] + }, + { + "id": "plaintext", + "highlighted": false, + "extensions": [ + ".txt" + ] + }, + { + "id": "another", + "highlighted": true, + "extensions": [ + ".rs" + ] + } + ] + }, + "expected": { + "formats": [ + { + "extension": ".kts", + "language": "kotlin" + }, + { + "extension": ".rs", + "language": "rust" + }, + { + "extension": ".txt", + "language": "plaintext" + }, + { + "extension": ".xml", + "language": "xml" + } + ] + } + }, + { + "name": "native package suffix syntax includes C++ and has a sixteen-character bound", + "payload": { + "languages": [ + { + "id": "cpp", + "highlighted": true, + "extensions": [ + ".c++", + ".h++", + ".abcdefghijklmnop", + ".abcdefghijklmnopq", + "._hidden", + ".+suffix", + ".Upper", + ".compound.ext" + ] + } + ] + }, + "expected": { + "formats": [ + { + "extension": ".abcdefghijklmnop", + "language": "cpp" + }, + { + "extension": ".c++", + "language": "cpp" + }, + { + "extension": ".h++", + "language": "cpp" + } + ] + } + } + ], + "plans": [ + { + "name": "sorted explicit registration", + "payload": { + "formats": [ + { + "extension": ".rs", + "language": "rust" + }, + { + "extension": ".txt", + "language": "plaintext" + } + ], + "selected": [ + ".txt", + ".rs" + ], + "baseline": [ + { + "extension": ".rs", + "defaultId": "other.editor", + "registration": "rev1" + }, + { + "extension": ".txt", + "defaultId": "lithe.editor", + "registration": "rev2" + } + ], + "current": [ + { + "extension": ".rs", + "defaultId": "other.editor", + "registration": "rev1" + }, + { + "extension": ".txt", + "defaultId": "lithe.editor", + "registration": "rev2" + } + ] + }, + "expected": { + "conflict": false, + "extensions": [ + ".rs", + ".txt" + ] + } + }, + { + "name": "reject changed defaultId", + "payload": { + "formats": [ + { + "extension": ".rs", + "language": "rust" + }, + { + "extension": ".txt", + "language": "plaintext" + } + ], + "selected": [ + ".txt", + ".rs" + ], + "baseline": [ + { + "extension": ".rs", + "defaultId": "other.editor", + "registration": "rev1" + }, + { + "extension": ".txt", + "defaultId": "lithe.editor", + "registration": "rev2" + } + ], + "current": [ + { + "extension": ".rs", + "defaultId": "changed.editor", + "registration": "rev1" + }, + { + "extension": ".txt", + "defaultId": "lithe.editor", + "registration": "rev2" + } + ] + }, + "expected": { + "conflict": true, + "extensions": [] + } + }, + { + "name": "reject changed registration", + "payload": { + "formats": [ + { + "extension": ".rs", + "language": "rust" + }, + { + "extension": ".txt", + "language": "plaintext" + } + ], + "selected": [ + ".txt", + ".rs" + ], + "baseline": [ + { + "extension": ".rs", + "defaultId": "other.editor", + "registration": "rev1" + }, + { + "extension": ".txt", + "defaultId": "lithe.editor", + "registration": "rev2" + } + ], + "current": [ + { + "extension": ".rs", + "defaultId": "other.editor", + "registration": "rev3" + }, + { + "extension": ".txt", + "defaultId": "lithe.editor", + "registration": "rev2" + } + ] + }, + "expected": { + "conflict": true, + "extensions": [] + } + } + ], + "errors": [ + { + "name": "unknown selection", + "command": "application.fileAssociations.plan", + "payload": { + "formats": [ + { + "extension": ".rs", + "language": "rust" + }, + { + "extension": ".txt", + "language": "plaintext" + } + ], + "selected": [ + ".exe" + ], + "baseline": [ + { + "extension": ".rs", + "defaultId": "other.editor", + "registration": "rev1" + }, + { + "extension": ".txt", + "defaultId": "lithe.editor", + "registration": "rev2" + } + ], + "current": [ + { + "extension": ".rs", + "defaultId": "other.editor", + "registration": "rev1" + }, + { + "extension": ".txt", + "defaultId": "lithe.editor", + "registration": "rev2" + } + ] + } + }, + { + "name": "empty selection", + "command": "application.fileAssociations.plan", + "payload": { + "formats": [ + { + "extension": ".rs", + "language": "rust" + }, + { + "extension": ".txt", + "language": "plaintext" + } + ], + "selected": [], + "baseline": [ + { + "extension": ".rs", + "defaultId": "other.editor", + "registration": "rev1" + }, + { + "extension": ".txt", + "defaultId": "lithe.editor", + "registration": "rev2" + } + ], + "current": [ + { + "extension": ".rs", + "defaultId": "other.editor", + "registration": "rev1" + }, + { + "extension": ".txt", + "defaultId": "lithe.editor", + "registration": "rev2" + } + ] + } + }, + { + "name": "duplicate selection", + "command": "application.fileAssociations.plan", + "payload": { + "formats": [ + { + "extension": ".rs", + "language": "rust" + }, + { + "extension": ".txt", + "language": "plaintext" + } + ], + "selected": [ + ".rs", + ".rs" + ], + "baseline": [ + { + "extension": ".rs", + "defaultId": "other.editor", + "registration": "rev1" + }, + { + "extension": ".txt", + "defaultId": "lithe.editor", + "registration": "rev2" + } + ], + "current": [ + { + "extension": ".rs", + "defaultId": "other.editor", + "registration": "rev1" + }, + { + "extension": ".txt", + "defaultId": "lithe.editor", + "registration": "rev2" + } + ] + } + }, + { + "name": "missing observations", + "command": "application.fileAssociations.plan", + "payload": { + "formats": [ + { + "extension": ".rs", + "language": "rust" + }, + { + "extension": ".txt", + "language": "plaintext" + } + ], + "selected": [ + ".txt", + ".rs" + ], + "baseline": [ + { + "extension": ".rs", + "defaultId": "other.editor", + "registration": "rev1" + }, + { + "extension": ".txt", + "defaultId": "lithe.editor", + "registration": "rev2" + } + ], + "current": [] + } + } + ] +}