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
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# Agent 笔记:按内置文本高亮目录注册系统文件关联

状态:已实现

## 先说结论

“通用”设置中的文件关联表格直接显示系统当前的默认应用,用户勾选后明确应用才改变关联。可选格式来自编辑器实际打包的文本高亮扩展名及纯文本,不接受正则或“所有文件”。macOS 使用 Finder 的“打开方式”和默认应用;Windows 注册“打开方式”候选并交给系统设置确认默认应用。

## 问题

操作系统按扩展名或内容类型注册文件处理程序,不能表达编辑器中的任意正则。单独维护一张扩展名表会与高亮支持和打包声明发生漂移;只保存一个“使用 Lithe 打开”的应用偏好,也无法说明系统真正使用哪个程序。系统打开文件时还必须保留用户已打开的项目,避免为了临时编辑一个文件而索引整个父目录。

## 决策

- 编辑器只导出内置元数据,不加载语法,也不混入插件贡献。Core(共享 Rust 规则层)筛出实际有语法的语言和纯文本,排除编译/压缩容器、文件名匹配和复合后缀,排序去重。简单后缀与 Viva 原生打包清单的字符和长度限制一致,保留 `.c++`、`.h++`。设置和打包生成器使用同一个结果;增加高亮后须重新生成 `desktop/viva.toml`,打包前检查是否一致。
- 设置只在内存保存勾选草稿。读取来自系统真实默认处理程序,应用前重读默认标识与自有注册信息,再由 Core 拒绝过期基线。成功或部分失败后均重新读取,不把草稿当成生效值。取消勾选只清除本次选择,不还原历史默认应用;复杂后果通过标题的 ⓘ 说明。
- macOS 在构建期声明备用文本编辑器,运行期只向 Launch Services(系统维护的文件类型与应用关联服务)注册当前 bundle,并显式设置所选类型。macOS 按内容类型关联,共用一种内容类型的多个扩展名可能同时变化,不能承诺每个后缀独立生效。开发二进制只读默认应用,不注册临时测试程序。
- Windows 只写当前用户的 Classes、Capabilities 和 RegisteredApplications。每个格式使用与 Viva 安装器相同的 ProgID(系统中的文件处理程序标识),显式注册时同时写入自己的“用 Lithe 打开”动作;只有已关联到该 ProgID 的文件有该独立动作,其他文件可从“打开方式”进入。Windows 11 的传统动作可能在“显示更多选项”下。受保护的 UserChoice(用户默认应用选择)只读,最后由 Windows 设置确认;刷新后回显系统结果。
- Windows 的右键动作放在 Lithe 自己的 ProgID 下,随 Viva 安装器卸载该格式一起移除,不在全局 `SystemFileAssociations` 或所有文件类写额外项。运行期仅允许名为 `lithe.exe` 的产品程序注册,避免测试二进制写入无法由卸载器移除的 Applications 项。
- Finder 事件只接受真实普通文件,复用独立编辑会话;已有项目保留,通过原有项目标签返回。Windows 从启动参数进入既有单文件模式。文档服务的隔离沿用[可选 CLI 注册与单文件编辑](2026-11-20-cli-and-standalone-editor.md),不创建插件、目录索引或项目服务。
- 表格复用 Viva 的虚拟列表和共享滚动条,只创建可见行;勾选以扩展名保存,不依赖离屏控件是否存在。系统查询和写入在可取消、有期限的后台任务中完成。

正确做法:新增内置高亮后运行生成器,把格式同时带到设置、macOS 声明和 Windows 安装器;打开设置只查系统,勾选后点击应用才发布。不要在界面手写另一份格式名单,也不要通过改写安装包里的清单来补运行期关联。

## 考虑过的备选方案

- 正则输入和所有文本文件总开关:系统不理解正则,也无法仅凭文件内容在 Explorer/Finder 注册默认应用。最终采用真实内置高亮扩展名的全选操作,避免抢占二进制或压缩文件。
- macOS 添加固定 Finder 右键动作:需要额外的系统扩展和生命周期;系统已有“打开方式”可表达同一入口,本次使用它。
- Windows 直接写 UserChoice:绕过系统保护且不能可靠生效,保留系统确认流程。
- 全局右键项配扩展名过滤:Viva 当前卸载器不会清理额外全局项。把动作放进自有 ProgID 可以复用现有安装和卸载边界,代价是它只出现在已关联文件上。
- 所有平台各写一份筛选和冲突判断:行为会漂移,共享规则在 Core,平台只负责原生查询和写入。

## 后果

