Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai bbfcdda0c1 fix(agents): title a task from the prompt's text outside code fences
A prompt that opened with a pasted fenced block (a log, a code sample)
was titled from the first line inside the block until the generated
title arrived. A line outside the fences now wins; a prompt that is one
fenced block is still titled from inside it.
2026-11-24 19:56:51 +08:00
l0ng-ai 77c531b9ca fix(python): keep inheritance inspections on classes an unsaved edit moved (#5629)
The inheritance inspections matched the open document's classes to the inheritance graph by exact position, and the graph is re-indexed only on save, so a line typed above a class hid the warnings of every class below until the file was saved. The document's classes now pair with the graph's in order while they read the same names, and by position otherwise; same-document methods and members come from the live document.
2026-11-24 19:55:22 +08:00
Deng Liu d411ace29b perf(vcs): cache unchanged ref queries (#5548)
Reuse the ref-decoration snapshot for log refs and cache branch lists, invalidated by ref storage, HEAD, repository config, shallow state and trust-mode changes.
2026-11-24 19:55:16 +08:00
l0ng-ai 4074d079b1 feat(agents): reorder the task menu and polish selection and images (#5621)
* feat(agents): reorder the task menu and polish selection and images

- Task menu: Pin, Rename, Mark as Unread/Read; Fork, Group; Archive (⇧⌘E
  in the task list), Archive All Below, Delete. Terminal and Open in New
  Window leave the menu. Hovering a task row shows Pin and Archive beside
  its age.
- Reply text: no stripe under the unselected start of a line when a
  selection runs on past it; inline code keeps its side insets inside the
  selection. A double or triple click no longer selects into the next
  message.
- Images: tool-read images show as same-height thumbnails; the remove
  button on attached images stays opaque on hover.

* fix(agents): keep Jump to Latest opaque on hover

* fix(agents): keep task row hover buttons from selecting or opening the task
2026-11-24 18:34:22 +08:00
l0ng-ai 2d0120f092 fix(editor): key navigation bar segments by position (#5616)
A path deeper than four folders collapses its middle into an ellipsis whose tooltip is the whole relative path, the same as the last folder's, so React warned about two children with the same key. Segments are now keyed by their position as well.
2026-11-24 17:53:35 +08:00
faysou df470f93c6 test(e2e): keep project focus checks from switching editor tabs (#5604)
With preview tabs enabled, selecting a file in the Project view also opens it, so the External Tools test disables preview tabs to keep the Project selection and the active editor on different files. The task-input shortcut test focuses a directory so the task editor stays visible.
2026-11-24 17:51:02 +08:00
faysou 764b6717e0 fix(python): skip Hatch discovery without a desktop bridge (#5608)
Opening Add Python Interpreter in a plain browser started a Hatch discovery request whose cancellation called the desktop command without a bridge, an unhandled rejection. Browser mode now returns an empty result with a no-op cancel.
2026-11-24 17:50:48 +08:00
l0ng-ai 7aa6adb0ef Revert "fix(agents): extend the chat scrollbar to the composer (#5583)"
This reverts commit c0f7ec93d3.
2026-11-24 17:22:50 +08:00
l0ng-ai 7ebdf04e2f ci: split E2E into four shards (#5591)
Two E2E shards of ~512 tests each hit the 30-minute job timeout; four shards keep each within it.
2026-11-24 16:13:51 +08:00
l0ng-ai c0f7ec93d3 fix(agents): extend the chat scrollbar to the composer (#5583) 2026-11-24 15:38:10 +08:00
32 змінених файлів з 705 додано та 117 видалено

No files matched your search

+3 -3
Переглянути файл
@@ -306,7 +306,7 @@ jobs:
- run: pnpm vitest run src/platform/locales/textCatalog.test.ts
e2e:
name: E2E (${{ matrix.shard }}/2)
name: E2E (${{ matrix.shard }}/4)
needs: changes
if: needs.changes.outputs.e2e == 'true'
timeout-minutes: 30
@@ -314,7 +314,7 @@ jobs:
strategy:
fail-fast: false
matrix:
shard: [1, 2]
shard: [1, 2, 3, 4]
# 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 }}/2
- run: pnpm e2e --shard=${{ matrix.shard }}/4
env:
HOME: /root
- uses: actions/upload-artifact@v6
+16 -3
Переглянути файл
@@ -4245,11 +4245,24 @@ fn file_uri(path: &Path) -> String {
out
}
/// The title of a task: the first line of the prompt that says something. A pasted Markdown
/// block opens with a code fence (```` ```text ````), which names no task.
/// The title of a task: the first line of the prompt that says something. Text inside a code
/// fence (```` ```text ````) is pasted material, so a line outside the fences wins; a prompt
/// that is all one pasted block still names its task from inside it.
fn title_of(prompt: &AgentPrompt) -> String {
let is_fence = |l: &str| l.starts_with("```") || l.starts_with("~~~");
let line = prompt.text.lines().map(str::trim).find(|l| !l.is_empty() && !is_fence(l));
let (mut outside, mut inside, mut fenced) = (None, None, false);
for l in prompt.text.lines().map(str::trim) {
if is_fence(l) {
fenced = !fenced;
} else if !l.is_empty() {
let slot = if fenced { &mut inside } else { &mut outside };
slot.get_or_insert(l);
if outside.is_some() {
break;
}
}
}
let line = outside.or(inside);
let line = match line {
Some(l) => l.to_owned(),
None => prompt.files.first().map(|f| file_name(&f.0)).unwrap_or_else(|| "Image".into()),
+3
Переглянути файл
@@ -1736,6 +1736,9 @@ fn prompts_become_acp_content_blocks() {
assert_eq!(title_of(&AgentPrompt { files: p.files.clone(), ..AgentPrompt::default() }), "my file.rs");
let pasted = AgentPrompt { text: "```text\n\n ## Fix the tab title\n```".into(), ..AgentPrompt::default() };
assert_eq!(title_of(&pasted), "## Fix the tab title");
let fenced_first =
AgentPrompt { text: "```txt\nlog line\n```\nWhy does this fail?".into(), ..AgentPrompt::default() };
assert_eq!(title_of(&fenced_first), "Why does this fail?");
assert!(clean(text(" ")).is_none());
}
+11 -5
Переглянути файл
@@ -1328,10 +1328,15 @@ impl Repo {
/// Reference names and peeled commit ids, including tags and detached HEAD.
pub fn log_refs(&self) -> IdeResult<std::collections::BTreeMap<String, String>> {
let repo = self.gix()?;
Ok(history::decorations(&repo)?
.into_iter()
.flat_map(|(id, names)| names.into_iter().map(move |name| (name, id.to_string())))
.collect())
let (decorations, _) = self.ref_decorations(&repo)?;
let mut refs = std::collections::BTreeMap::new();
for (id, names) in decorations.iter() {
let id = id.to_string();
for name in names {
refs.insert(name.clone(), id.clone());
}
}
Ok(refs)
}
pub fn log_users(&self) -> IdeResult<Vec<String>> {
let _scope = self.execution_scope();
@@ -1488,7 +1493,8 @@ impl Repo {
/// Local and remote branches; the current branch first, then most recent first.
pub fn branches(&self) -> IdeResult<Vec<Branch>> {
let _scope = self.execution_scope();
refs::branches(self)
let repo = self.gix()?;
self.cached_branches(&repo)
}
/// Stash entries, newest (`stash@{0}`) first.
pub fn stashes(&self) -> IdeResult<Vec<Stash>> {
+154 -6
Переглянути файл
@@ -4,9 +4,11 @@
//! even for a one-row page. A page now stats `HEAD`, `packed-refs` and the directories under
//! `refs/` instead: git replaces a loose ref by renaming a lock file over it, which changes
//! the modification time of the ref's directory, and rewrites `packed-refs` the same way.
//! Branch lists reuse the same snapshot because their ref walk and ahead/behind work are
//! otherwise repeated for every VCS view refresh.
use crate::Repo;
use crate::repo::absolute;
use crate::{Branch, Repo};
use gix::ObjectId;
use ide_core::IdeResult;
use std::collections::HashMap;
@@ -24,6 +26,7 @@ pub(crate) type Decorations = Arc<HashMap<ObjectId, Vec<String>>>;
#[derive(Default)]
pub(crate) struct RefDecorations {
snapshot: Option<Snapshot>,
branches: Option<BranchSnapshot>,
/// Changes when the decorations do, so cached views of them can be keyed by it.
generation: u64,
}
@@ -34,11 +37,37 @@ struct Snapshot {
reusable: bool,
}
struct BranchSnapshot {
branches: Vec<Branch>,
generation: u64,
/// The exact ref stamp also catches a checkout of another branch at the same commit.
references: Vec<(PathBuf, Stat)>,
trusted: bool,
configuration: Vec<(PathBuf, Stat)>,
reusable: bool,
}
fn stat(path: &Path) -> Stat {
let metadata = std::fs::metadata(path).ok()?;
Some((metadata.modified().ok()?, metadata.len()))
}
fn reusable(stamp: &[(PathBuf, Stat)], taken: SystemTime) -> bool {
stamp.iter().all(|(_, stat)| stat.is_none_or(|(modified, _)| modified + RACY_WINDOW <= taken))
}
fn configuration_stamp(git_dir: &Path, common_dir: &Path) -> Vec<(PathBuf, Stat)> {
[
common_dir.join("config"),
git_dir.join("config.worktree"),
common_dir.join("config.worktree"),
common_dir.join("shallow"),
]
.into_iter()
.map(|path| (path.clone(), stat(&path)))
.collect()
}
/// `HEAD`, `packed-refs` and every directory under `refs/`.
fn stamp(git_dir: &Path, common_dir: &Path) -> Vec<(PathBuf, Stat)> {
let mut paths = vec![git_dir.join("HEAD"), common_dir.join("packed-refs")];
@@ -64,7 +93,7 @@ impl RefDecorations {
let taken = SystemTime::now();
let stamp = stamp(git_dir, common_dir);
let map = crate::history::decorations(repo)?;
let reusable = stamp.iter().all(|(_, stat)| stat.is_none_or(|(modified, _)| modified + RACY_WINDOW <= taken));
let reusable = reusable(&stamp, taken);
let unchanged = self.snapshot.as_ref().is_some_and(|old| *old.map == map);
let map = match &self.snapshot {
Some(old) if unchanged => old.map.clone(),
@@ -76,6 +105,45 @@ impl RefDecorations {
self.snapshot = Some(Snapshot { map: map.clone(), stamp, reusable });
Ok((map, self.generation))
}
fn branches(
&mut self,
repo: &gix::Repository,
git_dir: &Path,
common_dir: &Path,
trusted: bool,
) -> IdeResult<Vec<Branch>> {
let (_, generation) = self.get(repo, git_dir, common_dir)?;
let references = self
.snapshot
.as_ref()
.ok_or_else(|| ide_core::IdeError::internal("reference cache did not populate a snapshot"))?
.stamp
.clone();
let taken = SystemTime::now();
let configuration = configuration_stamp(git_dir, common_dir);
if let Some(snapshot) = &self.branches
&& snapshot.reusable
&& snapshot.generation == generation
&& snapshot.references == references
&& snapshot.trusted == trusted
&& snapshot.configuration == configuration
{
return Ok(snapshot.branches.clone());
}
let branches = crate::refs::branches(repo)?;
let reusable =
self.snapshot.as_ref().is_some_and(|snapshot| snapshot.reusable) && reusable(&configuration, taken);
self.branches = Some(BranchSnapshot {
branches: branches.clone(),
generation,
references,
trusted,
configuration,
reusable,
});
Ok(branches)
}
}
impl Repo {
@@ -84,6 +152,17 @@ impl Repo {
let common_dir = absolute(repo.common_dir())?;
self.ref_decorations.lock().unwrap_or_else(|p| p.into_inner()).get(repo, &self.git_dir, &common_dir)
}
pub(crate) fn cached_branches(&self, repo: &gix::Repository) -> IdeResult<Vec<Branch>> {
let common_dir = absolute(repo.common_dir())?;
let trusted = self.execution_allowed.load(std::sync::atomic::Ordering::Acquire);
self.ref_decorations.lock().unwrap_or_else(|p| p.into_inner()).branches(
repo,
&self.git_dir,
&common_dir,
trusted,
)
}
}
#[cfg(test)]
@@ -112,11 +191,18 @@ mod tests {
git(dir, &["rev-parse", "HEAD"])
}
/// Sets the modification time of `HEAD`, `packed-refs` and every directory under `refs/`.
/// Sets the modification time of every metadata path used by the ref and branch caches.
fn set_ref_times(repo: &Repo, time: SystemTime) {
let git = repo.git_dir.clone();
let mut paths = vec![git.join("HEAD"), git.join("packed-refs")];
let mut pending = vec![git.join("refs")];
let [git, common] = repo.metadata_dirs().unwrap();
let mut paths = vec![
git.join("HEAD"),
common.join("packed-refs"),
common.join("config"),
git.join("config.worktree"),
common.join("config.worktree"),
common.join("shallow"),
];
let mut pending = vec![common.join("refs")];
while let Some(dir) = pending.pop() {
pending.extend(std::fs::read_dir(&dir).unwrap().flatten().filter(|e| e.path().is_dir()).map(|e| e.path()));
paths.push(dir);
@@ -175,6 +261,68 @@ mod tests {
assert_eq!(decorations_scans(), after_first, "a warm page listed the refs again");
}
#[test]
fn warm_log_refs_do_not_list_the_refs() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
commit(dir, "first");
for i in 0..20 {
git(dir, &["branch", &format!("b{i}")]);
}
let repo = Repo::discover(dir).unwrap().unwrap();
settle(&repo);
let after_first = decorations_scans();
for _ in 0..5 {
assert!(repo.log_refs().unwrap().contains_key("main"));
}
assert_eq!(decorations_scans(), after_first, "warm log refs listed the refs again");
}
#[test]
fn warm_branch_lists_reuse_the_ref_walk() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
let first = commit(dir, "first");
git(dir, &["remote", "add", "origin", "."]);
git(dir, &["update-ref", "refs/remotes/origin/main", &first]);
let repo = Repo::discover(dir).unwrap().unwrap();
repo.set_execution_allowed(true);
set_ref_times(&repo, SystemTime::now() - Duration::from_secs(3600));
let scans = crate::refs::branch_scans();
assert!(repo.branches().unwrap().iter().any(|branch| branch.name == "origin/main"));
let after_first = crate::refs::branch_scans();
assert!(after_first > scans);
for _ in 0..5 {
repo.branches().unwrap();
}
assert_eq!(crate::refs::branch_scans(), after_first, "warm branch list walked the refs again");
git(dir, &["branch", "side"]);
assert!(repo.branches().unwrap().iter().any(|branch| branch.name == "side"));
assert!(crate::refs::branch_scans() > after_first, "branch creation did not invalidate the cache");
git(dir, &["checkout", "-q", "side"]);
let at_side = repo.branches().unwrap();
assert!(at_side.iter().any(|branch| branch.name == "side" && branch.current));
assert!(!at_side.iter().any(|branch| branch.name == "main" && branch.current));
let scans = crate::refs::branch_scans();
git(dir, &["config", "branch.main.remote", "origin"]);
git(dir, &["config", "branch.main.merge", "refs/heads/main"]);
let main = repo.branches().unwrap().into_iter().find(|branch| branch.name == "main").unwrap();
assert_eq!(main.upstream.as_deref(), Some("origin/main"));
assert!(crate::refs::branch_scans() > scans, "config change did not invalidate the cache");
repo.set_execution_allowed(false);
let restricted = repo.branches().unwrap().into_iter().find(|branch| branch.name == "main").unwrap();
assert_eq!(restricted.upstream, None);
repo.set_execution_allowed(true);
let trusted = repo.branches().unwrap().into_iter().find(|branch| branch.name == "main").unwrap();
assert_eq!(trusted.upstream.as_deref(), Some("origin/main"));
}
#[test]
fn fresh_ref_timestamps_are_not_trusted() {
let tmp = tempfile::tempdir().unwrap();
+17 -8
Переглянути файл
@@ -137,8 +137,17 @@ fn commit_time_ms(repo: &gix::Repository, id: gix::ObjectId) -> f64 {
repo.find_commit(id).ok().and_then(|c| c.time().ok()).map(|t| t.seconds as f64 * 1000.0).unwrap_or(0.0)
}
pub(crate) fn branches(r: &Repo) -> IdeResult<Vec<Branch>> {
let repo = r.gix()?;
#[cfg(test)]
thread_local!(static BRANCH_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) });
#[cfg(test)]
pub(crate) fn branch_scans() -> usize {
BRANCH_SCANS.get()
}
pub(crate) fn branches(repo: &gix::Repository) -> IdeResult<Vec<Branch>> {
#[cfg(test)]
BRANCH_SCANS.set(BRANCH_SCANS.get() + 1);
let head_name = repo.head_name().map_err(gx)?;
let platform = repo.references().map_err(gx)?;
let remotes = repo.remote_names();
@@ -161,20 +170,20 @@ pub(crate) fn branches(r: &Repo) -> IdeResult<Vec<Branch>> {
ahead: 0,
behind: 0,
outgoing: None,
last_commit_ms: commit_time_ms(&repo, id),
last_commit_ms: commit_time_ms(repo, id),
commit: id.to_string(),
};
let mut counted_upstream = None;
if let Some((up, up_id)) = upstream_of(&repo, full.as_ref()) {
if let Some((up, up_id)) = upstream_of(repo, full.as_ref()) {
branch.upstream = Some(up);
branch.tracked_tip = configured_upstream(&repo, full.as_ref())
branch.tracked_tip = configured_upstream(repo, full.as_ref())
.map(|tracking| TrackedTip { tracking, commit: up_id.to_string() });
let (a, b) = ahead_behind(&repo, id, up_id)?;
let (a, b) = ahead_behind(repo, id, up_id)?;
branch.ahead = a;
branch.behind = b;
counted_upstream = Some((up_id, a));
}
branch.outgoing = crate::push_preview::outgoing_commits(&repo, &remotes, full.as_ref(), id, counted_upstream);
branch.outgoing = crate::push_preview::outgoing_commits(repo, &remotes, full.as_ref(), id, counted_upstream);
out.push(branch);
}
for reference in platform.remote_branches().map_err(gx)? {
@@ -194,7 +203,7 @@ pub(crate) fn branches(r: &Repo) -> IdeResult<Vec<Branch>> {
ahead: 0,
behind: 0,
outgoing: None,
last_commit_ms: commit_time_ms(&repo, id),
last_commit_ms: commit_time_ms(repo, id),
commit: id.to_string(),
});
}
+2 -1
Переглянути файл
@@ -335,7 +335,8 @@ 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: "README.md", exact: true }).click();
await page.getByRole("treeitem", { name: "src", exact: true }).click();
await expect(box).toBeVisible();
await expect(box).not.toBeFocused();
await page.keyboard.press("Meta+L");
await expect(box).toBeFocused();
+8 -1
Переглянути файл
@@ -11,7 +11,12 @@ 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: { externalTools: [{ ...tool, openConsole: false, synchronizeAfter: false }] } });
useProject.setState({
settings: {
editor: { tabs: { previewTab: false } },
externalTools: [{ ...tool, openConsole: false, synchronizeAfter: false }],
},
});
let id = 0;
window.__ipc.handlers.run_start = ({ config }) => {
id++;
@@ -40,10 +45,12 @@ 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
Переглянути файл
@@ -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={s.title}>
<Fragment key={`${i}:${s.title}`}>
{i > 0 && <Icon name="chevron-right" size={12} className={styles.statusSep} />}
<BarButton
className={styles.crumbButton}
+15
Переглянути файл
@@ -292,3 +292,18 @@ 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
Переглянути файл
@@ -91,6 +91,43 @@
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);
}
+43 -15
Переглянути файл
@@ -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,24 +388,39 @@ 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[0]).toMatchObject({ action: "agents.renameTask" });
expect(menu).toContainEqual(expect.objectContaining({ action: "agents.renameTask" }));
});
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" }),
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,
);
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" }));
});
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" }),
);
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);
});
});
@@ -466,6 +481,19 @@ 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") =>
+52 -3
Переглянути файл
@@ -41,7 +41,8 @@ import {
showImportSessions,
useAgents,
} from "./store";
import { groupMenu, taskMenu } from "./taskActions";
import { canArchive, groupMenu, taskMenu } from "./taskActions";
import { setFocusedTaskList } from "./taskListFocus";
import { matchTask } from "./taskSearch";
import { SessionEditor } from "./SessionEditor";
import { HomeEditor } from "./HomeEditor";
@@ -186,7 +187,13 @@ 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.
@@ -263,8 +270,43 @@ 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}>
<div
className={styles.tasks}
onFocus={() => setFocusedTaskList(() => [...selectedRef.current])}
onBlur={(e) => {
if (!(e.relatedTarget instanceof Element && e.currentTarget.contains(e.relatedTarget)))
setFocusedTaskList(null);
}}
>
{tasks.size > 0 && (
<SearchField
className={styles.taskSearch}
@@ -339,7 +381,7 @@ export function AgentsView() {
const task = tasks.get(id);
return task ? [task] : [];
});
showContextMenu(e, taskMenu(selection));
showContextMenu(e, taskMenu(selection, selection.length === 1 ? tasksBelow(n.task.id) : []));
}}
renderNode={(n) => {
switch (n.kind) {
@@ -393,6 +435,13 @@ 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
Переглянути файл
@@ -470,6 +470,7 @@
border: 0;
border-radius: 50%;
background: var(--bg-popup);
box-shadow: 0 0 0 1px var(--border);
color: var(--fg);
cursor: pointer;
opacity: 0;
@@ -478,6 +479,11 @@
.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,
+26 -10
Переглянути файл
@@ -265,8 +265,10 @@
color: var(--fg-muted);
cursor: pointer;
}
.jumpToLatest:hover {
/* Over the stream's text: keep it opaque against the icon button's translucent hover fill. */
.streamArea .jumpToLatest:not(:disabled):hover {
background: var(--bg-hover);
color: var(--fg-strong);
}
/* Your message with its actions, shown on hover. */
.message {
@@ -515,12 +517,21 @@
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;
@@ -531,8 +542,8 @@
}
.markdown :global(pre code) {
display: block;
padding: 0;
background: none;
box-shadow: none;
}
.codeBlock {
position: relative;
@@ -1203,14 +1214,13 @@
border: 1px solid var(--border);
border-radius: var(--radius-small);
}
.toolImages,
.toolImages .imageItem,
.toolImages .imageButton {
max-width: 100%;
}
/* Images a tool read (screenshots, crops): one row height whatever their size; a click shows the whole image. */
.toolImages .image {
max-width: min(100%, 640px);
max-height: 320px;
width: auto;
height: 96px;
max-width: 200px;
object-fit: cover;
object-position: top left;
}
.removeImage {
position: absolute;
@@ -1224,9 +1234,15 @@
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;
+14
Переглянути файл
@@ -27,6 +27,7 @@ import {
type RefObject,
} from "react";
import { useAgentSettings } from "../agentSettings";
import { clampSelectionToRow } from "./clampSelection";
import { ImageStrip } from "../ImageStrip";
import {
entriesKey,
@@ -204,6 +205,12 @@ 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,
@@ -623,6 +630,13 @@ export function Stream({
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();
+46
Переглянути файл
@@ -0,0 +1,46 @@
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);
});
});
+39
Переглянути файл
@@ -0,0 +1,39 @@
/**
* 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;
}
+5
Переглянути файл
@@ -369,6 +369,11 @@ 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);
+102 -50
Переглянути файл
@@ -1,12 +1,10 @@
import type { AgentTask } from "@/bindings";
import type { Action } from "@/platform/actions";
import { t, tx } from "@/platform/i18n";
import { auxiliaryWindow } from "@/platform/auxWindow";
import { useProject } from "@/platform/project";
import { executeActionFrom, type Action } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import type { MenuItem } from "@/ui";
import { confirm, showError, confirmChecked } from "@/workbench/messages";
import { promptInput } from "@/workbench/inputDialogs";
import { hasTaskTerminal, isBusy } from "./model";
import { isBusy } from "./model";
import { groupNameError, type OrganizeGroup } from "./organize";
import {
archiveTask,
@@ -25,10 +23,12 @@ 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,10 +43,11 @@ export function useAgentsHeaderMenu(): MenuItem[] {
];
}
const canArchive = (task: AgentTask) => !isBusy(task.status) && task.status !== "archived";
export 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;
@@ -133,10 +134,9 @@ async function confirmRemoveGroup(group: string) {
deleteTaskGroup(group);
}
/** 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);
/** Pins and unpins of the selected tasks. */
function pinMenu(tasks: AgentTask[]): MenuItem[] {
const isPinned = new Set(useAgents.getState().organize.pinned);
const toPin = tasks.filter((t) => !isPinned.has(t.id));
const toUnpin = tasks.filter((t) => isPinned.has(t.id));
return [
@@ -162,20 +162,40 @@ function arrangeMenu(tasks: AgentTask[], ids: string[]): 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: "item",
id: "move-to-group",
label: "Group",
icon: "folder",
submenu: groupSubmenu(
ids,
groups,
ids.map((id) => groupOf[id]),
),
kind: "action",
action: allUnread ? "agents.markTasksRead" : "agents.markTasksUnread",
label: allUnread ? "Mark as Read" : "Mark as Unread",
icon: "",
arg: ids,
},
];
}
/** 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 [
@@ -313,6 +333,8 @@ 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")),
},
@@ -357,6 +379,28 @@ 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",
@@ -385,49 +429,40 @@ export const taskActions: Action[] = [
},
];
export function taskMenu(tasks: AgentTask[]): MenuItem[] {
/**
* 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[] {
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[])
: []),
...arrangeMenu(tasks, ids),
...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),
{ kind: "separator" },
...(archived
? ([
@@ -443,9 +478,26 @@ export function taskMenu(tasks: 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
Переглянути файл
@@ -0,0 +1,11 @@
/** 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?.() ?? [];
+36 -1
Переглянути файл
@@ -26,6 +26,10 @@ 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[];
@@ -103,7 +107,14 @@ class Fixture {
bases: spec.bases,
methods,
});
this.graph.push({ path, line: spec.line, col, name: spec.name, bases: spec.indexedBases ?? spec.bases });
if (!spec.unindexed)
this.graph.push({
path,
line: spec.indexedLine ?? 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: [] });
@@ -357,6 +368,30 @@ 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"] },
+33 -8
Переглянути файл
@@ -95,7 +95,30 @@ class ProjectView {
private outlines = new Map<string, Promise<readonly OutlineItem[]>>();
private ancestry = new Map<string, Promise<AncestryResolution>>();
constructor(private readonly deps: InheritanceInspectionDeps) {}
/**
* 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);
}
}
/** The document's classes, in declaration order, skipping ones the graph does not match. */
async classes(): Promise<ClassView[]> {
@@ -126,11 +149,16 @@ 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) =>
@@ -140,13 +168,7 @@ class ProjectView {
}
private declarationOf(facts: PythonClassFacts): ClassInheritance | 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
);
return this.declOf.get(facts) ?? null;
}
private factsOf(path: string): Promise<PythonFacts | null> {
@@ -162,6 +184,9 @@ 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
Переглянути файл
@@ -144,6 +144,7 @@ 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
Переглянути файл
@@ -34,6 +34,7 @@ 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
Переглянути файл
@@ -406,6 +406,8 @@ 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
Переглянути файл
@@ -404,6 +404,8 @@ 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
Переглянути файл
@@ -436,6 +436,8 @@ 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.
+6 -1
Переглянути файл
@@ -3858,5 +3858,10 @@
"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"
"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"
}
+6 -1
Переглянути файл
@@ -10088,5 +10088,10 @@
"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": "无法用颜色选择器修改此颜色"
"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 任务标记为已读"
}
+1
Переглянути файл
@@ -332,6 +332,7 @@ 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
Переглянути файл
@@ -0,0 +1,4 @@
<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>

Після

Ширина:  |  Висота:  |  Розмір: 274 B