diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 58588f5490..1d694a9561 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -208,11 +208,15 @@ jobs: - run: pnpm build e2e: - name: E2E + name: E2E (${{ matrix.shard }}/2) needs: changes if: needs.changes.outputs.frontend == 'true' timeout-minutes: 30 runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + shard: [1, 2] # Browsers and their system libraries are preinstalled; keep the tag in step with @playwright/test. container: mcr.microsoft.com/playwright:v1.64.1-noble steps: @@ -222,12 +226,12 @@ jobs: - uses: actions/setup-node@v5 with: { node-version: 22, cache: pnpm } - run: pnpm install --frozen-lockfile - - run: pnpm e2e + - run: pnpm e2e --shard=${{ matrix.shard }}/2 env: HOME: /root - uses: actions/upload-artifact@v6 if: failure() with: - name: playwright-report + name: playwright-report-${{ matrix.shard }} path: playwright-report/ retention-days: 7 diff --git a/.github/workflows/release-build.yml b/.github/workflows/release-build.yml index 3943e2701c..d36896f2e5 100644 --- a/.github/workflows/release-build.yml +++ b/.github/workflows/release-build.yml @@ -262,26 +262,46 @@ jobs: } // The update's notes: the release body without its Download section. That // section only matters on the release page, and What's new follows it. + // A translated section, "## 中文" added at the end of the draft before it is + // published (it runs to the next heading of its level, or the end), becomes + // `notes.zh-CN`: What's new shows it in that UI language and falls back to + // `notes`, the English rest of the body. HTML comments are dropped. const { data: release } = await github.rest.repos.getRelease({ owner, repo, release_id }); - const withoutDownloadSection = (body) => { - const kept = []; + const languages = { "中文": "zh-CN" }; + const notesByLanguage = (body) => { + const parts = { "": [] }; + let lang = ""; + let langLevel = 0; let skip = 0; - for (const line of body.split(/\r?\n/)) { + for (const line of body.replace(//g, "").split(/\r?\n/)) { const heading = /^(#{1,6})\s+(.*)$/.exec(line); if (heading) { const level = heading[1].length; - if (!skip && level <= 3 && /^download$/i.test(heading[2].trim())) { + const title = heading[2].trim(); + if (skip && level <= skip) skip = 0; + if (lang && level <= langLevel) lang = ""; + if (!skip && level <= 3 && /^download$/i.test(title)) { skip = level; continue; } - if (skip && level <= skip) skip = 0; + if (!skip && !lang && level <= 2 && languages[title]) { + lang = languages[title]; + langLevel = level; + parts[lang] ??= []; + continue; + } } - if (!skip) kept.push(line); + if (!skip) parts[lang].push(line); } - return kept.join("\n").trim(); + return Object.fromEntries(Object.entries(parts).map(([key, lines]) => [key, lines.join("\n").trim()])); + }; + const { "": notes, ...translated } = notesByLanguage(String(release.body ?? "")); + const translations = Object.fromEntries( + Object.entries(translated).filter(([, text]) => text).map(([lang, text]) => [`notes.${lang}`, text]), + ); + const manifest = { + version: tag.replace(/^v/, ""), notes, ...translations, pub_date: new Date().toISOString(), platforms, }; - const notes = withoutDownloadSection(String(release.body ?? "")); - const manifest = { version: tag.replace(/^v/, ""), notes, pub_date: new Date().toISOString(), platforms }; const old = assets.find((a) => a.name === "latest.json"); if (old) await github.rest.repos.deleteReleaseAsset({ owner, repo, asset_id: old.id }); await github.rest.repos.uploadReleaseAsset({ diff --git a/crates/ide-host/src/mcp/http.rs b/crates/ide-host/src/mcp/http.rs new file mode 100644 index 0000000000..ead8534823 --- /dev/null +++ b/crates/ide-host/src/mcp/http.rs @@ -0,0 +1,252 @@ +//! HTTP Client tools: list and run requests from project `.http` / `.rest` files. + +use crate::mcp::tool::{Call, Output, Param, ParamType, Tool}; +use ide_core::{IdeError, IdeResult}; +use serde_json::json; +use std::path::Path; + +/// Response body characters returned at most (keeps agent context bounded). +const MAX_BODY_CHARS: usize = 8_192; + +pub fn tools() -> Vec { + vec![http_list_requests(), http_run_request()] +} + +fn is_http_file(path: &Path) -> bool { + path.extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| e.eq_ignore_ascii_case("http") || e.eq_ignore_ascii_case("rest")) +} + +async fn resolve_http_file(call: &Call, path: &str) -> IdeResult { + let path = call.resolve_inside(path)?; + if !is_http_file(&path) { + return Err(IdeError::invalid("path must be a .http or .rest file")); + } + if !path.is_file() { + return Err(IdeError::not_found(format!("No such file: {}", call.display(&path)))); + } + Ok(path) +} + +fn http_list_requests() -> Tool { + Tool::new( + "http_list_requests", + "Lists the HTTP requests in a project `.http` or `.rest` file (IntelliJ-style HTTP Client). +Returns each request's 0-based `index`, optional `name`, `method`, URL as written (variables not substituted), and `line`. +Use `http_run_request` with the same `path` and an `index` to send one.", + |call| async move { + let path = resolve_http_file(&call, &call.str("path")?).await?; + let text = crate::ops::fs::read_text(&call.host(), call.window(), path).await?; + let requests: Vec<_> = ide_http::parse::requests(&text) + .into_iter() + .map(|b| { + json!({ + "index": b.index, + "name": b.name, + "method": b.method, + "url": b.url, + "line": b.line, + }) + }) + .collect(); + Output::json(json!({ "requests": requests })) + }, + ) + .param(Param::required( + "path", + ParamType::String, + "Project-relative path to a `.http` or `.rest` file", + )) + .output(json!({ + "type": "object", + "properties": { + "requests": { + "type": "array", + "items": { + "type": "object", + "properties": { + "index": { "type": "integer" }, + "name": { "type": ["string", "null"] }, + "method": { "type": "string" }, + "url": { "type": "string" }, + "line": { "type": "integer" }, + }, + "required": ["index", "method", "url", "line"], + }, + }, + }, + "required": ["requests"], + })) +} + +fn truncate_chars(text: &str, max: usize) -> (String, bool) { + let count = text.chars().count(); + if count <= max { + return (text.to_owned(), false); + } + (text.chars().take(max).collect(), true) +} + +/// Drop resolved URLs from transport errors so MCP JSON does not echo env-substituted targets. +fn redact_transport_error(error: Option, resolved_url: &str) -> Option { + let error = error?; + let mut out = error.replace(resolved_url, ""); + // reqwest often embeds `https://host/...` even when the primary URL string differs slightly. + out = redact_urls(&out); + Some(out) +} + +fn redact_urls(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut rest = s; + loop { + // Prefer `https://` so we don't match the `http://` prefix inside it. + let start = match (rest.find("https://"), rest.find("http://")) { + (Some(a), Some(b)) => Some(a.min(b)), + (Some(a), None) => Some(a), + (None, Some(b)) => Some(b), + (None, None) => None, + }; + let Some(start) = start else { + out.push_str(rest); + break; + }; + out.push_str(&rest[..start]); + out.push_str(""); + let after = &rest[start..]; + let end = after.find(|c: char| c.is_whitespace() || c == '\'' || c == '"' || c == ')').unwrap_or(after.len()); + rest = &after[end..]; + } + out +} + +fn http_run_request() -> Tool { + Tool::new( + "http_run_request", + "Runs one request from a project `.http` or `.rest` file by 0-based `index`, using the IDE HTTP Client +(same as Run Request in the editor). Variables resolve from `http-client.env.json` / `http-client.private.env.json` +for the optional `env` name. Asks for confirmation with the resolved URL (and header names) first. +Returns status, timing and a truncated response body — not request headers or body (those may hold secrets). +The `url` field in the result is as written in the file (unsubstituted); transport errors redact URLs.", + |call| async move { + let rel = call.str("path")?; + let path = resolve_http_file(&call, &rel).await?; + let index = + call.opt_i64("index")?.ok_or_else(|| IdeError::invalid("missing or invalid argument `index`"))?; + if index < 0 { + return Err(IdeError::invalid("index must be >= 0")); + } + let index = index as u32; + let env = call.opt_str("env")?; + let text = crate::ops::fs::read_text(&call.host(), call.window(), path.clone()).await?; + let blocks = ide_http::parse::requests(&text); + let block = + blocks.get(index as usize).ok_or_else(|| IdeError::not_found(format!("no request #{}", index + 1)))?; + + let input = ide_http::RunInput { + text: &text, + index, + file: Some(&path), + root: Some(call.root()), + env: env.as_deref(), + }; + // Prepare before confirm so the dialog shows the real destination (after env substitution). + let prepared = ide_http::prepare(&input)?; + let subject = prepared.name.clone().unwrap_or_else(|| format!("{} {}", prepared.method, prepared.url)); + let headers: Vec<_> = prepared.headers.iter().map(|(k, _)| k.as_str()).collect(); + let mut detail = format!("{} {}\nFile: {rel}\nIndex: {index}", prepared.method, prepared.url); + if let Some(env) = &env { + detail.push_str(&format!("\nEnvironment: {env}")); + } + if !headers.is_empty() { + detail.push_str(&format!("\nHeaders: {}", headers.join(", "))); + } + if prepared.body.is_some() { + detail.push_str("\nBody: present"); + } + call.confirm(&subject, Some(detail)).await?; + + let exchange = ide_http::run(input, &call.cancel).await?; + let history = call.project().http_history.clone(); + let saved = exchange.clone(); + let _ = call.host().blocking(move || history.add(&saved)).await; + + let (body, body_truncated) = match exchange.response.as_ref().and_then(|r| r.body.as_deref()) { + Some(b) => { + let (t, truncated) = truncate_chars(b, MAX_BODY_CHARS); + (Some(t), truncated) + } + None => (None, false), + }; + let response = exchange.response.as_ref(); + Output::json(json!({ + "index": index, + "name": block.name, + "method": block.method, + "url": block.url, + "status": response.map(|r| r.status), + "statusText": response.map(|r| r.status_text.clone()), + "totalMs": response.map(|r| r.total_ms).or(exchange.entry.total_ms), + "error": redact_transport_error(exchange.entry.error.clone(), &prepared.url), + "body": body, + "bodyTruncated": body_truncated, + })) + }, + ) + .write() + .param(Param::required("path", ParamType::String, "Project-relative path to a `.http` or `.rest` file")) + .param(Param::required("index", ParamType::Integer, "0-based request index from `http_list_requests`")) + .param(Param::optional( + "env", + ParamType::String, + "Environment name from `http-client.env.json` / `http-client.private.env.json`", + )) + .output(json!({ + "type": "object", + "properties": { + "index": { "type": "integer" }, + "name": { "type": ["string", "null"] }, + "method": { "type": "string" }, + "url": { "type": "string" }, + "status": { "type": ["integer", "null"] }, + "statusText": { "type": ["string", "null"] }, + "totalMs": { "type": ["number", "null"] }, + "error": { "type": ["string", "null"] }, + "body": { "type": ["string", "null"] }, + "bodyTruncated": { "type": "boolean" }, + }, + "required": ["index", "method", "url", "bodyTruncated"], + })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn accepts_http_and_rest_extensions() { + assert!(is_http_file(Path::new("a.http"))); + assert!(is_http_file(Path::new("a.REST"))); + assert!(!is_http_file(Path::new("a.txt"))); + } + + #[test] + fn truncates_long_bodies() { + let long = "x".repeat(MAX_BODY_CHARS + 10); + let (t, truncated) = truncate_chars(&long, MAX_BODY_CHARS); + assert!(truncated); + assert_eq!(t.chars().count(), MAX_BODY_CHARS); + assert_eq!(truncate_chars("ok", MAX_BODY_CHARS), ("ok".into(), false)); + } + + #[test] + fn redacts_urls_in_transport_errors() { + let url = "https://secret.example/v1?token=abc"; + assert_eq!( + redact_transport_error(Some(format!("error sending request for {url}")), url).as_deref(), + Some("error sending request for ") + ); + assert_eq!(redact_urls("fail https://a.example/x and http://b/y"), "fail and "); + } +} diff --git a/crates/ide-host/src/mcp/mod.rs b/crates/ide-host/src/mcp/mod.rs index 4f9306fc74..262eb1998f 100644 --- a/crates/ide-host/src/mcp/mod.rs +++ b/crates/ide-host/src/mcp/mod.rs @@ -7,6 +7,7 @@ pub(crate) mod run; mod vcs; pub use requests::Requests; mod files; +mod http; mod page; mod reports; mod search; @@ -39,6 +40,7 @@ fn tools() -> Vec { tools.extend(edit::tools()); tools.extend(run::tools()); tools.extend(vcs::tools()); + tools.extend(http::tools()); tools } diff --git a/crates/ide-host/tests/mcp.rs b/crates/ide-host/tests/mcp.rs index 0ce26b90fa..60243d0f87 100644 --- a/crates/ide-host/tests/mcp.rs +++ b/crates/ide-host/tests/mcp.rs @@ -697,3 +697,76 @@ async fn agent_commands_run_in_named_tabs_and_report_what_the_user_did() { let interrupted = h.json("wait_for_run", json!({"name": "interrupt", "timeout": 10000})).await; assert_eq!(interrupted["state"], "stoppedByAgent", "{interrupted}"); } + +#[tokio::test(flavor = "multi_thread")] +async fn http_list_and_run_require_confirmation() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + let h = Harness::new(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut buf = [0u8; 1024]; + let _ = socket.read(&mut buf).await; + let body = b"{\"ok\":true}"; + let response = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}", + body.len(), + std::str::from_utf8(body).unwrap() + ); + let _ = socket.write_all(response.as_bytes()).await; + }); + + std::fs::write( + h.root.join("api.http"), + format!( + "### Health\nGET http://{addr}/health\nAccept: application/json\n\n### Echo\n# @name echo\nGET http://{addr}/echo\n" + ), + ) + .unwrap(); + std::fs::write(h.root.join("http-client.env.json"), r#"{"dev":{"unused":"x"}}"#).unwrap(); + + let listed = h.json("http_list_requests", json!({"path": "api.http"})).await; + assert_eq!(listed["requests"].as_array().unwrap().len(), 2, "{listed}"); + assert_eq!(listed["requests"][0]["index"], 0); + assert_eq!(listed["requests"][0]["name"], "Health"); + assert_eq!(listed["requests"][0]["method"], "GET"); + assert_eq!(listed["requests"][1]["name"], "echo"); + assert!(listed["requests"][0]["url"].as_str().unwrap().contains("/health")); + + // Write tool is hidden until the project is trusted. + assert!(Registry::new(h.host.clone()).tools(&h.root).unwrap().iter().all(|t| t.name != "http_run_request")); + h.trust().await; + assert!( + Registry::new(h.host.clone()) + .tools(&h.root) + .unwrap() + .iter() + .any(|t| t.name == "http_run_request" && !t.read_only) + ); + + h.host.mcp_requests.set_ready("main", true); + let denied = h.error("http_run_request", json!({"path": "api.http", "index": 0, "env": "dev"})); + let deny = async { + let id = h.request().await; + h.host.mcp_requests.answer("main", id, false, None).unwrap(); + }; + let (error, ()) = tokio::join!(denied, deny); + assert!(error.contains("denied by the user"), "{error}"); + + h.events.lock().unwrap().clear(); + let run = h.json("http_run_request", json!({"path": "api.http", "index": 0, "env": "dev"})); + let allow = async { + let id = h.request().await; + h.host.mcp_requests.answer("main", id, true, None).unwrap(); + }; + let (result, ()) = tokio::join!(run, allow); + assert_eq!(result["status"], 200, "{result}"); + assert_eq!(result["method"], "GET"); + assert!(result["body"].as_str().unwrap().contains("ok"), "{result}"); + assert_eq!(result["bodyTruncated"], false); + // Secrets must not appear as request headers/body in the tool payload. + assert!(result.get("headers").is_none(), "{result}"); + assert!(result.get("request").is_none(), "{result}"); +} diff --git a/docs/en/guide/mcp.mdx b/docs/en/guide/mcp.mdx index 6135a8e6e2..1357ea75e0 100644 --- a/docs/en/guide/mcp.mdx +++ b/docs/en/guide/mcp.mdx @@ -94,6 +94,7 @@ While the server runs, OpenIDEA writes its port and token to `mcp/server.json` i | Commands | `run_command`, `wait_for_run`, `send_run_input`, `stop_run` | | Command state | `get_run_status`, `read_run_output`, `list_runs` | | Git | `get_repositories`, `git_status`, `git_diff` | +| HTTP Client | `http_list_requests`, `http_run_request` | Notes on what they do: @@ -105,6 +106,7 @@ Notes on what they do: - `rename_refactoring` renames through the language server, so references that a text search would miss are updated too. It can preview without writing. - `apply_patch` accepts the Codex `apply_patch` format and unified diffs. Paths must stay inside the project. - `git_diff` compares files on disk, so unsaved editor text is not included. +- `http_list_requests` lists requests in a project `.http` / `.rest` file; `http_run_request` sends one by index (optional `env` from `http-client.env.json`), asks first, and returns status plus a truncated body — not request headers or body. ## Commands in the Run tool window @@ -122,7 +124,7 @@ Plugins can add more tools; they appear in the same list. A plugin tool marked a ## Safety - **Untrusted projects** expose only the read-only tools. Tools that write files, rename, reformat, build or run need a project you have trusted. -- **Running and building ask first.** `execute_run_configuration`, `build_project` and `run_command` show a dialog in OpenIDEA naming the client, the project, the tool and what will run. Choose **Allow** or **Deny**; several requests queue up. +- **Running and building ask first.** `execute_run_configuration`, `build_project`, `run_command` and `http_run_request` show a dialog in OpenIDEA naming the client, the project, the tool and what will run. Choose **Allow** or **Deny**; several requests queue up. - Tools that write refuse paths outside the project. ## Limits diff --git a/docs/zh/guide/mcp.mdx b/docs/zh/guide/mcp.mdx index a1a004b168..d2dbb4be9d 100644 --- a/docs/zh/guide/mcp.mdx +++ b/docs/zh/guide/mcp.mdx @@ -82,17 +82,18 @@ stdio 配置大致如下(路径以你机器上的为准): ## 工具 -| 类别 | 工具 | -| ---------- | --------------------------------------------------------------------------- | -| 文件 | `read_file`、`list_directory_tree`、`create_new_file`、`apply_patch` | -| 搜索 | `search_text`、`search_regex`、`search_symbol`、`search_file` | -| 编辑器 | `get_all_open_file_paths`、`get_current_file`、`open_file_in_editor` | -| 代码 | `get_symbol_info`、`find_references`、`rename_refactoring`、`reformat_file` | -| 问题 | `get_file_problems`、`get_project_problems`、`check_files` | -| 运行与构建 | `get_run_configurations`、`execute_run_configuration`、`build_project` | -| 命令 | `run_command`、`wait_for_run`、`send_run_input`、`stop_run` | -| 命令状态 | `get_run_status`、`read_run_output`、`list_runs` | -| Git | `get_repositories`、`git_status`、`git_diff` | +| 类别 | 工具 | +| ----------- | --------------------------------------------------------------------------- | +| 文件 | `read_file`、`list_directory_tree`、`create_new_file`、`apply_patch` | +| 搜索 | `search_text`、`search_regex`、`search_symbol`、`search_file` | +| 编辑器 | `get_all_open_file_paths`、`get_current_file`、`open_file_in_editor` | +| 代码 | `get_symbol_info`、`find_references`、`rename_refactoring`、`reformat_file` | +| 问题 | `get_file_problems`、`get_project_problems`、`check_files` | +| 运行与构建 | `get_run_configurations`、`execute_run_configuration`、`build_project` | +| 命令 | `run_command`、`wait_for_run`、`send_run_input`、`stop_run` | +| 命令状态 | `get_run_status`、`read_run_output`、`list_runs` | +| Git | `get_repositories`、`git_status`、`git_diff` | +| HTTP 客户端 | `http_list_requests`、`http_run_request` | 几点说明: @@ -104,6 +105,7 @@ stdio 配置大致如下(路径以你机器上的为准): - `rename_refactoring` 通过语言服务器重命名,文本搜索找不到的引用也会一并更新;也可以只预览不写入。 - `apply_patch` 接受 Codex 的 `apply_patch` 格式和 unified diff,路径必须在项目内。 - `git_diff` 比较的是磁盘上的文件,不包含编辑器中尚未保存的内容。 +- `http_list_requests` 列出项目中 `.http` / `.rest` 文件里的请求;`http_run_request` 按索引发送其中一个(可选 `env`,来自 `http-client.env.json`),会先询问,并返回状态和截断后的响应体——不含请求头或请求体。 ## 在运行工具窗口中执行命令 @@ -121,7 +123,7 @@ stdio 配置大致如下(路径以你机器上的为准): ## 安全 - **未受信任的项目** 只开放只读工具。写文件、重命名、重新格式化、构建或运行的工具都要求项目已被信任。 -- **运行和构建会先询问。** `execute_run_configuration`、`build_project` 和 `run_command` 会在 OpenIDEA 中弹出对话框,说明是哪个客户端、哪个项目、哪个工具以及要运行什么,选择 **允许** 或 **拒绝**;多个请求会排队。 +- **运行和构建会先询问。** `execute_run_configuration`、`build_project`、`run_command` 和 `http_run_request` 会在 OpenIDEA 中弹出对话框,说明是哪个客户端、哪个项目、哪个工具以及要运行什么,选择 **允许** 或 **拒绝**;多个请求会排队。 - 会写入的工具拒绝项目之外的路径。 ## 限制 diff --git a/src-tauri/src/commands/window.rs b/src-tauri/src/commands/window.rs index b0a26e8b0f..d4569f98ec 100644 --- a/src-tauri/src/commands/window.rs +++ b/src-tauri/src/commands/window.rs @@ -6,6 +6,7 @@ use crate::windows::{self, Launch, OpenOutcome, WindowsState}; use ide_core::{IdeError, IdeResult, RequestId}; use serde::{Deserialize, Serialize}; use specta::Type; +use std::collections::BTreeMap; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, Ordering}; use tauri::ipc::Channel; @@ -636,12 +637,18 @@ pub async fn app_install_update( } /// Release notes of `version` from the update manifest (`latest.json`), read -/// through the configured source. An install records the notes it saw, so this -/// is only for an update installed outside the app. `Ok(None)` when the manifest -/// covers another version or carries no notes. +/// through the configured source: the `notes` text under `"en"` plus any +/// `notes.` translations keyed by their base language code, so the page +/// can show the UI's language and fall back to English. An install records the +/// notes it saw, so this is only for an update installed outside the app. +/// `Ok(None)` when the manifest covers another version or carries no notes. #[tauri::command] #[specta::specta] -pub async fn app_release_notes(app: AppHandle, version: String, source: UpdateSource) -> IdeResult> { +pub async fn app_release_notes( + app: AppHandle, + version: String, + source: UpdateSource, +) -> IdeResult>> { let endpoints = match update_endpoint_env() { Some(url) => vec![url], None => source_endpoints(config_endpoints(&app), source, is_nightly(&app.package_info().version.to_string())), @@ -667,14 +674,32 @@ pub async fn app_release_notes(app: AppHandle, version: String, source: UpdateSo Ok(None) } -/// The notes of `version` in a manifest, when that is the entry it lists. -fn notes_for(manifest: &str, version: &str) -> Option { +/// The notes of `version` in a manifest, when that is the entry it lists: the +/// `notes` text as English and each `notes.` entry under its base language +/// code (`notes.zh-CN` → `zh`), the way the UI's locales are keyed. +fn notes_for(manifest: &str, version: &str) -> Option> { let value: serde_json::Value = serde_json::from_str(manifest).ok()?; if value.get("version")?.as_str()? != version { return None; } - let notes = value.get("notes")?.as_str()?.trim(); - (!notes.is_empty()).then(|| notes.to_string()) + let mut notes = BTreeMap::new(); + let entry = + |text: &serde_json::Value| text.as_str().map(str::trim).filter(|text| !text.is_empty()).map(str::to_string); + if let Some(text) = value.get("notes").and_then(entry) { + notes.insert("en".to_owned(), text); + } + for (key, text) in value.as_object().into_iter().flatten() { + let Some(tag) = key.strip_prefix("notes.").and_then(|tag| tag.split(['-', '_']).next()) else { + continue; + }; + if tag.is_empty() { + continue; + } + if let Some(text) = entry(text) { + notes.insert(tag.to_ascii_lowercase(), text); + } + } + (!notes.is_empty()).then_some(notes) } #[cfg(test)] @@ -684,10 +709,20 @@ mod tests { let manifest = serde_json::json!({ "version": "0.1.40", "notes": "## What's new\n\n- dev containers", + "notes.zh": "## 新变化\n\n- 开发容器", + "notes.ko-KR": "## 새 소식", + "notes.pl": " ", "pub_date": "2026-11-01T00:00:00Z", }) .to_string(); - assert_eq!(notes_for(&manifest, "0.1.40").as_deref(), Some("## What's new\n\n- dev containers")); + assert_eq!( + notes_for(&manifest, "0.1.40"), + Some(BTreeMap::from([ + ("en".to_owned(), "## What's new\n\n- dev containers".to_owned()), + ("zh".to_owned(), "## 新变化\n\n- 开发容器".to_owned()), + ("ko".to_owned(), "## 새 소식".to_owned()), + ])) + ); // Another version, empty notes, or not JSON: nothing to show. assert_eq!(notes_for(&manifest, "0.1.41"), None); assert_eq!(notes_for(r#"{ "version": "0.1.40", "notes": " " }"#, "0.1.40"), None); diff --git a/src/bindings.ts b/src/bindings.ts index 305340045f..f62f6e2e97 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1295,11 +1295,13 @@ export const commands = { appInstallUpdate: (source: UpdateSource, request: RequestId, onProgress: Channel) => typedError(__TAURI_INVOKE("app_install_update", { source, request, onProgress })), /** * Release notes of `version` from the update manifest (`latest.json`), read - * through the configured source. An install records the notes it saw, so this - * is only for an update installed outside the app. `Ok(None)` when the manifest - * covers another version or carries no notes. + * through the configured source: the `notes` text under `"en"` plus any + * `notes.` translations keyed by their base language code, so the page + * can show the UI's language and fall back to English. An install records the + * notes it saw, so this is only for an update installed outside the app. + * `Ok(None)` when the manifest covers another version or carries no notes. */ - appReleaseNotes: (version: string, source: UpdateSource) => typedError(__TAURI_INVOKE("app_release_notes", { version, source })), + appReleaseNotes: (version: string, source: UpdateSource) => typedError<{ [key in string]: string } | null, IdeError>(__TAURI_INVOKE("app_release_notes", { version, source })), debugExceptionFilters: () => typedError(__TAURI_INVOKE("debug_exception_filters")), debugSetExceptionBreakpoints: (choices: { [key in string]: boolean }) => typedError(__TAURI_INVOKE("debug_set_exception_breakpoints", { choices })), debugSetVariable: (session: DebugSessionId, container: number, name: string, evaluateName: string | null, frameId: number | null, value: string) => typedError(__TAURI_INVOKE("debug_set_variable", { session, container, name, evaluateName, frameId, value })), diff --git a/src/features/whats-new/WhatsNew.tsx b/src/features/whats-new/WhatsNew.tsx index 65fbd33522..70fd790958 100644 --- a/src/features/whats-new/WhatsNew.tsx +++ b/src/features/whats-new/WhatsNew.tsx @@ -4,7 +4,7 @@ */ import { useEffect, useState } from "react"; import { useMarkupHtml } from "@/editor/lsp/markdown"; -import { useT } from "@/platform/i18n"; +import { DEFAULT_LOCALE, useI18n, useT } from "@/platform/i18n"; import { call, commands } from "@/platform/ipc"; import { openExternalUrl } from "@/platform/openUrl"; import { useProject } from "@/platform/project"; @@ -22,27 +22,32 @@ function releasePage(version: string) { export function WhatsNewPage({ input }: { input: EditorInput }) { const t = useT(); + const locale = useI18n((s) => s.locale); const data = input.data as Partial | undefined; const version = data?.version ?? ""; - const [notes, setNotes] = useState(data?.notes ?? null); + // The notes the install recorded, in this language when the manifest carried a translation. + const recorded = data?.texts?.[locale] ?? data?.notes ?? null; + const [manifestNotes, setManifestNotes] = useState | null>(null); // Nothing recorded and a version to look up: the manifest read starts with the first render. const [loading, setLoading] = useState(!data?.notes && !!version); const show = useProject((s) => s.settings?.general?.showWhatsNewAfterUpdate !== false); - // Installed outside the app: no notes were recorded, read the update manifest. + // Installed outside the app, or the recorded notes lack this language: read the update manifest. useEffect(() => { - if (notes || !version) return; + if (!version || manifestNotes || (data?.notes && (locale === DEFAULT_LOCALE || data?.texts?.[locale]))) return; let live = true; void call(commands.appReleaseNotes(version, updateSource())) .catch(() => null) .then((fetched) => { if (!live) return; - setNotes(fetched); + setManifestNotes(fetched); setLoading(false); }); return () => { live = false; }; - }, [notes, version]); + }, [version, locale, manifestNotes, data?.notes, data?.texts]); + // The manifest carries every language it has; a missing translation shows the English notes. + const notes = manifestNotes?.[locale] ?? manifestNotes?.[DEFAULT_LOCALE] ?? recorded; const html = useMarkupHtml({ kind: "markdown", value: notes ?? "" }); return (
diff --git a/src/features/whats-new/__tests__/whatsNew.test.tsx b/src/features/whats-new/__tests__/whatsNew.test.tsx index 82791bdd4b..62e7a6e816 100644 --- a/src/features/whats-new/__tests__/whatsNew.test.tsx +++ b/src/features/whats-new/__tests__/whatsNew.test.tsx @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import type { Settings } from "@/platform/ipc"; @@ -35,6 +35,7 @@ const { _resetReleaseNotesForTests, recordInstalledUpdate } = await import("@/pl const { provideEditorService } = await import("@/workbench/contributions"); const { checkAfterUpdate, openCurrentWhatsNew } = await import("../model"); const { WhatsNewPage } = await import("../WhatsNew"); +const { _resetI18nForTests, setLocale } = await import("@/platform/i18n"); const openInput = vi.fn(async (_input: unknown, _options?: unknown) => {}); provideEditorService({ @@ -54,9 +55,12 @@ beforeEach(() => { localStorage.clear(); openInput.mockClear(); settingsSet.mockClear(); + appReleaseNotes.mockClear(); useProject.setState({ settings: settingsWith({}) }); }); +afterEach(() => _resetI18nForTests()); + describe("the first start after an update", () => { it("records the version and opens the page once", async () => { recordInstalledUpdate("0.1.41", "## What's new\n\n- dev containers"); @@ -107,10 +111,10 @@ describe("the first start after an update", () => { }); describe("the page", () => { - const input = (notes: string | null) => ({ + const input = (notes: string | null, texts?: Record) => ({ kind: "whatsNew", key: "whatsNew:0.1.41", - data: { version: "0.1.41", notes }, + data: { version: "0.1.41", notes, texts: texts ?? null }, }); it("shows the version and the notes, with its checkbox on by default", () => { @@ -130,12 +134,52 @@ describe("the page", () => { }); it("reads the manifest when the install recorded no notes", async () => { - appReleaseNotes.mockResolvedValueOnce({ status: "ok", data: "## From the manifest" }); + appReleaseNotes.mockResolvedValueOnce({ status: "ok", data: { en: "## From the manifest" } }); render(); await waitFor(() => expect(document.body.textContent).toContain("From the manifest")); expect(appReleaseNotes).toHaveBeenCalledWith("0.1.41", "github"); }); + it("shows the notes in the configured language when the manifest carries it", async () => { + await setLocale("zh"); + appReleaseNotes.mockResolvedValueOnce({ status: "ok", data: { en: "## From the manifest", zh: "## 来自清单" } }); + render(); + await waitFor(() => expect(document.body.textContent).toContain("来自清单")); + expect(document.body.textContent).not.toContain("From the manifest"); + }); + + it("shows the manifest's English notes when the configured language has no translation", async () => { + await setLocale("zh"); + appReleaseNotes.mockResolvedValueOnce({ status: "ok", data: { en: "## From the manifest", ko: "## 새 소식" } }); + render(); + await waitFor(() => expect(document.body.textContent).toContain("From the manifest")); + expect(document.body.textContent).not.toContain("새 소식"); + }); + + it("shows the recorded translation of the configured language without reading the manifest", async () => { + await setLocale("zh"); + render(); + expect(document.body.textContent).toContain("修复了一个崩溃"); + expect(appReleaseNotes).not.toHaveBeenCalled(); + }); + + it("shows English recorded notes while it reads the manifest for the missing language", async () => { + await setLocale("zh"); + appReleaseNotes.mockResolvedValueOnce({ status: "ok", data: { en: "- Fixed a crash", zh: "- 修复了一个崩溃" } }); + render(); + expect(document.body.textContent).toContain("Fixed a crash"); + await waitFor(() => expect(document.body.textContent).toContain("修复了一个崩溃")); + expect(appReleaseNotes).toHaveBeenCalledWith("0.1.41", "github"); + }); + + it("keeps the English recorded notes when the manifest has no translation either", async () => { + await setLocale("zh"); + appReleaseNotes.mockResolvedValueOnce({ status: "ok", data: { en: "- Fixed a crash" } }); + render(); + await waitFor(() => expect(appReleaseNotes).toHaveBeenCalledWith("0.1.41", "github")); + expect(document.body.textContent).toContain("Fixed a crash"); + }); + it("points at the release page when there are no notes to show", async () => { render(); await waitFor(() => expect(screen.getByText("There are no release notes for this version.")).toBeInTheDocument()); diff --git a/src/features/whats-new/model.ts b/src/features/whats-new/model.ts index ea750c2149..d45abb7d45 100644 --- a/src/features/whats-new/model.ts +++ b/src/features/whats-new/model.ts @@ -5,22 +5,25 @@ */ import { call, commands, isTauri } from "@/platform/ipc"; import { loadSettings, startupLaunchHandled, useProject } from "@/platform/project"; -import { releaseNotesOf } from "@/platform/releaseNotes"; +import { recordedNotes } from "@/platform/releaseNotes"; import { maybeEditorService, type EditorInput } from "@/workbench/contributions"; export const WHATS_NEW_KIND = "whatsNew"; export interface WhatsNewData { version: string; - /** Notes the install recorded; null when the page has to read the manifest. */ + /** Notes the install recorded, English; null when the page has to read the manifest. */ notes: string | null; + /** Their translations by locale, when the manifest carried them. */ + texts: Record | null; } export function whatsNewInput(version: string): EditorInput { + const recorded = recordedNotes(version); return { kind: WHATS_NEW_KIND, key: WHATS_NEW_KIND + ":" + version, - data: { version, notes: releaseNotesOf(version) } satisfies WhatsNewData, + data: { version, notes: recorded?.text ?? null, texts: recorded?.texts ?? null } satisfies WhatsNewData, }; } diff --git a/src/platform/releaseNotes.test.ts b/src/platform/releaseNotes.test.ts index 94a0810999..1a42e8daff 100644 --- a/src/platform/releaseNotes.test.ts +++ b/src/platform/releaseNotes.test.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it } from "vitest"; -import { _resetReleaseNotesForTests, recordInstalledUpdate, releaseNotesOf } from "./releaseNotes"; +import { _resetReleaseNotesForTests, recordInstalledUpdate, recordedNotes, releaseNotesOf } from "./releaseNotes"; beforeEach(() => { _resetReleaseNotesForTests(); @@ -31,3 +31,30 @@ describe("the notes an install records", () => { expect(releaseNotesOf("0.1.40")).toBeNull(); }); }); + +describe("the notes' languages", () => { + it("show the configured language when the manifest carried its translation", () => { + // The manifest's `notes.` entries arrive keyed by their base language code. + recordInstalledUpdate("0.1.40", "- English", { zh: "- 中文", pt: "- Português" }); + expect(releaseNotesOf("0.1.40", "zh")).toBe("- 中文"); + expect(releaseNotesOf("0.1.40", "pt")).toBe("- Português"); + expect(recordedNotes("0.1.40")?.texts).toEqual({ zh: "- 中文", pt: "- Português" }); + }); + + it("fall back to English when a language has no translation", () => { + recordInstalledUpdate("0.1.40", "- English", { ko: "- 한국어" }); + expect(releaseNotesOf("0.1.40", "zh")).toBe("- English"); + expect(releaseNotesOf("0.1.40")).toBe("- English"); + }); + + it("keep English and empty translations out of the languages", () => { + recordInstalledUpdate("0.1.40", "- English", { en: "- English again", zh: " ", "": "- nothing" }); + expect(recordedNotes("0.1.40")).toEqual({ text: "- English", texts: {} }); + }); + + it("read entries recorded before translations existed", () => { + localStorage.setItem("openidea.whatsNew.notes.v1", JSON.stringify({ version: "0.1.40", text: "- older" })); + expect(releaseNotesOf("0.1.40", "zh")).toBe("- older"); + expect(recordedNotes("0.1.40")).toEqual({ text: "- older", texts: {} }); + }); +}); diff --git a/src/platform/releaseNotes.ts b/src/platform/releaseNotes.ts index efc4b8f084..9a11fd27f9 100644 --- a/src/platform/releaseNotes.ts +++ b/src/platform/releaseNotes.ts @@ -1,14 +1,20 @@ /** * The release notes the updater installed, kept so the What's New page can show * them after the restart that installs an update. localStorage, because an - * update replaces the app bundle but not the webview's data. + * update replaces the app bundle but not the webview's data. Notes are kept in + * the languages the update manifest carried: `text` is English, the fallback + * for the locales `texts` has no entry for. */ +import { DEFAULT_LOCALE } from "./i18n"; + const KEY = "openidea.whatsNew.notes.v1"; interface Stored { version: string; text: string; + /** The notes' translations, keyed like the UI's locales (`zh`, not `zh-CN`). */ + texts?: Record; } function read(): Stored | null { @@ -17,29 +23,49 @@ function read(): Stored | null { const value: unknown = raw ? JSON.parse(raw) : null; if (!value || typeof value !== "object") return null; const stored = value as Partial; - return typeof stored.version === "string" && typeof stored.text === "string" - ? { version: stored.version, text: stored.text } - : null; + if (typeof stored.version !== "string" || typeof stored.text !== "string") return null; + const texts = stored.texts; + return { + version: stored.version, + text: stored.text, + texts: + texts && typeof texts === "object" + ? Object.fromEntries(Object.entries(texts).filter(([, t]) => typeof t === "string")) + : {}, + }; } catch { return null; } } /** Called once an update installed, with the notes its manifest carried. */ -export function recordInstalledUpdate(version: string, notes: string | null): void { +export function recordInstalledUpdate( + version: string, + notes: string | null, + translations: Record | null = null, +): void { const text = notes?.trim(); + const texts = Object.fromEntries( + Object.entries(translations ?? {}).filter(([lang, t]) => lang && lang !== DEFAULT_LOCALE && t.trim()), + ); try { - if (text) globalThis.localStorage?.setItem(KEY, JSON.stringify({ version, text })); + if (text) globalThis.localStorage?.setItem(KEY, JSON.stringify({ version, text, texts })); else globalThis.localStorage?.removeItem(KEY); } catch { /* storage unavailable: the page reads the manifest instead */ } } -/** Notes recorded when this version was installed, so the page shows them offline. */ -export function releaseNotesOf(version: string): string | null { +/** Notes recorded when this version was installed, for the page to pick the UI's language from. */ +export function recordedNotes(version: string): { text: string; texts: Record } | null { const stored = read(); - return stored?.version === version ? stored.text : null; + return stored?.version === version ? { text: stored.text, texts: stored.texts ?? {} } : null; +} + +/** Notes for `locale`: the recorded translation when there is one, English otherwise. */ +export function releaseNotesOf(version: string, locale: string = DEFAULT_LOCALE): string | null { + const stored = recordedNotes(version); + return stored ? (stored.texts[locale] ?? stored.text) : null; } /** Tests only. */