Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

fix(chat): aggregate the follow mirror per scrollport instead of iterating a WeakMap (#1199)

Hairyb595dc4f3c7d
diff --git a/.gitattributes b/.gitattributes
index 476cb0b4..73763bec 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -10,6 +10,7 @@
*.toml text eol=lf
*.js text eol=lf
*.mjs text eol=lf
+test/fixtures/chat-follow-anchor.txt text eol=lf
test/fixtures/scroll-follow-alpha5.txt text eol=lf
*.sh text eol=lf
*.ico binary
diff --git a/src-tauri/src/service/patch/chat_follow_anchor.rs b/src-tauri/src/service/patch/chat_follow_anchor.rs
index b8b03430..d23553d8 100644
--- a/src-tauri/src/service/patch/chat_follow_anchor.rs
+++ b/src-tauri/src/service/patch/chat_follow_anchor.rs
@@ -4,6 +4,9 @@
//! 重做选择器匹配(采样中占比近四成,表现为滚动和指针移动都慢半拍)。跟随意图本来
//! 就由 JS 持有,这里把它镜像到外层滚动容器,让 CSS 改用普通属性选择器;Chrome 不受
//! 影响是因为 Blink 的 `:has()` 失效范围更窄。
+//!
+//! 镜像值要按滚动容器聚合,而 `owners` 是 WeakMap 不可遍历,故另用 `followers` 记录
+//! 每个滚动容器上的跟随者集合;已发布的旧版补丁直接遍历 WeakMap,必须被就地修复。
use std::path::Path;
@@ -11,9 +14,14 @@ use crate::utils::{patch_core_file, patch_dsh, PatchOutcome};
const CLIENT: &str = "node_modules/@deepseek-ai/dsh-client-ui-chat/lib/client.js";
-const ORIGINAL_CSS: &str = r#"[data-conversation-scroll]:has(.EvIC1a_root[data-chat-following-tail])"#;
+const ORIGINAL_CSS: &str =
+ r#"[data-conversation-scroll]:has(.EvIC1a_root[data-chat-following-tail])"#;
const PATCHED_CSS: &str = r#"[data-conversation-scroll][data-chat-following-tail]"#;
+const ORIGINAL_STATIC: &str = r#" static owners = /* @__PURE__ */ new WeakMap();"#;
+const PATCHED_STATIC: &str = r#" static owners = /* @__PURE__ */ new WeakMap();
+ static followers = /* @__PURE__ */ new WeakMap();"#;
+
const ORIGINAL_BIND: &str = r#" bind(element) {
ScrollFollow.owners.set(element, this);
return () => {
@@ -21,6 +29,29 @@ const ORIGINAL_BIND: &str = r#" bind(element) {
};
}"#;
const PATCHED_BIND: &str = r#" bind(element) {
+ this.element = element;
+ this.scrollport = element.closest("[data-conversation-scroll]");
+ ScrollFollow.owners.set(element, this);
+ const scrollport = this.scrollport;
+ if (scrollport !== void 0 && scrollport !== null) {
+ let followers = ScrollFollow.followers.get(scrollport);
+ if (followers === void 0) ScrollFollow.followers.set(scrollport, followers = /* @__PURE__ */ new Set());
+ followers.add(this);
+ }
+ this.followAnchor();
+ return () => {
+ const followers = scrollport === void 0 || scrollport === null ? void 0 : ScrollFollow.followers.get(scrollport);
+ if (followers !== void 0) followers.delete(this);
+ const owned = ScrollFollow.owners.get(element) === this;
+ if (owned) ScrollFollow.owners.delete(element);
+ this.followAnchor();
+ if (owned) {
+ this.element = void 0;
+ this.scrollport = void 0;
+ }
+ };
+ }"#;
+const LEGACY_BIND: &str = r#" bind(element) {
this.element = element;
this.scrollport = element.closest("[data-conversation-scroll]");
ScrollFollow.owners.set(element, this);
@@ -44,6 +75,23 @@ const PATCHED_FOLLOW: &str = r#" setFollowing(active) {
if (!active) this.target = null;
this.followAnchor();
}
+ followAnchor() {
+ const scrollport = this.scrollport;
+ if (scrollport === void 0 || scrollport === null) return;
+ let following = false;
+ const followers = ScrollFollow.followers.get(scrollport);
+ if (followers !== void 0) followers.forEach((follower) => {
+ if (follower.following) following = true;
+ });
+ if (scrollport.hasAttribute("data-chat-following-tail") === following) return;
+ if (following) scrollport.setAttribute("data-chat-following-tail", "");
+ else scrollport.removeAttribute("data-chat-following-tail");
+ }"#;
+const LEGACY_FOLLOW: &str = r#" setFollowing(active) {
+ this.following = active;
+ if (!active) this.target = null;
+ this.followAnchor();
+ }
followAnchor() {
const scrollport = this.scrollport;
if (scrollport === void 0 || scrollport === null) return;
@@ -57,28 +105,39 @@ const PATCHED_FOLLOW: &str = r#" setFollowing(active) {
}"#;
fn patch_source(source: &str) -> PatchOutcome {
- let states = [
- (ORIGINAL_CSS, PATCHED_CSS),
- (ORIGINAL_BIND, PATCHED_BIND),
- (ORIGINAL_FOLLOW, PATCHED_FOLLOW),
+ let anchors: [(&[&str], &str); 4] = [
+ (&[ORIGINAL_CSS], PATCHED_CSS),
+ (&[ORIGINAL_STATIC], PATCHED_STATIC),
+ (&[ORIGINAL_BIND, LEGACY_BIND], PATCHED_BIND),
+ (&[ORIGINAL_FOLLOW, LEGACY_FOLLOW], PATCHED_FOLLOW),
];
- if states.iter().all(|(original, patched)| {
- source.matches(original).count() == 0 && source.matches(patched).count() == 1
- }) {
- return PatchOutcome::AlreadyPatched;
+ let mut patched = source.to_string();
+ let mut changed = false;
+ for (candidates, replacement) in anchors {
+ match patched.matches(replacement).count() {
+ 1 => continue,
+ 0 => {}
+ _ => return PatchOutcome::AnchorMissing,
+ }
+ let mut candidate = None;
+ for start in candidates {
+ match patched.matches(*start).count() {
+ 0 => {}
+ 1 if candidate.is_none() => candidate = Some(*start),
+ _ => return PatchOutcome::AnchorMissing,
+ }
+ }
+ let Some(candidate) = candidate else {
+ return PatchOutcome::AnchorMissing;
+ };
+ patched = patched.replacen(candidate, replacement, 1);
+ changed = true;
}
- if states
- .iter()
- .any(|(original, patched)| source.matches(original).count() != 1 || source.matches(patched).count() != 0)
- {
- return PatchOutcome::AnchorMissing;
+ if changed {
+ PatchOutcome::Patched(patched)
+ } else {
+ PatchOutcome::AlreadyPatched
}
- let patched = states
- .iter()
- .fold(source.to_string(), |source, (original, patched)| {
- source.replacen(original, patched, 1)
- });
- PatchOutcome::Patched(patched)
}
pub fn apply_at(core_dir: &Path) -> Result<(), String> {
@@ -92,31 +151,58 @@ pub fn apply(app_handle: &tauri::AppHandle) -> Result<(), String> {
#[cfg(test)]
mod tests {
use super::*;
+ use std::process::{Command, Stdio};
+ use std::time::{Duration, Instant};
+
+ const FIXTURE: &str = include_str!("../../../../test/fixtures/chat-follow-anchor.txt");
fn released() -> String {
format!(
- "<script>{}{}{}</script>",
- ORIGINAL_CSS, ORIGINAL_BIND, ORIGINAL_FOLLOW
+ "<script>{}{}{}{}</script>",
+ ORIGINAL_CSS, ORIGINAL_STATIC, ORIGINAL_BIND, ORIGINAL_FOLLOW
+ )
+ }
+
+ fn shipped() -> String {
+ format!(
+ "<script>{}{}{}{}</script>",
+ PATCHED_CSS, ORIGINAL_STATIC, LEGACY_BIND, LEGACY_FOLLOW
)
}
#[test]
- fn patches_follow_anchor_without_has() {
+ fn patches_released_source_once() {
let PatchOutcome::Patched(patched) = patch_source(&released()) else {
panic!("released source should patch");
};
assert!(patched.contains(PATCHED_CSS));
+ assert!(patched.contains(PATCHED_STATIC));
+ assert!(patched.contains(PATCHED_BIND));
+ assert!(patched.contains(PATCHED_FOLLOW));
assert!(!patched.contains(":has(.EvIC1a_root"));
- assert!(patched.contains("this.followAnchor();"));
assert!(!patched.contains(ORIGINAL_BIND));
+ assert!(!patched.contains(ORIGINAL_FOLLOW));
+ assert!(matches!(
+ patch_source(&patched),
+ PatchOutcome::AlreadyPatched
+ ));
}
#[test]
- fn patched_source_is_idempotent() {
- let PatchOutcome::Patched(patched) = patch_source(&released()) else {
- panic!("released source should patch");
+ fn repairs_the_shipped_patch_that_crashes_on_weakmap() {
+ let shipped = shipped();
+ assert!(shipped.contains("ScrollFollow.owners.forEach"));
+ let PatchOutcome::Patched(repaired) = patch_source(&shipped) else {
+ panic!("shipped patch should be repaired");
};
- assert!(matches!(patch_source(&patched), PatchOutcome::AlreadyPatched));
+ assert!(!repaired.contains("ScrollFollow.owners.forEach"));
+ assert!(!repaired.contains(LEGACY_BIND));
+ assert!(!repaired.contains(LEGACY_FOLLOW));
+ assert!(repaired.contains(PATCHED_STATIC));
+ assert!(matches!(
+ patch_source(&repaired),
+ PatchOutcome::AlreadyPatched
+ ));
}
#[test]
@@ -130,4 +216,65 @@ mod tests {
let source = released().replace("this.target = null;", "this.target = void 0;");
assert!(matches!(patch_source(&source), PatchOutcome::AnchorMissing));
}
+
+ #[test]
+ fn changed_owner_static_is_skipped() {
+ let source = released().replace(ORIGINAL_STATIC, "");
+ assert!(matches!(patch_source(&source), PatchOutcome::AnchorMissing));
+ }
+
+ #[test]
+ fn mixed_original_and_shipped_states_are_skipped() {
+ let source = format!("{}{}", released(), shipped());
+ assert!(matches!(patch_source(&source), PatchOutcome::AnchorMissing));
+ }
+
+ #[test]
+ fn repaired_core_passes_the_javascript_contract() {
+ 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();
+ let shipped = format!(
+ "const css = \"{}\";{}",
+ PATCHED_CSS,
+ FIXTURE.replacen(ORIGINAL_BIND, LEGACY_BIND, 1).replacen(
+ ORIGINAL_FOLLOW,
+ LEGACY_FOLLOW,
+ 1
+ )
+ );
+ let PatchOutcome::Patched(repaired) = patch_source(&shipped) else {
+ panic!("shipped fixture should be repaired");
+ };
+ assert!(matches!(
+ patch_source(&repaired),
+ PatchOutcome::AlreadyPatched
+ ));
+ std::fs::write(&target, &repaired).unwrap();
+
+ let script = Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("../test/fixtures/chat-follow-anchor-contract.mjs");
+ let mut child = Command::new("node")
+ .arg(script)
+ .arg(&target)
+ .stdin(Stdio::null())
+ .spawn()
+ .expect("node is required for the repaired JavaScript contract");
+ let deadline = Instant::now() + Duration::from_secs(20);
+ loop {
+ if let Some(status) = child.try_wait().unwrap() {
+ assert!(
+ status.success(),
+ "repaired JavaScript contract failed: {status}"
+ );
+ break;
+ }
+ if Instant::now() >= deadline {
+ child.kill().unwrap();
+ child.wait().unwrap();
+ panic!("repaired JavaScript contract timed out");
+ }
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ }
}
diff --git a/test/chat-follow-anchor-patch.test.ts b/test/chat-follow-anchor-patch.test.ts
index 82edff19..c736399a 100644
--- a/test/chat-follow-anchor-patch.test.ts
+++ b/test/chat-follow-anchor-patch.test.ts
@@ -7,19 +7,28 @@ const rust = readFileSync(resolve('src-tauri/src/service/patch/chat_follow_ancho
const fixturePath = resolve('test/fixtures/chat-follow-anchor.txt')
const fixture = readFileSync(fixturePath, 'utf8')
-function anchor(name: string) {
- const original = rust.match(new RegExp(`const ORIGINAL_${name}: &str = r#"([\\s\\S]*?)"#;`))?.[1]
- const patched = rust.match(new RegExp(`const PATCHED_${name}: &str = r#"([\\s\\S]*?)"#;`))?.[1]
- if (!original || !patched)
+function constString(name: string) {
+ const value = rust.match(new RegExp(`const ${name}: &str\\s*=\\s*r#"([\\s\\S]*?)"#;`))?.[1]
+ if (!value)
throw new Error(`Missing ${name} patch anchor`)
- return { original, patched }
+ return value
+}
+
+function anchor(name: string) {
+ return { original: constString(`ORIGINAL_${name}`), patched: constString(`PATCHED_${name}`) }
}
const css = anchor('CSS')
+const stat = anchor('STATIC')
const bind = anchor('BIND')
const follow = anchor('FOLLOW')
-if (fixture.split(bind.original).length !== 2 || fixture.split(follow.original).length !== 2)
- throw new Error('Missing unique production follow-anchor patch')
+const legacyBind = constString('LEGACY_BIND')
+const legacyFollow = constString('LEGACY_FOLLOW')
+
+for (const original of [stat.original, bind.original, follow.original]) {
+ if (fixture.split(original).length !== 2)
+ throw new Error('Missing unique production follow-anchor patch')
+}
let directory: string | undefined
@@ -37,26 +46,48 @@ function runContract(path: string) {
)
}
+function patchedFixture() {
+ return fixture
+ .replace(stat.original, stat.patched)
+ .replace(bind.original, bind.patched)
+ .replace(follow.original, follow.patched)
+}
+
+function writeTemporary(source: string) {
+ directory = mkdtempSync(resolve('test/.chat-follow-anchor-'))
+ const target = resolve(directory, 'client.txt')
+ writeFileSync(target, source)
+ return target
+}
+
describe('chat follow anchor patch', () => {
it('drops the ancestor :has() and mirrors the same attribute from JavaScript', () => {
expect(css.original).toContain(':has(.EvIC1a_root[data-chat-following-tail])')
expect(css.patched).toBe('[data-conversation-scroll][data-chat-following-tail]')
expect(css.patched).not.toContain(':has(')
+ expect(stat.patched).toContain('static followers = /* @__PURE__ */ new WeakMap();')
expect(bind.patched).toContain('this.followAnchor();')
+ expect(bind.patched).toContain('ScrollFollow.followers.get(scrollport)')
+ expect(follow.patched).not.toContain('ScrollFollow.owners.forEach')
+ expect(follow.patched).toContain('ScrollFollow.followers.get(scrollport)')
expect(follow.patched).toContain('scrollport.setAttribute("data-chat-following-tail", "")')
})
it('satisfies the shared contract with the production replacement', () => {
- directory = mkdtempSync(resolve('test/.chat-follow-anchor-'))
- const target = resolve(directory, 'client.txt')
- const patched = fixture.replace(bind.original, bind.patched).replace(follow.original, follow.patched)
- writeFileSync(target, patched)
- const result = runContract(target)
+ const result = runContract(writeTemporary(patchedFixture()))
expect(result.error).toBeUndefined()
expect(result.status, result.stdout + result.stderr).toBe(0)
expect(result.stdout).toMatch(/# fail 0\b/)
})
+ it('reproduces the shipped WeakMap crash for the legacy replacement', () => {
+ const legacy = fixture.replace(bind.original, legacyBind).replace(follow.original, legacyFollow)
+ const result = runContract(writeTemporary(legacy))
+ expect(result.error).toBeUndefined()
+ expect(result.status, result.stdout + result.stderr).toBe(1)
+ expect(result.stdout).toContain('ScrollFollow.owners.forEach is not a function')
+ })
+
it('rejects the released source that never mirrors the follow intent', () => {
const result = runContract(fixturePath)
expect(result.error).toBeUndefined()
diff --git a/test/fixtures/chat-follow-anchor-contract.mjs b/test/fixtures/chat-follow-anchor-contract.mjs
index 7f1d89f4..55476c3c 100644
--- a/test/fixtures/chat-follow-anchor-contract.mjs
+++ b/test/fixtures/chat-follow-anchor-contract.mjs
@@ -90,6 +90,23 @@ test('without an enclosing conversation scrollport nothing is written', () => {
assert.deepEqual(port.writes, [])
})
+test('releasing a stale binding still drops its follower', () => {
+ const port = scrollport()
+ const element = {
+ closest: selector => (selector === '[data-conversation-scroll]' ? port : null),
+ }
+ const stale = new ScrollFollow()
+ const unbindStale = stale.bind(element)
+ stale.setFollowing(true)
+ const current = new ScrollFollow()
+ current.bind(element)
+ assert.equal(port.attributes.has(ATTRIBUTE), true)
+ unbindStale()
+ assert.equal(port.attributes.has(ATTRIBUTE), false)
+ current.setFollowing(false)
+ assert.equal(port.attributes.has(ATTRIBUTE), false)
+})
+
test('one follower leaving the tail keeps the mirror while another follows', () => {
const shared = scrollport()
const first = bind({ port: shared })
diff --git a/test/fixtures/chat-follow-anchor.txt b/test/fixtures/chat-follow-anchor.txt
index 7c858b63..ffde7150 100644
--- a/test/fixtures/chat-follow-anchor.txt
+++ b/test/fixtures/chat-follow-anchor.txt
@@ -1,9 +1,10 @@
var ScrollFollow = class ScrollFollow {
+ static owners = /* @__PURE__ */ new WeakMap();
constructor() {
this.following = false;
this.target = null;
}
- bind(element) {
+ bind(element) {
ScrollFollow.owners.set(element, this);
return () => {
if (ScrollFollow.owners.get(element) === this) ScrollFollow.owners.delete(element);
@@ -14,4 +15,3 @@ var ScrollFollow = class ScrollFollow {
if (!active) this.target = null;
}
};
-ScrollFollow.owners = new Map();