diff --git a/.agents/notes/implemented/feature/2026-11-18-run-configuration-before-launch-steps.md b/.agents/notes/implemented/feature/2026-11-18-run-configuration-before-launch-steps.md new file mode 100644 index 0000000000..5e9b2584e3 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-18-run-configuration-before-launch-steps.md @@ -0,0 +1,57 @@ +# Agent 笔记:运行配置的启动前步骤 + +状态:已实现 + +## 先说结论 + +运行配置可以列出启动前步骤(#1616,对应 IntelliJ IDEA 的 “Before launch: Run Another Configuration”): + +- 配置文件里写 `beforeLaunch: [{configuration: }]`,最多 16 项。每一项只能引用内置进程运行(`process.shell`、`process.powershell`、`process.batch`、`process.executable`),不能引用自己。 +- 一层(项目文件或 `local.yaml`)写了 `beforeLaunch` 就整体替换下层的列表;`local.yaml` 写空列表可以关掉项目文件里的步骤。 +- 宿主启动前调用 Core 的 `runConfig.beforeLaunch`。Core 展开嵌套步骤(被引用的配置自己的步骤先运行),展开后最多 32 步;引用不存在、不能作为步骤、在本机不可用、成环、过长时返回 `rejected` 和原因码。 +- 只要展开过程中用到了项目文件写的列表,Core 就返回确认指纹:对列表和这些步骤启动的命令定义求 sha256。宿主第一次运行前弹框列出步骤和命令,用户点“运行步骤”后把指纹存进应用自己的存储 `run-before-launch-approvals.json`(按项目根目录,每个项目最多 64 个)。命令或列表一改,指纹就变,会再问一次。 +- 步骤按顺序在被启动配置的 Run 控制台里运行,每一步前写一行暗色标题。某一步退出码不是 0,就写出步骤名和退出码,不启动配置。停止配置会结束正在运行的步骤。 +- 内置运行编辑器(Core 描述的表单,字段类型 `beforeLaunch`,候选列表由 Core 给出)和构建提供者运行编辑器都可以添加、上移、下移、移除步骤。构建提供者编辑器只有列表改动时才发送 `beforeLaunch`,不会把解析后的列表抄进本地层。 + +## 问题 + +用户要在启动服务前先跑生成代码、编译前端、拉起依赖等命令。原来只能手动先点一个配置、等它结束再点另一个;也没有地方表达“这个配置依赖那几个命令”。IDEA 用户习惯在运行配置里配置启动前任务。 + +同时,项目文件是仓库内容,打开别人的仓库后点运行就执行仓库指定的任意命令,等于让仓库在用户机器上执行代码而不经确认。 + +## 决策 + +- 步骤只引用已经存在的内置进程运行,不在 `beforeLaunch` 里内联命令。这样每个步骤都能单独编辑、单独运行,展开、校验和命令定义都由 Core 统一处理,宿主只负责按顺序启动进程。 +- 校验、展开和指纹都放在 Core:三端行为一致,宿主不需要知道层级合并规则。保存时 Core 也用同一套规则检查(`check_edit`),成环在保存时报 `conflict`。 +- 确认记录放在应用存储而不是项目里,仓库不能替用户批准自己的步骤。指纹包含命令定义,所以仓库更新步骤命令后会重新询问。用户自己 `local.yaml` 里的列表不询问。 +- 步骤的进程用准备阶段的上下文启动(`op.bind`),停止配置时上下文取消,进程随之结束;每一步受 `runPreparationTimeout` 限制。 +- 步骤失败的提示在窗口线程上直接写进控制台(`writeBuildOutputNow`),然后结束操作。用 `streamBuildOutput` 会异步投递,到达时操作已经结束,提示会被丢弃。 + +## 考虑过的备选方案 + +- 支持 IDEA 的全部启动前任务类型(Build、Run Maven Goal、Launch Web Browser 等)。先做“运行另一个配置”,其他类型由插件的 `runOptions` 扩展点以后补充(#2100 中尚未实现的部分)。 +- 步骤并行运行。依赖顺序是用户最常见的需求,并行会让失败原因和输出交错,先保持顺序执行。 +- 每次运行都询问项目文件里的步骤。会打断正常工作流,用户很快就会习惯性点确认;按指纹记住一次,命令改变时再问,兼顾安全和效率。 + +## 后果 + +- 用户可以在一个配置里串起准备命令,一键运行。 +- 打开不信任的仓库时,第一次运行会看到将要执行的命令列表。 +- 以后新增步骤类型时,要在 Core 的 `before_launch.rs` 加类型并纳入指纹,在宿主 `runBeforeLaunchStep` 加执行方式;确认框必须能展示新类型会做什么。 + +## 验证 + +- Core:`cargo test -p lithe-core before_launch`(`core/src/tests/before_launch_steps.rs` 覆盖展开、确认指纹、拒绝原因、编辑校验和本地层清空)。 +- 宿主:`./scripts/desktop/desktop-go.sh test ./internal/workbench/ -run 'BeforeLaunch|TestRunConfigFormKeepsTheStepList' -count=1`,用真实 Core 和系统 shell/cmd 运行步骤,覆盖顺序、确认与记忆、改动后重新确认、取消、失败退出码和停止。 + +## 适用范围 + +- `desktop/internal/workbench/runconfig_before_launch.go` +- `desktop/internal/workbench/runconfig.go` +- `desktop/internal/workbench/runconfig_process.go` +- `desktop/internal/workbench/runconfig_form.go` +- `desktop/internal/workbench/runconfig_form_view.go` +- `desktop/internal/workbench/runconfig_edit.go` +- `desktop/internal/workbench/runconfig_view.go` +- `desktop/internal/core/run_before_launch.go` +- Core:`rust/crates/execution/src/configuration/before_launch.rs` diff --git a/desktop/internal/core/run_before_launch.go b/desktop/internal/core/run_before_launch.go new file mode 100644 index 0000000000..6c652e381d --- /dev/null +++ b/desktop/internal/core/run_before_launch.go @@ -0,0 +1,44 @@ +package core + +import "context" + +// RunBeforeLaunch is what `runConfig.beforeLaunch` answers: Status "ok" with the +// steps to run in order and, when a project file names them, the Confirmation to +// ask for; or "rejected" with the Refusal of the step that cannot run. +type RunBeforeLaunch struct { + Status string `json:"status"` + Steps []RunBeforeLaunchItem `json:"steps"` + Confirmation *RunBeforeLaunchConfirmation `json:"confirmation"` + Refusal *RunBeforeLaunchRefusal `json:"refusal"` +} + +// RunBeforeLaunchItem is one run to start before the configuration: its ID, its +// name and a line naming what it starts, shown in the confirmation. +type RunBeforeLaunchItem struct { + ConfigurationID string `json:"configurationId"` + Name string `json:"name"` + Summary string `json:"summary"` +} + +// RunBeforeLaunchConfirmation identifies a list of steps a project file names; the +// host asks once per Fingerprint before running it. +type RunBeforeLaunchConfirmation struct { + Fingerprint string `json:"fingerprint"` +} + +// RunBeforeLaunchRefusal is why the steps cannot run: Code is notFound, +// notAllowed, unavailable, cycle or tooLong, about step ConfigurationID. +type RunBeforeLaunchRefusal struct { + Code string `json:"code"` + ConfigurationID string `json:"configurationId"` +} + +// RunBeforeLaunch expands the built-in process runs configurationID starts first. +func (c *Client) RunBeforeLaunch(ctx context.Context, root, configurationID string) (RunBeforeLaunch, error) { + var result RunBeforeLaunch + err := c.Execute(ctx, "runConfig.beforeLaunch", struct { + Root string `json:"root"` + ConfigurationID string `json:"configurationId"` + }{root, configurationID}, &result) + return result, err +} diff --git a/desktop/internal/core/run_config.go b/desktop/internal/core/run_config.go index 79cb3898b5..0eb815aeb6 100644 --- a/desktop/internal/core/run_config.go +++ b/desktop/internal/core/run_config.go @@ -48,6 +48,14 @@ type RunConfiguration struct { // 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"` + // BeforeLaunch names the built-in process runs started, in order, before this one. + BeforeLaunch []RunBeforeLaunchStep `json:"beforeLaunch,omitempty"` +} + +// RunBeforeLaunchStep is one step of a configuration's beforeLaunch: the built-in +// process run to start first. +type RunBeforeLaunchStep struct { + Configuration string `json:"configuration"` } // RunPluginDependency is the plugin a configuration needs: its ID, and what the @@ -265,6 +273,9 @@ type RunOptionsEdit struct { Environment map[string]string `json:"environment"` // ProviderRunOptions replaces the build provider choices of the selected layer when set. ProviderRunOptions json.RawMessage `json:"providerRunOptions,omitempty"` + // BeforeLaunch replaces the steps of the selected layer when set; an empty list + // removes them (and in the local layer hides the project's). + BeforeLaunch *[]string `json:"beforeLaunch,omitempty"` // Plugins is the enabled plugin list of ResolveRunConfigurations, so a plugin // document Core writes records the installed plugin. Plugins []RunInstalledPlugin `json:"plugins,omitempty"` diff --git a/desktop/internal/core/run_process.go b/desktop/internal/core/run_process.go index 7b34bbeb7e..2659496ba7 100644 --- a/desktop/internal/core/run_process.go +++ b/desktop/internal/core/run_process.go @@ -39,6 +39,14 @@ type RunEditorField struct { Options []string `json:"options,omitempty"` VisibleWhen *RunFieldCondition `json:"visibleWhen,omitempty"` Note string `json:"note,omitempty"` + // Candidates are the configurations a beforeLaunch field may name. + Candidates []RunConfigurationName `json:"candidates,omitempty"` +} + +// RunConfigurationName is a run configuration's ID and name. +type RunConfigurationName struct { + ID string `json:"id"` + Name string `json:"name"` } // RunFieldCondition shows a field only while Field has the value Equals. diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index 446dbb1666..5eee338a6d 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -1330,6 +1330,26 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.runConfig.arguments": "Program arguments", "desktop.runConfig.argumentsPlaceholder": "Separate with spaces; quote values that contain spaces", "desktop.runConfig.automaticValue": "Automatic ({value})", + "desktop.runConfig.beforeLaunch.confirmBody": "Before {name} starts, the project's run configuration file asks to run these commands. Run them only if you trust this project.", + "desktop.runConfig.beforeLaunch.confirmRun": "Run Steps", + "desktop.runConfig.beforeLaunch.confirmTitle": "Run steps from the project file?", + "desktop.runConfig.beforeLaunch.exited": "Before-launch step {name} exited with code {code}; the configuration was not started.", + "desktop.runConfig.beforeLaunch.failed": "Before-launch step {name} could not run: {reason}", + "desktop.runConfig.beforeLaunch.refused.cycle": "Before-launch steps form a loop at {step}.", + "desktop.runConfig.beforeLaunch.refused.notAllowed": "{step} cannot be a before-launch step: only shell, PowerShell, batch and executable runs can.", + "desktop.runConfig.beforeLaunch.refused.notFound": "A before-launch step names configuration {step}, which does not exist.", + "desktop.runConfig.beforeLaunch.refused.other": "Before-launch step {step} cannot run.", + "desktop.runConfig.beforeLaunch.refused.tooLong": "Too many before-launch steps at {step}: at most 32 run once nested steps are expanded.", + "desktop.runConfig.beforeLaunch.refused.unavailable": "Before-launch step {step} is not available on this system.", + "desktop.runConfig.beforeLaunch.stepHeader": "Before launch ({index}/{count}): {name}", + "desktop.runConfig.beforeLaunchAdd": "Add step", + "desktop.runConfig.beforeLaunchDown": "Move down", + "desktop.runConfig.beforeLaunchEmpty": "No steps", + "desktop.runConfig.beforeLaunchHelp": "Process runs that start, in order, before this configuration. It starts only after each of them exits with code 0.", + "desktop.runConfig.beforeLaunchMissing": "Missing configuration {id}", + "desktop.runConfig.beforeLaunchNoCandidates": "Create a shell, PowerShell, batch or executable run first to use it as a step.", + "desktop.runConfig.beforeLaunchRemove": "Remove step", + "desktop.runConfig.beforeLaunchUp": "Move up", "desktop.runConfig.browse": "Browse…", "desktop.runConfig.builtInGroup": "Scripts and Programs", "desktop.runConfig.chooseFailed": "Could not open the file chooser.", @@ -1357,6 +1377,8 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.runConfig.errorOutsideProject": "The working directory must be inside the project", "desktop.runConfig.errorRequired": "Required", "desktop.runConfig.errorTooLong": "Too long", + "desktop.runConfig.errorUnavailable": "Not available on this system", + "desktop.runConfig.fieldBeforeLaunch": "Before launch", "desktop.runConfig.fieldExecutionPolicyBypass": "Bypass execution policy (-ExecutionPolicy Bypass)", "desktop.runConfig.fieldInterpreter": "Interpreter path", "desktop.runConfig.fieldInterpreterArguments": "Interpreter options", @@ -4208,6 +4230,26 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.runConfig.arguments": "程序参数", "desktop.runConfig.argumentsPlaceholder": "以空格分隔;含空格的值请加引号", "desktop.runConfig.automaticValue": "自动({value})", + "desktop.runConfig.beforeLaunch.confirmBody": "启动 {name} 前,项目的运行配置文件要求先运行以下命令。只有信任此项目时才运行。", + "desktop.runConfig.beforeLaunch.confirmRun": "运行步骤", + "desktop.runConfig.beforeLaunch.confirmTitle": "运行项目文件中的启动前步骤?", + "desktop.runConfig.beforeLaunch.exited": "启动前步骤 {name} 以退出码 {code} 结束,未启动配置。", + "desktop.runConfig.beforeLaunch.failed": "启动前步骤 {name} 无法运行:{reason}", + "desktop.runConfig.beforeLaunch.refused.cycle": "启动前步骤在 {step} 处形成循环。", + "desktop.runConfig.beforeLaunch.refused.notAllowed": "{step} 不能作为启动前步骤:只有 Shell、PowerShell、批处理和可执行文件运行配置可以。", + "desktop.runConfig.beforeLaunch.refused.notFound": "启动前步骤引用的配置 {step} 不存在。", + "desktop.runConfig.beforeLaunch.refused.other": "启动前步骤 {step} 无法运行。", + "desktop.runConfig.beforeLaunch.refused.tooLong": "启动前步骤在 {step} 处过多:展开嵌套步骤后最多 32 个。", + "desktop.runConfig.beforeLaunch.refused.unavailable": "启动前步骤 {step} 在此系统上不可用。", + "desktop.runConfig.beforeLaunch.stepHeader": "启动前步骤 ({index}/{count}): {name}", + "desktop.runConfig.beforeLaunchAdd": "添加步骤", + "desktop.runConfig.beforeLaunchDown": "下移", + "desktop.runConfig.beforeLaunchEmpty": "无步骤", + "desktop.runConfig.beforeLaunchHelp": "启动此配置前按顺序运行的进程配置。每一个都以退出码 0 结束后,才会启动此配置。", + "desktop.runConfig.beforeLaunchMissing": "找不到配置 {id}", + "desktop.runConfig.beforeLaunchNoCandidates": "先创建 Shell、PowerShell、批处理或可执行文件运行配置,才能把它作为步骤。", + "desktop.runConfig.beforeLaunchRemove": "移除步骤", + "desktop.runConfig.beforeLaunchUp": "上移", "desktop.runConfig.browse": "选择…", "desktop.runConfig.builtInGroup": "脚本与程序", "desktop.runConfig.chooseFailed": "无法打开文件选择器。", @@ -4235,6 +4277,8 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.runConfig.errorOutsideProject": "工作目录必须在项目内", "desktop.runConfig.errorRequired": "必填", "desktop.runConfig.errorTooLong": "内容太长", + "desktop.runConfig.errorUnavailable": "在此系统上不可用", + "desktop.runConfig.fieldBeforeLaunch": "启动前", "desktop.runConfig.fieldExecutionPolicyBypass": "绕过执行策略(-ExecutionPolicy Bypass)", "desktop.runConfig.fieldInterpreter": "解释器路径", "desktop.runConfig.fieldInterpreterArguments": "解释器选项", diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index a0a4272a80..fb25ce573f 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -110,6 +110,8 @@ type Kernel interface { 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) + // RunBeforeLaunch expands the steps a configuration runs before it starts (runconfig_before_launch.go). + RunBeforeLaunch(ctx context.Context, root, configurationID string) (core.RunBeforeLaunch, 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 e6c596cd08..cdb5f30a46 100644 --- a/desktop/internal/workbench/build.go +++ b/desktop/internal/workbench/build.go @@ -2146,6 +2146,18 @@ func (a *App) streamBuildOutput(p *project, op *buildOperation, text string) { }) } +// writeBuildOutputNow adds text to op's console on the window thread at once, for a line the +// window writes right before it ends op: a posted line would arrive after op ended and be dropped. +func (a *App) writeBuildOutputNow(p *project, op *buildOperation, text string) { + if text == "" { + return + } + op.decoder.deliver(text, func(chunk outputChunk, failure error) { + a.reportOutputStyleFailure(failure) + a.applyBuildOutput(p, op, chunk) + }) +} + // applyBuildOutput adds decoded output to op's console. Output of an operation the window no // longer runs is dropped, so it never lands in a later execution's console. func (a *App) applyBuildOutput(p *project, op *buildOperation, chunk outputChunk) { diff --git a/desktop/internal/workbench/root.go b/desktop/internal/workbench/root.go index 93ab9e9cd8..c9a669bd91 100644 --- a/desktop/internal/workbench/root.go +++ b/desktop/internal/workbench/root.go @@ -313,6 +313,7 @@ func (a *App) overlays(c ui.C) { a.drawRunConfigEditor(c, p) a.drawRunConfigForm(c, p) a.drawRunConfigDelete(c, p) + a.drawBeforeLaunchConfirmation(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 a390d0faf2..ba1c4a3a41 100644 --- a/desktop/internal/workbench/runconfig.go +++ b/desktop/internal/workbench/runconfig.go @@ -47,6 +47,9 @@ type runConfigState struct { newMenu bool // deleting is the user configuration whose delete waits for confirmation. deleting *runConfigDeletion + // beforeLaunch is the start that waits for the user to allow the steps a project file + // names before it (runconfig_before_launch.go). + beforeLaunch *beforeLaunchConfirmation // 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 @@ -286,6 +289,16 @@ func (a *App) startRunConfigurationWith(p *project, id string, debug *connection a.endBuildOperation(p, op, "failed", nil, "unsaved documents could not be saved", "") return } + // The steps a configuration names run first; Run and Debug both run them. + a.runBeforeLaunch(p, op, id, func() { a.prepareConfiguredRun(p, op, id, reference, index, debug) }) + }) + return op, nil +} + +// prepareConfiguredRun asks Core for the saved launch options of configuration id and has the +// build provider prepare and start the run. +func (a *App) prepareConfiguredRun(p *project, op *buildOperation, id string, reference core.RunProviderReference, index int, debug *connectionDebug) { + { root, kernel := p.root, a.kernel a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { prepare, release := op.bind(ctx) @@ -316,8 +329,7 @@ func (a *App) startRunConfigurationWith(p *project, id string, debug *connection a.runBuildTargetWith(p, op, &p.build.instances[index], inputs.Reference.ProjectID, inputs.Reference.TargetID, inputs.Reference.Run, options) } }) - }) - return op, nil + } } // buildInstanceIndex returns the detected build instance a provider reference names, or -1. diff --git a/desktop/internal/workbench/runconfig_before_launch.go b/desktop/internal/workbench/runconfig_before_launch.go new file mode 100644 index 0000000000..8ac4e67ad3 --- /dev/null +++ b/desktop/internal/workbench/runconfig_before_launch.go @@ -0,0 +1,274 @@ +package workbench + +// Steps before launch (#1616): a run configuration names built-in process runs that start, +// in order, before it does, as IntelliJ IDEA's "Before launch: Run Another Configuration". +// Core expands the list and says whether a project file named it +// (`runConfig.beforeLaunch`); the host asks once per list a project file names, runs each +// step as its process run, writes the output to the console of the configuration that +// starts, and starts the configuration only after every step exited with 0. Stopping the +// configuration stops the step that runs. +// +// Note: 决策见 .agents/notes/implemented/feature/2026-11-18-run-configuration-before-launch-steps.md + +import ( + "context" + "errors" + "fmt" + "os/exec" + "slices" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// beforeLaunchApprovalsFile keeps, per project root, the fingerprints of the step lists a +// project file names that the user allowed to run. It lives in the app's own storage, never +// in the project, so a repository cannot approve its own steps. +const beforeLaunchApprovalsFile = "run-before-launch-approvals.json" + +// beforeLaunchApprovalsLimit bounds the fingerprints kept per project; the oldest go first. +const beforeLaunchApprovalsLimit = 64 + +// beforeLaunchConfirmation is the open question whether to run the steps a project file +// names before op starts. +type beforeLaunchConfirmation struct { + op *buildOperation + name string + steps []core.RunBeforeLaunchItem + fingerprint string + // run continues the start once the user allowed the steps. + run func() +} + +// runBeforeLaunch runs the steps configuration id names before op starts, then calls start +// on the window thread. A list that cannot run, a step that fails and a stop end op instead, +// with the reason in its console. +func (a *App) runBeforeLaunch(p *project, op *buildOperation, id string, start func()) { + root, kernel := p.root, a.kernel + a.background(p, runPreparationTimeout, func(ctx context.Context) func(*App) { + prepare, release := op.bind(ctx) + defer release() + steps, err := kernel.RunBeforeLaunch(prepare, root, id) + return func(a *App) { + if !a.ownsLiveOperation(p, op) { + a.finishBuildError(p, op, context.Canceled) + return + } + if err != nil { + a.finishBuildError(p, op, err) + return + } + if steps.Status != "ok" { + a.refuseBeforeLaunch(p, op, steps.Refusal) + return + } + if len(steps.Steps) == 0 { + start() + return + } + run := func() { a.runBeforeLaunchSteps(p, op, steps.Steps, start) } + if steps.Confirmation == nil || a.beforeLaunchApproved(root, steps.Confirmation.Fingerprint) { + run() + return + } + p.runConfigs.beforeLaunch = &beforeLaunchConfirmation{ + op: op, name: op.session.label, steps: steps.Steps, fingerprint: steps.Confirmation.Fingerprint, run: run, + } + } + }) +} + +// ownsLiveOperation reports whether op is still the window's and was not stopped. +func (a *App) ownsLiveOperation(p *project, op *buildOperation) bool { + return a.project == p && p.build.owns(op) && !op.cancelled +} + +// refuseBeforeLaunch ends op with why its steps cannot run. +func (a *App) refuseBeforeLaunch(p *project, op *buildOperation, refusal *core.RunBeforeLaunchRefusal) { + code, step := "", "" + if refusal != nil { + code, step = refusal.Code, refusal.ConfigurationID + } + if configuration := p.runConfigs.configuration(step); configuration != nil { + step = configuration.Name + } + language := a.language() + var message string + switch code { + case "notFound": + message = i18n.SharedFormat(language, "desktop.runConfig.beforeLaunch.refused.notFound", map[string]string{"step": step}) + case "notAllowed": + message = i18n.SharedFormat(language, "desktop.runConfig.beforeLaunch.refused.notAllowed", map[string]string{"step": step}) + case "unavailable": + message = i18n.SharedFormat(language, "desktop.runConfig.beforeLaunch.refused.unavailable", map[string]string{"step": step}) + case "cycle": + message = i18n.SharedFormat(language, "desktop.runConfig.beforeLaunch.refused.cycle", map[string]string{"step": step}) + case "tooLong": + message = i18n.SharedFormat(language, "desktop.runConfig.beforeLaunch.refused.tooLong", map[string]string{"step": step}) + default: + message = i18n.SharedFormat(language, "desktop.runConfig.beforeLaunch.refused.other", map[string]string{"step": step}) + } + a.operationRejected("run_before_launch", "refused") + a.notifyError(message) + a.finishBuildError(p, op, errors.New(message)) +} + +// runBeforeLaunchSteps starts each step in order off the window thread and waits for it; +// start runs once the last one exited with 0. Each step is bounded like a run's +// preparation and ends when op is stopped. +func (a *App) runBeforeLaunchSteps(p *project, op *buildOperation, steps []core.RunBeforeLaunchItem, start func()) { + root, kernel, language := p.root, a.kernel, a.language() + a.background(p, 0, func(ctx context.Context) func(*App) { + for index, step := range steps { + header := i18n.SharedFormat(language, "desktop.runConfig.beforeLaunch.stepHeader", map[string]string{ + "index": fmt.Sprint(index + 1), "count": fmt.Sprint(len(steps)), "name": step.Name, + }) + a.streamBuildOutput(p, op, "\x1b[2m"+header+"\x1b[0m\n") + if err := a.runBeforeLaunchStep(ctx, p, op, kernel, language, root, step); err != nil { + return func(a *App) { a.failBeforeLaunch(p, op, step, err) } + } + } + return func(a *App) { + if !a.ownsLiveOperation(p, op) { + a.finishBuildError(p, op, context.Canceled) + return + } + start() + } + }) +} + +// runBeforeLaunchStep starts one step's process with its output in op's console and waits +// for it to exit. +func (a *App) runBeforeLaunchStep(ctx context.Context, p *project, op *buildOperation, kernel Kernel, language i18n.Language, root string, step core.RunBeforeLaunchItem) error { + bounded, cancel := context.WithTimeout(ctx, runPreparationTimeout) + defer cancel() + prepare, release := op.bind(bounded) + defer release() + process, cleanup, err := a.startConfiguredProcess(prepare, prepare, kernel, language, root, step.ConfigurationID, func(text string) { + a.streamBuildOutput(p, op, text) + }) + defer cleanup() + if err != nil { + return err + } + return process.Wait() +} + +// failBeforeLaunch ends op because step did not exit with 0, naming the step and its exit +// code; a stop ends it as stopped. +func (a *App) failBeforeLaunch(p *project, op *buildOperation, step core.RunBeforeLaunchItem, err error) { + if !a.ownsLiveOperation(p, op) || errors.Is(err, context.Canceled) { + a.finishBuildError(p, op, context.Canceled) + return + } + language := a.language() + var exit *exec.ExitError + message := i18n.SharedFormat(language, "desktop.runConfig.beforeLaunch.failed", map[string]string{"name": step.Name, "reason": err.Error()}) + if errors.As(err, &exit) { + message = i18n.SharedFormat(language, "desktop.runConfig.beforeLaunch.exited", map[string]string{"name": step.Name, "code": fmt.Sprint(exit.ExitCode())}) + } + a.writeBuildOutputNow(p, op, message+"\n") + a.finishBuildError(p, op, errors.New(message)) +} + +// beforeLaunchApproved reports whether the user allowed the step list fingerprint in the +// project at root. A store that cannot be read approves nothing, so the user is asked. +func (a *App) beforeLaunchApproved(root, fingerprint string) bool { + if a.store == nil { + return false + } + all := map[string][]string{} + if _, err := a.store.Load(beforeLaunchApprovalsFile, &all); err != nil { + a.backgroundFailed("run_before_launch_approvals", err) + return false + } + return slices.Contains(all[root], fingerprint) +} + +// approveBeforeLaunch remembers that the user allowed fingerprint in the project at root. +func (a *App) approveBeforeLaunch(root, fingerprint string) { + if a.store == nil { + return + } + all := map[string][]string{} + if _, err := a.store.Load(beforeLaunchApprovalsFile, &all); err != nil { + a.backgroundFailed("run_before_launch_approvals", err) + all = map[string][]string{} + } + approved := slices.DeleteFunc(all[root], func(known string) bool { return known == fingerprint }) + approved = append(approved, fingerprint) + if len(approved) > beforeLaunchApprovalsLimit { + approved = approved[len(approved)-beforeLaunchApprovalsLimit:] + } + all[root] = approved + if err := a.store.Save(beforeLaunchApprovalsFile, all); err != nil { + a.backgroundFailed("run_before_launch_approvals", err) + } +} + +// cancelBeforeLaunch closes the open question and ends its configuration without starting it. +func (a *App) cancelBeforeLaunch(p *project) { + ask := p.runConfigs.beforeLaunch + if ask == nil { + return + } + p.runConfigs.beforeLaunch = nil + a.finishBuildError(p, ask.op, context.Canceled) +} + +// drawBeforeLaunchConfirmation declares the question whether to run the steps a project file +// names: each step's name and what it starts. Run remembers the list for this project; Cancel +// does not start the configuration. A stop while it is open closes it. +func (a *App) drawBeforeLaunchConfirmation(c ui.C, p *project) { + ask := p.runConfigs.beforeLaunch + if ask == nil { + return + } + cancel := func() { a.cancelBeforeLaunch(p) } + if !a.ownsLiveOperation(p, ask.op) { + c.After(cancel) + return + } + language := a.language() + open := true + title := i18n.Shared(language, "desktop.runConfig.beforeLaunch.confirmTitle") + closed := ui.ModalWith(c, &open, title, ui.ModalSpec{Width: 520}, func() { + k := c.Part("run-before-launch-confirm") + ui.Column(k).FillWidth().Gap(8).Children(func() { + ui.Paragraph(k, i18n.SharedFormat(language, "desktop.runConfig.beforeLaunch.confirmBody", map[string]string{"name": ask.name}), 4).Color(a.colors.Text) + for index, step := range ask.steps { + row := k.Part(fmt.Sprint(index)) + ui.Column(row).FillWidth().Gap(2).Children(func() { + ui.Text(row, fmt.Sprintf("%d. %s", index+1, step.Name)).Weight(gfx.WeightSemibold).Color(a.colors.Text).Ellipsis() + if step.Summary != "" { + ui.Text(row, step.Summary).Mono().FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Ellipsis() + } + }) + } + }) + }, func() { + ui.Row(c.Part("run-before-launch-confirm-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() { + a.performed("run.beforeLaunch.cancel", surfaceButton) + cancel() + }) + } + if ui.Button(c, i18n.Shared(language, "desktop.runConfig.beforeLaunch.confirmRun")).Clicked() { + c.After(func() { + p.runConfigs.beforeLaunch = nil + a.performed("run.beforeLaunch.allow", surfaceButton) + a.approveBeforeLaunch(p.root, ask.fingerprint) + ask.run() + }) + } + }) + }) + if closed { + c.After(cancel) + } +} diff --git a/desktop/internal/workbench/runconfig_before_launch_test.go b/desktop/internal/workbench/runconfig_before_launch_test.go new file mode 100644 index 0000000000..fe41b7e299 --- /dev/null +++ b/desktop/internal/workbench/runconfig_before_launch_test.go @@ -0,0 +1,228 @@ +package workbench + +import ( + "encoding/json" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" +) + +// beforeLaunchScript is a built-in run of the system's own shell (cmd on Windows) whose text +// prints line, sleeps or exits with code; so the tests need no developer tool. +func beforeLaunchScript(id string, text map[string]string, steps ...string) map[string]any { + provider, script := runProviderShell, text["unix"] + if runtime.GOOS == "windows" { + provider, script = runProviderBatch, text["windows"] + } + entry := map[string]any{ + "id": id, "name": strings.TrimPrefix(id, "user:"), "provider": provider, "confidence": "declared", + "extensions": map[string]any{"process": map[string]any{"text": script}}, + } + if len(steps) > 0 { + named := []map[string]string{} + for _, step := range steps { + named = append(named, map[string]string{"configuration": step}) + } + entry["beforeLaunch"] = named + } + return entry +} + +func beforeLaunchEcho(id, line string, steps ...string) map[string]any { + return beforeLaunchScript(id, map[string]string{"unix": "echo " + line + "\n", "windows": "@echo " + line + "\r\n"}, steps...) +} + +// writeBeforeLaunchDocument writes a run configuration layer; YAML reads the JSON as it is. +func writeBeforeLaunchDocument(t *testing.T, root, file string, configurations ...map[string]any) { + t.Helper() + data, err := json.Marshal(map[string]any{"version": 2, "configurations": configurations}) + if err != nil { + t.Fatal(err) + } + directory := filepath.Join(root, ".lithe", "run") + if err := os.MkdirAll(directory, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(directory, file), data, 0o600); err != nil { + t.Fatal(err) + } +} + +// openBeforeLaunchProject opens root with the real Core and waits for its configurations. +func openBeforeLaunchProject(t *testing.T, root string) (*harness, *project) { + t.Helper() + temporary := t.TempDir() + for _, variable := range []string{"TMPDIR", "TMP", "TEMP"} { + t.Setenv(variable, temporary) + } + 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 + }) + if p.runConfigs.failure != "" { + t.Fatalf("configurations failed: %s", p.runConfigs.failure) + } + return h, p +} + +// awaitEndedRun waits for the session labeled label other than previous to end, whatever +// its outcome. +func awaitEndedRun(t *testing.T, h *harness, p *project, label string, previous *runEntry) *runEntry { + t.Helper() + var found *runEntry + awaitStateWithin(t, h, 20*time.Second, "the end of "+label, func() bool { + for _, entry := range p.build.runs { + if entry != previous && entry.label == label && !entry.running && !p.build.active() { + found = entry + return true + } + } + return false + }) + return found +} + +// Steps a project file names ask once: Run starts them in order, nested steps first, with +// their output in the console of the configuration, and the configuration after them. The +// answer is remembered, so the next start runs the steps without asking. +func TestBeforeLaunchStepsRunInOrderAfterTheProjectListIsAllowed(t *testing.T) { + root := t.TempDir() + writeBeforeLaunchDocument(t, root, "configurations.yaml", + beforeLaunchEcho("user:generate", "step-generate"), + beforeLaunchEcho("user:compile", "step-compile", "user:generate"), + beforeLaunchEcho("user:app", "app-ran", "user:compile"), + ) + h, p := openBeforeLaunchProject(t, root) + + h.app.post(func(a *App) { a.runConfiguration(p, "user:app") }) + awaitStateWithin(t, h, 10*time.Second, "the confirmation", func() bool { return p.runConfigs.beforeLaunch != nil }) + ask := p.runConfigs.beforeLaunch + if len(ask.steps) != 2 || ask.steps[0].ConfigurationID != "user:generate" || ask.steps[1].ConfigurationID != "user:compile" { + t.Fatalf("steps = %+v", ask.steps) + } + h.settle() + run := i18n.Shared(h.app.language(), "desktop.runConfig.beforeLaunch.confirmRun") + if !h.shows(run) || !h.shows("1. generate") { + t.Fatal("the confirmation does not list the steps") + } + h.clickNamed(run) + first := awaitProcessRun(t, h, p, "app", nil) + console := first.output.all() + generate, compile, app := strings.Index(console, "step-generate"), strings.Index(console, "step-compile"), strings.Index(console, "app-ran") + if generate < 0 || compile < generate || app < compile { + t.Fatalf("the steps did not run in order before the configuration; console:\n%s", console) + } + + h.app.post(func(a *App) { a.runConfiguration(p, "user:app") }) + again := awaitProcessRun(t, h, p, "app", first) + if p.runConfigs.beforeLaunch != nil || !strings.Contains(again.output.all(), "step-compile") { + t.Fatalf("the allowed list was asked again or skipped; console:\n%s", again.output.all()) + } + + // A changed list is a new question. + writeBeforeLaunchDocument(t, root, "configurations.yaml", + beforeLaunchEcho("user:generate", "step-generate-changed"), + beforeLaunchEcho("user:compile", "step-compile", "user:generate"), + beforeLaunchEcho("user:app", "app-ran", "user:compile"), + ) + h.app.post(func(a *App) { a.refreshRunConfigurations(p) }) + awaitStateWithin(t, h, 10*time.Second, "the changed configurations", func() bool { return !p.runConfigs.loading }) + h.app.post(func(a *App) { a.runConfiguration(p, "user:app") }) + awaitStateWithin(t, h, 10*time.Second, "the new confirmation", func() bool { return p.runConfigs.beforeLaunch != nil }) + h.app.post(func(a *App) { a.cancelBeforeLaunch(p) }) + cancelled := awaitEndedRun(t, h, p, "app", again) + if cancelled.outcome == runSucceeded || strings.Contains(cancelled.output.all(), "app-ran") { + t.Fatalf("a cancelled confirmation started the configuration; console:\n%s", cancelled.output.all()) + } +} + +// A step that exits with a code other than 0 ends the start: the configuration does not run +// and the console names the step and its code. Steps of the user's own file run unasked. +func TestFailingBeforeLaunchStepStopsTheStart(t *testing.T) { + root := t.TempDir() + writeBeforeLaunchDocument(t, root, "local.yaml", + beforeLaunchScript("user:check", map[string]string{"unix": "echo checking\nexit 3\n", "windows": "@echo checking\r\n@exit /b 3\r\n"}), + beforeLaunchEcho("user:app", "app-ran", "user:check"), + ) + h, p := openBeforeLaunchProject(t, root) + h.app.post(func(a *App) { a.runConfiguration(p, "user:app") }) + ended := awaitEndedRun(t, h, p, "app", nil) + console := ended.output.all() + want := i18n.SharedFormat(h.app.language(), "desktop.runConfig.beforeLaunch.exited", map[string]string{"name": "check", "code": "3"}) + if ended.outcome == runSucceeded || strings.Contains(console, "app-ran") || !strings.Contains(console, "checking") || !strings.Contains(console, want) { + t.Fatalf("outcome %v; console:\n%s", ended.outcome, console) + } +} + +// Stopping the configuration while a step runs stops the step, and the configuration does +// not start. +func TestStoppingDuringABeforeLaunchStepEndsIt(t *testing.T) { + root := t.TempDir() + writeBeforeLaunchDocument(t, root, "local.yaml", + beforeLaunchScript("user:wait", map[string]string{"unix": "echo waiting\nsleep 30\n", "windows": "@echo waiting\r\n@ping -n 30 127.0.0.1 >nul\r\n"}), + beforeLaunchEcho("user:app", "app-ran", "user:wait"), + ) + h, p := openBeforeLaunchProject(t, root) + h.app.post(func(a *App) { a.runConfiguration(p, "user:app") }) + var entry *runEntry + awaitStateWithin(t, h, 10*time.Second, "the step's output", func() bool { + for _, candidate := range p.build.runs { + if candidate.label == "app" && strings.Contains(candidate.output.all(), "waiting") { + entry = candidate + return true + } + } + return false + }) + started := time.Now() + h.app.post(func(a *App) { a.stopRun(p, entry) }) + ended := awaitEndedRun(t, h, p, "app", nil) + if elapsed := time.Since(started); elapsed > 15*time.Second { + t.Fatalf("the stop took %v", elapsed) + } + if ended.outcome == runSucceeded || strings.Contains(ended.output.all(), "app-ran") { + t.Fatalf("outcome %v; console:\n%s", ended.outcome, ended.output.all()) + } +} + +// The editor shows the chosen steps by name, offers the other process runs and sends the +// edited list; a save that did not change the list sends none. +func TestRunConfigFormKeepsTheStepList(t *testing.T) { + f := &runConfigForm{values: map[string]json.RawMessage{}, texts: map[string]*string{}, flags: map[string]*bool{}} + f.fields = []core.RunEditorField{{ID: "beforeLaunch", Kind: runFieldBeforeLaunch}} + f.readValues(f.fields, map[string]json.RawMessage{"beforeLaunch": json.RawMessage(`["user:a","user:b"]`)}) + if !f.drawable(i18n.English, f.fields[0]) { + t.Fatal("the step field is not drawn") + } + moveRunConfigStep(f.beforeLaunch, 1, 0) + moveRunConfigStep(f.beforeLaunch, 1, 2) + if got := string(f.collect()["beforeLaunch"]); got != `["user:b","user:a"]` { + t.Fatalf("collected %s", got) + } + + empty := &runConfigForm{values: map[string]json.RawMessage{}, texts: map[string]*string{}, flags: map[string]*bool{}} + empty.fields = f.fields + empty.readValues(empty.fields, map[string]json.RawMessage{}) + if got := string(empty.collect()["beforeLaunch"]); got != `[]` { + t.Fatalf("an empty list collected %s", got) + } + + s := runConfigState{list: []core.RunConfiguration{ + {ID: "user:a", Name: "a", Provider: runProviderShell}, + {ID: "user:self", Name: "self", Provider: runProviderShell}, + {ID: "run:maven", Name: "maven", Provider: "build.example"}, + }} + candidates := s.beforeLaunchCandidates("user:self") + if len(candidates) != 1 || candidates[0].ID != "user:a" { + t.Fatalf("candidates = %+v", candidates) + } +} diff --git a/desktop/internal/workbench/runconfig_before_launch_visual_test.go b/desktop/internal/workbench/runconfig_before_launch_visual_test.go new file mode 100644 index 0000000000..615124d5e1 --- /dev/null +++ b/desktop/internal/workbench/runconfig_before_launch_visual_test.go @@ -0,0 +1,94 @@ +//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" +) + +// TestVisualBeforeLaunchSteps captures the steps before launch: the editor of a run with two +// steps, the question before the steps a project file names run, and the Run window after the +// steps and the run. It needs only LITHE_VISUAL_OUTPUT_DIR; the dark captures are in Chinese +// and the light ones in English. +func TestVisualBeforeLaunchSteps(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(), "ServiceDemo") + server := map[string]any{ + "id": "user:server", "name": "Server", "provider": "process.executable", "confidence": "declared", + "args": []string{"server", "started"}, + "extensions": map[string]any{"process": map[string]any{"program": "echo"}}, + "beforeLaunch": []map[string]string{{"configuration": "user:generate"}, {"configuration": "user:frontend"}}, + } + writeBeforeLaunchDocument(t, root, "configurations.yaml", + beforeLaunchEcho("user:generate", "generated-sources"), + beforeLaunchEcho("user:frontend", "frontend-built"), + server, + ) + 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, 820 + 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, "before-launch-"+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 configurations", func() bool { + s := &p.runConfigs + return s.generation > 0 && !s.loading && s.configuration("user:server") != nil + }) + + f := &p.runConfigs.form + h.app.post(func(a *App) { a.openRunConfigForm(p, "process.executable", "user:server") }) + awaitStateWithin(t, h, 10*time.Second, "the editor", func() bool { return f.open && !f.loading && f.beforeLaunch != nil }) + shot("editor") + h.app.post(func(a *App) { a.closeRunConfigForm(p) }) + + h.app.post(func(a *App) { a.runConfiguration(p, "user:server") }) + awaitStateWithin(t, h, 10*time.Second, "the confirmation", func() bool { return p.runConfigs.beforeLaunch != nil }) + shot("confirm") + h.app.post(func(a *App) { + ask := p.runConfigs.beforeLaunch + p.runConfigs.beforeLaunch = nil + ask.run() + }) + awaitProcessRun(t, h, p, "Server", nil) + shot("run-output") + }) + } +} diff --git a/desktop/internal/workbench/runconfig_edit.go b/desktop/internal/workbench/runconfig_edit.go index 20c0d79c7f..1fded14f6c 100644 --- a/desktop/internal/workbench/runconfig_edit.go +++ b/desktop/internal/workbench/runconfig_edit.go @@ -47,6 +47,11 @@ type runConfigEditor struct { // the picker's selection, 0 for none. installs []runConfigInstall pick int + // beforeLaunch is the IDs of the process runs that start first, as the editor shows them; + // savedBeforeLaunch is the list it opened with, so a save that did not change it leaves the + // layers as they are. beforeLaunchMenu says the menu that adds a step is open. + beforeLaunch, savedBeforeLaunch []string + beforeLaunchMenu bool } // runConfigInstall is one discovered installation a tool choice can be set to. @@ -110,6 +115,10 @@ func (a *App) openRunConfigEditor(p *project, id string) { directory: configuration.Cwd, environment: environmentText(configuration.Env), scope: "local", loading: true, } + for _, step := range configuration.BeforeLaunch { + e.beforeLaunch = append(e.beforeLaunch, step.Configuration) + } + e.savedBeforeLaunch = slices.Clone(e.beforeLaunch) if provider, ok := providerRunEditorState(*configuration); ok { e.provider, e.runtimeArguments, e.entrypoint, e.options, e.tools = true, provider.runtimeArguments, provider.entrypoint, provider.options, provider.tools if reference, ok := configuration.BuildReference(); ok { @@ -162,6 +171,13 @@ func (a *App) saveRunConfigEditor(p *project) { Root: p.root, Scope: e.scope, ConfigurationID: e.id, WorkingDirectory: strings.TrimSpace(e.directory), Arguments: e.arguments, Environment: environment, } + if !slices.Equal(e.beforeLaunch, e.savedBeforeLaunch) { + steps := slices.Clone(e.beforeLaunch) + if steps == nil { + steps = []string{} + } + edit.BeforeLaunch = &steps + } if e.provider { applyRunOptionFields(e) raw, err := providerRunOptionsJSON(e) @@ -189,6 +205,18 @@ func (a *App) saveRunConfigEditor(p *project) { }) } +// beforeLaunchCandidates is the process runs configuration id can run first: every built-in +// process run that can start, other than itself, as Core allows them. +func (s *runConfigState) beforeLaunchCandidates(id string) []core.RunConfigurationName { + var candidates []core.RunConfigurationName + for _, configuration := range s.list { + if configuration.ID != id && configuration.IsProcess() && !configuration.Unavailable() { + candidates = append(candidates, core.RunConfigurationName{ID: configuration.ID, Name: configuration.Name}) + } + } + return candidates +} + // 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 { diff --git a/desktop/internal/workbench/runconfig_form.go b/desktop/internal/workbench/runconfig_form.go index 3136c5d980..a68e946014 100644 --- a/desktop/internal/workbench/runconfig_form.go +++ b/desktop/internal/workbench/runconfig_form.go @@ -46,6 +46,10 @@ type runConfigForm struct { // environment is the variable rows in order; each row keeps its address while rows // are added or removed. environment []*runConfigVariable + // beforeLaunch is the IDs of the process runs that start before this one, in order; nil + // until the form names the field. beforeLaunchMenu says the menu that adds one is open. + beforeLaunch []string + beforeLaunchMenu bool // 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 @@ -81,6 +85,7 @@ const ( runFieldDirectory = "directory" runFieldEnvironment = "environment" runFieldExecutable = "executable" + runFieldBeforeLaunch = "beforeLaunch" ) // runFieldTextual reports a kind whose value is one string. @@ -230,6 +235,16 @@ func (f *runConfigForm) readValues(fields []core.RunEditorField, values map[stri f.environment = append(f.environment, &runConfigVariable{name: row.Name, value: row.Value}) } } + case field.Kind == runFieldBeforeLaunch: + if f.beforeLaunch == nil { + f.beforeLaunch = []string{} + if known { + _ = json.Unmarshal(raw, &f.beforeLaunch) + } + if f.beforeLaunch == nil { + f.beforeLaunch = []string{} + } + } case runFieldTextual(field.Kind): if f.texts[field.ID] == nil { text := "" @@ -260,6 +275,8 @@ func (f *runConfigForm) collect() map[string]json.RawMessage { rows = append(rows, map[string]string{"name": row.name, "value": row.value}) } value = rows + case field.Kind == runFieldBeforeLaunch && f.beforeLaunch != nil: + value = f.beforeLaunch case runFieldTextual(field.Kind) && f.texts[field.ID] != nil: value = *f.texts[field.ID] default: diff --git a/desktop/internal/workbench/runconfig_form_view.go b/desktop/internal/workbench/runconfig_form_view.go index 34b72e1459..a37ed95142 100644 --- a/desktop/internal/workbench/runconfig_form_view.go +++ b/desktop/internal/workbench/runconfig_form_view.go @@ -2,7 +2,9 @@ package workbench import ( "encoding/json" + "fmt" "reflect" + "slices" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" @@ -85,6 +87,8 @@ func runConfigFieldLabel(language i18n.Language, id string) (string, bool) { return i18n.Shared(language, "desktop.runConfig.fieldExecutionPolicyBypass"), true case "program": return i18n.Shared(language, "desktop.runConfig.fieldProgram"), true + case "beforeLaunch": + return i18n.Shared(language, "desktop.runConfig.fieldBeforeLaunch"), true } return "", false } @@ -98,6 +102,8 @@ func runConfigFieldHelp(language i18n.Language, field core.RunEditorField) strin return i18n.Shared(language, "desktop.runConfig.storeAsProjectFileHelp") case field.ID == "interpreter": return i18n.Shared(language, "desktop.runConfig.interpreterHelp") + case field.ID == "beforeLaunch": + return i18n.Shared(language, "desktop.runConfig.beforeLaunchHelp") } return "" } @@ -137,6 +143,8 @@ func runConfigFieldError(language i18n.Language, code string) string { return i18n.Shared(language, "desktop.runConfig.errorInvalidName") case "duplicate": return i18n.Shared(language, "desktop.runConfig.errorDuplicate") + case "unavailable": + return i18n.Shared(language, "desktop.runConfig.errorUnavailable") } return i18n.SharedFormat(language, "desktop.runConfig.errorOther", map[string]string{"code": code}) } @@ -152,6 +160,8 @@ func (f *runConfigForm) drawable(language i18n.Language, field core.RunEditorFie return f.flags[field.ID] != nil case runFieldEnvironment: return f.environment != nil + case runFieldBeforeLaunch: + return f.beforeLaunch != nil case runFieldChoice: for _, option := range field.Options { if _, ok := runConfigChoiceLabel(language, field.ID, option); !ok { @@ -310,7 +320,7 @@ func (a *App) drawRunConfigFormHeaderField(c ui.C, p *project, f *runConfigForm, 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 + tall := field.Kind == runFieldMultilineText || field.Kind == runFieldEnvironment || field.Kind == runFieldBeforeLaunch ui.Column(c).FillWidth().Gap(4).Children(func() { row := ui.Row(c).FillWidth().Gap(12) if tall { @@ -355,6 +365,8 @@ func (a *App) drawRunConfigFormControl(c ui.C, p *project, f *runConfigForm, fie switch field.Kind { case runFieldEnvironment: a.drawRunConfigVariables(c, p, f, ready) + case runFieldBeforeLaunch: + a.drawRunConfigBeforeLaunch(c, &f.beforeLaunch, &f.beforeLaunchMenu, field.Candidates, ready) case runFieldChoice: options := field.Options if ui.Choice(c, f.texts[field.ID], options, func(option string) string { @@ -412,6 +424,85 @@ func (a *App) drawRunConfigVariables(c ui.C, p *project, f *runConfigForm, ready }) } +// runConfigBeforeLaunchLimit is the most steps a configuration names, as Core allows. +const runConfigBeforeLaunchLimit = 16 + +// drawRunConfigBeforeLaunch declares the steps that run before the configuration, each its name +// with buttons that move it up or down or remove it, and the button whose menu adds one of the +// process runs not chosen yet. A step whose configuration is gone shows its ID. +func (a *App) drawRunConfigBeforeLaunch(c ui.C, chosen *[]string, menuOpen *bool, candidates []core.RunConfigurationName, ready bool) { + language := a.language() + steps := *chosen + names := make(map[string]string, len(candidates)) + for _, candidate := range candidates { + names[candidate.ID] = candidate.Name + } + ui.Column(c.Part("before-launch")).Grow(1).MinWidth(0).Gap(4).Children(func() { + if len(steps) == 0 { + ui.Text(c, i18n.Shared(language, "desktop.runConfig.beforeLaunchEmpty")).Color(a.colors.Subtle).LineHeight(28) + } + for index, id := range steps { + k := c.KeyInt(index) + name, known := names[id] + if !known { + name = i18n.SharedFormat(language, "desktop.runConfig.beforeLaunchMissing", map[string]string{"id": id}) + } + ui.Row(k).FillWidth().MinHeight(28).Items(ui.Center).Gap(4).Children(func() { + ui.Icon(k, icons.Play).Size(14, 14).Shrink(0).Color(a.colors.Subtle) + color := a.colors.Text + if !known { + color = a.theme.Danger + } + ui.Text(k, fmt.Sprintf("%d. %s", index+1, name)).Color(color).Ellipsis().Grow(1).MinWidth(0) + if a.gitIconButton(k.Part("up"), i18n.Shared(language, "desktop.runConfig.beforeLaunchUp"), icons.ArrowUp, false, !ready || index == 0) { + c.After(func() { moveRunConfigStep(*chosen, index, index-1) }) + } + if a.gitIconButton(k.Part("down"), i18n.Shared(language, "desktop.runConfig.beforeLaunchDown"), icons.ArrowDown, false, !ready || index == len(steps)-1) { + c.After(func() { moveRunConfigStep(*chosen, index, index+1) }) + } + if a.gitIconButton(k.Part("remove"), i18n.Shared(language, "desktop.runConfig.beforeLaunchRemove"), icons.Trash2, false, !ready) { + c.After(func() { *chosen = slices.Delete(slices.Clone(*chosen), index, index+1) }) + } + }) + } + var left []core.RunConfigurationName + for _, candidate := range candidates { + if !slices.Contains(steps, candidate.ID) { + left = append(left, candidate) + } + } + full := len(steps) >= runConfigBeforeLaunchLimit + add := ui.Button(c.Part("add"), i18n.Shared(language, "desktop.runConfig.beforeLaunchAdd")).Icon(icons.Plus).Ghost(). + Disabled(!ready || len(left) == 0 || full) + if len(candidates) == 0 { + add = add.Tooltip(i18n.Shared(language, "desktop.runConfig.beforeLaunchNoCandidates")) + } + if add.Clicked() { + c.After(func() { *menuOpen = !*menuOpen }) + } + if *menuOpen { + ui.Menu(c.Part("add-menu"), add, menuOpen, func(menu *ui.MenuItems) { + for _, candidate := range left { + if menu.Item(candidate.Name).Clicked() { + c.After(func() { + a.performed("run.configuration.form.beforeLaunch.add", surfaceButton) + *chosen = append(slices.Clone(*chosen), candidate.ID) + }) + } + } + }) + } + }) +} + +// moveRunConfigStep swaps the step at from with the one at to, when both exist. +func moveRunConfigStep(steps []string, from, to int) { + if from < 0 || to < 0 || from >= len(steps) || to >= len(steps) { + return + } + steps[from], steps[to] = steps[to], steps[from] +} + // removeRunConfigVariable is rows without row. func removeRunConfigVariable(rows []*runConfigVariable, row *runConfigVariable) []*runConfigVariable { kept := make([]*runConfigVariable, 0, len(rows)) diff --git a/desktop/internal/workbench/runconfig_process.go b/desktop/internal/workbench/runconfig_process.go index dce23668f7..a19ef954b9 100644 --- a/desktop/internal/workbench/runconfig_process.go +++ b/desktop/internal/workbench/runconfig_process.go @@ -51,7 +51,7 @@ func (a *App) startProcessRun(p *project, configuration core.RunConfiguration) * a.endBuildOperation(p, op, "failed", nil, "unsaved documents could not be saved", "") return } - a.launchProcessRun(p, op, id) + a.runBeforeLaunch(p, op, id, func() { a.launchProcessRun(p, op, id) }) }) return op } @@ -66,35 +66,10 @@ func (a *App) launchProcessRun(p *project, op *buildOperation, id string) { 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) { + process, cleanup, err := a.startConfiguredProcess(prepare, ctx, kernel, language, root, id, func(text string) { a.streamBuildOutput(p, op, text) }) + defer cleanup() if err != nil { return func(a *App) { a.finishBuildError(p, op, err) } } @@ -104,6 +79,43 @@ func (a *App) launchProcessRun(p *project, op *buildOperation, id string) { }) } +// startConfiguredProcess plans the built-in process run id under prepare and starts its +// process under run, which ends it when it ends; output receives what the process prints. +// cleanup removes the temporary directory of a script saved as text once the process +// exited, and is always set. It runs off the window thread, with the kernel and language +// taken on it. +func (a *App) startConfiguredProcess(prepare, run context.Context, kernel Kernel, language i18n.Language, root, id string, output func(string)) (*buildprocess.Process, func(), error) { + cleanup := func() {} + scratch, err := os.MkdirTemp("", inlineScriptDirectoryPattern) + if err != nil { + return nil, cleanup, err + } + cleanup = func() { + if err := os.RemoveAll(scratch); err != nil { + a.backgroundFailedIn(run, "run_inline_script_cleanup", err) + } + } + plan, err := kernel.CreateRunLaunchPlan(prepare, root, id, filepath.Join(scratch, "script")) + if err != nil { + return nil, cleanup, 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 nil, cleanup, err + } + process, err := buildprocess.Start(run, spec, func(_ buildprocess.Stream, text string) { output(text) }) + return process, cleanup, 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. diff --git a/desktop/internal/workbench/runconfig_view.go b/desktop/internal/workbench/runconfig_view.go index 3c599b8754..acc43de36a 100644 --- a/desktop/internal/workbench/runconfig_view.go +++ b/desktop/internal/workbench/runconfig_view.go @@ -360,6 +360,14 @@ func (a *App) drawRunConfigEditor(c ui.C, p *project) { a.drawRunOptionField(c.Part("option-"+strconv.Itoa(index)), language, &e.optionFields[index], ready) } } + ui.Column(c.Part("before-launch-field")).FillWidth().Gap(4).Children(func() { + ui.Row(c).FillWidth().Items(ui.Center).Gap(4).Children(func() { + ui.Text(c, i18n.Shared(language, "desktop.runConfig.fieldBeforeLaunch")).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) + ui.Button(c.Part("help"), i18n.Shared(language, "native.moreInformation")).Icon(icons.Info).IconOnly().Ghost(). + Size(18, 18).Shrink(0).Tooltip(i18n.Shared(language, "desktop.runConfig.beforeLaunchHelp")).TooltipOn(ui.TooltipRight) + }) + a.drawRunConfigBeforeLaunch(c, &e.beforeLaunch, &e.beforeLaunchMenu, p.runConfigs.beforeLaunchCandidates(e.id), ready) + }) labels := map[string]string{"local": i18n.Shared(language, "desktop.runConfig.scopeLocal"), "project": i18n.Shared(language, "desktop.runConfig.scopeProject")} ui.Select(c.Part("scope"), &e.scope, []string{"local", "project"}, func(scope string) string { return labels[scope] }). Label(i18n.Shared(language, "desktop.runConfig.scope")).FillWidth() diff --git a/docs/assets/before-launch/before-launch-confirm-dark.png b/docs/assets/before-launch/before-launch-confirm-dark.png new file mode 100644 index 0000000000..01d5c01398 Binary files /dev/null and b/docs/assets/before-launch/before-launch-confirm-dark.png differ diff --git a/docs/assets/before-launch/before-launch-confirm-light.png b/docs/assets/before-launch/before-launch-confirm-light.png new file mode 100644 index 0000000000..4b7fc1d960 Binary files /dev/null and b/docs/assets/before-launch/before-launch-confirm-light.png differ diff --git a/docs/assets/before-launch/before-launch-editor-dark.png b/docs/assets/before-launch/before-launch-editor-dark.png new file mode 100644 index 0000000000..19920f8133 Binary files /dev/null and b/docs/assets/before-launch/before-launch-editor-dark.png differ diff --git a/docs/assets/before-launch/before-launch-editor-light.png b/docs/assets/before-launch/before-launch-editor-light.png new file mode 100644 index 0000000000..1c6ded7b48 Binary files /dev/null and b/docs/assets/before-launch/before-launch-editor-light.png differ diff --git a/docs/assets/before-launch/before-launch-run-output-dark.png b/docs/assets/before-launch/before-launch-run-output-dark.png new file mode 100644 index 0000000000..2b5f1d153d Binary files /dev/null and b/docs/assets/before-launch/before-launch-run-output-dark.png differ diff --git a/docs/assets/before-launch/before-launch-run-output-light.png b/docs/assets/before-launch/before-launch-run-output-light.png new file mode 100644 index 0000000000..c33f4f2623 Binary files /dev/null and b/docs/assets/before-launch/before-launch-run-output-light.png differ diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 44cca052a5..2961ea96b4 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -27,15 +27,17 @@ 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, +# Lithe-core-rust main at bb4832e, #88 squash-merged (on top of 4ed7a1f, #85): a run +# configuration's beforeLaunch names built-in process runs that start first; runConfig.beforeLaunch +# expands and checks them and fingerprints the lists a project file names, the editor form has a +# beforeLaunch field and runConfig.updateOptions takes the list (#1616). #85, squash-merged into +# main as 4ed7a1f (on top of 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 @@ -208,7 +210,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="7381e79a7705e9741ed3ff76c459c7a762484783" +PINNED_CORE_REVISION="bb4832ee73187c8dffcbd67eb4a68e839869252b" 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 265d772323..91686447a8 100644 --- a/shared/i18n/locales/en-US.json +++ b/shared/i18n/locales/en-US.json @@ -11484,6 +11484,28 @@ "desktop.runConfig.errorInvalidName": "Invalid variable name", "desktop.runConfig.errorDuplicate": "Duplicate variable name", "desktop.runConfig.errorOther": "Invalid value ({code})", + "desktop.runConfig.beforeLaunch.confirmBody": "Before {name} starts, the project's run configuration file asks to run these commands. Run them only if you trust this project.", + "desktop.runConfig.beforeLaunch.confirmRun": "Run Steps", + "desktop.runConfig.beforeLaunch.confirmTitle": "Run steps from the project file?", + "desktop.runConfig.beforeLaunch.exited": "Before-launch step {name} exited with code {code}; the configuration was not started.", + "desktop.runConfig.beforeLaunch.failed": "Before-launch step {name} could not run: {reason}", + "desktop.runConfig.beforeLaunch.refused.cycle": "Before-launch steps form a loop at {step}.", + "desktop.runConfig.beforeLaunch.refused.notAllowed": "{step} cannot be a before-launch step: only shell, PowerShell, batch and executable runs can.", + "desktop.runConfig.beforeLaunch.refused.notFound": "A before-launch step names configuration {step}, which does not exist.", + "desktop.runConfig.beforeLaunch.refused.other": "Before-launch step {step} cannot run.", + "desktop.runConfig.beforeLaunch.refused.tooLong": "Too many before-launch steps at {step}: at most 32 run once nested steps are expanded.", + "desktop.runConfig.beforeLaunch.refused.unavailable": "Before-launch step {step} is not available on this system.", + "desktop.runConfig.beforeLaunch.stepHeader": "Before launch ({index}/{count}): {name}", + "desktop.runConfig.beforeLaunchAdd": "Add step", + "desktop.runConfig.beforeLaunchDown": "Move down", + "desktop.runConfig.beforeLaunchEmpty": "No steps", + "desktop.runConfig.beforeLaunchHelp": "Process runs that start, in order, before this configuration. It starts only after each of them exits with code 0.", + "desktop.runConfig.beforeLaunchMissing": "Missing configuration {id}", + "desktop.runConfig.beforeLaunchNoCandidates": "Create a shell, PowerShell, batch or executable run first to use it as a step.", + "desktop.runConfig.beforeLaunchRemove": "Remove step", + "desktop.runConfig.beforeLaunchUp": "Move up", + "desktop.runConfig.errorUnavailable": "Not available on this system", + "desktop.runConfig.fieldBeforeLaunch": "Before launch", "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}", diff --git a/shared/i18n/locales/zh-CN.json b/shared/i18n/locales/zh-CN.json index fad05d54fc..3d33b07d24 100644 --- a/shared/i18n/locales/zh-CN.json +++ b/shared/i18n/locales/zh-CN.json @@ -11484,6 +11484,28 @@ "desktop.runConfig.errorInvalidName": "变量名无效", "desktop.runConfig.errorDuplicate": "变量名重复", "desktop.runConfig.errorOther": "值无效({code})", + "desktop.runConfig.beforeLaunch.confirmBody": "启动 {name} 前,项目的运行配置文件要求先运行以下命令。只有信任此项目时才运行。", + "desktop.runConfig.beforeLaunch.confirmRun": "运行步骤", + "desktop.runConfig.beforeLaunch.confirmTitle": "运行项目文件中的启动前步骤?", + "desktop.runConfig.beforeLaunch.exited": "启动前步骤 {name} 以退出码 {code} 结束,未启动配置。", + "desktop.runConfig.beforeLaunch.failed": "启动前步骤 {name} 无法运行:{reason}", + "desktop.runConfig.beforeLaunch.refused.cycle": "启动前步骤在 {step} 处形成循环。", + "desktop.runConfig.beforeLaunch.refused.notAllowed": "{step} 不能作为启动前步骤:只有 Shell、PowerShell、批处理和可执行文件运行配置可以。", + "desktop.runConfig.beforeLaunch.refused.notFound": "启动前步骤引用的配置 {step} 不存在。", + "desktop.runConfig.beforeLaunch.refused.other": "启动前步骤 {step} 无法运行。", + "desktop.runConfig.beforeLaunch.refused.tooLong": "启动前步骤在 {step} 处过多:展开嵌套步骤后最多 32 个。", + "desktop.runConfig.beforeLaunch.refused.unavailable": "启动前步骤 {step} 在此系统上不可用。", + "desktop.runConfig.beforeLaunch.stepHeader": "启动前步骤 ({index}/{count}): {name}", + "desktop.runConfig.beforeLaunchAdd": "添加步骤", + "desktop.runConfig.beforeLaunchDown": "下移", + "desktop.runConfig.beforeLaunchEmpty": "无步骤", + "desktop.runConfig.beforeLaunchHelp": "启动此配置前按顺序运行的进程配置。每一个都以退出码 0 结束后,才会启动此配置。", + "desktop.runConfig.beforeLaunchMissing": "找不到配置 {id}", + "desktop.runConfig.beforeLaunchNoCandidates": "先创建 Shell、PowerShell、批处理或可执行文件运行配置,才能把它作为步骤。", + "desktop.runConfig.beforeLaunchRemove": "移除步骤", + "desktop.runConfig.beforeLaunchUp": "上移", + "desktop.runConfig.errorUnavailable": "在此系统上不可用", + "desktop.runConfig.fieldBeforeLaunch": "启动前", "desktop.runConfig.formTooNew": "这个运行配置需要更新版本的 Lithe 才能编辑。", "desktop.runConfig.programNotFound": "在 PATH 中找不到“{program}”,请填写解释器或程序的完整路径。", "desktop.runConfig.documentIgnored": "未读取 {file} 中的运行配置", diff --git a/shared/i18n/messages.json b/shared/i18n/messages.json index 4ae3ec8c38..46abc76ee6 100644 --- a/shared/i18n/messages.json +++ b/shared/i18n/messages.json @@ -15793,6 +15793,197 @@ "code": "string" } }, + { + "id": "desktop.runConfig.beforeLaunch.confirmBody", + "description": "Body of the before-launch confirmation; name is the configuration that starts.", + "platforms": [ + "desktop" + ], + "parameters": { + "name": "string" + } + }, + { + "id": "desktop.runConfig.beforeLaunch.confirmRun", + "description": "Button of the before-launch confirmation that runs the steps and remembers the choice.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.beforeLaunch.confirmTitle", + "description": "Title of the dialog asking whether to run the before-launch steps a project file names.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.beforeLaunch.exited", + "description": "Console line and error when a before-launch step exited with a code other than 0.", + "platforms": [ + "desktop" + ], + "parameters": { + "name": "string", + "code": "string" + } + }, + { + "id": "desktop.runConfig.beforeLaunch.failed", + "description": "Console line and error when a before-launch step could not start.", + "platforms": [ + "desktop" + ], + "parameters": { + "name": "string", + "reason": "string" + } + }, + { + "id": "desktop.runConfig.beforeLaunch.refused.cycle", + "description": "Error when before-launch steps refer back to each other.", + "platforms": [ + "desktop" + ], + "parameters": { + "step": "string" + } + }, + { + "id": "desktop.runConfig.beforeLaunch.refused.notAllowed", + "description": "Error when a before-launch step names a configuration that is not a process run.", + "platforms": [ + "desktop" + ], + "parameters": { + "step": "string" + } + }, + { + "id": "desktop.runConfig.beforeLaunch.refused.notFound", + "description": "Error when a before-launch step names a configuration that does not exist.", + "platforms": [ + "desktop" + ], + "parameters": { + "step": "string" + } + }, + { + "id": "desktop.runConfig.beforeLaunch.refused.other", + "description": "Error when before-launch steps cannot run for a reason this version does not know.", + "platforms": [ + "desktop" + ], + "parameters": { + "step": "string" + } + }, + { + "id": "desktop.runConfig.beforeLaunch.refused.tooLong", + "description": "Error when nested before-launch steps expand to more than the limit.", + "platforms": [ + "desktop" + ], + "parameters": { + "step": "string" + } + }, + { + "id": "desktop.runConfig.beforeLaunch.refused.unavailable", + "description": "Error when a before-launch step cannot run on this system.", + "platforms": [ + "desktop" + ], + "parameters": { + "step": "string" + } + }, + { + "id": "desktop.runConfig.beforeLaunch.stepHeader", + "description": "Console line before one before-launch step starts.", + "platforms": [ + "desktop" + ], + "parameters": { + "index": "string", + "count": "string", + "name": "string" + } + }, + { + "id": "desktop.runConfig.beforeLaunchAdd", + "description": "Button whose menu adds a process run as a before-launch step.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.beforeLaunchDown", + "description": "Button that moves a before-launch step down.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.beforeLaunchEmpty", + "description": "Shown in the before-launch field when the configuration has no steps.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.beforeLaunchHelp", + "description": "Tip of the before-launch field of a run configuration.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.beforeLaunchMissing", + "description": "A before-launch step whose configuration no longer exists; id is the configuration ID.", + "platforms": [ + "desktop" + ], + "parameters": { + "id": "string" + } + }, + { + "id": "desktop.runConfig.beforeLaunchNoCandidates", + "description": "Tooltip of the disabled add-step button when the project has no process run to use.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.beforeLaunchRemove", + "description": "Button that removes a before-launch step.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.beforeLaunchUp", + "description": "Button that moves a before-launch step up.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.errorUnavailable", + "description": "Error under a run configuration field naming a configuration that cannot run on this system.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.runConfig.fieldBeforeLaunch", + "description": "Title of the run configuration field listing the process runs that start before it.", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.runConfig.formTooNew", "description": "Shown in the run configuration editor when Core describes the form in a newer version than this app understands.", diff --git a/shared/platform-feature-matrix/features/run-before-launch-steps.json b/shared/platform-feature-matrix/features/run-before-launch-steps.json new file mode 100644 index 0000000000..6cdc58ab80 --- /dev/null +++ b/shared/platform-feature-matrix/features/run-before-launch-steps.json @@ -0,0 +1,31 @@ +{ + "id": "run-before-launch-steps", + "area": "运行与调试", + "group": "运行配置", + "capability": "像 IntelliJ IDEA 的 Before launch: Run Another Configuration 一样,运行配置可以列出启动前步骤:每一步是一个内置进程运行(Shell、PowerShell、批处理、可执行程序),按顺序在同一个 Run 控制台里运行,全部以退出码 0 结束后才启动配置;某一步失败时报出步骤名和退出码并不启动配置,停止配置会停止正在运行的步骤。项目文件(.lithe/run/configurations.yaml)列出的步骤第一次运行前要确认,确认结果按步骤列表与命令的指纹记在应用自己的存储里", + "owner": "Run", + "notes": "Viva 共享实现。步骤只能引用内置进程运行,嵌套步骤先展开、最多 32 步,引用不存在、不可用、成环的配置时由 Core 拒绝。内置运行编辑器和构建提供者运行编辑器都有步骤列表,可添加、上移、下移、移除。调试(Debug)同样先运行步骤。插件可注入的 runOptions 扩展点不在本项范围。", + "verification": "在项目里创建两个 Shell 运行 A、B,并让应用运行配置的启动前步骤依次为 A、B;运行应用配置,确认弹出确认框列出 A、B,点“运行步骤”后控制台依次出现 A、B 的输出和应用输出;再次运行不再询问。把 B 改成以 3 退出,确认控制台写出“启动前步骤 B 以退出码 3 结束”,应用未启动。把 A 改成长时间运行,运行中点停止,确认 A 被结束、应用未启动。自动化:runconfig_before_launch_test.go 的 TestBeforeLaunchStepsRunInOrderAfterTheProjectListIsAllowed、TestFailingBeforeLaunchStepStopsTheStart、TestStoppingDuringABeforeLaunchStepEndsIt、TestRunConfigFormKeepsTheStepList。", + "macos": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/workbench/runconfig_before_launch.go", + "desktop/internal/workbench/runconfig_form_view.go", + "desktop/internal/workbench/runconfig_edit.go", + "desktop/internal/core/run_before_launch.go", + "desktop/internal/workbench/runconfig_before_launch_test.go" + ] + }, + "windows": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/workbench/runconfig_before_launch.go", + "desktop/internal/workbench/runconfig_form_view.go", + "desktop/internal/workbench/runconfig_edit.go", + "desktop/internal/core/run_before_launch.go", + "desktop/internal/workbench/runconfig_before_launch_test.go" + ] + } +}