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