fix(webui): keep automation review stable and share complete task details

This commit is contained in:
Xubin Ren committed 2026-10-07 01:12:23 +08:00
1 parent 845afe9215
commit c932720b20
8 files changed
+107 -23

No files matched your search

+3
View File
@@ -74,6 +74,7 @@ def session_automations_payload(
session_key: str,
*,
local_trigger_store: _LocalTriggerStoreLike | None = None,
session_manager: _SessionManagerLike | None = None,
pending_job_ids: Collection[str] | None = None,
) -> dict[str, Any]:
"""Return user-created automation jobs attached to a WebUI session."""
@@ -85,6 +86,8 @@ def session_automations_payload(
local_trigger_store=local_trigger_store,
),
pending_job_ids=pending_job_ids,
include_details=True,
session_manager=session_manager,
)
}
+1
View File
@@ -1305,6 +1305,7 @@ class GatewayHTTPHandler:
self.cron_service,
decoded_key,
local_trigger_store=self.local_trigger_store,
session_manager=self.session_manager,
pending_job_ids=pending_job_ids,
)
)
+13 -1
View File
@@ -14,6 +14,7 @@ import websockets
from nanobot.agent.loop import AgentLoop
from nanobot.bus.queue import MessageBus
from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig
from nanobot.config.schema import Config
from nanobot.cron.binding import CronBinding, binding_revision
from nanobot.cron.bound_runner import run_bound_cron_job
from nanobot.cron.service import CronService
@@ -198,7 +199,7 @@ async def test_real_gateway_move_run_reload_and_previous_result(tmp_path):
provider.chat_stream_with_retry = reply
bus = MessageBus()
agent = AgentLoop(bus=bus, provider=provider, workspace=tmp_path / "workspace",
model="test-model", session_manager=sessions)
model="test-model", session_manager=sessions, tools_config=Config().tools)
agent.tools.get_definitions = MagicMock(return_value=[])
async def execute(job):
return await run_bound_cron_job(job, agent=agent, cron=cron)
@@ -230,6 +231,17 @@ async def test_real_gateway_move_run_reload_and_previous_result(tmp_path):
assert json.loads(await client.recv())["event"] == "ready"
api_token = gateway.tokens.issue_api_token(60)
async with httpx.AsyncClient(trust_env=False) as http:
session_jobs = await http.get(
f"http://127.0.0.1:{port}/api/sessions/websocket%3Asource/automations",
headers={"Authorization": f"Bearer {api_token}"},
)
assert session_jobs.status_code == 200
detail = session_jobs.json()["jobs"][0]
assert detail["origin"]["session_key"] == "websocket:source"
assert detail["origin"]["title"] == "Daily report"
assert detail["protected"] is False
assert detail["chat_binding_revision"] == binding_revision(old)
assert detail["state"]["run_history"][0]["status"] == "ok"
url = f"http://127.0.0.1:{port}/api/webui/automations/chats?id={job.id}"
assert (await http.get(url)).status_code == 401
result = await http.get(url, headers={"Authorization": f"Bearer {api_token}"})
@@ -46,6 +46,13 @@ No new execution path, agent-loop policy, dependencies, or separate CSS system
are added. The dialog uses the existing Select, Dialog, Button, Textarea, channel
logos, and DropdownMenu. The detail dialog owns the modal lock. Confirmation is
explicit and progress stays local to that action. The page remains visible.
The review keeps the selected chat and original chat name stable across refreshes.
If refreshed choices omit the selected chat, its name remains visible and saving
is disabled. The gateway still checks the route at save time.
The session details endpoint uses the same complete task serializer as the
Automations page. Both shared-dialog entry points receive the binding needed to
enable Run now and resume; neither client invents a missing route.
## Compatibility
@@ -43,7 +43,7 @@ export function AutomationChatBinding({ job, token, onSave, children }: {
const [data, setData] = useState<AutomationChatsPayload | null>(null);
const [loadError, setLoadError] = useState(false);
const [reload, setReload] = useState(0);
const [draft, setDraft] = useState<{ target: string; revision: string; message: string } | null>(null);
const [draft, setDraft] = useState<{ target: AutomationChat; previousTitle: string; revision: string; message: string } | null>(null);
const [saving, setSaving] = useState(false);
const [error, setError] = useState("");
const [saved, setSaved] = useState(false);
@@ -59,25 +59,33 @@ export function AutomationChatBinding({ job, token, onSave, children }: {
return () => controller.abort();
}, [token, job.id, job.chat_binding_revision, reload]);
const reviewing = draft !== null;
const locked = saving || Boolean(job.state.pending);
const pickerDisabled = locked || !data?.chats.length || loadError || (!reviewing && data.revision !== job.chat_binding_revision);
useEffect(() => {
if (reviewing) heading.current?.focus();
else if (returning.current) { trigger.current?.focus(); returning.current = false; }
}, [reviewing]);
useEffect(() => {
if (!reviewing && !pickerDisabled && returning.current) {
trigger.current?.focus(); returning.current = false;
}
}, [reviewing, pickerDisabled]);
const back = () => { returning.current = true; setDraft(null); };
const current = data?.current;
const fallback: AutomationChat = { id: "current", title: job.origin?.title || tx("current"), channel: job.origin?.channel || "websocket" };
const locked = saving || Boolean(job.state.pending);
const picker = (review: boolean) => <Select value={review ? draft?.target : current?.id ?? "current"}
disabled={locked || !data?.chats.length || loadError || (!review && data.revision !== job.chat_binding_revision)} onValueChange={target => {
if (target === current?.id) return;
const targetUnavailable = Boolean(draft && data && !data.chats.some(chat => chat.id === draft.target.id && !chat.unavailable));
const picker = (review: boolean) => <Select value={review ? draft?.target.id : current?.id ?? "current"}
disabled={pickerDisabled} onValueChange={id => {
const target = data?.chats.find(chat => chat.id === id);
if (!target || target.unavailable || id === current?.id) return;
setError(""); setSaved(false);
setDraft(previous => previous ? { ...previous, target } : {
target, revision: job.chat_binding_revision!, message: job.payload.message,
target, previousTitle: current?.title || fallback.title,
revision: job.chat_binding_revision!, message: job.payload.message,
});
}}>
<SelectTrigger ref={review ? undefined : trigger} aria-label={tx(review ? "new" : "label")}
className={`h-auto min-h-11 w-full py-2 [&>span:first-child]:min-w-0 [&>span:first-child]:flex-1 [&>span:first-child]:text-start ${review ? "" : "border-transparent bg-transparent hover:bg-muted/50"}`}>
<SelectValue><ChatIdentity chat={data?.chats.find(chat => chat.id === (review ? draft?.target : current?.id)) ?? fallback} /></SelectValue>
<SelectValue><ChatIdentity chat={(review ? draft?.target : current) ?? fallback} /></SelectValue>
</SelectTrigger>
<SelectContent>
{!current ? <SelectItem value="current" disabled><ChatIdentity chat={fallback} /></SelectItem> : null}
@@ -87,11 +95,11 @@ export function AutomationChatBinding({ job, token, onSave, children }: {
</SelectContent>
</Select>;
const save = async () => {
if (!draft || locked || !draft.message.trim()) return;
if (!draft || locked || targetUnavailable || !draft.message.trim()) return;
setSaving(true); setError("");
try {
await onSave(job, { target_id: draft.target, revision: draft.revision, message: draft.message });
setData(previous => previous ? { ...previous, current: previous.chats.find(chat => chat.id === draft.target) ?? null } : previous);
await onSave(job, { target_id: draft.target.id, revision: draft.revision, message: draft.message });
setData(previous => previous ? { ...previous, current: draft.target } : previous);
setSaved(true); back(); setReload(value => value + 1);
} catch (cause) {
const reasons: Record<string, string> = {
@@ -119,7 +127,7 @@ export function AutomationChatBinding({ job, token, onSave, children }: {
<div className="min-h-0 space-y-4 overflow-y-auto overscroll-contain px-6">
<div className="space-y-2">
{picker(true)}
<p className="text-[12px] leading-5 text-muted-foreground">{tx("previous")} {current?.title || fallback.title}</p>
<p className="text-[12px] leading-5 text-muted-foreground">{tx("previous")} {draft.previousTitle}</p>
<p className="text-[13px] leading-5">{tx("effect")}</p>
</div>
<label className="block space-y-2"><span className="text-[13px] font-medium">{tx("message")}</span>
@@ -128,11 +136,11 @@ export function AutomationChatBinding({ job, token, onSave, children }: {
</label>
<p className="text-[12px] leading-5 text-muted-foreground">{tx("review")}</p>
<p className="text-[12px] leading-5 text-muted-foreground">{tx("history")}</p>
{error ? <p role="alert" className="text-[12px] leading-5 text-destructive">{error}</p> : null}
{error || targetUnavailable ? <p role="alert" className="text-[12px] leading-5 text-destructive">{error || tx("unavailable")}</p> : null}
</div>
<DialogFooter className="shrink-0 flex-row justify-end gap-2 px-6 pb-5 pt-3">
<Button variant="ghost" size="sm" disabled={saving} className="h-11 font-normal text-muted-foreground sm:h-9" onClick={back}>{t("settings.automations.cancel")}</Button>
<Button size="sm" className="h-11 sm:h-9" disabled={locked || !draft.message.trim()} aria-busy={saving} onClick={() => void save()}>{tx(saving ? "saving" : "confirm")}</Button>
<Button size="sm" className="h-11 sm:h-9" disabled={locked || targetUnavailable || !draft.message.trim()} aria-busy={saving} onClick={() => void save()}>{tx(saving ? "saving" : "confirm")}</Button>
</DialogFooter>
</>;
}
+11 -3
View File
@@ -1775,9 +1775,13 @@ describe("App layout", () => {
expect(within(screen.getByRole("dialog", { name: "Daily repo check" })).getByText("Check the repo status")).toBeVisible();
const detail = within(screen.getByRole("dialog", { name: "Daily repo check" }));
expect(detail.queryByText("Release prep")).not.toBeInTheDocument();
expect(detail.getByRole("link", { name: "Open a chat" })).toHaveAttribute(
const user = userEvent.setup();
await user.click(detail.getByRole("button", { name: "More actions" }));
expect(screen.getByRole("menuitem", { name: "Open a chat" })).toHaveAttribute(
"href", "#/chat/websocket%3Achat-a",
);
await user.keyboard("{Escape}");
expect(detail.getByRole("button", { name: "More actions" })).toHaveFocus();
fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));
expect(screen.getByText("WeChat quiz")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: /WeChat quiz/ }));
@@ -1829,7 +1833,9 @@ describe("App layout", () => {
const dialog = screen.getByRole("dialog", { name: "Drink water" });
expect(within(dialog).queryByText("推特大战场")).not.toBeInTheDocument();
expect(within(dialog).queryByText("Stored title")).not.toBeInTheDocument();
expect(within(dialog).getByRole("link", { name: "Open a chat" })).toHaveAttribute(
const user = userEvent.setup();
await user.click(within(dialog).getByRole("button", { name: "More actions" }));
expect(screen.getByRole("menuitem", { name: "Open a chat" })).toHaveAttribute(
"href", "#/chat/websocket%3Alinked-chat",
);
for (const title of ["新会话名称", ""]) {
@@ -1841,10 +1847,12 @@ describe("App layout", () => {
const expected = title || "Stored title";
expect(within(sidebar).getByText(expected)).toBeInTheDocument();
expect(within(dialog).queryByText(expected)).not.toBeInTheDocument();
expect(within(dialog).getByRole("link", { name: "Open a chat" })).toHaveAttribute(
expect(screen.getByRole("menuitem", { name: "Open a chat" })).toHaveAttribute(
"href", "#/chat/websocket%3Alinked-chat",
);
}
await user.keyboard("{Escape}");
expect(within(dialog).getByRole("button", { name: "More actions" })).toHaveFocus();
expect(requestMutationSpy).not.toHaveBeenCalled();
});
@@ -31,7 +31,7 @@ it("keeps the original route until acknowledgement and saves the reviewed prompt
let finish!: () => void;
const save = vi.fn(() => new Promise<void>(resolve => { finish = resolve; }));
const user = userEvent.setup();
render(<AutomationDetailDialog {...props} job={job} onChangeChat={save} />);
const { rerender } = render(<AutomationDetailDialog {...props} job={job} onChangeChat={save} />);
await choose();
expect(save).not.toHaveBeenCalled();
expect(screen.getByText(/Previous chat:/)).toHaveTextContent("My planning");
@@ -41,8 +41,17 @@ it("keeps the original route until acknowledgement and saves the reviewed prompt
expect(save).toHaveBeenCalledWith(job, { target_id: "target", revision: "rev-1", message: "New instructions" });
expect(screen.getByRole("button", { name: "Changing…" })).toBeDisabled();
expect(screen.queryByRole("status")).not.toBeInTheDocument();
await act(async () => finish());
let refresh!: (value: AutomationChatsPayload) => void;
vi.mocked(fetchAutomationChats).mockImplementation(() => new Promise(resolve => { refresh = resolve; }));
await act(async () => {
rerender(<AutomationDetailDialog {...props} job={{ ...job, chat_binding_revision: "rev-2" }} onChangeChat={save} />);
finish();
});
expect(await screen.findByRole("status")).toHaveTextContent("Applies to future runs");
expect(screen.getByRole("combobox", { name: "Task chat" })).toHaveTextContent("Product team");
expect(screen.getByRole("combobox", { name: "Task chat" })).toBeDisabled();
await act(async () => refresh({ ...choices, current: target, revision: "rev-2" }));
expect(screen.getByRole("combobox", { name: "Task chat" })).toHaveFocus();
expect(props.onAction).not.toHaveBeenCalled();
});
@@ -71,6 +80,26 @@ it("does not send the new request to an old host and locks a pending task", asyn
expect(save).not.toHaveBeenCalled();
});
it("keeps the reviewed chat identity when refreshed choices no longer contain it", async () => {
const user = userEvent.setup();
const save = vi.fn();
const { rerender } = render(<AutomationDetailDialog {...props} job={job} onChangeChat={save} />);
await choose();
await user.type(screen.getByRole("textbox", { name: "Task instructions" }), " Reviewed");
vi.mocked(fetchAutomationChats).mockResolvedValue({
revision: "rev-2", current: { ...source, title: "Renamed planning" }, chats: [source],
});
rerender(<AutomationDetailDialog {...props} job={{ ...job, chat_binding_revision: "rev-2" }} onChangeChat={save} />);
expect(await screen.findByRole("alert")).toHaveTextContent("no longer available");
expect(screen.getByRole("combobox", { name: "New chat" })).toHaveTextContent("Product team");
expect(screen.getByText(/Previous chat:/)).toHaveTextContent("My planning");
expect(screen.getByRole("textbox", { name: "Task instructions" })).toHaveValue("Summarize the work. Reviewed");
expect(screen.getByRole("button", { name: "Confirm change" })).toBeDisabled();
expect(save).not.toHaveBeenCalled();
await user.click(screen.getByRole("button", { name: "Cancel" }));
expect(screen.getByRole("combobox", { name: "Task chat" })).toHaveTextContent("Renamed planning");
});
it("keeps the current chat visible when discovery fails and permits a retry", async () => {
const user = userEvent.setup();
vi.mocked(fetchAutomationChats).mockRejectedValueOnce(new Error("offline"));
+19 -3
View File
@@ -87,7 +87,11 @@ describe("SessionInfoPopover", () => {
});
it("manages a session task through the shared detail dialog", async () => {
const pausedJob = { ...automationJob(), enabled: false };
const boundJob = { ...automationJob(), origin: {
session_key: "websocket:chat-1", channel: "websocket", chat_id: "chat-1",
} };
vi.mocked(fetch).mockResolvedValue(automationsResponse([boundJob]));
const pausedJob = { ...boundJob, enabled: false };
requestMutation.mockResolvedValue({ jobs: [pausedJob] });
const user = userEvent.setup();
@@ -103,14 +107,26 @@ describe("SessionInfoPopover", () => {
await user.click(screen.getByRole("button", { name: "Session details" }));
await user.click(await screen.findByRole("button", { name: /Morning check/ }));
const detail = screen.getByRole("dialog", { name: "Morning check" });
await user.click(within(detail).getByRole("button", { name: "Disable" }));
await user.click(within(detail).getByRole("button", { name: "More actions" }));
await user.click(screen.getByRole("menuitem", { name: "Disable" }));
expect(requestMutation).toHaveBeenCalledWith(
"automation.disable",
{ id: "job-1" },
20_000,
);
await waitFor(() => expect(within(detail).getByRole("button", { name: "Enable" })).toBeVisible());
await waitFor(() => expect(within(detail).getByRole("button", { name: "More actions" })).toBeEnabled());
await user.click(within(detail).getByRole("button", { name: "More actions" }));
expect(screen.getByRole("menuitem", { name: "Enable" })).toBeVisible();
requestMutation.mockResolvedValue({ jobs: [boundJob] });
await user.click(screen.getByRole("menuitem", { name: "Enable" }));
expect(requestMutation).toHaveBeenLastCalledWith(
"automation.enable", { id: "job-1" }, 20_000,
);
await user.click(within(detail).getByRole("button", { name: "More actions" }));
expect(screen.getByRole("menuitem", { name: "Disable" })).toBeVisible();
await user.keyboard("{Escape}");
expect(within(detail).getByRole("button", { name: "More actions" })).toHaveFocus();
});
it("returns from the shared editor to the same task detail", async () => {