Compare commits

...
Author SHA1 Message Date
l0ng-ai e1df881099 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	src/features/agents/session/Stream.tsx
2026-11-24 15:37:52 +08:00
l0ng-ai cc9089db11 test: make four tests pass on Windows (#5580)
Windows CI on main failed four tests the earlier clippy error had hidden:
- pipenv naming hashed a Unix path, which Windows joins with a backslash;
  the Windows expectation now uses a Windows path.
- the VIRTUAL_ENV assertion joined "member/.override" as one component.
- the diagnostics coalescing tests slept 30 ms for a 16 ms flush, too short
  for Windows timers; they wait for the flush with a deadline.
- the patch preview test read automatic mappings while new folders could
  still be re-indexing (automatic mappings pause then); it waits for indexing.
2026-11-24 15:36:45 +08:00
l0ng-ai 62095b904e fix(agents): keep selection highlights within reply text (#5574) 2026-11-24 15:36:40 +08:00
l0ng-ai 96c5e94975 fix(agents): open new tasks with less background work (#5573) 2026-11-24 15:36:35 +08:00
l0ng-ai da5f2bea68 fix(agents): extend the chat scrollbar to the composer 2026-11-24 15:28:50 +08:00
18 changed files with 281 additions and 148 deletions

No files matched your search

+8
View File
@@ -432,6 +432,14 @@ async fn patches_read_and_write_the_requested_repository() {
})
.collect::<String>();
let root = Some(roots[0].clone());
// Automatic mappings wait for indexing; the new folders and exclude rule may start a rescan.
tokio::time::sleep(Duration::from_millis(200)).await;
for _ in 0..500 {
if !project.index.status().indexing {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
let preview = vcs::vcs_patch_preview(&host, "main", root.clone(), patch.clone(), None, None).await.unwrap();
assert!(preview.files.iter().all(|file| file.applies && !file.missing_base));
assert_eq!(preview.automatic_mappings.len(), 1);
+3
View File
@@ -1605,7 +1605,10 @@ mod pipenv_tests {
#[test]
fn environments_are_named_as_pipenv_names_them() {
// `sanitize(folder)[:42] + "-" + urlsafe_b64encode(sha256(Pipfile path).digest()[:6])`, from pipenv.
#[cfg(unix)]
assert_eq!(pipenv_env_name(Path::new("/home/me/My Shop (2)")), "My_Shop__2_-6rNTtAUD");
#[cfg(windows)]
assert_eq!(pipenv_env_name(Path::new(r"C:\Users\me\My Shop (2)")), "My_Shop__2_-ED1rXUDC");
}
#[test]
+1 -1
View File
@@ -597,7 +597,7 @@ fn saved_python_configs_keep_their_explicit_interpreter() {
config.cwd = Some(Path::new("member").into());
apply_to_run_configs(std::slice::from_mut(&mut config), root, &settings);
assert_eq!(config.command, command);
assert_eq!(config.env["VIRTUAL_ENV"], root.join("member/.override").to_string_lossy());
assert_eq!(config.env["VIRTUAL_ENV"], root.join("member").join(".override").to_string_lossy());
let saved = without_derived(&config, root, &settings);
assert_eq!(saved.command, command);
}
+2 -1
View File
@@ -504,6 +504,7 @@ test("fits conversation stream, composer, question card and off-screen rows live
Number.parseFloat(getComputedStyle(root).paddingLeft) + Number.parseFloat(getComputedStyle(root).paddingRight);
return {
conversationWidth: conversation.clientWidth,
streamWidth: root.clientWidth,
streamInnerWidth: root.clientWidth - padding,
columnWidth: column.width,
bubbleWidth: bubble.width,
@@ -538,7 +539,7 @@ test("fits conversation stream, composer, question card and off-screen rows live
expect(Math.abs(fitted.columnWidth - fitted.streamInnerWidth)).toBeLessThan(1);
expect(fitted.bubbleWidth).toBeGreaterThan(720);
expect(Math.abs(fitted.bubbleWidth - fitted.streamInnerWidth * 0.8)).toBeLessThan(1);
expect(Math.abs(fitted.composerWidth - fitted.conversationWidth)).toBeLessThan(1);
expect(Math.abs(fitted.composerWidth - fitted.streamWidth)).toBeLessThan(1);
expect(Math.abs(fitted.questionWidth - fitted.streamInnerWidth)).toBeLessThan(1);
expect(fitted.offscreenRowHeight).toBeLessThan(capped.offscreenRowHeight);
expect(fitted.scrollHeight).toBeLessThan(capped.scrollHeight);
+30 -2
View File
@@ -61,7 +61,7 @@ async function openHistory(page: Page) {
{ task, entries },
);
const stream = page.locator("[class*='_stream_']:visible");
await expect(stream.locator(":scope > *")).toHaveCount(80 * 3);
await expect(stream.locator("[class*='_streamContent_'] > *")).toHaveCount(80 * 3);
await page.evaluate(() => document.fonts.ready);
return stream;
}
@@ -85,7 +85,7 @@ for (const placement of ["editor", "toolWindow"] as const) {
);
// The working indicator ends the conversation, after its rows; the turn ends with a reply.
await expect(stream.getByRole("status").getByText("Writing…", { exact: true })).toBeVisible();
await expect(stream.locator(":scope > *")).toHaveCount(80 * 3 + 1);
await expect(stream.locator("[class*='_streamContent_'] > *")).toHaveCount(80 * 3 + 1);
await expect.poll(() => stream.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop)).toBeLessThan(2);
const timer = await page.evaluate(async (id) => {
const path = "/src/features/agents/store.ts";
@@ -139,6 +139,34 @@ for (const placement of ["editor", "toolWindow"] as const) {
});
}
test("drags the conversation thumb through the full chat column", async ({ page }) => {
const stream = await openHistory(page);
const conversation = page.locator("[class*='_conversation_']:visible");
const track = conversation.locator(":scope > [class*='_track_']");
const thumb = track.locator(":scope > [class*='_thumb_']");
const column = (await conversation.boundingBox())!;
const viewport = (await stream.boundingBox())!;
const rail = (await track.boundingBox())!;
const handle = (await thumb.boundingBox())!;
expect(handle.height).toBeGreaterThanOrEqual(64);
expect(rail.y).toBeCloseTo(column.y, 0);
expect(rail.y + rail.height).toBeCloseTo(column.y + column.height, 0);
expect(rail.y + rail.height).toBeGreaterThan(viewport.y + viewport.height);
expect(handle.y + handle.height).toBeCloseTo(rail.y + rail.height, 0);
const x = handle.x + handle.width / 2;
await page.mouse.move(x, handle.y + handle.height / 2);
await page.mouse.down();
await page.mouse.move(x, rail.y + 1, { steps: 5 });
await expect.poll(() => stream.evaluate((el) => el.scrollTop)).toBeLessThan(2);
await page.mouse.move(x, rail.y + rail.height - 1, { steps: 5 });
await page.mouse.up();
await expect.poll(() => stream.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop)).toBeLessThan(2);
await page.mouse.wheel(0, -100);
await expect(page.getByRole("button", { name: "Jump to Latest" })).toBeVisible();
});
for (const selected of [false, true]) {
test(`keeps long-chat scroll geometry stable while jumping through history (selected: ${selected})`, async ({
page,
+10 -4
View File
@@ -228,6 +228,14 @@ mod tests {
(coalescing_sink(Arc::new(move |event| saved.lock().push(event)), tokio::runtime::Handle::current()), events)
}
/// Waits for the coalescing window to flush `n` events (a fixed sleep is too short on slow CI timers).
async fn wait_for_events(events: &Mutex<Vec<IdeEvent>>, n: usize) {
let deadline = std::time::Instant::now() + Duration::from_secs(5);
while events.lock().len() < n && std::time::Instant::now() < deadline {
tokio::time::sleep(Duration::from_millis(5)).await;
}
}
fn diagnostics(path: &str, source: &str, message: &str) -> IdeEvent {
IdeEvent::Diagnostics {
path: IpcPath::from(path),
@@ -316,9 +324,7 @@ mod tests {
sink.emit(diagnostics("/p/b.rs", "rust-analyzer", "other"));
assert!(events.lock().is_empty());
tokio::task::yield_now().await;
tokio::time::sleep(Duration::from_millis(30)).await;
tokio::task::yield_now().await;
wait_for_events(&events, 3).await;
{
let saved_events = events.lock();
@@ -381,7 +387,7 @@ mod tests {
}
assert_eq!(events.lock().len(), MAX_PENDING_DIAGNOSTICS);
tokio::time::sleep(Duration::from_millis(30)).await;
wait_for_events(&events, MAX_PENDING_DIAGNOSTICS + 1).await;
assert_eq!(events.lock().len(), MAX_PENDING_DIAGNOSTICS + 1);
}
+1 -1
View File
@@ -64,7 +64,7 @@ export function McpPicker({
testData,
}: McpPickerProps) {
const tx = useTx();
useMcpCatalogSync();
useMcpCatalogSync(!hideTrigger);
const catalogServers = useMcpCatalog((s) => s.servers);
const catalogSources = useMcpCatalog((s) => s.sources);
const projectIdeMcp = useProject((s) => s.settings?.mcpServer?.enabled ?? false);
+13 -7
View File
@@ -15,11 +15,13 @@
}
.conversation {
position: relative;
container-type: inline-size;
display: flex;
flex-direction: column;
min-width: 0;
min-height: 0;
padding-right: var(--space-3);
border-right: 1px solid var(--border);
}
@@ -38,7 +40,7 @@
.withChanges {
grid-template-columns: minmax(min(240px, 50%), 1fr) minmax(0, var(--agent-changes-width, 280px));
}
.fitWidth .stream > * {
.fitWidth .streamContent > * {
width: 100%;
}
.fitWidth .userMessage > .user {
@@ -204,12 +206,14 @@
padding: var(--space-3);
/* Room below the end that keeps the header of a section folded there in place (`Stream`). */
padding-bottom: calc(var(--space-3) + var(--stream-slack, 0px));
display: flex;
flex-direction: column;
font-size: var(--agent-fs-ui, var(--fs-ui));
}
/* Actual row heights keep WebKit's scrollbar and cross-message selections anchored. */
.stream > * {
.streamContent {
display: flex;
flex-direction: column;
}
/* Actual row heights keep the scrollbar and cross-message selections anchored. */
.streamContent > * {
flex: none;
min-width: 0;
width: min(100%, var(--session-content-width));
@@ -237,10 +241,10 @@
/* Keep turns distinct and the work within a turn close to its author. Not `* + *`: a
universal adjacent-sibling rule makes Chromium restyle whole sibling subtrees on every
DOM insertion anywhere in the window, which costs every editor scroll frame. */
.stream > :where(:not(:first-child)) {
.streamContent > :where(:not(:first-child)) {
margin-top: var(--space-4);
}
.stream > [data-process] + [data-process] {
.streamContent > [data-process] + [data-process] {
margin-top: var(--space-2);
}
.stream:focus {
@@ -408,6 +412,8 @@
.reply {
position: relative;
/* Keep WebKit's selection gap fill from extending across reply boundaries. */
transform: translateX(0);
}
.replyFooter {
position: absolute;
+1 -1
View File
@@ -176,7 +176,7 @@ export function SessionPicker({
</div>
)}
<div className={styles.list}>{children(query, controls)}</div>
<div className={styles.list}>{open && children(query, controls)}</div>
<div className={styles.footer}>
<span>
+1 -1
View File
@@ -67,7 +67,7 @@ export function SkillsPicker({
testData,
}: SkillsPickerProps) {
const tx = useTx();
useSkillsCatalogSync(backend);
useSkillsCatalogSync(!hideTrigger, backend);
const catalogSkills = useSkillsCatalog((s) => s.skills);
const skills = testData?.skills ?? catalogSkills;
const resolved = useMemo(() => resolveSessionSkills(skills, overrides ?? {}), [skills, overrides]);
+35 -22
View File
@@ -3,10 +3,13 @@ import { sendKeyAction } from "./Composer";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { EditorView } from "@codemirror/view";
import type { AgentCommand, AgentProvider } from "@/bindings";
import type { AgentCommand, AgentProvider, AgentSkillState } from "@/bindings";
const agentCommands = vi.fn();
const agentCreate = vi.fn();
const agentMcpList = vi.fn();
const agentMcpDiscoverSources = vi.fn();
const agentSkillsList = vi.fn();
const vcsBranches = vi.fn();
const vcsBranchInfo = vi.fn();
const clipboardImage = vi.fn();
@@ -20,6 +23,9 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
...real.commands,
agentCommands: (provider: string, task: string | null) => agentCommands(provider, task),
agentCreate: (request: unknown) => agentCreate(request),
agentMcpList: () => agentMcpList(),
agentMcpDiscoverSources: () => agentMcpDiscoverSources(),
agentSkillsList: () => agentSkillsList(),
agentRefreshModels: async (provider: string) => ({
status: "ok",
data: {
@@ -108,6 +114,9 @@ beforeEach(() => {
}),
);
agentCommands.mockReset();
for (const request of [agentMcpList, agentMcpDiscoverSources, agentSkillsList]) {
request.mockReset().mockResolvedValue({ status: "ok", data: [] });
}
clipboardImage.mockReset().mockResolvedValue({
status: "ok",
data: "data:image/png;base64,iVBORw0KGgo=",
@@ -174,6 +183,8 @@ describe("New Task composer commands", () => {
it("opens the per-session MCP picker when /mcp is completed in the composer", async () => {
agentCommands.mockResolvedValue({ status: "ok", data: [] });
render(<HomeEditor />);
expect(agentMcpList).not.toHaveBeenCalled();
expect(agentMcpDiscoverSources).not.toHaveBeenCalled();
const box = screen.getByRole("textbox");
typeIn(box, "/mc");
const list = await screen.findByRole("listbox", { name: "Commands" });
@@ -181,11 +192,14 @@ describe("New Task composer commands", () => {
fireEvent.keyDown(box, { key: "Enter" });
expect(textOf(box)).toBe("");
expect(await screen.findByText("Session MCP Servers")).toBeInTheDocument();
expect(agentMcpList).toHaveBeenCalledOnce();
expect(agentMcpDiscoverSources).toHaveBeenCalledOnce();
});
it("opens the per-session skills picker when /skills is completed in the composer", async () => {
agentCommands.mockResolvedValue({ status: "ok", data: [] });
render(<HomeEditor />);
expect(agentSkillsList).not.toHaveBeenCalled();
const box = screen.getByRole("textbox");
typeIn(box, "/sk");
const list = await screen.findByRole("listbox", { name: "Commands" });
@@ -193,6 +207,7 @@ describe("New Task composer commands", () => {
fireEvent.keyDown(box, { key: "Enter" });
expect(textOf(box)).toBe("");
expect(await screen.findByText("Session Skills")).toBeInTheDocument();
expect(agentSkillsList).toHaveBeenCalledOnce();
});
it("names the icon-only Start action and disables it while starting", async () => {
@@ -331,34 +346,32 @@ describe("New Task composer commands", () => {
expect(agentCreate.mock.calls[0]![0]).toMatchObject({ idle: true, prompt: { text: "!gi" } });
});
it("reflects per-session draft skillOverrides immediately in / completion", async () => {
it.each(["saved", "edited"])("reflects %s draft skill overrides in / completion", async (source) => {
agentCommands.mockResolvedValue({
status: "ok",
data: [command("triage", "Triage issues", "skill"), command("compact", "Compact")],
});
useSkillsCatalog.setState({
loaded: true,
skills: [
{
skill: {
name: "impeccable",
description: "Muted globally, enabled for this draft",
path: "/skills/impeccable",
source: "user",
valid: true,
warnings: [],
},
mode: "off",
origin: "user",
const skills: AgentSkillState[] = [
{
skill: {
name: "impeccable",
description: "Muted globally, enabled for this draft",
path: "/skills/impeccable",
source: "user",
valid: true,
warnings: [],
},
],
});
mode: "off",
origin: "user",
},
];
const overrides = { triage: "off", impeccable: "auto" } as const;
agentSkillsList.mockResolvedValue({ status: "ok", data: skills });
useSkillsCatalog.setState({ loaded: source === "edited", skills: source === "edited" ? skills : [] });
if (source === "saved") setDraftSkillOverrides(overrides);
render(<HomeEditor />);
await waitFor(() => expect(agentCommands).toHaveBeenCalled());
act(() => {
setDraftSkillOverrides({ triage: "off", impeccable: "auto" });
});
if (source === "edited") act(() => setDraftSkillOverrides(overrides));
const box = screen.getByRole("textbox");
typeIn(box, "/");
+6 -4
View File
@@ -239,13 +239,15 @@ export async function refreshMcpCatalog(): Promise<void> {
}));
}
export function useMcpCatalogSync(): void {
export function useMcpCatalogSync(eager: boolean): void {
const root = useProject((s) => s.project?.root);
useEffect(() => {
if (!isTauri()) return;
void refreshMcpCatalog();
const onFocus = () => void refreshMcpCatalog();
window.addEventListener("focus", onFocus);
if (eager) {
onFocus();
window.addEventListener("focus", onFocus);
}
if (!listenerAttached && typeof onIdeEvent === "function") {
listenerAttached = true;
onIdeEvent("settingsChanged", (e) => {
@@ -255,5 +257,5 @@ export function useMcpCatalogSync(): void {
});
}
return () => window.removeEventListener("focus", onFocus);
}, [root]);
}, [eager, root]);
}
+99 -71
View File
@@ -5,8 +5,10 @@ import {
Button,
copyMenuFor,
EmptyState,
hideNativeScrollbar,
Icon,
IconButton,
Scrollbar,
selectableText,
showContextMenu,
Spinner,
@@ -138,7 +140,7 @@ function useOffscreenRows(
mark();
}, 200);
});
resize.observe(el);
if (el.parentElement) resize.observe(el.parentElement);
return () => {
cancelAnimationFrame(frame);
window.clearTimeout(timer);
@@ -176,6 +178,7 @@ interface StreamProps {
/** Entries rendered at a time when a conversation opens at its end. */
const ENTRY_BATCH = 40;
const MIN_THUMB_SIZE = 64;
/** How long a conversation stays behind other tabs before it drops the entries painted above its tail. */
const HIDDEN_TRIM_MS = 30_000;
@@ -217,6 +220,8 @@ export function Stream({
drafts,
}: StreamProps) {
const ref = useRef<HTMLDivElement>(null);
const content = useRef<HTMLDivElement>(null);
const track = useRef<HTMLDivElement>(null);
// Hidden behind another tab, it has no layout to scroll; shown again, it follows the end again.
const visible = useEditorShown();
useSelectionBoundary(ref);
@@ -273,7 +278,7 @@ export function Stream({
const loadEarlier = useCallback(() => {
const el = ref.current;
if (!visible || !el || start <= 0 || dragging.current || anchor.current) return;
const first = el.firstElementChild;
const first = content.current?.firstElementChild;
if (!position.current.stick && first) anchor.current = { el: first, top: first.getBoundingClientRect().top };
startTransition(() => setShown((n) => n + ENTRY_BATCH));
}, [start, visible]);
@@ -288,8 +293,11 @@ export function Stream({
}, [loadEarlier]);
useEffect(() => {
const down = (event: PointerEvent) => {
if (!ref.current?.contains(event.target as Node)) return;
const target = event.target as Node;
if (!ref.current?.contains(target) && !(event.button === 0 && track.current?.contains(target))) return;
dragging.current = true;
markUserScroll();
scrollingUp.current = false;
if (loadTimer.current !== null) window.clearTimeout(loadTimer.current);
};
const up = () => {
@@ -308,7 +316,7 @@ export function Stream({
window.removeEventListener("blur", up);
if (loadTimer.current !== null) window.clearTimeout(loadTimer.current);
};
}, [loadWhenStill]);
}, [loadWhenStill, markUserScroll]);
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
@@ -336,7 +344,7 @@ export function Stream({
return () => window.clearTimeout(timer);
}, [visible]);
const { foldTurns, toolCalls, fitWindowWidth } = useAgentSettings();
useOffscreenRows(ref, visible, !finding, fitWindowWidth, fontZoom);
useOffscreenRows(content, visible, !finding, fitWindowWidth, fontZoom);
/**
* Blank space after the conversation that lets a section folded near the end keep its header
* in place. It is only ever what the view shows below the content: scrolling up or new rows
@@ -426,14 +434,16 @@ export function Stream({
*/
useEffect(() => {
const el = ref.current;
if (!el) return;
const scrollbar = track.current;
if (!el || !scrollbar) return;
let gesture: { owner: HTMLElement; at: number } | null = null;
const onWheel = (e: WheelEvent) => {
if (e.defaultPrevented || e.ctrlKey || e.metaKey) return;
if (e.shiftKey || Math.abs(e.deltaX) > Math.abs(e.deltaY)) return;
const overTrack = e.currentTarget === scrollbar;
const now = performance.now();
const latched = gesture && now - gesture.at < WHEEL_GESTURE_MS && gesture.owner.isConnected;
const owner = latched ? gesture!.owner : scrollOwner(e.target, el);
const owner = overTrack ? el : latched ? gesture!.owner : scrollOwner(e.target, el);
gesture = { owner, at: now };
if (owner !== el) {
const room = e.deltaY < 0 ? owner.scrollTop : owner.scrollHeight - owner.clientHeight - owner.scrollTop;
@@ -441,11 +451,25 @@ export function Stream({
return;
}
markUserScroll();
if (e.deltaY < 0) stopFollowing(e.target);
if (e.deltaY < 0) stopFollowing(overTrack ? el : e.target);
else if (e.deltaY > 0) scrollingUp.current = false;
if (overTrack) {
e.preventDefault();
const unit =
e.deltaMode === WheelEvent.DOM_DELTA_PAGE
? el.clientHeight
: e.deltaMode === WheelEvent.DOM_DELTA_LINE
? 16
: 1;
el.scrollTop += e.deltaY * unit;
}
};
el.addEventListener("wheel", onWheel, { passive: false });
return () => el.removeEventListener("wheel", onWheel);
scrollbar.addEventListener("wheel", onWheel, { passive: false });
return () => {
el.removeEventListener("wheel", onWheel);
scrollbar.removeEventListener("wheel", onWheel);
};
}, [markUserScroll, stopFollowing]);
/**
* The reader opened or closed a section: put its header back where it was, in the run or
@@ -551,6 +575,41 @@ export function Stream({
),
[task, lastIndex, busy, thinking, onDiagramDrawn, renderRow],
);
const agentName = providerName(task.provider);
// Switching tabs changes visibility without changing the conversation rows.
const renderedRows = useMemo(
() =>
rows.map((row) => {
const images = toolImages(row);
return (
<div
key={row.index}
className={styles.conversationRow}
data-message={
(row.kind === "entry" && (row.entry.type === "user" || row.entry.type === "agent")) || undefined
}
data-process={row.kind !== "entry" || row.entry.type !== "user" || undefined}
data-author={authorHeaders.has(row.index) || undefined}
>
{authorHeaders.has(row.index) && (
<div className={styles.agentAuthor}>
<div className={styles.role}>
<Icon name={providerIcon(task.provider)} size={13} />
<span>{agentName}</span>
</div>
</div>
)}
{renderConversationRow(row)}
{images.length > 0 && (
<div className={styles.toolImages}>
<ImageStrip images={images} />
</div>
)}
</div>
);
}),
[rows, authorHeaders, task.provider, agentName, renderConversationRow],
);
return (
<OpenFolds.Provider value={openFolds}>
<KeepFoldHeader.Provider value={keepFoldHeader}>
@@ -559,7 +618,7 @@ export function Stream({
<div
ref={ref}
// The conversation is read and copied like a document; focusable so ⌘F reaches it.
className={clsx(styles.stream, selectableText)}
className={clsx(styles.stream, selectableText, hideNativeScrollbar)}
tabIndex={-1}
onTouchStart={(e) => {
touchY.current = e.touches.length === 1 ? e.touches[0]!.clientY : null;
@@ -584,10 +643,6 @@ export function Stream({
)
scrollingUp.current = false;
}}
onPointerDown={() => {
markUserScroll();
scrollingUp.current = false;
}}
onScroll={(e) => {
const el = e.currentTarget;
trimSlack();
@@ -630,66 +685,39 @@ export function Stream({
showContextMenu(e, items);
}}
>
{loadError && (
<div role="alert">
<EmptyState
title={tx`Couldn't load the conversation: ${loadError}`}
actions={
<Button
onClick={() =>
void executeAction("agents.retryConversation", {
task: task.id,
subagent: subagent?.id ?? null,
})
}
>
Retry
</Button>
}
/>
</div>
)}
{entries === null ? (
!loadError && <Spinner />
) : entries.length === 0 && !busy && !loadError ? (
<EmptyState title="No conversation history" />
) : (
<RowRenderer.Provider value={renderConversationRow}>
{rows.map((row) => {
const images = toolImages(row);
return (
<div
key={row.index}
className={styles.conversationRow}
data-message={
(row.kind === "entry" && (row.entry.type === "user" || row.entry.type === "agent")) || undefined
}
data-process={row.kind !== "entry" || row.entry.type !== "user" || undefined}
data-author={authorHeaders.has(row.index) || undefined}
>
{authorHeaders.has(row.index) && (
<div className={styles.agentAuthor}>
<div className={styles.role}>
<Icon name={providerIcon(task.provider)} size={13} />
<span>{providerName(task.provider)}</span>
</div>
</div>
)}
{renderConversationRow(row)}
{images.length > 0 && (
<div className={styles.toolImages}>
<ImageStrip images={images} />
</div>
)}
</div>
);
})}
</RowRenderer.Provider>
)}
<WorkingRow task={task} entries={entries} subagent={subagent} />
<div ref={content} className={styles.streamContent}>
{loadError && (
<div role="alert">
<EmptyState
title={tx`Couldn't load the conversation: ${loadError}`}
actions={
<Button
onClick={() =>
void executeAction("agents.retryConversation", {
task: task.id,
subagent: subagent?.id ?? null,
})
}
>
Retry
</Button>
}
/>
</div>
)}
{entries === null ? (
!loadError && <Spinner />
) : entries.length === 0 && !busy && !loadError ? (
<EmptyState title="No conversation history" />
) : (
<RowRenderer.Provider value={renderConversationRow}>{renderedRows}</RowRenderer.Provider>
)}
<WorkingRow task={task} entries={entries} subagent={subagent} />
</div>
</div>
{away && !!entries?.length && <JumpToLatest onJump={jumpToLatest} />}
</div>
<Scrollbar target={ref} content={content} trackRef={track} fullHeight minThumbSize={MIN_THUMB_SIZE} />
</KeepFoldHeader.Provider>
</OpenFolds.Provider>
);
+10 -8
View File
@@ -218,6 +218,7 @@ const input = (id: string) => ({
data: { task: id },
});
const stream = () => document.querySelector<HTMLDivElement>(`.${styles.stream}`)!;
const streamContent = () => stream().querySelector<HTMLDivElement>(`.${styles.streamContent}`)!;
const tool = (id: string, overrides: Partial<Extract<AgentEntry, { type: "tool" }>> = {}): AgentEntry => ({
type: "tool",
id,
@@ -363,7 +364,7 @@ describe("conversation rows", () => {
render(<SessionEditor input={input("A")} />);
await screen.findByText("Done");
expect(stream().querySelectorAll(`.${styles.agentAuthor}`)).toHaveLength(1);
expect(stream().firstElementChild?.firstElementChild).toHaveClass(styles.agentAuthor!);
expect(streamContent().firstElementChild?.firstElementChild).toHaveClass(styles.agentAuthor!);
});
it.each<AgentEntry>([subagent, { type: "message", incoming: true, text: "Parent request" }])(
@@ -381,7 +382,7 @@ describe("conversation rows", () => {
await screen.findByText("After the work");
const authors = stream().querySelectorAll(`.${styles.agentAuthor}`);
expect(authors).toHaveLength(2);
expect(stream().children[1]?.querySelector(`.${styles.agentAuthor}`)).toBeNull();
expect(streamContent().children[1]?.querySelector(`.${styles.agentAuthor}`)).toBeNull();
expect(authors[1]?.nextElementSibling).toHaveClass(styles.processRun!);
expect(authors[1]?.parentElement?.nextElementSibling?.firstElementChild).toHaveClass(styles.agentMessage!);
},
@@ -548,7 +549,7 @@ describe("turn folding", () => {
// What the agent is doing ends the conversation, below its latest output.
const working = stream().querySelector(`.${styles.working}`);
expect(working).toHaveRole("status");
expect(stream().lastElementChild).toBe(working);
expect(streamContent().lastElementChild).toBe(working);
});
});
@@ -1144,18 +1145,19 @@ describe("scrolling", () => {
);
el.scrollTop = 20;
fireEvent.scroll(el);
const count = el.children.length;
const first = el.firstElementChild!;
const content = streamContent();
const count = content.children.length;
const first = content.firstElementChild!;
const top = vi.spyOn(first, "getBoundingClientRect");
top.mockReturnValue({ top: 100 } as DOMRect);
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 180));
});
expect(el.children.length).toBe(count);
expect(content.children.length).toBe(count);
// Its old top is measured at release, then shifts down when rows are inserted.
top.mockReturnValueOnce({ top: 100 } as DOMRect).mockReturnValue({ top: 500 } as DOMRect);
fireEvent.pointerUp(window);
await waitFor(() => expect(el.children.length).toBeGreaterThan(count));
await waitFor(() => expect(content.children.length).toBeGreaterThan(count));
expect(el.scrollTop).toBe(420);
view.unmount();
});
@@ -2006,7 +2008,7 @@ describe("session state across tasks and hosts", () => {
render(<SessionEditor input={input("A")} />);
expect(screen.getByText("Reply 149")).toBeInTheDocument();
expect(await screen.findByText("Reply 0")).toBeInTheDocument();
expect(stream().children).toHaveLength(150);
expect(streamContent().children).toHaveLength(150);
});
it("returns to the task conversation when the docked task changes after opening a subagent", async () => {
+6 -4
View File
@@ -153,13 +153,15 @@ export async function refreshSkillsCatalog(backend: SkillsBackend = defaultSkill
if (skills) useSkillsCatalog.setState({ skills, loaded: true });
}
export function useSkillsCatalogSync(backend: SkillsBackend = defaultSkillsBackend): void {
export function useSkillsCatalogSync(eager: boolean, backend: SkillsBackend = defaultSkillsBackend): void {
const root = useProject((s) => s.project?.root);
useEffect(() => {
if (!isTauri()) return;
void refreshSkillsCatalog(backend);
const onFocus = () => void refreshSkillsCatalog(backend);
window.addEventListener("focus", onFocus);
if (eager) {
onFocus();
window.addEventListener("focus", onFocus);
}
if (!listenerAttached && typeof onIdeEvent === "function") {
listenerAttached = true;
onIdeEvent("settingsChanged", (e) => {
@@ -169,5 +171,5 @@ export function useSkillsCatalogSync(backend: SkillsBackend = defaultSkillsBacke
});
}
return () => window.removeEventListener("focus", onFocus);
}, [root, backend]);
}, [eager, root, backend]);
}
+3 -1
View File
@@ -27,7 +27,7 @@ import { auxiliaryWindow, windowLabel } from "@/platform/auxWindow";
import { routeToWindow, taskWindowDraft, taskWindowFocused, updateTaskWindowDraft } from "./taskWindowRouting";
import { clearAgentTaskFontZoom, resetAllAgentFontZoom } from "./fontZoom";
import { clearDismissedAssets } from "./sessionAssetsModel";
import { useSkillsCatalog } from "./skillsModel";
import { useSkillsCatalog, useSkillsCatalogSync } from "./skillsModel";
import { basename, useProject } from "@/platform/project";
import { projectLocation } from "@/platform/remote";
import { defaultTaskProject } from "./project";
@@ -1067,6 +1067,8 @@ export function useAgentCommands(
offered: readonly AgentCommand[],
): readonly AgentCommand[] {
const skillOverrides = useAgents((s) => (task ? s.tasks.get(task)?.skillOverrides : s.draft.skillOverrides));
// The server's draft commands omit skills that only this draft has enabled.
useSkillsCatalogSync(task === null && Object.values(skillOverrides ?? {}).some((mode) => mode !== "off"));
const catalogSkills = useSkillsCatalog((s) => s.skills);
const [found, setFound] = useState<{
for: unknown[];
+4
View File
@@ -6,6 +6,10 @@
width: 10px;
z-index: 1;
}
.fullHeight {
bottom: 0;
touch-action: none;
}
.thumb {
position: absolute;
left: 0;
+48 -20
View File
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useLayoutEffect, useRef, type RefObject } from "react";
import clsx from "clsx";
import { lockScrollbarCursor } from "./dragCursor";
import styles from "./Scrollbar.module.css";
@@ -14,18 +15,30 @@ export const hideNativeScrollbar = styles.hideNative;
* native one scrolls asynchronously in WebKit and shows blank rows until the
* page catches up.
*
* `contentHeight` re-measures when the scroller's content grows.
* Pass `content` to observe its size or `contentHeight` to re-measure on demand.
* `fullHeight` uses the height of the scrollbar's positioned parent.
*/
export function Scrollbar({
target,
content,
contentHeight,
fullHeight = false,
minThumbSize = MIN_THUMB,
trackRef,
}: {
target: RefObject<HTMLElement | null>;
content?: RefObject<HTMLElement | null>;
contentHeight?: number;
fullHeight?: boolean;
minThumbSize?: number;
trackRef?: RefObject<HTMLDivElement | null>;
}) {
const track = useRef<HTMLDivElement>(null);
const ownTrack = useRef<HTMLDivElement>(null);
const track = trackRef ?? ownTrack;
const thumb = useRef<HTMLDivElement>(null);
const drag = useRef<{ pointerId: number; y: number; top: number; unlock: () => void } | null>(null);
const drag = useRef<{ el: HTMLDivElement; pointerId: number; y: number; top: number; unlock: () => void } | null>(
null,
);
const geometry = useRef<Geometry | null>(null);
const endDrag = useCallback(() => {
const current = drag.current;
@@ -33,22 +46,23 @@ export function Scrollbar({
drag.current = null;
current.unlock();
delete thumb.current?.dataset.dragging;
const el = track.current;
if (el?.hasPointerCapture(current.pointerId)) el.releasePointerCapture(current.pointerId);
if (current.el.hasPointerCapture(current.pointerId)) current.el.releasePointerCapture(current.pointerId);
}, []);
useLayoutEffect(() => {
geometry.current = layout(target.current, track.current, thumb.current);
}, [target, contentHeight]);
geometry.current = layout(target.current, track.current, thumb.current, fullHeight, minThumbSize);
}, [target, track, fullHeight, minThumbSize, contentHeight]);
useEffect(() => {
const el = target.current;
if (!el) return;
const sync = () => {
geometry.current = layout(el, track.current, thumb.current);
geometry.current = layout(el, track.current, thumb.current, fullHeight, minThumbSize);
};
el.addEventListener("scroll", sync, { passive: true });
const observer = new ResizeObserver(sync);
observer.observe(el);
if (content?.current) observer.observe(content.current);
if (fullHeight && track.current?.parentElement) observer.observe(track.current.parentElement);
window.addEventListener("blur", endDrag);
return () => {
endDrag();
@@ -56,12 +70,12 @@ export function Scrollbar({
el.removeEventListener("scroll", sync);
observer.disconnect();
};
}, [target, endDrag]);
}, [target, track, content, fullHeight, minThumbSize, endDrag]);
return (
<div
ref={track}
className={styles.track}
className={clsx(styles.track, fullHeight && styles.fullHeight)}
aria-hidden
onPointerDown={(e) => {
const el = target.current;
@@ -75,7 +89,13 @@ export function Scrollbar({
return;
}
e.currentTarget.setPointerCapture(e.pointerId);
drag.current = { pointerId: e.pointerId, y: e.clientY, top: el.scrollTop, unlock: lockScrollbarCursor() };
drag.current = {
el: e.currentTarget,
pointerId: e.pointerId,
y: e.clientY,
top: el.scrollTop,
unlock: lockScrollbarCursor(),
};
thumb.current!.dataset.dragging = "";
}}
onPointerMove={(e) => {
@@ -96,22 +116,30 @@ export function Scrollbar({
type Geometry = { range: number; max: number };
/** Positions the track over `el` and the thumb at its scroll offset; null when nothing scrolls. */
function layout(el: HTMLElement | null, t: HTMLElement | null, th: HTMLElement | null): Geometry | null {
function layout(
el: HTMLElement | null,
t: HTMLElement | null,
th: HTMLElement | null,
fullHeight: boolean,
minThumbSize: number,
): Geometry | null {
if (!el || !t || !th) return null;
const height = el.clientHeight;
const max = el.scrollHeight - height;
const viewport = el.clientHeight;
const height = fullHeight ? (t.parentElement?.clientHeight ?? 0) : viewport;
const content = el.scrollHeight;
const max = content - viewport;
// WebKit can report scrollHeight a pixel over clientHeight after the scroller is resized to a
// fractional height (dragging a splitter), with nothing overflowing: that is no scroll range.
const scrolls = max > 1;
t.style.top = `${el.offsetTop}px`;
t.style.height = `${height}px`;
const scrolls = viewport > 0 && height > 1 && max > 1;
t.style.top = fullHeight ? "" : `${el.offsetTop}px`;
t.style.height = fullHeight ? "" : `${height}px`;
t.style.display = scrolls ? "" : "none";
if (!scrolls) return null;
const size = Math.max(MIN_THUMB, (height * height) / el.scrollHeight);
const size = Math.min(height - 1, Math.max(minThumbSize, (height * viewport) / content));
const range = height - size;
th.style.height = `${size}px`;
th.style.transform = `translateY(${(Math.min(max, el.scrollTop) / max) * range}px)`;
return range > 0 ? { range, max } : null;
th.style.transform = `translateY(${(Math.max(0, Math.min(max, el.scrollTop)) / max) * range}px)`;
return { range, max };
}
/**