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 da5f2bea68 fix(agents): extend the chat scrollbar to the composer 2026-11-24 15:28:50 +08:00
32 changed files with 264 additions and 583 deletions

No files matched your search

+3 -3
View File
@@ -306,7 +306,7 @@ jobs:
- run: pnpm vitest run src/platform/locales/textCatalog.test.ts
e2e:
name: E2E (${{ matrix.shard }}/4)
name: E2E (${{ matrix.shard }}/2)
needs: changes
if: needs.changes.outputs.e2e == 'true'
timeout-minutes: 30
@@ -314,7 +314,7 @@ jobs:
strategy:
fail-fast: false
matrix:
shard: [1, 2, 3, 4]
shard: [1, 2]
# Browsers and their system libraries are preinstalled; keep the tag in step with @playwright/test.
container: mcr.microsoft.com/playwright:v1.64.1-noble
steps:
@@ -324,7 +324,7 @@ jobs:
- uses: actions/setup-node@v5
with: { node-version: 22, cache: pnpm }
- run: pnpm install --frozen-lockfile
- run: pnpm e2e --shard=${{ matrix.shard }}/4
- run: pnpm e2e --shard=${{ matrix.shard }}/2
env:
HOME: /root
- uses: actions/upload-artifact@v6
+1 -2
View File
@@ -335,8 +335,7 @@ for (const placement of ["editor", "toolWindow"] as const) {
await seedTasks(page, placement);
const box = messageBox(page);
await box.fill(draft);
await page.getByRole("treeitem", { name: "src", exact: true }).click();
await expect(box).toBeVisible();
await page.getByRole("treeitem", { name: "README.md", exact: true }).click();
await expect(box).not.toBeFocused();
await page.keyboard.press("Meta+L");
await expect(box).toBeFocused();
+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,
+1 -8
View File
@@ -11,12 +11,7 @@ test("External Tools take $FilePath$ from the Project view selection, else the e
const projectPath = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectPath);
const tool = { id: "echo", name: "Echo File Path", program: "echo", arguments: "$FilePath$ $FileName$" };
useProject.setState({
settings: {
editor: { tabs: { previewTab: false } },
externalTools: [{ ...tool, openConsole: false, synchronizeAfter: false }],
},
});
useProject.setState({ settings: { externalTools: [{ ...tool, openConsole: false, synchronizeAfter: false }] } });
let id = 0;
window.__ipc.handlers.run_start = ({ config }) => {
id++;
@@ -45,12 +40,10 @@ test("External Tools take $FilePath$ from the Project view selection, else the e
(await ipcCalls(page, "run_start")).map((c) => (c as { config: { args: string[] } }).config.args);
await page.getByRole("treeitem", { name: "build.gradle.kts", exact: true }).click();
await expect(page.getByRole("tab", { name: "README.md", exact: true })).toHaveAttribute("aria-selected", "true");
await runTool();
await expect.poll(startedArgs).toEqual([["/dev/acme-api/build.gradle.kts", "build.gradle.kts"]]);
await editor.click();
await expect(editor).toBeFocused();
await runTool();
await expect.poll(startedArgs).toEqual([
["/dev/acme-api/build.gradle.kts", "build.gradle.kts"],
+1 -1
View File
@@ -248,7 +248,7 @@ function CrumbNav({
const current = i === segments.length - 1;
const icon = s.nav?.kind === "dir" && !s.nav.root && !current ? undefined : s.icon;
return (
<Fragment key={`${i}:${s.title}`}>
<Fragment key={s.title}>
{i > 0 && <Icon name="chevron-right" size={12} className={styles.statusSep} />}
<BarButton
className={styles.crumbButton}
-15
View File
@@ -292,18 +292,3 @@ it("shows the revision and the file's folders for a file at a Git revision", ()
view.unmount();
useProject.setState({ project: null, settings: null });
});
it("elides the middle of a deep path without a duplicate React key", () => {
useProject.setState({
project: { root: "/p", name: "app", settings: {}, trusted: true, isGit: false },
settings: { appearance: { navigationBar: "top" } } as unknown as Settings,
});
useEditorStatus.setState({ status: { ...caret(0, 0), path: "/p/src/main/java/com/example/orders/Rule.java" } });
const error = vi.spyOn(console, "error").mockImplementation(() => {});
const view = render(<Breadcrumbs className="nav" />);
expect(screen.getByRole("navigation", { name: "Breadcrumbs" }).textContent).toBe("appsrc…exampleordersRule.java");
expect(error).not.toHaveBeenCalled();
error.mockRestore();
view.unmount();
useProject.setState({ project: null, settings: null });
});
-37
View File
@@ -91,43 +91,6 @@
font-size: var(--fs-small);
font-variant-numeric: tabular-nums;
}
/* Pin and Archive appear beside the age while the pointer is on the row. */
.rowActions {
display: none;
flex: none;
margin-left: auto;
margin-right: var(--space-2);
gap: var(--space-2);
}
.row:hover .rowActions,
.rowActions:focus-within {
display: flex;
}
.row:hover .age,
.row:has(.rowActions:focus-within) .age {
margin-left: 0;
}
.rowAction {
display: flex;
align-items: center;
justify-content: center;
width: 16px;
height: 16px;
padding: 0;
border: none;
background: none;
color: var(--fg-subtle);
--icon-color: currentColor;
cursor: pointer;
}
.rowAction:hover {
color: var(--fg-strong);
}
.rowAction:focus-visible {
outline: 2px solid var(--focus-ring);
outline-offset: 1px;
border-radius: var(--radius-small);
}
.ready {
color: var(--success);
}
+15 -43
View File
@@ -338,7 +338,7 @@ describe("Agents bulk actions", () => {
select("one");
select("three", { shiftKey: true });
context("two");
fireEvent.click(screen.getByRole("menuitem", { name: /^Archive \(1\)/ }));
fireEvent.click(screen.getByRole("menuitem", { name: "Archive (1)" }));
await waitFor(() => expect(archiveTask).toHaveBeenCalledExactlyOnceWith("two"));
});
@@ -388,39 +388,24 @@ describe("Agents task menu", () => {
expect(menu).not.toContainEqual(expect.objectContaining({ action: "agents.undockTask" }));
// A click opens the task: the menu doesn't repeat it.
expect(menu).not.toContainEqual(expect.objectContaining({ action: "agents.openTask" }));
expect(menu).toContainEqual(expect.objectContaining({ action: "agents.renameTask" }));
expect(menu[0]).toMatchObject({ action: "agents.renameTask" });
});
it("orders the single-task menu: pin, rename, unread; fork, group; archive, archive below, delete", () => {
const one = useAgents.getState().tasks.get("one")!;
const two = useAgents.getState().tasks.get("two")!;
const menu = taskMenu([{ ...one, capabilities: { fork: true } }], [two]);
const names = menu.map((item) =>
item.kind === "separator" ? "-" : "action" in item ? item.action : (item as { id?: string }).id,
it("offers Terminal for worktree or off-root tasks and hides it for local-checkout tasks at the project root", () => {
const localMenu = taskMenu([{ ...task("one", "ready", "local"), projectRoot: "/project", cwd: "/project" }]);
expect(localMenu).not.toContainEqual(expect.objectContaining({ action: "terminal.openAt" }));
const worktree = { ...task("two", "ready", "worktree"), cwd: "/worktrees/two" };
const worktreeMenu = taskMenu([worktree]);
expect(worktreeMenu).toContainEqual(
expect.objectContaining({ action: "terminal.openAt", label: "Terminal", arg: "/worktrees/two" }),
);
expect(names).toEqual([
"agents.pinTasks",
"agents.renameTask",
"agents.markTasksUnread",
"-",
"agents.forkTask",
"move-to-group",
"-",
"agents.archiveTasks",
"archive-below",
"agents.deleteTasks",
]);
expect(menu).not.toContainEqual(expect.objectContaining({ action: "terminal.openAt" }));
expect(menu).not.toContainEqual(expect.objectContaining({ action: "agents.moveToNewWindow" }));
});
it("marks tasks unread, then offers to mark them read", async () => {
await taskActions.find((action) => action.id === "agents.markTasksUnread")!.run({ ctx: {}, arg: ["one"] });
expect(useAgents.getState().unread.has("one")).toBe(true);
const menu = taskMenu([useAgents.getState().tasks.get("one")!]);
expect(menu).toContainEqual(expect.objectContaining({ action: "agents.markTasksRead", label: "Mark as Read" }));
await taskActions.find((action) => action.id === "agents.markTasksRead")!.run({ ctx: {}, arg: ["one"] });
expect(useAgents.getState().unread.has("one")).toBe(false);
const subfolder = { ...task("three", "ready", "local"), projectRoot: "/project", cwd: "/project/packages/api" };
const subfolderMenu = taskMenu([subfolder]);
expect(subfolderMenu).toContainEqual(
expect.objectContaining({ action: "terminal.openAt", label: "Terminal", arg: "/project/packages/api" }),
);
});
});
@@ -481,19 +466,6 @@ describe("Agents pinned and grouped tasks", () => {
expect(treeRows().some((text) => text.includes("Pinned"))).toBe(false);
});
it("pins from the row's hover button without selecting or opening the task", async () => {
setup();
select("one");
vi.mocked(openTask).mockClear();
const pin = within(row("two") as HTMLElement).getByRole("button", { name: "Pin" });
fireEvent.mouseDown(pin, { button: 0 });
fireEvent.click(pin);
fireEvent.doubleClick(pin);
await waitFor(() => expect(useAgents.getState().organize.pinned).toEqual(["two"]));
expect(selectedTasks()).toEqual(["one"]);
expect(openTask).not.toHaveBeenCalled();
});
it("filters every section by the search, archived ones included, and highlights the match", () => {
const tasks = useAgents.getState().tasks;
const rename = (id: string, title: string, status: AgentTask["status"] = "ready") =>
+3 -52
View File
@@ -41,8 +41,7 @@ import {
showImportSessions,
useAgents,
} from "./store";
import { canArchive, groupMenu, taskMenu } from "./taskActions";
import { setFocusedTaskList } from "./taskListFocus";
import { groupMenu, taskMenu } from "./taskActions";
import { matchTask } from "./taskSearch";
import { SessionEditor } from "./SessionEditor";
import { HomeEditor } from "./HomeEditor";
@@ -187,13 +186,7 @@ export function AgentsView() {
const task = sessionTask(maybeEditorService()?.activeInput?.());
return new Set(task ? [task] : []);
});
const selectedRef = useRef(selected);
useEffect(() => {
selectedRef.current = selected;
}, [selected]);
useEffect(() => () => setFocusedTaskList(null), []);
const organize = useAgents((s) => s.organize);
const pinned = useMemo(() => new Set(organize.pinned), [organize.pinned]);
const [query, setQuery] = useState("");
const treeRef = useRef<TreeHandle>(null);
// Follow the active session tab.
@@ -270,43 +263,8 @@ export function AgentsView() {
const dragTask = (e: ReactPointerEvent<HTMLSpanElement>, task: string) =>
startPointerDrag(e, e.currentTarget, { type: TASK_DRAG, payload: task });
// The tasks under `task` in its section, for Archive All Below.
const tasksBelow = (task: string): AgentTask[] => {
for (const root of roots) {
const members = root.kind === "group" ? root.group.tasks : root.kind === "task" ? [] : root.tasks;
const at = members.findIndex((t) => t.id === task);
if (at >= 0) return members.slice(at + 1);
}
return [];
};
const rowButton = (label: string, icon: "pin" | "archive", run: () => void) => (
<button
type="button"
className={styles.rowAction}
aria-label={tx(label)}
title={tx(label)}
// The row selects on mouse down and opens on double click; these buttons do neither.
onPointerDown={(e) => e.stopPropagation()}
onMouseDown={(e) => e.stopPropagation()}
onDoubleClick={(e) => e.stopPropagation()}
onClick={(e) => {
e.stopPropagation();
run();
}}
>
<Icon name={icon} size={14} />
</button>
);
const taskList = (
<div
className={styles.tasks}
onFocus={() => setFocusedTaskList(() => [...selectedRef.current])}
onBlur={(e) => {
if (!(e.relatedTarget instanceof Element && e.currentTarget.contains(e.relatedTarget)))
setFocusedTaskList(null);
}}
>
<div className={styles.tasks}>
{tasks.size > 0 && (
<SearchField
className={styles.taskSearch}
@@ -381,7 +339,7 @@ export function AgentsView() {
const task = tasks.get(id);
return task ? [task] : [];
});
showContextMenu(e, taskMenu(selection, selection.length === 1 ? tasksBelow(n.task.id) : []));
showContextMenu(e, taskMenu(selection));
}}
renderNode={(n) => {
switch (n.kind) {
@@ -435,13 +393,6 @@ export function AgentsView() {
{n.task.isolation === "worktree" && (
<span className={styles.detail}>{branchLabel(n.task.branch)}</span>
)}
<span className={styles.rowActions}>
{pinned.has(n.task.id)
? rowButton("Unpin", "pin", () => pinTasks([n.task.id], false))
: rowButton("Pin", "pin", () => pinTasks([n.task.id], true))}
{canArchive(n.task) &&
rowButton("Archive", "archive", () => void executeAction("agents.archiveTasks", [n.task.id]))}
</span>
<span className={styles.age}>{age(n.task.updatedMs ?? 0)}</span>
</span>
);
-6
View File
@@ -470,7 +470,6 @@
border: 0;
border-radius: 50%;
background: var(--bg-popup);
box-shadow: 0 0 0 1px var(--border);
color: var(--fg);
cursor: pointer;
opacity: 0;
@@ -479,11 +478,6 @@
.removeImage:focus-visible {
opacity: 1;
}
/* Opaque on hover too: the icon button's own hover fill is translucent over the image. */
.image .removeImage:not(:disabled):hover {
background: color-mix(in srgb, var(--fg-strong) 8%, var(--bg-popup));
color: var(--fg-strong);
}
/* Attached files and the current-file suggestion: one height, like the chips in the text. */
.attachment,
+21 -33
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 {
@@ -265,10 +269,8 @@
color: var(--fg-muted);
cursor: pointer;
}
/* Over the stream's text: keep it opaque against the icon button's translucent hover fill. */
.streamArea .jumpToLatest:not(:disabled):hover {
.jumpToLatest:hover {
background: var(--bg-hover);
color: var(--fg-strong);
}
/* Your message with its actions, shown on hover. */
.message {
@@ -517,21 +519,12 @@
it doesn't leave light boxes the way an opaque near-white fill does. */
--md-code-bg: color-mix(in srgb, var(--fg) 7%, transparent);
}
/* Each text block paints its own selection: WebKit otherwise fills the gap under a block's
last selected line across the whole block, a stripe below the unselected start of the line.
Not inside SVG (Mermaid labels): WebKit draws transformed foreignObject content at the origin. */
.markdown :global(:is(p, li, h1, h2, h3, h4, h5, h6):not(foreignObject *)) {
transform: translateX(0);
}
.markdown :global(code) {
font-family: var(--font-mono);
font-size: var(--agent-fs-small, var(--fs-small));
padding: 0 2px;
border-radius: 3px;
background: var(--md-code-bg);
/* Side insets as shadows, not padding: a selection leaves inline padding unpainted. */
box-shadow:
-2px 0 0 var(--md-code-bg),
2px 0 0 var(--md-code-bg);
}
.markdown :global(pre) {
margin: 0 0 8px;
@@ -542,8 +535,8 @@
}
.markdown :global(pre code) {
display: block;
padding: 0;
background: none;
box-shadow: none;
}
.codeBlock {
position: relative;
@@ -1214,13 +1207,14 @@
border: 1px solid var(--border);
border-radius: var(--radius-small);
}
/* Images a tool read (screenshots, crops): one row height whatever their size; a click shows the whole image. */
.toolImages,
.toolImages .imageItem,
.toolImages .imageButton {
max-width: 100%;
}
.toolImages .image {
width: auto;
height: 96px;
max-width: 200px;
object-fit: cover;
object-position: top left;
max-width: min(100%, 640px);
max-height: 320px;
}
.removeImage {
position: absolute;
@@ -1234,15 +1228,9 @@
border: 0;
border-radius: 50%;
background: var(--bg-popup);
box-shadow: 0 0 0 1px var(--border);
color: var(--fg);
cursor: pointer;
}
/* Opaque on hover too: the icon button's own hover fill is translucent over the image. */
.imageItem .removeImage:not(:disabled):hover {
background: color-mix(in srgb, var(--fg-strong) 8%, var(--bg-popup));
color: var(--fg-strong);
}
.attachments {
display: flex;
+64 -55
View File
@@ -5,8 +5,10 @@ import {
Button,
copyMenuFor,
EmptyState,
hideNativeScrollbar,
Icon,
IconButton,
Scrollbar,
selectableText,
showContextMenu,
Spinner,
@@ -27,7 +29,6 @@ import {
type RefObject,
} from "react";
import { useAgentSettings } from "../agentSettings";
import { clampSelectionToRow } from "./clampSelection";
import { ImageStrip } from "../ImageStrip";
import {
entriesKey,
@@ -139,7 +140,7 @@ function useOffscreenRows(
mark();
}, 200);
});
resize.observe(el);
if (el.parentElement) resize.observe(el.parentElement);
return () => {
cancelAnimationFrame(frame);
window.clearTimeout(timer);
@@ -177,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;
@@ -205,12 +207,6 @@ function scrollsUpInside(target: EventTarget | null, root: HTMLElement): boolean
/** A wheel gesture's events arrive closer together than this; a pause starts a new one. */
const WHEEL_GESTURE_MS = 150;
/** Keeps a double- or triple-click selection within the message it was made in. */
function clampMultiClick(target: EventTarget) {
const row = target instanceof Element ? target.closest(`.${styles.conversationRow}`) : null;
if (row) clampSelectionToRow(document.getSelection(), row);
}
export function Stream({
loadError,
task,
@@ -224,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);
@@ -280,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]);
@@ -295,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 = () => {
@@ -315,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
@@ -343,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
@@ -433,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;
@@ -448,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
@@ -601,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;
@@ -626,17 +643,6 @@ export function Stream({
)
scrollingUp.current = false;
}}
onPointerDown={() => {
markUserScroll();
scrollingUp.current = false;
}}
onMouseDown={(e) => {
// WebKit makes a double- or triple-click selection after this handler.
if (e.detail >= 2) setTimeout(() => clampMultiClick(e.target));
}}
onMouseUp={(e) => {
if (e.detail >= 2) clampMultiClick(e.target);
}}
onScroll={(e) => {
const el = e.currentTarget;
trimSlack();
@@ -679,36 +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}>{renderedRows}</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>
);
@@ -1,46 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { clampSelectionToRow } from "./clampSelection";
function conversation() {
document.body.innerHTML = `
<div id="reply"><p>First paragraph.</p><p id="last">Last paragraph.</p>
<div style="user-select: none">Nov 11 05:58 PM</div></div>
<div id="user"><span>Next message</span></div>`;
const text = (id: string) => document.getElementById(id)!.firstChild as Text;
return {
reply: document.getElementById("reply")!,
last: text("last"),
next: document.querySelector("#user span")!.firstChild as Text,
};
}
afterEach(() => {
document.getSelection()?.removeAllRanges();
document.body.innerHTML = "";
});
describe("clampSelectionToRow", () => {
it("ends a selection that ran into the next message at the row's last selectable text", () => {
const { reply, last, next } = conversation();
const selection = document.getSelection()!;
selection.setBaseAndExtent(last, 0, next, 4);
clampSelectionToRow(selection, reply);
expect(selection.toString()).toBe("Last paragraph.");
});
it("leaves a selection inside the row alone", () => {
const { reply, last } = conversation();
const selection = document.getSelection()!;
selection.setBaseAndExtent(last, 0, last, 4);
clampSelectionToRow(selection, reply);
expect(selection.toString()).toBe("Last");
});
it("collapses a selection made entirely outside the row", () => {
const { reply, next } = conversation();
const selection = document.getSelection()!;
selection.setBaseAndExtent(next, 0, next, 4);
clampSelectionToRow(selection, reply);
expect(selection.isCollapsed).toBe(true);
});
});
@@ -1,39 +0,0 @@
/**
* Keeps a double- or triple-click selection inside the conversation row it was made in. WebKit
* extends a word or paragraph at the end of a message past its unselectable footer, into the next
* message.
*/
export function clampSelectionToRow(selection: Selection | null, row: Element) {
if (!selection?.rangeCount) return;
const range = selection.getRangeAt(0);
const startInside = row.contains(range.startContainer);
const endInside = row.contains(range.endContainer);
if (startInside && endInside) return;
const texts = selectableTexts(row);
const first = texts[0];
const last = texts.at(-1);
if (!first || !last) return;
if (!startInside && !endInside) {
// The whole selection went past the row: none of the row's text is in it.
selection.collapse(last, last.length);
return;
}
const [startNode, startOffset] = startInside ? [range.startContainer, range.startOffset] : [first, 0];
const [endNode, endOffset] = endInside ? [range.endContainer, range.endOffset] : [last, last.length];
const backward = selection.anchorNode === range.endContainer && selection.anchorOffset === range.endOffset;
if (backward) selection.setBaseAndExtent(endNode, endOffset, startNode, startOffset);
else selection.setBaseAndExtent(startNode, startOffset, endNode, endOffset);
}
function selectableTexts(row: Element): Text[] {
const texts: Text[] = [];
const walker = row.ownerDocument.createTreeWalker(row, NodeFilter.SHOW_TEXT);
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
const parent = node.parentElement;
if (!node.nodeValue?.trim() || !parent) continue;
const style = getComputedStyle(parent);
if (style.userSelect === "none" || style.webkitUserSelect === "none") continue;
texts.push(node as Text);
}
return texts;
}
+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 () => {
-5
View File
@@ -369,11 +369,6 @@ function setUnread(task: string, value: boolean) {
useAgents.setState({ unread });
}
/** Marks tasks read or unread from the list's menu. */
export function setTasksUnread(tasks: readonly string[], value: boolean) {
for (const task of tasks) setUnread(task, value);
}
function markUnread(task: string) {
const current = useAgents.getState().tasks.get(task);
if (current && current.status !== "archived" && !viewing(task) && !quietTasks.has(task)) setUnread(task, true);
+50 -102
View File
@@ -1,10 +1,12 @@
import type { AgentTask } from "@/bindings";
import { executeActionFrom, type Action } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import type { Action } from "@/platform/actions";
import { t, tx } from "@/platform/i18n";
import { auxiliaryWindow } from "@/platform/auxWindow";
import { useProject } from "@/platform/project";
import type { MenuItem } from "@/ui";
import { confirm, showError, confirmChecked } from "@/workbench/messages";
import { promptInput } from "@/workbench/inputDialogs";
import { isBusy } from "./model";
import { hasTaskTerminal, isBusy } from "./model";
import { groupNameError, type OrganizeGroup } from "./organize";
import {
archiveTask,
@@ -23,12 +25,10 @@ import {
openTaskInEditorLocation,
renameTask,
setSessionLocation,
setTasksUnread,
showImportSessions,
undockTask,
useAgents,
} from "./store";
import { focusedTaskListSelection } from "./taskListFocus";
/** The Agents tool window's options menu: where conversations open, a new list group, importing sessions. */
export function useAgentsHeaderMenu(): MenuItem[] {
@@ -43,11 +43,10 @@ export function useAgentsHeaderMenu(): MenuItem[] {
];
}
export const canArchive = (task: AgentTask) => !isBusy(task.status) && task.status !== "archived";
const canArchive = (task: AgentTask) => !isBusy(task.status) && task.status !== "archived";
const canFork = (task: AgentTask) => canArchive(task) && !!task.capabilities?.fork;
function resolveTasks(arg: unknown): AgentTask[] {
if (arg == null) arg = focusedTaskListSelection();
if (!Array.isArray(arg)) return [];
return [...new Set(arg)].flatMap((id: unknown) => {
const task = typeof id === "string" ? useAgents.getState().tasks.get(id) : undefined;
@@ -134,9 +133,10 @@ async function confirmRemoveGroup(group: string) {
deleteTaskGroup(group);
}
/** Pins and unpins of the selected tasks. */
function pinMenu(tasks: AgentTask[]): MenuItem[] {
const isPinned = new Set(useAgents.getState().organize.pinned);
/** Pins and unpins of the selected tasks, then where they go. */
function arrangeMenu(tasks: AgentTask[], ids: string[]): MenuItem[] {
const { groups, groupOf, pinned } = useAgents.getState().organize;
const isPinned = new Set(pinned);
const toPin = tasks.filter((t) => !isPinned.has(t.id));
const toUnpin = tasks.filter((t) => isPinned.has(t.id));
return [
@@ -162,40 +162,20 @@ function pinMenu(tasks: AgentTask[]): MenuItem[] {
},
] satisfies MenuItem[])
: []),
];
}
/** Marks the tasks unread, or read when they all are unread already. */
function unreadMenu(ids: string[]): MenuItem[] {
const unread = useAgents.getState().unread;
const allUnread = ids.every((id) => unread.has(id));
return [
{
kind: "action",
action: allUnread ? "agents.markTasksRead" : "agents.markTasksUnread",
label: allUnread ? "Mark as Read" : "Mark as Unread",
icon: "",
arg: ids,
kind: "item",
id: "move-to-group",
label: "Group",
icon: "folder",
submenu: groupSubmenu(
ids,
groups,
ids.map((id) => groupOf[id]),
),
},
];
}
/** Where the selected tasks go. */
function groupMenuItem(ids: string[]): MenuItem {
const { groups, groupOf } = useAgents.getState().organize;
return {
kind: "item",
id: "move-to-group",
label: "Group",
icon: "folder",
submenu: groupSubmenu(
ids,
groups,
ids.map((id) => groupOf[id]),
),
};
}
/** The groups to move the tasks into; the one they all belong to is checked. */
function groupSubmenu(ids: string[], groups: OrganizeGroup[], current: Array<string | undefined>): MenuItem[] {
return [
@@ -333,8 +313,6 @@ export const taskActions: Action[] = [
title: "Archive Agent Tasks",
category: "Agents",
hidden: true,
// Without an argument the shortcut archives the task list's selection.
keyWhen: "agentTaskListFocus",
run: ({ arg }) =>
runTasks(resolveTasks(arg).filter(canArchive), (task) => archiveTask(task.id), tx("Cannot archive agent tasks")),
},
@@ -379,28 +357,6 @@ export const taskActions: Action[] = [
false,
),
},
{
id: "agents.markTasksUnread",
title: "Mark Agent Tasks as Unread",
category: "Agents",
hidden: true,
run: ({ arg }) =>
setTasksUnread(
resolveTasks(arg).map((task) => task.id),
true,
),
},
{
id: "agents.markTasksRead",
title: "Mark Agent Tasks as Read",
category: "Agents",
hidden: true,
run: ({ arg }) =>
setTasksUnread(
resolveTasks(arg).map((task) => task.id),
false,
),
},
{
id: "agents.newTaskGroup",
title: "New Agent Task Group",
@@ -429,40 +385,49 @@ export const taskActions: Action[] = [
},
];
/**
* The task rows' menu. `below` lists the tasks under a single selected one in its section,
* for Archive All Below.
*/
export function taskMenu(tasks: AgentTask[], below: AgentTask[] = []): MenuItem[] {
export function taskMenu(tasks: AgentTask[]): MenuItem[] {
if (!tasks.length) return [];
const ids = tasks.map((task) => task.id);
const task = tasks[0]!;
const projectRoot = task.projectRoot ?? useProject.getState().project?.root ?? null;
const multiple = tasks.length > 1;
const archived = tasks.filter((task) => task.status === "archived").length;
const archivable = tasks.filter(canArchive).length;
const archivableBelow = multiple ? [] : below.filter(canArchive);
return [
...pinMenu(tasks),
...(!multiple
? ([
{ kind: "action", action: "agents.renameTask", label: "Rename…", icon: "edit", arg: task.id },
...(!auxiliaryWindow()
? ([
{
kind: "action",
action: "agents.moveToNewWindow",
label: t("app.window.askNew"),
arg: task.id,
},
] satisfies MenuItem[])
: []),
...(hasTaskTerminal(task, projectRoot)
? ([
{ kind: "action", action: "terminal.openAt", label: "Terminal", icon: "terminal", arg: task.cwd },
] satisfies MenuItem[])
: []),
...(task.capabilities?.fork && task.status !== "archived"
? ([
{
kind: "action",
action: "agents.forkTask",
label: "Fork",
icon: "branch",
arg: task.id,
disabled: !canFork(task),
},
] satisfies MenuItem[])
: []),
{ kind: "separator" },
] satisfies MenuItem[])
: []),
...unreadMenu(ids),
{ kind: "separator" },
...(!multiple && task.capabilities?.fork && task.status !== "archived"
? ([
{
kind: "action",
action: "agents.forkTask",
label: "Fork",
icon: "branch",
arg: task.id,
disabled: !canFork(task),
},
] satisfies MenuItem[])
: []),
groupMenuItem(ids),
...arrangeMenu(tasks, ids),
{ kind: "separator" },
...(archived
? ([
@@ -478,26 +443,9 @@ export function taskMenu(tasks: AgentTask[], below: AgentTask[] = []): MenuItem[
kind: "action",
action: "agents.archiveTasks",
label: multiple ? tx`Archive (${archivable})` : "Archive",
icon: "archive",
arg: ids,
disabled: !archivable,
},
...(archivableBelow.length
? ([
{
kind: "item",
id: "archive-below",
label: "Archive All Below",
icon: "archive",
run: () =>
void executeActionFrom(
"menu",
"agents.archiveTasks",
archivableBelow.map((t) => t.id),
),
},
] satisfies MenuItem[])
: []),
{
kind: "action",
action: "agents.deleteTasks",
-11
View File
@@ -1,11 +0,0 @@
/** The Agents task list holding focus, so its shortcuts act on the selected tasks. */
import { setContext } from "@/platform/context";
let selection: (() => string[]) | null = null;
export function setFocusedTaskList(get: (() => string[]) | null) {
selection = get;
setContext("agentTaskListFocus", !!get);
}
export const focusedTaskListSelection = (): string[] => selection?.() ?? [];
@@ -26,10 +26,6 @@ interface ClassSpec {
name: string;
line: number;
col?: number;
/** The line the *index* saw (defaults to `line`): an unsaved edit has moved the class. */
indexedLine?: number;
/** Typed since the graph was indexed: the graph lacks it. */
unindexed?: boolean;
/** The bases the *index* saw (defaults to `bases`). */
indexedBases?: string[];
bases: string[];
@@ -107,14 +103,7 @@ class Fixture {
bases: spec.bases,
methods,
});
if (!spec.unindexed)
this.graph.push({
path,
line: spec.indexedLine ?? spec.line,
col,
name: spec.name,
bases: spec.indexedBases ?? spec.bases,
});
this.graph.push({ path, line: spec.line, col, name: spec.name, bases: spec.indexedBases ?? spec.bases });
this.outlines.set(path, [...(this.outlines.get(path) ?? []), classItem(spec, col, methods)]);
}
this.facts.set(path, { classes: [...(this.facts.get(path)?.classes ?? []), ...classFacts], suppressions: [] });
@@ -368,30 +357,6 @@ it("skips a class whose header no longer matches the indexed graph", async () =>
expect(await project.run()).toEqual([]);
});
it("keeps checking classes an unsaved edit moved off their indexed lines", async () => {
// A comment typed above `One` moved it and `Two` down a line; the graph still has the saved lines.
const project = new Fixture("/p/a.py").add("/p/a.py", [
{ name: "Base", line: 2, bases: ["ABC"], methods: [{ name: "report", line: 4, abstract: true }] },
{ name: "One", line: 7, indexedLine: 6, bases: ["Base"] },
{ name: "Two", line: 10, indexedLine: 9, bases: ["Base"] },
{ name: "Done", line: 13, indexedLine: 12, bases: ["Base"], methods: [{ name: "report", line: 14 }] },
]);
expect(codes(await project.run())).toEqual([
["builtin:python-abstract-method", "warning", 7],
["builtin:python-abstract-method", "warning", 10],
]);
});
it("pairs moved classes by position only once their names no longer line up", async () => {
// A class was added above `Two` since the graph was indexed: `Two` stays where it was indexed.
const project = new Fixture("/p/a.py").add("/p/a.py", [
{ name: "Base", line: 0, bases: [], methods: [{ name: "report", line: 1, abstract: true }] },
{ name: "New", line: 3, unindexed: true, bases: ["Base"] },
{ name: "Two", line: 6, bases: ["Base"] },
]);
expect(codes(await project.run())).toEqual([["builtin:python-abstract-method", "warning", 6]]);
});
it("runs only the producers that are enabled", async () => {
const project = new Fixture("/p/a.py").add("/p/a.py", [
{ name: "First", line: 0, bases: ["Second"] },
@@ -95,30 +95,7 @@ class ProjectView {
private outlines = new Map<string, Promise<readonly OutlineItem[]>>();
private ancestry = new Map<string, Promise<AncestryResolution>>();
/**
* The graph's declarations of this document paired with its live classes. An unsaved
* edit moves classes off the lines the graph indexed: while the classes still read the
* same names in the same order, they pair up in order; otherwise only by position.
*/
private readonly declOf = new Map<PythonClassFacts, ClassInheritance>();
private readonly liveOf = new Map<string, PythonClassFacts>();
constructor(private readonly deps: InheritanceInspectionDeps) {
const indexed = [...deps.index.byName.values()]
.flat()
.filter((c) => c.path === deps.path)
.sort(byPosition);
const live = [...deps.facts.classes].sort((a, b) => byPosition(a.selection.start, b.selection.start));
const inOrder = indexed.length === live.length && indexed.every((c, i) => c.name === live[i]!.name);
for (const [i, facts] of live.entries()) {
const decl = inOrder
? indexed[i]!
: indexed.find((c) => c.line === facts.selection.start.line && c.col === facts.selection.start.col);
if (!decl) continue;
this.declOf.set(facts, decl);
this.liveOf.set(declarationKey(decl), facts);
}
}
constructor(private readonly deps: InheritanceInspectionDeps) {}
/** The document's classes, in declaration order, skipping ones the graph does not match. */
async classes(): Promise<ClassView[]> {
@@ -149,16 +126,11 @@ class ProjectView {
}
async methodsOf(decl: ClassInheritance): Promise<PythonMethodFacts[]> {
if (decl.path === this.deps.path) return this.liveOf.get(declarationKey(decl))?.methods ?? [];
const facts = await this.factsOf(decl.path);
return facts?.classes.find((c) => sameDeclaration(c, decl))?.methods ?? [];
}
async membersOf(decl: ClassInheritance): Promise<ReadonlySet<string>> {
if (decl.path === this.deps.path) {
const live = this.liveOf.get(declarationKey(decl));
return memberNames(live ? classItem(this.deps.outline, live) : null);
}
const outline = await this.outlineOf(decl.path);
const item = outline.find(
(i) =>
@@ -168,7 +140,13 @@ class ProjectView {
}
private declarationOf(facts: PythonClassFacts): ClassInheritance | null {
return this.declOf.get(facts) ?? null;
const found = this.deps.index.byName.get(facts.name) ?? [];
return (
found.find(
(c) =>
c.path === this.deps.path && c.line === facts.selection.start.line && c.col === facts.selection.start.col,
) ?? null
);
}
private factsOf(path: string): Promise<PythonFacts | null> {
@@ -184,9 +162,6 @@ class ProjectView {
}
}
const byPosition = (a: { line: number; col: number }, b: { line: number; col: number }) =>
a.line - b.line || a.col - b.col;
function memo<T>(cache: Map<string, Promise<T>>, key: string, read: () => Promise<T>): Promise<T> {
let pending = cache.get(key);
if (!pending) {
-1
View File
@@ -144,7 +144,6 @@ export function createVenv(
* Hatch may install plugins first, so the caller cancels it when it no longer needs it.
*/
export function hatchEnvs(): Streamed<string[]> {
if (!isTauri()) return { promise: Promise.resolve([]), cancel: () => {} };
const request = nextRequestId();
return {
promise: call(commands.sdkPythonHatchEnvs(request)),
-1
View File
@@ -34,7 +34,6 @@ export const eclipseWindows: Record<string, string[]> = {
"debug.jumpToSource": ["F12", "Shift+Ctrl+E"],
"diff.jumpToSource": ["F12", "Shift+Ctrl+E"],
"find.popup.openResult": ["F12", "Shift+Ctrl+E"],
"agents.archiveTasks": [],
"editor.codeBlockEnd": ["Ctrl+]"],
"code.deleteLine": ["Ctrl+D"],
"code.duplicateLine": [],
-2
View File
@@ -406,8 +406,6 @@ export const intellijMacos: Record<string, string[]> = {
"agents.cycleEffort": ["Alt+T"],
"agents.showToolWindow": [],
"agents.sendToAgent": [],
// Agents task list (when it has focus)
"agents.archiveTasks": ["Meta+Shift+E"],
// Database tool window (when the tree has focus; `db.openConsole` anywhere).
"db.openConsole": ["Meta+Shift+L"],
"db.newDataSource": [],
-2
View File
@@ -404,8 +404,6 @@ export const intellijWindows: Record<string, string[]> = {
"agents.cycleEffort": ["Alt+T"],
"agents.showToolWindow": [],
"agents.sendToAgent": [],
// Agents task list (when it has focus)
"agents.archiveTasks": ["Ctrl+Shift+E"],
// Database tool window (when the tree has focus; `db.openConsole` anywhere).
"db.openConsole": ["Ctrl+Shift+Q"],
"db.newDataSource": [],
-2
View File
@@ -436,8 +436,6 @@ export const vscodeMacos: Record<string, string[]> = {
"agents.cycleEffort": ["Alt+T"],
"agents.showToolWindow": [],
"agents.sendToAgent": [],
// Agents task list (when it has focus)
"agents.archiveTasks": ["Meta+Shift+E"],
// Python Console: VS Code's Shift+Enter would shadow typing in Python files, so unbound.
"python.console.executeSelection": [],
// Search fields (find bar, Find in Files): last, so they win over editor keys while one is focused.
+1 -6
View File
@@ -3858,10 +3858,5 @@
"No stub or implementation found": "No stub or implementation found",
"Implementation of {name} in {file}": "Implementation of {name} in {file}",
"Stub of {name} in {file}": "Stub of {name} in {file}",
"This color can't be changed with the picker": "This color can't be changed with the picker",
"Mark as Read": "Mark as Read",
"Mark as Unread": "Mark as Unread",
"Archive All Below": "Archive All Below",
"Mark Agent Tasks as Unread": "Mark Agent Tasks as Unread",
"Mark Agent Tasks as Read": "Mark Agent Tasks as Read"
"This color can't be changed with the picker": "This color can't be changed with the picker"
}
+1 -6
View File
@@ -10088,10 +10088,5 @@
"No stub or implementation found": "未找到存根或实现",
"Implementation of {name} in {file}": "{file} 中 {name} 的实现",
"Stub of {name} in {file}": "{file} 中 {name} 的存根",
"This color can't be changed with the picker": "无法用颜色选择器修改此颜色",
"Mark as Read": "标记为已读",
"Mark as Unread": "标记为未读",
"Archive All Below": "归档下方全部",
"Mark Agent Tasks as Unread": "将 Agent 任务标记为未读",
"Mark Agent Tasks as Read": "将 Agent 任务标记为已读"
"This color can't be changed with the picker": "无法用颜色选择器修改此颜色"
}
+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 };
}
/**
-1
View File
@@ -332,7 +332,6 @@ const ICONS = {
"actual-size": "openidea/general/actualZoom",
chessboard: "openidea/general/chessboard",
eyedropper: "openidea/general/eyedropper",
archive: "openidea/general/archive",
minimize: "general/openInToolWindow",
"main-menu": "openidea/general/mainMenu",
"window-minimize": "openidea/general/windowMinimize",
-4
View File
@@ -1,4 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none">
<rect x="2" y="3" width="12" height="3" rx="1" stroke="#6C707E"/>
<path d="M3 6v6a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V6M6.5 8.5h3" stroke="#6C707E" stroke-linecap="round"/>
</svg>

Before

Width:  |  Height:  |  Size: 274 B