From 8f2da02901932d2056afb2f5a63f33ce831b3b2b Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Wed, 18 Nov 2026 12:48:59 +0800 Subject: [PATCH 1/2] feat(toolchain): support local workspace trust and project environment observation (#2122) --- desktop/internal/core/toolchain.go | 57 ++- desktop/internal/core/toolchain_catalog.go | 36 +- desktop/internal/i18n/shared.generated.go | 32 ++ desktop/internal/settingswindow/controller.go | 6 + .../settingswindow/toolchains_view.go | 202 +++++++- .../settingswindow/toolchains_view_test.go | 172 +++++++ .../settingswindow/visual_capture_test.go | 88 +++- desktop/internal/toolchain/catalog.go | 75 ++- desktop/internal/toolchain/load.go | 221 ++++++-- .../internal/toolchain/project_trust_test.go | 471 ++++++++++++++++++ desktop/internal/toolchain/scan.go | 68 ++- desktop/internal/toolchain/toolchain.go | 37 +- desktop/internal/workbench/debug_launch.go | 30 +- .../internal/workbench/debug_launch_test.go | 46 ++ .../internal/workbench/settings_toolchains.go | 35 +- .../workbench/settings_toolchains_test.go | 260 ++++++++++ desktop/internal/workbench/toolchains.go | 9 +- docs/ci-builds.md | 2 +- scripts/desktop/build-desktop-core.sh | 7 +- shared/i18n/locales/en-US.json | 18 +- shared/i18n/locales/zh-CN.json | 18 +- shared/i18n/messages.json | 115 +++++ .../features/plugin-debug-adapters.json | 4 +- .../features/plugin-injected-toolchains.json | 10 +- 24 files changed, 1901 insertions(+), 118 deletions(-) create mode 100644 desktop/internal/toolchain/project_trust_test.go diff --git a/desktop/internal/core/toolchain.go b/desktop/internal/core/toolchain.go index 50643f188d..c3592111c9 100644 --- a/desktop/internal/core/toolchain.go +++ b/desktop/internal/core/toolchain.go @@ -128,17 +128,28 @@ type ToolchainExport struct { Value string `json:"value"` } +// ToolchainDiscoveryPlanProjectFile is one platform-applicable projectFile +// candidate Core asks the host to observe along the directory ancestor chain. +type ToolchainDiscoveryPlanProjectFile struct { + ID string `json:"id,omitempty"` + ProjectKind string `json:"projectKind"` + Path string `json:"path"` + Home string `json:"home,omitempty"` + Requires []string `json:"requires"` +} + // ToolchainDiscoveryPlanTool is the declared scan and provider surface of one tool. type ToolchainDiscoveryPlanTool struct { - Tool string `json:"tool"` - PluginID string `json:"pluginID"` - Scans []ToolchainDiscoveryScan `json:"scans"` - Providers []string `json:"providers"` - HomeLayouts []ToolchainHomeLayout `json:"homeLayouts"` - ExecutableLayouts []ToolchainExecutableLayout `json:"executableLayouts"` - Version ToolchainVersionRule `json:"version"` - PathPrepend []string `json:"pathPrepend"` - Environment []ToolchainEnvironmentHome `json:"environment"` + Tool string `json:"tool"` + PluginID string `json:"pluginID"` + Scans []ToolchainDiscoveryScan `json:"scans"` + Providers []string `json:"providers"` + HomeLayouts []ToolchainHomeLayout `json:"homeLayouts"` + ExecutableLayouts []ToolchainExecutableLayout `json:"executableLayouts"` + Version ToolchainVersionRule `json:"version"` + PathPrepend []string `json:"pathPrepend"` + Environment []ToolchainEnvironmentHome `json:"environment"` + ProjectFiles []ToolchainDiscoveryPlanProjectFile `json:"projectFiles"` } // ToolchainEnvironmentHome is one login-shell home variable a definition reads. @@ -243,9 +254,22 @@ type ToolchainSkippedInstallation struct { Reason string `json:"reason"` } +// ToolchainProjectCandidate is one declared project-local environment or wrapper +// candidate and its resolution or pending-trust state. +type ToolchainProjectCandidate struct { + CandidateID string `json:"candidateID"` + ProjectKind string `json:"projectKind"` + Path string `json:"path"` + Home string `json:"home,omitempty"` + Executable string `json:"executable,omitempty"` + Version *string `json:"version,omitempty"` + Reason string `json:"reason,omitempty"` +} + // ToolchainCandidates is what a settings page shows for one tool. type ToolchainCandidates struct { Tool string `json:"tool"` + Project []ToolchainProjectCandidate `json:"project"` Shell []ToolchainShellCandidate `json:"shell"` Installations []ToolchainInstallation `json:"installations"` Skipped []ToolchainSkippedInstallation `json:"skipped"` @@ -336,13 +360,14 @@ type ToolchainResolutionTrace struct { // ToolchainResolution is the complete, deterministic resolution of one tool. type ToolchainResolution struct { - OperationID string `json:"operationID"` - Tool string `json:"tool"` - Directory string `json:"directory"` - Outcome ToolchainOutcome `json:"outcome"` - Trace []ToolchainResolutionTrace `json:"trace"` - Unmet []json.RawMessage `json:"unmet"` - Conflicts []json.RawMessage `json:"conflicts"` + OperationID string `json:"operationID"` + Tool string `json:"tool"` + Directory string `json:"directory"` + Outcome ToolchainOutcome `json:"outcome"` + ProjectCandidates []ToolchainProjectCandidate `json:"projectCandidates"` + Trace []ToolchainResolutionTrace `json:"trace"` + Unmet []json.RawMessage `json:"unmet"` + Conflicts []json.RawMessage `json:"conflicts"` } // ToolchainPin is one saved directory installation reference. diff --git a/desktop/internal/core/toolchain_catalog.go b/desktop/internal/core/toolchain_catalog.go index 694557971f..2bf1d813df 100644 --- a/desktop/internal/core/toolchain_catalog.go +++ b/desktop/internal/core/toolchain_catalog.go @@ -4,10 +4,11 @@ import ( "context" ) -// ToolchainCatalog contains registrations owned by this machine, independent of project pins. +// ToolchainCatalog contains registrations and workspace trust owned by this machine, independent of project pins. type ToolchainCatalog struct { - Version int `json:"version"` - Tools map[string]ToolchainCatalogEntry `json:"tools"` + Version int `json:"version"` + Tools map[string]ToolchainCatalogEntry `json:"tools"` + TrustedWorkspaces []string `json:"trustedWorkspaces,omitempty"` } type ToolchainCatalogEntry struct { @@ -16,8 +17,9 @@ type ToolchainCatalogEntry struct { } type ToolchainCatalogState struct { - Document ToolchainCatalog `json:"document"` - Storage struct { + Document ToolchainCatalog `json:"document"` + ProjectCodeAllowed bool `json:"projectCodeAllowed,omitempty"` + Storage struct { RelativePath string `json:"relativePath"` MaximumBytes int64 `json:"maximumBytes"` } `json:"storage"` @@ -29,6 +31,11 @@ type ToolchainCatalogEdit struct { DefaultHome *string `json:"defaultHome"` } +type ToolchainWorkspaceTrustEdit struct { + Workspace string `json:"workspace"` + Trusted bool `json:"trusted"` +} + type ToolchainCatalogPublication struct { Changed bool `json:"changed"` Document *string `json:"document"` @@ -36,10 +43,15 @@ type ToolchainCatalogPublication struct { } func (c *Client) ReadToolchainCatalog(ctx context.Context, document *string, platform string) (ToolchainCatalogState, error) { + return c.ReadToolchainCatalogForWorkspace(ctx, document, platform, "") +} + +func (c *Client) ReadToolchainCatalogForWorkspace(ctx context.Context, document *string, platform, workspaceRoot string) (ToolchainCatalogState, error) { return settingsSurfaceResult[ToolchainCatalogState](ctx, c, "toolchains.catalogState", "state", struct { - Document *string `json:"document"` - Platform string `json:"platform"` - }{document, platform}) + Document *string `json:"document"` + Platform string `json:"platform"` + WorkspaceRoot string `json:"workspaceRoot,omitempty"` + }{document, platform, workspaceRoot}) } func (c *Client) EditToolchainCatalog(ctx context.Context, document *string, platform string, edits []ToolchainCatalogEdit) (ToolchainCatalogPublication, error) { @@ -49,3 +61,11 @@ func (c *Client) EditToolchainCatalog(ctx context.Context, document *string, pla Edits []ToolchainCatalogEdit `json:"edits"` }{document, platform, edits}) } + +func (c *Client) EditToolchainWorkspaceTrust(ctx context.Context, document *string, platform string, trust ToolchainWorkspaceTrustEdit) (ToolchainCatalogPublication, error) { + return settingsSurfaceResult[ToolchainCatalogPublication](ctx, c, "toolchains.editCatalog", "edit", struct { + Document *string `json:"document"` + Platform string `json:"platform"` + WorkspaceTrust ToolchainWorkspaceTrustEdit `json:"workspaceTrust"` + }{document, platform, trust}) +} diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index ee13403216..7686935e32 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -1885,13 +1885,24 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.toolchains.globalHelp": "Manage detected and manually added SDKs for all projects. Save writes to the application’s user settings; projects can override the default. Existing processes use the new SDK after restarting.", "desktop.toolchains.installation": "{home} · {version} · {provider}", "desktop.toolchains.invalidDirectory": "The selected directory does not contain a usable installation. Check the directory and try again.", + "desktop.toolchains.layerAutomatic": "Automatic", + "desktop.toolchains.layerGlobal": "Global", + "desktop.toolchains.layerPinned": "Pinned", + "desktop.toolchains.layerProject": "Project", "desktop.toolchains.loadFailed": "Could not read toolchains: {reason}", "desktop.toolchains.loading": "Reading toolchains…", "desktop.toolchains.noInstallations": "No installations found.", "desktop.toolchains.noProject": "Open a project to read its toolchains.", "desktop.toolchains.pinSource": "Pinned in {directory}", "desktop.toolchains.project": "Current project", + "desktop.toolchains.projectCandidateBlocked": "{path} · Requires trusting this project", + "desktop.toolchains.projectTrustRequiredNotice": "Project tool environments were detected and will not be probed or run until this project is trusted.", "desktop.toolchains.providerUnsupported": "This build cannot query plugin backends yet; provider-reported installations are not shown.", + "desktop.toolchains.reasonNotExecutable": "File is not executable", + "desktop.toolchains.reasonProbeFailed": "Version check failed", + "desktop.toolchains.reasonProjectTrustRequired": "Requires trusting this project", + "desktop.toolchains.reasonUnsafePath": "Unsafe or outside allowed root", + "desktop.toolchains.reasonVersionUnsatisfied": "Does not meet minimum version", "desktop.toolchains.reload": "Reload", "desktop.toolchains.reloadAfterSave": "The save step completed, but its source could not be reloaded or closed cleanly. Reload before saving again; your draft has been kept.", "desktop.toolchains.reset": "Use automatic", @@ -1902,7 +1913,12 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.toolchains.sourceChanged": "The project or toolchain file changed. Reload before saving; your draft has been kept.", "desktop.toolchains.sourceInvalid": "The toolchain or ignore configuration is invalid, too large, or cannot be accessed safely. Check the source files, then reload.", "desktop.toolchains.title": "Toolchains", + "desktop.toolchains.trustProject": "Trust tool environments in this project", + "desktop.toolchains.trustProjectHelp": "Allows Lithe to probe versions of and run tool environments (such as virtual environments) and wrappers located inside this project folder. Trust applies only to this workspace on this machine, is saved in local application settings rather than .lithe/, and can be revoked at any time. Enable this only for projects from sources you trust; running processes use updated toolchains after restarting.", + "desktop.toolchains.trustStatusTrusted": "This project on this machine · Trusted", + "desktop.toolchains.trustStatusUntrusted": "This project on this machine · Not trusted", "desktop.toolchains.unavailable": "Unavailable: {reason}", + "desktop.toolchains.updatingTrust": "Updating project trust…", "desktop.toolchains.useDirectory": "Use directory", "desktop.tools.background": "Background", "desktop.tools.dragHint": "Drag to move elsewhere", @@ -4785,13 +4801,24 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.toolchains.globalHelp": "统一管理自动识别和手动添加的 SDK,保存到应用的用户设置。项目可单独覆盖默认版本;已启动的进程需重启后使用新版本。", "desktop.toolchains.installation": "{home} · {version} · {provider}", "desktop.toolchains.invalidDirectory": "所选目录中未找到可用的工具安装,请检查目录后重试。", + "desktop.toolchains.layerAutomatic": "自动发现", + "desktop.toolchains.layerGlobal": "全局默认", + "desktop.toolchains.layerPinned": "已固定", + "desktop.toolchains.layerProject": "项目环境", "desktop.toolchains.loadFailed": "无法读取工具链:{reason}", "desktop.toolchains.loading": "正在读取工具链…", "desktop.toolchains.noInstallations": "没有找到安装。", "desktop.toolchains.noProject": "打开项目后才能读取其工具链。", "desktop.toolchains.pinSource": "固定在 {directory}", "desktop.toolchains.project": "当前项目", + "desktop.toolchains.projectCandidateBlocked": "{path} · 需信任当前项目后探测与使用", + "desktop.toolchains.projectTrustRequiredNotice": "检测到项目内的工具环境;在开启项目信任前不会探测版本或运行。", "desktop.toolchains.providerUnsupported": "当前版本还不能查询插件后端;由提供方报告的安装不会显示。", + "desktop.toolchains.reasonNotExecutable": "文件不可执行", + "desktop.toolchains.reasonProbeFailed": "版本检测失败", + "desktop.toolchains.reasonProjectTrustRequired": "需要信任当前项目", + "desktop.toolchains.reasonUnsafePath": "路径不安全或超出允许目录", + "desktop.toolchains.reasonVersionUnsatisfied": "不满足最低版本要求", "desktop.toolchains.reload": "重新读取", "desktop.toolchains.reloadAfterSave": "保存步骤已完成,但未能重新读取或正常关闭配置来源。再次保存前请重新加载;草稿已保留。", "desktop.toolchains.reset": "使用自动", @@ -4802,7 +4829,12 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.toolchains.sourceChanged": "项目或工具链文件已变更,请重新加载后再保存。当前草稿已保留。", "desktop.toolchains.sourceInvalid": "工具链或忽略配置无效、过大或无法安全访问。请检查来源文件后重新加载。", "desktop.toolchains.title": "工具链", + "desktop.toolchains.trustProject": "信任当前项目中的工具环境", + "desktop.toolchains.trustProjectHelp": "允许 Lithe 对当前项目目录内的工具环境(如虚拟环境)和包装器执行版本探测与运行。此授权仅在本机对当前工作区生效,保存在应用本机设置中而不会写入项目 .lithe/,且可随时撤销。请仅对来源可信的项目开启;已运行的进程需重启后使用更新后的工具链。", + "desktop.toolchains.trustStatusTrusted": "本机此项目 · 已信任", + "desktop.toolchains.trustStatusUntrusted": "本机此项目 · 未信任", "desktop.toolchains.unavailable": "不可用:{reason}", + "desktop.toolchains.updatingTrust": "正在更新项目信任状态…", "desktop.toolchains.useDirectory": "使用此目录", "desktop.tools.background": "背景", "desktop.tools.dragHint": "可拖动到其他位置", diff --git a/desktop/internal/settingswindow/controller.go b/desktop/internal/settingswindow/controller.go index 0d4e3fd76a..99efaa4fa4 100644 --- a/desktop/internal/settingswindow/controller.go +++ b/desktop/internal/settingswindow/controller.go @@ -213,6 +213,12 @@ type ToolchainInspector interface { Inspect(context.Context, toolchain.Snapshot, string, string) (core.ToolchainSelection, error) } +// ToolchainTrustLoader updates machine-local permission to probe and run tool +// environments or wrappers inside the open project, then reloads its snapshot. +type ToolchainTrustLoader interface { + SetWorkspaceTrust(context.Context, toolchain.Snapshot, bool) (toolchain.Snapshot, error) +} + // 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. diff --git a/desktop/internal/settingswindow/toolchains_view.go b/desktop/internal/settingswindow/toolchains_view.go index df888b8424..64f75f38ef 100644 --- a/desktop/internal/settingswindow/toolchains_view.go +++ b/desktop/internal/settingswindow/toolchains_view.go @@ -27,6 +27,11 @@ type toolchainState struct { inspectSnapshot toolchain.Snapshot inspectTool, inspectHome string inspecting bool + trustEffect *ui.EffectState[toolchain.Snapshot, int] + trustKey int + trustSnapshot toolchain.Snapshot + trustWanted bool + trusting bool inputs map[string]*string custom map[string]core.ToolchainPin scope, loadScope string @@ -81,11 +86,20 @@ func newToolchainState(loader ToolchainLoader) *toolchainState { return inspector.Inspect(ctx, t.inspectSnapshot, t.inspectTool, t.inspectHome) }) } + if truster, ok := loader.(ToolchainTrustLoader); ok { + t.trustEffect = ui.NewEffect[toolchain.Snapshot, int](func(ctx context.Context) (toolchain.Snapshot, error) { + return truster.SetWorkspaceTrust(ctx, t.trustSnapshot, t.trustWanted) + }) + } return t } +func (t *toolchainState) busy() bool { + return t.loading || t.saving || t.inspecting || t.trusting +} + func (t *toolchainState) beginInspect(tool, home string) { - if t.inspectEffect == nil || t.loading || t.saving || t.inspecting || !t.loaded || home == "" { + if t.inspectEffect == nil || t.busy() || !t.loaded || home == "" { return } t.inspectSnapshot, t.inspectTool, t.inspectHome = t.snapshot, tool, home @@ -93,6 +107,15 @@ func (t *toolchainState) beginInspect(tool, home string) { t.inspecting, t.saved, t.failed = true, false, nil } +func (t *toolchainState) beginTrust(trusted bool) { + if t.trustEffect == nil || t.busy() || !t.loaded || t.snapshot.Global || t.snapshot.Root == "" { + return + } + t.trustSnapshot, t.trustWanted = t.snapshot, trusted + t.trustKey++ + t.trusting, t.saved, t.failed = true, false, nil +} + func toolchainFailureMessage(language i18n.Language, err error) string { var unavailable *toolchain.UnavailableError if errors.As(err, &unavailable) { @@ -114,7 +137,7 @@ func toolchainFailureMessage(language i18n.Language, err error) string { // beginLoad reads the project's toolchains off the window thread. func (t *toolchainState) beginLoad() { - if t.loader == nil || t.loading || t.saving || t.inspecting { + if t.loader == nil || t.busy() { return } t.loadScope = t.scope @@ -126,7 +149,7 @@ func (t *toolchainState) beginLoad() { // beginSave writes the draft's changed pins. Every edit goes through the same // Core-validated document merge; a conflict keeps the draft. func (t *toolchainState) beginSave() { - if t.loader == nil || !t.loaded || t.loading || t.saving || t.inspecting || !t.hasDraft() { + if t.loader == nil || !t.loaded || t.busy() || !t.hasDraft() { return } edits := t.edits() @@ -158,6 +181,11 @@ func (t *toolchainState) take() { } } } + if t.trustEffect != nil { + if snapshot, err, ok := t.trustEffect.Take(); ok { + t.finishTrust(snapshot, err) + } + } } func (t *toolchainState) acceptInspection(id string, selection core.ToolchainSelection) { @@ -207,6 +235,39 @@ func (t *toolchainState) finish(snapshot toolchain.Snapshot, err error, saved bo t.apply(snapshot, saved) } +func (t *toolchainState) finishTrust(snapshot toolchain.Snapshot, err error) { + t.trusting = false + if err != nil { + t.failed = err + if errors.Is(err, toolchain.ErrPinCommitted) { + t.loaded = false + } + t.saved = false + return + } + dirtyDrafts := make(map[string]string) + for _, tool := range t.snapshot.Tools { + current := "" + if tool.Pin != nil { + current = tool.Pin.Home + } + if wanted, ok := t.draft[tool.ID]; ok && wanted != current { + dirtyDrafts[tool.ID] = wanted + } + } + savedCustom := make(map[string]core.ToolchainPin, len(t.custom)) + for id, pin := range t.custom { + savedCustom[id] = pin + } + t.apply(snapshot, false) + for id, pin := range savedCustom { + t.custom[id] = pin + } + for id, wanted := range dirtyDrafts { + t.draft[id] = wanted + } +} + // declare keeps the requests that are out alive. The window declares it in every paint, so // leaving the Build page does not cancel a save that is writing the pins. func (t *toolchainState) declare(c ui.C) { @@ -222,6 +283,9 @@ func (t *toolchainState) declare(c ui.C) { if t.inspectKey != 0 { ui.Effect(c, t.inspectEffect, t.inspectKey) } + if t.trustKey != 0 && t.trustEffect != nil { + ui.Effect(c, t.trustEffect, t.trustKey) + } } func (t *toolchainState) apply(snapshot toolchain.Snapshot, saved bool) { @@ -331,7 +395,7 @@ func (w *window) toolchainsPage(c ui.C) { // toolchainCards are the Build page's cards of the tools the installed plugins resolve. func (w *window) toolchainCards(c ui.C, language i18n.Language) { t := w.toolchains - if !t.loaded && !t.loading && !t.saving && t.failed == nil { + if !t.loaded && !t.busy() && t.failed == nil { t.beginLoad() } w.card(c, i18n.Shared(language, "desktop.toolchains.title"), i18n.Shared(language, "desktop.toolchains.description"), func() { @@ -339,7 +403,7 @@ func (w *window) toolchainCards(c ui.C, language i18n.Language) { if _, ok := t.loader.(ToolchainScopedLoader); ok { previous := t.scope ui.Row(c.Part("scope")).FillWidth().Gap(16).Children(func() { - disabled := t.loading || t.saving || t.inspecting || t.hasDraft() + disabled := t.busy() || t.hasDraft() w.radio(c.Part("global"), &t.scope, "global", i18n.Shared(language, "desktop.toolchains.global"), disabled) w.radio(c.Part("project"), &t.scope, "project", i18n.Shared(language, "desktop.toolchains.project"), disabled) }) @@ -352,21 +416,44 @@ func (w *window) toolchainCards(c ui.C, language i18n.Language) { help = i18n.Shared(language, "desktop.toolchains.globalHelp") } ui.Wrap(c, help).FontSize(12).Color(w.pal.muted) + if !t.snapshot.Global && t.snapshot.Root != "" && t.loaded && t.trustEffect != nil { + trusted := t.snapshot.ProjectCodeAllowed + if t.trusting { + trusted = t.trustWanted + } + ui.Row(c.Part("trust")).FillWidth().Height(28).Items(ui.Center).Gap(6).Children(func() { + if ui.Switch(c.Part("switch"), &trusted, i18n.Shared(language, "desktop.toolchains.trustProject")).Disabled(t.busy()).Changed() { + t.beginTrust(trusted) + } + w.infoButton(c.Part("help"), i18n.Shared(language, "desktop.toolchains.trustProjectHelp")) + ui.Spacer(c) + statusText := i18n.Shared(language, "desktop.toolchains.trustStatusUntrusted") + if t.snapshot.ProjectCodeAllowed { + statusText = i18n.Shared(language, "desktop.toolchains.trustStatusTrusted") + } + ui.Text(c, statusText).FontSize(11).Color(w.pal.muted).Shrink(1).Ellipsis() + }) + if !t.snapshot.ProjectCodeAllowed && snapshotRequiresProjectTrust(t.snapshot) { + ui.Wrap(c, i18n.Shared(language, "desktop.toolchains.projectTrustRequiredNotice")).FontSize(12).Color(w.pal.warning) + } + } ui.Row(c).FillWidth().Gap(8).Items(ui.Center).Children(func() { - if ui.Button(c, i18n.Shared(language, "desktop.toolchains.reload")).Outline().Disabled(t.loading || t.saving || t.inspecting).Clicked() { + if ui.Button(c, i18n.Shared(language, "desktop.toolchains.reload")).Outline().Disabled(t.busy()).Clicked() { t.beginLoad() } - if ui.Button(c, i18n.Shared(language, "desktop.toolchains.reset")).Outline().Disabled(t.loading || t.saving || t.inspecting).Clicked() { + if ui.Button(c, i18n.Shared(language, "desktop.toolchains.reset")).Outline().Disabled(t.busy()).Clicked() { t.resetDrafts() } ui.Spacer(c) - if ui.Button(c, i18n.Shared(language, "desktop.toolchains.save")).Disabled(!t.loaded || !t.hasDraft() || t.saving || t.loading || t.inspecting).Clicked() { + if ui.Button(c, i18n.Shared(language, "desktop.toolchains.save")).Disabled(!t.loaded || !t.hasDraft() || t.busy()).Clicked() { t.beginSave() } }) switch { case t.loading || t.inspecting: ui.Text(c, i18n.Shared(language, "desktop.toolchains.loading")).FontSize(12).Color(w.pal.muted) + case t.trusting: + ui.Text(c, i18n.Shared(language, "desktop.toolchains.updatingTrust")).FontSize(12).Color(w.pal.muted) case t.saving: ui.Text(c, i18n.Shared(language, "desktop.toolchains.saving")).FontSize(12).Color(w.pal.muted) case t.failed != nil: @@ -397,7 +484,7 @@ func (w *window) toolchainCards(c ui.C, language i18n.Language) { func (w *window) toolchainTool(c ui.C, language i18n.Language, tool toolchain.Tool) { t := w.toolchains - busy := t.loading || t.saving || t.inspecting + busy := t.busy() ui.Column(c).FillWidth().Gap(6).Children(func() { ui.Text(c, tool.PluginID).FontSize(11).Color(w.pal.muted) switch { @@ -407,12 +494,16 @@ func (w *window) toolchainTool(c ui.C, language i18n.Language, tool toolchain.To value += " (" + tool.Effective.Version + ")" } if tool.Effective.Layer != "" { - value += " · " + tool.Effective.Layer + value += " · " + toolchainLayerLabel(language, tool.Effective.Layer) } ui.Text(c, i18n.SharedFormat(language, "desktop.toolchains.effective", map[string]string{"value": value})).FontSize(12).Color(w.pal.text) default: - reason := toolchainReason(tool) - ui.Text(c, i18n.SharedFormat(language, "desktop.toolchains.unavailable", map[string]string{"reason": reason})).FontSize(12).Color(w.pal.danger) + code := toolchainReason(tool) + color := w.pal.danger + if code == "projectCodeRequiresAction" { + color = w.pal.warning + } + ui.Text(c, i18n.SharedFormat(language, "desktop.toolchains.unavailable", map[string]string{"reason": toolchainReasonLabel(language, code)})).FontSize(12).Color(color) } // One list holds every directory the tool can use: the automatic choice, which shows // what discovery picks, each installation found, the saved pin, a checked directory, @@ -427,7 +518,11 @@ func (w *window) toolchainTool(c ui.C, language i18n.Language, tool toolchain.To } automatic := tool.AutomaticHome if automatic == "" { - automatic = i18n.Shared(language, "desktop.toolchains.noInstallations") + if toolRequiresProjectTrust(tool) { + automatic = i18n.Shared(language, "desktop.toolchains.reasonProjectTrustRequired") + } else { + automatic = i18n.Shared(language, "desktop.toolchains.noInstallations") + } } add("", i18n.SharedFormat(language, "desktop.toolchains.automatic", map[string]string{"value": automatic})) // An installation without a version cannot be pinned, so it is not a choice; it is @@ -499,6 +594,25 @@ func (w *window) toolchainTool(c ui.C, language i18n.Language, tool toolchain.To } }) } + for _, project := range tool.Project { + display := project.Home + if display == "" { + display = project.Path + } + if project.Reason == "projectCodeRequiresAction" { + ui.Text(c, i18n.SharedFormat(language, "desktop.toolchains.projectCandidateBlocked", map[string]string{"path": display})).FontSize(11).Color(w.pal.warning) + continue + } + version := "" + if project.Version != nil { + version = *project.Version + } else if project.Reason != "" { + version = toolchainReasonLabel(language, project.Reason) + } + ui.Text(c, i18n.SharedFormat(language, "desktop.toolchains.installation", map[string]string{ + "home": display, "version": version, "provider": "host:project", + })).FontSize(11).Color(w.pal.muted) + } for _, shell := range tool.Shell { // A variable's name, or the command found on the PATH: both are the user's own words. source := shell.Variable @@ -546,9 +660,71 @@ func toolchainReason(tool toolchain.Tool) string { return trace.Reason.Code } } + for _, project := range tool.Project { + if project.Reason != "" { + return project.Reason + } + } return "notFound" } +func toolRequiresProjectTrust(tool toolchain.Tool) bool { + for _, project := range tool.Project { + if project.Reason == "projectCodeRequiresAction" { + return true + } + } + for _, trace := range tool.Trace { + if trace.Reason != nil && trace.Reason.Code == "projectCodeRequiresAction" { + return true + } + } + return false +} + +func snapshotRequiresProjectTrust(snapshot toolchain.Snapshot) bool { + for _, tool := range snapshot.Tools { + if toolRequiresProjectTrust(tool) { + return true + } + } + return false +} + +func toolchainReasonLabel(language i18n.Language, code string) string { + switch code { + case "projectCodeRequiresAction": + return i18n.Shared(language, "desktop.toolchains.reasonProjectTrustRequired") + case "notFound": + return i18n.Shared(language, "desktop.toolchains.noInstallations") + case "probeFailed": + return i18n.Shared(language, "desktop.toolchains.reasonProbeFailed") + case "versionUnsatisfied": + return i18n.Shared(language, "desktop.toolchains.reasonVersionUnsatisfied") + case "notExecutable": + return i18n.Shared(language, "desktop.toolchains.reasonNotExecutable") + case "unsafePath": + return i18n.Shared(language, "desktop.toolchains.reasonUnsafePath") + default: + return code + } +} + +func toolchainLayerLabel(language i18n.Language, layer string) string { + switch layer { + case "pinned": + return i18n.Shared(language, "desktop.toolchains.layerPinned") + case "project": + return i18n.Shared(language, "desktop.toolchains.layerProject") + case "global": + return i18n.Shared(language, "desktop.toolchains.layerGlobal") + case "automatic": + return i18n.Shared(language, "desktop.toolchains.layerAutomatic") + default: + return layer + } +} + // pick is the bound value of one tool's radio group. It lives as long as the window, so the // radios keep their identities. func (t *toolchainState) pick(tool string) *string { diff --git a/desktop/internal/settingswindow/toolchains_view_test.go b/desktop/internal/settingswindow/toolchains_view_test.go index 7bce395d8e..49d509e355 100644 --- a/desktop/internal/settingswindow/toolchains_view_test.go +++ b/desktop/internal/settingswindow/toolchains_view_test.go @@ -315,3 +315,175 @@ func TestToolchainSourceFailuresUseSelectedLanguage(t *testing.T) { } } } + +type trustToolchainLoader struct { + fakeToolchainLoader + globalSnapshot toolchain.Snapshot + untrusted toolchain.Snapshot + trustedSnapshot toolchain.Snapshot + trusted bool + trustCalls []bool + trustErr error +} + +func (l *trustToolchainLoader) LoadScope(_ context.Context, scope string) (toolchain.Snapshot, error) { + if scope == "global" { + return l.globalSnapshot, nil + } + if l.trusted { + return l.trustedSnapshot, nil + } + return l.untrusted, nil +} + +func (l *trustToolchainLoader) SetWorkspaceTrust(_ context.Context, _ toolchain.Snapshot, trusted bool) (toolchain.Snapshot, error) { + l.trustCalls = append(l.trustCalls, trusted) + if l.trustErr != nil { + return toolchain.Snapshot{}, l.trustErr + } + l.trusted = trusted + if trusted { + return l.trustedSnapshot, nil + } + return l.untrusted, nil +} + +func TestProjectToolchainTrustSwitchGrantsAndRevokesImmediately(t *testing.T) { + global := fixtureSnapshot() + global.Global = true + global.Root = "" + + untrusted := toolchain.Snapshot{ + Root: "/fixture/project", + Directory: ".", + Tools: []toolchain.Tool{{ + ID: "dev.lithe.test.runtime:interp", + DisplayName: "Synthetic Runtime", + PluginID: "dev.lithe.test.runtime", + Project: []core.ToolchainProjectCandidate{{ + CandidateID: "project-venv", + ProjectKind: "environment", + Path: "/fixture/project/.venv/bin/interp", + Home: "/fixture/project/.venv", + Reason: "projectCodeRequiresAction", + }}, + Installations: []core.ToolchainInstallation{{ + Home: "/fixture/system-runtime", Version: "3.11.0", Provider: "host:system", + }}, + }}, + } + venvVersion := "3.12.4" + venvHome := "/fixture/project/.venv" + trusted := toolchain.Snapshot{ + Root: "/fixture/project", + Directory: ".", + ProjectCodeAllowed: true, + Tools: []toolchain.Tool{{ + ID: "dev.lithe.test.runtime:interp", + DisplayName: "Synthetic Runtime", + PluginID: "dev.lithe.test.runtime", + AutomaticHome: venvHome, + Effective: &core.ToolchainSelection{ + Home: &venvHome, + Executable: "/fixture/project/.venv/bin/interp", + Version: venvVersion, + Provider: "host:project", + Layer: "project", + ProjectCode: true, + }, + Project: []core.ToolchainProjectCandidate{{ + CandidateID: "project-venv", + ProjectKind: "environment", + Path: "/fixture/project/.venv/bin/interp", + Home: venvHome, + Executable: "/fixture/project/.venv/bin/interp", + Version: &venvVersion, + }}, + Installations: []core.ToolchainInstallation{{ + Home: "/fixture/system-runtime", Version: "3.11.0", Provider: "host:system", + }}, + }}, + } + + loader := &trustToolchainLoader{ + fakeToolchainLoader: fakeToolchainLoader{saved: make(chan []toolchain.Edit, 1)}, + globalSnapshot: global, + untrusted: untrusted, + trustedSnapshot: trusted, + } + w := newWindow(NewController(Options{Toolchains: loader}), Values{}) + w.sess.page = pageBuild + d := openWindow(t, w) + d.until("global toolchains loaded", func() bool { return w.toolchains.loaded }) + + // Switch to Current project scope. + d.click(i18n.Shared(i18n.English, "desktop.toolchains.project")) + d.until("project toolchains loaded", func() bool { return w.toolchains.loaded && !w.toolchains.snapshot.Global }) + + notice := i18n.Shared(i18n.English, "desktop.toolchains.projectTrustRequiredNotice") + blockedRow := i18n.SharedFormat(i18n.English, "desktop.toolchains.projectCandidateBlocked", map[string]string{"path": venvHome}) + autoBlocked := i18n.SharedFormat(i18n.English, "desktop.toolchains.automatic", map[string]string{ + "value": i18n.Shared(i18n.English, "desktop.toolchains.reasonProjectTrustRequired"), + }) + if !d.showsWrapped(notice) || !d.text(blockedRow) || !d.showsWrapped(autoBlocked) { + t.Fatalf("untrusted UI missing guidance: notice=%v blocked=%v auto=%v", + d.showsWrapped(notice), d.text(blockedRow), d.showsWrapped(autoBlocked)) + } + if !d.text(i18n.Shared(i18n.English, "desktop.toolchains.trustStatusUntrusted")) { + t.Fatal("missing untrusted status label") + } + + // Verify ⓘ help popover explains consequences and local storage scope. + help := i18n.Shared(i18n.English, "desktop.toolchains.trustProjectHelp") + infoBounds := d.hintHit(help).Bounds + if err := d.driver.Click(infoBounds.X+infoBounds.Width/2, infoBounds.Y+infoBounds.Height/2); err != nil { + t.Fatal(err) + } + d.pump() + if !d.showsHelp(help) { + t.Fatal("project trust ⓘ button did not open its help popover") + } + // Close popover before toggling the switch. + if err := d.driver.Click(infoBounds.X+infoBounds.Width/2, infoBounds.Y+infoBounds.Height/2); err != nil { + t.Fatal(err) + } + d.pump() + + // Grant trust: reloads immediately without touching .lithe/toolchains/local.json Save. + d.click(i18n.Shared(i18n.English, "desktop.toolchains.trustProject")) + d.until("project trust granted", func() bool { return w.toolchains.snapshot.ProjectCodeAllowed && !w.toolchains.trusting }) + if !slices.Equal(loader.trustCalls, []bool{true}) { + t.Fatalf("trustCalls = %v, want [true]", loader.trustCalls) + } + autoResolved := i18n.SharedFormat(i18n.English, "desktop.toolchains.automatic", map[string]string{"value": venvHome}) + if !d.showsWrapped(autoResolved) { + t.Fatalf("trusted UI did not update automatic effective value to %q", autoResolved) + } + if !d.text(i18n.Shared(i18n.English, "desktop.toolchains.trustStatusTrusted")) { + t.Fatal("missing trusted status label") + } + + // Create an unsaved pin draft, then revoke trust: the pin draft must be preserved. + d.click("Synthetic Runtime") + d.click(i18n.SharedFormat(i18n.English, "desktop.toolchains.installation", map[string]string{ + "home": "/fixture/system-runtime", "version": "3.11.0", "provider": "host:system", + })) + d.pump() + if !w.toolchains.hasDraft() { + t.Fatal("expected unsaved pin draft before revoking trust") + } + + d.click(i18n.Shared(i18n.English, "desktop.toolchains.trustProject")) + d.until("project trust revoked", func() bool { return !w.toolchains.snapshot.ProjectCodeAllowed && !w.toolchains.trusting }) + if !slices.Equal(loader.trustCalls, []bool{true, false}) { + t.Fatalf("trustCalls = %v, want [true, false]", loader.trustCalls) + } + if !w.toolchains.hasDraft() { + t.Fatal("revoking trust discarded the unsaved pin draft") + } + select { + case edits := <-loader.saved: + t.Fatalf("toggling local workspace trust wrote project pin file: %+v", edits) + default: + } +} diff --git a/desktop/internal/settingswindow/visual_capture_test.go b/desktop/internal/settingswindow/visual_capture_test.go index 8033a70f7e..4e45aaf40f 100644 --- a/desktop/internal/settingswindow/visual_capture_test.go +++ b/desktop/internal/settingswindow/visual_capture_test.go @@ -47,6 +47,7 @@ func TestVisualSettings(t *testing.T) { {"27-settings-terminal", pageTerminal}, {"28-plugins-installed", pagePlugins}, {"29-marketplace-empty", pagePlugins}, {"31-settings-updates", pageUpdates}, {"33-settings-toolchains", pageBuild}, {"m44-toolchain-directory-menu", pageBuild}, {"m45-toolchain-custom-directory", pageBuild}, + {"m47-toolchain-project-untrusted", pageBuild}, {"m48-toolchain-project-trusted", pageBuild}, {"m49-toolchain-project-trust-help", pageBuild}, {"fonts", pageFonts}, {"21-settings-language-popup", pageGeneral}, {"30-settings-history", pageGeneral}, {"m46-history-default-rules-help", pageGeneral}, {"35-settings-search", pageEditor}, {"m35-editor-tab-layout", pageEditor}, {"m25-project-open-mode", pageGeneral}, {"m29-editor-font-menu", pageFonts}, {"m38-plugin-management-menu", pagePlugins}, @@ -75,7 +76,7 @@ func TestVisualSettings(t *testing.T) { MonospaceFamilies: func() []string { return []string{"JetBrains Mono", "Menlo"} }, Marketplace: func(context.Context) (marketplace.Snapshot, error) { return marketplace.Snapshot{}, nil }, UpdateStatus: func() UpdateStatus { return UpdateStatus{Configured: true} }, - Toolchains: &scopedToolchainLoader{fakeToolchainLoader{snapshot: globalVisualToolchains()}}, + Toolchains: visualToolchainLoader(scenario.id), // Every build can sign in to GitHub; no account is connected yet. GitHub: &GitHubAccount{Snapshot: func() GitHubState { return GitHubState{Available: true} }}, } @@ -166,6 +167,28 @@ func TestVisualSettings(t *testing.T) { d.click("Compiler") d.click(text("desktop.toolchains.custom")) d.pump() + case "m47-toolchain-project-untrusted", "m48-toolchain-project-trusted": + d.click(text("desktop.toolchains.project")) + d.until("project toolchains", func() bool { return w.toolchains.loaded && !w.toolchains.snapshot.Global }) + case "m49-toolchain-project-trust-help": + d.click(text("desktop.toolchains.project")) + d.until("project toolchains help", func() bool { return w.toolchains.loaded && !w.toolchains.snapshot.Global }) + help := text("desktop.toolchains.trustProjectHelp") + info := d.hintHit(help).Bounds + x, y := info.X+info.Width/2, info.Y+info.Height/2 + if err := d.driver.Move(x, y); err != nil { + t.Fatal(err) + } + if err := d.driver.Click(x, y); err != nil { + t.Fatal(err) + } + d.pump() + if !d.showsHelp(help) { + t.Fatal("the project trust ⓘ did not pin its help open") + } + if err := session.Advance(time.Second); err != nil { + t.Fatal(err) + } } if err := session.Screenshot(filepath.Join(out, scenario.id+"-"+theme+".png")); err != nil { t.Fatal(err) @@ -190,3 +213,66 @@ func globalVisualToolchains() toolchain.Snapshot { tool.Effective = &core.ToolchainSelection{Home: &selected, Executable: selected + "/bin/compiler", Version: "21.0.4", Layer: "global"} return snapshot } + +func visualToolchainLoader(scenarioID string) ToolchainLoader { + global := globalVisualToolchains() + venvHome := "/fixture/workspace/.venv" + untrusted := toolchain.Snapshot{ + Root: "/fixture/workspace", + Directory: ".", + Tools: []toolchain.Tool{{ + ID: "dev.lithe.test.runtime:interp", + DisplayName: "Synthetic Runtime", + PluginID: "dev.lithe.test.runtime", + Project: []core.ToolchainProjectCandidate{{ + CandidateID: "project-venv", + ProjectKind: "environment", + Path: venvHome + "/bin/interp", + Home: venvHome, + Reason: "projectCodeRequiresAction", + }}, + Installations: []core.ToolchainInstallation{{ + Home: "/fixture/runtimes/3.11", Version: "3.11.9", Provider: "host:system", + }}, + }}, + } + venvVersion := "3.12.4" + trusted := toolchain.Snapshot{ + Root: "/fixture/workspace", + Directory: ".", + ProjectCodeAllowed: true, + Tools: []toolchain.Tool{{ + ID: "dev.lithe.test.runtime:interp", + DisplayName: "Synthetic Runtime", + PluginID: "dev.lithe.test.runtime", + AutomaticHome: venvHome, + Effective: &core.ToolchainSelection{ + Home: &venvHome, + Executable: venvHome + "/bin/interp", + Version: venvVersion, + Provider: "host:project", + Layer: "project", + ProjectCode: true, + }, + Project: []core.ToolchainProjectCandidate{{ + CandidateID: "project-venv", + ProjectKind: "environment", + Path: venvHome + "/bin/interp", + Home: venvHome, + Executable: venvHome + "/bin/interp", + Version: &venvVersion, + }}, + Installations: []core.ToolchainInstallation{{ + Home: "/fixture/runtimes/3.11", Version: "3.11.9", Provider: "host:system", + }}, + }}, + } + switch scenarioID { + case "m47-toolchain-project-untrusted": + return &trustToolchainLoader{globalSnapshot: global, untrusted: untrusted, trustedSnapshot: trusted} + case "m48-toolchain-project-trusted", "m49-toolchain-project-trust-help": + return &trustToolchainLoader{globalSnapshot: global, untrusted: untrusted, trustedSnapshot: trusted, trusted: true} + default: + return &scopedToolchainLoader{fakeToolchainLoader{snapshot: global}} + } +} diff --git a/desktop/internal/toolchain/catalog.go b/desktop/internal/toolchain/catalog.go index 2d217dcd90..a80078e201 100644 --- a/desktop/internal/toolchain/catalog.go +++ b/desktop/internal/toolchain/catalog.go @@ -10,8 +10,9 @@ import ( ) type catalogKernel interface { - ReadToolchainCatalog(context.Context, *string, string) (core.ToolchainCatalogState, error) + ReadToolchainCatalogForWorkspace(context.Context, *string, string, string) (core.ToolchainCatalogState, error) EditToolchainCatalog(context.Context, *string, string, []core.ToolchainCatalogEdit) (core.ToolchainCatalogPublication, error) + EditToolchainWorkspaceTrust(context.Context, *string, string, core.ToolchainWorkspaceTrustEdit) (core.ToolchainCatalogPublication, error) } type catalogSource struct { @@ -20,9 +21,14 @@ type catalogSource struct { platform string } -// Global registrations live in the platform preference root. Reads do not create -// that root; source bytes and native identity remain private to this adapter. -func captureCatalog(ctx context.Context, kernel Kernel, root, platform string) (*catalogSource, error) { +// Global SDK registrations and machine-local workspace toolchain trust +// (trustedWorkspaces / projectCodeAllowed) live in /toolchains/global.json +// inside the platform user preference directory (Application Support / LocalAppData). +// They are never written to the app bundle, plugin package directories or workspace +// .lithe/, do not affect code signing or Sparkle delta updates, and are never copied +// across worktrees. Reads do not create the root or file; source bytes and native +// identity remain private to this adapter. +func captureCatalog(ctx context.Context, kernel Kernel, root, workspaceRoot, platform string) (*catalogSource, error) { if root == "" { return nil, nil } @@ -33,7 +39,7 @@ func captureCatalog(ctx context.Context, kernel Kernel, root, platform string) ( if platform == "" { platform = PlatformName(runtime.GOOS) } - plan, err := native.ReadToolchainCatalog(ctx, nil, platform) + plan, err := native.ReadToolchainCatalogForWorkspace(ctx, nil, platform, "") if err != nil { return nil, err } @@ -45,7 +51,7 @@ func captureCatalog(ctx context.Context, kernel Kernel, root, platform string) ( if err != nil { return nil, err } - state, err := native.ReadToolchainCatalog(ctx, document, platform) + state, err := native.ReadToolchainCatalogForWorkspace(ctx, document, platform, workspaceRoot) if err != nil { return nil, err } @@ -101,3 +107,60 @@ func (s Snapshot) SaveCatalog(ctx context.Context, kernel Kernel, edits []Edit) } return committed, err } + +// SaveWorkspaceTrust grants or revokes machine-local permission to probe and +// select tool environments or wrappers inside s.Root. It writes only to the +// platform preference root (toolchains/global.json), never to .lithe/ inside +// the workspace, and rejects stale sources or replaced workspace directories. +func (s Snapshot) SaveWorkspaceTrust(ctx context.Context, kernel Kernel, trusted bool) (bool, error) { + if s.Global || s.Root == "" || s.catalog == nil { + return false, ErrPinConflict + } + native, ok := kernel.(catalogKernel) + if !ok { + return false, ErrPinConflict + } + if err := ctx.Err(); err != nil { + return false, err + } + check := func() error { + if err := checkDirectoryIdentity(ctx, s.Root, s.rootIdentity); err != nil { + return err + } + if err := s.catalog.file.Verify(ctx); err != nil { + if errors.Is(err, configfile.ErrConflict) { + return errors.Join(ErrPinConflict, err) + } + return err + } + return nil + } + if err := check(); err != nil { + return false, err + } + text, err := s.catalog.file.Text() + if err != nil { + return false, err + } + change, err := native.EditToolchainWorkspaceTrust(ctx, text, s.catalog.platform, core.ToolchainWorkspaceTrustEdit{ + Workspace: s.Root, + Trusted: trusted, + }) + if err != nil { + return false, err + } + if !change.Changed { + return false, check() + } + if change.Document == nil { + return false, errors.New("toolchain: changed catalog has no source") + } + committed, err := s.catalog.file.Replace(ctx, []byte(*change.Document), check) + if errors.Is(err, configfile.ErrConflict) { + err = errors.Join(ErrPinConflict, err) + } + if err != nil && committed { + err = errors.Join(ErrPinCommitted, err) + } + return committed, err +} diff --git a/desktop/internal/toolchain/load.go b/desktop/internal/toolchain/load.go index bb85b6333d..15a97328fa 100644 --- a/desktop/internal/toolchain/load.go +++ b/desktop/internal/toolchain/load.go @@ -48,14 +48,6 @@ func RegistryInput(manifests []json.RawMessage) (json.RawMessage, error) { // probes, Core's candidate report and the effective layer for every definition. // It writes nothing. func Load(ctx context.Context, kernel Kernel, root, directory string, manifests []json.RawMessage, options Options) (Snapshot, error) { - catalog, catalogErr := captureCatalog(ctx, kernel, options.GlobalRoot, options.Platform) - if catalogErr != nil { - return Snapshot{}, catalogErr - } - if catalog != nil { - options.catalog = &catalog.state.Document - } - if kernel == nil { return Snapshot{}, fmt.Errorf("toolchain: no Core client") } @@ -63,6 +55,15 @@ func Load(ctx context.Context, kernel Kernel, root, directory string, manifests if err != nil { return Snapshot{}, err } + catalog, catalogErr := captureCatalog(ctx, kernel, options.GlobalRoot, workspace.root, workspace.platform) + if catalogErr != nil { + return Snapshot{}, catalogErr + } + projectCodeAllowed := !options.Global && options.ProjectCodeAllowed + if catalog != nil { + options.catalog = &catalog.state.Document + projectCodeAllowed = !options.Global && catalog.state.ProjectCodeAllowed + } var rootIdentity os.FileInfo if !options.Global { rootIdentity, err = directoryIdentity(ctx, workspace.root) @@ -94,13 +95,15 @@ func Load(ctx context.Context, kernel Kernel, root, directory string, manifests return Snapshot{}, err } snapshot := Snapshot{ - Global: options.Global, catalog: catalog, - Root: workspace.root, - rootIdentity: rootIdentity, - Directory: directory, - Conflicts: registry.Conflicts, - Baseline: captured.file.Bytes(), - source: captured, + Global: options.Global, + ProjectCodeAllowed: projectCodeAllowed, + catalog: catalog, + Root: workspace.root, + rootIdentity: rootIdentity, + Directory: directory, + Conflicts: registry.Conflicts, + Baseline: captured.file.Bytes(), + source: captured, } sequence := loadSequence.Add(1) for index, planned := range plan.Tools { @@ -111,12 +114,12 @@ func Load(ctx context.Context, kernel Kernel, root, directory string, manifests if !ok { continue } - prepared, pin, source, err := prepareTool(ctx, kernel, workspace, registryRequest, captured.document, planned, definition, directory, options, nil) + prepared, pin, source, err := prepareTool(ctx, kernel, workspace, registryRequest, captured.document, planned, definition, directory, plan.Limits.Ancestors, projectCodeAllowed, options, nil) if err != nil { return Snapshot{}, err } - resolution, err := resolveTool(ctx, kernel, workspace, registryRequest, prepared, captured.document, directory, - options.MinimumVersion, fmt.Sprintf("settings-%d-%d", sequence, index)) + resolution, err := resolveTool(ctx, kernel, workspace, registryRequest, &prepared, captured.document, directory, + options.MinimumVersion, projectCodeAllowed, fmt.Sprintf("settings-%d-%d", sequence, index)) if err != nil { return Snapshot{}, err } @@ -151,7 +154,7 @@ func Load(ctx context.Context, kernel Kernel, root, directory string, manifests if options.Global && prepared.globalDefault != nil { automaticPrepared := prepared automaticPrepared.globalDefault = nil - automatic, err = resolveTool(ctx, kernel, workspace, registryRequest, automaticPrepared, captured.document, directory, options.MinimumVersion, fmt.Sprintf("settings-auto-global-%d-%d", sequence, index)) + automatic, err = resolveTool(ctx, kernel, workspace, registryRequest, &automaticPrepared, captured.document, directory, options.MinimumVersion, projectCodeAllowed, fmt.Sprintf("settings-auto-global-%d-%d", sequence, index)) if err != nil { return Snapshot{}, err } @@ -161,12 +164,20 @@ func Load(ctx context.Context, kernel Kernel, root, directory string, manifests if err != nil { return Snapshot{}, err } - automatic, err = resolveTool(ctx, kernel, workspace, registryRequest, prepared, document, directory, - options.MinimumVersion, fmt.Sprintf("settings-auto-%d-%d", sequence, index)) + automatic, err = resolveTool(ctx, kernel, workspace, registryRequest, &prepared, document, directory, + options.MinimumVersion, projectCodeAllowed, fmt.Sprintf("settings-auto-%d-%d", sequence, index)) if err != nil { return Snapshot{}, err } } + projectCandidates := automatic.ProjectCandidates + if len(projectCandidates) == 0 { + projectCandidates = resolution.ProjectCandidates + } + if len(projectCandidates) == 0 { + projectCandidates = prepared.candidates.Project + } + tool.Project = projectCandidates if automatic.Outcome.Kind == "resolved" && automatic.Outcome.Selection != nil { tool.AutomaticHome = automatic.Outcome.Selection.Executable if automatic.Outcome.Selection.Home != nil { @@ -185,14 +196,6 @@ func Load(ctx context.Context, kernel Kernel, root, directory string, manifests // facts and Core entry points as the settings page, so a displayed value and a // launched executable cannot come from two rule sets. func Resolve(ctx context.Context, kernel Kernel, root, directory, tool, minimumVersion string, fixed *Fixed, manifests []json.RawMessage, options Options) (Selection, error) { - catalog, catalogErr := captureCatalog(ctx, kernel, options.GlobalRoot, options.Platform) - if catalogErr != nil { - return Selection{}, catalogErr - } - if catalog != nil { - options.catalog = &catalog.state.Document - } - if kernel == nil { return Selection{}, fmt.Errorf("toolchain: no Core client") } @@ -200,6 +203,15 @@ func Resolve(ctx context.Context, kernel Kernel, root, directory, tool, minimumV if err != nil { return Selection{}, err } + catalog, catalogErr := captureCatalog(ctx, kernel, options.GlobalRoot, workspace.root, workspace.platform) + if catalogErr != nil { + return Selection{}, catalogErr + } + projectCodeAllowed := !options.Global && options.ProjectCodeAllowed + if catalog != nil { + options.catalog = &catalog.state.Document + projectCodeAllowed = !options.Global && catalog.state.ProjectCodeAllowed + } registryRequest, err := RegistryInput(manifests) if err != nil { return Selection{}, err @@ -231,11 +243,11 @@ func Resolve(ctx context.Context, kernel Kernel, root, directory, tool, minimumV if !ok { continue } - prepared, _, _, err := prepareTool(ctx, kernel, workspace, registryRequest, captured.document, planned, definition, directory, options, fixed) + prepared, _, _, err := prepareTool(ctx, kernel, workspace, registryRequest, captured.document, planned, definition, directory, plan.Limits.Ancestors, projectCodeAllowed, options, fixed) if err != nil { return Selection{}, err } - resolution, err := resolveTool(ctx, kernel, workspace, registryRequest, prepared, captured.document, directory, minimumVersion, + resolution, err := resolveTool(ctx, kernel, workspace, registryRequest, &prepared, captured.document, directory, minimumVersion, projectCodeAllowed, fmt.Sprintf("run-%d", loadSequence.Add(1))) if err != nil { return Selection{}, err @@ -266,8 +278,8 @@ type preparedTool struct { // prepareTool performs the declared native reads for one tool. Core only sees // facts this function observed; a probe is run only for executables Core would -// otherwise consider. -func prepareTool(ctx context.Context, kernel Kernel, workspace *workspace, registry json.RawMessage, document json.RawMessage, planned core.ToolchainDiscoveryPlanTool, definition core.ToolchainToolDefinition, directory string, options Options, fixed *Fixed) (preparedTool, *core.ToolchainPin, string, error) { +// otherwise consider, and never for workspace executables unless projectCodeAllowed is true. +func prepareTool(ctx context.Context, kernel Kernel, workspace *workspace, registry json.RawMessage, document json.RawMessage, planned core.ToolchainDiscoveryPlanTool, definition core.ToolchainToolDefinition, directory string, maxAncestors int, projectCodeAllowed bool, options Options, fixed *Fixed) (preparedTool, *core.ToolchainPin, string, error) { prepared := preparedTool{definition: definition, fixed: fixed} if options.catalog != nil { entry := options.catalog.Tools[planned.Tool] @@ -322,6 +334,9 @@ func prepareTool(ctx context.Context, kernel Kernel, workspace *workspace, regis } } workspace.observe(workspace.root) + if !options.Global && workspace.root != "" { + observeProjectFiles(workspace, directory, maxAncestors, planned) + } prepared.commandHomes = commandHomes(workspace, definition) for _, home := range uniqueSorted(evidenceHomes) { workspace.observe(home) @@ -351,8 +366,11 @@ func prepareTool(ctx context.Context, kernel Kernel, workspace *workspace, regis } } } - if prepared.fixed != nil { - workspace.observe(prepared.fixed.Executable) + if prepared.fixed != nil && prepared.fixed.Executable != "" { + fact := workspace.observe(prepared.fixed.Executable) + if fact.Kind != "missing" && fact.CanonicalPath != "" && fact.CanonicalPath != fact.Path { + workspace.observe(fact.CanonicalPath) + } } prepared.facts = workspace.all() @@ -368,12 +386,20 @@ func prepareTool(ctx context.Context, kernel Kernel, workspace *workspace, regis Environment: prepared.environment, CommandHomes: prepared.commandHomes, Fixed: prepared.fixed, + ProjectCodeAllowed: projectCodeAllowed, } candidates, err := kernel.ToolchainCandidatesOf(ctx, request) if err != nil { return prepared, nil, "", err } var probeTargets []string + if projectCodeAllowed { + for _, row := range candidates.Project { + if row.Executable != "" { + probeTargets = append(probeTargets, row.Executable) + } + } + } for _, row := range candidates.Shell { if row.Executable != "" { probeTargets = append(probeTargets, row.Executable) @@ -399,7 +425,7 @@ func prepareTool(ctx context.Context, kernel Kernel, workspace *workspace, regis probeTargets = append(probeTargets, executable) } } - prepared.probes = workspace.probeAll(ctx, definition, probeTargets) + prepared.probes = workspace.probeAll(ctx, definition, probeTargets, projectCodeAllowed) if ctx.Err() != nil { return prepared, nil, "", ctx.Err() } @@ -417,9 +443,12 @@ func prepareTool(ctx context.Context, kernel Kernel, workspace *workspace, regis } // resolveTool runs Core's four-layer resolution over the prepared evidence. -func resolveTool(ctx context.Context, kernel Kernel, workspace *workspace, registry json.RawMessage, prepared preparedTool, document json.RawMessage, directory, minimumVersion, operationID string) (core.ToolchainResolution, error) { +// When projectCodeAllowed is true and a subdirectory project candidate was not +// yet probed by the root candidates pass, it runs one bounded follow-up probe. +func resolveTool(ctx context.Context, kernel Kernel, workspace *workspace, registry json.RawMessage, prepared *preparedTool, document json.RawMessage, directory, minimumVersion string, projectCodeAllowed bool, operationID string) (core.ToolchainResolution, error) { request := core.ToolchainResolveRequest{ - Global: workspace.root == "", GlobalDefault: prepared.globalDefault, + Global: workspace.root == "", + GlobalDefault: prepared.globalDefault, Registry: registry, Tool: prepared.definition.ID, Directory: directory, @@ -433,12 +462,128 @@ func resolveTool(ctx context.Context, kernel Kernel, workspace *workspace, regis SystemInstallations: prepared.installations, Environment: prepared.environment, CommandHomes: prepared.commandHomes, + ProjectCodeAllowed: projectCodeAllowed, Generation: loadSequence.Add(1), Fixed: prepared.fixed, } + resolution, err := kernel.ResolveToolchain(ctx, request) + if err != nil || !projectCodeAllowed { + return resolution, err + } + probed := make(map[string]bool, len(prepared.probes)) + probeKey := func(name string) string { + cleaned := filepath.Clean(name) + if !workspace.caseSensitive { + return strings.ToLower(cleaned) + } + return cleaned + } + for _, probe := range prepared.probes { + probed[probeKey(probe.Executable)] = true + } + var missing []string + for _, candidate := range resolution.ProjectCandidates { + if candidate.Executable != "" && candidate.Reason == "probeFailed" && !probed[probeKey(candidate.Executable)] { + missing = append(missing, candidate.Executable) + } + } + if len(missing) == 0 { + return resolution, nil + } + extra := workspace.probeAll(ctx, prepared.definition, missing, projectCodeAllowed) + if ctx.Err() != nil { + return resolution, ctx.Err() + } + for _, probe := range extra { + key := probeKey(probe.Executable) + if !probed[key] { + probed[key] = true + prepared.probes = append(prepared.probes, probe) + } + } + request.Probes = prepared.probes + request.Generation = loadSequence.Add(1) + request.OperationID = operationID + "-project" return kernel.ResolveToolchain(ctx, request) } +func observeProjectFiles(workspace *workspace, directory string, maxAncestors int, planned core.ToolchainDiscoveryPlanTool) { + if workspace.root == "" { + return + } + for _, ancestor := range directoryAncestors(directory, maxAncestors) { + if !isSafeRelativeAnchor(ancestor) { + continue + } + anchor := workspace.root + if ancestor != "." { + anchor = filepath.Join(workspace.root, filepath.FromSlash(ancestor)) + } + workspace.observeChain(workspace.root, anchor) + for _, projectFile := range planned.ProjectFiles { + if !isSafeRelativeAnchor(projectFile.Path) { + continue + } + workspace.observeChain(anchor, filepath.Join(anchor, filepath.FromSlash(projectFile.Path))) + if projectFile.Home != "" && isSafeRelativeAnchor(projectFile.Home) { + nativeHome := anchor + if projectFile.Home != "." { + nativeHome = filepath.Join(anchor, filepath.FromSlash(projectFile.Home)) + } + workspace.observeChain(anchor, nativeHome) + for _, template := range planned.PathPrepend { + if prepend, ok := prependPath(nativeHome, template); ok { + workspace.observeChain(nativeHome, prepend) + } + } + } + for _, required := range projectFile.Requires { + if isSafeRelativeAnchor(required) { + workspace.observeChain(anchor, filepath.Join(anchor, filepath.FromSlash(required))) + } + } + } + } +} + +func directoryAncestors(directory string, maxAncestors int) []string { + if maxAncestors <= 0 { + maxAncestors = 64 + } + current := filepath.ToSlash(directory) + if current == "" { + current = "." + } + result := []string{current} + for current != "." && len(result) < maxAncestors { + if idx := strings.LastIndexByte(current, '/'); idx >= 0 { + current = current[:idx] + if current == "" { + current = "." + } + } else { + current = "." + } + result = append(result, current) + } + return result +} + +func isSafeRelativeAnchor(value string) bool { + if value == "." { + return true + } + if value == "" || strings.ContainsAny(value, "\\:") { + return false + } + for _, part := range strings.Split(value, "/") { + if part == "" || part == "." || part == ".." { + return false + } + } + return true +} + // declaredEnvironment passes only the home variables the definition declares. // Other login-shell values never cross the Core boundary. func declaredEnvironment(planned core.ToolchainDiscoveryPlanTool, environment map[string]string) map[string]string { diff --git a/desktop/internal/toolchain/project_trust_test.go b/desktop/internal/toolchain/project_trust_test.go new file mode 100644 index 0000000000..b3b9c63b99 --- /dev/null +++ b/desktop/internal/toolchain/project_trust_test.go @@ -0,0 +1,471 @@ +package toolchain + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "runtime" + "strings" + "sync" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +func syntheticProjectEnvManifest(t *testing.T) json.RawMessage { + t.Helper() + manifest := map[string]any{ + "schemaVersion": 0, + "id": "dev.lithe.test.projectenv", + "displayName": "Synthetic Project Environment", + "version": "1.0.0", + "pluginAPIVersion": 0, + "requires": map[string]any{"toolDefinitions": 0}, + "vendor": map[string]any{ + "id": "dev.lithe.test", + "displayName": "Synthetic Test Vendor", + "signatureRequirement": "publisherPackage", + }, + "permissions": []any{}, + "toolDefinitions": []any{ + map[string]any{ + "id": "dev.lithe.test.projectenv:interp", + "displayName": "Synthetic Interpreter", + "executableLayouts": []any{ + map[string]any{"path": "bin/interp", "platforms": []string{"macos", "linux"}}, + map[string]any{"path": "Scripts/interp.exe", "platforms": []string{"windows"}}, + }, + "executables": []any{ + map[string]any{ + "id": "pinned", + "kind": "setting", + "settingID": "executable", + "layer": "project", + }, + map[string]any{ + "id": "project-venv-unix", + "kind": "projectFile", + "projectKind": "environment", + "home": ".venv", + "path": ".venv/bin/interp", + "requires": []string{".venv/env.cfg"}, + "platforms": []string{"macos", "linux"}, + }, + map[string]any{ + "id": "project-venv-win", + "kind": "projectFile", + "projectKind": "environment", + "home": ".venv", + "path": ".venv/Scripts/interp.exe", + "requires": []string{".venv/env.cfg"}, + "platforms": []string{"windows"}, + }, + map[string]any{ + "id": "global-default", + "kind": "setting", + "settingID": "executable", + "layer": "global", + }, + map[string]any{ + "id": "shell-cmd", + "kind": "command", + "command": "synthetic-interp", + }, + map[string]any{ + "id": "detected", + "kind": "toolchain", + "scope": "installed", + }, + }, + "version": map[string]any{ + "arguments": []string{"--version"}, + "pattern": `SyntheticInterp (\d+(?:\.\d+)*)`, + }, + "commands": []string{"synthetic-interp"}, + "exports": []any{ + map[string]any{"name": "SYNTHETIC_ENV_HOME", "value": "${home}"}, + map[string]any{"name": "SYNTHETIC_INTERP", "value": "${executable}"}, + }, + "pathPrepend": []string{"${home}/bin", "${home}/Scripts"}, + "launch": []string{"${executable}", "${arguments}"}, + }, + }, + } + encoded, err := json.Marshal(manifest) + if err != nil { + t.Fatal(err) + } + return encoded +} + +func setupSyntheticVenv(t *testing.T, anchor, externalBase string) (venvHome, venvExe, prependDir string) { + t.Helper() + venvHome = filepath.Join(anchor, ".venv") + if err := os.MkdirAll(venvHome, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(venvHome, "env.cfg"), []byte("home = external\n"), 0o644); err != nil { + t.Fatal(err) + } + if runtime.GOOS == "windows" { + prependDir = filepath.Join(venvHome, "Scripts") + venvExe = filepath.Join(prependDir, "interp.exe") + writeExecutable(t, venvExe) + return venvHome, venvExe, prependDir + } + baseExe := filepath.Join(externalBase, "bin", "interp3.12") + writeExecutable(t, baseExe) + prependDir = filepath.Join(venvHome, "bin") + if err := os.MkdirAll(prependDir, 0o755); err != nil { + t.Fatal(err) + } + // Create a two-hop symlink chain (.venv/bin/interp -> interp3 -> externalBase/bin/interp3.12) + // mirroring real macOS/Homebrew/uv virtual environments. + hop := filepath.Join(prependDir, "interp3") + if err := os.Symlink(baseExe, hop); err != nil { + t.Fatal(err) + } + venvExe = filepath.Join(prependDir, "interp") + if err := os.Symlink("interp3", venvExe); err != nil { + t.Fatal(err) + } + return venvHome, venvExe, prependDir +} + +type probeRecorder struct { + mu sync.Mutex + calls []string + outputs map[string]string +} + +func (r *probeRecorder) probe(_ context.Context, executable string, _ []string) (string, int, error) { + cleaned := filepath.Clean(executable) + r.mu.Lock() + r.calls = append(r.calls, cleaned) + out, ok := r.outputs[cleaned] + r.mu.Unlock() + if !ok { + return "", 1, nil + } + return out, 0, nil +} + +func (r *probeRecorder) reset() { + r.mu.Lock() + r.calls = nil + r.mu.Unlock() +} + +func (r *probeRecorder) snapshot() []string { + r.mu.Lock() + defer r.mu.Unlock() + return append([]string(nil), r.calls...) +} + +func TestUntrustedProjectEnvironmentNeverProbesWorkspaceExecutables(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + kernel := core.NewClient() + settingsDir := filepath.Join(t.TempDir(), "app-settings") + root := canonical(t, t.TempDir()) + home := canonical(t, t.TempDir()) + externalBase := canonical(t, t.TempDir()) + + venvHome, venvExe, _ := setupSyntheticVenv(t, root, externalBase) + // Also place a sneaky workspace executable on Lookup (simulating a modified PATH) + // to verify probeAll blocks workspace code from every candidate channel until trusted. + sneakyExe := filepath.Join(root, "sneaky", "bin", "interp") + if runtime.GOOS == "windows" { + sneakyExe = filepath.Join(root, "sneaky", "Scripts", "interp.exe") + } + writeExecutable(t, sneakyExe) + + recorder := &probeRecorder{ + outputs: map[string]string{ + filepath.Clean(venvExe): "SyntheticInterp 3.12.4\n", + filepath.Clean(sneakyExe): "SyntheticInterp 9.9.9\n", + }, + } + options := Options{ + GlobalRoot: settingsDir, + Platform: PlatformName(runtime.GOOS), + Home: home, + Environment: map[string]string{}, + Probe: recorder.probe, + Lookup: func(command string) (string, error) { + if command == "synthetic-interp" { + return sneakyExe, nil + } + return "", errors.New("not found") + }, + } + manifests := []json.RawMessage{syntheticProjectEnvManifest(t)} + const toolID = "dev.lithe.test.projectenv:interp" + + snapshot, err := Load(ctx, kernel, root, ".", manifests, options) + if err != nil { + t.Fatal(err) + } + if snapshot.ProjectCodeAllowed { + t.Fatal("fresh workspace was trusted without explicit local user action") + } + if calls := recorder.snapshot(); len(calls) != 0 { + t.Fatalf("untrusted workspace ran version probes on %v, want zero probes", calls) + } + if len(snapshot.Tools) != 1 { + t.Fatalf("tools = %+v", snapshot.Tools) + } + tool := snapshot.Tools[0] + if tool.Effective != nil { + t.Fatalf("untrusted workspace resolved %+v, want nil", tool.Effective) + } + if len(tool.Project) != 1 || tool.Project[0].Reason != "projectCodeRequiresAction" || tool.Project[0].Executable != "" || filepath.Clean(tool.Project[0].Home) != filepath.Clean(venvHome) { + t.Fatalf("project candidates = %+v, want blocked .venv without executable probe target", tool.Project) + } + + _, err = Resolve(ctx, kernel, root, ".", toolID, "", nil, manifests, options) + var unavailable *UnavailableError + if !errors.As(err, &unavailable) || unavailable.Code != "projectCodeRequiresAction" { + t.Fatalf("Resolve error = %v, want projectCodeRequiresAction", err) + } + if calls := recorder.snapshot(); len(calls) != 0 { + t.Fatalf("untrusted Resolve ran version probes on %v", calls) + } + if _, statErr := os.Stat(filepath.Join(root, ".lithe")); !errors.Is(statErr, os.ErrNotExist) { + t.Fatalf("untrusted load/resolve wrote workspace .lithe: %v", statErr) + } + if _, statErr := os.Stat(settingsDir); !errors.Is(statErr, os.ErrNotExist) { + t.Fatalf("reading untrusted state created settings directory: %v", statErr) + } +} + +func TestTrustedWorkspacePersistsInLocalSettingsOnlyAndResolvesSymlinkedVenv(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second) + defer cancel() + kernel := core.NewClient() + settingsDir := filepath.Join(t.TempDir(), "app-settings") + root := canonical(t, t.TempDir()) + otherRoot := canonical(t, t.TempDir()) + home := canonical(t, t.TempDir()) + externalBase := canonical(t, t.TempDir()) + + venvHome, venvExe, prependDir := setupSyntheticVenv(t, root, externalBase) + _, otherExe, _ := setupSyntheticVenv(t, otherRoot, externalBase) + + recorder := &probeRecorder{ + outputs: map[string]string{ + filepath.Clean(venvExe): "SyntheticInterp 3.12.4\n", + filepath.Clean(otherExe): "SyntheticInterp 3.11.0\n", + }, + } + options := Options{ + GlobalRoot: settingsDir, + Platform: PlatformName(runtime.GOOS), + Home: home, + Environment: map[string]string{}, + Probe: recorder.probe, + Lookup: func(string) (string, error) { return "", errors.New("not found") }, + } + manifests := []json.RawMessage{syntheticProjectEnvManifest(t)} + const toolID = "dev.lithe.test.projectenv:interp" + + initial, err := Load(ctx, kernel, root, ".", manifests, options) + if err != nil { + t.Fatal(err) + } + // Revoking trust when already untrusted is a no-op and creates no file. + if changed, err := initial.SaveWorkspaceTrust(ctx, kernel, false); err != nil || changed { + t.Fatalf("no-op revoke = %v, %v", changed, err) + } + if _, statErr := os.Stat(filepath.Join(settingsDir, "toolchains", "global.json")); !errors.Is(statErr, os.ErrNotExist) { + t.Fatalf("no-op revoke created global.json: %v", statErr) + } + + // Grant trust for root: stored in settingsDir/toolchains/global.json, NEVER in root/.lithe. + if changed, err := initial.SaveWorkspaceTrust(ctx, kernel, true); err != nil || !changed { + t.Fatalf("grant workspace trust = %v, %v", changed, err) + } + if _, statErr := os.Stat(filepath.Join(root, ".lithe")); !errors.Is(statErr, os.ErrNotExist) { + t.Fatalf("granting workspace trust wrote inside workspace .lithe: %v", statErr) + } + storedBytes, err := os.ReadFile(filepath.Join(settingsDir, "toolchains", "global.json")) + if err != nil { + t.Fatalf("expected local trust file in settingsDir: %v", err) + } + if !strings.Contains(string(storedBytes), "trustedWorkspaces") { + t.Fatalf("global.json missing trustedWorkspaces: %s", storedBytes) + } + + recorder.reset() + trustedSnapshot, err := Load(ctx, kernel, root, ".", manifests, options) + if err != nil { + t.Fatal(err) + } + if !trustedSnapshot.ProjectCodeAllowed { + t.Fatal("reloaded snapshot did not reflect local workspace trust") + } + calls := recorder.snapshot() + if len(calls) != 1 || filepath.Clean(calls[0]) != filepath.Clean(venvExe) { + t.Fatalf("probed executables = %v, want literal [%s]", calls, filepath.Clean(venvExe)) + } + tool := trustedSnapshot.Tools[0] + if tool.Effective == nil || filepath.Clean(tool.Effective.Executable) != filepath.Clean(venvExe) { + t.Fatalf("effective selection = %+v, want literal venv executable %q", tool.Effective, venvExe) + } + if tool.Effective.Version != "3.12.4" || tool.Effective.Layer != "project" || !tool.Effective.ProjectCode { + t.Fatalf("effective metadata = %+v", tool.Effective) + } + if filepath.Clean(tool.Effective.Environment["SYNTHETIC_ENV_HOME"]) != filepath.Clean(venvHome) || + filepath.Clean(tool.Effective.Environment["SYNTHETIC_INTERP"]) != filepath.Clean(venvExe) { + t.Fatalf("effective exports = %+v", tool.Effective.Environment) + } + if len(tool.Effective.PathPrepend) != 1 || filepath.Clean(tool.Effective.PathPrepend[0]) != filepath.Clean(prependDir) { + t.Fatalf("effective pathPrepend = %+v, want [%s]", tool.Effective.PathPrepend, prependDir) + } + if filepath.Clean(tool.AutomaticHome) != filepath.Clean(venvHome) { + t.Fatalf("automaticHome = %q, want %q", tool.AutomaticHome, venvHome) + } + + selected, err := Resolve(ctx, kernel, root, ".", toolID, "", nil, manifests, options) + if err != nil { + t.Fatal(err) + } + if filepath.Clean(selected.Executable) != filepath.Clean(venvExe) { + t.Fatalf("Resolve executable = %q, want literal %q", selected.Executable, venvExe) + } + + // Another workspace on the same machine remains untrusted and unprobed. + recorder.reset() + otherSnapshot, err := Load(ctx, kernel, otherRoot, ".", manifests, options) + if err != nil { + t.Fatal(err) + } + if otherSnapshot.ProjectCodeAllowed || len(recorder.snapshot()) != 0 { + t.Fatalf("trust leaked to another workspace: allowed=%v probes=%v", otherSnapshot.ProjectCodeAllowed, recorder.snapshot()) + } + + // Revoking trust immediately stops probing and selecting the workspace environment. + if changed, err := trustedSnapshot.SaveWorkspaceTrust(ctx, kernel, false); err != nil || !changed { + t.Fatalf("revoke workspace trust = %v, %v", changed, err) + } + recorder.reset() + revokedSnapshot, err := Load(ctx, kernel, root, ".", manifests, options) + if err != nil { + t.Fatal(err) + } + if revokedSnapshot.ProjectCodeAllowed || revokedSnapshot.Tools[0].Effective != nil || len(recorder.snapshot()) != 0 { + t.Fatalf("revoked workspace still probed or resolved: allowed=%v effective=%+v probes=%v", + revokedSnapshot.ProjectCodeAllowed, revokedSnapshot.Tools[0].Effective, recorder.snapshot()) + } + if _, statErr := os.Stat(filepath.Join(root, ".lithe")); !errors.Is(statErr, os.ErrNotExist) { + t.Fatalf("revoking workspace trust wrote inside workspace .lithe: %v", statErr) + } +} + +func TestTrustedWorkspaceResolvesSubdirectoryEnvironmentAndRejectsEscapingDirectories(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + kernel := core.NewClient() + settingsDir := filepath.Join(t.TempDir(), "app-settings") + root := canonical(t, t.TempDir()) + home := canonical(t, t.TempDir()) + externalBase := canonical(t, t.TempDir()) + + subdir := filepath.Join(root, "services", "worker") + if err := os.MkdirAll(subdir, 0o755); err != nil { + t.Fatal(err) + } + subVenvHome, subVenvExe, _ := setupSyntheticVenv(t, subdir, externalBase) + + recorder := &probeRecorder{ + outputs: map[string]string{ + filepath.Clean(subVenvExe): "SyntheticInterp 3.13.1\n", + }, + } + options := Options{ + GlobalRoot: settingsDir, + Platform: PlatformName(runtime.GOOS), + Home: home, + Environment: map[string]string{}, + Probe: recorder.probe, + Lookup: func(string) (string, error) { return "", errors.New("not found") }, + } + manifests := []json.RawMessage{syntheticProjectEnvManifest(t)} + const toolID = "dev.lithe.test.projectenv:interp" + + initial, err := Load(ctx, kernel, root, "services/worker", manifests, options) + if err != nil { + t.Fatal(err) + } + if _, err := initial.SaveWorkspaceTrust(ctx, kernel, true); err != nil { + t.Fatal(err) + } + + selected, err := Resolve(ctx, kernel, root, "services/worker", toolID, "", nil, manifests, options) + if err != nil { + t.Fatalf("subdirectory Resolve failed: %v", err) + } + if filepath.Clean(selected.Executable) != filepath.Clean(subVenvExe) || selected.Home == nil || filepath.Clean(*selected.Home) != filepath.Clean(subVenvHome) { + t.Fatalf("subdirectory selection = %+v, want %q in %q", selected, subVenvExe, subVenvHome) + } + + // Replace root/.venv with a directory link escaping outside the workspace: + // Core must reject it as unsafePath BEFORE any probe is executed. + outsideEnv := canonical(t, t.TempDir()) + _, escapedTargetExe, _ := setupSyntheticVenv(t, outsideEnv, externalBase) + linkToolchainDirectory(t, filepath.Join(outsideEnv, ".venv"), filepath.Join(root, ".venv")) + escapedLexicalExe := filepath.Join(root, ".venv", "bin", "interp") + if runtime.GOOS == "windows" { + escapedLexicalExe = filepath.Join(root, ".venv", "Scripts", "interp.exe") + } + recorder.outputs[filepath.Clean(escapedLexicalExe)] = "SyntheticInterp 9.9.9\n" + recorder.outputs[filepath.Clean(escapedTargetExe)] = "SyntheticInterp 9.9.9\n" + recorder.reset() + + _, err = Resolve(ctx, kernel, root, ".", toolID, "", nil, manifests, options) + var unavailable *UnavailableError + if !errors.As(err, &unavailable) || unavailable.Code != "unsafePath" { + t.Fatalf("escaping .venv error = %v, want unsafePath", err) + } + if calls := recorder.snapshot(); len(calls) != 0 { + t.Fatalf("escaping directory symlink was probed: %v", calls) + } +} + +func TestSaveWorkspaceTrustRejectsReplacedWorkspaceDirectory(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + kernel := core.NewClient() + settingsDir := filepath.Join(t.TempDir(), "app-settings") + parent := canonical(t, t.TempDir()) + workspaceDir := filepath.Join(parent, "project") + if err := os.MkdirAll(workspaceDir, 0o755); err != nil { + t.Fatal(err) + } + options := Options{ + GlobalRoot: settingsDir, + Platform: PlatformName(runtime.GOOS), + Home: t.TempDir(), + Environment: map[string]string{}, + Lookup: func(string) (string, error) { return "", errors.New("not found") }, + } + snapshot, err := Load(ctx, kernel, workspaceDir, ".", nil, options) + if err != nil { + t.Fatal(err) + } + if err := os.Rename(workspaceDir, workspaceDir+"-old"); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(workspaceDir, 0o755); err != nil { + t.Fatal(err) + } + if _, err := snapshot.SaveWorkspaceTrust(ctx, kernel, true); !errors.Is(err, ErrPinConflict) { + t.Fatalf("replaced workspace error = %v, want ErrPinConflict", err) + } + if _, statErr := os.Stat(filepath.Join(settingsDir, "toolchains", "global.json")); !errors.Is(statErr, os.ErrNotExist) { + t.Fatalf("replaced workspace wrote global.json: %v", statErr) + } +} diff --git a/desktop/internal/toolchain/scan.go b/desktop/internal/toolchain/scan.go index 6926b91905..47535ab4ca 100644 --- a/desktop/internal/toolchain/scan.go +++ b/desktop/internal/toolchain/scan.go @@ -180,6 +180,66 @@ func (w *workspace) observe(name string) core.ToolchainFileFact { return fact } +// observeChain observes base, every path segment from base down to target, and +// any resolved symbolic-link target so Core can verify both parent containment +// and target executable identity. +func (w *workspace) observeChain(base, target string) core.ToolchainFileFact { + if target == "" { + return core.ToolchainFileFact{} + } + observeOne := func(name string) core.ToolchainFileFact { + fact := w.observe(name) + if fact.Kind != "missing" && fact.CanonicalPath != "" && fact.CanonicalPath != fact.Path { + w.observe(fact.CanonicalPath) + } + return fact + } + if base == "" { + return observeOne(target) + } + cleanBase := filepath.Clean(base) + cleanTarget := filepath.Clean(target) + observeOne(cleanBase) + relative, err := filepath.Rel(cleanBase, cleanTarget) + if err != nil || relative == "." { + return observeOne(cleanTarget) + } + if relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) { + return observeOne(cleanTarget) + } + current := cleanBase + var last core.ToolchainFileFact + for _, part := range strings.Split(relative, string(filepath.Separator)) { + if part == "" || part == "." { + continue + } + current = filepath.Join(current, part) + last = observeOne(current) + } + return last +} + +// isWorkspaceCode reports whether name or its resolved target lies inside the +// opened workspace root. Any resolution failure fails closed as workspace code. +func (w *workspace) isWorkspaceCode(name string) bool { + if w.root == "" || name == "" { + return false + } + absolute, err := filepath.Abs(name) + if err != nil { + return true + } + cleaned := filepath.Clean(absolute) + if w.insideRoot(cleaned) { + return true + } + canonical, err := canonicalPath(cleaned) + if err != nil { + return true + } + return w.insideRoot(canonical) +} + // all returns the facts in a stable order, which keeps Core's input comparable // between two loads that observed the same native state. func (w *workspace) all() []core.ToolchainFileFact { @@ -371,8 +431,9 @@ func prependPath(home, template string) (string, bool) { // probeAll runs the definition's version probe for every executable Core may // select. Probes are bounded in count, concurrency and time, and every process -// is owned by this call. -func (w *workspace) probeAll(ctx context.Context, definition core.ToolchainToolDefinition, executables []string) []core.ToolchainProbe { +// is owned by this call. Workspace executables are never probed unless +// projectCodeAllowed is true. +func (w *workspace) probeAll(ctx context.Context, definition core.ToolchainToolDefinition, executables []string, projectCodeAllowed bool) []core.ToolchainProbe { // Core returns native absolute paths with portable separators. Pins and // filesystem discovery can name the same Windows file with backslashes or // different case. Probe each native identity once; Core rejects duplicates. @@ -380,6 +441,9 @@ func (w *workspace) probeAll(ctx context.Context, definition core.ToolchainToolD paths := make([]string, 0, len(executables)) for _, executable := range uniqueSorted(executables) { cleaned := filepath.Clean(executable) + if !projectCodeAllowed && w.isWorkspaceCode(cleaned) { + continue + } key := cleaned if !w.caseSensitive { key = strings.ToLower(key) diff --git a/desktop/internal/toolchain/toolchain.go b/desktop/internal/toolchain/toolchain.go index f48ee9d5bc..a63b73daf0 100644 --- a/desktop/internal/toolchain/toolchain.go +++ b/desktop/internal/toolchain/toolchain.go @@ -64,6 +64,7 @@ type Tool struct { Pin *core.ToolchainPin `json:"pin,omitempty"` PinSource string `json:"pinSource,omitempty"` + Project []core.ToolchainProjectCandidate `json:"project,omitempty"` Shell []core.ToolchainShellCandidate `json:"shell"` Installations []core.ToolchainInstallation `json:"installations"` Skipped []core.ToolchainSkippedInstallation `json:"skipped"` @@ -80,12 +81,13 @@ type Tool struct { // Snapshot is everything one settings load read for one project directory. type Snapshot struct { - Global bool `json:"global,omitempty"` - catalog *catalogSource - Root string `json:"root"` - Directory string `json:"directory"` - Tools []Tool `json:"tools"` - Conflicts []core.ToolchainConflict `json:"conflicts"` + Global bool `json:"global,omitempty"` + ProjectCodeAllowed bool `json:"projectCodeAllowed,omitempty"` + catalog *catalogSource + Root string `json:"root"` + Directory string `json:"directory"` + Tools []Tool `json:"tools"` + Conflicts []core.ToolchainConflict `json:"conflicts"` // Baseline is the exact bytes of .lithe/toolchains/local.json that the // snapshot was built from, nil when the file did not exist. Baseline []byte `json:"-"` @@ -97,15 +99,20 @@ type Snapshot struct { // Options configure one load. The zero value uses the host platform, the user's // home, the process environment and a bounded native probe. type Options struct { - // Global permits discovery without any project; GlobalRoot owns the native SDK registry. - Global bool - GlobalRoot string - catalog *core.ToolchainCatalog - Platform string - Home string - Environment map[string]string - Probe ProbeFunc - Lookup LookupFunc + // Global permits discovery without any project; GlobalRoot owns the native SDK + // registry and per-workspace toolchain trust in user application settings. + Global bool + GlobalRoot string + // ProjectCodeAllowed grants probing and selection of workspace-local tool + // candidates only when GlobalRoot is unset in unit tests. Production loads and + // launches always supply GlobalRoot so trust comes solely from local storage. + ProjectCodeAllowed bool + catalog *core.ToolchainCatalog + Platform string + Home string + Environment map[string]string + Probe ProbeFunc + Lookup LookupFunc // MinimumVersion is a consumer requirement for one operation; settings // loads leave it empty. MinimumVersion string diff --git a/desktop/internal/workbench/debug_launch.go b/desktop/internal/workbench/debug_launch.go index a67843511d..deb07afa4e 100644 --- a/desktop/internal/workbench/debug_launch.go +++ b/desktop/internal/workbench/debug_launch.go @@ -81,7 +81,7 @@ func (a *App) resolveAdapterProcess(ctx context.Context, adapter debugAdapter, p if err != nil { return "", nil, nil, err } - selected, err = toolchain.Resolve(ctx, a.kernel, root, ".", plan.Launch.Tool, plan.Launch.MinimumVersion, &toolchain.Fixed{Executable: runtime}, manifests, toolchain.Options{Platform: buildPlatform()}) + selected, err = toolchain.Resolve(ctx, a.kernel, root, ".", plan.Launch.Tool, plan.Launch.MinimumVersion, &toolchain.Fixed{Executable: runtime}, manifests, toolchain.Options{Platform: buildPlatform(), GlobalRoot: a.globalToolchainRoot()}) if err != nil { return "", nil, nil, err } @@ -227,14 +227,32 @@ func (a *App) prepareDebugLaunch(ctx context.Context, start debugStart, stateDir if planned.Connection != nil && planned.Connection.Remote && !start.confirmed { return preparedDebugLaunch{}, &debugRemoteError{host: planned.Connection.Host, port: planned.Connection.Port} } - for _, directory := range plan.RequiredDirectories { - relative, err := filepath.Rel(stateDirectory, directory) - if err != nil { - return preparedDebugLaunch{}, adapterUnresolved(err) + for _, slot := range plan.RequiredDirectories { + var directory string + switch slot { + case "state": + directory = directories.StateDirectory + case "workspaceState": + directory = directories.WorkspaceStateDirectory + case "log": + directory = directories.LogDirectory + case "temporary": + directory = directories.TemporaryDirectory + default: + return preparedDebugLaunch{}, adapterUnresolved(errors.New(unavailable)) } - if relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) || filepath.IsAbs(relative) { + if directory == "" || !filepath.IsAbs(directory) { return preparedDebugLaunch{}, adapterUnresolved(errors.New(unavailable)) } + if slot != "log" { + relative, err := filepath.Rel(stateDirectory, directory) + if err != nil { + return preparedDebugLaunch{}, adapterUnresolved(err) + } + if relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) || filepath.IsAbs(relative) { + return preparedDebugLaunch{}, adapterUnresolved(errors.New(unavailable)) + } + } if err := ctx.Err(); err != nil { return preparedDebugLaunch{}, err } diff --git a/desktop/internal/workbench/debug_launch_test.go b/desktop/internal/workbench/debug_launch_test.go index 58b1e18b05..5b4a38963d 100644 --- a/desktop/internal/workbench/debug_launch_test.go +++ b/desktop/internal/workbench/debug_launch_test.go @@ -215,3 +215,49 @@ func TestDebugReadsProgramFromActualPluginSettingSources(t *testing.T) { }) } } + +func TestDebugRequiredDirectoriesCreateStateAndLogSlots(t *testing.T) { + h := debugHarness(t) + p := openDebugPanel(t, h, t.TempDir()) + adapter := p.debug.adapters[0] + var manifest map[string]any + if err := json.Unmarshal(adapter.Manifest, &manifest); err != nil { + t.Fatal(err) + } + process := manifest["debugAdapters"].([]any)[0].(map[string]any)["launch"].(map[string]any)["process"].(map[string]any) + process["arguments"] = []any{"-test.run=^TestDebugAdapterRunner$", "--state=${stateDir}", "--workspace-state=${workspaceStateDir}", "--log-dir=${logDir}"} + var err error + adapter.Manifest, err = json.Marshal(manifest) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(adapter.Directory, "plugin.json"), adapter.Manifest, 0o600); err != nil { + t.Fatal(err) + } + logRoot := filepath.Join(t.TempDir(), "logs", "plugins", adapter.PluginID, "files") + h.app.logSink = &pluginFilesLog{directory: logRoot} + t.Cleanup(func() { h.app.logSink = nil }) + + stateRoot := filepath.Join(t.TempDir(), "state") + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + plan, err := h.app.prepareDebugLaunch(ctx, debugStart{adapter: adapter, request: "launch"}, stateRoot, p.root, "", 1, "unavailable") + if err != nil { + t.Fatalf("prepareDebugLaunch failed for RequiredDirectories slots: %v", err) + } + for _, wantDir := range []string{stateRoot, filepath.Join(stateRoot, "workspace"), logRoot} { + info, statErr := os.Stat(wantDir) + if statErr != nil || !info.IsDir() { + t.Fatalf("required directory %q not created: %v", wantDir, statErr) + } + } + expected := []string{ + "-test.run=^TestDebugAdapterRunner$", + "--state=" + stateRoot, + "--workspace-state=" + filepath.Join(stateRoot, "workspace"), + "--log-dir=" + logRoot, + } + if !reflect.DeepEqual(plan.Arguments, expected) { + t.Fatalf("arguments = %v, want %v", plan.Arguments, expected) + } +} diff --git a/desktop/internal/workbench/settings_toolchains.go b/desktop/internal/workbench/settings_toolchains.go index 219e80b9a8..f51a2790f8 100644 --- a/desktop/internal/workbench/settings_toolchains.go +++ b/desktop/internal/workbench/settings_toolchains.go @@ -17,7 +17,7 @@ func (s settingsToolchains) Inspect(ctx context.Context, snapshot toolchain.Snap if readErr != nil { return selection, readErr } - return toolchain.Resolve(ctx, s.app.kernel, "", ".", tool, "", &toolchain.Fixed{Home: home}, manifests, toolchain.Options{Global: true, GlobalRoot: s.app.store.Dir(), Platform: buildPlatform()}) + return toolchain.Resolve(ctx, s.app.kernel, "", ".", tool, "", &toolchain.Fixed{Home: home}, manifests, toolchain.Options{Global: true, GlobalRoot: s.app.globalToolchainRoot(), Platform: buildPlatform()}) } root := s.app.toolchainRoot.Load() if root == nil || snapshot.Root == "" { @@ -30,7 +30,7 @@ func (s settingsToolchains) Inspect(ctx context.Context, snapshot toolchain.Snap if err != nil { return selection, err } - selection, err = toolchain.Resolve(ctx, s.app.kernel, snapshot.Root, snapshot.Directory, tool, "", &toolchain.Fixed{Home: home}, manifests, toolchain.Options{Platform: buildPlatform(), GlobalRoot: s.app.store.Dir()}) + selection, err = toolchain.Resolve(ctx, s.app.kernel, snapshot.Root, snapshot.Directory, tool, "", &toolchain.Fixed{Home: home}, manifests, toolchain.Options{Platform: buildPlatform(), GlobalRoot: s.app.globalToolchainRoot()}) if err != nil { return selection, err } @@ -40,6 +40,33 @@ func (s settingsToolchains) Inspect(ctx context.Context, snapshot toolchain.Snap return selection, snapshot.CheckWorkspace(ctx, *root) } +// SetWorkspaceTrust grants or revokes machine-local permission to probe and run +// tool environments or wrappers inside the open project, then reloads toolchains. +func (s settingsToolchains) SetWorkspaceTrust(ctx context.Context, snapshot toolchain.Snapshot, trusted bool) (updated toolchain.Snapshot, err error) { + if trusted { + ctx = s.app.performedIn(ctx, "toolchain.workspaceTrust.grant", surfaceButton) + } else { + ctx = s.app.performedIn(ctx, "toolchain.workspaceTrust.revoke", surfaceButton) + } + defer func() { s.recordFailure(ctx, "toolchain_settings_trust", err) }() + root := s.app.toolchainRoot.Load() + if snapshot.Global || root == nil || *root == "" || snapshot.Root == "" { + return snapshot, toolchain.ErrPinConflict + } + if err := snapshot.CheckWorkspace(ctx, *root); err != nil { + return snapshot, errors.Join(toolchain.ErrPinConflict, err) + } + if _, err := snapshot.SaveWorkspaceTrust(ctx, s.app.kernel, trusted); err != nil { + return snapshot, err + } + s.app.post(func(a *App) { a.retryFailedPluginServers() }) + updated, err = s.loadAt(ctx, snapshot.Root) + if err != nil { + return snapshot, 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. @@ -68,7 +95,7 @@ func (s settingsToolchains) LoadScope(ctx context.Context, scope string) (snapsh if err != nil { return snapshot, err } - return toolchain.Load(ctx, s.app.kernel, "", ".", manifests, toolchain.Options{Global: true, GlobalRoot: s.app.store.Dir(), Platform: buildPlatform()}) + return toolchain.Load(ctx, s.app.kernel, "", ".", manifests, toolchain.Options{Global: true, GlobalRoot: s.app.globalToolchainRoot(), Platform: buildPlatform()}) } func (s settingsToolchains) loadAt(ctx context.Context, root string) (toolchain.Snapshot, error) { @@ -76,7 +103,7 @@ func (s settingsToolchains) loadAt(ctx context.Context, root string) (toolchain. if err != nil && len(manifests) == 0 { return toolchain.Snapshot{}, err } - return toolchain.Load(ctx, s.app.kernel, root, ".", manifests, toolchain.Options{Platform: buildPlatform(), GlobalRoot: s.app.store.Dir()}) + return toolchain.Load(ctx, s.app.kernel, root, ".", manifests, toolchain.Options{Platform: buildPlatform(), GlobalRoot: s.app.globalToolchainRoot()}) } // Save applies all draft changes in one Core edit, against the exact diff --git a/desktop/internal/workbench/settings_toolchains_test.go b/desktop/internal/workbench/settings_toolchains_test.go index 24976ff588..5b614d1450 100644 --- a/desktop/internal/workbench/settings_toolchains_test.go +++ b/desktop/internal/workbench/settings_toolchains_test.go @@ -5,12 +5,16 @@ import ( "context" "encoding/json" "errors" + "fmt" "os" "path/filepath" + "runtime" + "sync" "testing" "time" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/logwindow" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginstate" @@ -257,3 +261,259 @@ func TestToolchainSettingsReadbackFailureReportsCommittedSource(t *testing.T) { t.Fatalf("test did not exercise a committed pin: %s", data) } } + +const syntheticWorkbenchInterpMarkerEnv = "LITHE_TEST_SYNTHETIC_INTERP_MARKER" + +func TestMain(m *testing.M) { + if marker := os.Getenv(syntheticWorkbenchInterpMarkerEnv); marker != "" && len(os.Args) == 2 && os.Args[1] == "--version" { + _ = os.WriteFile(marker, []byte("probed\n"), 0o600) + fmt.Println("SyntheticInterp 3.12.4") + os.Exit(0) + } + os.Exit(m.Run()) +} + +type actionFieldLog struct { + logwindow.Source + mu sync.Mutex + actions []string + failed []string +} + +func (l *actionFieldLog) Emit(_ core.LogLevel, event, _ string, fields map[string]any) { + l.mu.Lock() + defer l.mu.Unlock() + switch event { + case "app.action.performed": + if action, ok := fields["action"].(string); ok { + l.actions = append(l.actions, action) + } + case "app.notification.operation_failed": + if op, ok := fields["operation"].(string); ok { + l.failed = append(l.failed, op) + } + } +} + +func TestWorkbenchToolchainTrustPersistsLocallyLogsActionAndEnablesRuntimeResolution(t *testing.T) { + preferences := store.At(t.TempDir()) + pluginsRoot := t.TempDir() + workspaceRaw := t.TempDir() + workspaceRoot, err := filepath.EvalSymlinks(workspaceRaw) + if err != nil { + t.Fatal(err) + } + externalRaw := t.TempDir() + externalBase, err := filepath.EvalSymlinks(externalRaw) + if err != nil { + t.Fatal(err) + } + markerPath := filepath.Join(t.TempDir(), "probe-ran.marker") + + const pluginID = "dev.lithe.test.projectenv" + const toolID = pluginID + ":interp" + manifestDoc := map[string]any{ + "schemaVersion": 0, + "id": pluginID, + "displayName": "Synthetic Project Environment", + "version": "1.0.0", + "pluginAPIVersion": 0, + "requires": map[string]any{"toolDefinitions": 0}, + "vendor": map[string]any{ + "id": "dev.lithe.test", + "displayName": "Synthetic Test Vendor", + "signatureRequirement": "publisherPackage", + }, + "permissions": []any{}, + "toolDefinitions": []any{ + map[string]any{ + "id": toolID, + "displayName": "Synthetic Interpreter", + "executableLayouts": []any{ + map[string]any{"path": "bin/interp", "platforms": []string{"macos", "linux"}}, + map[string]any{"path": "Scripts/interp.exe", "platforms": []string{"windows"}}, + }, + "executables": []any{ + map[string]any{ + "id": "project-venv-unix", + "kind": "projectFile", + "projectKind": "environment", + "home": ".venv", + "path": ".venv/bin/interp", + "requires": []string{".venv/env.cfg"}, + "platforms": []string{"macos", "linux"}, + }, + map[string]any{ + "id": "project-venv-win", + "kind": "projectFile", + "projectKind": "environment", + "home": ".venv", + "path": ".venv/Scripts/interp.exe", + "requires": []string{".venv/env.cfg"}, + "platforms": []string{"windows"}, + }, + map[string]any{ + "id": "shell-cmd", + "kind": "command", + "command": "nonexistent-synthetic-interp", + }, + }, + "version": map[string]any{ + "arguments": []string{"--version"}, + "pattern": `SyntheticInterp (\d+(?:\.\d+)*)`, + }, + "commands": []string{"nonexistent-synthetic-interp"}, + "exports": []any{map[string]any{"name": "SYNTHETIC_ENV_HOME", "value": "${home}"}}, + "pathPrepend": []string{"${home}/bin", "${home}/Scripts"}, + "launch": []string{"${executable}", "${arguments}"}, + }, + }, + } + manifestBytes, err := json.Marshal(manifestDoc) + if err != nil { + t.Fatal(err) + } + + service, err := pluginservice.Open(core.NewClient(), preferences, pluginsRoot) + if err != nil { + t.Fatal(err) + } + staging, err := pluginpkg.NewStaging(pluginsRoot) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(staging, pluginpkg.ManifestFile), manifestBytes, 0o600); err != nil { + t.Fatal(err) + } + if _, err := pluginpkg.Install(pluginsRoot, pluginID, "1.0.0", staging); err != nil { + t.Fatal(err) + } + if err := pluginstate.New(preferences).SetEnabled(pluginID, true); err != nil { + t.Fatal(err) + } + + venvHome := filepath.Join(workspaceRoot, ".venv") + if err := os.MkdirAll(venvHome, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(venvHome, "env.cfg"), []byte("home = external\n"), 0o644); err != nil { + t.Fatal(err) + } + var venvExe string + if runtime.GOOS == "windows" { + t.Setenv(syntheticWorkbenchInterpMarkerEnv, markerPath) + scriptsDir := filepath.Join(venvHome, "Scripts") + if err := os.MkdirAll(scriptsDir, 0o755); err != nil { + t.Fatal(err) + } + venvExe = filepath.Join(scriptsDir, "interp.exe") + copyTestBinary(t, venvExe) + } else { + baseBin := filepath.Join(externalBase, "bin") + if err := os.MkdirAll(baseBin, 0o755); err != nil { + t.Fatal(err) + } + baseExe := filepath.Join(baseBin, "interp3.12") + script := fmt.Sprintf("#!/bin/sh\nprintf 'probed\\n' > %q\nprintf 'SyntheticInterp 3.12.4\\n'\n", markerPath) + if err := os.WriteFile(baseExe, []byte(script), 0o755); err != nil { + t.Fatal(err) + } + venvBin := filepath.Join(venvHome, "bin") + if err := os.MkdirAll(venvBin, 0o755); err != nil { + t.Fatal(err) + } + venvExe = filepath.Join(venvBin, "interp") + if err := os.Symlink(baseExe, venvExe); err != nil { + t.Fatal(err) + } + } + + logs := &actionFieldLog{} + app := &App{kernel: &testKernel{Client: core.NewClient()}, store: preferences, plugins: service, logSink: logs} + app.toolchainRoot.Store(&workspaceRoot) + + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + adapter := settingsToolchains{app: app} + + // 1. Untrusted load & runtime resolution: NEVER executes the probe, returns projectCodeRequiresAction. + initial, err := adapter.Load(ctx) + if err != nil { + t.Fatal(err) + } + if initial.ProjectCodeAllowed { + t.Fatal("fresh project was trusted without user action") + } + if _, err := app.resolveToolchainSelection(ctx, workspaceRoot, ".", toolID, ""); err == nil { + t.Fatal("untrusted runtime resolution succeeded unexpectedly") + } else { + var unavailable *toolchain.UnavailableError + if !errors.As(err, &unavailable) || unavailable.Code != "projectCodeRequiresAction" { + t.Fatalf("untrusted resolveToolchainSelection = %v, want projectCodeRequiresAction", err) + } + } + if _, statErr := os.Stat(markerPath); !errors.Is(statErr, os.ErrNotExist) { + t.Fatalf("untrusted load/resolve executed workspace probe: %v", statErr) + } + + // 2. Grant trust: logs action, stores only in preferences.Dir()/toolchains/global.json, reloads & resolves. + trusted, err := adapter.SetWorkspaceTrust(ctx, initial, true) + if err != nil { + t.Fatal(err) + } + if !trusted.ProjectCodeAllowed || len(trusted.Tools) != 1 || trusted.Tools[0].Effective == nil { + t.Fatalf("trusted snapshot = %+v", trusted) + } + if filepath.Clean(trusted.Tools[0].AutomaticHome) != filepath.Clean(venvHome) || + filepath.Clean(trusted.Tools[0].Effective.Executable) != filepath.Clean(venvExe) { + t.Fatalf("trusted snapshot tool = %+v", trusted.Tools[0]) + } + if _, statErr := os.Stat(markerPath); statErr != nil { + t.Fatalf("trusted load did not probe .venv interpreter: %v", statErr) + } + if _, statErr := os.Stat(filepath.Join(workspaceRoot, ".lithe")); !errors.Is(statErr, os.ErrNotExist) { + t.Fatalf("workspace trust wrote inside workspace .lithe: %v", statErr) + } + if _, statErr := os.Stat(filepath.Join(preferences.Dir(), "toolchains", "global.json")); statErr != nil { + t.Fatalf("workspace trust missing from local store: %v", statErr) + } + + // Build/Run/Debug shared resolver reads the same local trust and selects .venv. + selected, err := app.resolveToolchainSelection(ctx, workspaceRoot, ".", toolID, "") + if err != nil { + t.Fatalf("trusted resolveToolchainSelection failed: %v", err) + } + if filepath.Clean(selected.Executable) != filepath.Clean(venvExe) || selected.Version != "3.12.4" { + t.Fatalf("trusted selection = %+v, want %q 3.12.4", selected, venvExe) + } + + // 3. Revoke trust: logs action, removes probes on reload, blocks runtime resolution again. + if err := os.Remove(markerPath); err != nil { + t.Fatal(err) + } + revoked, err := adapter.SetWorkspaceTrust(ctx, trusted, false) + if err != nil { + t.Fatal(err) + } + if revoked.ProjectCodeAllowed || revoked.Tools[0].Effective != nil { + t.Fatalf("revoked snapshot = %+v", revoked) + } + if _, err := app.resolveToolchainSelection(ctx, workspaceRoot, ".", toolID, ""); err == nil { + t.Fatal("revoked workspace still resolved project environment") + } + if _, statErr := os.Stat(markerPath); !errors.Is(statErr, os.ErrNotExist) { + t.Fatalf("revoked workspace executed probe: %v", statErr) + } + + logs.mu.Lock() + gotActions := append([]string(nil), logs.actions...) + gotFailed := append([]string(nil), logs.failed...) + logs.mu.Unlock() + wantActions := []string{"toolchain.workspaceTrust.grant", "toolchain.workspaceTrust.revoke"} + if len(gotActions) != len(wantActions) || gotActions[0] != wantActions[0] || gotActions[1] != wantActions[1] { + t.Fatalf("logged actions = %v, want %v", gotActions, wantActions) + } + if len(gotFailed) != 0 { + t.Fatalf("unexpected operation failures logged: %v", gotFailed) + } +} diff --git a/desktop/internal/workbench/toolchains.go b/desktop/internal/workbench/toolchains.go index 80c311d151..a7dd88e103 100644 --- a/desktop/internal/workbench/toolchains.go +++ b/desktop/internal/workbench/toolchains.go @@ -49,6 +49,13 @@ func (a *App) resolveToolchainSelection(ctx context.Context, root, directory, to return a.defaultToolchainSelection(ctx, root, directory, tool, minimumVersion) } +func (a *App) globalToolchainRoot() string { + if a.store == nil { + return "" + } + return a.store.Dir() +} + func (a *App) defaultToolchainSelection(ctx context.Context, root, directory, tool, minimumVersion string) (core.ToolchainSelection, error) { manifests, err := a.toolchainManifests(ctx) if err != nil { @@ -59,7 +66,7 @@ func (a *App) defaultToolchainSelection(ctx context.Context, root, directory, to } return toolchain.Resolve(ctx, a.kernel, root, directory, tool, minimumVersion, nil, manifests, toolchain.Options{ Platform: buildPlatform(), - GlobalRoot: a.store.Dir(), + GlobalRoot: a.globalToolchainRoot(), }) } diff --git a/docs/ci-builds.md b/docs/ci-builds.md index d35be4c257..bf5e4eb86b 100644 --- a/docs/ci-builds.md +++ b/docs/ci-builds.md @@ -144,7 +144,7 @@ SDK 的构建输出,以及对当前工作树的 Core 运行的端到端测试 Windows 工具链和批处理模型的集成测试在 Go `t.TempDir()` 下创建含空格或中文的用户目录、安装目录与项目目录。合成工具只读地硬链接当前测试可执行文件;跨文件系统等情况下回退为复制,脚本与私有工具链配置也只属于该测试。子进程由有界上下文和工作台清理关闭后,Go 删除临时目录。它们不是下载缓存或可封存构建产物,不跨工作树复制或共享,不进入安装包,不改真实用户配置、代码签名或增量更新基线。 -全局 SDK 登记 `/toolchains/global.json` 属于本机用户设置,最多 256 KiB、64 个工具、每个工具 32 个目录;读取不创建来源,确认保存才条件原子写入并重新解析。没有可复用的构建身份,不允许跨工作树复制,不进入安装包,也不写入 SDK 或签名及增量更新基线。 +全局 SDK 登记与工作区项目内工具环境信任记录 `/toolchains/global.json` 属于本机用户设置,最多 256 KiB、64 个工具、每个工具 32 个目录,并按规范化工作区根路径保存用户显式授予的 `projectCodeAllowed` 信任记录(不写入工作区内的 `.lithe/`);读取不创建来源,确认保存或更新信任时才条件原子写入并重新解析。没有可复用的构建身份,不允许跨工作树复制,不进入安装包,也不写入 SDK 或签名及增量更新基线。 原生插件设置的暂存目录: `/lithe-source-settings-/` 只属于一次确认后的保存操作。 diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 67bac14277..c4b92bfa9d 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -27,6 +27,11 @@ native_path() { fi } +# Lithe-core-rust #93 branch commit 86bd06a (update to main squash commit after Lithe-IDEA/Lithe-core-rust#93 +# merges and before gh pr ready): toolchains.discoveryPlan expands projectFile discovery strategies +# along workspace ancestors, toolchains.candidates and toolchains.resolve report project candidates +# and validate symlinked .venv chains, and toolchains.readCatalogForWorkspace / editWorkspaceTrust +# keep per-workspace projectCodeAllowed in the machine-local catalog (#2122). # Lithe-core-rust main at d833d6a, #89 squash-merged (on top of bb4832e, #88): buildProviders 1 # adds runs with entrypoints: true; build.runEntrypointsPlan and build.decodeRunEntrypoints ask a # provider for the entrypoints of one source file, prepareRunPlan takes an entrypoint run without a @@ -214,7 +219,7 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # the contract, plugin guides, reference and SDKs live only in shared/plugins; on top of #16 (reported Git queries folded in the console), # #15 (git.write cherryPick, revert and reset fields), #14 (word-level changed ranges of diff # rows), #13, #8, #7, #6 and #4. -PINNED_CORE_REVISION="d833d6a71dfeaa5eda39d23f6a3a1a9ee29ff9ed" +PINNED_CORE_REVISION="86bd06a6393e543ca72d66c8398a7e0bd6a18971" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in diff --git a/shared/i18n/locales/en-US.json b/shared/i18n/locales/en-US.json index c4ff734a8f..de0f97d4c7 100644 --- a/shared/i18n/locales/en-US.json +++ b/shared/i18n/locales/en-US.json @@ -11519,7 +11519,23 @@ "desktop.runConfig.unavailableVersionUnsupported": "The installed “{plugin}” does not meet the version requirement {requirement}.", "desktop.runConfig.unavailableMissingDirectory": "The working directory “{directory}” no longer exists. Edit the configuration to change it.", "desktop.runConfig.unavailableInvalid": "The run configuration is invalid: {reason}", - "desktop.runConfig.unavailableOther": "This run configuration cannot run now: {reason}" + "desktop.runConfig.unavailableOther": "This run configuration cannot run now: {reason}", + "desktop.toolchains.trustProject": "Trust tool environments in this project", + "desktop.toolchains.trustProjectHelp": "Allows Lithe to probe versions of and run tool environments (such as virtual environments) and wrappers located inside this project folder. Trust applies only to this workspace on this machine, is saved in local application settings rather than .lithe/, and can be revoked at any time. Enable this only for projects from sources you trust; running processes use updated toolchains after restarting.", + "desktop.toolchains.trustStatusTrusted": "This project on this machine · Trusted", + "desktop.toolchains.trustStatusUntrusted": "This project on this machine · Not trusted", + "desktop.toolchains.projectTrustRequiredNotice": "Project tool environments were detected and will not be probed or run until this project is trusted.", + "desktop.toolchains.projectCandidateBlocked": "{path} · Requires trusting this project", + "desktop.toolchains.updatingTrust": "Updating project trust…", + "desktop.toolchains.reasonProjectTrustRequired": "Requires trusting this project", + "desktop.toolchains.reasonProbeFailed": "Version check failed", + "desktop.toolchains.reasonVersionUnsatisfied": "Does not meet minimum version", + "desktop.toolchains.reasonNotExecutable": "File is not executable", + "desktop.toolchains.reasonUnsafePath": "Unsafe or outside allowed root", + "desktop.toolchains.layerPinned": "Pinned", + "desktop.toolchains.layerProject": "Project", + "desktop.toolchains.layerGlobal": "Global", + "desktop.toolchains.layerAutomatic": "Automatic" }, "overrides": { "windows": { diff --git a/shared/i18n/locales/zh-CN.json b/shared/i18n/locales/zh-CN.json index 79f0d56398..d073cfbd7e 100644 --- a/shared/i18n/locales/zh-CN.json +++ b/shared/i18n/locales/zh-CN.json @@ -11519,7 +11519,23 @@ "desktop.runConfig.unavailableVersionUnsupported": "已安装的“{plugin}”版本不满足要求 {requirement}。", "desktop.runConfig.unavailableMissingDirectory": "工作目录“{directory}”不存在了,请编辑配置修改它。", "desktop.runConfig.unavailableInvalid": "运行配置无效:{reason}", - "desktop.runConfig.unavailableOther": "此运行配置现在无法运行:{reason}" + "desktop.runConfig.unavailableOther": "此运行配置现在无法运行:{reason}", + "desktop.toolchains.trustProject": "信任当前项目中的工具环境", + "desktop.toolchains.trustProjectHelp": "允许 Lithe 对当前项目目录内的工具环境(如虚拟环境)和包装器执行版本探测与运行。此授权仅在本机对当前工作区生效,保存在应用本机设置中而不会写入项目 .lithe/,且可随时撤销。请仅对来源可信的项目开启;已运行的进程需重启后使用更新后的工具链。", + "desktop.toolchains.trustStatusTrusted": "本机此项目 · 已信任", + "desktop.toolchains.trustStatusUntrusted": "本机此项目 · 未信任", + "desktop.toolchains.projectTrustRequiredNotice": "检测到项目内的工具环境;在开启项目信任前不会探测版本或运行。", + "desktop.toolchains.projectCandidateBlocked": "{path} · 需信任当前项目后探测与使用", + "desktop.toolchains.updatingTrust": "正在更新项目信任状态…", + "desktop.toolchains.reasonProjectTrustRequired": "需要信任当前项目", + "desktop.toolchains.reasonProbeFailed": "版本检测失败", + "desktop.toolchains.reasonVersionUnsatisfied": "不满足最低版本要求", + "desktop.toolchains.reasonNotExecutable": "文件不可执行", + "desktop.toolchains.reasonUnsafePath": "路径不安全或超出允许目录", + "desktop.toolchains.layerPinned": "已固定", + "desktop.toolchains.layerProject": "项目环境", + "desktop.toolchains.layerGlobal": "全局默认", + "desktop.toolchains.layerAutomatic": "自动发现" }, "overrides": { "macos": { diff --git a/shared/i18n/messages.json b/shared/i18n/messages.json index 8d417679e4..65b24405cd 100644 --- a/shared/i18n/messages.json +++ b/shared/i18n/messages.json @@ -108913,6 +108913,121 @@ "platforms": [ "desktop" ] + }, + { + "id": "desktop.toolchains.trustProject", + "description": "Switch that grants or revokes local permission to probe and run tool environments or wrappers inside the open project.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.toolchains.trustProjectHelp", + "description": "Info popover explaining consequences, local machine storage scope, security boundary and process restart behavior of project toolchain trust.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.toolchains.trustStatusTrusted", + "description": "Compact status label showing that project tool environments are trusted on this machine for the open workspace.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.toolchains.trustStatusUntrusted", + "description": "Compact status label showing that project tool environments are not trusted for the open workspace.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.toolchains.projectTrustRequiredNotice", + "description": "Actionable notice shown when one or more declared tools have project environments or wrappers blocked until the project is trusted.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.toolchains.projectCandidateBlocked", + "description": "Row under a tool card naming a detected project-local environment or wrapper that will not be probed until the project is trusted. {path} is its native home or executable path.", + "platforms": [ + "desktop" + ], + "parameters": { + "path": "string" + } + }, + { + "id": "desktop.toolchains.updatingTrust", + "description": "Shown while saving the workspace toolchain trust setting and reloading effective toolchains.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.toolchains.reasonProjectTrustRequired", + "description": "Localized reason when a tool's resolution or automatic value is blocked until the user trusts project tool environments.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.toolchains.reasonProbeFailed", + "description": "Localized reason when a candidate executable failed its bounded version check.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.toolchains.reasonVersionUnsatisfied", + "description": "Localized reason when a candidate executable does not satisfy the minimum version.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.toolchains.reasonNotExecutable", + "description": "Localized reason when a candidate file is not executable.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.toolchains.reasonUnsafePath", + "description": "Localized reason when a candidate path is unsafe or leaves its allowed root.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.toolchains.layerPinned", + "description": "Localized name of the pinned toolchain resolution layer.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.toolchains.layerProject", + "description": "Localized name of the project toolchain resolution layer.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.toolchains.layerGlobal", + "description": "Localized name of the global default toolchain resolution layer.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.toolchains.layerAutomatic", + "description": "Localized name of the automatic toolchain resolution layer.", + "platforms": [ + "desktop" + ] } ] } diff --git a/shared/platform-feature-matrix/features/plugin-debug-adapters.json b/shared/platform-feature-matrix/features/plugin-debug-adapters.json index 80971b1ca6..809e45f098 100644 --- a/shared/platform-feature-matrix/features/plugin-debug-adapters.json +++ b/shared/platform-feature-matrix/features/plugin-debug-adapters.json @@ -10,6 +10,7 @@ "desktop/internal/pluginservice/debug.go", "desktop/internal/workbench/debug_start.go", "desktop/internal/workbench/debug_launch.go", + "desktop/internal/workbench/debug_launch_test.go", "desktop/internal/workbench/debug_view.go", "desktop/internal/workbench/debug_tcp_test.go", "desktop/internal/workbench/debug_announced.go", @@ -24,6 +25,7 @@ "desktop/internal/pluginservice/debug.go", "desktop/internal/workbench/debug_start.go", "desktop/internal/workbench/debug_launch.go", + "desktop/internal/workbench/debug_launch_test.go", "desktop/internal/workbench/debug_view.go", "desktop/internal/workbench/debug_tcp_test.go", "desktop/internal/workbench/debug_announced.go", @@ -33,7 +35,7 @@ }, "owner": "Debug", "verification": "macOS:安装声明了 debugAdapters 的插件,在其语言文件上启动调试,确认适配器按声明的 stdio 传输由宿主拉起并命中断点;可执行文件缺失时显示插件设置里的安装提示而不是笼统错误;声明 tcpPort 传输的适配器在启动进程前被拒绝并说明原因。声明 tcpAnnounced 传输的适配器由宿主拉起进程,按 Core 的 debug.adapters.readAnnouncement 逐行读取声明的输出流:公告行不进调试控制台,其余输出照常显示;公告回环端点后连接并命中断点,暂停/继续正常,停止时先送达 disconnect 再停止进程;公告前退出显示“还没输出监听端口就退出”,公告非本机地址显示端点无效并停止进程,10 秒内没有公告按启动超时结束并停止进程。声明 tcpLanguageServer 传输的适配器(调试服务随同一插件的语言服务器运行)不由宿主拉起进程:宿主启动该插件声明的语言服务器,用 endpoint.command 向它要端口并连接 127.0.0.1,端口无效、语言服务器不属于该插件或不可用时会话以原因结束。从保存配置直接启动且未打开源码时也会激活、登记语言服务器并探测工具;停止调试取消端口命令而不停止共享语言服务器,拒绝工作区或会话替换后的旧端口。适配器只声明 attach,或 selectors 的 targetKinds 不含 file 时,不会被选作文件启动的调试器。capabilities.disabled 中的能力在调试会话里不可用,并随 debug.createSession 传给 Core。会话进行中禁用、更新或卸载该插件,或在模块设置里停用它,只停止该插件拥有的会话,同语言其他插件的会话继续运行。启动后 app bundle 文件清单不变(scripts/desktop/verify/verify-runtime-bundle-immutability.sh)。远程 attach 目前只有 Core 契约:attach 配置可声明 targetBindings.connection,Core 校验主机、端口与路径映射并按适配器自己的参数路径写入启动参数,非 localhost、127.0.0.0/8、::1 的端点返回 remote:true;macOS 宿主尚未接入 attach 与“附加到远程”对话框,因此本项暂不能在应用里验证远程附加,接入后补充:连接新的非回环端点前必须弹确认且默认不记住,附加结束只断开不结束远端程序。Windows:宿主尚未接入 debugAdapters,Core 校验通过不代表 Windows 能调试插件语言。 原生宿主路由回归:使用 Core 的 rust/fixtures/debug/adapter-selection-v1.json 验证自动文件选择、明确身份、无源文件目标、空身份、已撤回身份和 launch/attach 不匹配;同语言多个适配器分别收到断点,重试保持身份,附加会话启动失败保留原会话。这里只验证宿主交接与受控会话,Provider 原生程序准备 RPC 有受控流程与真实 SDK 进程覆盖;真实适配器的完整工作流与 Windows 接入仍未验收。 真实原生调试集成:公开 Node SDK Provider 用 Clang 编译 C 程序,经生产 macOS 会话、Core 准备、Registry 明确身份、生产 stdio 传输和 LLDB 命中源码断点、读取 main 栈帧、保留空格参数后继续并退出码 0;包 SHA-256/权限不变,所有本次进程回收。测试显式选择 SDK/工具,完整 UI、正式发行与 Windows 尚未验收,verification 保持 pending。 与显式 DAP 端点同时使用时,先按当前 Registry 身份校验请求能力,再调用端点工厂;launch/attach 与默认/明确身份的组合回归覆盖不会回退到本地适配器,配置编码与步进变换保留两个字段。 Windows 增量:服务目标显式保存并调试,唯一当前 Registry 类型/身份、Core 连接绑定、stdio/同包语言服务器、完整参数/初始化身份/禁用能力;覆盖重复/缺失适配器、包和设置变化、注册 ABA、监听取消、迟到启动回执、Run 退出/替换、清理失败重试。原生能力准入仍关闭,正式 Windows 适配器与真实框架断点 UI 尚未验收。 日志验收:在最新macOS宿主分别启动、初始化、暂停/继续、正常结束、取消、超时和适配器拒绝,确认debug/的关键生命周期INFO、内部状态DEBUG、真实失败ERROR;启动与原生进程非零退出固定stage/exit_code进入debug,原始stderr、DAP正文、源码、变量、内存和程序输出不进入诊断日志。同一次launch失败不能重复记session失败,取消不记ERROR。共享Core组件验证不能替代macOS真实UI和Windows v2验收。", - "notes": "Viva 声明 debugAdapters 0(契约版本已统一归 0,原 1、2、3 的内容都在其中):stdio、tcpAnnounced(宿主拉起进程,读取它输出的回环端口后连接)与 tcpLanguageServer 适配器、launch 与 attach、远程 attach(Core 判定非本机的端点需用户确认,不记住答案;暂无路径映射输入)、features 与 defaults 随 debug.createSession 交给调试引擎。debug/start 宿主方法与 run/start 的 launch 目标已接入;适配器的 startDebugging 子会话已接入(debug_child.go);launch.json 导入与 tcpPort 暂未实现。targetBindings.adapterArguments(按路径事实填适配器自有参数,env.<变量> 给环境加一个变量)与 targetBindings.cwd ← target.directory(被调程序在源文件所在目录运行)由共享 Core 在 debug.adapters.startArguments 里填好,宿主不需要改动。原生产品验收仍 pending。", + "notes": "Viva 声明 debugAdapters 0(契约版本已统一归 0,原 1、2、3 的内容都在其中):stdio、tcpAnnounced(宿主拉起进程,读取它输出的回环端口后连接)与 tcpLanguageServer 适配器、launch 与 attach、远程 attach(Core 判定非本机的端点需用户确认,不记住答案;暂无路径映射输入)、features 与 defaults 随 debug.createSession 交给调试引擎。debug/start 宿主方法与 run/start 的 launch 目标已接入;适配器的 startDebugging 子会话已接入(debug_child.go);launch.json 导入与 tcpPort 暂未实现。targetBindings.adapterArguments(按路径事实填适配器自有参数,env.<变量> 给环境加一个变量)与 targetBindings.cwd ← target.directory(被调程序在源文件所在目录运行)由共享 Core 在 debug.adapters.startArguments 里填好,宿主不需要改动。prepareDebugLaunch 将 Core 返回的 requiredDirectories 槽位(state、workspaceState、log、temporary)映射到对应可写目录并创建(TestDebugRequiredDirectoriesCreateStateAndLogSlots)。原生产品验收仍 pending。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { diff --git a/shared/platform-feature-matrix/features/plugin-injected-toolchains.json b/shared/platform-feature-matrix/features/plugin-injected-toolchains.json index e59cb01f41..7bd104c38f 100644 --- a/shared/platform-feature-matrix/features/plugin-injected-toolchains.json +++ b/shared/platform-feature-matrix/features/plugin-injected-toolchains.json @@ -2,7 +2,7 @@ "id": "plugin-injected-toolchains", "area": "扩展", "group": "插件与主题", - "capability": "Viva 从已启用插件的 toolDefinitions 声明发现工具链,将文件事实与有界版本探测交给原 Rust Core 的 candidates/resolve;Build 设置显示实际生效值与来源,草稿经显式 Save/Reset/Cancel 和受保护来源快照写入本机目录 pin,Core 统一提供读预算、严格来源解析与 Git 忽略编辑计划,无变化重置不创建文件,Build/Run/命令型 Tests 使用解析出的程序与环境。提供方 toolchains/query、完整配置来源编辑与原生 GUI 验收仍未完成。 支持手动目录验证、自动值回显及构建运行时依赖先解析再执行。 可在未打开项目时管理自动发现与手动登记的全局 SDK 默认值,项目可独立覆盖。", + "capability": "Viva 从已启用插件的 toolDefinitions 声明发现工具链,将文件事实与有界版本探测交给原 Rust Core 的 candidates/resolve;Build 设置显示实际生效值与来源,草稿经显式 Save/Reset/Cancel 和受保护来源快照写入本机目录 pin,Core 统一提供读预算、严格来源解析与 Git 忽略编辑计划,无变化重置不创建文件,Build/Run/命令型 Tests 使用解析出的程序与环境。支持沿工作区祖先链观测声明的 projectFile 环境与包装器候选,按规范化工作区根在本机用户设置保存与撤销项目工具环境信任(绝不写入工作区 .lithe/),未授权时零版本探测并清晰提示待信任状态,授权后立即重读展示自动生效值并供 Build/Run/Debug 共用。提供方 toolchains/query、完整配置来源编辑与原生 GUI 验收仍未完成。 支持手动目录验证、自动值回显及构建运行时依赖先解析再执行。 可在未打开项目时管理自动发现与手动登记的全局 SDK 默认值,项目可独立覆盖。", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", @@ -26,6 +26,8 @@ "desktop/internal/workbench/toolchains_test.go", "desktop/internal/toolchain/catalog.go", "desktop/internal/toolchain/catalog_test.go", + "desktop/internal/toolchain/project_trust_test.go", + "desktop/internal/core/toolchain_catalog.go", "desktop/internal/settingswindow/visual_capture_test.go", ".github/workflows/desktop-ci.yml", "desktop/internal/toolchain/load.go" @@ -48,6 +50,8 @@ "desktop/internal/workbench/toolchains_test.go", "desktop/internal/toolchain/catalog.go", "desktop/internal/toolchain/catalog_test.go", + "desktop/internal/toolchain/project_trust_test.go", + "desktop/internal/core/toolchain_catalog.go", "desktop/internal/settingswindow/visual_capture_test.go", ".github/workflows/desktop-ci.yml", "desktop/internal/toolchain/load.go", @@ -55,8 +59,8 @@ ] }, "owner": "Plugin Platform", - "verification": "共享 Core:cargo test --manifest-path rust/Cargo.toml -p lithe-core --lib toolchain,核对定义独占与官方短 ID、第二种通用工具、旧候选边界、答案身份/代次、Windows 路径大小写、工作区排除、固定值失效不回落、最近项目要求、冲突选择、最低版本、环境隔离和纯声明扫描;按逐项计时工具生成 HTML/JUnit。macOS 继续补齐下列消费者与保存验收,Windows 须先实现对应 adapter:启动提供方并协商、取消/超时和过期结果隔离、输入新建/删除后整体重查、目录固定保存/取消/冲突回读、插件停用撤回、真实 Build/LSP/Run 消费者取得同一选择、发行目录哈希不变与子进程清理。未完成原生流程前保持 pending,不以 Core 测试代替实机验证。 提供方查询:cargo test -p lithe-core --lib toolchain(含 lsp 引擎脚本后端:只有插件后端被提供 litheToolchains、未协商的提供方不写请求、错误回复原样返回;别名链接只有链接路径事实时仍选中规范 home);MacToolchainDiscoveryTests 用真实临时目录与注入的查询验证全局与目录查询各带独立 operationID/代次、链接 home 规范化、工作区内 home 整份拒绝;ToolchainSettingsFeatureTests 验证监视文件连续变化只重载一次、外部输入观察随关闭释放。真实 mise 插件端到端尚未在应用内验证。 原生布局回归 ToolchainSettingsLayoutTests:同一设置宿主按900/1180/1400/900重复缩放,真实分隔条拖动;来源页按500/666/946/500缩放,检查AX控件边界、卡片不重叠、选择和快照不改变。此几何验证不代表提供方查询或保存功能已完成。 声明式扫描 MacToolchainDiscoveryTests:真实临时目录、注入的用户目录与探测,覆盖 homeLayouts 首个匹配、隐藏与未匹配条目、链接到工作区的条目不探测、只探测 Core 返回的可执行文件、同版本冲突、被拒声明不扫描,以及隔离预览样例清单通过 Core 准入;不运行本机安装的工具。 固定集成新增 MacToolchainDiscoveryTests 的运行前解析回归和 MacBuildToolResolverTests,验证两个目录使用各自 pin、最低版本、独立环境与失败不回落;RunLaunchEnvironmentTests 证明操作返回值不会留下共享执行许可槽。该测试不是完整应用 UI 验收。 生产准入回归 installedToolDeclarationsPassTheProductionHostAdmission 经 RustDeclarativePluginOperations 验证工具定义和提供者。Build PATH 保留声明的附加目录,拒绝空目录项。 Windows 原生解析基础:lithe-project::defined_toolchain 逐项计时覆盖两个工具、声明式扫描、固定目录、最近继承、同版本冲突、最低版本、显式 Wrapper、输入撤销及宿主秘密不进入 RPC。真实 Windows 命令包装和进程清理继续由现有 CI 验证;准入仍关闭。 本次回归另核对同目录两个 Run 独立选择、团队/本机逐项合并和显式清空、私有环境隔离、失效固定值不回落、工作区启动器被动零探测,以及未知默认值迁移失败保留源文件。 本批显式 LITHE_TEST_NODE 驱动真实 Core/Node 会话,逐项计时覆盖单次协商、多次查询、原始错误、无协商拒绝、静默超时、后端意外退出与撤销清理;原生解析验证查询与当前事实、来源在探测中变化及稳定模型摘要。安装状态按 plugin/operation/workspace 隔离且不可跨工作树复制。 #1581 最终合入回归包含固定值与未扫描目录、同轮次/上下文、冲突及提供方超时和不可用的来源展示。 通用默认增量:更改工作区工具 home 后,消费者继承读取新值,按 Run 固定值保持独立;失效明确路径不回落,来源在探测期间改变或越出工作区时拒绝。旧编辑保存保留通用偏好,显式空 v1 文档清除。矩阵保持 pending,未把手写测试文档当成设置页或旧配置迁移验收。 macOS Build 偏好编辑:ToolchainPreferencesTests 验证打开/草稿/取消/空重置不建文件、明确保存/回读与权限保留、外部冲突保留原始草稿基线、仅偏好文档不阻断旧默认迁移、缺失子目录的父链接/最终链接/只读安装目录拒绝及主动取消;原生 Save/Reset 按钮在深浅主题通过实际存储执行。ToolchainSettingsLoaderTests 验证使用方来自当前 Core invocation 并随停用撤回。运行全量 Core 与相关 macOS 逐项计时;完整产品、全局默认、旧消费者和 Windows 设置页仍待验收。 tool 引用验证:共享 fixture/Core 覆盖最近通用目录、根目录、跳过父消费者、目录与工作区默认变化、显式 Run 优先和禁止通用工具反向引用;MacToolchainDiscoveryTests 与 lithe-project::defined_toolchain 的真实临时安装/注入探测验证运行前重读,不冻结安装路径。 本机目录/重载回归覆盖仅消费者偏好、父目录连接、重置撤回、链接/非法层级拒绝、单次重试与可刷新错误、未修改表单更新、冲突草稿保留及自身保存通知不等待/撤销保存。该集成不代替完整 GUI。 运行前来源审计 missingPreferenceLeafBehindAParentAliasIsRejectedBeforeToolWork 覆盖两级父目录及存在/悬空链接,四种情况均在工具探测前拒绝。 ToolchainPluginAdmissionTests 使用正式契约 fixture 与真实 Core 验证市场可安装、完整安装审查、清单加载,以及无后端纯工具定义插件的启用模块和工厂登记;本地编译验证不代替真实 mise 与 Windows 工作流验收。 2026-11-02 本机 Swift 6.4.2:准入、后端、发现和加载器 42 项通过,新增两个准入用例分别 4/6 ms;Swift 6.3.3 在本机 Xcode 27.2 SDK 下编译依赖清单崩溃,不能作为固定工具链通过。真实 mise 0.2.1 发布包 SHA-256 与市场一致,Core 证明修复前 unsupported、修复后 available;真实后端完成协商、查询并停止销毁,当前环境未安装 mise,查询真实返回 miseNotFound,未验证安装列表和应用内工作流。 增补来源保存验收:不存在的 pin 重置不创建状态;拒绝逃出工作区的符号链接/junction;有界 UTF-8 与重复键、未知字段和 dormant pin 校验;Git 后续否定规则、换行/评论/权限保留;公开字节基线不可替代私有快照;已提交但回读失败必须重新加载后才能重试。 Viva 全局 SDK 页:运行 TestVisualSettings/33-settings-toolchains,使用 en、zh-Hans 和 dark/light 的生产无头窗口,核对无项目模式、自动实际值、多版本登记与全局默认选择。通过 run-go-tests-with-timing.mjs 记录单测试 HTML/JUnit;desktop-ci 的 macOS/Windows 每次上传四张图和计时报告。2026-11-15 本机 macOS 与 Windows 11 ARM64 来宾的 GNU x64 系统仿真均通过两个语言各 3 个计时结果,Windows 49 个 SDK/来源/诊断/资源定向用例通过;该证据不替代工具提供方与完整产品工作流验收,整体保持 partial/pending。 Windows #2042:TestToolchainCandidatesUseNativeShellPathsInUserProfiles 以真实 PATH 查找、真实有界版本进程和 Core 候选规则,覆盖 PATH-only/环境变量-only 及空格/中文用户目录;合成工具位于扫描目录之外,全局登记使用私有根。 通过现有 Windows CI 的 scripts/desktop/check.sh 运行;本机逐项计时报告覆盖这些合成场景,完整原生界面验收仍保持 pending。", - "notes": "Viva:共享 Core toolchain 命令已接入 desktop/internal/core/toolchain.go;声明式扫描、文件事实、有界版本探测、toolchains.candidates/resolve 与目录 pin 保存位于 desktop/internal/toolchain/ 并有真实 Core 测试;设置窗口 Build 页可按插件声明展示工具、生效值与来源,显式 Save/Reset 写 .lithe/toolchains/local.json,Cancel 不写;Build 命令和 Provider Run 的 toolchain 候选使用 Core 解析出的可执行文件、环境导出和 PATH。提供方后端查询(toolchainProviders)未接入,因此未声明该能力;Windows 与完整 GUI/原生工作流未验收,状态保持 pending,legacy 证据不代表 Viva。 本轮通过外部 Core Draft PR #3 的精确提交接入 toolchains.editPins:平台不再编辑 pin schema;Core/Go 共用 fixture、批量保存和取消/外部并发修改回归通过。命令型 Tests 同样消费解析后的工具链环境。原生 Windows、提供方工具查询、完整 GUI 与发行验收仍 pending。 Windows 原生回归确认保存前后的文件模式以及真实访问控制描述符(所有者、组、DACL/继承保护)保留;元数据先准备到临时文件,再核对取消/冲突并原子发布。此证据不代表提供方查询或 GUI 已验收。 Viva 设置保存前核对读取项目的原生目录身份;项目关闭或切换后旧草稿拒绝写入,已确认保存的发布与回读固定捕获来源。冲突通过共享 i18n 显示并保留草稿,加载/保存失败进入目录日志;macOS 先失败后通过的回归已有计时,新增作用域行为的 Windows 验收尚未执行。 Windows 原生探测统一 Core 正斜杠路径与本机反斜杠/大小写别名,防止重复事实使目录 pin 解析遭拒绝;选择与校验规则仍由原有 Core 决定。 全局 SDK 登记与默认值可在未打开项目时编辑;项目范围保留独立覆盖,读取不创建文件,确认保存后按实际探测回显。新增合成工具原生与无头测试,不改变历史完整验收状态。 Viva 2026-11-16:Build 页每个工具改为一个下拉框,默认回显当前选择(未固定时为“自动(实际目录)”),列出识别到的其他安装、已保存固定值和已校验目录;选“自定义…”才显示目录输入、浏览和“使用此目录”,校验通过后该目录成为列表项并被选中。无版本的安装不可选,在列表下以说明文字列出。自动化:TestToolchainListShowsAutomaticAndHidesTheDirectoryUntilCustom 及原有草稿/保存/冲突用例;截图 TestVisualSettings/33-settings-toolchains、m44-toolchain-directory-menu、m45-toolchain-custom-directory。原生验收仍 pending。 Viva 2026-11-16(#2032):toolchains.candidates 改为同时接收宿主找到的 PATH 命令所在目录(commandHomes),JAVA_HOME 等声明变量和 PATH 上的安装校验通过后以 host:shell 并入安装列表并按规范目录去重,新建项目的工具选择、设置页和运行配置因此能选到只配置在 PATH 或环境变量上的 JDK;自动层的选择不变。Core 回归 toolchain_candidates_offer_shell_homes_that_no_discovery_scan_covers(Lithe-core-rust#67),宿主回归 TestShellHomesAreInstallationsWithoutADiscoveryScan;两者都确认修复前失败。Windows 0.8.0 实机复现了缺陷,修复后的完整 Windows 客户端尚未实机验收,状态保持 pending。", + "verification": "共享 Core:cargo test --manifest-path rust/Cargo.toml -p lithe-core --lib toolchain,核对定义独占与官方短 ID、第二种通用工具、旧候选边界、答案身份/代次、Windows 路径大小写、工作区排除、固定值失效不回落、最近项目要求、冲突选择、最低版本、环境隔离和纯声明扫描;按逐项计时工具生成 HTML/JUnit。macOS 继续补齐下列消费者与保存验收,Windows 须先实现对应 adapter:启动提供方并协商、取消/超时和过期结果隔离、输入新建/删除后整体重查、目录固定保存/取消/冲突回读、插件停用撤回、真实 Build/LSP/Run 消费者取得同一选择、发行目录哈希不变与子进程清理。未完成原生流程前保持 pending,不以 Core 测试代替实机验证。 提供方查询:cargo test -p lithe-core --lib toolchain(含 lsp 引擎脚本后端:只有插件后端被提供 litheToolchains、未协商的提供方不写请求、错误回复原样返回;别名链接只有链接路径事实时仍选中规范 home);MacToolchainDiscoveryTests 用真实临时目录与注入的查询验证全局与目录查询各带独立 operationID/代次、链接 home 规范化、工作区内 home 整份拒绝;ToolchainSettingsFeatureTests 验证监视文件连续变化只重载一次、外部输入观察随关闭释放。真实 mise 插件端到端尚未在应用内验证。 原生布局回归 ToolchainSettingsLayoutTests:同一设置宿主按900/1180/1400/900重复缩放,真实分隔条拖动;来源页按500/666/946/500缩放,检查AX控件边界、卡片不重叠、选择和快照不改变。此几何验证不代表提供方查询或保存功能已完成。 声明式扫描 MacToolchainDiscoveryTests:真实临时目录、注入的用户目录与探测,覆盖 homeLayouts 首个匹配、隐藏与未匹配条目、链接到工作区的条目不探测、只探测 Core 返回的可执行文件、同版本冲突、被拒声明不扫描,以及隔离预览样例清单通过 Core 准入;不运行本机安装的工具。 固定集成新增 MacToolchainDiscoveryTests 的运行前解析回归和 MacBuildToolResolverTests,验证两个目录使用各自 pin、最低版本、独立环境与失败不回落;RunLaunchEnvironmentTests 证明操作返回值不会留下共享执行许可槽。该测试不是完整应用 UI 验收。 生产准入回归 installedToolDeclarationsPassTheProductionHostAdmission 经 RustDeclarativePluginOperations 验证工具定义和提供者。Build PATH 保留声明的附加目录,拒绝空目录项。 Windows 原生解析基础:lithe-project::defined_toolchain 逐项计时覆盖两个工具、声明式扫描、固定目录、最近继承、同版本冲突、最低版本、显式 Wrapper、输入撤销及宿主秘密不进入 RPC。真实 Windows 命令包装和进程清理继续由现有 CI 验证;准入仍关闭。 本次回归另核对同目录两个 Run 独立选择、团队/本机逐项合并和显式清空、私有环境隔离、失效固定值不回落、工作区启动器被动零探测,以及未知默认值迁移失败保留源文件。 本批显式 LITHE_TEST_NODE 驱动真实 Core/Node 会话,逐项计时覆盖单次协商、多次查询、原始错误、无协商拒绝、静默超时、后端意外退出与撤销清理;原生解析验证查询与当前事实、来源在探测中变化及稳定模型摘要。安装状态按 plugin/operation/workspace 隔离且不可跨工作树复制。 #1581 最终合入回归包含固定值与未扫描目录、同轮次/上下文、冲突及提供方超时和不可用的来源展示。 通用默认增量:更改工作区工具 home 后,消费者继承读取新值,按 Run 固定值保持独立;失效明确路径不回落,来源在探测期间改变或越出工作区时拒绝。旧编辑保存保留通用偏好,显式空 v1 文档清除。矩阵保持 pending,未把手写测试文档当成设置页或旧配置迁移验收。 macOS Build 偏好编辑:ToolchainPreferencesTests 验证打开/草稿/取消/空重置不建文件、明确保存/回读与权限保留、外部冲突保留原始草稿基线、仅偏好文档不阻断旧默认迁移、缺失子目录的父链接/最终链接/只读安装目录拒绝及主动取消;原生 Save/Reset 按钮在深浅主题通过实际存储执行。ToolchainSettingsLoaderTests 验证使用方来自当前 Core invocation 并随停用撤回。运行全量 Core 与相关 macOS 逐项计时;完整产品、全局默认、旧消费者和 Windows 设置页仍待验收。 tool 引用验证:共享 fixture/Core 覆盖最近通用目录、根目录、跳过父消费者、目录与工作区默认变化、显式 Run 优先和禁止通用工具反向引用;MacToolchainDiscoveryTests 与 lithe-project::defined_toolchain 的真实临时安装/注入探测验证运行前重读,不冻结安装路径。 本机目录/重载回归覆盖仅消费者偏好、父目录连接、重置撤回、链接/非法层级拒绝、单次重试与可刷新错误、未修改表单更新、冲突草稿保留及自身保存通知不等待/撤销保存。该集成不代替完整 GUI。 运行前来源审计 missingPreferenceLeafBehindAParentAliasIsRejectedBeforeToolWork 覆盖两级父目录及存在/悬空链接,四种情况均在工具探测前拒绝。 ToolchainPluginAdmissionTests 使用正式契约 fixture 与真实 Core 验证市场可安装、完整安装审查、清单加载,以及无后端纯工具定义插件的启用模块和工厂登记;本地编译验证不代替真实 mise 与 Windows 工作流验收。 2026-11-02 本机 Swift 6.4.2:准入、后端、发现和加载器 42 项通过,新增两个准入用例分别 4/6 ms;Swift 6.3.3 在本机 Xcode 27.2 SDK 下编译依赖清单崩溃,不能作为固定工具链通过。真实 mise 0.2.1 发布包 SHA-256 与市场一致,Core 证明修复前 unsupported、修复后 available;真实后端完成协商、查询并停止销毁,当前环境未安装 mise,查询真实返回 miseNotFound,未验证安装列表和应用内工作流。 增补来源保存验收:不存在的 pin 重置不创建状态;拒绝逃出工作区的符号链接/junction;有界 UTF-8 与重复键、未知字段和 dormant pin 校验;Git 后续否定规则、换行/评论/权限保留;公开字节基线不可替代私有快照;已提交但回读失败必须重新加载后才能重试。 Viva 全局 SDK 页:运行 TestVisualSettings/33-settings-toolchains,使用 en、zh-Hans 和 dark/light 的生产无头窗口,核对无项目模式、自动实际值、多版本登记与全局默认选择。通过 run-go-tests-with-timing.mjs 记录单测试 HTML/JUnit;desktop-ci 的 macOS/Windows 每次上传四张图和计时报告。2026-11-15 本机 macOS 与 Windows 11 ARM64 来宾的 GNU x64 系统仿真均通过两个语言各 3 个计时结果,Windows 49 个 SDK/来源/诊断/资源定向用例通过;该证据不替代工具提供方与完整产品工作流验收,整体保持 partial/pending。 Windows #2042:TestToolchainCandidatesUseNativeShellPathsInUserProfiles 以真实 PATH 查找、真实有界版本进程和 Core 候选规则,覆盖 PATH-only/环境变量-only 及空格/中文用户目录;合成工具位于扫描目录之外,全局登记使用私有根。 通过现有 Windows CI 的 scripts/desktop/check.sh 运行;本机逐项计时报告覆盖这些合成场景,完整原生界面验收仍保持 pending。 2026-11-18(#2122):使用 dev.lithe.test.* 合成工具清单运行 TestUntrustedProjectEnvironmentNeverProbesWorkspaceExecutables、TestTrustedWorkspacePersistsInLocalSettingsOnlyAndResolvesSymlinkedVenv、TestTrustedWorkspaceResolvesSubdirectoryEnvironmentAndRejectsEscapingDirectories、TestProjectToolchainTrustSwitchGrantsAndRevokesImmediately 与 TestWorkbenchToolchainTrustPersistsLocallyLogsActionAndEnablesRuntimeResolution,验证未授权零探测、两跳符号链接虚拟环境字面路径保留、目录软链逃逸在探测前拒绝、本机 toolchains/global.json 原子保存与撤销(绝不写工作区 .lithe/)、performedIn 操作轨迹以及中英明暗无头截图 m47/m48;Windows 实机与完整原生 GUI 工作流保持 pending。", + "notes": "Viva:共享 Core toolchain 命令已接入 desktop/internal/core/toolchain.go;声明式扫描、文件事实、有界版本探测、toolchains.candidates/resolve 与目录 pin 保存位于 desktop/internal/toolchain/ 并有真实 Core 测试;设置窗口 Build 页可按插件声明展示工具、生效值与来源,显式 Save/Reset 写 .lithe/toolchains/local.json,Cancel 不写;Build 命令和 Provider Run 的 toolchain 候选使用 Core 解析出的可执行文件、环境导出和 PATH。提供方后端查询(toolchainProviders)未接入,因此未声明该能力;Windows 与完整 GUI/原生工作流未验收,状态保持 pending,legacy 证据不代表 Viva。 本轮通过外部 Core Draft PR #3 的精确提交接入 toolchains.editPins:平台不再编辑 pin schema;Core/Go 共用 fixture、批量保存和取消/外部并发修改回归通过。命令型 Tests 同样消费解析后的工具链环境。原生 Windows、提供方工具查询、完整 GUI 与发行验收仍 pending。 Windows 原生回归确认保存前后的文件模式以及真实访问控制描述符(所有者、组、DACL/继承保护)保留;元数据先准备到临时文件,再核对取消/冲突并原子发布。此证据不代表提供方查询或 GUI 已验收。 Viva 设置保存前核对读取项目的原生目录身份;项目关闭或切换后旧草稿拒绝写入,已确认保存的发布与回读固定捕获来源。冲突通过共享 i18n 显示并保留草稿,加载/保存失败进入目录日志;macOS 先失败后通过的回归已有计时,新增作用域行为的 Windows 验收尚未执行。 Windows 原生探测统一 Core 正斜杠路径与本机反斜杠/大小写别名,防止重复事实使目录 pin 解析遭拒绝;选择与校验规则仍由原有 Core 决定。 全局 SDK 登记与默认值可在未打开项目时编辑;项目范围保留独立覆盖,读取不创建文件,确认保存后按实际探测回显。新增合成工具原生与无头测试,不改变历史完整验收状态。 Viva 2026-11-16:Build 页每个工具改为一个下拉框,默认回显当前选择(未固定时为“自动(实际目录)”),列出识别到的其他安装、已保存固定值和已校验目录;选“自定义…”才显示目录输入、浏览和“使用此目录”,校验通过后该目录成为列表项并被选中。无版本的安装不可选,在列表下以说明文字列出。自动化:TestToolchainListShowsAutomaticAndHidesTheDirectoryUntilCustom 及原有草稿/保存/冲突用例;截图 TestVisualSettings/33-settings-toolchains、m44-toolchain-directory-menu、m45-toolchain-custom-directory。原生验收仍 pending。 Viva 2026-11-16(#2032):toolchains.candidates 改为同时接收宿主找到的 PATH 命令所在目录(commandHomes),JAVA_HOME 等声明变量和 PATH 上的安装校验通过后以 host:shell 并入安装列表并按规范目录去重,新建项目的工具选择、设置页和运行配置因此能选到只配置在 PATH 或环境变量上的 JDK;自动层的选择不变。Core 回归 toolchain_candidates_offer_shell_homes_that_no_discovery_scan_covers(Lithe-core-rust#67),宿主回归 TestShellHomesAreInstallationsWithoutADiscoveryScan;两者都确认修复前失败。Windows 0.8.0 实机复现了缺陷,修复后的完整 Windows 客户端尚未实机验收,状态保持 pending。 Viva 2026-11-18(#2122):prepareTool 沿工作区祖先链观测 discoveryPlan 返回的 projectFiles、requires、home、中间父目录、pathPrepend 及软链目标;probeAll 在 ProjectCodeAllowed 为 false 时拒绝探测任何工作区内可执行文件;本机信任记录经 Core catalogState/editCatalog 保存在应用用户设置目录 toolchains/global.json,设置页项目作用域提供带 ⓘ 说明的显式信任开关并立即回读生效值,工作台 resolveToolchainSelection 同步读取同一本机信任状态。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { From c87574c08ac1587e1fd98cfe1c1225af4de636d8 Mon Sep 17 00:00:00 2001 From: Mucheen <145200703+Mucheen@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:54:58 +0800 Subject: [PATCH 2/2] =?UTF-8?q?test(settings):=20=E7=AD=89=E5=BE=85?= =?UTF-8?q?=E9=A1=B9=E7=9B=AE=E5=B7=A5=E5=85=B7=E9=93=BE=E4=BF=A1=E4=BB=BB?= =?UTF-8?q?=E7=8A=B6=E6=80=81=E6=B8=B2=E6=9F=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../settingswindow/visual_capture_test.go | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/desktop/internal/settingswindow/visual_capture_test.go b/desktop/internal/settingswindow/visual_capture_test.go index 4e45aaf40f..0c409bfa16 100644 --- a/desktop/internal/settingswindow/visual_capture_test.go +++ b/desktop/internal/settingswindow/visual_capture_test.go @@ -167,12 +167,17 @@ func TestVisualSettings(t *testing.T) { d.click("Compiler") d.click(text("desktop.toolchains.custom")) d.pump() - case "m47-toolchain-project-untrusted", "m48-toolchain-project-trusted": + case "m47-toolchain-project-untrusted", "m48-toolchain-project-trusted", "m49-toolchain-project-trust-help": d.click(text("desktop.toolchains.project")) - d.until("project toolchains", func() bool { return w.toolchains.loaded && !w.toolchains.snapshot.Global }) - case "m49-toolchain-project-trust-help": - d.click(text("desktop.toolchains.project")) - d.until("project toolchains help", func() bool { return w.toolchains.loaded && !w.toolchains.snapshot.Global }) + status := text("desktop.toolchains.trustStatusTrusted") + if scenario.id == "m47-toolchain-project-untrusted" { + status = text("desktop.toolchains.trustStatusUntrusted") + } + // The load result can arrive during painting, before the trust controls appear. + d.until("the visible project trust status", func() bool { return d.text(status) }) + if scenario.id != "m49-toolchain-project-trust-help" { + break + } help := text("desktop.toolchains.trustProjectHelp") info := d.hintHit(help).Bounds x, y := info.X+info.Width/2, info.Y+info.Height/2