fix(agents): wait for attention before marking a chat unread (#7517)

Streamed reply entries no longer mark a background chat unread while the agent is still working. Task updates and attention events mark it unread when the turn finishes, needs input or fails.
Цей коміт міститься в:
l0ng-ai authored and GitHub committed 2026-12-02 19:33:11 +08:00
1 джерело 5b24b61b49
коміт 29d1a52d91
2 files changed
+29 -49

No files matched your search

+3 -24
Переглянути файл
@@ -645,8 +645,6 @@ type EntryEvent = Extract<AgentEvent, { type: "entry" | "append" | "toolOutput"
/** Entry events that arrived while their conversation loaded, applied on top of the copy it loads. */
const arrivedWhileLoading = new Map<string, EntryEvent[]>();
/** Whether the message each task streams now is the agent's reply, known without its conversation. */
const streamingReply = new Map<string, { index: number; reply: boolean }>();
/** `entries` with the event applied; `null` when the copy can't take it. */
function applyEntryEvent(entries: AgentEntry[], e: EntryEvent): AgentEntry[] | null {
@@ -691,7 +689,7 @@ function forgetClosed(taskId: string) {
if (idx >= 0) closedTaskMru.splice(idx, 1);
}
function clearTaskMaps(taskId: string, clearStreaming = false) {
function clearTaskMaps(taskId: string) {
forgetClosed(taskId);
for (const key of [...arrivedWhileLoading.keys()]) {
if (isTaskKey(key, taskId)) arrivedWhileLoading.delete(key);
@@ -701,7 +699,6 @@ function clearTaskMaps(taskId: string, clearStreaming = false) {
for (const key of [...positions.keys()]) {
if (isTaskKey(key, taskId)) positions.delete(key);
}
if (clearStreaming) streamingReply.delete(taskId);
cancelScheduledChanges(taskId);
const last = changeRefreshes.get(taskId);
if (last) last.cache.dropped = true;
@@ -793,7 +790,6 @@ export function releaseClosedTaskCache(taskId: string) {
export function disconnect() {
generation++;
arrivedWhileLoading.clear();
streamingReply.clear();
modelFlights.clear();
closedTaskMru.length = 0;
clearChangeRefreshes();
@@ -864,7 +860,7 @@ function onEvent(e: AgentEvent) {
break;
}
case "removed": {
clearTaskMaps(e.id, true);
clearTaskMaps(e.id);
const tasks = new Map(s.tasks);
tasks.delete(e.id);
const composers = new Map(s.composers);
@@ -914,30 +910,13 @@ function onEvent(e: AgentEvent) {
break;
}
case "entry": {
if (
!e.subagent &&
((e.entry.type === "agent" && e.entry.text.trim()) ||
e.entry.type === "error" ||
(e.entry.type === "permission" && e.entry.chosen === null))
) {
markUnread(e.task);
}
if (!e.subagent) streamingReply.set(e.task, { index: e.index, reply: e.entry.type === "agent" });
onEntryEvent(s, e);
if (e.entry.type === "tool" && e.entry.status === "completed" && e.entry.diffs.length) {
scheduleChanges(e.task);
}
break;
}
case "append": {
if (!e.subagent && e.text.trim()) {
const shown = s.entries.get(entriesKey(e.task, null))?.[e.index];
const streaming = streamingReply.get(e.task);
if (shown ? shown.type === "agent" : streaming?.index === e.index && streaming.reply) markUnread(e.task);
}
onEntryEvent(s, e);
break;
}
case "append":
case "toolOutput": {
onEntryEvent(s, e);
break;
+26 -25
Переглянути файл
@@ -103,6 +103,10 @@ const task = (id: string, status: AgentTask["status"] = "running"): AgentTask =>
const emit = (event: AgentEvent) => act(() => backend.channel!.onmessage(event));
const reply = (id = "one", text = "New reply") =>
emit({ type: "entry", task: id, subagent: null, index: 0, entry: { type: "agent", text } });
const finished = (id = "one") => {
emit({ type: "task", task: { ...task(id, "ready"), unread: true } });
emit({ type: "attention", task: id, eventId: `${id}:finished:1`, reason: "finished" });
};
const visible: Array<() => void> = [];
const show = (id = "one") => {
let hide!: () => void;
@@ -194,22 +198,18 @@ describe("in-flight change reads", () => {
});
describe("agent unread activity", () => {
it("does not mark historical tasks unread, but tracks replies even without loaded entries", () => {
it.each([false, true])("waits for completion before marking a streaming reply unread (cached: %s)", (cached) => {
if (cached) useAgents.setState({ entries: new Map([["one", []]]) });
reply("one", "Working");
emit({ type: "append", task: "one", subagent: null, index: 0, from: 7, text: " on it" });
if (cached) expect(useAgents.getState().entries.get("one")).toEqual([{ type: "agent", text: "Working on it" }]);
else expect(useAgents.getState().entries.has("one")).toBe(false);
expect(useAgents.getState().unread.size).toBe(0);
reply();
reply("one", "New reply, streamed further");
reply("two");
expect([...useAgents.getState().unread]).toEqual(["one", "two"]);
expect(useAgents.getState().entries.size).toBe(0);
expect(backend.notify).not.toHaveBeenCalled();
});
it("tracks a reply that streams on as appends, but not a thought", () => {
reply("one", "");
emit({ type: "append", task: "one", subagent: null, index: 0, from: 0, text: "Done" });
emit({ type: "entry", task: "two", subagent: null, index: 0, entry: { type: "thought", text: "" } });
emit({ type: "append", task: "two", subagent: null, index: 0, from: 0, text: "Hmm" });
finished();
expect([...useAgents.getState().unread]).toEqual(["one"]);
expect(backend.notify).toHaveBeenCalledTimes(1);
});
it.each([
@@ -244,11 +244,13 @@ describe("agent unread activity", () => {
expect(useAgents.getState().unread.size).toBe(0);
});
it("ignores user messages, thoughts, empty replies and subagent streaming", () => {
it("keeps transcript entries and subagent activity from raising unread on their own", () => {
const entries: AgentEntry[] = [
{ type: "user", text: "Do this", attachments: [] },
{ type: "thought", text: "Thinking" },
{ type: "agent", text: " " },
{ type: "permission", id: 1, title: "Run command", options: [], chosen: null },
{ type: "error", message: "Retrying" },
];
for (const entry of entries) emit({ type: "entry", task: "one", subagent: null, index: 0, entry });
emit({ type: "entry", task: "one", subagent: "child", index: 0, entry: { type: "agent", text: "Working" } });
@@ -257,47 +259,46 @@ describe("agent unread activity", () => {
});
it("clears only the viewed task and keeps reading while either split shows it", () => {
reply();
reply("two");
finished();
finished("two");
const hide = show();
show();
hide();
reply();
emit({ type: "task", task: task("one", "ready") });
finished();
expect([...useAgents.getState().unread]).toEqual(["two"]);
expect(backend.notify).not.toHaveBeenCalled();
expect(backend.notify).toHaveBeenCalledTimes(2);
});
it("keeps a visible session unread while the window is unfocused, then clears on focus", () => {
vi.mocked(document.hasFocus).mockReturnValue(false);
reply();
finished();
show();
expect(useAgents.getState().unread.has("one")).toBe(true);
vi.mocked(document.hasFocus).mockReturnValue(true);
fireEvent(window, new Event("focus"));
expect(useAgents.getState().unread.size).toBe(0);
reply();
finished();
expect(useAgents.getState().unread.size).toBe(0);
});
it("does not read hidden windows and removes focus listeners when the session closes", () => {
vi.spyOn(document, "visibilityState", "get").mockReturnValue("hidden");
const hide = show();
reply();
finished();
fireEvent(window, new Event("focus"));
expect(useAgents.getState().unread.has("one")).toBe(true);
vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
fireEvent(document, new Event("visibilitychange"));
expect(useAgents.getState().unread.size).toBe(0);
hide();
reply();
finished();
fireEvent(window, new Event("focus"));
expect(useAgents.getState().unread.has("one")).toBe(true);
});
it("cleans up archived and deleted tasks, ignores late replies, and resets on project switch", async () => {
reply();
reply("two");
finished();
finished("two");
emit({ type: "task", task: task("one", "archived") });
reply();
expect([...useAgents.getState().unread]).toEqual(["two"]);
@@ -305,7 +306,7 @@ describe("agent unread activity", () => {
reply("two");
expect(useAgents.getState().unread.size).toBe(0);
emit({ type: "task", task: task("one") });
reply();
finished();
const oldChannel = backend.channel!;
disconnect();
backend.tasks = [task("other")];