diff --git a/desktop/internal/core/client.go b/desktop/internal/core/client.go index 891936440..ca191efe4 100644 --- a/desktop/internal/core/client.go +++ b/desktop/internal/core/client.go @@ -49,6 +49,10 @@ type gitExecution struct { // Source is the request's provenance: "background" for an automatic refresh, whose // queries Core keeps silent unless QueryCategory names them; empty for unknown. Source string `json:"source,omitempty"` + // ProjectCodeAllowed is false for a request of a workspace the user has not trusted + // (WithProjectCodeAllowed): Core starts no Git process for it and answers + // CodeGitUntrustedWorkspace. Nil keeps Core's default, which allows Git. + ProjectCodeAllowed *bool `json:"projectCodeAllowed,omitempty"` } // responseEnvelope is the response the kernel encodes (CoreResponse in the Rust protocol). diff --git a/desktop/internal/core/errors.go b/desktop/internal/core/errors.go index 84ebab0d0..6da878e48 100644 --- a/desktop/internal/core/errors.go +++ b/desktop/internal/core/errors.go @@ -2,6 +2,7 @@ package core import ( "context" + "errors" "fmt" ) @@ -54,6 +55,10 @@ const ( // CodeGitCommitAuthorInvalid means a commit named an author that is not exactly // "Name "; nothing was committed. CodeGitCommitAuthorInvalid ErrorCode = "git_commit_author_invalid" + // CodeGitUntrustedWorkspace means the request belongs to a workspace the user has not trusted + // (WithProjectCodeAllowed), so Core started no Git process: the repository's own configuration + // can name programs Git runs, such as core.fsmonitor and hooks. + CodeGitUntrustedWorkspace ErrorCode = "git_untrusted_workspace" // CodeParseFailed means input or tool output could not be decoded into the stable // contract. This package also uses it for a response it cannot decode. CodeParseFailed ErrorCode = "parse_failed" @@ -97,6 +102,13 @@ func (e *Error) Is(target error) bool { return false } +// IsGitUntrustedWorkspace reports whether err is Core refusing to run Git for a workspace the +// user has not trusted (CodeGitUntrustedWorkspace). +func IsGitUntrustedWorkspace(err error) bool { + var coreErr *Error + return errors.As(err, &coreErr) && coreErr.Code == CodeGitUntrustedWorkspace +} + // newParseError reports a response that violates the envelope contract. func newParseError(command, message, details string) *Error { return &Error{Command: command, Code: CodeParseFailed, Message: message, Details: details} diff --git a/desktop/internal/core/gitconsole.go b/desktop/internal/core/gitconsole.go index 8d777dbae..15f53052b 100644 --- a/desktop/internal/core/gitconsole.go +++ b/desktop/internal/core/gitconsole.go @@ -822,26 +822,38 @@ func WithQueryCategory(ctx context.Context, category GitQueryCategory) context.C return context.WithValue(ctx, gitQueryCategoryKey{}, category) } -// gitExecutionOf is the Git policy of a request: a Git request of a context with a console -// asks Core to report the internal queries of the categories the console records, names the -// category the context gives, and marks an automatic refresh. Other requests, and a request -// with nothing to ask, keep Core's defaults. +type projectCodeAllowedKey struct{} + +// WithProjectCodeAllowed returns a context whose requests belong to a workspace whose trust +// allowed reads when each request is sent. While it reports false, every request of the +// context, not only the git ones, tells Core to start no Git process: Core runs Git for other +// commands too, such as the ignore check of workspace.listDirectories, and the repository's +// own configuration can name programs Git runs (core.fsmonitor, hooks, filters). +func WithProjectCodeAllowed(ctx context.Context, allowed func() bool) context.Context { + return context.WithValue(ctx, projectCodeAllowedKey{}, allowed) +} + +// gitExecutionOf is the Git policy of a request. A request of an untrusted workspace +// (WithProjectCodeAllowed) forbids Git, whatever its command. A Git request of a context with +// a console also asks Core to report the internal queries of the categories the console +// records, names the category the context gives, and marks an automatic refresh. A request +// with nothing to ask keeps Core's defaults. func gitExecutionOf(ctx context.Context, command string) *gitExecution { - if !strings.HasPrefix(command, "git.") || gitConsoleUnrecorded[command] { - return nil + var execution gitExecution + if allowed, _ := ctx.Value(projectCodeAllowedKey{}).(func() bool); allowed != nil && !allowed() { + execution.ProjectCodeAllowed = new(false) } sink, _ := ctx.Value(gitConsoleKey{}).(*gitConsoleSink) - if sink == nil { - return nil - } - execution := gitExecution{ConsoleQueries: sink.console.recordedQueries()} - if len(execution.ConsoleQueries) > 0 { - execution.QueryCategory, _ = ctx.Value(gitQueryCategoryKey{}).(GitQueryCategory) - } - if refresh, _ := ctx.Value(gitRefreshKey{}).(bool); refresh { - execution.Source = "background" + if sink != nil && strings.HasPrefix(command, "git.") && !gitConsoleUnrecorded[command] { + execution.ConsoleQueries = sink.console.recordedQueries() + if len(execution.ConsoleQueries) > 0 { + execution.QueryCategory, _ = ctx.Value(gitQueryCategoryKey{}).(GitQueryCategory) + } + if refresh, _ := ctx.Value(gitRefreshKey{}).(bool); refresh { + execution.Source = "background" + } } - if len(execution.ConsoleQueries) == 0 && execution.Source == "" { + if len(execution.ConsoleQueries) == 0 && execution.Source == "" && execution.ProjectCodeAllowed == nil { return nil } return &execution diff --git a/desktop/internal/core/gitconsole_test.go b/desktop/internal/core/gitconsole_test.go index 2d7e7eb3a..d36ce0d73 100644 --- a/desktop/internal/core/gitconsole_test.go +++ b/desktop/internal/core/gitconsole_test.go @@ -7,6 +7,7 @@ import ( "path/filepath" "slices" "strings" + "sync/atomic" "testing" "time" @@ -329,6 +330,33 @@ func TestGitConsoleRecordsNothingForADetachedContext(t *testing.T) { } } +// A request of an untrusted workspace starts no Git process: Core answers +// CodeGitUntrustedWorkspace, the console keeps only the refusal (a record with no command), and +// the same context runs Git once the workspace is trusted (#2208). +func TestGitRequestOfAnUntrustedWorkspaceRunsNoGit(t *testing.T) { + repo := committedRepository(t) + client := NewClient() + console := NewGitConsole(nil) + console.RecordQueries([]GitQueryCategory{GitQueryReferences, GitQueryChecks}) + var trusted atomic.Bool + ctx := WithProjectCodeAllowed(WithGitConsole(testContext(t), console, repo), trusted.Load) + if _, err := client.GitStatus(ctx, repo); !IsGitUntrustedWorkspace(err) { + t.Fatalf("GitStatus(untrusted) error = %v, want %s", err, CodeGitUntrustedWorkspace) + } + for _, record := range console.Snapshot().Records { + if record.Executable != "" || len(record.Arguments) != 0 || record.Error == "" { + t.Fatalf("an untrusted request recorded a command: %+v", record) + } + } + trusted.Store(true) + if _, err := client.GitStatus(ctx, repo); err != nil { + t.Fatalf("GitStatus(trusted) error: %v", err) + } + if commands := consoleCommands(console); !slices.Contains(commands, "status") { + t.Fatalf("console commands = %q, want the trusted status query", commands) + } +} + // consoleCommands are the Git subcommands of the console's records, in order. func consoleCommands(console *GitConsole) []string { var commands []string @@ -399,12 +427,15 @@ func TestGitConsoleRecordsTheQueriesOfTheCategoriesItShows(t *testing.T) { // Only a Git request with a console asks Core to report queries, of the categories the // console records and under the category the context names; an automatic refresh names its -// provenance. +// provenance. Every request of an untrusted workspace forbids Git, whatever its command, since +// Core also runs Git for requests that are not Git's (#2208); the decision is read per request. func TestGitExecutionOfAsksForTheCategoriesTheConsoleShows(t *testing.T) { idea := WithGitConsole(context.Background(), NewGitConsole(nil), "/repo") shown := NewGitConsole(nil) shown.RecordQueries(GitConsolePreferences{ShowDiffQueries: true, ShowCheckQueries: true}.QueryCategories()) ctx := WithGitConsole(context.Background(), shown, "/repo") + var trusted atomic.Bool + gated := WithProjectCodeAllowed(ctx, trusted.Load) cases := []struct { name string ctx context.Context @@ -421,6 +452,9 @@ func TestGitExecutionOfAsksForTheCategoriesTheConsoleShows(t *testing.T) { {"detached", WithGitConsole(ctx, nil, ""), "git.status", `null`}, {"never runs Git", ctx, "git.consolePresentation", `null`}, {"not Git", ctx, "core.ping", `null`}, + {"untrusted", gated, "git.status", `{"consoleQueries":["diff","checks"],"projectCodeAllowed":false}`}, + {"untrusted without console", WithProjectCodeAllowed(context.Background(), trusted.Load), "workspace.listDirectories", `{"projectCodeAllowed":false}`}, + {"untrusted never runs Git", gated, "git.consolePresentation", `{"projectCodeAllowed":false}`}, } for _, c := range cases { got, err := json.Marshal(gitExecutionOf(c.ctx, c.command)) @@ -428,6 +462,10 @@ func TestGitExecutionOfAsksForTheCategoriesTheConsoleShows(t *testing.T) { t.Fatalf("%s: gitExecution = %s (%v), want %s", c.name, got, err, c.want) } } + trusted.Store(true) + if got, err := json.Marshal(gitExecutionOf(gated, "core.ping")); err != nil || string(got) != `null` { + t.Fatalf("trusted: gitExecution = %s (%v), want null, Core's default", got, err) + } } // Every preference starts as IDEA's console, and each one turns on the category or display diff --git a/desktop/internal/core/plugin_session.go b/desktop/internal/core/plugin_session.go index eac1e3cfd..03810b8b7 100644 --- a/desktop/internal/core/plugin_session.go +++ b/desktop/internal/core/plugin_session.go @@ -3,6 +3,7 @@ package core import ( "context" "encoding/json" + "errors" "runtime" ) @@ -150,6 +151,24 @@ type PluginBackendDirectories struct { Architecture string `json:"architecture"` Settings map[string]json.RawMessage `json:"settings,omitempty"` ProjectSettings map[string]json.RawMessage `json:"projectSettings,omitempty"` + // ProjectCodeAllowed is whether the user trusts the workspace. Core plans no language + // server, build provider process or VCS provider that would run project code without it, + // and refuses them with LaunchUntrustedWorkspace. A plugin backend and a debug adapter of + // its own process are not refused; an adapter hosted in a language server is that + // server's launch, refused as the server is. + ProjectCodeAllowed bool `json:"projectCodeAllowed,omitempty"` +} + +// LaunchUntrustedWorkspace is the code Core refuses a launch plan with when the process +// would run project code and the workspace is not trusted. The host leaves the process +// stopped and starts it once the user trusts the workspace. +const LaunchUntrustedWorkspace = "plugin.launch.untrustedWorkspace" + +// IsLaunchUntrustedWorkspace reports whether err is Core's refusal of a launch for want of +// workspace trust. +func IsLaunchUntrustedWorkspace(err error) bool { + var rejection *MarketplaceRejection + return errors.As(err, &rejection) && rejection.Code == LaunchUntrustedWorkspace } // PluginArchitecture is this host's CPU in the plugin contract's names, which diff --git a/desktop/internal/core/plugin_session_test.go b/desktop/internal/core/plugin_session_test.go index fbcd683f4..5dd0f2eeb 100644 --- a/desktop/internal/core/plugin_session_test.go +++ b/desktop/internal/core/plugin_session_test.go @@ -444,7 +444,7 @@ func TestRuntimeToolPlanKeepsAnEntryForNativeInstantiation(t *testing.T) { t.Fatal(err) } root := t.TempDir() - plan, err := NewClient().PlanPluginLanguageServer(testContext(t), manifest, "script", PluginBackendDirectories{PluginDirectory: root, StateDirectory: t.TempDir(), Architecture: PluginArchitecture()}) + plan, err := NewClient().PlanPluginLanguageServer(testContext(t), manifest, "script", PluginBackendDirectories{PluginDirectory: root, StateDirectory: t.TempDir(), Architecture: PluginArchitecture(), ProjectCodeAllowed: true}) if err != nil { t.Fatal(err) } diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index a74f0ba76..6288bcaa1 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -2093,6 +2093,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.status.lineEndingLF": "LF", "desktop.status.lspFailed": "LSP failed", "desktop.status.lspReady": "LSP ready", + "desktop.status.lspSafeMode": "LSP safe mode", "desktop.status.lspStarting": "LSP starting", "desktop.status.lspStopped": "LSP stopped", "desktop.status.memory": "Memory", @@ -2293,7 +2294,11 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.trust.banner": "Safe mode, limited functionality. Trust the project to access full IDE functionality.", "desktop.trust.bannerLink": "Trust Project…", "desktop.trust.dontOpen": "Don’t Open", + "desktop.trust.gitSafeMode": "Safe mode does not run Git, because the repository's configuration can name programs Git runs. Trust the project to see its changes and history.", + "desktop.trust.launchSafeMode": "Safe mode does not start this process, because it can run code from the project. Trust the project to start it.", "desktop.trust.location": "Trust all projects in the “{folder}” folder", + "desktop.trust.lspSafeMode": "Safe mode does not start this language server, because it can run code from the project. It starts once you trust the project.", + "desktop.trust.lspSafeModeHeading": "Starts once you trust the project", "desktop.trust.modelSafeMode": "Safe mode: the model is not loaded. Reload to trust the project and load it.", "desktop.trust.openText": "Lithe provides features that may run code from this folder, such as build scripts, build wrappers and build-tool extensions. If you don’t trust the source, preview the project in safe mode to only browse its code.", "desktop.trust.openTitle": "Trust and Open Project “{project}”?", @@ -2302,6 +2307,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.trust.stayInSafeMode": "Stay in Safe Mode", "desktop.trust.title": "Trust Project?", "desktop.trust.trustProject": "Trust Project", + "desktop.trust.vcsSafeMode": "Safe mode does not run version control, because the working copy's configuration can name programs it runs. Trust the project to use it.", "desktop.updates.arrow.available": "Lithe {version} is available. Click to see what changed", "desktop.updates.arrow.downloading": "Downloading Lithe {version}… {percent}%", "desktop.updates.arrow.ready": "Lithe {version} is downloaded. Click to review and restart", @@ -5385,6 +5391,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.status.lineEndingLF": "LF", "desktop.status.lspFailed": "LSP 出错", "desktop.status.lspReady": "LSP 就绪", + "desktop.status.lspSafeMode": "LSP 安全模式", "desktop.status.lspStarting": "LSP 启动中", "desktop.status.lspStopped": "LSP 已停止", "desktop.status.memory": "内存", @@ -5585,7 +5592,11 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.trust.banner": "安全模式,功能受限。信任此项目后即可使用完整的 IDE 功能。", "desktop.trust.bannerLink": "信任项目…", "desktop.trust.dontOpen": "不打开", + "desktop.trust.gitSafeMode": "安全模式不运行 Git,因为仓库配置可以指定 Git 要运行的程序。信任项目后才显示更改和历史。", + "desktop.trust.launchSafeMode": "安全模式不启动此进程,因为它可能运行项目中的代码。信任项目后即可启动。", "desktop.trust.location": "信任“{folder}”文件夹中的所有项目", + "desktop.trust.lspSafeMode": "安全模式不启动此语言服务器,因为它可能运行项目中的代码。信任项目后才会启动。", + "desktop.trust.lspSafeModeHeading": "信任项目后才会启动", "desktop.trust.modelSafeMode": "安全模式:未加载项目模型。点击重新加载可信任项目并加载。", "desktop.trust.openText": "Lithe 的部分功能可能运行此文件夹中的代码,例如构建脚本、构建包装器和构建工具扩展。如果不信任来源,请以安全模式预览项目,只浏览代码。", "desktop.trust.openTitle": "信任并打开项目“{project}”?", @@ -5594,6 +5605,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.trust.stayInSafeMode": "保持安全模式", "desktop.trust.title": "信任项目?", "desktop.trust.trustProject": "信任项目", + "desktop.trust.vcsSafeMode": "安全模式不运行版本控制,因为工作副本的配置可以指定要运行的程序。信任项目后即可使用。", "desktop.updates.arrow.available": "Lithe {version} 可更新,点击查看更新内容", "desktop.updates.arrow.downloading": "正在下载 Lithe {version}… {percent}%", "desktop.updates.arrow.ready": "Lithe {version} 已下载,点击查看并重启更新", diff --git a/desktop/internal/pluginbackend/pluginbackend.go b/desktop/internal/pluginbackend/pluginbackend.go index baaa3508a..5164defe7 100644 --- a/desktop/internal/pluginbackend/pluginbackend.go +++ b/desktop/internal/pluginbackend/pluginbackend.go @@ -136,6 +136,10 @@ type StartRequest struct { Settings map[string]json.RawMessage // ProjectSettings is the separately captured project override layer. ProjectSettings map[string]json.RawMessage + // ProjectCodeAllowed is whether the user trusts the workspace. Without it Core plans no + // language server, build provider process or VCS provider that would run project code + // (core.LaunchUntrustedWorkspace). + ProjectCodeAllowed bool // Environment is added to the provider process environment. It is for host // integration tests and host-owned facts, never plugin-controlled secrets. Environment map[string]string @@ -310,6 +314,7 @@ func (r *Runner) Start(ctx context.Context, request StartRequest) (Session, erro Architecture: request.Architecture, Settings: request.Settings, ProjectSettings: request.ProjectSettings, + ProjectCodeAllowed: request.ProjectCodeAllowed, } var plan core.PluginBackendPlan var err error diff --git a/desktop/internal/pluginhost/pluginhost.go b/desktop/internal/pluginhost/pluginhost.go index f57ba8a03..730a38af7 100644 --- a/desktop/internal/pluginhost/pluginhost.go +++ b/desktop/internal/pluginhost/pluginhost.go @@ -209,6 +209,10 @@ func Declared() Capabilities { // Version 1 adds installers that download a pinned archive instead of running // a tool; the host extracts it below the plugin's managed command directory. declared["commandInstallers"] = []int{0, 1} + // Version 1 adds a server's executesProjectCode: in a project in safe mode Core + // starts only the servers that declare false, and the status bar says why the + // others wait for trust (#2208). + declared["languageServers"] = []int{0, 1} return declared } diff --git a/desktop/internal/pluginhost/pluginhost_test.go b/desktop/internal/pluginhost/pluginhost_test.go index 308d7ce95..3be348f64 100644 --- a/desktop/internal/pluginhost/pluginhost_test.go +++ b/desktop/internal/pluginhost/pluginhost_test.go @@ -95,6 +95,10 @@ func TestDeclaredServesTheBaselineOfEveryWiredCapability(t *testing.T) { if name == "commandInstallers" { wanted = []int{0, 1} } + // Safe mode starts the servers that declare the executesProjectCode version 1 adds as false. + if name == "languageServers" { + wanted = []int{0, 1} + } if versions := declared[name]; !slices.Equal(versions, wanted) { t.Fatalf("%s = %v, want %v", name, versions, wanted) } diff --git a/desktop/internal/pluginservice/backendlaunch.go b/desktop/internal/pluginservice/backendlaunch.go index 0c8762b32..cbccc770e 100644 --- a/desktop/internal/pluginservice/backendlaunch.go +++ b/desktop/internal/pluginservice/backendlaunch.go @@ -64,6 +64,7 @@ func (s *Service) resolveBackendLaunch(ctx context.Context, pluginID, version st Architecture: start.Architecture, Settings: start.Settings, ProjectSettings: start.ProjectSettings, + ProjectCodeAllowed: start.ProjectCodeAllowed, } plan, err := s.kernel.PlanPluginLanguageServer(ctx, manifest, languageID, request) if err != nil { diff --git a/desktop/internal/pluginservice/backends.go b/desktop/internal/pluginservice/backends.go index 340ec0f63..a1f4f565c 100644 --- a/desktop/internal/pluginservice/backends.go +++ b/desktop/internal/pluginservice/backends.go @@ -27,6 +27,10 @@ type BackendRequest struct { Context ContextRef // Architecture is the platform architecture Core plans for. Architecture string + // ProjectCodeAllowed is whether the user trusts the workspace. Without it Core plans no + // language server that would run project code, and the start fails with + // core.LaunchUntrustedWorkspace. + ProjectCodeAllowed bool // RuntimeProgress reports cancellable preparation before the bounded server // launch. It may be called from a worker goroutine. RuntimeProgress func(pluginruntime.Progress) @@ -116,20 +120,21 @@ func (s *Service) StartLanguageServer(ctx context.Context, entries []pluginmanag return fail(stateErr) } start := pluginbackend.StartRequest{ - Manifest: manifest, - PackageDirectory: entry.Installed.Path, - PluginID: entry.Installed.ID, - ProviderID: entry.Installed.ID + "/language-server", - LanguageID: languageID, - Attempt: attempt, - StateDirectory: stateDirectory, - LogDirectory: s.logDirectory(ctx, entry.Installed.ID), - Architecture: request.Architecture, - Settings: settings.State.Settings, - ProjectSettings: settings.State.ProjectSettings, - RootURI: request.RootURI, - WorkingDirectory: request.WorkingDirectory, - ManagedTools: runtimes.Tools, + Manifest: manifest, + PackageDirectory: entry.Installed.Path, + PluginID: entry.Installed.ID, + ProviderID: entry.Installed.ID + "/language-server", + LanguageID: languageID, + Attempt: attempt, + StateDirectory: stateDirectory, + LogDirectory: s.logDirectory(ctx, entry.Installed.ID), + Architecture: request.Architecture, + Settings: settings.State.Settings, + ProjectSettings: settings.State.ProjectSettings, + RootURI: request.RootURI, + WorkingDirectory: request.WorkingDirectory, + ManagedTools: runtimes.Tools, + ProjectCodeAllowed: request.ProjectCodeAllowed, } temporary := "" if declaresBackendLaunch(manifest, languageID) { diff --git a/desktop/internal/pluginservice/runtimes_test.go b/desktop/internal/pluginservice/runtimes_test.go index 50d052e89..e8c792696 100644 --- a/desktop/internal/pluginservice/runtimes_test.go +++ b/desktop/internal/pluginservice/runtimes_test.go @@ -542,7 +542,7 @@ func TestRuntimePreparationOwnsLanguageServerStartUntilCancelledProcessStops(t * var startErr error go func() { defer close(startDone) - _, startErr = service.StartLanguageServer(work, []pluginmanager.Entry{entry}, "fixture", BackendRequest{Architecture: core.PluginArchitecture()}) + _, startErr = service.StartLanguageServer(work, []pluginmanager.Entry{entry}, "fixture", BackendRequest{Architecture: core.PluginArchitecture(), ProjectCodeAllowed: true}) }() t.Cleanup(func() { cancelWork(); release(); joinRuntimeWorker(t, startDone, "late language-server start") }) select { diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index ceb07ab7b..4df61bc70 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -1603,10 +1603,12 @@ func (a *App) openProjectHere(path string) { func (a *App) openProjectWithTrust(root string, trusted bool) { a.requestCloseProject(func() { a.reduceRecent(a.recent, core.RecordRecent(root, a.now()), true) - // Every Git command the project runs is kept in the Git console. - ctx, cancel := context.WithCancel(core.WithGitConsole(context.Background(), a.gitConsole, root)) - p := &project{root: root, name: filepath.Base(root), ctx: ctx, cancel: cancel, commit: newCommitState()} + p := &project{root: root, name: filepath.Base(root), commit: newCommitState()} p.trust.codeAllowed.Store(trusted) + // Every Git command the project runs is kept in the Git console, and in safe mode Core + // runs none: the repository's configuration can name programs Git runs (#2208). + ctx := core.WithProjectCodeAllowed(core.WithGitConsole(context.Background(), a.gitConsole, root), p.trust.allowed) + p.ctx, p.cancel = context.WithCancel(ctx) a.searchView.reset() a.openTerminals(p) a.project = p diff --git a/desktop/internal/workbench/build.go b/desktop/internal/workbench/build.go index 5149dff03..544f64d85 100644 --- a/desktop/internal/workbench/build.go +++ b/desktop/internal/workbench/build.go @@ -479,6 +479,9 @@ func (a *App) standaloneBuildProvider(ctx context.Context, p *project, instance ProjectSettings: settings.ProjectSettings, RootURI: rootURI, WorkingDirectory: p.root, + // Core plans no provider process that runs project code in safe mode; the requests + // that would reach it already ask to trust the project first. + ProjectCodeAllowed: p.trust.allowed(), BeforeResolveTool: func(ctx context.Context) error { revision, err := a.buildToolchainSource(ctx, p) if err != nil { @@ -687,10 +690,11 @@ func (a *App) sharedBuildProvider(ctx context.Context, p *project, instance buil return nil, err } session, err := a.plugins.StartLanguageServer(ctx, entries, languageID, pluginservice.BackendRequest{ - RootURI: rootURI, - WorkingDirectory: p.root, - Context: p.pluginContext, - Architecture: core.PluginArchitecture(), + RootURI: rootURI, + WorkingDirectory: p.root, + Context: p.pluginContext, + Architecture: core.PluginArchitecture(), + ProjectCodeAllowed: p.trust.allowed(), }) if err != nil { return nil, err diff --git a/desktop/internal/workbench/build_tree_view.go b/desktop/internal/workbench/build_tree_view.go index 58e4b65ce..a03eb3503 100644 --- a/desktop/internal/workbench/build_tree_view.go +++ b/desktop/internal/workbench/build_tree_view.go @@ -174,9 +174,9 @@ func (a *App) buildFilter(c ui.C, p *project) { func (a *App) buildNotice(c ui.C, message, hint string, action func()) { ui.Column(c).Fill().Center().Gap(8).PadX(shellContentPad).Children(func() { ui.Icon(c, icons.Wrench).Size(28, 28).Shrink(0).Color(a.colors.Subtle).Opacity(0.6) - ui.Paragraph(c, message, 3).TextCenter().Color(a.colors.Text) + ui.Paragraph(c, message, 3).FillWidth().TextCenter().Color(a.colors.Text) if hint != "" { - ui.Paragraph(c, hint, 4).TextCenter().FontSize(treeFontSize - 1).Color(a.colors.Subtle) + ui.Paragraph(c, hint, 4).FillWidth().TextCenter().FontSize(treeFontSize - 1).Color(a.colors.Subtle) } if action != nil { action() diff --git a/desktop/internal/workbench/command_installers.go b/desktop/internal/workbench/command_installers.go index b9afa54be..69f9047d0 100644 --- a/desktop/internal/workbench/command_installers.go +++ b/desktop/internal/workbench/command_installers.go @@ -632,12 +632,16 @@ func commandMissingMessage(language i18n.Language, err error) (string, bool) { } // launchFailureText is the message of a plugin launch or provider request that failed: the -// missing commands when it found none, the provider's own message when the provider answered -// with an error, the error itself otherwise. +// missing commands when it found none, why safe mode holds the process back when Core refused +// it for want of trust, the provider's own message when the provider answered with an error, +// the error itself otherwise. func (a *App) launchFailureText(err error) string { if message, ok := commandMissingMessage(a.language(), err); ok { return message } + if core.IsLaunchUntrustedWorkspace(err) { + return i18n.Shared(a.language(), "desktop.trust.launchSafeMode") + } var provider *buildprovider.ProviderError if errors.As(err, &provider) { return provider.UserMessage() diff --git a/desktop/internal/workbench/commit_view.go b/desktop/internal/workbench/commit_view.go index 34e0201ed..473494006 100644 --- a/desktop/internal/workbench/commit_view.go +++ b/desktop/internal/workbench/commit_view.go @@ -125,11 +125,13 @@ func (a *App) drawCommitToolbar(c ui.C, p *project) { func (a *App) drawCommitStatus(c ui.C, p *project) bool { g := a.text.Git switch { + case p.git.safeMode: + a.safeModePanel(c, p, i18n.Shared(a.language(), "desktop.trust.gitSafeMode")) case !p.git.loaded: a.gitEmpty(c, g.Loading) case p.git.err != nil: ui.Column(c).Fill().Center().Gap(8).PadX(shellContentPad).Children(func() { - ui.Paragraph(c, g.Failed(p.git.err.Error()), 3).TextCenter().Color(a.colors.Subtle) + ui.Paragraph(c, g.Failed(p.git.err.Error()), 3).FillWidth().TextCenter().Color(a.colors.Subtle) if ui.Button(c, g.Retry).Ghost().Clicked() { c.After(func() { a.refreshChanges(p) }) } diff --git a/desktop/internal/workbench/debug_launch.go b/desktop/internal/workbench/debug_launch.go index deb07afa4..89d9ccb21 100644 --- a/desktop/internal/workbench/debug_launch.go +++ b/desktop/internal/workbench/debug_launch.go @@ -130,7 +130,9 @@ func (a *App) resolveAdapterProcess(ctx context.Context, adapter debugAdapter, p // prepareDebugLaunch runs off the window thread. The Core owns template expansion // and DAP argument bindings; this adapter only verifies and opens native resources. -func (a *App) prepareDebugLaunch(ctx context.Context, start debugStart, stateDirectory, root, targetPath string, generation uint64, unavailable string) (preparedDebugLaunch, error) { +// It reads only p's root and its workspace trust, which is atomic. +func (a *App) prepareDebugLaunch(ctx context.Context, start debugStart, stateDirectory string, p *project, targetPath string, generation uint64, unavailable string) (preparedDebugLaunch, error) { + root := p.root adapter := start.adapter hosted := adapter.Declaration.Transport == "tcpLanguageServer" settings, err := a.loadPluginPreferenceSources(ctx, adapter.Manifest, root) @@ -146,6 +148,9 @@ func (a *App) prepareDebugLaunch(ctx context.Context, start debugStart, stateDir Architecture: core.PluginArchitecture(), Settings: settings.State.Settings, ProjectSettings: settings.State.ProjectSettings, + // A hosted adapter's launch is its language server's, which Core refuses in an + // untrusted workspace when the server runs project code. + ProjectCodeAllowed: p.trust.allowed(), } plan, err := a.kernel.PlanPluginDebugAdapter(ctx, adapter.Manifest, adapter.Declaration.ID, directories) if err != nil { diff --git a/desktop/internal/workbench/debug_launch_test.go b/desktop/internal/workbench/debug_launch_test.go index 5b4a38963..4b93f4575 100644 --- a/desktop/internal/workbench/debug_launch_test.go +++ b/desktop/internal/workbench/debug_launch_test.go @@ -102,7 +102,7 @@ func TestDebugRuntimeArgumentsComeFromTheToolDefinition(t *testing.T) { } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - plan, err := h.app.prepareDebugLaunch(ctx, debugStart{adapter: adapter, request: "launch"}, filepath.Join(t.TempDir(), "state"), p.root, "", 1, "unavailable") + plan, err := h.app.prepareDebugLaunch(ctx, debugStart{adapter: adapter, request: "launch"}, filepath.Join(t.TempDir(), "state"), p, "", 1, "unavailable") if err != nil { t.Fatal(err) } @@ -148,7 +148,7 @@ func TestDebugExecutableLookupSkipsNonFileCandidates(t *testing.T) { copyTestBinary(t, executable) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - plan, err := h.app.prepareDebugLaunch(ctx, debugStart{adapter: adapter, request: "launch"}, filepath.Join(t.TempDir(), "state"), p.root, "", 1, "unavailable") + plan, err := h.app.prepareDebugLaunch(ctx, debugStart{adapter: adapter, request: "launch"}, filepath.Join(t.TempDir(), "state"), p, "", 1, "unavailable") if err != nil { t.Fatal(err) } @@ -198,7 +198,7 @@ func TestDebugReadsProgramFromActualPluginSettingSources(t *testing.T) { } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - plan, err := h.app.prepareDebugLaunch(ctx, debugStart{adapter: adapter, request: "launch"}, filepath.Join(t.TempDir(), "state"), p.root, "", 1, "unavailable") + plan, err := h.app.prepareDebugLaunch(ctx, debugStart{adapter: adapter, request: "launch"}, filepath.Join(t.TempDir(), "state"), p, "", 1, "unavailable") if invalid { if err == nil { t.Fatalf("invalid configured program fell back: %+v", plan.Configuration) @@ -241,7 +241,7 @@ func TestDebugRequiredDirectoriesCreateStateAndLogSlots(t *testing.T) { 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") + plan, err := h.app.prepareDebugLaunch(ctx, debugStart{adapter: adapter, request: "launch"}, stateRoot, p, "", 1, "unavailable") if err != nil { t.Fatalf("prepareDebugLaunch failed for RequiredDirectories slots: %v", err) } diff --git a/desktop/internal/workbench/debug_start.go b/desktop/internal/workbench/debug_start.go index 7a2c7c10e..f55172e1b 100644 --- a/desktop/internal/workbench/debug_start.go +++ b/desktop/internal/workbench/debug_start.go @@ -525,7 +525,7 @@ func (a *App) beginDebug(p *project, start debugStart) { // Assigned only by startup; cleanup reads it after startupDone closes. session.stateDirectory = stateDirectory preparationContext, cancelPreparation := context.WithTimeout(ctx, debugOperationTimeout) - prepared, err := a.prepareDebugLaunch(preparationContext, start, session.stateDirectory, p.root, targetPath, generation, targetUnavailable) + prepared, err := a.prepareDebugLaunch(preparationContext, start, session.stateDirectory, p, targetPath, generation, targetUnavailable) if err != nil { // Only the adapter's own launch is the plugin's start; a debuggee that cannot be // found or a remote endpoint waiting for the user is not. The preparation's diff --git a/desktop/internal/workbench/debug_tcp_test.go b/desktop/internal/workbench/debug_tcp_test.go index 7df12734d..fbe545b93 100644 --- a/desktop/internal/workbench/debug_tcp_test.go +++ b/desktop/internal/workbench/debug_tcp_test.go @@ -9,10 +9,12 @@ import ( "runtime" "strings" "sync" + "sync/atomic" "testing" "time" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginstate" "github.com/1lck/Lithe-IDEA/desktop/internal/store" @@ -348,6 +350,27 @@ func TestDebugTCPEndpointFailureIsShownAndStartsNothing(t *testing.T) { } } +// TestDebugHostedAdapterInSafeModeStartsNothing: an adapter hosted in a language server that +// runs project code is that server's launch, so safe mode refuses it before the server is +// asked for a port, and says why in the user's language rather than in Core's words (#2208). +func TestDebugHostedAdapterInSafeModeStartsNothing(t *testing.T) { + h := debugPluginHarness(t, "dev.lithe.test.debug-hosted", debugHostedManifest, false) + root, _ := fixtureWorkspace(t) + var asked atomic.Bool + h.app.debugHostedPort = func(context.Context, *project, debugAdapter) (int, error) { + asked.Store(true) + return 0, errors.New("the port was asked for") + } + p := openHostedPanel(t, h, root) + h.app.applyProjectTrust(p, false) + h.settle() + h.clickNamed(h.app.text.Debug.Start) + awaitStateWithin(t, h, 20*time.Second, "the failure", func() bool { return p.debug.failure != "" }) + if want := i18n.Shared(h.app.language(), "desktop.trust.launchSafeMode"); p.debug.failure != want || p.debug.activeSession() != nil || asked.Load() { + t.Fatalf("failure = %q, session = %v, port asked = %v; want %q and nothing started", p.debug.failure, p.debug.activeSession(), asked.Load(), want) + } +} + func TestDebugTCPAdapterThatNeverInitializesTimesOut(t *testing.T) { h := debugPluginHarness(t, "dev.lithe.test.debug-hosted", debugHostedManifest, false) root, _ := fixtureWorkspace(t) diff --git a/desktop/internal/workbench/filetree_view.go b/desktop/internal/workbench/filetree_view.go index e0ccb3ef1..d97ec49d8 100644 --- a/desktop/internal/workbench/filetree_view.go +++ b/desktop/internal/workbench/filetree_view.go @@ -60,7 +60,7 @@ func (a *App) projectTree(c ui.C, p *project) { switch { case t.failed != "": ui.Column(c).Fill().Center().Gap(8).Children(func() { - ui.Paragraph(c, a.text.Project.Failed(t.failed), 3).TextCenter().Color(a.colors.Subtle) + ui.Paragraph(c, a.text.Project.Failed(t.failed), 3).FillWidth().TextCenter().Color(a.colors.Subtle) if ui.Button(c, i18n.Shared(a.language(), "ui.retry")).Outline().Clicked() { c.After(func() { a.retryProjectTree(p) }) } diff --git a/desktop/internal/workbench/git.go b/desktop/internal/workbench/git.go index e93086e60..6039abd85 100644 --- a/desktop/internal/workbench/git.go +++ b/desktop/internal/workbench/git.go @@ -16,8 +16,11 @@ const gitTimeout = 30 * time.Second type gitState struct { // loaded is set once the kernel answered, whether it succeeded or failed. loaded bool - status core.GitStatus - err error + // safeMode is set, with loaded, when the status was not read because the project is in safe + // mode: Core runs no Git there (#2208), and the Git views offer to trust the project. + safeMode bool + status core.GitStatus + err error // tree is the same answer indexed for the project tree, which colors the rows of the // changed paths. It is rebuilt whenever the status is replaced. tree treeStatus @@ -42,12 +45,29 @@ func (a *App) reloadGit(p *project) { // readGit reads the status of p under the context policy gives its request. func (a *App) readGit(p *project, policy func(context.Context) context.Context) { generation := p.gitStatusGeneration.Add(1) + if p.safeMode() { + // The repository's configuration can name a program Git runs while it reads the status + // (core.fsmonitor), so safe mode reads none until the project is trusted + // (applyProjectTrust). + a.setGit(p, gitState{loaded: true, safeMode: true}, generation) + return + } kernel, root := a.kernel, p.root a.background(p, gitTimeout, func(ctx context.Context) func(*App) { status, err := kernel.GitStatus(policy(ctx), root) return func(a *App) { wasRepo := p.git.isRepository() - if !a.setGit(p, gitState{loaded: true, status: status, err: err}, generation) { + g := gitState{loaded: true, status: status, err: err} + if core.IsGitUntrustedWorkspace(err) { + // The trust was withdrawn while the read was on its way: Core ran no Git, and the + // views show safe mode rather than a failure. + g = gitState{loaded: true, safeMode: true} + } + if !a.setGit(p, g, generation) { + return + } + if g.safeMode { + a.backgroundFailed("git_status_safe_mode", err) return } if err != nil { diff --git a/desktop/internal/workbench/git_observation.go b/desktop/internal/workbench/git_observation.go index acfa0f5e4..300cb4c59 100644 --- a/desktop/internal/workbench/git_observation.go +++ b/desktop/internal/workbench/git_observation.go @@ -47,10 +47,11 @@ type gitObservation struct { } // startGitObservation resolves the metadata roots of the project in the background and -// installs their watches. The first answer rescans the status once. +// installs their watches. The first answer rescans the status once. Finding the roots runs Git, +// so a project in safe mode is observed once it is trusted (applyProjectTrust). func (a *App) startGitObservation(p *project) { kernel, ok := a.kernel.(gitObserveKernel) - if !ok || p.observe.metadata != nil || p.observe.watches != nil { + if !ok || p.safeMode() || p.observe.metadata != nil || p.observe.watches != nil { return } p.observe.gen++ diff --git a/desktop/internal/workbench/git_widgets.go b/desktop/internal/workbench/git_widgets.go index 40e34881e..3d5559b60 100644 --- a/desktop/internal/workbench/git_widgets.go +++ b/desktop/internal/workbench/git_widgets.go @@ -28,13 +28,13 @@ func (a *App) gitToolButton(c ui.C, label string, icon gfx.Icon, on, disabled bo // gitEmpty declares the message that stands for an empty pane. func (a *App) gitEmpty(c ui.C, message string) { ui.Column(c).Fill().Center().PadX(shellContentPad).Children(func() { - ui.Paragraph(c, message, 3).TextCenter().Color(a.colors.Subtle) + ui.Paragraph(c, message, 3).FillWidth().TextCenter().Color(a.colors.Subtle) }) } // panelMessage declares a centered empty or progress message. func (a *App) panelMessage(c ui.C, message string, color gfx.Color) { ui.Column(c).Fill().Center().PadX(shellContentPad).Children(func() { - ui.Paragraph(c, message, 3).TextCenter().Color(color) + ui.Paragraph(c, message, 3).FillWidth().TextCenter().Color(color) }) } diff --git a/desktop/internal/workbench/gitlog_view.go b/desktop/internal/workbench/gitlog_view.go index 817aa0801..d4854b31e 100644 --- a/desktop/internal/workbench/gitlog_view.go +++ b/desktop/internal/workbench/gitlog_view.go @@ -855,6 +855,9 @@ func (a *App) drawLogChip(c ui.C, i int, label, value string, open bool) ui.Box func (a *App) drawLogList(c ui.C, p *project) { l, v, g := &p.log, &a.logView, a.text.Git switch { + case p.git.safeMode: + a.safeModePanel(c, p, i18n.Shared(a.language(), "desktop.trust.gitSafeMode")) + return case !p.git.loaded || l.loading && len(l.commits) == 0: a.gitEmpty(c, g.Loading) return diff --git a/desktop/internal/workbench/gitworktree_view.go b/desktop/internal/workbench/gitworktree_view.go index ed7462a05..b6ee2f103 100644 --- a/desktop/internal/workbench/gitworktree_view.go +++ b/desktop/internal/workbench/gitworktree_view.go @@ -151,8 +151,8 @@ func (a *App) drawWorktreeStale(c ui.C, p *project, stale int) { // drawWorktreeEmpty declares a message with its hint that stands for an empty pane. func (a *App) drawWorktreeEmpty(c ui.C, title, hint string) { ui.Column(c).Fill().Center().Gap(6).PadX(shellContentPad).Children(func() { - ui.Paragraph(c, title, 2).TextCenter().Weight(gfx.WeightMedium) - ui.Paragraph(c, hint, 4).TextCenter().FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) + ui.Paragraph(c, title, 2).FillWidth().TextCenter().Weight(gfx.WeightMedium) + ui.Paragraph(c, hint, 4).FillWidth().TextCenter().FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) }) } diff --git a/desktop/internal/workbench/lsp_status.go b/desktop/internal/workbench/lsp_status.go index 2a5c4e6c1..c3d3786cb 100644 --- a/desktop/internal/workbench/lsp_status.go +++ b/desktop/internal/workbench/lsp_status.go @@ -205,6 +205,9 @@ func (a *App) lspStatusText() string { return i18n.Shared(a.language(), "desktop.status.lspStarting") } if failed := a.lspStatusFailedServer(); failed != nil { + if failed.untrusted { + return i18n.Shared(a.language(), "desktop.status.lspSafeMode") + } return i18n.Shared(a.language(), "desktop.status.lspFailed") } return "" @@ -262,14 +265,14 @@ func lspPhaseIcon(server *pluginServer) gfx.Icon { // lspStatusColor is the color of the status bar item's dot: the success color for a ready // server, the warning color while it starts, the danger color when it failed and subdued when -// it stopped or no server serves the document. +// it stopped, safe mode holds it back or no server serves the document. func (a *App) lspStatusColor() gfx.Color { server := a.lspStatusServer() if server == nil { if a.lspStatusPreparation() != nil { return a.colors.Warning } - if a.lspStatusFailedServer() != nil { + if failed := a.lspStatusFailedServer(); failed != nil && !failed.untrusted { return a.theme.Danger } return a.colors.Subtle @@ -451,25 +454,41 @@ func (a *App) lspStatusMenu(c ui.C, anchor ui.Box) { for _, entry := range failed { id := entry.displayID() langID := entry.languageID - description := failedText + description, icon := failedText, icons.CircleX + if entry.untrusted { + description, icon = i18n.Shared(language, "desktop.status.lspSafeMode"), icons.Lock + } if entry.version != "" { description += " · " + entry.version } menu.Sub(id, func(sub *ui.MenuItems) { - if entry.message != "" { - sub.Label(entry.message) + // A menu sizes to its items, not its headings, so a heading wider than them + // is cut short: safe mode's heading is a short one, the reason is in the log. + heading := entry.message + if entry.untrusted { + heading = i18n.Shared(language, "desktop.trust.lspSafeModeHeading") + sub.WidthRange(240, 0) + } + if heading != "" { + sub.Label(heading) sub.Separator() } if sub.Item(viewLogs).Icon(icons.FileText).Clicked() { c.After(func() { a.showLSPLog(p, id) }) } + if entry.untrusted { + if sub.Item(i18n.Shared(language, "desktop.trust.bannerLink")).Icon(icons.LockOpen).Disabled(p.trust.asking).Clicked() { + c.After(func() { a.askToTrustProject(p, nil) }) + } + return + } if sub.Item(i18n.Shared(language, "desktop.lsp.restartServer")).Icon(icons.RefreshCw).Clicked() { c.After(func() { a.performed("lsp.server.restart", surfaceMenu) a.retryFailedLSPServer(langID) }) } - }).Icon(icons.CircleX).Description(description) + }).Icon(icon).Description(description) } if len(servers) > 0 || len(failed) > 0 { menu.Separator() @@ -489,7 +508,10 @@ func (a *App) lspStatusMenu(c ui.C, anchor ui.Box) { a.restartLSPServer(server) } for _, entry := range failed { - a.retryFailedLSPServer(entry.languageID) + // A server safe mode holds back starts once the project is trusted. + if !entry.untrusted { + a.retryFailedLSPServer(entry.languageID) + } } }) } @@ -725,6 +747,8 @@ func (a *App) lspLogBar(c ui.C, servers []*pluginServer, failed []*failedPluginS stateText := "failed" if shown != nil { stateText = shown.stateName() + } else if shownFailed != nil && shownFailed.untrusted { + stateText = "untrusted" } ui.Text(c, i18n.SharedFormat(language, "desktop.lsp.state", map[string]string{"state": stateText})). FontSize(12).Color(a.colors.Subtle).Shrink(0) @@ -764,6 +788,13 @@ func (a *App) lspLogBar(c ui.C, servers []*pluginServer, failed []*failedPluginS a.restartLSPServer(server) }) } + } else if shownFailed != nil && shownFailed.untrusted { + // Safe mode holds the server back; trusting the project starts it. + if p := shownFailed.project; p == a.project { + if ui.Button(c.Key("lspTrust"), i18n.Shared(language, "desktop.trust.bannerLink")).Icon(icons.LockOpen).Ghost().Small().Disabled(p.trust.asking).Clicked() { + c.After(func() { a.askToTrustProject(p, nil) }) + } + } } else if shownFailed != nil { langID := shownFailed.languageID if ui.Button(c.Key("lspRestart"), i18n.Shared(language, "desktop.lsp.restartServer")).Icon(icons.RefreshCw).Ghost().Small().Clicked() { diff --git a/desktop/internal/workbench/outline_view.go b/desktop/internal/workbench/outline_view.go index 15e7a9348..438d8d9f4 100644 --- a/desktop/internal/workbench/outline_view.go +++ b/desktop/internal/workbench/outline_view.go @@ -225,9 +225,9 @@ func (a *App) outlineStatus(c ui.C, s *outlineState) { func (a *App) outlineNotice(c ui.C, message, hint string, action func()) { ui.Column(c).Fill().Center().Gap(8).PadX(shellContentPad).Children(func() { ui.Icon(c, icons.ListTree).Size(28, 28).Shrink(0).Color(a.colors.Subtle).Opacity(0.6) - ui.Paragraph(c, message, 3).TextCenter().Color(a.colors.Text) + ui.Paragraph(c, message, 3).FillWidth().TextCenter().Color(a.colors.Text) if hint != "" { - ui.Paragraph(c, hint, 4).TextCenter().FontSize(treeFontSize - 1).Color(a.colors.Subtle) + ui.Paragraph(c, hint, 4).FillWidth().TextCenter().FontSize(treeFontSize - 1).Color(a.colors.Subtle) } if action != nil { action() diff --git a/desktop/internal/workbench/pluginbackends.go b/desktop/internal/workbench/pluginbackends.go index 5369df9e9..17be21179 100644 --- a/desktop/internal/workbench/pluginbackends.go +++ b/desktop/internal/workbench/pluginbackends.go @@ -53,6 +53,10 @@ type failedPluginServer struct { message string logs []lspLogLine logsAdded uint64 + // untrusted is set when Core planned no server because the project is in safe mode and the + // server may run the project's code (#2208). It is no failure: the status bar says safe + // mode, and trusting the project starts the server (applyProjectTrust). + untrusted bool } func (f *failedPluginServer) displayID() string { @@ -310,6 +314,16 @@ func (a *App) finishPluginServerStart(p *project, languageID, failedPluginID, fa a.recordPluginServerFailure(p, languageID, failedPluginID, failedVersion, errors.New(i18n.Shared(a.language(), "desktop.lsp.preparationCancelled")), nil, 0) return } + if core.IsLaunchUntrustedWorkspace(err) { + if p.trust.allowed() { + // The project was trusted while Core planned this start: plan it again. + a.startPluginServer(languageID) + return + } + a.backgroundFailed("plugin_server_safe_mode", err) + a.recordPluginServerSafeMode(p, languageID, failedPluginID, failedVersion) + return + } a.operationFailed("plugin_server_start", err) a.recordPluginServerFailure(p, languageID, failedPluginID, failedVersion, err, nil, 0) a.notifyPluginServerFailure(p, languageID, err) @@ -631,6 +645,9 @@ func (a *App) pluginBackendRequest() pluginservice.BackendRequest { // goroutine; a map here would not fit lsp.startServer's string field. request.WorkingDirectory = a.project.root request.Context = a.project.pluginContext + // In safe mode Core plans only a server that declares it runs no project code; the + // others wait for trust (finishPluginServerStart). + request.ProjectCodeAllowed = a.project.trust.allowed() } return request } @@ -692,6 +709,32 @@ func (a *App) recordPluginServerFailure(p *project, languageID, pluginID, versio a.invalidator.Invalidate() } +// recordPluginServerSafeMode records that Core planned no server for languageID because the +// project is in safe mode and the server may run the project's code. The status bar, its menu +// and the LSP log say so and offer to trust the project, which starts the server. +func (a *App) recordPluginServerSafeMode(p *project, languageID, pluginID, version string) { + if a.project != p || languageID == "" { + return + } + message := i18n.Shared(a.language(), "desktop.trust.lspSafeMode") + a.pluginServerMu.Lock() + if a.pluginServerFailed == nil { + a.pluginServerFailed = make(map[string]*failedPluginServer) + } + a.pluginServerFailed[languageID] = &failedPluginServer{ + pluginID: pluginID, + languageID: languageID, + version: version, + project: p, + message: message, + logs: []lspLogLine{{level: "INFO", text: cutLogLine("[INFO] " + message), tag: len("[INFO]")}}, + logsAdded: 1, + untrusted: true, + } + a.pluginServerMu.Unlock() + a.invalidator.Invalidate() +} + func (a *App) notifyPluginServerFailure(p *project, languageID string, err error) { if a.project != p || err == nil { return diff --git a/desktop/internal/workbench/pluginbackends_test.go b/desktop/internal/workbench/pluginbackends_test.go index 21e54911b..e27e3b96a 100644 --- a/desktop/internal/workbench/pluginbackends_test.go +++ b/desktop/internal/workbench/pluginbackends_test.go @@ -193,9 +193,11 @@ func (k *failingLSPPlanKernel) PlanPluginLanguageServer(context.Context, json.Ra return core.PluginBackendPlan{}, errors.New(msg) } -func TestRetryFailedPluginServersPreservesNotifiedErrorDeduplication(t *testing.T) { - kernel := &failingLSPPlanKernel{testKernel: &testKernel{Client: core.NewClient()}, msg: "missing jdtls"} - h := newHarness(t, kernel) +// settingsFixturePlugins is a plugin service with Core's settings-documents fixture installed and +// enabled: dev.example.settings, whose language server serves the "fixture" language and does +// not declare it runs no project code. +func settingsFixturePlugins(t *testing.T, kernel pluginservice.Kernel) *pluginservice.Service { + t.Helper() preferences, plugins := t.TempDir(), t.TempDir() raw, err := os.ReadFile(contractfixture.CoreFixture("plugins/settings-documents.json")) if err != nil { @@ -221,7 +223,13 @@ func TestRetryFailedPluginServersPreservesNotifiedErrorDeduplication(t *testing. if err := service.Manager.SetEnabled("dev.example.settings", true); err != nil { t.Fatal(err) } - h.app.plugins = service + return service +} + +func TestRetryFailedPluginServersPreservesNotifiedErrorDeduplication(t *testing.T) { + kernel := &failingLSPPlanKernel{testKernel: &testKernel{Client: core.NewClient()}, msg: "missing jdtls"} + h := newHarness(t, kernel) + h.app.plugins = settingsFixturePlugins(t, kernel) h.open(t.TempDir()) h.app.startPluginServer("fixture") diff --git a/desktop/internal/workbench/plugins_test.go b/desktop/internal/workbench/plugins_test.go index c46f1274c..3298c7114 100644 --- a/desktop/internal/workbench/plugins_test.go +++ b/desktop/internal/workbench/plugins_test.go @@ -372,7 +372,7 @@ func TestUninstallStopsProviderSessionsBeforeDeletingFiles(t *testing.T) { }) } else if err == nil { started, err = runtime.session(ctx, h.app.plugins.Backend, h.app.plugins.Root, root, uri, - vcsWindow{PluginID: id, Version: "1.0.0", Directory: directory, Manifest: json.RawMessage(manifest), Vcs: "fakevcs"}, core.PluginSettingsState{}, h.app.pluginLogDirectory) + vcsWindow{PluginID: id, Version: "1.0.0", Directory: directory, Manifest: json.RawMessage(manifest), Vcs: "fakevcs"}, core.PluginSettingsState{}, true, h.app.pluginLogDirectory) } return func(*App) { if err != nil { @@ -415,7 +415,7 @@ func TestUninstallStopsProviderSessionsBeforeDeletingFiles(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() _, err := p.vcs.runtime().session(ctx, h.app.plugins.Backend, h.app.plugins.Root, root, "", - vcsWindow{PluginID: id, Version: "1.0.0"}, core.PluginSettingsState{}, h.app.pluginLogDirectory) + vcsWindow{PluginID: id, Version: "1.0.0"}, core.PluginSettingsState{}, true, h.app.pluginLogDirectory) if !errors.Is(err, buildprovider.ErrClosed) { t.Fatalf("catalog refresh reopened a removed plugin: %v", err) } @@ -532,7 +532,7 @@ func TestEnableReopensVcsAfterCatalogRefresh(t *testing.T) { uri, err := h.app.kernel.PluginDocumentURI(ctx, root, "auto") if err == nil { _, err = sessions.session(ctx, h.app.plugins.Backend, h.app.plugins.Root, root, uri, - vcsWindow{PluginID: id, Version: "1.0.0", Directory: filepath.Join(h.app.plugins.Root, id, "1.0.0"), Manifest: json.RawMessage(vcsFixtureManifest), Vcs: "fakevcs"}, core.PluginSettingsState{}, h.app.pluginLogDirectory) + vcsWindow{PluginID: id, Version: "1.0.0", Directory: filepath.Join(h.app.plugins.Root, id, "1.0.0"), Manifest: json.RawMessage(vcsFixtureManifest), Vcs: "fakevcs"}, core.PluginSettingsState{}, true, h.app.pluginLogDirectory) } return func(*App) { if err != nil { diff --git a/desktop/internal/workbench/vcs.go b/desktop/internal/workbench/vcs.go index d35c8e22f..39b71a90a 100644 --- a/desktop/internal/workbench/vcs.go +++ b/desktop/internal/workbench/vcs.go @@ -178,6 +178,17 @@ type vcsRootView struct { revision int } +// clearFailures forgets why each working copy's changes and history failed, so the window reads +// them again: trusting the project lifts errVcsSafeMode, which an operation that raced the +// revoking of trust may have left. +func (s *vcsState) clearFailures() { + for _, view := range s.views { + for _, root := range view.roots { + root.failure, root.historyFailure = "", "" + } + } +} + // vcsRow is one row of the list of changes: a section's title, with change -1, or a change of // the status at its index. type vcsRow struct { @@ -358,6 +369,12 @@ var errVcsNotNegotiated = errors.New("the provider session did not negotiate its // errVcsToolMissing is a provider whose client none of its commands finds. var errVcsToolMissing = errors.New("the version control client of the provider was not found") +// errVcsSafeMode is an operation of a project the user has not trusted. A provider runs a version +// control client, and the working copy's configuration can name programs that client runs, so no +// operation runs until the project is trusted, not even on a session started before trust was +// revoked (#2208). +var errVcsSafeMode = errors.New("the project is in safe mode") + // live is the running session of key, nil when there is none. func (r *vcsRuntime) live(key string) *buildprovider.Client { r.mu.Lock() @@ -373,7 +390,7 @@ func (r *vcsRuntime) live(key string) *buildprovider.Client { // outside the lock, so detaching on the window thread never waits for a start; a start that lost // to another one or to detaching is stopped again. logDirectory gives the process's ${logDir}, and // is asked only when a process starts. -func (r *vcsRuntime) session(ctx context.Context, runner *pluginbackend.Runner, pluginRoot, root, rootURI string, window vcsWindow, settings core.PluginSettingsState, logDirectory func(context.Context, string) string) (client *buildprovider.Client, err error) { +func (r *vcsRuntime) session(ctx context.Context, runner *pluginbackend.Runner, pluginRoot, root, rootURI string, window vcsWindow, settings core.PluginSettingsState, projectCodeAllowed bool, logDirectory func(context.Context, string) string) (client *buildprovider.Client, err error) { ctx, finish, err := r.launches.begin(ctx, window.PluginID) if err != nil { return nil, err @@ -413,6 +430,7 @@ func (r *vcsRuntime) session(ctx context.Context, runner *pluginbackend.Runner, ProjectSettings: settings.ProjectSettings, RootURI: rootURI, WorkingDirectory: root, + ProjectCodeAllowed: projectCodeAllowed, }) if err != nil { return nil, err @@ -645,6 +663,9 @@ func (a *App) runVcs(ctx context.Context, p *project, sessions *vcsRuntime, call if !ok || a.plugins == nil || a.plugins.Backend == nil { return nil, nil, errVcsNotNegotiated } + if !p.trust.allowed() { + return nil, nil, errVcsSafeMode + } client := sessions.live(call.window.PluginID + "\x00" + call.window.Vcs) if client == nil { settings, err := a.loadPluginPreferenceSources(ctx, call.window.Manifest, p.root) @@ -655,7 +676,7 @@ func (a *App) runVcs(ctx context.Context, p *project, sessions *vcsRuntime, call if err != nil { return nil, nil, err } - if client, err = sessions.session(ctx, a.plugins.Backend, a.plugins.Root, p.root, rootURI, call.window, settings.State, a.pluginLogDirectory); err != nil { + if client, err = sessions.session(ctx, a.plugins.Backend, a.plugins.Root, p.root, rootURI, call.window, settings.State, p.trust.allowed(), a.pluginLogDirectory); err != nil { return nil, nil, err } } @@ -726,6 +747,8 @@ func (a *App) vcsFailureText(err error) string { return message } switch { + case errors.Is(err, errVcsSafeMode), core.IsLaunchUntrustedWorkspace(err): + return i18n.Shared(language, "desktop.trust.vcsSafeMode") case errors.Is(err, errVcsToolMissing): return i18n.Shared(language, "native.theVersionControlClientCouldNotBeRunCheckThatItIsInstalled") case errors.Is(err, errVcsNotNegotiated): diff --git a/desktop/internal/workbench/vcs_view.go b/desktop/internal/workbench/vcs_view.go index a3eea520a..e00222661 100644 --- a/desktop/internal/workbench/vcs_view.go +++ b/desktop/internal/workbench/vcs_view.go @@ -31,6 +31,14 @@ const ( // vcsView declares the window of the provider of it in project p. func (a *App) vcsView(c ui.C, p *project, it item) { window, s, lang := it.vcs, &p.vcs, a.language() + // A project in safe mode runs no provider (errVcsSafeMode), so the window offers trust in + // place of working copies it could neither list nor change. + if p.safeMode() { + ui.Column(c).Fill().Background(a.colors.Editor).Children(func() { + a.safeModePanel(c, p, i18n.Shared(lang, "desktop.trust.vcsSafeMode")) + }) + return + } // The first paint of the window starts the detection, as the Run window starts its own: // After only runs in the paint of a click, and nothing has to be clicked here. if !s.detected && !s.detecting { @@ -85,7 +93,7 @@ func (a *App) vcsWarning(c ui.C, message string) { // Core look for them again. func (a *App) vcsDetectAgain(c ui.C, p *project, message string, color gfx.Color) { ui.Column(c).Fill().Center().Gap(8).PadX(shellContentPad).Children(func() { - ui.Paragraph(c, message, 4).TextCenter().Color(color) + ui.Paragraph(c, message, 4).FillWidth().TextCenter().Color(color) if ui.Button(c, i18n.Shared(a.language(), "native.detectAgain2")).Outline().Disabled(p.vcs.detecting).Clicked() { c.After(func() { a.performed("vcs.detect", surfaceButton) diff --git a/desktop/internal/workbench/viewer_image.go b/desktop/internal/workbench/viewer_image.go index fd738b27a..6bd132de6 100644 --- a/desktop/internal/workbench/viewer_image.go +++ b/desktop/internal/workbench/viewer_image.go @@ -172,7 +172,7 @@ func (a *App) imageFailure(c ui.C, path string) { ui.Column(c.Part("image-failed")).Fill().Center().Gap(10).PadX(20).Children(func() { ui.Icon(c, icons.ImageOff).Size(28, 28).Color(a.colors.Subtle) ui.Text(c, i18n.Shared(a.language(), "desktop.viewer.imageFailed")).FontSize(13).Color(a.colors.Text) - ui.Paragraph(c, path, 2).FontSize(11).TextCenter().Color(a.colors.Subtle) + ui.Paragraph(c, path, 2).FillWidth().FontSize(11).TextCenter().Color(a.colors.Subtle) }) } diff --git a/desktop/internal/workbench/workspace_trust.go b/desktop/internal/workbench/workspace_trust.go index a69d06ea4..f38609103 100644 --- a/desktop/internal/workbench/workspace_trust.go +++ b/desktop/internal/workbench/workspace_trust.go @@ -19,10 +19,19 @@ import ( // decision for opens, the user is asked to trust it, to preview it in safe mode or not to open // it; trusting may cover every project of the parent folder. The decision is machine-local, // kept by Core in the toolchain catalog of the preference directory (toolchains/global.json), -// never in the project. In safe mode the project's code is not run: models are not loaded and -// Core refuses the plans that would run the build tool, a wrapper or a build extension -// (plugin.build.untrustedWorkspace). A run, build, test or reload the user asks for first asks -// to trust the project, and the notice above the editor offers it too. +// never in the project. In safe mode the project's code is not run (#2208): +// - models are not loaded, and Core refuses the plans that would run the build tool, a wrapper +// or a build extension (plugin.build.untrustedWorkspace); +// - Core plans no language server, build provider process or version control provider that +// may run the project's code (plugin.launch.untrustedWorkspace); a language server whose +// plugin declares it runs none still starts; +// - no Git runs, since the repository's configuration can name programs Git runs: the window +// reads no status, and Core refuses any Git of the project's requests +// (git_untrusted_workspace, core.WithProjectCodeAllowed). +// +// A run, build, test or reload the user asks for first asks to trust the project; the notice +// above the editor, the Git and version control windows and the language server status offer +// it too. Trusting the project loads and starts what safe mode left out (applyProjectTrust). // workspaceTrustTimeout bounds reading or saving a trust decision: a Core call and a look at // the workspace folder. @@ -229,14 +238,25 @@ func (a *App) reloadProjectTrust(p *project) { } // applyProjectTrust makes trusted the trust of p. Leaving safe mode loads what safe mode left -// out: the models, and through them the run configurations of the title bar, and the language -// servers that failed for want of the workspace's tools. +// out: Git and the version control provider, the models, and through them the run +// configurations of the title bar, and the language servers Core planned none for or that +// failed for want of the workspace's tools. Entering it again stops Git at once, both the status +// and the watch of the repository's metadata; the language servers already running keep running +// until the project closes. func (a *App) applyProjectTrust(p *project, trusted bool) { was := p.trust.allowed() p.trust.codeAllowed.Store(trusted) - if !trusted || was { + if trusted == was { return } + if !trusted { + a.closeGitObservation(p) + a.loadGit(p) + return + } + a.loadGit(p) + a.startGitObservation(p) + p.vcs.clearFailures() for index := range p.build.instances { instance := &p.build.instances[index] if instance.modelUntrusted { @@ -254,6 +274,17 @@ func (a *App) skipUntrustedModel(instance *buildInstance) { instance.modelError = i18n.Shared(a.language(), "desktop.trust.modelSafeMode") } +// safeModePanel declares what a tool window shows in safe mode in place of what it would read by +// running project code: message, and the button that asks to trust the project. +func (a *App) safeModePanel(c ui.C, p *project, message string) { + ui.Column(c).Fill().Center().Gap(8).PadX(shellContentPad).Children(func() { + ui.Paragraph(c, message, 3).FillWidth().TextCenter().Color(a.colors.Subtle) + if ui.Button(c.Key("trust"), i18n.Shared(a.language(), "desktop.trust.bannerLink")).Ghost().Disabled(p.trust.asking).Clicked() { + c.After(func() { a.askToTrustProject(p, nil) }) + } + }) +} + // safeModeNotice declares the notice above the editor of a project in safe mode, with the link // that asks to trust it, as IDEA's editor notification does. func (a *App) safeModeNotice(c ui.C, p *project) { diff --git a/desktop/internal/workbench/workspace_trust_safe_mode_visual_test.go b/desktop/internal/workbench/workspace_trust_safe_mode_visual_test.go new file mode 100644 index 000000000..3328ccbca --- /dev/null +++ b/desktop/internal/workbench/workspace_trust_safe_mode_visual_test.go @@ -0,0 +1,118 @@ +//go:build vivahead && lithevisual + +package workbench + +import ( + "os" + "path/filepath" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" +) + +// TestVisualSafeModeHoldsBackProjectCode captures what safe mode shows in place of the tools +// that would run project code (#2208): the language server the status bar holds back, with its +// trust action, and the Commit window that reads no Git. +func TestVisualSafeModeHoldsBackProjectCode(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR") + } + if err := os.MkdirAll(out, 0o755); err != nil { + t.Fatal(err) + } + for _, theme := range []string{"light", "dark"} { + for _, language := range []string{"en", "zh-Hans"} { + t.Run(theme+"/"+language, func(t *testing.T) { + visualSafeModeLanguageServer(t, out, theme, language) + visualSafeModeCommit(t, out, theme, language) + }) + } + } +} + +// safeModeVisualHarness opens a headless window of width × height in theme and language. +func safeModeVisualHarness(t *testing.T, kernel Kernel, theme, language string, width, height int) (*harness, *headless.Session) { + t.Helper() + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, settings{Theme: themeChoice(theme), Language: language, DisableAutoSave: true}); err != nil { + t.Fatal(err) + } + var session *headless.Session + h := newHarnessWithDriver(t, Options{Kernel: kernel, Store: prefs, Languages: []string{language}}, func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = width, height + var err error + session, err = headless.Open(config, nil, headless.Options{}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + return h, session +} + +func visualSafeModeLanguageServer(t *testing.T, out, theme, language string) { + t.Helper() + root := t.TempDir() + file := filepath.Join(root, "example.fixture") + if err := os.WriteFile(file, []byte("let answer = 42;\n"), 0o600); err != nil { + t.Fatal(err) + } + h, session := safeModeVisualHarness(t, &testKernel{Client: core.NewClient()}, theme, language, 1200, 760) + h.open(root) + p := h.app.project + h.app.openFile(p, file) + h.settleChain() + d := p.docs.byPath(file) + if d == nil { + t.Fatal("fixture document did not open") + } + d.languageID = "fixture" + h.app.applyProjectTrust(p, false) + h.app.pluginServerMu.Lock() + if h.app.pluginServerFailed == nil { + h.app.pluginServerFailed = make(map[string]*failedPluginServer) + } + h.app.pluginServerFailed["fixture"] = &failedPluginServer{ + pluginID: "dev.example.settings", languageID: "fixture", version: "1.0.0", project: p, + message: i18n.Shared(h.app.language(), "desktop.trust.lspSafeMode"), untrusted: true, + } + h.app.pluginServerMu.Unlock() + h.app.invalidator.Invalidate() + h.settleChain() + h.click(center(h.button(itemLSP))) + h.settleChain() + h.clickNamed("dev.example.settings") + h.settleChain() + if err := session.Advance(time.Second); err != nil { + t.Fatal(err) + } + if err := session.Screenshot(filepath.Join(out, "safe-mode-lsp-"+theme+"-"+language+".png")); err != nil { + t.Fatal(err) + } +} + +func visualSafeModeCommit(t *testing.T, out, theme, language string) { + t.Helper() + dir := newTestRepository(t) + h, session := safeModeVisualHarness(t, &gitKernel{Client: core.NewClient()}, theme, language, 1200, 760) + h.open(dir) + p := h.app.project + h.app.applyProjectTrust(p, false) + h.click(center(h.button(itemCommit))) + h.settleChain() + if !p.git.safeMode { + t.Fatalf("the project is not in safe mode: %+v", p.git) + } + if err := session.Advance(time.Second); err != nil { + t.Fatal(err) + } + if err := session.Screenshot(filepath.Join(out, "safe-mode-commit-"+theme+"-"+language+".png")); err != nil { + t.Fatal(err) + } +} diff --git a/desktop/internal/workbench/workspace_trust_test.go b/desktop/internal/workbench/workspace_trust_test.go index c87aa01d9..1847b9d68 100644 --- a/desktop/internal/workbench/workspace_trust_test.go +++ b/desktop/internal/workbench/workspace_trust_test.go @@ -184,6 +184,94 @@ func TestSafeModeKeepsProjectCodeFromRunningUntilTrusted(t *testing.T) { } } +// In safe mode no Git process runs, since the repository's configuration can name programs Git +// runs: the Commit window says so in place of the changes, the repository's metadata is not +// watched, and trusting the project from the window loads the changes (#2208). +func TestSafeModeRunsNoGitUntilTrusted(t *testing.T) { + dir := newTestRepository(t) + h := newHarness(t, &gitKernel{Client: core.NewClient()}) + h.app.trustEveryWorkspace = false + language := h.app.language() + + openAsking(t, h, dir) + h.clickShared("desktop.trust.previewSafeMode") + p := awaitOpened(t, h, dir) + h.click(center(h.button(itemCommit))) + h.settle() + if !p.git.safeMode || p.git.isRepository() || p.git.err != nil { + t.Fatalf("safe mode read the repository: %+v", p.git) + } + if !h.showsWrapped(i18n.Shared(language, "desktop.trust.gitSafeMode")) || h.shows("changed.txt") { + t.Fatal("the Commit window does not say safe mode runs no Git, or lists the changes") + } + if p.observe.metadata != nil || p.observe.watches != nil { + t.Fatal("safe mode watches the repository's metadata") + } + + h.clickShared("desktop.trust.bannerLink") + awaitStateWithin(t, h, 10*time.Second, "the trust question", func() bool { return len(h.app.prompts.queue) == 1 }) + h.settle() + h.clickShared("desktop.trust.trustProject") + awaitStateWithin(t, h, 10*time.Second, "the changes to load", func() bool { return p.git.isRepository() }) + h.settle() + if p.git.safeMode || !h.shows("changed.txt") || h.showsWrapped(i18n.Shared(language, "desktop.trust.gitSafeMode")) { + t.Fatal("trusting the project did not list the changes") + } + awaitStateWithin(t, h, 10*time.Second, "the metadata watch", func() bool { return p.observe.metadata != nil }) + + // Withdrawing the trust stops Git again: the status and the watch of the metadata. + h.app.applyProjectTrust(p, false) + h.settle() + if !p.git.safeMode || p.observe.metadata != nil || p.observe.watches != nil { + t.Fatalf("withdrawn trust kept Git running: git %+v, watching %v", p.git, p.observe.watches) + } + if !h.showsWrapped(i18n.Shared(language, "desktop.trust.gitSafeMode")) || h.shows("changed.txt") { + t.Fatal("the Commit window still lists the changes of an untrusted project") + } +} + +// In safe mode Core refuses to start a language server that does not declare it runs no project +// code; the host keeps the refusal as safe mode, not as a failure, and trusting the project +// starts the server again (#2208). +func TestSafeModeStartsNoLanguageServerUntilTrusted(t *testing.T) { + kernel := &testKernel{Client: core.NewClient()} + h := newHarness(t, kernel) + h.app.plugins = settingsFixturePlugins(t, kernel) + h.open(t.TempDir()) + p := h.app.project + p.trust.codeAllowed.Store(false) + + failure := func() *failedPluginServer { + h.app.pluginServerMu.Lock() + defer h.app.pluginServerMu.Unlock() + if h.app.pluginServerStarting["fixture"] { + return nil + } + return h.app.pluginServerFailed["fixture"] + } + h.app.startPluginServer("fixture") + awaitStateWithin(t, h, 10*time.Second, "the refused start", func() bool { return failure() != nil }) + refused := failure() + if !refused.untrusted || refused.message != i18n.Shared(h.app.language(), "desktop.trust.lspSafeMode") { + t.Fatalf("refused start = %+v, want safe mode", refused) + } + if len(h.app.notifications.list) != 0 { + t.Fatalf("safe mode notified %+v", h.app.notifications.list) + } + + // The fixture's command may not run here; what matters is that Core no longer refuses it. + h.app.applyProjectTrust(p, true) + awaitStateWithin(t, h, 10*time.Second, "the start after trust", func() bool { + h.app.pluginServerMu.Lock() + defer h.app.pluginServerMu.Unlock() + return !h.app.pluginServerStarting["fixture"] && (h.app.pluginServerFailed["fixture"] != nil || h.app.pluginServerLanguages["fixture"] != "") + }) + if failed := failure(); failed != nil && failed.untrusted { + t.Fatalf("the start after trust = %+v, still safe mode", failed) + } + h.app.stopAllPluginServers() +} + func TestTrustFolderLabelShortensHomeAndLongPaths(t *testing.T) { home := filepath.Join(string(filepath.Separator)+"Users", "ann") // Core returns a slash-separated location even on Windows. diff --git a/docs/assets/workspace-safe-mode/README.md b/docs/assets/workspace-safe-mode/README.md new file mode 100644 index 000000000..ac2ddd6fd --- /dev/null +++ b/docs/assets/workspace-safe-mode/README.md @@ -0,0 +1,18 @@ +# 安全模式不启动项目代码(#2208)无头测试截图 + +来自生产 Viva Page 的无头渲染。工作区由测试在临时目录中创建,语言服务器条目由测试直接写入“安全模式未启动”的状态,Commit 窗口在不受信任的工作区中打开,不调用真实 Git、语言服务器或插件。截图覆盖深色与浅色主题、中文与英文界面,用于确认: + +- 状态栏语言服务器菜单把被安全模式拦下的服务器显示为锁图标和“LSP 安全模式”,子菜单标题完整显示,并提供“查看日志”和“信任项目…”,没有“重启”; +- Commit 窗口用一段可换行的说明代替更改列表,并提供“信任项目…”。 + +截图不代表 macOS/Windows 原生窗口验收。 + +| 场景 | 深色主题 | 浅色主题 | +| --- | --- | --- | +| 语言服务器菜单(中文) | [深色中文](safe-mode-lsp-dark-zh-Hans.png) | [浅色中文](safe-mode-lsp-light-zh-Hans.png) | +| 语言服务器菜单(英文) | [深色英文](safe-mode-lsp-dark-en.png) | [浅色英文](safe-mode-lsp-light-en.png) | +| Commit 窗口(中文) | [深色中文](safe-mode-commit-dark-zh-Hans.png) | [浅色中文](safe-mode-commit-light-zh-Hans.png) | +| Commit 窗口(英文) | [深色英文](safe-mode-commit-dark-en.png) | [浅色英文](safe-mode-commit-light-en.png) | + +复验:从仓库根目录设置绝对路径 `LITHE_VISUAL_OUTPUT_DIR="$(pwd)/docs/assets/workspace-safe-mode"`,通过 +`scripts/desktop/desktop-go.sh test -tags vivahead,lithevisual ./internal/workbench -run '^TestVisualSafeModeHoldsBackProjectCode$' -count=1 -timeout 180s` 生成。 diff --git a/docs/assets/workspace-safe-mode/safe-mode-commit-dark-en.png b/docs/assets/workspace-safe-mode/safe-mode-commit-dark-en.png new file mode 100644 index 000000000..de5e4c06f Binary files /dev/null and b/docs/assets/workspace-safe-mode/safe-mode-commit-dark-en.png differ diff --git a/docs/assets/workspace-safe-mode/safe-mode-commit-dark-zh-Hans.png b/docs/assets/workspace-safe-mode/safe-mode-commit-dark-zh-Hans.png new file mode 100644 index 000000000..6ce9364cd Binary files /dev/null and b/docs/assets/workspace-safe-mode/safe-mode-commit-dark-zh-Hans.png differ diff --git a/docs/assets/workspace-safe-mode/safe-mode-commit-light-en.png b/docs/assets/workspace-safe-mode/safe-mode-commit-light-en.png new file mode 100644 index 000000000..61645f344 Binary files /dev/null and b/docs/assets/workspace-safe-mode/safe-mode-commit-light-en.png differ diff --git a/docs/assets/workspace-safe-mode/safe-mode-commit-light-zh-Hans.png b/docs/assets/workspace-safe-mode/safe-mode-commit-light-zh-Hans.png new file mode 100644 index 000000000..2a6863c81 Binary files /dev/null and b/docs/assets/workspace-safe-mode/safe-mode-commit-light-zh-Hans.png differ diff --git a/docs/assets/workspace-safe-mode/safe-mode-lsp-dark-en.png b/docs/assets/workspace-safe-mode/safe-mode-lsp-dark-en.png new file mode 100644 index 000000000..28f7fdf6f Binary files /dev/null and b/docs/assets/workspace-safe-mode/safe-mode-lsp-dark-en.png differ diff --git a/docs/assets/workspace-safe-mode/safe-mode-lsp-dark-zh-Hans.png b/docs/assets/workspace-safe-mode/safe-mode-lsp-dark-zh-Hans.png new file mode 100644 index 000000000..d43c86221 Binary files /dev/null and b/docs/assets/workspace-safe-mode/safe-mode-lsp-dark-zh-Hans.png differ diff --git a/docs/assets/workspace-safe-mode/safe-mode-lsp-light-en.png b/docs/assets/workspace-safe-mode/safe-mode-lsp-light-en.png new file mode 100644 index 000000000..c2d7c4011 Binary files /dev/null and b/docs/assets/workspace-safe-mode/safe-mode-lsp-light-en.png differ diff --git a/docs/assets/workspace-safe-mode/safe-mode-lsp-light-zh-Hans.png b/docs/assets/workspace-safe-mode/safe-mode-lsp-light-zh-Hans.png new file mode 100644 index 000000000..75507a209 Binary files /dev/null and b/docs/assets/workspace-safe-mode/safe-mode-lsp-light-zh-Hans.png differ diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index c802b1391..a10a6706d 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -301,7 +301,10 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # to another file name (rustup's cargo and rust-analyzer proxies) to the layout path, so probes and # launches start cargo, not rustup; #134 hardens remote connections and #136 logs the remote # connection lifecycle as structured log v2 events. -PINNED_CORE_REVISION="39aa5fb51fcbc9c986536d1c48ab9665e4a68a62" +# Lithe-core-rust main at 4ab420e: #140 records remote workspace trust by target and host real +# path (S01/S02/S04); #141 starts no Git, language server, build provider or VCS that runs project +# code for a workspace the user has not trusted (#2208). +PINNED_CORE_REVISION="4ab420e312dbfe26c14ba1c6e64b059fd4775c70" PROFILE="debug" CHECKOUT_ONLY="no" while [[ $# -gt 0 ]]; do diff --git a/shared/i18n/features/workspace-trust-safe-mode.json b/shared/i18n/features/workspace-trust-safe-mode.json new file mode 100644 index 000000000..0abc2ed9c --- /dev/null +++ b/shared/i18n/features/workspace-trust-safe-mode.json @@ -0,0 +1,65 @@ +{ + "schemaVersion": 1, + "messages": [ + { + "id": "desktop.status.lspSafeMode", + "description": "Status bar and language server menu: a language server that safe mode does not start", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.trust.lspSafeMode", + "description": "Language server menu and log: why a language server is not started while the project is in safe mode", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.trust.lspSafeModeHeading", + "description": "Language server menu: heading of the submenu of a language server that safe mode does not start, short enough for one menu row", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.trust.gitSafeMode", + "description": "Commit and Git log windows: shown in place of changes and history while the project is in safe mode", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.trust.vcsSafeMode", + "description": "Version control window of a plugin provider: shown in place of working copies while the project is in safe mode", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.trust.launchSafeMode", + "description": "Run and Debug windows: why a process a plugin would start is not started while the project is in safe mode", + "platforms": [ + "desktop" + ] + } + ], + "locales": { + "en-US": { + "desktop.status.lspSafeMode": "LSP safe mode", + "desktop.trust.lspSafeMode": "Safe mode does not start this language server, because it can run code from the project. It starts once you trust the project.", + "desktop.trust.gitSafeMode": "Safe mode does not run Git, because the repository's configuration can name programs Git runs. Trust the project to see its changes and history.", + "desktop.trust.vcsSafeMode": "Safe mode does not run version control, because the working copy's configuration can name programs it runs. Trust the project to use it.", + "desktop.trust.launchSafeMode": "Safe mode does not start this process, because it can run code from the project. Trust the project to start it.", + "desktop.trust.lspSafeModeHeading": "Starts once you trust the project" + }, + "zh-CN": { + "desktop.status.lspSafeMode": "LSP 安全模式", + "desktop.trust.lspSafeMode": "安全模式不启动此语言服务器,因为它可能运行项目中的代码。信任项目后才会启动。", + "desktop.trust.gitSafeMode": "安全模式不运行 Git,因为仓库配置可以指定 Git 要运行的程序。信任项目后才显示更改和历史。", + "desktop.trust.vcsSafeMode": "安全模式不运行版本控制,因为工作副本的配置可以指定要运行的程序。信任项目后即可使用。", + "desktop.trust.launchSafeMode": "安全模式不启动此进程,因为它可能运行项目中的代码。信任项目后即可启动。", + "desktop.trust.lspSafeModeHeading": "信任项目后才会启动" + } + } +} diff --git a/shared/platform-feature-matrix/features/workspace-trust.json b/shared/platform-feature-matrix/features/workspace-trust.json index f15acf0ec..989090588 100644 --- a/shared/platform-feature-matrix/features/workspace-trust.json +++ b/shared/platform-feature-matrix/features/workspace-trust.json @@ -9,7 +9,10 @@ "evidence": [ "desktop/internal/workbench/workspace_trust.go", "desktop/internal/workbench/workspace_trust_test.go", - "desktop/internal/toolchain/catalog.go" + "desktop/internal/toolchain/catalog.go", + "desktop/internal/workbench/vcs.go", + "desktop/internal/workbench/lsp_status.go", + "desktop/internal/core/gitconsole.go" ] }, "windows": { @@ -18,10 +21,13 @@ "evidence": [ "desktop/internal/workbench/workspace_trust.go", "desktop/internal/workbench/workspace_trust_test.go", - "desktop/internal/toolchain/catalog.go" + "desktop/internal/toolchain/catalog.go", + "desktop/internal/workbench/vcs.go", + "desktop/internal/workbench/lsp_status.go", + "desktop/internal/core/gitconsole.go" ] }, "owner": "Workspace", - "verification": "打开一个没有信任记录的文件夹,先出现“信任并打开项目”对话框,按钮依次为不打开、以安全模式预览、信任项目,并可勾选信任父文件夹,父文件夹标签使用当前平台的路径分隔符;不打开时当前项目不变。信任后再次打开不再询问;勾选父文件夹后同级项目直接以信任打开。以安全模式预览后,编辑器上方显示安全模式提示条,构建窗口不加载模型,运行、构建、测试和重新加载前先问“信任项目?”,选择保持安全模式时不运行;点提示条的“信任项目…”信任后提示条消失,模型和标题栏运行配置自动加载。确认偏好目录 toolchains/global.json 记录决定,项目目录中没有新增 .lithe 文件。", - "notes": "2026-11-19(#2201):对齐 IntelliJ IDEA 的可信项目。信任状态(trusted/distrusted/unknown 与可信位置)由 Core 的工具链目录判定,计划请求带 projectCodeAllowed,Core 拒绝会运行项目代码的计划(plugin.build.untrustedWorkspace)。宿主无平台分支,两个平台共用同一实现;尚未在两个平台做真实应用验收。语言服务器和 Git 在安全模式下仍启动、可信位置没有独立设置页,分别由 #2208、#2207 跟进。" + "verification": "打开一个没有信任记录的文件夹,先出现“信任并打开项目”对话框,按钮依次为不打开、以安全模式预览、信任项目,并可勾选信任父文件夹,父文件夹标签使用当前平台的路径分隔符;不打开时当前项目不变。信任后再次打开不再询问;勾选父文件夹后同级项目直接以信任打开。以安全模式预览后,编辑器上方显示安全模式提示条,构建窗口不加载模型,运行、构建、测试和重新加载前先问“信任项目?”,选择保持安全模式时不运行;点提示条的“信任项目…”信任后提示条消失,模型和标题栏运行配置自动加载。安全模式下状态栏显示“LSP 安全模式”,语言服务器菜单说明原因并提供“信任项目…”,不提供重启;提交和 Git 日志窗口、插件版本控制窗口显示安全模式说明和“信任项目…”按钮,不运行 Git 或版本控制客户端;信任后语言服务器自动启动,更改和历史自动加载;取消信任后 Git 立即停止,已运行的语言服务器保持运行。确认偏好目录 toolchains/global.json 记录决定,项目目录中没有新增 .lithe 文件。", + "notes": "2026-11-19(#2201):对齐 IntelliJ IDEA 的可信项目。信任状态(trusted/distrusted/unknown 与可信位置)由 Core 的工具链目录判定,计划请求带 projectCodeAllowed,Core 拒绝会运行项目代码的计划(plugin.build.untrustedWorkspace)。宿主无平台分支,两个平台共用同一实现;尚未在两个平台做真实应用验收。可信位置没有独立设置页,由 #2207 跟进。2026-11-21(#2208):语言服务器启动计划带 projectCodeAllowed,Core 在安全模式下只启动声明 executesProjectCode: false 的服务器(languageServers 能力 v1,拒绝码 plugin.launch.untrustedWorkspace),版本控制提供者一律不启动;每个 Git 请求带 gitExecution.projectCodeAllowed,未信任时 Core 不启动 Git 进程(git_untrusted_workspace),宿主也不读取 Git 状态、不监视仓库元数据。两个平台共用同一实现,尚未做真实应用验收。" }