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

..
Автор SHA1 Повідомлення Дата
l0ng-ai a8a63a40c8 fix(lsp): retry incomplete counts and preserve newer hints 2026-10-29 20:36:19 +08:00
l0ng-ai a8b43c27f2 fix(lsp): keep background usage counts from delaying navigation 2026-10-29 20:23:00 +08:00
14 змінених файлів з 92 додано та 820 видалено

No files matched your search

-11
Переглянути файл
@@ -39,17 +39,6 @@
text-overflow: ellipsis;
white-space: nowrap;
}
.title[data-unread] {
color: var(--fg-strong);
font-weight: 600;
}
.unreadDot {
flex: none;
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--accent);
}
.detail {
flex: 1 1 0;
min-width: 0;
+2 -10
Переглянути файл
@@ -5,13 +5,11 @@ import styles from "./Agents.module.css";
export function AgentsStatus() {
const tasks = useAgents((s) => s.tasks);
const unread = useAgents((s) => s.unread);
const list = [...tasks.values()];
const unseen = list.filter((t) => unread.has(t.id)).sort((a, b) => (b.updatedMs ?? 0) - (a.updatedMs ?? 0));
const input = list.filter((t) => t.status === "needsInput");
const running = list.filter((t) => t.status === "running" || t.status === "starting").length;
if (!input.length && !running && !unseen.length) return null;
const target = input[0] ?? unseen[0] ?? list.find((t) => t.status === "running" || t.status === "starting");
if (!input.length && !running) return null;
const target = input[0] ?? list.find((t) => t.status === "running");
return (
<button type="button" className={styles.statusItem} onClick={() => target && openTask(target.id)}>
{input.length > 0 && (
@@ -26,12 +24,6 @@ export function AgentsStatus() {
{running} <T>running</T>
</span>
)}
{unseen.length > 0 && (
<span className={styles.statusPart}>
<span className={styles.unreadDot} aria-hidden="true" />
{unseen.length} <T>unread</T>
</span>
)}
</button>
);
}
-209
Переглянути файл
@@ -1,209 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import type { AgentTask } from "@/bindings";
import { registerActions } from "@/platform/actions";
import type { EditorInput } from "@/workbench/contributions";
import { confirmChecked, showError } from "@/workbench/messages";
import { ContextMenuHost, hideContextMenu } from "@/ui";
import { AgentsView } from "./AgentsView";
import { SESSION_KIND } from "./model";
import { archiveTask, deleteTask, openTask, useAgents } from "./store";
import { taskActions } from "./taskActions";
const editor = vi.hoisted(() => ({
active: undefined as EditorInput | undefined,
listener: undefined as ((input: EditorInput) => void) | undefined,
}));
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
maybeEditorService: () => ({
activeInput: () => editor.active,
onActiveInputChange: (listener: typeof editor.listener) => {
editor.listener = listener;
return () => {
editor.listener = undefined;
};
},
}),
}));
vi.mock("./store", async (original) => ({
...(await original<typeof import("./store")>()),
openTask: vi.fn((id: string) => editor.listener?.({ kind: "agent-session", key: id, data: { task: id } })),
archiveTask: vi.fn(async () => {}),
deleteTask: vi.fn(async () => {}),
}));
vi.mock("@/workbench/messages", () => ({
confirmChecked: vi.fn(async () => ({ checked: false })),
showError: vi.fn(async () => {}),
}));
function task(
id: string,
status: AgentTask["status"] = "ready",
isolation: AgentTask["isolation"] = "local",
): AgentTask {
return {
id,
title: id,
status,
isolation,
provider: "codex",
model: null,
cwd: "/project",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
};
}
const row = (id: string) => screen.getByText(id).closest('[role="treeitem"]')!;
const select = (id: string, modifiers: MouseEventInit = {}) =>
fireEvent.mouseDown(row(id), { button: 0, ...modifiers });
const selectedTasks = () =>
screen
.queryAllByRole("treeitem", { selected: true })
.filter((item) => item.getAttribute("aria-level") === "2")
.map((item) => item.querySelector("[title]")?.getAttribute("title"));
const context = (id: string) => {
fireEvent.mouseDown(row(id), { button: 2 });
fireEvent.contextMenu(row(id));
};
let dispose: () => void;
beforeEach(() => {
vi.clearAllMocks();
editor.active = undefined;
vi.mocked(confirmChecked).mockResolvedValue({ checked: false });
useAgents.setState({
loaded: true,
error: null,
tasks: new Map([task("one"), task("two"), task("three"), task("four")].map((t) => [t.id, t])),
});
dispose = registerActions(taskActions);
});
afterEach(() => {
dispose();
hideContextMenu();
});
function setup() {
render(
<>
<AgentsView />
<ContextMenuHost />
</>,
);
}
describe("Agents selection", () => {
it("extends and shrinks a range without opening its lead or losing selection to an editor echo", () => {
setup();
select("one");
select("three", { shiftKey: true });
expect(selectedTasks()).toEqual(["one", "two", "three"]);
expect(openTask).toHaveBeenCalledTimes(1);
act(() => editor.listener?.({ kind: SESSION_KIND, key: "one", data: { task: "one" } }));
expect(selectedTasks()).toEqual(["one", "two", "three"]);
select("two", { shiftKey: true });
expect(selectedTasks()).toEqual(["one", "two"]);
select("four");
expect(selectedTasks()).toEqual(["four"]);
});
it("keeps the initial active task as the anchor for repeated keyboard extension", () => {
editor.active = { kind: SESSION_KIND, key: "one", data: { task: "one" } };
setup();
const tree = screen.getByRole("tree");
fireEvent.keyDown(tree, { key: "ArrowDown", shiftKey: true });
fireEvent.keyDown(tree, { key: "ArrowDown", shiftKey: true });
expect(selectedTasks()).toEqual(["one", "two", "three"]);
expect(openTask).not.toHaveBeenCalled();
});
it.each(["metaKey", "ctrlKey"])("toggles individual tasks with %s", (modifier) => {
setup();
select("one");
select("three", { [modifier]: true });
expect(selectedTasks()).toEqual(["one", "three"]);
select("three", { [modifier]: true });
expect(selectedTasks()).toEqual(["one"]);
expect(openTask).toHaveBeenCalledTimes(1);
});
});
describe("Agents bulk actions", () => {
it("deletes the right-clicked selection after one confirmation, excluding group headers", async () => {
const tasks = [task("one", "running"), task("two"), task("three")];
useAgents.setState({ tasks: new Map(tasks.map((t) => [t.id, t])) });
setup();
select("one");
select("three", { shiftKey: true });
context("two");
fireEvent.click(screen.getByRole("menuitem", { name: "Delete (3)…" }));
await waitFor(() => expect(deleteTask).toHaveBeenCalledTimes(3));
expect(confirmChecked).toHaveBeenCalledTimes(1);
expect(confirmChecked).toHaveBeenCalledWith(
expect.objectContaining({ message: expect.stringContaining("3 agent tasks") }),
);
expect(vi.mocked(deleteTask).mock.calls).toEqual([
["one", false],
["two", false],
["three", false],
]);
});
it("right-clicking outside the selection targets only that task", async () => {
setup();
select("one");
select("two", { shiftKey: true });
context("four");
fireEvent.click(screen.getByRole("menuitem", { name: "Delete…" }));
await waitFor(() => expect(deleteTask).toHaveBeenCalledExactlyOnceWith("four", false));
});
it("archives only eligible tasks in a mixed selection", async () => {
const tasks = [task("one", "running"), task("two"), task("three", "archived")];
useAgents.setState({ tasks: new Map(tasks.map((t) => [t.id, t])) });
setup();
fireEvent.doubleClick(screen.getByText("Archived"));
select("one");
select("three", { shiftKey: true });
context("two");
fireEvent.click(screen.getByRole("menuitem", { name: "Archive (1)" }));
await waitFor(() => expect(archiveTask).toHaveBeenCalledExactlyOnceWith("two"));
});
it("cancels the whole batch", async () => {
vi.mocked(confirmChecked).mockResolvedValue(null);
await taskActions.find((action) => action.id === "agents.deleteTasks")!.run({ ctx: {}, arg: ["one", "two"] });
expect(deleteTask).not.toHaveBeenCalled();
});
it.each([false, true])("applies worktree cleanup (%s) only to worktree tasks", async (checked) => {
const tasks = [task("one"), task("two", "ready", "worktree")];
useAgents.setState({ tasks: new Map(tasks.map((t) => [t.id, t])) });
vi.mocked(confirmChecked).mockResolvedValue({ checked });
await taskActions.find((action) => action.id === "agents.deleteTasks")!.run({ ctx: {}, arg: ["one", "two"] });
expect(vi.mocked(deleteTask).mock.calls).toEqual([
["one", false],
["two", checked],
]);
});
it("continues after an error and reports the failed task", async () => {
vi.mocked(deleteTask).mockRejectedValueOnce(new Error("Cannot remove worktree"));
await taskActions.find((action) => action.id === "agents.deleteTasks")!.run({ ctx: {}, arg: ["one", "two"] });
expect(deleteTask).toHaveBeenCalledTimes(2);
expect(showError).toHaveBeenCalledWith("Cannot delete agent tasks", "one: Cannot remove worktree");
});
});
+36 -23
Переглянути файл
@@ -1,13 +1,14 @@
/** Agents tool window: tasks grouped by what they need from the user. */
import { useEffect, useMemo, useState } from "react";
import type { AgentStatus as Status, AgentTask } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { maybeEditorService, type EditorInput } from "@/workbench/contributions";
import { EmptyState, Icon, IconButton, Spinner, T, Tree, showContextMenu } from "@/ui";
import { SESSION_KIND, age, branchLabel, groupTasks, type TaskGroup } from "./model";
import { openHome, openTask, useAgents } from "./store";
import { taskMenu } from "./taskActions";
import { confirmChecked } from "@/workbench/messages";
import { EmptyState, Icon, IconButton, Spinner, T, Tree, showContextMenu, type MenuItem } from "@/ui";
import { SESSION_KIND, age, branchLabel, groupTasks, isBusy, type TaskGroup } from "./model";
import { archiveTask, deleteTask, openHome, openTask, useAgents } from "./store";
import styles from "./Agents.module.css";
import { useTx } from "@/platform/i18n";
import { tx } from "@/platform/i18n";
export function AgentsHeaderActions() {
return (
@@ -43,11 +44,9 @@ export function TaskStatusIcon({ status }: { status: Status }) {
}
export function AgentsView() {
const tx = useTx();
const loaded = useAgents((s) => s.loaded);
const error = useAgents((s) => s.error);
const tasks = useAgents((s) => s.tasks);
const unread = useAgents((s) => s.unread);
const providers = useAgents((s) => s.providers);
const [collapsed, setCollapsed] = useState<Set<string>>(() => new Set(["g:archived"]));
const [selected, setSelected] = useState<Set<string>>(() => {
@@ -60,7 +59,7 @@ export function AgentsView() {
maybeEditorService()?.onActiveInputChange?.((input) => {
const task = sessionTask(input);
if (!task) return;
setSelected((current) => (current.has(task) ? current : new Set([task])));
setSelected(new Set([task]));
const group = groupTasks(useAgents.getState().tasks.values()).find((g) => g.tasks.some((t) => t.id === task));
const key = group && `g:${group.status}`;
if (key) setCollapsed((c) => (c.has(key) ? new Set([...c].filter((k) => k !== key)) : c));
@@ -101,17 +100,10 @@ export function AgentsView() {
selected={selected}
onSelectionChange={(sel, lead) => {
setSelected(sel);
if (sel.size === 1 && lead?.kind === "task" && sel.has(lead.task.id)) openTask(lead.task.id);
if (lead?.kind === "task") openTask(lead.task.id);
}}
onActivate={(n) => n.kind === "task" && openTask(n.task.id)}
onContextMenu={(n, sel, e) => {
if (n?.kind !== "task") return;
const selection = [...sel].flatMap((id) => {
const task = tasks.get(id);
return task ? [task] : [];
});
showContextMenu(e, taskMenu(selection));
}}
onContextMenu={(n, _sel, e) => n?.kind === "task" && showContextMenu(e, taskMenu(n.task))}
renderNode={(n) =>
n.kind === "group" ? (
<span className={styles.row}>
@@ -123,12 +115,7 @@ export function AgentsView() {
) : (
<span className={styles.row} title={n.task.error ?? n.task.title}>
<TaskStatusIcon status={n.task.status} />
<span className={styles.title} data-unread={unread.has(n.task.id) || undefined}>
{n.task.title}
</span>
{unread.has(n.task.id) && (
<span className={styles.unreadDot} role="img" aria-label={tx("Unread")} title={tx("Unread")} />
)}
<span className={styles.title}>{n.task.title}</span>
<span className={styles.detail}>
{providerName(n.task.provider)}
{n.task.isolation === "worktree" ? ` · ${branchLabel(n.task.branch)}` : ""}
@@ -149,3 +136,29 @@ export function AgentsView() {
</div>
);
}
function taskMenu(task: AgentTask): MenuItem[] {
const busy = isBusy(task.status);
return [
{ label: "Open", run: () => openTask(task.id) },
{ label: "Open in Terminal", icon: "terminal", run: () => void executeAction("terminal.openAt", task.cwd) },
{ kind: "separator" },
{ label: "Archive", disabled: busy || task.status === "archived", run: () => void archiveTask(task.id) },
{ label: "Delete…", run: () => void confirmDelete(task) },
];
}
async function confirmDelete(task: AgentTask) {
const worktree = task.isolation === "worktree";
const r = await confirmChecked({
title: "Delete Agent Task",
message: worktree
? tx`Delete “${task.title}”? Its branch ${task.branch ?? ""} is kept.`
: tx`Delete “${task.title}”? Files it changed are kept.`,
ok: "Delete",
icon: "warning",
checkbox: worktree ? "Also remove its worktree folder" : undefined,
checked: worktree,
});
if (r) await deleteTask(task.id, worktree && r.checked);
}
+11 -16
Переглянути файл
@@ -98,26 +98,21 @@
opacity: 1;
}
/* `@` / `/` completion; Popup keeps the list within the viewport. */
.caretMirror {
position: fixed;
top: 0;
left: 0;
box-sizing: border-box;
visibility: hidden;
pointer-events: none;
white-space: pre-wrap;
overflow-wrap: break-word;
}
/* `@` / `/` completion, above the box like a code-completion popup. */
.popup {
width: min(560px, calc(100vw - 12px));
border-radius: var(--radius-popup);
cursor: default;
}
.items {
position: absolute;
left: 0;
bottom: calc(100% + 4px);
z-index: 10;
width: min(560px, 100%);
max-height: 300px;
overflow: auto;
padding: 4px 0;
border: 1px solid var(--border-popup);
border-radius: var(--radius-popup);
background: var(--bg-popup);
box-shadow: var(--shadow-popup);
cursor: default;
}
.item {
display: flex;
+34 -49
Переглянути файл
@@ -10,7 +10,7 @@ import { call, commands, isTauri } from "@/platform/ipc";
import { useTx } from "@/platform/i18n";
import { basename } from "@/platform/project";
import { notifications, OWNS_FILE_DROP } from "@/workbench/contributions";
import { Icon, IconButton, Popup, fileIconName } from "@/ui";
import { Icon, IconButton, fileIconName } from "@/ui";
import {
IMAGE_EXTENSIONS,
MAX_IMAGE_BYTES,
@@ -27,7 +27,6 @@ import {
type FileRef,
} from "./composerModel";
import { composerDraft, updateComposer, useAgents } from "./store";
import { useCompletionAnchor } from "./useCompletionAnchor";
import styles from "./Composer.module.css";
import { isImeKey } from "@/platform/ime";
@@ -128,14 +127,13 @@ export function Composer(props: ComposerProps) {
.map((command) => ({ kind: "command", command }));
}, [completion, files, props.commands]);
const open = !!completion && items.length > 0;
const completionAnchor = useCompletionAnchor(ref, open ? completion.to : null, text);
const setText = (value: string, caret?: number, restoreSelection = true) => {
const setText = (value: string, caret?: number) => {
updateComposer(id, { text: value });
const c = caret ?? value.length;
setCompletion(completionAt(value, c));
setActive(0);
if (caret !== undefined && restoreSelection) {
if (caret !== undefined) {
requestAnimationFrame(() => {
ref.current?.focus();
ref.current?.setSelectionRange(caret, caret);
@@ -283,49 +281,36 @@ export function Composer(props: ComposerProps) {
{...OWNS_FILE_DROP}
onClick={() => ref.current?.focus()}
>
{open && completionAnchor && (
<Popup
open
anchor={completionAnchor}
placement="bottom-start"
autoFocus={false}
restoreFocus={false}
closeOnOutsideClick={false}
onClose={() => setCompletion(null)}
className={styles.popup}
role="listbox"
aria-label={tx(completion.kind === "file" ? "Files" : "Commands")}
>
<div className={styles.items}>
{items.map((item, i) => (
<div
key={item.kind === "file" ? item.path : item.command.name}
role="option"
aria-selected={i === active}
className={clsx(styles.item, i === active && styles.active)}
onMouseEnter={() => setActive(i)}
onMouseDown={(e) => {
e.preventDefault();
accept(item);
}}
>
{item.kind === "file" ? (
<>
<Icon name={fileIconName(basename(item.rel))} size={16} />
<span className={styles.itemName}>{basename(item.rel)}</span>
<span className={styles.itemDetail}>{item.rel}</span>
</>
) : (
<>
<span className={styles.itemName}>/{item.command.name}</span>
{item.command.hint && <span className={styles.itemHint}>{item.command.hint}</span>}
<span className={styles.itemDetail}>{item.command.description}</span>
</>
)}
</div>
))}
</div>
</Popup>
{open && (
<div className={styles.popup} role="listbox" aria-label={tx(completion.kind === "file" ? "Files" : "Commands")}>
{items.map((item, i) => (
<div
key={item.kind === "file" ? item.path : item.command.name}
role="option"
aria-selected={i === active}
className={clsx(styles.item, i === active && styles.active)}
onMouseEnter={() => setActive(i)}
onMouseDown={(e) => {
e.preventDefault();
accept(item);
}}
>
{item.kind === "file" ? (
<>
<Icon name={fileIconName(basename(item.rel))} size={16} />
<span className={styles.itemName}>{basename(item.rel)}</span>
<span className={styles.itemDetail}>{item.rel}</span>
</>
) : (
<>
<span className={styles.itemName}>/{item.command.name}</span>
{item.command.hint && <span className={styles.itemHint}>{item.command.hint}</span>}
<span className={styles.itemDetail}>{item.command.description}</span>
</>
)}
</div>
))}
</div>
)}
{images.length > 0 && (
<div className={styles.images} onClick={(e) => e.stopPropagation()}>
@@ -354,7 +339,7 @@ export function Composer(props: ComposerProps) {
value={text}
aria-label={tx("Message")}
placeholder={tx(props.placeholder)}
onChange={(e) => setText(e.target.value, e.target.selectionStart, false)}
onChange={(e) => setText(e.target.value, undefined)}
onSelect={(e) => setCompletion(completionAt(e.currentTarget.value, e.currentTarget.selectionStart))}
onBlur={() => setCompletion(null)}
onKeyDown={onKeyDown}
-18
Переглянути файл
@@ -1,6 +1,5 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import type { AgentCommand, AgentProvider } from "@/bindings";
const agentCommands = vi.fn();
@@ -87,21 +86,4 @@ describe("New Task composer commands", () => {
fireEvent.change(box, { target: { value: "/com" } });
expect(await screen.findByRole("option")).toHaveTextContent("/compact");
});
it("completes at the caret without replacing the rest of the message", async () => {
const user = userEvent.setup();
agentCommands.mockResolvedValue({ status: "ok", data: [command("compact", "Free up context")] });
render(<HomeEditor />);
await waitFor(() => expect(agentCommands).toHaveBeenCalled());
const box = screen.getByRole("textbox");
box.focus();
fireEvent.change(box, { target: { value: "/com keep this context", selectionStart: 4, selectionEnd: 4 } });
expect(await screen.findByRole("option")).toHaveTextContent("/compact");
expect(box).toHaveFocus();
await user.keyboard("{Tab}");
expect(box).toHaveValue("/compact keep this context");
await waitFor(() => expect(screen.queryByRole("listbox", { name: "Commands" })).toBeNull());
expect(agentCreate).not.toHaveBeenCalled();
});
});
+1 -5
Переглянути файл
@@ -21,7 +21,6 @@ import { HOME_KIND, REGISTRY_PAGE, SESSION_KIND, TOOL_WINDOW } from "./model";
import { sendPaths, sendSelection } from "./references";
import { focusedSession } from "./sessionFocus";
import { connect, disconnect, openHome, useAgents } from "./store";
import { taskActions } from "./taskActions";
/** Settings › Tools › Agents (also used by the Settings window). */
export function activateSettingsPages(): () => void {
@@ -55,9 +54,7 @@ export function activate(): () => void {
component: lazyComponent(() => import("./AgentsView").then((m) => m.AgentsView)),
headerActions: lazyComponent(() => import("./AgentsView").then((m) => m.AgentsHeaderActions)),
useBadge: () => {
const n = useAgents(
(s) => [...s.tasks.values()].filter((t) => t.status === "needsInput" || s.unread.has(t.id)).length,
);
const n = useAgents((s) => [...s.tasks.values()].filter((t) => t.status === "needsInput").length);
return n || null;
},
}),
@@ -90,7 +87,6 @@ export function activate(): () => void {
: [],
}),
registerActions([
...taskActions,
{
id: "agents.findInConversation",
title: "Find in Conversation",
+7 -58
Переглянути файл
@@ -44,8 +44,6 @@ interface AgentsState {
/** Why the tasks could not be loaded. */
error: string | null;
tasks: Map<string, AgentTask>;
/** Tasks with unseen replies or status changes in this project. */
unread: Set<string>;
/** Entries of the tasks (and subagents) opened in this window, by `entriesKey`. */
entries: Map<string, AgentEntry[]>;
changes: Map<string, AgentChange[]>;
@@ -87,7 +85,6 @@ export const useAgents = create<AgentsState>(() => ({
loaded: false,
error: null,
tasks: new Map(),
unread: new Set(),
entries: new Map(),
changes: new Map(),
providers: [],
@@ -113,40 +110,11 @@ export function updateComposer(key: string, patch: Partial<ComposerDraft>) {
}));
}
/** Session tabs on screen; a task can be shown in more than one split. */
const visible = new Map<string, number>();
const windowFocused = () => document.visibilityState !== "hidden" && document.hasFocus();
const viewing = (task: string) => visible.has(task) && windowFocused();
function setUnread(task: string, value: boolean) {
const s = useAgents.getState();
if (s.unread.has(task) === value) return;
const unread = new Set(s.unread);
if (value) unread.add(task);
else unread.delete(task);
useAgents.setState({ unread });
}
function markUnread(task: string) {
const current = useAgents.getState().tasks.get(task);
if (current && current.status !== "archived" && !viewing(task)) setUnread(task, true);
}
/** Session tabs on screen; their tasks do not notify. */
const visible = new Set<string>();
export function markVisible(task: string): () => void {
visible.set(task, (visible.get(task) ?? 0) + 1);
const read = () => {
if (viewing(task)) setUnread(task, false);
};
read();
window.addEventListener("focus", read);
document.addEventListener("visibilitychange", read);
return () => {
const count = (visible.get(task) ?? 1) - 1;
if (count) visible.set(task, count);
else visible.delete(task);
window.removeEventListener("focus", read);
document.removeEventListener("visibilitychange", read);
};
visible.add(task);
return () => visible.delete(task);
}
let generation = 0;
@@ -186,14 +154,7 @@ export async function connect(): Promise<void> {
export function disconnect() {
generation++;
useAgents.setState({
loaded: false,
error: null,
tasks: new Map(),
unread: new Set(),
entries: new Map(),
changes: new Map(),
});
useAgents.setState({ loaded: false, error: null, tasks: new Map(), entries: new Map(), changes: new Map() });
}
function onEvent(e: AgentEvent) {
@@ -202,8 +163,6 @@ function onEvent(e: AgentEvent) {
case "task": {
const prev = s.tasks.get(e.task.id);
useAgents.setState({ tasks: new Map(s.tasks).set(e.task.id, e.task) });
if (e.task.status === "archived") setUnread(e.task.id, false);
else if (attentionChange(prev?.status, e.task.status)) markUnread(e.task.id);
notifyChange(prev, e.task);
if (prev?.status !== e.task.status && !isBusy(e.task.status)) {
void refreshChanges(e.task.id);
@@ -216,9 +175,7 @@ function onEvent(e: AgentEvent) {
tasks.delete(e.id);
const composers = new Map(s.composers);
composers.delete(e.id);
const unread = new Set(s.unread);
unread.delete(e.id);
useAgents.setState({ tasks, composers, unread });
useAgents.setState({ tasks, composers });
editorService().closeInput?.(sessionKey(e.id));
break;
}
@@ -229,14 +186,6 @@ function onEvent(e: AgentEvent) {
break;
}
case "entry": {
if (
!e.subagent &&
((e.entry.type === "agent" && e.entry.text.trim()) ||
e.entry.type === "error" ||
(e.entry.type === "permission" && e.entry.chosen === null))
) {
markUnread(e.task);
}
const key = entriesKey(e.task, e.subagent);
const current = s.entries.get(key);
if (!current) return;
@@ -254,7 +203,7 @@ function onEvent(e: AgentEvent) {
function notifyChange(prev: AgentTask | undefined, task: AgentTask) {
const change = attentionChange(prev?.status, task.status);
if (!change) return;
if (viewing(task.id)) return;
if (visible.has(task.id) && document.hasFocus()) return;
const body =
change === "input"
? "Waiting for your answer"
-115
Переглянути файл
@@ -1,115 +0,0 @@
import type { AgentTask } from "@/bindings";
import type { Action } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import type { MenuItem } from "@/ui";
import { showError, confirmChecked } from "@/workbench/messages";
import { isBusy } from "./model";
import { archiveTask, deleteTask, openTask, useAgents } from "./store";
const canArchive = (task: AgentTask) => !isBusy(task.status) && task.status !== "archived";
function resolveTasks(arg: unknown): AgentTask[] {
if (!Array.isArray(arg)) return [];
return [...new Set(arg)].flatMap((id: unknown) => {
const task = typeof id === "string" ? useAgents.getState().tasks.get(id) : undefined;
return task ? [task] : [];
});
}
async function runTasks(tasks: AgentTask[], run: (task: AgentTask) => Promise<unknown>, title: string) {
const errors: string[] = [];
for (const task of tasks) {
try {
await run(task);
} catch (error) {
errors.push(`${task.title}: ${error instanceof Error ? error.message : String(error)}`);
}
}
if (errors.length) await showError(title, errors.join("\n"));
}
async function confirmDelete(tasks: AgentTask[]) {
if (!tasks.length) return;
const task = tasks[0]!;
const multiple = tasks.length > 1;
const worktree = tasks.some((t) => t.isolation === "worktree");
const r = await confirmChecked({
title: multiple ? "Delete Agent Tasks" : "Delete Agent Task",
message: multiple
? tx`Delete ${tasks.length} agent tasks? Their branches and files outside worktrees are kept.`
: worktree
? tx`Delete “${task.title}”? Its branch ${task.branch ?? ""} is kept.`
: tx`Delete “${task.title}”? Files it changed are kept.`,
ok: "Delete",
icon: "warning",
checkbox: worktree
? multiple
? "Also remove their worktree folders"
: "Also remove its worktree folder"
: undefined,
checked: worktree,
});
if (r)
await runTasks(
tasks,
(t) => deleteTask(t.id, t.isolation === "worktree" && r.checked),
tx("Cannot delete agent tasks"),
);
}
export const taskActions: Action[] = [
{
id: "agents.openTask",
title: "Open Agent Task",
category: "Agents",
hidden: true,
run: ({ arg }) => {
if (typeof arg === "string") openTask(arg);
},
},
{
id: "agents.archiveTasks",
title: "Archive Agent Tasks",
category: "Agents",
hidden: true,
run: ({ arg }) =>
runTasks(resolveTasks(arg).filter(canArchive), (task) => archiveTask(task.id), tx("Cannot archive agent tasks")),
},
{
id: "agents.deleteTasks",
title: "Delete Agent Tasks",
category: "Agents",
hidden: true,
run: ({ arg }) => confirmDelete(resolveTasks(arg)),
},
];
export function taskMenu(tasks: AgentTask[]): MenuItem[] {
if (!tasks.length) return [];
const ids = tasks.map((task) => task.id);
const task = tasks[0]!;
const multiple = tasks.length > 1;
const archivable = tasks.filter(canArchive).length;
return [
...(!multiple
? ([
{ kind: "action", action: "agents.openTask", label: "Open", arg: task.id },
{ kind: "action", action: "terminal.openAt", label: "Open in Terminal", icon: "terminal", arg: task.cwd },
{ kind: "separator" },
] satisfies MenuItem[])
: []),
{
kind: "action",
action: "agents.archiveTasks",
label: multiple ? tx`Archive (${archivable})` : "Archive",
arg: ids,
disabled: !archivable,
},
{
kind: "action",
action: "agents.deleteTasks",
label: multiple ? tx`Delete (${tasks.length})…` : "Delete…",
arg: ids,
},
];
}
-224
Переглянути файл
@@ -1,224 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
import type { AgentEntry, AgentEvent, AgentTask } from "@/bindings";
import { useContributions } from "@/workbench/contributions";
import { AgentsView } from "./AgentsView";
import { AgentsStatus } from "./AgentsStatus";
import { activate } from "./index";
import { connect, disconnect, markVisible, useAgents } from "./store";
const backend = vi.hoisted(() => ({
channel: null as { onmessage: (event: AgentEvent) => void } | null,
tasks: [] as AgentTask[],
notify: vi.fn(),
openInput: vi.fn(),
closeInput: vi.fn(),
}));
vi.mock("@tauri-apps/api/core", async (original) => ({
...(await original<typeof import("@tauri-apps/api/core")>()),
Channel: class {
onmessage = () => {};
},
}));
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
isTauri: () => true,
commands: {
agentSubscribe: async (channel: typeof backend.channel) => {
backend.channel = channel;
return { status: "ok", data: backend.tasks };
},
agentProviders: async () => ({ status: "ok", data: [] }),
agentChanges: async () => ({ status: "ok", data: [] }),
},
}));
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
editorService: () => ({ openInput: backend.openInput, closeInput: backend.closeInput }),
notifications: () => ({ notify: backend.notify }),
}));
const task = (id: string, status: AgentTask["status"] = "running"): AgentTask => ({
id,
title: id,
status,
provider: "codex",
isolation: "local",
model: null,
cwd: "/project",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
});
const emit = (event: AgentEvent) => act(() => backend.channel!.onmessage(event));
const reply = (id = "one", text = "New reply") =>
emit({ type: "entry", task: id, subagent: null, index: 0, entry: { type: "agent", text } });
const visible: Array<() => void> = [];
const show = (id = "one") => {
let hide!: () => void;
act(() => {
hide = markVisible(id);
});
visible.push(hide);
return () => visible.splice(visible.indexOf(hide), 1)[0]!();
};
beforeEach(async () => {
vi.clearAllMocks();
vi.spyOn(document, "hasFocus").mockReturnValue(true);
vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
disconnect();
backend.tasks = [task("one"), task("two", "ready")];
await connect();
});
afterEach(() => {
visible.splice(0).forEach((hide) => hide());
disconnect();
vi.restoreAllMocks();
});
describe("agent unread activity", () => {
it("does not mark historical tasks unread, but tracks replies even without loaded entries", () => {
expect(useAgents.getState().unread.size).toBe(0);
reply();
reply("one", "New reply, streamed further");
reply("two");
expect([...useAgents.getState().unread]).toEqual(["one", "two"]);
expect(useAgents.getState().entries.size).toBe(0);
expect(backend.notify).not.toHaveBeenCalled();
});
it.each(["ready", "needsInput", "failed", "limited"] as const)("marks background %s transitions unread", (status) => {
emit({ type: "task", task: task("one", status) });
expect(useAgents.getState().unread.has("one")).toBe(true);
expect(backend.notify).toHaveBeenCalledTimes(1);
show();
emit({ type: "task", task: task("one", status) });
expect(useAgents.getState().unread.size).toBe(0);
expect(backend.notify).toHaveBeenCalledTimes(1);
});
it("ignores user messages, thoughts, empty replies and subagent streaming", () => {
const entries: AgentEntry[] = [
{ type: "user", text: "Do this", attachments: [] },
{ type: "thought", text: "Thinking" },
{ type: "agent", text: " " },
];
for (const entry of entries) emit({ type: "entry", task: "one", subagent: null, index: 0, entry });
emit({ type: "entry", task: "one", subagent: "child", index: 0, entry: { type: "agent", text: "Working" } });
emit({ type: "task", task: { ...task("one"), title: "Renamed" } });
expect(useAgents.getState().unread.size).toBe(0);
});
it("clears only the viewed task and keeps reading while either split shows it", () => {
reply();
reply("two");
const hide = show();
show();
hide();
reply();
emit({ type: "task", task: task("one", "ready") });
expect([...useAgents.getState().unread]).toEqual(["two"]);
expect(backend.notify).not.toHaveBeenCalled();
});
it("keeps a visible session unread while the window is unfocused, then clears on focus", () => {
vi.mocked(document.hasFocus).mockReturnValue(false);
reply();
show();
expect(useAgents.getState().unread.has("one")).toBe(true);
vi.mocked(document.hasFocus).mockReturnValue(true);
fireEvent(window, new Event("focus"));
expect(useAgents.getState().unread.size).toBe(0);
reply();
expect(useAgents.getState().unread.size).toBe(0);
});
it("does not read hidden windows and removes focus listeners when the session closes", () => {
vi.spyOn(document, "visibilityState", "get").mockReturnValue("hidden");
const hide = show();
reply();
fireEvent(window, new Event("focus"));
expect(useAgents.getState().unread.has("one")).toBe(true);
vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
fireEvent(document, new Event("visibilitychange"));
expect(useAgents.getState().unread.size).toBe(0);
hide();
reply();
fireEvent(window, new Event("focus"));
expect(useAgents.getState().unread.has("one")).toBe(true);
});
it("cleans up archived and deleted tasks, ignores late replies, and resets on project switch", async () => {
reply();
reply("two");
emit({ type: "task", task: task("one", "archived") });
reply();
expect([...useAgents.getState().unread]).toEqual(["two"]);
emit({ type: "removed", id: "two" });
reply("two");
expect(useAgents.getState().unread.size).toBe(0);
emit({ type: "task", task: task("one") });
reply();
const oldChannel = backend.channel!;
disconnect();
backend.tasks = [task("other")];
await connect();
oldChannel.onmessage({ type: "task", task: task("one", "ready") });
expect(useAgents.getState().unread.size).toBe(0);
expect([...useAgents.getState().tasks.keys()]).toEqual(["other"]);
});
});
describe("agent unread indicators", () => {
it("shows a dot on the task and a clickable status count even when all tasks are idle", () => {
emit({ type: "task", task: task("one", "ready") });
render(
<>
<AgentsView />
<AgentsStatus />
</>,
);
expect(screen.getByRole("img", { name: "Unread" })).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "1 unread" }));
expect(backend.openInput).toHaveBeenCalledWith(expect.objectContaining({ data: { task: "one", title: "one" } }), {
focus: true,
});
show();
expect(screen.queryByRole("img", { name: "Unread" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: /unread/ })).not.toBeInTheDocument();
});
it("counts unread and needs-input tasks once each in the sidebar badge", () => {
const dispose = activate();
try {
const useBadge = useContributions.getState().toolWindows.get("agents")!.useBadge!;
function Badge() {
return <span data-testid="badge">{useBadge()}</span>;
}
act(() =>
useAgents.setState({
tasks: new Map([task("one", "needsInput"), task("two", "ready")].map((t) => [t.id, t])),
unread: new Set(["one", "two"]),
}),
);
render(<Badge />);
expect(screen.getByTestId("badge")).toHaveTextContent("2");
show("two");
expect(screen.getByTestId("badge")).toHaveTextContent("1");
show("one");
expect(screen.getByTestId("badge")).toHaveTextContent("1");
} finally {
act(dispose);
}
});
});
-69
Переглянути файл
@@ -1,69 +0,0 @@
import { useLayoutEffect, useState, type RefObject } from "react";
import type { VirtualElement } from "@floating-ui/react-dom";
import styles from "./Composer.module.css";
const TEXT_STYLES = [
"fontFamily",
"fontSize",
"fontWeight",
"fontStyle",
"fontVariant",
"lineHeight",
"letterSpacing",
"wordSpacing",
"textIndent",
"textAlign",
"textTransform",
"tabSize",
"paddingTop",
"paddingRight",
"paddingBottom",
"paddingLeft",
] as const;
/** A textarea has no text DOM to measure; mirror its wrapping and scroll offset. */
function caretRect(textarea: HTMLTextAreaElement, caret: number): DOMRect {
const computed = getComputedStyle(textarea);
const mirror = document.createElement("div");
mirror.className = styles.caretMirror ?? "";
for (const property of TEXT_STYLES) mirror.style[property] = computed[property];
mirror.style.width = `${textarea.clientWidth}px`;
mirror.textContent = textarea.value.slice(0, caret);
const marker = document.createElement("span");
marker.textContent = textarea.value.slice(caret) || "\u200b";
mirror.append(marker);
document.body.append(mirror);
try {
const box = textarea.getBoundingClientRect();
const lineHeight = parseFloat(computed.lineHeight) || parseFloat(computed.fontSize) * 1.5;
return new DOMRect(
box.left + textarea.clientLeft + marker.offsetLeft - textarea.scrollLeft,
box.top + textarea.clientTop + marker.offsetTop - textarea.scrollTop,
0,
lineHeight,
);
} finally {
mirror.remove();
}
}
export function useCompletionAnchor(
ref: RefObject<HTMLTextAreaElement | null>,
caret: number | null,
text: string,
): VirtualElement | null {
const [anchor, setAnchor] = useState<VirtualElement | null>(null);
useLayoutEffect(() => {
const textarea = ref.current;
if (!textarea || caret === null) {
setAnchor(null);
return;
}
const update = () =>
setAnchor({ contextElement: textarea, getBoundingClientRect: () => caretRect(textarea, caret) });
update();
textarea.addEventListener("scroll", update);
return () => textarea.removeEventListener("scroll", update);
}, [ref, caret, text]);
return anchor;
}
+1 -12
Переглянути файл
@@ -2153,7 +2153,6 @@
"Underscored": "下划线",
"Underwaved": "波浪线",
"Undo": "撤消",
"Unread": "未读",
"Undo Commit": "撤消提交",
"Undo Commit…": "撤消提交…",
"Undo Move / Rename": "撤消移动/重命名",
@@ -3246,7 +3245,6 @@
"Also remove its worktree folder": "同时删除它的 worktree 目录",
"needs input": "等待输入",
"running": "正在运行",
"unread": "未读",
"This agent task no longer exists": "这个 Agent 任务已不存在",
"Local checkout": "当前工作区",
"Needs input": "等待输入",
@@ -4739,14 +4737,5 @@
"Cannot select Python interpreter": "无法选择 Python 解释器",
"Python Interpreter: {label}": "Python 解释器:{label}",
"Add to .gitignore": "添加到 .gitignore",
"Add to .git/info/exclude": "添加到 .git/info/exclude",
"Delete Agent Tasks": "删除 Agent 任务",
"Open Agent Task": "打开 Agent 任务",
"Archive Agent Tasks": "归档 Agent 任务",
"Delete {count} agent tasks? Their branches and files outside worktrees are kept.": "是否删除这 {count} 个 Agent 任务?它们的分支及 worktree 以外的文件将保留。",
"Also remove their worktree folders": "同时删除它们的 worktree 目录",
"Cannot delete agent tasks": "无法删除 Agent 任务",
"Cannot archive agent tasks": "无法归档 Agent 任务",
"Archive ({count})": "归档({count})",
"Delete ({count})…": "删除({count})…"
"Add to .git/info/exclude": "添加到 .git/info/exclude"
}
-1
Переглянути файл
@@ -267,7 +267,6 @@ export function Tree<T>(props: TreeProps<T>) {
commitSelection(next, row.key);
} else {
const a = anchor != null ? (indexOfKey.get(anchor) ?? i) : leadIndex >= 0 ? leadIndex : i;
setAnchor(rows[a]!.key);
const [s, e] = a < i ? [a, i] : [i, a];
const next = new Set<string>();
for (let j = s; j <= e; j++) if (!rows[j]!.loading) next.add(rows[j]!.key);