diff --git a/.agents/notes/implemented/architecture/2026-10-29-run-configuration-detection-in-memory.md b/.agents/notes/implemented/architecture/2026-10-29-run-configuration-detection-in-memory.md index bbca04e1d2..6af1f05b7e 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-run-configuration-detection-in-memory.md +++ b/.agents/notes/implemented/architecture/2026-10-29-run-configuration-detection-in-memory.md @@ -2,6 +2,8 @@ 状态:已实现 +> 2026-11-18 更新:用户层改存 `.lithe/run/configurations.yaml`、`local.yaml` 和按插件拆分的 `.lithe/run/plugin/<插件 ID>.toml`、`<插件 ID>.local.toml`;Core 不再写这些文件,编辑命令返回文件改动,由宿主按哈希检查后应用。内置的脚本与程序运行不经过生成层。决策见[脚本与程序运行由 Core 内置,运行配置存 YAML 和 TOML](2026-11-18-builtin-process-runs-and-run-file-formats.md)。 +> > 2026-11-16 更新:Core 删除了内置的运行发现探测器、项目内容指纹和工具链需求([Lithe-core-rust #77](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/77),#1856 第 4 项)。生成层现在只由构建插件声明的 `buildSystems[].run` 组成。原来的“跨会话缓存语言服务入口”和“识别前也能选 JDK”两节随之删除;分类与重名规则从已归档的 `.agents/notes/archived/feature/2026-09-20-run-configuration-discovery-quality.md` 并入本文,指纹相关的旧做法见已归档的 `.agents/notes/archived/bug-fix/2026-09-22-run-panel-fingerprint-loading.md`。 ## 先说结论 @@ -63,7 +65,7 @@ Core 按规范化后的工作区路径保存最近一次 `runConfig.generate` ### 发布用户文档的保护 -宿主先构造两层文档,用 Core 预检,然后比较所有输入(包括未改写的一层)和偏好状态,才使用带源版本检查的原子替换。写入、回读、取消或冲突失败时,只回滚自身仍未被改动的输出;不覆盖用户或另一进程的新数据。生成任务的租约(可撤销的写入资格)在取消、工作区切换、模型变化或后续生成时失效。 +Core 的编辑命令只返回文件改动(路径、改动前的哈希和新内容),宿主在 `applyRunConfigChanges` 里确认每个文件仍是 Core 读到的字节后才一次性应用;任何一个不符就整体放弃并报冲突。写入或回读失败时,只回滚自身仍未被改动的输出,不覆盖用户或另一进程的新数据。生成任务的租约(可撤销的写入资格)在取消、工作区切换、模型变化或后续生成时失效。 生成层不是持久配置,不参与这套发布。 @@ -97,9 +99,11 @@ Core 按规范化后的工作区路径保存最近一次 `runConfig.generate` 这是[构建系统 Provider 提案](../../proposed/architecture/2026-10-17-build-system-provider-api.md)原来的迁移计划。没有采用:Core 仍然维护生态知识,只是换了格式;插件已经能声明同样的内容。 -### 没有生成层时 `resolve` 按空生成层处理 +### 没有生成层时 `resolve` 按空生成层处理,并照常报孤立覆盖 -对只有稀疏覆盖的文档,这可以少一次“未生成”的判断。但团队层里覆盖自动条目的配置会全部变成“孤立覆盖”,用户会看到一批误导性的诊断。保留 `missing` 并让宿主自动生成更直接。 +对只有稀疏覆盖的文档,这可以少一次“未生成”的判断。但团队层里覆盖自动条目的配置会全部变成“孤立覆盖”,用户会看到一批误导性的诊断。 + +2026-11-18 起采用了折中做法:没有生成层时,`resolve` 返回已保存的配置(一个都没有时返回空列表),让内置的脚本与程序运行不必等构建模型;这时不报孤立覆盖。生成仍由 `inspect` 的 `requiresGeneration` 触发。 ## 后果 diff --git a/.agents/notes/implemented/architecture/2026-11-18-builtin-process-runs-and-run-file-formats.md b/.agents/notes/implemented/architecture/2026-11-18-builtin-process-runs-and-run-file-formats.md new file mode 100644 index 0000000000..c2743f0896 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-18-builtin-process-runs-and-run-file-formats.md @@ -0,0 +1,117 @@ +# Agent 笔记:脚本与程序运行由 Core 内置,运行配置存 YAML(内置)和 TOML(插件) + +状态:已实现 + +## 先说结论 + +Shell 脚本、PowerShell 脚本、cmd 批处理(只在 Windows)和可执行程序四种运行由 Core 自己提供,叫“内置运行”(provider 为 `process.*`)。它们的表单、校验和启动计划都在 Core,宿主只负责画表单、写文件和起进程,不经过任何构建插件,所以 Java 等插件缺失或出错时这四种运行照常可用。 + +用户保存的运行配置换成两种格式:内置运行存 `.lithe/run/configurations.yaml`(团队共享)和 `.lithe/run/local.yaml`(本机);插件提供的运行按插件拆成 `.lithe/run/plugin/<插件 ID>.toml` 和 `<插件 ID>.local.toml`,文件头记录插件的作者、仓库和版本要求。Core 只计算文件改动,不写文件,宿主按哈希检查后一次性应用。 + +## 问题 + +- 运行平台自带的脚本和程序本来就不需要生态知识,却要装插件才能出现在 Run 列表里;插件坏了,连最基本的“跑一下脚本”都做不到(Issue #2100)。 +- 旧的 `.lithe/run/configurations.json` 把所有提供者的配置混在一份 JSON 里。用户想把运行配置提交进仓库时,JSON 不便手改、合并冲突难读;插件的配置也看不出依赖哪个插件、哪个版本。 +- 同名插件可能来自不同作者。配置只记插件 ID 时,换了来源的插件会悄悄接手旧配置。 +- 以后表单上一定会多出按钮和参数框。如果字段写死在宿主里,每加一个字段都要同时改 Core、macOS 和 Windows。 + +## 决策 + +### 四种内置运行属于 Core + +`process.shell`、`process.powershell`、`process.batch`、`process.executable` 的运行类型列表(`runConfig.configurationTypes`)、表单(`runConfig.editorForm`)、保存校验(`runConfig.saveConfiguration`)和启动计划(`runConfig.createLaunchPlan`)都在 Core 的 `execution/src/configuration/process.rs` 与 `form.rs`。默认解释器由 Core 决定:Shell 取脚本首行的 `#!`,没有时用 `/bin/sh`;PowerShell 用 `pwsh`(Windows 上 `powershell`)并默认带 `-ExecutionPolicy Bypass`,用户可以取消。 + +Core 只在 Windows 上列出 `process.batch`。其他平台上读到已有的 batch 条目时丢弃,并给出 `unsupportedPlatform` 诊断,界面上不出现 cmd。 + +宿主(`desktop/internal/workbench/runconfig_process.go`)拿到启动计划后只做三件事:在 PATH 里找可执行文件,把“脚本文本”写到系统临时目录里的 `lithe-run-script-*` 目录、进程退出后删除,然后用 `buildprocess` 起进程,输出进 Run 窗口。宿主不判断脚本类型,也不拼解释器参数。 + +只内置平台本身就有的东西。Python、Node、Make 这类需要识别生态或工具链的运行,交给插件声明(见[运行配置的生成层只来自插件声明](2026-10-29-run-configuration-detection-in-memory.md))。 + +### 内置运行不依赖插件和构建模型 + +列出、新建、编辑和启动内置运行时,不需要构建模型或生成层,也不需要插件宿主。还没加载构建模型的项目,`resolve` 照样返回内置运行;插件宿主不可用时,标题栏和构建窗口仍然列出并运行它们。插件配置文件写坏时,只把那一份文件标为“未读取”(诊断带 `path`,标题栏下拉列出该文件,点一下在编辑器中打开),其余配置照常读取。 + +### 两种文件格式各管一层 + +| 文件 | 谁写 | 内容 | +| --- | --- | --- | +| `.lithe/run/configurations.yaml` | 用户勾选“存为项目文件” | 团队共享的内置配置 | +| `.lithe/run/local.yaml` | 默认 | 本机的内置配置、选项和工具偏好 | +| `.lithe/run/plugin/<插件 ID>.toml` | 插件运行存为项目文件 | 团队共享的插件配置 | +| `.lithe/run/plugin/<插件 ID>.local.toml` | 插件运行默认 | 本机的插件配置 | + +插件 TOML 的 `[plugin]` 头记录 `id`、`name`、`author`、`repository`、`version`、`versionRequirement`(默认“`>=` 保存时的版本”)、`pluginAPIVersion` 和 `capabilities`。作者和仓库取自插件清单新增的可选字段 `repository`(`https://github.com/<作者>/<仓库>`)。插件没装、仓库不一致或版本不满足时,这些配置标为不可用并说明原因,不删除也不改写。 + +旧 JSON 只在对应的 YAML 不存在时读取。第一次编辑某一层时,Core 返回“写 YAML、删 JSON”两项改动。 + +### Core 计算改动,宿主应用改动 + +所有编辑命令都返回 `changes: [{path, baseSha256, content}]`,Core 自己不写文件。宿主的 `applyRunConfigChanges`(`desktop/internal/workbench/runconfig_changes.go`)只接受 `.lithe/` 下的路径。它先确认每个文件仍是 Core 计算时的字节,有一个不符就整体放弃并报冲突;写入先于删除,所以新 YAML 落盘后才删旧 JSON。中途失败时,它只还原自己改过、并且之后没被别人改动的文件。 + +### 表单字段由 Core 描述,宿主按类型画 + +`runConfig.editorForm` 返回字段列表(类型、是否必填、位置、自动值、可选项、`visibleWhen` 条件、说明)和当前值,`formVersion` 为 1。宿主(`runconfig_form.go`、`runconfig_form_view.go`)只画同时满足两个条件的字段:类型是它认识的,`shared/i18n` 里有这个字段 ID 的标题。其余字段跳过不画,值原样回传。Core 返回的 `formVersion` 比宿主新时,宿主不打开表单,提示升级。 + +### 从界面按下运行时打开 Run 窗口 + +从编辑对话框的“运行”、构建窗口的配置列表(按钮或双击)和 Run 窗口的再次运行启动时,都走 `runConfiguration`(`runconfig.go`)。它启动后打开 Run 窗口,并选中这次运行的控制台;构建插件提供的运行从列表启动时也一样。经 IDE API(`startRunConfiguration`)启动的运行不改变窗口布局,因为调用方不一定是用户。 + +### 正确做法 + +- 给 Shell 表单加一个参数框:在 Core 的 `form.rs` 描述字段、在 `process.rs` 解释它的值,再在 `shared/i18n/` 加标题词条。宿主已认识这种类型时,不用改任何宿主代码。 +- 新增一种全新的字段类型:先在宿主实现它的绘制,再让 Core 开始返回它;旧宿主跳过新字段,配置照样能保存。 +- 插件运行需要新的元数据:加进插件 TOML 的 `[plugin]` 头,由 Core 读写,宿主不解析 TOML。 + +### 不要这样做 + +- 不要在宿主里按扩展名判断脚本类型、补 `-ExecutionPolicy` 或拼 `cmd /c`。这些规则只在 Core,宿主重复一份就会和 Windows 端分叉。 +- 不要在宿主或 Core 里直接写 `.lithe/run/` 下的文件,绕过 `changes` 和哈希检查会覆盖别人刚做的修改。 +- 不要让内置运行等构建模型加载完、或等插件宿主就绪再出现,那正是这次要去掉的依赖。 +- 不要把脚本文本写进项目目录或 app bundle。它是一次性的运行产物,只放系统临时目录。 + +## 考虑过的备选方案 + +### 把脚本和程序运行做成一个官方插件 + +和其他运行走同一条路,Core 不多一类提供者。没有采用:用户要求插件全坏时这几种运行也能用,放进插件就又依赖插件宿主、插件安装和插件版本。 + +### 全部配置都用 YAML,或都用 TOML + +一种格式更简单。没有采用:内置配置只有通用字段,YAML 适合手写和代码评审;插件配置要带一个“依赖哪个插件、哪个版本”的头,TOML 的 `[plugin]` 表把元数据和配置分得清楚。按插件拆文件后,卸载插件或插件出错只影响一份文件。 + +### 插件配置只记插件 ID + +字段少,也不用改插件清单。没有采用:插件 ID 防不了不同作者用同一个名字。作者和仓库让 Core 能发现“已安装的插件不是保存配置时那一个”,并把配置标为不可用,而不是交给另一个插件运行。 + +### 表单字段写死在宿主 + +宿主可以完全控制布局。没有采用:每加一个字段都要同时改 Core 和两个桌面端,还要在宿主里重复 Core 的校验规则;以后 Windows 端还得再写一遍。 + +### 迁移时立即把所有旧 JSON 转成 YAML + +一次转完,代码里不用再读 JSON。没有采用:打开项目就改写用户文件,会在版本控制里产生用户没做过的改动。现在只在用户真正编辑某一层时才转换。代价是旧客户端读不到被转换的那一层。 + +## 后果 + +- 收益:不装插件也能运行脚本和程序;运行配置可以按团队和本机分开提交;插件配置能说明自己依赖哪个插件;以后加字段时,通常只需改 Core 和词条。 +- 代价:多了一种文件格式和一套插件元数据要维护;脚本文本运行要在临时目录写文件,进程崩溃时留下的目录由系统清理;旧 macOS 客户端读不到 Viva 已转换的那一层配置。 +- Windows 上裸写的 `bash` 可能解析到 WSL 的启动器,需要 Git Bash 时要在解释器路径里填完整路径。批处理的 `commandLine` 只按 cmd 的规则加引号,不转义 `%`。 +- 需要重新评估:Windows 或 Linux 实机验收发现的解释器或引号问题;插件需要在 TOML 里放自定义字段时;`formVersion` 需要升到 2 时。 + +## 验证 + +- `scripts/desktop/desktop-go.sh test ./internal/core/... ./internal/buildprocess/... ./internal/workbench/...`:`runconfig_process_test.go` 用系统 shell 真实运行脚本,并断言 Run 窗口打开、输出进入控制台;`runconfig_browser_test.go`、`title_run_test.go`、`runconfig_edit_test.go` 覆盖列表、标题栏和保存。 +- `scripts/desktop/desktop-go.sh test -tags 'vivahead lithevisual' ./internal/workbench -run '^TestVisualBuiltInProcessRuns$'`:设置 `LITHE_VISUAL_OUTPUT_DIR` 后生成 `docs/assets/builtin-process-runs/` 的截图。 +- Core 仓库的 `cargo test -p lithe-execution -p lithe-core`:覆盖表单、校验、启动计划、YAML/TOML 读写、旧 JSON 和插件可用性。 +- `./scripts/desktop/verify/verify-runtime-bundle-immutability.sh`:确认运行不写发行目录。 + +## 适用范围 + +- `desktop/internal/workbench/runconfig_process.go` +- `desktop/internal/workbench/runconfig_changes.go` +- `desktop/internal/workbench/runconfig_form.go` +- `desktop/internal/workbench/runconfig_form_view.go` +- `desktop/internal/workbench/runconfig.go` +- `desktop/internal/core/run_process.go` +- `desktop/internal/buildprocess/` +- Core 仓库的内置运行与文件格式:[process.rs](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/execution/src/configuration/process.rs)、[storage.rs](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/execution/src/configuration/storage.rs)、[plugin_document.rs](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/execution/src/configuration/plugin_document.rs) diff --git a/desktop/internal/buildprocess/batch_windows_test.go b/desktop/internal/buildprocess/batch_windows_test.go index acac8a2f85..f5a7740bb2 100644 --- a/desktop/internal/buildprocess/batch_windows_test.go +++ b/desktop/internal/buildprocess/batch_windows_test.go @@ -95,3 +95,49 @@ func TestBatchFileUnderASpacedDirectoryReceivesItsArguments(t *testing.T) { t.Fatal("an argument ran a command") } } + +// A command line Core planned reaches the process unchanged, Executable included, instead of +// one quoted from the arguments: cmd.exe runs a batch script the way Core wrote its line. +func TestCommandLineReachesTheProcessUnchanged(t *testing.T) { + directory := filepath.Join(t.TempDir(), "spaced dir") + if err := os.MkdirAll(directory, 0o755); err != nil { + t.Fatal(err) + } + script := filepath.Join(directory, "run me.cmd") + body := "@echo off\r\n\"" + os.Args[0] + "\" \"-test.run=^TestBatchArgumentsHelper$\" -- %*\r\nexit /b %ERRORLEVEL%\r\n" + if err := os.WriteFile(script, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + cmd := filepath.Join(os.Getenv("SystemRoot"), "System32", "cmd.exe") + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + var output strings.Builder + var mu sync.Mutex + process, err := Start(ctx, Spec{ + Executable: cmd, + WorkingDirectory: directory, + Environment: map[string]string{batchArgumentsMode: "1"}, + CommandLine: `cmd /d /s /c ""` + script + `" "a b" c"`, + }, func(_ Stream, text string) { + mu.Lock() + output.WriteString(text) + mu.Unlock() + }) + if err != nil { + t.Fatal(err) + } + waitErr := process.Wait() + mu.Lock() + text := output.String() + mu.Unlock() + if waitErr != nil { + t.Fatalf("script failed: %v\n%s", waitErr, text) + } + var got []string + if err := json.Unmarshal([]byte(strings.TrimSpace(text)), &got); err != nil { + t.Fatalf("output is not the helper's JSON: %v\n%s", err, text) + } + if want := []string{"a b", "c"}; !slices.Equal(got, want) { + t.Fatalf("arguments = %q, want %q", got, want) + } +} diff --git a/desktop/internal/buildprocess/process.go b/desktop/internal/buildprocess/process.go index 284a0c9276..e41a646317 100644 --- a/desktop/internal/buildprocess/process.go +++ b/desktop/internal/buildprocess/process.go @@ -61,6 +61,11 @@ type Spec struct { // adapter) can write frames after the process starts while cancellation // still ends the whole tree. Stdin io.Reader + // CommandLine, when set, is the exact Windows command line the process gets, + // Executable included, instead of one quoted from Arguments. Core plans it for + // a batch script run by cmd.exe, whose quoting rules differ from a program's. + // Start refuses it on other platforms, which have no command line. + CommandLine string } // Process is one running host-owned process. Wait must be called once to @@ -108,7 +113,7 @@ func Start(ctx context.Context, spec Spec, observe func(Stream, string)) (*Proce command.Stdout = stdoutWrite command.Stderr = stderrWrite platform := &processPlatform{} - err = platform.configure(command) + err = platform.configure(command, spec.CommandLine) if err == nil { err = command.Start() } diff --git a/desktop/internal/buildprocess/process_unix.go b/desktop/internal/buildprocess/process_unix.go index 0a95519415..528a32223b 100644 --- a/desktop/internal/buildprocess/process_unix.go +++ b/desktop/internal/buildprocess/process_unix.go @@ -3,6 +3,7 @@ package buildprocess import ( + "errors" "os" "os/exec" "sync" @@ -20,12 +21,19 @@ type processPlatform struct { } // configure puts the process in its own group so Stop can end the whole build -// tree, including wrappers that start child compilers. -func (*processPlatform) configure(command *exec.Cmd) error { +// tree, including wrappers that start child compilers. A process here gets its +// arguments as a vector, so a Windows command line is refused. +func (*processPlatform) configure(command *exec.Cmd, commandLine string) error { + if commandLine != "" { + return errCommandLineUnsupported + } command.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} return nil } +// errCommandLineUnsupported refuses a Spec.CommandLine outside Windows. +var errCommandLineUnsupported = errors.New("buildprocess: a command line is passed only on Windows") + func (p *processPlatform) adopt(process *os.Process) error { if process == nil { return nil diff --git a/desktop/internal/buildprocess/process_unix_test.go b/desktop/internal/buildprocess/process_unix_test.go index b96fc2c48d..16daf913ee 100644 --- a/desktop/internal/buildprocess/process_unix_test.go +++ b/desktop/internal/buildprocess/process_unix_test.go @@ -4,6 +4,7 @@ package buildprocess import ( "context" + "errors" "strings" "sync" "testing" @@ -110,3 +111,19 @@ func TestProcessKillEndsATreeInItsGrace(t *testing.T) { t.Fatal("the killed program reported success") } } + +// A Windows command line is refused here, where a process gets its arguments as a vector, so +// a batch plan never starts with arguments it did not mean. +func TestStartRefusesACommandLineOutsideWindows(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + process, err := Start(ctx, Spec{Executable: "/bin/sh", CommandLine: `cmd /d /s /c "x.cmd"`}, func(Stream, string) {}) + if err == nil { + process.Kill() + _ = process.Wait() + t.Fatal("Start ran a command line outside Windows") + } + if !errors.Is(err, errCommandLineUnsupported) { + t.Fatalf("err = %v, want errCommandLineUnsupported", err) + } +} diff --git a/desktop/internal/buildprocess/process_windows.go b/desktop/internal/buildprocess/process_windows.go index c11c71d056..4a0d94d4f5 100644 --- a/desktop/internal/buildprocess/process_windows.go +++ b/desktop/internal/buildprocess/process_windows.go @@ -30,10 +30,16 @@ type processPlatform struct { active bool } -func (p *processPlatform) configure(command *exec.Cmd) error { +// configure creates the process suspended in a group of its own. commandLine, when set, is +// passed as the process's whole command line unchanged (Spec.CommandLine). +func (p *processPlatform) configure(command *exec.Cmd, commandLine string) error { command.SysProcAttr = &syscall.SysProcAttr{ CreationFlags: windows.CREATE_NO_WINDOW | windows.CREATE_SUSPENDED | windows.CREATE_NEW_PROCESS_GROUP, } + if commandLine != "" { + command.SysProcAttr.CmdLine = commandLine + return nil + } // A program that was not found keeps its lookup error for Start to report. if command.Err != nil || !isBatchFile(command.Path) { return nil diff --git a/desktop/internal/core/run_config.go b/desktop/internal/core/run_config.go index 2f55220907..79cb3898b5 100644 --- a/desktop/internal/core/run_config.go +++ b/desktop/internal/core/run_config.go @@ -3,6 +3,7 @@ package core import ( "context" "encoding/json" + "strings" ) // RunProviderReference selects one build provider run: the plugin's build system @@ -42,6 +43,74 @@ type RunConfiguration struct { Disabled bool `json:"disabled"` Source string `json:"source,omitempty"` Extensions map[string]json.RawMessage `json:"extensions,omitempty"` + // Plugin is the plugin the configuration needs, as its document records it. + Plugin *RunPluginDependency `json:"plugin,omitempty"` + // Availability is set when the saved configuration cannot run, such as when + // the plugin it needs is not installed. The host shows it and never starts it. + Availability *RunAvailability `json:"availability,omitempty"` +} + +// RunPluginDependency is the plugin a configuration needs: its ID, and what the +// configuration's plugin document recorded when it was saved. A build run outside +// a plugin document carries only the ID. +type RunPluginDependency struct { + ID string `json:"id"` + Name string `json:"name,omitempty"` + Author string `json:"author,omitempty"` + Repository string `json:"repository,omitempty"` + Version string `json:"version,omitempty"` + VersionRequirement string `json:"versionRequirement,omitempty"` +} + +// RunAvailability says why a saved configuration cannot run. Code is +// pluginMissing, pluginRepositoryMismatch, pluginVersionUnsupported, +// invalidConfiguration or missingWorkingDirectory; Message is Core's English +// description, which the host shows only as the detail of its own text. +type RunAvailability struct { + Status string `json:"status"` + Code string `json:"code"` + Message string `json:"message"` +} + +// ProcessProviderPrefix starts the providers of the built-in process runs Core +// plans without any plugin: shell, PowerShell and batch scripts, and programs. +const ProcessProviderPrefix = "process." + +// IsProcess says the configuration is a built-in process run the host starts itself. +func (r RunConfiguration) IsProcess() bool { + return strings.HasPrefix(r.Provider, ProcessProviderPrefix) +} + +// Unavailable says resolution found that the configuration cannot run. +func (r RunConfiguration) Unavailable() bool { + return r.Availability != nil && r.Availability.Status == "unavailable" +} + +// UserDefined says the user created the configuration, so it can be deleted. +func (r RunConfiguration) UserDefined() bool { + return strings.HasPrefix(r.ID, "user:") +} + +// RunInstalledPlugin is one installed, enabled plugin as `runConfig.resolve` +// and the edit commands check it: the fields of its plugin.json. +type RunInstalledPlugin struct { + ID string `json:"id"` + DisplayName string `json:"displayName,omitempty"` + Version string `json:"version"` + Repository string `json:"repository,omitempty"` + PluginAPIVersion *int `json:"pluginAPIVersion,omitempty"` + Requires json.RawMessage `json:"requires,omitempty"` +} + +// RunConfigChange is one file an edit command changes. Path is workspace-relative +// with '/', BaseSHA256 the lowercase hex SHA-256 of the bytes Core read (nil when +// the file did not exist) and Content the new text (nil deletes the file). Core +// writes nothing: the host applies the changes of one reply as one transaction, +// and only while every file still has its base bytes. +type RunConfigChange struct { + Path string `json:"path"` + BaseSHA256 *string `json:"baseSha256"` + Content *string `json:"content"` } // BuildReference is the configuration's build provider selector, when it has one. @@ -62,26 +131,33 @@ func (r RunConfiguration) BuildReference() (RunProviderReference, bool) { type RunConfigResolution struct { Configurations []RunConfiguration `json:"configurations"` Diagnostics []struct { - ID string `json:"id,omitempty"` - Code string `json:"code"` + ID string `json:"id,omitempty"` + Code string `json:"code"` + // Path is the workspace-relative file a diagnostic about a whole saved document + // names, such as a plugin's TOML document that cannot be read; Core left the + // configurations it holds out. + Path string `json:"path,omitempty"` Message string `json:"message"` } `json:"diagnostics"` DefaultRunConfiguration *string `json:"defaultRunConfiguration"` } // ResolveRunConfigurations merges the workspace's run configuration layers -// (local over team over detected) without writing anything. -func (c *Client) ResolveRunConfigurations(ctx context.Context, root string) (RunConfigResolution, error) { +// (local over team over detected) without writing anything. plugins lists the +// enabled plugins, so a configuration whose plugin is missing comes back +// unavailable; nil skips that check. +func (c *Client) ResolveRunConfigurations(ctx context.Context, root string, plugins []RunInstalledPlugin) (RunConfigResolution, error) { var result RunConfigResolution err := c.Execute(ctx, "runConfig.resolve", struct { - Root string `json:"root"` - }{root}, &result) + Root string `json:"root"` + Plugins []RunInstalledPlugin `json:"plugins,omitempty"` + }{root, plugins}, &result) return result, err } // TitleConfiguration describes the configuration the title bar shows, as far as starting it -// depends on. Kind is "unsupported", "instanceMissing", "modelNotLoaded" (with Failed) or -// "modelLoaded" (with Debuggable). +// depends on. Kind is "unsupported", "process", "unavailable", "instanceMissing", +// "modelNotLoaded" (with Failed) or "modelLoaded" (with Debuggable). type TitleConfiguration struct { Kind string `json:"kind"` Failed *bool `json:"failed,omitempty"` @@ -102,8 +178,8 @@ type TitleActionFacts struct { } // DecideTitleAction asks Core what a title bar press does. The answer is "currentFile", -// "wait", "loadModel", "unsupported", "targetMissing", "modelFailed", "run", "debug" or -// "notDebuggable". +// "wait", "loadModel", "unsupported", "unavailable", "targetMissing", "modelFailed", "run", +// "debug" or "notDebuggable". func (c *Client) DecideTitleAction(ctx context.Context, facts TitleActionFacts) (string, error) { var decision struct { Kind string `json:"kind"` @@ -179,8 +255,7 @@ func (c *Client) ProviderLaunchInputs(ctx context.Context, root, configurationID // RunOptionsEdit is a `runConfig.updateOptions` request: the user's arguments // (editor text Core splits), working directory and environment for one -// configuration in the local or project layer. LocalDocument, when set, is the -// captured local layer Core edits and resolves against instead of reading it. +// configuration in the local or project layer. type RunOptionsEdit struct { Root string `json:"root"` Scope string `json:"scope"` @@ -188,9 +263,11 @@ type RunOptionsEdit struct { WorkingDirectory string `json:"workingDirectory"` Arguments string `json:"arguments"` Environment map[string]string `json:"environment"` - LocalDocument json.RawMessage `json:"localDocument,omitempty"` // ProviderRunOptions replaces the build provider choices of the selected layer when set. ProviderRunOptions json.RawMessage `json:"providerRunOptions,omitempty"` + // Plugins is the enabled plugin list of ResolveRunConfigurations, so a plugin + // document Core writes records the installed plugin. + Plugins []RunInstalledPlugin `json:"plugins,omitempty"` } // ProviderRunOptionsSnapshot is the typed choices of a build provider configuration @@ -204,14 +281,14 @@ type ProviderRunOptionsSnapshot struct { Tools map[string]map[string]string `json:"tools"` } -// UpdateRunConfigurationOptions returns the layer document with the edit applied. -// Core writes nothing; the host publishes the document to the scope's file. -func (c *Client) UpdateRunConfigurationOptions(ctx context.Context, edit RunOptionsEdit) (string, error) { +// UpdateRunConfigurationOptions returns the file changes that apply the edit. +// Core writes nothing; the host applies them as one transaction. +func (c *Client) UpdateRunConfigurationOptions(ctx context.Context, edit RunOptionsEdit) ([]RunConfigChange, error) { var result struct { - Document string `json:"document"` + Changes []RunConfigChange `json:"changes"` } err := c.Execute(ctx, "runConfig.updateOptions", edit, &result) - return result.Document, err + return result.Changes, err } // RunArgumentText formats each argument vector as the editor text that diff --git a/desktop/internal/core/run_config_test.go b/desktop/internal/core/run_config_test.go index 4a81edff68..253d2f5057 100644 --- a/desktop/internal/core/run_config_test.go +++ b/desktop/internal/core/run_config_test.go @@ -5,6 +5,8 @@ import ( "encoding/json" "os" "path/filepath" + "slices" + "strings" "testing" "time" @@ -30,7 +32,7 @@ func TestProviderRunsResolveAndLaunchInputs(t *testing.T) { if _, err := client.GenerateRunConfigurations(ctx, root, runs); err != nil { t.Fatal(err) } - resolved, err := client.ResolveRunConfigurations(ctx, root) + resolved, err := client.ResolveRunConfigurations(ctx, root, nil) if err != nil { t.Fatal(err) } @@ -73,23 +75,21 @@ func TestRunConfigurationOptionsRoundTrip(t *testing.T) { if _, err := client.GenerateRunConfigurations(ctx, root, runs); err != nil { t.Fatal(err) } - resolved, err := client.ResolveRunConfigurations(ctx, root) + resolved, err := client.ResolveRunConfigurations(ctx, root, nil) if err != nil || len(resolved.Configurations) != 1 { t.Fatalf("resolve = %+v, %v", resolved, err) } id := resolved.Configurations[0].ID - document, err := client.UpdateRunConfigurationOptions(ctx, RunOptionsEdit{Root: root, Scope: "local", ConfigurationID: id, + changes, err := client.UpdateRunConfigurationOptions(ctx, RunOptionsEdit{Root: root, Scope: "local", ConfigurationID: id, WorkingDirectory: "app/data", Arguments: `--name "Alice Smith"`, Environment: map[string]string{"MODE": "dev"}}) if err != nil { t.Fatal(err) } - if err := os.MkdirAll(filepath.Join(root, ".lithe", "run"), 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(root, ".lithe", "run", "local.json"), []byte(document), 0o600); err != nil { - t.Fatal(err) + if len(changes) != 1 || changes[0].Path != ".lithe/run/plugin/dev.example.engine.local.toml" || changes[0].BaseSHA256 != nil { + t.Fatalf("changes = %+v", changes) } - resolved, err = client.ResolveRunConfigurations(ctx, root) + writeRunConfigChanges(t, root, changes) + resolved, err = client.ResolveRunConfigurations(ctx, root, nil) if err != nil || len(resolved.Configurations) != 1 { t.Fatalf("resolve = %+v, %v", resolved, err) } @@ -135,3 +135,80 @@ func TestTitleActionsFollowTheContractFixture(t *testing.T) { } } } + +// writeRunConfigChanges applies the file changes of an edit command as the host would, without +// its base checks: a test owns the workspace. +func writeRunConfigChanges(t *testing.T, root string, changes []RunConfigChange) { + t.Helper() + for _, change := range changes { + path := filepath.Join(root, filepath.FromSlash(change.Path)) + if change.Content == nil { + if err := os.Remove(path); err != nil { + t.Fatal(err) + } + continue + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(*change.Content), 0o600); err != nil { + t.Fatal(err) + } + } +} + +// A shell script saved as text goes through the built-in process API: the kinds list it, the +// editor describes its fields, saving refuses a missing value and then writes the project +// layer, the configuration resolves without any plugin, its plan carries the script for the +// host to write, and deleting removes it again. +func TestBuiltInProcessRunRoundTrip(t *testing.T) { + client := NewClient() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + root := t.TempDir() + kinds, err := client.RunConfigurationTypes(ctx) + if err != nil || len(kinds) == 0 || kinds[0].Provider != "process.shell" { + t.Fatalf("kinds = %+v, %v", kinds, err) + } + form, err := client.RunEditorForm(ctx, RunEditorFormRequest{Root: root, Provider: "process.shell"}) + if err != nil || form.FormVersion != RunFormVersion || form.ConfigurationID != nil || len(form.Fields) == 0 || form.Fields[0].ID != "name" { + t.Fatalf("form = %+v, %v", form, err) + } + values := form.Values + values["source"] = json.RawMessage(`"text"`) + values["name"] = json.RawMessage(`"Greet"`) + values["storeAsProjectFile"] = json.RawMessage(`true`) + invalid, err := client.SaveRunConfiguration(ctx, RunConfigurationSave{Root: root, Provider: "process.shell", Values: values}) + if err != nil || invalid.Status != "invalid" || len(invalid.Errors) != 1 || invalid.Errors[0] != (RunFieldError{Field: "text", Code: "required"}) { + t.Fatalf("save without text = %+v, %v", invalid, err) + } + values["text"] = json.RawMessage(`"echo hello"`) + saved, err := client.SaveRunConfiguration(ctx, RunConfigurationSave{Root: root, Provider: "process.shell", Values: values}) + if err != nil || saved.Status != "saved" || !strings.HasPrefix(saved.ID, "user:") || len(saved.Changes) != 1 || saved.Changes[0].Path != ".lithe/run/configurations.yaml" { + t.Fatalf("save = %+v, %v", saved, err) + } + writeRunConfigChanges(t, root, saved.Changes) + resolved, err := client.ResolveRunConfigurations(ctx, root, nil) + if err != nil || len(resolved.Configurations) != 1 { + t.Fatalf("resolve = %+v, %v", resolved, err) + } + if got := resolved.Configurations[0]; got.ID != saved.ID || got.Name != "Greet" || !got.IsProcess() || got.Unavailable() || !got.UserDefined() { + t.Fatalf("configuration = %+v", got) + } + base := filepath.Join(t.TempDir(), "script") + plan, err := client.CreateRunLaunchPlan(ctx, root, saved.ID, base) + if err != nil || plan.InlineScript == nil || plan.InlineScript.Content != "echo hello\n" || !strings.HasPrefix(plan.InlineScript.Path, base) || plan.WorkingDirectory != "." { + t.Fatalf("plan = %+v, %v", plan, err) + } + if plan.Executable.Command == "" && plan.Executable.Path == "" || !slices.Contains(plan.Arguments, plan.InlineScript.Path) { + t.Fatalf("plan does not run the script with the shell: %+v", plan) + } + removed, err := client.DeleteRunConfiguration(ctx, root, saved.ID, nil) + if err != nil || len(removed) != 1 || removed[0].Path != ".lithe/run/configurations.yaml" || removed[0].BaseSHA256 == nil { + t.Fatalf("delete = %+v, %v", removed, err) + } + writeRunConfigChanges(t, root, removed) + if resolved, err := client.ResolveRunConfigurations(ctx, root, nil); err != nil || len(resolved.Configurations) != 0 { + t.Fatalf("resolve after delete = %+v, %v", resolved, err) + } +} diff --git a/desktop/internal/core/run_process.go b/desktop/internal/core/run_process.go new file mode 100644 index 0000000000..7b34bbeb7e --- /dev/null +++ b/desktop/internal/core/run_process.go @@ -0,0 +1,168 @@ +package core + +import ( + "context" + "encoding/json" +) + +// RunFormVersion is the `runConfig.editorForm` version this host draws. A newer +// form is refused, since its fields may mean something this host cannot show. +const RunFormVersion = 1 + +// RunConfigurationType is one built-in run configuration kind a user can create +// on this platform, such as `process.shell`. +type RunConfigurationType struct { + Provider string `json:"provider"` +} + +// RunConfigurationTypes lists the built-in kinds a user can create here, in +// display order. Batch scripts are listed only on Windows. +func (c *Client) RunConfigurationTypes(ctx context.Context) ([]RunConfigurationType, error) { + var result struct { + Types []RunConfigurationType `json:"types"` + } + err := c.Execute(ctx, "runConfig.configurationTypes", struct{}{}, &result) + return result.Types, err +} + +// RunEditorField is one field of a run configuration editor. Kind is text, +// checkbox, choice, file, multilineText, arguments, directory, environment or +// executable; a host skips a kind it does not know and still sends its value +// back. Automatic is the value used while the field is empty, shown as its +// placeholder. Note is an explanation key, such as windowsOnly. +type RunEditorField struct { + ID string `json:"id"` + Kind string `json:"kind"` + Required bool `json:"required,omitempty"` + Placement string `json:"placement,omitempty"` + Automatic *string `json:"automatic,omitempty"` + Options []string `json:"options,omitempty"` + VisibleWhen *RunFieldCondition `json:"visibleWhen,omitempty"` + Note string `json:"note,omitempty"` +} + +// RunFieldCondition shows a field only while Field has the value Equals. +type RunFieldCondition struct { + Field string `json:"field"` + Equals any `json:"equals"` +} + +// RunEditorForm is what `runConfig.editorForm` returns: the fields in order and +// the current value of each, by field ID. Values stay raw so keys this host +// does not show go back unchanged. +type RunEditorForm struct { + FormVersion int `json:"formVersion"` + Provider string `json:"provider"` + ConfigurationID *string `json:"configurationId"` + Values map[string]json.RawMessage `json:"values"` + Fields []RunEditorField `json:"fields"` +} + +// RunEditorFormRequest asks for the editor of a new configuration of Provider or +// of the saved ConfigurationID. Values are the open editor's unsaved values, so +// the automatic values follow the edit. +type RunEditorFormRequest struct { + Root string `json:"root"` + Provider string `json:"provider,omitempty"` + ConfigurationID string `json:"configurationId,omitempty"` + Values map[string]json.RawMessage `json:"values,omitempty"` +} + +// RunEditorForm describes the editor fields and current values of a built-in run configuration. +func (c *Client) RunEditorForm(ctx context.Context, request RunEditorFormRequest) (RunEditorForm, error) { + var result RunEditorForm + err := c.Execute(ctx, "runConfig.editorForm", request, &result) + return result, err +} + +// RunFieldError is one wrong editor value: the field and a code such as +// required, notFound or outsideProject, which the host words beside the field. +type RunFieldError struct { + Field string `json:"field"` + Code string `json:"code"` +} + +// RunConfigurationSave is a `runConfig.saveConfiguration` request. +type RunConfigurationSave struct { + Root string `json:"root"` + Provider string `json:"provider"` + ConfigurationID string `json:"configurationId,omitempty"` + Values map[string]json.RawMessage `json:"values"` + Plugins []RunInstalledPlugin `json:"plugins,omitempty"` +} + +// RunConfigurationSaved is the answer of `runConfig.saveConfiguration`: Status +// "invalid" with Errors, or "saved" with the configuration's ID and the file +// changes that save it. +type RunConfigurationSaved struct { + Status string `json:"status"` + Errors []RunFieldError `json:"errors"` + ID string `json:"id"` + Changes []RunConfigChange `json:"changes"` +} + +// SaveRunConfiguration validates an editor form's values and returns field errors or the +// file changes that save it. Core writes nothing. +func (c *Client) SaveRunConfiguration(ctx context.Context, request RunConfigurationSave) (RunConfigurationSaved, error) { + var result RunConfigurationSaved + err := c.Execute(ctx, "runConfig.saveConfiguration", request, &result) + return result, err +} + +// DeleteRunConfiguration returns the file changes that remove a saved `user:` +// configuration from every layer. +func (c *Client) DeleteRunConfiguration(ctx context.Context, root, configurationID string, plugins []RunInstalledPlugin) ([]RunConfigChange, error) { + var result struct { + Changes []RunConfigChange `json:"changes"` + } + err := c.Execute(ctx, "runConfig.deleteConfiguration", struct { + Root string `json:"root"` + ConfigurationID string `json:"configurationId"` + Plugins []RunInstalledPlugin `json:"plugins,omitempty"` + }{root, configurationID, plugins}, &result) + return result.Changes, err +} + +// RunPlanExecutable is the program a launch plan starts: Command, a name looked +// up on the PATH of the launch environment; Path, a native absolute path; or +// Toolchain, a runtime the host resolves from its toolchain registry. +type RunPlanExecutable struct { + Command string `json:"command,omitempty"` + Path string `json:"path,omitempty"` + Toolchain string `json:"toolchain,omitempty"` +} + +// RunInlineScript is a script saved as text: the host writes Content to Path +// before starting and removes the file once the process exits. +type RunInlineScript struct { + Path string `json:"path"` + Content string `json:"content"` +} + +// RunLaunchPlan is the platform-neutral process `runConfig.createLaunchPlan` +// plans. WorkingDirectory is project-relative with '/'. Environment holds +// toolchain-derived values and Env the configuration's own variables. +// CommandLine, set for batch scripts, is the exact Windows command line the +// host passes unchanged instead of quoting Arguments itself. +type RunLaunchPlan struct { + Executable RunPlanExecutable `json:"executable"` + Arguments []string `json:"arguments"` + WorkingDirectory string `json:"workingDirectory"` + Environment map[string]string `json:"environment"` + Env map[string]string `json:"env"` + InlineScript *RunInlineScript `json:"inlineScript,omitempty"` + CommandLine string `json:"commandLine,omitempty"` +} + +// CreateRunLaunchPlan plans one effective configuration for this platform. +// inlineScriptBase is an absolute path prefix in a host-owned temporary +// directory for a script saved as text; Core appends the script's suffix. +func (c *Client) CreateRunLaunchPlan(ctx context.Context, root, configurationID, inlineScriptBase string) (RunLaunchPlan, error) { + var result RunLaunchPlan + err := c.Execute(ctx, "runConfig.createLaunchPlan", struct { + Root string `json:"root"` + ConfigurationID string `json:"configurationId"` + InlineScriptBase string `json:"inlineScriptBase,omitempty"` + }{root, configurationID, inlineScriptBase}, &result) + return result, err +} diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index 1a56c0a683..446dbb1666 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -1326,29 +1326,85 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.run.statusRunning": "Running", "desktop.run.statusStopped": "Stopped", "desktop.run.statusSucceeded": "Succeeded", + "desktop.runConfig.apply": "Apply", "desktop.runConfig.arguments": "Program arguments", "desktop.runConfig.argumentsPlaceholder": "Separate with spaces; quote values that contain spaces", + "desktop.runConfig.automaticValue": "Automatic ({value})", + "desktop.runConfig.browse": "Browse…", + "desktop.runConfig.builtInGroup": "Scripts and Programs", + "desktop.runConfig.chooseFailed": "Could not open the file chooser.", "desktop.runConfig.conflict": "The file changed on disk while saving. Close the editor, reopen it and try again.", + "desktop.runConfig.delete": "Delete", + "desktop.runConfig.deleteBody": "Delete “{name}”? It is removed from the run configuration file it is saved in.", + "desktop.runConfig.deleteFailed": "Could not delete the run configuration: {reason}", + "desktop.runConfig.deleteTitle": "Delete Run Configuration", + "desktop.runConfig.documentIgnored": "Not read: {file}", "desktop.runConfig.editTitle": "Edit {name}", + "desktop.runConfig.emptyHint": "No run configurations yet. Click + to add a script or program run.", "desktop.runConfig.entrypoint": "Entrypoint", "desktop.runConfig.entrypointPlaceholder": "Provider default", "desktop.runConfig.environment": "Environment variables", "desktop.runConfig.environmentInvalid": "Line {line} is not KEY=VALUE.", "desktop.runConfig.environmentPlaceholder": "One KEY=VALUE per line", + "desktop.runConfig.errorConflict": "Choose either a script file or script text", + "desktop.runConfig.errorDuplicate": "Duplicate variable name", + "desktop.runConfig.errorInvalidCharacter": "Contains a character that is not allowed", + "desktop.runConfig.errorInvalidName": "Invalid variable name", + "desktop.runConfig.errorInvalidPath": "Invalid path", + "desktop.runConfig.errorNotAllowed": "Not allowed for this kind of configuration", + "desktop.runConfig.errorNotFound": "File or folder not found", + "desktop.runConfig.errorOther": "Invalid value ({code})", + "desktop.runConfig.errorOutsideProject": "The working directory must be inside the project", + "desktop.runConfig.errorRequired": "Required", + "desktop.runConfig.errorTooLong": "Too long", + "desktop.runConfig.fieldExecutionPolicyBypass": "Bypass execution policy (-ExecutionPolicy Bypass)", + "desktop.runConfig.fieldInterpreter": "Interpreter path", + "desktop.runConfig.fieldInterpreterArguments": "Interpreter options", + "desktop.runConfig.fieldName": "Name", + "desktop.runConfig.fieldProgram": "Program path", + "desktop.runConfig.fieldScript": "Script path", + "desktop.runConfig.fieldScriptOptions": "Script options", + "desktop.runConfig.fieldSource": "Execute", + "desktop.runConfig.fieldStoreAsProjectFile": "Store as project file", + "desktop.runConfig.fieldText": "Script text", + "desktop.runConfig.formTooNew": "Editing this run configuration needs a newer version of Lithe.", + "desktop.runConfig.interpreterHelp": "Left empty, the automatic interpreter shown in brackets is used. You can also enter a command name, found on PATH, or the path of an executable.", "desktop.runConfig.loadFailed": "Run configurations are unavailable: {reason}", + "desktop.runConfig.newConfiguration": "New Configuration", + "desktop.runConfig.newTitle": "New {type} Configuration", + "desktop.runConfig.noteWindowsOnly": "Takes effect on Windows only; other systems ignore it.", + "desktop.runConfig.ok": "OK", "desktop.runConfig.optionDefault": "Default", "desktop.runConfig.optionReadOnly": "Not editable here", + "desktop.runConfig.programNotFound": "“{program}” was not found on PATH. Enter the full path of the interpreter or program.", "desktop.runConfig.run": "Run", "desktop.runConfig.runtimeArguments": "Runtime arguments", "desktop.runConfig.runtimeArgumentsPlaceholder": "One argument per line", "desktop.runConfig.saveFailed": "Could not save: {reason}", "desktop.runConfig.scope": "Save to", - "desktop.runConfig.scopeLocal": "This machine (.lithe/run/local.json)", - "desktop.runConfig.scopeProject": "Project, shared (.lithe/run/configurations.json)", + "desktop.runConfig.scopeLocal": "This machine (.lithe/run/local.yaml)", + "desktop.runConfig.scopeProject": "Project, shared (.lithe/run/configurations.yaml)", + "desktop.runConfig.sourceFile": "Script file", + "desktop.runConfig.sourceText": "Script text", + "desktop.runConfig.storeAsProjectFileHelp": "Checked, the configuration is saved in .lithe/run/configurations.yaml and can be committed with the project; unchecked, it stays on this machine in .lithe/run/local.yaml.", "desktop.runConfig.toolPath": "{arg1} {arg2}", "desktop.runConfig.toolPathPlaceholder": "Empty uses automatic selection", "desktop.runConfig.toolPick": "Tool installation", "desktop.runConfig.toolPickNone": "Choose an installation…", + "desktop.runConfig.typeBatch": "Batch Script (cmd)", + "desktop.runConfig.typeExecutable": "Program", + "desktop.runConfig.typePowerShell": "PowerShell Script", + "desktop.runConfig.typeShell": "Shell Script", + "desktop.runConfig.unavailableInvalid": "The run configuration is invalid: {reason}", + "desktop.runConfig.unavailableMissingDirectory": "The working directory “{directory}” no longer exists. Edit the configuration to change it.", + "desktop.runConfig.unavailableOther": "This run configuration cannot run now: {reason}", + "desktop.runConfig.unavailablePluginMissing": "Needs the plugin “{plugin}”, which is not installed or not enabled.", + "desktop.runConfig.unavailableRepositoryMismatch": "The installed “{plugin}” is not the plugin from {repository} the configuration records.", + "desktop.runConfig.unavailableVersionUnsupported": "The installed “{plugin}” does not meet the version requirement {requirement}.", + "desktop.runConfig.variableAdd": "Add variable", + "desktop.runConfig.variableName": "Name", + "desktop.runConfig.variableRemove": "Remove variable", + "desktop.runConfig.variableValue": "Value", "desktop.runConfig.workingDirectory": "Working directory", "desktop.runConfig.workingDirectoryPlaceholder": "Path inside the workspace; empty uses the default", "desktop.search.collapseFile": "Hide details", @@ -4148,29 +4204,85 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.run.statusRunning": "正在运行", "desktop.run.statusStopped": "已停止", "desktop.run.statusSucceeded": "成功", + "desktop.runConfig.apply": "应用", "desktop.runConfig.arguments": "程序参数", "desktop.runConfig.argumentsPlaceholder": "以空格分隔;含空格的值请加引号", + "desktop.runConfig.automaticValue": "自动({value})", + "desktop.runConfig.browse": "选择…", + "desktop.runConfig.builtInGroup": "脚本与程序", + "desktop.runConfig.chooseFailed": "无法打开文件选择器。", "desktop.runConfig.conflict": "保存期间文件已在磁盘上被修改,请关闭编辑器重新打开后再试。", + "desktop.runConfig.delete": "删除", + "desktop.runConfig.deleteBody": "确定删除“{name}”吗?它会从保存它的运行配置文件中移除。", + "desktop.runConfig.deleteFailed": "无法删除运行配置:{reason}", + "desktop.runConfig.deleteTitle": "删除运行配置", + "desktop.runConfig.documentIgnored": "未读取 {file} 中的运行配置", "desktop.runConfig.editTitle": "编辑 {name}", + "desktop.runConfig.emptyHint": "还没有运行配置,点 + 新建脚本或程序运行", "desktop.runConfig.entrypoint": "入口", "desktop.runConfig.entrypointPlaceholder": "提供方默认值", "desktop.runConfig.environment": "环境变量", "desktop.runConfig.environmentInvalid": "第 {line} 行不是 KEY=VALUE 格式。", "desktop.runConfig.environmentPlaceholder": "每行一个 KEY=VALUE", + "desktop.runConfig.errorConflict": "脚本文件和脚本文本只能选一个", + "desktop.runConfig.errorDuplicate": "变量名重复", + "desktop.runConfig.errorInvalidCharacter": "包含不允许的字符", + "desktop.runConfig.errorInvalidName": "变量名无效", + "desktop.runConfig.errorInvalidPath": "路径无效", + "desktop.runConfig.errorNotAllowed": "这种运行配置不能使用此项", + "desktop.runConfig.errorNotFound": "找不到该文件或文件夹", + "desktop.runConfig.errorOther": "值无效({code})", + "desktop.runConfig.errorOutsideProject": "工作目录必须在项目内", + "desktop.runConfig.errorRequired": "必填", + "desktop.runConfig.errorTooLong": "内容太长", + "desktop.runConfig.fieldExecutionPolicyBypass": "绕过执行策略(-ExecutionPolicy Bypass)", + "desktop.runConfig.fieldInterpreter": "解释器路径", + "desktop.runConfig.fieldInterpreterArguments": "解释器选项", + "desktop.runConfig.fieldName": "名称", + "desktop.runConfig.fieldProgram": "程序路径", + "desktop.runConfig.fieldScript": "脚本路径", + "desktop.runConfig.fieldScriptOptions": "脚本选项", + "desktop.runConfig.fieldSource": "执行", + "desktop.runConfig.fieldStoreAsProjectFile": "存为项目文件", + "desktop.runConfig.fieldText": "脚本文本", + "desktop.runConfig.formTooNew": "这个运行配置需要更新版本的 Lithe 才能编辑。", + "desktop.runConfig.interpreterHelp": "留空时使用括号里显示的自动解释器;也可以填命令名(按 PATH 查找)或可执行文件路径。", "desktop.runConfig.loadFailed": "无法读取运行配置:{reason}", + "desktop.runConfig.newConfiguration": "新建运行配置", + "desktop.runConfig.newTitle": "新建{type}运行配置", + "desktop.runConfig.noteWindowsOnly": "只在 Windows 上生效,其他系统会忽略。", + "desktop.runConfig.ok": "确定", "desktop.runConfig.optionDefault": "默认", "desktop.runConfig.optionReadOnly": "此处无法编辑", + "desktop.runConfig.programNotFound": "在 PATH 中找不到“{program}”,请填写解释器或程序的完整路径。", "desktop.runConfig.run": "运行", "desktop.runConfig.runtimeArguments": "运行时参数", "desktop.runConfig.runtimeArgumentsPlaceholder": "每行一个参数", "desktop.runConfig.saveFailed": "保存失败:{reason}", "desktop.runConfig.scope": "保存到", - "desktop.runConfig.scopeLocal": "仅本机(.lithe/run/local.json)", - "desktop.runConfig.scopeProject": "项目共享(.lithe/run/configurations.json)", + "desktop.runConfig.scopeLocal": "仅本机(.lithe/run/local.yaml)", + "desktop.runConfig.scopeProject": "项目共享(.lithe/run/configurations.yaml)", + "desktop.runConfig.sourceFile": "脚本文件", + "desktop.runConfig.sourceText": "脚本文本", + "desktop.runConfig.storeAsProjectFileHelp": "勾选后保存到 .lithe/run/configurations.yaml,可随项目提交共享;不勾选则只保存在本机的 .lithe/run/local.yaml。", "desktop.runConfig.toolPath": "{arg1} {arg2}", "desktop.runConfig.toolPathPlaceholder": "留空则自动选择", "desktop.runConfig.toolPick": "工具安装", "desktop.runConfig.toolPickNone": "选择安装…", + "desktop.runConfig.typeBatch": "批处理脚本(cmd)", + "desktop.runConfig.typeExecutable": "程序", + "desktop.runConfig.typePowerShell": "PowerShell 脚本", + "desktop.runConfig.typeShell": "Shell 脚本", + "desktop.runConfig.unavailableInvalid": "运行配置无效:{reason}", + "desktop.runConfig.unavailableMissingDirectory": "工作目录“{directory}”不存在了,请编辑配置修改它。", + "desktop.runConfig.unavailableOther": "此运行配置现在无法运行:{reason}", + "desktop.runConfig.unavailablePluginMissing": "需要插件“{plugin}”,但它没有安装或没有启用。", + "desktop.runConfig.unavailableRepositoryMismatch": "已安装的“{plugin}”不是配置记录的仓库 {repository} 发布的插件。", + "desktop.runConfig.unavailableVersionUnsupported": "已安装的“{plugin}”版本不满足要求 {requirement}。", + "desktop.runConfig.variableAdd": "添加变量", + "desktop.runConfig.variableName": "变量名", + "desktop.runConfig.variableRemove": "删除变量", + "desktop.runConfig.variableValue": "值", "desktop.runConfig.workingDirectory": "工作目录", "desktop.runConfig.workingDirectoryPlaceholder": "工作区内的路径;留空使用默认目录", "desktop.search.collapseFile": "收起详情", diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index d2f971ae1b..a0a4272a80 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -99,10 +99,17 @@ type Kernel interface { LaunchDebug(ctx context.Context, sessionID, operationID string, configuration core.DebugLaunchConfiguration) (core.DebugUpdate, error) NormalizeSteppingFilters(ctx context.Context, adapterID string, filters core.DebugSteppingFilters) (core.DebugSteppingFilters, error) GenerateRunConfigurations(ctx context.Context, root string, providerRuns json.RawMessage) (core.RunConfigGeneration, error) - ResolveRunConfigurations(ctx context.Context, root string) (core.RunConfigResolution, error) + ResolveRunConfigurations(ctx context.Context, root string, plugins []core.RunInstalledPlugin) (core.RunConfigResolution, error) DecideTitleAction(ctx context.Context, facts core.TitleActionFacts) (string, error) ProviderLaunchInputs(ctx context.Context, root, configurationID, providerRoot string) (core.RunProviderLaunchInputs, error) - UpdateRunConfigurationOptions(ctx context.Context, edit core.RunOptionsEdit) (string, error) + UpdateRunConfigurationOptions(ctx context.Context, edit core.RunOptionsEdit) ([]core.RunConfigChange, error) + // RunConfigurationTypes, RunEditorForm, SaveRunConfiguration, DeleteRunConfiguration and + // CreateRunLaunchPlan create, edit and start the built-in process runs (runconfig_process.go). + RunConfigurationTypes(ctx context.Context) ([]core.RunConfigurationType, error) + RunEditorForm(ctx context.Context, request core.RunEditorFormRequest) (core.RunEditorForm, error) + SaveRunConfiguration(ctx context.Context, request core.RunConfigurationSave) (core.RunConfigurationSaved, error) + DeleteRunConfiguration(ctx context.Context, root, configurationID string, plugins []core.RunInstalledPlugin) ([]core.RunConfigChange, error) + CreateRunLaunchPlan(ctx context.Context, root, configurationID, inlineScriptBase string) (core.RunLaunchPlan, error) RunArgumentText(ctx context.Context, lists [][]string) ([]string, error) SetDebugBreakpoints(ctx context.Context, sessionID, sourcePath string, breakpoints []core.DebugSourceBreakpoint) (core.DebugUpdate, error) ExecuteDebug(ctx context.Context, sessionID, operationID, command string, threadID *int64, granularity string) (core.DebugUpdate, error) diff --git a/desktop/internal/workbench/build.go b/desktop/internal/workbench/build.go index b12570e9a2..3090887d72 100644 --- a/desktop/internal/workbench/build.go +++ b/desktop/internal/workbench/build.go @@ -501,6 +501,8 @@ func (a *App) loadBuildSystems(p *project) { if a.plugins == nil || a.plugins.Backend == nil { p.build.loaded = true p.build.failed = a.text.Build.PluginsUnavailable + // Built-in process runs start without any plugin. + a.refreshRunConfigurations(p) return } p.build.loading = true @@ -580,6 +582,10 @@ func (a *App) finishBuildDetection(p *project, generation uint64, instances []bu } else if err != nil { p.build.status = a.launchFailureText(err) } + // The configurations are resolved after every detection: a model that came with detection + // is loaded already, so no model answer turns its runs into configurations, and built-in + // process runs need no build system at all, so a failed or empty detection lists them too. + a.refreshRunConfigurations(p) if len(instances) == 0 { p.build.status = a.text.Build.NoBuildSystems return @@ -588,11 +594,6 @@ func (a *App) finishBuildDetection(p *project, generation uint64, instances []bu if p.runConfigs.wanted { a.loadTitleRunConfigs(p) } - // A model that came with detection is loaded already, so no model answer turns its runs - // into configurations; they are resolved here instead. - if _, loaded := providerRuns(p.build.instances); loaded { - a.refreshRunConfigurations(p) - } } // loadBuildModel loads the model of an instance whose detection did not carry one (a @@ -1870,7 +1871,8 @@ func (a *App) finishBuildTask(p *project, op *buildOperation, result json.RawMes } // finishBuildRun ends a host process with how it exited: a non-zero exit fails with its code, -// and a process that could not be waited for or ended on a signal fails without one. +// and a process that could not be waited for or ended on a signal fails without one. A process +// that exited is summarized with its exit code, as a run a plugin reports is, not as a build. func (a *App) finishBuildRun(p *project, op *buildOperation, err error) { a.endServiceDebugSession(p, op) var exit *exec.ExitError @@ -1879,12 +1881,12 @@ func (a *App) finishBuildRun(p *project, op *buildOperation, err error) { a.endBuildOperation(p, op, "cancelled", nil, "", a.text.Build.Cancelled) case errors.As(err, &exit) && exit.ExitCode() > 0: code := exit.ExitCode() - a.endBuildOperation(p, op, "failed", &code, "", a.text.Build.Exited(code)) + a.endBuildOperation(p, op, "failed", &code, "", a.text.Run.Exited(code)) case err != nil: a.endBuildOperation(p, op, "failed", nil, "", a.text.Build.ProcessFailed(err.Error())) default: code := 0 - a.endBuildOperation(p, op, "completed", &code, "", a.text.Build.Succeeded) + a.endBuildOperation(p, op, "completed", &code, "", a.text.Run.Exited(code)) } } diff --git a/desktop/internal/workbench/build_tree_view.go b/desktop/internal/workbench/build_tree_view.go index 36e14672f8..5c0073941c 100644 --- a/desktop/internal/workbench/build_tree_view.go +++ b/desktop/internal/workbench/build_tree_view.go @@ -70,13 +70,33 @@ func (a *App) buildToolActions(c ui.C, p *project) { } // buildToolView declares the Build tool window: the run configurations, and under them the -// tree of the build systems under a filter field, or why there is none. The models of the groups the tree shows open are loaded after -// it is declared, a few at a time. +// tree of the build systems under a filter field, or why there is none. The configurations show +// whatever detection found, so the built-in script and program runs stay reachable in a project +// without a build system or while detection fails. The models of the groups the tree shows open +// are loaded after it is declared, a few at a time. func (a *App) buildToolView(c ui.C, p *project) { - b, t, language := &p.build, a.text.Build, a.language() + b := &p.build if !b.loaded && !b.loading { a.loadBuildSystems(p) } + ui.Column(c).Fill().Children(func() { + a.runConfigList(c, p) + // The filter field and the tree, or the notice that stands for them, are one pane, the + // second of the splitter under the run configurations, so the splitter's limits count + // the whole tree and not the field alone. + ui.Column(c).FillWidth().Grow(1).Shrink(1).MinHeight(0).Children(func() { + a.buildSystemsPane(c, p) + }) + }) + if b.loaded && b.failed == "" && len(b.instances) > 0 { + a.loadOpenBuildModels(p) + } +} + +// buildSystemsPane declares the build systems' part of the Build window: the filter field and +// the tree, or why there is none. +func (a *App) buildSystemsPane(c ui.C, p *project) { + b, t, language := &p.build, a.text.Build, a.language() switch { case b.loading || !b.loaded: a.buildNotice(c, t.LoadingModel, "", func() { @@ -104,37 +124,29 @@ func (a *App) buildToolView(c ui.C, p *project) { }) return } - ui.Column(c).Fill().Children(func() { - a.runConfigList(c, p) - // The filter field and the tree are one pane, the second of the splitter under the run - // configurations, so the splitter's limits count the whole tree and not the field alone. - ui.Column(c).FillWidth().Grow(1).Shrink(1).MinHeight(0).Children(func() { - a.buildFilter(c, p) - // The rows are listed after the filter field took this frame's typing, so the tree - // already shows what was typed. - rows, pending := a.buildTreeRows(p) - if len(rows) == 0 { - // A filter whose trees are still being laid out shows nothing rather than no match. - if !pending { - a.buildNotice(c, i18n.Shared(language, "desktop.build.noMatches"), "", nil) - } - return - } - list := &p.panels.choices - // Groups and folders open and close by a click, so none of them is a pinned header. - list.Header = nil - list.Label = func(i int) string { - if i >= 0 && i < len(rows) { - return rows[i].label - } - return "" - } - ui.List(c, list, len(rows), func(row ui.ListRow) { - a.buildTreeRow(row, p, rows[row.Index]) - }).Scrollbars().Label(t.Systems).FillWidth().Grow(1).MinHeight(0).PadY(treelist.PadY) - }) - }) - a.loadOpenBuildModels(p) + a.buildFilter(c, p) + // The rows are listed after the filter field took this frame's typing, so the tree + // already shows what was typed. + rows, pending := a.buildTreeRows(p) + if len(rows) == 0 { + // A filter whose trees are still being laid out shows nothing rather than no match. + if !pending { + a.buildNotice(c, i18n.Shared(language, "desktop.build.noMatches"), "", nil) + } + return + } + list := &p.panels.choices + // Groups and folders open and close by a click, so none of them is a pinned header. + list.Header = nil + list.Label = func(i int) string { + if i >= 0 && i < len(rows) { + return rows[i].label + } + return "" + } + ui.List(c, list, len(rows), func(row ui.ListRow) { + a.buildTreeRow(row, p, rows[row.Index]) + }).Scrollbars().Label(t.Systems).FillWidth().Grow(1).MinHeight(0).PadY(treelist.PadY) } // buildFilter declares the field that narrows the tree to the build systems, projects, diff --git a/desktop/internal/workbench/root.go b/desktop/internal/workbench/root.go index 3df5edb5b7..93ab9e9cd8 100644 --- a/desktop/internal/workbench/root.go +++ b/desktop/internal/workbench/root.go @@ -311,6 +311,8 @@ func (a *App) overlays(c ui.C) { a.drawSyncDialog(c, p) a.drawWorktreeDialog(c, p) a.drawRunConfigEditor(c, p) + a.drawRunConfigForm(c, p) + a.drawRunConfigDelete(c, p) a.buildOptionsDialog(c, p) a.drawStartupSweep(c) a.drawProjectReplace(c, p) diff --git a/desktop/internal/workbench/runconfig.go b/desktop/internal/workbench/runconfig.go index a317a36f49..0e0d53a3bc 100644 --- a/desktop/internal/workbench/runconfig.go +++ b/desktop/internal/workbench/runconfig.go @@ -8,12 +8,14 @@ import ( "slices" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" ) -// runConfigState is the Run tool window's run configurations: the build provider -// runs Core resolved from the detected, team (`.lithe/run/configurations.json`) and -// local (`.lithe/run/local.json`) layers, and the one the user picked. Only the -// window thread reads or writes it. +// runConfigState is the Run tool window's run configurations: the built-in process runs +// and the build provider runs Core resolved from the detected, project +// (`.lithe/run/configurations.yaml`), local (`.lithe/run/local.yaml`) and plugin +// (`.lithe/run/plugin/*.toml`) layers, and the one the user picked. Only the window +// thread reads or writes it. type runConfigState struct { // generation rejects the answer of a refresh another one replaced. generation uint64 @@ -21,13 +23,33 @@ type runConfigState struct { list []core.RunConfiguration selected string failure string - // hidden counts the saved configurations left out of list because no build plugin starts + // hidden counts the saved configurations left out of list because nothing here starts // them, so an empty list can say so: user entries of another provider, and saved entries // Core reports as orphaned because they no longer match a generated configuration, such as // the java.main entries an earlier version generated. hidden int - // editor is the dialog that edits one configuration's saved options. + // ignored are the saved documents Core left out, workspace-relative, each once: a plugin + // document that cannot be read or holds a configuration saved twice, and an earlier + // release's JSON document its YAML replacement wins over. The built-in configurations + // still list; the run menu names each file so its configurations do not vanish silently. + ignored []string + // types are the built-in kinds a user can create on this platform, in display order, + // read once per project; typesLoading is set while they are asked for. + types []core.RunConfigurationType + typesLoading bool + // editor is the dialog that edits one build provider run's saved options. editor runConfigEditor + // form is the dialog that creates or edits a built-in process run (runconfig_form.go). + form runConfigForm + // reveal is the configuration a save just wrote, selected once the next refresh lists it. + reveal string + // newMenu says the list header's menu of new configuration kinds is open. + newMenu bool + // deleting is the user configuration whose delete waits for confirmation. + deleting *runConfigDeletion + // start is the configuration a save asked to run, started once the next refresh lists it + // so the run reads what was saved. + start string // browser is the list that shows the configurations by scope and build system. browser runConfigBrowser // currentFile says the user chose Current File in the title bar, so its Run and Debug act @@ -87,7 +109,9 @@ func providerRuns(instances []buildInstance) ([]core.RunProviderRun, bool) { } // refreshRunConfigurations has Core generate the runs the loaded models declare and -// resolve the configurations again. Nothing is written into the workspace. +// resolve the configurations again. Nothing is written into the workspace. It runs +// without any loaded model too, so built-in process runs list and start while no +// build plugin works. func (a *App) refreshRunConfigurations(p *project) { if p == nil { return @@ -113,7 +137,7 @@ func (a *App) refreshRunConfigurations(p *project) { return func(a *App) { a.finishRunConfigurations(p, generation, core.RunConfigResolution{}, err) } } } - resolved, err := kernel.ResolveRunConfigurations(ctx, root) + resolved, err := kernel.ResolveRunConfigurations(ctx, root, a.runConfigPlugins(ctx)) return func(a *App) { a.finishRunConfigurations(p, generation, resolved, err) } }) } @@ -126,26 +150,49 @@ func (a *App) finishRunConfigurations(p *project, generation uint64, resolved co s.loading = false defer a.settleTitleAction(p) a.loadRunConfigPins(p) + a.loadRunConfigTypes(p) if err != nil { s.failure = err.Error() + s.reveal, s.start = "", "" return } s.failure = "" - // Only build provider runs can start here; the host has no launcher for the other - // providers Core detects. + // Built-in process runs and build provider runs start here; the host has no launcher + // for the other providers Core detects. An unavailable entry stays listed with its + // reason, so the user can fix or delete it. s.hidden = 0 + var ignored []string for _, diagnostic := range resolved.Diagnostics { if diagnostic.Code == "orphanedOverride" { s.hidden++ } + if diagnostic.Path != "" && !slices.Contains(ignored, diagnostic.Path) { + ignored = append(ignored, diagnostic.Path) + if !slices.Contains(s.ignored, diagnostic.Path) { + a.operationRejected("run_configuration_document", diagnostic.Code) + } + } } + s.ignored = ignored s.list = slices.DeleteFunc(resolved.Configurations, func(c core.RunConfiguration) bool { _, ok := c.BuildReference() + ok = ok || c.IsProcess() || c.Unavailable() if !ok && !c.Disabled { s.hidden++ } return !ok || c.Disabled }) + if s.reveal != "" && s.configuration(s.reveal) != nil { + s.selected = s.reveal + } + s.reveal = "" + if start := s.start; start != "" { + s.start = "" + if s.configuration(start) != nil && p.build.operation == nil { + s.selected = start + a.runConfiguration(p, start) + } + } if s.configuration(s.selected) == nil { s.selected = "" if resolved.DefaultRunConfiguration != nil && s.configuration(*resolved.DefaultRunConfiguration) != nil { @@ -156,11 +203,16 @@ func (a *App) finishRunConfigurations(p *project, generation uint64, resolved co } } -// runConfiguration starts configuration id through its build provider with the launch -// options Core resolves from the saved layers. The Run window ignores the refusal; the IDE -// API reports it through startRunConfiguration. +// runConfiguration is a press that runs configuration id, from the editor, the list of run +// configurations or a session's Rerun: it starts the run with the launch options Core +// resolves from the saved layers and brings the Run window forward on its console, since +// that is where the run prints. A refusal was already told the user or is a press on a +// button that is disabled; the IDE API reports it through startRunConfiguration, which +// leaves the windows as they are. func (a *App) runConfiguration(p *project, id string) { - _, _ = a.startRunConfiguration(p, id) + if _, err := a.startRunConfiguration(p, id); err == nil { + a.showBuildConsole(p) + } } // startRunConfiguration checks the request on the window thread, reserves the run as the @@ -182,6 +234,18 @@ func (a *App) startRunConfigurationWith(p *project, id string, debug *connection if p.build.operation != nil { return nil, errBuildBusy } + if configuration.Unavailable() { + message := a.runConfigUnavailableText(*configuration) + a.operationRejected("run_configuration", "unavailable") + a.notifyError(message) + return nil, refuseBuild(refusalNotReady, message) + } + if configuration.IsProcess() { + if debug != nil { + return nil, refuseBuild(refusalNotSupported, "a built-in process run has no debugger") + } + return a.startProcessRun(p, *configuration), nil + } reference, ok := configuration.BuildReference() if !ok { return nil, refuseBuild(refusalNotSupported, "this configuration does not start through a build provider") @@ -257,9 +321,16 @@ func (p *project) buildInstanceIndex(reference core.RunProviderReference) int { }) } -// runConfigurationReady reports whether a configuration can start now: its build instance -// has a loaded model. +// runConfigurationReady reports whether a configuration can start now: a built-in process +// run always can unless it is unavailable; a build provider run once its build instance has +// a loaded model. func (p *project) runConfigurationReady(configuration core.RunConfiguration) bool { + if configuration.Unavailable() { + return false + } + if configuration.IsProcess() { + return true + } reference, ok := configuration.BuildReference() if !ok { return false @@ -267,3 +338,33 @@ func (p *project) runConfigurationReady(configuration core.RunConfiguration) boo index := p.buildInstanceIndex(reference) return index >= 0 && p.build.instances[index].modelLoaded } + +// runConfigUnavailableText words why a listed configuration cannot run, from Core's +// availability code. An unknown code shows Core's own message as the reason. +func (a *App) runConfigUnavailableText(configuration core.RunConfiguration) string { + language := a.language() + availability := configuration.Availability + if availability == nil { + return "" + } + plugin, repository, requirement := "", "", "" + if configuration.Plugin != nil { + plugin, repository, requirement = configuration.Plugin.Name, configuration.Plugin.Repository, configuration.Plugin.VersionRequirement + if plugin == "" { + plugin = configuration.Plugin.ID + } + } + switch availability.Code { + case "pluginMissing": + return i18n.SharedFormat(language, "desktop.runConfig.unavailablePluginMissing", map[string]string{"plugin": plugin}) + case "pluginRepositoryMismatch": + return i18n.SharedFormat(language, "desktop.runConfig.unavailableRepositoryMismatch", map[string]string{"plugin": plugin, "repository": repository}) + case "pluginVersionUnsupported": + return i18n.SharedFormat(language, "desktop.runConfig.unavailableVersionUnsupported", map[string]string{"plugin": plugin, "requirement": requirement}) + case "missingWorkingDirectory": + return i18n.SharedFormat(language, "desktop.runConfig.unavailableMissingDirectory", map[string]string{"directory": configuration.Cwd}) + case "invalidConfiguration": + return i18n.SharedFormat(language, "desktop.runConfig.unavailableInvalid", map[string]string{"reason": availability.Message}) + } + return i18n.SharedFormat(language, "desktop.runConfig.unavailableOther", map[string]string{"reason": availability.Message}) +} diff --git a/desktop/internal/workbench/runconfig_browser.go b/desktop/internal/workbench/runconfig_browser.go index 808a4ba0d9..613911b645 100644 --- a/desktop/internal/workbench/runconfig_browser.go +++ b/desktop/internal/workbench/runconfig_browser.go @@ -90,10 +90,21 @@ type runConfigRow struct { group, configuration int } -// runConfigGroupKey names the build system that provides a configuration: its plugin and -// build system, whatever root the system was detected at. +// runProcessGroupKey is the group of the built-in process runs. It starts with the separator +// no plugin ID holds, so it never names a build system. +const runProcessGroupKey = "\x00process" + +// runConfigGroupKey names the group of a configuration: the built-in runs, or the build +// system that provides it, by its plugin and build system whatever root the system was +// detected at, or the plugin a run that cannot resolve needs. func runConfigGroupKey(configuration *core.RunConfiguration) string { - reference, _ := configuration.BuildReference() + if configuration.IsProcess() { + return runProcessGroupKey + } + reference, ok := configuration.BuildReference() + if !ok && configuration.Plugin != nil { + return configuration.Plugin.ID + "\x00" + } return reference.PluginID + "\x00" + reference.BuildSystemID } @@ -148,7 +159,7 @@ func (a *App) runScopeLabel(s *runConfigState, scope string) string { // collectRunConfigRows groups the configurations of the scope under their build systems, the // groups by title and the configurations by name, and lists the rows as they show: each // group, then its configurations unless the user closed it. -func (p *project) collectRunConfigRows() { +func (p *project) collectRunConfigRows(language i18n.Language) { s := &p.runConfigs b := &s.browser b.groups, b.rows = b.groups[:0], b.rows[:0] @@ -161,7 +172,7 @@ func (p *project) collectRunConfigRows() { g := slices.IndexFunc(b.groups, func(group runConfigGroup) bool { return group.key == key }) if g < 0 { g = len(b.groups) - b.groups = append(b.groups, runConfigGroup{key: key, title: p.runConfigGroupTitle(configuration)}) + b.groups = append(b.groups, runConfigGroup{key: key, title: p.runConfigGroupTitle(language, configuration)}) } b.groups[g].configurations = append(b.groups[g].configurations, index) } @@ -183,10 +194,17 @@ func (p *project) collectRunConfigRows() { } } -// runConfigGroupTitle is the title of the group of a configuration: the name its detected -// build system gives itself, else the build system's identity. -func (p *project) runConfigGroupTitle(configuration *core.RunConfiguration) string { - reference, _ := configuration.BuildReference() +// runConfigGroupTitle is the title of the group of a configuration: the built-in runs', the +// name its detected build system gives itself, else the build system's identity, or the name +// of the plugin a run that cannot resolve needs. +func (p *project) runConfigGroupTitle(language i18n.Language, configuration *core.RunConfiguration) string { + if configuration.IsProcess() { + return i18n.Shared(language, "desktop.runConfig.builtInGroup") + } + reference, ok := configuration.BuildReference() + if plugin := configuration.Plugin; !ok && plugin != nil { + return cmp.Or(plugin.Name, plugin.ID) + } if index := p.buildInstanceIndex(reference); index >= 0 && p.build.instances[index].System.DisplayName != "" { return p.build.instances[index].System.DisplayName } diff --git a/desktop/internal/workbench/runconfig_browser_test.go b/desktop/internal/workbench/runconfig_browser_test.go index 670e80d946..c4154ff66b 100644 --- a/desktop/internal/workbench/runconfig_browser_test.go +++ b/desktop/internal/workbench/runconfig_browser_test.go @@ -154,6 +154,13 @@ func TestRunConfigurationListScopesGroupsPinsAndRuns(t *testing.T) { t.Fatalf("run request %+v, want the service run of the main target", request) } h.settle() + // The run's console comes forward in the Run window. Its tab is named as the + // configuration is, so the window is closed again before the row is pressed by name. + if !h.app.chrome.isOpen(catalogIndex[itemRun]) { + t.Fatal("the run did not bring the Run window forward") + } + h.app.post(func(a *App) { a.reduceChrome(core.ToggleChrome(itemRun)) }) + h.settle() // The row of the configuration that runs shows it running, and its button stops it. operation := &buildOperation{configuration: serve} diff --git a/desktop/internal/workbench/runconfig_changes.go b/desktop/internal/workbench/runconfig_changes.go new file mode 100644 index 0000000000..e494c1ffd8 --- /dev/null +++ b/desktop/internal/workbench/runconfig_changes.go @@ -0,0 +1,201 @@ +package workbench + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "path/filepath" + "slices" + "strings" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// runConfigDirectory holds every document a run configuration edit changes: +// `.lithe/run/configurations.yaml` (project), `.lithe/run/local.yaml` (this +// machine) and the plugin documents under `.lithe/run/plugin/`. Core reads them +// when it resolves and never writes them; the host applies the changes Core returns. +const ( + runConfigDirectory = ".lithe/" + // runConfigMaximumBytes bounds each document the host captures and publishes. + runConfigMaximumBytes = 4 << 20 + // runConfigRollbackTimeout bounds restoring the files a failed transaction already changed. + runConfigRollbackTimeout = 5 * time.Second +) + +// errRunConfigChangePath refuses a change outside the workspace's `.lithe` directory. +var errRunConfigChangePath = errors.New("run configuration change outside .lithe") + +// runConfigFile is one change of a transaction with the file as it was captured. +type runConfigFile struct { + change core.RunConfigChange + snapshot configfile.Snapshot +} + +// applyRunConfigChanges applies the file changes of one Core edit reply as one transaction. +// Every file must still hold the bytes Core computed its change from, else nothing is written +// and the result is configfile.ErrConflict. Writes come before deletions, so a document that +// replaces a legacy one exists before the legacy one goes. When a later file fails, the files +// already changed are restored to their captured bytes, unless something else changed them since. +func applyRunConfigChanges(ctx context.Context, root string, changes []core.RunConfigChange) error { + files := make([]runConfigFile, 0, len(changes)) + seen := make(map[string]bool, len(changes)) + for _, change := range changes { + if !runConfigChangePathAllowed(change.Path) || seen[change.Path] { + return fmt.Errorf("%w: %s", errRunConfigChangePath, change.Path) + } + seen[change.Path] = true + if change.Content != nil && len(*change.Content) > runConfigMaximumBytes { + return configfile.ErrTooLarge + } + snapshot, err := configfile.Capture(ctx, root, change.Path, runConfigMaximumBytes) + if err != nil { + return err + } + if !runConfigBaseMatches(snapshot, change.BaseSHA256) { + return configfile.ErrConflict + } + files = append(files, runConfigFile{change: change, snapshot: snapshot}) + } + slices.SortStableFunc(files, func(a, b runConfigFile) int { + return runConfigChangeOrder(a.change) - runConfigChangeOrder(b.change) + }) + var committed []runConfigFile + for index, file := range files { + // Each publication rechecks the files still to come, so the transaction stops before + // its first write when any of them changed, not halfway through. + rest := files[index+1:] + check := func() error { + for _, other := range rest { + if err := other.snapshot.Verify(ctx); err != nil { + return err + } + } + return nil + } + var done bool + var err error + if file.change.Content == nil { + done, err = file.snapshot.Remove(ctx, check) + } else { + done, err = file.snapshot.Replace(ctx, []byte(*file.change.Content), check) + } + if done { + committed = append(committed, file) + } + if err != nil { + return errors.Join(err, rollbackRunConfigChanges(ctx, root, committed)) + } + } + return nil +} + +// runConfigChangeOrder sorts writes before deletions. +func runConfigChangeOrder(change core.RunConfigChange) int { + if change.Content == nil { + return 1 + } + return 0 +} + +// runConfigChangePathAllowed accepts a workspace-relative '/' path inside `.lithe`. +func runConfigChangePathAllowed(path string) bool { + return strings.HasPrefix(path, runConfigDirectory) && !strings.Contains(path, "\\") && + filepath.IsLocal(filepath.FromSlash(path)) && filepath.ToSlash(filepath.Clean(filepath.FromSlash(path))) == path +} + +// runConfigBaseMatches says the captured file is the one Core read: absent for a nil base, +// else bytes with that lowercase hex SHA-256. +func runConfigBaseMatches(snapshot configfile.Snapshot, base *string) bool { + if base == nil { + return !snapshot.Exists() + } + if !snapshot.Exists() { + return false + } + sum := sha256.Sum256(snapshot.Bytes()) + return hex.EncodeToString(sum[:]) == *base +} + +// rollbackRunConfigChanges restores the files a failed transaction changed, newest first. A +// file something else changed since is left alone and reported. The restore keeps running for +// a bounded time when the edit itself was cancelled. +func rollbackRunConfigChanges(ctx context.Context, root string, committed []runConfigFile) error { + if len(committed) == 0 { + return nil + } + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), runConfigRollbackTimeout) + defer cancel() + var failures []error + for _, file := range slices.Backward(committed) { + current, err := configfile.Capture(ctx, root, file.change.Path, runConfigMaximumBytes) + if err == nil && !runConfigHolds(current, file.change.Content) { + err = configfile.ErrConflict + } + if err == nil { + if file.snapshot.Exists() { + _, err = current.Replace(ctx, file.snapshot.Bytes(), nil) + } else { + _, err = current.Remove(ctx, nil) + } + } + if err != nil { + failures = append(failures, fmt.Errorf("restore %s: %w", file.change.Path, err)) + } + } + return errors.Join(failures...) +} + +// runConfigHolds says the file has content, or is absent for nil. +func runConfigHolds(snapshot configfile.Snapshot, content *string) bool { + if content == nil { + return !snapshot.Exists() + } + return snapshot.Exists() && string(snapshot.Bytes()) == *content +} + +// runConfigPluginManifest is the part of a plugin.json the run configuration checks read. +type runConfigPluginManifest struct { + ID string `json:"id"` + DisplayName string `json:"displayName"` + Version string `json:"version"` + Repository string `json:"repository"` + PluginAPIVersion *int `json:"pluginAPIVersion"` + Requires json.RawMessage `json:"requires"` +} + +// runConfigPlugins lists the enabled plugins for `runConfig.resolve` and the edit commands, so a +// configuration whose plugin is gone shows as unavailable and a written plugin document records +// the installed plugin. It is nil while the plugin host is not assembled, which skips those checks; +// a manifest that cannot be read leaves only that plugin out, and its configurations then show as +// unavailable. +func (a *App) runConfigPlugins(ctx context.Context) []core.RunInstalledPlugin { + if a.plugins == nil { + return nil + } + manifests, err := a.toolchainManifests(ctx) + if err != nil { + a.backgroundFailedIn(ctx, "run_config_plugins", err) + } + plugins := make([]core.RunInstalledPlugin, 0, len(manifests)) + for _, raw := range manifests { + var manifest runConfigPluginManifest + if json.Unmarshal(raw, &manifest) != nil || manifest.ID == "" || manifest.Version == "" { + continue + } + plugin := core.RunInstalledPlugin{ + ID: manifest.ID, DisplayName: manifest.DisplayName, Version: manifest.Version, + Repository: manifest.Repository, PluginAPIVersion: manifest.PluginAPIVersion, + } + if len(manifest.Requires) > 0 && string(manifest.Requires) != "null" { + plugin.Requires = manifest.Requires + } + plugins = append(plugins, plugin) + } + return plugins +} diff --git a/desktop/internal/workbench/runconfig_edit.go b/desktop/internal/workbench/runconfig_edit.go index be433082ba..20c0d79c7f 100644 --- a/desktop/internal/workbench/runconfig_edit.go +++ b/desktop/internal/workbench/runconfig_edit.go @@ -14,15 +14,6 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" ) -// The run configuration layers the editor writes, relative to the workspace root. Core -// reads the same files when it resolves; it never writes them. -const ( - runConfigLocalFile = ".lithe/run/local.json" - runConfigProjectFile = ".lithe/run/configurations.json" - // runConfigMaximumBytes bounds the layer document the host captures and publishes. - runConfigMaximumBytes = 4 << 20 -) - // runConfigEditor is the open editor of one configuration's options. It starts from // the effective values Core resolved, and saving writes them into the chosen layer // file, so the next resolve shows what took effect. Every field is bound to a widget @@ -153,8 +144,8 @@ func (a *App) closeRunConfigEditor(p *project) { e.open, e.loading, e.saving = false, false, false } -// saveRunConfigEditor has Core apply the edit to the chosen layer and publishes the -// document it returns, then resolves the configurations again. +// saveRunConfigEditor has Core apply the edit to the chosen layer, applies the file changes it +// returns, then resolves the configurations again. func (a *App) saveRunConfigEditor(p *project) { e := &p.runConfigs.editor if !e.open || e.loading || e.saving { @@ -180,9 +171,8 @@ func (a *App) saveRunConfigEditor(p *project) { } edit.ProviderRunOptions = raw } - kernel := a.kernel a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { - err := saveRunConfigOptions(ctx, kernel, edit) + err := a.saveRunConfigOptions(ctx, edit) return func(a *App) { e := &p.runConfigs.editor if !e.open || e.generation != generation { @@ -190,12 +180,7 @@ func (a *App) saveRunConfigEditor(p *project) { } e.saving = false if err != nil { - reason := err.Error() - if errors.Is(err, configfile.ErrConflict) { - e.failure = i18n.Shared(a.language(), "desktop.runConfig.conflict") - return - } - e.failure = i18n.SharedFormat(a.language(), "desktop.runConfig.saveFailed", map[string]string{"reason": reason}) + e.failure = a.runConfigSaveFailure(err) return } a.closeRunConfigEditor(p) @@ -204,31 +189,23 @@ func (a *App) saveRunConfigEditor(p *project) { }) } -// saveRunConfigOptions captures the scope's layer file, has Core edit it and publishes -// the result only if the file still holds the captured bytes. The local layer is -// handed to Core as captured, so the edit applies to exactly what is replaced. -func saveRunConfigOptions(ctx context.Context, kernel Kernel, edit core.RunOptionsEdit) error { - name := runConfigProjectFile - if edit.Scope == "local" { - name = runConfigLocalFile - } - file, err := configfile.Capture(ctx, edit.Root, name, runConfigMaximumBytes) +// saveRunConfigOptions has Core compute the file changes of the edit and applies them as one +// transaction, only while every file still holds the bytes Core read. +func (a *App) saveRunConfigOptions(ctx context.Context, edit core.RunOptionsEdit) error { + edit.Plugins = a.runConfigPlugins(ctx) + changes, err := a.kernel.UpdateRunConfigurationOptions(ctx, edit) if err != nil { return err } - if edit.Scope == "local" && file.Exists() { - local := file.Bytes() - if !json.Valid(local) { - return errors.New(name + ": invalid JSON") - } - edit.LocalDocument = local - } - document, err := kernel.UpdateRunConfigurationOptions(ctx, edit) - if err != nil { - return err + return applyRunConfigChanges(ctx, edit.Root, changes) +} + +// runConfigSaveFailure words a failed save: another edit that came first, or the reason. +func (a *App) runConfigSaveFailure(err error) string { + if errors.Is(err, configfile.ErrConflict) { + return i18n.Shared(a.language(), "desktop.runConfig.conflict") } - _, err = file.Replace(ctx, []byte(document), nil) - return err + return i18n.SharedFormat(a.language(), "desktop.runConfig.saveFailed", map[string]string{"reason": err.Error()}) } // environmentText is the editor text of an environment: one KEY=VALUE line per diff --git a/desktop/internal/workbench/runconfig_edit_test.go b/desktop/internal/workbench/runconfig_edit_test.go index a63fc77995..30aab4ab25 100644 --- a/desktop/internal/workbench/runconfig_edit_test.go +++ b/desktop/internal/workbench/runconfig_edit_test.go @@ -2,7 +2,6 @@ package workbench import ( "context" - "encoding/json" "errors" "os" "path/filepath" @@ -65,12 +64,14 @@ func TestRunConfigEditorSavesTheLocalLayer(t *testing.T) { if !slices.Equal(got.Args, []string{"--name", "Alice Smith"}) || got.Cwd != "app/server" || got.Env["MODE"] != "prod" || got.Env["TRACE"] != "1" { t.Fatalf("configuration = %+v", got) } - data, err := os.ReadFile(filepath.Join(root, ".lithe", "run", "local.json")) - if err != nil || !json.Valid(data) || !strings.Contains(string(data), "Alice Smith") { - t.Fatalf("local.json = %s, %v", data, err) + data, err := os.ReadFile(filepath.Join(root, ".lithe", "run", "plugin", "dev.example.engine.local.toml")) + if err != nil || !strings.Contains(string(data), "Alice Smith") { + t.Fatalf("dev.example.engine.local.toml = %s, %v", data, err) } - if _, err := os.Stat(filepath.Join(root, ".lithe", "run", "configurations.json")); !errors.Is(err, os.ErrNotExist) { - t.Fatalf("the project layer was written: %v", err) + for _, layer := range []string{"dev.example.engine.toml", "../configurations.yaml", "../local.yaml"} { + if _, err := os.Stat(filepath.Join(root, ".lithe", "run", "plugin", layer)); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("%s was written: %v", layer, err) + } } // Reopening shows the saved values as editor text. @@ -92,39 +93,44 @@ func TestRunConfigEditorSavesTheLocalLayer(t *testing.T) { } } -// conflictingKernel rewrites the target layer while Core is editing it. +// conflictingKernel writes a layer file after Core read the layers and before the host +// applies the changes Core computed from what it read. type conflictingKernel struct { Kernel path string } -func (k *conflictingKernel) UpdateRunConfigurationOptions(ctx context.Context, edit core.RunOptionsEdit) (string, error) { - if err := os.WriteFile(k.path, []byte(`{"version":2,"configurations":[]}`), 0o600); err != nil { - return "", err +const conflictingContent = "# written by another program\n" + +func (k *conflictingKernel) UpdateRunConfigurationOptions(ctx context.Context, edit core.RunOptionsEdit) ([]core.RunConfigChange, error) { + changes, err := k.Kernel.UpdateRunConfigurationOptions(ctx, edit) + if err != nil { + return nil, err + } + if err := os.MkdirAll(filepath.Dir(k.path), 0o755); err != nil { + return nil, err } - return k.Kernel.UpdateRunConfigurationOptions(ctx, edit) + if err := os.WriteFile(k.path, []byte(conflictingContent), 0o600); err != nil { + return nil, err + } + return changes, nil } -// A layer file another writer changed after it was captured is not replaced. +// A layer file another writer created or changed after Core read the layers is not +// replaced: the save fails with a conflict and the other writer's file stays as written. func TestRunConfigSaveRefusesAConcurrentlyChangedLayer(t *testing.T) { root := t.TempDir() h, p := loadedRunConfigs(t, &testKernel{Client: core.NewClient()}, root) - path := filepath.Join(root, ".lithe", "run", "configurations.json") - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(path, []byte(`{"version":2,"configurations":[] }`), 0o600); err != nil { - t.Fatal(err) - } - kernel := &conflictingKernel{Kernel: h.app.kernel, path: path} + path := filepath.Join(root, ".lithe", "run", "plugin", "dev.example.engine.toml") + h.app.kernel = &conflictingKernel{Kernel: h.app.kernel, path: path} ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) defer cancel() - err := saveRunConfigOptions(ctx, kernel, core.RunOptionsEdit{Root: root, Scope: "project", ConfigurationID: p.runConfigs.selected, + err := h.app.saveRunConfigOptions(ctx, core.RunOptionsEdit{Root: root, Scope: "project", ConfigurationID: p.runConfigs.selected, Arguments: "--port 9", Environment: map[string]string{}}) if !errors.Is(err, configfile.ErrConflict) { t.Fatalf("save = %v, want a conflict", err) } - if data, _ := os.ReadFile(path); string(data) != `{"version":2,"configurations":[]}` { + if data, _ := os.ReadFile(path); string(data) != conflictingContent { t.Fatalf("the other writer's file was replaced: %s", data) } } diff --git a/desktop/internal/workbench/runconfig_form.go b/desktop/internal/workbench/runconfig_form.go new file mode 100644 index 0000000000..3136c5d980 --- /dev/null +++ b/desktop/internal/workbench/runconfig_form.go @@ -0,0 +1,430 @@ +package workbench + +import ( + "context" + "encoding/json" + "errors" + "maps" + "path/filepath" + "strings" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/vivaui/viva/app" +) + +// This file holds the editor of built-in process runs: shell, PowerShell and batch scripts +// and programs. Core describes the editor as data (`runConfig.editorForm`): the fields in +// order, their kinds and current values, and the automatic value of each empty field. Core +// also checks the values and returns the file changes that save them +// (`runConfig.saveConfiguration`); the host draws the fields, applies the changes and +// resolves the configurations again. A field this host cannot draw (a kind it does not +// know, or an ID it has no label for) is left out and its value goes back as it came, so a +// later Core can add fields, options and buttons' inputs without breaking this host. A new +// field shows here once it has a label in runConfigFieldLabel and a widget for its kind. + +// runConfigForm is the open editor of a built-in process run. +type runConfigForm struct { + open bool + // generation rejects the answer of an editor that was closed or reopened since. + generation uint64 + provider string + // id is the saved configuration edited; empty for a new one until a save names it. + id string + // name is the configuration's name as it was saved, for the dialog's title. + name string + loading, saving bool + failure string + fields []core.RunEditorField + // values are the values by field ID as Core returned them. A save sends them with the + // drawn fields' edits over them, so keys this host does not show go back unchanged. + values map[string]json.RawMessage + // texts and flags are the edited text and checkbox values by field ID. They are + // pointers, so each widget keeps the address it is bound by while the maps grow. + texts map[string]*string + flags map[string]*bool + // environment is the variable rows in order; each row keeps its address while rows + // are added or removed. + environment []*runConfigVariable + // errors are the wrong values the last save reported: a code such as required by field ID. + errors map[string]string + // refreshing says an editorForm request for the edited values is out, so the automatic + // values follow the edit; stale says a value changed since it was sent. + refreshing, stale bool +} + +// runConfigVariable is one environment variable row of the editor. +type runConfigVariable struct { + name, value string +} + +// runConfigFormStep is what follows a save that succeeded. +type runConfigFormStep int + +const ( + // runConfigFormApply keeps the editor open on the saved configuration. + runConfigFormApply runConfigFormStep = iota + // runConfigFormClose closes the editor. + runConfigFormClose + // runConfigFormRun closes the editor and runs the configuration once it is listed. + runConfigFormRun +) + +// Field kinds of `runConfig.editorForm` this host draws. +const ( + runFieldText = "text" + runFieldCheckbox = "checkbox" + runFieldChoice = "choice" + runFieldFile = "file" + runFieldMultilineText = "multilineText" + runFieldArguments = "arguments" + runFieldDirectory = "directory" + runFieldEnvironment = "environment" + runFieldExecutable = "executable" +) + +// runFieldTextual reports a kind whose value is one string. +func runFieldTextual(kind string) bool { + switch kind { + case runFieldText, runFieldChoice, runFieldFile, runFieldMultilineText, runFieldArguments, runFieldDirectory, runFieldExecutable: + return true + } + return false +} + +// loadRunConfigTypes reads once per project which built-in kinds a user can create here. +// A failure leaves them unread, so the next refresh asks again. +func (a *App) loadRunConfigTypes(p *project) { + s := &p.runConfigs + if s.types != nil || s.typesLoading { + return + } + s.typesLoading = true + kernel := a.kernel + a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { + types, err := kernel.RunConfigurationTypes(ctx) + return func(a *App) { + s := &p.runConfigs + s.typesLoading = false + if err != nil { + a.backgroundFailed("run_config_types", err) + return + } + // Only kinds this host can name are offered; the list is never nil once read. + s.types = make([]core.RunConfigurationType, 0, len(types)) + for _, kind := range types { + if _, ok := runConfigTypeLabel(a.language(), kind.Provider); ok { + s.types = append(s.types, kind) + } + } + } + }) +} + +// openRunConfigForm opens the editor on a new configuration of provider, or on the saved +// configuration id when it is set. +func (a *App) openRunConfigForm(p *project, provider, id string) { + f := &p.runConfigs.form + generation := f.generation + 1 + *f = runConfigForm{open: true, generation: generation, provider: provider, id: id, loading: true} + if configuration := p.runConfigs.configuration(id); configuration != nil { + f.name = configuration.Name + } + a.requestRunConfigForm(p, generation, core.RunEditorFormRequest{Root: p.root, Provider: provider, ConfigurationID: id}, true) +} + +// closeRunConfigForm closes the editor; answers still out are dropped. +func (a *App) closeRunConfigForm(p *project) { + f := &p.runConfigs.form + f.generation++ + f.open, f.loading, f.saving, f.refreshing, f.stale = false, false, false, false, false +} + +// requestRunConfigForm asks Core for the editor. The first answer fills the fields and +// values; a later one, for the values being edited, only replaces the field descriptions, +// so the automatic values follow the edit and nothing the user typed since is lost. +func (a *App) requestRunConfigForm(p *project, generation uint64, request core.RunEditorFormRequest, initial bool) { + kernel := a.kernel + a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { + form, err := kernel.RunEditorForm(ctx, request) + return func(a *App) { + f := &p.runConfigs.form + if !f.open || f.generation != generation { + return + } + if !initial { + a.finishRunConfigFormRefresh(p, form, err) + return + } + f.loading = false + language := a.language() + if err != nil { + a.operationFailed("run_config_form", err) + f.failure = i18n.SharedFormat(language, "desktop.runConfig.loadFailed", map[string]string{"reason": err.Error()}) + return + } + if form.FormVersion > core.RunFormVersion { + a.operationRejected("run_config_form", "form_version") + f.failure = i18n.Shared(language, "desktop.runConfig.formTooNew") + return + } + f.provider, f.fields, f.values = form.Provider, form.Fields, form.Values + if f.values == nil { + f.values = map[string]json.RawMessage{} + } + f.texts, f.flags = map[string]*string{}, map[string]*bool{} + f.readValues(form.Fields, form.Values) + } + }) +} + +// finishRunConfigFormRefresh takes the field descriptions for the edited values. A field +// that appears only now takes its value from the answer. +func (a *App) finishRunConfigFormRefresh(p *project, form core.RunEditorForm, err error) { + f := &p.runConfigs.form + f.refreshing = false + switch { + case err != nil: + // The descriptions in hand stay; only their automatic values may be out of date. + a.backgroundFailed("run_config_form_refresh", err) + case form.FormVersion > core.RunFormVersion || form.Provider != f.provider: + a.operationRejected("run_config_form_refresh", "form_mismatch") + default: + f.fields = form.Fields + f.readValues(form.Fields, form.Values) + } + if f.stale { + a.runConfigFormEdited(p) + } +} + +// readValues takes the value of each drawn field that has no edited value yet. +func (f *runConfigForm) readValues(fields []core.RunEditorField, values map[string]json.RawMessage) { + for _, field := range fields { + raw, known := values[field.ID] + if known { + if _, ok := f.values[field.ID]; !ok { + f.values[field.ID] = raw + } + } + switch { + case field.Kind == runFieldCheckbox: + if f.flags[field.ID] == nil { + flag := false + if known { + _ = json.Unmarshal(raw, &flag) + } + f.flags[field.ID] = &flag + } + case field.Kind == runFieldEnvironment: + if f.environment == nil { + f.environment = []*runConfigVariable{} + var rows []struct { + Name string `json:"name"` + Value string `json:"value"` + } + if known { + _ = json.Unmarshal(raw, &rows) + } + for _, row := range rows { + f.environment = append(f.environment, &runConfigVariable{name: row.Name, value: row.Value}) + } + } + case runFieldTextual(field.Kind): + if f.texts[field.ID] == nil { + text := "" + if known { + _ = json.Unmarshal(raw, &text) + } + f.texts[field.ID] = &text + } + } + } +} + +// collect is the values a save or a refresh sends: Core's values with every edited value +// over them. A value of a field this host does not draw goes back as it came. +func (f *runConfigForm) collect() map[string]json.RawMessage { + values := maps.Clone(f.values) + if values == nil { + values = map[string]json.RawMessage{} + } + for _, field := range f.fields { + var value any + switch { + case field.Kind == runFieldCheckbox && f.flags[field.ID] != nil: + value = *f.flags[field.ID] + case field.Kind == runFieldEnvironment && f.environment != nil: + rows := make([]map[string]string, 0, len(f.environment)) + for _, row := range f.environment { + rows = append(rows, map[string]string{"name": row.name, "value": row.value}) + } + value = rows + case runFieldTextual(field.Kind) && f.texts[field.ID] != nil: + value = *f.texts[field.ID] + default: + continue + } + if raw, err := json.Marshal(value); err == nil { + values[field.ID] = raw + } + } + return values +} + +// runConfigFormEdited asks for the editor of the edited values, so automatic values such as +// the interpreter a script's first line names follow the edit. One request is out at a +// time; an edit made while it is out sends one more when it answers. +func (a *App) runConfigFormEdited(p *project) { + f := &p.runConfigs.form + if !f.open || f.loading || f.fields == nil { + return + } + if f.refreshing { + f.stale = true + return + } + f.refreshing, f.stale = true, false + request := core.RunEditorFormRequest{Root: p.root, Provider: f.provider, ConfigurationID: f.id, Values: f.collect()} + a.requestRunConfigForm(p, f.generation, request, false) +} + +// saveRunConfigForm has Core check the values and compute the file changes, applies them as +// one transaction and resolves the configurations again. Wrong values stay in the editor +// with the reason beside each field. +func (a *App) saveRunConfigForm(p *project, step runConfigFormStep) { + f := &p.runConfigs.form + if !f.open || f.loading || f.saving || f.fields == nil { + return + } + f.saving, f.failure = true, "" + generation := f.generation + request := core.RunConfigurationSave{Root: p.root, Provider: f.provider, ConfigurationID: f.id, Values: f.collect()} + kernel := a.kernel + a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { + request.Plugins = a.runConfigPlugins(ctx) + saved, err := kernel.SaveRunConfiguration(ctx, request) + if err == nil && saved.Status == "saved" { + err = applyRunConfigChanges(ctx, request.Root, saved.Changes) + } else if err == nil && saved.Status != "invalid" { + err = errors.New("runConfig.saveConfiguration returned an unknown status") + } + return func(a *App) { + f := &p.runConfigs.form + current := f.open && f.generation == generation + if current { + f.saving = false + } + if err != nil { + a.operationFailed("run_config_save", err) + if current { + f.failure = a.runConfigSaveFailure(err) + } + return + } + if saved.Status == "invalid" { + a.operationRejected("run_config_save", "invalid_values") + if current { + f.errors = make(map[string]string, len(saved.Errors)) + for _, wrong := range saved.Errors { + if _, seen := f.errors[wrong.Field]; !seen { + f.errors[wrong.Field] = wrong.Code + } + } + } + return + } + s := &p.runConfigs + s.reveal = saved.ID + if current { + f.errors, f.id = nil, saved.ID + if name := f.texts["name"]; name != nil && strings.TrimSpace(*name) != "" { + f.name = strings.TrimSpace(*name) + } + if step == runConfigFormRun { + s.start = saved.ID + } + if step != runConfigFormApply { + a.closeRunConfigForm(p) + } + } + a.refreshRunConfigurations(p) + } + }) +} + +// deleteRunConfiguration removes a saved `user:` configuration from every layer file. +func (a *App) deleteRunConfiguration(p *project, id string) { + root, kernel := p.root, a.kernel + a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { + changes, err := kernel.DeleteRunConfiguration(ctx, root, id, a.runConfigPlugins(ctx)) + if err == nil { + err = applyRunConfigChanges(ctx, root, changes) + } + return func(a *App) { + if err != nil { + a.operationFailed("run_config_delete", err) + a.notifyError(i18n.SharedFormat(a.language(), "desktop.runConfig.deleteFailed", map[string]string{"reason": err.Error()})) + return + } + if f := &p.runConfigs.form; f.open && f.id == id { + a.closeRunConfigForm(p) + } + a.refreshRunConfigurations(p) + } + }) +} + +// browseRunConfigField asks for a file or a directory and puts its path in the field. A +// path inside the project is shown project-relative, as Core saves it; a program there +// keeps a leading "./", so it does not read as a name looked up on PATH. +func (a *App) browseRunConfigField(p *project, field core.RunEditorField, title string) { + generation, root := p.runConfigs.form.generation, p.root + a.background(nil, 0, func(context.Context) func(*App) { + var path string + var err error + if field.Kind == runFieldDirectory { + path, err = app.OpenDirectory(app.OpenDirectoryOptions{Title: title}) + } else { + var paths []string + paths, err = app.OpenFiles(app.OpenFileOptions{Title: title}) + if err == nil && len(paths) == 0 { + err = app.ErrCanceled + } + if err == nil { + path = paths[0] + } + } + return func(a *App) { + if errors.Is(err, app.ErrCanceled) { + // log-exempt: 用户取消:未选择文件或目录,字段保持不变。 + return + } + if err != nil { + a.operationFailed("run_config_browse", documentLogError(err)) + a.notifyError(i18n.Shared(a.language(), "desktop.runConfig.chooseFailed")) + return + } + f := &p.runConfigs.form + text := f.texts[field.ID] + if !f.open || f.generation != generation || text == nil { + return + } + *text = runConfigFieldPath(root, path, field.Kind) + a.runConfigFormEdited(p) + } + }) +} + +// runConfigFieldPath is the text a browsed path shows in a field of kind. +func runConfigFieldPath(root, path, kind string) string { + relative, err := filepath.Rel(root, path) + if err != nil || !filepath.IsLocal(relative) && relative != "." { + return path + } + relative = filepath.ToSlash(relative) + if kind == runFieldExecutable && !strings.Contains(relative, "/") { + return "./" + relative + } + return relative +} diff --git a/desktop/internal/workbench/runconfig_form_view.go b/desktop/internal/workbench/runconfig_form_view.go new file mode 100644 index 0000000000..1bfcc13507 --- /dev/null +++ b/desktop/internal/workbench/runconfig_form_view.go @@ -0,0 +1,444 @@ +package workbench + +import ( + "encoding/json" + "reflect" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/icons" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +const ( + // runConfigFormWidth is the editor dialog's width, wide enough for a path and its options. + runConfigFormWidth = 640 + // runConfigFormBodyMaxHeight bounds the fields, which scroll beyond it. + runConfigFormBodyMaxHeight = 520 + // runConfigFormLabelWidth is the column of field titles. + runConfigFormLabelWidth = 150 + // runConfigFormTextHeight is the height of a script saved as text. + runConfigFormTextHeight = 140 + // runConfigFormVariableNameWidth is the name column of an environment variable row. + runConfigFormVariableNameWidth = 170 +) + +// Built-in process run providers, as Core names them. +const ( + runProviderShell = "process.shell" + runProviderPowerShell = "process.powershell" + runProviderBatch = "process.batch" + runProviderExecutable = "process.executable" +) + +// runConfigTypeLabel names a built-in kind; ok is false for one this host has no name for. +func runConfigTypeLabel(language i18n.Language, provider string) (string, bool) { + switch provider { + case runProviderShell: + return i18n.Shared(language, "desktop.runConfig.typeShell"), true + case runProviderPowerShell: + return i18n.Shared(language, "desktop.runConfig.typePowerShell"), true + case runProviderBatch: + return i18n.Shared(language, "desktop.runConfig.typeBatch"), true + case runProviderExecutable: + return i18n.Shared(language, "desktop.runConfig.typeExecutable"), true + } + return "", false +} + +// runConfigTypeIcon is the icon of a built-in kind: a script or a program. +func runConfigTypeIcon(provider string) gfx.Icon { + if provider == runProviderExecutable { + return icons.Cpu + } + return icons.FileCode +} + +// runConfigFieldLabel is the title of an editor field; ok is false for a field this host has +// no title for, which it then leaves out. +func runConfigFieldLabel(language i18n.Language, id string) (string, bool) { + switch id { + case "name": + return i18n.Shared(language, "desktop.runConfig.fieldName"), true + case "storeAsProjectFile": + return i18n.Shared(language, "desktop.runConfig.fieldStoreAsProjectFile"), true + case "source": + return i18n.Shared(language, "desktop.runConfig.fieldSource"), true + case "script": + return i18n.Shared(language, "desktop.runConfig.fieldScript"), true + case "text": + return i18n.Shared(language, "desktop.runConfig.fieldText"), true + case "scriptOptions": + return i18n.Shared(language, "desktop.runConfig.fieldScriptOptions"), true + case "programArguments": + return i18n.Shared(language, "desktop.runConfig.arguments"), true + case "workingDirectory": + return i18n.Shared(language, "desktop.runConfig.workingDirectory"), true + case "environment": + return i18n.Shared(language, "desktop.runConfig.environment"), true + case "interpreter": + return i18n.Shared(language, "desktop.runConfig.fieldInterpreter"), true + case "interpreterArguments": + return i18n.Shared(language, "desktop.runConfig.fieldInterpreterArguments"), true + case "executionPolicyBypass": + return i18n.Shared(language, "desktop.runConfig.fieldExecutionPolicyBypass"), true + case "program": + return i18n.Shared(language, "desktop.runConfig.fieldProgram"), true + } + return "", false +} + +// runConfigFieldHelp is the ⓘ tip of a field: what its note means, or what the field does. +func runConfigFieldHelp(language i18n.Language, field core.RunEditorField) string { + switch { + case field.Note == "windowsOnly": + return i18n.Shared(language, "desktop.runConfig.noteWindowsOnly") + case field.ID == "storeAsProjectFile": + return i18n.Shared(language, "desktop.runConfig.storeAsProjectFileHelp") + case field.ID == "interpreter": + return i18n.Shared(language, "desktop.runConfig.interpreterHelp") + } + return "" +} + +// runConfigChoiceLabel names an option of a choice field; ok is false for one this host has +// no name for, and the field is then left out. +func runConfigChoiceLabel(language i18n.Language, field, option string) (string, bool) { + switch field + "/" + option { + case "source/file": + return i18n.Shared(language, "desktop.runConfig.sourceFile"), true + case "source/text": + return i18n.Shared(language, "desktop.runConfig.sourceText"), true + } + return "", false +} + +// runConfigFieldError words the code of a wrong value. An unknown code shows as itself. +func runConfigFieldError(language i18n.Language, code string) string { + switch code { + case "required": + return i18n.Shared(language, "desktop.runConfig.errorRequired") + case "conflict": + return i18n.Shared(language, "desktop.runConfig.errorConflict") + case "notAllowed": + return i18n.Shared(language, "desktop.runConfig.errorNotAllowed") + case "tooLong": + return i18n.Shared(language, "desktop.runConfig.errorTooLong") + case "invalidCharacter": + return i18n.Shared(language, "desktop.runConfig.errorInvalidCharacter") + case "invalidPath": + return i18n.Shared(language, "desktop.runConfig.errorInvalidPath") + case "notFound": + return i18n.Shared(language, "desktop.runConfig.errorNotFound") + case "outsideProject": + return i18n.Shared(language, "desktop.runConfig.errorOutsideProject") + case "invalidName": + return i18n.Shared(language, "desktop.runConfig.errorInvalidName") + case "duplicate": + return i18n.Shared(language, "desktop.runConfig.errorDuplicate") + } + return i18n.SharedFormat(language, "desktop.runConfig.errorOther", map[string]string{"code": code}) +} + +// drawable reports whether this host draws field: a kind it knows, a title it has, and for a +// choice a name for every option. +func (f *runConfigForm) drawable(language i18n.Language, field core.RunEditorField) bool { + if _, ok := runConfigFieldLabel(language, field.ID); !ok { + return false + } + switch field.Kind { + case runFieldCheckbox: + return f.flags[field.ID] != nil + case runFieldEnvironment: + return f.environment != nil + case runFieldChoice: + for _, option := range field.Options { + if _, ok := runConfigChoiceLabel(language, field.ID, option); !ok { + return false + } + } + } + return runFieldTextual(field.Kind) && f.texts[field.ID] != nil +} + +// visible reports whether field shows for the edited values: always, or while the field its +// condition names has the value the condition wants. +func visibleRunConfigField(field core.RunEditorField, values map[string]json.RawMessage) bool { + condition := field.VisibleWhen + if condition == nil { + return true + } + var current any + if raw, ok := values[condition.Field]; !ok || json.Unmarshal(raw, ¤t) != nil { + return false + } + return reflect.DeepEqual(current, condition.Equals) +} + +// runConfigFormTitle is the dialog's title: the kind of a new configuration, or the name of +// the one edited. +func (a *App) runConfigFormTitle(f *runConfigForm) string { + language := a.language() + kind, _ := runConfigTypeLabel(language, f.provider) + if f.id == "" || f.name == "" { + return i18n.SharedFormat(language, "desktop.runConfig.newTitle", map[string]string{"type": kind}) + } + return i18n.SharedFormat(language, "desktop.runConfig.editTitle", map[string]string{"name": f.name}) +} + +// drawRunConfigForm declares the open editor of a built-in process run: the name and where it +// is stored on top, then the fields Core described in order, and Run, Cancel, Apply and OK. +func (a *App) drawRunConfigForm(c ui.C, p *project) { + f := &p.runConfigs.form + if !f.open { + return + } + language := a.language() + ready := !f.loading && !f.saving && f.fields != nil + open := true + closed := ui.ModalWith(c, &open, a.runConfigFormTitle(f), ui.ModalSpec{Width: runConfigFormWidth}, func() { + k := c.Part("run-config-form") + ui.Scroll(k).Scrollbars().FillWidth().MaxHeight(runConfigFormBodyMaxHeight).Children(func() { + ui.Column(k).FillWidth().Gap(10).PadSides(0, 12, 0, 0).Children(func() { + if f.loading { + ui.Text(k, i18n.Shared(language, "native.loading")).Color(a.colors.Subtle) + } + a.drawRunConfigFormFields(k, p, f, ready) + if f.failure != "" { + ui.Paragraph(k, f.failure, 4).FontSize(a.theme.Metrics.FontSizeS).Color(a.theme.Danger) + } + }) + }) + }, func() { + ui.Row(c.Part("run-config-form-footer")).FillWidth().Items(ui.Center).Gap(8).Children(func() { + if ui.Button(c, i18n.Shared(language, "desktop.runConfig.run")).Icon(icons.Play).Outline().Disabled(!ready || p.build.operation != nil).Clicked() { + c.After(func() { + a.performed("run.configuration.form.run", surfaceButton) + a.saveRunConfigForm(p, runConfigFormRun) + }) + } + ui.Spacer(c) + if ui.Button(c, i18n.Shared(language, "desktop.git.cancel")).Outline().Clicked() { + c.After(func() { a.closeRunConfigForm(p) }) + } + if ui.Button(c, i18n.Shared(language, "desktop.runConfig.apply")).Outline().Disabled(!ready).Clicked() { + c.After(func() { + a.performed("run.configuration.form.apply", surfaceButton) + a.saveRunConfigForm(p, runConfigFormApply) + }) + } + if ui.Button(c, i18n.Shared(language, "desktop.runConfig.ok")).Disabled(!ready).Clicked() { + c.After(func() { + a.performed("run.configuration.form.save", surfaceButton) + a.saveRunConfigForm(p, runConfigFormClose) + }) + } + }) + }) + if closed { + c.After(func() { a.closeRunConfigForm(p) }) + } +} + +// drawRunConfigFormFields declares the header row, then every other field that shows for the +// edited values. A wrong value's reason sits under its field; one for a field not drawn sits +// at the end. +func (a *App) drawRunConfigFormFields(c ui.C, p *project, f *runConfigForm, ready bool) { + if f.fields == nil { + return + } + language := a.language() + values := f.collect() + drawn := map[string]bool{} + var header, body []core.RunEditorField + for _, field := range f.fields { + if !f.drawable(language, field) || !visibleRunConfigField(field, values) { + continue + } + drawn[field.ID] = true + if field.Placement == "header" { + header = append(header, field) + } else { + body = append(body, field) + } + } + if len(header) > 0 { + ui.Row(c.Part("header")).FillWidth().Items(ui.Center).Gap(12).Children(func() { + for _, field := range header { + a.drawRunConfigFormHeaderField(c.Key(field.ID), p, f, field, ready) + } + }) + for _, field := range header { + a.drawRunConfigFormError(c.Key(field.ID), f, field.ID, 0) + } + ui.Divider(c) + } + for _, field := range body { + a.drawRunConfigFormField(c.Key(field.ID), p, f, field, ready) + } + for _, wrong := range f.fields { + if !drawn[wrong.ID] { + a.drawRunConfigFormError(c.Key(wrong.ID), f, wrong.ID, 0) + } + } +} + +// drawRunConfigFormHeaderField declares a field of the top row: the name grows, a checkbox +// keeps its size. +func (a *App) drawRunConfigFormHeaderField(c ui.C, p *project, f *runConfigForm, field core.RunEditorField, ready bool) { + language := a.language() + label, _ := runConfigFieldLabel(language, field.ID) + if field.Kind == runFieldCheckbox { + ui.Row(c).Shrink(0).Items(ui.Center).Gap(4).Children(func() { + if ui.Checkbox(c, f.flags[field.ID], label).Disabled(!ready).Changed() { + c.After(func() { a.runConfigFormEdited(p) }) + } + a.runConfigFormHelp(c, language, field) + }) + return + } + ui.Row(c).Grow(1).MinWidth(0).Items(ui.Center).Gap(8).Children(func() { + ui.Text(c, label).Shrink(0) + a.drawRunConfigFormControl(c, p, f, field, label, ready) + }) +} + +// drawRunConfigFormField declares one field as a row: its title and ⓘ in the title column, +// its control beside them, and the reason a saved value was wrong under it. A checkbox +// carries its own title in the control column. +func (a *App) drawRunConfigFormField(c ui.C, p *project, f *runConfigForm, field core.RunEditorField, ready bool) { + language := a.language() + label, _ := runConfigFieldLabel(language, field.ID) + tall := field.Kind == runFieldMultilineText || field.Kind == runFieldEnvironment + ui.Column(c).FillWidth().Gap(4).Children(func() { + row := ui.Row(c).FillWidth().Gap(12) + if tall { + row = row.Items(ui.Start) + } else { + row = row.Items(ui.Center) + } + row.Children(func() { + ui.Row(c.Part("title")).Width(runConfigFormLabelWidth).MinHeight(28).Shrink(0).Items(ui.Center).Gap(4).Children(func() { + if field.Kind != runFieldCheckbox { + ui.Text(c, label).Ellipsis().Shrink(1).MinWidth(0) + a.runConfigFormHelp(c, language, field) + } + }) + if field.Kind == runFieldCheckbox { + ui.Row(c).Grow(1).Items(ui.Center).Gap(4).Children(func() { + if ui.Checkbox(c, f.flags[field.ID], label).Disabled(!ready).Changed() { + c.After(func() { a.runConfigFormEdited(p) }) + } + a.runConfigFormHelp(c, language, field) + }) + return + } + a.drawRunConfigFormControl(c, p, f, field, label, ready) + }) + a.drawRunConfigFormError(c, f, field.ID, runConfigFormLabelWidth+12) + }) +} + +// drawRunConfigFormControl declares the control of a field by its kind. A field whose +// automatic value applies while it is empty shows that value as its placeholder. +func (a *App) drawRunConfigFormControl(c ui.C, p *project, f *runConfigForm, field core.RunEditorField, label string, ready bool) { + language := a.language() + placeholder := "" + switch { + case field.Automatic != nil: + placeholder = i18n.SharedFormat(language, "desktop.runConfig.automaticValue", map[string]string{"value": *field.Automatic}) + case field.Kind == runFieldArguments: + placeholder = i18n.Shared(language, "desktop.runConfig.argumentsPlaceholder") + } + edited := func() { c.After(func() { a.runConfigFormEdited(p) }) } + switch field.Kind { + case runFieldEnvironment: + a.drawRunConfigVariables(c, p, f, ready) + case runFieldChoice: + options := field.Options + if ui.Choice(c, f.texts[field.ID], options, func(option string) string { + name, _ := runConfigChoiceLabel(language, field.ID, option) + return name + }).Disabled(!ready).Changed() { + edited() + } + case runFieldMultilineText: + if ui.TextArea(c, f.texts[field.ID], label, placeholder).Mono().Grow(1).Height(runConfigFormTextHeight).Disabled(!ready).Changed() { + edited() + } + case runFieldFile, runFieldExecutable, runFieldDirectory: + box := ui.TextField(c, f.texts[field.ID], label, placeholder).Grow(1).MinWidth(0).Disabled(!ready). + Action(icons.FolderOpen, i18n.Shared(language, "desktop.runConfig.browse")) + if box.Changed() { + edited() + } + if box.ActionClicked() { + c.After(func() { a.browseRunConfigField(p, field, label) }) + } + default: + if ui.TextField(c, f.texts[field.ID], label, placeholder).Grow(1).MinWidth(0).Disabled(!ready).Changed() { + edited() + } + } +} + +// drawRunConfigVariables declares the environment variable rows, each a name, a value and its +// remove button, and the button that adds a row. +func (a *App) drawRunConfigVariables(c ui.C, p *project, f *runConfigForm, ready bool) { + language := a.language() + nameLabel, valueLabel := i18n.Shared(language, "desktop.runConfig.variableName"), i18n.Shared(language, "desktop.runConfig.variableValue") + ui.Column(c.Part("variables")).Grow(1).MinWidth(0).Gap(6).Children(func() { + for index, variable := range f.environment { + k := c.KeyInt(index) + ui.Row(k).FillWidth().Items(ui.Center).Gap(6).Children(func() { + if ui.TextField(k.Part("name"), &variable.name, nameLabel, nameLabel).Width(runConfigFormVariableNameWidth).Shrink(0).Disabled(!ready).Changed() { + c.After(func() { a.runConfigFormEdited(p) }) + } + if ui.TextField(k.Part("value"), &variable.value, valueLabel, valueLabel).Grow(1).MinWidth(0).Disabled(!ready).Changed() { + c.After(func() { a.runConfigFormEdited(p) }) + } + if a.gitIconButton(k.Part("remove"), i18n.Shared(language, "desktop.runConfig.variableRemove"), icons.Trash2, false, !ready) { + c.After(func() { + f.environment = removeRunConfigVariable(f.environment, variable) + a.runConfigFormEdited(p) + }) + } + }) + } + if ui.Button(c.Part("add"), i18n.Shared(language, "desktop.runConfig.variableAdd")).Icon(icons.Plus).Ghost().Disabled(!ready).Clicked() { + c.After(func() { f.environment = append(f.environment, &runConfigVariable{}) }) + } + }) +} + +// removeRunConfigVariable is rows without row. +func removeRunConfigVariable(rows []*runConfigVariable, row *runConfigVariable) []*runConfigVariable { + kept := make([]*runConfigVariable, 0, len(rows)) + for _, other := range rows { + if other != row { + kept = append(kept, other) + } + } + return kept +} + +// runConfigFormHelp declares the ⓘ of a field that has a tip. +func (a *App) runConfigFormHelp(c ui.C, language i18n.Language, field core.RunEditorField) { + if help := runConfigFieldHelp(language, field); help != "" { + ui.Button(c.Part("help"), i18n.Shared(language, "native.moreInformation")).Icon(icons.Info).IconOnly().Ghost(). + Size(18, 18).Shrink(0).Tooltip(help).TooltipOn(ui.TooltipRight) + } +} + +// drawRunConfigFormError declares the reason the last save found field's value wrong, indented +// under its control. +func (a *App) drawRunConfigFormError(c ui.C, f *runConfigForm, field string, indent float32) { + code, ok := f.errors[field] + if !ok { + return + } + ui.Row(c.Part("error")).FillWidth().PadSides(0, 0, 0, indent).Children(func() { + ui.Paragraph(c, runConfigFieldError(a.language(), code), 3).FontSize(a.theme.Metrics.FontSizeS).Color(a.theme.Danger) + }) +} diff --git a/desktop/internal/workbench/runconfig_process.go b/desktop/internal/workbench/runconfig_process.go new file mode 100644 index 0000000000..a3937ca358 --- /dev/null +++ b/desktop/internal/workbench/runconfig_process.go @@ -0,0 +1,192 @@ +package workbench + +import ( + "context" + "errors" + "fmt" + "maps" + "os" + "os/exec" + "path/filepath" + + "github.com/1lck/Lithe-IDEA/desktop/internal/buildprocess" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/loginenv" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" + "github.com/1lck/Lithe-IDEA/desktop/internal/processledger" +) + +// This file starts the built-in process runs: shell, PowerShell and batch scripts and +// programs. Core plans each run (`runConfig.createLaunchPlan`); the host only finds the +// executable, writes a script saved as text to a temporary file, and starts the process +// with its output in the Run window. No build plugin takes part, so these runs work while +// every plugin is missing or broken. +// +// Note: 内置运行和运行配置文件格式的决策见 .agents/notes/implemented/architecture/2026-11-18-builtin-process-runs-and-run-file-formats.md + +// inlineScriptDirectoryPattern names the temporary directory a script saved as text runs +// from. It lives under the system's temporary directory, never in the app bundle or the +// project, and is removed once the process exits; one left by a crash is the system's to +// clean. +const inlineScriptDirectoryPattern = "lithe-run-script-" + +// errRunProgramNotFound is a planned command that no PATH directory holds. +var errRunProgramNotFound = errors.New("run program not found") + +// startProcessRun reserves the run as the window's operation and starts it once unsaved +// documents are saved, so the process reads the files on disk. Rerun starts it again. +func (a *App) startProcessRun(p *project, configuration core.RunConfiguration) *buildOperation { + id := configuration.ID + op := a.beginBuildOperation(p, "run", configuration.Name, id, func(a *App, p *project) { + a.runConfiguration(p, id) + }) + a.saveProjectDocuments(p, func(ok bool) { + if op.cancelled { + a.finishBuildError(p, op, context.Canceled) + return + } + if !ok { + a.endBuildOperation(p, op, "failed", nil, "unsaved documents could not be saved", "") + return + } + a.launchProcessRun(p, op, id) + }) + return op +} + +// launchProcessRun plans the run, starts its process and waits for it off the window +// thread. The plan is bounded by the run preparation time; the process runs until it +// exits, the user stops it or the project closes. +func (a *App) launchProcessRun(p *project, op *buildOperation, id string) { + root, kernel, language := p.root, a.kernel, a.language() + a.background(p, 0, func(ctx context.Context) func(*App) { + bounded, cancel := context.WithTimeout(ctx, runPreparationTimeout) + defer cancel() + prepare, release := op.bind(bounded) + defer release() + scratch, err := os.MkdirTemp("", inlineScriptDirectoryPattern) + if err != nil { + return func(a *App) { a.finishBuildError(p, op, err) } + } + defer func() { + if err := os.RemoveAll(scratch); err != nil { + a.backgroundFailedIn(ctx, "run_inline_script_cleanup", err) + } + }() + plan, err := kernel.CreateRunLaunchPlan(prepare, root, id, filepath.Join(scratch, "script")) + if err != nil { + return func(a *App) { a.finishBuildError(p, op, err) } + } + spec, err := a.processRunSpec(prepare, root, plan) + if errors.Is(err, errRunProgramNotFound) { + err = errors.New(i18n.SharedFormat(language, "desktop.runConfig.programNotFound", map[string]string{"program": plan.Executable.Command})) + } + if err == nil && plan.InlineScript != nil { + err = writeInlineScript(scratch, *plan.InlineScript) + } + if err == nil { + err = prepare.Err() + } + if err != nil { + return func(a *App) { a.finishBuildError(p, op, err) } + } + process, err := buildprocess.Start(ctx, spec, func(_ buildprocess.Stream, text string) { + a.streamBuildOutput(p, op, text) + }) + if err != nil { + return func(a *App) { a.finishBuildError(p, op, err) } + } + a.post(func(a *App) { a.attachProcess(p, op, process) }) + err = process.Wait() + return func(a *App) { a.finishBuildRun(p, op, err) } + }) +} + +// processRunSpec turns a launch plan into the process to start: the executable found, the +// working directory under the project, and the environment the plan sets over the login +// environment. A toolchain executable brings its own variables and PATH entries. +func (a *App) processRunSpec(ctx context.Context, root string, plan core.RunLaunchPlan) (buildprocess.Spec, error) { + directory, err := projectRunDirectory(root, plan.WorkingDirectory) + if err != nil { + return buildprocess.Spec{}, err + } + environment := make(map[string]string, len(plan.Environment)+len(plan.Env)) + maps.Copy(environment, plan.Environment) + maps.Copy(environment, plan.Env) + spec := buildprocess.Spec{ + Kind: processledger.KindRun, + Arguments: plan.Arguments, + WorkingDirectory: directory, + CommandLine: plan.CommandLine, + } + switch executable := plan.Executable; { + case executable.Path != "": + if !filepath.IsAbs(executable.Path) { + return buildprocess.Spec{}, fmt.Errorf("run program path is not absolute: %s", executable.Path) + } + spec.Executable = executable.Path + case executable.Command != "": + searchPath, set := environment["PATH"] + if !set { + searchPath = loginenv.Path() + } + spec.Executable, err = runCommandOnPath(executable.Command, searchPath) + if err != nil { + return buildprocess.Spec{}, err + } + case executable.Toolchain != "": + selection, err := a.resolveToolchainSelection(ctx, root, plan.WorkingDirectory, executable.Toolchain, "") + if err != nil { + return buildprocess.Spec{}, err + } + spec.Executable = selection.Executable + environment = applyToolchainSelection(environment, selection) + default: + return buildprocess.Spec{}, errors.New("run launch plan has no executable") + } + spec.Environment = environment + return spec, nil +} + +// projectRunDirectory is the native path of a project-relative '/' working directory. Core +// keeps it inside the project; one that leaves it is refused here too. +func projectRunDirectory(root, directory string) (string, error) { + native := filepath.FromSlash(directory) + if directory == "" { + native = "." + } + if !filepath.IsLocal(native) && filepath.Clean(native) != "." { + return "", fmt.Errorf("run working directory is outside the project: %s", directory) + } + return filepath.Join(root, native), nil +} + +// runCommandOnPath finds a bare command name in the absolute directories of searchPath, in +// order, with the platform's executable extensions on Windows. Relative entries are skipped, +// so a command never resolves against the current directory. +func runCommandOnPath(name, searchPath string) (string, error) { + for _, directory := range filepath.SplitList(searchPath) { + if directory == "" || !filepath.IsAbs(directory) { + continue + } + if path, err := pluginhost.CommandInDirectory(directory, name); err == nil { + return path, nil + } + } + return "", fmt.Errorf("%w: %s: %w", errRunProgramNotFound, name, exec.ErrNotFound) +} + +// writeInlineScript writes a script saved as text where Core planned it, which must be a +// new file directly in the run's temporary directory. +func writeInlineScript(scratch string, script core.RunInlineScript) error { + if filepath.Dir(script.Path) != filepath.Clean(scratch) { + return fmt.Errorf("inline script is outside its temporary directory: %s", script.Path) + } + file, err := os.OpenFile(script.Path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o700) + if err != nil { + return err + } + _, err = file.WriteString(script.Content) + return errors.Join(err, file.Close()) +} diff --git a/desktop/internal/workbench/runconfig_process_test.go b/desktop/internal/workbench/runconfig_process_test.go new file mode 100644 index 0000000000..50a9a743ed --- /dev/null +++ b/desktop/internal/workbench/runconfig_process_test.go @@ -0,0 +1,304 @@ +package workbench + +import ( + "encoding/json" + "errors" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" +) + +// A bare command is found only in the absolute directories of the search path, in order; a +// relative entry such as the current directory is never searched. +func TestRunCommandOnPathSkipsRelativeDirectories(t *testing.T) { + first, second := t.TempDir(), t.TempDir() + name := "lithe-test-tool" + file := name + if runtime.GOOS == "windows" { + file += ".exe" + } + for _, directory := range []string{first, second} { + if err := os.WriteFile(filepath.Join(directory, file), []byte("#!/bin/sh\n"), 0o755); err != nil { + t.Fatal(err) + } + } + relative, err := filepath.Rel(mustGetwd(t), first) + if err != nil { + relative = "relative-entry" + } + searchPath := strings.Join([]string{"", relative, second, first}, string(os.PathListSeparator)) + got, err := runCommandOnPath(name, searchPath) + if err != nil || filepath.Dir(got) != second { + t.Fatalf("found %q, %v; want the copy in %s", got, err, second) + } + if _, err := runCommandOnPath("lithe-test-missing", searchPath); !errors.Is(err, errRunProgramNotFound) || !errors.Is(err, exec.ErrNotFound) { + t.Fatalf("missing command = %v", err) + } +} + +func mustGetwd(t *testing.T) string { + t.Helper() + directory, err := os.Getwd() + if err != nil { + t.Fatal(err) + } + return directory +} + +// A script saved as text is written only as a new file directly in the run's temporary +// directory. +func TestWriteInlineScriptStaysInItsDirectory(t *testing.T) { + scratch := t.TempDir() + path := filepath.Join(scratch, "script.sh") + if err := writeInlineScript(scratch, core.RunInlineScript{Path: path, Content: "echo hi\n"}); err != nil { + t.Fatal(err) + } + if data, err := os.ReadFile(path); err != nil || string(data) != "echo hi\n" { + t.Fatalf("script = %q, %v", data, err) + } + if err := writeInlineScript(scratch, core.RunInlineScript{Path: path, Content: "other"}); err == nil { + t.Fatal("an existing script was overwritten") + } + for _, outside := range []string{filepath.Join(t.TempDir(), "script.sh"), filepath.Join(scratch, "nested", "script.sh")} { + if err := writeInlineScript(scratch, core.RunInlineScript{Path: outside, Content: "x"}); err == nil { + t.Fatalf("a script was written at %s", outside) + } + } +} + +// The working directory Core plans is joined under the project; one that leaves it is +// refused here too. +func TestProjectRunDirectoryStaysInTheProject(t *testing.T) { + root := t.TempDir() + for directory, want := range map[string]string{"": root, ".": root, "app/server": filepath.Join(root, "app", "server")} { + if got, err := projectRunDirectory(root, directory); err != nil || got != want { + t.Fatalf("%q = %q, %v; want %q", directory, got, err, want) + } + } + for _, directory := range []string{"..", "../other", "app/../../other"} { + if got, err := projectRunDirectory(root, directory); err == nil { + t.Fatalf("%q = %q, want a refusal", directory, got) + } + } +} + +// A browsed path inside the project shows project-relative with '/'; a program directly in +// the project root keeps "./" so it is not looked up on PATH; anything else stays absolute. +func TestRunConfigFieldPathIsProjectRelative(t *testing.T) { + root := t.TempDir() + outside := filepath.Join(t.TempDir(), "tool") + cases := []struct{ path, kind, want string }{ + {filepath.Join(root, "scripts", "build.sh"), runFieldFile, "scripts/build.sh"}, + {filepath.Join(root, "tool"), runFieldExecutable, "./tool"}, + {filepath.Join(root, "bin", "tool"), runFieldExecutable, "bin/tool"}, + {root, runFieldDirectory, "."}, + {outside, runFieldExecutable, outside}, + } + for _, c := range cases { + if got := runConfigFieldPath(root, c.path, c.kind); got != c.want { + t.Fatalf("%s (%s) = %q, want %q", c.path, c.kind, got, c.want) + } + } +} + +// A field with a condition shows only while the other field holds the value; one without +// always shows. +func TestVisibleRunConfigFieldFollowsItsCondition(t *testing.T) { + script := core.RunEditorField{ID: "script", Kind: runFieldFile, VisibleWhen: &core.RunFieldCondition{Field: "source", Equals: "file"}} + name := core.RunEditorField{ID: "name", Kind: runFieldText} + for source, want := range map[string]bool{`"file"`: true, `"text"`: false} { + values := map[string]json.RawMessage{"source": json.RawMessage(source)} + if got := visibleRunConfigField(script, values); got != want { + t.Fatalf("script with source %s visible = %v", source, got) + } + if !visibleRunConfigField(name, values) { + t.Fatal("a field without a condition is hidden") + } + } + if visibleRunConfigField(script, map[string]json.RawMessage{}) { + t.Fatal("a field whose condition has no value is shown") + } +} + +// The values a save sends are Core's values with every edit over them; a value of a field +// this host does not draw goes back unchanged. +func TestRunConfigFormCollectKeepsValuesItDoesNotDraw(t *testing.T) { + f := &runConfigForm{values: map[string]json.RawMessage{}, texts: map[string]*string{}, flags: map[string]*bool{}} + f.fields = []core.RunEditorField{ + {ID: "name", Kind: runFieldText}, + {ID: "storeAsProjectFile", Kind: runFieldCheckbox}, + {ID: "environment", Kind: runFieldEnvironment}, + } + f.readValues(f.fields, map[string]json.RawMessage{ + "name": json.RawMessage(`"Old"`), + "storeAsProjectFile": json.RawMessage(`false`), + "environment": json.RawMessage(`[{"name":"A","value":"1"}]`), + "future": json.RawMessage(`{"kept":true}`), + }) + f.values["future"] = json.RawMessage(`{"kept":true}`) + *f.texts["name"] = "New" + *f.flags["storeAsProjectFile"] = true + f.environment = append(f.environment, &runConfigVariable{name: "B", value: "2"}) + got := f.collect() + want := map[string]string{ + "name": `"New"`, + "storeAsProjectFile": `true`, + "environment": `[{"name":"A","value":"1"},{"name":"B","value":"2"}]`, + "future": `{"kept":true}`, + } + for id, value := range want { + if string(got[id]) != value { + t.Fatalf("%s = %s, want %s", id, got[id], value) + } + } +} + +// A project without any build plugin creates a built-in run from the editor, saves it to the +// project file and starts it with Run; the output reaches the Run window and the temporary +// script is removed. The title bar's Run button starts it again. The script runs under the +// system's own shell (cmd on Windows), so no developer tool is needed. +func TestBuiltInRunIsCreatedAndRunWithoutAnyPlugin(t *testing.T) { + temporary := t.TempDir() + for _, variable := range []string{"TMPDIR", "TMP", "TEMP"} { + t.Setenv(variable, temporary) + } + provider, text := runProviderShell, "echo hello-from-lithe\n" + if runtime.GOOS == "windows" { + provider, text = runProviderBatch, "@echo hello-from-lithe\r\n" + } + root := t.TempDir() + h := newHarness(t, &testKernel{Client: core.NewClient()}) + h.open(root) + p := h.app.project + h.app.post(func(a *App) { a.refreshRunConfigurations(p) }) + awaitStateWithin(t, h, 10*time.Second, "the empty configuration list", func() bool { + s := &p.runConfigs + return s.generation > 0 && !s.loading && s.types != nil + }) + if s := &p.runConfigs; s.failure != "" || len(s.list) != 0 { + t.Fatalf("configurations = %+v failure %q", s.list, s.failure) + } + + f := &p.runConfigs.form + h.app.post(func(a *App) { a.openRunConfigForm(p, provider, "") }) + awaitStateWithin(t, h, 10*time.Second, "the new configuration's form", func() bool { return f.open && !f.loading && f.fields != nil }) + h.app.post(func(a *App) { + *f.texts["name"] = "Greet" + *f.texts["source"] = "text" + *f.flags["storeAsProjectFile"] = true + a.runConfigFormEdited(p) + }) + awaitStateWithin(t, h, 10*time.Second, "the text field", func() bool { return !f.refreshing && f.texts["text"] != nil }) + h.app.post(func(a *App) { + *f.texts["text"] = text + a.saveRunConfigForm(p, runConfigFormRun) + }) + awaitStateWithin(t, h, 10*time.Second, "the save", func() bool { return !f.open || len(f.errors) > 0 || f.failure != "" }) + if f.open { + t.Fatalf("the form stayed open: errors %v failure %q", f.errors, f.failure) + } + first := awaitProcessRun(t, h, p, "Greet", nil) + if !strings.Contains(first.output.all(), "hello-from-lithe") { + t.Fatalf("console:\n%s", first.output.all()) + } + if !h.app.chrome.isOpen(catalogIndex[itemRun]) || p.build.view != first.id { + t.Fatalf("the Run window is not showing the run: open %v, view %q", h.app.chrome.isOpen(catalogIndex[itemRun]), p.build.view) + } + data, err := os.ReadFile(filepath.Join(root, ".lithe", "run", "configurations.yaml")) + if err != nil || !strings.Contains(string(data), "Greet") || !strings.Contains(string(data), provider) { + t.Fatalf("configurations.yaml = %s, %v", data, err) + } + if _, err := os.Stat(filepath.Join(root, ".lithe", "run", "local.yaml")); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("the local layer was written: %v", err) + } + if left, _ := filepath.Glob(filepath.Join(temporary, inlineScriptDirectoryPattern+"*")); len(left) != 0 { + t.Fatalf("temporary scripts left behind: %v", left) + } + + if c := p.titleConfiguration(); c == nil || c.Name != "Greet" { + t.Fatalf("title configuration = %+v", c) + } + h.app.post(func(a *App) { a.titleRun(p) }) + again := awaitProcessRun(t, h, p, "Greet", first) + if !strings.Contains(again.output.all(), "hello-from-lithe") { + t.Fatalf("the title bar's Run did not run it again; console:\n%s", again.output.all()) + } +} + +// awaitProcessRun waits for an ended run session labeled label other than previous and +// requires it to have succeeded. A new run replaces the ended tab of the same label and the +// harness clock does not advance by itself, so the session is told apart by identity, not by +// its start time. +func awaitProcessRun(t *testing.T, h *harness, p *project, label string, previous *runEntry) *runEntry { + t.Helper() + var found *runEntry + defer func() { + if found == nil { + for _, entry := range p.build.runs { + t.Logf("session %q running %v outcome %v summary %q console:\n%s", entry.label, entry.running, entry.outcome, entry.summary, entry.output.all()) + } + t.Logf("configurations %+v failure %q notice %q", p.runConfigs.list, p.runConfigs.failure, lastNotice(h)) + } + }() + awaitStateWithin(t, h, 20*time.Second, "the run of "+label, func() bool { + for _, entry := range p.build.runs { + if entry != previous && entry.label == label && !entry.running && p.build.operation == nil { + found = entry + return true + } + } + return false + }) + if found.outcome != runSucceeded || found.summary != h.app.text.Run.Exited(0) { + t.Fatalf("run %s ended %v: %s; console:\n%s", label, found.outcome, found.summary, found.output.all()) + } + return found +} + +// A plugin's run configuration file that cannot be read leaves the built-in runs listed, and +// the run menu names the file whose configurations are missing. +func TestUnreadablePluginRunDocumentKeepsBuiltInRunsListed(t *testing.T) { + root := t.TempDir() + plugins := filepath.Join(root, ".lithe", "run", "plugin") + if err := os.MkdirAll(plugins, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(plugins, "dev.example.engine.toml"), []byte("["), 0o600); err != nil { + t.Fatal(err) + } + saved := "version: 2\nconfigurations:\n- id: user:greet\n name: Greet\n provider: " + runProviderShell + "\n" + if err := os.WriteFile(filepath.Join(root, ".lithe", "run", "configurations.yaml"), []byte(saved), 0o600); err != nil { + t.Fatal(err) + } + h := newHarness(t, &testKernel{Client: core.NewClient()}) + h.open(root) + p := h.app.project + h.app.post(func(a *App) { a.refreshRunConfigurations(p) }) + awaitStateWithin(t, h, 10*time.Second, "the run configurations", func() bool { + return p.runConfigs.generation > 0 && !p.runConfigs.loading + }) + s := &p.runConfigs + if s.failure != "" || s.configuration("user:greet") == nil { + t.Fatalf("configurations = %+v failure %q", s.list, s.failure) + } + path := ".lithe/run/plugin/dev.example.engine.toml" + if len(s.ignored) != 1 || s.ignored[0] != path { + t.Fatalf("ignored = %v, want [%s]", s.ignored, path) + } + h.click(center(h.button(itemRunConfig))) + h.settle() + text := i18n.SharedFormat(h.app.language(), "desktop.runConfig.documentIgnored", map[string]string{"file": "dev.example.engine.toml"}) + if !h.shows(text) { + t.Fatalf("the run menu does not show %q", text) + } + h.clickNamed(text) + file := filepath.Join(plugins, "dev.example.engine.toml") + awaitStateWithin(t, h, 10*time.Second, "the unread file in the editor", func() bool { return p.docs.byPath(file) != nil }) +} diff --git a/desktop/internal/workbench/runconfig_process_visual_test.go b/desktop/internal/workbench/runconfig_process_visual_test.go new file mode 100644 index 0000000000..fa8f7bdffa --- /dev/null +++ b/desktop/internal/workbench/runconfig_process_visual_test.go @@ -0,0 +1,165 @@ +//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/store" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" +) + +// TestVisualBuiltInProcessRuns captures the built-in runs of a project without any plugin: +// the editor of a shell script with a script file and with script text, the Run window after +// the script ran, the menu that creates a run of each kind this platform offers, the editors +// of a PowerShell script and of an executable, and the title bar's run menu naming a run +// configuration file that was not read. The script runs under the system's shell. It needs +// only LITHE_VISUAL_OUTPUT_DIR; the dark captures are in Chinese and the light ones in English. +func TestVisualBuiltInProcessRuns(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR") + } + if err := os.MkdirAll(out, 0755); err != nil { + t.Fatal(err) + } + for _, look := range []struct{ theme, language string }{{"dark", "zh-Hans"}, {"light", "en-US"}} { + theme, language := look.theme, look.language + { + t.Run(theme, func(t *testing.T) { + temporary := t.TempDir() + for _, variable := range []string{"TMPDIR", "TMP", "TEMP"} { + t.Setenv(variable, temporary) + } + root := filepath.Join(t.TempDir(), "ScriptDemo") + files := map[string]string{ + "scripts/greet.sh": "#!/bin/bash\necho \"$GREETING from $1\"\n", + "scripts/clean.ps1": "Remove-Item -Recurse build\n", + "bin/README.md": "Tools built here.\n", + } + for name, text := range files { + path := filepath.Join(root, filepath.FromSlash(name)) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(text), 0o644); err != nil { + t.Fatal(err) + } + } + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, map[string]string{"theme": theme}); err != nil { + t.Fatal(err) + } + var session *headless.Session + h := newHarnessWithDriver(t, Options{Kernel: &testKernel{Client: core.NewClient()}, Store: prefs, Languages: []string{language}}, func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = 1200, 760 + var err error + session, err = headless.Open(config, nil, headless.Options{}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + shot := func(scene string) { + t.Helper() + h.settleChain() + if err := session.Screenshot(filepath.Join(out, "builtin-run-"+scene+"-"+theme+".png")); err != nil { + t.Fatal(err) + } + } + p := h.openTree(t, root) + h.app.post(func(a *App) { a.refreshRunConfigurations(p) }) + awaitStateWithin(t, h, 10*time.Second, "the run kinds", func() bool { + s := &p.runConfigs + return s.generation > 0 && !s.loading && s.types != nil + }) + f := &p.runConfigs.form + // edit opens the editor of a new run of provider, sets the texts and checkboxes + // given, and waits for the fields that follow the edit. + edit := func(provider string, texts map[string]string, flags map[string]bool, variables ...*runConfigVariable) { + t.Helper() + // The editor closed before keeps its fields, so the one waited for is told + // apart by its generation. + var generation uint64 + h.app.post(func(a *App) { + a.openRunConfigForm(p, provider, "") + generation = f.generation + }) + awaitStateWithin(t, h, 10*time.Second, "the editor of "+provider, func() bool { + return generation != 0 && f.generation == generation && f.open && !f.loading && f.fields != nil + }) + h.app.post(func(a *App) { + for id, value := range texts { + if text := f.texts[id]; text != nil { + *text = value + } + } + for id, value := range flags { + if flag := f.flags[id]; flag != nil { + *flag = value + } + } + f.environment = append(f.environment, variables...) + a.runConfigFormEdited(p) + }) + awaitStateWithin(t, h, 10*time.Second, "the edited editor", func() bool { return !f.refreshing }) + } + + edit(runProviderShell, map[string]string{"name": "Greet", "source": "file", "script": "scripts/greet.sh", "scriptOptions": "Lithe", "workingDirectory": "scripts"}, + map[string]bool{"storeAsProjectFile": true}, &runConfigVariable{name: "GREETING", value: "Hello"}) + shot("shell-file") + + h.app.post(func(a *App) { + *f.texts["source"] = "text" + a.runConfigFormEdited(p) + }) + awaitStateWithin(t, h, 10*time.Second, "the script text field", func() bool { return !f.refreshing && f.texts["text"] != nil }) + h.app.post(func(a *App) { *f.texts["text"] = "echo \"$GREETING from $(pwd)\"\nuname -s\n" }) + shot("shell-text") + + h.app.post(func(a *App) { a.saveRunConfigForm(p, runConfigFormRun) }) + awaitStateWithin(t, h, 10*time.Second, "the save", func() bool { return !f.open || len(f.errors) > 0 || f.failure != "" }) + if f.open { + t.Fatalf("the editor stayed open: errors %v failure %q", f.errors, f.failure) + } + awaitProcessRun(t, h, p, "Greet", nil) + shot("run-output") + + h.click(center(h.button(itemBuild))) + h.settleChain() + h.app.post(func(a *App) { p.runConfigs.newMenu = true }) + shot("new-menu") + h.app.post(func(a *App) { p.runConfigs.newMenu = false }) + + edit(runProviderPowerShell, map[string]string{"name": "Clean", "source": "file", "script": "scripts/clean.ps1"}, nil) + shot("powershell") + h.app.post(func(a *App) { a.closeRunConfigForm(p) }) + + edit(runProviderExecutable, map[string]string{"name": "Tool", "program": "bin/tool", "programArguments": "--verbose \"two words\"", "workingDirectory": "bin"}, nil) + shot("executable") + h.app.post(func(a *App) { a.closeRunConfigForm(p) }) + + plugins := filepath.Join(root, ".lithe", "run", "plugin") + if err := os.MkdirAll(plugins, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(plugins, "dev.example.engine.toml"), []byte("["), 0o600); err != nil { + t.Fatal(err) + } + generation := p.runConfigs.generation + h.app.post(func(a *App) { a.refreshRunConfigurations(p) }) + awaitStateWithin(t, h, 10*time.Second, "the unread file", func() bool { + s := &p.runConfigs + return s.generation > generation && !s.loading && len(s.ignored) == 1 + }) + h.click(center(h.button(itemRunConfig))) + shot("run-menu") + }) + } + } +} diff --git a/desktop/internal/workbench/runconfig_view.go b/desktop/internal/workbench/runconfig_view.go index 5f477d94ec..1262af8c7d 100644 --- a/desktop/internal/workbench/runconfig_view.go +++ b/desktop/internal/workbench/runconfig_view.go @@ -13,21 +13,34 @@ import ( ) // runConfigList declares the run configurations over the build systems: a header with the -// scope picker, the configurations of the scope under the build system that provides them, -// and the splitter that sizes the list against the panes under it. It shows once Core resolved -// at least one configuration; a failure without one is a line of its own. +// scope picker and the button that creates a built-in run, the configurations of the scope +// under the build system that provides them, and the splitter that sizes the list against the +// panes under it. Without a configuration the header stays, over a line that says why: the +// load failed, or there is none yet. func (a *App) runConfigList(c ui.C, p *project) { s := &p.runConfigs b := &s.browser language, small := a.language(), a.theme.Metrics.FontSizeS + title := i18n.Shared(language, "native.runConfigurations") + // The list shares the Build window with the build tree, so its rows are keyed under a part + // of their own. + k := c.Part("run-configs") if len(s.list) == 0 { - if s.failure != "" { - ui.Row(c.Part("run-config")).Height(panelHeaderHeight).FillWidth().Shrink(0).Items(ui.Center).PadX(8).Children(func() { - ui.Text(c, i18n.SharedFormat(language, "desktop.runConfig.loadFailed", map[string]string{"reason": s.failure})). - FontSize(small).Color(a.colors.Warning).Ellipsis().Grow(1) + ui.Column(k).FillWidth().Shrink(0).Children(func() { + a.drawRunConfigHeader(k, p, title, nil) + ui.Row(k.Part("empty")).Height(panelHeaderHeight).FillWidth().Items(ui.Center).PadX(8).Children(func() { + switch { + case s.failure != "": + ui.Text(k, i18n.SharedFormat(language, "desktop.runConfig.loadFailed", map[string]string{"reason": s.failure})). + FontSize(small).Color(a.colors.Warning).Ellipsis().Grow(1).MinWidth(0) + case s.loading: + ui.Text(k, i18n.Shared(language, "native.loading")).FontSize(small).Color(a.colors.Subtle).Ellipsis().Grow(1).MinWidth(0) + default: + ui.Text(k, i18n.Shared(language, "desktop.runConfig.emptyHint")).FontSize(small).Color(a.colors.Subtle).Ellipsis().Grow(1).MinWidth(0) + } }) - ui.Divider(c) - } + }) + ui.Divider(c) return } if b.split.Pos == 0 { @@ -37,29 +50,86 @@ func (a *App) runConfigList(c ui.C, p *project) { if !slices.Contains(scopes, b.scope) { b.scope = "" } - title := i18n.Shared(language, "native.runConfigurations") - // The list shares the Build window with the build tree, so its rows are keyed under a part - // of their own. - k := c.Part("run-configs") ui.Column(k).FillWidth().Height(b.split.Pos).Shrink(0).Clip().Children(func() { - ui.Row(k).Height(panelHeaderHeight).FillWidth().Shrink(0).Items(ui.Center).Gap(8).PadX(8).Children(func() { - ui.Text(k, title).FontSize(small).Weight(gfx.WeightSemibold).Color(a.colors.Subtle).Shrink(0) - ui.Select(k.Part("scope"), &b.scope, scopes, func(scope string) string { return a.runScopeLabel(s, scope) }). - Label(title).Shrink(1).MinWidth(0).MaxWidth(240) - ui.Spacer(k) - }) + a.drawRunConfigHeader(k, p, title, scopes) a.drawRunConfigRows(k, p, title) }) ui.Splitter(c, &b.split).Mins(runConfigListMin, runConfigRestMin).Label(a.text.Panel.Resize) } +// drawRunConfigHeader declares the list's header: its title, the scope picker when there are +// scopes to pick, and the button whose menu creates a built-in run of each kind. +func (a *App) drawRunConfigHeader(c ui.C, p *project, title string, scopes []string) { + s := &p.runConfigs + b := &s.browser + language, small := a.language(), a.theme.Metrics.FontSizeS + ui.Row(c.Part("header")).Height(panelHeaderHeight).FillWidth().Shrink(0).Items(ui.Center).Gap(8).PadX(8).Children(func() { + ui.Text(c, title).FontSize(small).Weight(gfx.WeightSemibold).Color(a.colors.Subtle).Shrink(0) + if scopes != nil { + ui.Select(c.Part("scope"), &b.scope, scopes, func(scope string) string { return a.runScopeLabel(s, scope) }). + Label(title).Shrink(1).MinWidth(0).MaxWidth(240) + } + ui.Spacer(c) + label := i18n.Shared(language, "desktop.runConfig.newConfiguration") + add, clicked := a.toolIconButton(c.Part("new"), label, icons.Plus, s.newMenu, len(s.types) == 0) + if clicked { + s.newMenu = !s.newMenu + } + ui.Menu(c.Part("new-menu"), add, &s.newMenu, func(menu *ui.MenuItems) { + menu.WidthRange(180, 260) + a.runConfigTypeItems(c, menu, p, surfaceButton) + }) + }) +} + +// runConfigTypeItems adds an item per built-in kind this platform offers, each opening the +// editor of a new configuration of that kind. +func (a *App) runConfigTypeItems(c ui.C, menu *ui.MenuItems, p *project, surface actionSurface) { + language := a.language() + for _, kind := range p.runConfigs.types { + label, ok := runConfigTypeLabel(language, kind.Provider) + if !ok { + continue + } + provider := kind.Provider + if menu.Item(label).Icon(runConfigTypeIcon(provider)).Clicked() { + c.After(func() { + a.performed("run.configuration.new", surface) + a.openRunConfigForm(p, provider, "") + }) + } + } + if len(p.runConfigs.types) == 0 { + menu.Item(i18n.Shared(language, "native.loading")).Disabled(true) + } +} + +// editRunConfiguration opens the editor that suits configuration id: the form of a built-in +// run, or the options of a build provider run. +func (a *App) editRunConfiguration(p *project, id string) { + configuration := p.runConfigs.configuration(id) + switch { + case configuration == nil: + case configuration.IsProcess(): + a.openRunConfigForm(p, configuration.Provider, id) + default: + a.openRunConfigEditor(p, id) + } +} + +// runConfigEditable says whether the list offers an editor for configuration: every built-in +// run, and a build provider run its plugin can still resolve. +func runConfigEditable(configuration core.RunConfiguration) bool { + return configuration.IsProcess() || !configuration.Unavailable() +} + // drawRunConfigRows declares the rows of the scope. Selecting a row keeps it selected; Enter // or a double click runs a configuration, when nothing runs and its build model has loaded, // and on a group opens or closes it. func (a *App) drawRunConfigRows(c ui.C, p *project, title string) { s := &p.runConfigs b := &s.browser - p.collectRunConfigRows() + p.collectRunConfigRows(a.language()) if len(b.rows) == 0 { a.gitEmpty(c, i18n.Shared(a.language(), "native.noConfigurationsInThisScope")) return @@ -133,10 +203,21 @@ func (a *App) drawRunConfigRow(p *project, row ui.ListRow, selected bool) { configuration := s.list[r.configuration] running := p.runningConfiguration() == configuration.ID a.runConfigMenu(c, box, p, configuration, running) + unavailable := configuration.Unavailable() + if unavailable { + box = box.Tooltip(a.runConfigUnavailableText(configuration)) + } box.Children(func() { ui.Row(c.Part("arrow")).Size(treelist.Disclosure, treelist.Icon).Shrink(0) - ui.Icon(c, runExecutionIcon(configuration.Execution)).Size(14, 14).Shrink(0).Color(a.colors.Subtle) - ui.Text(c, configuration.Name).Color(a.colors.Text).Ellipsis().Shrink(1).MinWidth(0) + icon, name := runExecutionIcon(configuration.Execution), a.colors.Text + if configuration.IsProcess() { + icon = runConfigTypeIcon(configuration.Provider) + } + if unavailable { + icon, name = icons.CircleAlert, a.colors.Subtle + } + ui.Icon(c, icon).Size(14, 14).Shrink(0).Color(a.colors.Subtle) + ui.Text(c, configuration.Name).Color(name).Ellipsis().Shrink(1).MinWidth(0) if b.pins[configuration.ID] { ui.Icon(c, icons.Pin).Size(12, 12).Shrink(0).Color(a.colors.Subtle) } @@ -188,7 +269,7 @@ func (a *App) drawRunConfigGroupArrow(c ui.C, s *runConfigState, group runConfig } // runConfigMenu declares the context menu of a configuration's row: run it or stop its run, -// edit its saved options, and pin or unpin it. +// edit it, delete one the user created, and pin or unpin it. func (a *App) runConfigMenu(c ui.C, row ui.Box, p *project, configuration core.RunConfiguration, running bool) { ui.ContextMenu(c, row, func(menu *ui.MenuItems) { language, id := a.language(), configuration.ID @@ -204,12 +285,21 @@ func (a *App) runConfigMenu(c ui.C, row ui.Box, p *project, configuration core.R }) } menu.Separator() - if menu.Item(i18n.Shared(language, "native.editConfiguration")).Clicked() { + if menu.Item(i18n.Shared(language, "native.editConfiguration")).Disabled(!runConfigEditable(configuration)).Clicked() { c.After(func() { a.performed("run.configuration.edit", surfaceContextMenu) - a.openRunConfigEditor(p, id) + a.editRunConfiguration(p, id) }) } + if configuration.UserDefined() { + if menu.Item(i18n.Shared(language, "desktop.runConfig.delete")).Destructive().Disabled(running).Clicked() { + name := configuration.Name + c.After(func() { + a.performed("run.configuration.delete", surfaceContextMenu) + p.runConfigs.deleting = &runConfigDeletion{id: id, name: name} + }) + } + } pin, action := i18n.Shared(language, "native.pinConfiguration"), "run.configuration.pin" if p.runConfigs.browser.pins[id] { pin, action = i18n.Shared(language, "native.unpinConfiguration"), "run.configuration.unpin" @@ -327,3 +417,41 @@ func (a *App) drawRunOptionField(c ui.C, language i18n.Language, field *runOptio ui.Wrap(c, text).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) } } + +// runConfigDeletion is the user configuration the delete confirmation asks about. +type runConfigDeletion struct { + id, name string +} + +// drawRunConfigDelete declares the confirmation of deleting a user configuration: deleted, it +// leaves the project or local file it was saved in. +func (a *App) drawRunConfigDelete(c ui.C, p *project) { + d := p.runConfigs.deleting + if d == nil { + return + } + language := a.language() + open := true + title := i18n.Shared(language, "desktop.runConfig.deleteTitle") + closed := ui.ModalWith(c, &open, title, ui.ModalSpec{Width: 420}, func() { + ui.Paragraph(c.Part("run-config-delete"), i18n.SharedFormat(language, "desktop.runConfig.deleteBody", map[string]string{"name": d.name}), 4).Color(a.colors.Text) + }, func() { + ui.Row(c.Part("run-config-delete-footer")).FillWidth().Items(ui.Center).Gap(8).Children(func() { + ui.Spacer(c) + if ui.Button(c, i18n.Shared(language, "desktop.git.cancel")).Outline().Clicked() { + c.After(func() { p.runConfigs.deleting = nil }) + } + if ui.Button(c, i18n.Shared(language, "desktop.runConfig.delete")).Destructive().Clicked() { + id := d.id + c.After(func() { + p.runConfigs.deleting = nil + a.performed("run.configuration.delete.confirm", surfaceButton) + a.deleteRunConfiguration(p, id) + }) + } + }) + }) + if closed { + c.After(func() { p.runConfigs.deleting = nil }) + } +} diff --git a/desktop/internal/workbench/title_run.go b/desktop/internal/workbench/title_run.go index a218f0f187..ef1a41bfdc 100644 --- a/desktop/internal/workbench/title_run.go +++ b/desktop/internal/workbench/title_run.go @@ -121,19 +121,27 @@ func (a *App) chooseTitleConfiguration(p *project, id string) { } // editRunConfigurations opens the Run window, which lists the configurations, and the editor -// of the one the title bar runs. Once the configurations are read and there is none, it says -// why instead: the Run window would show nothing, so the press looked like it did nothing. +// of the one the title bar runs. With none chosen it opens the editor of a new built-in run; +// before the built-in kinds are read it says why there is nothing to edit instead, so the +// press never looks like it did nothing. func (a *App) editRunConfigurations(p *project) { if p == nil { return } + configuration := p.titleConfiguration() + if configuration == nil && len(p.runConfigs.types) > 0 { + // Nothing to edit yet: the editor opens on a new configuration of the platform's + // first built-in kind, whose kind the user can still pick from New Configuration. + a.openRunConfigForm(p, p.runConfigs.types[0].Provider, "") + return + } if notice := p.noRunConfigurationsNotice(a.language()); notice != "" { a.notifyInfo(notice) return } a.openToolWindow(itemRun) - if configuration := p.titleConfiguration(); configuration != nil { - a.openRunConfigEditor(p, configuration.ID) + if configuration != nil && runConfigEditable(*configuration) { + a.editRunConfiguration(p, configuration.ID) } } @@ -207,9 +215,16 @@ func (a *App) decideTitleAction(p *project, action titleAction, trigger string) if configuration != nil { facts.Configuration = &core.TitleConfiguration{Kind: "unsupported"} var ok bool - if reference, ok = configuration.BuildReference(); ok { - index = p.buildInstanceIndex(reference) - facts.Configuration = p.titleConfigurationFacts(index, reference) + switch { + case configuration.Unavailable(): + facts.Configuration = &core.TitleConfiguration{Kind: "unavailable"} + case configuration.IsProcess(): + facts.Configuration = &core.TitleConfiguration{Kind: "process"} + default: + if reference, ok = configuration.BuildReference(); ok { + index = p.buildInstanceIndex(reference) + facts.Configuration = p.titleConfigurationFacts(index, reference) + } } } ctx, cancel := context.WithTimeout(p.ctx, kernelCallTimeout) @@ -229,6 +244,9 @@ func (a *App) decideTitleAction(p *project, action titleAction, trigger string) a.loadBuildModel(p, index) case "currentFile": a.performCurrentFileAction(p, action) + case "unavailable": + a.operationRejected("title_run", "unavailable") + a.notifyError(a.runConfigUnavailableText(*configuration)) case "unsupported": a.notifyInfo(i18n.SharedFormat(a.language(), "desktop.title.configurationNotStartable", map[string]string{"name": configuration.Name})) case "targetMissing": diff --git a/desktop/internal/workbench/title_run_test.go b/desktop/internal/workbench/title_run_test.go index 10a19799a7..c7fb1dbb2c 100644 --- a/desktop/internal/workbench/title_run_test.go +++ b/desktop/internal/workbench/title_run_test.go @@ -234,23 +234,46 @@ func emptyRunConfigHarness(t *testing.T, root string) (*harness, *project) { } // Edit Configuration on a project without configurations used to open a Run window that showed -// nothing, which looked like no reaction (#2028); it now says why the list is empty. -func TestEditRunConfigurationsWithoutAnyExplainsWhy(t *testing.T) { +// nothing, which looked like no reaction (#2028). It now opens the editor on a new +// configuration of the platform's first built-in kind; only while no kind is known does it +// say why the list is empty. +func TestEditRunConfigurationsWithoutAnyOpensANewConfiguration(t *testing.T) { h, p := emptyRunConfigHarness(t, runConfigRoot(t)) - h.app.post(func(a *App) { a.editRunConfigurations(p) }) + awaitStateWithin(t, h, 10*time.Second, "the built-in kinds", func() bool { return p.runConfigs.types != nil }) + kinds := p.runConfigs.types + h.app.post(func(a *App) { + p.runConfigs.types = []core.RunConfigurationType{} + a.editRunConfigurations(p) + }) h.settle() want := i18n.Shared(h.app.language(), "desktop.title.nothingToEdit") if got := lastNotice(h); got != want { t.Fatalf("notice = %q, want %q", got, want) } - if p.runConfigs.editor.open { - t.Fatal("an editor opened without a configuration") + if p.runConfigs.editor.open || p.runConfigs.form.open { + t.Fatal("an editor opened without a kind") + } + + h.app.post(func(a *App) { + p.runConfigs.types = kinds + a.editRunConfigurations(p) + }) + awaitStateWithin(t, h, 10*time.Second, "the new configuration's form", func() bool { + f := &p.runConfigs.form + return f.open && !f.loading && len(f.fields) > 0 + }) + if f := &p.runConfigs.form; f.provider != runProviderShell || f.id != "" { + t.Fatalf("form = provider %q id %q, want a new %s", f.provider, f.id, runProviderShell) + } + title := i18n.SharedFormat(h.app.language(), "desktop.runConfig.newTitle", map[string]string{"type": i18n.Shared(h.app.language(), "desktop.runConfig.typeShell")}) + if !h.shows(title) { + t.Fatalf("the form titled %q is not shown", title) } } // Saved configurations that no build plugin starts, such as the java.main entries an earlier -// version wrote into .lithe/run/local.json, stay out of the list; the explanation counts them -// instead of dropping them silently (#2028). +// version wrote into .lithe/run/local.json, stay out of the list; the explanation, shown while +// no built-in kind can be created, counts them instead of dropping them silently (#2028). func TestEditRunConfigurationsCountsTheConfigurationsNoBuildPluginStarts(t *testing.T) { root := runConfigRoot(t) local := map[string]any{"version": 2, "configurations": []any{ @@ -273,7 +296,10 @@ func TestEditRunConfigurationsCountsTheConfigurationsNoBuildPluginStarts(t *test if p.runConfigs.hidden != 2 { t.Fatalf("hidden = %d, want 2", p.runConfigs.hidden) } - h.app.post(func(a *App) { a.editRunConfigurations(p) }) + h.app.post(func(a *App) { + p.runConfigs.types = []core.RunConfigurationType{} + a.editRunConfigurations(p) + }) h.settle() language := h.app.language() want := i18n.SharedFormat(language, "desktop.title.nothingToEditHidden", map[string]string{"count": "2"}) diff --git a/desktop/internal/workbench/title_run_view.go b/desktop/internal/workbench/title_run_view.go index 1bf06615ac..db9edf99a5 100644 --- a/desktop/internal/workbench/title_run_view.go +++ b/desktop/internal/workbench/title_run_view.go @@ -1,6 +1,9 @@ package workbench import ( + "path" + "path/filepath" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/icons" "github.com/vivaui/viva/ui" @@ -53,7 +56,23 @@ func (a *App) titleRunConfigMenu(c ui.C, anchor ui.Box) { menu.Item(hiddenRunConfigurations(lang, s.hidden)).Disabled(true) } } + // A saved file Core did not read is named by its file name, which fits the menu, and + // opens in the editor so it can be fixed; a directory has nothing to open. + for _, ignored := range s.ignored { + label := i18n.SharedFormat(lang, "desktop.runConfig.documentIgnored", map[string]string{"file": path.Base(ignored)}) + item := menu.Item(label).Icon(icons.CircleAlert) + if path.Ext(ignored) == "" { + item.Disabled(true) + } else if item.Clicked() { + file := filepath.Join(p.root, filepath.FromSlash(ignored)) + c.After(func() { a.openFile(p, file) }) + } + } menu.Separator() + menu.Sub(i18n.Shared(lang, "desktop.runConfig.newConfiguration"), func(sub *ui.MenuItems) { + sub.WidthRange(runConfigMenuMin, runConfigMenuMax) + a.runConfigTypeItems(c, sub, p, surfaceToolbar) + }).Icon(icons.Plus) if menu.Item(i18n.Shared(lang, "native.editConfiguration")).Icon(icons.Pencil).Clicked() { c.After(func() { a.editRunConfigurations(p) }) } diff --git a/docs/assets/builtin-process-runs/README.md b/docs/assets/builtin-process-runs/README.md new file mode 100644 index 0000000000..87394a9cc4 --- /dev/null +++ b/docs/assets/builtin-process-runs/README.md @@ -0,0 +1,22 @@ +# 内置脚本与程序运行测试截图 + +这些截图是生产 Viva Page 的无头渲染,跑在 macOS 上,使用隔离的临时项目 ScriptDemo 和临时配置,没有安装任何插件。 +深色界面用中文,浅色界面用英文,窗口 1200×760。 +测试内核不带插件宿主,所以构建窗口和运行下拉会显示“此窗口无法使用构建插件。”; +截图同时说明,插件不可用时内置运行照常列出、照常运行。 +Shell 脚本在系统 shell 里真实运行,控制台内容是真实输出,日期来自测试的虚拟时钟。 +无头截图不代表 macOS/Windows 原生窗口验收。 + +| 场景 | 深色中文 | 浅色英文 | +| --- | --- | --- | +| 新建 Shell 脚本,执行方式为脚本文件。勾选了“存为项目文件”,填了脚本路径、脚本选项、项目内的工作目录和一个环境变量。解释器路径没填,显示的自动值取自脚本首行的 `#!/bin/bash` | [截图](builtin-run-shell-file-dark.png) | [截图](builtin-run-shell-file-light.png) | +| 同一配置换成脚本文本,出现多行文本框。文本没有首行 `#!`,解释器自动值变为 `/bin/sh` | [截图](builtin-run-shell-text-dark.png) | [截图](builtin-run-shell-text-light.png) | +| 点击对话框的运行后,配置写入 `.lithe/run/configurations.yaml`,Run 窗口自动打开并选中这次运行。控制台打印脚本输出,执行树以“进程已结束,退出码 0。”结束;标题栏改选 Greet | [截图](builtin-run-run-output-dark.png) | [截图](builtin-run-run-output-light.png) | +| 构建窗口的运行配置列表:Greet 在“脚本与程序”组下,“+”菜单列出 macOS 提供的三类内置运行,没有 cmd 批处理 | [截图](builtin-run-new-menu-dark.png) | [截图](builtin-run-new-menu-light.png) | +| 新建 PowerShell 脚本:macOS 上的解释器自动值是 pwsh,解释器选项自动值是 `-NoLogo -NoProfile`。“绕过执行策略(-ExecutionPolicy Bypass)”默认勾选,ⓘ 说明只在 Windows 生效 | [截图](builtin-run-powershell-dark.png) | [截图](builtin-run-powershell-light.png) | +| 新建可执行程序:程序路径、程序参数(含带引号的空格参数)、工作目录和环境变量 | [截图](builtin-run-executable-dark.png) | [截图](builtin-run-executable-light.png) | +| 一个插件的运行配置文件 `.lithe/run/plugin/dev.example.engine.toml` 写坏后,标题栏运行下拉仍列出 Greet,并多出一项“未读取 dev.example.engine.toml 中的运行配置”,点击在编辑器中打开该文件 | [截图](builtin-run-run-menu-dark.png) | [截图](builtin-run-run-menu-light.png) | + +复验:设置 `LITHE_VISUAL_OUTPUT_DIR`,运行 `scripts/desktop/desktop-go.sh test +-tags 'vivahead lithevisual' ./internal/workbench -run '^TestVisualBuiltInProcessRuns$' +-count=1 -timeout 180s` 生成。 diff --git a/docs/assets/builtin-process-runs/builtin-run-executable-dark.png b/docs/assets/builtin-process-runs/builtin-run-executable-dark.png new file mode 100644 index 0000000000..5310edc923 Binary files /dev/null and b/docs/assets/builtin-process-runs/builtin-run-executable-dark.png differ diff --git a/docs/assets/builtin-process-runs/builtin-run-executable-light.png b/docs/assets/builtin-process-runs/builtin-run-executable-light.png new file mode 100644 index 0000000000..0da09b79c5 Binary files /dev/null and b/docs/assets/builtin-process-runs/builtin-run-executable-light.png differ diff --git a/docs/assets/builtin-process-runs/builtin-run-new-menu-dark.png b/docs/assets/builtin-process-runs/builtin-run-new-menu-dark.png new file mode 100644 index 0000000000..b8ec008491 Binary files /dev/null and b/docs/assets/builtin-process-runs/builtin-run-new-menu-dark.png differ diff --git a/docs/assets/builtin-process-runs/builtin-run-new-menu-light.png b/docs/assets/builtin-process-runs/builtin-run-new-menu-light.png new file mode 100644 index 0000000000..900bbc4acb Binary files /dev/null and b/docs/assets/builtin-process-runs/builtin-run-new-menu-light.png differ diff --git a/docs/assets/builtin-process-runs/builtin-run-powershell-dark.png b/docs/assets/builtin-process-runs/builtin-run-powershell-dark.png new file mode 100644 index 0000000000..84d0468e9a Binary files /dev/null and b/docs/assets/builtin-process-runs/builtin-run-powershell-dark.png differ diff --git a/docs/assets/builtin-process-runs/builtin-run-powershell-light.png b/docs/assets/builtin-process-runs/builtin-run-powershell-light.png new file mode 100644 index 0000000000..15c87abf6d Binary files /dev/null and b/docs/assets/builtin-process-runs/builtin-run-powershell-light.png differ diff --git a/docs/assets/builtin-process-runs/builtin-run-run-menu-dark.png b/docs/assets/builtin-process-runs/builtin-run-run-menu-dark.png new file mode 100644 index 0000000000..434bd89af2 Binary files /dev/null and b/docs/assets/builtin-process-runs/builtin-run-run-menu-dark.png differ diff --git a/docs/assets/builtin-process-runs/builtin-run-run-menu-light.png b/docs/assets/builtin-process-runs/builtin-run-run-menu-light.png new file mode 100644 index 0000000000..2264824df0 Binary files /dev/null and b/docs/assets/builtin-process-runs/builtin-run-run-menu-light.png differ diff --git a/docs/assets/builtin-process-runs/builtin-run-run-output-dark.png b/docs/assets/builtin-process-runs/builtin-run-run-output-dark.png new file mode 100644 index 0000000000..bc5dd59523 Binary files /dev/null and b/docs/assets/builtin-process-runs/builtin-run-run-output-dark.png differ diff --git a/docs/assets/builtin-process-runs/builtin-run-run-output-light.png b/docs/assets/builtin-process-runs/builtin-run-run-output-light.png new file mode 100644 index 0000000000..0b695eaaa1 Binary files /dev/null and b/docs/assets/builtin-process-runs/builtin-run-run-output-light.png differ diff --git a/docs/assets/builtin-process-runs/builtin-run-shell-file-dark.png b/docs/assets/builtin-process-runs/builtin-run-shell-file-dark.png new file mode 100644 index 0000000000..5435eec5ad Binary files /dev/null and b/docs/assets/builtin-process-runs/builtin-run-shell-file-dark.png differ diff --git a/docs/assets/builtin-process-runs/builtin-run-shell-file-light.png b/docs/assets/builtin-process-runs/builtin-run-shell-file-light.png new file mode 100644 index 0000000000..923d33e8e7 Binary files /dev/null and b/docs/assets/builtin-process-runs/builtin-run-shell-file-light.png differ diff --git a/docs/assets/builtin-process-runs/builtin-run-shell-text-dark.png b/docs/assets/builtin-process-runs/builtin-run-shell-text-dark.png new file mode 100644 index 0000000000..c93a0f4340 Binary files /dev/null and b/docs/assets/builtin-process-runs/builtin-run-shell-text-dark.png differ diff --git a/docs/assets/builtin-process-runs/builtin-run-shell-text-light.png b/docs/assets/builtin-process-runs/builtin-run-shell-text-light.png new file mode 100644 index 0000000000..7bb122f286 Binary files /dev/null and b/docs/assets/builtin-process-runs/builtin-run-shell-text-light.png differ diff --git a/docs/viva-migration.md b/docs/viva-migration.md index e28b465f87..f148e5fdce 100644 --- a/docs/viva-migration.md +++ b/docs/viva-migration.md @@ -562,7 +562,7 @@ MCP 管理随 Agent 对话失去消费者后,本轮整块删除,后续重新 | 未保存文档恢复 | 专用恢复存储未找到 | 未找到(`buffer.store.ts` 仅内存/localStorage 处理,未定位具体键) | — | 未找到 | 在新客户端设计恢复记录;不能丢旧未保存正文,但旧侧没有可迁移文件 | | 本地历史 | `Application Support/Lithe/LocalHistory`(`MacLocalHistoryAdapters.swift`,Rust Core 存取) | 未找到(`shelf_storage.rs` 的 `app_data_dir/git-shelves/<身份>` 是 Git Shelf,不是本地历史) | `RustLocalHistoryOperations.swift` | 未找到 | 保留旧目录只读,Viva 实现本地历史后按工作区相对身份导入 | | Git Shelf | `Application Support/Lithe/` 下版本化 JSON(`ShelveService.swift`) | `%APPDATA%\app.lithe.windows\git-shelves\<身份>` | 同左;Windows `shelf_storage.rs` | 未找到 | 随 Shelf 功能迁移 | -| 运行配置 / 工具链 | 工作区内 `.lithe/run/configurations.json`、`.lithe/run/local.json`、`.lithe/toolchains/local.json`;macOS 另有 UserDefaults 键 `buildSystemPluginID`、`buildSystemID` | 同工作区文件 | Rust Core `execution/configuration.rs`;macOS `MacRunConfigurationStore.swift` | 工作区文件无需迁移;Viva 的 `toolchain/pins.go` 写 `.lithe/toolchains/local.json`;运行配置编辑入口未找到 | 工作区文件两端共用,不动;UserDefaults 键只在需要时转为新偏好 | +| 运行配置 / 工具链 | 工作区内 `.lithe/run/configurations.json`、`.lithe/run/local.json`(Viva 改存 `.lithe/run/configurations.yaml`、`local.yaml` 与插件运行的 `.lithe/run/plugin/<插件>.toml`、`<插件>.local.toml`;没有对应 YAML 时仍读取旧 JSON,第一次编辑该层时写 YAML 并删除 JSON)、`.lithe/toolchains/local.json`;macOS 另有 UserDefaults 键 `buildSystemPluginID`、`buildSystemID` | 同工作区文件 | Rust Core `execution/configuration.rs`;macOS `MacRunConfigurationStore.swift` | 工作区文件无需迁移;Viva 的 `toolchain/pins.go` 写 `.lithe/toolchains/local.json`;运行配置由 Run 窗口与标题栏的“编辑运行配置…”编辑(`workbench/runconfig_edit.go`、`runconfig_form.go`) | 工具链文件两端共用,不动。Viva 第一次编辑某一层运行配置后,该层的旧 JSON 被删除,旧客户端(已停更)就读不到这一层;UserDefaults 键只在需要时转为新偏好 | | 日志目录 | `~/Library/Logs/Lithe`(Dev 多一层 `app.lithe.desktop.dev/`);自定义目录偏好存于旧偏好 | `%LOCALAPPDATA%\app.lithe.windows\logs`;自定义目录在 `%APPDATA%\app.lithe.windows\lithe-log-settings.json` | macOS `MacLogDirectoryProvider.swift`;Windows `logging.rs` | macOS `~/Library/Logs/Lithe Desktop`;Windows `%LOCALAPPDATA%\Lithe Desktop\Logs`;目录偏好 `Lithe Desktop/logging.json`(`logstore/`) | 日志不迁移;自定义目录也不导入:旧客户端仍在使用该目录,共用会混写两个产品的日志,用户可在日志窗口另选 | | Windows WebView 缓存 | — | `%LOCALAPPDATA%\app.lithe.windows\EBWebView\`(含 localStorage leveldb) | `profile_migration.rs` 已有读取 `EBWebView/Default/Local Storage/leveldb` 的先例 | 不适用 | 迁移期间需关闭旧应用后只读快照;上表标注 localStorage 的项目都经此读取 | diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index ef20502b79..44cca052a5 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -27,6 +27,15 @@ native_path() { fi } +# Lithe-core-rust branch feat/builtin-process-runs at 7381e79 (Draft #85, on top of main at +# 10da502, #84): built-in process runs. runConfig.configurationTypes, runConfig.editorForm, +# runConfig.saveConfiguration and runConfig.deleteConfiguration list, edit, save and delete the +# shell script, PowerShell, cmd and executable runs without any plugin, and +# runConfig.createLaunchPlan plans them with a script saved as text; built-in runs are stored in +# .lithe/run/configurations.yaml and local.yaml, and a plugin's runs in +# .lithe/run/plugin/.toml and .local.toml with the plugin's repository and +# version; runConfig.resolve lists the saved runs of a project nothing was generated for (#2100). +# Switch to main's commit once #85 is squash-merged. # Lithe-core-rust main at 885f2a6, #83 squash-merged (the same tree as its branch at d10ee76, on # top of cf2f260): a plugin's TextMate grammar may declare injections, an object of scope selectors # each with a rule, which the editor tries beside the current rule's patterns wherever the selector @@ -199,7 +208,7 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # the contract, plugin guides, reference and SDKs live only in shared/plugins; on top of #16 (reported Git queries folded in the console), # #15 (git.write cherryPick, revert and reset fields), #14 (word-level changed ranges of diff # rows), #13, #8, #7, #6 and #4. -PINNED_CORE_REVISION="885f2a6958a9e475c88c5fb39d48068f41b08ae1" +PINNED_CORE_REVISION="7381e79a7705e9741ed3ff76c459c7a762484783" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in diff --git a/shared/i18n/locales/en-US.json b/shared/i18n/locales/en-US.json index bf5cc6d25a..265d772323 100644 --- a/shared/i18n/locales/en-US.json +++ b/shared/i18n/locales/en-US.json @@ -1395,8 +1395,8 @@ "desktop.runConfig.run": "Run", "desktop.runConfig.saveFailed": "Could not save: {reason}", "desktop.runConfig.scope": "Save to", - "desktop.runConfig.scopeLocal": "This machine (.lithe/run/local.json)", - "desktop.runConfig.scopeProject": "Project, shared (.lithe/run/configurations.json)", + "desktop.runConfig.scopeLocal": "This machine (.lithe/run/local.yaml)", + "desktop.runConfig.scopeProject": "Project, shared (.lithe/run/configurations.yaml)", "desktop.runConfig.workingDirectory": "Working directory", "desktop.runConfig.workingDirectoryPlaceholder": "Path inside the workspace; empty uses the default", "desktop.search.fileMaskPlaceholder": "File mask, e.g. *.java, *.kt", @@ -11441,7 +11441,63 @@ "desktop.sourceSettings.modules": "Modules", "desktop.toolchains.global": "Global defaults", "desktop.toolchains.globalHelp": "Manage detected and manually added SDKs for all projects. Save writes to the application’s user settings; projects can override the default. Existing processes use the new SDK after restarting.", - "desktop.toolchains.project": "Current project" + "desktop.toolchains.project": "Current project", + "desktop.runConfig.typeShell": "Shell Script", + "desktop.runConfig.typePowerShell": "PowerShell Script", + "desktop.runConfig.typeBatch": "Batch Script (cmd)", + "desktop.runConfig.typeExecutable": "Program", + "desktop.runConfig.builtInGroup": "Scripts and Programs", + "desktop.runConfig.newConfiguration": "New Configuration", + "desktop.runConfig.emptyHint": "No run configurations yet. Click + to add a script or program run.", + "desktop.runConfig.newTitle": "New {type} Configuration", + "desktop.runConfig.fieldName": "Name", + "desktop.runConfig.fieldStoreAsProjectFile": "Store as project file", + "desktop.runConfig.storeAsProjectFileHelp": "Checked, the configuration is saved in .lithe/run/configurations.yaml and can be committed with the project; unchecked, it stays on this machine in .lithe/run/local.yaml.", + "desktop.runConfig.fieldSource": "Execute", + "desktop.runConfig.sourceFile": "Script file", + "desktop.runConfig.sourceText": "Script text", + "desktop.runConfig.fieldScript": "Script path", + "desktop.runConfig.fieldText": "Script text", + "desktop.runConfig.fieldScriptOptions": "Script options", + "desktop.runConfig.fieldInterpreter": "Interpreter path", + "desktop.runConfig.interpreterHelp": "Left empty, the automatic interpreter shown in brackets is used. You can also enter a command name, found on PATH, or the path of an executable.", + "desktop.runConfig.fieldInterpreterArguments": "Interpreter options", + "desktop.runConfig.fieldExecutionPolicyBypass": "Bypass execution policy (-ExecutionPolicy Bypass)", + "desktop.runConfig.noteWindowsOnly": "Takes effect on Windows only; other systems ignore it.", + "desktop.runConfig.fieldProgram": "Program path", + "desktop.runConfig.automaticValue": "Automatic ({value})", + "desktop.runConfig.browse": "Browse…", + "desktop.runConfig.variableName": "Name", + "desktop.runConfig.variableValue": "Value", + "desktop.runConfig.variableAdd": "Add variable", + "desktop.runConfig.variableRemove": "Remove variable", + "desktop.runConfig.apply": "Apply", + "desktop.runConfig.ok": "OK", + "desktop.runConfig.errorRequired": "Required", + "desktop.runConfig.errorConflict": "Choose either a script file or script text", + "desktop.runConfig.errorNotAllowed": "Not allowed for this kind of configuration", + "desktop.runConfig.errorTooLong": "Too long", + "desktop.runConfig.errorInvalidCharacter": "Contains a character that is not allowed", + "desktop.runConfig.errorInvalidPath": "Invalid path", + "desktop.runConfig.errorNotFound": "File or folder not found", + "desktop.runConfig.errorOutsideProject": "The working directory must be inside the project", + "desktop.runConfig.errorInvalidName": "Invalid variable name", + "desktop.runConfig.errorDuplicate": "Duplicate variable name", + "desktop.runConfig.errorOther": "Invalid value ({code})", + "desktop.runConfig.formTooNew": "Editing this run configuration needs a newer version of Lithe.", + "desktop.runConfig.programNotFound": "“{program}” was not found on PATH. Enter the full path of the interpreter or program.", + "desktop.runConfig.documentIgnored": "Not read: {file}", + "desktop.runConfig.deleteTitle": "Delete Run Configuration", + "desktop.runConfig.deleteBody": "Delete “{name}”? It is removed from the run configuration file it is saved in.", + "desktop.runConfig.delete": "Delete", + "desktop.runConfig.deleteFailed": "Could not delete the run configuration: {reason}", + "desktop.runConfig.chooseFailed": "Could not open the file chooser.", + "desktop.runConfig.unavailablePluginMissing": "Needs the plugin “{plugin}”, which is not installed or not enabled.", + "desktop.runConfig.unavailableRepositoryMismatch": "The installed “{plugin}” is not the plugin from {repository} the configuration records.", + "desktop.runConfig.unavailableVersionUnsupported": "The installed “{plugin}” does not meet the version requirement {requirement}.", + "desktop.runConfig.unavailableMissingDirectory": "The working directory “{directory}” no longer exists. Edit the configuration to change it.", + "desktop.runConfig.unavailableInvalid": "The run configuration is invalid: {reason}", + "desktop.runConfig.unavailableOther": "This run configuration cannot run now: {reason}" }, "overrides": { "windows": { diff --git a/shared/i18n/locales/zh-CN.json b/shared/i18n/locales/zh-CN.json index 82517619ca..fad05d54fc 100644 --- a/shared/i18n/locales/zh-CN.json +++ b/shared/i18n/locales/zh-CN.json @@ -1395,8 +1395,8 @@ "desktop.runConfig.run": "运行", "desktop.runConfig.saveFailed": "保存失败:{reason}", "desktop.runConfig.scope": "保存到", - "desktop.runConfig.scopeLocal": "仅本机(.lithe/run/local.json)", - "desktop.runConfig.scopeProject": "项目共享(.lithe/run/configurations.json)", + "desktop.runConfig.scopeLocal": "仅本机(.lithe/run/local.yaml)", + "desktop.runConfig.scopeProject": "项目共享(.lithe/run/configurations.yaml)", "desktop.runConfig.workingDirectory": "工作目录", "desktop.runConfig.workingDirectoryPlaceholder": "工作区内的路径;留空使用默认目录", "desktop.search.fileMaskPlaceholder": "文件掩码,例如 *.java、*.kt", @@ -11441,7 +11441,63 @@ "desktop.sourceSettings.modules": "模块", "desktop.toolchains.global": "全局默认", "desktop.toolchains.globalHelp": "统一管理自动识别和手动添加的 SDK,保存到应用的用户设置。项目可单独覆盖默认版本;已启动的进程需重启后使用新版本。", - "desktop.toolchains.project": "当前项目" + "desktop.toolchains.project": "当前项目", + "desktop.runConfig.typeShell": "Shell 脚本", + "desktop.runConfig.typePowerShell": "PowerShell 脚本", + "desktop.runConfig.typeBatch": "批处理脚本(cmd)", + "desktop.runConfig.typeExecutable": "程序", + "desktop.runConfig.builtInGroup": "脚本与程序", + "desktop.runConfig.newConfiguration": "新建运行配置", + "desktop.runConfig.emptyHint": "还没有运行配置,点 + 新建脚本或程序运行", + "desktop.runConfig.newTitle": "新建{type}运行配置", + "desktop.runConfig.fieldName": "名称", + "desktop.runConfig.fieldStoreAsProjectFile": "存为项目文件", + "desktop.runConfig.storeAsProjectFileHelp": "勾选后保存到 .lithe/run/configurations.yaml,可随项目提交共享;不勾选则只保存在本机的 .lithe/run/local.yaml。", + "desktop.runConfig.fieldSource": "执行", + "desktop.runConfig.sourceFile": "脚本文件", + "desktop.runConfig.sourceText": "脚本文本", + "desktop.runConfig.fieldScript": "脚本路径", + "desktop.runConfig.fieldText": "脚本文本", + "desktop.runConfig.fieldScriptOptions": "脚本选项", + "desktop.runConfig.fieldInterpreter": "解释器路径", + "desktop.runConfig.interpreterHelp": "留空时使用括号里显示的自动解释器;也可以填命令名(按 PATH 查找)或可执行文件路径。", + "desktop.runConfig.fieldInterpreterArguments": "解释器选项", + "desktop.runConfig.fieldExecutionPolicyBypass": "绕过执行策略(-ExecutionPolicy Bypass)", + "desktop.runConfig.noteWindowsOnly": "只在 Windows 上生效,其他系统会忽略。", + "desktop.runConfig.fieldProgram": "程序路径", + "desktop.runConfig.automaticValue": "自动({value})", + "desktop.runConfig.browse": "选择…", + "desktop.runConfig.variableName": "变量名", + "desktop.runConfig.variableValue": "值", + "desktop.runConfig.variableAdd": "添加变量", + "desktop.runConfig.variableRemove": "删除变量", + "desktop.runConfig.apply": "应用", + "desktop.runConfig.ok": "确定", + "desktop.runConfig.errorRequired": "必填", + "desktop.runConfig.errorConflict": "脚本文件和脚本文本只能选一个", + "desktop.runConfig.errorNotAllowed": "这种运行配置不能使用此项", + "desktop.runConfig.errorTooLong": "内容太长", + "desktop.runConfig.errorInvalidCharacter": "包含不允许的字符", + "desktop.runConfig.errorInvalidPath": "路径无效", + "desktop.runConfig.errorNotFound": "找不到该文件或文件夹", + "desktop.runConfig.errorOutsideProject": "工作目录必须在项目内", + "desktop.runConfig.errorInvalidName": "变量名无效", + "desktop.runConfig.errorDuplicate": "变量名重复", + "desktop.runConfig.errorOther": "值无效({code})", + "desktop.runConfig.formTooNew": "这个运行配置需要更新版本的 Lithe 才能编辑。", + "desktop.runConfig.programNotFound": "在 PATH 中找不到“{program}”,请填写解释器或程序的完整路径。", + "desktop.runConfig.documentIgnored": "未读取 {file} 中的运行配置", + "desktop.runConfig.deleteTitle": "删除运行配置", + "desktop.runConfig.deleteBody": "确定删除“{name}”吗?它会从保存它的运行配置文件中移除。", + "desktop.runConfig.delete": "删除", + "desktop.runConfig.deleteFailed": "无法删除运行配置:{reason}", + "desktop.runConfig.chooseFailed": "无法打开文件选择器。", + "desktop.runConfig.unavailablePluginMissing": "需要插件“{plugin}”,但它没有安装或没有启用。", + "desktop.runConfig.unavailableRepositoryMismatch": "已安装的“{plugin}”不是配置记录的仓库 {repository} 发布的插件。", + "desktop.runConfig.unavailableVersionUnsupported": "已安装的“{plugin}”版本不满足要求 {requirement}。", + "desktop.runConfig.unavailableMissingDirectory": "工作目录“{directory}”不存在了,请编辑配置修改它。", + "desktop.runConfig.unavailableInvalid": "运行配置无效:{reason}", + "desktop.runConfig.unavailableOther": "此运行配置现在无法运行:{reason}" }, "overrides": { "macos": { diff --git a/shared/i18n/messages.json b/shared/i18n/messages.json index 3b3f3fbbce..4c970e341b 100644 --- a/shared/i18n/messages.json +++ b/shared/i18n/messages.json @@ -15490,6 +15490,439 @@ "desktop" ] }, + { + "id": "desktop.runConfig.typeShell", + "description": "Name of the built-in run configuration kind that runs a shell script.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.typePowerShell", + "description": "Name of the built-in run configuration kind that runs a PowerShell script.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.typeBatch", + "description": "Name of the built-in run configuration kind that runs a Windows batch (cmd) script.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.typeExecutable", + "description": "Name of the built-in run configuration kind that runs a program file.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.builtInGroup", + "description": "Title of the run configuration list group that holds the built-in script and program runs.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.newConfiguration", + "description": "Button and menu item that creates a new run configuration; its menu lists the built-in kinds.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.emptyHint", + "description": "Line under the run configuration list header when the project has no run configuration yet.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.newTitle", + "description": "Title of the editor dialog of a new built-in run configuration; type is the kind's name.", + "platforms": [ + "desktop" + ], + "parameters": { + "type": "string" + } + }, + { + "id": "desktop.runConfig.fieldName", + "description": "Label of the name field of a built-in run configuration.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.fieldStoreAsProjectFile", + "description": "Checkbox that saves a run configuration in the project's shared file instead of on this machine only.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.storeAsProjectFileHelp", + "description": "Tooltip of the store as project file checkbox: where the configuration is saved either way.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.fieldSource", + "description": "Label of the choice between running a script file and running script text.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.sourceFile", + "description": "Option of the script source choice: run a script file.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.sourceText", + "description": "Option of the script source choice: run script text typed in the editor.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.fieldScript", + "description": "Label of the script file path field of a script run configuration.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.fieldText", + "description": "Label of the script text field of a script run configuration.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.fieldScriptOptions", + "description": "Label of the field of the arguments passed to the script.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.fieldInterpreter", + "description": "Label of the interpreter path field of a script run configuration.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.interpreterHelp", + "description": "Tooltip of the interpreter path field: an empty field uses the automatic interpreter shown.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.fieldInterpreterArguments", + "description": "Label of the field of the options passed to the interpreter before the script.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.fieldExecutionPolicyBypass", + "description": "Checkbox of a PowerShell run that passes -ExecutionPolicy Bypass.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.noteWindowsOnly", + "description": "Tooltip of an option that only takes effect on Windows.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.fieldProgram", + "description": "Label of the program path field of a program run configuration.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.automaticValue", + "description": "Placeholder of an empty field that uses an automatic value; value is that value.", + "platforms": [ + "desktop" + ], + "parameters": { + "value": "string" + } + }, + { + "id": "desktop.runConfig.browse", + "description": "Button inside a path field that opens a file or folder chooser.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.variableName", + "description": "Placeholder of the name field of an environment variable row.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.variableValue", + "description": "Placeholder of the value field of an environment variable row.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.variableAdd", + "description": "Button that adds an environment variable row.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.variableRemove", + "description": "Button that removes an environment variable row.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.apply", + "description": "Button of the run configuration editor that saves without closing it.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.ok", + "description": "Button of the run configuration editor that saves and closes it.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.errorRequired", + "description": "Error under a required run configuration field left empty.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.errorConflict", + "description": "Error under the script source choice when both a script file and script text are set.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.errorNotAllowed", + "description": "Error under a run configuration field this kind or platform does not allow.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.errorTooLong", + "description": "Error under a run configuration field whose value is too long.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.errorInvalidCharacter", + "description": "Error under a run configuration field holding a character it cannot hold, such as a line break.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.errorInvalidPath", + "description": "Error under a run configuration path field that is not a valid path.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.errorNotFound", + "description": "Error under a run configuration path field whose file or folder does not exist.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.errorOutsideProject", + "description": "Error under the working directory field when it is outside the project.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.errorInvalidName", + "description": "Error under the environment variables when a variable name is not valid.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.errorDuplicate", + "description": "Error under the environment variables when two variables have the same name.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.errorOther", + "description": "Error under a run configuration field for a reason this version does not know; code is Core's code.", + "platforms": [ + "desktop" + ], + "parameters": { + "code": "string" + } + }, + { + "id": "desktop.runConfig.formTooNew", + "description": "Shown in the run configuration editor when Core describes the form in a newer version than this app understands.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.programNotFound", + "description": "Run failure when the program or interpreter of a run is on no PATH directory; program is its name.", + "platforms": [ + "desktop" + ], + "parameters": { + "program": "string" + } + }, + { + "id": "desktop.runConfig.documentIgnored", + "description": "Item of the run configuration menu for a saved run configuration file that was not read, such as a plugin's TOML file that cannot be parsed; clicking it opens the file. file is the file's name.", + "platforms": [ + "desktop" + ], + "parameters": { + "file": "string" + } + }, + { + "id": "desktop.runConfig.deleteTitle", + "description": "Title of the dialog that confirms deleting a run configuration.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.deleteBody", + "description": "Body of the dialog that confirms deleting a run configuration; name is its name.", + "platforms": [ + "desktop" + ], + "parameters": { + "name": "string" + } + }, + { + "id": "desktop.runConfig.delete", + "description": "Menu item and button that delete a run configuration.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.deleteFailed", + "description": "Notification when deleting a run configuration fails; reason is the error.", + "platforms": [ + "desktop" + ], + "parameters": { + "reason": "string" + } + }, + { + "id": "desktop.runConfig.chooseFailed", + "description": "Notification when the file or folder chooser of a run configuration field could not open.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.unavailablePluginMissing", + "description": "Why a saved run configuration cannot run: the plugin it needs is not installed or enabled; plugin is its name.", + "platforms": [ + "desktop" + ], + "parameters": { + "plugin": "string" + } + }, + { + "id": "desktop.runConfig.unavailableRepositoryMismatch", + "description": "Why a saved run configuration cannot run: the installed plugin with its ID comes from another repository; plugin is its name, repository the recorded one.", + "platforms": [ + "desktop" + ], + "parameters": { + "plugin": "string", + "repository": "string" + } + }, + { + "id": "desktop.runConfig.unavailableVersionUnsupported", + "description": "Why a saved run configuration cannot run: the installed plugin version does not meet its requirement; plugin is its name, requirement the version range.", + "platforms": [ + "desktop" + ], + "parameters": { + "plugin": "string", + "requirement": "string" + } + }, + { + "id": "desktop.runConfig.unavailableMissingDirectory", + "description": "Why a saved run configuration cannot run: its working directory no longer exists; directory is the saved path.", + "platforms": [ + "desktop" + ], + "parameters": { + "directory": "string" + } + }, + { + "id": "desktop.runConfig.unavailableInvalid", + "description": "Why a saved run configuration cannot run: its saved values are invalid; reason is Core's detail.", + "platforms": [ + "desktop" + ], + "parameters": { + "reason": "string" + } + }, + { + "id": "desktop.runConfig.unavailableOther", + "description": "Why a saved run configuration cannot run, for a reason this version does not know; reason is Core's detail.", + "platforms": [ + "desktop" + ], + "parameters": { + "reason": "string" + } + }, { "id": "desktop.search.collapseFile", "description": "Find in Files result: collapse an expanded file row", diff --git a/shared/platform-feature-matrix/features/builtin-process-runs.json b/shared/platform-feature-matrix/features/builtin-process-runs.json new file mode 100644 index 0000000000..00e0aa6e9c --- /dev/null +++ b/shared/platform-feature-matrix/features/builtin-process-runs.json @@ -0,0 +1,57 @@ +{ + "id": "builtin-process-runs", + "area": "运行与调试", + "group": "运行配置", + "capability": "内置脚本与程序运行:不装任何插件也能新建、编辑、删除并运行 Shell 脚本、PowerShell 脚本、cmd 批处理(只在 Windows 列出)和可执行程序四类运行配置;编辑对话框参照 IDEA 的 Shell Script 配置,有名称、“存为项目文件”、脚本文件或脚本文本、脚本选项、工作目录、环境变量、解释器路径、解释器选项(留空时显示自动值:Shell 按脚本首行 #! 选解释器,没有时 macOS/Linux 用 /bin/sh、Windows 用 bash;PowerShell 用 Windows 的 powershell 或 pwsh;cmd 用 cmd /d),PowerShell 的“绕过执行策略”默认勾选、只在 Windows 生效;底部有运行、取消、应用、确定;可执行程序有程序路径、参数、工作目录和环境变量。字段、默认值、显示条件和校验错误全部来自 Core(runConfig.configurationTypes、runConfig.editorForm),新增字段不改宿主绘制代码。存为项目文件时写 .lithe/run/configurations.yaml,否则写 .lithe/run/local.yaml;插件运行另存 .lithe/run/plugin/<插件>.toml 与 <插件>.local.toml,并记下插件的作者/仓库、版本、版本要求、插件 API 版本和所需能力;旧版 configurations.json、local.json 在没有对应 YAML 时仍读取,第一次编辑该层时改写为 YAML 并删除 JSON。编辑对话框的“运行”、构建窗口的运行配置列表、标题栏的运行按钮和 Run 窗口的再次运行都能启动,启动时 Run 窗口自动打开并选中这次运行,输出进入它的控制台,以“进程已结束,退出码 N。”结束;脚本文本写到系统临时目录(不写安装目录),运行结束后删除。插件出错、未装或项目尚未加载构建模型时,内置运行照常列出和运行;某个运行配置文件没有读取(插件 TOML 写坏、同一配置存了两次、旧版 JSON 已被 YAML 取代)时,标题栏运行下拉按文件名列出它,点击在编辑器中打开", + "macos": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/core/run_config.go", + "desktop/internal/core/run_process.go", + "desktop/internal/core/run_config_test.go", + "desktop/internal/buildprocess/process.go", + "desktop/internal/buildprocess/process_unix.go", + "desktop/internal/buildprocess/process_unix_test.go", + "desktop/internal/workbench/runconfig.go", + "desktop/internal/workbench/runconfig_browser.go", + "desktop/internal/workbench/runconfig_changes.go", + "desktop/internal/workbench/runconfig_edit.go", + "desktop/internal/workbench/runconfig_form.go", + "desktop/internal/workbench/runconfig_form_view.go", + "desktop/internal/workbench/runconfig_process.go", + "desktop/internal/workbench/runconfig_process_test.go", + "desktop/internal/workbench/runconfig_edit_test.go", + "desktop/internal/workbench/runconfig_process_visual_test.go", + "desktop/internal/workbench/title_run.go", + "desktop/internal/workbench/title_run_test.go", + "docs/assets/builtin-process-runs/README.md" + ] + }, + "windows": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/core/run_config.go", + "desktop/internal/core/run_process.go", + "desktop/internal/core/run_config_test.go", + "desktop/internal/buildprocess/process.go", + "desktop/internal/buildprocess/process_windows.go", + "desktop/internal/buildprocess/batch_windows_test.go", + "desktop/internal/workbench/runconfig.go", + "desktop/internal/workbench/runconfig_browser.go", + "desktop/internal/workbench/runconfig_changes.go", + "desktop/internal/workbench/runconfig_edit.go", + "desktop/internal/workbench/runconfig_form.go", + "desktop/internal/workbench/runconfig_form_view.go", + "desktop/internal/workbench/runconfig_process.go", + "desktop/internal/workbench/runconfig_process_test.go", + "desktop/internal/workbench/runconfig_edit_test.go", + "desktop/internal/workbench/title_run.go", + "desktop/internal/workbench/title_run_test.go" + ] + }, + "owner": "Run", + "verification": "不装任何插件打开一个空文件夹:标题栏“编辑运行配置…”直接打开新建表单;新建 Shell 脚本,选“脚本文本”写 echo hello,勾选“存为项目文件”后点运行,确认 .lithe/run/configurations.yaml 出现该配置、Run 窗口控制台输出 hello 并以“进程已结束,退出码 0。”结束、系统临时目录没有残留的 lithe-run-script-*;标题栏运行按钮再次运行同一配置。改为脚本文件(项目内的 .sh,带与不带 #! 首行各一次)、填脚本选项、工作目录和环境变量,确认解释器自动值随首行变化,保存后重开回显一致;取消勾选“存为项目文件”后配置移到 .lithe/run/local.yaml。新建可执行程序运行项目内程序与 PATH 上的程序;程序不存在、工作目录出项目或不存在时运行前提示原因。macOS/Linux 的类型列表没有 cmd;Windows 上分别运行 .ps1(默认带 -ExecutionPolicy Bypass,取消勾选后不带)、.cmd/.bat(含空格与引号参数)和 .exe。放一份旧版 .lithe/run/configurations.json,确认仍列出,编辑一次后改写为 YAML 并删除 JSON。让一个插件的 TOML 文件写坏,确认内置运行仍列出可运行,运行下拉出现“未读取 <文件名> 中的运行配置”,点击后在编辑器打开该文件。自动化覆盖:runconfig_process_test.go 的端到端测试用真实 Core 和系统 shell(Windows 为 cmd)新建、保存、运行(确认 Run 窗口打开并选中这次运行)并从标题栏再运行;runconfig_process_visual_test.go 生成 docs/assets/builtin-process-runs 的无头截图;单元测试覆盖 PATH 查找跳过相对目录、临时脚本只写在本次目录、工作目录不出项目、浏览路径转为项目相对、字段显示条件和保留未绘制字段的值;TestUnreadablePluginRunDocumentKeepsBuiltInRunsListed 覆盖写坏的插件文件不影响内置运行、下拉列出并打开该文件;buildprocess 测试覆盖批处理参数转义。", + "notes": "Issue #2100。只内置平台自带的脚本和二进制程序,Python、Node 等其他运行交给插件注入。Windows 上未指定解释器的 Shell 脚本按 PATH 找 bash,可能找到 WSL 的 bash;cmd 参数转义不处理 %(cmd 会展开环境变量)。macOS 原生窗口验收、Windows 与 Linux 实机验证待做。" +} diff --git a/shared/platform-feature-matrix/features/run-discovery.json b/shared/platform-feature-matrix/features/run-discovery.json index 87b22ab83f..527d758d00 100644 --- a/shared/platform-feature-matrix/features/run-discovery.json +++ b/shared/platform-feature-matrix/features/run-discovery.json @@ -21,7 +21,7 @@ }, "owner": "Run", "verification": "Windows Run Actions 仍处于关闭状态;扩展 Run Actions 测试验证插件启用、禁用和声明的执行计划,TypeScript 检查所有调用方;重新启用前需完成实际应用验收。 多模块项目把服务工作目录改成模块目录后,服务仍留在列表中并以该目录启动;填写不存在的目录或 ${workspaceFolder} 等变量时,保存被拒绝并提示原因;在 Windows 确认重新扫描服务使用双箭头刷新图标,配置按语言生态、类型与实例呈现三栏布局;语言切换和外部选中能定位配置,空生态不显示,语言和配置栏不显示重复栏头,生态不显示配置数量;语言侧栏通过拖动阈值折叠和展开,收起与展开阈值不同以避免边界跳动,不显示专门折叠按钮;键盘可调整宽度及恢复展开,保存展开宽度与拖动折叠状态,拖动期间只更新局部宽度和紧凑标记,文字与图标对齐即时切换,结束后保存;语言行、类型行和实例行使用一致的紧凑行高,去掉列表上下留白和选中实例的圆角边距;窄面板自动缩成带提示的图标栏且扩大后恢复,右侧输出保留可用空间,窗口缩放或卸载时清理正在进行的拖动;所选配置的日志、运行状态、顶部停止按钮、清空输出与标准输入均指向其自身会话;保持选中 application 并后台启动服务后,顶部停止仍指向该应用的独立会话,不停止后台服务,左侧使用 SVG 箭头和类型图标,基础设施默认折叠,选择配置自动展开所在分组,运行、停止、编辑和完整名称提示可用;根据 Core 提供的元数据展示明确识别的框架图标,构建与测试任务保留工具图标,未知类型回退通用图标;同名自定义 provider 与已知框架分别分组且折叠状态独立,相同已知框架跨 provider 合组,项目与基础设施不合组;macOS Run 缺少配置且可重新生成时,检查空状态文字与链接在深浅主题下按 IDEA 工具窗口样式显示、窄面板不截断,并确认“识别并生成”仍触发原有生成流程;应用语言设为英文而系统语言为中文时,Run 空状态及其他本面板文案仍应显示英文;Run 顶部标题字号、颜色、41pt 高度和底部分隔线应与 Terminal、Git Log 等工具窗口一致;有项目配置或 Current File 正在运行/已有退出结果时,运行、重启、重新扫描和软换行按钮显示在独立的 36pt 操作栏,检查 16pt IDEA 图标、22pt 共享按钮的悬停、按下、选中及禁用状态;操作栏只保留一个运行/重运行动作:首次启动显示 Run,当前配置已运行过后显示 Rerun;右侧固定停止按钮,未运行禁用、运行中启用,两者始终指向当前选中配置;操作栏不重复显示 Running 圆点及状态文字,重运行按钮复用顶部工具栏的绿色 rerun_stroke 图标;标题栏菜单中的清空输出与原操作一致,收起按钮沿用共享样式;仅有 Current File 的项目启动后也可从 Run 操作栏停止,结束后保留重运行入口;Run 内容区不额外插入语言服务准备状态行,准备进度和失败入口保留在工作台状态栏;Run 标题、操作栏、配置列表标题、控制台标签底边及两侧纵向分割线统一使用工具窗口边框颜色和 1pt 绘制,左侧图标栏不出现 5pt 实心粗线,栏内分组线与 Git Log 一致使用共享 divider 颜色、22pt 宽度、1pt 高度及上下 3pt 间距;操作按钮组之间使用专用 ActionToolbar.separator,详情编辑按钮的边框由共享按钮样式负责,拖动命中范围保持不变;配置树直接显示分组与数量,不显示 Application types 标题;默认隐藏勾选框,通过更多菜单或右键进入批量选择,退出清空选择;配置单行显示名称,类型及服务地址放到悬停提示,行内仅运行/停止,编辑/固定/打开服务保留在共享右键菜单,固定后显示标记;分组与配置使用共享树行高、缩进及焦点选择样式;Run 范围筛选以固定图标栏呈现,应用范围筛选及当前运行导航使用中性 ToolWindowRun 图标,实际运行操作继续使用绿色 Execute 图标;全部采用 IDEA groups、服务采用 server 图标,固定、应用及任务沿用对应 IDEA 原始资源;检查所有图标的 16pt 尺寸、明暗 SVG 自动切换、提示和筛选,右键勾选范围和配置行勾选共享同一批量选择;配置行使用 IDEA 固定、编辑、运行及停止图标,悬停与点击维持箭头光标;配置过期提示使用共享中性通知表面及警告图标,操作仍可重新识别;Run 标题栏仅显示 Run,移除重复配置名与右侧状态胶囊;Console 和 Configuration details 标签位于运行操作按钮组右侧,配置列表选中项表示当前配置,内容区直接显示日志或详情;配置详情使用共享 13pt 字体、原生 Grid 自适应标签列、可选择且可换行的路径及值,编辑配置按钮复用共享 LitheCommitDialogButtonStyle 与 IDEA EditSource 图标,检查深浅主题、窄列及点击跳转设置,服务链接保留原动作;两个标签使用共享 LitheToolWindowTabStyle,检查 13pt 文字、28pt 标签、原始明暗 SVG、悬停及内容区聚焦/失焦状态,保留标签切换;Run 与 Debug 均启用共享 OutputTextView 的 IDEA 渲染入口,运行日志采用一致的 13pt 字体、1.2 倍行高和 ANSI 配色,不给普通 INFO 日志整行染蓝,源码链接继续跳转;Copy 与 Jump to latest 为共享图标按钮,复制不带 ANSI,向上滚动后可恢复跟随;其他配置恢复状态保留各自提示。 Current File 运行一次后修改未保存并切换编辑标签,重运行应先保存原运行文件再构建启动计划;原文件保存失败时提示错误并中止重启,当前焦点文档不被误保存;调整 Run 面板高度,外层横向操作栏固定为 36pt,剩余高度交给配置树和控制台。 保存构建任务后重启,确认用户任务和自动入口同时恢复;再次加载不重复生成。 #1562:Windows 普通应用 A/B 独立会话和输出;先启动 A 再 B,停止及重跑 B 不影响 A,切换配置只显示所属输出,关闭项目清理两者。 IDE API 在 primary 忙碌时仍能启动独立应用,同一配置准备期间拒绝重复启动;保存期间会话可见且可停止,停止后不再启动进程,顶部停止不影响后台服务;旧 Debug 回调不能停止重跑后的应用。 缺少工具链时错误只归属目标应用,不覆盖 primary 或后台会话,也不把已运行的目标实例标记为退出。 macOS 通用 Provider 运行发现:按当前公开声明及目标标签生成 build.provider;名称/执行类型变化保留 ID 和参数、环境、目录覆盖;模型撤回、重排、恢复、停用及重新生成核对指纹,撤回目标不从旧检测层复活。默认项优先 service,不依赖框架名单。 通用 Provider 选项:团队/本机层覆盖运行时 argv、入口与 Build 选项,覆盖空字符串参数、引号、反斜杠、Unicode、false/空数组、显式清空、旧调用者省略、未知/超限字段和重存目录保持。 旧 Run v2 转换:验证稳定 ID、默认项、两层覆盖和目标唯一性;转换前预检两层,覆盖源文件变化、未改写输入变化、偏好变化、各写入阶段取消、外部修改与回滚冲突。工作区/模型/任务取消及新生成撤销写入资格;只读安装目录和越界链接不写入。 当前 Provider 归属投影改用 build={pluginID,buildSystemID,root,projectID}。共享 provider-project-ownership fixture 由 Rust、Swift bridge 与 Windows 映射回归共同读取,覆盖同名类、非标准源码根、角色、稳定身份和 cwd 覆盖;团队/本机伪造 build 身份被当前模型拥有的值替换。原生精确导入查找拒绝错误插件/构建声明/根/项目以及已撤销模型。旧 Windows 生成路径在未提供 Provider 归属时保留,删除前需先迁移真实消费者。 macOS Debug 缺少精确源码路径时,使用通用 Build 归属根加模块路径定位源码;嵌套实例与工作区根实例优先,当前实例没有源码时不得选择其他实例的同名类。原生源码选择回归不替代 Registry/DAP 与完整产品验收。 编辑器行首入口的运行、调试及编辑配置使用 Core 的同一选择规则:精确匹配入口和源码、排除禁用项,优先已选配置,再优先用户配置;配置或工作区在异步选择期间发生变化时不得启动旧结果。 Viva 桌面端运行配置列表:范围选择器依次为全部配置、置顶及 Core 给出的服务/应用/任务/组合,各带数量;配置按提供它的构建系统分组、组按名称排序且可折叠,组内按名称排序;行内运行/停止,Enter 或双击运行,右键菜单运行/停止、编辑运行配置、置顶/取消置顶;置顶写入客户端数据目录 run-configuration-pins.json,不写项目或安装目录,重开后读回。批量选择与并发运行、服务地址尚未迁移。", - "notes": "Viva:构建模型加载后,宿主把已加载实例中每个运行声明适用的目标作为 providerRuns 交给 Core 的 runConfig.generate(不写工作区),再用 runConfig.resolve 合并生成层、.lithe/run/configurations.json 与 .lithe/run/local.json;Run 窗口顶部的“运行配置”选择器列出 build.provider 配置(默认选 Core 给出的默认项),“运行”经 runConfig.providerLaunchInputs 取出保存的参数、环境、工作目录与入口,按 buildProviders 10 的 launchOptions 交给 provider 的 prepareRun 与 decodeRunPreparation;没有任何自定义的 application 运行不带 launchOptions,保持旧 provider 可用。选择器旁的“编辑”打开运行配置编辑对话框:程序参数经 runConfig.argumentText 回显为可逆文本,工作目录与环境变量(每行 KEY=VALUE)回显当前生效值,保存时由 runConfig.updateOptions 生成所选层(本机 .lithe/run/local.json 或项目 .lithe/run/configurations.json)的文档,宿主用 configfile 按读取时的字节做冲突检查后原子替换,再重新解析。尚未实现:provider 运行时参数/入口/工具等 providerRunOptions 的编辑、未加载模型的实例的运行(快照只含已加载实例)、调试配置。 2026-11-12:运行配置检测走 Core(GenerateRunConfigurations/ResolveRunConfigurations/ResolveExecutionEnvironment),宿主没有 GOOS 分支,矩阵原记的 windows=missing 属失真:两个平台共缺 providerRunOptions 编辑与调试配置,与平台无关。 2026-11-16(#1856 第 4 项,Core #77):Core 删除内置运行发现探测器(Cargo、Go、npm/pnpm/yarn/bun、Python、Make、just、Procfile、Compose)、项目内容指纹和工具链需求,Run 列表的自动条目只来自已启用构建插件声明的 buildSystems[].run,加上用户保存的配置;没有插件声明 run 的生态不再出现自动条目。桌面端删除只有测试使用的 InspectRunConfigurations,GenerateRunConfigurations 不再传缓存目录;run_discovery_test.go 用合成的 provider run 验证生成不写工作区。", + "notes": "Viva:构建模型加载后,宿主把已加载实例中每个运行声明适用的目标作为 providerRuns 交给 Core 的 runConfig.generate(不写工作区),再用 runConfig.resolve 合并生成层与已保存的项目层、本机层(2026-11-18 起为 .lithe/run/configurations.yaml、local.yaml 与插件运行的 .lithe/run/plugin/<插件>.toml、<插件>.local.toml,旧版 JSON 在没有对应 YAML 时仍读取,见 builtin-process-runs);Run 窗口顶部的“运行配置”选择器列出 build.provider 配置(默认选 Core 给出的默认项),“运行”经 runConfig.providerLaunchInputs 取出保存的参数、环境、工作目录与入口,按 buildProviders 10 的 launchOptions 交给 provider 的 prepareRun 与 decodeRunPreparation;没有任何自定义的 application 运行不带 launchOptions,保持旧 provider 可用。选择器旁的“编辑”打开运行配置编辑对话框:程序参数经 runConfig.argumentText 回显为可逆文本,工作目录与环境变量(每行 KEY=VALUE)回显当前生效值,保存时由 runConfig.updateOptions 生成所选层(插件运行写 .lithe/run/plugin/<插件>.local.toml 或 <插件>.toml)的文档,宿主用 configfile 按读取时的字节做冲突检查后原子替换,再重新解析。尚未实现:provider 运行时参数/入口/工具等 providerRunOptions 的编辑、未加载模型的实例的运行(快照只含已加载实例)、调试配置。 2026-11-12:运行配置检测走 Core(GenerateRunConfigurations/ResolveRunConfigurations/ResolveExecutionEnvironment),宿主没有 GOOS 分支,矩阵原记的 windows=missing 属失真:两个平台共缺 providerRunOptions 编辑与调试配置,与平台无关。 2026-11-16(#1856 第 4 项,Core #77):Core 删除内置运行发现探测器(Cargo、Go、npm/pnpm/yarn/bun、Python、Make、just、Procfile、Compose)、项目内容指纹和工具链需求,Run 列表的自动条目只来自已启用构建插件声明的 buildSystems[].run,加上用户保存的配置;没有插件声明 run 的生态不再出现自动条目。桌面端删除只有测试使用的 InspectRunConfigurations,GenerateRunConfigurations 不再传缓存目录;run_discovery_test.go 用合成的 provider run 验证生成不写工作区。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": {