Merge remote-tracking branch 'origin/main' into pr-6269

Цей коміт міститься в:
l0ng-ai committed 2026-11-27 07:21:11 +08:00
коміт 9a9be3136e
8 files changed
+496 -61

No files matched your search

+31 -20
Переглянути файл
@@ -174,6 +174,9 @@ struct DocState {
/// The file changed on disk while this buffer had unsaved changes; autosave leaves it
/// alone until the user saves explicitly or the buffer is reloaded.
disk_conflict: bool,
/// External changes seen while the buffer had unsaved changes (each `disk_conflict`), so an
/// undo of a refactoring can tell a write by another program from the IDE's own saves.
external_writes: u64,
/// Text as of that disk state: an edit that returns to it (undo) leaves the document clean.
/// `None` for large files (no second copy), virtual documents, and once a pending encoding,
/// line-ending or BOM change makes the buffer differ from the file whatever the text.
@@ -540,6 +543,7 @@ impl Documents {
disk_mtime: loaded.mtime_ms,
disk_len: disk_len(path),
disk_conflict: false,
external_writes: 0,
clean_text: None,
closed: false,
uri: None,
@@ -616,6 +620,7 @@ impl Documents {
disk_mtime: 0.0,
disk_len: 0,
disk_conflict: false,
external_writes: 0,
clean_text: None,
closed: false,
uri: Some(uri.to_owned()),
@@ -676,6 +681,7 @@ impl Documents {
disk_mtime: 0.0,
disk_len: 0,
disk_conflict: false,
external_writes: 0,
clean_text: None,
closed: false,
uri: Some(key.to_string_lossy().into_owned()),
@@ -948,20 +954,7 @@ impl Documents {
/// on disk after this buffer was edited, which only an explicit save may overwrite.
pub fn autosave(&self, doc: DocId) -> IdeResult<bool> {
self.with_doc(doc, |st| {
// The watcher event for an external write may not have arrived yet: check the stamp now.
if st.dirty
&& !st.disk_conflict
&& st.uri.is_none()
&& let Ok(meta) = std::fs::metadata(&st.path)
&& st.changed_on_disk(&meta)
{
st.disk_mtime = ide_vfs::mtime_ms(&meta);
st.disk_len = meta.len();
st.disk_conflict = true;
// The text read before no longer matches the file: undoing back to it is not clean.
st.clean_text = None;
self.sink.emit(IdeEvent::DocDiskConflict { doc, path: st.path.to_string_lossy().into_owned() });
}
self.check_disk_conflict(doc, st);
if st.dirty && st.disk_conflict {
return Ok(false);
}
@@ -969,6 +962,29 @@ impl Documents {
})
}
/// An unsaved buffer whose file another program wrote: the watcher event may not have arrived
/// yet, so check the stamp now.
fn check_disk_conflict(&self, doc: DocId, st: &mut DocState) {
if st.dirty
&& !st.disk_conflict
&& st.uri.is_none()
&& let Ok(meta) = std::fs::metadata(&st.path)
&& st.changed_on_disk(&meta)
{
self.disk_conflict(doc, st, &meta);
}
}
fn disk_conflict(&self, doc: DocId, st: &mut DocState, meta: &std::fs::Metadata) {
st.disk_mtime = ide_vfs::mtime_ms(meta);
st.disk_len = meta.len();
st.disk_conflict = true;
st.external_writes += 1;
// The text read before no longer matches the file: undoing back to it is not clean.
st.clean_text = None;
self.sink.emit(IdeEvent::DocDiskConflict { doc, path: st.path.to_string_lossy().into_owned() });
}
fn write(&self, doc: DocId, st: &mut DocState) -> IdeResult<()> {
{
if !st.dirty || st.uri.is_some() {
@@ -1443,12 +1459,7 @@ impl Documents {
if !st.changed_on_disk(&meta) {
return Ok(());
}
st.disk_mtime = mtime;
st.disk_len = meta.len();
st.disk_conflict = true;
// The text read before no longer matches the file: undoing back to it is not clean.
st.clean_text = None;
self.sink.emit(IdeEvent::DocDiskConflict { doc: id, path: st.path.to_string_lossy().into_owned() });
self.disk_conflict(id, st, &meta);
return Ok(());
}
let loaded = if force_clean {
+42 -1
Переглянути файл
@@ -100,6 +100,8 @@ struct Record {
paths: Vec<SavedPath>,
documents: Vec<(DocId, DocState)>,
after: Vec<WorkspaceEditPrecondition>,
/// External writes seen by each open document as of `after` (see [`Documents::external_writes`]).
writes: Vec<(DocId, u64)>,
}
fn stale(path: &Path) -> IdeError {
@@ -369,6 +371,35 @@ impl Documents {
.collect()
}
/// How many external writes each open document under `roots` has seen, with its path. An
/// unsaved buffer's file is checked first, for a write the watcher hasn't reported yet.
fn external_writes(&self, roots: &[PathBuf]) -> IdeResult<Vec<(DocId, u64, PathBuf)>> {
let mut writes = Vec::new();
for id in self.open_documents() {
self.with_doc(id, |state| {
if roots.iter().any(|p| text_path(&state.path).is_ok_and(|file| file.starts_with(p))) {
self.check_disk_conflict(id, state);
writes.push((id, state.external_writes, state.path.clone()));
}
Ok(())
})?;
}
Ok(writes)
}
/// Fingerprints see an unsaved buffer in place of its file, so another program writing that
/// file since the record was made shows only as a disk conflict. The IDE's own saves don't count.
fn validate_external_writes(&self, record: &Record, roots: &[PathBuf]) -> IdeResult<()> {
for (id, writes, path) in self.external_writes(roots)? {
// A document opened since then starts at zero.
let before = record.writes.iter().find(|(doc, _)| *doc == id).map_or(0, |(_, writes)| *writes);
if writes != before {
return Err(stale(&path));
}
}
Ok(())
}
fn validate_preconditions(&self, expected: &[WorkspaceEditPrecondition]) -> IdeResult<()> {
let current = self.fingerprints(&expected.iter().map(|p| p.path.to_path_buf()).collect::<Vec<_>>())?;
for (before, after) in expected.iter().zip(current) {
@@ -469,6 +500,10 @@ impl Documents {
Ok(after) => after,
Err(error) => return Err(self.recover(record, error)),
};
record.writes = match self.external_writes(&roots) {
Ok(writes) => writes.into_iter().map(|(id, writes, _)| (id, writes)).collect(),
Err(error) => return Err(self.recover(record, error)),
};
if let Err(error) = fs::remove_file(record.directory.path().join("recovery")) {
return Err(self.recover(record, error.into()));
}
@@ -568,6 +603,7 @@ impl Documents {
paths,
documents,
after: Vec::new(),
writes: Vec::new(),
})
}
@@ -869,8 +905,9 @@ impl Documents {
if record.undone != redo {
return Err(IdeError::invalid("the refactoring is already in the requested history state"));
}
self.validate_preconditions(&record.after)?;
let roots = record.paths.iter().map(|p| p.path.clone()).collect::<Vec<_>>();
self.validate_external_writes(record, &roots)?;
self.validate_preconditions(&record.after)?;
let mut current = self.backup(&roots)?;
fs::write(current.directory.path().join("recovery"), b"history restore in progress")?;
let _active = ActiveEdit::new(&self.workspace_edit_active);
@@ -881,6 +918,10 @@ impl Documents {
Ok(after) => after,
Err(error) => return Err(self.recover(current, error)),
};
current.writes = match self.external_writes(&roots) {
Ok(writes) => writes.into_iter().map(|(id, writes, _)| (id, writes)).collect(),
Err(error) => return Err(self.recover(current, error)),
};
current.undone = !redo;
current.created = record.created;
if let Err(error) = fs::remove_file(current.directory.path().join("recovery")) {
+74
Переглянути файл
@@ -426,6 +426,80 @@ fn undo_refuses_later_changes_and_retains_the_record() {
assert_eq!(std::fs::read_to_string(a).unwrap(), "old\n");
}
/// An open file with unsaved typing, refactored: its buffer holds `new`, the disk still `old`.
fn refactored_unsaved(path: &Path) -> (Documents, Arc<Mutex<Vec<IdeEvent>>>, ide_core::DocId) {
std::fs::write(path, "old\n").unwrap();
let (docs, events) = recorded_documents();
let info = docs.open(path).unwrap();
docs.edit(info.id, info.version, ChangeSet { changes: vec![TextChange { from: 0, to: 3, insert: "own".into() }] })
.unwrap();
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(path, "new")], ..Default::default() }).unwrap();
assert_eq!(docs.snapshot(info.id).unwrap().text, "new\n");
(docs, events, info.id)
}
fn type_text(docs: &Documents, id: ide_core::DocId, text: &str) {
let snapshot = docs.snapshot(id).unwrap();
let to = snapshot.text.encode_utf16().count() as u32;
docs.edit(id, snapshot.version, ChangeSet { changes: vec![TextChange { from: 0, to, insert: text.into() }] })
.unwrap();
}
#[test]
fn undo_keeps_an_external_write_under_an_unsaved_buffer() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("a.txt");
let (docs, events, id) = refactored_unsaved(&path);
// Not reported by a watcher: undo itself notices the write.
std::fs::write(&path, "external\n").unwrap();
assert_eq!(docs.undo_workspace_edit(undo_id(&events)).unwrap_err().kind, ErrorKind::OutOfSync);
assert_eq!(std::fs::read_to_string(&path).unwrap(), "external\n");
assert_eq!(docs.snapshot(id).unwrap().text, "new\n");
}
#[test]
fn undo_after_saving_and_undoing_the_typing_is_allowed() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("a.txt");
let (docs, events, id) = refactored_unsaved(&path);
type_text(&docs, id, "typed later\n");
docs.save(id).unwrap();
// The typing undone: the buffer is back to the refactoring's text, the IDE's own save on disk.
type_text(&docs, id, "new\n");
docs.undo_workspace_edit(undo_id(&events)).unwrap();
assert_eq!(docs.snapshot(id).unwrap().text, "own\n");
assert_eq!(std::fs::read_to_string(&path).unwrap(), "old\n");
}
#[test]
fn undo_allows_a_disk_conflict_from_before_the_refactoring() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("a.txt");
std::fs::write(&path, "old\n").unwrap();
let (docs, events) = recorded_documents();
let info = docs.open(&path).unwrap();
type_text(&docs, info.id, "own\n");
std::fs::write(&path, "external\n").unwrap();
assert!(!docs.autosave(info.id).unwrap(), "the external write is a disk conflict");
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&path, "new")], ..Default::default() }).unwrap();
docs.undo_workspace_edit(undo_id(&events)).unwrap();
assert_eq!(docs.snapshot(info.id).unwrap().text, "own\n");
assert_eq!(std::fs::read_to_string(&path).unwrap(), "external\n");
}
#[test]
fn redo_keeps_an_external_write_made_after_the_undo() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("a.txt");
let (docs, events, id) = refactored_unsaved(&path);
let undo = undo_id(&events);
docs.undo_workspace_edit(undo).unwrap();
std::fs::write(&path, "external\n").unwrap();
assert_eq!(docs.redo_workspace_edit(undo).unwrap_err().kind, ErrorKind::OutOfSync);
assert_eq!(std::fs::read_to_string(&path).unwrap(), "external\n");
assert_eq!(docs.snapshot(id).unwrap().text, "own\n");
}
#[test]
fn ordered_resource_operations_and_binary_deletion_are_undoable() {
let tmp = tempfile::tempdir().unwrap();
+45
Переглянути файл
@@ -209,3 +209,48 @@ test("opens a folded process run with the keyboard and jumps back to the latest
await expect(jump).toBeHidden();
await expect.poll(() => stream.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop)).toBeLessThan(40);
});
test("paints earlier turns past folded process runs longer than ENTRY_BATCH", async ({ page }) => {
const longRun = (prefix: string, count: number): AgentEntry[] =>
Array.from({ length: count }, (_, i): AgentEntry => ({
type: "tool",
id: `${prefix}-${i}`,
kind: i % 3 === 0 ? "edit" : i % 2 === 0 ? "execute" : "read",
title: `tool ${prefix}-${i}`,
status: "completed",
locations: [],
output: null,
diffs: [],
}));
const longProcessEntries: AgentEntry[] = [
{ type: "user", text: "Earliest request before long runs", attachments: [], steered: false },
{ type: "agent", text: "Initial reply" },
{ type: "user", text: "Split PR into three focused PRs", attachments: [], steered: false },
...longRun("batch-a", 75),
{ type: "agent", text: "Interim status update" },
...longRun("batch-b", 75),
];
await page.goto("/");
await page.getByRole("tree", { name: "Project" }).waitFor();
await page.evaluate(
async ({ task, entries }) => {
const path = "/src/features/agents/store.ts";
const store = await import(path);
store.useAgents.setState({
loaded: true,
error: null,
providers: [],
tasks: new Map([[task.id, { ...task, status: "running" }]]),
entries: new Map([[task.id, entries]]),
unread: new Set(),
docked: null,
});
store.openTaskInEditorLocation(task.id);
},
{ task, entries: longProcessEntries },
);
const stream = page.locator("[class*='_stream_']:visible");
await expect(stream.getByText("Earliest request before long runs")).toBeVisible();
await expect(stream.getByText("Split PR into three focused PRs")).toBeVisible();
await expect(stream.getByText("Interim status update")).toBeVisible();
});
+1 -2
Переглянути файл
@@ -78,9 +78,8 @@ block2 = "0.6"
# Plugin secrets in the login keychain.
security-framework = "3.7"
objc2 = "0.6"
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "NSApplication", "NSButton", "NSEvent", "NSGraphics", "NSResponder", "NSScreen", "NSTitlebarAccessoryViewController", "NSToolbar", "NSView", "NSViewController", "NSWindow", "NSWindowTabGroup", "NSWorkspace"] }
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "NSApplication", "NSButton", "NSEvent", "NSGraphics", "NSResponder", "NSScreen", "NSTextCheckingClient", "NSTitlebarAccessoryViewController", "NSToolbar", "NSView", "NSViewController", "NSWindow", "NSWindowTabGroup", "NSWorkspace"] }
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSLocale", "NSNotification", "NSOperation", "NSString"] }
# Used only by the debug font-restriction override; Cargo dependency cfg cannot test debug_assertions.
objc2-web-kit = { version = "0.3", default-features = false, features = ["std", "WKWebViewConfiguration", "WKPreferences"] }
[target.'cfg(target_os = "linux")'.dependencies]
+166 -23
Переглянути файл
@@ -1069,7 +1069,9 @@ fn build_project_window(app: &AppHandle, mut config: WindowConfig) -> IdeResult<
(config.min_width, config.min_height) = (Some(min.0), Some(min.1));
}
let window = WebviewWindowBuilder::from_config(app, &config)
.and_then(|b| dev_font_preferences(webview_profile(app, b)).on_new_window(open_popup_in_browser).build())
.and_then(|b| {
macos_webview_configuration(app, webview_profile(app, b)).on_new_window(open_popup_in_browser).build()
})
.map_err(|e| IdeError::internal(format!("cannot create window: {e}")))?;
#[cfg(target_os = "linux")]
decorate_csd(&window);
@@ -1907,10 +1909,11 @@ pub fn open_auxiliary_window(app: &AppHandle, caller: &WebviewWindow, aux: AuxWi
// display's Space, so macOS keeps it too.
#[cfg(target_os = "linux")]
let builder = builder.and_then(|b| b.parent(&parent));
let window = builder.and_then(|b| dev_font_preferences(webview_profile(app, b)).build()).map_err(|e| {
windows.forget(&label);
IdeError::internal(format!("cannot create {} window: {e}", aux.kind.name()))
})?;
let window =
builder.and_then(|b| macos_webview_configuration(app, webview_profile(app, b)).build()).map_err(|e| {
windows.forget(&label);
IdeError::internal(format!("cannot create {} window: {e}", aux.kind.name()))
})?;
#[cfg(target_os = "linux")]
decorate_csd(&window);
#[cfg(target_os = "macos")]
@@ -2443,18 +2446,86 @@ fn webview_profile<'a>(
builder
}
/// Reproduce WKWebView's user-font restriction before WKWebView creation. The
/// private selector and environment override are absent from release builds.
#[cfg(all(debug_assertions, target_os = "macos"))]
fn dev_font_preferences(
builder: WebviewWindowBuilder<'_, tauri::Wry, AppHandle>,
) -> WebviewWindowBuilder<'_, tauri::Wry, AppHandle> {
/// Configure macOS `WKWebViewConfiguration` before `WKWebView` creation:
/// - Disable macOS 15+ Apple Intelligence Writing Tools so its floating selection
/// affordance does not appear over Markdown previews, Quick Documentation, or editors.
/// - In debug builds, optionally reproduce WKWebView's user-font restriction when
/// `OPENIDEA_DEV_DISALLOW_USER_FONTS=1` is set (absent from release builds).
#[cfg(target_os = "macos")]
fn macos_webview_configuration<'a>(
app: &AppHandle,
builder: WebviewWindowBuilder<'a, tauri::Wry, AppHandle>,
) -> WebviewWindowBuilder<'a, tauri::Wry, AppHandle> {
match build_macos_webview_configuration(app) {
Some(config) => builder.with_webview_configuration(config),
None => builder,
}
}
#[cfg(target_os = "macos")]
fn build_macos_webview_configuration(
app: &AppHandle,
) -> Option<objc2::rc::Retained<objc2_web_kit::WKWebViewConfiguration>> {
build_macos_webview_configuration_with(|f| app.run_on_main_thread(f))
}
#[cfg(target_os = "macos")]
fn build_macos_webview_configuration_with(
run_on_main_thread: impl FnOnce(Box<dyn FnOnce() + Send>) -> tauri::Result<()>,
) -> Option<objc2::rc::Retained<objc2_web_kit::WKWebViewConfiguration>> {
const ON_MAIN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
struct SendConfig(objc2::rc::Retained<objc2_web_kit::WKWebViewConfiguration>);
// SAFETY: Created and configured exclusively on the main thread, then moved untouched into
// `WebviewWindowBuilder::with_webview_configuration`, which transfers it back to the main
// thread when Wry constructs the WKWebView.
unsafe impl Send for SendConfig {}
let make = |mtm: objc2::MainThreadMarker| {
let config = unsafe { objc2_web_kit::WKWebViewConfiguration::new(mtm) };
configure_macos_webview_configuration(&config).then_some(SendConfig(config))
};
if let Some(mtm) = objc2::MainThreadMarker::new() {
return make(mtm).map(|c| c.0);
}
// Secondary project windows (`spawn_window`) and auxiliary windows (`open_auxiliary_window`)
// build off the main thread; create the configuration on the AppKit main thread and fall back
// to the default builder if the event loop cannot service it.
let (tx, rx) = std::sync::mpsc::sync_channel(1);
if let Err(err) = run_on_main_thread(Box::new(move || {
let result = objc2::MainThreadMarker::new().and_then(make);
let _ = tx.send(result);
})) {
tracing::warn!("could not schedule macOS WKWebViewConfiguration on main thread: {err}");
return None;
}
match rx.recv_timeout(ON_MAIN_TIMEOUT) {
Ok(Some(config)) => Some(config.0),
Ok(None) => None,
Err(err) => {
tracing::warn!("timed out waiting for macOS WKWebViewConfiguration on main thread: {err}");
None
}
}
}
#[cfg(target_os = "macos")]
fn configure_macos_webview_configuration(config: &objc2_web_kit::WKWebViewConfiguration) -> bool {
use objc2::{msg_send, sel};
use objc2_app_kit::NSWritingToolsBehavior;
use objc2_foundation::NSObjectProtocol;
let mut configured = false;
if config.respondsToSelector(sel!(setWritingToolsBehavior:)) {
unsafe {
let _: () = msg_send![config, setWritingToolsBehavior: NSWritingToolsBehavior::None];
}
configured = true;
}
#[cfg(debug_assertions)]
if std::env::var("OPENIDEA_DEV_DISALLOW_USER_FONTS").as_deref() == Ok("1") {
use objc2::{MainThreadMarker, msg_send, sel};
use objc2_foundation::NSObjectProtocol;
let config = unsafe {
objc2_web_kit::WKWebViewConfiguration::new(MainThreadMarker::new().expect("window creation on main thread"))
};
let preferences = unsafe { config.preferences() };
if preferences.respondsToSelector(sel!(_setShouldAllowUserInstalledFonts:)) {
unsafe {
@@ -2462,17 +2533,19 @@ fn dev_font_preferences(
}
let allowed: bool = unsafe { msg_send![&preferences, _shouldAllowUserInstalledFonts] };
tracing::info!(allowed, "Development user-installed fonts override");
return builder.with_webview_configuration(config);
configured = true;
} else {
tracing::warn!("WKPreferences user-font development selector unavailable");
}
tracing::warn!("WKPreferences user-font development selector unavailable");
}
builder
configured
}
#[cfg(not(all(debug_assertions, target_os = "macos")))]
fn dev_font_preferences(
builder: WebviewWindowBuilder<'_, tauri::Wry, AppHandle>,
) -> WebviewWindowBuilder<'_, tauri::Wry, AppHandle> {
#[cfg(not(target_os = "macos"))]
fn macos_webview_configuration<'a>(
_app: &AppHandle,
builder: WebviewWindowBuilder<'a, tauri::Wry, AppHandle>,
) -> WebviewWindowBuilder<'a, tauri::Wry, AppHandle> {
builder
}
@@ -2561,6 +2634,76 @@ mod tests {
}
}
#[cfg(target_os = "macos")]
#[test]
fn macos_webview_configuration_disables_writing_tools() {
use objc2::{MainThreadMarker, msg_send, sel};
use objc2_app_kit::NSWritingToolsBehavior;
use objc2_foundation::NSObjectProtocol;
let Some(mtm) = MainThreadMarker::new() else {
return;
};
let config = unsafe { objc2_web_kit::WKWebViewConfiguration::new(mtm) };
let configured = configure_macos_webview_configuration(&config);
if config.respondsToSelector(sel!(writingToolsBehavior)) {
assert!(configured);
let behavior: NSWritingToolsBehavior = unsafe { msg_send![&config, writingToolsBehavior] };
assert_eq!(behavior, NSWritingToolsBehavior::None);
}
}
#[cfg(target_os = "macos")]
#[test]
fn macos_webview_configuration_handles_non_main_thread() {
use objc2::{MainThreadMarker, sel};
use objc2_foundation::NSObjectProtocol;
// Off-thread scheduling failure falls back to None instead of panicking.
let result = std::thread::spawn(|| {
assert!(MainThreadMarker::new().is_none());
build_macos_webview_configuration_with(|_| Err(tauri::Error::FailedToReceiveMessage)).is_none()
})
.join()
.expect("worker thread must not panic");
assert!(result);
// Off-thread callback without a main-thread marker falls back to None instead of panicking.
let result = std::thread::spawn(|| {
assert!(MainThreadMarker::new().is_none());
build_macos_webview_configuration_with(|f| {
f();
Ok(())
})
.is_none()
})
.join()
.expect("worker thread must not panic");
assert!(result);
// When a main thread is available (e.g. nextest or --test-threads=1), dispatching from a
// worker thread constructs and configures WKWebViewConfiguration on the main thread.
if let Some(mtm) = MainThreadMarker::new() {
let probe = unsafe { objc2_web_kit::WKWebViewConfiguration::new(mtm) };
let expects_config = probe.respondsToSelector(sel!(setWritingToolsBehavior:));
let (work_tx, work_rx) = std::sync::mpsc::sync_channel::<Box<dyn FnOnce() + Send>>(1);
let worker = std::thread::spawn(move || {
assert!(MainThreadMarker::new().is_none());
build_macos_webview_configuration_with(move |f| {
work_tx.send(f).map_err(|_| tauri::Error::FailedToReceiveMessage)
})
.is_some()
});
let work = work_rx.recv().expect("worker should schedule onto main thread");
work();
let got_config = worker.join().expect("worker thread must not panic");
if expects_config {
assert!(got_config);
}
}
}
#[test]
fn frame_colours_from_the_ui_parse_as_hex() {
for (hex, expected) in [
+85
Переглянути файл
@@ -255,4 +255,89 @@ describe("a kept-alive session tab that stays hidden", { timeout: 30_000 }, () =
// The one request in the trimmed part of the history is found.
expect(await screen.findByText("1/1", {}, { timeout: 10_000 })).toBeInTheDocument();
});
it("paints earlier messages past folded process runs longer than ENTRY_BATCH on open and after hiding", async () => {
const toolCalls = (prefix: string, count: number): AgentEntry[] =>
Array.from({ length: count }, (_, k): AgentEntry => ({
type: "tool",
id: `${prefix}-${k}`,
title: `Read src/file${k}.ts`,
kind: "read",
status: "completed",
locations: [],
output: null,
diffs: [],
}));
const longRuns: AgentEntry[] = [
...history(5),
{ type: "user", text: "Split the PR", attachments: [], sentMs: null },
...toolCalls("first-run", 75),
{ type: "agent", text: "Interim update" },
...toolCalls("second-run", 75),
];
useAgents.setState({
tasks: new Map([[task("A").id, { ...task("A"), status: "running" }]]),
entries: new Map([["A", longRuns]]),
});
const view = render(session(true));
expect(await screen.findByText("Request 0", {}, { timeout: 3_000 })).toBeInTheDocument();
expect(screen.getByText("Split the PR")).toBeInTheDocument();
vi.useFakeTimers();
view.rerender(session(false));
await act(async () => {
await vi.advanceTimersByTimeAsync(LONG_HIDDEN_MS);
});
expect(screen.queryByText("Request 0")).toBeNull();
vi.useRealTimers();
view.rerender(session(true));
expect(await screen.findByText("Request 0", {}, { timeout: 3_000 })).toBeInTheDocument();
expect(screen.getByText("Split the PR")).toBeInTheDocument();
});
it("loads earlier messages past a long process run when scrolled to the top with stick disabled", async () => {
const longRun: AgentEntry[] = [
...history(3),
{ type: "user", text: "Prompt before long run", attachments: [], sentMs: null },
...Array.from({ length: 75 }, (_, k): AgentEntry => ({
type: "tool",
id: `top-run-${k}`,
title: `Read src/mod${k}.ts`,
kind: "read",
status: "completed",
locations: [],
output: null,
diffs: [],
})),
{ type: "agent", text: "Tail reply" },
];
useAgents.setState({ entries: new Map([["A", longRun]]) });
// Suppress background auto-follow after initial render by scrolling away before history finishes.
const view = render(session(true));
await settle("Tail reply");
vi.useFakeTimers();
view.rerender(session(false));
await act(async () => {
await vi.advanceTimersByTimeAsync(LONG_HIDDEN_MS);
});
expect(screen.queryByText("Request 0")).toBeNull();
// User switches back while holding pointer down, then scrolls to the top (`stick: false`).
fireEvent.pointerDown(stream());
view.rerender(session(true));
const el = stream();
layOut(el);
fireEvent.wheel(el, { deltaY: -120 });
el.scrollTop = 0;
fireEvent.scroll(el);
fireEvent.pointerUp(window);
await act(async () => {
await vi.advanceTimersByTimeAsync(2_000);
});
vi.useRealTimers();
expect(await screen.findByText("Request 0", {}, { timeout: 3_000 })).toBeInTheDocument();
expect(screen.getByText("Prompt before long run")).toBeInTheDocument();
});
});
+52 -15
Переглянути файл
@@ -212,6 +212,24 @@ function clampMultiClick(target: EventTarget) {
if (row) clampSelectionToRow(document.getSelection(), row);
}
/** First entry index painted for a `shown` tail cap, keeping a leading process run intact. */
function historyStart(entries: readonly AgentEntry[], shown: number): number {
let start = Math.max(0, entries.length - shown);
// Keep a process run intact so prepending never replaces the anchored row.
while (start > 0 && isProcessEntry(entries[start]!) && isProcessEntry(entries[start - 1]!)) start--;
return start;
}
/**
* Next `shown` cap after one batch. Keeping a process run intact can already paint more than
* `shown` entries, so step past what is actually painted (`entries.length - start`) rather than
* `shown`; otherwise a process run longer than `ENTRY_BATCH` leaves `start` unchanged and stalls.
*/
function nextShownBatch(entries: readonly AgentEntry[] | null, shown: number): number {
if (!entries) return shown + ENTRY_BATCH;
return Math.max(shown, entries.length - historyStart(entries, shown)) + ENTRY_BATCH;
}
export function Stream({
loadError,
task,
@@ -239,9 +257,11 @@ export function Stream({
// Opened at the end, the last entries come first and the earlier ones follow in batches:
// reopening a long conversation paints at once. A kept offset needs them all.
const [shown, setShown] = useState(() => (positions.get(key)?.stick === false ? Infinity : ENTRY_BATCH));
let start = finding || !entries ? 0 : Math.max(0, entries.length - shown);
// Keep a process run intact so prepending never replaces the anchored row.
while (entries && start > 0 && isProcessEntry(entries[start]!) && isProcessEntry(entries[start - 1]!)) start--;
const start = finding || !entries ? 0 : historyStart(entries, shown);
const latest = useRef({ entries, start, visible });
useLayoutEffect(() => {
latest.current = { entries, start, visible };
});
const dragging = useRef(false);
// When the user last scrolled the conversation (wheel, touch, keys, the scrollbar, Find):
// that leaves the end. WebKit also moves the offset back on its own while rows lay out,
@@ -280,11 +300,12 @@ export function Stream({
const anchor = useRef<{ el: Element; top: number } | null>(null);
const loadEarlier = useCallback(() => {
const el = ref.current;
if (!visible || !el || start <= 0 || dragging.current || anchor.current) return;
const { start: currentStart, visible: isVisible } = latest.current;
if (!isVisible || !el || currentStart <= 0 || dragging.current || anchor.current) return;
const first = el.firstElementChild;
if (!position.current.stick && first) anchor.current = { el: first, top: first.getBoundingClientRect().top };
startTransition(() => setShown((n) => n + ENTRY_BATCH));
}, [start, visible]);
startTransition(() => setShown((n) => nextShownBatch(latest.current.entries, n)));
}, []);
const loadTimer = useRef<number | null>(null);
/** Load the next batch once the user stops scrolling near the top. */
const loadWhenStill = useCallback(() => {
@@ -298,12 +319,19 @@ export function Stream({
const down = (event: PointerEvent) => {
if (!ref.current?.contains(event.target as Node)) return;
dragging.current = true;
if (loadTimer.current !== null) window.clearTimeout(loadTimer.current);
if (loadTimer.current !== null) {
window.clearTimeout(loadTimer.current);
loadTimer.current = null;
}
};
const up = () => {
if (!dragging.current) return;
dragging.current = false;
if (ref.current && (position.current.stick || ref.current.scrollTop < 120)) loadWhenStill();
if (
ref.current &&
(position.current.stick || ref.current.scrollHeight <= ref.current.clientHeight || ref.current.scrollTop < 120)
)
loadWhenStill();
};
window.addEventListener("pointerdown", down, true);
window.addEventListener("pointerup", up, true);
@@ -314,16 +342,24 @@ export function Stream({
window.removeEventListener("pointerup", up, true);
window.removeEventListener("pointercancel", up, true);
window.removeEventListener("blur", up);
if (loadTimer.current !== null) window.clearTimeout(loadTimer.current);
if (loadTimer.current !== null) {
window.clearTimeout(loadTimer.current);
loadTimer.current = null;
}
};
}, [loadWhenStill]);
useEffect(() => {
// Following the end, paint the rest in the background. A user who scrolled away
// gets them only after stopping near the top (`loadWhenStill`), so the scrollbar
// is not resized mid-drag. A hidden tab paints nothing more.
if (visible && start > 0 && position.current.stick && !dragging.current)
startTransition(() => setShown((n) => n + ENTRY_BATCH));
}, [start, visible]);
// gets them only after stopping near the top (`loadWhenStill`), or when folded rows
// do not yet fill the viewport, so the scrollbar is not resized mid-drag. A hidden
// tab paints nothing more.
if (!visible || start <= 0 || dragging.current) return;
if (position.current.stick) {
startTransition(() => setShown((n) => nextShownBatch(latest.current.entries, n)));
} else if (ref.current && (ref.current.scrollHeight <= ref.current.clientHeight || ref.current.scrollTop < 120)) {
loadWhenStill();
}
}, [loadWhenStill, start, visible]);
useEffect(() => {
// A conversation read to its end gives back the history painted above its recent entries
// once it stays behind other tabs: a few kept-alive tabs would otherwise hold every turn
@@ -418,6 +454,7 @@ export function Stream({
const observer = new ResizeObserver(() => {
trimSlack();
if (position.current.stick && !dragging.current) el.scrollTop = el.scrollHeight;
else if (!position.current.stick && el.scrollHeight <= el.clientHeight && !dragging.current) loadWhenStill();
updateJumpVisibility(el);
});
observer.observe(el);
@@ -425,7 +462,7 @@ export function Stream({
observer.disconnect();
if (restored.current) positions.set(key, { ...position.current, top: el.scrollTop });
};
}, [key, positions, trimSlack, updateJumpVisibility]);
}, [key, loadWhenStill, positions, trimSlack, updateJumpVisibility]);
/**
* The wheel scrolls the innermost container under the pointer, and only that one: a run of
* calls from its headers, a tool output from its text, the conversation elsewhere. A container