diff --git a/.agents/notes/implemented/architecture/2026-11-10-viva-plugin-host-services-and-backend-sessions.md b/.agents/notes/implemented/architecture/2026-11-10-viva-plugin-host-services-and-backend-sessions.md index 0fc69f2ea..903689c19 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-viva-plugin-host-services-and-backend-sessions.md +++ b/.agents/notes/implemented/architecture/2026-11-10-viva-plugin-host-services-and-backend-sessions.md @@ -83,13 +83,13 @@ Run 自己启动的进程还必须随附加的调试会话释放。单独发送 - 不要这样做:在 `get` 找不到时自动读旧位置。早先的版本这样做过,有两个问题:一是静默复制,用户不知道 Viva 拿到了旧密钥;二是为了防止已删除的值经迁移复活,`delete` 只好连旧项一起删,结果删掉了旧客户端仍在用的凭据。 - **编辑**:`editorview.View.ApplyEdits` 把一批互不重叠的编辑合成一次 rope 差异,只产生一步撤销和一次语言服务器同步事件;位置按 UTF-16 解析,越界、落在代理对中间、重叠都拒绝(`OffsetOf`,与 LSP 风格的 `ByteOffset` 钳制不同,过期范围不能被悄悄挪动)。版本号是 view 的修订号,`getSnapshot`、`getSelections` 和所有编辑使用同一个;只读、输入法组字、版本不符分别返回 `readOnly`、`busy`、`versionConflict`(带 `currentVersion`)。编辑器只有单选区,`getSelections` 返回一个选区;`editor/open|reveal` 只把范围起点放成光标。资源路径要求相对、`/` 分隔、无 `.`/`..`,并对最长已存在前缀解析符号链接后确认仍在根内。 - **窗口消息**:用现有 `sheet` 模态面板按到达顺序一次显示一个,限频 10 秒 5 条、每插件 3 条等待,其余返回 `rateLimited`(带 `retryAfterMilliseconds`)与 `busy`。面板用 Frame 引擎绘制,与旁边的插件审查面板一致,因为窗口主体还没迁到 Viva Page;迁移时与审查面板一起换。 -- **浏览器**:`browser/openExternal` 只接受 http/https URL(无内嵌凭据),经 Viva 的 `app.OpenURL` 打开;`resource` 形式返回 `unsupportedOption`。**`preview/openHTML` 不注册**:Viva 有系统 Web 视图(`docs/web-views.md`),但编辑器区还没有能承载网页的标签与“编辑器加预览”布局,在无头环境里也无法验证原生视图。 +- **浏览器与预览**:`browser/openExternal` 接受 http/https URL(无内嵌凭据)或已保存的 HTML 资源。资源默认要求没有未保存修改,只有显式选择 `openSavedFile` 才打开磁盘旧内容,宿主不自动保存。`preview/openMarkdown|openHTML` 注册后复用工作台预览,支持资源与只读内联文本;HTML 需要原生 WebView,不可用时在创建标签前拒绝。Core 先检查资源类型和默认模式,窗口不重复校验。 - **终端**:用户同意(精确程序、argv、目录)后在 Terminal 工具窗口启动,与用户终端共用标签条、拖拽和分组。`termview.Config` 增加 `Args/Env/Unset/Prefill/Exited`,带 `Exited` 的视图不再靠 Enter 重启,由插件通过 `reopen` 决定;`localshell.Config.Unset` 支持移除变量(Unix 与 Windows 后端);插件终端创建时立即启动,不等第一次绘制,因为 `show:false` 的终端不会被绘制。`close`、自然退出和关闭项目走同一条收尾路径,先取纯文本快照(`AppendRetainedText`,按预算在字符边界截断)再释放视图;自然退出后标签自动移除,退出事件只发一次。每个插件最多 8 个句柄,按会话和上下文归属,上下文关闭、会话结束、插件停用时关闭并忘记。`LITHE_` 前缀的环境变量不允许覆盖。 - **内容提供者**:绑定记录在 `contentProviders`(上下文加 scheme),不回调后端;`documents/registerContentProvider` 要求函数已在该会话注册,保留 scheme 与重复注册按契约拒绝。导航结果的 `FilePath` 为空且 URI 的 scheme 有提供者时,定义列表保留该目标,选中后向插件请求内容(30 秒),经 Core 的 `plugins.contentProviders.decode` 校验后以只读标签打开。虚拟文档的 `path` 就是 URI,不监视文件、不保存、不与语言服务器同步,关闭后宿主不留副本。 - **订阅与资源释放**:`hostResources` 统一登记订阅、内容提供者、终端句柄,归属 `(插件, 会话, 上下文)`;`subscriptions/dispose` 只释放调用方自己的 ID;会话结束与上下文关闭自动释放。 -- **命令**:`commands/didRun` 的发送端 `Service.NotifyCommandRun` 已实现(运行中的后端直接收;已停止的只有清单声明 `onCommand:` 才被启动),但 Viva 目前没有命令面板、编辑器右键菜单或插件命令贡献入口,没有调用方。 +- **命令**:`Service.NotifyCommandRun` 从命令面板、已有快捷键目录及状态项运行纯后端命令,不再要求命令绑定工具窗口。运行中的后端直接收;已停止的只有清单声明 `onCommand:` 才被启动。状态项只能引用本插件清单中的命令,归属由 Core 检查。 -未接通(会被 Core 以 `plugin.host.unavailable` 拒绝):`editor/registerActions`、`editor/registerProviders`(没有编辑器行首图标、命令入口与右键菜单,注册了用户也触发不了,所以不声明)、`preview/openHTML`、`run/*`、`debug/*`(后两者属其他车道)。凭据在插件卸载时的清理也未做:除 macOS 外平台存储不能按 service 枚举,需要后续由插件管理器记录已用的 key。 +本节记录宿主接线边界,不作为所有领域的完成清单;编辑器注册、运行和调试的现状分别由对应实现与功能矩阵维护。凭据在插件卸载时的跨平台清理不属于本次工作流 API 增量。 ### API-06:先由 Core 提供磁盘读取,再接窗口 @@ -101,7 +101,7 @@ Run 自己启动的进程还必须随附加的调试会话释放。单独发送 三个方法仅在窗口实现 `WorkspaceReadHost` 后注册。没有远程读取适配器时拒绝远程工作区,不读取本机占位目录。监听与搜索也按各自的可选宿主接口注册,遵循相同的上下文检查。 -验证使用 `scripts/desktop/desktop-go.sh test ./internal/pluginservice ./internal/workbench -run 'TestWorkspaceReads|TestPluginWorkspaceReads' -count=1`。默认构建固定到 Core `9ab2336`,包含 [Core #190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) 并保留现有 #187 增量更新依赖;无需本地覆盖路径。测试读取真实临时文件,覆盖资源隔离、磁盘与未保存文档的区别及项目关闭取消;不依赖任何具体插件。Windows 的原生目录句柄行为须在 Windows 单独验证,本机 macOS 测试不能替代。 +验证使用 `scripts/desktop/desktop-go.sh test ./internal/pluginservice ./internal/workbench -run 'TestWorkspaceReads|TestPluginWorkspaceReads' -count=1`。默认构建固定到 Core `75e1480`,包含 [Core #190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190)、[#193](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/193)、[#194](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/194) 并保留现有 #187 增量更新依赖;无需本地覆盖路径。测试读取真实临时文件,覆盖资源隔离、磁盘与未保存文档的区别及项目关闭取消;不依赖任何具体插件。Windows 的原生目录句柄行为须在 Windows 单独验证,本机 macOS 测试不能替代。 ### API-07/08:Core 处理搜索与监听语义,Viva 只提供原生事件 @@ -113,6 +113,20 @@ Run 自己启动的进程还必须随附加的调试会话释放。单独发送 验证读取 Core 的共享 fixture 和真实临时文件,macOS 使用 Viva 的原生文件事件覆盖递归创建、原子保存、删除、初始重扫、三种释放入口及根目录替换后的最终重扫与释放,并用可控通知验证释放会取消在途发送。`scripts/desktop/desktop-go.sh test ./internal/core ./internal/pluginservice ./internal/workbench -run 'TestWorkspace(Reads|Find|Search|Watch)|TestPluginWorkspace' -count=1` 与定向竞态检查覆盖桥接、资源封装、未保存缓冲区隔离和关闭取消;监听测试没有用定时睡眠同步。Windows 原生运行按本次任务范围不验收,不能据 macOS 结果标为 Windows 已验证。 +### 通用工作流:先完成 Core 计划,再接原生呈现 + +输入、预览、对比、输出、进度、状态、剪贴板、文件管理器和 HTTP 共用 `plugins.workflow` 的严格计划。Core 拥有参数、默认值、权限、过滤排序、分页停止条件、输出增量和预算;Go 只连接原生 I/O、控件与会话生命周期。不要在窗口重新写过滤、扩展名检查或分页规则,这会使另一平台产生不同结果。 + +例如,同一插件会话与工作区内重复打开相同内联预览 ID,应更新原标签;另一个会话使用同 ID 则获得独立的只读标签。内联 Diff 使用与工作区文件无关的身份,不能因标题恰好等于真实文件名而获得保存能力。预览和输出不写磁盘缓存,不改变发行包、代码签名或 Sparkle 增量更新基线。 + +长期输出、进度和状态归属插件、会话与上下文。关闭上下文时先取消正在执行的原生调用,再排队移除窗口资源;不要在窗口关闭过程中同步等待窗口队列,否则可能死锁。HTTP 连接仅首次请求时创建并复用,没有 Cookie jar,也不自动跟随重定向。请求结束释放应答,工作区关闭后清理空闲连接;错误只保留安全分类,不把 URL、查询参数、头或正文交给日志。 + +视图刷新绑定当前显示的实例和会话。关闭先使旧回调失效,再停止观察,避免同路径重开视图接收旧刷新。树只保留已加载范围,用稳定 ID 保持选择和展开;Core 判断视口何时请求下一页,游标或范围不前进就停止。代价是桌面需维护原生控件的呈现状态,但不再维护一份共享规则。 + +未选择让插件用网页复制输入面板、输出台或状态栏:这会重复原生控件和权限生命周期。也未把 Cookie、身份验证或下载文件塞进通用 HTTP;这些需要各自的凭据和资源所有权契约。 + +验证:`scripts/desktop/desktop-go.sh test ./internal/workbench ./internal/pluginservice ./internal/pluginview -run 'Test(Workflow|BrowserOpensOnlyHTTP|SessionRefresh|WorkbenchDefaultLayout)' -count=1 -timeout=45s`;同范围逐测试计时与竞态检查。`TestVisualPluginWorkflow` 采集深浅主题、中英文的真实预览、输出、任务菜单、只读对比和快速选择截图,CI 上传 artifact。macOS 定向测试不替代原生 WebView、系统剪贴板、外部浏览器或 Windows 整机验收;整体矩阵保持 partial/pending。 + ## 适用范围 - `desktop/internal/pluginservice/`(backendhost、contexts、hostmethods、backendlaunch、languagesession、activation) @@ -124,3 +138,4 @@ Run 自己启动的进程还必须随附加的调试会话释放。单独发送 - `desktop/internal/workbench/`(pluginworkbench、pluginprompt、pluginterminals、plugincontent) - `desktop/internal/core/workspace_read.go`、`desktop/internal/core/workspace_find_watch.go`、`desktop/internal/pluginservice/hostworkspaceread.go`、`desktop/internal/pluginservice/hostworkspacefind.go`、`desktop/internal/pluginservice/hostworkspacewatch.go`、`desktop/internal/workbench/pluginworkspaceread.go` - `desktop/internal/editorview/hostedit.go`、`desktop/internal/termview/`、`desktop/internal/localshell/` +- `desktop/internal/core/plugin_workflow.go`、`desktop/internal/pluginservice/hostworkflow.go`、`desktop/internal/pluginservice/hostviewrefresh.go`、`desktop/internal/workbench/plugin_workflow.go`、`desktop/internal/pluginview/` diff --git a/.github/workflows/desktop-ci.yml b/.github/workflows/desktop-ci.yml index d9c172985..0dc3bda27 100644 --- a/.github/workflows/desktop-ci.yml +++ b/.github/workflows/desktop-ci.yml @@ -172,6 +172,31 @@ jobs: mkdir -p .artifacts/test-stability node --test --test-reporter=junit --test-reporter-destination=.artifacts/test-stability/core-cache.junit.xml scripts/desktop/desktop-core-cache.test.mjs + - name: Install CJK fonts for visual evidence + timeout-minutes: 3 + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends fonts-noto-cjk + fc-match 'sans-serif:lang=zh-cn' + + - name: Capture plugin workflow surfaces + id: plugin-workflow-visual + timeout-minutes: 5 + env: + LITHE_VISUAL_OUTPUT_DIR: ${{ github.workspace }}/.artifacts/plugin-workflow-visual + run: | + ./scripts/desktop/desktop-go.sh test -tags 'vivahead lithevisual' ./internal/workbench \ + -run '^TestVisualPluginWorkflow$' -count=1 -timeout=90s + + - name: Upload plugin workflow screenshots + if: ${{ !cancelled() && steps.plugin-workflow-visual.outcome != 'skipped' }} + uses: actions/upload-artifact@v7 + with: + name: plugin-workflow-visual-${{ runner.os }}-${{ runner.arch }} + path: .artifacts/plugin-workflow-visual/*.png + if-no-files-found: error + retention-days: 14 + - name: Vet and test run: ./scripts/desktop/check.sh diff --git a/desktop/internal/core/plugin_workflow.go b/desktop/internal/core/plugin_workflow.go new file mode 100644 index 000000000..18a0a95c0 --- /dev/null +++ b/desktop/internal/core/plugin_workflow.go @@ -0,0 +1,9 @@ +package core + +import "context" + +// PluginWorkflow runs the shared workflow validator or a bounded projection. +// Callers send only one request, candidate set, or output increment. +func (c *Client) PluginWorkflow(ctx context.Context, request any, result any) error { + return c.Execute(ctx, "plugins.workflow", request, result) +} diff --git a/desktop/internal/i18n/messages.go b/desktop/internal/i18n/messages.go index 90e7fc285..b5d559027 100644 --- a/desktop/internal/i18n/messages.go +++ b/desktop/internal/i18n/messages.go @@ -119,6 +119,7 @@ type TitleMessages struct { // ToolMessages name the tool windows on the stripes. type ToolMessages struct { + Output string Project string Commit string Structure string diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index 3ec7c6dec..a7268b929 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -1286,6 +1286,8 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.marketplace.permissionBuild": "Run build tools for your projects", "desktop.marketplace.permissionBuildConfigurationWatch": "Get notified when your projects’ build configuration changes", "desktop.marketplace.permissionBuildOptionsRead": "Read the build options set for your projects", + "desktop.marketplace.permissionClipboardRead": "Read text from your system clipboard", + "desktop.marketplace.permissionClipboardWrite": "Write text to your system clipboard", "desktop.marketplace.permissionCommandsInstall": "Install the command-line tools the plugin needs (asks you before each installation)", "desktop.marketplace.permissionCredentialsStore": "Save and read its own passwords and tokens in the system’s secure storage", "desktop.marketplace.permissionDebug": "Start a debugger for your programs", @@ -1302,17 +1304,24 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.marketplace.permissionKeymapsProvide": "Offer keymaps from other editors for you to import", "desktop.marketplace.permissionKeymapsReadSelectedSources": "Read keymap files only from the source you choose to import", "desktop.marketplace.permissionLanguageServerRequest": "Send requests to its own language servers", - "desktop.marketplace.permissionPreviewOpen": "Open HTML files in a preview", + "desktop.marketplace.permissionNetworkRequest": "Send HTTP requests with the host’s proxy and certificate settings", + "desktop.marketplace.permissionOutputWrite": "Create and manage its own output channels", + "desktop.marketplace.permissionPreviewOpen": "Preview Markdown and HTML files or read-only content", "desktop.marketplace.permissionRunStart": "Start and stop runs in the Run window", "desktop.marketplace.permissionRuntimesInstall": "Download and install the plugin’s declared runtime dependencies. Existing verified installations are reused across plugin updates.", + "desktop.marketplace.permissionStatusBarWrite": "Show its own status items and command buttons", "desktop.marketplace.permissionTerminalCreate": "Open and manage its own terminals", "desktop.marketplace.permissionToolchainsProvide": "Find installed tools, such as SDKs, and list them in Toolchains", "desktop.marketplace.permissionVcs": "Run version control tools for your projects", + "desktop.marketplace.permissionViewsRefresh": "Refresh its currently open views", + "desktop.marketplace.permissionWindowInput": "Ask you to select items or enter text, including masked passwords", "desktop.marketplace.permissionWindowMessages": "Show information, warning and error messages", + "desktop.marketplace.permissionWindowProgress": "Show progress and receive your cancellation requests", "desktop.marketplace.permissionWorkspaceFilesRead": "Read files and folders in your workspace", "desktop.marketplace.permissionWorkspaceFilesWatch": "Watch files in your workspace for changes", "desktop.marketplace.permissionWorkspaceFilesWrite": "Create, rename, copy and move to the trash files and folders in your workspace", "desktop.marketplace.permissionWorkspaceMetadata": "See the names and folders of open workspaces, without reading file contents", + "desktop.marketplace.permissionWorkspaceReveal": "Reveal workspace files in the file manager", "desktop.marketplace.permissionWorkspaceSearch": "Search file names and text in your workspace", "desktop.marketplace.programDetails": "Program declarations ({count}) — show / hide details", "desktop.marketplace.programsSettingsHelp": "Setting values only fill the places the program templates reserve for them, so changing a setting never changes the programs listed here and needs no new review.", @@ -1463,10 +1472,18 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.pluginChangelog.prerelease": "Pre-release", "desktop.pluginChangelog.retry": "Retry", "desktop.pluginChangelog.unsupported": "The changelog can only be read from GitHub repositories. Open the repository to see this plugin's changes.", + "desktop.pluginHost.backgroundTasks": "Plugin progress", + "desktop.pluginHost.commandFailed": "The plugin command failed. See the logs for details.", "desktop.pluginHost.contentFailed": "Could not open {uri}: the plugin did not provide its content.", + "desktop.pluginHost.diff": "Text Comparison", + "desktop.pluginHost.inputLimit": "The input is too long or contains unsupported control characters.", "desktop.pluginHost.messageDismiss": "Dismiss", "desktop.pluginHost.messageFrom": "Message from {plugin}", "desktop.pluginHost.messageOK": "OK", + "desktop.pluginHost.modified": "Modified", + "desktop.pluginHost.noOutput": "No output channels", + "desktop.pluginHost.original": "Original", + "desktop.pluginHost.output": "Output", "desktop.pluginHost.terminalAllow": "Run", "desktop.pluginHost.terminalConsentDetails": "Program: {program}\nArguments: {arguments}\nDirectory: {directory}", "desktop.pluginHost.terminalConsentTitle": "{plugin} wants to run a program in a terminal", @@ -5294,6 +5311,8 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.marketplace.permissionBuild": "为项目运行构建工具", "desktop.marketplace.permissionBuildConfigurationWatch": "在项目的构建配置变化时收到通知", "desktop.marketplace.permissionBuildOptionsRead": "读取为项目设置的构建选项", + "desktop.marketplace.permissionClipboardRead": "读取系统剪贴板中的文本", + "desktop.marketplace.permissionClipboardWrite": "向系统剪贴板写入文本", "desktop.marketplace.permissionCommandsInstall": "安装插件所需的命令行工具(每次安装前都会征得你的同意)", "desktop.marketplace.permissionCredentialsStore": "在系统的安全存储中保存和读取插件自己的密码和令牌", "desktop.marketplace.permissionDebug": "启动程序调试器", @@ -5310,17 +5329,24 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.marketplace.permissionKeymapsProvide": "提供可从其他编辑器导入的快捷键方案", "desktop.marketplace.permissionKeymapsReadSelectedSources": "只读取你选择导入的来源中的快捷键文件", "desktop.marketplace.permissionLanguageServerRequest": "向插件自己的语言服务器发送请求", - "desktop.marketplace.permissionPreviewOpen": "在预览中打开 HTML 文件", + "desktop.marketplace.permissionNetworkRequest": "使用宿主的代理和证书设置发送 HTTP 请求", + "desktop.marketplace.permissionOutputWrite": "创建和管理插件自己的输出通道", + "desktop.marketplace.permissionPreviewOpen": "预览 Markdown、HTML 文件或只读内容", "desktop.marketplace.permissionRunStart": "在“运行”窗口中启动和停止运行", "desktop.marketplace.permissionRuntimesInstall": "下载并安装插件声明的运行依赖。插件更新时会复用已有且验证合格的环境。", + "desktop.marketplace.permissionStatusBarWrite": "显示插件自己的状态项和命令按钮", "desktop.marketplace.permissionTerminalCreate": "打开和管理插件自己的终端", "desktop.marketplace.permissionToolchainsProvide": "查找已安装的工具(例如 SDK),并列在“工具链”中", "desktop.marketplace.permissionVcs": "为项目运行版本控制工具", + "desktop.marketplace.permissionViewsRefresh": "刷新插件当前打开的视图", + "desktop.marketplace.permissionWindowInput": "请求选择条目或输入文本,包括掩码密码", "desktop.marketplace.permissionWindowMessages": "显示提示、警告和错误消息", + "desktop.marketplace.permissionWindowProgress": "显示进度并接收你的取消请求", "desktop.marketplace.permissionWorkspaceFilesRead": "读取工作区中的文件和文件夹", "desktop.marketplace.permissionWorkspaceFilesWatch": "监视工作区中文件的变化", "desktop.marketplace.permissionWorkspaceFilesWrite": "在工作区中新建、重命名、复制文件和文件夹,或把它们移到废纸篓", "desktop.marketplace.permissionWorkspaceMetadata": "查看已打开工作区的名称和文件夹,不读取文件内容", + "desktop.marketplace.permissionWorkspaceReveal": "在文件管理器中显示工作区文件", "desktop.marketplace.permissionWorkspaceSearch": "在工作区中搜索文件名和文本", "desktop.marketplace.programDetails": "程序声明({count} 项)· 展开/收起详情", "desktop.marketplace.programsSettingsHelp": "设置值只会填入程序模板预留的位置,不会改变这里列出的程序,所以修改设置不需要重新审查。", @@ -5471,10 +5497,18 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.pluginChangelog.prerelease": "预发布", "desktop.pluginChangelog.retry": "重试", "desktop.pluginChangelog.unsupported": "更新日志只能从 GitHub 仓库读取。打开仓库查看这个插件的改动。", + "desktop.pluginHost.backgroundTasks": "插件进度", + "desktop.pluginHost.commandFailed": "插件命令执行失败,请查看日志。", "desktop.pluginHost.contentFailed": "无法打开 {uri}:插件没有提供其内容。", + "desktop.pluginHost.diff": "文本对比", + "desktop.pluginHost.inputLimit": "输入过长或包含不支持的控制字符。", "desktop.pluginHost.messageDismiss": "关闭", "desktop.pluginHost.messageFrom": "来自 {plugin} 的消息", "desktop.pluginHost.messageOK": "好", + "desktop.pluginHost.modified": "修改后的文本", + "desktop.pluginHost.noOutput": "暂无输出通道", + "desktop.pluginHost.original": "原始文本", + "desktop.pluginHost.output": "输出", "desktop.pluginHost.terminalAllow": "运行", "desktop.pluginHost.terminalConsentDetails": "程序:{program}\n参数:{arguments}\n目录:{directory}", "desktop.pluginHost.terminalConsentTitle": "{plugin} 想在终端中运行程序", diff --git a/desktop/internal/i18n/shell_messages.go b/desktop/internal/i18n/shell_messages.go index b978deec5..b7a1f2bd4 100644 --- a/desktop/internal/i18n/shell_messages.go +++ b/desktop/internal/i18n/shell_messages.go @@ -3,6 +3,7 @@ package i18n // toolMessages reads tools labels from the shared catalog. func toolMessages(language Language) ToolMessages { return ToolMessages{ + Output: Shared(language, "desktop.pluginHost.output"), Project: Shared(language, "workbench.project"), Commit: Shared(language, "workbench.commit"), Structure: Shared(language, "desktop.tools.structure"), diff --git a/desktop/internal/pluginservice/activation.go b/desktop/internal/pluginservice/activation.go index c9f0f5f35..5db39116d 100644 --- a/desktop/internal/pluginservice/activation.go +++ b/desktop/internal/pluginservice/activation.go @@ -127,6 +127,13 @@ func (s *Service) DetachWorkspaces() func() { } stopObserving := s.toolchainProviders.Invalidate() s.Contexts.CloseAll() + if s.workflow != nil { + s.workflow.httpMu.Lock() + if s.workflow.transport != nil { + s.workflow.transport.CloseIdleConnections() + } + s.workflow.httpMu.Unlock() + } stopBackend := s.Host.DetachAll() return func() { stopObserving() diff --git a/desktop/internal/pluginservice/hostactions_refresh_test.go b/desktop/internal/pluginservice/hostactions_refresh_test.go index dae8dda55..c55b6f429 100644 --- a/desktop/internal/pluginservice/hostactions_refresh_test.go +++ b/desktop/internal/pluginservice/hostactions_refresh_test.go @@ -47,6 +47,10 @@ func TestEditorActionRegistrationRefreshesOpenDocuments(t *testing.T) { // Use the real decoder: the lightweight host test kernel deliberately omits it. type realActionDecoder struct{ *notifyKernel } +func (k *realActionDecoder) PluginWorkflow(ctx context.Context, payload, result any) error { + return core.NewClient().PluginWorkflow(ctx, payload, result) +} + func (k *realActionDecoder) DecodeEditorActions(ctx context.Context, payload any) (json.RawMessage, error) { return core.NewClient().DecodeEditorActions(ctx, payload) } diff --git a/desktop/internal/pluginservice/hostdocuments.go b/desktop/internal/pluginservice/hostdocuments.go index ddb25ba67..816ce74f0 100644 --- a/desktop/internal/pluginservice/hostdocuments.go +++ b/desktop/internal/pluginservice/hostdocuments.go @@ -97,6 +97,20 @@ func (s *Service) AttachWorkbench(workbench Workbench) error { return nil } s.workbench = workbench + // Browser addresses are checked by Core too; never grant an unchecked path + // to a native opener when a host has no workflow validator. + if _, ok := s.kernel.(workflowKernel); ok { + if err := s.HostServices.Register(methodBrowserOpenExternal, s.handleBrowserOpenExternal); err != nil { + return err + } + } + if host, ok := workbench.(WorkflowHost); ok { + if kernel, ok := s.kernel.(workflowKernel); ok { + if err := s.registerWorkflows(host, kernel); err != nil { + return err + } + } + } if host, ok := workbench.(WorkspaceFindHost); ok { if err := s.registerWorkspaceFind(host); err != nil { return err @@ -125,7 +139,6 @@ func (s *Service) AttachWorkbench(workbench Workbench) error { {methodEditorInsertText, s.handleEditorInsertText}, {methodEditorOpen, s.handleEditorOpen}, {methodEditorReveal, s.handleEditorOpen}, - {methodBrowserOpenExternal, s.handleBrowserOpenExternal}, } { if err := s.HostServices.Register(entry.method, entry.handler); err != nil { return err @@ -453,23 +466,52 @@ func (s *Service) handleBrowserOpenExternal(ctx context.Context, params json.Raw Resource *Resource `json:"resource"` Unsaved string `json:"unsaved"` } + kernel, ok := s.kernel.(workflowKernel) + if !ok { + return nil, failure(CodeUnsupportedOption, "Browser request validation is unavailable.") + } + var prepared struct { + Params json.RawMessage `json:"params"` + } + if err := kernel.PluginWorkflow(ctx, map[string]any{"operation": "prepare", "method": "browser/openExternal", "params": params}, &prepared); err != nil { + return nil, workflowFailure(err) + } + params = prepared.Params if err := decodeStrict(params, &request); err != nil { return nil, invalidParams(err) } + caller, workspace, refusal := s.workspaceRequest(ctx, request.Context) + if refusal != nil { + return nil, refusal + } + ctx, cancel := context.WithCancel(ctx) + lease := s.resources.add(caller, workspace.ContextID, cancel) + defer s.resources.dispose(caller, lease) + defer cancel() if _, _, refusal := s.workspaceRequest(ctx, request.Context); refusal != nil { return nil, refusal } - if request.Resource != nil || request.Unsaved != "" { - // The system browser opens addresses; opening a saved workspace file - // needs a file: URL, which the platform helper refuses. - return nil, &pluginhost.Failure{Code: CodeUnsupportedOption, Message: "Opening a workspace file in the browser is not supported.", - Details: detailsOf(map[string]any{"option": "resource"})} + if err := ctx.Err(); err != nil { + return nil, hostFailureOf(err) } - address, err := httpURL(request.URL) - if err != nil { - return nil, failure(codeInvalidParams, "url must be an http or https address.") + if request.Resource != nil { + host, ok := s.workbench.(interface { + OpenBrowserResource(context.Context, string, string, string) (bool, error) + }) + if !ok { + return nil, failure(CodeUnsupportedOption, "Opening a saved HTML resource is unavailable.") + } + path, err := s.resolveResource(caller.PluginID, workspace, *request.Resource) + if err != nil { + return nil, hostFailureOf(err) + } + dirty, err := host.OpenBrowserResource(ctx, workspace.Path, path, request.Unsaved) + if err != nil { + return nil, hostFailureOf(err) + } + return marshalResult(map[string]any{"opened": true, "source": "disk", "hasUnsavedChanges": dirty}) } - if err := s.workbench.OpenExternal(ctx, address); err != nil { + if err := s.workbench.OpenExternal(ctx, request.URL); err != nil { return nil, hostFailureOf(err) } return marshalResult(map[string]any{"opened": true, "source": "web"}) diff --git a/desktop/internal/pluginservice/hostresources.go b/desktop/internal/pluginservice/hostresources.go index 348b6b710..a1e06e449 100644 --- a/desktop/internal/pluginservice/hostresources.go +++ b/desktop/internal/pluginservice/hostresources.go @@ -80,6 +80,15 @@ func (r *hostResources) dispose(caller pluginhost.Caller, id string) { } } +// forget drops a lease whose owner has already performed its cleanup. +func (r *hostResources) forget(caller pluginhost.Caller, id string) { + r.mu.Lock() + defer r.mu.Unlock() + if resource := r.byID[id]; resource != nil && resource.pluginID == caller.PluginID && resource.sessionID == caller.SessionID { + delete(r.byID, id) + } +} + func (r *hostResources) releaseWhere(match func(*hostResource) bool) { r.mu.Lock() var released []*hostResource diff --git a/desktop/internal/pluginservice/hostsurface.go b/desktop/internal/pluginservice/hostsurface.go index 5ff349f41..5c91e6001 100644 --- a/desktop/internal/pluginservice/hostsurface.go +++ b/desktop/internal/pluginservice/hostsurface.go @@ -5,7 +5,6 @@ import ( "encoding/json" "errors" "fmt" - "net/url" "os" "path/filepath" "strings" @@ -247,16 +246,6 @@ func relativePath(root, path string) *string { // RelativePath is exported for Workbench implementations. func RelativePath(root, path string) *string { return relativePath(root, path) } -// httpURL validates the URL browser/openExternal opens: absolute, http or https, -// with a host and no embedded credentials. -func httpURL(raw string) (string, error) { - parsed, err := url.Parse(raw) - if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" || parsed.User != nil || len(raw) > 4096 { - return "", fmt.Errorf("%w: only http and https addresses open", ErrResource) - } - return parsed.String(), nil -} - // detailsOf encodes failure details; details are optional, so an encoding // problem drops them rather than the failure. func detailsOf(details map[string]any) json.RawMessage { diff --git a/desktop/internal/pluginservice/hostview.go b/desktop/internal/pluginservice/hostview.go index 1ca0c01da..d2b8ad226 100644 --- a/desktop/internal/pluginservice/hostview.go +++ b/desktop/internal/pluginservice/hostview.go @@ -68,9 +68,18 @@ func (s *Service) CallView(ctx context.Context, call ViewCall) (json.RawMessage, } } var reference json.RawMessage + contextID := "" if workspace, ok := s.Contexts.ByPath(call.Workspace); ok && call.Workspace != "" { reference = mustMarshal(workspace.ContextRef) + contextID = workspace.ContextID } + var identity struct { + Instance string `json:"instance"` + } + if err := json.Unmarshal(call.Event, &identity); err != nil { + return nil, false, err + } + s.bindView(call.PluginID, session.Session.ID, contextID, identity.Instance) event, err := s.viewEvent(ctx, call) if err != nil { return nil, false, err diff --git a/desktop/internal/pluginservice/hostviewrefresh.go b/desktop/internal/pluginservice/hostviewrefresh.go new file mode 100644 index 000000000..595954966 --- /dev/null +++ b/desktop/internal/pluginservice/hostviewrefresh.go @@ -0,0 +1,53 @@ +package pluginservice + +import ( + "sync" + + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" +) + +type viewRefreshBinding struct { + pluginID, sessionID, contextID string + wake func() +} +type viewRefreshRegistry struct { + mu sync.Mutex + byInstance map[string]*viewRefreshBinding +} + +// WatchView registers a thread-safe invalidation callback for one visible view. +func (s *Service) WatchView(pluginID, instance string, wake func()) func() { + s.viewRefresh.mu.Lock() + if s.viewRefresh.byInstance == nil { + s.viewRefresh.byInstance = map[string]*viewRefreshBinding{} + } + binding := &viewRefreshBinding{pluginID: pluginID, wake: wake} + s.viewRefresh.byInstance[instance] = binding + s.viewRefresh.mu.Unlock() + return func() { + s.viewRefresh.mu.Lock() + if s.viewRefresh.byInstance[instance] == binding { + delete(s.viewRefresh.byInstance, instance) + } + s.viewRefresh.mu.Unlock() + } +} +func (s *Service) bindView(pluginID, sessionID, contextID, instance string) { + s.viewRefresh.mu.Lock() + defer s.viewRefresh.mu.Unlock() + if binding := s.viewRefresh.byInstance[instance]; binding != nil && binding.pluginID == pluginID { + binding.sessionID = sessionID + binding.contextID = contextID + } +} +func (s *Service) refreshView(caller pluginhost.Caller, contextID, instance string) bool { + s.viewRefresh.mu.Lock() + binding := s.viewRefresh.byInstance[instance] + if binding == nil || binding.pluginID != caller.PluginID || binding.sessionID != caller.SessionID || binding.contextID != contextID { + s.viewRefresh.mu.Unlock() + return false + } + s.viewRefresh.mu.Unlock() + binding.wake() + return true +} diff --git a/desktop/internal/pluginservice/hostworkbench_test.go b/desktop/internal/pluginservice/hostworkbench_test.go index 8ec56d464..88e8dc9da 100644 --- a/desktop/internal/pluginservice/hostworkbench_test.go +++ b/desktop/internal/pluginservice/hostworkbench_test.go @@ -124,7 +124,7 @@ func (t *fakeTerminal) Done() <-chan TerminalExit { return t.done } func openWorkbenchService(t *testing.T) (*Service, *fakeWorkbench, WorkspaceContext, *notifyKernel) { t.Helper() - kernel := ¬ifyKernel{} + kernel := &realActionDecoder{notifyKernel: ¬ifyKernel{}} service, err := Open(kernel, store.At(t.TempDir()), t.TempDir()) if err != nil { t.Fatal(err) @@ -137,7 +137,7 @@ func openWorkbenchService(t *testing.T) (*Service, *fakeWorkbench, WorkspaceCont if err != nil { t.Fatal(err) } - return service, workbench, service.Contexts.Open(root), kernel + return service, workbench, service.Contexts.Open(root), kernel.notifyKernel } func contextJSONOf(workspace WorkspaceContext) string { diff --git a/desktop/internal/pluginservice/hostworkflow.go b/desktop/internal/pluginservice/hostworkflow.go new file mode 100644 index 000000000..62572140f --- /dev/null +++ b/desktop/internal/pluginservice/hostworkflow.go @@ -0,0 +1,647 @@ +package pluginservice + +import ( + "context" + "crypto/tls" + "crypto/x509" + "encoding/base64" + "encoding/json" + "errors" + "io" + "net" + "net/http" + "os" + "strings" + "sync" + "time" + "unicode/utf8" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" +) + +// QuickItem has a stable backend identifier; filtering never changes its identity. +type QuickItem struct { + ID string `json:"id"` + Label string `json:"label"` + Description string `json:"description,omitempty"` + Detail string `json:"detail,omitempty"` + Picked bool `json:"picked,omitempty"` +} + +// QuickInput is one queued user choice. Password input is never prefilled. +type QuickInput struct { + PluginID, Title, Prompt, Placeholder, Value string + Password, CanPickMany, Pick bool + Items []QuickItem + Filter func(context.Context, string) ([]int, error) + Validate func(context.Context, string) (bool, error) +} + +// QuickResult distinguishes dismissal (nil) from an accepted empty input. +type QuickResult struct { + Value string `json:"value"` + IDs []string `json:"ids"` +} + +// PreviewRequest names one saved resource or a private read-only inline document. +type PreviewRequest struct { + PluginID, Owner, ID, Title, Text, Path, Kind, Presentation string + Range *Range +} + +// DiffRequest shows two bounded texts in the existing read-only Diff editor. +type DiffRequest struct { + Title, Original, Modified, OriginalTitle, ModifiedTitle string +} + +// OutputUpdate carries only newly completed lines and the unfinished line. +type OutputUpdate struct { + ID, Name, Action string + Lines []string + Open string + MaxLines int + MaxBytes int +} + +// ProgressUpdate belongs to one backend handle. Cancel sends a subscription event. +type ProgressUpdate struct { + ID, Title, Message string + Percentage *float64 + Cancellable bool + Remove bool + Cancel func() + MessageSet bool +} + +// StatusUpdate belongs to one session and opaque item ID. +type StatusUpdate struct { + ID, PluginID, Text, Tooltip, CommandID string + Priority int + Order []string + Remove bool +} + +// PluginWorkflow exposes Core projections to the native view surfaces. +func (s *Service) PluginWorkflow(ctx context.Context, request, result any) error { + kernel, ok := s.kernel.(workflowKernel) + if !ok { + return &HostError{Code: CodeUnsupportedOption, Message: "Plugin workflow projections are unavailable."} + } + return kernel.PluginWorkflow(ctx, request, result) +} + +// WorkflowHost is the native presentation boundary. Core validates and projects +// each operation before these methods run; the host never parses plugin business. +type WorkflowHost interface { + QuickInput(context.Context, string, QuickInput) (*QuickResult, error) + OpenPreview(context.Context, string, PreviewRequest) (PreviewResult, error) + ShowTextDiff(context.Context, string, DiffRequest) error + UpdateOutput(context.Context, string, OutputUpdate) error + UpdateProgress(context.Context, string, ProgressUpdate) error + UpdateStatus(context.Context, string, StatusUpdate) error + ReadClipboard(context.Context) (string, error) + WriteClipboard(context.Context, string) error + RevealResource(context.Context, string) error + OpenBrowserResource(context.Context, string, string, string) (bool, error) + // ReleaseWorkflow queues idempotent removal without waiting for the window. + // Context closure may itself run on the window thread. + ReleaseWorkflow(root, kind, id string) +} + +// PreviewResult preserves the existing document-open result for HTML previews. +type PreviewResult struct { + OpenResult + UsesLiveBuffer bool `json:"usesLiveBuffer"` + Presentation string `json:"presentation"` +} + +type workflowKernel interface { + PluginWorkflow(context.Context, any, any) error +} + +type workflowResource struct { + mu sync.Mutex + caller pluginhost.Caller + contextID, root string + id, lease, kind, name, open string + priority int + closed bool + cancelled bool + lifetime context.Context + stop context.CancelFunc +} + +type workflowResources struct { + statusMu sync.Mutex + httpMu sync.Mutex + transport *http.Transport + mu sync.Mutex + byID map[string]*workflowResource +} + +func (s *Service) registerWorkflows(host WorkflowHost, kernel workflowKernel) error { + s.workflow = &workflowResources{byID: map[string]*workflowResource{}} + methods := []string{"window/showQuickPick", "window/showInputBox", "preview/openMarkdown", "preview/openHTML", "editor/showDiff", "views/refresh", "output/create", "output/append", "output/clear", "output/show", "output/dispose", "progress/create", "progress/report", "progress/end", "statusBar/setItem", "statusBar/removeItem", "clipboard/readText", "clipboard/writeText", "workspace/reveal", "network/request"} + for _, method := range methods { + name := method + handler := func(ctx context.Context, params json.RawMessage) (json.RawMessage, *pluginhost.Failure) { + return s.handleWorkflow(ctx, host, kernel, name, params) + } + register := s.HostServices.Register + if strings.HasPrefix(method, "window/") { + register = s.HostServices.RegisterUserChoice + } + if err := register(pluginhost.MethodPrefix+method, handler); err != nil { + return err + } + } + return nil +} + +type workflowParams struct { + Context ContextRef `json:"context"` + Title string `json:"title"` + Prompt string `json:"prompt"` + Placeholder string `json:"placeholder"` + Value string `json:"value"` + Password bool `json:"password"` + CanPickMany bool `json:"canPickMany"` + Items []QuickItem `json:"items"` + Resource *Resource `json:"resource"` + Text string `json:"text"` + ID string `json:"id"` + Presentation string `json:"presentation"` + Range *Range `json:"range"` + Original string `json:"original"` + Modified string `json:"modified"` + OriginalTitle string `json:"originalTitle"` + ModifiedTitle string `json:"modifiedTitle"` + Instance string `json:"instance"` + Name string `json:"name"` + ChannelID string `json:"channelID"` + ProgressID string `json:"progressID"` + Cancellable bool `json:"cancellable"` + Message *string `json:"message"` + Percentage *float64 `json:"percentage"` + Tooltip string `json:"tooltip"` + CommandID string `json:"commandID"` + Priority int `json:"priority"` + URL string `json:"url"` + Method string `json:"method"` + Headers map[string]string `json:"headers"` + Body string `json:"body"` + TimeoutMilliseconds int `json:"timeoutMilliseconds"` + MaximumResponseBytes int `json:"maximumResponseBytes"` +} + +func (s *Service) handleWorkflow(ctx context.Context, host WorkflowHost, kernel workflowKernel, method string, raw json.RawMessage) (json.RawMessage, *pluginhost.Failure) { + _, session, refusal := s.buildCaller(ctx) + if refusal != nil { + return nil, refusal + } + var prepared struct { + Params workflowParams `json:"params"` + Limits struct { + TextBytes int `json:"textBytes"` + Resources int `json:"resources"` + HTTPHeaderBytes int `json:"httpHeaderBytes"` + } `json:"limits"` + } + if err := kernel.PluginWorkflow(ctx, map[string]any{"operation": "prepare", "method": method, "params": raw, "manifest": session.manifest}, &prepared); err != nil { + return nil, workflowFailure(err) + } + p := prepared.Params + caller, workspace, refusal := s.workspaceRequest(ctx, p.Context) + if refusal != nil { + return nil, refusal + } + // Tie native I/O and queued input to context closure as well as request cancellation. + ctx, cancel := context.WithCancel(ctx) + lease := s.resources.add(caller, workspace.ContextID, cancel) + defer s.resources.dispose(caller, lease) + defer cancel() + if _, _, refusal := s.workspaceRequest(ctx, p.Context); refusal != nil { + return nil, refusal + } + if session.isEnded() { + return nil, failure(pluginhost.CodeCancelled, "The requesting backend session ended.") + } + if err := ctx.Err(); err != nil { + return nil, hostFailureOf(err) + } + root := workspace.Path + switch method { + case "window/showQuickPick", "window/showInputBox": + release, refusal := s.messages.admit(caller.PluginID) + if refusal != nil { + return nil, refusal + } + defer release() + input := QuickInput{PluginID: caller.PluginID, Title: p.Title, Prompt: p.Prompt, Placeholder: p.Placeholder, Value: p.Value, Password: p.Password, CanPickMany: p.CanPickMany, Items: p.Items, Pick: strings.HasSuffix(method, "showQuickPick")} + input.Filter = func(ctx context.Context, query string) ([]int, error) { + var result struct { + Indices []int `json:"indices"` + } + err := kernel.PluginWorkflow(ctx, map[string]any{"operation": "quickPick", "items": p.Items, "query": query}, &result) + return result.Indices, err + } + input.Validate = func(ctx context.Context, value string) (bool, error) { + var result struct { + Valid bool `json:"valid"` + } + err := kernel.PluginWorkflow(ctx, map[string]any{"operation": "input", "pick": input.Pick, "value": value}, &result) + return result.Valid, err + } + result, err := host.QuickInput(ctx, root, input) + if err != nil { + return nil, hostFailureOf(err) + } + if result == nil { + return json.RawMessage("null"), nil + } + if input.Pick { + return marshalResult(map[string]any{"selectedIDs": result.IDs}) + } + return marshalResult(map[string]any{"value": result.Value}) + case "preview/openMarkdown", "preview/openHTML": + request := PreviewRequest{PluginID: caller.PluginID, Owner: caller.SessionID + ":" + workspace.ContextID, ID: p.ID, Title: p.Title, Text: p.Text, Kind: strings.TrimPrefix(method, "preview/open"), Presentation: p.Presentation, Range: p.Range} + if p.Resource != nil { + path, err := s.resolveResource(caller.PluginID, workspace, *p.Resource) + if err != nil { + return nil, hostFailureOf(err) + } + request.Path = path + } + result, err := host.OpenPreview(ctx, root, request) + if err != nil { + return nil, hostFailureOf(err) + } + return marshalResult(result) + case "editor/showDiff": + if err := host.ShowTextDiff(ctx, root, DiffRequest{Title: p.Title, Original: p.Original, Modified: p.Modified, OriginalTitle: p.OriginalTitle, ModifiedTitle: p.ModifiedTitle}); err != nil { + return nil, hostFailureOf(err) + } + return marshalResult(map[string]bool{"opened": true}) + case "views/refresh": + if !s.refreshView(caller, workspace.ContextID, p.Instance) { + return nil, failure(CodeNotFound, "The view instance is no longer open.") + } + return marshalResult(map[string]bool{"refreshed": true}) + case "clipboard/readText": + text, err := host.ReadClipboard(ctx) + if err != nil { + return nil, hostFailureOf(err) + } + if len(text) > prepared.Limits.TextBytes { + return nil, failure(CodeLimitExceeded, "Clipboard text exceeds the transfer budget.") + } + return marshalResult(map[string]string{"text": text}) + case "clipboard/writeText": + if err := host.WriteClipboard(ctx, p.Text); err != nil { + return nil, hostFailureOf(err) + } + return nil, nil + case "workspace/reveal": + path, err := s.resolveResource(caller.PluginID, workspace, *p.Resource) + if err != nil { + return nil, hostFailureOf(err) + } + if _, err := os.Stat(path); err != nil { + return nil, hostFailureOf(err) + } + if err := host.RevealResource(ctx, path); err != nil { + return nil, hostFailureOf(err) + } + return nil, nil + case "network/request": + return managedRequest(ctx, p, s.workflow.httpTransport(prepared.Limits.HTTPHeaderBytes)) + default: + return s.workflowResourceRequest(ctx, host, kernel, caller, workspace, p, method, prepared.Limits.Resources) + } +} + +// managedRequest inherits the application's proxy and platform certificate roots. +// Redirects remain responses so credentials never travel to a different origin. +func managedRequest(ctx context.Context, p workflowParams, transport *http.Transport) (json.RawMessage, *pluginhost.Failure) { + ctx, cancel := context.WithTimeout(ctx, time.Duration(p.TimeoutMilliseconds)*time.Millisecond) + defer cancel() + request, err := http.NewRequestWithContext(ctx, p.Method, p.URL, strings.NewReader(p.Body)) + if err != nil { + return nil, failure(codeInvalidParams, "The HTTP request could not be created.") + } + for key, value := range p.Headers { + request.Header.Set(key, value) + } + client := &http.Client{Transport: transport, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + response, err := client.Do(request) + if err != nil { + if ctx.Err() != nil { + return nil, hostFailureOf(ctx.Err()) + } + // net/http exposes no typed header-budget error. Match its fixed native + // diagnostic only; the URL-wrapping error is never returned or logged. + cause := err + for errors.Unwrap(cause) != nil { + cause = errors.Unwrap(cause) + } + if strings.HasPrefix(cause.Error(), "net/http: server response headers exceeded ") || cause.Error() == "http2: response header list larger than advertised limit" { + return nil, failure(CodeLimitExceeded, "The HTTP response headers exceed their byte budget.") + } + return nil, failure(pluginhost.CodeHostFailure, "HTTP request failed: "+httpFailureReason(err)+".") + } + defer response.Body.Close() + body, err := io.ReadAll(io.LimitReader(response.Body, int64(p.MaximumResponseBytes)+1)) + if err != nil { + if ctx.Err() != nil { + return nil, hostFailureOf(ctx.Err()) + } + return nil, failure(pluginhost.CodeHostFailure, "HTTP response read failed: "+httpFailureReason(err)+".") + } + if len(body) > p.MaximumResponseBytes { + return nil, failure(CodeLimitExceeded, "The HTTP response exceeds its byte budget.") + } + encoding, text := "utf8", string(body) + if !utf8.Valid(body) { + encoding, text = "base64", base64.StdEncoding.EncodeToString(body) + } + return marshalResult(map[string]any{"status": response.StatusCode, "headers": response.Header, "body": text, "encoding": encoding}) +} + +// One transport shares native connections without sharing cookies or credentials. +// Closing the workspace closes its idle sockets; requests own cancellable leases. +func (r *workflowResources) httpTransport(headerBytes int) *http.Transport { + r.httpMu.Lock() + defer r.httpMu.Unlock() + if r.transport == nil { + r.transport = http.DefaultTransport.(*http.Transport).Clone() + r.transport.MaxResponseHeaderBytes = int64(headerBytes) + } + return r.transport +} + +// Transport errors can contain a full URL and its secret query. Classify native +// errors without copying their text into the RPC response or unified log. +func httpFailureReason(err error) string { + var dns *net.DNSError + var certificate *tls.CertificateVerificationError + var unknown x509.UnknownAuthorityError + var operation *net.OpError + switch { + case errors.As(err, &dns): + return "dns_resolution" + case errors.As(err, &certificate), errors.As(err, &unknown): + return "tls_certificate" + case errors.Is(err, io.ErrUnexpectedEOF): + return "unexpected_eof" + case errors.As(err, &operation): + if operation.Timeout() { + return "network_timeout" + } + if operation.Op == "dial" { + return "connection_failed" + } + return "connection_io" + default: + return "http_protocol_or_response_headers" + } +} + +func (s *Service) workflowResourceRequest(ctx context.Context, host WorkflowHost, kernel workflowKernel, caller pluginhost.Caller, workspace WorkspaceContext, p workflowParams, method string, limit int) (json.RawMessage, *pluginhost.Failure) { + kind, _, _ := strings.Cut(method, "/") + if kind == "statusBar" { + s.workflow.statusMu.Lock() + defer s.workflow.statusMu.Unlock() + } + creating := method == "output/create" || method == "progress/create" || method == "statusBar/setItem" + id := p.ChannelID + if kind == "progress" { + id = p.ProgressID + } + if kind == "statusBar" { + id = caller.SessionID + ":" + workspace.ContextID + ":" + p.ID + } + s.workflow.mu.Lock() + r := s.workflow.byID[id] + fresh := creating && r == nil + if fresh { + lifetime, stop := context.WithCancel(context.WithoutCancel(ctx)) + r = &workflowResource{caller: caller, contextID: workspace.ContextID, root: workspace.Path, kind: kind, name: p.Name, lifetime: lifetime, stop: stop} + // Hold the new resource until its identifiers are published. A concurrent + // context/session close may already have taken its lease for disposal. + r.mu.Lock() + resource := r + r.lease = s.resources.addLimited(caller, workspace.ContextID, func() { s.cleanupWorkflow(host, resource) }, limit) + if r.lease == "" { + stop() + r.mu.Unlock() + s.workflow.mu.Unlock() + return nil, failure(CodeLimitExceeded, "Too many workflow resources.") + } + if kind != "statusBar" { + id = r.lease + } + r.id = id + s.workflow.byID[id] = r + } + s.workflow.mu.Unlock() + if r == nil { + return nil, failure(CodeNotFound, "The workflow resource is no longer available.") + } + if !fresh { + r.mu.Lock() + } + defer r.mu.Unlock() + if r.closed || r.caller != caller || r.contextID != workspace.ContextID || r.kind != kind { + return nil, failure(CodeNotFound, "The workflow resource is not owned by this session and context.") + } + ctx, cancel := context.WithCancel(ctx) + stopClosing := context.AfterFunc(r.lifetime, cancel) + defer stopClosing() + defer cancel() + // A newly allocated handle must be removed even when validation or native + // creation fails after registration. Disposal runs after r.mu is released. + succeeded := !fresh + defer func() { + if !succeeded { + r.stop() + s.resources.forget(caller, r.lease) + } + }() + if _, session, refusal := s.buildCaller(ctx); refusal != nil || session.isEnded() { + if fresh { + r.closed = true + s.forgetWorkflow(r) + } + return nil, failure(pluginhost.CodeCancelled, "The requesting backend session ended.") + } + if _, _, refusal := s.workspaceRequest(ctx, p.Context); refusal != nil { + if fresh { + r.closed = true + s.forgetWorkflow(r) + } + return nil, refusal + } + if err := ctx.Err(); err != nil { + if fresh { + r.closed = true + s.forgetWorkflow(r) + } + return nil, hostFailureOf(err) + } + var err error + switch method { + case "output/create": + err = host.UpdateOutput(ctx, r.root, OutputUpdate{ID: id, Name: p.Name, Action: "create"}) + case "output/append": + var projection struct { + Lines []string `json:"lines"` + Open string `json:"open"` + MaxLines int `json:"maxLines"` + MaxBytes int `json:"maxBytes"` + } + err = kernel.PluginWorkflow(ctx, map[string]any{"operation": "output", "open": r.open, "text": p.Text}, &projection) + if err == nil { + err = host.UpdateOutput(ctx, r.root, OutputUpdate{ID: id, Action: "append", Lines: projection.Lines, Open: projection.Open, MaxLines: projection.MaxLines, MaxBytes: projection.MaxBytes}) + if err == nil { + r.open = projection.Open + } + } + case "output/clear": + err = host.UpdateOutput(ctx, r.root, OutputUpdate{ID: id, Action: "clear"}) + if err == nil { + r.open = "" + } + case "output/show": + err = host.UpdateOutput(ctx, r.root, OutputUpdate{ID: id, Action: "show"}) + case "progress/create", "progress/report": + if r.cancelled { + return nil, failure(pluginhost.CodeCancelled, "The user cancelled this operation.") + } + update := ProgressUpdate{ID: id, Title: p.Title, Percentage: p.Percentage, Cancellable: p.Cancellable, MessageSet: p.Message != nil} + if p.Message != nil { + update.Message = *p.Message + } + if method == "progress/create" && p.Cancellable { + update.Cancel = func() { s.cancelWorkflowProgress(r) } + } + err = host.UpdateProgress(ctx, r.root, update) + case "statusBar/setItem": + s.workflow.mu.Lock() + items := []map[string]any{} + for _, item := range s.workflow.byID { + if item.kind == "statusBar" && item.contextID == workspace.ContextID { + priority := item.priority + if item == r { + priority = p.Priority + } + items = append(items, map[string]any{"id": item.id, "priority": priority}) + } + } + s.workflow.mu.Unlock() + var projection struct { + IDs []string `json:"ids"` + } + err = kernel.PluginWorkflow(ctx, map[string]any{"operation": "status", "items": items}, &projection) + if err == nil { + err = host.UpdateStatus(ctx, r.root, StatusUpdate{ID: id, PluginID: caller.PluginID, Text: p.Text, Tooltip: p.Tooltip, CommandID: p.CommandID, Priority: p.Priority, Order: projection.IDs}) + } + if err == nil { + s.workflow.mu.Lock() + r.priority = p.Priority + s.workflow.mu.Unlock() + } + case "output/dispose", "progress/end", "statusBar/removeItem": + err = s.removeWorkflowUI(ctx, host, r) + if err == nil { + r.stop() + r.closed = true + s.forgetWorkflow(r) + s.resources.forget(caller, r.lease) + } + } + if err != nil { + if fresh { + r.closed = true + s.forgetWorkflow(r) + s.cleanupWorkflowUI(host, r) + } + return nil, hostFailureOf(err) + } + succeeded = true + if creating { + switch kind { + case "output": + return marshalResult(map[string]string{"channelID": id}) + case "progress": + return marshalResult(map[string]string{"progressID": id, "subscriptionID": r.lease}) + default: + return marshalResult(map[string]string{"id": p.ID}) + } + } + return nil, nil +} + +func (s *Service) forgetWorkflow(r *workflowResource) { + s.workflow.mu.Lock() + delete(s.workflow.byID, r.id) + s.workflow.mu.Unlock() +} + +func (s *Service) removeWorkflowUI(ctx context.Context, host WorkflowHost, r *workflowResource) error { + switch r.kind { + case "output": + return host.UpdateOutput(ctx, r.root, OutputUpdate{ID: r.id, Action: "dispose"}) + case "progress": + return host.UpdateProgress(ctx, r.root, ProgressUpdate{ID: r.id, Remove: true}) + default: + return host.UpdateStatus(ctx, r.root, StatusUpdate{ID: r.id, Remove: true}) + } +} +func (s *Service) cleanupWorkflowUI(host WorkflowHost, r *workflowResource) { + host.ReleaseWorkflow(r.root, r.kind, r.id) +} +func (s *Service) cleanupWorkflow(host WorkflowHost, r *workflowResource) { + // Cancel a native call before taking its lock: that call may be waiting for + // the very window thread that is closing this context. + r.stop() + r.mu.Lock() + defer r.mu.Unlock() + if r.closed { + return + } + r.closed = true + s.forgetWorkflow(r) + s.cleanupWorkflowUI(host, r) +} + +// Native UI invokes this on its owned project worker, never on the window thread. +func (s *Service) cancelWorkflowProgress(r *workflowResource) { + r.mu.Lock() + if r.closed || r.cancelled { + r.mu.Unlock() + return + } + r.cancelled = true + r.mu.Unlock() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + // Core records delivery failures at the lsp.hostNotify boundary. A session + // closing before delivery has no recipient and needs no retry. + _, err := s.kernel.SendPluginHostNotification(ctx, r.caller.SessionID, notifySubscription, mustMarshal(map[string]any{"subscriptionID": r.lease, "sequence": 1, "event": map[string]bool{"cancelled": true}})) + if err != nil { // log-exempt: 同一次失败已经记录过:Core records host notification delivery. + return + } +} + +// workflowFailure keeps Core's public refusal when native preparation fails. +func workflowFailure(err error) *pluginhost.Failure { + var coreErr *core.Error + if errors.As(err, &coreErr) && coreErr.Code == core.CodeInvalidRequest { + switch coreErr.Details { + case codeInvalidParams, CodeUnsupportedOption: + return failure(coreErr.Details, coreErr.Message) + } + } + return hostFailureOf(err) +} diff --git a/desktop/internal/pluginservice/hostworkflow_test.go b/desktop/internal/pluginservice/hostworkflow_test.go new file mode 100644 index 000000000..ebc71f1de --- /dev/null +++ b/desktop/internal/pluginservice/hostworkflow_test.go @@ -0,0 +1,215 @@ +package pluginservice + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" +) + +type workflowWindow struct { + *fakeWorkbench + mu sync.Mutex + progress ProgressUpdate + released []string + blockOutput bool + entered chan struct{} +} + +func (*workflowWindow) QuickInput(context.Context, string, QuickInput) (*QuickResult, error) { + return nil, nil +} +func (*workflowWindow) OpenPreview(context.Context, string, PreviewRequest) (PreviewResult, error) { + return PreviewResult{}, nil +} +func (*workflowWindow) ShowTextDiff(context.Context, string, DiffRequest) error { return nil } +func (w *workflowWindow) UpdateOutput(ctx context.Context, _ string, _ OutputUpdate) error { + if w.blockOutput { + close(w.entered) + <-ctx.Done() // Request and test deadlines bound the simulated window wait. + return ctx.Err() + } + return nil +} +func (w *workflowWindow) UpdateProgress(_ context.Context, _ string, update ProgressUpdate) error { + w.mu.Lock() + w.progress = update + w.mu.Unlock() + return nil +} +func (*workflowWindow) UpdateStatus(context.Context, string, StatusUpdate) error { return nil } +func (*workflowWindow) ReadClipboard(context.Context) (string, error) { return "", nil } +func (*workflowWindow) WriteClipboard(context.Context, string) error { return nil } +func (*workflowWindow) RevealResource(context.Context, string) error { return nil } +func (*workflowWindow) OpenBrowserResource(context.Context, string, string, string) (bool, error) { + return false, nil +} +func (w *workflowWindow) ReleaseWorkflow(_, kind, id string) { + w.mu.Lock() + w.released = append(w.released, kind+":"+id) + w.mu.Unlock() +} + +func workflowService(t *testing.T, window *workflowWindow) (*Service, WorkspaceContext, *notifyKernel) { + t.Helper() + if window.fakeWorkbench == nil { + window.fakeWorkbench = &fakeWorkbench{} + } + kernel := &realActionDecoder{notifyKernel: ¬ifyKernel{}} + service, workspace := openEditorServiceWith(t, kernel, window) + runningActionSession(service, "a", "session-a") + runningActionSession(service, "b", "session-b") + t.Cleanup(func() { + service.Contexts.CloseAll() + if service.workflow.transport != nil { + service.workflow.transport.CloseIdleConnections() + } + }) + return service, workspace, kernel.notifyKernel +} + +func TestWorkflowProgressOwnershipCancellationAndContextCleanup(t *testing.T) { + window := &workflowWindow{} + service, workspace, kernel := workflowService(t, window) + result, refusal := respond(t, service, "a", "progress/create", `{`+contextJSONOf(workspace)+`,"title":"Import","cancellable":true}`) + if refusal != nil { + t.Fatal(refusal) + } + var created struct{ ProgressID, SubscriptionID string } + if err := json.Unmarshal(result, &created); err != nil || created.ProgressID == "" || created.ProgressID != created.SubscriptionID { + t.Fatalf("create=%s, %v", result, err) + } + params := `{` + contextJSONOf(workspace) + `,"progressID":"` + created.ProgressID + `","percentage":25}` + if _, refusal := respond(t, service, "b", "progress/report", params); refusal == nil || refusal.Code != CodeNotFound { + t.Fatalf("foreign report=%+v", refusal) + } + window.progress.Cancel() + window.progress.Cancel() + kernel.mu.Lock() + notifications := append([]string(nil), kernel.sent...) + kernel.mu.Unlock() + if len(notifications) != 1 || !strings.Contains(notifications[0], `"cancelled":true`) { + t.Fatalf("cancel notifications=%v", notifications) + } + if _, refusal := respond(t, service, "a", "progress/report", params); refusal == nil || refusal.Code != pluginhost.CodeCancelled { + t.Fatalf("cancelled report=%+v", refusal) + } + service.Contexts.Close(workspace.Path) + if len(window.released) != 1 || window.released[0] != "progress:"+created.ProgressID { + t.Fatalf("released=%v", window.released) + } + if len(service.workflow.byID) != 0 { + t.Fatal("context retained workflow resources") + } +} + +func TestWorkflowClosingContextCancelsNativeCreationWithoutWaitingForWindow(t *testing.T) { + window := &workflowWindow{blockOutput: true, entered: make(chan struct{})} + service, workspace, _ := workflowService(t, window) + ctx, cancel := context.WithTimeout(callerContext("a"), 3*time.Second) + defer cancel() + done := make(chan *pluginhost.Failure, 1) + go func() { + _, refusal := service.HostServices.Respond(ctx, "lithe/host/output/create", json.RawMessage(`{`+contextJSONOf(workspace)+`,"name":"Build"}`)) + done <- refusal + }() + select { + case <-window.entered: + case <-ctx.Done(): + t.Fatal("native creation did not start") + } + closed := make(chan struct{}) + go func() { service.Contexts.Close(workspace.Path); close(closed) }() + select { + case <-closed: + case <-ctx.Done(): + t.Fatal("context close waited for the native window") + } + select { + case refusal := <-done: + if refusal == nil || refusal.Code != pluginhost.CodeCancelled { + t.Fatalf("cancel=%+v", refusal) + } + case <-ctx.Done(): + t.Fatal("native creation did not terminate") + } + if len(service.workflow.byID) != 0 { + t.Fatal("failed creation leaked a handle") + } +} + +func TestWorkflowHTTPRedirectBinaryBudgetAndContextCancellation(t *testing.T) { + window := &workflowWindow{} + service, workspace, _ := workflowService(t, window) + var redirected atomic.Int32 + started := make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/redirect": + w.Header().Set("Location", "/target") + w.Header().Set("Set-Cookie", "session=private") + w.WriteHeader(http.StatusFound) + case "/target": + redirected.Add(1) + case "/binary": + if r.Header.Get("Cookie") != "" { + t.Error("a cookie leaked between requests") + } + _, _ = w.Write([]byte{0xff, 0x00, 0xfe}) + case "/headers": + w.Header().Set("X-Large", strings.Repeat("h", 20*1024)) + case "/wait": + close(started) + select { + case <-r.Context().Done(): + case <-time.After(4 * time.Second): + t.Error("request was not cancelled") + } + default: + _, _ = w.Write([]byte("large")) + } + })) + t.Cleanup(server.Close) + request := func(ctx context.Context, path string, budget int) (json.RawMessage, *pluginhost.Failure) { + params := mustMarshal(map[string]any{"context": workspace.ContextRef, "url": server.URL + path, "maximumResponseBytes": budget}) + return service.HostServices.Respond(ctx, "lithe/host/network/request", params) + } + ctx, cancel := context.WithTimeout(callerContext("a"), 5*time.Second) + defer cancel() + result, refusal := request(ctx, "/redirect", 128) + if refusal != nil || !strings.Contains(string(result), `"status":302`) || redirected.Load() != 0 { + t.Fatalf("redirect=%s %+v, followed=%d", result, refusal, redirected.Load()) + } + result, refusal = request(ctx, "/binary", 128) + if refusal != nil || !strings.Contains(string(result), `"encoding":"base64"`) || !strings.Contains(string(result), `"body":"/wD+"`) { + t.Fatalf("binary=%s %+v", result, refusal) + } + for _, path := range []string{"/body", "/headers"} { + if _, refusal = request(ctx, path, 2); refusal == nil || refusal.Code != CodeLimitExceeded { + t.Fatalf("%s budget=%+v", path, refusal) + } + } + done := make(chan *pluginhost.Failure, 1) + go func() { _, refusal := request(ctx, "/wait?token=private", 128); done <- refusal }() + select { + case <-started: + case <-ctx.Done(): + t.Fatal("HTTP request did not start") + } + service.Contexts.Close(workspace.Path) + select { + case refusal := <-done: + if refusal == nil || refusal.Code != pluginhost.CodeCancelled || strings.Contains(refusal.Message, "private") { + t.Fatalf("cancel=%+v", refusal) + } + case <-ctx.Done(): + t.Fatal("context closure did not cancel HTTP") + } +} diff --git a/desktop/internal/pluginservice/pluginservice.go b/desktop/internal/pluginservice/pluginservice.go index 80a0dd4f9..0e89cbf3c 100644 --- a/desktop/internal/pluginservice/pluginservice.go +++ b/desktop/internal/pluginservice/pluginservice.go @@ -116,7 +116,9 @@ type Service struct { virtualHost VirtualDocumentHost providers *contentProviders // resources are the subscriptions, providers and terminals backends hold. - resources *hostResources + resources *hostResources + workflow *workflowResources + viewRefresh viewRefreshRegistry // Runs owns the processes backends start through run/start. Runs *Runs // LanguageTool resolves an optional installation for a backend-resolved diff --git a/desktop/internal/pluginservice/toolcommands.go b/desktop/internal/pluginservice/toolcommands.go index 66c630f63..e7a0d29b9 100644 --- a/desktop/internal/pluginservice/toolcommands.go +++ b/desktop/internal/pluginservice/toolcommands.go @@ -57,7 +57,7 @@ func (snapshot InstalledSnapshot) ToolCommands() ([]ToolCommand, error) { } first := len(commands) for _, command := range declared.UI.Commands { - if command.ID == "" || command.ToolWindowID == "" { + if command.ID == "" { continue } commands = append(commands, ToolCommand{ diff --git a/desktop/internal/pluginview/node.go b/desktop/internal/pluginview/node.go index 30829aa91..24285ac55 100644 --- a/desktop/internal/pluginview/node.go +++ b/desktop/internal/pluginview/node.go @@ -48,7 +48,8 @@ type Node struct { Rows [][]string `json:"rows,omitempty"` Tool string `json:"tool,omitempty"` // Choose makes a tool row in a settings region also the tool's picker. - Choose bool `json:"choose,omitempty"` + Choose bool `json:"choose,omitempty"` + Cursor string `json:"cursor,omitempty"` // Height, ViewBox, Pan, Zoom, On and Nodes describe a canvas. Height float64 `json:"height,omitempty"` ViewBox [4]float64 `json:"viewBox,omitempty"` @@ -67,14 +68,15 @@ type Option struct { // Item is a keyValue pair (Label, Value, Tone) or a tree item (ID, Label, Icon, // Detail, Expanded, Children). type Item struct { - ID string `json:"id,omitempty"` - Label string `json:"label"` - Value string `json:"value,omitempty"` - Tone string `json:"tone,omitempty"` - Icon string `json:"icon,omitempty"` - Detail string `json:"detail,omitempty"` - Expanded bool `json:"expanded,omitempty"` - Children []Item `json:"children,omitempty"` + ID string `json:"id,omitempty"` + Label string `json:"label"` + Value string `json:"value,omitempty"` + Tone string `json:"tone,omitempty"` + Icon string `json:"icon,omitempty"` + Detail string `json:"detail,omitempty"` + Expanded bool `json:"expanded,omitempty"` + HasChildren bool `json:"hasChildren,omitempty"` + Children []Item `json:"children,omitempty"` } // Column is one column of a table. diff --git a/desktop/internal/pluginview/render.go b/desktop/internal/pluginview/render.go index 7e6ca2be3..e1f2939b5 100644 --- a/desktop/internal/pluginview/render.go +++ b/desktop/internal/pluginview/render.go @@ -4,6 +4,7 @@ import ( "context" "errors" "strconv" + "time" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" @@ -591,7 +592,43 @@ func (r *renderer) tree(c ui.C, n *Node) { toggled = i item := state.rows[i].item open := !state.expanded(item) - c.After(func() { state.open[item.ID] = open }) + c.After(func() { + state.open[item.ID] = open + if item.HasChildren { + r.s.Send(Event{Name: "expand", Node: n.ID, Item: item.ID, Value: open}) + } + }) + } + // Only viewport changes cross Core; a failed event pauses until explicit Retry. + if r.s.options.Page != nil { + if state.paging == nil { + state.paging = ui.NewEffectKeyed(func(ctx context.Context, key pageKey) (bool, error) { + bounded, cancel := context.WithTimeout(ctx, 2*time.Second) + defer cancel() + var result struct { + Load bool `json:"load"` + } + err := r.s.options.Page(bounded, map[string]any{"operation": "treePage", "cursor": key.Cursor, "lastCursor": key.LastCursor, "count": key.Count, "lastCount": key.LastCount, "rows": key.Rows, "lastVisible": key.Visible}, &result) + return result.Load, err + }) + } + _, last := state.tree.Visible() + key := pageKey{n.Cursor, state.cursor, len(n.Items), state.count, len(state.rows), max(0, last)} + ui.Effect(c.Part("paging"), state.paging, key) + if load, err, ok := state.paging.Take(); ok { + if err != nil { + if r.s.options.Failed != nil { + r.s.options.Failed(err) + } + } else if load && r.s.Err() == nil { + cursor, count := n.Cursor, len(n.Items) + c.After(func() { + state.cursor = cursor + state.count = count + r.s.Send(Event{Name: "loadMore", Node: n.ID, Cursor: cursor}) + }) + } + } } i, ok := state.tree.Chosen() if !ok { @@ -602,7 +639,7 @@ func (r *renderer) tree(c ui.C, n *Node) { info, _ := canvas.ClickInfo() item, tree, session := state.rows[i].item, n.ID, r.s activate := byKey || info.Clicks >= 2 - branch := len(item.Children) > 0 && toggled != i + branch := (len(item.Children) > 0 || item.HasChildren) && toggled != i open := !state.expanded(item) c.After(func() { if item.ID != state.selected { @@ -614,6 +651,9 @@ func (r *renderer) tree(c ui.C, n *Node) { } if branch { state.open[item.ID] = open + if item.HasChildren { + session.Send(Event{Name: "expand", Node: tree, Item: item.ID, Value: open}) + } } session.Send(Event{Name: "activate", Node: tree, Item: item.ID}) }) diff --git a/desktop/internal/pluginview/session.go b/desktop/internal/pluginview/session.go index 276705c2f..dbdbcf2ab 100644 --- a/desktop/internal/pluginview/session.go +++ b/desktop/internal/pluginview/session.go @@ -51,6 +51,10 @@ type Options struct { // window thread, so a host that waits for its background work when it ends can count // the call before it starts. Go func(work func()) + // Watch connects one showing to a backend invalidation callback. + Watch func(instance string, refresh func()) func() + // Page asks Core whether a changed viewport should load another bounded page. + Page func(context.Context, any, any) error } // Event is one view event the host sends. Name is the contract's event name; the other @@ -63,6 +67,7 @@ type Event struct { Setting string Item string Viewport *Viewport + Cursor string } // Viewport is the visible part of a canvas in view-box coordinates. @@ -112,6 +117,9 @@ type Session struct { generation uint64 cancel context.CancelFunc queue []Event + unwatch func() + refresh atomic.Bool + watchEpoch atomic.Uint64 settings *settling viewports map[string]*settling @@ -159,6 +167,20 @@ func (s *Session) Open() { } s.open = true s.instance = "view-" + strconv.FormatUint(instances.Add(1), 10) + if s.options.Watch != nil { + epoch := s.watchEpoch.Add(1) + s.unwatch = s.options.Watch(s.instance, func() { + s.mu.Lock() + current := s.watchEpoch.Load() == epoch + if current { + s.refresh.Store(true) + } + s.mu.Unlock() + if current && s.options.Wake != nil { + s.options.Wake() + } + }) + } s.queue = append(s.queue[:0], Event{Name: "open"}) s.pump() } @@ -173,6 +195,14 @@ func (s *Session) Close() { if s.cancel != nil { s.cancel() } + s.mu.Lock() + s.watchEpoch.Add(1) + s.refresh.Store(false) + s.mu.Unlock() + if s.unwatch != nil { + s.unwatch() + s.unwatch = nil + } // heard is set when open goes out, so a view closed before its first paint sends // neither open nor close. if s.options.Call != nil && s.heard > 0 { @@ -243,6 +273,14 @@ func (s *Session) Send(event Event) { s.pump() } +// Refresh coalesces backend invalidations on the window thread. +func (s *Session) Refresh() { + s.refresh.Store(true) + if s.options.Wake != nil { + s.options.Wake() + } +} + // SettingsChanged sends settings once the values stop changing for settleDelay. A // change while one waits restarts the wait; the event carries the values at sending. func (s *Session) SettingsChanged() { @@ -273,6 +311,9 @@ func (s *Session) Take() (wait time.Duration) { if s == nil || !s.open { return 0 } + if s.refresh.Swap(false) { + s.enqueue(Event{Name: "refresh"}) + } s.mu.Lock() done := s.done s.done = nil @@ -436,6 +477,9 @@ func (s *Session) encode(event Event) json.RawMessage { if event.Item != "" { params["item"] = event.Item } + if event.Cursor != "" { + params["cursor"] = event.Cursor + } if event.Viewport != nil { params["viewport"] = event.Viewport } @@ -504,8 +548,13 @@ type toggleState struct { last bool } -// treeState is a tree's selection and its open items, which the host keeps: opening an -// item never reaches the plugin, and selecting one sends select. +// A tree keeps stable selection and expansion while the backend supplies its +// complete retained range. Lazy branches also emit expansion events. +type pageKey struct { + Cursor, LastCursor string + Count, LastCount, Rows, Visible int +} + type treeState struct { tree ui.TreeState // open holds the items the user opened or closed, by item ID; an item not in it is @@ -517,6 +566,9 @@ type treeState struct { // rows are the visible items, flattened in order, as the last paint showed them. rows []treeRow selected string + cursor string + count int + paging *ui.EffectState[bool, pageKey] } // treeRow is one visible tree item and its depth. @@ -610,7 +662,7 @@ func (s *Session) tree(id string) *treeState { row := state.rows[i] return ui.TreeNode{ Depth: row.depth, - Branch: len(row.item.Children) > 0, + Branch: len(row.item.Children) > 0 || row.item.HasChildren, Expanded: state.expanded(row.item), Selected: row.item.ID == state.selected, } diff --git a/desktop/internal/pluginview/session_test.go b/desktop/internal/pluginview/session_test.go index 4c2fb42c8..590c8f486 100644 --- a/desktop/internal/pluginview/session_test.go +++ b/desktop/internal/pluginview/session_test.go @@ -41,6 +41,35 @@ func newBackend(t *testing.T) *backend { } } +func TestSessionRefreshCoalescesAndClosedShowingCannotRefreshTheNext(t *testing.T) { + b := newBackend(t) + var refresh func() + unwatched := 0 + s := b.session(func(o *Options) { + o.Watch = func(_ string, callback func()) func() { + refresh = callback + return func() { unwatched++ } + } + }) + show(s) + refresh() + refresh() + s.Take() + b.answered(s) + b.answered(s) + if got := b.events(); !slices.Equal(got, []string{"open", "refresh"}) { + t.Fatalf("events=%v", got) + } + old := refresh + s.Close() + show(s) + old() + s.Take() + if unwatched != 1 || len(s.queue) != 0 { + t.Fatalf("old callback queued work after reopen: %v", s.queue) + } +} + // session is a closed session wired to the backend; it closes with the test. func (b *backend) session(adjust ...func(*Options)) *Session { options := Options{ diff --git a/desktop/internal/settingswindow/controller.go b/desktop/internal/settingswindow/controller.go index 94588ff71..460244460 100644 --- a/desktop/internal/settingswindow/controller.go +++ b/desktop/internal/settingswindow/controller.go @@ -294,6 +294,11 @@ type PluginViewLoader interface { View(ctx context.Context, editor pluginservice.SettingsEditor, region, function string, event, view json.RawMessage, closing bool) (json.RawMessage, bool, error) } +// PluginViewWatcher connects backend invalidations to a visible settings region. +type PluginViewWatcher interface { + WatchView(pluginID, instance string, refresh func()) func() +} + // PluginSourceSettingsLoader publishes only explicitly saved native-source drafts. type PluginSourceSettingsLoader interface { SaveSources(context.Context, pluginservice.SettingsEditor, string, pluginsettings.SourceEditor, []core.SourceSettingsEdits) (pluginsettings.SourceEditor, error) diff --git a/desktop/internal/settingswindow/installed_view.go b/desktop/internal/settingswindow/installed_view.go index 4844b07dc..902557430 100644 --- a/desktop/internal/settingswindow/installed_view.go +++ b/desktop/internal/settingswindow/installed_view.go @@ -1027,6 +1027,24 @@ func permissionDescription(language i18n.Language, permission string) string { return i18n.Shared(language, "desktop.marketplace.permissionWindowMessages") case "browser.open": return i18n.Shared(language, "desktop.marketplace.permissionBrowserOpen") + case "window.input": + return i18n.Shared(language, "desktop.marketplace.permissionWindowInput") + case "views.refresh": + return i18n.Shared(language, "desktop.marketplace.permissionViewsRefresh") + case "output.write": + return i18n.Shared(language, "desktop.marketplace.permissionOutputWrite") + case "window.progress": + return i18n.Shared(language, "desktop.marketplace.permissionWindowProgress") + case "statusBar.write": + return i18n.Shared(language, "desktop.marketplace.permissionStatusBarWrite") + case "clipboard.read": + return i18n.Shared(language, "desktop.marketplace.permissionClipboardRead") + case "clipboard.write": + return i18n.Shared(language, "desktop.marketplace.permissionClipboardWrite") + case "workspace.reveal": + return i18n.Shared(language, "desktop.marketplace.permissionWorkspaceReveal") + case "network.request": + return i18n.Shared(language, "desktop.marketplace.permissionNetworkRequest") case "preview.open": return i18n.Shared(language, "desktop.marketplace.permissionPreviewOpen") case "workspace.metadata": diff --git a/desktop/internal/settingswindow/plugin_region_view.go b/desktop/internal/settingswindow/plugin_region_view.go index 73f2d75d5..75d81b16b 100644 --- a/desktop/internal/settingswindow/plugin_region_view.go +++ b/desktop/internal/settingswindow/plugin_region_view.go @@ -3,6 +3,7 @@ package settingswindow import ( "context" "encoding/json" + "errors" "fmt" "strconv" "strings" @@ -139,6 +140,20 @@ func (w *window) openRegion(key regionKey, loader PluginViewLoader, p *pluginSet }, Wake: wake, Failed: failed(pluginRegionViewOperation), + Page: func(ctx context.Context, request, result any) error { + if workflow, ok := loader.(interface { + PluginWorkflow(context.Context, any, any) error + }); ok { + return workflow.PluginWorkflow(ctx, request, result) + } + return errors.New("plugin workflow projection is unavailable") + }, + Watch: func(instance string, refresh func()) func() { + if watcher, ok := loader.(PluginViewWatcher); ok { + return watcher.WatchView(key.plugin, instance, refresh) + } + return func() {} + }, }) v.host = pluginview.Host{Icon: pluginview.HostIcon, Images: v.images, Info: w.infoButton} v.session.Open() diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 951959114..0bdd6d8a9 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -574,6 +574,7 @@ type project struct { tree fileTree // pluginViews are the plugin views the project's tool windows show, by window (plugin_view.go). pluginViews map[string]*pluginViewState + workflow pluginWorkflowUI // build is the Run tool window's provider-backed instances and output. build buildState // buildSessions are the build provider sessions the project started. They live beside build diff --git a/desktop/internal/workbench/app_test.go b/desktop/internal/workbench/app_test.go index ae18b6770..4329eaa5c 100644 --- a/desktop/internal/workbench/app_test.go +++ b/desktop/internal/workbench/app_test.go @@ -278,7 +278,7 @@ func TestWorkbenchDefaultLayout(t *testing.T) { want := map[zone][]string{ zoneLeftTop: {itemProject, itemCommit, itemStructure, itemFind}, zoneLeftBottom: nil, - zoneBottomLeft: {itemGit, itemTerminal, itemProblems, itemReferences, itemRun, itemTests, itemSecurity, itemDebug}, + zoneBottomLeft: {itemGit, itemTerminal, itemProblems, itemReferences, itemOutput, itemRun, itemTests, itemSecurity, itemDebug}, zoneRightTop: {itemBuild, itemNotifications}, zoneRightBottom: nil, zoneBottomRight: {itemBackground}, diff --git a/desktop/internal/workbench/catalog.go b/desktop/internal/workbench/catalog.go index 88294586d..20073cf82 100644 --- a/desktop/internal/workbench/catalog.go +++ b/desktop/internal/workbench/catalog.go @@ -158,6 +158,7 @@ const ( itemProblems = "problems" itemReferences = "references" itemRun = "run" + itemOutput = "output" itemBuild = "build" itemTests = "tests" itemSecurity = "security" @@ -250,6 +251,7 @@ var catalog = []item{ {id: itemTerminal, zone: zoneBottomLeft, icon: &toolicons.Terminal, label: func(m *i18n.Messages) string { return m.Tools.Terminal }, panel: true}, {id: itemProblems, zone: zoneBottomLeft, icon: &toolicons.Problems, label: func(m *i18n.Messages) string { return m.Tools.Problems }, panel: true}, {id: itemReferences, zone: zoneBottomLeft, icon: stripeLucide(icons.Locate), label: func(m *i18n.Messages) string { return m.Tools.References }, panel: true}, + {id: itemOutput, zone: zoneBottomLeft, icon: &toolicons.Terminal, label: func(m *i18n.Messages) string { return m.Tools.Output }, panel: true}, {id: itemRun, zone: zoneBottomLeft, icon: &toolicons.Run, label: func(m *i18n.Messages) string { return m.Tools.Run }, panel: true}, {id: itemTests, zone: zoneBottomLeft, icon: stripeLucide(icons.CircleCheck), label: func(m *i18n.Messages) string { return m.Tools.Tests }, panel: true}, {id: itemSecurity, zone: zoneBottomLeft, icon: stripeLucide(icons.ShieldCheck), label: func(m *i18n.Messages) string { return m.Tools.Security }, panel: true}, diff --git a/desktop/internal/workbench/chrome_view.go b/desktop/internal/workbench/chrome_view.go index dbeb57308..952b3283d 100644 --- a/desktop/internal/workbench/chrome_view.go +++ b/desktop/internal/workbench/chrome_view.go @@ -516,6 +516,7 @@ func (a *App) statusBar(c ui.C) { a.remoteStatus(c) a.remotePortsStatusItem(c) a.statusPathView(c) + a.pluginWorkflowStatus(c) zone := ui.Row(c).Items(ui.Center).Gap(chromeStatusGap).Children(func() { for _, i := range a.chrome.items[zoneStatus] { if !a.vimStatusShown(i) { diff --git a/desktop/internal/workbench/commands.go b/desktop/internal/workbench/commands.go index 9870556ab..862cc37e2 100644 --- a/desktop/internal/workbench/commands.go +++ b/desktop/internal/workbench/commands.go @@ -183,6 +183,11 @@ func (a *App) commands() []command { if !pluginCommandOffered(command) { continue } + if command.ToolWindowID == "" { + command := command + add(pluginCommandID(command), t.GroupToolWindows, command.Title, "", true, func() { a.runPluginCommand(p, command.PluginID, command.ID) }) + continue + } windowID := pluginItemPrefix + command.ToolWindowID index := slices.IndexFunc(a.chrome.catalog, func(it item) bool { return it.id == windowID }) if index < 0 { diff --git a/desktop/internal/workbench/difftab.go b/desktop/internal/workbench/difftab.go index ca6a59860..cf85ee6d9 100644 --- a/desktop/internal/workbench/difftab.go +++ b/desktop/internal/workbench/difftab.go @@ -209,6 +209,8 @@ type diffEditor struct { type savedSource struct { before, after string files []core.GitDiffFile + // title identifies inline text, which has no working-tree file to open. + title string } // diffComparison is the comparison a Diff tab shows a file of: base against target, or against @@ -237,7 +239,12 @@ type diffOrigin struct { } // name is the title of the tab: the name of the file. -func (t *diffTab) name() string { return path.Base(t.change.Path) } +func (t *diffTab) name() string { + if t.saved != nil && t.saved.title != "" { + return t.saved.title + } + return path.Base(t.change.Path) +} // readOnly says the tab's right side cannot be written: a commit's change, or the index. func (t *diffTab) readOnly() bool { return t.commit != "" || t.staged } @@ -891,6 +898,9 @@ func (a *App) stepFile(p *project, t *diffTab, by int) { // openDiffFile opens the tab's file of the working tree in the editor. func (a *App) openDiffFile(p *project, t *diffTab) { + if t.saved != nil && t.saved.title != "" { + return + } a.openFile(p, filepath.Join(t.root, filepath.FromSlash(t.change.Path))) } diff --git a/desktop/internal/workbench/difftab_view.go b/desktop/internal/workbench/difftab_view.go index 306fcb59a..c3f30bd4b 100644 --- a/desktop/internal/workbench/difftab_view.go +++ b/desktop/internal/workbench/difftab_view.go @@ -77,7 +77,7 @@ func (a *App) diffToolbar(c ui.C, p *project, t *diffTab) { if a.gitIconButton(c, i18n.Shared(lang, "git.diff.nextDifference"), icons.ArrowDown, false, n == 0 || t.current >= n-1) { c.After(func() { t.step(1) }) } - if a.gitIconButton(c, i18n.Shared(lang, "git.openFile"), icons.Pencil, false, strings.Contains(t.change.Status, "D")) { + if a.gitIconButton(c, i18n.Shared(lang, "git.openFile"), icons.Pencil, false, strings.Contains(t.change.Status, "D") || t.saved != nil && t.saved.title != "") { c.After(func() { a.openDiffFile(p, t) }) } if len(t.files) > 1 { diff --git a/desktop/internal/workbench/documents.go b/desktop/internal/workbench/documents.go index fb84b8f72..b20b4b9cf 100644 --- a/desktop/internal/workbench/documents.go +++ b/desktop/internal/workbench/documents.go @@ -74,7 +74,9 @@ type document struct { // title, and languageID the editor language a language server is selected // by. path, name string - languageID string + // previewKind explicitly enables safe read-only plugin content previews. + previewKind string + languageID string // grammar is the syntax selected on open, including any bundled fallback. // Views of this document share it for the lifetime of the open document. grammar *syntax.Syntax diff --git a/desktop/internal/workbench/html_preview.go b/desktop/internal/workbench/html_preview.go index 17a6d260b..a4a8f6db1 100644 --- a/desktop/internal/workbench/html_preview.go +++ b/desktop/internal/workbench/html_preview.go @@ -66,6 +66,9 @@ type htmlPreviewState struct { // isHTMLDocument reports whether d is an HTML file, by its name. func isHTMLDocument(d *document) bool { + if d != nil && d.previewKind == "HTML" { + return true + } if d == nil || d.virtual { return false } @@ -159,7 +162,7 @@ func (a *App) htmlActions(c ui.C, p *project, d *document, s *htmlPreviewState, entry.view.Reload() } } - if a.viewerIconButton(c.Part("browser"), i18n.Shared(language, "desktop.editorMenu.openInBrowser"), icons.ExternalLink) { + if browserPreviewable(d) && a.viewerIconButton(c.Part("browser"), i18n.Shared(language, "desktop.editorMenu.openInBrowser"), icons.ExternalLink) { c.After(func() { a.openInBrowser(p, d, surfaceButton) }) } } diff --git a/desktop/internal/workbench/markdown_preview.go b/desktop/internal/workbench/markdown_preview.go index bf35a2477..7ce44c3ee 100644 --- a/desktop/internal/workbench/markdown_preview.go +++ b/desktop/internal/workbench/markdown_preview.go @@ -119,6 +119,9 @@ type markdownPreviewState struct { // isMarkdownDocument reports whether d is a Markdown file by its language or name. func isMarkdownDocument(d *document) bool { + if d != nil && d.previewKind == "Markdown" { + return true + } if d == nil || d.virtual { return false } diff --git a/desktop/internal/workbench/plugin_view.go b/desktop/internal/workbench/plugin_view.go index 9c0d26a54..f3a998c45 100644 --- a/desktop/internal/workbench/plugin_view.go +++ b/desktop/internal/workbench/plugin_view.go @@ -89,6 +89,10 @@ func (a *App) pluginView(p *project, window *pluginservice.ToolWindow) *pluginVi Wake: wake, Failed: func(err error) { a.operationFailed(pluginViewOperation, err) }, Context: ctx, + Page: a.plugins.PluginWorkflow, + Watch: func(instance string, refresh func()) func() { + return plugins.WatchView(current.PluginID, instance, refresh) + }, Go: func(work func()) { a.tasks.running.Add(1) go func() { diff --git a/desktop/internal/workbench/plugin_workflow.go b/desktop/internal/workbench/plugin_workflow.go new file mode 100644 index 000000000..9af64ceae --- /dev/null +++ b/desktop/internal/workbench/plugin_workflow.go @@ -0,0 +1,598 @@ +package workbench + +import ( + "context" + "net/url" + "os" + "slices" + "strconv" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/textview" +) + +var _ pluginservice.WorkflowHost = pluginWorkbench{} + +type pluginOutput struct { + id, name string + buffer outputBuffer + view textview.View +} + +// Only the window thread owns these presentation resources. The service owns +// their session/context leases and sends removal before a backend is forgotten. +type pluginWorkflowUI struct { + outputs []*pluginOutput + selected string + progress []pluginservice.ProgressUpdate + status []pluginservice.StatusUpdate + menu bool +} + +type quickInputProjection struct { + Indices []int + Valid bool +} + +type quickInputState struct { + request pluginservice.QuickInput + value string + indices []int + list ui.ListState + picked map[string]bool + filter *ui.EffectState[quickInputProjection, string] + invalid bool + ready bool + result *pluginservice.QuickResult +} + +func (w pluginWorkbench) QuickInput(ctx context.Context, root string, request pluginservice.QuickInput) (*pluginservice.QuickResult, error) { + state := &quickInputState{request: request, value: request.Value, picked: map[string]bool{}} + for index, item := range request.Items { + state.indices = append(state.indices, index) + state.picked[item.ID] = item.Picked + } + state.list.Key = func(index int) int { return state.indices[index] + 1 } + state.list.Label = func(index int) string { return request.Items[state.indices[index]].Label } + state.filter = ui.NewEffectKeyed(func(effect context.Context, query string) (quickInputProjection, error) { + bounded, cancel := context.WithTimeout(effect, kernelCallTimeout) + defer cancel() + stop := context.AfterFunc(ctx, cancel) + defer stop() + valid, err := request.Validate(bounded, query) + result := quickInputProjection{Valid: valid} + if err == nil && valid && request.Pick { + result.Indices, err = request.Filter(bounded, query) + } + return result, err + }) + prompt, err := onWindow(w.app, ctx, func(a *App) (*pluginPrompt, error) { + if _, err := a.projectAt(root); err != nil { + return nil, err + } + language := a.language() + title := request.Title + if title == "" { + title = i18n.SharedFormat(language, "desktop.pluginHost.messageFrom", map[string]string{"plugin": request.PluginID}) + } + return &pluginPrompt{title: title, quick: state, actions: []string{i18n.Shared(language, "desktop.files.cancel"), i18n.Shared(language, "desktop.pluginHost.messageOK")}}, nil + }) + if err != nil { + return nil, err + } + choice, err := w.app.askUser(ctx, prompt) + if err != nil || choice == nil || *choice != 1 { + return nil, err + } + return state.result, nil +} + +// quickInputBody uses the framework's secure field and virtualized native list. +// Filtering is a cancellable Core effect; a late result cannot replace a new query. +func (a *App) quickInputBody(c ui.C, s *quickInputState) bool { + request := s.request + if request.Prompt != "" { + ui.Wrap(c, request.Prompt).Shrink(0) + } + field := ui.TextField(c.Part("input"), &s.value, request.Title, request.Placeholder).FillWidth().AutoFocus() + if request.Password { + field = field.Secure() + } + submitted := field.Submitted() + ui.Effect(c, s.filter, s.value) + if result, err, ok := s.filter.Take(); ok { + if err != nil { + a.operationFailed("plugin_quick_pick_filter", err) + s.ready = false + s.invalid = false + } else { + previous := "" + if at := s.list.Selected(); at >= 0 && at < len(s.indices) { + previous = request.Items[s.indices[at]].ID + } + s.indices = result.Indices + s.ready = result.Valid + s.invalid = !result.Valid + selected := -1 + for row, index := range s.indices { + if request.Items[index].ID == previous || previous == "" && request.Items[index].Picked { + selected = row + break + } + } + if selected < 0 && len(s.indices) > 0 { + selected = 0 + } + s.list.Select(selected) + } + } + if field.Changed() { + s.ready = false + s.invalid = false + } + if s.invalid { + ui.Text(c, i18n.Shared(a.language(), "desktop.pluginHost.inputLimit")).Color(a.colors.Subtle) + } + if !request.Pick { + return submitted && s.ready + } + ui.List(c.Part("items"), &s.list, len(s.indices), func(row ui.ListRow) { + item := request.Items[s.indices[row.Index]] + row.Element.Items(ui.Center).Gap(8).Height(48).Children(func() { + if request.CanPickMany { + picked := s.picked[item.ID] + if ui.Checkbox(row.C.Part("picked"), &picked, item.Label).Changed() { + s.picked[item.ID] = picked + } + } else { + ui.Text(row.C, item.Label).Grow(1).Ellipsis() + } + ui.Column(row.C).Grow(1).Children(func() { + if item.Description != "" { + ui.Text(row.C, item.Description).Color(a.colors.Subtle).Ellipsis() + } + if item.Detail != "" { + ui.Text(row.C, item.Detail).Color(a.colors.Subtle).Ellipsis() + } + }) + }) + }).Scrollbars().Grow(1).FillWidth() + if _, ok := s.list.Submitted(); ok { + submitted = true + } + return submitted && s.ready +} + +func (s *quickInputState) accept() { + result := &pluginservice.QuickResult{Value: s.value, IDs: []string{}} + if s.request.Pick { + if s.request.CanPickMany { + for _, item := range s.request.Items { + if s.picked[item.ID] { + result.IDs = append(result.IDs, item.ID) + } + } + } else if row := s.list.Selected(); row >= 0 && row < len(s.indices) { + result.IDs = append(result.IDs, s.request.Items[s.indices[row]].ID) + } + } + s.result = result + s.clear() +} + +// clear removes input and cancels work even when a queued prompt is dismissed. +func (s *quickInputState) clear() { + s.value = "" + s.request.Value = "" +} + +func (w pluginWorkbench) OpenPreview(ctx context.Context, root string, request pluginservice.PreviewRequest) (pluginservice.PreviewResult, error) { + // Core has already checked the source type. Check native availability before + // opening a document, so a refusal leaves no unrelated editor tab behind. + if request.Kind == "HTML" { + _, err := onWindow(w.app, ctx, func(a *App) (struct{}, error) { + _, supported := a.kernel.(htmlKernel) + if !supported || !a.previewWeb() || a.previews.siteFailed { + return struct{}{}, hostError(pluginservice.CodeUnsupportedOption, "HTML preview is unavailable in this window.") + } + return struct{}{}, nil + }) + if err != nil { + return pluginservice.PreviewResult{}, err + } + } + path := request.Path + var opened pluginservice.OpenResult + if path != "" { + var err error + opened, err = w.Open(ctx, root, pluginservice.OpenRequest{Path: path}) + if err != nil { + return pluginservice.PreviewResult{}, err + } + } else { + path = "lithe-plugin-preview://" + url.PathEscape(request.PluginID) + "/" + url.PathEscape(request.Owner) + "/" + url.PathEscape(request.ID) + content := editorview.Prepare([]byte(request.Text)) + var err error + opened, err = onWindow(w.app, ctx, func(a *App) (pluginservice.OpenResult, error) { + p, err := a.projectAt(root) + if err != nil { + return pluginservice.OpenResult{}, err + } + d := p.docs.byPath(path) + already := d != nil + if d != nil { + if d.previewKind != request.Kind { + if d.html != nil && d.html.entry != nil { + d.html.entry.close() + } + if d.markdown != nil && d.markdown.web != nil { + d.markdown.web.entry.close() + } + d.html, d.markdown = nil, nil + } + d.view.ShowContent(content) + d.name = request.Title + a.selectDocument(p, d.id) + } else { + a.placeDocumentAs(p, path, request.Title, content, nil, "", true) + d = p.docs.byPath(path) + } + if d == nil { + return pluginservice.OpenResult{}, hostError(pluginservice.CodeLimitExceeded, "The preview tab could not be opened.") + } + d.previewKind = request.Kind + return pluginservice.OpenResult{DocumentSummary: summarize(p, d), WasAlreadyOpen: already, WindowIsForeground: true}, nil + }) + if err != nil { + return pluginservice.PreviewResult{}, err + } + } + return onWindow(w.app, ctx, func(a *App) (pluginservice.PreviewResult, error) { + p, err := a.projectAt(root) + if err != nil { + return pluginservice.PreviewResult{}, err + } + d := p.docs.byPath(path) + if d == nil { + return pluginservice.PreviewResult{}, hostError(pluginservice.CodeNotFound, "The preview document was closed.") + } + d.pageMode = pageSplit + if request.Presentation == "previewOnly" { + d.pageMode = pageOnly + } + if request.Range != nil { + d.view.GoToNavigation(request.Range.Start.Line-1, request.Range.Start.Column-1, false) + line, column := d.view.CaretUTF16() + opened.AppliedSelection = &pluginservice.AppliedCaret{Kind: "caret", Line: line + 1, Column: column + 1} + } + opened.DocumentSummary = summarize(p, d) + return pluginservice.PreviewResult{OpenResult: opened, UsesLiveBuffer: true, Presentation: request.Presentation}, nil + }) +} + +func (w pluginWorkbench) ShowTextDiff(ctx context.Context, root string, request pluginservice.DiffRequest) error { + kernel, ok := w.app.kernel.(interface { + CompareTexts(context.Context, string, string) (core.GitDiffFile, error) + }) + if !ok { + return hostError(pluginservice.CodeUnsupportedOption, "Text comparison is unavailable.") + } + file, err := kernel.CompareTexts(ctx, request.Original, request.Modified) + if err != nil { + return err + } + _, err = onWindow(w.app, ctx, func(a *App) (struct{}, error) { + p, err := a.projectAt(root) + if err != nil { + return struct{}{}, err + } + title := request.Title + if title == "" { + title = i18n.Shared(a.language(), "desktop.pluginHost.diff") + } + file.Path = "inline.txt" + source := &savedSource{title: title, before: request.OriginalTitle, after: request.ModifiedTitle, files: []core.GitDiffFile{file}} + if source.before == "" { + source.before = i18n.Shared(a.language(), "desktop.pluginHost.original") + } + if source.after == "" { + source.after = i18n.Shared(a.language(), "desktop.pluginHost.modified") + } + if a.showDiff(p, root, "plugin-inline:"+strconv.Itoa(p.diffs.next+1), core.GitChange{Path: file.Path, Status: "M"}, nil, diffOrigin{saved: source}) == nil { + return struct{}{}, hostError(pluginservice.CodeUnsupportedOption, "The comparison tab could not be opened.") + } + return struct{}{}, nil + }) + return err +} + +func (w pluginWorkbench) UpdateOutput(ctx context.Context, root string, update pluginservice.OutputUpdate) error { + _, err := onWindow(w.app, ctx, func(a *App) (struct{}, error) { + p, err := a.projectAt(root) + if err != nil { + if update.Action == "dispose" { + return struct{}{}, nil + } + return struct{}{}, err + } + state := &p.workflow + var output *pluginOutput + for _, candidate := range state.outputs { + if candidate.id == update.ID { + output = candidate + break + } + } + if update.Action == "create" && output == nil { + output = &pluginOutput{id: update.ID, name: update.Name} + state.outputs = append(state.outputs, output) + } + if output == nil { + return struct{}{}, nil + } + switch update.Action { + case "append": + output.buffer.maxLines, output.buffer.maxBytes = update.MaxLines, update.MaxBytes + chunk := outputChunk{open: styledLine{text: update.Open}} + for _, line := range update.Lines { + chunk.lines = append(chunk.lines, styledLine{text: line}) + } + output.buffer.apply(chunk) + case "clear": + output.buffer.clear() + output.buffer.open = styledLine{} + output.view = textview.View{} + case "show": + state.selected = update.ID + a.openToolWindow(itemOutput) + case "dispose": + for i, candidate := range state.outputs { + if candidate == output { + state.outputs = append(state.outputs[:i], state.outputs[i+1:]...) + if state.selected == update.ID { + state.selected = "" + } + break + } + } + } + return struct{}{}, nil + }) + return err +} + +func (w pluginWorkbench) UpdateProgress(ctx context.Context, root string, update pluginservice.ProgressUpdate) error { + _, err := onWindow(w.app, ctx, func(a *App) (struct{}, error) { + p, err := a.projectAt(root) + if err != nil { + if update.Remove { + return struct{}{}, nil + } + return struct{}{}, err + } + for i, item := range p.workflow.progress { + if item.ID != update.ID { + continue + } + if update.Remove { + p.workflow.progress = append(p.workflow.progress[:i], p.workflow.progress[i+1:]...) + } else { + if update.Title != "" { + item.Title = update.Title + } + if update.MessageSet { + item.Message = update.Message + } + if update.Percentage != nil { + item.Percentage = update.Percentage + } + p.workflow.progress[i] = item + } + return struct{}{}, nil + } + if !update.Remove { + p.workflow.progress = append(p.workflow.progress, update) + } + return struct{}{}, nil + }) + return err +} + +func (w pluginWorkbench) UpdateStatus(ctx context.Context, root string, update pluginservice.StatusUpdate) error { + _, err := onWindow(w.app, ctx, func(a *App) (struct{}, error) { + p, err := a.projectAt(root) + if err != nil { + if update.Remove { + return struct{}{}, nil + } + return struct{}{}, err + } + for i, item := range p.workflow.status { + if item.ID != update.ID { + continue + } + p.workflow.status = append(p.workflow.status[:i], p.workflow.status[i+1:]...) + break + } + if !update.Remove { + p.workflow.status = append(p.workflow.status, update) + } + if update.Order != nil { + byID := map[string]pluginservice.StatusUpdate{} + for _, item := range p.workflow.status { + byID[item.ID] = item + } + ordered := make([]pluginservice.StatusUpdate, 0, len(byID)) + for _, id := range update.Order { + if item, ok := byID[id]; ok { + ordered = append(ordered, item) + delete(byID, id) + } + } + for _, item := range p.workflow.status { + if _, ok := byID[item.ID]; ok { + ordered = append(ordered, item) + } + } + p.workflow.status = ordered + } + return struct{}{}, nil + }) + return err +} + +func (w pluginWorkbench) ReleaseWorkflow(root, kind, id string) { + w.app.post(func(a *App) { + p, err := a.projectAt(root) + if err != nil { + return // log-exempt: 预期的缺失:项目已关闭,呈现资源已经释放。 + } + switch kind { + case "output": + p.workflow.outputs = slices.DeleteFunc(p.workflow.outputs, func(item *pluginOutput) bool { return item.id == id }) + if p.workflow.selected == id { + p.workflow.selected = "" + } + case "progress": + p.workflow.progress = slices.DeleteFunc(p.workflow.progress, func(item pluginservice.ProgressUpdate) bool { return item.ID == id }) + case "statusBar": + p.workflow.status = slices.DeleteFunc(p.workflow.status, func(item pluginservice.StatusUpdate) bool { return item.ID == id }) + } + }) +} + +func (w pluginWorkbench) ReadClipboard(ctx context.Context) (string, error) { + return onWindow(w.app, ctx, func(*App) (string, error) { return app.ClipboardText() }) +} +func (w pluginWorkbench) WriteClipboard(ctx context.Context, text string) error { + _, err := onWindow(w.app, ctx, func(*App) (struct{}, error) { return struct{}{}, app.SetClipboardText(text) }) + return err +} +func (w pluginWorkbench) RevealResource(ctx context.Context, path string) error { + _, err := onWindow(w.app, ctx, func(*App) (struct{}, error) { return struct{}{}, treeRevealPath(path) }) + return err +} + +func (a *App) pluginOutputView(c ui.C, p *project) { + state := &p.workflow + if len(state.outputs) == 0 { + a.panelMessage(c, i18n.Shared(a.language(), "desktop.pluginHost.noOutput"), a.colors.Subtle) + return + } + selected := 0 + choices := make([]int, len(state.outputs)) + for i, output := range state.outputs { + choices[i] = i + if output.id == state.selected { + selected = i + } + } + ui.Select(c.Part("channel"), &selected, choices, func(i int) string { return state.outputs[i].name }).FillWidth() + output := state.outputs[selected] + state.selected = output.id + a.outputList(c.Part(output.id), p, &output.view, "plugin:"+output.id, output.name, &output.buffer, 0, false, nil).Fill() +} + +func (a *App) pluginWorkflowStatus(c ui.C) { + p := a.project + if p == nil { + return + } + state := &p.workflow + if len(state.status) > 0 { + status := state.status[0] + button := ui.Button(c.Key(status.ID), status.Text).MaxWidth(180).Ghost().Tooltip(status.Tooltip).Disabled(status.CommandID == "") + if button.Clicked() { + item := status + c.After(func() { a.runPluginCommand(p, item.PluginID, item.CommandID) }) + } + } + if len(state.progress) == 0 && len(state.status) <= 1 { + return + } + anchor := ui.Button(c.Part("workflowMenu"), i18n.Shared(a.language(), "desktop.pluginHost.backgroundTasks")).Ghost() + if anchor.Clicked() { + state.menu = true + } + ui.Menu(c.Part("workflowMenu"), anchor, &state.menu, func(menu *ui.MenuItems) { + menu.Above() + for _, progress := range state.progress { + label := progress.Title + if progress.Percentage != nil { + label += " " + strconv.FormatFloat(*progress.Percentage, 'f', 0, 64) + "%" + } + if progress.Cancel == nil { + menu.Item(label).Description(progress.Message).Disabled(true) + continue + } + menu.Sub(label, func(sub *ui.MenuItems) { + if sub.Item(i18n.Shared(a.language(), "desktop.files.cancel")).Clicked() { + cancel := progress.Cancel + c.After(func() { + a.performed("plugin.progress.cancel", surfaceMenu) + a.background(p, 5*time.Second, func(context.Context) func(*App) { cancel(); return nil }) + }) + } + }).Description(progress.Message) + } + for _, status := range state.status { + if menu.Item(status.Text).Description(status.Tooltip).Disabled(status.CommandID == "").Clicked() { + item := status + c.After(func() { a.runPluginCommand(p, item.PluginID, item.CommandID) }) + } + } + }) +} + +func (a *App) runPluginCommand(p *project, pluginID, commandID string) { + if a.plugins == nil { + return + } + a.performed("plugin.command.run", surfaceButton) + a.background(p, contentOpenTimeout, func(ctx context.Context) func(*App) { + err := a.plugins.NotifyCommandRun(ctx, pluginID, commandID, p.root) + return func(a *App) { + if err != nil { + a.operationFailed("plugin_command", err) + a.notifyError(i18n.Shared(a.language(), "desktop.pluginHost.commandFailed")) + } + } + }) +} + +// OpenBrowserResource opens only saved HTML, leaving a dirty editor untouched. +func (w pluginWorkbench) OpenBrowserResource(ctx context.Context, root, path, unsaved string) (bool, error) { + info, err := os.Stat(path) + if err != nil { + return false, err + } + if !info.Mode().IsRegular() { + return false, hostError(pluginservice.CodeUnsupportedOption, "The browser resource is not a regular file.") + } + dirty, err := onWindow(w.app, ctx, func(a *App) (bool, error) { + p, err := a.projectAt(root) + if err != nil { + return false, err + } + if d := p.docs.byPath(path); d != nil && (d.dirty() || d.saving) { + if unsaved == "requireSaved" { + return false, hostError(pluginservice.CodeBusy, "Save the document before opening it in a browser.") + } + return true, nil + } + return false, nil + }) + if err != nil { + return false, err + } + if err := ctx.Err(); err != nil { + return false, err + } + return dirty, app.OpenPathInBrowser(path) +} diff --git a/desktop/internal/workbench/plugin_workflow_test.go b/desktop/internal/workbench/plugin_workflow_test.go new file mode 100644 index 000000000..ba068246e --- /dev/null +++ b/desktop/internal/workbench/plugin_workflow_test.go @@ -0,0 +1,155 @@ +package workbench + +import ( + "context" + "path/filepath" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" +) + +func TestWorkflowPreviewIsolationUpdatesAndReadonlyDiff(t *testing.T) { + h := newHarness(t, &testKernel{Client: core.NewClient()}) + root, _ := openNote(t, h, "workspace text") + w := pluginWorkbench{app: h.app} + request := pluginservice.PreviewRequest{PluginID: "dev.lithe.test.workflow", Owner: "session:context", ID: "page", Title: "Notes", Text: "# First", Kind: "Markdown", Presentation: "previewOnly"} + open := func() pluginservice.PreviewResult { + t.Helper() + result, err := callOnWindow(h, "preview", func(ctx context.Context) (pluginservice.PreviewResult, error) { + return w.OpenPreview(ctx, root, request) + }) + if err != nil { + t.Fatal(err) + } + return result + } + first := open() + request.Text = "# Updated" + second := open() + if !second.WasAlreadyOpen || first.DocumentID != second.DocumentID || !second.IsReadOnly || !second.UsesLiveBuffer || second.Presentation != "previewOnly" { + t.Fatalf("updated preview=%+v", second) + } + var d *document + for _, candidate := range h.app.project.docs.list { + if documentPublicID(candidate) == first.DocumentID { + d = candidate + } + } + if d == nil || !d.virtual || !d.view.ReadOnly() || d.dirty() || d.pageMode != pageOnly { + t.Fatal("inline preview became editable, dirty, or lost its presentation") + } + if text, _ := d.view.Text(); string(text) != request.Text { + t.Fatalf("preview text=%q", text) + } + request.Owner = "another-session:context" + if third := open(); third.DocumentID == first.DocumentID || third.WasAlreadyOpen { + t.Fatal("two sessions shared an inline preview") + } + before := len(h.app.project.docs.list) + request.Kind, request.Path = "HTML", filepath.Join(root, "missing.html") + _, err := callOnWindow(h, "unavailable HTML", func(ctx context.Context) (pluginservice.PreviewResult, error) { + return w.OpenPreview(ctx, root, request) + }) + if hostErrorCode(err) != pluginservice.CodeUnsupportedOption || len(h.app.project.docs.list) != before { + t.Fatalf("unavailable HTML opened a tab: %v", err) + } + if err := callOnWindowErr(h, "diff", func(ctx context.Context) error { + return w.ShowTextDiff(ctx, root, pluginservice.DiffRequest{Title: "note.txt", Original: "before\n", Modified: "after\n"}) + }); err != nil { + t.Fatal(err) + } + h.settleChain() + diff := h.app.project.diffs.list[0] + if diff.saved == nil || diff.saved.title != "note.txt" || diff.change.Path != "inline.txt" || !diff.readOnly() { + t.Fatal("inline diff acquired a working-tree file identity") + } +} + +func TestWorkflowOutputProgressUpdatesAndRelease(t *testing.T) { + h := newHarness(t, &testKernel{Client: core.NewClient()}) + root := t.TempDir() + h.open(root) + w := pluginWorkbench{app: h.app} + for _, update := range []pluginservice.OutputUpdate{ + {ID: "out", Name: "Results", Action: "create"}, + {ID: "out", Action: "append", Lines: []string{"first", "second"}, Open: "tail", MaxLines: 4000, MaxBytes: 512 * 1024}, + {ID: "out", Action: "show"}, + } { + if err := callOnWindowErr(h, "output", func(ctx context.Context) error { return w.UpdateOutput(ctx, root, update) }); err != nil { + t.Fatal(err) + } + } + if h.app.project.workflow.selected != "out" || !h.shows("first") { + t.Fatal("output was not presented") + } + if err := callOnWindowErr(h, "clear output", func(ctx context.Context) error { + return w.UpdateOutput(ctx, root, pluginservice.OutputUpdate{ID: "out", Action: "clear"}) + }); err != nil { + t.Fatal(err) + } + if h.shows("first") || h.shows("tail") { + t.Fatal("cleared output remained visible") + } + percentage := 35.0 + for _, update := range []pluginservice.ProgressUpdate{ + {ID: "progress", Title: "Download", Message: "Reading", MessageSet: true, Percentage: &percentage}, + {ID: "progress", Message: "Finishing", MessageSet: true}, + } { + if err := callOnWindowErr(h, "progress", func(ctx context.Context) error { return w.UpdateProgress(ctx, root, update) }); err != nil { + t.Fatal(err) + } + } + item := h.app.project.workflow.progress[0] + if item.Title != "Download" || item.Message != "Finishing" || item.Percentage == nil || *item.Percentage != 35 { + t.Fatalf("partial progress update=%+v", item) + } + w.ReleaseWorkflow(root, "output", "out") + w.ReleaseWorkflow(root, "progress", "progress") + h.settle() + if state := h.app.project.workflow; len(state.outputs) != 0 || state.selected != "" || len(state.progress) != 0 { + t.Fatal("workflow UI retained released resources") + } +} + +func TestWorkflowQuickInputAcceptsEmptyAndClearsCancelledPassword(t *testing.T) { + h := newHarness(t, &testKernel{Client: core.NewClient()}) + root := t.TempDir() + h.open(root) + w := pluginWorkbench{app: h.app} + for _, password := range []bool{false, true} { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + type outcome struct { + value *pluginservice.QuickResult + err error + } + done := make(chan outcome, 1) + go func() { + value, err := w.QuickInput(ctx, root, pluginservice.QuickInput{Title: "Input", Password: password, Validate: func(context.Context, string) (bool, error) { return true, nil }}) + done <- outcome{value, err} + }() + h.await("input ready", func() bool { return len(h.app.prompts.queue) > 0 && h.app.prompts.queue[0].quick.ready }) + state := h.app.prompts.queue[0].quick + if password { + state.value = "private value" + h.app.answerPrompt(nil) + } else { + one := 1 + h.app.answerPrompt(&one) + } + select { + case got := <-done: + if got.err != nil || password && got.value != nil || !password && (got.value == nil || got.value.Value != "") { + t.Fatalf("input result=%+v, %v", got.value, got.err) + } + case <-ctx.Done(): + t.Fatal("input did not finish") + } + cancel() + if state.value != "" || state.request.Value != "" { + t.Fatal("dismissed input retained a password") + } + } +} diff --git a/desktop/internal/workbench/plugin_workflow_visual_test.go b/desktop/internal/workbench/plugin_workflow_visual_test.go new file mode 100644 index 000000000..c979205fc --- /dev/null +++ b/desktop/internal/workbench/plugin_workflow_visual_test.go @@ -0,0 +1,122 @@ +//go:build vivahead && lithevisual + +package workbench + +import ( + "context" + "os" + "path/filepath" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/headless" +) + +// TestVisualPluginWorkflow captures the actual native surfaces reached by the +// generic host API. The input is synthetic; no installed plugin is required. +func TestVisualPluginWorkflow(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR") + } + if err := os.MkdirAll(out, 0o755); err != nil { + t.Fatal(err) + } + for _, theme := range []string{"light", "dark"} { + for _, language := range []string{"zh-Hans", "en-US"} { + t.Run(theme+"-"+language, func(t *testing.T) { + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, map[string]string{"theme": theme}); err != nil { + t.Fatal(err) + } + var session *headless.Session + h := newHarnessWithDriver(t, Options{Kernel: &testKernel{Client: core.NewClient()}, Store: prefs, Languages: []string{language}}, func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = 1100, 720 + var err error + session, err = headless.Open(config, nil, headless.Options{}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + root := t.TempDir() + h.open(root) + screenshot := func(scene string) { + t.Helper() + h.settleChain() + if err := session.Screenshot(filepath.Join(out, scene+"-"+theme+"-"+language+".png")); err != nil { + t.Fatal(err) + } + } + screenshot("workflow-before") + w := pluginWorkbench{app: h.app} + if _, err := callOnWindow(h, "Markdown preview", func(ctx context.Context) (pluginservice.PreviewResult, error) { + return w.OpenPreview(ctx, root, pluginservice.PreviewRequest{PluginID: "dev.lithe.test.workflow", Owner: "visual:context", ID: "guide", Title: "Workflow", Text: "# Workflow\n\nRead-only plugin content.\n\n- Stable resource identity\n- Session and context isolation\n\n```go\nfmt.Println(42)\n```", Kind: "Markdown", Presentation: "editorAndPreview"}) + }); err != nil { + t.Fatal(err) + } + for _, update := range []pluginservice.OutputUpdate{ + {ID: "output", Name: "Workflow output", Action: "create"}, + {ID: "output", Action: "append", Lines: []string{"Preparing request", "Response received: 200", "Completed"}, MaxLines: 4000, MaxBytes: 512 * 1024}, + {ID: "output", Action: "show"}, + } { + if err := callOnWindowErr(h, "output", func(ctx context.Context) error { return w.UpdateOutput(ctx, root, update) }); err != nil { + t.Fatal(err) + } + } + if err := callOnWindowErr(h, "status", func(ctx context.Context) error { + return w.UpdateStatus(ctx, root, pluginservice.StatusUpdate{ID: "status", Text: "Ready", Tooltip: "Workflow status"}) + }); err != nil { + t.Fatal(err) + } + percentage := 65.0 + if err := callOnWindowErr(h, "progress", func(ctx context.Context) error { + return w.UpdateProgress(ctx, root, pluginservice.ProgressUpdate{ID: "progress", Title: "Indexing", Message: "Reading results", Percentage: &percentage, Cancellable: true, Cancel: func() {}}) + }); err != nil { + t.Fatal(err) + } + screenshot("workflow-output-preview") + h.clickNamed(h.shared("desktop.pluginHost.backgroundTasks")) + if !h.shows("Indexing 65%") { + t.Fatal("background task menu did not open") + } + screenshot("workflow-progress-menu") + h.key(gfx.KeyEscape) + if err := callOnWindowErr(h, "text diff", func(ctx context.Context) error { + return w.ShowTextDiff(ctx, root, pluginservice.DiffRequest{Title: "Comparison", Original: "first\nunchanged\n", Modified: "updated\nunchanged\n"}) + }); err != nil { + t.Fatal(err) + } + screenshot("workflow-readonly-diff") + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + done := make(chan error, 1) + go func() { + _, err := w.QuickInput(ctx, root, pluginservice.QuickInput{ + Title: "Choose an item", Pick: true, CanPickMany: true, + Items: []pluginservice.QuickItem{{ID: "first", Label: "First item", Description: "Available", Picked: true}, {ID: "second", Label: "Second item", Description: "Available"}}, + Validate: func(context.Context, string) (bool, error) { return true, nil }, + Filter: func(context.Context, string) ([]int, error) { return []int{0, 1}, nil }, + }) + done <- err + }() + h.await("quick pick ready", func() bool { return len(h.app.prompts.queue) > 0 && h.app.prompts.queue[0].quick.ready }) + screenshot("workflow-quick-pick") + h.app.answerPrompt(nil) + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-ctx.Done(): + t.Fatal("quick pick did not close") + } + }) + } + } +} diff --git a/desktop/internal/workbench/pluginprompt.go b/desktop/internal/workbench/pluginprompt.go index 596744dd0..0e9f305ca 100644 --- a/desktop/internal/workbench/pluginprompt.go +++ b/desktop/internal/workbench/pluginprompt.go @@ -16,6 +16,7 @@ import ( // pluginPrompt is one question to the user. type pluginPrompt struct { + quick *quickInputState title string text string // mono shows the text in a fixed-pitch font, for commands and paths. @@ -65,6 +66,9 @@ func (a *App) askUser(ctx context.Context, prompt *pluginPrompt) (*int, error) { func (a *App) dropPrompt(prompt *pluginPrompt) { for i, queued := range a.prompts.queue { if queued == prompt { + if prompt.quick != nil { + prompt.quick.clear() + } a.prompts.queue = append(a.prompts.queue[:i], a.prompts.queue[i+1:]...) return } @@ -77,6 +81,13 @@ func (a *App) answerPrompt(choice *int) { return } prompt := a.prompts.queue[0] + if prompt.quick != nil { + if choice != nil && *choice == 1 { + prompt.quick.accept() + } else { + prompt.quick.clear() + } + } a.prompts.queue = a.prompts.queue[1:] if prompt.onAnswer != nil { prompt.onAnswer(choice) @@ -121,6 +132,12 @@ func (a *App) pluginPromptView(c ui.C) { // is a new dialog; it is raised again for each paint the prompt is first. prompt.open = true dismissed := ui.ModalWith(c, &prompt.open, prompt.title, ui.ModalSpec{Width: 520, Height: 320}, func() { + if prompt.quick != nil { + if a.quickInputBody(c, prompt.quick) { + chosen = 1 + } + return + } ui.Scroll(c).Scrollbars().Grow(1).FillWidth().Children(func() { text := ui.Wrap(c, prompt.text).FontSize(13) if prompt.mono { @@ -139,9 +156,12 @@ func (a *App) pluginPromptView(c ui.C) { }, func() { for i, action := range prompt.actions { button := ui.Button(c.KeyInt(i), action) + if prompt.quick != nil && i == 1 { + button = button.Disabled(!prompt.quick.ready) + } if i < len(prompt.actions)-1 { button.Outline() - } else { + } else if prompt.quick == nil { button.AutoFocus() } if button.Clicked() { diff --git a/desktop/internal/workbench/settings_plugins.go b/desktop/internal/workbench/settings_plugins.go index a3ad47c60..86fd571b2 100644 --- a/desktop/internal/workbench/settings_plugins.go +++ b/desktop/internal/workbench/settings_plugins.go @@ -89,3 +89,11 @@ func (s pluginSettingsSources) View(ctx context.Context, editor pluginservice.Se s.app.viewCallFailed(ctx, "plugin_settings_view", err) return drawn, changed, err } + +func (s pluginSettingsSources) WatchView(pluginID, instance string, refresh func()) func() { + return s.app.plugins.WatchView(pluginID, instance, refresh) +} + +func (s pluginSettingsSources) PluginWorkflow(ctx context.Context, request, result any) error { + return s.app.plugins.PluginWorkflow(ctx, request, result) +} diff --git a/desktop/internal/workbench/shell_view.go b/desktop/internal/workbench/shell_view.go index 92815c769..d1be9706d 100644 --- a/desktop/internal/workbench/shell_view.go +++ b/desktop/internal/workbench/shell_view.go @@ -224,6 +224,8 @@ func (a *App) toolBody(c ui.C, tool item, p *project) { a.problemsPanel(c, p) case itemBuild: a.buildToolView(c, p) + case itemOutput: + a.pluginOutputView(c, p) case itemRun: a.runView(c, p) case itemTests: diff --git a/docs/ci-builds.md b/docs/ci-builds.md index 46c03c0c6..3e0a28204 100644 --- a/docs/ci-builds.md +++ b/docs/ci-builds.md @@ -90,6 +90,8 @@ TextMate 首行元数据随各插件归档发布,从已安装版本目录只 Desktop CI 的 LSP 无头截图由 `TestVisualLSPActions` 写入当前工作树的 `.artifacts/lsp-editor-visual/`。截图是当前提交与当前渲染环境的验证产物,绑定源码、平台、Go 工具链和固定的 Viva 与 Core 版本,不跨工作树复用。CI 上传后由运行器清理工作树,截图不进入安装包。 +通用插件工作流的无头截图由 `TestVisualPluginWorkflow` 写入当前检出的 `.artifacts/plugin-workflow-visual/`,覆盖输出与预览、进度菜单、只读对比和快速选择面板的中英文、明暗主题。截图绑定本次提交、平台、Go 工具链和固定的 Viva 与 Core 版本,必须在当前检出重新生成,不跨工作树复制作为验证证据。Linux Desktop CI 通过系统包管理器安装 `fonts-noto-cjk` 到 runner 的系统字体目录,供真实字体回退使用;字体由 runner 持有并随其销毁,不属于检出缓存,不跨工作树复制,也不打包进应用。CI 将 PNG 上传为 `plugin-workflow-visual-<系统>-<架构>` artifact,保留 14 天;本地输出由开发者或 CI 清理,不进入安装包,也不影响代码签名或增量更新基线。 + Desktop CI 的 Build 命令发现截图由 `TestVisualBuildCommandDiscovery` 写入当前工作树的 `.artifacts/build-command-discovery-visual/`。该结果绑定提交、平台、Go 工具链和固定的 Viva 与 Core 版本,上传后由 CI 清理,不跨工作树复制,也不进入安装包。 项目树失焦后的选择由 `TestVisualProjectTreeMissingFile` 验证。Linux Desktop CI 将明暗主题和中英文截图写入当前工作树的 `.artifacts/project-tree-visual/`,上传后保留 14 天。截图对应本次提交、主题、语言、渲染平台、Go 工具链和固定的 Viva 与 Core 版本,不跨工作树复制。运行器清理本地输出,截图不进入安装包。 diff --git a/docs/development/macos-plugin-api-plan.md b/docs/development/macos-plugin-api-plan.md index d3237ed49..8060f5f49 100644 --- a/docs/development/macos-plugin-api-plan.md +++ b/docs/development/macos-plugin-api-plan.md @@ -2,7 +2,50 @@ 状态:待实施计划。盘点日期:2026-10-28;2026-10-30 按 preview `e8c4e9fc9` 刷新(#1517、#1515 已合并)。2026-11-04 补充 Java 拆分对应条目的计划说明与 API-35 第一阶段,不新增 API 编号。 -## 当前实现进度(PR #1595) +## 2026-11-24:Viva 通用工作流 API 增量 + +Core [#193](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/193) 已合入, +[#194](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/194) 补齐原生执行前校验与默认值。 +桌面固定 Core `75e1480`,包含这两项改动,并保留既有 Core #187 增量更新依赖。 +桌面端接入对应的输入、预览、只读对比、输出、进度、状态项、剪贴板、文件管理器和 HTTP。 +纯后端命令接入命令面板与已有快捷键目录,树支持主动刷新、展开懒加载和接近末尾自动分页。 +本次不改变任何系统 API 版本;下文 `ui:4`、协议 3 等是旧客户端的历史记录, +当前协议与四种官方 SDK 只以 [Core 公共资料](https://github.com/Lithe-IDEA/Lithe-core-rust/tree/main/shared/plugins)为准。 + +以下清单按 API 编号升序,每个方法单独登记,用途使用中文;方法名保持协议原名。 +新增 19 个方法,并扩展已有的 HTML 预览和浏览器资源打开,共 21 项: + +| 原计划编号 | 方法 | 用途 | +| --- | --- | --- | +| API-03 | `statusBar/setItem` | 创建或更新本会话状态项,可运行本插件声明的命令 | +| API-03 | `statusBar/removeItem` | 移除本会话的状态项 | +| API-12 | `editor/showDiff` | 在只读对比标签中显示两份内联文本 | +| API-13 | `views/refresh` | 使本会话当前可见视图失效并重新请求 | +| API-16 | `preview/openMarkdown` | 预览 Markdown 资源或会话隔离的只读内联内容 | +| API-16 | `preview/openHTML` | 预览 HTML 资源或只读内联内容,支持仅预览或编辑器与预览并排 | +| API-16 | `browser/openExternal` | 用外部浏览器打开 HTTP(S) 地址或已保存的 HTML 文件 | +| API-17 | `window/showQuickPick` | 显示可搜索、支持多选的原生选择面板 | +| API-17 | `window/showInputBox` | 显示普通或密码输入,区分取消和接受空值 | +| API-18 | `clipboard/readText` | 在独立授权后读取系统剪贴板文本 | +| API-18 | `clipboard/writeText` | 在独立授权后写入系统剪贴板文本 | +| API-18 | `workspace/reveal` | 在系统文件管理器中定位工作区资源 | +| API-22 | `output/create` | 创建本会话拥有的有界输出通道 | +| API-22 | `output/append` | 增量追加文本,按 Core 预算保留输出 | +| API-22 | `output/clear` | 清空通道及当前显示的输出 | +| API-22 | `output/show` | 在工作台输出面板显示指定通道 | +| API-22 | `output/dispose` | 释放本会话的输出通道 | +| API-22 | `progress/create` | 创建可选取消的后台进度并返回订阅 | +| API-22 | `progress/report` | 增量更新消息或百分比,保留省略字段 | +| API-22 | `progress/end` | 结束进度并释放对应订阅 | +| API-38 | `network/request` | 发起可取消、有超时和字节上限的 HTTP(S) 请求 | + +共享参数校验、默认值、权限、过滤排序、分页停止规则与输出增量全部在 Core。 +Viva 只负责原生 I/O、控件呈现及插件/会话/上下文资源释放。 +本轮完成 macOS 定向回归、竞态检查和深浅主题/中英文无头截图;Windows 本轮不验收, +矩阵保持 partial/pending。原生 WebView、系统剪贴板和文件管理器交互仍需各平台整机验收。 +Cookie 自动提取、身份验证会话、AI/MCP 授权和下载到文件不在本次范围内。 + +## 历史实现进度(PR #1595) 本轮已将原有三组宿主内部服务注册为协议 3 的公共方法;`ui:4` 提供不打开 工具窗口的命令。逐方法授权、上下文 lease、编辑器返回 documentID/version、 @@ -13,7 +56,7 @@ 数据源、精确全文搜索匹配范围、文件修改/保存事务、可替换预览标签和 Windows 适配。三个完整安装插件的 UI 验收尚未全部完成,不把分层集成测试等同于整机验收。 -## API-01–44 完成度总表(PR #1595) +## API-01–44 完成度总表(基于 PR #1595,持续更新) 这是**实现范围**,不是发布或全平台验收结论。已公开表示已注册到 Core 白名单及 macOS 宿主分发、插件可按权限调用;仍需以 `getCapabilities` 判断当前宿主支持的方法。 @@ -25,26 +68,26 @@ Windows 不在本轮,平台矩阵的 partial/pending 保持真实。 | --- | --- | --- | | API-01 | 已公开 | 能力发现、backend:2 激活、订阅 dispose;新装后端仍需重启 | | API-02 | 部分完成 | ui:4 无工具窗口的声明命令与 didRun;动态 register/有结果的 execute 未做 | -| API-03 | 部分完成 | 既有命令 placements 可用;通用菜单、快捷键贡献、context.set/状态栏未做 | +| API-03 | 部分完成 | 既有命令 placements 可用;Viva 已接入 statusBar/setItem 与 removeItem,按 Core 顺序呈现;通用菜单、快捷键贡献与 context.set 未做 | | API-04 | 部分完成 | didChangeContexts 与 watch 事件;文档/选区/活动编辑器语义事件未做 | | API-05 | 已公开 | listContexts/getContext/getFolders,context/generation 与 rootID | -| API-06 | 已实现,待合入 | readDirectory/stat/readFile 已由 Rust Core 执行并接入 Viva 本地工作区;逐段拒绝符号链接/reparse point,目录有界分页,磁盘读取上限 128 KiB,支持文本/base64 与截断标记。macOS 定向验证通过;默认 Core 已固定到包含 [Core #190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) 与既有增量更新依赖的 `9ab2336`,本轮不做 Windows 验收 | +| API-06 | 已实现,待合入 | readDirectory/stat/readFile 已由 Rust Core 执行并接入 Viva 本地工作区;逐段拒绝符号链接/reparse point,目录有界分页,磁盘读取上限 128 KiB,支持文本/base64 与截断标记。macOS 定向验证通过;默认 Core 已固定到包含 [Core #190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) 与既有增量更新依赖的 `75e1480`,本轮不做 Windows 验收 | | API-07 | 已实现,待合入 | watch 已接入 Viva 原生事件,Core 负责范围、隐藏过滤、排序去重和溢出重扫;注册先发重扫,dispose/context/session 结束释放且停止通知;macOS 真实文件事件已验证,本轮不做 Windows 验收 | | API-08 | 已实现,精确范围未提供 | findFiles/findText 已由 Core 执行并接入 Viva;查询绑定游标、分页与 200 条总上限、取消、隐藏/索引过滤、no-follow 与磁盘编码处理;只搜磁盘,一行一条结果,range 如实为 null;macOS 定向验证通过 | | API-09 | 已公开 | documents/list/getSnapshot、editor/getActive/getSelections,含 dirty/版本/编码/EOL | | API-10 | 已公开 | applyEdits/replaceSelections/insertText;版本校验、IME/只读拒绝、一次 Undo | | API-11 | 已公开 | Viva 桌面端:`documents/save\|saveAs\|close`(`documents.save`)走文档自己的保存,冲突、硬链接、未命名、组字返回错误码不弹窗;`workspace/create\|rename\|copy\|trash`(`workspace.files.write`)由 Core 严格检查参数并完成磁盘变更(不覆盖、不跟随最后一段),`create` 支持 `kind:"symlink"`,不新增读链接的权限;trash 进系统废纸篓,不提供永久删除;Windows 实机与整机验收未做 | -| API-12 | 部分完成 | 已公开 `documents/registerContentProvider`(只读内容,≤1 MiB,每窗口每 scheme 一个,仅 macOS);公共多文件 edit、showDiff 未接入 | -| API-13 | 部分完成 | 插件视图(ui 0):工具窗口和设置区域的内容由插件后端返回节点树(宿主控件、树、画布),Core `plugins.ui.applyResult` 校验,桌面端用 Viva 原生绘制;设置区域的工具行可带 `choose`(ui 0 内的可选字段)成为该工具的选择器(工具链草稿,Viva 桌面端);旧的 Tree/List/Form 已删除;插件主动推送、树懒加载/分页、`views.reveal` 未做 | +| API-12 | 部分完成 | 已公开 `documents/registerContentProvider`(只读内容,≤1 MiB,每窗口每 scheme 一个,仅 macOS);Viva 已接入 editor/showDiff 的只读内联文本对比;公共多文件 edit 未接入 | +| API-13 | 部分完成 | 插件视图(ui 0):工具窗口和设置区域的内容由插件后端返回节点树(宿主控件、树、画布),Core `plugins.ui.applyResult` 校验,桌面端用 Viva 原生绘制;设置区域的工具行可带 `choose`(ui 0 内的可选字段)成为该工具的选择器(工具链草稿,Viva 桌面端);旧的 Tree/List/Form 已删除;Viva 已接入 views/refresh、hasChildren 展开懒加载与 cursor 自动分页,Core 决定停止条件;`views.reveal` 未做 | | API-14 | 部分完成 | 既有包内网页 bridge、状态/生命周期;通用双向页面消息未做 | | API-15 | 部分完成 | editor/open/reveal 返回 documentID/version;range 只起点光标,替换预览标签未做 | -| API-16 | 已公开 | preview/openHTML 支持 split/previewOnly;browser/openExternal 支持 HTTP(S)/已保存 HTML | -| API-17 | 部分完成 | 三类窗口消息和按钮/取消;通用 QuickPick/InputBox/授权文件句柄未做 | -| API-18 | 未做 | 通用剪贴板与 revealInFinder API 未开放 | +| API-16 | 已公开 | Viva 接入 preview/openMarkdown 与 openHTML(资源或只读内联文本,editorAndPreview/previewOnly);browser/openExternal 支持 HTTP(S)/已保存 HTML,默认 requireSaved;原生 WebView 验收仍待完成 | +| API-17 | 部分完成 | 三类窗口消息和按钮/取消;Viva 新增 showQuickPick(搜索/多选)和 showInputBox(含安全输入);授权文件句柄未做 | +| API-18 | 已接入,原生验收待完成 | clipboard/readText、writeText 与 workspace/reveal 走系统适配器;独立授权,Windows 本轮不验收 | | API-19 | 部分完成 | 已有声明式设置(settings 0)和设置区域 `settingRegions`(搜索关键词、绑定声明设置的插件视图);通用 settings.get/inspect/update/events 未做;Java 拆分计划(M1、D1):Maven 插件按真实配置读取、回显、写回 settings | | API-20 | 部分完成 | global/backend/workspace 可写目录与网页状态;语言服务器的按工作区状态目录按 `state.retention` 后台回收(Core 决定,仅 macOS,无用户可见重置入口);统一 KV/配额/session API 未做 | | API-21 | 既有能力 | 协议 2 credentials/get/set/delete;权限与插件隔离不变 | -| API-22 | 部分完成 | 既有函数进度与取消;语言服务器准备状态 `languageServer/setStatus`(仅百分比,无 actions,仅 macOS);新增 `outputLinkMatchers:1`,插件声明的匹配器让 Run 与测试控制台出现链接(macOS);独立 output channel、通用 log/progress API 未做 | +| API-22 | 部分完成 | 既有函数进度与取消;语言服务器准备状态 `languageServer/setStatus`(仅百分比,无 actions,仅 macOS);新增 `outputLinkMatchers:1`,插件声明的匹配器让 Run 与测试控制台出现链接(macOS);Viva 接入独立 output/create/append/clear/show/dispose 与 progress/create/report/end,复用有界输出视图与任务菜单,按上下文释放;结构化附件未做 | | API-23 | 部分完成 | 已有进程声明与运行时解析;新增 `serverProcess:4` 的工具 ID 引用(清单 `requiresTools`)与后端发起的 `run/start`、`run/stop`、`run/didExit`(macOS,工具 ID 未找到或不可用时返回 -32025);新增 `commandInstallers:0`:插件声明用哪个已注入工具安装 `systemCommand` 启动缺的命令,Core 校验并展开(`plugins.commandInstallers.requirements/plan/defaultDirectory`),宿主在能力卡片显示缺失与安装按钮,用户选择 Lithe 管理的目录或工具默认位置后运行并记录(权限 `commands.install`,Viva 桌面端);`commandInstallers:1` 增加下载安装器:插件为每个平台固定压缩包地址和 SHA-256,宿主确认后复用受管运行时的下载、校验、解压实现装进受管目录(Viva 桌面端);通用 toolchains/process 服务未开放 | | API-24 | 部分完成 | 已公开插件自有原生终端 create/show/close/reopen/dispose/onExit(macOS、本机);不开放 sendText/输出读取,Windows 待接入 | | API-25 | 部分完成 | 既有语言/LSP 贡献;`languages:2` 的清单与包内 JSON 语法/编辑配置,仅支持 Monarch;新增 `languageServers:3` 与 `serverProcess:3`:后端经 `languageServer/request\|notify\|setStatus` 使用自己的服务器、后端启动(`launch.kind:"backend"`),会话策略由 Core 执行(仅 macOS,远程后端启动未支持,见 Agent Note 2026-11-04-plugin-owned-language-server-sessions);新增宿主方法 `lithe/host/editor/registerProviders`(权限 `editor.providers`,macOS,待运行验收)把 definition/hover/completion/codeLens/foldingRange/semanticTokens/documentLink 绑定到普通插件函数,语言服务器优先、插件只补充;标准 LSP 的 Code Actions、签名帮助和内联提示由 Viva 编辑器呈现(#2128)。自定义插件 Provider 的符号、格式化、重命名、Code Action、签名帮助、内联提示及运行期 JSON 动态注册高亮仍待补齐;Java 拆分计划(C-EDIT):Spring、MyBatis 只补上游缺失的 Provider | @@ -60,7 +103,7 @@ Windows 不在本轮,平台矩阵的 partial/pending 保持真实。 | API-35 | 第一阶段进行中 | 第一阶段是 Java 拆分所需的 Core 中转插件函数调用(插件 1 → Core → 插件 2,C-IMPORT,进行中,不是安装依赖);依赖/导出安装闭包、版本求解、远程 Provider 剩余接续未完成 | | API-36 | 未做 | WASM/WASI 非本轮前置,未引入运行时 | | API-37 | 部分完成 | getCapabilities 提供协议/方法/预算/后端执行位置;插件设置文字的包内语言文件 `l10n/<语言>.json` 已做(`pluginAPIVersion` 0 补充,Core #36;桌面端只读地从已安装包取文件,按界面语言重读且保留草稿);其它插件文字的语言包与环境/主题事件未做;Java 拆分:界面语言走本项的环境信息,不在 workspace context 里加 locale | -| API-38 | 未做 | 通用受管 fetch/download 未开放 | +| API-38 | 部分完成 | network/request 已接入有界、可取消 HTTP(S),无 Cookie jar、不自动跟随重定向;下载到文件与身份验证会话未做 | | API-39 | 未做 | 通用 authentication session/provider 未开放 | | API-40 | 部分完成 | 上下文携带 local/remote;新文件/编辑器服务对 remote 明确拒绝,非远程执行实现 | | API-41 | 部分完成 | onWorkspaceOpen/onCommand、后台两路、initialize 超时/有界通知;内容匹配与全局冷启预算未做 | @@ -111,8 +154,12 @@ Windows 不在本轮,平台矩阵的 partial/pending 保持真实。 | 文档/选区 | documents.list/getSnapshot;editor.getActive/getSelections | documents.read | | 版本化编辑 | editor.applyEdits/replaceSelections/insertText | editor.edit | | 打开/定位 | editor.open/reveal | editor.open | -| 预览/浏览器 | preview.openHTML;browser.openExternal | preview.open;browser.open | -| 窗口消息 | window.showInformation/showWarning/showError | window.messages | +| 预览/浏览器 | preview.openMarkdown/openHTML;browser.openExternal | preview.open;browser.open | +| 窗口消息与输入 | window.showInformation/showWarning/showError;window.showQuickPick/showInputBox | window.messages;window.input | +| 剪贴板与定位 | clipboard.readText/writeText;workspace.reveal | clipboard.read;clipboard.write;workspace.reveal | +| 输出、进度、状态 | output.create/append/clear/show/dispose;progress.create/report/end;statusBar.setItem/removeItem | output.write;window.progress;statusBar.write | +| 视图刷新与对比 | views.refresh;editor.showDiff | views.refresh;editor.open | +| HTTP | network.request | network.request | | 本插件凭据 | credentials.get/set/delete | credentials.store | 宿主通知:workspace.didChangeContexts、subscriptions.notify、commands.didRun。 diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 64d81a5de..50e46f199 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -376,7 +376,7 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # #187 delta dependency at 076ce04. Both parents remain independently reviewable; # the pin preserves marketplace delta commands while adding workspace disk reads, # bounded search and native-watch planning/filtering. -PINNED_CORE_REVISION="9ab2336e8ca651e40baa5e65848b717b26f69e43" +PINNED_CORE_REVISION="75e148091439248e5927c58790019b26de02ca87" PROFILE="debug" CHECKOUT_ONLY="no" while [[ $# -gt 0 ]]; do diff --git a/shared/i18n/features/plugin-permissions.json b/shared/i18n/features/plugin-permissions.json index d5e62f436..c7dd13538 100644 --- a/shared/i18n/features/plugin-permissions.json +++ b/shared/i18n/features/plugin-permissions.json @@ -189,6 +189,69 @@ "platforms": [ "desktop" ] + }, + { + "id": "desktop.marketplace.permissionWindowInput", + "description": "Plugin permission list: what window.input allows", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.marketplace.permissionViewsRefresh", + "description": "Plugin permission list: what views.refresh allows", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.marketplace.permissionOutputWrite", + "description": "Plugin permission list: what output.write allows", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.marketplace.permissionWindowProgress", + "description": "Plugin permission list: what window.progress allows", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.marketplace.permissionStatusBarWrite", + "description": "Plugin permission list: what statusBar.write allows", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.marketplace.permissionClipboardRead", + "description": "Plugin permission list: what clipboard.read allows", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.marketplace.permissionClipboardWrite", + "description": "Plugin permission list: what clipboard.write allows", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.marketplace.permissionWorkspaceReveal", + "description": "Plugin permission list: what workspace.reveal allows", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.marketplace.permissionNetworkRequest", + "description": "Plugin permission list: what network.request allows", + "platforms": [ + "desktop" + ] } ], "locales": { @@ -209,7 +272,7 @@ "desktop.marketplace.permissionEditorActions": "Show its own actions in the editor, such as run icons beside lines", "desktop.marketplace.permissionEditorProviders": "Provide completion, hover and other language features in the editor", "desktop.marketplace.permissionEditorOpen": "Open files in the editor and go to locations in them", - "desktop.marketplace.permissionPreviewOpen": "Open HTML files in a preview", + "desktop.marketplace.permissionPreviewOpen": "Preview Markdown and HTML files or read-only content", "desktop.marketplace.permissionToolchainsProvide": "Find installed tools, such as SDKs, and list them in Toolchains", "desktop.marketplace.permissionKeymapsProvide": "Offer keymaps from other editors for you to import", "desktop.marketplace.permissionKeymapsReadSelectedSources": "Read keymap files only from the source you choose to import", @@ -219,7 +282,16 @@ "desktop.marketplace.permissionRunStart": "Start and stop runs in the Run window", "desktop.marketplace.permissionDebugStart": "Start debugging with its own debuggers", "desktop.marketplace.permissionLanguageServerRequest": "Send requests to its own language servers", - "desktop.marketplace.permissionDocumentsContentProvider": "Show read-only files it supplies, such as library sources" + "desktop.marketplace.permissionDocumentsContentProvider": "Show read-only files it supplies, such as library sources", + "desktop.marketplace.permissionWindowInput": "Ask you to select items or enter text, including masked passwords", + "desktop.marketplace.permissionViewsRefresh": "Refresh its currently open views", + "desktop.marketplace.permissionOutputWrite": "Create and manage its own output channels", + "desktop.marketplace.permissionWindowProgress": "Show progress and receive your cancellation requests", + "desktop.marketplace.permissionStatusBarWrite": "Show its own status items and command buttons", + "desktop.marketplace.permissionClipboardRead": "Read text from your system clipboard", + "desktop.marketplace.permissionClipboardWrite": "Write text to your system clipboard", + "desktop.marketplace.permissionWorkspaceReveal": "Reveal workspace files in the file manager", + "desktop.marketplace.permissionNetworkRequest": "Send HTTP requests with the host’s proxy and certificate settings" }, "zh-CN": { "desktop.marketplace.permissionVcs": "为项目运行版本控制工具", @@ -238,7 +310,7 @@ "desktop.marketplace.permissionEditorActions": "在编辑器中显示插件自己的操作,例如行旁的运行图标", "desktop.marketplace.permissionEditorProviders": "在编辑器中提供补全、悬停提示等语言功能", "desktop.marketplace.permissionEditorOpen": "在编辑器中打开文件并跳转到其中的位置", - "desktop.marketplace.permissionPreviewOpen": "在预览中打开 HTML 文件", + "desktop.marketplace.permissionPreviewOpen": "预览 Markdown、HTML 文件或只读内容", "desktop.marketplace.permissionToolchainsProvide": "查找已安装的工具(例如 SDK),并列在“工具链”中", "desktop.marketplace.permissionKeymapsProvide": "提供可从其他编辑器导入的快捷键方案", "desktop.marketplace.permissionKeymapsReadSelectedSources": "只读取你选择导入的来源中的快捷键文件", @@ -248,7 +320,16 @@ "desktop.marketplace.permissionRunStart": "在“运行”窗口中启动和停止运行", "desktop.marketplace.permissionDebugStart": "用插件自己的调试器开始调试", "desktop.marketplace.permissionLanguageServerRequest": "向插件自己的语言服务器发送请求", - "desktop.marketplace.permissionDocumentsContentProvider": "显示插件提供的只读文件,例如库的源码" + "desktop.marketplace.permissionDocumentsContentProvider": "显示插件提供的只读文件,例如库的源码", + "desktop.marketplace.permissionWindowInput": "请求选择条目或输入文本,包括掩码密码", + "desktop.marketplace.permissionViewsRefresh": "刷新插件当前打开的视图", + "desktop.marketplace.permissionOutputWrite": "创建和管理插件自己的输出通道", + "desktop.marketplace.permissionWindowProgress": "显示进度并接收你的取消请求", + "desktop.marketplace.permissionStatusBarWrite": "显示插件自己的状态项和命令按钮", + "desktop.marketplace.permissionClipboardRead": "读取系统剪贴板中的文本", + "desktop.marketplace.permissionClipboardWrite": "向系统剪贴板写入文本", + "desktop.marketplace.permissionWorkspaceReveal": "在文件管理器中显示工作区文件", + "desktop.marketplace.permissionNetworkRequest": "使用宿主的代理和证书设置发送 HTTP 请求" } } } diff --git a/shared/i18n/locales/en-US.json b/shared/i18n/locales/en-US.json index 2b15a5260..66fd96d85 100644 --- a/shared/i18n/locales/en-US.json +++ b/shared/i18n/locales/en-US.json @@ -11682,7 +11682,15 @@ "desktop.run.ports.open": "Open in browser", "desktop.run.ports.copy": "Copy URL", "desktop.run.ports.more": "+{count}", - "desktop.run.ports.openFailed": "Could not open {url}." + "desktop.run.ports.openFailed": "Could not open {url}.", + "desktop.pluginHost.backgroundTasks": "Plugin progress", + "desktop.pluginHost.commandFailed": "The plugin command failed. See the logs for details.", + "desktop.pluginHost.diff": "Text Comparison", + "desktop.pluginHost.inputLimit": "The input is too long or contains unsupported control characters.", + "desktop.pluginHost.modified": "Modified", + "desktop.pluginHost.noOutput": "No output channels", + "desktop.pluginHost.original": "Original", + "desktop.pluginHost.output": "Output" }, "overrides": { "windows": { diff --git a/shared/i18n/locales/zh-CN.json b/shared/i18n/locales/zh-CN.json index c7ec95ffa..f53ed5f07 100644 --- a/shared/i18n/locales/zh-CN.json +++ b/shared/i18n/locales/zh-CN.json @@ -11682,7 +11682,15 @@ "desktop.run.ports.open": "在浏览器中打开", "desktop.run.ports.copy": "复制地址", "desktop.run.ports.more": "+{count}", - "desktop.run.ports.openFailed": "无法打开 {url}。" + "desktop.run.ports.openFailed": "无法打开 {url}。", + "desktop.pluginHost.backgroundTasks": "插件进度", + "desktop.pluginHost.commandFailed": "插件命令执行失败,请查看日志。", + "desktop.pluginHost.diff": "文本对比", + "desktop.pluginHost.inputLimit": "输入过长或包含不支持的控制字符。", + "desktop.pluginHost.modified": "修改后的文本", + "desktop.pluginHost.noOutput": "暂无输出通道", + "desktop.pluginHost.original": "原始文本", + "desktop.pluginHost.output": "输出" }, "overrides": { "macos": { diff --git a/shared/i18n/messages.json b/shared/i18n/messages.json index 959c72812..ff910d6c2 100644 --- a/shared/i18n/messages.json +++ b/shared/i18n/messages.json @@ -110180,6 +110180,62 @@ "count": "string", "files": "string" } + }, + { + "id": "desktop.pluginHost.backgroundTasks", + "description": "Native plugin workflow backgroundTasks", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.pluginHost.commandFailed", + "description": "Native plugin workflow commandFailed", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.pluginHost.diff", + "description": "Native plugin workflow diff", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.pluginHost.inputLimit", + "description": "Native plugin workflow inputLimit", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.pluginHost.modified", + "description": "Native plugin workflow modified", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.pluginHost.noOutput", + "description": "Native plugin workflow noOutput", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.pluginHost.original", + "description": "Native plugin workflow original", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.pluginHost.output", + "description": "Native plugin workflow output", + "platforms": [ + "desktop" + ] } ] } diff --git a/shared/platform-feature-matrix/features/declarative-native-plugin-ui.json b/shared/platform-feature-matrix/features/declarative-native-plugin-ui.json index 7bf30e783..f38ede259 100644 --- a/shared/platform-feature-matrix/features/declarative-native-plugin-ui.json +++ b/shared/platform-feature-matrix/features/declarative-native-plugin-ui.json @@ -2,7 +2,7 @@ "id": "declarative-native-plugin-ui", "area": "插件", "group": "插件界面", - "capability": "插件视图(ui 0 的 view 工具窗口):插件后端的视图函数返回节点树(JSON 场景),宿主用自己的 Viva 控件原生绘制,后端不接触界面库;节点包括 row/section 布局、label、textField、select/segmented、toggle、button、keyValue、table、banner、可折叠树(选择、双击激活、超过 12 行自身滚动)和画布(rect/path/text/image/group,主题色令牌 $accent 等、viewBox 缩放:不写 pan 时完整显示、写了 pan 时宽度占满,平移缩放视口);宿主在绘制时量出视图宽度,量到后才发 open,每个事件带 width;按契约发送 open/close/click/change/select/activate/viewport/resize/settings 事件,同一时间只发一个调用、viewport、resize 与 settings 事件 400 ms 去抖合并,画布在 on 写了 resize 时窗口宽度变化后发 resize,让插件按新宽度重新排版;答案由 Core 校验后才绘制;失败显示宿主文案加插件原文并可重试,关闭、停用或替换时取消并丢弃晚到答案;工具窗口标题栏图标与停靠位置沿用已有工具窗口;设置区域(settingRegions)复用同一渲染器,见 plugin-registered-settings-pages", + "capability": "插件视图(ui 0 的 view 工具窗口):插件后端的视图函数返回节点树(JSON 场景),宿主用自己的 Viva 控件原生绘制,后端不接触界面库;节点包括 row/section 布局、label、textField、select/segmented、toggle、button、keyValue、table、banner、可折叠树(选择、双击激活、超过 12 行自身滚动)和画布(rect/path/text/image/group,主题色令牌 $accent 等、viewBox 缩放:不写 pan 时完整显示、写了 pan 时宽度占满,平移缩放视口);宿主在绘制时量出视图宽度,量到后才发 open,每个事件带 width;按契约发送 open/close/click/change/select/activate/viewport/resize/settings 事件,同一时间只发一个调用、viewport、resize 与 settings 事件 400 ms 去抖合并,画布在 on 写了 resize 时窗口宽度变化后发 resize,让插件按新宽度重新排版;答案由 Core 校验后才绘制;失败显示宿主文案加插件原文并可重试,关闭、停用或替换时取消并丢弃晚到答案;工具窗口标题栏图标与停靠位置沿用已有工具窗口;设置区域(settingRegions)复用同一渲染器,见 plugin-registered-settings-pages;支持 views/refresh 主动失效、hasChildren 分支懒加载与 cursor 自动分页,由 Core 决定分页停止条件", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", @@ -24,7 +24,9 @@ "desktop/internal/pluginview/view_visual_test.go", "desktop/internal/workbench/plugin_view.go", "desktop/internal/workbench/plugin_view_test.go", - "desktop/internal/settingswindow/plugin_region_view_test.go" + "desktop/internal/settingswindow/plugin_region_view_test.go", + "desktop/internal/pluginservice/hostviewrefresh.go", + "desktop/internal/core/plugin_workflow.go" ] }, "windows": { @@ -48,11 +50,13 @@ "desktop/internal/pluginview/view_visual_test.go", "desktop/internal/workbench/plugin_view.go", "desktop/internal/workbench/plugin_view_test.go", - "desktop/internal/settingswindow/plugin_region_view_test.go" + "desktop/internal/settingswindow/plugin_region_view_test.go", + "desktop/internal/pluginservice/hostviewrefresh.go", + "desktop/internal/core/plugin_workflow.go" ] }, "owner": "Plugin Platform", - "verification": "自动化:scripts/desktop/desktop-go.sh test ./internal/pluginview/ ./internal/pluginservice/ ./internal/workbench/ ./internal/core/,覆盖事件顺序与去抖、量到宽度后才发 open、每个事件带 width、resize 去抖与合并(含无头窗口缩小后发送新宽度)、画布缩放规则、晚到答案丢弃、失败重试、节点解析、画布路径与颜色、图片限制、嵌套树高度,宿主视图事件参数(Core 契约 fixture settings.plugin.json)和工作台视图调用失败的日志;无头截图:LITHE_VISUAL_OUTPUT_DIR=<目录> scripts/desktop/desktop-go.sh test -tags 'vivahead lithevisual' -run TestVisualPluginView ./internal/pluginview/,检查深浅主题。原生整机验收 pending:安装一个声明 view 工具窗口的测试插件,打开、点击、编辑、选择树项、双击激活、拖动与缩放画布,拖动窗口改变宽度后画布按新宽度重新排版、不放大也不裁剪,确认事件到达后端并重绘;停用插件、关闭项目时视图关闭且无晚到重绘;后端报错时显示失败与重试。Windows 使用同一 Go Viva 桌面端,需在 Windows 虚拟机上重复上述原生验收。 严格 dev 属性校验下,TestRegionViewSkipsUnavailableNodesWithoutRenamingTheirNeighbors 覆盖 label、缺失的 setting/tool 和类型不匹配的绑定节点:跳过节点后不影响后续文本或控件身份。", + "verification": "自动化:scripts/desktop/desktop-go.sh test ./internal/pluginview/ ./internal/pluginservice/ ./internal/workbench/ ./internal/core/,覆盖事件顺序与去抖、量到宽度后才发 open、每个事件带 width、resize 去抖与合并(含无头窗口缩小后发送新宽度)、画布缩放规则、晚到答案丢弃、失败重试、节点解析、画布路径与颜色、图片限制、嵌套树高度,宿主视图事件参数(Core 契约 fixture settings.plugin.json)和工作台视图调用失败的日志;无头截图:LITHE_VISUAL_OUTPUT_DIR=<目录> scripts/desktop/desktop-go.sh test -tags 'vivahead lithevisual' -run TestVisualPluginView ./internal/pluginview/,检查深浅主题。原生整机验收 pending:安装一个声明 view 工具窗口的测试插件,打开、点击、编辑、选择树项、双击激活、拖动与缩放画布,拖动窗口改变宽度后画布按新宽度重新排版、不放大也不裁剪,确认事件到达后端并重绘;停用插件、关闭项目时视图关闭且无晚到重绘;后端报错时显示失败与重试。Windows 使用同一 Go Viva 桌面端,需在 Windows 虚拟机上重复上述原生验收。 严格 dev 属性校验下,TestRegionViewSkipsUnavailableNodesWithoutRenamingTheirNeighbors 覆盖 label、缺失的 setting/tool 和类型不匹配的绑定节点:跳过节点后不影响后续文本或控件身份。 macOS TestSessionRefreshCoalescesAndClosedShowingCannotRefreshTheNext 验证刷新合并和旧显示不能刷新重开的视图;工作流与视图定向竞态检查覆盖释放。分页投影使用 Core 共享 fixture。Windows 本轮不验收,保持 pending。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { @@ -89,5 +93,5 @@ ] } }, - "notes": "Viva:pluginview 包是通用渲染器(session.go 管事件队列与去抖,render.go 绘制控件与树,canvas.go 绘制画布),pluginservice/hostview.go 经 Core 调用后端视图函数并校验答案,workbench/plugin_view.go 把视图挂进工具窗口;旧的 ui 原生树/列表/表单(plugin_native.go、hostnative.go)已删除,由插件视图取代。Viva 尚不支持的画布能力(自定义虚线、多色路径渐变、位图与图层透明度、捏合缩放、圆角裁剪)按契约降级绘制,在 Viva fork 跟进(#2182)。 节点身份以 NodeKey 值传递,仅在实际绘制容器或控件时应用;label 无身份,可选节点提前返回不留下待使用的名字。" + "notes": "Viva:pluginview 包是通用渲染器(session.go 管事件队列与去抖,render.go 绘制控件与树,canvas.go 绘制画布),pluginservice/hostview.go 经 Core 调用后端视图函数并校验答案,workbench/plugin_view.go 把视图挂进工具窗口;旧的 ui 原生树/列表/表单(plugin_native.go、hostnative.go)已删除,由插件视图取代。Viva 尚不支持的画布能力(自定义虚线、多色路径渐变、位图与图层透明度、捏合缩放、圆角裁剪)按契约降级绘制,在 Viva fork 跟进(#2182)。 节点身份以 NodeKey 值传递,仅在实际绘制容器或控件时应用;label 无身份,可选节点提前返回不留下待使用的名字。 主动刷新回调绑定插件、会话、上下文与实例,关闭时先失效再取消观察。树保留稳定选择和展开,展开时发 expand;视口接近末尾时由 Core 判断是否发 loadMore,游标重复或累积范围没有增长就停止,失败后显式重试。纯后端命令复用命令面板和已有快捷键目录,不要求工具窗口。" } 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 aa2dbc57a..5ab04b096 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 @@ -2,7 +2,7 @@ "id": "plugin-host-editor-file-window-services", "area": "扩展", "group": "插件与主题", - "capability": "插件公共宿主服务:按方法授权的文档读取、选区、版本化编辑、文档保存/另存为/关闭、工作区文件新建(含符号链接)/重命名/复制/移到废纸篓、工作区文件/搜索/watch、编辑器打开、HTML 预览与外部浏览器、窗口消息", + "capability": "插件公共宿主服务:按方法授权的文档读取、选区、版本化编辑、文档保存/另存为/关闭、工作区文件新建(含符号链接)/重命名/复制/移到废纸篓、工作区文件/搜索/watch、编辑器打开、HTML 预览与外部浏览器、窗口消息、Markdown/内联只读预览、文本对比、快速选择与输入、剪贴板与文件管理器、输出与进度、状态项、有界 HTTP", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", @@ -31,7 +31,13 @@ "desktop/internal/pluginservice/hostworkspacefind.go", "desktop/internal/pluginservice/hostworkspacefind_test.go", "desktop/internal/pluginservice/hostworkspacewatch.go", - "desktop/internal/pluginservice/hostworkspacewatch_test.go" + "desktop/internal/pluginservice/hostworkspacewatch_test.go", + "desktop/internal/core/plugin_workflow.go", + "desktop/internal/pluginservice/hostworkflow.go", + "desktop/internal/pluginservice/hostworkflow_test.go", + "desktop/internal/workbench/plugin_workflow.go", + "desktop/internal/workbench/plugin_workflow_test.go", + "desktop/internal/workbench/plugin_workflow_visual_test.go" ] }, "windows": { @@ -62,12 +68,18 @@ "desktop/internal/pluginservice/hostworkspacefind.go", "desktop/internal/pluginservice/hostworkspacefind_test.go", "desktop/internal/pluginservice/hostworkspacewatch.go", - "desktop/internal/pluginservice/hostworkspacewatch_test.go" + "desktop/internal/pluginservice/hostworkspacewatch_test.go", + "desktop/internal/core/plugin_workflow.go", + "desktop/internal/pluginservice/hostworkflow.go", + "desktop/internal/pluginservice/hostworkflow_test.go", + "desktop/internal/workbench/plugin_workflow.go", + "desktop/internal/workbench/plugin_workflow_test.go", + "desktop/internal/workbench/plugin_workflow_visual_test.go" ] }, "owner": "Extensions", - "verification": "API-06–08:默认固定 Core 9ab2336(含 Core #190 与既有 #187 增量更新),运行 scripts/desktop/desktop-go.sh test ./internal/core ./internal/pluginservice ./internal/workbench -run 'TestWorkspace(Reads|Find|Search|Watch)|TestPluginWorkspace' -count=1 及对应 -race 检查,验证真实文件分页、文本/二进制读取、资源封装与权限上下文隔离、dirty 文档仍读磁盘及项目关闭取消,搜索分页/查询游标/范围与磁盘隔离,以及 macOS/Linux Viva 原生监听的递归创建、原子保存、删除、调用方归属、会话/上下文释放、在途通知取消、根目录替换后的最终重扫与释放;Windows 上 root-replacement 子用例因 ReadDirectoryChangesW 持有目录句柄阻塞跨父目录重命名及不投递自身重命名事件而跳过(跟踪于 #2374),dispose/context/session 释放子用例继续在 Windows 运行。Windows 原生验收按用户要求本轮不执行,保持 pending。API-11:scripts/desktop/desktop-go.sh test ./internal/pluginservice -run 'TestFileChanges|TestChangeError' 与 ./internal/workbench -run 'TestPlugin(Save|Create|Rename|Trash)'。两平台原生验收使用内联合成插件:读取分页目录、磁盘文件,验证链接与 .. 越界拒绝、取消和重开工作区隔离,再保存/另存为、复制、重命名打开文件、移到废纸篓并恢复;无头测试不能替代 Windows reparse point 与目录共享行为验收。验收后关闭应用并确认无残留进程。", - "notes": "Viva 已接通 documents/list|getSnapshot、editor/getActive|getSelections|open|reveal|insertText|replaceSelections|applyEdits、window/showInformation|showWarning|showError、browser/openExternal(仅 http/https URL)、documents/registerContentProvider、editor/registerProviders。编辑走编辑器自己的撤销栈,整批一步,按 view 修订号做版本隔离,只读/组字/过期版本被拒。editor/open 只落光标(范围起点)。API-11(documents.save、workspace.files.write)已接通:documents/save|saveAs|close 走文档自己的保存,磁盘冲突、硬链接、未命名文档、组字被拒并返回错误码,不弹窗;workspace/create(文件、文件夹、kind:\"symlink\" 的符号链接)|rename|copy|trash 的参数由 Core 严格检查,磁盘变更由 Core 内核命令 workspace.createEntry|renameEntry|copyEntry|resolveEntry 完成(不跟随最后一段、不覆盖),窗口只负责先保存其下文档、打开的文档跟随文件移动、本地历史、项目树和系统废纸篓;Windows 上建符号链接需要开发者模式或管理员,否则返回 failed。API-06(workspace.files.read)已接通本地工作区的 workspace/readDirectory|stat|readFile:路径、隐藏规则、有界分页、no-follow 和 128 KiB 磁盘读取预算均由 Core 执行,文本/base64 与截断前缀 identity 如实返回,不读取 dirty 文档;窗口关闭或替换会取消并拒绝旧结果,remote authority 明确拒绝。API-07/08 已接通 workspace/watch|findFiles|findText:Core 复用匹配、编码和隐藏/索引规则,以 no-follow 句柄搜索磁盘、处理分页游标与监听过滤;Viva 原生事件无空闲轮询,订阅按插件/会话/上下文释放,dispose 返回前停止通知;搜索每页和总结果最多 200,精确范围为 null。macOS 真实文件与原生事件测试已通过;Windows 本轮不验收。默认 Core 已固定到 9ab2336,包含本次 Core #190 改动并保留既有 #187 增量更新依赖。整体条目仍含其他未完成能力,状态保持 partial/pending。未接通:preview/openHTML(Viva 有系统 Web 视图,但编辑器区还没有嵌入网页的标签)、browser/openExternal 的 resource 形式(返回 unsupportedOption)。", + "verification": "API-06–08:默认固定 Core 75e1480(含 Core #190 与既有 #187 增量更新),运行 scripts/desktop/desktop-go.sh test ./internal/core ./internal/pluginservice ./internal/workbench -run 'TestWorkspace(Reads|Find|Search|Watch)|TestPluginWorkspace' -count=1 及对应 -race 检查,验证真实文件分页、文本/二进制读取、资源封装与权限上下文隔离、dirty 文档仍读磁盘及项目关闭取消,搜索分页/查询游标/范围与磁盘隔离,以及 macOS Viva 原生监听的递归创建、原子保存、删除、调用方归属、会话/上下文释放、在途通知取消、根目录替换后的最终重扫与释放。Windows 原生验收按用户要求本轮不执行,保持 pending。API-11:scripts/desktop/desktop-go.sh test ./internal/pluginservice -run 'TestFileChanges|TestChangeError' 与 ./internal/workbench -run 'TestPlugin(Save|Create|Rename|Trash)'。两平台原生验收使用内联合成插件:读取分页目录、磁盘文件,验证链接与 .. 越界拒绝、取消和重开工作区隔离,再保存/另存为、复制、重命名打开文件、移到废纸篓并恢复;无头测试不能替代 Windows reparse point 与目录共享行为验收。验收后关闭应用并确认无残留进程。 工作流增量:macOS 执行 scripts/desktop/desktop-go.sh test ./internal/workbench ./internal/pluginservice ./internal/pluginview -run 'Test(Workflow|BrowserOpensOnlyHTTP|SessionRefresh|WorkbenchDefaultLayout)' -count=1 -timeout=45s 及同范围 -race。覆盖取消和释放、关闭上下文取消在途调用、HTTP 重定向与预算及错误脱敏、预览更新和会话隔离、只读 Diff、输出清空、进度部分更新、密码取消清理。TestVisualPluginWorkflow 生成深浅主题及中英文截图,CI 上传 plugin-workflow-visual artifact。系统 WebView、剪贴板、浏览器和文件管理器的整机验收仍待完成;Windows 本轮不验收。", + "notes": "Viva 已接通 documents/list|getSnapshot、editor/getActive|getSelections|open|reveal|insertText|replaceSelections|applyEdits、window/showInformation|showWarning|showError、browser/openExternal(HTTP(S) 地址或已保存 HTML 资源)、documents/registerContentProvider、editor/registerProviders。编辑走编辑器自己的撤销栈,整批一步,按 view 修订号做版本隔离,只读/组字/过期版本被拒。editor/open 只落光标(范围起点)。API-11(documents.save、workspace.files.write)已接通:documents/save|saveAs|close 走文档自己的保存,磁盘冲突、硬链接、未命名文档、组字被拒并返回错误码,不弹窗;workspace/create(文件、文件夹、kind:\"symlink\" 的符号链接)|rename|copy|trash 的参数由 Core 严格检查,磁盘变更由 Core 内核命令 workspace.createEntry|renameEntry|copyEntry|resolveEntry 完成(不跟随最后一段、不覆盖),窗口只负责先保存其下文档、打开的文档跟随文件移动、本地历史、项目树和系统废纸篓;Windows 上建符号链接需要开发者模式或管理员,否则返回 failed。API-06(workspace.files.read)已接通本地工作区的 workspace/readDirectory|stat|readFile:路径、隐藏规则、有界分页、no-follow 和 128 KiB 磁盘读取预算均由 Core 执行,文本/base64 与截断前缀 identity 如实返回,不读取 dirty 文档;窗口关闭或替换会取消并拒绝旧结果,remote authority 明确拒绝。API-07/08 已接通 workspace/watch|findFiles|findText:Core 复用匹配、编码和隐藏/索引规则,以 no-follow 句柄搜索磁盘、处理分页游标与监听过滤;Viva 原生事件无空闲轮询,订阅按插件/会话/上下文释放,dispose 返回前停止通知;搜索每页和总结果最多 200,精确范围为 null。macOS 真实文件与原生事件测试已通过;Windows 本轮不验收。默认 Core 已固定到 75e1480,包含本次 Core #190 改动并保留既有 #187 增量更新依赖。整体条目仍含其他未完成能力,状态保持 partial/pending。Core #193 与 #194 的工作流已接入:Markdown/HTML 资源和内联只读预览、只读文本对比、快速选择和安全输入、剪贴板、文件管理器定位、输出、进度、状态项、有界 HTTP。Core 负责参数、默认值、权限、过滤排序与预算;Viva 只做原生 I/O 和呈现。HTML 在原生 WebView 不可用时于打开标签前拒绝。浏览器资源默认 requireSaved,不自动保存。HTTP 惰性复用连接,无 Cookie jar、不跟随重定向,错误不带 URL 或正文。长期资源按插件、会话和上下文释放,不新增磁盘缓存。复杂身份验证、Cookie 提取与下载到文件不在本次范围。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": {