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
13 changes: 13 additions & 0 deletions rust/contracts/application-boundary.md
Original file line number Diff line number Diff line change
Expand Up @@ -624,3 +624,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.
42 changes: 42 additions & 0 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -8627,3 +8629,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).
9 changes: 8 additions & 1 deletion rust/crates/core-rules/src/dispatch.rs
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -24,6 +29,8 @@ pub const COMMANDS: &[&str] = &[
/// Runs one rule on an already decoded payload.
pub fn execute(command: &str, payload: Value) -> Result<Value, RuleError> {
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),
Expand Down
175 changes: 175 additions & 0 deletions rust/crates/core-rules/src/file_associations.rs
Original file line number Diff line number Diff line change
@@ -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<String>,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CatalogRequest {
languages: Vec<Language>,
}

#[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<Value, RuleError> {
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<Format> = 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<Format>,
selected: Vec<String>,
baseline: Vec<Observation>,
current: Vec<Observation>,
}

/// 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<Value, RuleError> {
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<Observation>| -> Result<BTreeMap<String, Observation>, 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}))
}
1 change: 1 addition & 0 deletions rust/crates/core-rules/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
44 changes: 44 additions & 0 deletions rust/crates/core-rules/tests/file_associations_fixture.rs
Original file line number Diff line number Diff line change
@@ -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<Value> = (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);
}
4 changes: 4 additions & 0 deletions rust/crates/core/src/protocol/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`).
Expand Down Expand Up @@ -1135,6 +1137,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)),
Expand Down
3 changes: 3 additions & 0 deletions rust/crates/core/src/runtime/dispatcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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("");
Expand Down
Loading
Loading