дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-16 14:45:40 +02:00
Порівняти коміти
1
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
6e1aa55e86 |
No files matched your search
@@ -66,7 +66,7 @@ import {
|
||||
} from "./composerModel";
|
||||
import { referenceExtensions, setReferences } from "./composerEditor";
|
||||
import { referenceHover } from "./ReferenceChip";
|
||||
import { composerDraft, updateComposer, useAgents } from "./store";
|
||||
import { composerDraft, provideIdeContext, setIdeContext, updateComposer, useAgents } from "./store";
|
||||
import { ImagePreview, imageSrc } from "./ImagePreview";
|
||||
import { useAgentSettings } from "./agentSettings";
|
||||
import styles from "./Composer.module.css";
|
||||
@@ -933,6 +933,27 @@ export function Composer(props: ComposerProps) {
|
||||
return { path: activePath, rel };
|
||||
}, [activePath, projectRoot, root, text]);
|
||||
|
||||
const ideContext = useAgents((s) => s.ideContext);
|
||||
useEffect(
|
||||
() =>
|
||||
provideIdeContext(id, () => {
|
||||
const active = useEditorRegistry.getState().active;
|
||||
const path = active?.ctx.path;
|
||||
if (!active || !path || isVirtualUri(path)) return null;
|
||||
const rel = relativeTo([projectRoot, root], path);
|
||||
if (!rel || rel === ".") return null;
|
||||
const { doc, selection } = active.view.state;
|
||||
const { from, to } = selection.main;
|
||||
if (from === to) return { path, rel };
|
||||
const first = doc.lineAt(from).number;
|
||||
const end = doc.lineAt(to);
|
||||
// A selection ending at the start of a line does not take that line.
|
||||
const last = end.from === to && end.number > first ? end.number - 1 : end.number;
|
||||
return { path, rel, lines: { from: first, to: last } };
|
||||
}),
|
||||
[id, projectRoot, root],
|
||||
);
|
||||
|
||||
const showContext = images.length > 0 || attached.length > 0 || !!suggested;
|
||||
|
||||
return (
|
||||
@@ -1056,7 +1077,14 @@ export function Composer(props: ComposerProps) {
|
||||
)}
|
||||
{showContext && (
|
||||
<div className={styles.context} onMouseDown={(e) => e.stopPropagation()}>
|
||||
{suggested && (
|
||||
{suggested && ideContext && (
|
||||
<span className={styles.attachment} title={tx`${suggested.rel} is added to your request`}>
|
||||
<Icon name={fileIconName(basename(suggested.rel), suggested.rel)} size={14} />
|
||||
<span className={styles.attachmentName}>{basename(suggested.rel)}</span>
|
||||
<span className={styles.suggestionHint}>{tx("Current File")}</span>
|
||||
</span>
|
||||
)}
|
||||
{suggested && !ideContext && (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.suggestion}
|
||||
@@ -1127,6 +1155,17 @@ export function Composer(props: ComposerProps) {
|
||||
replace(from, to, before && !/\s/.test(before) ? " @" : "@");
|
||||
}}
|
||||
/>
|
||||
<IconButton
|
||||
icon="file-code"
|
||||
title={
|
||||
ideContext
|
||||
? "IDE Context Enabled: the current file and selection are added to your request"
|
||||
: "IDE Context Disabled: the current file and selection are not added to your request"
|
||||
}
|
||||
pressed={ideContext}
|
||||
className={styles.composerButton}
|
||||
onClick={() => setIdeContext(!ideContext)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="image"
|
||||
title="Attach Image…"
|
||||
|
||||
@@ -14,6 +14,7 @@ const pathCompletions = vi.fn();
|
||||
const fsProbe = vi.fn();
|
||||
const fsEntryKind = vi.fn();
|
||||
const findSymbols = vi.fn();
|
||||
const agentPrompt = vi.fn((..._args: unknown[]) => Promise.resolve({ status: "ok", data: null }));
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
@@ -28,6 +29,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
fsProbe: (path: string) => fsProbe(path),
|
||||
fsEntryKind: (path: string) => fsEntryKind(path),
|
||||
findSymbols: (query: string, filter: string, limit: number) => findSymbols(query, filter, limit),
|
||||
agentPrompt: (...args: unknown[]) => agentPrompt(...args),
|
||||
},
|
||||
};
|
||||
});
|
||||
@@ -35,7 +37,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
import { Composer } from "./Composer";
|
||||
import { registerAgentContextSource } from "@/workbench/contributions";
|
||||
import { useEditorRegistry, type TextEditorHandle } from "@/editor/api";
|
||||
import { composerDraft, updateComposer } from "./store";
|
||||
import { composerDraft, sendMessage, setIdeContext, updateComposer, useAgents } from "./store";
|
||||
import { emptyDraft, toPrompt } from "./composerModel";
|
||||
|
||||
const ID = "folders-test";
|
||||
@@ -318,6 +320,7 @@ describe("Composer editing", () => {
|
||||
describe("Composer current file", () => {
|
||||
it("offers the focused editor's file until the draft references it", () => {
|
||||
const view = {} as TextEditorHandle["view"];
|
||||
act(() => setIdeContext(false));
|
||||
act(() =>
|
||||
useEditorRegistry.setState({ active: { view, ctx: { path: "/p/src/main.ts" } as TextEditorHandle["ctx"] } }),
|
||||
);
|
||||
@@ -336,6 +339,47 @@ describe("Composer current file", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Composer IDE context", () => {
|
||||
it("sends the focused editor's file, or its selected lines, while IDE context is on", async () => {
|
||||
const view = new EditorView({ doc: "a\nb\nc\nd\n" });
|
||||
act(() => setIdeContext(true));
|
||||
act(() =>
|
||||
useEditorRegistry.setState({ active: { view, ctx: { path: "/p/src/main.ts" } as TextEditorHandle["ctx"] } }),
|
||||
);
|
||||
try {
|
||||
renderComposer();
|
||||
const toggle = screen.getByRole("button", { name: /IDE Context Enabled/ });
|
||||
expect(toggle).toHaveAttribute("aria-pressed", "true");
|
||||
expect(screen.queryByRole("button", { name: /main\.ts/ })).toBeNull();
|
||||
expect(screen.getByTitle("src/main.ts is added to your request")).toHaveTextContent("Current File");
|
||||
|
||||
const send = async (text: string) => {
|
||||
updateComposer(ID, { text });
|
||||
await sendMessage(ID, false);
|
||||
return agentPrompt.mock.lastCall?.[1];
|
||||
};
|
||||
expect(await send("explain")).toEqual({ text: "explain", files: ["/p/src/main.ts"], images: [] });
|
||||
// Lines 2–3: the selection ends at the start of line 4.
|
||||
view.dispatch({ selection: { anchor: 2, head: 6 } });
|
||||
expect(await send("explain")).toEqual({
|
||||
text: "explain\n\n@src/main.ts:2-3",
|
||||
files: ["/p/src/main.ts"],
|
||||
images: [],
|
||||
});
|
||||
// A draft that already references the file is sent as written.
|
||||
expect(await send("see @src/main.ts:1")).toEqual({ text: "see @src/main.ts:1", files: [], images: [] });
|
||||
|
||||
fireEvent.click(toggle);
|
||||
expect(useAgents.getState().ideContext).toBe(false);
|
||||
expect(screen.getByRole("button", { name: /IDE Context Disabled/ })).toHaveAttribute("aria-pressed", "false");
|
||||
expect(await send("explain")).toEqual({ text: "explain", files: [], images: [] });
|
||||
} finally {
|
||||
act(() => useEditorRegistry.setState({ active: null }));
|
||||
view.destroy();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Composer pasted code and terminal output", () => {
|
||||
const paste = (box: HTMLElement, text: string) =>
|
||||
act(() => {
|
||||
|
||||
@@ -317,6 +317,36 @@ export function mentionOf(rel: string, lines?: { from: number; to: number }): st
|
||||
export const isMentioned = (text: string, rel: string) =>
|
||||
new RegExp(`@${escapeRe(rel)}(?![\\w./-])|@${escapeRe(rel)}:`).test(text);
|
||||
|
||||
/** The file in the focused editor and the lines selected in it, for IDE context. */
|
||||
export interface IdeContext {
|
||||
path: string;
|
||||
rel: string;
|
||||
/** 1-based lines of a non-empty selection. */
|
||||
lines?: { from: number; to: number };
|
||||
}
|
||||
|
||||
/**
|
||||
* `draft` with the editor's current file added (as an attachment), or its selection as a
|
||||
* line-range mention after the text; unchanged when the draft already references the file.
|
||||
*/
|
||||
export function withIdeContext(draft: ComposerDraft, context: IdeContext | null): ComposerDraft {
|
||||
if (
|
||||
!context ||
|
||||
isMentioned(draft.text, context.rel) ||
|
||||
draft.files.some((f) => f.path === context.path && f.attached)
|
||||
)
|
||||
return draft;
|
||||
if (!context.lines)
|
||||
return { ...draft, files: [...draft.files, { path: context.path, rel: context.rel, attached: true }] };
|
||||
const mention = mentionOf(context.rel, context.lines);
|
||||
const text = draft.text.trim();
|
||||
return {
|
||||
...draft,
|
||||
text: text ? `${text}\n\n${mention}` : mention,
|
||||
files: [...draft.files, { path: context.path, rel: context.rel }],
|
||||
};
|
||||
}
|
||||
|
||||
/** The prompt to send: attached files, files still mentioned in the text (each once), and the images. */
|
||||
export function toPrompt(draft: ComposerDraft): AgentPrompt {
|
||||
const seen = new Set<string>();
|
||||
|
||||
@@ -14,6 +14,7 @@ import type {
|
||||
AgentImage,
|
||||
AgentLimit,
|
||||
AgentModelCatalog,
|
||||
AgentPrompt,
|
||||
AgentProvider,
|
||||
AgentTask,
|
||||
ExternalSession,
|
||||
@@ -35,8 +36,10 @@ import {
|
||||
isMentioned,
|
||||
isPerModelOption,
|
||||
toPrompt,
|
||||
withIdeContext,
|
||||
type ComposerDraft,
|
||||
type FileRef,
|
||||
type IdeContext,
|
||||
} from "./composerModel";
|
||||
import { withQuote } from "./conversation";
|
||||
import {
|
||||
@@ -127,6 +130,8 @@ interface AgentsState {
|
||||
/** Side conversations by task id: kept out of the task list, discarded when their view closes. */
|
||||
ephemeral: ReadonlySet<string>;
|
||||
pinnedModels: string[];
|
||||
/** Whether messages carry the editor's current file and selection. */
|
||||
ideContext: boolean;
|
||||
}
|
||||
|
||||
const DRAFT_KEY = "openidea.agents.draft.v2";
|
||||
@@ -134,6 +139,7 @@ const HISTORY_KEY = "openidea.agents.history.v1";
|
||||
const HISTORY_SIZE = 50;
|
||||
const SESSION_LOCATION_KEY = "openidea.agents.sessionLocation.v1";
|
||||
const PINNED_MODELS_KEY = "openidea.agents.pinnedModels.v1";
|
||||
const IDE_CONTEXT_KEY = "openidea.agents.ideContext.v1";
|
||||
|
||||
function load<T>(key: string, fallback: T): T {
|
||||
try {
|
||||
@@ -198,6 +204,7 @@ export const useAgents = create<AgentsState>(() => ({
|
||||
homeOpen: false,
|
||||
ephemeral: new Set<string>(),
|
||||
pinnedModels: load<string[]>(PINNED_MODELS_KEY, []),
|
||||
ideContext: load<boolean>(IDE_CONTEXT_KEY, true),
|
||||
scrollPositions: new Map(),
|
||||
}));
|
||||
|
||||
@@ -972,7 +979,7 @@ export async function startTask(
|
||||
const task = await call(
|
||||
commands.agentCreate({
|
||||
projectRoot,
|
||||
prompt: toPrompt(composer),
|
||||
prompt: promptOf(HOME, composer),
|
||||
provider: draft.provider,
|
||||
config,
|
||||
isolation,
|
||||
@@ -1086,6 +1093,28 @@ export async function importExternalSessions(
|
||||
void showError(title, failures.join("\n"));
|
||||
}
|
||||
|
||||
export function setIdeContext(on: boolean) {
|
||||
useAgents.setState({ ideContext: on });
|
||||
save(IDE_CONTEXT_KEY, on);
|
||||
}
|
||||
|
||||
/** The IDE context of each mounted composer, by draft key. */
|
||||
const ideContexts = new Map<string, () => IdeContext | null>();
|
||||
|
||||
/** Registers what composer `key` sends as IDE context; returns the unregister. */
|
||||
export function provideIdeContext(key: string, context: () => IdeContext | null): () => void {
|
||||
ideContexts.set(key, context);
|
||||
return () => {
|
||||
if (ideContexts.get(key) === context) ideContexts.delete(key);
|
||||
};
|
||||
}
|
||||
|
||||
/** The prompt of composer `key`, with the IDE context when it is on. */
|
||||
function promptOf(key: string, composer: ComposerDraft): AgentPrompt {
|
||||
const context = useAgents.getState().ideContext ? (ideContexts.get(key)?.() ?? null) : null;
|
||||
return toPrompt(withIdeContext(composer, context));
|
||||
}
|
||||
|
||||
function remember(text: string) {
|
||||
if (!text) return;
|
||||
const history = [text, ...useAgents.getState().history.filter((h) => h !== text)].slice(0, HISTORY_SIZE);
|
||||
@@ -1098,7 +1127,7 @@ export async function sendMessage(task: string, now: boolean): Promise<void> {
|
||||
const composer = composerDraft(task);
|
||||
if (!canSend(composer)) return;
|
||||
const started = generation;
|
||||
await call(commands.agentPrompt(task, toPrompt(composer), now));
|
||||
await call(commands.agentPrompt(task, promptOf(task, composer), now));
|
||||
clearSubmittedComposer(task, composer, started);
|
||||
}
|
||||
|
||||
|
||||
@@ -2009,5 +2009,8 @@
|
||||
"Select Home Directory for JDK": "Select Home Directory for JDK",
|
||||
"The selected directory is not a valid home for JDK: {path}": "The selected directory is not a valid home for JDK: {path}",
|
||||
"Add SDK": "Add SDK",
|
||||
"Remove SDK": "Remove SDK"
|
||||
"Remove SDK": "Remove SDK",
|
||||
"{rel} is added to your request": "{rel} is added to your request",
|
||||
"IDE Context Enabled: the current file and selection are added to your request": "IDE Context Enabled: the current file and selection are added to your request",
|
||||
"IDE Context Disabled: the current file and selection are not added to your request": "IDE Context Disabled: the current file and selection are not added to your request"
|
||||
}
|
||||
@@ -8397,5 +8397,8 @@
|
||||
"Select Home Directory for JDK": "选择 JDK 主目录",
|
||||
"The selected directory is not a valid home for JDK: {path}": "所选目录不是有效的 JDK 主目录:{path}",
|
||||
"Add SDK": "添加 SDK",
|
||||
"Remove SDK": "移除 SDK"
|
||||
"Remove SDK": "移除 SDK",
|
||||
"{rel} is added to your request": "{rel} 会添加到你的请求中",
|
||||
"IDE Context Enabled: the current file and selection are added to your request": "IDE 上下文已启用:当前文件和所选内容会添加到你的请求中",
|
||||
"IDE Context Disabled: the current file and selection are not added to your request": "IDE 上下文已禁用:当前文件和所选内容不会添加到你的请求中"
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача