Compare commits

..
Author SHA1 Message Date
l0ng-ai ee2aa4de51 fix(vcs): keep Git Log file selection in place 2026-11-24 13:47:43 +08:00
44 changed files with 302 additions and 1315 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
-8
View File
@@ -432,14 +432,6 @@ async fn patches_read_and_write_the_requested_repository() {
})
.collect::<String>();
let root = Some(roots[0].clone());
// Automatic mappings wait for indexing; the new folders and exclude rule may start a rescan.
tokio::time::sleep(Duration::from_millis(200)).await;
for _ in 0..500 {
if !project.index.status().indexing {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
let preview = vcs::vcs_patch_preview(&host, "main", root.clone(), patch.clone(), None, None).await.unwrap();
assert!(preview.files.iter().all(|file| file.applies && !file.missing_base));
assert_eq!(preview.automatic_mappings.len(), 1);
-3
View File
@@ -1605,10 +1605,7 @@ mod pipenv_tests {
#[test]
fn environments_are_named_as_pipenv_names_them() {
// `sanitize(folder)[:42] + "-" + urlsafe_b64encode(sha256(Pipfile path).digest()[:6])`, from pipenv.
#[cfg(unix)]
assert_eq!(pipenv_env_name(Path::new("/home/me/My Shop (2)")), "My_Shop__2_-6rNTtAUD");
#[cfg(windows)]
assert_eq!(pipenv_env_name(Path::new(r"C:\Users\me\My Shop (2)")), "My_Shop__2_-ED1rXUDC");
}
#[test]
+1 -1
View File
@@ -597,7 +597,7 @@ fn saved_python_configs_keep_their_explicit_interpreter() {
config.cwd = Some(Path::new("member").into());
apply_to_run_configs(std::slice::from_mut(&mut config), root, &settings);
assert_eq!(config.command, command);
assert_eq!(config.env["VIRTUAL_ENV"], root.join("member").join(".override").to_string_lossy());
assert_eq!(config.env["VIRTUAL_ENV"], root.join("member/.override").to_string_lossy());
let saved = without_derived(&config, root, &settings);
assert_eq!(saved.command, command);
}
+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();
+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"],
-108
View File
@@ -679,111 +679,3 @@ test("Docker Compose dashboard shows per-service resource usage and named projec
});
await expect(detail).toContainText("27.40%", { timeout: 5000 });
});
test("Docker Compose dashboard keeps its action row pinned when scrolling", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1200, height: 640 });
await stubDesktop(page);
await page.evaluate(async () => {
const containers = Array.from({ length: 10 }, (_, idx) => {
const n = idx + 1;
return {
id: `runner-${n}`,
name: `selfhost-github-runner-${n}`,
image: "myoung34/github-runner:latest",
command: "./bin/Runner.Listener run",
state: "running",
status: "Up 24 hours",
ports: "",
createdAt: "2026-11-22T20:00:00Z",
composeProject: "selfhost",
composeService: `github-runner-${n}`,
composeWorkingDir: "/work/selfhost",
composeFiles: ["/work/selfhost/docker-compose.yml"],
mounts: [],
networks: ["selfhost_default"],
};
});
const snapshot = {
availability: { kind: "ready", clientVersion: "28.0.1", serverVersion: "28.0.1", context: "desktop-linux" },
executable: "/usr/bin/docker",
containers,
images: [],
volumes: [],
networks: [],
errors: [],
};
window.__ipc.handlers.docker_settings = () => ({
connections: [{ id: "default", name: "Docker", endpoint: { kind: "default" } }],
registries: [],
});
window.__ipc.handlers.docker_snapshot = () => snapshot;
window.__ipc.handlers.docker_events = () => new Promise(() => {});
window.__ipc.handlers.docker_inspect = () => "[]";
window.__ipc.handlers.docker_container_stats = () => ({
cpuPerc: "0.04%",
memUsage: "99.85MiB / 114.3GiB",
memPerc: "0.09%",
netIo: "1.1MB / 3.75MB",
blockIo: "0B / 213kB",
pids: "15",
});
const storeMod = "/src/features/services/store.ts";
const treeMod = "/src/features/services/tree.ts";
const { useServices } = await import(/* @vite-ignore */ storeMod);
const { useServicesTree } = await import(/* @vite-ignore */ treeMod);
useServices.setState({
settings: { connections: [{ id: "default", name: "Docker", endpoint: { kind: "default" } }], registries: [] },
conns: { default: { snapshot, loading: false, error: null } },
});
useServicesTree.setState({
expanded: new Set(["docker:default"]),
selectedKey: "docker:default:compose:selfhost",
selectedKeys: new Set(["docker:default:compose:selfhost"]),
});
});
await page.keyboard.press("Meta+8");
const services = page.getByRole("region", { name: "Services", exact: true });
const detail = services.locator("[data-panel][id=services-detail]");
const startBtn = detail.getByRole("button", { name: "Start", exact: true });
const stopBtn = detail.getByRole("button", { name: "Stop", exact: true });
const restartBtn = detail.getByRole("button", { name: "Restart", exact: true });
const downBtn = detail.getByRole("button", { name: "Compose Down", exact: true });
await expect(downBtn).toBeVisible();
const beforeStart = (await startBtn.boundingBox())!;
const beforeDown = (await downBtn.boundingBox())!;
const beforeBanner = (await detail.getByText("Compose project 'selfhost'").boundingBox())!;
const scrollState = await detail.evaluate((panel) => {
const scrollers = Array.from(panel.querySelectorAll<HTMLElement>("*")).filter((el) => {
const cs = getComputedStyle(el);
return (cs.overflowY === "auto" || cs.overflowY === "scroll") && el.scrollHeight - el.clientHeight > 2;
});
scrollers[0]!.scrollTop = 160;
return {
scrollerCount: scrollers.length,
scrollTop: scrollers[0]!.scrollTop,
scrollerTop: scrollers[0]!.getBoundingClientRect().top,
};
});
expect(scrollState.scrollerCount).toBe(1);
expect(scrollState.scrollTop).toBeGreaterThan(100);
// The scroll container starts strictly below the pinned action row.
expect(scrollState.scrollerTop).toBeGreaterThanOrEqual(beforeDown.y + beforeDown.height);
await expect(startBtn).toBeVisible();
await expect(stopBtn).toBeVisible();
await expect(restartBtn).toBeVisible();
await expect(downBtn).toBeVisible();
const afterStart = (await startBtn.boundingBox())!;
const afterDown = (await downBtn.boundingBox())!;
const afterBanner = (await detail.getByText("Compose project 'selfhost'").boundingBox())!;
expect(afterStart.y).toBe(beforeStart.y);
expect(afterDown.y).toBe(beforeDown.y);
expect(afterBanner.y).toBeLessThan(beforeBanner.y - 100);
});
+4 -10
View File
@@ -228,14 +228,6 @@ mod tests {
(coalescing_sink(Arc::new(move |event| saved.lock().push(event)), tokio::runtime::Handle::current()), events)
}
/// Waits for the coalescing window to flush `n` events (a fixed sleep is too short on slow CI timers).
async fn wait_for_events(events: &Mutex<Vec<IdeEvent>>, n: usize) {
let deadline = std::time::Instant::now() + Duration::from_secs(5);
while events.lock().len() < n && std::time::Instant::now() < deadline {
tokio::time::sleep(Duration::from_millis(5)).await;
}
}
fn diagnostics(path: &str, source: &str, message: &str) -> IdeEvent {
IdeEvent::Diagnostics {
path: IpcPath::from(path),
@@ -324,7 +316,9 @@ mod tests {
sink.emit(diagnostics("/p/b.rs", "rust-analyzer", "other"));
assert!(events.lock().is_empty());
wait_for_events(&events, 3).await;
tokio::task::yield_now().await;
tokio::time::sleep(Duration::from_millis(30)).await;
tokio::task::yield_now().await;
{
let saved_events = events.lock();
@@ -387,7 +381,7 @@ mod tests {
}
assert_eq!(events.lock().len(), MAX_PENDING_DIAGNOSTICS);
wait_for_events(&events, MAX_PENDING_DIAGNOSTICS + 1).await;
tokio::time::sleep(Duration::from_millis(30)).await;
assert_eq!(events.lock().len(), MAX_PENDING_DIAGNOSTICS + 1);
}
-154
View File
@@ -1,154 +0,0 @@
import { beforeAll, describe, expect, it } from "vitest";
import type { LanguageSupport } from "@codemirror/language";
import { highlightTree, tags as t, type Tag } from "@lezer/highlight";
import { findLanguageDescription, loadSupport } from "./languages";
import { openideaHighlightStyle } from "./highlight";
let java: LanguageSupport;
beforeAll(async () => {
java = (await loadSupport(findLanguageDescription("Java", "")!))!;
});
function tokens(doc: string): { text: string; cls: string }[] {
const out: { text: string; cls: string }[] = [];
highlightTree(java.language.parser.parse(doc), openideaHighlightStyle, (from, to, cls) => {
out.push({ text: doc.slice(from, to), cls });
});
return out;
}
const cls = (tag: Tag) => openideaHighlightStyle.style([tag])!;
function expectTokens(doc: string, expected: readonly (readonly [string, Tag])[]) {
const got = tokens(doc);
for (const [text, tag] of expected) expect(got, text).toContainEqual({ text, cls: cls(tag) });
}
/** The literal holding `text` is one string token: nothing is embedded. */
function expectPlainString(doc: string, text: string) {
expect(
tokens(doc).some((tok) => tok.cls === cls(t.string) && tok.text.includes(text)),
text,
).toBe(true);
}
const JPA = "import org.springframework.data.jpa.repository.Query;\n";
const VALUE = "import org.springframework.beans.factory.annotation.Value;\n";
describe("Java annotation string languages", () => {
it("highlights JPQL in Spring Data JPA @Query, also concatenated and as countQuery", () => {
const doc = `${JPA}interface Repo {
@Query(value = "select u from User u " + "where u.email = :email", countQuery = "select count(u) from User u")
User find(String email);
}`;
expectTokens(doc, [
["select", t.keyword],
["from", t.keyword],
["where", t.keyword],
["count", t.keyword],
// The quotes stay the Java string's.
['"', t.string],
]);
expect(tokens(doc).filter((tok) => tok.cls === cls(t.string) && tok.text.includes("select"))).toEqual([]);
// JPQL names entities: `User` is not SQL's `USER` keyword.
expect(tokens(doc).filter((tok) => tok.text === "User" && tok.cls === cls(t.keyword))).toEqual([]);
});
it("highlights native SQL in a text block", () => {
const doc = `${JPA}interface Repo {
@Query(nativeQuery = true, value = """
SELECT * FROM User WHERE id = 1
""")
User find();
}`;
expectTokens(doc, [
["SELECT", t.keyword],
["WHERE", t.keyword],
["1", t.number],
// Native SQL keeps SQL's keywords.
["User", t.keyword],
]);
});
it("resolves the annotation through a package import or its qualified name", () => {
expectTokens('import org.springframework.data.jpa.repository.*;\ninterface R { @Query("select 1") void f(); }', [
["select", t.keyword],
]);
expectTokens('interface R { @org.springframework.data.jpa.repository.Query("select 1") void f(); }', [
["select", t.keyword],
]);
});
it("leaves other annotations named Query as plain strings", () => {
expectPlainString('import com.example.Query;\ninterface R { @Query("select u from User u") void f(); }', "select");
expectPlainString('interface R { @Query("select u from User u") void f(); }', "select");
expectPlainString(
'import org.springframework.data.mongodb.repository.Query;\ninterface R { @Query("{ name: ?0 }") void f(); }',
"name",
);
expectPlainString(
'import org.springframework.data.mongodb.repository.*;\ninterface R { @Query("{ name: ?0 }") void f(); }',
"name",
);
});
it("keeps escape sequences out of the embedded text", () => {
const doc = `${JPA}interface R { @Query("select u from User u where u.name = \\"x\\"") void f(); }`;
const got = tokens(doc);
// The escapes keep the Java string's colour; the escape colouring of the semantic layer marks them.
expect(got).toContainEqual({ text: '\\"', cls: cls(t.string) });
expect(got).toContainEqual({ text: "where", cls: cls(t.keyword) });
// The escaped quotes don't open an SQL quoted identifier: `x` is plain text.
expect(got.filter((tok) => tok.text.includes("x"))).toEqual([]);
});
it("highlights placeholders and SpEL in @Value", () => {
const doc = `${VALUE}class C {
@Value("\${app.timeout:30}") int timeout;
@Value("#{systemProperties['user.region'] ?: 'eu'}") String region;
@Value("prefix-#{@config.name()}") String name;
}`;
expectTokens(doc, [
["${", t.meta],
["app.timeout", t.propertyName],
["30", t.string],
["#{", t.meta],
["}", t.meta],
["systemProperties", t.variableName],
["'user.region'", t.string],
["?:", t.operator],
["prefix-", t.string],
["#{@config", t.meta],
["name", t.function(t.propertyName)],
]);
});
it("highlights the whole value as SpEL in security and cache annotations", () => {
const doc = `import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.cache.annotation.Cacheable;
class C {
@PreAuthorize("hasRole('ADMIN') and #id == authentication.principal.id")
@Cacheable(cacheNames = "users", key = "#id", unless = "#result == null")
User find(long id) { return null; }
}`;
expectTokens(doc, [
["hasRole", t.function(t.variableName)],
["'ADMIN'", t.string],
["and", t.keyword],
["#id", t.standard(t.variableName)],
["principal", t.propertyName],
["#result", t.standard(t.variableName)],
["null", t.null],
]);
// Not a SpEL attribute.
expectPlainString(doc, "users");
});
it("closes #{…} after an inline list", () => {
expectTokens(`${VALUE}class C { @Value("#{ {1, 2}.size() } items") int n; }`, [
["size", t.function(t.propertyName)],
[" items", t.string],
]);
});
});
-261
View File
@@ -1,261 +0,0 @@
/**
* Embedded languages in Java annotation strings, as IntelliJ IDEA Ultimate's Spring support
* injects them: JPQL (SQL with `nativeQuery = true`) in Spring Data JPA's `@Query`, SpEL in `@PreAuthorize`, `@Cacheable(key = …)`
* and the like, and SpEL `#{…}` with property placeholders `${…}` in `@Value` and
* `@ConditionalOnExpression`.
*
* An annotation counts only by its resolved name: written fully qualified, or by a simple name the file
* imports (the class itself or its package with `.*`), so a project's own `@Query` keeps a plain string.
* Escape sequences stay outside the embedded text and keep the Java string's colours.
*/
import { LanguageSupport, LRLanguage, StreamLanguage, type StringStream } from "@codemirror/language";
import { java } from "@codemirror/lang-java";
import {
parseMixed,
type Input,
type NestedParse,
type Parser,
type SyntaxNode,
type SyntaxNodeRef,
} from "@lezer/common";
import { SQLDialect, StandardSQL } from "@codemirror/lang-sql";
type Embedded = "SQL" | "SpEL" | "SpEL template";
const PREPOST = "org.springframework.security.access.prepost.";
const CACHE = "org.springframework.cache.annotation.";
const CACHE_ATTRIBUTES = {
key: "SpEL",
condition: "SpEL",
unless: "SpEL",
} as const;
/** Annotation class → attribute → embedded language. */
const INJECTIONS: Record<string, Record<string, Embedded>> = {
"org.springframework.data.jpa.repository.Query": {
value: "SQL",
countQuery: "SQL",
},
"org.springframework.beans.factory.annotation.Value": {
value: "SpEL template",
},
"org.springframework.boot.autoconfigure.condition.ConditionalOnExpression": {
value: "SpEL template",
},
[`${PREPOST}PreAuthorize`]: { value: "SpEL" },
[`${PREPOST}PostAuthorize`]: { value: "SpEL" },
[`${PREPOST}PreFilter`]: { value: "SpEL" },
[`${PREPOST}PostFilter`]: { value: "SpEL" },
[`${CACHE}Cacheable`]: CACHE_ATTRIBUTES,
[`${CACHE}CachePut`]: CACHE_ATTRIBUTES,
[`${CACHE}CacheEvict`]: CACHE_ATTRIBUTES,
};
const SIMPLE_NAMES = new Set(Object.keys(INJECTIONS).map((name) => name.slice(name.lastIndexOf(".") + 1)));
const text = (node: SyntaxNode, input: Input) => input.read(node.from, node.to).replace(/\s+/g, "");
/** The annotation's class: `name` as written when qualified, else the import that brings it in. */
function annotationClass(annotation: SyntaxNode, input: Input): string | null {
const nameNode = annotation.getChild("Identifier") ?? annotation.getChild("ScopedIdentifier");
if (!nameNode) return null;
const name = text(nameNode, input);
if (name.includes(".")) return name;
if (!SIMPLE_NAMES.has(name)) return null;
let program = annotation;
while (program.parent) program = program.parent;
for (const decl of program.getChildren("ImportDeclaration")) {
if (decl.getChild("static")) continue;
const path = decl.getChild("ScopedIdentifier");
if (!path) continue;
const imported = text(path, input);
if (!decl.getChild("Asterisk")) {
if (imported.endsWith(`.${name}`)) return imported;
} else if (INJECTIONS[`${imported}.${name}`]) return `${imported}.${name}`;
}
return null;
}
/** The string literals of an attribute value: one literal, or several joined with `+`. */
function literals(value: SyntaxNode, out: SyntaxNode[] = []): SyntaxNode[] {
if (value.name === "StringLiteral" || value.name === "TextBlock") out.push(value);
else if (value.name === "BinaryExpression" || value.name === "ParenthesizedExpression")
for (let child = value.firstChild; child; child = child.nextSibling) literals(child, out);
return out;
}
const ESCAPE = /\\(?:u+[0-9a-fA-F]{4}|[0-7]{1,3}|[\s\S])/g;
/** The literal's text between its quotes, without escape sequences. */
function contentRanges(literal: SyntaxNode, input: Input, out: { from: number; to: number }[]) {
const quote = literal.name === "TextBlock" ? 3 : 1;
const from = literal.from + quote;
const raw = input.read(literal.from, literal.to);
const closed = raw.length >= 2 * quote && raw.endsWith(quote === 3 ? '"""' : '"');
const to = closed ? literal.to - quote : literal.to;
let start = from;
// ponytail: an escape splits the embedded text, so `FROM\nUser` reads as `FROMUser`; rare in queries.
for (const m of input.read(from, to).matchAll(ESCAPE)) {
const at = from + m.index;
if (at > start) out.push({ from: start, to: at });
start = at + m[0].length;
}
if (to > start) out.push({ from: start, to });
}
const SPEL_KEYWORDS = /^(?:and|or|not|eq|ne|lt|gt|le|ge|div|mod|instanceof|matches|between|new|T)\b(?![\w$])/;
interface Frame {
kind: "#" | "$";
/** Inside a placeholder, past the `:` before its default value. */
fallback: boolean;
/** Open `{` of inline lists and maps inside a `#{…}`. */
braces: number;
}
interface SpelState {
/** Open `#{` / `${`. Outside them a template string is text and an expression-only string is SpEL. */
stack: Frame[];
/** The last token was `.` or `?.`: a property or method name follows. */
member: boolean;
}
function spelToken(stream: StringStream, state: SpelState, template: boolean): string | null {
if (stream.match(/^[#$]\{/)) {
state.stack.push({
kind: stream.current()[0] as "#" | "$",
fallback: false,
braces: 0,
});
return "meta";
}
const frame = state.stack[state.stack.length - 1];
if (frame && (frame.kind === "$" || !frame.braces) && stream.eat("}")) {
state.stack.pop();
return "meta";
}
if (template && !frame) {
if (!stream.match(/^[^#$]+/)) stream.next();
return "string";
}
if (frame?.kind === "$") {
if (frame.fallback) {
if (!stream.match(/^[^#$}]+/)) stream.next();
return "string";
}
if (stream.eat(":")) {
frame.fallback = true;
return "operator";
}
if (!stream.match(/^[^:#$}]+/)) stream.next();
return "propertyName";
}
if (stream.eatSpace()) return null;
const member = state.member;
state.member = false;
if (stream.eat("'")) {
while (!stream.eol()) if (stream.next() === "'" && !stream.eat("'")) break;
return "string";
}
if (stream.match(/^\d+(?:\.\d+)?(?:[eE][-+]?\d+)?[lLfFdD]?/)) return "number";
if (stream.match(/^#\w+/)) return "variableName.standard";
if (stream.match(/^[@&][\w$]+/)) return "meta";
if (!member && stream.match(/^(?:true|false)\b/)) return "bool";
if (!member && stream.match(/^null\b/)) return "null";
if (!member && stream.match(SPEL_KEYWORDS)) return "keyword";
if (stream.match(/^[A-Za-z_$][\w$]*/)) {
const call = stream.match(/^\s*\(/, false);
if (member) return call ? "propertyName.function" : "propertyName";
return call ? "variableName.function" : "variableName";
}
if (stream.match(/^\??\./)) {
state.member = true;
return "derefOperator";
}
if (stream.match(/^(?:\?:|\.\?|\.\^|\.\$|[!=<>]=?|&&|\|\||[-+*/%^?:])/)) return "operator";
if (frame && stream.match(/^[{}]/)) frame.braces += stream.current() === "{" ? 1 : -1;
else if (!stream.match(/^[()[\]{}]/)) {
if (stream.eat(",")) return "separator";
stream.next();
return null;
}
return "bracket";
}
function spel(template: boolean): Parser {
return StreamLanguage.define<SpelState>({
name: template ? "spel-template" : "spel",
startState: () => ({ stack: [], member: false }),
copyState: (s) => ({
stack: s.stack.map((f) => ({ ...f })),
member: s.member,
}),
token: (stream, state) => spelToken(stream, state, template),
}).parser;
}
/** JPQL / HQL: entity names such as `User` or `Order` are not keywords, unlike in SQL. */
const JPQL_KEYWORDS =
"select from where and or not as join left right inner outer full cross fetch on with distinct order by group " +
"having asc desc nulls first last in like escape between is null empty member of exists all any some case when " +
"then else end new update set delete insert into union intersect except true false count sum avg min max upper " +
"lower trim leading trailing both length locate abs sqrt mod size index key value entry treat type coalesce " +
"nullif concat substring cast extract function current_date current_time current_timestamp object limit offset";
let parsers: Record<Embedded | "JPQL", Parser> | null = null;
/** Whether `@Query(…)` has `nativeQuery = true`. */
function nativeQuery(args: SyntaxNode, input: Input): boolean {
return args
.getChildren("ElementValuePair")
.some((pair) => /^nativeQuery\s*=\s*true$/.test(input.read(pair.from, pair.to)));
}
/** The nested parse for an annotation attribute value (`ElementValuePair`) or a lone value. */
export function javaInjection() {
return (ref: SyntaxNodeRef, input: Input): NestedParse | null => {
// Called for every node on each parse: rule out the rest before materializing the node.
if (ref.name !== "ElementValuePair" && ref.name !== "AnnotationArgumentList") return null;
const node = ref.node;
let attribute: string;
let value: SyntaxNode | null;
let annotation: SyntaxNode | null;
if (node.name === "ElementValuePair") {
const name = node.getChild("Identifier");
attribute = name ? input.read(name.from, name.to) : "";
value = node.lastChild;
annotation = node.parent?.parent ?? null;
} else {
// `@Ann("…")`: the value attribute's shorthand.
attribute = "value";
value = node.firstChild?.nextSibling ?? null;
if (value?.name === "ElementValuePair") return null;
annotation = node.parent;
}
if (!value || annotation?.name !== "Annotation") return null;
const cls = annotationClass(annotation, input);
const language = cls ? INJECTIONS[cls]?.[attribute] : undefined;
if (!language) return null;
const overlay: { from: number; to: number }[] = [];
for (const literal of literals(value)) contentRanges(literal, input, overlay);
if (!overlay.length) return null;
parsers ??= {
SQL: StandardSQL.language.parser,
JPQL: SQLDialect.define({ keywords: JPQL_KEYWORDS, types: "", builtin: "" }).language.parser,
SpEL: spel(false),
"SpEL template": spel(true),
};
// ponytail: the mount is per attribute, so toggling `nativeQuery` restyles the query once it is edited.
const jpql = language === "SQL" && !nativeQuery(annotation.getChild("AnnotationArgumentList")!, input);
return { parser: parsers[jpql ? "JPQL" : language], overlay };
};
}
/** `java()` that also parses the embedded languages of Spring annotation strings. */
export function javaWithInjections(): LanguageSupport {
const base = java();
const language = (base.language as LRLanguage).configure({
wrap: parseMixed(javaInjection()),
});
return new LanguageSupport(language, base.support);
}
-23
View File
@@ -411,29 +411,6 @@ describe("language modes", () => {
}
});
it("leaves Java statement labels uncoloured, unlike JavaScript's", async () => {
const highlighter = tagHighlighter([
{ tag: t.labelName, class: "label" },
{ tag: t.variableName, class: "variable" },
]);
const labels = async (mode: string, path: string, doc: string) => {
const support = await loadSupport(findLanguageDescription(mode, path)!);
const found: string[] = [];
highlightTree(support!.language.parser.parse(doc), highlighter, (from, to, style) =>
found.push(`${doc.slice(from, to)}:${style}`),
);
return found.filter((s) => s.startsWith("outer"));
};
expect(await labels("Java", "/p/A.java", "class A { void f() { outer: for (;;) { break outer; } } }")).toEqual([
"outer:variable",
"outer:variable",
]);
expect(await labels("JavaScript", "/p/a.js", "outer: for (;;) { break outer; }")).toEqual([
"outer:label",
"outer:label",
]);
});
it("recognizes go.mod and go.work files by mode and filename", async () => {
for (const [mode, path] of [
["GoMod", "/project/go.mod"],
-7
View File
@@ -224,11 +224,6 @@ const OWN_MODES = [
load: () => import("./templateLanguages").then((m) => m.javascriptWithTemplates(config, templateLanguage)),
}),
),
// JPQL / SQL in `@Query`, SpEL and property placeholders in Spring annotation strings.
LanguageDescription.of({
name: "Java",
load: () => import("./javaInjections").then((m) => m.javaWithInjections()),
}),
// Only for template literals: `.graphql` files keep the backend's tree-sitter highlighting.
LanguageDescription.of({
name: "GraphQL",
@@ -500,8 +495,6 @@ const CSS_TAGS: Parameters<typeof styleTags>[0] = {
export const JAVA_TAGS: Parameters<typeof styleTags>[0] = {
"MarkerAnnotation/Identifier Annotation/Identifier MarkerAnnotation Annotation": t.annotation,
this: t.keyword,
// IntelliJ has no Java label colour: `outer:` stays plain text, like `break outer`.
Label: t.variableName,
};
// @lezer/go leaves `default` uncoloured, unlike `case` and `switch`.
+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,
+1 -1
View File
@@ -64,7 +64,7 @@ export function McpPicker({
testData,
}: McpPickerProps) {
const tx = useTx();
useMcpCatalogSync(!hideTrigger);
useMcpCatalogSync();
const catalogServers = useMcpCatalog((s) => s.servers);
const catalogSources = useMcpCatalog((s) => s.sources);
const projectIdeMcp = useProject((s) => s.settings?.mcpServer?.enabled ?? false);
+10 -28
View File
@@ -265,10 +265,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 {
@@ -410,8 +408,6 @@
.reply {
position: relative;
/* Keep WebKit's selection gap fill from extending across reply boundaries. */
transform: translateX(0);
}
.replyFooter {
position: absolute;
@@ -517,21 +513,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 +529,8 @@
}
.markdown :global(pre code) {
display: block;
padding: 0;
background: none;
box-shadow: none;
}
.codeBlock {
position: relative;
@@ -1214,13 +1201,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 +1222,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;
+1 -1
View File
@@ -176,7 +176,7 @@ export function SessionPicker({
</div>
)}
<div className={styles.list}>{open && children(query, controls)}</div>
<div className={styles.list}>{children(query, controls)}</div>
<div className={styles.footer}>
<span>
+1 -1
View File
@@ -67,7 +67,7 @@ export function SkillsPicker({
testData,
}: SkillsPickerProps) {
const tx = useTx();
useSkillsCatalogSync(!hideTrigger, backend);
useSkillsCatalogSync(backend);
const catalogSkills = useSkillsCatalog((s) => s.skills);
const skills = testData?.skills ?? catalogSkills;
const resolved = useMemo(() => resolveSessionSkills(skills, overrides ?? {}), [skills, overrides]);
+22 -35
View File
@@ -3,13 +3,10 @@ import { sendKeyAction } from "./Composer";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { EditorView } from "@codemirror/view";
import type { AgentCommand, AgentProvider, AgentSkillState } from "@/bindings";
import type { AgentCommand, AgentProvider } from "@/bindings";
const agentCommands = vi.fn();
const agentCreate = vi.fn();
const agentMcpList = vi.fn();
const agentMcpDiscoverSources = vi.fn();
const agentSkillsList = vi.fn();
const vcsBranches = vi.fn();
const vcsBranchInfo = vi.fn();
const clipboardImage = vi.fn();
@@ -23,9 +20,6 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
...real.commands,
agentCommands: (provider: string, task: string | null) => agentCommands(provider, task),
agentCreate: (request: unknown) => agentCreate(request),
agentMcpList: () => agentMcpList(),
agentMcpDiscoverSources: () => agentMcpDiscoverSources(),
agentSkillsList: () => agentSkillsList(),
agentRefreshModels: async (provider: string) => ({
status: "ok",
data: {
@@ -114,9 +108,6 @@ beforeEach(() => {
}),
);
agentCommands.mockReset();
for (const request of [agentMcpList, agentMcpDiscoverSources, agentSkillsList]) {
request.mockReset().mockResolvedValue({ status: "ok", data: [] });
}
clipboardImage.mockReset().mockResolvedValue({
status: "ok",
data: "data:image/png;base64,iVBORw0KGgo=",
@@ -183,8 +174,6 @@ describe("New Task composer commands", () => {
it("opens the per-session MCP picker when /mcp is completed in the composer", async () => {
agentCommands.mockResolvedValue({ status: "ok", data: [] });
render(<HomeEditor />);
expect(agentMcpList).not.toHaveBeenCalled();
expect(agentMcpDiscoverSources).not.toHaveBeenCalled();
const box = screen.getByRole("textbox");
typeIn(box, "/mc");
const list = await screen.findByRole("listbox", { name: "Commands" });
@@ -192,14 +181,11 @@ describe("New Task composer commands", () => {
fireEvent.keyDown(box, { key: "Enter" });
expect(textOf(box)).toBe("");
expect(await screen.findByText("Session MCP Servers")).toBeInTheDocument();
expect(agentMcpList).toHaveBeenCalledOnce();
expect(agentMcpDiscoverSources).toHaveBeenCalledOnce();
});
it("opens the per-session skills picker when /skills is completed in the composer", async () => {
agentCommands.mockResolvedValue({ status: "ok", data: [] });
render(<HomeEditor />);
expect(agentSkillsList).not.toHaveBeenCalled();
const box = screen.getByRole("textbox");
typeIn(box, "/sk");
const list = await screen.findByRole("listbox", { name: "Commands" });
@@ -207,7 +193,6 @@ describe("New Task composer commands", () => {
fireEvent.keyDown(box, { key: "Enter" });
expect(textOf(box)).toBe("");
expect(await screen.findByText("Session Skills")).toBeInTheDocument();
expect(agentSkillsList).toHaveBeenCalledOnce();
});
it("names the icon-only Start action and disables it while starting", async () => {
@@ -346,32 +331,34 @@ describe("New Task composer commands", () => {
expect(agentCreate.mock.calls[0]![0]).toMatchObject({ idle: true, prompt: { text: "!gi" } });
});
it.each(["saved", "edited"])("reflects %s draft skill overrides in / completion", async (source) => {
it("reflects per-session draft skillOverrides immediately in / completion", async () => {
agentCommands.mockResolvedValue({
status: "ok",
data: [command("triage", "Triage issues", "skill"), command("compact", "Compact")],
});
const skills: AgentSkillState[] = [
{
skill: {
name: "impeccable",
description: "Muted globally, enabled for this draft",
path: "/skills/impeccable",
source: "user",
valid: true,
warnings: [],
useSkillsCatalog.setState({
loaded: true,
skills: [
{
skill: {
name: "impeccable",
description: "Muted globally, enabled for this draft",
path: "/skills/impeccable",
source: "user",
valid: true,
warnings: [],
},
mode: "off",
origin: "user",
},
mode: "off",
origin: "user",
},
];
const overrides = { triage: "off", impeccable: "auto" } as const;
agentSkillsList.mockResolvedValue({ status: "ok", data: skills });
useSkillsCatalog.setState({ loaded: source === "edited", skills: source === "edited" ? skills : [] });
if (source === "saved") setDraftSkillOverrides(overrides);
],
});
render(<HomeEditor />);
await waitFor(() => expect(agentCommands).toHaveBeenCalled());
if (source === "edited") act(() => setDraftSkillOverrides(overrides));
act(() => {
setDraftSkillOverrides({ triage: "off", impeccable: "auto" });
});
const box = screen.getByRole("textbox");
typeIn(box, "/");
+4 -6
View File
@@ -239,15 +239,13 @@ export async function refreshMcpCatalog(): Promise<void> {
}));
}
export function useMcpCatalogSync(eager: boolean): void {
export function useMcpCatalogSync(): void {
const root = useProject((s) => s.project?.root);
useEffect(() => {
if (!isTauri()) return;
void refreshMcpCatalog();
const onFocus = () => void refreshMcpCatalog();
if (eager) {
onFocus();
window.addEventListener("focus", onFocus);
}
window.addEventListener("focus", onFocus);
if (!listenerAttached && typeof onIdeEvent === "function") {
listenerAttached = true;
onIdeEvent("settingsChanged", (e) => {
@@ -257,5 +255,5 @@ export function useMcpCatalogSync(eager: boolean): void {
});
}
return () => window.removeEventListener("focus", onFocus);
}, [eager, root]);
}, [root]);
}
+31 -50
View File
@@ -27,7 +27,6 @@ import {
type RefObject,
} from "react";
import { useAgentSettings } from "../agentSettings";
import { clampSelectionToRow } from "./clampSelection";
import { ImageStrip } from "../ImageStrip";
import {
entriesKey,
@@ -205,12 +204,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,
@@ -558,41 +551,6 @@ export function Stream({
),
[task, lastIndex, busy, thinking, onDiagramDrawn, renderRow],
);
const agentName = providerName(task.provider);
// Switching tabs changes visibility without changing the conversation rows.
const renderedRows = useMemo(
() =>
rows.map((row) => {
const images = toolImages(row);
return (
<div
key={row.index}
className={styles.conversationRow}
data-message={
(row.kind === "entry" && (row.entry.type === "user" || row.entry.type === "agent")) || undefined
}
data-process={row.kind !== "entry" || row.entry.type !== "user" || undefined}
data-author={authorHeaders.has(row.index) || undefined}
>
{authorHeaders.has(row.index) && (
<div className={styles.agentAuthor}>
<div className={styles.role}>
<Icon name={providerIcon(task.provider)} size={13} />
<span>{agentName}</span>
</div>
</div>
)}
{renderConversationRow(row)}
{images.length > 0 && (
<div className={styles.toolImages}>
<ImageStrip images={images} />
</div>
)}
</div>
);
}),
[rows, authorHeaders, task.provider, agentName, renderConversationRow],
);
return (
<OpenFolds.Provider value={openFolds}>
<KeepFoldHeader.Provider value={keepFoldHeader}>
@@ -630,13 +588,6 @@ 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();
@@ -703,7 +654,37 @@ export function Stream({
) : entries.length === 0 && !busy && !loadError ? (
<EmptyState title="No conversation history" />
) : (
<RowRenderer.Provider value={renderConversationRow}>{renderedRows}</RowRenderer.Provider>
<RowRenderer.Provider value={renderConversationRow}>
{rows.map((row) => {
const images = toolImages(row);
return (
<div
key={row.index}
className={styles.conversationRow}
data-message={
(row.kind === "entry" && (row.entry.type === "user" || row.entry.type === "agent")) || undefined
}
data-process={row.kind !== "entry" || row.entry.type !== "user" || undefined}
data-author={authorHeaders.has(row.index) || undefined}
>
{authorHeaders.has(row.index) && (
<div className={styles.agentAuthor}>
<div className={styles.role}>
<Icon name={providerIcon(task.provider)} size={13} />
<span>{providerName(task.provider)}</span>
</div>
</div>
)}
{renderConversationRow(row)}
{images.length > 0 && (
<div className={styles.toolImages}>
<ImageStrip images={images} />
</div>
)}
</div>
);
})}
</RowRenderer.Provider>
)}
<WorkingRow task={task} entries={entries} subagent={subagent} />
</div>
@@ -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;
}
+4 -6
View File
@@ -153,15 +153,13 @@ export async function refreshSkillsCatalog(backend: SkillsBackend = defaultSkill
if (skills) useSkillsCatalog.setState({ skills, loaded: true });
}
export function useSkillsCatalogSync(eager: boolean, backend: SkillsBackend = defaultSkillsBackend): void {
export function useSkillsCatalogSync(backend: SkillsBackend = defaultSkillsBackend): void {
const root = useProject((s) => s.project?.root);
useEffect(() => {
if (!isTauri()) return;
void refreshSkillsCatalog(backend);
const onFocus = () => void refreshSkillsCatalog(backend);
if (eager) {
onFocus();
window.addEventListener("focus", onFocus);
}
window.addEventListener("focus", onFocus);
if (!listenerAttached && typeof onIdeEvent === "function") {
listenerAttached = true;
onIdeEvent("settingsChanged", (e) => {
@@ -171,5 +169,5 @@ export function useSkillsCatalogSync(eager: boolean, backend: SkillsBackend = de
});
}
return () => window.removeEventListener("focus", onFocus);
}, [eager, root, backend]);
}, [root, backend]);
}
+1 -8
View File
@@ -27,7 +27,7 @@ import { auxiliaryWindow, windowLabel } from "@/platform/auxWindow";
import { routeToWindow, taskWindowDraft, taskWindowFocused, updateTaskWindowDraft } from "./taskWindowRouting";
import { clearAgentTaskFontZoom, resetAllAgentFontZoom } from "./fontZoom";
import { clearDismissedAssets } from "./sessionAssetsModel";
import { useSkillsCatalog, useSkillsCatalogSync } from "./skillsModel";
import { useSkillsCatalog } from "./skillsModel";
import { basename, useProject } from "@/platform/project";
import { projectLocation } from "@/platform/remote";
import { defaultTaskProject } from "./project";
@@ -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);
@@ -1072,8 +1067,6 @@ export function useAgentCommands(
offered: readonly AgentCommand[],
): readonly AgentCommand[] {
const skillOverrides = useAgents((s) => (task ? s.tasks.get(task)?.skillOverrides : s.draft.skillOverrides));
// The server's draft commands omit skills that only this draft has enabled.
useSkillsCatalogSync(task === null && Object.values(skillOverrides ?? {}).some((mode) => mode !== "off"));
const catalogSkills = useSkillsCatalog((s) => s.skills);
const [found, setFound] = useState<{
for: unknown[];
+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) {
@@ -96,7 +96,6 @@
}
.detailPane {
height: 100%;
min-height: 0;
display: flex;
flex-direction: column;
}
@@ -236,7 +235,6 @@
user-select: text;
}
.dashboardActions {
flex: none;
display: flex;
flex-wrap: wrap;
align-items: center;
@@ -256,10 +254,6 @@
border-top: 1px solid var(--border);
border-bottom: 1px solid var(--border);
}
.dashboard > .sectionBanner:first-child,
.dashboardActions + .sectionBanner {
border-top: 0;
}
.propList {
display: flex;
flex-direction: column;
+137 -139
View File
@@ -1888,7 +1888,7 @@ export function ComposeProjectDashboard({
const { byId: activeStats, loading: statsLoading } = useLiveContainerStats(conn, runningIdsKey);
return (
<div className={styles.detailBody}>
<div className={styles.dashboard} tabIndex={0} onKeyDown={copySelectionOnKeyDown}>
<div className={styles.dashboardActions}>
<OpButton busy={busy === "start"} disabled={!canStart(target)} onClick={() => void start(target)}>
Start
@@ -1904,146 +1904,144 @@ export function ComposeProjectDashboard({
</Button>
</div>
<div className={styles.dashboard} tabIndex={0} onKeyDown={copySelectionOnKeyDown}>
<SectionBanner>{txTemplate(`Compose project '${project}'`)}</SectionBanner>
<div className={styles.propList}>
<PropRow label={<T>Project</T>}>
<span className={styles.mono}>{project}</span>
</PropRow>
<PropRow label={<T>Status</T>}>
<span>
{runningCount}/{containers.length} running
</span>
</PropRow>
<PropRow label={<T>Working directory</T>} hidden={!first?.composeWorkingDir}>
<span className={styles.mono}>{first?.composeWorkingDir}</span>
</PropRow>
<PropRow label={<T>Compose files</T>} hidden={!first?.composeFiles.length}>
<span className={styles.inlineRow}>
{first?.composeFiles.map((file) => (
<button
key={file}
type="button"
className={styles.link}
onClick={() => void openComposeFile(file, first.composeWorkingDir)}
>
<span className={styles.mono}>{file}</span>
</button>
))}
</span>
</PropRow>
</div>
<SectionBanner>
<T>Services</T>
</SectionBanner>
<div className={styles.composeTableWrap}>
<table className={clsx(styles.gridTable, styles.composeServicesTable)}>
<thead>
<tr>
<th>
<T>Service</T>
</th>
<th>
<T>Status</T>
</th>
<th>
<T>CPU</T>
</th>
<th>
<T>Memory</T>
</th>
<th>
<T>Network I/O</T>
</th>
<th>
<T>Block I/O</T>
</th>
<th>
<T>PIDs</T>
</th>
</tr>
</thead>
<tbody>
{containers.map((c) => {
const running = isRunning(c);
const stats = running ? activeStats[c.id] : undefined;
const cpuPct = stats ? parsePercent(stats.cpuPerc) : 0;
const memPair = stats ? parseUsagePair(stats.memUsage) : null;
const memPct = memPair ? memPair.percent : stats ? parsePercent(stats.memPerc) : 0;
return (
<tr key={c.id}>
<td className={styles.composeServiceCell}>
<button type="button" className={styles.link} onClick={() => selectContainerInTree(conn, c)}>
<span className={clsx(styles.statusDot, running ? styles.dotOk : styles.dotMuted)} />
<span className={styles.mono}>{c.name}</span>
</button>
{c.composeService && !c.name.includes(c.composeService) && (
<span className={styles.mutedMeta}>{c.composeService}</span>
)}
</td>
<td className={styles.nowrapCell}>
<StatusBadge state={c.state} text={c.status || c.state} />
</td>
<td className={styles.composeMetricCell}>
{stats ? (
<div className={styles.composeMetric}>
<span className={styles.mono}>{stats.cpuPerc}</span>
<LineProgress percent={cpuPct} />
</div>
) : running && statsLoading ? (
<Spinner size={12} />
) : (
<span className={styles.mutedMeta}>—</span>
)}
</td>
<td className={styles.composeMemoryCell}>
{stats ? (
<div className={styles.composeMetric}>
<span className={styles.mono}>
{stats.memUsage} ({stats.memPerc})
</span>
<LineProgress percent={memPct} />
</div>
) : running && statsLoading ? (
<span className={styles.mutedMeta}>
<T>Loading…</T>
</span>
) : (
<span className={styles.mutedMeta}>—</span>
)}
</td>
<td className={clsx(styles.mono, styles.nowrapCell)}>
{stats?.netIo || <span className={styles.mutedMeta}>—</span>}
</td>
<td className={clsx(styles.mono, styles.nowrapCell)}>
{stats?.blockIo || <span className={styles.mutedMeta}>—</span>}
</td>
<td className={clsx(styles.mono, styles.nowrapCell)}>
{stats?.pids || <span className={styles.mutedMeta}>—</span>}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
<SectionBanner>
<T>Volumes</T>
</SectionBanner>
{namedVolumes.length > 0 ? (
<div className={styles.chipGroup}>
{namedVolumes.map((v) => (
<VolumeLinkChip key={v.name} conn={conn} volume={v} />
<SectionBanner>{txTemplate(`Compose project '${project}'`)}</SectionBanner>
<div className={styles.propList}>
<PropRow label={<T>Project</T>}>
<span className={styles.mono}>{project}</span>
</PropRow>
<PropRow label={<T>Status</T>}>
<span>
{runningCount}/{containers.length} running
</span>
</PropRow>
<PropRow label={<T>Working directory</T>} hidden={!first?.composeWorkingDir}>
<span className={styles.mono}>{first?.composeWorkingDir}</span>
</PropRow>
<PropRow label={<T>Compose files</T>} hidden={!first?.composeFiles.length}>
<span className={styles.inlineRow}>
{first?.composeFiles.map((file) => (
<button
key={file}
type="button"
className={styles.link}
onClick={() => void openComposeFile(file, first.composeWorkingDir)}
>
<span className={styles.mono}>{file}</span>
</button>
))}
</div>
) : (
<div className={styles.emptySection}>
<T>No named volumes</T>
</div>
)}
</span>
</PropRow>
</div>
<SectionBanner>
<T>Services</T>
</SectionBanner>
<div className={styles.composeTableWrap}>
<table className={clsx(styles.gridTable, styles.composeServicesTable)}>
<thead>
<tr>
<th>
<T>Service</T>
</th>
<th>
<T>Status</T>
</th>
<th>
<T>CPU</T>
</th>
<th>
<T>Memory</T>
</th>
<th>
<T>Network I/O</T>
</th>
<th>
<T>Block I/O</T>
</th>
<th>
<T>PIDs</T>
</th>
</tr>
</thead>
<tbody>
{containers.map((c) => {
const running = isRunning(c);
const stats = running ? activeStats[c.id] : undefined;
const cpuPct = stats ? parsePercent(stats.cpuPerc) : 0;
const memPair = stats ? parseUsagePair(stats.memUsage) : null;
const memPct = memPair ? memPair.percent : stats ? parsePercent(stats.memPerc) : 0;
return (
<tr key={c.id}>
<td className={styles.composeServiceCell}>
<button type="button" className={styles.link} onClick={() => selectContainerInTree(conn, c)}>
<span className={clsx(styles.statusDot, running ? styles.dotOk : styles.dotMuted)} />
<span className={styles.mono}>{c.name}</span>
</button>
{c.composeService && !c.name.includes(c.composeService) && (
<span className={styles.mutedMeta}>{c.composeService}</span>
)}
</td>
<td className={styles.nowrapCell}>
<StatusBadge state={c.state} text={c.status || c.state} />
</td>
<td className={styles.composeMetricCell}>
{stats ? (
<div className={styles.composeMetric}>
<span className={styles.mono}>{stats.cpuPerc}</span>
<LineProgress percent={cpuPct} />
</div>
) : running && statsLoading ? (
<Spinner size={12} />
) : (
<span className={styles.mutedMeta}>—</span>
)}
</td>
<td className={styles.composeMemoryCell}>
{stats ? (
<div className={styles.composeMetric}>
<span className={styles.mono}>
{stats.memUsage} ({stats.memPerc})
</span>
<LineProgress percent={memPct} />
</div>
) : running && statsLoading ? (
<span className={styles.mutedMeta}>
<T>Loading…</T>
</span>
) : (
<span className={styles.mutedMeta}>—</span>
)}
</td>
<td className={clsx(styles.mono, styles.nowrapCell)}>
{stats?.netIo || <span className={styles.mutedMeta}>—</span>}
</td>
<td className={clsx(styles.mono, styles.nowrapCell)}>
{stats?.blockIo || <span className={styles.mutedMeta}>—</span>}
</td>
<td className={clsx(styles.mono, styles.nowrapCell)}>
{stats?.pids || <span className={styles.mutedMeta}>—</span>}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
<SectionBanner>
<T>Volumes</T>
</SectionBanner>
{namedVolumes.length > 0 ? (
<div className={styles.chipGroup}>
{namedVolumes.map((v) => (
<VolumeLinkChip key={v.name} conn={conn} volume={v} />
))}
</div>
) : (
<div className={styles.emptySection}>
<T>No named volumes</T>
</div>
)}
</div>
);
}
-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": "无法用颜色选择器修改此颜色"
}
-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