fix(webui): remove subtask polling and load error UI (#6212)

* fix(webui): stop subtask reads when gateway disconnects

* refactor(webui): limit subtask change to polling removal

* fix(webui): hide subtask load errors after disconnect

* fix(webui): remove subtask load error UI

* refactor(webui): keep subtask refresh fix focused
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-14 18:02:03 +08:00
1 parent 3881ed7dd1
commit a482281092
12 files changed
+30 -44

No files matched your search

+9 -20
View File
@@ -32,7 +32,6 @@ function isActive(task: SubagentTaskSnapshot): boolean {
interface TaskContext { interface TaskContext {
tasks: ObservedSubagentTask[]; tasks: ObservedSubagentTask[];
loadError: string | null;
stopError: string | null; stopError: string | null;
stoppingId: string | null; stoppingId: string | null;
open: (task: SubagentTaskSnapshot, trigger: HTMLButtonElement) => void; open: (task: SubagentTaskSnapshot, trigger: HTMLButtonElement) => void;
@@ -59,7 +58,6 @@ export function SubagentTasksProvider({ client, sessionKey, token, enabled, live
const [tasks, setTasks] = useState<ObservedSubagentTask[]>([]); const [tasks, setTasks] = useState<ObservedSubagentTask[]>([]);
const [selectedId, setSelectedId] = useState<string | null>(null); const [selectedId, setSelectedId] = useState<string | null>(null);
const [stoppingId, setStoppingId] = useState<string | null>(null); const [stoppingId, setStoppingId] = useState<string | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [stopError, setStopError] = useState<string | null>(null); const [stopError, setStopError] = useState<string | null>(null);
const scopeGeneration = useRef(0); const scopeGeneration = useRef(0);
const mounted = useRef(true); const mounted = useRef(true);
@@ -72,7 +70,6 @@ export function SubagentTasksProvider({ client, sessionKey, token, enabled, live
setTasks([]); setTasks([]);
setSelectedId(null); setSelectedId(null);
setStoppingId(null); setStoppingId(null);
setLoadError(null);
setStopError(null); setStopError(null);
return () => { scopeGeneration.current += 1; }; return () => { scopeGeneration.current += 1; };
}, [client, sessionKey]); }, [client, sessionKey]);
@@ -98,10 +95,9 @@ export function SubagentTasksProvider({ client, sessionKey, token, enabled, live
const payload = await fetchSubagentTasks(token, sessionKey); const payload = await fetchSubagentTasks(token, sessionKey);
if (!cancelled) { if (!cancelled) {
setTasks((current) => mergeSubagentTasks(current, payload.tasks)); setTasks((current) => mergeSubagentTasks(current, payload.tasks));
setLoadError(null);
} }
} catch { } catch {
if (!cancelled) setLoadError(t("thread.subagents.loadFailed")); // Background read failures retain the last task snapshot.
} finally { } finally {
refreshing = false; refreshing = false;
if (refreshPending && !cancelled) { if (refreshPending && !cancelled) {
@@ -112,28 +108,22 @@ export function SubagentTasksProvider({ client, sessionKey, token, enabled, live
}; };
const unsubscribeChat = liveEvents ? client.onChat(sessionKey.slice("websocket:".length), (event) => { const unsubscribeChat = liveEvents ? client.onChat(sessionKey.slice("websocket:".length), (event) => {
if (cancelled || event.event !== "subagent_task") return; if (cancelled || event.event !== "subagent_task") return;
if (!isSubagentTask(event.task)) { if (!isSubagentTask(event.task)) return;
setLoadError(t("thread.subagents.loadFailed"));
return;
}
setTasks((current) => mergeSubagentTasks(current, [event.task])); setTasks((current) => mergeSubagentTasks(current, [event.task]));
}) : undefined; }) : undefined;
const unsubscribeStatus = liveEvents ? client.onStatus((status) => { const unsubscribeStatus = liveEvents ? client.onStatus((status) => {
if (status === "open") void refresh(); if (status === "open") void refresh();
}) : undefined; }) : undefined;
if (!refreshing) void refresh(); if (!refreshing) void refresh();
// Protocol 1 hosts may support task reads without the optional event stream.
const timer = liveEvents ? undefined : window.setInterval(() => void refresh(), 3000);
const focus = () => void refresh(); const focus = () => void refresh();
window.addEventListener("focus", focus); window.addEventListener("focus", focus);
return () => { return () => {
cancelled = true; cancelled = true;
window.clearInterval(timer);
unsubscribeChat?.(); unsubscribeChat?.();
unsubscribeStatus?.(); unsubscribeStatus?.();
window.removeEventListener("focus", focus); window.removeEventListener("focus", focus);
}; };
}, [client, enabled, liveEvents, active, sessionKey, token, pageVisible, paneVisible, t]); }, [client, enabled, liveEvents, active, sessionKey, token, pageVisible, paneVisible]);
const stop = async (task: SubagentTaskSnapshot) => { const stop = async (task: SubagentTaskSnapshot) => {
if (!sessionKey) return; if (!sessionKey) return;
@@ -152,7 +142,7 @@ export function SubagentTasksProvider({ client, sessionKey, token, enabled, live
}; };
const selected = enabled && active && paneVisible ? tasks.find((task) => task.task_id === selectedId) : undefined; const selected = enabled && active && paneVisible ? tasks.find((task) => task.task_id === selectedId) : undefined;
const value: TaskContext = { const value: TaskContext = {
tasks: enabled ? tasks : [], loadError: enabled ? loadError : null, tasks: enabled ? tasks : [],
stopError: enabled ? stopError : null, stoppingId, stopError: enabled ? stopError : null, stoppingId,
open: (task, target) => { trigger.current = target; setSelectedId(task.task_id); }, stop, open: (task, target) => { trigger.current = target; setSelectedId(task.task_id); }, stop,
register: (id, button, previous) => { register: (id, button, previous) => {
@@ -261,7 +251,7 @@ function TaskButton({ task }: { task: ObservedSubagentTask }) {
export function useHasSubagentContent(): boolean { export function useHasSubagentContent(): boolean {
const context = useContext(TasksContext); const context = useContext(TasksContext);
return !!context && (context.tasks.length > 0 || !!context.loadError || !!context.stopError); return !!context && (context.tasks.length > 0 || !!context.stopError);
} }
/** Prefer an exact prompt, then its turn's first prompt when replay changed message IDs. */ /** Prefer an exact prompt, then its turn's first prompt when replay changed message IDs. */
@@ -287,7 +277,7 @@ export function SubagentThreadMessages(props: ComponentProps<typeof ThreadMessag
return <ThreadMessages {...props} return <ThreadMessages {...props}
beforeMessages={<SubagentWork tasks={groups.unlinked} unlinked />} beforeMessages={<SubagentWork tasks={groups.unlinked} unlinked />}
afterUserMessage={(message) => <SubagentWork tasks={groups.byMessage.get(message.id) ?? []} />} afterUserMessage={(message) => <SubagentWork tasks={groups.byMessage.get(message.id) ?? []} />}
afterMessages={<SubagentTaskErrors />} />; afterMessages={<SubagentStopError />} />;
} }
function SubagentWork({ tasks, unlinked = false }: { tasks: ObservedSubagentTask[]; unlinked?: boolean }) { function SubagentWork({ tasks, unlinked = false }: { tasks: ObservedSubagentTask[]; unlinked?: boolean }) {
@@ -333,11 +323,10 @@ function SubagentWork({ tasks, unlinked = false }: { tasks: ObservedSubagentTask
</section>; </section>;
} }
function SubagentTaskErrors() { function SubagentStopError() {
const context = useContext(TasksContext); const context = useContext(TasksContext);
if (!context?.loadError && !context?.stopError) return null; if (!context?.stopError) return null;
return <div className="thread-message-row mt-2 space-y-1 text-xs text-destructive"> return <div className="thread-message-row mt-2 space-y-1 text-xs text-destructive">
{context.loadError ? <p role="alert">{context.loadError}</p> : null} <p role="alert">{context.stopError}</p>
{context.stopError ? <p role="alert">{context.stopError}</p> : null}
</div>; </div>;
} }
-1
View File
@@ -1819,7 +1819,6 @@
}, },
"thread": { "thread": {
"subagents": { "subagents": {
"loadFailed": "Could not load subtasks.",
"stopFailed": "Could not stop this task.", "stopFailed": "Could not stop this task.",
"stopTask": "Stop {{label}}", "stopTask": "Stop {{label}}",
"receiptHelp": "Delivered means the message was included in the subtask’s next model request. It does not mean the instructions have been carried out.", "receiptHelp": "Delivered means the message was included in the subtask’s next model request. It does not mean the instructions have been carried out.",
-1
View File
@@ -1620,7 +1620,6 @@
}, },
"thread": { "thread": {
"subagents": { "subagents": {
"loadFailed": "No se pudieron cargar las subtareas.",
"stopFailed": "No se pudo detener esta tarea.", "stopFailed": "No se pudo detener esta tarea.",
"stopTask": "Detener {{label}}", "stopTask": "Detener {{label}}",
"receiptHelp": "Entregado significa que el mensaje se incluyó en la siguiente solicitud del subagente, sin confirmar su ejecución.", "receiptHelp": "Entregado significa que el mensaje se incluyó en la siguiente solicitud del subagente, sin confirmar su ejecución.",
-1
View File
@@ -1619,7 +1619,6 @@
}, },
"thread": { "thread": {
"subagents": { "subagents": {
"loadFailed": "Impossible de charger les sous-tâches.",
"stopFailed": "Impossible d’arrêter cette tâche.", "stopFailed": "Impossible d’arrêter cette tâche.",
"stopTask": "Arrêter {{label}}", "stopTask": "Arrêter {{label}}",
"receiptHelp": "Livré signifie que le message a été inclus dans la prochaine requête du sous-agent, sans confirmer son exécution.", "receiptHelp": "Livré signifie que le message a été inclus dans la prochaine requête du sous-agent, sans confirmer son exécution.",
-1
View File
@@ -1619,7 +1619,6 @@
}, },
"thread": { "thread": {
"subagents": { "subagents": {
"loadFailed": "Tidak dapat memuat subtugas.",
"stopFailed": "Tidak dapat menghentikan tugas ini.", "stopFailed": "Tidak dapat menghentikan tugas ini.",
"stopTask": "Hentikan {{label}}", "stopTask": "Hentikan {{label}}",
"receiptHelp": "Terkirim berarti pesan disertakan dalam permintaan model berikutnya dari subagen, bukan konfirmasi bahwa pekerjaan selesai.", "receiptHelp": "Terkirim berarti pesan disertakan dalam permintaan model berikutnya dari subagen, bukan konfirmasi bahwa pekerjaan selesai.",
-1
View File
@@ -1619,7 +1619,6 @@
}, },
"thread": { "thread": {
"subagents": { "subagents": {
"loadFailed": "サブタスクを読み込めませんでした。",
"stopFailed": "このタスクを停止できませんでした。", "stopFailed": "このタスクを停止できませんでした。",
"stopTask": "{{label}} を停止", "stopTask": "{{label}} を停止",
"receiptHelp": "配信済みは子タスクの次のモデルリクエストにメッセージが含まれたことを示し、実行完了を意味しません。", "receiptHelp": "配信済みは子タスクの次のモデルリクエストにメッセージが含まれたことを示し、実行完了を意味しません。",
-1
View File
@@ -1619,7 +1619,6 @@
}, },
"thread": { "thread": {
"subagents": { "subagents": {
"loadFailed": "하위 작업을 불러올 수 없습니다.",
"stopFailed": "이 작업을 중지할 수 없습니다.", "stopFailed": "이 작업을 중지할 수 없습니다.",
"stopTask": "{{label}} 중지", "stopTask": "{{label}} 중지",
"receiptHelp": "전달됨은 메시지가 하위 작업의 다음 모델 요청에 포함되었음을 뜻하며, 실행 완료를 의미하지 않습니다.", "receiptHelp": "전달됨은 메시지가 하위 작업의 다음 모델 요청에 포함되었음을 뜻하며, 실행 완료를 의미하지 않습니다.",
-1
View File
@@ -1633,7 +1633,6 @@
}, },
"thread": { "thread": {
"subagents": { "subagents": {
"loadFailed": "Não foi possível carregar as subtarefas.",
"stopFailed": "Não foi possível interromper esta tarefa.", "stopFailed": "Não foi possível interromper esta tarefa.",
"stopTask": "Interromper {{label}}", "stopTask": "Interromper {{label}}",
"receiptHelp": "Entregue significa que a mensagem foi incluída na próxima solicitação do subagente, sem confirmar sua execução.", "receiptHelp": "Entregue significa que a mensagem foi incluída na próxima solicitação do subagente, sem confirmar sua execução.",
-1
View File
@@ -1619,7 +1619,6 @@
}, },
"thread": { "thread": {
"subagents": { "subagents": {
"loadFailed": "Không thể tải tác vụ con.",
"stopFailed": "Không thể dừng tác vụ này.", "stopFailed": "Không thể dừng tác vụ này.",
"stopTask": "Dừng {{label}}", "stopTask": "Dừng {{label}}",
"receiptHelp": "Đã chuyển nghĩa là tin nhắn đã được đưa vào yêu cầu mô hình tiếp theo của tác nhân con, không xác nhận công việc đã hoàn tất.", "receiptHelp": "Đã chuyển nghĩa là tin nhắn đã được đưa vào yêu cầu mô hình tiếp theo của tác nhân con, không xác nhận công việc đã hoàn tất.",
-1
View File
@@ -1819,7 +1819,6 @@
}, },
"thread": { "thread": {
"subagents": { "subagents": {
"loadFailed": "无法加载子任务。",
"stopFailed": "无法停止此任务。", "stopFailed": "无法停止此任务。",
"stopTask": "停止 {{label}}", "stopTask": "停止 {{label}}",
"receiptHelp": "已送达表示消息已进入子任务的下一次模型请求,不代表已执行完成。", "receiptHelp": "已送达表示消息已进入子任务的下一次模型请求,不代表已执行完成。",
-1
View File
@@ -1619,7 +1619,6 @@
}, },
"thread": { "thread": {
"subagents": { "subagents": {
"loadFailed": "無法載入子任務。",
"stopFailed": "無法停止此任務。", "stopFailed": "無法停止此任務。",
"stopTask": "停止 {{label}}", "stopTask": "停止 {{label}}",
"receiptHelp": "已送達表示訊息已進入子任務的下一次模型請求,不代表已執行完成。", "receiptHelp": "已送達表示訊息已進入子任務的下一次模型請求,不代表已執行完成。",
+21 -14
View File
@@ -272,7 +272,7 @@ describe("session-owned task UI", () => {
expect(statusHandlers.size).toBe(0); expect(statusHandlers.size).toBe(0);
}); });
it("keeps load failures visible and keeps stop failures across a successful refresh", async () => { it("preserves loaded tasks and stop errors across background snapshot failures", async () => {
const user = userEvent.setup(); const user = userEvent.setup();
requestMutation.mockRejectedValue(new Error("Cannot stop task")); requestMutation.mockRejectedValue(new Error("Cannot stop task"));
render(layout()); render(layout());
@@ -282,23 +282,26 @@ describe("session-owned task UI", () => {
await waitFor(() => expect(fetch).toHaveBeenCalledTimes(2)); await waitFor(() => expect(fetch).toHaveBeenCalledTimes(2));
expect(screen.getByText("Cannot stop task")).toBeVisible(); expect(screen.getByText("Cannot stop task")).toBeVisible();
vi.mocked(fetch).mockRejectedValue(new Error("offline")); vi.mocked(fetch).mockRejectedValue(new Error("offline"));
fireEvent(window, new Event("focus")); await act(async () => { fireEvent(window, new Event("focus")); });
await screen.findByText("Could not load subtasks.");
expect(screen.getByRole("button", { name: /Config check Running/ })).toBeVisible(); expect(screen.getByRole("button", { name: /Config check Running/ })).toBeVisible();
expect(screen.getByText("Cannot stop task")).toBeVisible();
}); });
it("shows a read error for malformed or duplicate task records", async () => { it("retains the last valid snapshot after malformed reads and recovers on refresh", async () => {
render(layout());
await screen.findByRole("button", { name: /Config check Running/ });
vi.mocked(fetch).mockImplementation(async () => new Response(JSON.stringify({ vi.mocked(fetch).mockImplementation(async () => new Response(JSON.stringify({
tasks: [{ ...task(), label: { unexpected: true } }], tasks: [{ ...task(), label: { unexpected: true } }],
}), { headers: { "content-type": "application/json" } })); }), { headers: { "content-type": "application/json" } }));
render(layout()); await act(async () => { fireEvent(window, new Event("focus")); });
await screen.findByText("Could not load subtasks."); expect(screen.getByRole("button", { name: /Config check Running/ })).toBeVisible();
expect(screen.queryByText("Config check")).not.toBeInTheDocument(); expect(screen.queryByRole("alert")).not.toBeInTheDocument();
vi.mocked(fetch).mockImplementation(async () => response([task(), task()])); vi.mocked(fetch).mockImplementation(async () => response([task(), task()]));
fireEvent(window, new Event("focus")); await act(async () => { fireEvent(window, new Event("focus")); });
await waitFor(() => expect(fetch).toHaveBeenCalledTimes(2)); expect(screen.getByRole("button", { name: /Config check Running/ })).toBeVisible();
expect(screen.getByText("Could not load subtasks.")).toBeVisible(); vi.mocked(fetch).mockResolvedValue(response([task({ revision: 2, state: "done", completed_at: 102 })]));
expect(screen.queryByText("Config check")).not.toBeInTheDocument(); await act(async () => { fireEvent(window, new Event("focus")); });
expect(screen.getByRole("button", { name: /Subtasks Finished: 1/ })).toBeVisible();
}); });
it("discards reads from the previous session after switching", async () => { it("discards reads from the previous session after switching", async () => {
@@ -464,17 +467,21 @@ describe("session-owned task UI", () => {
expect(screen.getByRole("button", { name: /Config check Cancelled/ })).toBeVisible(); expect(screen.getByRole("button", { name: /Config check Cancelled/ })).toBeVisible();
expect(fetch).toHaveBeenCalledTimes(3); expect(fetch).toHaveBeenCalledTimes(3);
emitTask({ ...task(), revision: -1 }); emitTask({ ...task(), revision: -1 });
expect(screen.getByText("Could not load subtasks.")).toBeVisible(); expect(screen.getByRole("button", { name: /Config check Cancelled/ })).toBeVisible();
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
}); });
it("keeps protocol 1 task controls usable on a host without event support", async () => { it("reads snapshots without polling on a host without task events", async () => {
vi.mocked(fetch).mockImplementation(async () => response([task({ revision: undefined })])); vi.mocked(fetch).mockImplementation(async () => response([task({ revision: undefined })]));
vi.useFakeTimers(); vi.useFakeTimers();
const view = render(layout({ liveEvents: false })); const view = render(layout({ liveEvents: false }));
await act(async () => { await Promise.resolve(); }); await act(async () => { await Promise.resolve(); });
expect(screen.getByRole("button", { name: /Config check Running/ })).toBeVisible(); expect(screen.getByRole("button", { name: /Config check Running/ })).toBeVisible();
vi.mocked(fetch).mockImplementation(async () => response([task({ revision: undefined, state: "done", completed_at: 102 })])); vi.mocked(fetch).mockImplementation(async () => response([task({ revision: undefined, state: "done", completed_at: 102 })]));
await act(async () => { await vi.advanceTimersByTimeAsync(3000); }); await act(async () => { await vi.advanceTimersByTimeAsync(9000); });
expect(fetch).toHaveBeenCalledTimes(1);
expect(screen.getByRole("button", { name: /Config check Running/ })).toBeVisible();
await act(async () => { fireEvent(window, new Event("focus")); });
expect(screen.getByRole("button", { name: /Subtasks Finished: 1/ })).toBeVisible(); expect(screen.getByRole("button", { name: /Subtasks Finished: 1/ })).toBeVisible();
expect(client.onChat).not.toHaveBeenCalled(); expect(client.onChat).not.toHaveBeenCalled();
view.rerender(layout({ liveEvents: false, visible: false })); view.rerender(layout({ liveEvents: false, visible: false }));