diff --git a/.agents/notes/implemented/architecture/2026-10-26-build-provider-task-execution.md b/.agents/notes/implemented/architecture/2026-10-26-build-provider-task-execution.md index f2274a816e..4bed2b9ad0 100644 --- a/.agents/notes/implemented/architecture/2026-10-26-build-provider-task-execution.md +++ b/.agents/notes/implemented/architecture/2026-10-26-build-provider-task-execution.md @@ -32,6 +32,12 @@ Core 继续校验工程/目标/模型任务选择、路径与生效选项,返 插件显式声明 `test.discovery`,同时支持套件和用例筛选,原生窗口才提供发现入口。用户展开“已发现的测试”或点击发现时,宿主通过协议 3 的 `lithe/build/discoverTests` 请求整个实例的清单;不会在打开工程时扫描源码或后台执行工具。列表里的每个条目都必须能通过同一测试计划精确运行,Core(共享校验层)拒绝错误范围、路径、筛选类型和超限清单,不用部分成功假装已经列全测试。 +Viva 也支持插件声明一次性发现命令。它适合能直接请现有测试引擎列出用例的工具,因而可以沿用同一测试树而无需为了发现常驻后端。用户点击发现后,宿主用共享构建进程运行 Core 生成的参数,报告放进插件的工作区可写状态,以临时目录隔离并在操作结束后清理。Core 把命令报告和后端结果交给同一套选择校验。宿主按统一日志记录命令终态,源码或实例变化时取消在途命令并丢弃旧结果。 + +一次性发现沿用插件的原生启动登记,由各工作台持有到进程退出和报告目录清理完毕。关闭项目会取消命令,随后卸载仍能等待该工作台的登记,包括已离开标签栏的工作台。停用、被替换为其他语言服务提供方或卸载时,先撤销该插件的发现结果、阻断新命令,再等待清理。用 `TestPluginTeardownWaitsForBuildCommandDiscovery` 和 `TestPluginTeardownWaitsForDiscoveryAfterProjectCloses` 验证共用的清理入口。 + +命令发现计划使用当前工作区信任。Core 会在安全模式拒绝标明执行项目代码的命令。`TestBuildCommandDiscoversExactTestsAndRecordsItsResult` 覆盖信任项目下的发现与精确执行计划,以及安全模式的拒绝。 + 插件复用其已选择的上游测试引擎回答套件、用例、工程及目标;宿主只显示现有共享树的节点。不增加另一套 Java 注解扫描、框架探测、工程图或 Test Explorer。条目身份包括工程和目标,所以两个模块中的同名测试不会互相覆盖。 发现和执行共用唯一原生操作槽及工作区进程,避免又建一个后台任务运行时。加载状态、成功空列表和失败是不同结果;失败可由用户重试。发现缓存仅在同一插件包、生效选项、启动设置及配置代次下可用,任何工作区源码修改都会清除清单,并取消正在进行的发现。旧工具栏选择运行前必须用 ID 重新查验当前清单,不能只保存旧请求然后直接执行。停用、更新、工作区重开和退出继续通过既有会话释放资源;报告和清单不写进插件包。 diff --git a/.agents/notes/implemented/architecture/2026-11-16-local-shell-integration-shim.md b/.agents/notes/implemented/architecture/2026-11-16-local-shell-integration-shim.md index 59190b93fc..c5cc53dc7b 100644 --- a/.agents/notes/implemented/architecture/2026-11-16-local-shell-integration-shim.md +++ b/.agents/notes/implemented/architecture/2026-11-16-local-shell-integration-shim.md @@ -106,7 +106,8 @@ Motty 有开关。没有采用:只在命令行输入区、单击且未拖动 - 收益:本地 bash/zsh、WSL 和带 PSReadLine 的 PowerShell 里,提示符处调整大小不再留下重复提示符;单击命令行可以移动光标。Windows PowerShell/cmd 的提示符上报首次真正启用。 - 代价:每次启动本地 bash/zsh 多运行一次 `sh`(随即变成 Shell,不常驻);`TMPDIR` 下会短暂出现一个私有目录;第一个提示符上点击不生效。 -- 关闭时等 Shell 回到提示符再挂断(#2005):bash 只在“算作交互状态”时把挂断转给后台任务,它运行 `PROMPT_COMMAND`(集成也用它)期间不算。挂断如果落在这段时间里,bash 会退出,但后台任务留了下来。因此 `localshell.Shell` 在读输出时跟踪本会话带令牌的 A–D 标记(`prompt_marks.go`)。Shell 显示过提示符后,如果关闭时它正处在“命令结束到下一个提示符出现”之间(上一个标记不是 B,也不是“C 之后前台还有程序在跑”),挂断就推迟到它打出 B 标记、自己结束,或者最多等 1 秒(`promptGrace`),然后照常挂断,0.5 秒后强制结束。到 B 时 bash 已经回到交互状态,会把挂断转给后台任务。还没出过第一个提示符、或者没有集成的 Shell,照旧立即挂断。关闭后读端继续读输出但直接丢弃,这样内存不会增长,也能看到 B 标记。窗口退出要等每个 Shell 结束,所以最多多等约 1 秒。 +- 关闭集成终端时等 Shell 回到提示符再挂断(#2005、[#2054](https://github.com/1lck/Lithe-IDEA/issues/2054))。Bash 运行 `PROMPT_COMMAND` 时可能无法把挂断转给后台任务。提示符钩子也能启动前台程序,所以前台进程组无法区分正在运行的用户命令和提示符钩子。显示过提示符的 Shell 如还未打出下一个 B 标记,就继续读取并丢弃输出,最多等原有的 1 秒宽限再发送 SIGHUP。未经集成或还没有提示符的 Shell 立即挂断。 +- 伪终端主端(PTY master)留到 Shell 退出并完成有界输出排空。Unix 上关闭主端会让 Shell 的读端看到 EOF 或 EIO,与 Bash 处理 SIGHUP 的顺序产生竞争。保留主端使 Bash 有机会把信号转给自己的任务。Linux 并发复现显示,Bash 打出 B 标记后仍可能错过第一次 SIGHUP,0.5 秒后被强制结束而后台任务仍在运行。集成 Bash 在提示符处挂断后,若 100 毫秒内仍未完成关闭,再给 Shell 发一次 SIGHUP,让进入输入循环的 Bash 转发;0.5 秒强制结束宽限不变。 - 不要这样做:给会话里所有进程组都发挂断。用户 `disown` 掉的任务会被一起结束;挂断交给 Shell 转发,`disown`/`disown -h` 的语义才能保留。其他终端(如 Ghostty)也只挂断 Shell 自己的进程组。 - 仍然存在的限制:没有集成、但用户自己配了 `PROMPT_COMMAND` 的 bash 不变。zsh 只有在后台任务刚 fork、还没 exec 的约 1 毫秒里被挂断时才会留下任务,这个窗口没有标记可以等,不处理。一直不回提示符的 Shell(例如在 `PROMPT_COMMAND` 里死循环)在 1 秒后照常挂断。 - 没有消费方的回调和目录上报已由 #1984 删除,见“只上报有消费方的内容”。 @@ -116,6 +117,7 @@ Motty 有开关。没有采用:只在命令行输入区、单击且未拖动 ## 验证 - `./scripts/desktop/desktop-go.sh test ./internal/localshell/... ./internal/term/... ./internal/termview/... -count=1`:真实 bash/zsh 经垫片启动并上报提示符和命令,第一个提示符出现时启动目录已删除;挂断能结束 Shell 和后台任务;命令刚结束、bash 还在运行 `PROMPT_COMMAND`(包括慢的 `PROMPT_COMMAND`)时关闭,后台任务也会结束(`TestClosingAnIntegratedShellRightAfterACommandHangsUpItsJobs`,关掉推迟后 bash 的三个用例都会失败);一直不回提示符的 Shell 在宽限期后结束(`TestClosingAnIntegratedShellThatNeverPromptsStillEndsIt`);标记识别跨分片、只认本会话令牌(`TestPromptMarks*`、`TestPromptMarksAcrossEverySplit`);命令结束只在退出码有效时收回输入模式(`TestACommandEndReclaimsOnlyWithAValidStatus`);WSL 脚本在起始目录启动登录 Shell(`TestWSLScriptStartsTheLoginShellInTheStartFolder`);启动文件还在运行时关闭,Shell 被结束、目录被删除(`TestClosingAShellDuringItsStartupRemovesItsPrivateDirectory`);令牌每次启动更换;提示符处尺寸保持后只发一次;点击按条件发送方向键。 +- `TestCloseLetsTheShellHandleHangupBeforeReleasingThePTY` 用可控后端验证关闭顺序。即使提示符钩子占用前台进程组,也先等 B 标记,发出挂断后再等 Shell 退出,最后关闭主端。 - 运行 `./internal/workbench/` 测试前后统计 `TMPDIR` 下的 `motty-shell.*` 目录,数量不变。 - `scripts/desktop/verify/verify-runtime-bundle-immutability.sh`:确认运行时没有写入发行目录。 - 在 Windows 上运行 `TestWindowsShellsMarkTheirPromptsUnderTheToken`(PowerShell 在下一个提示符前标记命令开始、屏幕开启两项功能,cmd 不标记)、`TestPowerShellReadLineIntegrationMarksTheCommandStart`、`TestPowerShellPromptIntegrationPreservesCustomPromptAndExitStatus`,它们只在 Windows 编译。 diff --git a/.agents/notes/implemented/feature/2026-11-19-workspace-trust-and-safe-mode.md b/.agents/notes/implemented/feature/2026-11-19-workspace-trust-and-safe-mode.md index e54ed0a2f1..a1732f0564 100644 --- a/.agents/notes/implemented/feature/2026-11-19-workspace-trust-and-safe-mode.md +++ b/.agents/notes/implemented/feature/2026-11-19-workspace-trust-and-safe-mode.md @@ -12,7 +12,7 @@ Maven 这类命令来源的模型会运行 `mvn`,pom 里的扩展和插件就 ## 决策 -- **三种状态由 Core 判定。** Core 的工具链目录记着信任过的工作区、明确不信任的工作区和信任的位置(父文件夹)。`toolchains.catalogState` 返回 `workspaceTrust`(`trusted`、`distrusted`、`unknown`,以及可以提供的父文件夹);显式决定优先于位置,和 IDEA 的 `TrustedPaths` 一致。根目录、盘符和网络共享根不作为可信位置提供。 +- **三种状态由 Core 判定。** Core 的工具链目录记着信任过的工作区、明确不信任的工作区和信任的位置(父文件夹)。`toolchains.catalogState` 返回 `workspaceTrust`(`trusted`、`distrusted`、`unknown`,以及可以提供的父文件夹);显式决定优先于位置,和 IDEA 的 `TrustedPaths` 一致。根目录、盘符和网络共享根不作为可信位置提供。Core 返回的父文件夹路径在生成复选框标签时转换为当前平台的显示格式,再缩写主目录或长路径。 - **Core 拒绝会运行项目代码的计划。** 计划请求带 `projectCodeAllowed`;为假时,命令模型(清单标了 `executesProjectCode`)、执行类提供者计划和声明了运行项目代码的提供者都会被拒绝,错误码 `plugin.build.untrustedWorkspace`。宿主只负责把项目当前的信任带进请求(`desktop/internal/workbench` 中 11 处请求都填 `p.trust.allowed()`),不自己判断哪些计划危险。 - **先问再打开。** `openProjectHere` 先读信任(`toolchain.ReadWorkspaceTrust`),再决定直接打开、以安全模式打开或提问;选“不打开”时当前项目原样保留,新开的项目页签直接关掉。“以安全模式预览”记成不信任,下次打开不再问,和 IDEA 的 `setProjectTrusted(false)` 相同。 - **安全模式下的动作先问。** `startRun`、`runBuildTask`、`startTests`、运行当前文件和重新加载模型前,安全模式会弹出“信任项目?/ 保持安全模式”。信任保存成功后才执行原动作;保存失败按未信任处理。自动加载的模型不运行,构建窗口在模型位置显示安全模式说明。 diff --git a/.github/workflows/desktop-ci.yml b/.github/workflows/desktop-ci.yml index 4cf9e178ed..772e29cc33 100644 --- a/.github/workflows/desktop-ci.yml +++ b/.github/workflows/desktop-ci.yml @@ -169,6 +169,25 @@ jobs: - name: Vet and test run: ./scripts/desktop/check.sh + - name: Run command test discovery headless + id: build-command-discovery-visual + if: ${{ !cancelled() && steps.rust.outcome == 'success' }} + timeout-minutes: 5 + env: + LITHE_VISUAL_OUTPUT_DIR: ${{ github.workspace }}/.artifacts/build-command-discovery-visual + run: | + ./scripts/desktop/desktop-go.sh test -v -tags 'vivahead lithevisual' ./internal/workbench \ + -run '^TestVisualBuildCommandDiscovery$' -count=1 -timeout=120s + + - name: Upload command test discovery screenshots + if: ${{ !cancelled() && steps.build-command-discovery-visual.outcome != 'skipped' }} + uses: actions/upload-artifact@v7 + with: + name: build-command-discovery-visual-${{ runner.os }}-${{ runner.arch }} + path: .artifacts/build-command-discovery-visual/*.png + if-no-files-found: error + retention-days: 14 + - name: Run LSP editor headless tests id: lsp-visual # Capture evidence even when an unrelated test in the full suite fails. diff --git a/desktop/internal/core/plugin_operation.go b/desktop/internal/core/plugin_operation.go index 3bc1923983..b19b809623 100644 --- a/desktop/internal/core/plugin_operation.go +++ b/desktop/internal/core/plugin_operation.go @@ -22,6 +22,8 @@ const ( OperationDebugAdapterStart PluginOperationName = "debugAdapter/start" // OperationBuildModel is one model load of a buildSystems[].model command source. OperationBuildModel PluginOperationName = "lithe/build/model" + // OperationBuildTestDiscovery is one test discovery command. + OperationBuildTestDiscovery PluginOperationName = "lithe/build/discoverTests" // OperationBuildDependencies is one dependency tree load of a command source. OperationBuildDependencies PluginOperationName = "lithe/build/dependencies" // OperationCommandInstallerInstall is one commandInstallers[] installation the user diff --git a/desktop/internal/core/plugin_operation_test.go b/desktop/internal/core/plugin_operation_test.go index e338440672..816994c7cb 100644 --- a/desktop/internal/core/plugin_operation_test.go +++ b/desktop/internal/core/plugin_operation_test.go @@ -162,7 +162,7 @@ func TestCoreTakesEveryResultTheHostRecords(t *testing.T) { } contributions := map[PluginOperationName]map[PluginStage]string{ OperationLanguageServerStart: processStart, OperationDebugAdapterStart: processStart, - OperationBuildModel: commandRun, OperationBuildDependencies: commandRun, + OperationBuildModel: commandRun, OperationBuildDependencies: commandRun, OperationBuildTestDiscovery: commandRun, } allStages := []PluginStage{StagePlan, StageResolve, StageLaunch, StageInitialize, StageTimeout, StageExit, StageDecode} want := map[string]string{} // op -> code, "" for finished diff --git a/desktop/internal/core/test.go b/desktop/internal/core/test.go index 4e3fbcc7e8..879c4be379 100644 --- a/desktop/internal/core/test.go +++ b/desktop/internal/core/test.go @@ -129,7 +129,7 @@ func (c *Client) DecodeBuildTestResults(ctx context.Context, manifest json.RawMe return *result.Results, nil } -// BuildDiscoveredTest is one exact test a provider discovered. Core accepted it only after the +// BuildDiscoveredTest is one exact test discovered by a command or provider. Core accepted it only after the // ordinary test plan could run it, so Suite, Case, Project and Target go back into // BuildTestRequest unchanged. ID tells tests with equal names in sibling modules apart. type BuildDiscoveredTest struct { @@ -146,22 +146,23 @@ type BuildTestDiscovery struct { } // BuildDecodeTestDiscoveryRequest carries the plan context the discovery ran with and the -// litheTestDiscovery document the provider answered. +// litheTestDiscovery document returned by a command or provider. type BuildDecodeTestDiscoveryRequest struct { Root string `json:"root"` Options map[string]json.RawMessage `json:"options,omitempty"` PluginDirectory string `json:"pluginDirectory,omitempty"` WorkspaceStateDirectory string `json:"workspaceStateDirectory,omitempty"` - Result json.RawMessage `json:"result"` + OutputFile string `json:"outputFile,omitempty"` + Result json.RawMessage `json:"result,omitempty"` } -// PlanBuildTestDiscovery plans the provider request that lists the instance's tests. Only a +// PlanBuildTestDiscovery plans how to list the instance's tests. Only a // declaration with test discovery accepts it, and it always addresses the whole instance. func (c *Client) PlanBuildTestDiscovery(ctx context.Context, manifest json.RawMessage, buildSystemID string, request BuildPlanRequest) (BuildPlan, error) { return c.planBuild(ctx, "build.testDiscoveryPlan", manifest, buildSystemID, request) } -// DecodeBuildTestDiscovery validates a provider's discovered tests. Core rejects the whole +// DecodeBuildTestDiscovery validates the discovered tests. Core rejects the whole // document rather than publish a partial list. func (c *Client) DecodeBuildTestDiscovery(ctx context.Context, manifest json.RawMessage, buildSystemID string, request BuildDecodeTestDiscoveryRequest) (BuildTestDiscovery, error) { const command = "build.decodeTestDiscovery" diff --git a/desktop/internal/localshell/backend_unix.go b/desktop/internal/localshell/backend_unix.go index 8f8c7069a7..f6687fe8a8 100644 --- a/desktop/internal/localshell/backend_unix.go +++ b/desktop/internal/localshell/backend_unix.go @@ -41,6 +41,7 @@ func startBackend(config Config) (backend, error) { } env := append(withoutVariables(inherited, config.Unset), "TERM=xterm-256color", "COLORTERM=truecolor") env = withUTF8Locale(append(env, config.Env...)) + bash := filepath.Base(program) == "bash" args := config.Args // runtime is the private directory of an integrated shell's startup files: // it is made here and removed once the shell has ended, however it ended, @@ -117,7 +118,8 @@ func startBackend(config Config) (backend, error) { }) return readErr == nil && err == nil && group > 0 && group != cmd.Process.Pid }, - promptToken: promptToken, + promptToken: promptToken, + retryHangupAtPrompt: bash && promptToken != "", }, nil } diff --git a/desktop/internal/localshell/shell.go b/desktop/internal/localshell/shell.go index 33441be9ad..52af1f3a56 100644 --- a/desktop/internal/localshell/shell.go +++ b/desktop/internal/localshell/shell.go @@ -91,6 +91,8 @@ type backend struct { // promptToken is the token of the prompt marks the shell prints when it was // started with integration (see integration_scripts.go), else empty. promptToken string + // retryHangupAtPrompt is set by the Unix backend for integrated Bash. + retryHangupAtPrompt bool } // ExitError is why a shell ended with a nonzero status. It has the same @@ -281,6 +283,9 @@ func (shell *Shell) wait() { case <-shell.readDone: case <-time.After(readDrainGrace): } + // Closing a Unix PTY early can make Bash read EOF before it handles SIGHUP. + // By now the shell has had its chance to forward SIGHUP to its jobs. + _ = shell.b.io.Close() shell.mu.Lock() shell.exitErr = err shell.finished = true @@ -398,10 +403,9 @@ func (shell *Shell) ExitStatus() int { // The shell passes the hangup on to the jobs it would end, and leaves those the user // disowned. Bash does so only while it is interactive, and running PROMPT_COMMAND, // which the integration uses, it is not; a job Zsh is still starting misses it too. -// So an integrated shell that has shown a prompt but is not at one now and runs no -// program in the foreground, that is one between a command and its next prompt, is -// hung up when it shows the prompt, or after promptGrace. Without integration the -// shell is hung up at once. +// A foreground program can also be part of PROMPT_COMMAND. Wait for the next +// prompt of an integrated shell that has already shown one, bounded by +// promptGrace. A shell without prompt information is hung up at once. func (shell *Shell) Close() { shell.mu.Lock() if shell.closed { @@ -414,35 +418,20 @@ func (shell *Shell) Close() { if shell.resizeWake != nil { close(shell.resizeWake) } - settling := shell.prompted && shell.lastMark != 'B' && !shell.finished - mark := shell.lastMark + var shown chan struct{} + if shell.prompted && shell.lastMark != 'B' && !shell.finished { + shown = make(chan struct{}) + shell.promptShown = shown + } + shell.finished = true shell.mu.Unlock() // A reader waiting for room drops what it holds and reads on. shell.space.Broadcast() - // A command in the foreground keeps the shell waiting for it, interactive. - if settling && mark == 'C' && shell.b.busy != nil && shell.b.busy() { - settling = false - } - var shown chan struct{} - if settling { - shell.mu.Lock() - if shell.lastMark == 'B' { - settling = false - } else { - shown = make(chan struct{}) - shell.promptShown = shown - } - shell.mu.Unlock() - } - if settling { + if shown != nil { go shell.hangUpAtPrompt(shown) } else { shell.hangUp() } - shell.mu.Lock() - shell.finished = true - shell.mu.Unlock() - shell.space.Broadcast() } // hangUpAtPrompt hangs up a closed shell once it shows its prompt, ends, or has had @@ -453,21 +442,40 @@ func (shell *Shell) hangUpAtPrompt(shown <-chan struct{}) { select { case <-shown: case <-shell.done: + return case <-timer.C: } shell.hangUp() } -// hangUp asks the shell to end, kills it when it outlives killGrace and lets go of -// the terminal. +// hangUp asks the shell to end and kills it if it outlives killGrace. The +// waiter releases the terminal after the process exits and output is drained. func (shell *Shell) hangUp() { + select { + case <-shell.done: + return + default: + } shell.b.hangup() - timer := time.AfterFunc(killGrace, shell.b.kill) + kill := time.AfterFunc(killGrace, shell.b.kill) + var retry *time.Timer + if shell.b.retryHangupAtPrompt { + shell.mu.Lock() + atPrompt := shell.lastMark == 'B' + shell.mu.Unlock() + if atPrompt { + // Bash can print the prompt before Readline is ready to handle + // SIGHUP. Give the shell another chance to forward it to its jobs. + retry = time.AfterFunc(hangupRetryDelay, shell.b.hangup) + } + } go func() { <-shell.done - timer.Stop() + kill.Stop() + if retry != nil { + retry.Stop() + } }() - _ = shell.b.io.Close() } // sawMark records a prompt mark the reader found in the output. @@ -485,6 +493,9 @@ func (shell *Shell) sawMark(kind byte) { } } +// hangupRetryDelay lets Readline finish entering its input loop after the prompt. +const hangupRetryDelay = 100 * time.Millisecond + // killGrace is how long a shell gets to leave after a hangup before it is killed. const killGrace = 500 * time.Millisecond diff --git a/desktop/internal/localshell/shell_unix_test.go b/desktop/internal/localshell/shell_unix_test.go index 4d152f47e8..aba75a53d2 100644 --- a/desktop/internal/localshell/shell_unix_test.go +++ b/desktop/internal/localshell/shell_unix_test.go @@ -7,7 +7,9 @@ import ( "path/filepath" "slices" "strings" + "sync" "testing" + "testing/synctest" "time" ) @@ -200,6 +202,100 @@ func TestCloseHangsUpARunningProgramAndReleasesIt(t *testing.T) { shell.Close() // idempotent } +type hangupTestPTY struct { + resizeTestIO + onClose func() +} + +func (pty hangupTestPTY) Close() error { + pty.onClose() + return nil +} + +func TestCloseLetsTheShellHandleHangupBeforeReleasingThePTY(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + exited := make(chan struct{}) + var calls []string + shell := resizeTestShell(backend{ + io: hangupTestPTY{onClose: func() { calls = append(calls, "close PTY") }}, + wait: func() (int, error) { + <-exited + return 0, nil + }, + hangup: func() { calls = append(calls, "hangup") }, + kill: func() { calls = append(calls, "kill") }, + busy: func() bool { return true }, + retryHangupAtPrompt: true, + }) + shell.space = sync.NewCond(&shell.mu) + shell.readDone = make(chan struct{}) + shell.prompted, shell.lastMark = true, 'C' + liveShells.Acquire() + go shell.wait() + + // A foreground process can belong to a slow PROMPT_COMMAND. Its + // presence doesn't mean the shell can already propagate a hangup. + shell.Close() + synctest.Wait() + if len(calls) != 0 { + t.Errorf("while the prompt hook runs: %v, want no backend calls", calls) + } + shell.sawMark('B') + synctest.Wait() + if !slices.Equal(calls, []string{"hangup"}) { + t.Errorf("before the shell handles hangup: %v, want only hangup", calls) + } + + close(exited) + close(shell.readDone) + select { + case <-shell.Done(): + case <-time.After(time.Second): + t.Fatal("the shell never released its terminal") + } + synctest.Wait() + if !slices.Equal(calls, []string{"hangup", "close PTY"}) { + t.Fatalf("shutdown order = %v, want hangup followed by PTY close", calls) + } + }) +} + +func TestHangupRetriesAtTheBashPromptBeforeForcingExit(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + signals := make(chan string, 3) + shell := resizeTestShell(backend{ + hangup: func() { signals <- "hangup" }, + retryHangupAtPrompt: true, + }) + shell.b.kill = func() { + signals <- "kill" + close(shell.done) + } + shell.lastMark = 'B' + shell.hangUp() + synctest.Wait() + if len(signals) != 1 { + t.Errorf("initial signal count = %d, want one hangup", len(signals)) + } + + select { + case <-shell.done: + case <-time.After(killGrace + time.Millisecond): + t.Fatal("the fallback did not end the shell within its original grace period") + } + for _, want := range []string{"hangup", "hangup", "kill"} { + select { + case got := <-signals: + if got != want { + t.Fatalf("signal = %q, want %q", got, want) + } + default: + t.Fatalf("missing signal %q", want) + } + } + }) +} + func TestOutputIsBoundedAndNothingIsLost(t *testing.T) { shell, wakes := start(t, Config{}) // 3 MiB of output against a 1 MiB buffer: the program is held back, not diff --git a/desktop/internal/pluginhost/pluginhost.go b/desktop/internal/pluginhost/pluginhost.go index 82070a1b17..8999b5a52e 100644 --- a/desktop/internal/pluginhost/pluginhost.go +++ b/desktop/internal/pluginhost/pluginhost.go @@ -188,6 +188,8 @@ func Declared() Capabilities { // Version 1 adds module sidebars, field sections and entry lists, which the // settings window's source forms render. declared["sourceSettings"] = []int{0, 1} + // Version 1 adds command-sourced discovery in the Build test tree. + declared["buildSystems"] = []int{0, 1} // Version 1 adds entrypoint runs, which Run on Current File starts. declared["buildProviders"] = []int{0, 1} // Version 1 adds a definition's category and audience, by which the diff --git a/desktop/internal/pluginhost/pluginhost_test.go b/desktop/internal/pluginhost/pluginhost_test.go index b43c8c2647..19306b36c0 100644 --- a/desktop/internal/pluginhost/pluginhost_test.go +++ b/desktop/internal/pluginhost/pluginhost_test.go @@ -74,6 +74,10 @@ func TestDeclaredServesTheBaselineOfEveryWiredCapability(t *testing.T) { if name == "sourceSettings" { wanted = []int{0, 1} } + // The Build test tree supports the discovery command version 1 adds. + if name == "buildSystems" { + wanted = []int{0, 1} + } // Run on Current File starts the entrypoint runs version 1 adds. if name == "buildProviders" { wanted = []int{0, 1} diff --git a/desktop/internal/pluginservice/builds.go b/desktop/internal/pluginservice/builds.go index 7aafa428a9..440ae9ec75 100644 --- a/desktop/internal/pluginservice/builds.go +++ b/desktop/internal/pluginservice/builds.go @@ -67,6 +67,8 @@ type BuildTestDeclaration struct { // beyond choosing how to present the run. Source string Discovery bool + // DiscoveryCommand selects the command path for an enabled discovery action. + DiscoveryCommand bool } // BuildTaskDeclaration is one task the Build window may offer. @@ -195,10 +197,11 @@ type rawBuildManifest struct { } `json:"debug"` } `json:"run"` Test *struct { - Scopes []string `json:"scopes"` - TargetTags []string `json:"targetTags"` - Source string `json:"source"` - Discovery bool `json:"discovery"` + Scopes []string `json:"scopes"` + TargetTags []string `json:"targetTags"` + Source string `json:"source"` + Discovery bool `json:"discovery"` + DiscoveryCommand *struct{} `json:"discoveryCommand"` } `json:"test"` Dependencies *struct { Scopes []string `json:"scopes"` @@ -261,10 +264,11 @@ func parseBuildSystems(manifest json.RawMessage) (map[string]BuildSystemDeclarat } if raw.Test != nil { system.Test = &BuildTestDeclaration{ - Scopes: append([]string(nil), raw.Test.Scopes...), - TargetTags: append([]string(nil), raw.Test.TargetTags...), - Source: raw.Test.Source, - Discovery: raw.Test.Discovery, + Scopes: append([]string(nil), raw.Test.Scopes...), + TargetTags: append([]string(nil), raw.Test.TargetTags...), + Source: raw.Test.Source, + Discovery: raw.Test.Discovery || raw.Test.DiscoveryCommand != nil, + DiscoveryCommand: raw.Test.DiscoveryCommand != nil, } } if deps := raw.Dependencies; deps != nil && len(deps.Scopes) > 0 { diff --git a/desktop/internal/pluginservice/lifecycle.go b/desktop/internal/pluginservice/lifecycle.go index 32dab4f0b9..5a0676d7cb 100644 --- a/desktop/internal/pluginservice/lifecycle.go +++ b/desktop/internal/pluginservice/lifecycle.go @@ -26,37 +26,39 @@ func (s *Service) Uninstall(ctx context.Context, id string, server *LanguageSess if err := s.stopRuntimePreparations(ctx, id); err != nil { return err } - _, err := s.Manager.Apply(ctx, core.PluginUninstall, id, func() error { - var failures []error - for _, stop := range stopNative { - failures = append(failures, stop(ctx)) - } - failures = append(failures, s.stopPlugin(ctx, id, server)) - return errors.Join(failures...) - }) + _, err := s.Manager.Apply(ctx, core.PluginUninstall, id, func() error { return s.stopWithNativePrograms(ctx, id, server, stopNative) }) return err } // Disable records that the user turned plugin id off and stops what it runs, // as Uninstall does, so a disabled plugin keeps no process. Core plans the // choice before the stop, so nothing starts the plugin again while it stops. -func (s *Service) Disable(ctx context.Context, id string, server *LanguageSession) error { +func (s *Service) Disable(ctx context.Context, id string, server *LanguageSession, stopNative ...func(context.Context) error) error { release := s.holdRuntimeStop(id) defer release() if err := s.stopRuntimePreparations(ctx, id); err != nil { return err } - _, err := s.Manager.Apply(ctx, core.PluginDisable, id, func() error { return s.stopPlugin(ctx, id, server) }) + _, err := s.Manager.Apply(ctx, core.PluginDisable, id, func() error { return s.stopWithNativePrograms(ctx, id, server, stopNative) }) return err } +func (s *Service) stopWithNativePrograms(ctx context.Context, id string, server *LanguageSession, stopNative []func(context.Context) error) error { + var failures []error + for _, stop := range stopNative { + failures = append(failures, stop(ctx)) + } + failures = append(failures, s.stopPlugin(ctx, id, server)) + return errors.Join(failures...) +} + // StopDisplaced stops what plugin id runs after enabling another plugin turned it // off (pluginmanager.Displaced): its choice is already recorded, so only the // programs remain. server is its language server session, or nil. -func (s *Service) StopDisplaced(ctx context.Context, id string, server *LanguageSession) error { +func (s *Service) StopDisplaced(ctx context.Context, id string, server *LanguageSession, stopNative ...func(context.Context) error) error { release := s.holdRuntimeStop(id) defer release() - return s.stopPlugin(ctx, id, server) + return s.stopWithNativePrograms(ctx, id, server, stopNative) } // stopPlugin first cancels and awaits preparation/launch work, then stops all diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 6349f1370f..62ada9b541 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -672,6 +672,9 @@ type App struct { // pluginFacts is what the Installed tab shows about each installed plugin, in name order, // read from disk off the window thread. pluginFacts atomic.Pointer[[]settingswindow.PluginFacts] + // Discovery remains registered until its report is cleaned up, even after + // this workbench closes its project or leaves the tab strip. + pluginDiscoveryLaunches pluginLaunches // pluginServerMu guards the language-server maps because a build provider // may attach to a shared session from a background model load. pluginServerMu sync.Mutex diff --git a/desktop/internal/workbench/build.go b/desktop/internal/workbench/build.go index 1d20b09503..a06a046718 100644 --- a/desktop/internal/workbench/build.go +++ b/desktop/internal/workbench/build.go @@ -2263,6 +2263,7 @@ func (a *App) invalidateBuild(p *project) { } a.stopTestsForProject(p) a.stopBuildSessions(p, false) + p.revokeAllBuildTests() // The Run window's sessions are what ran, not the models, so they stay. runs, view, sessions := p.build.runs, p.build.view, p.build.sessions p.build = buildState{runs: runs, view: view, sessions: sessions} diff --git a/desktop/internal/workbench/build_command_discovery_visual_test.go b/desktop/internal/workbench/build_command_discovery_visual_test.go new file mode 100644 index 0000000000..6fb0f46a76 --- /dev/null +++ b/desktop/internal/workbench/build_command_discovery_visual_test.go @@ -0,0 +1,85 @@ +//go:build vivahead && lithevisual + +package workbench + +import ( + "os" + "path/filepath" + "slices" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" +) + +func TestVisualBuildCommandDiscovery(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR") + } + if err := os.MkdirAll(out, 0o755); err != nil { + t.Fatal(err) + } + installBuildTool(t) + for _, theme := range []string{"light", "dark"} { + for _, language := range []string{"zh-Hans", "en"} { + t.Run(theme+"-"+language, func(t *testing.T) { + root := t.TempDir() + writeBuildCommandMarker(t, root, "discover-tests") + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, settings{Theme: themeChoice(theme), Language: language}); err != nil { + t.Fatal(err) + } + var session *headless.Session + client := &testKernel{Client: core.NewClient()} + h := newHarnessWithDriver(t, Options{Kernel: client, PluginKernel: client, PluginRoot: t.TempDir(), Store: prefs, Languages: []string{language}}, func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = 1440, 900 + var err error + session, err = headless.Open(config, nil, headless.Options{}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + h.open(root) + p := h.app.project + instance := commandDiscoveryTestInstance(t, contractfixture.Path("fixtures/build-systems/build-command-test-discovery.json")) + instance.System.DisplayName = "Sample Build" + instance.modelLoaded = true + h.app.post(func(a *App) { + p.build.instances, p.build.loaded, p.build.selected = []buildInstance{instance}, true, 0 + p.setBuildGroupOpen(0, true) + a.reduceChrome(core.SetChromeOpen(itemBuild, true)) + }) + h.settleChain() + setBuildNodeOpen(t, p, laidOutBuildRows(t, h, p), true, i18n.Shared(h.app.language(), "native.discoveredTests")) + h.app.invalidator.Invalidate() + h.settle() + h.clickNamed(i18n.Shared(h.app.language(), "native.discoverTests")) + awaitStateWithin(t, h, 20*time.Second, "the command discovery result", func() bool { + tests := p.build.discovered[instance.ID] + return tests != nil && !tests.loading + }) + if tests := p.build.discovered[instance.ID]; tests.failed != "" || len(tests.tests) != 2 { + t.Fatalf("discovery = %+v", tests) + } + h.app.invalidator.Invalidate() + h.settleChain() + rows := laidOutBuildRows(t, h, p) + if !slices.ContainsFunc(rows, func(row buildRow) bool { + return row.label == "ExampleSuite · checks spaces # [exact]" + }) { + t.Fatalf("the command's discovered test has no row: %+v", rows) + } + if err := session.Screenshot(filepath.Join(out, "build-command-discovery-"+theme+"-"+language+".png")); err != nil { + t.Fatal(err) + } + }) + } + } +} diff --git a/desktop/internal/workbench/build_command_record_test.go b/desktop/internal/workbench/build_command_record_test.go index 2f6444aba6..48e3f2d20a 100644 --- a/desktop/internal/workbench/build_command_record_test.go +++ b/desktop/internal/workbench/build_command_record_test.go @@ -9,10 +9,12 @@ import ( "os" "path/filepath" "runtime" + "slices" "strings" "testing" "time" + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" "github.com/1lck/Lithe-IDEA/desktop/internal/store" @@ -130,6 +132,30 @@ func TestBuildCommandRunner(t *testing.T) { if err := os.WriteFile(arguments[len(arguments)-1], []byte(tree), 0o600); err != nil { os.Exit(5) } + case "discover-blocked": + arguments := flag.Args() + if len(arguments) != 2 { + os.Exit(4) + } + if err := os.WriteFile(arguments[0], []byte("running"), 0o600); err != nil { + os.Exit(5) + } + // The deadline is a watchdog for a failed cancellation, not a readiness signal. + timer := time.NewTimer(pluginOperationWait) + <-timer.C + os.Exit(7) + case "discover-tests": + arguments := flag.Args() + if len(arguments) != 2 { + os.Exit(4) + } + result, err := os.ReadFile(arguments[0]) + if err != nil { + os.Exit(5) + } + if err := os.WriteFile(arguments[1], result, 0o600); err != nil { + os.Exit(6) + } case "fail": os.Exit(3) case "explain": @@ -229,6 +255,195 @@ func failedBuildCommand(operation core.PluginOperationName, op string, stage cor return core.PluginOperation{PluginID: buildCommandPluginID, Operation: operation, Outcome: "failed", Stage: stage, OperationID: op} } +func commandDiscoveryTestInstance(t *testing.T, reportSource string) buildInstance { + t.Helper() + raw, err := os.ReadFile(contractfixture.Path("fixtures/build-systems/build-command-test-discovery.plugin.json")) + if err != nil { + t.Fatal(err) + } + var manifest map[string]any + if err := json.Unmarshal(raw, &manifest); err != nil { + t.Fatal(err) + } + system := manifest["buildSystems"].([]any)[0].(map[string]any) + system["invocation"] = map[string]any{"executables": []map[string]string{{"kind": "command", "command": "fixture-build"}}} + test := system["test"].(map[string]any) + discovery := test["discoveryCommand"].(map[string]any) + discovery["arguments"] = []string{"-test.run=^TestBuildCommandRunner$", "--", reportSource, "${outputFile}"} + contents, err := json.Marshal(manifest) + if err != nil { + t.Fatal(err) + } + instance := buildCommandInstance(".", false) + instance.BuildSystemID, instance.Manifest = "sample", contents + instance.System.Test = &pluginservice.BuildTestDeclaration{Discovery: true, DiscoveryCommand: true} + return instance +} + +func TestBuildCommandDiscoversExactTestsAndRecordsItsResult(t *testing.T) { + h, plugins, p := buildCommandHarness(t) + installBuildTool(t) + kernel := h.app.kernel.(buildTestDiscoveryKernel) + fixture := contractfixture.Path("fixtures/build-systems/build-command-test-discovery.json") + for _, tc := range []struct { + mode string + file string + stage core.PluginStage + untrusted bool + }{ + {mode: "discover-tests", file: fixture}, + {mode: "fail", file: fixture, stage: core.StageExit}, + {mode: "garbage", file: fixture, stage: core.StageDecode}, + {mode: "safe-mode", file: fixture, stage: core.StagePlan, untrusted: true}, + } { + t.Run(tc.mode, func(t *testing.T) { + p.trust.codeAllowed.Store(!tc.untrusted) + writeBuildCommandMarker(t, p.root, tc.mode) + instance := commandDiscoveryTestInstance(t, tc.file) + ctx := buildLoadContext(t, "action-discovery", pluginOperationWait) + result, err := h.app.buildTestDiscovery(ctx, p, instance, kernel, false) + if tc.stage != "" { + if err == nil || len(result.Tests) != 0 { + t.Fatalf("discovery = %+v, error = %v", result, err) + } + if tc.untrusted { + var rejection *core.MarketplaceRejection + if !errors.As(err, &rejection) || rejection.Code != core.BuildUntrustedWorkspace { + t.Fatalf("safe-mode discovery returned %v, want %s", err, core.BuildUntrustedWorkspace) + } + } + wantPluginOperation(t, plugins.next(t, tc.mode), failedBuildCommand(core.OperationBuildTestDiscovery, "action-discovery", tc.stage)) + } else { + if err != nil || len(result.Tests) != 2 || result.Tests[0].ID == result.Tests[1].ID { + t.Fatalf("discovery = %+v, error = %v", result, err) + } + for _, test := range result.Tests { + plan, err := core.NewClient().PlanBuildTest(ctx, instance.Manifest, instance.BuildSystemID, core.BuildTestRequest{ + Root: instance.Root, WorkspaceRoot: p.root, Project: test.Project, Target: test.Target, Suite: test.Suite, Case: test.Case, + ProjectCodeAllowed: p.trust.allowed(), + }) + if err != nil || !slices.Contains(plan.Arguments, "--case=checks spaces # [exact]") { + t.Fatalf("exact test plan = %+v, error = %v", plan, err) + } + } + wantPluginOperation(t, plugins.next(t, tc.mode), core.PluginOperation{PluginID: buildCommandPluginID, Operation: core.OperationBuildTestDiscovery, Outcome: "finished", OperationID: "action-discovery"}) + } + plugins.none(t) + entries, err := os.ReadDir(buildStateDirectory(h.app.plugins.Root, p.root, instance)) + if err != nil || len(entries) != 0 { + t.Fatalf("discovery left state entries %v (%v)", entries, err) + } + }) + } +} + +func TestBuildCommandDiscoveryRevocationCancelsTheProcess(t *testing.T) { + h, plugins, p := buildCommandHarness(t) + installBuildTool(t) + ready := filepath.Join(t.TempDir(), "discovery-ready") + writeBuildCommandMarker(t, p.root, "discover-blocked") + instance := commandDiscoveryTestInstance(t, ready) + h.app.discoverBuildTests(p, &instance, false) + discovery := p.build.discovered[instance.ID] + awaitStateWithin(t, h, 5*time.Second, "the discovery process to start", func() bool { + _, err := os.Stat(ready) + return err == nil + }) + p.revokeBuildTests(instance.ID) + state := buildStateDirectory(h.app.plugins.Root, p.root, instance) + awaitStateWithin(t, h, 5*time.Second, "the cancelled discovery process to release its report directory", func() bool { + entries, err := os.ReadDir(state) + return err == nil && len(entries) == 0 + }) + if p.build.discovered[instance.ID] != nil || discovery.loaded { + t.Fatal("revoked discovery published a result") + } + plugins.none(t) +} + +func TestPluginTeardownWaitsForBuildCommandDiscovery(t *testing.T) { + h, _, p := buildCommandHarness(t) + installBuildTool(t) + ready := filepath.Join(t.TempDir(), "discovery-ready") + writeBuildCommandMarker(t, p.root, "discover-blocked") + instance := commandDiscoveryTestInstance(t, ready) + h.app.discoverBuildTests(p, &instance, false) + awaitStateWithin(t, h, 5*time.Second, "the discovery process to start", func() bool { + _, err := os.Stat(ready) + return err == nil + }) + _, stop := h.app.detachPluginPrograms(instance.PluginID) + ctx := buildLoadContext(t, "stop-discovery", 5*time.Second) + if err := stop(ctx); err != nil { + t.Fatal(err) + } + entries, err := os.ReadDir(buildStateDirectory(h.app.plugins.Root, p.root, instance)) + if err != nil || len(entries) != 0 { + t.Fatalf("plugin teardown returned with discovery state %v (%v)", entries, err) + } + if p.build.discovered[instance.ID] != nil { + t.Fatal("plugin teardown left its discovery state published") + } +} + +type blockedDiscoveryDecoder struct { + buildTestDiscoveryKernel + entered chan struct{} + release chan struct{} +} + +func (k blockedDiscoveryDecoder) DecodeBuildTestDiscovery(ctx context.Context, _ json.RawMessage, _ string, _ core.BuildDecodeTestDiscoveryRequest) (core.BuildTestDiscovery, error) { + close(k.entered) + select { + case <-k.release: + return core.BuildTestDiscovery{}, ctx.Err() + case <-time.After(10 * time.Second): + return core.BuildTestDiscovery{}, errors.New("test did not release discovery cleanup") + } +} + +func TestPluginTeardownWaitsForDiscoveryAfterProjectCloses(t *testing.T) { + h, _, p := buildCommandHarness(t) + installBuildTool(t) + writeBuildCommandMarker(t, p.root, "discover-tests") + instance := commandDiscoveryTestInstance(t, contractfixture.Path("fixtures/build-systems/build-command-test-discovery.json")) + kernel := blockedDiscoveryDecoder{h.app.kernel.(buildTestDiscoveryKernel), make(chan struct{}), make(chan struct{})} + released := false + defer func() { + if !released { + close(kernel.release) + } + }() + h.app.background(p, 15*time.Second, func(ctx context.Context) func(*App) { + _, _ = h.app.commandTestDiscovery(ctx, p, instance, kernel) + return nil + }) + select { + case <-kernel.entered: + case <-time.After(5 * time.Second): + t.Fatal("discovery never entered report decoding") + } + h.app.finishCloseProject(p, nil) + if h.app.project != nil || p.ctx.Err() == nil { + t.Fatal("closing the project did not cancel its work") + } + _, stop := h.app.detachPluginPrograms(instance.PluginID) + cancelled, cancel := context.WithCancel(context.Background()) + cancel() + if err := stop(cancelled); !errors.Is(err, context.Canceled) { + t.Fatalf("plugin teardown returned %v while discovery still owned its report", err) + } + close(kernel.release) + released = true + if err := stop(buildLoadContext(t, "stop-closed-discovery", 5*time.Second)); err != nil { + t.Fatal(err) + } + entries, err := os.ReadDir(buildStateDirectory(h.app.plugins.Root, p.root, instance)) + if err != nil || len(entries) != 0 { + t.Fatalf("plugin teardown returned with discovery state %v (%v)", entries, err) + } +} + func TestBuildCommandModelLoadIsRecordedAtTheStageItEnded(t *testing.T) { h, plugins, p := buildCommandHarness(t) withoutTool := installBuildTool(t) diff --git a/desktop/internal/workbench/build_tests.go b/desktop/internal/workbench/build_tests.go index 67a5063f89..19c3ea3e9f 100644 --- a/desktop/internal/workbench/build_tests.go +++ b/desktop/internal/workbench/build_tests.go @@ -4,6 +4,8 @@ import ( "context" "encoding/json" "errors" + "os" + "path/filepath" "strings" "time" @@ -17,8 +19,8 @@ import ( // The Build tool window offers the test scopes the build system declares. A project row and a // target row run their tests from the context menu, and a build system that discovers tests // lists them under Discovered Tests, where one test runs on its own. Core plans discovery -// (build.testDiscoveryPlan), the plugin's provider answers lithe/build/discoverTests, and Core -// checks and bounds the list (build.decodeTestDiscovery). Every run is planned by Core's +// (build.testDiscoveryPlan), the declared command or provider finds the tests, and Core checks +// and bounds the list (build.decodeTestDiscovery). Every run is planned by Core's // build.testPlan and shows in the Tests tool window (tests.go). // buildTestDiscoveryKernel is the part of Core test discovery uses. @@ -30,12 +32,14 @@ type buildTestDiscoveryKernel interface { // buildDiscoveredTests are the tests one build instance discovered. Discovery runs only when // asked for, because it may compile the workspace. type buildDiscoveredTests struct { - loading bool - loaded bool - failed string - tests []core.BuildDiscoveredTest + pluginID string + loading bool + loaded bool + failed string + tests []core.BuildDiscoveredTest // generation rejects a discovery a reload replaced. generation uint64 + cancel context.CancelFunc } // discoveredTestsOf is the discovery state of instance, created empty the first time. @@ -45,7 +49,7 @@ func (p *project) discoveredTestsOf(instance *buildInstance) *buildDiscoveredTes } tests := p.build.discovered[instance.ID] if tests == nil { - tests = &buildDiscoveredTests{} + tests = &buildDiscoveredTests{pluginID: instance.PluginID} p.build.discovered[instance.ID] = tests } return tests @@ -62,10 +66,13 @@ func (p *project) discoveredTestsView(instance *buildInstance) buildDiscoveredTe // revokeBuildTests forgets the tests the instance discovered: a reloaded model or a saved // source file can rename, add or remove them, and a selector Core no longer recognizes would -// only fail when run. A discovery still running is dropped by its generation. +// only fail when run. Cancel an in-flight discovery and discard its result by generation. func (p *project) revokeBuildTests(instanceID string) { if tests := p.build.discovered[instanceID]; tests != nil { tests.generation++ + if tests.cancel != nil { + tests.cancel() + } delete(p.build.discovered, instanceID) } } @@ -78,6 +85,14 @@ func (p *project) revokeAllBuildTests() { } } +func (p *project) revokePluginBuildTests(pluginID string) { + for id, tests := range p.build.discovered { + if tests.pluginID == pluginID { + p.revokeBuildTests(id) + } + } +} + // buildTestDeclares reports whether the instance declares the test scope. func buildTestDeclares(instance *buildInstance, scope string) bool { if instance == nil || instance.System.Test == nil { @@ -178,7 +193,7 @@ func (a *App) startBuildTests(p *project, selection testSelection) { a.startTests(p, selection) } -// discoverBuildTests asks the instance's provider for its tests off the window thread. +// discoverBuildTests runs the instance's declared discovery off the window thread. func (a *App) discoverBuildTests(p *project, instance *buildInstance, refresh bool) { kernel, ok := a.kernel.(buildTestDiscoveryKernel) if !ok || instance.System.Test == nil || !instance.System.Test.Discovery { @@ -192,13 +207,25 @@ func (a *App) discoverBuildTests(p *project, instance *buildInstance, refresh bo tests.generation++ generation := tests.generation captured := *instance + lifetime, cancel := context.WithCancel(p.ctx) + tests.cancel = cancel a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { + defer cancel() + ctx, stop := context.WithCancel(ctx) + defer stop() + unregister := context.AfterFunc(lifetime, stop) + defer unregister() + if lifetime.Err() != nil { + // log-exempt: 用户取消:发现请求在后台执行前已因实例失效撤销。 + return nil + } discovery, err := a.buildTestDiscovery(ctx, p, captured, kernel, refresh) return func(a *App) { if tests.generation != generation { return } tests.loading = false + tests.cancel = nil if err != nil { a.operationFailed("build_test_discovery", err) tests.failed = err.Error() @@ -210,8 +237,11 @@ func (a *App) discoverBuildTests(p *project, instance *buildInstance, refresh bo }) } -// buildTestDiscovery plans, sends and decodes one discovery request. +// buildTestDiscovery plans, executes and decodes a discovery request. func (a *App) buildTestDiscovery(ctx context.Context, p *project, instance buildInstance, kernel buildTestDiscoveryKernel, refresh bool) (core.BuildTestDiscovery, error) { + if instance.System.Test.DiscoveryCommand { + return a.commandTestDiscovery(ctx, p, instance, kernel) + } execution, err := a.resolveBuildExecutable(ctx, p, instance, a.text.Build) if err != nil { return core.BuildTestDiscovery{}, err @@ -246,6 +276,65 @@ func (a *App) buildTestDiscovery(ctx context.Context, p *project, instance build }) } +// commandTestDiscovery runs the plan in the workspace and owns the report until Core decodes it. +func (a *App) commandTestDiscovery(ctx context.Context, p *project, instance buildInstance, kernel buildTestDiscoveryKernel) (core.BuildTestDiscovery, error) { + ctx, finish, err := a.pluginDiscoveryLaunches.begin(ctx, instance.PluginID) + if err != nil { + return core.BuildTestDiscovery{}, err + } + var cleanupErr error + defer func() { finish(cleanupErr) }() + attempt := core.StartPluginAttempt(instance.PluginID, core.OperationBuildTestDiscovery, core.OriginOf(ctx).Operation) + fail := func(stage core.PluginStage, err error) (core.BuildTestDiscovery, error) { + a.plugins.EndAttempt(ctx, attempt, stage, err) + return core.BuildTestDiscovery{}, err + } + state := buildStateDirectory(a.plugins.Root, p.root, instance) + if err := os.MkdirAll(state, 0o700); err != nil { + return fail(core.StagePlan, err) + } + dir, err := os.MkdirTemp(state, "test-discovery-") + if err != nil { + return fail(core.StagePlan, err) + } + defer func() { + cleanupErr = os.RemoveAll(dir) + if cleanupErr != nil { + a.backgroundFailedIn(ctx, "build_test_discovery_cleanup", cleanupErr) + } + }() + outputFile := filepath.Join(dir, "tests.json") + plan, err := kernel.PlanBuildTestDiscovery(ctx, instance.Manifest, instance.BuildSystemID, core.BuildPlanRequest{ + Root: instance.Root, Options: instance.Options, WorkspaceRoot: p.root, + PluginDirectory: instance.PackageDirectory, WorkspaceStateDirectory: state, OutputFile: outputFile, + ProjectCodeAllowed: p.trust.allowed(), + }) + if err != nil { + return fail(core.StagePlan, err) + } + if plan.Provider != nil || plan.Output != "outputFile" || plan.Decoder != "litheTestDiscovery" { + return fail(core.StagePlan, errors.New(a.text.Build.CommandUnsupported)) + } + execution, err := a.resolveBuildExecutable(ctx, p, instance, a.text.Build) + if err != nil { + return fail(core.StageResolve, err) + } + if err := ctx.Err(); err != nil { + return fail(core.StageLaunch, err) + } + workingDirectory := filepath.Join(p.root, filepath.FromSlash(plan.WorkingDirectory)) + output, err := captureBuildProcess(ctx, execution.Executable, plan.Arguments, workingDirectory, applyToolchainSelection(plan.Environment, execution.selection()), false, nil) + if err != nil { + return fail(buildCommandStage(err), withBuildOutput(err, output.combined)) + } + result, err := kernel.DecodeBuildTestDiscovery(ctx, instance.Manifest, instance.BuildSystemID, core.BuildDecodeTestDiscoveryRequest{ + Root: instance.Root, Options: instance.Options, OutputFile: outputFile, + PluginDirectory: instance.PackageDirectory, WorkspaceStateDirectory: state, + }) + a.plugins.EndAttempt(ctx, attempt, core.StageDecode, err) + return result, err +} + // discoveredTestLabel names a discovered test by the selectors that tell it apart. func discoveredTestLabel(test core.BuildDiscoveredTest) string { parts := make([]string, 0, 3) diff --git a/desktop/internal/workbench/plugin_displace.go b/desktop/internal/workbench/plugin_displace.go index f5463e2d7e..477aa06fd5 100644 --- a/desktop/internal/workbench/plugin_displace.go +++ b/desktop/internal/workbench/plugin_displace.go @@ -61,9 +61,9 @@ func (a *App) stopDisplaced(d displacement) { p := a.project for _, item := range d.displaced { id, languages := item.PluginID, item.LanguageIDs - server := a.detachPluginServer(id) + server, stop := a.detachPluginPrograms(id) a.background(nil, pluginServerStopTimeout, func(ctx context.Context) func(*App) { - err := a.plugins.StopDisplaced(ctx, id, server) + err := a.plugins.StopDisplaced(ctx, id, server, stop) return func(a *App) { if err != nil { a.backgroundFailed("plugin_displace", err) diff --git a/desktop/internal/workbench/plugin_programs.go b/desktop/internal/workbench/plugin_programs.go index 761a3be6e3..8f01644993 100644 --- a/desktop/internal/workbench/plugin_programs.go +++ b/desktop/internal/workbench/plugin_programs.go @@ -7,6 +7,7 @@ import ( "sync" "github.com/1lck/Lithe-IDEA/desktop/internal/buildprovider" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" ) // pluginLaunches owns native starts until they either publish a process or finish @@ -138,10 +139,11 @@ func (r *vcsRuntime) detachPlugin(id string) func(context.Context) error { } // detachPluginPrograms takes native handles on the UI thread, then returns the -// bounded cleanup performed by Core's stopPrograms step. A hidden project tab -// owns its own plugin stack and must finish using the same package too. +// current tab's language server and the bounded cleanup for the other native +// owners. The caller stops the current tab's service as part of its lifecycle action. // Note: 卸载约束见 .agents/notes/implemented/bug-fix/2026-11-13-viva-plugin-install-enables-and-uninstall-cleans-state.md。 -func (a *App) detachPluginPrograms(id string) func(context.Context) error { +func (a *App) detachPluginPrograms(id string) (*pluginservice.LanguageSession, func(context.Context) error) { + var currentServer *pluginservice.LanguageSession var stops []func(context.Context) error for _, tab := range a.everyTab() { service := tab.plugins @@ -149,7 +151,9 @@ func (a *App) detachPluginPrograms(id string) func(context.Context) error { continue } server := tab.detachPluginServer(id) + stops = append(stops, tab.pluginDiscoveryLaunches.stop(id)) if p := tab.project; p != nil { + p.revokePluginBuildTests(id) stops = append(stops, p.buildSessions.detachPlugin(id)) stops = append(stops, p.vcs.runtime().detachPlugin(id)) var debugging []*debugSession @@ -179,11 +183,15 @@ func (a *App) detachPluginPrograms(id string) func(context.Context) error { return errors.Join(failures...) }) } - stops = append(stops, func(ctx context.Context) error { - return service.StopDisplaced(ctx, id, server) - }) + if tab == a { + currentServer = server + } else { + stops = append(stops, func(ctx context.Context) error { + return service.StopDisplaced(ctx, id, server) + }) + } } - return func(ctx context.Context) error { + return currentServer, func(ctx context.Context) error { var failures []error for _, stop := range stops { failures = append(failures, stop(ctx)) @@ -205,6 +213,7 @@ func (a *App) allowPluginPrograms(id string) { tab.pluginServerMu.Lock() delete(tab.pluginServerSuppressed, id) tab.pluginServerMu.Unlock() + tab.pluginDiscoveryLaunches.allow(id) if p := tab.project; p != nil { p.buildSessions.launches.allow(id) if p.vcs.launches != nil { diff --git a/desktop/internal/workbench/plugins.go b/desktop/internal/workbench/plugins.go index 96cda45012..dfaad87619 100644 --- a/desktop/internal/workbench/plugins.go +++ b/desktop/internal/workbench/plugins.go @@ -268,11 +268,10 @@ func (a *App) setPluginEnabled(id string, enabled bool) { if a.plugins == nil { return } - // A disabled plugin keeps no process and no session: its server leaves the - // workbench now, and Disable stops it and the plugin's backend. var server *pluginservice.LanguageSession + var stop func(context.Context) error if !enabled { - server = a.detachPluginServer(id) + server, stop = a.detachPluginPrograms(id) } a.background(nil, pluginStateTimeout+pluginServerStopTimeout, func(ctx context.Context) func(*App) { var err error @@ -284,7 +283,7 @@ func (a *App) setPluginEnabled(id string, enabled bool) { list, err = a.plugins.Manager.Enable(id) displaced = a.describeDisplacement(ctx, id, list) } else { - err = a.plugins.Disable(ctx, id, server) + err = a.plugins.Disable(ctx, id, server, stop) } return func(a *App) { if err != nil { @@ -317,9 +316,9 @@ func (a *App) uninstallPlugin(id string) { } // Detach native owners on their window thread before asking Core to remove // anything. The stopPrograms step waits for every tab, including late starts. - stop := a.detachPluginPrograms(id) + server, stop := a.detachPluginPrograms(id) a.background(nil, pluginInstallTimeout, func(ctx context.Context) func(*App) { - err := a.plugins.Uninstall(ctx, id, nil, stop) + err := a.plugins.Uninstall(ctx, id, server, stop) return func(a *App) { if err != nil { a.operationFailed("plugin_uninstall", err) diff --git a/desktop/internal/workbench/workspace_trust.go b/desktop/internal/workbench/workspace_trust.go index 050bb3ec34..5bc2d5e7b9 100644 --- a/desktop/internal/workbench/workspace_trust.go +++ b/desktop/internal/workbench/workspace_trust.go @@ -112,7 +112,7 @@ const trustFolderMaxRunes = 48 // trustFolderLabel is how the checkbox names folder: under home as "~" plus the rest, as IDEA // writes it, and a longer one with its middle left out, so its start and its own name stay. func trustFolderLabel(folder, home string) string { - label := []rune(welcomeShorten(folder, home)) + label := []rune(welcomeShorten(filepath.FromSlash(folder), home)) if len(label) <= trustFolderMaxRunes { return string(label) } diff --git a/desktop/internal/workbench/workspace_trust_test.go b/desktop/internal/workbench/workspace_trust_test.go index ecab664161..c87aa01d93 100644 --- a/desktop/internal/workbench/workspace_trust_test.go +++ b/desktop/internal/workbench/workspace_trust_test.go @@ -186,7 +186,9 @@ func TestSafeModeKeepsProjectCodeFromRunningUntilTrusted(t *testing.T) { func TestTrustFolderLabelShortensHomeAndLongPaths(t *testing.T) { home := filepath.Join(string(filepath.Separator)+"Users", "ann") - if got, want := trustFolderLabel(filepath.Join(home, "IdeaProjects"), home), "~"+string(filepath.Separator)+"IdeaProjects"; got != want { + // Core returns a slash-separated location even on Windows. + folder := filepath.ToSlash(filepath.Join(home, "IdeaProjects")) + if got, want := trustFolderLabel(folder, home), "~"+string(filepath.Separator)+"IdeaProjects"; got != want { t.Fatalf("label = %q, want %q", got, want) } long := filepath.Join(string(filepath.Separator)+"srv", "builds", "a-very-long-folder-name-for-every-checkout", "of-the-team", "projects") diff --git a/docs/ci-builds.md b/docs/ci-builds.md index 26227cfd7d..fb72ce5f90 100644 --- a/docs/ci-builds.md +++ b/docs/ci-builds.md @@ -70,6 +70,8 @@ macOS 的本地手动打包可用 `package-desktop.sh --ad-hoc-sign` 生成有 Desktop CI 的 LSP 无头截图由 `TestVisualLSPActions` 写入当前工作树的 `.artifacts/lsp-editor-visual/`。截图是当前提交与当前渲染环境的验证产物,绑定源码、平台、Go 工具链和固定的 Viva 与 Core 版本,不跨工作树复用。CI 上传后由运行器清理工作树,截图不进入安装包。 +Desktop CI 的 Build 命令发现截图由 `TestVisualBuildCommandDiscovery` 写入当前工作树的 `.artifacts/build-command-discovery-visual/`。该结果绑定提交、平台、Go 工具链和固定的 Viva 与 Core 版本,上传后由 CI 清理,不跨工作树复制,也不进入安装包。 + Viva 编辑器性能基线 `scripts/desktop/perf/editor-bench.sh` 把每次运行的原始输出和 Markdown 预算报告写入当前工作树的 `.artifacts/editor-perf/`(`run-.txt`、`record-.txt` 及同名 `.md`,以及开发者用 `--out` 指定在该目录下的文件)。它们只属于这一次运行,受源码修订、机器、CPU、运行时负载、Go 工具链和大文档大小(默认 10 MiB,可用 `LITHE_EDITOR_PERF_LARGE_BYTES` 或 `--large-bytes` 修改)影响;没有可验证的跨树身份 stamp,不跨工作树复制,由开发者在本地清理;该基线不是 CI 必跑项,CI 不运行基准,也没有 artifact。随仓库提交的历史记录 `desktop/benchmarks/history/*.jsonl` 由 Git 跟踪,属于源码而不是下载或生成资源,各工作树从 Git 检出。这些文件都不进入安装包,也不会改变代码签名或增量更新。 Viva 的 Core 源码检出、Cargo 目标目录和暂存静态库位于当前工作树的 @@ -226,7 +228,9 @@ Build Provider 的模型与依赖快照位于插件根(`pluginpkg.DefaultRoot` 它属于具体插件、构建系统和工作区的可变上游状态,没有版本/平台/架构/工具链 identity stamp, 不跨工作树复制或共享。 Provider 状态经平台 adapter 写 Application Support;插件安装目录和发行 bundle 只读, -不改变代码签名或增量更新的源基线。 +不改变代码签名或增量更新的源基线。命令式测试发现把这次命令的 JSON 报告写入同一工作区状态下的 +`test-discovery-*/tests.json`。宿主为每个操作创建独立目录,在成功、失败或取消后清理, +报告不能跨工作树复用。 显式声明 `requires.managedRuntimes: 0` 和 `runtimes.install` 权限的插件,可以让宿主在安装提交前 准备经过插件校验的依赖。下载来源、SHA-256、平台和目录布局属于插件清单及程序审批摘要; diff --git a/shared/platform-feature-matrix/features/build-command-test-discovery.json b/shared/platform-feature-matrix/features/build-command-test-discovery.json new file mode 100644 index 0000000000..815441f9e8 --- /dev/null +++ b/shared/platform-feature-matrix/features/build-command-test-discovery.json @@ -0,0 +1,27 @@ +{ + "id": "build-command-test-discovery", + "area": "扩展", + "group": "插件与主题", + "capability": "构建插件通过一次性命令发现测试,并从已有构建树精确运行选中的用例。", + "macos": { + "implementationStatus": "implemented", + "verificationStatus": "verified", + "evidence": [ + "desktop/internal/workbench/build_tests.go", + "desktop/internal/workbench/build_command_record_test.go", + "desktop/internal/workbench/build_command_discovery_visual_test.go" + ] + }, + "windows": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/workbench/build_tests.go", + "desktop/internal/buildprocess/process_windows.go", + "desktop/internal/workbench/build_command_record_test.go" + ] + }, + "owner": "Extensions", + "verification": "在构建面板展开已发现的测试,点击发现,检查命令返回两个同名但属于不同工程的用例,验证精确选择器和终态日志。使实例在发现中失效,确认子进程及报告目录清理,旧列表不重新出现。用 TestVisualBuildCommandDiscovery 截取中英与明暗主题。Windows 原生交互待验收。", + "notes": "buildSystems 1 使用 Core 计划并解码宿主状态目录中的临时报告。工作区关闭或构建实例失效时取消命令。停用或卸载插件时等待打开和已关闭工作区的进程与报告清理,由 TestPluginTeardownWaitsForBuildCommandDiscovery 和 TestPluginTeardownWaitsForDiscoveryAfterProjectCloses 覆盖。原有后端发现路径仍可用。" +} diff --git a/shared/platform-feature-matrix/features/terminal-shell-integration.json b/shared/platform-feature-matrix/features/terminal-shell-integration.json index 6681512a4b..5f8bc44942 100644 --- a/shared/platform-feature-matrix/features/terminal-shell-integration.json +++ b/shared/platform-feature-matrix/features/terminal-shell-integration.json @@ -62,6 +62,6 @@ ] }, "owner": "Terminal", - "verification": "macOS/Linux 打开默认的 zsh 或 bash 终端:Lithe 经 /bin/sh 小脚本启动用户 Shell,用户自己的启动文件、历史记录和提示符照常生效(TestIntegratedBashStartupMatchesALoginShell、TestIntegratedZshHistorySurvivesSessions)。执行一条命令后,Shell 带着本次启动新生成的令牌上报提示符、命令开始与结束和退出码(OSC 133 A/B/C/D);其他程序打印的同样序列、嵌套 Shell 和重启前旧 Shell 的令牌都不被采信(TestIntegratedShellReportsPromptsAndCommands、TestTheUsersShellReportsItsPromptsUnderATokenNewToEachStart)。bash 的登录配置把 PROMPT_COMMAND 设成数组、在 PS0 前放命令替换(systemd 257 起的 /etc/profile.d/80-systemd-osc-context.sh 就这样做,Ubuntu 26.04 默认带),或用户自己的 DEBUG trap 回显 BASH_COMMAND 时,每条命令行仍只上报一次命令开始,用户的 PROMPT_COMMAND、PS0 和 DEBUG trap 照常运行;Bash 4.4 起的 PS0 路径和更早 Bash 的 DEBUG trap 路径都覆盖(TestIntegratedBashReportsEachCommandLineOnce、TestIntegratedBashDebugTrapReportsEachCommandLineOnce、TestIntegratedSystemBashReportsEachCommandLineOnce)。带参数启动的程序、插件终端、Git Bash 和未识别的 Shell 不带令牌,照原样启动(TestAProgramWithArgumentsOfItsOwnGetsNoToken、TestShellsTheIntegrationDoesNotCoverStartAsThemselves)。启动文件写在 Lithe 于 TMPDIR 下新建、仅本人可读的临时目录,sh 写完后直接变成用户 Shell(exec),Shell 读完启动文件即删除目录;Shell 结束后 Lithe 再删一次,所以启动中途被关闭、挂断被忽略而被强制结束时也不留目录、不留 Shell 进程(TestClosingAShellDuringItsStartupRemovesItsPrivateDirectory),应用包字节不变(verify-runtime-bundle-immutability.sh)。终端启动的进程仍是用户 Shell,关闭确认的忙碌判断、挂断与退出码都和不集成时一样;关闭终端时 Shell 与它的后台任务都收到挂断(TestClosingAnIntegratedShellHangsUpTheShellAndItsJobs)。命令刚结束、Shell 还没回到提示符(bash 正在运行 PROMPT_COMMAND)时关闭终端,Lithe 等 Shell 打出提示符标记再挂断,最多等 1 秒,后台任务同样结束;一直不回提示符的 Shell 在 1 秒后照常挂断(TestClosingAnIntegratedShellRightAfterACommandHangsUpItsJobs、TestClosingAnIntegratedShellThatNeverPromptsStillEndsIt、TestPromptMarksFindTheSessionsMarksInPiecesOfOutput)。 在提示符处拖动窗口或分隔条改变终端宽度:屏幕跟随每一步,提示符行留给 Shell 自己重绘,Shell 在尺寸保持 100 毫秒后只收到一次新尺寸,回到原尺寸则不发送;结束后只有一份提示符,没有重复或被截断的提示符行(TestAShellAtItsPromptIsToldItsSizeOnceItHolds、TestASizeThatComesBackIsNotSentToAShellAtItsPrompt、TestResizeLeavesTheShellPromptForTheShellToRedraw、TestResizeBackToItsWidthRestoresThePrompt)。运行命令或全屏程序时尺寸立即发送(TestAProgramIsToldItsSizeAtOnce)。 在正在输入的命令行上单击或 Option+单击:Shell 光标移到点击处(按程序要求的光标键编码发送左右方向键,宽字符、软换行按显示计算);拖动仍是选择,点在提示符上、输入行以外、命令运行中或备用屏时不发送按键(TestOptionClickMovesTheShellCursorWithinTheInputLine、TestPlainClickMovesTheCursorButADragDoesNot、TestAClickLeavesTheKeyboardAloneWhereItCannotPlaceTheCursor、TestInputMoveAcrossSoftWrap)。与 Motty 一致,Shell 至少执行过一条命令后点击移动才生效。 Windows:PowerShell 5.1 与 7 在 PSReadLine 交回用户确认的命令行后、命令运行前上报命令开始(包住 PSConsoleHostReadLine,行内容和上一条命令的成败状态不变,没有 PSReadLine 时不包;TestPowerShellReadLineIntegrationMarksTheCommandStart),之后提示符处延迟调整大小和点击移动光标对 PowerShell 生效(TestWindowsShellsMarkTheirPromptsUnderTheToken)。cmd 读完一行就直接运行,没有可插入的时机,只上报提示符,这两项对它不生效,尺寸立即发送、点击只是点击。WSL 发行版里的 bash/zsh 走同一脚本,三项都生效。Windows 运行时测试与 PowerShell、cmd、WSL 实机验收 pending;macOS 真实产品交互验收 pending。", + "verification": "macOS/Linux 打开默认的 zsh 或 bash 终端:Lithe 经 /bin/sh 小脚本启动用户 Shell,用户自己的启动文件、历史记录和提示符照常生效(TestIntegratedBashStartupMatchesALoginShell、TestIntegratedZshHistorySurvivesSessions)。执行一条命令后,Shell 带着本次启动新生成的令牌上报提示符、命令开始与结束和退出码(OSC 133 A/B/C/D);其他程序打印的同样序列、嵌套 Shell 和重启前旧 Shell 的令牌都不被采信(TestIntegratedShellReportsPromptsAndCommands、TestTheUsersShellReportsItsPromptsUnderATokenNewToEachStart)。bash 的登录配置把 PROMPT_COMMAND 设成数组、在 PS0 前放命令替换(systemd 257 起的 /etc/profile.d/80-systemd-osc-context.sh 就这样做,Ubuntu 26.04 默认带),或用户自己的 DEBUG trap 回显 BASH_COMMAND 时,每条命令行仍只上报一次命令开始,用户的 PROMPT_COMMAND、PS0 和 DEBUG trap 照常运行;Bash 4.4 起的 PS0 路径和更早 Bash 的 DEBUG trap 路径都覆盖(TestIntegratedBashReportsEachCommandLineOnce、TestIntegratedBashDebugTrapReportsEachCommandLineOnce、TestIntegratedSystemBashReportsEachCommandLineOnce)。带参数启动的程序、插件终端、Git Bash 和未识别的 Shell 不带令牌,照原样启动(TestAProgramWithArgumentsOfItsOwnGetsNoToken、TestShellsTheIntegrationDoesNotCoverStartAsThemselves)。启动文件写在 Lithe 于 TMPDIR 下新建、仅本人可读的临时目录,sh 写完后直接变成用户 Shell(exec),Shell 读完启动文件即删除目录;Shell 结束后 Lithe 再删一次,所以启动中途被关闭、挂断被忽略而被强制结束时也不留目录、不留 Shell 进程(TestClosingAShellDuringItsStartupRemovesItsPrivateDirectory),应用包字节不变(verify-runtime-bundle-immutability.sh)。终端启动的进程仍是用户 Shell,关闭确认的忙碌判断、挂断与退出码都和不集成时一样;关闭终端时 Shell 与它的后台任务都收到挂断(TestClosingAnIntegratedShellHangsUpTheShellAndItsJobs)。Shell 退出后再关闭伪终端主端,避免读取 EOF 抢在挂断处理之前(TestCloseLetsTheShellHandleHangupBeforeReleasingThePTY)。命令刚结束、Shell 还没回到提示符(bash 正在运行 PROMPT_COMMAND)时关闭终端,Lithe 等 Shell 打出提示符标记再挂断,最多等 1 秒,后台任务同样结束;一直不回提示符的 Shell 在 1 秒后照常挂断(TestClosingAnIntegratedShellRightAfterACommandHangsUpItsJobs、TestClosingAnIntegratedShellThatNeverPromptsStillEndsIt、TestPromptMarksFindTheSessionsMarksInPiecesOfOutput)。 在提示符处拖动窗口或分隔条改变终端宽度:屏幕跟随每一步,提示符行留给 Shell 自己重绘,Shell 在尺寸保持 100 毫秒后只收到一次新尺寸,回到原尺寸则不发送;结束后只有一份提示符,没有重复或被截断的提示符行(TestAShellAtItsPromptIsToldItsSizeOnceItHolds、TestASizeThatComesBackIsNotSentToAShellAtItsPrompt、TestResizeLeavesTheShellPromptForTheShellToRedraw、TestResizeBackToItsWidthRestoresThePrompt)。运行命令或全屏程序时尺寸立即发送(TestAProgramIsToldItsSizeAtOnce)。 在正在输入的命令行上单击或 Option+单击:Shell 光标移到点击处(按程序要求的光标键编码发送左右方向键,宽字符、软换行按显示计算);拖动仍是选择,点在提示符上、输入行以外、命令运行中或备用屏时不发送按键(TestOptionClickMovesTheShellCursorWithinTheInputLine、TestPlainClickMovesTheCursorButADragDoesNot、TestAClickLeavesTheKeyboardAloneWhereItCannotPlaceTheCursor、TestInputMoveAcrossSoftWrap)。与 Motty 一致,Shell 至少执行过一条命令后点击移动才生效。 Windows:PowerShell 5.1 与 7 在 PSReadLine 交回用户确认的命令行后、命令运行前上报命令开始(包住 PSConsoleHostReadLine,行内容和上一条命令的成败状态不变,没有 PSReadLine 时不包;TestPowerShellReadLineIntegrationMarksTheCommandStart),之后提示符处延迟调整大小和点击移动光标对 PowerShell 生效(TestWindowsShellsMarkTheirPromptsUnderTheToken)。cmd 读完一行就直接运行,没有可插入的时机,只上报提示符,这两项对它不生效,尺寸立即发送、点击只是点击。WSL 发行版里的 bash/zsh 走同一脚本,三项都生效。Windows 运行时测试与 PowerShell、cmd、WSL 实机验收 pending;macOS 真实产品交互验收 pending。", "notes": "2026-11-16:同步 Motty 203857c9(调整大小只保留一份提示符)与 b2357d69(点击命令行移动光标),并把 Motty internal/sshconn/integration.go(0ae3ba59)的 bash/zsh 集成脚本用于本地 Shell 与 WSL,见 termview/NOTICE。#1984 留下的令牌链路(localshell.Config.PromptToken,原名 DirectoryToken;term.SetPromptToken)由 termview 接通,每次启动生成新令牌;Windows 的 PowerShell/cmd 集成因此首次真正启用。#1984 随后删除了没有消费方的部分:term 的目录、提示符、命令与输入环境回调和 OSC 7、OSC 9;9 目录解析,以及集成脚本里的目录上报(Unix OSC 7,WSL、PowerShell、cmd 的 OSC 9;9);OSC 133 标记照常上报并被使用(TestPromptMarksAcrossEverySplit、TestACommandEndReclaimsOnlyWithAValidStatus),WSL 起始目录(MOTTY_WSL_CD)保留(TestWSLScriptStartsTheLoginShellInTheStartFolder)。与 Motty 的差异:不提供点击移动的设置开关;调整大小不等待鼠标松开,只等尺寸保持 100 毫秒;见 .agents/notes/implemented/architecture/2026-11-16-local-shell-integration-shim.md。Windows 为 partial:cmd 不上报命令开始,后两项在 cmd 中不生效;PowerShell 自 #2008 起经 PSReadLine 上报命令开始(与 VS Code 的 PowerShell 集成做法相同)。 2026-11-16:#2005 关闭时把挂断推迟到 Shell 回到提示符(最多 1 秒),修复 bash 在 PROMPT_COMMAND 期间被关闭时留下后台任务;Windows 后端不跟踪提示符标记,行为不变。 2026-11-16:bash 的 PS0 改用提示符转义写命令开始标记,赋值语句的文本里不再带标记字节,用户 DEBUG trap 回显 BASH_COMMAND 时不会伪造一次命令开始;DEBUG trap 路径遇到数组形式的 PROMPT_COMMAND 也在首尾加入钩子,不再整段跳过而一次命令开始都不报。这两处与 Motty 的脚本不同。" } diff --git a/shared/platform-feature-matrix/features/workspace-trust.json b/shared/platform-feature-matrix/features/workspace-trust.json index e9ade6db16..f15acf0ec5 100644 --- a/shared/platform-feature-matrix/features/workspace-trust.json +++ b/shared/platform-feature-matrix/features/workspace-trust.json @@ -22,6 +22,6 @@ ] }, "owner": "Workspace", - "verification": "打开一个没有信任记录的文件夹,先出现“信任并打开项目”对话框,按钮依次为不打开、以安全模式预览、信任项目,并可勾选信任父文件夹;不打开时当前项目不变。信任后再次打开不再询问;勾选父文件夹后同级项目直接以信任打开。以安全模式预览后,编辑器上方显示安全模式提示条,构建窗口不加载模型,运行、构建、测试和重新加载前先问“信任项目?”,选择保持安全模式时不运行;点提示条的“信任项目…”信任后提示条消失,模型和标题栏运行配置自动加载。确认偏好目录 toolchains/global.json 记录决定,项目目录中没有新增 .lithe 文件。", + "verification": "打开一个没有信任记录的文件夹,先出现“信任并打开项目”对话框,按钮依次为不打开、以安全模式预览、信任项目,并可勾选信任父文件夹,父文件夹标签使用当前平台的路径分隔符;不打开时当前项目不变。信任后再次打开不再询问;勾选父文件夹后同级项目直接以信任打开。以安全模式预览后,编辑器上方显示安全模式提示条,构建窗口不加载模型,运行、构建、测试和重新加载前先问“信任项目?”,选择保持安全模式时不运行;点提示条的“信任项目…”信任后提示条消失,模型和标题栏运行配置自动加载。确认偏好目录 toolchains/global.json 记录决定,项目目录中没有新增 .lithe 文件。", "notes": "2026-11-19(#2201):对齐 IntelliJ IDEA 的可信项目。信任状态(trusted/distrusted/unknown 与可信位置)由 Core 的工具链目录判定,计划请求带 projectCodeAllowed,Core 拒绝会运行项目代码的计划(plugin.build.untrustedWorkspace)。宿主无平台分支,两个平台共用同一实现;尚未在两个平台做真实应用验收。语言服务器和 Git 在安全模式下仍启动、可信位置没有独立设置页,分别由 #2208、#2207 跟进。" }