дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-26 20:46:22 +02:00
feat(agents): support drag-and-drop reordering in the Agents list (#6140)
## Summary - Add manual drag-and-drop reordering for tasks within `Pinned`, custom groups, and status groups (`Running`, `Ready to Review`, `Archived`, etc.), with before/after insertion indicators and edge auto-scrolling. - Support dropping tasks onto exact slots across compatible sections (pinning, moving into custom groups, or returning pinned/grouped tasks back to their matching status group), while rejecting incompatible status groups and disabling row reordering while searching. - Support drag-and-drop reordering between custom group headers (`GROUP_DRAG`). - Persist per-section manual order in `localStorage` (`TaskOrganize.order`), keeping manually ordered tasks stable across activity updates while placing newly added tasks at the top of the section. - Open tasks on click release instead of `mousedown` so starting a drag does not open the dragged task's chat history, and allow initiating drag from anywhere on the 24px row. ## Testing - `vitest run src/features/agents/organize.test.ts src/features/agents/AgentsView.test.tsx src/features/agents/unread.test.tsx` (90 passed) - `oxlint` & `oxfmt` clean on all changed files - `tsc --noEmit` passed Made with [Cursor](https://cursor.com)
Цей коміт міститься в:
1 джерело
e909c50fe4
коміт
b79dbae83f
7 files changed
+860
-81
No files matched your search
@@ -49,6 +49,24 @@
|
||||
outline: 1px dashed var(--accent);
|
||||
outline-offset: -1px;
|
||||
}
|
||||
/* Drop insertion indicator on a tree row while dragging to reorder tasks or custom groups. */
|
||||
.dropBefore::before,
|
||||
.dropAfter::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 2px;
|
||||
background: var(--focus-ring);
|
||||
pointer-events: none;
|
||||
z-index: 1;
|
||||
}
|
||||
.dropBefore::before {
|
||||
top: 0;
|
||||
}
|
||||
.dropAfter::after {
|
||||
bottom: 0;
|
||||
}
|
||||
.title {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
|
||||
@@ -8,7 +8,7 @@ import { confirm, confirmChecked, showError } from "@/workbench/messages";
|
||||
import { promptInput } from "@/workbench/inputDialogs";
|
||||
import { ContextMenuHost, dragSession, hideContextMenu } from "@/ui";
|
||||
import { AgentsHeaderActions, AgentsView } from "./AgentsView";
|
||||
import { SESSION_KIND, TASK_DRAG } from "./model";
|
||||
import { GROUP_DRAG, SESSION_KIND, TASK_DRAG } from "./model";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { archiveTask, unarchiveTask, deleteTask, dockTask, openTask, useAgents } from "./store";
|
||||
import { taskActions, taskMenu, useAgentsHeaderMenu } from "./taskActions";
|
||||
@@ -84,8 +84,11 @@ const row = (id: string) =>
|
||||
within(screen.getByRole("tree", { name: "Agent tasks" }))
|
||||
.getByText(id)
|
||||
.closest('[role="treeitem"]')!;
|
||||
const select = (id: string, modifiers: MouseEventInit = {}) =>
|
||||
fireEvent.mouseDown(row(id), { button: 0, ...modifiers });
|
||||
const select = (id: string, modifiers: MouseEventInit = {}) => {
|
||||
const el = row(id);
|
||||
fireEvent.mouseDown(el, { button: 0, ...modifiers });
|
||||
fireEvent.click(el, { button: 0, ...modifiers });
|
||||
};
|
||||
const selectedTasks = () =>
|
||||
screen
|
||||
.queryAllByRole("treeitem", { selected: true })
|
||||
@@ -618,4 +621,169 @@ describe("Agents pinned and grouped tasks", () => {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
const dropOnRow = (target: Element, type: string, payload: string, position: "before" | "after") => {
|
||||
vi.spyOn(target, "getBoundingClientRect").mockReturnValue({
|
||||
top: 100,
|
||||
bottom: 124,
|
||||
left: 0,
|
||||
right: 200,
|
||||
width: 200,
|
||||
height: 24,
|
||||
x: 0,
|
||||
y: 100,
|
||||
toJSON: () => {},
|
||||
});
|
||||
const y = position === "before" ? 104 : 120;
|
||||
const restore = pointAt(target);
|
||||
try {
|
||||
const session = dragSession({ type, payload });
|
||||
act(() => session.move(10, y));
|
||||
const indicator = target.className;
|
||||
act(() => session.drop(10, y));
|
||||
return indicator;
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
};
|
||||
|
||||
it("reorders tasks within a section by dragging before or after a sibling", () => {
|
||||
const tasks = new Map(
|
||||
[
|
||||
{ ...task("one"), updatedMs: 40 },
|
||||
{ ...task("two"), updatedMs: 30 },
|
||||
{ ...task("three"), updatedMs: 20 },
|
||||
].map((t) => [t.id, t]),
|
||||
);
|
||||
useAgents.setState({ tasks, organize: { groups: [], groupOf: {}, pinned: [] } });
|
||||
setup();
|
||||
|
||||
const indicatorBefore = dropOnRow(row("one"), TASK_DRAG, "three", "before");
|
||||
expect(indicatorBefore).toContain(styles.dropBefore);
|
||||
expect(
|
||||
treeRows()
|
||||
.slice(1)
|
||||
.map((t) => t.replace(/\d+[smhd]|now/g, "").trim()),
|
||||
).toEqual(["three", "one", "two"]);
|
||||
|
||||
// Updating activity later keeps the manual order intact.
|
||||
act(() => {
|
||||
const next = new Map(useAgents.getState().tasks);
|
||||
next.set("two", { ...next.get("two")!, updatedMs: 999 });
|
||||
useAgents.setState({ tasks: next });
|
||||
});
|
||||
expect(
|
||||
treeRows()
|
||||
.slice(1)
|
||||
.map((t) => t.replace(/\d+[smhd]|now/g, "").trim()),
|
||||
).toEqual(["three", "one", "two"]);
|
||||
|
||||
const indicatorAfter = dropOnRow(row("two"), TASK_DRAG, "three", "after");
|
||||
expect(indicatorAfter).toContain(styles.dropAfter);
|
||||
expect(
|
||||
treeRows()
|
||||
.slice(1)
|
||||
.map((t) => t.replace(/\d+[smhd]|now/g, "").trim()),
|
||||
).toEqual(["one", "two", "three"]);
|
||||
});
|
||||
|
||||
it("places a task at the exact slot when dragged across Pinned, custom, and matching status groups", () => {
|
||||
const tasks = new Map(
|
||||
[
|
||||
{ ...task("one"), updatedMs: 40 },
|
||||
{ ...task("two"), updatedMs: 30 },
|
||||
{ ...task("three"), updatedMs: 20 },
|
||||
{ ...task("run", "running"), updatedMs: 50 },
|
||||
].map((t) => [t.id, t]),
|
||||
);
|
||||
useAgents.setState({ tasks, organize: { groups: [frontend], groupOf: {}, pinned: ["one"] } });
|
||||
setup();
|
||||
|
||||
// Drag `three` before `one` in Pinned -> pins `three` above `one`.
|
||||
dropOnRow(row("one"), TASK_DRAG, "three", "before");
|
||||
expect(useAgents.getState().organize.pinned).toEqual(["one", "three"]);
|
||||
expect(useAgents.getState().organize.order?.pinned).toEqual(["three", "one"]);
|
||||
|
||||
// Drag `three` back onto `Ready to Review` after `two` -> unpins `three` and places it after `two`.
|
||||
dropOnRow(row("two"), TASK_DRAG, "three", "after");
|
||||
expect(useAgents.getState().organize.pinned).toEqual(["one"]);
|
||||
expect(useAgents.getState().organize.order?.["g:ready"]).toEqual(["two", "three"]);
|
||||
|
||||
// Dragging a `running` task onto a `ready` row is rejected.
|
||||
const rejected = dropOnRow(row("two"), TASK_DRAG, "run", "before");
|
||||
expect(rejected).not.toContain(styles.dropBefore);
|
||||
expect(useAgents.getState().organize.order?.["g:ready"]).toEqual(["two", "three"]);
|
||||
|
||||
// Dropping a pinned `ready` task onto the `Ready to Review` header returns it to the status group.
|
||||
const restore = pointAt(screen.getByText("Ready to Review"));
|
||||
try {
|
||||
const session = dragSession({ type: TASK_DRAG, payload: "one" });
|
||||
act(() => session.move(10, 10));
|
||||
act(() => session.drop(10, 10));
|
||||
expect(useAgents.getState().organize.pinned).toEqual([]);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
it("disables row reordering while searching", () => {
|
||||
setup();
|
||||
fireEvent.change(screen.getByLabelText("Search tasks"), { target: { value: "o" } });
|
||||
const oneRow = document.querySelector('[data-tree-key="one"]')!;
|
||||
const indicator = dropOnRow(oneRow, TASK_DRAG, "two", "before");
|
||||
expect(indicator).not.toContain(styles.dropBefore);
|
||||
expect(useAgents.getState().organize.order).toBeUndefined();
|
||||
});
|
||||
|
||||
it("reorders custom groups by dragging a group header before or after another", () => {
|
||||
const backend = { id: "g2", name: "Backend" };
|
||||
useAgents.setState({ organize: { groups: [frontend, backend], groupOf: {}, pinned: [] } });
|
||||
setup();
|
||||
|
||||
const frontendRow = screen.getByText("Frontend").closest('[role="treeitem"]')!;
|
||||
const indicator = dropOnRow(frontendRow, GROUP_DRAG, "g2", "before");
|
||||
expect(indicator).toContain(styles.dropBefore);
|
||||
expect(useAgents.getState().organize.groups.map((g) => g.id)).toEqual(["g2", "g1"]);
|
||||
});
|
||||
|
||||
it("opens a task only on click release, not when starting a drag", () => {
|
||||
setup();
|
||||
const target = row("one");
|
||||
const sourceSpan = within(row("two") as HTMLElement)
|
||||
.getByText("two")
|
||||
.closest(`.${styles.row}`)!;
|
||||
vi.spyOn(target, "getBoundingClientRect").mockReturnValue({
|
||||
top: 100,
|
||||
bottom: 124,
|
||||
left: 0,
|
||||
right: 200,
|
||||
width: 200,
|
||||
height: 24,
|
||||
x: 0,
|
||||
y: 100,
|
||||
toJSON: () => {},
|
||||
});
|
||||
const restore = pointAt(target);
|
||||
try {
|
||||
// Pressing and dragging `two` onto `one` must not open `two`, even if the browser fires a click after drop.
|
||||
fireEvent.pointerDown(sourceSpan, { button: 0, clientX: 10, clientY: 130 });
|
||||
fireEvent.mouseDown(row("two"), { button: 0 });
|
||||
expect(openTask).not.toHaveBeenCalled();
|
||||
fireEvent.pointerMove(window, { buttons: 1, clientX: 10, clientY: 104 });
|
||||
fireEvent.pointerUp(window, { button: 0, clientX: 10, clientY: 104 });
|
||||
fireEvent.click(sourceSpan, { button: 0 });
|
||||
expect(openTask).not.toHaveBeenCalled();
|
||||
expect(useAgents.getState().organize.order?.["g:ready"]?.[0]).toBe("two");
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
|
||||
// A normal press + release without dragging opens the task on click.
|
||||
fireEvent.pointerDown(sourceSpan, { button: 0, clientX: 10, clientY: 104 });
|
||||
fireEvent.mouseDown(row("two"), { button: 0 });
|
||||
expect(openTask).not.toHaveBeenCalled();
|
||||
fireEvent.pointerUp(window, { button: 0, clientX: 10, clientY: 104 });
|
||||
fireEvent.click(sourceSpan, { button: 0 });
|
||||
expect(openTask).toHaveBeenCalledWith("two");
|
||||
});
|
||||
});
|
||||
@@ -19,24 +19,37 @@ import {
|
||||
type TreeHandle,
|
||||
} from "@/ui";
|
||||
import {
|
||||
GROUP_DRAG,
|
||||
SESSION_KIND,
|
||||
TASK_DRAG,
|
||||
age,
|
||||
branchLabel,
|
||||
groupStatus,
|
||||
groupTasks,
|
||||
providerIcon,
|
||||
sessionKey,
|
||||
type TaskGroup,
|
||||
} from "./model";
|
||||
import { groupMembers, pinnedMembers, ungroupedMembers, type OrganizeGroup } from "./organize";
|
||||
import {
|
||||
PINNED_SECTION,
|
||||
canReorderTask,
|
||||
customSection,
|
||||
groupMembers,
|
||||
pinnedMembers,
|
||||
sectionOfTask,
|
||||
statusGroups,
|
||||
statusSection,
|
||||
type OrganizeGroup,
|
||||
} from "./organize";
|
||||
import {
|
||||
externalKey,
|
||||
importExternalSession,
|
||||
moveTasksToGroup,
|
||||
moveTasksToStatusGroup,
|
||||
openHome,
|
||||
pinTasks,
|
||||
refreshExternalSessions,
|
||||
reorderTask,
|
||||
reorderTaskGroup,
|
||||
showImportSessions,
|
||||
useAgents,
|
||||
} from "./store";
|
||||
@@ -59,11 +72,6 @@ export function AgentsHeaderActions() {
|
||||
);
|
||||
}
|
||||
|
||||
/** Key of the pinned section, above the groups. */
|
||||
const PINNED_KEY = "pinned";
|
||||
/** Key of a group the user made. */
|
||||
const customKey = (group: string) => `ug:${group}`;
|
||||
|
||||
type Node =
|
||||
| { kind: "pinned"; tasks: AgentTask[] }
|
||||
| { kind: "custom"; group: OrganizeGroup; tasks: AgentTask[] }
|
||||
@@ -73,11 +81,11 @@ type Node =
|
||||
function nodeKey(n: Node): string {
|
||||
switch (n.kind) {
|
||||
case "pinned":
|
||||
return PINNED_KEY;
|
||||
return PINNED_SECTION;
|
||||
case "custom":
|
||||
return customKey(n.group.id);
|
||||
return customSection(n.group.id);
|
||||
case "group":
|
||||
return `g:${n.group.status}`;
|
||||
return statusSection(n.group.status);
|
||||
case "task":
|
||||
return n.task.id;
|
||||
}
|
||||
@@ -85,40 +93,23 @@ function nodeKey(n: Node): string {
|
||||
|
||||
/** Where a task shows: the pinned section first, else its group, else its status group. */
|
||||
function keysOf(task: AgentTask): string[] {
|
||||
const organize = useAgents.getState().organize;
|
||||
if (organize.pinned.includes(task.id)) return [PINNED_KEY];
|
||||
const group = organize.groupOf[task.id];
|
||||
if (group && organize.groups.some((g) => g.id === group)) return [customKey(group)];
|
||||
return [`g:${groupStatus(task.status)}`];
|
||||
return [sectionOfTask(task, useAgents.getState().organize)];
|
||||
}
|
||||
|
||||
/** A group header; tasks dropped on it go into the group (or into the pinned section). */
|
||||
function GroupRow({
|
||||
label,
|
||||
count,
|
||||
onDropTask,
|
||||
}: {
|
||||
label: ReactNode;
|
||||
count: number;
|
||||
onDropTask?: (task: string) => void;
|
||||
}) {
|
||||
const ref = useRef<HTMLSpanElement>(null);
|
||||
const [over, setOver] = useState(false);
|
||||
useEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el || !onDropTask) return;
|
||||
return registerDropTarget(el, {
|
||||
accepts: (type) => type === TASK_DRAG,
|
||||
over: () => setOver(true),
|
||||
leave: () => setOver(false),
|
||||
drop: (data) => {
|
||||
setOver(false);
|
||||
onDropTask(data.payload);
|
||||
},
|
||||
});
|
||||
}, [onDropTask]);
|
||||
type DropIndicator = { kind: "section"; key: string } | { kind: "row"; key: string; position: "before" | "after" };
|
||||
|
||||
const sameIndicator = (a: DropIndicator | null, b: DropIndicator | null) =>
|
||||
a === b ||
|
||||
(!!a &&
|
||||
!!b &&
|
||||
a.kind === b.kind &&
|
||||
a.key === b.key &&
|
||||
(a.kind !== "row" || b.kind !== "row" || a.position === b.position));
|
||||
|
||||
/** A group header row inside the task tree. */
|
||||
function GroupRow({ label, count }: { label: ReactNode; count: number }) {
|
||||
return (
|
||||
<span ref={ref} className={clsx(styles.row, over && styles.dropOver)}>
|
||||
<span className={styles.row}>
|
||||
<span className={styles.groupLabel}>{label}</span>
|
||||
<span className={styles.count}>{count}</span>
|
||||
</span>
|
||||
@@ -225,13 +216,133 @@ export function AgentsView() {
|
||||
const members = groupMembers(all, organize, group.id);
|
||||
return matches && !members.length ? [] : [{ kind: "custom", group, tasks: members }];
|
||||
}),
|
||||
...groupTasks(ungroupedMembers(all, organize)).map((group): Node => ({ kind: "group", group })),
|
||||
...statusGroups(all, organize).map((group): Node => ({ kind: "group", group })),
|
||||
];
|
||||
}, [tasks, organize, matches]);
|
||||
const expanded = useMemo(
|
||||
() => new Set(roots.map(nodeKey).filter((k) => matches || !collapsed.has(k))),
|
||||
[roots, collapsed, matches],
|
||||
);
|
||||
const searchingRef = useRef(false);
|
||||
useEffect(() => {
|
||||
searchingRef.current = matches !== null;
|
||||
}, [matches]);
|
||||
const cancelDragRef = useRef<(() => void) | undefined>(undefined);
|
||||
const [tasksEl, setTasksEl] = useState<HTMLDivElement | null>(null);
|
||||
const [dropIndicator, setDropIndicator] = useState<DropIndicator | null>(null);
|
||||
useEffect(() => {
|
||||
if (!tasksEl) return;
|
||||
let frame = 0;
|
||||
let pointer: { data: { type: string; payload: string }; x: number; y: number } | null = null;
|
||||
const resolveDrop = (data: { type: string; payload: string }, x: number, y: number) => {
|
||||
const rowEl = document.elementFromPoint(x, y)?.closest<HTMLElement>("[data-tree-key]");
|
||||
if (!rowEl || !tasksEl.contains(rowEl)) return null;
|
||||
const targetKey = rowEl.dataset.treeKey;
|
||||
if (!targetKey) return null;
|
||||
const rect = rowEl.getBoundingClientRect();
|
||||
const position: "before" | "after" = y < rect.top + rect.height / 2 ? "before" : "after";
|
||||
|
||||
if (data.type === GROUP_DRAG) {
|
||||
if (searchingRef.current || !targetKey.startsWith("ug:")) return null;
|
||||
const targetGroup = targetKey.slice(3);
|
||||
if (targetGroup === data.payload) return null;
|
||||
return {
|
||||
indicator: { kind: "row", key: targetKey, position } as DropIndicator,
|
||||
apply: () => reorderTaskGroup(data.payload, targetGroup, position),
|
||||
};
|
||||
}
|
||||
|
||||
if (data.type !== TASK_DRAG) return null;
|
||||
const { tasks, organize } = useAgents.getState();
|
||||
const source = tasks.get(data.payload);
|
||||
if (!source) return null;
|
||||
|
||||
if (targetKey === PINNED_SECTION) {
|
||||
return {
|
||||
indicator: { kind: "section", key: targetKey } as DropIndicator,
|
||||
apply: () => pinTasks([source.id], true),
|
||||
};
|
||||
}
|
||||
if (targetKey.startsWith("ug:")) {
|
||||
const groupId = targetKey.slice(3);
|
||||
if (!organize.groups.some((g) => g.id === groupId)) return null;
|
||||
return {
|
||||
indicator: { kind: "section", key: targetKey } as DropIndicator,
|
||||
apply: () => moveTasksToGroup([source.id], groupId),
|
||||
};
|
||||
}
|
||||
if (targetKey.startsWith("g:")) {
|
||||
if (sectionOfTask(source, organize) === targetKey) return null;
|
||||
if (statusSection(groupStatus(source.status)) !== targetKey) return null;
|
||||
return {
|
||||
indicator: { kind: "section", key: targetKey } as DropIndicator,
|
||||
apply: () => moveTasksToStatusGroup([source.id]),
|
||||
};
|
||||
}
|
||||
if (searchingRef.current) return null;
|
||||
const target = tasks.get(targetKey);
|
||||
if (!target || !canReorderTask(source, target, organize)) return null;
|
||||
return {
|
||||
indicator: { kind: "row", key: targetKey, position } as DropIndicator,
|
||||
apply: () => reorderTask(source.id, target.id, position),
|
||||
};
|
||||
};
|
||||
const update = () => {
|
||||
const next = pointer ? (resolveDrop(pointer.data, pointer.x, pointer.y)?.indicator ?? null) : null;
|
||||
setDropIndicator((cur) => (sameIndicator(cur, next) ? cur : next));
|
||||
};
|
||||
const scroll = () => {
|
||||
frame = 0;
|
||||
if (!pointer) return;
|
||||
const scroller = tasksEl.querySelector<HTMLElement>('[role="tree"]');
|
||||
if (!scroller) return;
|
||||
const rect = scroller.getBoundingClientRect();
|
||||
const delta = pointer.y < rect.top + 24 ? -8 : pointer.y > rect.bottom - 24 ? 8 : 0;
|
||||
if (!delta) return;
|
||||
const before = scroller.scrollTop;
|
||||
scroller.scrollTop = Math.max(0, Math.min(scroller.scrollHeight - scroller.clientHeight, before + delta));
|
||||
if (scroller.scrollTop !== before) {
|
||||
update();
|
||||
frame = requestAnimationFrame(scroll);
|
||||
}
|
||||
};
|
||||
const leave = () => {
|
||||
pointer = null;
|
||||
cancelAnimationFrame(frame);
|
||||
frame = 0;
|
||||
setDropIndicator(null);
|
||||
};
|
||||
const unregister = registerDropTarget(tasksEl, {
|
||||
accepts: (type) => type === TASK_DRAG || type === GROUP_DRAG,
|
||||
over: (data, x, y) => {
|
||||
pointer = { data, x, y };
|
||||
update();
|
||||
if (!frame) frame = requestAnimationFrame(scroll);
|
||||
},
|
||||
leave,
|
||||
drop: (data, x, y) => {
|
||||
const hit = resolveDrop(data, x, y);
|
||||
leave();
|
||||
hit?.apply();
|
||||
},
|
||||
});
|
||||
return () => {
|
||||
cancelDragRef.current?.();
|
||||
leave();
|
||||
unregister();
|
||||
};
|
||||
}, [tasksEl]);
|
||||
const suppressClickRef = useRef(false);
|
||||
const mouseSelectingRef = useRef(false);
|
||||
const mouseSelectTimerRef = useRef<number | undefined>(undefined);
|
||||
const resetMouseSelecting = () => {
|
||||
mouseSelectingRef.current = false;
|
||||
if (mouseSelectTimerRef.current !== undefined) {
|
||||
window.clearTimeout(mouseSelectTimerRef.current);
|
||||
mouseSelectTimerRef.current = undefined;
|
||||
}
|
||||
};
|
||||
useEffect(() => resetMouseSelecting, []);
|
||||
// Dropping a session editor tab anywhere on the tool window docks it.
|
||||
const viewRef = useRef<HTMLDivElement>(null);
|
||||
const [tabOver, setTabOver] = useState(false);
|
||||
@@ -263,8 +374,36 @@ export function AgentsView() {
|
||||
void executeAction("agents.openTask", task);
|
||||
};
|
||||
const dockedTitle = docked ? (tasks.get(docked)?.title ?? docked) : null;
|
||||
const dragTask = (e: ReactPointerEvent<HTMLSpanElement>, task: string) =>
|
||||
startPointerDrag(e, e.currentTarget, { type: TASK_DRAG, payload: task });
|
||||
const dragTask = (e: ReactPointerEvent<HTMLElement>, task: string, source: HTMLElement = e.currentTarget) => {
|
||||
suppressClickRef.current = false;
|
||||
if (e.button !== 0 || e.ctrlKey || e.metaKey || e.shiftKey) return;
|
||||
cancelDragRef.current?.();
|
||||
cancelDragRef.current = startPointerDrag(
|
||||
e,
|
||||
source,
|
||||
{ type: TASK_DRAG, payload: task },
|
||||
{
|
||||
onEnd: (dragged) => {
|
||||
suppressClickRef.current = dragged;
|
||||
cancelDragRef.current = undefined;
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
const dragGroup = (e: ReactPointerEvent<HTMLElement>, group: string, source: HTMLElement = e.currentTarget) => {
|
||||
if (matches || organize.groups.length < 2 || e.button !== 0 || e.ctrlKey || e.metaKey || e.shiftKey) return;
|
||||
cancelDragRef.current?.();
|
||||
cancelDragRef.current = startPointerDrag(
|
||||
e,
|
||||
source,
|
||||
{ type: GROUP_DRAG, payload: group },
|
||||
{
|
||||
onEnd: () => {
|
||||
cancelDragRef.current = undefined;
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
// The tasks under `task` in its section, for Archive All Below.
|
||||
const tasksBelow = (task: string): AgentTask[] => {
|
||||
@@ -296,7 +435,41 @@ export function AgentsView() {
|
||||
|
||||
const taskList = (
|
||||
<div
|
||||
ref={setTasksEl}
|
||||
className={styles.tasks}
|
||||
onPointerDownCapture={() => {
|
||||
suppressClickRef.current = false;
|
||||
}}
|
||||
onPointerDown={(e) => {
|
||||
if (e.button !== 0 || e.ctrlKey || e.metaKey || e.shiftKey) return;
|
||||
if ((e.target as Element).closest("button, input, textarea, [data-tree-toggle]")) return;
|
||||
const rowEl = (e.target as Element).closest<HTMLElement>("[data-tree-key]");
|
||||
const key = rowEl?.dataset.treeKey;
|
||||
if (!rowEl || !key) return;
|
||||
const ghostSource = rowEl.querySelector<HTMLElement>(`.${styles.row}`) ?? rowEl;
|
||||
if (tasks.has(key)) dragTask(e, key, ghostSource);
|
||||
else if (key.startsWith("ug:")) dragGroup(e, key.slice(3), ghostSource);
|
||||
}}
|
||||
onMouseDownCapture={(e) => {
|
||||
if (e.button !== 0 || (e.target as Element).closest("button, input, textarea, [data-tree-toggle]")) return;
|
||||
// Macrotask fallback (not microtask): browsers flush microtasks between React's capture
|
||||
// and bubble root listeners on real user clicks, which would clear this flag too early.
|
||||
mouseSelectingRef.current = true;
|
||||
if (mouseSelectTimerRef.current !== undefined) window.clearTimeout(mouseSelectTimerRef.current);
|
||||
mouseSelectTimerRef.current = window.setTimeout(resetMouseSelecting, 0);
|
||||
}}
|
||||
onMouseDown={resetMouseSelecting}
|
||||
onKeyDownCapture={resetMouseSelecting}
|
||||
onClick={(e) => {
|
||||
if (suppressClickRef.current) {
|
||||
suppressClickRef.current = false;
|
||||
return;
|
||||
}
|
||||
if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey) return;
|
||||
if ((e.target as Element).closest("button, input, textarea, [data-tree-toggle]")) return;
|
||||
const key = (e.target as Element).closest<HTMLElement>("[data-tree-key]")?.dataset.treeKey;
|
||||
if (key && tasks.has(key)) showTask(key);
|
||||
}}
|
||||
onFocus={() => setFocusedTaskList(() => [...selectedRef.current])}
|
||||
onBlur={(e) => {
|
||||
if (!(e.relatedTarget instanceof Element && e.currentTarget.contains(e.relatedTarget)))
|
||||
@@ -362,7 +535,15 @@ export function AgentsView() {
|
||||
selected={selected}
|
||||
onSelectionChange={(sel, lead, reason) => {
|
||||
setSelected(sel);
|
||||
if (reason !== "contextMenu" && !inline && sel.size === 1 && lead?.kind === "task" && sel.has(lead.task.id))
|
||||
// Mouse clicks open on release (`onClick`) so starting a drag never opens the task.
|
||||
if (
|
||||
reason !== "contextMenu" &&
|
||||
!mouseSelectingRef.current &&
|
||||
!inline &&
|
||||
sel.size === 1 &&
|
||||
lead?.kind === "task" &&
|
||||
sel.has(lead.task.id)
|
||||
)
|
||||
showTask(lead.task.id);
|
||||
}}
|
||||
onActivate={(n) => n.kind === "task" && showTask(n.task.id)}
|
||||
@@ -379,32 +560,22 @@ export function AgentsView() {
|
||||
});
|
||||
showContextMenu(e, taskMenu(selection, selection.length === 1 ? tasksBelow(n.task.id) : []));
|
||||
}}
|
||||
rowClassName={(n) => {
|
||||
if (!dropIndicator || dropIndicator.key !== nodeKey(n)) return undefined;
|
||||
if (dropIndicator.kind === "section") return styles.dropOver;
|
||||
return dropIndicator.position === "before" ? styles.dropBefore : styles.dropAfter;
|
||||
}}
|
||||
renderNode={(n) => {
|
||||
switch (n.kind) {
|
||||
case "pinned":
|
||||
return (
|
||||
<GroupRow label={<T>Pinned</T>} count={n.tasks.length} onDropTask={(task) => pinTasks([task], true)} />
|
||||
);
|
||||
return <GroupRow label={<T>Pinned</T>} count={n.tasks.length} />;
|
||||
case "custom":
|
||||
return (
|
||||
<GroupRow
|
||||
label={n.group.name}
|
||||
count={n.tasks.length}
|
||||
onDropTask={(task) => moveTasksToGroup([task], n.group.id)}
|
||||
/>
|
||||
);
|
||||
return <GroupRow label={n.group.name} count={n.tasks.length} />;
|
||||
case "group":
|
||||
return <GroupRow label={<T>{n.group.label}</T>} count={n.group.tasks.length} />;
|
||||
case "task":
|
||||
return (
|
||||
<span
|
||||
className={styles.row}
|
||||
title={n.task.error ?? n.task.title}
|
||||
onPointerDown={(e) => dragTask(e, n.task.id)}
|
||||
onClick={(e) => {
|
||||
if (inline && !e.metaKey && !e.ctrlKey && !e.shiftKey) showTask(n.task.id);
|
||||
}}
|
||||
>
|
||||
<span className={styles.row} title={n.task.error ?? n.task.title}>
|
||||
<Icon name={providerIcon(n.task.provider)} size={16} label={providerName(n.task.provider)} />
|
||||
<span className={styles.title} data-unread={unread.has(n.task.id) || undefined}>
|
||||
{matches?.get(n.task.id)?.length ? (
|
||||
|
||||
@@ -8,6 +8,8 @@ export const HOME_KEY = "agent:new";
|
||||
export const TOOL_WINDOW = "agents";
|
||||
/** MIME of a dragged agent task (a tree row or the docked conversation bar): the payload is the task id. */
|
||||
export const TASK_DRAG = "application/x-openidea-agent-task";
|
||||
/** MIME of a dragged custom agent task group header: the payload is the group id. */
|
||||
export const GROUP_DRAG = "application/x-openidea-agent-group";
|
||||
/** Settings › Agents › Agent Setup. */
|
||||
export const REGISTRY_PAGE = "agents.list";
|
||||
/** The Settings folder holding the agent pages. */
|
||||
|
||||
@@ -2,13 +2,19 @@ import { beforeEach, describe, expect, it } from "vitest";
|
||||
import type { AgentTask } from "@/bindings";
|
||||
import {
|
||||
EMPTY_ORGANIZE,
|
||||
PINNED_SECTION,
|
||||
customSection,
|
||||
groupMembers,
|
||||
groupNameError,
|
||||
loadOrganize,
|
||||
parseOrganize,
|
||||
pinnedMembers,
|
||||
pruneOrganize,
|
||||
reorderGroupsInOrganize,
|
||||
reorderTaskInOrganize,
|
||||
saveOrganize,
|
||||
statusGroups,
|
||||
statusSection,
|
||||
ungroupedMembers,
|
||||
} from "./organize";
|
||||
|
||||
@@ -96,4 +102,111 @@ describe("task organize", () => {
|
||||
expect(groupNameError("Docs", groups, "Docs")).toBeNull();
|
||||
expect(groupNameError(" ", groups)).toBe("Enter a group name");
|
||||
});
|
||||
|
||||
it("parses and prunes saved manual section orders", () => {
|
||||
const parsed = parseOrganize({
|
||||
groups: [{ id: "g1", name: "Docs" }],
|
||||
groupOf: { a: "g1" },
|
||||
pinned: ["b"],
|
||||
order: {
|
||||
pinned: ["b", "b", 123],
|
||||
"ug:g1": ["a"],
|
||||
"ug:missing": ["a"],
|
||||
"g:ready": ["c", "d"],
|
||||
"g:unknown": ["c"],
|
||||
"g:running": [],
|
||||
},
|
||||
});
|
||||
expect(parsed).toEqual({
|
||||
groups: [{ id: "g1", name: "Docs" }],
|
||||
groupOf: { a: "g1" },
|
||||
pinned: ["b"],
|
||||
order: { pinned: ["b"], "ug:g1": ["a"], "g:ready": ["c", "d"] },
|
||||
});
|
||||
|
||||
const pruned = pruneOrganize(parsed, [task("a"), task("b"), task("c")]);
|
||||
expect(pruned.order).toEqual({ pinned: ["b"], "ug:g1": ["a"], "g:ready": ["c"] });
|
||||
expect(pruneOrganize(pruned, [task("a"), task("b"), task("c")])).toBe(pruned);
|
||||
// When all ordered tasks are gone, `order` is omitted cleanly.
|
||||
expect(pruneOrganize(parsed, [task("x")])).toEqual({
|
||||
groups: [{ id: "g1", name: "Docs" }],
|
||||
groupOf: {},
|
||||
pinned: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps manual order stable across activity updates and places new tasks on top", () => {
|
||||
const initial = [task("a", "ready", 10), task("b", "ready", 20), task("c", "ready", 30)];
|
||||
const organize = {
|
||||
groups: [],
|
||||
groupOf: {},
|
||||
pinned: ["a", "b", "c"],
|
||||
order: { [PINNED_SECTION]: ["a", "c", "b"] },
|
||||
};
|
||||
// `b` becomes the most recently active, yet manual order holds.
|
||||
const bumped = [task("a", "ready", 10), task("b", "ready", 999), task("c", "ready", 30)];
|
||||
expect(pinnedMembers(bumped, organize).map((t) => t.id)).toEqual(["a", "c", "b"]);
|
||||
// A newly pinned task not in `order` appears above the manually ordered ones.
|
||||
const withNew = [...initial, task("d", "ready", 5)];
|
||||
const organizeWithNew = { ...organize, pinned: [...organize.pinned, "d"] };
|
||||
expect(pinnedMembers(withNew, organizeWithNew).map((t) => t.id)).toEqual(["d", "a", "c", "b"]);
|
||||
});
|
||||
|
||||
it("reorders tasks within a section, across compatible sections, and rejects incompatible status groups", () => {
|
||||
const tasks = [task("a", "ready", 30), task("b", "ready", 20), task("c", "ready", 10), task("r", "running", 40)];
|
||||
// Reorder within status group `g:ready`.
|
||||
const reordered = reorderTaskInOrganize(EMPTY_ORGANIZE, tasks, "c", "a", "before");
|
||||
expect(
|
||||
statusGroups(tasks, reordered)
|
||||
.find((g) => g.status === "ready")
|
||||
?.tasks.map((t) => t.id),
|
||||
).toEqual(["c", "a", "b"]);
|
||||
// Dropping in the same effective slot is a no-op.
|
||||
expect(reorderTaskInOrganize(reordered, tasks, "a", "c", "after")).toBe(reordered);
|
||||
|
||||
// Move `b` into Pinned before `a` (when `a` is pinned), then into a custom group after `c`.
|
||||
const withPinned = {
|
||||
groups: [{ id: "g1", name: "Docs" }],
|
||||
groupOf: { c: "g1" },
|
||||
pinned: ["a"],
|
||||
order: { [statusSection("ready")]: ["b"] },
|
||||
};
|
||||
const pinnedB = reorderTaskInOrganize(withPinned, tasks, "b", "a", "before");
|
||||
expect(pinnedB.pinned).toEqual(["a", "b"]);
|
||||
expect(pinnedMembers(tasks, pinnedB).map((t) => t.id)).toEqual(["b", "a"]);
|
||||
expect(pinnedB.order?.[statusSection("ready")]).toBeUndefined();
|
||||
|
||||
const groupedB = reorderTaskInOrganize(pinnedB, tasks, "b", "c", "after");
|
||||
expect(groupedB.pinned).toEqual(["a"]);
|
||||
expect(groupedB.groupOf.b).toBe("g1");
|
||||
expect(groupMembers(tasks, groupedB, "g1").map((t) => t.id)).toEqual(["c", "b"]);
|
||||
expect(groupedB.order?.[PINNED_SECTION]).toEqual(["a"]);
|
||||
|
||||
// Returning a ready task from a custom group to `g:ready` succeeds; a running task cannot land in `g:ready`.
|
||||
const withReady = {
|
||||
groups: [{ id: "g1", name: "Docs" }],
|
||||
groupOf: { b: "g1" },
|
||||
pinned: ["r"],
|
||||
};
|
||||
const returned = reorderTaskInOrganize(withReady, tasks, "b", "a", "after");
|
||||
expect(returned.groupOf.b).toBeUndefined();
|
||||
expect(returned.order?.[statusSection("ready")]).toEqual(["a", "b", "c"]);
|
||||
expect(reorderTaskInOrganize(withReady, tasks, "r", "a", "before")).toBe(withReady);
|
||||
});
|
||||
|
||||
it("reorders custom groups", () => {
|
||||
const organize = {
|
||||
groups: [
|
||||
{ id: "g1", name: "One" },
|
||||
{ id: "g2", name: "Two" },
|
||||
{ id: "g3", name: "Three" },
|
||||
],
|
||||
groupOf: {},
|
||||
pinned: [],
|
||||
order: { [customSection("g1")]: ["a"] },
|
||||
};
|
||||
const moved = reorderGroupsInOrganize(organize, "g3", "g1", "before");
|
||||
expect(moved.groups.map((g) => g.id)).toEqual(["g3", "g1", "g2"]);
|
||||
expect(reorderGroupsInOrganize(moved, "g1", "g3", "after")).toBe(moved);
|
||||
});
|
||||
});
|
||||
@@ -6,7 +6,23 @@
|
||||
import type { AgentTask } from "@/bindings";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { parseRemoteLocation } from "@/platform/remote";
|
||||
import { attentionRank } from "./model";
|
||||
import { attentionRank, groupStatus, groupTasks, type TaskGroup } from "./model";
|
||||
|
||||
/** Section key of the pinned group, above every other group. */
|
||||
export const PINNED_SECTION = "pinned";
|
||||
/** Section key of a user-created group. */
|
||||
export const customSection = (group: string) => `ug:${group}`;
|
||||
/** Section key of a status group. */
|
||||
export const statusSection = (status: TaskGroup["status"]) => `g:${status}`;
|
||||
|
||||
const STATUS_SECTIONS = new Set<string>([
|
||||
"g:needsInput",
|
||||
"g:failed",
|
||||
"g:limited",
|
||||
"g:running",
|
||||
"g:ready",
|
||||
"g:archived",
|
||||
]);
|
||||
|
||||
/** A group the user made ("Frontend", "Docs"…). */
|
||||
export interface OrganizeGroup {
|
||||
@@ -21,10 +37,60 @@ export interface TaskOrganize {
|
||||
groupOf: Record<string, string>;
|
||||
/** Pinned tasks, by task id: they are shown above every group. */
|
||||
pinned: string[];
|
||||
/** Manual task order per section (`pinned`, `ug:<id>`, `g:<status>`). Absent means default sort. */
|
||||
order?: Record<string, string[]>;
|
||||
}
|
||||
|
||||
export const EMPTY_ORGANIZE: TaskOrganize = { groups: [], groupOf: {}, pinned: [] };
|
||||
|
||||
/** Section key where `task` is currently shown. */
|
||||
export function sectionOfTask(task: AgentTask, organize: TaskOrganize): string {
|
||||
if (organize.pinned.includes(task.id)) return PINNED_SECTION;
|
||||
const group = organize.groupOf[task.id];
|
||||
if (group && organize.groups.some((g) => g.id === group)) return customSection(group);
|
||||
return statusSection(groupStatus(task.status));
|
||||
}
|
||||
|
||||
function isKnownSection(section: string, knownGroups: ReadonlySet<string>): boolean {
|
||||
return (
|
||||
section === PINNED_SECTION ||
|
||||
STATUS_SECTIONS.has(section) ||
|
||||
(section.startsWith("ug:") && knownGroups.has(section.slice(3)))
|
||||
);
|
||||
}
|
||||
|
||||
/** Drops empty section entries so `order` is omitted when no section has a manual order. */
|
||||
export function compactOrder(order: Record<string, string[]> | undefined): Record<string, string[]> | undefined {
|
||||
if (!order) return undefined;
|
||||
const out: Record<string, string[]> = {};
|
||||
for (const [section, list] of Object.entries(order)) {
|
||||
if (list.length) out[section] = list;
|
||||
}
|
||||
return Object.keys(out).length ? out : undefined;
|
||||
}
|
||||
|
||||
/** Removes `removed` task ids from the listed `sections` of `order`. */
|
||||
export function removeFromOrder(
|
||||
order: Record<string, string[]> | undefined,
|
||||
sections: Iterable<string>,
|
||||
removed: ReadonlySet<string>,
|
||||
): Record<string, string[]> | undefined {
|
||||
if (!order || !removed.size) return order;
|
||||
let changed = false;
|
||||
const next = { ...order };
|
||||
for (const section of sections) {
|
||||
const list = next[section];
|
||||
if (!list) continue;
|
||||
const kept = list.filter((id) => !removed.has(id));
|
||||
if (kept.length !== list.length) {
|
||||
changed = true;
|
||||
if (kept.length) next[section] = kept;
|
||||
else delete next[section];
|
||||
}
|
||||
}
|
||||
return changed ? compactOrder(next) : order;
|
||||
}
|
||||
|
||||
/** Why `value` cannot name a group (trimmed, and not one already there), or null when it can. */
|
||||
export function groupNameError(value: string, groups: readonly OrganizeGroup[], current?: string): string | null {
|
||||
const name = value.trim();
|
||||
@@ -53,7 +119,16 @@ export function parseOrganize(saved: unknown): TaskOrganize {
|
||||
for (const [task, group] of Object.entries(record.groupOf))
|
||||
if (typeof group === "string" && known.has(group)) groupOf[task] = group;
|
||||
const pinned = Array.isArray(record.pinned) ? record.pinned.filter((id): id is string => typeof id === "string") : [];
|
||||
return { groups, groupOf, pinned };
|
||||
const order: Record<string, string[]> = {};
|
||||
if (record.order && typeof record.order === "object" && !Array.isArray(record.order)) {
|
||||
for (const [section, list] of Object.entries(record.order)) {
|
||||
if (!isKnownSection(section, known) || !Array.isArray(list)) continue;
|
||||
const seen = new Set<string>();
|
||||
const ids = list.filter((id): id is string => typeof id === "string" && !seen.has(id) && (seen.add(id), true));
|
||||
if (ids.length) order[section] = ids;
|
||||
}
|
||||
}
|
||||
return Object.keys(order).length ? { groups, groupOf, pinned, order } : { groups, groupOf, pinned };
|
||||
}
|
||||
|
||||
export function loadOrganize(root: string | null | undefined): TaskOrganize {
|
||||
@@ -88,17 +163,57 @@ export function pruneOrganize(organize: TaskOrganize, tasks: Iterable<AgentTask>
|
||||
for (const [task, group] of Object.entries(organize.groupOf))
|
||||
if (ids.has(task) && known.has(group)) groupOf[task] = group;
|
||||
const pinned = organize.pinned.filter((id) => ids.has(id));
|
||||
let orderChanged = false;
|
||||
let nextOrder: Record<string, string[]> | undefined;
|
||||
if (organize.order) {
|
||||
const cleaned: Record<string, string[]> = {};
|
||||
for (const [section, list] of Object.entries(organize.order)) {
|
||||
if (!isKnownSection(section, known)) {
|
||||
orderChanged = true;
|
||||
continue;
|
||||
}
|
||||
const kept = list.filter((id) => ids.has(id));
|
||||
if (kept.length !== list.length || kept.length === 0) orderChanged = true;
|
||||
if (kept.length) cleaned[section] = kept;
|
||||
}
|
||||
nextOrder = Object.keys(cleaned).length ? cleaned : undefined;
|
||||
if (!nextOrder) orderChanged = true;
|
||||
}
|
||||
const same =
|
||||
pinned.length === organize.pinned.length && Object.keys(groupOf).length === Object.keys(organize.groupOf).length;
|
||||
return same ? organize : { groups: organize.groups, groupOf, pinned };
|
||||
!orderChanged &&
|
||||
pinned.length === organize.pinned.length &&
|
||||
Object.keys(groupOf).length === Object.keys(organize.groupOf).length;
|
||||
if (same) return organize;
|
||||
return nextOrder
|
||||
? { groups: organize.groups, groupOf, pinned, order: nextOrder }
|
||||
: { groups: organize.groups, groupOf, pinned };
|
||||
}
|
||||
|
||||
/** The tasks of `group`, what waits for the user first, then the most recently active. */
|
||||
/**
|
||||
* Applies a saved manual order on top of `defaultSorted`: manually ordered tasks keep their
|
||||
* saved relative order even when activity changes, while new tasks appear above them.
|
||||
*/
|
||||
export function applyOrder(defaultSorted: AgentTask[], manual: readonly string[] | undefined): AgentTask[] {
|
||||
if (!manual?.length) return defaultSorted;
|
||||
const rank = new Map<string, number>();
|
||||
for (const id of manual) if (!rank.has(id)) rank.set(id, rank.size);
|
||||
const fresh: AgentTask[] = [];
|
||||
const ordered: AgentTask[] = [];
|
||||
for (const task of defaultSorted) {
|
||||
if (rank.has(task.id)) ordered.push(task);
|
||||
else fresh.push(task);
|
||||
}
|
||||
ordered.sort((a, b) => rank.get(a.id)! - rank.get(b.id)!);
|
||||
return [...fresh, ...ordered];
|
||||
}
|
||||
|
||||
/** The tasks of `group`, what waits for the user first, then the most recently active (or manual order). */
|
||||
export function groupMembers(tasks: Iterable<AgentTask>, organize: TaskOrganize, group: string): AgentTask[] {
|
||||
const pinned = new Set(organize.pinned);
|
||||
return [...tasks]
|
||||
const sorted = [...tasks]
|
||||
.filter((t) => organize.groupOf[t.id] === group && !pinned.has(t.id))
|
||||
.sort((a, b) => attentionRank(a.status) - attentionRank(b.status) || (b.updatedMs ?? 0) - (a.updatedMs ?? 0));
|
||||
return applyOrder(sorted, organize.order?.[customSection(group)]);
|
||||
}
|
||||
|
||||
/** The tasks the status groups show: not pinned, and in no group of the user's. */
|
||||
@@ -112,8 +227,130 @@ export function ungroupedMembers(tasks: Iterable<AgentTask>, organize: TaskOrgan
|
||||
});
|
||||
}
|
||||
|
||||
/** The pinned tasks, most recently active first. */
|
||||
/** Status groups of the ungrouped tasks, with each group's saved manual order applied. */
|
||||
export function statusGroups(tasks: Iterable<AgentTask>, organize: TaskOrganize): TaskGroup[] {
|
||||
return groupTasks(ungroupedMembers(tasks, organize)).map((group) => ({
|
||||
...group,
|
||||
tasks: applyOrder(group.tasks, organize.order?.[statusSection(group.status)]),
|
||||
}));
|
||||
}
|
||||
|
||||
/** The pinned tasks, most recently active first (or manual order). */
|
||||
export function pinnedMembers(tasks: Iterable<AgentTask>, organize: TaskOrganize): AgentTask[] {
|
||||
const pinned = new Set(organize.pinned);
|
||||
return [...tasks].filter((t) => pinned.has(t.id)).sort((a, b) => (b.updatedMs ?? 0) - (a.updatedMs ?? 0));
|
||||
const sorted = [...tasks].filter((t) => pinned.has(t.id)).sort((a, b) => (b.updatedMs ?? 0) - (a.updatedMs ?? 0));
|
||||
return applyOrder(sorted, organize.order?.[PINNED_SECTION]);
|
||||
}
|
||||
|
||||
function placeId(
|
||||
ids: readonly string[],
|
||||
source: string,
|
||||
target: string,
|
||||
position: "before" | "after",
|
||||
): string[] | null {
|
||||
const rest = ids.filter((id) => id !== source);
|
||||
const at = rest.indexOf(target);
|
||||
if (at < 0) return null;
|
||||
const insert = position === "before" ? at : at + 1;
|
||||
return [...rest.slice(0, insert), source, ...rest.slice(insert)];
|
||||
}
|
||||
|
||||
/** Whether `source` can be placed beside `target` (same status required when landing in a status group). */
|
||||
export function canReorderTask(source: AgentTask, target: AgentTask, organize: TaskOrganize): boolean {
|
||||
if (source.id === target.id) return false;
|
||||
const targetSection = sectionOfTask(target, organize);
|
||||
if (targetSection.startsWith("g:")) return statusSection(groupStatus(source.status)) === targetSection;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Places `sourceId` before or after `targetId`, moving it into the target's section when needed
|
||||
* and persisting that section's display order.
|
||||
*/
|
||||
export function reorderTaskInOrganize(
|
||||
organize: TaskOrganize,
|
||||
tasks: Iterable<AgentTask>,
|
||||
sourceId: string,
|
||||
targetId: string,
|
||||
position: "before" | "after",
|
||||
): TaskOrganize {
|
||||
const all = [...tasks];
|
||||
const byId = new Map(all.map((t) => [t.id, t]));
|
||||
const source = byId.get(sourceId);
|
||||
const target = byId.get(targetId);
|
||||
if (!source || !target || !canReorderTask(source, target, organize)) return organize;
|
||||
|
||||
const sourceSection = sectionOfTask(source, organize);
|
||||
const targetSection = sectionOfTask(target, organize);
|
||||
|
||||
let visibleIds: string[];
|
||||
if (targetSection === PINNED_SECTION) {
|
||||
visibleIds = pinnedMembers(all, organize).map((t) => t.id);
|
||||
} else if (targetSection.startsWith("ug:")) {
|
||||
visibleIds = groupMembers(all, organize, targetSection.slice(3)).map((t) => t.id);
|
||||
} else {
|
||||
const status = targetSection.slice(2) as TaskGroup["status"];
|
||||
visibleIds =
|
||||
statusGroups(all, organize)
|
||||
.find((g) => g.status === status)
|
||||
?.tasks.map((t) => t.id) ?? [];
|
||||
}
|
||||
|
||||
const nextList = placeId(visibleIds, sourceId, targetId, position);
|
||||
if (!nextList) return organize;
|
||||
|
||||
if (
|
||||
sourceSection === targetSection &&
|
||||
nextList.length === visibleIds.length &&
|
||||
nextList.every((id, i) => id === visibleIds[i])
|
||||
)
|
||||
return organize;
|
||||
|
||||
let pinned = organize.pinned;
|
||||
let groupOf = organize.groupOf;
|
||||
if (sourceSection !== targetSection) {
|
||||
if (targetSection === PINNED_SECTION) {
|
||||
pinned = pinned.includes(sourceId) ? pinned : [...pinned, sourceId];
|
||||
} else if (targetSection.startsWith("ug:")) {
|
||||
const groupId = targetSection.slice(3);
|
||||
groupOf = { ...groupOf, [sourceId]: groupId };
|
||||
pinned = pinned.filter((id) => id !== sourceId);
|
||||
} else {
|
||||
pinned = pinned.filter((id) => id !== sourceId);
|
||||
if (sourceId in groupOf) {
|
||||
groupOf = { ...groupOf };
|
||||
delete groupOf[sourceId];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const baseOrder =
|
||||
sourceSection !== targetSection
|
||||
? removeFromOrder(organize.order, [sourceSection], new Set([sourceId]))
|
||||
: organize.order;
|
||||
const order = compactOrder({ ...(baseOrder ?? {}), [targetSection]: nextList });
|
||||
return order ? { groups: organize.groups, groupOf, pinned, order } : { groups: organize.groups, groupOf, pinned };
|
||||
}
|
||||
|
||||
/** Moves a custom group before or after another custom group. */
|
||||
export function reorderGroupsInOrganize(
|
||||
organize: TaskOrganize,
|
||||
sourceId: string,
|
||||
targetId: string,
|
||||
position: "before" | "after",
|
||||
): TaskOrganize {
|
||||
if (sourceId === targetId) return organize;
|
||||
const nextIds = placeId(
|
||||
organize.groups.map((g) => g.id),
|
||||
sourceId,
|
||||
targetId,
|
||||
position,
|
||||
);
|
||||
if (!nextIds || nextIds.every((id, i) => id === organize.groups[i]?.id)) return organize;
|
||||
const byId = new Map(organize.groups.map((g) => [g.id, g]));
|
||||
const groups = nextIds.flatMap((id) => {
|
||||
const g = byId.get(id);
|
||||
return g ? [g] : [];
|
||||
});
|
||||
return { ...organize, groups };
|
||||
}
|
||||
@@ -55,8 +55,14 @@ import {
|
||||
import { withQuote } from "./conversation";
|
||||
import {
|
||||
EMPTY_ORGANIZE,
|
||||
PINNED_SECTION,
|
||||
compactOrder,
|
||||
customSection,
|
||||
loadOrganize,
|
||||
pruneOrganize,
|
||||
removeFromOrder,
|
||||
reorderGroupsInOrganize,
|
||||
reorderTaskInOrganize,
|
||||
saveOrganize,
|
||||
type OrganizeGroup,
|
||||
type TaskOrganize,
|
||||
@@ -1824,10 +1830,15 @@ export const renameTask = (task: string, title: string) => call(commands.agentRe
|
||||
export const archiveTask = (task: string) => call(commands.agentArchive(task));
|
||||
export const deleteTask = (task: string, removeWorktree: boolean) => call(commands.agentDelete(task, removeWorktree));
|
||||
|
||||
function withOrder(base: Omit<TaskOrganize, "order">, order: Record<string, string[]> | undefined): TaskOrganize {
|
||||
return order ? { ...base, order } : base;
|
||||
}
|
||||
|
||||
/** Applies `change` to the saved arrange state of the project the tasks belong to. */
|
||||
function changeOrganize(change: (organize: TaskOrganize) => TaskOrganize) {
|
||||
const s = useAgents.getState();
|
||||
const organize = change(s.organize);
|
||||
if (organize === s.organize) return;
|
||||
useAgents.setState({ organize });
|
||||
saveOrganize(s.organizeRoot, organize);
|
||||
}
|
||||
@@ -1840,7 +1851,8 @@ export function pinTasks(tasks: readonly string[], pinned: boolean) {
|
||||
if (pinned) next.add(task);
|
||||
else next.delete(task);
|
||||
}
|
||||
return { ...organize, pinned: [...next] };
|
||||
const order = pinned ? organize.order : removeFromOrder(organize.order, [PINNED_SECTION], new Set(tasks));
|
||||
return withOrder({ groups: organize.groups, groupOf: organize.groupOf, pinned: [...next] }, order);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1872,22 +1884,80 @@ export function renameTaskGroup(group: string, name: string) {
|
||||
|
||||
/** Removes a group; its tasks go back to the status groups. */
|
||||
export function deleteTaskGroup(group: string) {
|
||||
changeOrganize((organize) => ({
|
||||
...organize,
|
||||
groups: organize.groups.filter((g) => g.id !== group),
|
||||
groupOf: Object.fromEntries(Object.entries(organize.groupOf).filter(([, g]) => g !== group)),
|
||||
}));
|
||||
changeOrganize((organize) => {
|
||||
const section = customSection(group);
|
||||
let order = organize.order;
|
||||
if (order && section in order) {
|
||||
const rest = { ...order };
|
||||
delete rest[section];
|
||||
order = compactOrder(rest);
|
||||
}
|
||||
return withOrder(
|
||||
{
|
||||
groups: organize.groups.filter((g) => g.id !== group),
|
||||
groupOf: Object.fromEntries(Object.entries(organize.groupOf).filter(([, g]) => g !== group)),
|
||||
pinned: organize.pinned,
|
||||
},
|
||||
order,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/** Moves the tasks into `group`, out of the pinned section; `null` puts them back among the status groups. */
|
||||
export function moveTasksToGroup(tasks: readonly string[], group: string | null) {
|
||||
changeOrganize((organize) => {
|
||||
const groupOf = { ...organize.groupOf };
|
||||
const leftSections = new Set<string>();
|
||||
for (const task of tasks) {
|
||||
const prev = organize.groupOf[task];
|
||||
if (prev && prev !== group) leftSections.add(customSection(prev));
|
||||
if (group) groupOf[task] = group;
|
||||
else delete groupOf[task];
|
||||
}
|
||||
if (group) leftSections.add(PINNED_SECTION);
|
||||
const moved = new Set(tasks);
|
||||
return { ...organize, groupOf, pinned: group ? organize.pinned.filter((id) => !moved.has(id)) : organize.pinned };
|
||||
const order = removeFromOrder(organize.order, leftSections, moved);
|
||||
return withOrder(
|
||||
{
|
||||
groups: organize.groups,
|
||||
groupOf,
|
||||
pinned: group ? organize.pinned.filter((id) => !moved.has(id)) : organize.pinned,
|
||||
},
|
||||
order,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/** Returns tasks to their status group (unpinned and out of any custom group). */
|
||||
export function moveTasksToStatusGroup(tasks: readonly string[]) {
|
||||
changeOrganize((organize) => {
|
||||
const moved = new Set(tasks);
|
||||
const groupOf = { ...organize.groupOf };
|
||||
const leftSections = new Set<string>([PINNED_SECTION]);
|
||||
for (const task of tasks) {
|
||||
const prev = organize.groupOf[task];
|
||||
if (prev) leftSections.add(customSection(prev));
|
||||
delete groupOf[task];
|
||||
}
|
||||
const order = removeFromOrder(organize.order, leftSections, moved);
|
||||
return withOrder(
|
||||
{
|
||||
groups: organize.groups,
|
||||
groupOf,
|
||||
pinned: organize.pinned.filter((id) => !moved.has(id)),
|
||||
},
|
||||
order,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/** Places `sourceId` before or after `targetId` (moving it into the target's section when needed). */
|
||||
export function reorderTask(sourceId: string, targetId: string, position: "before" | "after") {
|
||||
const tasks = useAgents.getState().tasks.values();
|
||||
changeOrganize((organize) => reorderTaskInOrganize(organize, tasks, sourceId, targetId, position));
|
||||
}
|
||||
|
||||
/** Reorders a custom group before or after another custom group. */
|
||||
export function reorderTaskGroup(sourceId: string, targetId: string, position: "before" | "after") {
|
||||
changeOrganize((organize) => reorderGroupsInOrganize(organize, sourceId, targetId, position));
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача