diff --git a/desktop/internal/pluginservice/backendlaunch.go b/desktop/internal/pluginservice/backendlaunch.go index cbccc770e..8b5b5c1a0 100644 --- a/desktop/internal/pluginservice/backendlaunch.go +++ b/desktop/internal/pluginservice/backendlaunch.go @@ -1,6 +1,7 @@ package pluginservice import ( + "bytes" "context" "encoding/json" "fmt" @@ -17,6 +18,23 @@ import ( type backendLaunch struct { plan *core.PluginBackendPlan directories pluginDirectories + // configuration is set when the answer carried its own + // workspaceConfiguration: that value follows the settings only through + // the plugin's function, so an immediate change has to ask it again. + configuration *launchConfiguration +} + +// launchConfiguration is what a running backend-resolved server needs to +// answer its workspace configuration again: the request of its start, whose +// directories stay the server's until it ends, and what the host resolved +// for that start. +type launchConfiguration struct { + pluginID string + manifest json.RawMessage + languageID string + workspace WorkspaceContext + request core.PluginBackendDirectories + runtimes RuntimeEnvironment } // resolveBackendLaunch runs the two steps of a backend-resolved language-server @@ -66,44 +84,92 @@ func (s *Service) resolveBackendLaunch(ctx context.Context, pluginID, version st ProjectSettings: start.ProjectSettings, ProjectCodeAllowed: start.ProjectCodeAllowed, } - plan, err := s.kernel.PlanPluginLanguageServer(ctx, manifest, languageID, request) + launch := launchConfiguration{pluginID: pluginID, manifest: manifest, languageID: languageID, workspace: workspace, request: request, runtimes: runtimes} + decoded, carried, err := s.answerBackendLaunch(ctx, launch) if err != nil { return fail(err) } + // The host creates the parents of the paths the server writes before the + // start, as the contract requires; Core already refused any outside the four + // directories. + for _, path := range decoded.WritablePaths { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return fail(err) + } + } + resolved := backendLaunch{plan: &decoded, directories: directories} + if carried { + resolved.configuration = &launch + } + return resolved, nil +} + +// answerBackendLaunch plans the first step of the launch, calls the plugin's +// function and returns the plan Core decodes from its answer, and whether the +// answer carried its own workspaceConfiguration. Without one, Core fills the +// plan's configuration from the declaration. +func (s *Service) answerBackendLaunch(ctx context.Context, launch launchConfiguration) (core.PluginBackendPlan, bool, error) { + plan, err := s.kernel.PlanPluginLanguageServer(ctx, launch.manifest, launch.languageID, launch.request) + if err != nil { + return core.PluginBackendPlan{}, false, err + } if plan.Launch.Kind != "backend" || plan.Launch.Function == "" { - return fail(fmt.Errorf("%w: the plan is not a backend-resolved launch", pluginbackend.ErrRequest)) + return core.PluginBackendPlan{}, false, fmt.Errorf("%w: the plan is not a backend-resolved launch", pluginbackend.ErrRequest) } // The function's params are the plan's resolveParams themselves, as the // contract says: serverID, platform, the four directories and the settings. - params, err := s.languageLaunchParamsWithRuntimes(ctx, workspace.Path, manifest, plan.ResolveParams, runtimes) + params, err := s.languageLaunchParamsWithRuntimes(ctx, launch.workspace.Path, launch.manifest, plan.ResolveParams, launch.runtimes) if err != nil { - return fail(err) + return core.PluginBackendPlan{}, false, err } - reference, err := json.Marshal(workspace.ContextRef) + reference, err := json.Marshal(launch.workspace.ContextRef) if err != nil { - return fail(err) + return core.PluginBackendPlan{}, false, err } timeout := time.Duration(plan.Launch.TimeoutMilliseconds) * time.Millisecond - answer, err := s.Host.Call(ctx, pluginID, plan.Launch.Function, params, reference, timeout) + answer, err := s.Host.Call(ctx, launch.pluginID, plan.Launch.Function, params, reference, timeout) if err != nil { - return fail(fmt.Errorf("resolve the %s launch: %w", languageID, err)) + return core.PluginBackendPlan{}, false, fmt.Errorf("resolve the %s launch: %w", launch.languageID, err) } - decoded, err := s.kernel.DecodePluginLanguageServerLaunch(ctx, manifest, languageID, request, answer) + decoded, err := s.kernel.DecodePluginLanguageServerLaunch(ctx, launch.manifest, launch.languageID, launch.request, answer) if err != nil { - return fail(err) + return core.PluginBackendPlan{}, false, err } if decoded.Owner == nil { decoded.Owner = plan.Owner } - // The host creates the parents of the paths the server writes before the - // start, as the contract requires; Core already refused any outside the four - // directories. - for _, path := range decoded.WritablePaths { - if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { - return fail(err) - } + return decoded, answerCarriesConfiguration(answer), nil +} + +// answerCarriesConfiguration reports whether a launch answer Core accepted +// has a workspaceConfiguration of its own. +func answerCarriesConfiguration(answer json.RawMessage) bool { + var fields struct { + WorkspaceConfiguration json.RawMessage `json:"workspaceConfiguration"` + } + if json.Unmarshal(answer, &fields) != nil { + return false + } + value := bytes.TrimSpace(fields.WorkspaceConfiguration) + return len(value) > 0 && !bytes.Equal(value, []byte("null")) +} + +// launchWorkspaceConfiguration asks the plugin's function again with the +// current settings and the directories of the running start, and returns +// the workspaceConfiguration of the plan Core decodes. The rest of the +// answer waits for the next start: an immediate setting changes nothing but +// the configuration. +func (s *Service) launchWorkspaceConfiguration(ctx context.Context, launch launchConfiguration, settings, projectSettings map[string]json.RawMessage) (json.RawMessage, error) { + launch.request.Settings = settings + launch.request.ProjectSettings = projectSettings + plan, _, err := s.answerBackendLaunch(ctx, launch) + if err != nil { + return nil, err + } + if value := bytes.TrimSpace(plan.WorkspaceConfiguration); len(value) == 0 || bytes.Equal(value, []byte("null")) { + return nil, nil } - return backendLaunch{plan: &decoded, directories: directories}, nil + return plan.WorkspaceConfiguration, nil } // languageLaunchParams supplies native installation facts, without interpreting diff --git a/desktop/internal/pluginservice/backendlaunch_configuration_test.go b/desktop/internal/pluginservice/backendlaunch_configuration_test.go new file mode 100644 index 000000000..89d8f374b --- /dev/null +++ b/desktop/internal/pluginservice/backendlaunch_configuration_test.go @@ -0,0 +1,196 @@ +package pluginservice + +import ( + "context" + "encoding/json" + "os" + "sync" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginbackend" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" +) + +// launchConfigurationKernel plans, decodes and expands with the real Core and +// answers the launch function itself: the answer derives the server's +// configuration from the `strict` setting the function receives. +type launchConfigurationKernel struct { + *fakeKernel + client *core.Client + backend *BackendSession + carries bool + + mu sync.Mutex + calls int + configuration json.RawMessage +} + +func (k *launchConfigurationKernel) PlanPluginLanguageServer(ctx context.Context, manifest json.RawMessage, languageID string, directories core.PluginBackendDirectories) (core.PluginBackendPlan, error) { + return k.client.PlanPluginLanguageServer(ctx, manifest, languageID, directories) +} + +func (k *launchConfigurationKernel) DecodePluginLanguageServerLaunch(ctx context.Context, manifest json.RawMessage, languageID string, directories core.PluginBackendDirectories, answer json.RawMessage) (core.PluginBackendPlan, error) { + return k.client.DecodePluginLanguageServerLaunch(ctx, manifest, languageID, directories, answer) +} + +func (k *launchConfigurationKernel) ReadPluginSettingsState(ctx context.Context, manifest json.RawMessage, global, project *string, localization *core.PluginSettingsLocalizationRequest) (core.PluginSettingsState, error) { + return k.client.ReadPluginSettingsState(ctx, manifest, global, project, localization) +} + +func (k *launchConfigurationKernel) EditPluginSettings(ctx context.Context, manifest json.RawMessage, scope string, document *string, edits []core.PluginSettingEdit) (core.PluginSettingsEditPlan, error) { + return k.client.EditPluginSettings(ctx, manifest, scope, document, edits) +} + +func (k *launchConfigurationKernel) ExpandPluginWorkspaceConfiguration(ctx context.Context, manifest json.RawMessage, languageID string, global, project map[string]json.RawMessage) (json.RawMessage, error) { + return k.client.ExpandPluginWorkspaceConfiguration(ctx, manifest, languageID, global, project) +} + +func (k *launchConfigurationKernel) UpdatePluginWorkspaceConfiguration(_ context.Context, _ string, configuration json.RawMessage) (bool, error) { + k.mu.Lock() + defer k.mu.Unlock() + k.configuration = append(json.RawMessage(nil), configuration...) + return true, nil +} + +func (k *launchConfigurationKernel) InvokePluginFunctionInContext(_ context.Context, _, operation, _, function string, params, _ json.RawMessage, _ int) (string, error) { + var request struct { + Settings struct { + Strict bool `json:"strict"` + } `json:"settings"` + } + if err := json.Unmarshal(params, &request); err != nil { + return "", err + } + k.mu.Lock() + k.calls++ + k.mu.Unlock() + checks := "relaxed" + if request.Settings.Strict { + checks = "strict" + } + answer := map[string]any{"executable": map[string]string{"kind": "packaged", "path": "server/bin/metals"}} + if k.carries { + answer["workspaceConfiguration"] = map[string]any{"metals": map[string]string{"checks": checks}} + } + value, err := json.Marshal(map[string]any{"value": answer}) + if err != nil { + return "", err + } + go k.backend.observe(core.BackendEvent{Type: "requestCompleted", OperationID: operation, Result: value}) + return operation, nil +} + +func (k *launchConfigurationKernel) counts() (int, string) { + k.mu.Lock() + defer k.mu.Unlock() + return k.calls, string(k.configuration) +} + +// backendLaunchSettingsManifest is the contract's backend-launched server with +// an immediate project setting and a declarative template for it. +func backendLaunchSettingsManifest(t *testing.T) json.RawMessage { + t.Helper() + data, err := os.ReadFile(contractfixture.Path("fixtures/languages/language-server-backend-launch.plugin.json")) + if err != nil { + t.Fatal(err) + } + var manifest map[string]any + if err := json.Unmarshal(data, &manifest); err != nil { + t.Fatal(err) + } + manifest["requires"].(map[string]any)["settings"] = 0 + manifest["settings"] = []any{map[string]any{ + "id": "strict", "type": "boolean", "title": "Strict", "default": false, + "scope": "project", "effect": "immediate", "page": map[string]any{"languageID": "scala"}, + }} + server := manifest["languageServers"].([]any)[0].(map[string]any) + server["workspaceConfiguration"] = map[string]any{"metals": map[string]any{"strict": "${setting:strict}"}} + encoded, err := json.Marshal(manifest) + if err != nil { + t.Fatal(err) + } + return encoded +} + +func TestImmediateSettingAsksTheBackendForTheConfigurationItsLaunchAnswered(t *testing.T) { + for _, carries := range []bool{true, false} { + name := "answer-carries-configuration" + if !carries { + name = "answer-leaves-the-declaration" + } + t.Run(name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + manifest := backendLaunchSettingsManifest(t) + kernel := &launchConfigurationKernel{fakeKernel: &fakeKernel{}, client: core.NewClient(), carries: carries} + service, err := Open(kernel, store.At(t.TempDir()), t.TempDir()) + if err != nil { + t.Fatal(err) + } + const pluginID = "dev.lithe.fixture.language-server-backend-launch" + backend := &BackendSession{ + host: service.Host, PluginID: pluginID, Version: "0.1.0", + Session: pluginbackend.Session{ID: "backend-1"}, + functions: map[string]bool{"metals.resolveLaunch": true}, waiters: map[string]chan core.BackendEvent{}, + done: make(chan struct{}), changed: make(chan struct{}), ready: true, + } + kernel.backend = backend + service.Host.sessions[pluginID] = backend + + workspace := t.TempDir() + workspaceContext := service.Contexts.Open(workspace) + t.Cleanup(service.Contexts.CloseAll) + snapshot, err := service.Settings.Load(ctx, manifest, workspace) + if err != nil { + t.Fatal(err) + } + start := pluginbackend.StartRequest{ + PackageDirectory: t.TempDir(), + StateDirectory: t.TempDir(), + LogDirectory: t.TempDir(), + Architecture: core.PluginArchitecture(), + Settings: snapshot.State.Settings, + ProjectSettings: snapshot.State.ProjectSettings, + ProjectCodeAllowed: true, + } + resolved, err := service.resolveBackendLaunch(ctx, pluginID, "0.1.0", manifest, "scala", workspaceContext, start, RuntimeEnvironment{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { removeTemporary(resolved.directories.temporary) }) + if (resolved.configuration != nil) != carries { + t.Fatalf("kept the launch for later answers = %v, the answer carried a configuration = %v", resolved.configuration != nil, carries) + } + + saved, err := service.Settings.Save(ctx, snapshot, "project", []core.PluginSettingEdit{{ID: "strict", Value: json.RawMessage(`true`)}}, nil) + if err != nil || !saved.Committed { + t.Fatalf("save the setting: %+v, %v", saved, err) + } + session := &LanguageSession{ + PluginID: pluginID, Version: "0.1.0", LanguageID: "scala", manifest: manifest, workspace: workspace, + Session: pluginbackend.Session{ID: "language-1"}, launch: resolved.configuration, + } + result, err := service.ApplyLanguageSettings(ctx, session) + if err != nil || !result.Available || !result.Sent { + t.Fatalf("apply the setting: %+v, %v", result, err) + } + calls, configuration := kernel.counts() + if carries { + // The backend derives its configuration from the settings, so the + // declaration's expansion would replace what it answered. + if calls != 2 || configuration != `{"metals":{"checks":"strict"}}` { + t.Fatalf("calls = %d, configuration = %s", calls, configuration) + } + return + } + // Without one, the declaration is the configuration, and the launch + // function, which may install or download, is not asked again. + if calls != 1 || configuration != `{"metals":{"strict":true}}` { + t.Fatalf("calls = %d, configuration = %s", calls, configuration) + } + }) + } +} diff --git a/desktop/internal/pluginservice/backends.go b/desktop/internal/pluginservice/backends.go index a1f4f565c..0816cc5d5 100644 --- a/desktop/internal/pluginservice/backends.go +++ b/desktop/internal/pluginservice/backends.go @@ -61,6 +61,9 @@ type LanguageSession struct { // temporary is the scratch directory of one backend-resolved start; it is // removed when the process ends. temporary string + // launch is set when the backend's launch answer carried the server's + // workspace configuration; an immediate setting change asks it again. + launch *launchConfiguration languageSessionState } @@ -137,6 +140,7 @@ func (s *Service) StartLanguageServer(ctx context.Context, entries []pluginmanag ProjectCodeAllowed: request.ProjectCodeAllowed, } temporary := "" + var launch *launchConfiguration if declaresBackendLaunch(manifest, languageID) { resolved, resolveErr := s.resolveBackendLaunch(ctx, entry.Installed.ID, entry.Installed.Version, manifest, languageID, workspaceContext, start, runtimes) if resolveErr != nil { @@ -145,6 +149,7 @@ func (s *Service) StartLanguageServer(ctx context.Context, entries []pluginmanag start.Plan = resolved.plan start.WorkspaceStateDirectory = resolved.directories.workspaceState temporary = resolved.directories.temporary + launch = resolved.configuration } if _, contextErr := s.workspaceForBackend(ctx, request); contextErr != nil { removeTemporary(temporary) @@ -180,6 +185,7 @@ func (s *Service) StartLanguageServer(ctx context.Context, entries []pluginmanag ContextID: workspaceContext.ContextID, ContextGeneration: workspaceContext.Generation, temporary: temporary, + launch: launch, } s.registerLanguageSession(session) return session, nil diff --git a/desktop/internal/pluginservice/settings.go b/desktop/internal/pluginservice/settings.go index ec737662d..78c940306 100644 --- a/desktop/internal/pluginservice/settings.go +++ b/desktop/internal/pluginservice/settings.go @@ -2,6 +2,7 @@ package pluginservice import ( "context" + "encoding/json" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginbackend" ) @@ -15,6 +16,9 @@ type LanguageConfigurationResult struct { // ApplyLanguageSettings rereads real sources for the exact running declaration. // Core expands values and updates its existing session; no process is started. +// A server whose backend answered its own workspace configuration at launch +// gets it from the backend again, with the new settings, instead of the +// declaration's expansion, which would replace what the backend derived. // The caller owns admission, session generation and user-visible error handling. func (s *Service) ApplyLanguageSettings(ctx context.Context, session *LanguageSession) (LanguageConfigurationResult, error) { if session == nil { @@ -24,7 +28,12 @@ func (s *Service) ApplyLanguageSettings(ctx context.Context, session *LanguageSe if err != nil { return LanguageConfigurationResult{}, err } - configuration, err := s.kernel.ExpandPluginWorkspaceConfiguration(ctx, session.manifest, session.LanguageID, snapshot.State.Settings, snapshot.State.ProjectSettings) + var configuration json.RawMessage + if session.launch != nil { + configuration, err = s.launchWorkspaceConfiguration(ctx, *session.launch, snapshot.State.Settings, snapshot.State.ProjectSettings) + } else { + configuration, err = s.kernel.ExpandPluginWorkspaceConfiguration(ctx, session.manifest, session.LanguageID, snapshot.State.Settings, snapshot.State.ProjectSettings) + } if err != nil { return LanguageConfigurationResult{}, err }