DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
fix(chat): honor reduced motion during scroll following (#1116)
Hairyeb7b3cba0cfd
diff --git a/.gitattributes b/.gitattributesindex 8f9b805f..476cb0b4 100644--- a/.gitattributes+++ b/.gitattributes@@ -10,6 +10,7 @@*.toml text eol=lf*.js text eol=lf*.mjs text eol=lf+test/fixtures/scroll-follow-alpha5.txt text eol=lf*.sh text eol=lf*.ico binary*.icns binarydiff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 83fc2ff2..dfee5b75 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -5,6 +5,7 @@| 插件 | 引用宿主 | 版本 | hash | source | 声明文件 || --- | --- | --- | --- | --- | --- |+| `test/fixtures` | [deepseek-ai/deepseek-harness](https://github.com/deepseek-ai/deepseek-harness) | `@deepseek-ai/[email protected]` | — | — | [THIRD_PARTY_NOTICES.md](test/fixtures/THIRD_PARTY_NOTICES.md) || `packages/dsh-tauri` | [deepseek-ai/deepseek-harness](https://github.com/deepseek-ai/deepseek-harness) | `dsh-v0.2.1-rc.1` | `1600d8a1e140dcde43a1a0941940a0480712c011` | `source/deepseek-harness` | [THIRD_PARTY_NOTICES.md](packages/dsh-tauri/THIRD_PARTY_NOTICES.md) || `packages/dsh-tauri-model` | [deepseek-ai/deepseek-harness](https://github.com/deepseek-ai/deepseek-harness) | `dsh-v0.2.1-rc.1` | `1600d8a1e140dcde43a1a0941940a0480712c011` | `source/deepseek-harness` | [THIRD_PARTY_NOTICES.md](packages/dsh-tauri-model/THIRD_PARTY_NOTICES.md) || `packages/dsh-tauri-extension` | [deepseek-ai/deepseek-harness](https://github.com/deepseek-ai/deepseek-harness) | `dsh-v0.2.1-rc.1` | `1600d8a1e140dcde43a1a0941940a0480712c011` | `source/deepseek-harness` | [THIRD_PARTY_NOTICES.md](packages/dsh-tauri-extension/THIRD_PARTY_NOTICES.md) |diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.mdindex d10be00f..c1b865d8 100644--- a/docs/DEVELOPMENT.md+++ b/docs/DEVELOPMENT.md@@ -64,6 +64,14 @@ cargo test --manifest-path src-tauri/Cargo.toml --all-features --lockedUse `git diff --check` for documentation-only edits. Tests must use isolated data, never real user profiles.+## Reduced motion for chat following++At desktop startup, the [patch](<../src-tauri/src/service/patch/scroll_follow.rs>) for compatible managed chat bundles ([#1114](https://github.com/dsh-tauri/deepseek-harness-desktop/issues/1114)) makes chat and process-group following use the existing `jump` path when the DSH document root has `data-reduce-motion` or the system requests `prefers-reduced-motion: reduce`. This also cancels an active smooth scroll. Normal startup, early startup and `--patch-core` are covered; missing files or changed upstream anchors are logged and skipped without rewriting unknown versions.++The deployment owns the root attribute. This patch does not disable motion by default, inject CSS, or implement `?reduce-motion=0` / browser persistence. Official pages without the attribute retain smooth behavior unless the system requests reduced motion. Set the attribute inside the **DSH page / frame**; for a temporary check, run `document.documentElement.setAttribute('data-reduce-motion', '')` in that frame's console. Values `0` and `false` still count as present. Restore motion with `document.documentElement.removeAttribute('data-reduce-motion')` and a non-reduced system preference. Manual changes do not survive refresh and are read on the next follow call.++The [regression tests](<../test/scroll-follow-patch.test.ts>) compare the released class with the production replacement; Rust tests run the same JavaScript contract on the actual `apply_at` file output. These are logic checks, not M5 / multi-display GPU measurements or full browser pagination coverage. Performance claims still need a same-device before/after comparison.+## Runtime isolation| Mode | Harness data | Store | Default loopback port |diff --git a/docs/DEVELOPMENT.zh.md b/docs/DEVELOPMENT.zh.mdindex ac85d3ab..5b7095f2 100644--- a/docs/DEVELOPMENT.zh.md+++ b/docs/DEVELOPMENT.zh.md@@ -64,6 +64,14 @@ cargo test --manifest-path src-tauri/Cargo.toml --all-features --locked文档修改使用 `git diff --check`。测试数据必须隔离,不能使用真实用户档案。+## 聊天跟随的减弱动效++桌面端启动时对兼容的托管聊天包施加[补丁](<../src-tauri/src/service/patch/scroll_follow.rs>)([#1114](https://github.com/dsh-tauri/deepseek-harness-desktop/issues/1114)):聊天和进程组的跟随滚动在 DSH 文档根节点存在 `data-reduce-motion` 或系统开启 `prefers-reduced-motion: reduce` 时,通过原有 `jump` 即时落位并取消正在进行的平滑滚动。常规启动、早启动与 `--patch-core` 均覆盖;缺文件或上游锚点变化时记录日志并跳过,不修改未知版本。++该属性由部署方设置;本补丁不默认禁用动画,不注入 CSS,也不实现 `?reduce-motion=0` 或浏览器记忆。官方页面没有该属性且系统未要求减弱时,原有平滑行为保持不变。部署方应在 **DSH 页面 / 帧** 内设置;临时验证可在对应控制台执行 `document.documentElement.setAttribute('data-reduce-motion', '')`。属性值为 `0` 或 `false` 仍表示存在;恢复用 `document.documentElement.removeAttribute('data-reduce-motion')`,且系统偏好也必须关闭。手动设置不跨刷新保存,下一次跟随调用才读取新状态。++[回归测试](<../test/scroll-follow-patch.test.ts>)对比原版与生产替换体;Rust 测试执行真实 `apply_at` 文件产物上的同一套 JavaScript 契约。它们验证逻辑,不代表 M5 / 多屏 GPU 实测,也不覆盖完整浏览器分页界面;性能结论仍需同设备前后对照。+## 运行时隔离| 模式 | Harness 数据 | Store | 默认回环端口 |diff --git a/src-tauri/src/service/patch/mod.rs b/src-tauri/src/service/patch/mod.rsindex b8d49a7f..b6041a3c 100644--- a/src-tauri/src/service/patch/mod.rs+++ b/src-tauri/src/service/patch/mod.rs@@ -19,6 +19,7 @@ pub(crate) mod model_selection;pub(crate) mod pi_ai_thinking;pub(crate) mod plugin_visibility;pub(crate) mod renderer;+pub(crate) mod scroll_follow;pub(crate) mod session;pub(crate) mod workspace;pub(crate) mod workspace_view;@@ -35,11 +36,12 @@ use std::path::Path;/// 让编排层能看见哪一条出了问题。pub(crate) fn apply_all_at(core_dir: &Path) -> Result<(), String> {#[allow(clippy::type_complexity)]- let patches: [(&str, fn(&Path) -> Result<(), String>); 13] = [+ let patches: [(&str, fn(&Path) -> Result<(), String>); 14] = [("renderer", renderer::apply_at),("mcp_startup", mcp_startup::apply_at),("composer", composer::apply_at),("conversation_draft", conversation_draft::apply_at),+ ("scroll_follow", scroll_follow::apply_at),("mobile_composer", mobile_composer::apply_at),("mobile_sidebar", mobile_sidebar::apply_at),("session", session::apply_at),diff --git a/src-tauri/src/service/patch/scroll_follow.rs b/src-tauri/src/service/patch/scroll_follow.rsnew file mode 100644index 00000000..ad295726--- /dev/null+++ b/src-tauri/src/service/patch/scroll_follow.rs@@ -0,0 +1,175 @@+use std::path::Path;++use crate::utils::{patch_core_file, patch_dsh, PatchOutcome};++const CLIENT: &str = "node_modules/@deepseek-ai/dsh-client-ui-chat/lib/client.js";+const CLASS: &str = "var ScrollFollow = class ScrollFollow {";+const METHOD: &str = "toBottom(element, metrics, behavior) {";+const ORIGINAL: &str = r#"toBottom(element, metrics, behavior) {+ this.following = true;+ if (metrics.top === metrics.floor) return this.jump(element, metrics, metrics.floor);+ if (behavior === "instant" && this.animating) {+ if (this.target !== metrics.floor) {+ this.target = metrics.floor;+ element.scrollTo({+ top: metrics.floor,+ behavior: "smooth"+ });+ }+ return metrics;+ }+ if (behavior === "instant" || !this.animating && this.nearBottom(metrics)) return this.jump(element, metrics, metrics.floor);+ if (typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches) return this.jump(element, metrics, metrics.floor);+ if (this.target === null) {+ this.target = metrics.floor;+ element.scrollTo({+ top: metrics.floor,+ behavior: "smooth"+ });+ }+ return metrics;+ }"#;+const PATCHED: &str = r#"toBottom(element, metrics, behavior) {+ this.following = true;+ if (typeof document !== "undefined" && document.documentElement.hasAttribute("data-reduce-motion") || typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches) return this.jump(element, metrics, metrics.floor);+ if (metrics.top === metrics.floor) return this.jump(element, metrics, metrics.floor);+ if (behavior === "instant" && this.animating) {+ if (this.target !== metrics.floor) {+ this.target = metrics.floor;+ element.scrollTo({+ top: metrics.floor,+ behavior: "smooth"+ });+ }+ return metrics;+ }+ if (behavior === "instant" || !this.animating && this.nearBottom(metrics)) return this.jump(element, metrics, metrics.floor);+ if (this.target === null) {+ this.target = metrics.floor;+ element.scrollTo({+ top: metrics.floor,+ behavior: "smooth"+ });+ }+ return metrics;+ }"#;++fn patch_source(source: &str) -> PatchOutcome {+ if source.matches(CLASS).count() != 1 || source.matches(METHOD).count() != 1 {+ return PatchOutcome::AnchorMissing;+ }+ match (+ source.matches(ORIGINAL).count(),+ source.matches(PATCHED).count(),+ ) {+ (0, 1) => PatchOutcome::AlreadyPatched,+ (1, 0) => PatchOutcome::Patched(source.replacen(ORIGINAL, PATCHED, 1)),+ _ => PatchOutcome::AnchorMissing,+ }+}++pub fn apply_at(core_dir: &Path) -> Result<(), String> {+ patch_core_file(core_dir, CLIENT, patch_source)+}++pub fn apply(app_handle: &tauri::AppHandle) -> Result<(), String> {+ patch_dsh(app_handle, CLIENT, patch_source)+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::process::{Command, Stdio};+ use std::time::{Duration, Instant};++ const FIXTURE: &str = include_str!("../../../../test/fixtures/scroll-follow-alpha5.txt");++ #[test]+ fn patches_the_released_class_once() {+ let source = format!("before\n{FIXTURE}\nafter");+ let PatchOutcome::Patched(patched) = patch_source(&source) else {+ panic!("expected Patched");+ };+ assert_eq!(patched.matches(PATCHED).count(), 1);+ assert_eq!(patched.replacen(PATCHED, ORIGINAL, 1), source);+ assert_eq!(patch_source(&patched), PatchOutcome::AlreadyPatched);+ }++ #[test]+ fn rejects_missing_changed_or_ambiguous_anchors() {+ let guard = r#"if (typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches) return this.jump(element, metrics, metrics.floor);"#;+ let patched = FIXTURE.replacen(ORIGINAL, PATCHED, 1);+ for source in [+ String::new(),+ FIXTURE.replace("metrics", "geometry"),+ FIXTURE.replace(CLASS, "class Follow {"),+ FIXTURE.replace(guard, ""),+ format!("{}\n{guard}", FIXTURE.replace(guard, "")),+ FIXTURE.replace(guard, "").replace(+ "interrupt(element, metrics) {",+ &format!("interrupt(element, metrics) {{\n{guard}"),+ ),+ format!("{FIXTURE}\n{FIXTURE}"),+ format!("{patched}\n{patched}"),+ format!("{patched}\n{FIXTURE}"),+ format!("{FIXTURE}\n{patched}"),+ patched.replace("hasAttribute", "getAttribute"),+ FIXTURE.replace('\n', "\r\n"),+ ] {+ assert_eq!(patch_source(&source), PatchOutcome::AnchorMissing);+ }+ }++ #[test]+ fn applies_to_an_isolated_core_and_executes_the_result() {+ let core = tempfile::tempdir_in(env!("CARGO_MANIFEST_DIR")).unwrap();+ let target = core.path().join(CLIENT);+ std::fs::create_dir_all(target.parent().unwrap()).unwrap();+ std::fs::write(&target, FIXTURE).unwrap();+ apply_at(core.path()).unwrap();+ let first = std::fs::read_to_string(&target).unwrap();+ assert_eq!(patch_source(&first), PatchOutcome::AlreadyPatched);+ apply_at(core.path()).unwrap();+ assert_eq!(std::fs::read_to_string(&target).unwrap(), first);++ let script = Path::new(env!("CARGO_MANIFEST_DIR"))+ .join("../test/fixtures/scroll-follow-contract.mjs");+ let mut child = Command::new("node")+ .arg(script)+ .arg(&target)+ .stdin(Stdio::null())+ .spawn()+ .expect("node is required for the patched JavaScript contract");+ let deadline = Instant::now() + Duration::from_secs(20);+ loop {+ if let Some(status) = child.try_wait().unwrap() {+ assert!(+ status.success(),+ "patched JavaScript contract failed: {status}"+ );+ break;+ }+ if Instant::now() >= deadline {+ child.kill().unwrap();+ child.wait().unwrap();+ panic!("patched JavaScript contract timed out");+ }+ std::thread::sleep(Duration::from_millis(20));+ }+ }++ #[test]+ fn leaves_missing_or_unsupported_core_files_unchanged() {+ let core = tempfile::tempdir_in(env!("CARGO_MANIFEST_DIR")).unwrap();+ apply_at(core.path()).unwrap();+ let target = core.path().join(CLIENT);+ assert!(!target.exists());+ std::fs::create_dir_all(target.parent().unwrap()).unwrap();+ std::fs::write(&target, "upstream changed").unwrap();+ apply_at(core.path()).unwrap();+ assert_eq!(+ std::fs::read_to_string(&target).unwrap(),+ "upstream changed"+ );+ }+}diff --git a/src-tauri/src/service/workflow/early_plan.rs b/src-tauri/src/service/workflow/early_plan.rsindex 76856eb3..7419f644 100644--- a/src-tauri/src/service/workflow/early_plan.rs+++ b/src-tauri/src/service/workflow/early_plan.rs@@ -250,6 +250,10 @@ pub(super) fn prepare("conversation draft compatibility patch",patch::conversation_draft::apply_at,),+ (+ "scroll follow reduced-motion patch",+ patch::scroll_follow::apply_at,+ ),("mobile composer patch", patch::mobile_composer::apply_at),("mobile sidebar patch", patch::mobile_sidebar::apply_at),("SessionStore.remove patch", patch::session::apply_at),diff --git a/src-tauri/src/service/workflow/launch.rs b/src-tauri/src/service/workflow/launch.rsindex 0173b22a..9ad0c445 100644--- a/src-tauri/src/service/workflow/launch.rs+++ b/src-tauri/src/service/workflow/launch.rs@@ -709,6 +709,9 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {if let Err(e) = crate::service::patch::conversation_draft::apply(&app_handle) {log::warn!("conversation draft compatibility patch failed: {e}");}+ if let Err(e) = crate::service::patch::scroll_follow::apply(&app_handle) {+ log::warn!("Scroll follow reduced-motion patch skipped: {e}");+ }if let Err(e) = crate::service::patch::mobile_composer::apply(&app_handle) {log::warn!("mobile composer patch failed: {e}");}diff --git a/test/fixtures/THIRD_PARTY_NOTICES.md b/test/fixtures/THIRD_PARTY_NOTICES.mdnew file mode 100644index 00000000..4ceded33--- /dev/null+++ b/test/fixtures/THIRD_PARTY_NOTICES.md@@ -0,0 +1,25 @@+# Scroll-follow fixture++[`scroll-follow-alpha5.txt`](<./scroll-follow-alpha5.txt>) is the `ScrollFollow` class extracted from `@deepseek-ai/[email protected]`, `lib/client.js`, with comments and blank lines removed. Source: [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness/blob/dsh-v0.2.1-alpha.5/packages/client/ui-chat/src/client/chat/use-scroll-follow.ts). This fixture does not change the read-only reference submodule.++## MIT License++Copyright (c) 2026 DeepSeek++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/test/fixtures/scroll-follow-alpha5.txt b/test/fixtures/scroll-follow-alpha5.txtnew file mode 100644index 00000000..31f018c9--- /dev/null+++ b/test/fixtures/scroll-follow-alpha5.txt@@ -0,0 +1,97 @@+var ScrollFollow = class ScrollFollow {+ following;+ threshold;+ static owners = new WeakMap();+ target = null;+ sampledTop;+ constructor(following, threshold) {+ this.following = following;+ this.threshold = threshold;+ }+ static forElement(element) {+ return this.owners.get(element);+ }+ bind(element) {+ ScrollFollow.owners.set(element, this);+ return () => {+ if (ScrollFollow.owners.get(element) === this) ScrollFollow.owners.delete(element);+ };+ }+ get active() {+ return this.following;+ }+ get animating() {+ return this.target !== null;+ }+ nearBottom(metrics) {+ return Math.abs(metrics.floor - metrics.top) <= this.threshold;+ }+ setFollowing(active) {+ this.following = active;+ if (!active) this.target = null;+ }+ reset() {+ this.setFollowing(false);+ this.sampledTop = void 0;+ }+ sample(metrics, movedByReader = this.sampledTop === void 0 || Math.abs(metrics.top - this.sampledTop) > .5) {+ this.sampledTop = metrics.top;+ if (!this.animating && movedByReader) this.following = this.nearBottom(metrics);+ return this.active;+ }+ settle(metrics) {+ const target = this.target;+ this.target = null;+ return this.sample(metrics, target === null ? void 0 : Math.abs(metrics.top - Math.min(target, metrics.floor)) > this.threshold);+ }+ jump(element, metrics, top) {+ const animated = this.animating;+ this.target = null;+ const target = Math.max(0, Math.min(metrics.floor, top));+ if (animated) element.scrollTo({+ top: target,+ behavior: "instant"+ });+ else if (target !== metrics.top) element.scrollTop = target;+ const landed = {+ ...metrics,+ top: element.scrollTop+ };+ this.sampledTop = landed.top;+ this.following = this.nearBottom(landed);+ return landed;+ }+ toBottom(element, metrics, behavior) {+ this.following = true;+ if (metrics.top === metrics.floor) return this.jump(element, metrics, metrics.floor);+ if (behavior === "instant" && this.animating) {+ if (this.target !== metrics.floor) {+ this.target = metrics.floor;+ element.scrollTo({+ top: metrics.floor,+ behavior: "smooth"+ });+ }+ return metrics;+ }+ if (behavior === "instant" || !this.animating && this.nearBottom(metrics)) return this.jump(element, metrics, metrics.floor);+ if (typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches) return this.jump(element, metrics, metrics.floor);+ if (this.target === null) {+ this.target = metrics.floor;+ element.scrollTo({+ top: metrics.floor,+ behavior: "smooth"+ });+ }+ return metrics;+ }+ interrupt(element, metrics) {+ if (!this.animating) return;+ this.target = null;+ this.sampledTop = metrics.top;+ element.scrollTo({+ top: metrics.top,+ behavior: "instant"+ });+ }+ };diff --git a/test/fixtures/scroll-follow-contract.mjs b/test/fixtures/scroll-follow-contract.mjsnew file mode 100644index 00000000..0326a5a6--- /dev/null+++ b/test/fixtures/scroll-follow-contract.mjs@@ -0,0 +1,214 @@+import assert from 'node:assert/strict'+import { readFileSync } from 'node:fs'+import process from 'node:process'+import { test } from 'node:test'+import { runInNewContext } from 'node:vm'++const source = readFileSync(process.argv[2], 'utf8')+const metrics = { top: 0, floor: 400, height: 200 }++function world({ system = false, api = 'function', dom = true } = {}) {+ const root = new Map()+ const body = new Map()+ const preference = { matches: system }+ const queries = []+ const calls = []+ const element = {+ scrollTop: 0,+ scrollTo(options) {+ calls.push({ ...options })+ if (options.behavior === 'instant')+ this.scrollTop = options.top+ },+ }+ const context = {}+ if (dom) {+ context.document = {+ documentElement: {+ hasAttribute: name => root.has(name),+ getAttribute: name => root.get(name) ?? null,+ },+ body: { hasAttribute: name => body.has(name) },+ }+ }+ if (api === 'function') {+ context.matchMedia = (query) => {+ assert.equal(query, '(prefers-reduced-motion: reduce)')+ queries.push(query)+ return preference+ }+ }+ else if (api === 'nonfunction') {+ context.matchMedia = false+ }+ const follow = runInNewContext(`${source}\nnew ScrollFollow(false, 1)`, context, { timeout: 1000 })+ return { follow, element, calls, root, body, preference, queries }+}++function landed(state, input) {+ assert.equal(state.element.scrollTop, input.floor)+ assert.equal(state.follow.animating, false)+ assert.equal(state.follow.active, true)+ assert.equal(state.follow.sample({ ...input, top: input.floor, floor: input.floor + 100 }), true)+ assert.equal(state.follow.settle({ ...input, top: input.floor, floor: input.floor + 100 }), true)+ assert.equal(state.follow.sample({ ...input, top: input.floor - 50, floor: input.floor + 100 }), false)+}++for (const api of ['function', 'missing', 'nonfunction']) {+ for (const value of ['', 'true', '0', 'false']) {+ test(`root attribute presence (${JSON.stringify(value)}, ${api}) jumps without motion`, () => {+ const state = world({ api })+ state.root.set('data-reduce-motion', value)+ const result = state.follow.toBottom(state.element, metrics, 'smooth')+ assert.deepEqual({ ...result }, { ...metrics, top: metrics.floor })+ assert.deepEqual(state.calls, [])+ landed(state, metrics)+ })+ }+ test(`no preference preserves smooth following (${api})`, () => {+ const state = world({ api })+ assert.deepEqual({ ...state.follow.toBottom(state.element, metrics, 'smooth') }, metrics)+ assert.deepEqual(state.calls, [{ top: 400, behavior: 'smooth' }])+ assert.equal(state.element.scrollTop, 0)+ assert.equal(state.follow.animating, true)+ assert.equal(state.follow.active, true)+ assert.equal(state.queries.length, api === 'function' ? 1 : 0)+ })+}++for (const behavior of ['instant', 'smooth']) {+ for (const floor of [400, 600]) {+ for (const policy of ['none', 'root', 'system']) {+ test(`active ${behavior}, floor ${floor}, policy ${policy}`, () => {+ const state = world()+ state.follow.toBottom(state.element, metrics, 'smooth')+ state.calls.length = 0+ state.element.scrollTop = 100+ if (policy === 'root')+ state.root.set('data-reduce-motion', '')+ if (policy === 'system')+ state.preference.matches = true+ const grown = { ...metrics, top: 100, floor }+ const result = state.follow.toBottom(state.element, grown, behavior)+ if (policy !== 'none') {+ assert.deepEqual({ ...result }, { ...grown, top: floor })+ assert.deepEqual(state.calls, [{ top: floor, behavior: 'instant' }])+ landed(state, grown)+ }+ else {+ assert.deepEqual({ ...result }, grown)+ assert.deepEqual(state.calls, behavior === 'instant' && floor !== 400 ? [{ top: floor, behavior: 'smooth' }] : [])+ assert.equal(state.element.scrollTop, 100)+ assert.equal(state.follow.animating, true)+ }+ })+ }+ }+}++for (const system of [false, true]) {+ test(`system preference ${system} respects root absence`, () => {+ const state = world({ system })+ const result = state.follow.toBottom(state.element, metrics, 'smooth')+ assert.equal(result.top, system ? 400 : 0)+ assert.equal(state.follow.animating, !system)+ assert.deepEqual(state.calls, system ? [] : [{ top: 400, behavior: 'smooth' }])+ assert.equal(state.queries.length, 1)+ })+}++test('root and system preferences can be toggled on the same instance', () => {+ const state = world()+ state.follow.toBottom(state.element, metrics, 'smooth')+ state.calls.length = 0+ state.root.set('data-reduce-motion', '')+ state.preference.matches = true+ state.follow.toBottom(state.element, { ...metrics, floor: 600 }, 'instant')+ assert.deepEqual(state.calls, [{ top: 600, behavior: 'instant' }])+ state.calls.length = 0+ state.root.delete('data-reduce-motion')+ assert.equal(state.follow.toBottom(state.element, { ...metrics, top: 600, floor: 800 }, 'smooth').top, 800)+ assert.deepEqual(state.calls, [])+ state.preference.matches = false+ state.follow.toBottom(state.element, { ...metrics, top: 800, floor: 1000 }, 'smooth')+ assert.deepEqual(state.calls, [{ top: 1000, behavior: 'smooth' }])+ assert.equal(state.follow.animating, true)+ state.preference.matches = true+ state.calls.length = 0+ assert.equal(state.follow.toBottom(state.element, { ...metrics, top: 800, floor: 1200 }, 'instant').top, 1200)+ assert.deepEqual(state.calls, [{ top: 1200, behavior: 'instant' }])+ assert.equal(state.follow.animating, false)+})++test('removing the root attribute restores motion without matchMedia', () => {+ const state = world({ api: 'missing' })+ state.root.set('data-reduce-motion', '0')+ assert.equal(state.follow.toBottom(state.element, metrics, 'smooth').top, 400)+ state.root.delete('data-reduce-motion')+ state.follow.toBottom(state.element, { ...metrics, top: 400, floor: 800 }, 'smooth')+ assert.deepEqual(state.calls, [{ top: 800, behavior: 'smooth' }])+})++test('a body-only attribute does not opt out of motion', () => {+ const state = world()+ state.body.set('data-reduce-motion', '')+ state.follow.toBottom(state.element, metrics, 'smooth')+ assert.deepEqual(state.calls, [{ top: 400, behavior: 'smooth' }])+ assert.equal(state.root.has('data-reduce-motion'), false)+})++test('the class remains usable without a document', () => {+ const state = world({ dom: false })+ state.follow.toBottom(state.element, metrics, 'smooth')+ assert.deepEqual(state.calls, [{ top: 400, behavior: 'smooth' }])+})++for (const input of [{ ...metrics, top: 399.5 }, { ...metrics, top: 400.5 }]) {+ test(`no preference preserves the near-bottom jump at ${input.top}`, () => {+ const state = world()+ state.element.scrollTop = input.top+ assert.equal(state.follow.toBottom(state.element, input, 'smooth').top, 400)+ assert.deepEqual(state.calls, [])+ assert.equal(state.follow.animating, false)+ })+}++test('idle instant requests still jump without a preference', () => {+ const state = world()+ assert.equal(state.follow.toBottom(state.element, metrics, 'instant').top, 400)+ assert.deepEqual(state.calls, [])+ assert.equal(state.follow.animating, false)+})++test('an active animation already at the floor is cancelled without a preference', () => {+ const state = world()+ state.follow.toBottom(state.element, metrics, 'smooth')+ state.calls.length = 0+ state.element.scrollTop = 400+ assert.equal(state.follow.toBottom(state.element, { ...metrics, top: 400 }, 'instant').top, 400)+ assert.deepEqual(state.calls, [{ top: 400, behavior: 'instant' }])+ assert.equal(state.follow.animating, false)+})++test('independent containers keep reader, jump and paging state isolated', () => {+ const outer = world()+ const inner = world()+ for (const state of [outer, inner]) {+ state.root.set('data-reduce-motion', '')+ state.follow.bind(state.element)+ state.follow.toBottom(state.element, metrics, 'smooth')+ }+ outer.element.scrollTop = 100+ assert.equal(outer.follow.sample({ ...metrics, top: 100 }), false)+ assert.equal(inner.follow.active, true)+ inner.follow.toBottom(inner.element, { ...metrics, top: 400, floor: 600 }, 'smooth')+ assert.equal(inner.element.scrollTop, 600)+ assert.equal(outer.element.scrollTop, 100)+ const page = outer.follow.jump(outer.element, { ...metrics, top: 100, floor: 900 }, 300)+ assert.equal(page.top, 300)+ assert.equal(outer.follow.active, false)+ assert.equal(inner.follow.active, true)+ assert.equal(outer.follow.toBottom(outer.element, page, 'instant').top, 900)+ assert.equal(outer.follow.active, true)+ assert.equal(inner.element.scrollTop, 600)+})diff --git a/test/scroll-follow-patch.test.ts b/test/scroll-follow-patch.test.tsnew file mode 100644index 00000000..dcad045a--- /dev/null+++ b/test/scroll-follow-patch.test.ts@@ -0,0 +1,50 @@+import { spawnSync } from 'node:child_process'+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { resolve } from 'node:path'+import { afterEach, describe, expect, it } from 'vitest'++const rust = readFileSync(resolve('src-tauri/src/service/patch/scroll_follow.rs'), 'utf8')+const fixturePath = resolve('test/fixtures/scroll-follow-alpha5.txt')+const fixture = readFileSync(fixturePath, 'utf8')+const original = rust.match(/const ORIGINAL: &str = r#"([\s\S]*?)"#;/)?.[1]+const patched = rust.match(/const PATCHED: &str = r#"([\s\S]*?)"#;/)?.[1]+if (!original || !patched || fixture.split(original).length !== 2)+ throw new Error('Missing unique production scroll-follow patch anchor')++let directory: string | undefined++afterEach(() => {+ if (directory)+ rmSync(directory, { recursive: true, force: true })+ directory = undefined+})++function runContract(path: string) {+ return spawnSync(process.execPath, [resolve('test/fixtures/scroll-follow-contract.mjs'), path], {+ encoding: 'utf8',+ timeout: 20000,+ })+}++describe('scroll-follow reduced-motion startup patch', () => {+ it('satisfies the shared JavaScript contract with the production replacement', () => {+ directory = mkdtempSync(resolve('test/.scroll-follow-'))+ const target = resolve(directory, 'client.js')+ writeFileSync(target, fixture.replace(original, patched))+ const result = runContract(target)+ expect(result.error).toBeUndefined()+ expect(result.status, result.stdout + result.stderr).toBe(0)+ expect(result.stdout).toMatch(/# tests 38\b/)+ expect(result.stdout).toMatch(/# fail 0\b/)+ })++ it('rejects the released class without the document and early system guard', () => {+ const result = runContract(fixturePath)+ expect(result.error).toBeUndefined()+ expect(result.status, result.stdout + result.stderr).toBe(1)+ expect(result.stdout).toContain('not ok 1 - root attribute presence')+ expect(result.stdout).toContain('policy system')+ expect(result.stdout).toMatch(/# tests 38\b/)+ expect(result.stdout).toMatch(/# fail [1-9]\d*\b/)+ })+})