From 5c6200e18fb2e2ca794f729633e09f658978a8d8 Mon Sep 17 00:00:00 2001 From: nonoqing Date: Mon, 9 Nov 2026 19:32:23 +0800 Subject: [PATCH 1/2] feat(desktop): add LaTeX paper writing and PDF preview --- .../src/i18n/generatedLocaleContract.ts | 3 + docs/interactive-capabilities/README.md | 4 +- .../technical/tauri-command-map.json | 22 +- src/apps/desktop/AGENTS.md | 11 + src/apps/desktop/README.md | 19 + src/apps/desktop/src/api/latex_api.rs | 399 ++++++++++++++++++ src/apps/desktop/src/api/mod.rs | 1 + src/apps/desktop/src/lib.rs | 1 + .../prompts/agents/paper_writing_agent.md | 9 + .../tests/prompt_catalog_contracts.rs | 4 + .../agentic/agents/definitions/modes/mod.rs | 2 + .../agents/definitions/modes/paper_writing.rs | 52 +++ .../assembly/core/src/agentic/agents/mod.rs | 1 + .../src/agentic/agents/registry/catalog.rs | 7 +- .../core/src/agentic/agents/registry/tests.rs | 1 + .../service/i18n/generated_locale_contract.rs | 15 + .../assembly/product-capabilities/src/lib.rs | 2 +- .../runtime_boundary.rs | 7 + .../generated/remote-surface-registry.json | 16 +- .../src/remote_surface/capabilities.rs | 5 + .../src/remote_surface/table.rs | 1 + .../execution/agent-runtime/src/agents.rs | 8 +- .../src/remote_connect.rs | 1 + .../tests/remote_connect_contracts.rs | 4 + .../src/i18n/generatedLocaleContract.ts | 3 + src/mobile-web/src/pages/SessionListPage.tsx | 2 + .../i18n/resources/shared/en-US/terms.json | 1 + .../i18n/resources/shared/zh-CN/terms.json | 1 + .../i18n/resources/shared/zh-TW/terms.json | 1 + .../interactive-capabilities/catalog.json | 6 + .../components/panels/base/FlexiblePanel.tsx | 7 +- .../src/flow_chat/utils/chatInputMode.test.ts | 2 + .../api/generated/remoteSurface.ts | 4 +- .../src/infrastructure/api/logSanitizer.ts | 2 +- .../api/service-api/LatexAPI.test.ts | 40 ++ .../api/service-api/LatexAPI.ts | 25 ++ .../registry/defaultAppearanceRegistry.ts | 2 + .../i18n/presets/generatedLocaleContract.ts | 3 + .../peer-device/PeerConnectionManager.ts | 4 + src/web-ui/src/locales/en-US/flow-chat.json | 1 + .../src/locales/en-US/scenes/agents.json | 1 + src/web-ui/src/locales/en-US/tools.json | 14 + src/web-ui/src/locales/zh-CN/flow-chat.json | 1 + .../src/locales/zh-CN/scenes/agents.json | 1 + src/web-ui/src/locales/zh-CN/tools.json | 14 + src/web-ui/src/locales/zh-TW/flow-chat.json | 1 + .../src/locales/zh-TW/scenes/agents.json | 1 + src/web-ui/src/locales/zh-TW/tools.json | 14 + src/web-ui/src/shared/agents/identity.ts | 1 + src/web-ui/src/tools/editor/AGENTS.md | 9 + .../tools/editor/components/CodeEditor.tsx | 12 +- .../components/LatexEditor.appearance.ts | 11 + .../tools/editor/components/LatexEditor.scss | 63 +++ .../editor/components/LatexEditor.test.tsx | 125 ++++++ .../tools/editor/components/LatexEditor.tsx | 167 ++++++++ .../src/tools/editor/components/PdfViewer.tsx | 13 +- .../tools/editor/languages/latex.language.ts | 20 + .../editor/services/MonacoInitManager.ts | 2 + 58 files changed, 1151 insertions(+), 18 deletions(-) create mode 100644 src/apps/desktop/src/api/latex_api.rs create mode 100644 src/crates/assembly/agent-content/prompts/agents/paper_writing_agent.md create mode 100644 src/crates/assembly/core/src/agentic/agents/definitions/modes/paper_writing.rs create mode 100644 src/web-ui/src/infrastructure/api/service-api/LatexAPI.test.ts create mode 100644 src/web-ui/src/infrastructure/api/service-api/LatexAPI.ts create mode 100644 src/web-ui/src/tools/editor/components/LatexEditor.appearance.ts create mode 100644 src/web-ui/src/tools/editor/components/LatexEditor.scss create mode 100644 src/web-ui/src/tools/editor/components/LatexEditor.test.tsx create mode 100644 src/web-ui/src/tools/editor/components/LatexEditor.tsx create mode 100644 src/web-ui/src/tools/editor/languages/latex.language.ts diff --git a/OpenBitFun-Installer/src/i18n/generatedLocaleContract.ts b/OpenBitFun-Installer/src/i18n/generatedLocaleContract.ts index 39944db129..1c66f73862 100644 --- a/OpenBitFun-Installer/src/i18n/generatedLocaleContract.ts +++ b/OpenBitFun-Installer/src/i18n/generatedLocaleContract.ts @@ -82,6 +82,7 @@ export const SHARED_TERMS_BY_APP_LANGUAGE = { "Claw": "Assistant", "Cowork": "Cowork", "DeepResearch": "Deep Research", + "PaperWriting": "Paper Writing", "ComputerUse": "Computer Use", "default": "Default Assistant" }, @@ -144,6 +145,7 @@ export const SHARED_TERMS_BY_APP_LANGUAGE = { "Claw": "助理", "Cowork": "办公协作", "DeepResearch": "深度研究", + "PaperWriting": "论文写作", "ComputerUse": "电脑操作", "default": "默认助手" }, @@ -206,6 +208,7 @@ export const SHARED_TERMS_BY_APP_LANGUAGE = { "Claw": "助理", "Cowork": "辦公協作", "DeepResearch": "深度研究", + "PaperWriting": "論文寫作", "ComputerUse": "電腦操作", "default": "預設助手" }, diff --git a/docs/interactive-capabilities/README.md b/docs/interactive-capabilities/README.md index 24b73822e4..6eb01d1990 100644 --- a/docs/interactive-capabilities/README.md +++ b/docs/interactive-capabilities/README.md @@ -27,9 +27,9 @@ OpenBitFun Playbook currently contains **22 features**, **22 settings pages**, a - Generated per-item interaction audit: `docs/interactive-capabilities/technical/product-control-open-audit.json` - Generated low-level audit map: `docs/interactive-capabilities/technical/tauri-command-map.json` -说明书、网站、搜索和智能体只看“功能 + 设置 + 子能力”。每项子能力都必须引用已注册 Tauri Command 或可解析的源码标记;这些证据不会进入公开目录。当前 **707** 个 Tauri 命令只用于实现覆盖审计。产品 UI 交互源码会在生成和检查时扫描并校验,但不会保存成随普通 UI 改动频繁变化的版本化快照。 +说明书、网站、搜索和智能体只看“功能 + 设置 + 子能力”。每项子能力都必须引用已注册 Tauri Command 或可解析的源码标记;这些证据不会进入公开目录。当前 **708** 个 Tauri 命令只用于实现覆盖审计。产品 UI 交互源码会在生成和检查时扫描并校验,但不会保存成随普通 UI 改动频繁变化的版本化快照。 -Docs, website, search, and agents see only features, settings, and documented sub-capabilities. Every sub-capability must reference a registered Tauri command or a resolvable source marker; evidence is stripped from public projections. The **707** Tauri commands remain implementation-audit evidence only. Product UI interaction sources are scanned and validated during generation and checks, but are not stored as a versioned snapshot that churns with ordinary UI changes. +Docs, website, search, and agents see only features, settings, and documented sub-capabilities. Every sub-capability must reference a registered Tauri command or a resolvable source marker; evidence is stripped from public projections. The **708** Tauri commands remain implementation-audit evidence only. Product UI interaction sources are scanned and validated during generation and checks, but are not stored as a versioned snapshot that churns with ordinary UI changes. ## 控制边界 / Control boundary diff --git a/docs/interactive-capabilities/technical/tauri-command-map.json b/docs/interactive-capabilities/technical/tauri-command-map.json index bc30805684..10d745ec36 100644 --- a/docs/interactive-capabilities/technical/tauri-command-map.json +++ b/docs/interactive-capabilities/technical/tauri-command-map.json @@ -2,12 +2,12 @@ "schemaVersion": 2, "generatedFrom": "src/shared/interactive-capabilities/catalog.json", "catalogDigest": "8a02be2b328791ebb823e4b7a956bf0371c523caa7f881a6c778cbaa42d72575", - "commandCount": 707, + "commandCount": 708, "coverage": { - "commandCount": 707, + "commandCount": 708, "documentedCommandCount": 646, - "implementationCommandCount": 61, - "implementationDigest": "fdb6f78b009b95270d26834349aade36e0987553167f325a9c674a085b876a2d" + "implementationCommandCount": 62, + "implementationDigest": "39288402985a24c84852570c8137b888b15b3d9e1b40448d974085b25c0fcf46" }, "commands": [ { @@ -1316,6 +1316,20 @@ "signature": "fn compact_session( coordinator: State<'_, Arc>, request: CompactSessionRequest, ) -> Result", "remoteWorkspacePolicy": "RemoteRouted" }, + { + "id": "compile_workspace_latex", + "moduleId": "latex", + "capabilityId": "feature.files-editor", + "capabilityIds": [ + "feature.files-editor" + ], + "documentedItemIds": [], + "visibility": "implementation", + "rustPath": "api::latex_api::compile_workspace_latex", + "sourceFile": "src/apps/desktop/src/api/latex_api.rs", + "signature": "fn compile_workspace_latex( request: CompileWorkspaceLatexRequest, ) -> Result", + "remoteWorkspacePolicy": "RemoteRouted" + }, { "id": "compress_path", "moduleId": "commands", diff --git a/src/apps/desktop/AGENTS.md b/src/apps/desktop/AGENTS.md index ecd13b81ba..0f048bd37b 100644 --- a/src/apps/desktop/AGENTS.md +++ b/src/apps/desktop/AGENTS.md @@ -433,3 +433,14 @@ adapter owns HTTP authentication, explicit-refresh headers and peer RPC wiring. Use `node tests/e2e/scripts/run-html-preview.mjs` after building Desktop and Web UI to verify CSS, JavaScript modules, images and concurrent preview cookies in native browser child views. The fixture uses isolated storage; see `tests/e2e/AGENTS.md`. + +For the LaTeX workspace compiler, run: + +```bash +cargo test --locked -p openbitfun-desktop --no-default-features --lib latex_api::tests +``` + +Use `-- --include-ignored` with `latexmk`, pdfLaTeX, and XeLaTeX on PATH to +exercise a multi-file paper build, error diagnostics, and temporary output. +The POSIX build test checks the remote command in a local shell. Verify live +SSH, container, and peer routing separately. diff --git a/src/apps/desktop/README.md b/src/apps/desktop/README.md index a0df236c92..0c2233d81b 100644 --- a/src/apps/desktop/README.md +++ b/src/apps/desktop/README.md @@ -130,6 +130,25 @@ Both modes require the online identity service for sign-in. Same-network mode does not provide offline login. See the [Relay FAQ](../relay-server/FAQ.md) for privacy, service availability, and private-deployment requirements. +## Writing a LaTeX paper + +Choose **Other agents → Paper Writing** in the session composer and ask the +agent to draft or revise files in your workspace. Open the main `.tex` file +from the file tree or its chat link. The editor shows source on the left and the +typeset PDF on the right. Use **Save & compile** or turn on **Auto compile** +to save and recompile the main source after you pause. A failed build keeps the +last successful preview and shows the compiler log. + +Install `latexmk` and the selected pdfLaTeX or XeLaTeX engine on the machine that +owns the workspace. For SSH, Docker, and WSL workspaces, compile in that +environment. In Peer Device Mode the selected Desktop host must advertise +LaTeX preview support. Mobile and bot surfaces can continue an existing writing +session and receive PDF files saved to the workspace by the agent. + +Preview compilation uses temporary files and accepts PDFs up to 8 MiB. +It disables shell escape and skips `latexmk` configuration scripts. +Enable automatic compilation for projects you trust. + ## Global agent instructions Put personal instructions for local OpenBitFun sessions in diff --git a/src/apps/desktop/src/api/latex_api.rs b/src/apps/desktop/src/api/latex_api.rs new file mode 100644 index 0000000000..0e84c617d6 --- /dev/null +++ b/src/apps/desktop/src/api/latex_api.rs @@ -0,0 +1,399 @@ +//! Run the user's TeX installation on the host that owns the workspace. + +use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _}; +use openbitfun_core::agentic::WorkspaceBinding; +use openbitfun_core::service::remote_ssh::workspace_state::get_remote_workspace_manager; +use openbitfun_services_core::{ + bounded_fs::{is_symlink_or_reparse, read_bounded_file, BoundedFileRead}, + process_manager::create_tokio_command, + process_tree::ProcessTreeChild, +}; +use openbitfun_services_integrations::remote_ssh::{shell_quote_posix, SSHCommandOptions}; +use serde::{Deserialize, Serialize}; +use std::{path::Path, process::Stdio, time::Duration}; +use tokio::io::{AsyncRead, AsyncReadExt}; + +const COMPILE_TIMEOUT: Duration = Duration::from_secs(60); +const MAX_PDF_BYTES: usize = 8 * 1024 * 1024; +const MAX_LOG_BYTES: usize = 16 * 1024; +const MISSING_COMPILER: &str = "latexmk is required on the machine that owns this workspace."; +const MISSING_PDF: &str = "LaTeX did not produce a PDF."; + +#[derive(Clone, Copy, Deserialize)] +#[serde(rename_all = "lowercase")] +enum LatexEngine { + PdfLatex, + XeLatex, +} + +impl LatexEngine { + fn arguments(self) -> [&'static str; 6] { + [ + "-norc", + match self { + Self::PdfLatex => "-pdf", + Self::XeLatex => "-xelatex", + }, + "-no-shell-escape", + "-interaction=nonstopmode", + "-halt-on-error", + "-file-line-error", + ] + } +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CompileWorkspaceLatexRequest { + workspace_id: String, + file_path: String, + engine: LatexEngine, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CompileWorkspaceLatexResponse { + pdf_base64: String, +} + +#[tauri::command] +pub async fn compile_workspace_latex( + request: CompileWorkspaceLatexRequest, +) -> Result { + let workspace = WorkspaceBinding::resolve(&request.workspace_id) + .await + .map_err(|error| error.to_string())?; + let pdf_base64 = if workspace.is_remote() { + let connection_id = workspace + .connection_id() + .ok_or("Remote workspace is disconnected.")?; + compile_remote(connection_id, &workspace.root_path_string(), &request).await? + } else { + BASE64.encode(compile_local(workspace.root_path(), &request).await?) + }; + Ok(CompileWorkspaceLatexResponse { pdf_base64 }) +} + +// latexmk invokes TeX and bibliography programs via their command templates. +// Avoid names that are shell syntax in either a POSIX or Windows invocation. +fn source_stem(file_name: &str) -> Result<&str, String> { + let (stem, extension) = file_name.rsplit_once('.').unwrap_or_default(); + if stem.is_empty() || !extension.eq_ignore_ascii_case("tex") { + return Err("Select the main .tex file.".into()); + } + if file_name + .chars() + .any(|c| c.is_control() || "'\"\\`$%!*?[]{}|&;<>".contains(c)) + { + return Err("The LaTeX source filename contains unsupported characters.".into()); + } + Ok(stem) +} + +async fn compile_local( + root: &Path, + request: &CompileWorkspaceLatexRequest, +) -> Result, String> { + let source = root.join(&request.file_path); + let root = tokio::fs::canonicalize(root) + .await + .map_err(|error| error.to_string())?; + let source = tokio::fs::canonicalize(source) + .await + .map_err(|error| error.to_string())?; + if !source.starts_with(root) + || !tokio::fs::metadata(&source) + .await + .is_ok_and(|entry| entry.is_file()) + { + return Err("The main .tex file must be inside this workspace.".into()); + } + let file_name = source + .file_name() + .and_then(|name| name.to_str()) + .ok_or("The LaTeX source filename is invalid.")?; + let stem = source_stem(file_name)?; + let directory = source + .parent() + .ok_or("The LaTeX source directory is invalid.")?; + let build = tempfile::tempdir().map_err(|error| error.to_string())?; + let mut command = create_tokio_command("latexmk"); + #[cfg(target_os = "macos")] + if let Some(path) = openbitfun_services_core::process_manager::platform_path_env() { + let entries = std::env::split_paths(&path).chain([Path::new("/Library/TeX/texbin").into()]); + command.env( + "PATH", + std::env::join_paths(entries).map_err(|error| error.to_string())?, + ); + } + command + .current_dir(directory) + .args(request.engine.arguments()) + .arg(format!("-outdir={}", build.path().display())) + .arg(format!("./{file_name}")) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + + let mut child = ProcessTreeChild::spawn(&mut command) + .await + .map_err(|error| { + if error.kind() == std::io::ErrorKind::NotFound { + MISSING_COMPILER.into() + } else { + format!("Could not start latexmk: {error}") + } + })?; + let stdout = child + .take_stdout() + .ok_or("Could not capture LaTeX output.")?; + let stderr = child + .take_stderr() + .ok_or("Could not capture LaTeX errors.")?; + let (status, stdout, stderr) = tokio::time::timeout(COMPILE_TIMEOUT, async { + tokio::try_join!(child.wait(), read_log_tail(stdout), read_log_tail(stderr)) + }) + .await + .map_err(|_| "LaTeX compilation timed out.")? + .map_err(|error| error.to_string())?; + if !status.success() { + let log = format!("{stdout}\n{stderr}"); + return Err(format!("latexmk exited with {status}.\n{}", log.trim())); + } + drop(child); + + let pdf = build.path().join(format!("{stem}.pdf")); + tokio::task::spawn_blocking(move || { + let _build = build; + let metadata = std::fs::symlink_metadata(&pdf).map_err(|_| MISSING_PDF)?; + if !metadata.is_file() || is_symlink_or_reparse(&metadata) { + return Err(MISSING_PDF.into()); + } + match read_bounded_file(&pdf, MAX_PDF_BYTES).map_err(|error| error.to_string())? { + BoundedFileRead::Content(bytes) if bytes.starts_with(b"%PDF-") => Ok(bytes), + BoundedFileRead::Content(_) => Err(MISSING_PDF.into()), + BoundedFileRead::TooLarge => Err("The PDF exceeds the 8 MiB preview limit.".into()), + } + }) + .await + .map_err(|error| error.to_string())? +} + +async fn read_log_tail(mut reader: impl AsyncRead + Unpin) -> std::io::Result { + let mut tail = Vec::with_capacity(MAX_LOG_BYTES); + let mut chunk = [0; 4096]; + loop { + let size = reader.read(&mut chunk).await?; + if size == 0 { + return Ok(String::from_utf8_lossy(&tail).into_owned()); + } + let overflow = (tail.len() + size).saturating_sub(MAX_LOG_BYTES); + tail.drain(..overflow); + tail.extend_from_slice(&chunk[..size]); + } +} + +fn remote_build_command(root: &str, path: &str, engine: LatexEngine) -> Result { + if path.chars().any(char::is_control) || path.split('/').any(|part| part == "..") { + return Err("The main .tex file must be inside this workspace.".into()); + } + let root = root.trim_end_matches('/'); + let relative = if path.starts_with('/') { + path.strip_prefix(root) + .and_then(|value| value.strip_prefix('/')) + .ok_or("The main .tex file must be inside this workspace.")? + } else { + path + }; + let (directory, file_name) = relative.rsplit_once('/').unwrap_or(("", relative)); + let stem = source_stem(file_name)?; + let root_path = format!("{root}/"); + let directory_path = format!("{root_path}{directory}"); + let script = format!( + r#"set -eu +root=$(CDPATH= cd -P -- {root} && pwd -P) +CDPATH= cd -P -- {directory} +case "$PWD/" in + "${{root%/}}/"*) ;; + *) echo "The main .tex file must be inside this workspace." >&2; exit 1 ;; +esac +source={source} +[ -f "$source" ] && [ ! -L "$source" ] || {{ echo "The main .tex file is unavailable." >&2; exit 1; }} +PATH="$PATH:/Library/TeX/texbin" +export PATH +command -v latexmk >/dev/null || {{ echo "{MISSING_COMPILER}" >&2; exit 127; }} +build=$(mktemp -d /tmp/openbitfun-latex.XXXXXXXX) +trap 'rm -rf -- "$build"' EXIT +trap 'exit 124' HUP INT TERM +if latexmk {arguments} "-outdir=$build" "$source" "$build/compile.log" 2>&1; then + pdf="$build/"{pdf} + [ -f "$pdf" ] && [ ! -L "$pdf" ] || {{ echo "{MISSING_PDF}" >&2; exit 1; }} + [ "$(wc -c < "$pdf")" -le {MAX_PDF_BYTES} ] || {{ echo "The PDF exceeds the 8 MiB preview limit." >&2; exit 1; }} + base64 < "$pdf" +else + tail -c {MAX_LOG_BYTES} "$build/compile.log" >&2 + exit 1 +fi"#, + root = shell_quote_posix(&root_path), + directory = shell_quote_posix(&directory_path), + source = shell_quote_posix(&format!("./{file_name}")), + arguments = engine.arguments().join(" "), + pdf = shell_quote_posix(&format!("{stem}.pdf")), + ); + Ok(format!("sh -c {}", shell_quote_posix(&script))) +} + +async fn compile_remote( + connection_id: &str, + root: &str, + request: &CompileWorkspaceLatexRequest, +) -> Result { + let command = remote_build_command(root, &request.file_path, request.engine)?; + let manager = get_remote_workspace_manager().ok_or("Remote workspace is unavailable.")?; + let ssh = manager + .get_ssh_manager() + .await + .ok_or("Remote workspace is disconnected.")?; + let result = ssh + .execute_command_with_options( + connection_id, + &command, + SSHCommandOptions { + timeout_ms: Some(COMPILE_TIMEOUT.as_millis() as u64), + ..Default::default() + }, + ) + .await + .map_err(|error| error.to_string())?; + if result.timed_out { + return Err("LaTeX compilation timed out on the workspace host.".into()); + } + if result.interrupted || result.exit_code != 0 { + return Err(format!( + "Remote LaTeX compilation failed.\n{}", + result.stderr.trim() + )); + } + let encoded: String = result + .stdout + .chars() + .filter(|c| !c.is_ascii_whitespace()) + .collect(); + // The remote shell limits the output before encoding it. Recheck it before + // accepting the result from the workspace host. + if encoded.len() > MAX_PDF_BYTES.div_ceil(3) * 4 { + return Err("The PDF exceeds the 8 MiB preview limit.".into()); + } + let pdf = BASE64.decode(&encoded).map_err(|_| MISSING_PDF)?; + if pdf.len() > MAX_PDF_BYTES || !pdf.starts_with(b"%PDF-") { + return Err(MISSING_PDF.into()); + } + Ok(encoded) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn compile_paths_and_names_remain_workspace_scoped() { + for path in [ + "/paper-other/main.tex", + "../main.tex", + "/paper/chapters/../main.tex", + "draft.pdf", + "unsafe%name.tex", + ] { + assert!( + remote_build_command("/paper", path, LatexEngine::PdfLatex).is_err(), + "{path}" + ); + } + assert!(remote_build_command( + "/paper's folder", + "/paper's folder/manuscript draft.tex", + LatexEngine::XeLatex + ) + .is_ok()); + } + + #[tokio::test] + #[ignore = "requires a working latexmk and TeX installation"] + async fn builds_a_paper_without_replacing_workspace_files() { + let root = tempfile::tempdir().unwrap(); + let file_path = "main draft.tex"; + let source = root.path().join(file_path); + std::fs::write( + &source, + r"\documentclass{article} +\begin{document} +\input{section} +\cite{knuth1984} +\bibliographystyle{plain} +\bibliography{refs} +\end{document}", + ) + .unwrap(); + std::fs::write(root.path().join("section.tex"), "An equation: $E = mc^2$.").unwrap(); + std::fs::write( + root.path().join("refs.bib"), + "@book{knuth1984, title={The TeXbook}, author={Donald Knuth}, year={1984}, publisher={Addison-Wesley}}", + ).unwrap(); + std::fs::write( + root.path().join("latexmkrc"), + "die 'Project rc must not run';", + ) + .unwrap(); + let previous_pdf = root.path().join("main draft.pdf"); + std::fs::write(&previous_pdf, "previous build").unwrap(); + + let request = CompileWorkspaceLatexRequest { + workspace_id: "fixture".into(), + file_path: file_path.into(), + engine: LatexEngine::PdfLatex, + }; + let pdf = compile_local(root.path(), &request).await.unwrap(); + assert!(pdf.starts_with(b"%PDF-")); + assert!(!root.path().join("main draft.aux").exists()); + assert_eq!( + std::fs::read_to_string(previous_pdf).unwrap(), + "previous build" + ); + + #[cfg(unix)] + { + // Exercise the POSIX build command independently of the SSH transport. + let command = remote_build_command( + root.path().to_str().unwrap(), + file_path, + LatexEngine::XeLatex, + ) + .unwrap(); + let output = create_tokio_command("sh") + .arg("-c") + .arg(command) + .output() + .await + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let encoded: Vec = output + .stdout + .into_iter() + .filter(|byte| !byte.is_ascii_whitespace()) + .collect(); + assert!(BASE64.decode(encoded).unwrap().starts_with(b"%PDF-")); + } + + std::fs::write( + &source, + r"\documentclass{article}\begin{document}\undefinedcommand\end{document}", + ) + .unwrap(); + let error = compile_local(root.path(), &request).await.unwrap_err(); + assert!(error.contains("Undefined control sequence"), "{error}"); + } +} diff --git a/src/apps/desktop/src/api/mod.rs b/src/apps/desktop/src/api/mod.rs index 7b8fc15cf6..d247a193a6 100644 --- a/src/apps/desktop/src/api/mod.rs +++ b/src/apps/desktop/src/api/mod.rs @@ -33,6 +33,7 @@ pub mod git_api; pub mod html_preview_api; pub mod i18n_api; pub mod insights_api; +pub mod latex_api; pub mod local_file_download; pub mod market_image_api; pub mod mcp_api; diff --git a/src/apps/desktop/src/lib.rs b/src/apps/desktop/src/lib.rs index 04d6722e2c..4e35ab7707 100644 --- a/src/apps/desktop/src/lib.rs +++ b/src/apps/desktop/src/lib.rs @@ -2012,6 +2012,7 @@ pub async fn run() { api::html_preview_api::html_preview_create, api::html_preview_api::html_preview_read_resource, api::html_preview_api::html_preview_release, + api::latex_api::compile_workspace_latex, // Browser Control API (CDP-based user browser control) api::browser_control_api::browser_control_list_browsers, api::browser_control_api::browser_control_get_status, diff --git a/src/crates/assembly/agent-content/prompts/agents/paper_writing_agent.md b/src/crates/assembly/agent-content/prompts/agents/paper_writing_agent.md new file mode 100644 index 0000000000..300cd1d6f8 --- /dev/null +++ b/src/crates/assembly/agent-content/prompts/agents/paper_writing_agent.md @@ -0,0 +1,9 @@ +You are OpenBitFun's Paper Writing agent. Work with the user on the LaTeX manuscript in the active workspace. + +{LANGUAGE_PREFERENCE} + +- Inspect the workspace before editing. Find the main `.tex` file, included chapters, bibliography, figures, and any submission template. Use the existing manuscript and preserve its document class, structure, and bibliography conventions. If the user wants a new paper and provides no template, create a minimal compilable `main.tex` and add companion files only as needed. +- Make targeted edits to the real workspace files. Read the latest source before changing it because the user may be editing the same file. Cite specific, verified sources. Keep claims within the evidence, preserve uncertainty, and flag missing evidence instead of inventing results, citations, DOIs, affiliations, or author details. +- When the user requests a build or a finished PDF, use the execution environment that owns the workspace. Select the engine the manuscript needs. If using `latexmk`, use `-norc -no-shell-escape -interaction=nonstopmode -halt-on-error -file-line-error` and the appropriate engine flag. Keep auxiliary files separate from the source where possible. Do not run untrusted build scripts, enable shell escape, or install software without the user's authorization. +- Check the compiler exit status and the generated PDF. Surface missing compilers, packages, fonts, or citations and the relevant error location. Report a successful build only after verifying the output. +- Link the main `.tex` file in your reply, plus any PDF that was actually built and saved. In the Desktop workbench the user can open the main source and compile it in the right-hand PDF pane. If that pane is unavailable on their surface, give the workspace file links and report the available build result. diff --git a/src/crates/assembly/agent-content/tests/prompt_catalog_contracts.rs b/src/crates/assembly/agent-content/tests/prompt_catalog_contracts.rs index 70a16bf5ba..d4adf4a991 100644 --- a/src/crates/assembly/agent-content/tests/prompt_catalog_contracts.rs +++ b/src/crates/assembly/agent-content/tests/prompt_catalog_contracts.rs @@ -57,6 +57,10 @@ const CATALOG_PROMPT_SOURCES: &[(&str, &[u8])] = &[ "openbitfun_agent", include_bytes!("../prompts/agents/openbitfun_agent.md"), ), + ( + "paper_writing_agent", + include_bytes!("../prompts/agents/paper_writing_agent.md"), + ), ( "phase1_system", include_bytes!("../prompts/memories/phase1_system.md"), diff --git a/src/crates/assembly/core/src/agentic/agents/definitions/modes/mod.rs b/src/crates/assembly/core/src/agentic/agents/definitions/modes/mod.rs index bf8e47734f..c8ab574f97 100644 --- a/src/crates/assembly/core/src/agentic/agents/definitions/modes/mod.rs +++ b/src/crates/assembly/core/src/agentic/agents/definitions/modes/mod.rs @@ -3,6 +3,7 @@ mod cowork; mod creative; mod deep_research; mod minimal; +mod paper_writing; mod standard; mod ultimate; @@ -11,5 +12,6 @@ pub use cowork::CoworkMode; pub use creative::CreativeHarness; pub use deep_research::DeepResearchMode; pub use minimal::MinimalHarness; +pub(crate) use paper_writing::PaperWritingAgent; pub use standard::StandardHarness; pub use ultimate::UltimateHarness; diff --git a/src/crates/assembly/core/src/agentic/agents/definitions/modes/paper_writing.rs b/src/crates/assembly/core/src/agentic/agents/definitions/modes/paper_writing.rs new file mode 100644 index 0000000000..a7d90d192b --- /dev/null +++ b/src/crates/assembly/core/src/agentic/agents/definitions/modes/paper_writing.rs @@ -0,0 +1,52 @@ +use crate::agentic::agents::{Agent, UserContextPolicy}; +use async_trait::async_trait; + +pub(crate) struct PaperWritingAgent; + +#[async_trait] +impl Agent for PaperWritingAgent { + fn as_any(&self) -> &dyn std::any::Any { + self + } + + fn id(&self) -> &str { + "PaperWriting" + } + + fn name(&self) -> &str { + "Paper Writing" + } + + fn description(&self) -> &str { + "Draft and revise academic papers in a LaTeX workspace, with sources, bibliography, figures, and a compiled PDF." + } + + fn prompt_template_name(&self, _model_name: Option<&str>) -> &str { + "paper_writing_agent" + } + + fn default_tools(&self) -> Vec { + [ + "Glob", + "Grep", + "Read", + "Edit", + "Write", + "WebSearch", + "WebFetch", + "ExecCommand", + "ExecControl", + "WriteStdin", + "AskUserQuestion", + ] + .into_iter() + .map(String::from) + .collect() + } + + fn user_context_policy(&self) -> UserContextPolicy { + UserContextPolicy::empty() + .with_workspace_context() + .with_workspace_instructions() + } +} diff --git a/src/crates/assembly/core/src/agentic/agents/mod.rs b/src/crates/assembly/core/src/agentic/agents/mod.rs index 5c779625ce..0c4194ddea 100644 --- a/src/crates/assembly/core/src/agentic/agents/mod.rs +++ b/src/crates/assembly/core/src/agentic/agents/mod.rs @@ -15,6 +15,7 @@ pub use definitions::custom::{CustomMode, CustomSubagent, CustomSubagentKind}; #[cfg(feature = "external-sources")] pub(crate) use definitions::external::ExternalProvidedAgent; pub use definitions::hidden::{CodeReviewAgent, DeepReviewAgent, OpenBitFunAgent}; +use definitions::modes::PaperWritingAgent; pub use definitions::modes::{ ClawMode, CoworkMode, CreativeHarness, DeepResearchMode, MinimalHarness, StandardHarness, UltimateHarness, diff --git a/src/crates/assembly/core/src/agentic/agents/registry/catalog.rs b/src/crates/assembly/core/src/agentic/agents/registry/catalog.rs index 8cac89940e..edc4931814 100644 --- a/src/crates/assembly/core/src/agentic/agents/registry/catalog.rs +++ b/src/crates/assembly/core/src/agentic/agents/registry/catalog.rs @@ -3,9 +3,9 @@ use super::visibility::SubagentVisibilityPolicy; use crate::agentic::agents::{ Agent, ClawMode, CodeReviewAgent, ComputerUseMode, CoworkMode, CreativeHarness, DeepResearchMode, DeepReviewAgent, ExploreAgent, GeneralPurposeAgent, MinimalHarness, - OpenBitFunAgent, ResearchSpecialistAgent, ReviewFixerAgent, ReviewJudgeAgent, - ReviewWorkerAgent, StandardHarness, SwarmPlannerAgent, SwarmReviewerAgent, SwarmWorkerAgent, - UltimateHarness, + OpenBitFunAgent, PaperWritingAgent, ResearchSpecialistAgent, ReviewFixerAgent, + ReviewJudgeAgent, ReviewWorkerAgent, StandardHarness, SwarmPlannerAgent, SwarmReviewerAgent, + SwarmWorkerAgent, UltimateHarness, }; use crate::agentic::memories::MemoryPhase2Agent; use openbitfun_agent_runtime::agents as runtime_agents; @@ -52,6 +52,7 @@ fn builtin_agent_factory(id: &str) -> fn() -> Arc { "Creative" => || Arc::new(CreativeHarness::new()), "Claw" => || Arc::new(ClawMode::new()), "DeepResearch" => || Arc::new(DeepResearchMode::new()), + "PaperWriting" => || Arc::new(PaperWritingAgent), "Ultimate" => || Arc::new(UltimateHarness::new()), "SwarmPlanner" => || Arc::new(SwarmPlannerAgent::new()), "SwarmWorker" => || Arc::new(SwarmWorkerAgent::new()), diff --git a/src/crates/assembly/core/src/agentic/agents/registry/tests.rs b/src/crates/assembly/core/src/agentic/agents/registry/tests.rs index 5513cb72c0..f6de8b3638 100644 --- a/src/crates/assembly/core/src/agentic/agents/registry/tests.rs +++ b/src/crates/assembly/core/src/agentic/agents/registry/tests.rs @@ -280,6 +280,7 @@ fn top_level_modes_default_to_auto() { "Creative", "Claw", "DeepResearch", + "PaperWriting", "Ultimate", ] { assert_eq!(default_model_id_for_builtin_agent(agent_type), "primary"); diff --git a/src/crates/assembly/core/src/service/i18n/generated_locale_contract.rs b/src/crates/assembly/core/src/service/i18n/generated_locale_contract.rs index 581ddee779..ca05c4d9c4 100644 --- a/src/crates/assembly/core/src/service/i18n/generated_locale_contract.rs +++ b/src/crates/assembly/core/src/service/i18n/generated_locale_contract.rs @@ -102,6 +102,11 @@ pub const GENERATED_SHARED_TERMS: &[GeneratedSharedTermEntry] = &[ key: "agents.Minimal", value: "极简", }, + GeneratedSharedTermEntry { + locale: LocaleId::ZhCN, + key: "agents.PaperWriting", + value: "论文写作", + }, GeneratedSharedTermEntry { locale: LocaleId::ZhCN, key: "agents.Standard", @@ -312,6 +317,11 @@ pub const GENERATED_SHARED_TERMS: &[GeneratedSharedTermEntry] = &[ key: "agents.Minimal", value: "極簡", }, + GeneratedSharedTermEntry { + locale: LocaleId::ZhTW, + key: "agents.PaperWriting", + value: "論文寫作", + }, GeneratedSharedTermEntry { locale: LocaleId::ZhTW, key: "agents.Standard", @@ -522,6 +532,11 @@ pub const GENERATED_SHARED_TERMS: &[GeneratedSharedTermEntry] = &[ key: "agents.Minimal", value: "Minimal", }, + GeneratedSharedTermEntry { + locale: LocaleId::EnUS, + key: "agents.PaperWriting", + value: "Paper Writing", + }, GeneratedSharedTermEntry { locale: LocaleId::EnUS, key: "agents.Standard", diff --git a/src/crates/assembly/product-capabilities/src/lib.rs b/src/crates/assembly/product-capabilities/src/lib.rs index 32761fe4bf..b5df509a38 100644 --- a/src/crates/assembly/product-capabilities/src/lib.rs +++ b/src/crates/assembly/product-capabilities/src/lib.rs @@ -1044,7 +1044,7 @@ const DEEP_REVIEW_AGENT_IDS: &[&str] = &[ "CodeReview", "DeepReview", ]; -const DEEP_RESEARCH_AGENT_IDS: &[&str] = &["DeepResearch", "ResearchSpecialist"]; +const DEEP_RESEARCH_AGENT_IDS: &[&str] = &["DeepResearch", "ResearchSpecialist", "PaperWriting"]; const CREATION_AGENT_IDS: &[&str] = &["Creative"]; const NO_PRODUCT_AGENTS: &[&str] = &[]; diff --git a/src/crates/assembly/product-capabilities/tests/product_capability_contracts/runtime_boundary.rs b/src/crates/assembly/product-capabilities/tests/product_capability_contracts/runtime_boundary.rs index c1c72f618f..8d4307a030 100644 --- a/src/crates/assembly/product-capabilities/tests/product_capability_contracts/runtime_boundary.rs +++ b/src/crates/assembly/product-capabilities/tests/product_capability_contracts/runtime_boundary.rs @@ -86,6 +86,7 @@ fn headless_agent_hosts_keep_explore_code_agents_without_product_workflow_agents for product_agent in [ "DeepResearch", + "PaperWriting", "ResearchSpecialist", "DeepReview", "CodeReview", @@ -119,6 +120,12 @@ fn headless_agent_hosts_keep_explore_code_agents_without_product_workflow_agents } } +#[test] +fn paper_writing_agent_is_available_on_desktop() { + let plan = product_assembly_plan_for_profile(DeliveryProfile::Desktop); + assert!(plan.agent_ids().contains(&"PaperWriting")); +} + #[test] fn cli_pages_are_independent_of_miniapp_and_acp() { let plan = product_assembly_plan_for_profile(DeliveryProfile::Cli); diff --git a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json index 4a4a6c045b..75d7c3fc0d 100644 --- a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json +++ b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "digest": "fnv1a64:8b695d77ffe4587b", + "digest": "fnv1a64:697c80a6c8436cae", "retiredCommandPrefixes": [ { "prefix": "lsp_", @@ -50,6 +50,7 @@ "workspace_icon_v1", "workspace_id_references_v1", "workspace_html_preview_v1", + "workspace_latex_preview_v1", "whole_session_copy_v1", "session_trajectory_v1", "session_reference_browse_v1", @@ -101,6 +102,7 @@ "workspace_icon_v1", "workspace_id_references_v1", "workspace_html_preview_v1", + "workspace_latex_preview_v1", "whole_session_copy_v1", "session_trajectory_v1", "session_reference_browse_v1", @@ -1101,6 +1103,18 @@ "reason": "the CLI peer host has no handler for this command" } }, + { + "id": "compile_workspace_latex", + "surface": "tauri_command", + "remoteWorkspace": "RemoteRouted", + "peer": { + "kind": "proxied" + }, + "cliPeer": { + "kind": "unsupported", + "reason": "the CLI peer host has no handler for this command" + } + }, { "id": "compress_path", "surface": "tauri_command", diff --git a/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs b/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs index 043a4e4fce..4004d69b74 100644 --- a/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs +++ b/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs @@ -105,6 +105,8 @@ pub enum PeerHostCapability { WorkspaceIdReferencesV1, /// Workspace-confined static resources for controller-owned HTML preview. WorkspaceHtmlPreviewV1, + /// Compile a workspace's main TeX source on this Desktop host. + WorkspaceLatexPreviewV1, /// `copy_session` copies a whole session without a caller-selected turn id. WholeSessionCopyV1, /// Bounded session trajectory summaries and host-side body search. @@ -170,6 +172,7 @@ impl PeerHostCapability { Self::WorkspaceIconV1, Self::WorkspaceIdReferencesV1, Self::WorkspaceHtmlPreviewV1, + Self::WorkspaceLatexPreviewV1, Self::WholeSessionCopyV1, Self::SessionTrajectoryV1, Self::SessionReferenceBrowseV1, @@ -224,6 +227,7 @@ impl PeerHostCapability { Self::WorkspaceIconV1 => "workspace_icon_v1", Self::WorkspaceIdReferencesV1 => "workspace_id_references_v1", Self::WorkspaceHtmlPreviewV1 => "workspace_html_preview_v1", + Self::WorkspaceLatexPreviewV1 => "workspace_latex_preview_v1", Self::SessionTrajectoryV1 => "session_trajectory_v1", Self::SessionReferenceBrowseV1 => "session_reference_browse_v1", Self::WholeSessionCopyV1 => "whole_session_copy_v1", @@ -285,6 +289,7 @@ const DESKTOP_CAPABILITIES: &[PeerHostCapability] = &[ PeerHostCapability::WorkspaceIconV1, PeerHostCapability::WorkspaceIdReferencesV1, PeerHostCapability::WorkspaceHtmlPreviewV1, + PeerHostCapability::WorkspaceLatexPreviewV1, PeerHostCapability::WholeSessionCopyV1, PeerHostCapability::SessionTrajectoryV1, PeerHostCapability::SessionReferenceBrowseV1, diff --git a/src/crates/contracts/product-domains/src/remote_surface/table.rs b/src/crates/contracts/product-domains/src/remote_surface/table.rs index 4e6bde5749..8b9fedc4bf 100644 --- a/src/crates/contracts/product-domains/src/remote_surface/table.rs +++ b/src/crates/contracts/product-domains/src/remote_surface/table.rs @@ -171,6 +171,7 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("clear_web_search_credential", Agnostic, Proxied, HANDLED), op("close_workspace", Routed, Proxied, CLI_NOT_IMPLEMENTED), op("compact_session", Routed, Proxied, CLI_NOT_IMPLEMENTED), + op("compile_workspace_latex", Routed, Proxied, CLI_NOT_IMPLEMENTED), op("compress_path", Routed, Proxied, CLI_NOT_IMPLEMENTED), op("compute_diff", Agnostic, Proxied, CLI_NOT_IMPLEMENTED), op("computer_use_control_preview", LocalOnly, Proxied, CLI_NO_BROWSER_OR_OS_AUTOMATION), diff --git a/src/crates/execution/agent-runtime/src/agents.rs b/src/crates/execution/agent-runtime/src/agents.rs index 3c2afa202c..18d49fcb31 100644 --- a/src/crates/execution/agent-runtime/src/agents.rs +++ b/src/crates/execution/agent-runtime/src/agents.rs @@ -107,6 +107,12 @@ pub fn builtin_agent_definition_specs() -> Vec { "primary", SubagentVisibilityPolicy::default(), ), + builtin_agent_spec( + "PaperWriting", + Mode, + "primary", + SubagentVisibilityPolicy::default(), + ), builtin_agent_spec( "Ultimate", Mode, @@ -210,7 +216,7 @@ pub fn builtin_agent_definition_specs() -> Vec { pub fn default_model_id_for_builtin_agent(agent_type: &str) -> &'static str { match agent_type { "OpenBitFun" | "Minimal" | "Standard" | "Cowork" | "Creative" | "ComputerUse" | "Claw" - | "DeepResearch" | "Ultimate" => "primary", + | "DeepResearch" | "PaperWriting" | "Ultimate" => "primary", "MemoryPhase2" => "primary", "ResearchSpecialist" | "DeepReview" diff --git a/src/crates/services/services-integrations/src/remote_connect.rs b/src/crates/services/services-integrations/src/remote_connect.rs index 5c7132d00f..c07af44c81 100644 --- a/src/crates/services/services-integrations/src/remote_connect.rs +++ b/src/crates/services/services-integrations/src/remote_connect.rs @@ -2387,6 +2387,7 @@ pub fn resolve_remote_agent_type(mobile_type: Option<&str>) -> &'static str { } Some("code") => "Standard", Some("cowork") | Some("Cowork") => "Cowork", + Some("PaperWriting") => "PaperWriting", Some("claw") | Some("Claw") | Some("assistant") | Some("chat") => "Claw", _ => "Standard", } diff --git a/src/crates/services/services-integrations/tests/remote_connect_contracts.rs b/src/crates/services/services-integrations/tests/remote_connect_contracts.rs index bd02a6201c..8107c14720 100644 --- a/src/crates/services/services-integrations/tests/remote_connect_contracts.rs +++ b/src/crates/services/services-integrations/tests/remote_connect_contracts.rs @@ -2714,6 +2714,10 @@ fn remote_connect_agent_type_mapping_preserves_current_mobile_aliases() { assert_eq!(resolve_remote_agent_type(Some("Ultimate")), "Ultimate"); assert_eq!(resolve_remote_agent_type(Some("cowork")), "Cowork"); assert_eq!(resolve_remote_agent_type(Some("Cowork")), "Cowork"); + assert_eq!( + resolve_remote_agent_type(Some("PaperWriting")), + "PaperWriting" + ); assert_eq!(resolve_remote_agent_type(Some("plan")), "Standard"); assert_eq!(resolve_remote_agent_type(Some("Plan")), "Standard"); assert_eq!(resolve_remote_agent_type(Some("unknown")), "Standard"); diff --git a/src/mobile-web/src/i18n/generatedLocaleContract.ts b/src/mobile-web/src/i18n/generatedLocaleContract.ts index 096da421f0..b255c35039 100644 --- a/src/mobile-web/src/i18n/generatedLocaleContract.ts +++ b/src/mobile-web/src/i18n/generatedLocaleContract.ts @@ -66,6 +66,7 @@ export const SHARED_TERMS_BY_LOCALE = { "Claw": "助理", "Cowork": "办公协作", "DeepResearch": "深度研究", + "PaperWriting": "论文写作", "ComputerUse": "电脑操作", "default": "默认助手" }, @@ -128,6 +129,7 @@ export const SHARED_TERMS_BY_LOCALE = { "Claw": "助理", "Cowork": "辦公協作", "DeepResearch": "深度研究", + "PaperWriting": "論文寫作", "ComputerUse": "電腦操作", "default": "預設助手" }, @@ -190,6 +192,7 @@ export const SHARED_TERMS_BY_LOCALE = { "Claw": "Assistant", "Cowork": "Cowork", "DeepResearch": "Deep Research", + "PaperWriting": "Paper Writing", "ComputerUse": "Computer Use", "default": "Default Assistant" }, diff --git a/src/mobile-web/src/pages/SessionListPage.tsx b/src/mobile-web/src/pages/SessionListPage.tsx index 0b09e76f05..99cc18d058 100644 --- a/src/mobile-web/src/pages/SessionListPage.tsx +++ b/src/mobile-web/src/pages/SessionListPage.tsx @@ -231,6 +231,8 @@ function agentLabel(agentType: string, t: (key: string) => string): string { case 'cowork': case 'Cowork': return t('sessions.agentCowork'); + case 'PaperWriting': + return t('shared.agents.PaperWriting'); case 'claw': case 'Claw': return t('shared.agents.Claw'); diff --git a/src/shared/i18n/resources/shared/en-US/terms.json b/src/shared/i18n/resources/shared/en-US/terms.json index 71ade45678..3dddc5020c 100644 --- a/src/shared/i18n/resources/shared/en-US/terms.json +++ b/src/shared/i18n/resources/shared/en-US/terms.json @@ -29,6 +29,7 @@ "Claw": "Assistant", "Cowork": "Cowork", "DeepResearch": "Deep Research", + "PaperWriting": "Paper Writing", "ComputerUse": "Computer Use", "default": "Default Assistant" }, diff --git a/src/shared/i18n/resources/shared/zh-CN/terms.json b/src/shared/i18n/resources/shared/zh-CN/terms.json index 6eba6ade31..f422995e53 100644 --- a/src/shared/i18n/resources/shared/zh-CN/terms.json +++ b/src/shared/i18n/resources/shared/zh-CN/terms.json @@ -29,6 +29,7 @@ "Claw": "助理", "Cowork": "办公协作", "DeepResearch": "深度研究", + "PaperWriting": "论文写作", "ComputerUse": "电脑操作", "default": "默认助手" }, diff --git a/src/shared/i18n/resources/shared/zh-TW/terms.json b/src/shared/i18n/resources/shared/zh-TW/terms.json index 1e6b968dea..8b9ec964bb 100644 --- a/src/shared/i18n/resources/shared/zh-TW/terms.json +++ b/src/shared/i18n/resources/shared/zh-TW/terms.json @@ -29,6 +29,7 @@ "Claw": "助理", "Cowork": "辦公協作", "DeepResearch": "深度研究", + "PaperWriting": "論文寫作", "ComputerUse": "電腦操作", "default": "預設助手" }, diff --git a/src/shared/interactive-capabilities/catalog.json b/src/shared/interactive-capabilities/catalog.json index 4f16db2661..a8ea30c378 100644 --- a/src/shared/interactive-capabilities/catalog.json +++ b/src/shared/interactive-capabilities/catalog.json @@ -318,6 +318,9 @@ "html_preview_read_resource", "html_preview_release" ], + "latexPreview": [ + "compile_workspace_latex" + ], "githubDeviceRouting": [ "account_get_credential_hint", "account_login", @@ -10182,6 +10185,9 @@ "html_preview": { "capabilityId": "feature.files-editor" }, + "latex": { + "capabilityId": "feature.files-editor" + }, "tool": { "capabilityId": "feature.ai-assistant" }, diff --git a/src/web-ui/src/app/components/panels/base/FlexiblePanel.tsx b/src/web-ui/src/app/components/panels/base/FlexiblePanel.tsx index 48c2a611ad..a69daa198b 100644 --- a/src/web-ui/src/app/components/panels/base/FlexiblePanel.tsx +++ b/src/web-ui/src/app/components/panels/base/FlexiblePanel.tsx @@ -26,6 +26,8 @@ const CodeEditor = lazyWithRecovery(() => })) ); +const LatexEditor = lazyWithRecovery(() => import('@/tools/editor/components/LatexEditor')); + const MarkdownEditor = lazyWithRecovery(() => import('@/tools/editor/components/MarkdownEditor').then(module => ({ default: module.default, @@ -459,8 +461,11 @@ const FlexiblePanel: React.FC = memo(({ const fileName = editorData.fileName || content.title; const editorLanguage = editorData.language; const editorWorkspacePath = editorData.workspacePath || workspacePath; + const Editor = documentSession && /\.tex$/i.test(filePath) && + !editorData.readOnly && typeof editorData.initialContent !== 'string' ? LatexEditor : CodeEditor; return renderLazyEditor( - { resolveChatInputMainAgentModes([ { id: 'Standard' }, { id: 'Cowork' }, + { id: 'PaperWriting' }, { id: 'Multitask' }, { id: 'Plan' }, { id: 'Claw' }, @@ -236,6 +237,7 @@ describe('ChatInput Agent projection', () => { ]), ).toEqual([ { id: 'Cowork' }, + { id: 'PaperWriting' }, { id: 'PlannerPlus' }, ]); }); diff --git a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts index 1e4c9c5eba..0b863ea30c 100644 --- a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts +++ b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate-interactive-capabilities.mjs; do not edit. // Source: openbitfun_product_domains::remote_surface (Product Operation Registry). -export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:8b695d77ffe4587b" as const; +export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:697c80a6c8436cae" as const; /** * Registered Tauri commands the Peer Device controller keeps on the controller @@ -211,6 +211,7 @@ export const PEER_HOST_CAPABILITY_IDS = [ "workspace_icon_v1", "workspace_id_references_v1", "workspace_html_preview_v1", + "workspace_latex_preview_v1", "whole_session_copy_v1", "session_trajectory_v1", "session_reference_browse_v1", @@ -269,6 +270,7 @@ export const PEER_HOST_ADVERTISED_CAPABILITIES: Readonly< "workspace_icon_v1", "workspace_id_references_v1", "workspace_html_preview_v1", + "workspace_latex_preview_v1", "whole_session_copy_v1", "session_trajectory_v1", "session_reference_browse_v1", diff --git a/src/web-ui/src/infrastructure/api/logSanitizer.ts b/src/web-ui/src/infrastructure/api/logSanitizer.ts index 090133ebe2..4c7ed8cca0 100644 --- a/src/web-ui/src/infrastructure/api/logSanitizer.ts +++ b/src/web-ui/src/infrastructure/api/logSanitizer.ts @@ -12,7 +12,7 @@ const SENSITIVE_KEY_PATTERNS = [ 'set-cookie', 'token', ]; -const OPAQUE_VALUE_KEYS = new Set(['body']); +const OPAQUE_VALUE_KEYS = new Set(['body', 'pdfbase64']); const MAX_LOG_STRING_LENGTH = 500; const MAX_LOG_ARRAY_ITEMS = 10; const MAX_LOG_OBJECT_KEYS = 30; diff --git a/src/web-ui/src/infrastructure/api/service-api/LatexAPI.test.ts b/src/web-ui/src/infrastructure/api/service-api/LatexAPI.test.ts new file mode 100644 index 0000000000..73560f9fd2 --- /dev/null +++ b/src/web-ui/src/infrastructure/api/service-api/LatexAPI.test.ts @@ -0,0 +1,40 @@ +import { afterEach, expect, it, vi } from 'vitest'; +import { activateSurface } from '@/infrastructure/peer-device/deviceSurface'; +import { compileWorkspaceLatex } from './LatexAPI'; + +const host = vi.hoisted(() => ({ invoke: vi.fn(), supportsPreview: false })); +vi.mock('./ApiClient', () => ({ api: { invoke: host.invoke } })); +vi.mock('@/infrastructure/peer-device/PeerConnectionManager', () => ({ + peerConnectionManager: { + get: () => ({ + getState: () => ({ + capabilities: host.supportsPreview ? { workspaceLatexPreviewV1: true } : {}, + }), + }), + }, +})); + +afterEach(() => { + activateSurface('local'); + host.supportsPreview = false; + host.invoke.mockReset(); +}); + +it('keeps an older peer on the source-only path and dispatches only to an advertising host', async () => { + const origin = { surfaceId: 'peer-a', workspaceId: 'paper-id', workspacePath: '/remote/paper' }; + const path = '/remote/paper/main.tex'; + activateSurface('peer-a'); + await expect(compileWorkspaceLatex(origin, path, 'xelatex')).rejects.toThrow('does not support'); + expect(host.invoke).not.toHaveBeenCalled(); + + host.supportsPreview = true; + host.invoke.mockResolvedValue({ pdfBase64: 'compiled-preview' }); + await expect(compileWorkspaceLatex(origin, path, 'xelatex')).resolves.toEqual({ pdfBase64: 'compiled-preview' }); + expect(host.invoke).toHaveBeenCalledExactlyOnceWith('compile_workspace_latex', { + request: { workspaceId: 'paper-id', filePath: path, engine: 'xelatex' }, + }); + + activateSurface('peer-b'); + await expect(compileWorkspaceLatex(origin, path, 'xelatex')).rejects.toThrow('unavailable'); + expect(host.invoke).toHaveBeenCalledTimes(1); +}); diff --git a/src/web-ui/src/infrastructure/api/service-api/LatexAPI.ts b/src/web-ui/src/infrastructure/api/service-api/LatexAPI.ts new file mode 100644 index 0000000000..1b9d283726 --- /dev/null +++ b/src/web-ui/src/infrastructure/api/service-api/LatexAPI.ts @@ -0,0 +1,25 @@ +import { isLocalSurface } from '@/infrastructure/peer-device/deviceSurface'; +import { peerConnectionManager, type PeerHostCapabilities } from '@/infrastructure/peer-device/PeerConnectionManager'; +import { isTauriRuntime } from '@/infrastructure/runtime'; +import type { ContentResourceScope } from '@/shared/types/contentResource'; +import { invokePrepared } from './invokePrepared'; + +export type LatexEngine = 'pdflatex' | 'xelatex'; + +export function supportsLatexPreview(surfaceId: string, capabilities?: PeerHostCapabilities | null): boolean { + return isLocalSurface(surfaceId) ? isTauriRuntime() : capabilities?.workspaceLatexPreviewV1 === true; +} + +export async function compileWorkspaceLatex(origin: ContentResourceScope, filePath: string, engine: LatexEngine) { + const { workspaceId, surfaceId } = origin; + return invokePrepared<{ pdfBase64: string }>('compile_workspace_latex', async scope => { + if (scope.surfaceId !== surfaceId || !workspaceId) { + throw new Error('The LaTeX source workspace is unavailable on this device.'); + } + const capabilities = peerConnectionManager.get(surfaceId)?.getState().capabilities; + if (!supportsLatexPreview(surfaceId, capabilities)) { + throw new Error('This host does not support LaTeX preview.'); + } + return { request: { workspaceId, filePath, engine } }; + }); +} diff --git a/src/web-ui/src/infrastructure/appearance/registry/defaultAppearanceRegistry.ts b/src/web-ui/src/infrastructure/appearance/registry/defaultAppearanceRegistry.ts index 1f9ff26dfb..8fb8ebc23b 100644 --- a/src/web-ui/src/infrastructure/appearance/registry/defaultAppearanceRegistry.ts +++ b/src/web-ui/src/infrastructure/appearance/registry/defaultAppearanceRegistry.ts @@ -179,6 +179,7 @@ import { mcpResourceBrowserAppearanceDescriptor } from '@/infrastructure/config/ import { editorStatusBarAppearanceDescriptor } from '@/tools/editor/components/EditorStatusBar.appearance'; import { imageViewerAppearanceDescriptor } from '@/tools/editor/components/ImageViewer.appearance'; import { pdfViewerAppearanceDescriptor } from '@/tools/editor/components/PdfViewer.appearance'; +import { latexEditorAppearanceDescriptor } from '@/tools/editor/components/LatexEditor.appearance'; import { branchQuickSwitchAppearanceDescriptor } from '@/tools/git/components/BranchQuickSwitch.appearance'; import { workspaceListSectionAppearanceDescriptor } from '@/app/components/NavPanel/sections/workspaces/WorkspaceListSection.appearance'; import { navDeviceSectionAppearanceDescriptor } from '@/app/components/NavPanel/sections/devices/DeviceWorkspaceSections.appearance'; @@ -455,6 +456,7 @@ export function createDefaultAppearanceRegistry(): AppearanceRegistry { .registerComponent(editorStatusBarAppearanceDescriptor) .registerComponent(imageViewerAppearanceDescriptor) .registerComponent(pdfViewerAppearanceDescriptor) + .registerComponent(latexEditorAppearanceDescriptor) .registerComponent(branchQuickSwitchAppearanceDescriptor) .registerComponent(workspaceListSectionAppearanceDescriptor) .registerComponent(navDeviceSectionAppearanceDescriptor) diff --git a/src/web-ui/src/infrastructure/i18n/presets/generatedLocaleContract.ts b/src/web-ui/src/infrastructure/i18n/presets/generatedLocaleContract.ts index 7baaf01361..d9a29095a2 100644 --- a/src/web-ui/src/infrastructure/i18n/presets/generatedLocaleContract.ts +++ b/src/web-ui/src/infrastructure/i18n/presets/generatedLocaleContract.ts @@ -60,6 +60,7 @@ export const SHARED_TERMS_BY_LOCALE = { "Claw": "助理", "Cowork": "办公协作", "DeepResearch": "深度研究", + "PaperWriting": "论文写作", "ComputerUse": "电脑操作", "default": "默认助手" }, @@ -122,6 +123,7 @@ export const SHARED_TERMS_BY_LOCALE = { "Claw": "Assistant", "Cowork": "Cowork", "DeepResearch": "Deep Research", + "PaperWriting": "Paper Writing", "ComputerUse": "Computer Use", "default": "Default Assistant" }, @@ -184,6 +186,7 @@ export const SHARED_TERMS_BY_LOCALE = { "Claw": "助理", "Cowork": "辦公協作", "DeepResearch": "深度研究", + "PaperWriting": "論文寫作", "ComputerUse": "電腦操作", "default": "預設助手" }, diff --git a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts index 396b0c968f..7874345d18 100644 --- a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts +++ b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts @@ -115,6 +115,7 @@ export interface PeerHostCapabilities { readonly workspaceIconV1?: boolean; readonly workspaceIdReferencesV1?: boolean; readonly gitTrackedChangeCountV1?: boolean; + readonly workspaceLatexPreviewV1?: boolean; /** * Host implements `submit_user_answers` for Runtime-owned * AskUserQuestion interactions. Older Desktop hosts already implemented the @@ -240,6 +241,7 @@ const NO_CAPABILITIES: PeerHostCapabilities = { sessionReferenceBrowseV1: false, workspaceIconV1: false, workspaceIdReferencesV1: false, + workspaceLatexPreviewV1: false, userQuestionResponse: null, // Host kind is unknown until the first `peer_mode_ping` resolves. Consumers // treat `null` optimistically. See PR #2428 round 5 #1. @@ -612,6 +614,7 @@ export class PeerConnectionManager { workspaceIconV1: caps?.workspace_icon_v1 === true, workspaceIdReferencesV1: caps?.workspace_id_references_v1 === true, gitTrackedChangeCountV1: caps?.git_tracked_change_count_v1 === true, + workspaceLatexPreviewV1: caps?.workspace_latex_preview_v1 === true, userQuestionResponse, userQuestionInteraction: caps?.user_question_interaction_v1 === true, dialogQueueV1: caps?.dialog_queue_v1 === true, @@ -879,6 +882,7 @@ function capabilitiesEqual( a.workspaceIconV1 === b.workspaceIconV1 && a.workspaceIdReferencesV1 === b.workspaceIdReferencesV1 && a.gitTrackedChangeCountV1 === b.gitTrackedChangeCountV1 && + a.workspaceLatexPreviewV1 === b.workspaceLatexPreviewV1 && a.userQuestionResponse === b.userQuestionResponse && a.userQuestionInteraction === b.userQuestionInteraction && a.dialogQueueV1 === b.dialogQueueV1 && diff --git a/src/web-ui/src/locales/en-US/flow-chat.json b/src/web-ui/src/locales/en-US/flow-chat.json index 7ec0386629..8daadd89ba 100644 --- a/src/web-ui/src/locales/en-US/flow-chat.json +++ b/src/web-ui/src/locales/en-US/flow-chat.json @@ -1190,6 +1190,7 @@ "Cowork": "$t(shared:agents.Cowork)", "ComputerUse": "$t(shared:agents.ComputerUse)", "DeepResearch": "$t(shared:agents.DeepResearch)", + "PaperWriting": "$t(shared:agents.PaperWriting)", "Standard": "$t(shared:agents.Standard)", "Ultimate": "$t(shared:agents.Ultimate)", "Minimal": "$t(shared:agents.Minimal)", diff --git a/src/web-ui/src/locales/en-US/scenes/agents.json b/src/web-ui/src/locales/en-US/scenes/agents.json index 64eb865121..d6e618b7e4 100644 --- a/src/web-ui/src/locales/en-US/scenes/agents.json +++ b/src/web-ui/src/locales/en-US/scenes/agents.json @@ -394,6 +394,7 @@ "Cowork": "Office collaboration Agent: help with office and research tasks, confirming key steps with you.", "ComputerUse": "Computer use SubAgent: perform delegated work in browsers, desktop apps, and file systems.", "DeepResearch": "Deep research agent: conduct systematic investigation and analysis on complex topics", + "PaperWriting": "Draft and revise academic manuscripts in LaTeX, with bibliography, figures, and a compiled PDF.", "ResearchSpecialist": "Finds and evaluates web sources to deliver focused research with clear supporting evidence.", "GeneralPurpose": "Combines search, analysis, and coding to complete multi-step tasks independently.", "Explore": "Explore SubAgent: quickly browse the codebase to understand project structure and key files", diff --git a/src/web-ui/src/locales/en-US/tools.json b/src/web-ui/src/locales/en-US/tools.json index f1aa2e448a..a9ad27b1cb 100644 --- a/src/web-ui/src/locales/en-US/tools.json +++ b/src/web-ui/src/locales/en-US/tools.json @@ -119,6 +119,20 @@ "exitFullscreen": "Exit fullscreen", "imageUrlEmpty": "Image URL is empty" }, + "latexEditor": { + "preview": "PDF preview", + "engine": "LaTeX engine", + "compile": "Save & compile", + "compiling": "Compiling…", + "autoCompile": "Auto compile", + "autoCompileHint": "Automatically save and compile this source when you pause. Enable for projects you trust.", + "resize": "Resize LaTeX source and PDF preview", + "empty": "Open the main .tex file and compile to see the typeset PDF. The workspace host needs latexmk and the selected TeX engine.", + "unavailable": "LaTeX compilation requires a supported OpenBitFun Desktop host and an opened workspace.", + "compileFailed": "Compilation failed. View log", + "stalePreview": "Compilation failed. Showing the last successful PDF", + "saveFailed": "The source could not be saved. Save your changes before compiling." + }, "pdfViewer": { "loading": "Loading PDF...", "filePathEmpty": "File path is empty", diff --git a/src/web-ui/src/locales/zh-CN/flow-chat.json b/src/web-ui/src/locales/zh-CN/flow-chat.json index 41dae38327..5006efa542 100644 --- a/src/web-ui/src/locales/zh-CN/flow-chat.json +++ b/src/web-ui/src/locales/zh-CN/flow-chat.json @@ -1184,6 +1184,7 @@ "Cowork": "$t(shared:agents.Cowork)", "ComputerUse": "$t(shared:agents.ComputerUse)", "DeepResearch": "$t(shared:agents.DeepResearch)", + "PaperWriting": "$t(shared:agents.PaperWriting)", "Standard": "$t(shared:agents.Standard)", "Ultimate": "$t(shared:agents.Ultimate)", "Minimal": "$t(shared:agents.Minimal)", diff --git a/src/web-ui/src/locales/zh-CN/scenes/agents.json b/src/web-ui/src/locales/zh-CN/scenes/agents.json index 4303423d6f..44d29ecbf9 100644 --- a/src/web-ui/src/locales/zh-CN/scenes/agents.json +++ b/src/web-ui/src/locales/zh-CN/scenes/agents.json @@ -394,6 +394,7 @@ "Cowork": "办公协作智能体:协助处理办公与研究任务,在关键步骤与您确认。", "ComputerUse": "电脑操作子智能体:受委派操作浏览器、桌面应用和文件系统。", "DeepResearch": "深度研究智能体:对复杂主题进行系统性调研和分析", + "PaperWriting": "撰写和修改 LaTeX 论文,整理文献引用和图表,并编译成稿 PDF。", "ResearchSpecialist": "聚焦网络调研,检索可靠资料并整理有来源依据的研究结论。", "GeneralPurpose": "结合检索、分析与编程能力,独立完成多步骤任务。", "Explore": "探索子智能体:快速浏览代码库,理解项目结构和关键文件", diff --git a/src/web-ui/src/locales/zh-CN/tools.json b/src/web-ui/src/locales/zh-CN/tools.json index 609c5b147f..f2b1d20e97 100644 --- a/src/web-ui/src/locales/zh-CN/tools.json +++ b/src/web-ui/src/locales/zh-CN/tools.json @@ -119,6 +119,20 @@ "exitFullscreen": "退出全屏", "imageUrlEmpty": "图片URL为空" }, + "latexEditor": { + "preview": "PDF 预览", + "engine": "LaTeX 引擎", + "compile": "保存并编译", + "compiling": "正在编译…", + "autoCompile": "自动编译", + "autoCompileHint": "停顿时自动保存并编译当前源码。请在信任的项目中开启。", + "resize": "调整 LaTeX 源码和 PDF 预览的宽度", + "empty": "打开主 .tex 文件并编译,即可预览排版后的 PDF。工作区所在机器需要安装 latexmk 和所选的 TeX 引擎。", + "unavailable": "LaTeX 编译需要支持此功能的 OpenBitFun 桌面宿主,以及已打开的工作区。", + "compileFailed": "编译失败,查看日志", + "stalePreview": "编译失败,正在显示上次成功的 PDF", + "saveFailed": "源码保存未完成。请保存修改后再编译。" + }, "pdfViewer": { "loading": "正在加载 PDF...", "filePathEmpty": "文件路径为空", diff --git a/src/web-ui/src/locales/zh-TW/flow-chat.json b/src/web-ui/src/locales/zh-TW/flow-chat.json index 55b8dd356d..06ba4d5d18 100644 --- a/src/web-ui/src/locales/zh-TW/flow-chat.json +++ b/src/web-ui/src/locales/zh-TW/flow-chat.json @@ -1184,6 +1184,7 @@ "Cowork": "$t(shared:agents.Cowork)", "ComputerUse": "$t(shared:agents.ComputerUse)", "DeepResearch": "$t(shared:agents.DeepResearch)", + "PaperWriting": "$t(shared:agents.PaperWriting)", "Standard": "$t(shared:agents.Standard)", "Ultimate": "$t(shared:agents.Ultimate)", "Minimal": "$t(shared:agents.Minimal)", diff --git a/src/web-ui/src/locales/zh-TW/scenes/agents.json b/src/web-ui/src/locales/zh-TW/scenes/agents.json index 79f360a259..27c4372dff 100644 --- a/src/web-ui/src/locales/zh-TW/scenes/agents.json +++ b/src/web-ui/src/locales/zh-TW/scenes/agents.json @@ -394,6 +394,7 @@ "Cowork": "辦公協作智能體:協助處理辦公與研究任務,在關鍵步驟與您確認。", "ComputerUse": "電腦操作子智能體:受委派操作瀏覽器、桌面應用程式與檔案系統。", "DeepResearch": "深度研究智能體:對複雜主題進行系統性調研和分析", + "PaperWriting": "撰寫和修改 LaTeX 論文,整理文獻引用和圖表,並編譯成稿 PDF。", "ResearchSpecialist": "聚焦網路調研,檢索可靠資料並整理有來源依據的研究結論。", "GeneralPurpose": "結合檢索、分析與程式設計能力,獨立完成多步驟任務。", "Explore": "探索子智能體:快速瀏覽程式碼庫,理解專案結構和關鍵檔案", diff --git a/src/web-ui/src/locales/zh-TW/tools.json b/src/web-ui/src/locales/zh-TW/tools.json index 201a5f83b4..5bb31f315d 100644 --- a/src/web-ui/src/locales/zh-TW/tools.json +++ b/src/web-ui/src/locales/zh-TW/tools.json @@ -119,6 +119,20 @@ "exitFullscreen": "退出全屏", "imageUrlEmpty": "圖片URL為空" }, + "latexEditor": { + "preview": "PDF 預覽", + "engine": "LaTeX 引擎", + "compile": "儲存並編譯", + "compiling": "正在編譯…", + "autoCompile": "自動編譯", + "autoCompileHint": "停頓時自動儲存並編譯目前的原始碼。請在信任的專案中開啟。", + "resize": "調整 LaTeX 原始碼和 PDF 預覽的寬度", + "empty": "開啟主 .tex 檔案並編譯,即可預覽排版後的 PDF。工作區所在的裝置需要安裝 latexmk 和選取的 TeX 引擎。", + "unavailable": "LaTeX 編譯需要支援此功能的 OpenBitFun 桌面主機,以及已開啟的工作區。", + "compileFailed": "編譯失敗,查看記錄", + "stalePreview": "編譯失敗,正在顯示上次成功的 PDF", + "saveFailed": "原始碼尚未儲存。請儲存變更後再編譯。" + }, "pdfViewer": { "loading": "正在載入 PDF...", "filePathEmpty": "檔案路徑為空", diff --git a/src/web-ui/src/shared/agents/identity.ts b/src/web-ui/src/shared/agents/identity.ts index 8b91180e68..019d1c01d4 100644 --- a/src/web-ui/src/shared/agents/identity.ts +++ b/src/web-ui/src/shared/agents/identity.ts @@ -27,6 +27,7 @@ const BUILTIN_NAME_KEYS: Readonly> = { Claw: 'shared:agents.Claw', Cowork: 'shared:agents.Cowork', DeepResearch: 'shared:agents.DeepResearch', + PaperWriting: 'shared:agents.PaperWriting', ComputerUse: 'shared:agents.ComputerUse', }; diff --git a/src/web-ui/src/tools/editor/AGENTS.md b/src/web-ui/src/tools/editor/AGENTS.md index 6db4be5ebf..9a0ce1012e 100644 --- a/src/web-ui/src/tools/editor/AGENTS.md +++ b/src/web-ui/src/tools/editor/AGENTS.md @@ -91,6 +91,15 @@ For UI, types, and theme contracts, also follow the parent guide's `check:web` command. Local DOM tests do not establish remote workspace, Remote Connect, Peer Device Mode, or Detached Dispatch behavior. +For the LaTeX source and PDF split, run: + +```bash +pnpm --dir src/web-ui run test:run src/tools/editor/components/LatexEditor.test.tsx src/tools/editor/components/PdfViewer.test.tsx src/infrastructure/api/service-api/LatexAPI.test.ts +``` + +The fixtures cover save ordering, coalesced rebuilds, last-successful preview, +and the peer capability gate. Use the Desktop compiler tests for real TeX. + For rich-text interaction changes, run the focused browser E2E from the root: ```bash diff --git a/src/web-ui/src/tools/editor/components/CodeEditor.tsx b/src/web-ui/src/tools/editor/components/CodeEditor.tsx index 254479a193..d7cd266431 100644 --- a/src/web-ui/src/tools/editor/components/CodeEditor.tsx +++ b/src/web-ui/src/tools/editor/components/CodeEditor.tsx @@ -303,6 +303,7 @@ const CodeEditor: React.FC = ({ const navigationSettleFrameRef = useRef(null); const filePathRef = useRef(filePath); const saveFileContentRef = useRef<() => Promise>(); + const saveInFlightRef = useRef>(); const latestEditorConfigRef = useRef | null>(null); const delayedFontApplyTimerRef = useRef | null>(null); const userLanguageOverrideRef = useRef(false); @@ -1649,7 +1650,7 @@ const CodeEditor: React.FC = ({ ]); // Save file content - const saveFileContent = useCallback(async () => { + const persistFileContent = useCallback(async () => { if (!filePath) return; if (isMemoryContent) return; @@ -1743,6 +1744,15 @@ const CodeEditor: React.FC = ({ t, workspacePath, ]); + + const saveFileContent = useCallback(() => { + if (!saveInFlightRef.current) { + saveInFlightRef.current = persistFileContent().finally(() => { + saveInFlightRef.current = undefined; + }); + } + return saveInFlightRef.current; + }, [persistFileContent]); useEffect(() => { saveFileContentRef.current = saveFileContent; diff --git a/src/web-ui/src/tools/editor/components/LatexEditor.appearance.ts b/src/web-ui/src/tools/editor/components/LatexEditor.appearance.ts new file mode 100644 index 0000000000..f866b48a99 --- /dev/null +++ b/src/web-ui/src/tools/editor/components/LatexEditor.appearance.ts @@ -0,0 +1,11 @@ +import type { AppearanceSurfaceDescriptor } from '@/infrastructure/appearance'; + +export const latexEditorAppearanceDescriptor: AppearanceSurfaceDescriptor = { + id: 'latex-editor', + parts: [ + { id: 'preview' }, + { id: 'toolbar' }, + { id: 'diagnostics' }, + { id: 'empty' }, + ], +}; diff --git a/src/web-ui/src/tools/editor/components/LatexEditor.scss b/src/web-ui/src/tools/editor/components/LatexEditor.scss new file mode 100644 index 0000000000..4d5db83b2f --- /dev/null +++ b/src/web-ui/src/tools/editor/components/LatexEditor.scss @@ -0,0 +1,63 @@ +.latex-editor { + width: 100%; + height: 100%; + min-width: 0; + min-height: 0; + + &__preview { + display: flex; + flex-direction: column; + height: 100%; + min-width: 0; + min-height: 0; + background: var(--openbitfun-color-surface-canvas); + color: var(--openbitfun-color-content-primary); + font-size: var(--openbitfun-type-body-sm-font-size); + } + + &__toolbar { + display: flex; + flex-wrap: wrap; + flex-shrink: 0; + align-items: center; + gap: var(--openbitfun-space-2); + padding: var(--openbitfun-space-2) var(--openbitfun-space-3); + border-bottom: 1px solid var(--openbitfun-color-border-subtle); + } + + &__auto { + display: inline-flex; + align-items: center; + gap: var(--openbitfun-space-2); + } + + &__engine { + width: 110px; + } + + &__empty { + display: grid; + flex: 1; + place-content: center; + padding: var(--openbitfun-space-5); + color: var(--openbitfun-color-content-secondary); + text-align: center; + } + + &__diagnostics { + max-height: 45%; + padding: var(--openbitfun-space-2) var(--openbitfun-space-3); + overflow: auto; + border-bottom: 1px solid var(--openbitfun-color-border-subtle); + } + + &__log { + white-space: pre-wrap; + overflow-wrap: anywhere; + } + + &__pdf { + flex: 1; + min-height: 0; + } +} diff --git a/src/web-ui/src/tools/editor/components/LatexEditor.test.tsx b/src/web-ui/src/tools/editor/components/LatexEditor.test.tsx new file mode 100644 index 0000000000..a73e09da01 --- /dev/null +++ b/src/web-ui/src/tools/editor/components/LatexEditor.test.tsx @@ -0,0 +1,125 @@ +// @vitest-environment jsdom + +import { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import LatexEditor from './LatexEditor'; +import { EditorDocument, EditorDocumentContext } from '../services/EditorDocument'; +import { activateSurface } from '@/infrastructure/peer-device/deviceSurface'; + +const mocks = vi.hoisted(() => ({ + invoke: vi.fn(), + supported: true, + sourceProps: undefined as import('./CodeEditor').CodeEditorProps | undefined, +})); + +vi.mock('@/infrastructure/api/service-api/LatexAPI', () => ({ + compileWorkspaceLatex: mocks.invoke, + supportsLatexPreview: () => mocks.supported, +})); +vi.mock('@/infrastructure/i18n', () => { + const t = (key: string) => key; + return { useI18n: () => ({ t }) }; +}); +vi.mock('./CodeEditor', () => ({ + default: (props: import('./CodeEditor').CodeEditorProps) => { + mocks.sourceProps = props; + return