格式目录、高亮支持和安装声明可以相互核对,打开设置不改变系统,也没有虚假的“已注册”偏好。代价是仅文件名匹配的 Makefile 等不在系统关联列表中;设置默认应用需要安装后的程序,macOS 的类型别名和 Windows 的用户确认由系统决定。平台外部进程在重读与写入之间仍可竞争,原生接口不提供跨进程事务,批量部分失败会显示错误并回读。

清单是构建输入,由仓库维护,不是缓存。运行期注册数据由系统管理,macOS bundle 和 Windows 安装目录始终只读,不产生新下载或资源路径,不改变代码签名和增量更新基线。截图和计时报告只属于当前检出的 `.artifacts/`,不跨工作树复制。

## 验证

- `scripts/desktop/desktop-go.sh test ./internal/core ./internal/fileassociations ./internal/workbench -run '^Test(FileAssociations|SystemDocuments)' -count=1 -timeout=60s`:链接修改后的 Core,核对共享 fixture、真实高亮解析、Viva 原生清单,以及真实文件的独立打开与项目保留。
- `scripts/desktop/desktop-go.sh test -tags 'vivahead lithevisual' ./internal/settingswindow -run '^TestVisualFileAssociations$' -count=1 -timeout=60s`:使用 `LITHE_VISUAL_OUTPUT_DIR` 输出中英、明暗截图;系统默认应用只读,验证全选、清空、刷新、鼠标滚轮到末尾、虚拟化和选择保留。
- `scripts/desktop/generate-file-associations.sh --check`、`node --test --test-timeout=60000 scripts/desktop/package-desktop.test.mjs`:核对打包目录和生成器在构建主机执行、最终辅助程序保持目标架构。
- `scripts/desktop/desktop-go.sh build -o ../.artifacts/desktop/bin/lithe-file-associations ./cmd/lithe`:macOS arm64 最终消费者构建通过。宿主固定到配套 Core PR 的确切提交,包含同功能分支与当时最新的 Core main;宿主合并前先合入 Core,合并方式改变提交哈希时同步更新固定修订。
- `scripts/desktop/perf/editor-bench.sh run --bench '^BenchmarkEditorSyntaxViewportWarm' --count 6`:同机改动前后各测六次,六个场景均在预算内,保持 0 B/op、0 allocs/op;对比没有回归。元数据导出不改变分词或视口读取路径。
- Core 的 `cargo clippy --manifest-path rust/Cargo.toml -p lithe-core --all-targets --target x86_64-pc-windows-msvc -- -D warnings`(设置 `LIBSQLITE3_SYS_USE_PKG_CONFIG=1`)通过。它不验证 Windows 的 Go 原生适配器,也不替代来宾运行。
- `scripts/desktop/verify/verify-runtime-bundle-immutability.sh`:检查发行目录只读边界。
- 发布包的 macOS 注册和 Finder 打开、Windows 注册表与默认应用确认、卸载清理需要在目标系统单独验收,功能矩阵保持 pending。无头测试不修改开发机默认应用。

## 适用范围

- `desktop/internal/fileassociations/`
- `desktop/internal/core/file_associations.go`
- `desktop/internal/editor/syntax/catalog.go`
- `desktop/internal/settingswindow/file_associations_view.go`
- `desktop/internal/workbench/system_document.go`
- `desktop/cmd/file-associations-manifest/`
- `desktop/viva.toml`
- `shared/platform-feature-matrix/features/system-file-associations.json`
2 changes: 2 additions & 0 deletions .github/workflows/desktop-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ jobs:
bash -n scripts/desktop/build-remote-server.sh
bash -n scripts/desktop/desktop-go.sh
bash -n scripts/desktop/package-desktop.sh
bash -n scripts/desktop/generate-file-associations.sh
bash -n scripts/desktop/build-viva-tool.sh
bash -n scripts/desktop/perf/editor-bench.sh
bash -n scripts/ci/desktop-release/package-release.sh
Expand All @@ -90,6 +91,7 @@ jobs:
scripts/desktop/build-remote-server.sh \
scripts/desktop/desktop-go.sh \
scripts/desktop/package-desktop.sh \
scripts/desktop/generate-file-associations.sh \
scripts/desktop/build-viva-tool.sh \
scripts/desktop/perf/editor-bench.sh \
scripts/ci/desktop-release/package-release.sh \
Expand Down
62 changes: 62 additions & 0 deletions desktop/cmd/file-associations-manifest/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Command file-associations-manifest projects the editor's actual bundled syntax
// catalog through Core into Viva's native package declarations.
package main

import (
"bytes"
"context"
"flag"
"fmt"
"os"
"strings"
"time"

"github.com/1lck/Lithe-IDEA/desktop/internal/core"
"github.com/1lck/Lithe-IDEA/desktop/internal/fileassociations"
)

const begin = "# BEGIN generated file associations\n"
const end = "# END generated file associations\n"

