From 96bea43b7ebecdab5da913ccbea303c1843841a8 Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Sat, 21 Nov 2026 20:10:44 -0800 Subject: [PATCH 1/3] feat(remote): wire desktop plugin execution, debugging and deployment Refs 1lck/Lithe-IDEA#2231 --- .../2026-10-24-remote-workspace-routing.md | 12 + desktop/internal/buildprefs/documents.go | 24 +- desktop/internal/buildprocess/remote.go | 104 ++++ desktop/internal/core/build.go | 32 +- desktop/internal/core/debug.go | 29 +- desktop/internal/core/debug_state.go | 28 + desktop/internal/core/debug_transport.go | 4 +- desktop/internal/core/marketplace.go | 96 ++++ desktop/internal/core/plugin_files.go | 106 ++++ desktop/internal/core/plugin_session.go | 47 +- .../internal/core/plugin_setting_actions.go | 32 +- desktop/internal/core/remote.go | 21 + .../internal/core/remote_native_settings.go | 75 +++ desktop/internal/core/remote_plugin.go | 89 ++++ desktop/internal/core/remote_plugin_test.go | 51 ++ desktop/internal/core/remote_process.go | 155 ++++++ desktop/internal/core/remote_runtime.go | 57 ++ desktop/internal/core/remote_session.go | 174 +++++- desktop/internal/core/remote_session_test.go | 57 +- desktop/internal/core/remote_terminal.go | 21 +- desktop/internal/core/remote_terminal_test.go | 12 +- desktop/internal/core/run_config.go | 16 + desktop/internal/core/run_start.go | 9 + desktop/internal/core/source_settings.go | 3 +- desktop/internal/core/toolchain.go | 27 +- .../lock.go => filelock/filelock.go} | 27 +- .../{pluginruntime => filelock}/lock_unix.go | 2 +- .../lock_windows.go | 2 +- desktop/internal/i18n/run_messages.go | 18 +- desktop/internal/i18n/shared.generated.go | 20 + .../marketplace/remote_archive_cache.go | 229 ++++++++ .../marketplace/remote_archive_cache_test.go | 75 +++ desktop/internal/marketplace/service.go | 25 + .../internal/pluginbackend/log_facts_test.go | 36 ++ .../internal/pluginbackend/pluginbackend.go | 230 ++++++-- .../pluginbackend/pluginbackend_test.go | 124 +++++ desktop/internal/pluginhost/hostservices.go | 39 +- desktop/internal/pluginhost/pluginhost.go | 2 +- .../internal/pluginhost/pluginhost_test.go | 5 +- .../plugininstall/installed_snapshot.go | 207 ++++++++ .../plugininstall/installed_snapshot_other.go | 7 + .../plugininstall/installed_snapshot_unix.go | 8 + .../internal/plugininstall/plugininstall.go | 98 ++-- .../plugininstall/plugininstall_test.go | 65 ++- .../internal/plugininstall/remote_variant.go | 51 ++ desktop/internal/pluginruntime/mirrors.go | 3 +- desktop/internal/pluginruntime/runtime.go | 15 +- desktop/internal/pluginservice/activation.go | 2 +- desktop/internal/pluginservice/backendhost.go | 13 +- .../internal/pluginservice/backendlaunch.go | 55 +- desktop/internal/pluginservice/backends.go | 78 ++- desktop/internal/pluginservice/contexts.go | 128 +++-- desktop/internal/pluginservice/debug_start.go | 17 +- desktop/internal/pluginservice/hostactions.go | 8 +- .../pluginservice/hostactions_refresh_test.go | 2 +- desktop/internal/pluginservice/hostbuild.go | 47 +- .../internal/pluginservice/hostbuild_test.go | 88 ++++ desktop/internal/pluginservice/hostcontent.go | 9 +- .../internal/pluginservice/hostdocuments.go | 33 +- desktop/internal/pluginservice/hostfiles.go | 129 +++++ .../internal/pluginservice/hostfiles_test.go | 62 +++ desktop/internal/pluginservice/hostmethods.go | 103 +++- .../pluginservice/hostmethods_test.go | 81 +++ .../internal/pluginservice/hostproviders.go | 8 +- .../internal/pluginservice/hostresources.go | 16 +- desktop/internal/pluginservice/hostsurface.go | 47 +- .../internal/pluginservice/hostterminal.go | 79 ++- desktop/internal/pluginservice/hostwatch.go | 208 ++++++++ .../internal/pluginservice/hostwatch_test.go | 96 ++++ .../internal/pluginservice/lifecycle_test.go | 48 ++ desktop/internal/pluginservice/pages.go | 108 +++- desktop/internal/pluginservice/pages_test.go | 56 +- .../internal/pluginservice/pluginservice.go | 10 +- .../pluginservice/pluginservice_test.go | 20 + .../pluginservice/remote_deployment.go | 283 ++++++++++ desktop/internal/pluginservice/remote_runs.go | 226 ++++++++ .../pluginservice/remote_runs_test.go | 279 ++++++++++ .../internal/pluginservice/remote_runtimes.go | 155 ++++++ .../internal/pluginservice/remote_settings.go | 148 ++++++ desktop/internal/pluginservice/runs.go | 497 ++++++++++++------ desktop/internal/pluginservice/runs_test.go | 11 +- desktop/internal/pluginservice/settings.go | 33 +- .../internal/pluginservice/settings_editor.go | 67 ++- .../pluginservice/settings_start_test.go | 109 ++++ .../pluginservice/toolchain_provider.go | 5 +- desktop/internal/pluginsettings/remote.go | 104 ++++ .../internal/pluginsettings/remote_sources.go | 186 +++++++ desktop/internal/pluginsettings/sources.go | 26 +- desktop/internal/pluginsettings/store.go | 57 +- desktop/internal/plugintrust/plugintrust.go | 48 +- desktop/internal/pluginweb/page.go | 17 +- desktop/internal/pluginweb/page_test.go | 2 +- .../settingswindow/page_driver_test.go | 25 +- .../internal/settingswindow/plugin_install.go | 2 + .../settingswindow/plugin_settings_view.go | 4 + .../settingswindow/source_settings_entries.go | 1 + .../source_settings_entries_view.go | 26 +- .../settingswindow/source_settings_view.go | 77 ++- .../source_settings_view_test.go | 80 +++ desktop/internal/termview/menu.go | 2 +- desktop/internal/termview/session.go | 8 +- desktop/internal/termview/view.go | 2 + desktop/internal/toolchain/load.go | 21 +- desktop/internal/workbench/app.go | 18 + desktop/internal/workbench/build.go | 478 ++++++++++++----- .../workbench/build_connection_debug.go | 76 ++- .../internal/workbench/build_dependencies.go | 29 +- desktop/internal/workbench/build_options.go | 2 +- .../workbench/build_options_runtime.go | 14 +- desktop/internal/workbench/debug.go | 31 +- .../internal/workbench/debug_adapter_test.go | 15 + desktop/internal/workbench/debug_announced.go | 18 +- desktop/internal/workbench/debug_child.go | 24 +- desktop/internal/workbench/debug_kernel.go | 1 + desktop/internal/workbench/debug_launch.go | 134 ++++- .../internal/workbench/debug_launch_test.go | 8 +- .../workbench/debug_remote_terminal.go | 76 +++ .../workbench/debug_remote_terminal_test.go | 144 +++++ .../workbench/debug_remote_transport.go | 207 ++++++++ desktop/internal/workbench/debug_start.go | 150 ++++-- .../workbench/debug_stdio_ssh_test.go | 133 +++++ desktop/internal/workbench/debug_transport.go | 46 +- .../workbench/debug_tunnel_ssh_test.go | 389 ++++++++++++++ desktop/internal/workbench/documents.go | 51 +- .../internal/workbench/documents_tabless.go | 6 +- desktop/internal/workbench/editor_actions.go | 10 +- desktop/internal/workbench/editor_session.go | 2 +- .../internal/workbench/plugin_auto_update.go | 18 +- desktop/internal/workbench/plugin_programs.go | 2 +- .../workbench/plugin_recommendations.go | 2 +- .../workbench/plugin_recommendations_test.go | 3 +- desktop/internal/workbench/plugin_settings.go | 17 +- desktop/internal/workbench/pluginbackends.go | 36 +- desktop/internal/workbench/pluginpages.go | 127 +++-- desktop/internal/workbench/plugins.go | 18 +- desktop/internal/workbench/plugins_test.go | 6 +- desktop/internal/workbench/pluginsync.go | 3 +- .../internal/workbench/pluginsync_e2e_test.go | 2 +- desktop/internal/workbench/pluginterminals.go | 37 ++ desktop/internal/workbench/remote_browse.go | 16 +- .../workbench/remote_build_process.go | 163 ++++++ .../internal/workbench/remote_build_test.go | 129 +++++ .../workbench/remote_documents_test.go | 34 ++ desktop/internal/workbench/remote_git_test.go | 49 +- .../remote_native_settings_ssh_test.go | 298 +++++++++++ .../remote_plugin_variant_ssh_test.go | 491 +++++++++++++++++ desktop/internal/workbench/remote_run.go | 159 ++++-- desktop/internal/workbench/remote_run_test.go | 157 ++++-- .../workbench/remote_run_visual_test.go | 3 +- desktop/internal/workbench/remote_terminal.go | 86 ++- .../workbench/remote_terminal_test.go | 109 +++- desktop/internal/workbench/remote_watch.go | 13 +- .../internal/workbench/remote_workspace.go | 62 ++- .../workbench/remote_workspace_test.go | 175 +++++- desktop/internal/workbench/runconfig.go | 45 +- .../workbench/runconfig_before_launch.go | 36 +- .../internal/workbench/runconfig_changes.go | 28 + .../internal/workbench/runconfig_dialog.go | 8 +- desktop/internal/workbench/runconfig_edit.go | 8 +- desktop/internal/workbench/runconfig_form.go | 12 +- .../internal/workbench/runconfig_process.go | 4 +- desktop/internal/workbench/runconfig_types.go | 105 ++-- desktop/internal/workbench/runs.go | 76 ++- .../workbench/settings_plugin_actions.go | 15 +- .../workbench/settings_plugin_sources.go | 93 +++- .../internal/workbench/settings_plugins.go | 26 +- .../workbench/settings_publication.go | 12 +- desktop/internal/workbench/shell_view.go | 5 +- desktop/internal/workbench/terminals.go | 23 +- .../testdata/remote_debug_adapter/main.go | 106 ++++ .../testdata/remote_debuggee/main.go | 162 ++++++ .../testdata/remote_settings_helper/main.go | 148 ++++++ .../testdata/remote_variant_server/main.go | 90 ++++ desktop/internal/workbench/tests.go | 74 +-- desktop/internal/workbench/tests_test.go | 33 +- desktop/internal/workbench/tests_view.go | 7 +- desktop/internal/workbench/title_run.go | 12 +- .../workbench/title_run_entrypoints.go | 28 +- desktop/internal/workbench/title_run_test.go | 4 +- desktop/internal/workbench/toolchains.go | 16 +- desktop/internal/workbench/vcs.go | 168 ++++-- desktop/internal/workbench/workspace_trust.go | 18 +- docs/ci-builds.md | 10 +- scripts/desktop/build-desktop-core.sh | 7 +- .../features/plugin-managed-runtimes.json | 14 + .../features/plugin-native-terminals.json | 21 + shared/i18n/features/run-remote.json | 28 + shared/i18n/locales/en-US.json | 6 + shared/i18n/locales/zh-CN.json | 6 + shared/i18n/messages.json | 45 ++ .../features/build-system-plugins.json | 8 +- .../features/debug-tcp-transport.json | 12 +- .../features/declarative-plugin-settings.json | 12 +- .../features/plugin-backend-run-start.json | 8 +- .../plugin-backend-workspace-context.json | 10 +- ...ugin-host-editor-file-window-services.json | 12 +- .../plugin-language-server-sessions.json | 12 +- .../features/plugin-managed-runtimes.json | 10 +- .../features/plugin-native-terminals.json | 10 +- .../remote-development-workspace.json | 48 +- .../features/remote-workspace.json | 12 +- 201 files changed, 11119 insertions(+), 1432 deletions(-) create mode 100644 desktop/internal/buildprocess/remote.go create mode 100644 desktop/internal/core/plugin_files.go create mode 100644 desktop/internal/core/remote_native_settings.go create mode 100644 desktop/internal/core/remote_plugin.go create mode 100644 desktop/internal/core/remote_plugin_test.go create mode 100644 desktop/internal/core/remote_runtime.go rename desktop/internal/{pluginruntime/lock.go => filelock/filelock.go} (70%) rename desktop/internal/{pluginruntime => filelock}/lock_unix.go (93%) rename desktop/internal/{pluginruntime => filelock}/lock_windows.go (94%) create mode 100644 desktop/internal/marketplace/remote_archive_cache.go create mode 100644 desktop/internal/marketplace/remote_archive_cache_test.go create mode 100644 desktop/internal/plugininstall/installed_snapshot.go create mode 100644 desktop/internal/plugininstall/installed_snapshot_other.go create mode 100644 desktop/internal/plugininstall/installed_snapshot_unix.go create mode 100644 desktop/internal/plugininstall/remote_variant.go create mode 100644 desktop/internal/pluginservice/hostfiles.go create mode 100644 desktop/internal/pluginservice/hostfiles_test.go create mode 100644 desktop/internal/pluginservice/hostwatch.go create mode 100644 desktop/internal/pluginservice/hostwatch_test.go create mode 100644 desktop/internal/pluginservice/remote_deployment.go create mode 100644 desktop/internal/pluginservice/remote_runs.go create mode 100644 desktop/internal/pluginservice/remote_runs_test.go create mode 100644 desktop/internal/pluginservice/remote_runtimes.go create mode 100644 desktop/internal/pluginservice/remote_settings.go create mode 100644 desktop/internal/pluginsettings/remote.go create mode 100644 desktop/internal/pluginsettings/remote_sources.go create mode 100644 desktop/internal/workbench/debug_remote_terminal.go create mode 100644 desktop/internal/workbench/debug_remote_terminal_test.go create mode 100644 desktop/internal/workbench/debug_remote_transport.go create mode 100644 desktop/internal/workbench/debug_stdio_ssh_test.go create mode 100644 desktop/internal/workbench/debug_tunnel_ssh_test.go create mode 100644 desktop/internal/workbench/remote_build_process.go create mode 100644 desktop/internal/workbench/remote_build_test.go create mode 100644 desktop/internal/workbench/remote_native_settings_ssh_test.go create mode 100644 desktop/internal/workbench/remote_plugin_variant_ssh_test.go create mode 100644 desktop/internal/workbench/testdata/remote_debug_adapter/main.go create mode 100644 desktop/internal/workbench/testdata/remote_debuggee/main.go create mode 100644 desktop/internal/workbench/testdata/remote_settings_helper/main.go create mode 100644 desktop/internal/workbench/testdata/remote_variant_server/main.go create mode 100644 shared/i18n/features/plugin-native-terminals.json create mode 100644 shared/i18n/features/run-remote.json diff --git a/.agents/notes/implemented/architecture/2026-10-24-remote-workspace-routing.md b/.agents/notes/implemented/architecture/2026-10-24-remote-workspace-routing.md index ec257f409c..def4b5cb13 100644 --- a/.agents/notes/implemented/architecture/2026-10-24-remote-workspace-routing.md +++ b/.agents/notes/implemented/architecture/2026-10-24-remote-workspace-routing.md @@ -23,10 +23,17 @@ - **运行时与 Shell 发现**:网络调用在平台工作线程运行,界面读取缓存;发现有数量、数据和时间限制,取消或切换工作区后丢弃旧结果,失败不发布部分结果或本机回退。Shell 从远端登录环境、`/etc/shells` 和文件权限发现,旧服务缺目标权限时再查询链接真实路径;本机终端设置里的可执行文件路径不作为远程默认值。 - **资源生命周期**:Git 临时索引和源文件快照在远端临时目录或 Git common directory,由单次操作清理;探测、可执行文件与搜索缓存保存在客户端内存并按连接隔离。服务的 socket、锁和日志身份同时包含会话键与二进制 SHA-256,版本号相同但内容变化时不复用旧常驻进程。以上资源不跨工作树复制,运行时不写安装资源,不改变签名和 Sparkle delta 基线。 - **构建与插件运行**:构建扫描、工具探测、构建进程和报告读取使用原工作区的主机身份,stdout/stderr 分别增量解码。插件只部署经过原安装来源复核的包,异平台变体必须同版本、同声明且不增加批准程序;复用市场校验和下载器,不向小型服务引入包管理或语言引擎。目标文件通过带 SHA-256 的分块上传原子发布,普通文件只读、可执行文件只读可执行,可写状态位于远端用户目录。快照清理捕获原连接,在 Core 销毁进程后执行。 +- **桌面缓存与同平台包**:异平台 ZIP 以索引 SHA-256 命名,保存在系统用户缓存目录,有总容量和文件数上限,复用时重新验哈希。同平台安装包先复制到私有临时目录,检查安装审批记录绑定的文件名、大小、内容和执行位,再复核清单。缺少新校验值的旧市场安装包走已批准来源的 ZIP 路径。缓存与快照均独立于安装目录和构建检出。 - **上传不互相拖住**:上传表只登记和移除身份,不把文件打开、写入、同步、发布或删除放在全局锁里。每个文件独立同步,同一上传的并发操作返回 `BUSY`;断线、取消和到期先标记取消,由仍在执行的工作线程保管并最终删除暂存文件。一个慢文件不能阻止另一个文件完成,释放动作也不能等慢文件的锁。 - **stdio 与启动**:语言、构建和 VCS 提供者复用 Core 的协议引擎,远程通道保留有界输入输出与原连接。异步部署、工具探测和启动在工作线程进行,启动期间保留有界文档快照与文件变更,停止后到达的会话先销毁再删除包。仅映射协议定义的 URI 和 VCS 路径字段,参数、文本与插件自定义值保持原样。依赖本机原生集成的 Java 仍明确拒绝,不能伪装成通用 stdio 已支持。 - **常驻服务启动只允许一个代理创建进程**:daemon 的存活锁只能防止同时服务,不能阻止竞争失败的启动进程在旧会话关闭后接管锁。代理在启动前先取得同一身份的 `.start` 文件锁,再检查 socket,已有服务就复用;锁覆盖创建进程至 socket 可连接,等待使用原有启动期限。`.start` 位于远端用户私有状态目录的 `run/`,进程关闭文件即释放锁,文件本身保留,避免删除后不同代理锁住不同 inode;它属于远端会话协调状态,不可跨工作树复用,不写安装包,不影响代码签名或 Sparkle delta。验证启动锁互斥、期限、释放及并发连接收到关闭确认后服务确实退出,不用延长测试超时掩盖残留进程。 - **断线与会话结束不同**:常驻会话仅断线时保留终端和进程供重连;非驻留连接断开、显式关闭会话或空闲到期时,迟到发布的资源必须由创建者清理。结束标记在清理现有资源表之前设置,否则慢启动可能在清理后才出现,尤其是常驻会话不能再把它当成“等待重连”的合法资源。 +- **插件工作区身份**:远程上下文使用连接身份和主机平台,沿用按插件隔离的 rootID。宿主只在单独授权的 `workspace/getHostPaths` 中返回对应的 Linux 路径;常规上下文和目录列表不含主机路径或客户端占位目录。插件后端在客户端启动,保留工作区关闭时的取消。同一连接身份、主机目录和平台重连时沿用原上下文版本;任一变化时递增 generation,将订阅和句柄按过期版本释放。本机工具链发现排除远程占位目录。 +- **插件文件读取边界**:宿主校验调用者的 rootID 和上下文版本,通过 Core 传入当前工作区绑定。远端服务从打开的根目录逐级使用目录描述符定位,拒绝跟随子路径中的符号链接。读取最多 128 KiB,目录分页游标绑定到根、路径和上下文版本。Core 只在完整读取时返回内容哈希。 +- **语言服务器设置**:远程 `systemCommand` 启动和运行中的设置刷新使用同一个读取入口。全局设置留在客户端,项目设置通过启动时捕获的连接读取。重连会撤销旧语言服务器会话及其诊断,迟到的读取结果不会进入新会话。这样项目设置始终来自项目所在的主机。 +- **构建选项读取**:插件查询构建选项时,从原连接读取项目里的团队配置,再由 Core 应用该远程工作区在客户端保存的个人覆盖。客户端占位目录只作为个人偏好的存储键。工作区关闭或连接更换后丢弃旧结果,避免把错误当成缺失配置后继续执行。 +- **插件终端**:受信任的远程项目里,确认框显示连接、程序、参数和远端工作目录。确认只对当时的连接有效,重连后需要重新发起请求。程序复用已有的远端伪终端,工作目录由远端服务从项目根目录逐级打开并拒绝跟随子路径中的符号链接。环境变量在远端登录环境上应用,关闭标签后由原会话回收进程。 +- **插件发起远端运行**:启动前和远端确认启动后都复核信任、工作区世代和连接身份。确认后的进程由 Run 窗口持有,后端请求结束不影响运行。关闭工作区或更换连接时取消原进程,等远端进程回收后在原会话释放临时文件。这样旧请求不会跨到重连后的主机,也不会在本机进程记录里混入远端 PID。工具版本探测和启动都用目录描述符限定在同一工作区。 ### 正确做法 @@ -65,6 +72,9 @@ - 新增适配覆盖:远端 PTY、按主机探测环境、Git 文件与进程 I/O、搜索索引与 Shift+Shift 的文件及内容查询。真实服务 fixture 已覆盖状态、暂存、分页历史、设置来源、worktree 创建和管理、克隆、保留无关暂存的选择文件提交,以及未保存缓冲区的行历史;不能据此把完整真实 SSH 产品流程标为已验收。 - 文件树新建、复制、重命名、移到主机废纸篓和普通删除已接入;外部修改监听覆盖文件树与文档,真实 SSH 的原生 watcher 仍需产品验收。 - 构建 I/O、工具与状态目录适配,以及通用插件部署和 stdio 提供者接入已有实现与 fixture;真实 SSH 的完整构建、插件启动与取消链路仍待验收。 +- 插件的文件名和文本搜索在远端服务中执行,每页有整次遍历、字节和时间预算。游标记录原连接和已返回结果的摘要。插件监听复用工作台的递归监听,每个订阅独立合并事件,发生缺口或重连时请求重扫。 +- 本机后端解析远程语言服务器时,只接收目标平台和远端工具安装信息。Core 验证回答中的工具 ID 后,直接使用远端选定的路径和环境启动。私有远端目录与打包资源的生命周期由远端部署负责。 +- 每次连接或重连都在原会话上提交 Core 按语义版本选出的当前安装版本,禁用的插件也保留其当前版本。本机可用于回滚的旧版本不进入远端保留清单。清单读取或版本选择失败时跳过清理。远端服务在发布或复用部署时取得会话共享锁,等会话进程停止后释放。只有取得独占锁才移除已卸载或升级的版本,避免另一个工作区失去仍在使用的文件。 - 连接在工作区关闭后仍保留,直到 App 退出。 - 代价:主机调用增加往返时间,远端无有效工具或连接中断时必须明确失败;缓存与长期资源都需要保留原连接身份,不能复用本机路径命中的结果。 - 当前限制:Git 原子写入仍保留 8 MiB 上限;新分块上传仅用于已批准插件文件,不代表 Git 大文件临时内容已经接入。 @@ -72,6 +82,8 @@ ## 验证 - 在 Core 仓库运行 `cargo test -p lithe-remote`:协议、服务端与客户端的 Linux 真实服务测试。 +- 在 Core 仓库运行 `cargo test -p lithe-remote --all-features --test run_directories`,验证完整发布、多个会话复用、按清单回收无租约版本和服务强制退出后回收废弃暂存目录。桌面端的 `TestSweepRemoteDeploymentsKeepsOnlyCurrentVersions` 检查版本排序、保留禁用插件和本机回滚包。 +- 在桌面端运行 `./scripts/desktop/desktop-go.sh test ./internal/pluginservice ./internal/workbench`:覆盖元数据、路径权限边界,以及连接、重连与关闭时的上下文生命周期;真实 SSH 和 Windows 原生验收仍待完成。 - `./scripts/desktop/verify/verify-runtime-bundle-immutability.sh`。 - `./scripts/platform-feature-matrix/verify-platform-feature-matrix.sh`。 - `./scripts/agent-notes/verify-agent-notes.sh`。 diff --git a/desktop/internal/buildprefs/documents.go b/desktop/internal/buildprefs/documents.go index 835f9b4c7a..d6a58c948d 100644 --- a/desktop/internal/buildprefs/documents.go +++ b/desktop/internal/buildprefs/documents.go @@ -32,13 +32,31 @@ type Documents struct { // Read reads the team document from the project and the local document from the data // store. A document that exists but is not valid JSON is an error, not an empty document. func Read(ctx context.Context, preferences *store.Store, root string) (Documents, error) { + return read(preferences, root, func() ([]byte, bool, error) { + snapshot, err := configfile.Capture(ctx, root, TeamFile, buildOptionsMaximumBytes) + return snapshot.Bytes(), snapshot.Exists(), err + }) +} + +// ReadRemote reads the team document from a captured workspace connection. +// The client root is used solely as a key into the client's preference store. +func ReadRemote(ctx context.Context, preferences *store.Store, root string, readConfiguration func(context.Context, string, int64) (*string, error)) (Documents, error) { + return read(preferences, root, func() ([]byte, bool, error) { + team, err := readConfiguration(ctx, TeamFile, buildOptionsMaximumBytes) + if err != nil || team == nil { + return nil, false, err + } + return []byte(*team), true, nil + }) +} + +func read(preferences *store.Store, root string, readTeam func() ([]byte, bool, error)) (Documents, error) { docs := Documents{Team: emptyTeam, Local: EmptyLocal} - snapshot, err := configfile.Capture(ctx, root, TeamFile, buildOptionsMaximumBytes) + team, exists, err := readTeam() if err != nil { return docs, err } - if snapshot.Exists() { - team := snapshot.Bytes() + if exists { if !json.Valid(team) { return docs, errors.New(TeamFile + ": invalid JSON") } diff --git a/desktop/internal/buildprocess/remote.go b/desktop/internal/buildprocess/remote.go new file mode 100644 index 0000000000..bc366ec71d --- /dev/null +++ b/desktop/internal/buildprocess/remote.go @@ -0,0 +1,104 @@ +package buildprocess + +import ( + "context" + "errors" + "fmt" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// RemoteRunner streams a process on the workspace's captured connection. +type RemoteRunner interface { + RunRemoteProcess(context.Context, core.RemoteProcessOpen, core.RemoteProcessEvents) (core.RemoteProcessExit, error) +} + +// StartRemote waits for the host to start the process. The startup request may +// cancel it until then. The lifetime context owns the running process. +func StartRemote(ctx, lifetime context.Context, host RemoteRunner, spec core.RemoteProcessOpen, output func(Stream, string)) (*RemoteProcess, error) { + return StartRemoteBytes(ctx, lifetime, host, spec, func(stream string, data []byte) { + if output != nil { + output(Stream(stream), string(data)) + } + }) +} + +// StartRemoteBytes starts the same owned process, preserving stdout and +// stderr as bytes for framed protocols. +func StartRemoteBytes(ctx, lifetime context.Context, host RemoteRunner, spec core.RemoteProcessOpen, output func(string, []byte)) (*RemoteProcess, error) { + lifetime, cancel := context.WithCancel(lifetime) + stopStartup := context.AfterFunc(ctx, cancel) + defer stopStartup() + if err := ctx.Err(); err != nil { + cancel() + return nil, err + } + process := &RemoteProcess{cancel: cancel, done: make(chan struct{})} + started := make(chan struct{}) + go func() { + defer close(process.done) + defer cancel() + exit, err := host.RunRemoteProcess(lifetime, spec, core.RemoteProcessEvents{ + Started: func(processID uint64, _ int) { + process.ID = processID + stopStartup() + close(started) + }, + Output: output, + }) + process.err = err + if err == nil && (exit.Signal != nil || exit.ExitCode == nil || *exit.ExitCode != 0) { + process.err = &RemoteExit{Status: exit} + } + }() + select { + case <-started: + return process, nil + case <-process.done: + select { + case <-started: + return process, nil + default: + if process.err == nil { + return nil, errors.New("remote process exited without a start event") + } + return nil, process.err + } + } +} + +// RemoteProcess owns a Core call. Its PID is never a local process ID. +type RemoteProcess struct { + // ID addresses this process on its captured remote session only. + ID uint64 + cancel context.CancelFunc + done chan struct{} + err error +} + +func (p *RemoteProcess) Wait() error { <-p.done; return p.err } +func (p *RemoteProcess) Stop() { p.cancel() } +func (p *RemoteProcess) Kill() { p.cancel() } +func (p *RemoteProcess) Pid() int { return 0 } + +// RemoteExit is the status reported by the process's host. +type RemoteExit struct { + Status core.RemoteProcessExit +} + +func (e *RemoteExit) ExitCode() int { + if e.Status.ExitCode == nil { + return -1 + } + return *e.Status.ExitCode +} + +func (e *RemoteExit) Error() string { + if e.Status.ExitCode != nil { + return fmt.Sprintf("remote process exited with code %d", *e.Status.ExitCode) + } + if e.Status.Signal != nil { + return fmt.Sprintf("remote process ended with signal %d", *e.Status.Signal) + } + return "remote process ended without an exit status" +} diff --git a/desktop/internal/core/build.go b/desktop/internal/core/build.go index 3bbab5e416..a00d6743fb 100644 --- a/desktop/internal/core/build.go +++ b/desktop/internal/core/build.go @@ -147,18 +147,25 @@ type BuildProviderRequest struct { // BuildPlan is either a command plan or a provider request. A provider plan has // no Arguments; the plugin owns the build semantics. type BuildPlan struct { - BuildSystemID string `json:"buildSystemID"` - Root string `json:"root"` - Arguments []string `json:"arguments"` - Environment map[string]string `json:"environment"` - WorkingDirectory string `json:"workingDirectory"` - Execution string `json:"execution"` - OptionFingerprint string `json:"optionFingerprint"` - Output string `json:"output,omitempty"` - Decoder string `json:"decoder,omitempty"` - ExecutesProjectCode bool `json:"executesProjectCode,omitempty"` - MayUseNetwork bool `json:"mayUseNetwork,omitempty"` - Provider *BuildProviderRequest `json:"provider,omitempty"` + // RequiredPackagePaths is the preflight response for a remote model + // command with package inputs and no deployed plugin directory yet. + RequiredPackagePaths []string `json:"requiredPackagePaths,omitempty"` + BuildSystemID string `json:"buildSystemID"` + Root string `json:"root"` + Arguments []string `json:"arguments"` + Environment map[string]string `json:"environment"` + WorkingDirectory string `json:"workingDirectory"` + Execution string `json:"execution"` + OptionFingerprint string `json:"optionFingerprint"` + Output string `json:"output,omitempty"` + Decoder string `json:"decoder,omitempty"` + ExecutesProjectCode bool `json:"executesProjectCode,omitempty"` + MayUseNetwork bool `json:"mayUseNetwork,omitempty"` + Provider *BuildProviderRequest `json:"provider,omitempty"` + // Results is set only for a test plan that declares a structured report. + Results *struct { + Decoder string `json:"decoder"` + } `json:"results,omitempty"` } // BuildDecodeModelRequest decodes a static or command model, or the result a @@ -264,6 +271,7 @@ type BuildLaunch struct { Arguments []string `json:"arguments"` WorkingDirectory string `json:"workingDirectory"` Environment map[string]string `json:"environment"` + Placement ProcessPlacement `json:"placement,omitempty"` OutputEncoding string `json:"outputEncoding,omitempty"` } diff --git a/desktop/internal/core/debug.go b/desktop/internal/core/debug.go index 68bf42d2c4..788ec69d4a 100644 --- a/desktop/internal/core/debug.go +++ b/desktop/internal/core/debug.go @@ -41,13 +41,36 @@ type DebugEvent struct { Result *DebugOperationResult `json:"result,omitempty"` Breakpoint *DebugBreakpoint `json:"breakpoint,omitempty"` // Capabilities is set on the `capabilities` event: what the adapter negotiated. - Capabilities *DebugCapabilities `json:"capabilities,omitempty"` - // StartDebugging is set on the `startDebuggingRequested` event. + Capabilities *DebugCapabilities `json:"capabilities,omitempty"` RequestID string `json:"requestId,omitempty"` - StartDebugging *DebugStartDebugging `json:"request,omitempty"` + StartDebugging *DebugStartDebugging `json:"-"` + RunInTerminal *DebugRunInTerminal `json:"-"` ChildSessionID string `json:"childSessionId,omitempty"` } +// UnmarshalJSON decodes the request shared by both reverse-event variants. +func (e *DebugEvent) UnmarshalJSON(data []byte) error { + type eventFields DebugEvent + var wire struct { + eventFields + Request json.RawMessage `json:"request"` + } + if err := json.Unmarshal(data, &wire); err != nil { + return err + } + *e = DebugEvent(wire.eventFields) + if len(wire.Request) == 0 { + return nil + } + switch e.Type { + case "startDebuggingRequested": + return json.Unmarshal(wire.Request, &e.StartDebugging) + case "runInTerminalRequested": + return json.Unmarshal(wire.Request, &e.RunInTerminal) + } + return nil +} + // DebugOperationResult is the typed terminal data of one inspect or execute // operation. Kind is Core's result tag; only the matching fields are set. type DebugOperationResult struct { diff --git a/desktop/internal/core/debug_state.go b/desktop/internal/core/debug_state.go index 6ebd8220fc..69133cf7f7 100644 --- a/desktop/internal/core/debug_state.go +++ b/desktop/internal/core/debug_state.go @@ -76,6 +76,34 @@ type DebugStartDebugging struct { Configuration map[string]any `json:"configuration"` } +// DebugRunInTerminal is an adapter's request to run the debuggee in a terminal. +type DebugRunInTerminal struct { + Title string `json:"title"` + RemoteDirectory *string `json:"remoteDirectory"` + Args []string `json:"args"` + Environment []struct { + Name string `json:"name"` + Value *string `json:"value"` + } `json:"environment"` +} + +// DebugRunInTerminalResponse reports the debuggee PID or a launch failure to Core. +// A zero PID is a failure and message explains it to the adapter. +func (c *Client) DebugRunInTerminalResponse(ctx context.Context, sessionID, requestID string, pid int64, message string) (DebugUpdate, error) { + var update DebugUpdate + payload := struct { + SessionID string `json:"sessionId"` + RequestID string `json:"requestId"` + Success bool `json:"success"` + ProcessID int64 `json:"processId,omitempty"` + Message string `json:"message,omitempty"` + }{sessionID, requestID, pid != 0, pid, message} + if err := c.Execute(ctx, "debug.runInTerminalResponse", payload, &update); err != nil { + return DebugUpdate{}, err + } + return update, nil +} + // DebugStartDebuggingResponse answers one startDebuggingRequested event: the // host reports whether it opened the child session, and Core replies to the // adapter with the original request sequence. diff --git a/desktop/internal/core/debug_transport.go b/desktop/internal/core/debug_transport.go index 33d60bab0f..6888025e1d 100644 --- a/desktop/internal/core/debug_transport.go +++ b/desktop/internal/core/debug_transport.go @@ -10,6 +10,8 @@ import ( // field that does not apply to it stays zero and is not sent. type DebugTransportEvent struct { Type string `json:"type"` + // DirectStream starts with openStream instead of endpoint discovery. + DirectStream bool `json:"directStream,omitempty"` // Limits overrides the policy defaults on a start event. Limits *DebugTransportLimitOverrides `json:"limits,omitempty"` // Bytes is the size of the frame a send event queues. @@ -35,7 +37,7 @@ type DebugTransportLimitOverrides struct { } // DebugTransportEffect is one thing the platform runs after an event. Kind is -// discoverEndpoint, armTimer, cancelTimer, connect, write, deliverData, close, +// discoverEndpoint, armTimer, cancelTimer, connect, openStream, write, deliverData, close, // reportFailure or notifyTermination; only the fields of that kind are set. type DebugTransportEffect struct { Kind string `json:"kind"` diff --git a/desktop/internal/core/marketplace.go b/desktop/internal/core/marketplace.go index 5bd30270a5..e1445a1a97 100644 --- a/desktop/internal/core/marketplace.go +++ b/desktop/internal/core/marketplace.go @@ -28,6 +28,8 @@ type marketplaceOutcome struct { Error *MarketplaceRejection `json:"error"` Index *MarketplaceIndex `json:"index"` Source *MarketplaceSource `json:"source"` + Selection *MarketplaceAvailability `json:"selection"` + Manifest json.RawMessage `json:"manifest"` Review *MarketplaceReview `json:"review"` Recommendation *MarketplaceRecommendationResult `json:"recommendation"` } @@ -180,6 +182,100 @@ func (c *Client) ReviewMarketplaceInstall(ctx context.Context, manifest json.Raw return *result.Review, nil } +// MarketplaceRemoteVariantRequest binds the fetched index to an approved release. +type MarketplaceRemoteVariantRequest struct { + Index json.RawMessage `json:"index"` + SourceKind MarketplaceSourceKind `json:"sourceKind"` + PluginID string `json:"pluginID"` + Version string `json:"version"` + InstalledPlatform string `json:"installedPlatform"` + InstalledSHA256 string `json:"installedSha256"` + Repository string `json:"repository,omitempty"` + Target RemotePlatform `json:"target"` + HostCapabilities map[string][]int `json:"hostCapabilities"` +} + +// SelectMarketplaceRemoteVariant requests only the remote archive of the approved release. +func (c *Client) SelectMarketplaceRemoteVariant(ctx context.Context, request MarketplaceRemoteVariantRequest) (MarketplaceAvailability, error) { + const command = "plugins.marketplace.selectRemoteVariant" + var result marketplaceOutcome + if err := c.Execute(WithoutRemoteWorkspace(ctx), command, request, &result); err != nil { + return MarketplaceAvailability{}, err + } + if err := result.failure(command); err != nil { + return MarketplaceAvailability{}, err + } + if result.Selection == nil || result.Selection.Status != "available" { + return MarketplaceAvailability{}, newParseError(command, "marketplace returned no remote archive", "") + } + return *result.Selection, nil +} + +// MarketplaceVariantReview carries the extracted manifest and the installed approval. +type MarketplaceVariantReview struct { + InstalledManifest json.RawMessage `json:"installedManifest"` + VariantManifest json.RawMessage `json:"variantManifest"` + PluginID string `json:"pluginID"` + Version string `json:"version"` + ApprovedPrograms []json.RawMessage `json:"approvedPrograms"` + HostCapabilities map[string][]int `json:"hostCapabilities"` +} + +// VerifyMarketplaceRemoteVariant validates declaration equality and program approval in Core. +func (c *Client) VerifyMarketplaceRemoteVariant(ctx context.Context, request MarketplaceVariantReview) (json.RawMessage, error) { + const command = "plugins.marketplace.verifyRemoteVariant" + if request.ApprovedPrograms == nil { + request.ApprovedPrograms = []json.RawMessage{} + } + var result marketplaceOutcome + if err := c.Execute(WithoutRemoteWorkspace(ctx), command, request, &result); err != nil { + return nil, err + } + if err := result.failure(command); err != nil { + return nil, err + } + if len(result.Manifest) == 0 { + return nil, newParseError(command, "marketplace returned no verified manifest", "") + } + return result.Manifest, nil +} + +// MarketplaceDeployment identifies a verified package and its process inputs. +type MarketplaceDeployment struct { + SHA256 string `json:"sha256"` + Paths []string `json:"paths"` +} + +// MarketplaceDeploymentRequest first plans a key and, after review and +// extraction, selects files from the verified archive inventory. +type MarketplaceDeploymentRequest struct { + ArchiveSHA256 string `json:"archiveSha256,omitempty"` + InstalledTreeSHA256 string `json:"installedTreeSha256,omitempty"` + Manifest json.RawMessage `json:"manifest"` + Target RemotePlatform `json:"target"` + RequiredPaths []string `json:"requiredPaths"` + ArchiveFiles []string `json:"archiveFiles"` +} + +// PlanMarketplaceRemoteDeployment validates the package paths and derives the lease key. +func (c *Client) PlanMarketplaceRemoteDeployment(ctx context.Context, request MarketplaceDeploymentRequest) (MarketplaceDeployment, error) { + const command = "plugins.marketplace.planRemoteDeployment" + var result struct { + marketplaceOutcome + Deployment *MarketplaceDeployment `json:"deployment"` + } + if err := c.Execute(WithoutRemoteWorkspace(ctx), command, request, &result); err != nil { + return MarketplaceDeployment{}, err + } + if err := result.failure(command); err != nil { + return MarketplaceDeployment{}, err + } + if result.Deployment == nil { + return MarketplaceDeployment{}, newParseError(command, "marketplace returned no deployment", "") + } + return *result.Deployment, nil +} + // MarketplaceRecommendationCatalog pairs one marketplace index with its companion recommendations catalog. type MarketplaceRecommendationCatalog struct { Index json.RawMessage `json:"index"` diff --git a/desktop/internal/core/plugin_files.go b/desktop/internal/core/plugin_files.go new file mode 100644 index 0000000000..e3709efbcf --- /dev/null +++ b/desktop/internal/core/plugin_files.go @@ -0,0 +1,106 @@ +package core + +import ( + "context" + "encoding/json" +) + +// PluginFileRequest reads a resource through the remote workspace binding on +// the request context. Only openDocument accepts absolute host paths. +type PluginFileRequest struct { + RootID string `json:"rootID"` + Generation uint64 `json:"generation"` + Attachment uint64 `json:"attachment"` + Path string `json:"path"` + Operation PluginFileOperation `json:"operation"` +} + +// PluginFileOperation selects a directory page, metadata, a bounded file read, or disk search. +type PluginFileOperation struct { + Kind string `json:"kind"` + Cursor *string `json:"cursor,omitempty"` + Limit *int64 `json:"limit,omitempty"` + MaximumBytes *int64 `json:"maximumBytes,omitempty"` + Query *string `json:"query,omitempty"` + Pattern *string `json:"pattern,omitempty"` + FileMask *string `json:"fileMask,omitempty"` + CaseSensitive *bool `json:"caseSensitive,omitempty"` + WholeWords *bool `json:"wholeWords,omitempty"` + RegularExpression *bool `json:"regularExpression,omitempty"` +} + +// ReadPluginFile returns a result already shaped for the plugin protocol. +func (c *Client) ReadPluginFile(ctx context.Context, request PluginFileRequest) (json.RawMessage, error) { + var result json.RawMessage + err := c.Execute(ctx, "workspace.pluginFile", request, &result) + return result, err +} + +// ReadWorkspaceConfiguration reads the settings source Core selected, over the +// request's remote connection. A nil text means the source does not exist. +func (c *Client) ReadWorkspaceConfiguration(ctx context.Context, path string, maximumBytes int64) (*string, error) { + var result struct { + Text *string `json:"text"` + } + err := c.Execute(ctx, "workspace.readConfiguration", struct { + Path string `json:"path"` + MaximumBytes int64 `json:"maximumBytes"` + }{path, maximumBytes}, &result) + return result.Text, err +} + +// ProjectPluginSettingsBaseline identifies the opened host directory and the +// exact source bytes. Neither the path nor the revision is editable UI state. +type ProjectPluginSettingsBaseline struct { + WorkspaceIdentity string `json:"workspaceIdentity"` + BaseSHA256 *string `json:"baseSha256"` +} + +// ProjectPluginSettings contains the private source and baseline for an editor. +type ProjectPluginSettings struct { + Path string `json:"path"` + Text *string `json:"text"` + Baseline ProjectPluginSettingsBaseline `json:"baseline"` +} + +// ReadProjectPluginSettings captures the preferences file on the bound host. +func (c *Client) ReadProjectPluginSettings(ctx context.Context) (ProjectPluginSettings, error) { + var source ProjectPluginSettings + err := c.Execute(ctx, "workspace.readPluginSettings", nil, &source) + return source, err +} + +// PublishProjectPluginSettings returns a committed write and distinguishes a +// stale remote source from transport or I/O failures. +func (c *Client) PublishProjectPluginSettings(ctx context.Context, baseline ProjectPluginSettingsBaseline, content *string) (committed, conflict bool, err error) { + var result struct { + Committed bool `json:"committed"` + } + err = c.Execute(ctx, "workspace.publishPluginSettings", struct { + Baseline ProjectPluginSettingsBaseline `json:"baseline"` + Content *string `json:"content"` + }{baseline, content}, &result) + return result.Committed, remoteHostCode(err) == "CONFLICT", err +} + +// PluginWatchChangesRequest describes one subscription and one batch of paths +// from its workspace's host watch. +type PluginWatchChangesRequest struct { + RootID string `json:"rootID"` + HostRoot string `json:"hostRoot"` + Path string `json:"path"` + Directory bool `json:"directory"` + Recursive bool `json:"recursive"` + HostPaths []string `json:"hostPaths"` + RequiresRescan bool `json:"requiresRescan"` +} + +// PluginWatchChanges projects scoped paths into a plugin event without disk I/O. +func (c *Client) PluginWatchChanges(ctx context.Context, request PluginWatchChangesRequest) (json.RawMessage, error) { + var result json.RawMessage + if request.HostPaths == nil { + request.HostPaths = []string{} + } + err := c.Execute(WithoutRemoteWorkspace(ctx), "workspace.pluginWatchChanges", request, &result) + return result, err +} diff --git a/desktop/internal/core/plugin_session.go b/desktop/internal/core/plugin_session.go index 03810b8b7c..0be6f80abb 100644 --- a/desktop/internal/core/plugin_session.go +++ b/desktop/internal/core/plugin_session.go @@ -10,16 +10,20 @@ import ( // PluginBackendStart is the host-resolved process and workspace. The host must // only supply programs and grants from an approved, verified plugin package. type PluginBackendStart struct { - ProviderID string `json:"providerId"` - PluginID string `json:"pluginId"` - Role string `json:"role,omitempty"` - ExecutablePath string `json:"executablePath"` - Arguments []string `json:"arguments,omitempty"` - Environment map[string]string `json:"environment,omitempty"` - RootURI any `json:"rootUri"` - WorkingDirectory string `json:"workingDirectory"` - HostServices []string `json:"hostServices,omitempty"` - ToolchainProviders []string `json:"toolchainProviders,omitempty"` + ProviderID string `json:"providerId"` + PluginID string `json:"pluginId"` + Role string `json:"role,omitempty"` + ExecutablePath string `json:"executablePath"` + UIProcess bool `json:"uiProcess,omitempty"` + RemoteCommands []string `json:"remoteCommands,omitempty"` + RemoteExecutablePath string `json:"remoteExecutablePath,omitempty"` + RemotePathPrepend []string `json:"remotePathPrepend,omitempty"` + Arguments []string `json:"arguments,omitempty"` + Environment map[string]string `json:"environment,omitempty"` + RootURI any `json:"rootUri"` + WorkingDirectory string `json:"workingDirectory"` + HostServices []string `json:"hostServices,omitempty"` + ToolchainProviders []string `json:"toolchainProviders,omitempty"` // FunctionRelayEnabled isolates preparation sessions from both incoming and // outgoing cross-plugin calls. Omitted preserves ordinary backend behavior. FunctionRelayEnabled *bool `json:"functionRelayEnabled,omitempty"` @@ -41,9 +45,19 @@ type PluginBackendStart struct { // PluginHostOptions are what the host declares about the services it grants one session. type PluginHostOptions struct { - Editor *EditorHostOptions `json:"editor,omitempty"` + Editor *EditorHostOptions `json:"editor,omitempty"` + MethodAuthorities map[string]PluginAuthoritySupport `json:"methodAuthorities,omitempty"` } +// PluginAuthoritySupport names the workspace authorities a host method accepts. +type PluginAuthoritySupport string + +const ( + PluginAuthorityLocal PluginAuthoritySupport = "local" + PluginAuthorityRemote PluginAuthoritySupport = "remote" + PluginAuthorityBoth PluginAuthoritySupport = "both" +) + // EditorHostOptions are the editor service's options: the icons the host draws for an // action, the largest document it collects actions for, and the provider types // editor/registerProviders accepts because the host routes them. @@ -87,10 +101,12 @@ type PluginBackendStarted struct { // host must verify package paths and trust, resolve tools, and create the // requested writable directories before starting a process. type PluginBackendPlan struct { + Placement string `json:"placement,omitempty"` // Owner identifies the validated package that produced this launch plan. Owner *PluginSettingsOwner `json:"owner,omitempty"` Launch struct { Kind string `json:"kind"` + RemoteExecutable string `json:"remoteExecutable"` Path string `json:"path"` Commands []string `json:"commands"` Tool string `json:"tool"` @@ -144,11 +160,14 @@ type PluginBuildProviderPlan struct { type PluginBackendDirectories struct { PluginDirectory string `json:"pluginDirectory"` + RemotePluginDirectory string `json:"remotePluginDirectory,omitempty"` StateDirectory string `json:"stateDirectory"` WorkspaceStateDirectory string `json:"workspaceStateDirectory,omitempty"` LogDirectory string `json:"logDirectory,omitempty"` TemporaryDirectory string `json:"temporaryDirectory,omitempty"` Architecture string `json:"architecture"` + RemoteWorkspace bool `json:"remoteWorkspace,omitempty"` + ProbeLocalPlacement bool `json:"probeLocalPlacement,omitempty"` Settings map[string]json.RawMessage `json:"settings,omitempty"` ProjectSettings map[string]json.RawMessage `json:"projectSettings,omitempty"` // ProjectCodeAllowed is whether the user trusts the workspace. Core plans no language @@ -164,6 +183,12 @@ type PluginBackendDirectories struct { // stopped and starts it once the user trusts the workspace. const LaunchUntrustedWorkspace = "plugin.launch.untrustedWorkspace" +// IsLaunchRemoteUnsupported reports an explicit local-only declaration. +func IsLaunchRemoteUnsupported(err error) bool { + var rejection *MarketplaceRejection + return errors.As(err, &rejection) && rejection.Code == "plugin.launch.remoteUnsupported" +} + // IsLaunchUntrustedWorkspace reports whether err is Core's refusal of a launch for want of // workspace trust. func IsLaunchUntrustedWorkspace(err error) bool { diff --git a/desktop/internal/core/plugin_setting_actions.go b/desktop/internal/core/plugin_setting_actions.go index 6b8f36d190..6f286cef24 100644 --- a/desktop/internal/core/plugin_setting_actions.go +++ b/desktop/internal/core/plugin_setting_actions.go @@ -25,18 +25,26 @@ type PluginSettingsActionRequest struct { // Only an invoke plan contains Function and Params; runtime ownership is checked // again when the existing provider session receives that invocation. type PluginSettingsActionPlan struct { - Version string `json:"version"` - Kind string `json:"kind"` - PluginID string `json:"pluginID"` - ActionID string `json:"actionID"` - Title string `json:"title"` - Reason string `json:"reason,omitempty"` - Function string `json:"function,omitempty"` - Params json.RawMessage `json:"params,omitempty"` - SourceEditor bool `json:"sourceEditor,omitempty"` - BuildSystemID string `json:"buildSystemID,omitempty"` - LanguageID string `json:"languageID,omitempty"` - EditFunction string `json:"editFunction,omitempty"` + Version string `json:"version"` + Kind string `json:"kind"` + PluginID string `json:"pluginID"` + ActionID string `json:"actionID"` + Title string `json:"title"` + Reason string `json:"reason,omitempty"` + Function string `json:"function,omitempty"` + Params json.RawMessage `json:"params,omitempty"` + SourceEditor bool `json:"sourceEditor,omitempty"` + BuildSystemID string `json:"buildSystemID,omitempty"` + LanguageID string `json:"languageID,omitempty"` + EditFunction string `json:"editFunction,omitempty"` + RemoteHelper *RemoteSettingsHelper `json:"remoteHelper,omitempty"` +} + +// RemoteSettingsHelper contains the launch inputs approved with the plugin package. +type RemoteSettingsHelper struct { + Executable string `json:"executable"` + Arguments []string `json:"arguments,omitempty"` + Resources []string `json:"resources,omitempty"` } // PlanPluginSettingsAction resolves a manifest action without opening a backend diff --git a/desktop/internal/core/remote.go b/desktop/internal/core/remote.go index a9eda7f8fa..8ae628cbe5 100644 --- a/desktop/internal/core/remote.go +++ b/desktop/internal/core/remote.go @@ -265,6 +265,27 @@ type RemoteProbedHost struct { Details RemoteHostDetails `json:"details"` } +// RemotePlatform is the platform vocabulary shared by remote plugin contexts and runtimes. +type RemotePlatform struct { + OS string `json:"os"` + Arch string `json:"arch"` +} + +// PluginPlatform translates the server target Core selected into the plugin contract's vocabulary. +func (h *RemoteProbedHost) PluginPlatform() *RemotePlatform { + if h == nil { + return nil + } + switch h.ServerTarget { + case "aarch64-unknown-linux-musl": + return &RemotePlatform{OS: "linux", Arch: "arm64"} + case "x86_64-unknown-linux-musl": + return &RemotePlatform{OS: "linux", Arch: "x86_64"} + default: + return nil + } +} + // RemoteProbeResult is the outcome of a probe, and the host when its shell ran. type RemoteProbeResult struct { Status RemoteProbeStatus `json:"status"` diff --git a/desktop/internal/core/remote_native_settings.go b/desktop/internal/core/remote_native_settings.go new file mode 100644 index 0000000000..a19597546a --- /dev/null +++ b/desktop/internal/core/remote_native_settings.go @@ -0,0 +1,75 @@ +package core + +import ( + "context" + "encoding/json" + "errors" +) + +// RemoteNativeSettingsTarget names a source in an authorized host directory. +type RemoteNativeSettingsTarget struct { + Scope string `json:"scope"` + Path string `json:"path"` +} + +// RemoteNativeSettingsBaseline is a host-issued identity for conditional publication. +type RemoteNativeSettingsBaseline struct { + Target RemoteNativeSettingsTarget `json:"target"` + Identity string `json:"identity"` + Revision string `json:"revision"` + HostPath string `json:"hostPath"` + Writable bool `json:"writable"` +} + +// RemoteNativeSettingsReplacement identifies a staged output without returning source bytes. +type RemoteNativeSettingsReplacement struct { + Slot uint16 `json:"slot"` + Baseline RemoteNativeSettingsBaseline `json:"baseline"` + Revision string `json:"revision"` +} + +// InspectRemoteNativeSettings verifies source identities on the captured workspace host. +func (c *Client) InspectRemoteNativeSettings(ctx context.Context, targets []RemoteNativeSettingsTarget) ([]RemoteNativeSettingsBaseline, error) { + var sources []RemoteNativeSettingsBaseline + err := c.Execute(ctx, "workspace.nativeSettings", struct { + Kind string `json:"kind"` + Targets []RemoteNativeSettingsTarget `json:"targets"` + }{"inspect", targets}, &sources) + return sources, err +} + +// StageRemoteNativeSettings allocates existing empty output files within private host staging. +func (c *Client) StageRemoteNativeSettings(ctx context.Context, id string, baselines []RemoteNativeSettingsBaseline) ([]string, error) { + var files []string + err := c.Execute(ctx, "workspace.nativeSettings", struct { + Kind string `json:"kind"` + DirectoryID string `json:"directoryId"` + Baselines []RemoteNativeSettingsBaseline `json:"baselines"` + }{"stage", id, baselines}, &files) + return files, err +} + +// PublishRemoteNativeSettings consumes staging and preserves partial and uncertain outcomes. +func (c *Client) PublishRemoteNativeSettings(ctx context.Context, id string, replacements []RemoteNativeSettingsReplacement) (slots []uint16, uncertain bool, err error) { + var result struct { + Slots []uint16 `json:"committedSlots"` + Uncertain bool `json:"publicationUncertain"` + } + err = c.Execute(ctx, "workspace.nativeSettings", struct { + Kind string `json:"kind"` + DirectoryID string `json:"directoryId"` + Replacements []RemoteNativeSettingsReplacement `json:"replacements"` + }{"publish", id, replacements}, &result) + var failure *Error + if errors.As(err, &failure) && failure.Details != "" { + if decodeErr := json.Unmarshal([]byte(failure.Details), &result); decodeErr != nil { + return nil, true, errors.Join(err, decodeErr) + } + } + return result.Slots, result.Uncertain, err +} + +// IsRemoteNativeSettingsConflict recognizes a host refusal of an outdated source. +func IsRemoteNativeSettingsConflict(err error) bool { + return remoteHostCode(err) == "CONFLICT" +} diff --git a/desktop/internal/core/remote_plugin.go b/desktop/internal/core/remote_plugin.go new file mode 100644 index 0000000000..5b40ceb482 --- /dev/null +++ b/desktop/internal/core/remote_plugin.go @@ -0,0 +1,89 @@ +package core + +import ( + "context" + "errors" + "path" +) + +// RemotePluginDeployment identifies a content-addressed tree on the host. +type RemotePluginDeployment struct { + PluginID string `json:"pluginId"` + Version string `json:"version"` + SHA256 string `json:"sha256"` +} + +// RemoteInstalledPluginVersion identifies a release retained by the desktop. +type RemoteInstalledPluginVersion struct { + PluginID string `json:"pluginId"` + Version string `json:"version"` +} + +// SweepRemotePluginDeployments removes unused versions absent from the complete inventory. +func (c *Client) SweepRemotePluginDeployments(ctx context.Context, installed []RemoteInstalledPluginVersion) error { + return c.remoteWorkspaceHostRequest(ctx, "fs.pluginDeploymentSweep", struct { + Installed []RemoteInstalledPluginVersion `json:"installed"` + }{installed}, nil) +} + +// LookupRemotePluginDeployment acquires a session lease if the deployment exists. +func (c *Client) LookupRemotePluginDeployment(ctx context.Context, key RemotePluginDeployment) (string, error) { + return c.remotePluginPath(ctx, "fs.pluginDeploymentLookup", key) +} + +// CommitRemotePluginDeployment publishes a complete package from private scratch. +func (c *Client) CommitRemotePluginDeployment(ctx context.Context, key RemotePluginDeployment, directoryID string) (string, error) { + return c.remotePluginPath(ctx, "fs.pluginDeploymentCommit", struct { + Key RemotePluginDeployment `json:"key"` + DirectoryID string `json:"directoryId"` + }{key, directoryID}) +} + +func (c *Client) remotePluginPath(ctx context.Context, method string, params any) (string, error) { + var result struct { + Path string `json:"path"` + } + if err := c.remoteWorkspaceHostRequest(ctx, method, params, &result); err != nil { + return "", err + } + if result.Path == "" && method == "fs.pluginDeploymentLookup" { + return "", nil + } + if !path.IsAbs(result.Path) { + return "", errors.New("core: invalid remote plugin deployment directory") + } + return result.Path, nil +} + +// CreateRemotePluginDirectory prepares private staging on the captured host. +func (c *Client) CreateRemotePluginDirectory(ctx context.Context, directory string) error { + return c.remoteWorkspaceHostRequest(ctx, "fs.createDir", struct { + Path string `json:"path"` + Recursive bool `json:"recursive"` + Mode uint32 `json:"mode"` + }{directory, true, 0o700}, nil) +} + +// UploadRemotePluginFile streams a verified file to the captured workspace. +func (c *Client) UploadRemotePluginFile(ctx context.Context, source, target, sha256 string, mode uint32) error { + const command = "remote.uploadFile" + // Session commands carry their session ID in the payload. Capture the + // attachment from the operation so staging cannot follow a reconnection. + binding := RemoteWorkspaceOf(ctx) + connection := binding.CapturedConnection(ctx) + sessionID := connection.SessionID() + if sessionID == "" { + return &Error{Command: command, Code: CodeConnectionClosed, Message: "the remote workspace is not connected"} + } + observer := remoteStageObserver(ctx) + observationErr, err := c.ExecuteWithEvents(ctx, command, struct { + SessionID string `json:"sessionId"` + SourcePath string `json:"sourcePath"` + Path string `json:"path"` + SHA256 string `json:"sha256"` + Mode uint32 `json:"mode"` + ReportProgress bool `json:"reportProgress,omitempty"` + }{sessionID, source, target, sha256, mode, observer != nil}, nil, observer) + remoteWorkspaceAnswered(binding, connection.session, err) + return errors.Join(observationErr, err) +} diff --git a/desktop/internal/core/remote_plugin_test.go b/desktop/internal/core/remote_plugin_test.go new file mode 100644 index 0000000000..15527d3768 --- /dev/null +++ b/desktop/internal/core/remote_plugin_test.go @@ -0,0 +1,51 @@ +package core + +import ( + "context" + "path/filepath" + "strings" + "testing" +) + +func TestRemotePluginUploadRequiresAndDispatchesToCapturedAttachment(t *testing.T) { + ctx := testContext(t) + client := NewClient() + var lost []string + workspace := NewRemoteWorkspace(t.TempDir(), "/srv/repo", func(id string) { lost = append(lost, id) }) + t.Cleanup(func() { workspace.Detach() }) + workspace.Attach("missing-plugin-upload-session") + previous := workspace.CaptureConnection() + workspace.Attach("missing-plugin-upload-session") + current := workspace.CaptureConnection() + source := filepath.Join(t.TempDir(), "server") + writeFile(t, source, "fixture") + target := "/private/staging/server" + digest := strings.Repeat("a", 64) + + for _, rejected := range []struct { + name string + ctx context.Context + }{ + {"local", ctx}, + {"following reconnections", WithRemoteWorkspace(ctx, workspace)}, + {"replaced attachment with the same session ID", previous.Context(ctx)}, + } { + t.Run(rejected.name, func(t *testing.T) { + requireCode(t, client.UploadRemotePluginFile(rejected.ctx, "relative", target, digest, 0o500), CodeConnectionClosed) + if !current.IsCurrent() || len(lost) != 0 { + t.Fatalf("refused upload affected the current attachment, reported loss %v", lost) + } + }) + } + + // Core validates the source path before it looks up the session. Its + // validation error proves an upload on the captured attachment was sent. + requireCode(t, client.UploadRemotePluginFile(current.Context(ctx), "relative", target, digest, 0o500), CodeInvalidRequest) + if !current.IsCurrent() || len(lost) != 0 { + t.Fatalf("invalid source affected the current attachment, reported loss %v", lost) + } + requireCode(t, client.UploadRemotePluginFile(current.Context(ctx), source, target, digest, 0o500), CodeConnectionClosed) + if current.IsCurrent() || len(lost) != 1 || lost[0] != "missing-plugin-upload-session" { + t.Fatalf("missing Core session: attachment current = %v, reported loss %v", current.IsCurrent(), lost) + } +} diff --git a/desktop/internal/core/remote_process.go b/desktop/internal/core/remote_process.go index e65fbf4904..a0c09cf058 100644 --- a/desktop/internal/core/remote_process.go +++ b/desktop/internal/core/remote_process.go @@ -6,8 +6,80 @@ import ( "encoding/base64" "encoding/json" "errors" + "path" ) +// RemoteExecutableRequest describes a candidate Core already planned. The host +// checks its files or login environment without launching the program. +type RemoteExecutableRequest struct { + Kind string `json:"kind"` + Value string `json:"value,omitempty"` + Root string `json:"root,omitempty"` + Path string `json:"path,omitempty"` + Variable string `json:"variable,omitempty"` + Requires []string `json:"requires,omitempty"` + SearchPath *string `json:"searchPath,omitempty"` +} + +// ResolveRemoteExecutable locates a candidate in the bound workspace's host. +func (c *Client) ResolveRemoteExecutable(ctx context.Context, request RemoteExecutableRequest) (string, error) { + var executable *string + err := c.remoteWorkspaceHostRequest(ctx, "process.resolveExecutable", request, &executable) + if executable == nil || err != nil { + return "", err + } + return *executable, nil +} + +// PickRemoteLoopbackPort asks the workspace host for a port the debuggee can bind. +func (c *Client) PickRemoteLoopbackPort(ctx context.Context) (int, error) { + var port int + err := c.remoteWorkspaceHostRequest(ctx, "ports.pickLoopback", nil, &port) + return port, err +} + +// RemoteProcessDebugPortReady observes whether the owned process session listens on port. +func (c *Client) RemoteProcessDebugPortReady(ctx context.Context, processID uint64, port int) (bool, error) { + var ready bool + err := c.remoteWorkspaceHostRequest(ctx, "process.debugPortReady", struct { + ProcessID uint64 `json:"processId"` + Port int `json:"port"` + }{processID, port}, &ready) + return ready, err +} + +// RemoteDebugLaunch describes the scoped directory and environment for a debuggee. +type RemoteDebugLaunch struct { + Cwd string `json:"cwd"` + Path *string `json:"path"` +} + +// ResolveRemoteDebugLaunch checks the working directory and plans PATH on the captured host. +func (c *Client) ResolveRemoteDebugLaunch(ctx context.Context, cwd RemoteScopedDirectory, path *string, pathPrepend []string) (RemoteDebugLaunch, error) { + var launch RemoteDebugLaunch + err := c.remoteWorkspaceHostRequest(ctx, "process.resolveDebugLaunch", struct { + Cwd RemoteScopedDirectory `json:"scopedCwd"` + Path *string `json:"path,omitempty"` + PathPrepend []string `json:"pathPrepend,omitempty"` + }{cwd, path, pathPrepend}, &launch) + return launch, err +} + +// remoteWorkspaceHostRequest derives the session from the operation's +// attachment and reports loss only to that attachment. +func (c *Client) remoteWorkspaceHostRequest(ctx context.Context, method string, params, result any) error { + wire, binding, session, err := remoteWorkspaceRequest(ctx, method) + if err != nil { + return err + } + if wire == nil { + return &Error{Code: CodeConnectionClosed, Message: "the remote workspace is not connected"} + } + err = c.RemoteHostRequest(ctx, wire.SessionID, method, params, result) + remoteWorkspaceAnswered(binding, session, err) + return err +} + // RemoteProcessOpen is how a host process starts. type RemoteProcessOpen struct { // Argv is the program and its arguments; a program without "/" is looked up on the PATH of @@ -15,11 +87,15 @@ type RemoteProcessOpen struct { Argv []string `json:"argv"` // Cwd is the absolute host working directory; empty starts in the user's home. Cwd string `json:"cwd,omitempty"` + // ScopedCwd asks the host to resolve the working directory within the workspace. + ScopedCwd *RemoteScopedDirectory `json:"scopedCwd,omitempty"` // Environment is the base environment: "login" asks the user's login shell for it, as an SSH // login sees it, and "server" (the default when empty) is the remote server's own. Environment string `json:"environment,omitempty"` // Env adds variables to the base environment. Env map[string]string `json:"env,omitempty"` + // PathPrepend adds toolchain directories ahead of the host's effective PATH. + PathPrepend []string `json:"pathPrepend,omitempty"` // PipeStdin keeps the program's standard input open; false gives it /dev/null. PipeStdin bool `json:"pipeStdin,omitempty"` // Label is what server.state reports for the process, so the window that closes the session @@ -73,6 +149,22 @@ var errRemoteProcessEvent = errors.New("core: unreadable remote process event") // the client cannot read ends the process too and is returned as the error, since its output // would be incomplete. func (c *Client) RemoteRunProcess(ctx context.Context, sessionID string, open RemoteProcessOpen, events RemoteProcessEvents) (RemoteProcessExit, error) { + return c.runRemoteProcess(ctx, sessionID, open, events, nil, nil) +} + +// RunRemoteProcess runs on the workspace attachment captured in ctx. +func (c *Client) RunRemoteProcess(ctx context.Context, open RemoteProcessOpen, events RemoteProcessEvents) (RemoteProcessExit, error) { + wire, binding, session, err := remoteWorkspaceRequest(ctx, "workspace.process") + if err != nil { + return RemoteProcessExit{}, err + } + if wire == nil { + return RemoteProcessExit{}, &Error{Code: CodeConnectionClosed, Message: "the remote workspace is not connected"} + } + return c.runRemoteProcess(ctx, wire.SessionID, open, events, binding, session) +} + +func (c *Client) runRemoteProcess(ctx context.Context, sessionID string, open RemoteProcessOpen, events RemoteProcessEvents, binding *RemoteWorkspace, session *remoteAttachment) (RemoteProcessExit, error) { ctx, cancel := context.WithCancel(ctx) defer cancel() var unreadable error @@ -91,6 +183,7 @@ func (c *Client) RemoteRunProcess(ctx context.Context, sessionID string, open Re SessionID string `json:"sessionId"` Params RemoteProcessOpen `json:"params"` }{sessionID, open}, &exit, observer) + remoteWorkspaceAnswered(binding, session, err) switch { case unreadable != nil: return RemoteProcessExit{}, unreadable @@ -114,6 +207,9 @@ func deliverRemoteProcessEvent(raw json.RawMessage, events RemoteProcessEvents) } switch event.Event { case "process.started": + if event.Params.ProcessID == 0 { + return errRemoteProcessEvent + } if events.Started != nil { pid := 0 if event.Params.PID != nil { @@ -172,3 +268,62 @@ func (c *Client) RemoteRemove(ctx context.Context, sessionID, path string, recur Recursive bool `json:"recursive"` }{path, recursive}, nil) } + +// WriteRemoteProcessInput sends a bounded chunk of bytes to a process owned +// by the caller's captured connection. +func (c *Client) WriteRemoteProcessInput(ctx context.Context, processID uint64, data []byte) error { + if workspace := RemoteWorkspaceOf(ctx); workspace == nil || workspace.CapturedConnection(ctx) == nil { + return &Error{Code: CodeConnectionClosed, Message: "remote process input has no captured connection"} + } + return c.remoteWorkspaceHostRequest(ctx, "process.writeStdin", struct { + ProcessID uint64 `json:"processId"` + Data []byte `json:"data"` + }{processID, data}, nil) +} + +// CreateRemoteRunDirectory allocates private scratch on the captured session. +func (c *Client) CreateRemoteRunDirectory(ctx context.Context, id string) (string, error) { + return c.createRemoteRunDirectory(ctx, "fs.createRunDirectory", id) +} + +func (c *Client) createRemoteRunDirectory(ctx context.Context, method, id string) (string, error) { + var result struct { + Path string `json:"path"` + } + err := c.remoteWorkspaceHostRequest(ctx, method, map[string]string{"directoryId": id}, &result) + if err == nil && !path.IsAbs(result.Path) { + err = errors.New("core: invalid remote run directory") + } + return result.Path, err +} + +// WriteRemoteRunFile creates a file supplied by Core's run decoder in private session scratch. +func (c *Client) WriteRemoteRunFile(ctx context.Context, file string, data []byte) error { + wire, binding, session, err := remoteWorkspaceRequest(ctx, "workspace.runFile") + if err != nil { + return err + } + if wire == nil { + return &Error{Code: CodeConnectionClosed, Message: "the remote workspace is not connected"} + } + _, saved, err := c.RemoteWriteFile(ctx, wire.SessionID, file, data, nil) + remoteWorkspaceAnswered(binding, session, err) + if err == nil && !saved { + err = errors.New("core: the remote run file already exists") + } + return err +} + +// ReleaseRemoteRunDirectory frees the scratch owned by the captured session. +func (c *Client) ReleaseRemoteRunDirectory(ctx context.Context, id string) error { + params := map[string]string{"directoryId": id} + // A replacement attachment must never receive cleanup for this random + // resource. The original session can still own it until close completes. + connection, _ := ctx.Value(remoteWorkspaceKey{}).(RemoteWorkspaceConnection) + if connection.session != nil { + err := c.RemoteHostRequest(ctx, connection.session.id, "fs.releaseRunDirectory", params, nil) + remoteWorkspaceAnswered(connection.workspace, connection.session, err) + return err + } + return c.remoteWorkspaceHostRequest(ctx, "fs.releaseRunDirectory", params, nil) +} diff --git a/desktop/internal/core/remote_runtime.go b/desktop/internal/core/remote_runtime.go new file mode 100644 index 0000000000..4a2f978a00 --- /dev/null +++ b/desktop/internal/core/remote_runtime.go @@ -0,0 +1,57 @@ +package core + +import ( + "context" + "errors" + "path" +) + +// RemoteManagedRuntimeLayout binds a cache entry to the approved archive and its native layout. +type RemoteManagedRuntimeLayout struct { + Key RemotePluginDeployment `json:"key"` + ArchiveSHA256 string `json:"archiveSha256"` + Archive string `json:"archive"` + StripPrefix string `json:"stripPrefix"` + Home string `json:"home"` + Executable string `json:"executable"` +} + +// RemoteManagedRuntimePaths are verified by the workspace host and live for the session. +type RemoteManagedRuntimePaths struct { + Home string `json:"home"` + Executable string `json:"executable"` +} + +// LookupRemoteManagedRuntime returns nil on a cache miss and otherwise leases the runtime. +func (c *Client) LookupRemoteManagedRuntime(ctx context.Context, layout RemoteManagedRuntimeLayout) (*RemoteManagedRuntimePaths, error) { + return c.remoteManagedRuntime(ctx, "fs.managedRuntimeLookup", layout, layout.Executable != "") +} + +// CreateRemoteRuntimeStaging allocates connection-owned scratch for a plugin or runtime deployment. +func (c *Client) CreateRemoteRuntimeStaging(ctx context.Context, id string) (string, error) { + return c.createRemoteRunDirectory(ctx, "fs.createRuntimeStaging", id) +} + +// CommitRemoteManagedRuntime verifies and unpacks the upload before leasing the published runtime. +func (c *Client) CommitRemoteManagedRuntime(ctx context.Context, layout RemoteManagedRuntimeLayout, id string) (*RemoteManagedRuntimePaths, error) { + const method = "fs.managedRuntimeCommit" + result, err := c.remoteManagedRuntime(ctx, method, struct { + Layout RemoteManagedRuntimeLayout `json:"layout"` + DirectoryID string `json:"directoryId"` + }{layout, id}, layout.Executable != "") + if result == nil && err == nil { + return nil, errors.New("core: remote runtime commit returned no installation") + } + return result, err +} + +func (c *Client) remoteManagedRuntime(ctx context.Context, method string, payload any, executable bool) (*RemoteManagedRuntimePaths, error) { + var result *RemoteManagedRuntimePaths + if err := c.remoteWorkspaceHostRequest(ctx, method, payload, &result); err != nil || result == nil { + return nil, err + } + if !path.IsAbs(result.Home) || (executable && !path.IsAbs(result.Executable)) || (!executable && result.Executable != "") { + return nil, errors.New("core: invalid remote runtime installation paths") + } + return result, nil +} diff --git a/desktop/internal/core/remote_session.go b/desktop/internal/core/remote_session.go index f417ebaaff..1dca1b9e02 100644 --- a/desktop/internal/core/remote_session.go +++ b/desktop/internal/core/remote_session.go @@ -596,10 +596,18 @@ func (c *Client) RemoteServerState(ctx context.Context, sessionID string) error // them and never reads or writes the placeholder. The session is swapped as the connection is // lost and opened again, and is safe to change from any goroutine. type RemoteWorkspace struct { - localRoot string - remoteRoot string - session atomic.Pointer[string] - lost func(sessionID string) + localRoot string + remoteRoot string + session atomic.Pointer[remoteAttachment] + nextAttachment atomic.Uint64 + lost func(sessionID string) +} + +type remoteAttachment struct { + revision uint64 + id string + lifetime context.Context + cancel context.CancelFunc } // NewRemoteWorkspace returns a binding of localRoot to the host folder remoteRoot with no @@ -616,12 +624,18 @@ func (w *RemoteWorkspace) LocalRoot() string { return w.localRoot } func (w *RemoteWorkspace) RemoteRoot() string { return w.remoteRoot } // Attach makes sessionID the session the binding's requests go over. -func (w *RemoteWorkspace) Attach(sessionID string) { w.session.Store(&sessionID) } +func (w *RemoteWorkspace) Attach(sessionID string) { + lifetime, cancel := context.WithCancel(context.Background()) + if previous := w.session.Swap(&remoteAttachment{revision: w.nextAttachment.Add(1), id: sessionID, lifetime: lifetime, cancel: cancel}); previous != nil { + previous.cancel() + } +} // Detach leaves the binding without a session and returns the one it had, empty for none. func (w *RemoteWorkspace) Detach() string { if previous := w.session.Swap(nil); previous != nil { - return *previous + previous.cancel() + return previous.id } return "" } @@ -629,13 +643,70 @@ func (w *RemoteWorkspace) Detach() string { // SessionID is the session the binding's requests go over, empty while it has none. func (w *RemoteWorkspace) SessionID() string { if current := w.session.Load(); current != nil { - return *current + return current.id } return "" } type remoteWorkspaceKey struct{} +// RemoteWorkspaceConnection identifies one attachment of a workspace, even if +// the same session ID is attached again later. +type RemoteWorkspaceConnection struct { + workspace *RemoteWorkspace + session *remoteAttachment +} + +// CaptureConnection takes the current attachment, or returns nil while disconnected. +func (w *RemoteWorkspace) CaptureConnection() *RemoteWorkspaceConnection { + session := w.session.Load() + if session == nil { + return nil + } + return &RemoteWorkspaceConnection{workspace: w, session: session} +} + +// IsCurrent reports whether this attachment still serves its workspace. +func (c *RemoteWorkspaceConnection) IsCurrent() bool { + return c != nil && c.workspace.session.Load() == c.session +} + +// SessionID returns the captured session ID while the attachment is current. +func (c *RemoteWorkspaceConnection) SessionID() string { + if !c.IsCurrent() { + return "" + } + return c.session.id +} + +// Revision distinguishes attachments even when the server resumes the same session. +func (c *RemoteWorkspaceConnection) Revision() uint64 { return c.session.revision } + +// SameAttachment compares the captured attachments rather than the session IDs. +func (c *RemoteWorkspaceConnection) SameAttachment(other *RemoteWorkspaceConnection) bool { + return c != nil && other != nil && c.workspace == other.workspace && c.session == other.session +} + +// SameWorkspace compares the stable placeholder and canonical host root, so +// settings notifications can reach separate windows on the saved connection. +func (c *RemoteWorkspaceConnection) SameWorkspace(other *RemoteWorkspaceConnection) bool { + return c != nil && other != nil && + c.workspace.localRoot == other.workspace.localRoot && + c.workspace.remoteRoot == other.workspace.remoteRoot +} + +// AfterDetach runs f when this attachment disconnects or is replaced. +// It returns a function that unregisters f. +func (c *RemoteWorkspaceConnection) AfterDetach(f func()) func() bool { + return context.AfterFunc(c.session.lifetime, f) +} + +// Context binds workspace requests to this attachment. They fail if the +// attachment changes before dispatch, and a late loss cannot detach its successor. +func (c *RemoteWorkspaceConnection) Context(ctx context.Context) context.Context { + return context.WithValue(ctx, remoteWorkspaceKey{}, *c) +} + // WithRemoteWorkspace returns a context whose requests run on the host of binding. Every // request of the context carries the binding except the remote.* commands, which name their // session themselves, and the payload-only commands (payloadOnlyCommands); Core refuses a @@ -646,7 +717,13 @@ func WithRemoteWorkspace(ctx context.Context, binding *RemoteWorkspace) context. if binding == nil { return ctx } - return context.WithValue(ctx, remoteWorkspaceKey{}, binding) + return context.WithValue(ctx, remoteWorkspaceKey{}, RemoteWorkspaceConnection{workspace: binding}) +} + +// WithoutRemoteWorkspace keeps the context's cancellation for work explicitly owned +// by the client, such as starting a plugin's local backend. +func WithoutRemoteWorkspace(ctx context.Context) context.Context { + return context.WithValue(ctx, remoteWorkspaceKey{}, RemoteWorkspaceConnection{}) } // payloadOnlyCommands are the commands an open document, the Project tool window or the search @@ -674,7 +751,25 @@ var payloadOnlyCommands = map[string]bool{ "editor.recovery.decide": true, "github.parseRemote": true, "languages.matchFirstLine": true, + "plugins.launchPlan": true, + "lsp.applyTextEdits": true, + "lsp.classifyNavigationTarget": true, + "lsp.declarationOrUsages": true, + "lsp.documentIdentity": true, + "lsp.documentUri": true, + "lsp.mergeCompletions": true, + "lsp.plainSnippet": true, + "lsp.planWorkspaceEdit": true, + "lsp.problems.query": true, + "lsp.references.lines": true, + "lsp.references.query": true, "markdown.outline": true, + "plugins.installed.lifecycle": true, + "plugins.installed.select": true, + "plugins.settings.sourceState": true, + "plugins.settings.sourceEdit": true, + "plugins.settings.sourceReceipt": true, + "runConfig.decideTitleAction": true, "text.decode": true, "text.encode": true, "workspace.filterChanges": true, @@ -684,8 +779,18 @@ var payloadOnlyCommands = map[string]bool{ // RemoteWorkspaceOf is the binding WithRemoteWorkspace put in ctx, nil for a local context. func RemoteWorkspaceOf(ctx context.Context) *RemoteWorkspace { - binding, _ := ctx.Value(remoteWorkspaceKey{}).(*RemoteWorkspace) - return binding + scope, _ := ctx.Value(remoteWorkspaceKey{}).(RemoteWorkspaceConnection) + return scope.workspace +} + +// CapturedConnection returns the operation's attachment to this workspace. +// A context that follows reconnections cannot own a long-lived process. +func (w *RemoteWorkspace) CapturedConnection(ctx context.Context) *RemoteWorkspaceConnection { + scope, _ := ctx.Value(remoteWorkspaceKey{}).(RemoteWorkspaceConnection) + if scope.workspace != w || scope.session == nil { + return nil + } + return &scope } // remoteWorkspace is the request's remote workspace on the wire (Workspace in the Rust @@ -700,20 +805,32 @@ type remoteWorkspace struct { // local context, a remote.* command and a payload-only command, the binding's session and roots // otherwise. session is the pointer the request read, so a later loss detaches only that // session. -func remoteWorkspaceRequest(ctx context.Context, command string) (wire *remoteWorkspace, binding *RemoteWorkspace, session *string, err error) { - binding = RemoteWorkspaceOf(ctx) - if binding == nil || isRemoteSessionCommand(command) || payloadOnlyCommands[command] { +func remoteWorkspaceRequest(ctx context.Context, command string) (wire *remoteWorkspace, binding *RemoteWorkspace, session *remoteAttachment, err error) { + scope, _ := ctx.Value(remoteWorkspaceKey{}).(RemoteWorkspaceConnection) + binding = scope.workspace + if binding == nil || isRemoteSessionCommand(command) || payloadOnlyCommands[command] || isLanguageSessionCommand(command) || isDebugCommandWithoutWorkspace(command) { return nil, nil, nil, nil } session = binding.session.Load() - if session == nil { + if session == nil || (scope.session != nil && scope.session != session) { return nil, nil, nil, &Error{ Command: command, Code: CodeConnectionClosed, Message: "the remote workspace is not connected", } } - return &remoteWorkspace{SessionID: *session, LocalRoot: binding.localRoot, RemoteRoot: binding.remoteRoot}, binding, session, nil + return &remoteWorkspace{SessionID: session.id, LocalRoot: binding.localRoot, RemoteRoot: binding.remoteRoot}, binding, session, nil +} + +// Debug reducers address the debug session by ID or consume explicit facts. +// Creation binds the workspace. The launch planners use its path namespace. +func isDebugCommandWithoutWorkspace(command string) bool { + switch command { + case "debug.createSession", "debug.adapters.executablePlan", "debug.adapters.startArguments": + return false + default: + return strings.HasPrefix(command, "debug.") + } } // isRemoteSessionCommand reports whether command addresses a session by its id rather than @@ -722,9 +839,27 @@ func isRemoteSessionCommand(command string) bool { return strings.HasPrefix(command, "remote.") } +// The registry already owns the host and path mapping of each language +// session. Sending the window's current binding would reject these calls on +// disconnect and could redirect pending work to a replacement session. +func isLanguageSessionCommand(command string) bool { + switch command { + case "lsp.applyEditResponse", "lsp.buildRequest", "lsp.cancelOperation", + "lsp.closeDocument", "lsp.destroyServer", "lsp.functionRequest", + "lsp.hostNotify", "lsp.hostResponse", "lsp.pluginServerNotify", + "lsp.pluginServerRequest", "lsp.request", "lsp.saveDocument", + "lsp.setDetailedDiagnostics", "lsp.stopServer", "lsp.syncDocument", + "lsp.toolchainRequest", "lsp.updateWorkspaceConfiguration", + "lsp.vcsRequest", "lsp.waitEvents": + return true + default: + return false + } +} + // remoteWorkspaceAnswered detaches session from binding when the request failed because its // connection closed, and tells the binding's owner once. -func remoteWorkspaceAnswered(binding *RemoteWorkspace, session *string, err error) { +func remoteWorkspaceAnswered(binding *RemoteWorkspace, session *remoteAttachment, err error) { if binding == nil || session == nil { return } @@ -732,7 +867,10 @@ func remoteWorkspaceAnswered(binding *RemoteWorkspace, session *string, err erro if !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed { return } - if binding.session.CompareAndSwap(session, nil) && binding.lost != nil { - binding.lost(*session) + if binding.session.CompareAndSwap(session, nil) { + session.cancel() + if binding.lost != nil { + binding.lost(session.id) + } } } diff --git a/desktop/internal/core/remote_session_test.go b/desktop/internal/core/remote_session_test.go index a1409b8b71..23acfe2b7c 100644 --- a/desktop/internal/core/remote_session_test.go +++ b/desktop/internal/core/remote_session_test.go @@ -36,7 +36,7 @@ func TestRemoteWorkspaceRequestsCarryTheBindingExceptSessionCommands(t *testing. binding.Attach("session-7") wire, owner, session, err := remoteWorkspaceRequest(ctx, "file.read") - if err != nil || owner != binding || session == nil || *session != "session-7" { + if err != nil || owner != binding || session == nil || session.id != "session-7" { t.Fatalf("request = %+v, %v, %v", wire, session, err) } encoded, err := json.Marshal(requestEnvelope{Command: "file.read", Payload: struct{}{}, RemoteWorkspace: wire}) @@ -56,6 +56,33 @@ func TestRemoteWorkspaceRequestsCarryTheBindingExceptSessionCommands(t *testing. } } +func TestCapturedRemoteConnectionCannotMoveToAReplacement(t *testing.T) { + binding := NewRemoteWorkspace("/cache/remote/repo", "/srv/repo", nil) + binding.Attach("session-7") + captured := binding.CaptureConnection() + ctx := captured.Context(context.Background()) + wire, owner, oldSession, err := remoteWorkspaceRequest(ctx, "lsp.startServer") + if err != nil || wire == nil || wire.SessionID != "session-7" || owner != binding { + t.Fatalf("captured start = %+v, %v", wire, err) + } + binding.Detach() + // Even attaching the same ID creates a different connection. + binding.Attach("session-7") + lost := &Error{Code: CodeConnectionClosed} + remoteWorkspaceAnswered(owner, oldSession, lost) + if captured.IsCurrent() || binding.SessionID() != "session-7" { + t.Fatal("the old request affected the replacement connection") + } + wire, _, _, err = remoteWorkspaceRequest(ctx, "workspace.pluginFile") + var coreErr *Error + if wire != nil || !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed { + t.Fatalf("stale captured request = %+v, %v, want connection_closed", wire, err) + } + if wire, _, _, err := remoteWorkspaceRequest(WithoutRemoteWorkspace(ctx), "lsp.stopServer"); wire != nil || err != nil { + t.Fatalf("cleanup with a session ID = %+v, %v, want no workspace", wire, err) + } +} + // With the real kernel: a command without a remote adapter is refused instead of reading the // placeholder, and a command with one over a session Core does not know reports the loss once // and detaches the binding, so the next request fails without reaching Core. @@ -163,6 +190,34 @@ func TestPayloadOnlyCommandsSendNoRemoteWorkspace(t *testing.T) { } } +func TestPlanPluginUninstallFromRemoteWindow(t *testing.T) { + const pluginID = "dev.lithe.test.uninstall" + binding := NewRemoteWorkspace("/cache/remote/repo", "/srv/repo", nil) + ctx := WithRemoteWorkspace(testContext(t), binding) + request := PluginLifecycleRequest{ + Installed: []PluginInstalledVersion{{PluginID: pluginID, Version: "1.0.0"}}, + Action: PluginUninstall, PluginID: pluginID, + } + + client := NewClient() + for _, name := range []string{"connected", "disconnected"} { + t.Run(name, func(t *testing.T) { + if name == "connected" { + binding.Attach("remote-window-session") + } else { + binding.Detach() + } + plan, err := client.PlanPluginLifecycle(ctx, request) + if err != nil { + t.Fatal(err) + } + if plan.Rejection != "" || len(plan.Steps) == 0 || plan.Steps[0].Kind != PluginStopPrograms { + t.Fatalf("uninstall plan = %+v, want the plugin's programs stopped first", plan) + } + }) + } +} + // Closing every session ends the process's remote development: Core then refuses to connect. // It runs in a child process, since the refusal lasts as long as the process. func TestRemoteCloseAllRefusesLaterConnections(t *testing.T) { diff --git a/desktop/internal/core/remote_terminal.go b/desktop/internal/core/remote_terminal.go index 71ed1e1ee0..2b1fc47726 100644 --- a/desktop/internal/core/remote_terminal.go +++ b/desktop/internal/core/remote_terminal.go @@ -16,9 +16,16 @@ type RemoteTerminalOpen struct { Argv []string `json:"argv,omitempty"` // Cwd is the absolute host working directory; empty starts in the user's home. Cwd string `json:"cwd,omitempty"` + // ScopedCwd is an alternative to Cwd that the host resolves without following + // links below the workspace root. + ScopedCwd *RemoteScopedDirectory `json:"scopedCwd,omitempty"` + // Environment selects the base environment before Env and UnsetEnv are applied. + Environment string `json:"environment,omitempty"` // Env adds variables to the server's environment. TERM is xterm-256color unless Env sets // it. Env map[string]string `json:"env,omitempty"` + // UnsetEnv removes variables from the resulting environment. + UnsetEnv []string `json:"unsetEnv,omitempty"` // Columns and Rows are the size in character cells; both must be at least 1. Columns uint16 `json:"columns"` Rows uint16 `json:"rows"` @@ -27,6 +34,12 @@ type RemoteTerminalOpen struct { Label *RemoteResourceLabel `json:"label,omitempty"` } +// RemoteScopedDirectory identifies an approved workspace root and a directory within it. +type RemoteScopedDirectory struct { + Root string `json:"root"` + Path string `json:"path"` +} + // RemoteResourceLabel names a host resource in server.state. type RemoteResourceLabel struct { // Kind is the client's category, such as "terminal"; at most 64 characters. @@ -61,9 +74,8 @@ func cutRunes(text string, limit int) string { // Core holds 1024 undelivered events per terminal and ends the terminal, and with it the // request, when a subscriber stops reading. type RemoteTerminalEvents struct { - // Started is called once, before any output, with the id terminal.write, terminal.resize - // and terminal.close take. - Started func(terminalID uint64) + // Started is called once, before any output, with the terminal resource ID and the host PID. + Started func(terminalID uint64, pid int64) // Output receives the bytes the program wrote, in order. Output owns data. Output func(data []byte) } @@ -81,6 +93,7 @@ type remoteTerminalEvent struct { Event string `json:"event"` Params struct { TerminalID uint64 `json:"terminalId"` + PID int64 `json:"pid"` Data string `json:"data"` } `json:"params"` } @@ -138,7 +151,7 @@ func deliverRemoteTerminalEvent(raw json.RawMessage, events RemoteTerminalEvents switch event.Event { case "terminal.started": if events.Started != nil { - events.Started(event.Params.TerminalID) + events.Started(event.Params.TerminalID, event.Params.PID) } case "terminal.output": data, err := base64.StdEncoding.DecodeString(event.Params.Data) diff --git a/desktop/internal/core/remote_terminal_test.go b/desktop/internal/core/remote_terminal_test.go index ce2c77c97e..12151cbe07 100644 --- a/desktop/internal/core/remote_terminal_test.go +++ b/desktop/internal/core/remote_terminal_test.go @@ -15,12 +15,14 @@ import ( func TestRemoteTerminalEventsReachTheirCallbacks(t *testing.T) { var got []string events := RemoteTerminalEvents{ - Started: func(id uint64) { got = append(got, "started "+strconv.FormatUint(id, 10)) }, - Output: func(data []byte) { got = append(got, "output "+string(data)) }, + Started: func(id uint64, pid int64) { + got = append(got, "started "+strconv.FormatUint(id, 10)+"/"+strconv.FormatInt(pid, 10)) + }, + Output: func(data []byte) { got = append(got, "output "+string(data)) }, } for _, raw := range []string{ `{"type":"progress","message":"remote"}`, - `{"type":"remote","event":"terminal.started","params":{"terminalId":7}}`, + `{"type":"remote","event":"terminal.started","params":{"terminalId":7,"pid":123}}`, `{"type":"remote","event":"terminal.output","params":{"terminalId":7,"data":"aGk="}}`, `{"type":"remote","event":"terminal.output","params":{"terminalId":7,"data":""}}`, `{"type":"remote","event":"terminal.exit","params":{"terminalId":7,"exitCode":0}}`, @@ -30,7 +32,7 @@ func TestRemoteTerminalEventsReachTheirCallbacks(t *testing.T) { t.Fatalf("event %s: %v", raw, err) } } - if want := []string{"started 7", "output hi"}; strings.Join(got, "|") != strings.Join(want, "|") { + if want := []string{"started 7/123", "output hi"}; strings.Join(got, "|") != strings.Join(want, "|") { t.Fatalf("delivered %q, want %q", got, want) } bad := `{"type":"remote","event":"terminal.output","params":{"terminalId":7,"data":"not base64!"}}` @@ -76,7 +78,7 @@ func TestRemoteTerminalOfAnUnknownSession(t *testing.T) { ctx := testContext(t) started := false _, err := client.RemoteRunTerminal(ctx, "no-such-session", RemoteTerminalOpen{Columns: 80, Rows: 24}, RemoteTerminalEvents{ - Started: func(uint64) { started = true }, + Started: func(uint64, int64) { started = true }, }) var coreErr *Error if !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed || started { diff --git a/desktop/internal/core/run_config.go b/desktop/internal/core/run_config.go index 5b4e49d765..f230f98b20 100644 --- a/desktop/internal/core/run_config.go +++ b/desktop/internal/core/run_config.go @@ -131,6 +131,22 @@ type RunConfigChange struct { Content *string `json:"content"` } +// ApplyRemoteRunConfigurationChanges publishes a Core edit on its captured workspace host. +// The host checks all base hashes before the first write. A file conflict is reported +// separately so the editor can use the same message as a local conflict. +func (c *Client) ApplyRemoteRunConfigurationChanges(ctx context.Context, root string, changes []RunConfigChange) (bool, error) { + binding := RemoteWorkspaceOf(ctx) + if binding == nil || binding.LocalRoot() != root { + return false, &Error{Code: CodeConnectionClosed, Message: "the Run edit has no matching workspace attachment"} + } + params := struct { + Root string `json:"root"` + Changes []RunConfigChange `json:"changes"` + }{binding.RemoteRoot(), changes} + err := c.remoteWorkspaceHostRequest(ctx, "fs.applyRunConfigChanges", params, nil) + return remoteHostCode(err) == "CONFLICT", err +} + // BuildReference is the configuration's build provider selector, when it has one. func (r RunConfiguration) BuildReference() (RunProviderReference, bool) { raw, ok := r.Extensions["build"] diff --git a/desktop/internal/core/run_start.go b/desktop/internal/core/run_start.go index e507936952..c7f55f8858 100644 --- a/desktop/internal/core/run_start.go +++ b/desktop/internal/core/run_start.go @@ -6,6 +6,14 @@ import ( "encoding/json" ) +// ProcessPlacement selects the workspace host or the host displaying the IDE. +type ProcessPlacement string + +const ( + ProcessPlacementWorkspace ProcessPlacement = "workspace" + ProcessPlacementUI ProcessPlacement = "ui" +) + // RunStartExecutable names the program of a plugin-started run. Kind is // "toolchain" (Value is a tool definition ID the manifest requires) or // "packaged" (Value is a normalized path inside the plugin package). @@ -57,6 +65,7 @@ type RunStart struct { Arguments []string `json:"arguments"` WorkingDirectory string `json:"workingDirectory"` Environment map[string]string `json:"environment"` + Placement ProcessPlacement `json:"placement,omitempty"` OutputEncoding string `json:"outputEncoding,omitempty"` TemporaryFiles []RunStartFile `json:"temporaryFiles"` Debug *RunStartDebug `json:"debug"` diff --git a/desktop/internal/core/source_settings.go b/desktop/internal/core/source_settings.go index 7d7b9bcd9d..136d70feaf 100644 --- a/desktop/internal/core/source_settings.go +++ b/desktop/internal/core/source_settings.go @@ -27,6 +27,7 @@ type SettingsSource struct { Group string `json:"group"` Title string `json:"title"` Path string `json:"path"` + Scope string `json:"scope,omitempty"` Revision string `json:"revision"` Writable bool `json:"writable"` Fields []SourceSettingField `json:"fields"` @@ -95,7 +96,7 @@ type SourceSettingInput struct { On bool `json:"on"` Inherit bool `json:"inherit"` // Entries is the ordered entryList draft; other kinds leave it empty. - Entries []SourceEntry `json:"entries"` + Entries []SourceEntry `json:"entries,omitempty"` } type SourceSettingsLimits struct { diff --git a/desktop/internal/core/toolchain.go b/desktop/internal/core/toolchain.go index 0410b98597..44fede34ad 100644 --- a/desktop/internal/core/toolchain.go +++ b/desktop/internal/core/toolchain.go @@ -322,6 +322,15 @@ type ToolchainResolveRequest struct { Fixed *ToolchainFixed `json:"fixed,omitempty"` } +// RemoteToolchainResolveRequest selects an installation from the captured host. +// Directory is relative to the remote workspace root. +type RemoteToolchainResolveRequest struct { + Registry json.RawMessage `json:"registry"` + Tool string `json:"tool"` + Directory string `json:"directory"` + MinimumVersion string `json:"minimumVersion,omitempty"` +} + // ToolchainGlobalDefault is an application-wide installation Core may select. type ToolchainGlobalDefault struct { Home string `json:"home"` @@ -481,7 +490,19 @@ func (c *Client) ToolchainCandidatesOf(ctx context.Context, request ToolchainCan // ResolveToolchain selects one installation through the fixed four layers. func (c *Client) ResolveToolchain(ctx context.Context, request ToolchainResolveRequest) (ToolchainResolution, error) { - const command = "toolchains.resolve" + return c.resolveToolchain(ctx, "toolchains.resolve", request) +} + +// ResolveRemoteToolchain gathers filesystem and login environment facts on the host. +func (c *Client) ResolveRemoteToolchain(ctx context.Context, request RemoteToolchainResolveRequest) (ToolchainResolution, error) { + allowed, _ := ctx.Value(projectCodeAllowedKey{}).(func() bool) + return c.resolveToolchain(ctx, "toolchains.resolveRemote", struct { + RemoteToolchainResolveRequest + ProjectCodeAllowed bool `json:"projectCodeAllowed"` + }{request, allowed != nil && allowed()}) +} + +func (c *Client) resolveToolchain(ctx context.Context, command string, request any) (ToolchainResolution, error) { var result toolchainOutcome if err := c.Execute(ctx, command, request, &result); err != nil { return ToolchainResolution{}, err @@ -490,11 +511,11 @@ func (c *Client) ResolveToolchain(ctx context.Context, request ToolchainResolveR return ToolchainResolution{}, err } if len(result.Resolution) == 0 { - return ToolchainResolution{}, newParseError(command, "toolchains.resolve returned no resolution", "") + return ToolchainResolution{}, newParseError(command, "Core returned no toolchain resolution", "") } var resolution ToolchainResolution if err := json.Unmarshal(result.Resolution, &resolution); err != nil { - return ToolchainResolution{}, newParseError(command, "toolchains.resolve returned an invalid resolution", err.Error()) + return ToolchainResolution{}, newParseError(command, "Core returned an invalid toolchain resolution", err.Error()) } return resolution, nil } diff --git a/desktop/internal/pluginruntime/lock.go b/desktop/internal/filelock/filelock.go similarity index 70% rename from desktop/internal/pluginruntime/lock.go rename to desktop/internal/filelock/filelock.go index ac28bc2f5f..e9784f3324 100644 --- a/desktop/internal/pluginruntime/lock.go +++ b/desktop/internal/filelock/filelock.go @@ -1,4 +1,5 @@ -package pluginruntime +// Package filelock owns the native, process-scoped locks for writable caches. +package filelock import ( "context" @@ -8,10 +9,14 @@ import ( "time" ) -// acquire uses an OS lock, not a pid or timestamp lease: process death releases +// ErrInvalidFile means the lock path does not name the opened regular file. +var ErrInvalidFile = errors.New("lock path is not a regular file") + +// Acquire uses an OS lock, not a pid or timestamp lease: process death releases // ownership automatically. The file stays in place so another opener cannot -// lock a different inode while a previous waiter still holds the old one. -func acquire(ctx context.Context, name string) (unlock func() error, err error) { +// lock a different inode while a previous waiter still holds the old one. The +// caller bounds the wait through ctx. +func Acquire(ctx context.Context, name string) (unlock func() error, err error) { defer func() { if err != nil && unlock != nil { err = errors.Join(err, unlock()) @@ -46,11 +51,12 @@ func acquire(ctx context.Context, name string) (unlock func() error, err error) return nil, err } if !info.Mode().IsRegular() || !os.SameFile(info, opened) { - return nil, ErrArtifact + return nil, ErrInvalidFile } - bounded, cancel := context.WithTimeout(ctx, 5*time.Minute) - defer cancel() for { + if err := ctx.Err(); err != nil { + return nil, err + } locked, err := tryLock(file) if err != nil { return nil, err @@ -63,12 +69,9 @@ func acquire(ctx context.Context, name string) (unlock func() error, err error) // bounded timer performs no filesystem scanning and owns no goroutine. timer := time.NewTimer(100 * time.Millisecond) select { - case <-bounded.Done(): + case <-ctx.Done(): timer.Stop() - if ctx.Err() != nil { - return nil, ctx.Err() - } - return nil, ErrBusy + return nil, ctx.Err() case <-timer.C: } } diff --git a/desktop/internal/pluginruntime/lock_unix.go b/desktop/internal/filelock/lock_unix.go similarity index 93% rename from desktop/internal/pluginruntime/lock_unix.go rename to desktop/internal/filelock/lock_unix.go index 4eae6187d8..4ce41a8f2a 100644 --- a/desktop/internal/pluginruntime/lock_unix.go +++ b/desktop/internal/filelock/lock_unix.go @@ -1,6 +1,6 @@ //go:build darwin || linux -package pluginruntime +package filelock import ( "errors" diff --git a/desktop/internal/pluginruntime/lock_windows.go b/desktop/internal/filelock/lock_windows.go similarity index 94% rename from desktop/internal/pluginruntime/lock_windows.go rename to desktop/internal/filelock/lock_windows.go index ef7fbb7c85..659e7ac8ba 100644 --- a/desktop/internal/pluginruntime/lock_windows.go +++ b/desktop/internal/filelock/lock_windows.go @@ -1,6 +1,6 @@ //go:build windows -package pluginruntime +package filelock import ( "errors" diff --git a/desktop/internal/i18n/run_messages.go b/desktop/internal/i18n/run_messages.go index 37140481b8..6651b53c2b 100644 --- a/desktop/internal/i18n/run_messages.go +++ b/desktop/internal/i18n/run_messages.go @@ -7,10 +7,12 @@ import ( // RunMessages are the words of the Run tool window: its execution tabs, tree and console. type RunMessages struct { - Rerun string - Ended string - LinkMissing string - LinkUnresolved string + Rerun string + Ended string + RemoteDisconnected string + RemoteLabel func(label string) string + LinkMissing string + LinkUnresolved string // CloseSession closes the tab of a finished execution; Empty is the window before anything ran. CloseSession string Empty string @@ -35,8 +37,12 @@ type RunMessages struct { func runMessages(language Language) RunMessages { return RunMessages{ - Rerun: Shared(language, "desktop.run.rerun"), - Ended: Shared(language, "desktop.run.ended"), + Rerun: Shared(language, "desktop.run.rerun"), + Ended: Shared(language, "desktop.run.ended"), + RemoteDisconnected: Shared(language, "desktop.run.remoteDisconnected"), + RemoteLabel: func(label string) string { + return SharedFormat(language, "desktop.run.remoteLabel", map[string]string{"label": label}) + }, LinkMissing: Shared(language, "desktop.run.linkMissing"), LinkUnresolved: Shared(language, "desktop.run.linkUnresolved"), CloseSession: Shared(language, "desktop.run.closeSession"), diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index a75305fbcb..080f7e0b1d 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -554,6 +554,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.debug.stepOver": "Step Over", "desktop.debug.stop": "Stop debugging", "desktop.debug.targetUnavailable": "No runnable debug target was found. Build the program first.", + "desktop.debug.terminalUnavailable": "Could not start the remote debug terminal.", "desktop.debug.terminated": "Debug session terminated", "desktop.debug.threadFallback": "Thread {id}", "desktop.debug.threadRunning": "{name} (running)", @@ -1271,6 +1272,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.marketplace.runtimeReady": "{dependency} is ready", "desktop.marketplace.runtimeReceived": "Downloading {dependency}… {received} MiB", "desktop.marketplace.runtimeRepairing": "Repairing {dependency}…", + "desktop.marketplace.runtimeUploading": "Uploading {dependency} to workspace host… {sent} / {total} MiB", "desktop.marketplace.runtimeVerifying": "Verifying {dependency}…", "desktop.marketplace.sourceInvalid": "Enter an HTTPS address for the index.", "desktop.marketplace.sourceUnavailable": "Source unavailable: {source}", @@ -1396,6 +1398,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.pluginHost.messageOK": "OK", "desktop.pluginHost.terminalAllow": "Run", "desktop.pluginHost.terminalConsentDetails": "Program: {program}\nArguments: {arguments}\nDirectory: {directory}", + "desktop.pluginHost.terminalConsentRemote": "Remote connection: {connection}", "desktop.pluginHost.terminalConsentTitle": "{plugin} wants to run a program in a terminal", "desktop.pluginHost.terminalDeny": "Cancel", "desktop.pluginSettings.actionCancel": "Cancel", @@ -1422,6 +1425,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.pluginSettings.project": "Project", "desktop.pluginSettings.range": "Range: {minimum}–{maximum} {unit}", "desktop.pluginSettings.reload": "Reload", + "desktop.pluginSettings.remoteConnection": "Remote: {name}", "desktop.pluginSettings.reset": "Reset", "desktop.pluginSettings.restart": "Restart language server", "desktop.pluginSettings.restartFailed": "Could not finish restarting the language server. Close and reopen the project before trying again.", @@ -2143,6 +2147,8 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.run.remote.signal": "the program was ended by signal {signal}", "desktop.run.remote.toolchain": "a remote workspace cannot run a program chosen through a toolchain yet; name the program or its path on the host", "desktop.run.remote.unsupported": "a remote workspace runs only program and script configurations, on the host, and does not debug yet", + "desktop.run.remoteDisconnected": "Connection to the remote workspace lost.", + "desktop.run.remoteLabel": "{label} (Remote)", "desktop.run.rerun": "Run again", "desktop.run.signalled": "Process stopped by signal {signal}.", "desktop.run.snapshot.menu": "Snapshot output", @@ -2633,6 +2639,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.sourceSettings.chooseTitle": "Add {title}", "desktop.sourceSettings.close": "Back", "desktop.sourceSettings.compilerTitle": "{compiler} Compiler", + "desktop.sourceSettings.confirmRemoteSave": "Save to these remote files?", "desktop.sourceSettings.effective": "Effective: {value}", "desktop.sourceSettings.entryAdd": "Add", "desktop.sourceSettings.entryDown": "Move down", @@ -2644,6 +2651,9 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.sourceSettings.inherit": "Inherit ({value})", "desktop.sourceSettings.modules": "Modules", "desktop.sourceSettings.noValue": "Not determined", + "desktop.sourceSettings.remotePath": "Absolute path on the remote host", + "desktop.sourceSettings.remoteSaveUnverified": "One or more remote files may have been saved. Reload to check their contents before trying again.", + "desktop.sourceSettings.remoteSourceChanged": "The remote file or connection changed. Reload the settings before saving.", "desktop.sourceSettings.remove": "Inherit project defaults", "desktop.startupSweep.body": "{arg1} processes started by an earlier run of Lithe are still running. Ending them stops them.", "desktop.startupSweep.end": "End them", @@ -4455,6 +4465,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.debug.stepOver": "单步跳过", "desktop.debug.stop": "停止调试", "desktop.debug.targetUnavailable": "没有找到可运行的调试目标,请先构建程序。", + "desktop.debug.terminalUnavailable": "无法启动远程调试终端。", "desktop.debug.terminated": "调试会话已终止", "desktop.debug.threadFallback": "线程 {id}", "desktop.debug.threadRunning": "{name}(运行中)", @@ -5172,6 +5183,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.marketplace.runtimeReady": "{dependency} 已就绪", "desktop.marketplace.runtimeReceived": "正在下载 {dependency}… {received} MiB", "desktop.marketplace.runtimeRepairing": "正在修复 {dependency}…", + "desktop.marketplace.runtimeUploading": "正在将 {dependency} 上传至工作区主机… {sent} / {total} MiB", "desktop.marketplace.runtimeVerifying": "正在验证 {dependency}…", "desktop.marketplace.sourceInvalid": "请输入 HTTPS 格式的索引地址。", "desktop.marketplace.sourceUnavailable": "来源不可用:{source}", @@ -5297,6 +5309,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.pluginHost.messageOK": "好", "desktop.pluginHost.terminalAllow": "运行", "desktop.pluginHost.terminalConsentDetails": "程序:{program}\n参数:{arguments}\n目录:{directory}", + "desktop.pluginHost.terminalConsentRemote": "远程连接:{connection}", "desktop.pluginHost.terminalConsentTitle": "{plugin} 想在终端中运行程序", "desktop.pluginHost.terminalDeny": "取消", "desktop.pluginSettings.actionCancel": "取消", @@ -5323,6 +5336,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.pluginSettings.project": "项目", "desktop.pluginSettings.range": "范围:{minimum}–{maximum} {unit}", "desktop.pluginSettings.reload": "重新加载", + "desktop.pluginSettings.remoteConnection": "远端:{name}", "desktop.pluginSettings.reset": "重置", "desktop.pluginSettings.restart": "重启语言服务器", "desktop.pluginSettings.restartFailed": "无法完成语言服务器重启,请关闭并重新打开项目后再试。", @@ -6044,6 +6058,8 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.run.remote.signal": "程序被信号 {signal} 结束", "desktop.run.remote.toolchain": "远程工作区暂不支持运行通过工具链选择的程序,请填写主机上的程序名或路径", "desktop.run.remote.unsupported": "远程工作区只在主机上运行程序和脚本运行配置,暂不支持调试", + "desktop.run.remoteDisconnected": "与远程工作区的连接已断开。", + "desktop.run.remoteLabel": "{label}(远端)", "desktop.run.rerun": "再次运行", "desktop.run.signalled": "进程被信号 {signal} 终止。", "desktop.run.snapshot.menu": "快照当前输出", @@ -6534,6 +6550,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.sourceSettings.chooseTitle": "添加{title}", "desktop.sourceSettings.close": "返回", "desktop.sourceSettings.compilerTitle": "{compiler} 编译器", + "desktop.sourceSettings.confirmRemoteSave": "保存到以下远端文件?", "desktop.sourceSettings.effective": "当前生效:{value}", "desktop.sourceSettings.entryAdd": "添加", "desktop.sourceSettings.entryDown": "下移", @@ -6545,6 +6562,9 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.sourceSettings.inherit": "继承({value})", "desktop.sourceSettings.modules": "模块", "desktop.sourceSettings.noValue": "未确定", + "desktop.sourceSettings.remotePath": "远端主机上的绝对路径", + "desktop.sourceSettings.remoteSaveUnverified": "一个或多个远端文件可能已保存。请重新加载以确认内容,再重试。", + "desktop.sourceSettings.remoteSourceChanged": "远端文件或连接已变化。请重新加载设置后再保存。", "desktop.sourceSettings.remove": "继承项目设置", "desktop.startupSweep.body": "上次运行 Lithe 启动的 {arg1} 个进程仍在运行。结束它们会停止这些进程。", "desktop.startupSweep.end": "结束这些进程", diff --git a/desktop/internal/marketplace/remote_archive_cache.go b/desktop/internal/marketplace/remote_archive_cache.go new file mode 100644 index 0000000000..f049c74115 --- /dev/null +++ b/desktop/internal/marketplace/remote_archive_cache.go @@ -0,0 +1,229 @@ +package marketplace + +import ( + "context" + "encoding/hex" + "errors" + "io" + "io/fs" + "os" + "path/filepath" + "slices" + "strings" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/filelock" +) + +const ( + remoteCacheBytes int64 = 2 * MaxArchiveBytes + remoteCacheEntries = 32 + remoteCachePending = ".pending" +) + +var errRemoteCacheFile = errors.New("remote archive cache entry is not a regular bounded archive") + +// RemoteArchiveCache stores completed, checksum-addressed transfers in the +// platform's user cache. Entries are disposable; users of Read verify the +// opened file against its expected checksum before relying on it. +type RemoteArchiveCache struct { + directory string + maxBytes int64 +} + +// NewRemoteArchiveCache resolves the runtime cache independently of the bundle, +// plugin directory and checkout. +func NewRemoteArchiveCache() (RemoteArchiveCache, error) { + root, err := os.UserCacheDir() + if err != nil { + return RemoteArchiveCache{}, err + } + if !filepath.IsAbs(root) { + return RemoteArchiveCache{}, ErrArchiveSelection + } + return RemoteArchiveCache{filepath.Join(root, "Lithe", "remote-plugin-archives"), remoteCacheBytes}, nil +} + +// Read holds the entry in place until consume completes, including on Windows. +// The returned boolean reports whether consume ran. An absent entry is a miss. +func (c RemoteArchiveCache) Read(ctx context.Context, digest string, consume func(string) error) (used bool, err error) { + name, err := remoteArchiveName(digest) + if err != nil { + return false, err + } + err = c.locked(ctx, func() error { + path := filepath.Join(c.directory, name) + info, err := os.Lstat(path) + // log-exempt: 预期的缺失:只有已经下载且尚未被清理的包才有缓存。 + if errors.Is(err, fs.ErrNotExist) { + return nil + } + if err != nil { + return err + } + if !info.Mode().IsRegular() || info.Size() > MaxArchiveBytes { + return errRemoteCacheFile + } + used = true + if err := consume(path); err != nil { + return err + } + now := time.Now() + return os.Chtimes(path, now, now) + }) + return used, err +} + +// Store publishes a fully downloaded archive. Files reviewed or read by other +// instances are pinned by the same native lock until the reader releases it. +func (c RemoteArchiveCache) Store(ctx context.Context, digest string, archive *DownloadedArchive) error { + name, err := remoteArchiveName(digest) + if err != nil { + return err + } + file, err := os.Open(archive.Path()) + if err != nil { + return err + } + saveErr := c.locked(ctx, func() error { + info, err := file.Stat() + if err != nil { + return err + } + if !info.Mode().IsRegular() || info.Size() > MaxArchiveBytes || info.Size() > c.maxBytes { + return errRemoteCacheFile + } + pending := filepath.Join(c.directory, remoteCachePending) + if err := removeArchiveEntry(pending); err != nil { + return err + } + if err := c.evict(name, info.Size()); err != nil { + return err + } + return copyCacheEntry(ctx, file, info.Size(), pending, filepath.Join(c.directory, name)) + }) + return errors.Join(saveErr, file.Close()) +} + +// locked serializes disk inventory and publication across desktop processes. +// A slow reader never holds this lock while downloading. +func (c RemoteArchiveCache) locked(ctx context.Context, action func() error) (err error) { + if err := ctx.Err(); err != nil { + return err + } + if err := os.MkdirAll(c.directory, 0o700); err != nil { + return err + } + info, err := os.Lstat(c.directory) + if err != nil { + return err + } + if !info.IsDir() { + return errRemoteCacheFile + } + lockCtx, cancel := context.WithTimeout(ctx, 15*time.Second) + unlock, err := filelock.Acquire(lockCtx, filepath.Join(c.directory, ".lock")) + cancel() + if err != nil { + return err + } + defer func() { err = errors.Join(err, unlock()) }() + return action() +} + +// evict leaves enough room for staging the replacement, both in bytes and in +// file count. Recency is the last verified use, recorded as the file's mtime. +func (c RemoteArchiveCache) evict(replacing string, size int64) error { + entries, err := os.ReadDir(c.directory) + if err != nil { + return err + } + var inventory []fs.FileInfo + total := size + for _, entry := range entries { + name, err := remoteArchiveName(entry.Name()) + if err != nil || name != entry.Name() { + continue + } + info, err := entry.Info() + // log-exempt: 预期的缺失:系统清理缓存后该文件已无需逐出。 + if errors.Is(err, fs.ErrNotExist) { + continue + } + if err != nil { + return err + } + if name == replacing || !info.Mode().IsRegular() || info.Size() > MaxArchiveBytes { + if err := removeArchiveEntry(filepath.Join(c.directory, name)); err != nil { + return err + } + continue + } + inventory = append(inventory, info) + total += info.Size() + } + slices.SortStableFunc(inventory, func(a, b fs.FileInfo) int { return a.ModTime().Compare(b.ModTime()) }) + for index, info := range inventory { + if total <= c.maxBytes && len(inventory)-index < remoteCacheEntries { + break + } + if err := removeArchiveEntry(filepath.Join(c.directory, info.Name())); err != nil { + return err + } + total -= info.Size() + } + return nil +} + +func remoteArchiveName(digest string) (string, error) { + if len(digest) != 64 { + return "", ErrArchiveSelection + } + if _, err := hex.DecodeString(digest); err != nil { + return "", ErrArchiveSelection + } + return strings.ToLower(digest), nil +} + +func removeArchiveEntry(path string) error { + err := os.Remove(path) + // log-exempt: 预期的缺失:另一个清理者已移除此缓存条目。 + if errors.Is(err, fs.ErrNotExist) { + return nil + } + return err +} + +func copyCacheEntry(ctx context.Context, source io.Reader, size int64, pending, destination string) (err error) { + defer func() { + if err != nil { + err = errors.Join(err, removeArchiveEntry(pending)) + } + }() + temp, err := os.OpenFile(pending, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + if err != nil { + return err + } + // The temporary file stays within the cache budget even if its source + // grows after Stat. Check the exact byte count before publication. + written, err := io.Copy(temp, io.LimitReader(cacheCopyReader{ctx, source}, size)) + if err := errors.Join(err, temp.Close(), ctx.Err()); err != nil { + return err + } + if written != size { + return io.ErrUnexpectedEOF + } + return os.Rename(pending, destination) +} + +type cacheCopyReader struct { + ctx context.Context + source io.Reader +} + +func (r cacheCopyReader) Read(p []byte) (int, error) { + if err := r.ctx.Err(); err != nil { + return 0, err + } + return r.source.Read(p) +} diff --git a/desktop/internal/marketplace/remote_archive_cache_test.go b/desktop/internal/marketplace/remote_archive_cache_test.go new file mode 100644 index 0000000000..69d0665a2c --- /dev/null +++ b/desktop/internal/marketplace/remote_archive_cache_test.go @@ -0,0 +1,75 @@ +package marketplace + +import ( + "context" + "errors" + "os" + "path/filepath" + "testing" + "time" +) + +func TestRemoteArchiveCacheKeepsRecentlyUsedArchivesWithinItsBudget(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + root := t.TempDir() + cache := RemoteArchiveCache{directory: filepath.Join(root, "cache"), maxBytes: 8} + download := func(body string) string { + t.Helper() + selection := archiveSelection(body) + archive, err := newArchiveDownloader(archiveClient(body, int64(len(body))), root).Download(ctx, selection) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := archive.Discard(); err != nil { + t.Error(err) + } + }) + if err := cache.Store(ctx, selection.SHA256, archive); err != nil { + t.Fatal(err) + } + return selection.SHA256 + } + read := func(digest, want string) error { + t.Helper() + used, err := cache.Read(ctx, digest, func(path string) error { + bytes, err := os.ReadFile(path) + if err == nil && string(bytes) != want { + t.Errorf("cached bytes = %q, want %q", bytes, want) + } + return err + }) + if err == nil && !used { + return os.ErrNotExist + } + return err + } + first, second := download("old!"), download("two!") + for _, digest := range []string{first, second} { + past := time.Unix(1, 0) + if err := os.Chtimes(filepath.Join(cache.directory, digest), past, past); err != nil { + t.Fatal(err) + } + } + if err := read(first, "old!"); err != nil { + t.Fatal(err) + } + // Simulate the private staging file left by a process that was killed. + if err := os.WriteFile(filepath.Join(cache.directory, remoteCachePending), []byte("partial"), 0o600); err != nil { + t.Fatal(err) + } + third := download("new!") + if err := read(second, "two!"); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("least recently used archive survives: %v", err) + } + if err := read(first, "old!"); err != nil { + t.Fatal(err) + } + if err := read(third, "new!"); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(cache.directory, remoteCachePending)); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("abandoned archive survives: %v", err) + } +} diff --git a/desktop/internal/marketplace/service.go b/desktop/internal/marketplace/service.go index 2cab99d72b..4261a0561c 100644 --- a/desktop/internal/marketplace/service.go +++ b/desktop/internal/marketplace/service.go @@ -8,6 +8,7 @@ import ( "fmt" "io" "net/http" + "runtime" "strings" "time" @@ -117,6 +118,30 @@ func (s *Service) Fetch(ctx context.Context, input string, kind core.Marketplace return Snapshot{Source: source, Index: index}, nil } +// CurrentPlatform is the identifier desktop marketplace indexes use. +func CurrentPlatform() string { + arch := runtime.GOARCH + if arch == "amd64" { + arch = "x64" + } + return runtime.GOOS + "-" + arch +} + +// FetchRemoteVariant reads the installation's recorded index and leaves +// release selection to Core. The source kind comes from the built-in index identity. +func (s *Service) FetchRemoteVariant(ctx context.Context, indexURL string, request core.MarketplaceRemoteVariantRequest, selectVariant func(context.Context, core.MarketplaceRemoteVariantRequest) (core.MarketplaceAvailability, error)) (core.MarketplaceAvailability, error) { + data, _, err := s.fetchJSON(ctx, indexURL) + if err != nil { + return core.MarketplaceAvailability{}, err + } + request.Index = data + request.SourceKind = core.MarketplaceThirdParty + if indexURL == OfficialIndexURL { + request.SourceKind = core.MarketplaceOfficial + } + return selectVariant(ctx, request) +} + // FetchRecommendationBundle downloads the companion recommendations file first and returns // ok=false without fetching the index when the marketplace publishes no recommendations (HTTP 404). func (s *Service) FetchRecommendationBundle(ctx context.Context, input string, kind core.MarketplaceSourceKind) (RecommendationBundle, bool, error) { diff --git a/desktop/internal/pluginbackend/log_facts_test.go b/desktop/internal/pluginbackend/log_facts_test.go index 70e22c22bf..ff87f98eac 100644 --- a/desktop/internal/pluginbackend/log_facts_test.go +++ b/desktop/internal/pluginbackend/log_facts_test.go @@ -78,6 +78,34 @@ func TestStopForwardsTheLastFactsItWaitsThrough(t *testing.T) { } } +func TestStopDisposesAfterServeDrainsTheTerminalEvents(t *testing.T) { + for _, state := range []string{"sessionStopped", "sessionFailed"} { + t.Run(state, func(t *testing.T) { + kernel := &stoppingKernel{ + refusals: 1, + waitErr: &core.Error{ + Command: "lsp.waitEvents", + Code: core.CodeProcessFailed, + Details: state, + }, + } + disposed, err := New(kernel, nil).StopAndDispose(context.Background(), Session{ID: "session-1"}) + if !disposed || !kernel.destroyed || err != nil { + t.Fatalf("stop and dispose after terminal events were drained: disposed=%v, destroyed=%v, err=%v", disposed, kernel.destroyed, err) + } + }) + } +} + +func TestStopReportsAnEventWaitFailure(t *testing.T) { + waitErr := &core.Error{Command: "lsp.waitEvents", Code: core.CodeProcessFailed, Details: "transport failed"} + kernel := &stoppingKernel{refusals: 1, waitErr: waitErr} + disposed, err := New(kernel, nil).StopAndDispose(context.Background(), Session{ID: "session-1"}) + if disposed || kernel.destroyed || !errors.Is(err, waitErr) { + t.Fatalf("stop and dispose after wait fails: disposed=%v, destroyed=%v, err=%v", disposed, kernel.destroyed, err) + } +} + // TestRunnerWithoutLogSinkDropsFacts checks that a runner nobody gave a sink still serves // its session. func TestRunnerWithoutLogSinkDropsFacts(t *testing.T) { @@ -94,6 +122,14 @@ func TestRunnerWithoutLogSinkDropsFacts(t *testing.T) { type stoppingKernel struct { fakeKernel refusals int + waitErr error +} + +func (k *stoppingKernel) WaitBackendEvents(ctx context.Context, session string, timeout int) ([]core.BackendEvent, error) { + if k.waitErr != nil { + return nil, k.waitErr + } + return k.fakeKernel.WaitBackendEvents(ctx, session, timeout) } func (k *stoppingKernel) DestroyPluginBackend(ctx context.Context, session string) error { diff --git a/desktop/internal/pluginbackend/pluginbackend.go b/desktop/internal/pluginbackend/pluginbackend.go index 5164defe74..fef055ffc6 100644 --- a/desktop/internal/pluginbackend/pluginbackend.go +++ b/desktop/internal/pluginbackend/pluginbackend.go @@ -19,7 +19,6 @@ import ( "fmt" "os/exec" "path/filepath" - "strings" "sync" "time" @@ -132,6 +131,18 @@ type StartRequest struct { TemporaryDirectory string // Architecture is the platform Core plans for. Architecture string + // RemoteConnection binds a workspace process to the attachment + // captured when its owner requested the launch. + RemoteConnection *core.RemoteWorkspaceConnection + // PrepareUI provides local storage if Core places a process serving a + // remote workspace on the UI host. Workspace processes never call it. + PrepareUI func(context.Context, *StartRequest) error + // PrepareRemote deploys the package files Core selected to the captured host. + PrepareRemote func(context.Context, []string) (string, error) + // PrepareRemoteTools installs pinned runtimes needed by a launch after + // Core has confirmed that the process runs on the workspace host. + PrepareRemoteTools func(context.Context) (map[string]ToolExecutable, error) + remotePackageDirectory string // Settings are the plugin's own settings, opaque to this package. Settings map[string]json.RawMessage // ProjectSettings is the separately captured project override layer. @@ -146,6 +157,9 @@ type StartRequest struct { // ManagedTools are per-launch installations verified by the managed runtime resolver. // They are never stored as global defaults or used by a different plugin/session. ManagedTools map[string]ToolExecutable + // ManagedToolConnection binds remote tool paths to their verified attachment. + // Local installations leave it nil. + ManagedToolConnection *core.RemoteWorkspaceConnection // BeforeResolveTool lets a launch owner capture the sources that determine // the selected installation. It runs only before host toolchain resolution. BeforeResolveTool func(context.Context) error @@ -253,7 +267,9 @@ func (r *Runner) SetInitializeTimeout(timeout time.Duration) { r.initializeTimeo // the environment its selection declares (such as the tool's home and PATH). type ToolExecutable struct { Path string + Home string Environment map[string]string + PathPrepend []string // Arguments are the complete vector Core instantiated for a package entry. Arguments []string } @@ -261,8 +277,8 @@ type ToolExecutable struct { // ToolEntryLaunch contains verified native paths and the opaque inputs to // Core's tool template. No host code interprets a tool's entry grammar. type ToolEntryLaunch struct { - Tool, Executable, Entry, MinimumVersion string - RuntimeArguments, Arguments []string + Tool, Executable, Home, Entry, MinimumVersion string + RuntimeArguments, Arguments []string } // ToolEntryResolver applies a Core-owned tool template to verified native facts. @@ -305,30 +321,9 @@ func (r *Runner) Start(ctx context.Context, request StartRequest) (Session, erro if err := checkStartRequest(request); err != nil { return Session{}, err } - directories := core.PluginBackendDirectories{ - PluginDirectory: request.PackageDirectory, - StateDirectory: request.StateDirectory, - WorkspaceStateDirectory: request.WorkspaceStateDirectory, - LogDirectory: request.LogDirectory, - TemporaryDirectory: request.TemporaryDirectory, - Architecture: request.Architecture, - Settings: request.Settings, - ProjectSettings: request.ProjectSettings, - ProjectCodeAllowed: request.ProjectCodeAllowed, - } - var plan core.PluginBackendPlan - var err error - if request.Plan != nil { - plan = *request.Plan - } else if request.BuildSystemID != "" { - plan, err = r.kernel.PlanPluginBuildProvider(ctx, request.Manifest, request.BuildSystemID, directories) - } else if request.VcsProviderID != "" { - plan, err = r.kernel.PlanPluginVcsProvider(ctx, request.Manifest, request.VcsProviderID, directories) - } else if request.LanguageID != "" { - plan, err = r.kernel.PlanPluginLanguageServer(ctx, request.Manifest, request.LanguageID, directories) - } else { - plan, err = r.kernel.PlanPluginBackend(ctx, request.Manifest, directories) - } + ctx = core.WithoutRemoteWorkspace(ctx) + attachment := request.RemoteConnection + plan, err := r.plan(ctx, request, request.PrepareUI != nil || request.PrepareRemote != nil) if err != nil { return Session{}, err } @@ -346,15 +341,72 @@ func (r *Runner) Start(ctx context.Context, request StartRequest) (Session, erro } } } + uiProcess := attachment != nil && plan.Placement == "ui" + if uiProcess && request.PrepareUI != nil { + if err := request.PrepareUI(ctx, &request); err != nil { + return Session{}, err + } + plan, err = r.plan(ctx, request, false) + if err != nil { + return Session{}, err + } + } + remote := attachment + processDirectory := request.WorkingDirectory + if uiProcess { + remote = nil + processDirectory = request.StateDirectory + if !filepath.IsAbs(processDirectory) { + return Session{}, fmt.Errorf("%w: a UI process requires a local state directory", ErrRequest) + } + } if request.VcsProviderID != "" && plan.VcsProvider == nil { return Session{}, fmt.Errorf("%w: the plan names no VCS provider", ErrRequest) } if plan.Owner != nil && plan.Owner.PluginID != request.PluginID { return Session{}, fmt.Errorf("%w: launch plan belongs to another plugin", ErrRequest) } - resolved, err := pluginhost.VerifyLaunch(request.PackageDirectory, LaunchFromPlan(plan)) - if err != nil { - return Session{}, err + var resolved pluginhost.Resolved + if remote != nil { + if request.LanguageID == "" && request.VcsProviderID == "" && request.BuildSystemID == "" { + return Session{}, fmt.Errorf("%w: the backend must run on the UI host", ErrRequest) + } + if len(plan.RequiredPackagePaths) != 0 { + if request.PrepareRemote == nil { + return Session{}, fmt.Errorf("%w: the plugin has no deployment adapter", ErrRequest) + } + directory, prepareErr := request.PrepareRemote(remote.Context(ctx), plan.RequiredPackagePaths) + if prepareErr != nil { + return Session{}, prepareErr + } + request.remotePackageDirectory = directory + request.Plan = nil + plan, err = r.plan(ctx, request, false) + if err != nil { + return Session{}, err + } + } + systemCommand := plan.Launch.Kind == pluginhost.LaunchSystemCommand && len(plan.Launch.Commands) != 0 + tool := plan.Launch.Kind == pluginhost.LaunchTool && plan.Launch.Tool != "" + packaged := plan.Launch.Kind == pluginhost.LaunchPackaged && plan.Launch.RemoteExecutable != "" + if (!systemCommand && !tool && !packaged) || + len(plan.RequiredDirectories) != 0 || len(plan.WritablePaths) != 0 { + return Session{}, fmt.Errorf("%w: the plan has no available launch on the workspace host", ErrRequest) + } + if tool && plan.Launch.RemoteExecutable == "" && request.PrepareRemoteTools != nil { + request.ManagedTools, err = request.PrepareRemoteTools(remote.Context(ctx)) + if err != nil { + return Session{}, err + } + request.ManagedToolConnection = remote + } + resolved.Executable = plan.Launch.RemoteExecutable + resolved.Entry = plan.Launch.Entry + } else { + resolved, err = pluginhost.VerifyLaunch(request.PackageDirectory, LaunchFromPlan(plan)) + if err != nil { + return Session{}, err + } } granted := pluginhost.GrantServices(plan.Backend.HostServices, r.services) if request.Preparation { @@ -367,7 +419,7 @@ func (r *Runner) Start(ctx context.Context, request StartRequest) (Session, erro if executable == "" { executable = resolved.Runtime } - if executable == "" && plan.Launch.Kind == pluginhost.LaunchSystemCommand { + if executable == "" && remote == nil && plan.Launch.Kind == pluginhost.LaunchSystemCommand { executable, err = pluginhost.ResolveCommand(plan.Launch.Commands, r.commands.Lookup(request.PluginID, r.lookup)) if err != nil { return Session{}, err @@ -386,28 +438,41 @@ func (r *Runner) Start(ctx context.Context, request StartRequest) (Session, erro // A tool entry is instantiated by Core using its declaring plugin's // template after native path verification. This also covers packaged tools. var toolEnvironment map[string]string + var toolPathPrepend []string if plan.Launch.Kind == pluginhost.LaunchTool && resolved.Entry != "" { if r.toolEntries == nil { return Session{}, fmt.Errorf("%w: this host cannot instantiate tool entries", ErrRequest) } + toolCtx := ctx + home := "" + if remote != nil { + toolCtx = remote.Context(ctx) + if executable == "" && remote.SameAttachment(request.ManagedToolConnection) { + managed := request.ManagedTools[plan.Launch.Tool] + executable, home = managed.Path, managed.Home + } + } if executable == "" && request.BeforeResolveTool != nil { if err := request.BeforeResolveTool(ctx); err != nil { return Session{}, err } } - tool, err := r.toolEntries(ctx, request.PluginID, request.WorkingDirectory, ToolEntryLaunch{ - Tool: plan.Launch.Tool, Executable: executable, Entry: resolved.Entry, + tool, err := r.toolEntries(toolCtx, request.PluginID, processDirectory, ToolEntryLaunch{ + Tool: plan.Launch.Tool, Executable: executable, Home: home, Entry: resolved.Entry, MinimumVersion: plan.Launch.MinimumVersion, RuntimeArguments: plan.Launch.RuntimeArguments, Arguments: plan.Arguments, }) if err != nil { return Session{}, err } executable, toolEnvironment, arguments = tool.Path, tool.Environment, tool.Arguments + toolPathPrepend = tool.PathPrepend } // A bare tool launch uses the selected installation and the opaque args. if executable == "" && plan.Launch.Kind == pluginhost.LaunchTool { tool, managed := request.ManagedTools[plan.Launch.Tool] - if !managed { + managedOnHost := remote == nil && request.ManagedToolConnection == nil || + remote.SameAttachment(request.ManagedToolConnection) + if !managed || !managedOnHost { if r.tools == nil { return Session{}, fmt.Errorf("%w: this host cannot resolve tool launches", ErrRequest) } @@ -416,15 +481,19 @@ func (r *Runner) Start(ctx context.Context, request StartRequest) (Session, erro return Session{}, err } } + toolCtx := ctx + if remote != nil { + toolCtx = remote.Context(ctx) + } var err error - tool, err = r.tools(ctx, request.PluginID, request.WorkingDirectory, plan.Launch.Tool) + tool, err = r.tools(toolCtx, request.PluginID, processDirectory, plan.Launch.Tool) if err != nil { return Session{}, err } } - executable, toolEnvironment = tool.Path, tool.Environment + executable, toolEnvironment, toolPathPrepend = tool.Path, tool.Environment, tool.PathPrepend } - if executable == "" { + if executable == "" && (remote == nil || plan.Launch.Kind == pluginhost.LaunchTool) { return Session{}, fmt.Errorf("%w: the plan names no program", ErrRequest) } role := request.Role @@ -436,14 +505,15 @@ func (r *Runner) Start(ctx context.Context, request StartRequest) (Session, erro PluginID: request.PluginID, Role: role, ExecutablePath: executable, + UIProcess: uiProcess, Arguments: arguments, Environment: mergeEnvironment(mergeEnvironment(toolEnvironment, plan.Environment), request.Environment), SessionPolicy: plan.SessionPolicy, RootURI: request.RootURI, - WorkingDirectory: request.WorkingDirectory, + WorkingDirectory: processDirectory, HostServices: granted, ToolchainProviders: request.ToolchainProviders, - HostOptions: hostOptions(granted), + HostOptions: hostOptions(granted, r.services), InitializationOptions: plan.InitializationOptions, WorkspaceConfiguration: plan.WorkspaceConfiguration, @@ -456,6 +526,15 @@ func (r *Runner) Start(ctx context.Context, request StartRequest) (Session, erro enabled := false start.FunctionRelayEnabled = &enabled } + if remote != nil { + start.ExecutablePath = "" + start.RemoteCommands = plan.Launch.Commands + start.RemoteExecutablePath = executable + start.RemotePathPrepend = toolPathPrepend + } + if attachment != nil { + ctx = attachment.Context(ctx) + } var started core.PluginBackendStarted if request.LanguageID != "" { // From here Core owns the attempt: it records the launch, the early exit, the @@ -484,6 +563,36 @@ func (r *Runner) Start(ctx context.Context, request StartRequest) (Session, erro return session, nil } +func (r *Runner) plan(ctx context.Context, request StartRequest, probeLocalPlacement bool) (core.PluginBackendPlan, error) { + if request.Plan != nil { + return *request.Plan, nil + } + directories := core.PluginBackendDirectories{ + PluginDirectory: request.PackageDirectory, + RemotePluginDirectory: request.remotePackageDirectory, + StateDirectory: request.StateDirectory, + WorkspaceStateDirectory: request.WorkspaceStateDirectory, + LogDirectory: request.LogDirectory, + TemporaryDirectory: request.TemporaryDirectory, + Architecture: request.Architecture, + RemoteWorkspace: request.RemoteConnection != nil, + ProbeLocalPlacement: probeLocalPlacement, + Settings: request.Settings, + ProjectSettings: request.ProjectSettings, + ProjectCodeAllowed: request.ProjectCodeAllowed, + } + switch { + case request.BuildSystemID != "": + return r.kernel.PlanPluginBuildProvider(ctx, request.Manifest, request.BuildSystemID, directories) + case request.VcsProviderID != "": + return r.kernel.PlanPluginVcsProvider(ctx, request.Manifest, request.VcsProviderID, directories) + case request.LanguageID != "": + return r.kernel.PlanPluginLanguageServer(ctx, request.Manifest, request.LanguageID, directories) + default: + return r.kernel.PlanPluginBackend(ctx, request.Manifest, directories) + } +} + // mergeEnvironment layers the host's variables over a launch answer's. func mergeEnvironment(plan, host map[string]string) map[string]string { if len(plan) == 0 { @@ -522,15 +631,25 @@ func (r *Runner) StopAndDispose(ctx context.Context, session Session) (bool, err // Core keeps the session until its shutdown reaches a terminal state, so a // destroy immediately after stop is normally refused. Wait for queued // lifecycle events instead of treating that refusal as a cleanup failure. - var destroyErr error for { - destroyErr = r.kernel.DestroyPluginBackend(ctx, session.ID) - if destroyErr == nil || ctx.Err() != nil { - break + destroyErr := r.kernel.DestroyPluginBackend(ctx, session.ID) + if destroyErr == nil { + return true, stopErr + } + if err := ctx.Err(); err != nil { + return false, errors.Join(stopErr, destroyErr, err) } events, waitErr := r.kernel.WaitBackendEvents(ctx, session.ID, 250) if waitErr != nil { - break + // Serve can consume the terminal events before this wait sees them. + // Core then reports the terminal state as an error, and we can dispose once. + var coreErr *core.Error + if ctx.Err() == nil && errors.As(waitErr, &coreErr) && coreErr.Code == core.CodeProcessFailed && + (coreErr.Details == "sessionStopped" || coreErr.Details == "sessionFailed") { + destroyErr = r.kernel.DestroyPluginBackend(ctx, session.ID) + return destroyErr == nil, errors.Join(stopErr, destroyErr) + } + return false, errors.Join(stopErr, destroyErr, waitErr) } // The session's last lifecycle facts arrive here when nothing serves it // any more. @@ -538,7 +657,6 @@ func (r *Runner) StopAndDispose(ctx context.Context, session Session) (bool, err r.forwardLog(event) } } - return destroyErr == nil, errors.Join(stopErr, destroyErr) } // EventDiagnostics is the runtime event carrying a language server's diagnostics @@ -853,20 +971,28 @@ func checkStartRequest(request StartRequest) error { if request.PluginID == "" || request.ProviderID == "" { return fmt.Errorf("%w: no plugin or provider identity", ErrRequest) } - if request.StateDirectory == "" || !filepath.IsAbs(request.StateDirectory) { + if request.RemoteConnection == nil && !filepath.IsAbs(request.StateDirectory) { return fmt.Errorf("%w: the state directory must be absolute", ErrRequest) } return nil } -// hostOptions declares the editor service's options when the session is granted one of -// its registration methods; Core reports them only for granted methods. -func hostOptions(granted []string) *core.PluginHostOptions { +// hostOptions describes the host's registered methods. Core reports options +// only for methods the backend was actually granted. +func hostOptions(granted []string, services *pluginhost.Services) *core.PluginHostOptions { + if len(granted) == 0 { + return nil + } + options := &core.PluginHostOptions{MethodAuthorities: services.MethodAuthorities()} for _, method := range granted { - if strings.HasSuffix(method, "editor/registerActions") || strings.HasSuffix(method, "editor/registerProviders") { + switch method { + case pluginhost.MethodPrefix + "editor/registerActions", pluginhost.MethodPrefix + "editor/registerProviders": editor := core.EditorHost - return &core.PluginHostOptions{Editor: &editor} + options.Editor = &editor + case "functions": + options.MethodAuthorities[pluginhost.MethodPrefix+"functions/providers"] = core.PluginAuthorityBoth + options.MethodAuthorities[pluginhost.MethodPrefix+"functions/invoke"] = core.PluginAuthorityBoth } } - return nil + return options } diff --git a/desktop/internal/pluginbackend/pluginbackend_test.go b/desktop/internal/pluginbackend/pluginbackend_test.go index 78f3fc8910..d3bab00058 100644 --- a/desktop/internal/pluginbackend/pluginbackend_test.go +++ b/desktop/internal/pluginbackend/pluginbackend_test.go @@ -7,6 +7,7 @@ import ( "os" "path/filepath" "runtime" + "slices" "sort" "sync" "testing" @@ -560,6 +561,129 @@ func TestStartUsesLanguageServerPlanAndRole(t *testing.T) { } } +type packagedRemoteKernel struct { + fakeKernel + client *core.Client +} + +func (k *packagedRemoteKernel) PlanPluginLanguageServer(ctx context.Context, manifest json.RawMessage, language string, directories core.PluginBackendDirectories) (core.PluginBackendPlan, error) { + return k.client.PlanPluginLanguageServer(ctx, manifest, language, directories) +} + +func TestRemotePackagedLanguageServerUsesDeployedFiles(t *testing.T) { + const pluginID = "dev.lithe.test.remote-packaged" + const deployed = "/home/fixture/.lithe-server/plugin-deployments/fixture" + request := startRequest(t.TempDir()) + request.Manifest = json.RawMessage(`{ + "schemaVersion":0,"pluginAPIVersion":0,"id":"dev.lithe.test.remote-packaged","displayName":"Remote Packaged","version":"1.0.0", + "vendor":{"id":"org.example","displayName":"Example","signatureRequirement":"publisherPackage"}, + "requires":{"languages":0,"languageServers":0},"permissions":["languageServer.launch"], + "activationEvents":["onLanguage:fixture"],"languages":[{"id":"fixture","displayName":"Fixture","fileExtensions":["fixture"]}], + "languageServers":[{"languageID":"fixture","remote":"supported","launch":{"kind":"packaged","path":"bin/server"},"arguments":["${pluginDir}/lib/config.json"]}] + }`) + request.PluginID = pluginID + request.ProviderID = pluginID + "/language-server" + request.LanguageID = "fixture" + request.Architecture = "x86_64" + request.ProjectCodeAllowed = true + binding := core.NewRemoteWorkspace(request.PackageDirectory, "/home/fixture/project", nil) + binding.Attach("remote-fixture") + request.RemoteConnection = binding.CaptureConnection() + deployments := 0 + request.PrepareRemote = func(ctx context.Context, paths []string) (string, error) { + deployments++ + if core.RemoteWorkspaceOf(ctx) != binding || !slices.Equal(paths, []string{"bin/server", "lib/config.json"}) { + t.Fatalf("deployment used unexpected host or paths: %v", paths) + } + return deployed, nil + } + kernel := &packagedRemoteKernel{client: core.NewClient()} + kernel.started.SessionID = "remote-packaged-session" + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if _, err := New(kernel, nil).Start(ctx, request); err != nil { + t.Fatal(err) + } + started := kernel.started_ + if deployments != 1 || started.ExecutablePath != "" || started.RemoteExecutablePath != deployed+"/bin/server" || + !slices.Equal(started.Arguments, []string{deployed + "/lib/config.json"}) { + t.Fatalf("start did not use the deployed program and assets: deployments=%d request=%+v", deployments, started) + } +} + +func TestRemoteProviderPreparesToolsOnThePlannedAttachment(t *testing.T) { + for _, placement := range []string{"workspace", "ui"} { + t.Run(placement, func(t *testing.T) { + root := backendPackage(t) + request := startRequest(root) + request.BuildSystemID, request.Role = "provider", "build" + + workspace := core.NewRemoteWorkspace(root, "/home/fixture/project", nil) + workspace.Attach("remote-fixture") + request.RemoteConnection = workspace.CaptureConnection() + t.Cleanup(func() { workspace.Detach() }) + + plan := packagedPlan() + plan.Placement = placement + plan.BuildProvider = &core.PluginBuildProviderPlan{} + if placement == "workspace" { + plan.Launch.Kind = pluginhost.LaunchTool + plan.Launch.Tool = "fixture-runtime" + plan.Launch.Entry = "/home/fixture/deployed/server.script" + plan.Launch.MinimumVersion = "3.9" + plan.RequiredPackagePaths = []string{"server.script"} + } + request.PrepareRemote = func(ctx context.Context, paths []string) (string, error) { + if placement != "workspace" || !request.RemoteConnection.SameAttachment(workspace.CapturedConnection(ctx)) || + !slices.Equal(paths, []string{"server.script"}) { + t.Fatalf("unexpected provider deployment: %v", paths) + } + return "/home/fixture/deployed", nil + } + kernel := &fakeKernel{plan: plan, started: core.PluginBackendStarted{SessionID: "provider-session"}} + runner := New(kernel, nil) + calls := 0 + const executable = "/home/fixture/runtime/bin/interpreter" + request.PrepareRemoteTools = func(ctx context.Context) (map[string]ToolExecutable, error) { + calls++ + if !request.RemoteConnection.SameAttachment(workspace.CapturedConnection(ctx)) { + t.Fatal("runtime preparation did not capture the provider attachment") + } + return map[string]ToolExecutable{"fixture-runtime": {Path: executable, Home: "/home/fixture/runtime"}}, nil + } + runner.SetToolEntryResolver(func(ctx context.Context, _, _ string, input ToolEntryLaunch) (ToolExecutable, error) { + if !request.RemoteConnection.SameAttachment(workspace.CapturedConnection(ctx)) || + input.Executable != executable || input.MinimumVersion != "3.9" || input.Entry != plan.Launch.Entry { + t.Fatalf("runtime entry resolved with unexpected input: %+v", input) + } + return ToolExecutable{ + Path: executable, Arguments: []string{input.Entry}, + Environment: map[string]string{"FIXTURE_HOME": input.Home}, + PathPrepend: []string{"/home/fixture/runtime/bin"}, + }, nil + }) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if _, err := runner.Start(ctx, request); err != nil { + t.Fatal(err) + } + started := kernel.started_ + if placement == "ui" { + if calls != 0 || !started.UIProcess || started.RemoteExecutablePath != "" { + t.Fatalf("UI provider used the remote launch: %d preparations, %+v", calls, started) + } + return + } + if calls != 1 || started.ExecutablePath != "" || started.RemoteExecutablePath != executable || + !slices.Equal(started.Arguments, []string{plan.Launch.Entry}) || + !slices.Equal(started.RemotePathPrepend, []string{"/home/fixture/runtime/bin"}) || + started.Environment["FIXTURE_HOME"] != "/home/fixture/runtime" { + t.Fatalf("provider did not use the prepared runtime: %d preparations, %+v", calls, started) + } + }) + } +} + // A language-server start hands its attempt to Core with the start itself, so Core records // the result; a plugin backend reports its own operations and hands nothing over, and a start // that fails before Core is asked keeps the attempt for the host to record. diff --git a/desktop/internal/pluginhost/hostservices.go b/desktop/internal/pluginhost/hostservices.go index bdb8064482..cbf0e5eac8 100644 --- a/desktop/internal/pluginhost/hostservices.go +++ b/desktop/internal/pluginhost/hostservices.go @@ -8,6 +8,8 @@ import ( "sort" "sync" "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" ) // MethodPrefix is the namespace every host service method lives in. Grants in a @@ -79,7 +81,8 @@ type Handler func(ctx context.Context, params json.RawMessage) (json.RawMessage, // serviceHandler is one registered method and how its requests are bounded. type serviceHandler struct { - handler Handler + handler Handler + authority core.PluginAuthoritySupport // userChoice says the request waits for the user, so the machine deadline // does not apply to it. userChoice bool @@ -122,8 +125,8 @@ func (s *Services) GrantService(name string) error { // A method may be registered once: the contract says a later registration cannot // replace an earlier one, so a second call is an error rather than a silent // override that would change what a running backend is talking to. -func (s *Services) Register(method string, handler Handler) error { - return s.register(method, handler, false) +func (s *Services) Register(method string, handler Handler, authority ...core.PluginAuthoritySupport) error { + return s.register(method, handler, false, authority) } // RegisterUserChoice adds a handler whose requests wait for the user. @@ -132,26 +135,48 @@ func (s *Services) Register(method string, handler Handler) error { // message wait until the user answers, the request is cancelled or the session // closes. Registering such a method as a machine handler would answer it with // "cancelled" after thirty seconds. -func (s *Services) RegisterUserChoice(method string, handler Handler) error { - return s.register(method, handler, true) +func (s *Services) RegisterUserChoice(method string, handler Handler, authority ...core.PluginAuthoritySupport) error { + return s.register(method, handler, true, authority) } -func (s *Services) register(method string, handler Handler, userChoice bool) error { +func (s *Services) register(method string, handler Handler, userChoice bool, authority []core.PluginAuthoritySupport) error { if !validMethod(method) { return fmt.Errorf("%w: %q is not a host method name", ErrServiceRegistration, method) } if handler == nil { return fmt.Errorf("%w: %q has no handler", ErrServiceRegistration, method) } + support := core.PluginAuthorityLocal + if len(authority) == 1 { + support = authority[0] + } + if len(authority) > 1 || (support != core.PluginAuthorityLocal && support != core.PluginAuthorityRemote && support != core.PluginAuthorityBoth) { + return fmt.Errorf("%w: %q has invalid workspace authority support", ErrServiceRegistration, method) + } s.mu.Lock() defer s.mu.Unlock() if _, exists := s.handlers[method]; exists { return fmt.Errorf("%w: %q is already registered", ErrServiceRegistration, method) } - s.handlers[method] = serviceHandler{handler: handler, userChoice: userChoice} + s.handlers[method] = serviceHandler{handler: handler, userChoice: userChoice, authority: support} return nil } +// MethodAuthorities reports the workspace authority of every registered handler. +// Core projects these declarations onto the methods the plugin may call. +func (s *Services) MethodAuthorities() map[string]core.PluginAuthoritySupport { + if s == nil { + return nil + } + s.mu.RLock() + defer s.mu.RUnlock() + methods := make(map[string]core.PluginAuthoritySupport, len(s.handlers)) + for method, entry := range s.handlers { + methods[method] = entry.authority + } + return methods +} + // Grant reports the sorted method names this host can answer. It is what a start // request may advertise; advertising a method that is not registered would let a // backend call into a hole. diff --git a/desktop/internal/pluginhost/pluginhost.go b/desktop/internal/pluginhost/pluginhost.go index 730a38af7b..5253485e2c 100644 --- a/desktop/internal/pluginhost/pluginhost.go +++ b/desktop/internal/pluginhost/pluginhost.go @@ -194,7 +194,7 @@ 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} + declared["sourceSettings"] = []int{0, 1, 2} // Version 1 adds command-sourced discovery in the Build test tree. // Version 2 adds registry connection debugging for provider applications. declared["buildSystems"] = []int{0, 1, 2} diff --git a/desktop/internal/pluginhost/pluginhost_test.go b/desktop/internal/pluginhost/pluginhost_test.go index 3be348f645..ab51453306 100644 --- a/desktop/internal/pluginhost/pluginhost_test.go +++ b/desktop/internal/pluginhost/pluginhost_test.go @@ -69,10 +69,9 @@ func TestDeclaredServesTheBaselineOfEveryWiredCapability(t *testing.T) { } for _, name := range want { wanted := []int{0} - // The settings window renders the module sidebars, sections and entry - // lists that version 1 adds. + // Version 1 adds structured source forms. Version 2 adds remote source helpers. if name == "sourceSettings" { - wanted = []int{0, 1} + wanted = []int{0, 1, 2} } // Version 1 adds test discovery, and version 2 adds registry attach for provider applications. if name == "buildSystems" { diff --git a/desktop/internal/plugininstall/installed_snapshot.go b/desktop/internal/plugininstall/installed_snapshot.go new file mode 100644 index 0000000000..0e944574d5 --- /dev/null +++ b/desktop/internal/plugininstall/installed_snapshot.go @@ -0,0 +1,207 @@ +package plugininstall + +import ( + "context" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "encoding/json" + "errors" + "hash" + "io" + "io/fs" + "os" + "path/filepath" + "slices" + "strings" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" +) + +// ErrInstalledSeal indicates that a mutable installation cannot be reproduced as approved. +var ErrInstalledSeal = errors.New("installed plugin files differ from the approved package") + +func newTreeSeal() hash.Hash { + seal := sha256.New() + seal.Write([]byte("lithe-installed-plugin-tree-v1\x00")) + return seal +} + +func addTreeFile(seal hash.Hash, file pluginpkg.File) { + seal.Write([]byte(file.Path)) + seal.Write([]byte{0, byte(file.Mode.Perm() & 0o100)}) + seal.Write(binary.BigEndian.AppendUint64(nil, uint64(file.Size))) +} + +// digestExtractedTree retains the previous content digest for approval reuse +// and seals the file sizes and executable permissions in the same read pass. +func digestExtractedTree(ctx context.Context, directory string, files []pluginpkg.File) (string, string, error) { + legacy := sha256.New() + seal := newTreeSeal() + for _, entry := range files { + legacy.Write([]byte(entry.Path)) + legacy.Write([]byte{0}) + addTreeFile(seal, entry) + file, err := os.Open(filepath.Join(directory, filepath.FromSlash(entry.Path))) + if err != nil { + return "", "", err + } + err = copySealedFile(ctx, io.MultiWriter(legacy, seal), file, entry.Size) + if err := errors.Join(err, file.Close()); err != nil { + return "", "", err + } + legacy.Write([]byte{0}) + } + return hex.EncodeToString(legacy.Sum(nil)), hex.EncodeToString(seal.Sum(nil)), nil +} + +// SnapshotInstalledVariant copies a same-platform installation into a private +// directory. The seal is computed over the bytes written there, and the staged +// manifest is reviewed before any of those bytes can reach the workspace host. +func SnapshotInstalledVariant(ctx context.Context, installed, want string, review core.MarketplaceVariantReview, verify func(context.Context, core.MarketplaceVariantReview) (json.RawMessage, error)) (result RemoteVariant, err error) { + var staging string + defer func() { + if err != nil && staging != "" { + result = RemoteVariant{} + err = errors.Join(err, os.RemoveAll(staging)) + } + }() + root, err := os.OpenRoot(installed) + if err != nil { + return RemoteVariant{}, err + } + defer func() { err = errors.Join(err, root.Close()) }() + files, err := inventoryInstalledFiles(ctx, root) + if err != nil { + return RemoteVariant{}, err + } + staging, err = os.MkdirTemp("", "lithe-remote-installed-") + if err != nil { + return RemoteVariant{}, err + } + seal := newTreeSeal() + inventory := make([]pluginpkg.File, 0, len(files)) + for _, file := range files { + entry := pluginpkg.File{Path: file.path, Size: file.info.Size(), Mode: file.info.Mode()} + addTreeFile(seal, entry) + if err := writeSnapshotFile(ctx, root, staging, file, seal); err != nil { + return RemoteVariant{}, err + } + inventory = append(inventory, entry) + } + if want != hex.EncodeToString(seal.Sum(nil)) { + return RemoteVariant{}, ErrInstalledSeal + } + review.VariantManifest, err = readManifest(staging) + if err != nil { + return RemoteVariant{}, err + } + manifest, err := verify(ctx, review) + if err != nil { + return RemoteVariant{}, err + } + return RemoteVariant{Directory: staging, Manifest: manifest, Files: inventory}, nil +} + +type installedFile struct { + path string + info fs.FileInfo +} + +func inventoryInstalledFiles(ctx context.Context, root *os.Root) ([]installedFile, error) { + var files []installedFile + var total int64 + var entries int + err := fs.WalkDir(root.FS(), ".", func(path string, entry fs.DirEntry, err error) error { + if err != nil { + return err + } + if err := ctx.Err(); err != nil { + return err + } + if path == "." { + return nil + } + entries++ + if entries > pluginpkg.MaxEntries { + return pluginpkg.ErrTooManyEntries + } + if _, err := pluginpkg.ValidatePath(path); err != nil { + return err + } + if entry.IsDir() { + return nil + } + info, err := entry.Info() + if err != nil { + return err + } + if !info.Mode().IsRegular() { + return pluginpkg.ErrNotPackageFile + } + if info.Size() > pluginpkg.MaxFileBytes { + return pluginpkg.ErrFileTooLarge + } + total += info.Size() + if total > pluginpkg.MaxExtractedBytes { + return pluginpkg.ErrArchiveTooLarge + } + files = append(files, installedFile{path, info}) + return nil + }) + slices.SortFunc(files, func(a, b installedFile) int { return strings.Compare(a.path, b.path) }) + return files, err +} + +func writeSnapshotFile(ctx context.Context, root *os.Root, staging string, file installedFile, seal hash.Hash) (err error) { + if err := ctx.Err(); err != nil { + return err + } + source, err := root.OpenFile(file.path, snapshotReadFlags, 0) + if err != nil { + return err + } + defer func() { err = errors.Join(err, source.Close()) }() + opened, err := source.Stat() + if err != nil { + return err + } + if !os.SameFile(file.info, opened) || !opened.Mode().IsRegular() || + file.info.Size() != opened.Size() || file.info.Mode()&0o100 != opened.Mode()&0o100 { + return ErrInstalledSeal + } + path := filepath.Join(staging, filepath.FromSlash(file.path)) + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + target, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) + if err != nil { + return err + } + writeErr := copySealedFile(ctx, io.MultiWriter(target, seal), source, opened.Size()) + return errors.Join(writeErr, target.Close()) +} + +func copySealedFile(ctx context.Context, target io.Writer, source *os.File, size int64) error { + read, err := io.Copy(target, io.LimitReader(sealReader{ctx, source}, size+1)) + if err != nil { + return err + } + if read != size { + return ErrInstalledSeal + } + return ctx.Err() +} + +type sealReader struct { + ctx context.Context + source *os.File +} + +func (r sealReader) Read(buffer []byte) (int, error) { + if err := r.ctx.Err(); err != nil { + return 0, err + } + return r.source.Read(buffer) +} diff --git a/desktop/internal/plugininstall/installed_snapshot_other.go b/desktop/internal/plugininstall/installed_snapshot_other.go new file mode 100644 index 0000000000..9b6da4cc44 --- /dev/null +++ b/desktop/internal/plugininstall/installed_snapshot_other.go @@ -0,0 +1,7 @@ +//go:build !unix + +package plugininstall + +import "os" + +const snapshotReadFlags = os.O_RDONLY diff --git a/desktop/internal/plugininstall/installed_snapshot_unix.go b/desktop/internal/plugininstall/installed_snapshot_unix.go new file mode 100644 index 0000000000..beb7b7e8bd --- /dev/null +++ b/desktop/internal/plugininstall/installed_snapshot_unix.go @@ -0,0 +1,8 @@ +//go:build unix + +package plugininstall + +import "syscall" + +// A replaced package entry must never block an open if it became a FIFO. +const snapshotReadFlags = syscall.O_RDONLY | syscall.O_NONBLOCK | syscall.O_NOFOLLOW diff --git a/desktop/internal/plugininstall/plugininstall.go b/desktop/internal/plugininstall/plugininstall.go index 98d3035746..e8729d0c32 100644 --- a/desktop/internal/plugininstall/plugininstall.go +++ b/desktop/internal/plugininstall/plugininstall.go @@ -73,7 +73,8 @@ type Request struct { // ArchiveSHA256 is the digest the download layer verified against the index. ArchiveSHA256 string // MarketplaceIndexURL is the Core-canonical index URL that offered this archive. - MarketplaceIndexURL string + MarketplaceIndexURL string + MarketplaceRepository string // ExpectedID and ExpectedVersion pin the marketplace entry this archive is // supposed to be. They are empty for a package the user picked themselves. ExpectedID string @@ -91,15 +92,18 @@ type Plan struct { Manifest json.RawMessage // ContentDigest is the digest of the extracted tree. ContentDigest string + // SealedTreeSHA256 binds file names, sizes, contents, and owner execute bits. + SealedTreeSHA256 string // Review is Core's install review, ready to show to the user. Review plugintrust.Review // Decision says whether an earlier approval covers this package. Decision plugintrust.Decision // Source, ArchiveSHA256 and Root repeat the request for Commit. - Source plugintrust.Source - ArchiveSHA256 string - MarketplaceIndexURL string - Root string + Source plugintrust.Source + ArchiveSHA256 string + MarketplaceIndexURL string + MarketplaceRepository string + Root string } // NeedsApproval reports that the user has to confirm the review before Commit. @@ -153,7 +157,7 @@ func (s *Service) Prepare(ctx context.Context, request Request) (plan Plan, err err = errors.Join(err, os.RemoveAll(staging)) } }() - extracted, err := extractVerified(ctx, request, staging) + extracted, err := extractVerified(ctx, request.ArchivePath, request.ArchiveSHA256, staging) if err != nil { return Plan{}, err } @@ -172,7 +176,7 @@ func (s *Service) Prepare(ctx context.Context, request Request) (plan Plan, err if err := checkContentRoot(extracted.ContentRoot, identity.ID); err != nil { return Plan{}, err } - digest, err := ContentDigest(staging, extracted.Files) + digest, seal, err := digestExtractedTree(ctx, staging, extracted.Files) if err != nil { return Plan{}, err } @@ -187,24 +191,27 @@ func (s *Service) Prepare(ctx context.Context, request Request) (plan Plan, err return Plan{}, err } decision := plugintrust.Decide(record, found, plugintrust.Request{ - Source: request.Source, - ArchiveSHA256: request.ArchiveSHA256, - MarketplaceIndexURL: request.MarketplaceIndexURL, - ContentDigest: digest, - Review: review, + Source: request.Source, + ArchiveSHA256: request.ArchiveSHA256, + MarketplaceIndexURL: request.MarketplaceIndexURL, + MarketplaceRepository: request.MarketplaceRepository, + ContentDigest: digest, + Review: review, }) return Plan{ - Staging: staging, - ID: identity.ID, - Version: identity.Version, - Manifest: normalised, - ContentDigest: digest, - Review: review, - Decision: decision, - Source: request.Source, - ArchiveSHA256: request.ArchiveSHA256, - MarketplaceIndexURL: request.MarketplaceIndexURL, - Root: request.Root, + Staging: staging, + ID: identity.ID, + Version: identity.Version, + Manifest: normalised, + ContentDigest: digest, + SealedTreeSHA256: seal, + Review: review, + Decision: decision, + Source: request.Source, + ArchiveSHA256: request.ArchiveSHA256, + MarketplaceIndexURL: request.MarketplaceIndexURL, + MarketplaceRepository: request.MarketplaceRepository, + Root: request.Root, }, nil } @@ -222,11 +229,13 @@ func (s *Service) Commit(plan Plan) (pluginpkg.Installed, error) { return pluginpkg.Installed{}, err } record := plugintrust.RecordFor(plan.ID, plan.Version, plugintrust.Request{ - Source: plan.Source, - ArchiveSHA256: plan.ArchiveSHA256, - MarketplaceIndexURL: plan.MarketplaceIndexURL, - ContentDigest: plan.ContentDigest, - Review: plan.Review, + Source: plan.Source, + ArchiveSHA256: plan.ArchiveSHA256, + MarketplaceIndexURL: plan.MarketplaceIndexURL, + MarketplaceRepository: plan.MarketplaceRepository, + ContentDigest: plan.ContentDigest, + SealedTreeSHA256: plan.SealedTreeSHA256, + Review: plan.Review, }) if err := s.approvals.Approve(record); err != nil { return installed, &ApprovalError{Installed: installed, Err: err} @@ -249,27 +258,8 @@ func (s *Service) Discard(plan Plan) error { // The path order comes from Extract, so the same package always digests the same // way. func ContentDigest(directory string, files []pluginpkg.File) (string, error) { - hash := sha256.New() - for _, file := range files { - hash.Write([]byte(file.Path)) - hash.Write([]byte{0}) - if err := hashPath(hash, filepath.Join(directory, filepath.FromSlash(file.Path))); err != nil { - return "", err - } - hash.Write([]byte{0}) - } - return hex.EncodeToString(hash.Sum(nil)), nil -} - -// hashPath streams one file into writer. -func hashPath(writer io.Writer, path string) error { - file, err := os.Open(path) - if err != nil { - return err - } - copyErr := hashFile(writer, file) - closeErr := file.Close() - return errors.Join(copyErr, closeErr) + digest, _, err := digestExtractedTree(context.Background(), directory, files) + return digest, err } func hashFile(writer io.Writer, source io.Reader) error { @@ -289,11 +279,11 @@ func hashFile(writer io.Writer, source io.Reader) error { // The download layer checked the digest of the bytes it received. Hashing a path // and then opening it again would leave a window in which the file is replaced, // so the check and the extraction share one open file. -func extractVerified(ctx context.Context, request Request, staging string) (pluginpkg.Package, error) { +func extractVerified(ctx context.Context, archivePath, archiveSHA256, staging string) (pluginpkg.Package, error) { if err := ctx.Err(); err != nil { return pluginpkg.Package{}, err } - file, err := os.Open(request.ArchivePath) + file, err := os.Open(archivePath) if err != nil { return pluginpkg.Package{}, err } @@ -304,10 +294,10 @@ func extractVerified(ctx context.Context, request Request, staging string) (plug } if !info.Mode().IsRegular() { // A named pipe or a directory would block or read something else. - return pluginpkg.Package{}, fmt.Errorf("%w: %s is not a regular file", ErrArchiveDigest, request.ArchivePath) + return pluginpkg.Package{}, fmt.Errorf("%w: %s is not a regular file", ErrArchiveDigest, archivePath) } - if request.ArchiveSHA256 != "" { - if err := verifyDigest(file, request.ArchivePath, request.ArchiveSHA256); err != nil { + if archiveSHA256 != "" { + if err := verifyDigest(file, archivePath, archiveSHA256); err != nil { return pluginpkg.Package{}, err } if _, err := file.Seek(0, io.SeekStart); err != nil { diff --git a/desktop/internal/plugininstall/plugininstall_test.go b/desktop/internal/plugininstall/plugininstall_test.go index 7fdd410b55..50625c94a8 100644 --- a/desktop/internal/plugininstall/plugininstall_test.go +++ b/desktop/internal/plugininstall/plugininstall_test.go @@ -9,8 +9,11 @@ import ( "errors" "os" "path/filepath" + "runtime" "testing" + "time" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" "github.com/1lck/Lithe-IDEA/desktop/internal/plugintrust" @@ -504,11 +507,71 @@ func TestCommitInstallsAndRecordsTheApproval(t *testing.T) { if err != nil || !found { t.Fatalf("record: %v, found = %v", err, found) } - if record.ContentDigest != plan.ContentDigest || record.ArchiveSHA256 != digest { + if record.ContentDigest != plan.ContentDigest || record.ArchiveSHA256 != digest || + record.SealedTreeSHA256 == "" || record.SealedTreeSHA256 != plan.SealedTreeSHA256 { t.Fatalf("record = %+v", record) } } +func TestSamePlatformSnapshotVerifiesInstalledBytesAndModes(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + service, _, root := newService(t, &fakeValidator{}, sampleReviewer()) + archive := writeArchive(t, sampleManifest, map[string]string{"lib/a.txt": "code", "lib-extra.txt": "keep"}) + plan, err := service.Prepare(ctx, Request{ArchivePath: archive, Root: root, Source: plugintrust.Disk}) + if err != nil { + t.Fatal(err) + } + installed, err := service.Commit(plan) + if err != nil { + t.Fatal(err) + } + reviewCalls := 0 + review := func(_ context.Context, request core.MarketplaceVariantReview) (json.RawMessage, error) { + reviewCalls++ + if string(request.VariantManifest) != sampleManifest { + t.Fatalf("reviewed manifest = %q", request.VariantManifest) + } + return request.VariantManifest, nil + } + snapshot := func() (RemoteVariant, error) { + return SnapshotInstalledVariant(ctx, installed.Path, plan.SealedTreeSHA256, core.MarketplaceVariantReview{}, review) + } + first, err := snapshot() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := os.RemoveAll(first.Directory); err != nil { + t.Error(err) + } + }) + current := filepath.Join(installed.Path, "lib", "a.txt") + if runtime.GOOS != "windows" { + if err := os.Chmod(current, 0o755); err != nil { + t.Fatal(err) + } + if _, err := snapshot(); !errors.Is(err, ErrInstalledSeal) { + t.Fatalf("changed execute bit was accepted: %v", err) + } + if err := os.Chmod(current, 0o644); err != nil { + t.Fatal(err) + } + } + // Even a same-size edit must invalidate the approval and leave earlier + // snapshots independent of the mutable installation. + if err := os.WriteFile(current, []byte("edit"), 0o644); err != nil { + t.Fatal(err) + } + if _, err := snapshot(); !errors.Is(err, ErrInstalledSeal) { + t.Fatalf("changed installation was accepted: %v", err) + } + bytes, err := os.ReadFile(filepath.Join(first.Directory, "lib", "a.txt")) + if err != nil || string(bytes) != "code" || reviewCalls != 1 { + t.Fatalf("snapshot = %q, error = %v, reviews = %d", bytes, err, reviewCalls) + } +} + func TestPrepareStopsWhenCancelled(t *testing.T) { service, _, root := newService(t, &fakeValidator{}, sampleReviewer()) archive := writeArchive(t, sampleManifest, nil) diff --git a/desktop/internal/plugininstall/remote_variant.go b/desktop/internal/plugininstall/remote_variant.go new file mode 100644 index 0000000000..42c14efef6 --- /dev/null +++ b/desktop/internal/plugininstall/remote_variant.go @@ -0,0 +1,51 @@ +package plugininstall + +import ( + "context" + "encoding/json" + "errors" + "os" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" +) + +// RemoteVariant owns a private snapshot of a reviewed plugin package. +type RemoteVariant struct { + Directory string + Manifest json.RawMessage + Files []pluginpkg.File +} + +// ExtractRemoteVariant binds the manifest check to the same archive handle +// used to verify the marketplace digest. The caller owns the resulting directory. +func ExtractRemoteVariant(ctx context.Context, archivePath, sha256, stagingRoot string, review core.MarketplaceVariantReview, verify func(context.Context, core.MarketplaceVariantReview) (json.RawMessage, error)) (_ RemoteVariant, err error) { + if sha256 == "" { + return RemoteVariant{}, ErrArchiveDigest + } + staging, err := os.MkdirTemp(stagingRoot, "lithe-remote-variant-") + if err != nil { + return RemoteVariant{}, err + } + defer func() { + if err != nil { + err = errors.Join(err, os.RemoveAll(staging)) + } + }() + extracted, err := extractVerified(ctx, archivePath, sha256, staging) + if err != nil { + return RemoteVariant{}, err + } + if err := checkContentRoot(extracted.ContentRoot, review.PluginID); err != nil { + return RemoteVariant{}, err + } + review.VariantManifest, err = readManifest(staging) + if err != nil { + return RemoteVariant{}, err + } + manifest, err := verify(ctx, review) + if err != nil { + return RemoteVariant{}, err + } + return RemoteVariant{Directory: staging, Manifest: manifest, Files: extracted.Files}, nil +} diff --git a/desktop/internal/pluginruntime/mirrors.go b/desktop/internal/pluginruntime/mirrors.go index 1b925bcc1a..d91ae364c0 100644 --- a/desktop/internal/pluginruntime/mirrors.go +++ b/desktop/internal/pluginruntime/mirrors.go @@ -46,7 +46,8 @@ func candidateURLs(artifact Artifact) []string { return urls } -func (m *Manager) downloadArchive(ctx context.Context, artifact Artifact, progress func(Progress)) (*marketplace.DownloadedArchive, func() error, error) { +// DownloadArchive downloads and verifies an artifact and returns cleanup for its private scratch. +func (m *Manager) DownloadArchive(ctx context.Context, artifact Artifact, progress func(Progress)) (*marketplace.DownloadedArchive, func() error, error) { urls := candidateURLs(artifact) if len(urls) == 0 { return nil, nil, ErrArtifact diff --git a/desktop/internal/pluginruntime/runtime.go b/desktop/internal/pluginruntime/runtime.go index d4fb9a6c38..c5f7ae30ac 100644 --- a/desktop/internal/pluginruntime/runtime.go +++ b/desktop/internal/pluginruntime/runtime.go @@ -15,8 +15,10 @@ import ( "os" "path/filepath" "strings" + "time" "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "github.com/1lck/Lithe-IDEA/desktop/internal/filelock" "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" ) @@ -169,8 +171,17 @@ func (m *Manager) Prepare(ctx context.Context, artifact Artifact, validate func( if err != nil { return result, err } - unlock, err := acquire(ctx, filepath.Join(base, ".lock")) + lockCtx, cancelLock := context.WithTimeoutCause(ctx, 5*time.Minute, ErrBusy) + unlock, err := filelock.Acquire(lockCtx, filepath.Join(base, ".lock")) + lockCause := context.Cause(lockCtx) + cancelLock() if err != nil { + if errors.Is(lockCause, ErrBusy) && errors.Is(err, context.DeadlineExceeded) { + err = errors.Join(ErrBusy, err) + } + if errors.Is(err, filelock.ErrInvalidFile) { + err = errors.Join(ErrArtifact, err) + } return result, err } defer func() { err = errors.Join(err, unlock()) }() @@ -373,7 +384,7 @@ func (m *Manager) archive(ctx context.Context, artifact Artifact, base string, p if progress != nil && errors.Is(checkErr, ErrCorrupt) { progress(Progress{ID: artifact.ID, Phase: "repairing", Total: -1, Cause: checkErr}) } - download, cleanup, err := m.downloadArchive(ctx, artifact, progress) + download, cleanup, err := m.DownloadArchive(ctx, artifact, progress) if err != nil { return nil, err } diff --git a/desktop/internal/pluginservice/activation.go b/desktop/internal/pluginservice/activation.go index ca7fecb660..a41721d2af 100644 --- a/desktop/internal/pluginservice/activation.go +++ b/desktop/internal/pluginservice/activation.go @@ -59,7 +59,7 @@ func (s *Service) SyncFunctionRelay(ctx context.Context, entries []pluginmanager _, workspaces := s.Contexts.List() contexts := make([]core.RelayContext, 0, len(workspaces)) for _, workspace := range workspaces { - contexts = append(contexts, core.RelayContext{ContextID: workspace.ContextID, Generation: workspace.Generation, Authority: "local"}) + contexts = append(contexts, core.RelayContext{ContextID: workspace.ContextID, Generation: workspace.Generation, Authority: workspace.authorityKind()}) } if err := s.kernel.ConfigureFunctionRelay(ctx, plugins, contexts); err != nil { failures = append(failures, err) diff --git a/desktop/internal/pluginservice/backendhost.go b/desktop/internal/pluginservice/backendhost.go index 9056daf601..eb88b0be15 100644 --- a/desktop/internal/pluginservice/backendhost.go +++ b/desktop/internal/pluginservice/backendhost.go @@ -346,16 +346,21 @@ func (h *BackendHost) DetachAll() func() { // Notify sends a host notification to a running backend that holds the grant. // A backend that is not running or not granted never sees it. func (h *BackendHost) Notify(ctx context.Context, pluginID, grant, method string, params json.RawMessage) { - session := h.Running(pluginID) - if session == nil || !session.granted(grant) { + if session := h.Running(pluginID); session != nil { + session.notify(ctx, grant, method, params) + } +} + +func (b *BackendSession) notify(ctx context.Context, grant, method string, params json.RawMessage) { + if !b.granted(grant) { return } // A notification may arrive before initialize completes; it is dropped then, // because a backend that starts later reads the state itself. - if !session.isReady() { + if !b.isReady() { return } - _, _ = h.service.kernel.SendPluginHostNotification(ctx, session.Session.ID, method, params) + _, _ = b.host.service.kernel.SendPluginHostNotification(ctx, b.Session.ID, method, params) } // NotifyAll sends a host notification to every running backend that holds the grant. diff --git a/desktop/internal/pluginservice/backendlaunch.go b/desktop/internal/pluginservice/backendlaunch.go index cbccc770ea..97c2595c63 100644 --- a/desktop/internal/pluginservice/backendlaunch.go +++ b/desktop/internal/pluginservice/backendlaunch.go @@ -29,34 +29,37 @@ type backendLaunch struct { // system temporary directory. Nothing is derived from the installed // package or the application bundle, which stay read-only so the next // differential update still matches what the user installed. -func (s *Service) resolveBackendLaunch(ctx context.Context, pluginID, version string, manifest json.RawMessage, languageID string, workspace WorkspaceContext, start pluginbackend.StartRequest, runtimes RuntimeEnvironment) (backendLaunch, error) { +func (s *Service) resolveBackendLaunch(ctx context.Context, pluginID, version string, manifest json.RawMessage, languageID string, workspace WorkspaceContext, start pluginbackend.StartRequest, runtimes RuntimeEnvironment, uiProcess bool) (backendLaunch, error) { if workspace.ContextID == "" { return backendLaunch{}, fmt.Errorf("%w: a backend-resolved server needs an open workspace", pluginbackend.ErrRequest) } - base := pluginpkg.StateRoot(s.Root, pluginID) - temporary, err := os.MkdirTemp("", "lithe-server-") - if err != nil { - return backendLaunch{}, err - } - directories := pluginDirectories{ - state: start.StateDirectory, - workspaceState: filepath.Join(base, "servers", languageID, "workspaces", WorkspaceKey(workspace.Path)), - log: start.LogDirectory, - temporary: temporary, - } + var directories pluginDirectories fail := func(err error) (backendLaunch, error) { - removeTemporary(temporary) + removeTemporary(directories.temporary) return backendLaunch{}, err } - if err := directories.create(); err != nil { - return fail(err) + remote := start.RemoteConnection + if uiProcess { + base := pluginpkg.StateRoot(s.Root, pluginID) + temporary, err := os.MkdirTemp("", "lithe-server-") + if err != nil { + return backendLaunch{}, err + } + directories = pluginDirectories{ + state: start.StateDirectory, + workspaceState: filepath.Join(base, "servers", languageID, "workspaces", WorkspaceKey(workspace.Path)), + log: start.LogDirectory, + temporary: temporary, + } + if err := directories.create(); err != nil { + return fail(err) + } + // Retention distinguishes open workspaces from abandoned ones by this time. + now := time.Now() + _ = os.Chtimes(directories.workspaceState, now, now) } - // The host refreshes the directory's time on each start so retention can tell - // open workspaces from abandoned ones. - now := time.Now() - _ = os.Chtimes(directories.workspaceState, now, now) request := core.PluginBackendDirectories{ - PluginDirectory: start.PackageDirectory, + RemoteWorkspace: remote != nil, StateDirectory: directories.state, WorkspaceStateDirectory: directories.workspaceState, LogDirectory: directories.log, @@ -66,6 +69,9 @@ func (s *Service) resolveBackendLaunch(ctx context.Context, pluginID, version st ProjectSettings: start.ProjectSettings, ProjectCodeAllowed: start.ProjectCodeAllowed, } + if uiProcess { + request.PluginDirectory = start.PackageDirectory + } plan, err := s.kernel.PlanPluginLanguageServer(ctx, manifest, languageID, request) if err != nil { return fail(err) @@ -75,7 +81,14 @@ func (s *Service) resolveBackendLaunch(ctx context.Context, pluginID, version st } // The function's params are the plan's resolveParams themselves, as the // contract says: serverID, platform, the four directories and the settings. - params, err := s.languageLaunchParamsWithRuntimes(ctx, workspace.Path, manifest, plan.ResolveParams, runtimes) + toolCtx := ctx + toolRoot := workspace.Path + if remote != nil && !uiProcess { + toolCtx = remote.Context(ctx) + } else if remote != nil { + toolRoot = start.StateDirectory + } + params, err := s.languageLaunchParamsWithRuntimes(toolCtx, toolRoot, manifest, plan.ResolveParams, runtimes) if err != nil { return fail(err) } diff --git a/desktop/internal/pluginservice/backends.go b/desktop/internal/pluginservice/backends.go index a1f4f565c6..bc1147b9ff 100644 --- a/desktop/internal/pluginservice/backends.go +++ b/desktop/internal/pluginservice/backends.go @@ -27,6 +27,8 @@ type BackendRequest struct { Context ContextRef // Architecture is the platform architecture Core plans for. Architecture string + // RemoteConnection is the attachment captured by the window for this start. + RemoteConnection *core.RemoteWorkspaceConnection // ProjectCodeAllowed is whether the user trusts the workspace. Without it Core plans no // language server that would run project code, and the start fails with // core.LaunchUntrustedWorkspace. @@ -47,6 +49,7 @@ type LanguageSession struct { Warnings error manifest json.RawMessage workspace string + remote *core.RemoteWorkspaceConnection // Session is Core's session. Session pluginbackend.Session // Documents keeps the session's open documents in step with the editor. @@ -64,12 +67,18 @@ type LanguageSession struct { languageSessionState } +// ServesAttachment reports whether the server belongs to this exact workspace connection. +func (s *LanguageSession) ServesAttachment(connection *core.RemoteWorkspaceConnection) bool { + return (s.remote == nil && connection == nil) || s.remote.SameAttachment(connection) +} + // StartLanguageServer starts the language server of the plugin that serves // languageID, if an enabled plugin declares one. // // It returns a nil session and no error when nothing serves the language: that is // the ordinary case for most files, not a failure. func (s *Service) StartLanguageServer(ctx context.Context, entries []pluginmanager.Entry, languageID string, request BackendRequest) (*LanguageSession, error) { + ctx = core.WithoutRemoteWorkspace(ctx) entry, ok, err := s.LanguageServerProvider(ctx, entries, languageID) if !ok { return nil, err @@ -96,11 +105,40 @@ func (s *Service) StartLanguageServer(ctx context.Context, entries []pluginmanag if contextErr != nil { return fail(contextErr) } - settings, settingsErr := s.Settings.Load(ctx, manifest, request.WorkingDirectory) + settings, settingsErr := s.ReadWorkspacePluginSettings(ctx, manifest, request.WorkingDirectory, request.RemoteConnection) if settingsErr != nil { return fail(settingsErr) } - runtimes, runtimeErr := s.EnsureRuntimesWithSettings(ctx, manifest, entry.Installed.Path, entry.Installed.ID, entry.Installed.Version, false, settings.State, request.RuntimeProgress) + var runtimes RuntimeEnvironment + var workspacePlan *core.PluginBackendPlan + uiProcess := request.RemoteConnection == nil + if request.RemoteConnection != nil { + request.Architecture = workspaceContext.remote.platform.Arch + plan, planErr := s.kernel.PlanPluginLanguageServer(ctx, manifest, languageID, core.PluginBackendDirectories{ + Architecture: request.Architecture, + RemoteWorkspace: true, + ProbeLocalPlacement: true, + Settings: settings.Settings, + ProjectSettings: settings.ProjectSettings, + ProjectCodeAllowed: request.ProjectCodeAllowed, + }) + if planErr != nil { + if core.IsLaunchRemoteUnsupported(planErr) { + return nil, err + } + return fail(planErr) + } + uiProcess = plan.Placement == "ui" + if !uiProcess && plan.Launch.Kind != "backend" { + workspacePlan = &plan + } + } + var runtimeErr error + if uiProcess { + runtimes, runtimeErr = s.EnsureRuntimesWithSettings(ctx, manifest, entry.Installed.Path, entry.Installed.ID, entry.Installed.Version, false, settings, request.RuntimeProgress) + } else { + runtimes, runtimeErr = s.prepareRemoteRuntimes(ctx, entry.Installed, manifest, request.RemoteConnection, workspaceContext.HostPlatform(), request.RuntimeProgress) + } if runtimeErr != nil { return fail(runtimeErr) } @@ -116,9 +154,6 @@ func (s *Service) StartLanguageServer(ctx context.Context, entries []pluginmanag // package is read-only for the host, and a version directory that changed // would no longer match the digest the user approved. stateDirectory := pluginpkg.VersionStateRoot(s.Root, entry.Installed.ID, entry.Installed.Version) - if stateErr := os.MkdirAll(stateDirectory, 0o700); stateErr != nil { - return fail(stateErr) - } start := pluginbackend.StartRequest{ Manifest: manifest, PackageDirectory: entry.Installed.Path, @@ -127,19 +162,32 @@ func (s *Service) StartLanguageServer(ctx context.Context, entries []pluginmanag LanguageID: languageID, Attempt: attempt, StateDirectory: stateDirectory, - LogDirectory: s.logDirectory(ctx, entry.Installed.ID), Architecture: request.Architecture, - Settings: settings.State.Settings, - ProjectSettings: settings.State.ProjectSettings, + RemoteConnection: request.RemoteConnection, + Settings: settings.Settings, + ProjectSettings: settings.ProjectSettings, RootURI: request.RootURI, WorkingDirectory: request.WorkingDirectory, ManagedTools: runtimes.Tools, ProjectCodeAllowed: request.ProjectCodeAllowed, + Plan: workspacePlan, + } + if uiProcess { + if stateErr := os.MkdirAll(stateDirectory, 0o700); stateErr != nil { + return fail(stateErr) + } + start.LogDirectory = s.logDirectory(ctx, entry.Installed.ID) + } else { + start.ManagedToolConnection = request.RemoteConnection + start.PrepareRemote = s.RemoteDeployment(entry.Installed, manifest, workspaceContext.HostPlatform(), request.RuntimeProgress) } temporary := "" if declaresBackendLaunch(manifest, languageID) { - resolved, resolveErr := s.resolveBackendLaunch(ctx, entry.Installed.ID, entry.Installed.Version, manifest, languageID, workspaceContext, start, runtimes) + resolved, resolveErr := s.resolveBackendLaunch(ctx, entry.Installed.ID, entry.Installed.Version, manifest, languageID, workspaceContext, start, runtimes, uiProcess) if resolveErr != nil { + if core.IsLaunchRemoteUnsupported(resolveErr) { + return nil, err + } return fail(resolveErr) } start.Plan = resolved.plan @@ -153,6 +201,9 @@ func (s *Service) StartLanguageServer(ctx context.Context, entries []pluginmanag started, startErr := s.Backend.Start(ctx, start) if startErr != nil { removeTemporary(temporary) + if core.IsLaunchRemoteUnsupported(startErr) { + return nil, err + } return fail(startErr) } if _, contextErr := s.workspaceForBackend(ctx, request); contextErr != nil { @@ -175,6 +226,7 @@ func (s *Service) StartLanguageServer(ctx context.Context, entries []pluginmanag Warnings: err, manifest: append(json.RawMessage(nil), manifest...), workspace: request.WorkingDirectory, + remote: request.RemoteConnection, Session: started, Documents: pluginlsp.New(s.kernel, started.ID), ContextID: workspaceContext.ContextID, @@ -199,6 +251,14 @@ func (s *Service) workspaceForBackend(ctx context.Context, request BackendReques if filepath.Clean(workspace.Path) != filepath.Clean(request.WorkingDirectory) { return WorkspaceContext{}, ErrContextExpired } + if workspace.remote.binding != nil { + remote := request.RemoteConnection + if !remote.IsCurrent() || core.RemoteWorkspaceOf(remote.Context(ctx)) != workspace.remote.binding { + return WorkspaceContext{}, &core.Error{Code: core.CodeConnectionClosed, Message: "The workspace connection changed."} + } + } else if request.RemoteConnection != nil { + return WorkspaceContext{}, ErrContextExpired + } return workspace, nil } diff --git a/desktop/internal/pluginservice/contexts.go b/desktop/internal/pluginservice/contexts.go index b14720348e..174e375175 100644 --- a/desktop/internal/pluginservice/contexts.go +++ b/desktop/internal/pluginservice/contexts.go @@ -1,6 +1,7 @@ package pluginservice import ( + "context" "crypto/hmac" "crypto/rand" "crypto/sha256" @@ -10,6 +11,8 @@ import ( "path/filepath" "sort" "sync" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" ) // ErrContextExpired reports a workspace context that is closed or whose @@ -27,8 +30,30 @@ type WorkspaceContext struct { ContextRef // Name is the workspace's display name. Name string - // Path is the local root folder. - Path string + // Path identifies the workspace on the client. For a remote context it is an + // opaque placeholder used by the workbench and state store. + Path string + remote remoteWorkspaceContext + codeAllowed func() bool + lifetime context.Context + cancel context.CancelFunc +} + +type remoteWorkspaceContext struct { + connectionID string + hostPath string + platform core.RemotePlatform + binding *core.RemoteWorkspace +} + +// HostPlatform is the connected host's platform, or zero for a local workspace. +func (w WorkspaceContext) HostPlatform() core.RemotePlatform { return w.remote.platform } + +func (w WorkspaceContext) authorityKind() string { + if w.remote.connectionID != "" { + return "remote" + } + return "local" } // WorkspaceContexts keeps the contexts plugin backends see. @@ -45,8 +70,8 @@ type WorkspaceContexts struct { // stateRoot holds the plugin storage; per-workspace state lives below it. stateRoot string onChange func() - // onClosed hears the ID of every context that ends, so what was made for it can go too. - onClosed func(contextID string) + // onClosed releases resources belonging to the generation that ended. + onClosed func(ContextRef) } // Contexts remain private to a workbench. Native runtime checks only need the @@ -127,9 +152,9 @@ func (c *WorkspaceContexts) SetObserver(onChange func()) { c.mu.Unlock() } -// SetClosedObserver installs the function called with the ID of each context that -// closes. It runs without the lock held. -func (c *WorkspaceContexts) SetClosedObserver(onClosed func(contextID string)) { +// SetClosedObserver installs the function called when a context closes or is +// replaced. It runs without the lock held. +func (c *WorkspaceContexts) SetClosedObserver(onClosed func(ContextRef)) { c.mu.Lock() c.onClosed = onClosed c.mu.Unlock() @@ -139,29 +164,63 @@ func (c *WorkspaceContexts) SetClosedObserver(onClosed func(contextID string)) { // is not open yet. func (c *WorkspaceContexts) Open(path string) WorkspaceContext { path = filepath.Clean(path) + return c.open(WorkspaceContext{Path: path, Name: filepath.Base(path)}) +} + +// OpenRemote updates the host metadata without adding its placeholder to native tool discovery. +// Reconnecting to the same authority preserves the context reference. +func (c *WorkspaceContexts) OpenRemote(binding *core.RemoteWorkspace, name, connectionID string, platform core.RemotePlatform, codeAllowed func() bool) WorkspaceContext { + return c.open(WorkspaceContext{ + Path: filepath.Clean(binding.LocalRoot()), Name: name, codeAllowed: codeAllowed, + remote: remoteWorkspaceContext{ + connectionID: connectionID, hostPath: binding.RemoteRoot(), platform: platform, binding: binding, + }, + }) +} + +func (c *WorkspaceContexts) open(workspace WorkspaceContext) WorkspaceContext { c.mu.Lock() - if existing, ok := c.byPath[path]; ok { - value := *existing - c.mu.Unlock() - return value + previous := c.byPath[workspace.Path] + if previous == nil { + id := make([]byte, 6) + _, _ = rand.Read(id) + workspace.ContextRef = ContextRef{ContextID: "w-" + hex.EncodeToString(id), Generation: 1} + if workspace.authorityKind() == "local" { + c.retainRoot(workspace.Path) + } + } else { + if workspace.remote == previous.remote { + value := *previous + c.mu.Unlock() + return value + } + workspace.ContextRef = previous.ContextRef + workspace.Generation++ + if previous.authorityKind() != workspace.authorityKind() { + if workspace.authorityKind() == "local" { + c.retainRoot(workspace.Path) + } else { + c.releaseRoot(workspace.Path) + } + } + } + if previous != nil && previous.cancel != nil { + previous.cancel() } - id := make([]byte, 6) - _, _ = rand.Read(id) - created := &WorkspaceContext{ - ContextRef: ContextRef{ContextID: "w-" + hex.EncodeToString(id), Generation: 1}, - Name: filepath.Base(path), - Path: path, + if workspace.remote.binding != nil { + workspace.lifetime, workspace.cancel = context.WithCancel(context.Background()) } - c.byPath[path] = created - c.retainRoot(path) + c.byPath[workspace.Path] = &workspace c.revision++ - observer := c.onChange - value := *created + observer, closed := c.onChange, c.onClosed c.mu.Unlock() + if previous != nil && closed != nil { + closed(previous.ContextRef) + } if observer != nil { observer() } - return value + return workspace } // Close ends the context of a workspace root. @@ -174,13 +233,17 @@ func (c *WorkspaceContexts) Close(path string) { return } delete(c.byPath, path) - c.releaseRoot(path) + if closing.cancel != nil { + closing.cancel() + } + if closing.authorityKind() == "local" { + c.releaseRoot(path) + } c.revision++ observer, closed := c.onChange, c.onClosed - id := closing.ContextID c.mu.Unlock() if closed != nil { - closed(id) + closed(closing.ContextRef) } if observer != nil { observer() @@ -194,18 +257,23 @@ func (c *WorkspaceContexts) CloseAll() { c.mu.Unlock() return } - ids := make([]string, 0, len(c.byPath)) + refs := make([]ContextRef, 0, len(c.byPath)) for _, closing := range c.byPath { - ids = append(ids, closing.ContextID) - c.releaseRoot(closing.Path) + refs = append(refs, closing.ContextRef) + if closing.cancel != nil { + closing.cancel() + } + if closing.authorityKind() == "local" { + c.releaseRoot(closing.Path) + } } c.byPath = make(map[string]*WorkspaceContext) c.revision++ observer, closed := c.onChange, c.onClosed c.mu.Unlock() if closed != nil { - for _, id := range ids { - closed(id) + for _, ref := range refs { + closed(ref) } } if observer != nil { diff --git a/desktop/internal/pluginservice/debug_start.go b/desktop/internal/pluginservice/debug_start.go index 0ab1e513f7..8b4d14b358 100644 --- a/desktop/internal/pluginservice/debug_start.go +++ b/desktop/internal/pluginservice/debug_start.go @@ -6,6 +6,7 @@ import ( "errors" "strings" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" ) @@ -21,6 +22,7 @@ type DebugSessionRequest struct { Label string AdapterID string Request string + Connection *core.RemoteWorkspaceConnection // Configuration is the plugin's DAP launch or attach arguments, applied on // top of the adapter's declared defaults. Configuration map[string]any @@ -51,6 +53,10 @@ func (r *Runs) handleDebugStart(ctx context.Context, params json.RawMessage) (js if err != nil { return nil, contextFailure(err) } + remote, refusal := r.captureRemoteRun(workspace) + if refusal != nil { + return nil, refusal + } _, manifest, err := r.service.installedPlugin(ctx, caller.PluginID) if err != nil { return nil, failure(pluginhost.CodeHostFailure, err.Error()) @@ -70,10 +76,17 @@ func (r *Runs) handleDebugStart(ctx context.Context, params json.RawMessage) (js if starter == nil { return nil, failure("plugin.host.unavailable", "This host starts no debug sessions.") } - sessionID, err := starter(ctx, DebugSessionRequest{ + session := DebugSessionRequest{ PluginID: caller.PluginID, WorkspaceRoot: workspace.Path, Label: start.Label, AdapterID: start.AdapterID, Request: start.Request, Configuration: start.Configuration, - }) + } + if remote != nil { + if refusal := remote.refusal(ctx); refusal != nil { + return nil, refusal + } + session.Connection = remote.connection + } + sessionID, err := starter(ctx, session) if err != nil { if errors.Is(err, context.Canceled) { return nil, failure("plugin.host.cancelled", "The request was cancelled.") diff --git a/desktop/internal/pluginservice/hostactions.go b/desktop/internal/pluginservice/hostactions.go index fbce4e5408..a23bf55d0c 100644 --- a/desktop/internal/pluginservice/hostactions.go +++ b/desktop/internal/pluginservice/hostactions.go @@ -103,7 +103,7 @@ type editorActionBindings struct { // recorded here; the backend is called when a document is collected. func (s *Service) registerEditorActions() error { s.actions = &editorActionBindings{} - return s.HostServices.Register(methodRegisterEditorActions, s.handleRegisterEditorActions) + return s.HostServices.Register(methodRegisterEditorActions, s.handleRegisterEditorActions, core.PluginAuthorityBoth) } func (s *Service) handleRegisterEditorActions(ctx context.Context, params json.RawMessage) (json.RawMessage, *pluginhost.Failure) { @@ -164,12 +164,16 @@ func (s *Service) handleRegisterEditorActions(ctx context.Context, params json.R if refusal != nil { return nil, refusal } - id := s.resources.add(caller, workspace.ContextID, func() { + id := s.resources.add(caller, workspace.ContextRef, func() { s.actions.mu.Lock() s.actions.list = removeBinding(s.actions.list, binding) s.actions.mu.Unlock() s.editorActionsChanged(workspace.Path) }) + if _, err := s.Contexts.Lookup(workspace.ContextRef); err != nil { + s.resources.dispose(caller, id) + return nil, contextFailure(err) + } if session.isEnded() { // The session ended after the check above. Its release may already have run without this // resource, which would leave the binding behind for good; withdrawing it here closes that diff --git a/desktop/internal/pluginservice/hostactions_refresh_test.go b/desktop/internal/pluginservice/hostactions_refresh_test.go index dae8dda55e..4e0307fece 100644 --- a/desktop/internal/pluginservice/hostactions_refresh_test.go +++ b/desktop/internal/pluginservice/hostactions_refresh_test.go @@ -38,7 +38,7 @@ func TestEditorActionRegistrationRefreshesOpenDocuments(t *testing.T) { if len(observer.roots) != 1 { t.Fatal("rejected registration refreshed documents") } - service.resources.releaseContext(workspace.ContextID) + service.resources.releaseContext(workspace.ContextRef) if len(observer.roots) != 2 { t.Fatalf("withdrawal did not clear actions: %v", observer.roots) } diff --git a/desktop/internal/pluginservice/hostbuild.go b/desktop/internal/pluginservice/hostbuild.go index 8ace85d87f..2372004949 100644 --- a/desktop/internal/pluginservice/hostbuild.go +++ b/desktop/internal/pluginservice/hostbuild.go @@ -24,7 +24,7 @@ const ( maxBuildConfigurationWatches = 16 ) -func (s *Service) buildCaller(ctx context.Context) (pluginhost.Caller, *BackendSession, *pluginhost.Failure) { +func (s *Service) backendCaller(ctx context.Context) (pluginhost.Caller, *BackendSession, *pluginhost.Failure) { caller, ok := pluginhost.CallerFrom(ctx) if !ok { return caller, nil, failure(pluginhost.CodeHostFailure, "The request has no calling plugin.") @@ -45,7 +45,7 @@ func (s *Service) handleBuildGetOptions(ctx context.Context, params json.RawMess if err := decodeStrict(params, &request); err != nil { return nil, invalidParams(err) } - _, session, refusal := s.buildCaller(ctx) + _, session, refusal := s.backendCaller(ctx) if refusal != nil { return nil, refusal } @@ -59,11 +59,27 @@ func (s *Service) handleBuildGetOptions(ctx context.Context, params json.RawMess if !ok { return nil, failure(pluginhost.CodeHostFailure, "Build option resolution is unavailable.") } - docs, err := buildprefs.Read(ctx, s.preferences, workspace.Path) + var docs buildprefs.Documents + var connection *core.RemoteWorkspaceConnection + if workspace.authorityKind() == "remote" { + connection = workspace.remote.binding.CaptureConnection() + if connection == nil { + return nil, failure("plugin.host.remoteDisconnected", "The remote workspace is disconnected.") + } + docs, err = buildprefs.ReadRemote(connection.Context(ctx), s.preferences, workspace.Path, s.kernel.ReadWorkspaceConfiguration) + } else { + docs, err = buildprefs.Read(ctx, s.preferences, workspace.Path) + } + if refusal := s.buildOptionsLifetimeFailure(ctx, workspace, connection); refusal != nil { + return nil, refusal + } if err != nil { return nil, failure(pluginhost.CodeHostFailure, "Build preferences could not be read.") } - options, err := resolver.ResolveStoredInstanceOptions(ctx, session.manifest, request.BuildSystemID, request.Root, docs.Team, docs.Local) + options, err := resolver.ResolveStoredInstanceOptions(core.WithoutRemoteWorkspace(ctx), session.manifest, request.BuildSystemID, request.Root, docs.Team, docs.Local) + if refusal := s.buildOptionsLifetimeFailure(ctx, workspace, connection); refusal != nil { + return nil, refusal + } if err != nil { var rejected *core.MarketplaceRejection if errors.As(err, &rejected) { @@ -76,12 +92,22 @@ func (s *Service) handleBuildGetOptions(ctx context.Context, params json.RawMess } return nil, failure(pluginhost.CodeHostFailure, "Build preferences could not be resolved.") } - if _, err := s.Contexts.Lookup(request.Context); err != nil { - return nil, contextFailure(err) - } return marshalResult(map[string]json.RawMessage{"options": options}) } +func (s *Service) buildOptionsLifetimeFailure(ctx context.Context, workspace WorkspaceContext, connection *core.RemoteWorkspaceConnection) *pluginhost.Failure { + if _, err := s.Contexts.Lookup(workspace.ContextRef); err != nil { + return contextFailure(err) + } + if err := ctx.Err(); err != nil { + return hostFailureOf(err) + } + if connection != nil && !connection.IsCurrent() { + return failure("plugin.host.remoteDisconnected", "The remote workspace connection changed.") + } + return nil +} + func (s *Service) handleBuildWatchConfiguration(ctx context.Context, params json.RawMessage) (json.RawMessage, *pluginhost.Failure) { var request struct { Context ContextRef `json:"context"` @@ -93,7 +119,7 @@ func (s *Service) handleBuildWatchConfiguration(ctx context.Context, params json if len(request.Files) > maxBuildConfigurationFiles { return nil, failure("plugin.host.limitExceeded", "A build configuration watch accepts at most four extra files.") } - caller, session, refusal := s.buildCaller(ctx) + caller, session, refusal := s.backendCaller(ctx) if refusal != nil { return nil, refusal } @@ -101,6 +127,9 @@ func (s *Service) handleBuildWatchConfiguration(ctx context.Context, params json if err != nil { return nil, contextFailure(err) } + if workspace.authorityKind() == "remote" { + return nil, unsupportedRemoteWorkspace() + } paths := []string{filepath.Join(workspace.Path, buildprefs.TeamFile), s.preferences.Path(buildprefs.LocalFile)} for _, file := range request.Files { if len(file) > 4096 || !filepath.IsAbs(file) || filepath.Clean(file) != file || filepath.Dir(file) == file || strings.ContainsRune(file, 0) { @@ -114,7 +143,7 @@ func (s *Service) handleBuildWatchConfiguration(ctx context.Context, params json } lifetime, stop := context.WithCancel(context.Background()) - id := s.resources.addLimited(caller, workspace.ContextID, stop, maxBuildConfigurationWatches) + id := s.resources.addLimited(caller, workspace.ContextRef, stop, maxBuildConfigurationWatches) if id == "" { stop() return nil, failure("plugin.host.limitExceeded", "The backend has reached its build configuration watch limit.") diff --git a/desktop/internal/pluginservice/hostbuild_test.go b/desktop/internal/pluginservice/hostbuild_test.go index 8d845a4c42..177141d3c7 100644 --- a/desktop/internal/pluginservice/hostbuild_test.go +++ b/desktop/internal/pluginservice/hostbuild_test.go @@ -8,10 +8,98 @@ import ( "testing" "time" + "github.com/1lck/Lithe-IDEA/desktop/internal/buildprefs" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" "github.com/1lck/Lithe-IDEA/desktop/internal/store" ) +type buildOptionsKernel struct { + fakeKernel + client *core.Client + read func(context.Context, string, int64) (*string, error) + resolveError error +} + +func (k *buildOptionsKernel) ReadWorkspaceConfiguration(ctx context.Context, path string, limit int64) (*string, error) { + return k.read(ctx, path, limit) +} + +func (k *buildOptionsKernel) ResolveStoredInstanceOptions(ctx context.Context, manifest json.RawMessage, systemID, root string, team, local json.RawMessage) (json.RawMessage, error) { + result, err := k.client.ResolveStoredInstanceOptions(ctx, manifest, systemID, root, team, local) + k.resolveError = err + return result, err +} + +func TestRemoteBuildOptionsReadTeamValuesAndClientOverrides(t *testing.T) { + kernel := &buildOptionsKernel{client: core.NewClient()} + prefs := store.At(t.TempDir()) + service, err := Open(kernel, prefs, t.TempDir()) + if err != nil { + t.Fatal(err) + } + placeholder := t.TempDir() + binding := core.NewRemoteWorkspace(placeholder, "/home/dev/project", nil) + binding.Attach("remote-build") + workspace := service.Contexts.OpenRemote(binding, "project", "connection", core.RemotePlatform{OS: "linux", Arch: "x86_64"}, nil) + t.Cleanup(service.Contexts.CloseAll) + const pluginID = "dev.lithe.test.remote-build-options" + session := runningActionSession(service, pluginID, "backend") + session.manifest = json.RawMessage(`{ + "schemaVersion":0,"id":"dev.lithe.test.remote-build-options","displayName":"Test","version":"1.0.0","pluginAPIVersion":0, + "requires":{"buildSystems":0},"vendor":{"id":"dev.lithe.test","displayName":"Test","signatureRequirement":"publisherPackage"}, + "permissions":["process.build"],"activationEvents":["onBuildSystem:fixture"],"languages":[], + "buildSystems":[{ + "id":"fixture","displayName":"Fixture","detection":{"markers":["fixture.build"]}, + "invocation":{"executables":[{"kind":"command","command":"fixture-build"}]}, + "options":[{"id":"mode","displayName":"Mode","kind":"text","arguments":["--mode","${value}"]},{"id":"profile","displayName":"Profile","kind":"text","arguments":["--profile","${value}"]}], + "model":{"source":"command","arguments":["model"],"decoder":"litheBuildModel","executesProjectCode":false,"mayUseNetwork":false}, + "tasks":[{"id":"compile","displayName":"Compile","group":"lifecycle","scopes":["workspace"],"arguments":["compile"]}] + }] + }`) + team := `{"version":1,"systems":{"fixture":{"options":{"mode":"team","profile":"from host"}}}}` + local := json.RawMessage(`{"version":1,"document":{"version":1,"systems":{"fixture":{"options":{"mode":"client"}}}}}`) + if err := prefs.Save(buildprefs.LocalFile, map[string]json.RawMessage{placeholder: local}); err != nil { + t.Fatal(err) + } + localTeam := filepath.Join(placeholder, buildprefs.TeamFile) + if err := os.MkdirAll(filepath.Dir(localTeam), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(localTeam, []byte("invalid JSON in placeholder"), 0o600); err != nil { + t.Fatal(err) + } + calls := 0 + reconnect := false + kernel.read = func(ctx context.Context, path string, limit int64) (*string, error) { + calls++ + if core.RemoteWorkspaceOf(ctx) != binding || path != buildprefs.TeamFile || limit != 1<<20 { + t.Fatalf("unexpected remote configuration read: %q, limit %d", path, limit) + } + if reconnect { + binding.Attach("remote-build") + } + return &team, nil + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + ctx = pluginhost.WithCaller(ctx, pluginhost.Caller{PluginID: pluginID, SessionID: session.Session.ID}) + request := json.RawMessage(`{` + contextJSONOf(workspace) + `,"buildSystemID":"fixture","root":"."}`) + result, refusal := service.HostServices.Respond(ctx, methodBuildGetOptions, request) + var got struct{ Options map[string]string } + if err := json.Unmarshal(result, &got); refusal != nil || err != nil || got.Options["mode"] != "client" || got.Options["profile"] != "from host" || calls != 1 { + t.Fatalf("effective options = %s, refusal = %+v, decode error = %v, remote reads = %d, Core error = %+v", result, refusal, err, calls, kernel.resolveError) + } + reconnect = true + if result, refusal := service.HostServices.Respond(ctx, methodBuildGetOptions, request); refusal == nil || refusal.Code != "plugin.host.remoteDisconnected" || result != nil { + t.Fatalf("options from the replaced attachment = %s, %+v", result, refusal) + } + binding.Detach() + if result, refusal := service.HostServices.Respond(ctx, methodBuildGetOptions, request); refusal == nil || refusal.Code != "plugin.host.remoteDisconnected" || result != nil || calls != 2 { + t.Fatalf("options while disconnected = %s, %+v, remote reads = %d", result, refusal, calls) + } +} + type buildWatchNotification struct { session, method string body json.RawMessage diff --git a/desktop/internal/pluginservice/hostcontent.go b/desktop/internal/pluginservice/hostcontent.go index 7fb6383b10..1b0a6d0fb2 100644 --- a/desktop/internal/pluginservice/hostcontent.go +++ b/desktop/internal/pluginservice/hostcontent.go @@ -11,6 +11,7 @@ import ( "sync" "time" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" ) @@ -66,7 +67,7 @@ func providerKey(contextID, scheme string) string { return contextID + "\x00" + func (s *Service) registerContentProviders(host VirtualDocumentHost) error { s.virtualHost = host s.providers = &contentProviders{byName: make(map[string]*contentProvider)} - return s.HostServices.Register(methodRegisterContentProvider, s.handleRegisterContentProvider) + return s.HostServices.Register(methodRegisterContentProvider, s.handleRegisterContentProvider, core.PluginAuthorityBoth) } // validScheme is a URI scheme: a letter, then letters, digits, "+", "-" or ".", at @@ -133,13 +134,17 @@ func (s *Service) handleRegisterContentProvider(ctx context.Context, params json binding := &contentProvider{pluginID: caller.PluginID, sessionID: caller.SessionID, function: request.Function} s.providers.byName[key] = binding s.providers.mu.Unlock() - id := s.resources.add(caller, workspace.ContextID, func() { + id := s.resources.add(caller, workspace.ContextRef, func() { s.providers.mu.Lock() if s.providers.byName[key] == binding { delete(s.providers.byName, key) } s.providers.mu.Unlock() }) + if _, err := s.Contexts.Lookup(workspace.ContextRef); err != nil { + s.resources.dispose(caller, id) + return nil, contextFailure(err) + } return marshalResult(map[string]string{"subscriptionID": id}) } diff --git a/desktop/internal/pluginservice/hostdocuments.go b/desktop/internal/pluginservice/hostdocuments.go index dee79ccaf2..af3170eea2 100644 --- a/desktop/internal/pluginservice/hostdocuments.go +++ b/desktop/internal/pluginservice/hostdocuments.go @@ -7,6 +7,7 @@ import ( "time" "unicode/utf8" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" ) @@ -98,21 +99,22 @@ func (s *Service) AttachWorkbench(workbench Workbench) error { } s.workbench = workbench for _, entry := range []struct { - method string - handler pluginhost.Handler + method string + handler pluginhost.Handler + authority core.PluginAuthoritySupport }{ - {methodDocumentsList, s.handleDocumentsList}, - {methodDocumentsGetSnapshot, s.handleDocumentsSnapshot}, - {methodEditorGetActive, s.handleEditorActive}, - {methodEditorGetSelections, s.handleEditorSelections}, - {methodEditorApplyEdits, s.handleEditorApplyEdits}, - {methodEditorReplaceSel, s.handleEditorReplaceSelections}, - {methodEditorInsertText, s.handleEditorInsertText}, - {methodEditorOpen, s.handleEditorOpen}, - {methodEditorReveal, s.handleEditorOpen}, - {methodBrowserOpenExternal, s.handleBrowserOpenExternal}, + {methodDocumentsList, s.handleDocumentsList, core.PluginAuthorityBoth}, + {methodDocumentsGetSnapshot, s.handleDocumentsSnapshot, core.PluginAuthorityBoth}, + {methodEditorGetActive, s.handleEditorActive, core.PluginAuthorityBoth}, + {methodEditorGetSelections, s.handleEditorSelections, core.PluginAuthorityBoth}, + {methodEditorApplyEdits, s.handleEditorApplyEdits, core.PluginAuthorityBoth}, + {methodEditorReplaceSel, s.handleEditorReplaceSelections, core.PluginAuthorityBoth}, + {methodEditorInsertText, s.handleEditorInsertText, core.PluginAuthorityBoth}, + {methodEditorOpen, s.handleEditorOpen, core.PluginAuthorityLocal}, + {methodEditorReveal, s.handleEditorOpen, core.PluginAuthorityLocal}, + {methodBrowserOpenExternal, s.handleBrowserOpenExternal, core.PluginAuthorityBoth}, } { - if err := s.HostServices.Register(entry.method, entry.handler); err != nil { + if err := s.HostServices.Register(entry.method, entry.handler, entry.authority); err != nil { return err } } @@ -140,7 +142,7 @@ func (s *Service) AttachWorkbench(workbench Workbench) error { // A message waits for the user, so the machine deadline must not cut it. if err := s.HostServices.RegisterUserChoice(level.method, func(ctx context.Context, params json.RawMessage) (json.RawMessage, *pluginhost.Failure) { return s.handleWindowMessage(ctx, params, name) - }); err != nil { + }, core.PluginAuthorityBoth); err != nil { return err } } @@ -366,6 +368,9 @@ func (s *Service) handleEditorOpen(ctx context.Context, params json.RawMessage) if refusal != nil { return nil, refusal } + if workspace.authorityKind() == "remote" { + return nil, unsupportedRemoteWorkspace() + } switch request.Activation { case "", "select", "background": default: diff --git a/desktop/internal/pluginservice/hostfiles.go b/desktop/internal/pluginservice/hostfiles.go new file mode 100644 index 0000000000..36d3ea6b20 --- /dev/null +++ b/desktop/internal/pluginservice/hostfiles.go @@ -0,0 +1,129 @@ +package pluginservice + +import ( + "context" + "encoding/json" + "errors" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" +) + +type workspaceFileParams struct { + Context ContextRef `json:"context"` + Resource json.RawMessage `json:"resource"` + Cursor *string `json:"cursor"` + Limit *int64 `json:"limit"` + MaximumBytes *int64 `json:"maximumBytes"` + Query *string `json:"query"` + Pattern *string `json:"pattern"` + FileMask *string `json:"fileMask"` + CaseSensitive *bool `json:"caseSensitive"` + WholeWords *bool `json:"wholeWords"` + RegularExpression *bool `json:"regularExpression"` +} + +type pluginWorkspaceResource struct { + RootID string `json:"rootID"` + Path *string `json:"path"` +} + +func (s *Service) remoteFileResource(ctx context.Context, ref ContextRef, raw json.RawMessage) (pluginhost.Caller, WorkspaceContext, pluginWorkspaceResource, *core.RemoteWorkspaceConnection, *pluginhost.Failure) { + var resource pluginWorkspaceResource + if err := decodeStrict(raw, &resource); err != nil { + return pluginhost.Caller{}, WorkspaceContext{}, resource, nil, invalidParams(err) + } + caller, workspace, refusal := s.workspaceRequest(ctx, ref) + if refusal != nil { + return caller, workspace, resource, nil, refusal + } + if resource.Path == nil || resource.RootID == "" || + resource.RootID != s.Contexts.RootID(caller.PluginID, workspace.Path) { + return caller, workspace, resource, nil, failure("plugin.host.invalidParams", "Expected a resource in the caller's workspace folder.") + } + binding := workspace.remote.binding + if binding == nil { + return caller, workspace, resource, nil, failure(codeAuthorityUnsupported, "This file service requires a remote workspace.") + } + connection := binding.CaptureConnection() + if connection == nil { + return caller, workspace, resource, nil, failure("plugin.host.remoteDisconnected", "The remote workspace is disconnected.") + } + return caller, workspace, resource, connection, nil +} + +func (s *Service) workspaceFileHandler(kind string, options ...string) pluginhost.Handler { + allowed := append([]string{"context", "resource"}, options...) + return func(ctx context.Context, raw json.RawMessage) (json.RawMessage, *pluginhost.Failure) { + var request workspaceFileParams + if err := decodeStrictEmbedded(raw, &request, allowed...); err != nil { + return nil, invalidParams(err) + } + _, workspace, resource, connection, refusal := s.remoteFileResource(ctx, request.Context, request.Resource) + if refusal != nil { + return nil, refusal + } + return s.readRemotePluginFile(ctx, workspace, connection, resource, core.PluginFileOperation{ + Kind: kind, Cursor: request.Cursor, Limit: request.Limit, MaximumBytes: request.MaximumBytes, + Query: request.Query, Pattern: request.Pattern, FileMask: request.FileMask, + CaseSensitive: request.CaseSensitive, WholeWords: request.WholeWords, RegularExpression: request.RegularExpression, + }) + } +} + +func (s *Service) readRemotePluginFile(ctx context.Context, workspace WorkspaceContext, connection *core.RemoteWorkspaceConnection, resource pluginWorkspaceResource, operation core.PluginFileOperation) (json.RawMessage, *pluginhost.Failure) { + result, err := s.kernel.ReadPluginFile(connection.Context(ctx), core.PluginFileRequest{ + RootID: resource.RootID, + Generation: workspace.Generation, + Attachment: connection.Revision(), + Path: *resource.Path, + Operation: operation, + }) + if _, lookupErr := s.Contexts.Lookup(workspace.ContextRef); lookupErr != nil { + return nil, contextFailure(lookupErr) + } + if ctx.Err() != nil { + return nil, hostFailureOf(ctx.Err()) + } + if !connection.IsCurrent() { + return nil, failure("plugin.host.remoteDisconnected", "The remote workspace connection changed.") + } + if err != nil { + return nil, pluginFileFailure(err) + } + return result, nil +} + +func pluginFileFailure(err error) *pluginhost.Failure { + var detail *core.Error + if !errors.As(err, &detail) { + return hostFailureOf(err) + } + switch detail.Code { + case core.CodeInvalidRequest: + return failure("plugin.host.invalidParams", detail.Message) + case core.CodeWorkspaceNotFound: + return failure("plugin.host.notFound", "The workspace resource does not exist.") + case core.CodePermissionDenied: + return failure("plugin.host.permissionDenied", "The workspace host refused access to the resource.") + case core.CodeConnectionClosed: + return failure("plugin.host.remoteDisconnected", "The remote workspace is disconnected.") + case core.CodeProcessFailed: + var host struct { + RemoteCode string `json:"remoteCode"` + } + if json.Unmarshal([]byte(detail.Details), &host) == nil { + switch host.RemoteCode { + case "TOO_LARGE": + return failure("plugin.host.limitExceeded", detail.Message) + case "BUSY": + return failure("plugin.host.busy", detail.Message) + case "NOT_A_DIRECTORY", "IS_A_DIRECTORY", "INVALID_PATH", "INVALID_REQUEST": + return failure("plugin.host.invalidParams", detail.Message) + case "UNKNOWN_METHOD", "UNSUPPORTED": + return failure(codeAuthorityUnsupported, "The remote host does not offer this file service.") + } + } + } + return hostFailureOf(err) +} diff --git a/desktop/internal/pluginservice/hostfiles_test.go b/desktop/internal/pluginservice/hostfiles_test.go new file mode 100644 index 0000000000..0c8a8bf6a6 --- /dev/null +++ b/desktop/internal/pluginservice/hostfiles_test.go @@ -0,0 +1,62 @@ +package pluginservice + +import ( + "context" + "encoding/json" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +func TestRemotePluginFilesUseTheAuthorizedWorkspaceBinding(t *testing.T) { + service := openHostService(t) + binding := core.NewRemoteWorkspace(t.TempDir(), "/home/dev/remote", nil) + binding.Attach("live-session") + workspace := service.Contexts.OpenRemote(binding, "project", "c-test", core.RemotePlatform{OS: "linux", Arch: "x86_64"}, nil) + t.Cleanup(service.Contexts.CloseAll) + const plugin = "dev.lithe.test.remote-files" + rootID := service.Contexts.RootID(plugin, workspace.Path) + ref, err := json.Marshal(workspace.ContextRef) + if err != nil { + t.Fatal(err) + } + params := `{"context":` + string(ref) + `,"resource":{"rootID":"` + rootID + `","path":"src/main.txt"},"maximumBytes":64}` + calls := 0 + next := func() (json.RawMessage, error) { return json.RawMessage(`{"text":"from host"}`), nil } + service.kernel.(*fakeKernel).pluginFile = func(ctx context.Context, request core.PluginFileRequest) (json.RawMessage, error) { + calls++ + if core.RemoteWorkspaceOf(ctx) != binding || request.RootID != rootID || request.Generation != workspace.Generation || + request.Path != "src/main.txt" || request.Operation.Kind != "readFile" || request.Operation.MaximumBytes == nil || *request.Operation.MaximumBytes != 64 { + t.Fatalf("incorrect host dispatch: %+v", request) + } + return next() + } + + result, refusal := respond(t, service, plugin, "workspace/readFile", params) + if refusal != nil || string(result) != `{"text":"from host"}` { + t.Fatalf("readFile = %s, %+v", result, refusal) + } + if _, refusal := respond(t, service, "dev.lithe.test.another", "workspace/readFile", params); refusal == nil || refusal.Code != "plugin.host.invalidParams" || calls != 1 { + t.Fatalf("foreign resource = %+v, dispatched %d times", refusal, calls) + } + next = func() (json.RawMessage, error) { + return nil, &core.Error{Code: core.CodeProcessFailed, Details: `{"remoteCode":"TOO_LARGE"}`} + } + if _, refusal := respond(t, service, plugin, "workspace/readFile", params); refusal == nil || refusal.Code != "plugin.host.limitExceeded" { + t.Fatalf("oversize request = %+v", refusal) + } + next = func() (json.RawMessage, error) { + binding.Attach("replacement-session") + return json.RawMessage(`{"text":"from old session"}`), nil + } + if result, refusal := respond(t, service, plugin, "workspace/readFile", params); refusal == nil || refusal.Code != "plugin.host.remoteDisconnected" || result != nil { + t.Fatalf("old session result = %s, %+v", result, refusal) + } + next = func() (json.RawMessage, error) { + service.Contexts.Close(workspace.Path) + return json.RawMessage(`{"text":"from closed context"}`), nil + } + if result, refusal := respond(t, service, plugin, "workspace/readFile", params); refusal == nil || refusal.Code != "plugin.host.contextExpired" || result != nil { + t.Fatalf("closed context result = %s, %+v", result, refusal) + } +} diff --git a/desktop/internal/pluginservice/hostmethods.go b/desktop/internal/pluginservice/hostmethods.go index 18be8f42ab..71fd9b4f74 100644 --- a/desktop/internal/pluginservice/hostmethods.go +++ b/desktop/internal/pluginservice/hostmethods.go @@ -27,6 +27,7 @@ const ( methodListContexts = pluginhost.MethodPrefix + "workspace/listContexts" methodGetContext = pluginhost.MethodPrefix + "workspace/getContext" + methodGetHostPaths = pluginhost.MethodPrefix + "workspace/getHostPaths" methodGetFolders = pluginhost.MethodPrefix + "workspace/getFolders" methodDisposeSub = pluginhost.MethodPrefix + "subscriptions/dispose" methodLSRequest = pluginhost.MethodPrefix + "languageServer/request" @@ -43,26 +44,34 @@ const ( // pluginhost.CallerFrom, so per-plugin scoping never needs a second registry. func (s *Service) registerHostServices() error { machine := []struct { - method string - handler pluginhost.Handler + method string + handler pluginhost.Handler + authority core.PluginAuthoritySupport }{ - {methodListContexts, s.handleListContexts}, - {methodBuildGetOptions, s.handleBuildGetOptions}, - {methodBuildWatchConfiguration, s.handleBuildWatchConfiguration}, - {methodGetContext, s.handleGetContext}, - {methodGetFolders, s.handleGetFolders}, - {methodDisposeSub, s.handleDisposeSubscription}, - {methodLSNotify, s.handleLanguageServerNotify}, - {methodLSSetStatus, s.handleLanguageServerSetStatus}, + {methodListContexts, s.handleListContexts, core.PluginAuthorityBoth}, + {methodBuildGetOptions, s.handleBuildGetOptions, core.PluginAuthorityBoth}, + {methodBuildWatchConfiguration, s.handleBuildWatchConfiguration, core.PluginAuthorityLocal}, + {methodGetContext, s.handleGetContext, core.PluginAuthorityBoth}, + {methodGetFolders, s.handleGetFolders, core.PluginAuthorityBoth}, + {methodGetHostPaths, s.handleGetHostPaths, core.PluginAuthorityRemote}, + {pluginhost.MethodPrefix + "workspace/readDirectory", s.workspaceFileHandler("readDirectory", "cursor", "limit"), core.PluginAuthorityRemote}, + {pluginhost.MethodPrefix + "workspace/stat", s.workspaceFileHandler("stat"), core.PluginAuthorityRemote}, + {pluginhost.MethodPrefix + "workspace/readFile", s.workspaceFileHandler("readFile", "maximumBytes"), core.PluginAuthorityRemote}, + {pluginhost.MethodPrefix + "workspace/findFiles", s.workspaceFileHandler("findFiles", "query", "fileMask", "cursor", "limit"), core.PluginAuthorityRemote}, + {pluginhost.MethodPrefix + "workspace/findText", s.workspaceFileHandler("findText", "pattern", "fileMask", "caseSensitive", "wholeWords", "regularExpression", "cursor", "limit"), core.PluginAuthorityRemote}, + {pluginhost.MethodPrefix + "workspace/watch", s.handleWorkspaceWatch, core.PluginAuthorityRemote}, + {methodDisposeSub, s.handleDisposeSubscription, core.PluginAuthorityBoth}, + {methodLSNotify, s.handleLanguageServerNotify, core.PluginAuthorityBoth}, + {methodLSSetStatus, s.handleLanguageServerSetStatus, core.PluginAuthorityBoth}, } for _, entry := range machine { - if err := s.HostServices.Register(entry.method, entry.handler); err != nil { + if err := s.HostServices.Register(entry.method, entry.handler, entry.authority); err != nil { return err } } // A language-server request waits for the server, up to the request's own // timeout (at most 300 s), so the machine deadline of 30 s must not cut it. - if err := s.HostServices.RegisterUserChoice(methodLSRequest, s.handleLanguageServerRequest); err != nil { + if err := s.HostServices.RegisterUserChoice(methodLSRequest, s.handleLanguageServerRequest, core.PluginAuthorityBoth); err != nil { return err } if err := s.registerCredentials(); err != nil { @@ -70,10 +79,10 @@ func (s *Service) registerHostServices() error { } // run/start answers after the process started and returns at once, so the // machine deadline is enough; the run itself outlives the request. - if err := s.HostServices.Register(methodRunStart, s.Runs.handleStart); err != nil { + if err := s.HostServices.Register(methodRunStart, s.Runs.handleStart, core.PluginAuthorityBoth); err != nil { return err } - if err := s.HostServices.Register(methodRunStop, s.Runs.handleStop); err != nil { + if err := s.HostServices.Register(methodRunStop, s.Runs.handleStop, core.PluginAuthorityBoth); err != nil { return err } if err := s.HostServices.Register(methodDebugStart, s.Runs.handleDebugStart); err != nil { @@ -103,27 +112,41 @@ func contextFailure(err error) *pluginhost.Failure { } type contextJSON struct { - ContextID string `json:"contextID"` - Generation uint64 `json:"generation"` - Name string `json:"name"` - Authority map[string]any `json:"authority"` - Folders []folderJSON `json:"folders"` - StateDirectory string `json:"stateDirectory,omitempty"` + ContextID string `json:"contextID"` + Generation uint64 `json:"generation"` + Name string `json:"name"` + Authority authorityJSON `json:"authority"` + Folders []folderJSON `json:"folders"` + StateDirectory string `json:"stateDirectory,omitempty"` +} + +type authorityJSON struct { + Kind string `json:"kind"` + ID string `json:"id,omitempty"` + Platform *core.RemotePlatform `json:"platform,omitempty"` } type folderJSON struct { RootID string `json:"rootID"` Name string `json:"name"` - Path string `json:"path"` + Path string `json:"path,omitempty"` } func (s *Service) contextJSON(pluginID string, workspace WorkspaceContext) contextJSON { + authority := authorityJSON{Kind: workspace.authorityKind()} + folder := folderJSON{RootID: s.Contexts.RootID(pluginID, workspace.Path), Name: workspace.Name} + if authority.Kind == "remote" { + authority.ID = workspace.remote.connectionID + authority.Platform = &workspace.remote.platform + } else { + folder.Path = workspace.Path + } return contextJSON{ ContextID: workspace.ContextID, Generation: workspace.Generation, Name: workspace.Name, - Authority: map[string]any{"kind": "local"}, - Folders: []folderJSON{{RootID: s.Contexts.RootID(pluginID, workspace.Path), Name: workspace.Name, Path: workspace.Path}}, + Authority: authority, + Folders: []folderJSON{folder}, } } @@ -193,6 +216,40 @@ func (s *Service) handleGetFolders(ctx context.Context, params json.RawMessage) return marshalResult(map[string]any{"folders": s.contextJSON(caller.PluginID, workspace).Folders}) } +func (s *Service) handleGetHostPaths(ctx context.Context, params json.RawMessage) (json.RawMessage, *pluginhost.Failure) { + // Core checks the separate method grant and validates the root ID selection + // before forwarding the call. Only the client knows which roots are open. + var request struct { + Context ContextRef `json:"context"` + RootIDs []string `json:"rootIDs"` + } + if err := json.Unmarshal(params, &request); err != nil { + return nil, invalidParams(err) + } + caller, workspace, refusal := s.workspaceRequest(ctx, request.Context) + if refusal != nil { + return nil, refusal + } + if workspace.authorityKind() != "remote" { + return nil, failure(codeAuthorityUnsupported, "Host paths are available for remote workspaces.") + } + rootID := s.Contexts.RootID(caller.PluginID, workspace.Path) + for _, requested := range request.RootIDs { + if requested != rootID { + return nil, failure(CodeNotFound, "No such root in the workspace.") + } + } + type hostFolder struct { + RootID string `json:"rootID"` + HostPath string `json:"hostPath"` + } + return marshalResult(map[string][]hostFolder{"folders": {{RootID: rootID, HostPath: workspace.remote.hostPath}}}) +} + +func unsupportedRemoteWorkspace() *pluginhost.Failure { + return failure(codeAuthorityUnsupported, "This operation is unavailable for remote workspaces.") +} + func marshalResult(value any) (json.RawMessage, *pluginhost.Failure) { data, err := json.Marshal(value) if err != nil { diff --git a/desktop/internal/pluginservice/hostmethods_test.go b/desktop/internal/pluginservice/hostmethods_test.go index eb81773b9c..0d97006b08 100644 --- a/desktop/internal/pluginservice/hostmethods_test.go +++ b/desktop/internal/pluginservice/hostmethods_test.go @@ -373,3 +373,84 @@ func (m *memoryCredentials) Delete(service, account string) error { func pluginhostGrant(service *Service, methods ...string) []string { return pluginhost.GrantServices(methods, service.HostServices) } + +func TestRemoteWorkspaceHostPathsKeepNativeAndRemotePathsSeparate(t *testing.T) { + service := openHostService(t) + if err := service.AttachWorkbench(&fakeWorkbench{}); err != nil { + t.Fatal(err) + } + service.Contexts.SetObserver(nil) + placeholder := filepath.Join(t.TempDir(), "placeholder") + const hostPath = "/home/dev/project" + const plugin = "dev.lithe.test.remote-metadata" + workspace := service.Contexts.OpenRemote(core.NewRemoteWorkspace(placeholder, hostPath, nil), "project", "c-build", + core.RemotePlatform{OS: "linux", Arch: "arm64"}, nil) + t.Cleanup(service.Contexts.CloseAll) + ref, err := json.Marshal(workspace.ContextRef) + if err != nil { + t.Fatal(err) + } + params := `{"context":` + string(ref) + `}` + rootID := service.Contexts.RootID(plugin, placeholder) + for _, request := range []struct{ method, params string }{ + {"workspace/listContexts", "{}"}, + {"workspace/getContext", params}, + {"workspace/getFolders", params}, + } { + result, refusal := respond(t, service, plugin, request.method, request.params) + if refusal != nil || strings.Contains(string(result), hostPath) || strings.Contains(string(result), "placeholder") || strings.Contains(string(result), `"path"`) { + t.Fatalf("%s = %s, %+v", request.method, result, refusal) + } + if !strings.Contains(string(result), rootID) { + t.Fatalf("%s omitted the plugin's root ID: %s", request.method, result) + } + if request.method != "workspace/getFolders" && !strings.Contains(string(result), `"authority":{"kind":"remote","id":"c-build","platform":{"os":"linux","arch":"arm64"}}`) { + t.Fatalf("%s omitted the remote authority: %s", request.method, result) + } + } + for _, selection := range []string{"", `,"rootIDs":["` + rootID + `"]`} { + result, refusal := respond(t, service, plugin, "workspace/getHostPaths", `{"context":`+string(ref)+selection+`}`) + want := `{"folders":[{"rootID":"` + rootID + `","hostPath":"` + hostPath + `"}]}` + if refusal != nil || string(result) != want { + t.Fatalf("getHostPaths = %s, %+v, want %s", result, refusal, want) + } + } + _, refusal := respond(t, service, "dev.lithe.test.other", "workspace/getHostPaths", + `{"context":`+string(ref)+`,"rootIDs":["`+rootID+`"]}`) + if refusal == nil || refusal.Code != CodeNotFound { + t.Fatalf("foreign root refusal = %+v", refusal) + } + + _, refusal = respond(t, service, plugin, "editor/open", params) + if refusal == nil || refusal.Code != codeAuthorityUnsupported { + t.Fatalf("editor/open refusal = %+v, want authorityUnsupported", refusal) + } + for _, method := range []string{"debug/start", "run/start"} { + _, refusal := respond(t, service, plugin, method, params) + if refusal == nil || refusal.Code != CodeRemoteDisconnected { + t.Fatalf("%s on the disconnected workspace = %+v, want remoteDisconnected", method, refusal) + } + } + _, refusal = respond(t, service, plugin, "terminal/create", + `{"context":`+string(ref)+`,"executable":"/usr/bin/printf"}`) + if refusal == nil || refusal.Code != CodeRemoteDisconnected { + t.Fatalf("terminal/create on the disconnected workspace = %+v, want remoteDisconnected", refusal) + } + if roots := service.Contexts.workspaceRoots(); len(roots) != 0 { + t.Fatalf("native runtime discovery received remote roots: %v", roots) + } + service.Contexts.Close(placeholder) + _, refusal = respond(t, service, plugin, "workspace/getHostPaths", params) + if refusal == nil || refusal.Code != CodeContextExpired { + t.Fatalf("closed context refusal = %+v", refusal) + } + local := service.Contexts.Open(t.TempDir()) + ref, err = json.Marshal(local.ContextRef) + if err != nil { + t.Fatal(err) + } + _, refusal = respond(t, service, plugin, "workspace/getHostPaths", `{"context":`+string(ref)+`}`) + if refusal == nil || refusal.Code != codeAuthorityUnsupported { + t.Fatalf("local context refusal = %+v", refusal) + } +} diff --git a/desktop/internal/pluginservice/hostproviders.go b/desktop/internal/pluginservice/hostproviders.go index dd60003159..23cec87dc5 100644 --- a/desktop/internal/pluginservice/hostproviders.go +++ b/desktop/internal/pluginservice/hostproviders.go @@ -82,7 +82,7 @@ type editorProviderBindings struct { // registerEditorProviders attaches the provider registration method to a window. func (s *Service) registerEditorProviders() error { s.providers2 = &editorProviderBindings{} - return s.HostServices.Register(methodRegisterEditorProviders, s.handleRegisterEditorProviders) + return s.HostServices.Register(methodRegisterEditorProviders, s.handleRegisterEditorProviders, core.PluginAuthorityBoth) } func (s *Service) handleRegisterEditorProviders(ctx context.Context, params json.RawMessage) (json.RawMessage, *pluginhost.Failure) { @@ -183,11 +183,15 @@ func (s *Service) handleRegisterEditorProviders(ctx context.Context, params json } s.providers2.list = append(s.providers2.list, binding) s.providers2.mu.Unlock() - id := s.resources.add(caller, workspace.ContextID, func() { + id := s.resources.add(caller, workspace.ContextRef, func() { s.providers2.mu.Lock() defer s.providers2.mu.Unlock() s.providers2.list = removeProviderBinding(s.providers2.list, binding) }) + if _, err := s.Contexts.Lookup(workspace.ContextRef); err != nil { + s.resources.dispose(caller, id) + return nil, contextFailure(err) + } return marshalResult(map[string]string{"subscriptionID": id}) } diff --git a/desktop/internal/pluginservice/hostresources.go b/desktop/internal/pluginservice/hostresources.go index 348b6b7106..98704028e2 100644 --- a/desktop/internal/pluginservice/hostresources.go +++ b/desktop/internal/pluginservice/hostresources.go @@ -16,7 +16,7 @@ type hostResource struct { id string pluginID string sessionID string - contextID string + workspace ContextRef limited bool // dispose releases the resource. It runs once, without the registry lock. dispose func() @@ -38,13 +38,13 @@ func newHostResources() *hostResources { } // add records a resource and returns its subscription ID. -func (r *hostResources) add(caller pluginhost.Caller, contextID string, dispose func()) string { - return r.addLimited(caller, contextID, dispose, 0) +func (r *hostResources) add(caller pluginhost.Caller, workspace ContextRef, dispose func()) string { + return r.addLimited(caller, workspace, dispose, 0) } // addLimited caps limited resources held by one backend session for callers that // allocate a native registration. A zero limit preserves uncapped callers. -func (r *hostResources) addLimited(caller pluginhost.Caller, contextID string, dispose func(), limit int) string { +func (r *hostResources) addLimited(caller pluginhost.Caller, workspace ContextRef, dispose func(), limit int) string { r.mu.Lock() defer r.mu.Unlock() if limit > 0 { @@ -60,7 +60,7 @@ func (r *hostResources) addLimited(caller pluginhost.Caller, contextID string, d } r.next++ id := "s-" + strconv.FormatUint(r.next, 10) - r.byID[id] = &hostResource{id: id, pluginID: caller.PluginID, sessionID: caller.SessionID, contextID: contextID, limited: limit > 0, dispose: dispose} + r.byID[id] = &hostResource{id: id, pluginID: caller.PluginID, sessionID: caller.SessionID, workspace: workspace, limited: limit > 0, dispose: dispose} return id } @@ -102,9 +102,9 @@ func (r *hostResources) releaseSession(sessionID string) { r.releaseWhere(func(resource *hostResource) bool { return resource.sessionID == sessionID }) } -// releaseContext releases everything made for a closed workspace context. -func (r *hostResources) releaseContext(contextID string) { - r.releaseWhere(func(resource *hostResource) bool { return resource.contextID != "" && resource.contextID == contextID }) +// releaseContext releases resources owned by the generation that expired. +func (r *hostResources) releaseContext(workspace ContextRef) { + r.releaseWhere(func(resource *hostResource) bool { return resource.workspace == workspace }) } // releasePlugin releases everything one plugin holds, for disable and update. diff --git a/desktop/internal/pluginservice/hostsurface.go b/desktop/internal/pluginservice/hostsurface.go index 5ff349f41f..aefa2503c2 100644 --- a/desktop/internal/pluginservice/hostsurface.go +++ b/desktop/internal/pluginservice/hostsurface.go @@ -34,6 +34,7 @@ const ( CodeRateLimited = "plugin.host.rateLimited" CodePermissionDenied = "plugin.host.permissionDenied" CodeContextExpired = "plugin.host.contextExpired" + CodeRemoteDisconnected = "plugin.host.remoteDisconnected" CodeUnsupportedOption = "plugin.host.unsupportedOption" codeInvalidParams = "plugin.host.invalidParams" codeAuthorityUnsupported = "plugin.host.authorityUnsupported" @@ -185,23 +186,9 @@ type Resource struct { // stay inside the root, so a link cannot lead out of it. The check and the later // open are not atomic, which the contract documents. func (s *Service) resolveResource(pluginID string, workspace WorkspaceContext, resource Resource) (string, error) { - if resource.RootID == "" || resource.RootID != s.Contexts.RootID(pluginID, workspace.Path) { - return "", fmt.Errorf("%w: unknown root", ErrResource) - } - rel := resource.Path - if strings.ContainsAny(rel, "\\\x00") || strings.HasPrefix(rel, "/") || (len(rel) >= 2 && rel[1] == ':') { - return "", fmt.Errorf("%w: the path must be relative with / separators", ErrResource) - } - var parts []string - for _, part := range strings.Split(rel, "/") { - switch part { - case "": - // An empty path is the root; a doubled slash is tolerated. - case ".", "..": - return "", fmt.Errorf("%w: the path has a %q component", ErrResource, part) - default: - parts = append(parts, part) - } + parts, err := s.resourcePathParts(pluginID, workspace, resource) + if err != nil { + return "", err } root := filepath.Clean(workspace.Path) target := filepath.Join(append([]string{root}, parts...)...) @@ -210,7 +197,6 @@ func (s *Service) resolveResource(pluginID string, workspace WorkspaceContext, r return "", err } existing := target - var rest []string for { if _, statErr := os.Lstat(existing); statErr == nil { break @@ -219,7 +205,6 @@ func (s *Service) resolveResource(pluginID string, workspace WorkspaceContext, r if parent == existing { return "", fmt.Errorf("%w: no existing parent", ErrResource) } - rest = append([]string{filepath.Base(existing)}, rest...) existing = parent } canonical, err := filepath.EvalSymlinks(existing) @@ -229,10 +214,32 @@ func (s *Service) resolveResource(pluginID string, workspace WorkspaceContext, r if canonical != canonicalRoot && !strings.HasPrefix(canonical, canonicalRoot+string(filepath.Separator)) { return "", fmt.Errorf("%w: the path leaves the workspace", ErrResource) } - _ = rest return target, nil } +// resourcePathParts checks the plugin's resource identity before either host resolves it. +func (s *Service) resourcePathParts(pluginID string, workspace WorkspaceContext, resource Resource) ([]string, error) { + if resource.RootID == "" || resource.RootID != s.Contexts.RootID(pluginID, workspace.Path) { + return nil, fmt.Errorf("%w: unknown root", ErrResource) + } + rel := resource.Path + if strings.ContainsAny(rel, "\\\x00") || strings.HasPrefix(rel, "/") || (len(rel) >= 2 && rel[1] == ':') { + return nil, fmt.Errorf("%w: the path must be relative with / separators", ErrResource) + } + var parts []string + for _, part := range strings.Split(rel, "/") { + switch part { + case "": + // An empty path is the root; a doubled slash is tolerated. + case ".", "..": + return nil, fmt.Errorf("%w: the path has a %q component", ErrResource, part) + default: + parts = append(parts, part) + } + } + return parts, nil +} + // relativePath is the workspace-relative form of a document's absolute path, or // nil for a document outside the root. func relativePath(root, path string) *string { diff --git a/desktop/internal/pluginservice/hostterminal.go b/desktop/internal/pluginservice/hostterminal.go index bfebd87041..663dcce7ca 100644 --- a/desktop/internal/pluginservice/hostterminal.go +++ b/desktop/internal/pluginservice/hostterminal.go @@ -3,6 +3,7 @@ package pluginservice import ( "context" "encoding/json" + "path" "path/filepath" "strconv" "strings" @@ -10,6 +11,7 @@ import ( "time" "unicode/utf8" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" ) @@ -48,6 +50,10 @@ type TerminalSpec struct { Title string // Directory is the absolute working directory inside the workspace. Directory string + // RemoteDirectory holds the approved host root and relative cwd in a remote workspace. + RemoteDirectory *core.RemoteScopedDirectory + // RemoteConnection is captured for each consent and launch, including reopen. + RemoteConnection *core.RemoteWorkspaceConnection // Environment overrides variables; a nil value removes one. Environment map[string]*string // Show selects the terminal and reveals the terminal panel. @@ -93,7 +99,6 @@ type TerminalHost interface { type terminalHandle struct { id string caller pluginhost.Caller - contextID string workspace WorkspaceContext spec TerminalSpec @@ -137,9 +142,9 @@ func (s *Service) registerTerminals(host TerminalHost) error { } { var err error if entry.choice { - err = s.HostServices.RegisterUserChoice(entry.method, entry.handler) + err = s.HostServices.RegisterUserChoice(entry.method, entry.handler, core.PluginAuthorityBoth) } else { - err = s.HostServices.Register(entry.method, entry.handler) + err = s.HostServices.Register(entry.method, entry.handler, core.PluginAuthorityBoth) } if err != nil { return err @@ -170,11 +175,11 @@ func retainedBudget(value *int) (int, *pluginhost.Failure) { return *value, nil } -func validExecutable(name string) bool { +func validExecutable(name string, isAbsolute func(string) bool) bool { if name == "" || len(name) > maxTerminalValueBytes || strings.ContainsRune(name, 0) { return false } - if filepath.IsAbs(name) { + if isAbsolute(name) { return true } // A bare command is resolved by PATH; a relative path with a separator is not. @@ -182,8 +187,8 @@ func validExecutable(name string) bool { } // validateTerminal checks the launch data against the contract's limits. -func validateTerminal(request terminalCreateParams) *pluginhost.Failure { - if !validExecutable(request.Executable) { +func validateTerminal(request terminalCreateParams, isAbsolute func(string) bool) *pluginhost.Failure { + if !validExecutable(request.Executable, isAbsolute) { return failure(codeInvalidParams, "executable is an absolute path or a bare command.") } if len(request.Arguments) > maxTerminalArguments { @@ -229,25 +234,40 @@ func (s *Service) handleTerminalCreate(ctx context.Context, params json.RawMessa if refusal != nil { return nil, refusal } - if refusal := validateTerminal(request); refusal != nil { + remote := workspace.authorityKind() == "remote" + isAbsolute := filepath.IsAbs + if remote { + isAbsolute = path.IsAbs + } + if refusal := validateTerminal(request, isAbsolute); refusal != nil { return nil, refusal } budget, refusal := retainedBudget(request.RetainedBytes) if refusal != nil { return nil, refusal } - directory := workspace.Path - if request.Cwd != nil { + spec := TerminalSpec{ + PluginID: caller.PluginID, Executable: request.Executable, Arguments: request.Arguments, + Title: request.Title, Directory: workspace.Path, Environment: request.Environment, + Show: request.Show == nil || *request.Show, RetainedBytes: budget, + } + if remote { + var relative string + if request.Cwd != nil { + parts, err := s.resourcePathParts(caller.PluginID, workspace, *request.Cwd) + if err != nil { + return nil, failure(codeInvalidParams, "cwd is not a directory inside the workspace.") + } + relative = strings.Join(parts, "/") + } + spec.RemoteDirectory = &core.RemoteScopedDirectory{Root: workspace.remote.hostPath, Path: relative} + spec.Directory = path.Join(spec.RemoteDirectory.Root, spec.RemoteDirectory.Path) + } else if request.Cwd != nil { resolved, err := s.resolveResource(caller.PluginID, workspace, *request.Cwd) if err != nil { return nil, failure(codeInvalidParams, "cwd is not a directory inside the workspace.") } - directory = resolved - } - spec := TerminalSpec{ - PluginID: caller.PluginID, Executable: request.Executable, Arguments: request.Arguments, - Title: request.Title, Directory: directory, Environment: request.Environment, - Show: request.Show == nil || *request.Show, RetainedBytes: budget, + spec.Directory = resolved } handle, refusal := s.reserveTerminal(caller, workspace, spec) if refusal != nil { @@ -276,14 +296,14 @@ func (s *Service) reserveTerminal(caller pluginhost.Caller, workspace WorkspaceC } registry.next++ handle := &terminalHandle{ - id: "t-" + strconv.Itoa(registry.next), caller: caller, contextID: workspace.ContextID, + id: "t-" + strconv.Itoa(registry.next), caller: caller, workspace: workspace, spec: spec, budget: spec.RetainedBytes, } // The handle counts against the limit from the start, so concurrent creates // cannot pass it together. handle.busy = true registry.byID[handle.id] = handle - handle.resource = s.resources.add(caller, workspace.ContextID, func() { s.disposeTerminal(handle) }) + handle.resource = s.resources.add(caller, workspace.ContextRef, func() { s.disposeTerminal(handle) }) return handle, nil } @@ -302,6 +322,13 @@ func (s *Service) launchTerminal(ctx context.Context, handle *terminalHandle, ge handle.mu.Lock() spec.RetainedBytes = handle.budget handle.mu.Unlock() + if spec.RemoteDirectory != nil { + spec.RemoteConnection = handle.workspace.remote.binding.CaptureConnection() + if spec.RemoteConnection == nil { + handle.leave() + return failure(CodeRemoteDisconnected, "The remote workspace is disconnected.") + } + } session, err := s.terminalHost.StartTerminal(ctx, handle.workspace.Path, spec) if err != nil { handle.mu.Lock() @@ -309,17 +336,19 @@ func (s *Service) launchTerminal(ctx context.Context, handle *terminalHandle, ge handle.mu.Unlock() return hostFailureOf(err) } - if ctx.Err() != nil { + handle.mu.Lock() + if handle.disposed || ctx.Err() != nil || (spec.RemoteConnection != nil && !spec.RemoteConnection.IsCurrent()) { + handle.busy = false + handle.mu.Unlock() // Cancelled or the context was lost while launching: nothing may keep running. closeCtx, cancel := context.WithTimeout(context.Background(), terminalCleanupTimeout) _ = session.Close(closeCtx, 0) cancel() - handle.mu.Lock() - handle.busy = false - handle.mu.Unlock() + if ctx.Err() == nil && spec.RemoteConnection != nil && !spec.RemoteConnection.IsCurrent() { + return failure(CodeRemoteDisconnected, "The remote workspace connection changed.") + } return failure(pluginhost.CodeCancelled, "The request was cancelled.") } - handle.mu.Lock() handle.generation = generation handle.session = session handle.exit = nil @@ -380,7 +409,7 @@ func (s *Service) lookupTerminal(ctx context.Context, ref ContextRef, id string) s.terminals.mu.Lock() handle := s.terminals.byID[id] s.terminals.mu.Unlock() - if handle == nil || handle.caller != caller || handle.contextID != workspace.ContextID { + if handle == nil || handle.caller != caller || handle.workspace.ContextRef != workspace.ContextRef { return nil, caller, failure(CodeNotFound, "No such terminal.") } return handle, caller, nil @@ -616,7 +645,7 @@ func (s *Service) handleTerminalOnExit(ctx context.Context, params json.RawMessa if handle.exitSub != "" { return nil, failure(CodePreconditionFailed, "The terminal already has an exit subscription.") } - id := s.resources.add(caller, handle.contextID, func() { + id := s.resources.add(caller, handle.workspace.ContextRef, func() { handle.mu.Lock() handle.exitSub = "" handle.mu.Unlock() diff --git a/desktop/internal/pluginservice/hostwatch.go b/desktop/internal/pluginservice/hostwatch.go new file mode 100644 index 0000000000..061b988c5c --- /dev/null +++ b/desktop/internal/pluginservice/hostwatch.go @@ -0,0 +1,208 @@ +package pluginservice + +import ( + "context" + "encoding/json" + "sync" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" +) + +const ( + maxWorkspaceWatches = 16 + maxWorkspaceWatchPaths = 1024 + maxWorkspaceWatchBytes = 128 * 1024 +) + +type workspaceWatchBatch struct { + connection *core.RemoteWorkspaceConnection + paths []string + bytes int + rescan bool +} + +type workspaceWatch struct { + workspace *core.RemoteWorkspace + request core.PluginWatchChangesRequest + wake chan struct{} + + mu sync.Mutex + pending workspaceWatchBatch +} + +func (s *Service) handleWorkspaceWatch(ctx context.Context, raw json.RawMessage) (json.RawMessage, *pluginhost.Failure) { + var request struct { + Context ContextRef `json:"context"` + Resource json.RawMessage `json:"resource"` + Recursive bool `json:"recursive"` + } + if err := decodeStrict(raw, &request); err != nil { + return nil, invalidParams(err) + } + _, session, refusal := s.backendCaller(ctx) + if refusal != nil { + return nil, refusal + } + caller, workspace, resource, connection, refusal := s.remoteFileResource(ctx, request.Context, request.Resource) + if refusal != nil { + return nil, refusal + } + result, refusal := s.readRemotePluginFile(ctx, workspace, connection, resource, core.PluginFileOperation{Kind: "watch"}) + if refusal != nil { + return nil, refusal + } + var target struct { + Path *string `json:"path"` + Directory bool `json:"directory"` + } + if err := json.Unmarshal(result, &target); err != nil || target.Path == nil { + return nil, failure(pluginhost.CodeHostFailure, "The workspace watch target could not be resolved.") + } + watch := &workspaceWatch{ + workspace: workspace.remote.binding, + request: core.PluginWatchChangesRequest{ + RootID: resource.RootID, HostRoot: workspace.remote.binding.RemoteRoot(), Path: *target.Path, + Directory: target.Directory, Recursive: request.Recursive, + }, + wake: make(chan struct{}, 1), + } + lifetime, stop := context.WithCancel(workspace.lifetime) + s.workspaceWatchesMu.Lock() + id := s.resources.addLimited(caller, workspace.ContextRef, func() { + stop() + s.workspaceWatchesMu.Lock() + delete(s.workspaceWatches, watch) + s.workspaceWatchesMu.Unlock() + }, maxWorkspaceWatches) + if id != "" { + s.workspaceWatches[watch] = struct{}{} + } + s.workspaceWatchesMu.Unlock() + if id == "" { + stop() + return nil, failure("plugin.host.limitExceeded", "The backend has reached its workspace watch limit.") + } + if lifetime.Err() != nil || session.isEnded() || ctx.Err() != nil || !connection.IsCurrent() { + s.resources.dispose(caller, id) + return nil, failure(pluginhost.CodeCancelled, "The workspace changed while opening the watch.") + } + go s.serveWorkspaceWatch(lifetime, caller, id, watch) + return marshalResult(map[string]string{"subscriptionID": id}) +} + +// PublishRemoteWorkspaceChanges feeds the already-running workbench watch to +// subscriptions of the same workspace. The window never waits for a plugin. +func (s *Service) PublishRemoteWorkspaceChanges(workspace *core.RemoteWorkspace, connection *core.RemoteWorkspaceConnection, paths []string, rescan bool) { + if connection == nil || (len(paths) == 0 && !rescan) { + return + } + s.workspaceWatchesMu.Lock() + defer s.workspaceWatchesMu.Unlock() + for watch := range s.workspaceWatches { + if watch.workspace == workspace { + watch.offer(connection, paths, rescan) + } + } +} + +func (w *workspaceWatch) offer(connection *core.RemoteWorkspaceConnection, paths []string, rescan bool) { + w.mu.Lock() + pending := &w.pending + if pending.connection != nil && !pending.connection.SameAttachment(connection) { + rescan = true + } + pending.connection = connection + pending.rescan = pending.rescan || rescan || !connection.IsCurrent() || + len(pending.paths)+len(paths) > maxWorkspaceWatchPaths + if !pending.rescan { + for _, path := range paths { + pending.bytes += len(path) + if pending.bytes > maxWorkspaceWatchBytes { + pending.rescan = true + break + } + } + } + if pending.rescan { + pending.paths, pending.bytes = nil, 0 + } else { + pending.paths = append(pending.paths, paths...) + } + w.mu.Unlock() + select { + case w.wake <- struct{}{}: + default: + } +} + +func (s *Service) serveWorkspaceWatch(lifetime context.Context, caller pluginhost.Caller, id string, watch *workspaceWatch) { + defer s.resources.dispose(caller, id) + var sequence uint64 + for { + select { + case <-lifetime.Done(): + return + case <-watch.wake: + } + watch.mu.Lock() + batch := watch.pending + watch.pending = workspaceWatchBatch{} + watch.mu.Unlock() + if batch.connection == nil { + continue + } + request := watch.request + request.HostPaths = batch.paths + request.RequiresRescan = batch.rescan || !batch.connection.IsCurrent() + if request.RequiresRescan { + request.HostPaths = nil + } + call, cancel := context.WithTimeout(lifetime, 5*time.Second) + event, err := s.kernel.PluginWatchChanges(call, request) + cancel() + if lifetime.Err() != nil { + return + } + if err != nil { + if s.WorkspaceWatchIssue != nil { + s.WorkspaceWatchIssue(lifetime, err) + } + // A failed projection or a concurrent reattachment invalidates the + // path details. A rescan is still useful on the original context. + event = workspaceWatchRescan(request.RootID) + } else if !batch.connection.IsCurrent() { + event = workspaceWatchRescan(request.RootID) + } + if len(event) == 0 || string(event) == "null" { + continue + } + sequence++ + params, err := json.Marshal(struct { + ID string `json:"subscriptionID"` + Sequence uint64 `json:"sequence"` + Event json.RawMessage `json:"event"` + }{id, sequence, event}) + if err != nil { + if s.WorkspaceWatchIssue != nil { + s.WorkspaceWatchIssue(lifetime, err) + } + return + } + call, cancel = context.WithTimeout(lifetime, 5*time.Second) + // Core records notification admission and terminal outcomes. + _, _ = s.kernel.SendPluginHostNotification(call, caller.SessionID, notifySubscription, params) + cancel() + } +} + +func workspaceWatchRescan(rootID string) json.RawMessage { + // rootID is a host-generated, JSON-encodable identifier. + event, _ := json.Marshal(struct { + RootID string `json:"rootID"` + ChangedPaths []string `json:"changedPaths"` + RequiresRescan bool `json:"requiresRescan"` + }{rootID, []string{}, true}) + return event +} diff --git a/desktop/internal/pluginservice/hostwatch_test.go b/desktop/internal/pluginservice/hostwatch_test.go new file mode 100644 index 0000000000..9ea137a135 --- /dev/null +++ b/desktop/internal/pluginservice/hostwatch_test.go @@ -0,0 +1,96 @@ +package pluginservice + +import ( + "context" + "encoding/json" + "slices" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" +) + +func TestRemoteWorkspaceWatchKeepsSubscriptionOwnershipAcrossAttachments(t *testing.T) { + kernel := &buildWatchKernel{events: make(chan buildWatchNotification, 8)} + kernel.pluginFile = func(_ context.Context, _ core.PluginFileRequest) (json.RawMessage, error) { + return json.RawMessage(`{"path":"src","directory":true}`), nil + } + kernel.pluginWatch = core.NewClient().PluginWatchChanges + service, err := Open(kernel, store.At(t.TempDir()), t.TempDir()) + if err != nil { + t.Fatal(err) + } + binding := core.NewRemoteWorkspace(t.TempDir(), "/home/dev/work", nil) + binding.Attach("live") + workspace := service.Contexts.OpenRemote(binding, "project", "c-test", core.RemotePlatform{OS: "linux", Arch: "x86_64"}, nil) + t.Cleanup(service.Contexts.CloseAll) + const plugin, session = "dev.lithe.test.watch", "session-test-watch" + runningActionSession(service, plugin, session) + caller := pluginhost.Caller{PluginID: plugin, SessionID: session} + root := service.Contexts.RootID(plugin, workspace.Path) + params, err := json.Marshal(map[string]any{ + "context": workspace.ContextRef, "resource": map[string]string{"rootID": root, "path": "src"}, + }) + if err != nil { + t.Fatal(err) + } + ctx := pluginhost.WithCaller(context.Background(), caller) + result, refusal := service.HostServices.Respond(ctx, pluginhost.MethodPrefix+"workspace/watch", params) + var subscription struct { + ID string `json:"subscriptionID"` + } + if err := json.Unmarshal(result, &subscription); refusal != nil || err != nil || subscription.ID == "" { + t.Fatalf("watch = %s, %+v, %v", result, refusal, err) + } + wait, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + await := func(sequence uint64, rescan bool, paths ...string) { + t.Helper() + select { + case note := <-kernel.events: + var message struct { + ID string `json:"subscriptionID"` + Sequence uint64 + Event struct { + RootID string + ChangedPaths []string + RequiresRescan bool + } + } + if err := json.Unmarshal(note.body, &message); err != nil { + t.Fatal(err) + } + if note.session != session || note.method != notifySubscription || message.ID != subscription.ID || + message.Sequence != sequence || message.Event.RootID != root || + message.Event.RequiresRescan != rescan || !slices.Equal(message.Event.ChangedPaths, paths) { + t.Fatalf("notification %s %s %s", note.session, note.method, note.body) + } + case <-wait.Done(): + t.Fatalf("waiting for watch event %d: %v", sequence, wait.Err()) + } + } + foreign := pluginhost.Caller{PluginID: plugin, SessionID: "other-session"} + service.resources.dispose(foreign, subscription.ID) + old := binding.CaptureConnection() + service.PublishRemoteWorkspaceChanges(binding, old, []string{"/home/dev/work/src/one"}, false) + await(1, false, "src/one") + + binding.Attach("replacement") + service.PublishRemoteWorkspaceChanges(binding, old, []string{"/home/dev/work/src/from-old"}, false) + await(2, true) + + current := binding.CaptureConnection() + service.PublishRemoteWorkspaceChanges(binding, current, []string{"/home/dev/work/src/two"}, false) + await(3, false, "src/two") + service.PublishRemoteWorkspaceChanges(binding, current, make([]string, maxWorkspaceWatchPaths+1), false) + await(4, true) + + service.resources.dispose(caller, subscription.ID) + service.workspaceWatchesMu.Lock() + defer service.workspaceWatchesMu.Unlock() + if len(service.workspaceWatches) != 0 { + t.Fatal("disposing the subscription left its watch registered") + } +} diff --git a/desktop/internal/pluginservice/lifecycle_test.go b/desktop/internal/pluginservice/lifecycle_test.go index b90dc55ada..3be2f372e5 100644 --- a/desktop/internal/pluginservice/lifecycle_test.go +++ b/desktop/internal/pluginservice/lifecycle_test.go @@ -5,6 +5,7 @@ import ( "errors" "os" "path/filepath" + "slices" "testing" "github.com/1lck/Lithe-IDEA/desktop/internal/core" @@ -116,3 +117,50 @@ func TestDisableStopsTheBackend(t *testing.T) { t.Fatalf("disable a plugin that is not installed = %v", err) } } + +type remoteDeploymentSweepKernel struct { + fakeKernel + retained []core.RemoteInstalledPluginVersion +} + +func (k *remoteDeploymentSweepKernel) SweepRemotePluginDeployments(_ context.Context, retained []core.RemoteInstalledPluginVersion) error { + k.retained = retained + return nil +} + +func TestSweepRemoteDeploymentsKeepsOnlyCurrentVersions(t *testing.T) { + const upgraded = "dev.lithe.test.upgraded" + const disabled = "dev.lithe.test.disabled" + kernel := &remoteDeploymentSweepKernel{} + root := t.TempDir() + service, err := Open(kernel, store.At(t.TempDir()), root) + if err != nil { + t.Fatal(err) + } + for _, pkg := range []core.RemoteInstalledPluginVersion{ + {PluginID: upgraded, Version: "1.2.0"}, + {PluginID: upgraded, Version: "1.10.0"}, + {PluginID: disabled, Version: "2.0.0"}, + } { + if err := os.MkdirAll(filepath.Join(root, pkg.PluginID, pkg.Version), 0o700); err != nil { + t.Fatal(err) + } + } + if err := service.Manager.SetEnabled(disabled, false); err != nil { + t.Fatal(err) + } + + if err := service.SweepRemoteDeployments(t.Context()); err != nil { + t.Fatal(err) + } + want := []core.RemoteInstalledPluginVersion{ + {PluginID: disabled, Version: "2.0.0"}, + {PluginID: upgraded, Version: "1.10.0"}, + } + if !slices.Equal(kernel.retained, want) { + t.Fatalf("retained remote deployments = %+v, want %+v", kernel.retained, want) + } + if _, err := os.Stat(filepath.Join(root, upgraded, "1.2.0")); err != nil { + t.Fatalf("the local package retained for rollback was removed: %v", err) + } +} diff --git a/desktop/internal/pluginservice/pages.go b/desktop/internal/pluginservice/pages.go index be4e10860a..33d20f716c 100644 --- a/desktop/internal/pluginservice/pages.go +++ b/desktop/internal/pluginservice/pages.go @@ -3,6 +3,7 @@ package pluginservice import ( "context" "crypto/sha256" + "encoding/base64" "encoding/hex" "encoding/json" "errors" @@ -10,6 +11,8 @@ import ( "path/filepath" "time" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" ) @@ -30,25 +33,107 @@ func (s *Service) CallFromPage(ctx context.Context, pluginID, function string, p if !ok { return nil, ErrContextExpired } - reference, err := json.Marshal(workspace.ContextRef) + return s.CallFromWorkspace(ctx, pluginID, function, params, workspace.ContextRef, progress) +} + +// CallFromWorkspace invokes the local backend for the captured workspace generation. +func (s *Service) CallFromWorkspace(ctx context.Context, pluginID, function string, params json.RawMessage, ref ContextRef, progress func(json.RawMessage)) (json.RawMessage, error) { + workspace, err := s.Contexts.Lookup(ref) + if err != nil { + return nil, err + } + var connection *core.RemoteWorkspaceConnection + if workspace.remote.binding != nil { + connection = workspace.remote.binding.CaptureConnection() + if connection == nil { + return nil, &core.Error{Code: core.CodeConnectionClosed, Message: "The remote workspace is disconnected."} + } + bound, cancel := context.WithCancel(ctx) + defer cancel() + stopClose := context.AfterFunc(workspace.lifetime, cancel) + defer stopClose() + stopDetach := connection.AfterDetach(cancel) + defer stopDetach() + ctx = bound + } + reference, err := json.Marshal(ref) if err != nil { return nil, err } - return s.Host.CallWithProgress(ctx, pluginID, function, params, reference, pageCallTimeout, progress) + result, err := s.Host.CallWithProgress(core.WithoutRemoteWorkspace(ctx), pluginID, function, params, reference, pageCallTimeout, progress) + if _, lookupErr := s.Contexts.Lookup(ref); lookupErr != nil { + return nil, lookupErr + } + if connection != nil && !connection.IsCurrent() { + return nil, &core.Error{Code: core.CodeConnectionClosed, Message: "The remote workspace connection changed."} + } + return result, err +} + +// PageDocument is a scoped editor read tied to the attachment that answered it. +type PageDocument struct { + Path string + Data []byte + Connection *core.RemoteWorkspaceConnection +} + +func (s *Service) ReadPageDocument(ctx context.Context, pluginID string, ref ContextRef, path string, limit int64) (PageDocument, *pluginhost.Failure) { + workspace, err := s.Contexts.Lookup(ref) + if err != nil { + return PageDocument{}, contextFailure(err) + } + if workspace.remote.binding == nil { + return PageDocument{}, unsupportedRemoteWorkspace() + } + connection := workspace.remote.binding.CaptureConnection() + if connection == nil { + return PageDocument{}, failure(CodeRemoteDisconnected, "The remote workspace is disconnected.") + } + raw, refusal := s.readRemotePluginFile(ctx, workspace, connection, pluginWorkspaceResource{ + Path: &path, RootID: s.Contexts.RootID(pluginID, workspace.Path), + }, core.PluginFileOperation{Kind: "openDocument", MaximumBytes: &limit}) + if refusal != nil { + return PageDocument{}, refusal + } + var result struct { + Path string `json:"path"` + Base64 string `json:"base64"` + IsTruncated bool `json:"isTruncated"` + } + if err := json.Unmarshal(raw, &result); err != nil || result.Path == "" { + return PageDocument{}, failure(pluginhost.CodeHostFailure, "The host returned an invalid document.") + } + if result.IsTruncated { + return PageDocument{}, failure("plugin.host.limitExceeded", "The document exceeds the editor's read budget.") + } + data, err := base64.StdEncoding.DecodeString(result.Base64) + if err != nil { + return PageDocument{}, failure(pluginhost.CodeHostFailure, "The host returned an invalid document.") + } + return PageDocument{Path: result.Path, Data: data, Connection: connection}, nil } // pageStatePath is where one window's page state for one workspace is kept: // in the plugin's state directory, outside its package and the application // bundle. The window ID is a digest, so it is one path component. -func (s *Service) pageStatePath(pluginID, windowID, workspacePath string) string { +func (s *Service) pageStatePath(pluginID, windowID string, workspace WorkspaceContext) string { sum := sha256.Sum256([]byte(windowID)) - return filepath.Join(pluginpkg.StateRoot(s.Root, pluginID), "pages", "workspaces", WorkspaceKey(workspacePath), hex.EncodeToString(sum[:])[:24]+".json") + key := WorkspaceKey(workspace.Path) + if workspace.authorityKind() == "remote" { + identity := sha256.Sum256([]byte(workspace.remote.connectionID + "\x00" + workspace.remote.hostPath)) + key = "remote-" + hex.EncodeToString(identity[:])[:24] + } + return filepath.Join(pluginpkg.StateRoot(s.Root, pluginID), "pages", "workspaces", key, hex.EncodeToString(sum[:])[:24]+".json") } // PageState returns the stored state of a window, nil when there is none. // A state over limit bytes is treated as none. -func (s *Service) PageState(pluginID, windowID, workspacePath string, limit int) ([]byte, error) { - path := s.pageStatePath(pluginID, windowID, workspacePath) +func (s *Service) PageState(pluginID, windowID string, ref ContextRef, limit int) ([]byte, error) { + workspace, err := s.Contexts.Lookup(ref) + if err != nil { + return nil, err + } + path := s.pageStatePath(pluginID, windowID, workspace) info, err := os.Stat(path) if errors.Is(err, os.ErrNotExist) { return nil, nil @@ -64,8 +149,12 @@ func (s *Service) PageState(pluginID, windowID, workspacePath string, limit int) // SetPageState stores the state of a window, or removes it for nil. It // writes a temporary file and renames it, so a reader never sees half a state. -func (s *Service) SetPageState(pluginID, windowID, workspacePath string, state []byte, limit int) error { - path := s.pageStatePath(pluginID, windowID, workspacePath) +func (s *Service) SetPageState(pluginID, windowID string, ref ContextRef, state []byte, limit int) error { + workspace, err := s.Contexts.Lookup(ref) + if err != nil { + return err + } + path := s.pageStatePath(pluginID, windowID, workspace) if state == nil { if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { return err @@ -90,5 +179,8 @@ func (s *Service) SetPageState(pluginID, windowID, workspacePath string, state [ if err := temporary.Close(); err != nil { return err } + if _, err := s.Contexts.Lookup(ref); err != nil { + return err + } return os.Rename(temporary.Name(), path) } diff --git a/desktop/internal/pluginservice/pages_test.go b/desktop/internal/pluginservice/pages_test.go index c543c17b94..e7362e01b6 100644 --- a/desktop/internal/pluginservice/pages_test.go +++ b/desktop/internal/pluginservice/pages_test.go @@ -74,27 +74,65 @@ func TestPageStateIsKeptPerWindowAndWorkspace(t *testing.T) { t.Fatal(err) } const limit = 16 - if state, err := service.PageState("a", "a.window", "/work/one", limit); err != nil || state != nil { + t.Cleanup(service.Contexts.CloseAll) + first := service.Contexts.Open(t.TempDir()) + second := service.Contexts.Open(t.TempDir()) + if state, err := service.PageState("a", "a.window", first.ContextRef, limit); err != nil || state != nil { t.Fatalf("empty state = %q %v", state, err) } - if err := service.SetPageState("a", "a.window", "/work/one", []byte(`{"tab":1}`), limit); err != nil { + if err := service.SetPageState("a", "a.window", first.ContextRef, []byte(`{"tab":1}`), limit); err != nil { t.Fatal(err) } - if state, err := service.PageState("a", "a.window", "/work/one", limit); err != nil || string(state) != `{"tab":1}` { + if state, err := service.PageState("a", "a.window", first.ContextRef, limit); err != nil || string(state) != `{"tab":1}` { t.Fatalf("state = %q %v", state, err) } - for _, other := range [][2]string{{"a.window", "/work/two"}, {"a.other", "/work/one"}} { - if state, _ := service.PageState("a", other[0], other[1], limit); state != nil { - t.Fatalf("%v saw another window's state: %q", other, state) + for _, other := range []struct { + window string + ref ContextRef + }{{"a.window", second.ContextRef}, {"a.other", first.ContextRef}} { + if state, err := service.PageState("a", other.window, other.ref, limit); err != nil || state != nil { + t.Fatalf("state for %v = %q %v", other, state, err) } } - if err := service.SetPageState("a", "a.window", "/work/one", []byte(`"0123456789abcdef"`), limit); !errors.Is(err, ErrPageStateTooLarge) { + if err := service.SetPageState("a", "a.window", first.ContextRef, []byte(`"0123456789abcdef"`), limit); !errors.Is(err, ErrPageStateTooLarge) { t.Fatalf("oversized state = %v", err) } - if err := service.SetPageState("a", "a.window", "/work/one", nil, limit); err != nil { + if err := service.SetPageState("a", "a.window", first.ContextRef, nil, limit); err != nil { t.Fatal(err) } - if _, err := os.Stat(service.pageStatePath("a", "a.window", "/work/one")); !errors.Is(err, os.ErrNotExist) { + if _, err := os.Stat(service.pageStatePath("a", "a.window", first)); !errors.Is(err, os.ErrNotExist) { t.Fatalf("cleared state remains: %v", err) } } + +func TestRemotePageDocumentUsesTheOriginalAttachment(t *testing.T) { + service := openHostService(t) + binding := core.NewRemoteWorkspace(t.TempDir(), "/home/dev/project", nil) + binding.Attach("session") + workspace := service.Contexts.OpenRemote(binding, "project", "connection", core.RemotePlatform{OS: "linux", Arch: "x86_64"}, nil) + t.Cleanup(service.Contexts.CloseAll) + + const path = "/home/dev/project/src/main.txt" + const plugin = "dev.lithe.test.page" + replace := false + service.kernel.(*fakeKernel).pluginFile = func(ctx context.Context, request core.PluginFileRequest) (json.RawMessage, error) { + if core.RemoteWorkspaceOf(ctx) != binding || request.Path != path || + request.Operation.Kind != "openDocument" || request.RootID != service.Contexts.RootID(plugin, workspace.Path) { + t.Fatalf("unexpected document request: %+v", request) + } + if replace { + binding.Detach() + binding.Attach("session") + } + return json.RawMessage(`{"path":"src/main.txt","base64":"dGV4dA==","isTruncated":false}`), nil + } + document, refusal := service.ReadPageDocument(context.Background(), plugin, workspace.ContextRef, path, 64) + if refusal != nil || document.Path != "src/main.txt" || string(document.Data) != "text" || !document.Connection.IsCurrent() { + t.Fatalf("page document = %+v, refusal = %+v", document, refusal) + } + replace = true + document, refusal = service.ReadPageDocument(context.Background(), plugin, workspace.ContextRef, path, 64) + if refusal == nil || refusal.Code != CodeRemoteDisconnected || document.Data != nil { + t.Fatalf("old attachment document = %+v, refusal = %+v", document, refusal) + } +} diff --git a/desktop/internal/pluginservice/pluginservice.go b/desktop/internal/pluginservice/pluginservice.go index df499026e0..7f5a553c80 100644 --- a/desktop/internal/pluginservice/pluginservice.go +++ b/desktop/internal/pluginservice/pluginservice.go @@ -41,6 +41,9 @@ var ErrAssembly = errors.New("plugin service cannot be assembled") // satisfies it. type Kernel interface { PlanPluginSettingsAction(context.Context, core.PluginSettingsActionRequest) (core.PluginSettingsActionPlan, error) + ReadPluginFile(context.Context, core.PluginFileRequest) (json.RawMessage, error) + PluginWatchChanges(context.Context, core.PluginWatchChangesRequest) (json.RawMessage, error) + ReadWorkspaceConfiguration(context.Context, string, int64) (*string, error) pluginhost.ManifestValidator pluginbackend.Kernel pluginsettings.Kernel @@ -71,6 +74,8 @@ type Service struct { ToolchainIssue func(context.Context, error) // BuildConfigurationIssue records native failures opening or rebinding configuration watches. BuildConfigurationIssue func(context.Context, error) + // WorkspaceWatchIssue records failures projecting remote workspace watch events. + WorkspaceWatchIssue func(context.Context, error) // providers2 holds the editor provider registrations of the window (hostproviders.go). providers2 *editorProviderBindings // actions holds the editor action registrations of the window (hostactions.go). @@ -114,7 +119,9 @@ type Service struct { virtualHost VirtualDocumentHost providers *contentProviders // resources are the subscriptions, providers and terminals backends hold. - resources *hostResources + resources *hostResources + workspaceWatchesMu sync.Mutex + workspaceWatches map[*workspaceWatch]struct{} // Runs owns the processes backends start through run/start. Runs *Runs // LanguageTool resolves an optional installation for a backend-resolved @@ -201,6 +208,7 @@ func open(kernel Kernel, preferences *store.Store, root string, first bool) (*Se kernel: kernel, preferences: preferences, resources: newHostResources(), + workspaceWatches: make(map[*workspaceWatch]struct{}), ledger: ledger, messages: newMessageLimiter(), RuntimeDownloader: marketplace.NewArchiveDownloader(nil), diff --git a/desktop/internal/pluginservice/pluginservice_test.go b/desktop/internal/pluginservice/pluginservice_test.go index d3b10fe849..e15a30221b 100644 --- a/desktop/internal/pluginservice/pluginservice_test.go +++ b/desktop/internal/pluginservice/pluginservice_test.go @@ -16,6 +16,8 @@ import ( // fakeKernel records what the stack asked Core to do. type fakeKernel struct { + pluginFile func(context.Context, core.PluginFileRequest) (json.RawMessage, error) + pluginWatch func(context.Context, core.PluginWatchChangesRequest) (json.RawMessage, error) review core.MarketplaceReview reviewErr error reviewManifest json.RawMessage @@ -40,6 +42,24 @@ type fakeKernel struct { recordErr error } +func (k *fakeKernel) ReadPluginFile(ctx context.Context, request core.PluginFileRequest) (json.RawMessage, error) { + if k.pluginFile == nil { + return nil, &core.Error{Code: core.CodeNotSupported, Message: "no file fixture"} + } + return k.pluginFile(ctx, request) +} + +func (k *fakeKernel) PluginWatchChanges(ctx context.Context, request core.PluginWatchChangesRequest) (json.RawMessage, error) { + if k.pluginWatch == nil { + return nil, &core.Error{Code: core.CodeNotSupported, Message: "no watch fixture"} + } + return k.pluginWatch(ctx, request) +} + +func (k *fakeKernel) ReadWorkspaceConfiguration(context.Context, string, int64) (*string, error) { + return nil, &core.Error{Code: core.CodeNotSupported, Message: "no remote settings fixture"} +} + func (k *fakeKernel) ValidatePluginManifest(_ context.Context, manifest json.RawMessage, _ map[string][]int) (json.RawMessage, error) { return manifest, nil } diff --git a/desktop/internal/pluginservice/remote_deployment.go b/desktop/internal/pluginservice/remote_deployment.go new file mode 100644 index 0000000000..8a772857bb --- /dev/null +++ b/desktop/internal/pluginservice/remote_deployment.go @@ -0,0 +1,283 @@ +package pluginservice + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "io" + "os" + "path" + "path/filepath" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" + "github.com/1lck/Lithe-IDEA/desktop/internal/plugininstall" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginruntime" + "github.com/1lck/Lithe-IDEA/desktop/internal/plugintrust" +) + +type remoteDeploymentKernel interface { + SelectMarketplaceRemoteVariant(context.Context, core.MarketplaceRemoteVariantRequest) (core.MarketplaceAvailability, error) + VerifyMarketplaceRemoteVariant(context.Context, core.MarketplaceVariantReview) (json.RawMessage, error) + PlanMarketplaceRemoteDeployment(context.Context, core.MarketplaceDeploymentRequest) (core.MarketplaceDeployment, error) + LookupRemotePluginDeployment(context.Context, core.RemotePluginDeployment) (string, error) + CreateRemoteRuntimeStaging(context.Context, string) (string, error) + ReleaseRemoteRunDirectory(context.Context, string) error + CreateRemotePluginDirectory(context.Context, string) error + UploadRemotePluginFile(context.Context, string, string, string, uint32) error + CommitRemotePluginDeployment(context.Context, core.RemotePluginDeployment, string) (string, error) +} + +var _ remoteDeploymentKernel = (*core.Client)(nil) + +// SweepRemoteDeployments retains the current installed version of each plugin, +// including disabled ones. The host protects older versions with active leases. +func (s *Service) SweepRemoteDeployments(ctx context.Context) error { + kernel, ok := s.kernel.(interface { + SweepRemotePluginDeployments(context.Context, []core.RemoteInstalledPluginVersion) error + }) + if !ok { + return &core.Error{Code: core.CodeNotSupported, Message: "Remote plugin deployment is unavailable."} + } + packages, err := s.CurrentInstalled(ctx) + if err != nil { + return err + } + installed := make([]core.RemoteInstalledPluginVersion, 0, len(packages)) + for _, pkg := range packages { + installed = append(installed, core.RemoteInstalledPluginVersion{PluginID: pkg.Installed.ID, Version: pkg.Installed.Version}) + } + if err := ctx.Err(); err != nil { + return err + } + return kernel.SweepRemotePluginDeployments(ctx, installed) +} + +// RemoteDeployment binds an installed release to the target captured for a +// process launch. The runner asks for its files only after Core plans placement. +func (s *Service) RemoteDeployment(installed pluginpkg.Installed, manifest json.RawMessage, target core.RemotePlatform, progress func(pluginruntime.Progress)) func(context.Context, []string) (string, error) { + return func(ctx context.Context, required []string) (string, error) { + return s.prepareRemoteDeployment(ctx, installed, manifest, target, required, progress) + } +} + +func (s *Service) prepareRemoteDeployment(ctx context.Context, installed pluginpkg.Installed, manifest json.RawMessage, target core.RemotePlatform, required []string, progress func(pluginruntime.Progress)) (directory string, err error) { + kernel, ok := s.kernel.(remoteDeploymentKernel) + if !ok { + return "", &core.Error{Code: core.CodeNotSupported, Message: "Remote plugin deployment is unavailable."} + } + approval, found, err := s.Manager.Approval(installed.ID, installed.Version) + if err != nil { + return "", err + } + local := ArchivePlatform() + useInstalled := found && approval.SealedTreeSHA256 != "" && local.OS == target.OS && local.Arch == target.Arch + capabilities := s.Capabilities().Clone() + review := core.MarketplaceVariantReview{ + InstalledManifest: manifest, PluginID: installed.ID, Version: installed.Version, + ApprovedPrograms: approval.ApprovedPrograms, HostCapabilities: capabilities, + } + request := core.MarketplaceDeploymentRequest{ + Manifest: manifest, Target: target, RequiredPaths: required, + } + var selection core.MarketplaceAvailability + if useInstalled { + request.InstalledTreeSHA256 = approval.SealedTreeSHA256 + } else { + if !found || approval.Source != plugintrust.Marketplace || approval.ArchiveSHA256 == "" || approval.MarketplaceIndexURL == "" { + return "", &core.MarketplaceRejection{ + Code: "plugin.remote.variantUnavailable", Message: "No approved package is available for the workspace host.", + } + } + index := marketplace.New(nil, s.RuntimeDownloader.HTTPClient()) + selection, err = index.FetchRemoteVariant(core.WithoutRemoteWorkspace(ctx), approval.MarketplaceIndexURL, core.MarketplaceRemoteVariantRequest{ + PluginID: installed.ID, Version: installed.Version, InstalledPlatform: marketplace.CurrentPlatform(), + InstalledSHA256: approval.ArchiveSHA256, Repository: approval.MarketplaceRepository, + Target: target, HostCapabilities: capabilities, + }, kernel.SelectMarketplaceRemoteVariant) + if err != nil { + return "", err + } + request.ArchiveSHA256 = selection.SHA256 + } + plan, err := kernel.PlanMarketplaceRemoteDeployment(ctx, request) + if err != nil { + return "", err + } + key := core.RemotePluginDeployment{PluginID: installed.ID, Version: installed.Version, SHA256: plan.SHA256} + var variant plugininstall.RemoteVariant + defer func() { + if variant.Directory != "" { + s.recordDeploymentCleanup(ctx, os.RemoveAll(variant.Directory)) + } + }() + if useInstalled { + // Verify the installation before using either its bytes or an existing + // deployment. Its manifest and mode bits may have changed on disk. + variant, err = plugininstall.SnapshotInstalledVariant(ctx, installed.Path, approval.SealedTreeSHA256, review, kernel.VerifyMarketplaceRemoteVariant) + if err != nil { + return "", err + } + } + + // The lookup follows provenance validation so a package under the same + // version cannot claim another archive's deployment. + directory, err = kernel.LookupRemotePluginDeployment(ctx, key) + if err != nil || directory != "" { + return directory, err + } + + if !useInstalled { + variant, err = s.extractRemoteVariant(ctx, kernel, selection, review, progress) + if err != nil { + return "", err + } + } + request.ArchiveFiles = make([]string, 0, len(variant.Files)) + for _, file := range variant.Files { + request.ArchiveFiles = append(request.ArchiveFiles, file.Path) + } + selected, err := kernel.PlanMarketplaceRemoteDeployment(ctx, request) + if err != nil { + return "", err + } + if selected.SHA256 != key.SHA256 || len(selected.Paths) == 0 { + return "", errors.New("the deployment plan changed after package verification") + } + return s.publishRemoteDeployment(ctx, kernel, key, selected.Paths, variant) +} + +func (s *Service) extractRemoteVariant(ctx context.Context, kernel remoteDeploymentKernel, selection core.MarketplaceAvailability, review core.MarketplaceVariantReview, progress func(pluginruntime.Progress)) (plugininstall.RemoteVariant, error) { + var variant plugininstall.RemoteVariant + consume := func(archivePath string) error { + var err error + variant, err = plugininstall.ExtractRemoteVariant(ctx, archivePath, selection.SHA256, "", review, kernel.VerifyMarketplaceRemoteVariant) + return err + } + cache, cacheErr := marketplace.NewRemoteArchiveCache() + cacheAvailable := cacheErr == nil + if cacheAvailable { + var used bool + used, cacheErr = cache.Read(ctx, selection.SHA256, consume) + if variant.Directory != "" { + s.recordDeploymentCleanup(ctx, cacheErr) + return variant, nil + } + // A checksum failure is repairable by downloading again. A different + // manifest or review failure will recur for that same digest. + if used && !errors.Is(cacheErr, plugininstall.ErrArchiveDigest) && !errors.Is(cacheErr, os.ErrNotExist) { + return variant, cacheErr + } + } + if err := ctx.Err(); err != nil { + return variant, err + } + if cacheErr != nil { + s.recordDeploymentCleanup(ctx, cacheErr) + } + + downloads := marketplace.NewArchiveSession(s.RuntimeDownloader) + defer func() { s.recordDeploymentCleanup(ctx, downloads.Close()) }() + archive, err := downloads.Download(ctx, selection, func(update marketplace.ArchiveProgress) { + if progress != nil { + progress(pluginruntime.Progress{ID: review.PluginID, Phase: "downloading", Received: update.Received, Total: update.Total}) + } + }) + if err != nil { + return variant, err + } + defer func() { s.recordDeploymentCleanup(ctx, archive.Discard()) }() + if err := consume(archive.Path()); err != nil { + return variant, err + } + if cacheAvailable { + s.recordDeploymentCleanup(ctx, cache.Store(ctx, selection.SHA256, archive)) + } + return variant, nil +} + +func (s *Service) publishRemoteDeployment(ctx context.Context, kernel remoteDeploymentKernel, key core.RemotePluginDeployment, required []string, variant plugininstall.RemoteVariant) (string, error) { + files := make(map[string]pluginpkg.File, len(variant.Files)) + for _, file := range variant.Files { + files[file.Path] = file + } + for _, name := range required { + if _, found := files[name]; !found { + return "", &core.MarketplaceRejection{ + Code: "plugin.remote.invalidDeployment", Message: "The deployment plan names a file outside the verified package inventory.", + } + } + } + id := "plugin-" + rand.Text() + defer func() { + cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + defer cancel() + s.recordDeploymentCleanup(ctx, kernel.ReleaseRemoteRunDirectory(cleanup, id)) + }() + staging, err := kernel.CreateRemoteRuntimeStaging(ctx, id) + if err != nil { + return "", err + } + staging = path.Join(staging, "package") + if err := kernel.CreateRemotePluginDirectory(ctx, staging); err != nil { + return "", err + } + created := map[string]bool{staging: true} + for _, name := range required { + source := filepath.Join(variant.Directory, filepath.FromSlash(name)) + destination := path.Join(staging, name) + parent := path.Dir(destination) + if !created[parent] { + if err := kernel.CreateRemotePluginDirectory(ctx, parent); err != nil { + return "", err + } + created[parent] = true + } + digest, err := hashDeploymentFile(ctx, source) + if err != nil { + return "", err + } + // Keep the owner execute bit from the zip on Windows as well. + mode := uint32(0o400 | files[name].Mode.Perm()&0o100) + if err := kernel.UploadRemotePluginFile(ctx, source, destination, digest, mode); err != nil { + return "", err + } + } + return kernel.CommitRemotePluginDeployment(ctx, key, id) +} + +func hashDeploymentFile(ctx context.Context, source string) (string, error) { + if err := ctx.Err(); err != nil { + return "", err + } + file, err := os.Open(source) + if err != nil { + return "", err + } + hash := sha256.New() + _, copyErr := io.Copy(hash, deploymentReader{ctx, file}) + return hex.EncodeToString(hash.Sum(nil)), errors.Join(copyErr, file.Close()) +} + +type deploymentReader struct { + context.Context + io.Reader +} + +func (r deploymentReader) Read(buffer []byte) (int, error) { + if err := r.Err(); err != nil { + return 0, err + } + return r.Reader.Read(buffer) +} + +func (s *Service) recordDeploymentCleanup(ctx context.Context, err error) { + if err != nil && s.RuntimeIssue != nil { + s.RuntimeIssue(ctx, err) + } +} diff --git a/desktop/internal/pluginservice/remote_runs.go b/desktop/internal/pluginservice/remote_runs.go new file mode 100644 index 0000000000..92c03b0692 --- /dev/null +++ b/desktop/internal/pluginservice/remote_runs.go @@ -0,0 +1,226 @@ +package pluginservice + +import ( + "context" + "crypto/rand" + "encoding/json" + "errors" + "fmt" + "path" + + "github.com/1lck/Lithe-IDEA/desktop/internal/buildprocess" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginmanager" +) + +type remoteRunKernel interface { + buildprocess.RemoteRunner + CreateRemoteRunDirectory(context.Context, string) (string, error) + WriteRemoteRunFile(context.Context, string, []byte) error + ReleaseRemoteRunDirectory(context.Context, string) error +} + +type remoteRun struct { + workspace WorkspaceContext + connection *core.RemoteWorkspaceConnection +} + +func (r *Runs) captureRemoteRun(workspace WorkspaceContext) (*remoteRun, *pluginhost.Failure) { + if workspace.authorityKind() != "remote" { + return nil, nil + } + binding := workspace.remote.binding + if binding == nil { + return nil, unsupportedRemoteWorkspace() + } + connection := binding.CaptureConnection() + if connection == nil { + return nil, failure(CodeRemoteDisconnected, "The remote workspace is disconnected.") + } + return &remoteRun{workspace: workspace, connection: connection}, nil +} + +func (remote *remoteRun) refusal(ctx context.Context) *pluginhost.Failure { + if remote.workspace.lifetime.Err() != nil { + return contextFailure(ErrContextExpired) + } + if !remote.connection.IsCurrent() { + return failure(CodeRemoteDisconnected, "The remote workspace connection changed.") + } + if err := ctx.Err(); err != nil { + return hostFailureOf(err) + } + if remote.workspace.codeAllowed == nil || !remote.workspace.codeAllowed() { + return failure(CodePermissionDenied, "Running a plugin command requires a trusted remote workspace.") + } + return nil +} + +func (r *Runs) startRemote(ctx, lifetime context.Context, run *hostRun, remote *remoteRun, entry pluginmanager.Entry, manifest json.RawMessage, request runStartParams, params json.RawMessage, output func(buildprocess.Stream, string)) (runProcess, bool, *pluginhost.Failure) { + host, ok := r.service.kernel.(remoteRunKernel) + if !ok { + return nil, false, unsupportedRemoteWorkspace() + } + lifetime = remote.connection.Context(lifetime) + setup, cancelSetup := context.WithCancel(remote.connection.Context(ctx)) + defer cancelSetup() + stopSetup := context.AfterFunc(lifetime, cancelSetup) + defer stopSetup() + setup = core.WithProjectCodeAllowed(setup, func() bool { + return remote.refusal(ctx) == nil + }) + + temporary := "" + if len(request.TemporaryFiles) != 0 { + id := "run-" + rand.Text() + run.cleanup = func() { + cleanup, cancel := context.WithTimeout(context.WithoutCancel(lifetime), runStopTimeout) + defer cancel() + err := host.ReleaseRemoteRunDirectory(cleanup, id) + if err != nil { + r.recordRunIssue(cleanup, fmt.Errorf("release remote run directory: %w", err)) + } + } + var err error + temporary, err = host.CreateRemoteRunDirectory(setup, id) + if err != nil { + return nil, false, remote.startFailure(ctx, err) + } + } + start, err := r.service.kernel.DecodeRunStart(setup, manifest, run.workspace.Path, temporary, params) + if err != nil { + return nil, false, remote.startFailure(ctx, err) + } + if refusal := remote.refusal(ctx); refusal != nil { + return nil, false, refusal + } + launch := start.Debug != nil && start.Debug.Target.Kind == "launch" + if start.Placement == core.ProcessPlacementUI || (start.Debug != nil && !launch && start.Debug.Target.Kind != "connection") { + return nil, false, unsupportedRemoteWorkspace() + } + if launch && r.LaunchDebug == nil { + return nil, false, failure("plugin.host.unavailable", "This host starts no debug sessions.") + } + executable, refusal := r.resolveRemoteRunExecutable(setup, entry, remote, manifest, start) + if current := remote.refusal(ctx); current != nil { + return nil, false, current + } + if refusal != nil { + return nil, false, refusal + } + for _, file := range start.TemporaryFiles { + data, err := file.Bytes() + if err != nil { + return nil, false, remote.startFailure(ctx, err) + } + if err := host.WriteRemoteRunFile(setup, file.Path, data); err != nil { + return nil, false, remote.startFailure(ctx, err) + } + } + + environment := runEnvironment(executable.Environment, start.Environment) + pathPrepend := executable.PathPrepend + if _, explicit := start.Environment["PATH"]; explicit { + pathPrepend = nil + } + if refusal := remote.refusal(ctx); refusal != nil { + return nil, false, refusal + } + run.start = start + cwd := core.RemoteScopedDirectory{Root: remote.workspace.remote.hostPath, Path: start.WorkingDirectory} + if launch { + resolver, ok := host.(interface { + ResolveRemoteDebugLaunch(context.Context, core.RemoteScopedDirectory, *string, []string) (core.RemoteDebugLaunch, error) + }) + if !ok { + return nil, false, unsupportedRemoteWorkspace() + } + var pathOverride *string + if value, ok := environment["PATH"]; ok { + pathOverride = &value + } + facts, err := resolver.ResolveRemoteDebugLaunch(setup, cwd, pathOverride, pathPrepend) + if err != nil { + return nil, false, remote.startFailure(ctx, err) + } + if !path.IsAbs(facts.Cwd) { + return nil, false, remote.startFailure(ctx, errors.New("the remote launch directory is invalid")) + } + if facts.Path != nil { + environment["PATH"] = *facts.Path + } + if refusal := remote.refusal(ctx); refusal != nil { + return nil, false, refusal + } + process, err := r.startDebugLaunch(setup, run, executable.Path, facts.Cwd, environment) + if err != nil { + return nil, false, remote.startFailure(ctx, err) + } + return process, true, nil + } + process, err := buildprocess.StartRemote(setup, lifetime, host, core.RemoteProcessOpen{ + Argv: append([]string{executable.Path}, start.Arguments...), + ScopedCwd: &cwd, + Environment: "login", + Env: environment, + PathPrepend: pathPrepend, + Label: core.NewRemoteResourceLabel("run", start.Label), + }, output) + if err != nil { + return nil, false, remote.startFailure(ctx, err) + } + return process, false, nil +} + +func (r *Runs) resolveRemoteRunExecutable(ctx context.Context, entry pluginmanager.Entry, remote *remoteRun, manifest json.RawMessage, start core.RunStart) (RunExecutable, *pluginhost.Failure) { + switch start.Executable.Kind { + case "toolchain": + return r.resolveTool(ctx, remote.workspace.Path, start.WorkingDirectory, start.Executable.Value) + case "packaged": + deploy := r.service.RemoteDeployment(entry.Installed, manifest, remote.workspace.remote.platform, nil) + directory, err := deploy(ctx, []string{start.Executable.Value}) + if err != nil { + return RunExecutable{}, remote.startFailure(ctx, err) + } + executable := path.Join(directory, start.Executable.Value) + return RunExecutable{Path: executable}, nil + default: + return RunExecutable{}, failure(codeInvalidParams, "The executable kind is unknown.") + } +} + +func (remote *remoteRun) startFailure(ctx context.Context, err error) *pluginhost.Failure { + if refusal := remote.refusal(ctx); refusal != nil { + return refusal + } + var coreErr *core.Error + if errors.As(err, &coreErr) { + switch coreErr.Code { + case core.CodeConnectionClosed: + return failure(CodeRemoteDisconnected, "The remote workspace is disconnected.") + case core.CodeInvalidRequest, core.CodeWorkspaceNotFound: + return failure(codeInvalidParams, coreErr.Message) + case core.CodePermissionDenied: + return failure(CodePermissionDenied, coreErr.Message) + case core.CodeProcessFailed: + var details struct { + RemoteCode string `json:"remoteCode"` + } + if json.Unmarshal([]byte(coreErr.Details), &details) == nil { + switch details.RemoteCode { + case "UNKNOWN_METHOD", "UNSUPPORTED": + return unsupportedRemoteWorkspace() + case "INVALID_PATH", "NOT_A_DIRECTORY": + return failure(codeInvalidParams, coreErr.Message) + } + } + } + } + return runStartFailure(err) +} + +func remoteRunDisconnected(err error) bool { + var detail *core.Error + return errors.As(err, &detail) && detail.Code == core.CodeConnectionClosed +} diff --git a/desktop/internal/pluginservice/remote_runs_test.go b/desktop/internal/pluginservice/remote_runs_test.go new file mode 100644 index 0000000000..d1b56f8249 --- /dev/null +++ b/desktop/internal/pluginservice/remote_runs_test.go @@ -0,0 +1,279 @@ +package pluginservice + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "reflect" + "sync/atomic" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginbackend" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" +) + +const ( + remoteRunRoot = "/home/dev/project" + remoteScratch = "/home/dev/.lithe-server/plugin-runs/fixture" + remotePayload = "AP8=" +) + +type remoteRunFixture struct { + runKernel + notifications chan string + start core.RunStart + spawn func(context.Context, core.RemoteProcessOpen, core.RemoteProcessEvents) (core.RemoteProcessExit, error) + write func(string, []byte) error + scratch string + released chan string +} + +func (k *remoteRunFixture) SendPluginHostNotification(ctx context.Context, session, method string, params json.RawMessage) (bool, error) { + if k.notifications == nil { + return false, nil + } + select { + case k.notifications <- session + " " + method + " " + string(params): + return true, nil + case <-ctx.Done(): + return false, ctx.Err() + } +} + +func (k *remoteRunFixture) DecodeRunStart(ctx context.Context, _ json.RawMessage, root, temporary string, _ json.RawMessage) (core.RunStart, error) { + binding := core.RemoteWorkspaceOf(ctx) + if binding == nil || binding.LocalRoot() != root || binding.RemoteRoot() != remoteRunRoot { + return core.RunStart{}, errors.New("run decoder did not receive the remote workspace") + } + if k.scratch != "" && temporary != remoteScratch { + return core.RunStart{}, fmt.Errorf("run decoder received scratch %q", temporary) + } + return k.start, ctx.Err() +} + +func (k *remoteRunFixture) CreateRemoteRunDirectory(ctx context.Context, id string) (string, error) { + k.scratch = id + return remoteScratch, ctx.Err() +} + +func (k *remoteRunFixture) ReleaseRemoteRunDirectory(ctx context.Context, id string) error { + binding := core.RemoteWorkspaceOf(ctx) + if binding == nil || binding.RemoteRoot() != remoteRunRoot || id != k.scratch || ctx.Err() != nil { + return errors.New("scratch release lost its original workspace, identity or deadline") + } + k.released <- id + return nil +} + +func (k *remoteRunFixture) WriteRemoteRunFile(_ context.Context, path string, data []byte) error { + return k.write(path, data) +} + +func (k *remoteRunFixture) RunRemoteProcess(ctx context.Context, spec core.RemoteProcessOpen, events core.RemoteProcessEvents) (core.RemoteProcessExit, error) { + return k.spawn(ctx, spec, events) +} + +func openRemoteRunFixture(t *testing.T, k *remoteRunFixture) (*runHarness, *core.RemoteWorkspace, *atomic.Bool, chan RunEvent) { + t.Helper() + k.runKernel.client = core.NewClient() + k.released = make(chan string, 2) + k.start.Label = "Remote fixture" + k.start.Executable = core.RunStartExecutable{Kind: "toolchain", Value: "interpreter"} + k.start.WorkingDirectory = "module" + h := newRunHarnessWithKernel(t, k) + binding := core.NewRemoteWorkspace(h.root, remoteRunRoot, nil) + binding.Attach("session-1") + trusted := &atomic.Bool{} + trusted.Store(true) + h.service.Contexts.OpenRemote(binding, "fixture", "connection-1", core.RemotePlatform{OS: "linux", Arch: "x86_64"}, trusted.Load) + events := make(chan RunEvent, 8) + h.service.Runs.SetObserver(func(event RunEvent) { events <- event }) + h.service.Runs.Tools = func(ctx context.Context, root, directory, tool string) (RunExecutable, error) { + if core.RemoteWorkspaceOf(ctx) != binding || root != h.root || directory != "module" || tool != "interpreter" { + return RunExecutable{}, fmt.Errorf("unexpected remote tool request for %q in %q (%q)", tool, root, directory) + } + return RunExecutable{ + Path: "/opt/tool/bin/interpreter", Environment: map[string]string{"TOOL_ROOT": "/opt/tool", "MODE": "default"}, + PathPrepend: []string{"/opt/tool/bin"}, + }, nil + } + return h, binding, trusted, events +} + +func waitRemoteRunEvent[T any](t *testing.T, events <-chan T) T { + t.Helper() + select { + case event := <-events: + return event + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for the remote run") + var zero T + return zero + } +} + +func TestRemoteRunStartPreservesScopeEnvironmentAndScratch(t *testing.T) { + for _, explicitPath := range []bool{false, true} { + t.Run(fmt.Sprintf("explicitPath=%t", explicitPath), func(t *testing.T) { + k := &remoteRunFixture{} + h, binding, _, events := openRemoteRunFixture(t, k) + k.start.Environment = map[string]string{"MODE": "plugin"} + if explicitPath { + k.start.Environment["PATH"] = "/other/bin" + } + file := remoteScratch + "/argument-file" + k.start.Arguments = []string{"@" + file} + k.start.TemporaryFiles = []core.RunStartFile{{Path: file, Base64: remotePayload}} + k.write = func(name string, data []byte) error { + if name != file || !reflect.DeepEqual(data, []byte{0, 255}) { + return fmt.Errorf("write %q = %x", name, data) + } + return nil + } + specs := make(chan core.RemoteProcessOpen, 1) + k.spawn = func(ctx context.Context, spec core.RemoteProcessOpen, sink core.RemoteProcessEvents) (core.RemoteProcessExit, error) { + if core.RemoteWorkspaceOf(ctx) != binding { + return core.RemoteProcessExit{}, errors.New("spawn lost its workspace") + } + specs <- spec + sink.Started(1, 42) + sink.Output("stderr", []byte("remote output\n")) + code := 7 + return core.RemoteProcessExit{ExitCode: &code}, nil + } + + response, refusal := respond(t, h.service, runFixturePlugin, "run/start", h.params(t, "remote", map[string]any{ + "temporaryFiles": []map[string]string{{"name": "argument-file", "base64": remotePayload}}, + })) + id := startedRunID(t, response, refusal) + spec := waitRemoteRunEvent(t, specs) + if !reflect.DeepEqual(spec.Argv, []string{"/opt/tool/bin/interpreter", "@" + file}) || + spec.Cwd != "" || spec.ScopedCwd == nil || *spec.ScopedCwd != (core.RemoteScopedDirectory{Root: remoteRunRoot, Path: "module"}) || + spec.Environment != "login" || spec.Env["MODE"] != "plugin" || spec.Env["TOOL_ROOT"] != "/opt/tool" { + t.Fatalf("remote spawn = %+v", spec) + } + if explicitPath { + if spec.Env["PATH"] != "/other/bin" || len(spec.PathPrepend) != 0 { + t.Fatalf("explicit path was changed in %+v", spec) + } + } else if _, set := spec.Env["PATH"]; set || !reflect.DeepEqual(spec.PathPrepend, []string{"/opt/tool/bin"}) { + t.Fatalf("remote login PATH was replaced in %+v", spec) + } + started, output, ended := waitRemoteRunEvent(t, events), waitRemoteRunEvent(t, events), waitRemoteRunEvent(t, events) + if started.Type != RunStarted || started.RunID != id || !started.Remote || started.PID != 0 || + output.Type != RunOutput || output.RunID != id || output.Text != "remote output\n" || + ended.Type != RunExited || ended.RunID != id || ended.ExitCode == nil || *ended.ExitCode != 7 { + t.Fatalf("run events out of order or incomplete: %+v %+v %+v", started, output, ended) + } + waitRemoteRunEvent(t, k.released) + }) + } +} + +func TestRemoteRunRefusesUntrustedWorkspaceAndReleasesFailedSetup(t *testing.T) { + k := &remoteRunFixture{} + h, _, trusted, events := openRemoteRunFixture(t, k) + params := h.params(t, "remote", map[string]any{ + "temporaryFiles": []map[string]string{{"name": "argument-file", "base64": remotePayload}}, + }) + trusted.Store(false) + _, refusal := respond(t, h.service, runFixturePlugin, "run/start", params) + if refusal == nil || refusal.Code != CodePermissionDenied || k.scratch != "" { + t.Fatalf("untrusted start = %+v, scratch = %q", refusal, k.scratch) + } + trusted.Store(true) + k.start.TemporaryFiles = []core.RunStartFile{{Path: remoteScratch + "/argument-file", Base64: remotePayload}} + k.write = func(string, []byte) error { return errors.New("scratch write failed") } + _, refusal = respond(t, h.service, runFixturePlugin, "run/start", params) + if refusal == nil || refusal.Code != pluginhost.CodeHostFailure || len(events) != 0 { + t.Fatalf("failed scratch write = %+v, events = %d", refusal, len(events)) + } + waitRemoteRunEvent(t, k.released) +} + +func TestRemoteRunStopsOnRequestContextCloseOrAttachmentReplacement(t *testing.T) { + for _, action := range []string{"stop", "close", "reattach", "replace during launch"} { + t.Run(action, func(t *testing.T) { + k := &remoteRunFixture{} + h, binding, _, events := openRemoteRunFixture(t, k) + k.spawn = func(ctx context.Context, _ core.RemoteProcessOpen, sink core.RemoteProcessEvents) (core.RemoteProcessExit, error) { + if action == "replace during launch" { + binding.Attach("session-1") + } + sink.Started(1, 42) + sink.Output("stdout", []byte("started\n")) + select { + case <-ctx.Done(): + return core.RemoteProcessExit{}, ctx.Err() + case <-time.After(5 * time.Second): + return core.RemoteProcessExit{}, errors.New("owner did not cancel the remote process") + } + } + ctx, cancel := context.WithCancel(callerContext(runFixturePlugin)) + defer cancel() + result, refusal := h.service.HostServices.Respond(ctx, methodRunStart, json.RawMessage(h.params(t, "remote", nil))) + if action == "replace during launch" { + if refusal == nil || refusal.Code != CodeRemoteDisconnected || len(events) != 0 { + t.Fatalf("stale start = %+v, events = %d", refusal, len(events)) + } + return + } + id := startedRunID(t, result, refusal) + // The request ends after acknowledgement. A different owner ends + // the actual process below. + cancel() + switch action { + case "stop": + if _, refusal := respond(t, h.service, runFixturePlugin, "run/stop", `{"runID":"`+id+`"}`); refusal != nil { + t.Fatalf("stop: %+v", refusal) + } + case "close": + h.service.Contexts.Close(h.root) + case "reattach": + binding.Attach("session-1") + } + if started, output := waitRemoteRunEvent(t, events), waitRemoteRunEvent(t, events); started.Type != RunStarted || output.Type != RunOutput { + t.Fatalf("run events out of order: %+v %+v", started, output) + } + ended := waitRemoteRunEvent(t, events) + if ended.Type != RunExited || ended.ExitCode != nil || ended.Signal != "" || + ended.Disconnected != (action == "reattach") || len(h.service.Runs.Active()) != 0 { + t.Fatalf("end = %+v, active = %v", ended, h.service.Runs.Active()) + } + }) + } +} + +func TestRemoteRunReportsSignalWithoutExitCode(t *testing.T) { + k := &remoteRunFixture{notifications: make(chan string, 1)} + h, _, _, events := openRemoteRunFixture(t, k) + backend := &BackendSession{ + host: h.service.Host, PluginID: runFixturePlugin, ready: true, + Session: pluginbackend.Session{ID: "session-" + runFixturePlugin, Granted: []string{methodRunStart}}, + } + h.service.Host.sessions[runFixturePlugin] = backend + k.spawn = func(_ context.Context, _ core.RemoteProcessOpen, sink core.RemoteProcessEvents) (core.RemoteProcessExit, error) { + sink.Started(1, 42) + signal := 15 + return core.RemoteProcessExit{Signal: &signal}, nil + } + response, refusal := respond(t, h.service, runFixturePlugin, "run/start", h.params(t, "remote", nil)) + id := startedRunID(t, response, refusal) + started, ended := waitRemoteRunEvent(t, events), waitRemoteRunEvent(t, events) + if started.Type != RunStarted || started.RunID != id || ended.Type != RunExited || + ended.RunID != id || ended.ExitCode != nil || ended.Signal != "15" || ended.Disconnected { + t.Fatalf("remote signal events = %+v %+v", started, ended) + } + select { + case notice := <-k.notifications: + want := fmt.Sprintf("%s %s {\"runID\":%q,\"signal\":15}", backend.Session.ID, notifyRunDidExit, id) + if notice != want { + t.Fatalf("run exit notification = %s, want %s", notice, want) + } + case <-time.After(2 * time.Second): + t.Fatal("the backend did not receive the run exit notification") + } +} diff --git a/desktop/internal/pluginservice/remote_runtimes.go b/desktop/internal/pluginservice/remote_runtimes.go new file mode 100644 index 0000000000..e880b3584f --- /dev/null +++ b/desktop/internal/pluginservice/remote_runtimes.go @@ -0,0 +1,155 @@ +package pluginservice + +import ( + "context" + "crypto/rand" + "encoding/json" + "fmt" + "path" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginbackend" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginruntime" +) + +type remoteRuntimeKernel interface { + PlanManagedRuntimes(context.Context, json.RawMessage, core.ManagedRuntimePlatform) (core.ManagedRuntimePlan, error) + VerifyMarketplaceRemoteVariant(context.Context, core.MarketplaceVariantReview) (json.RawMessage, error) + LookupRemoteManagedRuntime(context.Context, core.RemoteManagedRuntimeLayout) (*core.RemoteManagedRuntimePaths, error) + CreateRemoteRuntimeStaging(context.Context, string) (string, error) + ReleaseRemoteRunDirectory(context.Context, string) error + UploadRemotePluginFile(context.Context, string, string, string, uint32) error + CommitRemoteManagedRuntime(context.Context, core.RemoteManagedRuntimeLayout, string) (*core.RemoteManagedRuntimePaths, error) +} + +var _ remoteRuntimeKernel = (*core.Client)(nil) + +// RemoteTools supplies the installations approved for processes on this attachment. +func (s *Service) RemoteTools(ctx context.Context, installed pluginpkg.Installed, manifest json.RawMessage, connection *core.RemoteWorkspaceConnection, platform core.RemotePlatform) (map[string]pluginbackend.ToolExecutable, error) { + environment, err := s.prepareRemoteRuntimes(ctx, installed, manifest, connection, platform, nil) + return environment.Tools, err +} + +// prepareRemoteRuntimes uses the remote platform's approved pinned artifacts. +// The local compatibility hook is for local installations. The remote host +// verifies the pinned archive, runtime home and executable before supplying +// these native facts to the plugin's launch resolver. +func (s *Service) prepareRemoteRuntimes(ctx context.Context, installed pluginpkg.Installed, manifest json.RawMessage, connection *core.RemoteWorkspaceConnection, platform core.RemotePlatform, progress func(pluginruntime.Progress)) (RuntimeEnvironment, error) { + if !HasManagedRuntimes(manifest) { + return RuntimeEnvironment{}, nil + } + kernel, ok := s.kernel.(remoteRuntimeKernel) + if !ok { + return RuntimeEnvironment{}, fmt.Errorf("%w: remote managed runtime service unavailable", ErrAssembly) + } + ctx, cancel := context.WithCancel(ctx) + defer cancel() + stopDetach := connection.AfterDetach(cancel) + defer stopDetach() + ctx = connection.Context(ctx) + + approval, found, err := s.Manager.Approval(installed.ID, installed.Version) + if err != nil { + return RuntimeEnvironment{}, err + } + if !found { + return RuntimeEnvironment{}, &core.MarketplaceRejection{ + Code: "plugin.remote.approvalRequired", Message: "The remote runtime requires an approved plugin release.", + } + } + // Revalidate the programs from the exact manifest used for this launch. + // A modified installed manifest cannot introduce a new archive or tool. + local := core.WithoutRemoteWorkspace(ctx) + approved, err := kernel.VerifyMarketplaceRemoteVariant(local, core.MarketplaceVariantReview{ + InstalledManifest: manifest, VariantManifest: manifest, PluginID: installed.ID, Version: installed.Version, + ApprovedPrograms: approval.ApprovedPrograms, HostCapabilities: s.Capabilities().Clone(), + }) + if err != nil { + return RuntimeEnvironment{}, err + } + plan, err := kernel.PlanManagedRuntimes(local, approved, core.ManagedRuntimePlatform(platform)) + if err != nil { + return RuntimeEnvironment{}, err + } + environment := RuntimeEnvironment{ + Runtimes: make(map[string]core.ManagedRuntimeInstallation, len(plan.Dependencies)), + Tools: make(map[string]pluginbackend.ToolExecutable), + Facts: make(map[string]RuntimeTool), + } + for _, dependency := range plan.Dependencies { + installation, err := s.prepareRemoteRuntime(ctx, kernel, installed, dependency, progress) + if err != nil { + return RuntimeEnvironment{}, err + } + environment.Runtimes[dependency.ID] = core.ManagedRuntimeInstallation{ + ID: dependency.ID, Version: dependency.Version, Home: installation.Home, + } + if dependency.Tool != "" { + environment.Tools[dependency.Tool] = pluginbackend.ToolExecutable{Path: installation.Executable, Home: installation.Home} + environment.Facts[dependency.Tool] = RuntimeTool{ + Executable: installation.Executable, Home: installation.Home, Version: dependency.Version, + } + } + } + return environment, ctx.Err() +} + +func (s *Service) prepareRemoteRuntime(ctx context.Context, kernel remoteRuntimeKernel, installed pluginpkg.Installed, dependency core.ManagedRuntimeDependency, progress func(pluginruntime.Progress)) (*core.RemoteManagedRuntimePaths, error) { + report := func(phase string) { + if progress != nil { + progress(pluginruntime.Progress{ID: dependency.ID, Phase: phase}) + } + } + report("checking") + layout := core.RemoteManagedRuntimeLayout{ + Key: core.RemotePluginDeployment{PluginID: installed.ID, Version: installed.Version, SHA256: dependency.CacheKey}, + ArchiveSHA256: dependency.SHA256, Archive: dependency.Archive, + StripPrefix: dependency.StripPrefix, Home: dependency.Home, Executable: dependency.Executable, + } + installation, err := kernel.LookupRemoteManagedRuntime(ctx, layout) + if err != nil { + return nil, err + } + if installation != nil { + report("ready") + return installation, nil + } + manager := pluginruntime.Manager{Downloader: s.RuntimeDownloader} + download, cleanup, err := manager.DownloadArchive(core.WithoutRemoteWorkspace(ctx), runtimeArtifact(dependency), progress) + if err != nil { + return nil, err + } + defer func() { s.recordDeploymentCleanup(ctx, cleanup()) }() + + id := "runtime-" + rand.Text() + defer func() { + cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + defer cancel() + s.recordDeploymentCleanup(ctx, kernel.ReleaseRemoteRunDirectory(cleanup, id)) + }() + staging, err := kernel.CreateRemoteRuntimeStaging(ctx, id) + if err != nil { + return nil, err + } + uploadCtx := ctx + if progress != nil { + uploadCtx = core.WithRemoteStages(ctx, func(stage core.RemoteStage) { + if stage.Stage == core.RemoteStageUploading { + progress(pluginruntime.Progress{ID: dependency.ID, Phase: "uploading", + Received: int64(stage.SentBytes), Total: int64(stage.TotalBytes)}) + } + }) + } + if err := kernel.UploadRemotePluginFile(uploadCtx, download.Path(), path.Join(staging, "archive"), dependency.SHA256, 0o400); err != nil { + return nil, err + } + report("extracting") + installation, err = kernel.CommitRemoteManagedRuntime(ctx, layout, id) + if err != nil { + return nil, err + } + report("ready") + return installation, nil +} diff --git a/desktop/internal/pluginservice/remote_settings.go b/desktop/internal/pluginservice/remote_settings.go new file mode 100644 index 0000000000..935d9c3ff2 --- /dev/null +++ b/desktop/internal/pluginservice/remote_settings.go @@ -0,0 +1,148 @@ +package pluginservice + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/json" + "errors" + "path" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +type remoteSettingsHelperKernel interface { + RunRemoteProcess(context.Context, core.RemoteProcessOpen, core.RemoteProcessEvents) (core.RemoteProcessExit, error) + CreateRemoteRuntimeStaging(context.Context, string) (string, error) + ReleaseRemoteRunDirectory(context.Context, string) error + WriteRemoteRunFile(context.Context, string, []byte) error +} + +const remoteSettingsOutputLimit = 2 * 1024 * 1024 + +// CheckRemoteSettingsWorkspace uses the live trust decision of the editor's +// original attachment. Read-back and publication share this check. +func (s *Service) CheckRemoteSettingsWorkspace(editor SettingsEditor) error { + _, err := s.remoteSettingsWorkspace(editor) + return err +} + +func (s *Service) remoteSettingsWorkspace(editor SettingsEditor) (WorkspaceContext, error) { + workspace, ok := s.Contexts.ByPath(editor.Snapshot.Workspace()) + if !ok || workspace.remote.binding == nil || workspace.lifetime.Err() != nil { + return WorkspaceContext{}, configfile.ErrConflict + } + connection := workspace.remote.binding.CaptureConnection() + if !connection.SameAttachment(editor.RemoteConnection()) || !connection.IsCurrent() { + return WorkspaceContext{}, configfile.ErrConflict + } + if workspace.codeAllowed == nil || !workspace.codeAllowed() { + return WorkspaceContext{}, &core.Error{Code: core.CodePermissionDenied, Message: "Native settings require a trusted remote workspace."} + } + return workspace, nil +} + +// PrepareRemoteSettingsHelper uses the same approved package variant and lease +// as other native providers, with an invocation scoped to this workspace. +func (s *Service) PrepareRemoteSettingsHelper(ctx context.Context, editor SettingsEditor, plan core.PluginSettingsActionPlan, check func() error) (func(context.Context, json.RawMessage) (json.RawMessage, error), error) { + if plan.Kind != "invoke" || !plan.SourceEditor { + return nil, configfile.ErrConflict + } + if err := check(); err != nil { + return nil, err + } + kernel, ok := s.kernel.(remoteSettingsHelperKernel) + if !ok || plan.RemoteHelper == nil { + return nil, &core.Error{Code: core.CodeNotSupported, Message: "This plugin does not provide a remote native settings helper."} + } + workspace, err := s.remoteSettingsWorkspace(editor) + if err != nil { + return nil, err + } + connection := editor.RemoteConnection() + ctx, done := remoteSettingsHelperContext(ctx, workspace, connection) + defer done() + helper := plan.RemoteHelper + required := append([]string{helper.Executable}, helper.Resources...) + directory, err := s.prepareRemoteDeployment(ctx, editor.entry.Installed, editor.manifest, workspace.HostPlatform(), required, nil) + if err != nil { + return nil, err + } + argv := append([]string{path.Join(directory, helper.Executable)}, helper.Arguments...) + return func(ctx context.Context, request json.RawMessage) (json.RawMessage, error) { + return runRemoteSettingsHelper(ctx, kernel, workspace, connection, argv, request, check) + }, nil +} + +func remoteSettingsHelperContext(ctx context.Context, workspace WorkspaceContext, connection *core.RemoteWorkspaceConnection) (context.Context, func()) { + ctx, cancel := context.WithTimeout(connection.Context(ctx), 60*time.Second) + stopClose := context.AfterFunc(workspace.lifetime, cancel) + stopDetach := connection.AfterDetach(cancel) + return ctx, func() { + stopClose() + stopDetach() + cancel() + } +} + +func runRemoteSettingsHelper(ctx context.Context, kernel remoteSettingsHelperKernel, workspace WorkspaceContext, connection *core.RemoteWorkspaceConnection, argv []string, request json.RawMessage, check func() error) (_ json.RawMessage, err error) { + if err := check(); err != nil { + return nil, err + } + ctx, done := remoteSettingsHelperContext(ctx, workspace, connection) + defer done() + ctx, cancel := context.WithCancel(ctx) + defer cancel() + + id := "settings-request-" + rand.Text() + defer func() { + cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + defer cancel() + if cleanupErr := kernel.ReleaseRemoteRunDirectory(cleanup, id); cleanupErr != nil { + err = errors.Join(err, cleanupErr) + } + }() + directory, err := kernel.CreateRemoteRuntimeStaging(ctx, id) + if err != nil { + return nil, err + } + input := path.Join(directory, "request.json") + if err := kernel.WriteRemoteRunFile(ctx, input, request); err != nil { + return nil, err + } + if err := check(); err != nil { + return nil, err + } + var output bytes.Buffer + var oversized bool + exit, err := kernel.RunRemoteProcess(ctx, core.RemoteProcessOpen{ + Argv: append(append([]string(nil), argv...), input), + ScopedCwd: &core.RemoteScopedDirectory{Root: workspace.remote.hostPath}, + Environment: "login", + }, core.RemoteProcessEvents{Output: func(stream string, data []byte) { + if stream != "stdout" || oversized { + return + } + if output.Len()+len(data) > remoteSettingsOutputLimit { + oversized = true + cancel() + return + } + output.Write(data) + }}) + if oversized { + return nil, configfile.ErrTooLarge + } + if err != nil { + return nil, err + } + if exit.ExitCode == nil || *exit.ExitCode != 0 || !json.Valid(output.Bytes()) { + return nil, &core.Error{Code: core.CodeProcessFailed, Message: "The remote native settings helper did not return a valid result."} + } + if err := check(); err != nil { + return nil, err + } + return output.Bytes(), nil +} diff --git a/desktop/internal/pluginservice/runs.go b/desktop/internal/pluginservice/runs.go index e721a54936..454f26f6e5 100644 --- a/desktop/internal/pluginservice/runs.go +++ b/desktop/internal/pluginservice/runs.go @@ -10,9 +10,9 @@ import ( "os/exec" "path/filepath" "strconv" - "strings" "sync" "sync/atomic" + "syscall" "time" "github.com/1lck/Lithe-IDEA/desktop/internal/buildprocess" @@ -60,11 +60,13 @@ type RunEvent struct { PluginID string Label string Workspace string + Remote bool Text string // OutputEncoding is the process's declaration, set on RunStarted before any output. OutputEncoding string ExitCode *int Signal string + Disconnected bool // Rerun is set on RunStarted when the plugin supplied a rerun function. Rerun *RunRerun // PID is the run's root process on RunStarted, 0 when it has none (a debug launch). @@ -77,11 +79,12 @@ type RunEvent struct { type RunExecutable struct { Path string Environment map[string]string + PathPrepend []string } // RunToolResolver resolves a tool definition the manifest requires, through the // host's toolchain layers, for the workspace the run belongs to. -type RunToolResolver func(ctx context.Context, workspaceRoot, tool string) (RunExecutable, error) +type RunToolResolver func(ctx context.Context, workspaceRoot, directory, tool string) (RunExecutable, error) // RunDebugRequest asks the host to attach a debug adapter to a running debuggee. type RunDebugRequest struct { @@ -91,6 +94,7 @@ type RunDebugRequest struct { ConfigurationType string Host string Port int + Connection *core.RemoteWorkspaceConnection // StopRun ends the host-owned process when its attached debug session is // released. It requests bounded cleanup off the UI thread; another owner // already stopping the run keeps its grace and remains responsible for waiting. @@ -114,6 +118,7 @@ type RunDebugLaunchRequest struct { Arguments []string WorkingDirectory string Environment map[string]string + Connection *core.RemoteWorkspaceConnection } // RunDebugSession is a debug session that stands for a run: its ID, and a channel @@ -189,18 +194,20 @@ type Runs struct { type hostRun struct { // pid is the root process of a started run, recorded in the ledger while it lives. - pid int - id string - pluginID string - backend string - workspace WorkspaceContext - start core.RunStart - process runProcess - cancel context.CancelFunc - temporary string - debug atomic.Pointer[string] - stopped atomic.Bool - done chan struct{} + pid int + id string + pluginID string + backend string + workspace WorkspaceContext + connection *core.RemoteWorkspaceConnection + start core.RunStart + process runProcess + cancel context.CancelFunc + detach func() + cleanup func() + debug atomic.Pointer[string] + stopped atomic.Bool + done chan struct{} } func newRuns(service *Service) *Runs { @@ -299,6 +306,9 @@ func (r *Runs) StopAll() { type runStartParams struct { Context ContextRef `json:"context"` TemporaryFiles []json.RawMessage `json:"temporaryFiles"` + Process struct { + Placement json.RawMessage `json:"placement"` + } `json:"process"` } // handleStart answers lithe/host/run/start. @@ -315,139 +325,108 @@ func (r *Runs) handleStart(ctx context.Context, params json.RawMessage) (json.Ra if err != nil { return nil, contextFailure(err) } - entry, manifest, err := r.service.installedPlugin(ctx, caller.PluginID) - if err != nil { - return nil, failure(pluginhost.CodeHostFailure, err.Error()) - } - temporary := "" - if len(request.TemporaryFiles) > 0 { - // The host's own temporary directory: the plugin never learns where it is, - // and it is removed when the run ends. - temporary, err = os.MkdirTemp("", "lithe-run-") - if err != nil { - return nil, failure(pluginhost.CodeHostFailure, "the run's temporary directory cannot be created") - } - } - cleanup := func() { - if temporary != "" { - _ = os.RemoveAll(temporary) - } - } - start, err := r.service.kernel.DecodeRunStart(ctx, manifest, workspace.Path, temporary, params) - if err != nil { - cleanup() - return nil, runStartFailure(err) - } - launch := start.Debug != nil && start.Debug.Target.Kind == "launch" - if start.Debug != nil && start.Debug.Target.Kind != "connection" && !launch { - cleanup() - return nil, failure("plugin.host.unavailable", "This host does not serve the debug target.") - } - if launch && r.LaunchDebug == nil { - cleanup() - return nil, failure("plugin.host.unavailable", "This host starts no debug sessions.") - } - executable, environment, refusal := r.resolveExecutable(ctx, entry, workspace.Path, start) + remote, refusal := r.captureRemoteRun(workspace) if refusal != nil { - cleanup() return nil, refusal } - for _, file := range start.TemporaryFiles { - data, err := file.Bytes() - if err == nil { - err = os.WriteFile(file.Path, data, 0o600) - } - if err != nil { - cleanup() - return nil, failure(pluginhost.CodeHostFailure, "a temporary file cannot be written") + if remote != nil { + if refusal := remote.refusal(ctx); refusal != nil { + return nil, refusal } } - for key, value := range start.Environment { - environment[key] = value + + r.mu.Lock() + if r.closed { + r.mu.Unlock() + return nil, runHostClosing() } - // An app started from Finder has launchd's PATH; the run gets the user's shell PATH - // unless the plugin or the tool chose one. - if _, set := environment["PATH"]; !set { - if path := loginenv.Path(); path != "" { - environment["PATH"] = path - } + r.wait.Add(1) + r.mu.Unlock() + defer r.wait.Done() + + entry, manifest, err := r.service.installedPlugin(ctx, caller.PluginID) + if err != nil { + return nil, failure(pluginhost.CodeHostFailure, err.Error()) } - runCtx, cancel := context.WithCancel(context.Background()) + runCtx, cancel := context.WithCancel(context.WithoutCancel(ctx)) run := &hostRun{ id: fmt.Sprintf("run-%d", r.sequence.Add(1)), pluginID: caller.PluginID, backend: caller.SessionID, workspace: workspace, - start: start, cancel: cancel, - temporary: temporary, done: make(chan struct{}), } - // Output is delivered only after the started event, so an observer never sees - // a run's text before it knows the run. + if remote != nil { + run.connection = remote.connection + stopDetach := remote.connection.AfterDetach(run.cancel) + stopClose := context.AfterFunc(workspace.lifetime, run.cancel) + run.detach = func() { + stopDetach() + stopClose() + } + } + accepted := false + defer func() { + if !accepted { + run.release() + } + }() + + // Cancellation of the startup request ends a pending launch. Once admitted, + // the workbench owns the run, including when the calling backend exits. started := make(chan struct{}) - workingDirectory := filepath.Join(workspace.Path, filepath.FromSlash(start.WorkingDirectory)) - var process runProcess - if launch { - // The adapter starts the process: the run stands for the debug session, its - // output is the Debug console's, and stopping the run stops the session. - session, err := r.LaunchDebug(ctx, RunDebugLaunchRequest{ - PluginID: run.pluginID, WorkspaceRoot: workspace.Path, Label: start.Label, - ConfigurationType: start.Debug.ConfigurationType, Executable: executable, - Arguments: start.Arguments, WorkingDirectory: workingDirectory, Environment: environment, - }) - if err != nil { - cancel() - cleanup() - return nil, failure(pluginhost.CodeHostFailure, err.Error()) - } - run.debug.Store(&session.ID) - stop := r.StopDebugSession - process = &debugRunProcess{ended: session.Ended, stop: func() { - if stop != nil { - stop(session.ID) - } - }} - } else { - // The command line is the plugin's, started as it is. A launch that would - // overflow the system limit is the plugin's to shorten, for example with an - // argument file passed in temporaryFiles. - spawned, err := buildprocess.Start(runCtx, buildprocess.Spec{ - Executable: executable, - Arguments: start.Arguments, - WorkingDirectory: workingDirectory, - Environment: environment, - }, func(_ buildprocess.Stream, text string) { - <-started + output := func(_ buildprocess.Stream, text string) { + <-started + if accepted { r.emit(RunEvent{Type: RunOutput, RunID: run.id, PluginID: run.pluginID, Text: text}) - }) - if err != nil { - cancel() - cleanup() - return nil, failure(pluginhost.CodeHostFailure, err.Error()) } - process = spawned } + var process runProcess + var launch bool + // This only selects where to allocate scratch. Core validates the full + // process declaration before either branch resolves or starts a program. + var placement core.ProcessPlacement + _ = json.Unmarshal(request.Process.Placement, &placement) + if remote != nil && placement != core.ProcessPlacementUI { + process, launch, refusal = r.startRemote(ctx, runCtx, run, remote, entry, manifest, request, params, output) + } else { + process, launch, refusal = r.startLocal(ctx, runCtx, run, remote, entry, manifest, request, params, output) + } + if refusal != nil { + close(started) + return nil, refusal + } + run.process = process - if owned, ok := process.(interface{ Pid() int }); ok { + if owned, ok := process.(interface{ Pid() int }); ok && owned.Pid() > 0 { run.pid = owned.Pid() - _ = r.service.ledger.Add(run.pid) + r.recordRunIssue(ctx, r.service.ledger.Add(run.pid)) } r.mu.Lock() - if r.closed { + switch { + case r.closed: + refusal = runHostClosing() + case remote != nil: + refusal = remote.refusal(ctx) + } + if refusal != nil { r.mu.Unlock() - // The host is shutting down: end the process that just started. - process.Stop() - _ = process.Wait() + // Release the output readers before waiting for a refused process. close(started) - cancel() - cleanup() - return nil, failure("plugin.host.unavailable", "The host is shutting down.") + process.Stop() + err := process.Wait() + if code, signal := exitStatus(err); err != nil && code == nil && signal == 0 && !errors.Is(err, context.Canceled) { + r.recordRunIssue(ctx, err) + } + r.recordRunIssue(ctx, r.service.ledger.Remove(run.pid)) + return nil, refusal } r.runs[run.id] = run r.wait.Add(1) r.mu.Unlock() - event := RunEvent{Type: RunStarted, RunID: run.id, PluginID: run.pluginID, Label: start.Label, Workspace: workspace.Path, PID: run.pid, OutputEncoding: start.OutputEncoding} + start := run.start + event := RunEvent{Type: RunStarted, RunID: run.id, PluginID: run.pluginID, Label: start.Label, Workspace: workspace.Path, PID: run.pid, OutputEncoding: start.OutputEncoding, Remote: remote != nil && start.Placement != core.ProcessPlacementUI} if start.Debug != nil && start.Debug.Target.Kind == "connection" && start.Debug.Target.Port > 0 { event.DebugPort = start.Debug.Target.Port } @@ -455,6 +434,7 @@ func (r *Runs) handleStart(ctx context.Context, params json.RawMessage) (json.Ra event.Rerun = &RunRerun{PluginID: run.pluginID, Function: start.Rerun.Function, Data: start.Rerun.Data, Workspace: workspace.Path} } r.emit(event) + accepted = true close(started) go r.supervise(run) if start.Debug != nil && !launch { @@ -463,35 +443,177 @@ func (r *Runs) handleStart(ctx context.Context, params json.RawMessage) (json.Ra return marshalResult(map[string]string{"runID": run.id}) } -// resolveExecutable turns the decoded executable reference into a program. A -// packaged file is verified against the installed package, never the workspace. -func (r *Runs) resolveExecutable(ctx context.Context, entry pluginmanager.Entry, workspaceRoot string, start core.RunStart) (string, map[string]string, *pluginhost.Failure) { - environment := map[string]string{} +func runHostClosing() *pluginhost.Failure { + return failure("plugin.host.unavailable", "The host is shutting down.") +} + +func (r *Runs) startLocal(ctx, runCtx context.Context, run *hostRun, remote *remoteRun, entry pluginmanager.Entry, manifest json.RawMessage, request runStartParams, params json.RawMessage, output func(buildprocess.Stream, string)) (runProcess, bool, *pluginhost.Failure) { + decodeCtx := ctx + if remote != nil { + setup, cancel := context.WithCancel(ctx) + defer cancel() + stop := context.AfterFunc(runCtx, cancel) + defer stop() + ctx = core.WithoutRemoteWorkspace(setup) + decodeCtx = remote.connection.Context(setup) + } + temporary := "" + var err error + if len(request.TemporaryFiles) > 0 { + temporary, err = os.MkdirTemp("", "lithe-run-") + if err != nil { + return nil, false, failure(pluginhost.CodeHostFailure, "the run's temporary directory cannot be created") + } + run.cleanup = func() { r.recordRunIssue(ctx, os.RemoveAll(temporary)) } + } + start, err := r.service.kernel.DecodeRunStart(decodeCtx, manifest, run.workspace.Path, temporary, params) + if err != nil { + if remote != nil { + return nil, false, remote.startFailure(ctx, err) + } + return nil, false, runStartFailure(err) + } + run.start = start + executionRoot := run.workspace.Path + if remote != nil { + if refusal := remote.refusal(ctx); refusal != nil { + return nil, false, refusal + } + if start.Placement != core.ProcessPlacementUI || start.Debug != nil { + return nil, false, unsupportedRemoteWorkspace() + } + executionRoot, err = r.service.contextState(run.pluginID, run.workspace) + if err != nil { + return nil, false, failure(pluginhost.CodeHostFailure, err.Error()) + } + } + launch := start.Debug != nil && start.Debug.Target.Kind == "launch" + if start.Debug != nil && start.Debug.Target.Kind != "connection" && !launch { + return nil, false, failure("plugin.host.unavailable", "This host does not serve the debug target.") + } + if launch && r.LaunchDebug == nil { + return nil, false, failure("plugin.host.unavailable", "This host starts no debug sessions.") + } + executable, refusal := r.resolveExecutable(ctx, entry, executionRoot, start) + if refusal != nil { + return nil, false, refusal + } + for _, file := range start.TemporaryFiles { + data, err := file.Bytes() + if err == nil { + err = os.WriteFile(file.Path, data, 0o600) + } + if err != nil { + return nil, false, failure(pluginhost.CodeHostFailure, "a temporary file cannot be written") + } + } + environment := runEnvironment(executable.Environment, start.Environment) + // An app started from Finder has launchd's PATH. Give the local run the + // user's shell PATH unless the plugin or the tool chose one. + if _, set := environment["PATH"]; !set { + if path := loginenv.Path(); path != "" { + environment["PATH"] = path + } + } + workingDirectory := filepath.Join(executionRoot, filepath.FromSlash(start.WorkingDirectory)) + if remote != nil { + if refusal := remote.refusal(ctx); refusal != nil { + return nil, false, refusal + } + } + if launch { + process, err := r.startDebugLaunch(ctx, run, executable.Path, workingDirectory, environment) + if err != nil { + return nil, false, failure(pluginhost.CodeHostFailure, err.Error()) + } + return process, true, nil + } + spawned, err := buildprocess.Start(runCtx, buildprocess.Spec{ + Executable: executable.Path, Arguments: start.Arguments, + WorkingDirectory: workingDirectory, Environment: environment, + }, output) + if err != nil { + return nil, false, failure(pluginhost.CodeHostFailure, err.Error()) + } + return spawned, false, nil +} + +func (r *Runs) startDebugLaunch(ctx context.Context, run *hostRun, executable, directory string, environment map[string]string) (runProcess, error) { + start := run.start + session, err := r.LaunchDebug(ctx, RunDebugLaunchRequest{ + PluginID: run.pluginID, WorkspaceRoot: run.workspace.Path, Label: start.Label, + ConfigurationType: start.Debug.ConfigurationType, Executable: executable, + Arguments: start.Arguments, WorkingDirectory: directory, Environment: environment, + Connection: run.connection, + }) + if err != nil { + return nil, err + } + run.debug.Store(&session.ID) + stop := r.StopDebugSession + return &debugRunProcess{ended: session.Ended, stop: func() { + if stop != nil { + stop(session.ID) + } + }}, nil +} + +// resolveExecutable turns a local executable reference into a program. A +// packaged file is verified against the installed package. +func (r *Runs) resolveExecutable(ctx context.Context, entry pluginmanager.Entry, workspaceRoot string, start core.RunStart) (RunExecutable, *pluginhost.Failure) { switch start.Executable.Kind { case "packaged": path, err := pluginhost.ResolveExecutable(entry.Installed.Path, start.Executable.Value) if err != nil { - return "", nil, failure("plugin.host.invalidParams", err.Error()) + return RunExecutable{}, failure("plugin.host.invalidParams", err.Error()) } - return path, environment, nil + return RunExecutable{Path: path}, nil case "toolchain": - if r.Tools == nil { - return "", nil, failure("plugin.host.toolUnresolved", "This host resolves no tools.") - } - resolved, err := r.Tools(ctx, workspaceRoot, start.Executable.Value) - if err != nil || resolved.Path == "" { - message := "The tool resolves to no executable." - if err != nil { - message = err.Error() - } - return "", nil, failure("plugin.host.toolUnresolved", message) - } - for key, value := range resolved.Environment { - environment[key] = value - } - return resolved.Path, environment, nil + return r.resolveTool(ctx, workspaceRoot, ".", start.Executable.Value) + default: + return RunExecutable{}, failure("plugin.host.invalidParams", "The executable kind is unknown.") + } +} + +func (r *Runs) resolveTool(ctx context.Context, workspaceRoot, directory, tool string) (RunExecutable, *pluginhost.Failure) { + if r.Tools == nil { + return RunExecutable{}, failure("plugin.host.toolUnresolved", "This host resolves no tools.") + } + resolved, err := r.Tools(ctx, workspaceRoot, directory, tool) + if err != nil { + return RunExecutable{}, failure("plugin.host.toolUnresolved", err.Error()) + } + if resolved.Path == "" { + return RunExecutable{}, failure("plugin.host.toolUnresolved", "The tool resolves to no executable.") + } + return resolved, nil +} + +func runEnvironment(defaults, overrides map[string]string) map[string]string { + environment := make(map[string]string, len(defaults)+len(overrides)) + for key, value := range defaults { + environment[key] = value + } + for key, value := range overrides { + environment[key] = value + } + return environment +} + +func (run *hostRun) release() { + run.cancel() + if run.detach != nil { + run.detach() + } + if run.cleanup != nil { + run.cleanup() + } +} + +func (r *Runs) recordRunIssue(ctx context.Context, err error) { + if err != nil && r.service.RuntimeIssue != nil { + r.service.RuntimeIssue(ctx, err) } - return "", nil, failure("plugin.host.invalidParams", "The executable kind is unknown.") } // runStartFailure maps a Core refusal to the contract's failure: the code is @@ -510,13 +632,16 @@ func runStartFailure(err error) *pluginhost.Failure { func (r *Runs) supervise(run *hostRun) { defer r.wait.Done() err := run.process.Wait() - _ = r.service.ledger.Remove(run.pid) - run.cancel() - if run.temporary != "" { - _ = os.RemoveAll(run.temporary) - } + r.recordRunIssue(context.Background(), r.service.ledger.Remove(run.pid)) + run.release() code, signal := exitStatus(err) - if run.stopped.Load() && code == nil && signal == "" { + disconnected := run.connection != nil && code == nil && signal == 0 && err != nil && (remoteRunDisconnected(err) || !run.connection.IsCurrent()) + var debugExit *debugRunExit + if run.connection != nil && code == nil && signal == 0 && err != nil && !disconnected && + !errors.Is(err, context.Canceled) && !errors.As(err, &debugExit) { + r.recordRunIssue(context.Background(), err) + } + if run.connection == nil && run.stopped.Load() && code == nil && signal == 0 { // Stopping a run that was already gone ends it without a status of its own. zero := 0 code = &zero @@ -525,11 +650,20 @@ func (r *Runs) supervise(run *hostRun) { delete(r.runs, run.id) r.mu.Unlock() close(run.done) - r.emit(RunEvent{Type: RunExited, RunID: run.id, PluginID: run.pluginID, ExitCode: code, Signal: signal}) + signalLabel := "" + if signal != 0 { + if run.connection != nil && run.start.Placement != core.ProcessPlacementUI { + // The same signal number can mean different things on the two hosts. + signalLabel = strconv.Itoa(signal) + } else { + signalLabel = syscall.Signal(signal).String() + } + } + r.emit(RunEvent{Type: RunExited, RunID: run.id, PluginID: run.pluginID, ExitCode: code, Signal: signalLabel, Disconnected: disconnected}) r.notifyExit(run, code, signal) } -func (r *Runs) notifyExit(run *hostRun, code *int, signal string) { +func (r *Runs) notifyExit(run *hostRun, code *int, signal int) { session := r.service.Host.Running(run.pluginID) if session == nil || session.Session.ID != run.backend { return @@ -538,7 +672,7 @@ func (r *Runs) notifyExit(run *hostRun, code *int, signal string) { if code != nil { body["exitCode"] = *code } - if signal != "" { + if signal > 0 && signal <= 127 { body["signal"] = signal } params, err := json.Marshal(body) @@ -547,32 +681,39 @@ func (r *Runs) notifyExit(run *hostRun, code *int, signal string) { } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - r.service.Host.Notify(ctx, run.pluginID, methodRunStart, notifyRunDidExit, params) + session.notify(ctx, methodRunStart, notifyRunDidExit, params) } // exitStatus separates a normal exit code from a terminating signal. A process // that could not report either has neither. -func exitStatus(err error) (*int, string) { +func exitStatus(err error) (*int, int) { if err == nil { code := 0 - return &code, "" + return &code, 0 } var debugEnd *debugRunExit if errors.As(err, &debugEnd) { - return debugEnd.code, "" + return debugEnd.code, 0 + } + var remoteEnd *buildprocess.RemoteExit + if errors.As(err, &remoteEnd) { + if remoteEnd.Status.Signal != nil { + return nil, *remoteEnd.Status.Signal + } + return remoteEnd.Status.ExitCode, 0 } var exit *exec.ExitError if errors.As(err, &exit) { if code := exit.ExitCode(); code >= 0 { - return &code, "" + return &code, 0 } if state := exit.ProcessState; state != nil { - if _, signal, found := strings.Cut(state.String(), "signal: "); found { - return nil, strings.TrimSpace(signal) + if status, ok := state.Sys().(syscall.WaitStatus); ok && status.Signaled() { + return nil, int(status.Signal()) } } } - return nil, "" + return nil, 0 } // attachDebugger waits for the debuggee's port, then asks the host to attach the @@ -586,9 +727,8 @@ func (r *Runs) attachDebugger(ctx context.Context, run *hostRun) { r.stopRun(run, false) } } - err := waitForDebugPort(ctx, port, run.done, RunDebugConnectTimeout, func(context.Context) (bool, error) { - return debuggeeListening(run.pid, uint16(port)) - }) + reader, _ := r.service.kernel.(remoteDebugPortReader) + err := WaitForOwnedDebugPort(attachedRunContext(ctx, run.connection), reader, run.process, port, run.done) if err != nil { fail(err) return @@ -600,13 +740,48 @@ func (r *Runs) attachDebugger(ctx context.Context, run *hostRun) { session, err := r.Debug(ctx, RunDebugRequest{ PluginID: run.pluginID, WorkspaceRoot: run.workspace.Path, Label: run.start.Label, ConfigurationType: run.start.Debug.ConfigurationType, Host: "127.0.0.1", Port: port, - StopRun: func() { r.stopRun(run, false) }, + Connection: run.connection, + StopRun: func() { r.stopRun(run, false) }, }) if err != nil { fail(err) return } run.debug.Store(&session) + <-ctx.Done() + if r.StopDebugSession != nil { + r.StopDebugSession(session) + } +} + +func attachedRunContext(ctx context.Context, connection *core.RemoteWorkspaceConnection) context.Context { + if connection != nil { + return connection.Context(ctx) + } + return ctx +} + +type remoteDebugPortReader interface { + RemoteProcessDebugPortReady(context.Context, uint64, int) (bool, error) +} + +// WaitForOwnedDebugPort observes a Run-owned process's listener on its host. +func WaitForOwnedDebugPort(ctx context.Context, reader remoteDebugPortReader, process interface{ Wait() error }, port int, ended <-chan struct{}) error { + if remote, ok := process.(*buildprocess.RemoteProcess); ok { + if reader == nil { + return errors.New("this host cannot inspect remote debug ports") + } + return waitForDebugPort(ctx, port, ended, RunDebugConnectTimeout, func(ctx context.Context) (bool, error) { + return reader.RemoteProcessDebugPortReady(ctx, remote.ID, port) + }) + } + local, ok := process.(interface{ Pid() int }) + if !ok || local.Pid() <= 0 { + return errors.New("the debuggee has no local process") + } + return waitForDebugPort(ctx, port, ended, RunDebugConnectTimeout, func(context.Context) (bool, error) { + return debuggeeListening(local.Pid(), uint16(port)) + }) } // ErrDebuggeeEnded and ErrDebugPortTimeout are why WaitForDebugPort gave up: the diff --git a/desktop/internal/pluginservice/runs_test.go b/desktop/internal/pluginservice/runs_test.go index 41fbea11f7..061edca492 100644 --- a/desktop/internal/pluginservice/runs_test.go +++ b/desktop/internal/pluginservice/runs_test.go @@ -104,6 +104,11 @@ type runHarness struct { } func newRunHarness(t *testing.T) *runHarness { + t.Helper() + return newRunHarnessWithKernel(t, &runKernel{client: core.NewClient()}) +} + +func newRunHarnessWithKernel(t *testing.T, kernel Kernel) *runHarness { t.Helper() preferences := store.At(t.TempDir()) pluginRoot := t.TempDir() @@ -121,7 +126,7 @@ func newRunHarness(t *testing.T) *runHarness { if err := pluginstate.New(preferences).SetEnabled(runFixturePlugin, true); err != nil { t.Fatal(err) } - service, err := Open(&runKernel{client: core.NewClient()}, preferences, pluginRoot) + service, err := Open(kernel, preferences, pluginRoot) if err != nil { t.Fatal(err) } @@ -131,7 +136,7 @@ func newRunHarness(t *testing.T) *runHarness { h.events = append(h.events, event) h.mu.Unlock() }) - service.Runs.Tools = func(_ context.Context, _, tool string) (RunExecutable, error) { + service.Runs.Tools = func(_ context.Context, _, _, tool string) (RunExecutable, error) { if tool != "interpreter" { return RunExecutable{}, fmt.Errorf("no tool %s", tool) } @@ -374,7 +379,7 @@ func TestRunStartRefusals(t *testing.T) { t.Fatalf("details = %s (%v), want Core's code and field", refusal.Details, err) } - h.service.Runs.Tools = func(context.Context, string, string) (RunExecutable, error) { + h.service.Runs.Tools = func(context.Context, string, string, string) (RunExecutable, error) { return RunExecutable{}, fmt.Errorf("no interpreter installed") } _, refusal = respond(t, h.service, runFixturePlugin, "run/start", h.params(t, "print", nil)) diff --git a/desktop/internal/pluginservice/settings.go b/desktop/internal/pluginservice/settings.go index ec737662d4..634d0fa44b 100644 --- a/desktop/internal/pluginservice/settings.go +++ b/desktop/internal/pluginservice/settings.go @@ -2,7 +2,9 @@ package pluginservice import ( "context" + "encoding/json" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginbackend" ) @@ -20,17 +22,44 @@ func (s *Service) ApplyLanguageSettings(ctx context.Context, session *LanguageSe if session == nil { return LanguageConfigurationResult{}, pluginbackend.ErrNoSession } - snapshot, err := s.Settings.Load(ctx, session.manifest, session.workspace) + ctx = core.WithoutRemoteWorkspace(ctx) + settings, err := s.ReadWorkspacePluginSettings(ctx, session.manifest, session.workspace, session.remote) if err != nil { return LanguageConfigurationResult{}, err } - configuration, err := s.kernel.ExpandPluginWorkspaceConfiguration(ctx, session.manifest, session.LanguageID, snapshot.State.Settings, snapshot.State.ProjectSettings) + configuration, err := s.kernel.ExpandPluginWorkspaceConfiguration(ctx, session.manifest, session.LanguageID, settings.Settings, settings.ProjectSettings) if err != nil { return LanguageConfigurationResult{}, err } if configuration == nil { return LanguageConfigurationResult{}, nil } + if session.remote != nil && !session.remote.IsCurrent() { + return LanguageConfigurationResult{}, workspaceSettingsConnectionChanged() + } sent, err := s.kernel.UpdatePluginWorkspaceConfiguration(ctx, session.Session.ID, configuration) return LanguageConfigurationResult{Available: true, Sent: sent}, err } + +// ReadWorkspacePluginSettings combines the user's preferences on this +// computer with the project layer read from the selected workspace host. +func (s *Service) ReadWorkspacePluginSettings(ctx context.Context, manifest json.RawMessage, workspace string, remote *core.RemoteWorkspaceConnection) (core.PluginSettingsState, error) { + if remote == nil { + snapshot, err := s.Settings.Load(ctx, manifest, workspace) + return snapshot.State, err + } + if !remote.IsCurrent() { + return core.PluginSettingsState{}, workspaceSettingsConnectionChanged() + } + settings, err := s.Settings.LoadRemote(core.WithoutRemoteWorkspace(ctx), manifest, func(ctx context.Context, path string, maximumBytes int64) (*string, error) { + return s.kernel.ReadWorkspaceConfiguration(remote.Context(ctx), path, maximumBytes) + }) + if err == nil && !remote.IsCurrent() { + return core.PluginSettingsState{}, workspaceSettingsConnectionChanged() + } + return settings, err +} + +func workspaceSettingsConnectionChanged() error { + return &core.Error{Code: core.CodeConnectionClosed, Message: "The workspace connection changed."} +} diff --git a/desktop/internal/pluginservice/settings_editor.go b/desktop/internal/pluginservice/settings_editor.go index 2776730425..d3c9565a18 100644 --- a/desktop/internal/pluginservice/settings_editor.go +++ b/desktop/internal/pluginservice/settings_editor.go @@ -21,6 +21,7 @@ type SettingsEditor struct { entry pluginmanager.Entry directory os.FileInfo workspaceIdentity os.FileInfo + remote *core.RemoteWorkspaceConnection manifest []byte } @@ -69,6 +70,28 @@ func (s *Service) settingsEntry(ctx context.Context, id string) (pluginmanager.E // language is the interface language tag; translations are read from the // installed package, so an empty language keeps manifest text. func (s *Service) LoadSettingsEditor(ctx context.Context, id, workspace, language string) (SettingsEditor, error) { + return s.loadSettingsEditor(ctx, id, workspace, language, nil) +} + +// LoadRemoteSettingsEditor captures a host-backed editor independent of the +// local placeholder directory and rejects disconnected workspaces. +func (s *Service) LoadRemoteSettingsEditor(ctx context.Context, id, language, name string, binding *core.RemoteWorkspace) (SettingsEditor, error) { + if s == nil || s.Settings == nil { + return SettingsEditor{}, ErrAssembly + } + storage, ok := s.kernel.(pluginsettings.RemoteProjectStorage) + if !ok { + return SettingsEditor{}, ErrAssembly + } + connection := binding.CaptureConnection() + if connection == nil { + return SettingsEditor{}, workspaceSettingsConnectionChanged() + } + remote := &pluginsettings.RemoteProject{Storage: storage, Connection: connection, Name: name} + return s.loadSettingsEditor(ctx, id, binding.LocalRoot(), language, remote) +} + +func (s *Service) loadSettingsEditor(ctx context.Context, id, workspace, language string, remote *pluginsettings.RemoteProject) (SettingsEditor, error) { if s == nil || s.Settings == nil { return SettingsEditor{}, ErrAssembly } @@ -88,22 +111,31 @@ func (s *Service) LoadSettingsEditor(ctx context.Context, id, workspace, languag return SettingsEditor{}, err } var workspaceIdentity os.FileInfo - if workspace != "" { + if workspace != "" && remote == nil { workspaceIdentity, err = settingsPackageDirectoryInfo(ctx, workspace) if err != nil { return SettingsEditor{}, err } } + var presentation *pluginsettings.Presentation + if language != "" { + presentation = &pluginsettings.Presentation{Language: language, Package: entry.Installed.Path} + } var snapshot pluginsettings.Snapshot - if language == "" { + var connection *core.RemoteWorkspaceConnection + switch { + case remote != nil: + connection = remote.Connection + snapshot, err = s.Settings.LoadRemoteEditor(ctx, manifest.Bytes(), workspace, presentation, *remote) + case presentation != nil: + snapshot, err = s.Settings.LoadPresented(ctx, manifest.Bytes(), workspace, *presentation) + default: snapshot, err = s.Settings.Load(ctx, manifest.Bytes(), workspace) - } else { - snapshot, err = s.Settings.LoadPresented(ctx, manifest.Bytes(), workspace, pluginsettings.Presentation{Language: language, Package: entry.Installed.Path}) } if err != nil { return SettingsEditor{}, err } - return SettingsEditor{Snapshot: snapshot, entry: entry, directory: info, workspaceIdentity: workspaceIdentity, manifest: manifest.Bytes()}, nil + return SettingsEditor{Snapshot: snapshot, entry: entry, directory: info, workspaceIdentity: workspaceIdentity, remote: connection, manifest: manifest.Bytes()}, nil } // SaveSettingsEditor rejects replacement, uninstall and upgrade before publishing @@ -146,6 +178,9 @@ func (s *Service) checkSettingsEditor(ctx context.Context, editor SettingsEditor if !bytes.Equal(manifest.Bytes(), editor.manifest) { return pluginmanager.Entry{}, configfile.ErrConflict } + if editor.remote != nil && !editor.remote.IsCurrent() { + return pluginmanager.Entry{}, errors.Join(configfile.ErrConflict, workspaceSettingsConnectionChanged()) + } if editor.workspaceIdentity != nil { current, err := settingsPackageDirectoryInfo(ctx, editor.Snapshot.Workspace()) if err != nil { @@ -161,6 +196,8 @@ func (s *Service) checkSettingsEditor(ctx context.Context, editor SettingsEditor // PlanSettingsEditorAction revalidates the captured installed package around a // pure Core plan. It neither saves drafts nor admits or starts a backend. func (s *Service) PlanSettingsEditorAction(ctx context.Context, editor SettingsEditor, actionID string, confirmed bool, check func() error) (core.PluginSettingsActionPlan, error) { + // The installed manifest is local; the check separately validates the captured attachment. + ctx = core.WithoutRemoteWorkspace(ctx) if s == nil || s.Settings == nil { return core.PluginSettingsActionPlan{}, ErrAssembly } @@ -222,6 +259,9 @@ func (e SettingsEditor) SettingsOwner() core.PluginSettingsOwner { return core.PluginSettingsOwner{PluginID: e.entry.Installed.ID, Version: e.entry.Installed.Version} } +// RemoteConnection returns the attachment captured on load, if any. +func (e SettingsEditor) RemoteConnection() *core.RemoteWorkspaceConnection { return e.remote } + // Package is the installed package directory the editor was read from, which a region's // canvas reads its images from. It is read only. func (e SettingsEditor) Package() string { @@ -300,7 +340,7 @@ func (s *Service) SettingsPages(ctx context.Context, language string) ([]core.Se // PlanSettingsDelivery captures native identities off the UI thread and delegates // scope/effect policy to Core. It reads no saved values from the source window. -func (s *Service) PlanSettingsDelivery(ctx context.Context, editor SettingsEditor, scope string, effects []string, workspace string) (core.SettingsDelivery, error) { +func (s *Service) PlanSettingsDelivery(ctx context.Context, editor SettingsEditor, scope string, effects []string, workspace string, remote *core.RemoteWorkspaceConnection) (core.SettingsDelivery, error) { kernel, ok := s.kernel.(interface { SettingsDelivery(context.Context, core.SettingsDeliveryRequest) (core.SettingsDelivery, error) }) @@ -333,12 +373,17 @@ func (s *Service) PlanSettingsDelivery(ctx context.Context, editor SettingsEdito return core.SettingsDelivery{}, nil } sameWorkspace := false - if scope == "project" && workspace != "" && editor.workspaceIdentity != nil { - info, err := settingsPackageDirectoryInfo(ctx, workspace) - if err != nil { - return core.SettingsDelivery{}, err + if scope == "project" { + switch { + case editor.remote != nil: + sameWorkspace = editor.remote.SameWorkspace(remote) && remote.IsCurrent() + case remote == nil && workspace != "" && editor.workspaceIdentity != nil: + info, err := settingsPackageDirectoryInfo(ctx, workspace) + if err != nil { + return core.SettingsDelivery{}, err + } + sameWorkspace = os.SameFile(editor.workspaceIdentity, info) } - sameWorkspace = os.SameFile(editor.workspaceIdentity, info) } entries, err := s.CurrentInstalled(ctx) if err != nil { diff --git a/desktop/internal/pluginservice/settings_start_test.go b/desktop/internal/pluginservice/settings_start_test.go index 82baaa429d..5ebf60749a 100644 --- a/desktop/internal/pluginservice/settings_start_test.go +++ b/desktop/internal/pluginservice/settings_start_test.go @@ -159,3 +159,112 @@ func TestSavedProjectSettingIsRereadBeforeUpdatingTheCurrentLanguageSession(t *t t.Fatalf("invalid source changed the live session: session=%q error=%v", kernel.updatedSession, err) } } + +// The Core planner and settings projection are real. Only the remote file +// transport and process handoff are substituted at the desktop bridge. +type remoteSettingsKernel struct { + *settingsPlanningKernel + binding *core.RemoteWorkspace + read func() (string, error) + start func(context.Context, core.PluginBackendStart) +} + +func (k *remoteSettingsKernel) PlanPluginLanguageServer(ctx context.Context, manifest json.RawMessage, language string, directories core.PluginBackendDirectories) (core.PluginBackendPlan, error) { + k.directories = directories + return k.client.PlanPluginLanguageServer(ctx, manifest, language, directories) +} + +func (k *remoteSettingsKernel) ReadWorkspaceConfiguration(ctx context.Context, path string, maximumBytes int64) (*string, error) { + if core.RemoteWorkspaceOf(ctx) != k.binding || path != ".lithe/plugin-settings.json" || maximumBytes <= 0 { + return nil, errors.New("remote setting read used the wrong source or connection") + } + value, err := k.read() + return &value, err +} + +func (k *remoteSettingsKernel) StartPluginLanguageServer(ctx context.Context, request core.PluginBackendStart) (core.PluginBackendStarted, error) { + k.start(ctx, request) + return core.PluginBackendStarted{SessionID: "remote-language-session"}, nil +} + +func TestRemoteLanguageServerUsesTheWorkspaceHostAndItsSettings(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + entry := serverPackage(t, "1.0.0", true, "fixture") + entry.Installed.ID = "dev.example.remote-settings" + manifest := []byte(`{ + "schemaVersion":0,"pluginAPIVersion":0,"id":"dev.example.remote-settings","displayName":"Remote Settings","version":"1.0.0", + "vendor":{"id":"dev.example","displayName":"Fixture","signatureRequirement":"none"}, + "requires":{"settings":0,"languages":0,"languageServers":0},"permissions":["languageServer.launch"], + "activationEvents":["onLanguage:fixture"],"languages":[{"id":"fixture","displayName":"Fixture","fileExtensions":["fixture"]}], + "settings":[{"id":"flag","type":"boolean","title":"Flag","default":true,"scope":"project","effect":"immediate"}], + "languageServers":[{"languageID":"fixture","remote":"supported","launch":{"kind":"systemCommand","commands":["lithe-remote-fixture-server"]},"workspaceConfiguration":{"fixture":{"flag":"${setting:flag}"}}}] + }`) + if err := os.WriteFile(filepath.Join(entry.Installed.Path, pluginpkg.ManifestFile), manifest, 0o600); err != nil { + t.Fatal(err) + } + preferences := t.TempDir() + if err := os.WriteFile(filepath.Join(preferences, "plugin-settings.json"), []byte(`{"dev.example.remote-settings":{"flag":true}}`), 0o600); err != nil { + t.Fatal(err) + } + placeholder := t.TempDir() + if err := os.Mkdir(filepath.Join(placeholder, ".lithe"), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(placeholder, ".lithe", "plugin-settings.json"), []byte("not a workspace source"), 0o600); err != nil { + t.Fatal(err) + } + binding := core.NewRemoteWorkspace(placeholder, "/home/fixture/project", nil) + binding.Attach("remote-fixture") + kernel := &remoteSettingsKernel{settingsPlanningKernel: &settingsPlanningKernel{fakeKernel: &fakeKernel{}, client: core.NewClient()}, binding: binding} + kernel.read = func() (string, error) { return `{"dev.example.remote-settings":{"flag":false}}`, nil } + kernel.start = func(ctx context.Context, request core.PluginBackendStart) { + if core.RemoteWorkspaceOf(ctx) != binding || request.ExecutablePath != "" || len(request.RemoteCommands) != 1 || request.RemoteCommands[0] != "lithe-remote-fixture-server" { + t.Fatalf("process was not dispatched through the workspace host: %+v", request) + } + if string(request.WorkspaceConfiguration) != `{"fixture":{"flag":false}}` { + t.Fatalf("start ignored remote configuration: %s", request.WorkspaceConfiguration) + } + } + service, err := Open(kernel, store.At(preferences), t.TempDir()) + if err != nil { + t.Fatal(err) + } + workspace := service.Contexts.OpenRemote(binding, "Fixture", "c-fixture", core.RemotePlatform{OS: "linux", Arch: "x86_64"}, nil) + t.Cleanup(service.Contexts.CloseAll) + session, err := service.StartLanguageServer(ctx, []pluginmanager.Entry{entry}, "fixture", BackendRequest{ + RootURI: "file:///placeholder", WorkingDirectory: placeholder, Architecture: "arm64", Context: workspace.ContextRef, + RemoteConnection: binding.CaptureConnection(), ProjectCodeAllowed: true, + }) + if err != nil || session == nil { + t.Fatalf("start remote server: session=%v error=%v", session, err) + } + t.Cleanup(func() { + stopCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := service.StopLanguageServer(stopCtx, session); err != nil { + t.Error(err) + } + }) + if !kernel.directories.RemoteWorkspace || kernel.directories.Architecture != "x86_64" { + t.Fatalf("planner ignored the workspace host: %+v", kernel.directories) + } + if _, err := service.ApplyLanguageSettings(ctx, session); err != nil { + t.Fatalf("reload remote settings: %v", err) + } + if kernel.updatedSession != session.Session.ID || string(kernel.updatedConfiguration) != `{"fixture":{"flag":false}}` { + t.Fatalf("reload used the wrong source or session: %s %s", kernel.updatedSession, kernel.updatedConfiguration) + } + + kernel.updatedSession = "" + kernel.read = func() (string, error) { + // A replacement may reuse the Core session ID. An in-flight preference + // read still belongs to the connection that started it. + binding.Attach("remote-fixture") + return `{"dev.example.remote-settings":{"flag":true}}`, nil + } + var connectionErr *core.Error + if _, err := service.ApplyLanguageSettings(ctx, session); !errors.As(err, &connectionErr) || connectionErr.Code != core.CodeConnectionClosed || kernel.updatedSession != "" { + t.Fatalf("stale reload reached the retired language server: session=%q error=%v", kernel.updatedSession, err) + } +} diff --git a/desktop/internal/pluginservice/toolchain_provider.go b/desktop/internal/pluginservice/toolchain_provider.go index f6fc90df8c..24b30df96e 100644 --- a/desktop/internal/pluginservice/toolchain_provider.go +++ b/desktop/internal/pluginservice/toolchain_provider.go @@ -35,6 +35,9 @@ func (s *Service) ToolchainOptions(root string, options toolchain.Options) toolc if expected, err := os.Stat(root); err == nil { _, contexts := s.Contexts.List() for _, candidate := range contexts { + if candidate.authorityKind() != "local" { + continue + } if info, err := os.Stat(candidate.Path); err == nil && os.SameFile(info, expected) { workspace, present = candidate, true break @@ -42,7 +45,7 @@ func (s *Service) ToolchainOptions(root string, options toolchain.Options) toolc } } } - if !present { + if !present || workspace.authorityKind() != "local" { // No project context is available for paths that a consumer is inspecting // without opening. Such paths remain eligible for declarative discovery. options.Providers = nil diff --git a/desktop/internal/pluginsettings/remote.go b/desktop/internal/pluginsettings/remote.go new file mode 100644 index 0000000000..c47b2316be --- /dev/null +++ b/desktop/internal/pluginsettings/remote.go @@ -0,0 +1,104 @@ +package pluginsettings + +import ( + "context" + "encoding/json" + "errors" + "path" + + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// RemoteProjectStorage is the host-specific part of a settings publication. +// Core chooses the only eligible source and checks its revision on the host. +type RemoteProjectStorage interface { + ReadProjectPluginSettings(context.Context) (core.ProjectPluginSettings, error) + PublishProjectPluginSettings(context.Context, core.ProjectPluginSettingsBaseline, *string) (bool, bool, error) +} + +// RemoteProject owns one captured attachment for the lifetime of an editor. +type RemoteProject struct { + Connection *core.RemoteWorkspaceConnection + Storage RemoteProjectStorage + Name string +} + +type remoteProjectSnapshot struct { + project RemoteProject + source core.ProjectPluginSettings + root string +} + +// LoadRemoteEditor reads the local user layer and the host project layer, +// keeping the host's baseline private so the same source can be saved. +func (s *Store) LoadRemoteEditor(ctx context.Context, manifest json.RawMessage, workspace string, presentation *Presentation, project RemoteProject) (Snapshot, error) { + if !project.Connection.IsCurrent() { + return Snapshot{}, remoteSourceChanged() + } + binding := core.RemoteWorkspaceOf(project.Connection.Context(ctx)) + if binding.LocalRoot() != workspace { + return Snapshot{}, configfile.ErrConflict + } + baseline := &remoteProjectSnapshot{project: project, root: binding.RemoteRoot()} + snapshot, err := s.load(core.WithoutRemoteWorkspace(ctx), manifest, workspace, presentation, func(ctx context.Context, relative string, _ int64) (*string, error) { + source, err := project.Storage.ReadProjectPluginSettings(project.Connection.Context(ctx)) + if err != nil { + return nil, err + } + if source.Path != relative || source.Baseline.WorkspaceIdentity == "" { + return nil, configfile.ErrTarget + } + baseline.source = source + return source.Text, nil + }) + if err != nil { + return Snapshot{}, err + } + if !project.Connection.IsCurrent() { + return Snapshot{}, remoteSourceChanged() + } + snapshot.remote = baseline + return snapshot, nil +} + +func (s *remoteProjectSnapshot) displayPath() string { + if s.source.Path == "" { + return "" + } + return path.Join(s.root, s.source.Path) +} + +func (s *remoteProjectSnapshot) publish(ctx context.Context, plan core.PluginSettingsEditPlan, check func() error) (bool, error) { + if s.source.Baseline.WorkspaceIdentity == "" { + return false, configfile.ErrTarget + } + if !s.project.Connection.IsCurrent() { + return false, remoteSourceChanged() + } + if check != nil { + if err := check(); err != nil { + return false, err + } + } + content := &plan.Document + if plan.Delete { + content = nil + } + committed, conflict, err := s.project.Storage.PublishProjectPluginSettings(s.project.Connection.Context(ctx), s.source.Baseline, content) + if conflict { + err = errors.Join(configfile.ErrConflict, err) + } + return committed, err +} + +func (s *remoteProjectSnapshot) matches(plan core.PluginSettingsEditPlan) bool { + if plan.Delete { + return s.source.Text == nil + } + return s.source.Text != nil && *s.source.Text == plan.Document +} + +func remoteSourceChanged() error { + return &core.Error{Code: core.CodeConnectionClosed, Message: "The workspace connection changed."} +} diff --git a/desktop/internal/pluginsettings/remote_sources.go b/desktop/internal/pluginsettings/remote_sources.go new file mode 100644 index 0000000000..ffe7672de7 --- /dev/null +++ b/desktop/internal/pluginsettings/remote_sources.go @@ -0,0 +1,186 @@ +package pluginsettings + +import ( + "context" + "crypto/rand" + "encoding/json" + "errors" + "path" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// RemoteSourceHost operates on captured host files. Neither a baseline nor a +// staged output includes the native document's bytes. +type RemoteSourceHost interface { + InspectRemoteNativeSettings(context.Context, []core.RemoteNativeSettingsTarget) ([]core.RemoteNativeSettingsBaseline, error) + StageRemoteNativeSettings(context.Context, string, []core.RemoteNativeSettingsBaseline) ([]string, error) + PublishRemoteNativeSettings(context.Context, string, []core.RemoteNativeSettingsReplacement) ([]uint16, bool, error) + CreateRemoteRuntimeStaging(context.Context, string) (string, error) + ReleaseRemoteRunDirectory(context.Context, string) error +} + +type remoteSources struct { + host RemoteSourceHost + connection *core.RemoteWorkspaceConnection + baselines map[string]core.RemoteNativeSettingsBaseline +} + +// CaptureRemoteSources independently checks every writable namespace binding +// against the host before exposing its path or admitting edits. +func CaptureRemoteSources(ctx context.Context, host RemoteSourceHost, connection *core.RemoteWorkspaceConnection, state core.SourceSettingsState) (SourceEditor, error) { + if !connection.IsCurrent() { + return SourceEditor{}, configfile.ErrConflict + } + editor := SourceEditor{State: state, remote: &remoteSources{ + host: host, connection: connection, baselines: make(map[string]core.RemoteNativeSettingsBaseline), + }} + editor.State.Snapshot.Sources = append([]core.SettingsSource(nil), state.Snapshot.Sources...) + targets := make([]core.RemoteNativeSettingsTarget, 0, len(state.Snapshot.Sources)) + indices := make([]int, 0, len(state.Snapshot.Sources)) + for index, source := range state.Snapshot.Sources { + switch source.Scope { + case "workspace", "home": + targets = append(targets, core.RemoteNativeSettingsTarget{Scope: source.Scope, Path: source.Path}) + indices = append(indices, index) + case "hostReadOnly": + // Core admits only absolute paths with writable=false in this scope. + default: + return SourceEditor{}, configfile.ErrTarget + } + } + if len(targets) != 0 { + baselines, err := host.InspectRemoteNativeSettings(connection.Context(ctx), targets) + if err != nil { + return SourceEditor{}, remoteSourceError(err) + } + if len(baselines) != len(targets) { + return SourceEditor{}, configfile.ErrConflict + } + for index, baseline := range baselines { + source := &editor.State.Snapshot.Sources[indices[index]] + if baseline.Target != targets[index] || baseline.Identity == "" || + baseline.Revision != source.Revision || !path.IsAbs(baseline.HostPath) { + return SourceEditor{}, configfile.ErrConflict + } + source.Writable = source.Writable && baseline.Writable + editor.remote.baselines[source.ID] = baseline + } + } + if !connection.IsCurrent() { + return SourceEditor{}, configfile.ErrConflict + } + return editor, ctx.Err() +} + +// IsRemote identifies a source projection captured on a remote attachment. +func (s SourceEditor) IsRemote() bool { return s.remote != nil } + +// DisplayPath returns the path the native host verified for this binding. +func (s SourceEditor) DisplayPath(source core.SettingsSource) string { + if s.remote != nil { + if baseline, ok := s.remote.baselines[source.ID]; ok { + return baseline.HostPath + } + } + return source.Path +} + +// MatchesConnection prevents a source editor from moving to a new attachment. +func (s SourceEditor) MatchesConnection(connection *core.RemoteWorkspaceConnection) bool { + if s.remote == nil { + return connection == nil + } + return s.remote.connection.SameAttachment(connection) && s.remote.connection.IsCurrent() +} + +func (s *remoteSources) apply(ctx context.Context, kernel SourceKernel, writes []core.SourceSettingsWrite, call func(context.Context, json.RawMessage) (json.RawMessage, error), check func() error) (map[string]string, error) { + ctx = s.connection.Context(ctx) + baselines := make([]core.RemoteNativeSettingsBaseline, len(writes)) + for index, write := range writes { + baseline, ok := s.baselines[write.SourceID] + if !ok || !baseline.Writable || baseline.Target.Path != write.Path || baseline.Revision != write.Revision { + return nil, configfile.ErrConflict + } + baselines[index] = baseline + } + + id := "settings-" + rand.Text() + return s.withStaging(ctx, id, func(directory string) (map[string]string, error) { + files, err := s.host.StageRemoteNativeSettings(ctx, id, baselines) + if err != nil { + return nil, remoteSourceError(err) + } + if len(files) != len(writes) { + return nil, configfile.ErrConflict + } + var replacements []core.RemoteNativeSettingsReplacement + for index, write := range writes { + if path.Dir(files[index]) != directory { + return nil, configfile.ErrTarget + } + if err := check(); err != nil { + return nil, err + } + params, err := sourceEditRequest(write, files[index], baselines[index].HostPath) + if err != nil { + return nil, err + } + result, err := call(ctx, params) + if err != nil { + return nil, err + } + receipt, err := kernel.DecodeSourceSettingsReceipt(ctx, write, result) + if err != nil { + return nil, err + } + if receipt.Changed { + replacements = append(replacements, core.RemoteNativeSettingsReplacement{ + Slot: uint16(index), Baseline: baselines[index], Revision: receipt.Revision, + }) + } + } + if len(replacements) == 0 { + return nil, nil + } + if err := check(); err != nil { + return nil, err + } + committed, uncertain, err := s.host.PublishRemoteNativeSettings(ctx, id, replacements) + published := make(map[string]string, len(committed)) + // The host acknowledges a prefix in the same order it was asked to publish. + for index, slot := range committed { + if index >= len(replacements) || replacements[index].Slot != slot { + return published, errors.Join(ErrSourcesCommitted, configfile.ErrConflict, err) + } + published[writes[slot].SourceID] = replacements[index].Revision + } + if uncertain || (err == nil && len(committed) != len(replacements)) { + return published, errors.Join(ErrSourcesCommitted, configfile.ErrConflict, err) + } + return published, remoteSourceError(err) + }) +} + +func (s *remoteSources) withStaging(ctx context.Context, id string, use func(string) (map[string]string, error)) (published map[string]string, err error) { + // Allocation can succeed remotely while the client loses its reply. + defer func() { + cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + defer cancel() + err = errors.Join(err, s.host.ReleaseRemoteRunDirectory(cleanup, id)) + }() + dir, err := s.host.CreateRemoteRuntimeStaging(ctx, id) + if err != nil { + return nil, err + } + return use(dir) +} + +func remoteSourceError(err error) error { + if core.IsRemoteNativeSettingsConflict(err) { + return errors.Join(configfile.ErrConflict, err) + } + return err +} diff --git a/desktop/internal/pluginsettings/sources.go b/desktop/internal/pluginsettings/sources.go index 390d5ba0e4..ad8121c7c1 100644 --- a/desktop/internal/pluginsettings/sources.go +++ b/desktop/internal/pluginsettings/sources.go @@ -31,6 +31,7 @@ type SourceEditor struct { paths map[string]string limits core.SourceSettingsLimits protectedRoots []string + remote *remoteSources } func sourceRevision(file configfile.Snapshot) string { @@ -54,6 +55,9 @@ func CaptureSources(ctx context.Context, workspace string, state core.SourceSett if err := ctx.Err(); err != nil { return editor, err } + if source.Scope != "" { + return editor, configfile.ErrTarget + } file, err := configfile.Capture(ctx, workspace, source.Path, editor.limits.MaximumSourceBytes) if err != nil { return editor, err @@ -153,6 +157,9 @@ func (s SourceEditor) Apply(ctx context.Context, kernel SourceKernel, edits []co if err := check(); err != nil { return published, err } + if s.remote != nil { + return s.remote.apply(ctx, kernel, writes, call, check) + } staging, err := os.MkdirTemp("", "lithe-source-settings-") if err != nil { return published, err @@ -179,13 +186,7 @@ func (s SourceEditor) Apply(ctx context.Context, kernel SourceKernel, edits []co if err := file.Close(); err != nil { return published, err } - params, err := json.Marshal(struct { - Operation string `json:"operation"` - SourceID string `json:"sourceID"` - Revision string `json:"revision"` - Values map[string]json.RawMessage `json:"values"` - OutputFile string `json:"outputFile"` - }{"editSource", write.SourceID, write.Revision, write.Values, name}) + params, err := sourceEditRequest(write, name, "") if err != nil { return published, err } @@ -250,3 +251,14 @@ func (s SourceEditor) Apply(ctx context.Context, kernel SourceKernel, edits []co } return published, nil } + +func sourceEditRequest(write core.SourceSettingsWrite, output, hostPath string) ([]byte, error) { + return json.Marshal(struct { + Operation string `json:"operation"` + SourceID string `json:"sourceID"` + Revision string `json:"revision"` + Values map[string]json.RawMessage `json:"values"` + OutputFile string `json:"outputFile"` + HostPath string `json:"hostPath,omitempty"` + }{"editSource", write.SourceID, write.Revision, write.Values, output, hostPath}) +} diff --git a/desktop/internal/pluginsettings/store.go b/desktop/internal/pluginsettings/store.go index 8a6567ca0b..997ec9d80c 100644 --- a/desktop/internal/pluginsettings/store.go +++ b/desktop/internal/pluginsettings/store.go @@ -57,6 +57,7 @@ type Snapshot struct { global configfile.Snapshot project configfile.Snapshot unreadable []LocalizationReadFailure + remote *remoteProjectSnapshot } func (s Snapshot) Workspace() string { return s.workspace } @@ -74,12 +75,23 @@ func (s *Store) PreferenceDirectory() string { return s.globalRoot } func (s Snapshot) GlobalPath() string { return s.global.Path() } func (s Snapshot) ProjectPath() string { + if s.remote != nil { + return s.remote.displayPath() + } if s.workspace == "" { return "" } return s.project.Path() } +// ProjectConnectionName labels a remote settings source in the editor. +func (s Snapshot) ProjectConnectionName() string { + if s.remote == nil { + return "" + } + return s.remote.project.Name +} + // SaveResult distinguishes a committed source from readback/cleanup failures. // A caller must keep its draft and invalidate the baseline if Readback is nil; // it must not blindly retry a committed publication against the old snapshot. @@ -93,16 +105,23 @@ type SaveResult struct { // missing project is explicit; malformed or unreadable files never become empty. // Text stays as written in the manifest; use LoadPresented for a settings view. func (s *Store) Load(ctx context.Context, manifest json.RawMessage, workspace string) (Snapshot, error) { - return s.load(ctx, manifest, workspace, nil) + return s.load(ctx, manifest, workspace, nil, nil) +} + +// LoadRemote reads local global preferences and the project layer of a remote +// workspace. The returned projection carries no native edit baseline. +func (s *Store) LoadRemote(ctx context.Context, manifest json.RawMessage, readProject func(context.Context, string, int64) (*string, error)) (core.PluginSettingsState, error) { + snapshot, err := s.load(ctx, manifest, "", nil, readProject) + return snapshot.State, err } // LoadPresented also applies the package translation Core selects for the // language. Save readback keeps the same presentation. func (s *Store) LoadPresented(ctx context.Context, manifest json.RawMessage, workspace string, presentation Presentation) (Snapshot, error) { - return s.load(ctx, manifest, workspace, &presentation) + return s.load(ctx, manifest, workspace, &presentation, nil) } -func (s *Store) load(ctx context.Context, manifest json.RawMessage, workspace string, presentation *Presentation) (Snapshot, error) { +func (s *Store) load(ctx context.Context, manifest json.RawMessage, workspace string, presentation *Presentation, readProject func(context.Context, string, int64) (*string, error)) (Snapshot, error) { var localization *core.PluginSettingsLocalizationRequest if presentation != nil { localization = &core.PluginSettingsLocalizationRequest{Language: presentation.Language} @@ -139,7 +158,12 @@ func (s *Store) load(ctx context.Context, manifest json.RawMessage, workspace st return Snapshot{}, err } var project *string - if workspace != "" { + if readProject != nil { + project, err = readProject(ctx, policy.Storage.ProjectRelativePath, policy.Storage.MaximumBytes) + if err != nil { + return Snapshot{}, err + } + } else if workspace != "" { info, statErr := os.Stat(workspace) if statErr != nil { return Snapshot{}, errors.Join(ErrNoProject, statErr) @@ -201,13 +225,19 @@ func (s *Store) Save(ctx context.Context, snapshot Snapshot, scope string, edits } } var source configfile.Snapshot + var document *string + var err error switch scope { case "global": source = snapshot.global case "project": source = snapshot.project } - document, err := source.Text() + if scope == "project" && snapshot.remote != nil { + document = snapshot.remote.source.Text + } else { + document, err = source.Text() + } if err != nil { return SaveResult{}, err } @@ -219,7 +249,9 @@ func (s *Store) Save(ctx context.Context, snapshot Snapshot, scope string, edits return SaveResult{}, ErrNoProject } var result SaveResult - if plan.Delete { + if scope == "project" && snapshot.remote != nil { + result.Committed, err = snapshot.remote.publish(ctx, plan, check) + } else if plan.Delete { result.Committed, err = source.Remove(ctx, check) } else { result.Committed, err = source.Replace(ctx, []byte(plan.Document), check) @@ -229,7 +261,18 @@ func (s *Store) Save(ctx context.Context, snapshot Snapshot, scope string, edits } // Effects belong to the validated edit, but must not run before publication. result.Effects = plan.Effects - readback, readErr := New(s.kernel, snapshot.globalRoot).load(ctx, snapshot.manifest, snapshot.workspace, snapshot.presentation) + capturedStore := New(s.kernel, snapshot.globalRoot) + var readback Snapshot + var readErr error + if snapshot.remote != nil { + readback, readErr = capturedStore.LoadRemoteEditor(ctx, snapshot.manifest, snapshot.workspace, snapshot.presentation, snapshot.remote.project) + if readErr == nil && (readback.remote.source.Baseline.WorkspaceIdentity != snapshot.remote.source.Baseline.WorkspaceIdentity || + (scope == "project" && !readback.remote.matches(plan))) { + readErr = configfile.ErrConflict + } + } else { + readback, readErr = capturedStore.load(ctx, snapshot.manifest, snapshot.workspace, snapshot.presentation, nil) + } if readErr == nil { result.Readback = &readback } diff --git a/desktop/internal/plugintrust/plugintrust.go b/desktop/internal/plugintrust/plugintrust.go index fce1810bef..66171344d8 100644 --- a/desktop/internal/plugintrust/plugintrust.go +++ b/desktop/internal/plugintrust/plugintrust.go @@ -12,6 +12,8 @@ package plugintrust import ( + "crypto/sha256" + "encoding/hex" "encoding/json" "fmt" "sort" @@ -44,14 +46,16 @@ type Review struct { // Record is the provenance of one approved plugin version. type Record struct { - PluginID string `json:"pluginID"` - Version string `json:"version"` - Source Source `json:"source"` - ArchiveSHA256 string `json:"archiveSHA256,omitempty"` - MarketplaceIndexURL string `json:"marketplaceIndexURL,omitempty"` - ContentDigest string `json:"contentDigest,omitempty"` - Permissions []string `json:"permissions"` - ApprovedPrograms []json.RawMessage `json:"approvedPrograms"` + PluginID string `json:"pluginID"` + Version string `json:"version"` + Source Source `json:"source"` + ArchiveSHA256 string `json:"archiveSHA256,omitempty"` + MarketplaceIndexURL string `json:"marketplaceIndexURL,omitempty"` + MarketplaceRepository string `json:"marketplaceRepository,omitempty"` + ContentDigest string `json:"contentDigest,omitempty"` + SealedTreeSHA256 string `json:"sealedTreeSHA256,omitempty"` + Permissions []string `json:"permissions"` + ApprovedPrograms []json.RawMessage `json:"approvedPrograms"` } // Request is what the host knows about the package it is about to install. @@ -62,8 +66,12 @@ type Request struct { ArchiveSHA256 string // MarketplaceIndexURL is the canonical index source, not a plugin's own claim. MarketplaceIndexURL string + // MarketplaceRepository is the release repository in the approved listing. + MarketplaceRepository string // ContentDigest is the digest of the extracted package tree. ContentDigest string + // SealedTreeSHA256 covers package file boundaries and execute bits. + SealedTreeSHA256 string // Review is Core's install review for this package. Review Review } @@ -120,14 +128,16 @@ func Decide(record Record, found bool, req Request) Decision { // RecordFor builds the record that approves req for one plugin version. func RecordFor(id, version string, req Request) Record { return Record{ - PluginID: id, - Version: version, - Source: req.Source, - ArchiveSHA256: req.ArchiveSHA256, - MarketplaceIndexURL: req.MarketplaceIndexURL, - ContentDigest: req.ContentDigest, - Permissions: append([]string(nil), req.Review.Permissions...), - ApprovedPrograms: clonePrograms(req.Review.Programs), + PluginID: id, + Version: version, + Source: req.Source, + ArchiveSHA256: req.ArchiveSHA256, + MarketplaceIndexURL: req.MarketplaceIndexURL, + MarketplaceRepository: req.MarketplaceRepository, + ContentDigest: req.ContentDigest, + SealedTreeSHA256: req.SealedTreeSHA256, + Permissions: append([]string(nil), req.Review.Permissions...), + ApprovedPrograms: clonePrograms(req.Review.Programs), } } @@ -144,6 +154,12 @@ func (r Record) Validate() error { default: return fmt.Errorf("%w: unknown source %q", ErrInvalidRecord, r.Source) } + if r.SealedTreeSHA256 != "" { + digest, err := hex.DecodeString(r.SealedTreeSHA256) + if err != nil || len(digest) != sha256.Size { + return fmt.Errorf("%w: invalid installed tree digest", ErrInvalidRecord) + } + } for _, program := range r.ApprovedPrograms { if !json.Valid(program) { return fmt.Errorf("%w: an approved program is not valid JSON", ErrInvalidRecord) diff --git a/desktop/internal/pluginweb/page.go b/desktop/internal/pluginweb/page.go index d896458e32..13217b6f83 100644 --- a/desktop/internal/pluginweb/page.go +++ b/desktop/internal/pluginweb/page.go @@ -33,6 +33,8 @@ const ( stateTimeout = 10 * time.Second // callTimeout bounds one function call of a page, consent included. callTimeout = 15 * time.Minute + // openFileTimeout bounds resolving and reading an editor document. + openFileTimeout = 30 * time.Second ) // Kernel is the part of Core a page uses. @@ -76,8 +78,8 @@ type Host interface { // or "" when cancelled. It is called off the window thread and blocks // until the user answers; Core lets a page have one dialog at a time. ChooseFile(pluginID string, request FileRequest) (string, error) - // OpenFile opens a workspace file in the editor on the window thread. - OpenFile(path string, line, column int) error + // OpenFile resolves a workspace file off the window thread and opens it in the editor. + OpenFile(ctx context.Context, path string, line, column int) error } // Failure is an answer a page receives as `{ code, message }`. @@ -334,8 +336,15 @@ func (p *Page) carryOut(action core.PluginWebAction) { p.answer(action, "", map[string]*string{"path": chosen}, nil) }() case "workspace.openFile": - err := host.OpenFile(params.Path, params.Line, params.Column) - go p.answer(action, "", struct{}{}, err) + go func() { + ctx, cancel := context.WithTimeout(p.ctx, openFileTimeout) + defer cancel() + err := host.OpenFile(ctx, params.Path, params.Line, params.Column) + if err != nil { + p.log("open_file", err) + } + p.answer(action, "", struct{}{}, err) + }() default: go p.answer(action, "", nil, Fail("plugin.web.unknownMethod", "This host does not answer "+action.Method+".")) } diff --git a/desktop/internal/pluginweb/page_test.go b/desktop/internal/pluginweb/page_test.go index f4eb632811..ace2c91fe4 100644 --- a/desktop/internal/pluginweb/page_test.go +++ b/desktop/internal/pluginweb/page_test.go @@ -82,7 +82,7 @@ func (h *fakeHost) ChooseFile(string, FileRequest) (string, error) { return h.chosen, nil } -func (h *fakeHost) OpenFile(path string, _, _ int) error { +func (h *fakeHost) OpenFile(_ context.Context, path string, _, _ int) error { h.mu.Lock() defer h.mu.Unlock() h.opened = append(h.opened, path) diff --git a/desktop/internal/settingswindow/page_driver_test.go b/desktop/internal/settingswindow/page_driver_test.go index 977ea93691..363b7cbb73 100644 --- a/desktop/internal/settingswindow/page_driver_test.go +++ b/desktop/internal/settingswindow/page_driver_test.go @@ -114,14 +114,27 @@ func (d *windowDriver) text(value string) bool { return false } -// wrapped reports whether the frame's labels, read in order, hold value, which a wrapping -// text splits over several labels. +// wrapped reports whether the frame's labels contain value. A wrap can drop the +// space between words or break inside a path without dropping any character. func (d *windowDriver) wrapped(value string) bool { - var lines []string - for _, label := range d.driver.Snapshot().Labels { - lines = append(lines, label.Value) + labels := d.driver.Snapshot().Labels + for start, label := range labels { + if strings.Contains(label.Value, value) { + return true + } + remaining := value + for _, line := range labels[start:] { + if strings.HasPrefix(line.Value, remaining) { + return true + } + after, matches := strings.CutPrefix(remaining, line.Value) + if !matches { + break + } + remaining = strings.TrimPrefix(after, " ") + } } - return strings.Contains(strings.Join(lines, " "), value) + return false } // until pumps the window until cond holds, within a bounded time. It wakes the window each diff --git a/desktop/internal/settingswindow/plugin_install.go b/desktop/internal/settingswindow/plugin_install.go index fe67582225..9d6e6f7b98 100644 --- a/desktop/internal/settingswindow/plugin_install.go +++ b/desktop/internal/settingswindow/plugin_install.go @@ -312,6 +312,8 @@ func RuntimeProgressText(language i18n.Language, progress pluginruntime.Progress return i18n.SharedFormat(language, "desktop.marketplace.runtimeReceived", map[string]string{"dependency": progress.ID, "received": fmt.Sprintf("%.1f", float64(progress.Received)/(1<<20))}) } return i18n.SharedFormat(language, "desktop.marketplace.runtimeDownloading", map[string]string{"dependency": progress.ID, "received": fmt.Sprintf("%.1f", float64(progress.Received)/(1<<20)), "total": fmt.Sprintf("%.1f", float64(progress.Total)/(1<<20))}) + case "uploading": + return i18n.SharedFormat(language, "desktop.marketplace.runtimeUploading", map[string]string{"dependency": progress.ID, "sent": fmt.Sprintf("%.1f", float64(progress.Received)/(1<<20)), "total": fmt.Sprintf("%.1f", float64(progress.Total)/(1<<20))}) case "extracting": return i18n.SharedFormat(language, "desktop.marketplace.runtimeExtracting", map[string]string{"dependency": progress.ID}) case "verifying": diff --git a/desktop/internal/settingswindow/plugin_settings_view.go b/desktop/internal/settingswindow/plugin_settings_view.go index b8fe544f15..092c37bc66 100644 --- a/desktop/internal/settingswindow/plugin_settings_view.go +++ b/desktop/internal/settingswindow/plugin_settings_view.go @@ -164,6 +164,10 @@ func (w *window) pluginSettingsPanel(c ui.C, id string, ruled bool) { if source == "" { ui.Wrap(c, i18n.Shared(language, "desktop.pluginSettings.openProject")).FontSize(12).Color(w.pal.muted) } else { + if remote := p.editor.Snapshot.ProjectConnectionName(); p.scope == 1 && remote != "" { + label := i18n.SharedFormat(language, "desktop.pluginSettings.remoteConnection", map[string]string{"name": remote}) + ui.Wrap(c, label).FontSize(11).Color(w.pal.muted) + } ui.Wrap(c, source).FontSize(11).Color(w.pal.muted) } w.pluginSettingActions(c) diff --git a/desktop/internal/settingswindow/source_settings_entries.go b/desktop/internal/settingswindow/source_settings_entries.go index 850f4d0200..6e7e1b9784 100644 --- a/desktop/internal/settingswindow/source_settings_entries.go +++ b/desktop/internal/settingswindow/source_settings_entries.go @@ -44,6 +44,7 @@ type sourceNavItem struct { // sourceEntryChooser is the dialog that adds entries of a choice kind. type sourceEntryChooser struct { + path string open bool source, field string kind int diff --git a/desktop/internal/settingswindow/source_settings_entries_view.go b/desktop/internal/settingswindow/source_settings_entries_view.go index ab480fbae9..103ae0f432 100644 --- a/desktop/internal/settingswindow/source_settings_entries_view.go +++ b/desktop/internal/settingswindow/source_settings_entries_view.go @@ -177,7 +177,7 @@ func (w *window) sourceEntryRow(c ui.C, p *sourceSettingsForm, source core.Setti func (w *window) addSourceEntries(c ui.C, p *sourceSettingsForm, source core.SettingsSource, field core.SourceSettingField, kindIndex int) { kind := field.EntryKinds[kindIndex] control := p.controls[source.ID][field.ID] - if kind.Input == "choice" { + if kind.Input == "choice" || p.editor.IsRemote() { p.chooser = sourceEntryChooser{open: true, source: source.ID, field: field.ID, kind: kindIndex, picked: make([]bool, len(kind.Choices))} return } @@ -244,6 +244,10 @@ func (w *window) sourceEntryChooser(c ui.C, p *sourceSettingsForm) { } control := p.controls[source.ID][field.ID] kind := field.EntryKinds[chooser.kind] + if kind.Input != "choice" { + w.remoteSourceEntry(c, p, source, field, kind) + return + } available := choiceEntries(field, chooser.kind, control.input.Entries) title := i18n.SharedFormat(language, "desktop.sourceSettings.chooseTitle", map[string]string{"title": kind.Title}) ui.ModalWith(c, &chooser.open, title, ui.ModalSpec{Width: 480, Height: 440}, func() { @@ -278,3 +282,23 @@ func (w *window) sourceEntryChooser(c ui.C, p *sourceSettingsForm) { } }) } + +// Remote paths retain their Linux spelling and are interpreted by the remote helper. +func (w *window) remoteSourceEntry(c ui.C, p *sourceSettingsForm, source core.SettingsSource, field core.SourceSettingField, kind core.SourceEntryKind) { + chooser := &p.chooser + language := w.marketLanguage() + label := i18n.Shared(language, "desktop.sourceSettings.remotePath") + ui.ModalWith(c, &chooser.open, kind.Title, ui.ModalSpec{Width: 480}, func() { + ui.Wrap(c, p.remoteLabel(language)).FontSize(12).Color(w.pal.muted) + ui.TextField(c, &chooser.path, label, label).FillWidth() + }, func() { + if ui.Button(c, i18n.Shared(language, "desktop.sourceSettings.cancel")).Outline().Clicked() { + chooser.open = false + } + if ui.Button(c, i18n.Shared(language, "desktop.sourceSettings.entryAdd")).Disabled(!strings.HasPrefix(chooser.path, "/")).Clicked() { + control := p.controls[source.ID][field.ID] + p.addEntries(source.ID, field, pathEntries(control.input.Entries, kind.ID, []string{chooser.path})) + chooser.open = false + } + }) +} diff --git a/desktop/internal/settingswindow/source_settings_view.go b/desktop/internal/settingswindow/source_settings_view.go index 396e4c0566..224c2eec83 100644 --- a/desktop/internal/settingswindow/source_settings_view.go +++ b/desktop/internal/settingswindow/source_settings_view.go @@ -51,6 +51,9 @@ type sourceSettingsForm struct { effect *ui.EffectState[pluginsettings.SourceEditor, int] key int jobEdits []core.SourceSettingsEdits + confirmEdits []core.SourceSettingsEdits + confirmSave bool + confirmList ui.ListState jobEditor pluginsettings.SourceEditor reload bool busy, stale, saved bool @@ -94,6 +97,7 @@ func (p *sourceSettingsForm) apply(editor pluginsettings.SourceEditor) { p.pending = make(map[string]map[string]core.SourceSettingInput) p.tableSources = make(map[string]bool) p.chooser.open = false + p.confirmSave, p.confirmEdits = false, nil for _, section := range editor.State.Layout { if editor.State.Snapshot.Groups[section.Group].Layout == "table" { for _, index := range section.Sources { @@ -252,7 +256,11 @@ func (p *sourceSettingsForm) start(reload bool) { if p.busy { return } - p.jobEditor, p.jobEdits = p.editor, p.edits() + edits := p.edits() + if !reload && p.confirmSave { + edits = p.confirmEdits + } + p.jobEditor, p.jobEdits = p.editor, edits p.reload, p.busy, p.saved, p.failed = reload, true, false, nil p.key++ } @@ -282,18 +290,31 @@ func (w *window) sourceSettingsPanel(c ui.C, p *sourceSettingsForm) { p.start(true) } if ui.Button(c, i18n.Shared(language, "desktop.pluginSettings.save")).Disabled(p.busy || p.stale || len(p.pending) == 0).Clicked() { - p.start(false) + if p.editor.IsRemote() { + p.confirmEdits = p.edits() + p.confirmSave = true + } else { + p.start(false) + } } if ui.Button(c, i18n.Shared(language, "desktop.sourceSettings.close")).Outline().Disabled(p.busy).Clicked() { w.pluginSettings.sources = nil } }) + if p.editor.IsRemote() { + ui.Wrap(c, p.remoteLabel(language)).FontSize(11).Color(w.pal.muted) + } if p.busy { ui.Text(c, i18n.Shared(language, "native.loading")).FontSize(12).Color(w.pal.muted) } if p.failed != nil { message := i18n.Shared(language, "desktop.pluginSettings.failed") - if p.stale { + switch { + case p.editor.IsRemote() && errors.Is(p.failed, pluginsettings.ErrSourcesCommitted): + message = i18n.Shared(language, "desktop.sourceSettings.remoteSaveUnverified") + case p.editor.IsRemote() && p.stale: + message = i18n.Shared(language, "desktop.sourceSettings.remoteSourceChanged") + case p.stale: message = i18n.Shared(language, "desktop.pluginSettings.sourceChanged") } ui.Wrap(c, message).FontSize(12).Color(w.pal.danger) @@ -321,6 +342,7 @@ func (w *window) sourceSettingsPanel(c ui.C, p *sourceSettingsForm) { }) }) w.sourceEntryChooser(c, p) + w.confirmRemoteSourceSave(c.Part("confirm-remote-source-save"), p) // A click that selected a module or tab or changed an entry list changed the // rows being declared; lay them out again before the next paint. if p.layoutDirty { @@ -332,6 +354,47 @@ func (w *window) sourceSettingsPanel(c ui.C, p *sourceSettingsForm) { } } +func (p *sourceSettingsForm) remoteLabel(language i18n.Language) string { + return i18n.SharedFormat(language, "desktop.pluginSettings.remoteConnection", map[string]string{"name": p.owner.Snapshot.ProjectConnectionName()}) +} + +func (w *window) confirmRemoteSourceSave(c ui.C, p *sourceSettingsForm) { + if !p.confirmSave { + return + } + language := w.marketLanguage() + title := i18n.Shared(language, "desktop.sourceSettings.confirmRemoteSave") + edited := make(map[string]bool, len(p.confirmEdits)) + for _, change := range p.confirmEdits { + edited[change.SourceID] = true + } + var paths []string + for _, source := range p.editor.State.Snapshot.Sources { + if edited[source.ID] { + paths = append(paths, p.editor.DisplayPath(source)) + } + } + ui.ModalWith(c, &p.confirmSave, title, ui.ModalSpec{Width: 540}, func() { + ui.Wrap(c, p.remoteLabel(language)).FontSize(12).Color(w.pal.text) + ui.List(c, &p.confirmList, len(paths), func(row ui.ListRow) { + row.Element.FillWidth().Children(func() { + ui.Wrap(row.C, paths[row.Index]).FontSize(12).Color(w.pal.text) + }) + }).Scrollbars().FillWidth().Height(144).Label(title) + }, func() { + if ui.Button(c, i18n.Shared(language, "desktop.sourceSettings.cancel")).Outline().Clicked() { + p.confirmSave = false + } + if ui.Button(c, i18n.Shared(language, "desktop.pluginSettings.save")).Disabled(p.busy || p.stale).Clicked() { + p.start(false) + p.confirmSave = false + } + }) + if !p.confirmSave { + p.confirmEdits = nil + } +} + // sourceNavWidth is the width of the module list beside a sidebar form. const sourceNavWidth = 168 @@ -386,7 +449,7 @@ func (w *window) sourceSettingsRow(c ui.C, p *sourceSettingsForm, item sourceSet ui.Row(c).FillWidth().Items(ui.Center).Gap(8).PadY(6).Children(func() { ui.Text(c, source.Title).FontSize(15).Weight(gfx.WeightSemibold).Color(w.pal.text).Shrink(0) ui.Spacer(c) - ui.Text(c, source.Path).FontSize(11).Color(w.pal.muted).Shrink(1).MinWidth(0).Ellipsis() + ui.Text(c, p.editor.DisplayPath(source)).FontSize(11).Color(w.pal.muted).Shrink(1).MinWidth(0).Ellipsis() }) return case sourceRowTabs: @@ -406,7 +469,7 @@ func (w *window) sourceSettingsRow(c ui.C, p *sourceSettingsForm, item sourceSet if item.kind == sourceRowTable { ui.Row(c).FillWidth().MinHeight(36).Items(ui.Center).Gap(8).Children(func() { ui.Text(c, source.Title).FontSize(12).Color(w.pal.text).Grow(1).Ellipsis() - w.infoButton(c, source.Path) + w.infoButton(c, p.editor.DisplayPath(source)) for _, field := range source.Fields { w.sourceSettingsControl(c.Key(field.ID), p, source, field) } @@ -439,7 +502,7 @@ func (w *window) sourceSettingsRow(c ui.C, p *sourceSettingsForm, item sourceSet if field.Kind == "entryList" && field.EffectiveSource != "" { ui.Text(c, field.EffectiveSource).FontSize(11).Color(w.pal.muted).Shrink(1).MinWidth(0).Ellipsis() } else if item.field == 0 && group.Layout != "sidebar" { - ui.Text(c, source.Path).FontSize(11).Color(w.pal.muted).Ellipsis() + ui.Text(c, p.editor.DisplayPath(source)).FontSize(11).Color(w.pal.muted).Ellipsis() } }) if field.Kind == "entryList" { @@ -559,7 +622,7 @@ func (w *window) sourceSettingsControl(c ui.C, p *sourceSettingsForm, source cor p.changed(source.ID, field.ID) } } - if field.Kind == "fileList" && source.Writable && ui.Button(c, i18n.Shared(language, "desktop.pluginSettings.browse")).Outline().Disabled(disabled).Clicked() { + if field.Kind == "fileList" && !p.editor.IsRemote() && source.Writable && ui.Button(c, i18n.Shared(language, "desktop.pluginSettings.browse")).Outline().Disabled(disabled).Clicked() { c.After(func() { paths, err := app.OpenFiles(app.OpenFileOptions{Title: field.Title}) // log-exempt: 用户取消:文件选择器取消不修改依赖草稿。 diff --git a/desktop/internal/settingswindow/source_settings_view_test.go b/desktop/internal/settingswindow/source_settings_view_test.go index d31b0c9b42..807b755b5e 100644 --- a/desktop/internal/settingswindow/source_settings_view_test.go +++ b/desktop/internal/settingswindow/source_settings_view_test.go @@ -6,6 +6,7 @@ import ( "encoding/json" "fmt" "os" + "path" "path/filepath" "sync/atomic" "testing" @@ -167,6 +168,85 @@ func TestNativeSettingsFormKeepsInheritanceAndSavesOnlyAnExplicitModuleEdit(t *t } } +type nativeFormSSHHost struct { + *core.Client + sources []core.SettingsSource +} + +func (h nativeFormSSHHost) InspectRemoteNativeSettings(_ context.Context, targets []core.RemoteNativeSettingsTarget) ([]core.RemoteNativeSettingsBaseline, error) { + baselines := make([]core.RemoteNativeSettingsBaseline, len(targets)) + for i, source := range h.sources { + root := "/work/project" + if source.Scope == "home" { + root = "/home/fixture" + } + baselines[i] = core.RemoteNativeSettingsBaseline{ + Target: targets[i], Identity: source.ID, Revision: source.Revision, + HostPath: path.Join(root, source.Path), Writable: source.Writable, + } + } + return baselines, nil +} + +func TestRemoteNativeSettingsSaveRequiresConfirmation(t *testing.T) { + source := nativeFormSource(t) + state := source.native.State + for i := range state.Snapshot.Sources { + row := &state.Snapshot.Sources[i] + row.Scope = "workspace" + if row.ID == "child" { + row.Scope = "home" + } + } + binding := core.NewRemoteWorkspace(source.workspace, "/work/project", nil) + binding.Attach("ssh-fixture") + t.Cleanup(func() { binding.Detach() }) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + var err error + source.native, err = pluginsettings.CaptureRemoteSources(ctx, nativeFormSSHHost{ + Client: core.NewClient(), sources: state.Snapshot.Sources, + }, binding.CaptureConnection(), state) + if err != nil { + t.Fatal(err) + } + w := nativeFormWindow(t, source, i18n.English, "dark") + d := openWindow(t, w, func(config *app.Config) { config.Height = 1100 }) + openNativeForm(t, w, d) + d.click("Child module Target") + d.click("Version 1") + d.pump() + save := i18n.Shared(i18n.English, "desktop.pluginSettings.save") + p := w.pluginSettings.sources + d.click(save) + d.until("remote save confirmation", func() bool { return p.confirmSave }) + if p.busy || !d.wrapped("/home/fixture/child/tool.json") { + t.Fatal("Save should display the target on the SSH host before starting the worker") + } + d.click(i18n.Shared(i18n.English, "desktop.sourceSettings.cancel")) + d.pump() + select { + case <-source.saves: + t.Fatal("dismissing the confirmation saved the change") + default: + } + if p.confirmSave || p.busy || len(p.pending) != 1 { + t.Fatal("dismissing the confirmation did not preserve the draft") + } + d.click(save) + d.until("another remote save confirmation", func() bool { return p.confirmSave }) + d.click(save) + d.until("confirmed remote save", func() bool { return p.saved }) + select { + case edits := <-source.saves: + if len(edits) != 1 || edits[0].SourceID != "child" || edits[0].Values["target"].Choice != "one" { + t.Fatalf("remote edits: %+v", edits) + } + default: + t.Fatal("confirmation did not deliver the captured edit") + } +} + func TestNativeCompilerPageRequiresAnExplicitRead(t *testing.T) { source := nativeFormSource(t) w := nativeFormWindow(t, source, i18n.English, "dark") diff --git a/desktop/internal/termview/menu.go b/desktop/internal/termview/menu.go index cfc108559f..438f1a88b2 100644 --- a/desktop/internal/termview/menu.go +++ b/desktop/internal/termview/menu.go @@ -58,7 +58,7 @@ func (v *View) lineEditorNeedsFormFeed() bool { } // Ended reports that the shell ended and Restart can start a new one. -func (v *View) Ended() bool { return v.ended && !v.closed && v.cfg.Exited == nil } +func (v *View) Ended() bool { return v.ended && !v.closed && v.cfg.Exited == nil && !v.cfg.NoRestart } // Restart starts a new shell in a view whose shell ended, and reports whether it did. func (v *View) Restart() bool { return v.restart() } diff --git a/desktop/internal/termview/session.go b/desktop/internal/termview/session.go index 0f1315c4d8..5b4a8fa913 100644 --- a/desktop/internal/termview/session.go +++ b/desktop/internal/termview/session.go @@ -114,7 +114,9 @@ func (v *View) launched() { if l.err != nil { v.ended = true v.say(sgrFail, v.cfg.Messages.StartFailed(l.err.Error())) - v.say(sgrMuted, v.cfg.Messages.RestartHint) + if v.Ended() { + v.say(sgrMuted, v.cfg.Messages.RestartHint) + } v.failed(Failure{Event: eventStartFailed, Stage: stageSpawn, Warn: true, Err: l.err}) v.exited(nil) return @@ -258,7 +260,7 @@ func (v *View) shellEnded() { line = v.cfg.Messages.SessionEndedStatus(exit.ExitStatus()) } v.say(sgrMuted, line) - if v.cfg.Exited == nil { + if v.Ended() { v.say(sgrMuted, v.cfg.Messages.RestartHint) } var status *int @@ -401,7 +403,7 @@ func (v *View) tellShellSize(cols, rows int) { // whether it did. What the old session printed stays in the history above the new one, so // the user can still read why it ended. func (v *View) restart() bool { - if !v.ended || v.closed || v.cfg.Exited != nil { + if !v.Ended() { return false } // A blank line sets the new shell's prompt apart from the notes the old session ended diff --git a/desktop/internal/termview/view.go b/desktop/internal/termview/view.go index 2ebe3ee733..2397da6e71 100644 --- a/desktop/internal/termview/view.go +++ b/desktop/internal/termview/view.go @@ -165,6 +165,8 @@ type Config struct { // status when it has one. A view with Exited set does not restart on Enter: the // owner decides what happens next. Exited func(status *int) + // NoRestart keeps the terminal output after a command ends without offering to run it again. + NoRestart bool // Clipboard reads the system clipboard for a paste. Nil uses app.ClipboardText. Clipboard func() (string, error) // PasteImage is asked first when a paste into a live shell finds no text on the diff --git a/desktop/internal/toolchain/load.go b/desktop/internal/toolchain/load.go index c592c5fc2c..01122986ce 100644 --- a/desktop/internal/toolchain/load.go +++ b/desktop/internal/toolchain/load.go @@ -422,18 +422,23 @@ func resolve(ctx context.Context, kernel Kernel, root, directory, tool, minimumV return Selection{}, err } } - if resolution.Outcome.Kind != "resolved" || resolution.Outcome.Selection == nil { - code := "notFound" - if resolution.Outcome.Reason != nil && resolution.Outcome.Reason.Code != "" { - code = resolution.Outcome.Reason.Code - } - return Selection{}, &UnavailableError{Tool: tool, Code: code, Terminal: resolution.Outcome.Kind == "terminalFailure"} - } - return *resolution.Outcome.Selection, nil + return SelectionFromResolution(tool, resolution) } return Selection{}, &UnavailableError{Tool: tool, Code: "definitionUnavailable"} } +// SelectionFromResolution translates Core's outcome for build and run consumers. +func SelectionFromResolution(tool string, resolution core.ToolchainResolution) (Selection, error) { + if resolution.Outcome.Kind == "resolved" && resolution.Outcome.Selection != nil { + return *resolution.Outcome.Selection, nil + } + code := "notFound" + if resolution.Outcome.Reason != nil && resolution.Outcome.Reason.Code != "" { + code = resolution.Outcome.Reason.Code + } + return Selection{}, &UnavailableError{Tool: tool, Code: code, Terminal: resolution.Outcome.Kind == "terminalFailure"} +} + type preparedTool struct { providerRound *providerRound queries []core.ToolchainQuery diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 7dee97853c..415b1e087c 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -69,6 +69,7 @@ type Kernel interface { DetectBuildSystems(ctx context.Context, workspaceRoot string, manifests []json.RawMessage) (core.BuildDetection, error) LocalizeBuildOptions(ctx context.Context, language string, plugins []core.BuildOptionPlugin) (core.BuildOptionTexts, error) DetectBuildSystemsWithOptions(ctx context.Context, workspaceRoot string, manifests []json.RawMessage, options core.BuildDetectOptions) (core.BuildDetection, error) + ReadWorkspaceConfiguration(context.Context, string, int64) (*string, error) ResolveStoredBuildOptions(ctx context.Context, document, local json.RawMessage) (core.BuildStoredOptions, error) ResolveBuildOptions(ctx context.Context, manifest json.RawMessage, buildSystemID string, request core.BuildResolveOptionsRequest) (core.BuildResolvedOptions, error) EditStoredBuildOption(ctx context.Context, manifest json.RawMessage, buildSystemID string, request core.BuildOptionEditRequest) (core.BuildOptionEdit, error) @@ -168,6 +169,8 @@ type Kernel interface { ToolchainDiscoveryPlanOf(ctx context.Context, registry json.RawMessage, platform string) (core.ToolchainDiscoveryPlan, error) ToolchainCandidatesOf(ctx context.Context, request core.ToolchainCandidatesRequest) (core.ToolchainCandidates, error) ResolveToolchain(ctx context.Context, request core.ToolchainResolveRequest) (core.ToolchainResolution, error) + ResolveRemoteToolchain(ctx context.Context, request core.RemoteToolchainResolveRequest) (core.ToolchainResolution, error) + CheckToolchainVersion(ctx context.Context, registry json.RawMessage, tool, output, minimumVersion string) (core.ToolchainVersion, error) ResolveToolchainPins(ctx context.Context, document json.RawMessage, directory, tool string) (core.ToolchainPinResolution, error) EditToolchainPins(ctx context.Context, document json.RawMessage, directory string, edits []core.ToolchainPinEdit) (json.RawMessage, error) ToolchainPinStorage(ctx context.Context) (core.ToolchainPinStoragePlan, error) @@ -239,6 +242,15 @@ type Kernel interface { RemoteWorkspaceTrust(ctx context.Context, document *string, sessionID, workspace string) (core.RemoteWorkspaceTrustState, error) EditRemoteWorkspaceTrust(ctx context.Context, document *string, decision core.RemoteWorkspaceTrustDecision) (core.RemoteWorkspaceTrustPublication, error) RevokeRemoteWorkspaceTrust(ctx context.Context, document *string, revoke core.RemoteWorkspaceTrustRevoke) (core.RemoteWorkspaceTrustPublication, error) + ResolveRemoteExecutable(context.Context, core.RemoteExecutableRequest) (string, error) + PickRemoteLoopbackPort(context.Context) (int, error) + RemoteProcessDebugPortReady(context.Context, uint64, int) (bool, error) + RunRemoteProcess(context.Context, core.RemoteProcessOpen, core.RemoteProcessEvents) (core.RemoteProcessExit, error) + WriteRemoteProcessInput(context.Context, uint64, []byte) error + CreateRemoteRunDirectory(context.Context, string) (string, error) + WriteRemoteRunFile(context.Context, string, []byte) error + ApplyRemoteRunConfigurationChanges(context.Context, string, []core.RunConfigChange) (bool, error) + ReleaseRemoteRunDirectory(context.Context, string) error RemoteRunTerminal(ctx context.Context, sessionID string, open core.RemoteTerminalOpen, events core.RemoteTerminalEvents) (core.RemoteTerminalExit, error) RemoteRunWatch(ctx context.Context, sessionID, root string, excludeNames []string, events core.RemoteWatchEvents) error RemoteTerminalWrite(ctx context.Context, sessionID string, terminalID uint64, data []byte) (bool, error) @@ -848,6 +860,8 @@ type App struct { // toolchainRoot is the open project's root, read by the settings window from // its own thread. Nil means no project is open. toolchainRoot atomic.Pointer[string] + // Remote Settings reads the captured host, even while its session is disconnected. + settingsRemote atomic.Pointer[remoteSettingsWorkspace] // toolchainResolve is the execution-side selector; tests replace it to keep // workspace file reads out of the window. Production leaves it nil. toolchainResolve func(ctx context.Context, root, directory, tool, minimumVersion string) (core.ToolchainSelection, error) @@ -1114,6 +1128,9 @@ func (a *App) openPlugins(options Options) { a.backgroundFailedIn(ctx, "toolchain_provider_discovery", err) } + service.WorkspaceWatchIssue = func(ctx context.Context, err error) { + a.backgroundFailedIn(ctx, "plugin_workspace_watch", remoteLogError(err)) + } service.BuildConfigurationIssue = func(ctx context.Context, err error) { a.backgroundFailedIn(ctx, "plugin_build_configuration_watch", documentLogError(err)) } @@ -1851,6 +1868,7 @@ func (a *App) disposeProject(p *project) { a.clearAllPluginDiagnostics() a.problems.reset() a.toolchainRoot.Store(nil) + a.settingsRemote.Store(nil) a.project = nil a.chrome.setRemote(false) a.ideAPISetProject(nil) diff --git a/desktop/internal/workbench/build.go b/desktop/internal/workbench/build.go index eba426a3d0..5fb56163d1 100644 --- a/desktop/internal/workbench/build.go +++ b/desktop/internal/workbench/build.go @@ -18,6 +18,7 @@ import ( "sync" "time" + "github.com/1lck/Lithe-IDEA/desktop/internal/buildprefs" "github.com/1lck/Lithe-IDEA/desktop/internal/buildprocess" "github.com/1lck/Lithe-IDEA/desktop/internal/buildprovider" "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" @@ -158,6 +159,8 @@ type buildOperation struct { // debugging, nil for a plain run; debugSession is the session attached to it, once it is. debug *connectionDebug debugSession *debugSession + // Configured runs keep the same attachment through saves, steps and launch. + connection *core.RemoteWorkspaceConnection } // beginBuildOperation makes a new operation the window's current one and gives it the IDE @@ -251,13 +254,8 @@ func (b *buildState) active() bool { return b.operation != nil || len(b.running) // runs; otherwise it stops the one that runs and starts the new one once it ended, so the two // never share a port or files. A start that is asked again while one waits replaces it. // -// In safe mode the user is first asked to trust the project, since a run runs its code. A -// remote workspace runs only its run configurations, on its host (startRunConfigurationWith -// checks which); its build systems' tasks and entry points are not run there yet. +// In safe mode the user is first asked to trust the project, since a run runs its code. func (a *App) startRun(p *project, key string, start func(*App, *project)) { - if !strings.HasPrefix(key, configurationRunKey("")) && a.refuseRemote(p, "run_start") { - return - } if p.safeMode() { a.askToTrustProject(p, func() { a.startRun(p, key, start) }) return @@ -406,32 +404,39 @@ type buildRuntime struct { type buildProviderLaunchKey struct { settings string + connection *core.RemoteWorkspaceConnection usesToolchain bool toolchain toolchain.SourceRevision } func (key buildProviderLaunchKey) equal(other buildProviderLaunchKey) bool { - return key.settings == other.settings && key.usesToolchain == other.usesToolchain && key.toolchain.Equal(other.toolchain) + return key.sameWorkspace(other) && key.usesToolchain == other.usesToolchain && key.toolchain.Equal(other.toolchain) +} + +func (key buildProviderLaunchKey) sameWorkspace(other buildProviderLaunchKey) bool { + return key.settings == other.settings && + ((key.connection == nil && other.connection == nil) || key.connection.SameAttachment(other.connection)) } var errBuildProviderSourceChanged = errors.New("build provider source changed during launch") // standaloneBuildProvider starts a process outside the session lock. Only a // start from the current project and saved toolchain sources can be published. -func (a *App) standaloneBuildProvider(ctx context.Context, p *project, instance buildInstance, rootURI string, settings core.PluginSettingsState, settingsKey string, detached uint64) (*buildprovider.Client, error) { +func (a *App) standaloneBuildProvider(ctx context.Context, p *project, instance buildInstance, rootURI string, settings core.PluginSettingsState, launchKey buildProviderLaunchKey, target core.RemotePlatform, detached uint64) (*buildprovider.Client, error) { r := &p.buildSessions + connection := launchKey.connection key := instance.PluginID + "\x00" + instance.BuildSystemID r.mu.Lock() if err := ctx.Err(); err != nil { r.mu.Unlock() return nil, err } - if r.closed || r.detached != detached { + if r.closed || r.detached != detached || (connection != nil && !connection.IsCurrent()) { r.mu.Unlock() return nil, buildprovider.ErrClosed } client := r.providers[key] - if cached := r.launchKeys[key]; client != nil && !client.Closed() && cached.settings == settingsKey { + if cached := r.launchKeys[key]; client != nil && !client.Closed() && cached.sameWorkspace(launchKey) { if !cached.usesToolchain { r.mu.Unlock() return client, nil @@ -471,43 +476,59 @@ func (a *App) standaloneBuildProvider(ctx context.Context, p *project, instance a.retireBuildProvider(ctx, client) } - state := buildStateDirectory(a.plugins.Root, p.root, instance) - workspaceState := filepath.Join(state, "workspace") - temporaryDirectory := filepath.Join(state, "tmp") - for _, directory := range []string{workspaceState, temporaryDirectory} { - if err := os.MkdirAll(directory, 0o700); err != nil { - return nil, err + prepareLocal := func(ctx context.Context, request *pluginbackend.StartRequest) error { + request.StateDirectory = buildStateDirectory(a.plugins.Root, p.root, instance) + request.WorkspaceStateDirectory = filepath.Join(request.StateDirectory, "workspace") + request.TemporaryDirectory = filepath.Join(request.StateDirectory, "tmp") + for _, directory := range []string{request.WorkspaceStateDirectory, request.TemporaryDirectory} { + if err := os.MkdirAll(directory, 0o700); err != nil { + return err + } + } + request.LogDirectory = a.pluginLogDirectory(ctx, instance.PluginID) + if connection == nil { + request.BeforeResolveTool = func(ctx context.Context) error { + revision, err := a.buildToolchainSource(ctx, p) + if err != nil { + return err + } + launchKey.toolchain, launchKey.usesToolchain = revision, true + return nil + } } + return nil } - launchKey := buildProviderLaunchKey{settings: settingsKey} - started, startErr := buildprovider.Launch(ctx, a.plugins.Backend, pluginbackend.StartRequest{ - Manifest: instance.Manifest, - PackageDirectory: instance.PackageDirectory, - PluginID: instance.PluginID, - ProviderID: instance.PluginID + "/" + instance.BuildSystemID, - BuildSystemID: instance.BuildSystemID, - Role: "build", - StateDirectory: state, - WorkspaceStateDirectory: workspaceState, - LogDirectory: a.pluginLogDirectory(ctx, instance.PluginID), - TemporaryDirectory: temporaryDirectory, - Architecture: core.PluginArchitecture(), - Settings: settings.Settings, - ProjectSettings: settings.ProjectSettings, - RootURI: rootURI, - WorkingDirectory: p.root, + start := pluginbackend.StartRequest{ + Manifest: instance.Manifest, + PackageDirectory: instance.PackageDirectory, + PluginID: instance.PluginID, + ProviderID: instance.PluginID + "/" + instance.BuildSystemID, + BuildSystemID: instance.BuildSystemID, + Role: "build", + Architecture: core.PluginArchitecture(), + RemoteConnection: connection, + Settings: settings.Settings, + ProjectSettings: settings.ProjectSettings, + RootURI: rootURI, + WorkingDirectory: p.root, // Core plans no provider process that runs project code in safe mode; the requests // that would reach it already ask to trust the project first. ProjectCodeAllowed: p.trust.allowed(), - BeforeResolveTool: func(ctx context.Context) error { - revision, err := a.buildToolchainSource(ctx, p) - if err != nil { - return err - } - launchKey.toolchain, launchKey.usesToolchain = revision, true - return nil - }, - }) + } + if connection == nil { + if err := prepareLocal(ctx, &start); err != nil { + return nil, err + } + } else { + start.Architecture = target.Arch + start.PrepareUI = prepareLocal + installed := pluginpkg.Installed{ID: instance.PluginID, Version: instance.Version, Path: instance.PackageDirectory} + start.PrepareRemote = a.plugins.RemoteDeployment(installed, instance.Manifest, target, nil) + start.PrepareRemoteTools = func(ctx context.Context) (map[string]pluginbackend.ToolExecutable, error) { + return a.plugins.RemoteTools(ctx, installed, instance.Manifest, connection, target) + } + } + started, startErr := buildprovider.Launch(ctx, a.plugins.Backend, start) var shared *pluginbackend.SharedProviderError if errors.As(startErr, &shared) { return nil, startErr @@ -521,7 +542,7 @@ func (a *App) standaloneBuildProvider(ctx context.Context, p *project, instance latest, revisionErr = a.buildToolchainSource(ctx, p) } r.mu.Lock() - open := !r.closed && r.detached == detached && ctx.Err() == nil + open := !r.closed && r.detached == detached && ctx.Err() == nil && (connection == nil || connection.IsCurrent()) current := open && revisionErr == nil && launchKey.toolchain.Equal(latest) client = r.providers[key] if current && startErr == nil && client == nil { @@ -621,6 +642,13 @@ func buildStateDirectory(pluginRoot, workspace string, instance buildInstance) s // buildProvider starts a provider process, or attaches to the language server // that shares it. The caller runs this away from the window thread. func (a *App) buildProvider(ctx context.Context, p *project, instance buildInstance) (client *buildprovider.Client, err error) { + var connection *core.RemoteWorkspaceConnection + if p.remote != nil { + connection = p.remote.binding.CapturedConnection(ctx) + if !connection.IsCurrent() { + return nil, &core.Error{Code: core.CodeConnectionClosed, Message: "The workspace connection changed."} + } + } ctx, finish, err := a.buildProviderLaunches.begin(ctx, instance.PluginID) if err != nil { return nil, err @@ -639,7 +667,7 @@ func (a *App) buildProvider(ctx context.Context, p *project, instance buildInsta p.buildSessions.mu.Unlock() const maxSourceAttempts = 3 for range maxSourceAttempts { - client, err = a.buildProviderWithSources(ctx, p, instance, detached) + client, err = a.buildProviderWithSources(ctx, p, instance, connection, detached) // log-exempt: 预期的缺失:读取或启动期间工具链来源已更新,在原请求期限内重试。 if err == errBuildProviderSourceChanged { continue @@ -657,12 +685,20 @@ func (a *App) buildToolchainSource(ctx context.Context, p *project) (toolchain.S return revision, err } -func (a *App) buildProviderWithSources(ctx context.Context, p *project, instance buildInstance, detached uint64) (*buildprovider.Client, error) { - settings, err := a.loadPluginPreferenceSources(ctx, instance.Manifest, p.root) +func (a *App) buildProviderWithSources(ctx context.Context, p *project, instance buildInstance, connection *core.RemoteWorkspaceConnection, detached uint64) (*buildprovider.Client, error) { + var target core.RemotePlatform + if connection != nil { + workspace, ok := a.plugins.Contexts.ByPath(p.root) + if !ok || !connection.IsCurrent() { + return nil, pluginservice.ErrContextExpired + } + target = workspace.HostPlatform() + } + state, err := a.loadPluginPreferenceSources(ctx, instance.Manifest, p.root) if err != nil { return nil, err } - settingsKey, err := buildSettingsKey(settings.State) + settingsKey, err := buildSettingsKey(state) if err != nil { return nil, err } @@ -670,21 +706,28 @@ func (a *App) buildProviderWithSources(ctx context.Context, p *project, instance if err != nil { return nil, err } - client, err := a.standaloneBuildProvider(ctx, p, instance, rootURI, settings.State, settingsKey, detached) + launchKey := buildProviderLaunchKey{settings: settingsKey, connection: connection} + client, err := a.standaloneBuildProvider(ctx, p, instance, rootURI, state, launchKey, target, detached) var shared *pluginbackend.SharedProviderError if !errors.As(err, &shared) { return client, err } - return a.sharedBuildProvider(ctx, p, instance, shared.LanguageID) + return a.sharedBuildProvider(ctx, p, instance, shared.LanguageID, connection, detached) } // sharedBuildProvider attaches a build client to the language server of the // same plugin. If no server runs yet, it starts one and publishes it as the // window's language server so both build and editor requests reuse it. -func (a *App) sharedBuildProvider(ctx context.Context, p *project, instance buildInstance, languageID string) (*buildprovider.Client, error) { +func (a *App) sharedBuildProvider(ctx context.Context, p *project, instance buildInstance, languageID string, connection *core.RemoteWorkspaceConnection, detached uint64) (*buildprovider.Client, error) { key := instance.PluginID + "\x00" + languageID + if connection != nil { + key += "\x00" + strconv.FormatUint(connection.Revision(), 10) + } p.buildSessions.mu.Lock() - detached := p.buildSessions.detached + if p.buildSessions.closed || p.buildSessions.detached != detached || (connection != nil && !connection.IsCurrent()) { + p.buildSessions.mu.Unlock() + return nil, buildprovider.ErrClosed + } if client := p.buildSessions.shared[key]; client != nil && !client.Closed() { p.buildSessions.mu.Unlock() return client, nil @@ -692,9 +735,9 @@ func (a *App) sharedBuildProvider(ctx context.Context, p *project, instance buil p.buildSessions.mu.Unlock() a.pluginServerMu.Lock() - if server := a.pluginServers[instance.PluginID]; server != nil && server.project == p { + if server := a.pluginServers[instance.PluginID]; server != nil && server.project == p && server.session.ServesAttachment(connection) { a.pluginServerMu.Unlock() - return a.attachSharedBuildClient(ctx, p, instance, key, server, detached) + return a.attachSharedBuildClient(ctx, p, key, server, connection, detached) } a.pluginServerMu.Unlock() @@ -706,11 +749,13 @@ func (a *App) sharedBuildProvider(ctx context.Context, p *project, instance buil if err != nil { return nil, err } + workspace, _ := a.plugins.Contexts.ByPath(p.root) session, err := a.plugins.StartLanguageServer(ctx, entries, languageID, pluginservice.BackendRequest{ RootURI: rootURI, WorkingDirectory: p.root, - Context: p.pluginContext, + Context: workspace.ContextRef, Architecture: core.PluginArchitecture(), + RemoteConnection: connection, ProjectCodeAllowed: p.trust.allowed(), }) if err != nil { @@ -727,7 +772,8 @@ func (a *App) sharedBuildProvider(ctx context.Context, p *project, instance buil server.cancel = serveCancel a.pluginServerMu.Lock() - if ctx.Err() != nil || p.ctx.Err() != nil || a.pluginServerSuppressed[instance.PluginID] { + if ctx.Err() != nil || p.ctx.Err() != nil || a.pluginServerSuppressed[instance.PluginID] || + (connection != nil && !connection.IsCurrent()) { a.pluginServerMu.Unlock() serveCancel() a.stopPluginSession(session) @@ -743,7 +789,10 @@ func (a *App) sharedBuildProvider(ctx context.Context, p *project, instance buil // Another start won; attach to it and dispose the extra session. serveCancel() a.stopPluginSession(session) - return a.attachSharedBuildClient(ctx, p, instance, key, existing, detached) + if existing.project != p || !existing.session.ServesAttachment(connection) { + return nil, buildprovider.ErrClosed + } + return a.attachSharedBuildClient(ctx, p, key, existing, connection, detached) } a.pluginServers[instance.PluginID] = server if a.pluginServerLanguages == nil { @@ -760,7 +809,7 @@ func (a *App) sharedBuildProvider(ctx context.Context, p *project, instance buil a.releasePluginDocuments(instance.PluginID) a.openDocumentsForPlugin(p, server, languageID) }) - return a.attachSharedBuildClient(ctx, p, instance, key, server, detached) + return a.attachSharedBuildClient(ctx, p, key, server, connection, detached) } // attachSharedBuildClient waits for the session's real ready event before it @@ -768,7 +817,10 @@ func (a *App) sharedBuildProvider(ctx context.Context, p *project, instance buil // so Attach can mark this client ready without inventing a ready state. detached // is the runtime's detach count when the caller began: a client attached after // another detach belongs to the sessions it took and is dropped. -func (a *App) attachSharedBuildClient(ctx context.Context, p *project, instance buildInstance, key string, server *pluginServer, detached uint64) (*buildprovider.Client, error) { +func (a *App) attachSharedBuildClient(ctx context.Context, p *project, key string, server *pluginServer, connection *core.RemoteWorkspaceConnection, detached uint64) (*buildprovider.Client, error) { + if !server.session.ServesAttachment(connection) { + return nil, buildprovider.ErrClosed + } client := server.attachBuild(a.plugins.Backend, server.session.Session) if err := client.WaitReady(ctx); err != nil { server.detachBuild(client) @@ -776,12 +828,19 @@ func (a *App) attachSharedBuildClient(ctx context.Context, p *project, instance return nil, err } p.buildSessions.mu.Lock() - if p.buildSessions.closed || p.buildSessions.detached != detached || ctx.Err() != nil || p.ctx.Err() != nil { + if p.buildSessions.closed || p.buildSessions.detached != detached || ctx.Err() != nil || p.ctx.Err() != nil || + (connection != nil && !connection.IsCurrent()) { p.buildSessions.mu.Unlock() server.detachBuild(client) _ = client.Close(context.Background()) return nil, buildprovider.ErrClosed } + if existing := p.buildSessions.shared[key]; existing != nil && !existing.Closed() { + p.buildSessions.mu.Unlock() + server.detachBuild(client) + _ = client.Close(context.Background()) + return existing, nil + } if p.buildSessions.shared == nil { p.buildSessions.shared = make(map[string]*buildprovider.Client) } @@ -795,13 +854,12 @@ func (a *App) loadBuildSystems(p *project) { if p == nil || p.build.loading { return } + var connection *core.RemoteWorkspaceConnection if p.remote != nil { - // log-exempt: 远程工作区的构建工具要在主机上运行,现在还不支持:本机的占位文件夹里没有项目,不探测构建系统; - // 运行配置菜单用 failed 说明这一点,内置的程序和脚本运行照常从 Core 读出、在主机上启动(remote_run.go)。 - p.build.loaded = true - p.build.failed = i18n.Shared(a.language(), "desktop.run.remote.buildTools") - a.refreshRunConfigurations(p) - return + connection = p.remote.binding.CaptureConnection() + if connection == nil { + return + } } if a.plugins == nil || a.plugins.Backend == nil { p.build.loaded = true @@ -815,21 +873,45 @@ func (a *App) loadBuildSystems(p *project) { p.build.generation++ generation := p.build.generation kernel := a.kernel - // The team and local option documents are read here, on the window thread, and resolved and detected - // with the instances below; a document that cannot be read fails the detection instead of emptying it. - docs, docsErr := a.readBuildOptionDocuments(a.operationContext(context.Background()), p.root) + // For a local project, capture the documents on the window thread before an option + // edit can change them. A remote team's document is read over the captured connection. + var docs buildOptionDocuments + var docsErr error + if connection == nil { + docs, docsErr = a.readBuildOptionDocuments(a.operationContext(context.Background()), p.root) + } language := a.language().Code() + finish := func(instances []buildInstance, err error) func(*App) { + return func(a *App) { + if connection != nil && !connection.IsCurrent() { + return + } + a.finishBuildDetection(p, generation, instances, err) + } + } a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { + local := core.WithoutRemoteWorkspace(ctx) entries, err := a.plugins.Manager.Installed() if err != nil { - return func(a *App) { a.finishBuildDetection(p, generation, nil, err) } + return finish(nil, err) } if docsErr != nil { - return func(a *App) { a.finishBuildDetection(p, generation, nil, docsErr) } + return finish(nil, docsErr) + } + plugins, pluginErr := a.plugins.BuildPlugins(local, entries) + if connection != nil { + if len(plugins) == 0 { + return finish(nil, pluginErr) + } + ctx = connection.Context(ctx) + remoteDocs, err := buildprefs.ReadRemote(ctx, a.store, p.root, kernel.ReadWorkspaceConfiguration) + if err != nil { + return finish(nil, errors.Join(pluginErr, err)) + } + docs = buildOptionDocuments{team: remoteDocs.Team, local: remoteDocs.Local} } - plugins, pluginErr := a.plugins.BuildPlugins(ctx, entries) // The manifests carry their option text in the interface language from here on. - manifests := a.localizeBuildManifests(ctx, kernel, language, plugins) + manifests := a.localizeBuildManifests(local, kernel, language, plugins) byPlugin := make(map[string]pluginservice.BuildPlugin, len(plugins)) for index, plugin := range plugins { plugin.Manifest = manifests[index] @@ -861,9 +943,7 @@ func (a *App) loadBuildSystems(p *project) { } instances = append(instances, instance) } - return func(a *App) { - a.finishBuildDetection(p, generation, instances, errors.Join(pluginErr, detectErr)) - } + return finish(instances, errors.Join(pluginErr, detectErr)) }) } @@ -928,6 +1008,10 @@ func (a *App) loadBuildModelWith(p *project, index int, refresh bool) { } return } + connection, ok := captureWorkspaceConnection(p) + if !ok { + return + } instance.modelLoading = true instance.modelError, instance.modelStopped = "", false captured := *instance @@ -936,7 +1020,7 @@ func (a *App) loadBuildModelWith(p *project, index int, refresh bool) { // The load is a session of the Run window, which shows what the tool prints meanwhile. feed := a.beginBuildSync(p, instance) a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { - ctx, cancel := feed.bind(ctx) + ctx, cancel := feed.bind(attachedWorkspaceContext(ctx, connection)) defer cancel() model, err := a.buildModel(ctx, p, captured, kernel, feed, a.text.Build, refresh) if err != nil && feed.stopRequested() { @@ -944,7 +1028,7 @@ func (a *App) loadBuildModelWith(p *project, index int, refresh bool) { } return func(a *App) { a.endBuildSync(feed.session, err) - if a.project != p || p.build.generation != generation { + if a.project != p || p.build.generation != generation || (connection != nil && !connection.IsCurrent()) { return } a.finishBuildModel(p, captured.ID, model, err) @@ -989,33 +1073,42 @@ func (a *App) commandModel(ctx context.Context, p *project, instance buildInstan a.plugins.EndAttempt(ctx, attempt, stage, err) return core.BuildModel{}, err } - state := buildStateDirectory(a.plugins.Root, p.root, instance) - if err := os.MkdirAll(state, 0o700); err != nil { + if p.remote != nil && p.remote.binding.CapturedConnection(ctx) == nil { + return fail(core.StagePlan, errRemoteSessionClosed) + } + scratch, err := a.prepareBuildScratch(ctx, p, instance, "model") + if err != nil { return fail(core.StagePlan, err) } - file, createErr := os.CreateTemp(state, "model-*.json") - if createErr != nil { - return fail(core.StagePlan, createErr) - } - outputFile := file.Name() - _ = file.Close() - _ = os.Remove(outputFile) - defer os.Remove(outputFile) - // The package directory expands ${pluginDir}, which a model command uses to load a - // plugin-shipped script or extension into the build tool. - // ${workspaceStateDir} is the same writable directory, outside the read-only package. - plan, err := kernel.PlanBuildModel(ctx, instance.Manifest, instance.BuildSystemID, core.BuildPlanRequest{ + defer scratch.release() + planRequest := core.BuildPlanRequest{ Root: instance.Root, Options: instance.Options, - PluginDirectory: instance.PackageDirectory, - WorkspaceStateDirectory: state, + PluginDirectory: scratch.packageDirectory, + WorkspaceStateDirectory: scratch.state, WorkspaceRoot: p.root, - OutputFile: outputFile, + OutputFile: scratch.output, ProjectCodeAllowed: p.trust.allowed(), - }) + } + plan, err := kernel.PlanBuildModel(ctx, instance.Manifest, instance.BuildSystemID, planRequest) if err != nil { return fail(core.StagePlan, err) } + if p.remote != nil && len(plan.RequiredPackagePaths) != 0 { + installed := pluginpkg.Installed{ID: instance.PluginID, Version: instance.Version, Path: instance.PackageDirectory} + deploy := a.plugins.RemoteDeployment(installed, instance.Manifest, p.remote.platform, nil) + planRequest.PluginDirectory, err = deploy(ctx, plan.RequiredPackagePaths) + if err != nil { + return fail(core.StagePlan, err) + } + plan, err = kernel.PlanBuildModel(ctx, instance.Manifest, instance.BuildSystemID, planRequest) + if err != nil { + return fail(core.StagePlan, err) + } + if len(plan.RequiredPackagePaths) != 0 { + return fail(core.StagePlan, errors.New("the model command still requires a deployed package")) + } + } if plan.Provider != nil { return fail(core.StagePlan, errors.New("the build system answered with a provider model")) } @@ -1030,11 +1123,11 @@ func (a *App) commandModel(ctx context.Context, p *project, instance buildInstan } workingDirectory := filepath.Join(p.root, filepath.FromSlash(plan.WorkingDirectory)) toFile := plan.Output == "outputFile" - output, runErr := captureBuildProcess(ctx, execution.Executable, plan.Arguments, workingDirectory, applyToolchainSelection(plan.Environment, execution.selection()), !toFile, feed.logger()) + output, runErr := a.captureWorkspaceBuildProcess(ctx, p, execution, plan.Arguments, workingDirectory, plan.Environment, !toFile, feed.logger()) runErr = withBuildOutput(runErr, output.combined) request := core.BuildDecodeModelRequest{WorkspaceRoot: p.root, Root: instance.Root, Options: instance.Options} if toFile { - request.OutputFile = outputFile + request.OutputFile = scratch.output } else { request.Output = output.stdout } @@ -1355,10 +1448,10 @@ func buildTaskSelection(instance *buildInstance, task *pluginservice.BuildTaskDe // so a tool call can report them, and the Build window keeps its notification and ignores them. func (a *App) runBuildTask(p *project, projectID, targetID, taskID string, userArguments []string) (*buildOperation, error) { // A task runs the build tool on the project: in safe mode the user is asked to trust it - // first, and the task starts once trusted. The caller, such as the IDE API, is refused. A - // remote workspace's build tool runs on its host, which a task does not reach yet. - if a.refuseRemote(p, "build_task") { - return nil, refuseBuild(refusalNotReady, "the workspace is remote") + // first, and the task starts once trusted. The caller, such as the IDE API, is refused. + connection, ok := captureWorkspaceConnection(p) + if !ok { + return nil, refuseBuild(refusalNotReady, "the workspace is disconnected") } if p.safeMode() { a.askToTrustProject(p, func() { _, _ = a.runBuildTask(p, projectID, targetID, taskID, userArguments) }) @@ -1421,6 +1514,7 @@ func (a *App) runBuildTask(p *project, projectID, targetID, taskID string, userA _, _ = a.runBuildTask(p, projectID, targetID, taskID, userArguments) })) a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { + ctx = attachedWorkspaceContext(ctx, connection) prepare, release := op.bind(ctx) defer release() plan, err := kernel.PlanBuildTask(prepare, captured.Manifest, captured.BuildSystemID, request) @@ -1452,13 +1546,7 @@ func (a *App) runCommandTask(ctx, prepare context.Context, p *project, op *build return err } workingDirectory := filepath.Join(p.root, filepath.FromSlash(plan.WorkingDirectory)) - process, err := buildprocess.Start(ctx, buildprocess.Spec{ - Kind: processledger.KindBuild, - Executable: execution.Executable, - Arguments: plan.Arguments, - WorkingDirectory: workingDirectory, - Environment: applyToolchainSelection(plan.Environment, execution.selection()), - }, func(_ buildprocess.Stream, text string) { + process, err := a.startBuildExecution(ctx, p, execution, plan.Arguments, workingDirectory, plan.Environment, func(_ buildprocess.Stream, text string) { a.streamBuildOutput(p, op, text) }) if err != nil { @@ -1494,7 +1582,7 @@ func (a *App) resolveBuildExecutable(ctx context.Context, p *project, instance b if err != nil { return buildExecution{}, err } - invocation, err := a.kernel.PlanBuildInvocation(ctx, instance.Manifest, instance.BuildSystemID, core.BuildInvocationRequest{Root: instance.Root, Platform: buildPlatform(), Settings: settings.State.Settings}) + invocation, err := a.kernel.PlanBuildInvocation(ctx, instance.Manifest, instance.BuildSystemID, core.BuildInvocationRequest{Root: instance.Root, Platform: p.buildPlatform(), Settings: settings.Settings}) if err != nil { return buildExecution{}, err } @@ -1504,7 +1592,7 @@ func (a *App) resolveBuildExecutable(ctx context.Context, p *project, instance b return nil } return func(candidate buildExecution) error { - output, probeErr := probeBuildTool(ctx, candidate.Executable, versionSpec.Arguments, p.root, applyToolchainSelection(nil, candidate.selection())) + output, probeErr := a.probeWorkspaceBuildTool(ctx, p, candidate, versionSpec.Arguments) if probeErr != nil { return probeErr } @@ -1518,7 +1606,7 @@ func (a *App) resolveBuildExecutable(ctx context.Context, p *project, instance b return nil } } - var runtimeEnvironment map[string]string + var runtimeEnvironment core.ToolchainSelection for _, requirement := range invocation.RuntimeDependencies { resolved, err := a.resolveAndCheckBuildCandidates( ctx, p, instance.Root, requirement.Executables, requirement.MinimumVersion, @@ -1534,7 +1622,12 @@ func (a *App) resolveBuildExecutable(ctx context.Context, p *project, instance b } resolved.Environment[requirement.PathVariable] = resolved.Executable } - runtimeEnvironment = applyToolchainSelection(runtimeEnvironment, resolved.selection()) + selection := resolved.selection() + if p.remote != nil { + runtimeEnvironment.PathPrepend = append(append([]string(nil), resolved.PathPrepend...), runtimeEnvironment.PathPrepend...) + selection.PathPrepend = nil + } + runtimeEnvironment.Environment = applyToolchainSelection(runtimeEnvironment.Environment, selection) runtimes[requirement.ID] = resolved } execution, err := a.resolveAndCheckBuildCandidates( @@ -1551,14 +1644,14 @@ func (a *App) resolveBuildExecutable(ctx context.Context, p *project, instance b // Native candidate lookup consumes Core's order and runtime bindings. Runtime // exports and version probes are applied before the build tool itself starts. func (a *App) resolveBuildCandidates(ctx context.Context, p *project, directory string, candidates []core.BuildExecutableCandidate, minimum string, messages i18n.BuildMessages, runtimes map[string]buildExecution) (buildExecution, error) { - return a.resolveAndCheckBuildCandidates(ctx, p, directory, candidates, minimum, messages, runtimes, nil, nil) + return a.resolveAndCheckBuildCandidates(ctx, p, directory, candidates, minimum, messages, runtimes, core.ToolchainSelection{}, nil) } func (a *App) resolveAndCheckBuildCandidates( ctx context.Context, p *project, directory string, candidates []core.BuildExecutableCandidate, minimum string, messages i18n.BuildMessages, runtimes map[string]buildExecution, - inheritedEnv map[string]string, validate func(buildExecution) error, + inherited core.ToolchainSelection, validate func(buildExecution) error, ) (buildExecution, error) { var lastErr error for _, candidate := range candidates { @@ -1573,7 +1666,10 @@ func (a *App) resolveAndCheckBuildCandidates( if candidate.Kind != "runtime" { execution.Source.Kind, execution.Source.Variable = candidate.Kind, candidate.Variable } - execution.Environment = applyToolchainSelection(execution.Environment, core.ToolchainSelection{Environment: inheritedEnv}) + execution.Environment = applyToolchainSelection(execution.Environment, core.ToolchainSelection{Environment: inherited.Environment}) + if len(inherited.PathPrepend) != 0 { + execution.PathPrepend = append(append([]string(nil), execution.PathPrepend...), inherited.PathPrepend...) + } if validate != nil { if checkErr := validate(execution); checkErr != nil { if terminal || ctx.Err() != nil { @@ -1592,6 +1688,9 @@ func (a *App) resolveAndCheckBuildCandidates( } func (a *App) resolveOneBuildCandidate(ctx context.Context, p *project, directory string, candidate core.BuildExecutableCandidate, minimum string, runtimes map[string]buildExecution) (buildExecution, bool, bool, error) { + if p.remote != nil && candidate.Kind != "toolchain" && candidate.Kind != "runtime" { + return a.remoteBuildCandidate(ctx, p, candidate) + } var execution buildExecution terminal := false resolved := false @@ -1641,6 +1740,9 @@ func (a *App) resolveOneBuildCandidate(ctx context.Context, p *project, director resolved = true } case "toolchain": + if p.remote != nil && core.RemoteWorkspaceOf(ctx) == nil { + return buildExecution{}, true, false, errors.New("remote toolchain resolution has no workspace attachment") + } selection, selectErr := a.resolveToolchainSelection(ctx, p.root, directory, candidate.ToolchainID, minimum) if selectErr != nil { var unavailable *toolchain.UnavailableError @@ -1670,10 +1772,22 @@ func buildRequiresPresent(path string, required []string, root string) bool { return err == nil } +func (a *App) probeWorkspaceBuildTool(ctx context.Context, p *project, execution buildExecution, arguments []string) (string, error) { + return probeBuildOutput(ctx, func(probeCtx context.Context) (buildCommandOutput, error) { + return a.captureWorkspaceBuildProcess(probeCtx, p, execution, arguments, p.root, nil, false, nil) + }) +} + func probeBuildTool(ctx context.Context, executable string, arguments []string, workingDirectory string, environment map[string]string) (string, error) { + return probeBuildOutput(ctx, func(probeCtx context.Context) (buildCommandOutput, error) { + return captureBuildProcess(probeCtx, executable, arguments, workingDirectory, environment, false, nil) + }) +} + +func probeBuildOutput(ctx context.Context, capture func(context.Context) (buildCommandOutput, error)) (string, error) { probeCtx, cancel := context.WithTimeout(ctx, buildToolProbeTimeout) defer cancel() - output, waitErr := captureBuildProcess(probeCtx, executable, arguments, workingDirectory, environment, false, nil) + output, waitErr := capture(probeCtx) if waitErr != nil { if errors.Is(probeCtx.Err(), context.DeadlineExceeded) && ctx.Err() == nil { return "", fmt.Errorf("version check timed out after %s: %w", buildToolProbeTimeout, waitErr) @@ -1699,15 +1813,21 @@ type buildCommandOutput struct { // one's log. What a tool reports on stderr while it works, as go does while it downloads // modules, then never lands in the document. func captureBuildProcess(ctx context.Context, executable string, arguments []string, workingDirectory string, environment map[string]string, documentOnStdout bool, log func(string)) (buildCommandOutput, error) { + return collectBuildOutput(documentOnStdout, log, func(output func(buildprocess.Stream, string)) (buildProcess, error) { + return buildprocess.Start(ctx, buildprocess.Spec{ + Kind: processledger.KindBuild, + Executable: executable, + Arguments: arguments, + WorkingDirectory: workingDirectory, + Environment: environment, + }, output) + }) +} + +func collectBuildOutput(documentOnStdout bool, log func(string), start func(func(buildprocess.Stream, string)) (buildProcess, error)) (buildCommandOutput, error) { var stdout, combined strings.Builder var outputMu sync.Mutex - process, err := buildprocess.Start(ctx, buildprocess.Spec{ - Kind: processledger.KindBuild, - Executable: executable, - Arguments: arguments, - WorkingDirectory: workingDirectory, - Environment: environment, - }, func(stream buildprocess.Stream, text string) { + process, err := start(func(stream buildprocess.Stream, text string) { outputMu.Lock() if stream == buildprocess.Stdout && stdout.Len() < buildCaptureBytes { stdout.WriteString(text) @@ -1740,6 +1860,13 @@ func buildPlatform() string { } } +func (p *project) buildPlatform() string { + if p.remote != nil { + return "linux" + } + return buildPlatform() +} + // buildTargetRunEntries returns the command Run entries Core derived for targetID, in Core's // order. Provider runs are not among them; the Build window lists those from the declarations. func buildTargetRunEntries(instance *buildInstance, targetID string) []core.BuildRunEntry { @@ -1768,6 +1895,10 @@ func (a *App) runBuildEntry(p *project, entryID string) { // startBuildEntry runs the command Run entry entryID of the instance instanceID, which is // selected, once no run of it runs (runBuildEntry). func (a *App) startBuildEntry(p *project, instanceID, entryID string) { + connection, ok := captureWorkspaceConnection(p) + if !ok { + return + } instance := p.selectedBuildInstance() if instance == nil || instance.ID != instanceID { return @@ -1795,6 +1926,7 @@ func (a *App) startBuildEntry(p *project, instanceID, entryID string) { a.runBuildEntry(p, entryID) })) a.background(p, 0, func(ctx context.Context) func(*App) { + ctx = attachedWorkspaceContext(ctx, connection) bounded, cancel := context.WithTimeout(ctx, runPreparationTimeout) defer cancel() prepare, release := op.bind(bounded) @@ -1833,6 +1965,9 @@ func (a *App) startBuildTarget(p *project, targetID string, run pluginservice.Bu } key, instanceID := targetRunKey(instance.ID, targetID, run.ID), instance.ID a.startRun(p, key, func(a *App, p *project) { + if debug != nil && debug.connection != nil && !debug.connection.IsCurrent() { + return + } if selected := p.selectedBuildInstance(); selected != nil && selected.ID == instanceID { a.beginBuildTarget(p, key, targetID, run, debug) } @@ -1867,6 +2002,7 @@ func (a *App) beginBuildTarget(p *project, key, targetID string, run pluginservi } if debug != nil { op.debug = debug + op.connection = debug.connection options.Debug = &debug.launch } a.runBuildTargetWith(p, op, instance, target.ProjectID, targetID, runID, options, nil) @@ -1895,6 +2031,10 @@ func (a *App) debugProviderTarget(p *project, index int, projectID, targetID, ru if p == nil || index < 0 || index >= len(p.build.instances) || p.debug.preparing { return } + connection, connected := captureWorkspaceConnection(p) + if !connected { + return + } instance := &p.build.instances[index] run, ok := buildRunDeclaration(instance.System, runID) if !ok || run.DebugAdapter == "" { @@ -1915,6 +2055,15 @@ func (a *App) debugProviderTarget(p *project, index int, projectID, targetID, ru return } captured := *instance + if p.safeMode() { + reference := core.RunProviderReference{PluginID: captured.PluginID, BuildSystemID: captured.BuildSystemID, Root: captured.Root} + a.askToTrustProject(p, func() { + if connection == nil || connection.IsCurrent() { + a.redebugProviderTarget(p, reference, projectID, targetID, runID) + } + }) + return + } kernel := a.kernel messages := a.text.Build // Rerun prepares the same target again, through the instance detection names the same way, @@ -1934,16 +2083,21 @@ func (a *App) debugProviderTarget(p *project, index int, projectID, targetID, ru fail := func(err error) func(*App) { return func(a *App) { p.debug.preparing = false + // log-exempt: 用户取消:原工作区连接已经关闭。 + if connection != nil && !connection.IsCurrent() { + return + } a.operationFailed("build_debug_prepare", err) a.notifyError(a.launchFailureText(err)) } } a.saveProjectDocuments(p, func(saved bool) { - if !saved { + if !saved || (connection != nil && !connection.IsCurrent()) { p.debug.preparing = false return } a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { + ctx = attachedWorkspaceContext(ctx, connection) a.addBuildToolHint(ctx, p, captured, &request) plan, err := kernel.PlanBuildDebug(ctx, captured.Manifest, captured.BuildSystemID, request) if err != nil { @@ -1975,7 +2129,7 @@ func (a *App) debugProviderTarget(p *project, index int, projectID, targetID, ru } return func(a *App) { p.debug.preparing = false - a.startProviderDebug(p, captured.PluginID, preparation, rerun) + a.startProviderDebug(p, captured.PluginID, preparation, rerun, connection) } }) }) @@ -2010,8 +2164,11 @@ func buildRunDeclaration(system pluginservice.BuildSystemDeclaration, id string) // Core checked belongs to the same plugin. The installed adapters are read first when the Debug // window has not read them yet. Core answers workspace-relative paths; the adapter gets them // absolute. rerun prepares the program again for the Debug window's Rerun. -func (a *App) startProviderDebug(p *project, pluginID string, preparation core.BuildDebugPreparation, rerun func()) { +func (a *App) startProviderDebug(p *project, pluginID string, preparation core.BuildDebugPreparation, rerun func(), connection *core.RemoteWorkspaceConnection) { a.whenDebugAdaptersLoaded(p, func() { + if connection != nil && !connection.IsCurrent() { + return + } for _, adapter := range p.debug.adapters { if adapter.PluginID != pluginID || adapter.Declaration.ID != preparation.Adapter || !adapter.Declaration.Serves("launch") { continue @@ -2026,7 +2183,7 @@ func (a *App) startProviderDebug(p *project, pluginID string, preparation core.B environment = map[string]string{} } a.beginDebug(p, debugStart{ - adapter: adapter, request: "launch", ended: make(chan *int, 1), rerun: rerun, + adapter: adapter, request: "launch", ended: make(chan *int, 1), rerun: rerun, connection: connection, launchTarget: &core.DebugTargetFacts{ Kind: "executable", Path: program, Executable: program, WorkingDirectory: filepath.Join(p.root, filepath.FromSlash(preparation.WorkingDirectory)), @@ -2046,6 +2203,14 @@ func (a *App) startProviderDebug(p *project, pluginID string, preparation core.B // run declarations do not come here: Core expands them into the model's Run entries, which // runBuildEntry runs. func (a *App) runBuildTargetWith(p *project, op *buildOperation, instance *buildInstance, projectID, targetID, runID string, options *core.RunLaunchOptions, overrides map[string]json.RawMessage) { + connection, connected := captureWorkspaceConnection(p) + if op.connection != nil { + connection, connected = op.connection, op.connection.IsCurrent() + } + if !connected { + a.finishBuildError(p, op, &core.Error{Code: core.CodeConnectionClosed, Message: "The workspace connection changed."}) + return + } project, ok := buildProjectByID(instance.Model, projectID) if !ok { a.notifyError(a.text.Build.ProjectMissing) @@ -2067,6 +2232,7 @@ func (a *App) runBuildTargetWith(p *project, op *buildOperation, instance *build kernel := a.kernel messages := a.text.Build a.background(p, 0, func(ctx context.Context) func(*App) { + ctx = attachedWorkspaceContext(ctx, connection) bounded, cancel := context.WithTimeout(ctx, runPreparationTimeout) defer cancel() prepare, release := op.bind(bounded) @@ -2114,16 +2280,51 @@ func (a *App) runBuildTargetWith(p *project, op *buildOperation, instance *build if err != nil { return func(a *App) { a.finishBuildError(p, op, err) } } - execution := buildExecution{} + execution := buildExecution{Placement: launch.Placement} + executionRoot, executionInstance := p.root, captured.Root + resolveContext := prepare + remoteProcess := connection != nil && launch.Placement != core.ProcessPlacementUI + if op.debug != nil && connection != nil && !remoteProcess { + return func(a *App) { a.finishBuildError(p, op, errors.New(messages.CommandUnsupported)) } + } + if connection != nil && !remoteProcess { + if !connection.IsCurrent() { + return func(a *App) { + a.finishBuildError(p, op, &core.Error{Code: core.CodeConnectionClosed, Message: "The workspace connection changed."}) + } + } + runContext, cancelRun := context.WithCancel(ctx) + defer cancelRun() + stopDetach := connection.AfterDetach(cancelRun) + defer stopDetach() + stopPrepare := context.AfterFunc(runContext, release) + defer stopPrepare() + ctx = runContext + resolveContext = core.WithoutRemoteWorkspace(prepare) + executionRoot = buildStateDirectory(a.plugins.Root, p.root, captured) + executionInstance = "." + if err := os.MkdirAll(executionRoot, 0o700); err != nil { + return func(a *App) { a.finishBuildError(p, op, err) } + } + } switch launch.Executable.Kind { case "command": - executable, lookupErr := exec.LookPath(launch.Executable.Value) + var executable string + var lookupErr error + if !remoteProcess { + executable, lookupErr = exec.LookPath(launch.Executable.Value) + } else { + executable, lookupErr = a.kernel.ResolveRemoteExecutable(prepare, core.RemoteExecutableRequest{Kind: "program", Value: launch.Executable.Value}) + if lookupErr == nil && executable == "" { + lookupErr = errors.New(messages.ExecutableMissing) + } + } if lookupErr != nil { return func(a *App) { a.finishBuildError(p, op, lookupErr) } } execution.Executable = executable case "toolchain": - selection, selectErr := a.resolveToolchainSelection(prepare, p.root, captured.Root, launch.Executable.Value, "") + selection, selectErr := a.resolveToolchainSelection(resolveContext, executionRoot, executionInstance, launch.Executable.Value, "") if selectErr != nil { return func(a *App) { a.finishBuildError(p, op, selectErr) } } @@ -2138,15 +2339,14 @@ func (a *App) runBuildTargetWith(p *project, op *buildOperation, instance *build if prepare.Err() != nil { return func(a *App) { a.finishBuildError(p, op, prepare.Err()) } } - workingDirectory := filepath.Join(p.root, filepath.FromSlash(launch.WorkingDirectory)) + if connection != nil && !connection.IsCurrent() { + return func(a *App) { + a.finishBuildError(p, op, &core.Error{Code: core.CodeConnectionClosed, Message: "The workspace connection changed."}) + } + } + workingDirectory := filepath.Join(executionRoot, filepath.FromSlash(launch.WorkingDirectory)) op.decoder.declare(launch.OutputEncoding) - process, err := buildprocess.Start(ctx, buildprocess.Spec{ - Kind: processledger.KindBuild, - Executable: execution.Executable, - Arguments: launch.Arguments, - WorkingDirectory: workingDirectory, - Environment: applyToolchainSelection(launch.Environment, execution.selection()), - }, func(_ buildprocess.Stream, text string) { + process, err := a.startBuildExecution(ctx, p, execution, launch.Arguments, workingDirectory, launch.Environment, func(_ buildprocess.Stream, text string) { a.streamBuildOutput(p, op, text) }) if err != nil { @@ -2155,7 +2355,7 @@ func (a *App) runBuildTargetWith(p *project, op *buildOperation, instance *build a.post(func(a *App) { a.attachProcess(p, op, process) }) ended := make(chan struct{}) if op.debug != nil { - go a.attachServiceDebugger(ctx, p, op, *op.debug, ended) + go a.attachServiceDebugger(ctx, p, op, *op.debug, process, ended) } err = process.Wait() close(ended) diff --git a/desktop/internal/workbench/build_connection_debug.go b/desktop/internal/workbench/build_connection_debug.go index dd3d451843..09d3373d9d 100644 --- a/desktop/internal/workbench/build_connection_debug.go +++ b/desktop/internal/workbench/build_connection_debug.go @@ -24,8 +24,9 @@ import ( // connectionDebug is one debug launch of a service run: the adapter the host selected, kept to // attach exactly that registration, and the debug options the provider prepares the run with. type connectionDebug struct { - adapter debugAdapter - launch core.RunLaunchDebug + adapter debugAdapter + launch core.RunLaunchDebug + connection *core.RemoteWorkspaceConnection } // connectionDebugRefusal is why no adapter can attach to a run's declared type: reason is the @@ -86,7 +87,22 @@ func (a *App) prepareConnectionDebug(p *project, configurationType string, start if p == nil { return } + connection, connected := captureWorkspaceConnection(p) + if !connected { + return + } + if p.safeMode() { + a.askToTrustProject(p, func() { + if connection == nil || connection.IsCurrent() { + a.prepareConnectionDebug(p, configurationType, start) + } + }) + return + } a.whenDebugAdaptersLoaded(p, func() { + if connection != nil && !connection.IsCurrent() { + return + } if p.debug.activeSession() != nil { a.operationRejected("build_debug_connection", "session_running") a.notifyInfo(i18n.Shared(a.language(), "desktop.build.debugSessionRunning")) @@ -101,17 +117,33 @@ func (a *App) prepareConnectionDebug(p *project, configurationType string, start } return } - port, err := freeLoopbackPort() - if err != nil { - a.operationFailed("build_debug_port", err) - a.notifyError(err.Error()) + finish := func(a *App, port int, err error) { + if err != nil { + a.operationFailed("build_debug_port", err) + a.notifyError(a.launchFailureText(err)) + return + } + start(connectionDebug{adapter: adapter, connection: connection, launch: core.RunLaunchDebug{ + AdapterID: adapter.PluginID + "/" + adapter.Declaration.ID, + ConfigurationType: configurationType, + Target: core.RunDebugConnection{Kind: "connection", Host: debugLoopback, Port: port}, + }}) + } + if connection == nil { + port, err := freeLoopbackPort() + finish(a, port, err) return } - start(connectionDebug{adapter: adapter, launch: core.RunLaunchDebug{ - AdapterID: adapter.PluginID + "/" + adapter.Declaration.ID, - ConfigurationType: configurationType, - Target: core.RunDebugConnection{Kind: "connection", Host: "127.0.0.1", Port: port}, - }}) + kernel := a.kernel + a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { + port, err := kernel.PickRemoteLoopbackPort(connection.Context(ctx)) + return func(a *App) { + // log-exempt: 用户取消:端口属于已经断开的会话。 + if connection.IsCurrent() { + finish(a, port, err) + } + } + }) }) } @@ -131,16 +163,23 @@ func (a *App) debugRunConfiguration(p *project, id, configurationType string) { // debugServiceTarget debugs one target of the selected instance through run, a service run that // declares a public debug type, with the launch options of a run that has no configuration. func (a *App) debugServiceTarget(p *project, targetID string, run pluginservice.BuildRunDeclaration) { + instance := p.selectedBuildInstance() + if instance == nil { + return + } + instanceID := instance.ID a.prepareConnectionDebug(p, run.DebugConfigurationType, func(debug connectionDebug) { - a.startBuildTarget(p, targetID, run, &debug) + if selected := p.selectedBuildInstance(); selected != nil && selected.ID == instanceID { + a.startBuildTarget(p, targetID, run, &debug) + } }) } // attachServiceDebugger waits off the window thread until the debuggee listens on its port, then // attaches the selected adapter on the window thread. A debuggee that never listens ends the run // with the reason; one that exits first ends the run the ordinary way, as its exit reports. -func (a *App) attachServiceDebugger(ctx context.Context, p *project, op *buildOperation, debug connectionDebug, ended <-chan struct{}) { - err := pluginservice.WaitForDebugPort(ctx, debug.launch.Target.Port, ended, pluginservice.RunDebugConnectTimeout) +func (a *App) attachServiceDebugger(ctx context.Context, p *project, op *buildOperation, debug connectionDebug, process buildProcess, ended <-chan struct{}) { + err := pluginservice.WaitForOwnedDebugPort(ctx, a.kernel, process, debug.launch.Target.Port, ended) a.post(func(a *App) { if a.project != p || !p.build.owns(op) || op.cancelled { return @@ -151,7 +190,12 @@ func (a *App) attachServiceDebugger(ctx context.Context, p *project, op *buildOp // against the plugins as they are now. a.whenDebugAdaptersLoaded(p, func() { if p.build.owns(op) && !op.cancelled { - a.attachServiceDebugSession(p, op, debug) + select { + case <-ended: + return + default: + a.attachServiceDebugSession(p, op, debug) + } } }) case errors.Is(err, pluginservice.ErrDebuggeeEnded) || errors.Is(err, context.Canceled): @@ -183,7 +227,7 @@ func (a *App) attachServiceDebugSession(p *project, op *buildOperation, debug co return } a.beginDebug(p, debugStart{ - adapter: p.debug.adapters[index], request: "attach", confirmed: true, + adapter: p.debug.adapters[index], request: "attach", confirmed: true, connection: debug.connection, target: &core.DebugTargetFacts{Kind: "connection", Host: debug.launch.Target.Host, Port: debug.launch.Target.Port}, // Release calls stopRun off the window thread. stopRun: func() { diff --git a/desktop/internal/workbench/build_dependencies.go b/desktop/internal/workbench/build_dependencies.go index 6383f300aa..442966284d 100644 --- a/desktop/internal/workbench/build_dependencies.go +++ b/desktop/internal/workbench/build_dependencies.go @@ -74,6 +74,10 @@ func (a *App) loadBuildDependencies(p *project, instance *buildInstance, project if !ok { return } + connection, connected := captureWorkspaceConnection(p) + if !connected { + return + } var selection *core.BuildSelection if projectID != "" { project, found := buildProjectByID(instance.Model, projectID) @@ -88,9 +92,9 @@ func (a *App) loadBuildDependencies(p *project, instance *buildInstance, project generation := deps.generation captured := *instance a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { - tree, err := a.buildDependencyTree(ctx, p, captured, kernel, selection, refresh) + tree, err := a.buildDependencyTree(attachedWorkspaceContext(ctx, connection), p, captured, kernel, selection, refresh) return func(a *App) { - if deps.generation != generation { + if deps.generation != generation || (connection != nil && !connection.IsCurrent()) { return } deps.loading = false @@ -125,8 +129,7 @@ func (a *App) buildDependencyTree(ctx context.Context, p *project, instance buil } return fail(core.StageResolve, err) } - // The package directory expands ${pluginDir} in a dependency command. - request := core.BuildPlanRequest{Root: instance.Root, Options: instance.Options, PluginDirectory: instance.PackageDirectory, WorkspaceRoot: p.root, Project: selection, ProjectCodeAllowed: p.trust.allowed()} + request := core.BuildPlanRequest{Root: instance.Root, Options: instance.Options, WorkspaceRoot: p.root, Project: selection, ProjectCodeAllowed: p.trust.allowed()} decode := core.BuildDecodeDependenciesRequest{WorkspaceRoot: p.root, Root: instance.Root} if selection != nil { decode.Project = selection.Path @@ -159,19 +162,13 @@ func (a *App) buildDependencyTree(ctx context.Context, p *project, instance buil return kernel.DecodeBuildDependencies(ctx, instance.Manifest, instance.BuildSystemID, decode) } // A command may write its tree to a file the host allocates in the plugin's state. - state := buildStateDirectory(a.plugins.Root, p.root, instance) - if err := os.MkdirAll(state, 0o700); err != nil { - return fail(core.StagePlan, err) - } - file, err := os.CreateTemp(state, "dependencies-*.json") + scratch, err := a.prepareBuildScratch(ctx, p, instance, "dependencies") if err != nil { return fail(core.StagePlan, err) } - outputFile := file.Name() - _ = file.Close() - _ = os.Remove(outputFile) - defer os.Remove(outputFile) - request.OutputFile = outputFile + defer scratch.release() + request.PluginDirectory = scratch.packageDirectory + request.OutputFile = scratch.output plan, err := kernel.PlanBuildDependencies(ctx, instance.Manifest, instance.BuildSystemID, request) if err != nil { return fail(core.StagePlan, err) @@ -179,7 +176,7 @@ func (a *App) buildDependencyTree(ctx context.Context, p *project, instance buil if plan.Provider != nil { return fail(core.StagePlan, errors.New("the build system answered with a provider request")) } - return a.commandDependencies(ctx, p, instance, kernel, attempt, plan, execution, decode, outputFile) + return a.commandDependencies(ctx, p, instance, kernel, attempt, plan, execution, decode, scratch.output) } // commandDependencies runs a command plan and decodes what it printed or wrote, and ends the @@ -187,7 +184,7 @@ func (a *App) buildDependencyTree(ctx context.Context, p *project, instance buil func (a *App) commandDependencies(ctx context.Context, p *project, instance buildInstance, kernel buildDependencyKernel, attempt *core.PluginAttempt, plan core.BuildPlan, execution buildExecution, decode core.BuildDecodeDependenciesRequest, outputFile string) (core.BuildDependencyTree, error) { workingDirectory := filepath.Join(p.root, filepath.FromSlash(plan.WorkingDirectory)) toFile := plan.Output == "outputFile" && outputFile != "" - output, runErr := captureBuildProcess(ctx, execution.Executable, plan.Arguments, workingDirectory, applyToolchainSelection(plan.Environment, execution.selection()), !toFile, nil) + output, runErr := a.captureWorkspaceBuildProcess(ctx, p, execution, plan.Arguments, workingDirectory, plan.Environment, !toFile, nil) runErr = withBuildOutput(runErr, output.combined) if toFile { decode.OutputFile = outputFile diff --git a/desktop/internal/workbench/build_options.go b/desktop/internal/workbench/build_options.go index a741d4c4e3..1a88b0b09f 100644 --- a/desktop/internal/workbench/build_options.go +++ b/desktop/internal/workbench/build_options.go @@ -40,7 +40,7 @@ func (a *App) readBuildOptionDocuments(ctx context.Context, root string) (buildO // detectBuildSystemsWithStoredOptions resolves the stored documents and detects the instances with the merged // values. Only Core merges documents; this function maps the merged document onto the detection inputs. func detectBuildSystemsWithStoredOptions(ctx context.Context, kernel Kernel, root string, manifests []json.RawMessage, docs buildOptionDocuments) (core.BuildDetection, error) { - storage, err := kernel.ResolveStoredBuildOptions(ctx, docs.team, docs.local) + storage, err := kernel.ResolveStoredBuildOptions(core.WithoutRemoteWorkspace(ctx), docs.team, docs.local) if err != nil { return core.BuildDetection{}, err } diff --git a/desktop/internal/workbench/build_options_runtime.go b/desktop/internal/workbench/build_options_runtime.go index aa02228bea..4505e68d5b 100644 --- a/desktop/internal/workbench/build_options_runtime.go +++ b/desktop/internal/workbench/build_options_runtime.go @@ -61,13 +61,19 @@ func droppedBuildOptionIDs(instance *buildInstance, fields []runOptionField) []s func (a *App) readBuildInstanceDetails(p *project, instance buildInstance, dropped []string) { session, root, messages := p.build.options.session, p.root, a.text.Build tool := buildSystemName(&instance) + connection, connected := captureWorkspaceConnection(p) a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { + ctx = attachedWorkspaceContext(ctx, connection) var values []buildDroppedOption var readErr error - if len(dropped) > 0 { + if connected && len(dropped) > 0 { values, readErr = a.readDroppedBuildOptions(ctx, root, instance, dropped) } - runtimes, planErr := a.resolveBuildRuntimes(ctx, p, instance, tool, messages) + var runtimes []buildRuntimeView + var planErr error + if connected && (connection == nil || p.trust.allowed()) { + runtimes, planErr = a.resolveBuildRuntimes(ctx, p, instance, tool, messages) + } if readErr != nil { a.backgroundFailedIn(ctx, "build_options_dropped", readErr) } @@ -76,7 +82,7 @@ func (a *App) readBuildInstanceDetails(p *project, instance buildInstance, dropp } return func(a *App) { e := &p.build.options - if !e.open || e.session != session { + if !e.open || e.session != session || (connection != nil && !connection.IsCurrent()) { return } if readErr == nil { @@ -97,7 +103,7 @@ func (a *App) resolveBuildRuntimes(ctx context.Context, p *project, instance bui if err != nil { return nil, err } - invocation, err := a.kernel.PlanBuildInvocation(ctx, instance.Manifest, instance.BuildSystemID, core.BuildInvocationRequest{Root: instance.Root, Platform: buildPlatform(), Settings: settings.State.Settings}) + invocation, err := a.kernel.PlanBuildInvocation(ctx, instance.Manifest, instance.BuildSystemID, core.BuildInvocationRequest{Root: instance.Root, Platform: p.buildPlatform(), Settings: settings.Settings}) if err != nil { return nil, err } diff --git a/desktop/internal/workbench/debug.go b/desktop/internal/workbench/debug.go index c2446338e7..188da061b4 100644 --- a/desktop/internal/workbench/debug.go +++ b/desktop/internal/workbench/debug.go @@ -285,6 +285,13 @@ type debugSession struct { // tcpAnnounced adapter; nil for a stdio adapter. It is also the session's // transport. hosted *debugTransport + // connection and any owned native resources stay with the attachment that + // launched the session. Cleanup reads these after startup and stream release. + connection *core.RemoteWorkspaceConnection + waitRemoteAdapter func() + releaseForward func(context.Context) error + // The window owns the tabs of any terminals that this adapter started. + remoteTerminals []int // drainOnStop marks a user stop: a live hosted session sends its disconnect // and lets Core's drain flush it instead of closing the stream at once. drainOnStop atomic.Bool @@ -673,6 +680,8 @@ func (a *App) applyDebugUpdate(p *project, session *debugSession, update core.De case "startDebuggingRequested": // Opening the child changes the sessions, so it runs after this update. a.post(func(a *App) { a.startChildDebug(p, session, event) }) + case "runInTerminalRequested": + a.post(func(a *App) { a.openRemoteDebugTerminal(p, session, event) }) case "output": p.debug.addOutput(event.Output) } @@ -887,7 +896,15 @@ func (a *App) releaseDebugSession(p *project, session *debugSession) { // failed for a reason that is not the adapter's: it records nothing. session.adapterStart.Abandon() session.cancel() - drain := session.drainOnStop.Load() && session.hosted != nil + for _, id := range session.remoteTerminals { + focus := a.focus + a.closeTerminal(p, id) + if focus.term != id { + a.focus = focus + } + } + session.remoteTerminals = nil + drain := session.drainOnStop.Load() if !drain { session.closeTransport() // A tcpAnnounced adapter's process outlives the session's context; a @@ -906,6 +923,7 @@ func (a *App) releaseDebugSession(p *project, session *debugSession) { <-session.startupDone ctx, cancel := context.WithTimeout(context.Background(), debugStopTimeout) defer cancel() + drain := drain && session.hosted != nil var cleanupErr error var destroyed []string if session.hosted != nil { @@ -946,6 +964,14 @@ func (a *App) releaseDebugSession(p *project, session *debugSession) { if session.hosted != nil { session.hosted.Release() } + if session.waitRemoteAdapter != nil { + session.waitRemoteAdapter() + } + if session.releaseForward != nil { + forwardCtx, cancelForward := context.WithTimeout(context.Background(), debugStopTimeout) + cleanupErr = errors.Join(cleanupErr, session.releaseForward(forwardCtx)) + cancelForward() + } if session.stateDirectory != "" { cleanupErr = errors.Join(cleanupErr, os.RemoveAll(session.stateDirectory)) } @@ -1024,6 +1050,9 @@ func (a *App) finishDebugError(p *project, session *debugSession, err error) { return } message := a.launchFailureText(err) + if remoteConnectionClosed(err) { + message = a.text.Debug.ConnectionClosed + } var settingsError *debugSettingsError if errors.As(err, &settingsError) { message = i18n.Shared(a.language(), "desktop.debug.settingsUnreadable") diff --git a/desktop/internal/workbench/debug_adapter_test.go b/desktop/internal/workbench/debug_adapter_test.go index 6ad0beb330..9f57beefe2 100644 --- a/desktop/internal/workbench/debug_adapter_test.go +++ b/desktop/internal/workbench/debug_adapter_test.go @@ -35,6 +35,10 @@ func TestDebugAdapterRunner(t *testing.T) { // adapter answers over a process's stdio and over a TCP connection. It returns // the exit code the stdio runner reports, and 0 when the peer disconnects. func serveFixtureAdapter(input io.Reader, output io.Writer, workspace string) int { + return serveFixtureAdapterWithAttach(input, output, workspace, nil) +} + +func serveFixtureAdapterWithAttach(input io.Reader, output io.Writer, workspace string, attach func(json.RawMessage) error) int { source := filepath.Join(workspace, "tests", "debug_source.go") reader := bufio.NewReader(input) seq := 1 @@ -94,6 +98,17 @@ func serveFixtureAdapter(input io.Reader, output io.Writer, workspace string) in write(map[string]any{"type": "response", "request_seq": request.Seq, "success": true, "command": request.Command, "body": result}) } switch request.Command { + case "attach": + if attach != nil { + if err := attach(request.Body); err != nil { + write(map[string]any{"type": "response", "request_seq": request.Seq, "success": false, "command": request.Command, "message": err.Error()}) + continue + } + } + respond(map[string]any{}) + if attach != nil { + event("stopped", map[string]any{"reason": "breakpoint", "threadId": 7}) + } case "initialize": respond(map[string]any{ "supportsConfigurationDoneRequest": true, diff --git a/desktop/internal/workbench/debug_announced.go b/desktop/internal/workbench/debug_announced.go index d4a3e6bbee..40dcc000bc 100644 --- a/desktop/internal/workbench/debug_announced.go +++ b/desktop/internal/workbench/debug_announced.go @@ -3,6 +3,7 @@ package workbench import ( "context" "errors" + "net" "strings" "sync" @@ -34,6 +35,17 @@ func (a *App) openAnnouncedTransport(ctx context.Context, p *project, session *d ) hooks := a.debugStreamHooks(p, session, messages) hooks.Discover = reader.wait + if prepared.RemoteAdapter { + hooks.Dial = func(ctx context.Context, host string, port int) (net.Conn, error) { + forward, err := a.forwardDebugEndpoint(ctx, session.connection, host, port, false) + if err != nil { + return nil, err + } + // Release waits for this dial before the session reclaims its forward. + session.releaseForward = forward.release + return dialDebugTCP(ctx, forward.host, forward.port) + } + } transport := newDebugTransport(a.kernel, session.id+"-transport", hooks) if !session.setTransport(transport) { return context.Canceled @@ -45,7 +57,11 @@ func (a *App) openAnnouncedTransport(ctx context.Context, p *project, session *d if err := transport.Start(nil); err != nil { return err } - return a.startAdapterProcess(ctx, p, session, prepared, nil, reader.observe, errors.New(messages.NotAnnounced)) + unreached := errors.New(messages.NotAnnounced) + if prepared.RemoteAdapter { + return a.startRemoteAnnouncedAdapter(ctx, p, session, prepared, reader.observe, unreached) + } + return a.startAdapterProcess(ctx, p, session, prepared, nil, reader.observe, unreached) } // debugAnnouncedEndpoint is the result of waiting for an announcement: the diff --git a/desktop/internal/workbench/debug_child.go b/desktop/internal/workbench/debug_child.go index 351b29cfa0..9aefb898b2 100644 --- a/desktop/internal/workbench/debug_child.go +++ b/desktop/internal/workbench/debug_child.go @@ -26,6 +26,7 @@ func (a *App) startChildDebug(p *project, parent *debugSession, event core.Debug adapter: parent.adapter, request: event.StartDebugging.Request, configuration: event.StartDebugging.Configuration, + connection: parent.connection, parent: parent, startRequestID: event.RequestID, }) @@ -43,20 +44,27 @@ func (a *App) answerChildStart(p *project, child *debugSession, success bool, me // respondStartDebugging sends the reply to the parent adapter through Core. Core // writes the DAP response; the frames go out before the update is applied. func (a *App) respondStartDebugging(p *project, parent *debugSession, requestID string, success bool, message string) { + a.replyDebugReverseRequest(p, parent, func(ctx context.Context) (core.DebugUpdate, error) { + return a.kernel.DebugStartDebuggingResponse(ctx, parent.id, requestID, success, message) + }) +} + +// replyDebugReverseRequest serializes the native reply with the other DAP operations. +func (a *App) replyDebugReverseRequest(p *project, session *debugSession, reduce func(context.Context) (core.DebugUpdate, error)) { a.background(p, debugOperationTimeout, func(ctx context.Context) func(*App) { - parent.operationMu.Lock() - defer parent.operationMu.Unlock() - if parent.stopped.Load() { + session.operationMu.Lock() + defer session.operationMu.Unlock() + if session.stopped.Load() { return nil } - update, err := a.kernel.DebugStartDebuggingResponse(ctx, parent.id, requestID, success, message) + update, err := reduce(ctx) if err != nil { - return func(a *App) { a.finishDebugError(p, parent, err) } + return func(a *App) { a.finishDebugError(p, session, err) } } - if err := parent.writeFrames(update.OutboundFrames); err != nil { - return func(a *App) { a.finishDebugError(p, parent, err) } + if err := session.writeFrames(update.OutboundFrames); err != nil { + return func(a *App) { a.finishDebugError(p, session, err) } } - a.postDebugUpdate(p, parent, update) + a.postDebugUpdate(p, session, update) return nil }) } diff --git a/desktop/internal/workbench/debug_kernel.go b/desktop/internal/workbench/debug_kernel.go index 7f91904a48..1108d1627f 100644 --- a/desktop/internal/workbench/debug_kernel.go +++ b/desktop/internal/workbench/debug_kernel.go @@ -21,6 +21,7 @@ type debugStateKernel interface { LocateDebugMemoryWindow(ctx context.Context, window core.DebugMemoryWindow, start string, length uint32) (core.DebugMemoryLocation, error) SetDebugVariable(ctx context.Context, sessionID, operationID string, variablesReference int64, name, value string) (core.DebugUpdate, error) DebugStartDebuggingResponse(ctx context.Context, sessionID, requestID string, success bool, message string) (core.DebugUpdate, error) + DebugRunInTerminalResponse(ctx context.Context, sessionID, requestID string, pid int64, message string) (core.DebugUpdate, error) DebugStartOrContinue(ctx context.Context, active, paused, requestPending bool) (core.DebugStartAction, error) PlanDebugVariablePage(ctx context.Context, variablesReference, namedVariables, indexedVariables int64, pageSize uint32) (core.DebugVariablePageState, error) ReduceDebugVariablePage(ctx context.Context, state core.DebugVariablePageState, requested core.DebugVariablePageRequest, page []core.DebugVariablePageItem, newItemCount uint64) (bool, core.DebugVariablePageState, error) diff --git a/desktop/internal/workbench/debug_launch.go b/desktop/internal/workbench/debug_launch.go index 89d9ccb212..29ef704b57 100644 --- a/desktop/internal/workbench/debug_launch.go +++ b/desktop/internal/workbench/debug_launch.go @@ -13,6 +13,7 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginbackend" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" ) @@ -44,6 +45,8 @@ type preparedDebugLaunch struct { DisabledCapabilities []string Features json.RawMessage Defaults json.RawMessage + RemoteAdapter bool + RemotePathPrepend []string // Endpoint is the plan's endpoint descriptor, passed unchanged to Core when // it reads the output of a tcpAnnounced adapter for its announcement. Endpoint json.RawMessage @@ -131,8 +134,9 @@ func (a *App) resolveAdapterProcess(ctx context.Context, adapter debugAdapter, p // prepareDebugLaunch runs off the window thread. The Core owns template expansion // and DAP argument bindings; this adapter only verifies and opens native resources. // It reads only p's root and its workspace trust, which is atomic. -func (a *App) prepareDebugLaunch(ctx context.Context, start debugStart, stateDirectory string, p *project, targetPath string, generation uint64, unavailable string) (preparedDebugLaunch, error) { +func (a *App) prepareDebugLaunch(ctx context.Context, start debugStart, session *debugSession, p *project, targetPath string, generation uint64, unavailable string) (preparedDebugLaunch, error) { root := p.root + stateDirectory := session.stateDirectory adapter := start.adapter hosted := adapter.Declaration.Transport == "tcpLanguageServer" settings, err := a.loadPluginPreferenceSources(ctx, adapter.Manifest, root) @@ -146,23 +150,77 @@ func (a *App) prepareDebugLaunch(ctx context.Context, start debugStart, stateDir LogDirectory: a.pluginLogDirectory(ctx, adapter.PluginID), TemporaryDirectory: filepath.Join(stateDirectory, "tmp"), Architecture: core.PluginArchitecture(), - Settings: settings.State.Settings, - ProjectSettings: settings.State.ProjectSettings, + Settings: settings.Settings, + ProjectSettings: settings.ProjectSettings, // A hosted adapter's launch is its language server's, which Core refuses in an // untrusted workspace when the server runs project code. ProjectCodeAllowed: p.trust.allowed(), } - plan, err := a.kernel.PlanPluginDebugAdapter(ctx, adapter.Manifest, adapter.Declaration.ID, directories) + if start.connection != nil { + directories.RemoteWorkspace = true + directories.Architecture = p.remote.platform.Arch + directories.ProbeLocalPlacement = true + } + plan, err := a.kernel.PlanPluginDebugAdapter(core.WithoutRemoteWorkspace(ctx), adapter.Manifest, adapter.Declaration.ID, directories) if err != nil { return preparedDebugLaunch{}, adapterUnresolved(err) } + remoteAdapter := start.connection != nil && plan.Placement != string(core.ProcessPlacementUI) + if start.connection != nil && !remoteAdapter { + directories.ProbeLocalPlacement = false + plan, err = a.kernel.PlanPluginDebugAdapter(core.WithoutRemoteWorkspace(ctx), adapter.Manifest, adapter.Declaration.ID, directories) + if err != nil { + return preparedDebugLaunch{}, adapterUnresolved(err) + } + } + installed := pluginpkg.Installed{ID: adapter.PluginID, Version: adapter.Version, Path: adapter.Directory} + if remoteAdapter && !hosted && len(plan.RequiredPackagePaths) != 0 { + deploy := a.plugins.RemoteDeployment(installed, adapter.Manifest, p.remote.platform, nil) + directories.RemotePluginDirectory, err = deploy(start.connection.Context(ctx), plan.RequiredPackagePaths) + if err != nil { + return preparedDebugLaunch{}, adapterUnresolved(err) + } + directories.ProbeLocalPlacement = false + plan, err = a.kernel.PlanPluginDebugAdapter(core.WithoutRemoteWorkspace(ctx), adapter.Manifest, adapter.Declaration.ID, directories) + if err != nil { + return preparedDebugLaunch{}, adapterUnresolved(err) + } + } var executable string processArguments := plan.Arguments var environment map[string]string + var remotePathPrepend []string // An adapter inside a language server has no process of its own: the plan's // launch is the server's, which its language session starts. if !hosted { - executable, processArguments, environment, err = a.resolveAdapterProcess(ctx, adapter, plan, root, stateDirectory) + if remoteAdapter { + remoteCtx := start.connection.Context(ctx) + switch plan.Launch.Kind { + case pluginhost.LaunchPackaged: + executable = plan.Launch.RemoteExecutable + case pluginhost.LaunchSystemCommand: + executable, err = a.resolveRemoteDebugCommand(remoteCtx, plan.Launch.Commands) + case pluginhost.LaunchTool: + input := pluginbackend.ToolEntryLaunch{ + Tool: plan.Launch.Tool, Executable: plan.Launch.RemoteExecutable, Entry: plan.Launch.Entry, + MinimumVersion: plan.Launch.MinimumVersion, RuntimeArguments: plan.Launch.RuntimeArguments, Arguments: plan.Arguments, + } + if input.Executable == "" { + managed, err := a.plugins.RemoteTools(remoteCtx, installed, adapter.Manifest, start.connection, p.remote.platform) + if err != nil { + return preparedDebugLaunch{}, adapterUnresolved(err) + } + tool := managed[input.Tool] + input.Executable, input.Home = tool.Path, tool.Home + } + var tool pluginbackend.ToolExecutable + tool, err = a.resolveBackendToolEntry(remoteCtx, adapter.PluginID, root, input) + executable, processArguments = tool.Path, tool.Arguments + environment, remotePathPrepend = tool.Environment, tool.PathPrepend + } + } else { + executable, processArguments, environment, err = a.resolveAdapterProcess(core.WithoutRemoteWorkspace(ctx), adapter, plan, root, stateDirectory) + } if err != nil { return preparedDebugLaunch{}, adapterUnresolved(err) } @@ -184,12 +242,24 @@ func (a *App) prepareDebugLaunch(ctx context.Context, start debugStart, stateDir // adapter's declared connection, so the host passes the facts unchanged. target = *start.target } else { - lookup, err := a.kernel.PlanDebugExecutable(ctx, adapter.Manifest, adapter.Declaration.ID, root, targetPath, settings.State.Settings, settings.State.ProjectSettings) + lookup, err := a.kernel.PlanDebugExecutable(ctx, adapter.Manifest, adapter.Declaration.ID, root, targetPath, settings.Settings, settings.ProjectSettings) if err != nil { return preparedDebugLaunch{}, err } if lookup != nil { - if lookup.Configured != nil { + if remoteAdapter { + candidates := lookup.Candidates + if lookup.Configured != nil { + candidates = []string{lookup.Configured.Path} + } + target.Executable, err = a.resolveRemoteDebugCommand(ctx, candidates) + if err != nil { + return preparedDebugLaunch{}, err + } + if target.Executable == "" { + return preparedDebugLaunch{}, errors.New(unavailable) + } + } else if lookup.Configured != nil { target.Executable, err = exec.LookPath(lookup.Configured.Path) if err != nil { return preparedDebugLaunch{}, err @@ -220,7 +290,11 @@ func (a *App) prepareDebugLaunch(ctx context.Context, start debugStart, stateDir } // A backend's configuration goes to Core too, which puts it over the // adapter's arguments: the host sends the result as it is. - planned, err := a.kernel.PlanDebugStart(ctx, adapter.Manifest, adapter.Declaration.ID, start.request, core.DebugStartFacts{ + argumentContext := ctx + if !remoteAdapter { + argumentContext = core.WithoutRemoteWorkspace(ctx) + } + planned, err := a.kernel.PlanDebugStart(argumentContext, adapter.Manifest, adapter.Declaration.ID, start.request, core.DebugStartFacts{ Registration: core.DebugGeneration{Generation: generation, CurrentGeneration: generation}, Target: target, }, start.configuration) @@ -229,8 +303,28 @@ func (a *App) prepareDebugLaunch(ctx context.Context, start debugStart, stateDir } // Core says which endpoints it can prove local; every other one waits for the // user, and the answer is not remembered. - if planned.Connection != nil && planned.Connection.Remote && !start.confirmed { - return preparedDebugLaunch{}, &debugRemoteError{host: planned.Connection.Host, port: planned.Connection.Port} + endpoint := planned.Connection + tunnel := start.connection != nil && !remoteAdapter + if endpoint != nil && (endpoint.Remote || tunnel) && !start.confirmed { + return preparedDebugLaunch{}, &debugRemoteError{host: endpoint.Host, port: endpoint.Port} + } + if tunnel { + if start.request != "attach" || endpoint == nil { + return preparedDebugLaunch{}, &core.Error{Code: core.CodeNotSupported, Message: unavailable} + } + local, err := a.forwardDebugEndpoint(ctx, start.connection, endpoint.Host, endpoint.Port, start.confirmed) + if err != nil { + return preparedDebugLaunch{}, err + } + session.releaseForward = local.release + target.Host, target.Port = local.host, local.port + planned, err = a.kernel.PlanDebugStart(argumentContext, adapter.Manifest, adapter.Declaration.ID, start.request, core.DebugStartFacts{ + Registration: core.DebugGeneration{Generation: generation, CurrentGeneration: generation}, + Target: target, + }, start.configuration) + if err != nil { + return preparedDebugLaunch{}, err + } } for _, slot := range plan.RequiredDirectories { var directory string @@ -266,10 +360,12 @@ func (a *App) prepareDebugLaunch(ctx context.Context, start debugStart, stateDir } } prepared := preparedDebugLaunch{ - Executable: executable, - Arguments: processArguments, - Environment: environment, - Configuration: core.DebugLaunchConfiguration{Name: adapter.Declaration.DisplayName, Request: start.request, Arguments: planned.Arguments}, + Executable: executable, + Arguments: processArguments, + Environment: environment, + RemoteAdapter: remoteAdapter, + RemotePathPrepend: remotePathPrepend, + Configuration: core.DebugLaunchConfiguration{Name: adapter.Declaration.DisplayName, Request: start.request, Arguments: planned.Arguments}, } if descriptor := plan.DebugAdapter; descriptor != nil { prepared.DisabledCapabilities = descriptor.DisabledCapabilities @@ -280,6 +376,16 @@ func (a *App) prepareDebugLaunch(ctx context.Context, start debugStart, stateDir return prepared, ctx.Err() } +func (a *App) resolveRemoteDebugCommand(ctx context.Context, candidates []string) (string, error) { + for _, candidate := range candidates { + executable, err := a.kernel.ResolveRemoteExecutable(ctx, core.RemoteExecutableRequest{Kind: "program", Value: candidate}) + if err != nil || executable != "" { + return executable, err + } + } + return "", nil +} + // installedCommands is the record of the commands the host installed for plugins; // nil, which looks up PATH only, before the plugin service opens. func (a *App) installedCommands() *pluginhost.CommandStore { diff --git a/desktop/internal/workbench/debug_launch_test.go b/desktop/internal/workbench/debug_launch_test.go index 4b93f45758..db6c665921 100644 --- a/desktop/internal/workbench/debug_launch_test.go +++ b/desktop/internal/workbench/debug_launch_test.go @@ -102,7 +102,7 @@ func TestDebugRuntimeArgumentsComeFromTheToolDefinition(t *testing.T) { } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - plan, err := h.app.prepareDebugLaunch(ctx, debugStart{adapter: adapter, request: "launch"}, filepath.Join(t.TempDir(), "state"), p, "", 1, "unavailable") + plan, err := h.app.prepareDebugLaunch(ctx, debugStart{adapter: adapter, request: "launch"}, &debugSession{stateDirectory: filepath.Join(t.TempDir(), "state")}, p, "", 1, "unavailable") if err != nil { t.Fatal(err) } @@ -148,7 +148,7 @@ func TestDebugExecutableLookupSkipsNonFileCandidates(t *testing.T) { copyTestBinary(t, executable) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - plan, err := h.app.prepareDebugLaunch(ctx, debugStart{adapter: adapter, request: "launch"}, filepath.Join(t.TempDir(), "state"), p, "", 1, "unavailable") + plan, err := h.app.prepareDebugLaunch(ctx, debugStart{adapter: adapter, request: "launch"}, &debugSession{stateDirectory: filepath.Join(t.TempDir(), "state")}, p, "", 1, "unavailable") if err != nil { t.Fatal(err) } @@ -198,7 +198,7 @@ func TestDebugReadsProgramFromActualPluginSettingSources(t *testing.T) { } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - plan, err := h.app.prepareDebugLaunch(ctx, debugStart{adapter: adapter, request: "launch"}, filepath.Join(t.TempDir(), "state"), p, "", 1, "unavailable") + plan, err := h.app.prepareDebugLaunch(ctx, debugStart{adapter: adapter, request: "launch"}, &debugSession{stateDirectory: filepath.Join(t.TempDir(), "state")}, p, "", 1, "unavailable") if invalid { if err == nil { t.Fatalf("invalid configured program fell back: %+v", plan.Configuration) @@ -241,7 +241,7 @@ func TestDebugRequiredDirectoriesCreateStateAndLogSlots(t *testing.T) { stateRoot := filepath.Join(t.TempDir(), "state") ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - plan, err := h.app.prepareDebugLaunch(ctx, debugStart{adapter: adapter, request: "launch"}, stateRoot, p, "", 1, "unavailable") + plan, err := h.app.prepareDebugLaunch(ctx, debugStart{adapter: adapter, request: "launch"}, &debugSession{stateDirectory: stateRoot}, p, "", 1, "unavailable") if err != nil { t.Fatalf("prepareDebugLaunch failed for RequiredDirectories slots: %v", err) } diff --git a/desktop/internal/workbench/debug_remote_terminal.go b/desktop/internal/workbench/debug_remote_terminal.go new file mode 100644 index 0000000000..0dc9622a43 --- /dev/null +++ b/desktop/internal/workbench/debug_remote_terminal.go @@ -0,0 +1,76 @@ +package workbench + +import ( + "context" + "errors" + "path" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" +) + +// openRemoteDebugTerminal runs the already validated DAP command on the same +// attachment as its adapter. The session owns the terminal until it stops. +func (a *App) openRemoteDebugTerminal(p *project, session *debugSession, event core.DebugEvent) { + if a.project != p || !p.debug.hasSession(session) { + return + } + unavailable := i18n.Shared(a.language(), "desktop.debug.terminalUnavailable") + reply := func(pid int64, err error) { + if session.stopped.Load() || !p.debug.hasSession(session) { + return + } + var message string + if err != nil { + pid = 0 + message = err.Error() + if errors.Is(err, context.Canceled) { + message = unavailable + } + } + a.replyDebugReverseRequest(p, session, func(ctx context.Context) (core.DebugUpdate, error) { + return a.kernel.DebugRunInTerminalResponse(ctx, session.id, event.RequestID, pid, message) + }) + } + request := event.RunInTerminal + switch { + case p.remote == nil || request == nil || request.RemoteDirectory == nil || len(request.Args) == 0: + err := errors.New(unavailable) + a.operationFailed("debug_terminal", p.logError(err)) + reply(0, err) + return + case !session.connection.IsCurrent(): + a.operationFailed("debug_terminal", remoteLogError(errRemoteSessionClosed)) + reply(0, errors.New(a.text.Debug.ConnectionClosed)) + return + case !p.trust.allowed(): + err := remoteDebugUntrusted() + a.operationFailed("debug_terminal", remoteLogError(err)) + reply(0, errors.New(a.launchFailureText(err))) + return + } + overrides := make(map[string]*string, len(request.Environment)) + for _, entry := range request.Environment { + overrides[entry.Name] = entry.Value + } + env, unset := terminalEnvironment(overrides) + title := request.Title + if title == "" { + title = path.Base(request.Args[0]) + } + t := a.newTerminalWith(p, terminalOptions{ + shell: request.Args[0], args: request.Args[1:], env: env, unset: unset, + title: title, activate: true, + remoteDirectory: &core.RemoteScopedDirectory{Root: p.remote.binding.RemoteRoot(), Path: *request.RemoteDirectory}, + remoteConnection: session.connection, + remoteStartContext: session.ctx, + remoteStarted: reply, + }) + if t == nil { + // The failed terminal layout reduction has already been logged. + reply(0, errors.New(unavailable)) + return + } + session.remoteTerminals = append(session.remoteTerminals, t.id) + a.reduceChrome(core.SetChromeOpen(itemTerminal, true)) +} diff --git a/desktop/internal/workbench/debug_remote_terminal_test.go b/desktop/internal/workbench/debug_remote_terminal_test.go new file mode 100644 index 0000000000..ca80ddda59 --- /dev/null +++ b/desktop/internal/workbench/debug_remote_terminal_test.go @@ -0,0 +1,144 @@ +package workbench + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "slices" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +type debugTerminalReplies chan []byte + +func (output debugTerminalReplies) Write(data []byte) (int, error) { + select { + case output <- bytes.Clone(data): + return len(data), nil + default: + return 0, fmt.Errorf("the fixture did not consume the debug adapter's responses") + } +} + +func (debugTerminalReplies) Close() error { return nil } + +// Test the window side of the reverse request using the real DAP reply reducer. +// The remote Core test supplies the remoteDirectory projection and path validation. +func TestRemoteDebugTerminalRepliesWithHostPIDAndStopsWithSession(t *testing.T) { + h, k, _, _ := remoteWorkspaceHarness(t) + p := h.openRemoteTestProject(t) + p.trust.codeAllowed.Store(true) + connection, ok := captureWorkspaceConnection(p) + if !ok { + t.Fatal("the workspace did not connect") + } + ctx, cancel := context.WithCancel(p.ctx) + t.Cleanup(cancel) + startup := make(chan struct{}) + close(startup) + replies := make(debugTerminalReplies, 4) + session := &debugSession{ + id: "desktop-debug-remote-terminal-fixture", adapterID: "fixture", project: p, + ctx: ctx, cancel: cancel, startupDone: startup, created: true, connection: connection, + generation: p.debug.generation, transport: replies, + } + _, err := k.CreateDebugSession(core.WithoutRemoteWorkspace(ctx), core.DebugCreateSessionRequest{ + SessionID: session.id, AdapterID: session.adapterID, RootPath: p.root, SupportsRunInTerminalRequest: true, + }) + if err != nil { + t.Fatal(err) + } + p.debug.addSession(session) + + request := func(sequence int) { + t.Helper() + body := fmt.Sprintf(`{"seq":%d,"type":"request","command":"runInTerminal","arguments":`+ + `{"cwd":%q,"args":["/usr/bin/debuggee","a b","$(literal)"],"env":{"SET_ME":"value","DROP_ME":null},"title":"Fixture debuggee"}}`, + sequence, remoteTestFolder+"/src") + frame := fmt.Sprintf("Content-Length: %d\r\n\r\n%s", len(body), body) + update, err := k.ReceiveDebug(ctx, session.id, []byte(frame)) + if err != nil { + t.Fatal(err) + } + if len(update.Events) != 1 || update.Events[0].RunInTerminal == nil { + t.Fatalf("missing decoded reverse terminal request: %+v", update) + } + // The simulated host has no registered Core SSH transport. This is + // the only field added to the result Core would send on a real host. + directory := "src" + update.Events[0].RunInTerminal.RemoteDirectory = &directory + h.app.applyDebugUpdate(p, session, update) + } + type reply struct { + Sequence int `json:"request_seq"` + Command string `json:"command"` + Success bool `json:"success"` + Message string `json:"message"` + Body struct { + ProcessID int64 `json:"processId"` + } `json:"body"` + } + readReply := func(sequence int) reply { + t.Helper() + var data []byte + awaitStateWithin(t, h, 8*time.Second, "the debug adapter's terminal response", func() bool { + select { + case data = <-replies: + return true + default: + return false + } + }) + _, body, _ := bytes.Cut(data, []byte("\r\n\r\n")) + var response reply + if err := json.Unmarshal(body, &response); err != nil || response.Sequence != sequence || response.Command != "runInTerminal" { + t.Fatalf("unexpected debug adapter response %s: %v", body, err) + } + return response + } + + k.terminals.set(func(host *remoteHostTerminals) { + host.refuse = &core.Error{Code: core.CodeProcessFailed, Message: "fixture refused to start"} + }) + request(10) + if response := readReply(10); response.Success || response.Message != "fixture refused to start" { + t.Fatalf("failed terminal launch response = %+v", response) + } + + request(11) + if response := readReply(11); !response.Success || response.Body.ProcessID != remoteTestTerminalPID { + t.Fatalf("successful terminal launch response = %+v", response) + } + runs := k.terminals.started() + if len(runs) != 1 { + t.Fatalf("started host terminals = %d, want one", len(runs)) + } + run := runs[0] + if run.session != connection.SessionID() || run.open.ScopedCwd == nil || + *run.open.ScopedCwd != (core.RemoteScopedDirectory{Root: remoteTestFolder, Path: "src"}) || + !slices.Equal(run.open.Argv, []string{"/usr/bin/debuggee", "a b", "$(literal)"}) || + run.open.Environment != "login" || len(run.open.Env) != 1 || run.open.Env["SET_ME"] != "value" || + !slices.Equal(run.open.UnsetEnv, []string{"DROP_ME"}) { + t.Fatalf("terminal opened on %q with %+v", run.session, run.open) + } + if len(session.remoteTerminals) != 2 { + t.Fatalf("session owns terminal tabs %v, want both launch attempts", session.remoteTerminals) + } + term := p.terms.find(session.remoteTerminals[1]) + h.awaitTerminal(term, remoteHostPrompt) + h.app.stopDebug(p) + k.terminals.await(t, "the debuggee's terminal to stop", func() bool { + select { + case <-run.ended: + return true + default: + return false + } + }) + if p.terms.find(term.id) != nil { + t.Fatal("the debug session left its terminal tab behind") + } +} diff --git a/desktop/internal/workbench/debug_remote_transport.go b/desktop/internal/workbench/debug_remote_transport.go new file mode 100644 index 0000000000..087ef0454f --- /dev/null +++ b/desktop/internal/workbench/debug_remote_transport.go @@ -0,0 +1,207 @@ +package workbench + +import ( + "context" + "errors" + "io" + "sync" + + "github.com/1lck/Lithe-IDEA/desktop/internal/buildprocess" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" +) + +func remoteDebugUntrusted() error { + return &core.MarketplaceRejection{Code: core.LaunchUntrustedWorkspace} +} + +type debugForward struct { + host string + port int + release func(context.Context) error +} + +func (a *App) forwardDebugEndpoint(ctx context.Context, connection *core.RemoteWorkspaceConnection, host string, port int, confirmed bool) (debugForward, error) { + sessionID := connection.SessionID() + if sessionID == "" { + return debugForward{}, errRemoteSessionClosed + } + forward, created, err := a.kernel.RemoteStartForward(ctx, sessionID, core.RemoteForwardTarget{ + Host: host, Port: uint16(port), AllowNonLoopback: confirmed, + }) + if err != nil { + return debugForward{}, err + } + local := debugForward{host: forward.LocalHost, port: int(forward.LocalPort)} + if created { + local.release = func(ctx context.Context) error { + // A resumed attachment can have the same session ID. IDs for + // this forward stay owned by that original Core session. + _, err := a.kernel.RemoteStopForward(ctx, sessionID, forward.ID) + // log-exempt: 预期的缺失:会话已关闭时,Core 已回收它的转发。 + if remoteConnectionClosed(err) { + return nil + } + return err + } + } + return local, nil +} + +// remoteDebugStream bridges the process events and input requests of one +// captured workspace attachment. The event callback cannot wait for DAP to +// respond, since it runs inside a Core call. +type remoteDebugStream struct { + kernel Kernel + ctx context.Context + cancel context.CancelFunc + process *buildprocess.RemoteProcess + output chan []byte + done chan struct{} + err error + pending []byte + mu sync.Mutex + queued int + full bool +} + +func (a *App) startRemoteAnnouncedAdapter(ctx context.Context, p *project, session *debugSession, prepared preparedDebugLaunch, observe func(buildprocess.Stream, string), unreached error) error { + if !p.trust.allowed() { + return remoteDebugUntrusted() + } + startup, cancel := context.WithTimeout(ctx, debugOperationTimeout) + defer cancel() + process, err := buildprocess.StartRemote(startup, context.WithoutCancel(ctx), a.kernel, remoteDebugProcessSpec(p, prepared, false), observe) + if err != nil { + return err + } + done := make(chan struct{}) + // The process stays alive through transport shutdown so Stop can flush DAP disconnect. + session.waitRemoteAdapter = func() { + process.Stop() + <-done + } + go func() { + defer close(done) + a.debugAdapterProcessExited(p, session, process.Wait(), unreached) + }() + return nil +} + +func (a *App) openRemoteDebugTransport(p *project, session *debugSession, prepared preparedDebugLaunch, policy core.DebugTransportPolicy, messages i18n.DebugMessages) error { + hooks := a.debugStreamHooks(p, session, messages) + hooks.OpenStream = func(wait context.Context) (io.ReadWriteCloser, error) { + if !p.trust.allowed() { + return nil, remoteDebugUntrusted() + } + ctx, cancel := context.WithCancel(context.WithoutCancel(session.ctx)) + stop := context.AfterFunc(wait, cancel) + stream := &remoteDebugStream{ + kernel: a.kernel, ctx: ctx, cancel: cancel, + output: make(chan []byte, policy.Limits.BufferedWrites), + done: make(chan struct{}), + } + process, err := buildprocess.StartRemoteBytes(ctx, ctx, a.kernel, remoteDebugProcessSpec(p, prepared, true), func(name string, data []byte) { + if name == "stderr" { + text := string(data) + a.post(func(a *App) { a.appendDebugOutput(p, session, text) }) + return + } + stream.enqueue(data, policy.Limits.BufferedBytes) + }) + if err != nil { + stop() + cancel() + if stream.full { + err = errors.New(messages.BufferLimit) + } + return nil, err + } + stream.process = process + session.waitRemoteAdapter = func() { <-stream.done } + go func() { + defer stop() + defer close(stream.done) + err := process.Wait() + if stream.full { + err = errors.New(messages.BufferLimit) + } + stream.err = err + close(stream.output) + }() + return stream, nil + } + transport := newDebugTransport(a.kernel, session.id+"-transport", hooks) + if !session.setTransport(transport) { + return context.Canceled + } + session.hosted = transport + return transport.Start(nil) +} + +func remoteDebugProcessSpec(p *project, prepared preparedDebugLaunch, stdio bool) core.RemoteProcessOpen { + return core.RemoteProcessOpen{ + Argv: append([]string{prepared.Executable}, prepared.Arguments...), + ScopedCwd: &core.RemoteScopedDirectory{Root: p.remote.binding.RemoteRoot()}, + Environment: "login", + Env: prepared.Environment, + PathPrepend: prepared.RemotePathPrepend, + PipeStdin: stdio, + Label: core.NewRemoteResourceLabel("debug", prepared.Configuration.Name), + } +} + +func (s *remoteDebugStream) enqueue(data []byte, byteLimit int) { + if len(data) == 0 { + return + } + s.mu.Lock() + defer s.mu.Unlock() + if !s.full && len(data) <= byteLimit-s.queued { + select { + case s.output <- data: + s.queued += len(data) + return + default: + } + } + s.full = true + s.cancel() +} + +func (s *remoteDebugStream) Read(buffer []byte) (int, error) { + if len(s.pending) == 0 { + data, ok := <-s.output + if !ok { + if s.err != nil { + return 0, s.err + } + return 0, io.EOF + } + s.pending = data + } + count := copy(buffer, s.pending) + s.pending = s.pending[count:] + s.mu.Lock() + s.queued -= count + s.mu.Unlock() + return count, nil +} + +func (s *remoteDebugStream) Write(frame []byte) (int, error) { + var written int + for len(frame) > 0 { + chunk := frame[:min(len(frame), debugReadChunk)] + if err := s.kernel.WriteRemoteProcessInput(s.ctx, s.process.ID, chunk); err != nil { + return written, err + } + written += len(chunk) + frame = frame[len(chunk):] + } + return written, nil +} + +func (s *remoteDebugStream) Close() error { + s.cancel() + return nil +} diff --git a/desktop/internal/workbench/debug_start.go b/desktop/internal/workbench/debug_start.go index f55172e1b9..84041af55c 100644 --- a/desktop/internal/workbench/debug_start.go +++ b/desktop/internal/workbench/debug_start.go @@ -46,6 +46,8 @@ type debugStart struct { target *core.DebugTargetFacts // confirmed records that the user accepted a non-local endpoint. confirmed bool + // connection stays fixed even while an attach waits for confirmation. + connection *core.RemoteWorkspaceConnection // configuration is the plugin backend's DAP launch or attach arguments, set // when a backend started the session through debug/start. They apply on top // of the adapter's declared arguments and no file or connection is planned. @@ -145,8 +147,13 @@ func (a *App) saveAndBeginDebug(p *project, start debugStart) { a.beginDebug(p, start) return } + connection, connected := captureWorkspaceConnection(p) + if !connected { + return + } + start.connection = connection a.saveProjectDocuments(p, func(ok bool) { - if ok { + if ok && (connection == nil || connection.IsCurrent()) { a.beginDebug(p, start) } }) @@ -219,6 +226,7 @@ func (a *App) attachDebugForRun(ctx context.Context, request pluginservice.RunDe err error } result := make(chan outcome, 1) + var started *debugSession a.post(func(a *App) { p := a.project if p == nil || filepath.Clean(p.root) != filepath.Clean(request.WorkspaceRoot) { @@ -245,16 +253,17 @@ func (a *App) attachDebugForRun(ctx context.Context, request pluginservice.RunDe a.performed("debug.start", surfacePlugin) a.beginDebug(p, debugStart{ adapter: adapter, request: "attach", confirmed: true, - target: &core.DebugTargetFacts{Kind: "connection", Host: request.Host, Port: request.Port}, - stopRun: request.StopRun, + target: &core.DebugTargetFacts{Kind: "connection", Host: request.Host, Port: request.Port}, + stopRun: request.StopRun, + connection: request.Connection, }) - session := p.debug.activeSession() - if session == nil { + started = p.debug.activeSession() + if started == nil { result <- outcome{err: errors.New("the debug session did not start")} return } a.openToolWindow(itemDebug) - result <- outcome{id: session.id} + result <- outcome{id: started.id} return } } @@ -265,6 +274,7 @@ func (a *App) attachDebugForRun(ctx context.Context, request pluginservice.RunDe case r := <-result: return r.id, r.err case <-ctx.Done(): + a.post(func(a *App) { a.cancelPendingRunDebug(started) }) return "", ctx.Err() } } @@ -279,6 +289,7 @@ func (a *App) launchDebugForRun(ctx context.Context, request pluginservice.RunDe err error } result := make(chan outcome, 1) + var started *debugSession a.post(func(a *App) { p := a.project if p == nil || filepath.Clean(p.root) != filepath.Clean(request.WorkspaceRoot) { @@ -310,17 +321,18 @@ func (a *App) launchDebugForRun(ctx context.Context, request pluginservice.RunDe } a.performed("debug.start", surfacePlugin) a.beginDebug(p, debugStart{ - adapter: adapter, request: "launch", ended: ended, + adapter: adapter, request: "launch", ended: ended, connection: request.Connection, launchTarget: &core.DebugTargetFacts{ Kind: "executable", Path: request.Executable, Executable: request.Executable, WorkingDirectory: request.WorkingDirectory, Arguments: arguments, Environment: environment, }, }) - if p.debug.activeSession() == nil || p.debug.activeSession().ended != ended { + started = p.debug.activeSession() + if started == nil || started.ended != ended { result <- outcome{err: fmt.Errorf("the debug session did not start: %s", p.debug.failure)} return } - result <- outcome{session: pluginservice.RunDebugSession{ID: p.debug.activeSession().id, Ended: ended}} + result <- outcome{session: pluginservice.RunDebugSession{ID: started.id, Ended: ended}} return } result <- outcome{err: fmt.Errorf("no debug adapter launches %q", request.ConfigurationType)} @@ -330,10 +342,18 @@ func (a *App) launchDebugForRun(ctx context.Context, request pluginservice.RunDe case r := <-result: return r.session, r.err case <-ctx.Done(): + a.post(func(a *App) { a.cancelPendingRunDebug(started) }) return pluginservice.RunDebugSession{}, ctx.Err() } } +// cancelPendingRunDebug cleans up a session created just as its caller cancelled the request. +func (a *App) cancelPendingRunDebug(session *debugSession) { + if session != nil && a.project == session.project && session.project.debug.activeSession() == session { + a.stopDebugByUser(session.project) + } +} + // startDebugForBackend starts the plugin's own adapter for a backend's // debug/start. It runs on a background goroutine, asks the window thread to // create the session and returns its ID. The workspace must be the open project @@ -357,12 +377,16 @@ func (a *App) startDebugForBackend(ctx context.Context, request pluginservice.De result <- outcome{err: errors.New("a debug session is already running")} return } + if err := ctx.Err(); err != nil { + result <- outcome{err: err} + return + } for _, adapter := range p.debug.adapters { if adapter.PluginID+"/"+adapter.Declaration.ID != request.AdapterID { continue } a.performed("debug.start", surfacePlugin) - a.beginDebug(p, debugStart{adapter: adapter, request: request.Request, confirmed: true, configuration: request.Configuration}) + a.beginDebug(p, debugStart{adapter: adapter, request: request.Request, configuration: request.Configuration, connection: request.Connection}) if p.debug.activeSession() == nil { result <- outcome{err: errors.New("the debug session could not start")} return @@ -402,6 +426,22 @@ func (a *App) beginDebug(p *project, start debugStart) { if suppressed { return } + if p.remote != nil { + connection, connected := captureWorkspaceConnection(p) + if !connected || (start.connection != nil && !start.connection.SameAttachment(connection)) { + err := errRemoteSessionClosed + a.operationFailed("debug", err) + p.debug.failure = a.text.Debug.ConnectionClosed + return + } + if !p.trust.allowed() { + err := remoteDebugUntrusted() + a.operationFailed("debug", err) + p.debug.failure = a.launchFailureText(err) + return + } + start.connection = connection + } targetPath := start.targetPath if doc := p.selectedDocument(p.docs.group); targetPath == "" && doc != nil { targetPath = doc.path @@ -442,7 +482,7 @@ func (a *App) beginDebug(p *project, start debugStart) { for path, lines := range p.debug.breakpoints { breakpoints[path] = append([]debugBreakpoint(nil), lines...) } - ctx, cancel := context.WithCancel(p.ctx) + ctx, cancel := context.WithCancel(attachedWorkspaceContext(p.ctx, start.connection)) id := fmt.Sprintf("desktop-debug-%d", debugSessionSequence.Add(1)) session := &debugSession{ id: id, @@ -458,6 +498,7 @@ func (a *App) beginDebug(p *project, start debugStart) { adapter: adapter, parent: start.parent, startRequestID: start.startRequestID, + connection: start.connection, // The debug session ID is the start's operation ID, so its result sits with the // session's own debug records. adapterStart: core.StartPluginAttempt(adapter.PluginID, core.OperationDebugAdapterStart, id), @@ -472,7 +513,7 @@ func (a *App) beginDebug(p *project, start debugStart) { // Only a stdio adapter is written through its standard input; the other // transports are written through their TCP stream. var stdinReader *os.File - if !hosted && !announced { + if start.connection == nil && !hosted && !announced { reader, writer, err := os.Pipe() if err != nil { cancel() @@ -500,6 +541,12 @@ func (a *App) beginDebug(p *project, start debugStart) { // Instruction addresses are valid for one run of one process: the set is not replayed. p.debug.instructionBreakpoints = nil p.debug.hideFiltered = hideFiltered + if start.connection != nil { + stopDetach := start.connection.AfterDetach(func() { + a.post(func(a *App) { a.finishDebugError(p, session, errRemoteSessionClosed) }) + }) + context.AfterFunc(ctx, func() { stopDetach() }) + } a.background(p, 0, func(_ context.Context) func(*App) { session.operationMu.Lock() @@ -524,8 +571,12 @@ func (a *App) beginDebug(p *project, start debugStart) { } // Assigned only by startup; cleanup reads it after startupDone closes. session.stateDirectory = stateDirectory - preparationContext, cancelPreparation := context.WithTimeout(ctx, debugOperationTimeout) - prepared, err := a.prepareDebugLaunch(preparationContext, start, session.stateDirectory, p, targetPath, generation, targetUnavailable) + preparationTimeout := debugOperationTimeout + if start.connection != nil && !hosted { + preparationTimeout = pluginPrepareTimeout + } + preparationContext, cancelPreparation := context.WithTimeout(ctx, preparationTimeout) + prepared, err := a.prepareDebugLaunch(preparationContext, start, session, p, targetPath, generation, targetUnavailable) if err != nil { // Only the adapter's own launch is the plugin's start; a debuggee that cannot be // found or a remote endpoint waiting for the user is not. The preparation's @@ -554,14 +605,34 @@ func (a *App) beginDebug(p *project, start debugStart) { a.recordDebugStart(ctx, session, core.StageLaunch, err) return func(a *App) { a.finishDebugError(p, session, err) } } - } else if err := a.startAdapterProcess(ctx, p, session, prepared, stdinReader, a.stdioDebugOutput(p, session), nil); err != nil { - a.recordDebugStart(ctx, session, core.StageLaunch, err) - return func(a *App) { a.finishDebugError(p, session, err) } + } else if prepared.RemoteAdapter { + if err := a.openRemoteDebugTransport(p, session, prepared, policy, messages); err != nil { + a.recordDebugStart(ctx, session, core.StageLaunch, err) + return func(a *App) { a.finishDebugError(p, session, err) } + } + } else { + if stdinReader == nil { + reader, writer, err := os.Pipe() + if err != nil { + a.recordDebugStart(ctx, session, core.StageLaunch, err) + return func(a *App) { a.finishDebugError(p, session, err) } + } + defer reader.Close() + if !session.setTransport(writer) { + return nil + } + stdinReader = reader + } + if err := a.startAdapterProcess(ctx, p, session, prepared, stdinReader, a.stdioDebugOutput(p, session), nil); err != nil { + a.recordDebugStart(ctx, session, core.StageLaunch, err) + return func(a *App) { a.finishDebugError(p, session, err) } + } } update, err := a.kernel.CreateDebugSession(ctx, core.DebugCreateSessionRequest{ SessionID: session.id, AdapterID: session.adapterID, RootPath: p.root, + SupportsRunInTerminalRequest: prepared.RemoteAdapter && !hosted && !announced, SupportsStartDebuggingRequest: true, ParentSessionID: parentSessionID, DisabledCapabilities: prepared.DisabledCapabilities, @@ -698,6 +769,9 @@ func (a *App) startAdapterProcess(ctx context.Context, p *project, session *debu Environment: prepared.Environment, WorkingDirectory: p.root, } + if session.connection != nil { + spec.WorkingDirectory = session.stateDirectory + } processContext := context.WithoutCancel(ctx) if stdin != nil { // A nil *os.File would be a non-nil reader, so the field is set only here. @@ -718,29 +792,33 @@ func (a *App) startAdapterProcess(ctx context.Context, p *project, session *debu // Observe native exit even when the adapter cannot send a DAP terminated event. go func() { defer close(session.exitObserved) - err := process.Wait() - // An exit before initialize was answered ends the start, whatever its status. It is - // read before the session's context ends, which would make it a stop by the user. - stage := core.StageExit - if !session.reached.Load() { - stage = core.StageLaunch - } - a.recordDebugStart(session.ctx, session, stage, errDebugAdapterExited) - session.cancel() - session.closeTransport() - if err == nil && !session.reached.Load() { - // A tcpAnnounced adapter that ends before its stream connected never - // served the session, whatever its exit status. - err = session.recordedFailure() - if err == nil { - err = unreached - } - } - a.debugStreamEnded(p, session, err) + a.debugAdapterProcessExited(p, session, process.Wait(), unreached) }() return nil } +func (a *App) debugAdapterProcessExited(p *project, session *debugSession, err, unreached error) { + if session.stopped.Load() { + return + } + // An exit before initialize was answered ends the start, whatever its status. + reached := session.reached.Load() + stage := core.StageExit + if !reached { + stage = core.StageLaunch + } + a.recordDebugStart(session.ctx, session, stage, errDebugAdapterExited) + session.cancel() + session.closeTransport() + if err == nil && !reached { + err = session.recordedFailure() + if err == nil { + err = unreached + } + } + a.debugStreamEnded(p, session, err) +} + // debugStreamEnded finishes a session whose adapter process or stream ended on // its own. A clean end is a terminated session; anything else is a failure. func (a *App) debugStreamEnded(p *project, session *debugSession, err error) { diff --git a/desktop/internal/workbench/debug_stdio_ssh_test.go b/desktop/internal/workbench/debug_stdio_ssh_test.go new file mode 100644 index 0000000000..ef50ac0e0f --- /dev/null +++ b/desktop/internal/workbench/debug_stdio_ssh_test.go @@ -0,0 +1,133 @@ +//go:build lithe_remote_e2e && (darwin || windows) + +package workbench + +import ( + "context" + "crypto/sha256" + "fmt" + "os" + "path" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteplaceholder" +) + +func TestRemoteStdioDebugAdapterMapsWorkspaceBreakpointsOverSSH(t *testing.T) { + host := os.Getenv("LITHE_TEST_VARIANT_SSH_HOST") + if host == "" { + t.Skip("set LITHE_TEST_VARIANT_SSH_HOST to a disposable Linux OpenSSH target") + } + client := core.NewClient() + connection, connected := connectVariantSSH(t, client, host) + arch := linuxSSHFixtureArch(t, connected) + platform := connected.Host.PluginPlatform() + fixture := buildLinuxSSHFixtureFor(t, "stdio-adapter", "./testdata/remote_debug_adapter", arch) + manifest := strings.Replace(debugFixtureManifest, `{"kind": "packaged", "path": "adapter"}`, `{"kind": "systemCommand", "commands": ["sh"]}`, 1) + manifest = strings.Replace(manifest, `["-test.run=^TestDebugAdapterRunner$"]`, `["-c", "exec ./stdio-adapter"]`, 1) + const pluginID = "dev.lithe.test.debug-adapter" + options := debugPluginOptions(t, pluginID, manifest, false, client, "dark") + options.Kernel = &testKernel{Client: client} + h := newHarnessWithOptions(t, options) + + const directoryID = "debug-stdio" + sessionID := connected.Session.ID + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + var directory struct{ Path string } + if err := client.RemoteHostRequest(ctx, sessionID, "fs.createRunDirectory", map[string]string{"directoryId": directoryID}, &directory); err != nil { + t.Fatalf("create remote fixture directory: %v", err) + } + t.Cleanup(func() { + cleanup, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := client.RemoteHostRequest(cleanup, sessionID, "fs.releaseRunDirectory", map[string]string{"directoryId": directoryID}, nil); err != nil && !remoteConnectionClosed(err) { + t.Errorf("release remote fixture directory: %v", err) + } + }) + for _, name := range []string{"source.txt", "other.txt"} { + if _, saved, err := client.RemoteWriteFile(ctx, sessionID, path.Join(directory.Path, name), []byte("one\ntwo\nthree\n"), nil); err != nil || !saved { + t.Fatalf("write remote %s: saved=%v, err=%v", name, saved, err) + } + } + anchor := filepath.Join(t.TempDir(), remoteplaceholder.AnchorName) + if err := remoteplaceholder.Ensure(anchor); err != nil { + t.Fatal(err) + } + const connectionID = "debug-stdio-ssh" + root := remoteplaceholder.Root(anchor, connectionID, directory.Path) + h.app.openRemoteProject(remoteTarget{ + connectionID: connectionID, name: "Stdio adapter SSH test", host: connection, + session: *connected.Session, platform: platform, remoteRoot: directory.Path, root: root, trusted: true, + }) + p := h.app.project + if p == nil || p.remote == nil { + t.Fatal("the SSH project did not open") + } + attachment := p.remote.binding.CaptureConnection() + if attachment == nil { + t.Fatal("the SSH project has no active connection") + } + data, err := os.ReadFile(fixture) + if err != nil { + t.Fatal(err) + } + if err := client.UploadRemotePluginFile(attachment.Context(ctx), fixture, path.Join(directory.Path, "stdio-adapter"), fmt.Sprintf("%x", sha256.Sum256(data)), 0o500); err != nil { + t.Fatalf("upload remote adapter: %v", err) + } + source, other := filepath.Join(root, "source.txt"), filepath.Join(root, "other.txt") + openSource(t, h, p, source) + h.app.chooseTitleConfiguration(p, "") + h.app.toggleBreakpointAt(p, source, 3) + h.click(center(h.button(itemTitleDebug))) + awaitStateWithin(t, h, 20*time.Second, "a stopped event and stack trace over stdio", func() bool { + if notice := lastNotice(h); notice == i18n.Shared(h.app.language(), "desktop.remote.workspace.localOnly") { + t.Fatalf("toolbar Debug rejected the remote workspace: %s", notice) + } + if p.debug.failure != "" { + t.Fatalf("remote stdio adapter failed: %s\noutput: %q", p.debug.failure, p.debug.output) + } + return p.debug.state == "paused" && len(p.debug.frames) > 0 + }) + if frame := p.debug.frames[0]; frame.Name != "fixture-linux" || frame.SourcePath != source || frame.Line != 3 { + t.Fatalf("stack frame = %+v, want the remote adapter's mapped source and line", frame) + } + h.app.openFileAt(p, other, 1) + awaitStateWithin(t, h, 10*time.Second, "the remote editor and thread picker", func() bool { + doc := p.selectedDocument(p.docs.group) + return doc != nil && doc.path == other && len(p.debug.threads) > 0 + }) + if err := h.driver.Pump(); err != nil { + t.Fatal(err) + } + point := center(h.pageHit("fixture-linux").Bounds) + if err := h.driver.Click(point.X, point.Y); err != nil { + t.Fatal(err) + } + awaitStateWithin(t, h, 10*time.Second, "the selected remote stack frame to open the source", func() bool { + if p.debug.failure != "" { + t.Fatalf("remote stdio adapter failed while opening the stack frame: %s", p.debug.failure) + } + doc := p.selectedDocument(p.docs.group) + return doc != nil && doc.path == source + }) + if line, column := p.selectedDocument(p.docs.group).view.Caret(); line != 2 || column != 0 { + t.Fatalf("source opened at line %d, column %d; want line 3, column 1", line+1, column+1) + } + session := p.debug.activeSession() + h.app.stopDebugByUser(p) + awaitValueWithin(t, h, 10*time.Second, session.cleanupDone, "the stdio adapter process to exit") + if session.cleanupErr != nil || p.debug.activeSession() != nil { + t.Fatalf("the stdio adapter did not stop cleanly: %v", session.cleanupErr) + } + check, cancelCheck := context.WithTimeout(context.Background(), 5*time.Second) + defer cancelCheck() + if forwards, err := client.RemoteForwards(check, sessionID); err != nil || len(forwards) != 0 { + t.Fatalf("stdio adapter used a port forward: forwards=%+v, err=%v", forwards, err) + } +} diff --git a/desktop/internal/workbench/debug_transport.go b/desktop/internal/workbench/debug_transport.go index d6b4935e51..d6800a0a83 100644 --- a/desktop/internal/workbench/debug_transport.go +++ b/desktop/internal/workbench/debug_transport.go @@ -33,6 +33,8 @@ type debugTransportHooks struct { Discover func(ctx context.Context) (host string, port int, err error) // Dial opens the socket; nil dials TCP. Dial func(ctx context.Context, host string, port int) (net.Conn, error) + // OpenStream opens a process byte stream without a TCP endpoint. + OpenStream func(ctx context.Context) (io.ReadWriteCloser, error) // Connected, when set, runs once Core took the socket as ready, before anything is read // from it. Connected func() @@ -70,7 +72,7 @@ type debugTransport struct { mu sync.Mutex generation uint64 queue [][]byte - conn net.Conn + conn io.ReadWriteCloser timers map[uint64]*time.Timer released bool } @@ -88,7 +90,9 @@ func (t *debugTransport) Done() <-chan struct{} { return t.done } // Start begins the lifecycle: Core arms the discovery deadline and asks for the // endpoint. Frames written before the socket is ready are queued by Core's rule. func (t *debugTransport) Start(limits *core.DebugTransportLimitOverrides) error { - _, err := t.apply(core.DebugTransportEvent{Type: "start", Limits: limits}, nil, nil) + _, err := t.apply(core.DebugTransportEvent{ + Type: "start", Limits: limits, DirectStream: t.hooks.OpenStream != nil, + }, nil, nil) return err } @@ -232,6 +236,12 @@ func (t *debugTransport) runLocked(step core.DebugTransportStep, data []byte, ow host, port := effect.Host, effect.Port wait := t.wait t.spawn(func() { t.connect(wait, generation, host, port) }) + case "openStream": + wait := t.wait + t.spawn(func() { + stream, err := t.hooks.OpenStream(wait) + t.acceptStream(wait, generation, stream, err) + }) case "write": if len(t.queue) == 0 { continue @@ -296,20 +306,25 @@ func (t *debugTransport) discover(wait context.Context, generation uint64) { func (t *debugTransport) connect(wait context.Context, generation uint64, host string, port int) { dial := t.hooks.Dial if dial == nil { - dial = func(ctx context.Context, host string, port int) (net.Conn, error) { - var dialer net.Dialer - return dialer.DialContext(ctx, "tcp", net.JoinHostPort(host, strconv.Itoa(port))) - } + dial = dialDebugTCP } conn, err := dial(wait, host, port) - if wait.Err() != nil { + t.acceptStream(wait, generation, conn, err) +} + +func dialDebugTCP(ctx context.Context, host string, port int) (net.Conn, error) { + var dialer net.Dialer + return dialer.DialContext(ctx, "tcp", net.JoinHostPort(host, strconv.Itoa(port))) +} + +func (t *debugTransport) acceptStream(wait context.Context, generation uint64, conn io.ReadWriteCloser, err error) { + if wait.Err() != nil || err != nil { if conn != nil { _ = conn.Close() } - return - } - if err != nil { - t.failed(generation, err) + if wait.Err() == nil { + t.failed(generation, err) + } return } t.mu.Lock() @@ -325,14 +340,17 @@ func (t *debugTransport) connect(wait context.Context, generation uint64, host s if err != nil { return } - if step.Phase == "ready" && t.hooks.Connected != nil { + if step.Phase != "ready" || step.Outcome != "applied" { + return + } + if t.hooks.Connected != nil { t.hooks.Connected() } t.read(generation, conn) } // read reports every chunk to Core and forwards it only when Core says so. -func (t *debugTransport) read(generation uint64, conn net.Conn) { +func (t *debugTransport) read(generation uint64, conn io.Reader) { buffer := make([]byte, debugReadChunk) for { count, err := conn.Read(buffer) @@ -352,7 +370,7 @@ func (t *debugTransport) read(generation uint64, conn net.Conn) { } } -func (t *debugTransport) writeFrame(generation, writeID uint64, conn net.Conn, frame []byte) { +func (t *debugTransport) writeFrame(generation, writeID uint64, conn io.Writer, frame []byte) { if conn == nil { t.failed(generation, errDebugTransportNotRunning) return diff --git a/desktop/internal/workbench/debug_tunnel_ssh_test.go b/desktop/internal/workbench/debug_tunnel_ssh_test.go new file mode 100644 index 0000000000..bffc7102fe --- /dev/null +++ b/desktop/internal/workbench/debug_tunnel_ssh_test.go @@ -0,0 +1,389 @@ +//go:build lithe_remote_e2e && (darwin || windows) + +package workbench + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "io" + "net" + "os" + "path" + "path/filepath" + "slices" + "strconv" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/buildprocess" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteplaceholder" +) + +// The copied adapter must receive the challenge response from the Linux host +// before it reports a successful attach and a stopped thread. +func TestSSHTunnelDebugAdapterRunner(t *testing.T) { + if len(os.Args) == 0 || os.Args[len(os.Args)-1] != "lithe-ssh-tunnel-adapter" { + t.Skip("only the SSH attach fixture runs this adapter") + } + os.Exit(serveFixtureAdapterWithAttach(os.Stdin, os.Stdout, ".", func(raw json.RawMessage) error { + var endpoint struct { + Host string `json:"hostName"` + Port int `json:"port"` + } + if err := json.Unmarshal(raw, &endpoint); err != nil { + return err + } + if endpoint.Host != "127.0.0.1" || endpoint.Port < 1 { + return fmt.Errorf("unexpected forwarded endpoint: %s:%d", endpoint.Host, endpoint.Port) + } + address := net.JoinHostPort(endpoint.Host, strconv.Itoa(endpoint.Port)) + conn, err := net.DialTimeout("tcp", address, 5*time.Second) + if err != nil { + return err + } + defer conn.Close() + if err := conn.SetDeadline(time.Now().Add(5 * time.Second)); err != nil { + return err + } + if _, err := io.WriteString(conn, "lithe"); err != nil { + return err + } + response := make([]byte, len("linux")) + if _, err := io.ReadFull(conn, response); err != nil { + return err + } + if string(response) != "linux" { + return fmt.Errorf("unexpected remote response %q", response) + } + return nil + })) +} + +func TestLocalDebugAdapterAttachesThroughSSHWorkspaceTunnel(t *testing.T) { + host := os.Getenv("LITHE_TEST_VARIANT_SSH_HOST") + if host == "" { + t.Skip("set LITHE_TEST_VARIANT_SSH_HOST to a disposable Linux OpenSSH target") + } + const pluginID = "dev.lithe.test.debug-attach" + manifest := strings.Replace(debugAttachManifest, `"process": {"launch":`, `"process": {"placement": "ui", "launch":`, 1) + manifest = strings.Replace(manifest, `"-test.run=^TestDebugAdapterRunner$"`, `"-test.run=^TestSSHTunnelDebugAdapterRunner$", "--", "lithe-ssh-tunnel-adapter"`, 1) + client := core.NewClient() + connection, connected := connectVariantSSH(t, client, host) + arch := linuxSSHFixtureArch(t, connected) + fixture := buildLinuxSSHFixtureFor(t, "debuggee", "./testdata/remote_debuggee", arch) + options := debugPluginOptions(t, pluginID, manifest, true, client, "dark") + options.Kernel = &testKernel{Client: client} + h := newHarnessWithOptions(t, options) + sessionID := connected.Session.ID + const directoryID = "debug-tunnel" + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + var directory struct { + Path string `json:"path"` + } + err := client.RemoteHostRequest(ctx, sessionID, "fs.createRunDirectory", map[string]string{"directoryId": directoryID}, &directory) + cancel() + if err == nil { + t.Cleanup(func() { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := client.RemoteHostRequest(ctx, sessionID, "fs.releaseRunDirectory", map[string]string{"directoryId": directoryID}, nil); err != nil { + t.Errorf("release remote fixture directory: %v", err) + } + }) + } + if err != nil || !path.IsAbs(directory.Path) { + t.Fatalf("create remote fixture directory: path=%q, err=%v", directory.Path, err) + } + anchor := filepath.Join(t.TempDir(), remoteplaceholder.AnchorName) + if err := remoteplaceholder.Ensure(anchor); err != nil { + t.Fatal(err) + } + const connectionID = "debug-tunnel-ssh" + root := remoteplaceholder.Root(anchor, connectionID, directory.Path) + h.app.openRemoteProject(remoteTarget{ + connectionID: connectionID, name: "Debug tunnel SSH test", host: connection, + session: *connected.Session, platform: connected.Host.PluginPlatform(), remoteRoot: directory.Path, root: root, trusted: true, + }) + p := h.app.project + if p == nil || p.remote == nil { + t.Fatal("the SSH project did not open") + } + attachment := p.remote.binding.CaptureConnection() + if attachment == nil { + t.Fatal("the SSH project has no active connection") + } + remoteContext := attachment.Context(p.ctx) + data, err := os.ReadFile(fixture) + if err != nil { + t.Fatal(err) + } + remoteFixture := path.Join(directory.Path, "debuggee") + ctx, cancel = context.WithTimeout(remoteContext, 20*time.Second) + err = client.UploadRemotePluginFile(ctx, fixture, remoteFixture, fmt.Sprintf("%x", sha256.Sum256(data)), 0o500) + cancel() + if err != nil { + t.Fatalf("upload remote debuggee: %v", err) + } + remotePort, exit := startSSHTunnelDebuggee(t, client, remoteContext, directory.Path, remoteFixture) + gate := &captureDebugLaunch{Kernel: h.app.kernel, configurations: make(chan core.DebugLaunchConfiguration, 1)} + h.app.kernel = gate + h.app.reduceChrome(core.ToggleChrome(itemDebug)) + awaitStateWithin(t, h, 10*time.Second, "the attach adapter", func() bool { return len(p.debug.adapters) == 1 }) + h.app.debugAttach.host.SetText("127.0.0.1") + h.app.debugAttach.port.SetText(strconv.Itoa(remotePort)) + h.app.startDebug(p) + awaitRemotePrompt(t, h, p) + if len(gate.configurations) != 0 || p.debug.activeSession() != nil { + t.Fatal("the adapter started before approval") + } + ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second) + forwards, err := client.RemoteForwards(ctx, sessionID) + cancel() + if err != nil || len(forwards) != 0 { + t.Fatalf("before approval got forwards %+v, err=%v", forwards, err) + } + h.clickNamed(h.app.text.Debug.RemoteAttach) + configuration := awaitValueWithin(t, h, 20*time.Second, gate.configurations, "the forwarded attach") + ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second) + forwards, err = client.RemoteForwards(ctx, sessionID) + cancel() + if err != nil || len(forwards) != 1 { + t.Fatalf("after approval got forwards %+v, err=%v", forwards, err) + } + forward := forwards[0] + if int(forward.TargetPort) != remotePort || configuration.Request != "attach" || + configuration.Arguments["hostName"] != forward.LocalHost || !sameDebugPort(configuration.Arguments["port"], int(forward.LocalPort)) { + t.Fatalf("attach configuration %+v does not use the forward %+v", configuration, forward) + } + awaitStateWithin(t, h, 15*time.Second, "the adapter to receive the remote response", func() bool { + if p.debug.failure != "" { + t.Fatalf("attach failed: %s", p.debug.failure) + } + return p.debug.state == "paused" + }) + if err := awaitValueWithin(t, h, 5*time.Second, exit, "the remote debuggee to verify its challenge"); err != nil { + t.Fatalf("debuggee: %v", err) + } + session := p.debug.activeSession() + if session == nil { + t.Fatal("the paused adapter has no active session") + } + h.app.stopDebugByUser(p) + awaitValueWithin(t, h, 15*time.Second, session.cleanupDone, "the attached session to release its resources") + if session.cleanupErr != nil || p.debug.activeSession() != nil { + t.Fatalf("debug session remained active or failed to clean up: %v", session.cleanupErr) + } + ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second) + forwards, err = client.RemoteForwards(ctx, sessionID) + cancel() + if err != nil || len(forwards) != 0 { + t.Fatalf("after Stop got forwards %+v, err=%v", forwards, err) + } + listener, err := net.Listen("tcp", net.JoinHostPort(forward.LocalHost, strconv.Itoa(int(forward.LocalPort)))) + if err != nil { + t.Fatalf("Stop did not release the local port: %v", err) + } + if err := listener.Close(); err != nil { + t.Fatal(err) + } +} + +func TestProviderServiceDebugAttachesOverSSHFromRunConfigurationAndBuild(t *testing.T) { + host := os.Getenv("LITHE_TEST_VARIANT_SSH_HOST") + if host == "" { + t.Skip("set LITHE_TEST_VARIANT_SSH_HOST to a disposable Linux OpenSSH target") + } + const adapterID = "dev.lithe.test.registry-attach" + adapter := strings.Replace(registryAttachManifest(adapterID), `"process": {"launch":`, `"process": {"placement": "ui", "launch":`, 1) + adapter = strings.Replace(adapter, `"-test.run=^TestDebugAdapterRunner$"`, `"-test.run=^TestSSHTunnelDebugAdapterRunner$", "--", "lithe-ssh-tunnel-adapter"`, 1) + provider := strings.NewReplacer( + `"command": "fixture-tool"`, `"command": "sh"`, + `{"kind": "packaged", "path": "provider"}`, `{"kind": "systemCommand", "commands": ["sh"]}`, + `"-test.run=^TestProviderTestRunner$"`, `"-c", "exec ./debuggee provider"`, + ).Replace(providerServiceDebugManifest) + client := core.NewClient() + connection, connected := connectVariantSSH(t, client, host) + arch := linuxSSHFixtureArch(t, connected) + fixture := buildLinuxSSHFixtureFor(t, "debuggee", "./testdata/remote_debuggee", arch) + + sessionID := connected.Session.ID + const directoryID = "debug-provider" + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + var directory struct{ Path string } + if err := client.RemoteHostRequest(ctx, sessionID, "fs.createRunDirectory", map[string]string{"directoryId": directoryID}, &directory); err != nil { + t.Fatalf("create the provider's remote workspace: %v", err) + } + t.Cleanup(func() { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := client.RemoteHostRequest(ctx, sessionID, "fs.releaseRunDirectory", map[string]string{"directoryId": directoryID}, nil); err != nil { + t.Errorf("release the provider's remote workspace: %v", err) + } + }) + anchor := filepath.Join(t.TempDir(), remoteplaceholder.AnchorName) + if err := remoteplaceholder.Ensure(anchor); err != nil { + t.Fatal(err) + } + root := remoteplaceholder.Root(anchor, directoryID, directory.Path) + remoteFixture := path.Join(directory.Path, "debuggee") + if _, saved, err := client.RemoteWriteFile(ctx, sessionID, path.Join(directory.Path, "fixture.marker"), []byte("fixture\n"), nil); err != nil || !saved { + t.Fatalf("write the build marker: saved=%v, err=%v", saved, err) + } + binding := core.NewRemoteWorkspace(root, directory.Path, nil) + binding.Attach(sessionID) + data, err := os.ReadFile(fixture) + if err != nil { + t.Fatal(err) + } + if err := client.UploadRemotePluginFile(binding.CaptureConnection().Context(ctx), fixture, remoteFixture, fmt.Sprintf("%x", sha256.Sum256(data)), 0o500); err != nil { + t.Fatalf("upload the provider and service executable: %v", err) + } + h := connectionDebugHarnessWithProvider(t, provider, map[string]string{adapterID: adapter}) + h.app.openRemoteProject(remoteTarget{ + connectionID: directoryID, name: "Provider debug SSH test", host: connection, + session: *connected.Session, platform: connected.Host.PluginPlatform(), remoteRoot: directory.Path, root: root, trusted: true, + }) + p := h.app.project + if p == nil || p.remote == nil { + t.Fatal("the provider's remote workspace did not open") + } + if p.remote.binding.CaptureConnection() == nil { + t.Fatal("the provider's remote workspace has no connection") + } + h.app.post(func(a *App) { a.loadTitleRunConfigs(p) }) + awaitStateWithin(t, h, 20*time.Second, "the remote provider model and service configuration", func() bool { + instance := p.selectedBuildInstance() + return instance != nil && instance.modelLoaded && len(instance.Model.Targets) == 1 && + p.runConfigsSettled() && len(p.runConfigs.list) == 1 + }) + configurationID := p.runConfigs.list[0].ID + targetID := p.selectedBuildInstance().Model.Targets[0].ID + for _, entry := range []string{"run configuration", "build target"} { + t.Run(entry, func(t *testing.T) { + t.Cleanup(func() { + if !t.Failed() { + return + } + output := "" + if runs := p.build.runs; len(runs) > 0 { + output = runs[len(runs)-1].output.all() + } + t.Logf("notice %q, build status %q, debug state %q, run console:\n%s", lastNotice(h), p.build.status, p.debug.state, output) + }) + h.app.post(func(a *App) { + if entry == "run configuration" { + a.chooseTitleConfiguration(p, configurationID) + a.titleDebug(p) + return + } + a.debugBuildTarget(p, targetID, "service") + }) + awaitStateWithin(t, h, 25*time.Second, "the debugger's first handshake with the provider-owned service", func() bool { + if p.debug.failure != "" { + t.Fatalf("provider debug failed: %s", p.debug.failure) + } + return p.debug.state == "paused" + }) + session := p.debug.activeSession() + if session == nil || session.adapter.PluginID != adapterID || !p.build.active() { + t.Fatalf("the selected adapter did not own the service: session=%v, active=%v", session != nil, p.build.active()) + } + process, ok := p.build.latest().process.(*buildprocess.RemoteProcess) + if !ok || process.ID == 0 { + t.Fatal("the service run did not track its remote process") + } + check, cancel := context.WithTimeout(context.Background(), 10*time.Second) + forwards, err := client.RemoteForwards(check, sessionID) + cancel() + if err != nil || len(forwards) != 1 || forwards[0].TargetPort < 1 { + t.Fatalf("provider attach must have one loopback tunnel: forwards=%+v, err=%v", forwards, err) + } + serviceIsRunning := func() bool { + check, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + programs, err := client.RemoteRunningPrograms(check, sessionID) + if err != nil { + t.Fatal(err) + } + return slices.ContainsFunc(programs, func(program core.RemoteProgram) bool { + return program.Kind == core.RemoteProgramProcess && program.ID == process.ID + }) + } + if !serviceIsRunning() { + t.Fatal("the remote session did not list the provider's running service") + } + h.app.stopDebugByUser(p) + awaitValueWithin(t, h, 15*time.Second, session.cleanupDone, "the debugger and tunnel to stop") + awaitStateWithin(t, h, 15*time.Second, "the provider-owned service to exit", func() bool { return !p.build.active() }) + if session.cleanupErr != nil { + t.Fatal(session.cleanupErr) + } + check, cancel = context.WithTimeout(context.Background(), 10*time.Second) + forwards, err = client.RemoteForwards(check, sessionID) + cancel() + if err != nil || len(forwards) != 0 { + t.Fatalf("provider stop left forwards: %+v, err=%v", forwards, err) + } + if serviceIsRunning() { + t.Fatal("the provider's debuggee remained active after Stop") + } + }) + } +} + +func startSSHTunnelDebuggee(t *testing.T, client *core.Client, lifetime context.Context, root, executable string) (int, <-chan error) { + t.Helper() + ready := make(chan string, 1) + var stdout strings.Builder + ctx, cancel := context.WithTimeout(lifetime, 10*time.Second) + defer cancel() + process, err := buildprocess.StartRemote(ctx, lifetime, client, core.RemoteProcessOpen{ + Argv: []string{executable}, Environment: "login", + ScopedCwd: &core.RemoteScopedDirectory{Root: root}, + }, func(stream buildprocess.Stream, chunk string) { + if stream == "stdout" { + stdout.WriteString(chunk) + if line, _, found := strings.Cut(stdout.String(), "\n"); found { + select { + case ready <- line: + default: + } + } + } + }) + if err != nil { + t.Fatalf("start remote debuggee: %v", err) + } + exit := make(chan error, 1) + done := make(chan struct{}) + go func() { + defer close(done) + exit <- process.Wait() + }() + t.Cleanup(func() { + process.Stop() + select { + case <-done: + case <-time.After(10 * time.Second): + t.Error("remote debuggee stayed active after cancellation") + } + }) + select { + case line := <-ready: + port, err := strconv.Atoi(line) + if err != nil || port < 1 || port > 65535 { + t.Fatalf("invalid remote debug port %q", line) + } + return port, exit + case err := <-exit: + t.Fatalf("remote debuggee exited before listening: %v", err) + case <-ctx.Done(): + t.Fatalf("wait for remote debuggee to listen: %v", ctx.Err()) + } + return 0, nil +} diff --git a/desktop/internal/workbench/documents.go b/desktop/internal/workbench/documents.go index bd23c450d8..fdb09518d0 100644 --- a/desktop/internal/workbench/documents.go +++ b/desktop/internal/workbench/documents.go @@ -189,19 +189,26 @@ type documentLocation struct { line int column int columnSet bool + // connection binds a plugin page's queued navigation to the host that authorized it. + connection *core.RemoteWorkspaceConnection // group is the editor group the file opens in when it is still there; "" opens it // where files open (placeEditorMember). A restored session sets it (editor_session.go). group string } +// documentOpen identifies one pending read, including the attachment of a scoped read. +type documentOpen struct { + connection *core.RemoteWorkspaceConnection +} + // documentSet is the files a project has open. The zero value has none. type documentSet struct { list []*document next int // clock orders the documents by when they were last shown (tab_limit.go). clock uint64 - // opening are the paths being read, so a second click while one is read opens nothing. - opening map[string]bool + // opening coalesces reads while their attachment remains current. + opening map[string]*documentOpen // openWaiters are the callers that wait for a file being read to become a tab, or to fail. openWaiters map[string][]func(*document, error) // locations hold the latest requested position while a document opens. @@ -274,6 +281,11 @@ func (a *App) syntaxRegistry() *syntax.Registry { // group. The file is read and its language's grammar loaded away from the window thread; a // file that cannot be read, is binary or is too large is not opened and the banner says why. func (a *App) openFile(p *project, path string) { + a.openFileWith(p, path, nil, nil) +} + +// openFileWith can use scoped bytes tied to the connection that authorized them. +func (a *App) openFileWith(p *project, path string, bytesOf documentBytes, connection *core.RemoteWorkspaceConnection) { if path == "" { return } @@ -296,18 +308,21 @@ func (a *App) openFile(p *project, path string) { a.openViewer(p, path, kind) return } - if p.docs.opening[path] { + if pending := p.docs.opening[path]; pending != nil && (pending.connection == nil || pending.connection.IsCurrent()) { return } if p.docs.opening == nil { - p.docs.opening = map[string]bool{} + p.docs.opening = make(map[string]*documentOpen) } - p.docs.opening[path] = true + opening := &documentOpen{connection: connection} + p.docs.opening[path] = opening registry := a.syntaxRegistry() name := filepath.Base(path) kernel, _ := a.kernel.(editorKernel) budget := int64(a.searchPreferences.MaxFileBytes) - bytesOf := a.documentBytesOf(p) + if bytesOf == nil { + bytesOf = a.documentBytesOf(p) + } remote := p.remote != nil a.background(p, 0, func(ctx context.Context) func(*App) { // A host file is read over the session (remote_documents.go); decoding, recovery and the @@ -336,9 +351,19 @@ func (a *App) openFile(p *project, path string) { languageID, grammar = a.resolveDocumentLanguage(ctx, registry, path, snapshot) } return func(a *App) { + if p.docs.opening[path] != opening { + return + } delete(p.docs.opening, path) location := p.docs.locations[path] delete(p.docs.locations, path) + if connection != nil && !connection.IsCurrent() { + a.openFinished(p, path, errRemoteDisconnected) + return + } + if location.connection != nil && !location.connection.IsCurrent() { + location = documentLocation{} + } defer a.openFinished(p, path, err) if errors.Is(err, errNotText) && !p.standalone && !remote { // A binary file opens in the hex viewer rather than not at all. The viewer reads @@ -361,10 +386,8 @@ func (a *App) openFile(p *project, path string) { a.applyRecoveredDocument(p, d, restored) } // A plugin that serves this language starts its server the first time a - // file of it is opened, not when the project opens: a workspace of Go - // files must not pay for a Java server. A remote workspace runs none on this - // computer, which would read the placeholder. - if languageID != "" && !remote { + // file of it is opened. Its process uses the workspace host. + if languageID != "" { a.startPluginServer(languageID) } if d := p.docs.byPath(path); d != nil { @@ -402,6 +425,10 @@ func (a *App) openFileAt(p *project, path string, line int) { // A file that is already open is selected and its caret moved without reading // it again. func (a *App) openFileAtPosition(p *project, path string, line, column int) { + a.openFileAtPositionWith(p, path, line, column, nil, nil) +} + +func (a *App) openFileAtPositionWith(p *project, path string, line, column int, bytesOf documentBytes, connection *core.RemoteWorkspaceConnection) { if path == "" { return } @@ -415,8 +442,8 @@ func (a *App) openFileAtPosition(p *project, path string, line, column int) { if p.docs.locations == nil { p.docs.locations = make(map[string]documentLocation) } - p.docs.locations[path] = documentLocation{line: line + 1, column: column, columnSet: true} - a.openFile(p, path) + p.docs.locations[path] = documentLocation{line: line + 1, column: column, columnSet: true, connection: connection} + a.openFileWith(p, path, bytesOf, connection) } // readDocument reads an editor file and asks Core to classify its complete diff --git a/desktop/internal/workbench/documents_tabless.go b/desktop/internal/workbench/documents_tabless.go index f1ab254473..53c369d319 100644 --- a/desktop/internal/workbench/documents_tabless.go +++ b/desktop/internal/workbench/documents_tabless.go @@ -32,13 +32,13 @@ func (a *App) ensureTablessDocument(t *diffTab) { // openTablessDocument reads path in the background and makes it a document without a tab. The Diff // tabs of the file are laid out again once it is there, so their right sides become editable. func (a *App) openTablessDocument(p *project, path string) { - if p.docs.opening[path] { + if p.docs.opening[path] != nil { return } if p.docs.opening == nil { - p.docs.opening = map[string]bool{} + p.docs.opening = make(map[string]*documentOpen) } - p.docs.opening[path] = true + p.docs.opening[path] = &documentOpen{} registry := a.syntaxRegistry() kernel, _ := a.kernel.(editorKernel) bytesOf := a.documentBytesOf(p) diff --git a/desktop/internal/workbench/editor_actions.go b/desktop/internal/workbench/editor_actions.go index fec2decf39..d85caab8b6 100644 --- a/desktop/internal/workbench/editor_actions.go +++ b/desktop/internal/workbench/editor_actions.go @@ -348,7 +348,7 @@ func (a *App) editorActionMenuItems(c ui.C, p *project, d *document, menu *ui.Me // runCurrentFileEditorAction presents the same plugin invocation the gutter // offers. An absent cached action may mean its initial collection is still in flight. -func (a *App) runCurrentFileEditorAction(p *project, d *document, mode titleAction, discoveryErr error) { +func (a *App) runCurrentFileEditorAction(p *project, d *document, mode titleAction, discoveryErr error, connection *core.RemoteWorkspaceConnection) { fallback := func(a *App) { if discoveryErr != nil { a.notifyError(discoveryErr.Error()) @@ -356,7 +356,7 @@ func (a *App) runCurrentFileEditorAction(p *project, d *document, mode titleActi } if mode == titleActionDebug { a.whenDebugAdaptersLoaded(p, func() { - if p.selectedDocument(p.docs.group) == d { + if p.selectedDocument(p.docs.group) == d && (connection == nil || connection.IsCurrent()) { a.startDebug(p) } }) @@ -373,7 +373,7 @@ func (a *App) runCurrentFileEditorAction(p *project, d *document, mode titleActi return } start := func() { - if a.project != p || p.selectedDocument(p.docs.group) != d { + if a.project != p || p.selectedDocument(p.docs.group) != d || (connection != nil && !connection.IsCurrent()) { return } invoke := func(a *App, actions []pluginservice.EditorAction) bool { @@ -394,10 +394,12 @@ func (a *App) runCurrentFileEditorAction(p *project, d *document, mode titleActi text := string(data) id := strconv.Itoa(d.id) a.background(p, 10*time.Second, func(ctx context.Context) func(*App) { + ctx = attachedWorkspaceContext(ctx, connection) actions, err := plugins.CollectEditorActions(ctx, p.root, path, id, revision, text) return func(a *App) { p.runConfigs.findingEntrypoint = false - if p.selectedDocument(p.docs.group) != d || d.path != path || d.view.Revision() != revision { + if p.selectedDocument(p.docs.group) != d || d.path != path || d.view.Revision() != revision || + (connection != nil && !connection.IsCurrent()) { return } if invoke(a, actions) { diff --git a/desktop/internal/workbench/editor_session.go b/desktop/internal/workbench/editor_session.go index 68420f760a..655375fba0 100644 --- a/desktop/internal/workbench/editor_session.go +++ b/desktop/internal/workbench/editor_session.go @@ -295,7 +295,7 @@ func (a *App) stepEditorRestore(p *project) { } p.docs.locations[item.path] = documentLocation{line: item.line + 1, column: item.column, columnSet: true, group: item.group} a.openFile(p, item.path) - if p.docs.opening[item.path] { + if p.docs.opening[item.path] != nil { r.waiting = item.path return } diff --git a/desktop/internal/workbench/plugin_auto_update.go b/desktop/internal/workbench/plugin_auto_update.go index 57dbe03345..210ffe893a 100644 --- a/desktop/internal/workbench/plugin_auto_update.go +++ b/desktop/internal/workbench/plugin_auto_update.go @@ -3,7 +3,6 @@ package workbench import ( "context" "errors" - "runtime" "strconv" "time" @@ -129,7 +128,7 @@ func (a *App) checkPluginAutoUpdates() { ctx, cancel := context.WithCancel(context.Background()) u.checking, u.cancel = true, cancel sources := a.marketplaceSources() - platform := marketplaceHostPlatform() + platform := marketplace.CurrentPlatform() capabilities := pluginhost.Declared().Clone() a.background(nil, 0, func(context.Context) func(*App) { defer cancel() @@ -168,14 +167,6 @@ func (a *App) marketplaceSources() []PluginRecommendationSource { return sources } -func marketplaceHostPlatform() string { - arch := runtime.GOARCH - if arch == "amd64" { - arch = "x64" - } - return runtime.GOOS + "-" + arch -} - // autoUpdateCandidates uses only Core-validated availability and release order. // Its source must be exactly the index the user originally approved. func autoUpdateCandidates(entries []pluginmanager.Entry, approvals map[string]plugintrust.Record, snapshot marketplace.Snapshot) []core.MarketplacePlugin { @@ -294,9 +285,10 @@ func (a *App) applyPluginAutoUpdate(ctx context.Context, downloader *marketplace defer func() { a.recordPluginInstallCleanup(ctx, archive.Discard()) }() plan, err := a.preparePlugin(ctx, plugininstall.Request{ ArchivePath: archive.Path(), Root: a.plugins.Root, Source: plugintrust.Marketplace, - ArchiveSHA256: plugin.Availability.SHA256, - MarketplaceIndexURL: plugin.MarketplaceIndexURL, - ExpectedID: plugin.ID, ExpectedVersion: plugin.Availability.Version, + ArchiveSHA256: plugin.Availability.SHA256, + MarketplaceIndexURL: plugin.MarketplaceIndexURL, + MarketplaceRepository: plugin.Repository, + ExpectedID: plugin.ID, ExpectedVersion: plugin.Availability.Version, }) if err != nil { return false, err diff --git a/desktop/internal/workbench/plugin_programs.go b/desktop/internal/workbench/plugin_programs.go index dd7734122e..c4745feb42 100644 --- a/desktop/internal/workbench/plugin_programs.go +++ b/desktop/internal/workbench/plugin_programs.go @@ -154,7 +154,7 @@ func (a *App) detachPluginPrograms(id string) (*pluginservice.LanguageSession, f if p := tab.project; p != nil { p.revokePluginBuildTests(id) stops = append(stops, p.buildSessions.detachPlugin(id)) - stops = append(stops, p.vcs.runtime().detachPlugin(id)) + stops = append(stops, p.vcsRuntime().detachPlugin(id)) var debugging []*debugSession for _, session := range p.debug.sessions { if session.adapter.PluginID == id { diff --git a/desktop/internal/workbench/plugin_recommendations.go b/desktop/internal/workbench/plugin_recommendations.go index 63f0543b93..9f695289af 100644 --- a/desktop/internal/workbench/plugin_recommendations.go +++ b/desktop/internal/workbench/plugin_recommendations.go @@ -116,7 +116,7 @@ func (a *App) checkPluginRecommendations(p *project) { } root := p.root sources := a.marketplaceSources() - platform := marketplaceHostPlatform() + platform := marketplace.CurrentPlatform() capabilities := pluginhost.Declared().Clone() dismissed := append([]string(nil), a.settings.DismissedPluginRecommendations...) fetcher := a.recommendationFetcher diff --git a/desktop/internal/workbench/plugin_recommendations_test.go b/desktop/internal/workbench/plugin_recommendations_test.go index 40c2c96b82..0d63e82dcd 100644 --- a/desktop/internal/workbench/plugin_recommendations_test.go +++ b/desktop/internal/workbench/plugin_recommendations_test.go @@ -18,6 +18,7 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" "github.com/1lck/Lithe-IDEA/desktop/internal/plugininstall" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" "github.com/1lck/Lithe-IDEA/desktop/internal/plugintrust" @@ -36,7 +37,7 @@ func recommendationTestStore(t *testing.T) *store.Store { func syntheticRecommendationCatalog(t *testing.T, recommendationsJSON string) core.MarketplaceRecommendationCatalog { t.Helper() - platform := marketplaceHostPlatform() + platform := marketplace.CurrentPlatform() shaA := strings.Repeat("a", 64) shaB := strings.Repeat("b", 64) indexPayload, err := json.Marshal(map[string]any{ diff --git a/desktop/internal/workbench/plugin_settings.go b/desktop/internal/workbench/plugin_settings.go index e15b7fbb74..6ee5b6d8ad 100644 --- a/desktop/internal/workbench/plugin_settings.go +++ b/desktop/internal/workbench/plugin_settings.go @@ -4,15 +4,28 @@ import ( "context" "encoding/json" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginsettings" ) // loadPluginPreferenceSources supplies one operation's real native layers to // Core. It runs on the operation worker; it never reads on the window thread. -func (a *App) loadPluginPreferenceSources(ctx context.Context, manifest json.RawMessage, workspace string) (pluginsettings.Snapshot, error) { +func (a *App) loadPluginPreferenceSources(ctx context.Context, manifest json.RawMessage, workspace string) (core.PluginSettingsState, error) { + if binding := core.RemoteWorkspaceOf(ctx); binding != nil { + connection := binding.CapturedConnection(ctx) + if !connection.IsCurrent() { + return core.PluginSettingsState{}, &core.Error{Code: core.CodeConnectionClosed, Message: "The workspace connection changed."} + } + if a.plugins == nil { + return core.PluginSettingsState{}, pluginservice.ErrAssembly + } + return a.plugins.ReadWorkspacePluginSettings(ctx, manifest, workspace, connection) + } root := "" if a.store != nil { root = a.store.Dir() } - return pluginsettings.New(a.kernel, root).Load(ctx, manifest, workspace) + snapshot, err := pluginsettings.New(a.kernel, root).Load(ctx, manifest, workspace) + return snapshot.State, err } diff --git a/desktop/internal/workbench/pluginbackends.go b/desktop/internal/workbench/pluginbackends.go index ce23094655..b443af8d10 100644 --- a/desktop/internal/workbench/pluginbackends.go +++ b/desktop/internal/workbench/pluginbackends.go @@ -21,6 +21,7 @@ import ( // cancellation remain protected by pluginServerMu. type pluginServerPreparation struct { project *project + remote *core.RemoteWorkspaceConnection cancel context.CancelFunc progress atomic.Pointer[pluginruntime.Progress] cancelled atomic.Bool @@ -194,9 +195,8 @@ func (a *App) requestPluginServer(languageID string, providersChanged bool) { if a.plugins == nil || languageID == "" { return } - if a.project != nil && a.project.remote != nil { - // log-exempt: 远程工作区的语言服务器要在主机上运行,现在还不支持;在本机启动只会读到空的占位文件夹, - // 信任远程文件夹后也不在本机运行任何项目代码。 + request := a.pluginBackendRequest() + if a.project != nil && a.project.remote != nil && request.RemoteConnection == nil { return } a.pluginServerMu.Lock() @@ -228,11 +228,10 @@ func (a *App) requestPluginServer(languageID string, providersChanged bool) { if p != nil && p.ctx != nil { parent = p.ctx } - ctx, cancel := context.WithCancel(a.operationContext(parent)) - preparation := &pluginServerPreparation{project: p, cancel: cancel, revision: a.pluginServerRevision} + ctx, cancel := context.WithCancel(core.WithoutRemoteWorkspace(a.operationContext(parent))) + preparation := &pluginServerPreparation{project: p, remote: request.RemoteConnection, cancel: cancel, revision: a.pluginServerRevision} a.pluginServerPreparations[languageID] = preparation a.pluginServerMu.Unlock() - request := a.pluginBackendRequest() request.RuntimeProgress = func(progress pluginruntime.Progress) { preparation.progress.Store(&progress) a.invalidator.Invalidate() @@ -282,8 +281,8 @@ func (a *App) finishPluginServerPreparation(preparation *pluginServerPreparation delete(a.pluginServerPreparations, languageID) } a.pluginServerMu.Unlock() - if !current || changed { - // A result from the previous project cannot clear a newer start's marker. + if !current || changed || (preparation.remote != nil && !preparation.remote.IsCurrent()) { + // A result from the previous project or connection cannot clear a newer start's marker. a.stopPluginSession(session) if current { a.pluginServerMu.Lock() @@ -563,10 +562,10 @@ func (a *App) activatePluginWorkspace(p *project) { a.background(p, pluginServerStartTimeout, func(ctx context.Context) func(*App) { entries, err := a.plugins.Manager.Installed() if err == nil { - err = a.plugins.ActivateWorkspace(ctx, entries, workspace) + err = a.plugins.ActivateWorkspace(core.WithoutRemoteWorkspace(ctx), entries, workspace) } return func(a *App) { - if err != nil { + if err != nil && p.pluginContext == workspace { a.operationFailed("plugin_backend_start", err) } } @@ -592,6 +591,12 @@ func (a *App) closePluginBackends() { // the project closes and when the client quits. func (a *App) stopAllPluginServers() { a.closePluginBackends() + a.stopLanguageServers() +} + +// stopLanguageServers withdraws workspace sessions while keeping local plugin +// backends alive across a remote reconnection. +func (a *App) stopLanguageServers() { a.pluginServerMu.Lock() for _, preparation := range a.pluginServerPreparations { preparation.stop() @@ -612,17 +617,15 @@ func (a *App) stopAllPluginServers() { a.pluginServerMu.Unlock() return } - servers := make([]*pluginServer, 0, len(a.pluginServers)) - for _, server := range a.pluginServers { - servers = append(servers, server) - } + servers := a.pluginServers a.releaseAllPluginDocuments() a.pluginServers = nil a.pluginServerLanguages = nil a.pluginServerStarting = nil a.pluginServerMu.Unlock() - for _, server := range servers { + for pluginID, server := range servers { server.cancel() + a.clearPluginDiagnostics(pluginID) a.stopPluginSession(server.session) } } @@ -650,6 +653,9 @@ func (a *App) pluginBackendRequest() pluginservice.BackendRequest { // goroutine; a map here would not fit lsp.startServer's string field. request.WorkingDirectory = a.project.root request.Context = a.project.pluginContext + if remote := a.project.remote; remote != nil && remote.binding != nil { + request.RemoteConnection = remote.binding.CaptureConnection() + } // In safe mode Core plans only a server that declares it runs no project code; the // others wait for trust (finishPluginServerStart). request.ProjectCodeAllowed = a.project.trust.allowed() diff --git a/desktop/internal/workbench/pluginpages.go b/desktop/internal/workbench/pluginpages.go index 12d1435dbc..7e2429eea0 100644 --- a/desktop/internal/workbench/pluginpages.go +++ b/desktop/internal/workbench/pluginpages.go @@ -36,6 +36,7 @@ import ( type pluginPage struct { tool pluginservice.ToolWindow project *project + context pluginservice.ContextRef page *pluginweb.Page view *app.WebView // failure is why the page could not open; the window says so instead. @@ -82,13 +83,17 @@ func (a *App) pluginPageMessage(c ui.C, message string) { // pluginPage returns the page of a web tool window in project p, opening it on first // use. It is nil while the window's web host is not ready yet. func (a *App) pluginPage(it item, p *project) *pluginPage { - if page := a.pluginPages[it.id]; page != nil && page.project == p { - return page + if page := a.pluginPages[it.id]; page != nil { + if page.project == p && page.context == p.pluginContext { + return page + } + page.close() + delete(a.pluginPages, it.id) } if !a.webReady { return nil } - page := &pluginPage{tool: *it.tool, project: p, colors: a.colors} + page := &pluginPage{tool: *it.tool, project: p, context: p.pluginContext, colors: a.colors} if a.pluginPages == nil { a.pluginPages = make(map[string]*pluginPage) } @@ -105,7 +110,10 @@ func (a *App) openPluginPage(page *pluginPage) error { if !ok || a.plugins == nil { return errors.ErrUnsupported } - host := &pluginPageHost{a: a, plugins: a.plugins, tool: page.tool, project: page.project, language: a.language()} + host := &pluginPageHost{ + a: a, plugins: a.plugins, tool: page.tool, project: page.project, workspace: page.context, + language: a.language(), maximumFileBytes: int64(a.searchPreferences.MaxFileBytes), + } ctx, cancel := context.WithTimeout(a.operationContext(context.Background()), kernelCallTimeout) defer cancel() opened, err := pluginweb.Open(ctx, pluginweb.Config{ @@ -119,7 +127,7 @@ func (a *App) openPluginPage(page *pluginPage) error { Post: func(fn func()) { a.post(func(*App) { fn() }) }, Log: func(stage string, err error) { a.post(func(a *App) { - a.backgroundFailed("plugin_web_"+stage, err) + a.backgroundFailed("plugin_web_"+stage, page.project.logError(err)) }) }, }) @@ -226,20 +234,22 @@ func cssColor(c gfx.Color) string { // pluginPageHost carries out the checked requests of one page for the project it is // shown in. type pluginPageHost struct { - a *App - plugins *pluginservice.Service - tool pluginservice.ToolWindow - project *project - language i18n.Language - stateLimit int + a *App + plugins *pluginservice.Service + tool pluginservice.ToolWindow + project *project + workspace pluginservice.ContextRef + language i18n.Language + stateLimit int + maximumFileBytes int64 } func (h *pluginPageHost) State(_ context.Context, pluginID, windowID string) ([]byte, error) { - return h.plugins.PageState(pluginID, windowID, h.project.root, h.stateLimit) + return h.plugins.PageState(pluginID, windowID, h.workspace, h.stateLimit) } func (h *pluginPageHost) SetState(_ context.Context, pluginID, windowID string, state []byte) error { - return h.plugins.SetPageState(pluginID, windowID, h.project.root, state, h.stateLimit) + return h.plugins.SetPageState(pluginID, windowID, h.workspace, state, h.stateLimit) } func (h *pluginPageHost) BackendFunctions(ctx context.Context, pluginID string) ([]string, error) { @@ -247,7 +257,7 @@ func (h *pluginPageHost) BackendFunctions(ctx context.Context, pluginID string) } func (h *pluginPageHost) CallBackend(ctx context.Context, pluginID, function string, params json.RawMessage, progress func(json.RawMessage)) (json.RawMessage, error) { - return h.plugins.CallFromPage(ctx, pluginID, function, params, h.project.root, progress) + return h.plugins.CallFromWorkspace(ctx, pluginID, function, params, h.workspace, progress) } // ChooseFile shows the system's file dialog, titled with the plugin's name so the user @@ -292,35 +302,90 @@ func (h *pluginPageHost) ChooseFile(_ string, request pluginweb.FileRequest) (st return path, err } -// OpenFile opens a file of the workspace in the editor. Core refused paths with ".."; -// a path that leads out of the workspace through a link is refused here. -func (h *pluginPageHost) OpenFile(path string, line, column int) error { +// OpenFile checks the file on its workspace host before asking the editor to open it. +func (h *pluginPageHost) OpenFile(ctx context.Context, path string, line, column int) error { a, p := h.a, h.project - if a.project != p { - return pluginweb.Fail("plugin.web.forbidden", "The workspace of this page is closed.") + var target string + var document pluginservice.PageDocument + if p.remote != nil { + result, failure := h.plugins.ReadPageDocument(ctx, h.tool.PluginID, h.workspace, path, h.maximumFileBytes) + if failure != nil { + switch failure.Code { + case pluginservice.CodePermissionDenied, pluginservice.CodeRemoteDisconnected: + return pluginweb.Fail("plugin.web.forbidden", failure.Message) + default: + return pluginweb.Fail("plugin.web.invalidRequest", failure.Message) + } + } + document = result + if relative := filepath.FromSlash(document.Path); !filepath.IsLocal(relative) { + return pluginweb.Fail("plugin.web.invalidRequest", "The editor cannot address this file name.") + } else { + target = filepath.Join(p.root, relative) + } + } else { + var err error + target, err = localPluginPageFile(p.root, path) + if err != nil { + return err + } } + + result := make(chan error, 1) + a.post(func(a *App) { + switch { + case ctx.Err() != nil: + result <- ctx.Err() + case a.project != p || p.pluginContext != h.workspace: + result <- pluginweb.Fail("plugin.web.forbidden", "The workspace of this page is closed.") + case document.Connection != nil && !document.Connection.IsCurrent(): + result <- pluginweb.Fail("plugin.web.forbidden", "The remote workspace connection changed.") + default: + var read documentBytes + if document.Connection != nil { + // Use the scoped bytes from the same attachment. A second + // unscoped read could see a substituted parent path. + read = func(_ context.Context, _ string, limit int64) ([]byte, error) { + if int64(len(document.Data)) > limit { + return nil, errTooLarge + } + return document.Data, nil + } + } + if line <= 0 { + a.openFileWith(p, target, read, document.Connection) + } else { + a.openFileAtPositionWith(p, target, line-1, max(column-1, 0), read, document.Connection) + } + result <- nil + } + }) + select { + case err := <-result: + return err + case <-ctx.Done(): + return ctx.Err() + } +} + +func localPluginPageFile(workspace, path string) (string, error) { target := path if !filepath.IsAbs(target) { - target = filepath.Join(p.root, target) + target = filepath.Join(workspace, target) } resolved, err := filepath.EvalSymlinks(target) if err != nil { - return pluginweb.Fail("plugin.web.invalidRequest", path+" does not exist.") + return "", pluginweb.Fail("plugin.web.invalidRequest", path+" does not exist.") } - root, err := filepath.EvalSymlinks(p.root) + root, err := filepath.EvalSymlinks(workspace) if err != nil { - return err + return "", err } if relative, err := filepath.Rel(root, resolved); err != nil || relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) { - return pluginweb.Fail("plugin.web.forbidden", path+" is outside the workspace.") + return "", pluginweb.Fail("plugin.web.forbidden", path+" is outside the workspace.") } if info, err := os.Stat(resolved); err != nil || !info.Mode().IsRegular() { - return pluginweb.Fail("plugin.web.invalidRequest", path+" is not a file.") + return "", pluginweb.Fail("plugin.web.invalidRequest", path+" is not a file.") } - if line <= 0 { - a.openFileAt(p, target, 0) - return nil - } - a.openFileAtPosition(p, target, line-1, max(column-1, 0)) - return nil + return target, nil } diff --git a/desktop/internal/workbench/plugins.go b/desktop/internal/workbench/plugins.go index b9e7254401..36002f92f3 100644 --- a/desktop/internal/workbench/plugins.go +++ b/desktop/internal/workbench/plugins.go @@ -95,13 +95,14 @@ func (a *App) installPlugin(plugin core.MarketplacePlugin, feedback settingswind feedback.Preparing() } plan, err := a.preparePlugin(ctx, plugininstall.Request{ - ArchivePath: archive.Path(), - Root: a.plugins.Root, - Source: plugintrust.Marketplace, - ArchiveSHA256: availability.SHA256, - MarketplaceIndexURL: plugin.MarketplaceIndexURL, - ExpectedID: plugin.ID, - ExpectedVersion: availability.Version, + ArchivePath: archive.Path(), + Root: a.plugins.Root, + Source: plugintrust.Marketplace, + ArchiveSHA256: availability.SHA256, + MarketplaceIndexURL: plugin.MarketplaceIndexURL, + MarketplaceRepository: plugin.Repository, + ExpectedID: plugin.ID, + ExpectedVersion: availability.Version, }) if err != nil && !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded) { a.recordPluginInstallCleanup(ctx, downloads.Forget(archive)) @@ -285,6 +286,9 @@ func (a *App) applyPluginLifecycleChange(reload bool) { // recordPluginRuntimeIssue records automatic repair and cleanup at the native I/O boundary. func (a *App) recordPluginRuntimeIssue(ctx context.Context, err error) { + if core.RemoteWorkspaceOf(ctx) != nil { + err = remoteLogError(err) + } fields := core.LogErrorFields(err) fields["stage"] = "plugin_runtime_repair" a.emitIn(ctx, core.LevelWarn, "app.storage.maintenance_failed", fields) diff --git a/desktop/internal/workbench/plugins_test.go b/desktop/internal/workbench/plugins_test.go index 3298c71144..88283efaac 100644 --- a/desktop/internal/workbench/plugins_test.go +++ b/desktop/internal/workbench/plugins_test.go @@ -371,7 +371,7 @@ func TestUninstallStopsProviderSessionsBeforeDeletingFiles(t *testing.T) { PluginID: id, Version: "1.0.0", PackageDirectory: directory, Manifest: json.RawMessage(manifest), }) } else if err == nil { - started, err = runtime.session(ctx, h.app.plugins.Backend, h.app.plugins.Root, root, uri, + started, err = runtime.session(ctx, h.app.plugins, root, uri, vcsWindow{PluginID: id, Version: "1.0.0", Directory: directory, Manifest: json.RawMessage(manifest), Vcs: "fakevcs"}, core.PluginSettingsState{}, true, h.app.pluginLogDirectory) } return func(*App) { @@ -414,7 +414,7 @@ func TestUninstallStopsProviderSessionsBeforeDeletingFiles(t *testing.T) { h.app.invalidateVcs(p) ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() - _, err := p.vcs.runtime().session(ctx, h.app.plugins.Backend, h.app.plugins.Root, root, "", + _, err := p.vcs.runtime().session(ctx, h.app.plugins, root, "", vcsWindow{PluginID: id, Version: "1.0.0"}, core.PluginSettingsState{}, true, h.app.pluginLogDirectory) if !errors.Is(err, buildprovider.ErrClosed) { t.Fatalf("catalog refresh reopened a removed plugin: %v", err) @@ -531,7 +531,7 @@ func TestEnableReopensVcsAfterCatalogRefresh(t *testing.T) { h.app.background(p, 30*time.Second, func(ctx context.Context) func(*App) { uri, err := h.app.kernel.PluginDocumentURI(ctx, root, "auto") if err == nil { - _, err = sessions.session(ctx, h.app.plugins.Backend, h.app.plugins.Root, root, uri, + _, err = sessions.session(ctx, h.app.plugins, root, uri, vcsWindow{PluginID: id, Version: "1.0.0", Directory: filepath.Join(h.app.plugins.Root, id, "1.0.0"), Manifest: json.RawMessage(vcsFixtureManifest), Vcs: "fakevcs"}, core.PluginSettingsState{}, true, h.app.pluginLogDirectory) } return func(*App) { diff --git a/desktop/internal/workbench/pluginsync.go b/desktop/internal/workbench/pluginsync.go index c7101b8818..df715632eb 100644 --- a/desktop/internal/workbench/pluginsync.go +++ b/desktop/internal/workbench/pluginsync.go @@ -123,8 +123,7 @@ func (a *App) documentEdited(p *project, d *document, edit editorview.Edit) { // document; edits that arrive meanwhile stay queued. func (a *App) startDocumentSync(p *project, d *document) { s := &d.sync - // A remote workspace starts no language server (#2231): its documents name placeholder paths. - if s.running || a.plugins == nil || a.project != p || p.remote != nil { + if s.running || a.plugins == nil || a.project != p { return } server, pluginID := a.documentSyncServer(d) diff --git a/desktop/internal/workbench/pluginsync_e2e_test.go b/desktop/internal/workbench/pluginsync_e2e_test.go index a3e22e9811..efb915c2ff 100644 --- a/desktop/internal/workbench/pluginsync_e2e_test.go +++ b/desktop/internal/workbench/pluginsync_e2e_test.go @@ -333,7 +333,7 @@ func TestClangdBuildStartedSessionSynchronizesEditor(t *testing.T) { h.app.tasks.running.Add(1) go func() { defer h.app.tasks.running.Done() - _, err := h.app.sharedBuildProvider(ctx, p, instance, "c") + _, err := h.app.sharedBuildProvider(ctx, p, instance, "c", nil, 0) result <- err h.app.invalidator.Invalidate() }() diff --git a/desktop/internal/workbench/pluginterminals.go b/desktop/internal/workbench/pluginterminals.go index b20412d9e5..c1afa7d18a 100644 --- a/desktop/internal/workbench/pluginterminals.go +++ b/desktop/internal/workbench/pluginterminals.go @@ -71,6 +71,22 @@ func (a *App) pluginTerminalExited(p *project, t *terminal, status *int) { func (w pluginWorkbench) StartTerminal(ctx context.Context, root string, spec pluginservice.TerminalSpec) (pluginservice.TerminalSession, error) { a := w.app language := a.language() + connectionName, err := onWindow(a, ctx, func(a *App) (string, error) { + p, err := a.projectAt(root) + if err != nil { + return "", err + } + if err := validatePluginTerminalHost(p, ctx, spec); err != nil { + return "", err + } + if p.remote != nil { + return p.remote.name, nil + } + return "", nil + }) + if err != nil { + return nil, err + } prompt := &pluginPrompt{ title: i18n.SharedFormat(language, "desktop.pluginHost.terminalConsentTitle", map[string]string{"plugin": spec.PluginID}), text: i18n.SharedFormat(language, "desktop.pluginHost.terminalConsentDetails", map[string]string{ @@ -84,6 +100,9 @@ func (w pluginWorkbench) StartTerminal(ctx context.Context, root string, spec pl i18n.Shared(language, "desktop.pluginHost.terminalAllow"), }, } + if spec.RemoteConnection != nil { + prompt.text += "\n" + i18n.SharedFormat(language, "desktop.pluginHost.terminalConsentRemote", map[string]string{"connection": connectionName}) + } choice, err := a.askUser(ctx, prompt) if err != nil { return nil, err @@ -96,6 +115,9 @@ func (w pluginWorkbench) StartTerminal(ctx context.Context, root string, spec pl if err != nil { return nil, err } + if err := validatePluginTerminalHost(p, ctx, spec); err != nil { + return nil, err + } plugin := &pluginTerminal{budget: spec.RetainedBytes, done: make(chan pluginservice.TerminalExit, 1)} env, unset := terminalEnvironment(spec.Environment) title := spec.Title @@ -109,6 +131,7 @@ func (w pluginWorkbench) StartTerminal(ctx context.Context, root string, spec pl t := a.newTerminalWith(p, terminalOptions{ shell: spec.Executable, args: args, env: env, unset: unset, dir: spec.Directory, title: title, prefill: spec.Prefill, activate: spec.Show, plugin: plugin, + remoteDirectory: spec.RemoteDirectory, remoteConnection: spec.RemoteConnection, }) if t == nil { return nil, hostError(pluginservice.CodeBusy, "The terminal could not be opened.") @@ -121,6 +144,20 @@ func (w pluginWorkbench) StartTerminal(ctx context.Context, root string, spec pl }) } +func validatePluginTerminalHost(p *project, ctx context.Context, spec pluginservice.TerminalSpec) error { + if p.remote == nil && spec.RemoteConnection == nil && spec.RemoteDirectory == nil { + return nil + } + if p.remote == nil || spec.RemoteDirectory == nil || !spec.RemoteConnection.IsCurrent() || + core.RemoteWorkspaceOf(spec.RemoteConnection.Context(ctx)) != p.remote.binding { + return hostError(pluginservice.CodeRemoteDisconnected, "The remote workspace connection changed.") + } + if p.safeMode() { + return hostError(pluginservice.CodePermissionDenied, "Plugin terminals require a trusted remote workspace.") + } + return nil +} + // reveal selects the terminal and shows the Terminal tool window when the tab // lives there. func (s *pluginTerminalSession) reveal(p *project, t *terminal) { diff --git a/desktop/internal/workbench/remote_browse.go b/desktop/internal/workbench/remote_browse.go index 5cc9493f44..148cd5de2d 100644 --- a/desktop/internal/workbench/remote_browse.go +++ b/desktop/internal/workbench/remote_browse.go @@ -32,9 +32,9 @@ import ( // remoteBrowser chooses the host folder to open over a session the window connected. type remoteBrowser struct { - session core.RemoteSession - // entryID and name are the saved connection's, or the WSL distribution's or the container's - // identity and name. + session core.RemoteSession + platform *core.RemotePlatform + // entryID and name identify the saved connection, WSL distribution or container. entryID string name string host remoteHost @@ -160,7 +160,7 @@ func (a *App) connectRemoteTo(entry core.SavedRemoteConnection, host remoteHost, r.connect = nil if err == nil && result.Status == core.RemoteProbeConnected && result.Session != nil { r.steps = nil - a.browseRemote(entry, host, *result.Session) + a.browseRemote(entry, host, *result.Session, result.Host.PluginPlatform()) if folder != "" { a.openRemoteFolderAt(folder) } @@ -220,9 +220,9 @@ func remoteConnectFailureText(language i18n.Language, err error) string { // browseRemote starts choosing the folder to open over session to host, in the account's home // directory. -func (a *App) browseRemote(entry core.SavedRemoteConnection, host remoteHost, session core.RemoteSession) { +func (a *App) browseRemote(entry core.SavedRemoteConnection, host remoteHost, session core.RemoteSession, platform *core.RemotePlatform) { r := &a.remote - r.browser = &remoteBrowser{session: session, entryID: entry.ID, name: entry.Name, host: host, recent: entry.RecentFolders} + r.browser = &remoteBrowser{session: session, platform: platform, entryID: entry.ID, name: entry.Name, host: host, recent: entry.RecentFolders} start := session.HomeDirectory if !path.IsAbs(start) { start = "/" @@ -507,7 +507,7 @@ func (a *App) openRemoteFolderNow(dir string, trusted bool) { return } target := remoteTarget{ - connectionID: b.entryID, name: b.name, host: b.host, session: b.session, + connectionID: b.entryID, name: b.name, host: b.host, session: b.session, platform: b.platform, remoteRoot: dir, root: remoteplaceholder.Root(anchor, b.entryID, dir), trusted: trusted, } // The session is the workspace's from here on. @@ -527,7 +527,7 @@ func (a *App) openRemoteWorkspace(target remoteTarget) { p := open.project if r := p.remote; r != nil && !r.closed && r.session == "" && r.reconnecting == nil { r.stopRemoteTimer() - open.attachRemote(p, target.session) + open.attachRemote(p, target.session, target.platform) open.refreshRemoteTree(p) open.offerKeptPrograms(p, target.session) } else { diff --git a/desktop/internal/workbench/remote_build_process.go b/desktop/internal/workbench/remote_build_process.go new file mode 100644 index 0000000000..3ac48e942d --- /dev/null +++ b/desktop/internal/workbench/remote_build_process.go @@ -0,0 +1,163 @@ +package workbench + +import ( + "context" + "crypto/rand" + "errors" + "os" + "path" + "path/filepath" + "slices" + + "github.com/1lck/Lithe-IDEA/desktop/internal/buildprocess" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/processledger" +) + +// buildProcess is the process lifetime the Run and Tests windows own. +type buildProcess interface { + Wait() error + Stop() + Kill() + Pid() int +} + +// startBuildExecution runs the plan under the captured workspace attachment. +func (a *App) startBuildExecution(ctx context.Context, p *project, execution buildExecution, arguments []string, directory string, environment map[string]string, output func(buildprocess.Stream, string)) (buildProcess, error) { + selection := execution.selection() + remoteProcess := p.remote != nil && execution.Placement != core.ProcessPlacementUI + if remoteProcess { + // The host prepends these to its own login PATH. + selection.PathPrepend = nil + } + spec := buildprocess.Spec{ + Kind: processledger.KindBuild, Executable: execution.Executable, Arguments: arguments, + WorkingDirectory: directory, Environment: applyToolchainSelection(environment, selection), + } + if err := ctx.Err(); err != nil { + return nil, err + } + if !remoteProcess { + return buildprocess.Start(ctx, spec, output) + } + if core.RemoteWorkspaceOf(ctx) == nil { + return nil, errors.New("remote execution has no workspace attachment") + } + relativeDirectory, err := filepath.Rel(p.root, spec.WorkingDirectory) + if err != nil { + return nil, err + } + cwd, err := remoteRunDirectory(p.remote.binding.RemoteRoot(), filepath.ToSlash(relativeDirectory)) + if err != nil { + return nil, err + } + return buildprocess.StartRemote(ctx, ctx, a.kernel, core.RemoteProcessOpen{ + Argv: append([]string{spec.Executable}, spec.Arguments...), + ScopedCwd: cwd, + Environment: core.RemoteProcessEnvironmentLogin, + Env: spec.Environment, + PathPrepend: execution.PathPrepend, + Label: core.NewRemoteResourceLabel(string(spec.Kind), spec.Executable), + }, output) +} + +// captureWorkspaceConnection takes the attachment on the window thread, before an +// operation is queued. A disconnected project has no attachment to run through. +func captureWorkspaceConnection(p *project) (*core.RemoteWorkspaceConnection, bool) { + if p.remote == nil { + return nil, true + } + connection := p.remote.binding.CaptureConnection() + return connection, connection != nil +} + +// attachedWorkspaceContext binds a queued operation to the captured attachment. +func attachedWorkspaceContext(ctx context.Context, connection *core.RemoteWorkspaceConnection) context.Context { + if connection != nil { + return connection.Context(ctx) + } + return ctx +} + +// remoteBuildCandidate translates Core's planned candidate into a host lookup. +func (a *App) remoteBuildCandidate(ctx context.Context, p *project, candidate core.BuildExecutableCandidate) (buildExecution, bool, bool, error) { + request := core.RemoteExecutableRequest{} + terminal := candidate.Kind == "setting" + switch candidate.Kind { + case "setting": + request.Kind, request.Value = "program", candidate.Path + case "command": + request.Kind, request.Value = "program", candidate.Command + case "projectFile": + request.Kind, request.Root, request.Path = "projectFile", p.remote.binding.RemoteRoot(), candidate.Path + request.Requires = slices.Clone(candidate.Requires) + case "environment": + request.Kind, request.Variable, request.Path = "environment", candidate.Variable, candidate.Path + default: + return buildExecution{}, false, false, nil + } + if request.Kind == "program" && request.Value == "" { + return buildExecution{}, false, false, nil + } + executable, err := a.kernel.ResolveRemoteExecutable(ctx, request) + if err == nil && executable == "" && terminal { + err = errors.New(a.text.Build.ExecutableMissing) + } + execution := buildExecution{Executable: executable} + if terminal && executable != "" { + execution.PathPrepend = []string{path.Dir(executable)} + } + return execution, terminal, executable != "", err +} + +// buildScratch owns the private output location for one command until decoding +// is complete. A remote command receives package paths only after deployment. +type buildScratch struct { + state, output, packageDirectory string + release func() error +} + +func (a *App) prepareBuildScratch(ctx context.Context, p *project, instance buildInstance, purpose string) (buildScratch, error) { + cleanupCtx := context.WithoutCancel(ctx) + if p.remote == nil { + state := buildStateDirectory(a.plugins.Root, p.root, instance) + if err := os.MkdirAll(state, 0o700); err != nil { + return buildScratch{}, err + } + dir, err := os.MkdirTemp(state, purpose+"-") + if err != nil { + return buildScratch{}, err + } + return buildScratch{state: state, output: filepath.Join(dir, "output.json"), packageDirectory: instance.PackageDirectory, + release: func() error { + err := os.RemoveAll(dir) + if err != nil { + a.backgroundFailedIn(cleanupCtx, "build_scratch_cleanup", err) + } + return err + }, + }, nil + } + id := "build-" + rand.Text() + release := func() error { + ctx, cancel := context.WithTimeout(cleanupCtx, buildStopTimeout) + defer cancel() + err := a.kernel.ReleaseRemoteRunDirectory(ctx, id) + if err != nil { + a.backgroundFailedIn(ctx, "build_scratch_cleanup", remoteLogError(err)) + } + return err + } + dir, err := a.kernel.CreateRemoteRunDirectory(ctx, id) + if err != nil { + // Allocation can succeed on the host after the client cancels its wait. + return buildScratch{}, errors.Join(err, release()) + } + return buildScratch{state: dir, output: path.Join(dir, "output.json"), release: release}, nil +} + +func (a *App) captureWorkspaceBuildProcess(ctx context.Context, p *project, execution buildExecution, arguments []string, directory string, environment map[string]string, documentOnStdout bool, log func(string)) (buildCommandOutput, error) { + return collectBuildOutput(documentOnStdout, log, func(output func(buildprocess.Stream, string)) (buildProcess, error) { + return a.startBuildExecution(ctx, p, execution, arguments, directory, environment, output) + }) +} diff --git a/desktop/internal/workbench/remote_build_test.go b/desktop/internal/workbench/remote_build_test.go new file mode 100644 index 0000000000..0874a55c51 --- /dev/null +++ b/desktop/internal/workbench/remote_build_test.go @@ -0,0 +1,129 @@ +package workbench + +import ( + "context" + "encoding/json" + "errors" + "path/filepath" + "slices" + "sync" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" +) + +func TestRemoteBuildExecutionUsesScopedWorkingDirectory(t *testing.T) { + h, host, _, _ := remoteWorkspaceHarness(t) + p := h.openRemoteTestProject(t) + connection := p.remote.binding.CaptureConnection() + if connection == nil { + t.Fatal("the project did not capture the host connection") + } + host.setRuns(func(runs *remoteHostRuns) { + zero := 0 + runs.exit = core.RemoteProcessExit{ExitCode: &zero} + }) + ctx, cancel := context.WithTimeout(connection.Context(p.ctx), 5*time.Second) + defer cancel() + directory := filepath.Join(p.root, "nested", "src") + _, err := h.app.captureWorkspaceBuildProcess(ctx, p, buildExecution{Executable: "fixture-tool"}, nil, directory, nil, false, func(string) {}) + if err != nil { + t.Fatal(err) + } + opens, _, _, _, _ := host.hostRuns() + want := core.RemoteScopedDirectory{Root: remoteTestFolder, Path: "nested/src"} + if len(opens) != 1 || opens[0].Cwd != "" || opens[0].ScopedCwd == nil || *opens[0].ScopedCwd != want { + t.Fatalf("expected one scoped launch in %+v, got %+v", want, opens) + } +} + +type remoteBuildKernel struct { + *remoteHostKernel + firstStarted chan struct{} + releaseFirst chan struct{} +} + +func (k *remoteBuildKernel) ReadWorkspaceConfiguration(ctx context.Context, path string, _ int64) (*string, error) { + binding := core.RemoteWorkspaceOf(ctx) + if binding == nil || path != buildTeamOptionsFile { + return nil, errors.New("team build preferences must come from the remote workspace") + } + document := `{"version":1,"systems":{},"ignoredPaths":["remote-vendor/"]}` + return &document, nil +} + +func (k *remoteBuildKernel) ResolveStoredBuildOptions(ctx context.Context, team, local json.RawMessage) (core.BuildStoredOptions, error) { + if core.RemoteWorkspaceOf(ctx) != nil { + return core.BuildStoredOptions{}, errors.New("merging build preferences must run on the client") + } + return k.Client.ResolveStoredBuildOptions(ctx, team, local) +} + +func (k *remoteBuildKernel) DetectBuildSystemsWithOptions(ctx context.Context, root string, manifests []json.RawMessage, options core.BuildDetectOptions) (core.BuildDetection, error) { + binding := core.RemoteWorkspaceOf(ctx) + if binding == nil || root != binding.LocalRoot() || len(manifests) != 1 || !slices.Equal(options.IgnoredPaths, []string{"remote-vendor/"}) { + return core.BuildDetection{}, errors.New("detection did not receive the remote binding, plugin or team preferences") + } + session := binding.SessionID() + if session == "session-1" { + close(k.firstStarted) + select { + case <-ctx.Done(): + return core.BuildDetection{}, ctx.Err() + case <-k.releaseFirst: + } + } + return core.BuildDetection{Instances: []core.BuildInstance{{ + ID: session, PluginID: hotBuildPluginID, BuildSystemID: "hot-fixture", Root: ".", + ModelSource: "static", Model: json.RawMessage(`{"projects":[{"id":"app","name":"Remote App"}]}`), + }}}, nil +} + +func TestRemoteBuildDetectionUsesHostOptionsAndDiscardsOldSession(t *testing.T) { + h, host, timers, _ := remoteWorkspaceHarness(t) + p := h.openRemoteTestProject(t) + + kernel := &remoteBuildKernel{ + remoteHostKernel: host, + firstStarted: make(chan struct{}), + releaseFirst: make(chan struct{}), + } + releaseFirst := sync.OnceFunc(func() { close(kernel.releaseFirst) }) + defer releaseFirst() + h.app.kernel = kernel + service, err := pluginservice.Open(kernel, h.store, t.TempDir()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(service.Contexts.CloseAll) + h.app.plugins = service + + // Installing starts detection. Reconnect while its first answer is held, then + // deliver that answer after the replacement connection's model has been published. + h.app.installPluginFromFile(writeHotBuildPluginArchive(t, hotBuildPluginID, hotBuildPluginManifest), approvingPluginInstall(t)) + awaitValueWithin(t, h, kernelCallTimeout, kernel.firstStarted, "first remote build detection") + h.app.post(func(a *App) { a.loseRemote(p, "session-1", errRemoteSessionClosed) }) + h.await("the scheduled reconnection", func() bool { + return p.remote.session == "" && timers.live() == 1 + }) + // Drive only the reconnect timer so the first detection can arrive after the new model. + timers.take(t).run() + h.await("replacement connection's build model", func() bool { + return !p.build.loading && len(p.build.instances) == 1 && p.build.instances[0].ID == "session-2" + }) + releaseFirst() + h.settle() + if len(p.build.instances) != 1 || p.build.instances[0].ID != "session-2" { + t.Fatalf("old connection replaced the build instances: %+v", p.build.instances) + } + instance := p.build.instances[0] + if !instance.modelLoaded || len(instance.Model.Projects) != 1 || instance.Model.Projects[0].Name != "Remote App" { + t.Fatalf("the remote static model was not loaded: %+v", instance) + } + if p.runConfigs.generation == 0 || p.runConfigs.loading || p.runConfigs.failure != "" { + t.Fatalf("remote build detection did not resolve run configurations: generation %d, loading %v, failure %q", + p.runConfigs.generation, p.runConfigs.loading, p.runConfigs.failure) + } +} diff --git a/desktop/internal/workbench/remote_documents_test.go b/desktop/internal/workbench/remote_documents_test.go index bcb7716701..4da8a7dfcf 100644 --- a/desktop/internal/workbench/remote_documents_test.go +++ b/desktop/internal/workbench/remote_documents_test.go @@ -187,6 +187,40 @@ func TestRemoteWorkspaceEditsTheHostsFiles(t *testing.T) { } } +func TestScopedDocumentOpenDiscardsBytesFromAReplacedAttachment(t *testing.T) { + h, _, _, _ := remoteWorkspaceHarness(t) + p := h.openRemoteTestProject(t) + path := filepath.Join(p.root, "scoped.txt") + abandoned := filepath.Join(p.root, "abandoned.txt") + binding := p.remote.binding + session := binding.SessionID() + stale := binding.CaptureConnection() + readOld := func(context.Context, string, int64) ([]byte, error) { return []byte("old attachment\n"), nil } + h.app.openFileAtPositionWith(p, path, 0, 0, readOld, stale) + h.app.openFileWith(p, abandoned, readOld, stale) + + // Replace the attachment before the window applies the background read, + // even if the transport resumes with the same session identifier. + binding.Detach() + binding.Attach(session) + h.app.openFileAtPositionWith(p, path, 0, 0, func(context.Context, string, int64) ([]byte, error) { + return []byte("new attachment\n"), nil + }, binding.CaptureConnection()) + h.await("the pending reads to finish", func() bool { + return p.docs.opening[path] == nil && p.docs.opening[abandoned] == nil + }) + if p.docs.byPath(abandoned) != nil { + t.Fatal("the editor opened bytes from the replaced attachment") + } + d := p.docs.byPath(path) + if d == nil { + t.Fatal("the current attachment could not open the document") + } + if text, _ := d.view.Text(); string(text) != "new attachment\n" { + t.Fatalf("opened %q, want the current attachment's bytes", text) + } +} + // A host file that cannot be read or saved says why in the user's words: it is missing, not a // regular file, not permitted, larger than the host takes, or the connection closed. A closed // connection connects again on its own and then compares the documents with the host, so a change diff --git a/desktop/internal/workbench/remote_git_test.go b/desktop/internal/workbench/remote_git_test.go index de1d237bca..2194a9db5e 100644 --- a/desktop/internal/workbench/remote_git_test.go +++ b/desktop/internal/workbench/remote_git_test.go @@ -2,6 +2,7 @@ package workbench import ( "context" + "errors" "os" "path/filepath" "slices" @@ -460,37 +461,45 @@ func TestRemoteWorkspaceSaysItsRepositoryStartsAbove(t *testing.T) { sessionKept(t, logger, p, "session-1") } -// What runs the project's code on this computer refuses in a trusted remote workspace too, and -// says so: Debug, the current file's run, a run that is not a configuration, the tests and the -// build tasks, and the Debug tool window. Run configurations start on the host -// (remote_run_test.go). -func TestRemoteWorkspaceRefusesToRunItsCode(t *testing.T) { +// A trusted remote workspace with no executable entry reports the same missing selections as a +// local workspace and keeps its SSH session attached. +func TestRemoteWorkspaceWithoutAnExecutionEntry(t *testing.T) { h, k, _, logger := remoteWorkspaceHarness(t) lang := h.app.language() k.trustAtHost(core.WorkspaceTrusted, ".") p := h.openRemoteTestProject(t) h.awaitRemoteGit(p) - h.app.titleStart(p, titleActionDebug) - h.app.performCurrentFileAction(p, titleActionRun) - h.app.startRun(p, "run", func(*App, *project) { t.Error("a run started") }) + h.app.titleStart(p, titleActionRun) + missingEntrypoint := i18n.Shared(lang, "desktop.title.currentFileNotRunnable") + h.await("the toolbar's missing entrypoint notice", func() bool { + if countFailures(logger, "title_run") != 0 { + for _, notice := range h.app.notifications.list { + t.Logf("notification: %s", notice.text) + } + t.Fatal("the toolbar could not decide what to run") + } + return h.notified(missingEntrypoint) + }) + if operation, err := h.app.startRunConfiguration(p, "run"); operation != nil || err == nil { + t.Fatalf("unknown run configuration: operation %v, error %v", operation != nil, err) + } else if refusal, ok := errors.AsType[*buildRefusal](err); !ok || refusal.code != refusalNotFound { + t.Fatalf("unknown run configuration returned %v, want not found", err) + } h.app.startTests(p, testSelection{}) - if _, err := h.app.runBuildTask(p, "project", "target", "task", nil); err == nil { + if p.tests.running || !h.notified(h.app.text.Tests.NoSystems) { + t.Fatal("the test request did not report that no test system was available") + } + if operation, err := h.app.runBuildTask(p, "project", "target", "task", nil); operation != nil || err == nil { t.Fatal("a build task started") } h.settle() - for _, operation := range []string{"title_run", "run_current_file", "run_start", "test_start", "build_task"} { - if !rejected(logger, operation, "remote_workspace") { - t.Fatalf("%s was not logged as refused", operation) - } - } - localOnly := i18n.Shared(lang, "desktop.remote.workspace.localOnly") - if !h.notified(localOnly) || p.trust.asking { - t.Fatal("the refusal was not notified, or the trusted workspace asked to be trusted") + if !rejected(logger, "title_run_current_file", "no_entrypoint") || p.trust.asking { + t.Fatal("the missing entrypoint was not logged, or the trusted workspace asked to be trusted") } - h.app.openToolWindow(itemDebug) + h.app.openToolWindow(itemRun) h.redraw() - if !h.showsWrapped(localOnly) { - t.Fatal("the Debug tool window does not say it does not work here") + if !h.showsWrapped(h.app.text.Run.Empty) || p.build.active() { + t.Fatal("the Run tool window did not stay empty") } sessionKept(t, logger, p, "session-1") } diff --git a/desktop/internal/workbench/remote_native_settings_ssh_test.go b/desktop/internal/workbench/remote_native_settings_ssh_test.go new file mode 100644 index 0000000000..d159aa903d --- /dev/null +++ b/desktop/internal/workbench/remote_native_settings_ssh_test.go @@ -0,0 +1,298 @@ +//go:build lithe_remote_e2e && (darwin || windows) + +package workbench + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "path" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" + "github.com/1lck/Lithe-IDEA/desktop/internal/plugininstall" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginsettings" + "github.com/1lck/Lithe-IDEA/desktop/internal/plugintrust" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" +) + +func TestNativeToolSettingsUseTheSSHHost(t *testing.T) { + host := os.Getenv("LITHE_TEST_VARIANT_SSH_HOST") + if host == "" { + t.Skip("set LITHE_TEST_VARIANT_SSH_HOST to a disposable Linux OpenSSH target") + } + const id = "io.github.example.remote-native-settings-fixture" + const name = "Native settings SSH fixture" + const action = "nativeConfig" + client := core.NewClient() + hostConnection, connected := connectVariantSSH(t, client, host) + session := connected.Session.ID + platform := connected.Host.PluginPlatform() + if platform == nil || platform.OS != "linux" || !path.IsAbs(connected.Session.HomeDirectory) { + t.Fatalf("the fixture requires a Linux session with a reported home directory: %+v", connected.Host) + } + arch := linuxSSHFixtureArch(t, connected) + helperFile := buildLinuxSSHFixtureFor(t, "settings-helper", "./testdata/remote_settings_helper", arch) + helper, err := os.ReadFile(helperFile) + if err != nil { + t.Fatal(err) + } + + ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) + defer cancel() + directory, err := client.RemoteTempDirectory(ctx, session, "lithe-native-settings-test") + if err != nil || !path.IsAbs(directory) { + t.Fatalf("create host fixture: path=%q, err=%v", directory, err) + } + homeName := ".lithe-native-settings-" + rand.Text() + homeFile := path.Join(connected.Session.HomeDirectory, homeName) + defer func() { + cleanup, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + if err := client.RemoteHostRequest(cleanup, session, "fs.remove", map[string]string{"path": homeFile}, nil); err != nil && !missingSSHFixture(err) { + t.Errorf("remove test home file: %v", err) + } + if err := client.RemoteRemove(cleanup, session, directory, true); err != nil { + t.Errorf("release host fixture: %v", err) + } + }() + projectFile, defaultsFile := path.Join(directory, "project.fixture"), path.Join(directory, "defaults.fixture") + for file, value := range map[string]string{projectFile: "initial-project", defaultsFile: "initial-default"} { + if _, saved, err := client.RemoteWriteFile(ctx, session, file, []byte(value), nil); err != nil || !saved { + t.Fatalf("write host fixture: saved=%v, err=%v", saved, err) + } + } + + root := filepath.Join(t.TempDir(), "workspace") + writeFixture(t, root, map[string]string{"project.fixture": "desktop-sentinel"}) + preferences := t.TempDir() + writeFixture(t, preferences, map[string]string{settingsFile: `{"theme":"dark"}`}) + h := newHarnessWithOptions(t, Options{ + Kernel: &testKernel{Client: client}, PluginKernel: client, PluginRoot: t.TempDir(), + Store: store.At(preferences), Languages: []string{"en"}, + }) + installNativeSettingsFixture(t, h, ctx, id, action, homeName, helper, *platform) + h.app.openRemoteProject(remoteTarget{ + connectionID: "native-settings-ssh", name: name, host: hostConnection, platform: platform, + session: *connected.Session, remoteRoot: directory, root: root, trusted: true, + }) + project := h.app.project + if project == nil || project.remote == nil { + t.Fatal("the SSH project did not open") + } + settings := pluginSettingsSources{app: h.app} + editor, err := settings.Load(ctx, id, i18n.English) + if err != nil { + t.Fatalf("open plugin settings: %v", err) + } + if editor.Snapshot.ProjectConnectionName() != name { + t.Fatalf("connection name = %q, want %q", editor.Snapshot.ProjectConnectionName(), name) + } + load := func() pluginsettings.SourceEditor { + t.Helper() + result, err := settings.Action(ctx, editor, action, true) + if err != nil || result.Sources == nil || !result.Sources.IsRemote() { + t.Fatalf("load native settings from SSH: %v", err) + } + return *result.Sources + } + checkFile := func(file, want string) { + t.Helper() + data, _, err := client.RemoteReadFile(ctx, session, file) + if err != nil || string(data) != want { + t.Fatalf("read host fixture %q: got %q, want %q, err=%v", path.Base(file), data, want, err) + } + } + checkMissing := func(file string) { + t.Helper() + if _, err := client.RemoteStat(ctx, session, file); !missingSSHFixture(err) { + t.Fatalf("fixture path should be absent: err=%v", err) + } + } + checkStaging := func(marker string, count int, operation string) { + t.Helper() + data, _, err := client.RemoteReadFile(ctx, session, path.Join(directory, marker)) + if err != nil { + t.Fatalf("read helper marker: %v", err) + } + lines := strings.Split(string(data), "\n") + if operation != "" { + if lines[0] != operation { + t.Fatalf("read operation = %q, want %q", lines[0], operation) + } + lines = lines[1:] + } + if len(lines) != count { + t.Fatalf("staging paths = %d, want %d", len(lines), count) + } + for _, file := range lines { + if !path.IsAbs(file) { + t.Fatal("the helper did not receive an absolute staging path") + } + checkMissing(path.Dir(file)) + } + } + edit := func(source, text string) core.SourceSettingsEdits { + return core.SourceSettingsEdits{SourceID: source, Values: map[string]core.SourceSettingInput{"name": {Text: text}}} + } + + source := load() + checkMissing(homeFile) + wantPaths := map[string]string{"project": projectFile, "user": homeFile, "defaults": defaultsFile} + if len(source.State.Snapshot.Sources) != len(wantPaths) { + t.Fatalf("expected %d projected sources", len(wantPaths)) + } + for _, row := range source.State.Snapshot.Sources { + if source.DisplayPath(row) != wantPaths[row.ID] || row.Writable != (row.ID != "defaults") { + t.Fatalf("wrong host path or editability for %q: %q, writable=%v", row.ID, source.DisplayPath(row), row.Writable) + } + } + if _, err := settings.SaveSources(ctx, editor, action, source, []core.SourceSettingsEdits{edit("defaults", "blocked")}); err == nil { + t.Fatal("the settings worker accepted an edit to a read-only source") + } + checkMissing(path.Join(directory, "last-edit")) + source, err = settings.SaveSources(ctx, editor, action, source, []core.SourceSettingsEdits{ + edit("project", "saved-project"), edit("user", "saved-user"), + }) + if err != nil { + t.Fatalf("save remote settings: %v", err) + } + if source.State.Inputs["project"]["name"].Text != "saved-project" || source.State.Inputs["user"]["name"].Text != "saved-user" { + t.Fatal("the settings worker did not return the saved values from the host") + } + checkFile(projectFile, "saved-project") + checkFile(homeFile, "saved-user") + checkFile(defaultsFile, "initial-default") + checkStaging("last-read", 1, "readAfterSave") + checkStaging("last-edit", 2, "") + + if _, err := settings.SaveSources(ctx, editor, action, source, []core.SourceSettingsEdits{edit("project", "bad-receipt")}); err == nil || errors.Is(err, pluginsettings.ErrSourcesCommitted) { + t.Fatalf("a malformed receipt was not refused before publication: %v", err) + } + checkStaging("last-edit", 2, "") + checkFile(projectFile, "saved-project") + _, version, err := client.RemoteReadFile(ctx, session, projectFile) + if err != nil { + t.Fatalf("read project settings revision: %v", err) + } + if _, saved, err := client.RemoteWriteFile(ctx, session, projectFile, []byte("external-project"), &version); err != nil || !saved { + t.Fatalf("write external edit: saved=%v, err=%v", saved, err) + } + if _, err := settings.SaveSources(ctx, editor, action, source, []core.SourceSettingsEdits{edit("project", "old-projection")}); !errors.Is(err, configfile.ErrConflict) { + t.Fatalf("save over external edit: %v", err) + } + source = load() + project.remote.binding.Detach() + project.remote.binding.Attach(session) + if _, err := settings.SaveSources(ctx, editor, action, source, []core.SourceSettingsEdits{edit("user", "old-connection")}); !errors.Is(err, configfile.ErrConflict) { + t.Fatalf("save from previous attachment: %v", err) + } + checkFile(projectFile, "external-project") + checkFile(homeFile, "saved-user") + if data, err := os.ReadFile(filepath.Join(root, "project.fixture")); err != nil || string(data) != "desktop-sentinel" { + t.Fatalf("remote settings changed the desktop fixture: %q, %v", data, err) + } +} + +func missingSSHFixture(err error) bool { + var failure *core.Error + return errors.As(err, &failure) && failure.Code == core.CodeWorkspaceNotFound +} + +func installNativeSettingsFixture(t *testing.T, h *harness, ctx context.Context, id, action, homeName string, helper []byte, platform core.RemotePlatform) { + t.Helper() + const version = "1.0.0" + const helperPath = "bin/settings-helper" + const repository = "https://github.com/example/native-settings" + const indexURL = "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-index.json" + const localURL = repository + "/releases/download/1.0.0/desktop.zip" + const remoteURL = repository + "/releases/download/1.0.0/linux.zip" + const requires = `{"backend":0,"languages":0,"settings":0,"sourceSettings":2}` + manifest := fmt.Sprintf(`{ + "schemaVersion":0, "pluginAPIVersion":0, "id":%q, "version":%q, "displayName":"Native settings fixture", + "requires":%s, "vendor":{"id":"io.github.example","displayName":"Fixture","signatureRequirement":"none"}, + "permissions":["backend.launch","workspace.metadata"], + "languages":[{"id":"native-fixture","displayName":"Native fixture","fileExtensions":["native-fixture"]}], + "backend":{"launch":{"kind":"packaged","path":"bin/backend"}}, + "settingActions":[{"id":%q,"title":"Native fixture settings","function":"fixture.read", + "sourceEditor":{"editFunction":"fixture.edit","remoteHelper":{"executable":%q,"arguments":[%q]}}}] + }`, id, version, requires, action, helperPath, homeName) + archive, localDigest := pluginProgramVariantArchive(t, id, manifest, helperPath, []byte("#!/bin/sh\nexit 1\n")) + linuxArchive, remoteDigest := pluginProgramVariantArchive(t, id, manifest, helperPath, helper) + linuxPlatform := "linux-arm64" + if platform.Arch == "x86_64" { + linuxPlatform = "linux-x64" + } + index := fmt.Sprintf(`{"schemaVersion":0,"plugins":[{ + "id":%q,"name":"Native settings fixture","author":"Fixture","repository":%q, + "description":"Fixture for remote tool settings.","license":"MIT","versions":[{ + "version":%q,"pluginAPIVersion":0,"releaseDate":"2026-10-01","requires":%s,"downloads":[ + {"platforms":[%q],"downloadURL":%q,"sha256":%q}, + {"platforms":[%q],"downloadURL":%q,"sha256":%q} + ]}]}]}`, id, repository, version, requires, marketplace.CurrentPlatform(), localURL, localDigest, linuxPlatform, remoteURL, remoteDigest) + service := h.app.plugins + service.RuntimeDownloader = marketplace.NewArchiveDownloader(&http.Client{ + Transport: pluginArchiveTransport(func(request *http.Request) (*http.Response, error) { + var data []byte + switch request.URL.String() { + case indexURL: + data = []byte(index) + case remoteURL: + data = linuxArchive + default: + return nil, fmt.Errorf("unexpected fixture request to %s", request.URL) + } + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), + Body: io.NopCloser(bytes.NewReader(data)), ContentLength: int64(len(data)), Request: request}, nil + }), + }) + file := filepath.Join(t.TempDir(), "desktop.zip") + if err := os.WriteFile(file, archive, 0o600); err != nil { + t.Fatal(err) + } + plan, err := h.app.preparePlugin(ctx, plugininstall.Request{ + ArchivePath: file, Root: service.Root, Source: plugintrust.Marketplace, + ArchiveSHA256: localDigest, MarketplaceIndexURL: indexURL, MarketplaceRepository: repository, + ExpectedID: id, ExpectedVersion: version, + }) + if err != nil { + t.Fatalf("prepare native settings fixture: %v", err) + } + defer func() { + if err := service.Installer.Discard(plan); err != nil { + t.Errorf("discard native settings package staging: %v", err) + } + }() + reviewed := false + for _, program := range plan.Review.NewPrograms { + var entry struct { + Kind string `json:"kind"` + Executable string `json:"executable"` + } + if err := json.Unmarshal(program, &entry); err != nil { + t.Fatal(err) + } + reviewed = reviewed || (entry.Kind == "settingsHelper" && entry.Executable == helperPath) + } + if !plan.NeedsApproval() || !reviewed { + t.Fatal("the helper was not included in the installation approval") + } + if _, err := service.Installer.Commit(plan); err != nil { + t.Fatal(err) + } + if _, err := service.Manager.EnableInstalled(id); err != nil { + t.Fatal(err) + } +} diff --git a/desktop/internal/workbench/remote_plugin_variant_ssh_test.go b/desktop/internal/workbench/remote_plugin_variant_ssh_test.go new file mode 100644 index 0000000000..0e6d1b2291 --- /dev/null +++ b/desktop/internal/workbench/remote_plugin_variant_ssh_test.go @@ -0,0 +1,491 @@ +//go:build lithe_remote_e2e && (darwin || windows) + +package workbench + +import ( + "archive/zip" + "bytes" + "context" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "os/exec" + "path" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" + "github.com/1lck/Lithe-IDEA/desktop/internal/plugininstall" + "github.com/1lck/Lithe-IDEA/desktop/internal/plugintrust" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteplaceholder" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteserver" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" +) + +// Run with -tags lithe_remote_e2e, a staged server, and +// LITHE_TEST_VARIANT_SSH_HOST set to a disposable Linux x86_64 host. The SSH +// configuration may be supplied by LITHE_TEST_VARIANT_SSH_PROGRAM. +func TestEditorDeploysPackagedLanguageServerToLinuxX64OverSSH(t *testing.T) { + host := os.Getenv("LITHE_TEST_VARIANT_SSH_HOST") + if host == "" { + t.Skip("set LITHE_TEST_VARIANT_SSH_HOST to a disposable Linux x86_64 OpenSSH target") + } + const id = "io.github.example.remote-variant-fixture" + const version = "1.0.0" + const programPath = "bin/server" + const repository = "https://github.com/example/remote-variant" + const indexURL = "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-index.json" + const remoteURL = repository + "/releases/download/1.0.0/linux-x64.zip" + const runtimeURL = "https://runtimes.example.test/runner-linux-x64.zip" + const diagnostic = "Packaged language server running on linux/amd64 via managed runtime" + runtimeArchive, runtimeDigest := writeVariantArchive(t, "runner", []variantArchiveFile{ + {"bin/runner", []byte("#!/bin/sh\nif [ \"$1\" = --version ]; then echo 'Runner 1'; exit 0; fi\nexport LITHE_TEST_MANAGED_RUNNER=1\nexec \"$@\"\n"), 0o755}, + }) + manifest := fmt.Sprintf(`{ + "schemaVersion": 0, "pluginAPIVersion": 0, "id": %q, + "displayName": "Remote Variant Fixture", "version": %q, + "requires": {"backend": 0, "languages": 0, "languageServers": 0, "managedRuntimes": 0, "toolDefinitions": 0}, + "vendor": {"id": "io.github.example", "displayName": "Example", "signatureRequirement": "none"}, + "permissions": ["backend.launch", "languageServer.launch", "runtimes.install"], + "backend": {"launch": {"kind": "packaged", "path": "bin/backend"}}, + "activationEvents": ["onLanguage:example"], + "languages": [{"id": "example", "displayName": "Example", "fileExtensions": ["example"]}], + "languageServers": [{"languageID": "example", "remote": "supported", + "launch": {"kind": "runtime", "tool": "fixture-runner", "minimumVersion": "1", "entry": %q}}], + "requiresTools": ["fixture-runner"], + "toolDefinitions": [{ + "id": "fixture-runner", "displayName": "Fixture runner", "icon": {"host": "plugin"}, + "executableLayouts": [{"path": "bin/runner"}], + "executables": [{"id": "shell", "kind": "command", "command": "fixture-runner"}], + "version": {"arguments": ["--version"], "pattern": "Runner (\\d+)"}, + "commands": ["fixture-runner"], + "launch": ["${executable}", "${entry}", "${arguments}"] + }], + "managedRuntimes": { + "resolve": {"function": "fixture.resolve"}, + "dependencies": [{"id": "runner", "tool": "fixture-runner", "version": "1", + "artifacts": [{"os": "linux", "arch": "x86_64", "url": %q, "sha256": %q, + "archive": "zip", "stripPrefix": "runner", "executable": "bin/runner"}]}] + } + }`, id, version, programPath, runtimeURL, runtimeDigest) + + linuxProgram := buildLinuxVariantLanguageServer(t) + localArchive, localDigest := pluginProgramVariantArchive(t, id, manifest, programPath, []byte("#!/bin/sh\nexit 1\n")) + linuxArchive, linuxDigest := pluginProgramVariantArchive(t, id, manifest, programPath, linuxProgram) + index := fmt.Sprintf(`{ + "schemaVersion": 0, + "plugins": [{ + "id": %q, "name": "Remote Variant Fixture", "author": "Example", + "repository": %q, "description": "Tests exact remote variants.", "license": "MIT", + "versions": [ + {"version": "2.0.0", "pluginAPIVersion": 0, "releaseDate": "2026-10-01", + "requires": {"backend": 0, "languageServers": 0, "languages": 0, "managedRuntimes": 0, "toolDefinitions": 0}, + "downloads": [{"platforms": ["linux-x64"], "downloadURL": %q, "sha256": %q}]}, + {"version": %q, "pluginAPIVersion": 0, "releaseDate": "2026-10-01", + "requires": {"backend": 0, "languageServers": 0, "languages": 0, "managedRuntimes": 0, "toolDefinitions": 0}, + "downloads": [ + {"platforms": [%q], "downloadURL": %q, "sha256": %q}, + {"platforms": ["linux-x64"], "downloadURL": %q, "sha256": %q} + ]} + ] + }] + }`, id, repository, repository+"/releases/download/2.0.0/linux-x64.zip", strings.Repeat("5", 64), + version, marketplace.CurrentPlatform(), repository+"/releases/download/1.0.0/desktop.zip", localDigest, remoteURL, linuxDigest) + + client := core.NewClient() + connection, connected := connectVariantSSH(t, client, host) + session := connected.Session.ID + platform := connected.Host.PluginPlatform() + if platform == nil || platform.OS != "linux" || platform.Arch != "x86_64" { + t.Fatalf("target = %+v, want Linux x86_64", connected.Host) + } + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + var directory struct { + Path string `json:"path"` + } + if err := client.RemoteHostRequest(ctx, session, "fs.createRunDirectory", map[string]string{"directoryId": "language-variant"}, &directory); err != nil || !path.IsAbs(directory.Path) { + t.Fatalf("create remote fixture directory: path=%q, err=%v", directory.Path, err) + } + const filename = "source.example" + if _, saved, err := client.RemoteWriteFile(ctx, session, path.Join(directory.Path, filename), []byte("example\n"), nil); err != nil || !saved { + t.Fatalf("write remote fixture: saved=%v, err=%v", saved, err) + } + + settings := t.TempDir() + writeFixture(t, settings, map[string]string{settingsFile: `{"theme":"dark"}`}) + h := newHarnessWithOptions(t, Options{ + Kernel: &testKernel{Client: client}, PluginKernel: client, PluginRoot: t.TempDir(), + Store: store.At(settings), Languages: []string{"en"}, + }) + service := h.app.plugins + if service == nil { + t.Fatal("the plugin service did not open") + } + service.RuntimeDownloader = marketplace.NewArchiveDownloader(&http.Client{ + Transport: pluginArchiveTransport(func(request *http.Request) (*http.Response, error) { + var data []byte + switch request.URL.String() { + case indexURL: + data = []byte(index) + case remoteURL: + data = linuxArchive + case runtimeURL: + data = runtimeArchive + default: + return nil, fmt.Errorf("unexpected marketplace request to %s", request.URL) + } + return &http.Response{ + StatusCode: http.StatusOK, Header: make(http.Header), + Body: io.NopCloser(bytes.NewReader(data)), ContentLength: int64(len(data)), Request: request, + }, nil + }), + }) + archiveFile := filepath.Join(t.TempDir(), "desktop.zip") + if err := os.WriteFile(archiveFile, localArchive, 0o600); err != nil { + t.Fatal(err) + } + plan, err := h.app.preparePlugin(ctx, plugininstall.Request{ + ArchivePath: archiveFile, Root: service.Root, Source: plugintrust.Marketplace, + ArchiveSHA256: localDigest, MarketplaceIndexURL: indexURL, MarketplaceRepository: repository, + ExpectedID: id, ExpectedVersion: version, + }) + if err != nil { + var rejection *core.MarketplaceRejection + if errors.As(err, &rejection) { + t.Fatalf("prepare plugin at %q: %v", rejection.Field, err) + } + t.Fatalf("prepare plugin: %v", err) + } + t.Cleanup(func() { + if err := service.Installer.Discard(plan); err != nil { + t.Errorf("discard installation staging: %v", err) + } + }) + installed, err := service.Installer.Commit(plan) + if err != nil { + t.Fatal(err) + } + if _, err := service.Manager.EnableInstalled(id); err != nil { + t.Fatal(err) + } + cancel() + h.app.reloadPluginLanguages() + + anchor := filepath.Join(t.TempDir(), remoteplaceholder.AnchorName) + if err := remoteplaceholder.Ensure(anchor); err != nil { + t.Fatal(err) + } + const connectionID = "language-variant-ssh" + root := remoteplaceholder.Root(anchor, connectionID, directory.Path) + h.app.openRemoteProject(remoteTarget{ + connectionID: connectionID, name: "Language variant SSH test", host: connection, + session: *connected.Session, platform: platform, remoteRoot: directory.Path, root: root, trusted: true, + }) + project := h.app.project + if project == nil || project.remote == nil { + t.Fatal("the SSH project did not open") + } + file := filepath.Join(root, filename) + h.app.openFileAt(project, file, 1) + awaitStateWithin(t, h, time.Minute, diagnostic, func() bool { + for _, server := range h.app.lspFailedServers() { + if server.displayID() == id || server.languageID == "example" { + t.Fatalf("start remote language server: %s; logs: %+v", server.message, server.logs) + } + } + return problemMessagesContain(h.app, diagnostic) && diagnosticsForFile(h.app, file) > 0 + }) + t.Log("The managed Linux x86_64 runtime started the selected language server and the editor received diagnostics") + + verify, cancelVerify := context.WithTimeout(project.ctx, 15*time.Second) + defer cancelVerify() + expected, err := client.PlanMarketplaceRemoteDeployment(verify, core.MarketplaceDeploymentRequest{ + Manifest: plan.Manifest, Target: *platform, RequiredPaths: []string{programPath}, ArchiveSHA256: linuxDigest, + }) + if err != nil { + t.Fatalf("plan expected deployment: %v", err) + } + key := core.RemotePluginDeployment{ + PluginID: id, Version: version, SHA256: expected.SHA256, + } + deployment, err := client.LookupRemotePluginDeployment(verify, key) + if err != nil || !path.IsAbs(deployment) { + t.Fatalf("lookup same-version deployment by archive checksum: path=%q, err=%v", deployment, err) + } + program := path.Join(deployment, programPath) + metadata, err := client.RemoteStat(verify, session, program) + if err != nil || metadata.Mode != 0o500 { + t.Fatalf("remote program mode = %#o, want 0500; err=%v", metadata.Mode, err) + } + data, _, err := client.RemoteReadFile(verify, session, program) + if err != nil || sha256.Sum256(data) != sha256.Sum256(linuxProgram) { + t.Fatalf("deployed binary differs from the verified Linux variant: bytes=%d, err=%v", len(data), err) + } + localProgram, err := os.ReadFile(filepath.Join(installed.Path, programPath)) + if err != nil || string(localProgram) != "#!/bin/sh\nexit 1\n" { + t.Fatalf("desktop plugin changed: err=%v", err) + } + if err := service.Uninstall(verify, id, nil); err != nil { + t.Fatalf("uninstall the plugin and stop its language server: %v", err) + } + cancelVerify() + h.app.closeProject() + awaitStateWithin(t, h, 15*time.Second, "the initial workspace to close and release its deployment lease", func() bool { + return h.app.project == nil && !h.app.closingProject + }) + _, reconnected := connectVariantSSH(t, client, host) + binding := core.NewRemoteWorkspace(root, directory.Path, nil) + binding.Attach(reconnected.Session.ID) + cleanup, cancelCleanup := context.WithTimeout(binding.CaptureConnection().Context(context.Background()), 15*time.Second) + defer cancelCleanup() + if _, err := client.RemoteStat(cleanup, reconnected.Session.ID, program); err != nil { + t.Fatalf("the published program was missing before the installed-version sweep: %v", err) + } + if err := service.SweepRemoteDeployments(cleanup); err != nil { + t.Fatalf("reconcile the remote deployments against the desktop installations: %v", err) + } + if got, err := client.LookupRemotePluginDeployment(cleanup, key); err != nil || got != "" { + t.Fatalf("the uninstalled plugin's deployment remained after the sweep: path=%q, err=%v", got, err) + } +} + +// Exercises the same settings worker used by the preferences window over SSH. +func TestProjectPluginSettingsUseTheSSHHost(t *testing.T) { + host := os.Getenv("LITHE_TEST_VARIANT_SSH_HOST") + if host == "" { + t.Skip("set LITHE_TEST_VARIANT_SSH_HOST to a disposable Linux OpenSSH target") + } + const id = "io.github.example.remote-project-settings-fixture" + client := core.NewClient() + connection, connected := connectVariantSSH(t, client, host) + session := connected.Session.ID + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + directory, err := client.RemoteTempDirectory(ctx, session, "lithe-project-settings-test") + if err != nil || !path.IsAbs(directory) { + t.Fatalf("create remote settings fixture: path=%q, err=%v", directory, err) + } + defer func() { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := client.RemoteRemove(ctx, session, directory, true); err != nil { + t.Errorf("release SSH settings fixture: %v", err) + } + }() + manifest := fmt.Sprintf(`{ + "schemaVersion":0,"pluginAPIVersion":0,"id":%q, + "displayName":"Remote settings fixture","version":"1.0.0", + "vendor":{"id":"io.github.example","displayName":"Fixture","signatureRequirement":"none"}, + "requires":{"languageServers":0,"languages":0,"settings":0}, + "permissions":["languageServer.launch"], + "activationEvents":["onLanguage:settings-fixture"], + "languages":[{"id":"settings-fixture","displayName":"Settings fixture","fileExtensions":["settings-fixture"]}], + "languageServers":[{"languageID":"settings-fixture","remote":"unsupported","launch":{"kind":"systemCommand","commands":["settings-fixture-lsp"]}}], + "settings":[{"id":"flag","type":"boolean","title":"Flag","default":true,"scope":"project","effect":"reload"}] + }`, id) + pluginRoot := t.TempDir() + writeFixture(t, pluginRoot, map[string]string{filepath.Join(id, "1.0.0", "plugin.json"): manifest}) + clientSettings := t.TempDir() + writeFixture(t, clientSettings, map[string]string{settingsFile: `{"theme":"dark"}`}) + h := newHarnessWithOptions(t, Options{ + Kernel: &testKernel{Client: client}, PluginKernel: client, PluginRoot: pluginRoot, + Store: store.At(clientSettings), Languages: []string{"en"}, + }) + if _, err := h.app.plugins.Manager.EnableInstalled(id); err != nil { + t.Fatal(err) + } + // Use a writable decoy here to detect accidental client-side writes. + // Production workspace roots are under a read-only regular-file anchor. + const connectionID = "project-settings-ssh" + root := filepath.Join(t.TempDir(), "workspace") + h.app.openRemoteProject(remoteTarget{ + connectionID: connectionID, name: "Settings SSH fixture", host: connection, + session: *connected.Session, remoteRoot: directory, root: root, trusted: true, + }) + project := h.app.project + if project == nil || project.remote == nil { + t.Fatal("the SSH project did not open") + } + localFile := filepath.Join(root, ".lithe", "plugin-settings.json") + writeFixture(t, root, map[string]string{filepath.Join(".lithe", "plugin-settings.json"): "local sentinel"}) + settings := pluginSettingsSources{app: h.app} + editor, err := settings.Load(ctx, id, i18n.English) + if err != nil { + t.Fatal(err) + } + edits := []core.PluginSettingEdit{{ID: "flag", Value: json.RawMessage("false")}} + result, err := settings.Save(ctx, editor, "project", edits) + if err != nil || !result.Committed || result.Readback == nil { + t.Fatalf("save to SSH host: committed=%v, readback=%v, err=%v", result.Committed, result.Readback != nil, err) + } + effective := result.Readback.State.Rows[0].Effective + if string(effective.Value) != "false" || effective.Source != "project" { + t.Fatalf("read-back used the wrong source: %+v", effective) + } + hostFile := path.Join(directory, ".lithe", "plugin-settings.json") + content, version, err := client.RemoteReadFile(ctx, session, hostFile) + var preferences map[string]map[string]json.RawMessage + if err != nil || json.Unmarshal(content, &preferences) != nil || string(preferences[id]["flag"]) != "false" { + t.Fatalf("saved preference on the SSH host: %q, %v", content, err) + } + reloaded, err := settings.Load(ctx, id, i18n.English) + if err != nil { + t.Fatal(err) + } + external := bytes.Replace(content, []byte("false"), []byte("true"), 1) + if _, saved, err := client.RemoteWriteFile(ctx, session, hostFile, external, &version); err != nil || !saved { + t.Fatalf("external host change: saved=%v, err=%v", saved, err) + } + if result, err := settings.Save(ctx, reloaded, "project", []core.PluginSettingEdit{{ID: "flag", Value: json.RawMessage("true")}}); result.Committed || !errors.Is(err, configfile.ErrConflict) { + t.Fatalf("stale save: committed=%v, err=%v", result.Committed, err) + } + current, err := settings.Load(ctx, id, i18n.English) + if err != nil { + t.Fatal(err) + } + // Reattaching the same session ID still invalidates the older editor. + project.remote.binding.Detach() + project.remote.binding.Attach(session) + if result, err := settings.Save(ctx, current, "project", edits); result.Committed || !errors.Is(err, configfile.ErrConflict) { + t.Fatalf("old attachment save: committed=%v, err=%v", result.Committed, err) + } + current, err = settings.Load(ctx, id, i18n.English) + if err != nil { + t.Fatal(err) + } + if result, err := settings.Save(ctx, current, "global", edits); err != nil || !result.Committed || result.Readback == nil { + t.Fatalf("save client preference: committed=%v, readback=%v, err=%v", result.Committed, result.Readback != nil, err) + } + after, _, err := client.RemoteReadFile(ctx, session, hostFile) + if err != nil || !bytes.Equal(after, external) { + t.Fatalf("global or rejected save changed the host document: %q, %v", after, err) + } + if data, err := os.ReadFile(localFile); err != nil || string(data) != "local sentinel" { + t.Fatalf("remote preference used the client placeholder: %q, %v", data, err) + } +} + +func connectVariantSSH(t *testing.T, client *core.Client, host string) (remoteHost, core.RemoteConnectResult) { + t.Helper() + bundle, err := remoteserver.Staged(os.Getenv("LITHE_REMOTE_SERVER_STAGE")) + if err != nil { + t.Fatal(err) + } + builds := make([]core.RemoteServerBuild, 0, len(bundle.Builds)) + for _, build := range bundle.Builds { + builds = append(builds, core.RemoteServerBuild{Target: build.Target, Path: build.Path, SHA256: build.SHA256}) + } + connection := remoteHost{ssh: core.SSHConnection{Host: host}} + request := connection.request(builds, bundle.Version) + request.InstallRoot = os.Getenv("LITHE_TEST_VARIANT_SSH_INSTALL_ROOT") + if ssh := os.Getenv("LITHE_TEST_VARIANT_SSH_PROGRAM"); ssh != "" { + data, err := json.Marshal(map[string]any{"version": 1, "sshProgram": ssh}) + if err != nil { + t.Fatal(err) + } + preferences := string(data) + request.Preferences = &preferences + } + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + connected, err := client.RemoteConnect(ctx, request) + if err != nil || connected.Status != core.RemoteProbeConnected || connected.Session == nil { + t.Fatalf("SSH connect: status=%s, err=%v, diagnostics=%s", connected.Status, err, connected.Diagnostics) + } + t.Cleanup(func() { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if _, err := client.RemoteDisconnect(ctx, connected.Session.ID, core.RemoteCloseEnd); err != nil { + t.Errorf("disconnect SSH session: %v", err) + } + }) + return connection, connected +} + +func buildLinuxVariantLanguageServer(t *testing.T) []byte { + t.Helper() + binary := buildLinuxSSHFixture(t, "test-language-server", "./testdata/remote_variant_server") + data, err := os.ReadFile(binary) + if err != nil { + t.Fatal(err) + } + return data +} + +func buildLinuxSSHFixture(t *testing.T, name, source string) string { + t.Helper() + return buildLinuxSSHFixtureFor(t, name, source, "amd64") +} + +// linuxSSHFixtureArch uses the connected host's architecture for executable test inputs. +func linuxSSHFixtureArch(t *testing.T, host core.RemoteConnectResult) string { + t.Helper() + platform := host.Host.PluginPlatform() + if platform == nil || platform.OS != "linux" { + t.Fatalf("target = %+v, want Linux", host.Host) + } + if platform.Arch == "x86_64" { + return "amd64" + } + return platform.Arch +} + +func buildLinuxSSHFixtureFor(t *testing.T, name, source, arch string) string { + t.Helper() + binary := filepath.Join(t.TempDir(), name) + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + command := exec.CommandContext(ctx, "go", "build", "-trimpath", "-ldflags=-s -w", "-o", binary, source) + command.Env = append(os.Environ(), "GOOS=linux", "GOARCH="+arch, "CGO_ENABLED=0") + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("build Linux %s fixture %s: %v\n%s", arch, name, err, output) + } + return binary +} + +func pluginProgramVariantArchive(t *testing.T, id, manifest, programPath string, program []byte) ([]byte, string) { + t.Helper() + return writeVariantArchive(t, id, []variantArchiveFile{ + {"plugin.json", []byte(manifest), 0o644}, + {"bin/backend", []byte("#!/bin/sh\nexit 1\n"), 0o755}, + {programPath, program, 0o755}, + }) +} + +type variantArchiveFile struct { + name string + data []byte + mode os.FileMode +} + +func writeVariantArchive(t *testing.T, root string, files []variantArchiveFile) ([]byte, string) { + t.Helper() + var data bytes.Buffer + archive := zip.NewWriter(&data) + for _, file := range files { + header := &zip.FileHeader{Name: path.Join(root, file.name), Method: zip.Deflate} + header.SetMode(file.mode) + entry, err := archive.CreateHeader(header) + if err != nil { + t.Fatal(err) + } + if _, err := entry.Write(file.data); err != nil { + t.Fatal(err) + } + } + if err := archive.Close(); err != nil { + t.Fatal(err) + } + return data.Bytes(), fmt.Sprintf("%x", sha256.Sum256(data.Bytes())) +} diff --git a/desktop/internal/workbench/remote_run.go b/desktop/internal/workbench/remote_run.go index 26fb050150..a1681e2ae0 100644 --- a/desktop/internal/workbench/remote_run.go +++ b/desktop/internal/workbench/remote_run.go @@ -42,14 +42,10 @@ const ( // the run preparation time; the process runs until it exits, the user stops it, the project // closes or the connection is lost, which ends it on the host too. func (a *App) launchRemoteProcessRun(p *project, op *buildOperation, id string) { - host := remoteRunHost{ - kernel: a.kernel, binding: p.remote.binding, root: p.root, language: a.language(), - label: core.NewRemoteResourceLabel("run", op.session.label), - output: func(text string) { a.streamBuildOutput(p, op, text) }, - lost: a.remoteSessionLost(p), - } + host := a.remoteRunHostFor(p, op) a.background(p, 0, func(ctx context.Context) func(*App) { - host.failed = func(operation string, err error) { a.backgroundFailedIn(ctx, operation, remoteLogError(err)) } + ctx = attachedWorkspaceContext(ctx, host.connection) + host.logFailures(a, ctx) bounded, cancel := context.WithTimeout(ctx, runPreparationTimeout) prepare, release := op.bind(bounded) start, err := host.prepare(prepare, id) @@ -66,6 +62,47 @@ func (a *App) launchRemoteProcessRun(p *project, op *buildOperation, id string) }) } +// remoteRunHostFor captures the window state shared by built-in and declared runs. +func (a *App) remoteRunHostFor(p *project, op *buildOperation) remoteRunHost { + return remoteRunHost{ + kernel: a.kernel, connection: op.connection, hostRoot: p.remote.binding.RemoteRoot(), + root: p.root, language: a.language(), resolveTool: a.resolveToolchainSelection, + label: core.NewRemoteResourceLabel("run", op.session.label), + output: func(text string) { a.streamBuildOutput(p, op, text) }, + lost: func(session string) { + a.post(func(a *App) { + if a.project == p && op.connection.IsCurrent() { + a.loseRemote(p, session, errRemoteSessionClosed) + } + }) + }, + } +} + +func (h *remoteRunHost) logFailures(a *App, ctx context.Context) { + h.failed = func(operation string, err error) { a.backgroundFailedIn(ctx, operation, remoteLogError(err)) } +} + +// command opens a build-tool plan under the same host scope as a built-in run. +func (h remoteRunHost) command(planned declaredProcess) (remoteRunStart, error) { + directory, err := remoteRunDirectory(h.hostRoot, planned.plan.WorkingDirectory) + if err != nil { + return remoteRunStart{}, err + } + session := h.connection.SessionID() + if session == "" { + return remoteRunStart{}, errors.New(i18n.Shared(h.language, "desktop.run.remote.notConnected")) + } + selection := planned.execution.selection() + selection.PathPrepend = nil + return remoteRunStart{session: session, open: core.RemoteProcessOpen{ + Argv: append([]string{planned.execution.Executable}, planned.plan.Arguments...), + ScopedCwd: directory, Environment: core.RemoteProcessEnvironmentLogin, + Env: applyToolchainSelection(planned.plan.Environment, selection), + PathPrepend: planned.execution.PathPrepend, Label: h.label, + }}, nil +} + // runStep runs a before-launch step that starts built-in run configuration step.ConfigurationID // on the host and waits for it, with its output in the console of the configuration that starts. // prepare bounds the step like a local one: once it ends, through a stop or the preparation @@ -78,6 +115,14 @@ func (h remoteRunHost) runStep(ctx, prepare context.Context, step core.RunBefore if err != nil { return err } + return h.waitStep(prepare, start) +} + +// waitStep gives a running host step the same grace period as a stopped local step. +func (h remoteRunHost) waitStep(prepare context.Context, start remoteRunStart) error { + if err := prepare.Err(); err != nil { + return err + } request, cancel := context.WithCancel(context.WithoutCancel(prepare)) defer cancel() var attached atomic.Pointer[remoteProcess] @@ -97,11 +142,12 @@ func (h remoteRunHost) runStep(ctx, prepare context.Context, step core.RunBefore // remoteRunHost is what one run of a remote workspace takes from the window thread. type remoteRunHost struct { - kernel Kernel - binding *core.RemoteWorkspace - root string - language i18n.Language - label *core.RemoteResourceLabel + kernel Kernel + connection *core.RemoteWorkspaceConnection + hostRoot, root string + resolveTool func(context.Context, string, string, string, string) (core.ToolchainSelection, error) + language i18n.Language + label *core.RemoteResourceLabel // output adds text to the run's console. Decoding it may wait for Core, so only the run's // output pump calls it, never the request's goroutine. output func(string) @@ -122,7 +168,7 @@ type remoteRunStart struct { // the run's temporary folder. The start it returns names the folder whenever one was created, so // the caller removes it even when preparing failed. func (h remoteRunHost) prepare(ctx context.Context, id string) (remoteRunStart, error) { - start := remoteRunStart{session: h.binding.SessionID()} + start := remoteRunStart{session: h.connection.SessionID()} if start.session == "" { return start, errors.New(i18n.Shared(h.language, "desktop.run.remote.notConnected")) } @@ -135,8 +181,14 @@ func (h remoteRunHost) prepare(ctx context.Context, id string) (remoteRunStart, if err != nil { return start, h.failure(start.session, err) } - if start.open, err = h.processOpen(plan); err != nil { - return start, err + if start.open, err = h.processOpen(ctx, plan); err != nil { + if errors.Is(err, errRunProgramNotFound) { + err = errors.New(i18n.SharedFormat(h.language, "desktop.runConfig.programNotFound", map[string]string{"program": plan.Executable.Command})) + } + return start, h.failure(start.session, err) + } + if !h.connection.IsCurrent() { + return start, errors.New(i18n.Shared(h.language, "desktop.run.remote.notConnected")) } if plan.InlineScript != nil { if err := h.writeScript(ctx, start, *plan.InlineScript); err != nil { @@ -149,13 +201,18 @@ func (h remoteRunHost) prepare(ctx context.Context, id string) (remoteRunStart, // processOpen turns a launch plan Core made for the host into the host process to start: the // program and its arguments as planned, the working directory under the workspace's host folder, // and the plan's variables over the user's login environment. A bare command is looked up on the -// host's PATH. A toolchain executable is resolved from this computer's toolchains, which do not -// run on the host, so such a run is refused. -func (h remoteRunHost) processOpen(plan core.RunLaunchPlan) (core.RemoteProcessOpen, error) { - directory, err := remoteRunDirectory(h.binding.RemoteRoot(), plan.WorkingDirectory) +// host's PATH, and a toolchain executable is resolved for the same workspace connection. +func (h remoteRunHost) processOpen(ctx context.Context, plan core.RunLaunchPlan) (core.RemoteProcessOpen, error) { + directory, err := remoteRunDirectory(h.hostRoot, plan.WorkingDirectory) if err != nil { return core.RemoteProcessOpen{}, err } + environment := make(map[string]string, len(plan.Environment)+len(plan.Env)) + maps.Copy(environment, plan.Environment) + maps.Copy(environment, plan.Env) + open := core.RemoteProcessOpen{ + ScopedCwd: directory, Environment: core.RemoteProcessEnvironmentLogin, Label: h.label, + } var program string switch executable := plan.Executable; { case executable.Path != "": @@ -164,33 +221,45 @@ func (h remoteRunHost) processOpen(plan core.RunLaunchPlan) (core.RemoteProcessO } program = executable.Path case executable.Command != "": - program = executable.Command + request := core.RemoteExecutableRequest{Kind: "program", Value: executable.Command} + if searchPath, overridden := environment["PATH"]; overridden { + request.SearchPath = &searchPath + } + program, err = h.kernel.ResolveRemoteExecutable(ctx, request) + if err != nil { + return core.RemoteProcessOpen{}, err + } + if program == "" { + return core.RemoteProcessOpen{}, errRunProgramNotFound + } case executable.Toolchain != "": - return core.RemoteProcessOpen{}, errors.New(i18n.Shared(h.language, "desktop.run.remote.toolchain")) + selection, err := h.resolveTool(ctx, h.root, plan.WorkingDirectory, executable.Toolchain, "") + if err != nil { + return core.RemoteProcessOpen{}, err + } + program = selection.Executable + open.PathPrepend = selection.PathPrepend + selection.PathPrepend = nil + environment = applyToolchainSelection(environment, selection) default: return core.RemoteProcessOpen{}, errors.New("run launch plan has no executable") } - environment := make(map[string]string, len(plan.Environment)+len(plan.Env)) - maps.Copy(environment, plan.Environment) - maps.Copy(environment, plan.Env) - return core.RemoteProcessOpen{ - Argv: append([]string{program}, plan.Arguments...), - Cwd: directory, - Environment: core.RemoteProcessEnvironmentLogin, - Env: environment, - Label: h.label, - }, nil + open.Argv = append([]string{program}, plan.Arguments...) + open.Env = environment + return open, nil } -// remoteRunDirectory is the host path of a project-relative '/' working directory below the -// workspace's host folder remoteRoot. Core keeps it inside the project; one that leaves it is -// refused here too. -func remoteRunDirectory(remoteRoot, directory string) (string, error) { +// remoteRunDirectory names a project-relative directory. The remote server +// resolves it under the workspace root when it starts the process. +func remoteRunDirectory(remoteRoot, directory string) (*core.RemoteScopedDirectory, error) { clean := path.Clean(directory) if path.IsAbs(clean) || clean == ".." || strings.HasPrefix(clean, "../") { - return "", errors.New("run working directory is outside the project") + return nil, errors.New("run working directory is outside the project") } - return path.Join(remoteRoot, clean), nil + if clean == "." { + clean = "" + } + return &core.RemoteScopedDirectory{Root: remoteRoot, Path: clean}, nil } // writeScript writes a script saved as text where Core planned it, which must be a new file @@ -215,11 +284,14 @@ func (h remoteRunHost) writeScript(ctx context.Context, start remoteRunStart, sc // returns nil for a clean exit, a remoteRunExit for a nonzero exit code, and why the run ended // otherwise. func (h remoteRunHost) run(ctx context.Context, start remoteRunStart, attach func(*remoteProcess)) error { + if !h.connection.IsCurrent() { + return errors.New(i18n.Shared(h.language, "desktop.run.remote.notConnected")) + } ctx, cancel := context.WithCancel(ctx) defer cancel() - process := &remoteProcess{kernel: h.kernel, session: start.session, cancel: cancel, done: make(chan struct{}), failed: h.failed} + process := &remoteProcess{kernel: h.kernel, connection: h.connection, session: start.session, cancel: cancel, done: make(chan struct{}), failed: h.failed} output := newRemoteRunOutput(h.output, "\n\x1b[2m"+i18n.Shared(h.language, "desktop.run.remote.outputDropped")+"\x1b[0m\n") - exit, err := h.kernel.RemoteRunProcess(ctx, start.session, start.open, core.RemoteProcessEvents{ + exit, err := h.kernel.RunRemoteProcess(ctx, start.open, core.RemoteProcessEvents{ Started: func(processID uint64, _ int) { if process.id.CompareAndSwap(0, processID) { attach(process) @@ -282,8 +354,9 @@ func (e remoteRunExit) ExitCode() int { return int(e) } // remoteProcess is a run's process on the host as the Run window stops it (runProcess). type remoteProcess struct { - kernel Kernel - session string + kernel Kernel + connection *core.RemoteWorkspaceConnection + session string // cancel ends the run's request, and with it every process of the run: Core kills them. cancel context.CancelFunc // id is the process's id for process.kill, set before the process is attached. @@ -302,7 +375,7 @@ func (r *remoteProcess) Pid() int { return 0 } func (r *remoteProcess) Stop() { r.stopping.Do(func() { grace := buildprocess.StopGrace() - if grace <= 0 || r.id.Load() == 0 { + if grace <= 0 || r.id.Load() == 0 || !r.connection.IsCurrent() { r.cancel() return } @@ -310,8 +383,8 @@ func (r *remoteProcess) Stop() { timer := time.NewTimer(grace) defer timer.Stop() ctx, cancel := context.WithTimeout(context.Background(), grace) + defer cancel() err := r.kernel.RemoteProcessKill(ctx, r.session, r.id.Load(), false) - cancel() if err != nil { if ctx.Err() == nil && !remoteConnectionClosed(err) { r.failed("run_stop", err) diff --git a/desktop/internal/workbench/remote_run_test.go b/desktop/internal/workbench/remote_run_test.go index ddec25953a..1783d59f05 100644 --- a/desktop/internal/workbench/remote_run_test.go +++ b/desktop/internal/workbench/remote_run_test.go @@ -26,7 +26,8 @@ type remoteHostRuns struct { configurations []core.RunConfiguration plan core.RunLaunchPlan // steps are the before-launch steps of every configuration. - steps []core.RunBeforeLaunchItem + steps []core.RunBeforeLaunchItem + beforeLaunch func(context.Context) error // exit is how a process that is not held ends; hold keeps it running. exit core.RemoteProcessExit hold bool @@ -46,22 +47,33 @@ type remoteHostRuns struct { // remoteHostRunOutput is what a host process prints. const remoteHostRunOutput = "hello from the host\n" -func (k *remoteHostKernel) ResolveRunConfigurations(context.Context, string, []core.RunInstalledPlugin) (core.RunConfigResolution, error) { +func (k *remoteHostKernel) remoteRunConfigurations() core.RunConfigResolution { r := &k.runs r.mu.Lock() defer r.mu.Unlock() - return core.RunConfigResolution{Configurations: append([]core.RunConfiguration(nil), r.configurations...)}, nil + return core.RunConfigResolution{Configurations: append([]core.RunConfiguration(nil), r.configurations...)} } -func (k *remoteHostKernel) RunConfigurationTypes(context.Context, *core.RunTypePlugins) ([]core.RunConfigurationType, []core.RunTypeLocalization, error) { - return []core.RunConfigurationType{}, nil, nil -} - -func (k *remoteHostKernel) RunBeforeLaunch(context.Context, string, string, *core.RunTypePlugins) (core.RunBeforeLaunch, error) { +func (k *remoteHostKernel) RunBeforeLaunch(ctx context.Context, _ string, _ string, _ *core.RunTypePlugins) (core.RunBeforeLaunch, error) { r := &k.runs r.mu.Lock() - defer r.mu.Unlock() - return core.RunBeforeLaunch{Status: "ok", Steps: r.steps}, nil + steps, beforeLaunch := r.steps, r.beforeLaunch + r.mu.Unlock() + if beforeLaunch != nil { + if err := beforeLaunch(ctx); err != nil { + return core.RunBeforeLaunch{}, err + } + } + return core.RunBeforeLaunch{Status: "ok", Steps: steps}, nil +} + +func (k *remoteHostKernel) ResolveRemoteExecutable(ctx context.Context, request core.RemoteExecutableRequest) (string, error) { + if request.Kind == "program" && request.Value == "sh" { + if workspace := core.RemoteWorkspaceOf(ctx); workspace != nil && workspace.CapturedConnection(ctx).IsCurrent() { + return "/usr/bin/sh", nil + } + } + return "", nil } func (k *remoteHostKernel) CreateRunLaunchPlan(_ context.Context, _, _, base string) (core.RunLaunchPlan, error) { @@ -103,7 +115,15 @@ func (k *remoteHostKernel) RemoteRemove(_ context.Context, _, path string, recur return nil } -func (k *remoteHostKernel) RemoteRunProcess(ctx context.Context, session string, open core.RemoteProcessOpen, events core.RemoteProcessEvents) (core.RemoteProcessExit, error) { +func (k *remoteHostKernel) RunRemoteProcess(ctx context.Context, open core.RemoteProcessOpen, events core.RemoteProcessEvents) (core.RemoteProcessExit, error) { + workspace := core.RemoteWorkspaceOf(ctx) + if workspace == nil { + return core.RemoteProcessExit{}, &core.Error{Code: core.CodeConnectionClosed, Message: "no captured workspace"} + } + session := workspace.CapturedConnection(ctx).SessionID() + if session == "" { + return core.RemoteProcessExit{}, &core.Error{Code: core.CodeConnectionClosed, Message: "no captured session"} + } script, written := "", false if len(open.Argv) > 1 { script, written = k.file(open.Argv[1]) @@ -175,6 +195,7 @@ var remoteTestRunConfiguration = core.RunConfiguration{ID: "greet", Name: "Greet func openRemoteRunProject(t *testing.T) (*harness, *remoteHostKernel, *project, *treeRecordingLog) { t.Helper() h, k, _, logger := remoteWorkspaceHarness(t) + k.set(func(k *remoteHostKernel) { k.git.trust[remoteTestFolder] = core.WorkspaceTrusted }) k.setRuns(func(r *remoteHostRuns) { r.configurations = []core.RunConfiguration{remoteTestRunConfiguration} zero := 0 @@ -195,13 +216,28 @@ func openRemoteRunProject(t *testing.T) (*harness, *remoteHostKernel, *project, return h, k, p, logger } -// startRemoteRun starts the configuration as the title bar's Run does, without the trust -// question the folder's safe mode asks first. +// startRemoteRun starts a configuration in a trusted workspace and checks admission +// before the caller waits for its output. func (h *harness) startRemoteRun(p *project, id string) { + h.t.Helper() + started := make(chan error, 1) h.app.post(func(a *App) { - if _, err := a.startRunConfiguration(p, id); err == nil { + _, err := a.startRunConfiguration(p, id) + if err == nil { a.showBuildConsole(p) } + started <- err + }) + h.await("the remote run to start", func() bool { + select { + case err := <-started: + if err != nil { + h.t.Fatalf("start remote run %q: %v", id, err) + } + return true + default: + return false + } }) } @@ -230,10 +266,6 @@ func (h *harness) awaitRemoteRun(p *project, label string, previous *runEntry) * func TestRemoteWorkspaceRunsBuiltInConfigurationsOnTheHost(t *testing.T) { h, k, p, logger := openRemoteRunProject(t) lang := h.app.language() - if p.build.failed != i18n.Shared(lang, "desktop.run.remote.buildTools") { - t.Fatal("the run configuration menu does not say build tools do not work here") - } - h.startRemoteRun(p, remoteTestRunConfiguration.ID) run := h.awaitRemoteRun(p, remoteTestRunConfiguration.Name, nil) if run.outcome != runSucceeded || !strings.Contains(run.output.all(), "hello from the host") { @@ -251,8 +283,8 @@ func TestRemoteWorkspaceRunsBuiltInConfigurationsOnTheHost(t *testing.T) { if len(bases) != 1 || bases[0] != remoteTestRunScratch+"/script" { t.Fatal("Core did not plan the script below the host's temporary folder") } - if strings.Join(open.Argv, " ") != "sh "+script || open.Cwd != remoteTestFolder+"/src" || open.Environment != core.RemoteProcessEnvironmentLogin { - t.Fatalf("the process started with %d arguments, cwd matched %v, environment %q", len(open.Argv), open.Cwd == remoteTestFolder+"/src", open.Environment) + if want := (core.RemoteScopedDirectory{Root: remoteTestFolder, Path: "src"}); strings.Join(open.Argv, " ") != "/usr/bin/sh "+script || open.ScopedCwd == nil || *open.ScopedCwd != want || open.Environment != core.RemoteProcessEnvironmentLogin { + t.Fatalf("the process started with argv=%v, scoped directory=%+v, environment=%q", open.Argv, open.ScopedCwd, open.Environment) } if open.Env["FROM_PLAN"] != "1" || open.Env["FROM_CONFIG"] != "2" || open.Label == nil || open.Label.Kind != "run" || open.Label.Name != "Greet" { t.Fatalf("the process started with %d variables and label %v", len(open.Env), open.Label != nil) @@ -326,34 +358,32 @@ func TestRemoteWorkspaceRunEndsAsTheHostProcessEnds(t *testing.T) { sessionKept(t, logger, p, p.remote.session) } -// A remote workspace refuses, with its reason, what it cannot run on the host yet: a -// configuration whose before-launch list names a plugin's task, a debug session and a program -// chosen through a toolchain. None of them starts a host process. func TestRemoteWorkspaceRefusesRunsItCannotStartOnTheHost(t *testing.T) { h, k, p, _ := openRemoteRunProject(t) lang := h.app.language() k.setRuns(func(r *remoteHostRuns) { - r.steps = []core.RunBeforeLaunchItem{ - {ConfigurationID: remoteTestRunConfiguration.ID, Name: "Prepare"}, - {Task: &core.RunTaskReference{RunTypeKey: core.RunTypeKey{PluginID: "dev.example.build", BuildSystemID: "example", Type: "compile"}}, Name: "Compile"}, - } + r.steps = []core.RunBeforeLaunchItem{{ + Task: &core.RunTaskReference{RunTypeKey: core.RunTypeKey{PluginID: "dev.lithe.test.build", BuildSystemID: "example", Type: "compile"}}, + Name: "Compile", + }} }) h.startRemoteRun(p, remoteTestRunConfiguration.ID) refused := h.awaitRemoteRun(p, remoteTestRunConfiguration.Name, nil) - if !h.notified(i18n.Shared(lang, "desktop.run.remote.beforeLaunch")) { - t.Fatal("the before-launch steps were not refused with their reason") + if refused.outcome == runSucceeded || !strings.Contains(refused.output.all(), h.app.text.Build.TargetMissing) { + t.Fatalf("the missing build target was not reported: %s", refused.output.all()) } k.setRuns(func(r *remoteHostRuns) { r.steps = nil - r.plan.Executable = core.RunPlanExecutable{Toolchain: "python"} + r.plan.Executable = core.RunPlanExecutable{Command: "missing-program"} }) h.app.post(func(a *App) { p.closeRunSession(refused.id) }) h.startRemoteRun(p, remoteTestRunConfiguration.ID) run := h.awaitRemoteRun(p, remoteTestRunConfiguration.Name, refused) - if !strings.Contains(run.output.all(), i18n.Shared(lang, "desktop.run.remote.toolchain")) && !strings.Contains(run.summary, i18n.Shared(lang, "desktop.run.remote.toolchain")) { - t.Fatalf("a toolchain program was not refused with its reason: %q\n%s", run.summary, run.output.all()) + message := i18n.SharedFormat(lang, "desktop.runConfig.programNotFound", map[string]string{"program": "missing-program"}) + if run.outcome == runSucceeded || !strings.Contains(run.output.all()+run.summary, message) { + t.Fatalf("the missing host program was not reported: %q\n%s", run.summary, run.output.all()) } done := make(chan error, 1) @@ -361,15 +391,60 @@ func TestRemoteWorkspaceRefusesRunsItCannotStartOnTheHost(t *testing.T) { _, err := a.startRunConfigurationWith(p, remoteTestRunConfiguration.ID, &connectionDebug{}) done <- err }) - h.settle() - if err := <-done; err == nil || !h.notified(i18n.Shared(lang, "desktop.run.remote.unsupported")) { - t.Fatalf("a debug session was not refused: %v", err) - } + h.await("the built-in debug refusal", func() bool { + select { + case err := <-done: + if err == nil || !h.notified(i18n.Shared(lang, "desktop.remote.workspace.localOnly")) { + t.Fatalf("a built-in debug session was not refused: %v", err) + } + return true + default: + return false + } + }) if opens, _, _, _, _ := k.hostRuns(); len(opens) != 0 { t.Fatalf("the host started %d processes", len(opens)) } } +func TestRemoteWorkspaceRunDoesNotSurviveReattachment(t *testing.T) { + h, k, p, _ := openRemoteRunProject(t) + planning := make(chan struct{}) + release := make(chan struct{}) + k.setRuns(func(r *remoteHostRuns) { + r.beforeLaunch = func(ctx context.Context) error { + close(planning) + select { + case <-release: + return nil + case <-ctx.Done(): + return ctx.Err() + } + } + }) + var releaseOnce sync.Once + unblock := func() { releaseOnce.Do(func() { close(release) }) } + t.Cleanup(unblock) + h.startRemoteRun(p, remoteTestRunConfiguration.ID) + h.await("the run to request its before-launch plan", func() bool { + select { + case <-planning: + return true + default: + return false + } + }) + // A resumed session can keep its ID. A pending run still owns the old attachment. + h.app.post(func(a *App) { + p.remote.binding.Attach(p.remote.session) + unblock() + }) + run := h.awaitRemoteRun(p, remoteTestRunConfiguration.Name, nil) + if opens, _, bases, _, _ := k.hostRuns(); run.outcome == runSucceeded || len(opens) != 0 || len(bases) != 0 { + t.Fatalf("the stale run reached the reattached workspace: outcome=%v, opens=%d, plans=%d", run.outcome, len(opens), len(bases)) + } +} + // A remote workspace runs the before-launch steps that start another built-in run on its host, // in order and over the workspace's session, with their output and headers in the console of the // configuration that starts, which starts once every step exited with 0. Each step's temporary @@ -401,8 +476,8 @@ func TestRemoteWorkspaceRunsBeforeLaunchStepsOnTheHost(t *testing.T) { t.Fatal("a process started over another session") } } - if len(bases) != 2 || len(removed) != 2 || opens[0].Cwd != remoteTestFolder+"/src" { - t.Fatalf("%d plans, %d temporary folders removed, step cwd matched %v", len(bases), len(removed), opens[0].Cwd == remoteTestFolder+"/src") + if want := (core.RemoteScopedDirectory{Root: remoteTestFolder, Path: "src"}); len(bases) != 2 || len(removed) != 2 || opens[0].ScopedCwd == nil || *opens[0].ScopedCwd != want { + t.Fatalf("%d plans, %d temporary folders removed, step scoped directory=%+v", len(bases), len(removed), opens[0].ScopedCwd) } three := 3 @@ -451,9 +526,9 @@ func TestRemoteWorkspaceRunsBeforeLaunchStepsOnTheHost(t *testing.T) { // remoteRunDirectory keeps a plan's working directory inside the host folder. func TestRemoteRunDirectoryStaysInTheHostFolder(t *testing.T) { - for directory, want := range map[string]string{"": "/srv/app", ".": "/srv/app", "src": "/srv/app/src", "src/../lib": "/srv/app/lib"} { - if got, err := remoteRunDirectory("/srv/app", directory); err != nil || got != want { - t.Errorf("%q: %q, %v; want %q", directory, got, err, want) + for directory, want := range map[string]string{"": "", ".": "", "src": "src", "src/../lib": "lib"} { + if got, err := remoteRunDirectory("/srv/app", directory); err != nil || got == nil || got.Root != "/srv/app" || got.Path != want { + t.Errorf("%q: %+v, %v; want root /srv/app and path %q", directory, got, err, want) } } for _, directory := range []string{"..", "../other", "/etc", "src/../../other"} { diff --git a/desktop/internal/workbench/remote_run_visual_test.go b/desktop/internal/workbench/remote_run_visual_test.go index e8caba7017..2990874b3a 100644 --- a/desktop/internal/workbench/remote_run_visual_test.go +++ b/desktop/internal/workbench/remote_run_visual_test.go @@ -39,8 +39,7 @@ func TestVisualRemoteRun(t *testing.T) { } var session *headless.Session kernel := &remoteHostKernel{testKernel: &testKernel{Client: core.NewClient()}} - // The folder was kept in safe mode before, so it opens without the trust question. - kernel.git.trust = map[string]string{remoteTestFolder: core.WorkspaceDistrusted} + kernel.git.trust = map[string]string{remoteTestFolder: core.WorkspaceTrusted} zero := 0 // Greet starts once Prepare, another built-in run, ran before it on the host. prepare := core.RunConfiguration{ID: "prepare", Name: "Prepare", Provider: runProviderShell} diff --git a/desktop/internal/workbench/remote_terminal.go b/desktop/internal/workbench/remote_terminal.go index f3ff681c72..43fe2b9f8d 100644 --- a/desktop/internal/workbench/remote_terminal.go +++ b/desktop/internal/workbench/remote_terminal.go @@ -83,6 +83,8 @@ func (s remoteExitStatus) ExitStatus() int { return int(s) } type remoteTerminalHost struct { kernel Kernel binding *core.RemoteWorkspace + // connection pins a plugin launch to the attachment the user approved. + connection *core.RemoteWorkspaceConnection // ctx ends with the terminal's tab; each start's request runs under a child of it. ctx context.Context open core.RemoteTerminalOpen @@ -96,8 +98,11 @@ type remoteTerminalHost struct { // start runs the host terminal in a grid of cols by rows cells and returns once the host // started it, or why it could not. It blocks, so termview runs it off the window thread. -func (h remoteTerminalHost) start(cols, rows int) (termview.Shell, error) { +func (h remoteTerminalHost) start(cols, rows int) (*remoteShell, error) { session := h.binding.SessionID() + if h.connection != nil { + session = h.connection.SessionID() + } if session == "" { return nil, &remoteTerminalStartError{reason: h.notConnected, cause: errRemoteSessionClosed} } @@ -158,7 +163,9 @@ type remoteShell struct { // started is closed when the host started the program, done when the request returned. started chan struct{} startedOnce sync.Once - done chan struct{} + // Written before started closes and only read once the launch succeeds. + pid int64 + done chan struct{} // wake tells the sender there is input or a size to send. wake chan struct{} @@ -179,11 +186,16 @@ type remoteShell struct { // run is the start's request: it returns when the program ends or the terminal closes. func (s *remoteShell) run(open core.RemoteTerminalOpen) { exit, err := s.host.kernel.RemoteRunTerminal(s.ctx, s.session, open, core.RemoteTerminalEvents{ - Started: func(terminalID uint64) { + Started: func(terminalID uint64, pid int64) { + if s.host.connection != nil && !s.host.connection.IsCurrent() { + s.cancel() + return + } s.startedOnce.Do(func() { s.mu.Lock() s.terminal = terminalID s.mu.Unlock() + s.pid = pid close(s.started) }) }, @@ -431,30 +443,80 @@ func (s *remoteShell) wait(d time.Duration) bool { // remoteTerminalConfig makes config start terminal t of the remote workspace p on the host, in // dir, with env added to the server's environment. It returns what cancels the terminal's // requests when its tab closes. -func (a *App) remoteTerminalConfig(p *project, t *terminal, config *termview.Config, dir string, env []string) context.CancelFunc { +func (a *App) remoteTerminalConfig(p *project, t *terminal, config *termview.Config, options terminalOptions) context.CancelFunc { r := p.remote - ctx, cancel := context.WithCancel(p.ctx) + parent := p.ctx + if options.remoteStartContext != nil { + parent = options.remoteStartContext + } + ctx, cancel := context.WithCancel(parent) host := remoteTerminalHost{ - kernel: a.kernel, - binding: r.binding, - ctx: ctx, + kernel: a.kernel, + binding: r.binding, + connection: options.remoteConnection, + ctx: ctx, open: core.RemoteTerminalOpen{ - Cwd: p.remoteTerminalDir(dir), - Env: environmentMap(env), + Cwd: p.remoteTerminalDir(config.Dir), + Env: environmentMap(config.Env), Label: core.NewRemoteResourceLabel("terminal", a.terminalTitle(t)), }, notify: a.invalidator.Invalidate, notConnected: i18n.Shared(a.language(), "desktop.remote.terminal.notConnected"), lost: func(session string, err error) { a.post(func(a *App) { - if a.project == p { + if a.project == p && (options.remoteConnection == nil || options.remoteConnection.IsCurrent()) { a.loseRemote(p, session, err) } }) }, failed: func(operation string, err error) { a.backgroundFailedIn(ctx, operation, remoteLogError(err)) }, } - config.Open = host.start + if options.remoteDirectory != nil { + host.open.Cwd = "" + host.open.ScopedCwd = options.remoteDirectory + host.open.Argv = append([]string{options.shell}, options.args...) + host.open.Environment = "login" + host.open.UnsetEnv = options.unset + } + if options.remoteStarted != nil { + // Preserve the remote login environment and apply the DAP overrides. + host.open.Env = environmentMap(options.env) + host.open.Label = core.NewRemoteResourceLabel("debug", a.terminalTitle(t)) + } + terminalUnavailable := i18n.Shared(a.language(), "desktop.debug.terminalUnavailable") + untrusted := a.launchFailureText(remoteDebugUntrusted()) + config.Open = func(cols, rows int) (termview.Shell, error) { + var shell *remoteShell + var err error + if options.remoteStarted != nil && !p.trust.allowed() { + err = &remoteTerminalStartError{reason: untrusted, cause: remoteDebugUntrusted()} + } else { + shell, err = host.start(cols, rows) + } + if options.remoteStarted != nil { + var pid int64 + if err == nil { + pid = shell.pid + if pid <= 0 || pid > 1<<31-1 { + shell.Close() + // The view cannot track a shell returned as a failed start. + <-shell.Done() + err = errors.New(terminalUnavailable) + } + } + a.post(func(a *App) { + if err == nil && (ctx.Err() != nil || p.terms.find(t.id) != t) { + options.remoteStarted(0, context.Canceled) + return + } + options.remoteStarted(pid, err) + }) + } + if err != nil { + return nil, err + } + return shell, nil + } config.Shell, config.Args, config.Unset = "", nil, nil // A picture pasted into the terminal would be saved on this computer, where the host's // shell cannot read it. diff --git a/desktop/internal/workbench/remote_terminal_test.go b/desktop/internal/workbench/remote_terminal_test.go index 6aeb670ca7..3165cdb44b 100644 --- a/desktop/internal/workbench/remote_terminal_test.go +++ b/desktop/internal/workbench/remote_terminal_test.go @@ -13,6 +13,7 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" ) // remoteHostTerminals stands in for the host's terminals (remote.runTerminal): a terminal starts @@ -35,6 +36,7 @@ type remoteHostTerminals struct { // remoteHostPrompt is what a host terminal prints when it starts. const remoteHostPrompt = "host$" +const remoteTestTerminalPID = 11223 // remoteHostRun is one terminal the host ran. type remoteHostRun struct { @@ -70,7 +72,7 @@ func (k *remoteHostKernel) RemoteRunTerminal(ctx context.Context, session string close(run.ended) h.signal() }() - events.Started(id) + events.Started(id, remoteTestTerminalPID) events.Output([]byte(remoteHostPrompt + " ")) h.signal() for { @@ -195,6 +197,108 @@ func (h *remoteHostTerminals) await(t *testing.T, what string, condition func() } } +func TestRemotePluginTerminalRequiresFreshConsentAndRunsOnTheHost(t *testing.T) { + h, k, _, _ := remoteWorkspaceHarness(t) + p := h.openRemoteTestProject(t) + ctx, cancel := context.WithTimeout(t.Context(), 20*time.Second) + defer cancel() + + type result struct { + session pluginservice.TerminalSession + err error + } + done := make(chan result, 1) + start := func() { + mode := "test" + spec := pluginservice.TerminalSpec{ + PluginID: "dev.lithe.test.remote-terminal", Executable: "/usr/bin/printf", + Arguments: []string{"%s", "two words", ""}, Title: "Remote tool", + Directory: remoteTestFolder + "/src", + RemoteDirectory: &core.RemoteScopedDirectory{Root: remoteTestFolder, Path: "src"}, + RemoteConnection: p.remote.binding.CaptureConnection(), + Environment: map[string]*string{"TOOL_MODE": &mode, "REMOVE_ME": nil}, + } + go func() { + session, err := (pluginWorkbench{app: h.app}).StartTerminal(ctx, p.root, spec) + done <- result{session: session, err: err} + h.app.invalidator.Invalidate() + }() + } + wait := func() result { + var finished result + h.await("the plugin terminal launch decision", func() bool { + select { + case finished = <-done: + return true + default: + return false + } + }) + return finished + } + checkRefusal := func(code string) { + t.Helper() + finished := wait() + var refusal *pluginservice.HostError + if finished.session != nil || !errors.As(finished.err, &refusal) || refusal.Code != code { + t.Fatalf("launch should fail with %s, got session %v, error %v", code, finished.session, finished.err) + } + if len(h.app.prompts.queue) != 0 || len(k.terminals.started()) != 0 { + t.Fatal("refused launch left a consent prompt or started a host terminal") + } + } + awaitPrompt := func() { + t.Helper() + h.await("the remote terminal consent prompt", func() bool { return len(h.app.prompts.queue) == 1 }) + prompt := h.app.prompts.queue[0] + if !strings.Contains(prompt.text, p.remote.name) || !strings.Contains(prompt.text, remoteTestFolder+"/src") { + t.Fatalf("consent does not identify the remote destination: %q", prompt.text) + } + if len(k.terminals.started()) != 0 { + t.Fatal("the host started before consent") + } + } + + start() + checkRefusal(pluginservice.CodePermissionDenied) + h.app.applyProjectTrust(p, true) + + allow := 1 + start() + awaitPrompt() + p.remote.binding.Attach(p.remote.session) + h.app.answerPrompt(&allow) + checkRefusal(pluginservice.CodeRemoteDisconnected) + + start() + awaitPrompt() + h.app.answerPrompt(&allow) + finished := wait() + if finished.err != nil || finished.session == nil { + t.Fatalf("approved launch = %v, %v", finished.session, finished.err) + } + k.terminals.await(t, "the approved host terminal", func() bool { return len(k.terminals.started()) == 1 }) + run := k.terminals.started()[0] + open := run.open + if run.session != p.remote.session || open.Cwd != "" || open.ScopedCwd == nil || + open.ScopedCwd.Root != remoteTestFolder || open.ScopedCwd.Path != "src" || + !slices.Equal(open.Argv, []string{"/usr/bin/printf", "%s", "two words", ""}) { + t.Fatalf("incorrect remote launch: session = %q, request = %#v", run.session, open) + } + if open.Environment != "login" || open.Env["TOOL_MODE"] != "test" || open.Env["TERM_PROGRAM"] != "Lithe" || + !slices.Equal(open.UnsetEnv, []string{"REMOVE_ME"}) { + t.Fatalf("incorrect remote environment: source = %q, set = %v, unset = %v", open.Environment, open.Env, open.UnsetEnv) + } + + term := p.terms.list[len(p.terms.list)-1] + h.app.closeTerminal(p, term.id) + select { + case <-run.ended: + case <-ctx.Done(): + t.Fatal("closing the tab did not end its remote PTY") + } +} + // openRemoteTerminal shows the Terminal tool window of the remote workspace p, which opens a // terminal on the host, and waits for the host's prompt. func (h *harness) openRemoteTerminal(t *testing.T, k *remoteHostKernel, p *project) (*terminal, *remoteHostRun) { @@ -422,12 +526,11 @@ func remoteTestShell(t *testing.T, k *remoteHostKernel) (*remoteShell, *remoteSh reports.failed = append(reports.failed, operation) }, } - shell, err := host.start(80, 24) + s, err := host.start(80, 24) if err != nil { cancel() t.Fatalf("start: %v", err) } - s := shell.(*remoteShell) t.Cleanup(func() { cancel() deadline := time.NewTimer(8 * time.Second) diff --git a/desktop/internal/workbench/remote_watch.go b/desktop/internal/workbench/remote_watch.go index ce86cceac5..06f82efe0a 100644 --- a/desktop/internal/workbench/remote_watch.go +++ b/desktop/internal/workbench/remote_watch.go @@ -80,8 +80,9 @@ const ( // remoteWatch is one run of a remote workspace's host watch (remoteProject.watch). type remoteWatch struct { // session is the session the watch runs over; cancel stops it. - session string - cancel context.CancelFunc + session string + attachment *core.RemoteWorkspaceConnection + cancel context.CancelFunc // watching is set once the host watches the folder, and partial once the host ran out of // watches, so some of its folders go unwatched; lostReported and excessReported once this // run's lost changes and too many changes were logged. They are the window thread's. @@ -122,7 +123,7 @@ func (a *App) startRemoteWatch(p *project) { return } ctx, cancel := context.WithCancel(p.ctx) - w := &remoteWatch{session: r.session, cancel: cancel} + w := &remoteWatch{session: r.session, attachment: r.binding.CaptureConnection(), cancel: cancel} r.watch = w kernel, root, excludes := a.kernel, r.binding.RemoteRoot(), remoteWatchExcludeNames() events := core.RemoteWatchEvents{ @@ -159,6 +160,9 @@ func (a *App) stopRemoteWatch(p *project) { if r == nil || r.watch == nil { return } + if a.plugins != nil && !r.closed { + a.plugins.PublishRemoteWorkspaceChanges(r.binding, r.watch.attachment, nil, true) + } r.watch.cancel() r.watch = nil p.tree.eventEpoch++ @@ -186,6 +190,9 @@ func (a *App) drainRemoteWatch(p *project, w *remoteWatch) { // log-exempt: 用户取消:工作区已关闭,或这次监听已停止(会话丢失、隐藏目录变化),它的变化不再适用。 return } + if a.plugins != nil { + a.plugins.PublishRemoteWorkspaceChanges(r.binding, w.attachment, paths, started || overflow || limited || excess) + } if limited { w.partial = true a.backgroundFailed("remote_watch", errRemoteWatchLimit) diff --git a/desktop/internal/workbench/remote_workspace.go b/desktop/internal/workbench/remote_workspace.go index 17e477595b..182bece72e 100644 --- a/desktop/internal/workbench/remote_workspace.go +++ b/desktop/internal/workbench/remote_workspace.go @@ -81,7 +81,8 @@ type remoteProject struct { name string host remoteHost // session is the session the binding is attached to, "" while there is none. - session string + session string + platform core.RemotePlatform // resume is what connecting again presents to attach to the same host session, nil when the // host issued no token. It is a secret: it stays in memory and is never logged. resume *core.RemoteResume @@ -131,6 +132,7 @@ type remoteTarget struct { name string host remoteHost session core.RemoteSession + platform *core.RemotePlatform // remoteRoot is the host folder, an absolute POSIX path; root is its local placeholder. remoteRoot string root string @@ -307,16 +309,55 @@ func (r *remoteProject) stopRemoteTimer() { // attachRemote makes session the workspace's session and starts its heartbeat, the host watch of // its folder and, in a trusted workspace, the watch of its Git metadata, which reads the status // again. -func (a *App) attachRemote(p *project, session core.RemoteSession) { +func (a *App) attachRemote(p *project, session core.RemoteSession, platform *core.RemotePlatform) { r := p.remote a.stopRemoteWatch(p) + a.invalidateVcs(p) + if platform != nil { + r.platform = *platform + } r.session, r.link, r.attempt, r.misses, r.failure = session.ID, remoteConnected, 0, 0, nil r.resume = session.Resume() r.binding.Attach(session.ID) + if a.plugins != nil { + a.sweepRemoteDeployments(p) + } + if a.plugins != nil && platform != nil { + workspace := a.plugins.Contexts.OpenRemote(r.binding, p.name, r.connectionID, *platform, p.trust.allowed) + if workspace.ContextRef != p.pluginContext { + p.pluginContext = workspace.ContextRef + a.activatePluginWorkspace(p) + } + } a.beatRemote(p) r.watchWait = remoteWatchReady a.startRemoteWatch(p) a.resumeRemoteGit(p) + if a.project == p { + if a.plugins != nil { + a.loadBuildSystems(p) + } + for _, document := range p.docs.list { + a.startPluginServer(document.languageID) + } + } +} + +func (a *App) sweepRemoteDeployments(p *project) { + plugins, connection := a.plugins, p.remote.binding.CaptureConnection() + a.background(p, remoteReadTimeout, func(ctx context.Context) func(*App) { + err := plugins.SweepRemoteDeployments(connection.Context(ctx)) + if err == nil { + return nil + } + return func(a *App) { + if !connection.IsCurrent() { + // log-exempt: 用户取消:原会话已经结束或被替换。 + return + } + a.backgroundFailed("remote_plugin_deployment_sweep", remoteLogError(err)) + } + }) } // beatRemote asks the server of the workspace's session what still runs, and schedules the next @@ -376,6 +417,14 @@ func (a *App) loseRemote(p *project, session string, err error) { r.ports.reset() r.session, r.misses = "", 0 r.binding.Detach() + // A Run or Debug press waiting for model or configuration data belongs to the lost attachment. + p.runConfigs.pending = titleActionNone + p.runConfigs.start, p.runConfigs.startAction = "", titleActionNone + a.invalidateVcs(p) + if a.project == p { + a.invalidateBuild(p) + a.stopLanguageServers() + } r.stopRemoteTimer() a.releaseRemoteSession(session) a.startRemoteReconnection(p) @@ -451,7 +500,7 @@ func (a *App) reconnectRemote(p *project, userStarted bool) { if err == nil && result.Status == core.RemoteProbeConnected && result.Session != nil { // The programs a resumed session still runs are the workspace's own, which closing // it lists; nothing asks about them now. - a.attachRemote(p, *result.Session) + a.attachRemote(p, *result.Session, result.Host.PluginPlatform()) a.refreshRemoteTree(p) a.recheckRemoteDocuments(p) return @@ -552,6 +601,11 @@ func (a *App) openRemoteProject(target remoteTarget) { r := &remoteProject{connectionID: target.connectionID, name: target.name, host: target.host, home: target.session.HomeDirectory} p.remote = r r.binding = core.NewRemoteWorkspace(target.root, target.remoteRoot, a.remoteSessionLost(p)) + settingsName := target.name + if settingsName == "" { + settingsName = target.host.address() + } + a.settingsRemote.Store(&remoteSettingsWorkspace{binding: r.binding, name: settingsName}) // Trusted, the workspace's Git runs on the host, and its commands are kept in the Git console // as a local project's are; in safe mode Core runs none (remote_trust.go). p.trust.codeAllowed.Store(target.trusted) @@ -567,7 +621,7 @@ func (a *App) openRemoteProject(target remoteTarget) { a.logView.reset() a.worktreeView.reset() // Attaching the session starts the watch of the Git metadata (remote_git.go). - a.attachRemote(p, target.session) + a.attachRemote(p, target.session, target.platform) a.loadGit(p) a.loadLog(p) // Unsaved edits of the folder's files are drafts on this computer; they open over the host's diff --git a/desktop/internal/workbench/remote_workspace_test.go b/desktop/internal/workbench/remote_workspace_test.go index 531eb43bc3..e77ffcd084 100644 --- a/desktop/internal/workbench/remote_workspace_test.go +++ b/desktop/internal/workbench/remote_workspace_test.go @@ -2,6 +2,8 @@ package workbench import ( "context" + "encoding/json" + "errors" "path/filepath" "slices" "strconv" @@ -12,6 +14,8 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" "github.com/1lck/Lithe-IDEA/desktop/internal/remoteplaceholder" "github.com/1lck/Lithe-IDEA/desktop/internal/remoteserver" ) @@ -40,8 +44,8 @@ var remoteTestFolders = map[string][]core.RemoteDirectoryEntry{ // remoteTestFolders, answers heartbeats as the test says, lists the workspace's tree only for a // request that carries the workspace's session, keeps the files of files // (remote_documents_test.go), watches the workspace's folder (remote_watch_test.go), searches -// it (remote_search_test.go) and forwards the host's ports (remote_ports_test.go). Everything else -// is the real Core. +// it (remote_search_test.go), forwards the host's ports (remote_ports_test.go) and answers for an +// empty set of run configuration layers. Everything else is the real Core. type remoteHostKernel struct { *testKernel mu sync.Mutex @@ -51,9 +55,12 @@ type remoteHostKernel struct { state error once error connects int + target string servers [][]core.RemoteServerBuild beats int closed []string + // deploymentSweeps records the captured attachment for each cache sweep. + deploymentSweeps []string // listings are the sessions the Project tool window's listings carried, "" for none. listings []string // files are the host's files by host path, and modified the time each was last written. @@ -172,7 +179,13 @@ func (k *remoteHostKernel) RemoteConnect(_ context.Context, request core.RemoteC if k.refuse != "" { return core.RemoteConnectResult{Status: k.refuse}, nil } - return core.RemoteConnectResult{Status: core.RemoteProbeConnected, Session: k.close.session(k.connects, request.Resume)}, nil + session := k.close.session(k.connects, request.Resume) + target := k.target + if target == "" { + target = "x86_64-unknown-linux-musl" + } + host := &core.RemoteProbedHost{ServerTarget: target} + return core.RemoteConnectResult{Status: core.RemoteProbeConnected, Session: session, Host: host}, nil } func (k *remoteHostKernel) RemoteReadDir(_ context.Context, _ string, dir string) (core.RemoteDirectory, error) { @@ -194,6 +207,19 @@ func (k *remoteHostKernel) RemoteServerState(context.Context, string) error { return k.state } +func (k *remoteHostKernel) SweepRemotePluginDeployments(ctx context.Context, installed []core.RemoteInstalledPluginVersion) error { + workspace := core.RemoteWorkspaceOf(ctx) + connection := workspace.CapturedConnection(ctx) + session := connection.SessionID() + if session == "" || installed == nil { + return errors.New("missing deployment sweep attachment or inventory") + } + k.mu.Lock() + defer k.mu.Unlock() + k.deploymentSweeps = append(k.deploymentSweeps, session) + return nil +} + func (k *remoteHostKernel) RemoteDisconnect(_ context.Context, id string, programs core.RemoteClosePrograms) (core.RemoteDisconnectResult, error) { k.mu.Lock() defer k.mu.Unlock() @@ -209,6 +235,37 @@ func (k *remoteHostKernel) RemoteDisconnect(_ context.Context, id string, progra return core.RemoteDisconnectResult{Closed: true, Kept: kept}, nil } +func (k *remoteHostKernel) ResolveRunConfigurations(ctx context.Context, root string, plugins []core.RunInstalledPlugin) (core.RunConfigResolution, error) { + if binding := core.RemoteWorkspaceOf(ctx); binding != nil { + if connection := binding.CapturedConnection(ctx); connection == nil || root != binding.LocalRoot() { + return core.RunConfigResolution{}, errors.New("remote run configuration resolution requires the project's captured connection") + } + return k.remoteRunConfigurations(), nil + } + return k.Client.ResolveRunConfigurations(ctx, root, plugins) +} + +func (k *remoteHostKernel) GenerateRunConfigurations(ctx context.Context, root string, runs json.RawMessage) (core.RunConfigGeneration, error) { + if binding := core.RemoteWorkspaceOf(ctx); binding != nil { + if connection := binding.CapturedConnection(ctx); connection == nil || root != binding.LocalRoot() { + return core.RunConfigGeneration{}, errors.New("remote run configuration generation requires the project's captured connection") + } + return core.RunConfigGeneration{}, nil + } + return k.Client.GenerateRunConfigurations(ctx, root, runs) +} + +func (k *remoteHostKernel) RunConfigurationTypes(ctx context.Context, plugins *core.RunTypePlugins) ([]core.RunConfigurationType, []core.RunTypeLocalization, error) { + if binding := core.RemoteWorkspaceOf(ctx); binding != nil { + if binding.CapturedConnection(ctx) == nil { + return nil, nil, errors.New("remote run configuration types require the project's captured connection") + } + // Tests of configuration types and their target-platform availability use the real Core. + return nil, nil, nil + } + return k.Client.RunConfigurationTypes(ctx, plugins) +} + func (k *remoteHostKernel) ListDirectories(ctx context.Context, _ string, paths []string) ([]core.DirectoryListing, error) { session := "" if binding := core.RemoteWorkspaceOf(ctx); binding != nil { @@ -643,6 +700,118 @@ func TestRemoteWorkspaceReconnectsWhenTheConnectionCloses(t *testing.T) { } } +func TestRemoteWorkspacePluginContextFollowsTheConnectedHost(t *testing.T) { + h, kernel, timers, logger := remoteWorkspaceHarness(t) + service, err := pluginservice.Open(kernel, h.store, t.TempDir()) + if err != nil { + t.Fatal(err) + } + h.app.plugins = service + t.Cleanup(service.Contexts.CloseAll) + p := h.openRemoteTestProject(t) + initial := p.pluginContext + const pluginID = "dev.lithe.test.remote-metadata" + caller := pluginhost.WithCaller(t.Context(), pluginhost.Caller{PluginID: pluginID}) + checkHost := func(ref pluginservice.ContextRef, arch string) { + t.Helper() + request, err := json.Marshal(map[string]pluginservice.ContextRef{"context": ref}) + if err != nil { + t.Fatal(err) + } + result, refusal := service.HostServices.Respond(caller, "lithe/host/workspace/getContext", request) + var metadata struct { + Authority struct { + Kind string + ID string + Platform core.RemotePlatform + } + Folders []struct{ RootID, Path string } + } + if refusal != nil { + t.Fatalf("getContext: %+v", refusal) + } + if err := json.Unmarshal(result, &metadata); err != nil { + t.Fatal(err) + } + wantPlatform := core.RemotePlatform{OS: "linux", Arch: arch} + if metadata.Authority.Kind != "remote" || metadata.Authority.ID != p.remote.connectionID || + metadata.Authority.Platform != wantPlatform || len(metadata.Folders) != 1 || + metadata.Folders[0].Path != "" { + t.Fatalf("unexpected remote metadata: %s", result) + } + result, refusal = service.HostServices.Respond(caller, "lithe/host/workspace/getHostPaths", request) + var paths struct { + Folders []struct{ RootID, HostPath string } + } + if refusal != nil { + t.Fatalf("getHostPaths: %+v", refusal) + } + if err := json.Unmarshal(result, &paths); err != nil { + t.Fatal(err) + } + if len(paths.Folders) != 1 || paths.Folders[0].HostPath != remoteTestHome+"/project" || + paths.Folders[0].RootID != metadata.Folders[0].RootID { + t.Fatalf("unexpected remote paths: %s", result) + } + } + checkHost(initial, "x86_64") + awaitSweep := func(session string) { + t.Helper() + h.await("deployment sweep on "+session, func() bool { + kernel.mu.Lock() + defer kernel.mu.Unlock() + return slices.Contains(kernel.deploymentSweeps, session) + }) + } + awaitSweep("session-1") + reconnect := func(target, session string) { + t.Helper() + kernel.set(func(k *remoteHostKernel) { + k.target = target + k.once = &core.Error{Command: "remote.serverState", Code: core.CodeConnectionClosed, Message: "closed"} + }) + h.fire(t, timers) + losses := countFailures(logger, "remote_session_lost") + h.fireReconnect(t, timers, p.remote) + h.await("the replacement host session", func() bool { + if countFailures(logger, "remote_session_lost") > losses || p.remote.session == "" && p.remote.reconnecting == nil { + t.Fatalf("session %s did not stay connected (current %q, link %v)", session, p.remote.session, p.remote.link) + } + return p.remote.session == session && !p.remote.beating && !p.tree.reading + }) + awaitSweep(session) + } + reconnect("x86_64-unknown-linux-musl", "session-2") + if p.pluginContext != initial { + t.Fatalf("same host platform replaced context %+v with %+v", initial, p.pluginContext) + } + reconnect("aarch64-unknown-linux-musl", "session-3") + current := p.pluginContext + if current.ContextID != initial.ContextID || current.Generation != initial.Generation+1 { + t.Fatalf("changed platform did not advance generation: %+v to %+v", initial, current) + } + if _, err := service.Contexts.Lookup(initial); !errors.Is(err, pluginservice.ErrContextExpired) { + t.Fatalf("old context lookup: %v", err) + } + checkHost(current, "arm64") + kernel.set(func(k *remoteHostKernel) { + if want := []string{"session-1", "session-2", "session-3"}; !slices.Equal(k.deploymentSweeps, want) { + t.Errorf("deployment sweeps ran on %v, want %v", k.deploymentSweeps, want) + } + }) + h.await("the run configuration types for the reconnected host", func() bool { + return p.runConfigsSettled() && !p.runConfigs.typesLoading + }) + if countFailures(logger, "run_config_plugins") != 0 || countFailures(logger, "run_config_types") != 0 { + t.Fatal("could not resolve installed plugins or run configuration types for the remote workspace") + } + h.app.closeProject() + h.await("the closed workspace", func() bool { return h.app.project == nil }) + if _, err := service.Contexts.Lookup(current); !errors.Is(err, pluginservice.ErrContextExpired) { + t.Fatalf("closed context lookup: %v", err) + } +} + // Back ends the browser's session and shows the form again; a folder that does not exist says so // in the browser and keeps Open disabled. func TestRemoteBrowserBackEndsTheSession(t *testing.T) { diff --git a/desktop/internal/workbench/runconfig.go b/desktop/internal/workbench/runconfig.go index 3577431e04..5f7fb87541 100644 --- a/desktop/internal/workbench/runconfig.go +++ b/desktop/internal/workbench/runconfig.go @@ -129,6 +129,10 @@ func (a *App) refreshRunConfigurations(p *project) { if p == nil { return } + connection, connected := captureWorkspaceConnection(p) + if !connected { + return + } s := &p.runConfigs s.generation++ generation := s.generation @@ -146,14 +150,22 @@ func (a *App) refreshRunConfigurations(p *project) { snapshot = json.RawMessage("[]") } root, kernel := p.root, a.kernel + finish := func(resolved core.RunConfigResolution, err error) func(*App) { + return func(a *App) { + if connection == nil || connection.IsCurrent() { + a.finishRunConfigurations(p, generation, resolved, err) + } + } + } a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { + ctx = attachedWorkspaceContext(ctx, connection) if snapshot != nil { if _, err := kernel.GenerateRunConfigurations(ctx, root, snapshot); err != nil { - return func(a *App) { a.finishRunConfigurations(p, generation, core.RunConfigResolution{}, err) } + return finish(core.RunConfigResolution{}, err) } } resolved, err := kernel.ResolveRunConfigurations(ctx, root, a.runConfigPlugins(ctx)) - return func(a *App) { a.finishRunConfigurations(p, generation, resolved, err) } + return finish(resolved, err) }) } @@ -240,7 +252,7 @@ func (a *App) runConfiguration(p *project, id string) { } // A configuration that allows several instances starts beside the ones that run; any // other that runs is stopped first and started again once it ended (startRun). - if configuration := p.runConfigs.configuration(id); configuration != nil && configuration.AllowMultipleInstances { + if configuration := p.runConfigs.configuration(id); configuration != nil && configuration.AllowMultipleInstances && !p.safeMode() { start(a, p) return } @@ -262,6 +274,16 @@ func (a *App) startRunConfiguration(p *project, id string) (*buildOperation, err // startRunConfigurationWith is startRunConfiguration; debug, when set, prepares the service // suspended for the adapter the host selected (debugRunConfiguration), and Rerun debugs again. func (a *App) startRunConfigurationWith(p *project, id string, debug *connectionDebug) (*buildOperation, error) { + connection, connected := captureWorkspaceConnection(p) + if debug != nil && debug.connection != nil { + connection, connected = debug.connection, debug.connection.IsCurrent() + } + if !connected { + return nil, refuseBuild(refusalNotReady, "the workspace is disconnected") + } + if p.safeMode() { + return nil, refuseBuild(refusalNotReady, "the workspace is not trusted") + } configuration := p.runConfigs.configuration(id) if configuration == nil { return nil, refuseBuild(refusalNotFound, "unknown run configuration") @@ -276,19 +298,11 @@ func (a *App) startRunConfigurationWith(p *project, id string, debug *connection a.notifyError(message) return nil, refuseBuild(refusalNotReady, message) } - // A remote workspace runs its built-in process runs on its host; a debugger and the runs of - // plugins, which run on this computer, do not reach it yet. - if p.remote != nil && (debug != nil || !configuration.IsProcess()) { - message := i18n.Shared(a.language(), "desktop.run.remote.unsupported") - a.operationRejected("run_configuration", "remote_workspace") - a.notifyError(message) - return nil, refuseBuild(refusalNotSupported, message) - } if configuration.IsProcess() { if debug != nil { return nil, refuseBuild(refusalNotSupported, "a built-in process run has no debugger") } - return a.startProcessRun(p, *configuration), nil + return a.startProcessRun(p, *configuration, connection), nil } if key, ok := configuration.RunTypeReference(); ok { if debug != nil { @@ -299,7 +313,7 @@ func (a *App) startRunConfigurationWith(p *project, id string, debug *connection a.notifyError(a.text.Build.TargetMissing) return nil, refuseBuild(refusalNotReady, a.text.Build.TargetMissing) } - return a.startProcessRun(p, *configuration), nil + return a.startProcessRun(p, *configuration, connection), nil } reference, ok := configuration.BuildReference() if !ok { @@ -323,6 +337,7 @@ func (a *App) startRunConfigurationWith(p *project, id string, debug *connection a.runConfiguration(p, id) }) op.debug = debug + op.connection = connection // The run starts a process on the files on disk, so unsaved documents are saved first, // as a rerun does; a failed save keeps the run from starting. The save reports its own // failure, so the window's status only drops the preparation. @@ -347,7 +362,7 @@ func (a *App) prepareConfiguredRun(p *project, op *buildOperation, id string, re { root, kernel := p.root, a.kernel a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { - prepare, release := op.bind(ctx) + prepare, release := op.bind(attachedWorkspaceContext(ctx, op.connection)) defer release() inputs, err := kernel.ProviderLaunchInputs(prepare, root, id, reference.Root) if err != nil { @@ -358,7 +373,7 @@ func (a *App) prepareConfiguredRun(p *project, op *buildOperation, id string, re a.finishBuildError(p, op, context.Canceled) return } - if index >= len(p.build.instances) || p.build.instances[index].PluginID != reference.PluginID { + if index != p.buildInstanceIndex(reference) || !p.build.instances[index].modelLoaded { a.notifyError(a.text.Build.TargetMissing) a.finishBuildError(p, op, errors.New(a.text.Build.TargetMissing)) return diff --git a/desktop/internal/workbench/runconfig_before_launch.go b/desktop/internal/workbench/runconfig_before_launch.go index 295f5bceb8..97fd95757a 100644 --- a/desktop/internal/workbench/runconfig_before_launch.go +++ b/desktop/internal/workbench/runconfig_before_launch.go @@ -19,7 +19,6 @@ import ( "fmt" "slices" - "github.com/1lck/Lithe-IDEA/desktop/internal/buildprocess" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/vivaui/viva/gfx" @@ -52,7 +51,7 @@ func (a *App) runBeforeLaunch(p *project, op *buildOperation, id string, start f root, kernel := p.root, a.kernel kinds, language := p.runConfigs.kinds(), a.language().Code() a.background(p, runPreparationTimeout, func(ctx context.Context) func(*App) { - prepare, release := op.bind(ctx) + prepare, release := op.bind(attachedWorkspaceContext(ctx, op.connection)) defer release() steps, err := kernel.RunBeforeLaunch(prepare, root, id, a.runTypePlugins(prepare, kernel, kinds, language)) return func(a *App) { @@ -72,16 +71,6 @@ func (a *App) runBeforeLaunch(p *project, op *buildOperation, id string, start f start() return } - // A remote workspace runs a step that starts another built-in run on its host. A - // plugin's task is planned by the plugin's backend on this computer, which reads no - // host files (#2231 §2, R3), so a list naming one does not start. - if p.remote != nil && slices.ContainsFunc(steps.Steps, func(step core.RunBeforeLaunchItem) bool { return step.Task != nil }) { - message := i18n.Shared(a.language(), "desktop.run.remote.beforeLaunch") - a.operationRejected("run_before_launch", "remote_workspace") - a.notifyError(message) - a.finishBuildError(p, op, errors.New(message)) - return - } run := func() { a.runBeforeLaunchSteps(p, op, steps.Steps, start) } if steps.Confirmation == nil || a.beforeLaunchApproved(root, steps.Confirmation.Fingerprint) { run() @@ -167,15 +156,13 @@ func (a *App) runBeforeLaunchSteps(p *project, op *buildOperation, steps []core. } } if p.remote != nil { - run.remote = &remoteRunHost{ - kernel: a.kernel, binding: p.remote.binding, root: p.root, language: run.language, - output: func(text string) { a.streamBuildOutput(p, op, text) }, - lost: a.remoteSessionLost(p), - } + host := a.remoteRunHostFor(p, op) + run.remote = &host } a.background(p, 0, func(ctx context.Context) func(*App) { + ctx = attachedWorkspaceContext(ctx, op.connection) if run.remote != nil { - run.remote.failed = func(operation string, err error) { a.backgroundFailedIn(ctx, operation, remoteLogError(err)) } + run.remote.logFailures(a, ctx) } for index, step := range steps { header := i18n.SharedFormat(run.language, "desktop.runConfig.beforeLaunch.stepHeader", map[string]string{ @@ -228,7 +215,7 @@ func (a *App) runBeforeLaunchTask(ctx context.Context, p *project, run beforeLau return errors.New(run.messages.TargetMissing) } task := *step.Task - spec, err := a.declaredProcessSpec(ctx, p, run.root, run.pluginRoot, instances, run.messages, func(manifest json.RawMessage, sources declaredPlanSources) (core.BuildPlan, error) { + planned, err := a.planDeclaredProcess(ctx, p, run.root, run.pluginRoot, instances, run.messages, func(manifest json.RawMessage, sources declaredPlanSources) (core.BuildPlan, error) { return run.kernel.PlanBeforeLaunchTask(ctx, manifest, task.BuildSystemID, run.root, core.BeforeLaunchTaskPlanRequest{ Task: task, WorkingDirectory: step.WorkingDirectory, Instances: sources.instances, PluginDirectory: sources.pluginDirectory, WorkspaceStateDirectory: sources.stateDirectory, @@ -241,7 +228,16 @@ func (a *App) runBeforeLaunchTask(ctx context.Context, p *project, run beforeLau if err != nil { return err } - process, err := buildprocess.Start(ctx, spec, func(_ buildprocess.Stream, text string) { output(text) }) + if run.remote != nil { + host := *run.remote + host.label = core.NewRemoteResourceLabel("run", step.Name) + start, err := host.command(planned) + if err != nil { + return err + } + return host.waitStep(ctx, start) + } + process, err := planned.startLocal(ctx, run.root, output) if err != nil { return err } diff --git a/desktop/internal/workbench/runconfig_changes.go b/desktop/internal/workbench/runconfig_changes.go index e494c1ffd8..3550d74137 100644 --- a/desktop/internal/workbench/runconfig_changes.go +++ b/desktop/internal/workbench/runconfig_changes.go @@ -37,6 +37,34 @@ type runConfigFile struct { snapshot configfile.Snapshot } +// backgroundRunConfig captures the source of an edit before the window queues it. +func (a *App) backgroundRunConfig(p *project, work func(context.Context) func(*App)) { + connection, connected := captureWorkspaceConnection(p) + a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { + if !connected { + disconnected, cancel := context.WithCancel(ctx) + cancel() + return work(disconnected) + } + return work(attachedWorkspaceContext(ctx, connection)) + }) +} + +// applyRunConfigChanges sends an edit to the same filesystem Core read. +func (a *App) applyRunConfigChanges(ctx context.Context, root string, changes []core.RunConfigChange) error { + if len(changes) == 0 { + return ctx.Err() + } + if core.RemoteWorkspaceOf(ctx) == nil { + return applyRunConfigChanges(ctx, root, changes) + } + conflict, err := a.kernel.ApplyRemoteRunConfigurationChanges(ctx, root, changes) + if conflict { + return errors.Join(configfile.ErrConflict, err) + } + return err +} + // applyRunConfigChanges applies the file changes of one Core edit reply as one transaction. // Every file must still hold the bytes Core computed its change from, else nothing is written // and the result is configfile.ErrConflict. Writes come before deletions, so a document that diff --git a/desktop/internal/workbench/runconfig_dialog.go b/desktop/internal/workbench/runconfig_dialog.go index e98dff8afa..712d4b2f24 100644 --- a/desktop/internal/workbench/runconfig_dialog.go +++ b/desktop/internal/workbench/runconfig_dialog.go @@ -1142,10 +1142,10 @@ func (p *project) runConfigDialogArrangement() (core.RunConfigArrangement, bool) // the copy's ID. func (a *App) copyRunConfiguration(p *project, id, name string, done func(string, error)) { root, kernel := p.root, a.kernel - a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { + a.backgroundRunConfig(p, func(ctx context.Context) func(*App) { copied, changes, err := kernel.CopyRunConfiguration(ctx, root, id, name, a.runConfigPlugins(ctx)) if err == nil { - err = applyRunConfigChanges(ctx, root, changes) + err = a.applyRunConfigChanges(ctx, root, changes) } return func(a *App) { if err != nil { @@ -1159,11 +1159,11 @@ func (a *App) copyRunConfiguration(p *project, id, name string, done func(string // arrangeRunConfigurations writes the folders, order and sort choice of request. func (a *App) arrangeRunConfigurations(p *project, request core.RunConfigArrangement, done func(error)) { kernel := a.kernel - a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { + a.backgroundRunConfig(p, func(ctx context.Context) func(*App) { request.Plugins = a.runConfigPlugins(ctx) changes, err := kernel.ArrangeRunConfigurations(ctx, request) if err == nil { - err = applyRunConfigChanges(ctx, request.Root, changes) + err = a.applyRunConfigChanges(ctx, request.Root, changes) } return func(a *App) { if err != nil { diff --git a/desktop/internal/workbench/runconfig_edit.go b/desktop/internal/workbench/runconfig_edit.go index 715d68cc99..cd596e79eb 100644 --- a/desktop/internal/workbench/runconfig_edit.go +++ b/desktop/internal/workbench/runconfig_edit.go @@ -143,7 +143,7 @@ func (a *App) openRunConfigEditor(p *project, id string) *runConfigEditor { generation := e.generation args, kernel, root := slices.Clone(configuration.Args), a.kernel, p.root kinds, language := p.runConfigs.kinds(), a.language().Code() - a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { + a.backgroundRunConfig(p, func(ctx context.Context) func(*App) { texts, err := kernel.RunArgumentText(ctx, [][]string{args}) if err == nil && len(texts) != 1 { err = errors.New("runConfig.argumentText returned no text") @@ -304,7 +304,7 @@ func (a *App) saveRunConfigEditor(p *project, e *runConfigEditor, done func(ok b done(true) } } - a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { + a.backgroundRunConfig(p, func(ctx context.Context) func(*App) { if len(multiSelectEdits) != 0 && multiSelectInstance != nil { request := core.BuildResolveOptionsRequest{ Options: editorSnapshot.options, @@ -357,7 +357,7 @@ func (a *App) saveRunConfigOptions(ctx context.Context, edit core.RunOptionsEdit if err != nil { return err } - return applyRunConfigChanges(ctx, edit.Root, changes) + return a.applyRunConfigChanges(ctx, edit.Root, changes) } // runConfigSaveFailure words a failed save: another edit that came first, or the reason. @@ -426,7 +426,7 @@ func providerRunOptionsJSON(e *runConfigEditor) (json.RawMessage, error) { // loadRunConfigInstalls reads the toolchain discovery the settings page reads, so the editor can offer // the discovered installations. The answer is applied only while the same editor is open. func (a *App) loadRunConfigInstalls(p *project, e *runConfigEditor, generation uint64) { - a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { + a.backgroundRunConfig(p, func(ctx context.Context) func(*App) { snapshot, err := settingsToolchains{app: a}.Load(ctx) var installs []runConfigInstall for _, tool := range snapshot.Tools { diff --git a/desktop/internal/workbench/runconfig_form.go b/desktop/internal/workbench/runconfig_form.go index d963470167..cb6e04eec6 100644 --- a/desktop/internal/workbench/runconfig_form.go +++ b/desktop/internal/workbench/runconfig_form.go @@ -177,7 +177,7 @@ func (a *App) loadRunConfigTypes(p *project, reload bool) { } s.typesLoading, s.typesStale = true, false kernel, language := a.kernel, a.language() - a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { + a.backgroundRunConfig(p, func(ctx context.Context) func(*App) { kinds, err := a.readRunConfigKinds(ctx, kernel, language.Code()) return func(a *App) { s := &p.runConfigs @@ -234,7 +234,7 @@ func (f *runConfigForm) ready() bool { // kind's fields read in the interface language and the Before Launch field offers the tasks. func (a *App) requestRunConfigForm(p *project, f *runConfigForm, generation uint64, request core.RunEditorFormRequest, initial bool) { kernel, kinds, language := a.kernel, p.runConfigs.kinds(), a.language().Code() - a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { + a.backgroundRunConfig(p, func(ctx context.Context) func(*App) { read := a.runTypeRead(ctx, kernel, kinds, language) request.RunTypePlugins = read.plugins form, err := kernel.RunEditorForm(ctx, request) @@ -428,12 +428,12 @@ func (a *App) saveRunConfigForm(p *project, f *runConfigForm, done func(id strin generation := f.generation request := core.RunConfigurationSave{Root: p.root, Provider: f.kind.provider, RunType: f.kind.key(), ConfigurationID: f.id, Values: f.collect()} kernel, kinds, language := a.kernel, p.runConfigs.kinds(), a.language().Code() - a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { + a.backgroundRunConfig(p, func(ctx context.Context) func(*App) { request.Plugins = a.runConfigPlugins(ctx) request.RunTypePlugins = a.runTypePlugins(ctx, kernel, kinds, language) saved, err := kernel.SaveRunConfiguration(ctx, request) if err == nil && saved.Status == "saved" { - err = applyRunConfigChanges(ctx, request.Root, saved.Changes) + err = a.applyRunConfigChanges(ctx, request.Root, saved.Changes) } else if err == nil && saved.Status != "invalid" { err = errors.New("runConfig.saveConfiguration returned an unknown status") } @@ -489,10 +489,10 @@ func (a *App) deleteRunConfiguration(p *project, id string) { // configuration from every layer and applies them; done gets the failure, logged already. func (a *App) removeRunConfiguration(p *project, id string, done func(error)) { root, kernel := p.root, a.kernel - a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { + a.backgroundRunConfig(p, func(ctx context.Context) func(*App) { changes, err := kernel.DeleteRunConfiguration(ctx, root, id, a.runConfigPlugins(ctx)) if err == nil { - err = applyRunConfigChanges(ctx, root, changes) + err = a.applyRunConfigChanges(ctx, root, changes) } return func(a *App) { if err != nil { diff --git a/desktop/internal/workbench/runconfig_process.go b/desktop/internal/workbench/runconfig_process.go index 892b89f5a3..97074cb59c 100644 --- a/desktop/internal/workbench/runconfig_process.go +++ b/desktop/internal/workbench/runconfig_process.go @@ -37,11 +37,12 @@ var errRunProgramNotFound = errors.New("run program not found") // startProcessRun begins the run of a built-in process configuration, or of one of a kind a // plugin declares, beside the window's other executions and starts it once unsaved documents // are saved, so the process reads the files on disk. Rerun starts it again. -func (a *App) startProcessRun(p *project, configuration core.RunConfiguration) *buildOperation { +func (a *App) startProcessRun(p *project, configuration core.RunConfiguration, connection *core.RemoteWorkspaceConnection) *buildOperation { id := configuration.ID op := a.beginRunOperation(p, configuration.Name, id, configurationRunKey(id), func(a *App, p *project) { a.runConfiguration(p, id) }) + op.connection = connection a.saveProjectDocuments(p, func(ok bool) { if op.cancelled { a.finishBuildError(p, op, context.Canceled) @@ -72,6 +73,7 @@ func (a *App) startProcessRun(p *project, configuration core.RunConfiguration) * func (a *App) launchProcessRun(p *project, op *buildOperation, id string) { root, kernel, language := p.root, a.kernel, a.language() a.background(p, 0, func(ctx context.Context) func(*App) { + ctx = attachedWorkspaceContext(ctx, op.connection) bounded, cancel := context.WithTimeout(ctx, runPreparationTimeout) defer cancel() prepare, release := op.bind(bounded) diff --git a/desktop/internal/workbench/runconfig_types.go b/desktop/internal/workbench/runconfig_types.go index 91557049df..8ac7ece9ce 100644 --- a/desktop/internal/workbench/runconfig_types.go +++ b/desktop/internal/workbench/runconfig_types.go @@ -232,21 +232,42 @@ func (a *App) launchDeclaredRun(p *project, op *buildOperation, id string, key c return } root, kernel, messages, pluginRoot := p.root, a.kernel, a.text.Build, a.plugins.Root + var host *remoteRunHost + if p.remote != nil { + remote := a.remoteRunHostFor(p, op) + host = &remote + } a.background(p, 0, func(ctx context.Context) func(*App) { + ctx = attachedWorkspaceContext(ctx, op.connection) bounded, cancel := context.WithTimeout(ctx, runPreparationTimeout) defer cancel() prepare, release := op.bind(bounded) defer release() - spec, err := a.declaredRunSpec(prepare, p, kernel, root, pluginRoot, id, key, instances, messages) + planned, err := a.planDeclaredProcess(prepare, p, root, pluginRoot, instances, messages, func(manifest json.RawMessage, sources declaredPlanSources) (core.BuildPlan, error) { + return kernel.PlanRunConfiguration(prepare, manifest, key.BuildSystemID, root, core.RunConfigurationPlanRequest{ + ConfigurationID: id, Instances: sources.instances, + PluginDirectory: sources.pluginDirectory, WorkspaceStateDirectory: sources.stateDirectory, + ProjectCodeAllowed: p.trust.allowed(), + }) + }) if err == nil { err = prepare.Err() } if err != nil { return func(a *App) { a.finishBuildError(p, op, err) } } - process, err := buildprocess.Start(ctx, spec, func(_ buildprocess.Stream, text string) { - a.streamBuildOutput(p, op, text) - }) + if host != nil { + host.logFailures(a, ctx) + start, err := host.command(planned) + if err != nil { + return func(a *App) { a.finishBuildError(p, op, err) } + } + err = host.run(ctx, start, func(process *remoteProcess) { + a.post(func(a *App) { a.attachProcess(p, op, process) }) + }) + return func(a *App) { a.finishBuildRun(p, op, err) } + } + process, err := planned.startLocal(ctx, root, func(text string) { a.streamBuildOutput(p, op, text) }) if err != nil { return func(a *App) { a.finishBuildError(p, op, err) } } @@ -256,71 +277,59 @@ func (a *App) launchDeclaredRun(p *project, op *buildOperation, id string, key c }) } -// declaredRunSpec is the process a configuration of a declared kind starts: Core's plan -// (`build.runConfigurationPlan`) of the build system's command, run by the build tool the -// chosen instance resolves, at the configuration's working directory under the project. The -// plugin package is read-only, so the writable state directory the plan may name is the -// plugin's per-workspace state, outside it. -func (a *App) declaredRunSpec(ctx context.Context, p *project, kernel Kernel, root, pluginRoot, id string, key core.RunTypeKey, instances []buildInstance, messages i18n.BuildMessages) (buildprocess.Spec, error) { - return a.declaredProcessSpec(ctx, p, root, pluginRoot, instances, messages, func(manifest json.RawMessage, sources declaredPlanSources) (core.BuildPlan, error) { - return kernel.PlanRunConfiguration(ctx, manifest, key.BuildSystemID, root, core.RunConfigurationPlanRequest{ - ConfigurationID: id, Instances: sources.instances, - PluginDirectory: sources.pluginDirectory, WorkspaceStateDirectory: sources.stateDirectory, - ProjectCodeAllowed: p.trust.allowed(), - }) - }) -} - -// declaredPlanSources are what Core's plan of a declared kind or task takes from the detected -// instances of its build system: every instance, and the package directory and writable -// per-workspace state directory of the plugin. +// declaredPlanSources are the build instances and directories Core needs for a declared run. type declaredPlanSources struct { instances []core.RunTypeInstance pluginDirectory, stateDirectory string } -// declaredProcessSpec is the process of a plan of a declared kind or task: request asks Core -// for the plan with the plugin's manifest and sources, and the process runs the build tool the -// instance the plan picks resolves, at the plan's working directory under the project. -func (a *App) declaredProcessSpec(ctx context.Context, p *project, root, pluginRoot string, instances []buildInstance, messages i18n.BuildMessages, request func(json.RawMessage, declaredPlanSources) (core.BuildPlan, error)) (buildprocess.Spec, error) { +type declaredProcess struct { + plan core.BuildPlan + execution buildExecution +} + +// planDeclaredProcess selects a build instance and resolves its executable on the host +// captured by ctx. Declared commands expose no package or state directory variables. +func (a *App) planDeclaredProcess(ctx context.Context, p *project, root, pluginRoot string, instances []buildInstance, messages i18n.BuildMessages, request func(json.RawMessage, declaredPlanSources) (core.BuildPlan, error)) (declaredProcess, error) { first := instances[0] - state := buildStateDirectory(pluginRoot, root, first) - if err := os.MkdirAll(state, 0o700); err != nil { - return buildprocess.Spec{}, err - } - sources := declaredPlanSources{ - pluginDirectory: first.PackageDirectory, stateDirectory: state, - instances: make([]core.RunTypeInstance, 0, len(instances)), + sources := declaredPlanSources{instances: make([]core.RunTypeInstance, 0, len(instances))} + if p.remote == nil { + sources.pluginDirectory = first.PackageDirectory + sources.stateDirectory = buildStateDirectory(pluginRoot, root, first) + if err := os.MkdirAll(sources.stateDirectory, 0o700); err != nil { + return declaredProcess{}, err + } } for _, instance := range instances { sources.instances = append(sources.instances, core.RunTypeInstance{Root: instance.Root, Options: instance.Options}) } planned, err := request(first.Manifest, sources) if err != nil { - return buildprocess.Spec{}, err + return declaredProcess{}, err } if planned.Provider != nil { - return buildprocess.Spec{}, errors.New("the declared plan names a provider request") + return declaredProcess{}, errors.New("the declared plan names a provider request") } index := slices.IndexFunc(instances, func(instance buildInstance) bool { return instance.Root == planned.Root }) if index < 0 { - return buildprocess.Spec{}, fmt.Errorf("the declared plan names no detected instance: %s", planned.Root) + return declaredProcess{}, fmt.Errorf("the declared plan names no detected instance: %s", planned.Root) } - directory, err := projectRunDirectory(root, planned.WorkingDirectory) + execution, err := a.resolveBuildExecutable(ctx, p, instances[index], messages) if err != nil { - return buildprocess.Spec{}, err + return declaredProcess{}, err } - execution, err := a.resolveBuildExecutable(ctx, p, instances[index], messages) + return declaredProcess{plan: planned, execution: execution}, nil +} + +func (p declaredProcess) startLocal(ctx context.Context, root string, output func(string)) (*buildprocess.Process, error) { + directory, err := projectRunDirectory(root, p.plan.WorkingDirectory) if err != nil { - return buildprocess.Spec{}, err - } - return buildprocess.Spec{ - Kind: processledger.KindRun, - Executable: execution.Executable, - Arguments: planned.Arguments, - WorkingDirectory: directory, - Environment: applyToolchainSelection(planned.Environment, execution.selection()), - }, nil + return nil, err + } + return buildprocess.Start(ctx, buildprocess.Spec{ + Kind: processledger.KindRun, Executable: p.execution.Executable, Arguments: p.plan.Arguments, + WorkingDirectory: directory, Environment: applyToolchainSelection(p.plan.Environment, p.execution.selection()), + }, func(_ buildprocess.Stream, text string) { output(text) }) } // kindTitle names kind k: the host's title of a built-in kind, the translated title the plugin diff --git a/desktop/internal/workbench/runs.go b/desktop/internal/workbench/runs.go index f361d4aa11..6c150436e3 100644 --- a/desktop/internal/workbench/runs.go +++ b/desktop/internal/workbench/runs.go @@ -1,6 +1,7 @@ package workbench import ( + "bytes" "context" "errors" "path/filepath" @@ -151,11 +152,14 @@ func (d *runDecoders) end(id string) { // resolveRunTool resolves a tool a run needs through the same toolchain layers // Build and Debug use: project pins, user choices, then discovery. -func (a *App) resolveRunTool(ctx context.Context, workspaceRoot, tool string) (pluginservice.RunExecutable, error) { - selection, err := a.resolveToolchainSelection(ctx, workspaceRoot, ".", tool, "") +func (a *App) resolveRunTool(ctx context.Context, workspaceRoot, directory, tool string) (pluginservice.RunExecutable, error) { + selection, err := a.resolveToolchainSelection(ctx, workspaceRoot, directory, tool, "") if err != nil { return pluginservice.RunExecutable{}, err } + if core.RemoteWorkspaceOf(ctx) != nil { + return pluginservice.RunExecutable{Path: selection.Executable, Environment: selection.Environment, PathPrepend: selection.PathPrepend}, nil + } environment := applyToolchainSelection(nil, selection) return pluginservice.RunExecutable{Path: selection.Executable, Environment: environment}, nil } @@ -163,17 +167,20 @@ func (a *App) resolveRunTool(ctx context.Context, workspaceRoot, tool string) (p // resolveBackendTool resolves the tool a plugin backend or language server launch // names, through the same layers as a run's tool, for the workspace it serves. func (a *App) resolveBackendTool(ctx context.Context, _, workingDirectory, tool string) (pluginbackend.ToolExecutable, error) { - resolved, err := a.resolveRunTool(ctx, workingDirectory, tool) + resolved, err := a.resolveRunTool(ctx, workingDirectory, ".", tool) if err != nil { return pluginbackend.ToolExecutable{}, err } - return pluginbackend.ToolExecutable{Path: resolved.Path, Environment: resolved.Environment}, nil + return pluginbackend.ToolExecutable{Path: resolved.Path, Environment: resolved.Environment, PathPrepend: resolved.PathPrepend}, nil } // resolveBackendToolEntry supplies native installation facts and the verified // entry to Core. The definition, not the host, decides how a tool loads it. func (a *App) resolveBackendToolEntry(ctx context.Context, _ string, workingDirectory string, input pluginbackend.ToolEntryLaunch) (pluginbackend.ToolExecutable, error) { selection := core.ToolchainSelection{Executable: input.Executable} + if input.Home != "" { + selection.Home = &input.Home + } if selection.Executable == "" { var err error selection, err = a.resolveToolchainSelection(ctx, workingDirectory, ".", input.Tool, input.MinimumVersion) @@ -181,7 +188,8 @@ func (a *App) resolveBackendToolEntry(ctx context.Context, _ string, workingDire return pluginbackend.ToolExecutable{}, err } } - manifests, err := a.toolchainManifests(ctx) + local := core.WithoutRemoteWorkspace(ctx) + manifests, err := a.toolchainManifests(local) if err != nil { return pluginbackend.ToolExecutable{}, err } @@ -193,13 +201,59 @@ func (a *App) resolveBackendToolEntry(ctx context.Context, _ string, workingDire if selection.Home != nil { home = *selection.Home } - launch, err := a.kernel.InstantiateToolchainLaunch(ctx, registry, input.Tool, selection.Executable, home, input.Entry, input.RuntimeArguments, input.Arguments) + launch, err := a.kernel.InstantiateToolchainLaunch(local, registry, input.Tool, selection.Executable, home, input.Entry, input.RuntimeArguments, input.Arguments) if err != nil { return pluginbackend.ToolExecutable{}, err } + if workspace := core.RemoteWorkspaceOf(ctx); workspace != nil { + if input.Home != "" && input.MinimumVersion != "" { + if err := a.checkRemoteRuntimeVersion(ctx, workspace, registry, input, launch.VersionArguments); err != nil { + return pluginbackend.ToolExecutable{}, err + } + } + return pluginbackend.ToolExecutable{Path: launch.Executable, Arguments: launch.Arguments, Environment: selection.Environment, PathPrepend: selection.PathPrepend}, nil + } return pluginbackend.ToolExecutable{Path: launch.Executable, Arguments: launch.Arguments, Environment: applyToolchainSelection(nil, selection)}, nil } +// A managed artifact's version identifies its archive. Use the tool's +// declared probe to check the executable against a launch's minimum version. +func (a *App) checkRemoteRuntimeVersion(ctx context.Context, workspace *core.RemoteWorkspace, registry []byte, input pluginbackend.ToolEntryLaunch, arguments []string) error { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + const maxOutput = 128 * 1024 + var stdout, stderr bytes.Buffer + exit, err := a.kernel.RunRemoteProcess(ctx, core.RemoteProcessOpen{ + Argv: append([]string{input.Executable}, arguments...), + ScopedCwd: &core.RemoteScopedDirectory{Root: workspace.RemoteRoot()}, + Environment: "login", + }, core.RemoteProcessEvents{Output: func(stream string, data []byte) { + if len(data) > maxOutput-1-stdout.Len()-stderr.Len() { + cancel() + return + } + if stream == "stdout" { + stdout.Write(data) + } else if stream == "stderr" { + stderr.Write(data) + } + }}) + if err != nil { + return err + } + if exit.ExitCode != nil && *exit.ExitCode == 0 && ctx.Err() == nil { + output := stdout.String() + "\n" + stderr.String() + version, err := a.kernel.CheckToolchainVersion(core.WithoutRemoteWorkspace(ctx), registry, input.Tool, output, input.MinimumVersion) + if err != nil { + return err + } + if version.Satisfied { + return nil + } + } + return &core.MarketplaceRejection{Code: "plugin.toolchain.launchMismatch", Message: "The managed runtime does not satisfy the launch's minimum version."} +} + // resolveLanguageTool supplies the complete installation selected by Core. // An unavailable optional tool leaves the language server's configuration alone; // actual I/O failures propagate to the existing server-start failure boundary. @@ -229,8 +283,12 @@ func (a *App) applyRunEvent(event pluginservice.RunEvent) { return } p.links.loaded, p.links.sources = false, nil + label := event.Label + if event.Remote { + label = a.text.Run.RemoteLabel(label) + } entry := &runEntry{ - id: event.RunID, pluginID: event.PluginID, label: event.Label, rerun: event.Rerun, running: true, + id: event.RunID, pluginID: event.PluginID, label: label, rerun: event.Rerun, running: true, processRunning: true, started: a.now(), output: newOutputBuffer(runOutputMaxLines, runOutputBytes), } a.addRunSession(p, entry) @@ -253,6 +311,8 @@ func (a *App) applyRunEvent(event pluginservice.RunEvent) { stopRunPortSampling(entry) messages := a.text.Run switch { + case event.Disconnected: + entry.summary = messages.RemoteDisconnected case event.ExitCode != nil: entry.summary = messages.Exited(*event.ExitCode) case event.Signal != "": @@ -263,7 +323,7 @@ func (a *App) applyRunEvent(event pluginservice.RunEvent) { switch { case entry.stopping: entry.outcome = runStopped - case event.ExitCode != nil && *event.ExitCode != 0 || event.Signal != "": + case event.Disconnected || event.ExitCode != nil && *event.ExitCode != 0 || event.Signal != "": entry.outcome = runFailed default: entry.outcome = runSucceeded diff --git a/desktop/internal/workbench/settings_plugin_actions.go b/desktop/internal/workbench/settings_plugin_actions.go index 9369c95943..e80a7e74a0 100644 --- a/desktop/internal/workbench/settings_plugin_actions.go +++ b/desktop/internal/workbench/settings_plugin_actions.go @@ -15,9 +15,20 @@ import ( func (s pluginSettingsSources) actionWorkspaceCheck(editor pluginservice.SettingsEditor) func() error { publication := s.app.toolchainRoot.Load() + remote := s.app.settingsRemote.Load() return func() error { current := s.app.toolchainRoot.Load() - if current != publication { + if current != publication || s.app.settingsRemote.Load() != remote { + return configfile.ErrConflict + } + if remote != nil { + connection := remote.binding.CaptureConnection() + if !connection.SameAttachment(editor.RemoteConnection()) || !connection.IsCurrent() { + return configfile.ErrConflict + } + return nil + } + if editor.RemoteConnection() != nil { return configfile.ErrConflict } source := editor.Snapshot.Workspace() @@ -105,7 +116,7 @@ func (s pluginSettingsSources) Action(ctx context.Context, editor pluginservice. attached, detached := p.buildSessions.shared[key], p.buildSessions.detached p.buildSessions.mu.Unlock() if attached == nil || attached.Closed() { - if _, err := s.app.attachSharedBuildClient(ctx, p, buildInstance{}, key, server, detached); err != nil { + if _, err := s.app.attachSharedBuildClient(ctx, p, key, server, nil, detached); err != nil { return result, err } } diff --git a/desktop/internal/workbench/settings_plugin_sources.go b/desktop/internal/workbench/settings_plugin_sources.go index 68d71d0252..07f33fbfec 100644 --- a/desktop/internal/workbench/settings_plugin_sources.go +++ b/desktop/internal/workbench/settings_plugin_sources.go @@ -45,10 +45,24 @@ func (s pluginSettingsSources) sourceSettingsCall(ctx context.Context, editor pl } func (s pluginSettingsSources) readSourceSettings(ctx context.Context, editor pluginservice.SettingsEditor, action string, published map[string]string) (pluginsettings.SourceEditor, error) { - plan, err := s.app.plugins.PlanSettingsEditorAction(ctx, editor, action, true, s.actionWorkspaceCheck(editor)) + check := s.sourceSettingsCheck(ctx, editor, action) + plan, err := s.app.plugins.PlanSettingsEditorAction(ctx, editor, action, true, check) if err != nil { return pluginsettings.SourceEditor{}, err } + if plan.Kind != "invoke" || !plan.SourceEditor { + return pluginsettings.SourceEditor{}, configfile.ErrConflict + } + read := func(ctx context.Context, params json.RawMessage) (json.RawMessage, error) { + return s.sourceSettingsCall(ctx, editor, action, params, false) + } + connection := editor.RemoteConnection() + if connection != nil { + read, err = s.app.plugins.PrepareRemoteSettingsHelper(ctx, editor, plan, check) + if err != nil { + return pluginsettings.SourceEditor{}, err + } + } environment, err := s.sourceSettingsContext(ctx, editor, plan, len(published) > 0) if err != nil { return pluginsettings.SourceEditor{}, err @@ -59,12 +73,14 @@ func (s pluginSettingsSources) readSourceSettings(ctx context.Context, editor pl }{Context: environment} if len(published) > 0 { request.Operation = "readAfterSave" + } else if connection != nil { + request.Operation = "read" } params, err := json.Marshal(request) if err != nil { return pluginsettings.SourceEditor{}, err } - raw, err := s.sourceSettingsCall(ctx, editor, action, params, false) + raw, err := read(ctx, params) if err != nil { return pluginsettings.SourceEditor{}, err } @@ -84,6 +100,17 @@ func (s pluginSettingsSources) readSourceSettings(ctx context.Context, editor pl return pluginsettings.SourceEditor{}, configfile.ErrConflict } } + if connection != nil { + host, ok := s.app.kernel.(pluginsettings.RemoteSourceHost) + if !ok { + return pluginsettings.SourceEditor{}, &core.Error{Code: core.CodeNotSupported, Message: "The remote native settings service is unavailable."} + } + sources, err := pluginsettings.CaptureRemoteSources(ctx, host, connection, state) + if err != nil { + return pluginsettings.SourceEditor{}, err + } + return sources, check() + } // The plugin store and the running application's installation are immutable. // macOS resources are siblings of MacOS inside the enclosing .app bundle; // Windows resources live beside the executable in the installation directory. @@ -105,19 +132,30 @@ func (s pluginSettingsSources) SaveSources(ctx context.Context, editor pluginser (settingsToolchains{app: s.app}).recordFailure(ctx, "plugin_settings_source_save", err) } }() - check := func() error { - plan, err := s.app.plugins.PlanSettingsEditorAction(ctx, editor, action, true, s.actionWorkspaceCheck(editor)) - if err != nil { - return err - } - if plan.Kind != "invoke" || !plan.SourceEditor { - return configfile.ErrConflict - } - return nil + if !sources.MatchesConnection(editor.RemoteConnection()) { + return sources, configfile.ErrConflict } - published, err := sources.Apply(ctx, s.app.kernel, edits, func(ctx context.Context, params json.RawMessage) (json.RawMessage, error) { + check := s.sourceSettingsCheck(ctx, editor, action) + edit := func(ctx context.Context, params json.RawMessage) (json.RawMessage, error) { return s.sourceSettingsCall(ctx, editor, action, params, true) - }, check) + } + if editor.RemoteConnection() != nil { + var helper func(context.Context, json.RawMessage) (json.RawMessage, error) + edit = func(ctx context.Context, params json.RawMessage) (json.RawMessage, error) { + if helper == nil { + plan, err := s.app.plugins.PlanSettingsEditorAction(ctx, editor, action, true, check) + if err != nil { + return nil, err + } + helper, err = s.app.plugins.PrepareRemoteSettingsHelper(ctx, editor, plan, check) + if err != nil { + return nil, err + } + } + return helper(ctx, params) + } + } + published, err := sources.Apply(ctx, s.app.kernel, edits, edit, check) if err != nil { return sources, err } @@ -128,6 +166,23 @@ func (s pluginSettingsSources) SaveSources(ctx context.Context, editor pluginser return updated, err } +func (s pluginSettingsSources) sourceSettingsCheck(ctx context.Context, editor pluginservice.SettingsEditor, action string) func() error { + workspace := s.actionWorkspaceCheck(editor) + return func() error { + plan, err := s.app.plugins.PlanSettingsEditorAction(ctx, editor, action, true, workspace) + if err != nil { + return err + } + if plan.Kind != "invoke" || !plan.SourceEditor { + return configfile.ErrConflict + } + if editor.RemoteConnection() != nil { + return s.app.plugins.CheckRemoteSettingsWorkspace(editor) + } + return nil + } +} + // Only native session handles are selected here. Source semantics, grouping and // declaration validation belong to Core; project facts come from the build engine. type sourceEditorBuild struct { @@ -223,7 +278,17 @@ func (s pluginSettingsSources) sourceSettingsContext(ctx context.Context, editor if err != nil { return result, err } - result.Builds = append(result.Builds, sourceEditorBuild{instance.Root, instance.Options, core.BuildTool{Executable: execution.Executable}, sourceEditorProjectModel{Projects: model.Projects}}) + root, projects := instance.Root, model.Projects + if editor.RemoteConnection() != nil { + // Only schema-owned paths are translated. Opaque model properties + // already use the upstream tool's path namespace. + root = current.project.remoteHostPath(root) + projects = append([]core.BuildProject(nil), projects...) + for index := range projects { + projects[index].Path = current.project.remoteHostPath(projects[index].Path) + } + } + result.Builds = append(result.Builds, sourceEditorBuild{root, instance.Options, core.BuildTool{Executable: execution.Executable}, sourceEditorProjectModel{Projects: projects}}) } return result, nil } diff --git a/desktop/internal/workbench/settings_plugins.go b/desktop/internal/workbench/settings_plugins.go index a3ad47c604..10e15fcaca 100644 --- a/desktop/internal/workbench/settings_plugins.go +++ b/desktop/internal/workbench/settings_plugins.go @@ -17,13 +17,27 @@ import ( // is an immutable publication from the workbench window, shared with toolchains. type pluginSettingsSources struct{ app *App } +type remoteSettingsWorkspace struct { + binding *core.RemoteWorkspace + name string +} + func (s pluginSettingsSources) Load(ctx context.Context, id string, language i18n.Language) (editor pluginservice.SettingsEditor, err error) { defer func() { (settingsToolchains{app: s.app}).recordFailure(ctx, "plugin_settings_load", err) }() - root := "" - if current := s.app.toolchainRoot.Load(); current != nil { - root = *current + current := s.app.toolchainRoot.Load() + remote := s.app.settingsRemote.Load() + if remote != nil { + editor, err = s.app.plugins.LoadRemoteSettingsEditor(ctx, id, language.Code(), remote.name, remote.binding) + } else { + root := "" + if current != nil { + root = *current + } + editor, err = s.app.plugins.LoadSettingsEditor(ctx, id, root, language.Code()) + } + if err == nil && (s.app.toolchainRoot.Load() != current || s.app.settingsRemote.Load() != remote) { + err = configfile.ErrConflict } - editor, err = s.app.plugins.LoadSettingsEditor(ctx, id, root, language.Code()) if err == nil { // A skipped translation falls back to the next candidate or to manifest // text; the page still loads, so this is a degraded read, not a failure. @@ -49,7 +63,11 @@ func (s pluginSettingsSources) Load(ctx context.Context, id string, language i18 func (s pluginSettingsSources) Save(ctx context.Context, editor pluginservice.SettingsEditor, scope string, edits []core.PluginSettingEdit) (result pluginsettings.SaveResult, err error) { defer func() { (settingsToolchains{app: s.app}).recordFailure(ctx, "plugin_settings_save", err) }() + workspaceCheck := s.actionWorkspaceCheck(editor) check := func() error { + if scope == "project" && (editor.RemoteConnection() != nil || s.app.settingsRemote.Load() != nil) { + return workspaceCheck() + } if scope != "project" { return nil } diff --git a/desktop/internal/workbench/settings_publication.go b/desktop/internal/workbench/settings_publication.go index 7da6926310..bf65ecc035 100644 --- a/desktop/internal/workbench/settings_publication.go +++ b/desktop/internal/workbench/settings_publication.go @@ -20,6 +20,7 @@ var settingsWindows = struct { type settingsNotice struct { owner core.PluginSettingsOwner root *string + remote *remoteSettingsWorkspace delivery core.SettingsDelivery } @@ -76,7 +77,12 @@ func (a *App) publishSettings(editor pluginservice.SettingsEditor, scope string, if root != nil { workspace = *root } - delivery, err := target.plugins.PlanSettingsDelivery(ctx, editor, scope, effects, workspace) + remote := target.settingsRemote.Load() + var connection *core.RemoteWorkspaceConnection + if remote != nil { + connection = remote.binding.CaptureConnection() + } + delivery, err := target.plugins.PlanSettingsDelivery(ctx, editor, scope, effects, workspace, connection) if err != nil { failures = append(failures, err) continue @@ -84,7 +90,7 @@ func (a *App) publishSettings(editor pluginservice.SettingsEditor, scope string, if !delivery.Refresh { continue } - notice := settingsNotice{owner: editor.SettingsOwner(), root: root, delivery: delivery} + notice := settingsNotice{owner: editor.SettingsOwner(), root: root, remote: remote, delivery: delivery} select { case sub.notices <- notice: target.invalidator.Invalidate() @@ -114,7 +120,7 @@ func (a *App) drainSettings() { if a.settingsWindow != nil { a.settingsWindow.PluginSettingsChanged(notice.owner.PluginID) } - if notice.root != a.toolchainRoot.Load() { + if notice.root != a.toolchainRoot.Load() || notice.remote != a.settingsRemote.Load() { continue } a.applyPluginSettingsEffects(notice.owner, notice.delivery.Effects) diff --git a/desktop/internal/workbench/shell_view.go b/desktop/internal/workbench/shell_view.go index 558103015a..b8680400d6 100644 --- a/desktop/internal/workbench/shell_view.go +++ b/desktop/internal/workbench/shell_view.go @@ -166,11 +166,10 @@ func (a *App) shellPanel(c ui.C, s slot, index int, hidden *slot) ui.Box { // remoteToolWindow reports whether the tool window id works in a remote workspace: the project // listing, search and terminals run on the host, and so do Git's log and commit once the -// workspace is trusted (in safe mode they say so, as in a local project), and so does Run, for the -// built-in process runs; Ports exists only there. +// workspace is trusted. Build, Run, Tests and Debug show remote operations. func remoteToolWindow(id string) bool { switch id { - case itemProject, itemNotifications, itemTerminal, itemFind, itemGit, itemCommit, itemRun, itemPorts: + case itemProject, itemNotifications, itemTerminal, itemFind, itemGit, itemCommit, itemPorts, itemBuild, itemRun, itemTests, itemDebug: return true } return false diff --git a/desktop/internal/workbench/terminals.go b/desktop/internal/workbench/terminals.go index e7966cf739..1976d20e0e 100644 --- a/desktop/internal/workbench/terminals.go +++ b/desktop/internal/workbench/terminals.go @@ -383,15 +383,21 @@ type terminalOptions struct { prefill string // activate selects the new tab; a background plugin terminal leaves the // selection where it was. - activate bool - plugin *pluginTerminal + activate bool + plugin *pluginTerminal + remoteDirectory *core.RemoteScopedDirectory + remoteConnection *core.RemoteWorkspaceConnection + // A debug terminal is one shot. Its session context owns the launch, and + // remoteStarted receives the result on the window thread. + remoteStartContext context.Context + remoteStarted func(pid int64, err error) } // newTerminalWith is newTerminal with the options of a plugin terminal. A terminal of a remote -// workspace runs the host's login shell on the host (remote_terminal.go); a plugin's terminal -// would run on this computer, so a remote workspace refuses it. +// workspace runs the host's login shell or the plugin's approved program on the host. func (a *App) newTerminalWith(p *project, options terminalOptions) *terminal { - if options.plugin != nil && a.refuseRemote(p, "open_terminal") { + if options.plugin != nil && (options.remoteDirectory == nil || !options.remoteConnection.IsCurrent()) && + a.refuseRemote(p, "open_terminal") { return nil } shell := options.shell @@ -428,6 +434,7 @@ func (a *App) newTerminalWith(p *project, options terminalOptions) *terminal { Notify: a.invalidator.Invalidate, Failed: a.terminalFailed, OpenLink: a.openTerminalLink, + NoRestart: options.remoteStarted != nil, } t := &terminal{id: id, number: set.freeNumber(), shell: shell, title: options.title, plugin: options.plugin} config.PasteImage = func() bool { return a.pasteTerminalImage(p, t) } @@ -436,7 +443,7 @@ func (a *App) newTerminalWith(p *project, options terminalOptions) *terminal { } if p.remote != nil { t.host = p.remote.name - t.closeHost = a.remoteTerminalConfig(p, t, &config, dir, config.Env) + t.closeHost = a.remoteTerminalConfig(p, t, &config, options) } t.view = termview.New(config) // A terminal can start before its first paint (Start below), and the switches decide how @@ -444,8 +451,8 @@ func (a *App) newTerminalWith(p *project, options terminalOptions) *terminal { t.view.SetOptions(a.terminalOptions()) a.terminalInput(t) set.list = append(set.list, t) - if options.plugin != nil { - // A plugin asked for this program; it runs even while the tab is not on show. + if options.plugin != nil || options.remoteStarted != nil { + // Explicit commands run even while the tab is hidden. t.view.Start() } return t diff --git a/desktop/internal/workbench/testdata/remote_debug_adapter/main.go b/desktop/internal/workbench/testdata/remote_debug_adapter/main.go new file mode 100644 index 0000000000..724389056c --- /dev/null +++ b/desktop/internal/workbench/testdata/remote_debug_adapter/main.go @@ -0,0 +1,106 @@ +// This fixture speaks DAP over stdin/stdout in the remote project directory. +package main + +import ( + "bufio" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "strings" +) + +func main() { + if err := serve(); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +func serve() error { + root, err := os.Getwd() + if err != nil { + return err + } + source := filepath.Join(root, "source.txt") + input := bufio.NewReader(os.Stdin) + seq := 0 + write := func(message map[string]any) error { + seq++ + message["seq"] = seq + body, err := json.Marshal(message) + if err != nil { + return err + } + _, err = fmt.Fprintf(os.Stdout, "Content-Length: %d\r\n\r\n%s", len(body), body) + return err + } + breakpoint := false + for { + header, err := input.ReadString('\n') + if err != nil { + return err + } + var size int + if _, err := fmt.Sscanf(header, "Content-Length: %d", &size); err != nil || size <= 0 || size > 1<<20 { + return fmt.Errorf("invalid DAP frame header") + } + separator, err := input.ReadString('\n') + if err != nil || strings.TrimSpace(separator) != "" { + return fmt.Errorf("invalid DAP frame separator") + } + body := make([]byte, size) + if _, err := io.ReadFull(input, body); err != nil { + return err + } + var request struct { + Seq int + Command string + Arguments struct { + Source struct{ Path string } + Breakpoints []struct{ Line int } + } + } + if err := json.Unmarshal(body, &request); err != nil { + return err + } + var result, event any + eventName := "" + switch request.Command { + case "initialize": + result = map[string]bool{"supportsConfigurationDoneRequest": true} + eventName = "initialized" + case "setBreakpoints": + lines := request.Arguments.Breakpoints + breakpoint = request.Arguments.Source.Path == source && len(lines) == 1 && lines[0].Line == 3 + result = map[string]any{"breakpoints": []any{map[string]any{"verified": breakpoint, "line": 3}}} + case "configurationDone": + if !breakpoint { + return fmt.Errorf("the remote source breakpoint did not reach the adapter") + } + eventName = "stopped" + event = map[string]any{"reason": "breakpoint", "threadId": 1, "allThreadsStopped": true} + case "threads": + result = map[string]any{"threads": []any{map[string]any{"id": 1, "name": "fixture"}}} + case "stackTrace": + result = map[string]any{"stackFrames": []any{map[string]any{ + "id": 1, "name": "fixture-" + runtime.GOOS, "source": map[string]string{"path": source}, "line": 3, "column": 1, + }}} + case "scopes": + result = map[string]any{"scopes": []any{}} + } + if err := write(map[string]any{"type": "response", "request_seq": request.Seq, "success": true, "command": request.Command, "body": result}); err != nil { + return err + } + if eventName != "" { + if err := write(map[string]any{"type": "event", "event": eventName, "body": event}); err != nil { + return err + } + } + if request.Command == "disconnect" { + return nil + } + } +} diff --git a/desktop/internal/workbench/testdata/remote_debuggee/main.go b/desktop/internal/workbench/testdata/remote_debuggee/main.go new file mode 100644 index 0000000000..736c1c2a68 --- /dev/null +++ b/desktop/internal/workbench/testdata/remote_debuggee/main.go @@ -0,0 +1,162 @@ +package main + +import ( + "bufio" + "encoding/json" + "fmt" + "io" + "net" + "os" + "strconv" + "strings" + "time" +) + +func main() { + run := respond + if len(os.Args) > 1 && os.Args[1] == "provider" { + run = provide + } + if err := run(); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +func respond() error { + var port int + if chosen := os.Getenv("LITHE_FIXTURE_SERVICE_PORT"); chosen != "" { + value, err := strconv.Atoi(chosen) + if err != nil { + return err + } + port = value + } + listener, err := net.ListenTCP("tcp4", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: port}) + if err != nil { + return err + } + defer listener.Close() + if err := listener.SetDeadline(time.Now().Add(45 * time.Second)); err != nil { + return err + } + fmt.Println(listener.Addr().(*net.TCPAddr).Port) + connection, err := listener.AcceptTCP() + if err != nil { + return err + } + defer connection.Close() + if err := connection.SetDeadline(time.Now().Add(5 * time.Second)); err != nil { + return err + } + challenge := make([]byte, len("lithe")) + if _, err := io.ReadFull(connection, challenge); err != nil { + return err + } + if string(challenge) != "lithe" { + return fmt.Errorf("incorrect attach challenge %q", challenge) + } + if _, err := io.WriteString(connection, "linux"); err != nil { + return err + } + if port == 0 { + return nil + } + if err := connection.Close(); err != nil { + return err + } + // The provider-owned process stays alive after DAP attaches so the test can stop it. + extra, err := listener.AcceptTCP() + if err != nil { + return err + } + extra.Close() + return fmt.Errorf("unexpected second attach") +} + +func provide() error { + input := bufio.NewReader(os.Stdin) + for { + var size int + for { + header, err := input.ReadString('\n') + if err == io.EOF { + return nil + } + if err != nil { + return err + } + if strings.TrimSpace(header) == "" { + break + } + if key, value, ok := strings.Cut(header, ":"); ok && strings.EqualFold(key, "Content-Length") { + size, err = strconv.Atoi(strings.TrimSpace(value)) + if err != nil { + return err + } + } + } + if size < 1 || size > 1<<20 { + return fmt.Errorf("invalid provider frame size %d", size) + } + body := make([]byte, size) + if _, err := io.ReadFull(input, body); err != nil { + return err + } + var request struct { + ID json.RawMessage + Method string + Params struct { + LaunchOptions struct { + Debug struct { + Target struct{ Port int } + } + } + } + } + if err := json.Unmarshal(body, &request); err != nil { + return err + } + if request.Method == "exit" { + return nil + } + if len(request.ID) == 0 { + continue + } + var result any + switch request.Method { + case "initialize": + result = map[string]any{"capabilities": map[string]any{ + "experimental": map[string]any{"litheBuild": map[string]int{"version": 0}}, + }} + case "lithe/build/model": + result = map[string]any{ + "format": "litheBuildModel", "version": 0, + "projects": []any{map[string]string{"path": ".", "name": "fixture"}}, + "targets": []any{map[string]any{"project": ".", "path": ".", "name": "app", "tags": []string{"app"}}}, + } + case "lithe/build/prepareRun": + port := request.Params.LaunchOptions.Debug.Target.Port + if port <= 0 { + return fmt.Errorf("the provider received no owned debug endpoint") + } + // The run contract takes a PATH command. The fixture lives in the + // remote working directory and exec keeps it in the owned session. + result = map[string]any{ + "executable": map[string]string{"kind": "command", "value": "sh"}, + "arguments": []string{"-c", "exec ./debuggee"}, "workingDirectory": ".", + "environment": map[string]string{"LITHE_FIXTURE_SERVICE_PORT": strconv.Itoa(port)}, + } + case "shutdown": + default: + return fmt.Errorf("unexpected provider method %q", request.Method) + } + reply, err := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": request.ID, "result": result}) + if err != nil { + return err + } + if _, err := fmt.Fprintf(os.Stdout, "Content-Length: %d\r\n\r\n%s", len(reply), reply); err != nil { + return err + } + } +} diff --git a/desktop/internal/workbench/testdata/remote_settings_helper/main.go b/desktop/internal/workbench/testdata/remote_settings_helper/main.go new file mode 100644 index 0000000000..1449db2ee2 --- /dev/null +++ b/desktop/internal/workbench/testdata/remote_settings_helper/main.go @@ -0,0 +1,148 @@ +//go:build linux + +// The fixture implements a tiny native configuration format on the SSH host. +package main + +import ( + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "syscall" +) + +type request struct { + Operation string `json:"operation"` + SourceID string `json:"sourceID"` + Revision string `json:"revision"` + Values map[string]string `json:"values"` + HostPath string `json:"hostPath"` + OutputFile string `json:"outputFile"` +} + +type source struct { + ID string + Scope string + Path string + HostPath string + Writable bool +} + +func main() { + err := run() + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +func run() error { + if len(os.Args) != 3 { + return errors.New("expected a home fixture name and a request file") + } + root, err := os.Getwd() + if err != nil { + return err + } + home, err := os.UserHomeDir() + if err != nil { + return err + } + homeFile, input := os.Args[1], os.Args[2] + sources := []source{ + {"project", "workspace", "project.fixture", filepath.Join(root, "project.fixture"), true}, + {"user", "home", homeFile, filepath.Join(home, homeFile), true}, + {"defaults", "hostReadOnly", filepath.Join(root, "defaults.fixture"), filepath.Join(root, "defaults.fixture"), false}, + } + data, err := os.ReadFile(input) + if err != nil { + return err + } + var req request + if err := json.Unmarshal(data, &req); err != nil { + return err + } + if req.Operation == "editSource" { + for _, entry := range sources { + if entry.ID == req.SourceID && entry.Writable && entry.HostPath == req.HostPath { + return edit(req, root, input) + } + } + return errors.New("unrecognized edit target") + } + if req.Operation != "read" && req.Operation != "readAfterSave" { + return errors.New("unrecognized operation") + } + return read(sources, req.Operation, input) +} + +func read(sources []source, operation, input string) error { + projection := make([]map[string]any, 0, len(sources)) + for _, entry := range sources { + value, revision, err := readSource(entry.HostPath) + if err != nil { + return err + } + projection = append(projection, map[string]any{ + "id": entry.ID, "group": "general", "title": entry.ID, + "path": entry.Path, "scope": entry.Scope, "revision": revision, "writable": entry.Writable, + "fields": []map[string]any{{ + "id": "name", "title": "Name", "kind": "text", + "value": value, "effectiveValue": value, "effectiveSource": entry.ID, + }}, + }) + } + if err := os.WriteFile("last-read", []byte(operation+"\n"+input), 0o600); err != nil { + return err + } + return json.NewEncoder(os.Stdout).Encode(map[string]any{ + "format": "litheSettingsSources", "version": 0, "title": "Remote fixture settings", + "groups": []map[string]any{{"id": "general", "title": "General", "layout": "form"}}, + "sources": projection, + }) +} + +func edit(req request, root, input string) error { + _, revision, err := readSource(req.HostPath) + if err != nil { + return err + } + if revision != req.Revision { + return errors.New("source changed") + } + value := req.Values["name"] + if err := os.WriteFile(filepath.Join(root, "last-edit"), []byte(input+"\n"+req.OutputFile), 0o600); err != nil { + return err + } + file, err := os.OpenFile(req.OutputFile, os.O_WRONLY|syscall.O_NOFOLLOW, 0) + if err != nil { + return err + } + _, writeErr := file.WriteString(value) + if err := errors.Join(writeErr, file.Close()); err != nil { + return err + } + receiptRevision := digest([]byte(value)) + if value == "bad-receipt" { + receiptRevision = "missing" + } + return json.NewEncoder(os.Stdout).Encode(map[string]any{ + "format": "litheSettingsSourceEdit", "version": 0, "sourceID": req.SourceID, + "revision": receiptRevision, "changed": true, + }) +} + +func readSource(name string) (any, string, error) { + data, err := os.ReadFile(name) + if errors.Is(err, os.ErrNotExist) { + return nil, "missing", nil + } + if err != nil { + return nil, "", err + } + return string(data), digest(data), nil +} + +func digest(data []byte) string { return fmt.Sprintf("sha256:%x", sha256.Sum256(data)) } diff --git a/desktop/internal/workbench/testdata/remote_variant_server/main.go b/desktop/internal/workbench/testdata/remote_variant_server/main.go new file mode 100644 index 0000000000..e6046cc581 --- /dev/null +++ b/desktop/internal/workbench/testdata/remote_variant_server/main.go @@ -0,0 +1,90 @@ +// This synthetic language server reports which platform's binary was launched. +package main + +import ( + "bufio" + "encoding/json" + "fmt" + "io" + "log" + "os" + "runtime" + "strconv" + "strings" +) + +func main() { + if err := serve(bufio.NewReader(os.Stdin), os.Stdout); err != nil && err != io.EOF { + log.Fatal(err) + } +} + +func serve(input *bufio.Reader, output io.Writer) error { + for { + body, err := readMessage(input) + if err != nil { + return err + } + var request struct { + ID json.RawMessage `json:"id"` + Method string `json:"method"` + Params struct { + TextDocument struct { + URI string `json:"uri"` + } `json:"textDocument"` + } `json:"params"` + } + if err := json.Unmarshal(body, &request); err != nil { + return err + } + if request.Method == "exit" { + return nil + } + var response []byte + switch { + case request.Method == "initialize": + response = fmt.Appendf(nil, `{"jsonrpc":"2.0","id":%s,"result":{"capabilities":{"textDocumentSync":1}}}`, request.ID) + case request.Method == "textDocument/didOpen": + message := "Packaged language server running on " + runtime.GOOS + "/" + runtime.GOARCH + if os.Getenv("LITHE_TEST_MANAGED_RUNNER") == "1" { + message += " via managed runtime" + } + response = fmt.Appendf(nil, `{"jsonrpc":"2.0","method":"textDocument/publishDiagnostics","params":{"uri":%q,"diagnostics":[{"range":{"start":{"line":0,"character":0},"end":{"line":0,"character":1}},"severity":1,"message":%q}]}}`, + request.Params.TextDocument.URI, message) + case len(request.ID) != 0: + response = fmt.Appendf(nil, `{"jsonrpc":"2.0","id":%s,"result":null}`, request.ID) + } + if len(response) > 0 { + if _, err := fmt.Fprintf(output, "Content-Length: %d\r\n\r\n%s", len(response), response); err != nil { + return err + } + } + } +} + +func readMessage(input *bufio.Reader) ([]byte, error) { + var length int + for { + line, err := input.ReadString('\n') + if err != nil { + return nil, err + } + line = strings.TrimSpace(line) + if line == "" { + break + } + key, value, found := strings.Cut(line, ":") + if found && strings.EqualFold(key, "Content-Length") { + length, err = strconv.Atoi(strings.TrimSpace(value)) + if err != nil { + return nil, err + } + } + } + if length < 1 || length > 1<<20 { + return nil, fmt.Errorf("invalid Content-Length %d", length) + } + body := make([]byte, length) + _, err := io.ReadFull(input, body) + return body, err +} diff --git a/desktop/internal/workbench/tests.go b/desktop/internal/workbench/tests.go index dfd87a2ee3..b4833cd3f9 100644 --- a/desktop/internal/workbench/tests.go +++ b/desktop/internal/workbench/tests.go @@ -4,8 +4,6 @@ import ( "context" "encoding/json" "errors" - "github.com/1lck/Lithe-IDEA/desktop/internal/processledger" - "os/exec" "path/filepath" "strconv" "strings" @@ -114,20 +112,20 @@ func buildModelProjectPaths(model core.BuildModel) []string { return paths } -func (s *testState) reset() { *s = testState{} } +func (s *testState) reset() { *s = testState{generation: s.generation + 1} } // testOperation is the one provider request or host process a test run owns. // stopped is set on the window thread and read by the run goroutine. type testOperation struct { provider *buildprovider.Client request *buildprovider.Operation - process *buildprocess.Process + process buildProcess stopped atomic.Bool } // stop terminates the run's host process. A provider request is cancelled separately. func (o *testOperation) stop() { - if o != nil { + if o != nil && o.process != nil { o.process.Stop() } } @@ -196,7 +194,8 @@ func (a *App) startTests(p *project, selection testSelection) { if p == nil || p.tests.running { return } - if a.refuseRemote(p, "test_start") { + connection, ok := captureWorkspaceConnection(p) + if !ok { return } if p.safeMode() { @@ -225,7 +224,7 @@ func (a *App) startTests(p *project, selection testSelection) { startedMillis := time.Now().UnixMilli() a.performed("tests.run."+selection.scope(), surfaceButton) a.background(p, testRequestTimeout, func(ctx context.Context) func(*App) { - return a.executeTestRun(ctx, p, captured, selection, generation, startedMillis) + return a.executeTestRun(attachedWorkspaceContext(ctx, connection), p, captured, selection, generation, startedMillis) }) } @@ -264,13 +263,7 @@ func (a *App) executeTestCommand(ctx context.Context, p *project, instance build decoder := newOutputDecoder(a.kernel, a.outputEncodingPolicy()) operation := &testOperation{} workingDirectory := filepath.Join(p.root, filepath.FromSlash(plan.WorkingDirectory)) - process, err := buildprocess.Start(ctx, buildprocess.Spec{ - Kind: processledger.KindBuild, - Executable: executable.Executable, - Arguments: plan.Arguments, - WorkingDirectory: workingDirectory, - Environment: applyToolchainSelection(plan.Environment, executable.selection()), - }, func(_ buildprocess.Stream, text string) { + process, err := a.startBuildExecution(ctx, p, executable, plan.Arguments, workingDirectory, plan.Environment, func(_ buildprocess.Stream, text string) { output.append(text) a.streamTestOutput(p, generation, decoder, text) }) @@ -280,6 +273,7 @@ func (a *App) executeTestCommand(ctx context.Context, p *project, instance build operation.process = process a.post(func(a *App) { if a.project != p || p.tests.generation != generation { + process.Stop() return } p.tests.operation = operation @@ -290,11 +284,12 @@ func (a *App) executeTestCommand(ctx context.Context, p *project, instance build if interrupted { return func(a *App) { a.finishTestInterrupted(p, generation, selection, termination) } } - result, decodeErr := a.decodeTestResults(ctx, p, instance, testResultsRequest(p, instance, selection, output.text(), nil, startedMillis)) - if decodeErr != nil { - return func(a *App) { a.finishTestError(p, generation, decodeErr) } + var exit interface{ ExitCode() int } + if waitErr != nil && !errors.As(waitErr, &exit) { + return func(a *App) { a.finishTestError(p, generation, waitErr) } } - return func(a *App) { a.finishTestRun(p, generation, selection, result, termination) } + request := testResultsRequest(p, instance, selection, output.text(), nil, startedMillis) + return a.completeTestRun(ctx, p, instance, selection, plan, generation, request, termination) } // executeTestProvider runs the provider's lithe/build/test request. The reply's @@ -319,7 +314,6 @@ func (a *App) executeTestProvider(ctx context.Context, p *project, instance buil }) output := &testOutput{} decoder := newOutputDecoder(a.kernel, a.outputEncodingPolicy()) - var providerResult json.RawMessage for { select { case progress, ok := <-operation.Progress(): @@ -366,13 +360,8 @@ completed: output.append(execution.Output) a.streamTestOutput(p, generation, decoder, execution.Output) } - providerResult = execution.TestResults - request := testResultsRequest(p, instance, selection, output.text(), providerResult, startedMillis) - result, decodeErr := a.decodeTestResults(ctx, p, instance, request) - if decodeErr != nil { - return func(a *App) { a.finishTestError(p, generation, decodeErr) } - } - return func(a *App) { a.finishTestRun(p, generation, selection, result, termination) } + request := testResultsRequest(p, instance, selection, output.text(), execution.TestResults, startedMillis) + return a.completeTestRun(ctx, p, instance, selection, plan, generation, request, termination) } // testResultsRequest builds the decode request. notBeforeMillis is the host's @@ -395,8 +384,17 @@ func testResultsRequest(p *project, instance buildInstance, selection testSelect return request } -func (a *App) decodeTestResults(ctx context.Context, p *project, instance buildInstance, request core.BuildTestResultsRequest) (core.BuildTestResults, error) { - return a.kernel.DecodeBuildTestResults(ctx, instance.Manifest, instance.BuildSystemID, request) +// completeTestRun decodes a report only when Core's plan says the plugin produces one. +func (a *App) completeTestRun(ctx context.Context, p *project, instance buildInstance, selection testSelection, plan core.BuildPlan, generation uint64, request core.BuildTestResultsRequest, termination core.BuildTestTermination) func(*App) { + var results *core.BuildTestResults + if plan.Results != nil { + report, err := a.kernel.DecodeBuildTestResults(ctx, instance.Manifest, instance.BuildSystemID, request) + if err != nil { + return func(a *App) { a.finishTestError(p, generation, err) } + } + results = &report + } + return func(a *App) { a.finishTestRun(p, generation, selection, results, termination) } } // testTermination classifies how the test process or provider ended. A run the @@ -412,7 +410,7 @@ func testTermination(ctx context.Context, operation *testOperation, waitErr erro return testContextTermination(ctx), true } termination := core.BuildTestTermination{Kind: "exited"} - var exitErr *exec.ExitError + var exitErr interface{ ExitCode() int } if errors.As(waitErr, &exitErr) { code := exitErr.ExitCode() termination.ExitCode = &code @@ -434,11 +432,15 @@ func testContextTermination(ctx context.Context) core.BuildTestTermination { } // finishTestRun reduces the run through Core and publishes the result tree. -func (a *App) finishTestRun(p *project, generation uint64, selection testSelection, results core.BuildTestResults, termination core.BuildTestTermination) { +func (a *App) finishTestRun(p *project, generation uint64, selection testSelection, results *core.BuildTestResults, termination core.BuildTestTermination) { if a.project != p || p.tests.generation != generation { return } - verdict, err := a.kernel.ResolveBuildTestOutcome(a.operationContext(context.Background()), termination, selection.scopeProject(), selection.suite, selection.caseName, &results.Summary) + var summary *core.BuildTestSummary + if results != nil { + summary = &results.Summary + } + verdict, err := a.kernel.ResolveBuildTestOutcome(a.operationContext(context.Background()), termination, selection.scopeProject(), selection.suite, selection.caseName, summary) if err != nil { a.finishTestError(p, generation, err) return @@ -447,11 +449,13 @@ func (a *App) finishTestRun(p *project, generation uint64, selection testSelecti p.tests.operation = nil p.tests.running = false p.tests.stopping = false - p.tests.results = results p.tests.verdict = verdict - p.tests.hasResults = true - p.tests.status = a.testVerdictStatus(verdict, results.Summary) - p.tests.rows = flattenTestRows(results) + if results != nil { + p.tests.results = *results + p.tests.hasResults = true + p.tests.rows = flattenTestRows(*results) + } + p.tests.status = a.testVerdictStatus(verdict, p.tests.results.Summary) } // finishTestInterrupted publishes a cancelled or timed-out run without diff --git a/desktop/internal/workbench/tests_test.go b/desktop/internal/workbench/tests_test.go index f0709acbff..7e449ff38c 100644 --- a/desktop/internal/workbench/tests_test.go +++ b/desktop/internal/workbench/tests_test.go @@ -71,6 +71,11 @@ func TestFixtureTestRunner(t *testing.T) { // testsHarness installs the fixture plugin into an isolated plugin root and // marks it enabled without the user installation or trust flow. func testsHarness(t *testing.T) *harness { + t.Helper() + return testsHarnessWithManifest(t, testsPanelManifest) +} + +func testsHarnessWithManifest(t *testing.T, manifest string) *harness { t.Helper() dir := t.TempDir() if err := os.WriteFile(filepath.Join(dir, settingsFile), []byte(`{"theme":"dark"}`), 0o600); err != nil { @@ -82,7 +87,7 @@ func testsHarness(t *testing.T) *harness { if err := os.MkdirAll(installed, 0o700); err != nil { t.Fatal(err) } - if err := os.WriteFile(filepath.Join(installed, "plugin.json"), []byte(testsPanelManifest), 0o600); err != nil { + if err := os.WriteFile(filepath.Join(installed, "plugin.json"), []byte(manifest), 0o600); err != nil { t.Fatal(err) } if err := pluginstate.New(preferences).SetEnabled("dev.lithe.test.tests-panel", true); err != nil { @@ -207,6 +212,30 @@ func TestTestsPanelRunsFixtureAndOpensFailureLocation(t *testing.T) { } } +func TestTestsPanelUsesExitCodeWhenNoReportIsDeclared(t *testing.T) { + manifest := strings.Replace(testsPanelManifest, + ",\n \"results\": {\"decoder\": \"junitXml\", \"reports\": [\"reports/*.xml\"]}", "", 1) + h := testsHarnessWithManifest(t, manifest) + root := t.TempDir() + if err := os.WriteFile(filepath.Join(root, "fixture.test"), []byte("fixture\n"), 0o600); err != nil { + t.Fatal(err) + } + installTestRunner(t, root) + p := openTestsPanel(t, h, root) + + clickRun(t, h) + awaitStateWithin(t, h, 30*time.Second, "the test command to finish", func() bool { + return p.tests.last != nil && !p.tests.running + }) + if p.tests.failed != "" || !p.tests.verdict.Success || p.tests.hasResults { + t.Fatalf("expected a successful test command without a report: verdict=%+v failure=%q hasResults=%v", + p.tests.verdict, p.tests.failed, p.tests.hasResults) + } + if !strings.Contains(p.tests.output.all(), "PASS") { + t.Fatalf("test console lost the command output: %q", p.tests.output.all()) + } +} + func TestTestsPanelStopCancelsAndPublishesNoOutcome(t *testing.T) { h := testsHarness(t) root := t.TempDir() @@ -284,7 +313,7 @@ func TestTestsPanelDropsStaleResultAndBoundsOutput(t *testing.T) { // A result from generation 1 belongs to a replaced run and must not replace // the current state. - h.app.finishTestRun(p, 1, testSelection{}, core.BuildTestResults{Summary: core.BuildTestSummary{Total: 1, Passed: 1}}, core.BuildTestTermination{Kind: "exited"}) + h.app.finishTestRun(p, 1, testSelection{}, &core.BuildTestResults{Summary: core.BuildTestSummary{Total: 1, Passed: 1}}, core.BuildTestTermination{Kind: "exited"}) if p.tests.hasResults || !p.tests.running { t.Fatalf("a stale result changed the run state: %+v", p.tests) } diff --git a/desktop/internal/workbench/tests_view.go b/desktop/internal/workbench/tests_view.go index 441484c06f..c87bc3c0f7 100644 --- a/desktop/internal/workbench/tests_view.go +++ b/desktop/internal/workbench/tests_view.go @@ -28,7 +28,7 @@ func (a *App) testsView(c ui.C, p *project) { ui.Column(c).Fill().Background(a.colors.Editor).Children(func() { ui.Row(c).FillWidth().Height(panelHeaderHeight).Shrink(0).Items(ui.Center).Gap(6).PadX(8).Children(func() { label := t.Run - if s.hasResults || s.failed != "" { + if s.hasResults || s.verdict.ExitCode != nil || s.failed != "" { label = t.Rerun } if ui.Button(c, label).Disabled(s.running || !available).Clicked() { @@ -66,6 +66,9 @@ func (a *App) testsView(c ui.C, p *project) { } else if s.running { a.panelMessage(c, t.Running, a.colors.Subtle) return + } else if s.verdict.ExitCode != nil { + a.testOutput(c, p) + return } else { a.panelMessage(c, t.Empty, a.colors.Subtle) return @@ -187,7 +190,7 @@ func (a *App) testStatusMark(status string) (gfx.Icon, gfx.Color) { } } -// testOutput shows the tail of a run that failed before reporting results, +// testOutput shows the tail of a run without structured results, // bounded to the same console budget the run kept. func (a *App) testOutput(c ui.C, p *project) { output := &p.tests.output diff --git a/desktop/internal/workbench/title_run.go b/desktop/internal/workbench/title_run.go index 19a405db94..da2cf6a2f1 100644 --- a/desktop/internal/workbench/title_run.go +++ b/desktop/internal/workbench/title_run.go @@ -150,9 +150,7 @@ func (a *App) titleDebug(p *project) { // while the configurations are read, and an answer that settles them while they are asked for // performs it; otherwise Core decides what the press does now. func (a *App) titleStart(p *project, action titleAction) { - // A remote workspace's project runs on its host, where Run starts a built-in configuration - // (remote_run.go); Debug and the current file's run do not reach it yet. - if (action == titleActionDebug || p.runConfigs.currentFile) && a.refuseRemote(p, "title_run") { + if _, connected := captureWorkspaceConnection(p); !connected { return } if !p.runConfigs.currentFile { @@ -187,14 +185,6 @@ func (a *App) decideTitleAction(p *project, action titleAction, trigger string) facts.Action = "debug" } configuration := p.titleConfiguration() - if p.remote != nil && configuration != nil && !configuration.IsProcess() && !configuration.Unavailable() { - // A remote workspace detects no build system and runs no plugin, so only a built-in - // configuration starts there; the others say why instead of a missing target. - p.runConfigs.pending = titleActionNone - a.operationRejected("title_run", "remote_workspace") - a.notifyError(i18n.Shared(a.language(), "desktop.run.remote.unsupported")) - return - } var reference core.RunProviderReference index := -1 if configuration != nil { diff --git a/desktop/internal/workbench/title_run_entrypoints.go b/desktop/internal/workbench/title_run_entrypoints.go index 6292c4e508..1d0a8e3664 100644 --- a/desktop/internal/workbench/title_run_entrypoints.go +++ b/desktop/internal/workbench/title_run_entrypoints.go @@ -39,7 +39,8 @@ type entrypointFound struct { // loaded first, since the configuration names the model's project; a press waits for it as a // press on a configuration does. func (a *App) performCurrentFileAction(p *project, action titleAction) { - if a.refuseRemote(p, "run_current_file") { + connection, connected := captureWorkspaceConnection(p) + if !connected { return } if p.safeMode() { @@ -52,12 +53,12 @@ func (a *App) performCurrentFileAction(p *project, action titleAction) { } doc := p.selectedDocument(p.docs.group) if doc == nil || doc.path == "" { - a.runCurrentFileEditorAction(p, doc, action, nil) + a.runCurrentFileEditorAction(p, doc, action, nil, connection) return } relative, err := filepath.Rel(p.root, doc.path) if err != nil || relative == "." || strings.HasPrefix(relative, "..") { - a.runCurrentFileEditorAction(p, doc, action, nil) + a.runCurrentFileEditorAction(p, doc, action, nil, connection) return } file := filepath.ToSlash(relative) @@ -79,14 +80,15 @@ func (a *App) performCurrentFileAction(p *project, action titleAction) { } candidates = slices.DeleteFunc(candidates, func(c entrypointCandidate) bool { return !c.instance.modelLoaded }) if len(candidates) == 0 { - a.runCurrentFileEditorAction(p, doc, action, nil) + a.runCurrentFileEditorAction(p, doc, action, nil, connection) return } if doc.dirty() || doc.saving || doc.conflicted { s.findingEntrypoint = true a.saveBeforeClose(p, doc, func(ok bool) { s.findingEntrypoint = false - if ok && a.project == p && p.selectedDocument(p.docs.group) == doc { + if ok && a.project == p && p.selectedDocument(p.docs.group) == doc && + (connection == nil || connection.IsCurrent()) { a.performCurrentFileAction(p, action) } }) @@ -99,12 +101,13 @@ func (a *App) performCurrentFileAction(p *project, action titleAction) { kernel := a.kernel documentPath, revision := doc.path, doc.view.Revision() a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { + ctx = attachedWorkspaceContext(ctx, connection) found, err := a.findEntrypoint(ctx, p, kernel, candidates, file, action) cancelled := errors.Is(ctx.Err(), context.Canceled) return func(a *App) { s.findingEntrypoint = false // log-exempt: 用户取消:项目关闭或请求取消后没有入口需要启动。 - if cancelled { + if cancelled || (connection != nil && !connection.IsCurrent()) { return } if p.selectedDocument(p.docs.group) != doc || doc.path != documentPath || doc.view.Revision() != revision { @@ -116,8 +119,13 @@ func (a *App) performCurrentFileAction(p *project, action titleAction) { if found != nil { s.findingEntrypoint = true a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { - id, err := a.saveEntrypointConfiguration(ctx, p, kernel, *found) - return func(a *App) { a.startEntrypointConfiguration(p, id, action, err) } + id, err := a.saveEntrypointConfiguration(attachedWorkspaceContext(ctx, connection), p, kernel, *found) + return func(a *App) { + s.findingEntrypoint = false + if connection == nil || connection.IsCurrent() { + a.startEntrypointConfiguration(p, id, action, err) + } + } }) return } @@ -129,7 +137,7 @@ func (a *App) performCurrentFileAction(p *project, action titleAction) { if err != nil { a.backgroundFailed("title_run_current_file", err) } - a.runCurrentFileEditorAction(p, doc, action, err) + a.runCurrentFileEditorAction(p, doc, action, err, connection) } }) } @@ -227,7 +235,7 @@ func (a *App) saveEntrypointConfiguration(ctx context.Context, p *project, kerne if err != nil { return "", err } - if err := applyRunConfigChanges(ctx, p.root, changes); err != nil { + if err := a.applyRunConfigChanges(ctx, p.root, changes); err != nil { return "", err } return id, nil diff --git a/desktop/internal/workbench/title_run_test.go b/desktop/internal/workbench/title_run_test.go index 04bd13947f..05cc94b2e3 100644 --- a/desktop/internal/workbench/title_run_test.go +++ b/desktop/internal/workbench/title_run_test.go @@ -150,7 +150,7 @@ func TestProviderDebugStartsTheNamedAdapter(t *testing.T) { decoy := named decoy.Declaration.ID, decoy.Declaration.AdapterID = "decoy", "decoy-dap" p.debug.adapters = []debugAdapter{decoy, named} - h.app.startProviderDebug(p, named.PluginID, core.BuildDebugPreparation{Adapter: named.Declaration.ID, Program: "bin/app", WorkingDirectory: "."}, nil) + h.app.startProviderDebug(p, named.PluginID, core.BuildDebugPreparation{Adapter: named.Declaration.ID, Program: "bin/app", WorkingDirectory: "."}, nil, nil) session := p.debug.activeSession() if session == nil { t.Fatal("the provider did not start a debug session") @@ -168,7 +168,7 @@ func TestProviderDebugStartsTheNamedAdapter(t *testing.T) { func TestProviderDebugRefusesAnAdapterThePluginDoesNotInstall(t *testing.T) { h := debugHarness(t) p := openDebugPanel(t, h, t.TempDir()) - h.app.startProviderDebug(p, p.debug.adapters[0].PluginID, core.BuildDebugPreparation{Adapter: "missing", Program: "bin/app"}, nil) + h.app.startProviderDebug(p, p.debug.adapters[0].PluginID, core.BuildDebugPreparation{Adapter: "missing", Program: "bin/app"}, nil, nil) if p.debug.activeSession() != nil { t.Fatal("an adapter the preparation does not name started") } diff --git a/desktop/internal/workbench/toolchains.go b/desktop/internal/workbench/toolchains.go index 35163ae237..84e1424b67 100644 --- a/desktop/internal/workbench/toolchains.go +++ b/desktop/internal/workbench/toolchains.go @@ -20,6 +20,7 @@ type buildExecution struct { Executable string Environment map[string]string PathPrepend []string + Placement core.ProcessPlacement // Source is the candidate the executable was found by, which the options dialog shows // beside a build's runtime. Source buildExecutionSource @@ -74,13 +75,26 @@ func (a *App) managedToolchainOptions(ctx context.Context, manifests []json.RawM } func (a *App) defaultToolchainSelection(ctx context.Context, root, directory, tool, minimumVersion string) (core.ToolchainSelection, error) { - manifests, err := a.toolchainManifests(ctx) + manifests, err := a.toolchainManifests(core.WithoutRemoteWorkspace(ctx)) if err != nil { return core.ToolchainSelection{}, err } if directory == "" { directory = "." } + if core.RemoteWorkspaceOf(ctx) != nil { + registry, err := toolchain.RegistryInput(manifests) + if err != nil { + return core.ToolchainSelection{}, err + } + resolution, err := a.kernel.ResolveRemoteToolchain(ctx, core.RemoteToolchainResolveRequest{ + Registry: registry, Tool: tool, Directory: directory, MinimumVersion: minimumVersion, + }) + if err != nil { + return core.ToolchainSelection{}, err + } + return toolchain.SelectionFromResolution(tool, resolution) + } return toolchain.Resolve(ctx, a.kernel, root, directory, tool, minimumVersion, nil, manifests, a.toolchainOptions(ctx, root, manifests)) } diff --git a/desktop/internal/workbench/vcs.go b/desktop/internal/workbench/vcs.go index 39b71a90af..6067e77e7e 100644 --- a/desktop/internal/workbench/vcs.go +++ b/desktop/internal/workbench/vcs.go @@ -19,6 +19,7 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/pluginbackend" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteplaceholder" "github.com/vivaui/viva/ui" ) @@ -356,10 +357,14 @@ func (s *vcsState) rejection(plugin string) string { // vcsRuntime holds the provider sessions of one project, one per provider. type vcsRuntime struct { - launches *pluginLaunches - mu sync.Mutex - clients map[string]*buildprovider.Client - closed bool + // The window creates a new runtime after each remote attachment. Workers + // that already hold this runtime can only address the previous host. + connection *core.RemoteWorkspaceConnection + platform core.RemotePlatform + launches *pluginLaunches + mu sync.Mutex + clients map[string]*buildprovider.Client + closed bool } // errVcsNotNegotiated is a session that started without negotiating the provider it was started @@ -390,7 +395,7 @@ func (r *vcsRuntime) live(key string) *buildprovider.Client { // outside the lock, so detaching on the window thread never waits for a start; a start that lost // to another one or to detaching is stopped again. logDirectory gives the process's ${logDir}, and // is asked only when a process starts. -func (r *vcsRuntime) session(ctx context.Context, runner *pluginbackend.Runner, pluginRoot, root, rootURI string, window vcsWindow, settings core.PluginSettingsState, projectCodeAllowed bool, logDirectory func(context.Context, string) string) (client *buildprovider.Client, err error) { +func (r *vcsRuntime) session(ctx context.Context, plugins *pluginservice.Service, root, rootURI string, window vcsWindow, settings core.PluginSettingsState, projectCodeAllowed bool, logDirectory func(context.Context, string) string) (client *buildprovider.Client, err error) { ctx, finish, err := r.launches.begin(ctx, window.PluginID) if err != nil { return nil, err @@ -406,32 +411,47 @@ func (r *vcsRuntime) session(ctx context.Context, runner *pluginbackend.Runner, if client != nil && !client.Closed() { return client, nil } - state := filepath.Join(pluginpkg.VersionStateRoot(pluginRoot, window.PluginID, window.Version), "vcs", workspaceDigest(root)) - workspaceState := filepath.Join(state, "workspace") - temporaryDirectory := filepath.Join(state, "tmp") - for _, directory := range []string{state, workspaceState, temporaryDirectory} { - if err := os.MkdirAll(directory, 0o700); err != nil { + prepareLocal := func(ctx context.Context, request *pluginbackend.StartRequest) error { + request.StateDirectory = filepath.Join(pluginpkg.VersionStateRoot(plugins.Root, window.PluginID, window.Version), "vcs", workspaceDigest(root)) + request.WorkspaceStateDirectory = filepath.Join(request.StateDirectory, "workspace") + request.TemporaryDirectory = filepath.Join(request.StateDirectory, "tmp") + for _, directory := range []string{request.WorkspaceStateDirectory, request.TemporaryDirectory} { + if err := os.MkdirAll(directory, 0o700); err != nil { + return err + } + } + request.LogDirectory = logDirectory(ctx, window.PluginID) + return nil + } + request := pluginbackend.StartRequest{ + Manifest: window.Manifest, + PackageDirectory: window.Directory, + PluginID: window.PluginID, + ProviderID: window.PluginID + "/" + window.Vcs, + VcsProviderID: window.Vcs, + Role: "vcs", + Architecture: core.PluginArchitecture(), + RemoteConnection: r.connection, + Settings: settings.Settings, + ProjectSettings: settings.ProjectSettings, + RootURI: rootURI, + WorkingDirectory: root, + ProjectCodeAllowed: projectCodeAllowed, + } + if r.connection == nil { + if err := prepareLocal(ctx, &request); err != nil { return nil, err } + } else { + request.Architecture = r.platform.Arch + request.PrepareUI = prepareLocal + installed := pluginpkg.Installed{ID: window.PluginID, Version: window.Version, Path: window.Directory} + request.PrepareRemote = plugins.RemoteDeployment(installed, window.Manifest, r.platform, nil) + request.PrepareRemoteTools = func(ctx context.Context) (map[string]pluginbackend.ToolExecutable, error) { + return plugins.RemoteTools(ctx, installed, window.Manifest, r.connection, r.platform) + } } - started, err := buildprovider.Start(ctx, runner, pluginbackend.StartRequest{ - Manifest: window.Manifest, - PackageDirectory: window.Directory, - PluginID: window.PluginID, - ProviderID: window.PluginID + "/" + window.Vcs, - VcsProviderID: window.Vcs, - Role: "vcs", - StateDirectory: state, - WorkspaceStateDirectory: workspaceState, - LogDirectory: logDirectory(ctx, window.PluginID), - TemporaryDirectory: temporaryDirectory, - Architecture: core.PluginArchitecture(), - Settings: settings.Settings, - ProjectSettings: settings.ProjectSettings, - RootURI: rootURI, - WorkingDirectory: root, - ProjectCodeAllowed: projectCodeAllowed, - }) + started, err := buildprovider.Start(ctx, plugins.Backend, request) if err != nil { return nil, err } @@ -441,7 +461,8 @@ func (r *vcsRuntime) session(ctx context.Context, runner *pluginbackend.Runner, return nil, errors.Join(errVcsNotNegotiated, started.Close(stopCtx)) } r.mu.Lock() - closed, client = r.closed || ctx.Err() != nil, r.clients[key] + closed, client = r.closed || ctx.Err() != nil || + (r.connection != nil && !r.connection.IsCurrent()), r.clients[key] if !closed && (client == nil || client.Closed()) { if r.clients == nil { r.clients = map[string]*buildprovider.Client{} @@ -488,6 +509,16 @@ func (s *vcsState) runtime() *vcsRuntime { return s.sessions } +// vcsRuntime captures an attachment before an operation is queued. +func (p *project) vcsRuntime() *vcsRuntime { + if p.remote != nil && p.vcs.sessions == nil { + runtime := p.vcs.runtime() + runtime.connection = p.remote.binding.CaptureConnection() + runtime.platform = p.remote.platform + } + return p.vcs.runtime() +} + // stopVcs stops every provider session of a project that closes, on a background task with a // bounded wait. func (a *App) stopVcs(p *project) { @@ -536,6 +567,12 @@ func (a *App) detectVcsRoots(p *project) { return } s := &p.vcs + connection, connected := captureWorkspaceConnection(p) + if !connected { + s.detecting, s.detected = false, true + s.failure = a.vcsFailureText(errRemoteDisconnected) + return + } var manifests []json.RawMessage var plugins []string for _, window := range a.vcsWindowsShown() { @@ -553,9 +590,9 @@ func (a *App) detectVcsRoots(p *project) { generation, root := s.generation, p.root s.detecting, s.failure = true, "" a.background(p, vcsReadTimeout, func(ctx context.Context) func(*App) { - detection, err := kernel.VcsDetectRoots(ctx, root, manifests, mappings) + detection, err := kernel.VcsDetectRoots(attachedWorkspaceContext(ctx, connection), root, manifests, mappings) return func(a *App) { - if s.generation != generation { + if s.generation != generation || (connection != nil && !connection.IsCurrent()) { return } s.detecting, s.detected = false, true @@ -666,9 +703,19 @@ func (a *App) runVcs(ctx context.Context, p *project, sessions *vcsRuntime, call if !p.trust.allowed() { return nil, nil, errVcsSafeMode } + attachment := sessions.connection + if p.remote != nil { + if !attachment.IsCurrent() { + return nil, nil, errRemoteDisconnected + } + work, cancel := context.WithCancel(ctx) + defer cancel() + defer attachment.AfterDetach(cancel)() + ctx = attachment.Context(work) + } client := sessions.live(call.window.PluginID + "\x00" + call.window.Vcs) if client == nil { - settings, err := a.loadPluginPreferenceSources(ctx, call.window.Manifest, p.root) + settings, err := a.plugins.ReadWorkspacePluginSettings(core.WithoutRemoteWorkspace(ctx), call.window.Manifest, p.root, attachment) if err != nil { return nil, nil, err } @@ -676,14 +723,14 @@ func (a *App) runVcs(ctx context.Context, p *project, sessions *vcsRuntime, call if err != nil { return nil, nil, err } - if client, err = sessions.session(ctx, a.plugins.Backend, a.plugins.Root, p.root, rootURI, call.window, settings.State, p.trust.allowed(), a.pluginLogDirectory); err != nil { + if client, err = sessions.session(ctx, a.plugins, p.root, rootURI, call.window, settings, p.trust.allowed(), a.pluginLogDirectory); err != nil { return nil, nil, err } } _, capabilities, _ := client.VcsProvider() var tool *string if len(call.tool) > 0 { - executable, err := a.plugins.Backend.ResolveCommand(call.window.PluginID, call.tool) + executable, err := a.resolveVcsClient(ctx, call) if err != nil { return nil, capabilities, errors.Join(errVcsToolMissing, err) } @@ -709,10 +756,27 @@ func (a *App) runVcs(ctx context.Context, p *project, sessions *vcsRuntime, call } return nil, capabilities, err } - decoded, err := kernel.VcsDecodeReply(ctx, call.operation, capabilities, arguments, value) + decoded, err := kernel.VcsDecodeReply(core.WithoutRemoteWorkspace(ctx), call.operation, capabilities, arguments, value) return decoded, capabilities, err } +// resolveVcsClient searches the same host that runs the provider. +func (a *App) resolveVcsClient(ctx context.Context, call vcsCall) (string, error) { + if core.RemoteWorkspaceOf(ctx) == nil { + return a.plugins.Backend.ResolveCommand(call.window.PluginID, call.tool) + } + for _, candidate := range call.tool { + executable, err := a.kernel.ResolveRemoteExecutable(ctx, core.RemoteExecutableRequest{Kind: "command", Value: candidate}) + if err != nil { + return "", err + } + if executable != "" { + return executable, nil + } + } + return "", errVcsToolMissing +} + // vcsFailureText is what the window says of a failed operation: the meaning of each stable code // the contract defines, else the provider's or Core's own message, which is a diagnostic. func (a *App) vcsFailureText(err error) string { @@ -747,6 +811,8 @@ func (a *App) vcsFailureText(err error) string { return message } switch { + case errors.Is(err, errRemoteDisconnected), refused != nil && refused.Code == core.CodeConnectionClosed: + return i18n.Shared(language, "desktop.remote.document.disconnected") case errors.Is(err, errVcsSafeMode), core.IsLaunchUntrustedWorkspace(err): return i18n.Shared(language, "desktop.trust.vcsSafeMode") case errors.Is(err, errVcsToolMissing): @@ -796,7 +862,7 @@ func (a *App) refreshVcsStatus(p *project, t vcsTarget) { } t.state.loading, t.state.failure = true, "" call := p.vcs.call(t.window, t.root, core.VcsStatus, struct{}{}, vcsReadTimeout) - sessions := p.vcs.runtime() + sessions := p.vcsRuntime() a.background(p, vcsReadTimeout, func(ctx context.Context) func(*App) { decoded, capabilities, err := a.runVcs(ctx, p, sessions, call) var status core.VcsStatusReply @@ -844,7 +910,7 @@ func (a *App) loadVcsHistory(p *project, t vcsTarget, more bool) { } t.state.historyLoading, t.state.historyFailure = true, "" call := p.vcs.call(t.window, t.root, core.VcsHistory, arguments, vcsReadTimeout) - sessions := p.vcs.runtime() + sessions := p.vcsRuntime() a.background(p, vcsReadTimeout, func(ctx context.Context) func(*App) { decoded, capabilities, err := a.runVcs(ctx, p, sessions, call) var page core.VcsHistoryReply @@ -884,7 +950,7 @@ func (a *App) runVcsChange(p *project, t vcsTarget, action, operation string, ar a.performed(action, surfaceButton) t.view.busy, t.view.notice, t.view.failure = operation, "", "" call := p.vcs.call(t.window, t.root, operation, arguments, vcsWriteTimeout) - sessions := p.vcs.runtime() + sessions := p.vcsRuntime() a.background(p, vcsWriteTimeout, func(ctx context.Context) func(*App) { decoded, capabilities, err := a.runVcs(ctx, p, sessions, call) return func(a *App) { @@ -1004,11 +1070,14 @@ func (a *App) showVcsDiff(p *project, t vcsTarget, change core.VcsChange) { } a.performed("vcs.showDiff", surfaceButton) call := p.vcs.call(t.window, t.root, core.VcsBaseContent, map[string]any{"path": change.Path}, vcsReadTimeout) - sessions := p.vcs.runtime() + sessions := p.vcsRuntime() a.background(p, vcsReadTimeout, func(ctx context.Context) func(*App) { file, capabilities, err := a.readVcsDiff(ctx, p, sessions, kernel, call, change) return func(a *App) { - if capabilities != nil && p.vcs.views[t.id] == t.view { + if !p.stillShows(t) { + return + } + if capabilities != nil { t.view.capabilities = capabilities } if err != nil { @@ -1044,7 +1113,24 @@ func (a *App) readVcsDiff(ctx context.Context, p *project, sessions *vcsRuntime, } var current []byte if change.Status != "deleted" && change.Status != "missing" { - current, err = os.ReadFile(filepath.Join(call.root, filepath.FromSlash(change.Path))) + file := filepath.Join(call.root, filepath.FromSlash(change.Path)) + if p.remote == nil { + current, err = os.ReadFile(file) + } else { + binding := p.remote.binding + host, ok := remoteplaceholder.HostPath(binding.LocalRoot(), binding.RemoteRoot(), file) + if !ok { + return core.GitDiffFile{}, capabilities, errRemoteOutsideFolder + } + session := sessions.connection.SessionID() + if session == "" { + return core.GitDiffFile{}, capabilities, errRemoteDisconnected + } + current, _, err = a.remoteDocuments(p).readHost(ctx, session, host, remoteDocumentReadLimit) + if !sessions.connection.IsCurrent() { + return core.GitDiffFile{}, capabilities, errRemoteDisconnected + } + } if err != nil && !errors.Is(err, os.ErrNotExist) { return core.GitDiffFile{}, capabilities, err } diff --git a/desktop/internal/workbench/workspace_trust.go b/desktop/internal/workbench/workspace_trust.go index bdf0bcf243..671305356e 100644 --- a/desktop/internal/workbench/workspace_trust.go +++ b/desktop/internal/workbench/workspace_trust.go @@ -269,20 +269,24 @@ func (a *App) applyProjectTrust(p *project, trusted bool) { } a.loadGit(p) a.startGitObservation(p) - if p.remote != nil { - // A remote workspace's Git runs on its host; its build tools and language servers do not - // run yet, so trusting it starts nothing else. - return + if p.remote == nil { + p.vcs.clearFailures() } - p.vcs.clearFailures() for index := range p.build.instances { instance := &p.build.instances[index] if instance.modelUntrusted { instance.modelUntrusted, instance.modelStopped, instance.modelError = false, false, "" } } - a.loadTitleRunConfigs(p) - a.retryFailedPluginServers() + if p.remote != nil { + a.loadBuildModel(p, p.build.selected) + for _, document := range p.docs.list { + a.startPluginServer(document.languageID) + } + } else { + a.loadTitleRunConfigs(p) + a.retryFailedPluginServers() + } } // skipUntrustedModel keeps the model of instance unloaded in safe mode, since loading it runs diff --git a/docs/ci-builds.md b/docs/ci-builds.md index 3acb1fd630..28892440a4 100644 --- a/docs/ci-builds.md +++ b/docs/ci-builds.md @@ -94,6 +94,14 @@ Viva 的 IDE API 辅助程序 `lithe-mcp` 由 `scripts/desktop/build-desktop-cor 远端工作区服务 `lithe-remote-server`(#2231)也嵌入客户端二进制:`package-desktop.sh` 在 `viva package` 前取得一个暂存目录(CI 通过 `LITHE_REMOTE_SERVER_STAGE` 给出可复用工作流已经冒烟测试过的产物,用 `--require-pinned` 校验;本地打包运行 `build-remote-server.sh` 重新编译,不要求固定提交),用 `verify-remote-server-artifacts.mjs` 校验后,再逐个核对体积和 SHA-256,复制成 `desktop/internal/remoteserver/<目标>.bin` 和 `remote-server-manifest.json`,以 `lithe_bundled_remote_server` 构建标签嵌入;校验后字节有变化就停止打包。这些生成文件被 Git 忽略,打包开始前先删掉上一次中断留下的旧文件,打包结束或失败时再删除,不跨工作树复制。运行期由 `remoteserver.Install` 在远程开发窗口连接主机时把与清单哈希一致的字节原子安装到用户缓存目录 `/Lithe/remote-server/<目标>/lithe-remote-server`(目录 0700、文件 0600,字节相同就复用),再交给 Core 上传到远程主机;它不执行这个文件,不写安装目录,安装包里也不多出文件,签名和增量更新基线不受影响。删除该缓存目录是安全的,下次连接会重新安装。开发运行由 `desktop-go.sh` 在 `.artifacts/desktop/remote-server/` 有清单时导出 `LITHE_REMOTE_SERVER_STAGE`,客户端直接读取暂存目录并按清单校验,不复制;打包版只用嵌入的字节,忽略该变量。 打开的远程工作区以本机占位目录作为项目根(`desktop/internal/remoteplaceholder`)。所有占位目录都在锚点文件 `/Lithe/remote-workspaces` 之下:它是一个空的只读普通文件(0444,所在目录 0700),第一次打开远程工作区时创建,之后每次使用都检查它仍是普通文件,是目录、链接或其他类型就拒绝打开。占位目录因此永远无法在本机列出或创建,没走 Core 的本机文件调用会以 ENOTDIR(Windows 上为 ERROR_PATH_NOT_FOUND)失败,不会读写一个看起来像项目的本机文件夹。锚点不含数据、不随工作区关闭删除;手动删除是安全的,下次打开会重新创建。它属于用户缓存目录,不在任何检出或安装目录里,不跨工作树复制,也不影响签名和增量更新基线。 + +插件运行的临时输入和远端构建报告保存在远端用户目录 `~/.lithe-server/plugin-runs/<随机 ID>/` 下。远端会话拥有目录,单次运行或构建在进程退出并读完结果后释放,启动失败时也释放,结束整个会话时服务端会清理余下目录。目录不参与本地编译缓存,不跨会话或工作树复制。客户端运行时不会把这些输入或报告写进安装资源,应用签名和增量更新基线不会受影响。 + +已批准的插件进程资源和托管运行时归档先上传到远端用户目录 `~/.lithe-server/deployment-staging/<随机 ID>/`。连接拥有暂存目录,提交、取消或断开会释放它。若远端服务异常退出,下次连接扫描并回收没有进程持有租约的暂存目录。暂存不跨连接或工作树复制,也不包含正在执行的项目快照。 + +资源全部校验通过后原子移到远端服务拥有的部署缓存。插件资源位于 `~/.lithe-server/plugin-deployments/<插件 ID>/<版本>-/`,托管运行时位于同一用户目录的 `managed-runtimes/`。同一远端账户按部署哈希复用,连接时根据桌面端的完整安装清单移除已卸载、且没有会话使用的版本。部署缓存不能当作编译产物跨工作树复制。客户端不写安装资源,应用签名和增量更新基线不受影响。 + +异平台插件包由桌面端保存在 `/Lithe/remote-plugin-archives/`。只保留校验和清单复核通过的完整 ZIP,最多 32 个、总计 1 GiB,按最近一次通过验证的使用时间淘汰。各客户端进程共用本机账户的目录和系统文件锁,每次解包重新验哈希。原子发布的暂存文件 `.pending` 随失败清理,异常退出遗留的文件由下次写入清理。用户可以清空缓存,程序会重新下载。对同平台安装包,桌面端在系统临时目录创建私有快照,核对安装时记录的文件路径、大小、内容和执行位,使用后删除。快照及缓存都不属于编译产物,不跨工作树复制,不改变应用签名或增量更新基线。 `viva package` 的链接参数是固定的,不能用 `-X` 注入构建信息,所以 `package-desktop.sh` 每次打包都生成 `desktop/internal/buildinfo/package_info.go`,以 `lithe_package_info` 构建标签编进客户端。文件记录更新渠道(`--stable` 为正式版,`--autobuild` 为 AutoBuild,本地包为空,不会自我更新)、构建时间(`LITHE_BUILD_TIME`,缺省为打包时刻)、提交(`LITHE_BUILD_COMMIT`,缺省为 `git HEAD`),以及验证更新源签名的公钥(`LITHE_UPDATE_PUBLIC_KEYS`,逗号分隔,只含公钥)。打包结束或失败时删除这个文件;它被 Git 忽略,不跨工作树复制。它只改变可执行文件本身,安装包里不会多出文件,签名和增量更新基线也不受影响。 打包和更新源签名用的 `viva` 命令由 `scripts/desktop/build-viva-tool.sh` 按 `desktop/go.mod` 的 `replace` 从 Viva fork 编译,放在当前工作树的 `.artifacts/desktop/tools/viva-<模块版本>/`;`replace` 指向本地目录时没有版本,放在 `viva-local/` 并每次重新编译。目录名只固定 Viva 源码,不记录 Go 工具链和主机平台;随 `.artifacts/desktop/` 一起复制时,必须满足下文的前提(含相同的 Go 工具链和主机平台),否则删掉该目录,由脚本在本工作树重新编译。它只在打包(`package-desktop.sh`)和签名更新源(`publish-update-feed.sh`)时使用,不进入安装包,不影响签名或增量更新基线。 @@ -135,7 +143,7 @@ Viva 桌面端(`desktop/`,Go)的构建状态位于 `.artifacts/desktop/` 默认从构建脚本中固定的 Lithe-core-rust 提交检出;联调尚未合入的 core 改动时,设置 `LITHE_CORE_RUST_DIR=/path/to/Lithe-core-rust` 改用本地检出(脚本只读取它,不修改该检出)。 `desktop-go.sh` 每次运行前都调用构建脚本重新暂存,固定提交变了或本地检出改了都不会继续链接旧库; -没有变化时 git 和 cargo 都判定为最新,这一步约一秒。固定检出和 `LITHE_CORE_RUST_DIR` 共用同一个 Cargo 编译目录, +没有变化时 git 和 cargo 都判定为最新,暂存时按内容复用相同的静态库,无需为未变化的归档再分配空间。固定检出和 `LITHE_CORE_RUST_DIR` 共用同一个 Cargo 编译目录, 而 cargo 按成员在工作区内的相对路径计算哈希,不看检出所在位置:两个检出把每个工作区成员(例如事件目录所在的 `lithe-diagnostics`)编译到同一组文件、同一份指纹,新旧只按修改时间判断,切回原检出时会把另一个检出的代码当作 本检出暂存。构建脚本因此按 target 和 profile 在编译目录里记录上次编译工作区成员的检出 diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index acbfcd1ee8..976b363899 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -458,7 +458,12 @@ if [[ ! -s "$NATIVE_LIBS_FILE" ]]; then exit 1 fi -install -m 0644 "$LIBRARY_DIR/liblithe_core.a" "$STAGE_DIR/lib/liblithe_core.a" +# Compare before install: BSD install -C can still stage a temporary copy +# before comparing, so an unchanged archive can otherwise exhaust disk space. +STAGED_LIBRARY="$STAGE_DIR/lib/liblithe_core.a" +if [[ -L "$STAGED_LIBRARY" ]] || ! cmp -s "$LIBRARY_DIR/liblithe_core.a" "$STAGED_LIBRARY"; then + install -m 0644 "$LIBRARY_DIR/liblithe_core.a" "$STAGED_LIBRARY" +fi install -m 0644 "$CORE_DIR/rust/crates/core/include/lithe_core.h" "$STAGE_DIR/include/lithe_core.h" # The IDE API helper is the lithe-ide-host crate's lithe-mcp binary from the same pinned diff --git a/shared/i18n/features/plugin-managed-runtimes.json b/shared/i18n/features/plugin-managed-runtimes.json index 7b615cabde..58d7f94bdf 100644 --- a/shared/i18n/features/plugin-managed-runtimes.json +++ b/shared/i18n/features/plugin-managed-runtimes.json @@ -34,6 +34,18 @@ "received": "string" } }, + { + "id": "desktop.marketplace.runtimeUploading", + "description": "Upload of a verified managed runtime archive to the workspace host", + "platforms": [ + "desktop" + ], + "parameters": { + "dependency": "string", + "sent": "string", + "total": "string" + } + }, { "id": "desktop.marketplace.runtimeExtracting", "description": "Managed plugin runtime installation: runtimeExtracting", @@ -146,6 +158,7 @@ "desktop.marketplace.runtimeChecking": "Checking {dependency}…", "desktop.marketplace.runtimeDownloading": "Downloading {dependency}… {received} / {total} MiB", "desktop.marketplace.runtimeReceived": "Downloading {dependency}… {received} MiB", + "desktop.marketplace.runtimeUploading": "Uploading {dependency} to workspace host… {sent} / {total} MiB", "desktop.marketplace.runtimeExtracting": "Unpacking {dependency}…", "desktop.marketplace.runtimeVerifying": "Verifying {dependency}…", "desktop.marketplace.runtimeRepairing": "Repairing {dependency}…", @@ -164,6 +177,7 @@ "desktop.marketplace.runtimeChecking": "正在检查 {dependency}…", "desktop.marketplace.runtimeDownloading": "正在下载 {dependency}… {received} / {total} MiB", "desktop.marketplace.runtimeReceived": "正在下载 {dependency}… {received} MiB", + "desktop.marketplace.runtimeUploading": "正在将 {dependency} 上传至工作区主机… {sent} / {total} MiB", "desktop.marketplace.runtimeExtracting": "正在解压 {dependency}…", "desktop.marketplace.runtimeVerifying": "正在验证 {dependency}…", "desktop.marketplace.runtimeRepairing": "正在修复 {dependency}…", diff --git a/shared/i18n/features/plugin-native-terminals.json b/shared/i18n/features/plugin-native-terminals.json new file mode 100644 index 0000000000..c82ab8742b --- /dev/null +++ b/shared/i18n/features/plugin-native-terminals.json @@ -0,0 +1,21 @@ +{ + "schemaVersion": 1, + "messages": [ + { + "id": "desktop.pluginHost.terminalConsentRemote", + "description": "Remote connection where the plugin's terminal command will run", + "platforms": ["desktop"], + "parameters": { + "connection": "string" + } + } + ], + "locales": { + "en-US": { + "desktop.pluginHost.terminalConsentRemote": "Remote connection: {connection}" + }, + "zh-CN": { + "desktop.pluginHost.terminalConsentRemote": "远程连接:{connection}" + } + } +} diff --git a/shared/i18n/features/run-remote.json b/shared/i18n/features/run-remote.json new file mode 100644 index 0000000000..70ad61e61c --- /dev/null +++ b/shared/i18n/features/run-remote.json @@ -0,0 +1,28 @@ +{ + "schemaVersion": 1, + "messages": [ + { + "id": "desktop.run.remoteLabel", + "description": "Run tab title for a process running on the remote workspace host", + "platforms": ["desktop"], + "parameters": { + "label": "string" + } + }, + { + "id": "desktop.run.remoteDisconnected", + "description": "Run status when the remote process connection was lost", + "platforms": ["desktop"] + } + ], + "locales": { + "en-US": { + "desktop.run.remoteLabel": "{label} (Remote)", + "desktop.run.remoteDisconnected": "Connection to the remote workspace lost." + }, + "zh-CN": { + "desktop.run.remoteLabel": "{label}(远端)", + "desktop.run.remoteDisconnected": "与远程工作区的连接已断开。" + } + } +} diff --git a/shared/i18n/locales/en-US.json b/shared/i18n/locales/en-US.json index 95383f3430..0bc6aba7af 100644 --- a/shared/i18n/locales/en-US.json +++ b/shared/i18n/locales/en-US.json @@ -949,6 +949,7 @@ "desktop.debug.starting": "Starting the debug adapter…", "desktop.debug.stop": "Stop debugging", "desktop.debug.targetUnavailable": "No runnable debug target was found. Build the program first.", + "desktop.debug.terminalUnavailable": "Could not start the remote debug terminal.", "desktop.debug.terminated": "Debug session terminated", "desktop.debug.timedOut": "The debug adapter did not answer in time.", "desktop.debug.toggleBreakpoint": "Toggle breakpoint at caret", @@ -1385,6 +1386,7 @@ "desktop.pluginSettings.restartRequired": "Saved changes need a language server restart to take effect.", "desktop.pluginSettings.save": "Save", "desktop.pluginSettings.saved": "Saved and read back from the source.", + "desktop.pluginSettings.remoteConnection": "Remote: {name}", "desktop.pluginSettings.scope": "Settings scope", "desktop.pluginSettings.scopeHelp": "Global settings apply to every project. Project settings apply to this project only, and each value stored there overrides the global one. Save or reload your draft before switching scope.", "desktop.pluginSettings.sourceChanged": "Settings changed in another window. Your draft is kept; reload before saving.", @@ -1544,6 +1546,10 @@ "desktop.sourceSettings.add": "Add override", "desktop.sourceSettings.allEntriesShown": "All available entries are shown.", "desktop.sourceSettings.close": "Back", + "desktop.sourceSettings.confirmRemoteSave": "Save to these remote files?", + "desktop.sourceSettings.remotePath": "Absolute path on the remote host", + "desktop.sourceSettings.remoteSaveUnverified": "One or more remote files may have been saved. Reload to check their contents before trying again.", + "desktop.sourceSettings.remoteSourceChanged": "The remote file or connection changed. Reload the settings before saving.", "desktop.sourceSettings.compilerTitle": "{compiler} Compiler", "desktop.sourceSettings.inherit": "Inherit ({value})", "desktop.sourceSettings.noValue": "Not determined", diff --git a/shared/i18n/locales/zh-CN.json b/shared/i18n/locales/zh-CN.json index e828064c0a..c61026d591 100644 --- a/shared/i18n/locales/zh-CN.json +++ b/shared/i18n/locales/zh-CN.json @@ -949,6 +949,7 @@ "desktop.debug.starting": "正在启动调试适配器…", "desktop.debug.stop": "停止调试", "desktop.debug.targetUnavailable": "没有找到可运行的调试目标,请先构建程序。", + "desktop.debug.terminalUnavailable": "无法启动远程调试终端。", "desktop.debug.terminated": "调试会话已终止", "desktop.debug.timedOut": "调试适配器没有及时响应。", "desktop.debug.toggleBreakpoint": "在当前行切换断点", @@ -1385,6 +1386,7 @@ "desktop.pluginSettings.restartRequired": "已保存的更改需要重启语言服务器后生效。", "desktop.pluginSettings.save": "保存", "desktop.pluginSettings.saved": "已保存并从来源重新读取。", + "desktop.pluginSettings.remoteConnection": "远端:{name}", "desktop.pluginSettings.scope": "设置范围", "desktop.pluginSettings.scopeHelp": "全局设置对所有项目生效;项目设置只对当前项目生效,存了值的项会覆盖全局值。切换范围前,请保存或重新加载草稿。", "desktop.pluginSettings.sourceChanged": "设置已在其他窗口更改。草稿已保留;请重新加载后再保存。", @@ -1544,6 +1546,10 @@ "desktop.sourceSettings.add": "添加覆盖", "desktop.sourceSettings.allEntriesShown": "所有可用条目已列出。", "desktop.sourceSettings.close": "返回", + "desktop.sourceSettings.confirmRemoteSave": "保存到以下远端文件?", + "desktop.sourceSettings.remotePath": "远端主机上的绝对路径", + "desktop.sourceSettings.remoteSaveUnverified": "一个或多个远端文件可能已保存。请重新加载以确认内容,再重试。", + "desktop.sourceSettings.remoteSourceChanged": "远端文件或连接已变化。请重新加载设置后再保存。", "desktop.sourceSettings.compilerTitle": "{compiler} 编译器", "desktop.sourceSettings.inherit": "继承({value})", "desktop.sourceSettings.noValue": "未确定", diff --git a/shared/i18n/messages.json b/shared/i18n/messages.json index ff59f14371..57145c91a8 100644 --- a/shared/i18n/messages.json +++ b/shared/i18n/messages.json @@ -8831,6 +8831,13 @@ "desktop" ] }, + { + "id": "desktop.debug.terminalUnavailable", + "description": "Error when the integrated debug terminal cannot start a program on the remote host.", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.debug.terminated", "description": "Debug session terminated", @@ -14404,6 +14411,16 @@ "desktop" ] }, + { + "id": "desktop.pluginSettings.remoteConnection", + "description": "The connection that owns the displayed settings source.", + "platforms": [ + "desktop" + ], + "parameters": { + "name": "string" + } + }, { "id": "desktop.pluginSettings.scope", "description": "Installed plugin settings editor: scope", @@ -18791,6 +18808,34 @@ "desktop" ] }, + { + "id": "desktop.sourceSettings.confirmRemoteSave", + "description": "Confirmation, path entry and recovery for remote native settings.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.sourceSettings.remotePath", + "description": "Confirmation, path entry and recovery for remote native settings.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.sourceSettings.remoteSaveUnverified", + "description": "Confirmation, path entry and recovery for remote native settings.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.sourceSettings.remoteSourceChanged", + "description": "Confirmation, path entry and recovery for remote native settings.", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.sourceSettings.compilerTitle", "description": "Generic source-backed settings form controls and status.", diff --git a/shared/platform-feature-matrix/features/build-system-plugins.json b/shared/platform-feature-matrix/features/build-system-plugins.json index 4bfb8cbc44..845ea5d2c4 100644 --- a/shared/platform-feature-matrix/features/build-system-plugins.json +++ b/shared/platform-feature-matrix/features/build-system-plugins.json @@ -2,7 +2,7 @@ "id": "build-system-plugins", "area": "扩展", "group": "插件与主题", - "capability": "构建系统插件(API 3 buildSystems):插件用 JSON 声明构建工具的识别、可执行文件、选项、任务、运行入口、测试和输出格式,或由插件自带、与语言服务器同类的 Provider 进程回答模型和依赖,Rust Core 统一校验、生成命令行或 Provider 请求并解码结果,宿主为每个构建系统打开一个按声明(icon、presentation、category)布局的工具窗口;通过共享 executableResolution 候选解析支持可选设置路径、优先级与相对排序,空值自动发现、显式失败不回退;buildProviders 2/3 原生任务与测试执行复用工作区后端会话,带进度、取消、结果与配置失效隔离;协议 3 可按声明发现测试并在现有构建树按精确选择器运行,源码/设置变化撤销旧清单;协议 4 可为应用目标准备启动计划,Core 校验后交给原生 Run 管理进程;Provider 应用可保存到本地 Run v2 配置并重新准备后重启;插件自有原生程序经 Provider v5 构建并准备 Debug,Build 树和保存的 Run 配置复用原生调试会话;协议 7 可选原生配置投影经通用设置页确认保存并回读(独立能力行 build-native-configuration);buildSystems 3 可声明按实例根独立保存选项;executableResolution 2 复用 Run 工具链注册表和实例本机选择;团队 Build 偏好与本机差异覆盖分开保存;buildProviders 8 支持后端随执行返回有界规范报告并保留工程身份;协议 9 支持声明命名空间的语义测试标识,旧后端不能忽略筛选条件;Provider 以 JSON-RPC 错误回答时,运行、调试准备、模型和依赖失败显示 Provider 自己的说明,日志只记录 Core 的错误代码。通过宿主工具链启动的独立构建提供者按已保存的项目和全局来源判断是否重启,覆盖共用来源的独立窗口。直接运行打包程序的提供者可在工具链来源不可读时继续使用。初始化期间保存时,在原请求期限内重启。已有请求排空后关闭旧进程,卸载时等待退役进程退出再删包。 本地构建插件可以读取自己声明的构建系统实例的生效选项,并订阅偏好和指定配置文件的变更。", + "capability": "构建系统插件(API 3 buildSystems):插件用 JSON 声明构建工具的识别、可执行文件、选项、任务、运行入口、测试和输出格式,或由插件自带、与语言服务器同类的 Provider 进程回答模型和依赖,Rust Core 统一校验、生成命令行或 Provider 请求并解码结果,宿主为每个构建系统打开一个按声明(icon、presentation、category)布局的工具窗口;通过共享 executableResolution 候选解析支持可选设置路径、优先级与相对排序,空值自动发现、显式失败不回退;buildProviders 2/3 原生任务与测试执行复用工作区后端会话,带进度、取消、结果与配置失效隔离;协议 3 可按声明发现测试并在现有构建树按精确选择器运行,源码/设置变化撤销旧清单;协议 4 可为应用目标准备启动计划,Core 校验后交给原生 Run 管理进程;Provider 应用可保存到本地 Run v2 配置并重新准备后重启;插件自有原生程序经 Provider v5 构建并准备 Debug,Build 树和保存的 Run 配置复用原生调试会话;协议 7 可选原生配置投影经通用设置页确认保存并回读(独立能力行 build-native-configuration);buildSystems 3 可声明按实例根独立保存选项;executableResolution 2 复用 Run 工具链注册表和实例本机选择;团队 Build 偏好与本机差异覆盖分开保存;buildProviders 8 支持后端随执行返回有界规范报告并保留工程身份;协议 9 支持声明命名空间的语义测试标识,旧后端不能忽略筛选条件;Provider 以 JSON-RPC 错误回答时,运行、调试准备、模型和依赖失败显示 Provider 自己的说明,日志只记录 Core 的错误代码。通过宿主工具链启动的独立构建提供者按已保存的项目和全局来源判断是否重启,覆盖共用来源的独立窗口。直接运行打包程序的提供者可在工具链来源不可读时继续使用。初始化期间保存时,在原请求期限内重启。已有请求排空后关闭旧进程,卸载时等待退役进程退出再删包。 构建插件可查询自己声明的构建系统实例的生效选项。远程查询合并远端团队配置和客户端个人偏好,重连时拒绝旧结果。偏好和指定文件的变更订阅适用于本地工作区。桌面端从当前 SSH 会话识别构建系统并读取静态模型,重连后重新检测。", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", @@ -42,7 +42,8 @@ "desktop/internal/workbench/build_command_output_test.go", "desktop/internal/buildprovider/lifecycle_regression_test.go", "desktop/internal/pluginservice/hostbuild.go", - "desktop/internal/pluginservice/hostbuild_test.go" + "desktop/internal/pluginservice/hostbuild_test.go", + "desktop/internal/workbench/remote_build_test.go" ] }, "windows": { @@ -86,7 +87,8 @@ "desktop/internal/workbench/build_command_windows_test.go", "desktop/internal/buildprovider/lifecycle_regression_test.go", "desktop/internal/pluginservice/hostbuild.go", - "desktop/internal/pluginservice/hostbuild_test.go" + "desktop/internal/pluginservice/hostbuild_test.go", + "desktop/internal/workbench/remote_build_test.go" ] }, "owner": "Extensions", diff --git a/shared/platform-feature-matrix/features/debug-tcp-transport.json b/shared/platform-feature-matrix/features/debug-tcp-transport.json index d8a29a5b83..26d33c125d 100644 --- a/shared/platform-feature-matrix/features/debug-tcp-transport.json +++ b/shared/platform-feature-matrix/features/debug-tcp-transport.json @@ -13,11 +13,13 @@ "desktop/internal/workbench/debug_tcp_test.go", "desktop/internal/workbench/debug_announced.go", "desktop/internal/workbench/debug_announced_test.go", + "desktop/internal/workbench/debug_remote_transport.go", "desktop/internal/core/debug_transport.go", "desktop/internal/core/debug_state_test.go", "desktop/internal/core/debug_announcement_test.go", "desktop/internal/buildprocess/process.go", - "desktop/internal/buildprocess/process_test.go" + "desktop/internal/buildprocess/process_test.go", + "desktop/internal/workbench/debug_tunnel_ssh_test.go" ] }, "windows": { @@ -30,16 +32,18 @@ "desktop/internal/workbench/debug_tcp_test.go", "desktop/internal/workbench/debug_announced.go", "desktop/internal/workbench/debug_announced_test.go", + "desktop/internal/workbench/debug_remote_transport.go", "desktop/internal/core/debug_transport.go", "desktop/internal/core/debug_state_test.go", "desktop/internal/core/debug_announcement_test.go", "desktop/internal/buildprocess/process.go", - "desktop/internal/buildprocess/process_test.go" + "desktop/internal/buildprocess/process_test.go", + "desktop/internal/workbench/debug_tunnel_ssh_test.go" ] }, "owner": "Debug", - "verification": "macOS:在有已安装调试提供方的源码文件上,从 Debug 更多操作打开连接调试适配器,填写已运行的 DAP 服务地址、launch/attach 与适配器参数。分别验证回环、IPv4/IPv6/DNS 外部地址、非回环默认取消的逐次确认、错误 JSON 与非法端点。确认 IDE 到 DAP 的地址不覆盖适配器到 debuggee 的地址,既有 stdio 与 tcpLanguageServer 回环限制不变。验证端点发现与建连两段独立超时(冷启动发现不缩短也不拉长建连)、被拒绝/不可达端口立即以系统原因结束、连接拒绝或 initialize 超时/未获批准/已有活动会话时对话框保持打开并保留已填内容,初始化完成后才关闭;取消等待只停止本次连接,不能误停后来选中的会话、当前文件无调试提供方时菜单项不可用、单个在途写入、字节/消息预算、写入超时、EOF、解析/建连/已连接时取消和旧回调隔离(含 Core 桥接失败清理后重新登记的连接);停止时断开帧最多排空 1 秒且 attach 的 terminateDebuggee 为 false,超时仍回收;停止后外部服务、共享 LSP、attach 目标与用户隧道仍存活。真实回环测试覆盖 Core initialize/attach 帧;真实适配器和界面全链路仍待验收。Windows 未接入此 TCP 宿主。 Viva:托管 tcpAnnounced 适配器停止时验证 disconnect 后在 Core 退出宽限内自行退出并完成清理;忽略协议退出的子进程在宽限到期后强制回收,重复停止不提前打断。", - "notes": "语言服务器托管适配器(tcpLanguageServer)和自行输出监听端口的适配器进程(tcpAnnounced)的环回 TCP 连接都按 Core 的 debug.transport.handle 生命周期驱动;tcpAnnounced 的端点由 Core 的 debug.adapters.readAnnouncement 从进程输出行读出,发现期限沿用 Core 默认值:帧先入队、同时只有一个写在途,发现/连接/写入期限与排空期限都是 Core 下发的定时器,用户停止时先发 DAP disconnect 再有界排空。直接连接用户指定的远程适配器端点(adapterEndpoint)仍未接入。 已通过协议请求退出的托管进程使用 Core 解析的进程退出宽限,不再立即发送系统终止信号;启动失败仍直接停止,不等待远端协议应答。", + "verification": "macOS:在有已安装调试提供方的源码文件上,从 Debug 更多操作打开连接调试适配器,填写已运行的 DAP 服务地址、launch/attach 与适配器参数。分别验证回环、IPv4/IPv6/DNS 外部地址、非回环默认取消的逐次确认、错误 JSON 与非法端点。确认 IDE 到 DAP 的地址不覆盖适配器到 debuggee 的地址,既有 stdio 与 tcpLanguageServer 回环限制不变。验证端点发现与建连两段独立超时(冷启动发现不缩短也不拉长建连)、被拒绝/不可达端口立即以系统原因结束、连接拒绝或 initialize 超时/未获批准/已有活动会话时对话框保持打开并保留已填内容,初始化完成后才关闭;取消等待只停止本次连接,不能误停后来选中的会话、当前文件无调试提供方时菜单项不可用、单个在途写入、字节/消息预算、写入超时、EOF、解析/建连/已连接时取消和旧回调隔离(含 Core 桥接失败清理后重新登记的连接);停止时断开帧最多排空 1 秒且 attach 的 terminateDebuggee 为 false,超时仍回收;停止后外部服务、共享 LSP、attach 目标与用户隧道仍存活。真实回环测试覆盖 Core initialize/attach 帧;真实适配器和界面全链路仍待验收。Windows 未接入此 TCP 宿主。 Viva:托管 tcpAnnounced 适配器停止时验证 disconnect 后在 Core 退出宽限内自行退出并完成清理;忽略协议退出的子进程在宽限到期后强制回收,重复停止不提前打断。 TestLocalDebugAdapterAttachesThroughSSHWorkspaceTunnel 已在 macOS arm64 和 Windows x64(ARM64 来宾内仿真)连接 Linux x86_64,验证本机适配器通过会话转发附加,停止后释放转发并保留远端被调试进程。", + "notes": "Viva 在可信远程工作区显示 Debug 工具窗口。远端 tcpAnnounced 适配器通过工作区会话启动,Core 从输出识别环回地址并建立转发,会话结束时回收进程与本次创建的转发。验收时在远程源码设置断点,启动后检查断点命中并从调用栈打开正确的文件和行,继续后检查进程与端口转发均已回收。语言服务器托管适配器(tcpLanguageServer)和本机 tcpAnnounced 都复用 Core 的 TCP 生命周期。帧先入队,同时只有一个写在途,Core 管理发现、连接、写入和排空期限。用户停止时先发送 DAP disconnect 并有界排空,本机托管进程使用 Core 的退出宽限。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { diff --git a/shared/platform-feature-matrix/features/declarative-plugin-settings.json b/shared/platform-feature-matrix/features/declarative-plugin-settings.json index 822cfd6d26..d642004cb6 100644 --- a/shared/platform-feature-matrix/features/declarative-plugin-settings.json +++ b/shared/platform-feature-matrix/features/declarative-plugin-settings.json @@ -2,7 +2,7 @@ "id": "declarative-plugin-settings", "area": "插件", "group": "插件管理", - "capability": "声明式插件通过 Core 校验的设置声明提供整数、枚举、布尔、多选、文本、文件和目录设置,支持全局/项目继承、真实来源保存、通用界面、页面/动作注册及 restart/immediate/reload/nextRun 生效;实际启动与运行消费者必须读取同一来源。 声明动作经显式确认、安装/工作区身份复查与 Core 同工作区函数会话选择后调用;支持取消和完成状态,保留未保存草稿。 已启用插件动态贡献语言/构建系统页,同一应用内窗口按原生目录身份接收全局/项目保存通知,独立保留项目覆盖值与未保存草稿。 插件包可自带 l10n/<语言>.json 翻译设置文字,Core 按界面语言挑选文件并逐条回退到清单原文;切换界面语言后重读文字,但保留未保存草稿。 支持 Core 来源表单、编译器页面、有效/继承值和显式条件原子保存;读取项目工具须点击读取按钮。 来源表单支持 sourceSettings 1:模块侧栏(按父子缩进)、字段分组标签页,以及带添加/移除/排序、文件/目录/候选项三种添加方式和布尔/枚举属性列的条目列表;只读模块只显示条目;独立构建提供者进程记录启动时的插件设置,设置变化后下一次请求启动新进程,旧进程在已有请求结束后关闭。", + "capability": "声明式插件通过 Core 校验的设置声明提供整数、枚举、布尔、多选、文本、文件和目录设置,支持全局/项目继承、真实来源保存、通用界面、页面/动作注册及 restart/immediate/reload/nextRun 生效;实际启动与运行消费者必须读取同一来源。 声明动作经显式确认、安装/工作区身份复查与 Core 同工作区函数会话选择后调用;支持取消和完成状态,保留未保存草稿。 已启用插件动态贡献语言/构建系统页,同一应用内窗口按原生目录身份接收全局/项目保存通知,独立保留项目覆盖值与未保存草稿。 插件包可自带 l10n/<语言>.json 翻译设置文字,Core 按界面语言挑选文件并逐条回退到清单原文;切换界面语言后重读文字,但保留未保存草稿。 支持 Core 来源表单、编译器页面、有效/继承值和显式条件原子保存;读取项目工具须点击读取按钮。 来源表单支持 sourceSettings 1:模块侧栏(按父子缩进)、字段分组标签页,以及带添加/移除/排序、文件/目录/候选项三种添加方式和布尔/枚举属性列的条目列表;只读模块只显示条目;独立构建提供者进程记录启动时的插件设置,设置变化后下一次请求启动新进程,旧进程在已有请求结束后关闭。 远端原生设置支持 sourceSettings 2,通过插件声明的远端程序读回非敏感字段,显示连接和写入目标,经确认后在远端项目或用户目录条件写入并回读。", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", @@ -57,7 +57,9 @@ "desktop/internal/workbench/debug_start.go", "desktop/internal/workbench/pluginbackends_test.go", "desktop/internal/settingswindow/plugin_settings_visual_test.go", - "desktop/internal/workbench/build_provider_restart_test.go" + "desktop/internal/workbench/build_provider_restart_test.go", + "desktop/internal/pluginservice/remote_settings.go", + "desktop/internal/pluginsettings/remote_sources.go" ] }, "windows": { @@ -116,11 +118,13 @@ "desktop/internal/workbench/debug_start.go", "desktop/internal/workbench/pluginbackends_test.go", "desktop/internal/settingswindow/plugin_settings_visual_test.go", - "desktop/internal/workbench/build_provider_restart_test.go" + "desktop/internal/workbench/build_provider_restart_test.go", + "desktop/internal/pluginservice/remote_settings.go", + "desktop/internal/pluginsettings/remote_sources.go" ] }, "owner": "Plugin Platform", - "verification": "Viva:共享 settings-documents fixture 经真实 Core C ABI 验证类型、作用层、整批拒绝及文档保留;原生来源覆盖权限/元数据、冲突、取消、捕获来源回读、提交后回读失败。Build/Debug 读取实际文件,明确失效路径不能静默回退;Build 全局专属程序不能被项目文件替换。LSP 启动同时传全局/项目设置、初始化选项与 Core 展开的 workspaceConfiguration。真实协议子进程在同一 Core 会话接收更新通知并重新拉取值;保存来源后服务层回读、展开并更新现有会话,损坏来源不推空配置。macOS 有定向测试与真实子进程证据;此前设置动作节点已在 Lithe-dev 通过完整消费者与定向 race;本节点结果按独立报告记录。已安装本地目录独立于商店网络,Core 绑定注册 ID/版本;原生快照拒绝安装替换。七种控件与全局/项目草稿已接线,macOS 无头驱动验证原生文本输入、明确保存回读、冲突保留、重新加载;共享模型验证七种类型及非法整数原文。保存后的即时通知与所属插件模型刷新已接线,旧模型回包不会覆盖待刷新状态,运行任务及无关模型保持。动作原生窗体、重启与完整生效状态、目标平台原生 UI 及正式市场准入尚未验收,宿主仍不声明 settings 2。 动作节点增加:实际按钮确认/取消,草稿不保存;真实提供方函数成功与取消、原进程复用、会话关闭后不可用;拒绝不同工作区/版本/未注册函数,显示版本不可替代私有身份,项目同路径重开不能接受过期动作。 动态页面节点验证 Core 启用过滤、多个贡献者、动作独立页面、搜索保留父节点、作用域/版本通知规则;Viva 验证页面/动作筛选与切页草稿保留;多工作台驱动验证同偏好目录全局通知、同项目通知、项目覆盖隔离、私有身份及旧生命周期拒绝。同一应用进程内通知不代表独立进程实时同步,也不新增多工作台创建入口。 设置列表填满表单标题下的高度、最少 160 像素,窗口放不下时滚动整页而不截断;Viva 无头驱动在最小窗口、800、1000 高度下验证语言页与已安装插件“设置”标签页的列表随窗口等量增长、底部与确定按钮间距不变、最后一项完整显示。 插件语言文件:契约 localization-cases 的 13 个用例经真实 Core 逐条比对 applied/rejected;保存回读保留译文;从已安装包读取前后,文件清单与字节不变;Viva 无头驱动验证切换界面语言、有草稿时不重读、确认弹窗用译后的按钮标题;读不了或被拒绝的语言文件各记一条 WARN。 模块结构节点:Core settings-sources-modules fixture 经真实 C ABI 读取;Viva 无头驱动验证模块侧栏按父子缩进且只显示所选模块、标签页只显示本组字段、浏览不产生草稿;排序、勾选导出、从候选项对话框添加后保存,Core 规划的写入按顺序且去掉显示文字;全部移除为显式空列表,插件给出继承值时才提供重置;只读模块无编辑控件且条目不可选。自动化:TestSourceModuleListShowsTheSelectedModuleOneTabAtATime、TestSourceEntryListEditsReachThePluginWithoutDisplayText、TestSourceEntryListRemovesToAnExplicitEmptyListAndResets、TestReadOnlyModuleShowsEntriesWithoutEditing、TestEntryDraftsCompareWithoutDisplayTextAndSkipDuplicatePaths;截图 TestVisualModuleStructureForm(中英、深浅主题)。原生文件/目录选择器只在实机验收,Windows 实机未执行。 #2079 修复:动作依赖的语言服务器未运行时返回携带失败详情的 ErrNoSession,设置页显示提供方未运行指引与原始启动失败原因;保存 restart 效果设置对失败态语言服务器同样展示可点击的重启按钮;工具链保存后的自动重试保留已通知错误去重。macOS 自动化与 -race 验证通过:TestRetryFailedPluginServersPreservesNotifiedErrorDeduplication、TestWaitReadyPluginServerWrapsErrNoSession、TestPluginSettingsRestartEffectMarksFailedServerRetryable、TestSettingsActionUnavailableShowsProviderReasonAndRestartForFailedServer 及截图 TestVisualPluginSettingsUnavailableAction;Windows 原生窗口未在本机实机验收。 Windows:用普通账户在继承“修改”权限的 NTFS 目录里再次保存已有配置,检查新内容和原所有者、组及访问规则。原生回归 TestNativeConfigPublicationWithWindowsModifyAccess。", + "verification": "Viva:共享 settings-documents fixture 经真实 Core C ABI 验证类型、作用层、整批拒绝及文档保留;原生来源覆盖权限/元数据、冲突、取消、捕获来源回读、提交后回读失败。Build/Debug 读取实际文件,明确失效路径不能静默回退;Build 全局专属程序不能被项目文件替换。LSP 启动同时传全局/项目设置、初始化选项与 Core 展开的 workspaceConfiguration。真实协议子进程在同一 Core 会话接收更新通知并重新拉取值;保存来源后服务层回读、展开并更新现有会话,损坏来源不推空配置。macOS 有定向测试与真实子进程证据;此前设置动作节点已在 Lithe-dev 通过完整消费者与定向 race;本节点结果按独立报告记录。已安装本地目录独立于商店网络,Core 绑定注册 ID/版本;原生快照拒绝安装替换。七种控件与全局/项目草稿已接线,macOS 无头驱动验证原生文本输入、明确保存回读、冲突保留、重新加载;共享模型验证七种类型及非法整数原文。保存后的即时通知与所属插件模型刷新已接线,旧模型回包不会覆盖待刷新状态,运行任务及无关模型保持。动作原生窗体、重启与完整生效状态、目标平台原生 UI 及正式市场准入尚未验收,宿主仍不声明 settings 2。 动作节点增加:实际按钮确认/取消,草稿不保存;真实提供方函数成功与取消、原进程复用、会话关闭后不可用;拒绝不同工作区/版本/未注册函数,显示版本不可替代私有身份,项目同路径重开不能接受过期动作。 动态页面节点验证 Core 启用过滤、多个贡献者、动作独立页面、搜索保留父节点、作用域/版本通知规则;Viva 验证页面/动作筛选与切页草稿保留;多工作台驱动验证同偏好目录全局通知、同项目通知、项目覆盖隔离、私有身份及旧生命周期拒绝。同一应用进程内通知不代表独立进程实时同步,也不新增多工作台创建入口。 设置列表填满表单标题下的高度、最少 160 像素,窗口放不下时滚动整页而不截断;Viva 无头驱动在最小窗口、800、1000 高度下验证语言页与已安装插件“设置”标签页的列表随窗口等量增长、底部与确定按钮间距不变、最后一项完整显示。 插件语言文件:契约 localization-cases 的 13 个用例经真实 Core 逐条比对 applied/rejected;保存回读保留译文;从已安装包读取前后,文件清单与字节不变;Viva 无头驱动验证切换界面语言、有草稿时不重读、确认弹窗用译后的按钮标题;读不了或被拒绝的语言文件各记一条 WARN。 模块结构节点:Core settings-sources-modules fixture 经真实 C ABI 读取;Viva 无头驱动验证模块侧栏按父子缩进且只显示所选模块、标签页只显示本组字段、浏览不产生草稿;排序、勾选导出、从候选项对话框添加后保存,Core 规划的写入按顺序且去掉显示文字;全部移除为显式空列表,插件给出继承值时才提供重置;只读模块无编辑控件且条目不可选。自动化:TestSourceModuleListShowsTheSelectedModuleOneTabAtATime、TestSourceEntryListEditsReachThePluginWithoutDisplayText、TestSourceEntryListRemovesToAnExplicitEmptyListAndResets、TestReadOnlyModuleShowsEntriesWithoutEditing、TestEntryDraftsCompareWithoutDisplayTextAndSkipDuplicatePaths;截图 TestVisualModuleStructureForm(中英、深浅主题)。原生文件/目录选择器只在实机验收,Windows 实机未执行。 #2079 修复:动作依赖的语言服务器未运行时返回携带失败详情的 ErrNoSession,设置页显示提供方未运行指引与原始启动失败原因;保存 restart 效果设置对失败态语言服务器同样展示可点击的重启按钮;工具链保存后的自动重试保留已通知错误去重。macOS 自动化与 -race 验证通过:TestRetryFailedPluginServersPreservesNotifiedErrorDeduplication、TestWaitReadyPluginServerWrapsErrNoSession、TestPluginSettingsRestartEffectMarksFailedServerRetryable、TestSettingsActionUnavailableShowsProviderReasonAndRestartForFailedServer 及截图 TestVisualPluginSettingsUnavailableAction;Windows 原生窗口未在本机实机验收。 Windows:用普通账户在继承“修改”权限的 NTFS 目录里再次保存已有配置,检查新内容和原所有者、组及访问规则。原生回归 TestNativeConfigPublicationWithWindowsModifyAccess。 #2231:分别在远端项目目录和用户目录读取配置,检查保存确认中的连接及文件路径。验证取消、文件被其他进程改写、重新连接和写入后回读;客户端本地源文件保持原样。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { diff --git a/shared/platform-feature-matrix/features/plugin-backend-run-start.json b/shared/platform-feature-matrix/features/plugin-backend-run-start.json index 38258280d9..e43dd1470c 100644 --- a/shared/platform-feature-matrix/features/plugin-backend-run-start.json +++ b/shared/platform-feature-matrix/features/plugin-backend-run-start.json @@ -2,13 +2,15 @@ "id": "plugin-backend-run-start", "area": "扩展", "group": "插件与主题", - "capability": "插件后端发起原生运行:后端经 lithe/host/run/start 让宿主在 Run 窗口运行一个进程(可执行文件来自工具定义 ID 或插件包内文件,工作目录限工作区内,环境变量由插件显式给出并优先于工具导出),支持临时文件(Core 校验并替换 ${temporaryFile:名称},运行结束即删除)、连接式调试(进程监听端口后宿主附加该插件声明的适配器)和再次运行(调用插件声明的函数);lithe/host/run/stop 只停止调用方插件自己的运行或调试会话;运行结束向启动它的后端会话发送 lithe/host/run/didExit。工具 ID 由用户的工具链层级解析,找不到或不可用时返回 plugin.host.toolUnresolved", + "capability": "插件后端发起原生运行:后端经 lithe/host/run/start 让宿主在 Run 窗口运行一个进程(可执行文件来自工具定义 ID 或插件包内文件,工作目录限工作区内,环境变量由插件显式给出并优先于工具导出),支持临时文件(Core 校验并替换 ${temporaryFile:名称},运行结束即删除)、连接式调试(进程监听端口后宿主附加该插件声明的适配器)和再次运行(调用插件声明的函数);lithe/host/run/stop 只停止调用方插件自己的运行或调试会话;运行结束向启动它的后端会话发送 lithe/host/run/didExit。工具 ID 由用户的工具链层级解析,找不到或不可用时返回 plugin.host.toolUnresolved。受信任的远程工作区支持工具 ID 运行,使用远端工作目录、登录环境和私有临时目录,Run 标签标出远端", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", "evidence": [ "desktop/internal/pluginservice/runs.go", "desktop/internal/pluginservice/runs_test.go", + "desktop/internal/pluginservice/remote_runs.go", + "desktop/internal/pluginservice/remote_runs_test.go", "desktop/internal/core/run_start.go", "desktop/internal/core/run_start_test.go", "desktop/internal/workbench/runs.go", @@ -25,6 +27,8 @@ "evidence": [ "desktop/internal/pluginservice/runs.go", "desktop/internal/pluginservice/runs_test.go", + "desktop/internal/pluginservice/remote_runs.go", + "desktop/internal/pluginservice/remote_runs_test.go", "desktop/internal/core/run_start.go", "desktop/internal/core/run_start_test.go", "desktop/internal/workbench/runs.go", @@ -36,7 +40,7 @@ ] }, "owner": "Extensions / Run", - "verification": "macOS:用声明 requires.serverProcess 4 与 permissions run.start 的测试插件,让后端依次发起(1)工具 ID 运行:Run 窗口出现以 label 命名的条目,进程使用用户在设置里选中的安装,参数、工作目录和环境符合请求,插件显式给出的环境变量覆盖工具导出;(2)插件包内可执行文件运行,路径逃出包目录、文件不存在或不可执行时返回 plugin.host.notFound;(3)带 temporaryFiles 的运行,进程内能读到文件内容,结束后临时目录被删除;(4)带 debug.target connection 的运行,进程监听后调试器附加并命中断点,声明 target launch 时宿主不启动进程,由适配器按 targetBindings 启动程序并命中断点,Run 窗口停止该运行会结束调试会话,会话结束后运行条目以退出码结束;(5)带 rerun 的运行,在 Run 窗口点击再次运行会调用插件函数,函数失败时用户看到提示;(6)run/stop 只停止调用方插件的运行,用户点击停止后后端收到不带 exitCode 的 lithe/host/run/didExit,进程自然退出时收到 exitCode。工具未安装时返回 plugin.host.toolUnresolved,details.reason 为 notFound,所选安装不可运行时为 unusable,两种情况都不启动进程。禁用插件或后端退出后,已启动的进程继续运行,后端不再收到通知。远程工作区返回 plugin.host.authorityUnsupported。启动后 app bundle 文件清单不变(scripts/desktop/verify/verify-runtime-bundle-immutability.sh)。Windows:宿主尚未接入 run/start,Core 校验通过不代表 Windows 能运行插件请求的进程。 合成回归验证仅接受一次连接的进程收到适配器的首个连接,并在附加后显示 Debug 窗口。", + "verification": "macOS:用声明 requires.serverProcess 4 与 permissions run.start 的测试插件,让后端依次发起(1)工具 ID 运行:Run 窗口出现以 label 命名的条目,进程使用用户在设置里选中的安装,参数、工作目录和环境符合请求,插件显式给出的环境变量覆盖工具导出;(2)插件包内可执行文件运行,路径逃出包目录、文件不存在或不可执行时返回 plugin.host.notFound;(3)带 temporaryFiles 的运行,进程内能读到文件内容,结束后临时目录被删除;(4)带 debug.target connection 的运行,进程监听后调试器附加并命中断点,声明 target launch 时宿主不启动进程,由适配器按 targetBindings 启动程序并命中断点,Run 窗口停止该运行会结束调试会话,会话结束后运行条目以退出码结束;(5)带 rerun 的运行,在 Run 窗口点击再次运行会调用插件函数,函数失败时用户看到提示;(6)run/stop 只停止调用方插件的运行,用户点击停止后后端收到不带 exitCode 的 lithe/host/run/didExit,进程自然退出时收到 exitCode。工具未安装时返回 plugin.host.toolUnresolved,details.reason 为 notFound,所选安装不可运行时为 unusable,两种情况都不启动进程。禁用插件或后端退出后,已启动的进程继续运行,后端不再收到通知。另连接 Linux 主机,用合成插件在受信任的远程工作区发起工具 ID 运行。确认 Run 标签标出远端,进程在工作区子目录运行,远端登录 PATH 和插件覆盖值正确,二进制临时文件的字节原样交给程序。分别检查正常退出、手动停止、关闭工作区和断线重连时的进程与临时文件回收。未信任时拒绝启动,远端打包可执行文件和调试请求返回 plugin.host.authorityUnsupported。启动后 app bundle 文件清单不变(scripts/desktop/verify/verify-runtime-bundle-immutability.sh)。Windows:用同一流程验证 Windows 桌面端连接 Linux 主机,并验证本地启动和停止。 合成回归验证仅接受一次连接的进程收到适配器的首个连接,并在附加后显示 Debug 窗口。", "notes": "Viva 注册 run/start、run/stop 并在进程结束时发送 run/didExit(只发给发起它的那次后端会话);Core 的 run.decodeStart 校验参数,宿主解析工具或包内可执行文件、写入临时文件、启动进程并把输出放进 Run 窗口中这次运行自己的标签,支持停止与再次运行。debug.target 为 connection 时等待端口打开再附加适配器;target 为 launch 时宿主不启动进程,而是按 configurationType 找到本插件能 launch 的适配器,把解析好的程序、参数、绝对工作目录与环境作为 executable 目标事实交给 Core,经适配器的 launch targetBindings 绑定后启动调试会话;运行条目代表该会话,停止运行即停止会话,会话释放后运行以 terminated 事件的退出码结束(适配器未报时不带 exitCode),进程输出在调试控制台。没有调试能力的宿主仍返回 plugin.host.unavailable。debug/start 已实现(见 plugin-debug-start-and-adapter-features)。原生产品验收仍 pending。 2026-11-13:插件 run/start 的调试附加与启动会按需读取适配器目录,不要求用户先打开 Debug 工具窗口;目录返回后检查调用取消,关闭项目不会启动旧请求。 Run 持有的进程在附加调试会话释放后由后台有界回收,Debug 工具栏停止不再留下暂停的 Run 进程;手动附加的外部进程保持原有所有权。 对宿主启动的连接式调试,宿主通过系统套接字表观察进程树的监听状态,首条连接交给调试适配器。附加后自动打开 Debug 窗口,程序输出保留在 Run 窗口。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", diff --git a/shared/platform-feature-matrix/features/plugin-backend-workspace-context.json b/shared/platform-feature-matrix/features/plugin-backend-workspace-context.json index 41af6c484f..ca4a8b368d 100644 --- a/shared/platform-feature-matrix/features/plugin-backend-workspace-context.json +++ b/shared/platform-feature-matrix/features/plugin-backend-workspace-context.json @@ -2,7 +2,7 @@ "id": "plugin-backend-workspace-context", "area": "扩展", "group": "插件与主题", - "capability": "插件后端 v2 与工作区上下文:requires.backend 2 的后端可由 onWorkspaceOpen 或 onCommand 激活,不依赖网页,启用插件时已有工作区打开即启动;函数协议 3 提供 lithe/host/getCapabilities、subscriptions/dispose、workspace/listContexts|getContext|getFolders,调用带 {contextID, generation},换工作区发新 contextID,rootID 按插件加密钥,远程工作区不暴露路径;宿主错误码各有独立 JSON-RPC 码并可带 details;宿主经 lsp.hostNotify 推送 didChangeContexts、订阅事件和 commands/didRun", + "capability": "插件后端 v2 与工作区上下文:requires.backend 2 的后端可由 onWorkspaceOpen 或 onCommand 激活,不依赖网页,启用插件时已有工作区打开即启动;函数协议 3 提供 lithe/host/getCapabilities、subscriptions/dispose、workspace/listContexts|getContext|getFolders,调用带 {contextID, generation},换工作区发新 contextID,rootID 按插件加密钥;远程上下文给出 Linux 平台,具备 workspace.metadata 且获准调用 workspace/getHostPaths 的插件可按 rootID 查询主机路径;宿主错误码各有独立 JSON-RPC 码并可带 details;宿主经 lsp.hostNotify 推送 didChangeContexts、订阅事件和 commands/didRun", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", @@ -11,7 +11,8 @@ "desktop/internal/pluginservice/contexts.go", "desktop/internal/pluginservice/hostmethods.go", "desktop/internal/pluginservice/hostmethods_test.go", - "desktop/internal/pluginservice/activation.go" + "desktop/internal/pluginservice/activation.go", + "desktop/internal/workbench/remote_workspace_test.go" ] }, "windows": { @@ -22,11 +23,12 @@ "desktop/internal/pluginservice/contexts.go", "desktop/internal/pluginservice/hostmethods.go", "desktop/internal/pluginservice/hostmethods_test.go", - "desktop/internal/pluginservice/activation.go" + "desktop/internal/pluginservice/activation.go", + "desktop/internal/workbench/remote_workspace_test.go" ] }, "owner": "Extensions", - "verification": "共享 Core:cargo test --manifest-path rust/Cargo.toml -p lithe-core,核对 function-protocol.json 的 hostRequests/hostFailures/hostNotifications、v2 清单拒绝 onStartupFinished 与 *、旧宿主拒绝 backend 2、v3 会话第 17 个挂起请求返回 plugin.host.limitExceeded(-32014)、$/cancelRequest 立即返回 -32800 并发布 hostRequestCancelled、details 只以不超过 4 KiB 的对象送到 v3 后端、v2 会话的 lsp.hostNotify 返回 delivered:false。macOS 宿主:scripts/macos/test/test-macos.sh --filter \"PluginHostServiceDispatchTests|MacPluginBackendSessionsTests\"。macOS 原生验收:debug 应用安装一个 backend 2、声明 onWorkspaceOpen 与 workspace.metadata 的示例插件,打开本地工作区后确认后端自动启动、listContexts/getFolders 返回该窗口的根;同一窗口换工作区后收到 didChangeContexts,旧 contextID 得到 plugin.host.contextExpired;执行插件命令后后端收到 commands/didRun;打开远程工作区时 folders 不含 path;关闭窗口、停用插件后用 pgrep 确认后端不残留。", + "verification": "共享 Core:cargo test --manifest-path rust/Cargo.toml -p lithe-core,核对 function-protocol.json 的 hostRequests/hostFailures/hostNotifications、v2 清单拒绝 onStartupFinished 与 *、旧宿主拒绝 backend 2、v3 会话第 17 个挂起请求返回 plugin.host.limitExceeded(-32014)、$/cancelRequest 立即返回 -32800 并发布 hostRequestCancelled、details 只以不超过 4 KiB 的对象送到 v3 后端、v2 会话的 lsp.hostNotify 返回 delivered:false。macOS 宿主:scripts/macos/test/test-macos.sh --filter \"PluginHostServiceDispatchTests|MacPluginBackendSessionsTests\"。macOS 原生验收:debug 应用安装一个 backend 2、声明 onWorkspaceOpen 与 workspace.metadata 的示例插件,打开本地工作区后确认后端自动启动、listContexts/getFolders 返回该窗口的根;同一窗口换工作区后收到 didChangeContexts,旧 contextID 得到 plugin.host.contextExpired;执行插件命令后后端收到 commands/didRun;打开远程工作区时 folders 不含 path,authority.platform 返回实际 Linux 平台;获准调用 workspace/getHostPaths 时返回对应 rootID 的主机路径。同一主机重连保留上下文,主机平台变化会使旧代失效。关闭窗口、停用插件后确认后端不残留。Viva 的元数据与生命周期回归通过 scripts/desktop/desktop-go.sh test ./internal/pluginservice ./internal/workbench 验证;真实 SSH 和 Windows 原生验收待完成。", "notes": "Viva 已按需激活插件后端(onWorkspaceOpen、语言服务器启动、跨插件调用),每个插件一个会话,项目关闭或插件停用时有界停止;已回答 workspace/getContext|listContexts|getFolders 与 didChangeContexts,rootID 按插件加密隔离,状态目录在插件存储下。getCapabilities 由 Core 回答且只列已注册处理器。credentials、documents、editor、window、browser、terminal 与内容提供者已注册(见各自行);run、debug 属其他车道。subscriptions/dispose 由统一资源表处理:会话结束、上下文关闭时释放订阅、内容提供者与终端句柄。commands/didRun 的发送方 Service.NotifyCommandRun 已实现,但 Viva 还没有命令入口(命令面板、右键菜单、插件命令贡献),尚无调用方。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", diff --git a/shared/platform-feature-matrix/features/plugin-host-editor-file-window-services.json b/shared/platform-feature-matrix/features/plugin-host-editor-file-window-services.json index 01d0032ca4..e1915cd31c 100644 --- a/shared/platform-feature-matrix/features/plugin-host-editor-file-window-services.json +++ b/shared/platform-feature-matrix/features/plugin-host-editor-file-window-services.json @@ -8,6 +8,10 @@ "verificationStatus": "pending", "evidence": [ "desktop/internal/pluginservice/hostdocuments.go", + "desktop/internal/pluginservice/hostfiles.go", + "desktop/internal/pluginservice/hostfiles_test.go", + "desktop/internal/pluginservice/hostwatch.go", + "desktop/internal/pluginservice/hostwatch_test.go", "desktop/internal/pluginservice/hostsurface.go", "desktop/internal/pluginservice/hostworkbench_test.go", "desktop/internal/workbench/pluginworkbench.go", @@ -22,6 +26,10 @@ "verificationStatus": "pending", "evidence": [ "desktop/internal/pluginservice/hostdocuments.go", + "desktop/internal/pluginservice/hostfiles.go", + "desktop/internal/pluginservice/hostfiles_test.go", + "desktop/internal/pluginservice/hostwatch.go", + "desktop/internal/pluginservice/hostwatch_test.go", "desktop/internal/pluginservice/hostsurface.go", "desktop/internal/pluginservice/hostworkbench_test.go", "desktop/internal/workbench/pluginworkbench.go", @@ -32,8 +40,8 @@ ] }, "owner": "Extensions", - "verification": "macOS 单测:scripts/macos/test/test-macos.sh --filter \"EditorTextEditPlannerTests|EditorDocumentServiceTests|PluginWorkspaceFileServiceTests|PluginHostEditorServiceTests|PluginHostBrowserServiceTests|PluginHostMessageServiceTests|HTMLPreviewBridgeIsolationTests\";前端:frontend/editor 下运行 plugin-edits.test.ts。服务接入宿主分发、对插件开放后,按计划 §7 用三个验收插件(选区转换器、分页文件浏览器、HTML 预览启动器)在 debug 应用中原生验收:版本冲突与 IME 组字时编辑被拒、撤销一步回退整批编辑;符号链接与 .. 越界被拒、远程工作区返回 authorityUnsupported;后台窗口打开文件不抢焦点、消息限频生效;验收后关闭应用并确认无残留进程。 显式设置 LITHE_PLUGIN_HOST_TEST_NODE 后运行 PluginHostProcessIntegrationTests,验证真实 Node 后端经 Core 请求宿主、编辑 dirty 缓冲区、退出清理及插件包字节不变;scripts/macos/probe/probe-macos-monaco.sh --workbench-tests 验证真实 WebKit 的整批编辑与一次撤销。", - "notes": "Viva 已接通 documents/list|getSnapshot、editor/getActive|getSelections|open|reveal|insertText|replaceSelections|applyEdits、window/showInformation|showWarning|showError、browser/openExternal(仅 http/https URL)。编辑走编辑器自己的撤销栈,整批一步,按 view 修订号做版本隔离,只读/组字/过期版本被拒。editor/open 只落光标(范围起点)。未接通:workspace/readDirectory|stat|readFile|watch|findFiles|findText(需要 workspace.files/search 授权的文件服务)、preview/openHTML(Viva 有系统 Web 视图,但编辑器区还没有嵌入网页的标签)、browser/openExternal 的 resource 形式(返回 unsupportedOption);editor/registerProviders 未接。", + "verification": "macOS 单测:scripts/macos/test/test-macos.sh --filter \"EditorTextEditPlannerTests|EditorDocumentServiceTests|PluginWorkspaceFileServiceTests|PluginHostEditorServiceTests|PluginHostBrowserServiceTests|PluginHostMessageServiceTests|HTMLPreviewBridgeIsolationTests\";前端:frontend/editor 下运行 plugin-edits.test.ts。服务接入宿主分发、对插件开放后,按计划 §7 用三个验收插件(选区转换器、分页文件浏览器、HTML 预览启动器)在 debug 应用中原生验收:版本冲突与 IME 组字时编辑被拒、撤销一步回退整批编辑;远程根目录通过 workspace/readDirectory|stat|readFile 读取,目录分页和 128 KiB 读文件上限生效,禁止沿符号链接或 .. 越界,断开时返回 remoteDisconnected;宿主入口回归由 TestRemotePluginFilesUseTheAuthorizedWorkspaceBinding 与 TestRemoteWorkspaceWatchKeepsSubscriptionOwnershipAcrossAttachments 覆盖;后台窗口打开文件不抢焦点、消息限频生效;验收后关闭应用并确认无残留进程。 显式设置 LITHE_PLUGIN_HOST_TEST_NODE 后运行 PluginHostProcessIntegrationTests,验证真实 Node 后端经 Core 请求宿主、编辑 dirty 缓冲区、退出清理及插件包字节不变;scripts/macos/probe/probe-macos-monaco.sh --workbench-tests 验证真实 WebKit 的整批编辑与一次撤销。", + "notes": "Viva 已接通 documents/list|getSnapshot、editor/getActive|getSelections|open|reveal|insertText|replaceSelections|applyEdits、window/showInformation|showWarning|showError、browser/openExternal(仅 http/https URL)。编辑走编辑器自己的撤销栈,整批一步,按 view 修订号做版本隔离,只读/组字/过期版本被拒。editor/open 只落光标(范围起点)。已接通远程 workspace/readDirectory|stat|readFile,需要 workspace.files.read 授权并通过已绑定的 Core 会话访问远端根目录。远程 workspace/watch|findFiles|findText 已接通。搜索只读磁盘,监听断开重连后要求重扫。本机工作区的文件、搜索和监听待接通;preview/openHTML(Viva 有系统 Web 视图,但编辑器区还没有嵌入网页的标签)、browser/openExternal 的 resource 形式(返回 unsupportedOption);editor/registerProviders 未接。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { diff --git a/shared/platform-feature-matrix/features/plugin-language-server-sessions.json b/shared/platform-feature-matrix/features/plugin-language-server-sessions.json index 72f4529f59..a61c2a6bd4 100644 --- a/shared/platform-feature-matrix/features/plugin-language-server-sessions.json +++ b/shared/platform-feature-matrix/features/plugin-language-server-sessions.json @@ -2,13 +2,15 @@ "id": "plugin-language-server-sessions", "area": "扩展", "group": "插件与主题", - "capability": "插件自有语言服务器会话与后端决定启动方式:声明 languageServers 0 的插件,其后端经 lithe/host/languageServer/request|notify|setStatus 向自己的服务器发请求、通知并上报准备状态(preparing/ready/degraded/failed,随进程结束),收到 didChangeState 与 didReceiveNotification;会话策略(请求白名单、门控、串行命令、超时与排队上限、远程不支持)由 Rust Core 执行;launch.kind:backend 由后端函数在每次启动时给出可执行文件(包内文件或声明的工具)、参数、环境与初始化选项,Core 校验后宿主才启动;documents.contentProvider 让插件为自定义 scheme 提供只读文档(如 jar 内源码);宿主按 state.retention 在后台回收每个工作区的服务器状态目录;状态栏显示插件自己上报的准备状态;宿主在 resolveParams.tools 中提供声明工具的所选安装事实,使语言服务器与 Build/Run 使用同一项目工具链;工具入口计划经原生路径校验后复用 Core 的工具模板实例化,保留包入口、运行时参数与工具定义的参数顺序", + "capability": "插件自有语言服务器会话与后端决定启动方式:声明 languageServers 0 的插件,其后端经 lithe/host/languageServer/request|notify|setStatus 向自己的服务器发请求、通知并上报准备状态(preparing/ready/degraded/failed,随进程结束),收到 didChangeState 与 didReceiveNotification;会话策略(请求白名单、门控、串行命令、超时与排队上限)由 Rust Core 执行;launch.kind:backend 由后端函数在每次启动时给出可执行文件(包内文件或声明的工具)、参数、环境与初始化选项,Core 校验后宿主才启动;documents.contentProvider 让插件为自定义 scheme 提供只读文档(如 jar 内源码);宿主按 state.retention 在后台回收每个工作区的服务器状态目录;状态栏显示插件自己上报的准备状态;宿主在 resolveParams.tools 中提供声明工具的所选安装事实,使语言服务器与 Build/Run 使用同一项目工具链;工具入口计划经原生路径校验后复用 Core 的工具模板实例化,保留包入口、运行时参数与工具定义的参数顺序", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", "evidence": [ "desktop/internal/pluginservice/backendlaunch.go", + "desktop/internal/workbench/remote_plugin_variant_ssh_test.go", "desktop/internal/pluginservice/languagesession.go", + "desktop/internal/pluginservice/settings_start_test.go", "desktop/internal/pluginservice/hostmethods.go", "desktop/internal/pluginservice/hostmethods_test.go", ".agents/notes/implemented/architecture/2026-11-10-viva-plugin-host-services-and-backend-sessions.md", @@ -25,6 +27,7 @@ "evidence": [ "desktop/internal/pluginservice/backendlaunch.go", "desktop/internal/pluginservice/languagesession.go", + "desktop/internal/pluginservice/settings_start_test.go", "desktop/internal/pluginservice/hostmethods.go", "desktop/internal/pluginservice/hostmethods_test.go", ".agents/notes/implemented/architecture/2026-11-10-viva-plugin-host-services-and-backend-sessions.md", @@ -32,12 +35,13 @@ "desktop/internal/pluginbackend/pluginbackend.go", "desktop/internal/pluginbackend/pluginbackend_test.go", "desktop/internal/pluginhost/launch.go", - "desktop/internal/pluginhost/launch_test.go" + "desktop/internal/pluginhost/launch_test.go", + "desktop/internal/workbench/remote_plugin_variant_ssh_test.go" ] }, "owner": "Extensions", - "verification": "Viva:scripts/desktop/desktop-go.sh test ./internal/pluginservice -run TestLanguageLaunch -count=1,验证所选安装、可选缺失、项目脚本排除与实际错误传播。两平台另行验证原生窗口中的后端启动、请求/通知、准备状态、只读虚拟文档、关闭项目后的进程释放;远程工作区与状态保留清理未实现,不视为已验收。scripts/desktop/verify/verify-runtime-bundle-immutability.sh 检查资源只读边界。 TestToolEntryUsesCoreInstantiationAfterNativeVerification 读取链接 Core 的非 Java 工具 fixture,验证通用入口模板;TestToolEntryIsVerifiedInsideThePackage 拒绝越界入口。", - "notes": "Viva 通过后端函数解析语言服务器启动,Core 校验计划与会话权限,宿主提供所选工具的 executable/home/version,不传环境或凭据,也不把项目脚本当作本地安装。可选工具缺失时保留服务器自己的配置,实际读取失败交给既有启动失败边界。通用逻辑不识别 Java 或其他工具名。远程工作区、状态保留清理及完整原生窗口验收仍有缺口;无头测试不能据此标记全部平台验证完成。", + "verification": "Viva:scripts/desktop/desktop-go.sh test ./internal/pluginservice -run TestLanguageLaunch -count=1,验证所选安装、可选缺失、项目脚本排除与实际错误传播。两平台另行验证原生窗口中的后端启动、请求/通知、准备状态、只读虚拟文档、关闭项目后的进程释放;TestRemoteLanguageServerUsesTheWorkspaceHostAndItsSettings 验证远端系统命令启动规划、项目设置读取和重连后的旧结果隔离。TestEditorDeploysPackagedLanguageServerToLinuxX64OverSSH 在 macOS arm64 和 Windows x64(ARM64 来宾内仿真)经 SSH 连接 Linux x86_64 仿真来宾,验证同版本变体选型、文件哈希和执行权限,以及编辑器收到远端诊断。两平台原生窗口及状态保留清理仍待验收。scripts/desktop/verify/verify-runtime-bundle-immutability.sh 检查资源只读边界。 TestToolEntryUsesCoreInstantiationAfterNativeVerification 读取链接 Core 的非 Java 工具 fixture,验证通用入口模板;TestToolEntryIsVerifiedInsideThePackage 拒绝越界入口。", + "notes": "Viva 通过后端函数解析语言服务器启动,Core 校验计划与会话权限,宿主提供所选工具的 executable/home/version,不传环境或凭据,也不把项目脚本当作本地安装。可选工具缺失时保留服务器自己的配置,实际读取失败交给既有启动失败边界。通用逻辑不识别 Java 或其他工具名。声明支持远程的 systemCommand 语言服务器由工作区主机启动,客户端读取全局设置,工作区主机提供项目设置。远程后端解析启动可以返回已声明的系统工具,由 Core 在远端选定安装并启动。包内程序通过已批准的同版本目标平台包部署,远端托管运行时安装到用户的私有运行目录。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { diff --git a/shared/platform-feature-matrix/features/plugin-managed-runtimes.json b/shared/platform-feature-matrix/features/plugin-managed-runtimes.json index 54b23c8a60..c545ed3abc 100644 --- a/shared/platform-feature-matrix/features/plugin-managed-runtimes.json +++ b/shared/platform-feature-matrix/features/plugin-managed-runtimes.json @@ -26,7 +26,8 @@ "desktop/internal/pluginservice/runtime_trust_test.go", "desktop/internal/toolchain/", "desktop/internal/toolchain/toolchain.go", - "desktop/internal/toolchain/load.go" + "desktop/internal/toolchain/load.go", + "desktop/internal/workbench/remote_plugin_variant_ssh_test.go" ] }, "windows": { @@ -35,7 +36,7 @@ "evidence": [ "desktop/internal/core/managed_runtimes.go", "desktop/internal/pluginruntime/", - "desktop/internal/pluginruntime/lock_windows.go", + "desktop/internal/filelock/lock_windows.go", "desktop/internal/pluginservice/runtimes.go", "desktop/internal/pluginservice/runtime_lifecycle.go", "desktop/internal/pluginbackend/pluginbackend_test.go", @@ -50,11 +51,12 @@ "desktop/internal/pluginservice/runtime_trust_test.go", "desktop/internal/toolchain/", "desktop/internal/toolchain/toolchain.go", - "desktop/internal/toolchain/load.go" + "desktop/internal/toolchain/load.go", + "desktop/internal/workbench/remote_plugin_variant_ssh_test.go" ] }, "owner": "Plugins", - "verification": "合成插件测试通过真实 Core 清单与回复校验,使用本地传输夹具验证外部安装零下载、仅下载缺失项、插件版本变化不重复下载、缓存破损从已校验归档恢复、哈希与解压路径拒绝、并发和取消、失败不改旧目录以及准备后端不参与函数转发;验证无后端探测即可汇总受管工具与未绑定依赖到工具链设置视图,并可在缺失时按需触发准备、就绪后触发校验修复。使用合成可执行文件验证当前与其他已打开项目的 PATH、全局符号链接和检查函数返回路径不会绕过工具信任;绑定工具保持 Core 验证的规范文件与目录身份,工作区关闭后释放根引用。运行 desktop-go.sh test ./internal/toolchain/ ./internal/pluginservice/ ./internal/settingswindow/ ./internal/workbench/ 覆盖绑定/未绑定受管依赖投影与准备按钮。macOS 与 Windows 真机仍保留 pending 状态以完成完整安装与原生流程验收。", + "verification": "合成插件测试通过真实 Core 清单与回复校验,使用本地传输夹具验证外部安装零下载、仅下载缺失项、插件版本变化不重复下载、缓存破损从已校验归档恢复、哈希与解压路径拒绝、并发和取消、失败不改旧目录以及准备后端不参与函数转发;验证无后端探测即可汇总受管工具与未绑定依赖到工具链设置视图,并可在缺失时按需触发准备、就绪后触发校验修复。使用合成可执行文件验证当前与其他已打开项目的 PATH、全局符号链接和检查函数返回路径不会绕过工具信任;绑定工具保持 Core 验证的规范文件与目录身份,工作区关闭后释放根引用。运行 desktop-go.sh test ./internal/toolchain/ ./internal/pluginservice/ ./internal/settingswindow/ ./internal/workbench/ 覆盖绑定/未绑定受管依赖投影与准备按钮。macOS 与 Windows 真机仍保留 pending 状态以完成完整安装与原生流程验收。 TestEditorDeploysPackagedLanguageServerToLinuxX64OverSSH 已在 macOS arm64 和 Windows x64(ARM64 来宾内仿真)验证按目标平台下发托管运行时,并由远端语言服务器启动后向编辑器投递诊断。", "notes": "通用能力 managedRuntimes 0/1 和权限 runtimes.install;清单、归档选择、缓存键及结果完整性由独立 Core 仓库定义,插件检查版本与目录是否合用。状态在 /.state//runtimes/,与插件版本分开;旧插件不进入新流程。安装与更新不再阻塞下载受管依赖,改为在工具链“插件自用运行时”页按需准备/修复或在语言服务器首次启动前自动准备。平台实现共用 Go/Viva 服务,Windows 使用本机文件锁和可执行文件验证,实机验证状态独立保留为 pending。", "lastReviewed": "2026-11-19" } diff --git a/shared/platform-feature-matrix/features/plugin-native-terminals.json b/shared/platform-feature-matrix/features/plugin-native-terminals.json index 37249e6e26..597ca871ad 100644 --- a/shared/platform-feature-matrix/features/plugin-native-terminals.json +++ b/shared/platform-feature-matrix/features/plugin-native-terminals.json @@ -11,7 +11,8 @@ "desktop/internal/pluginservice/hostworkbench_test.go", "desktop/internal/workbench/pluginterminals.go", "desktop/internal/workbench/pluginworkbench_test.go", - "desktop/internal/termview/pluginterm_test.go" + "desktop/internal/termview/pluginterm_test.go", + "desktop/internal/workbench/remote_terminal_test.go" ] }, "windows": { @@ -22,12 +23,13 @@ "desktop/internal/pluginservice/hostworkbench_test.go", "desktop/internal/workbench/pluginterminals.go", "desktop/internal/workbench/pluginworkbench_test.go", - "desktop/internal/termview/pluginterm_test.go" + "desktop/internal/termview/pluginterm_test.go", + "desktop/internal/workbench/remote_terminal_test.go" ] }, "owner": "Extensions / Terminal", - "verification": "运行 PluginTerminalHostServiceTests、PluginTerminalNativeTests 与 TerminalModuleTests:权限和归属、argv 原样、远程拒绝、取消和工作区关闭、真实 PTY create/close/reopen、UTF-8 历史字节预算、只恢复显示而不重放输入、dispose 释放及迟到 generation 隔离。在测试内联的合成插件中核对本窗口终端标签、焦点、输入、Ctrl-C、缩放、用户关标签重开、插件停用与退出无残留进程;完成整机验收后再更新 verified。三个官方 SDK 在 Lithe-core-rust 的 shared/plugins/sdk 验证。 回归验证 show:false 创建/重开保留已有活动终端;用户关标签与自然退出后,在退出通知前释放原生会话和完整渲染缓冲区,按 0/8 字节保留历史;长参数和工作目录可完整滚动、选择、复制,取消确认不启动终端。 本次在 Swift 6.3.3 + macOS 26.5 SDK 下运行 75 项相关 Swift 测试全部通过(含四种真实 PTY 退出释放场景);HTML/JUnit 逐项计时在 .artifacts/test-stability/plugin-terminal-review-fixes.*。使用合成插件的 GUI 验收仍 pending。", - "notes": "Viva 已实现 terminal/create|show|close|reopen|dispose|onExit:用户同意(精确程序、argv、目录)后在 Terminal 工具窗口里启动,与用户终端同一面板;每个插件最多 8 个句柄,按会话/工作区上下文归属,close 保留有界纯文本快照,reopen 起新进程并把快照画在上方(不写入输入),exit 事件按 generation 只发一次。环境变量 null 通过 localshell.Config.Unset 移除。未做:Windows 与 Linux 上的真实终端未验证,GUI 验收 pending。", + "verification": "在 macOS 和 Windows 运行桌面端的 TestTerminalLifecycle、TestPluginTerminalReportsItsExit、TestClosingAPluginTerminalRecordsClosedWithTheBudget 和 TestRemotePluginTerminalRequiresFreshConsentAndRunsOnTheHost。核对 argv、工作目录、环境变量、拒绝未信任项目、重连后拒绝使用旧确认及关闭远端 PTY。再用受信任的真实 SSH 项目验证插件终端创建、重开、Ctrl-C、缩放和关闭后进程回收。", + "notes": "Viva 已实现 terminal/create|show|close|reopen|dispose|onExit:用户同意(精确程序、argv、目录)后在 Terminal 工具窗口里启动,与用户终端同一面板;每个插件最多 8 个句柄,按会话/工作区上下文归属,close 保留有界纯文本快照,reopen 起新进程并把快照画在上方(不写入输入),exit 事件按 generation 只发一次。环境变量 null 通过 localshell.Config.Unset 移除。未做:Windows 与 Linux 上的真实终端未验证,GUI 验收 pending。 受信任的远程项目可启动插件原生终端,确认框显示连接名与远端工作目录,远端按项目根目录校验相对路径。重连后原确认失效。真实 SSH 终端验收仍 pending。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { diff --git a/shared/platform-feature-matrix/features/remote-development-workspace.json b/shared/platform-feature-matrix/features/remote-development-workspace.json index b164e7f0ab..401548e965 100644 --- a/shared/platform-feature-matrix/features/remote-development-workspace.json +++ b/shared/platform-feature-matrix/features/remote-development-workspace.json @@ -2,23 +2,53 @@ "id": "remote-development-workspace", "area": "工作区", "group": "远程开发", - "capability": "在 SSH 主机、容器和远程 Mac 上打开并开发项目", + "capability": "在 Linux SSH 主机、WSL 发行版和 Linux 容器中打开并开发项目 远端原生设置支持 sourceSettings 2,通过插件声明的远端程序读回非敏感字段,显示连接和写入目标,经确认后在远端项目或用户目录条件写入并回读。", "macos": { - "implementationStatus": "missing", - "verificationStatus": "not-applicable", + "implementationStatus": "partial", + "verificationStatus": "pending", "evidence": [ - "docs/viva-migration.md" + "desktop/internal/pluginservice/remote_deployment.go", + "desktop/internal/pluginservice/lifecycle_test.go", + "desktop/internal/workbench/remote_plugin_variant_ssh_test.go", + "desktop/internal/core/remote_plugin.go", + "desktop/internal/workbench/remote_workspace.go", + "desktop/internal/workbench/remote_workspace_test.go", + "desktop/internal/workbench/debug_remote_transport.go", + "desktop/internal/pluginservice/remote_runtimes.go", + "desktop/internal/workbench/debug_remote_terminal_test.go", + "desktop/internal/workbench/debug_stdio_ssh_test.go", + "desktop/internal/workbench/remote_native_settings_ssh_test.go", + "desktop/internal/workbench/debug_tunnel_ssh_test.go", + "desktop/internal/workbench/settings_plugin_sources.go", + "desktop/internal/pluginservice/remote_settings.go", + "desktop/internal/pluginsettings/remote_sources.go", + "desktop/internal/settingswindow/source_settings_view.go" ] }, "windows": { - "implementationStatus": "missing", - "verificationStatus": "not-applicable", + "implementationStatus": "partial", + "verificationStatus": "pending", "evidence": [ - "docs/viva-migration.md" + "desktop/internal/pluginservice/remote_deployment.go", + "desktop/internal/pluginservice/lifecycle_test.go", + "desktop/internal/core/remote_plugin.go", + "desktop/internal/workbench/remote_workspace.go", + "desktop/internal/workbench/remote_workspace_test.go", + "desktop/internal/workbench/debug_remote_transport.go", + "desktop/internal/pluginservice/remote_runtimes.go", + "desktop/internal/workbench/debug_remote_terminal_test.go", + "desktop/internal/workbench/debug_stdio_ssh_test.go", + "desktop/internal/workbench/remote_native_settings_ssh_test.go", + "desktop/internal/workbench/debug_tunnel_ssh_test.go", + "desktop/internal/workbench/remote_plugin_variant_ssh_test.go", + "desktop/internal/workbench/settings_plugin_sources.go", + "desktop/internal/pluginservice/remote_settings.go", + "desktop/internal/pluginsettings/remote_sources.go", + "desktop/internal/settingswindow/source_settings_view.go" ] }, "owner": "Workspace", - "verification": "欢迎页点“远程开发”:新建 Linux SSH 连接,分别验证 SSH Agent、私钥、密码和 2FA,核对主机信息卡片;打开项目后验证文件树、编辑保存和外部修改冲突。在远程终端运行 pwd,检查真实主机目录;探测 Shell,确认仅出现远端可执行程序,连续缩放与取消启动无残留进程。刷新工具链,确认读取远端环境且断线不回退本机。在远端仓库验证状态、暂存、提交、历史分页和 Git 设置来源;检查选择文件提交保留无关暂存,未保存缓冲区的行历史正确,worktree 创建、列举、锁定、删除及克隆均只操作远端目录;Shift+Shift 搜索远端文件与内容。Core 远端文件装入内存不超过 32 MiB,原子写入不超过 8 MiB,超限和断线均明确失败且不覆盖现有内容;更大的 Git 临时内容尚不支持。上述 I/O 路径已有适配和隔离 fixture,真实 SSH 完整流程待验收;构建 I/O、工具解析、状态目录、插件资源部署和通用 stdio 提供者接入已有实现;真实 SSH 上的完整构建和插件启动尚未验收。Agent 执行位置选择、远端服务强制终止后的快照安全回收、远程 Mac 和容器入口仍待完成。运行 scripts/remote/verify-remote-workspace.sh、RemoteRuntimeDiscoveryTests、RemoteTerminalTransportTests、RemoteShellDiscoveryTests 和 Core remote::sessions 集成测试。Linux musl 两种架构服务由 scripts/desktop/build-remote-server.sh 编译,scripts/desktop/verify/verify-remote-server-artifacts.mjs 检查清单、哈希、ELF 架构与静态链接;CI 在 x86_64 与 arm64 runner 上用 --require-smoke <目标> --require-pinned 分别原生运行同一份产物的 --identity、--version 和 server.hello 冒烟,不用模拟器;体积由 CI 记录在任务摘要中,不设硬上限(#2231 的 D9)。Release 与 AutoBuild 调用同一个 desktop-remote-server.yml,package-desktop.sh 把这份已冒烟的产物以 lithe_bundled_remote_server 嵌入客户端;desktop/internal/remoteserver 按嵌入清单校验后安装到用户缓存目录(0600,字节相同不重写),不写安装目录,由 package-desktop.test.mjs 与 remoteserver 测试覆盖。远程开发窗口与 Open 面板在 800×650 父窗口中验证信息换行、架构标签、底部按钮和编辑期间尺寸稳定。 文件树新建、目录、复制、重命名与主机废纸篓已接入,14 项 Swift 路由/监听 fixture 通过;真实 SSH 验证外部创建、编辑、移动、删除、溢出重扫和 watcher 取消后无资源残留。 RemoteBuildExecutionTests、RemotePluginDeploymentTests 与 MacBuildProviderSessionsTests 覆盖字节/参数保留、信号和错误、上传完整性、原连接清理、异步准备及迟到启动;补充真实 SSH stdio 顺序、断线、背压与取消后再更新验证状态。 通用资源启动在读取请求时预留身份,启动期间的关闭由创建者保留最终清理责任;验证清理早于注册、工作线程饱和、失败启动、无效关闭参数,以及不同资源独立性;区分常驻会话断线保留、非驻留断线清理和会话关闭/空闲到期后的迟到资源清理。RemotePluginLaunchPreparerTests 使用真实声明覆盖目标架构、远端状态目录、缺失资源、准备中重连和取消清理;本机 fixture 不替代 SSH/Linux 验收。语言和工具专属集成由各插件负责,不在本能力范围。 会话拥有完整插件快照:验证分配回复丢失后按原身份释放、重复释放不接管已有目录、跨会话隔离、父目录权限与链接拒绝、删除失败(包括等待创建者清理)保留原身份供重试、普通断线清理、常驻断线保留及关闭/空闲到期回收;服务端强杀后的回收仍未实现。上传验证同文件并发 BUSY、不同文件独立提交,以及取消/到期不等待文件锁。Agent 后续单独处理,本轮不扩展。 远端子目录与符号链接根:验证发现父仓库后,仅用返回 URL 查询状态和暂存仍选择原连接;同名本机哨兵仓库的索引和文件保持不变,同一远端路径在不同连接上隔离;外部 Git 元数据监听的订阅与事件使用同一可逆身份。 运行配置发现与生成(runConfig.inspect 等)尚未接入远程工作区,Core 对它们返回 NotSupported,不得把本机扫描结果当作远端项目。共享运行扫描的远程契约由 Core 集成测试 shared_run_scan_reads_the_host_tree_and_stops_when_the_link_drops 覆盖:读取主机目录树且占位目录保持为空、主机报告的单目录错误记为扫描不完整、链路中断时整体失败而不发布截断结果。运行准备与测试发现复用远程构建的状态租约(BuildSystemService.withPlanContext),真实 SSH 上的验收仍待完成。 macOS 远程开发主面板经 LitheCenteredPopup 有标题表单入口居中无动画打开,复用统一窗口外框;取消、保存成功、关闭窗口复位呈现状态并清理任务。输入框和按钮样式不变,内部认证/目录浏览 sheet 保留。运行 LitheCenteredPopupTests、RemoteConnectionsTests 和 RemoteWorkspaceRoutingTests;人工验证欢迎页和菜单入口。", + "verification": "在 Viva 欢迎页打开“远程开发”,分别连接 Linux SSH 主机、Windows 上的 WSL 发行版和 Linux 容器。打开项目后验证文件树、编辑保存与冲突提示、外部修改监听、搜索、Git、远端终端和断线重连。安全模式下验证构建、运行、调试和插件进程被拒绝,断线后验证请求不会操作本机占位目录。使用合成插件验证远端平台与工作区路径查询、宿主文件和终端调用,以及构建和测试命令运行在远端。远端 stdio 调试验证断点、调用栈跳转和远端终端,TCP 路径验证本机适配器经 SSH 隧道附加并在结束时释放转发。从 macOS arm64 连接 Linux x86_64,验证按已批准的版本选择插件包、下发语言服务器和托管运行时、编辑器收到诊断、相同产物复用,以及升级或卸载后在下次连接回收无租约的远端旧版本。桌面回归测试核对清单只保留每个插件的当前版本(包含已禁用插件),本机仍保留回滚包。Core 集成测试覆盖活跃租约保护及服务强制退出后回收废弃暂存目录。合成插件的真实 SSH 测试已在 macOS arm64 和 Windows x64(ARM64 来宾内仿真)验证 Linux x86_64 的变体与运行时下发、诊断投递及本机调试适配器附加后的转发清理。Release 与 AutoBuild 对两种架构的 Linux 服务做原生冒烟后嵌入客户端;连接和上载流程使用用户缓存与主机私有目录,检查 macOS app bundle 和 Windows 安装目录保持只读。 #2231:分别在远端项目目录和用户目录读取配置,检查保存确认中的连接及文件路径。验证取消、文件被其他进程改写、重新连接和写入后回读;客户端本地源文件保持原样。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { @@ -68,5 +98,5 @@ "verificationStatus": "not-applicable" } }, - "notes": "Viva:未找到 SSH、容器或远程 Mac 的远程开发入口、远程文件、远程 Git 或远端工具链探测实现;localshell/shell.go 只在注释中提及 sshconn.Shell,desktop/ 中没有对应包。" + "notes": "Viva 已接入 SSH 与 Windows 上的 WSL。macOS arm64 已经通过 SSH 至 Linux arm64 验证文件上传与完整性校验,并通过 SSH 至 Linux x86_64 仿真来宾验证自动部署合成语言服务器和托管运行时,以及经隧道附加。Windows x64 桌面测试在 ARM64 来宾内经 SSH 连接 Linux arm64,覆盖远端 stdio 调试、SSH 隧道附加、从运行配置和构建目标调试服务,以及读写远端原生设置。Windows 原生界面、容器完整流程和真实 SSH 环境下的强制退出回收仍待验收。" } diff --git a/shared/platform-feature-matrix/features/remote-workspace.json b/shared/platform-feature-matrix/features/remote-workspace.json index 1a9f74081c..a709f0ef10 100644 --- a/shared/platform-feature-matrix/features/remote-workspace.json +++ b/shared/platform-feature-matrix/features/remote-workspace.json @@ -82,7 +82,9 @@ "desktop/internal/workbench/remote_devcontainer_test.go", "desktop/internal/workbench/remote_worktree.go", "desktop/internal/workbench/remote_worktree_test.go", - "desktop/internal/workbench/remote_worktree_visual_test.go" + "desktop/internal/workbench/remote_worktree_visual_test.go", + "desktop/internal/pluginservice/remote_deployment.go", + "desktop/internal/core/remote_plugin.go" ] }, "windows": { @@ -138,11 +140,13 @@ "desktop/internal/workbench/remote_devcontainer.go", "desktop/internal/workbench/remote_worktree.go", "desktop/internal/workbench/remote_worktree_test.go", - "desktop/internal/workbench/remote_worktree_visual_test.go" + "desktop/internal/workbench/remote_worktree_visual_test.go", + "desktop/internal/pluginservice/remote_deployment.go", + "desktop/internal/core/remote_plugin.go" ] }, "owner": "Remote", - "verification": "在“远程开发”窗口选中已保存的 Linux SSH 连接点“连接”:SSH 询问出现在窗口中,连接后窗口改为主机的文件夹选择,从主目录开始列出子文件夹(跳过名称不是 UTF-8 的条目并说明数量),可输入 ~ 或 / 开头的路径跳转,不存在的路径说明原因且不能打开;“返回”断开这次会话回到连接表单。选中文件夹点“打开”:新标签页打开远程工作区,窗口标题为“文件夹 [SSH: 连接名]”,项目树经 Core 列出主机目录(本机占位目录始终为空),右键只有复制主机路径和刷新;以安全模式打开的文件夹,编辑器上方说明可以浏览、编辑、保存和搜索主机文件,信任文件夹后才能用 Git;受信任的文件夹说明文件、终端和 Git 都在主机上,运行、调试和语言服务器暂不可用;空白编辑区提示 Search Everywhere 和 Find in Files。在项目树双击文件:编辑器经会话读取主机文件(不超过 16 MiB),保存时带上打开时的大小和修改时间写回主机,新建的文件只在主机上不存在时创建;主机上的文件期间被别人改过时保存被拒绝并显示外部修改冲突,“加载磁盘版本”载入主机内容,本机占位目录始终为空。超过 8 MiB 的保存说明主机单次保存上限,编辑内容保留;主机上缺失、无权限、不是普通文件、超时和连接断开分别说明原因,连接断开后自动重连并把打开的文档和主机重新比对。图片、PDF 等查看器、本地历史和插件终端都被拒绝并提示,不回退到本机;在文件浏览器中显示(标签页右键、Search Everywhere 结果、Git 变更)在远程工作区里不提供。状态栏连接菜单的“打开主机上的文件…”(未连接时不可用)从窗口顶部弹出路径框,默认 ~/,经 remote.readDir 列出路径最后一个“/”之前的文件夹,按其后的文字(不分大小写)筛选名称开头,文件夹在前,以“.”开头时才列出隐藏条目,无法读取的条目说明数量;上下键移动、Tab 补全名称、回车进入文件夹或打开文件,没有匹配时回车按输入的路径打开,Esc 或点外面关闭;不以 / 或 ~/ 开头的输入说明要输入什么,名称含“\\”的路径说明在 Windows 上无法打开。工作区文件夹里的文件与项目树打开的相同、可以编辑;文件夹以外的文件(对标 Zed)在占位目录旁的 .lithe-remote-host 下以只读方式打开(S25):不能切换为可编辑(提示原因并记为拒绝),保存和新建都被拒绝并说明原因、不写主机,状态栏导航路径显示 ~ 开头的主机路径,复制相对路径不提供;重连和关闭前与其他文档一样和主机比对,主机上的改动在没有编辑时重新载入(主机监听只覆盖工作区文件夹)。日志只记 remote_open_host_file、remote_read_dir、toggle_read_only 等操作名和原因,不含主机路径。打开“终端”工具窗口:经会话的 remote.runTerminal 在主机文件夹运行主机账户的登录 shell(不带参数,不读本机 Shell 设置,没有本机 Shell 菜单),标签名为连接名,之后的标签为“连接名 (2)”等;输入按顺序、每块不超过 32 KiB 写入,主机说忙时稍后重试,窗口尺寸随输入发送;输出超过 8 MiB 未显示时丢弃最旧的部分并记一次失败。程序退出显示退出码,被信号结束显示 128+信号,关闭标签不算失败。连接断开时终端显示会话已结束,工作区按退避重连;未连接时按回车说明工作区未连接,重连后按回车在新会话上运行。终端起不来时显示 Core 给出的原因(可能含主机路径),日志只记命令名和错误码。拖到终端的文件粘贴为主机路径并按 POSIX shell 加引号,本机工作区外的文件不粘贴并提示原因;粘贴图片不可用(图片会存到本机)。每个会话连接后,经 remote.runWatch 在主机上递归监听整个文件夹,跳过已启用插件隐藏的文件夹名(按原样比较大小写),插件改变隐藏名称时重新开始监听;在主机上新建、修改、删除文件后,项目树重新列出受影响的目录(Core 的 workspace.filterChanges 按可见性规则过滤,不需要会话),打开的文档与主机比对:没有编辑的重新载入,有编辑的显示外部修改冲突;文件夹外和被隐藏文件夹里的变化不触发列表。监听开始时、主机丢失变化(overflow)时、一次超过 4096 个变化时,重新列出树中展开的目录并比对所有文档,日志每次监听各记一次;主机监听数用尽时其余部分继续监听,提示一次“项目文件可能无法自动更新”。监听中文件夹被删除或移走时立即重新监听;主机找不到文件夹时项目树显示根目录不可用,监听等树重新列出文件夹后再开始,主机与树结论不一致时也只等待、不反复重试。其他监听失败只记命令名和错误码、提示一次,等下一个会话再开始;监听发现连接断开时与心跳一样结束会话并重连。Find in Files 的搜索、计数和替换预览带远程绑定发送,Core 从主机文件夹建立索引并读取主机上的当前内容,结果路径相对主机文件夹;点结果在远程编辑器打开主机文件并定位到匹配处,本机占位目录始终为空。主机监听报告的变化路径在下一次查询前增量更新索引,不重建;监听开始和主机丢失变化时重建一次。包含生成文件的查询每次都重建索引(主机监听跳过插件隐藏的文件夹);主机监听数用尽后、会话断开到下一个会话的监听开始之间,每次查询都重建,只由监听提示一次“项目文件可能无法自动更新”,搜索不再另外提示。查询显示期间主机上的变化让结果重新查询。Search Everywhere 所有页签都可用,文件名和文本来自主机,打开弹窗时重新读取生成文件的名称;远程工作区不启动语言服务器,符号只有 Core 在主机文件中找到的。Replace All 在编辑器中替换打开的文档;未打开的文件经会话读取主机内容,由 Core 替换后,只在主机文件仍是读取时的内容时写回,期间被改过的报告冲突,已被删除的说明主机上找不到文件,其余文件照常替换,都不写本机占位目录。在文件夹选择中打开从未决定过的文件夹:先询问是否信任(显示连接名和主机文件夹,Core 给出上级文件夹时可勾选信任其下的所有文件夹),“信任并打开”把决定按连接名记入 Core 的远程信任记录后以受信任方式打开,“以安全模式打开”只读打开,“返回”回到文件夹选择;之前决定过的文件夹直接按记录打开。安全模式下 Git、提交和日志窗口与本机项目一样说明需要信任,编辑器上方的提示里可以信任文件夹,信任后不重开窗口就在主机上启动 Git。受信任的工作区经会话在主机上运行 Git:状态、暂存、提交、差异(含编辑器行号旁的变更标记)、日志与分支、逐行追溯(读取主机上的文件内容)、搁置与储藏都读写主机仓库,本机占位目录始终没有 .git;“排除到本地”写入主机仓库的 info/exclude(缺少 info 文件夹时在主机上创建,读写期间文件被别人改过时这次排除失败、不覆盖)。同一会话经 remote.runWatch 递归监听主机仓库的 git 目录(公共目录在别处时一并监听),主机上 git checkout、commit 等改动元数据后按路径分类并重新读取状态;监听开始、丢失变化或主机监听数用尽时重新读取一次完整状态,新会话重新开始监听。主机文件夹位于上级目录开始的仓库内时,Git 和提交窗口说明要打开仓库顶层文件夹,不显示变更也不记为失败。工作树列表、锁定、解锁、删除在主机上执行,列表和详情显示主机路径,复制路径复制主机路径。打开关联工作树时“远程开发”窗口打开,用打开工作区所用的连接(或 WSL 发行版)再连一次,显示连接步骤和 OpenSSH 的询问,从未决定过的文件夹先询问是否信任,然后在本窗口的新标签页经一个新会话打开该主机文件夹;再次打开时切到已打开的标签页,不再连接;连接在工作区打开后被删除时窗口说明原因、不连接。新建工作树对话框把 Core 在仓库旁的建议显示为主机路径(如 /home/dev/project-topic),输入框下说明路径是主机上的文件夹、由主机上的 Git 创建;输入的其他主机路径原样保留,“创建”在工作区会话上由主机上的 Git 创建并选中新工作树,“创建后打开”同样经新会话在新标签页打开。在新窗口打开和在文件浏览器中显示仍被拒绝并提示。受信任的远程工作区里运行、调试、当前文件运行、测试、构建任务和插件语言服务器都不在本机启动,都记为拒绝并提示,运行、测试和构建工具窗口说明暂不可用。状态栏前端显示连接名和心跳往返时间;连续两次心跳无响应显示“无响应”,第三次结束会话并按 Core 由“自动重连时长”给出的间隔重连(默认 1、2、4、8、16、29 秒,共 60 秒),每次失败后等下一个间隔,用完后显示“已断开”和原因,菜单里可“重新连接”;连接被关闭时同样按这些间隔重连;时长设为“不自动重连”时直接显示“已断开”。关闭窗口、退出 Lithe、菜单里“断开并关闭”和切换工作区时,先经 remote.runningPrograms 读取主机上 Lithe 为这个工作区启动的进程和终端;没有时直接结束会话,有时询问“关闭远程工作区?”,正文写明连接名并逐项列出类型(终端、进程)、名称、命令(原样显示,不脱敏)和已运行时长,按钮为“结束并关闭”(默认)、“保留在远端并关闭”和“取消”,“记住我的选择”旁的 ⓘ 说明之后不再询问、只能在 设置 › 工具 › 远程工作区 修改。“取消”保留窗口和会话;“结束并关闭”经 remote.disconnect 结束主机会话;“保留在远端并关闭”让主机保留会话,把恢复凭据按连接存入系统密钥存储后通知“N 个进程保留在 <连接名> 上”,凭据存不下时改为结束并说明原因,主机拒绝保留时同样结束并说明;读取进程列表失败时不询问、照常结束。勾选“记住我的选择”把结束或保留写入 Core 的远程工作区设置,之后直接按设置执行。下次经同一连接、同一 WSL 发行版或同一容器连接时带上最新的保留凭据接回会话,打开文件夹后列出上次保留、仍在运行的进程,可“结束这些进程”(经 remote.endPrograms 只结束它们,不动这次新开的)或“继续运行”;主机上已没有该会话时开新会话并忘掉凭据;接回后没打开工作区就停止的连接再次保留该会话,进程不会未经用户选择就结束。退出 Lithe 时每个远程工作区窗口同样询问,取消的窗口保持打开。最近项目不记录远程工作区。日志只有 remote.connect、remote.workspace.open/reconnect/disconnect、remote.close.cancel/keep/end、remote.kept.end/keep 等动作和失败的操作名,不含主机、用户名、主机路径、主目录、进程名称或命令。运行 remote_close_test.go 的 7 个测试、remoteconn 的 kept_test.go 3 个测试、TestVisualRemoteClose 无头截图(询问、保留后的通知、下次连接列出保留的进程)、remote_workspace_test.go 的 5 个测试、remote_git_test.go 的 6 个测试、remoteplaceholder 的 TestHostAndLocalPathsMapBothWays 与 TestHostNamedPathNamesEveryHostPathBelowTheSibling、remote_worktree_test.go 的 3 个测试、remote_documents_test.go 的 2 个测试、remote_terminal_test.go 的 9 个测试、remote_watch_test.go 的 5 个测试、remote_search_test.go 的 4 个测试、remote_host_files_test.go 的 TestRemoteOpenFileOnHost、internal/core 的 TestRemoteTerminal*、TestRemoteWatch* 与 TestRemoteWorkspaceFiltersChangesWithoutTheHost、termview 的 TestOpenStartsTheProgramElsewhere,以及 TestVisualRemoteWorkspace 与 TestVisualRemoteWorktrees 无头截图;在 Windows 运行 TestCoreRefusesUnadaptedCommandsAndAClosedSessionDetachesTheBinding,验证 Linux 主机路径能通过绑定校验。真实 SSH 主机上的整机验收(包括终端里 vim、top 等全屏程序与窗口缩放,主机上 git checkout 等大批量修改后的监听,以及大仓库上的搜索)仍待完成。远程工作区左侧多出“端口”工具窗口(本机工作区没有,关闭工作区后消失):窗口打开时每 3 秒经 ports.listening 读取主机上正在监听的端口和会话的转发,窗口关闭或未显示时停止读取;同一端口在 0.0.0.0 与 :: 上监听只显示一行;远端端口带上主机监听的 IP 地址,多个地址时显示第一个和其余数量,悬停提示列出全部,地址或网址过长被截断时悬停提示给出全文;列出远端端口、本机地址、进程(名称与 PID,读不到时为“未知”)、来源(监听发现、手动添加)和状态。默认不自动转发任何端口,打开窗口和发现新端口都不转发;行尾“转发”把端口转发到主机上对应族的回环地址,本机在 127.0.0.1 的同号端口监听,该端口被本机其他程序占用时改用空闲端口,本机地址用警告色显示并在提示里说明原端口。右键“转发到指定本机端口…”和已转发行的“更改本机端口…”打开对话框输入 1–65535 的本机端口,非法输入就地说明且不转发;改到另一个端口时先停止原转发再在新端口转发,选择在工作区打开期间保留,停止后再转发仍用该端口。顶部输入端口、主机:端口或网址(http、https、ws、wss,省略端口时按协议默认端口)可手动添加并转发,由 Core 的 remote.parseForwardAddress 解析;格式不对就地说明,网址里带用户名或密码时拒绝并说明,输入框保留原文、日志不记输入内容;同一目标再次添加不重复。网址行按输入的样子显示,转发到主机上提供该端口的回环地址;在浏览器打开和复制本机地址把主机部分换成本机地址并保留路径和查询,ws/wss 网址不提供在浏览器打开;浏览器打不开时提示网址,日志只记失败、不记网址。主机回环地址以外的目标先询问(S28),确认后才带 AllowNonLoopback 转发,取消记为拒绝。已转发行可在浏览器打开、复制本机地址、停止;手动添加且已停止、主机上也没有在监听的行可移除;窗口标题栏可全部停止,标题栏的 ⓘ 说明转发对本机其他程序可见(S30);会话转发数达到 Core 上限时说明上限;状态栏显示已转发数量,点击打开端口窗口;会话结束时转发随之结束,重连后不自动恢复。日志只记 remote.ports.forward/localPort/move/stop/status 等动作和失败操作名,不含主机、地址或进程名。运行 remote_ports_test.go 的 12 个测试、internal/core 的 TestRemoteSessionCommandsOfAnUnknownSession 与 TestRemoteParseForwardAddressReadsPortsAndURLs,以及 TestVisualRemotePorts 无头截图。手动添加的端口和本机端口选择只在工作区打开期间保留,关闭后不保存(需 Core 存储,后续阶段)。端口窗口标题栏的“+”打开“添加转发规则”:方向默认“主机端口 → 另一台服务器”,由主机自己连接目标,数据不经过本机;主机端口可留空由主机选择,目标接受端口、主机:端口或网址(由 Core 的 remote.parseForwardAddress 解析,网址里带用户名或密码时拒绝)。规则默认只在主机的回环地址 127.0.0.1 上监听;勾选“监听主机的全部网卡”时显示警告,每次添加都再次询问、不记住,列表里的监听地址用警告色显示并在悬停提示里说明;目标不是主机自身的回环地址时先询问(S28)。“主机端口 → 本机(反向转发)”只在 设置 › 工具 › 远程工作区 的“反向转发”允许时提供(默认自动,即不允许,对话框说明在哪里开启),每条都询问,主机只在回环地址监听,本机只连接回环地址上的端口。主机端口被占用、主机不允许监听(如 1024 以下)、远端服务不支持、达到会话转发上限(与本机转发合计)、反向转发未被允许分别说明原因,主机端口不是 1–65535 时就地说明,对话框保留输入。端口窗口的“转发规则”一节列出主机监听地址、转到的目标(反向转发为“本机 地址”)、连接数(有失败时注明失败数)和状态,每行可停止,标题栏的全部停止同样停止规则;规则随会话结束而停止,重连后不自动恢复,关闭工作区后也不保存。日志只记 remote.ports.addRule/ruleHost/ruleReverse/ruleConfirm/stopRule 等动作和失败的操作名,不含地址、网址或进程名。运行 remote_port_rules_test.go 的 5 个测试、settingswindow 的 TestRemoteWorkspaceReverseForwardingIsAppliedAndRestored,以及 TestVisualRemotePorts 的转发规则列表、添加对话框和全部网卡询问截图。远程 Git 的 AskPass 转交(推送、拉取时的凭据询问)、从上级目录开始的仓库尚未支持。Windows 上“远程开发”窗口在已保存的连接之后以“WSL”标题列出本机安装的 WSL 发行版(Core 的 remote.listWslDistributions,每次打开窗口读取一次;搜索时不列出,标题可折叠;macOS 和没有 WSL 的 Windows 不显示这一组)。选中发行版后右侧说明经本机 wsl.exe 打开、不保存任何信息,可填写 Linux 用户(留空为发行版默认用户),地址显示为 wsl:[用户@]发行版。“连接”经 remote.connect 的 wsl 参数启动,不经 OpenSSH、没有询问,步骤从“启动发行版”开始,不显示读取配置和身份验证;发行版没有安装或没能启动、本机找不到 wsl.exe 时分别说明,不显示 SSH 的排查提示,也没有“编辑连接”;Core 拒绝的用户名或发行版名就地说明。连接后与 SSH 相同:选择文件夹、信任询问、工作区、心跳与重连;窗口标题为“文件夹 [WSL: 发行版]”,状态栏为“WSL: 发行版”(SSH 工作区的“SSH”也由同一参数给出),列表和概览显示已打开该发行版的窗口数。发行版不写入已保存的连接,打开过的文件夹不记入最近文件夹。日志只有 remote.wsl.select、remote.connect 等动作,不含发行版名、用户名或主机路径。运行 remote_wsl_test.go 的 3 个测试、internal/core 的 TestRemoteConnectSendsWSLAloneAndCoreRefusesItByField 与 TestRemoteListWSLDistributionsIsUnavailableOutsideWindows,以及 TestVisualRemoteConnections 的 WSL 截图;真实 Windows 上的 WSL 验收(wsl.exe 的错误输出、--exec 的二进制透传、结束 wsl.exe 后 Linux 进程是否退出、未知用户)仍待完成。打开“设置 › 工具 › 远程工作区”:页面只读取、不创建任何文件。“SSH 程序”默认“自动(Core 在 PATH 上找到的 ssh 路径)”,找不到时为“自动(未找到 ssh)”;“选择…”选一个文件作为草稿,下拉菜单可回到自动;保存的程序缺失或不可执行时在行下说明。“SSH 配置文件”只显示 Core 读取的 ~/.ssh/config 路径,不存在时注明。“自动重连时长”可选“自动(1 分钟)”、不自动重连、15 秒到 1 小时,保存过的其他值也列出。“反向转发”默认“自动(不允许)”,可选允许或不允许,ⓘ 说明主机上的所有用户都能连接反向转发的端口、每条规则仍会确认。“关闭工作区”卡片里“关闭时的远端进程”可选“每次询问”(默认)、“结束”和“保留在远端”,关闭对话框勾选“记住我的选择”后只能在这里改回;“常驻会话的空闲超时”只读显示 Core 报告的远端服务超时(10 分钟),ⓘ 说明断线且没人保留的会话多久后由主机结束。“保存位置”显示偏好目录下的 remote/preferences.json,还没有文件时注明修改后才创建。修改只是草稿:侧栏和底部显示未应用数量,“应用”或“好”经 Core 的 remote.editPreferences 写入(程序先于时长),写入后重新读取显示;Core 拒绝相对路径、不存在、不可执行的程序或超出 0–3600 秒的时长时在页面说明原因并保留草稿,不写文件;文件期间被改过时重新读取并请用户再次应用;文件损坏时说明路径、不提供编辑,此时连接、测试连接、读取有效设置和导入 SSH 主机都失败并说明原因,不用未经用户选择的程序启动 OpenSSH。选中的 SSH 程序用于连接、测试连接、有效设置和 SSH 配置导入(WSL 经 wsl.exe 启动,不使用它)。日志只记 remote_preferences_settings_load/save 等操作名和 Core 错误码,不记路径。运行 settingswindow 的 TestRemoteWorkspace* 6 个测试、remoteconn 的 preferences_test.go、internal/core 的 TestRemotePreferences*,以及 TestVisualRemoteWorkspace 无头截图(中英文、深浅色,自动值、草稿和关闭时保留远端进程三种状态)。真实 SSH 主机上关闭后保留、重连接回和结束保留进程的整机验收,以及保留进程的输出重新接回终端和运行窗口(后续阶段),仍待完成。“远程开发”窗口在 WSL 发行版之后以“容器”标题列出本机 Docker 和 Podman 正在运行的容器(Core 的 remote.listContainers,每次打开窗口读取一次,两个引擎在同一个后台任务里依次读取,一个超时或报错时跳过它并记一次 remote_containers_list 失败,另一个照常列出;搜索时不列出,标题可折叠;两个引擎都没有时不显示这一组)。每行显示容器名和“引擎 · 镜像”,已有窗口打开它时显示绿点。选中容器后右侧显示引擎标签、地址 引擎:[用户@]容器、镜像与引擎给出的状态,说明经本机引擎进入正在运行的容器、不启动不创建不改动容器、不挂载目录、不保存任何信息,可填写容器内用户(用户名、uid 或 用户:组,留空为镜像默认用户)。“连接”经 remote.connect 的 container 参数进入,不经 OpenSSH、没有询问、不发送 SSH 偏好,步骤从“进入容器”开始;容器已停止或暂停、引擎没有应答时说明这几种可能,找不到引擎命令行时说明需要安装哪个引擎,引擎输出只显示在步骤下方,不显示 SSH 的排查提示,也没有“编辑连接”;Core 拒绝的用户或容器名就地说明。连接后与 SSH 相同:选择文件夹、信任询问(信任记录包含容器)、工作区、心跳与重连;窗口标题为“文件夹 [容器: 容器名]”,状态栏为“容器: 容器名”,列表和概览按引擎和容器名显示已打开的窗口数。按容器名连接,所以同名重建的容器仍能接上;容器不写入已保存的连接,打开过的文件夹不记入最近文件夹。日志只有 remote.container.select、remote.connect 等动作,不含容器名、镜像、状态或用户名。测试替换的内核不运行本机的 docker 或 podman。运行 remote_container_test.go 的 4 个测试、internal/core 的 TestRemoteConnectSendsAContainerAloneAndCoreRefusesItByField 与 TestRemoteListContainersNamesTheSessionAndTheEngine,以及 TestVisualRemoteConnections 的容器截图;真实 Docker、Podman 与 Windows 上的整机验收仍待完成。“远程开发”窗口列表工具栏和空白页的“从 devcontainer.json 打开…”打开“在 Dev Container 中打开”页(窗口标题为“远程开发 › 在 Dev Container 中打开”):说明用官方 Dev Container CLI 按本机文件夹的 devcontainer.json 构建并启动容器、构建会运行文件夹的 Dockerfile、features 和命令所以文件夹必须受信任、Lithe 不额外挂载目录也不额外加参数。“选择文件夹…”打开系统文件夹选择,也可输入路径后按回车;相对路径、不存在的路径就地说明。读取文件夹时经 Core 的 remote.devcontainerConfigs 按规范顺序列出 .devcontainer/devcontainer.json、.devcontainer.json 和 .devcontainer 下一层文件夹里的配置,配置有 name 时显示“名称(路径)”,默认选第一个;没有配置时说明并且不能构建。容器引擎可选 Docker 或 Podman。同时读取文件夹的信任:未受信任时说明并把按钮换成“信任并构建”,先以与打开受信任项目相同的方式写入本机信任记录(记一次 workspace.trust.grant),再构建;读取信任失败时说明原因、不能构建。“构建并打开”经 remote.devcontainerUp 运行 CLI(带 projectCodeAllowed),CLI 的输出逐行显示在“构建日志”里(Core 已隐藏敏感信息,最多保留最近 5000 行,Core 截断时在下方说明),只显示、不写入 Lithe 的日志;构建期间左侧列表、配置、引擎和文件夹都不能改,底部显示“正在构建 dev container…”和“停止”。“停止”取消这次构建,日志保留并说明已经启动的容器会继续运行,不记失败;“取消”和关闭窗口也会先停止构建。找不到 devcontainer CLI 时说明用 npm 安装,CLI 报告失败时显示它的输出,超过一小时、结果里没有容器或工作区文件夹、文件夹不受信任分别说明,各记一次 remote_devcontainer_up 失败。成功后选中 CLI 返回的容器(重新读取容器列表,显示镜像),以 CLI 返回的 remoteUser 为容器内用户,按容器连接并直接打开 CLI 返回的工作区文件夹(与容器入口相同的信任询问、工作区、心跳与重连)。日志只有 remote.devcontainer.open/choose/build/stop、remote.connect 等动作,不含文件夹、配置名、容器名、用户名或 CLI 输出。测试替换的内核不运行本机的 devcontainer、docker 或 podman。运行 remote_devcontainer_test.go 的 5 个测试、internal/core 的 TestRemoteDevcontainer*,以及 TestVisualRemoteConnections 的 devcontainer 截图;装有 Dev Container CLI 的真实 Docker、Podman 上的整机验收仍待完成。在 SSH 主机或 WSL 发行版的文件夹选择里,标题栏的“主机上的容器”在文件夹的位置列出那台主机上 Docker 和 Podman 正在运行的容器(经浏览会话的 remote.listContainers 依次读取两个引擎,在远端服务的环境里运行,所以列出的容器就是能进入的;主机没有引擎命令行时说明没有找到 Docker 或 Podman,引擎报错时显示它的输出、不写日志),每行显示容器名、“引擎 · 镜像”和状态,可填写容器内用户(留空为镜像默认用户)。“进入容器”或双击一行结束浏览会话,重新连接主机并经主机上的引擎 exec 进入容器(OpenSSH 会再次询问它要问的内容;步骤与主机相同,地址显示为“主机 › 引擎:[用户@]容器”),随后在容器里选择文件夹;“返回文件夹”回到主机的文件夹。主机连不上或容器已停止、暂停、引擎没有应答时用同一段文字说明并点名引擎,具体原因在诊断输出里;没有“编辑连接”,“重试”进入同一台主机上的同一个容器。工作区身份为“已保存连接或发行版的身份/引擎:[用户@]容器”,窗口名为“容器名(主机名)”,不写入已保存的连接,打开过的文件夹不记入最近文件夹;信任记录包含主机与容器。Core 同样只进正在运行的容器,不提权、不改容器、不挂载(S32)。主机上不支持从 devcontainer.json 构建(devcontainer up 只在本机运行)。日志只有 remote.browse.containers/folders、remote.browse.container.enter、remote.connect 等动作和 remote_host_containers_list 失败名,不含主机、容器名、镜像、用户名或主机路径。运行 remote_host_containers_test.go 的 3 个测试和 TestVisualRemoteConnections 的主机容器截图;真实 SSH 主机与 Windows WSL 上的容器验收仍待完成。在远程工作区的标题栏选中程序或脚本运行配置点“运行”:程序在主机上启动(工作目录为主机文件夹下的相对目录,环境为主机登录环境加配置的变量),输出进入运行窗口,标签页带“主机”徽标;脚本写到主机临时目录,运行结束后删除;“停止”先发 SIGTERM,超过停止等待时间再强制结束;输出里的主机路径可点击并经占位路径在编辑器打开。配置的“执行前”列表里引用的其他程序或脚本运行配置按顺序在主机上先运行,步骤标题和输出写在同一个控制台,全部以 0 退出后才启动配置本身;某一步以非零退出码结束时说明步骤名和退出码,配置不启动;运行步骤时“停止”先给步骤的主机进程发 SIGTERM。列表里有插件提供的任务时说明远程工作区暂不支持插件任务,请从“执行前”列表删除后再运行。构建工具、插件提供的运行和调试在远程工作区说明暂不支持。", + "verification": "在“远程开发”窗口选中已保存的 Linux SSH 连接点“连接”:SSH 询问出现在窗口中,连接后窗口改为主机的文件夹选择,从主目录开始列出子文件夹(跳过名称不是 UTF-8 的条目并说明数量),可输入 ~ 或 / 开头的路径跳转,不存在的路径说明原因且不能打开;“返回”断开这次会话回到连接表单。选中文件夹点“打开”:新标签页打开远程工作区,窗口标题为“文件夹 [SSH: 连接名]”,项目树经 Core 列出主机目录(本机占位目录始终为空),右键只有复制主机路径和刷新;以安全模式打开的文件夹,编辑器上方说明可以浏览、编辑、保存和搜索主机文件,信任文件夹后才能用 Git;受信任的文件夹说明文件、终端和 Git 都在主机上;空白编辑区提示 Search Everywhere 和 Find in Files。在项目树双击文件:编辑器经会话读取主机文件(不超过 16 MiB),保存时带上打开时的大小和修改时间写回主机,新建的文件只在主机上不存在时创建;主机上的文件期间被别人改过时保存被拒绝并显示外部修改冲突,“加载磁盘版本”载入主机内容,本机占位目录始终为空。超过 8 MiB 的保存说明主机单次保存上限,编辑内容保留;主机上缺失、无权限、不是普通文件、超时和连接断开分别说明原因,连接断开后自动重连并把打开的文档和主机重新比对。图片、PDF 等查看器和本地历史都被拒绝并提示,不回退到本机;在文件浏览器中显示(标签页右键、Search Everywhere 结果、Git 变更)在远程工作区里不提供。状态栏连接菜单的“打开主机上的文件…”(未连接时不可用)从窗口顶部弹出路径框,默认 ~/,经 remote.readDir 列出路径最后一个“/”之前的文件夹,按其后的文字(不分大小写)筛选名称开头,文件夹在前,以“.”开头时才列出隐藏条目,无法读取的条目说明数量;上下键移动、Tab 补全名称、回车进入文件夹或打开文件,没有匹配时回车按输入的路径打开,Esc 或点外面关闭;不以 / 或 ~/ 开头的输入说明要输入什么,名称含“\\”的路径说明在 Windows 上无法打开。工作区文件夹里的文件与项目树打开的相同、可以编辑;文件夹以外的文件(对标 Zed)在占位目录旁的 .lithe-remote-host 下以只读方式打开(S25):不能切换为可编辑(提示原因并记为拒绝),保存和新建都被拒绝并说明原因、不写主机,状态栏导航路径显示 ~ 开头的主机路径,复制相对路径不提供;重连和关闭前与其他文档一样和主机比对,主机上的改动在没有编辑时重新载入(主机监听只覆盖工作区文件夹)。日志只记 remote_open_host_file、remote_read_dir、toggle_read_only 等操作名和原因,不含主机路径。打开“终端”工具窗口:经会话的 remote.runTerminal 在主机文件夹运行主机账户的登录 shell(不带参数,不读本机 Shell 设置,没有本机 Shell 菜单),标签名为连接名,之后的标签为“连接名 (2)”等;输入按顺序、每块不超过 32 KiB 写入,主机说忙时稍后重试,窗口尺寸随输入发送;输出超过 8 MiB 未显示时丢弃最旧的部分并记一次失败。程序退出显示退出码,被信号结束显示 128+信号,关闭标签不算失败。连接断开时终端显示会话已结束,工作区按退避重连;未连接时按回车说明工作区未连接,重连后按回车在新会话上运行。终端起不来时显示 Core 给出的原因(可能含主机路径),日志只记命令名和错误码。拖到终端的文件粘贴为主机路径并按 POSIX shell 加引号,本机工作区外的文件不粘贴并提示原因;粘贴图片不可用(图片会存到本机)。每个会话连接后,经 remote.runWatch 在主机上递归监听整个文件夹,跳过已启用插件隐藏的文件夹名(按原样比较大小写),插件改变隐藏名称时重新开始监听;在主机上新建、修改、删除文件后,项目树重新列出受影响的目录(Core 的 workspace.filterChanges 按可见性规则过滤,不需要会话),打开的文档与主机比对:没有编辑的重新载入,有编辑的显示外部修改冲突;文件夹外和被隐藏文件夹里的变化不触发列表。监听开始时、主机丢失变化(overflow)时、一次超过 4096 个变化时,重新列出树中展开的目录并比对所有文档,日志每次监听各记一次;主机监听数用尽时其余部分继续监听,提示一次“项目文件可能无法自动更新”。监听中文件夹被删除或移走时立即重新监听;主机找不到文件夹时项目树显示根目录不可用,监听等树重新列出文件夹后再开始,主机与树结论不一致时也只等待、不反复重试。其他监听失败只记命令名和错误码、提示一次,等下一个会话再开始;监听发现连接断开时与心跳一样结束会话并重连。Find in Files 的搜索、计数和替换预览带远程绑定发送,Core 从主机文件夹建立索引并读取主机上的当前内容,结果路径相对主机文件夹;点结果在远程编辑器打开主机文件并定位到匹配处,本机占位目录始终为空。主机监听报告的变化路径在下一次查询前增量更新索引,不重建;监听开始和主机丢失变化时重建一次。包含生成文件的查询每次都重建索引(主机监听跳过插件隐藏的文件夹);主机监听数用尽后、会话断开到下一个会话的监听开始之间,每次查询都重建,只由监听提示一次“项目文件可能无法自动更新”,搜索不再另外提示。查询显示期间主机上的变化让结果重新查询。Search Everywhere 所有页签都可用,文件名和文本来自主机,打开弹窗时重新读取生成文件的名称;受信任的远程工作区也可使用在主机上启动的语言服务器提供符号。Replace All 在编辑器中替换打开的文档;未打开的文件经会话读取主机内容,由 Core 替换后,只在主机文件仍是读取时的内容时写回,期间被改过的报告冲突,已被删除的说明主机上找不到文件,其余文件照常替换,都不写本机占位目录。在文件夹选择中打开从未决定过的文件夹:先询问是否信任(显示连接名和主机文件夹,Core 给出上级文件夹时可勾选信任其下的所有文件夹),“信任并打开”把决定按连接名记入 Core 的远程信任记录后以受信任方式打开,“以安全模式打开”只读打开,“返回”回到文件夹选择;之前决定过的文件夹直接按记录打开。安全模式下 Git、提交和日志窗口与本机项目一样说明需要信任,编辑器上方的提示里可以信任文件夹,信任后不重开窗口就在主机上启动 Git。受信任的工作区经会话在主机上运行 Git:状态、暂存、提交、差异(含编辑器行号旁的变更标记)、日志与分支、逐行追溯(读取主机上的文件内容)、搁置与储藏都读写主机仓库,本机占位目录始终没有 .git;“排除到本地”写入主机仓库的 info/exclude(缺少 info 文件夹时在主机上创建,读写期间文件被别人改过时这次排除失败、不覆盖)。同一会话经 remote.runWatch 递归监听主机仓库的 git 目录(公共目录在别处时一并监听),主机上 git checkout、commit 等改动元数据后按路径分类并重新读取状态;监听开始、丢失变化或主机监听数用尽时重新读取一次完整状态,新会话重新开始监听。主机文件夹位于上级目录开始的仓库内时,Git 和提交窗口说明要打开仓库顶层文件夹,不显示变更也不记为失败。工作树列表、锁定、解锁、删除在主机上执行,列表和详情显示主机路径,复制路径复制主机路径。打开关联工作树时“远程开发”窗口打开,用打开工作区所用的连接(或 WSL 发行版)再连一次,显示连接步骤和 OpenSSH 的询问,从未决定过的文件夹先询问是否信任,然后在本窗口的新标签页经一个新会话打开该主机文件夹;再次打开时切到已打开的标签页,不再连接;连接在工作区打开后被删除时窗口说明原因、不连接。新建工作树对话框把 Core 在仓库旁的建议显示为主机路径(如 /home/dev/project-topic),输入框下说明路径是主机上的文件夹、由主机上的 Git 创建;输入的其他主机路径原样保留,“创建”在工作区会话上由主机上的 Git 创建并选中新工作树,“创建后打开”同样经新会话在新标签页打开。在新窗口打开和在文件浏览器中显示仍被拒绝并提示。受信任的远程工作区通过捕获的会话在主机上运行当前文件、构建、运行和测试,语言服务器及声明在主机上启动的调试适配器也由远端会话管理。状态栏前端显示连接名和心跳往返时间;连续两次心跳无响应显示“无响应”,第三次结束会话并按 Core 由“自动重连时长”给出的间隔重连(默认 1、2、4、8、16、29 秒,共 60 秒),每次失败后等下一个间隔,用完后显示“已断开”和原因,菜单里可“重新连接”;连接被关闭时同样按这些间隔重连;时长设为“不自动重连”时直接显示“已断开”。关闭窗口、退出 Lithe、菜单里“断开并关闭”和切换工作区时,先经 remote.runningPrograms 读取主机上 Lithe 为这个工作区启动的进程和终端;没有时直接结束会话,有时询问“关闭远程工作区?”,正文写明连接名并逐项列出类型(终端、进程)、名称、命令(原样显示,不脱敏)和已运行时长,按钮为“结束并关闭”(默认)、“保留在远端并关闭”和“取消”,“记住我的选择”旁的 ⓘ 说明之后不再询问、只能在 设置 › 工具 › 远程工作区 修改。“取消”保留窗口和会话;“结束并关闭”经 remote.disconnect 结束主机会话;“保留在远端并关闭”让主机保留会话,把恢复凭据按连接存入系统密钥存储后通知“N 个进程保留在 <连接名> 上”,凭据存不下时改为结束并说明原因,主机拒绝保留时同样结束并说明;读取进程列表失败时不询问、照常结束。勾选“记住我的选择”把结束或保留写入 Core 的远程工作区设置,之后直接按设置执行。下次经同一连接、同一 WSL 发行版或同一容器连接时带上最新的保留凭据接回会话,打开文件夹后列出上次保留、仍在运行的进程,可“结束这些进程”(经 remote.endPrograms 只结束它们,不动这次新开的)或“继续运行”;主机上已没有该会话时开新会话并忘掉凭据;接回后没打开工作区就停止的连接再次保留该会话,进程不会未经用户选择就结束。退出 Lithe 时每个远程工作区窗口同样询问,取消的窗口保持打开。最近项目不记录远程工作区。日志只有 remote.connect、remote.workspace.open/reconnect/disconnect、remote.close.cancel/keep/end、remote.kept.end/keep 等动作和失败的操作名,不含主机、用户名、主机路径、主目录、进程名称或命令。运行 remote_close_test.go 的 7 个测试、remoteconn 的 kept_test.go 3 个测试、TestVisualRemoteClose 无头截图(询问、保留后的通知、下次连接列出保留的进程)、remote_workspace_test.go 的 5 个测试、remote_git_test.go 的 6 个测试、remoteplaceholder 的 TestHostAndLocalPathsMapBothWays 与 TestHostNamedPathNamesEveryHostPathBelowTheSibling、remote_worktree_test.go 的 3 个测试、remote_documents_test.go 的 2 个测试、remote_terminal_test.go 的 9 个测试、remote_watch_test.go 的 5 个测试、remote_search_test.go 的 4 个测试、remote_host_files_test.go 的 TestRemoteOpenFileOnHost、internal/core 的 TestRemoteTerminal*、TestRemoteWatch* 与 TestRemoteWorkspaceFiltersChangesWithoutTheHost、termview 的 TestOpenStartsTheProgramElsewhere,以及 TestVisualRemoteWorkspace 与 TestVisualRemoteWorktrees 无头截图;在 Windows 运行 TestCoreRefusesUnadaptedCommandsAndAClosedSessionDetachesTheBinding,验证 Linux 主机路径能通过绑定校验。真实 SSH 主机上的整机验收(包括终端里 vim、top 等全屏程序与窗口缩放,主机上 git checkout 等大批量修改后的监听,以及大仓库上的搜索)仍待完成。远程工作区左侧多出“端口”工具窗口(本机工作区没有,关闭工作区后消失):窗口打开时每 3 秒经 ports.listening 读取主机上正在监听的端口和会话的转发,窗口关闭或未显示时停止读取;同一端口在 0.0.0.0 与 :: 上监听只显示一行;远端端口带上主机监听的 IP 地址,多个地址时显示第一个和其余数量,悬停提示列出全部,地址或网址过长被截断时悬停提示给出全文;列出远端端口、本机地址、进程(名称与 PID,读不到时为“未知”)、来源(监听发现、手动添加)和状态。默认不自动转发任何端口,打开窗口和发现新端口都不转发;行尾“转发”把端口转发到主机上对应族的回环地址,本机在 127.0.0.1 的同号端口监听,该端口被本机其他程序占用时改用空闲端口,本机地址用警告色显示并在提示里说明原端口。右键“转发到指定本机端口…”和已转发行的“更改本机端口…”打开对话框输入 1–65535 的本机端口,非法输入就地说明且不转发;改到另一个端口时先停止原转发再在新端口转发,选择在工作区打开期间保留,停止后再转发仍用该端口。顶部输入端口、主机:端口或网址(http、https、ws、wss,省略端口时按协议默认端口)可手动添加并转发,由 Core 的 remote.parseForwardAddress 解析;格式不对就地说明,网址里带用户名或密码时拒绝并说明,输入框保留原文、日志不记输入内容;同一目标再次添加不重复。网址行按输入的样子显示,转发到主机上提供该端口的回环地址;在浏览器打开和复制本机地址把主机部分换成本机地址并保留路径和查询,ws/wss 网址不提供在浏览器打开;浏览器打不开时提示网址,日志只记失败、不记网址。主机回环地址以外的目标先询问(S28),确认后才带 AllowNonLoopback 转发,取消记为拒绝。已转发行可在浏览器打开、复制本机地址、停止;手动添加且已停止、主机上也没有在监听的行可移除;窗口标题栏可全部停止,标题栏的 ⓘ 说明转发对本机其他程序可见(S30);会话转发数达到 Core 上限时说明上限;状态栏显示已转发数量,点击打开端口窗口;会话结束时转发随之结束,重连后不自动恢复。日志只记 remote.ports.forward/localPort/move/stop/status 等动作和失败操作名,不含主机、地址或进程名。运行 remote_ports_test.go 的 12 个测试、internal/core 的 TestRemoteSessionCommandsOfAnUnknownSession 与 TestRemoteParseForwardAddressReadsPortsAndURLs,以及 TestVisualRemotePorts 无头截图。手动添加的端口和本机端口选择只在工作区打开期间保留,关闭后不保存(需 Core 存储,后续阶段)。端口窗口标题栏的“+”打开“添加转发规则”:方向默认“主机端口 → 另一台服务器”,由主机自己连接目标,数据不经过本机;主机端口可留空由主机选择,目标接受端口、主机:端口或网址(由 Core 的 remote.parseForwardAddress 解析,网址里带用户名或密码时拒绝)。规则默认只在主机的回环地址 127.0.0.1 上监听;勾选“监听主机的全部网卡”时显示警告,每次添加都再次询问、不记住,列表里的监听地址用警告色显示并在悬停提示里说明;目标不是主机自身的回环地址时先询问(S28)。“主机端口 → 本机(反向转发)”只在 设置 › 工具 › 远程工作区 的“反向转发”允许时提供(默认自动,即不允许,对话框说明在哪里开启),每条都询问,主机只在回环地址监听,本机只连接回环地址上的端口。主机端口被占用、主机不允许监听(如 1024 以下)、远端服务不支持、达到会话转发上限(与本机转发合计)、反向转发未被允许分别说明原因,主机端口不是 1–65535 时就地说明,对话框保留输入。端口窗口的“转发规则”一节列出主机监听地址、转到的目标(反向转发为“本机 地址”)、连接数(有失败时注明失败数)和状态,每行可停止,标题栏的全部停止同样停止规则;规则随会话结束而停止,重连后不自动恢复,关闭工作区后也不保存。日志只记 remote.ports.addRule/ruleHost/ruleReverse/ruleConfirm/stopRule 等动作和失败的操作名,不含地址、网址或进程名。运行 remote_port_rules_test.go 的 5 个测试、settingswindow 的 TestRemoteWorkspaceReverseForwardingIsAppliedAndRestored,以及 TestVisualRemotePorts 的转发规则列表、添加对话框和全部网卡询问截图。远程 Git 的 AskPass 转交(推送、拉取时的凭据询问)、从上级目录开始的仓库尚未支持。Windows 上“远程开发”窗口在已保存的连接之后以“WSL”标题列出本机安装的 WSL 发行版(Core 的 remote.listWslDistributions,每次打开窗口读取一次;搜索时不列出,标题可折叠;macOS 和没有 WSL 的 Windows 不显示这一组)。选中发行版后右侧说明经本机 wsl.exe 打开、不保存任何信息,可填写 Linux 用户(留空为发行版默认用户),地址显示为 wsl:[用户@]发行版。“连接”经 remote.connect 的 wsl 参数启动,不经 OpenSSH、没有询问,步骤从“启动发行版”开始,不显示读取配置和身份验证;发行版没有安装或没能启动、本机找不到 wsl.exe 时分别说明,不显示 SSH 的排查提示,也没有“编辑连接”;Core 拒绝的用户名或发行版名就地说明。连接后与 SSH 相同:选择文件夹、信任询问、工作区、心跳与重连;窗口标题为“文件夹 [WSL: 发行版]”,状态栏为“WSL: 发行版”(SSH 工作区的“SSH”也由同一参数给出),列表和概览显示已打开该发行版的窗口数。发行版不写入已保存的连接,打开过的文件夹不记入最近文件夹。日志只有 remote.wsl.select、remote.connect 等动作,不含发行版名、用户名或主机路径。运行 remote_wsl_test.go 的 3 个测试、internal/core 的 TestRemoteConnectSendsWSLAloneAndCoreRefusesItByField 与 TestRemoteListWSLDistributionsIsUnavailableOutsideWindows,以及 TestVisualRemoteConnections 的 WSL 截图;真实 Windows 上的 WSL 验收(wsl.exe 的错误输出、--exec 的二进制透传、结束 wsl.exe 后 Linux 进程是否退出、未知用户)仍待完成。打开“设置 › 工具 › 远程工作区”:页面只读取、不创建任何文件。“SSH 程序”默认“自动(Core 在 PATH 上找到的 ssh 路径)”,找不到时为“自动(未找到 ssh)”;“选择…”选一个文件作为草稿,下拉菜单可回到自动;保存的程序缺失或不可执行时在行下说明。“SSH 配置文件”只显示 Core 读取的 ~/.ssh/config 路径,不存在时注明。“自动重连时长”可选“自动(1 分钟)”、不自动重连、15 秒到 1 小时,保存过的其他值也列出。“反向转发”默认“自动(不允许)”,可选允许或不允许,ⓘ 说明主机上的所有用户都能连接反向转发的端口、每条规则仍会确认。“关闭工作区”卡片里“关闭时的远端进程”可选“每次询问”(默认)、“结束”和“保留在远端”,关闭对话框勾选“记住我的选择”后只能在这里改回;“常驻会话的空闲超时”只读显示 Core 报告的远端服务超时(10 分钟),ⓘ 说明断线且没人保留的会话多久后由主机结束。“保存位置”显示偏好目录下的 remote/preferences.json,还没有文件时注明修改后才创建。修改只是草稿:侧栏和底部显示未应用数量,“应用”或“好”经 Core 的 remote.editPreferences 写入(程序先于时长),写入后重新读取显示;Core 拒绝相对路径、不存在、不可执行的程序或超出 0–3600 秒的时长时在页面说明原因并保留草稿,不写文件;文件期间被改过时重新读取并请用户再次应用;文件损坏时说明路径、不提供编辑,此时连接、测试连接、读取有效设置和导入 SSH 主机都失败并说明原因,不用未经用户选择的程序启动 OpenSSH。选中的 SSH 程序用于连接、测试连接、有效设置和 SSH 配置导入(WSL 经 wsl.exe 启动,不使用它)。日志只记 remote_preferences_settings_load/save 等操作名和 Core 错误码,不记路径。运行 settingswindow 的 TestRemoteWorkspace* 6 个测试、remoteconn 的 preferences_test.go、internal/core 的 TestRemotePreferences*,以及 TestVisualRemoteWorkspace 无头截图(中英文、深浅色,自动值、草稿和关闭时保留远端进程三种状态)。真实 SSH 主机上关闭后保留、重连接回和结束保留进程的整机验收,以及保留进程的输出重新接回终端和运行窗口(后续阶段),仍待完成。“远程开发”窗口在 WSL 发行版之后以“容器”标题列出本机 Docker 和 Podman 正在运行的容器(Core 的 remote.listContainers,每次打开窗口读取一次,两个引擎在同一个后台任务里依次读取,一个超时或报错时跳过它并记一次 remote_containers_list 失败,另一个照常列出;搜索时不列出,标题可折叠;两个引擎都没有时不显示这一组)。每行显示容器名和“引擎 · 镜像”,已有窗口打开它时显示绿点。选中容器后右侧显示引擎标签、地址 引擎:[用户@]容器、镜像与引擎给出的状态,说明经本机引擎进入正在运行的容器、不启动不创建不改动容器、不挂载目录、不保存任何信息,可填写容器内用户(用户名、uid 或 用户:组,留空为镜像默认用户)。“连接”经 remote.connect 的 container 参数进入,不经 OpenSSH、没有询问、不发送 SSH 偏好,步骤从“进入容器”开始;容器已停止或暂停、引擎没有应答时说明这几种可能,找不到引擎命令行时说明需要安装哪个引擎,引擎输出只显示在步骤下方,不显示 SSH 的排查提示,也没有“编辑连接”;Core 拒绝的用户或容器名就地说明。连接后与 SSH 相同:选择文件夹、信任询问(信任记录包含容器)、工作区、心跳与重连;窗口标题为“文件夹 [容器: 容器名]”,状态栏为“容器: 容器名”,列表和概览按引擎和容器名显示已打开的窗口数。按容器名连接,所以同名重建的容器仍能接上;容器不写入已保存的连接,打开过的文件夹不记入最近文件夹。日志只有 remote.container.select、remote.connect 等动作,不含容器名、镜像、状态或用户名。测试替换的内核不运行本机的 docker 或 podman。运行 remote_container_test.go 的 4 个测试、internal/core 的 TestRemoteConnectSendsAContainerAloneAndCoreRefusesItByField 与 TestRemoteListContainersNamesTheSessionAndTheEngine,以及 TestVisualRemoteConnections 的容器截图;真实 Docker、Podman 与 Windows 上的整机验收仍待完成。“远程开发”窗口列表工具栏和空白页的“从 devcontainer.json 打开…”打开“在 Dev Container 中打开”页(窗口标题为“远程开发 › 在 Dev Container 中打开”):说明用官方 Dev Container CLI 按本机文件夹的 devcontainer.json 构建并启动容器、构建会运行文件夹的 Dockerfile、features 和命令所以文件夹必须受信任、Lithe 不额外挂载目录也不额外加参数。“选择文件夹…”打开系统文件夹选择,也可输入路径后按回车;相对路径、不存在的路径就地说明。读取文件夹时经 Core 的 remote.devcontainerConfigs 按规范顺序列出 .devcontainer/devcontainer.json、.devcontainer.json 和 .devcontainer 下一层文件夹里的配置,配置有 name 时显示“名称(路径)”,默认选第一个;没有配置时说明并且不能构建。容器引擎可选 Docker 或 Podman。同时读取文件夹的信任:未受信任时说明并把按钮换成“信任并构建”,先以与打开受信任项目相同的方式写入本机信任记录(记一次 workspace.trust.grant),再构建;读取信任失败时说明原因、不能构建。“构建并打开”经 remote.devcontainerUp 运行 CLI(带 projectCodeAllowed),CLI 的输出逐行显示在“构建日志”里(Core 已隐藏敏感信息,最多保留最近 5000 行,Core 截断时在下方说明),只显示、不写入 Lithe 的日志;构建期间左侧列表、配置、引擎和文件夹都不能改,底部显示“正在构建 dev container…”和“停止”。“停止”取消这次构建,日志保留并说明已经启动的容器会继续运行,不记失败;“取消”和关闭窗口也会先停止构建。找不到 devcontainer CLI 时说明用 npm 安装,CLI 报告失败时显示它的输出,超过一小时、结果里没有容器或工作区文件夹、文件夹不受信任分别说明,各记一次 remote_devcontainer_up 失败。成功后选中 CLI 返回的容器(重新读取容器列表,显示镜像),以 CLI 返回的 remoteUser 为容器内用户,按容器连接并直接打开 CLI 返回的工作区文件夹(与容器入口相同的信任询问、工作区、心跳与重连)。日志只有 remote.devcontainer.open/choose/build/stop、remote.connect 等动作,不含文件夹、配置名、容器名、用户名或 CLI 输出。测试替换的内核不运行本机的 devcontainer、docker 或 podman。运行 remote_devcontainer_test.go 的 5 个测试、internal/core 的 TestRemoteDevcontainer*,以及 TestVisualRemoteConnections 的 devcontainer 截图;装有 Dev Container CLI 的真实 Docker、Podman 上的整机验收仍待完成。在 SSH 主机或 WSL 发行版的文件夹选择里,标题栏的“主机上的容器”在文件夹的位置列出那台主机上 Docker 和 Podman 正在运行的容器(经浏览会话的 remote.listContainers 依次读取两个引擎,在远端服务的环境里运行,所以列出的容器就是能进入的;主机没有引擎命令行时说明没有找到 Docker 或 Podman,引擎报错时显示它的输出、不写日志),每行显示容器名、“引擎 · 镜像”和状态,可填写容器内用户(留空为镜像默认用户)。“进入容器”或双击一行结束浏览会话,重新连接主机并经主机上的引擎 exec 进入容器(OpenSSH 会再次询问它要问的内容;步骤与主机相同,地址显示为“主机 › 引擎:[用户@]容器”),随后在容器里选择文件夹;“返回文件夹”回到主机的文件夹。主机连不上或容器已停止、暂停、引擎没有应答时用同一段文字说明并点名引擎,具体原因在诊断输出里;没有“编辑连接”,“重试”进入同一台主机上的同一个容器。工作区身份为“已保存连接或发行版的身份/引擎:[用户@]容器”,窗口名为“容器名(主机名)”,不写入已保存的连接,打开过的文件夹不记入最近文件夹;信任记录包含主机与容器。Core 同样只进正在运行的容器,不提权、不改容器、不挂载(S32)。主机上不支持从 devcontainer.json 构建(devcontainer up 只在本机运行)。日志只有 remote.browse.containers/folders、remote.browse.container.enter、remote.connect 等动作和 remote_host_containers_list 失败名,不含主机、容器名、镜像、用户名或主机路径。运行 remote_host_containers_test.go 的 3 个测试和 TestVisualRemoteConnections 的主机容器截图;真实 SSH 主机与 Windows WSL 上的容器验收仍待完成。在远程工作区的标题栏选中程序或脚本运行配置点“运行”:程序在主机上启动(工作目录为主机文件夹下的相对目录,环境为主机登录环境加配置的变量),输出进入运行窗口,标签页带“主机”徽标;脚本写到主机临时目录,运行结束后删除;“停止”先发 SIGTERM,超过停止等待时间再强制结束;输出里的主机路径可点击并经占位路径在编辑器打开。配置的“执行前”列表里引用的其他程序或脚本运行配置按顺序在主机上先运行,步骤标题和输出写在同一个控制台,全部以 0 退出后才启动配置本身;某一步以非零退出码结束时说明步骤名和退出码,配置不启动;运行步骤时“停止”先给步骤的主机进程发 SIGTERM。远端插件、运行和调试的完整跨平台验收仍待完成。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { @@ -179,5 +183,5 @@ "verificationStatus": "pending" } }, - "notes": "Viva:连接和会话由 Core 的 remote.connect/remote.disconnect/remote.closeAll 管理,远端服务按嵌入清单上传;文件夹选择用 remote.readDir。打开的工作区以用户缓存目录下的空占位目录作为本机根,每个请求带上远程绑定(会话、占位根、主机根),Core 只对有远程适配的命令放行,其余以 not_supported 拒绝,所以没有远程实现的功能在桌面端直接拒绝而不读本机占位目录。编辑器的读、写和比对改走 remote.stat、remote.readFile、remote.writeFile(带预期版本,主机按大小和修改时间拒绝过期写入);解码、恢复、语言识别等纯计算命令不带远程绑定发送。日志只记命令名和错误码,不记 Core 返回的消息(可能含主机路径)。macOS 由单元测试与无头截图覆盖;Core 按 POSIX 规则校验 Linux 主机路径,按客户端规则处理本机占位根(#2264)。终端经 remote.runTerminal 运行,输入与尺寸经 remote.hostRequest 的 terminal.write/terminal.resize 发送;关闭标签取消这次请求,Core 随即向主机发 terminal.close;一个连接断开的终端让工作区按同一会话丢失处理(与心跳一致),其他失败只结束该终端。文件夹监听经 remote.runWatch 在请求的 goroutine 上运行整个会话期间,不计入窗口的后台任务;事件在锁内合并后只投递一次到窗口线程,停止监听时作废已排队的变化。Find in Files、Search Everywhere 和 Replace All 的 workspace.search、searchIndex.update/invalidate、searchEverywhere、replacePreview 带远程绑定发送,searchPresentation、replaceText 等纯计算命令不带绑定;Core 以“会话身份 + 主机路径”为键缓存索引,主机监听的变化经 workspace.filterChanges 过滤后更新它。会话结束后 Core 不释放该会话的索引,每次重连或重新打开多留一份(#2277)。 远程信任:Core 的 remote.workspaceTrust 按“会话身份 + 主机文件夹”读出记录,remote.editWorkspaceTrust 写入决定(含连接名),桌面端只把 Core 给出的文档存到偏好目录;projectCodeAllowed 且状态为 trusted 才算受信任。受信任后 git.* 请求带远程绑定发送,Core 在主机上运行 Git,返回的路径是占位路径(remoteplaceholder.LocalPath 把主机路径换成占位路径,文件夹外的主机路径映射到占位目录旁的 .lithe-remote-host 下,不会落到本机真实路径)。git 目录的监听与文件夹监听同样跑在请求自己的 goroutine 上,会话丢失或失去信任时取消。 端口:remote.startForward/stopForward/forwards 与 ports.listening 都带会话发送;Core 只在本机 127.0.0.1 监听,请求的本机端口被占用时选空闲端口并返回 localPortChanged 与 requestedLocalPort;同一目标再次转发返回已有转发(created=false),所以更改本机端口是先停止再转发。顶部输入由 Core 的 remote.parseForwardAddress 解析为目标端口、主机、协议和路径,不连接主机;桌面端把网址的主机换成主机上提供该端口的回环地址再转发。非回环目标需 allowNonLoopback(S28),超过上限返回 forward_limit_reached 并带 maximum。读取在窗口的后台任务里进行,只在窗口打开且被绘制过时排下一次,不做空闲轮询。 转发规则:remote.startHostForward 让主机在回环地址(allInterfaces 时在全部网卡)监听并由主机连接目标,remote.startReverseForward 让主机只在回环地址监听、把每个连接带回本机回环地址上的端口;两者与 remote.startForward 共用会话转发上限,remote.forwards 用 kind 区分三种转发,端口窗口的端口列表只列本机转发。主机端口被占用、被拒绝、远端服务不支持和反向转发未允许分别是 forward_host_port_in_use、forward_host_port_denied、forward_host_unsupported、reverse_forward_disabled。remote.preferences 返回 reverseForwarding(来源与是否允许):打开对话框时据此决定是否提供反向方向,startReverseForward 也带上偏好文档由 Core 再校验一次。 WSL:remote.connect 的 connection 与 wsl 二选一,Core 经 wsl.exe --distribution … --exec 启动同一个远端服务,会话身份为 wsl:[用户@]发行版;桌面端的 remoteHost 在 SSH 连接与 WSL 发行版之间二选一,步骤、文件夹选择、信任、工作区和重连共用同一流程。remote.listWslDistributions 在 Windows 以外直接返回不可用,不运行任何程序。 远程工作区设置:Core 的 remote.preferences 读取偏好文档并解析 SSH 程序(found/missing/notExecutable)、~/.ssh/config 是否存在和重连间隔,remote.editPreferences 一次修改一个字段并返回新文档或 null(全部为自动时删除文件);桌面端只把文档按版本写到偏好目录的 remote/preferences.json(不超过 16 KiB),期间被改过时以冲突拒绝。每次连接、测试连接、读取有效设置和 SSH 配置导入都在后台重新读取文档并随请求发送;连接丢失时在后台读取重连间隔,读取失败时工作区保持断开并说明原因。页面的“自动(…)”另用不带文档的 remote.preferences 求出 Core 的默认值,所以保存了其他值时也能显示自动值。 关闭确认:连接都以常驻会话建立,Core 的 remote.connect 返回 sessionKey、sessionToken 和 resumed;关闭时 remote.runningPrograms 列出主机进程,remote.disconnect 带 programs=end/keep,keep 由 Core 发 server.keep,主机拒绝时返回错误、桌面端改为结束。保留的 sessionKey 与 sessionToken 按连接存入系统密钥存储(每个连接最多 8 条、整项不超过 2560 字节以适配 Windows 凭据管理器,最新的排最后),下次连接带上最新一条作为 resume;resumed=false 时忘掉这条。resumed 会话的 keptPrograms 在打开文件夹后列出,remote.endPrograms 按列出的 ID 只结束这些进程;空闲超时来自 Core 的 closing.idleTimeoutSeconds。记住的选择经 remote.editPreferences 的 closePrograms 写入同一份偏好文档。进程名称和命令只在对话框里显示,不写日志。 容器:remote.connect 的 container 单独出现时由 Core 在本机运行 exec -i [-u 用户] 容器 进入(S32:只进正在运行的容器,不提权、不改容器、不挂载),会话身份为 engine:[用户@]容器;container 跟在 connection 或 wsl 后面时 Core 在那台主机上、远端服务的非登录环境里运行同样的 exec,信任键包含主机与容器,remote.listContainers 带 sessionId 时也在那里列出。桌面端 remoteHost 由 SSH 连接或 WSL 发行版加可选的容器组成:overSSH() 决定是否发送 SSH 偏好、显示配置与认证步骤,saved() 决定是否提供编辑和记住文件夹,hosted() 区分主机上的容器(失败文字、重试目标)。列表键为 引擎:完整 ID,请求只发容器名。 devcontainer.json:Core 的 remote.devcontainerConfigs 只读文件夹并列出配置,remote.devcontainerUp 要求 projectCodeAllowed,在本机运行 devcontainer up(只传 --workspace-folder、选中的 --config,选 Podman 时加 --docker-path podman,不加挂载或其他参数),按流式事件返回已隐藏敏感信息的输出,结束时给出容器 ID、名称、remoteUser 和 remoteWorkspaceFolder;桌面端随后走与容器入口相同的 remote.connect 的 container 参数。未受信任的文件夹由桌面端先写本机信任记录再构建。 工作树:打开远程工作区的工作树等于用同一个连接打开另一个主机文件夹,每个文件夹一个会话、一个标签页,已有标签页的会话还活着时直接切换;新建对话框把仓库、目标和建议路径都用 remoteplaceholder.HostNamedPath 映射到占位根旁的 .lithe-remote-host 下发给 Core,Core 按仓库路径推出的建议也落在那里,显示前换回主机路径,所以不用改 Core 的建议和映射规则,Windows 与 WSL 上的主机路径也是本机绝对路径。 运行配置在远程工作区由 Core 路由到主机(runConfig.*,计划按主机平台生成),桌面端用 remote.runProcess 启动内置的程序和脚本运行,输出经有界缓冲(8 MiB,超出丢弃最旧部分并提示)进入运行窗口;进程 id 不是本机的,不采样端口和资源。“执行前”列表里的内置运行配置步骤同样经 remote.runProcess 在主机上运行(各自的临时目录在下一步开始前删除,停止或超出准备时间先发 SIGTERM);插件任务步骤、构建工具、插件运行和调试要在本机插件后端计划主机上的进程(#2231 R3/R4),本阶段不做。" + "notes": "Viva:连接和会话由 Core 的 remote.connect/remote.disconnect/remote.closeAll 管理,远端服务按嵌入清单上传;文件夹选择用 remote.readDir。打开的工作区以用户缓存目录下的空占位目录作为本机根,每个请求带上远程绑定(会话、占位根、主机根),Core 只对有远程适配的命令放行,其余以 not_supported 拒绝,所以没有远程实现的功能在桌面端直接拒绝而不读本机占位目录。编辑器的读、写和比对改走 remote.stat、remote.readFile、remote.writeFile(带预期版本,主机按大小和修改时间拒绝过期写入);解码、恢复、语言识别等纯计算命令不带远程绑定发送。日志只记命令名和错误码,不记 Core 返回的消息(可能含主机路径)。macOS 由单元测试与无头截图覆盖;Core 按 POSIX 规则校验 Linux 主机路径,按客户端规则处理本机占位根(#2264)。终端经 remote.runTerminal 运行,输入与尺寸经 remote.hostRequest 的 terminal.write/terminal.resize 发送;关闭标签取消这次请求,Core 随即向主机发 terminal.close;一个连接断开的终端让工作区按同一会话丢失处理(与心跳一致),其他失败只结束该终端。文件夹监听经 remote.runWatch 在请求的 goroutine 上运行整个会话期间,不计入窗口的后台任务;事件在锁内合并后只投递一次到窗口线程,停止监听时作废已排队的变化。Find in Files、Search Everywhere 和 Replace All 的 workspace.search、searchIndex.update/invalidate、searchEverywhere、replacePreview 带远程绑定发送,searchPresentation、replaceText 等纯计算命令不带绑定;Core 以“会话身份 + 主机路径”为键缓存索引,主机监听的变化经 workspace.filterChanges 过滤后更新它。会话结束后 Core 不释放该会话的索引,每次重连或重新打开多留一份(#2277)。 远程信任:Core 的 remote.workspaceTrust 按“会话身份 + 主机文件夹”读出记录,remote.editWorkspaceTrust 写入决定(含连接名),桌面端只把 Core 给出的文档存到偏好目录;projectCodeAllowed 且状态为 trusted 才算受信任。受信任后 git.* 请求带远程绑定发送,Core 在主机上运行 Git,返回的路径是占位路径(remoteplaceholder.LocalPath 把主机路径换成占位路径,文件夹外的主机路径映射到占位目录旁的 .lithe-remote-host 下,不会落到本机真实路径)。git 目录的监听与文件夹监听同样跑在请求自己的 goroutine 上,会话丢失或失去信任时取消。 端口:remote.startForward/stopForward/forwards 与 ports.listening 都带会话发送;Core 只在本机 127.0.0.1 监听,请求的本机端口被占用时选空闲端口并返回 localPortChanged 与 requestedLocalPort;同一目标再次转发返回已有转发(created=false),所以更改本机端口是先停止再转发。顶部输入由 Core 的 remote.parseForwardAddress 解析为目标端口、主机、协议和路径,不连接主机;桌面端把网址的主机换成主机上提供该端口的回环地址再转发。非回环目标需 allowNonLoopback(S28),超过上限返回 forward_limit_reached 并带 maximum。读取在窗口的后台任务里进行,只在窗口打开且被绘制过时排下一次,不做空闲轮询。 转发规则:remote.startHostForward 让主机在回环地址(allInterfaces 时在全部网卡)监听并由主机连接目标,remote.startReverseForward 让主机只在回环地址监听、把每个连接带回本机回环地址上的端口;两者与 remote.startForward 共用会话转发上限,remote.forwards 用 kind 区分三种转发,端口窗口的端口列表只列本机转发。主机端口被占用、被拒绝、远端服务不支持和反向转发未允许分别是 forward_host_port_in_use、forward_host_port_denied、forward_host_unsupported、reverse_forward_disabled。remote.preferences 返回 reverseForwarding(来源与是否允许):打开对话框时据此决定是否提供反向方向,startReverseForward 也带上偏好文档由 Core 再校验一次。 WSL:remote.connect 的 connection 与 wsl 二选一,Core 经 wsl.exe --distribution … --exec 启动同一个远端服务,会话身份为 wsl:[用户@]发行版;桌面端的 remoteHost 在 SSH 连接与 WSL 发行版之间二选一,步骤、文件夹选择、信任、工作区和重连共用同一流程。remote.listWslDistributions 在 Windows 以外直接返回不可用,不运行任何程序。 远程工作区设置:Core 的 remote.preferences 读取偏好文档并解析 SSH 程序(found/missing/notExecutable)、~/.ssh/config 是否存在和重连间隔,remote.editPreferences 一次修改一个字段并返回新文档或 null(全部为自动时删除文件);桌面端只把文档按版本写到偏好目录的 remote/preferences.json(不超过 16 KiB),期间被改过时以冲突拒绝。每次连接、测试连接、读取有效设置和 SSH 配置导入都在后台重新读取文档并随请求发送;连接丢失时在后台读取重连间隔,读取失败时工作区保持断开并说明原因。页面的“自动(…)”另用不带文档的 remote.preferences 求出 Core 的默认值,所以保存了其他值时也能显示自动值。 关闭确认:连接都以常驻会话建立,Core 的 remote.connect 返回 sessionKey、sessionToken 和 resumed;关闭时 remote.runningPrograms 列出主机进程,remote.disconnect 带 programs=end/keep,keep 由 Core 发 server.keep,主机拒绝时返回错误、桌面端改为结束。保留的 sessionKey 与 sessionToken 按连接存入系统密钥存储(每个连接最多 8 条、整项不超过 2560 字节以适配 Windows 凭据管理器,最新的排最后),下次连接带上最新一条作为 resume;resumed=false 时忘掉这条。resumed 会话的 keptPrograms 在打开文件夹后列出,remote.endPrograms 按列出的 ID 只结束这些进程;空闲超时来自 Core 的 closing.idleTimeoutSeconds。记住的选择经 remote.editPreferences 的 closePrograms 写入同一份偏好文档。进程名称和命令只在对话框里显示,不写日志。 容器:remote.connect 的 container 单独出现时由 Core 在本机运行 exec -i [-u 用户] 容器 进入(S32:只进正在运行的容器,不提权、不改容器、不挂载),会话身份为 engine:[用户@]容器;container 跟在 connection 或 wsl 后面时 Core 在那台主机上、远端服务的非登录环境里运行同样的 exec,信任键包含主机与容器,remote.listContainers 带 sessionId 时也在那里列出。桌面端 remoteHost 由 SSH 连接或 WSL 发行版加可选的容器组成:overSSH() 决定是否发送 SSH 偏好、显示配置与认证步骤,saved() 决定是否提供编辑和记住文件夹,hosted() 区分主机上的容器(失败文字、重试目标)。列表键为 引擎:完整 ID,请求只发容器名。 devcontainer.json:Core 的 remote.devcontainerConfigs 只读文件夹并列出配置,remote.devcontainerUp 要求 projectCodeAllowed,在本机运行 devcontainer up(只传 --workspace-folder、选中的 --config,选 Podman 时加 --docker-path podman,不加挂载或其他参数),按流式事件返回已隐藏敏感信息的输出,结束时给出容器 ID、名称、remoteUser 和 remoteWorkspaceFolder;桌面端随后走与容器入口相同的 remote.connect 的 container 参数。未受信任的文件夹由桌面端先写本机信任记录再构建。 工作树:打开远程工作区的工作树等于用同一个连接打开另一个主机文件夹,每个文件夹一个会话、一个标签页,已有标签页的会话还活着时直接切换;新建对话框把仓库、目标和建议路径都用 remoteplaceholder.HostNamedPath 映射到占位根旁的 .lithe-remote-host 下发给 Core,Core 按仓库路径推出的建议也落在那里,显示前换回主机路径,所以不用改 Core 的建议和映射规则,Windows 与 WSL 上的主机路径也是本机绝对路径。 运行配置在远程工作区由 Core 路由到主机(runConfig.*,计划按主机平台生成),桌面端用 remote.runProcess 启动内置的程序和脚本运行,输出经有界缓冲(8 MiB,超出丢弃最旧部分并提示)进入运行窗口;进程 id 不是本机的,不采样端口和资源。“执行前”列表里的内置运行配置步骤同样经 remote.runProcess 在主机上运行(各自的临时目录在下一步开始前删除,停止或超出准备时间先发 SIGTERM);插件任务步骤和插件运行由 Core 按主机路径生成执行计划,工作目录由远端会话约束。 插件进程资源按插件版本与部署哈希保存在远端用户缓存,首次连接和重连均从捕获的会话提交完整安装清单;仍有会话使用的版本保留。" } From 6b076eace7150af22aec519f8b53f60c12ec7ba3 Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Sat, 21 Nov 2026 20:13:02 -0800 Subject: [PATCH 2/3] fix(desktop): pin Rust Core for remote plugin integration Refs #2231 --- scripts/desktop/build-desktop-core.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 3ca7f5dcee..47862a109d 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -339,7 +339,8 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # Lithe-core-rust main at 2e4be2c: #166 a connection accepts a Windows domain user (DOMAIN\name, # name@domain) and remote.mottyHosts marks a refused setting on its own field with the invalid # status; #165 ending a remote session releases the search indexes it built (#2231, #2277). -PINNED_CORE_REVISION="2e4be2ca23bd8ba83bea93278067b566a7194ead" +# Core follow-up for #2231 R3–R5: remote plugin host services, execution, debugging and deployment. +PINNED_CORE_REVISION="908a53057ed295d5be3ef3f8f2cd9470a405af16" PROFILE="debug" CHECKOUT_ONLY="no" while [[ $# -gt 0 ]]; do From 3ac81eb176ad3f5293cb549eb7bac0c56ae8a5d6 Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Sat, 21 Nov 2026 20:16:01 -0800 Subject: [PATCH 3/3] fix(test): assert the remote builtin debugger refusal code Refs #2231 --- desktop/internal/workbench/remote_run_test.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/desktop/internal/workbench/remote_run_test.go b/desktop/internal/workbench/remote_run_test.go index 1783d59f05..eb65485be1 100644 --- a/desktop/internal/workbench/remote_run_test.go +++ b/desktop/internal/workbench/remote_run_test.go @@ -2,6 +2,7 @@ package workbench import ( "context" + "errors" "path/filepath" "strings" "sync" @@ -394,8 +395,9 @@ func TestRemoteWorkspaceRefusesRunsItCannotStartOnTheHost(t *testing.T) { h.await("the built-in debug refusal", func() bool { select { case err := <-done: - if err == nil || !h.notified(i18n.Shared(lang, "desktop.remote.workspace.localOnly")) { - t.Fatalf("a built-in debug session was not refused: %v", err) + var refusal *buildRefusal + if !errors.As(err, &refusal) || refusal.code != refusalNotSupported { + t.Fatalf("debug start = %v, want not supported", err) } return true default: