From f816d073627891e36c8cbfb5f4449b6e8ca2cd87 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 14 Nov 2026 14:57:10 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat(desktop):=20=E6=8F=92=E4=BB=B6?= =?UTF-8?q?=E8=AE=BE=E7=BD=AE=E9=A1=B5=E6=8C=89=E7=95=8C=E9=9D=A2=E8=AF=AD?= =?UTF-8?q?=E8=A8=80=E6=98=BE=E7=A4=BA=E6=8F=92=E4=BB=B6=E5=8C=85=E8=87=AA?= =?UTF-8?q?=E5=B8=A6=E7=9A=84=E7=BF=BB=E8=AF=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 插件可以在包里放 l10n/<语言>.json(Lithe-core-rust#36,API-37)。设置页 现在按界面语言读取:Core 先给出候选文件和上限,宿主经 configfile 从已安装 插件目录只读地取文件,再交给 Core 校验并逐条回退到清单原文。 - pluginsettings:Store.LoadPresented 两步读取,保存后的回读保留译文; 读不了的候选记进 Snapshot.LocalizationReadFailures 并继续下一个 - pluginservice:LoadSettingsEditor 带界面语言,包根即取清单的已安装目录 - settingswindow:界面语言变化后重读文字,有未保存草稿时不重读; 按钮确认弹窗使用译后的按钮标题 - workbench:读不了或被 Core 拒绝的语言文件各记一条 app.notification.operation_rejected(localization_unreadable、 invalid_localization) - Agent Note、API 实施计划 API-37 和功能矩阵同步更新 --- .../2026-10-21-plugin-settings-surfaces.md | 45 +++- .../2026-10-14-declarative-plugin-settings.md | 2 +- desktop/internal/core/plugin_settings.go | 61 ++++- desktop/internal/core/plugin_settings_test.go | 2 +- .../pluginservice/pluginservice_test.go | 2 +- .../pluginservice/settings_actions_test.go | 2 +- .../internal/pluginservice/settings_editor.go | 11 +- .../pluginservice/settings_editor_test.go | 85 ++++++- .../pluginservice/settings_start_test.go | 4 +- .../pluginsettings/localization_test.go | 222 ++++++++++++++++++ desktop/internal/pluginsettings/store.go | 102 +++++++- desktop/internal/pluginsettings/store_test.go | 4 +- desktop/internal/settingswindow/controller.go | 4 +- .../plugin_settings_actions_test.go | 3 +- .../plugin_settings_language_test.go | 138 +++++++++++ .../settingswindow/plugin_settings_model.go | 60 +++-- .../plugin_settings_model_test.go | 12 +- .../settingswindow/plugin_settings_view.go | 4 +- .../plugin_settings_view_test.go | 4 +- .../settingswindow/settings_surfaces.go | 1 + .../settingswindow/settings_surfaces_test.go | 2 +- desktop/internal/workbench/app.go | 2 +- desktop/internal/workbench/build_tree_test.go | 2 +- desktop/internal/workbench/logevents_test.go | 4 + .../workbench/settings_plugin_actions_test.go | 2 +- .../internal/workbench/settings_plugins.go | 25 +- .../workbench/settings_publication_test.go | 7 +- desktop/internal/workbench/startup_test.go | 67 +++++- desktop/internal/workbench/toolchains_test.go | 2 +- docs/development/macos-plugin-api-plan.md | 4 +- .../features/declarative-plugin-settings.json | 20 +- 31 files changed, 826 insertions(+), 79 deletions(-) create mode 100644 desktop/internal/pluginsettings/localization_test.go create mode 100644 desktop/internal/settingswindow/plugin_settings_language_test.go diff --git a/.agents/notes/implemented/architecture/2026-10-21-plugin-settings-surfaces.md b/.agents/notes/implemented/architecture/2026-10-21-plugin-settings-surfaces.md index 775f6ede8b..3f1466be9d 100644 --- a/.agents/notes/implemented/architecture/2026-10-21-plugin-settings-surfaces.md +++ b/.agents/notes/implemented/architecture/2026-10-21-plugin-settings-surfaces.md @@ -8,7 +8,9 @@ macOS 设置窗口现在可以由插件“注册”页面:插件在 `plugin.js “立即生效”的设置通过 LSP 的 `workspace/configuration` 推给正在运行的语言服务器,不需要重启。项目级的值写进项目里的 `.lithe/plugin-settings.json`,团队可以通过版本控制共享。 -日常开发的直接影响:想给某个语言或构建工具加设置或按钮,改插件清单,不要改宿主。 +设置页的文字由插件包自带的 `l10n/<语言>.json` 翻译。Core 按界面语言挑文件,缺哪条就回退到清单原文;宿主只负责从已安装的包里只读地取文件,不为插件文字维护词条(见决策第 9 节)。 + +日常开发的直接影响:想给某个语言或构建工具加设置或按钮,改插件清单,不要改宿主;想让插件设置显示中文,在插件包里加语言文件,不要往 `shared/i18n` 加插件的词条。 ## 问题 @@ -139,6 +141,23 @@ macOS 保留既有原生控件和主题,只在通用 owner 中修复压缩规 传入,不在几何回调里重新加载插件、重建列表或保存宽度。拖动和持久化仍由 既有 `LitheSplitPaneView` 负责,窄宽切换不替换表单实例。 +### 9. 插件包自带的设置文案翻译 + +设置页上的分组名、设置标题、说明、选项名和按钮名都来自 `plugin.json`,只有插件作者写的一种语言。宿主的 `shared/i18n` 只翻译宿主自己的界面,不为插件文字维护词条:那样宿主就要按插件内容维护特判,第三方插件也拿不到。所以译文由插件包自带,属于 API-37、`pluginAPIVersion` 0 的补充: + +- 插件在包里放 `l10n/<语言标签>.json`(例如 `l10n/zh-Hans.json`),按设置 ID、选项值、分组名和按钮 ID 给出译文。格式只由 Core 契约的 `plugin-l10n.schema.json` 和契约 README 定义,宿主不解析这些文件。 +- 读取分两步,都走 `plugins.declarative.settingsState`。第一步宿主只带界面语言,Core 返回候选文件和单文件上限:`zh-Hans` 依次是 `l10n/zh-Hans.json`、`l10n/zh.json`(逐级去掉子标签),上限 1 MiB。第二步宿主把读到的文本按包内路径交回,Core 校验后应用第一个有效文件;某一条缺失或无效时,只有这一条回退到清单原文。Core 返回 `localization.applied` 和 `rejected`,并给出译后的 `state`。 +- 宿主读文件用 `configfile.Capture`(`pluginsettings.Store.LoadPresented`)。根目录是取清单时用的那个已安装插件目录,经 `os.Root` 限定在包内,不跟随指向包外的链接。不存在的候选直接跳过,不算错误;存在但读不了的(例如是目录或没有权限)记进 `Snapshot.LocalizationReadFailures()`,然后继续读下一个候选。保存后的回读带着同一个语言请求,保存之后页面仍显示译文。 +- 已安装的插件包是该插件版本的发行基线,运行时只读。这条功能只读包里的固定文件,不新增写入、缓存、下载或解压位置,不影响代码签名,也不影响 Sparkle delta。`pluginservice` 和 `pluginsettings` 的测试会对比包内文件清单和字节,确认读取前后没有变化。 + +界面规则: + +- 分组标题显示 `state.Sections[].Title`。每行的 `Declaration.Section` 保持清单原文,只作分组键,不能拿来显示。 +- 界面语言改变后,设置页在下一次绘制时用新语言重读(`pluginSettingsForm.follow`)。如果用户有未保存的草稿,先不重读,保留当前文字和草稿;草稿保存或清掉后,再按新语言重读。正确做法:语言切换绝不丢草稿。不要这样做:语言一变就丢掉草稿、重建表单。 +- 按钮的确认弹窗用页面上译后的按钮标题。动作计划里的 `Title` 是清单原文,不能直接显示,否则中文按钮会弹出英文确认框。 + +日志:页面仍能加载,所以翻译问题记为“部分拒绝”,不是失败。事件是 `app.notification.operation_rejected`(WARN),`operation=plugin_settings_load`,`reason` 三选一:`localization_unreadable`(有候选文件读不了)、`invalid_localization`(Core 拒绝了文件或其中的条目)、`invalid_stored_values`(既有:保存的值无效)。字段都是 Token,不写路径和插件文字。只有整个读取失败时,才走 `app.notification.operation_failed`(`operation=plugin_settings_load`)。 + ## 考虑过的备选方案 ### 宿主为常见工具内置设置页 @@ -158,12 +177,25 @@ macOS 保留既有原生控件和主题,只在通用 owner 中修复压缩规 Swift 和 Windows 各写一遍合并规则最直接,但两边一旦有细微差异,界面显示的值和实际启动使用的值就会不同。所以合并只在 Core 做,宿主只负责存储和显示。 +### 宿主词条表翻译插件文字 + +旧 macOS 客户端的做法是:官方插件的文字以英文原文为键,放进宿主的 `Localizable.strings`。这样第三方插件拿不到翻译,插件改一个字就失效,宿主还要跟着插件内容维护词条。所以不采用,改为插件包自带译文。 + +### 由 Store 索引提供翻译 + +译文放在 Store 可以不改插件包。但离线安装和本地开发的插件拿不到,译文也会和已安装的插件版本脱节。所以译文跟着插件包发布,和清单同版本。 + +### 宿主解析并合并语言文件 + +Go 端直接读 JSON 再替换文字最省一次 Core 调用。但候选顺序、逐条回退和校验规则都要在 Windows 再写一遍,和“合并只在 Core 做”冲突。所以宿主只负责取字节,由 Core 决定用哪个文件、哪些条目。 + ## 后果 - 收益:新语言、新构建工具的设置不需要改宿主;社区插件和官方插件拿到同样的位置。 - 收益:团队可以通过 `.lithe/plugin-settings.json` 共享项目设置;“立即生效”的选项不再打断语言服务。 - 代价:宿主无法为某个工具做专门的交互(例如自定义排版);需要更复杂的界面时,只能扩展通用控件类型,而不是写专用页面。 - 代价:项目设置文件会出现在用户仓库里,团队需要决定是否提交它。 +- 收益:任何插件都能自带设置文字的翻译,不需要宿主发版。代价:插件作者要自己维护每种语言的文件。语言文件目前只覆盖设置,其它插件文字以后按同一格式扩展。 - 现有的 Java/Maven 项目设置页(`ProjectRuntimeSettingsView`、`LSPControlCenterView` 中的 Maven 重试)仍是宿主代码,属于历史遗留,后续应迁移到 Java 插件的声明里,不能作为新增特判的先例。 ## 验证 @@ -177,6 +209,11 @@ Swift 和 Windows 各写一遍合并规则最直接,但两边一旦有细微 - ~~./scripts/macos/test/test-macos.sh --filter PluginSettingsLayoutTests~~(随旧客户端移除):480、640、900 点宽的深浅主题下,路径输入框和完整选择按钮都在容器内,按钮可调用选择器并写入所选路径。 - ~~./scripts/macos/test/test-macos.sh --filter PluginDetailLayoutTests~~(随旧客户端移除):实际 Java 插件表单在深浅主题中往返缩放,详情边界始终跟随分隔条,窄面板下右侧设置可经原生横向滚动到达。 - 共享夹具:`Lithe-core-rust/shared/plugins/contract/v1/fixtures/settings/settings.plugin.json`。 +- Core `cargo test -p lithe-plugin-model localization` 与 `cargo test -p lithe-core settings_state_`:候选顺序、上限、逐条回退和拒绝原因;契约用例在 `fixtures/settings/localization-cases.json`。 +- `./scripts/desktop/desktop-go.sh test ./internal/pluginsettings -run 'Presented|Unreadable'`:按契约用例逐条比对 applied/rejected,保存回读保留译文,读不了的候选被跳过并上报,包内容不变。 +- `./scripts/desktop/desktop-go.sh test ./internal/pluginservice -run TestInstalledSettingsEditorTranslatesFromThePackageWithoutWritingIt`:从已安装插件目录取译文,包内文件清单和字节不变。 +- `./scripts/desktop/desktop-go.sh test ./internal/settingswindow -run TestPluginSettingsTextFollowsTheWindowLanguageWithoutDiscardingDrafts`:真实 Core 下切换界面语言,有草稿时不重读,确认弹窗使用译后的标题。 +- `./scripts/desktop/desktop-go.sh test ./internal/workbench -run 'TestPluginSettingsLoadLogsSkippedAndRefusedTranslations|TestLogEventsMatchCatalog'`:两种翻译问题各记一条 WARN,三个 reason 通过 Core 日志目录校验。 ## 适用范围 @@ -190,3 +227,9 @@ Swift 和 Windows 各写一遍合并规则最直接,但两边一旦有细微 - ~~`macos/Sources/Lithe/Views/Components/LitheSettingsControls.swift`~~(已随 #1794 移除) - ~~`macos/Sources/Lithe/Views/App/ContributedSettingsPageView.swift`~~(已随 #1794 移除) - `https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/contract/v1/README.md` +- Lithe-core-rust 锁定修订:[rust/crates/plugin-model/src/settings/localization.rs](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/3cff44040167971ea4384393238549d61e77746c/rust/crates/plugin-model/src/settings/localization.rs) +- Lithe-core-rust 锁定修订:[shared/plugins/contract/v1/plugin-l10n.schema.json](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/3cff44040167971ea4384393238549d61e77746c/shared/plugins/contract/v1/plugin-l10n.schema.json) +- `desktop/internal/pluginsettings/store.go`(两步读取与包内只读取文件) +- `desktop/internal/pluginservice/settings_editor.go`(以已安装插件目录作为包根) +- `desktop/internal/settingswindow/plugin_settings_model.go`、`plugin_settings_view.go`(跟随界面语言、保留草稿、确认标题) +- `desktop/internal/workbench/settings_plugins.go`(翻译问题的日志) diff --git a/.agents/notes/implemented/feature/2026-10-14-declarative-plugin-settings.md b/.agents/notes/implemented/feature/2026-10-14-declarative-plugin-settings.md index 53603286f5..8d39ce17d3 100644 --- a/.agents/notes/implemented/feature/2026-10-14-declarative-plugin-settings.md +++ b/.agents/notes/implemented/feature/2026-10-14-declarative-plugin-settings.md @@ -65,7 +65,7 @@ settings v2 仍复用 v1 的启动模板展开,但新增设置注册页、项 代价: -- 选项的显示文字来自插件清单,官方插件靠宿主的 `Localizable.strings` 以英文原文为键翻译,第三方插件的文字不会被翻译。 +- 选项的显示文字来自插件清单。当时官方插件靠宿主的 `Localizable.strings` 以英文原文为键翻译,第三方插件的文字不会被翻译;这个做法已随旧客户端移除。现在任何插件都在包里自带 `l10n/<语言>.json`,没有译文的条目显示清单原文,见 `2026-10-21-plugin-settings-surfaces.md` 决策第 9 节。 - 当前只覆盖“语言服务器启动”这一处用法,运行和测试模板不能引用选项。 - 选项值不会跟着卸载一起删除,重装后会找回;这是有意的,数据量很小。 diff --git a/desktop/internal/core/plugin_settings.go b/desktop/internal/core/plugin_settings.go index 01a9c75cea..ddb8f78cb9 100644 --- a/desktop/internal/core/plugin_settings.go +++ b/desktop/internal/core/plugin_settings.go @@ -127,6 +127,33 @@ type PluginSettingsState struct { Settings map[string]json.RawMessage `json:"settings"` ProjectSettings map[string]json.RawMessage `json:"projectSettings"` Storage PluginSettingsStorage `json:"storage"` + // Localization is present whenever the request named a language. + Localization *PluginSettingsLocalization `json:"localization,omitempty"` +} + +// PluginSettingsLocalizationRequest names the interface language and, on the +// second read, the candidate files found in the installed package. Nil Files +// asks Core which candidates to read; a non-nil empty map reports none found. +type PluginSettingsLocalizationRequest struct { + Language string + Files map[string]string +} + +// PluginSettingsLocalization reports which package translation Core applied. +// The host reads Candidates only when ReadRequired; Core never reads files. +type PluginSettingsLocalization struct { + Language string `json:"language"` + Candidates []string `json:"candidates"` + MaximumBytes int64 `json:"maximumBytes"` + ReadRequired bool `json:"readRequired"` + Applied *string `json:"applied"` + Rejected []PluginSettingsLocalizationRejection `json:"rejected"` +} + +// PluginSettingsLocalizationRejection is one supplied file Core refused whole. +type PluginSettingsLocalizationRejection struct { + Path string `json:"path"` + Error MarketplaceRejection `json:"error"` } // PluginSettingEdit supplies a typed override or unparsed editor Text. @@ -148,8 +175,9 @@ type PluginSettingsEditPlan struct { // ReadPluginSettingsState asks Core to decode whole documents. Nil identifies a // missing file; an existing empty file must be passed as a non-nil empty string. -func (c *Client) ReadPluginSettingsState(ctx context.Context, manifest json.RawMessage, global, project *string) (PluginSettingsState, error) { - return c.readPluginSettingsState(ctx, manifest, global, project, nil) +// A nil localization keeps manifest text and omits State.Localization. +func (c *Client) ReadPluginSettingsState(ctx context.Context, manifest json.RawMessage, global, project *string, localization *PluginSettingsLocalizationRequest) (PluginSettingsState, error) { + return c.readPluginSettingsState(ctx, manifest, global, project, nil, localization) } // ReadInstalledPluginSettingsState binds declaration metadata to native package @@ -158,22 +186,34 @@ func (c *Client) ReadInstalledPluginSettingsState(ctx context.Context, manifest return c.readPluginSettingsState(ctx, manifest, nil, nil, &struct { PluginID string `json:"pluginID"` Version string `json:"version"` - }{id, version}) + }{id, version}, nil) } -func (c *Client) readPluginSettingsState(ctx context.Context, manifest json.RawMessage, global, project *string, owner any) (PluginSettingsState, error) { +func (c *Client) readPluginSettingsState(ctx context.Context, manifest json.RawMessage, global, project *string, owner any, localization *PluginSettingsLocalizationRequest) (PluginSettingsState, error) { const command = "plugins.declarative.settingsState" var result struct { Status string `json:"status"` Error *MarketplaceRejection `json:"error"` State *PluginSettingsState `json:"state"` } + var language *string + var files *map[string]string + if localization != nil { + language = &localization.Language + if localization.Files != nil { + files = &localization.Files + } + } + // The pointer keeps an empty map on the wire: "read, none found" differs + // from "not read yet", which Core answers with readRequired. if err := c.Execute(ctx, command, struct { - Manifest json.RawMessage `json:"manifest"` - Owner any `json:"owner,omitempty"` - Global *string `json:"globalDocument"` - Project *string `json:"projectDocument"` - }{manifest, owner, global, project}, &result); err != nil { + Manifest json.RawMessage `json:"manifest"` + Owner any `json:"owner,omitempty"` + Global *string `json:"globalDocument"` + Project *string `json:"projectDocument"` + Language *string `json:"language,omitempty"` + Localizations *map[string]string `json:"localizations,omitempty"` + }{manifest, owner, global, project, language, files}, &result); err != nil { return PluginSettingsState{}, err } if result.Status == "rejected" && result.Error != nil { @@ -186,6 +226,9 @@ func (c *Client) readPluginSettingsState(ctx context.Context, manifest json.RawM if state.Metadata.DisplayName == "" || state.Metadata.Version == "" || len(state.Editors.Global) != len(state.Rows) || len(state.Editors.Project) != len(state.Rows) { return PluginSettingsState{}, newParseError(command, "invalid editor projection", "") } + if localization != nil && (state.Localization == nil || state.Localization.MaximumBytes <= 0) { + return PluginSettingsState{}, newParseError(command, "invalid localization report", "") + } sections := append([]PluginSettingsSection(nil), state.Sections...) for _, page := range state.Pages { sections = append(sections, page.Sections...) diff --git a/desktop/internal/core/plugin_settings_test.go b/desktop/internal/core/plugin_settings_test.go index aff41fcd42..6243d7791b 100644 --- a/desktop/internal/core/plugin_settings_test.go +++ b/desktop/internal/core/plugin_settings_test.go @@ -67,7 +67,7 @@ func TestPluginSettingsDocumentSharedFixture(t *testing.T) { } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - state, err := client.ReadPluginSettingsState(ctx, fixture.Manifest, nil, nil) + state, err := client.ReadPluginSettingsState(ctx, fixture.Manifest, nil, nil, nil) if err != nil { t.Fatal(err) } diff --git a/desktop/internal/pluginservice/pluginservice_test.go b/desktop/internal/pluginservice/pluginservice_test.go index 79f5d2f7e0..93ddc903fe 100644 --- a/desktop/internal/pluginservice/pluginservice_test.go +++ b/desktop/internal/pluginservice/pluginservice_test.go @@ -407,7 +407,7 @@ func TestLoadLanguagesRefusesAnEscapingGrammarPath(t *testing.T) { // These package-assembly tests use minimal manifests, not declaration rules. // Settings-specific tests override this method with the real Core bridge. -func (k *fakeKernel) ReadPluginSettingsState(context.Context, json.RawMessage, *string, *string) (core.PluginSettingsState, error) { +func (k *fakeKernel) ReadPluginSettingsState(context.Context, json.RawMessage, *string, *string, *core.PluginSettingsLocalizationRequest) (core.PluginSettingsState, error) { return core.PluginSettingsState{}, nil } diff --git a/desktop/internal/pluginservice/settings_actions_test.go b/desktop/internal/pluginservice/settings_actions_test.go index d027c0c034..367e0f5c49 100644 --- a/desktop/internal/pluginservice/settings_actions_test.go +++ b/desktop/internal/pluginservice/settings_actions_test.go @@ -62,7 +62,7 @@ func TestSettingsActionPlanningRechecksNativeOwnersWithoutPublishing(t *testing. if err != nil { t.Fatal(err) } - editor, err := service.LoadSettingsEditor(ctx, "dev.lithe.fixture.settings", workspace) + editor, err := service.LoadSettingsEditor(ctx, "dev.lithe.fixture.settings", workspace, "") if err != nil { t.Fatal(err) } diff --git a/desktop/internal/pluginservice/settings_editor.go b/desktop/internal/pluginservice/settings_editor.go index fe2cb83853..f49851f240 100644 --- a/desktop/internal/pluginservice/settings_editor.go +++ b/desktop/internal/pluginservice/settings_editor.go @@ -66,7 +66,9 @@ func (s *Service) settingsEntry(ctx context.Context, id string) (pluginmanager.E } // LoadSettingsEditor captures real sources without creating files or processes. -func (s *Service) LoadSettingsEditor(ctx context.Context, id, workspace string) (SettingsEditor, error) { +// language is the interface language tag; translations are read from the +// installed package, so an empty language keeps manifest text. +func (s *Service) LoadSettingsEditor(ctx context.Context, id, workspace, language string) (SettingsEditor, error) { if s == nil || s.Settings == nil { return SettingsEditor{}, ErrAssembly } @@ -92,7 +94,12 @@ func (s *Service) LoadSettingsEditor(ctx context.Context, id, workspace string) return SettingsEditor{}, err } } - snapshot, err := s.Settings.Load(ctx, manifest.Bytes(), workspace) + var snapshot pluginsettings.Snapshot + if language == "" { + snapshot, err = s.Settings.Load(ctx, manifest.Bytes(), workspace) + } else { + snapshot, err = s.Settings.LoadPresented(ctx, manifest.Bytes(), workspace, pluginsettings.Presentation{Language: language, Package: entry.Installed.Path}) + } if err != nil { return SettingsEditor{}, err } diff --git a/desktop/internal/pluginservice/settings_editor_test.go b/desktop/internal/pluginservice/settings_editor_test.go index 30613afe15..aef757a8a7 100644 --- a/desktop/internal/pluginservice/settings_editor_test.go +++ b/desktop/internal/pluginservice/settings_editor_test.go @@ -52,7 +52,7 @@ func TestInstalledSettingsEditorPublishesAndRejectsChangedOwners(t *testing.T) { if err != nil || len(catalog) != 1 || catalog[0].ID != "dev.example.settings" { t.Fatalf("local catalog=%+v error=%v", catalog, err) } - editor, err := service.LoadSettingsEditor(ctx, "dev.example.settings", "") + editor, err := service.LoadSettingsEditor(ctx, "dev.example.settings", "", "") if err != nil { t.Fatal(err) } @@ -94,7 +94,7 @@ func TestInstalledSettingsEditorPublishesAndRejectsChangedOwners(t *testing.T) { if err != nil || !result.Committed || result.Readback == nil { t.Fatalf("save=%+v error=%v", result, err) } - reopened, err := service.LoadSettingsEditor(ctx, "dev.example.settings", "") + reopened, err := service.LoadSettingsEditor(ctx, "dev.example.settings", "", "") if err != nil { t.Fatal(err) } @@ -155,9 +155,88 @@ func TestInstalledSettingsRejectsManifestForAnotherRegistration(t *testing.T) { if err == nil || len(catalog) != 0 { t.Fatalf("mismatched package entered settings catalog: %+v %v", catalog, err) } - if _, err := service.LoadSettingsEditor(ctx, "dev.example.settings", ""); err == nil { + if _, err := service.LoadSettingsEditor(ctx, "dev.example.settings", "", ""); err == nil { t.Fatal("mismatched package acquired an editable source") } }) } } + +func TestInstalledSettingsEditorTranslatesFromThePackageWithoutWritingIt(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + source := contractfixture.Path("fixtures/settings") + preferences, plugins := t.TempDir(), t.TempDir() + packageRoot := filepath.Join(plugins, "dev.lithe.fixture.settings", "0.1.0") + files := map[string][]byte{} + for name, from := range map[string]string{pluginpkg.ManifestFile: "settings.plugin.json", "l10n/zh-Hans.json": "l10n/zh-Hans.json"} { + data, err := os.ReadFile(filepath.Join(source, filepath.FromSlash(from))) + if err != nil { + t.Fatal(err) + } + target := filepath.Join(packageRoot, filepath.FromSlash(name)) + if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(target, data, 0o600); err != nil { + t.Fatal(err) + } + files[name] = data + } + kernel := &settingsPlanningKernel{fakeKernel: &fakeKernel{}, client: core.NewClient()} + service, err := Open(kernel, store.At(preferences), plugins) + if err != nil { + t.Fatal(err) + } + title := func(state core.PluginSettingsState) string { + for _, row := range state.Rows { + if row.Declaration.ID == "checks" { + return row.Declaration.Title + } + } + t.Fatalf("no checks row: %+v", state.Rows) + return "" + } + plain, err := service.LoadSettingsEditor(ctx, "dev.lithe.fixture.settings", "", "") + if err != nil { + t.Fatal(err) + } + if title(plain.Snapshot.State) != "Checks" || plain.Snapshot.State.Localization != nil { + t.Fatalf("no language translated: %+v", plain.Snapshot.State.Localization) + } + editor, err := service.LoadSettingsEditor(ctx, "dev.lithe.fixture.settings", "", "zh-Hans") + if err != nil { + t.Fatal(err) + } + if title(editor.Snapshot.State) != "检查项" { + t.Fatalf("package translation not applied: %+v", editor.Snapshot.State.Localization) + } + result, err := service.SaveSettingsEditor(ctx, editor, "global", []core.PluginSettingEdit{{ID: "checks", Value: json.RawMessage(`["credo"]`)}}, nil) + if err != nil || !result.Committed || result.Readback == nil { + t.Fatalf("save=%+v error=%v", result, err) + } + if title(result.Readback.State) != "检查项" { + t.Fatal("readback dropped the translation") + } + // The installed package is an exact input: reading its translation writes nothing into it. + var names []string + if err := filepath.WalkDir(packageRoot, func(path string, entry os.DirEntry, err error) error { + if err != nil || entry.IsDir() { + return err + } + name, err := filepath.Rel(packageRoot, path) + names = append(names, filepath.ToSlash(name)) + return err + }); err != nil { + t.Fatal(err) + } + if len(names) != len(files) { + t.Fatalf("package files changed: %v", names) + } + for name, want := range files { + actual, err := os.ReadFile(filepath.Join(packageRoot, filepath.FromSlash(name))) + if err != nil || string(actual) != string(want) { + t.Fatalf("installed %s changed: %v", name, err) + } + } +} diff --git a/desktop/internal/pluginservice/settings_start_test.go b/desktop/internal/pluginservice/settings_start_test.go index 5cca71d876..1222aaae89 100644 --- a/desktop/internal/pluginservice/settings_start_test.go +++ b/desktop/internal/pluginservice/settings_start_test.go @@ -34,8 +34,8 @@ func (k *settingsPlanningKernel) PlanPluginLanguageServer(_ context.Context, _ j return core.PluginBackendPlan{}, errSettingsPlanCaptured } -func (k *settingsPlanningKernel) ReadPluginSettingsState(ctx context.Context, manifest json.RawMessage, global, project *string) (core.PluginSettingsState, error) { - return k.client.ReadPluginSettingsState(ctx, manifest, global, project) +func (k *settingsPlanningKernel) ReadPluginSettingsState(ctx context.Context, manifest json.RawMessage, global, project *string, localization *core.PluginSettingsLocalizationRequest) (core.PluginSettingsState, error) { + return k.client.ReadPluginSettingsState(ctx, manifest, global, project, localization) } func (k *settingsPlanningKernel) EditPluginSettings(ctx context.Context, manifest json.RawMessage, scope string, document *string, edits []core.PluginSettingEdit) (core.PluginSettingsEditPlan, error) { diff --git a/desktop/internal/pluginsettings/localization_test.go b/desktop/internal/pluginsettings/localization_test.go new file mode 100644 index 0000000000..94a8c1738b --- /dev/null +++ b/desktop/internal/pluginsettings/localization_test.go @@ -0,0 +1,222 @@ +package pluginsettings + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// translatedFixture is the contract's settings manifest and the directory holding its packaged +// l10n/zh-Hans.json, which the tests read in place as an installed package. +func translatedFixture(t *testing.T) (json.RawMessage, string) { + t.Helper() + directory := contractfixture.Path("fixtures/settings") + manifest, err := os.ReadFile(filepath.Join(directory, "settings.plugin.json")) + if err != nil { + t.Fatal(err) + } + return manifest, directory +} + +func declaration(t *testing.T, state core.PluginSettingsState, id string) core.PluginSettingDeclaration { + t.Helper() + for _, row := range state.Rows { + if row.Declaration.ID == id { + return row.Declaration + } + } + t.Fatalf("no row %q in %+v", id, state.Rows) + return core.PluginSettingDeclaration{} +} + +// assertTranslated checks the text l10n/zh-Hans.json gives the fixture manifest. +func assertTranslated(t *testing.T, state core.PluginSettingsState) { + t.Helper() + localization := state.Localization + if localization == nil || localization.Applied == nil || *localization.Applied != "l10n/zh-Hans.json" || len(localization.Rejected) != 0 { + t.Fatalf("translation not applied: %+v", localization) + } + if title := declaration(t, state, "dialyzer").Title; title != "Dialyzer 静态分析" { + t.Fatalf("dialyzer title %q", title) + } + checks := declaration(t, state, "checks") + if checks.Title != "检查项" || len(checks.Options) != 2 || checks.Options[0].Title != "格式检查" || checks.Options[1].Title != "Credo" { + t.Fatalf("checks not translated, untranslated option not kept: %+v", checks) + } + // A row's section stays the manifest heading, a grouping key; the view shows the section title. + var titles []string + for _, section := range state.Sections { + titles = append(titles, section.Title) + } + if len(titles) != 2 || titles[0] != "" || titles[1] != "服务器" { + t.Fatalf("section titles %q", titles) + } + if len(state.Actions) != 1 || state.Actions[0].Title != "重建 PLT" { + t.Fatalf("action not translated: %+v", state.Actions) + } +} + +func TestPresentedLoadAppliesPackageTranslationAndReadbackKeepsIt(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + manifest, directory := translatedFixture(t) + store, workspace := New(core.NewClient(), filepath.Join(t.TempDir(), "preferences")), t.TempDir() + + plain, err := store.Load(ctx, manifest, workspace) + if err != nil { + t.Fatal(err) + } + if plain.State.Localization != nil || declaration(t, plain.State, "dialyzer").Title != "Dialyzer" { + t.Fatalf("a load without a language changed manifest text: %+v", plain.State.Localization) + } + + snapshot, err := store.LoadPresented(ctx, manifest, workspace, Presentation{Language: "zh-Hans", Package: directory}) + if err != nil { + t.Fatal(err) + } + assertTranslated(t, snapshot.State) + // l10n/zh.json, the shorter candidate, is absent: expected, not a read failure. + if got := snapshot.State.Localization.Candidates; len(got) != 2 || got[0] != "l10n/zh-Hans.json" || got[1] != "l10n/zh.json" { + t.Fatalf("candidates %v", got) + } + if failures := snapshot.LocalizationReadFailures(); len(failures) != 0 { + t.Fatalf("absent candidate reported: %+v", failures) + } + + saved, err := store.Save(ctx, snapshot, "project", []core.PluginSettingEdit{{ID: "dialyzer", Value: json.RawMessage(`false`)}}, nil) + if err != nil || !saved.Committed || saved.Readback == nil { + t.Fatalf("save: %+v, %v", saved, err) + } + assertTranslated(t, saved.Readback.State) + for _, row := range saved.Readback.State.Rows { + if row.Declaration.ID == "dialyzer" && string(row.Effective.Value) != "false" { + t.Fatalf("readback lost the saved value: %+v", row) + } + } +} + +// TestPresentedLoadFollowsContractLocalizationCases runs every case of the contract through the +// adapter: the files are placed in a package, read from the candidates Core names, and Core's +// report must match the case. +func TestPresentedLoadFollowsContractLocalizationCases(t *testing.T) { + data, err := os.ReadFile(contractfixture.Path("fixtures/settings/localization-cases.json")) + if err != nil { + t.Fatal(err) + } + var suite struct { + Manifest string `json:"manifest"` + Cases []struct { + Name string `json:"name"` + Language string `json:"language"` + Files map[string]json.RawMessage `json:"files"` + Applied *string `json:"applied"` + Rejected []struct { + Path string `json:"path"` + Field *string `json:"field"` + } `json:"rejected"` + } `json:"cases"` + } + if err := json.Unmarshal(data, &suite); err != nil { + t.Fatal(err) + } + if len(suite.Cases) == 0 { + t.Fatal("no localization cases") + } + manifest, err := os.ReadFile(contractfixture.Path("fixtures/settings/" + suite.Manifest)) + if err != nil { + t.Fatal(err) + } + for _, c := range suite.Cases { + t.Run(c.Name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + directory := t.TempDir() + for path, value := range c.Files { + // A JSON string is text sent as is; any other value is sent serialized. + text := []byte(value) + var literal string + if json.Unmarshal(value, &literal) == nil { + text = []byte(literal) + } + target := filepath.Join(directory, filepath.FromSlash(path)) + if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(target, text, 0o600); err != nil { + t.Fatal(err) + } + } + snapshot, err := New(core.NewClient(), t.TempDir()).LoadPresented(ctx, manifest, "", Presentation{Language: c.Language, Package: directory}) + if err != nil { + t.Fatal(err) + } + localization := snapshot.State.Localization + if localization == nil || localization.ReadRequired { + t.Fatalf("no final report: %+v", localization) + } + if (localization.Applied == nil) != (c.Applied == nil) || (c.Applied != nil && *localization.Applied != *c.Applied) { + t.Fatalf("applied %v, want %v", localization.Applied, c.Applied) + } + if len(localization.Rejected) != len(c.Rejected) { + t.Fatalf("rejected %+v, want %+v", localization.Rejected, c.Rejected) + } + for index, want := range c.Rejected { + got := localization.Rejected[index] + field := "" + if want.Field != nil { + field = *want.Field + } + if got.Path != want.Path || got.Error.Field != field || got.Error.Code != "plugin.settings.invalidLocalization" { + t.Fatalf("rejection %d: %+v, want %s %q", index, got, want.Path, field) + } + } + if failures := snapshot.LocalizationReadFailures(); len(failures) != 0 { + t.Fatalf("readable files reported unreadable: %+v", failures) + } + }) + } +} + +func TestUnreadableTranslationIsSkippedAndReported(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + manifest, _ := translatedFixture(t) + directory := t.TempDir() + // The specific candidate is a directory, so it cannot be read; the shorter one still serves. + if err := os.MkdirAll(filepath.Join(directory, "l10n", "zh-Hans.json"), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(directory, "l10n", "zh.json"), []byte(`{"settings":{"dialyzer":{"title":"中文"}}}`), 0o600); err != nil { + t.Fatal(err) + } + before, err := os.ReadDir(filepath.Join(directory, "l10n")) + if err != nil { + t.Fatal(err) + } + snapshot, err := New(core.NewClient(), t.TempDir()).LoadPresented(ctx, manifest, "", Presentation{Language: "zh-Hans", Package: directory}) + if err != nil { + t.Fatal(err) + } + failures := snapshot.LocalizationReadFailures() + if len(failures) != 1 || failures[0].Path != "l10n/zh-Hans.json" || !errors.Is(failures[0].Err, configfile.ErrTarget) { + t.Fatalf("read failures %+v", failures) + } + if applied := snapshot.State.Localization.Applied; applied == nil || *applied != "l10n/zh.json" { + t.Fatalf("applied %v", applied) + } + if title := declaration(t, snapshot.State, "dialyzer").Title; title != "中文" { + t.Fatalf("dialyzer title %q", title) + } + after, err := os.ReadDir(filepath.Join(directory, "l10n")) + if err != nil || len(after) != len(before) { + t.Fatalf("reading translations changed the package: %v, %v", after, err) + } +} diff --git a/desktop/internal/pluginsettings/store.go b/desktop/internal/pluginsettings/store.go index ae62be2beb..39de7f688b 100644 --- a/desktop/internal/pluginsettings/store.go +++ b/desktop/internal/pluginsettings/store.go @@ -16,7 +16,7 @@ var ErrNoProject = errors.New("plugin project settings have no workspace source" // Kernel owns document validation, inheritance, edit rules, and effect planning. type Kernel interface { - ReadPluginSettingsState(context.Context, json.RawMessage, *string, *string) (core.PluginSettingsState, error) + ReadPluginSettingsState(context.Context, json.RawMessage, *string, *string, *core.PluginSettingsLocalizationRequest) (core.PluginSettingsState, error) EditPluginSettings(context.Context, json.RawMessage, string, *string, []core.PluginSettingEdit) (core.PluginSettingsEditPlan, error) } @@ -30,19 +30,43 @@ func New(kernel Kernel, preferenceDirectory string) *Store { return &Store{kernel: kernel, globalRoot: preferenceDirectory} } +// Presentation selects the interface language of a settings view. Package is +// the installed plugin directory; translations are only read from it, never +// written, so the installed package stays byte-identical. +type Presentation struct { + Language string + Package string +} + +// LocalizationReadFailure is a candidate translation that exists but could not +// be read. The adapter skips it, so Core falls back to the next candidate or to +// manifest text; the caller owns logging it. +type LocalizationReadFailure struct { + Path string + Err error +} + // Snapshot exposes only Core's projection and source locations. Whole documents // and baselines stay private, separate from editable view state. type Snapshot struct { - State core.PluginSettingsState - workspace string - globalRoot string - manifest json.RawMessage - global configfile.Snapshot - project configfile.Snapshot + State core.PluginSettingsState + workspace string + globalRoot string + manifest json.RawMessage + presentation *Presentation + global configfile.Snapshot + project configfile.Snapshot + unreadable []LocalizationReadFailure } func (s Snapshot) Workspace() string { return s.workspace } +// LocalizationReadFailures lists candidates skipped by this load. Files Core +// refused are in State.Localization.Rejected instead. +func (s Snapshot) LocalizationReadFailures() []LocalizationReadFailure { + return append([]LocalizationReadFailure(nil), s.unreadable...) +} + // PreferenceDirectory is the private native storage owner, not view metadata. func (s Snapshot) PreferenceDirectory() string { return s.globalRoot } @@ -67,16 +91,45 @@ type SaveResult struct { // Load reads actual sources after asking Core what to read and how much. A // missing project is explicit; malformed or unreadable files never become empty. +// Text stays as written in the manifest; use LoadPresented for a settings view. func (s *Store) Load(ctx context.Context, manifest json.RawMessage, workspace string) (Snapshot, error) { - policy, err := s.kernel.ReadPluginSettingsState(ctx, manifest, nil, nil) + return s.load(ctx, manifest, workspace, nil) +} + +// LoadPresented also applies the package translation Core selects for the +// language. Save readback keeps the same presentation. +func (s *Store) LoadPresented(ctx context.Context, manifest json.RawMessage, workspace string, presentation Presentation) (Snapshot, error) { + return s.load(ctx, manifest, workspace, &presentation) +} + +func (s *Store) load(ctx context.Context, manifest json.RawMessage, workspace string, presentation *Presentation) (Snapshot, error) { + var localization *core.PluginSettingsLocalizationRequest + if presentation != nil { + localization = &core.PluginSettingsLocalizationRequest{Language: presentation.Language} + } + policy, err := s.kernel.ReadPluginSettingsState(ctx, manifest, nil, nil, localization) if err != nil { return Snapshot{}, err } - snapshot := Snapshot{workspace: workspace, globalRoot: s.globalRoot, manifest: append(json.RawMessage(nil), manifest...)} - if !policy.Storage.ReadRequired { + snapshot := Snapshot{workspace: workspace, globalRoot: s.globalRoot, manifest: append(json.RawMessage(nil), manifest...), presentation: presentation} + translate := policy.Localization != nil && policy.Localization.ReadRequired + if !policy.Storage.ReadRequired && !translate { snapshot.State = policy return snapshot, nil } + if translate { + localization.Files, snapshot.unreadable, err = readTranslations(ctx, presentation.Package, *policy.Localization) + if err != nil { + return Snapshot{}, err + } + } + if !policy.Storage.ReadRequired { + snapshot.State, err = s.kernel.ReadPluginSettingsState(ctx, manifest, nil, nil, localization) + if err != nil { + return Snapshot{}, err + } + return snapshot, nil + } snapshot.global, err = configfile.Capture(ctx, s.globalRoot, policy.Storage.GlobalRelativePath, policy.Storage.MaximumBytes) if err != nil { return Snapshot{}, err @@ -103,13 +156,38 @@ func (s *Store) Load(ctx context.Context, manifest json.RawMessage, workspace st return Snapshot{}, err } } - snapshot.State, err = s.kernel.ReadPluginSettingsState(ctx, manifest, global, project) + snapshot.State, err = s.kernel.ReadPluginSettingsState(ctx, manifest, global, project, localization) if err != nil { return Snapshot{}, err } return snapshot, nil } +// readTranslations returns every candidate present in the package. A missing +// candidate is the normal case; any other failure skips only that file. +func readTranslations(ctx context.Context, packageDirectory string, plan core.PluginSettingsLocalization) (map[string]string, []LocalizationReadFailure, error) { + files := map[string]string{} + var unreadable []LocalizationReadFailure + for _, candidate := range plan.Candidates { + source, err := configfile.Capture(ctx, packageDirectory, candidate, plan.MaximumBytes) + var text *string + if err == nil { + text, err = source.Text() + } + if ctxErr := ctx.Err(); ctxErr != nil { + return nil, nil, ctxErr + } + if err != nil { + unreadable = append(unreadable, LocalizationReadFailure{Path: candidate, Err: err}) + continue + } + if text != nil { + files[candidate] = *text + } + } + return files, unreadable, nil +} + // Save changes one captured layer only. check binds the plugin registration and // workspace to the initiating owner; it runs before planning and publication. func (s *Store) Save(ctx context.Context, snapshot Snapshot, scope string, edits []core.PluginSettingEdit, check func() error) (SaveResult, error) { @@ -150,7 +228,7 @@ func (s *Store) Save(ctx context.Context, snapshot Snapshot, scope string, edits } // Effects belong to the validated edit, but must not run before publication. result.Effects = plan.Effects - readback, readErr := New(s.kernel, snapshot.globalRoot).Load(ctx, snapshot.manifest, snapshot.workspace) + readback, readErr := New(s.kernel, snapshot.globalRoot).load(ctx, snapshot.manifest, snapshot.workspace, snapshot.presentation) if readErr == nil { result.Readback = &readback } diff --git a/desktop/internal/pluginsettings/store_test.go b/desktop/internal/pluginsettings/store_test.go index af5d07b986..f97a0c1a0f 100644 --- a/desktop/internal/pluginsettings/store_test.go +++ b/desktop/internal/pluginsettings/store_test.go @@ -177,11 +177,11 @@ type readbackFailureKernel struct { failure error } -func (k *readbackFailureKernel) ReadPluginSettingsState(ctx context.Context, manifest json.RawMessage, global, project *string) (core.PluginSettingsState, error) { +func (k *readbackFailureKernel) ReadPluginSettingsState(ctx context.Context, manifest json.RawMessage, global, project *string, localization *core.PluginSettingsLocalizationRequest) (core.PluginSettingsState, error) { if global != nil { return core.PluginSettingsState{}, k.failure } - return k.Client.ReadPluginSettingsState(ctx, manifest, global, project) + return k.Client.ReadPluginSettingsState(ctx, manifest, global, project, localization) } func TestPluginSettingsCommittedReadbackFailureCannotRetryOldBaseline(t *testing.T) { diff --git a/desktop/internal/settingswindow/controller.go b/desktop/internal/settingswindow/controller.go index d603e81985..bd7433925c 100644 --- a/desktop/internal/settingswindow/controller.go +++ b/desktop/internal/settingswindow/controller.go @@ -186,8 +186,10 @@ type ToolchainLoader interface { } // PluginSettingsLoader reads and publishes captured native sources off the UI thread. +// Load translates the plugin's own text for the language; a save's readback keeps the +// language its editor was loaded in. type PluginSettingsLoader interface { - Load(context.Context, string) (pluginservice.SettingsEditor, error) + Load(context.Context, string, i18n.Language) (pluginservice.SettingsEditor, error) Save(context.Context, pluginservice.SettingsEditor, string, []core.PluginSettingEdit) (pluginsettings.SaveResult, error) } diff --git a/desktop/internal/settingswindow/plugin_settings_actions_test.go b/desktop/internal/settingswindow/plugin_settings_actions_test.go index 2fbae42c8d..6471342986 100644 --- a/desktop/internal/settingswindow/plugin_settings_actions_test.go +++ b/desktop/internal/settingswindow/plugin_settings_actions_test.go @@ -7,6 +7,7 @@ import ( "time" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginsettings" ) @@ -19,7 +20,7 @@ type actionFormLoader struct { returned chan struct{} } -func (s *actionFormLoader) Load(context.Context, string) (pluginservice.SettingsEditor, error) { +func (s *actionFormLoader) Load(context.Context, string, i18n.Language) (pluginservice.SettingsEditor, error) { return pluginservice.SettingsEditor{}, errors.New("unexpected load") } func (s *actionFormLoader) Save(context.Context, pluginservice.SettingsEditor, string, []core.PluginSettingEdit) (pluginsettings.SaveResult, error) { diff --git a/desktop/internal/settingswindow/plugin_settings_language_test.go b/desktop/internal/settingswindow/plugin_settings_language_test.go new file mode 100644 index 0000000000..652462ea0b --- /dev/null +++ b/desktop/internal/settingswindow/plugin_settings_language_test.go @@ -0,0 +1,138 @@ +package settingswindow + +import ( + "context" + "os" + "path/filepath" + "sync" + "sync/atomic" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginsettings" + "github.com/vivaui/viva/app" +) + +// presentedFormSource loads the contract's settings fixture as an installed package with its +// l10n/zh-Hans.json, the way the plugin service does, and records the language of each load. +// Its action asks for confirmation with the manifest's title, as Core plans it. +type presentedFormSource struct { + store *pluginsettings.Store + manifest []byte + directory string + mu sync.Mutex + languages []i18n.Language +} + +func (s *presentedFormSource) Load(ctx context.Context, _ string, language i18n.Language) (pluginservice.SettingsEditor, error) { + s.mu.Lock() + s.languages = append(s.languages, language) + s.mu.Unlock() + snapshot, err := s.store.LoadPresented(ctx, s.manifest, "", pluginsettings.Presentation{Language: language.Code(), Package: s.directory}) + return pluginservice.SettingsEditor{Snapshot: snapshot}, err +} + +func (s *presentedFormSource) Save(ctx context.Context, editor pluginservice.SettingsEditor, scope string, edits []core.PluginSettingEdit) (pluginsettings.SaveResult, error) { + return s.store.Save(ctx, editor.Snapshot, scope, edits, nil) +} + +func (s *presentedFormSource) Action(_ context.Context, _ pluginservice.SettingsEditor, id string, _ bool) (pluginservice.SettingsActionResult, error) { + return pluginservice.SettingsActionResult{Plan: core.PluginSettingsActionPlan{Kind: "confirmationRequired", ActionID: id, Title: "Rebuild PLT"}}, nil +} + +func (s *presentedFormSource) loads() []i18n.Language { + s.mu.Lock() + defer s.mu.Unlock() + return append([]i18n.Language(nil), s.languages...) +} + +// The plugin's own text follows the window's language: a clean form reloads in the new +// language, a form with a draft keeps its text and the draft until the draft is gone, and the +// confirmation of an action names it the way its translated button does. +func TestPluginSettingsTextFollowsTheWindowLanguageWithoutDiscardingDrafts(t *testing.T) { + directory := contractfixture.Path("fixtures/settings") + manifest, err := os.ReadFile(filepath.Join(directory, "settings.plugin.json")) + if err != nil { + t.Fatal(err) + } + client := core.NewClient() + source := &presentedFormSource{store: pluginsettings.New(client, t.TempDir()), manifest: manifest, directory: directory} + var language atomic.Int32 + current := func() i18n.Language { return i18n.Language(language.Load()) } + w := newWindow(NewController(Options{ + PluginSettings: source, + Language: current, + Text: func() *i18n.Messages { return i18n.For(current()) }, + SettingsNavigation: client.SettingsNavigation, + SettingsPages: func(ctx context.Context) ([]core.SettingsPage, error) { + return client.SettingsPages(ctx, []core.SettingsContribution{{Manifest: manifest, Owner: core.PluginSettingsOwner{PluginID: "dev.lithe.fixture.settings", Version: "0.1.0"}, Enabled: true}}) + }, + }), Values{Theme: "dark"}) + d := openWindow(t, w, func(config *app.Config) { config.Height = 1100 }) + d.until("the plugin's pages", func() bool { return w.dynamic.loaded && len(w.dynamic.pages) > 0 }) + key := "" + for _, page := range w.dynamic.pages { + if page.Kind == "language" { + key = page.Key + } + } + if key == "" { + t.Fatalf("no language page in %+v", w.dynamic.pages) + } + w.selectSettingsPage(pageLanguages, key) + d.until("the English form", func() bool { return w.pluginSettings.loaded && d.text("Dialyzer") }) + form := w.pluginSettings + + language.Store(int32(i18n.Chinese)) + d.until("the Chinese form", func() bool { return form.loaded && d.text("Dialyzer 静态分析") }) + if got := source.loads(); len(got) != 2 || got[0] != i18n.English || got[1] != i18n.Chinese { + t.Fatalf("loads %v", got) + } + + // A draft on another page of the same plugin still belongs to this form. + checks := -1 + for index, row := range form.editor.Snapshot.State.Rows { + if row.Declaration.ID == "checks" { + checks = index + } + } + if checks < 0 { + t.Fatal("no checks row") + } + control := &form.controls[form.scope][checks] + baseline := append([]bool(nil), control.input.Checks...) + control.input.Checks = []bool{!baseline[0], baseline[1]} + if !form.hasDraft() { + t.Fatal("the test did not make a draft") + } + language.Store(int32(i18n.English)) + for range 3 { + w.inv.Invalidate() + d.pump() + } + // A reload would have started on the first of these paints and cleared loaded. + if !form.loaded || len(source.loads()) != 2 || !d.text("Dialyzer 静态分析") || control.input.Checks[0] == baseline[0] { + t.Fatalf("a language change replaced a draft: loaded=%v loads=%v", form.loaded, source.loads()) + } + control.input.Checks = baseline + d.until("the English form after the draft", func() bool { return form.loaded && d.text("Dialyzer") }) + if got := source.loads(); len(got) != 3 || got[2] != i18n.English { + t.Fatalf("loads %v", got) + } + + language.Store(int32(i18n.Chinese)) + d.until("the Chinese action", func() bool { return form.loaded && d.has("重建 PLT") }) + d.click("重建 PLT") + d.until("the confirmation", func() bool { return form.actionConfirmation != nil }) + if form.actionConfirmation.Title != "重建 PLT" { + t.Fatalf("confirmation title %q", form.actionConfirmation.Title) + } + w.inv.Invalidate() + d.pump() + if !d.textContaining("重建 PLT") || d.textContaining("Rebuild PLT") { + t.Fatal("the confirmation does not name the translated action") + } +} diff --git a/desktop/internal/settingswindow/plugin_settings_model.go b/desktop/internal/settingswindow/plugin_settings_model.go index 3420f9c69f..7e5f2e0a3b 100644 --- a/desktop/internal/settingswindow/plugin_settings_model.go +++ b/desktop/internal/settingswindow/plugin_settings_model.go @@ -10,6 +10,7 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginsettings" "github.com/vivaui/viva/ui" @@ -83,17 +84,23 @@ type pluginSettingsForm struct { loadEffect *ui.EffectState[pluginservice.SettingsEditor, int] opEffect *ui.EffectState[pluginSettingsResult, int] loadKey, opKey int - // mu guards what a run reads when it starts, loadID and op, and the cancel of the - // operation running: a run may start after the window thread asked for the next one. - mu sync.Mutex - loadID string - op pluginSettingsOp - cancelOp context.CancelFunc - running bool - id string - loaded bool - failed error - saved bool + // mu guards what a run reads when it starts, loadID, loadLanguage and op, and the + // cancel of the operation running: a run may start after the window thread asked for + // the next one. + mu sync.Mutex + loadID string + loadLanguage i18n.Language + op pluginSettingsOp + cancelOp context.CancelFunc + running bool + id string + loaded bool + failed error + saved bool + // language is the interface language the window shows; shown is the one the loaded + // editor's plugin text was translated for. They differ after a language change until + // the form is clean and idle and reloads. + language, shown i18n.Language // scope and both drafts are view state; switching scope does not lose edits. scope int editor pluginservice.SettingsEditor @@ -109,9 +116,9 @@ func newPluginSettingsForm(loader PluginSettingsLoader) *pluginSettingsForm { ctx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() p.mu.Lock() - id := p.loadID + id, language := p.loadID, p.loadLanguage p.mu.Unlock() - return loader.Load(ctx, id) + return loader.Load(ctx, id, language) }) p.opEffect = ui.NewEffect[pluginSettingsResult, int](p.runOp) } @@ -168,7 +175,7 @@ func (p *pluginSettingsForm) load(id string) { return } p.mu.Lock() - p.loadID = id + p.loadID, p.loadLanguage = id, p.language p.mu.Unlock() p.id, p.loaded, p.failed, p.saved = id, false, nil, false p.running = true @@ -216,6 +223,15 @@ func (p *pluginSettingsForm) applyOp(result pluginSettingsResult) { } plan := result.action.Plan if result.err == nil && plan.Kind == "confirmationRequired" { + // The plan carries the manifest's title; the dialog names the action the way + // its button does, in the editor's translation. No reload replaces the editor + // while an action runs, so it is the one the action was planned from. + for _, action := range p.editor.Snapshot.State.Actions { + if action.ID == plan.ActionID { + plan.Title = action.Title + break + } + } p.actionConfirmation = &plan p.confirmOpen = true } @@ -251,7 +267,9 @@ func (p *pluginSettingsForm) applyLoad(editor pluginservice.SettingsEditor, err if err != nil { return } - p.editor, p.loaded = editor, true + // Only the window thread writes loadLanguage, and a result of an earlier load is + // dropped before it gets here, so this is the language the editor was read in. + p.editor, p.loaded, p.shown = editor, true, p.loadLanguage p.applyScope(0) p.applyScope(1) p.layoutRows() @@ -446,6 +464,18 @@ func (p *pluginSettingsForm) sourceChanged() { } } +// follow keeps the plugin's own text in the window's language. A form that has a draft +// or a request running keeps its text, so a language change never discards an edit; it +// reloads once it is clean. The language check comes first, so a settled form costs one +// comparison per paint. +func (p *pluginSettingsForm) follow(language i18n.Language) { + p.language = language + if p.shown == language || !p.loaded || p.running || p.hasDraft() { + return + } + p.load(p.id) +} + // Leaving a surface dismisses transient dialogs, while retaining the drafts for the next // visit to this plugin. func (p *pluginSettingsForm) blur() { diff --git a/desktop/internal/settingswindow/plugin_settings_model_test.go b/desktop/internal/settingswindow/plugin_settings_model_test.go index b97607de72..f4fbf88c51 100644 --- a/desktop/internal/settingswindow/plugin_settings_model_test.go +++ b/desktop/internal/settingswindow/plugin_settings_model_test.go @@ -11,6 +11,7 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginsettings" ) @@ -136,15 +137,16 @@ func TestPluginSettingsInvalidIntegerDraftStaysUnparsedUntilCoreRejectsSave(t *t } type queuedSettingsLoad struct { - id string - ctx context.Context - release chan struct{} + id string + language i18n.Language + ctx context.Context + release chan struct{} } type queuedSettingsSource struct{ requests chan queuedSettingsLoad } -func (s queuedSettingsSource) Load(ctx context.Context, id string) (pluginservice.SettingsEditor, error) { +func (s queuedSettingsSource) Load(ctx context.Context, id string, language i18n.Language) (pluginservice.SettingsEditor, error) { release := make(chan struct{}) - s.requests <- queuedSettingsLoad{id: id, ctx: ctx, release: release} + s.requests <- queuedSettingsLoad{id: id, language: language, ctx: ctx, release: release} <-release // Model a native read completing just after cancellation. return pluginservice.SettingsEditor{Snapshot: pluginsettings.Snapshot{State: core.PluginSettingsState{PluginID: id}}}, nil } diff --git a/desktop/internal/settingswindow/plugin_settings_view.go b/desktop/internal/settingswindow/plugin_settings_view.go index d1342c44e1..c3f91c3b8f 100644 --- a/desktop/internal/settingswindow/plugin_settings_view.go +++ b/desktop/internal/settingswindow/plugin_settings_view.go @@ -51,10 +51,12 @@ func (w *window) pluginSettingsPanel(c ui.C, id string) { if p.loader == nil { return } + language := w.marketLanguage() if p.id != id { + p.language = language p.load(id) } - language := w.marketLanguage() + p.follow(language) ui.Column(c).FillWidth().Grow(1).Gap(10).Children(func() { ui.Row(c).FillWidth().Height(1).Background(w.pal.line) ui.Row(c).FillWidth().Gap(8).Items(ui.Center).Children(func() { diff --git a/desktop/internal/settingswindow/plugin_settings_view_test.go b/desktop/internal/settingswindow/plugin_settings_view_test.go index a429e0972d..820192f420 100644 --- a/desktop/internal/settingswindow/plugin_settings_view_test.go +++ b/desktop/internal/settingswindow/plugin_settings_view_test.go @@ -25,7 +25,7 @@ type settingsFormSource struct { workspace string } -func (s settingsFormSource) Load(ctx context.Context, _ string) (pluginservice.SettingsEditor, error) { +func (s settingsFormSource) Load(ctx context.Context, _ string, _ i18n.Language) (pluginservice.SettingsEditor, error) { snapshot, err := s.store.Load(ctx, s.manifest, s.workspace) return pluginservice.SettingsEditor{Snapshot: snapshot}, err } @@ -127,7 +127,7 @@ func TestPluginSettingsFormEditsOnlyOnExplicitSaveAndPreservesConflictDraft(t *t if w.pluginSettings.failed != nil { t.Fatal(w.pluginSettings.failed) } - actual, err := source.Load(ctx, "") + actual, err := source.Load(ctx, "", i18n.English) if err != nil { t.Fatal(err) } diff --git a/desktop/internal/settingswindow/settings_surfaces.go b/desktop/internal/settingswindow/settings_surfaces.go index 1e8bd6d326..fc1a936fd3 100644 --- a/desktop/internal/settingswindow/settings_surfaces.go +++ b/desktop/internal/settingswindow/settings_surfaces.go @@ -244,6 +244,7 @@ func (w *window) selectPluginForm(id string) bool { w.formLimitReported = false w.pluginSettings = form w.pluginForms[id] = form + form.language = w.marketLanguage() form.load(id) return true } diff --git a/desktop/internal/settingswindow/settings_surfaces_test.go b/desktop/internal/settingswindow/settings_surfaces_test.go index 3aea24c920..fc77373b66 100644 --- a/desktop/internal/settingswindow/settings_surfaces_test.go +++ b/desktop/internal/settingswindow/settings_surfaces_test.go @@ -159,7 +159,7 @@ type dynamicFormsSource struct { other json.RawMessage } -func (s dynamicFormsSource) Load(ctx context.Context, id string) (pluginservice.SettingsEditor, error) { +func (s dynamicFormsSource) Load(ctx context.Context, id string, _ i18n.Language) (pluginservice.SettingsEditor, error) { manifest := s.manifest if id == "dev.example.settings-other" { manifest = s.other diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 1a934e2eab..263f9ca55b 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -79,7 +79,7 @@ type Kernel interface { DecodeBuildTestResults(ctx context.Context, manifest json.RawMessage, buildSystemID string, request core.BuildTestResultsRequest) (core.BuildTestResults, error) ResolveBuildTestOutcome(ctx context.Context, termination core.BuildTestTermination, project, suite, caseName string, summary *core.BuildTestSummary) (core.BuildTestVerdict, error) InstantiateToolchainLaunch(context.Context, json.RawMessage, string, string, string, string, []string, []string) (core.ToolchainLaunch, error) - ReadPluginSettingsState(context.Context, json.RawMessage, *string, *string) (core.PluginSettingsState, error) + ReadPluginSettingsState(context.Context, json.RawMessage, *string, *string, *core.PluginSettingsLocalizationRequest) (core.PluginSettingsState, error) EditPluginSettings(context.Context, json.RawMessage, string, *string, []core.PluginSettingEdit) (core.PluginSettingsEditPlan, error) PlanPluginDebugAdapter(context.Context, json.RawMessage, string, core.PluginBackendDirectories) (core.PluginBackendPlan, error) PlanDebugExecutable(context.Context, json.RawMessage, string, string, string, map[string]json.RawMessage, map[string]json.RawMessage) (*core.DebugExecutablePlan, error) diff --git a/desktop/internal/workbench/build_tree_test.go b/desktop/internal/workbench/build_tree_test.go index ef09d9a625..351a796b42 100644 --- a/desktop/internal/workbench/build_tree_test.go +++ b/desktop/internal/workbench/build_tree_test.go @@ -216,7 +216,7 @@ type gatedModelKernel struct { release chan struct{} } -func (k *gatedModelKernel) ReadPluginSettingsState(context.Context, json.RawMessage, *string, *string) (core.PluginSettingsState, error) { +func (k *gatedModelKernel) ReadPluginSettingsState(context.Context, json.RawMessage, *string, *string, *core.PluginSettingsLocalizationRequest) (core.PluginSettingsState, error) { return core.PluginSettingsState{}, nil } diff --git a/desktop/internal/workbench/logevents_test.go b/desktop/internal/workbench/logevents_test.go index 032eebfee9..85edafe18f 100644 --- a/desktop/internal/workbench/logevents_test.go +++ b/desktop/internal/workbench/logevents_test.go @@ -77,6 +77,10 @@ func TestLogEventsMatchCatalog(t *testing.T) { {operationFailedLevel, operationFailedEvent, operationFailedFields("editor_preferences", failure)}, {operationFailedLevel, operationFailedEvent, operationFailedFields("keymap_schemes", failure)}, {operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_settings_surface", failure)}, + {operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_settings_load", failure)}, + {core.LevelWarn, pluginSettingsLoadRejectedEvent, pluginSettingsLoadRejected("localization_unreadable")}, + {core.LevelWarn, pluginSettingsLoadRejectedEvent, pluginSettingsLoadRejected("invalid_localization")}, + {core.LevelWarn, pluginSettingsLoadRejectedEvent, pluginSettingsLoadRejected("invalid_stored_values")}, {core.LevelInfo, "app.action.performed", map[string]any{"action": "settings.openLink", "surface": surfaceButton}}, } events := make([]core.LogEvent, len(cases)) diff --git a/desktop/internal/workbench/settings_plugin_actions_test.go b/desktop/internal/workbench/settings_plugin_actions_test.go index e2b7f96d24..ce2d8d826a 100644 --- a/desktop/internal/workbench/settings_plugin_actions_test.go +++ b/desktop/internal/workbench/settings_plugin_actions_test.go @@ -55,7 +55,7 @@ func TestSettingsActionConfirmsInvokesExistingProviderWithoutSaving(t *testing.T p := openTestsPanel(t, h, root) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - editor, err := h.app.plugins.LoadSettingsEditor(ctx, "dev.lithe.test.provider-tests", root) + editor, err := h.app.plugins.LoadSettingsEditor(ctx, "dev.lithe.test.provider-tests", root, "") if err != nil { t.Fatal(err) } diff --git a/desktop/internal/workbench/settings_plugins.go b/desktop/internal/workbench/settings_plugins.go index d4eea6ed38..fab434af68 100644 --- a/desktop/internal/workbench/settings_plugins.go +++ b/desktop/internal/workbench/settings_plugins.go @@ -7,6 +7,7 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginsettings" ) @@ -15,14 +16,22 @@ import ( // is an immutable publication from the workbench window, shared with toolchains. type pluginSettingsSources struct{ app *App } -func (s pluginSettingsSources) Load(ctx context.Context, id string) (editor pluginservice.SettingsEditor, err error) { +func (s pluginSettingsSources) Load(ctx context.Context, id string, language i18n.Language) (editor pluginservice.SettingsEditor, err error) { defer func() { (settingsToolchains{app: s.app}).recordFailure("plugin_settings_load", err) }() root := "" if current := s.app.toolchainRoot.Load(); current != nil { root = *current } - editor, err = s.app.plugins.LoadSettingsEditor(ctx, id, root) + editor, err = s.app.plugins.LoadSettingsEditor(ctx, id, root, language.Code()) if err == nil { + // A skipped translation falls back to the next candidate or to manifest + // text; the page still loads, so this is a degraded read, not a failure. + if len(editor.Snapshot.LocalizationReadFailures()) > 0 { + s.app.emit(core.LevelWarn, pluginSettingsLoadRejectedEvent, pluginSettingsLoadRejected("localization_unreadable")) + } + if localization := editor.Snapshot.State.Localization; localization != nil && len(localization.Rejected) > 0 { + s.app.emit(core.LevelWarn, pluginSettingsLoadRejectedEvent, pluginSettingsLoadRejected("invalid_localization")) + } invalid := false for _, value := range editor.Snapshot.State.Editors.Global { invalid = invalid || value.InvalidStored @@ -31,12 +40,22 @@ func (s pluginSettingsSources) Load(ctx context.Context, id string) (editor plug invalid = invalid || value.InvalidStored } if invalid { - s.app.emit(core.LevelWarn, "app.notification.operation_rejected", map[string]any{"operation": "plugin_settings_load", "reason": "invalid_stored_values"}) + s.app.emit(core.LevelWarn, pluginSettingsLoadRejectedEvent, pluginSettingsLoadRejected("invalid_stored_values")) } } return editor, err } +// pluginSettingsLoadRejectedEvent logs a plugin settings read that loaded but refused part of +// what it read: a stored value or a translation file of the package. +const pluginSettingsLoadRejectedEvent = "app.notification.operation_rejected" + +// pluginSettingsLoadRejected are the fields of that event; reason is localization_unreadable, +// invalid_localization or invalid_stored_values. +func pluginSettingsLoadRejected(reason string) map[string]any { + return map[string]any{"operation": "plugin_settings_load", "reason": reason} +} + func (s pluginSettingsSources) Save(ctx context.Context, editor pluginservice.SettingsEditor, scope string, edits []core.PluginSettingEdit) (result pluginsettings.SaveResult, err error) { defer func() { (settingsToolchains{app: s.app}).recordFailure("plugin_settings_save", err) }() check := func() error { diff --git a/desktop/internal/workbench/settings_publication_test.go b/desktop/internal/workbench/settings_publication_test.go index 08be0ad0ea..7c3d26b503 100644 --- a/desktop/internal/workbench/settings_publication_test.go +++ b/desktop/internal/workbench/settings_publication_test.go @@ -10,6 +10,7 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginstate" "github.com/1lck/Lithe-IDEA/desktop/internal/store" ) @@ -71,7 +72,7 @@ func TestSettingsPublicationReachesMatchingWindowsAndKeepsProjectLayers(t *testi t.Fatal(err) } source := pluginSettingsSources{app: windows[0].app} - editor, err := source.Load(ctx, id) + editor, err := source.Load(ctx, id, i18n.English) if err != nil { t.Fatal(err) } @@ -88,7 +89,7 @@ func TestSettingsPublicationReachesMatchingWindowsAndKeepsProjectLayers(t *testi t.Errorf("global window %d loaded=%v", index, got) } } - b, err := windows[2].app.plugins.LoadSettingsEditor(ctx, id, rootB) + b, err := windows[2].app.plugins.LoadSettingsEditor(ctx, id, rootB, "") if err != nil { t.Fatal(err) } @@ -98,7 +99,7 @@ func TestSettingsPublicationReachesMatchingWindowsAndKeepsProjectLayers(t *testi for _, h := range windows { h.app.project.build.instances[0].modelLoaded = true } - editor, err = source.Load(ctx, id) + editor, err = source.Load(ctx, id, i18n.English) if err != nil { t.Fatal(err) } diff --git a/desktop/internal/workbench/startup_test.go b/desktop/internal/workbench/startup_test.go index 47205318e4..75a6cf088c 100644 --- a/desktop/internal/workbench/startup_test.go +++ b/desktop/internal/workbench/startup_test.go @@ -10,6 +10,7 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" "github.com/1lck/Lithe-IDEA/desktop/internal/store" ) @@ -61,7 +62,7 @@ func TestDesktopStartupMakesInstalledPluginSettingsReachable(t *testing.T) { } source := pluginSettingsSources{app: h.app} - editor, err := source.Load(ctx, "dev.example.settings") + editor, err := source.Load(ctx, "dev.example.settings", i18n.English) if err != nil { t.Fatal(err) } @@ -80,3 +81,67 @@ func TestDesktopStartupMakesInstalledPluginSettingsReachable(t *testing.T) { t.Fatalf("startup changed the installed package: %v", err) } } + +// A package translation that cannot be read, and one Core refuses, each leave one warning while +// the page still loads in manifest text; a language without a translation file logs nothing. +func TestPluginSettingsLoadLogsSkippedAndRefusedTranslations(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + manifest, err := os.ReadFile(contractfixture.Path("fixtures/settings/settings.plugin.json")) + if err != nil { + t.Fatal(err) + } + preferences, plugins := t.TempDir(), t.TempDir() + directory := filepath.Join(plugins, "dev.lithe.fixture.settings", "0.1.0") + // l10n/zh-Hans.json is a directory, so the adapter cannot read it; l10n/zh.json is not JSON. + if err := os.MkdirAll(filepath.Join(directory, "l10n", "zh-Hans.json"), 0o700); err != nil { + t.Fatal(err) + } + for name, data := range map[string][]byte{pluginpkg.ManifestFile: manifest, "l10n/zh.json": []byte("settings: {}")} { + if err := os.WriteFile(filepath.Join(directory, filepath.FromSlash(name)), data, 0o600); err != nil { + t.Fatal(err) + } + } + if err := os.WriteFile(filepath.Join(preferences, settingsFile), []byte(`{"theme":"dark"}`), 0o600); err != nil { + t.Fatal(err) + } + options := DesktopOptions(core.NewClient(), store.At(preferences), "test") + options.PluginRoot = plugins + options.Languages = []string{"en"} + options.AIKernel = nil + h := newHarnessWithOptions(t, options) + log := &treeRecordingLog{} + h.app.logSink = log + t.Cleanup(func() { h.app.logSink = nil }) + warnings := func() []string { + log.mu.Lock() + defer log.mu.Unlock() + var reasons []string + for _, event := range log.events { + if event.Fields["operation"] == "plugin_settings_load" { + if event.Level != core.LevelWarn || event.Event != pluginSettingsLoadRejectedEvent { + t.Fatalf("plugin settings load logged %s %s %v", event.Level, event.Event, event.Fields) + } + reasons = append(reasons, event.Fields["reason"].(string)) + } + } + return reasons + } + source := pluginSettingsSources{app: h.app} + editor, err := source.Load(ctx, "dev.lithe.fixture.settings", i18n.Chinese) + if err != nil { + t.Fatal(err) + } + if editor.Snapshot.State.Localization == nil || editor.Snapshot.State.Localization.Applied != nil { + t.Fatalf("a translation was applied: %+v", editor.Snapshot.State.Localization) + } + if got := warnings(); len(got) != 2 || got[0] != "localization_unreadable" || got[1] != "invalid_localization" { + t.Fatalf("warnings %v", got) + } + if _, err := source.Load(ctx, "dev.lithe.fixture.settings", i18n.English); err != nil { + t.Fatal(err) + } + if got := warnings(); len(got) != 2 { + t.Fatalf("a load without a translation file logged %v", got) + } +} diff --git a/desktop/internal/workbench/toolchains_test.go b/desktop/internal/workbench/toolchains_test.go index 0616d88f50..866df6b866 100644 --- a/desktop/internal/workbench/toolchains_test.go +++ b/desktop/internal/workbench/toolchains_test.go @@ -22,7 +22,7 @@ func (k *invocationKernel) PlanBuildInvocation(context.Context, json.RawMessage, } // These candidate-execution tests inject the invocation independently of a manifest. -func (k *invocationKernel) ReadPluginSettingsState(context.Context, json.RawMessage, *string, *string) (core.PluginSettingsState, error) { +func (k *invocationKernel) ReadPluginSettingsState(context.Context, json.RawMessage, *string, *string, *core.PluginSettingsLocalizationRequest) (core.PluginSettingsState, error) { return core.PluginSettingsState{}, nil } diff --git a/docs/development/macos-plugin-api-plan.md b/docs/development/macos-plugin-api-plan.md index aa90f346fd..ac41ab3064 100644 --- a/docs/development/macos-plugin-api-plan.md +++ b/docs/development/macos-plugin-api-plan.md @@ -59,7 +59,7 @@ Windows 不在本轮,平台矩阵的 partial/pending 保持真实。 | API-34 | 未做 | 插件公共 IDE/AI/MCP 授权面未开放;独立 broker 不能直接转授 | | API-35 | 第一阶段进行中 | 第一阶段是 Java 拆分所需的 Core 中转插件函数调用(插件 1 → Core → 插件 2,C-IMPORT,进行中,不是安装依赖);依赖/导出安装闭包、版本求解、远程 Provider 剩余接续未完成 | | API-36 | 未做 | WASM/WASI 非本轮前置,未引入运行时 | -| API-37 | 部分完成 | getCapabilities 提供协议/方法/预算/后端执行位置;语言包与环境/主题事件未做;Java 拆分:界面语言走本项的环境信息,不在 workspace context 里加 locale | +| API-37 | 部分完成 | getCapabilities 提供协议/方法/预算/后端执行位置;插件设置文字的包内语言文件 `l10n/<语言>.json` 已做(`pluginAPIVersion` 0 补充,Core #36;桌面端只读地从已安装包取文件,按界面语言重读且保留草稿);其它插件文字的语言包与环境/主题事件未做;Java 拆分:界面语言走本项的环境信息,不在 workspace context 里加 locale | | API-38 | 未做 | 通用受管 fetch/download 未开放 | | API-39 | 未做 | 通用 authentication session/provider 未开放 | | API-40 | 部分完成 | 上下文携带 local/remote;新文件/编辑器服务对 remote 明确拒绝,非远程执行实现 | @@ -256,7 +256,7 @@ Mac 当前声明的能力版本为:`backend:1`、`buildModelInputs:1`、`build | ID / 方向 | 候选能力与现状/所有者 | 权限、作用域与验收 | 阶段 | | --- | --- | --- | --- | -| API-37 H/E | `environment.getInfo`、插件语言包/`l10n`、语言/主题变化;已有应用语言和主题 owner [S16/S19] | 只返回必要的产品/能力/界面语言信息,不导出进程环境、HOME 或账号;宿主文案走共享 i18n,插件文案用自己的包内语言资源并明确回退 | M1:最低能力信息;后续:完整语言包;Java 拆分:沿用本项,不加 locale 字段 | +| API-37 H/E | `environment.getInfo`、插件语言包/`l10n`、语言/主题变化;已有应用语言和主题 owner [S16/S19] | 只返回必要的产品/能力/界面语言信息,不导出进程环境、HOME 或账号;宿主文案走共享 i18n,插件文案用自己的包内语言资源并明确回退 | M1:最低能力信息;已做:插件设置的包内语言文件;后续:其它插件文字的语言包与切语言事件;Java 拆分:沿用本项,不加 locale 字段 | | API-38 H | 可选受管 `network.fetch/download`;现有 HTTP adapter 服务具体业务,不是通用插件 API [S19] | 单独声明网络目标与授权;限制重定向、协议、内网目标、响应大小和超时,不转授宿主 cookie/代理凭据。下载只到平台可写临时目录,校验后显式交付,不能自动执行 | 后续 | | API-39 H/P/E | 可选 `authentication.getSession/registerProvider` 与登录变化;已有 GitHub/Agent 专属账号流程 [S19] | 凭据存储不是“读取 IDE 账号”权限;须按插件、服务、账号、scope 显式授权,撤销和注销可见,复用系统浏览器/Keychain,不向任意插件提供宿主 GitHub 或 Agent token | 后续,独立安全评审 | diff --git a/shared/platform-feature-matrix/features/declarative-plugin-settings.json b/shared/platform-feature-matrix/features/declarative-plugin-settings.json index 9fa8c6f6fc..ae01bb243e 100644 --- a/shared/platform-feature-matrix/features/declarative-plugin-settings.json +++ b/shared/platform-feature-matrix/features/declarative-plugin-settings.json @@ -2,7 +2,7 @@ "id": "declarative-plugin-settings", "area": "插件", "group": "插件管理", - "capability": "声明式插件通过 Core 校验的设置声明提供整数、枚举、布尔、多选、文本、文件和目录设置,支持全局/项目继承、真实来源保存、通用界面、页面/动作注册及 restart/immediate/reload/nextRun 生效;实际启动与运行消费者必须读取同一来源。 声明动作经显式确认、安装/工作区身份复查与 Core 同工作区函数会话选择后调用;支持取消和完成状态,保留未保存草稿。 已启用插件动态贡献语言/构建系统页,同一应用内窗口按原生目录身份接收全局/项目保存通知,独立保留项目覆盖值与未保存草稿。", + "capability": "声明式插件通过 Core 校验的设置声明提供整数、枚举、布尔、多选、文本、文件和目录设置,支持全局/项目继承、真实来源保存、通用界面、页面/动作注册及 restart/immediate/reload/nextRun 生效;实际启动与运行消费者必须读取同一来源。 声明动作经显式确认、安装/工作区身份复查与 Core 同工作区函数会话选择后调用;支持取消和完成状态,保留未保存草稿。 已启用插件动态贡献语言/构建系统页,同一应用内窗口按原生目录身份接收全局/项目保存通知,独立保留项目覆盖值与未保存草稿。 插件包可自带 l10n/<语言>.json 翻译设置文字,Core 按界面语言挑选文件并逐条回退到清单原文;切换界面语言后重读文字,但保留未保存草稿。", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", @@ -37,7 +37,12 @@ "desktop/internal/workbench/settings_publication.go", "desktop/internal/workbench/settings_publication_test.go", "desktop/internal/settingswindow/installed_view.go", - "desktop/internal/settingswindow/installed_view_test.go" + "desktop/internal/settingswindow/installed_view_test.go", + "desktop/internal/pluginsettings/localization_test.go", + "desktop/internal/settingswindow/plugin_settings_language_test.go", + "desktop/internal/workbench/settings_plugins.go", + "desktop/internal/workbench/startup_test.go", + ".agents/notes/implemented/architecture/2026-10-21-plugin-settings-surfaces.md" ] }, "windows": { @@ -74,11 +79,16 @@ "desktop/internal/workbench/settings_publication.go", "desktop/internal/workbench/settings_publication_test.go", "desktop/internal/settingswindow/installed_view.go", - "desktop/internal/settingswindow/installed_view_test.go" + "desktop/internal/settingswindow/installed_view_test.go", + "desktop/internal/pluginsettings/localization_test.go", + "desktop/internal/settingswindow/plugin_settings_language_test.go", + "desktop/internal/workbench/settings_plugins.go", + "desktop/internal/workbench/startup_test.go", + ".agents/notes/implemented/architecture/2026-10-21-plugin-settings-surfaces.md" ] }, "owner": "Plugin Platform", - "verification": "Viva:共享 settings-documents fixture 经真实 Core C ABI 验证类型、作用层、整批拒绝及文档保留;原生来源覆盖权限/元数据、冲突、取消、捕获来源回读、提交后回读失败。Build/Debug 读取实际文件,明确失效路径不能静默回退;Build 全局专属程序不能被项目文件替换。LSP 启动同时传全局/项目设置、初始化选项与 Core 展开的 workspaceConfiguration。真实协议子进程在同一 Core 会话接收更新通知并重新拉取值;保存来源后服务层回读、展开并更新现有会话,损坏来源不推空配置。macOS 有定向测试与真实子进程证据;此前设置动作节点已在 Lithe-dev 通过完整消费者与定向 race;本节点结果按独立报告记录。已安装本地目录独立于商店网络,Core 绑定注册 ID/版本;原生快照拒绝安装替换。七种控件与全局/项目草稿已接线,macOS 无头驱动验证原生文本输入、明确保存回读、冲突保留、重新加载;共享模型验证七种类型及非法整数原文。保存后的即时通知与所属插件模型刷新已接线,旧模型回包不会覆盖待刷新状态,运行任务及无关模型保持。动作原生窗体、重启与完整生效状态、目标平台原生 UI 及正式市场准入尚未验收,宿主仍不声明 settings 2。 动作节点增加:实际按钮确认/取消,草稿不保存;真实提供方函数成功与取消、原进程复用、会话关闭后不可用;拒绝不同工作区/版本/未注册函数,显示版本不可替代私有身份,项目同路径重开不能接受过期动作。 动态页面节点验证 Core 启用过滤、多个贡献者、动作独立页面、搜索保留父节点、作用域/版本通知规则;Viva 验证页面/动作筛选与切页草稿保留;多工作台驱动验证同偏好目录全局通知、同项目通知、项目覆盖隔离、私有身份及旧生命周期拒绝。同一应用进程内通知不代表独立进程实时同步,也不新增多工作台创建入口。 设置列表填满表单标题下的高度、最少 160 像素,窗口放不下时滚动整页而不截断;Viva 无头驱动在最小窗口、800、1000 高度下验证语言页与已安装插件“设置”标签页的列表随窗口等量增长、底部与确定按钮间距不变、最后一项完整显示。", + "verification": "Viva:共享 settings-documents fixture 经真实 Core C ABI 验证类型、作用层、整批拒绝及文档保留;原生来源覆盖权限/元数据、冲突、取消、捕获来源回读、提交后回读失败。Build/Debug 读取实际文件,明确失效路径不能静默回退;Build 全局专属程序不能被项目文件替换。LSP 启动同时传全局/项目设置、初始化选项与 Core 展开的 workspaceConfiguration。真实协议子进程在同一 Core 会话接收更新通知并重新拉取值;保存来源后服务层回读、展开并更新现有会话,损坏来源不推空配置。macOS 有定向测试与真实子进程证据;此前设置动作节点已在 Lithe-dev 通过完整消费者与定向 race;本节点结果按独立报告记录。已安装本地目录独立于商店网络,Core 绑定注册 ID/版本;原生快照拒绝安装替换。七种控件与全局/项目草稿已接线,macOS 无头驱动验证原生文本输入、明确保存回读、冲突保留、重新加载;共享模型验证七种类型及非法整数原文。保存后的即时通知与所属插件模型刷新已接线,旧模型回包不会覆盖待刷新状态,运行任务及无关模型保持。动作原生窗体、重启与完整生效状态、目标平台原生 UI 及正式市场准入尚未验收,宿主仍不声明 settings 2。 动作节点增加:实际按钮确认/取消,草稿不保存;真实提供方函数成功与取消、原进程复用、会话关闭后不可用;拒绝不同工作区/版本/未注册函数,显示版本不可替代私有身份,项目同路径重开不能接受过期动作。 动态页面节点验证 Core 启用过滤、多个贡献者、动作独立页面、搜索保留父节点、作用域/版本通知规则;Viva 验证页面/动作筛选与切页草稿保留;多工作台驱动验证同偏好目录全局通知、同项目通知、项目覆盖隔离、私有身份及旧生命周期拒绝。同一应用进程内通知不代表独立进程实时同步,也不新增多工作台创建入口。 设置列表填满表单标题下的高度、最少 160 像素,窗口放不下时滚动整页而不截断;Viva 无头驱动在最小窗口、800、1000 高度下验证语言页与已安装插件“设置”标签页的列表随窗口等量增长、底部与确定按钮间距不变、最后一项完整显示。 插件语言文件:契约 localization-cases 的 13 个用例经真实 Core 逐条比对 applied/rejected;保存回读保留译文;从已安装包读取前后,文件清单与字节不变;Viva 无头驱动验证切换界面语言、有草稿时不重读、确认弹窗用译后的按钮标题;读不了或被拒绝的语言文件各记一条 WARN。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { @@ -110,5 +120,5 @@ "verificationStatus": "pending" } }, - "notes": "partial 包含原生双层存储、运行消费、离线目录、七类控件、声明动作、动态页面及同一应用内跨窗口通知。语言状态卡、完整 settings v2、独立进程同步及原生产品验收仍 pending;宿主现已声明 settings 2。 Viva 2026-11-14:设置页每项是标题行(标题、ⓘ 说明、重置)加控件行,开关不再重复标题,标题只作无障碍名称;去掉每行常驻的“继承值”说明,作用范围的说明收进范围选择旁的 ⓘ;无效值和仅全局可改两条状态提示保留;自动化:TestPluginSettingsFormEditsOnlyOnExplicitSaveAndPreservesConflictDraft,截图场景 TestVisualPluginSettingsForm。" + "notes": "partial 包含原生双层存储、运行消费、离线目录、七类控件、声明动作、动态页面及同一应用内跨窗口通知。语言状态卡、完整 settings v2、独立进程同步及原生产品验收仍 pending;宿主现已声明 settings 2。 Viva 2026-11-14:设置页每项是标题行(标题、ⓘ 说明、重置)加控件行,开关不再重复标题,标题只作无障碍名称;去掉每行常驻的“继承值”说明,作用范围的说明收进范围选择旁的 ⓘ;无效值和仅全局可改两条状态提示保留;自动化:TestPluginSettingsFormEditsOnlyOnExplicitSaveAndPreservesConflictDraft,截图场景 TestVisualPluginSettingsForm。 Viva 2026-11-14:插件设置文字由包内 l10n/<语言>.json 翻译(API-37)。宿主经 configfile 从已安装插件目录只读地取文件,由 Core 选候选并逐条回退。自动化:TestPresentedLoadFollowsContractLocalizationCases、TestInstalledSettingsEditorTranslatesFromThePackageWithoutWritingIt、TestPluginSettingsTextFollowsTheWindowLanguageWithoutDiscardingDrafts、TestPluginSettingsLoadLogsSkippedAndRefusedTranslations;目标平台真机界面验收仍 pending。" } From dece8e872e9562c990e840ecedc56f5cb9ffc4fd Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 14 Nov 2026 17:14:48 +0800 Subject: [PATCH 2/2] =?UTF-8?q?fix(scripts):=20i18n=20=E7=94=9F=E6=88=90?= =?UTF-8?q?=E5=99=A8=E6=94=B9=E7=94=A8=E4=B8=B4=E6=97=B6=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E8=B0=83=E7=94=A8=20gofmt=20=E5=B9=B6=E8=AE=BE=E8=B6=85?= =?UTF-8?q?=E6=97=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 生成器原来用 spawnSync 把约 450 KB 的桌面词条源码从 stdin 喂给 gofmt。 在 macOS(Node 24.14.0、Go 1.27.4)上,gofmt 偶尔收不到输入结束,会 一直等待:800 次里卡住 2 次,换成 cat 或改用文件参数则不会出现。 spawnSync 还会阻塞事件循环,test-i18n.mjs 的超时也无法终止它。 现在把源码写进系统临时目录下的私有目录,以文件参数异步调用 gofmt, 超时 10 秒,结束后删除该目录。临时文件不在仓库里,--check 仍不改 仓库文件,生成结果逐字节不变。 --- scripts/i18n/generate-i18n.mjs | 40 +++++++++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/scripts/i18n/generate-i18n.mjs b/scripts/i18n/generate-i18n.mjs index 7d06f55e23..6dba4c8f5c 100644 --- a/scripts/i18n/generate-i18n.mjs +++ b/scripts/i18n/generate-i18n.mjs @@ -1,18 +1,50 @@ #!/usr/bin/env node // Build-time only. Note: .agents/notes/implemented/architecture/2026-10-23-shared-i18n-generation.md -import { readFile, writeFile, mkdir, readdir, access } from "node:fs/promises"; +import { readFile, writeFile, mkdir, mkdtemp, readdir, access, rm } from "node:fs/promises"; +import os from "node:os"; import path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; -import { spawnSync } from "node:child_process"; +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; export const ROOT = path.dirname(path.dirname(path.dirname(fileURLToPath(import.meta.url)))); const PLATFORMS = ["macos", "windows", "desktop"]; const BEGIN = "/* BEGIN GENERATED SHARED I18N — DO NOT EDIT */"; const END = "/* END GENERATED SHARED I18N */"; const HEADER = "// Generated by scripts/i18n/generate-i18n.mjs. Edit shared/i18n instead.\n"; +// gofmt formats the desktop catalog (about 450 KB) in well under a second. +const GOFMT_TIMEOUT_MS = 10_000; +const GOFMT_MAX_OUTPUT_BYTES = 64 * 1024 * 1024; +const execFileAsync = promisify(execFile); const fail = (message) => { throw new Error(`i18n: ${message}`); }; + +// gofmt reads the source from a file in a private temporary directory, not from stdin. Fed +// through stdin by Node, gofmt on macOS occasionally never receives end of input and waits +// forever, and a synchronous spawn also stops the test runner from enforcing its timeout. +// The directory is outside the repository, so --check still leaves repository files untouched. +async function gofmt(source) { + const directory = await mkdtemp(path.join(os.tmpdir(), "lithe-i18n-gofmt-")); + try { + const file = path.join(directory, "shared.generated.go"); + await writeFile(file, source); + const { stdout } = await execFileAsync("gofmt", [file], { + encoding: "utf8", + timeout: GOFMT_TIMEOUT_MS, + maxBuffer: GOFMT_MAX_OUTPUT_BYTES, + windowsHide: true, + }); + return stdout; + } catch (error) { + const reason = error.killed + ? `no result within ${GOFMT_TIMEOUT_MS} ms` + : error.stderr?.trim() || error.message; + fail(`gofmt failed: ${reason}`); + } finally { + await rm(directory, { recursive: true, force: true }); + } +} const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value); const own = (object, key) => Object.hasOwn(object, key); function fields(value, allowed, label) { @@ -468,9 +500,7 @@ export async function planGeneration(root = ROOT) { return `\t${JSON.stringify(locale.id)}: {\n${entries}\n\t},`; }).join("\n"); const source = `// Code generated by scripts/i18n/generate-i18n.mjs; DO NOT EDIT.\npackage i18n\n\nvar sharedCatalogs = map[string]map[string]string{\n${mappings}\n}\n`; - const formatted = spawnSync("gofmt", [], { input: source, encoding: "utf8" }); - if (formatted.error || formatted.status !== 0) fail(`gofmt failed: ${formatted.error?.message ?? formatted.stderr}`); - outputs.set("desktop/internal/i18n/shared.generated.go", formatted.stdout); + outputs.set("desktop/internal/i18n/shared.generated.go", await gofmt(source)); } return { outputs, contract }; }