From 3396ae61837956aeb4ba88d60fea3cfc8481b9e9 Mon Sep 17 00:00:00 2001 From: "lithe-support[bot]" <356900028+lithe-support[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:58:57 +0000 Subject: [PATCH 01/20] feat(i18n): declare managed runtime preparation messages --- .../features/plugin-managed-runtimes.json | 125 ++++++++++++++++++ 1 file changed, 125 insertions(+) create mode 100644 shared/i18n/features/plugin-managed-runtimes.json diff --git a/shared/i18n/features/plugin-managed-runtimes.json b/shared/i18n/features/plugin-managed-runtimes.json new file mode 100644 index 000000000..e3503acae --- /dev/null +++ b/shared/i18n/features/plugin-managed-runtimes.json @@ -0,0 +1,125 @@ +{ + "schemaVersion": 1, + "messages": [ + { + "id": "desktop.marketplace.runtimeChecking", + "description": "Managed plugin runtime installation: runtimeChecking", + "platforms": [ + "desktop" + ], + "parameters": { + "dependency": "string" + } + }, + { + "id": "desktop.marketplace.runtimeDownloading", + "description": "Managed plugin runtime installation: runtimeDownloading", + "platforms": [ + "desktop" + ], + "parameters": { + "dependency": "string", + "received": "string", + "total": "string" + } + }, + { + "id": "desktop.marketplace.runtimeReceived", + "description": "Managed plugin runtime installation: runtimeReceived", + "platforms": [ + "desktop" + ], + "parameters": { + "dependency": "string", + "received": "string" + } + }, + { + "id": "desktop.marketplace.runtimeExtracting", + "description": "Managed plugin runtime installation: runtimeExtracting", + "platforms": [ + "desktop" + ], + "parameters": { + "dependency": "string" + } + }, + { + "id": "desktop.marketplace.runtimeVerifying", + "description": "Managed plugin runtime installation: runtimeVerifying", + "platforms": [ + "desktop" + ], + "parameters": { + "dependency": "string" + } + }, + { + "id": "desktop.marketplace.runtimeRepairing", + "description": "Managed plugin runtime installation: runtimeRepairing", + "platforms": [ + "desktop" + ], + "parameters": { + "dependency": "string" + } + }, + { + "id": "desktop.marketplace.runtimeReady", + "description": "Managed plugin runtime installation: runtimeReady", + "platforms": [ + "desktop" + ], + "parameters": { + "dependency": "string" + } + }, + { + "id": "desktop.marketplace.permissionRuntimesInstall", + "description": "Managed plugin runtime installation: permissionRuntimesInstall", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.marketplace.runtimeFailureHelp", + "description": "Managed plugin runtime installation: runtimeFailureHelp", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.lsp.preparationCancelled", + "description": "Language service runtime preparation was cancelled; it can be retried from the status menu.", + "platforms": [ + "desktop" + ] + } + ], + "locales": { + "en-US": { + "desktop.marketplace.runtimeChecking": "Checking {dependency}…", + "desktop.marketplace.runtimeDownloading": "Downloading {dependency}… {received} / {total} MiB", + "desktop.marketplace.runtimeReceived": "Downloading {dependency}… {received} MiB", + "desktop.marketplace.runtimeExtracting": "Unpacking {dependency}…", + "desktop.marketplace.runtimeVerifying": "Verifying {dependency}…", + "desktop.marketplace.runtimeRepairing": "Repairing {dependency}…", + "desktop.marketplace.runtimeReady": "{dependency} is ready", + "desktop.marketplace.permissionRuntimesInstall": "Download and install the plugin’s declared runtime dependencies. Existing verified installations are reused across plugin updates.", + "desktop.marketplace.runtimeFailureHelp": "The runtime environment could not be prepared. Installed plugin versions and verified downloads have been kept. Retry to continue.", + "desktop.lsp.preparationCancelled": "Language service preparation cancelled" + }, + "zh-CN": { + "desktop.marketplace.runtimeChecking": "正在检查 {dependency}…", + "desktop.marketplace.runtimeDownloading": "正在下载 {dependency}… {received} / {total} MiB", + "desktop.marketplace.runtimeReceived": "正在下载 {dependency}… {received} MiB", + "desktop.marketplace.runtimeExtracting": "正在解压 {dependency}…", + "desktop.marketplace.runtimeVerifying": "正在验证 {dependency}…", + "desktop.marketplace.runtimeRepairing": "正在修复 {dependency}…", + "desktop.marketplace.runtimeReady": "{dependency} 已就绪", + "desktop.marketplace.permissionRuntimesInstall": "下载并安装插件声明的运行依赖。插件更新时会复用已有且验证合格的环境。", + "desktop.marketplace.runtimeFailureHelp": "运行环境准备失败。已安装的插件版本和校验合格的下载缓存均已保留,可重试继续。", + "desktop.lsp.preparationCancelled": "语言服务准备已取消" + } + } +} From ceb56533b80fd01e8c5a284e42c6403ef8acf523 Mon Sep 17 00:00:00 2001 From: "lithe-support[bot]" <356900028+lithe-support[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:59:53 +0000 Subject: [PATCH 02/20] feat(i18n): merge strict feature catalogs at build time --- scripts/i18n/generate-i18n.mjs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/scripts/i18n/generate-i18n.mjs b/scripts/i18n/generate-i18n.mjs index 6dba4c8f5..820e88601 100644 --- a/scripts/i18n/generate-i18n.mjs +++ b/scripts/i18n/generate-i18n.mjs @@ -94,6 +94,32 @@ async function json(root, relative) { return parseJSON(await readFile(path.join(root, relative), "utf8"), relative); } +async function loadFeatures(root, localeIDs) { + let entries; + try { + entries = await readdir(path.join(root, "shared/i18n/features"), { withFileTypes: true }); + } catch (error) { + // Older source trees keep every declaration in messages.json. + if (error.code === "ENOENT") return []; + throw error; + } + const features = []; + for (const entry of entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) { + const relative = `shared/i18n/features/${entry.name}`; + if (!entry.isFile() || !entry.name.endsWith(".json")) fail(`${relative}: expected a JSON file`); + const feature = await json(root, relative); + fields(feature, ["schemaVersion", "messages", "locales"], relative); + if (feature.schemaVersion !== 1 || !Array.isArray(feature.messages) || !feature.messages.length) + fail(`${relative}: unsupported feature catalog`); + fields(feature.locales, localeIDs, `${relative} locales`); + const keys = feature.messages.map((message) => message?.id); + for (const [locale, translations] of Object.entries(feature.locales)) + fields(translations, keys, `${relative}/${locale}`); + features.push(feature); + } + return features; +} + function parameters(text, message, label) { if (!(message.allowEmptyTranslation && text === "")) nonempty(text, label); const names = [...text.matchAll(/\{([a-zA-Z][a-zA-Z0-9]*)\}/g)].map((match) => match[1]); @@ -183,6 +209,8 @@ export async function loadContract(root = ROOT) { !registry.messages.length ) fail("unsupported messages registry"); + const features = await loadFeatures(root, [...locales.keys()]); + for (const feature of features) registry.messages.push(...feature.messages); const aliases = new Set(); for (const message of registry.messages) { fields( @@ -311,6 +339,12 @@ export async function loadContract(root = ROOT) { const catalog = await json(root, `shared/i18n/locales/${locale.id}.json`); fields(catalog, ["messages", "overrides"], locale.id); if (!record(catalog.messages)) fail(`${locale.id}: missing messages`); + for (const feature of features) { + for (const [key, text] of Object.entries(feature.locales[locale.id] ?? {})) { + if (own(catalog.messages, key)) fail(`${locale.id}: duplicate translation ${key}`); + catalog.messages[key] = text; + } + } for (const [key, text] of Object.entries(catalog.messages)) { if (!byID.has(key)) fail(`${locale.id}: unknown key ${key}`); parameters(text, byID.get(key), `${locale.id}/${key}`); From 301c9bdd8fd485a1868f097569c862ad2fb938fc Mon Sep 17 00:00:00 2001 From: "lithe-support[bot]" <356900028+lithe-support[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:59:58 +0000 Subject: [PATCH 03/20] fix(i18n): validate lookups against the merged contract --- scripts/i18n/verify-app-language-localization.mjs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/i18n/verify-app-language-localization.mjs b/scripts/i18n/verify-app-language-localization.mjs index 7f2846162..4d0d0adda 100755 --- a/scripts/i18n/verify-app-language-localization.mjs +++ b/scripts/i18n/verify-app-language-localization.mjs @@ -6,6 +6,7 @@ import { existsSync, readdirSync, readFileSync } from "node:fs"; import { basename, join, relative, sep } from "node:path"; import { fileURLToPath } from "node:url"; +import { loadContract } from "./generate-i18n.mjs"; const root = fileURLToPath(new URL("../..", import.meta.url)); const sourceRoot = join(root, "macos/Sources"); @@ -188,10 +189,9 @@ for (const file of swiftFiles(sourceRoot)) { // Desktop uses the same generated registry. Each literal lookup must be declared // for desktop so a missing translation cannot silently reach the UI. const desktopRoot = join(root, "desktop/internal"); -const registryPath = join(root, "shared/i18n/messages.json"); if (existsSync(desktopRoot)) { - const registry = JSON.parse(readFileSync(registryPath, "utf8")); - const desktopMessages = new Map(registry.messages.filter((message) => message.platforms.includes("desktop")).map((message) => [message.id, message])); + const contract = await loadContract(root); + const desktopMessages = new Map(contract.messages.filter((message) => message.platforms.includes("desktop")).map((message) => [message.id, message])); function goFiles(dir) { return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => entry.isDirectory() ? goFiles(join(dir, entry.name)) : entry.name.endsWith(".go") && !entry.name.endsWith("_test.go") && !entry.name.endsWith(".generated.go") ? [join(dir, entry.name)] : []); } From 02aec73c38bad4c0bb357932bf64292414b69c6f Mon Sep 17 00:00:00 2001 From: "lithe-support[bot]" <356900028+lithe-support[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:00:02 +0000 Subject: [PATCH 04/20] test(i18n): cover feature ownership and strict validation --- scripts/i18n/test-i18n.mjs | 136 +++++++++++++++++++++++++++++++++++++ 1 file changed, 136 insertions(+) diff --git a/scripts/i18n/test-i18n.mjs b/scripts/i18n/test-i18n.mjs index e10f7362e..579ce2220 100644 --- a/scripts/i18n/test-i18n.mjs +++ b/scripts/i18n/test-i18n.mjs @@ -62,6 +62,142 @@ async function addLocale(root) { ); } +async function featureFixture(t) { + const root = await mkdtemp(path.join(os.tmpdir(), "lithe-i18n-feature-")); + t.after(() => rm(root, { recursive: true, force: true })); + await mkdir(path.join(root, "shared/i18n/locales"), { recursive: true }); + await mkdir(path.join(root, "desktop/internal/i18n"), { recursive: true }); + await cp(path.join(ROOT, "shared/i18n/manifest.json"), path.join(root, "shared/i18n/manifest.json")); + await writeFile(path.join(root, "shared/i18n/messages.json"), JSON.stringify({ + schemaVersion: 1, + messages: [{ id: "fixture.base", description: "Base catalog fixture.", platforms: ["desktop"] }], + })); + const manifest = JSON.parse(await readFile(path.join(root, "shared/i18n/manifest.json"), "utf8")); + for (const locale of manifest.locales) + await writeFile(path.join(root, `shared/i18n/locales/${locale.id}.json`), JSON.stringify({ + messages: { "fixture.base": "Base" }, + })); + return root; +} + +function featureCatalog(id = "fixture.feature") { + return { + schemaVersion: 1, + messages: [{ id, description: "Feature catalog fixture.", platforms: ["desktop"], parameters: { dependency: "string" } }], + locales: { + "en-US": { [id]: "{dependency} is ready" }, + "zh-CN": { [id]: "{dependency} 已就绪" }, + }, + }; +} + +async function writeFeature(root, name, feature) { + await mkdir(path.join(root, "shared/i18n/features"), { recursive: true }); + await writeFile(path.join(root, `shared/i18n/features/${name}.json`), JSON.stringify(feature)); +} + +test("source trees without a features directory preserve their generated output", { timeout: 15000 }, async (t) => { + const root = await featureFixture(t); + const before = await planGeneration(root); + assert.deepEqual(before.contract.messages.map((message) => message.id), ["fixture.base"]); + await mkdir(path.join(root, "shared/i18n/features")); + assert.deepEqual((await planGeneration(root)).outputs, before.outputs); +}); + +test("feature catalogs generate deterministically without rewriting base sources", { timeout: 15000 }, async (t) => { + const root = await featureFixture(t); + const sources = ["messages.json", "locales/en-US.json", "locales/zh-CN.json"]; + const before = await Promise.all(sources.map((file) => readFile(path.join(root, "shared/i18n", file), "utf8"))); + await writeFeature(root, "zeta", featureCatalog("fixture.zeta")); + await writeFeature(root, "alpha", featureCatalog("fixture.alpha")); + const first = await planGeneration(root); + const desktop = first.outputs.get("desktop/internal/i18n/shared.generated.go"); + assert.match(desktop, /fixture\.alpha/); + assert.match(desktop, /\{dependency\} 已就绪/); + await rename(path.join(root, "shared/i18n/features/alpha.json"), path.join(root, "shared/i18n/features/zz-alpha.json")); + assert.deepEqual((await planGeneration(root)).outputs, first.outputs); + await generate(root); + await generate(root, true); + assert.deepEqual(await Promise.all(sources.map((file) => readFile(path.join(root, "shared/i18n", file), "utf8"))), before); +}); + +test("feature catalogs cannot shadow base or other feature ownership", { timeout: 15000 }, async (t) => { + const cases = [ + ["duplicate base declaration", async (root) => writeFeature(root, "feature", featureCatalog("fixture.base")), /semantic keys must be unique/], + ["duplicate feature declaration", async (root) => { + await writeFeature(root, "one", featureCatalog()); + await writeFeature(root, "two", featureCatalog()); + }, /semantic keys must be unique/], + ["base translation overwrite", async (root) => { + await writeFeature(root, "feature", featureCatalog()); + await edit(root, "shared/i18n/locales/en-US.json", (catalog) => { + catalog.messages["fixture.feature"] = "Existing {dependency}"; + }); + }, /duplicate translation fixture\.feature/], + ["translation owned by another feature", async (root) => { + await writeFeature(root, "one", featureCatalog()); + const feature = featureCatalog("fixture.other"); + feature.locales["en-US"]["fixture.feature"] = "Borrowed {dependency}"; + await writeFeature(root, "two", feature); + }, /unknown field fixture\.feature/], + ]; + for (const [name, arrange, error] of cases) + await t.test(name, { timeout: 1000 }, async (t) => { + const root = await featureFixture(t); + await arrange(root); + await assert.rejects(loadContract(root), error); + }); +}); + +test("feature catalogs retain schema, locale, coverage and parameter validation", { timeout: 15000 }, async (t) => { + const cases = [ + ["unknown top-level field", (feature) => { feature.override = true; }, /unknown field override/], + ["unsupported schema", (feature) => { feature.schemaVersion = 2; }, /unsupported feature catalog/], + ["unknown message field", (feature) => { feature.messages[0].extra = true; }, /unknown field extra/], + ["unknown locale", (feature) => { feature.locales["xx-XX"] = {}; }, /unknown field xx-XX/], + ["translation outside the feature", (feature) => { feature.locales["en-US"]["fixture.base"] = "Base"; }, /unknown field fixture\.base/], + ["missing complete locale", (feature) => { delete feature.locales["zh-CN"]; }, /incomplete translation coverage/], + ["missing complete translation", (feature) => { feature.locales["zh-CN"] = {}; }, /incomplete translation coverage/], + ["non-text translation", (feature) => { feature.locales["en-US"]["fixture.feature"] = 42; }, /must be nonempty text/], + ["missing parameter", (feature) => { feature.locales["en-US"]["fixture.feature"] = "Ready"; }, /placeholder names differ/], + ["unknown parameter", (feature) => { feature.locales["en-US"]["fixture.feature"] = "{other} is ready"; }, /unknown placeholder/], + ["alias outside declared platform", (feature) => { feature.messages[0].macos = { key: "%@ is ready", arguments: ["dependency"] }; }, /macOS alias outside scope/], + ]; + for (const [name, mutate, error] of cases) + await t.test(name, { timeout: 1000 }, async (t) => { + const root = await featureFixture(t); + const feature = featureCatalog(); + mutate(feature); + await writeFeature(root, "feature", feature); + await assert.rejects(loadContract(root), error); + }); +}); + +test("feature JSON rejects duplicate keys including escaped spellings", { timeout: 1000 }, async (t) => { + const root = await featureFixture(t); + await mkdir(path.join(root, "shared/i18n/features")); + await writeFile(path.join(root, "shared/i18n/features/duplicate.json"), + '{"schemaVersion":1,"messages":[],"locales":{"en-US":{"fixture.value":"First","fixture.\\u0076alue":"Second"}}}'); + await assert.rejects(loadContract(root), /duplicate JSON key fixture\.value/); +}); + +test("desktop lookups use feature declarations with unchanged parameter checks", { timeout: 15000 }, async (t) => { + const root = await featureFixture(t); + await writeFeature(root, "feature", featureCatalog()); + await mkdir(path.join(root, "scripts/i18n"), { recursive: true }); + for (const name of ["generate-i18n.mjs", "verify-app-language-localization.mjs"]) + await cp(path.join(ROOT, "scripts/i18n", name), path.join(root, "scripts/i18n", name)); + const sample = path.join(root, "desktop/internal/i18n/sample.go"); + const verify = () => spawnSync(process.execPath, [path.join(root, "scripts/i18n/verify-app-language-localization.mjs")], { encoding: "utf8", timeout: 5000 }); + await writeFile(sample, 'package i18n\nvar s = SharedFormat(language, "fixture.feature", map[string]string{"dependency": value})\n'); + const valid = verify(); + assert.equal(valid.status, 0, `${valid.error ?? ""}\n${valid.stderr}`); + await writeFile(sample, 'package i18n\nvar s = Shared(language, "fixture.feature")\n'); + assert.match(verify().stderr, /desktop key requires SharedFormat/); + await writeFile(sample, 'package i18n\nvar s = SharedFormat(language, "fixture.feature", map[string]string{"wrong": value})\n'); + assert.match(verify().stderr, /desktop SharedFormat parameters differ/); +}); + test( "checked-in generation is current and checking never changes bytes", { timeout: 15000 }, From aa8b6d13ac1177493cf695c9a8e9551e4e751117 Mon Sep 17 00:00:00 2001 From: "lithe-support[bot]" <356900028+lithe-support[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:00:07 +0000 Subject: [PATCH 05/20] docs(i18n): describe feature catalog sources --- shared/i18n/README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/shared/i18n/README.md b/shared/i18n/README.md index 9b5d027df..8992d9ea7 100644 --- a/shared/i18n/README.md +++ b/shared/i18n/README.md @@ -13,6 +13,14 @@ macOS 的字符串表、Windows 的完整翻译字典,以及原先页面内的 显式兼容,原生英文旧 key 通过 `macos.key` 显式兼容。 - `locales/.json` 保存对应语言的 `messages`。平台措辞确实不同时,使用 `overrides.macos` 或 `overrides.windows`,同时填写 `value` 和 `reason`。 +- `features/.json` 可以把同一宿主功能的新增声明和译文放在一个小文件中, + 顶层只有 `schemaVersion: 1`、`messages` 和 `locales`。`messages` 使用同一声明格式; + `locales` 按 manifest 中的语言 ID 保存该文件自有词条的 key → 译文映射, + 例如 `"locales": {"en-US": {"feature.status": "Ready"}, "zh-CN": {"feature.status": "就绪"}}`。 + 不能重复基础词库或其他文件的声明、覆盖已有译文,或为别处声明的词条补译文。 + 生成器按文件名稳定读取,再对合并后的词库执行相同的平台、别名、参数和完整翻译校验; + 调用检查器也读取这份合并契约。这里只拆分源码文件,不增加运行时加载或另一套字典。 + 没有 `features/` 的旧源码目录继续使用原有词库。 - `fixtures/` 保存生成器测试读取的格式样例(`format-v1.json`、`native-abi-v1.json`), 只给 `scripts/i18n/test-i18n.mjs` 使用。Rust Core 不读取它们,所以放在这里,不放进 Core 的 `rust/fixtures/`。 From fac1b537ae78e4edd88d27d6734edfe5f5548855 Mon Sep 17 00:00:00 2001 From: "lithe-support[bot]" <356900028+lithe-support[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:00:21 +0000 Subject: [PATCH 06/20] chore(i18n): generate managed runtime preparation copy --- desktop/internal/i18n/shared.generated.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index b57221d29..8bdfcbb4a 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -995,6 +995,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.lsp.noFilteredLog": "No log line matches the filter.", "desktop.lsp.noLog": "This server has reported nothing yet.", "desktop.lsp.noServers": "No language server is running.", + "desktop.lsp.preparationCancelled": "Language service preparation cancelled", "desktop.lsp.restartServer": "Restart Server", "desktop.lsp.state": "State: {state}", "desktop.lsp.stopServer": "Stop Server", @@ -1038,6 +1039,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.marketplace.permissionCommandsInstall": "Install the command-line tools the plugin needs (asks you before each installation)", "desktop.marketplace.permissionDebug": "Start a debugger for your programs", "desktop.marketplace.permissionGenerate": "Create project files in the location you choose", + "desktop.marketplace.permissionRuntimesInstall": "Download and install the plugin’s declared runtime dependencies. Existing verified installations are reused across plugin updates.", "desktop.marketplace.programDetails": "Program declarations ({count}) — show / hide details", "desktop.marketplace.queryTooLong": "Search query is too long", "desktop.marketplace.reviewConsent": "Install only if you trust this source. Installing approves the permissions and programs declared by this package.", @@ -1045,6 +1047,14 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.marketplace.reviewPermissions": "Permissions", "desktop.marketplace.reviewPrograms": "Programs", "desktop.marketplace.reviewTitle": "Review plugin", + "desktop.marketplace.runtimeChecking": "Checking {dependency}…", + "desktop.marketplace.runtimeDownloading": "Downloading {dependency}… {received} / {total} MiB", + "desktop.marketplace.runtimeExtracting": "Unpacking {dependency}…", + "desktop.marketplace.runtimeFailureHelp": "The runtime environment could not be prepared. Installed plugin versions and verified downloads have been kept. Retry to continue.", + "desktop.marketplace.runtimeReady": "{dependency} is ready", + "desktop.marketplace.runtimeReceived": "Downloading {dependency}… {received} MiB", + "desktop.marketplace.runtimeRepairing": "Repairing {dependency}…", + "desktop.marketplace.runtimeVerifying": "Verifying {dependency}…", "desktop.marketplace.sourceInvalid": "Enter an HTTPS address for the index.", "desktop.marketplace.sourceUnavailable": "Source unavailable: {source}", "desktop.marketplace.tab.settings": "Settings", @@ -3974,6 +3984,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.lsp.noFilteredLog": "没有匹配筛选条件的日志。", "desktop.lsp.noLog": "此服务器暂无日志。", "desktop.lsp.noServers": "没有正在运行的语言服务器。", + "desktop.lsp.preparationCancelled": "语言服务准备已取消", "desktop.lsp.restartServer": "重启服务器", "desktop.lsp.state": "状态:{state}", "desktop.lsp.stopServer": "停止服务器", @@ -4017,6 +4028,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.marketplace.permissionCommandsInstall": "安装插件所需的命令行工具(每次安装前都会征得你的同意)", "desktop.marketplace.permissionDebug": "启动程序调试器", "desktop.marketplace.permissionGenerate": "在你选择的位置生成项目文件", + "desktop.marketplace.permissionRuntimesInstall": "下载并安装插件声明的运行依赖。插件更新时会复用已有且验证合格的环境。", "desktop.marketplace.programDetails": "程序声明({count} 项)· 展开/收起详情", "desktop.marketplace.queryTooLong": "搜索内容过长", "desktop.marketplace.reviewConsent": "请仅安装可信来源的插件。确认安装将批准这个包所声明的权限和程序。", @@ -4024,6 +4036,14 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.marketplace.reviewPermissions": "权限", "desktop.marketplace.reviewPrograms": "程序", "desktop.marketplace.reviewTitle": "审查插件", + "desktop.marketplace.runtimeChecking": "正在检查 {dependency}…", + "desktop.marketplace.runtimeDownloading": "正在下载 {dependency}… {received} / {total} MiB", + "desktop.marketplace.runtimeExtracting": "正在解压 {dependency}…", + "desktop.marketplace.runtimeFailureHelp": "运行环境准备失败。已安装的插件版本和校验合格的下载缓存均已保留,可重试继续。", + "desktop.marketplace.runtimeReady": "{dependency} 已就绪", + "desktop.marketplace.runtimeReceived": "正在下载 {dependency}… {received} MiB", + "desktop.marketplace.runtimeRepairing": "正在修复 {dependency}…", + "desktop.marketplace.runtimeVerifying": "正在验证 {dependency}…", "desktop.marketplace.sourceInvalid": "请输入 HTTPS 格式的索引地址。", "desktop.marketplace.sourceUnavailable": "来源不可用:{source}", "desktop.marketplace.tab.settings": "设置", From 46ca8463d646a2f18e7c6f0d3e7b5dae91ac607c Mon Sep 17 00:00:00 2001 From: "lithe-support[bot]" <356900028+lithe-support[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:05:24 +0000 Subject: [PATCH 07/20] feat(plugins): add reviewed managed runtime support (1/7) --- ...09-30-lsp-plugin-build-and-distribution.md | 7 +- desktop/internal/core/managed_runtimes.go | 101 ++++++++++++++++++ .../internal/core/managed_runtimes_test.go | 54 ++++++++++ desktop/internal/core/plugin_session.go | 3 + .../internal/pluginbackend/pluginbackend.go | 43 ++++++-- 5 files changed, 198 insertions(+), 10 deletions(-) create mode 100644 desktop/internal/core/managed_runtimes.go create mode 100644 desktop/internal/core/managed_runtimes_test.go diff --git a/.agents/notes/implemented/architecture/2026-09-30-lsp-plugin-build-and-distribution.md b/.agents/notes/implemented/architecture/2026-09-30-lsp-plugin-build-and-distribution.md index 01ffca872..2e9ab6606 100644 --- a/.agents/notes/implemented/architecture/2026-09-30-lsp-plugin-build-and-distribution.md +++ b/.agents/notes/implemented/architecture/2026-09-30-lsp-plugin-build-and-distribution.md @@ -4,7 +4,12 @@ ## 先说结论 -带语言服务器(Language Server,通过 LSP 提供补全、诊断和跳转能力的进程)的插件,必须在构建阶段固定语言服务器的来源和校验值,下载并校验后放入插件包,插件包完成签名后再分发。运行时只从已安装插件中发现入口,不能把下载物、解压物或插件状态写入应用安装目录,也不能写入跨工作树共享的缓存。插件卸载、重装和回滚时,必须能连同自己的语言服务器一起清理或替换。 +带语言服务器(Language Server,通过 LSP 提供补全、诊断和跳转能力的进程)的插件,默认在构建阶段固定语言服务器的来源和校验值,下载并校验后放入插件包,插件包完成签名后再分发。运行时不能把下载物、解压物或插件状态写入应用安装目录,也不能写入跨工作树共享的缓存。插件卸载、重装和回滚时,必须能按声明管理自己的语言服务器。 + +下文的包内入口和随版本替换规则适用于默认的 bundled 模式。显式声明 `requires.managedRuntimes: 0` +及对应安装权限的插件可以采用[受管插件运行时](2026-11-18-managed-plugin-runtimes.md):来源与校验值仍在插件清单中固定, +经审批后先检查已有安装,只为缺失项下载,并保存到该插件独立、跨版本的状态目录。 +这个受控模式没有恢复宿主自行识别语言、选择版本或维护跨插件共享工具目录的旧路径。 语言服务器的声明位于插件的 `plugin.json` 的 `languageServers` 中;Lithe 负责插件包验证、启停、运行时发现、进程生命周期和现有 LSP 会话编排。插件包是声明式的,不含宿主加载的代码,见 [声明式语言插件](2026-10-12-declarative-language-plugins.md)。 diff --git a/desktop/internal/core/managed_runtimes.go b/desktop/internal/core/managed_runtimes.go new file mode 100644 index 000000000..027684fbc --- /dev/null +++ b/desktop/internal/core/managed_runtimes.go @@ -0,0 +1,101 @@ +package core + +import ( + "context" + "encoding/json" +) + +// ManagedRuntimePlatform uses plugin contract platform tokens, independent of Go names. +type ManagedRuntimePlatform struct { + OS string `json:"os"` + Arch string `json:"arch"` +} + +// ManagedRuntimeResolver is the packaged backend function that verifies a dependency set. +type ManagedRuntimeResolver struct { + Function string `json:"function"` + TimeoutMilliseconds int `json:"timeoutMilliseconds"` +} + +// ManagedRuntimeDependency is Core's platform-selected, content-addressed download plan. +// Home is relative to the extracted root after StripPrefix; Executable is relative to Home. +type ManagedRuntimeDependency struct { + ID string `json:"id"` + Version string `json:"version"` + Tool string `json:"tool,omitempty"` + OS string `json:"os"` + Arch string `json:"arch"` + URL string `json:"url"` + SHA256 string `json:"sha256"` + Archive string `json:"archive"` + StripPrefix string `json:"stripPrefix"` + Home string `json:"home"` + Executable string `json:"executable"` + CacheKey string `json:"cacheKey"` +} + +// ManagedRuntimePlan describes downloads and the plugin-owned compatibility check. +type ManagedRuntimePlan struct { + Resolve *ManagedRuntimeResolver `json:"resolve,omitempty"` + Dependencies []ManagedRuntimeDependency `json:"dependencies"` +} + +// ManagedRuntimeInstallation is a validated read-only home, managed or external. +type ManagedRuntimeInstallation struct { + ID string `json:"id"` + Home string `json:"home"` + Version string `json:"version"` +} + +// ManagedRuntimeResolution partitions every declared dependency into usable or missing. +type ManagedRuntimeResolution struct { + Runtimes []ManagedRuntimeInstallation `json:"runtimes"` + Missing []string `json:"missing"` +} + +// PlanManagedRuntimes validates the manifest and chooses immutable artifacts for a platform. +func (c *Client) PlanManagedRuntimes(ctx context.Context, manifest json.RawMessage, platform ManagedRuntimePlatform) (ManagedRuntimePlan, error) { + const command = "plugins.managedRuntimes.plan" + var result struct { + Status string `json:"status"` + Error *MarketplaceRejection `json:"error"` + Plan *ManagedRuntimePlan `json:"plan"` + } + if err := c.Execute(ctx, command, struct { + Manifest json.RawMessage `json:"manifest"` + Platform ManagedRuntimePlatform `json:"platform"` + }{manifest, platform}, &result); err != nil { + return ManagedRuntimePlan{}, err + } + if result.Status == "rejected" && result.Error != nil { + return ManagedRuntimePlan{}, result.Error + } + if result.Status != "ok" || result.Plan == nil { + return ManagedRuntimePlan{}, newParseError(command, "runtime plan returned an invalid outcome", "") + } + return *result.Plan, nil +} + +// DecodeManagedRuntimeResolution checks the plugin's answer before native paths are consumed. +func (c *Client) DecodeManagedRuntimeResolution(ctx context.Context, manifest json.RawMessage, platform ManagedRuntimePlatform, answer json.RawMessage) (ManagedRuntimeResolution, error) { + const command = "plugins.managedRuntimes.decodeResolution" + var result struct { + Status string `json:"status"` + Error *MarketplaceRejection `json:"error"` + Resolution *ManagedRuntimeResolution `json:"resolution"` + } + if err := c.Execute(ctx, command, struct { + Manifest json.RawMessage `json:"manifest"` + Platform ManagedRuntimePlatform `json:"platform"` + Result json.RawMessage `json:"result"` + }{manifest, platform, answer}, &result); err != nil { + return ManagedRuntimeResolution{}, err + } + if result.Status == "rejected" && result.Error != nil { + return ManagedRuntimeResolution{}, result.Error + } + if result.Status != "ok" || result.Resolution == nil { + return ManagedRuntimeResolution{}, newParseError(command, "runtime resolution returned an invalid outcome", "") + } + return *result.Resolution, nil +} diff --git a/desktop/internal/core/managed_runtimes_test.go b/desktop/internal/core/managed_runtimes_test.go new file mode 100644 index 000000000..1b2e3f8e2 --- /dev/null +++ b/desktop/internal/core/managed_runtimes_test.go @@ -0,0 +1,54 @@ +package core + +import ( + "context" + "encoding/json" + "os" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" +) + +func TestManagedRuntimesBridgeUsesSharedContract(t *testing.T) { + data, err := os.ReadFile(contractfixture.CoreFixture("plugins/managed-runtimes.json")) + if err != nil { + t.Fatal(err) + } + var fixture struct { + Manifest json.RawMessage `json:"manifest"` + Resolution json.RawMessage `json:"resolution"` + WindowsResolution json.RawMessage `json:"windowsResolution"` + } + if err := json.Unmarshal(data, &fixture); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + client := NewClient() + for _, os := range []string{"linux", "windows"} { + t.Run(os, func(t *testing.T) { + platform := ManagedRuntimePlatform{OS: os, Arch: "x86_64"} + plan, err := client.PlanManagedRuntimes(ctx, fixture.Manifest, platform) + if err != nil || plan.Resolve == nil || len(plan.Dependencies) != 2 { + t.Fatalf("plan=%+v error=%v", plan, err) + } + for _, dependency := range plan.Dependencies { + if dependency.OS != os || len(dependency.CacheKey) != 64 || dependency.SHA256 == "" { + t.Fatalf("incomplete native download plan: %+v", dependency) + } + } + answer := fixture.Resolution + if os == "windows" { + answer = fixture.WindowsResolution + } + resolution, err := client.DecodeManagedRuntimeResolution(ctx, fixture.Manifest, platform, answer) + if err != nil || len(resolution.Runtimes) != 1 || len(resolution.Missing) != 1 || resolution.Missing[0] != "server" { + t.Fatalf("resolution=%+v error=%v", resolution, err) + } + if _, err := client.DecodeManagedRuntimeResolution(ctx, fixture.Manifest, platform, json.RawMessage(`{"runtimes":[],"missing":[]}`)); err == nil { + t.Fatal("an incomplete answer crossed the native boundary") + } + }) + } +} diff --git a/desktop/internal/core/plugin_session.go b/desktop/internal/core/plugin_session.go index cb2d7065a..f9b976e3b 100644 --- a/desktop/internal/core/plugin_session.go +++ b/desktop/internal/core/plugin_session.go @@ -18,6 +18,9 @@ type PluginBackendStart struct { RootURI any `json:"rootUri"` WorkingDirectory string `json:"workingDirectory"` HostServices []string `json:"hostServices,omitempty"` + // FunctionRelayEnabled isolates preparation sessions from both incoming and + // outgoing cross-plugin calls. Omitted preserves ordinary backend behavior. + FunctionRelayEnabled *bool `json:"functionRelayEnabled,omitempty"` // HostOptions are the options of the granted services, which Core reports to the // backend through lithe/host/getCapabilities. HostOptions *PluginHostOptions `json:"hostOptions,omitempty"` diff --git a/desktop/internal/pluginbackend/pluginbackend.go b/desktop/internal/pluginbackend/pluginbackend.go index 38f00b9c2..c12d02430 100644 --- a/desktop/internal/pluginbackend/pluginbackend.go +++ b/desktop/internal/pluginbackend/pluginbackend.go @@ -137,6 +137,12 @@ type StartRequest struct { // Environment is added to the provider process environment. It is for host // integration tests and host-owned facts, never plugin-controlled secrets. Environment map[string]string + // ManagedTools are per-launch installations verified by the managed runtime resolver. + // They are never stored as global defaults or used by a different plugin/session. + ManagedTools map[string]ToolExecutable + // Preparation starts a private resolver without workspace services or the + // cross-plugin function relay. Only direct host invocations may reach it. + Preparation bool // RootURI and WorkingDirectory are the workspace the backend serves. RootURI any WorkingDirectory string @@ -341,6 +347,9 @@ func (r *Runner) Start(ctx context.Context, request StartRequest) (Session, erro return Session{}, err } granted := pluginhost.GrantServices(plan.Backend.HostServices, r.services) + if request.Preparation { + granted = nil + } // A packaged launch runs the program the package ships; a runtime launch runs the // packaged runtime, which VerifyLaunch put in Runtime; a system-command launch // names a bare command the host resolves itself. @@ -382,12 +391,16 @@ func (r *Runner) Start(ctx context.Context, request StartRequest) (Session, erro } // A bare tool launch uses the selected installation and the opaque args. if executable == "" && plan.Launch.Kind == pluginhost.LaunchTool { - if r.tools == nil { - return Session{}, fmt.Errorf("%w: this host cannot resolve tool launches", ErrRequest) - } - tool, err := r.tools(ctx, request.PluginID, request.WorkingDirectory, plan.Launch.Tool) - if err != nil { - return Session{}, err + tool, managed := request.ManagedTools[plan.Launch.Tool] + if !managed { + if r.tools == nil { + return Session{}, fmt.Errorf("%w: this host cannot resolve tool launches", ErrRequest) + } + var err error + tool, err = r.tools(ctx, request.PluginID, request.WorkingDirectory, plan.Launch.Tool) + if err != nil { + return Session{}, err + } } executable, toolEnvironment = tool.Path, tool.Environment } @@ -418,6 +431,10 @@ func (r *Runner) Start(ctx context.Context, request StartRequest) (Session, erro if start.InitializeTimeoutMilliseconds == 0 && r.initializeTimeout > 0 { start.InitializeTimeoutMilliseconds = int(r.initializeTimeout / time.Millisecond) } + if request.Preparation { + enabled := false + start.FunctionRelayEnabled = &enabled + } var started core.PluginBackendStarted if request.LanguageID != "" { // From here Core owns the attempt: it records the launch, the early exit, the @@ -465,11 +482,19 @@ func mergeEnvironment(plan, host map[string]string) map[string]string { // shutdown request fails, because Core keeps owning the session until it is // disposed. func (r *Runner) Stop(ctx context.Context, session Session) error { + _, err := r.StopAndDispose(ctx, session) + return err +} + +// StopAndDispose also reports whether Core released the session. A graceful +// shutdown can fail while disposal succeeds; file owners must not retry an +// already-destroyed session or mistake that diagnostic for a live process. +func (r *Runner) StopAndDispose(ctx context.Context, session Session) (bool, error) { if r == nil || r.kernel == nil { - return errors.New("pluginbackend: no kernel") + return false, errors.New("pluginbackend: no kernel") } if session.ID == "" { - return ErrNoSession + return false, ErrNoSession } r.untrackTrace(session.ID) stopErr := r.kernel.StopPluginBackend(ctx, session.ID) @@ -492,7 +517,7 @@ func (r *Runner) Stop(ctx context.Context, session Session) error { r.forwardLog(event) } } - return errors.Join(stopErr, destroyErr) + return destroyErr == nil, errors.Join(stopErr, destroyErr) } // EventDiagnostics is the runtime event carrying a language server's diagnostics From 4a8dad92853ce860d78e43b4073d7ea1b8618408 Mon Sep 17 00:00:00 2001 From: "lithe-support[bot]" <356900028+lithe-support[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:05:32 +0000 Subject: [PATCH 08/20] feat(plugins): add reviewed managed runtime support (2/7) --- .../pluginbackend/pluginbackend_test.go | 53 ++ desktop/internal/pluginhost/pluginhost.go | 1 + desktop/internal/pluginruntime/extract.go | 471 ++++++++++++++++++ desktop/internal/pluginruntime/lock.go | 75 +++ desktop/internal/pluginruntime/lock_unix.go | 18 + 5 files changed, 618 insertions(+) create mode 100644 desktop/internal/pluginruntime/extract.go create mode 100644 desktop/internal/pluginruntime/lock.go create mode 100644 desktop/internal/pluginruntime/lock_unix.go diff --git a/desktop/internal/pluginbackend/pluginbackend_test.go b/desktop/internal/pluginbackend/pluginbackend_test.go index f00fc2d21..a403338ef 100644 --- a/desktop/internal/pluginbackend/pluginbackend_test.go +++ b/desktop/internal/pluginbackend/pluginbackend_test.go @@ -256,6 +256,32 @@ func TestStartRefusesAnUnverifiedProgram(t *testing.T) { } } +func TestPreparationSessionHasNoWorkspaceOrRelayAccess(t *testing.T) { + plan := packagedPlan() + plan.Backend.HostServices = []string{pluginhost.MethodPrefix + "workspace/stat"} + kernel := &fakeKernel{plan: plan, started: core.PluginBackendStarted{SessionID: "preflight"}} + runner := New(kernel, echoServices(t)) + request := startRequest(backendPackage(t)) + request.Preparation = true + session, err := runner.Start(context.Background(), request) + if err != nil { + t.Fatal(err) + } + if len(session.Granted) != 0 || len(kernel.started_.HostServices) != 0 || kernel.started_.HostOptions != nil { + t.Fatalf("preparation inherited workspace grants: %+v", kernel.started_) + } + if kernel.started_.FunctionRelayEnabled == nil || *kernel.started_.FunctionRelayEnabled { + t.Fatal("preparation was not isolated from the cross-plugin relay") + } + request.Preparation = false + if _, err := runner.Start(context.Background(), request); err != nil { + t.Fatal(err) + } + if kernel.started_.FunctionRelayEnabled != nil || len(kernel.started_.HostServices) != 1 { + t.Fatal("private preparation changed the next ordinary session's grants") + } +} + func TestStartRefusesAnUnusableRequest(t *testing.T) { root := backendPackage(t) kernel := &fakeKernel{plan: packagedPlan()} @@ -692,6 +718,33 @@ func TestStartResolvesAToolThroughTheHostToolchain(t *testing.T) { } } +func TestManagedToolSelectionBelongsOnlyToOneLaunch(t *testing.T) { + root := backendPackage(t) + var plan core.PluginBackendPlan + plan.Launch.Kind, plan.Launch.Tool = pluginhost.LaunchTool, "fixture-runtime" + kernel := &fakeKernel{plan: plan, started: core.PluginBackendStarted{SessionID: "managed-session"}} + runner := New(kernel, echoServices(t)) + projectCalls := 0 + runner.SetToolResolver(func(context.Context, string, string, string) (ToolExecutable, error) { + projectCalls++ + return ToolExecutable{Path: "/project/compiler"}, nil + }) + request := startRequest(root) + request.ManagedTools = map[string]ToolExecutable{"fixture-runtime": {Path: "/managed/runtime"}} + if _, err := runner.Start(context.Background(), request); err != nil { + t.Fatal(err) + } + if kernel.started_.ExecutablePath != "/managed/runtime" || projectCalls != 0 || len(kernel.started_.Environment) != 0 { + t.Fatalf("managed selection was not isolated: %+v, calls=%d", kernel.started_, projectCalls) + } + if _, err := runner.Start(context.Background(), startRequest(root)); err != nil { + t.Fatal(err) + } + if kernel.started_.ExecutablePath != "/project/compiler" || projectCalls != 1 { + t.Fatalf("managed selection leaked into a subsequent launch: %+v", kernel.started_) + } +} + func TestToolEntryUsesCoreInstantiationAfterNativeVerification(t *testing.T) { root := backendPackage(t) entry := filepath.Join(root, "入口 with 空格.script") diff --git a/desktop/internal/pluginhost/pluginhost.go b/desktop/internal/pluginhost/pluginhost.go index 434630950..f0190dcc3 100644 --- a/desktop/internal/pluginhost/pluginhost.go +++ b/desktop/internal/pluginhost/pluginhost.go @@ -157,6 +157,7 @@ func Declared() Capabilities { "debugAdapters", "languageServers", "languages", + "managedRuntimes", "outputLinkMatchers", "pluginFunctions", "projectGenerators", diff --git a/desktop/internal/pluginruntime/extract.go b/desktop/internal/pluginruntime/extract.go new file mode 100644 index 000000000..17388dfd9 --- /dev/null +++ b/desktop/internal/pluginruntime/extract.go @@ -0,0 +1,471 @@ +package pluginruntime + +import ( + "archive/tar" + "archive/zip" + "compress/gzip" + "context" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path" + "path/filepath" + "strings" + + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" +) + +const ( + // Native extraction budgets complement the downloader's compressed-byte + // bound. Neither ZIP metadata nor a small gzip stream can allocate freely. + maxEntries = 50000 + maxExpandedBytes = int64(4 << 30) +) + +type archiveLink struct { + name, target string + hard bool +} + +type extraction struct { + ctx context.Context + root *os.Root + prefix string + paths map[string]string + links []archiveLink + total int64 + entries int +} + +func extract(ctx context.Context, file *os.File, directory string, artifact Artifact) (_ []inventoryEntry, err error) { + root, err := os.OpenRoot(directory) + if err != nil { + return nil, err + } + defer func() { err = errors.Join(err, root.Close()) }() + x := extraction{ctx: ctx, root: root, prefix: artifact.StripPrefix, paths: make(map[string]string)} + switch artifact.Archive { + case "zip": + info, err := file.Stat() + if err != nil { + return nil, err + } + if err := checkZIPDirectory(ctx, file, info.Size()); err != nil { + return nil, err + } + reader, err := zip.NewReader(contextReaderAt{ctx, file}, info.Size()) + if err != nil { + return nil, fmt.Errorf("%w: %w", ErrArchive, err) + } + if len(reader.File) > maxEntries { + return nil, ErrArchive + } + for _, entry := range reader.File { + if err := ctx.Err(); err != nil { + return nil, err + } + if entry.UncompressedSize64 > uint64(maxExpandedBytes) { + return nil, ErrArchive + } + content, err := entry.Open() + if err != nil { + return nil, err + } + mode := entry.Mode() + err = x.entry(entry.Name, mode, int64(entry.UncompressedSize64), content, "", false) + err = errors.Join(err, content.Close()) + if err != nil { + return nil, err + } + } + case "tar.gz": + reader, err := gzip.NewReader(contextReader{ctx, file}) + if err != nil { + return nil, fmt.Errorf("%w: %w", ErrArchive, err) + } + defer func() { err = errors.Join(err, reader.Close()) }() + archive := tar.NewReader(reader) + for { + if err := ctx.Err(); err != nil { + return nil, err + } + header, err := archive.Next() + if errors.Is(err, io.EOF) { + // Finish gzip validation, including its checksum and trailer. Bound + // ignored tar padding so trailing compression cannot evade limits. + remaining := maxExpandedBytes - x.total + n, tailErr := io.Copy(io.Discard, io.LimitReader(contextReader{ctx, reader}, remaining+1)) + if tailErr != nil || n > remaining { + return nil, errors.Join(ErrArchive, tailErr) + } + break + } + if err != nil { + return nil, fmt.Errorf("%w: %w", ErrArchive, err) + } + mode := header.FileInfo().Mode() + if header.Typeflag != tar.TypeReg && header.Typeflag != tar.TypeRegA && header.Typeflag != tar.TypeDir && header.Typeflag != tar.TypeSymlink && header.Typeflag != tar.TypeLink { + return nil, fmt.Errorf("%w: unsupported entry type", ErrArchive) + } + if err := x.entry(header.Name, mode, header.Size, archive, header.Linkname, header.Typeflag == tar.TypeLink); err != nil { + return nil, err + } + } + default: + return nil, ErrArtifact + } + // Link creation is deferred until every ordinary file exists. No archive + // entry can write through a link laid down by an earlier entry. + for _, link := range x.links { + if err := ctx.Err(); err != nil { + return nil, err + } + if link.hard { + info, err := root.Lstat(link.target) + if err != nil || !info.Mode().IsRegular() { + return nil, fmt.Errorf("%w: hard link target", ErrArchive) + } + if err := root.Link(link.target, link.name); err != nil { + return nil, err + } + } else if err := root.Symlink(link.target, link.name); err != nil { + return nil, err + } + } + return captureInventory(ctx, root) +} + +func (x *extraction) entry(raw string, mode fs.FileMode, size int64, source io.Reader, target string, hard bool) error { + x.entries++ + if x.entries > maxEntries || size < 0 || size > maxExpandedBytes-x.total { + return ErrArchive + } + x.total += size + name, err := x.name(raw, mode.IsDir()) + if err != nil || name == "" { + return err + } + kind := "file" + if mode.IsDir() { + kind = "directory" + } else if mode&fs.ModeSymlink != 0 || hard { + kind = "link" + } else if !mode.IsRegular() { + return fmt.Errorf("%w: special file", ErrArchive) + } + if err := x.reserve(name, kind); err != nil { + return err + } + if err := x.root.MkdirAll(filepath.FromSlash(path.Dir(name)), 0o700); err != nil { + return err + } + if kind == "directory" { + return x.root.MkdirAll(filepath.FromSlash(name), mode.Perm()|0o700) + } + if kind == "link" { + if target == "" { + bytes, err := io.ReadAll(io.LimitReader(contextReader{x.ctx, source}, int64(pluginpkg.MaxPathLength)+1)) + if err != nil || len(bytes) > pluginpkg.MaxPathLength { + return errors.Join(ErrArchive, err) + } + target = string(bytes) + } + if hard { + target, err = x.name(target, false) + } else { + // Relative parent segments are necessary for real runtime archives. + // Resolve lexically first, then os.Root checks the complete link chain + // during inventory capture, rejecting escapes and dangling cycles. + if path.IsAbs(target) || strings.ContainsAny(target, "\\\x00:") { + return ErrArchive + } + _, err = pluginpkg.ValidatePath(path.Clean(path.Join(path.Dir(name), target))) + } + if err != nil || target == "" { + return errors.Join(ErrArchive, err) + } + x.links = append(x.links, archiveLink{filepath.FromSlash(name), filepath.FromSlash(target), hard}) + return nil + } + file, err := x.root.OpenFile(filepath.FromSlash(name), os.O_CREATE|os.O_EXCL|os.O_WRONLY, mode.Perm()|0o600) + if err != nil { + return err + } + written, writeErr := io.Copy(file, io.LimitReader(contextReader{x.ctx, source}, size+1)) + closeErr := file.Close() + if written != size { + return errors.Join(ErrArchive, writeErr, closeErr) + } + return errors.Join(writeErr, closeErr) +} + +func (x *extraction) name(raw string, directory bool) (string, error) { + // GNU tar commonly prefixes the archive root with "./". Only that prefix + // is normalized; internal dot or parent segments are refused by ValidatePath. + for strings.HasPrefix(raw, "./") { + raw = strings.TrimPrefix(raw, "./") + } + if directory { + raw = strings.TrimSuffix(raw, "/") + if raw == "" || raw == "." { + return "", nil + } + } + if _, err := pluginpkg.ValidatePath(raw); err != nil { + return "", fmt.Errorf("%w: %w", ErrArchive, err) + } + if x.prefix != "" { + if raw == x.prefix && directory { + return "", nil + } + if !strings.HasPrefix(raw, x.prefix+"/") { + return "", fmt.Errorf("%w: entry outside strip prefix", ErrArchive) + } + raw = strings.TrimPrefix(raw, x.prefix+"/") + } + return raw, nil +} + +func (x *extraction) reserve(name, kind string) error { + key := strings.ToLower(name) + if previous := x.paths[key]; previous != "" && (kind != "directory" || previous != "directory") { + return fmt.Errorf("%w: duplicate or conflicting entry", ErrArchive) + } + x.paths[key] = kind + for parent := path.Dir(key); parent != "."; parent = path.Dir(parent) { + if previous := x.paths[parent]; previous != "" && previous != "directory" { + return fmt.Errorf("%w: entry nested under a file or link", ErrArchive) + } + x.paths[parent] = "directory" + } + if len(x.paths) > maxEntries { + return ErrArchive + } + return nil +} + +func captureInventory(ctx context.Context, root *os.Root) ([]inventoryEntry, error) { + var entries []inventoryEntry + err := fs.WalkDir(root.FS(), ".", func(name string, item fs.DirEntry, walkErr error) error { + if walkErr != nil { + return walkErr + } + if err := ctx.Err(); err != nil { + return err + } + if name == "." { + return nil + } + if len(entries) >= maxEntries { + return ErrArchive + } + entry, err := inspectEntry(ctx, root, name, true) + if err == nil { + entries = append(entries, entry) + } + return err + }) + return entries, err +} + +func inspectEntry(ctx context.Context, root *os.Root, name string, contents bool) (entry inventoryEntry, err error) { + entry.Path = name + info, err := root.Lstat(filepath.FromSlash(name)) + if err != nil { + return entry, err + } + entry.Mode = uint32(info.Mode().Perm()) + switch { + case info.IsDir(): + entry.Kind = "directory" + case info.Mode()&os.ModeSymlink != 0: + entry.Kind = "link" + entry.Link, err = root.Readlink(filepath.FromSlash(name)) + if err == nil { + _, err = root.Stat(filepath.FromSlash(name)) + } + case info.Mode().IsRegular(): + entry.Kind, entry.Size, entry.Modified = "file", info.Size(), info.ModTime().UnixNano() + if contents { + file, openErr := root.Open(filepath.FromSlash(name)) + if openErr != nil { + return entry, openErr + } + hash := sha256.New() + _, readErr := io.Copy(hash, contextReader{ctx, io.LimitReader(file, maxExpandedBytes+1)}) + err = errors.Join(readErr, file.Close()) + entry.SHA256 = hex.EncodeToString(hash.Sum(nil)) + } + default: + err = ErrArchive + } + return entry, err +} + +func verifyInventory(ctx context.Context, directory string, entries []inventoryEntry, contents bool) (err error) { + info, err := os.Lstat(directory) + if err != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return fmt.Errorf("%w: generation directory", ErrCorrupt) + } + root, err := os.OpenRoot(directory) + if err != nil { + return err + } + defer func() { err = errors.Join(err, root.Close()) }() + expected := make(map[string]inventoryEntry, len(entries)) + for _, entry := range entries { + if _, err := pluginpkg.ValidatePath(entry.Path); err != nil { + return ErrCorrupt + } + if _, exists := expected[entry.Path]; exists { + return ErrCorrupt + } + expected[entry.Path] = entry + } + seen := 0 + err = fs.WalkDir(root.FS(), ".", func(name string, item fs.DirEntry, walkErr error) error { + if walkErr != nil { + return walkErr + } + if err := ctx.Err(); err != nil { + return err + } + if name == "." { + return nil + } + want, ok := expected[name] + if !ok { + return ErrCorrupt + } + got, err := inspectEntry(ctx, root, name, false) + if err != nil { + return err + } + if got.Kind != want.Kind || got.Size != want.Size || got.Mode != want.Mode || got.Link != want.Link { + return ErrCorrupt + } + if got.Kind == "file" && (contents || got.Modified != want.Modified) { + got, err = inspectEntry(ctx, root, name, true) + if err != nil { + return err + } + if got.SHA256 != want.SHA256 { + return ErrCorrupt + } + } + seen++ + return nil + }) + if err != nil { + if ctx.Err() != nil { + return ctx.Err() + } + return fmt.Errorf("%w: %w", ErrCorrupt, err) + } + if seen != len(expected) { + return ErrCorrupt + } + return nil +} + +// checkZIPDirectory checks the entry count before archive/zip allocates its +// central directory objects. ZIP64 is supported, but cannot raise the I/O bound. +func checkZIPDirectory(ctx context.Context, source io.ReaderAt, size int64) error { + if size < 22 { + return ErrArchive + } + length := min(size, 22+65535) + buffer := make([]byte, int(length)) + reader := contextReaderAt{ctx, source} + if _, err := reader.ReadAt(buffer, size-length); err != nil { + return err + } + for i := len(buffer) - 22; i >= 0; i-- { + if binary.LittleEndian.Uint32(buffer[i:]) != 0x06054b50 || i+22+int(binary.LittleEndian.Uint16(buffer[i+20:])) != len(buffer) { + continue + } + if binary.LittleEndian.Uint16(buffer[i+4:]) != 0 || binary.LittleEndian.Uint16(buffer[i+6:]) != 0 { + return ErrArchive + } + count := uint64(binary.LittleEndian.Uint16(buffer[i+10:])) + centralSize := uint64(binary.LittleEndian.Uint32(buffer[i+12:])) + centralOffset := uint64(binary.LittleEndian.Uint32(buffer[i+16:])) + if count == 0xffff || centralSize == 0xffffffff || centralOffset == 0xffffffff { + position := size - length + int64(i) + if position < 20 { + return ErrArchive + } + var locator [20]byte + if _, err := reader.ReadAt(locator[:], position-20); err != nil { + return err + } + if binary.LittleEndian.Uint32(locator[:]) != 0x07064b50 || binary.LittleEndian.Uint32(locator[4:]) != 0 || binary.LittleEndian.Uint32(locator[16:]) != 1 { + return ErrArchive + } + offset := binary.LittleEndian.Uint64(locator[8:]) + if offset > uint64(size-56) { + return ErrArchive + } + var end [56]byte + if _, err := reader.ReadAt(end[:], int64(offset)); err != nil { + return err + } + if binary.LittleEndian.Uint32(end[:]) != 0x06064b50 { + return ErrArchive + } + count = binary.LittleEndian.Uint64(end[32:]) + centralSize = binary.LittleEndian.Uint64(end[40:]) + centralOffset = binary.LittleEndian.Uint64(end[48:]) + } + if count == 0 || count > maxEntries || centralSize > inventoryLimit || centralOffset > uint64(size) || centralSize > uint64(size)-centralOffset { + return ErrArchive + } + // Do not trust the count alone: a forged small count can accompany a + // large actual directory. Walk fixed headers before zip.NewReader is + // allowed to allocate one object per entry. + var consumed, actual uint64 + for consumed < centralSize { + var header [46]byte + if centralSize-consumed < uint64(len(header)) { + return ErrArchive + } + if _, err := reader.ReadAt(header[:], int64(centralOffset+consumed)); err != nil { + return err + } + if binary.LittleEndian.Uint32(header[:]) != 0x02014b50 { + return ErrArchive + } + length := uint64(len(header)) + uint64(binary.LittleEndian.Uint16(header[28:])) + uint64(binary.LittleEndian.Uint16(header[30:])) + uint64(binary.LittleEndian.Uint16(header[32:])) + if length > centralSize-consumed { + return ErrArchive + } + consumed += length + actual++ + if actual > maxEntries { + return ErrArchive + } + } + if actual != count { + return ErrArchive + } + return nil + } + return ErrArchive +} + +type contextReaderAt struct { + ctx context.Context + source io.ReaderAt +} + +func (r contextReaderAt) ReadAt(p []byte, offset int64) (int, error) { + if err := r.ctx.Err(); err != nil { + return 0, err + } + return r.source.ReadAt(p, offset) +} diff --git a/desktop/internal/pluginruntime/lock.go b/desktop/internal/pluginruntime/lock.go new file mode 100644 index 000000000..ac28bc2f5 --- /dev/null +++ b/desktop/internal/pluginruntime/lock.go @@ -0,0 +1,75 @@ +package pluginruntime + +import ( + "context" + "errors" + "os" + "path/filepath" + "time" +) + +// acquire uses an OS lock, not a pid or timestamp lease: process death releases +// ownership automatically. The file stays in place so another opener cannot +// lock a different inode while a previous waiter still holds the old one. +func acquire(ctx context.Context, name string) (unlock func() error, err error) { + defer func() { + if err != nil && unlock != nil { + err = errors.Join(err, unlock()) + unlock = nil + } + }() + if err := ctx.Err(); err != nil { + return nil, err + } + root, err := os.OpenRoot(filepath.Dir(name)) + if err != nil { + return nil, err + } + defer func() { err = errors.Join(err, root.Close()) }() + base := filepath.Base(name) + file, err := root.OpenFile(base, os.O_CREATE|os.O_RDWR, 0o600) + if err != nil { + return nil, err + } + owned := false + defer func() { + if !owned { + err = errors.Join(err, file.Close()) + } + }() + info, err := root.Lstat(base) + if err != nil { + return nil, err + } + opened, err := file.Stat() + if err != nil { + return nil, err + } + if !info.Mode().IsRegular() || !os.SameFile(info, opened) { + return nil, ErrArtifact + } + bounded, cancel := context.WithTimeout(ctx, 5*time.Minute) + defer cancel() + for { + locked, err := tryLock(file) + if err != nil { + return nil, err + } + if locked { + owned = true + return file.Close, nil + } + // Native advisory locks have no cross-platform cancellable wait. The + // bounded timer performs no filesystem scanning and owns no goroutine. + timer := time.NewTimer(100 * time.Millisecond) + select { + case <-bounded.Done(): + timer.Stop() + if ctx.Err() != nil { + return nil, ctx.Err() + } + return nil, ErrBusy + case <-timer.C: + } + } +} diff --git a/desktop/internal/pluginruntime/lock_unix.go b/desktop/internal/pluginruntime/lock_unix.go new file mode 100644 index 000000000..4eae6187d --- /dev/null +++ b/desktop/internal/pluginruntime/lock_unix.go @@ -0,0 +1,18 @@ +//go:build darwin || linux + +package pluginruntime + +import ( + "errors" + "os" + + "golang.org/x/sys/unix" +) + +func tryLock(file *os.File) (bool, error) { + err := unix.Flock(int(file.Fd()), unix.LOCK_EX|unix.LOCK_NB) + if errors.Is(err, unix.EWOULDBLOCK) || errors.Is(err, unix.EAGAIN) { + return false, nil + } + return err == nil, err +} From 18ebb87fc2a8faf6c9238bebb170a2090616575f Mon Sep 17 00:00:00 2001 From: "lithe-support[bot]" <356900028+lithe-support[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:05:39 +0000 Subject: [PATCH 09/20] feat(plugins): add reviewed managed runtime support (3/7) --- .../internal/pluginruntime/lock_windows.go | 18 + desktop/internal/pluginruntime/runtime.go | 468 +++++++++++++++++ .../internal/pluginruntime/runtime_test.go | 479 ++++++++++++++++++ desktop/internal/pluginservice/backendhost.go | 5 +- .../internal/pluginservice/backendlaunch.go | 26 +- 5 files changed, 991 insertions(+), 5 deletions(-) create mode 100644 desktop/internal/pluginruntime/lock_windows.go create mode 100644 desktop/internal/pluginruntime/runtime.go create mode 100644 desktop/internal/pluginruntime/runtime_test.go diff --git a/desktop/internal/pluginruntime/lock_windows.go b/desktop/internal/pluginruntime/lock_windows.go new file mode 100644 index 000000000..ef7fbb7c8 --- /dev/null +++ b/desktop/internal/pluginruntime/lock_windows.go @@ -0,0 +1,18 @@ +//go:build windows + +package pluginruntime + +import ( + "errors" + "os" + + "golang.org/x/sys/windows" +) + +func tryLock(file *os.File) (bool, error) { + err := windows.LockFileEx(windows.Handle(file.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, new(windows.Overlapped)) + if errors.Is(err, windows.ERROR_LOCK_VIOLATION) { + return false, nil + } + return err == nil, err +} diff --git a/desktop/internal/pluginruntime/runtime.go b/desktop/internal/pluginruntime/runtime.go new file mode 100644 index 000000000..7b1e11b78 --- /dev/null +++ b/desktop/internal/pluginruntime/runtime.go @@ -0,0 +1,468 @@ +// Package pluginruntime performs native I/O for Core-selected, immutable runtime +// archives. The caller owns dependency selection and plugin validation; this +// package never knows a language, changes a toolchain default, or writes inside +// an installed plugin. Root is the platform's version-independent plugin state. +package pluginruntime + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strings" + + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" +) + +const inventoryLimit = 32 << 20 + +var ( + // ErrCorrupt means recorded runtime contents no longer match their install. + // Preparing the same artifact repairs it without touching the old generation. + ErrCorrupt = errors.New("managed runtime contents are incomplete or changed") + ErrArtifact = errors.New("managed runtime artifact is not usable") + ErrArchive = errors.New("managed runtime archive is not safe to extract") + ErrBusy = errors.New("managed runtime preparation is busy") +) + +// Artifact is the selected platform artifact returned by Core. All paths are +// slash-separated and relative; Executable is relative to Home. CacheKey binds +// dependency version, platform and archive identity, independently of plugin +// versions. Empty Home means the stripped extraction root. +type Artifact struct { + ID, Version, CacheKey, URL, SHA256, Archive string + StripPrefix, Home, Executable string +} + +// Installation names a completed immutable generation. Directory is the +// extraction root, Home the dependency's home, and Executable may be empty. +type Installation struct { + Directory, Home, Executable string + Reused bool +} + +// Progress runs on the I/O worker. A consumer must publish a bounded UI snapshot +// without blocking. Cause is present only when an earlier cache needs repair; +// the owning host boundary records that recovery in its structured log. +type Progress struct { + ID, Phase string + Received, Total int64 + Cause error +} + +// Manager owns no background worker. Root and Downloader must be configured +// before use; multiple managers and processes safely share Root. Generations +// and verified archives survive plugin upgrades and are removed with plugin +// state. Old generations remain readable by running processes and rollback. +type Manager struct { + Root string + Downloader *marketplace.ArchiveDownloader +} + +type inventoryEntry struct { + Path string `json:"path"` + Kind string `json:"kind"` + Size int64 `json:"size,omitempty"` + Modified int64 `json:"modified,omitempty"` + Mode uint32 `json:"mode,omitempty"` + SHA256 string `json:"sha256,omitempty"` + Link string `json:"link,omitempty"` +} + +type receipt struct { + CacheKey string `json:"cacheKey"` + SHA256 string `json:"sha256"` + Generation string `json:"generation"` + Entries []inventoryEntry `json:"entries"` +} + +// Find checks the completion record and complete file inventory without reading +// unchanged file contents. Changed timestamps trigger a checksum check. It is +// suitable for startup, followed by the plugin's version/layout health check. +func (m *Manager) Find(ctx context.Context, artifact Artifact) (Installation, bool, error) { + return m.find(ctx, artifact, false) +} + +// Verify also hashes every recorded file. Installation and update preflight use +// this stronger check; normal language-server startups use Find. +func (m *Manager) Verify(ctx context.Context, artifact Artifact) (Installation, bool, error) { + return m.find(ctx, artifact, true) +} + +func (m *Manager) find(ctx context.Context, artifact Artifact, contents bool) (Installation, bool, error) { + if err := m.check(artifact); err != nil { + return Installation{}, false, err + } + if err := ctx.Err(); err != nil { + return Installation{}, false, err + } + base := filepath.Join(m.Root, artifact.CacheKey) + for _, directory := range []string{m.Root, base} { + info, statErr := os.Lstat(directory) + if errors.Is(statErr, os.ErrNotExist) { + return Installation{}, false, nil + } + if statErr != nil { + return Installation{}, false, statErr + } + if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return Installation{}, false, ErrArtifact + } + } + data, err := configfile.Capture(ctx, base, "ready.json", inventoryLimit) + if err != nil { + return Installation{}, false, err + } + if !data.Exists() { + return Installation{}, false, nil + } + var record receipt + if err := json.Unmarshal(data.Bytes(), &record); err != nil { + return Installation{}, false, fmt.Errorf("%w: completion record", ErrCorrupt) + } + if record.CacheKey != artifact.CacheKey || record.SHA256 != artifact.SHA256 || + !strings.HasPrefix(record.Generation, "install-") || strings.ContainsAny(record.Generation, "/\\") || + len(record.Entries) == 0 || len(record.Entries) > maxEntries { + return Installation{}, false, fmt.Errorf("%w: completion identity", ErrCorrupt) + } + if _, err := pluginpkg.ValidatePath(record.Generation); err != nil { + return Installation{}, false, ErrCorrupt + } + directory := filepath.Join(base, record.Generation) + if err := verifyInventory(ctx, directory, record.Entries, contents); err != nil { + return Installation{}, false, err + } + result, err := installation(directory, artifact) + result.Reused = true + return result, err == nil, err +} + +// Prepare reuses a verified generation or downloads only the selected missing +// archive, extracts privately, asks the plugin to validate it, and publishes one +// completion record. The callback is required and must not retain the staging +// paths: Prepare returns their final, stable paths after publication. +func (m *Manager) Prepare(ctx context.Context, artifact Artifact, validate func(context.Context, Installation) error, progress func(Progress)) (result Installation, err error) { + if err := m.check(artifact); err != nil { + return result, err + } + if validate == nil { + return result, ErrArtifact + } + report := func(phase string, cause error) { + if progress != nil { + progress(Progress{ID: artifact.ID, Phase: phase, Total: -1, Cause: cause}) + } + } + report("checking", nil) + base, err := m.createRoot(artifact.CacheKey) + if err != nil { + return result, err + } + unlock, err := acquire(ctx, filepath.Join(base, ".lock")) + if err != nil { + return result, err + } + defer func() { err = errors.Join(err, unlock()) }() + if err := removeAbandoned(ctx, base); err != nil { + return result, err + } + previous, found, checkErr := m.Verify(ctx, artifact) + if checkErr == nil && found { + checkErr = validate(ctx, previous) + if checkErr == nil { + report("ready", nil) + return previous, nil + } + } + if ctx.Err() != nil { + return result, ctx.Err() + } + if checkErr != nil { + if !found && !errors.Is(checkErr, ErrCorrupt) { + return result, checkErr + } + report("repairing", checkErr) + } + archive, err := m.archive(ctx, artifact, base, progress) + if err != nil { + return result, err + } + defer func() { err = errors.Join(err, archive.Close()) }() + staging, err := os.MkdirTemp(base, ".staging-") + if err != nil { + return result, err + } + defer func() { + if staging != "" { + err = errors.Join(err, os.RemoveAll(staging)) + } + }() + report("extracting", nil) + entries, err := extract(ctx, archive, staging, artifact) + if err != nil { + return result, err + } + report("verifying", nil) + candidate, err := installation(staging, artifact) + if err != nil { + return result, err + } + if err := validate(ctx, candidate); err != nil { + return result, err + } + // A validator may execute a probe but must not modify the immutable input. + if err := verifyInventory(ctx, staging, entries, true); err != nil { + return result, err + } + if err := ctx.Err(); err != nil { + return result, err + } + generation := "install-" + strings.TrimPrefix(filepath.Base(staging), ".staging-") + finalDirectory := filepath.Join(base, generation) + if err := os.Rename(staging, finalDirectory); err != nil { + return result, err + } + staging = finalDirectory // Unpublished generation is still this attempt's to remove. + encoded, err := json.Marshal(receipt{artifact.CacheKey, artifact.SHA256, generation, entries}) + if err != nil { + return result, err + } + snapshot, err := configfile.Capture(ctx, base, "ready.json", inventoryLimit) + if err != nil { + return result, err + } + committed, err := snapshot.Replace(ctx, encoded, nil) + if committed { + staging = "" + } + if err != nil { + return result, err + } + result, err = installation(finalDirectory, artifact) + if err == nil { + report("ready", nil) + } + return result, err +} + +func (m *Manager) check(artifact Artifact) error { + if m == nil || !filepath.IsAbs(m.Root) || filepath.Clean(m.Root) == string(filepath.Separator) { + return ErrArtifact + } + for _, digest := range []string{artifact.CacheKey, artifact.SHA256} { + bytes, err := hex.DecodeString(digest) + if err != nil || len(bytes) != sha256.Size || digest != strings.ToLower(digest) { + return ErrArtifact + } + } + for _, name := range []string{artifact.StripPrefix, artifact.Home, artifact.Executable} { + if name != "" { + if _, err := pluginpkg.ValidatePath(name); err != nil { + return fmt.Errorf("%w: %w", ErrArtifact, err) + } + } + } + if artifact.Archive != "zip" && artifact.Archive != "tar.gz" { + return ErrArtifact + } + return nil +} + +func (m *Manager) createRoot(key string) (_ string, err error) { + if err := os.MkdirAll(m.Root, 0o700); err != nil { + return "", err + } + info, err := os.Lstat(m.Root) + if err != nil { + return "", err + } + if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return "", ErrArtifact + } + root, err := os.OpenRoot(m.Root) + if err != nil { + return "", err + } + defer func() { err = errors.Join(err, root.Close()) }() + if err := root.Mkdir(key, 0o700); err != nil && !errors.Is(err, os.ErrExist) { + return "", err + } + info, err = root.Lstat(key) + if err != nil { + return "", err + } + if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return "", ErrArtifact + } + return filepath.Join(m.Root, key), nil +} + +func installation(directory string, artifact Artifact) (result Installation, err error) { + result = Installation{Directory: directory, Home: filepath.Join(directory, filepath.FromSlash(artifact.Home))} + if artifact.Executable != "" { + result.Executable = filepath.Join(result.Home, filepath.FromSlash(artifact.Executable)) + } + root, err := os.OpenRoot(directory) + if err != nil { + return Installation{}, fmt.Errorf("%w: %w", ErrCorrupt, err) + } + defer func() { err = errors.Join(err, root.Close()) }() + homeName := filepath.FromSlash(artifact.Home) + if homeName == "" { + homeName = "." + } + home, err := root.Stat(homeName) + if err != nil || !home.IsDir() { + return Installation{}, fmt.Errorf("%w: home directory", ErrCorrupt) + } + if artifact.Executable != "" { + file, err := root.Stat(filepath.Join(filepath.FromSlash(artifact.Home), filepath.FromSlash(artifact.Executable))) + if err != nil || !file.Mode().IsRegular() { + return Installation{}, fmt.Errorf("%w: executable", ErrCorrupt) + } + } + return result, nil +} + +func removeAbandoned(ctx context.Context, base string) error { + entries, err := os.ReadDir(base) + if err != nil { + return err + } + for _, entry := range entries { + if err := ctx.Err(); err != nil { + return err + } + if strings.HasPrefix(entry.Name(), ".staging-") || strings.HasPrefix(entry.Name(), ".archive-") { + if err := os.RemoveAll(filepath.Join(base, entry.Name())); err != nil { + return err + } + } + } + return nil +} + +// archive returns one open, verified handle. Extraction reads that exact handle +// rather than reopening a pathname after checking its digest. +func (m *Manager) archive(ctx context.Context, artifact Artifact, base string, progress func(Progress)) (result *os.File, err error) { + defer func() { + if err != nil && result != nil { + err = errors.Join(err, result.Close()) + result = nil + } + }() + path := filepath.Join(base, "archive") + file, checkErr := openVerified(ctx, path, artifact.SHA256) + if checkErr == nil { + return file, nil + } + if !errors.Is(checkErr, os.ErrNotExist) && !errors.Is(checkErr, ErrCorrupt) { + return nil, checkErr + } + if progress != nil && errors.Is(checkErr, ErrCorrupt) { + progress(Progress{ID: artifact.ID, Phase: "repairing", Total: -1, Cause: checkErr}) + } + session := marketplace.NewArchiveSession(m.Downloader) + defer func() { err = errors.Join(err, session.Close()) }() + download, err := session.Download(ctx, core.MarketplaceAvailability{Status: "available", DownloadURL: artifact.URL, SHA256: artifact.SHA256}, func(p marketplace.ArchiveProgress) { + if progress != nil { + progress(Progress{ID: artifact.ID, Phase: "downloading", Received: p.Received, Total: p.Total}) + } + }) + if err != nil { + return nil, err + } + defer func() { err = errors.Join(err, download.Discard()) }() + source, err := openVerified(ctx, download.Path(), artifact.SHA256) + if err != nil { + return nil, err + } + defer func() { err = errors.Join(err, source.Close()) }() + temporary, err := os.CreateTemp(base, ".archive-") + if err != nil { + return nil, err + } + temporaryName := temporary.Name() + defer func() { + if temporary != nil { + err = errors.Join(err, temporary.Close()) + } + if cleanup := os.Remove(temporaryName); cleanup != nil && !errors.Is(cleanup, os.ErrNotExist) { + err = errors.Join(err, cleanup) + } + }() + if _, err := io.Copy(temporary, contextReader{ctx, source}); err != nil { + return nil, err + } + if err := temporary.Sync(); err != nil { + return nil, err + } + if err := temporary.Close(); err != nil { + return nil, err + } + temporary = nil + if err := ctx.Err(); err != nil { + return nil, err + } + if err := os.Rename(temporaryName, path); err != nil { + return nil, err + } + return openVerified(ctx, path, artifact.SHA256) +} + +func openVerified(ctx context.Context, path, digest string) (_ *os.File, err error) { + info, err := os.Lstat(path) + if err != nil { + return nil, err + } + if !info.Mode().IsRegular() || info.Size() > marketplace.MaxArchiveBytes { + return nil, ErrCorrupt + } + file, err := os.Open(path) + if err != nil { + return nil, err + } + defer func() { + if err != nil { + err = errors.Join(err, file.Close()) + } + }() + opened, err := file.Stat() + if err != nil { + return nil, err + } + if !os.SameFile(info, opened) || !opened.Mode().IsRegular() { + return nil, ErrCorrupt + } + hash := sha256.New() + if _, err := io.Copy(hash, contextReader{ctx, io.LimitReader(file, marketplace.MaxArchiveBytes+1)}); err != nil { + return nil, err + } + if hex.EncodeToString(hash.Sum(nil)) != digest { + return nil, ErrCorrupt + } + if _, err := file.Seek(0, io.SeekStart); err != nil { + return nil, err + } + return file, nil +} + +type contextReader struct { + ctx context.Context + source io.Reader +} + +func (r contextReader) Read(p []byte) (int, error) { + if err := r.ctx.Err(); err != nil { + return 0, err + } + return r.source.Read(p) +} diff --git a/desktop/internal/pluginruntime/runtime_test.go b/desktop/internal/pluginruntime/runtime_test.go new file mode 100644 index 000000000..f088ed865 --- /dev/null +++ b/desktop/internal/pluginruntime/runtime_test.go @@ -0,0 +1,479 @@ +package pluginruntime + +import ( + "archive/tar" + "archive/zip" + "bytes" + "compress/gzip" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "io" + "net/http" + "os" + "path/filepath" + "runtime" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" +) + +type transportFunc func(*http.Request) (*http.Response, error) + +func (f transportFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +type member struct { + name, body, link string + kind byte + mode int64 +} + +func tarArchive(t *testing.T, members ...member) []byte { + t.Helper() + var buffer bytes.Buffer + compressed := gzip.NewWriter(&buffer) + archive := tar.NewWriter(compressed) + for _, item := range members { + kind := item.kind + if kind == 0 { + kind = tar.TypeReg + } + mode := item.mode + if mode == 0 { + mode = 0o644 + } + size := int64(len(item.body)) + if kind != tar.TypeReg { + size = 0 + } + if err := archive.WriteHeader(&tar.Header{Name: item.name, Mode: mode, Size: size, Typeflag: kind, Linkname: item.link}); err != nil { + t.Fatal(err) + } + if size != 0 { + if _, err := archive.Write([]byte(item.body)); err != nil { + t.Fatal(err) + } + } + } + if err := archive.Close(); err != nil { + t.Fatal(err) + } + if err := compressed.Close(); err != nil { + t.Fatal(err) + } + return buffer.Bytes() +} + +func zipArchive(t *testing.T, members ...member) []byte { + t.Helper() + var buffer bytes.Buffer + archive := zip.NewWriter(&buffer) + for _, item := range members { + header := &zip.FileHeader{Name: item.name, Method: zip.Deflate} + mode := os.FileMode(item.mode) + if mode == 0 { + mode = 0o644 + } + header.SetMode(mode) + writer, err := archive.CreateHeader(header) + if err != nil { + t.Fatal(err) + } + if _, err := writer.Write([]byte(item.body)); err != nil { + t.Fatal(err) + } + } + if err := archive.Close(); err != nil { + t.Fatal(err) + } + return buffer.Bytes() +} + +func selected(body []byte, format, version string) Artifact { + digest := sha256.Sum256(body) + key := sha256.Sum256(append([]byte(version), digest[:]...)) + return Artifact{ID: "worker", Version: version, CacheKey: hex.EncodeToString(key[:]), URL: "https://runtimes.example.test/worker", SHA256: hex.EncodeToString(digest[:]), Archive: format, StripPrefix: "distribution", Executable: "bin/worker"} +} + +func testManager(t *testing.T, bodies map[string][]byte) (*Manager, *atomic.Int64) { + t.Helper() + calls := new(atomic.Int64) + client := &http.Client{Transport: transportFunc(func(request *http.Request) (*http.Response, error) { + calls.Add(1) + body, ok := bodies[request.URL.String()] + if !ok { + return nil, errors.New("unexpected download") + } + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(bytes.NewReader(body)), ContentLength: int64(len(body)), Request: request}, nil + })} + return &Manager{Root: filepath.Join(t.TempDir(), "state with spaces", "runtimes"), Downloader: marketplace.NewArchiveDownloader(client)}, calls +} + +func testContext(t *testing.T) context.Context { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + t.Cleanup(cancel) + return ctx +} + +func validateBody(expected string) func(context.Context, Installation) error { + return func(ctx context.Context, installation Installation) error { + if err := ctx.Err(); err != nil { + return err + } + body, err := os.ReadFile(installation.Executable) + if err == nil && string(body) != expected { + err = errors.New("runtime probe rejected the installed version") + } + return err + } +} + +func TestPrepareReusesAcrossPluginVersionsAndRepairsOffline(t *testing.T) { + for _, format := range []string{"tar.gz", "zip"} { + t.Run(format, func(t *testing.T) { + items := []member{{name: "distribution/bin/worker", body: "version one", mode: 0o755}, {name: "distribution/lib/resource", body: "payload"}} + body := tarArchive(t, items...) + if format == "zip" { + body = zipArchive(t, items...) + } + artifact := selected(body, format, "1") + manager, calls := testManager(t, map[string][]byte{artifact.URL: body}) + ctx := testContext(t) + first, err := manager.Prepare(ctx, artifact, validateBody("version one"), nil) + if err != nil || first.Reused { + t.Fatalf("first prepare = %+v, %v", first, err) + } + if runtime.GOOS != "windows" { + info, err := os.Stat(first.Executable) + if err != nil || info.Mode().Perm()&0o111 != 0o111 { + t.Fatalf("executable permissions = %v, %v", info, err) + } + } + // A new plugin version creates a new manager, but the same Core cache + // identity is independent of that plugin's package version. + updated := *manager + reused, err := updated.Prepare(ctx, artifact, validateBody("version one"), nil) + if err != nil || !reused.Reused || reused.Directory != first.Directory || calls.Load() != 1 { + t.Fatalf("reuse = %+v, %v, downloads %d", reused, err, calls.Load()) + } + if err := os.WriteFile(first.Executable, []byte("version two"), 0o755); err != nil { + t.Fatal(err) + } + if _, _, err := updated.Verify(ctx, artifact); !errors.Is(err, ErrCorrupt) { + t.Fatalf("changed runtime verified: %v", err) + } + var repairing bool + repaired, err := updated.Prepare(ctx, artifact, validateBody("version one"), func(p Progress) { repairing = repairing || p.Phase == "repairing" }) + if err != nil || repaired.Reused || repaired.Directory == first.Directory || calls.Load() != 1 || !repairing { + t.Fatalf("repair = %+v, %v, downloads %d, repairing %v", repaired, err, calls.Load(), repairing) + } + if _, err := os.Stat(first.Executable); err != nil { + t.Fatalf("repair removed a generation that an existing process may use: %v", err) + } + }) + } +} + +func TestFailedDependencyUpgradeRetainsPreviousRuntime(t *testing.T) { + oldBody := tarArchive(t, member{name: "distribution/bin/worker", body: "working"}) + newBody := tarArchive(t, member{name: "distribution/bin/worker", body: "incompatible"}) + old := selected(oldBody, "tar.gz", "1") + next := selected(newBody, "tar.gz", "2") + next.URL += "-new" + manager, _ := testManager(t, map[string][]byte{old.URL: oldBody, next.URL: newBody}) + ctx := testContext(t) + previous, err := manager.Prepare(ctx, old, validateBody("working"), nil) + if err != nil { + t.Fatal(err) + } + if _, err := manager.Prepare(ctx, next, validateBody("working"), nil); err == nil { + t.Fatal("incompatible upgrade was published") + } + if _, found, err := manager.Find(ctx, next); err != nil || found { + t.Fatalf("failed upgrade has a completion marker: %v, %v", found, err) + } + current, found, err := manager.Verify(ctx, old) + if err != nil || !found || current.Directory != previous.Directory { + t.Fatalf("previous runtime was lost: %+v, %v, %v", current, found, err) + } +} + +func TestConcurrentManagersDownloadOnceAndCancellationReleasesWaiter(t *testing.T) { + body := tarArchive(t, member{name: "distribution/bin/worker", body: "working"}) + artifact := selected(body, "tar.gz", "1") + manager, calls := testManager(t, map[string][]byte{artifact.URL: body}) + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + entered, release := make(chan struct{}), make(chan struct{}) + var firstOnce sync.Once + validator := func(ctx context.Context, candidate Installation) error { + firstOnce.Do(func() { + close(entered) + select { + case <-release: + case <-ctx.Done(): + } + }) + return validateBody("working")(ctx, candidate) + } + type outcome struct { + installation Installation + err error + } + firstDone, secondDone := make(chan outcome, 1), make(chan outcome, 1) + firstFinished, secondFinished := make(chan struct{}), make(chan struct{}) + go func() { + defer close(firstFinished) + value, err := manager.Prepare(ctx, artifact, validator, nil) + firstDone <- outcome{value, err} + }() + secondCtx, cancelSecond := context.WithCancel(ctx) + secondStarted := make(chan struct{}, 1) + var secondStartedOnce sync.Once + go func() { + defer close(secondFinished) + select { + case <-entered: + case <-ctx.Done(): + } + other := *manager + value, err := other.Prepare(secondCtx, artifact, validateBody("working"), func(p Progress) { + if p.Phase == "checking" { + secondStartedOnce.Do(func() { secondStarted <- struct{}{} }) + } + }) + secondDone <- outcome{value, err} + }() + t.Cleanup(func() { + cancelSecond() + cancel() + for _, finished := range []<-chan struct{}{firstFinished, secondFinished} { + select { + case <-finished: + case <-time.After(5 * time.Second): + t.Error("runtime preparation worker did not stop during cleanup") + } + } + }) + select { + case <-secondStarted: + case <-ctx.Done(): + t.Fatal("second manager did not reach the lock") + } + cancelSecond() + select { + case result := <-secondDone: + if !errors.Is(result.err, context.Canceled) { + t.Fatalf("waiting manager returned %v", result.err) + } + case <-ctx.Done(): + t.Fatal("cancelled lock waiter did not exit") + } + close(release) + var first outcome + select { + case first = <-firstDone: + case <-ctx.Done(): + t.Fatal("first manager did not complete") + } + if first.err != nil { + t.Fatal(first.err) + } + other := *manager + last, err := other.Prepare(ctx, artifact, validateBody("working"), nil) + if err != nil || !last.Reused || last.Directory != first.installation.Directory || calls.Load() != 1 { + t.Fatalf("final reuse = %+v, %v, downloads %d", last, err, calls.Load()) + } +} + +func TestUnsafeArchivesNeverPublishOrWriteOutsideTheirGeneration(t *testing.T) { + cases := []struct { + name string + items []member + }{ + {"parent", []member{{name: "distribution/../../escape", body: "bad"}}}, + {"absolute", []member{{name: "/escape", body: "bad"}}}, + {"drive", []member{{name: "distribution/C:/escape", body: "bad"}}}, + {"backslash", []member{{name: "distribution/a\\escape", body: "bad"}}}, + {"outside prefix", []member{{name: "another/bin/worker", body: "bad"}}}, + {"duplicate", []member{{name: "distribution/bin/worker", body: "one"}, {name: "distribution/bin/worker", body: "two"}}}, + {"case collision", []member{{name: "distribution/bin/worker", body: "one"}, {name: "distribution/BIN/WORKER", body: "two"}}}, + {"link escape", []member{{name: "distribution/bin/worker", kind: tar.TypeSymlink, link: "../../escape"}}}, + {"link parent write", []member{{name: "distribution/bin", kind: tar.TypeSymlink, link: "lib"}, {name: "distribution/bin/worker", body: "bad"}}}, + {"hardlink escape", []member{{name: "distribution/bin/worker", kind: tar.TypeLink, link: "../../escape"}}}, + {"device", []member{{name: "distribution/bin/worker", kind: tar.TypeChar}}}, + } + for _, test := range cases { + t.Run(test.name, func(t *testing.T) { + body := tarArchive(t, test.items...) + artifact := selected(body, "tar.gz", "1") + manager, _ := testManager(t, map[string][]byte{artifact.URL: body}) + ctx := testContext(t) + if _, err := manager.Prepare(ctx, artifact, validateBody("working"), nil); err == nil { + t.Fatal("unsafe archive accepted") + } + if _, found, err := manager.Find(ctx, artifact); err != nil || found { + t.Fatalf("unsafe archive published: %v, %v", found, err) + } + entries, err := os.ReadDir(filepath.Join(manager.Root, artifact.CacheKey)) + if err != nil { + t.Fatal(err) + } + for _, entry := range entries { + if strings.HasPrefix(entry.Name(), ".staging-") || strings.HasPrefix(entry.Name(), "install-") { + t.Fatalf("unverified extraction remains: %s", entry.Name()) + } + } + }) + } +} + +func TestInternalArchiveLinksAndHomeLayout(t *testing.T) { + probe := t.TempDir() + if err := os.WriteFile(filepath.Join(probe, "target"), nil, 0o600); err != nil { + t.Fatal(err) + } + if err := os.Symlink("target", filepath.Join(probe, "link")); err != nil { + t.Skipf("native symbolic link creation unavailable: %v", err) + } + body := tarArchive(t, + member{name: "./distribution/Contents/Home/bin/worker", body: "working", mode: 0o755}, + member{name: "./distribution/Contents/Home/lib/resource", body: "resource"}, + member{name: "./distribution/Contents/Home/bin/resource", kind: tar.TypeSymlink, link: "../lib/resource"}, + member{name: "./distribution/Contents/Home/lib/alias", kind: tar.TypeLink, link: "distribution/Contents/Home/lib/resource"}, + ) + artifact := selected(body, "tar.gz", "1") + artifact.Home = "Contents/Home" + manager, _ := testManager(t, map[string][]byte{artifact.URL: body}) + ctx := testContext(t) + installed, err := manager.Prepare(ctx, artifact, validateBody("working"), nil) + if err != nil { + t.Fatal(err) + } + for _, name := range []string{"bin/resource", "lib/alias"} { + data, err := os.ReadFile(filepath.Join(installed.Home, filepath.FromSlash(name))) + if err != nil || string(data) != "resource" { + t.Fatalf("archive link %s = %q, %v", name, data, err) + } + } +} + +func TestChecksumFailureAndCancelledValidationNeverPublish(t *testing.T) { + body := tarArchive(t, member{name: "distribution/bin/worker", body: "working"}) + artifact := selected(body, "tar.gz", "1") + manager, _ := testManager(t, map[string][]byte{artifact.URL: []byte("damaged download")}) + ctx := testContext(t) + if _, err := manager.Prepare(ctx, artifact, validateBody("working"), nil); !errors.Is(err, marketplace.ErrArchiveChecksum) { + t.Fatalf("checksum failure = %v", err) + } + manager, _ = testManager(t, map[string][]byte{artifact.URL: body}) + cancelCtx, cancel := context.WithCancel(ctx) + _, err := manager.Prepare(cancelCtx, artifact, func(context.Context, Installation) error { cancel(); return context.Canceled }, nil) + if !errors.Is(err, context.Canceled) { + t.Fatalf("cancelled validation = %v", err) + } + if _, found, err := manager.Find(ctx, artifact); err != nil || found { + t.Fatalf("cancelled preparation published: %v, %v", found, err) + } +} + +func TestArchiveBudgetsRejectOversizedMetadataBeforeExtraction(t *testing.T) { + ctx := testContext(t) + valid := zipArchive(t, member{name: "distribution/bin/worker", body: "working"}) + for _, mutate := range []func([]byte){ + func(body []byte) { body[len(body)-12], body[len(body)-11] = 0xfe, 0xff }, + func(body []byte) { + body[len(body)-10], body[len(body)-9], body[len(body)-8], body[len(body)-7] = 0xff, 0xff, 0xff, 0x7f + }, + } { + body := bytes.Clone(valid) + mutate(body) + if err := checkZIPDirectory(ctx, bytes.NewReader(body), int64(len(body))); !errors.Is(err, ErrArchive) { + t.Fatalf("oversized ZIP metadata accepted: %v", err) + } + } + var compressed bytes.Buffer + gzipWriter := gzip.NewWriter(&compressed) + tarWriter := tar.NewWriter(gzipWriter) + if err := tarWriter.WriteHeader(&tar.Header{Name: "distribution/bin/worker", Mode: 0o755, Size: maxExpandedBytes + 1}); err != nil { + t.Fatal(err) + } + // The deliberately truncated file has a valid gzip stream. Its oversized + // tar declaration must be refused before any content is requested or written. + if err := gzipWriter.Close(); err != nil { + t.Fatal(err) + } + body := compressed.Bytes() + artifact := selected(body, "tar.gz", "1") + manager, _ := testManager(t, map[string][]byte{artifact.URL: body}) + if _, err := manager.Prepare(ctx, artifact, validateBody("working"), nil); !errors.Is(err, ErrArchive) { + t.Fatalf("oversized tar declaration accepted: %v", err) + } +} + +type blockedBody struct { + ctx context.Context + started chan struct{} + once sync.Once +} + +func (b *blockedBody) Read([]byte) (int, error) { + b.once.Do(func() { close(b.started) }) + <-b.ctx.Done() + return 0, b.ctx.Err() +} +func (*blockedBody) Close() error { return nil } + +func TestCancelledTransferLeavesNoCompleteOrPartialGeneration(t *testing.T) { + body := tarArchive(t, member{name: "distribution/bin/worker", body: "working"}) + artifact := selected(body, "tar.gz", "1") + started := make(chan struct{}) + client := &http.Client{Transport: transportFunc(func(request *http.Request) (*http.Response, error) { + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: &blockedBody{ctx: request.Context(), started: started}, ContentLength: -1, Request: request}, nil + })} + manager := &Manager{Root: filepath.Join(t.TempDir(), "runtimes"), Downloader: marketplace.NewArchiveDownloader(client)} + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + result, finished := make(chan error, 1), make(chan struct{}) + go func() { + defer close(finished) + _, err := manager.Prepare(ctx, artifact, validateBody("working"), nil) + result <- err + }() + t.Cleanup(func() { + cancel() + select { + case <-finished: + case <-time.After(5 * time.Second): + t.Error("cancelled transfer worker did not stop") + } + }) + select { + case <-started: + case <-ctx.Done(): + t.Fatal("transfer did not reach the body") + } + cancel() + select { + case err := <-result: + if !errors.Is(err, context.Canceled) { + t.Fatalf("cancelled transfer error = %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("transfer did not return after cancellation") + } + entries, err := os.ReadDir(filepath.Join(manager.Root, artifact.CacheKey)) + if err != nil { + t.Fatal(err) + } + for _, entry := range entries { + if entry.Name() != ".lock" { + t.Fatalf("cancelled transfer left unverified data: %s", entry.Name()) + } + } +} diff --git a/desktop/internal/pluginservice/backendhost.go b/desktop/internal/pluginservice/backendhost.go index e172ca940..e87e3a5ea 100644 --- a/desktop/internal/pluginservice/backendhost.go +++ b/desktop/internal/pluginservice/backendhost.go @@ -81,6 +81,9 @@ type BackendSession struct { Session pluginbackend.Session cancel context.CancelFunc done chan struct{} + // stopErr is published by closing done, after native shutdown/disposal. + stopErr error + disposed bool mu sync.Mutex ready bool @@ -490,7 +493,7 @@ func (b *BackendSession) serve(ctx context.Context) { b.host.mu.Unlock() stopCtx, cancel := context.WithTimeout(context.Background(), backendStopTimeout) defer cancel() - _ = b.host.service.Backend.Stop(stopCtx, b.Session) + b.disposed, b.stopErr = b.host.service.Backend.StopAndDispose(stopCtx, b.Session) } // observe records the lifecycle facts calls depend on and routes completions. diff --git a/desktop/internal/pluginservice/backendlaunch.go b/desktop/internal/pluginservice/backendlaunch.go index 4a37bb766..0c8762b32 100644 --- a/desktop/internal/pluginservice/backendlaunch.go +++ b/desktop/internal/pluginservice/backendlaunch.go @@ -29,7 +29,7 @@ type backendLaunch struct { // system temporary directory. Nothing is derived from the installed // package or the application bundle, which stay read-only so the next // differential update still matches what the user installed. -func (s *Service) resolveBackendLaunch(ctx context.Context, pluginID, version string, manifest json.RawMessage, languageID string, workspace WorkspaceContext, start pluginbackend.StartRequest) (backendLaunch, error) { +func (s *Service) resolveBackendLaunch(ctx context.Context, pluginID, version string, manifest json.RawMessage, languageID string, workspace WorkspaceContext, start pluginbackend.StartRequest, runtimes RuntimeEnvironment) (backendLaunch, error) { if workspace.ContextID == "" { return backendLaunch{}, fmt.Errorf("%w: a backend-resolved server needs an open workspace", pluginbackend.ErrRequest) } @@ -74,7 +74,7 @@ func (s *Service) resolveBackendLaunch(ctx context.Context, pluginID, version st } // The function's params are the plan's resolveParams themselves, as the // contract says: serverID, platform, the four directories and the settings. - params, err := s.languageLaunchParams(ctx, workspace.Path, manifest, plan.ResolveParams) + params, err := s.languageLaunchParamsWithRuntimes(ctx, workspace.Path, manifest, plan.ResolveParams, runtimes) if err != nil { return fail(err) } @@ -109,7 +109,11 @@ func (s *Service) resolveBackendLaunch(ctx context.Context, pluginID, version st // any tool's version or configuration. Core already validated requiresTools; // the resolver uses the same user choices and discovery as Build and Run. func (s *Service) languageLaunchParams(ctx context.Context, root string, manifest, params json.RawMessage) (json.RawMessage, error) { - if s.LanguageTool == nil { + return s.languageLaunchParamsWithRuntimes(ctx, root, manifest, params, RuntimeEnvironment{}) +} + +func (s *Service) languageLaunchParamsWithRuntimes(ctx context.Context, root string, manifest, params json.RawMessage, runtimes RuntimeEnvironment) (json.RawMessage, error) { + if s.LanguageTool == nil && len(runtimes.Runtimes) == 0 { return params, nil } var declaration struct { @@ -125,6 +129,14 @@ func (s *Service) languageLaunchParams(ctx context.Context, root string, manifes } tools := make(map[string]installation) for _, tool := range declaration.RequiresTools { + if managed, found := runtimes.Facts[tool]; found { + home := managed.Home + tools[tool] = installation{managed.Executable, &home, managed.Version} + continue + } + if s.LanguageTool == nil { + continue + } selected, err := s.LanguageTool(ctx, root, tool) if err != nil { return nil, err @@ -133,7 +145,7 @@ func (s *Service) languageLaunchParams(ctx context.Context, root string, manifes tools[tool] = installation{selected.Executable, selected.Home, selected.Version} } } - if len(tools) == 0 { + if len(tools) == 0 && len(runtimes.Runtimes) == 0 { return params, nil } var value map[string]json.RawMessage @@ -145,5 +157,11 @@ func (s *Service) languageLaunchParams(ctx context.Context, root string, manifes return nil, err } value["tools"] = encoded + if len(runtimes.Runtimes) > 0 { + value["runtimes"], err = json.Marshal(runtimes.Runtimes) + if err != nil { + return nil, err + } + } return json.Marshal(value) } From 21f54669e3098c59f7f756037d8506ab6eede079 Mon Sep 17 00:00:00 2001 From: "lithe-support[bot]" <356900028+lithe-support[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:05:47 +0000 Subject: [PATCH 10/20] feat(plugins): add reviewed managed runtime support (4/7) --- .../pluginservice/backendlaunch_test.go | 29 ++++++++++++ desktop/internal/pluginservice/backends.go | 45 +++++++++++++++++-- desktop/internal/pluginservice/lifecycle.go | 37 +++++++++++++-- .../internal/pluginservice/pluginservice.go | 38 ++++++++++------ .../internal/settingswindow/installed_view.go | 2 + 5 files changed, 130 insertions(+), 21 deletions(-) diff --git a/desktop/internal/pluginservice/backendlaunch_test.go b/desktop/internal/pluginservice/backendlaunch_test.go index f6ed64d3d..97015a782 100644 --- a/desktop/internal/pluginservice/backendlaunch_test.go +++ b/desktop/internal/pluginservice/backendlaunch_test.go @@ -55,3 +55,32 @@ func TestLanguageLaunchKeepsParamsWithoutOptionalTools(t *testing.T) { t.Fatalf("changed unconfigured launch: %s %v", result, err) } } + +func TestManagedServerToolDoesNotReplaceProjectCompiler(t *testing.T) { + projectHome := "/project/compiler" + service := &Service{LanguageTool: func(_ context.Context, _, tool string) (*core.ToolchainSelection, error) { + if tool != "project-compiler" { + t.Fatalf("managed tool incorrectly reached the project resolver: %s", tool) + } + return &core.ToolchainSelection{Home: &projectHome, Executable: projectHome + "/bin/compiler", Version: "8"}, nil + }} + runtimes := RuntimeEnvironment{ + Runtimes: map[string]core.ManagedRuntimeInstallation{"engine": {ID: "engine", Home: "/managed/engine", Version: "25"}}, + Facts: map[string]RuntimeTool{"server-runtime": {Executable: "/managed/engine/bin/runtime", Home: "/managed/engine", Version: "25"}}, + } + params, err := service.languageLaunchParamsWithRuntimes(context.Background(), "/workspace", + json.RawMessage(`{"requiresTools":["project-compiler","server-runtime"]}`), json.RawMessage(`{"settings":{}}`), runtimes) + if err != nil { + t.Fatal(err) + } + var decoded struct { + Tools map[string]RuntimeTool `json:"tools"` + Runtimes map[string]core.ManagedRuntimeInstallation `json:"runtimes"` + } + if err := json.Unmarshal(params, &decoded); err != nil { + t.Fatal(err) + } + if decoded.Tools["project-compiler"].Version != "8" || decoded.Tools["server-runtime"].Version != "25" || decoded.Runtimes["engine"].Home != "/managed/engine" { + t.Fatalf("project and language-service installations were mixed: %s", params) + } +} diff --git a/desktop/internal/pluginservice/backends.go b/desktop/internal/pluginservice/backends.go index ad66abaf0..4fefff099 100644 --- a/desktop/internal/pluginservice/backends.go +++ b/desktop/internal/pluginservice/backends.go @@ -7,12 +7,14 @@ import ( "fmt" "os" "path/filepath" + "time" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginbackend" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginlsp" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginmanager" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginruntime" ) // BackendRequest is the workspace a language server serves. @@ -22,6 +24,9 @@ type BackendRequest struct { WorkingDirectory string // Architecture is the platform architecture Core plans for. Architecture string + // RuntimeProgress reports cancellable preparation before the bounded server + // launch. It may be called from a worker goroutine. + RuntimeProgress func(pluginruntime.Progress) } // LanguageSession is one running language server. @@ -62,6 +67,12 @@ func (s *Service) StartLanguageServer(ctx context.Context, entries []pluginmanag if !ok { return nil, err } + ctx, preparation, preparationErr := s.beginRuntimePreparation(ctx, entry.Installed.ID) + if preparationErr != nil { + return nil, errors.Join(err, preparationErr) + } + var cleanupErr error + defer func() { preparation.finish(cleanupErr) }() // The start is one attempt of the plugin's languageServers declaration. What fails before // the runner hands it to Core is the host's to record, as a launch it could not resolve; // Core records everything after the handoff. @@ -84,6 +95,15 @@ func (s *Service) StartLanguageServer(ctx context.Context, entries []pluginmanag if settingsErr != nil { return fail(settingsErr) } + runtimes, runtimeErr := s.EnsureRuntimesWithSettings(ctx, manifest, entry.Installed.Path, entry.Installed.ID, entry.Installed.Version, false, settings.State, request.RuntimeProgress) + if runtimeErr != nil { + return fail(runtimeErr) + } + // Downloads have their own cancellation and transport stall limits. Apply + // the process-start budget only after the environment is ready, so slow + // healthy downloads do not repeatedly lose their progress. + ctx, cancelStart := context.WithTimeout(ctx, 2*time.Minute) + defer cancelStart() // State lives beside the installed versions, never inside one: an installed // package is read-only for the host, and a version directory that changed // would no longer match the digest the user approved. @@ -105,10 +125,11 @@ func (s *Service) StartLanguageServer(ctx context.Context, entries []pluginmanag ProjectSettings: settings.State.ProjectSettings, RootURI: request.RootURI, WorkingDirectory: request.WorkingDirectory, + ManagedTools: runtimes.Tools, } temporary := "" if declaresBackendLaunch(manifest, languageID) { - resolved, resolveErr := s.resolveBackendLaunch(ctx, entry.Installed.ID, entry.Installed.Version, manifest, languageID, workspaceContext, start) + resolved, resolveErr := s.resolveBackendLaunch(ctx, entry.Installed.ID, entry.Installed.Version, manifest, languageID, workspaceContext, start, runtimes) if resolveErr != nil { return fail(resolveErr) } @@ -121,6 +142,19 @@ func (s *Service) StartLanguageServer(ctx context.Context, entries []pluginmanag removeTemporary(temporary) return fail(startErr) } + if cancelled := ctx.Err(); cancelled != nil { + preparation.retryCleanup = func(stopCtx context.Context) error { + disposed, err := s.Backend.StopAndDispose(stopCtx, started) + if disposed { + removeTemporary(temporary) + } + return s.runtimeStopFailure(stopCtx, disposed, err) + } + stopCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), backendStopTimeout) + cleanupErr = preparation.retryCleanup(stopCtx) + cancel() + return fail(errors.Join(cancelled, cleanupErr)) + } session := &LanguageSession{ PluginID: entry.Installed.ID, Version: entry.Installed.Version, @@ -170,11 +204,14 @@ func (s *Service) StopLanguageServer(ctx context.Context, session *LanguageSessi if session == nil { return nil } - s.unregisterLanguageSession(session) session.end() s.observeLanguage(session, core.BackendEvent{Type: "stateChanged", State: "stopped"}) - removeTemporary(session.temporary) - return s.Backend.Stop(ctx, session.Session) + disposed, err := s.Backend.StopAndDispose(ctx, session.Session) + if disposed { + s.unregisterLanguageSession(session) + removeTemporary(session.temporary) + } + return err } type languageServerDeclaration struct { diff --git a/desktop/internal/pluginservice/lifecycle.go b/desktop/internal/pluginservice/lifecycle.go index 0a47e0694..32dab4f0b 100644 --- a/desktop/internal/pluginservice/lifecycle.go +++ b/desktop/internal/pluginservice/lifecycle.go @@ -19,6 +19,13 @@ import ( // other native owners, including other project tabs, before stopping the language // server and backend. A failed stop preserves the package and state for retry. func (s *Service) Uninstall(ctx context.Context, id string, server *LanguageSession, stopNative ...func(context.Context) error) error { + release := s.holdRuntimeStop(id) + defer release() + // A commit already past its cancellation check may finish while stopping. + // Await it before Core snapshots installed versions for the removal plan. + if err := s.stopRuntimePreparations(ctx, id); err != nil { + return err + } _, err := s.Manager.Apply(ctx, core.PluginUninstall, id, func() error { var failures []error for _, stop := range stopNative { @@ -34,6 +41,11 @@ func (s *Service) Uninstall(ctx context.Context, id string, server *LanguageSess // as Uninstall does, so a disabled plugin keeps no process. Core plans the // choice before the stop, so nothing starts the plugin again while it stops. func (s *Service) Disable(ctx context.Context, id string, server *LanguageSession) error { + release := s.holdRuntimeStop(id) + defer release() + if err := s.stopRuntimePreparations(ctx, id); err != nil { + return err + } _, err := s.Manager.Apply(ctx, core.PluginDisable, id, func() error { return s.stopPlugin(ctx, id, server) }) return err } @@ -42,14 +54,31 @@ func (s *Service) Disable(ctx context.Context, id string, server *LanguageSessio // off (pluginmanager.Displaced): its choice is already recorded, so only the // programs remain. server is its language server session, or nil. func (s *Service) StopDisplaced(ctx context.Context, id string, server *LanguageSession) error { + release := s.holdRuntimeStop(id) + defer release() return s.stopPlugin(ctx, id, server) } -// stopPlugin stops a plugin's language server session and its backend, and -// returns once both ended or gave up. +// stopPlugin first cancels and awaits preparation/launch work, then stops all +// sessions it could have published before allowing package or state removal. func (s *Service) stopPlugin(ctx context.Context, id string, server *LanguageSession) error { + preparationErr := s.stopRuntimePreparations(ctx, id) stopBackend := s.DetachBackend(id) - err := s.StopLanguageServer(ctx, server) + sessions := make(map[*LanguageSession]struct{}) + if server != nil { + sessions[server] = struct{}{} + } + s.lsMu.Lock() + for _, session := range s.lsSessions { + if session.PluginID == id { + sessions[session] = struct{}{} + } + } + s.lsMu.Unlock() + failures := []error{preparationErr} + for session := range sessions { + failures = append(failures, s.StopLanguageServer(ctx, session)) + } stopBackend() - return err + return errors.Join(failures...) } diff --git a/desktop/internal/pluginservice/pluginservice.go b/desktop/internal/pluginservice/pluginservice.go index e3d45359d..76c8f5cbe 100644 --- a/desktop/internal/pluginservice/pluginservice.go +++ b/desktop/internal/pluginservice/pluginservice.go @@ -16,9 +16,11 @@ import ( "fmt" "path/filepath" "sync" + "sync/atomic" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/credentials" + "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginbackend" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" "github.com/1lck/Lithe-IDEA/desktop/internal/plugininstall" @@ -111,6 +113,15 @@ type Service struct { // LanguageTool resolves an optional installation for a backend-resolved // language server. A nil installation means the tool is unavailable. LanguageTool func(context.Context, string, string) (*core.ToolchainSelection, error) + // RuntimeIssue records a damaged cache being repaired or a native cleanup failure. + // Production always wires the owning log boundary before preparing any runtime. + RuntimeIssue func(context.Context, error) + // RuntimeDownloader is the application's HTTPS transport for pinned dependency archives. + RuntimeDownloader *marketplace.ArchiveDownloader + runtimeLanguage atomic.Pointer[string] + // runtimeBlocked closes preparation admission after disable/uninstall. The + // cross-window runtimePreparationCoordinator guards it and active preparations. + runtimeBlocked map[string]bool // LogDirectory gives the ${logDir} of a process started for a plugin: the current log // session's plugins//files directory, created by the window's log store. An empty // answer, or a nil LogDirectory, means there is no local log store; the process then gets @@ -170,19 +181,20 @@ func open(kernel Kernel, preferences *store.Store, root string, first bool) (*Se leftovers, _ = ledger.Leftovers() } service := &Service{ - startupLeftovers: leftovers, - Root: root, - Manager: pluginmanager.New(kernel, root, approvals, state), - Installer: plugininstall.New(kernel, NewReviewer(kernel), approvals, pluginhost.Declared()), - Backend: pluginbackend.New(kernel, hostServices), - Commands: &pluginhost.CommandStore{State: filepath.Join(root, pluginpkg.StateDirectory)}, - Settings: pluginsettings.New(kernel, preferences.Dir()), - HostServices: hostServices, - Credentials: credentials.Default(), - kernel: kernel, - resources: newHostResources(), - ledger: ledger, - messages: newMessageLimiter(), + startupLeftovers: leftovers, + Root: root, + Manager: pluginmanager.New(kernel, root, approvals, state), + Installer: plugininstall.New(kernel, NewReviewer(kernel), approvals, pluginhost.Declared()), + Backend: pluginbackend.New(kernel, hostServices), + Commands: &pluginhost.CommandStore{State: filepath.Join(root, pluginpkg.StateDirectory)}, + Settings: pluginsettings.New(kernel, preferences.Dir()), + HostServices: hostServices, + Credentials: credentials.Default(), + kernel: kernel, + resources: newHostResources(), + ledger: ledger, + messages: newMessageLimiter(), + RuntimeDownloader: marketplace.NewArchiveDownloader(nil), } service.Backend.SetCommandStore(service.Commands) service.Host = newBackendHost(service) diff --git a/desktop/internal/settingswindow/installed_view.go b/desktop/internal/settingswindow/installed_view.go index b84b8eaa2..7b4752c8d 100644 --- a/desktop/internal/settingswindow/installed_view.go +++ b/desktop/internal/settingswindow/installed_view.go @@ -950,6 +950,8 @@ func permissionDescription(language i18n.Language, permission string) string { return i18n.Shared(language, "native.runYourTests") case "commands.install": return i18n.Shared(language, "desktop.marketplace.permissionCommandsInstall") + case "runtimes.install": + return i18n.Shared(language, "desktop.marketplace.permissionRuntimesInstall") } return "" } From 07c7c00a7c70c4cc539184c18d4dfa304603a6ad Mon Sep 17 00:00:00 2001 From: "lithe-support[bot]" <356900028+lithe-support[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:05:54 +0000 Subject: [PATCH 11/20] feat(plugins): add reviewed managed runtime support (5/7) --- .../internal/settingswindow/plugin_install.go | 45 ++++++++++++- .../settingswindow/plugin_install_test.go | 40 +++++++++++ .../settingswindow/runtime_visual_test.go | 67 +++++++++++++++++++ desktop/internal/workbench/app.go | 9 +++ 4 files changed, 158 insertions(+), 3 deletions(-) create mode 100644 desktop/internal/settingswindow/runtime_visual_test.go diff --git a/desktop/internal/settingswindow/plugin_install.go b/desktop/internal/settingswindow/plugin_install.go index 8ed0976e5..fe6758222 100644 --- a/desktop/internal/settingswindow/plugin_install.go +++ b/desktop/internal/settingswindow/plugin_install.go @@ -13,6 +13,7 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginruntime" "github.com/1lck/Lithe-IDEA/desktop/internal/plugintrust" "github.com/vivaui/viva/ui" ) @@ -23,6 +24,8 @@ type PluginInstallFeedback struct { // Progress and Preparing publish transport progress and the local I/O stage. Progress func(marketplace.ArchiveProgress) Preparing func() + // RuntimeProgress keeps dependency preparation inside the installation's cancellable flow. + RuntimeProgress func(pluginruntime.Progress) // Review accepts a verified reusable approval, or publishes the complete // review and waits for the user's decision. Review func(version string, review plugintrust.Review, reused bool) bool @@ -41,6 +44,7 @@ type pluginInstallReview struct { type pluginInstallProgress struct { marketplace.ArchiveProgress preparing bool + runtime *pluginruntime.Progress } type pluginInstallFailure struct{ err error } @@ -101,6 +105,10 @@ func (w *window) startPluginInstall(name string, fromMarketplace bool) PluginIns dialog.progress.Store(&pluginInstallProgress{preparing: true}) w.inv.Invalidate() }, + RuntimeProgress: func(progress pluginruntime.Progress) { + dialog.progress.Store(&pluginInstallProgress{runtime: &progress}) + w.inv.Invalidate() + }, Review: func(version string, review plugintrust.Review, reused bool) bool { if ctx.Err() != nil { return false @@ -161,6 +169,8 @@ func (w *window) pluginInstallModal(c ui.C) { default: } outcome := pluginInstallOutcome(dialog.outcome.Load()) + progress := dialog.progress.Load() + preparingRuntime := progress != nil && progress.runtime != nil review := dialog.review.Load() description := dialog.name @@ -195,6 +205,9 @@ func (w *window) pluginInstallModal(c ui.C) { ui.Wrap(c, i18n.Shared(language, "desktop.marketplace.downloadPrompt")) case outcome == pluginInstallFailed: ui.Wrap(c, pluginInstallFailureText(language, dialog.failure.Load())).Color(w.pal.danger) + if preparingRuntime { + ui.Wrap(c, i18n.Shared(language, "desktop.marketplace.runtimeFailureHelp")) + } case review != nil && !committing: ui.Wrap(c, i18n.Shared(language, "desktop.marketplace.reviewConsent")) shown := *review @@ -210,10 +223,15 @@ func (w *window) pluginInstallModal(c ui.C) { pluginInstallReviewBody(c, language, &dialog.details, &shown) default: label := i18n.Shared(language, "native.loading") - progress := dialog.progress.Load() determinate := false var fraction float32 switch { + case preparingRuntime: + label = RuntimeProgressText(language, *progress.runtime) + if progress.runtime.Phase == "downloading" && progress.runtime.Total > 0 { + determinate = true + fraction = float32(progress.runtime.Received) / float32(progress.runtime.Total) + } case committing: label = i18n.Shared(language, "settings.general.installing") case progress != nil && progress.preparing: @@ -252,13 +270,13 @@ func (w *window) pluginInstallModal(c ui.C) { retried = ui.Button(c, i18n.Shared(language, "ui.retry")).Disabled(dialog.retry == nil).Clicked() return } - if committing { + if committing && !preparingRuntime { return } cancelled = ui.Button(c, i18n.Shared(language, "desktop.marketplace.cancel")).Outline().Clicked() if dialog.download != nil { downloadConfirmed = ui.Button(c, i18n.Shared(language, "native.download")).AutoFocus().Clicked() - } else if review != nil { + } else if review != nil && !committing { confirmed = ui.Button(c, i18n.Shared(language, "desktop.marketplace.confirmInstall")).AutoFocus().Clicked() } }) @@ -286,6 +304,27 @@ func (w *window) pluginInstallModal(c ui.C) { } } +// RuntimeProgressText formats preparation progress for installation and startup UI. +func RuntimeProgressText(language i18n.Language, progress pluginruntime.Progress) string { + switch progress.Phase { + case "downloading": + if progress.Total <= 0 { + return i18n.SharedFormat(language, "desktop.marketplace.runtimeReceived", map[string]string{"dependency": progress.ID, "received": fmt.Sprintf("%.1f", float64(progress.Received)/(1<<20))}) + } + return i18n.SharedFormat(language, "desktop.marketplace.runtimeDownloading", map[string]string{"dependency": progress.ID, "received": fmt.Sprintf("%.1f", float64(progress.Received)/(1<<20)), "total": fmt.Sprintf("%.1f", float64(progress.Total)/(1<<20))}) + case "extracting": + return i18n.SharedFormat(language, "desktop.marketplace.runtimeExtracting", map[string]string{"dependency": progress.ID}) + case "verifying": + return i18n.SharedFormat(language, "desktop.marketplace.runtimeVerifying", map[string]string{"dependency": progress.ID}) + case "repairing": + return i18n.SharedFormat(language, "desktop.marketplace.runtimeRepairing", map[string]string{"dependency": progress.ID}) + case "ready": + return i18n.SharedFormat(language, "desktop.marketplace.runtimeReady", map[string]string{"dependency": progress.ID}) + default: + return i18n.SharedFormat(language, "desktop.marketplace.runtimeChecking", map[string]string{"dependency": progress.ID}) + } +} + func pluginInstallReviewBody(c ui.C, language i18n.Language, details *ui.ListState, review *pluginInstallReview) { ui.Column(c).FillWidth().Gap(8).Children(func() { permissions := i18n.Shared(language, "desktop.marketplace.reviewPermissions") diff --git a/desktop/internal/settingswindow/plugin_install_test.go b/desktop/internal/settingswindow/plugin_install_test.go index f51372f51..34c207a2a 100644 --- a/desktop/internal/settingswindow/plugin_install_test.go +++ b/desktop/internal/settingswindow/plugin_install_test.go @@ -12,6 +12,7 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginruntime" "github.com/1lck/Lithe-IDEA/desktop/internal/plugintrust" "github.com/vivaui/viva/gfx" ) @@ -269,6 +270,45 @@ func TestPluginInstallShowsTransferBytesAndLocalVerification(t *testing.T) { } } +func TestRuntimePreparationRemainsCancellableAfterApproval(t *testing.T) { + w := newWindow(NewController(Options{}), Values{}) + feedback := w.startPluginInstall("Example Support", true) + if !feedback.Review("2.0.0", plugintrust.Review{}, true) { + t.Fatal("a reusable approval was refused") + } + progress := pluginruntime.Progress{ID: "fixture-engine", Phase: "downloading", Received: 12 << 20, Total: 251 << 20} + feedback.RuntimeProgress(progress) + d := openWindow(t, w) + if !d.text(RuntimeProgressText(i18n.English, progress)) { + t.Fatal("dependency transfer was hidden by the installing state") + } + d.click(i18n.Shared(i18n.English, "desktop.marketplace.cancel")) + select { + case <-feedback.Context.Done(): + default: + t.Fatal("cancelling an approved dependency download did not cancel its worker") + } +} + +func TestRuntimeFailureExplainsPreservedInstallationAndOffersRetry(t *testing.T) { + w := newWindow(NewController(Options{}), Values{}) + feedback := w.startPluginInstall("Example Support", true) + feedback.Review("2.0.0", plugintrust.Review{}, true) + feedback.RuntimeProgress(pluginruntime.Progress{ID: "fixture-engine", Phase: "repairing"}) + retried := false + w.install.retry = func() { retried = true } + feedback.Failure(errors.New("offline fixture")) + feedback.Finish(true) + d := openWindow(t, w) + if !d.showsHelp(i18n.Shared(i18n.English, "desktop.marketplace.runtimeFailureHelp")) { + t.Fatal("failure omitted the retained environment and retry guidance") + } + d.click(i18n.Shared(i18n.English, "ui.retry")) + if !retried { + t.Fatal("retry action was lost after dependency failure") + } +} + func TestPluginInstallReviewScrollsLongDetails(t *testing.T) { w := newWindow(NewController(Options{}), Values{}) w.startPluginInstall("Example Support", false) diff --git a/desktop/internal/settingswindow/runtime_visual_test.go b/desktop/internal/settingswindow/runtime_visual_test.go new file mode 100644 index 000000000..ae9a2d9ba --- /dev/null +++ b/desktop/internal/settingswindow/runtime_visual_test.go @@ -0,0 +1,67 @@ +//go:build vivahead && lithevisual + +package settingswindow + +import ( + "context" + "errors" + "os" + "path/filepath" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginruntime" + "github.com/1lck/Lithe-IDEA/desktop/internal/plugintrust" + "github.com/vivaui/viva/headless" +) + +// TestVisualManagedRuntimeInstall captures the actual production modal using inert dependency +// facts. It exercises every changed user-visible state without network or a concrete plugin. +func TestVisualManagedRuntimeInstall(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR to capture runtime installation") + } + if err := os.MkdirAll(out, 0o755); err != nil { + t.Fatal(err) + } + for _, language := range []i18n.Language{i18n.English, i18n.Chinese} { + for _, theme := range []string{"dark", "light"} { + for _, phase := range []string{"checking", "downloading", "repairing", "failed"} { + t.Run(language.Code()+"/"+theme+"/"+phase, func(t *testing.T) { + w := newWindow(NewController(Options{ + Text: func() *i18n.Messages { return i18n.For(language) }, Language: func() i18n.Language { return language }, + SystemLanguage: language, SystemDark: func() bool { return theme == "dark" }, + Marketplace: func(context.Context) (marketplace.Snapshot, error) { return marketplace.Snapshot{}, nil }, + }), Values{Theme: theme, Language: language.Code()}) + w.sess.page = pagePlugins + feedback := w.startPluginInstall("Example Support", true) + t.Cleanup(w.dismissPluginInstall) + feedback.Review("2.0.0", plugintrust.Review{}, true) + feedback.RuntimeProgress(pluginruntime.Progress{ID: "engine", Phase: phase, Received: 48 << 20, Total: 192 << 20}) + if phase == "failed" { + w.install.retry = func() {} + feedback.Failure(errors.New("offline fixture")) + feedback.Finish(true) + } + session, err := headless.Open(w.config(), nil, headless.Options{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + driver := &windowDriver{t: t, w: w, driver: session.Driver()} + driver.until("the runtime installation modal", func() bool { return driver.text("Example Support") }) + // Complete the modal's fade using the deterministic frame clock. + if err := session.Advance(time.Second); err != nil { + t.Fatal(err) + } + if err := session.Screenshot(filepath.Join(out, "runtime-"+phase+"-"+theme+"-"+language.Code()+".png")); err != nil { + t.Fatal(err) + } + }) + } + } + } +} diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index f7a509526..9a4ec8dd2 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -667,6 +667,10 @@ type App struct { pluginServerLanguages map[string]string // pluginServerStarting marks a language whose first start is in flight. pluginServerStarting map[string]bool + // Preparations own cancellable starts until a real server takes over. + pluginServerPreparations map[string]*pluginServerPreparation + pluginServerRevision uint64 + pluginServerChanges map[string]uint64 // pluginServerSuppressed marks plugins the user disabled or uninstalled while // a start was in flight, so the finished start is disposed instead of // registering a server the plugin no longer owns. @@ -940,6 +944,8 @@ func (a *App) openPlugins(options Options) { service.LanguageTool = a.resolveLanguageTool service.LogDirectory = a.pluginLogDirectory service.RecordFailed = a.pluginOperationRecordFailed + service.RuntimeIssue = a.recordPluginRuntimeIssue + service.SetRuntimeLanguage(a.language().Code()) if err := service.AttachWorkbench(pluginWorkbench{app: a}); err != nil { a.operationFailed("plugin_host_services", err) } @@ -1265,6 +1271,9 @@ func (a *App) setLanguage(code string) { a.settings.Language = code a.text = i18n.For(a.language()) a.shared.text.Store(a.text) + if a.plugins != nil { + a.plugins.SetRuntimeLanguage(a.language().Code()) + } if a.settingsWindow != nil { a.settingsWindow.Invalidate() } From e0afb29ea9c4783e4d7f65e5eb31be303e1cc0b0 Mon Sep 17 00:00:00 2001 From: "lithe-support[bot]" <356900028+lithe-support[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:06:02 +0000 Subject: [PATCH 12/20] feat(plugins): add reviewed managed runtime support (6/7) --- desktop/internal/workbench/lsp_status.go | 53 ++++++++- desktop/internal/workbench/plugin_programs.go | 6 + desktop/internal/workbench/pluginbackends.go | 112 ++++++++++++++++-- desktop/internal/workbench/plugins.go | 34 +++++- .../workbench/runtime_preparation_test.go | 94 +++++++++++++++ 5 files changed, 286 insertions(+), 13 deletions(-) create mode 100644 desktop/internal/workbench/runtime_preparation_test.go diff --git a/desktop/internal/workbench/lsp_status.go b/desktop/internal/workbench/lsp_status.go index 00bc45cdf..2a5c4e6c1 100644 --- a/desktop/internal/workbench/lsp_status.go +++ b/desktop/internal/workbench/lsp_status.go @@ -8,6 +8,7 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/icons" + "github.com/1lck/Lithe-IDEA/desktop/internal/settingswindow" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) @@ -200,6 +201,9 @@ func (a *App) lspStatusText() string { if server := a.lspStatusServer(); server != nil { return a.lspPhaseText(server) } + if a.lspStatusPreparation() != nil { + return i18n.Shared(a.language(), "desktop.status.lspStarting") + } if failed := a.lspStatusFailedServer(); failed != nil { return i18n.Shared(a.language(), "desktop.status.lspFailed") } @@ -262,6 +266,9 @@ func lspPhaseIcon(server *pluginServer) gfx.Icon { func (a *App) lspStatusColor() gfx.Color { server := a.lspStatusServer() if server == nil { + if a.lspStatusPreparation() != nil { + return a.colors.Warning + } if a.lspStatusFailedServer() != nil { return a.theme.Danger } @@ -278,6 +285,38 @@ func (a *App) lspStatusColor() gfx.Color { return a.colors.Warning } +func (a *App) lspStatusPreparation() *pluginServerPreparation { + if p := a.project; p != nil { + if d := p.selectedDocument(p.docs.group); d != nil { + a.pluginServerMu.Lock() + preparation := a.pluginServerPreparations[d.languageID] + a.pluginServerMu.Unlock() + if preparation != nil && preparation.project == p { + return preparation + } + } + } + return nil +} + +type lspPreparation struct { + languageID string + attempt *pluginServerPreparation +} + +func (a *App) lspPreparations() []lspPreparation { + a.pluginServerMu.Lock() + defer a.pluginServerMu.Unlock() + var preparations []lspPreparation + for languageID, attempt := range a.pluginServerPreparations { + if attempt.project == a.project { + preparations = append(preparations, lspPreparation{languageID, attempt}) + } + } + sort.Slice(preparations, func(i, j int) bool { return preparations[i].languageID < preparations[j].languageID }) + return preparations +} + // lspServers lists the language servers the window runs, by plugin. func (a *App) lspServers() []*pluginServer { a.pluginServerMu.Lock() @@ -365,14 +404,26 @@ func (a *App) lspStatusMenu(c ui.C, anchor ui.Box) { viewLogs := i18n.Shared(language, "native.inline.viewLogs") servers := a.lspServers() failed := a.lspFailedServers() + preparations := a.lspPreparations() failedText := i18n.Shared(language, "desktop.status.lspFailed") ui.Menu(c, anchor, &v.menu, func(menu *ui.MenuItems) { menu.Above() menu.WidthRange(240, 380) menu.Label(i18n.Shared(language, "native.languageServices")) - if len(servers) == 0 && len(failed) == 0 { + if len(servers) == 0 && len(failed) == 0 && len(preparations) == 0 { menu.Item(i18n.Shared(language, "native.noRegisteredLanguageServers")).Disabled(true) } + for _, preparation := range preparations { + description := i18n.Shared(language, "desktop.status.lspStarting") + if progress := preparation.attempt.progress.Load(); progress != nil && progress.Phase != "ready" { + description = settingswindow.RuntimeProgressText(language, *progress) + } + menu.Sub(preparation.languageID, func(sub *ui.MenuItems) { + if sub.Item(i18n.Shared(language, "desktop.marketplace.cancel")).Icon(icons.Square).Clicked() { + c.After(func() { preparation.attempt.stop() }) + } + }).Icon(icons.LoaderCircle).Description(description) + } for _, server := range servers { id := server.session.PluginID description := a.lspPhaseText(server) diff --git a/desktop/internal/workbench/plugin_programs.go b/desktop/internal/workbench/plugin_programs.go index 7e53500ed..761a3be6e 100644 --- a/desktop/internal/workbench/plugin_programs.go +++ b/desktop/internal/workbench/plugin_programs.go @@ -196,6 +196,12 @@ func (a *App) detachPluginPrograms(id string) func(context.Context) error { // explicit enable. The old starts were awaited before the package changed. func (a *App) allowPluginPrograms(id string) { for _, tab := range a.everyTab() { + if tab.plugins != nil { + if err := tab.plugins.AllowRuntimePreparation(id); err != nil { + tab.operationFailed("plugin_enable", err) + continue + } + } tab.pluginServerMu.Lock() delete(tab.pluginServerSuppressed, id) tab.pluginServerMu.Unlock() diff --git a/desktop/internal/workbench/pluginbackends.go b/desktop/internal/workbench/pluginbackends.go index b72260c78..3fbfc79b9 100644 --- a/desktop/internal/workbench/pluginbackends.go +++ b/desktop/internal/workbench/pluginbackends.go @@ -2,6 +2,7 @@ package workbench import ( "context" + "errors" "strings" "sync" "sync/atomic" @@ -11,9 +12,27 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginbackend" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginruntime" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" ) +// pluginServerPreparation owns one start, including an optional runtime repair. +// Progress is written by the worker and read by the status bar; identity and +// cancellation remain protected by pluginServerMu. +type pluginServerPreparation struct { + project *project + cancel context.CancelFunc + progress atomic.Pointer[pluginruntime.Progress] + cancelled atomic.Bool + pluginID string + revision uint64 +} + +func (p *pluginServerPreparation) stop() { + p.cancelled.Store(true) + p.cancel() +} + const ( // pluginServerStartTimeout bounds resolving and launching one language server. pluginServerStartTimeout = 2 * time.Minute @@ -179,33 +198,86 @@ func (a *App) startPluginServer(languageID string) { return } a.pluginServerStarting[languageID] = true + if a.pluginServerPreparations == nil { + a.pluginServerPreparations = make(map[string]*pluginServerPreparation) + } + p := a.project + parent := context.Background() + if p != nil && p.ctx != nil { + parent = p.ctx + } + ctx, cancel := context.WithCancel(a.operationContext(parent)) + preparation := &pluginServerPreparation{project: p, cancel: cancel, revision: a.pluginServerRevision} + a.pluginServerPreparations[languageID] = preparation a.pluginServerMu.Unlock() request := a.pluginBackendRequest() - p := a.project - a.background(nil, pluginServerStartTimeout, func(ctx context.Context) func(*App) { + request.RuntimeProgress = func(progress pluginruntime.Progress) { + preparation.progress.Store(&progress) + a.invalidator.Invalidate() + } + // This task must return even after a project change to dispose a late session. + // The preparation's context is nevertheless canceled with its project/window. + a.background(nil, 0, func(context.Context) func(*App) { + defer cancel() if request.WorkingDirectory != "" { uri, uriErr := a.kernel.PluginDocumentURI(ctx, request.WorkingDirectory, "auto") if uriErr != nil { - return func(a *App) { a.finishPluginServerStart(p, languageID, "", "", nil, uriErr) } + return func(a *App) { a.finishPluginServerPreparation(preparation, languageID, "", "", nil, uriErr) } } request.RootURI = uri } entries, err := a.plugins.Manager.Installed() if err != nil { - return func(a *App) { a.finishPluginServerStart(p, languageID, "", "", nil, err) } + return func(a *App) { a.finishPluginServerPreparation(preparation, languageID, "", "", nil, err) } } - session, err := a.plugins.StartLanguageServer(ctx, entries, languageID, request) var failedPluginID, failedVersion string - if err != nil { - if entry, ok, _ := a.plugins.LanguageServerProvider(ctx, entries, languageID); ok { - failedPluginID = entry.Installed.ID - failedVersion = entry.Installed.Version + if entry, ok, _ := a.plugins.LanguageServerProvider(ctx, entries, languageID); ok { + failedPluginID, failedVersion = entry.Installed.ID, entry.Installed.Version + a.pluginServerMu.Lock() + preparation.pluginID = failedPluginID + if a.pluginServerSuppressed[failedPluginID] || a.pluginServerChanges[failedPluginID] > preparation.revision { + cancel() } + a.pluginServerMu.Unlock() + } + session, err := a.plugins.StartLanguageServer(ctx, entries, languageID, request) + return func(a *App) { + a.finishPluginServerPreparation(preparation, languageID, failedPluginID, failedVersion, session, err) } - return func(a *App) { a.finishPluginServerStart(p, languageID, failedPluginID, failedVersion, session, err) } }) } +func (a *App) finishPluginServerPreparation(preparation *pluginServerPreparation, languageID, pluginID, version string, session *pluginservice.LanguageSession, err error) { + a.pluginServerMu.Lock() + current := a.pluginServerPreparations[languageID] == preparation + owner := pluginID + if session != nil { + owner = session.PluginID + } + changed := a.pluginServerChanges[owner] > preparation.revision + if current { + delete(a.pluginServerPreparations, languageID) + } + a.pluginServerMu.Unlock() + if !current || changed { + // A result from the previous project cannot clear a newer start's marker. + a.stopPluginSession(session) + if current { + a.pluginServerMu.Lock() + delete(a.pluginServerStarting, languageID) + a.pluginServerMu.Unlock() + } + return + } + if preparation.cancelled.Load() && err == nil { + // Cancel may be clicked after the worker finishes but before its queued + // result reaches this window. It must still dispose that late session. + a.stopPluginSession(session) + session, err = nil, context.Canceled + } + a.finishPluginServerStart(preparation.project, languageID, pluginID, version, session, err) +} + // finishPluginServerStart takes the started session back on the window thread and // runs its serve loop. func (a *App) finishPluginServerStart(p *project, languageID, failedPluginID, failedVersion string, session *pluginservice.LanguageSession, err error) { @@ -217,6 +289,10 @@ func (a *App) finishPluginServerStart(p *project, languageID, failedPluginID, fa if a.project != p || suppressed { return } + if errors.Is(err, context.Canceled) { + a.recordPluginServerFailure(p, languageID, failedPluginID, failedVersion, errors.New(i18n.Shared(a.language(), "desktop.lsp.preparationCancelled")), nil, 0) + return + } a.operationFailed("plugin_server_start", err) a.recordPluginServerFailure(p, languageID, failedPluginID, failedVersion, err, nil, 0) a.notifyPluginServerFailure(p, languageID, err) @@ -404,6 +480,18 @@ func (a *App) detachPluginServer(pluginID string) *pluginservice.LanguageSession } // A start that is still resolving must not register this plugin afterwards. a.pluginServerSuppressed[pluginID] = true + a.pluginServerRevision++ + if a.pluginServerChanges == nil { + a.pluginServerChanges = make(map[string]uint64) + } + a.pluginServerChanges[pluginID] = a.pluginServerRevision + for languageID, preparation := range a.pluginServerPreparations { + if preparation.pluginID == pluginID { + preparation.stop() + delete(a.pluginServerPreparations, languageID) + delete(a.pluginServerStarting, languageID) + } + } if server, ok := a.pluginServers[pluginID]; ok { delete(a.pluginServers, pluginID) for languageID, provider := range a.pluginServerLanguages { @@ -461,6 +549,10 @@ func (a *App) closePluginBackends() { func (a *App) stopAllPluginServers() { a.closePluginBackends() a.pluginServerMu.Lock() + for _, preparation := range a.pluginServerPreparations { + preparation.stop() + } + a.pluginServerPreparations = nil for id := range a.pluginServerRestarting { delete(a.pluginServerSuppressed, id) } diff --git a/desktop/internal/workbench/plugins.go b/desktop/internal/workbench/plugins.go index 689d6968e..44be1fad6 100644 --- a/desktop/internal/workbench/plugins.go +++ b/desktop/internal/workbench/plugins.go @@ -170,7 +170,15 @@ func (a *App) preparePluginInstall(feedback settingswindow.PluginInstallFeedback return nil } commitCtx, cancelCommit := context.WithTimeout(core.WithOrigin(context.Background(), origin), pluginInstallTimeout) + if pluginservice.HasManagedRuntimes(plan.Manifest) { + cancelCommit() + // Large dependencies use the downloader's inactivity deadline. Cancellation + // remains available until the verified environment is ready to publish. + commitCtx, cancelCommit = context.WithCancel(core.WithOrigin(feedback.Context, origin)) + } defer cancelCommit() + stop := context.AfterFunc(work, cancelCommit) + defer stop() return a.commitPluginInstall(commitCtx, plan, feedback) }) } @@ -193,7 +201,21 @@ func (a *App) recordPluginInstallCleanup(ctx context.Context, err error) { } func (a *App) commitPluginInstall(ctx context.Context, plan plugininstall.Plan, feedback settingswindow.PluginInstallFeedback) func(*App) { - _, err := a.plugins.Installer.Commit(plan) + work, finish, err := a.plugins.BeginRuntimeInstallation(ctx, plan.ID) + if err == nil { + defer finish() + ctx = work + _, err = a.plugins.EnsureRuntimes(ctx, plan.Manifest, plan.Staging, plan.ID, plan.Version, true, feedback.RuntimeProgress) + } + if err == nil { + err = ctx.Err() + } + if err == nil { + if feedback.Preparing != nil { + feedback.Preparing() + } + _, err = a.plugins.Installer.Commit(plan) + } var approval *plugininstall.ApprovalError var enableErr error var displaced displacement @@ -221,9 +243,10 @@ func (a *App) commitPluginInstall(ctx context.Context, plan plugininstall.Plan, // user is not told the installation failed. The next installation // of the same version asks again. a.operationFailed("plugin_approval", err) - } else { + } else if !errors.Is(err, context.Canceled) { a.operationFailed("plugin_commit", err) } + // log-exempt: the user may cancel runtime preparation before publication. } if installed && plan.ID != "" { // The installation was just enabled, unless the user had disabled the @@ -241,6 +264,13 @@ func (a *App) commitPluginInstall(ctx context.Context, plan plugininstall.Plan, } } +// recordPluginRuntimeIssue records automatic repair and cleanup at the native I/O boundary. +func (a *App) recordPluginRuntimeIssue(ctx context.Context, err error) { + fields := core.LogErrorFields(err) + fields["stage"] = "plugin_runtime_repair" + a.emitIn(ctx, core.LevelWarn, "app.storage.maintenance_failed", fields) +} + // setPluginEnabled turns an installed plugin on or off. func (a *App) setPluginEnabled(id string, enabled bool) { if a.plugins == nil { diff --git a/desktop/internal/workbench/runtime_preparation_test.go b/desktop/internal/workbench/runtime_preparation_test.go new file mode 100644 index 000000000..6f7767305 --- /dev/null +++ b/desktop/internal/workbench/runtime_preparation_test.go @@ -0,0 +1,94 @@ +package workbench + +import ( + "context" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginruntime" + "github.com/1lck/Lithe-IDEA/desktop/internal/settingswindow" +) + +func TestClosingProjectCancelsRuntimePreparationAndIgnoresLateResult(t *testing.T) { + h := newHarness(t, &testKernel{Client: core.NewClient()}) + h.open(t.TempDir()) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + previous := &pluginServerPreparation{project: h.app.project, cancel: cancel} + h.app.pluginServerPreparations = map[string]*pluginServerPreparation{"fixture": previous} + h.app.pluginServerStarting = map[string]bool{"fixture": true} + h.app.stopAllPluginServers() + if ctx.Err() != context.Canceled || len(h.app.pluginServerPreparations) != 0 { + t.Fatal("project close left runtime preparation running") + } + next := &pluginServerPreparation{project: h.app.project, cancel: func() {}} + h.app.pluginServerPreparations = map[string]*pluginServerPreparation{"fixture": next} + h.app.pluginServerStarting = map[string]bool{"fixture": true} + h.app.finishPluginServerPreparation(previous, "fixture", "dev.example.runtime", "1", nil, context.Canceled) + if h.app.pluginServerPreparations["fixture"] != next || !h.app.pluginServerStarting["fixture"] { + t.Fatal("late result cleared the next project's preparation") + } +} + +func TestDisableInvalidatesPreparationEvenAfterReenable(t *testing.T) { + h := newHarness(t, &testKernel{Client: core.NewClient()}) + h.open(t.TempDir()) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + previous := &pluginServerPreparation{project: h.app.project, cancel: cancel, pluginID: "dev.example.runtime"} + h.app.pluginServerPreparations = map[string]*pluginServerPreparation{"fixture": previous} + h.app.pluginServerStarting = map[string]bool{"fixture": true} + h.app.detachPluginServer(previous.pluginID) + if ctx.Err() != context.Canceled || h.app.pluginServerStarting["fixture"] { + t.Fatal("disabling did not cancel and invalidate the old preparation") + } + delete(h.app.pluginServerSuppressed, previous.pluginID) + h.app.finishPluginServerPreparation(previous, "fixture", previous.pluginID, "1", nil, context.Canceled) + if len(h.app.pluginServerFailed) != 0 || len(h.app.notifications.list) != 0 { + t.Fatal("late canceled start affected the reenabled plugin") + } +} + +func TestRuntimePreparationStatusShowsProgressAndCancels(t *testing.T) { + f := newSemanticFixture(t) + a := f.h.app + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + attempt := &pluginServerPreparation{project: f.p, cancel: cancel} + progress := pluginruntime.Progress{ID: "engine", Phase: "downloading", Received: 48 << 20, Total: 192 << 20} + attempt.progress.Store(&progress) + a.pluginServers = nil + a.pluginServerLanguages = nil + a.pluginServerPreparations = map[string]*pluginServerPreparation{f.d.languageID: attempt} + a.invalidator.Invalidate() + f.h.settle() + if a.lspStatusText() != i18n.Shared(a.language(), "desktop.status.lspStarting") || a.lspStatusColor() != a.colors.Warning { + t.Fatal("runtime preparation is invisible in the status bar") + } + f.h.click(center(f.h.button(itemLSP))) + f.h.settle() + if !f.h.shows(settingswindow.RuntimeProgressText(a.language(), progress)) { + t.Fatal("server menu does not show runtime download progress") + } + f.h.clickNamed(f.d.languageID) + f.h.settle() + f.h.clickNamed(i18n.Shared(a.language(), "desktop.marketplace.cancel")) + f.h.settle() + if ctx.Err() != context.Canceled { + t.Fatal("cancel action left the runtime download running") + } +} + +func TestRuntimePreparationCancelWinsQueuedSuccessfulResult(t *testing.T) { + h := newHarness(t, &testKernel{Client: core.NewClient()}) + h.open(t.TempDir()) + attempt := &pluginServerPreparation{project: h.app.project, cancel: func() {}} + h.app.pluginServerPreparations = map[string]*pluginServerPreparation{"fixture": attempt} + h.app.pluginServerStarting = map[string]bool{"fixture": true} + attempt.stop() + h.app.finishPluginServerPreparation(attempt, "fixture", "dev.example.runtime", "1", nil, nil) + if h.app.pluginServerFailed["fixture"] == nil || h.app.pluginServerStarting["fixture"] || len(h.app.notifications.list) != 0 { + t.Fatal("queued completion ignored cancellation or produced an error toast") + } +} From d00678c0baf56fc7cda63a470f5daeeeff8754a0 Mon Sep 17 00:00:00 2001 From: "lithe-support[bot]" <356900028+lithe-support[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:06:24 +0000 Subject: [PATCH 13/20] feat(plugins): add reviewed managed runtime support (7/7) --- .../runtime_preparation_visual_test.go | 80 +++++++++++++++++++ docs/ci-builds.md | 18 +++++ scripts/desktop/build-desktop-core.sh | 2 +- 3 files changed, 99 insertions(+), 1 deletion(-) create mode 100644 desktop/internal/workbench/runtime_preparation_visual_test.go diff --git a/desktop/internal/workbench/runtime_preparation_visual_test.go b/desktop/internal/workbench/runtime_preparation_visual_test.go new file mode 100644 index 000000000..7e8678ce2 --- /dev/null +++ b/desktop/internal/workbench/runtime_preparation_visual_test.go @@ -0,0 +1,80 @@ +//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/pluginruntime" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" +) + +// TestVisualRuntimePreparationStatus captures the real status menu while a +// synthetic language service prepares a runtime, including its cancel action. +func TestVisualRuntimePreparationStatus(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{"dark", "light"} { + for _, language := range []string{"zh-Hans", "en"} { + t.Run(theme+"/"+language, func(t *testing.T) { + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, settings{Theme: themeChoice(theme), Language: language, DisableAutoSave: true}); err != nil { + t.Fatal(err) + } + root := t.TempDir() + file := filepath.Join(root, "example.fixture") + if err := os.WriteFile(file, []byte("let answer = 42;\n"), 0o600); err != nil { + t.Fatal(err) + } + var session *headless.Session + h := newHarnessWithDriver(t, Options{Kernel: &testKernel{Client: core.NewClient()}, Store: prefs, Languages: []string{language}}, func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = 1200, 760 + var err error + session, err = headless.Open(config, nil, headless.Options{}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + h.open(root) + p := h.app.project + h.app.openFile(p, file) + h.settleChain() + d := p.docs.byPath(file) + if d == nil { + t.Fatal("fixture document did not open") + } + d.languageID = "fixture" + _, cancel := context.WithCancel(p.ctx) + t.Cleanup(cancel) + preparation := &pluginServerPreparation{project: p, cancel: cancel} + preparation.progress.Store(&pluginruntime.Progress{ID: "engine", Phase: "downloading", Received: 48 << 20, Total: 192 << 20}) + h.app.pluginServerPreparations = map[string]*pluginServerPreparation{"fixture": preparation} + h.app.invalidator.Invalidate() + h.settleChain() + h.click(center(h.button(itemLSP))) + h.settleChain() + h.clickNamed("fixture") + h.settleChain() + if err := session.Advance(time.Second); err != nil { + t.Fatal(err) + } + if err := session.Screenshot(filepath.Join(out, "runtime-startup-"+theme+"-"+language+".png")); err != nil { + t.Fatal(err) + } + }) + } + } +} diff --git a/docs/ci-builds.md b/docs/ci-builds.md index c0c780bdb..0359d0070 100644 --- a/docs/ci-builds.md +++ b/docs/ci-builds.md @@ -225,6 +225,24 @@ Build Provider 的模型与依赖快照位于插件根(`pluginpkg.DefaultRoot` Provider 状态经平台 adapter 写 Application Support;插件安装目录和发行 bundle 只读, 不改变代码签名或增量更新的源基线。 +显式声明 `requires.managedRuntimes: 0` 和 `runtimes.install` 权限的插件,可以让宿主在安装提交前 +准备经过插件校验的依赖。下载来源、SHA-256、平台和目录布局属于插件清单及程序审批摘要; +宿主不保存任何特定语言的版本或下载地址。Core 选出当前平台的归档并生成依赖身份摘要, +原生下载与解压结果位于 `/.state//runtimes//`, +其中 `archive` 是校验过的归档,`install-/` 是完成校验后发布的只读一代文件, +`ready.json` 记录当前完成的一代及文件清单,`.lock` 协调跨进程写入。 +下载、解压和资格检查在私有暂存区完成;取消或失败删除本次未发布的文件,已发布的一代仍可供旧进程读取。 +正常启动检查文件清单和插件要求;安装、升级以及修复同时核对内容哈希。 + +该目录由插件身份拥有,不含插件版本号。插件代码升级而依赖声明不变时复用同一目录和归档; +依赖、平台或校验值变化时使用另一身份,不覆盖旧文件。完整且符合插件要求的外部安装可以直接复用, +宿主只下载缺失项;外部目录不属于宿主,不在卸载时删除。插件禁用会取消准备任务并停止进程, +保留已完成依赖;卸载先等待准备任务和进程退出,再随整个插件状态删除受管归档与各代文件。 +这些目录是用户运行时状态,不是工作树构建输入,不跨工作树复制或共享,不写插件包、app bundle +或 Windows 安装目录。归档压缩大小上限为 512 MiB,展开总量 4 GiB、条目数 50,000,完成记录上限 32 MiB; +路径和链接不能逃出解压根。相关边界见 +[受管插件运行时](../.agents/notes/implemented/architecture/2026-11-18-managed-plugin-runtimes.md)。 + 插件网页的宿主持久状态(Viva 的 `pluginservice.SetPageState`)写到每用户插件根目录 (`pluginpkg.DefaultRoot`)下的 `/.state//pages/workspaces//.json`, diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 66945c5e7..6ae408e29 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -245,7 +245,7 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # the contract, plugin guides, reference and SDKs live only in shared/plugins; on top of #16 (reported Git queries folded in the console), # #15 (git.write cherryPick, revert and reset fields), #14 (word-level changed ranges of diff # rows), #13, #8, #7, #6 and #4. -PINNED_CORE_REVISION="e56dbb65090a96cb24a53bbbbeffe424bed3ac1d" +PINNED_CORE_REVISION="c08330dcc73d7b3e3b7b8f735ad441e0c97e5133" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in From 3d9e9b13d8781efee993db07f574bcf2d6818076 Mon Sep 17 00:00:00 2001 From: "lithe-support[bot]" <356900028+lithe-support[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:12:21 +0000 Subject: [PATCH 14/20] fix(plugins): bind only validated external runtime identities --- .../pluginservice/context_roots_test.go | 47 +++ desktop/internal/pluginservice/contexts.go | 52 +++ .../pluginservice/runtime_trust_test.go | 336 +++++++++++++++ desktop/internal/pluginservice/runtimes.go | 399 ++++++++++++++++++ 4 files changed, 834 insertions(+) create mode 100644 desktop/internal/pluginservice/context_roots_test.go create mode 100644 desktop/internal/pluginservice/runtime_trust_test.go create mode 100644 desktop/internal/pluginservice/runtimes.go diff --git a/desktop/internal/pluginservice/context_roots_test.go b/desktop/internal/pluginservice/context_roots_test.go new file mode 100644 index 000000000..ee2a5ef58 --- /dev/null +++ b/desktop/internal/pluginservice/context_roots_test.go @@ -0,0 +1,47 @@ +package pluginservice + +import ( + "path/filepath" + "reflect" + "testing" +) + +func TestWorkspaceRootsTrackEachOpenContext(t *testing.T) { + state := t.TempDir() + first, second := newWorkspaceContexts(state), newWorkspaceContexts(state) + t.Cleanup(first.CloseAll) + t.Cleanup(second.CloseAll) + alpha, beta := filepath.Join(t.TempDir(), "alpha"), filepath.Join(t.TempDir(), "beta") + first.Open(alpha) + first.Open(alpha) // Opening the same context twice retains one owner. + second.Open(alpha) + second.Open(beta) + if got := first.workspaceRoots(); len(got) != 2 { + t.Fatalf("shared open roots = %v", got) + } + if _, local := first.List(); len(local) != 1 || local[0].Path != alpha { + t.Fatalf("shared runtime facts changed plugin context visibility: %v", local) + } + first.Close(alpha) + first.Close(alpha) + if got := first.workspaceRoots(); len(got) != 2 { + t.Fatalf("closing one owner removed another workbench's roots: %v", got) + } + snapshot := first.workspaceRoots() + second.CloseAll() + second.CloseAll() + if got := first.workspaceRoots(); len(got) != 0 { + t.Fatalf("closed contexts retained roots: %v", got) + } + if len(snapshot) != 2 { + t.Fatalf("closing contexts mutated an in-flight snapshot: %v", snapshot) + } + first.Open(beta) + if got := second.workspaceRoots(); !reflect.DeepEqual(got, []string{beta}) { + t.Fatalf("reopened roots = %v", got) + } + independent := newWorkspaceContexts(t.TempDir()) + if got := independent.workspaceRoots(); len(got) != 0 { + t.Fatalf("roots crossed independent plugin state directories: %v", got) + } +} diff --git a/desktop/internal/pluginservice/contexts.go b/desktop/internal/pluginservice/contexts.go index 88a0cd5c6..b14720348 100644 --- a/desktop/internal/pluginservice/contexts.go +++ b/desktop/internal/pluginservice/contexts.go @@ -49,6 +49,55 @@ type WorkspaceContexts struct { onClosed func(contextID string) } +// Contexts remain private to a workbench. Native runtime checks only need the +// paths currently open in any workbench sharing this plugin state directory. +// Counts follow Open/Close, retain no Service, and disappear with the last owner. +// Writers hold c.mu before this lock; snapshots take only this lock. +var openedWorkspaceRoots = struct { + sync.Mutex + byState map[string]map[string]int +}{byState: make(map[string]map[string]int)} + +func (c *WorkspaceContexts) retainRoot(path string) { + openedWorkspaceRoots.Lock() + defer openedWorkspaceRoots.Unlock() + key := filepath.Clean(c.stateRoot) + if openedWorkspaceRoots.byState[key] == nil { + openedWorkspaceRoots.byState[key] = make(map[string]int) + } + openedWorkspaceRoots.byState[key][path]++ +} + +func (c *WorkspaceContexts) releaseRoot(path string) { + openedWorkspaceRoots.Lock() + defer openedWorkspaceRoots.Unlock() + key := filepath.Clean(c.stateRoot) + roots := openedWorkspaceRoots.byState[key] + roots[path]-- + if roots[path] == 0 { + delete(roots, path) + } + if len(roots) == 0 { + delete(openedWorkspaceRoots.byState, key) + } +} + +// workspaceRoots takes one immutable native path snapshot for an entire runtime +// preparation, including its discovery probes and final tool validation. +func (c *WorkspaceContexts) workspaceRoots() []string { + if c == nil { + return nil + } + openedWorkspaceRoots.Lock() + var paths []string + for path := range openedWorkspaceRoots.byState[filepath.Clean(c.stateRoot)] { + paths = append(paths, path) + } + openedWorkspaceRoots.Unlock() + sort.Strings(paths) + return paths +} + // newWorkspaceContexts loads or creates the host secret that keys root IDs. The // secret is stored beside the plugin state, never in a package or the app bundle. func newWorkspaceContexts(stateRoot string) *WorkspaceContexts { @@ -104,6 +153,7 @@ func (c *WorkspaceContexts) Open(path string) WorkspaceContext { Path: path, } c.byPath[path] = created + c.retainRoot(path) c.revision++ observer := c.onChange value := *created @@ -124,6 +174,7 @@ func (c *WorkspaceContexts) Close(path string) { return } delete(c.byPath, path) + c.releaseRoot(path) c.revision++ observer, closed := c.onChange, c.onClosed id := closing.ContextID @@ -146,6 +197,7 @@ func (c *WorkspaceContexts) CloseAll() { ids := make([]string, 0, len(c.byPath)) for _, closing := range c.byPath { ids = append(ids, closing.ContextID) + c.releaseRoot(closing.Path) } c.byPath = make(map[string]*WorkspaceContext) c.revision++ diff --git a/desktop/internal/pluginservice/runtime_trust_test.go b/desktop/internal/pluginservice/runtime_trust_test.go new file mode 100644 index 000000000..046dcd58f --- /dev/null +++ b/desktop/internal/pluginservice/runtime_trust_test.go @@ -0,0 +1,336 @@ +package pluginservice + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "runtime" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" +) + +const runtimeFixtureTool = "dev.lithe.test.managed-environment:worker" + +func runtimeFixtureCommand() string { + if runtime.GOOS == "windows" { + return "managed-fixture-tool.exe" + } + return "managed-fixture-tool" +} + +// The version probe is the test binary itself, so this boundary test requires no +// installed interpreter. The child records its execution before printing a version. +func TestMain(m *testing.M) { + executable, err := os.Executable() + if err == nil && filepath.Base(executable) == runtimeFixtureCommand() && len(os.Args) == 2 && os.Args[1] == "--version" { + if err := os.WriteFile(filepath.Join(filepath.Dir(executable), "probe-ran"), []byte("ran"), 0o600); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + fmt.Println("ManagedFixture 1.0") + os.Exit(0) + } + os.Exit(m.Run()) +} + +func runtimeToolFixture(t *testing.T) (json.RawMessage, string) { + t.Helper() + manifest, _, packageRoot := runtimeFixture(t) + var value map[string]any + if err := json.Unmarshal(manifest, &value); err != nil { + t.Fatal(err) + } + value["requires"].(map[string]any)["toolDefinitions"] = 0 + value["requiresTools"] = []string{runtimeFixtureTool} + value["toolDefinitions"] = []any{map[string]any{ + "id": runtimeFixtureTool, "displayName": "Managed fixture tool", + "executableLayouts": []any{map[string]any{"path": "bin/" + runtimeFixtureCommand()}}, + "executables": []any{ + map[string]any{"id": "global", "kind": "setting", "settingID": "executable", "layer": "global"}, + map[string]any{"id": "shell", "kind": "command", "command": runtimeFixtureCommand()}, + map[string]any{"id": "installed", "kind": "toolchain", "scope": "installed"}, + }, + "version": map[string]any{"arguments": []string{"--version"}, "pattern": `ManagedFixture (\d+(?:\.\d+)*)`}, + "commands": []string{runtimeFixtureCommand()}, + "exports": []any{}, "pathPrepend": []string{}, + "launch": []string{"${executable}", "${arguments}"}, + }} + managed := value["managedRuntimes"].(map[string]any) + dependencies := managed["dependencies"].([]any)[:1] + dependency := dependencies[0].(map[string]any) + dependency["tool"] = runtimeFixtureTool + dependency["artifacts"].([]any)[0].(map[string]any)["executable"] = "bin/" + runtimeFixtureCommand() + managed["dependencies"] = dependencies + manifest, err := json.Marshal(value) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(packageRoot, "plugin.json"), manifest, 0o600); err != nil { + t.Fatal(err) + } + return manifest, packageRoot +} + +func runtimeToolHome(t *testing.T, home, packageRoot string) string { + t.Helper() + executable := filepath.Join(home, "bin", runtimeFixtureCommand()) + if err := os.MkdirAll(filepath.Dir(executable), 0o700); err != nil { + t.Fatal(err) + } + image, err := os.ReadFile(filepath.Join(packageRoot, "bin", "resolver")) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(executable, image, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(home, "payload"), []byte("usable"), 0o600); err != nil { + t.Fatal(err) + } + return executable +} + +func runtimeTrustService(t *testing.T, external string) (*Service, *runtimeResolverKernel, *store.Store) { + t.Helper() + kernel := &runtimeResolverKernel{Client: core.NewClient(), queues: make(map[string]chan core.BackendEvent), external: map[string]string{"alpha": external}} + preferences := store.At(t.TempDir()) + service, err := Open(kernel, preferences, t.TempDir()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(service.Contexts.CloseAll) + return service, kernel, preferences +} + +func TestManagedRuntimeToolsDoNotProbeOpenWorkspaces(t *testing.T) { + for _, source := range []string{"path", "global-symlink"} { + for _, owner := range []string{"current", "other-workbench"} { + t.Run(source+"/"+owner, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + manifest, packageRoot := runtimeToolFixture(t) + project := t.TempDir() + home := filepath.Join(project, "local-tool") + executable := runtimeToolHome(t, home, packageRoot) + service, kernel, preferences := runtimeTrustService(t, "") + contexts := service.Contexts + if owner == "other-workbench" { + other, err := OpenAnother(kernel, preferences, service.Root) + if err != nil { + t.Fatal(err) + } + contexts = other.Contexts + t.Cleanup(contexts.CloseAll) + } + contexts.Open(project) + t.Setenv("PATH", t.TempDir()) + if source == "path" { + t.Setenv("PATH", filepath.Dir(executable)) + } else { + alias := filepath.Join(t.TempDir(), "registered-tool") + if err := os.Symlink(home, alias); err != nil { + if runtime.GOOS == "windows" { + t.Skipf("symlinks unavailable: %v", err) + } + t.Fatal(err) + } + change, err := kernel.EditToolchainCatalog(ctx, nil, toolchain.PlatformName(runtime.GOOS), []core.ToolchainCatalogEdit{{Tool: runtimeFixtureTool, Homes: []string{alias}, DefaultHome: &alias}}) + if err != nil || change.Document == nil { + t.Fatalf("catalog fixture: %+v, %v", change, err) + } + catalog := filepath.Join(preferences.Dir(), "toolchains", "global.json") + if err := os.MkdirAll(filepath.Dir(catalog), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(catalog, []byte(*change.Document), 0o600); err != nil { + t.Fatal(err) + } + } + plan, err := kernel.PlanManagedRuntimes(ctx, manifest, core.ManagedRuntimePlatform{OS: toolchain.PlatformName(runtime.GOOS), Arch: core.PluginArchitecture()}) + if err != nil { + t.Fatal(err) + } + tools, err := service.runtimeTools(ctx, manifest, plan, service.Contexts.workspaceRoots()) + if _, probeErr := os.Stat(filepath.Join(filepath.Dir(executable), "probe-ran")); !errors.Is(probeErr, os.ErrNotExist) { + t.Errorf("workspace tool ran a version probe: %v", probeErr) + } + if tools[runtimeFixtureTool].Executable != "" { + t.Errorf("workspace executable escaped into runtime facts: %+v", tools) + } + if source == "global-symlink" { + var unavailable *toolchain.UnavailableError + if !errors.As(err, &unavailable) || !unavailable.Terminal { + t.Errorf("explicit workspace selection must fail without fallback: %v", err) + } + } else if err != nil { + t.Fatal(err) + } + }) + } + } +} + +func TestManagedRuntimeHookCannotReturnOpenWorkspaceTool(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + manifest, packageRoot := runtimeToolFixture(t) + project := t.TempDir() + home := filepath.Join(project, "hook-tool") + executable := runtimeToolHome(t, home, packageRoot) + service, kernel, preferences := runtimeTrustService(t, home) + other, err := OpenAnother(kernel, preferences, service.Root) + if err != nil { + t.Fatal(err) + } + other.Contexts.Open(project) + t.Cleanup(other.Contexts.CloseAll) + t.Setenv("PATH", t.TempDir()) + environment, err := service.EnsureRuntimes(ctx, manifest, packageRoot, "dev.lithe.test.managed-environment", "1.0.0", true, nil) + var unavailable *toolchain.UnavailableError + if !errors.As(err, &unavailable) || !unavailable.Terminal { + t.Errorf("hook returned a project executable without terminal rejection: environment=%+v error=%v", environment, err) + } + if _, probeErr := os.Stat(filepath.Join(filepath.Dir(executable), "probe-ran")); !errors.Is(probeErr, os.ErrNotExist) { + t.Errorf("hook's workspace executable ran before rejection: %v", probeErr) + } +} + +func TestManagedRuntimeBoundToolValidationIsReadOnly(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + manifest, packageRoot := runtimeToolFixture(t) + home := t.TempDir() + executable := runtimeToolHome(t, home, packageRoot) + service, _, preferences := runtimeTrustService(t, home) + project := t.TempDir() + service.Contexts.Open(project) + t.Setenv("PATH", t.TempDir()) + projectPins := filepath.Join(project, ".lithe", "toolchains.json") + catalog := filepath.Join(preferences.Dir(), "toolchains", "global.json") + sources := map[string][]byte{ + projectPins: []byte(`{"version":1,"toolchains":{"dev.lithe.test.project:compiler":{"home":"project-choice"}}}`), + catalog: []byte(`{"version":1,"tools":{}}`), + } + for path, body := range sources { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, body, 0o600); err != nil { + t.Fatal(err) + } + } + environment, err := service.EnsureRuntimes(ctx, manifest, packageRoot, "dev.lithe.test.managed-environment", "1.0.0", true, nil) + want, canonicalErr := filepath.EvalSymlinks(executable) + if err != nil || canonicalErr != nil || filepath.Clean(environment.Tools[runtimeFixtureTool].Path) != filepath.Clean(want) { + t.Fatalf("external runtime = %+v, error=%v, canonical=%v", environment, err, canonicalErr) + } + if _, err := os.Stat(filepath.Join(filepath.Dir(executable), "probe-ran")); err != nil { + t.Fatalf("external bound tool was never version-checked: %v", err) + } + for path, before := range sources { + after, err := os.ReadFile(path) + if err != nil || !bytes.Equal(before, after) { + t.Fatalf("runtime validation changed toolchain choices at %s: %v", path, err) + } + } +} + +func TestManagedRuntimeBoundExecutableMustMatchToolSelection(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + manifest, packageRoot := runtimeToolFixture(t) + home := t.TempDir() + executable := runtimeToolHome(t, home, packageRoot) + other := filepath.Join(home, "bin", "other-tool") + image, err := os.ReadFile(executable) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(other, image, 0o755); err != nil { + t.Fatal(err) + } + var value map[string]any + if err := json.Unmarshal(manifest, &value); err != nil { + t.Fatal(err) + } + dependency := value["managedRuntimes"].(map[string]any)["dependencies"].([]any)[0].(map[string]any) + dependency["artifacts"].([]any)[0].(map[string]any)["executable"] = "bin/other-tool" + manifest, err = json.Marshal(value) + if err != nil { + t.Fatal(err) + } + service, _, _ := runtimeTrustService(t, home) + t.Setenv("PATH", t.TempDir()) + _, err = service.EnsureRuntimes(ctx, manifest, packageRoot, "dev.lithe.test.managed-environment", "1.0.0", true, nil) + if !errors.Is(err, ErrRuntimeIncomplete) { + t.Fatalf("bound executable differed from the Core-selected file: %v", err) + } +} + +func TestManagedRuntimeBoundToolDoesNotRetainWorkspaceSymlink(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + manifest, packageRoot := runtimeToolFixture(t) + project, home := t.TempDir(), t.TempDir() + executable := runtimeToolHome(t, home, packageRoot) + alias := filepath.Join(t.TempDir(), "workspace") + if err := os.Symlink(project, alias); err != nil { + if runtime.GOOS == "windows" { + t.Skipf("symlinks unavailable: %v", err) + } + t.Fatal(err) + } + link := filepath.Join(alias, "tool") + if err := os.Symlink(home, link); err != nil { + t.Fatal(err) + } + service, _, _ := runtimeTrustService(t, link) + service.Contexts.Open(alias) + t.Setenv("PATH", t.TempDir()) + environment, err := service.EnsureRuntimes(ctx, manifest, packageRoot, "dev.lithe.test.managed-environment", "1.0.0", true, nil) + if err != nil { + t.Fatal(err) + } + want, err := filepath.EvalSymlinks(executable) + if err != nil { + t.Fatal(err) + } + if filepath.Clean(environment.Tools[runtimeFixtureTool].Path) != filepath.Clean(want) || filepath.Clean(environment.Facts[runtimeFixtureTool].Executable) != filepath.Clean(want) { + t.Errorf("bound runtime retained a mutable workspace alias: %+v", environment) + } + wantHome, err := filepath.EvalSymlinks(home) + if err != nil { + t.Fatal(err) + } + if filepath.Clean(environment.Runtimes["alpha"].Home) != filepath.Clean(wantHome) || filepath.Clean(environment.Facts[runtimeFixtureTool].Home) != filepath.Clean(wantHome) { + t.Errorf("runtime launch facts retained a mutable workspace home: %+v", environment) + } + otherHome := t.TempDir() + runtimeToolHome(t, otherHome, packageRoot) + if err := os.Remove(link); err != nil { + t.Fatal(err) + } + if err := os.Symlink(otherHome, link); err != nil { + t.Fatal(err) + } + approved, err := os.Stat(want) + if err != nil { + t.Fatal(err) + } + bound, err := os.Stat(environment.Tools[runtimeFixtureTool].Path) + if err != nil || !os.SameFile(approved, bound) { + t.Fatalf("changing a workspace symlink redirected the approved tool: %v", err) + } + fromHome, err := os.Stat(filepath.Join(environment.Runtimes["alpha"].Home, "bin", runtimeFixtureCommand())) + if err != nil || !os.SameFile(approved, fromHome) { + t.Fatalf("changing a workspace symlink redirected the approved runtime home: %v", err) + } +} diff --git a/desktop/internal/pluginservice/runtimes.go b/desktop/internal/pluginservice/runtimes.go new file mode 100644 index 000000000..4b45f9318 --- /dev/null +++ b/desktop/internal/pluginservice/runtimes.go @@ -0,0 +1,399 @@ +package pluginservice + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "runtime" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginbackend" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginruntime" + "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" +) + +// ErrRuntimeIncomplete reports a resolver that did not accept a fully prepared dependency set. +var ErrRuntimeIncomplete = errors.New("plugin runtime preparation did not produce a verified environment") + +type managedRuntimeKernel interface { + PlanManagedRuntimes(context.Context, json.RawMessage, core.ManagedRuntimePlatform) (core.ManagedRuntimePlan, error) + DecodeManagedRuntimeResolution(context.Context, json.RawMessage, core.ManagedRuntimePlatform, json.RawMessage) (core.ManagedRuntimeResolution, error) +} + +// RuntimeTool is a native installation fact supplied to the plugin's compatibility check. +type RuntimeTool struct { + Executable string `json:"executable"` + Home string `json:"home,omitempty"` + Version string `json:"version,omitempty"` + Provider string `json:"provider,omitempty"` + Layer string `json:"layer,omitempty"` +} + +// RuntimeEnvironment belongs to one verified package and one launch. It never changes the +// global tool catalog or the project's tools; only explicitly bound dependency tools appear. +type RuntimeEnvironment struct { + Runtimes map[string]core.ManagedRuntimeInstallation + Tools map[string]pluginbackend.ToolExecutable + Facts map[string]RuntimeTool +} + +// SetRuntimeLanguage supplies the UI's current language without reading view state on an I/O worker. +func (s *Service) SetRuntimeLanguage(language string) { s.runtimeLanguage.Store(&language) } + +// HasManagedRuntimes is a dispatch check, not manifest validation. Core validates the declaration +// before any process or I/O; old plugins keep their existing path without a new service call. +func HasManagedRuntimes(manifest json.RawMessage) bool { + var value struct { + Runtimes json.RawMessage `json:"managedRuntimes"` + } + return json.Unmarshal(manifest, &value) == nil && len(value.Runtimes) > 0 && string(value.Runtimes) != "null" +} + +// EnsureRuntimes prepares an approved package's environment before publication, or repairs it +// before a language-server launch. Installation verifies every recorded file; launches use the +// inventory's cheap metadata check plus the plugin's bounded compatibility check. Download and +// extraction are native I/O; the declaration, artifact identity and reply validation are Core's. +// +// packageDirectory may be the approved installation staging tree. Neither this method nor the +// runtime manager writes there. A failed update leaves the previously installed package usable. +func (s *Service) EnsureRuntimes(ctx context.Context, manifest json.RawMessage, packageDirectory, pluginID, version string, installing bool, progress func(pluginruntime.Progress)) (RuntimeEnvironment, error) { + return s.ensureRuntimes(ctx, manifest, packageDirectory, pluginID, version, installing, nil, progress) +} + +// EnsureRuntimesWithSettings uses the same effective settings snapshot as the following +// language-server start. Installation uses EnsureRuntimes and the global preference layer. +func (s *Service) EnsureRuntimesWithSettings(ctx context.Context, manifest json.RawMessage, packageDirectory, pluginID, version string, installing bool, settings core.PluginSettingsState, progress func(pluginruntime.Progress)) (RuntimeEnvironment, error) { + return s.ensureRuntimes(ctx, manifest, packageDirectory, pluginID, version, installing, &settings, progress) +} + +func (s *Service) ensureRuntimes(ctx context.Context, manifest json.RawMessage, packageDirectory, pluginID, version string, installing bool, effectiveSettings *core.PluginSettingsState, progress func(pluginruntime.Progress)) (_ RuntimeEnvironment, resultErr error) { + if !HasManagedRuntimes(manifest) { + return RuntimeEnvironment{}, nil + } + ctx, preparation, err := s.beginRuntimePreparation(ctx, pluginID) + if err != nil { + return RuntimeEnvironment{}, err + } + var cleanupErr error + defer func() { preparation.finish(cleanupErr) }() + kernel, ok := s.kernel.(managedRuntimeKernel) + if !ok { + return RuntimeEnvironment{}, fmt.Errorf("%w: managed runtime service unavailable", ErrAssembly) + } + platform := core.ManagedRuntimePlatform{OS: toolchain.PlatformName(runtime.GOOS), Arch: core.PluginArchitecture()} + plan, err := kernel.PlanManagedRuntimes(ctx, manifest, platform) + if err != nil { + return RuntimeEnvironment{}, err + } + if len(plan.Dependencies) == 0 { + return RuntimeEnvironment{}, nil + } + if effectiveSettings == nil { + settings, err := s.Settings.Load(ctx, manifest, "") + if err != nil { + return RuntimeEnvironment{}, err + } + effectiveSettings = &settings.State + } + // Core already projected inheritance, validity and defaults in these rows. + // Settings/ProjectSettings remain raw launch layers, not effective values. + resolvedSettings := make(map[string]json.RawMessage, len(effectiveSettings.Rows)) + for _, row := range effectiveSettings.Rows { + resolvedSettings[row.Declaration.ID] = row.Effective.Value + } + workspaceRoots := s.Contexts.workspaceRoots() + tools, err := s.runtimeTools(ctx, manifest, plan, workspaceRoots) + if err != nil { + return RuntimeEnvironment{}, err + } + manager := pluginruntime.Manager{Root: filepath.Join(pluginpkg.StateRoot(s.Root, pluginID), "runtimes"), Downloader: s.RuntimeDownloader} + candidates := make(map[string]string, len(plan.Dependencies)) + report := func(value pluginruntime.Progress) { + if value.Cause != nil && s.RuntimeIssue != nil { + s.RuntimeIssue(ctx, value.Cause) + } + if progress != nil { + progress(value) + } + } + for _, dependency := range plan.Dependencies { + report(pluginruntime.Progress{ID: dependency.ID, Phase: "checking"}) + inspect := manager.Find + if installing { + inspect = manager.Verify + } + installation, found, err := inspect(ctx, runtimeArtifact(dependency)) + if errors.Is(err, pluginruntime.ErrCorrupt) { + if s.RuntimeIssue != nil { + s.RuntimeIssue(ctx, err) + } + report(pluginruntime.Progress{ID: dependency.ID, Phase: "repairing"}) + continue + } + if err != nil { + return RuntimeEnvironment{}, err + } + if found { + candidates[dependency.ID] = installation.Home + } + } + // The preparation process uses exactly the package being reviewed, even when an older + // backend of the same plugin is running. Its lifetime ends before installation commits. + backend, cleanup, err := s.runtimeBackend(ctx, manifest, packageDirectory, pluginID, version, *effectiveSettings) + if err != nil { + return RuntimeEnvironment{}, err + } + preparation.retryCleanup = cleanup + defer func() { + stopCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), backendStopTimeout) + defer cancel() + cleanupErr = cleanup(stopCtx) + resultErr = errors.Join(resultErr, cleanupErr) + }() + resolve := func(ctx context.Context) (core.ManagedRuntimeResolution, error) { + language := "" + if selected := s.runtimeLanguage.Load(); selected != nil { + language = *selected + } + params, err := json.Marshal(struct { + Platform core.ManagedRuntimePlatform `json:"platform"` + Dependencies []core.ManagedRuntimeDependency `json:"dependencies"` + Candidates map[string]string `json:"candidates"` + Tools map[string]RuntimeTool `json:"tools"` + Settings map[string]json.RawMessage `json:"settings"` + Language string `json:"language,omitempty"` + }{platform, plan.Dependencies, candidates, tools, resolvedSettings, language}) + if err != nil { + return core.ManagedRuntimeResolution{}, err + } + timeout := time.Duration(plan.Resolve.TimeoutMilliseconds) * time.Millisecond + callCtx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + answer, err := backend.Call(callCtx, plan.Resolve.Function, params, nil, timeout) + if err != nil { + return core.ManagedRuntimeResolution{}, err + } + return kernel.DecodeManagedRuntimeResolution(ctx, manifest, platform, answer) + } + resolution, err := resolve(ctx) + if err != nil { + return RuntimeEnvironment{}, err + } + for _, id := range resolution.Missing { + // Core checked the complete partition, so every ID names exactly one selected artifact. + for _, dependency := range plan.Dependencies { + if dependency.ID != id { + continue + } + installation, err := manager.Prepare(ctx, runtimeArtifact(dependency), func(ctx context.Context, staged pluginruntime.Installation) error { + previous, present := candidates[id] + candidates[id] = staged.Home + defer func() { + if present { + candidates[id] = previous + } else { + delete(candidates, id) + } + }() + checked, err := resolve(ctx) + if err != nil { + return err + } + for _, item := range checked.Runtimes { + if item.ID == id { + accepted, acceptedErr := os.Stat(item.Home) + candidate, candidateErr := os.Stat(staged.Home) + if acceptedErr == nil && candidateErr == nil && accepted.IsDir() && candidate.IsDir() && os.SameFile(accepted, candidate) { + return nil + } + } + } + return fmt.Errorf("%w: %s", ErrRuntimeIncomplete, id) + }, report) + if err != nil { + return RuntimeEnvironment{}, err + } + candidates[id] = installation.Home + } + } + resolution, err = resolve(ctx) + if err != nil { + return RuntimeEnvironment{}, err + } + if len(resolution.Missing) != 0 { + return RuntimeEnvironment{}, ErrRuntimeIncomplete + } + environment := RuntimeEnvironment{ + Runtimes: make(map[string]core.ManagedRuntimeInstallation), + Tools: make(map[string]pluginbackend.ToolExecutable), Facts: make(map[string]RuntimeTool), + } + for _, installation := range resolution.Runtimes { + for _, dependency := range plan.Dependencies { + if dependency.ID != installation.ID || dependency.Tool == "" { + continue + } + executable := filepath.Join(installation.Home, filepath.FromSlash(dependency.Executable)) + info, err := os.Stat(executable) + if err != nil || !info.Mode().IsRegular() || (runtime.GOOS != "windows" && info.Mode()&0o111 == 0) { + return RuntimeEnvironment{}, fmt.Errorf("%w: executable for %s", ErrRuntimeIncomplete, dependency.ID) + } + selected, err := s.validateRuntimeTool(ctx, manifest, dependency, installation, info, workspaceRoots) + if err != nil { + return RuntimeEnvironment{}, err + } + // Keep Core's native identities in every launch view. A workspace alias + // must not redirect the verified outside installation after preparation. + executable, installation.Home = selected.Executable, *selected.Home + environment.Tools[dependency.Tool] = pluginbackend.ToolExecutable{Path: executable} + environment.Facts[dependency.Tool] = RuntimeTool{Executable: executable, Home: installation.Home, Version: installation.Version} + } + environment.Runtimes[installation.ID] = installation + report(pluginruntime.Progress{ID: installation.ID, Phase: "ready"}) + } + return environment, nil +} + +func runtimeArtifact(dependency core.ManagedRuntimeDependency) pluginruntime.Artifact { + return pluginruntime.Artifact{ID: dependency.ID, Version: dependency.Version, CacheKey: dependency.CacheKey, + URL: dependency.URL, SHA256: dependency.SHA256, Archive: dependency.Archive, + StripPrefix: dependency.StripPrefix, Home: dependency.Home, Executable: dependency.Executable} +} + +func (s *Service) runtimeTools(ctx context.Context, manifest json.RawMessage, plan core.ManagedRuntimePlan, workspaceRoots []string) (map[string]RuntimeTool, error) { + tools := make(map[string]RuntimeTool) + kernel, ok := s.kernel.(toolchain.Kernel) + if !ok { + return tools, fmt.Errorf("%w: tool discovery unavailable", ErrAssembly) + } + for _, dependency := range plan.Dependencies { + if dependency.Tool == "" { + continue + } + selected, err := toolchain.Resolve(ctx, kernel, "", ".", dependency.Tool, "", nil, []json.RawMessage{manifest}, toolchain.Options{ + Global: true, GlobalRoot: s.Settings.PreferenceDirectory(), WorkspaceRoots: workspaceRoots, + }) + var unavailable *toolchain.UnavailableError + if errors.As(err, &unavailable) && !unavailable.Terminal { + // log-exempt: 预期的缺失:缺少工具是声明式运行环境准备流程的正常输入。 + continue + } + if err != nil { + return nil, err + } + if selected.ProjectCode { + continue + } + fact := RuntimeTool{Executable: selected.Executable, Version: selected.Version, Provider: selected.Provider, Layer: selected.Layer} + if selected.Home != nil { + fact.Home = *selected.Home + } + tools[dependency.Tool] = fact + } + return tools, nil +} + +// A compatibility hook may discover a home through its own settings. Its approval +// does not grant native execution: Core checks that exact home with the same open +// workspace facts as discovery before the bound tool bypasses normal resolution. +// Fixed selection is read-only and cannot silently fall back to another tool. +func (s *Service) validateRuntimeTool(ctx context.Context, manifest json.RawMessage, dependency core.ManagedRuntimeDependency, installation core.ManagedRuntimeInstallation, executableInfo os.FileInfo, workspaceRoots []string) (toolchain.Selection, error) { + kernel, ok := s.kernel.(toolchain.Kernel) + if !ok { + return toolchain.Selection{}, fmt.Errorf("%w: tool discovery unavailable", ErrAssembly) + } + selected, err := toolchain.Resolve(ctx, kernel, "", ".", dependency.Tool, "", &toolchain.Fixed{Home: installation.Home}, []json.RawMessage{manifest}, toolchain.Options{ + Global: true, GlobalRoot: s.Settings.PreferenceDirectory(), WorkspaceRoots: workspaceRoots, + }) + if err != nil { + return toolchain.Selection{}, err + } + checked, err := os.Stat(selected.Executable) + if err != nil || selected.ProjectCode || selected.Home == nil || !os.SameFile(executableInfo, checked) { + return toolchain.Selection{}, fmt.Errorf("%w: executable for %s", ErrRuntimeIncomplete, dependency.ID) + } + home, homeErr := os.Stat(installation.Home) + canonicalHome, canonicalErr := os.Stat(*selected.Home) + if homeErr != nil || canonicalErr != nil || !home.IsDir() || !os.SameFile(home, canonicalHome) { + return toolchain.Selection{}, fmt.Errorf("%w: home for %s", ErrRuntimeIncomplete, dependency.ID) + } + return selected, nil +} + +func (s *Service) runtimeBackend(ctx context.Context, manifest json.RawMessage, directory, pluginID, version string, settings core.PluginSettingsState) (*BackendSession, func(context.Context) error, error) { + root := pluginpkg.StateRoot(s.Root, pluginID) + if err := os.MkdirAll(root, 0o700); err != nil { + return nil, nil, err + } + state, err := os.MkdirTemp(root, "runtime-check-") + if err != nil { + return nil, nil, err + } + startCtx, cancelStart := context.WithTimeout(ctx, backendStartTimeout) + defer cancelStart() + started, err := s.Backend.Start(startCtx, pluginbackend.StartRequest{ + Manifest: manifest, PackageDirectory: directory, PluginID: pluginID, + ProviderID: pluginID + "/runtime-check", StateDirectory: state, + LogDirectory: s.logDirectory(ctx, pluginID), Architecture: core.PluginArchitecture(), + RootURI: fileURI(state), WorkingDirectory: state, + Preparation: true, Settings: settings.Settings, ProjectSettings: settings.ProjectSettings, + }) + if err != nil { + return nil, nil, errors.Join(err, os.RemoveAll(state)) + } + serveCtx, cancel := context.WithCancel(ctx) + session := &BackendSession{ + host: s.Host, PluginID: pluginID, Version: version, Session: started, + cancel: cancel, done: make(chan struct{}), functions: make(map[string]bool), + waiters: make(map[string]chan core.BackendEvent), progress: make(map[string]func(json.RawMessage)), changed: make(chan struct{}), + } + go session.serve(serveCtx) + // A failed stop retains ownership and state, and a later lifecycle attempt can + // retry it. The gate also serializes simultaneous window shutdown requests. + gate := make(chan struct{}, 1) + gate <- struct{}{} + stopObserved := false + var stopErr error + cleanup := func(ctx context.Context) error { + select { + case <-gate: + case <-ctx.Done(): + return ctx.Err() + } + defer func() { gate <- struct{}{} }() + session.cancel() + select { + case <-session.done: + case <-ctx.Done(): + return ctx.Err() + } + if !stopObserved { + stopErr = s.runtimeStopFailure(ctx, session.disposed, session.stopErr) + stopObserved = true + } else if stopErr != nil { + disposed, err := s.Backend.StopAndDispose(ctx, session.Session) + stopErr = s.runtimeStopFailure(ctx, disposed, err) + } + if stopErr != nil { + return stopErr + } + return os.RemoveAll(state) + } + return session, cleanup, nil +} + +// A failed graceful shutdown remains a diagnostic when disposal already proved +// the process cannot use its files. Only an undisposed process retains ownership. +func (s *Service) runtimeStopFailure(ctx context.Context, disposed bool, err error) error { + if disposed { + if err != nil && s.RuntimeIssue != nil { + s.RuntimeIssue(ctx, err) + } + return nil + } + return err +} From 1b0cafe08fc5847e599e5202be78086eeb4ca5a4 Mon Sep 17 00:00:00 2001 From: "lithe-support[bot]" <356900028+lithe-support[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:12:28 +0000 Subject: [PATCH 15/20] fix(toolchains): exclude open workspace code from runtime probes --- desktop/internal/toolchain/load.go | 5 ++ desktop/internal/toolchain/scan.go | 80 ++++++++++++++++++------- desktop/internal/toolchain/toolchain.go | 3 + 3 files changed, 66 insertions(+), 22 deletions(-) diff --git a/desktop/internal/toolchain/load.go b/desktop/internal/toolchain/load.go index 15a97328f..d05954abd 100644 --- a/desktop/internal/toolchain/load.go +++ b/desktop/internal/toolchain/load.go @@ -334,6 +334,9 @@ func prepareTool(ctx context.Context, kernel Kernel, workspace *workspace, regis } } workspace.observe(workspace.root) + for _, root := range workspace.workspaceRoots { + workspace.observe(root) + } if !options.Global && workspace.root != "" { observeProjectFiles(workspace, directory, maxAncestors, planned) } @@ -380,6 +383,7 @@ func prepareTool(ctx context.Context, kernel Kernel, workspace *workspace, regis Tool: planned.Tool, Platform: workspace.platform, WorkspaceRoot: workspace.root, + WorkspaceRoots: workspace.workspaceRoots, Filesystem: prepared.facts, MinimumVersion: options.MinimumVersion, SystemInstallations: prepared.installations, @@ -456,6 +460,7 @@ func resolveTool(ctx context.Context, kernel Kernel, workspace *workspace, regis Local: document, Platform: workspace.platform, WorkspaceRoot: workspace.root, + WorkspaceRoots: workspace.workspaceRoots, Filesystem: prepared.facts, MinimumVersion: minimumVersion, Probes: prepared.probes, diff --git a/desktop/internal/toolchain/scan.go b/desktop/internal/toolchain/scan.go index 47535ab4c..9e0459619 100644 --- a/desktop/internal/toolchain/scan.go +++ b/desktop/internal/toolchain/scan.go @@ -18,13 +18,15 @@ import ( // workspace holds the native facts one load may read. It is confined to the // opened project root and the declared scan roots. type workspace struct { - root string - home string - platform string - environment map[string]string - lookup LookupFunc - probe ProbeFunc - caseSensitive bool + root string + workspaceRoots []string + lexicalRoots []string + home string + platform string + environment map[string]string + lookup LookupFunc + probe ProbeFunc + caseSensitive bool // entries bounds every scan this load performs, as Core's plan declares. entries int facts map[string]core.ToolchainFileFact @@ -49,6 +51,21 @@ func newWorkspace(root string, options Options) (*workspace, error) { return nil, errors.New("toolchain: the workspace root is not a directory") } } + var workspaceRoots, lexicalRoots []string + for _, root := range options.WorkspaceRoots { + if root == "" || !filepath.IsAbs(root) { + return nil, errors.New("toolchain: the workspace root must be absolute") + } + canonical, err := canonicalPath(root) + if err != nil { + return nil, err + } + if info, err := os.Stat(canonical); err != nil || !info.IsDir() { + return nil, errors.New("toolchain: the workspace root is not a directory") + } + workspaceRoots = append(workspaceRoots, canonical) + lexicalRoots = append(lexicalRoots, filepath.Clean(root)) + } home := options.Home if home == "" { if home, err = os.UserHomeDir(); err != nil { @@ -68,15 +85,17 @@ func newWorkspace(root string, options Options) (*workspace, error) { probe = defaultProbe } return &workspace{ - root: canonicalRoot, - home: home, - platform: options.Platform, - environment: environment, - lookup: lookup, - probe: probe, - caseSensitive: options.Platform != "windows", - entries: 4096, - facts: make(map[string]core.ToolchainFileFact), + root: canonicalRoot, + workspaceRoots: uniqueSorted(workspaceRoots), + lexicalRoots: uniqueSorted(lexicalRoots), + home: home, + platform: options.Platform, + environment: environment, + lookup: lookup, + probe: probe, + caseSensitive: options.Platform != "windows", + entries: 4096, + facts: make(map[string]core.ToolchainFileFact), }, nil } @@ -125,10 +144,13 @@ func canonicalPath(name string) (string, error) { } func (w *workspace) insideRoot(name string) bool { - if w.root == "" { + return w.insidePath(w.root, name) +} + +func (w *workspace) insidePath(root, name string) bool { + if root == "" { return false } - root := w.root candidate := name if !w.caseSensitive { root = strings.ToLower(root) @@ -141,6 +163,20 @@ func (w *workspace) insideRoot(name string) bool { return relative == "." || (relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator))) } +func (w *workspace) insideWorkspace(name string) bool { + if w.insideRoot(name) { + return true + } + for _, roots := range [][]string{w.workspaceRoots, w.lexicalRoots} { + for _, root := range roots { + if w.insidePath(root, name) { + return true + } + } + } + return false +} + // observe records one native fact. Every fact is deduplicated by native identity // so Core never sees two contradictory rows for one path. func (w *workspace) observe(name string) core.ToolchainFileFact { @@ -220,9 +256,9 @@ func (w *workspace) observeChain(base, target string) core.ToolchainFileFact { } // isWorkspaceCode reports whether name or its resolved target lies inside the -// opened workspace root. Any resolution failure fails closed as workspace code. +// opened workspace roots. Any resolution failure fails closed as workspace code. func (w *workspace) isWorkspaceCode(name string) bool { - if w.root == "" || name == "" { + if name == "" || (w.root == "" && len(w.workspaceRoots) == 0) { return false } absolute, err := filepath.Abs(name) @@ -230,14 +266,14 @@ func (w *workspace) isWorkspaceCode(name string) bool { return true } cleaned := filepath.Clean(absolute) - if w.insideRoot(cleaned) { + if w.insideWorkspace(cleaned) { return true } canonical, err := canonicalPath(cleaned) if err != nil { return true } - return w.insideRoot(canonical) + return w.insideWorkspace(canonical) } // all returns the facts in a stable order, which keeps Core's input comparable diff --git a/desktop/internal/toolchain/toolchain.go b/desktop/internal/toolchain/toolchain.go index a63b73daf..24c5b0388 100644 --- a/desktop/internal/toolchain/toolchain.go +++ b/desktop/internal/toolchain/toolchain.go @@ -103,6 +103,9 @@ type Options struct { // registry and per-workspace toolchain trust in user application settings. Global bool GlobalRoot string + // WorkspaceRoots are native open-workspace facts, including other workbenches. + // Global selection still excludes their code before any version probe. + WorkspaceRoots []string // ProjectCodeAllowed grants probing and selection of workspace-local tool // candidates only when GlobalRoot is unset in unit tests. Production loads and // launches always supply GlobalRoot so trust comes solely from local storage. From d7f5d6617b8900e32e2e38aa388dad8c28ec667d Mon Sep 17 00:00:00 2001 From: "lithe-support[bot]" <356900028+lithe-support[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:25:57 +0000 Subject: [PATCH 16/20] fix(plugins): preserve runtime and workspace lifecycle ownership --- .../2026-11-18-managed-plugin-runtimes.md | 89 ++ desktop/internal/pluginservice/activation.go | 29 +- desktop/internal/pluginservice/backends.go | 39 +- .../pluginservice/runtime_lifecycle.go | 180 +++++ .../internal/pluginservice/runtimes_test.go | 761 ++++++++++++++++++ 5 files changed, 1087 insertions(+), 11 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-11-18-managed-plugin-runtimes.md create mode 100644 desktop/internal/pluginservice/runtime_lifecycle.go create mode 100644 desktop/internal/pluginservice/runtimes_test.go diff --git a/.agents/notes/implemented/architecture/2026-11-18-managed-plugin-runtimes.md b/.agents/notes/implemented/architecture/2026-11-18-managed-plugin-runtimes.md new file mode 100644 index 000000000..cd15bfbd8 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-18-managed-plugin-runtimes.md @@ -0,0 +1,89 @@ +# Agent 笔记:插件声明的运行时按依赖身份安装并跨插件版本复用 + +状态:已实现 + +## 先说结论 + +插件可以显式声明安装自己所需的运行时,用户批准该插件的程序与下载权限后,宿主先让插件检查已有安装,只下载缺失项。完成校验的依赖放在该插件的跨版本状态目录,因此普通插件升级不必重复下载大型运行时。Core 决定声明是否合法、当前平台选哪个归档以及回复是否完整;插件判断实际安装是否合用,宿主负责下载、文件安全和进程生命周期。默认随插件打包资源的方式仍然有效,不声明新能力的插件保留原有流程。 + +## 问题 + +把大型运行时随每个插件版本打包,更新少量插件代码也要重新传输依赖;完全依赖用户安装,又容易因工具缺失、版本或目录不兼容而启动失败。简单地在语言服务器启动时下载也有问题:包已显示安装成功,实际依赖却可能尚未可用;下载中断和插件更新重叠时,旧进程还可能读到正在覆盖的文件。 + +已有插件状态目录可以提供写入位置,但目录本身不回答依赖版本、平台、来源、校验值和兼容性问题。需要把这些内容纳入正式清单和审批,同时保持应用安装包只读,且不能把某种语言的下载规则搬回宿主。 + +## 决策 + +### 1. 新能力必须显式声明并进入程序审批 + +`managedRuntimes` 是版本为 0 的可选能力,同时要求 `runtimes.install` 权限。插件清单固定每个依赖的版本、平台归档、HTTPS 来源、SHA-256 和相对目录布局,并声明一个检查函数。这些内容进入既有程序审批摘要,插件改变下载来源或可执行文件布局时必须重新走审批。 + +检查函数由插件自带的后端运行;这个后端必须能够独立启动,不能先依赖尚待准备的工具。宿主在审批后、插件版本提交前运行检查,因此检查失败或下载失败不会替换已安装的可用版本。检查进程不加入正常插件函数转发,不获得工作区和其他宿主服务授权;宿主仍可直接调用它,并接收能力查询和日志。 + +### 2. Core、插件与宿主分别回答不同问题 + +Core 校验清单、按平台选择唯一归档、计算稳定缓存键,并校验检查结果覆盖全部依赖且没有未知或重复项。插件检查显式配置、宿主提供的候选目录和外部工具事实,决定哪些目录合用、哪些依赖缺失;无效的显式选择应报告错误,不能悄悄换成下载。宿主只执行通过 Core 校验的计划,不推断语言版本,也不维护特定工具的下载地址。 + +安装检查使用全局设置;启动前修复使用随后启动所用的有效设置快照,避免忽略项目覆盖。选中的运行时目录只读传给该次语言服务器启动;声明绑定的工具也只覆盖这一次启动,不写全局工具目录、项目配置或用户选择。 + +全局选择模式不抹除已打开项目的路径边界。工作区上下文按真实 Open、Close、CloseAll 生命周期登记根目录,跨窗口和标签页按引用计数维护;一次准备捕获同一份根快照,供原生探针执行前检查和 Core 工具路径分类使用。检查函数返回的工具目录仍以固定 Home 走 Core 校验,确认实际可执行文件是同一文件后,向后续启动传递已验证的规范路径与 Home,避免重新使用项目内可变的符号链接。这个过程只读,不写工具目录或信任授权。 + +上下文由界面在打开项目时同步建立。后台激活、语言服务启动和共享构建服务只消费捕获的 ContextRef,不代替已关闭项目重新 Open;关闭后即使重新打开同一路径,旧身份也不能借用新项目。准备结束及原生启动边界再次核对身份,失效时沿用取消与销毁流程。这使共享根引用严格对应仍打开的项目,迟到后台任务不会留下永久根记录。 + +正确做法:插件检查函数确认一个外部安装完整可用后返回该目录;若另一个声明依赖缺失,宿主只下载后者。 +不要这样做:宿主通过插件名称猜测所需工具版本,或者发现项目工具不合适时直接修改项目默认工具。 + +### 3. 按依赖身份保留完整文件,不按插件版本覆盖 + +受管文件位于 `/.state//runtimes//`。缓存键包含选定依赖的版本、平台、下载内容身份和布局,不包含插件版本;同一依赖跨插件升级可直接复用。不同插件不共享这个目录,外部安装也不转为宿主拥有的文件。 + +下载归档经过 SHA-256 校验后保存。解压先写私有目录,核对路径、链接、数量和字节预算,再调用插件检查;检查通过且输入文件没有被改写,才原子发布完成记录。每次发布使用新的完整目录,不原地替换旧进程正在读取的文件。归档损坏时重新下载;展开文件损坏而归档仍有效时可离线重建。旧的完整目录保留到插件状态被删除,为仍运行的进程和旧插件版本提供稳定路径。 + +安装与升级完整核对缓存文件哈希;正常启动先核对文件清单和元数据,再由插件作有界兼容性检查。启动发现缺失或损坏时复用同一准备流程。缓存布局、限制与清理规则见 [CI 构建与资源归属](../../../../docs/ci-builds.md),它不是可以跨工作树复制的构建缓存。 + +### 4. 取消、禁用和卸载必须等待准备工作结束 + +宿主跟踪准备任务及其检查进程。取消后清理未发布文件;禁用、替换或卸载先阻止新任务,取消并等待已有任务和语言服务器退出,再进行后续操作。停止失败保留包和状态供重试,避免后台任务在删除后重新创建目录。外部安装不在删除范围内;禁用也不删除已下载完成的依赖。 + +应用包、插件包和受管完成目录都是只读输入。索引、日志和进程的可写配置仍使用各自状态目录;这沿用[运行时保持发布程序包不变](../bug-fix/2026-09-25-runtime-bundle-immutability-and-update-delta.md)的边界。默认打包资源的规则见 [LSP 插件构建与分发](2026-09-30-lsp-plugin-build-and-distribution.md)。 + +### 5. 准备进度使用共享词条和原有生成器 + +检查、下载、解压、验证、修复和取消都显示当前准备阶段;失败说明保留旧插件版本与已校验下载物,用户可以重试。宿主新增文案仍由共享 i18n 生成,具体插件的诊断由插件自己翻译。 + +这组声明和双语译文放在 `shared/i18n/features/plugin-managed-runtimes.json`。既有注册表已经超过提交接口的单次内容上限,而旧下载与权限文案的语义不适用于运行依赖,因此采用构建时的小文件输入,不重排大词库,也不换用含义不同的提示。原生成器合并后继续执行同一套声明、平台、别名、参数和完整翻译校验;片段不能重复或覆盖别处的词条。运行时只读取既有生成字典,没有额外加载路径。格式与操作见[共享翻译](../../../../shared/i18n/README.md)。 + +## 考虑过的备选方案 + +- 每个插件版本都内含完整运行时:适合需要完全离线分发的插件,也继续受支持,但会重复传输不变的大文件。 +- 宿主按语言名称管理共享工具目录:目录少,但兼容规则、下载地址和清理责任会重新落回宿主,多个插件还可能互相影响版本。 +- 只在第一次语言服务器启动时补装:接入简单,却无法在安装提交前发现问题,用户看到安装成功后仍要等待或排查失败。 +- 插件更新时覆盖同一路径:节省旧目录空间,但无法保证旧进程继续读取完整文件,Windows 上运行中的可执行文件也可能无法替换。 + +## 后果 + +插件更新可以复用未变化的依赖,已具备合用外部安装的用户不必重复下载;缺失和损坏都经过相同的检查、校验与错误通道。新增语言的规则留在插件仓库,宿主和 Core 只新增一次通用能力。 + +代价是首次安装可能需要较大下载,插件必须提供独立可运行的检查后端并维护固定校验值。保留归档和旧的完整目录会占用更多磁盘;当前按整个插件状态清理,不在升级时猜测哪些旧进程已经不再使用目录。没有匹配平台归档、无法联网且没有合用缓存、或显式配置无效时,准备会明确失败,不提交半完成的插件版本。 + +## 验证 + +- `cd desktop && ../scripts/desktop/desktop-go.sh test -race ./internal/core/ ./internal/pluginruntime/ ./internal/pluginbackend/ ./internal/pluginservice/`:共享 Core 契约、外部复用、跨版本不重复下载、缓存损坏修复、失败保留旧目录、并发与取消、安全解压及准备进程隔离。 +- `cd desktop && ../scripts/desktop/desktop-go.sh test -tags vivahead ./internal/workbench/ ./internal/settingswindow/`:安装前准备、进度与取消、启动等待以及关闭项目后的旧结果保护。macOS 与 Windows 原生窗口流程另行验收,功能矩阵不以无头测试替代实机结果。 +- `./scripts/desktop/verify/verify-runtime-bundle-immutability.sh` +- `./scripts/platform-feature-matrix/verify-platform-feature-matrix.sh` +- `./scripts/agent-notes/verify-agent-notes.sh` + +## 适用范围 + +- `desktop/internal/core/managed_runtimes.go` +- `desktop/internal/pluginruntime/` +- `desktop/internal/pluginservice/runtimes.go` +- `desktop/internal/pluginservice/runtime_lifecycle.go` +- `desktop/internal/pluginbackend/pluginbackend.go` +- `desktop/internal/settingswindow/plugin_install.go` +- `desktop/internal/workbench/runtime_preparation_test.go` +- `shared/i18n/features/plugin-managed-runtimes.json` +- `docs/ci-builds.md` +- `shared/platform-feature-matrix/features/plugin-managed-runtimes.json` +- `https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/contract/v1/README.md` diff --git a/desktop/internal/pluginservice/activation.go b/desktop/internal/pluginservice/activation.go index 5cd94c737..588896f21 100644 --- a/desktop/internal/pluginservice/activation.go +++ b/desktop/internal/pluginservice/activation.go @@ -67,17 +67,22 @@ func (s *Service) SyncFunctionRelay(ctx context.Context, entries []pluginmanager return errors.Join(failures...) } -// ActivateWorkspace opens the workspace's context and starts the backends that -// asked for onWorkspaceOpen, one plugin at a time. It belongs on a background +// ActivateWorkspace consumes the context the window opened and starts the backends +// that asked for onWorkspaceOpen, one plugin at a time. It belongs on a background // goroutine: starting a backend never delays opening the workspace, and a backend // that fails to start is reported without blocking the others. -func (s *Service) ActivateWorkspace(ctx context.Context, entries []pluginmanager.Entry, root string) error { +func (s *Service) ActivateWorkspace(ctx context.Context, entries []pluginmanager.Entry, workspace ContextRef) error { if s == nil || s.Contexts == nil || s.Host == nil { return nil } - s.Contexts.Open(root) + if _, err := s.checkedWorkspaceContext(ctx, workspace); err != nil { + return err + } selected, selectionErr := s.selectInstalled(ctx, entries, false) failures := []error{selectionErr} + if _, err := s.checkedWorkspaceContext(ctx, workspace); err != nil { + return errors.Join(append(failures, err)...) + } for _, entry := range selected { manifest, err := readBounded(filepath.Join(entry.Installed.Path, pluginpkg.ManifestFile), MaxManifestBytes) if err != nil { @@ -87,6 +92,9 @@ func (s *Service) ActivateWorkspace(ctx context.Context, entries []pluginmanager if !declaresBackend(manifest) || !declaredActivation(manifest, EventWorkspaceOpen) { continue } + if _, err := s.checkedWorkspaceContext(ctx, workspace); err != nil { + return errors.Join(append(failures, err)...) + } if _, err := s.Host.EnsureBackend(ctx, entry.Installed.ID); err != nil { failures = append(failures, fmt.Errorf("%s: %w", entry.Installed.ID, err)) } @@ -94,6 +102,19 @@ func (s *Service) ActivateWorkspace(ctx context.Context, entries []pluginmanager return errors.Join(failures...) } +// checkedWorkspaceContext never creates an owner on behalf of delayed work. +// Closing and reopening a path invalidates the captured ID/generation even when +// the new project's native root is identical. +func (s *Service) checkedWorkspaceContext(ctx context.Context, ref ContextRef) (WorkspaceContext, error) { + if err := ctx.Err(); err != nil { + return WorkspaceContext{}, err + } + if s == nil || s.Contexts == nil { + return WorkspaceContext{}, ErrContextExpired + } + return s.Contexts.Lookup(ref) +} + // DetachWorkspaces ends every workspace context and removes every backend from // the host at once, returning the function that stops the detached processes // (bounded). It runs when the project closes: a backend is shared by the windows diff --git a/desktop/internal/pluginservice/backends.go b/desktop/internal/pluginservice/backends.go index 4fefff099..340ec0f63 100644 --- a/desktop/internal/pluginservice/backends.go +++ b/desktop/internal/pluginservice/backends.go @@ -22,6 +22,9 @@ type BackendRequest struct { // RootURI and WorkingDirectory are the workspace root. RootURI any WorkingDirectory string + // Context is captured while the window owns WorkingDirectory. A background + // start cannot adopt a new context after the same path is reopened. + Context ContextRef // Architecture is the platform architecture Core plans for. Architecture string // RuntimeProgress reports cancellable preparation before the bounded server @@ -85,11 +88,9 @@ func (s *Service) StartLanguageServer(ctx context.Context, entries []pluginmanag if readErr != nil { return fail(readErr) } - var workspaceContext WorkspaceContext - if request.WorkingDirectory != "" && s.Contexts != nil { - // The server serves this workspace, so a backend that asks for it by - // context finds it: the context exists for as long as the project is open. - workspaceContext = s.Contexts.Open(request.WorkingDirectory) + workspaceContext, contextErr := s.workspaceForBackend(ctx, request) + if contextErr != nil { + return fail(contextErr) } settings, settingsErr := s.Settings.Load(ctx, manifest, request.WorkingDirectory) if settingsErr != nil { @@ -99,6 +100,9 @@ func (s *Service) StartLanguageServer(ctx context.Context, entries []pluginmanag if runtimeErr != nil { return fail(runtimeErr) } + if _, contextErr := s.workspaceForBackend(ctx, request); contextErr != nil { + return fail(contextErr) + } // Downloads have their own cancellation and transport stall limits. Apply // the process-start budget only after the environment is ready, so slow // healthy downloads do not repeatedly lose their progress. @@ -137,12 +141,16 @@ func (s *Service) StartLanguageServer(ctx context.Context, entries []pluginmanag start.WorkspaceStateDirectory = resolved.directories.workspaceState temporary = resolved.directories.temporary } + if _, contextErr := s.workspaceForBackend(ctx, request); contextErr != nil { + removeTemporary(temporary) + return fail(contextErr) + } started, startErr := s.Backend.Start(ctx, start) if startErr != nil { removeTemporary(temporary) return fail(startErr) } - if cancelled := ctx.Err(); cancelled != nil { + if _, contextErr := s.workspaceForBackend(ctx, request); contextErr != nil { preparation.retryCleanup = func(stopCtx context.Context) error { disposed, err := s.Backend.StopAndDispose(stopCtx, started) if disposed { @@ -153,7 +161,7 @@ func (s *Service) StartLanguageServer(ctx context.Context, entries []pluginmanag stopCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), backendStopTimeout) cleanupErr = preparation.retryCleanup(stopCtx) cancel() - return fail(errors.Join(cancelled, cleanupErr)) + return fail(errors.Join(contextErr, cleanupErr)) } session := &LanguageSession{ PluginID: entry.Installed.ID, @@ -172,6 +180,23 @@ func (s *Service) StartLanguageServer(ctx context.Context, entries []pluginmanag return session, nil } +func (s *Service) workspaceForBackend(ctx context.Context, request BackendRequest) (WorkspaceContext, error) { + if err := ctx.Err(); err != nil { + return WorkspaceContext{}, err + } + if request.WorkingDirectory == "" { + return WorkspaceContext{}, nil + } + workspace, err := s.checkedWorkspaceContext(ctx, request.Context) + if err != nil { + return WorkspaceContext{}, err + } + if filepath.Clean(workspace.Path) != filepath.Clean(request.WorkingDirectory) { + return WorkspaceContext{}, ErrContextExpired + } + return workspace, nil +} + // ServeLanguageSession answers the session's host requests until it ends or ctx is // done, passing every other event to observe, which may be nil. func (s *Service) ServeLanguageSession(ctx context.Context, session *LanguageSession, observe pluginbackend.EventObserver) error { diff --git a/desktop/internal/pluginservice/runtime_lifecycle.go b/desktop/internal/pluginservice/runtime_lifecycle.go new file mode 100644 index 000000000..73dbfe058 --- /dev/null +++ b/desktop/internal/pluginservice/runtime_lifecycle.go @@ -0,0 +1,180 @@ +package pluginservice + +import ( + "context" + "errors" + "path/filepath" + "sync" +) + +// ErrRuntimeBusy reports a stop still owning a plugin's files. A new approved +// installation can retry after that operation finishes; it cannot reopen admission. +var ErrRuntimeBusy = errors.New("plugin runtime preparation is stopping") + +type runtimePreparationKey struct{ root, plugin string } + +// Preparations from different workbenches share the same package and runtime files. +// The coordinator keeps only unfinished work and ongoing lifecycle operations; +// each Service owns its persistent admission choices. +var runtimePreparationCoordinator = struct { + sync.Mutex + active map[runtimePreparationKey]map[*runtimePreparation]struct{} + stops map[runtimePreparationKey]int +}{active: make(map[runtimePreparationKey]map[*runtimePreparation]struct{}), stops: make(map[runtimePreparationKey]int)} + +type runtimePreparation struct { + service *Service + key runtimePreparationKey + ctx context.Context + cancel context.CancelFunc + done chan struct{} + cleanupErr error + retryCleanup func(context.Context) error +} + +func (s *Service) preparationKey(id string) runtimePreparationKey { + return runtimePreparationKey{root: filepath.Clean(s.Root), plugin: id} +} + +func (s *Service) beginRuntimePreparation(ctx context.Context, id string) (context.Context, *runtimePreparation, error) { + runtimePreparationCoordinator.Lock() + defer runtimePreparationCoordinator.Unlock() + if err := ctx.Err(); err != nil { + return nil, nil, err + } + key := s.preparationKey(id) + if s.runtimeBlocked[id] || runtimePreparationCoordinator.stops[key] != 0 { + return nil, nil, ErrRuntimeBusy + } + ctx, preparation := s.newRuntimePreparationLocked(ctx, key) + return ctx, preparation, nil +} + +func (s *Service) newRuntimePreparationLocked(ctx context.Context, key runtimePreparationKey) (context.Context, *runtimePreparation) { + ctx, cancel := context.WithCancel(ctx) + preparation := &runtimePreparation{service: s, key: key, ctx: ctx, cancel: cancel, done: make(chan struct{})} + if runtimePreparationCoordinator.active[key] == nil { + runtimePreparationCoordinator.active[key] = make(map[*runtimePreparation]struct{}) + } + runtimePreparationCoordinator.active[key][preparation] = struct{}{} + return ctx, preparation +} + +// finish follows all process/file cleanup. Only cleanup failures remain registered: +// a rejected artifact or a cancelled download does not make an uninstall unsafe. +func (p *runtimePreparation) finish(cleanupErr error) { + p.cancel() + runtimePreparationCoordinator.Lock() + defer runtimePreparationCoordinator.Unlock() + p.cleanupErr = cleanupErr + if cleanupErr == nil { + p.forgetLocked() + } + close(p.done) +} + +func (p *runtimePreparation) forgetLocked() { + delete(runtimePreparationCoordinator.active[p.key], p) + if len(runtimePreparationCoordinator.active[p.key]) == 0 { + delete(runtimePreparationCoordinator.active, p.key) + } +} + +// holdRuntimeStop closes cross-window admission for the whole lifecycle action, +// including the file removal after stopPrograms. Concurrent approvals return busy. +func (s *Service) holdRuntimeStop(id string) func() { + key := s.preparationKey(id) + runtimePreparationCoordinator.Lock() + runtimePreparationCoordinator.stops[key]++ + runtimePreparationCoordinator.Unlock() + return func() { + runtimePreparationCoordinator.Lock() + defer runtimePreparationCoordinator.Unlock() + runtimePreparationCoordinator.stops[key]-- + if runtimePreparationCoordinator.stops[key] == 0 { + delete(runtimePreparationCoordinator.stops, key) + } + } +} + +// AllowRuntimePreparation reopens admission only for an explicit installation or +// enable. It never overrides a running stop or an unfinished cancelled attempt. +func (s *Service) AllowRuntimePreparation(id string) error { + runtimePreparationCoordinator.Lock() + defer runtimePreparationCoordinator.Unlock() + return s.allowRuntimePreparationLocked(id) +} + +func (s *Service) allowRuntimePreparationLocked(id string) error { + key := s.preparationKey(id) + if runtimePreparationCoordinator.stops[key] != 0 { + return ErrRuntimeBusy + } + for preparation := range runtimePreparationCoordinator.active[key] { + if preparation.ctx.Err() != nil || preparation.cleanupErr != nil { + return ErrRuntimeBusy + } + } + delete(s.runtimeBlocked, id) + return nil +} + +// BeginRuntimeInstallation belongs after package approval. Its lifetime includes +// preparation and publication, so an uninstall either refuses this start or waits +// until it can no longer publish a package or recreate the removed state. +func (s *Service) BeginRuntimeInstallation(ctx context.Context, id string) (context.Context, func(), error) { + runtimePreparationCoordinator.Lock() + defer runtimePreparationCoordinator.Unlock() + if err := ctx.Err(); err != nil { + return nil, nil, err + } + if err := s.allowRuntimePreparationLocked(id); err != nil { + return nil, nil, err + } + ctx, preparation := s.newRuntimePreparationLocked(ctx, s.preparationKey(id)) + return ctx, func() { preparation.finish(nil) }, nil +} + +func (s *Service) stopRuntimePreparations(ctx context.Context, id string) error { + runtimePreparationCoordinator.Lock() + s.blockRuntimePreparationLocked(id) + var pending []*runtimePreparation + for preparation := range runtimePreparationCoordinator.active[s.preparationKey(id)] { + preparation.service.blockRuntimePreparationLocked(id) + preparation.cancel() + pending = append(pending, preparation) + } + runtimePreparationCoordinator.Unlock() + + ctx, cancel := context.WithTimeout(ctx, backendStopTimeout) + defer cancel() + var failures []error + for _, preparation := range pending { + select { + case <-preparation.done: + case <-ctx.Done(): + return errors.Join(append(failures, ctx.Err())...) + } + runtimePreparationCoordinator.Lock() + err := preparation.cleanupErr + runtimePreparationCoordinator.Unlock() + if err != nil && preparation.retryCleanup != nil { + err = preparation.retryCleanup(ctx) + runtimePreparationCoordinator.Lock() + preparation.cleanupErr = err + if err == nil { + preparation.forgetLocked() + } + runtimePreparationCoordinator.Unlock() + } + failures = append(failures, err) + } + return errors.Join(failures...) +} + +func (s *Service) blockRuntimePreparationLocked(id string) { + if s.runtimeBlocked == nil { + s.runtimeBlocked = make(map[string]bool) + } + s.runtimeBlocked[id] = true +} diff --git a/desktop/internal/pluginservice/runtimes_test.go b/desktop/internal/pluginservice/runtimes_test.go new file mode 100644 index 000000000..50d052e89 --- /dev/null +++ b/desktop/internal/pluginservice/runtimes_test.go @@ -0,0 +1,761 @@ +package pluginservice + +import ( + "archive/zip" + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "runtime" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginbackend" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginmanager" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" +) + +// runtimeResolverKernel runs the actual Core contract and native preparation, replacing only +// the plugin process with an event-driven resolver. No concrete plugin or system tool is used. +type runtimeResolverKernel struct { + *core.Client + mu sync.Mutex + queues map[string]chan core.BackendEvent + external map[string]string + canonicalHomes bool + settingsHome bool + start func(context.Context, core.PluginBackendStart) error + stop func(context.Context, string) error + destroy func(context.Context, string) error + waitError func(string) error + starts atomic.Int32 + stops atomic.Int32 +} + +func (k *runtimeResolverKernel) StartPluginBackend(ctx context.Context, request core.PluginBackendStart) (core.PluginBackendStarted, error) { + if k.start != nil { + if err := k.start(ctx, request); err != nil { + return core.PluginBackendStarted{}, err + } + } + id := fmt.Sprintf("runtime-check-%d", k.starts.Add(1)) + queue := make(chan core.BackendEvent, 8) + queue <- core.BackendEvent{Type: "stateChanged", State: "ready"} + queue <- core.BackendEvent{Type: "functionsChanged", Result: json.RawMessage(`{"functions":["fixture.resolve"]}`)} + k.mu.Lock() + k.queues[id] = queue + k.mu.Unlock() + return core.PluginBackendStarted{SessionID: id}, nil +} + +func (k *runtimeResolverKernel) StartPluginLanguageServer(ctx context.Context, request core.PluginBackendStart) (core.PluginBackendStarted, error) { + request.Role = "language-server" + return k.StartPluginBackend(ctx, request) +} + +func (k *runtimeResolverKernel) WaitBackendEvents(ctx context.Context, session string, _ int) ([]core.BackendEvent, error) { + if k.waitError != nil { + if err := k.waitError(session); err != nil { + return nil, err + } + } + k.mu.Lock() + queue := k.queues[session] + k.mu.Unlock() + if queue == nil { + return nil, errors.New("unknown fixture session") + } + select { + case event := <-queue: + return []core.BackendEvent{event}, nil + case <-ctx.Done(): + return nil, ctx.Err() + } +} + +func (k *runtimeResolverKernel) InvokePluginFunctionInContext(ctx context.Context, session, operation, _, function string, params, _ json.RawMessage, _ int) (string, error) { + if function != "fixture.resolve" { + return "", errors.New("unexpected preparation function") + } + var request struct { + Candidates map[string]string `json:"candidates"` + Dependencies []core.ManagedRuntimeDependency `json:"dependencies"` + Settings map[string]json.RawMessage `json:"settings"` + } + if err := json.Unmarshal(params, &request); err != nil { + return "", err + } + answer := core.ManagedRuntimeResolution{Runtimes: []core.ManagedRuntimeInstallation{}, Missing: []string{}} + for _, dependency := range request.Dependencies { + home := request.Candidates[dependency.ID] + if k.settingsHome { + if err := json.Unmarshal(request.Settings["runtimeHome"], &home); err != nil { + return "", err + } + } + if home == "" { + home = k.external[dependency.ID] + } + body, err := os.ReadFile(filepath.Join(home, "payload")) + if home != "" && err == nil && string(body) == "usable" { + if k.canonicalHomes { + home, err = filepath.EvalSymlinks(home) + if err != nil { + return "", err + } + } + answer.Runtimes = append(answer.Runtimes, core.ManagedRuntimeInstallation{ID: dependency.ID, Home: home, Version: dependency.Version}) + } else { + answer.Missing = append(answer.Missing, dependency.ID) + } + } + value, err := json.Marshal(map[string]any{"value": answer}) + if err != nil { + return "", err + } + k.mu.Lock() + queue := k.queues[session] + k.mu.Unlock() + select { + case queue <- core.BackendEvent{Type: "requestCompleted", OperationID: operation, Result: value}: + return operation, nil + case <-ctx.Done(): + return "", ctx.Err() + } +} + +func (k *runtimeResolverKernel) StopPluginBackend(ctx context.Context, session string) error { + k.stops.Add(1) + if k.stop != nil { + return k.stop(ctx, session) + } + return nil +} +func (k *runtimeResolverKernel) DestroyPluginBackend(ctx context.Context, session string) error { + if k.destroy != nil { + if err := k.destroy(ctx, session); err != nil { + return err + } + } + k.mu.Lock() + defer k.mu.Unlock() + if k.queues[session] == nil { + return errors.New("unknown fixture session") + } + delete(k.queues, session) + return nil +} +func (k *runtimeResolverKernel) SetDetailedDiagnostics(context.Context, string, bool) error { + return nil +} + +type runtimeTransport func(*http.Request) (*http.Response, error) + +func (f runtimeTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +func runtimeFixture(t *testing.T) (json.RawMessage, []byte, string) { + t.Helper() + var archive bytes.Buffer + writer := zip.NewWriter(&archive) + file, err := writer.Create("payload") + if err != nil { + t.Fatal(err) + } + if _, err := file.Write([]byte("usable")); err != nil { + t.Fatal(err) + } + if err := writer.Close(); err != nil { + t.Fatal(err) + } + hash := sha256.Sum256(archive.Bytes()) + deps := make([]any, 0, 2) + for _, id := range []string{"alpha", "beta"} { + deps = append(deps, map[string]any{"id": id, "version": "1.0", "artifacts": []any{map[string]any{ + "os": toolchain.PlatformName(runtime.GOOS), "arch": core.PluginArchitecture(), "url": "https://runtimes.example.test/" + id + ".zip", + "sha256": hex.EncodeToString(hash[:]), "archive": "zip", + }}}) + } + manifest, err := json.Marshal(map[string]any{ + "schemaVersion": 0, "pluginAPIVersion": 0, "id": "dev.lithe.test.managed-environment", "displayName": "Environment fixture", "version": "1.0.0", + "requires": map[string]int{"backend": 0, "managedRuntimes": 0}, + "vendor": map[string]string{"id": "org.example", "displayName": "Example", "signatureRequirement": "publisherPackage"}, + "permissions": []string{"backend.launch", "runtimes.install"}, + "backend": map[string]any{"launch": map[string]string{"kind": "packaged", "path": "bin/resolver"}}, + "managedRuntimes": map[string]any{"resolve": map[string]any{"function": "fixture.resolve", "timeoutMilliseconds": 5000}, "dependencies": deps}, + }) + if err != nil { + t.Fatal(err) + } + packageRoot := t.TempDir() + if err := os.MkdirAll(filepath.Join(packageRoot, "bin"), 0o700); err != nil { + t.Fatal(err) + } + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + image, err := os.ReadFile(executable) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(packageRoot, "bin", "resolver"), image, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(packageRoot, "plugin.json"), manifest, 0o600); err != nil { + t.Fatal(err) + } + return manifest, archive.Bytes(), packageRoot +} + +func TestRuntimePreparationReusesExternalAndManagedHomesAcrossUpdates(t *testing.T) { + manifest, archive, packageRoot := runtimeFixture(t) + external := t.TempDir() + if err := os.WriteFile(filepath.Join(external, "payload"), []byte("usable"), 0o600); err != nil { + t.Fatal(err) + } + kernel := &runtimeResolverKernel{Client: core.NewClient(), queues: make(map[string]chan core.BackendEvent), external: map[string]string{"alpha": external}} + service, err := Open(kernel, store.At(t.TempDir()), t.TempDir()) + if err != nil { + t.Fatal(err) + } + var downloads atomic.Int32 + service.RuntimeDownloader = marketplace.NewArchiveDownloader(&http.Client{Transport: runtimeTransport(func(request *http.Request) (*http.Response, error) { + downloads.Add(1) + if request.URL.Path != "/beta.zip" { + return nil, errors.New("eligible external dependency was downloaded") + } + return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(bytes.NewReader(archive)), ContentLength: int64(len(archive)), Request: request}, nil + })}) + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + first, err := service.EnsureRuntimes(ctx, manifest, packageRoot, "dev.lithe.test.managed-environment", "1.0.0", true, nil) + if err != nil { + t.Fatal(err) + } + if downloads.Load() != 1 || first.Runtimes["alpha"].Home != external || len(first.Runtimes) != 2 { + t.Fatalf("first environment=%+v downloads=%d", first, downloads.Load()) + } + updated := bytes.Replace(manifest, []byte(`"version":"1.0.0"`), []byte(`"version":"1.1.0"`), 1) + second, err := service.EnsureRuntimes(ctx, updated, packageRoot, "dev.lithe.test.managed-environment", "1.1.0", true, nil) + if err != nil || downloads.Load() != 1 || second.Runtimes["beta"].Home != first.Runtimes["beta"].Home { + t.Fatalf("update=%+v downloads=%d error=%v", second, downloads.Load(), err) + } + if err := os.WriteFile(filepath.Join(first.Runtimes["beta"].Home, "payload"), []byte("broken"), 0o600); err != nil { + t.Fatal(err) + } + repaired, err := service.EnsureRuntimes(ctx, updated, packageRoot, "dev.lithe.test.managed-environment", "1.1.0", false, nil) + if err != nil || downloads.Load() != 1 || repaired.Runtimes["beta"].Home == first.Runtimes["beta"].Home { + t.Fatalf("offline repair=%+v downloads=%d error=%v", repaired, downloads.Load(), err) + } + if kernel.starts.Load() != 3 || kernel.stops.Load() != 3 { + t.Fatalf("preflight process leak: starts=%d stops=%d", kernel.starts.Load(), kernel.stops.Load()) + } + after, err := os.ReadFile(filepath.Join(packageRoot, "plugin.json")) + if err != nil || !bytes.Equal(after, manifest) { + t.Fatal("preparation modified the approved package") + } +} + +func TestOldPluginDoesNotStartRuntimePreparation(t *testing.T) { + service := &Service{} + if _, err := service.EnsureRuntimes(context.Background(), json.RawMessage(`{"id":"dev.lithe.test.legacy"}`), "", "", "", true, nil); err != nil { + t.Fatal(err) + } +} + +func runtimePayload(t *testing.T) string { + t.Helper() + directory := t.TempDir() + if err := os.WriteFile(filepath.Join(directory, "payload"), []byte("usable"), 0o600); err != nil { + t.Fatal(err) + } + return directory +} + +func installRuntimeFixture(t *testing.T, root, packageRoot string, manifest json.RawMessage) string { + t.Helper() + directory := filepath.Join(root, "dev.lithe.test.managed-environment", "1.0.0") + if err := os.MkdirAll(filepath.Dir(directory), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(packageRoot, pluginpkg.ManifestFile), manifest, 0o600); err != nil { + t.Fatal(err) + } + if err := os.Rename(packageRoot, directory); err != nil { + t.Fatal(err) + } + return directory +} + +func waitRuntimeSignal(t *testing.T, ctx context.Context, done <-chan struct{}, what string) { + t.Helper() + select { + case <-done: + case <-ctx.Done(): + t.Fatalf("waiting for %s: %v", what, ctx.Err()) + } +} + +func joinRuntimeWorker(t *testing.T, done <-chan struct{}, what string) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + select { + case <-done: + case <-ctx.Done(): + t.Errorf("cleanup did not finish %s: %v", what, ctx.Err()) + } +} + +func TestRuntimePreparationAcceptsCanonicalHomeThroughSymlink(t *testing.T) { + manifest, archive, packageRoot := runtimeFixture(t) + root := t.TempDir() + alias := filepath.Join(t.TempDir(), "plugin-root") + if err := os.Symlink(root, alias); err != nil { + if runtime.GOOS == "windows" { + t.Skipf("symlink privilege unavailable: %v", err) + } + t.Fatal(err) + } + kernel := &runtimeResolverKernel{Client: core.NewClient(), queues: make(map[string]chan core.BackendEvent), canonicalHomes: true} + service, err := Open(kernel, store.At(t.TempDir()), alias) + if err != nil { + t.Fatal(err) + } + var downloads atomic.Int32 + service.RuntimeDownloader = marketplace.NewArchiveDownloader(&http.Client{Transport: runtimeTransport(func(request *http.Request) (*http.Response, error) { + downloads.Add(1) + return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(bytes.NewReader(archive)), ContentLength: int64(len(archive)), Request: request}, nil + })}) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + environment, err := service.EnsureRuntimes(ctx, manifest, packageRoot, "dev.lithe.test.managed-environment", "1.0.0", true, nil) + if err != nil || downloads.Load() != 2 || len(environment.Runtimes) != 2 { + t.Fatalf("canonical managed homes=%+v downloads=%d error=%v", environment, downloads.Load(), err) + } + for _, installation := range environment.Runtimes { + canonical, err := filepath.EvalSymlinks(installation.Home) + if err != nil || canonical != installation.Home { + t.Fatalf("resolver did not return its canonical home: %q, %v", installation.Home, err) + } + } +} + +func TestRuntimePreparationUsesEffectiveWorkspaceSettingsSnapshot(t *testing.T) { + manifest, _, packageRoot := runtimeFixture(t) + globalHome, projectHome := runtimePayload(t), runtimePayload(t) + var declaration map[string]any + if err := json.Unmarshal(manifest, &declaration); err != nil { + t.Fatal(err) + } + declaration["requires"].(map[string]any)["settings"] = 0 + declaration["settings"] = []any{map[string]any{"id": "runtimeHome", "type": "directory", "title": "Runtime home", "default": "", "scope": "project"}} + manifest, err := json.Marshal(declaration) + if err != nil { + t.Fatal(err) + } + kernel := &runtimeResolverKernel{Client: core.NewClient(), queues: make(map[string]chan core.BackendEvent), settingsHome: true} + service, err := Open(kernel, store.At(t.TempDir()), t.TempDir()) + if err != nil { + t.Fatal(err) + } + service.RuntimeDownloader = marketplace.NewArchiveDownloader(&http.Client{Transport: runtimeTransport(func(*http.Request) (*http.Response, error) { + return nil, errors.New("effective settings selected a reusable external home; no download is expected") + })}) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + snapshot, err := service.Settings.Load(ctx, manifest, t.TempDir()) + if err != nil { + t.Fatal(err) + } + globalValue, err := json.Marshal(globalHome) + if err != nil { + t.Fatal(err) + } + global, err := service.Settings.Save(ctx, snapshot, "global", []core.PluginSettingEdit{{ID: "runtimeHome", Value: globalValue}}, nil) + if err != nil || global.Readback == nil { + t.Fatalf("global settings save: %+v, %v", global, err) + } + value, err := json.Marshal(projectHome) + if err != nil { + t.Fatal(err) + } + saved, err := service.Settings.Save(ctx, *global.Readback, "project", []core.PluginSettingEdit{{ID: "runtimeHome", Value: value}}, nil) + if err != nil || saved.Readback == nil { + t.Fatalf("workspace settings save: %+v, %v", saved, err) + } + environment, err := service.EnsureRuntimesWithSettings(ctx, manifest, packageRoot, "dev.lithe.test.managed-environment", "1.0.0", false, saved.Readback.State, nil) + if err != nil || environment.Runtimes["alpha"].Home != projectHome || environment.Runtimes["beta"].Home != projectHome { + t.Fatalf("workspace preparation=%+v, error=%v", environment, err) + } + installation, err := service.EnsureRuntimes(ctx, manifest, packageRoot, "dev.lithe.test.managed-environment", "1.0.0", true, nil) + if err != nil || installation.Runtimes["alpha"].Home != globalHome { + t.Fatalf("installation must use global settings: %+v, %v", installation, err) + } +} + +func TestUninstallCancelsOtherWindowPreparationBeforeRemovingFiles(t *testing.T) { + manifest, _, packageRoot := runtimeFixture(t) + root, preferences := t.TempDir(), store.At(t.TempDir()) + kernel := &runtimeResolverKernel{Client: core.NewClient(), queues: make(map[string]chan core.BackendEvent)} + owner, err := Open(kernel, preferences, root) + if err != nil { + t.Fatal(err) + } + other, err := OpenAnother(kernel, preferences, root) + if err != nil { + t.Fatal(err) + } + installed := installRuntimeFixture(t, root, packageRoot, manifest) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + downloadStarted, downloadCancelled, releaseDownload := make(chan struct{}), make(chan struct{}), make(chan struct{}) + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(releaseDownload) }) } + other.RuntimeDownloader = marketplace.NewArchiveDownloader(&http.Client{Transport: runtimeTransport(func(request *http.Request) (*http.Response, error) { + close(downloadStarted) + select { + case <-request.Context().Done(): + close(downloadCancelled) + case <-ctx.Done(): + return nil, ctx.Err() + } + select { + case <-releaseDownload: + return nil, request.Context().Err() + case <-ctx.Done(): + return nil, ctx.Err() + } + })}) + preparationDone := make(chan struct{}) + var preparationErr error + go func() { + defer close(preparationDone) + _, preparationErr = other.EnsureRuntimes(ctx, manifest, installed, "dev.lithe.test.managed-environment", "1.0.0", true, nil) + }() + t.Cleanup(func() { cancel(); release(); joinRuntimeWorker(t, preparationDone, "cancelled preparation") }) + waitRuntimeSignal(t, ctx, downloadStarted, "dependency download") + uninstallDone := make(chan struct{}) + var uninstallErr error + go func() { + defer close(uninstallDone) + uninstallErr = owner.Uninstall(ctx, "dev.lithe.test.managed-environment", nil) + }() + t.Cleanup(func() { cancel(); release(); joinRuntimeWorker(t, uninstallDone, "uninstall") }) + waitRuntimeSignal(t, ctx, downloadCancelled, "uninstall cancelling the other window") + if _, err := os.Stat(installed); err != nil { + t.Fatalf("package removed before preparation released its files: %v", err) + } + if _, _, err := other.BeginRuntimeInstallation(ctx, "dev.lithe.test.managed-environment"); !errors.Is(err, ErrRuntimeBusy) { + t.Fatalf("approved installation bypassed ongoing uninstall: %v", err) + } + release() + waitRuntimeSignal(t, ctx, preparationDone, "preparation cleanup") + waitRuntimeSignal(t, ctx, uninstallDone, "uninstall completion") + if uninstallErr != nil || !errors.Is(preparationErr, context.Canceled) { + t.Fatalf("uninstall=%v preparation=%v", uninstallErr, preparationErr) + } + if kernel.starts.Load() != 1 || kernel.stops.Load() != 1 { + t.Fatalf("checker process leak: starts=%d stops=%d", kernel.starts.Load(), kernel.stops.Load()) + } + if _, err := os.Stat(pluginpkg.StateRoot(root, "dev.lithe.test.managed-environment")); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("preparation recreated removed state: %v", err) + } + if err := other.AllowRuntimePreparation("dev.lithe.test.managed-environment"); err != nil { + t.Fatalf("completed uninstall did not permit a later explicit installation: %v", err) + } +} + +func TestRuntimePreparationOwnsLanguageServerStartUntilCancelledProcessStops(t *testing.T) { + manifest, archive, packageRoot := runtimeFixture(t) + var declaration map[string]any + if err := json.Unmarshal(manifest, &declaration); err != nil { + t.Fatal(err) + } + requirements := declaration["requires"].(map[string]any) + requirements["languages"], requirements["languageServers"] = 0, 0 + declaration["permissions"] = []string{"backend.launch", "runtimes.install", "languageServer.launch"} + declaration["activationEvents"] = []string{"onLanguage:fixture"} + declaration["languages"] = []any{map[string]any{"id": "fixture", "displayName": "Fixture", "fileExtensions": []string{"fixture"}}} + declaration["languageServers"] = []any{map[string]any{"languageID": "fixture", "launch": map[string]string{"kind": "packaged", "path": "bin/resolver"}}} + manifest, err := json.Marshal(declaration) + if err != nil { + t.Fatal(err) + } + kernel := &runtimeResolverKernel{Client: core.NewClient(), queues: make(map[string]chan core.BackendEvent)} + service, err := Open(kernel, store.At(t.TempDir()), t.TempDir()) + if err != nil { + t.Fatal(err) + } + installed := installRuntimeFixture(t, service.Root, packageRoot, manifest) + waitCtx, cancelWait := context.WithTimeout(context.Background(), 10*time.Second) + defer cancelWait() + work, cancelWork := context.WithCancel(context.Background()) + defer cancelWork() + startEntered, startCancelled, releaseStart := make(chan struct{}), make(chan struct{}), make(chan struct{}) + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(releaseStart) }) } + var downloadHasDeadline, processHasBudget atomic.Bool + service.RuntimeDownloader = marketplace.NewArchiveDownloader(&http.Client{Transport: runtimeTransport(func(request *http.Request) (*http.Response, error) { + if _, present := request.Context().Deadline(); present { + downloadHasDeadline.Store(true) + } + return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(bytes.NewReader(archive)), ContentLength: int64(len(archive)), Request: request}, nil + })}) + kernel.start = func(ctx context.Context, request core.PluginBackendStart) error { + if request.Role != "language-server" { + return nil + } + deadline, present := ctx.Deadline() + processHasBudget.Store(present && time.Until(deadline) > 0 && time.Until(deadline) <= 2*time.Minute) + close(startEntered) + select { + case <-ctx.Done(): + close(startCancelled) + case <-waitCtx.Done(): + return waitCtx.Err() + } + // Native process creation can complete after cancellation. The service + // must still stop that process before uninstall may remove the executable. + select { + case <-releaseStart: + return nil + case <-waitCtx.Done(): + return waitCtx.Err() + } + } + entry := pluginmanager.Entry{Installed: pluginpkg.Installed{ID: "dev.lithe.test.managed-environment", Version: "1.0.0", Path: installed}, Enabled: true} + startDone := make(chan struct{}) + var startErr error + go func() { + defer close(startDone) + _, startErr = service.StartLanguageServer(work, []pluginmanager.Entry{entry}, "fixture", BackendRequest{Architecture: core.PluginArchitecture()}) + }() + t.Cleanup(func() { cancelWork(); release(); joinRuntimeWorker(t, startDone, "late language-server start") }) + select { + case <-startEntered: + case <-startDone: + t.Fatalf("language-server start ended before native launch: %v", startErr) + case <-waitCtx.Done(): + t.Fatalf("waiting for native language-server start: %v", waitCtx.Err()) + } + uninstallDone := make(chan struct{}) + var uninstallErr error + go func() { defer close(uninstallDone); uninstallErr = service.Uninstall(waitCtx, entry.Installed.ID, nil) }() + t.Cleanup(func() { cancelWork(); release(); joinRuntimeWorker(t, uninstallDone, "language-server uninstall") }) + waitRuntimeSignal(t, waitCtx, startCancelled, "native start cancellation") + if _, err := os.Stat(installed); err != nil { + t.Fatalf("uninstall removed an in-flight process image: %v", err) + } + release() + waitRuntimeSignal(t, waitCtx, startDone, "cancelled process disposal") + waitRuntimeSignal(t, waitCtx, uninstallDone, "safe file removal") + if uninstallErr != nil || !errors.Is(startErr, context.Canceled) || kernel.starts.Load() != 2 || kernel.stops.Load() != 2 { + t.Fatalf("uninstall=%v start=%v starts=%d stops=%d", uninstallErr, startErr, kernel.starts.Load(), kernel.stops.Load()) + } + if downloadHasDeadline.Load() || !processHasBudget.Load() { + t.Fatalf("download total deadline=%v process bounded=%v", downloadHasDeadline.Load(), processHasBudget.Load()) + } +} + +func TestRuntimeInstallationAdmissionCoversPublicationAfterPreparation(t *testing.T) { + manifest, _, packageRoot := runtimeFixture(t) + kernel := &runtimeResolverKernel{Client: core.NewClient(), queues: make(map[string]chan core.BackendEvent)} + service, err := Open(kernel, store.At(t.TempDir()), t.TempDir()) + if err != nil { + t.Fatal(err) + } + installed := installRuntimeFixture(t, service.Root, packageRoot, manifest) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + work, finish, err := service.BeginRuntimeInstallation(ctx, "dev.lithe.test.managed-environment") + if err != nil { + t.Fatal(err) + } + var finishOnce sync.Once + release := func() { finishOnce.Do(finish) } + t.Cleanup(release) + // Preparation has finished, but the approved operation still owns publication. + uninstallDone := make(chan struct{}) + var uninstallErr error + go func() { + defer close(uninstallDone) + uninstallErr = service.Uninstall(ctx, "dev.lithe.test.managed-environment", nil) + }() + t.Cleanup(func() { cancel(); release(); joinRuntimeWorker(t, uninstallDone, "publication cancellation") }) + waitRuntimeSignal(t, ctx, work.Done(), "installation cancellation") + if _, err := os.Stat(installed); err != nil { + t.Fatalf("uninstall did not wait for the publication owner: %v", err) + } + // An atomic publication already past its cancellation check may still finish. + // Core must take the uninstall snapshot after this owner releases the files. + published := filepath.Join(service.Root, "dev.lithe.test.managed-environment", "1.1.0") + if err := os.MkdirAll(published, 0o700); err != nil { + t.Fatal(err) + } + updated := bytes.Replace(manifest, []byte(`"version":"1.0.0"`), []byte(`"version":"1.1.0"`), 1) + if err := os.WriteFile(filepath.Join(published, pluginpkg.ManifestFile), updated, 0o600); err != nil { + t.Fatal(err) + } + release() + waitRuntimeSignal(t, ctx, uninstallDone, "uninstall after publication ownership ended") + if uninstallErr != nil { + t.Fatal(uninstallErr) + } + if _, err := os.Stat(published); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("uninstall planned before the final publication and left its package: %v", err) + } +} + +func TestRuntimeCheckerCleanupFailureRemainsOwnedUntilRetry(t *testing.T) { + manifest, _, packageRoot := runtimeFixture(t) + home := runtimePayload(t) + kernel := &runtimeResolverKernel{Client: core.NewClient(), queues: make(map[string]chan core.BackendEvent), external: map[string]string{"alpha": home, "beta": home}} + var failStop atomic.Bool + failStop.Store(true) + stopFailure := errors.New("fixture native stop failed") + kernel.stop = func(context.Context, string) error { + if failStop.Load() { + return stopFailure + } + return nil + } + kernel.destroy = kernel.stop + kernel.waitError = func(string) error { + if kernel.stops.Load() > 0 && failStop.Load() { + return stopFailure + } + return nil + } + service, err := Open(kernel, store.At(t.TempDir()), t.TempDir()) + if err != nil { + t.Fatal(err) + } + installed := installRuntimeFixture(t, service.Root, packageRoot, manifest) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + t.Cleanup(func() { + failStop.Store(false) + cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cleanupCancel() + if err := service.StopDisplaced(cleanupCtx, "dev.lithe.test.managed-environment", nil); err != nil { + t.Errorf("cleanup retained checker: %v", err) + } + }) + if _, err := service.EnsureRuntimes(ctx, manifest, installed, "dev.lithe.test.managed-environment", "1.0.0", true, nil); !errors.Is(err, stopFailure) { + t.Fatalf("lost native stop failure: %v", err) + } + if err := service.Uninstall(ctx, "dev.lithe.test.managed-environment", nil); !errors.Is(err, stopFailure) { + t.Fatalf("uninstall ignored owned process failure: %v", err) + } + if _, err := os.Stat(installed); err != nil { + t.Fatalf("failed stop removed the package: %v", err) + } + failStop.Store(false) + if err := service.Uninstall(ctx, "dev.lithe.test.managed-environment", nil); err != nil { + t.Fatalf("retry did not finish native cleanup: %v", err) + } + if _, err := os.Stat(installed); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("successful retry did not remove the package: %v", err) + } +} + +func TestDisposedRuntimeCheckerRecordsShutdownFailureWithoutRetainingOwnership(t *testing.T) { + manifest, _, packageRoot := runtimeFixture(t) + home := runtimePayload(t) + kernel := &runtimeResolverKernel{Client: core.NewClient(), queues: make(map[string]chan core.BackendEvent), external: map[string]string{"alpha": home, "beta": home}} + stopFailure := errors.New("fixture graceful shutdown failed") + kernel.stop = func(context.Context, string) error { return stopFailure } + service, err := Open(kernel, store.At(t.TempDir()), t.TempDir()) + if err != nil { + t.Fatal(err) + } + installed := installRuntimeFixture(t, service.Root, packageRoot, manifest) + var reported atomic.Int32 + service.RuntimeIssue = func(_ context.Context, err error) { + if errors.Is(err, stopFailure) { + reported.Add(1) + } + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if _, err := service.EnsureRuntimes(ctx, manifest, installed, "dev.lithe.test.managed-environment", "1.0.0", true, nil); err != nil { + t.Fatalf("disposed checker retained ownership: %v", err) + } + if err := service.Uninstall(ctx, "dev.lithe.test.managed-environment", nil); err != nil { + t.Fatalf("uninstall retried an already-destroyed session: %v", err) + } + if reported.Load() != 1 || kernel.stops.Load() != 1 { + t.Fatalf("shutdown diagnostic=%d native stops=%d", reported.Load(), kernel.stops.Load()) + } +} + +func TestRuntimeLanguageServerOwnershipSurvivesFailedDisposal(t *testing.T) { + kernel := &runtimeResolverKernel{Client: core.NewClient(), queues: make(map[string]chan core.BackendEvent)} + service, err := Open(kernel, store.At(t.TempDir()), t.TempDir()) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + started, err := kernel.StartPluginLanguageServer(ctx, core.PluginBackendStart{}) + if err != nil { + t.Fatal(err) + } + var failStop atomic.Bool + failStop.Store(true) + stopFailure := errors.New("fixture process still owns files") + kernel.stop = func(context.Context, string) error { + if failStop.Load() { + return stopFailure + } + return nil + } + kernel.destroy = kernel.stop + kernel.waitError = func(string) error { + if failStop.Load() { + return stopFailure + } + return nil + } + temporary := filepath.Join(t.TempDir(), "active-server") + if err := os.MkdirAll(temporary, 0o700); err != nil { + t.Fatal(err) + } + session := &LanguageSession{PluginID: "dev.lithe.test.managed-environment", LanguageID: "fixture", Session: pluginbackend.Session{ID: started.SessionID}, temporary: temporary} + service.registerLanguageSession(session) + t.Cleanup(func() { + failStop.Store(false) + cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cleanupCancel() + if err := service.StopDisplaced(cleanupCtx, session.PluginID, nil); err != nil { + t.Errorf("retained language-server cleanup: %v", err) + } + }) + if err := service.StopLanguageServer(ctx, session); !errors.Is(err, stopFailure) { + t.Fatalf("failed native stop=%v", err) + } + if _, err := os.Stat(temporary); err != nil { + t.Fatalf("failed stop removed live process state: %v", err) + } + failStop.Store(false) + if err := service.StopDisplaced(ctx, session.PluginID, nil); err != nil { + t.Fatalf("plugin stop did not retry its retained language server: %v", err) + } + if _, err := os.Stat(temporary); !errors.Is(err, os.ErrNotExist) || kernel.stops.Load() != 2 { + t.Fatalf("late cleanup state=%v stops=%d", err, kernel.stops.Load()) + } +} From a6ab6e59119b6a94169dd950bd0a19ae597b3a36 Mon Sep 17 00:00:00 2001 From: "lithe-support[bot]" <356900028+lithe-support[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:26:04 +0000 Subject: [PATCH 17/20] fix(workbench): bind queued startup to its captured workspace --- .../pluginservice/settings_start_test.go | 4 +- .../pluginservice/workspace_lifecycle_test.go | 89 +++++++++++++++++++ desktop/internal/workbench/app.go | 7 +- desktop/internal/workbench/pluginbackends.go | 12 +-- 4 files changed, 105 insertions(+), 7 deletions(-) create mode 100644 desktop/internal/pluginservice/workspace_lifecycle_test.go diff --git a/desktop/internal/pluginservice/settings_start_test.go b/desktop/internal/pluginservice/settings_start_test.go index 1222aaae8..82baaa429 100644 --- a/desktop/internal/pluginservice/settings_start_test.go +++ b/desktop/internal/pluginservice/settings_start_test.go @@ -88,7 +88,9 @@ func TestLanguageServerReadsActualPluginPreferenceLayersBeforePlanning(t *testin t.Fatal(err) } entry := pluginmanager.Entry{Enabled: true, Installed: pluginpkg.Installed{ID: "dev.example.settings", Version: "1.0.0", Path: packageRoot}} - _, err = service.StartLanguageServer(ctx, []pluginmanager.Entry{entry}, "fixture", BackendRequest{WorkingDirectory: workspace, Architecture: core.PluginArchitecture()}) + workspaceContext := service.Contexts.Open(workspace) + t.Cleanup(service.Contexts.CloseAll) + _, err = service.StartLanguageServer(ctx, []pluginmanager.Entry{entry}, "fixture", BackendRequest{WorkingDirectory: workspace, Context: workspaceContext.ContextRef, Architecture: core.PluginArchitecture()}) if malformed { if err == nil || kernel.planned != 0 { t.Fatalf("malformed settings reached process planning: plans=%d, error=%v", kernel.planned, err) diff --git a/desktop/internal/pluginservice/workspace_lifecycle_test.go b/desktop/internal/pluginservice/workspace_lifecycle_test.go new file mode 100644 index 000000000..3aa35922f --- /dev/null +++ b/desktop/internal/pluginservice/workspace_lifecycle_test.go @@ -0,0 +1,89 @@ +package pluginservice + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginmanager" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" +) + +// A queued task retains the identity from before close. Reopening the same path +// is a new owner; neither delayed activation nor an LSP start may adopt it. +func TestDelayedWorkspaceTasksDoNotReopenOrAdoptAnotherContext(t *testing.T) { + for _, consumer := range []string{"activation", "language-server"} { + for _, transition := range []string{"open", "closed", "reopened"} { + t.Run(consumer+"/"+transition, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + planned := errors.New("test stopped at language-server planning") + kernel := &fakeKernel{planErr: planned} + preferences := store.At(t.TempDir()) + service, err := Open(kernel, preferences, t.TempDir()) + if err != nil { + t.Fatal(err) + } + // This test controls the lifecycle directly, without notification work. + service.Contexts.SetObserver(nil) + t.Cleanup(service.Contexts.CloseAll) + peer, err := OpenAnother(kernel, preferences, service.Root) + if err != nil { + t.Fatal(err) + } + peer.Contexts.SetObserver(nil) + t.Cleanup(peer.Contexts.CloseAll) + peerRoot := t.TempDir() + peer.Contexts.Open(peerRoot) + root := t.TempDir() + captured := service.Contexts.Open(root) + current := captured + if transition != "open" { + service.DetachWorkspaces()() + } + if transition == "reopened" { + current = service.Contexts.Open(root) + if current.ContextRef == captured.ContextRef { + t.Fatal("reopening reused a closed workspace identity") + } + } + if consumer == "activation" { + err = service.ActivateWorkspace(ctx, nil, captured.ContextRef) + } else { + _, err = service.StartLanguageServer(ctx, []pluginmanager.Entry{languageServerEntry(t)}, "go", BackendRequest{ + WorkingDirectory: root, Context: captured.ContextRef, Architecture: core.PluginArchitecture(), + }) + } + want := ErrContextExpired + if transition == "open" { + want = nil + if consumer == "language-server" { + want = planned + } + } + if !errors.Is(err, want) { + t.Errorf("queued %s with %s context = %v, want %v", consumer, transition, err, want) + } + opened, exists := service.Contexts.ByPath(root) + wantRoots := 2 + if transition == "closed" { + wantRoots = 1 + if exists { + t.Fatal("a delayed task retained the closed workspace root") + } + } else if !exists || opened.ContextRef != current.ContextRef { + t.Fatalf("a delayed task replaced the current workspace: %+v, want %+v", opened, current) + } + if roots := peer.Contexts.workspaceRoots(); len(roots) != wantRoots { + t.Fatalf("a delayed task changed another workbench's root snapshot: %v", roots) + } + service.Contexts.CloseAll() + if roots := peer.Contexts.workspaceRoots(); len(roots) != 1 || roots[0] != peerRoot { + t.Fatalf("closing one workbench removed or leaked another owner's roots: %v", roots) + } + }) + } + } +} diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 9a4ec8dd2..59288b8c8 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -426,6 +426,8 @@ const ( type project struct { // root is the absolute, cleaned path of the project folder. root string + // pluginContext belongs to this open project, not to any background consumer. + pluginContext pluginservice.ContextRef // indexing is the search exclusion policy the project installed in Core (directory_exclusions.go). indexing projectIndexing // name is the folder's name, shown in the title bar. @@ -1493,6 +1495,9 @@ func (a *App) openProjectHere(path string) { a.openTerminals(p) a.project = p a.ideAPISetProject(p) + if a.plugins != nil && a.plugins.Contexts != nil { + p.pluginContext = a.plugins.Contexts.Open(root).ContextRef + } rootCopy := root a.toolchainRoot.Store(&rootCopy) a.notice = "" @@ -1502,7 +1507,7 @@ func (a *App) openProjectHere(path string) { a.loadGit(p) a.startGitObservation(p) a.loadLog(p) - a.activatePluginWorkspace(root) + a.activatePluginWorkspace(p) a.restoreEditorSession(p) a.restoreCheckpoints(p) a.restoreNativePanels(p) diff --git a/desktop/internal/workbench/pluginbackends.go b/desktop/internal/workbench/pluginbackends.go index 3fbfc79b9..aed7dd857 100644 --- a/desktop/internal/workbench/pluginbackends.go +++ b/desktop/internal/workbench/pluginbackends.go @@ -509,17 +509,18 @@ func (a *App) detachPluginServer(pluginID string) *pluginservice.LanguageSession return session } -// activatePluginWorkspace opens the workspace's context for plugin backends and -// starts the ones that asked for onWorkspaceOpen. It runs after the window shows +// activatePluginWorkspace starts the backends that asked for onWorkspaceOpen +// using the identity the window already owns. It runs after the window shows // the project, off the window thread, so it never delays opening the workspace. -func (a *App) activatePluginWorkspace(root string) { +func (a *App) activatePluginWorkspace(p *project) { if a.plugins == nil { return } - a.background(nil, pluginServerStartTimeout, func(ctx context.Context) func(*App) { + workspace := p.pluginContext + a.background(p, pluginServerStartTimeout, func(ctx context.Context) func(*App) { entries, err := a.plugins.Manager.Installed() if err == nil { - err = a.plugins.ActivateWorkspace(ctx, entries, root) + err = a.plugins.ActivateWorkspace(ctx, entries, workspace) } return func(a *App) { if err != nil { @@ -605,6 +606,7 @@ func (a *App) pluginBackendRequest() pluginservice.BackendRequest { // The root URI is resolved by Core from the absolute path in the start // goroutine; a map here would not fit lsp.startServer's string field. request.WorkingDirectory = a.project.root + request.Context = a.project.pluginContext } return request } From 2670237045a9491d89979a6d9df3447d42632cce Mon Sep 17 00:00:00 2001 From: "lithe-support[bot]" <356900028+lithe-support[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:26:10 +0000 Subject: [PATCH 18/20] fix(plugins): retain workspace identity for shared build launches --- desktop/internal/workbench/build.go | 1 + .../workbench/runtime_preparation_test.go | 37 ++++++++++++++ .../features/plugin-managed-runtimes.json | 48 +++++++++++++++++++ 3 files changed, 86 insertions(+) create mode 100644 shared/platform-feature-matrix/features/plugin-managed-runtimes.json diff --git a/desktop/internal/workbench/build.go b/desktop/internal/workbench/build.go index fd5fb53f4..b31c31573 100644 --- a/desktop/internal/workbench/build.go +++ b/desktop/internal/workbench/build.go @@ -604,6 +604,7 @@ func (a *App) sharedBuildProvider(ctx context.Context, p *project, instance buil session, err := a.plugins.StartLanguageServer(ctx, entries, languageID, pluginservice.BackendRequest{ RootURI: rootURI, WorkingDirectory: p.root, + Context: p.pluginContext, Architecture: core.PluginArchitecture(), }) if err != nil { diff --git a/desktop/internal/workbench/runtime_preparation_test.go b/desktop/internal/workbench/runtime_preparation_test.go index 6f7767305..96c5cc971 100644 --- a/desktop/internal/workbench/runtime_preparation_test.go +++ b/desktop/internal/workbench/runtime_preparation_test.go @@ -2,14 +2,51 @@ package workbench import ( "context" + "errors" "testing" + "time" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginruntime" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" "github.com/1lck/Lithe-IDEA/desktop/internal/settingswindow" ) +func TestPluginWorkspaceRequestKeepsIdentityAcrossReopen(t *testing.T) { + kernel := &testKernel{Client: core.NewClient()} + h := newHarness(t, kernel) + service, err := pluginservice.Open(kernel, h.store, t.TempDir()) + if err != nil { + t.Fatal(err) + } + h.app.plugins = service + root := t.TempDir() + h.open(root) + first := h.app.pluginBackendRequest() + if first.Context.ContextID == "" { + t.Fatal("the project opened before owning its plugin workspace context") + } + h.app.closeProject() + h.settle() + if h.app.project != nil { + t.Fatal("the first project did not close") + } + h.open(root) + second := h.app.pluginBackendRequest() + if first.WorkingDirectory != second.WorkingDirectory || first.Context == second.Context { + t.Fatal("reopening a path reused the previous language-server request identity") + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := h.app.plugins.ActivateWorkspace(ctx, nil, first.Context); !errors.Is(err, pluginservice.ErrContextExpired) { + t.Fatalf("the old queued activation adopted the reopened project: %v", err) + } + if _, err := h.app.plugins.Contexts.Lookup(second.Context); err != nil { + t.Fatalf("a late activation invalidated the new project: %v", err) + } +} + func TestClosingProjectCancelsRuntimePreparationAndIgnoresLateResult(t *testing.T) { h := newHarness(t, &testKernel{Client: core.NewClient()}) h.open(t.TempDir()) diff --git a/shared/platform-feature-matrix/features/plugin-managed-runtimes.json b/shared/platform-feature-matrix/features/plugin-managed-runtimes.json new file mode 100644 index 000000000..b3250da16 --- /dev/null +++ b/shared/platform-feature-matrix/features/plugin-managed-runtimes.json @@ -0,0 +1,48 @@ +{ + "id": "plugin-managed-runtimes", + "area": "插件", + "group": "插件管理", + "capability": "插件声明的受管运行时:安装与升级在程序审批后、提交前由插件检查已有运行时,只下载缺失依赖;宿主按 Core 选择的平台与内容身份校验、解压并保存完整文件,插件升级复用不变的依赖,启动前可修复缺失或损坏。进度可见且可取消,准备失败保留已安装版本;选定运行时只服务这次语言服务器启动,不修改项目工具或全局 SDK。禁用与卸载先停止准备和进程,外部安装不被删除。", + "macos": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/core/managed_runtimes.go", + "desktop/internal/core/managed_runtimes_test.go", + "desktop/internal/pluginruntime/", + "desktop/internal/pluginservice/runtimes.go", + "desktop/internal/pluginservice/runtimes_test.go", + "desktop/internal/pluginservice/runtime_lifecycle.go", + "desktop/internal/pluginbackend/pluginbackend_test.go", + "desktop/internal/settingswindow/plugin_install.go", + "desktop/internal/settingswindow/runtime_visual_test.go", + "desktop/internal/workbench/runtime_preparation_test.go", + ".agents/notes/implemented/architecture/2026-11-18-managed-plugin-runtimes.md", + "desktop/internal/pluginservice/contexts.go", + "desktop/internal/pluginservice/runtime_trust_test.go", + "desktop/internal/toolchain/" + ] + }, + "windows": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/core/managed_runtimes.go", + "desktop/internal/pluginruntime/", + "desktop/internal/pluginruntime/lock_windows.go", + "desktop/internal/pluginservice/runtimes.go", + "desktop/internal/pluginservice/runtime_lifecycle.go", + "desktop/internal/pluginbackend/pluginbackend_test.go", + "desktop/internal/settingswindow/plugin_install.go", + "desktop/internal/workbench/runtime_preparation_test.go", + ".agents/notes/implemented/architecture/2026-11-18-managed-plugin-runtimes.md", + "desktop/internal/pluginservice/contexts.go", + "desktop/internal/pluginservice/runtime_trust_test.go", + "desktop/internal/toolchain/" + ] + }, + "owner": "Plugins", + "verification": "合成插件测试通过真实 Core 清单与回复校验,使用本地传输夹具验证外部安装零下载、仅下载缺失项、插件版本变化不重复下载、缓存破损从已校验归档恢复、哈希与解压路径拒绝、并发和取消、失败不改旧目录以及准备后端不参与函数转发。使用合成可执行文件验证当前与其他已打开项目的 PATH、全局符号链接和检查函数返回路径不会绕过工具信任;绑定工具保持 Core 验证的规范文件与目录身份,工作区关闭后释放根引用。运行 desktop-go.sh test -race ./internal/core/ ./internal/pluginruntime/ ./internal/pluginbackend/ ./internal/pluginservice/,及 -tags vivahead 的 workbench、settingswindow 测试。macOS 与 Windows 真机分别安装声明 managedRuntimes 的插件:缺依赖时看到准备进度,取消和断网保留原插件;完整外部安装不下载;仅更新插件代码不下载依赖;损坏缓存后启动修复;关闭项目、禁用和卸载不残留进程,卸载不删除外部目录;运行前后安装包文件清单一致。原生窗口验收尚未完成。", + "notes": "通用能力 managedRuntimes 0 和权限 runtimes.install;清单、归档选择、缓存键及结果完整性由独立 Core 仓库定义,插件检查版本与目录是否合用。状态在 /.state//runtimes/,与插件版本分开;旧插件不进入新流程。平台实现共用 Go 服务,Windows 使用本机文件锁和可执行文件验证,实机验证状态独立保留为 pending。", + "lastReviewed": "2026-11-18" +} From 3a1ddefeee06524a6e8b411ba3737182a592a1da Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Wed, 18 Nov 2026 02:58:03 -0800 Subject: [PATCH 19/20] test(plugins): align host tests with managed runtimes and workspace identity --- desktop/internal/pluginhost/pluginhost_test.go | 2 +- desktop/internal/workbench/settings_plugin_restart_test.go | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/desktop/internal/pluginhost/pluginhost_test.go b/desktop/internal/pluginhost/pluginhost_test.go index f068fc197..130716095 100644 --- a/desktop/internal/pluginhost/pluginhost_test.go +++ b/desktop/internal/pluginhost/pluginhost_test.go @@ -60,7 +60,7 @@ func TestDeclaredServesTheBaselineOfEveryWiredCapability(t *testing.T) { declared := Declared() want := []string{ "backend", "buildProviders", "buildSystems", "commandInstallers", "debugAdapters", - "languageServers", "languages", "outputLinkMatchers", "pluginFunctions", + "languageServers", "languages", "managedRuntimes", "outputLinkMatchers", "pluginFunctions", "projectGenerators", "runConfigurationTypes", "settings", "sourceSettings", "toolDefinitions", "ui", "vcsProviders", } diff --git a/desktop/internal/workbench/settings_plugin_restart_test.go b/desktop/internal/workbench/settings_plugin_restart_test.go index 510109061..17035bd66 100644 --- a/desktop/internal/workbench/settings_plugin_restart_test.go +++ b/desktop/internal/workbench/settings_plugin_restart_test.go @@ -82,6 +82,10 @@ func TestPluginSettingsRestartWaitsForTeardownAndHonorsRevocation(t *testing.T) t.Fatal(err) } h.app.plugins = service + // The service is attached after the project opened, so give the + // project the workspace identity opening would have registered; + // a replacement start is refused without it. + p.pluginContext = service.Contexts.Open(p.root).ContextRef session := &pluginservice.LanguageSession{PluginID: "dev.example.settings", Version: "1.0.0", LanguageID: "fixture", Session: pluginbackend.Session{ID: "old-session"}} server := &pluginServer{session: session, project: p, cancel: func() {}, done: kernel.destroyed} h.app.pluginServers = map[string]*pluginServer{session.PluginID: server} From 35c92868e9d53a3ba154edf1f642365ff2b248b6 Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Wed, 18 Nov 2026 03:14:17 -0800 Subject: [PATCH 20/20] build(core): pin the merged managed runtimes contract (Lithe-core-rust#96) Co-Authored-By: Claude Opus 5.5 --- scripts/desktop/build-desktop-core.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 6ae408e29..7c41ae4f0 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -245,7 +245,7 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # the contract, plugin guides, reference and SDKs live only in shared/plugins; on top of #16 (reported Git queries folded in the console), # #15 (git.write cherryPick, revert and reset fields), #14 (word-level changed ranges of diff # rows), #13, #8, #7, #6 and #4. -PINNED_CORE_REVISION="c08330dcc73d7b3e3b7b8f735ad441e0c97e5133" +PINNED_CORE_REVISION="7f1fc4becd0b4b415aa463abd0ea5e2810b3e964" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in