func main() {
check := flag.Bool("check", false, "fail if viva.toml differs from the built-in text catalog")
flag.Parse()
if err := generate(*check); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}

func generate(check bool) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
formats, err := fileassociations.Catalog(ctx, core.NewClient())
if err != nil {
return err
}
source, err := os.ReadFile("viva.toml")
if err != nil {
return err
}
start := bytes.Index(source, []byte(begin))
finish := bytes.Index(source, []byte(end))
if start < 0 || finish < start {
return fmt.Errorf("viva.toml: missing generated file-association markers")
}
var block bytes.Buffer
block.WriteString(begin)
block.WriteString("# Generated by scripts/desktop/generate-file-associations.sh; do not edit.\n")
for _, format := range formats {
fmt.Fprintf(&block, "[[app.file_types]]\nname = %q\nextensions = [%q]\n\n", "Lithe Desktop "+format.Extension, strings.TrimPrefix(format.Extension, "."))
}
block.WriteString(end)
result := append(bytes.Clone(source[:start]), block.Bytes()...)
result = append(result, source[finish+len(end):]...)
if bytes.Equal(result, source) {
return nil
}
if check {
return fmt.Errorf("viva.toml: file associations are stale; run scripts/desktop/generate-file-associations.sh")
}
return os.WriteFile("viva.toml", result, 0644)
}
1 change: 1 addition & 0 deletions desktop/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ require (
github.com/danieljoos/wincred v1.2.3 // indirect
github.com/ebitengine/purego v0.11.1 // indirect
github.com/godbus/dbus/v5 v5.2.2 // indirect
github.com/pelletier/go-toml/v2 v2.4.3 // indirect
)

replace github.com/vivaui/viva => github.com/Lithe-IDEA/viva v0.6.7-0.20261123062230-3c6c46081fe6
49 changes: 49 additions & 0 deletions desktop/internal/core/file_associations.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package core

import "context"

// FileAssociationLanguage is observed metadata from the bundled syntax registry.
type FileAssociationLanguage struct {
ID string `json:"id"`
Highlighted bool `json:"highlighted"`
Extensions []string `json:"extensions"`
}

// FileAssociationFormat is a registrable text suffix selected by Core.
type FileAssociationFormat struct {
Extension string `json:"extension"`
Language string `json:"language"`
}

func (c *Client) FileAssociationCatalog(ctx context.Context, languages []FileAssociationLanguage) ([]FileAssociationFormat, error) {
var result struct {
Formats []FileAssociationFormat `json:"formats"`
}
err := c.Execute(ctx, "application.fileAssociations.catalog", struct {
Languages []FileAssociationLanguage `json:"languages"`
}{nonNil(languages)}, &result)
return result.Formats, err
}

// FileAssociationObservation contains native identities, excluding display labels.
type FileAssociationObservation struct {
Extension string `json:"extension"`
DefaultID string `json:"defaultId"`
Registration string `json:"registration"`
}

type FileAssociationPlan struct {
Conflict bool `json:"conflict"`
Extensions []string `json:"extensions"`
}

func (c *Client) PlanFileAssociations(ctx context.Context, formats []FileAssociationFormat, selected []string, baseline, current []FileAssociationObservation) (FileAssociationPlan, error) {
var result FileAssociationPlan
err := c.Execute(ctx, "application.fileAssociations.plan", struct {
Formats []FileAssociationFormat `json:"formats"`
Selected []string `json:"selected"`
Baseline []FileAssociationObservation `json:"baseline"`
Current []FileAssociationObservation `json:"current"`
}{nonNil(formats), nonNil(selected), nonNil(baseline), nonNil(current)}, &result)
return result, err
}
57 changes: 57 additions & 0 deletions desktop/internal/core/file_associations_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package core

import (
"context"
"encoding/json"
"os"
"reflect"
"testing"
"time"

"github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture"
)

func TestFileAssociationsSharedFixture(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
data, err := os.ReadFile(contractfixture.CoreFixture("application/file-associations-v1.json"))
if err != nil {
t.Fatal(err)
}
type fixtureCase struct {
Name, Command string
Payload, Expected json.RawMessage
}
var fixture struct{ Catalog, Plans, Errors []fixtureCase }
if err := json.Unmarshal(data, &fixture); err != nil {
t.Fatal(err)
}
client := NewClient()
for section, cases := range map[string][]fixtureCase{
"application.fileAssociations.catalog": fixture.Catalog,
"application.fileAssociations.plan": fixture.Plans,
} {
for _, test := range cases {
t.Run(test.Name, func(t *testing.T) {
var actual, expected any
if err := client.Execute(ctx, section, test.Payload, &actual); err != nil {
t.Fatal(err)
}
if err := json.Unmarshal(test.Expected, &expected); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(actual, expected) {
t.Fatalf("got %+v, want %+v", actual, expected)
}
})
}
}
for _, test := range fixture.Errors {
t.Run(test.Name, func(t *testing.T) {
var result any
if err := client.Execute(ctx, test.Command, test.Payload, &result); err == nil {
t.Fatal("invalid association plan accepted")
}
})
}
}
24 changes: 24 additions & 0 deletions desktop/internal/editor/syntax/catalog.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package syntax

