diff --git a/.agents/notes/implemented/feature/2026-10-15-macos-settings-hierarchy.md b/.agents/notes/implemented/feature/2026-10-15-macos-settings-hierarchy.md index e1f4e0bc1..ea975fa60 100644 --- a/.agents/notes/implemented/feature/2026-10-15-macos-settings-hierarchy.md +++ b/.agents/notes/implemented/feature/2026-10-15-macos-settings-hierarchy.md @@ -19,7 +19,7 @@ | 外观与行为 | 应用本身的外观、编辑器显示与输入、快捷键,以及应用自身网络请求的代理设置 | | 插件 | 插件的安装、启用和插件自带的选项;一级页面,不属于任何分组 | | 版本控制 | Git、SVN 等版本控制系统的配置 | -| 构建、执行、部署 | 分组本身是目录页;固定子页“工具链”(插件声明的全部工具,包括项目 JDK)、“调试器”(单步过滤等调试设置)和“控制台”(程序输出编码);插件声明的构建工具页、编译器页按种类排在后面,以及运行配置、服务运行和框架、构建工具注入的配置 | +| 构建、执行、部署 | 分组本身是目录页;固定子页“工具链”(插件声明的全部工具,包括项目 JDK)、“调试器”(单步过滤等调试设置)和“控制台”(程序输出编码)和“可信位置”(本机可信文件夹列表,与工具链共用偏好目录的 toolchains/global.json,2026-11-21 由 #2207 加入);插件声明的构建工具页、编译器页按种类排在后面,以及运行配置、服务运行和框架、构建工具注入的配置 | | 语言与框架 | 没有固定子页;插件声明的语言页、框架页(语言服务开关、Spring Boot 等框架配置)排在下面,有子页时它成为分组,分组本身是目录页 | | 工具 | 终端、搜索(搜索和替换文件大小预算)等通用工具;插件带来的专用工具可以放进对应工具页。日志与诊断不属于设置,它是独立的日志窗口 | | AI | 与 AI 有关的全部配置:MCP、Skill、全局指令、AI 提交信息、Agents、AI 服务商 | diff --git a/.agents/notes/implemented/feature/2026-11-19-workspace-trust-and-safe-mode.md b/.agents/notes/implemented/feature/2026-11-19-workspace-trust-and-safe-mode.md index a1732f056..a12f726f1 100644 --- a/.agents/notes/implemented/feature/2026-11-19-workspace-trust-and-safe-mode.md +++ b/.agents/notes/implemented/feature/2026-11-19-workspace-trust-and-safe-mode.md @@ -17,6 +17,7 @@ Maven 这类命令来源的模型会运行 `mvn`,pom 里的扩展和插件就 - **先问再打开。** `openProjectHere` 先读信任(`toolchain.ReadWorkspaceTrust`),再决定直接打开、以安全模式打开或提问;选“不打开”时当前项目原样保留,新开的项目页签直接关掉。“以安全模式预览”记成不信任,下次打开不再问,和 IDEA 的 `setProjectTrusted(false)` 相同。 - **安全模式下的动作先问。** `startRun`、`runBuildTask`、`startTests`、运行当前文件和重新加载模型前,安全模式会弹出“信任项目?/ 保持安全模式”。信任保存成功后才执行原动作;保存失败按未信任处理。自动加载的模型不运行,构建窗口在模型位置显示安全模式说明。 - **设置页和对话框是同一份记录。** 构建设置里撤销或授予工作区信任后,工作台重新读取信任并应用;离开安全模式时重新加载被跳过的模型和失败的语言服务器。 +- **可信位置有自己的设置页(#2207)。** 设置 › 构建、执行、部署 › 可信位置列出 Core 读出的 `trustedLocations`。增删都是草稿:每项改动单独交给 Core 的 `toolchains.editCatalog`(字段 `trustedLocations`)预演,页面显示 Core 算出的结果;Core 拒绝根目录(`plugin.toolchain.rootLocation`)和超过 256 项(`plugin.toolchain.trustListFull`),拒绝只丢掉这一项改动。“撤销修改”去掉该文件夹的全部改动,而不是追加一项反向改动,否则恢复的文件夹会跑到列表末尾。底栏应用时先写工具链、再写可信位置;两边共用偏好目录的 `toolchains/global.json`,任一方写入后把另一方读到的内容标记为过期,过期的列表在写入前先重新读取,改动相互抵消时不写文件。写入成功后工作台重试失败的语言服务器并重新判定当前项目的信任。 ## 考虑过的备选方案 @@ -28,16 +29,18 @@ Maven 这类命令来源的模型会运行 `mvn`,pom 里的扩展和插件就 ## 后果 - 测试 harness 默认把所有工作区当作信任(`Options.trustEveryWorkspace`,相当于 IDEA 单元测试模式关闭信任检查);测试信任流程的用例要显式关掉。 -- 语言服务器和 Git 在安全模式下仍照常启动(#2208),可信位置也还没有独立的设置页(#2207)。 +- 安全模式下不启动会运行项目代码的语言服务器和 Git 由 #2208 处理;远程工作区的可信条目(#2231 的 S04)还没有界面,等远程连接界面一起做。 - 通过 IDE API 发起的构建任务在安全模式下会被拒绝,同时提示用户信任。 ## 验证 - `desktop/internal/workbench/workspace_trust_test.go`:信任后打开并记住、勾选父文件夹后同级项目也被信任、不打开不留下任何状态、安全模式不加载模型且动作先问、提示条信任后消失。 - Core 的 `rust/crates/toolchain` 和 `rust/crates/build` 测试,以及 `build-plans.json`、`toolchain-global-catalog.json` 两份 fixture 覆盖状态判定和计划拒绝。 +- `desktop/internal/toolchain/trusted_locations_test.go`(真实 Core):预演不写文件、保存后嵌套项目被信任、过期列表写入被拒、相互抵消的改动不写文件、根目录被拒并指出是哪一项。`desktop/internal/settingswindow/trusted_locations_view_test.go`:草稿标记与撤销、拒绝只丢一项、应用前重读过期列表、写入后回读失败时重新读取。截图见 `docs/assets/trusted-locations/`。 ```bash scripts/desktop/desktop-go.sh test ./internal/workbench/ -run 'TestTrusting|TestDontOpen|TestSafeMode' +scripts/desktop/desktop-go.sh test ./internal/toolchain ./internal/settingswindow -run 'TrustedLocations' ``` ## 适用范围 diff --git a/desktop/internal/core/toolchain_catalog.go b/desktop/internal/core/toolchain_catalog.go index 63662ed3a..7ebb8ebe9 100644 --- a/desktop/internal/core/toolchain_catalog.go +++ b/desktop/internal/core/toolchain_catalog.go @@ -5,10 +5,15 @@ import ( ) // ToolchainCatalog contains registrations and workspace trust owned by this machine, independent of project pins. +// DistrustedWorkspaces are the workspaces the user chose to keep in safe mode, and +// TrustedLocations the folders whose every workspace is trusted unless distrusted itself; Core +// normalizes both for the platform and never lists a filesystem root as a location. type ToolchainCatalog struct { - Version int `json:"version"` - Tools map[string]ToolchainCatalogEntry `json:"tools"` - TrustedWorkspaces []string `json:"trustedWorkspaces,omitempty"` + Version int `json:"version"` + Tools map[string]ToolchainCatalogEntry `json:"tools"` + TrustedWorkspaces []string `json:"trustedWorkspaces,omitempty"` + DistrustedWorkspaces []string `json:"distrustedWorkspaces,omitempty"` + TrustedLocations []string `json:"trustedLocations,omitempty"` } type ToolchainCatalogEntry struct { @@ -91,3 +96,22 @@ func (c *Client) EditToolchainWorkspaceTrust(ctx context.Context, document *stri WorkspaceTrust ToolchainWorkspaceTrustEdit `json:"workspaceTrust"` }{document, platform, trust}) } + +// ToolchainTrustedLocationsEdit adds folders to the trusted locations and removes others. Core +// matches folders by the platform's path identity and refuses a filesystem root +// (plugin.toolchain.rootLocation), a folder both added and removed (invalidDocument) and a +// list past its bound (plugin.toolchain.trustListFull). +type ToolchainTrustedLocationsEdit struct { + Add []string `json:"add,omitempty"` + Remove []string `json:"remove,omitempty"` +} + +// EditToolchainTrustedLocations applies edit to document and returns the result. It writes +// nothing: the caller publishes the document against the bytes it read. +func (c *Client) EditToolchainTrustedLocations(ctx context.Context, document *string, platform string, edit ToolchainTrustedLocationsEdit) (ToolchainCatalogPublication, error) { + return settingsSurfaceResult[ToolchainCatalogPublication](ctx, c, "toolchains.editCatalog", "edit", struct { + Document *string `json:"document"` + Platform string `json:"platform"` + TrustedLocations ToolchainTrustedLocationsEdit `json:"trustedLocations"` + }{document, platform, edit}) +} diff --git a/desktop/internal/i18n/messages.go b/desktop/internal/i18n/messages.go index 6c96b4f34..6756429f2 100644 --- a/desktop/internal/i18n/messages.go +++ b/desktop/internal/i18n/messages.go @@ -578,6 +578,7 @@ type SettingsMessages struct { Toolchains string Debuggers string Console string + TrustedLocations string Languages string Tools string SearchPage string diff --git a/desktop/internal/i18n/settings_messages.go b/desktop/internal/i18n/settings_messages.go index 56042d0dc..a042223d3 100644 --- a/desktop/internal/i18n/settings_messages.go +++ b/desktop/internal/i18n/settings_messages.go @@ -20,6 +20,7 @@ func settingsMessages(language Language) SettingsMessages { Toolchains: Shared(language, "desktop.toolchains.title"), Debuggers: Shared(language, "desktop.buildSettings.debuggers"), Console: Shared(language, "desktop.consoleSettings.title"), + TrustedLocations: Shared(language, "desktop.trustedLocations.title"), Languages: Shared(language, "settings.groups.languages"), Tools: Shared(language, "settings.groups.tools"), SearchPage: Shared(language, "desktop.search.settings.title"), diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index 228f9d18f..5036b9e01 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -2324,6 +2324,21 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.trust.title": "Trust Project?", "desktop.trust.trustProject": "Trust Project", "desktop.trust.vcsSafeMode": "Safe mode does not run version control, because the working copy's configuration can name programs it runs. Trust the project to use it.", + "desktop.trustedLocations.add": "Add Folder…", + "desktop.trustedLocations.chooseFolder": "Choose a Folder to Trust", + "desktop.trustedLocations.directory": "Trusted folders: {count}", + "desktop.trustedLocations.directoryNone": "No trusted folders; untrusted projects ask before opening", + "desktop.trustedLocations.empty": "No trusted locations. Lithe asks before opening each project you haven't trusted.", + "desktop.trustedLocations.folders": "Trusted Folders", + "desktop.trustedLocations.foldersHelp": "Projects anywhere inside these folders open trusted without asking, except the ones you chose to keep in safe mode. Changes take effect when you click Apply or OK.", + "desktop.trustedLocations.keywords": "trust trusted safe mode folder location workspace project", + "desktop.trustedLocations.listFull": "This trust list is full (256 entries). Remove one before adding another.", + "desktop.trustedLocations.pendingAdd": "To add", + "desktop.trustedLocations.pendingRemove": "To remove", + "desktop.trustedLocations.remove": "Stop Trusting This Folder", + "desktop.trustedLocations.rootLocation": "A disk or filesystem root cannot be a trusted location: it would trust every project on that disk.", + "desktop.trustedLocations.target": "trusted locations", + "desktop.trustedLocations.title": "Trusted Locations", "desktop.updates.arrow.available": "Lithe {version} is available. Click to see what changed", "desktop.updates.arrow.downloading": "Downloading Lithe {version}… {percent}%", "desktop.updates.arrow.ready": "Lithe {version} is downloaded. Click to review and restart", @@ -5638,6 +5653,21 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.trust.title": "信任项目?", "desktop.trust.trustProject": "信任项目", "desktop.trust.vcsSafeMode": "安全模式不运行版本控制,因为工作副本的配置可以指定要运行的程序。信任项目后即可使用。", + "desktop.trustedLocations.add": "添加文件夹…", + "desktop.trustedLocations.chooseFolder": "选择要信任的文件夹", + "desktop.trustedLocations.directory": "{count} 个可信文件夹", + "desktop.trustedLocations.directoryNone": "没有可信文件夹,打开未信任的项目时会先询问", + "desktop.trustedLocations.empty": "没有可信位置。打开尚未信任的项目时会先询问。", + "desktop.trustedLocations.folders": "可信文件夹", + "desktop.trustedLocations.foldersHelp": "这些文件夹内任意层级的项目都直接以信任方式打开,不再询问;你选择保持安全模式的项目除外。点击“应用”或“确定”后生效。", + "desktop.trustedLocations.keywords": "信任 可信 安全模式 文件夹 位置 工作区 项目", + "desktop.trustedLocations.listFull": "信任列表已满(最多 256 项),请先删除一项再添加。", + "desktop.trustedLocations.pendingAdd": "待添加", + "desktop.trustedLocations.pendingRemove": "待删除", + "desktop.trustedLocations.remove": "不再信任此文件夹", + "desktop.trustedLocations.rootLocation": "磁盘或文件系统的根目录不能作为可信位置,否则会信任该磁盘上的所有项目。", + "desktop.trustedLocations.target": "可信位置", + "desktop.trustedLocations.title": "可信位置", "desktop.updates.arrow.available": "Lithe {version} 可更新,点击查看更新内容", "desktop.updates.arrow.downloading": "正在下载 Lithe {version}… {percent}%", "desktop.updates.arrow.ready": "Lithe {version} 已下载,点击查看并重启更新", diff --git a/desktop/internal/settingswindow/build_apply.go b/desktop/internal/settingswindow/build_apply.go index f0d9accd9..0a3e16d0f 100644 --- a/desktop/internal/settingswindow/build_apply.go +++ b/desktop/internal/settingswindow/build_apply.go @@ -8,12 +8,14 @@ import ( // The Build pages keep their edits as drafts until the footer's Apply or OK writes them, as // in docs/design/build-execution-settings.html: the machine's toolchain defaults, then the -// project's, then each debugger's stepping policy. One request is out at a time, because the -// toolchain scopes share one writer and every write is read back before the next. A failed -// write stops the rest and keeps the window open with its drafts; Cancel writes nothing. +// project's, then the trusted locations, then each debugger's stepping policy. One request is +// out at a time, because the toolchain scopes and the trusted locations share one writer and +// every write is read back before the next. A failed write stops the rest and keeps the window +// open with its drafts; Cancel writes nothing. const ( applyToolchain = "toolchain:" + applyLocations = "locations:" applyStepping = "stepping:" ) @@ -45,6 +47,10 @@ func (w *window) buildDrafts(language i18n.Language) (count int, targets []strin targets = append(targets, i18n.Shared(language, "desktop.buildSettings.targetProject")) } } + if n := t.locations.drafts(); n > 0 { + count += n + targets = append(targets, i18n.Shared(language, "desktop.trustedLocations.target")) + } } if pending := w.steppingPending(); len(pending) > 0 { count += len(pending) @@ -68,6 +74,12 @@ func (w *window) startApply(close bool) { a.steps = append(a.steps, applyToolchain+name) } } + if t.locations.drafts() > 0 { + // The apply reads a stale list again before it writes; a failed read stops it, and + // the next apply tries the read again. + t.locations.readFailed = nil + a.steps = append(a.steps, applyLocations) + } } for _, id := range w.steppingPending() { a.steps = append(a.steps, applyStepping+id) @@ -105,6 +117,14 @@ func (w *window) advanceApply(toolchainFailed error, stepping steppingResult) { if w.toolchains.saving { return } + case a.running == applyLocations: + if toolchainFailed != nil { + w.stopApply(toolchainFailed) + return + } + if w.toolchains.locations.saving { + return + } case strings.HasPrefix(a.running, applyStepping): if !stepping.done { return @@ -128,6 +148,28 @@ func (w *window) advanceApply(toolchainFailed error, stepping steppingResult) { } continue } + if step == applyLocations { + locations := w.toolchains.locations + if w.toolchains.busy() { + return + } + if !locations.loaded || locations.stale { + // An earlier write in this apply changed the catalog file: read it again and + // write the changes against what it holds now. + if locations.readFailed != nil { + w.stopApply(locations.readFailed) + return + } + locations.beginLoad() + return + } + a.steps = a.steps[1:] + if locations.beginSave() { + a.running = step + return + } + continue + } a.steps = a.steps[1:] if w.beginSteppingApply(strings.TrimPrefix(step, applyStepping)) { a.running = step diff --git a/desktop/internal/settingswindow/build_directory_view.go b/desktop/internal/settingswindow/build_directory_view.go index e423932c8..61355a078 100644 --- a/desktop/internal/settingswindow/build_directory_view.go +++ b/desktop/internal/settingswindow/build_directory_view.go @@ -32,6 +32,7 @@ func (w *window) buildPage(c ui.C) { if t := w.toolchains; t.available() { t.ensureLoaded() t.requestView() + t.locations.ensureLoaded() } if s := w.stepping; s.available() { s.beginLoad() @@ -230,6 +231,21 @@ func (w *window) directoryEntries(language i18n.Language) []directoryEntry { desc: i18n.SharedFormat(language, "desktop.consoleSettings.directory", map[string]string{"encoding": w.consoleEncodingLabel(w.sess.values.ConsoleEncoding)}), open: func() { w.openBuildChild(pageConsole) }, }) + if l := w.toolchains.locations; l.available() { + entry := directoryEntry{ + key: "trusted-locations", tile: locationsTile, icon: icons.ShieldCheck, title: titleOf(&w.text.Settings, pageTrustedLocations), + desc: i18n.Shared(language, "desktop.toolchains.loading"), + open: func() { w.openBuildChild(pageTrustedLocations) }, + } + if l.loaded { + if count := len(l.source.Locations); count > 0 { + entry.desc = i18n.SharedFormat(language, "desktop.trustedLocations.directory", map[string]string{"count": formatCount(count)}) + } else { + entry.desc = i18n.Shared(language, "desktop.trustedLocations.directoryNone") + } + } + entries = append(entries, entry) + } for _, kind := range buildKinds { var names []string count := 0 diff --git a/desktop/internal/settingswindow/build_style.go b/desktop/internal/settingswindow/build_style.go index 32fe58ff4..963794c0d 100644 --- a/desktop/internal/settingswindow/build_style.go +++ b/desktop/internal/settingswindow/build_style.go @@ -438,6 +438,7 @@ var ( toolchainsTile = gfx.RGB24(0x30a46c) debuggersTile = gfx.RGB24(0xe5484d) consoleTile = gfx.RGB24(0x6e56cf) + locationsTile = gfx.RGB24(0xd97706) kindTile = gfx.RGB24(0x3e7bfa) ) diff --git a/desktop/internal/settingswindow/controller.go b/desktop/internal/settingswindow/controller.go index 8a9c6cf8f..2d5237fe1 100644 --- a/desktop/internal/settingswindow/controller.go +++ b/desktop/internal/settingswindow/controller.go @@ -253,6 +253,15 @@ type ToolchainTrustLoader interface { SetWorkspaceTrust(context.Context, toolchain.Snapshot, bool) (toolchain.Snapshot, error) } +// TrustedLocationsLoader reads and writes the folders whose every workspace this machine +// trusts. Preview asks Core what draft changes lead to without writing; Save writes them +// against the bytes the list was read from and re-reads it. All calls run off the window thread. +type TrustedLocationsLoader interface { + LoadTrustedLocations(context.Context) (toolchain.TrustedLocations, error) + PreviewTrustedLocations(context.Context, toolchain.TrustedLocations, []toolchain.LocationChange) ([]string, error) + SaveTrustedLocations(context.Context, toolchain.TrustedLocations, []toolchain.LocationChange) (toolchain.TrustedLocations, error) +} + // ToolchainRuntimePreparer downloads or repairs a plugin's managed runtimes // from the Toolchains settings page, then reloads its snapshot. type ToolchainRuntimePreparer interface { diff --git a/desktop/internal/settingswindow/model.go b/desktop/internal/settingswindow/model.go index e09c7d012..d05df0d1d 100644 --- a/desktop/internal/settingswindow/model.go +++ b/desktop/internal/settingswindow/model.go @@ -31,7 +31,7 @@ const ( pagePlugins pageVersionControl // pageBuild is the group "Build, Execution, Deployment", which also has a page of its - // own: the directory of its pages and what needs attention. The three pages after it + // own: the directory of its pages and what needs attention. The four pages after it // belong to it, and so does a row for each kind of page plugins contribute to it, build // systems and compilers, which opens that kind's pages as Toolchains and Debuggers list // theirs. @@ -39,6 +39,7 @@ const ( pageToolchains pageDebuggers pageConsole + pageTrustedLocations // pageLanguages is "Languages & Frameworks", a top-level page with no static pages // under it: the pages plugins contribute to it make it a group, and its own page is the // directory of them. @@ -76,6 +77,7 @@ var parents = [pageCount]pageID{ pageToolchains: pageBuild, pageDebuggers: pageBuild, pageConsole: pageBuild, + pageTrustedLocations: pageBuild, pageLanguages: noPage, pageTools: noPage, pageTerminal: pageTools, @@ -142,6 +144,8 @@ func titleOf(messages *i18n.SettingsMessages, id pageID) string { return messages.Debuggers case pageConsole: return messages.Console + case pageTrustedLocations: + return messages.TrustedLocations case pageLanguages: return messages.Languages case pageTools: @@ -336,6 +340,8 @@ func pageKeywords(language i18n.Language, id pageID) string { return i18n.Shared(language, "desktop.buildSettings.keywordsDebuggers") case pageConsole: return i18n.Shared(language, "desktop.consoleSettings.keywords") + case pageTrustedLocations: + return i18n.Shared(language, "desktop.trustedLocations.keywords") } return "" } diff --git a/desktop/internal/settingswindow/toolchains_state.go b/desktop/internal/settingswindow/toolchains_state.go index 39062e2e5..24b9f31ef 100644 --- a/desktop/internal/settingswindow/toolchains_state.go +++ b/desktop/internal/settingswindow/toolchains_state.go @@ -388,6 +388,9 @@ type toolchainState struct { // failed is the last write, check or trust request's error; a read's error is its scope's. failed error + // locations is the Trusted Locations page, which writes the same catalog file. + locations *trustedLocationsState + // The list's query and the page's selection. query string filter string @@ -405,6 +408,7 @@ func newToolchainState(loader ToolchainLoader) *toolchainState { t := &toolchainState{loader: loader, scopes: make(map[string]*toolchainScope), filter: "all", groupBy: "category", folds: make(map[string]bool)} viewer, _ := loader.(ToolchainViewer) t.view, t.search = newToolchainProjection(viewer), newToolchainProjection(viewer) + t.locations = newTrustedLocationsState(t, loader) if loader == nil { return t } @@ -463,7 +467,7 @@ func (t *toolchainState) current() *toolchainScope { } func (t *toolchainState) busy() bool { - if t.saving || t.inspecting || t.trusting || t.preparingRuntime { + if t.saving || t.inspecting || t.trusting || t.preparingRuntime || t.locations.busy() { return true } for _, scope := range t.scopes { @@ -611,15 +615,20 @@ func (t *toolchainState) take() (saveFailed error) { scope.draft = make(map[string]string) scope.revision++ saveFailed = err + if t.saveScope == scopeGlobal { + t.locations.markStale() + } case err != nil: t.failed, saveFailed = err, err default: scope.apply(snapshot, true) - // A machine default is what the project scope inherits. + // A machine default is what the project scope inherits, and the machine catalog + // also holds the trusted locations. if t.saveScope == scopeGlobal { if project := t.scopes[scopeProject]; project != nil && project.loaded { project.stale = true } + t.locations.markStale() } } } @@ -639,10 +648,12 @@ func (t *toolchainState) take() (saveFailed error) { t.failed = err if errors.Is(err, toolchain.ErrPinCommitted) { scope.loaded, scope.stale = false, true + t.trustWritten() } } else { // The grant changes what the project probes; the user's choices stay. scope.apply(snapshot, false) + t.trustWritten() } } } @@ -666,11 +677,33 @@ func (t *toolchainState) take() (saveFailed error) { } } } + if err := t.locations.take(); err != nil && saveFailed == nil { + saveFailed = err + } t.view.take() t.search.take() return saveFailed } +// trustWritten marks what was read from the machine catalog before a trust decision wrote it. +func (t *toolchainState) trustWritten() { + if global := t.scopes[scopeGlobal]; global != nil && global.loaded { + global.stale = true + } + t.locations.markStale() +} + +// catalogWritten marks both scopes stale after the Trusted Locations page wrote the machine +// catalog: it changes which projects are trusted and the bytes the machine defaults are +// written against. +func (t *toolchainState) catalogWritten() { + for _, scope := range t.scopes { + if scope.loaded { + scope.stale = true + } + } +} + // acceptInspection lists a checked directory as the tool's candidate and chooses it. func (t *toolchainState) acceptInspection(name, id string, selection core.ToolchainSelection) { scope := t.scopes[name] @@ -709,6 +742,7 @@ func (t *toolchainState) declare(c ui.C) { if t.runtimeKey != 0 && t.runtimeEffect != nil { ui.Effect(c, t.runtimeEffect, t.runtimeKey) } + t.locations.declare(c) t.view.declare(c.Part("toolchain-view")) t.search.declare(c.Part("toolchain-search")) } @@ -1062,6 +1096,12 @@ func toolchainFailureMessage(language i18n.Language, err error) string { return i18n.Shared(language, "desktop.toolchains.sourceChanged") } var rejection *core.MarketplaceRejection + if errors.As(err, &rejection) && rejection.Code == "plugin.toolchain.rootLocation" { + return i18n.Shared(language, "desktop.trustedLocations.rootLocation") + } + if errors.As(err, &rejection) && rejection.Code == "plugin.toolchain.trustListFull" { + return i18n.Shared(language, "desktop.trustedLocations.listFull") + } if errors.Is(err, configfile.ErrTarget) || errors.Is(err, configfile.ErrEncoding) || errors.Is(err, configfile.ErrTooLarge) || (errors.As(err, &rejection) && (rejection.Code == "plugin.toolchain.invalidDocument" || rejection.Code == "plugin.toolchain.invalidIgnore")) { return i18n.Shared(language, "desktop.toolchains.sourceInvalid") diff --git a/desktop/internal/settingswindow/trusted_locations_state.go b/desktop/internal/settingswindow/trusted_locations_state.go new file mode 100644 index 000000000..30064963e --- /dev/null +++ b/desktop/internal/settingswindow/trusted_locations_state.go @@ -0,0 +1,272 @@ +package settingswindow + +import ( + "context" + "errors" + "slices" + + "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" + "github.com/vivaui/viva/ui" +) + +// trustedLocationsState is the Trusted Locations page: the folders Core read from the machine +// catalog (toolchains/global.json in the preference directory), the user's changes that are +// not applied yet and the requests that read, check and write them. Only the window thread +// touches the fields; each request is an Effect whose key changes when it is made, taken at the +// start of a paint. +// +// It belongs to toolchainState because both write the same catalog file: owner.busy() covers +// every request of either, so a locations write never races a toolchain default or a trust +// decision, and each write marks what the other read as stale. +type trustedLocationsState struct { + loader TrustedLocationsLoader + owner *toolchainState + + loadEffect *ui.EffectState[toolchain.TrustedLocations, int] + loadKey int + loading bool + loaded bool + // stale asks for a re-read before the page shows or writes again, after another write + // changed the catalog file. + stale bool + // readFailed is the last read's error; the page offers to read again. + readFailed error + source toolchain.TrustedLocations + + // changes are the user's changes in the order made; shown is the list Core says they lead + // to. Both are empty when nothing differs from source. + changes []toolchain.LocationChange + shown []string + + previewEffect *ui.EffectState[[]string, int] + previewKey int + previewSource toolchain.TrustedLocations + previewChanges []toolchain.LocationChange + // previewPick says the request checks a change the user just made, which Core's refusal + // drops; otherwise it checks the kept changes again after a re-read. + previewPick bool + previewing bool + // refused is Core's refusal of the user's last change, shown under the list. + refused error + + saveEffect *ui.EffectState[toolchain.TrustedLocations, int] + saveKey int + saveSource toolchain.TrustedLocations + saveChanges []toolchain.LocationChange + saving bool + // failed is the last write's error, or the re-check's of kept changes. + failed error +} + +// locationMark is how a folder of the page's list differs from what is saved. +type locationMark int + +const ( + locationSaved locationMark = iota + locationAdded + locationRemoved +) + +type locationRow struct { + folder string + mark locationMark +} + +func newTrustedLocationsState(owner *toolchainState, loader ToolchainLoader) *trustedLocationsState { + l := &trustedLocationsState{owner: owner} + locations, ok := loader.(TrustedLocationsLoader) + if !ok { + return l + } + l.loader = locations + l.loadEffect = ui.NewEffect[toolchain.TrustedLocations, int](func(ctx context.Context) (toolchain.TrustedLocations, error) { + return locations.LoadTrustedLocations(ctx) + }) + l.previewEffect = ui.NewEffect[[]string, int](func(ctx context.Context) ([]string, error) { + return locations.PreviewTrustedLocations(ctx, l.previewSource, l.previewChanges) + }) + l.saveEffect = ui.NewEffect[toolchain.TrustedLocations, int](func(ctx context.Context) (toolchain.TrustedLocations, error) { + return locations.SaveTrustedLocations(ctx, l.saveSource, l.saveChanges) + }) + return l +} + +func (l *trustedLocationsState) available() bool { return l != nil && l.loader != nil } + +// busy reports a request of the page that is out; owner.busy() includes it. +func (l *trustedLocationsState) busy() bool { + return l.available() && (l.loading || l.previewing || l.saving) +} + +// ensureLoaded reads the list when the page or the Build directory shows and there is none, +// or the one there is went stale. It waits for every request on the catalog that is out. +func (l *trustedLocationsState) ensureLoaded() { + if !l.available() || l.owner.busy() || l.readFailed != nil { + return + } + if !l.loaded || l.stale { + l.beginLoad() + } +} + +func (l *trustedLocationsState) beginLoad() { + l.loadKey++ + l.loading, l.readFailed = true, nil +} + +// reload reads the list again; the changes stay and are checked against what it reads. +func (l *trustedLocationsState) reload() { + if !l.available() || l.owner.busy() { + return + } + l.failed, l.refused = nil, nil + l.beginLoad() +} + +// markStale asks for a re-read after another write changed the catalog file. +func (l *trustedLocationsState) markStale() { + if l.available() && l.loaded { + l.stale = true + } +} + +// change records one change once Core accepted it: the list shows what all changes lead to. +func (l *trustedLocationsState) change(folder string, add bool) { + if !l.available() || !l.loaded || folder == "" || l.owner.busy() { + return + } + l.refused, l.failed = nil, nil + l.beginPreview(append(slices.Clone(l.changes), toolchain.LocationChange{Folder: folder, Add: add}), true) +} + +// undo drops every change of folder, so the folder is back where the saved list has it; adding +// the opposite change instead would move a restored folder to the end. +func (l *trustedLocationsState) undo(folder string) { + if !l.available() || !l.loaded || l.owner.busy() { + return + } + l.refused, l.failed = nil, nil + kept := slices.DeleteFunc(slices.Clone(l.changes), func(change toolchain.LocationChange) bool { return change.Folder == folder }) + l.beginPreview(kept, true) +} + +func (l *trustedLocationsState) beginPreview(changes []toolchain.LocationChange, pick bool) { + l.previewSource, l.previewChanges, l.previewPick = l.source, changes, pick + l.previewKey++ + l.previewing = true +} + +// rows are the page's list: the saved folders in their order, each marked when the changes +// remove it, then the folders the changes add. +func (l *trustedLocationsState) rows() []locationRow { + if !l.available() || !l.loaded { + return nil + } + rows := make([]locationRow, 0, len(l.source.Locations)+len(l.shown)) + for _, folder := range l.source.Locations { + mark := locationSaved + if len(l.changes) > 0 && !slices.Contains(l.shown, folder) { + mark = locationRemoved + } + rows = append(rows, locationRow{folder: folder, mark: mark}) + } + for _, folder := range l.shown { + if !slices.Contains(l.source.Locations, folder) { + rows = append(rows, locationRow{folder: folder, mark: locationAdded}) + } + } + return rows +} + +// drafts counts the folders the changes add or remove. +func (l *trustedLocationsState) drafts() int { + count := 0 + for _, row := range l.rows() { + if row.mark != locationSaved { + count++ + } + } + return count +} + +// beginSave writes the changes against the list they were made on. A stale list is read +// again first; the caller tries again once that read is taken. +func (l *trustedLocationsState) beginSave() bool { + if !l.available() || !l.loaded || l.stale || l.owner.busy() || l.drafts() == 0 { + return false + } + l.saveSource, l.saveChanges = l.source, slices.Clone(l.changes) + l.saveKey++ + l.saving, l.failed = true, nil + return true +} + +// take applies the page's finished requests and reports a write that failed, so the footer's +// apply stops. +func (l *trustedLocationsState) take() (saveFailed error) { + if !l.available() { + return nil + } + if source, err, ok := l.loadEffect.Take(); ok { + l.loading = false + if err != nil { + l.readFailed = err + } else { + l.source, l.loaded, l.stale = source, true, false + if len(l.changes) > 0 { + // Core checks the kept changes on what was read; the list shows the result. + l.beginPreview(l.changes, false) + } + } + } + if shown, err, ok := l.previewEffect.Take(); ok { + l.previewing = false + switch { + case err != nil && l.previewPick: + l.refused = err + case err != nil: + l.failed = err + default: + l.changes, l.shown = l.previewChanges, shown + if l.drafts() == 0 { + l.changes, l.shown = nil, nil + } + } + } + if source, err, ok := l.saveEffect.Take(); ok { + l.saving = false + switch { + case err != nil && errors.Is(err, toolchain.ErrPinCommitted): + // The list was written but not read back: the changes are on disk, and the page + // reads them before it shows the list again. + l.failed, l.loaded, l.stale = err, false, true + l.changes, l.shown = nil, nil + l.owner.catalogWritten() + saveFailed = err + case err != nil: + l.failed, saveFailed = err, err + default: + l.source, l.loaded, l.stale = source, true, false + l.changes, l.shown, l.refused = nil, nil, nil + l.owner.catalogWritten() + } + } + return saveFailed +} + +// declare keeps the requests that are out alive in every paint, so leaving the page does not +// cancel a write. +func (l *trustedLocationsState) declare(c ui.C) { + if !l.available() { + return + } + if l.loadKey != 0 { + ui.Effect(c.Part("trusted-locations-load"), l.loadEffect, l.loadKey) + } + if l.previewKey != 0 { + ui.Effect(c.Part("trusted-locations-preview"), l.previewEffect, l.previewKey) + } + if l.saveKey != 0 { + ui.Effect(c.Part("trusted-locations-save"), l.saveEffect, l.saveKey) + } +} diff --git a/desktop/internal/settingswindow/trusted_locations_view.go b/desktop/internal/settingswindow/trusted_locations_view.go new file mode 100644 index 000000000..ee203c08b --- /dev/null +++ b/desktop/internal/settingswindow/trusted_locations_view.go @@ -0,0 +1,144 @@ +package settingswindow + +import ( + "errors" + "path/filepath" + + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/icons" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// trustedLocationsPage lists the folders whose every project opens trusted, as Core read them +// from the machine catalog. Opening it only reads; adding or removing a folder is a draft that +// Core checks at once and the footer's Apply writes with the other Build drafts. +func (w *window) trustedLocationsPage(c ui.C) { + l := w.toolchains.locations + language := w.marketLanguage() + l.ensureLoaded() + w.pageScroll(c, pageTrustedLocations, func() { + w.card(c, i18n.Shared(language, "desktop.trustedLocations.folders"), i18n.Shared(language, "desktop.trustedLocations.foldersHelp"), func() { + w.trustedLocationsList(c.Part("list"), language, l) + }) + w.trustedLocationsNotices(c.Part("notices"), language, l) + }) +} + +// trustedLocationsList is one row per folder, marked when a draft adds or removes it, then +// the button that adds one. +func (w *window) trustedLocationsList(c ui.C, language i18n.Language, l *trustedLocationsState) { + p := &w.pal + if !l.loaded { + if l.readFailed == nil { + ui.Row(c).FillWidth().Height(28).Items(ui.Center).Children(func() { + ui.Text(c, i18n.Shared(language, "desktop.toolchains.loading")).FontSize(12).Color(p.muted) + }) + } + return + } + busy := w.toolchains.busy() + rows := l.rows() + if len(rows) == 0 { + ui.Row(c).FillWidth().MinHeight(28).PadY(4).Items(ui.Center).Children(func() { + ui.Wrap(c, i18n.Shared(language, "desktop.trustedLocations.empty")).FontSize(12).Color(p.muted).Grow(1).Shrink(1).MinWidth(0) + }) + } + for _, row := range rows { + k := c.Key(row.folder) + shown := filepath.FromSlash(row.folder) + ui.Row(k).FillWidth().MinWidth(0).Height(28).Gap(8).Items(ui.Center).Children(func() { + words := p.text + if row.mark == locationRemoved { + words = p.subtle + } + ui.Icon(k, icons.Folder).Size(14, 14).Color(p.muted).Shrink(0) + // The tooltip shows a path the row's width cuts; it needs an element with an identity. + path := k.Part("path") + ui.Row(path).Grow(1).Shrink(1).MinWidth(0).Items(ui.Center). + HitWith(ui.ID(path), shown, gfx.HitOptions{Role: gfx.RoleGroup}).Tooltip(shown).Children(func() { + ui.Text(path, shown).FontSize(12).Mono().Color(words).Grow(1).Shrink(1).MinWidth(0).Ellipsis() + }) + switch row.mark { + case locationAdded: + w.tag(k.Part("mark"), tagGreen, i18n.Shared(language, "desktop.trustedLocations.pendingAdd")) + if w.button(k.Part("undo"), buttonLinkSmall, i18n.Shared(language, "desktop.buildSettings.undoChange"), busy) { + l.undo(row.folder) + } + case locationRemoved: + w.tag(k.Part("mark"), tagErr, i18n.Shared(language, "desktop.trustedLocations.pendingRemove")) + if w.button(k.Part("undo"), buttonLinkSmall, i18n.Shared(language, "desktop.buildSettings.undoChange"), busy) { + l.undo(row.folder) + } + default: + if w.iconButton(k.Part("remove"), icons.X, i18n.Shared(language, "desktop.trustedLocations.remove"), busy) { + l.change(row.folder, false) + } + } + }) + } + ui.Row(c).FillWidth().Height(1).Shrink(0).Background(p.line) + ui.Row(c).FillWidth().PadTop(6).PadBottom(2).Items(ui.Center).Children(func() { + if w.button(c.Part("add"), buttonSmall, i18n.Shared(language, "desktop.trustedLocations.add"), busy) { + w.pickTrustedLocation(language) + } + }) +} + +// trustedLocationsNotices are the read's, the check's and the write's failures, and the write +// that is out. +func (w *window) trustedLocationsNotices(c ui.C, language i18n.Language, l *trustedLocationsState) { + if l.readFailed == nil && l.refused == nil && l.failed == nil && !l.saving { + return + } + ui.Column(c).FillWidth().Shrink(0).Gap(8).Children(func() { + if l.readFailed != nil { + message := toolchainFailureMessage(language, l.readFailed) + w.box(c.Part("load-failed"), boxErr, func(words gfx.Color) { + boxIcon(c, icons.CircleX, words) + boxText(c, message, words) + if w.button(c.Part("load-retry"), buttonSmall, i18n.Shared(language, "desktop.toolchains.reload"), w.toolchains.busy()) { + l.reload() + } + }) + } + for _, failure := range []struct { + key string + err error + }{{"refused", l.refused}, {"failed", l.failed}} { + if failure.err == nil { + continue + } + message := toolchainFailureMessage(language, failure.err) + w.box(c.Part(failure.key), boxErr, func(words gfx.Color) { + boxIcon(c, icons.CircleX, words) + boxText(c, message, words) + }) + } + if l.saving { + w.box(c.Part("busy"), boxInfo, func(words gfx.Color) { + boxIcon(c, icons.Clock, words) + boxText(c, i18n.Shared(language, "desktop.toolchains.saving"), words) + }) + } + }) +} + +// pickTrustedLocation asks for a folder and adds it as a draft once Core accepts it. +func (w *window) pickTrustedLocation(language i18n.Language) { + path, err := app.OpenDirectory(app.OpenDirectoryOptions{Title: i18n.Shared(language, "desktop.trustedLocations.chooseFolder")}) + // log-exempt: 用户取消:关闭目录选择器不修改可信位置草稿。 + if errors.Is(err, app.ErrCanceled) { + return + } + l := w.toolchains.locations + if err != nil { + l.failed = err + if w.ctrl.opts.MarketplaceError != nil { + w.ctrl.opts.MarketplaceError(err) + } + return + } + l.change(path, true) +} diff --git a/desktop/internal/settingswindow/trusted_locations_view_test.go b/desktop/internal/settingswindow/trusted_locations_view_test.go new file mode 100644 index 000000000..9fd954463 --- /dev/null +++ b/desktop/internal/settingswindow/trusted_locations_view_test.go @@ -0,0 +1,254 @@ +package settingswindow + +import ( + "context" + "errors" + "path/filepath" + "slices" + "strings" + "sync" + "sync/atomic" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" +) + +// fakeLocationsLoader keeps a trusted folder list the way Core edits it: a change removes the +// folder, an add then appends it, and a filesystem root is refused. A write checks it is made +// on the list last read. +type fakeLocationsLoader struct { + fakeToolchainLoader + mu sync.Mutex + locations []string + // commitErr is returned after a write lands, as when the read-back fails. + commitErr error + saved chan []toolchain.LocationChange + // locationLoads counts the reads; the window reads on an effect goroutine. + locationLoads atomic.Int32 +} + +func (f *fakeLocationsLoader) LoadTrustedLocations(context.Context) (toolchain.TrustedLocations, error) { + f.locationLoads.Add(1) + f.mu.Lock() + defer f.mu.Unlock() + return toolchain.TrustedLocations{Locations: slices.Clone(f.locations)}, nil +} + +func (f *fakeLocationsLoader) PreviewTrustedLocations(_ context.Context, source toolchain.TrustedLocations, changes []toolchain.LocationChange) ([]string, error) { + return replayLocations(source.Locations, changes) +} + +func (f *fakeLocationsLoader) SaveTrustedLocations(_ context.Context, source toolchain.TrustedLocations, changes []toolchain.LocationChange) (toolchain.TrustedLocations, error) { + if f.saved != nil { + select { + case f.saved <- slices.Clone(changes): + default: + } + } + f.mu.Lock() + defer f.mu.Unlock() + if !slices.Equal(source.Locations, f.locations) { + return source, toolchain.ErrPinConflict + } + locations, err := replayLocations(f.locations, changes) + if err != nil { + return source, err + } + f.locations = locations + if f.commitErr != nil { + return source, f.commitErr + } + return toolchain.TrustedLocations{Locations: slices.Clone(locations)}, nil +} + +func (f *fakeLocationsLoader) set(locations ...string) { + f.mu.Lock() + defer f.mu.Unlock() + f.locations = locations +} + +func (f *fakeLocationsLoader) list() []string { + f.mu.Lock() + defer f.mu.Unlock() + return slices.Clone(f.locations) +} + +func replayLocations(list []string, changes []toolchain.LocationChange) ([]string, error) { + out := slices.Clone(list) + for index, change := range changes { + if change.Folder == "/" { + return nil, &toolchain.LocationChangeError{Index: index, Err: &core.MarketplaceRejection{Code: "plugin.toolchain.rootLocation", Message: "fixture root diagnostic"}} + } + out = slices.DeleteFunc(out, func(folder string) bool { return folder == change.Folder }) + if change.Add { + out = append(out, change.Folder) + } + } + return out, nil +} + +const ( + savedFolder = "/fixture/saved" + addedFolder = "/fixture/added" + otherFolder = "/fixture/other" +) + +// locationsWindow opens a settings window on page with loader and waits for the trusted +// folder list. +func locationsWindow(t *testing.T, loader *fakeLocationsLoader, page pageID) (*window, *windowDriver, *trustedLocationsState) { + t.Helper() + w := newWindow(NewController(Options{Toolchains: loader}), Values{}) + w.sess.page = page + d := openWindow(t, w) + l := w.toolchains.locations + d.until("the trusted folders to load", func() bool { return l.loaded && !l.busy() }) + d.pump() + return w, d, l +} + +// changeLocation makes one change as the page's controls do and waits for Core's check. +func (d *windowDriver) changeLocation(l *trustedLocationsState, folder string, add bool) { + d.t.Helper() + l.change(folder, add) + d.until("the change to be checked", func() bool { return !l.previewing }) + d.pump() +} + +func locationMarks(l *trustedLocationsState) map[string]locationMark { + marks := map[string]locationMark{} + for _, row := range l.rows() { + marks[row.folder] = row.mark + } + return marks +} + +// Adding and removing folders are drafts marked in the list until Apply writes them; undoing a +// change takes its mark away, and opening the page writes nothing. +func TestTrustedLocationsDraftsAreMarkedUndoneAndApplied(t *testing.T) { + loader := &fakeLocationsLoader{saved: make(chan []toolchain.LocationChange, 1)} + loader.set(savedFolder) + w, d, l := locationsWindow(t, loader, pageTrustedLocations) + if !d.text(filepath.FromSlash(savedFolder)) { + t.Fatal("the saved folder is not listed") + } + select { + case changes := <-loader.saved: + t.Fatalf("opening the page wrote %v", changes) + default: + } + + d.changeLocation(l, addedFolder, true) + d.click(en("desktop.trustedLocations.remove")) + d.until("the removal to be checked", func() bool { return !l.previewing }) + d.pump() + if marks := locationMarks(l); marks[savedFolder] != locationRemoved || marks[addedFolder] != locationAdded || l.drafts() != 2 { + t.Fatalf("marks = %v, drafts = %d", marks, l.drafts()) + } + if !d.text(en("desktop.trustedLocations.pendingAdd")) || !d.text(en("desktop.trustedLocations.pendingRemove")) { + t.Fatal("the drafts are not tagged") + } + + // The saved folder's row is drawn first: undo its removal. + d.clickHit(d.first(en("desktop.buildSettings.undoChange"))) + d.until("the undo to be checked", func() bool { return !l.previewing }) + d.pump() + if marks := locationMarks(l); marks[savedFolder] != locationSaved || marks[addedFolder] != locationAdded || l.drafts() != 1 { + t.Fatalf("after undo marks = %v, drafts = %d", marks, l.drafts()) + } + + d.applyBuild() + if w.apply.failed != nil { + t.Fatalf("apply failed: %v", w.apply.failed) + } + if got, want := loader.list(), []string{savedFolder, addedFolder}; !slices.Equal(got, want) { + t.Fatalf("written list = %v, want %v", got, want) + } + if l.drafts() != 0 || !slices.Equal(l.source.Locations, []string{savedFolder, addedFolder}) { + t.Fatalf("after apply the page shows %v with %d drafts", l.source.Locations, l.drafts()) + } +} + +// Core's refusal of a folder shows under the list and drops only that change. +func TestTrustedLocationsRefusalKeepsTheOtherDrafts(t *testing.T) { + loader := &fakeLocationsLoader{} + loader.set(savedFolder) + _, d, l := locationsWindow(t, loader, pageTrustedLocations) + d.changeLocation(l, addedFolder, true) + d.changeLocation(l, "/", true) + if l.refused == nil || l.drafts() != 1 || locationMarks(l)[addedFolder] != locationAdded { + t.Fatalf("refused = %v, drafts = %d", l.refused, l.drafts()) + } + message := toolchainFailureMessage(i18n.English, l.refused) + if message != en("desktop.trustedLocations.rootLocation") { + t.Fatalf("refusal message = %q", message) + } + if !d.showsWrapped(message) { + t.Fatal("the refusal is not on the page") + } + if strings.Contains(message, "fixture") { + t.Fatalf("the refusal shows Core's diagnostic: %q", message) + } +} + +// A write elsewhere makes the list stale; Apply reads it again and writes the drafts on what it +// read, so it keeps the folder the other write added. +func TestTrustedLocationsApplyReadsAStaleListFirst(t *testing.T) { + loader := &fakeLocationsLoader{saved: make(chan []toolchain.LocationChange, 1)} + loader.set(savedFolder) + w, d, l := locationsWindow(t, loader, pageTrustedLocations) + d.changeLocation(l, addedFolder, true) + // Leave for a page that does not read the list, so only the apply can. + w.sess.page = pageConsole + d.pump() + loader.set(savedFolder, otherFolder) + l.markStale() + before := loader.locationLoads.Load() + d.applyBuild() + if w.apply.failed != nil { + t.Fatalf("apply failed: %v", w.apply.failed) + } + if loader.locationLoads.Load() <= before { + t.Fatal("the apply wrote without reading the stale list") + } + if got, want := loader.list(), []string{savedFolder, otherFolder, addedFolder}; !slices.Equal(got, want) { + t.Fatalf("written list = %v, want %v", got, want) + } + if l.drafts() != 0 { + t.Fatalf("drafts after apply = %d", l.drafts()) + } +} + +// A write that landed but could not be read back leaves no list to show: the page reads it +// again, and the drafts, now on disk, are gone. +func TestTrustedLocationsCommittedApplyReadsTheListAgain(t *testing.T) { + loader := &fakeLocationsLoader{commitErr: errors.Join(toolchain.ErrPinCommitted, errors.New("readback failed"))} + loader.set(savedFolder) + w, d, l := locationsWindow(t, loader, pageTrustedLocations) + d.changeLocation(l, addedFolder, true) + before := loader.locationLoads.Load() + d.applyBuild() + if !errors.Is(w.apply.failed, toolchain.ErrPinCommitted) { + t.Fatalf("footer failure = %v", w.apply.failed) + } + d.until("the list to be read again", func() bool { return loader.locationLoads.Load() > before && l.loaded && !l.busy() }) + if l.drafts() != 0 || locationMarks(l)[addedFolder] != locationSaved { + t.Fatalf("after the committed write marks = %v, drafts = %d", locationMarks(l), l.drafts()) + } +} + +// The Build directory shows how many folders are trusted and opens the page. +func TestBuildDirectoryCountsTrustedLocations(t *testing.T) { + loader := &fakeLocationsLoader{} + loader.set(savedFolder, otherFolder) + w, d, _ := locationsWindow(t, loader, pageBuild) + if want := i18n.SharedFormat(i18n.English, "desktop.trustedLocations.directory", map[string]string{"count": "2"}); !d.showsWrapped(want) { + t.Fatalf("the directory does not show %q", want) + } + d.click(w.text.Settings.TrustedLocations) + d.pump() + if w.sess.page != pageTrustedLocations { + t.Fatalf("the directory row opened page %v", w.sess.page) + } +} diff --git a/desktop/internal/settingswindow/trusted_locations_visual_test.go b/desktop/internal/settingswindow/trusted_locations_visual_test.go new file mode 100644 index 000000000..505bf9e7a --- /dev/null +++ b/desktop/internal/settingswindow/trusted_locations_visual_test.go @@ -0,0 +1,72 @@ +//go:build vivahead && lithevisual + +package settingswindow + +import ( + "os" + "path/filepath" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/vivaui/viva/headless" +) + +// TestVisualTrustedLocations renders the Trusted Locations page and its Build directory row: +// the saved list, then a draft that adds a folder, one that removes a folder and Core's refusal +// of a filesystem root. The folders are fictional; the loader is the tests' fake. +func TestVisualTrustedLocations(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR to capture the trusted locations page") + } + if err := os.MkdirAll(out, 0o755); err != nil { + t.Fatal(err) + } + const ( + work = "/Volumes/Work/clients" + studies = "/Users/example/Projects/studies" + sandbox = "/Users/example/Sandbox/experiments" + ) + for _, language := range []i18n.Language{i18n.English, i18n.Chinese} { + for _, theme := range []string{"dark", "light"} { + t.Run(language.Code()+"/"+theme, func(t *testing.T) { + loader := &fakeLocationsLoader{} + loader.set(work, studies) + w := newWindow(NewController(Options{ + Text: func() *i18n.Messages { return i18n.For(language) }, Language: func() i18n.Language { return language }, + SystemLanguage: language, SystemDark: func() bool { return theme == "dark" }, + Toolchains: loader, + }), Values{Theme: theme, Language: language.Code()}) + w.sess.page = pageBuild + session, err := headless.Open(w.config(), nil, headless.Options{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + d := &windowDriver{t: t, w: w, driver: session.Driver()} + l := w.toolchains.locations + d.until("the trusted folders to load", func() bool { return l.loaded && !l.busy() }) + d.pump() + shot := func(state string) { + t.Helper() + if err := session.Screenshot(filepath.Join(out, "trusted-locations-"+state+"-"+theme+"-"+language.Code()+".png")); err != nil { + t.Fatal(err) + } + } + shot("directory") + // Pump paints only what was invalidated, so wait for the list's first folder to be + // on the screen; otherwise the shot repeats the directory page. + w.openBuildChild(pageTrustedLocations) + d.until("the saved list to be painted", func() bool { return d.text(work) }) + shot("list") + d.changeLocation(l, sandbox, true) + d.changeLocation(l, studies, false) + d.changeLocation(l, "/", true) + if l.drafts() != 2 || l.refused == nil { + t.Fatalf("drafts = %d, refused = %v", l.drafts(), l.refused) + } + shot("drafts") + }) + } + } +} diff --git a/desktop/internal/settingswindow/window_view.go b/desktop/internal/settingswindow/window_view.go index ac856485b..5b08aedf9 100644 --- a/desktop/internal/settingswindow/window_view.go +++ b/desktop/internal/settingswindow/window_view.go @@ -308,7 +308,8 @@ func (w *window) navContent(c ui.C, i int) { } // navTrailing ends a row as the prototype does: Build folded and the Toolchains page count the -// tools with a problem, the Debuggers page marks drafts and a kind counts its pages. +// tools with a problem, the Debuggers and Trusted Locations pages mark drafts and a kind counts +// its pages. func (w *window) navTrailing(c ui.C, r row) { if r.dynamic != "" { return @@ -324,6 +325,10 @@ func (w *window) navTrailing(c ui.C, r row) { if len(w.steppingPending()) > 0 { dot(c, 7, w.bp.accent) } + case r.page == pageTrustedLocations: + if w.toolchains.locations.drafts() > 0 { + dot(c, 7, w.bp.accent) + } } } @@ -376,6 +381,8 @@ func (w *window) content(c ui.C) { w.debuggersPage(c) case w.sess.page == pageConsole: w.consolePage(c) + case w.sess.page == pageTrustedLocations && w.toolchains.locations.available(): + w.trustedLocationsPage(c) case w.sess.page == pageTerminal && w.ctrl.opts.TerminalShells != nil: w.terminalPage(c) case w.sess.page == pageSearch: diff --git a/desktop/internal/toolchain/catalog.go b/desktop/internal/toolchain/catalog.go index c3cf7b130..e8dce318f 100644 --- a/desktop/internal/toolchain/catalog.go +++ b/desktop/internal/toolchain/catalog.go @@ -5,6 +5,7 @@ import ( "errors" "os" "runtime" + "slices" "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" "github.com/1lck/Lithe-IDEA/desktop/internal/core" @@ -107,8 +108,26 @@ func (s Snapshot) SaveCatalog(ctx context.Context, kernel Kernel, edits []Edit) if change.Document == nil { return false, errors.New("toolchain: changed catalog has no source") } - committed, err := s.catalog.file.Replace(ctx, []byte(*change.Document), func() error { return s.catalog.file.Verify(ctx) }) - if errors.Is(err, configfile.ErrConflict) { + check := func() error { return s.catalog.verify(ctx) } + return s.catalog.replace(ctx, *change.Document, check) +} + +// verify refuses a catalog file changed since it was read, as ErrPinConflict. +func (c *catalogSource) verify(ctx context.Context) error { + if err := c.file.Verify(ctx); err != nil { + if errors.Is(err, configfile.ErrConflict) { + return errors.Join(ErrPinConflict, err) + } + return err + } + return nil +} + +// replace writes document over the catalog file atomically once check passes. A conflict is +// ErrPinConflict; a failure after the bytes were committed is also ErrPinCommitted. +func (c *catalogSource) replace(ctx context.Context, document string, check func() error) (bool, error) { + committed, err := c.file.Replace(ctx, []byte(document), check) + if errors.Is(err, configfile.ErrConflict) && !errors.Is(err, ErrPinConflict) { err = errors.Join(ErrPinConflict, err) } if err != nil && committed { @@ -191,13 +210,7 @@ func saveWorkspaceTrust(ctx context.Context, kernel Kernel, catalog *catalogSour if err := checkDirectoryIdentity(ctx, root, rootIdentity); err != nil { return err } - if err := catalog.file.Verify(ctx); err != nil { - if errors.Is(err, configfile.ErrConflict) { - return errors.Join(ErrPinConflict, err) - } - return err - } - return nil + return catalog.verify(ctx) } if err := check(); err != nil { return false, err @@ -216,12 +229,123 @@ func saveWorkspaceTrust(ctx context.Context, kernel Kernel, catalog *catalogSour if change.Document == nil { return false, errors.New("toolchain: changed catalog has no source") } - committed, err := catalog.file.Replace(ctx, []byte(*change.Document), check) - if errors.Is(err, configfile.ErrConflict) { - err = errors.Join(ErrPinConflict, err) + return catalog.replace(ctx, *change.Document, check) +} + +// locationsKernel is a Core client that edits the trusted locations of a catalog. +type locationsKernel interface { + EditToolchainTrustedLocations(context.Context, *string, string, core.ToolchainTrustedLocationsEdit) (core.ToolchainCatalogPublication, error) +} + +// LocationChange is one change the user made to the trusted locations: Add trusts Folder, +// otherwise the change stops trusting it. +type LocationChange struct { + Folder string + Add bool +} + +// LocationChangeError is a change Core refused; Index is its place in the changes. +type LocationChangeError struct { + Index int + Err error +} + +func (e *LocationChangeError) Error() string { return e.Err.Error() } +func (e *LocationChangeError) Unwrap() error { return e.Err } + +// TrustedLocations are the folders the machine trusts every workspace in, as Core reads them +// from the catalog in the preference directory (toolchains/global.json), with the bytes they +// were read from, so changes are saved against the same source. The catalog lives in the +// platform user preference directory, never in the app bundle, an installation directory or a +// workspace, so it affects neither code signing nor Sparkle delta updates. +type TrustedLocations struct { + // Locations are the trusted folders in the catalog's order, as Core normalized them. + Locations []string + catalog *catalogSource +} + +// ReadTrustedLocations reads the trusted locations from the catalog in globalRoot, the +// platform preference directory. Reading creates nothing. +func ReadTrustedLocations(ctx context.Context, kernel Kernel, globalRoot string) (TrustedLocations, error) { + if globalRoot == "" { + return TrustedLocations{}, errors.New("toolchain: trusted locations need the preference directory") } - if err != nil && committed { - err = errors.Join(ErrPinCommitted, err) + catalog, err := captureCatalog(ctx, kernel, globalRoot, "", "") + if err != nil { + return TrustedLocations{}, err } - return committed, err + return TrustedLocations{Locations: slices.Clone(catalog.state.Document.TrustedLocations), catalog: catalog}, nil +} + +// Preview replays changes, in order, on the bytes l was read from and returns the locations +// they lead to. It writes nothing. A change Core refuses is a *LocationChangeError. +func (l TrustedLocations) Preview(ctx context.Context, kernel Kernel, changes []LocationChange) ([]string, error) { + _, locations, err := l.replay(ctx, kernel, changes) + return locations, err +} + +// Save replays changes on the bytes l was read from and, when the locations they lead to +// differ, writes the result to the catalog. It refuses a catalog changed since it was read +// (ErrPinConflict) and writes only toolchains/global.json in the preference directory. +func (l TrustedLocations) Save(ctx context.Context, kernel Kernel, changes []LocationChange) (bool, error) { + if l.catalog == nil { + return false, ErrPinConflict + } + check := func() error { return l.catalog.verify(ctx) } + if err := check(); err != nil { + return false, err + } + document, locations, err := l.replay(ctx, kernel, changes) + if err != nil { + return false, err + } + if document == nil || sameLocations(locations, l.Locations) { + // Nothing to write: the changes cancel out, at most moving a folder in the list. + return false, check() + } + return l.catalog.replace(ctx, *document, check) +} + +// sameLocations reports whether two lists hold the same folders, in any order. +func sameLocations(a, b []string) bool { + if len(a) != len(b) { + return false + } + a, b = slices.Clone(a), slices.Clone(b) + slices.Sort(a) + slices.Sort(b) + return slices.Equal(a, b) +} + +// replay applies changes one at a time, so a folder removed and added again is trusted, as +// the user's last change says, rather than refused as both added and removed. document is the +// source the last change led to, nil while it is the file's own missing source. +func (l TrustedLocations) replay(ctx context.Context, kernel Kernel, changes []LocationChange) (document *string, locations []string, err error) { + native, ok := kernel.(locationsKernel) + if !ok || l.catalog == nil { + return nil, nil, ErrPinConflict + } + document, err = l.catalog.file.Text() + if err != nil { + return nil, nil, err + } + locations = slices.Clone(l.Locations) + for index, change := range changes { + edit := core.ToolchainTrustedLocationsEdit{Remove: []string{change.Folder}} + if change.Add { + edit = core.ToolchainTrustedLocationsEdit{Add: []string{change.Folder}} + } + publication, err := native.EditToolchainTrustedLocations(ctx, document, l.catalog.platform, edit) + if err != nil { + return nil, nil, &LocationChangeError{Index: index, Err: err} + } + if publication.Changed { + if publication.Document == nil { + return nil, nil, errors.New("toolchain: changed catalog has no source") + } + document = publication.Document + } + locations = publication.Catalog.TrustedLocations + } + return document, locations, nil } diff --git a/desktop/internal/toolchain/trusted_locations_test.go b/desktop/internal/toolchain/trusted_locations_test.go new file mode 100644 index 000000000..5f9c2ee1c --- /dev/null +++ b/desktop/internal/toolchain/trusted_locations_test.go @@ -0,0 +1,158 @@ +package toolchain + +import ( + "bytes" + "context" + "errors" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// sameFolder compares a folder Core lists with a native path, in the platform's path identity. +func sameFolder(listed, native string) bool { + a, b := filepath.Clean(filepath.FromSlash(listed)), filepath.Clean(native) + if runtime.GOOS == "windows" { + return strings.EqualFold(a, b) + } + return a == b +} + +func readCatalogBytes(t *testing.T, settings string) []byte { + t.Helper() + data, err := os.ReadFile(filepath.Join(settings, "toolchains", "global.json")) + if err != nil { + t.Fatal(err) + } + return data +} + +func TestTrustedLocationsPreviewWritesNothingAndSaveTrustsNestedWorkspaces(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + kernel := core.NewClient() + settings := filepath.Join(t.TempDir(), "user-settings") + first, second := canonical(t, t.TempDir()), canonical(t, t.TempDir()) + + locations, err := ReadTrustedLocations(ctx, kernel, settings) + if err != nil { + t.Fatal(err) + } + if len(locations.Locations) != 0 { + t.Fatalf("a missing catalog listed locations: %v", locations.Locations) + } + // The user adds both folders, then changes their mind about the first. + changes := []LocationChange{{Folder: first, Add: true}, {Folder: second, Add: true}, {Folder: first}} + preview, err := locations.Preview(ctx, kernel, changes) + if err != nil { + t.Fatal(err) + } + if len(preview) != 1 || !sameFolder(preview[0], second) { + t.Fatalf("preview = %v, want only %s", preview, second) + } + if _, err := os.Stat(settings); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("reading and previewing created the preference directory: %v", err) + } + + if changed, err := locations.Save(ctx, kernel, changes); err != nil || !changed { + t.Fatalf("save = %v, %v", changed, err) + } + saved, err := ReadTrustedLocations(ctx, kernel, settings) + if err != nil { + t.Fatal(err) + } + if len(saved.Locations) != 1 || !sameFolder(saved.Locations[0], second) { + t.Fatalf("saved locations = %v, want only %s", saved.Locations, second) + } + nested := filepath.Join(second, "group", "project") + document, err := saved.catalog.file.Text() + if err != nil { + t.Fatal(err) + } + state, err := kernel.ReadToolchainCatalogForWorkspace(ctx, document, saved.catalog.platform, nested) + if err != nil { + t.Fatal(err) + } + if state.WorkspaceTrust == nil || state.WorkspaceTrust.State != core.WorkspaceTrusted || + state.WorkspaceTrust.Location == nil || !sameFolder(*state.WorkspaceTrust.Location, second) { + t.Fatalf("a project inside the trusted folder = %+v", state.WorkspaceTrust) + } + + // The list read before the write is stale now. + if _, err := locations.Save(ctx, kernel, []LocationChange{{Folder: first, Add: true}}); !errors.Is(err, ErrPinConflict) { + t.Fatalf("a stale list was written over: %v", err) + } +} + +func TestTrustedLocationsChangesThatCancelOutWriteNothing(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + kernel := core.NewClient() + settings := filepath.Join(t.TempDir(), "user-settings") + first, second := canonical(t, t.TempDir()), canonical(t, t.TempDir()) + initial, err := ReadTrustedLocations(ctx, kernel, settings) + if err != nil { + t.Fatal(err) + } + if _, err := initial.Save(ctx, kernel, []LocationChange{{Folder: first, Add: true}, {Folder: second, Add: true}}); err != nil { + t.Fatal(err) + } + before := readCatalogBytes(t, settings) + locations, err := ReadTrustedLocations(ctx, kernel, settings) + if err != nil { + t.Fatal(err) + } + // Removing the first folder and adding it again only moves it to the end of the list. + changed, err := locations.Save(ctx, kernel, []LocationChange{{Folder: first}, {Folder: first, Add: true}}) + if err != nil || changed { + t.Fatalf("save = %v, %v; want nothing written", changed, err) + } + if after := readCatalogBytes(t, settings); !bytes.Equal(before, after) { + t.Fatalf("a save that changes nothing rewrote the catalog:\n%s\n%s", before, after) + } +} + +func TestTrustedLocationsRefuseAFilesystemRootAndNameTheChange(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + kernel := core.NewClient() + settings := filepath.Join(t.TempDir(), "user-settings") + folder := canonical(t, t.TempDir()) + root := filepath.VolumeName(folder) + string(filepath.Separator) + locations, err := ReadTrustedLocations(ctx, kernel, settings) + if err != nil { + t.Fatal(err) + } + _, err = locations.Preview(ctx, kernel, []LocationChange{{Folder: folder, Add: true}, {Folder: root, Add: true}}) + var change *LocationChangeError + if !errors.As(err, &change) || change.Index != 1 { + t.Fatalf("preview error = %v, want the second change refused", err) + } + var rejection *core.MarketplaceRejection + if !errors.As(err, &rejection) || rejection.Code != "plugin.toolchain.rootLocation" { + t.Fatalf("preview error = %v, want plugin.toolchain.rootLocation", err) + } + if changed, err := locations.Save(ctx, kernel, []LocationChange{{Folder: root, Add: true}}); changed || !errors.As(err, &rejection) { + t.Fatalf("save of a root = %v, %v", changed, err) + } + if _, err := os.Stat(settings); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("a refused save created the preference directory: %v", err) + } +} + +func TestReadTrustedLocationsNeedsThePreferenceDirectory(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if _, err := ReadTrustedLocations(ctx, core.NewClient(), ""); err == nil { + t.Fatal("read without a preference directory succeeded") + } + var empty TrustedLocations + if _, err := empty.Save(ctx, core.NewClient(), []LocationChange{{Folder: "/tmp", Add: true}}); !errors.Is(err, ErrPinConflict) { + t.Fatalf("save of a list never read = %v", err) + } +} diff --git a/desktop/internal/workbench/settings_toolchains.go b/desktop/internal/workbench/settings_toolchains.go index accafd880..ace6741e5 100644 --- a/desktop/internal/workbench/settings_toolchains.go +++ b/desktop/internal/workbench/settings_toolchains.go @@ -71,6 +71,37 @@ func (s settingsToolchains) SetWorkspaceTrust(ctx context.Context, snapshot tool return updated, nil } +// LoadTrustedLocations reads the machine's trusted locations from the preference directory. +func (s settingsToolchains) LoadTrustedLocations(ctx context.Context) (locations toolchain.TrustedLocations, err error) { + defer func() { s.recordFailure(ctx, "toolchain_settings_trusted_locations_load", err) }() + return toolchain.ReadTrustedLocations(ctx, s.app.kernel, s.app.globalToolchainRoot()) +} + +// PreviewTrustedLocations asks Core what the draft changes lead to, writing nothing. +func (s settingsToolchains) PreviewTrustedLocations(ctx context.Context, locations toolchain.TrustedLocations, changes []toolchain.LocationChange) (preview []string, err error) { + defer func() { s.recordFailure(ctx, "toolchain_settings_trusted_locations_preview", err) }() + return locations.Preview(ctx, s.app.kernel, changes) +} + +// SaveTrustedLocations writes the draft changes against the bytes locations were read from; +// the open project then leaves or enters safe mode with its new trust, and the list is re-read. +func (s settingsToolchains) SaveTrustedLocations(ctx context.Context, locations toolchain.TrustedLocations, changes []toolchain.LocationChange) (updated toolchain.TrustedLocations, err error) { + ctx = s.app.performedIn(ctx, "toolchain.trustedLocations.save", surfaceButton) + defer func() { s.recordFailure(ctx, "toolchain_settings_trusted_locations_save", err) }() + if _, err := locations.Save(ctx, s.app.kernel, changes); err != nil { + return locations, err + } + s.app.post(func(a *App) { + a.retryFailedPluginServers() + a.reloadProjectTrust(a.project) + }) + updated, err = toolchain.ReadTrustedLocations(ctx, s.app.kernel, s.app.globalToolchainRoot()) + if err != nil { + return locations, errors.Join(toolchain.ErrPinCommitted, err) + } + return updated, nil +} + // settingsToolchains is the settings window's adapter onto the workbench: it // reads the open project's enabled plugin manifests and writes explicit // directory pins. All calls run on the settings window's background worker. diff --git a/docs/assets/trusted-locations/README.md b/docs/assets/trusted-locations/README.md new file mode 100644 index 000000000..2d5565d73 --- /dev/null +++ b/docs/assets/trusted-locations/README.md @@ -0,0 +1,22 @@ +# 可信位置设置页(#2207)无头测试截图 + +来自生产 Viva Page 的无头渲染。可信文件夹列表由测试的假加载器提供,路径都是虚构的;不读写真实的偏好目录,也不调用真实 Core。截图覆盖深色与浅色主题、中文与英文界面,用于确认: + +- “构建、执行、部署”目录页多出“可信位置”一行,显示可信文件夹数量; +- 可信位置页按保存顺序列出文件夹,长路径用等宽字体并在悬停时显示完整路径; +- 待添加和待删除的文件夹分别带标签和“撤销修改”,底栏显示未应用的项数和写入目标; +- Core 拒绝把文件系统根目录设为可信位置时,提示显示在列表下方,其他草稿保留。 + +截图不代表 macOS/Windows 原生窗口验收。 + +| 场景 | 深色主题 | 浅色主题 | +| --- | --- | --- | +| 目录页(中文) | [深色中文](trusted-locations-directory-dark-zh-Hans.png) | [浅色中文](trusted-locations-directory-light-zh-Hans.png) | +| 目录页(英文) | [深色英文](trusted-locations-directory-dark-en.png) | [浅色英文](trusted-locations-directory-light-en.png) | +| 已保存的列表(中文) | [深色中文](trusted-locations-list-dark-zh-Hans.png) | [浅色中文](trusted-locations-list-light-zh-Hans.png) | +| 已保存的列表(英文) | [深色英文](trusted-locations-list-dark-en.png) | [浅色英文](trusted-locations-list-light-en.png) | +| 草稿与拒绝提示(中文) | [深色中文](trusted-locations-drafts-dark-zh-Hans.png) | [浅色中文](trusted-locations-drafts-light-zh-Hans.png) | +| 草稿与拒绝提示(英文) | [深色英文](trusted-locations-drafts-dark-en.png) | [浅色英文](trusted-locations-drafts-light-en.png) | + +复验:从仓库根目录设置绝对路径 `LITHE_VISUAL_OUTPUT_DIR="$(pwd)/docs/assets/trusted-locations"`,在 `desktop/` 下通过 +`../scripts/desktop/desktop-go.sh test -tags vivahead,lithevisual ./internal/settingswindow -run '^TestVisualTrustedLocations$' -count=1 -timeout 180s` 生成。 diff --git a/docs/assets/trusted-locations/trusted-locations-directory-dark-en.png b/docs/assets/trusted-locations/trusted-locations-directory-dark-en.png new file mode 100644 index 000000000..6ddddc679 Binary files /dev/null and b/docs/assets/trusted-locations/trusted-locations-directory-dark-en.png differ diff --git a/docs/assets/trusted-locations/trusted-locations-directory-dark-zh-Hans.png b/docs/assets/trusted-locations/trusted-locations-directory-dark-zh-Hans.png new file mode 100644 index 000000000..d9e2382f6 Binary files /dev/null and b/docs/assets/trusted-locations/trusted-locations-directory-dark-zh-Hans.png differ diff --git a/docs/assets/trusted-locations/trusted-locations-directory-light-en.png b/docs/assets/trusted-locations/trusted-locations-directory-light-en.png new file mode 100644 index 000000000..116d9e8f7 Binary files /dev/null and b/docs/assets/trusted-locations/trusted-locations-directory-light-en.png differ diff --git a/docs/assets/trusted-locations/trusted-locations-directory-light-zh-Hans.png b/docs/assets/trusted-locations/trusted-locations-directory-light-zh-Hans.png new file mode 100644 index 000000000..854982a06 Binary files /dev/null and b/docs/assets/trusted-locations/trusted-locations-directory-light-zh-Hans.png differ diff --git a/docs/assets/trusted-locations/trusted-locations-drafts-dark-en.png b/docs/assets/trusted-locations/trusted-locations-drafts-dark-en.png new file mode 100644 index 000000000..b53d20075 Binary files /dev/null and b/docs/assets/trusted-locations/trusted-locations-drafts-dark-en.png differ diff --git a/docs/assets/trusted-locations/trusted-locations-drafts-dark-zh-Hans.png b/docs/assets/trusted-locations/trusted-locations-drafts-dark-zh-Hans.png new file mode 100644 index 000000000..284ec5e74 Binary files /dev/null and b/docs/assets/trusted-locations/trusted-locations-drafts-dark-zh-Hans.png differ diff --git a/docs/assets/trusted-locations/trusted-locations-drafts-light-en.png b/docs/assets/trusted-locations/trusted-locations-drafts-light-en.png new file mode 100644 index 000000000..25b3318ad Binary files /dev/null and b/docs/assets/trusted-locations/trusted-locations-drafts-light-en.png differ diff --git a/docs/assets/trusted-locations/trusted-locations-drafts-light-zh-Hans.png b/docs/assets/trusted-locations/trusted-locations-drafts-light-zh-Hans.png new file mode 100644 index 000000000..6d62589e1 Binary files /dev/null and b/docs/assets/trusted-locations/trusted-locations-drafts-light-zh-Hans.png differ diff --git a/docs/assets/trusted-locations/trusted-locations-list-dark-en.png b/docs/assets/trusted-locations/trusted-locations-list-dark-en.png new file mode 100644 index 000000000..f662693bb Binary files /dev/null and b/docs/assets/trusted-locations/trusted-locations-list-dark-en.png differ diff --git a/docs/assets/trusted-locations/trusted-locations-list-dark-zh-Hans.png b/docs/assets/trusted-locations/trusted-locations-list-dark-zh-Hans.png new file mode 100644 index 000000000..dccfca5b7 Binary files /dev/null and b/docs/assets/trusted-locations/trusted-locations-list-dark-zh-Hans.png differ diff --git a/docs/assets/trusted-locations/trusted-locations-list-light-en.png b/docs/assets/trusted-locations/trusted-locations-list-light-en.png new file mode 100644 index 000000000..e2367029e Binary files /dev/null and b/docs/assets/trusted-locations/trusted-locations-list-light-en.png differ diff --git a/docs/assets/trusted-locations/trusted-locations-list-light-zh-Hans.png b/docs/assets/trusted-locations/trusted-locations-list-light-zh-Hans.png new file mode 100644 index 000000000..89c0d9f6e Binary files /dev/null and b/docs/assets/trusted-locations/trusted-locations-list-light-zh-Hans.png differ diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 31254b130..029844e1d 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -306,7 +306,10 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # code for a workspace the user has not trusted (#2208). # Lithe-core-rust main at 94408ca: #142 returns Git's authentication failure without asking to # retry once a credential question was cancelled or expired unanswered (#2231). -PINNED_CORE_REVISION="94408ca269b3c56d2c66a805d224609151c8a781" +# Lithe-core-rust main at 7c1cd55: #143 shares one peer_uid implementation across the remote +# crate; #144 lets toolchains.editCatalog add and remove trustedLocations, refusing filesystem +# roots and lists over 256 entries (#2207). +PINNED_CORE_REVISION="7c1cd55e6947d41ce8cb30f569cd896a61bf6bd5" PROFILE="debug" CHECKOUT_ONLY="no" while [[ $# -gt 0 ]]; do diff --git a/shared/i18n/features/trusted-locations.json b/shared/i18n/features/trusted-locations.json new file mode 100644 index 000000000..2a3b4f19b --- /dev/null +++ b/shared/i18n/features/trusted-locations.json @@ -0,0 +1,149 @@ +{ + "schemaVersion": 1, + "messages": [ + { + "id": "desktop.trustedLocations.title", + "description": "Settings sidebar and breadcrumb: title of the page listing the folders whose projects open trusted", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.trustedLocations.keywords", + "description": "Settings search: extra words that find the Trusted Locations page, separated by spaces", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.trustedLocations.target", + "description": "Settings footer: where Apply writes the trusted location drafts, joined into the list of targets; lowercase in English", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.trustedLocations.folders", + "description": "Trusted Locations page: title of the card listing the trusted folders", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.trustedLocations.foldersHelp", + "description": "Trusted Locations page: help behind the info glyph of the folder list", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.trustedLocations.empty", + "description": "Trusted Locations page: shown in the list when no folder is trusted", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.trustedLocations.add", + "description": "Trusted Locations page: button that chooses a folder to trust", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.trustedLocations.chooseFolder", + "description": "Trusted Locations page: title of the folder chooser", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.trustedLocations.remove", + "description": "Trusted Locations page: tip and accessible label of the button that removes a folder", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.trustedLocations.pendingAdd", + "description": "Trusted Locations page: tag of a folder a draft adds", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.trustedLocations.pendingRemove", + "description": "Trusted Locations page: tag of a folder a draft removes", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.trustedLocations.rootLocation", + "description": "Trusted Locations page: Core refused a disk or filesystem root as a trusted location", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.trustedLocations.listFull", + "description": "Trusted Locations and Toolchains pages: Core refused a trust list past its 256 entries", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.trustedLocations.directory", + "description": "Build, Execution, Deployment page: description of the Trusted Locations row, with the number of trusted folders", + "platforms": [ + "desktop" + ], + "parameters": { + "count": "string" + } + }, + { + "id": "desktop.trustedLocations.directoryNone", + "description": "Build, Execution, Deployment page: description of the Trusted Locations row when no folder is trusted", + "platforms": [ + "desktop" + ] + } + ], + "locales": { + "en-US": { + "desktop.trustedLocations.title": "Trusted Locations", + "desktop.trustedLocations.keywords": "trust trusted safe mode folder location workspace project", + "desktop.trustedLocations.target": "trusted locations", + "desktop.trustedLocations.folders": "Trusted Folders", + "desktop.trustedLocations.foldersHelp": "Projects anywhere inside these folders open trusted without asking, except the ones you chose to keep in safe mode. Changes take effect when you click Apply or OK.", + "desktop.trustedLocations.empty": "No trusted locations. Lithe asks before opening each project you haven't trusted.", + "desktop.trustedLocations.add": "Add Folder…", + "desktop.trustedLocations.chooseFolder": "Choose a Folder to Trust", + "desktop.trustedLocations.remove": "Stop Trusting This Folder", + "desktop.trustedLocations.pendingAdd": "To add", + "desktop.trustedLocations.pendingRemove": "To remove", + "desktop.trustedLocations.rootLocation": "A disk or filesystem root cannot be a trusted location: it would trust every project on that disk.", + "desktop.trustedLocations.listFull": "This trust list is full (256 entries). Remove one before adding another.", + "desktop.trustedLocations.directory": "Trusted folders: {count}", + "desktop.trustedLocations.directoryNone": "No trusted folders; untrusted projects ask before opening" + }, + "zh-CN": { + "desktop.trustedLocations.title": "可信位置", + "desktop.trustedLocations.keywords": "信任 可信 安全模式 文件夹 位置 工作区 项目", + "desktop.trustedLocations.target": "可信位置", + "desktop.trustedLocations.folders": "可信文件夹", + "desktop.trustedLocations.foldersHelp": "这些文件夹内任意层级的项目都直接以信任方式打开,不再询问;你选择保持安全模式的项目除外。点击“应用”或“确定”后生效。", + "desktop.trustedLocations.empty": "没有可信位置。打开尚未信任的项目时会先询问。", + "desktop.trustedLocations.add": "添加文件夹…", + "desktop.trustedLocations.chooseFolder": "选择要信任的文件夹", + "desktop.trustedLocations.remove": "不再信任此文件夹", + "desktop.trustedLocations.pendingAdd": "待添加", + "desktop.trustedLocations.pendingRemove": "待删除", + "desktop.trustedLocations.rootLocation": "磁盘或文件系统的根目录不能作为可信位置,否则会信任该磁盘上的所有项目。", + "desktop.trustedLocations.listFull": "信任列表已满(最多 256 项),请先删除一项再添加。", + "desktop.trustedLocations.directory": "{count} 个可信文件夹", + "desktop.trustedLocations.directoryNone": "没有可信文件夹,打开未信任的项目时会先询问" + } + } +} diff --git a/shared/platform-feature-matrix/features/workspace-trust.json b/shared/platform-feature-matrix/features/workspace-trust.json index 989090588..af174789e 100644 --- a/shared/platform-feature-matrix/features/workspace-trust.json +++ b/shared/platform-feature-matrix/features/workspace-trust.json @@ -29,5 +29,5 @@ }, "owner": "Workspace", "verification": "打开一个没有信任记录的文件夹,先出现“信任并打开项目”对话框,按钮依次为不打开、以安全模式预览、信任项目,并可勾选信任父文件夹,父文件夹标签使用当前平台的路径分隔符;不打开时当前项目不变。信任后再次打开不再询问;勾选父文件夹后同级项目直接以信任打开。以安全模式预览后,编辑器上方显示安全模式提示条,构建窗口不加载模型,运行、构建、测试和重新加载前先问“信任项目?”,选择保持安全模式时不运行;点提示条的“信任项目…”信任后提示条消失,模型和标题栏运行配置自动加载。安全模式下状态栏显示“LSP 安全模式”,语言服务器菜单说明原因并提供“信任项目…”,不提供重启;提交和 Git 日志窗口、插件版本控制窗口显示安全模式说明和“信任项目…”按钮,不运行 Git 或版本控制客户端;信任后语言服务器自动启动,更改和历史自动加载;取消信任后 Git 立即停止,已运行的语言服务器保持运行。确认偏好目录 toolchains/global.json 记录决定,项目目录中没有新增 .lithe 文件。", - "notes": "2026-11-19(#2201):对齐 IntelliJ IDEA 的可信项目。信任状态(trusted/distrusted/unknown 与可信位置)由 Core 的工具链目录判定,计划请求带 projectCodeAllowed,Core 拒绝会运行项目代码的计划(plugin.build.untrustedWorkspace)。宿主无平台分支,两个平台共用同一实现;尚未在两个平台做真实应用验收。可信位置没有独立设置页,由 #2207 跟进。2026-11-21(#2208):语言服务器启动计划带 projectCodeAllowed,Core 在安全模式下只启动声明 executesProjectCode: false 的服务器(languageServers 能力 v1,拒绝码 plugin.launch.untrustedWorkspace),版本控制提供者一律不启动;每个 Git 请求带 gitExecution.projectCodeAllowed,未信任时 Core 不启动 Git 进程(git_untrusted_workspace),宿主也不读取 Git 状态、不监视仓库元数据。两个平台共用同一实现,尚未做真实应用验收。" + "notes": "2026-11-19(#2201):对齐 IntelliJ IDEA 的可信项目。信任状态(trusted/distrusted/unknown 与可信位置)由 Core 的工具链目录判定,计划请求带 projectCodeAllowed,Core 拒绝会运行项目代码的计划(plugin.build.untrustedWorkspace)。宿主无平台分支,两个平台共用同一实现;尚未在两个平台做真实应用验收。可信位置的设置页见 workspace-trusted-locations(#2207)。2026-11-21(#2208):语言服务器启动计划带 projectCodeAllowed,Core 在安全模式下只启动声明 executesProjectCode: false 的服务器(languageServers 能力 v1,拒绝码 plugin.launch.untrustedWorkspace),版本控制提供者一律不启动;每个 Git 请求带 gitExecution.projectCodeAllowed,未信任时 Core 不启动 Git 进程(git_untrusted_workspace),宿主也不读取 Git 状态、不监视仓库元数据。两个平台共用同一实现,尚未做真实应用验收。" } diff --git a/shared/platform-feature-matrix/features/workspace-trusted-locations.json b/shared/platform-feature-matrix/features/workspace-trusted-locations.json new file mode 100644 index 000000000..b87fd8828 --- /dev/null +++ b/shared/platform-feature-matrix/features/workspace-trusted-locations.json @@ -0,0 +1,36 @@ +{ + "id": "workspace-trusted-locations", + "area": "工作区", + "group": "工作区生命周期", + "capability": "设置 › 构建、执行、部署 › 可信位置:查看、添加和删除可信文件夹,由 Core 校验并原子写入本机工具链目录", + "macos": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/settingswindow/trusted_locations_view.go", + "desktop/internal/settingswindow/trusted_locations_state.go", + "desktop/internal/settingswindow/trusted_locations_view_test.go", + "desktop/internal/settingswindow/build_apply.go", + "desktop/internal/toolchain/catalog.go", + "desktop/internal/toolchain/trusted_locations_test.go", + "desktop/internal/workbench/settings_toolchains.go", + "docs/assets/trusted-locations/README.md" + ] + }, + "windows": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/settingswindow/trusted_locations_view.go", + "desktop/internal/settingswindow/trusted_locations_state.go", + "desktop/internal/settingswindow/trusted_locations_view_test.go", + "desktop/internal/settingswindow/build_apply.go", + "desktop/internal/toolchain/catalog.go", + "desktop/internal/toolchain/trusted_locations_test.go", + "desktop/internal/workbench/settings_toolchains.go" + ] + }, + "owner": "Workspace", + "verification": "打开设置 › 构建、执行、部署,目录页显示“可信位置”一行和可信文件夹数量;进入后按保存顺序列出偏好目录 toolchains/global.json 中的 trustedLocations,打开页面不创建也不改写该文件。点“添加文件夹…”选择一个文件夹,列表末尾出现带“待添加”标签的行;点某行的删除按钮,该行变灰并显示“待删除”;“撤销修改”恢复原位置;选择磁盘或文件系统根目录时列表下方显示拒绝原因,其他草稿保留。底栏显示未应用项数和“写入 可信位置”;点“应用”或“确定”后文件只写一次,重新读取后标记消失。此后在已添加文件夹内任意层级打开一个没有信任记录的项目,直接以信任方式打开;在已删除文件夹中的项目重新询问。另一处写入(如工具链页或信任对话框)改变文件后,应用前会先重新读取再写入,不覆盖对方的改动。Windows 上路径使用反斜杠显示。", + "notes": "2026-11-21(#2207):Core 的 toolchains.editCatalog 新增 trustedLocations 字段(Lithe-IDEA/Lithe-core-rust#144),拒绝根目录(plugin.toolchain.rootLocation)和超过 256 项(plugin.toolchain.trustListFull)。桌面端每次只向 Core 提交一项改动,草稿由 Core 预演;与工具链页共用同一个目录文件,写入互相标记过期,应用时先写工具链再写可信位置。两个平台共用同一实现,只有无头测试与截图,尚未在两个平台做真实应用验收。远程工作区的可信条目由 #2231 R1 跟进。" +}