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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 5ef5448727 fix(agents): use the spacing token for the edit row gap 2026-11-30 22:53:13 +08:00
l0ng-ai cbf709c72b Merge remote-tracking branch 'origin/main' into t7007 2026-11-30 22:52:43 +08:00
l0ng-ai 338e1a5b02 fix(agents): keep active and pinned task order stable (#7002)
Active status groups and active tasks in custom groups were ordered by updatedMs, so concurrent turns, status changes, renames and per-task MCP/skill/memory overrides kept reshuffling the list. They now sort by creation time, newest first, and Pinned keeps its pinned order including manual drag overrides. Renaming a task or changing its overrides no longer bumps updated_ms.
2026-11-30 22:52:26 +08:00
l0ng-ai e914d6a508 fix(agents): edit user messages in place without layout jump 2026-11-30 18:12:27 +08:00
10 змінених файлів з 450 додано та 160 видалено

No files matched your search

-4
Переглянути файл
@@ -2762,7 +2762,6 @@ impl AgentManager {
}
s.task.title = title;
s.title_renamed = true;
s.task.updated_ms = now_ms();
}
task.persist();
task.emit_task();
@@ -3126,7 +3125,6 @@ impl AgentManager {
let changed = s.task.mcp_overrides != cleaned;
if changed {
s.task.mcp_overrides = cleaned;
s.task.updated_ms = now_ms();
}
(changed, s.busy, !s.background_tasks.is_empty(), s.snapshot())
};
@@ -3158,7 +3156,6 @@ impl AgentManager {
let changed = s.task.skill_overrides != cleaned;
if changed {
s.task.skill_overrides = cleaned;
s.task.updated_ms = now_ms();
}
(changed, s.busy, !s.background_tasks.is_empty(), s.task.clone())
};
@@ -3194,7 +3191,6 @@ impl AgentManager {
let changed = s.task.memory_overrides != next_boxed;
if changed {
s.task.memory_overrides = next_boxed;
s.task.updated_ms = now_ms();
}
(changed, s.busy, !s.background_tasks.is_empty(), s.task.clone())
};
+33
Переглянути файл
@@ -6928,3 +6928,36 @@ async fn network_outage_window_off_or_expired_degrades_to_interrupted_and_auth_e
mgr2.shutdown();
mgr3.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn metadata_edits_do_not_bump_updated_ms() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let _down = ShutDown(&mgr);
let task = mgr
.create(NewAgentTask { provider: "claude".into(), prompt: text("again"), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let handle = mgr.task(&task.id).unwrap();
let fixed_ms = 1_234.0;
handle.state.lock().task.updated_ms = fixed_ms;
mgr.rename(&task.id, "Custom Title").unwrap();
assert_eq!(handle.state.lock().task.updated_ms, fixed_ms);
let after_mcp = mgr.set_mcp_overrides(&task.id, BTreeMap::from([("github".into(), false)])).unwrap();
assert_eq!(after_mcp.updated_ms, fixed_ms);
let after_skill =
mgr.set_skill_overrides(&task.id, BTreeMap::from([("triage".into(), AgentSkillMode::Off)])).unwrap();
assert_eq!(after_skill.updated_ms, fixed_ms);
let after_memory = mgr
.set_memory_overrides(
&task.id,
AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off), entries: BTreeMap::new() },
)
.unwrap();
assert_eq!(after_memory.updated_ms, fixed_ms);
}
+30
Переглянути файл
@@ -658,6 +658,36 @@ describe("Agents pinned and grouped tasks", () => {
}
};
it("keeps Pinned and active status groups stable when activity timestamps change", () => {
const tasks = new Map(
[
{ ...task("pin-first"), createdMs: 10, updatedMs: 10 },
{ ...task("pin-second"), createdMs: 20, updatedMs: 20 },
{ ...task("ready-new"), createdMs: 40, updatedMs: 40 },
{ ...task("ready-old"), createdMs: 30, updatedMs: 30 },
].map((t) => [t.id, t]),
);
useAgents.setState({ tasks, organize: { groups: [], groupOf: {}, pinned: ["pin-first", "pin-second"] } });
setup();
const visibleIds = () =>
Array.from(document.querySelectorAll<HTMLElement>("[data-tree-key]"))
.map((el) => el.dataset.treeKey)
.filter((k) => k && !k.startsWith("g:") && k !== "pinned");
expect(visibleIds()).toEqual(["pin-first", "pin-second", "ready-new", "ready-old"]);
// Activity updates on older/later-pinned tasks do not reshuffle either section.
act(() => {
const next = new Map(useAgents.getState().tasks);
next.set("pin-second", { ...next.get("pin-second")!, updatedMs: 999 });
next.set("ready-old", { ...next.get("ready-old")!, updatedMs: 999 });
useAgents.setState({ tasks: next });
});
expect(visibleIds()).toEqual(["pin-first", "pin-second", "ready-new", "ready-old"]);
});
it("reorders tasks within a section by dragging before or after a sibling", () => {
const tasks = new Map(
[
+126 -13
Переглянути файл
@@ -28,9 +28,15 @@
.fitWidth .stream > * {
width: 100%;
}
.fitWidth .userMessage > .user {
.fitWidth .userMessage > .user,
.fitWidth .userMessage > .editCard,
.fitWidth .userMessage > .editNote,
.fitWidth .userMessage > .editError {
max-width: var(--session-card-width);
}
.fitWidth .userMessage > .editCard {
width: var(--edit-width, var(--session-card-width));
}
.fitWidth .composerArea {
max-width: none;
}
@@ -338,6 +344,15 @@
width: fit-content;
max-width: min(var(--session-card-width), 720px);
}
.userMessage > .editCard {
width: var(--edit-width, min(var(--session-card-width), 720px));
min-width: min(100%, 220px);
max-width: min(var(--session-card-width), 720px);
}
.userMessage > .editNote,
.userMessage > .editError {
max-width: min(var(--session-card-width), 720px);
}
.userMessage > .messageHead {
justify-content: flex-end;
}
@@ -518,33 +533,131 @@
overflow-wrap: anywhere;
}
/* In-place bubble editor: matches the Islands composer frame and keeps the text origin fixed. */
.editCard {
box-sizing: border-box;
display: flex;
flex-direction: column;
border-radius: var(--radius-tab);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border-popup);
cursor: text;
transition:
background var(--dur-fast) var(--ease),
box-shadow var(--dur-fast) var(--ease);
}
.editCard:focus-within {
background: var(--bg-field, var(--bg-button));
box-shadow:
inset 0 0 0 1px var(--focus-ring),
0 0 0 1px var(--focus-ring);
}
@media (prefers-reduced-motion: reduce) {
.editCard {
transition: none;
}
}
.editField {
display: grid;
grid-template-columns: minmax(0, 1fr);
min-width: 0;
max-height: 280px;
}
.editMirror,
.editMessage {
grid-area: 1 / 1;
min-width: 0;
margin: 0;
padding: 6px 10px 4px;
border: 0;
font: inherit;
line-height: 1.4;
white-space: pre-wrap;
overflow-wrap: anywhere;
box-sizing: border-box;
}
.editMirror {
visibility: hidden;
pointer-events: none;
max-height: 280px;
overflow: hidden;
-webkit-user-select: none;
user-select: none;
}
.editMessage {
width: 100%;
box-sizing: border-box;
padding: 6px 8px;
resize: vertical;
font: inherit;
height: 100%;
min-height: 0;
overflow-y: auto;
resize: none;
background: transparent;
color: var(--fg-strong);
background: var(--bg-input);
border: 1px solid var(--accent);
border-radius: var(--radius-control);
caret-color: var(--fg-strong);
outline: none;
}
.editBar {
.editImages {
padding: 0 10px 4px;
}
.editImages .images {
margin-top: 0;
}
.editFooter {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
margin-top: 6px;
font-size: var(--fs-small);
padding: 2px 6px 6px 10px;
cursor: default;
}
.editHint {
display: inline-flex;
align-items: center;
gap: var(--space-0-5);
color: var(--fg-faint);
font-size: var(--fs-tiny, 11px);
-webkit-user-select: none;
user-select: none;
}
.editHint kbd {
display: inline-grid;
place-items: center;
min-width: 16px;
height: 16px;
padding: 0 3px;
border-radius: var(--radius-small);
background: var(--bg-hover);
color: var(--fg-muted);
font-family: var(--font-keys, inherit);
font-size: var(--fs-tiny, 11px);
}
.editButtons {
display: flex;
gap: var(--space-1-5);
display: inline-flex;
align-items: center;
gap: var(--space-1);
margin-left: auto;
}
.editError {
margin-top: var(--space-1-5);
font-size: var(--fs-small);
}
.editNote {
margin-top: var(--space-1);
color: var(--fg-subtle);
font-size: var(--fs-small);
line-height: 1.35;
text-align: right;
}
.markdown {
line-height: 1.4;
overflow-wrap: anywhere;
+11 -8
Переглянути файл
@@ -57,7 +57,7 @@ import {
} from "./model";
import { markdownHtml } from "./Markdown";
function task(id: string, status: AgentStatus, updatedMs: number): AgentTask {
function task(id: string, status: AgentStatus, createdMs: number, updatedMs = createdMs): AgentTask {
return {
id,
title: id,
@@ -70,7 +70,7 @@ function task(id: string, status: AgentStatus, updatedMs: number): AgentTask {
base: "main",
baseCommit: "abc",
error: null,
createdMs: 0,
createdMs,
updatedMs,
config: [],
commands: [],
@@ -634,18 +634,21 @@ describe("usage meters", () => {
});
describe("agents model", () => {
it("groups tasks by what they need, newest first", () => {
it("groups tasks by what they need, keeping active groups in creation order and archived by last update", () => {
const groups = groupTasks([
task("a", "ready", 1),
task("b", "needsInput", 2),
task("c", "running", 3),
task("d", "starting", 4),
task("e", "ready", 5),
task("a", "ready", 1, 90),
task("b", "needsInput", 2, 2),
task("c", "running", 3, 100),
task("d", "starting", 4, 4),
task("e", "ready", 5, 5),
task("arch-old-created-recent-archived", "archived", 1, 200),
task("arch-new-created-older-archived", "archived", 50, 100),
]);
expect(groups.map((g) => [g.status, g.tasks.map((t) => t.id)])).toEqual([
["needsInput", ["b"]],
["running", ["d", "c"]],
["ready", ["e", "a"]],
["archived", ["arch-old-created-recent-archived", "arch-new-created-older-archived"]],
]);
});
+28
Переглянути файл
@@ -44,6 +44,7 @@ vi.mock("@tauri-apps/api/webview", () => ({
}));
import { SessionEditor } from "./SessionEditor";
import styles from "./Session.module.css";
import { textOf, typeIn } from "./composerTesting";
import { registerActions } from "@/platform/actions";
import { composerDraft, rollBackTo, rerunFrom, sendMessage, updateComposer, useAgents } from "./store";
@@ -463,6 +464,33 @@ describe("editing a sent agent message", () => {
expect(textOf(screen.getAllByRole("textbox", { name: "Message" })[0]!)).toBe("Original message");
},
);
it("edits in place inside the user message header and preserves the bubble width", async () => {
const { container } = render(
<SessionEditor input={{ kind: "agent-session", key: task.id, data: { task: task.id } }} />,
);
const user = userEvent.setup();
const editButton = await screen.findByRole("button", { name: "Edit" });
const bubble = container.querySelector<HTMLElement>(`.${styles.user}`)!;
vi.spyOn(bubble, "getBoundingClientRect").mockReturnValue(new DOMRect(100, 50, 272, 32));
const focusSpy = vi.spyOn(HTMLTextAreaElement.prototype, "focus");
try {
await user.click(editButton);
const message = container.querySelector(`.${styles.userMessage}`)!;
expect(message).toBeInTheDocument();
expect(message.querySelector(`.${styles.messageHead}`)).toBeInTheDocument();
expect(message.querySelector(`.${styles.role}`)).toHaveTextContent("You");
const card = message.querySelector<HTMLElement>(`.${styles.editCard}`)!;
expect(card).toBeInTheDocument();
expect(card.style.getPropertyValue("--edit-width")).toBe("272px");
const box = screen.getAllByRole("textbox", { name: "Message" })[0] as HTMLTextAreaElement;
expect(focusSpy).toHaveBeenCalledWith({ preventScroll: true });
expect(box.selectionStart).toBe("Original message".length);
expect(box.selectionEnd).toBe("Original message".length);
} finally {
focusSpy.mockRestore();
}
});
});
describe("session composer submission", () => {
+12 -2
Переглянути файл
@@ -120,12 +120,22 @@ export const taskGroupStatus = (task: Pick<AgentTask, "status" | "interrupted">)
export const taskAttentionRank = (task: Pick<AgentTask, "status" | "interrupted">): number =>
GROUP_RANK.get(taskGroupStatus(task)) ?? GROUPS.length;
/** Active sections sort by creation time (newest first) so turns don't reshuffle rows. */
export const compareTaskCreated = (a: AgentTask, b: AgentTask): number =>
(b.createdMs ?? b.updatedMs ?? 0) - (a.createdMs ?? a.updatedMs ?? 0) || (b.updatedMs ?? 0) - (a.updatedMs ?? 0);
/** Archived tasks sort by last update (newest first) so a just-archived task appears at the top. */
export const compareTaskUpdated = (a: AgentTask, b: AgentTask): number =>
(b.updatedMs ?? b.createdMs ?? 0) - (a.updatedMs ?? a.createdMs ?? 0);
export function groupTasks(tasks: Iterable<AgentTask>): TaskGroup[] {
const sorted = [...tasks].sort((a, b) => (b.updatedMs ?? 0) - (a.updatedMs ?? 0));
const list = [...tasks];
return GROUPS.map(([status, label]) => ({
status,
label,
tasks: sorted.filter((t) => taskGroupStatus(t) === status),
tasks: list
.filter((t) => taskGroupStatus(t) === status)
.sort(status === "archived" ? compareTaskUpdated : compareTaskCreated),
})).filter((g) => g.tasks.length > 0);
}
+21 -11
Переглянути файл
@@ -18,7 +18,7 @@ import {
ungroupedMembers,
} from "./organize";
function task(id: string, status: AgentTask["status"] = "ready", updatedMs = 0): AgentTask {
function task(id: string, status: AgentTask["status"] = "ready", updatedMs = 0, createdMs = updatedMs): AgentTask {
return {
id,
title: id,
@@ -31,7 +31,7 @@ function task(id: string, status: AgentTask["status"] = "ready", updatedMs = 0):
base: null,
baseCommit: null,
error: null,
createdMs: 0,
createdMs,
updatedMs,
config: [],
commands: [],
@@ -72,25 +72,35 @@ describe("task organize", () => {
expect(pruneOrganize(clean, [task("a")])).toBe(clean);
});
it("orders a group by what needs attention, then by activity, leaving pinned tasks out", () => {
it("orders a group by what needs attention, then by creation order for active tasks and activity for archived", () => {
const tasks = [
task("slow", "running", 30),
task("ask", "needsInput", 10),
task("pinned", "ready", 99),
task("done", "ready", 20),
task("slow", "running", 30, 30),
task("ask", "needsInput", 10, 10),
task("pinned", "ready", 99, 99),
task("done-old", "ready", 500, 10),
task("done-new", "ready", 20, 20),
task("arch-just", "archived", 600, 5),
task("arch-earlier", "archived", 40, 40),
];
const organize = {
groups: [{ id: "g1", name: "Docs" }],
groupOf: Object.fromEntries(tasks.map((t) => [t.id, "g1"])),
pinned: ["pinned"],
};
expect(groupMembers(tasks, organize, "g1").map((t) => t.id)).toEqual(["ask", "slow", "done"]);
expect(groupMembers(tasks, organize, "g1").map((t) => t.id)).toEqual([
"ask",
"slow",
"done-new",
"done-old",
"arch-just",
"arch-earlier",
]);
});
it("shows pinned tasks by activity, and the others under the status groups", () => {
const tasks = [task("a", "ready", 10), task("b", "running", 30), task("c", "ready", 20)];
it("keeps pinned tasks in pinned order regardless of activity, and puts others under status groups", () => {
const tasks = [task("a", "ready", 10, 10), task("b", "running", 999, 30), task("c", "ready", 20, 20)];
const organize = { groups: [{ id: "g1", name: "Docs" }], groupOf: { c: "g1" }, pinned: ["a", "b"] };
expect(pinnedMembers(tasks, organize).map((t) => t.id)).toEqual(["b", "a"]);
expect(pinnedMembers(tasks, organize).map((t) => t.id)).toEqual(["a", "b"]);
expect(ungroupedMembers(tasks, organize).map((t) => t.id)).toEqual([]);
expect(ungroupedMembers([...tasks, task("d")], organize).map((t) => t.id)).toEqual(["d"]);
});
+26 -7
Переглянути файл
@@ -6,7 +6,14 @@
import type { AgentTask } from "@/bindings";
import { tx } from "@/platform/i18n";
import { parseRemoteLocation } from "@/platform/remote";
import { groupTasks, taskAttentionRank, taskGroupStatus, type TaskGroup } from "./model";
import {
compareTaskCreated,
compareTaskUpdated,
groupTasks,
taskAttentionRank,
taskGroupStatus,
type TaskGroup,
} from "./model";
/** Section key of the pinned group, above every other group. */
export const PINNED_SECTION = "pinned";
@@ -208,12 +215,16 @@ export function applyOrder(defaultSorted: AgentTask[], manual: readonly string[]
return [...fresh, ...ordered];
}
/** The tasks of `group`, what waits for the user first, then the most recently active (or manual order). */
/** The tasks of `group`, what waits for the user first, then creation order for active tasks (or manual order). */
export function groupMembers(tasks: Iterable<AgentTask>, organize: TaskOrganize, group: string): AgentTask[] {
const pinned = new Set(organize.pinned);
const sorted = [...tasks]
.filter((t) => organize.groupOf[t.id] === group && !pinned.has(t.id))
.sort((a, b) => taskAttentionRank(a) - taskAttentionRank(b) || (b.updatedMs ?? 0) - (a.updatedMs ?? 0));
.sort(
(a, b) =>
taskAttentionRank(a) - taskAttentionRank(b) ||
(taskGroupStatus(a) === "archived" ? compareTaskUpdated(a, b) : compareTaskCreated(a, b)),
);
return applyOrder(sorted, organize.order?.[customSection(group)]);
}
@@ -236,11 +247,19 @@ export function statusGroups(tasks: Iterable<AgentTask>, organize: TaskOrganize)
}));
}
/** The pinned tasks, most recently active first (or manual order). */
/** The pinned tasks, in pinned order (or manual order when rearranged). */
export function pinnedMembers(tasks: Iterable<AgentTask>, organize: TaskOrganize): AgentTask[] {
const pinned = new Set(organize.pinned);
const sorted = [...tasks].filter((t) => pinned.has(t.id)).sort((a, b) => (b.updatedMs ?? 0) - (a.updatedMs ?? 0));
return applyOrder(sorted, organize.order?.[PINNED_SECTION]);
const byId = new Map<string, AgentTask>();
for (const task of tasks) byId.set(task.id, task);
const seen = new Set<string>();
const ordered: AgentTask[] = [];
for (const id of organize.pinned) {
if (seen.has(id)) continue;
seen.add(id);
const task = byId.get(id);
if (task) ordered.push(task);
}
return applyOrder(ordered, organize.order?.[PINNED_SECTION]);
}
function placeId(
+163 -115
Переглянути файл
@@ -2,11 +2,12 @@ import type { AgentEntry, AgentImage, AgentTask } from "@/bindings";
import { useTx } from "@/platform/i18n";
import { isImeKey } from "@/platform/ime";
import { call, commands, isTauri } from "@/platform/ipc";
import { isMacHost } from "@/platform/keymap";
import { basename } from "@/platform/project";
import { Button, copyText, fileIconName, Icon, IconButton, T } from "@/ui";
import { notifications } from "@/workbench/contributions";
import clsx from "clsx";
import { memo, useLayoutEffect, useRef, useState, type RefObject } from "react";
import { memo, useLayoutEffect, useRef, useState, type CSSProperties, type RefObject } from "react";
import { AgentReply, MessageActions, ReplyActions } from "../AgentReply";
import { CliSignInDialog } from "@/workbench/CliSignInDialog";
import { ImageStrip } from "../ImageStrip";
@@ -287,6 +288,8 @@ function UserMessage({
}) {
const tx = useTx();
const [editing, setEditing] = useState(false);
const [editWidth, setEditWidth] = useState<number | null>(null);
const bubbleRef = useRef<HTMLDivElement>(null);
if (entry.recovery) {
return (
<div className={styles.recoveryDivider} role="separator">
@@ -310,20 +313,12 @@ function UserMessage({
// A copy up to an earlier turn drops the later ones from the copied session.
const canFork = idle && fork && (rollback || turn === turnCount - 1);
const text = userMessageText(entry.text);
if (editing && turn !== null) {
return (
<MessageEditor
initial={text}
initialImages={entry.images ?? []}
later={turn < turnCount - 1}
onCancel={() => setEditing(false)}
onSend={async (text, images) => {
if (await rerunFrom(task.id, turn, text, images)) setEditing(false);
}}
/>
);
}
const images = entry.images ?? [];
const startEditing = () => {
const width = bubbleRef.current?.getBoundingClientRect().width ?? 0;
setEditWidth(width > 0 ? width : null);
setEditing(true);
};
// Images are listed after the files in `attachments` and shown as thumbnails instead.
// Files mentioned in the text are chips there already.
const mentioned = new Set(
@@ -337,67 +332,80 @@ function UserMessage({
<div className={clsx(styles.message, styles.userMessage)}>
{/* Actions and the time sit beside the author on hover: the reply under it has the turn's duration. */}
<div className={styles.messageHead}>
<MessageActions>
<IconButton size="small" icon="copy" title="Copy" onClick={() => void copyText(text)} />
{inPlace && entry.text && (
<IconButton size="small" icon="edit" title="Edit" onClick={() => setEditing(true)} />
)}
{inPlace && (
<IconButton
size="small"
icon="diff-revert"
iconSize={14}
title="Roll Back to Here"
action="agents.rollBackToMessage"
actionArg={{ task: task.id, turn }}
/>
)}
{!archived && entry.text && entry.attachments.length === 0 && (
<IconButton
size="small"
icon="refresh"
title={inPlace ? "Run Again From Here" : "Send Again"}
onClick={() =>
void (
inPlace
? rerunFrom(task.id, turn, entry.text, images, {
title: "Run Again From Here",
later: turn < turnCount - 1,
})
: resendMessage(task.id, entry.text)
).catch(fail)
}
/>
)}
{canFork && (
<IconButton
size="small"
icon="branch"
title="Fork"
onClick={() => void forkTask(task.id, turn + 1).catch(failed("Couldn't fork the task"))}
/>
)}
</MessageActions>
{!(editing && turn !== null) && (
<MessageActions>
<IconButton size="small" icon="copy" title="Copy" onClick={() => void copyText(text)} />
{inPlace && entry.text && <IconButton size="small" icon="edit" title="Edit" onClick={startEditing} />}
{inPlace && (
<IconButton
size="small"
icon="diff-revert"
iconSize={14}
title="Roll Back to Here"
action="agents.rollBackToMessage"
actionArg={{ task: task.id, turn }}
/>
)}
{!archived && entry.text && entry.attachments.length === 0 && (
<IconButton
size="small"
icon="refresh"
title={inPlace ? "Run Again From Here" : "Send Again"}
onClick={() =>
void (
inPlace
? rerunFrom(task.id, turn, entry.text, images, {
title: "Run Again From Here",
later: turn < turnCount - 1,
})
: resendMessage(task.id, entry.text)
).catch(fail)
}
/>
)}
{canFork && (
<IconButton
size="small"
icon="branch"
title="Fork"
onClick={() => void forkTask(task.id, turn + 1).catch(failed("Couldn't fork the task"))}
/>
)}
</MessageActions>
)}
<MessageTime sentMs={entry.sentMs ?? null} doneMs={null} />
<span className={styles.role}>
<T>You</T>
</span>
</div>
<div className={styles.user}>
<ReferencedText text={text} cwd={task.cwd} />
<ImageStrip images={images} />
{files.length > 0 && (
<div className={styles.attachments}>
{files.map((a, i) => (
// oxlint-disable-next-line react/no-array-index-key -- attachments from different directories can share a basename
<span key={i} className={styles.attachment}>
<Icon name={fileIconName(a)} size={12} />
{a}
</span>
))}
</div>
)}
</div>
{editing && turn !== null ? (
<MessageEditor
initial={text}
initialImages={images}
initialWidth={editWidth}
later={turn < turnCount - 1}
onCancel={() => setEditing(false)}
onSend={async (nextText, nextImages) => {
if (await rerunFrom(task.id, turn, nextText, nextImages)) setEditing(false);
}}
/>
) : (
<div ref={bubbleRef} className={styles.user}>
<ReferencedText text={text} cwd={task.cwd} />
<ImageStrip images={images} />
{files.length > 0 && (
<div className={styles.attachments}>
{files.map((a, i) => (
// oxlint-disable-next-line react/no-array-index-key -- attachments from different directories can share a basename
<span key={i} className={styles.attachment}>
<Icon name={fileIconName(a)} size={12} />
{a}
</span>
))}
</div>
)}
</div>
)}
</div>
);
}
@@ -406,12 +414,15 @@ function UserMessage({
function MessageEditor({
initial,
initialImages,
initialWidth,
later,
onCancel,
onSend,
}: {
initial: string;
initialImages: AgentImage[];
/** Measured width of the bubble being replaced, so editing starts in place without jumping. */
initialWidth: number | null;
/** Turns follow it (they are dropped on send). */
later: boolean;
onCancel: () => void;
@@ -423,6 +434,25 @@ function MessageEditor({
const [sending, setSending] = useState(false);
const [error, setError] = useState<string | null>(null);
const pending = useRef(false);
const cardRef = useRef<HTMLDivElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
useLayoutEffect(() => {
const box = textareaRef.current;
if (!box) return;
// Avoid native autoFocus scroll jumps; only nudge if the expanded footer sits past the bottom edge.
box.focus({ preventScroll: true });
box.setSelectionRange(box.value.length, box.value.length);
const card = cardRef.current;
const scroller = card?.closest(`.${styles.stream}`);
if (card && scroller instanceof HTMLElement) {
const view = scroller.getBoundingClientRect();
const rect = card.getBoundingClientRect();
if (rect.bottom > view.bottom) {
const nudge = Math.min(rect.bottom - view.bottom + 8, Math.max(0, rect.top - view.top));
if (nudge > 0) scroller.scrollTop += nudge;
}
}
}, []);
const send = async () => {
if ((!text.trim() && images.length === 0) || pending.current) return;
pending.current = true;
@@ -442,59 +472,77 @@ function MessageEditor({
setSending(false);
}
};
const cardStyle = initialWidth ? ({ "--edit-width": `${initialWidth}px` } as CSSProperties) : undefined;
return (
<div className={styles.message}>
<textarea
className={styles.editMessage}
value={text}
rows={Math.min(Math.max(text.split("\n").length, 2), 12)}
autoFocus
readOnly={sending}
aria-label={tx("Message")}
onChange={(e) => setText(e.target.value)}
onFocus={(e) => e.currentTarget.setSelectionRange(text.length, text.length)}
onKeyDown={(e) => {
if (isImeKey(e.nativeEvent)) return;
if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
if (!pending.current) onCancel();
} else if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
void send();
}
}}
/>
<ImageStrip images={images} onRemove={sending ? undefined : (i) => setImages(images.filter((_, j) => j !== i))} />
<>
<div ref={cardRef} className={styles.editCard} style={cardStyle}>
<div className={styles.editField}>
<div className={styles.editMirror} aria-hidden="true">
{text.endsWith("\n") ? `${text}\u200b` : text || "\u200b"}
</div>
<textarea
ref={textareaRef}
className={styles.editMessage}
value={text}
rows={1}
readOnly={sending}
aria-label={tx("Message")}
onChange={(e) => setText(e.target.value)}
onKeyDown={(e) => {
if (isImeKey(e.nativeEvent)) return;
if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
if (!pending.current) onCancel();
} else if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
void send();
}
}}
/>
</div>
{images.length > 0 && (
<div className={styles.editImages}>
<ImageStrip
images={images}
onRemove={sending ? undefined : (i) => setImages(images.filter((_, j) => j !== i))}
/>
</div>
)}
<div className={styles.editFooter}>
<span className={styles.editHint} aria-hidden="true">
<kbd>{isMacHost() ? "⌘" : "Ctrl"}</kbd>
<kbd>↵</kbd>
</span>
<span className={styles.editButtons}>
<IconButton icon="close" title="Cancel" disabled={sending} onClick={onCancel} />
<SubmitButton
label="Send"
pending={sending}
disabled={(!text.trim() && images.length === 0) || sending}
onClick={() => void send()}
/>
</span>
</div>
</div>
{error && (
<div className={styles.error} role="alert">
<div className={clsx(styles.error, styles.editError)} role="alert">
<Icon name="error" size={14} />
<span>
<T>Couldn't send the message</T>: {error}
</span>
</div>
)}
<div className={styles.editBar}>
<span className={styles.muted}>
{later ? (
<T>
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.
</T>
) : (
<T>The files the agent changed since go back to how they were before this message was sent.</T>
)}
</span>
<span className={styles.editButtons}>
<IconButton icon="close" title="Cancel" disabled={sending} onClick={onCancel} />
<SubmitButton
label="Send"
pending={sending}
disabled={(!text.trim() && images.length === 0) || sending}
onClick={() => void send()}
/>
</span>
<div className={styles.editNote}>
{later ? (
<T>
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.
</T>
) : (
<T>The files the agent changed since go back to how they were before this message was sent.</T>
)}
</div>
</div>
</>
);
}