Skip to content

Commit e2ff09c

Browse files
committed
Merge remote-tracking branch 'origin/main' into lithe-support/issue-2260-toolchain-error-codes
# Conflicts: # shared/plugins/reference/protocol-changelog.md
2 parents 07afd01 + 9c8e89a commit e2ff09c

73 files changed

Lines changed: 3143 additions & 124 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎rust/Cargo.lock‎

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎rust/contracts/application-boundary.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -405,6 +405,9 @@ meaning; `lithe_protocol::ErrorCode` documents when it is reported:
405405
- `git_untrusted_workspace`: the workspace is not trusted, so Git did not start
406406
- `parse_failed`
407407
- `encoding_unmappable`
408+
- `entry_not_found`: a file change names a path, or a target's parent
409+
directory, that does not exist below its root; nothing changed
410+
- `entry_exists`: a file change's target already exists; nothing was replaced
408411
- `cancelled`
409412
- `timed_out`
410413
- `connection_closed`: the remote connection the request names closed or was lost
@@ -621,3 +624,16 @@ never cached authority about an executable. A project may override the global
621624
default, while running processes retain their launch environment. Native SDK
622625
probing, cancellation and filesystem permissions remain adapter responsibilities;
623626
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: 78 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 |
@@ -612,6 +614,10 @@ or removing a command fails until the table changes in the same commit.
612614
| `workspace.rankNames` | Pure ranking of candidate names that the platform enumerates itself (`{ query, candidates: [{ name, path? }], context: { openPaths, recentPaths }, limitPerTier? }`). Use it only for lists Core cannot index: Windows remote/WSL roots, symbol lists, navigator lists. Roots Core indexes go through `workspace.searchEverywhere`, so an inventory is never sent back to Core. Returns `matches: [{ index, degree, tier, nameMatchRanges }]` ordered by degree, open/recent tier, recency, then file-name order (fixture `rust/fixtures/search/rank-names-v1.json`) |
613615
| `workspace.planDuplicate` | Name the copy of one project item next to its source (`foo.txt` → `foo copy.txt`, then `foo copy 2.txt`) from the sibling names the host has seen to exist |
614616
| `workspace.planPaste` | Name pasted project items in one destination directory: a free name is kept, a taken one gets the copy suffix, and earlier items of the same paste count as taken |
617+
| `workspace.createEntry` | Create one file, directory or symbolic link below a workspace root without replacing anything |
618+
| `workspace.renameEntry` | Rename one entry to a new path of the same root without replacing anything; a link is renamed as a link |
619+
| `workspace.copyEntry` | Copy one entry, a directory with everything in it, to a new path of the same root without replacing anything; links stay links |
620+
| `workspace.resolveEntry` | Name one existing entry below a workspace root without following it |
615621
| `workspace.reduceDirectoryAction` | Apply "set role", "exclude" or "cancel exclusion" to a root's persisted directory rules and return the complete state to persist |
616622
| `workspace.relocateDirectoryRules` | Move (or drop, after a delete) the directory rule keys of a renamed, moved or deleted subtree, optionally into another workspace root's rules |
617623
| `workspace.repositories` | Discover deterministic Git repository roots for an opened workspace |
@@ -7440,6 +7446,38 @@ to exist, creates the copy without replacing anything (`FileManager.copyItem`, w
74407446
appeared meanwhile, adds the name to `existing` and plans again. After 512 rounds the host reports
74417447
the stable `destination_exists` error. Cases are in `rust/fixtures/workspace/file-copy-names-v1.json`.
74427448

7449+
`workspace.createEntry`, `workspace.renameEntry`, `workspace.copyEntry` and `workspace.resolveEntry`
7450+
change and name entries below a local workspace root on a plugin's behalf (plan API-11). Each takes
7451+
`root`, the absolute path of the root as the host spells it, and `path`, the entry below it.
7452+
`createEntry` takes `{ root, path, kind, text?, linkTarget? }`: `kind` is `file`, `directory` or
7453+
`symlink`; a file takes optional UTF-8 `text`, and a link takes the `linkTarget` it stores verbatim,
7454+
absolute or relative to the link's directory, which may leave the root or name nothing. On Windows each
7455+
`/` of `linkTarget` is stored as `\`, and the link is a directory link when the target is an existing
7456+
directory at creation, otherwise a file link. `renameEntry` and `copyEntry` take
7457+
`{ root, path, target }`, `target` being the full new path in the same root; `resolveEntry` takes
7458+
`{ root, path }`. Every command returns `{ path, fullPath, kind }`: `fullPath` is spelled from the
7459+
`root` the host sent, as its open documents name the entry, and `kind` is `file`, `directory`,
7460+
`symlink` or `other`.
7461+
7462+
A path is `/`-separated with no empty, `.` or `..` component, and on Windows every component must be
7463+
one Windows stores as written (no reserved name such as `CON`, no trailing dot or space, none of
7464+
`\ : * ? " < > |`); the root itself is not an entry. The directory holding the entry must exist and
7465+
resolve inside the root, so no entry is created or moved through a link that leaves it; the last
7466+
component is never followed, so a link is renamed, copied or resolved as a link, and a copied
7467+
directory keeps its links as links. Nothing is replaced: macOS and Linux rename with one exclusive
7468+
system call (`renamex_np` with `RENAME_EXCL`, `renameat2` with `RENAME_NOREPLACE`) and fall back to a
7469+
check before the rename on volumes that refuse it; Windows renames with `MoveFileExW` without
7470+
`MOVEFILE_REPLACE_EXISTING`. A rename that only changes the case of a name on a file system that
7471+
ignores case is not a collision, and a target naming the source itself is. A directory is never moved
7472+
or copied into itself. A copy that fails part way removes what it created.
7473+
7474+
Errors are `invalid_request` (a malformed path or root, fields that do not match the `kind`, a
7475+
directory moved into itself), `permission_denied` (a parent that resolves outside the root),
7476+
`workspace_not_found` (no root), `entry_not_found` (no entry, or no parent directory), `entry_exists`
7477+
(the target exists), and `unknown` with the system's message in `details` for anything else, such as
7478+
Windows refusing to create a link without Developer Mode or elevation. Saving and moving the open
7479+
documents under an entry, the system trash and refreshing the project tree stay with the host.
7480+
74437481
`history.planEvent` takes `{ event }` and returns `{ snapshots: [{ source, reason }] }`. `source` says
74447482
whose text the host records: `beforeChange` (the text an event replaces), `afterChange` (the text it
74457483
produced) or `editorBuffer` (unsaved editor text that is discarded). A save or auto-save records
@@ -8592,3 +8630,43 @@ permissions and environment-change notification. Inspect is read-only; only an
85928630
explicit install/remove click publishes. Launcher resources live in user data,
85938631
never the read-only installation. Removing registration deletes the owned launcher after removing its PATH entry. See
85948632
[fixtures](../fixtures/application/cli-v1.json).
8633+
8634+
## Built-in text file associations
8635+
8636+
`application.fileAssociations.catalog` accepts `{languages: [{id, highlighted,
8637+
extensions: string[]}]}` observed from the host's built-in syntax catalog. It
8638+
returns `{formats: [{extension, language}]}` sorted by extension with first-source
8639+
identity winning duplicates. Plugin contributions and filename/prefix-only rules
8640+
are not inputs. Languages without a bundled grammar are omitted except
8641+
`plaintext`. Only lowercase simple suffixes (a leading dot followed by ASCII
8642+
letters or digits, then letters, digits, hyphens, underscores or plus signs)
8643+
are registrable; compiled `.rlib` and
8644+
compressed `.svgz` are omitted. Compound suffixes are covered by their final simple
8645+
suffix when that suffix is declared, rather than claiming OS support for regexes.
8646+
At most 128 languages and 512 input suffixes are accepted; suffixes are at most
8647+
17 bytes including the leading dot (16 suffix characters), matching the native
8648+
package manifest. Language identities are at most 64 ASCII identifier bytes.
8649+
8650+
`application.fileAssociations.plan` accepts `{formats, selected: string[],
8651+
baseline, current}`. Both observation arrays contain `{extension, defaultId,
8652+
registration}`, where registration is an opaque revision of the host-owned native
8653+
source. The adapter captures the baseline on read and rereads before an explicit
8654+
Apply. Selected extensions must be unique, nonempty, and present in the catalog.
8655+
Each selected extension requires one baseline and one current observation.
8656+
Changes to default identities or registration revisions produce
8657+
`{conflict: true, extensions: []}`. Otherwise the result is
8658+
`{conflict: false, extensions: string[]}` in deterministic order. Invalid payloads
8659+
fail with `invalid_request`; arrays are bounded to 512 entries, default identities
8660+
to 32768 bytes and revision tokens to 128 bytes. Display names are not identity.
8661+
8662+
Native hosts own actual Launch Services or per-user Windows registry I/O,
8663+
readback, cancellation and partial-failure reporting. Opening settings is
8664+
read-only; selecting checkboxes is draft UI state. Applying requests changes only
8665+
for selected formats. Windows registers Open With candidates and a context verb
8666+
under each owned ProgID, then opens system Default Apps for user confirmation; it
8667+
never writes protected UserChoice. The standalone verb appears only for files
8668+
associated with that ProgID. macOS registers the signed bundle as an alternate
8669+
editor and may explicitly set selected default handlers. macOS associates content
8670+
types, so extensions sharing a type may change together. The installed package
8671+
stays read-only. No regex or all-files catch-all
8672+
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;

0 commit comments

Comments
 (0)