import "slices"

// BundledFileType is metadata observed from the editor's built-in catalog. It
// does not include plugin contributions and does not load or tokenize grammars.
type BundledFileType struct {
ID string
Highlighted bool
Extensions []string
}

// BundledFileTypes returns independent metadata for settings and packaging. Core
// decides which suffixes can safely be registered with the operating system.
func BundledFileTypes() []BundledFileType {
result := make([]BundledFileType, len(bundledLanguages))
for i, language := range bundledLanguages {
result[i] = BundledFileType{
ID: language.ID, Highlighted: hasBundledGrammar(language.Scope),
Extensions: slices.Clone(language.Extensions),
}
}
return result
}
109 changes: 109 additions & 0 deletions desktop/internal/fileassociations/registration.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
// Package fileassociations reads the system's actual text-file handlers and
// publishes explicit registrations. It never writes into the installed package.
package fileassociations

// Note: 系统默认应用与只读包边界见 .agents/notes/implemented/feature/2026-11-23-system-file-associations.md

import (
"context"
"errors"
"sync"

"github.com/1lck/Lithe-IDEA/desktop/internal/core"
"github.com/1lck/Lithe-IDEA/desktop/internal/editor/syntax"
)

var ErrConflict = errors.New("system file associations changed; refresh before applying")
var ErrNotPackaged = errors.New("file association registration requires an installed application")
var ErrUnsupported = errors.New("file association registration is not supported on this platform")

// Handler is an OS observation, rather than a stored Lithe preference.
type Handler struct {
Extension, DefaultID, DefaultName string
IsDefault, Registered bool
registration string
}

// State retains an optimistic baseline for the explicit apply action.
type State struct {
Formats []core.FileAssociationFormat
Handlers []Handler
Available bool
native nativeState
}

// Manager serializes this controller's reads and writes. Opening settings and
// changing draft checkboxes never create files or publish OS registrations.
type Manager struct {
mu sync.Mutex
Kernel *core.Client
}

func New() *Manager { return &Manager{Kernel: core.NewClient()} }

// Catalog uses the exact metadata of the built-in editor, including whether a
// grammar is actually bundled. Core owns filtering, deduplication and ordering.
func Catalog(ctx context.Context, kernel *core.Client) ([]core.FileAssociationFormat, error) {
observed := syntax.BundledFileTypes()
languages := make([]core.FileAssociationLanguage, len(observed))
for i, language := range observed {
languages[i] = core.FileAssociationLanguage{
ID: language.ID, Highlighted: language.Highlighted,
Extensions: language.Extensions,
}
}
return kernel.FileAssociationCatalog(ctx, languages)
}

func (m *Manager) Read(ctx context.Context) (State, error) {
m.mu.Lock()
defer m.mu.Unlock()
formats, err := Catalog(ctx, m.Kernel)
if err != nil {
return State{}, err
}
return readNative(ctx, formats)
}

func observations(state State) []core.FileAssociationObservation {
result := make([]core.FileAssociationObservation, len(state.Handlers))
for i, handler := range state.Handlers {
result[i] = core.FileAssociationObservation{
Extension: handler.Extension, DefaultID: handler.DefaultID,
Registration: handler.registration,
}
}
return result
}

// Apply requests changes for explicitly selected formats; macOS content-type
// aliases may share the resulting default. Native failures are followed by
// readback too, so a partially applied batch is never displayed as success.
func (m *Manager) Apply(ctx context.Context, baseline State, selected []string, menuLabel string) (State, error) {
m.mu.Lock()
defer m.mu.Unlock()
formats, err := Catalog(ctx, m.Kernel)
if err != nil {
return State{}, err
}
current, err := readNative(ctx, formats)
if err != nil {
return State{}, err
}
if !current.Available {
return current, ErrNotPackaged
}
plan, err := m.Kernel.PlanFileAssociations(ctx, formats, selected, observations(baseline), observations(current))
if err != nil {
return current, err
}
if plan.Conflict {
return current, ErrConflict
}
err = applyNative(ctx, current.native, plan.Extensions, menuLabel)
after, readErr := readNative(ctx, formats)
if readErr != nil {
return current, errors.Join(err, readErr)
}
return after, err
}
Loading
Loading