mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-25 02:44:03 -10:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ec91e91c8 | ||
|
|
493bde17a9 |
No files matched your search
+43
-50
@@ -92,23 +92,23 @@ async function seedChanges(page: Page) {
|
||||
await page.evaluate(async (id) => {
|
||||
// Seed the store in the browser realm; a static import would run in Node.
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
(await import(storePath)).useAgents.setState({
|
||||
changes: new Map([
|
||||
[
|
||||
id,
|
||||
[
|
||||
{
|
||||
path: "/dev/acme-api/file.ts",
|
||||
relPath: "file.ts",
|
||||
kind: "modified",
|
||||
added: 1,
|
||||
removed: 0,
|
||||
oldPath: null,
|
||||
},
|
||||
],
|
||||
],
|
||||
]),
|
||||
});
|
||||
const ipcPath = "/src/platform/ipc.ts";
|
||||
const changes = [
|
||||
{
|
||||
path: "/dev/acme-api/file.ts",
|
||||
relPath: "file.ts",
|
||||
kind: "modified",
|
||||
added: 1,
|
||||
removed: 0,
|
||||
oldPath: null,
|
||||
repo: null,
|
||||
},
|
||||
];
|
||||
const { commands } = await import(ipcPath);
|
||||
// The Changes tab reads them again when it opens.
|
||||
commands.agentChanges = async () => ({ status: "ok", data: changes });
|
||||
commands.agentBaseText = async () => ({ status: "ok", data: "" });
|
||||
(await import(storePath)).useAgents.setState({ changes: new Map([[id, changes]]) });
|
||||
}, firstTask.id);
|
||||
}
|
||||
|
||||
@@ -383,42 +383,35 @@ test("Find Action focuses the current task input after closing its popup", async
|
||||
await expect.poll(() => selection(box)).toEqual(expected);
|
||||
});
|
||||
|
||||
test("docked Changes view returns to the task input without losing its selection", async ({ workbench: page }) => {
|
||||
test("a task's changes open in a tab of their own", async ({ workbench: page }) => {
|
||||
await seedTasks(page, "editor");
|
||||
await seedChanges(page);
|
||||
const box = messageBox(page);
|
||||
await expect(box).toBeVisible();
|
||||
const chip = page.getByRole("button", { name: /1 changed file/ });
|
||||
await chip.click();
|
||||
const changes = page.getByRole("region", { name: "Changes", exact: true });
|
||||
await expect(changes).toBeVisible();
|
||||
await expect(changes.getByRole("tree", { name: "Changed files" }).getByText("file.ts")).toBeVisible();
|
||||
await expect(changes.locator('[data-combined-block="/dev/acme-api/file.ts"]')).toBeVisible();
|
||||
// The conversation stays in its tab, as it was.
|
||||
await expect(box).toBeHidden();
|
||||
await page.getByRole("tab", { name: firstTask.title, exact: true }).click();
|
||||
await expect(box).toBeVisible();
|
||||
|
||||
// Again: the same tab, not another one.
|
||||
await chip.click();
|
||||
await expect(changes).toBeVisible();
|
||||
await expect(page.getByRole("tab", { name: `Changes: ${firstTask.title}` })).toHaveCount(1);
|
||||
});
|
||||
|
||||
test("a docked task's changes open in the editor, the conversation staying in place", async ({ workbench: page }) => {
|
||||
await seedTasks(page, "toolWindow");
|
||||
const box = messageBox(page);
|
||||
const expected = await selectDraft(box, true);
|
||||
await selectDraft(box, true);
|
||||
await seedChanges(page);
|
||||
await page.getByRole("button", { name: /1 changed file/ }).click();
|
||||
const changes = page.getByRole("complementary", { name: "Changes", exact: true });
|
||||
await expect(changes).toBeVisible();
|
||||
await expect(box).toHaveCount(0);
|
||||
await changes.getByRole("button", { name: "Back to conversation", exact: true }).focus();
|
||||
await page.keyboard.press("Meta+L");
|
||||
await expect(changes).toBeHidden();
|
||||
await expect(box).toBeFocused();
|
||||
await expect(page.getByRole("region", { name: "Changes", exact: true })).toBeVisible();
|
||||
await expect(box).toBeVisible();
|
||||
await expect(box).toHaveText(draft);
|
||||
await expect.poll(() => selection(box)).toEqual(expected);
|
||||
});
|
||||
|
||||
test("dragging the Changes pane's edge resizes it for the next session too", async ({ workbench: page }) => {
|
||||
await seedTasks(page, "editor");
|
||||
await seedChanges(page);
|
||||
const changes = page.getByRole("complementary", { name: "Changes", exact: true });
|
||||
await expect(changes).toBeVisible();
|
||||
const handle = changes.getByRole("separator", { name: "Resize changes", exact: true });
|
||||
const before = (await changes.boundingBox())!.width;
|
||||
const box = (await handle.boundingBox())!;
|
||||
await page.mouse.move(box.x, box.y + box.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(box.x - 120, box.y + box.height / 2, { steps: 5 });
|
||||
await page.mouse.up();
|
||||
await expect.poll(async () => (await changes.boundingBox())!.width).toBeGreaterThan(before + 100);
|
||||
const widened = (await changes.boundingBox())!.width;
|
||||
|
||||
// The next session starts with the dragged width.
|
||||
await page.reload();
|
||||
await expect(page.getByRole("tree", { name: "Project" })).toBeVisible();
|
||||
await seedTasks(page, "editor");
|
||||
await seedChanges(page);
|
||||
await expect.poll(async () => Math.round((await changes.boundingBox())!.width)).toBe(Math.round(widened));
|
||||
});
|
||||
@@ -1,85 +0,0 @@
|
||||
/**
|
||||
* The drag handle on the conversation side of a task's Changes pane. The width applies to
|
||||
* every task and is remembered across sessions.
|
||||
*/
|
||||
import type { CSSProperties, KeyboardEvent, PointerEvent } from "react";
|
||||
import { lockDragCursor } from "@/ui";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { clampChangesWidth, setChangesOptions, useChangesOptions } from "./changesOptions";
|
||||
import styles from "./Session.module.css";
|
||||
|
||||
/** CSS custom property read by `.withChanges` in Session.module.css. */
|
||||
const WIDTH_VAR = "--agent-changes-width";
|
||||
/** Keep in step with the conversation's minimum in `.withChanges`. */
|
||||
const MIN_CONVERSATION = 240;
|
||||
const KEY_STEP = 16;
|
||||
|
||||
/** Style for the session that holds the pane. */
|
||||
export function useChangesWidthStyle(): CSSProperties | undefined {
|
||||
const width = useChangesOptions((s) => s.width);
|
||||
return width == null ? undefined : ({ [WIDTH_VAR]: `${width}px` } as CSSProperties);
|
||||
}
|
||||
|
||||
/** Pane width for `px`, leaving the conversation its minimum in `session`. */
|
||||
function fit(px: number, session: HTMLElement) {
|
||||
return Math.min(clampChangesWidth(px), Math.max(0, session.clientWidth - MIN_CONVERSATION));
|
||||
}
|
||||
|
||||
/** Render as the first child of the pane. */
|
||||
export function ChangesResizer() {
|
||||
const onPointerDown = (e: PointerEvent<HTMLDivElement>) => {
|
||||
const handle = e.currentTarget;
|
||||
const pane = handle.parentElement;
|
||||
const session = pane?.parentElement;
|
||||
if (e.button !== 0 || !pane || !session) return;
|
||||
// No focus ring or text selection from a mouse drag.
|
||||
e.preventDefault();
|
||||
handle.setPointerCapture(e.pointerId);
|
||||
const start = pane.getBoundingClientRect().width;
|
||||
const origin = e.clientX;
|
||||
const previous = session.style.getPropertyValue(WIDTH_VAR);
|
||||
const releaseCursor = lockDragCursor("col-resize");
|
||||
let next: number | null = null;
|
||||
// Only this session follows the pointer; every task takes the new width on release.
|
||||
const move = (ev: globalThis.PointerEvent) => {
|
||||
if (!(ev.buttons & 1)) return end();
|
||||
next = fit(start + origin - ev.clientX, session);
|
||||
session.style.setProperty(WIDTH_VAR, `${next}px`);
|
||||
};
|
||||
const end = () => {
|
||||
handle.removeEventListener("pointermove", move);
|
||||
handle.removeEventListener("pointerup", end);
|
||||
handle.removeEventListener("pointercancel", end);
|
||||
releaseCursor();
|
||||
if (next != null) setChangesOptions({ width: clampChangesWidth(next) });
|
||||
else if (previous) session.style.setProperty(WIDTH_VAR, previous);
|
||||
else session.style.removeProperty(WIDTH_VAR);
|
||||
};
|
||||
handle.addEventListener("pointermove", move);
|
||||
handle.addEventListener("pointerup", end);
|
||||
handle.addEventListener("pointercancel", end);
|
||||
};
|
||||
|
||||
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
|
||||
const dir = e.key === "ArrowLeft" ? 1 : e.key === "ArrowRight" ? -1 : 0;
|
||||
const pane = e.currentTarget.parentElement;
|
||||
const session = pane?.parentElement;
|
||||
if (!dir || !pane || !session) return;
|
||||
e.preventDefault();
|
||||
setChangesOptions({
|
||||
width: clampChangesWidth(fit(pane.getBoundingClientRect().width + dir * KEY_STEP, session)),
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
role="separator"
|
||||
aria-orientation="vertical"
|
||||
aria-label={tx("Resize changes")}
|
||||
tabIndex={0}
|
||||
className={styles.changesResizer}
|
||||
onPointerDown={onPointerDown}
|
||||
onKeyDown={onKeyDown}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -8,7 +8,7 @@
|
||||
min-height: 0;
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
background: var(--bg-app);
|
||||
color: var(--fg);
|
||||
font-size: var(--fs-ui);
|
||||
@@ -20,24 +20,10 @@
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
border-right: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.conversation[hidden] {
|
||||
display: none;
|
||||
}
|
||||
.docked {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
overflow: hidden;
|
||||
}
|
||||
.docked .conversation {
|
||||
border-right: 0;
|
||||
}
|
||||
/* The pane takes its width while the conversation keeps 240px (half of a narrower session);
|
||||
keep that minimum in step with ChangesResizer. */
|
||||
.withChanges {
|
||||
grid-template-columns: minmax(min(240px, 50%), 1fr) minmax(0, var(--agent-changes-width, 280px));
|
||||
}
|
||||
.fitWidth .stream > * {
|
||||
width: 100%;
|
||||
}
|
||||
@@ -143,8 +129,7 @@
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
}
|
||||
.statusChip:hover,
|
||||
.statusChip[aria-expanded="true"] {
|
||||
.statusChip:hover {
|
||||
background: var(--bg-toolbar-hover);
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
@@ -1269,80 +1254,27 @@
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
/* The Changes tab: the file tree beside the diff of every file, under one toolbar. */
|
||||
.changes {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
min-width: 0;
|
||||
}
|
||||
/* On the conversation's border; the hit area reaches 3px either side of it. */
|
||||
.changesResizer {
|
||||
position: absolute;
|
||||
z-index: 1;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: -1px;
|
||||
width: 0;
|
||||
outline: none;
|
||||
}
|
||||
.changesResizer::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0 -3px;
|
||||
cursor: col-resize;
|
||||
}
|
||||
.changesResizer:focus-visible::after {
|
||||
background: color-mix(in srgb, var(--focus-ring) 55%, transparent);
|
||||
}
|
||||
.changesHeader {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
height: 32px;
|
||||
flex: none;
|
||||
padding: 0 6px 0 10px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.changesTitle {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-weight: 600;
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
.changesHeader > .muted {
|
||||
flex: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.changesScope {
|
||||
flex: none;
|
||||
padding: 0 4px;
|
||||
flex-direction: column;
|
||||
background: var(--bg-app);
|
||||
color: var(--fg);
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
.changesSummary {
|
||||
flex: none;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
padding: 4px 10px;
|
||||
padding-inline: var(--space-1-5);
|
||||
font-size: var(--fs-small);
|
||||
color: var(--fg-subtle);
|
||||
white-space: pre;
|
||||
}
|
||||
.changesList {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.changesList > * {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
.changesEmpty {
|
||||
padding: 8px 10px;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.change {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
|
||||
@@ -1,18 +1,14 @@
|
||||
/** An agent task as an editor tab: the conversation, a composer and the task's changed files. */
|
||||
/** An agent task as an editor tab: the conversation and a composer. */
|
||||
import type { AgentTask } from "@/bindings";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { onIdeEvent } from "@/platform/ipc";
|
||||
import { isSameOrInside } from "@/platform/paths";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { EmptyState, Icon, IconButton, T } from "@/ui";
|
||||
import { useEditorShown, useToolWindowShown, type EditorInput } from "@/workbench/contributions";
|
||||
import clsx from "clsx";
|
||||
import { Fragment, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import { useChangesWidthStyle } from "./ChangesResizer";
|
||||
import styles from "./Session.module.css";
|
||||
import { useAgentSettings } from "./agentSettings";
|
||||
import { useChangesOptions } from "./changesOptions";
|
||||
import { useAgentFontZoomSurface } from "./fontZoom";
|
||||
import {
|
||||
entriesKey,
|
||||
@@ -23,13 +19,13 @@ import {
|
||||
subagentWorking,
|
||||
type SubagentEntry,
|
||||
} from "./model";
|
||||
import { ChangesPane, useChangesOpen, useLocalHead } from "./session/ChangesPane";
|
||||
import { openTaskChanges, useChangesRefresh, useLocalHead, useTaskChanges } from "./session/ChangesTab";
|
||||
import { FoldedContent } from "./session/Folds";
|
||||
import { QuestionCard, type QuestionAnswer } from "./session/QuestionForm";
|
||||
import { SessionComposer } from "./session/SessionComposer";
|
||||
import { Stream } from "./session/Stream";
|
||||
import { focusedSession, registerReachableSession, setFocusedSession, type FocusedSession } from "./sessionFocus";
|
||||
import { cancelTask, loadEntries, markVisible, refreshChanges, scheduleChanges, useAgents } from "./store";
|
||||
import { cancelTask, loadEntries, markVisible, useAgents } from "./store";
|
||||
|
||||
export function SessionEditor({ input, docked = false }: { input: EditorInput; docked?: boolean }) {
|
||||
const id = (input.data as { task: string }).task;
|
||||
@@ -54,22 +50,13 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {
|
||||
const shown = useEditorShown();
|
||||
const task = useAgents((s) => s.tasks.get(id));
|
||||
const entries = useAgentsWhileShown(shown, (s) => s.entries.get(id));
|
||||
// Grouping needs commits of the task's own: local checkouts keep the flat list.
|
||||
const isolation = useAgents((s) => s.tasks.get(id)?.isolation);
|
||||
const grouped = useChangesOptions((s) => s.groupByCommit) && isolation === "worktree";
|
||||
const sinceStart = useAgents((s) => s.changes.get(id));
|
||||
const review = useAgents((s) => s.groupedChanges.get(id));
|
||||
const changes = grouped ? (review?.uncommitted ?? null) : (sinceStart ?? null);
|
||||
const commits = grouped ? (review?.commits ?? []) : [];
|
||||
const scope = useChangesOptions((s) => s.scope);
|
||||
const lastTurn = useAgents((s) => s.turnChanges.get(id));
|
||||
const { changes, commits } = useTaskChanges(id);
|
||||
useChangesRefresh(id);
|
||||
const project = useProject((s) => s.project);
|
||||
const head = useLocalHead(
|
||||
task?.isolation === "local" ? task.status : null,
|
||||
project?.workspace ? (task?.projectRoot ?? project.root) : null,
|
||||
);
|
||||
const [changesOpen, setChangesOpen] = useChangesOpen(id, changes ?? null, docked);
|
||||
const changesWidth = useChangesWidthStyle();
|
||||
// The subagent conversation shown, with the subagents that lead to it (empty: the task's own).
|
||||
const [path, setPath] = useState<string[]>([]);
|
||||
const view = path.at(-1) ?? null;
|
||||
@@ -87,25 +74,10 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {
|
||||
if (!connected) return;
|
||||
// Loaded entries are kept current by the task's events: reopening the tab needn't fetch them again.
|
||||
if (!useAgents.getState().entries.has(id)) void loadEntries(id).catch(() => undefined);
|
||||
void refreshChanges(id);
|
||||
}, [id, connected]);
|
||||
// A commit in the task's checkout moves its HEAD: pick it up without waiting for the agent.
|
||||
// The watcher reports every repository under the project, so the main checkout and other
|
||||
// tasks' worktrees would otherwise re-read this task's changes for nothing. A worktree's
|
||||
// gitdir is `<project>/.git/worktrees/<slug>`, outside the worktree itself: the watcher only
|
||||
// reports the project there, so that is the root its events match.
|
||||
const refreshRoot =
|
||||
task?.isolation === "worktree" ? (task.projectRoot ?? project?.root ?? null) : (task?.cwd ?? null);
|
||||
useEffect(() => {
|
||||
if (!connected) return;
|
||||
return onIdeEvent("vcsChanged", (e) => {
|
||||
if (!refreshRoot || !isSameOrInside(refreshRoot, e.root)) return;
|
||||
scheduleChanges(id);
|
||||
});
|
||||
}, [id, connected, refreshRoot]);
|
||||
useEffect(() => {
|
||||
if (shown && (!docked || !changesOpen)) return markVisible(id);
|
||||
}, [id, docked, changesOpen, shown]);
|
||||
if (shown) return markVisible(id);
|
||||
}, [id, shown]);
|
||||
useEffect(() => {
|
||||
if (connected && view && !useAgents.getState().entries.has(entriesKey(id, view))) {
|
||||
void loadEntries(id, view).catch(() => undefined);
|
||||
@@ -130,14 +102,9 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {
|
||||
setFinding(true);
|
||||
setFindFocus((n) => n + 1);
|
||||
},
|
||||
focusInput: canFocusInput
|
||||
? () => {
|
||||
if (docked) setChangesOpen(false);
|
||||
setInputFocus((n) => n + 1);
|
||||
}
|
||||
: undefined,
|
||||
focusInput: canFocusInput ? () => setInputFocus((n) => n + 1) : undefined,
|
||||
}),
|
||||
[canFocusInput, docked, setChangesOpen],
|
||||
[canFocusInput],
|
||||
);
|
||||
useLayoutEffect(() => {
|
||||
if (shown && sessionRoot.current?.contains(document.activeElement)) setFocusedSession(session);
|
||||
@@ -152,13 +119,8 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {
|
||||
return (
|
||||
<div
|
||||
ref={sessionRoot}
|
||||
className={clsx(
|
||||
styles.session,
|
||||
docked && styles.docked,
|
||||
changesOpen && !docked && styles.withChanges,
|
||||
fitWindowWidth && styles.fitWidth,
|
||||
)}
|
||||
style={{ ...changesWidth, ...zoomStyle }}
|
||||
className={clsx(styles.session, docked && styles.docked, fitWindowWidth && styles.fitWidth)}
|
||||
style={zoomStyle}
|
||||
onFocusCapture={() => shown && setFocusedSession(session)}
|
||||
onBlurCapture={(e) => {
|
||||
if (!e.currentTarget.contains(e.relatedTarget as Node | null) && focusedSession() === session) {
|
||||
@@ -166,7 +128,7 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className={styles.conversation} hidden={docked && changesOpen}>
|
||||
<div className={styles.conversation}>
|
||||
{view && <SubagentBar task={task} path={path} cards={cards} onNavigate={setPath} />}
|
||||
<FoldedContent.Provider value={finding && shown}>
|
||||
<Stream
|
||||
@@ -198,25 +160,12 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {
|
||||
head={head}
|
||||
changes={changes ?? null}
|
||||
commits={commits}
|
||||
changesOpen={changesOpen}
|
||||
onToggleChanges={() => setChangesOpen(!changesOpen)}
|
||||
onOpenChanges={() => openTaskChanges(id)}
|
||||
onOpenSubagent={openSubagent}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{changesOpen && (
|
||||
<ChangesPane
|
||||
task={task}
|
||||
changes={scope === "turn" ? (lastTurn ?? null) : (changes ?? null)}
|
||||
commits={scope === "turn" ? [] : commits}
|
||||
grouped={grouped && scope === "task"}
|
||||
scope={scope}
|
||||
head={head}
|
||||
docked={docked}
|
||||
onHide={() => setChangesOpen(false)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,26 +1,17 @@
|
||||
/** Changes pane view options, persisted across sessions. */
|
||||
/** Changes tab view options, persisted across sessions. */
|
||||
import { create } from "zustand";
|
||||
|
||||
/** What the pane lists: the whole task's changes, or the last turn's. */
|
||||
/** What the tab lists: the whole task's changes, or the last turn's. */
|
||||
export type ChangesScope = "task" | "turn";
|
||||
|
||||
export interface ChangesOptions {
|
||||
/** Files grouped by the commit that changed them; otherwise the flat list since the task started. */
|
||||
groupByCommit: boolean;
|
||||
scope: ChangesScope;
|
||||
/** Width of the pane beside the conversation, in px; `null`: the stylesheet's default. */
|
||||
width: number | null;
|
||||
}
|
||||
|
||||
/** IDEA-like default: the review view. */
|
||||
export const DEFAULT_CHANGES_OPTIONS: ChangesOptions = { groupByCommit: true, scope: "task", width: null };
|
||||
|
||||
const MIN_CHANGES_WIDTH = 200;
|
||||
const MAX_CHANGES_WIDTH = 1600;
|
||||
|
||||
export function clampChangesWidth(px: number) {
|
||||
return Math.round(Math.min(MAX_CHANGES_WIDTH, Math.max(MIN_CHANGES_WIDTH, px)));
|
||||
}
|
||||
export const DEFAULT_CHANGES_OPTIONS: ChangesOptions = { groupByCommit: true, scope: "task" };
|
||||
|
||||
const KEY = "openidea.agents.changesView.v1";
|
||||
|
||||
@@ -31,7 +22,6 @@ function load(): ChangesOptions {
|
||||
return {
|
||||
groupByCommit: typeof o.groupByCommit === "boolean" ? o.groupByCommit : DEFAULT_CHANGES_OPTIONS.groupByCommit,
|
||||
scope: o.scope === "turn" ? "turn" : DEFAULT_CHANGES_OPTIONS.scope,
|
||||
width: typeof o.width === "number" && Number.isFinite(o.width) ? clampChangesWidth(o.width) : null,
|
||||
};
|
||||
} catch {
|
||||
return { ...DEFAULT_CHANGES_OPTIONS };
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
/**
|
||||
* Coding agents (Claude Code, Codex, Gemini CLI over ACP, run by `ide-agent`): the
|
||||
* Agents tool window lists tasks by what they need from the user, a task opens as an
|
||||
* editor tab (conversation + changed files), and New Task is an editor page.
|
||||
* editor tab (its changed files in a Changes tab beside it), and New Task is an editor page.
|
||||
*/
|
||||
import { createElement } from "react";
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { clearContext, setContext } from "@/platform/context";
|
||||
import { onWorkflowSettingsChange, workflowSettings } from "@/platform/workflowSettings";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
@@ -26,7 +27,16 @@ import {
|
||||
} from "@/workbench/contributions";
|
||||
import { AgentsStatus } from "./AgentsStatus";
|
||||
import { activateSettingsPages } from "./settingsPages";
|
||||
import { HOME_KIND, MCP_PAGE, REGISTRY_PAGE, SESSION_KIND, TASK_DRAG, TOOL_WINDOW, providerIcon } from "./model";
|
||||
import {
|
||||
CHANGES_KIND,
|
||||
HOME_KIND,
|
||||
MCP_PAGE,
|
||||
REGISTRY_PAGE,
|
||||
SESSION_KIND,
|
||||
TASK_DRAG,
|
||||
TOOL_WINDOW,
|
||||
providerIcon,
|
||||
} from "./model";
|
||||
import { sendPaths, sendSelection, trackEditorCopies } from "./references";
|
||||
import { copyAgentReferenceActions, registerCopyAgentReference } from "./copyReference";
|
||||
import { diagnoseTestFailure, isTestFailure } from "./testFailure";
|
||||
@@ -168,6 +178,17 @@ export function activate(): () => void {
|
||||
// Rebuilding a long conversation on every switch back is slow.
|
||||
keepAlive: true,
|
||||
}),
|
||||
registerEditorKind({
|
||||
kind: CHANGES_KIND,
|
||||
component: lazyComponent(() => import("./session/ChangesTab").then((m) => m.ChangesTab)),
|
||||
title: (input) => {
|
||||
const title = useAgents.getState().tasks.get((input.data as { task: string }).task)?.title;
|
||||
return title ? tx("Changes: {task}").replace("{task}", title) : tx("Changes");
|
||||
},
|
||||
icon: () => "diff",
|
||||
restorable: true,
|
||||
onClose: (input) => releaseClosedTaskCache((input.data as { task: string }).task),
|
||||
}),
|
||||
registerEditorKind({
|
||||
kind: HOME_KIND,
|
||||
component: lazyComponent(() => import("./HomeEditor").then((m) => m.HomeEditor), { prefetch: true }),
|
||||
|
||||
@@ -19,6 +19,9 @@ export const SKILLS_PAGE = "agents.skills";
|
||||
export const POLICY_PAGE = "agents.policy";
|
||||
|
||||
export const sessionKey = (task: string) => `agent:${task}`;
|
||||
/** A task's Changes editor tab: its changed files and their diffs. */
|
||||
export const CHANGES_KIND = "agent-changes";
|
||||
export const changesKey = (task: string) => `agent-changes:${task}`;
|
||||
|
||||
/** Key of a conversation in the entries store: the task's own, or its subagent `subagent`'s. */
|
||||
export const entriesKey = (task: string, subagent: string | null) => (subagent ? `${task}/${subagent}` : task);
|
||||
|
||||
@@ -1,622 +0,0 @@
|
||||
import type { AgentChange, AgentCommit, AgentTask } from "@/bindings";
|
||||
import { commitFileDiffData, openDiff, withChain, type DiffData } from "@/features/vcs/diffInput";
|
||||
import { repositoryPath } from "@/features/vcs/repositoryPaths";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { call, commands, onIdeEvent } from "@/platform/ipc";
|
||||
import { basename, dirname, relativeDir } from "@/platform/project";
|
||||
import { fileIconName, Icon, IconButton, showContextMenu, Spinner, T, Tabs, Tree } from "@/ui";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { confirm } from "@/workbench/messages";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { ChangesResizer } from "../ChangesResizer";
|
||||
import styles from "../Session.module.css";
|
||||
import { setChangesOptions, type ChangesScope } from "../changesOptions";
|
||||
import { formatSentAt } from "../conversation";
|
||||
import { branchLabel } from "../model";
|
||||
import { acceptChanges, refreshChanges, rollbackChanges, useAgents } from "../store";
|
||||
|
||||
/**
|
||||
* Current branch of the project's repository for a local-checkout task (`status` is
|
||||
* `null` otherwise); followed as git changes, since the agent or the user may switch it.
|
||||
*/
|
||||
export function useLocalHead(status: AgentTask["status"] | null, root: string | null): string | null {
|
||||
const [head, setHead] = useState<string | null>(null);
|
||||
const local = status !== null;
|
||||
useEffect(() => {
|
||||
if (!local) return;
|
||||
let live = true;
|
||||
const load = () =>
|
||||
void call(commands.vcsBranchInfo(root)).then(
|
||||
(b) => live && setHead(b.head ?? b.headCommit?.slice(0, 8) ?? null),
|
||||
() => live && setHead(null),
|
||||
);
|
||||
load();
|
||||
const off = onIdeEvent("vcsChanged", load);
|
||||
return () => {
|
||||
live = false;
|
||||
off();
|
||||
};
|
||||
}, [local, status, root]);
|
||||
return local ? head : null;
|
||||
}
|
||||
|
||||
const KIND_COLOR: Partial<Record<AgentChange["kind"], string>> = {
|
||||
added: "var(--vcs-added)",
|
||||
untracked: "var(--vcs-untracked)",
|
||||
modified: "var(--vcs-modified)",
|
||||
renamed: "var(--vcs-modified)",
|
||||
deleted: "var(--vcs-deleted)",
|
||||
conflicted: "var(--vcs-conflict)",
|
||||
};
|
||||
|
||||
const CHANGES_OPEN_KEY = "openidea.agents.changesOpen.v1";
|
||||
|
||||
function loadChangesOpen(): Record<string, boolean> {
|
||||
try {
|
||||
const raw = globalThis.localStorage?.getItem(CHANGES_OPEN_KEY);
|
||||
const v: unknown = raw ? JSON.parse(raw) : {};
|
||||
return v && typeof v === "object" ? (v as Record<string, boolean>) : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the Changes pane is shown for `task`: the user's choice once made, else
|
||||
* only while the task has changes. Docked sessions stay in the conversation until
|
||||
* the user explicitly opens changes; navigation there does not change editor preferences.
|
||||
*/
|
||||
export function useChangesOpen(
|
||||
task: string,
|
||||
changes: AgentChange[] | null,
|
||||
docked: boolean,
|
||||
): [boolean, (open: boolean) => void] {
|
||||
const [state, setState] = useState<{
|
||||
task: string;
|
||||
open: boolean | undefined;
|
||||
}>(() => ({
|
||||
task,
|
||||
open: docked ? false : loadChangesOpen()[task],
|
||||
}));
|
||||
const chosen = state.task === task ? state.open : docked ? false : loadChangesOpen()[task];
|
||||
const set = useCallback(
|
||||
(open: boolean) => {
|
||||
setState({ task, open });
|
||||
if (docked) return;
|
||||
try {
|
||||
globalThis.localStorage?.setItem(CHANGES_OPEN_KEY, JSON.stringify({ ...loadChangesOpen(), [task]: open }));
|
||||
} catch {
|
||||
/* storage unavailable */
|
||||
}
|
||||
},
|
||||
[task, docked],
|
||||
);
|
||||
return [chosen ?? (changes?.length ?? 0) > 0, set];
|
||||
}
|
||||
|
||||
const NO_SELECTION: ReadonlySet<string> = new Set();
|
||||
|
||||
/** A row of the Changes pane: a group, a commit, a repository, or a file. */
|
||||
type ChangeRow =
|
||||
| {
|
||||
key: string;
|
||||
type: "group";
|
||||
label: "Uncommitted" | "Committed";
|
||||
count: number;
|
||||
added: number;
|
||||
removed: number;
|
||||
children: ChangeRow[];
|
||||
}
|
||||
| { key: string; type: "commit"; commit: AgentCommit; children: ChangeRow[] }
|
||||
| { key: string; type: "repo"; root: string; children: ChangeRow[] }
|
||||
| { key: string; type: "file"; change: AgentChange; commit?: AgentCommit };
|
||||
|
||||
/** `files` under a row per repository, when the task changed files in several. */
|
||||
function byRepository(files: ChangeRow[], prefix: string): ChangeRow[] {
|
||||
const roots = new Map<string, ChangeRow[]>();
|
||||
for (const f of files) {
|
||||
const root = f.type === "file" ? f.change.repo : null;
|
||||
if (!root) return files;
|
||||
roots.set(root, [...(roots.get(root) ?? []), f]);
|
||||
}
|
||||
if (roots.size < 2) return files;
|
||||
return [...roots].map(([root, children]) => ({
|
||||
key: `${prefix}repo:${root}`,
|
||||
type: "repo" as const,
|
||||
root,
|
||||
children,
|
||||
}));
|
||||
}
|
||||
|
||||
/** The keys of the repository rows, at the top or in a group: shown open. */
|
||||
function repositoryKeys(rows: readonly ChangeRow[]): string[] {
|
||||
return rows
|
||||
.flatMap((r) => (r.type === "group" ? r.children : [r]))
|
||||
.flatMap((r) => (r.type === "repo" ? [r.key] : []));
|
||||
}
|
||||
|
||||
function statsOf(changes: readonly AgentChange[]) {
|
||||
return changes.reduce((n, c) => ({ added: n.added + c.added, removed: n.removed + c.removed }), {
|
||||
added: 0,
|
||||
removed: 0,
|
||||
});
|
||||
}
|
||||
|
||||
function changeRows(
|
||||
uncommitted: readonly AgentChange[],
|
||||
commits: readonly AgentCommit[],
|
||||
grouped: boolean,
|
||||
): ChangeRow[] {
|
||||
if (!grouped)
|
||||
return byRepository(
|
||||
uncommitted.map((change) => ({ key: change.path, type: "file" as const, change })),
|
||||
"",
|
||||
);
|
||||
const roots: ChangeRow[] = [];
|
||||
if (uncommitted.length) {
|
||||
roots.push({
|
||||
key: "group:uncommitted",
|
||||
type: "group",
|
||||
label: "Uncommitted",
|
||||
count: uncommitted.length,
|
||||
...statsOf(uncommitted),
|
||||
children: byRepository(
|
||||
uncommitted.map((change) => ({ key: `uncommitted:${change.path}`, type: "file" as const, change })),
|
||||
"uncommitted:",
|
||||
),
|
||||
});
|
||||
}
|
||||
if (commits.length) {
|
||||
const files = commits.flatMap((commit) => commit.files);
|
||||
roots.push({
|
||||
key: "group:committed",
|
||||
type: "group",
|
||||
label: "Committed",
|
||||
count: commits.length,
|
||||
...statsOf(files),
|
||||
children: commits.map((commit) => ({
|
||||
key: `commit:${commit.id}`,
|
||||
type: "commit",
|
||||
commit,
|
||||
children: commit.files.map((change) => ({
|
||||
key: `commit:${commit.id}:${change.path}`,
|
||||
type: "file",
|
||||
change,
|
||||
commit,
|
||||
})),
|
||||
})),
|
||||
});
|
||||
}
|
||||
return roots;
|
||||
}
|
||||
|
||||
export function ChangesPane({
|
||||
task,
|
||||
changes,
|
||||
commits,
|
||||
grouped,
|
||||
scope,
|
||||
head,
|
||||
docked,
|
||||
onHide,
|
||||
}: {
|
||||
task: AgentTask;
|
||||
changes: AgentChange[] | null;
|
||||
commits: readonly AgentCommit[];
|
||||
grouped: boolean;
|
||||
scope: ChangesScope;
|
||||
head: string | null;
|
||||
docked: boolean;
|
||||
onHide: () => void;
|
||||
}) {
|
||||
// The views key their rows differently, and list different changes: a selection doesn't carry over.
|
||||
const view = scope === "turn" ? "turn" : grouped ? "grouped" : "flat";
|
||||
const [selection, setSelection] = useState<{
|
||||
view: string;
|
||||
keys: ReadonlySet<string>;
|
||||
}>(() => ({
|
||||
view,
|
||||
keys: NO_SELECTION,
|
||||
}));
|
||||
const selected = selection.view === view ? selection.keys : NO_SELECTION;
|
||||
const setSelected = (keys: ReadonlySet<string>) => setSelection({ view, keys });
|
||||
const rows = useMemo(() => changeRows(changes ?? [], commits, grouped), [changes, commits, grouped]);
|
||||
// Only the working files roll back; a commit's files are history.
|
||||
const rollbackable = useMemo(() => {
|
||||
const out = new Map<string, AgentChange>();
|
||||
const walk = (row: ChangeRow) => {
|
||||
if (row.type === "file") {
|
||||
if (!row.commit) out.set(row.key, row.change);
|
||||
} else if (row.type !== "commit") row.children.forEach(walk);
|
||||
};
|
||||
rows.forEach(walk);
|
||||
return out;
|
||||
}, [rows]);
|
||||
// Selection keys that no longer name a working file (a commit's file, a stale row) don't count.
|
||||
const picked = [...selected].flatMap((key) => rollbackable.get(key) ?? []);
|
||||
const added = changes?.reduce((n, c) => n + c.added, 0) ?? 0;
|
||||
const removed = changes?.reduce((n, c) => n + c.removed, 0) ?? 0;
|
||||
const rollback = async () => {
|
||||
const count = picked.length || changes?.length || 0;
|
||||
if (!count) return;
|
||||
const ok = await confirm({
|
||||
title: "Rollback Changes",
|
||||
message: (
|
||||
<>
|
||||
<p>
|
||||
{count === 1
|
||||
? tx`Roll back the changes to ${basename((picked[0] ?? changes![0]!).path)}?`
|
||||
: tx`Roll back the changes to ${count} files?`}
|
||||
</p>
|
||||
<p>
|
||||
{scope === "turn"
|
||||
? tx(
|
||||
"They go back to how they were when the last turn started. Edits of yours made to them since then are lost too.",
|
||||
)
|
||||
: grouped
|
||||
? tx("They go back to the last commit; changes made after it are lost.")
|
||||
: task.isolation === "worktree"
|
||||
? tx("They go back to how they were when the task started, in the task's worktree.")
|
||||
: tx(
|
||||
"They go back to how they were when the task started. Edits of yours made to them since then are lost too; edits from before the task are kept.",
|
||||
)}
|
||||
</p>
|
||||
</>
|
||||
),
|
||||
ok: "Rollback",
|
||||
icon: "warning",
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
await rollbackChanges(
|
||||
task.id,
|
||||
picked.length ? picked.map((c) => c.relPath) : null,
|
||||
scope === "turn" ? "lastTurn" : grouped ? "group" : "sinceStart",
|
||||
);
|
||||
setSelected(new Set());
|
||||
} catch (e) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: tx("Cannot roll back the changes"),
|
||||
body: e instanceof Error ? e.message : String(e),
|
||||
});
|
||||
}
|
||||
};
|
||||
const accept = async () => {
|
||||
// Accepting brings over the task's whole work, committed or not: grouping and the last turn
|
||||
// only change the listing.
|
||||
const all =
|
||||
(grouped || scope === "turn") && !picked.length
|
||||
? await call(commands.agentChanges(task.id, null)).catch(() => changes ?? [])
|
||||
: (changes ?? []);
|
||||
const targets = picked.length ? picked : all;
|
||||
const count = targets.length;
|
||||
if (!count) return;
|
||||
const name = basename(targets[0]!.path);
|
||||
const ok = await confirm({
|
||||
title: "Accept Changes",
|
||||
message: (
|
||||
<>
|
||||
<p>
|
||||
{count === 1
|
||||
? tx`Copy the changes to ${name} into the local checkout?`
|
||||
: tx`Copy the changes to ${count} files into the local checkout?`}
|
||||
</p>
|
||||
<p>{tx("They land uncommitted. Files you changed yourself since the task started are left alone.")}</p>
|
||||
</>
|
||||
),
|
||||
ok: "Accept",
|
||||
icon: "warning",
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
const outcome = await acceptChanges(task.id, picked.length ? picked.map((c) => c.relPath) : null);
|
||||
setSelected(new Set());
|
||||
if (outcome.skipped.length) {
|
||||
const skippedNames = outcome.skipped.map((s) => s.path).join(", ");
|
||||
notifications().notify({
|
||||
level: "warning",
|
||||
title: tx("Changes accepted, some files kept"),
|
||||
body: tx`You changed them yourself, accept them by hand: ${skippedNames}.`,
|
||||
});
|
||||
} else {
|
||||
notifications().notify({
|
||||
level: "info",
|
||||
title: tx("Changes accepted"),
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: tx("Cannot accept the changes"),
|
||||
body: e instanceof Error ? e.message : String(e),
|
||||
});
|
||||
}
|
||||
};
|
||||
return (
|
||||
<aside className={styles.changes} aria-label={tx("Changes")}>
|
||||
{!docked && <ChangesResizer />}
|
||||
<div className={styles.changesHeader}>
|
||||
{docked && <IconButton icon="arrow-left" title="Back to conversation" onClick={onHide} />}
|
||||
<span className={styles.changesTitle}>
|
||||
<T>Changes</T>
|
||||
</span>
|
||||
{changes && changes.length > 0 && (
|
||||
<span className={styles.muted}>
|
||||
{changes.length} <T>{changes.length === 1 ? "file" : "files"}</T>
|
||||
</span>
|
||||
)}
|
||||
<span className={styles.bannerSpacer} />
|
||||
{task.isolation === "worktree" && (
|
||||
<IconButton
|
||||
icon="check"
|
||||
title={picked.length ? "Accept Selected Changes…" : "Accept All Changes…"}
|
||||
disabled={(!changes?.length && !commits.length) || task.status === "starting" || task.status === "running"}
|
||||
onClick={() => void accept()}
|
||||
/>
|
||||
)}
|
||||
<IconButton
|
||||
icon="revert"
|
||||
title={picked.length ? "Rollback Selected Changes…" : "Rollback All Changes…"}
|
||||
disabled={!changes?.length || task.status === "starting" || task.status === "running"}
|
||||
onClick={() => void rollback()}
|
||||
/>
|
||||
<IconButton icon="refresh" title="Refresh" onClick={() => void refreshChanges(task.id)} />
|
||||
{task.isolation === "worktree" && scope === "task" && (
|
||||
<IconButton
|
||||
icon="eye"
|
||||
title="View Options"
|
||||
aria-haspopup="menu"
|
||||
onClick={(e) =>
|
||||
showContextMenu(e, [
|
||||
{ kind: "header", label: "Group By" },
|
||||
{
|
||||
id: "groupByCommit",
|
||||
label: "Commit",
|
||||
checked: grouped,
|
||||
run: () => {
|
||||
setChangesOptions({ groupByCommit: !grouped });
|
||||
void refreshChanges(task.id);
|
||||
},
|
||||
},
|
||||
])
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{!docked && <IconButton icon="chevron-right" title={tx("Hide changes")} size="small" onClick={onHide} />}
|
||||
</div>
|
||||
<Tabs
|
||||
variant="compact"
|
||||
className={styles.changesScope}
|
||||
aria-label="Changes to show"
|
||||
activeId={scope}
|
||||
onSelect={(id) => {
|
||||
if (id === scope) return;
|
||||
setChangesOptions({ scope: id === "turn" ? "turn" : "task" });
|
||||
void refreshChanges(task.id);
|
||||
}}
|
||||
items={[
|
||||
{ id: "task", label: "Whole Task" },
|
||||
{ id: "turn", label: "Last Turn" },
|
||||
]}
|
||||
/>
|
||||
{(scope === "turn" || grouped || head || task.base) && (
|
||||
<div className={styles.changesSummary}>
|
||||
{scope === "turn" ? (
|
||||
<T>Since the last turn started</T>
|
||||
) : (
|
||||
<>
|
||||
<T>vs</T> {grouped ? "HEAD" : (head ?? task.base)}
|
||||
</>
|
||||
)}
|
||||
{changes && changes.length > 0 && (
|
||||
<>
|
||||
{" "}
|
||||
<span className={styles.added}>+{added}</span> <span className={styles.removed}>−{removed}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className={styles.changesList}>
|
||||
{changes === null ? (
|
||||
<Spinner />
|
||||
) : (
|
||||
<Tree<ChangeRow>
|
||||
key={view}
|
||||
aria-label="Changed files"
|
||||
roots={rows}
|
||||
getKey={(n) => n.key}
|
||||
getLabel={(n) =>
|
||||
n.type === "file"
|
||||
? basename(n.change.path)
|
||||
: n.type === "commit"
|
||||
? n.commit.summary
|
||||
: n.type === "repo"
|
||||
? basename(n.root)
|
||||
: n.label
|
||||
}
|
||||
getChildren={(n) => (n.type === "file" ? undefined : n.children)}
|
||||
isExpandable={(n) => n.type !== "file" && n.children.length > 0}
|
||||
defaultExpanded={[...(grouped ? ["group:uncommitted", "group:committed"] : []), ...repositoryKeys(rows)]}
|
||||
activateExpandable={(n) => n.type === "commit"}
|
||||
selected={selected}
|
||||
onSelectionChange={(sel, lead) => {
|
||||
if (lead?.type === "file" && !lead.commit) setSelected(sel);
|
||||
}}
|
||||
onActivate={(n) => {
|
||||
if (n.type === "file") {
|
||||
if (n.commit) void openCommitDiff(task, n.commit, n.change.path);
|
||||
else if (grouped) void openUncommittedDiff(task, n.change.path);
|
||||
else void openChangeDiff(task, n.change.path, scope);
|
||||
} else if (n.type === "commit") {
|
||||
void openCommitDiff(task, n.commit, n.commit.files[0]?.path ?? "");
|
||||
}
|
||||
}}
|
||||
renderNode={(n) => {
|
||||
if (n.type === "group") {
|
||||
return (
|
||||
<span className={styles.changeGroup}>
|
||||
<span className={styles.changeGroupName}>
|
||||
{n.label === "Uncommitted" ? <T>Uncommitted</T> : <T>Committed</T>}
|
||||
</span>
|
||||
<span className={styles.muted}>
|
||||
{n.label === "Committed"
|
||||
? tx(n.count === 1 ? "1 commit" : "{count} commits").replace("{count}", String(n.count))
|
||||
: `${n.count} ${tx(n.count === 1 ? "file" : "files")}`}
|
||||
</span>
|
||||
<span className={styles.changeStat}>
|
||||
{n.added > 0 && <span className={styles.added}>+{n.added}</span>}{" "}
|
||||
{n.removed > 0 && <span className={styles.removed}>−{n.removed}</span>}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (n.type === "repo") {
|
||||
const files = n.children.flatMap((c) => (c.type === "file" ? [c.change] : []));
|
||||
const stats = statsOf(files);
|
||||
return (
|
||||
<span className={styles.changeGroup} title={n.root}>
|
||||
<Icon name="folder" size={14} />
|
||||
<span className={styles.changeGroupName}>{basename(n.root)}</span>
|
||||
<span
|
||||
className={styles.muted}
|
||||
>{`${files.length} ${tx(files.length === 1 ? "file" : "files")}`}</span>
|
||||
<span className={styles.changeStat}>
|
||||
{stats.added > 0 && <span className={styles.added}>+{stats.added}</span>}{" "}
|
||||
{stats.removed > 0 && <span className={styles.removed}>−{stats.removed}</span>}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (n.type === "commit") {
|
||||
const stats = statsOf(n.commit.files);
|
||||
return (
|
||||
<span className={styles.changeCommit} title={n.commit.message}>
|
||||
<Icon name="commit" size={14} />
|
||||
<span className={styles.changeCommitHash}>{n.commit.shortId}</span>
|
||||
<span className={styles.changeCommitSummary}>{n.commit.summary}</span>
|
||||
{n.commit.timeMs != null && (
|
||||
<span className={styles.changeCommitTime}>{formatSentAt(n.commit.timeMs)}</span>
|
||||
)}
|
||||
<span className={styles.changeStat}>
|
||||
{stats.added > 0 && <span className={styles.added}>+{stats.added}</span>}{" "}
|
||||
{stats.removed > 0 && <span className={styles.removed}>−{stats.removed}</span>}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span className={styles.change} title={n.change.relPath}>
|
||||
<Icon name={fileIconName(basename(n.change.path), n.change.path)} size={16} />
|
||||
<span className={styles.changeName} style={{ color: KIND_COLOR[n.change.kind] }}>
|
||||
{basename(n.change.path)}
|
||||
</span>
|
||||
<span className={styles.changeDir}>
|
||||
{n.change.repo
|
||||
? n.change.relPath.includes("/")
|
||||
? dirname(n.change.relPath)
|
||||
: ""
|
||||
: relativeDir(task.cwd, n.change.path)}
|
||||
</span>
|
||||
<span className={styles.changeStat}>
|
||||
{n.change.added > 0 && <span className={styles.added}>+{n.change.added}</span>}{" "}
|
||||
{n.change.removed > 0 && <span className={styles.removed}>−{n.change.removed}</span>}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}}
|
||||
empty={
|
||||
<div className={styles.changesEmpty}>
|
||||
{scope === "turn" ? <T>The last turn changed no files</T> : <T>No changes yet</T>}
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
/** Opens the diff of `path` between the task's start (or its last turn's) and now. */
|
||||
export async function openChangeDiff(task: AgentTask, path: string, scope: ChangesScope = "task") {
|
||||
const { changes, turnChanges } = useAgents.getState();
|
||||
const changed = ((scope === "turn" ? turnChanges : changes).get(task.id) ?? []).map((change) => change.path);
|
||||
const paths = changed.includes(path) ? changed : [path];
|
||||
const baseLabel = scope === "turn" ? tx("Before Last Turn") : (task.base ?? "Base");
|
||||
const right = task.isolation === "worktree" ? branchLabel(task.branch) : "Working tree";
|
||||
const diffs = await Promise.all(
|
||||
paths.map(async (file): Promise<DiffData> => {
|
||||
const base = await call(commands.agentBaseText(task.id, file, scope === "turn" ? "lastTurn" : null)).catch(
|
||||
() => null,
|
||||
);
|
||||
return {
|
||||
path: file,
|
||||
left: { type: "text", text: base ?? "", label: baseLabel },
|
||||
right: { type: "file", path: file, label: right },
|
||||
title: `${basename(file)} (${baseLabel} ↔ ${right})`,
|
||||
};
|
||||
}),
|
||||
);
|
||||
await openDiff(withChain(diffs, paths.indexOf(path)));
|
||||
}
|
||||
|
||||
/** Diff of `path` in the grouped view: `HEAD` ↔ the working file. */
|
||||
function uncommittedDiffData(task: AgentTask, change: AgentChange): DiffData {
|
||||
const left: DiffData["left"] =
|
||||
change.kind === "added" || change.kind === "untracked"
|
||||
? { type: "text", text: "", label: "(does not exist)", absent: true }
|
||||
: {
|
||||
type: "rev",
|
||||
rev: "HEAD",
|
||||
path: change.oldPath ? repositoryPath(task.cwd, change.oldPath) : undefined,
|
||||
label: "HEAD",
|
||||
};
|
||||
const right: DiffData["right"] =
|
||||
change.kind === "deleted"
|
||||
? { type: "text", text: "", label: "(deleted)", absent: true }
|
||||
: {
|
||||
type: "worktree",
|
||||
label: task.isolation === "worktree" ? branchLabel(task.branch) : "Working tree",
|
||||
};
|
||||
return { path: change.path, left, right };
|
||||
}
|
||||
|
||||
/** Registration needed before a diff reads revisions inside the task's own worktree. */
|
||||
async function ensureTaskRepo(task: AgentTask) {
|
||||
// A worktree is its own repository, outside the project's: `vcs_file_at` reads it only once
|
||||
// it is registered as an external log for this window.
|
||||
if (task.isolation === "worktree") await call(commands.vcsOpenExternalLog(task.cwd)).catch(() => undefined);
|
||||
}
|
||||
|
||||
/** Opens the diff of `path` among the task's uncommitted files (grouped view). */
|
||||
async function openUncommittedDiff(task: AgentTask, path: string) {
|
||||
const changes = useAgents.getState().groupedChanges.get(task.id)?.uncommitted ?? [];
|
||||
const paths = changes.map((change) => change.path);
|
||||
if (!paths.includes(path)) return;
|
||||
await ensureTaskRepo(task);
|
||||
await openDiff(
|
||||
withChain(
|
||||
changes.map((change) => uncommittedDiffData(task, change)),
|
||||
paths.indexOf(path),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Opens the diff of one commit (`parent ↔ commit`), starting at `path`. */
|
||||
async function openCommitDiff(task: AgentTask, commit: AgentCommit, path: string) {
|
||||
const diffs = commit.files.map((file) =>
|
||||
commitFileDiffData(
|
||||
{
|
||||
id: commit.id,
|
||||
shortId: commit.shortId,
|
||||
parents: commit.parent ? [commit.parent] : [],
|
||||
repo: task.cwd,
|
||||
},
|
||||
{ path: file.relPath, kind: file.kind, oldPath: file.oldPath },
|
||||
),
|
||||
);
|
||||
if (!diffs.length) return;
|
||||
await ensureTaskRepo(task);
|
||||
const index = commit.files.findIndex((file) => file.path === path);
|
||||
await openDiff(withChain(diffs, index < 0 ? 0 : index));
|
||||
}
|
||||
@@ -0,0 +1,694 @@
|
||||
/**
|
||||
* A task's Changes editor tab: its changed files in a tree beside one scrolling diff of
|
||||
* them all, with the actions on the task's work (accept, rollback).
|
||||
*/
|
||||
import type { AgentChange, AgentCommit, AgentTask } from "@/bindings";
|
||||
import { CombinedDiffView, type CombinedDiffHandle, type CombinedDiffItem } from "@/features/vcs/CombinedDiff";
|
||||
import { commitFileDiffData, diffInput, openDiff, withChain, type DiffData } from "@/features/vcs/diffInput";
|
||||
import { repositoryPath } from "@/features/vcs/repositoryPaths";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { call, commands, onIdeEvent } from "@/platform/ipc";
|
||||
import { isSameOrInside } from "@/platform/paths";
|
||||
import { basename, dirname, relativeDir, useProject } from "@/platform/project";
|
||||
import { EmptyState, fileIconName, Icon, IconButton, showContextMenu, Spinner, T, Tabs, Tree } from "@/ui";
|
||||
import { editorService, notifications, type EditorInput } from "@/workbench/contributions";
|
||||
import { confirm } from "@/workbench/messages";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import styles from "../Session.module.css";
|
||||
import { setChangesOptions, useChangesOptions, type ChangesScope } from "../changesOptions";
|
||||
import { formatSentAt } from "../conversation";
|
||||
import { branchLabel, CHANGES_KIND, changesKey } from "../model";
|
||||
import { acceptChanges, refreshChanges, rollbackChanges, scheduleChanges, useAgents } from "../store";
|
||||
|
||||
/**
|
||||
* Current branch of the project's repository for a local-checkout task (`status` is
|
||||
* `null` otherwise); followed as git changes, since the agent or the user may switch it.
|
||||
*/
|
||||
export function useLocalHead(status: AgentTask["status"] | null, root: string | null): string | null {
|
||||
const [head, setHead] = useState<string | null>(null);
|
||||
const local = status !== null;
|
||||
useEffect(() => {
|
||||
if (!local) return;
|
||||
let live = true;
|
||||
const load = () =>
|
||||
void call(commands.vcsBranchInfo(root)).then(
|
||||
(b) => live && setHead(b.head ?? b.headCommit?.slice(0, 8) ?? null),
|
||||
() => live && setHead(null),
|
||||
);
|
||||
load();
|
||||
const off = onIdeEvent("vcsChanged", load);
|
||||
return () => {
|
||||
live = false;
|
||||
off();
|
||||
};
|
||||
}, [local, status, root]);
|
||||
return local ? head : null;
|
||||
}
|
||||
|
||||
const KIND_COLOR: Partial<Record<AgentChange["kind"], string>> = {
|
||||
added: "var(--vcs-added)",
|
||||
untracked: "var(--vcs-untracked)",
|
||||
modified: "var(--vcs-modified)",
|
||||
renamed: "var(--vcs-modified)",
|
||||
deleted: "var(--vcs-deleted)",
|
||||
conflicted: "var(--vcs-conflict)",
|
||||
};
|
||||
|
||||
/** What a task's changes look like as the options show them: the files, and the commits they're grouped by. */
|
||||
export function useTaskChanges(id: string) {
|
||||
// Grouping needs commits of the task's own: local checkouts keep the flat list.
|
||||
const isolation = useAgents((s) => s.tasks.get(id)?.isolation);
|
||||
const grouped = useChangesOptions((s) => s.groupByCommit) && isolation === "worktree";
|
||||
const sinceStart = useAgents((s) => s.changes.get(id));
|
||||
const review = useAgents((s) => s.groupedChanges.get(id));
|
||||
const changes = (grouped ? review?.uncommitted : sinceStart) ?? null;
|
||||
const commits = (grouped ? review?.commits : undefined) ?? NO_COMMITS;
|
||||
return { grouped, changes, commits };
|
||||
}
|
||||
|
||||
const NO_COMMITS: readonly AgentCommit[] = [];
|
||||
|
||||
/**
|
||||
* Reads the task's changes once the project's agents are connected, and again as its checkout
|
||||
* changes. The watcher reports every repository under the project, so the main checkout and other
|
||||
* tasks' worktrees would otherwise re-read this task's changes for nothing. A worktree's gitdir is
|
||||
* `<project>/.git/worktrees/<slug>`, outside the worktree itself: the watcher only reports the
|
||||
* project there, so that is the root its events match.
|
||||
*/
|
||||
export function useChangesRefresh(id: string) {
|
||||
const connected = useAgents((s) => s.loaded);
|
||||
const task = useAgents((s) => s.tasks.get(id));
|
||||
const projectRoot = useProject((s) => s.project?.root ?? null);
|
||||
const refreshRoot = task?.isolation === "worktree" ? (task.projectRoot ?? projectRoot) : (task?.cwd ?? null);
|
||||
useEffect(() => {
|
||||
if (connected) void refreshChanges(id);
|
||||
}, [id, connected]);
|
||||
useEffect(() => {
|
||||
if (!connected) return;
|
||||
return onIdeEvent("vcsChanged", (e) => {
|
||||
if (!refreshRoot || !isSameOrInside(refreshRoot, e.root)) return;
|
||||
scheduleChanges(id);
|
||||
});
|
||||
}, [id, connected, refreshRoot]);
|
||||
}
|
||||
|
||||
/** Shows the task's Changes tab: a new tab the first time, where it already is after that. */
|
||||
export function openTaskChanges(task: string) {
|
||||
void editorService().openInput({ kind: CHANGES_KIND, key: changesKey(task), data: { task } }, { focus: true });
|
||||
}
|
||||
|
||||
const NO_ITEMS: readonly CombinedDiffItem[] = [];
|
||||
|
||||
const NO_SELECTION: ReadonlySet<string> = new Set();
|
||||
|
||||
/** A row of the Changes pane: a group, a commit, a repository, or a file. */
|
||||
type ChangeRow =
|
||||
| {
|
||||
key: string;
|
||||
type: "group";
|
||||
label: "Uncommitted" | "Committed";
|
||||
count: number;
|
||||
added: number;
|
||||
removed: number;
|
||||
children: ChangeRow[];
|
||||
}
|
||||
| { key: string; type: "commit"; commit: AgentCommit; children: ChangeRow[] }
|
||||
| { key: string; type: "repo"; root: string; children: ChangeRow[] }
|
||||
| { key: string; type: "file"; change: AgentChange; commit?: AgentCommit };
|
||||
|
||||
/** `files` under a row per repository, when the task changed files in several. */
|
||||
function byRepository(files: ChangeRow[], prefix: string): ChangeRow[] {
|
||||
const roots = new Map<string, ChangeRow[]>();
|
||||
for (const f of files) {
|
||||
const root = f.type === "file" ? f.change.repo : null;
|
||||
if (!root) return files;
|
||||
roots.set(root, [...(roots.get(root) ?? []), f]);
|
||||
}
|
||||
if (roots.size < 2) return files;
|
||||
return [...roots].map(([root, children]) => ({
|
||||
key: `${prefix}repo:${root}`,
|
||||
type: "repo" as const,
|
||||
root,
|
||||
children,
|
||||
}));
|
||||
}
|
||||
|
||||
/** The keys of the repository rows, at the top or in a group: shown open. */
|
||||
function repositoryKeys(rows: readonly ChangeRow[]): string[] {
|
||||
return rows
|
||||
.flatMap((r) => (r.type === "group" ? r.children : [r]))
|
||||
.flatMap((r) => (r.type === "repo" ? [r.key] : []));
|
||||
}
|
||||
|
||||
function statsOf(changes: readonly AgentChange[]) {
|
||||
return changes.reduce((n, c) => ({ added: n.added + c.added, removed: n.removed + c.removed }), {
|
||||
added: 0,
|
||||
removed: 0,
|
||||
});
|
||||
}
|
||||
|
||||
function changeRows(
|
||||
uncommitted: readonly AgentChange[],
|
||||
commits: readonly AgentCommit[],
|
||||
grouped: boolean,
|
||||
): ChangeRow[] {
|
||||
if (!grouped)
|
||||
return byRepository(
|
||||
uncommitted.map((change) => ({ key: change.path, type: "file" as const, change })),
|
||||
"",
|
||||
);
|
||||
const roots: ChangeRow[] = [];
|
||||
if (uncommitted.length) {
|
||||
roots.push({
|
||||
key: "group:uncommitted",
|
||||
type: "group",
|
||||
label: "Uncommitted",
|
||||
count: uncommitted.length,
|
||||
...statsOf(uncommitted),
|
||||
children: byRepository(
|
||||
uncommitted.map((change) => ({ key: `uncommitted:${change.path}`, type: "file" as const, change })),
|
||||
"uncommitted:",
|
||||
),
|
||||
});
|
||||
}
|
||||
if (commits.length) {
|
||||
const files = commits.flatMap((commit) => commit.files);
|
||||
roots.push({
|
||||
key: "group:committed",
|
||||
type: "group",
|
||||
label: "Committed",
|
||||
count: commits.length,
|
||||
...statsOf(files),
|
||||
children: commits.map((commit) => ({
|
||||
key: `commit:${commit.id}`,
|
||||
type: "commit",
|
||||
commit,
|
||||
children: commit.files.map((change) => ({
|
||||
key: `commit:${commit.id}:${change.path}`,
|
||||
type: "file",
|
||||
change,
|
||||
commit,
|
||||
})),
|
||||
})),
|
||||
});
|
||||
}
|
||||
return roots;
|
||||
}
|
||||
|
||||
export function ChangesTab({ input }: { input: EditorInput }) {
|
||||
const id = (input.data as { task: string }).task;
|
||||
const task = useAgents((s) => s.tasks.get(id));
|
||||
if (!task) return <EmptyState title="This agent task no longer exists" />;
|
||||
return <TaskChanges key={id} task={task} tabKey={input.key} />;
|
||||
}
|
||||
|
||||
function TaskChanges({ task, tabKey }: { task: AgentTask; tabKey: string }) {
|
||||
useChangesRefresh(task.id);
|
||||
const { grouped: groupedView, changes: taskChanges, commits: taskCommits } = useTaskChanges(task.id);
|
||||
const scope = useChangesOptions((s) => s.scope);
|
||||
const lastTurn = useAgents((s) => s.turnChanges.get(task.id));
|
||||
const project = useProject((s) => s.project);
|
||||
const head = useLocalHead(
|
||||
task.isolation === "local" ? task.status : null,
|
||||
project?.workspace ? (task.projectRoot ?? project.root) : null,
|
||||
);
|
||||
const changes = scope === "turn" ? (lastTurn ?? null) : taskChanges;
|
||||
const commits = scope === "turn" ? NO_COMMITS : taskCommits;
|
||||
const grouped = groupedView && scope === "task";
|
||||
// The views key their rows differently, and list different changes: a selection doesn't carry over.
|
||||
const view = scope === "turn" ? "turn" : grouped ? "grouped" : "flat";
|
||||
const [selection, setSelection] = useState<{
|
||||
view: string;
|
||||
keys: ReadonlySet<string>;
|
||||
}>(() => ({
|
||||
view,
|
||||
keys: NO_SELECTION,
|
||||
}));
|
||||
const selected = selection.view === view ? selection.keys : NO_SELECTION;
|
||||
const setSelected = (keys: ReadonlySet<string>) => setSelection({ view, keys });
|
||||
const rows = useMemo(() => changeRows(changes ?? [], commits, grouped), [changes, commits, grouped]);
|
||||
// Only the working files roll back; a commit's files are history.
|
||||
const rollbackable = useMemo(() => {
|
||||
const out = new Map<string, AgentChange>();
|
||||
const walk = (row: ChangeRow) => {
|
||||
if (row.type === "file") {
|
||||
if (!row.commit) out.set(row.key, row.change);
|
||||
} else if (row.type !== "commit") row.children.forEach(walk);
|
||||
};
|
||||
rows.forEach(walk);
|
||||
return out;
|
||||
}, [rows]);
|
||||
// Selection keys that no longer name a working file (a commit's file, a stale row) don't count.
|
||||
const picked = [...selected].flatMap((key) => rollbackable.get(key) ?? []);
|
||||
const added = changes?.reduce((n, c) => n + c.added, 0) ?? 0;
|
||||
const removed = changes?.reduce((n, c) => n + c.removed, 0) ?? 0;
|
||||
const rollback = async () => {
|
||||
const count = picked.length || changes?.length || 0;
|
||||
if (!count) return;
|
||||
const ok = await confirm({
|
||||
title: "Rollback Changes",
|
||||
message: (
|
||||
<>
|
||||
<p>
|
||||
{count === 1
|
||||
? tx`Roll back the changes to ${basename((picked[0] ?? changes![0]!).path)}?`
|
||||
: tx`Roll back the changes to ${count} files?`}
|
||||
</p>
|
||||
<p>
|
||||
{scope === "turn"
|
||||
? tx(
|
||||
"They go back to how they were when the last turn started. Edits of yours made to them since then are lost too.",
|
||||
)
|
||||
: grouped
|
||||
? tx("They go back to the last commit; changes made after it are lost.")
|
||||
: task.isolation === "worktree"
|
||||
? tx("They go back to how they were when the task started, in the task's worktree.")
|
||||
: tx(
|
||||
"They go back to how they were when the task started. Edits of yours made to them since then are lost too; edits from before the task are kept.",
|
||||
)}
|
||||
</p>
|
||||
</>
|
||||
),
|
||||
ok: "Rollback",
|
||||
icon: "warning",
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
await rollbackChanges(
|
||||
task.id,
|
||||
picked.length ? picked.map((c) => c.relPath) : null,
|
||||
scope === "turn" ? "lastTurn" : grouped ? "group" : "sinceStart",
|
||||
);
|
||||
setSelected(new Set());
|
||||
} catch (e) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: tx("Cannot roll back the changes"),
|
||||
body: e instanceof Error ? e.message : String(e),
|
||||
});
|
||||
}
|
||||
};
|
||||
const accept = async () => {
|
||||
// Accepting brings over the task's whole work, committed or not: grouping and the last turn
|
||||
// only change the listing.
|
||||
const all =
|
||||
(grouped || scope === "turn") && !picked.length
|
||||
? await call(commands.agentChanges(task.id, null)).catch(() => changes ?? [])
|
||||
: (changes ?? []);
|
||||
const targets = picked.length ? picked : all;
|
||||
const count = targets.length;
|
||||
if (!count) return;
|
||||
const name = basename(targets[0]!.path);
|
||||
const ok = await confirm({
|
||||
title: "Accept Changes",
|
||||
message: (
|
||||
<>
|
||||
<p>
|
||||
{count === 1
|
||||
? tx`Copy the changes to ${name} into the local checkout?`
|
||||
: tx`Copy the changes to ${count} files into the local checkout?`}
|
||||
</p>
|
||||
<p>{tx("They land uncommitted. Files you changed yourself since the task started are left alone.")}</p>
|
||||
</>
|
||||
),
|
||||
ok: "Accept",
|
||||
icon: "warning",
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
const outcome = await acceptChanges(task.id, picked.length ? picked.map((c) => c.relPath) : null);
|
||||
setSelected(new Set());
|
||||
if (outcome.skipped.length) {
|
||||
const skippedNames = outcome.skipped.map((s) => s.path).join(", ");
|
||||
notifications().notify({
|
||||
level: "warning",
|
||||
title: tx("Changes accepted, some files kept"),
|
||||
body: tx`You changed them yourself, accept them by hand: ${skippedNames}.`,
|
||||
});
|
||||
} else {
|
||||
notifications().notify({
|
||||
level: "info",
|
||||
title: tx("Changes accepted"),
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: tx("Cannot accept the changes"),
|
||||
body: e instanceof Error ? e.message : String(e),
|
||||
});
|
||||
}
|
||||
};
|
||||
const items = useDiffItems(task, rows, grouped, scope);
|
||||
const diff = useRef<CombinedDiffHandle>(null);
|
||||
const busy = task.status === "starting" || task.status === "running";
|
||||
const fileTree =
|
||||
changes === null ? (
|
||||
<Spinner />
|
||||
) : (
|
||||
<Tree<ChangeRow>
|
||||
key={view}
|
||||
aria-label="Changed files"
|
||||
roots={rows}
|
||||
getKey={(n) => n.key}
|
||||
getLabel={(n) =>
|
||||
n.type === "file"
|
||||
? basename(n.change.path)
|
||||
: n.type === "commit"
|
||||
? n.commit.summary
|
||||
: n.type === "repo"
|
||||
? basename(n.root)
|
||||
: n.label
|
||||
}
|
||||
getChildren={(n) => (n.type === "file" ? undefined : n.children)}
|
||||
isExpandable={(n) => n.type !== "file" && n.children.length > 0}
|
||||
defaultExpanded={[...(grouped ? ["group:uncommitted", "group:committed"] : []), ...repositoryKeys(rows)]}
|
||||
activateExpandable={(n) => n.type === "commit"}
|
||||
selected={selected}
|
||||
onSelectionChange={(sel, lead) => {
|
||||
if (lead?.type === "file" && !lead.commit) setSelected(sel);
|
||||
// The diff follows the tree: a row shows its first file.
|
||||
const first = lead && firstFile(lead);
|
||||
if (first) diff.current?.reveal(first);
|
||||
}}
|
||||
onActivate={(n) => {
|
||||
const first = firstFile(n);
|
||||
if (first) diff.current?.reveal(first);
|
||||
}}
|
||||
renderNode={(n) => {
|
||||
if (n.type === "group") {
|
||||
return (
|
||||
<span className={styles.changeGroup}>
|
||||
<span className={styles.changeGroupName}>
|
||||
{n.label === "Uncommitted" ? <T>Uncommitted</T> : <T>Committed</T>}
|
||||
</span>
|
||||
<span className={styles.muted}>
|
||||
{n.label === "Committed"
|
||||
? tx(n.count === 1 ? "1 commit" : "{count} commits").replace("{count}", String(n.count))
|
||||
: `${n.count} ${tx(n.count === 1 ? "file" : "files")}`}
|
||||
</span>
|
||||
<span className={styles.changeStat}>
|
||||
{n.added > 0 && <span className={styles.added}>+{n.added}</span>}{" "}
|
||||
{n.removed > 0 && <span className={styles.removed}>−{n.removed}</span>}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (n.type === "repo") {
|
||||
const files = n.children.flatMap((c) => (c.type === "file" ? [c.change] : []));
|
||||
const stats = statsOf(files);
|
||||
return (
|
||||
<span className={styles.changeGroup} title={n.root}>
|
||||
<Icon name="folder" size={14} />
|
||||
<span className={styles.changeGroupName}>{basename(n.root)}</span>
|
||||
<span className={styles.muted}>{`${files.length} ${tx(files.length === 1 ? "file" : "files")}`}</span>
|
||||
<span className={styles.changeStat}>
|
||||
{stats.added > 0 && <span className={styles.added}>+{stats.added}</span>}{" "}
|
||||
{stats.removed > 0 && <span className={styles.removed}>−{stats.removed}</span>}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (n.type === "commit") {
|
||||
const stats = statsOf(n.commit.files);
|
||||
return (
|
||||
<span className={styles.changeCommit} title={n.commit.message}>
|
||||
<Icon name="commit" size={14} />
|
||||
<span className={styles.changeCommitHash}>{n.commit.shortId}</span>
|
||||
<span className={styles.changeCommitSummary}>{n.commit.summary}</span>
|
||||
{n.commit.timeMs != null && (
|
||||
<span className={styles.changeCommitTime}>{formatSentAt(n.commit.timeMs)}</span>
|
||||
)}
|
||||
<span className={styles.changeStat}>
|
||||
{stats.added > 0 && <span className={styles.added}>+{stats.added}</span>}{" "}
|
||||
{stats.removed > 0 && <span className={styles.removed}>−{stats.removed}</span>}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span className={styles.change} title={n.change.relPath}>
|
||||
<Icon name={fileIconName(basename(n.change.path), n.change.path)} size={16} />
|
||||
<span className={styles.changeName} style={{ color: KIND_COLOR[n.change.kind] }}>
|
||||
{basename(n.change.path)}
|
||||
</span>
|
||||
<span className={styles.changeDir}>{changeDir(task, n.change)}</span>
|
||||
<span className={styles.changeStat}>
|
||||
{n.change.added > 0 && <span className={styles.added}>+{n.change.added}</span>}{" "}
|
||||
{n.change.removed > 0 && <span className={styles.removed}>−{n.change.removed}</span>}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
<section className={styles.changes} aria-label={tx("Changes")}>
|
||||
<CombinedDiffView
|
||||
key={view}
|
||||
items={items ?? NO_ITEMS}
|
||||
tabKey={tabKey}
|
||||
handle={diff}
|
||||
empty={
|
||||
items === null ? (
|
||||
<Spinner />
|
||||
) : scope === "turn" ? (
|
||||
<T>The last turn changed no files</T>
|
||||
) : (
|
||||
<T>No changes yet</T>
|
||||
)
|
||||
}
|
||||
toolbarStart={
|
||||
<>
|
||||
<Tabs
|
||||
variant="compact"
|
||||
aria-label="Changes to show"
|
||||
activeId={scope}
|
||||
onSelect={(id) => {
|
||||
if (id === scope) return;
|
||||
setChangesOptions({ scope: id === "turn" ? "turn" : "task" });
|
||||
void refreshChanges(task.id);
|
||||
}}
|
||||
items={[
|
||||
{ id: "task", label: "Whole Task" },
|
||||
{ id: "turn", label: "Last Turn" },
|
||||
]}
|
||||
/>
|
||||
{(scope === "turn" || grouped || head || task.base) && (
|
||||
<span className={styles.changesSummary}>
|
||||
{scope === "turn" ? (
|
||||
<T>Since the last turn started</T>
|
||||
) : (
|
||||
<>
|
||||
<T>vs</T> {grouped ? "HEAD" : (head ?? task.base)}
|
||||
</>
|
||||
)}
|
||||
{changes && changes.length > 0 && (
|
||||
<>
|
||||
{" "}
|
||||
<span className={styles.added}>+{added}</span> <span className={styles.removed}>−{removed}</span>
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
toolbarEnd={
|
||||
<>
|
||||
{task.isolation === "worktree" && (
|
||||
<IconButton
|
||||
size="small"
|
||||
icon="check"
|
||||
title={picked.length ? "Accept Selected Changes…" : "Accept All Changes…"}
|
||||
disabled={(!changes?.length && !commits.length) || busy}
|
||||
onClick={() => void accept()}
|
||||
/>
|
||||
)}
|
||||
<IconButton
|
||||
size="small"
|
||||
icon="revert"
|
||||
title={picked.length ? "Rollback Selected Changes…" : "Rollback All Changes…"}
|
||||
disabled={!changes?.length || busy}
|
||||
onClick={() => void rollback()}
|
||||
/>
|
||||
<IconButton icon="refresh" title="Refresh" size="small" onClick={() => void refreshChanges(task.id)} />
|
||||
{task.isolation === "worktree" && scope === "task" && (
|
||||
<IconButton
|
||||
size="small"
|
||||
icon="eye"
|
||||
title="View Options"
|
||||
aria-haspopup="menu"
|
||||
onClick={(e) =>
|
||||
showContextMenu(e, [
|
||||
{ kind: "header", label: "Group By" },
|
||||
{
|
||||
id: "groupByCommit",
|
||||
label: "Commit",
|
||||
checked: grouped,
|
||||
run: () => {
|
||||
setChangesOptions({ groupByCommit: !grouped });
|
||||
void refreshChanges(task.id);
|
||||
},
|
||||
},
|
||||
])
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
files={{ content: fileTree, label: tx("Resize changed files"), storageKey: "openidea.agents.changesTab.files" }}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** Key of the first file row at or under `row`: what the diff scrolls to for it. */
|
||||
function firstFile(row: ChangeRow): string | null {
|
||||
if (row.type === "file") return row.key;
|
||||
for (const child of row.children) {
|
||||
const key = firstFile(child);
|
||||
if (key) return key;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The file rows under `rows`, in tree order (collapsed ones included). */
|
||||
function fileRows(rows: readonly ChangeRow[]): Extract<ChangeRow, { type: "file" }>[] {
|
||||
return rows.flatMap((r) => (r.type === "file" ? [r] : fileRows(r.children)));
|
||||
}
|
||||
|
||||
/**
|
||||
* The diff of every file row, keyed like the rows. Since the task started (or the last turn),
|
||||
* the left side is the base the backend kept; grouped, `HEAD` or the commit's parent. A file
|
||||
* whose diff is unchanged keeps its object, so its block doesn't load again as the task works.
|
||||
*/
|
||||
function useDiffItems(
|
||||
task: AgentTask,
|
||||
rows: readonly ChangeRow[],
|
||||
grouped: boolean,
|
||||
scope: ChangesScope,
|
||||
): CombinedDiffItem[] | null {
|
||||
const [items, setItems] = useState<CombinedDiffItem[] | null>(null);
|
||||
const previous = useRef(new Map<string, CombinedDiffItem>());
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
const files = fileRows(rows);
|
||||
const detail = (row: (typeof files)[number]) => {
|
||||
const dir = changeDir(task, row.change);
|
||||
return row.commit ? [row.commit.shortId, dir].filter(Boolean).join(" · ") : dir;
|
||||
};
|
||||
const build = async (): Promise<CombinedDiffItem[]> => {
|
||||
if (grouped) await ensureTaskRepo(task);
|
||||
return Promise.all(
|
||||
files.map(async (row) => {
|
||||
const data = row.commit
|
||||
? commitFileDiff(task, row.commit, row.change)
|
||||
: grouped
|
||||
? uncommittedDiffData(task, row.change)
|
||||
: await changeDiffData(task, row.change.path, scope, row.change.kind);
|
||||
return { key: row.key, data, detail: detail(row) };
|
||||
}),
|
||||
);
|
||||
};
|
||||
void build().then((next) => {
|
||||
if (!live) return;
|
||||
const kept = next.map((item) => {
|
||||
const before = previous.current.get(item.key);
|
||||
return before && diffInput(before.data).key === diffInput(item.data).key && before.detail === item.detail
|
||||
? before
|
||||
: item;
|
||||
});
|
||||
previous.current = new Map(kept.map((item) => [item.key, item]));
|
||||
setItems(kept);
|
||||
});
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [task, rows, grouped, scope]);
|
||||
return items;
|
||||
}
|
||||
|
||||
/** The folder of a changed file, as the tree names it. */
|
||||
function changeDir(task: AgentTask, change: AgentChange): string {
|
||||
if (!change.repo) return relativeDir(task.cwd, change.path);
|
||||
return change.relPath.includes("/") ? dirname(change.relPath) : "";
|
||||
}
|
||||
|
||||
/** Diff of `path` between the task's start (or its last turn's) and now. */
|
||||
async function changeDiffData(
|
||||
task: AgentTask,
|
||||
path: string,
|
||||
scope: ChangesScope,
|
||||
kind?: AgentChange["kind"],
|
||||
): Promise<DiffData> {
|
||||
const baseLabel = scope === "turn" ? tx("Before Last Turn") : (task.base ?? "Base");
|
||||
const right = task.isolation === "worktree" ? branchLabel(task.branch) : "Working tree";
|
||||
// A file the task added or deleted has one side only, shown alone.
|
||||
const added = kind === "added" || kind === "untracked";
|
||||
const base = added
|
||||
? null
|
||||
: await call(commands.agentBaseText(task.id, path, scope === "turn" ? "lastTurn" : null)).catch(() => null);
|
||||
return {
|
||||
path,
|
||||
left: added
|
||||
? { type: "text", text: "", label: baseLabel, absent: true }
|
||||
: { type: "text", text: base ?? "", label: baseLabel },
|
||||
right:
|
||||
kind === "deleted"
|
||||
? { type: "text", text: "", label: right, absent: true }
|
||||
: { type: "file", path, label: right },
|
||||
title: `${basename(path)} (${baseLabel} ↔ ${right})`,
|
||||
};
|
||||
}
|
||||
|
||||
/** Opens the diff of `path` between the task's start (or its last turn's) and now. */
|
||||
export async function openChangeDiff(task: AgentTask, path: string, scope: ChangesScope = "task") {
|
||||
const { changes, turnChanges } = useAgents.getState();
|
||||
const listed = (scope === "turn" ? turnChanges : changes).get(task.id) ?? [];
|
||||
const changed = listed.map((change) => change.path);
|
||||
const paths = changed.includes(path) ? changed : [path];
|
||||
const kinds = new Map(listed.map((change) => [change.path, change.kind]));
|
||||
const diffs = await Promise.all(paths.map((file) => changeDiffData(task, file, scope, kinds.get(file))));
|
||||
await openDiff(withChain(diffs, paths.indexOf(path)));
|
||||
}
|
||||
|
||||
/** Diff of `path` in the grouped view: `HEAD` ↔ the working file. */
|
||||
function uncommittedDiffData(task: AgentTask, change: AgentChange): DiffData {
|
||||
const left: DiffData["left"] =
|
||||
change.kind === "added" || change.kind === "untracked"
|
||||
? { type: "text", text: "", label: "(does not exist)", absent: true }
|
||||
: {
|
||||
type: "rev",
|
||||
rev: "HEAD",
|
||||
path: change.oldPath ? repositoryPath(task.cwd, change.oldPath) : undefined,
|
||||
label: "HEAD",
|
||||
};
|
||||
const right: DiffData["right"] =
|
||||
change.kind === "deleted"
|
||||
? { type: "text", text: "", label: "(deleted)", absent: true }
|
||||
: {
|
||||
type: "worktree",
|
||||
label: task.isolation === "worktree" ? branchLabel(task.branch) : "Working tree",
|
||||
};
|
||||
return { path: change.path, left, right };
|
||||
}
|
||||
|
||||
/** Registration needed before a diff reads revisions inside the task's own worktree. */
|
||||
async function ensureTaskRepo(task: AgentTask) {
|
||||
// A worktree is its own repository, outside the project's: `vcs_file_at` reads it only once
|
||||
// it is registered as an external log for this window.
|
||||
if (task.isolation === "worktree") await call(commands.vcsOpenExternalLog(task.cwd)).catch(() => undefined);
|
||||
}
|
||||
|
||||
/** Diff of a file of one of the task's commits: `parent ↔ commit`. */
|
||||
function commitFileDiff(task: AgentTask, commit: AgentCommit, file: AgentChange): DiffData {
|
||||
return commitFileDiffData(
|
||||
{
|
||||
id: commit.id,
|
||||
shortId: commit.shortId,
|
||||
parents: commit.parent ? [commit.parent] : [],
|
||||
repo: task.cwd,
|
||||
},
|
||||
{ path: file.relPath, kind: file.kind, oldPath: file.oldPath },
|
||||
);
|
||||
}
|
||||
@@ -143,8 +143,7 @@ export function SessionComposer({
|
||||
head,
|
||||
changes,
|
||||
commits,
|
||||
changesOpen,
|
||||
onToggleChanges,
|
||||
onOpenChanges,
|
||||
onOpenSubagent,
|
||||
}: {
|
||||
task: AgentTask;
|
||||
@@ -154,8 +153,7 @@ export function SessionComposer({
|
||||
head: string | null;
|
||||
changes: AgentChange[] | null;
|
||||
commits: readonly AgentCommit[];
|
||||
changesOpen: boolean;
|
||||
onToggleChanges: () => void;
|
||||
onOpenChanges: () => void;
|
||||
onOpenSubagent: (id: string) => void;
|
||||
}) {
|
||||
const { sendWith, whileRunning } = useAgentSettings();
|
||||
@@ -382,8 +380,7 @@ export function SessionComposer({
|
||||
head={head}
|
||||
changes={changes}
|
||||
commits={commits}
|
||||
changesOpen={changesOpen}
|
||||
onToggleChanges={onToggleChanges}
|
||||
onOpenChanges={onOpenChanges}
|
||||
effortAnnouncement={effortAnnouncement}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -39,18 +39,16 @@ export function SessionStatus({
|
||||
head,
|
||||
changes,
|
||||
commits,
|
||||
changesOpen,
|
||||
effortAnnouncement,
|
||||
onToggleChanges,
|
||||
onOpenChanges,
|
||||
}: {
|
||||
task: AgentTask;
|
||||
entries: AgentEntry[] | null;
|
||||
head: string | null;
|
||||
changes: AgentChange[] | null;
|
||||
commits: readonly AgentCommit[];
|
||||
changesOpen: boolean;
|
||||
effortAnnouncement: string | null;
|
||||
onToggleChanges: () => void;
|
||||
onOpenChanges: () => void;
|
||||
}) {
|
||||
const tx = useTx();
|
||||
const project = useProject((s) => s.project);
|
||||
@@ -124,13 +122,7 @@ export function SessionStatus({
|
||||
{(!!changes?.length || !!commits.length) && (
|
||||
<span className={styles.statusChips}>
|
||||
{!!changes?.length && (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.statusChip}
|
||||
aria-expanded={changesOpen}
|
||||
title={filesLabel}
|
||||
onClick={onToggleChanges}
|
||||
>
|
||||
<button type="button" className={styles.statusChip} title={filesLabel} onClick={onOpenChanges}>
|
||||
<Icon name="edit" size={12} />
|
||||
{/* The counts are the chip's own items, so its gap spaces them and the label can still truncate. */}
|
||||
<span className={styles.statusChipLabel}>{filesLabel}</span>
|
||||
@@ -142,13 +134,7 @@ export function SessionStatus({
|
||||
</button>
|
||||
)}
|
||||
{!!commits.length && (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.statusChip}
|
||||
aria-expanded={changesOpen}
|
||||
title={commitsLabel}
|
||||
onClick={onToggleChanges}
|
||||
>
|
||||
<button type="button" className={styles.statusChip} title={commitsLabel} onClick={onOpenChanges}>
|
||||
<Icon name="commit" size={12} />
|
||||
<span className={styles.statusChipLabel}>{commitsLabel}</span>
|
||||
<span className={styles.statusChipCount} aria-hidden>
|
||||
|
||||
@@ -13,7 +13,7 @@ import { subagentTitle, subagentWorking, type SubagentEntry } from "../model";
|
||||
import { useRevealedText } from "../reveal";
|
||||
import { toolDuration, toolRun } from "../timeline";
|
||||
import { cancelTask } from "../store";
|
||||
import { openChangeDiff } from "./ChangesPane";
|
||||
import { openChangeDiff } from "./ChangesTab";
|
||||
import { Fold } from "./Folds";
|
||||
import { liveTool } from "./conversationRows";
|
||||
import { shortTitle, useNow } from "./shared";
|
||||
|
||||
@@ -10,7 +10,8 @@ import type { AgentChange, AgentCommit, AgentEntry, AgentTask } from "@/bindings
|
||||
import { AgentsView } from "./AgentsView";
|
||||
import { SessionEditor } from "./SessionEditor";
|
||||
import { conversationRows } from "./session/conversationRows";
|
||||
import { entriesKey, SESSION_KIND, sessionKey, type SubagentEntry } from "./model";
|
||||
import { CHANGES_KIND, changesKey, entriesKey, SESSION_KIND, sessionKey, type SubagentEntry } from "./model";
|
||||
import { ChangesTab } from "./session/ChangesTab";
|
||||
import {
|
||||
acceptChanges,
|
||||
disconnect,
|
||||
@@ -108,6 +109,8 @@ vi.mock("@/platform/ipc", async (original) => ({
|
||||
backend.changesCalls += 1;
|
||||
return { status: "ok", data: backend.changes };
|
||||
},
|
||||
agentBaseText: async () => ({ status: "ok", data: "" }),
|
||||
vcsOpenExternalLog: async () => ({ status: "ok", data: null }),
|
||||
agentGroupedChanges: async () => {
|
||||
backend.groupedCalls += 1;
|
||||
return { status: "ok", data: backend.grouped };
|
||||
@@ -172,9 +175,10 @@ vi.mock("@/workbench/messages", async (original) => ({
|
||||
await backend.errorWait;
|
||||
},
|
||||
}));
|
||||
const editors = vi.hoisted(() => ({ closeInput: vi.fn(), openInput: vi.fn() }));
|
||||
vi.mock("@/workbench/contributions", async (original) => ({
|
||||
...(await original<typeof import("@/workbench/contributions")>()),
|
||||
editorService: () => ({ closeInput: vi.fn(), openInput: vi.fn() }),
|
||||
editorService: () => editors,
|
||||
toolWindowService: () => ({ show: vi.fn() }),
|
||||
}));
|
||||
|
||||
@@ -217,6 +221,10 @@ const input = (id: string) => ({
|
||||
key: sessionKey(id),
|
||||
data: { task: id },
|
||||
});
|
||||
const renderChanges = (id: string) =>
|
||||
render(<ChangesTab input={{ kind: CHANGES_KIND, key: changesKey(id), data: { task: id } }} />);
|
||||
/** The Changes tab's file tree (the diff beside it names the files too). */
|
||||
const changedFiles = () => screen.findByRole("tree", { name: "Changed files" });
|
||||
const stream = () => document.querySelector<HTMLDivElement>(`.${styles.stream}`)!;
|
||||
const tool = (id: string, overrides: Partial<Extract<AgentEntry, { type: "tool" }>> = {}): AgentEntry => ({
|
||||
type: "tool",
|
||||
@@ -2031,7 +2039,7 @@ describe("session state across tasks and hosts", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps docked changes opt-in, preserves the draft, and returns to the same conversation", async () => {
|
||||
it("opens a docked task's changes in the editor, keeping the conversation and its draft", async () => {
|
||||
backend.changes = [
|
||||
{
|
||||
path: "/project/very-long-file-name.ts",
|
||||
@@ -2043,33 +2051,20 @@ describe("session state across tasks and hosts", () => {
|
||||
repo: null,
|
||||
},
|
||||
];
|
||||
localStorage.setItem("openidea.agents.changesOpen.v1", JSON.stringify({ A: true }));
|
||||
useAgents.setState({ docked: "A", sessionLocation: "toolWindow" });
|
||||
render(<AgentsView />);
|
||||
await screen.findByText("Answer A");
|
||||
await screen.findByRole("button", { name: /1 changed file/ });
|
||||
expect(screen.queryByRole("complementary", { name: "Changes" })).toBeNull();
|
||||
const markVisible = vi.spyOn(await import("./store"), "markVisible");
|
||||
vi.spyOn(document, "hasFocus").mockReturnValue(true);
|
||||
const message = screen.getByRole("textbox", { name: "Message" });
|
||||
typeIn(message, "Draft to keep");
|
||||
const conversation = stream();
|
||||
fireEvent.click(screen.getByRole("button", { name: /1 changed file/ }));
|
||||
expect(screen.getByRole("complementary", { name: "Changes" })).toBeVisible();
|
||||
expect(screen.getByText("Answer A")).not.toBeVisible();
|
||||
expect(screen.queryByRole("textbox", { name: "Message" })).toBeNull();
|
||||
act(() => useAgents.setState({ unread: new Set(["A"]) }));
|
||||
fireEvent(window, new Event("focus"));
|
||||
expect(useAgents.getState().unread.has("A")).toBe(true);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Back to conversation" }));
|
||||
editors.openInput.mockClear();
|
||||
fireEvent.click(await screen.findByRole("button", { name: /1 changed file/ }));
|
||||
expect(editors.openInput).toHaveBeenCalledWith(
|
||||
{ kind: CHANGES_KIND, key: changesKey("A"), data: { task: "A" } },
|
||||
{ focus: true },
|
||||
);
|
||||
expect(screen.getByText("Answer A")).toBeVisible();
|
||||
expect(stream()).toBe(conversation);
|
||||
expect(markVisible).toHaveBeenCalledWith("A");
|
||||
expect(useAgents.getState().unread.has("A")).toBe(false);
|
||||
expect(screen.getByRole("textbox", { name: "Message" })).toBe(message);
|
||||
expect(textOf(message)).toBe("Draft to keep");
|
||||
expect(useAgents.getState().composers.get("A")?.text).toBe("Draft to keep");
|
||||
expect(JSON.parse(localStorage.getItem("openidea.agents.changesOpen.v1")!).A).toBe(true);
|
||||
});
|
||||
|
||||
it.each([false, true])("retains scrolling and follow-output (%s) when moving in both directions", async (stick) => {
|
||||
@@ -2201,7 +2196,6 @@ describe("session state across tasks and hosts", () => {
|
||||
repo: null,
|
||||
},
|
||||
];
|
||||
localStorage.setItem("openidea.agents.changesOpen.v1", JSON.stringify({ A: true }));
|
||||
useAgents.setState((s) => ({
|
||||
tasks: new Map(s.tasks).set("A", { ...s.tasks.get("A")!, status: "archived" }),
|
||||
}));
|
||||
@@ -2210,8 +2204,8 @@ describe("session state across tasks and hosts", () => {
|
||||
backend.fetched = [];
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
expect(await screen.findByText("Answer A")).toBeInTheDocument();
|
||||
const panel = await screen.findByRole("complementary", { name: "Changes" });
|
||||
expect(await within(panel).findByText("kept-change.ts")).toBeInTheDocument();
|
||||
renderChanges("A");
|
||||
expect(await within(await changedFiles()).findByText("kept-change.ts")).toBeInTheDocument();
|
||||
expect(backend.fetched).toEqual(["A"]);
|
||||
});
|
||||
});
|
||||
@@ -3066,7 +3060,6 @@ describe("accept changes", () => {
|
||||
repo: null,
|
||||
},
|
||||
];
|
||||
localStorage.setItem("openidea.agents.changesOpen.v1", JSON.stringify({ A: true }));
|
||||
useAgents.setState({
|
||||
tasks: new Map([[task("A").id, { ...task("A"), isolation: "worktree", status: "ready" }]]),
|
||||
});
|
||||
@@ -3074,8 +3067,8 @@ describe("accept changes", () => {
|
||||
|
||||
it("copies a worktree task's changes into the checkout after confirming", async () => {
|
||||
worktreeChanges();
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
await screen.findByRole("complementary", { name: "Changes" });
|
||||
renderChanges("A");
|
||||
await changedFiles();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Accept All Changes…" }));
|
||||
expect(backend.confirmed).toEqual(["Accept Changes"]);
|
||||
await waitFor(() => expect(backend.accepted).toEqual([["A", null]]));
|
||||
@@ -3084,8 +3077,8 @@ describe("accept changes", () => {
|
||||
it("does nothing when the confirm dialog is dismissed", async () => {
|
||||
worktreeChanges();
|
||||
backend.confirmAnswer = false;
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
await screen.findByRole("complementary", { name: "Changes" });
|
||||
renderChanges("A");
|
||||
await changedFiles();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Accept All Changes…" }));
|
||||
await waitFor(() => expect(backend.confirmed).toEqual(["Accept Changes"]));
|
||||
expect(backend.accepted).toEqual([]);
|
||||
@@ -3103,9 +3096,8 @@ describe("accept changes", () => {
|
||||
repo: null,
|
||||
},
|
||||
];
|
||||
localStorage.setItem("openidea.agents.changesOpen.v1", JSON.stringify({ A: true }));
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
await screen.findByRole("complementary", { name: "Changes" });
|
||||
renderChanges("A");
|
||||
await changedFiles();
|
||||
expect(screen.queryByRole("button", { name: /Accept .* Changes…/ })).toBeNull();
|
||||
expect(screen.getByRole("button", { name: "Rollback All Changes…" })).toBeInTheDocument();
|
||||
});
|
||||
@@ -3125,27 +3117,30 @@ describe("last turn changes", () => {
|
||||
it("lists and rolls back only what the last turn changed, the session still counting the whole task", async () => {
|
||||
backend.changes = [change("a.ts"), change("b.ts")];
|
||||
backend.turnChanges = [change("b.ts")];
|
||||
localStorage.setItem("openidea.agents.changesOpen.v1", JSON.stringify({ A: true }));
|
||||
useAgents.setState({ tasks: new Map([["A", { ...task("A"), status: "ready" }]]) });
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
const pane = await screen.findByRole("complementary", { name: "Changes" });
|
||||
renderChanges("A");
|
||||
const pane = await changedFiles();
|
||||
expect(await within(pane).findByText("a.ts")).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(within(pane).getByRole("tab", { name: "Last Turn" }));
|
||||
await waitFor(() => expect(within(pane).queryByText("a.ts")).toBeNull());
|
||||
expect(within(pane).getByText("b.ts")).toBeInTheDocument();
|
||||
expect(within(pane).getByText("Since the last turn started")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("tab", { name: "Last Turn" }));
|
||||
// Each view has a tree of its own.
|
||||
await waitFor(() =>
|
||||
expect(within(screen.getByRole("tree", { name: "Changed files" })).queryByText("a.ts")).toBeNull(),
|
||||
);
|
||||
expect(within(await changedFiles()).getByText("b.ts")).toBeInTheDocument();
|
||||
expect(screen.getByText("Since the last turn started")).toBeInTheDocument();
|
||||
expect(useChangesOptions.getState().scope).toBe("turn");
|
||||
expect(screen.getByRole("button", { name: /2 changed files/ })).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(within(pane).getByRole("button", { name: "Rollback All Changes…" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Rollback All Changes…" }));
|
||||
await waitFor(() => expect(backend.rolledBack).toEqual([["A", null, "lastTurn"]]));
|
||||
|
||||
backend.turnChanges = [];
|
||||
fireEvent.click(within(pane).getByRole("button", { name: "Refresh" }));
|
||||
expect(await within(pane).findByText("The last turn changed no files")).toBeInTheDocument();
|
||||
fireEvent.click(within(pane).getByRole("tab", { name: "Whole Task" }));
|
||||
expect(await within(pane).findByText("a.ts")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Refresh" }));
|
||||
expect((await screen.findAllByText("The last turn changed no files")).length).toBeGreaterThan(0);
|
||||
fireEvent.click(screen.getByRole("tab", { name: "Whole Task" }));
|
||||
expect(await within(await changedFiles()).findByText("a.ts")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3174,7 +3169,6 @@ describe("grouped changes", () => {
|
||||
useAgents.setState({
|
||||
tasks: new Map([["A", { ...task("A"), isolation: "worktree" }]]),
|
||||
});
|
||||
localStorage.setItem("openidea.agents.changesOpen.v1", JSON.stringify({ A: true }));
|
||||
};
|
||||
|
||||
it("puts committed files under their commit and rolls back only the uncommitted ones", async () => {
|
||||
@@ -3183,21 +3177,22 @@ describe("grouped changes", () => {
|
||||
commits: [commit({ files: [change("b.ts")] })],
|
||||
};
|
||||
worktreeTask();
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
renderChanges("A");
|
||||
const tree = await changedFiles();
|
||||
|
||||
expect(await screen.findByText("Uncommitted")).toBeInTheDocument();
|
||||
expect(screen.getByText("Committed")).toBeInTheDocument();
|
||||
expect(screen.getByText("aaaaaaa")).toBeInTheDocument();
|
||||
expect(screen.getByText("change a")).toBeInTheDocument();
|
||||
expect(await within(tree).findByText("Uncommitted")).toBeInTheDocument();
|
||||
expect(within(tree).getByText("Committed")).toBeInTheDocument();
|
||||
expect(within(tree).getByText("aaaaaaa")).toBeInTheDocument();
|
||||
expect(within(tree).getByText("change a")).toBeInTheDocument();
|
||||
|
||||
// The commit's files show once it is expanded; selecting one is not a rollback selection.
|
||||
const commitRow = screen.getByText("change a").closest("[data-row]")!;
|
||||
const commitRow = within(tree).getByText("change a").closest("[data-row]")!;
|
||||
fireEvent.mouseDown(commitRow.querySelector("[data-tree-toggle]")!);
|
||||
expect(await screen.findByText("b.ts")).toBeInTheDocument();
|
||||
fireEvent.mouseDown(screen.getByText("b.ts"));
|
||||
expect(await within(tree).findByText("b.ts")).toBeInTheDocument();
|
||||
fireEvent.mouseDown(within(tree).getByText("b.ts"));
|
||||
expect(screen.getByRole("button", { name: "Rollback All Changes…" })).toBeInTheDocument();
|
||||
|
||||
fireEvent.mouseDown(screen.getByText("a.ts"));
|
||||
fireEvent.mouseDown(within(tree).getByText("a.ts"));
|
||||
expect(screen.getByRole("button", { name: "Rollback Selected Changes…" })).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Rollback Selected Changes…" }));
|
||||
@@ -3205,6 +3200,33 @@ describe("grouped changes", () => {
|
||||
expect(backend.rolledBack).toEqual([["A", ["a.ts"], "group"]]);
|
||||
});
|
||||
|
||||
it("shows every file's diff beside the tree, the same file once per commit, and follows the tree", async () => {
|
||||
backend.grouped = {
|
||||
uncommitted: [change("a.ts")],
|
||||
commits: [commit({ files: [change("a.ts"), change("b.ts")] })],
|
||||
};
|
||||
worktreeTask();
|
||||
// Room to scroll, so a reveal isn't clamped to the top.
|
||||
vi.spyOn(HTMLElement.prototype, "scrollHeight", "get").mockReturnValue(5000);
|
||||
vi.spyOn(HTMLElement.prototype, "clientHeight", "get").mockReturnValue(400);
|
||||
vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(400);
|
||||
renderChanges("A");
|
||||
const tree = await changedFiles();
|
||||
const blocks = () => [...document.querySelectorAll<HTMLElement>("[data-combined-block]")];
|
||||
await waitFor(() =>
|
||||
expect(blocks().map((b) => b.dataset.combinedBlock)).toEqual(["/project/a.ts", "/project/a.ts", "/project/b.ts"]),
|
||||
);
|
||||
// A commit's file names its commit.
|
||||
expect(blocks()[0]!.textContent).not.toContain("aaaaaaa");
|
||||
expect(blocks()[1]!.textContent).toContain("aaaaaaa");
|
||||
const scroller = document.querySelector<HTMLElement>("[data-combined-scroll]")!;
|
||||
const scrollTo = vi.spyOn(scroller, "scrollTo");
|
||||
const second = Number.parseFloat(scroller.querySelector<HTMLElement>('[data-index="1"]')!.style.top);
|
||||
fireEvent.mouseDown(within(tree).getByText("change a"));
|
||||
await act(() => new Promise((r) => setTimeout(r, 50)));
|
||||
expect(scrollTo).toHaveBeenLastCalledWith(expect.objectContaining({ top: second }));
|
||||
});
|
||||
|
||||
it("counts only uncommitted files in the header and the tray", async () => {
|
||||
backend.grouped = {
|
||||
uncommitted: [change("a.ts")],
|
||||
@@ -3212,9 +3234,8 @@ describe("grouped changes", () => {
|
||||
};
|
||||
worktreeTask();
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
await screen.findByRole("complementary", { name: "Changes" });
|
||||
expect(await screen.findByRole("button", { name: /1 commit/ })).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: /1 changed file/ })).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: /1 commit/ })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("puts the files of a task across nested repositories under a row per repository", async () => {
|
||||
@@ -3225,9 +3246,8 @@ describe("grouped changes", () => {
|
||||
});
|
||||
backend.changes = [inRepo("api", "api/src/a.ts"), inRepo("api", "api/b.ts"), inRepo("web", "web/c.ts")];
|
||||
useAgents.setState({ tasks: new Map([["A", task("A")]]) });
|
||||
localStorage.setItem("openidea.agents.changesOpen.v1", JSON.stringify({ A: true }));
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
const pane = await screen.findByRole("complementary", { name: "Changes" });
|
||||
renderChanges("A");
|
||||
const pane = await changedFiles();
|
||||
|
||||
await within(pane).findByText("a.ts");
|
||||
// Open from the start, each repository leads its files, which show their folder as the agent names it.
|
||||
@@ -3236,7 +3256,7 @@ describe("grouped changes", () => {
|
||||
expect(within(pane).getByTitle("/api")).toBeInTheDocument();
|
||||
|
||||
fireEvent.mouseDown(within(pane).getByText("c.ts"));
|
||||
fireEvent.click(within(pane).getByRole("button", { name: "Rollback Selected Changes…" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Rollback Selected Changes…" }));
|
||||
await waitFor(() => expect(backend.rolledBack).toEqual([["A", ["web/c.ts"], "sinceStart"]]));
|
||||
});
|
||||
|
||||
@@ -3246,9 +3266,8 @@ describe("grouped changes", () => {
|
||||
{ ...change("b.ts"), repo: "/project" },
|
||||
];
|
||||
useAgents.setState({ tasks: new Map([["A", task("A")]]) });
|
||||
localStorage.setItem("openidea.agents.changesOpen.v1", JSON.stringify({ A: true }));
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
const pane = await screen.findByRole("complementary", { name: "Changes" });
|
||||
renderChanges("A");
|
||||
const pane = await changedFiles();
|
||||
expect(await within(pane).findByText("a.ts")).toBeInTheDocument();
|
||||
expect(within(pane).queryByText("project")).toBeNull();
|
||||
// A file at the top of the project names no folder.
|
||||
@@ -3265,8 +3284,8 @@ describe("grouped changes", () => {
|
||||
useAgents.setState({
|
||||
tasks: new Map([["A", { ...task("A"), isolation: "worktree", status: "ready" }]]),
|
||||
});
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
await screen.findByText("Committed");
|
||||
renderChanges("A");
|
||||
await within(await changedFiles()).findByText("Committed");
|
||||
|
||||
const accept = screen.getByRole("button", { name: "Accept All Changes…" });
|
||||
expect(accept).toBeEnabled();
|
||||
|
||||
@@ -62,6 +62,7 @@ import {
|
||||
type TaskOrganize,
|
||||
} from "./organize";
|
||||
import {
|
||||
CHANGES_KIND,
|
||||
HOME_KEY,
|
||||
HOME_KIND,
|
||||
SESSION_KIND,
|
||||
@@ -579,7 +580,11 @@ export async function connect(): Promise<void> {
|
||||
const editors = editorService();
|
||||
for (const t of editors.openTabs?.() ?? []) {
|
||||
const task = (t.input.data as { task?: string } | undefined)?.task;
|
||||
if (t.input.kind === SESSION_KIND && task && !useAgents.getState().tasks.has(task))
|
||||
if (
|
||||
(t.input.kind === SESSION_KIND || t.input.kind === CHANGES_KIND) &&
|
||||
task &&
|
||||
!useAgents.getState().tasks.has(task)
|
||||
)
|
||||
await editors.closeInput?.(t.input.key);
|
||||
}
|
||||
}
|
||||
@@ -692,7 +697,9 @@ function dropTaskCache(taskId: string) {
|
||||
function isTaskOpenInUi(taskId: string): boolean {
|
||||
if (useAgents.getState().docked === taskId) return true;
|
||||
return (editorService().openTabs?.() ?? []).some(
|
||||
(t) => t.input.kind === SESSION_KIND && (t.input.data as { task?: string } | undefined)?.task === taskId,
|
||||
(t) =>
|
||||
(t.input.kind === SESSION_KIND || t.input.kind === CHANGES_KIND) &&
|
||||
(t.input.data as { task?: string } | undefined)?.task === taskId,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
import { AgentsView } from "./AgentsView";
|
||||
import { AgentsStatus } from "./AgentsStatus";
|
||||
import { activate } from "./index";
|
||||
import { openChangeDiff } from "./session/ChangesPane";
|
||||
import { openChangeDiff } from "./session/ChangesTab";
|
||||
import * as actions from "@/platform/actions";
|
||||
import { commands } from "@/platform/ipc";
|
||||
import { deferred } from "@/test/deferred";
|
||||
|
||||
@@ -33,6 +33,22 @@
|
||||
.grow {
|
||||
flex: 1;
|
||||
}
|
||||
/* A list of the files beside the diffs, under the shared toolbar. */
|
||||
.split {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
.files,
|
||||
.diffs {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
.files > *,
|
||||
.diffs > .scroll {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
.scroll {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
|
||||
@@ -3,12 +3,23 @@
|
||||
* as tall as its content under a sticky header, in one scrolling view. Only the blocks near
|
||||
* the viewport are mounted; a header collapses its block or opens the file's own diff tab.
|
||||
*/
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
type Ref,
|
||||
} from "react";
|
||||
import { defaultRangeExtractor, elementScroll, useVirtualizer, type Range } from "@tanstack/react-virtual";
|
||||
import clsx from "clsx";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { relativeDir, useProject } from "@/platform/project";
|
||||
import { Icon, IconButton, T, fileIconName } from "@/ui";
|
||||
import { Icon, IconButton, SplitGroup, SplitHandle, SplitPanel, T, fileIconName } from "@/ui";
|
||||
import { editorService, type EditorInput } from "@/workbench/contributions";
|
||||
import { combinedDiffDocumentOwner, setAllInOneDiff, type CombinedDiffData } from "./allInOneDiff";
|
||||
import { ResolvedDiffEditor, type DiffViewState } from "./DiffEditor";
|
||||
@@ -30,8 +41,22 @@ export function blockKind(item: DiffData): Kind {
|
||||
/** Height of a block not measured yet: its header and a short diff. */
|
||||
const ESTIMATE = 200;
|
||||
|
||||
function Block({
|
||||
item,
|
||||
/** A file of the view: `key` tells apart the same file shown twice (staged and unstaged, in two commits). */
|
||||
export interface CombinedDiffItem {
|
||||
key: string;
|
||||
data: DiffData;
|
||||
/** Shown after the file name instead of its folder under the project. */
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
/** Scrolls the view to the block of an item. */
|
||||
export interface CombinedDiffHandle {
|
||||
reveal(key: string): void;
|
||||
}
|
||||
|
||||
// Memoized: selecting a file elsewhere (a file list beside the view) mustn't render every diff again.
|
||||
const Block = memo(function Block({
|
||||
entry,
|
||||
index,
|
||||
items,
|
||||
collapsed,
|
||||
@@ -42,11 +67,11 @@ function Block({
|
||||
viewStates,
|
||||
entriesCache,
|
||||
}: {
|
||||
item: DiffData;
|
||||
entry: CombinedDiffItem;
|
||||
index: number;
|
||||
items: readonly DiffData[];
|
||||
collapsed: boolean;
|
||||
onToggle: () => void;
|
||||
onToggle: (key: string) => void;
|
||||
mode: "split" | "unified";
|
||||
tabKey: string;
|
||||
/** Height of each block's loaded diff, by layout and diff, kept while blocks are unmounted. */
|
||||
@@ -56,6 +81,7 @@ function Block({
|
||||
/** Git entries of the blocks, so a block back in view shows without asking Git again. */
|
||||
entriesCache: DiffEntriesCache;
|
||||
}) {
|
||||
const item = entry.data;
|
||||
// A block mounted collapsed creates its diff once expanded.
|
||||
const [loaded, setLoaded] = useState(!collapsed);
|
||||
if (!collapsed && !loaded) setLoaded(true);
|
||||
@@ -93,7 +119,7 @@ function Block({
|
||||
const kind = blockKind(item);
|
||||
const name = baseName(item.path);
|
||||
const root = useProject((s) => s.project?.root ?? "");
|
||||
const dir = relativeDir(root, item.path);
|
||||
const dir = entry.detail ?? relativeDir(root, item.path);
|
||||
return (
|
||||
<section
|
||||
className={styles.block}
|
||||
@@ -107,7 +133,7 @@ function Block({
|
||||
title={collapsed ? "Expand File" : "Collapse File"}
|
||||
size="small"
|
||||
aria-expanded={!collapsed}
|
||||
onClick={onToggle}
|
||||
onClick={() => onToggle(entry.key)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="diff"
|
||||
@@ -151,19 +177,64 @@ function Block({
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
export function CombinedDiffTab({ input }: { input: EditorInput }) {
|
||||
const data = input.data as CombinedDiffData;
|
||||
const items = data.items;
|
||||
// A partially staged file is listed twice (staged and unstaged), so blocks go by diff, not path.
|
||||
const entries = useMemo(() => data.items.map((item) => ({ key: diffInput(item).key, data: item })), [data.items]);
|
||||
const reveal = data.reveal ? entries.find((e) => e.data.path === data.reveal)?.key : undefined;
|
||||
return (
|
||||
<CombinedDiffView
|
||||
items={entries}
|
||||
tabKey={input.key}
|
||||
reveal={reveal}
|
||||
onSeparateTabs={(at) => {
|
||||
// Back to one diff per file, at the file in view.
|
||||
setAllInOneDiff(false);
|
||||
void openDiff(withChain(data.items, at)).then(() => editorService().closeInput?.(input.key));
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Every file of `items` in one scrolling view, with its toolbar. `tabKey` owns the working
|
||||
* documents its diffs edit; `onSeparateTabs` (given the index in view) offers one tab per file.
|
||||
* A view with a list of its files (`files`, beside the diffs) shares the toolbar: its controls
|
||||
* go before (`toolbarStart`) and after (`toolbarEnd`) the diff's.
|
||||
*/
|
||||
export function CombinedDiffView({
|
||||
items: entries,
|
||||
tabKey,
|
||||
reveal,
|
||||
handle,
|
||||
empty = <T>No changes</T>,
|
||||
onSeparateTabs,
|
||||
toolbarStart,
|
||||
toolbarEnd,
|
||||
files,
|
||||
}: {
|
||||
items: readonly CombinedDiffItem[];
|
||||
tabKey: string;
|
||||
/** Key of the item to scroll to when the view opens. */
|
||||
reveal?: string;
|
||||
handle?: Ref<CombinedDiffHandle>;
|
||||
/** Shown instead of the diffs when there are none. */
|
||||
empty?: ReactNode;
|
||||
onSeparateTabs?: (index: number) => void;
|
||||
toolbarStart?: ReactNode;
|
||||
toolbarEnd?: ReactNode;
|
||||
files?: { content: ReactNode; label: string; storageKey: string };
|
||||
}) {
|
||||
const items = useMemo(() => entries.map((e) => e.data), [entries]);
|
||||
const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const [mode, setMode] = useState(() => loadDiffOptions().mode);
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const [heights] = useState(() => new Map<string, number>());
|
||||
const [viewStates] = useState(() => new Map<string, DiffViewState>());
|
||||
const [entriesCache] = useState<DiffEntriesCache>(() => new Map());
|
||||
// A partially staged file is listed twice (staged and unstaged), so blocks go by diff, not path.
|
||||
const keys = useMemo(() => items.map((item) => diffInput(item).key), [items]);
|
||||
const keys = useMemo(() => entries.map((e) => e.key), [entries]);
|
||||
|
||||
// Blocks that stay mounted when scrolled away: the one holding the keyboard focus, so typing still
|
||||
// reaches it, and with autosave off those with unsaved staged edits, which unmounting would save.
|
||||
@@ -174,12 +245,12 @@ export function CombinedDiffTab({ input }: { input: EditorInput }) {
|
||||
const slot = scrollRef.current?.contains(active) ? active?.closest<HTMLElement>("[data-index]") : null;
|
||||
if (slot) shown.add(Number(slot.dataset.index));
|
||||
if (useProject.getState().settings?.files?.autoSave === false)
|
||||
keys.forEach((key, index) => {
|
||||
if (ownedStagedDocument(combinedDiffDocumentOwner(input.key, key))?.dirty) shown.add(index);
|
||||
items.forEach((item, index) => {
|
||||
if (ownedStagedDocument(combinedDiffDocumentOwner(tabKey, diffInput(item).key))?.dirty) shown.add(index);
|
||||
});
|
||||
return [...shown].sort((a, b) => a - b);
|
||||
},
|
||||
[keys, input.key],
|
||||
[items, tabKey],
|
||||
);
|
||||
const virtualizer = useVirtualizer({
|
||||
count: items.length,
|
||||
@@ -210,11 +281,16 @@ export function CombinedDiffTab({ input }: { input: EditorInput }) {
|
||||
if (next >= 0 && next < items.length) virtualizer.scrollToIndex(next, { align: "start" });
|
||||
};
|
||||
|
||||
const scrollTo = (key: string) => {
|
||||
const at = keys.indexOf(key);
|
||||
if (at >= 0) virtualizer.scrollToIndex(at, { align: "start" });
|
||||
};
|
||||
useImperativeHandle(handle, () => ({ reveal: scrollTo }));
|
||||
|
||||
// Open at the file the diff was asked for.
|
||||
useLayoutEffect(() => {
|
||||
const at = data.reveal ? items.findIndex((i) => i.path === data.reveal) : -1;
|
||||
if (at >= 0) virtualizer.scrollToIndex(at, { align: "start" });
|
||||
// Once per tab: later revisits keep their scroll position.
|
||||
if (reveal) scrollTo(reveal);
|
||||
// Once per view: later revisits keep their scroll position.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
@@ -222,18 +298,62 @@ export function CombinedDiffTab({ input }: { input: EditorInput }) {
|
||||
setMode(next);
|
||||
saveDiffOptions({ ...loadDiffOptions(), mode: next });
|
||||
};
|
||||
const toggle = (key: string) =>
|
||||
setCollapsed((c) => {
|
||||
const s = new Set(c);
|
||||
if (s.has(key)) s.delete(key);
|
||||
else s.add(key);
|
||||
return s;
|
||||
});
|
||||
const toggle = useCallback(
|
||||
(key: string) =>
|
||||
setCollapsed((c) => {
|
||||
const s = new Set(c);
|
||||
if (s.has(key)) s.delete(key);
|
||||
else s.add(key);
|
||||
return s;
|
||||
}),
|
||||
[],
|
||||
);
|
||||
const allCollapsed = items.length > 0 && keys.every((key) => collapsed.has(key));
|
||||
|
||||
const scroller = (
|
||||
<div ref={scrollRef} className={styles.scroll} data-combined-scroll>
|
||||
{items.length ? (
|
||||
<div className={styles.blocks} style={{ height: virtualizer.getTotalSize() }}>
|
||||
{virtualizer.getVirtualItems().map(({ index, key, start }) => (
|
||||
<div
|
||||
// Keyed by diff alone: switching the layout keeps each block's diff and its documents.
|
||||
key={key}
|
||||
ref={virtualizer.measureElement}
|
||||
data-index={index}
|
||||
className={styles.slot}
|
||||
// `top`, not a transform: a sticky header inside a transformed box sticks off by the transform.
|
||||
style={{ top: start }}
|
||||
>
|
||||
<Block
|
||||
entry={entries[index]!}
|
||||
index={index}
|
||||
items={items}
|
||||
collapsed={collapsed.has(keys[index]!)}
|
||||
onToggle={toggle}
|
||||
mode={mode}
|
||||
tabKey={tabKey}
|
||||
heights={heights}
|
||||
viewStates={viewStates}
|
||||
entriesCache={entriesCache}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className={clsx(styles.placeholder, styles.empty)}>{empty}</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={styles.root}>
|
||||
<div className={styles.toolbar} role="toolbar" aria-label={tx("Combined Changes Diff")}>
|
||||
{toolbarStart && (
|
||||
<>
|
||||
{toolbarStart}
|
||||
<span className={styles.sep} />
|
||||
</>
|
||||
)}
|
||||
<IconButton icon="arrow-up" title="Previous File" size="small" onClick={() => step(-1)} />
|
||||
<IconButton icon="arrow-down" title="Next File" size="small" onClick={() => step(1)} />
|
||||
<IconButton
|
||||
@@ -257,54 +377,31 @@ export function CombinedDiffTab({ input }: { input: EditorInput }) {
|
||||
pressed={mode === "unified"}
|
||||
onClick={() => setViewer("unified")}
|
||||
/>
|
||||
<span className={styles.count}>{fileCount(items.length)}</span>
|
||||
{!files && <span className={styles.count}>{fileCount(items.length)}</span>}
|
||||
<span className={styles.grow} />
|
||||
<IconButton
|
||||
icon="editor-only"
|
||||
title="Show Files in Separate Diff Tabs"
|
||||
size="small"
|
||||
onClick={() => {
|
||||
// Back to one diff per file, at the file in view.
|
||||
setAllInOneDiff(false);
|
||||
const at = Math.max(0, current());
|
||||
void openDiff(withChain(items, at)).then(() => editorService().closeInput?.(input.key));
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div ref={scrollRef} className={styles.scroll} data-combined-scroll>
|
||||
{items.length ? (
|
||||
<div className={styles.blocks} style={{ height: virtualizer.getTotalSize() }}>
|
||||
{virtualizer.getVirtualItems().map(({ index, key, start }) => (
|
||||
<div
|
||||
// Keyed by diff alone: switching the layout keeps each block's diff and its documents.
|
||||
key={key}
|
||||
ref={virtualizer.measureElement}
|
||||
data-index={index}
|
||||
className={styles.slot}
|
||||
// `top`, not a transform: a sticky header inside a transformed box sticks off by the transform.
|
||||
style={{ top: start }}
|
||||
>
|
||||
<Block
|
||||
item={items[index]!}
|
||||
index={index}
|
||||
items={items}
|
||||
collapsed={collapsed.has(keys[index]!)}
|
||||
onToggle={() => toggle(keys[index]!)}
|
||||
mode={mode}
|
||||
tabKey={input.key}
|
||||
heights={heights}
|
||||
viewStates={viewStates}
|
||||
entriesCache={entriesCache}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className={clsx(styles.placeholder, styles.empty)}>
|
||||
<T>No changes</T>
|
||||
</div>
|
||||
{toolbarEnd}
|
||||
{onSeparateTabs && (
|
||||
<IconButton
|
||||
icon="editor-only"
|
||||
title="Show Files in Separate Diff Tabs"
|
||||
size="small"
|
||||
onClick={() => onSeparateTabs(Math.max(0, current()))}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{files ? (
|
||||
<SplitGroup orientation="horizontal" storageKey={files.storageKey} className={styles.split}>
|
||||
<SplitPanel id="combined-files" defaultSize={240} minSize={160} maxSize="50%" className={styles.files}>
|
||||
{files.content}
|
||||
</SplitPanel>
|
||||
<SplitHandle aria-label={files.label} />
|
||||
<SplitPanel id="combined-diffs" minSize={240} className={styles.diffs}>
|
||||
{scroller}
|
||||
</SplitPanel>
|
||||
</SplitGroup>
|
||||
) : (
|
||||
scroller
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4000,5 +4000,7 @@
|
||||
"Couldn't roll back": "Couldn't roll back",
|
||||
"This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.": "This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.",
|
||||
"The messages after this one are replaced, and the files the agent changed since go back to how they were before this message was sent.": "The messages after this one are replaced, and the files the agent changed since go back to how they were before this message was sent.",
|
||||
"The files the agent changed since go back to how they were before this message was sent.": "The files the agent changed since go back to how they were before this message was sent."
|
||||
"The files the agent changed since go back to how they were before this message was sent.": "The files the agent changed since go back to how they were before this message was sent.",
|
||||
"Changes: {task}": "Changes: {task}",
|
||||
"Resize changed files": "Resize changed files"
|
||||
}
|
||||
@@ -980,7 +980,6 @@
|
||||
"Hide Active Tool Window": "Ocultar ventana de herramientas activa",
|
||||
"Hide All Tool Windows": "Ocultar todas las ventanas de herramientas",
|
||||
"Hide Side Tool Windows": "Ocultar ventanas de herramientas laterales",
|
||||
"Hide changes": "Ocultar cambios",
|
||||
"Hide Coverage": "Ocultar cobertura",
|
||||
"Hide Library Frames": "Ocultar marcos de bibliotecas",
|
||||
"Hide Replace": "Ocultar reemplazar",
|
||||
@@ -5513,7 +5512,6 @@
|
||||
"cannot copy through a destination symlink": "no se puede copiar a través de un enlace simbólico de destino",
|
||||
"expected a relative comparison entry path": "se esperaba una ruta relativa de entrada de comparación",
|
||||
"Agent sessions": "Sesiones del agente",
|
||||
"Back to conversation": "Volver a la conversación",
|
||||
"Chat in Tool Window": "Chat en ventana de herramientas",
|
||||
"Chat in Editor": "Chat en el editor",
|
||||
"Agent settings": "Configuración del agente",
|
||||
|
||||
@@ -917,7 +917,6 @@
|
||||
"Hide Active Tool Window": "Masquer la fenêtre d'outil active",
|
||||
"Hide All Tool Windows": "Masquer toutes les fenêtres d'outils",
|
||||
"Hide Side Tool Windows": "Masquer les fenêtres d'outils latérales",
|
||||
"Hide changes": "Masquer les modifications",
|
||||
"Hide Coverage": "Masquer la couverture",
|
||||
"Hide Library Frames": "Masquer les cadres de bibliothèque",
|
||||
"Hide Replace": "Masquer le remplacement",
|
||||
@@ -5350,7 +5349,6 @@
|
||||
"cannot copy through a destination symlink": "impossible de copier via un lien symbolique de destination",
|
||||
"expected a relative comparison entry path": "chemin d'entrée de comparaison relatif attendu",
|
||||
"Agent sessions": "Sessions d'agent",
|
||||
"Back to conversation": "Retour à la conversation",
|
||||
"Chat in Tool Window": "Discussion dans la fenêtre d'outil",
|
||||
"Chat in Editor": "Discussion dans l'éditeur",
|
||||
"Agent settings": "Paramètres de l'agent",
|
||||
|
||||
@@ -1016,7 +1016,6 @@
|
||||
"Hide Active Tool Window": "활성 도구 창 숨기기",
|
||||
"Hide All Tool Windows": "모든 도구 창 숨기기",
|
||||
"Hide Side Tool Windows": "측면 도구 창 숨기기",
|
||||
"Hide changes": "변경 사항 숨기기",
|
||||
"Hide Coverage": "커버리지 숨기기",
|
||||
"Hide Library Frames": "라이브러리 프레임 숨기기",
|
||||
"Hide Replace": "바꾸기 숨기기",
|
||||
@@ -5580,7 +5579,6 @@
|
||||
"cannot copy through a destination symlink": "대상 심볼릭 링크를 통해 복사할 수 없습니다",
|
||||
"expected a relative comparison entry path": "상대 비교 항목 경로가 필요합니다",
|
||||
"Agent sessions": "에이전트 세션",
|
||||
"Back to conversation": "대화로 돌아가기",
|
||||
"Chat in Tool Window": "도구 창에서 채팅",
|
||||
"Chat in Editor": "편집기에서 채팅",
|
||||
"Agent settings": "에이전트 설정",
|
||||
|
||||
@@ -972,7 +972,6 @@
|
||||
"Hide Active Tool Window": "Ukryj aktywne okno narzędziowe",
|
||||
"Hide All Tool Windows": "Ukryj wszystkie okna narzędziowe",
|
||||
"Hide Side Tool Windows": "Ukryj boczne okna narzędziowe",
|
||||
"Hide changes": "Ukryj zmiany",
|
||||
"Hide Coverage": "Ukryj pokrycie kodu",
|
||||
"Hide Library Frames": "Ukryj ramki biblioteczne",
|
||||
"Hide Replace": "Ukryj zastępowanie",
|
||||
@@ -5464,7 +5463,6 @@
|
||||
"cannot copy through a destination symlink": "nie można kopiować przez dowiązanie symboliczne celu",
|
||||
"expected a relative comparison entry path": "oczekiwano względnej ścieżki wpisu porównania",
|
||||
"Agent sessions": "Sesje agenta",
|
||||
"Back to conversation": "Powrót do rozmowy",
|
||||
"Chat in Tool Window": "Czat w oknie narzędziowym",
|
||||
"Chat in Editor": "Czat w edytorze",
|
||||
"Agent settings": "Ustawienia agenta",
|
||||
|
||||
@@ -972,7 +972,6 @@
|
||||
"Hide Active Tool Window": "Ocultar janela de ferramentas ativa",
|
||||
"Hide All Tool Windows": "Ocultar todas as janelas de ferramentas",
|
||||
"Hide Side Tool Windows": "Ocultar janelas de ferramentas laterais",
|
||||
"Hide changes": "Ocultar alterações",
|
||||
"Hide Coverage": "Ocultar cobertura",
|
||||
"Hide Library Frames": "Ocultar frames de biblioteca",
|
||||
"Hide Replace": "Ocultar substituir",
|
||||
@@ -5479,7 +5478,6 @@
|
||||
"cannot copy through a destination symlink": "não é possível copiar por meio de um link simbólico de destino",
|
||||
"expected a relative comparison entry path": "esperava-se um caminho relativo de entrada de comparação",
|
||||
"Agent sessions": "Sessões do agente",
|
||||
"Back to conversation": "Voltar para a conversa",
|
||||
"Chat in Tool Window": "Chat na janela de ferramentas",
|
||||
"Chat in Editor": "Chat no editor",
|
||||
"Agent settings": "Configurações do agente",
|
||||
|
||||
@@ -2039,8 +2039,6 @@
|
||||
"Hide Active Tool Window": "Скрыть активное окно инструментов",
|
||||
"Hide All Tool Windows": "Скрыть все окна инструментов",
|
||||
"Hide Side Tool Windows": "Скрыть боковые окна инструментов",
|
||||
"Hide changes": "Скрыть изменения",
|
||||
"Resize changes": "Изменить размер изменений",
|
||||
"Hide Coverage": "Скрыть покрытие",
|
||||
"Hide Library Frames": "Скрыть фреймы библиотек",
|
||||
"Hide Replace": "Скрыть замену",
|
||||
@@ -7044,7 +7042,6 @@
|
||||
"cannot copy through a destination symlink": "невозможно скопировать через символическую ссылку назначения",
|
||||
"expected a relative comparison entry path": "ожидался относительный путь элемента сравнения",
|
||||
"Agent sessions": "Сеансы агента",
|
||||
"Back to conversation": "Назад к диалогу",
|
||||
"Chat in Tool Window": "Чат в окне инструментов",
|
||||
"Chat in Editor": "Чат в редакторе",
|
||||
"Agent settings": "Настройки агента",
|
||||
|
||||
@@ -3764,7 +3764,6 @@
|
||||
"Hide Active Tool Window": "Etkin Araç Penceresini Gizle",
|
||||
"Hide All Tool Windows": "Tüm Araç Pencerelerini Gizle",
|
||||
"Hide Side Tool Windows": "Yan Araç Pencerelerini Gizle",
|
||||
"Hide changes": "Değişiklikleri gizle",
|
||||
"Hide Coverage": "Kapsamayı Gizle",
|
||||
"Hide Library Frames": "Kütüphane Çerçevelerini Gizle",
|
||||
"Hide Replace": "Değiştirmeyi Gizle",
|
||||
@@ -8181,7 +8180,6 @@
|
||||
"cannot copy through a destination symlink": "hedef sembolik bağlantı üzerinden kopyalama yapılamaz",
|
||||
"expected a relative comparison entry path": "göreli karşılaştırma girdisi yolu bekleniyordu",
|
||||
"Agent sessions": "Ajan oturumları",
|
||||
"Back to conversation": "Konuşmaya dön",
|
||||
"Chat in Tool Window": "Araç Penceresinde Sohbet",
|
||||
"Chat in Editor": "Düzenleyicide Sohbet",
|
||||
"Agent settings": "Ajan ayarları",
|
||||
|
||||
@@ -1652,8 +1652,6 @@
|
||||
"Hide Active Tool Window": "隱藏活動工具視窗",
|
||||
"Hide All Tool Windows": "隱藏所有工具視窗",
|
||||
"Hide Side Tool Windows": "隱藏側邊工具視窗",
|
||||
"Hide changes": "隱藏更改",
|
||||
"Resize changes": "調整更改面板寬度",
|
||||
"Hide Coverage": "隱藏覆蓋率",
|
||||
"Hide Library Frames": "隱藏庫幀",
|
||||
"Hide Replace": "隱藏取代",
|
||||
@@ -6537,7 +6535,6 @@
|
||||
"cannot copy through a destination symlink": "無法透過目標目錄內的符號連結複製",
|
||||
"expected a relative comparison entry path": "需要比較條目的相對路徑",
|
||||
"Agent sessions": "代理工作階段",
|
||||
"Back to conversation": "返回對話",
|
||||
"Chat in Tool Window": "在工具視窗中聊天",
|
||||
"Chat in Editor": "在編輯器中聊天",
|
||||
"Agent settings": "代理設定",
|
||||
|
||||
@@ -2063,8 +2063,6 @@
|
||||
"Hide Active Tool Window": "隐藏活动工具窗口",
|
||||
"Hide All Tool Windows": "隐藏所有工具窗口",
|
||||
"Hide Side Tool Windows": "隐藏侧边工具窗口",
|
||||
"Hide changes": "隐藏更改",
|
||||
"Resize changes": "调整更改面板宽度",
|
||||
"Hide Coverage": "隐藏覆盖率",
|
||||
"Hide Library Frames": "隐藏库帧",
|
||||
"Hide Replace": "隐藏替换",
|
||||
@@ -7113,7 +7111,6 @@
|
||||
"cannot copy through a destination symlink": "无法通过目标目录内的符号链接复制",
|
||||
"expected a relative comparison entry path": "需要比较条目的相对路径",
|
||||
"Agent sessions": "智能体会话",
|
||||
"Back to conversation": "返回会话",
|
||||
"Chat in Tool Window": "在工具窗口中聊天",
|
||||
"Chat in Editor": "在编辑器中聊天",
|
||||
"Agent settings": "智能体设置",
|
||||
@@ -10286,5 +10283,7 @@
|
||||
"Closing labels": "结束标签",
|
||||
"Roll Back to Here": "回滚到这里",
|
||||
"Couldn't roll back": "无法回滚",
|
||||
"This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.": "这条消息及之后的消息会被移除,Agent 在此之后改动的文件会恢复到这条消息发送前的状态。消息会放回输入框。"
|
||||
"This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.": "这条消息及之后的消息会被移除,Agent 在此之后改动的文件会恢复到这条消息发送前的状态。消息会放回输入框。",
|
||||
"Changes: {task}": "改动:{task}",
|
||||
"Resize changed files": "调整改动文件列表宽度"
|
||||
}
|
||||
Reference in new issue
Block a user