Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(release): backport #9140, #9153, #9151, #9164 and #9162 to v0.8.5 (CUDA graphs blocker, orphan sweep, Windows QA fixes) (#9165)
James Dam79932ec4f4d2
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/cmdscan.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/cmdscan.rsindex 1fcf68d06..f91472784 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/cmdscan.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/cmdscan.rs@@ -51,7 +51,7 @@ const OPAQUE: &[&str] = &[/// Builtins that assign to the variable names in their arguments. Plain when/// every name is an ordinary one: not one of [`RESOLUTION_VARS`] and with no/// `[...]` subscript, which bash evaluates as arithmetic.-const ASSIGNING_BUILTINS: &[&str] = &["export", "unset", "read", "set"];+const ASSIGNING_BUILTINS: &[&str] = &["export", "unset", "read", "set", "setx"];/// Shell and loader variables that decide which program a name runs, or that/// run code on their own (`BASH_ENV`, `PS4` under `set -x`). Assigning one/// changes what an already granted base means. Matched case-insensitively.@@ -116,9 +116,12 @@ const WINDOWS_OPAQUE: &[&str] = &[const POWERSHELL_ONLY_OPAQUE: &[&str] = &["cp", "copy", "mv", "move", "ren", "set"];/// Whether assigning `name` (a variable name, optionally `+=`-suffixed or-/// with an `env:` drive) can change what a granted base runs.+/// with an `env:` drive) can change what a granted base runs. `^` is cmd's+/// escape character and is stripped from every token before cmd acts on it,+/// so `PA^TH` sets `PATH`; matching on the literal text would miss that.fn is_resolution_var(name: &str) -> bool {- let lower = name.to_ascii_lowercase();+ let unescaped: String = name.chars().filter(|&c| c != '^').collect();+ let lower = unescaped.to_ascii_lowercase();let lower = lower.trim_end_matches('+');let lower = lower.strip_prefix("env:").unwrap_or(lower);RESOLUTION_VARS.contains(&lower) || RESOLUTION_VAR_PREFIXES.iter().any(|p| lower.starts_with(p))@@ -406,6 +409,20 @@ fn windows_name(base: &str) -> String {lower.strip_suffix(".exe").unwrap_or(&lower).to_string()}+/// GNU `time`'s getopt spec is `+af:o:pqvV`: only `-f`/`--format` and+/// `-o`/`--output` take a separate value; `-a`, `-p`, `-q`, `-v`, `-V` do+/// not and may combine into one cluster (`-aqvV`). Whether `t` is entirely+/// made of those no-value flags, so anything else (an unknown flag, a+/// cluster containing `f` or `o`, or a `--` abbreviation of `--format`/+/// `--output` such as `--out`) is treated as ambiguous rather than missed.+fn is_time_plain_flag(t: &str) -> bool {+ const LONG: &[&str] = &["--append", "--portability", "--quiet", "--verbose", "--version"];+ if let Some(short) = t.strip_prefix('-').filter(|s| !s.starts_with('-')) {+ return !short.is_empty() && short.chars().all(|c| "apqvV".contains(c));+ }+ LONG.contains(&t)+}+/// Whether `seg` holds a brace outside quotes and outside a `${...}` variable./// Such a brace is a PowerShell script block (`& { ... }`, `%{ ... }`,/// `try{...}finally{...}`) or a POSIX `{ ...; }` group, whose contents are not@@ -533,7 +550,8 @@ const WRAPPERS: &[&str] = &["until", "for", "case", "select", "coproc", "!",];/// [`WRAPPERS`] with a flag that takes a separate value.-const VALUE_FLAG_WRAPPERS: &[&str] = &["nice", "timeout", "stdbuf", "ionice", "chrt", "exec"];+const VALUE_FLAG_WRAPPERS: &[&str] =+ &["nice", "timeout", "stdbuf", "ionice", "chrt", "exec", "time"];/// Typographic quotes PowerShell accepts as `'` (U+2018-U+201B) and `"`/// (U+201C-U+201E), each closing a string any of its class opened.@@ -968,10 +986,17 @@ fn scan_segment(seg: &str, bases: &mut BTreeSet<String>, kind: ShellKind, depth:// A bare flag followed by a word may take that word as its// value (`timeout -s KILL 5 rm`, `exec -a ls rm`), so which// token is the command is ambiguous. Attached values- // (`-oL`, `--signal=KILL`) are not.- let bare_flag = (t.len() == 2 && t.starts_with('-') && !numeric(&t[1..]))- || (t.starts_with("--") && !t.contains('='));- if bare_flag+ // (`-oL`, `--signal=KILL`) are not. `time` is checked by+ // `is_time_plain_flag` instead, which whitelists its+ // no-value flags so unknown/combined/abbreviated spellings+ // default to ambiguous rather than being missed.+ let value_flag = if base.as_str() == "time" {+ t.starts_with('-') && !is_time_plain_flag(t)+ } else {+ (t.len() == 2 && t.starts_with('-') && !numeric(&t[1..]))+ || (t.starts_with("--") && !t.contains('='))+ };+ if value_flag&& VALUE_FLAG_WRAPPERS.contains(&base.as_str())&& tokens.get(idx + 1).is_some_and(|n| !n.starts_with('-') && !numeric(n)){@@ -1467,6 +1492,20 @@ mod tests {"nice PATH=/tmp ls","set PATH=C:\\evil","path C:\\evil",+ // janhq/jan#9149: `time -o FILE cmd` writes to `FILE` and+ // runs `cmd`, not `FILE`; `-o` must not be skipped as an+ // ordinary flag. `-f`/`--format` take a value too, and so+ // does `-o` combined into a short-flag cluster (`-ao`) or+ // spelled as a getopt_long abbreviation (`--out`).+ "time -o ls rm -rf ~",+ "command time -o ls rm -rf ~",+ "/usr/bin/time -o ls rm x",+ "time -f ls rm -rf ~",+ "time -ao ls rm -rf ~",+ "time --out ls rm -rf ~",+ "time --format ls rm -rf ~",+ "time --forma ls rm -rf ~",+ "time -zo ls rm -rf ~",// A command word built at run time."l$x -la","/bin/r? x",@@ -1492,6 +1531,11 @@ mod tests {plain("timeout --signal=KILL 5 curl u", kind, &["curl"]);plain("nice -n 10 make", kind, &["make"]);plain("stdbuf -oL make", kind, &["make"]);+ // janhq/jan#9149: `time`'s no-value flags still yield its+ // wrapped command.+ plain("time -p ls", kind, &["ls"]);+ plain("time -aqvV ls", kind, &["ls"]);+ plain("time --verbose ls", kind, &["ls"]);plain("read -r line < f", kind, &["read"]);plain("echo \"$(git rev-parse HEAD)\"", kind, &["echo", "git"]);// A path stays the base: `./ls` is not the granted `ls`.@@ -1558,6 +1602,25 @@ mod tests {plain("./build.ps1 -Release", ShellKind::PowerShell, &["./build.ps1"]);}+ /// janhq/jan#9149: cmd strips `^` from every token before acting on it,+ /// so `set PA^TH=...` and `setx` can still change `PATH` even though the+ /// literal assignment name does not match `PATH`.+ #[test]+ fn cmd_caret_and_setx_assignments_are_opaque() {+ for command in [+ "set PA^TH=C:\\evil& git status",+ "setx PATH C:\\evil & git status",+ "setx PA^TH C:\\evil & git status",+ ] {+ assert_eq!(scan_command_as(command, ShellKind::Cmd), CommandScan::Opaque, "{command}");+ }+ // The un-escaped, quoted form was already caught before #9149.+ assert_eq!(+ scan_command_as("set \"PATH=C:\\evil\" & git status", ShellKind::Cmd),+ CommandScan::Opaque+ );+ }+#[test]fn empty_command_has_no_bases() {assert_eq!(bases(""), set(&[]));diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rsindex c1de5dc66..604c7fd4c 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs@@ -400,14 +400,13 @@ const TEMP_ENV_KEYS: &[&str] = &["TMPDIR", "TMP", "TEMP"];/// `cargo test` binary or incremental artifact can pass a gigabyte on its own./// Caps that low break ordinary work long before they stop abuse. `FSIZE` is a/// per-file cap enforced with `SIGXFSZ`, so exceeding it kills the writer rather-/// than returning an error most tools report clearly.+/// than returning an error most tools report clearly. Linux `NPROC` is omitted+/// because the kernel counts it across the entire real UID, so unrelated host+/// processes can exhaust a limit mounted on one Jan shell. Per-run process-tree+/// isolation requires a cgroup `pids.max`; until then the child inherits the+/// launcher's process limit.#[cfg(unix)]const CHILD_LIMITS: &[(RlimitResource, u64)] = &[- // Linux counts NPROC across the entire UID, not one Jan child tree. Keep a- // finite fork-bomb guard without making ordinary workstation activity starve- // agent-tool shells. macOS inherits its host-managed per-UID ceiling instead.- #[cfg(target_os = "linux")]- (nix::libc::RLIMIT_NPROC, 8192),(nix::libc::RLIMIT_NOFILE, 65536),(nix::libc::RLIMIT_FSIZE, 16 * 1024 * 1024 * 1024),];@@ -423,12 +422,12 @@ type RlimitResource = nix::libc::c_int;/// Bound the resource exhaustion a sandboxed command could otherwise trigger on/// the host. `bwrap` 0.6.1 (and older) has no `--rlimit`, so instead we clamp the/// child's soft limits here, before exec, from the one choke point every backend-/// funnels through. Linux `NPROC` still constrains fork bombs, while descriptor-/// exhaustion and disk fill are capped by `NOFILE` and `FSIZE`. The hard limit is-/// left at the host's value so a command that genuinely needs more can raise its-/// own soft limit back up. The bwrap wrapper execs `bwrap` itself, which sets up-/// the namespace and then execs the real shell, so the limits carry over to every-/// descendant. Linux only; the Windows AppContainer child is limited by its token.+/// funnels through. Descriptor exhaustion and disk fill are capped by `NOFILE`+/// and `FSIZE`. The hard limit is left at the host's value so a command that+/// genuinely needs more can raise its own soft limit back up. The bwrap wrapper+/// execs `bwrap` itself, which sets up the namespace and then execs the real+/// shell, so the limits carry over to every descendant. Unix only; the Windows+/// AppContainer child is limited by its token.#[cfg(unix)]fn confine_limits(cmd: &mut Command) {// `tokio::process::Command::pre_exec` (unix) is the std `pre_exec`; the call@@ -1278,7 +1277,7 @@ mod tests {// Spawn a shell that reports its own soft limits; confine_limits sets// each to the target, bounded by whatever hard limit the host allows.- // `ulimit -f` reports FSIZE in 1024-byte blocks; `-n` and `-u` are raw.+ // `ulimit -f` reports FSIZE in 1024-byte blocks; `-n` is a raw count.for (name, flag, resource, target, unit) in [("NOFILE", "-n", nix::libc::RLIMIT_NOFILE, 65536_u64, 1_u64),(@@ -1288,8 +1287,6 @@ mod tests {16 * 1024 * 1024 * 1024,1024,),- #[cfg(target_os = "linux")]- ("NPROC", "-u", nix::libc::RLIMIT_NPROC, 8192_u64, 1_u64),] {let cmd = format!("ulimit {flag}");let child = spawn(shell(), &cmd, &tmp(), None, ShellEnv::default(), None).await.unwrap();@@ -1316,6 +1313,44 @@ mod tests {);}}++ #[cfg(target_os = "linux")]+ #[tokio::test]+ async fn confine_limits_preserves_the_launcher_process_limit() {+ // NPROC counts every process owned by the real UID. Jan must inherit the+ // launcher's value so unrelated workstation activity cannot starve one+ // agent-tool shell at an arbitrary Jan-specific threshold.+ let mut launcher = nix::libc::rlimit {+ rlim_cur: 0,+ rlim_max: 0,+ };+ // # Safety: reads the test process's own limit into a local value.+ assert_eq!(+ unsafe { nix::libc::getrlimit(nix::libc::RLIMIT_NPROC, &mut launcher) },+ 0+ );++ let child = spawn(+ shell(),+ "ulimit -u",+ &tmp(),+ None,+ ShellEnv::default(),+ None,+ )+ .await+ .unwrap();+ let pid = child.id().unwrap();+ let out = child.wait_with_output().await.unwrap();+ unregister(None, pid);+ let actual = String::from_utf8_lossy(&out.stdout).trim().to_string();++ assert_eq!(+ actual,+ launcher.rlim_cur.to_string(),+ "NPROC soft limit should be inherited from the launcher, got: {actual}"+ );+ }}#[cfg(test)]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs b/src-tauri/plugins/tauri-plugin-llamacpp/build.rsindex 5bb709f9f..25d9af6ea 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/build.rs@@ -473,6 +473,15 @@ mod engine {// difference on a CUDA rebuild is minutes versus tens of minutes.// ggml picks up ccache or sccache, whichever it finds."-DGGML_CCACHE=ON",+ // llama.cpp turns both of these on in its top-level CMakeLists.txt,+ // which the wrapper above never reads; ggml's own default for each+ // is OFF. Without CUDA graphs every decode step launches each kernel+ // separately, which cost 2-4x in token generation against 0.8.4's+ // upstream-built engine (#9163). Without llamafile the CPU variants+ // lose the sgemm path upstream ships. Graphs is read only by the+ // CUDA backend, so it is inert for every other leg.+ "-DGGML_CUDA_GRAPHS=ON",+ "-DGGML_LLAMAFILE=ON",]);// Every ggml library is staged into one directory, so each can find// its siblings from its own location. cmake otherwise strips the rpathdiff --git a/src-tauri/src/core/system/orphans.rs b/src-tauri/src/core/system/orphans.rsindex bcd2b3279..79a7e78be 100644--- a/src-tauri/src/core/system/orphans.rs+++ b/src-tauri/src/core/system/orphans.rs@@ -12,13 +12,19 @@//! - it is `llama-server`,//! - it was started with `--models-preset <data folder>/llamacpp/router.preset.ini`,//! the preset file Jan writes, so it belongs to this data folder,-//! - its parent is gone or is not a Jan process, so a Jan that is still running-//! (another instance, or this one) keeps its engine. That includes a detached-//! `jan serve` from 0.8.4, which keeps its router as a live child.+//! - its parent is gone, is not a Jan process, or cannot be the process that+//! started it (see below), so a Jan that is still running (another instance,+//! or this one) keeps its engine. That includes a detached `jan serve` from+//! 0.8.4, which keeps its router as a live child.//!-//! Its descendants, the per-model children the router spawns, go with it. A-//! process counts as a descendant only if it started no earlier than the parent-//! it names, because Windows never reparents and reuses pids.+//! Its descendants, the per-model children the router spawns, go with it.+//!+//! Windows never reparents and reuses pids, so a pid in a parent link can name+//! a different, later process. Start times settle it: a process counts as a+//! descendant only if it started no earlier than the parent it names, and a+//! parent that started after its child is not its owner. When a start time is+//! unknown the order cannot be told: a router keeps its Jan, and a process is+//! never swept as a child on that evidence.use std::collections::{HashMap, HashSet};use std::path::Path;@@ -42,7 +48,17 @@ pub struct ProcInfo {}fn normalize(path: &str) -> String {- path.replace('\\', "/").to_ascii_lowercase()+ let path = path.replace('\\', "/").to_ascii_lowercase();+ // `\\?\C:\...` and `\\?\UNC\server\share\...` name the same file as their plain+ // form. 0.8.4 passes its preset path in the verbatim form, so without this+ // the sweep never recognises the engine it exists to reap.+ if let Some(rest) = path.strip_prefix("//?/unc/") {+ format!("//{rest}")+ } else if let Some(rest) = path.strip_prefix("//?/") {+ rest.to_string()+ } else {+ path+ }}fn is_router_binary(name: &str) -> bool {@@ -87,13 +103,33 @@ fn is_jan(name: &str) -> bool {name.to_ascii_lowercase().contains("jan")}-/// Orphaned when the parent no longer exists, was adopted by init (pid 1), or is-/// something other than Jan. The last case covers a systemd user session-/// adopting the process on Linux, where the new parent is not pid 1.+/// Whether `parent` could really be the parent of `child`: a parent cannot have+/// started after its child. Windows never reparents and reuses pids, so the+/// pid an old Jan had can be handed to a process started later, such as the+/// freshly launched new Jan. When either start time is unknown (0) the order+/// cannot be told and the parent is given the benefit of the doubt.+fn could_be_parent(parent: &ProcInfo, child: &ProcInfo) -> bool {+ parent.start_time == 0 || child.start_time == 0 || parent.start_time <= child.start_time+}++/// Whether `child` is provably a child of `parent`: it started no earlier than+/// the parent it names. An unknown start time (0) on either side proves+/// nothing, so the process is not treated as a child and is never killed on+/// that evidence.+fn is_child_of(child: &ProcInfo, parent: &ProcInfo) -> bool {+ child.start_time != 0 && parent.start_time != 0 && child.start_time >= parent.start_time+}++/// Orphaned when the parent no longer exists, was adopted by init (pid 1), is+/// something other than Jan, or cannot be the process that started it. The+/// third case covers a systemd user session adopting the process on Linux,+/// where the new parent is not pid 1.fn is_orphaned(proc: &ProcInfo, by_pid: &HashMap<u32, &ProcInfo>) -> bool {match proc.parent {None | Some(1) => true,- Some(parent) => by_pid.get(&parent).is_none_or(|p| !is_jan(&p.name)),+ Some(parent) => by_pid+ .get(&parent)+ .is_none_or(|p| !is_jan(&p.name) || !could_be_parent(p, proc)),}}@@ -127,14 +163,13 @@ pub fn orphaned_engine_pids(procs: &[ProcInfo], data_folder: &Path) -> Vec<u32>let Some(parent_pid) = p.parent else {continue;};- // A child cannot be older than its parent. Windows never reparents and- // reuses pids, so a live process can name a long-dead parent whose pid- // a router has since taken; without this check it would be swept as- // that router's child. An unknown start time (0) is left alone.- let started_after_parent = by_pid+ // Windows never reparents and reuses pids, so a live process can name a+ // long-dead parent whose pid a router has since taken; without this+ // check it would be swept as that router's child.+ let is_child = by_pid.get(&parent_pid)- .is_some_and(|parent| p.start_time >= parent.start_time);- if started_after_parent {+ .is_some_and(|parent| is_child_of(p, parent));+ if is_child {children.entry(parent_pid).or_default().push(p.pid);}}@@ -250,18 +285,24 @@ mod tests {#[test]fn a_router_adopted_by_init_is_swept_with_its_children_first() {let procs = [- router(200, Some(1)),- proc(- 201,- Some(200),- "llama-server",- &["llama-server", "-m", "a.gguf"],+ started_at(router(200, Some(1)), 100),+ started_at(+ proc(+ 201,+ Some(200),+ "llama-server",+ &["llama-server", "-m", "a.gguf"],+ ),+ 200,),- proc(- 202,- Some(200),- "llama-server",- &["llama-server", "-m", "b.gguf"],+ started_at(+ proc(+ 202,+ Some(200),+ "llama-server",+ &["llama-server", "-m", "b.gguf"],+ ),+ 200,),];let victims = sweep(&procs);@@ -361,6 +402,36 @@ mod tests {assert_eq!(victims, vec![200]);}+ #[test]+ fn verbatim_prefixed_preset_paths_match() {+ // 0.8.4 starts its router with `\\?\C:\...`, the form the sweep exists+ // to reap; `\\?\UNC\` is the same rule for a data folder on a share.+ for (pid, preset, data) in [+ (+ 200,+ "\\\\?\\C:\\Users\\u\\AppData\\Roaming\\Jan\\data\\llamacpp\\router.preset.ini",+ "C:\\Users\\u\\AppData\\Roaming\\Jan\\data",+ ),+ (+ 201,+ "\\\\?\\UNC\\srv\\share\\Jan\\data\\llamacpp\\router.preset.ini",+ "\\\\srv\\share\\Jan\\data",+ ),+ ] {+ let router = proc(+ pid,+ Some(4242),+ "llama-server.exe",+ &["llama-server.exe", "--models-preset", preset],+ );+ assert_eq!(+ orphaned_engine_pids(&[router], &PathBuf::from(data)),+ vec![pid],+ "{preset}"+ );+ }+ }+#[test]fn a_parent_cycle_from_pid_reuse_terminates() {// Windows never reparents and reuses pids: the router's dead parent's@@ -405,4 +476,58 @@ mod tests {victims.sort_unstable();assert_eq!(victims, vec![200, 301]);}++ #[test]+ fn a_jan_that_started_after_the_router_is_not_its_owner() {+ // Windows handed the old Jan's pid to the freshly launched new Jan.exe,+ // which started after the router and so cannot be its parent.+ let procs = [+ started_at(proc(50, Some(1), "Jan.exe", &["Jan.exe"]), 900),+ started_at(router(200, Some(50)), 500),+ ];+ assert_eq!(sweep(&procs), vec![200]);+ }++ #[test]+ fn a_jan_that_started_before_the_router_still_owns_it() {+ let procs = [+ started_at(proc(50, Some(1), "Jan.exe", &["Jan.exe"]), 100),+ started_at(router(200, Some(50)), 500),+ ];+ assert!(sweep(&procs).is_empty());+ }++ #[test]+ fn a_router_with_an_unknown_start_time_takes_no_live_process_with_it() {+ // With the router's own start time unknown, every process naming its+ // pid would otherwise count as started after it.+ let procs = [+ router(200, Some(1)),+ started_at(proc(300, Some(200), "explorer.exe", &["explorer.exe"]), 100),+ started_at(+ proc(+ 301,+ Some(200),+ "llama-server",+ &["llama-server", "-m", "a.gguf"],+ ),+ 600,+ ),+ ];+ assert_eq!(sweep(&procs), vec![200]);+ }++ #[test]+ fn a_process_with_an_unknown_start_time_is_not_taken_as_a_child() {+ let procs = [+ started_at(router(200, Some(1)), 500),+ proc(+ 301,+ Some(200),+ "llama-server",+ &["llama-server", "-m", "a.gguf"],+ ),+ ];+ assert_eq!(sweep(&procs), vec![200]);+ }}diff --git a/web-app/src/components/WindowControls.tsx b/web-app/src/components/WindowControls.tsxindex 34769c064..bd5b47b0d 100644--- a/web-app/src/components/WindowControls.tsx+++ b/web-app/src/components/WindowControls.tsx@@ -1,5 +1,5 @@-import { useCallback, useEffect, useMemo } from 'react'-import { Minus, Square, X } from 'lucide-react'+import { useCallback, useEffect, useMemo, useState } from 'react'+import { Copy, Minus, Square, X } from 'lucide-react'import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow'import { invoke } from '@tauri-apps/api/core'import { Button } from '@/components/ui/button'@@ -43,6 +43,27 @@ export const WindowControls = () => {}}, [appWindow, refresh])+ // Maximize, restore and OS snapping all resize the window, so re-read the+ // state on every resize to swap the Maximize/Restore glyph.+ const [isMaximized, setIsMaximized] = useState(false)+ useEffect(() => {+ let cancelled = false+ const sync = async () => {+ try {+ const maximized = await appWindow.isMaximized()+ if (!cancelled) setIsMaximized(maximized)+ } catch {+ // Missing permission must not break the title bar; keep last state.+ }+ }+ sync()+ const unlisten = appWindow.onResized(sync)+ return () => {+ cancelled = true+ unlisten.then((fn) => fn()).catch(() => {})+ }+ }, [appWindow])+const actions: Record<ButtonId, () => Promise<void>> = {minimize: () => appWindow.minimize(),maximize: () => appWindow.toggleMaximize(),@@ -50,12 +71,16 @@ export const WindowControls = () => {}const icons: Record<ButtonId, React.ReactNode> = {minimize: <Minus className="size-4" />,- maximize: <Square className="size-3" />,+ maximize: isMaximized ? (+ <Copy className="size-3" />+ ) : (+ <Square className="size-3" />+ ),close: <X className="size-4" />,}const labels: Record<ButtonId, string> = {minimize: 'Minimize',- maximize: 'Maximize',+ maximize: isMaximized ? 'Restore' : 'Maximize',close: 'Close',}diff --git a/web-app/src/components/ai-elements/conversation.tsx b/web-app/src/components/ai-elements/conversation.tsxindex 7240dbf23..ae1e11488 100644--- a/web-app/src/components/ai-elements/conversation.tsx+++ b/web-app/src/components/ai-elements/conversation.tsx@@ -1,5 +1,6 @@import { Button } from '@/components/ui/button'import { cn } from '@/lib/utils'+import { useTranslation } from '@/i18n/react-i18next-compat'import { IconArrowDown } from '@tabler/icons-react'import type { ComponentProps } from 'react'import { useCallback, memo } from 'react'@@ -71,6 +72,7 @@ export const ConversationScrollButton = ({className,...props}: ConversationScrollButtonProps) => {+ const { t } = useTranslation()const { isAtBottom, scrollToBottom } = useStickToBottomContext()const handleScrollToBottom = useCallback(() => {@@ -88,9 +90,11 @@ export const ConversationScrollButton = ({size="icon"type="button"variant="outline"+ aria-label={t('common:scrollToBottom')}+ title={t('common:scrollToBottom')}{...props}>- <IconArrowDown className="size-4" />+ <IconArrowDown className="size-4" aria-hidden="true" /></Button>))diff --git a/web-app/src/lib/__tests__/custom-chat-transport.test.ts b/web-app/src/lib/__tests__/custom-chat-transport.test.tsindex 37971b3e0..b479667f5 100644--- a/web-app/src/lib/__tests__/custom-chat-transport.test.ts+++ b/web-app/src/lib/__tests__/custom-chat-transport.test.ts@@ -6,6 +6,7 @@ import {coalesceMessagesForAlternation,effectiveContextWindow,hasGenuineUserQuery,+ isLocalChatServer,extractContextInfoFromError,normalizeToolInputSchema,resolveOrphanToolCalls,@@ -14,6 +15,7 @@ import {unwrapRetryError,} from '../custom-chat-transport'import { encodeToolImageSentinel } from '../tool-image-sentinel'+import { encodeAudioSentinel } from '../audio-sentinel'const userMsg = (id: string, text: string): UIMessage =>({@@ -458,26 +460,78 @@ describe('buildLlamacppReasoningParams', () => {})describe('coalesceMessagesForAlternation', () => {- it('drops an empty assistant placeholder and merges the surrounding users', () => {+ it('drops a failed turn instead of resending it inside the next question', () => {const input = [- userMsg('u1', 'first question'),+ userMsg('u1', 'failed question'),assistantMsg('a1', []),- userMsg('u2', 'retry after error'),+ userMsg('u2', 'new question'),]const out = coalesceMessagesForAlternation(input)expect(out).toHaveLength(1)- expect(out[0].role).toBe('user')- expect(out[0].parts).toEqual([- { type: 'text', text: 'first question\n\nretry after error' },- ])+ expect(out[0].id).toBe('u2')+ expect(out[0].parts).toEqual([{ type: 'text', text: 'new question' }])+ })++ it('keeps only the last of consecutive unanswered user messages', () => {+ const input = [+ userMsg('u1', 'q'),+ assistantMsg('a1', [{ type: 'text', text: 'a' }] as UIMessage['parts']),+ userMsg('u2', 'failed'),+ userMsg('u3', 'next'),+ ]+ const out = coalesceMessagesForAlternation(input)+ expect(out.map((m) => m.id)).toEqual(['u1', 'a1', 'u3'])})- it('merges two consecutive user messages with no intervening assistant', () => {- const input = [userMsg('u1', 'hello'), userMsg('u2', 'still hello')]+ it("carries a dropped turn's attachments forward, but not its question", () => {+ const image = {+ type: 'file',+ mediaType: 'image/png',+ url: 'data:image/png;base64,AAA',+ } as unknown as UIMessage['parts'][number]+ const audio = { type: 'text', text: encodeAudioSentinel('wav', 'UklG') }+ const docs =+ '[ATTACHED_FILES]\n- file_id: f1, name: a.pdf\n[/ATTACHED_FILES]'+ const input: UIMessage[] = [+ {+ id: 'u1',+ role: 'user',+ parts: [+ { type: 'text', text: `failed question\n\n${docs}` },+ image,+ audio,+ ],+ } as UIMessage,+ assistantMsg('a1', []),+ userMsg('u2', 'what is in it?'),+ ]const out = coalesceMessagesForAlternation(input)expect(out).toHaveLength(1)+ expect(out[0].id).toBe('u2')expect(out[0].parts).toEqual([- { type: 'text', text: 'hello\n\nstill hello' },+ { type: 'text', text: docs },+ image,+ audio,+ { type: 'text', text: 'what is in it?' },+ ])+ })++ it('carries a Cowork ping turn forward into the next user message', () => {+ const ping = {+ type: 'text',+ text: '<SYSTEM>\nsubagent a1 finished\n</SYSTEM>',+ }+ const input: UIMessage[] = [+ userMsg('u1', 'start'),+ assistantMsg('a1', [{ type: 'text', text: 'ok' }] as UIMessage['parts']),+ { id: 'ping-2', role: 'user', parts: [ping] } as UIMessage,+ userMsg('u2', 'what did it find?'),+ ]+ const out = coalesceMessagesForAlternation(input)+ expect(out.map((m) => m.id)).toEqual(['u1', 'a1', 'u2'])+ expect(out[2].parts).toEqual([+ ping,+ { type: 'text', text: 'what did it find?' },])})@@ -514,31 +568,6 @@ describe('coalesceMessagesForAlternation', () => {expect(out[0].role).toBe('user')})- it('preserves non-text user parts (e.g. file attachments) when merging', () => {- const filePart = {- type: 'file',- mediaType: 'image/png',- url: 'data:image/png;base64,AAA',- } as unknown as UIMessage['parts'][number]- const input: UIMessage[] = [- {- id: 'u1',- role: 'user',- parts: [{ type: 'text', text: 'first' }, filePart],- } as UIMessage,- userMsg('u2', 'second'),- ]- const out = coalesceMessagesForAlternation(input)- expect(out).toHaveLength(1)- // Order is preserved: file stays where it was sent, second message's- // text is appended after it rather than merged into the first text part.- expect(out[0].parts).toEqual([- { type: 'text', text: 'first' },- filePart,- { type: 'text', text: 'second' },- ])- })-it('returns the input unchanged when alternation is already valid', () => {const input = [userMsg('u1', 'q'),@@ -839,3 +868,28 @@ describe('hasGenuineUserQuery', () => {).toBe(true)})})++describe('isLocalChatServer', () => {+ it.each([+ ['llamacpp', undefined],+ ['mlx', undefined],+ ['custom', 'http://localhost:11434/v1'],+ ['custom', 'http://127.0.0.1:8080/v1'],+ ['custom', 'http://127.0.0.2:8080/v1'],+ ['custom', 'http://0.0.0.0:1234/v1'],+ ['custom', 'http://[::1]:1234/v1'],+ ])('treats %s at %s as local (no retries)', (provider, baseUrl) => {+ expect(isLocalChatServer(provider, baseUrl)).toBe(true)+ })++ it.each([+ ['openai', 'https://api.openai.com/v1'],+ ['custom', 'http://192.168.1.5:1234/v1'],+ ['custom', 'https://localhost.example.com/v1'],+ ['custom', 'http://127.example.com/v1'],+ ['custom', undefined],+ ['custom', 'not a url'],+ ])('treats %s at %s as hosted (SDK retries)', (provider, baseUrl) => {+ expect(isLocalChatServer(provider, baseUrl)).toBe(false)+ })+})diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.tsindex 9becf8a9d..8d72a84b9 100644--- a/web-app/src/lib/custom-chat-transport.ts+++ b/web-app/src/lib/custom-chat-transport.ts@@ -61,9 +61,18 @@ import {} from './context-manager'import { mcpOrchestrator } from '@/lib/mcp-orchestrator'import { isRouterModelSelectable } from '@/lib/mcp-router-model-filter'-import { encodeAudioSentinel, parseAudioDataUrl } from '@/lib/audio-sentinel'-import { encodeVideoSentinel, parseVideoDataUrl } from '@/lib/video-sentinel'+import {+ encodeAudioSentinel,+ hasAudioSentinel,+ parseAudioDataUrl,+} from '@/lib/audio-sentinel'+import {+ encodeVideoSentinel,+ hasVideoSentinel,+ parseVideoDataUrl,+} from '@/lib/video-sentinel'import { isPredefinedRemoteProvider } from '@/lib/providerCaps'+import { PING_OPEN } from '@/lib/coworkPing'import { paramsSettings } from '@/lib/predefinedParams'import { CHAT_SLOT_ID } from '@/constants/models'import { createStepMetadata } from '@/lib/stepMetadata'@@ -374,34 +383,40 @@ function isAssistantMessageEmpty(message: UIMessage): boolean {}/**- * Merge `b`'s parts onto `a`'s parts. When adjacent text parts meet at the- * boundary, they're concatenated with a blank-line separator so the merged- * message reads as one continuous turn rather than two.+ * Parts of an unanswered user turn to keep when a newer user turn replaces it:+ * its attachments, but not its question. The UI still shows those attachments+ * in the earlier bubble, so a follow-up like "what is in it?" must still reach+ * the model with them. By this point images are `file` parts, audio and video+ * are sentinel-only text parts, and documents are an [ATTACHED_FILES] block+ * (plus any inlined contents) appended after the question text. Cowork pings+ * are carried too.*/-function mergeMessageParts(- a: UIMessage['parts'],- b: UIMessage['parts']+function carryAttachmentsForward(+ dropped: UIMessage['parts'],+ kept: UIMessage['parts']): UIMessage['parts'] {- const aParts = Array.isArray(a) ? [...a] : []- const bParts = Array.isArray(b) ? b : []- for (const part of bParts) {- const last = aParts[aParts.length - 1]- if (- last &&- (last as { type?: string }).type === 'text' &&- (part as { type?: string }).type === 'text' &&- typeof (last as { text?: string }).text === 'string' &&- typeof (part as { text?: string }).text === 'string'- ) {- aParts[aParts.length - 1] = {- ...(last as object),- text: `${(last as { text: string }).text}\n\n${(part as { text: string }).text}`,- } as (typeof aParts)[number]- } else {- aParts.push(part)+ const attachments: UIMessage['parts'] = []+ for (const part of Array.isArray(dropped) ? dropped : []) {+ if (part.type === 'file') {+ attachments.push(part)+ } else if (part.type === 'text' && typeof part.text === 'string') {+ // Cowork's <SYSTEM> pings (finished subagents) ride as their own user+ // turn; they are context the model has not seen yet, not a question.+ if (+ hasAudioSentinel(part.text) ||+ hasVideoSentinel(part.text) ||+ part.text.trimStart().startsWith(PING_OPEN)+ ) {+ attachments.push(part)+ continue+ }+ const filesAt = part.text.indexOf('[ATTACHED_FILES]')+ if (filesAt !== -1) {+ attachments.push({ ...part, text: part.text.slice(filesAt) })+ }}}- return aParts as UIMessage['parts']+ return [...attachments, ...(Array.isArray(kept) ? kept : [])]}/**@@ -417,9 +432,10 @@ function mergeMessageParts(* server side. We fix that here by:** 1. Dropping assistant placeholders with no content (failed turns).- * 2. Merging any remaining adjacent user messages by concatenating their- * text parts and appending their non-text parts. This preserves all of- * the user's content — nothing is silently dropped.+ * 2. Keeping only the last of any adjacent user messages. The earlier ones+ * were never answered; merging their text would resend a failed question+ * inside the next one while the UI shows them as separate bubbles. Their+ * attachments are carried forward (see carryAttachmentsForward).** Adjacent assistant messages are intentionally left alone: the Anthropic* serial-tool-use wave-split in `sendMessages` deliberately produces them.@@ -654,8 +670,8 @@ export function coalesceMessagesForAlternation(const cur = filtered[i]if (prev.role === 'user' && cur.role === 'user') {out[out.length - 1] = {- ...prev,- parts: mergeMessageParts(prev.parts, cur.parts),+ ...cur,+ parts: carryAttachmentsForward(prev.parts, cur.parts),}} else {out.push(cur)@@ -664,6 +680,39 @@ export function coalesceMessagesForAlternation(return out}+const LOCAL_ENGINE_PROVIDERS: Record<string, true> = {+ llamacpp: true,+ mlx: true,+}++const LOOPBACK_HOSTS: Record<string, true> = {+ localhost: true,+ // What some local servers print as their listen address.+ '0.0.0.0': true,+ // URL.hostname keeps the brackets on IPv6 literals.+ '[::1]': true,+}++/**+ * Jan's own engines and any server on this machine (Ollama, LM Studio, a+ * local llama-server). Their 5xx is deterministic and a retry re-runs the+ * whole prompt, so such requests are not retried.+ */+export function isLocalChatServer(+ providerId: string,+ baseUrl: string | undefined+): boolean {+ if (LOCAL_ENGINE_PROVIDERS[providerId]) return true+ if (!baseUrl) return false+ try {+ const host = new URL(baseUrl).hostname+ // URL has already normalised IPv4, so 127.0.0.0/8 is a prefix match.+ return !!LOOPBACK_HOSTS[host] || /^127\.\d+\.\d+\.\d+$/.test(host)+ } catch {+ return false+ }+}+const TOOL_RESPONSE_ONLY = /^<tool_response>[\s\S]*<\/tool_response>$//**@@ -1539,6 +1588,9 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {model: this.model,messages: modelMessages,abortSignal: options.abortSignal,+ // Hosted providers keep the SDK's two backoff retries for transient+ // 429/5xx; local servers fail at once (see isLocalChatServer).+ maxRetries: isLocalChatServer(providerId, provider.base_url) ? 0 : 2,tools: shouldEnableTools ? this.tools : undefined,toolChoice: shouldEnableTools ? 'auto' : undefined,system: effectiveSystem,