Skip to content

Commit 9c8e89a

Browse files
authored
feat(settings): add built-in file association catalog and plans (#186)
1 parent 6846776 commit 9c8e89a

9 files changed

Lines changed: 713 additions & 1 deletion

File tree

‎rust/contracts/application-boundary.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -624,3 +624,16 @@ never cached authority about an executable. A project may override the global
624624
default, while running processes retain their launch environment. Native SDK
625625
probing, cancellation and filesystem permissions remain adapter responsibilities;
626626
neither these commands nor runtime consumers write into SDKs or installed bundles.
627+
628+
### System file-association ownership
629+
630+
Built-in syntax metadata is a host observation; Core owns the bounded text-format
631+
projection, deduplication and conflict-checked explicit selection plan through
632+
`application.fileAssociations.*`. Native adapters read the actual OS defaults and
633+
owned registration, publish only after the user applies the selection, then read
634+
back. They do not maintain a preference that pretends to be the system default.
635+
Windows protected defaults require system user confirmation; native registration
636+
must not write UserChoice. macOS declares alternate editors at build time and
637+
uses Launch Services at runtime without changing bundle resources. OS-opened
638+
regular files enter the same isolated document policy as CLI-opened files, never
639+
implicitly opening or indexing the parent directory.

‎rust/contracts/rust-core-api.md‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -467,6 +467,8 @@ or removing a command fails until the table changes in the same commit.
467467

468468
| Command | Purpose |
469469
| --- | --- |
470+
| `application.fileAssociations.catalog` | Project the built-in highlighted text suffixes into native package formats |
471+
| `application.fileAssociations.plan` | Validate an explicit selection against current native association revisions |
470472
| `core.ping` | Verify the ABI and protocol version |
471473
| `ideHost.control` | Control the native IDE capability broker |
472474
| `ai.commitInputBudget` | Budget diff prefixes before crossing the native boundary |
@@ -8627,3 +8629,43 @@ permissions and environment-change notification. Inspect is read-only; only an
86278629
explicit install/remove click publishes. Launcher resources live in user data,
86288630
never the read-only installation. Removing registration deletes the owned launcher after removing its PATH entry. See
86298631
[fixtures](../fixtures/application/cli-v1.json).
8632+
8633+
## Built-in text file associations
8634+
8635+
`application.fileAssociations.catalog` accepts `{languages: [{id, highlighted,
8636+
extensions: string[]}]}` observed from the host's built-in syntax catalog. It
8637+
returns `{formats: [{extension, language}]}` sorted by extension with first-source
8638+
identity winning duplicates. Plugin contributions and filename/prefix-only rules
8639+
are not inputs. Languages without a bundled grammar are omitted except
8640+
`plaintext`. Only lowercase simple suffixes (a leading dot followed by ASCII
8641+
letters or digits, then letters, digits, hyphens, underscores or plus signs)
8642+
are registrable; compiled `.rlib` and
8643+
compressed `.svgz` are omitted. Compound suffixes are covered by their final simple
8644+
suffix when that suffix is declared, rather than claiming OS support for regexes.
8645+
At most 128 languages and 512 input suffixes are accepted; suffixes are at most
8646+
17 bytes including the leading dot (16 suffix characters), matching the native
8647+
package manifest. Language identities are at most 64 ASCII identifier bytes.
8648+
8649+
`application.fileAssociations.plan` accepts `{formats, selected: string[],
8650+
baseline, current}`. Both observation arrays contain `{extension, defaultId,
8651+
registration}`, where registration is an opaque revision of the host-owned native
8652+
source. The adapter captures the baseline on read and rereads before an explicit
8653+
Apply. Selected extensions must be unique, nonempty, and present in the catalog.
8654+
Each selected extension requires one baseline and one current observation.
8655+
Changes to default identities or registration revisions produce
8656+
`{conflict: true, extensions: []}`. Otherwise the result is
8657+
`{conflict: false, extensions: string[]}` in deterministic order. Invalid payloads
8658+
fail with `invalid_request`; arrays are bounded to 512 entries, default identities
8659+
to 32768 bytes and revision tokens to 128 bytes. Display names are not identity.
8660+
8661+
Native hosts own actual Launch Services or per-user Windows registry I/O,
8662+
readback, cancellation and partial-failure reporting. Opening settings is
8663+
read-only; selecting checkboxes is draft UI state. Applying requests changes only
8664+
for selected formats. Windows registers Open With candidates and a context verb
8665+
under each owned ProgID, then opens system Default Apps for user confirmation; it
8666+
never writes protected UserChoice. The standalone verb appears only for files
8667+
associated with that ProgID. macOS registers the signed bundle as an alternate
8668+
editor and may explicitly set selected default handlers. macOS associates content
8669+
types, so extensions sharing a type may change together. The installed package
8670+
stays read-only. No regex or all-files catch-all
8671+
registration is permitted. See [fixtures](../fixtures/application/file-associations-v1.json).

‎rust/crates/core-rules/src/dispatch.rs‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
11
//! Command routing for the rules `lithe-core` forwards to this crate.
22
3-
use crate::{action_search, cli, editor, keymap, visibility, workbench, RuleError, RuleErrorCode};
3+
use crate::{
4+
action_search, cli, editor, file_associations, keymap, visibility, workbench, RuleError,
5+
RuleErrorCode,
6+
};
47
use serde_json::Value;
58

69
/// Every command name this crate owns. `lithe-core` routes exactly these names here.
710
pub const COMMANDS: &[&str] = &[
811
action_search::SEARCH_ACTIONS,
12+
file_associations::CATALOG,
13+
file_associations::PLAN,
914
cli::PLAN_LAUNCH,
1015
cli::OPEN_TARGET,
1116
cli::EDIT_REGISTRATION,
@@ -24,6 +29,8 @@ pub const COMMANDS: &[&str] = &[
2429
/// Runs one rule on an already decoded payload.
2530
pub fn execute(command: &str, payload: Value) -> Result<Value, RuleError> {
2631
match command {
32+
file_associations::CATALOG => file_associations::catalog_json(payload),
33+
file_associations::PLAN => file_associations::plan_json(payload),
2734
cli::PLAN_LAUNCH => cli::plan_launch_json(payload),
2835
cli::OPEN_TARGET => cli::open_target_json(payload),
2936
cli::EDIT_REGISTRATION => cli::edit_registration_json(payload),
Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
//! File-association catalog and conflict-checked plans; native hosts own registration I/O.
2+
3+
use crate::{RuleError, RuleErrorCode};
4+
use serde::{Deserialize, Serialize};
5+
use serde_json::{json, Value};
6+
use std::collections::{BTreeMap, BTreeSet};
7+
8+
/// Projects the host's built-in syntax metadata into registrable text suffixes.
9+
pub const CATALOG: &str = "application.fileAssociations.catalog";
10+
/// Validates an explicit selection against fresh native observations before publication.
11+
pub const PLAN: &str = "application.fileAssociations.plan";
12+
const MAX_FORMATS: usize = 512;
13+
14+
fn invalid(reason: &str) -> RuleError {
15+
RuleError::new(RuleErrorCode::InvalidRequest, reason)
16+
}
17+
18+
#[derive(Deserialize)]
19+
#[serde(rename_all = "camelCase", deny_unknown_fields)]
20+
struct Language {
21+
id: String,
22+
highlighted: bool,
23+
extensions: Vec<String>,
24+
}
25+
26+
#[derive(Deserialize)]
27+
#[serde(deny_unknown_fields)]
28+
struct CatalogRequest {
29+
languages: Vec<Language>,
30+
}
31+
32+
#[derive(Clone, Debug, Deserialize, Serialize)]
33+
#[serde(deny_unknown_fields)]
34+
struct Format {
35+
extension: String,
36+
language: String,
37+
}
38+
39+
// Viva package declarations accept one suffix of at most 16 ASCII characters.
40+
fn safe_extension(extension: &str) -> bool {
41+
extension.len() > 1
42+
&& extension.len() <= 17
43+
&& extension.starts_with('.')
44+
&& extension.as_bytes()[1].is_ascii_alphanumeric()
45+
&& extension[1..]
46+
.bytes()
47+
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-' || c == b'_' || c == b'+')
48+
// Legacy syntax metadata also recognizes compiled/compressed containers.
49+
// Those are not safe default text-editor associations.
50+
&& !matches!(extension, ".rlib" | ".svgz")
51+
}
52+
53+
fn valid_language(id: &str) -> bool {
54+
!id.is_empty()
55+
&& id.len() <= 64
56+
&& id
57+
.bytes()
58+
.all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')
59+
}
60+
61+
/// Sorts and deduplicates metadata without loading grammars or inspecting user files.
62+
pub fn catalog_json(payload: Value) -> Result<Value, RuleError> {
63+
let request: CatalogRequest = serde_json::from_value(payload)
64+
.map_err(|_| invalid("Invalid built-in language catalog"))?;
65+
if request.languages.len() > 128 {
66+
return Err(invalid("Too many built-in languages"));
67+
}
68+
let mut formats = BTreeMap::new();
69+
let mut count = 0;
70+
for language in request.languages {
71+
if !valid_language(&language.id) {
72+
return Err(invalid("Invalid built-in language identity"));
73+
}
74+
count += language.extensions.len();
75+
if count > MAX_FORMATS {
76+
return Err(invalid("Too many built-in file extensions"));
77+
}
78+
if !language.highlighted && language.id != "plaintext" {
79+
continue;
80+
}
81+
for extension in language.extensions {
82+
if safe_extension(&extension) {
83+
formats
84+
.entry(extension)
85+
.or_insert_with(|| language.id.clone());
86+
}
87+
}
88+
}
89+
let formats: Vec<Format> = formats
90+
.into_iter()
91+
.map(|(extension, language)| Format {
92+
extension,
93+
language,
94+
})
95+
.collect();
96+
Ok(json!({"formats": formats}))
97+
}
98+
99+
/// Display names are excluded: only native identities and owned registration revisions conflict.
100+
#[derive(Debug, Deserialize, PartialEq, Eq)]
101+
#[serde(rename_all = "camelCase", deny_unknown_fields)]
102+
struct Observation {
103+
extension: String,
104+
default_id: String,
105+
registration: String,
106+
}
107+
108+
#[derive(Deserialize)]
109+
#[serde(rename_all = "camelCase", deny_unknown_fields)]
110+
struct PlanRequest {
111+
formats: Vec<Format>,
112+
selected: Vec<String>,
113+
baseline: Vec<Observation>,
114+
current: Vec<Observation>,
115+
}
116+
117+
/// Refuses stale selections and returns a deterministic additive registration plan.
118+
///
119+
/// Hosts supply revisions of their owned native registration, re-read before applying the plan.
120+
/// Only selected suffixes enter the plan; native content-type aliases may share defaults.
121+
/// Windows UserChoice is never part of a write plan.
122+
pub fn plan_json(payload: Value) -> Result<Value, RuleError> {
123+
let request: PlanRequest =
124+
serde_json::from_value(payload).map_err(|_| invalid("Invalid file-association plan"))?;
125+
if request.formats.len() > MAX_FORMATS
126+
|| request.selected.is_empty()
127+
|| request.selected.len() > MAX_FORMATS
128+
|| request.baseline.len() > MAX_FORMATS
129+
|| request.current.len() > MAX_FORMATS
130+
{
131+
return Err(invalid("File-association plan exceeds its bounds"));
132+
}
133+
let allowed: BTreeSet<&str> = request
134+
.formats
135+
.iter()
136+
.map(|f| f.extension.as_str())
137+
.collect();
138+
if allowed.len() != request.formats.len()
139+
|| allowed.iter().any(|e| !safe_extension(e))
140+
|| request.formats.iter().any(|f| !valid_language(&f.language))
141+
{
142+
return Err(invalid("Invalid file-association formats"));
143+
}
144+
let selected: BTreeSet<&str> = request.selected.iter().map(String::as_str).collect();
145+
if selected.len() != request.selected.len() || !selected.is_subset(&allowed) {
146+
return Err(invalid("Selection is not in the built-in text catalog"));
147+
}
148+
let observations =
149+
|items: Vec<Observation>| -> Result<BTreeMap<String, Observation>, RuleError> {
150+
let mut out = BTreeMap::new();
151+
for item in items {
152+
if !allowed.contains(item.extension.as_str())
153+
|| item.default_id.len() > 32768
154+
|| item.registration.len() > 128
155+
{
156+
return Err(invalid("Invalid native association observation"));
157+
}
158+
if out.insert(item.extension.clone(), item).is_some() {
159+
return Err(invalid("Duplicate native association observation"));
160+
}
161+
}
162+
Ok(out)
163+
};
164+
let baseline = observations(request.baseline)?;
165+
let current = observations(request.current)?;
166+
for extension in &selected {
167+
if !baseline.contains_key(*extension) || !current.contains_key(*extension) {
168+
return Err(invalid("Missing native association observation"));
169+
}
170+
if baseline.get(*extension) != current.get(*extension) {
171+
return Ok(json!({"conflict": true, "extensions": []}));
172+
}
173+
}
174+
Ok(json!({"conflict": false, "extensions": selected}))
175+
}

‎rust/crates/core-rules/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ pub mod cli;
1515
mod dispatch;
1616
pub mod editor;
1717
mod error;
18+
pub mod file_associations;
1819
pub mod file_names;
1920
pub mod keymap;
2021
pub mod visibility;
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
//! Checks the file-association contract without native default-handler mutations.
2+
3+
use lithe_core_rules::{execute, RuleErrorCode};
4+
use serde_json::{json, Value};
5+
6+
const FIXTURE: &str = include_str!("../../../fixtures/application/file-associations-v1.json");
7+
8+
#[test]
9+
fn shared_catalog_and_registration_plans_match() {
10+
let fixture: Value = serde_json::from_str(FIXTURE).unwrap();
11+
assert_eq!(fixture["version"], 1);
12+
for (section, command) in [
13+
("catalog", "application.fileAssociations.catalog"),
14+
("plans", "application.fileAssociations.plan"),
15+
] {
16+
for case in fixture[section].as_array().unwrap() {
17+
let actual = execute(command, case["payload"].clone()).unwrap();
18+
assert_eq!(actual, case["expected"], "{}", case["name"]);
19+
}
20+
}
21+
for case in fixture["errors"].as_array().unwrap() {
22+
let error =
23+
execute(case["command"].as_str().unwrap(), case["payload"].clone()).unwrap_err();
24+
assert_eq!(
25+
error.code,
26+
RuleErrorCode::InvalidRequest,
27+
"{}",
28+
case["name"]
29+
);
30+
}
31+
}
32+
33+
#[test]
34+
fn association_catalog_input_is_bounded() {
35+
let languages: Vec<Value> = (0..129)
36+
.map(|_| json!({"id": "text", "highlighted": true, "extensions": []}))
37+
.collect();
38+
let error = execute(
39+
"application.fileAssociations.catalog",
40+
json!({"languages": languages}),
41+
)
42+
.unwrap_err();
43+
assert_eq!(error.code, RuleErrorCode::InvalidRequest);
44+
}

‎rust/crates/core/src/protocol/command.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ pub struct RequestOrigin {
5353
pub enum CoreCommand {
5454
/// Plans CLI launch and native shell registration (`application.cli.*`).
5555
ApplicationCli,
56+
/// Plans built-in text format registration (`application.fileAssociations.*`).
57+
ApplicationFileAssociations,
5658
/// Controls the native IDE capability broker (`ideHost.control`).
5759
IdeHostControl,
5860
/// Reports the Core and protocol versions (`core.ping`).
@@ -1135,6 +1137,8 @@ impl CoreCommand {
11351137
"application.cli.planLaunch"
11361138
| "application.cli.openTarget"
11371139
| "application.cli.editRegistration" => Some(Self::ApplicationCli),
1140+
"application.fileAssociations.catalog" => Some(Self::ApplicationFileAssociations),
1141+
"application.fileAssociations.plan" => Some(Self::ApplicationFileAssociations),
11381142
"core.ping" => Some(Self::Ping),
11391143
"ideHost.control" => Some(Self::IdeHostControl),
11401144
"ai.commitInputBudget" => Some(Self::Ai(AiCommand::CommitInputBudget)),

‎rust/crates/core/src/runtime/dispatcher.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,9 @@ fn execute_parsed(mut parsed: CoreRequest, document: Option<&str>) -> CoreRespon
171171
let preserve_workspace_outcome =
172172
matches!(command, CoreCommand::Git(GitCommand::WorkspaceCommitStep));
173173
let response = match command {
174+
CoreCommand::ApplicationFileAssociations => {
175+
rules_response(id, &parsed.command, parsed.payload)
176+
}
174177
CoreCommand::ApplicationCli => rules_response(id, &parsed.command, parsed.payload),
175178
CoreCommand::IdeHostControl => {
176179
let action = parsed.payload["action"].as_str().unwrap_or("");

0 commit comments

Comments
 (0)